ua_network_tcp.c 38 KB

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