network_tcp.c 38 KB

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