ua_network_tcp.c 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  1. /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
  2. * See http://creativecommons.org/publicdomain/zero/1.0/ for more information.
  3. *
  4. * Copyright 2016-2017 (c) Fraunhofer IOSB (Author: Julius Pfrommer)
  5. * Copyright 2016-2017 (c) Stefan Profanter, fortiss GmbH
  6. * Copyright 2017 (c) frax2222
  7. * Copyright 2017 (c) Jose Cabral
  8. * Copyright 2017 (c) Thomas Stalder, Blue Time Concept SA
  9. */
  10. #define UA_INTERNAL
  11. #include "ua_network_tcp.h"
  12. #include "ua_log_stdout.h"
  13. #include "../deps/queue.h"
  14. #include "ua_util.h"
  15. #include <string.h> // memset
  16. #ifndef MSG_NOSIGNAL
  17. #define MSG_NOSIGNAL 0
  18. #endif
  19. /****************************/
  20. /* Generic Socket Functions */
  21. /****************************/
  22. static UA_StatusCode
  23. connection_getsendbuffer(UA_Connection *connection,
  24. size_t length, UA_ByteString *buf) {
  25. if(length > connection->config.sendBufferSize)
  26. return UA_STATUSCODE_BADCOMMUNICATIONERROR;
  27. return UA_ByteString_allocBuffer(buf, length);
  28. }
  29. static void
  30. connection_releasesendbuffer(UA_Connection *connection,
  31. UA_ByteString *buf) {
  32. UA_ByteString_deleteMembers(buf);
  33. }
  34. static void
  35. connection_releaserecvbuffer(UA_Connection *connection,
  36. UA_ByteString *buf) {
  37. UA_ByteString_deleteMembers(buf);
  38. }
  39. static UA_StatusCode
  40. connection_write(UA_Connection *connection, UA_ByteString *buf) {
  41. if(connection->state == UA_CONNECTION_CLOSED) {
  42. UA_ByteString_deleteMembers(buf);
  43. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  44. }
  45. /* Prevent OS signals when sending to a closed socket */
  46. int flags = 0;
  47. flags |= MSG_NOSIGNAL;
  48. /* Send the full buffer. This may require several calls to send */
  49. size_t nWritten = 0;
  50. do {
  51. ssize_t n = 0;
  52. do {
  53. size_t bytes_to_send = buf->length - nWritten;
  54. n = UA_send(connection->sockfd,
  55. (const char*)buf->data + nWritten,
  56. bytes_to_send, flags);
  57. if(n < 0 && UA_ERRNO != UA_INTERRUPTED && UA_ERRNO != UA_AGAIN) {
  58. connection->close(connection);
  59. UA_ByteString_deleteMembers(buf);
  60. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  61. }
  62. } while(n < 0);
  63. nWritten += (size_t)n;
  64. } while(nWritten < buf->length);
  65. /* Free the buffer */
  66. UA_ByteString_deleteMembers(buf);
  67. return UA_STATUSCODE_GOOD;
  68. }
  69. static UA_StatusCode
  70. connection_recv(UA_Connection *connection, UA_ByteString *response,
  71. UA_UInt32 timeout) {
  72. if(connection->state == UA_CONNECTION_CLOSED)
  73. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  74. /* Listen on the socket for the given timeout until a message arrives */
  75. if(timeout > 0) {
  76. fd_set fdset;
  77. FD_ZERO(&fdset);
  78. UA_fd_set(connection->sockfd, &fdset);
  79. UA_UInt32 timeout_usec = timeout * 1000;
  80. struct timeval tmptv = {(long int)(timeout_usec / 1000000),
  81. (long int)(timeout_usec % 1000000)};
  82. int resultsize = UA_select(connection->sockfd+1, &fdset, NULL,
  83. NULL, &tmptv);
  84. /* No result */
  85. if(resultsize == 0)
  86. return UA_STATUSCODE_GOODNONCRITICALTIMEOUT;
  87. if(resultsize == -1) {
  88. /* The call to select was interrupted manually. Act as if it timed
  89. * out */
  90. if(UA_ERRNO == EINTR)
  91. return UA_STATUSCODE_GOODNONCRITICALTIMEOUT;
  92. /* The error cannot be recovered. Close the connection. */
  93. connection->close(connection);
  94. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  95. }
  96. }
  97. response->data = (UA_Byte*)UA_malloc(connection->config.recvBufferSize);
  98. if(!response->data) {
  99. response->length = 0;
  100. return UA_STATUSCODE_BADOUTOFMEMORY; /* not enough memory retry */
  101. }
  102. size_t offset = connection->incompleteChunk.length;
  103. size_t remaining = connection->config.recvBufferSize - offset;
  104. /* Get the received packet(s) */
  105. ssize_t ret = UA_recv(connection->sockfd, (char*)&response->data[offset],
  106. remaining, 0);
  107. /* The remote side closed the connection */
  108. if(ret == 0) {
  109. UA_ByteString_deleteMembers(response);
  110. connection->close(connection);
  111. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  112. }
  113. /* Error case */
  114. if(ret < 0) {
  115. UA_ByteString_deleteMembers(response);
  116. if(UA_ERRNO == UA_INTERRUPTED || (timeout > 0) ?
  117. false : (UA_ERRNO == UA_EAGAIN || UA_ERRNO == UA_WOULDBLOCK))
  118. return UA_STATUSCODE_GOOD; /* statuscode_good but no data -> retry */
  119. connection->close(connection);
  120. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  121. }
  122. /* Preprend the last incompleteChunk into the buffer */
  123. memcpy(response->data, connection->incompleteChunk.data,
  124. connection->incompleteChunk.length);
  125. UA_ByteString_deleteMembers(&connection->incompleteChunk);
  126. /* Set the length of the received buffer */
  127. response->length = offset + (size_t)ret;
  128. return UA_STATUSCODE_GOOD;
  129. }
  130. /***************************/
  131. /* Server NetworkLayer TCP */
  132. /***************************/
  133. #define MAXBACKLOG 100
  134. #define NOHELLOTIMEOUT 120000 /* timeout in ms before close the connection
  135. * if server does not receive Hello Message */
  136. typedef struct ConnectionEntry {
  137. UA_Connection connection;
  138. LIST_ENTRY(ConnectionEntry) pointers;
  139. } ConnectionEntry;
  140. typedef struct {
  141. const UA_Logger *logger;
  142. UA_UInt16 port;
  143. UA_SOCKET serverSockets[FD_SETSIZE];
  144. UA_UInt16 serverSocketsSize;
  145. LIST_HEAD(, ConnectionEntry) connections;
  146. } ServerNetworkLayerTCP;
  147. static void
  148. ServerNetworkLayerTCP_freeConnection(UA_Connection *connection) {
  149. UA_Connection_deleteMembers(connection);
  150. UA_free(connection);
  151. }
  152. /* This performs only 'shutdown'. 'close' is called when the shutdown
  153. * socket is returned from select. */
  154. static void
  155. ServerNetworkLayerTCP_close(UA_Connection *connection) {
  156. if (connection->state == UA_CONNECTION_CLOSED)
  157. return;
  158. UA_shutdown((UA_SOCKET)connection->sockfd, 2);
  159. connection->state = UA_CONNECTION_CLOSED;
  160. }
  161. static UA_StatusCode
  162. ServerNetworkLayerTCP_add(UA_ServerNetworkLayer *nl, ServerNetworkLayerTCP *layer,
  163. UA_Int32 newsockfd, struct sockaddr_storage *remote) {
  164. /* Set nonblocking */
  165. UA_socket_set_nonblocking(newsockfd);//TODO: check return value
  166. /* Do not merge packets on the socket (disable Nagle's algorithm) */
  167. int dummy = 1;
  168. if(UA_setsockopt(newsockfd, IPPROTO_TCP, TCP_NODELAY,
  169. (const char *)&dummy, sizeof(dummy)) < 0) {
  170. UA_LOG_SOCKET_ERRNO_WRAP(
  171. UA_LOG_ERROR(layer->logger, UA_LOGCATEGORY_NETWORK,
  172. "Cannot set socket option TCP_NODELAY. Error: %s",
  173. errno_str));
  174. return UA_STATUSCODE_BADUNEXPECTEDERROR;
  175. }
  176. #if defined(UA_getnameinfo)
  177. /* Get the peer name for logging */
  178. char remote_name[100];
  179. int res = UA_getnameinfo((struct sockaddr*)remote,
  180. sizeof(struct sockaddr_storage),
  181. remote_name, sizeof(remote_name),
  182. NULL, 0, NI_NUMERICHOST);
  183. if(res == 0) {
  184. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  185. "Connection %i | New connection over TCP from %s",
  186. (int)newsockfd, remote_name);
  187. } else {
  188. UA_LOG_SOCKET_ERRNO_WRAP(UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  189. "Connection %i | New connection over TCP, "
  190. "getnameinfo failed with error: %s",
  191. (int)newsockfd, errno_str));
  192. }
  193. #else
  194. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  195. "Connection %i | New connection over TCP",
  196. (int)newsockfd);
  197. #endif
  198. /* Allocate and initialize the connection */
  199. ConnectionEntry *e = (ConnectionEntry*)UA_malloc(sizeof(ConnectionEntry));
  200. if(!e){
  201. UA_close(newsockfd);
  202. return UA_STATUSCODE_BADOUTOFMEMORY;
  203. }
  204. UA_Connection *c = &e->connection;
  205. memset(c, 0, sizeof(UA_Connection));
  206. c->sockfd = newsockfd;
  207. c->handle = layer;
  208. c->config = nl->localConnectionConfig;
  209. c->send = connection_write;
  210. c->close = ServerNetworkLayerTCP_close;
  211. c->free = ServerNetworkLayerTCP_freeConnection;
  212. c->getSendBuffer = connection_getsendbuffer;
  213. c->releaseSendBuffer = connection_releasesendbuffer;
  214. c->releaseRecvBuffer = connection_releaserecvbuffer;
  215. c->state = UA_CONNECTION_OPENING;
  216. c->openingDate = UA_DateTime_nowMonotonic();
  217. /* Add to the linked list */
  218. LIST_INSERT_HEAD(&layer->connections, e, pointers);
  219. return UA_STATUSCODE_GOOD;
  220. }
  221. static void
  222. addServerSocket(ServerNetworkLayerTCP *layer, struct addrinfo *ai) {
  223. /* Create the server socket */
  224. UA_SOCKET newsock = UA_socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
  225. if(newsock == UA_INVALID_SOCKET)
  226. {
  227. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  228. "Error opening the server socket");
  229. return;
  230. }
  231. /* Some Linux distributions have net.ipv6.bindv6only not activated. So
  232. * sockets can double-bind to IPv4 and IPv6. This leads to problems. Use
  233. * AF_INET6 sockets only for IPv6. */
  234. int optval = 1;
  235. #if UA_IPV6
  236. if(ai->ai_family == AF_INET6 &&
  237. UA_setsockopt(newsock, IPPROTO_IPV6, IPV6_V6ONLY,
  238. (const char*)&optval, sizeof(optval)) == -1) {
  239. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  240. "Could not set an IPv6 socket to IPv6 only");
  241. UA_close(newsock);
  242. return;
  243. }
  244. #endif
  245. if(UA_setsockopt(newsock, SOL_SOCKET, SO_REUSEADDR,
  246. (const char *)&optval, sizeof(optval)) == -1) {
  247. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  248. "Could not make the socket reusable");
  249. UA_close(newsock);
  250. return;
  251. }
  252. if(UA_socket_set_nonblocking(newsock) != UA_STATUSCODE_GOOD) {
  253. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  254. "Could not set the server socket to nonblocking");
  255. UA_close(newsock);
  256. return;
  257. }
  258. /* Bind socket to address */
  259. if(UA_bind(newsock, ai->ai_addr, (socklen_t)ai->ai_addrlen) < 0) {
  260. UA_LOG_SOCKET_ERRNO_WRAP(
  261. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  262. "Error binding a server socket: %s", errno_str));
  263. UA_close(newsock);
  264. return;
  265. }
  266. /* Start listening */
  267. if(UA_listen(newsock, MAXBACKLOG) < 0) {
  268. UA_LOG_SOCKET_ERRNO_WRAP(
  269. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  270. "Error listening on server socket: %s", errno_str));
  271. UA_close(newsock);
  272. return;
  273. }
  274. layer->serverSockets[layer->serverSocketsSize] = newsock;
  275. layer->serverSocketsSize++;
  276. }
  277. static UA_StatusCode
  278. ServerNetworkLayerTCP_start(UA_ServerNetworkLayer *nl, const UA_String *customHostname) {
  279. UA_initialize_architecture_network();
  280. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  281. /* Get the discovery url from the hostname */
  282. UA_String du = UA_STRING_NULL;
  283. char discoveryUrlBuffer[256];
  284. char hostnameBuffer[256];
  285. if (customHostname->length) {
  286. du.length = (size_t)UA_snprintf(discoveryUrlBuffer, 255, "opc.tcp://%.*s:%d/",
  287. (int)customHostname->length,
  288. customHostname->data,
  289. layer->port);
  290. du.data = (UA_Byte*)discoveryUrlBuffer;
  291. }else{
  292. if(UA_gethostname(hostnameBuffer, 255) == 0) {
  293. du.length = (size_t)UA_snprintf(discoveryUrlBuffer, 255, "opc.tcp://%s:%d/",
  294. hostnameBuffer, layer->port);
  295. du.data = (UA_Byte*)discoveryUrlBuffer;
  296. } else {
  297. UA_LOG_ERROR(layer->logger, UA_LOGCATEGORY_NETWORK, "Could not get the hostname");
  298. }
  299. }
  300. UA_String_copy(&du, &nl->discoveryUrl);
  301. /* Get addrinfo of the server and create server sockets */
  302. char portno[6];
  303. UA_snprintf(portno, 6, "%d", layer->port);
  304. struct addrinfo hints, *res;
  305. memset(&hints, 0, sizeof hints);
  306. hints.ai_family = AF_UNSPEC;
  307. hints.ai_socktype = SOCK_STREAM;
  308. hints.ai_flags = AI_PASSIVE;
  309. hints.ai_protocol = IPPROTO_TCP;
  310. if(UA_getaddrinfo(NULL, portno, &hints, &res) != 0)
  311. return UA_STATUSCODE_BADINTERNALERROR;
  312. /* There might be serveral addrinfos (for different network cards,
  313. * IPv4/IPv6). Add a server socket for all of them. */
  314. struct addrinfo *ai = res;
  315. for(layer->serverSocketsSize = 0;
  316. layer->serverSocketsSize < FD_SETSIZE && ai != NULL;
  317. ai = ai->ai_next)
  318. addServerSocket(layer, ai);
  319. UA_freeaddrinfo(res);
  320. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  321. "TCP network layer listening on %.*s",
  322. (int)nl->discoveryUrl.length, nl->discoveryUrl.data);
  323. return UA_STATUSCODE_GOOD;
  324. }
  325. /* After every select, reset the sockets to listen on */
  326. static UA_Int32
  327. setFDSet(ServerNetworkLayerTCP *layer, fd_set *fdset) {
  328. FD_ZERO(fdset);
  329. UA_Int32 highestfd = 0;
  330. for(UA_UInt16 i = 0; i < layer->serverSocketsSize; i++) {
  331. UA_fd_set(layer->serverSockets[i], fdset);
  332. if((UA_Int32)layer->serverSockets[i] > highestfd)
  333. highestfd = (UA_Int32)layer->serverSockets[i];
  334. }
  335. ConnectionEntry *e;
  336. LIST_FOREACH(e, &layer->connections, pointers) {
  337. UA_fd_set(e->connection.sockfd, fdset);
  338. if((UA_Int32)e->connection.sockfd > highestfd)
  339. highestfd = (UA_Int32)e->connection.sockfd;
  340. }
  341. return highestfd;
  342. }
  343. static UA_StatusCode
  344. ServerNetworkLayerTCP_listen(UA_ServerNetworkLayer *nl, UA_Server *server,
  345. UA_UInt16 timeout) {
  346. /* Every open socket can generate two jobs */
  347. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  348. if (layer->serverSocketsSize == 0)
  349. return UA_STATUSCODE_GOOD;
  350. /* Listen on open sockets (including the server) */
  351. fd_set fdset, errset;
  352. UA_Int32 highestfd = setFDSet(layer, &fdset);
  353. setFDSet(layer, &errset);
  354. struct timeval tmptv = {0, timeout * 1000};
  355. if (UA_select(highestfd+1, &fdset, NULL, &errset, &tmptv) < 0) {
  356. UA_LOG_SOCKET_ERRNO_WRAP(
  357. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  358. "Socket select failed with %s", errno_str));
  359. // we will retry, so do not return bad
  360. return UA_STATUSCODE_GOOD;
  361. }
  362. /* Accept new connections via the server sockets */
  363. for(UA_UInt16 i = 0; i < layer->serverSocketsSize; i++) {
  364. if(!UA_fd_isset(layer->serverSockets[i], &fdset))
  365. continue;
  366. struct sockaddr_storage remote;
  367. socklen_t remote_size = sizeof(remote);
  368. UA_SOCKET newsockfd = UA_accept((UA_SOCKET)layer->serverSockets[i],
  369. (struct sockaddr*)&remote, &remote_size);
  370. if(newsockfd == UA_INVALID_SOCKET)
  371. continue;
  372. UA_LOG_TRACE(layer->logger, UA_LOGCATEGORY_NETWORK,
  373. "Connection %i | New TCP connection on server socket %i",
  374. (int)newsockfd, (int)(layer->serverSockets[i]));
  375. ServerNetworkLayerTCP_add(nl, layer, (UA_Int32)newsockfd, &remote);
  376. }
  377. /* Read from established sockets */
  378. ConnectionEntry *e, *e_tmp;
  379. UA_DateTime now = UA_DateTime_nowMonotonic();
  380. LIST_FOREACH_SAFE(e, &layer->connections, pointers, e_tmp) {
  381. if ((e->connection.state == UA_CONNECTION_OPENING) &&
  382. (now > (e->connection.openingDate + (NOHELLOTIMEOUT * UA_DATETIME_MSEC)))){
  383. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  384. "Connection %i | Closed by the server (no Hello Message)",
  385. (int)(e->connection.sockfd));
  386. LIST_REMOVE(e, pointers);
  387. UA_close(e->connection.sockfd);
  388. UA_Server_removeConnection(server, &e->connection);
  389. continue;
  390. }
  391. if(!UA_fd_isset(e->connection.sockfd, &errset) &&
  392. !UA_fd_isset(e->connection.sockfd, &fdset))
  393. continue;
  394. UA_LOG_TRACE(layer->logger, UA_LOGCATEGORY_NETWORK,
  395. "Connection %i | Activity on the socket",
  396. (int)(e->connection.sockfd));
  397. UA_ByteString buf = UA_BYTESTRING_NULL;
  398. UA_StatusCode retval = connection_recv(&e->connection, &buf, 0);
  399. if(retval == UA_STATUSCODE_GOOD) {
  400. /* Process packets */
  401. UA_Server_processBinaryMessage(server, &e->connection, &buf);
  402. connection_releaserecvbuffer(&e->connection, &buf);
  403. } else if(retval == UA_STATUSCODE_BADCONNECTIONCLOSED) {
  404. /* The socket is shutdown but not closed */
  405. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  406. "Connection %i | Closed",
  407. (int)(e->connection.sockfd));
  408. LIST_REMOVE(e, pointers);
  409. UA_close(e->connection.sockfd);
  410. UA_Server_removeConnection(server, &e->connection);
  411. }
  412. }
  413. return UA_STATUSCODE_GOOD;
  414. }
  415. static void
  416. ServerNetworkLayerTCP_stop(UA_ServerNetworkLayer *nl, UA_Server *server) {
  417. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  418. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  419. "Shutting down the TCP network layer");
  420. /* Close the server sockets */
  421. for(UA_UInt16 i = 0; i < layer->serverSocketsSize; i++) {
  422. UA_shutdown(layer->serverSockets[i], 2);
  423. UA_close(layer->serverSockets[i]);
  424. }
  425. layer->serverSocketsSize = 0;
  426. /* Close open connections */
  427. ConnectionEntry *e;
  428. LIST_FOREACH(e, &layer->connections, pointers)
  429. ServerNetworkLayerTCP_close(&e->connection);
  430. /* Run recv on client sockets. This picks up the closed sockets and frees
  431. * the connection. */
  432. ServerNetworkLayerTCP_listen(nl, server, 0);
  433. UA_deinitialize_architecture_network();
  434. }
  435. /* run only when the server is stopped */
  436. static void
  437. ServerNetworkLayerTCP_deleteMembers(UA_ServerNetworkLayer *nl) {
  438. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  439. UA_String_deleteMembers(&nl->discoveryUrl);
  440. /* Hard-close and remove remaining connections. The server is no longer
  441. * running. So this is safe. */
  442. ConnectionEntry *e, *e_tmp;
  443. LIST_FOREACH_SAFE(e, &layer->connections, pointers, e_tmp) {
  444. LIST_REMOVE(e, pointers);
  445. UA_close(e->connection.sockfd);
  446. UA_free(e);
  447. }
  448. /* Free the layer */
  449. UA_free(layer);
  450. }
  451. UA_ServerNetworkLayer
  452. UA_ServerNetworkLayerTCP(UA_ConnectionConfig config, UA_UInt16 port,
  453. const UA_Logger *logger) {
  454. UA_ServerNetworkLayer nl;
  455. memset(&nl, 0, sizeof(UA_ServerNetworkLayer));
  456. nl.deleteMembers = ServerNetworkLayerTCP_deleteMembers;
  457. nl.localConnectionConfig = config;
  458. nl.start = ServerNetworkLayerTCP_start;
  459. nl.listen = ServerNetworkLayerTCP_listen;
  460. nl.stop = ServerNetworkLayerTCP_stop;
  461. nl.handle = NULL;
  462. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP*)
  463. UA_calloc(1,sizeof(ServerNetworkLayerTCP));
  464. if(!layer)
  465. return nl;
  466. nl.handle = layer;
  467. layer->logger = logger;
  468. layer->port = port;
  469. return nl;
  470. }
  471. typedef struct TCPClientConnection {
  472. struct addrinfo hints, *server;
  473. UA_DateTime connStart;
  474. char* endpointURL;
  475. UA_UInt32 timeout;
  476. } TCPClientConnection;
  477. /***************************/
  478. /* Client NetworkLayer TCP */
  479. /***************************/
  480. static void
  481. ClientNetworkLayerTCP_close(UA_Connection *connection) {
  482. if (connection->state == UA_CONNECTION_CLOSED)
  483. return;
  484. if(connection->sockfd != UA_INVALID_SOCKET) {
  485. UA_shutdown(connection->sockfd, 2);
  486. UA_close(connection->sockfd);
  487. }
  488. connection->state = UA_CONNECTION_CLOSED;
  489. }
  490. static void
  491. ClientNetworkLayerTCP_free(UA_Connection *connection) {
  492. if (connection->handle){
  493. TCPClientConnection *tcpConnection = (TCPClientConnection *)connection->handle;
  494. if(tcpConnection->server)
  495. UA_freeaddrinfo(tcpConnection->server);
  496. UA_free(tcpConnection);
  497. }
  498. }
  499. UA_StatusCode UA_ClientConnectionTCP_poll(UA_Client *client, void *data) {
  500. UA_Connection *connection = (UA_Connection*) data;
  501. if (connection->state == UA_CONNECTION_CLOSED)
  502. return UA_STATUSCODE_BADDISCONNECT;
  503. TCPClientConnection *tcpConnection =
  504. (TCPClientConnection*) connection->handle;
  505. UA_DateTime connStart = UA_DateTime_nowMonotonic();
  506. UA_SOCKET clientsockfd;
  507. UA_ClientConfig *config = UA_Client_getConfig(client);
  508. if (connection->state == UA_CONNECTION_ESTABLISHED) {
  509. UA_Client_removeRepeatedCallback(client, connection->connectCallbackID);
  510. connection->connectCallbackID = 0;
  511. return UA_STATUSCODE_GOOD;
  512. }
  513. if ((UA_Double) (UA_DateTime_nowMonotonic() - tcpConnection->connStart)
  514. > tcpConnection->timeout* UA_DATETIME_MSEC ) {
  515. // connection timeout
  516. ClientNetworkLayerTCP_close(connection);
  517. UA_LOG_WARNING(&config->logger, UA_LOGCATEGORY_NETWORK,
  518. "Timed out");
  519. return UA_STATUSCODE_BADDISCONNECT;
  520. }
  521. /* On linux connect may immediately return with ECONNREFUSED but we still want to try to connect */
  522. /* Thus use a loop and retry until timeout is reached */
  523. /* Get a socket */
  524. clientsockfd = UA_socket(tcpConnection->server->ai_family,
  525. tcpConnection->server->ai_socktype,
  526. tcpConnection->server->ai_protocol);
  527. connection->sockfd = (UA_Int32) clientsockfd; /* cast for win32 */
  528. if(clientsockfd == UA_INVALID_SOCKET) {
  529. UA_LOG_WARNING(&config->logger, UA_LOGCATEGORY_NETWORK,
  530. "Could not create client socket: %s", strerror(UA_ERRNO));
  531. ClientNetworkLayerTCP_close(connection);
  532. return UA_STATUSCODE_BADDISCONNECT;
  533. }
  534. /* Non blocking connect to be able to timeout */
  535. if(UA_socket_set_nonblocking(clientsockfd) != UA_STATUSCODE_GOOD) {
  536. UA_LOG_WARNING(&config->logger, UA_LOGCATEGORY_NETWORK,
  537. "Could not set the client socket to nonblocking");
  538. ClientNetworkLayerTCP_close(connection);
  539. return UA_STATUSCODE_BADDISCONNECT;
  540. }
  541. /* Non blocking connect */
  542. int error = UA_connect(clientsockfd, tcpConnection->server->ai_addr,
  543. tcpConnection->server->ai_addrlen);
  544. if ((error == -1) && (UA_ERRNO != UA_ERR_CONNECTION_PROGRESS)) {
  545. ClientNetworkLayerTCP_close(connection);
  546. UA_LOG_WARNING(&config->logger, UA_LOGCATEGORY_NETWORK,
  547. "Connection to failed with error: %s", strerror(UA_ERRNO));
  548. return UA_STATUSCODE_BADDISCONNECT;
  549. }
  550. /* Use select to wait and check if connected */
  551. if (error == -1 && (UA_ERRNO == UA_ERR_CONNECTION_PROGRESS)) {
  552. /* connection in progress. Wait until connected using select */
  553. UA_UInt32 timeSinceStart =
  554. (UA_UInt32) ((UA_Double) (UA_DateTime_nowMonotonic() - connStart)
  555. * UA_DATETIME_MSEC);
  556. #ifdef _OS9000
  557. /* OS-9 can't use select for checking write sockets.
  558. * Therefore, we need to use connect until success or failed
  559. */
  560. UA_UInt32 timeout_usec = (tcpConnection->timeout - timeSinceStart)
  561. * 1000;
  562. int resultsize = 0;
  563. do {
  564. u_int32 time = 0x80000001;
  565. signal_code sig;
  566. timeout_usec -= 1000000/256; // Sleep 1/256 second
  567. if (timeout_usec < 0)
  568. break;
  569. _os_sleep(&time,&sig);
  570. error = connect(clientsockfd, tcpConnection->server->ai_addr,
  571. tcpConnection->server->ai_addrlen);
  572. if ((error == -1 && UA_ERRNO == EISCONN) || (error == 0))
  573. resultsize = 1;
  574. if (error == -1 && UA_ERRNO != EALREADY && UA_ERRNO != EINPROGRESS)
  575. break;
  576. }
  577. while(resultsize == 0);
  578. #else
  579. fd_set fdset;
  580. FD_ZERO(&fdset);
  581. UA_fd_set(clientsockfd, &fdset);
  582. UA_UInt32 timeout_usec = (tcpConnection->timeout - timeSinceStart)
  583. * 1000;
  584. struct timeval tmptv = { (long int) (timeout_usec / 1000000),
  585. (long int) (timeout_usec % 1000000) };
  586. int resultsize = UA_select((UA_Int32) (clientsockfd + 1), NULL, &fdset,
  587. NULL, &tmptv);
  588. #endif
  589. if (resultsize == 1) {
  590. /* Windows does not have any getsockopt equivalent and it is not needed there */
  591. #ifdef _WIN32
  592. connection->sockfd = clientsockfd;
  593. connection->state = UA_CONNECTION_ESTABLISHED;
  594. return UA_STATUSCODE_GOOD;
  595. #else
  596. OPTVAL_TYPE so_error;
  597. socklen_t len = sizeof so_error;
  598. int ret = UA_getsockopt(clientsockfd, SOL_SOCKET, SO_ERROR, &so_error,
  599. &len);
  600. if (ret != 0 || so_error != 0) {
  601. /* on connection refused we should still try to connect */
  602. /* connection refused happens on localhost or local ip without timeout */
  603. if (so_error != ECONNREFUSED) {
  604. // general error
  605. ClientNetworkLayerTCP_close(connection);
  606. UA_LOG_WARNING(&config->logger, UA_LOGCATEGORY_NETWORK,
  607. "Connection to failed with error: %s",
  608. strerror(ret == 0 ? so_error : UA_ERRNO));
  609. return UA_STATUSCODE_BADDISCONNECT;
  610. }
  611. /* wait until we try a again. Do not make this too small, otherwise the
  612. * timeout is somehow wrong */
  613. } else {
  614. connection->state = UA_CONNECTION_ESTABLISHED;
  615. return UA_STATUSCODE_GOOD;
  616. }
  617. #endif
  618. }
  619. } else {
  620. connection->state = UA_CONNECTION_ESTABLISHED;
  621. return UA_STATUSCODE_GOOD;
  622. }
  623. #ifdef SO_NOSIGPIPE
  624. int val = 1;
  625. int sso_result = setsockopt(connection->sockfd, SOL_SOCKET,
  626. SO_NOSIGPIPE, (void*)&val, sizeof(val));
  627. if(sso_result < 0)
  628. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  629. "Couldn't set SO_NOSIGPIPE");
  630. #endif
  631. return UA_STATUSCODE_GOOD;
  632. }
  633. UA_Connection
  634. UA_ClientConnectionTCP_init(UA_ConnectionConfig config, const char *endpointUrl,
  635. const UA_UInt32 timeout, const UA_Logger *logger) {
  636. UA_Connection connection;
  637. memset(&connection, 0, sizeof(UA_Connection));
  638. connection.state = UA_CONNECTION_OPENING;
  639. connection.config = config;
  640. connection.send = connection_write;
  641. connection.recv = connection_recv;
  642. connection.close = ClientNetworkLayerTCP_close;
  643. connection.free = ClientNetworkLayerTCP_free;
  644. connection.getSendBuffer = connection_getsendbuffer;
  645. connection.releaseSendBuffer = connection_releasesendbuffer;
  646. connection.releaseRecvBuffer = connection_releaserecvbuffer;
  647. TCPClientConnection *tcpClientConnection = (TCPClientConnection*) UA_malloc(
  648. sizeof(TCPClientConnection));
  649. connection.handle = (void*) tcpClientConnection;
  650. tcpClientConnection->timeout = timeout;
  651. UA_String endpointUrlString = UA_STRING((char*) (uintptr_t) endpointUrl);
  652. UA_String hostnameString = UA_STRING_NULL;
  653. UA_String pathString = UA_STRING_NULL;
  654. UA_UInt16 port = 0;
  655. char hostname[512];
  656. tcpClientConnection->connStart = UA_DateTime_nowMonotonic();
  657. UA_StatusCode parse_retval = UA_parseEndpointUrl(&endpointUrlString,
  658. &hostnameString, &port, &pathString);
  659. if (parse_retval != UA_STATUSCODE_GOOD || hostnameString.length > 511) {
  660. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  661. "Server url is invalid: %s", endpointUrl);
  662. connection.state = UA_CONNECTION_CLOSED;
  663. return connection;
  664. }
  665. memcpy(hostname, hostnameString.data, hostnameString.length);
  666. hostname[hostnameString.length] = 0;
  667. if (port == 0) {
  668. port = 4840;
  669. UA_LOG_INFO(logger, UA_LOGCATEGORY_NETWORK,
  670. "No port defined, using default port %d", port);
  671. }
  672. memset(&tcpClientConnection->hints, 0, sizeof(tcpClientConnection->hints));
  673. tcpClientConnection->hints.ai_family = AF_UNSPEC;
  674. tcpClientConnection->hints.ai_socktype = SOCK_STREAM;
  675. char portStr[6];
  676. UA_snprintf(portStr, 6, "%d", port);
  677. int error = UA_getaddrinfo(hostname, portStr, &tcpClientConnection->hints,
  678. &tcpClientConnection->server);
  679. if (error != 0 || !tcpClientConnection->server) {
  680. UA_LOG_SOCKET_ERRNO_GAI_WRAP(UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  681. "DNS lookup of %s failed with error %s", hostname, errno_str));
  682. connection.state = UA_CONNECTION_CLOSED;
  683. return connection;
  684. }
  685. return connection;
  686. }
  687. UA_Connection
  688. UA_ClientConnectionTCP(UA_ConnectionConfig config, const char *endpointUrl,
  689. const UA_UInt32 timeout, const UA_Logger *logger) {
  690. UA_initialize_architecture_network();
  691. UA_Connection connection;
  692. memset(&connection, 0, sizeof(UA_Connection));
  693. connection.state = UA_CONNECTION_CLOSED;
  694. connection.config = config;
  695. connection.send = connection_write;
  696. connection.recv = connection_recv;
  697. connection.close = ClientNetworkLayerTCP_close;
  698. connection.free = ClientNetworkLayerTCP_free;
  699. connection.getSendBuffer = connection_getsendbuffer;
  700. connection.releaseSendBuffer = connection_releasesendbuffer;
  701. connection.releaseRecvBuffer = connection_releaserecvbuffer;
  702. connection.handle = NULL;
  703. UA_String endpointUrlString = UA_STRING((char*)(uintptr_t)endpointUrl);
  704. UA_String hostnameString = UA_STRING_NULL;
  705. UA_String pathString = UA_STRING_NULL;
  706. UA_UInt16 port = 0;
  707. char hostname[512];
  708. UA_StatusCode parse_retval =
  709. UA_parseEndpointUrl(&endpointUrlString, &hostnameString,
  710. &port, &pathString);
  711. if(parse_retval != UA_STATUSCODE_GOOD || hostnameString.length > 511) {
  712. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  713. "Server url is invalid: %s", endpointUrl);
  714. return connection;
  715. }
  716. memcpy(hostname, hostnameString.data, hostnameString.length);
  717. hostname[hostnameString.length] = 0;
  718. if(port == 0) {
  719. port = 4840;
  720. UA_LOG_INFO(logger, UA_LOGCATEGORY_NETWORK,
  721. "No port defined, using default port %d", port);
  722. }
  723. struct addrinfo hints, *server;
  724. memset(&hints, 0, sizeof(hints));
  725. hints.ai_family = AF_UNSPEC;
  726. hints.ai_socktype = SOCK_STREAM;
  727. hints.ai_protocol = IPPROTO_TCP;
  728. char portStr[6];
  729. UA_snprintf(portStr, 6, "%d", port);
  730. int error = UA_getaddrinfo(hostname, portStr, &hints, &server);
  731. if(error != 0 || !server) {
  732. UA_LOG_SOCKET_ERRNO_GAI_WRAP(UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  733. "DNS lookup of %s failed with error %s", hostname, errno_str));
  734. return connection;
  735. }
  736. UA_Boolean connected = false;
  737. UA_DateTime dtTimeout = timeout * UA_DATETIME_MSEC;
  738. UA_DateTime connStart = UA_DateTime_nowMonotonic();
  739. UA_SOCKET clientsockfd;
  740. /* On linux connect may immediately return with ECONNREFUSED but we still
  741. * want to try to connect. So use a loop and retry until timeout is
  742. * reached. */
  743. do {
  744. /* Get a socket */
  745. clientsockfd = UA_socket(server->ai_family,
  746. server->ai_socktype,
  747. server->ai_protocol);
  748. if(clientsockfd == UA_INVALID_SOCKET) {
  749. UA_LOG_SOCKET_ERRNO_WRAP(UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  750. "Could not create client socket: %s", errno_str));
  751. UA_freeaddrinfo(server);
  752. return connection;
  753. }
  754. connection.state = UA_CONNECTION_OPENING;
  755. /* Connect to the server */
  756. connection.sockfd = clientsockfd;
  757. /* Non blocking connect to be able to timeout */
  758. if (UA_socket_set_nonblocking(clientsockfd) != UA_STATUSCODE_GOOD) {
  759. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  760. "Could not set the client socket to nonblocking");
  761. ClientNetworkLayerTCP_close(&connection);
  762. UA_freeaddrinfo(server);
  763. return connection;
  764. }
  765. /* Non blocking connect */
  766. error = UA_connect(clientsockfd, server->ai_addr, (socklen_t)server->ai_addrlen);
  767. if ((error == -1) && (UA_ERRNO != UA_ERR_CONNECTION_PROGRESS)) {
  768. ClientNetworkLayerTCP_close(&connection);
  769. UA_LOG_SOCKET_ERRNO_WRAP(
  770. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  771. "Connection to %s failed with error: %s",
  772. endpointUrl, errno_str));
  773. UA_freeaddrinfo(server);
  774. return connection;
  775. }
  776. /* Use select to wait and check if connected */
  777. if (error == -1 && (UA_ERRNO == UA_ERR_CONNECTION_PROGRESS)) {
  778. /* connection in progress. Wait until connected using select */
  779. UA_DateTime timeSinceStart = UA_DateTime_nowMonotonic() - connStart;
  780. if(timeSinceStart > dtTimeout)
  781. break;
  782. #ifdef _OS9000
  783. /* OS-9 can't use select for checking write sockets.
  784. * Therefore, we need to use connect until success or failed
  785. */
  786. UA_DateTime timeout_usec = (dtTimeout - timeSinceStart) / UA_DATETIME_USEC;
  787. int resultsize = 0;
  788. do {
  789. u_int32 time = 0x80000001;
  790. signal_code sig;
  791. timeout_usec -= 1000000/256; // Sleep 1/256 second
  792. if (timeout_usec < 0)
  793. break;
  794. _os_sleep(&time,&sig);
  795. error = connect(clientsockfd, server->ai_addr, server->ai_addrlen);
  796. if ((error == -1 && UA_ERRNO == EISCONN) || (error == 0))
  797. resultsize = 1;
  798. if (error == -1 && UA_ERRNO != EALREADY && UA_ERRNO != EINPROGRESS)
  799. break;
  800. }
  801. while(resultsize == 0);
  802. #else
  803. fd_set fdset;
  804. FD_ZERO(&fdset);
  805. UA_fd_set(clientsockfd, &fdset);
  806. UA_DateTime timeout_usec = (dtTimeout - timeSinceStart) / UA_DATETIME_USEC;
  807. struct timeval tmptv = {(long int) (timeout_usec / 1000000),
  808. (long int) (timeout_usec % 1000000)};
  809. int resultsize = UA_select((UA_Int32)(clientsockfd + 1), NULL, &fdset, NULL, &tmptv);
  810. #endif
  811. if(resultsize == 1) {
  812. #ifdef _WIN32
  813. /* Windows does not have any getsockopt equivalent and it is not
  814. * needed there */
  815. connected = true;
  816. break;
  817. #else
  818. OPTVAL_TYPE so_error;
  819. socklen_t len = sizeof so_error;
  820. int ret = UA_getsockopt(clientsockfd, SOL_SOCKET, SO_ERROR, &so_error, &len);
  821. if (ret != 0 || so_error != 0) {
  822. /* on connection refused we should still try to connect */
  823. /* connection refused happens on localhost or local ip without timeout */
  824. if (so_error != ECONNREFUSED) {
  825. ClientNetworkLayerTCP_close(&connection);
  826. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  827. "Connection to %s failed with error: %s",
  828. endpointUrl, strerror(ret == 0 ? so_error : UA_ERRNO));
  829. UA_freeaddrinfo(server);
  830. return connection;
  831. }
  832. /* wait until we try a again. Do not make this too small, otherwise the
  833. * timeout is somehow wrong */
  834. UA_sleep_ms(100);
  835. } else {
  836. connected = true;
  837. break;
  838. }
  839. #endif
  840. }
  841. } else {
  842. connected = true;
  843. break;
  844. }
  845. ClientNetworkLayerTCP_close(&connection);
  846. } while ((UA_DateTime_nowMonotonic() - connStart) < dtTimeout);
  847. UA_freeaddrinfo(server);
  848. if(!connected) {
  849. /* connection timeout */
  850. if (connection.state != UA_CONNECTION_CLOSED)
  851. ClientNetworkLayerTCP_close(&connection);
  852. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  853. "Trying to connect to %s timed out",
  854. endpointUrl);
  855. return connection;
  856. }
  857. /* We are connected. Reset socket to blocking */
  858. if(UA_socket_set_blocking(clientsockfd) != UA_STATUSCODE_GOOD) {
  859. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  860. "Could not set the client socket to blocking");
  861. ClientNetworkLayerTCP_close(&connection);
  862. return connection;
  863. }
  864. #ifdef SO_NOSIGPIPE
  865. int val = 1;
  866. int sso_result = UA_setsockopt(connection.sockfd, SOL_SOCKET,
  867. SO_NOSIGPIPE, (void*)&val, sizeof(val));
  868. if(sso_result < 0)
  869. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  870. "Couldn't set SO_NOSIGPIPE");
  871. #endif
  872. return connection;
  873. }