network_tcp.c 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  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. layer->serverSockets[layer->serverSocketsSize] = newsock;
  283. layer->serverSocketsSize++;
  284. }
  285. static UA_StatusCode
  286. ServerNetworkLayerTCP_start(UA_ServerNetworkLayer *nl, const UA_String *customHostname) {
  287. UA_initialize_architecture_network();
  288. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  289. /* Get the discovery url from the hostname */
  290. UA_String du = UA_STRING_NULL;
  291. char discoveryUrlBuffer[256];
  292. char hostnameBuffer[256];
  293. if (customHostname->length) {
  294. du.length = (size_t)UA_snprintf(discoveryUrlBuffer, 255, "opc.tcp://%.*s:%d/",
  295. (int)customHostname->length,
  296. customHostname->data,
  297. layer->port);
  298. du.data = (UA_Byte*)discoveryUrlBuffer;
  299. }else{
  300. if(UA_gethostname(hostnameBuffer, 255) == 0) {
  301. du.length = (size_t)UA_snprintf(discoveryUrlBuffer, 255, "opc.tcp://%s:%d/",
  302. hostnameBuffer, layer->port);
  303. du.data = (UA_Byte*)discoveryUrlBuffer;
  304. } else {
  305. UA_LOG_ERROR(layer->logger, UA_LOGCATEGORY_NETWORK, "Could not get the hostname");
  306. }
  307. }
  308. UA_String_copy(&du, &nl->discoveryUrl);
  309. /* Get addrinfo of the server and create server sockets */
  310. char portno[6];
  311. UA_snprintf(portno, 6, "%d", layer->port);
  312. struct addrinfo hints, *res;
  313. memset(&hints, 0, sizeof hints);
  314. hints.ai_family = AF_UNSPEC;
  315. hints.ai_socktype = SOCK_STREAM;
  316. hints.ai_flags = AI_PASSIVE;
  317. hints.ai_protocol = IPPROTO_TCP;
  318. if(UA_getaddrinfo(NULL, portno, &hints, &res) != 0)
  319. return UA_STATUSCODE_BADINTERNALERROR;
  320. /* There might be serveral addrinfos (for different network cards,
  321. * IPv4/IPv6). Add a server socket for all of them. */
  322. struct addrinfo *ai = res;
  323. for(layer->serverSocketsSize = 0;
  324. layer->serverSocketsSize < FD_SETSIZE && ai != NULL;
  325. ai = ai->ai_next)
  326. addServerSocket(layer, ai);
  327. UA_freeaddrinfo(res);
  328. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  329. "TCP network layer listening on %.*s",
  330. (int)nl->discoveryUrl.length, nl->discoveryUrl.data);
  331. return UA_STATUSCODE_GOOD;
  332. }
  333. /* After every select, reset the sockets to listen on */
  334. static UA_Int32
  335. setFDSet(ServerNetworkLayerTCP *layer, fd_set *fdset) {
  336. FD_ZERO(fdset);
  337. UA_Int32 highestfd = 0;
  338. for(UA_UInt16 i = 0; i < layer->serverSocketsSize; i++) {
  339. UA_fd_set(layer->serverSockets[i], fdset);
  340. if((UA_Int32)layer->serverSockets[i] > highestfd)
  341. highestfd = (UA_Int32)layer->serverSockets[i];
  342. }
  343. ConnectionEntry *e;
  344. LIST_FOREACH(e, &layer->connections, pointers) {
  345. UA_fd_set(e->connection.sockfd, fdset);
  346. if((UA_Int32)e->connection.sockfd > highestfd)
  347. highestfd = (UA_Int32)e->connection.sockfd;
  348. }
  349. return highestfd;
  350. }
  351. static UA_StatusCode
  352. ServerNetworkLayerTCP_listen(UA_ServerNetworkLayer *nl, UA_Server *server,
  353. UA_UInt16 timeout) {
  354. /* Every open socket can generate two jobs */
  355. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  356. if (layer->serverSocketsSize == 0)
  357. return UA_STATUSCODE_GOOD;
  358. /* Listen on open sockets (including the server) */
  359. fd_set fdset, errset;
  360. UA_Int32 highestfd = setFDSet(layer, &fdset);
  361. setFDSet(layer, &errset);
  362. struct timeval tmptv = {0, timeout * 1000};
  363. if (UA_select(highestfd+1, &fdset, NULL, &errset, &tmptv) < 0) {
  364. UA_LOG_SOCKET_ERRNO_WRAP(
  365. UA_LOG_DEBUG(layer->logger, UA_LOGCATEGORY_NETWORK,
  366. "Socket select failed with %s", errno_str));
  367. // we will retry, so do not return bad
  368. return UA_STATUSCODE_GOOD;
  369. }
  370. /* Accept new connections via the server sockets */
  371. for(UA_UInt16 i = 0; i < layer->serverSocketsSize; i++) {
  372. if(!UA_fd_isset(layer->serverSockets[i], &fdset))
  373. continue;
  374. struct sockaddr_storage remote;
  375. socklen_t remote_size = sizeof(remote);
  376. UA_SOCKET newsockfd = UA_accept((UA_SOCKET)layer->serverSockets[i],
  377. (struct sockaddr*)&remote, &remote_size);
  378. if(newsockfd == UA_INVALID_SOCKET)
  379. continue;
  380. UA_LOG_TRACE(layer->logger, UA_LOGCATEGORY_NETWORK,
  381. "Connection %i | New TCP connection on server socket %i",
  382. (int)newsockfd, (int)(layer->serverSockets[i]));
  383. ServerNetworkLayerTCP_add(nl, layer, (UA_Int32)newsockfd, &remote);
  384. }
  385. /* Read from established sockets */
  386. ConnectionEntry *e, *e_tmp;
  387. UA_DateTime now = UA_DateTime_nowMonotonic();
  388. LIST_FOREACH_SAFE(e, &layer->connections, pointers, e_tmp) {
  389. if ((e->connection.state == UA_CONNECTION_OPENING) &&
  390. (now > (e->connection.openingDate + (NOHELLOTIMEOUT * UA_DATETIME_MSEC)))){
  391. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  392. "Connection %i | Closed by the server (no Hello Message)",
  393. (int)(e->connection.sockfd));
  394. LIST_REMOVE(e, pointers);
  395. UA_close(e->connection.sockfd);
  396. UA_Server_removeConnection(server, &e->connection);
  397. continue;
  398. }
  399. if(!UA_fd_isset(e->connection.sockfd, &errset) &&
  400. !UA_fd_isset(e->connection.sockfd, &fdset))
  401. continue;
  402. UA_LOG_TRACE(layer->logger, UA_LOGCATEGORY_NETWORK,
  403. "Connection %i | Activity on the socket",
  404. (int)(e->connection.sockfd));
  405. UA_ByteString buf = UA_BYTESTRING_NULL;
  406. UA_StatusCode retval = connection_recv(&e->connection, &buf, 0);
  407. if(retval == UA_STATUSCODE_GOOD) {
  408. /* Process packets */
  409. UA_Server_processBinaryMessage(server, &e->connection, &buf);
  410. connection_releaserecvbuffer(&e->connection, &buf);
  411. } else if(retval == UA_STATUSCODE_BADCONNECTIONCLOSED) {
  412. /* The socket is shutdown but not closed */
  413. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  414. "Connection %i | Closed",
  415. (int)(e->connection.sockfd));
  416. LIST_REMOVE(e, pointers);
  417. UA_close(e->connection.sockfd);
  418. UA_Server_removeConnection(server, &e->connection);
  419. }
  420. }
  421. return UA_STATUSCODE_GOOD;
  422. }
  423. static void
  424. ServerNetworkLayerTCP_stop(UA_ServerNetworkLayer *nl, UA_Server *server) {
  425. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  426. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  427. "Shutting down the TCP network layer");
  428. /* Close the server sockets */
  429. for(UA_UInt16 i = 0; i < layer->serverSocketsSize; i++) {
  430. UA_shutdown(layer->serverSockets[i], 2);
  431. UA_close(layer->serverSockets[i]);
  432. }
  433. layer->serverSocketsSize = 0;
  434. /* Close open connections */
  435. ConnectionEntry *e;
  436. LIST_FOREACH(e, &layer->connections, pointers)
  437. ServerNetworkLayerTCP_close(&e->connection);
  438. /* Run recv on client sockets. This picks up the closed sockets and frees
  439. * the connection. */
  440. ServerNetworkLayerTCP_listen(nl, server, 0);
  441. UA_deinitialize_architecture_network();
  442. }
  443. /* run only when the server is stopped */
  444. static void
  445. ServerNetworkLayerTCP_deleteMembers(UA_ServerNetworkLayer *nl) {
  446. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  447. UA_String_deleteMembers(&nl->discoveryUrl);
  448. /* Hard-close and remove remaining connections. The server is no longer
  449. * running. So this is safe. */
  450. ConnectionEntry *e, *e_tmp;
  451. LIST_FOREACH_SAFE(e, &layer->connections, pointers, e_tmp) {
  452. LIST_REMOVE(e, pointers);
  453. UA_close(e->connection.sockfd);
  454. UA_free(e);
  455. }
  456. /* Free the layer */
  457. UA_free(layer);
  458. }
  459. UA_ServerNetworkLayer
  460. UA_ServerNetworkLayerTCP(UA_ConnectionConfig config, UA_UInt16 port,
  461. UA_Logger *logger) {
  462. UA_ServerNetworkLayer nl;
  463. memset(&nl, 0, sizeof(UA_ServerNetworkLayer));
  464. nl.deleteMembers = ServerNetworkLayerTCP_deleteMembers;
  465. nl.localConnectionConfig = config;
  466. nl.start = ServerNetworkLayerTCP_start;
  467. nl.listen = ServerNetworkLayerTCP_listen;
  468. nl.stop = ServerNetworkLayerTCP_stop;
  469. nl.handle = NULL;
  470. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP*)
  471. UA_calloc(1,sizeof(ServerNetworkLayerTCP));
  472. if(!layer)
  473. return nl;
  474. nl.handle = layer;
  475. layer->logger = logger;
  476. layer->port = port;
  477. return nl;
  478. }
  479. typedef struct TCPClientConnection {
  480. struct addrinfo hints, *server;
  481. UA_DateTime connStart;
  482. char* endpointURL;
  483. UA_UInt32 timeout;
  484. } TCPClientConnection;
  485. /***************************/
  486. /* Client NetworkLayer TCP */
  487. /***************************/
  488. static void
  489. ClientNetworkLayerTCP_close(UA_Connection *connection) {
  490. if (connection->state == UA_CONNECTION_CLOSED)
  491. return;
  492. if(connection->sockfd != UA_INVALID_SOCKET) {
  493. UA_shutdown(connection->sockfd, 2);
  494. UA_close(connection->sockfd);
  495. }
  496. connection->state = UA_CONNECTION_CLOSED;
  497. }
  498. static void
  499. ClientNetworkLayerTCP_free(UA_Connection *connection) {
  500. if(connection->handle) {
  501. TCPClientConnection *tcpConnection = (TCPClientConnection *)connection->handle;
  502. if(tcpConnection->server)
  503. UA_freeaddrinfo(tcpConnection->server);
  504. UA_free(tcpConnection);
  505. connection->handle = NULL;
  506. }
  507. }
  508. UA_StatusCode UA_ClientConnectionTCP_poll(UA_Client *client, void *data) {
  509. UA_Connection *connection = (UA_Connection*) data;
  510. if (connection->state == UA_CONNECTION_CLOSED)
  511. return UA_STATUSCODE_BADDISCONNECT;
  512. TCPClientConnection *tcpConnection =
  513. (TCPClientConnection*) connection->handle;
  514. UA_DateTime connStart = UA_DateTime_nowMonotonic();
  515. UA_SOCKET clientsockfd = connection->sockfd;
  516. UA_ClientConfig *config = UA_Client_getConfig(client);
  517. if (connection->state == UA_CONNECTION_ESTABLISHED) {
  518. UA_Client_removeRepeatedCallback(client, connection->connectCallbackID);
  519. connection->connectCallbackID = 0;
  520. return UA_STATUSCODE_GOOD;
  521. }
  522. if ((UA_Double) (UA_DateTime_nowMonotonic() - tcpConnection->connStart)
  523. > tcpConnection->timeout* UA_DATETIME_MSEC ) {
  524. // connection timeout
  525. ClientNetworkLayerTCP_close(connection);
  526. UA_LOG_WARNING(&config->logger, UA_LOGCATEGORY_NETWORK,
  527. "Timed out");
  528. return UA_STATUSCODE_BADDISCONNECT;
  529. }
  530. /* On linux connect may immediately return with ECONNREFUSED but we still want to try to connect */
  531. /* Thus use a loop and retry until timeout is reached */
  532. /* Get a socket */
  533. if(clientsockfd <= 0) {
  534. clientsockfd = UA_socket(tcpConnection->server->ai_family,
  535. tcpConnection->server->ai_socktype,
  536. tcpConnection->server->ai_protocol);
  537. connection->sockfd = (UA_Int32)clientsockfd; /* cast for win32 */
  538. }
  539. if(clientsockfd == UA_INVALID_SOCKET) {
  540. UA_LOG_WARNING(&config->logger, UA_LOGCATEGORY_NETWORK,
  541. "Could not create client socket: %s", strerror(UA_ERRNO));
  542. ClientNetworkLayerTCP_close(connection);
  543. return UA_STATUSCODE_BADDISCONNECT;
  544. }
  545. /* Non blocking connect to be able to timeout */
  546. if(UA_socket_set_nonblocking(clientsockfd) != UA_STATUSCODE_GOOD) {
  547. UA_LOG_WARNING(&config->logger, UA_LOGCATEGORY_NETWORK,
  548. "Could not set the client socket to nonblocking");
  549. ClientNetworkLayerTCP_close(connection);
  550. return UA_STATUSCODE_BADDISCONNECT;
  551. }
  552. /* Non blocking connect */
  553. int error = UA_connect(clientsockfd, tcpConnection->server->ai_addr,
  554. tcpConnection->server->ai_addrlen);
  555. if ((error == -1) && (UA_ERRNO != UA_ERR_CONNECTION_PROGRESS)) {
  556. ClientNetworkLayerTCP_close(connection);
  557. UA_LOG_WARNING(&config->logger, UA_LOGCATEGORY_NETWORK,
  558. "Connection to failed with error: %s", strerror(UA_ERRNO));
  559. return UA_STATUSCODE_BADDISCONNECT;
  560. }
  561. /* Use select to wait and check if connected */
  562. if (error == -1 && (UA_ERRNO == UA_ERR_CONNECTION_PROGRESS)) {
  563. /* connection in progress. Wait until connected using select */
  564. UA_UInt32 timeSinceStart = (UA_UInt32)
  565. ((UA_Double) (UA_DateTime_nowMonotonic() - connStart) / UA_DATETIME_MSEC);
  566. #ifdef _OS9000
  567. /* OS-9 can't use select for checking write sockets.
  568. * Therefore, we need to use connect until success or failed
  569. */
  570. UA_UInt32 timeout_usec = (tcpConnection->timeout - timeSinceStart)
  571. * 1000;
  572. int resultsize = 0;
  573. do {
  574. u_int32 time = 0x80000001;
  575. signal_code sig;
  576. timeout_usec -= 1000000/256; // Sleep 1/256 second
  577. if (timeout_usec < 0)
  578. break;
  579. _os_sleep(&time,&sig);
  580. error = connect(clientsockfd, tcpConnection->server->ai_addr,
  581. tcpConnection->server->ai_addrlen);
  582. if ((error == -1 && UA_ERRNO == EISCONN) || (error == 0))
  583. resultsize = 1;
  584. if (error == -1 && UA_ERRNO != EALREADY && UA_ERRNO != EINPROGRESS)
  585. break;
  586. }
  587. while(resultsize == 0);
  588. #else
  589. fd_set fdset;
  590. FD_ZERO(&fdset);
  591. UA_fd_set(clientsockfd, &fdset);
  592. UA_UInt32 timeout_usec = (tcpConnection->timeout - timeSinceStart)
  593. * 1000;
  594. struct timeval tmptv = { (long int) (timeout_usec / 1000000),
  595. (int) (timeout_usec % 1000000) };
  596. int resultsize = UA_select((UA_Int32) (clientsockfd + 1), NULL, &fdset,
  597. NULL, &tmptv);
  598. #endif
  599. if (resultsize == 1) {
  600. /* Windows does not have any getsockopt equivalent and it is not needed there */
  601. #ifdef _WIN32
  602. connection->sockfd = clientsockfd;
  603. connection->state = UA_CONNECTION_ESTABLISHED;
  604. return UA_STATUSCODE_GOOD;
  605. #else
  606. OPTVAL_TYPE so_error;
  607. socklen_t len = sizeof so_error;
  608. int ret = UA_getsockopt(clientsockfd, SOL_SOCKET, SO_ERROR, &so_error,
  609. &len);
  610. if (ret != 0 || so_error != 0) {
  611. /* on connection refused we should still try to connect */
  612. /* connection refused happens on localhost or local ip without timeout */
  613. if (so_error != ECONNREFUSED) {
  614. // general error
  615. ClientNetworkLayerTCP_close(connection);
  616. UA_LOG_WARNING(&config->logger, UA_LOGCATEGORY_NETWORK,
  617. "Connection to failed with error: %s",
  618. strerror(ret == 0 ? so_error : UA_ERRNO));
  619. return UA_STATUSCODE_BADDISCONNECT;
  620. }
  621. /* wait until we try a again. Do not make this too small, otherwise the
  622. * timeout is somehow wrong */
  623. } else {
  624. connection->state = UA_CONNECTION_ESTABLISHED;
  625. return UA_STATUSCODE_GOOD;
  626. }
  627. #endif
  628. }
  629. } else {
  630. connection->state = UA_CONNECTION_ESTABLISHED;
  631. return UA_STATUSCODE_GOOD;
  632. }
  633. #ifdef SO_NOSIGPIPE
  634. int val = 1;
  635. int sso_result = setsockopt(connection->sockfd, SOL_SOCKET,
  636. SO_NOSIGPIPE, (void*)&val, sizeof(val));
  637. if(sso_result < 0)
  638. UA_LOG_WARNING(&config->logger, UA_LOGCATEGORY_NETWORK,
  639. "Couldn't set SO_NOSIGPIPE");
  640. #endif
  641. return UA_STATUSCODE_GOOD;
  642. }
  643. UA_Connection
  644. UA_ClientConnectionTCP_init(UA_ConnectionConfig config, const UA_String endpointUrl,
  645. UA_UInt32 timeout, UA_Logger *logger) {
  646. UA_Connection connection;
  647. memset(&connection, 0, sizeof(UA_Connection));
  648. connection.state = UA_CONNECTION_OPENING;
  649. connection.config = config;
  650. connection.send = connection_write;
  651. connection.recv = connection_recv;
  652. connection.close = ClientNetworkLayerTCP_close;
  653. connection.free = ClientNetworkLayerTCP_free;
  654. connection.getSendBuffer = connection_getsendbuffer;
  655. connection.releaseSendBuffer = connection_releasesendbuffer;
  656. connection.releaseRecvBuffer = connection_releaserecvbuffer;
  657. TCPClientConnection *tcpClientConnection = (TCPClientConnection*) UA_malloc(
  658. sizeof(TCPClientConnection));
  659. connection.handle = (void*) tcpClientConnection;
  660. tcpClientConnection->timeout = timeout;
  661. UA_String hostnameString = UA_STRING_NULL;
  662. UA_String pathString = UA_STRING_NULL;
  663. UA_UInt16 port = 0;
  664. char hostname[512];
  665. tcpClientConnection->connStart = UA_DateTime_nowMonotonic();
  666. UA_StatusCode parse_retval = UA_parseEndpointUrl(&endpointUrl,
  667. &hostnameString, &port, &pathString);
  668. if (parse_retval != UA_STATUSCODE_GOOD || hostnameString.length > 511) {
  669. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  670. "Server url is invalid: %.*s",
  671. (int)endpointUrl.length, endpointUrl.data);
  672. connection.state = UA_CONNECTION_CLOSED;
  673. return connection;
  674. }
  675. memcpy(hostname, hostnameString.data, hostnameString.length);
  676. hostname[hostnameString.length] = 0;
  677. if (port == 0) {
  678. port = 4840;
  679. UA_LOG_INFO(logger, UA_LOGCATEGORY_NETWORK,
  680. "No port defined, using default port %d", port);
  681. }
  682. memset(&tcpClientConnection->hints, 0, sizeof(tcpClientConnection->hints));
  683. tcpClientConnection->hints.ai_family = AF_UNSPEC;
  684. tcpClientConnection->hints.ai_socktype = SOCK_STREAM;
  685. char portStr[6];
  686. UA_snprintf(portStr, 6, "%d", port);
  687. int error = UA_getaddrinfo(hostname, portStr, &tcpClientConnection->hints,
  688. &tcpClientConnection->server);
  689. if (error != 0 || !tcpClientConnection->server) {
  690. UA_LOG_SOCKET_ERRNO_GAI_WRAP(UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  691. "DNS lookup of %s failed with error %s", hostname, errno_str));
  692. connection.state = UA_CONNECTION_CLOSED;
  693. return connection;
  694. }
  695. return connection;
  696. }
  697. UA_Connection
  698. UA_ClientConnectionTCP(UA_ConnectionConfig config, const UA_String endpointUrl,
  699. UA_UInt32 timeout, UA_Logger *logger) {
  700. UA_initialize_architecture_network();
  701. UA_Connection connection;
  702. memset(&connection, 0, sizeof(UA_Connection));
  703. connection.state = UA_CONNECTION_CLOSED;
  704. connection.config = config;
  705. connection.send = connection_write;
  706. connection.recv = connection_recv;
  707. connection.close = ClientNetworkLayerTCP_close;
  708. connection.free = ClientNetworkLayerTCP_free;
  709. connection.getSendBuffer = connection_getsendbuffer;
  710. connection.releaseSendBuffer = connection_releasesendbuffer;
  711. connection.releaseRecvBuffer = connection_releaserecvbuffer;
  712. connection.handle = NULL;
  713. UA_String hostnameString = UA_STRING_NULL;
  714. UA_String pathString = UA_STRING_NULL;
  715. UA_UInt16 port = 0;
  716. char hostname[512];
  717. UA_StatusCode parse_retval =
  718. UA_parseEndpointUrl(&endpointUrl, &hostnameString, &port, &pathString);
  719. if(parse_retval != UA_STATUSCODE_GOOD || hostnameString.length > 511) {
  720. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  721. "Server url is invalid: %.*s",
  722. (int)endpointUrl.length, endpointUrl.data);
  723. return connection;
  724. }
  725. memcpy(hostname, hostnameString.data, hostnameString.length);
  726. hostname[hostnameString.length] = 0;
  727. if(port == 0) {
  728. port = 4840;
  729. UA_LOG_INFO(logger, UA_LOGCATEGORY_NETWORK,
  730. "No port defined, using default port %d", port);
  731. }
  732. struct addrinfo hints, *server;
  733. memset(&hints, 0, sizeof(hints));
  734. hints.ai_family = AF_UNSPEC;
  735. hints.ai_socktype = SOCK_STREAM;
  736. hints.ai_protocol = IPPROTO_TCP;
  737. char portStr[6];
  738. UA_snprintf(portStr, 6, "%d", port);
  739. int error = UA_getaddrinfo(hostname, portStr, &hints, &server);
  740. if(error != 0 || !server) {
  741. UA_LOG_SOCKET_ERRNO_GAI_WRAP(UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  742. "DNS lookup of %s failed with error %s", hostname, errno_str));
  743. return connection;
  744. }
  745. UA_Boolean connected = false;
  746. UA_DateTime dtTimeout = timeout * UA_DATETIME_MSEC;
  747. UA_DateTime connStart = UA_DateTime_nowMonotonic();
  748. UA_SOCKET clientsockfd;
  749. /* On linux connect may immediately return with ECONNREFUSED but we still
  750. * want to try to connect. So use a loop and retry until timeout is
  751. * reached. */
  752. do {
  753. /* Get a socket */
  754. clientsockfd = UA_socket(server->ai_family,
  755. server->ai_socktype,
  756. server->ai_protocol);
  757. if(clientsockfd == UA_INVALID_SOCKET) {
  758. UA_LOG_SOCKET_ERRNO_WRAP(UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  759. "Could not create client socket: %s", errno_str));
  760. UA_freeaddrinfo(server);
  761. return connection;
  762. }
  763. connection.state = UA_CONNECTION_OPENING;
  764. /* Connect to the server */
  765. connection.sockfd = clientsockfd;
  766. /* Non blocking connect to be able to timeout */
  767. if (UA_socket_set_nonblocking(clientsockfd) != UA_STATUSCODE_GOOD) {
  768. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  769. "Could not set the client socket to nonblocking");
  770. ClientNetworkLayerTCP_close(&connection);
  771. UA_freeaddrinfo(server);
  772. return connection;
  773. }
  774. /* Non blocking connect */
  775. error = UA_connect(clientsockfd, server->ai_addr, (socklen_t)server->ai_addrlen);
  776. if ((error == -1) && (UA_ERRNO != UA_ERR_CONNECTION_PROGRESS)) {
  777. ClientNetworkLayerTCP_close(&connection);
  778. UA_LOG_SOCKET_ERRNO_WRAP(
  779. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  780. "Connection to %.*s failed with error: %s",
  781. (int)endpointUrl.length, endpointUrl.data, errno_str));
  782. UA_freeaddrinfo(server);
  783. return connection;
  784. }
  785. /* Use select to wait and check if connected */
  786. if (error == -1 && (UA_ERRNO == UA_ERR_CONNECTION_PROGRESS)) {
  787. /* connection in progress. Wait until connected using select */
  788. UA_DateTime timeSinceStart = UA_DateTime_nowMonotonic() - connStart;
  789. if(timeSinceStart > dtTimeout)
  790. break;
  791. #ifdef _OS9000
  792. /* OS-9 can't use select for checking write sockets.
  793. * Therefore, we need to use connect until success or failed
  794. */
  795. UA_DateTime timeout_usec = (dtTimeout - timeSinceStart) / UA_DATETIME_USEC;
  796. int resultsize = 0;
  797. do {
  798. u_int32 time = 0x80000001;
  799. signal_code sig;
  800. timeout_usec -= 1000000/256; // Sleep 1/256 second
  801. if (timeout_usec < 0)
  802. break;
  803. _os_sleep(&time,&sig);
  804. error = connect(clientsockfd, server->ai_addr, server->ai_addrlen);
  805. if ((error == -1 && UA_ERRNO == EISCONN) || (error == 0))
  806. resultsize = 1;
  807. if (error == -1 && UA_ERRNO != EALREADY && UA_ERRNO != EINPROGRESS)
  808. break;
  809. }
  810. while(resultsize == 0);
  811. #else
  812. fd_set fdset;
  813. FD_ZERO(&fdset);
  814. UA_fd_set(clientsockfd, &fdset);
  815. UA_DateTime timeout_usec = (dtTimeout - timeSinceStart) / UA_DATETIME_USEC;
  816. struct timeval tmptv = {(long int) (timeout_usec / 1000000),
  817. (int) (timeout_usec % 1000000)};
  818. int resultsize = UA_select((UA_Int32)(clientsockfd + 1), NULL, &fdset, NULL, &tmptv);
  819. #endif
  820. if(resultsize == 1) {
  821. #ifdef _WIN32
  822. /* Windows does not have any getsockopt equivalent and it is not
  823. * needed there */
  824. connected = true;
  825. break;
  826. #else
  827. OPTVAL_TYPE so_error;
  828. socklen_t len = sizeof so_error;
  829. int ret = UA_getsockopt(clientsockfd, SOL_SOCKET, SO_ERROR, &so_error, &len);
  830. if (ret != 0 || so_error != 0) {
  831. /* on connection refused we should still try to connect */
  832. /* connection refused happens on localhost or local ip without timeout */
  833. if (so_error != ECONNREFUSED) {
  834. ClientNetworkLayerTCP_close(&connection);
  835. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  836. "Connection to %.*s failed with error: %s",
  837. (int)endpointUrl.length, endpointUrl.data,
  838. strerror(ret == 0 ? so_error : UA_ERRNO));
  839. UA_freeaddrinfo(server);
  840. return connection;
  841. }
  842. /* wait until we try a again. Do not make this too small, otherwise the
  843. * timeout is somehow wrong */
  844. UA_sleep_ms(100);
  845. } else {
  846. connected = true;
  847. break;
  848. }
  849. #endif
  850. }
  851. } else {
  852. connected = true;
  853. break;
  854. }
  855. ClientNetworkLayerTCP_close(&connection);
  856. } while ((UA_DateTime_nowMonotonic() - connStart) < dtTimeout);
  857. UA_freeaddrinfo(server);
  858. if(!connected) {
  859. /* connection timeout */
  860. if (connection.state != UA_CONNECTION_CLOSED)
  861. ClientNetworkLayerTCP_close(&connection);
  862. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  863. "Trying to connect to %.*s timed out",
  864. (int)endpointUrl.length, endpointUrl.data);
  865. return connection;
  866. }
  867. /* We are connected. Reset socket to blocking */
  868. if(UA_socket_set_blocking(clientsockfd) != UA_STATUSCODE_GOOD) {
  869. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  870. "Could not set the client socket to blocking");
  871. ClientNetworkLayerTCP_close(&connection);
  872. return connection;
  873. }
  874. #ifdef SO_NOSIGPIPE
  875. int val = 1;
  876. int sso_result = UA_setsockopt(connection.sockfd, SOL_SOCKET,
  877. SO_NOSIGPIPE, (void*)&val, sizeof(val));
  878. if(sso_result < 0)
  879. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  880. "Couldn't set SO_NOSIGPIPE");
  881. #endif
  882. return connection;
  883. }