network_tcp.c 38 KB

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