ua_network_tcp.c 37 KB

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