ua_network_tcp.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  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. #include "ua_architecture.h"
  11. #ifndef MSG_NOSIGNAL
  12. #define MSG_NOSIGNAL 0
  13. #endif
  14. #include "ua_network_tcp.h"
  15. #include "ua_log_stdout.h"
  16. #include "../deps/queue.h"
  17. #include <string.h> // memset
  18. #include "ua_log_socket_error.h"
  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->remoteConf.recvBufferSize)
  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. (long 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(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*)
  98. UA_malloc(connection->localConf.recvBufferSize);
  99. if(!response->data) {
  100. response->length = 0;
  101. return UA_STATUSCODE_BADOUTOFMEMORY; /* not enough memory retry */
  102. }
  103. /* Get the received packet(s) */
  104. ssize_t ret = ua_recv(connection->sockfd, (char*)response->data,
  105. connection->localConf.recvBufferSize, 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. /* Set the length of the received buffer */
  122. response->length = (size_t)ret;
  123. return UA_STATUSCODE_GOOD;
  124. }
  125. /***************************/
  126. /* Server NetworkLayer TCP */
  127. /***************************/
  128. #define MAXBACKLOG 100
  129. #define NOHELLOTIMEOUT 120000 /* timeout in ms before close the connection
  130. * if server does not receive Hello Message */
  131. typedef struct ConnectionEntry {
  132. UA_Connection connection;
  133. LIST_ENTRY(ConnectionEntry) pointers;
  134. } ConnectionEntry;
  135. typedef struct {
  136. UA_Logger logger;
  137. UA_ConnectionConfig conf;
  138. UA_UInt16 port;
  139. UA_SOCKET serverSockets[FD_SETSIZE];
  140. UA_UInt16 serverSocketsSize;
  141. LIST_HEAD(, ConnectionEntry) connections;
  142. } ServerNetworkLayerTCP;
  143. static void
  144. ServerNetworkLayerTCP_freeConnection(UA_Connection *connection) {
  145. UA_Connection_deleteMembers(connection);
  146. UA_free(connection);
  147. }
  148. /* This performs only 'shutdown'. 'close' is called when the shutdown
  149. * socket is returned from select. */
  150. static void
  151. ServerNetworkLayerTCP_close(UA_Connection *connection) {
  152. if (connection->state == UA_CONNECTION_CLOSED)
  153. return;
  154. ua_shutdown((UA_SOCKET)connection->sockfd, 2);
  155. connection->state = UA_CONNECTION_CLOSED;
  156. }
  157. static UA_StatusCode
  158. ServerNetworkLayerTCP_add(ServerNetworkLayerTCP *layer, UA_Int32 newsockfd,
  159. struct sockaddr_storage *remote) {
  160. /* Set nonblocking */
  161. socket_set_nonblocking(newsockfd);
  162. /* Do not merge packets on the socket (disable Nagle's algorithm) */
  163. int dummy = 1;
  164. if(ua_setsockopt(newsockfd, IPPROTO_TCP, TCP_NODELAY,
  165. (const char *)&dummy, sizeof(dummy)) < 0) {
  166. UA_LOG_SOCKET_ERRNO_WRAP(
  167. UA_LOG_ERROR(layer->logger, UA_LOGCATEGORY_NETWORK,
  168. "Cannot set socket option TCP_NODELAY. Error: %s",
  169. errno_str));
  170. return UA_STATUSCODE_BADUNEXPECTEDERROR;
  171. }
  172. #if !defined(UA_FREERTOS)
  173. /* Get the peer name for logging */
  174. char remote_name[100];
  175. int res = getnameinfo((struct sockaddr*)remote,
  176. sizeof(struct sockaddr_storage),
  177. remote_name, sizeof(remote_name),
  178. NULL, 0, NI_NUMERICHOST);
  179. if(res == 0) {
  180. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  181. "Connection %i | New connection over TCP from %s",
  182. (int)newsockfd, remote_name);
  183. } else {
  184. UA_LOG_SOCKET_ERRNO_WRAP(UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  185. "Connection %i | New connection over TCP, "
  186. "getnameinfo failed with error: %s",
  187. (int)newsockfd, errno_str));
  188. }
  189. #endif
  190. /* Allocate and initialize the connection */
  191. ConnectionEntry *e = (ConnectionEntry*)UA_malloc(sizeof(ConnectionEntry));
  192. if(!e){
  193. ua_close(newsockfd);
  194. return UA_STATUSCODE_BADOUTOFMEMORY;
  195. }
  196. UA_Connection *c = &e->connection;
  197. memset(c, 0, sizeof(UA_Connection));
  198. c->sockfd = newsockfd;
  199. c->handle = layer;
  200. c->localConf = layer->conf;
  201. c->remoteConf = layer->conf;
  202. c->send = connection_write;
  203. c->close = ServerNetworkLayerTCP_close;
  204. c->free = ServerNetworkLayerTCP_freeConnection;
  205. c->getSendBuffer = connection_getsendbuffer;
  206. c->releaseSendBuffer = connection_releasesendbuffer;
  207. c->releaseRecvBuffer = connection_releaserecvbuffer;
  208. c->state = UA_CONNECTION_OPENING;
  209. c->openingDate = UA_DateTime_nowMonotonic();
  210. /* Add to the linked list */
  211. LIST_INSERT_HEAD(&layer->connections, e, pointers);
  212. return UA_STATUSCODE_GOOD;
  213. }
  214. static void
  215. addServerSocket(ServerNetworkLayerTCP *layer, struct addrinfo *ai) {
  216. /* Create the server socket */
  217. UA_SOCKET newsock = ua_socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
  218. if(newsock == UA_INVALID_SOCKET)
  219. {
  220. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  221. "Error opening the server socket");
  222. return;
  223. }
  224. /* Some Linux distributions have net.ipv6.bindv6only not activated. So
  225. * sockets can double-bind to IPv4 and IPv6. This leads to problems. Use
  226. * AF_INET6 sockets only for IPv6. */
  227. int optval = 1;
  228. #if UA_IPV6
  229. if(ai->ai_family == AF_INET6 &&
  230. ua_setsockopt(newsock, IPPROTO_IPV6, IPV6_V6ONLY,
  231. (const char*)&optval, sizeof(optval)) == -1) {
  232. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  233. "Could not set an IPv6 socket to IPv6 only");
  234. ua_close(newsock);
  235. return;
  236. }
  237. #endif
  238. if(ua_setsockopt(newsock, SOL_SOCKET, SO_REUSEADDR,
  239. (const char *)&optval, sizeof(optval)) == -1) {
  240. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  241. "Could not make the socket reusable");
  242. ua_close(newsock);
  243. return;
  244. }
  245. if(socket_set_nonblocking(newsock) != UA_STATUSCODE_GOOD) {
  246. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  247. "Could not set the server socket to nonblocking");
  248. ua_close(newsock);
  249. return;
  250. }
  251. /* Bind socket to address */
  252. if(ua_bind(newsock, ai->ai_addr, (socklen_t)ai->ai_addrlen) < 0) {
  253. UA_LOG_SOCKET_ERRNO_WRAP(
  254. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  255. "Error binding a server socket: %s", errno_str));
  256. ua_close(newsock);
  257. return;
  258. }
  259. /* Start listening */
  260. if(ua_listen(newsock, MAXBACKLOG) < 0) {
  261. UA_LOG_SOCKET_ERRNO_WRAP(
  262. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  263. "Error listening on server socket: %s", errno_str));
  264. ua_close(newsock);
  265. return;
  266. }
  267. layer->serverSockets[layer->serverSocketsSize] = newsock;
  268. layer->serverSocketsSize++;
  269. }
  270. static UA_StatusCode
  271. ServerNetworkLayerTCP_start(UA_ServerNetworkLayer *nl, const UA_String *customHostname) {
  272. ua_initialize_architecture_network();
  273. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  274. /* Get the discovery url from the hostname */
  275. UA_String du = UA_STRING_NULL;
  276. if (customHostname->length) {
  277. char discoveryUrl[256];
  278. du.length = (size_t)ua_snprintf(discoveryUrl, 255, "opc.tcp://%.*s:%d/",
  279. (int)customHostname->length,
  280. customHostname->data,
  281. layer->port);
  282. du.data = (UA_Byte*)discoveryUrl;
  283. }else{
  284. char hostname[256];
  285. if(gethostname(hostname, 255) == 0) {
  286. char discoveryUrl[256];
  287. du.length = (size_t)ua_snprintf(discoveryUrl, 255, "opc.tcp://%s:%d/",
  288. hostname, layer->port);
  289. du.data = (UA_Byte*)discoveryUrl;
  290. }
  291. }
  292. UA_String_copy(&du, &nl->discoveryUrl);
  293. /* Get addrinfo of the server and create server sockets */
  294. char portno[6];
  295. ua_snprintf(portno, 6, "%d", layer->port);
  296. struct addrinfo hints, *res;
  297. memset(&hints, 0, sizeof hints);
  298. hints.ai_family = AF_UNSPEC;
  299. hints.ai_socktype = SOCK_STREAM;
  300. hints.ai_flags = AI_PASSIVE;
  301. hints.ai_protocol = IPPROTO_TCP;
  302. if(ua_getaddrinfo(NULL, portno, &hints, &res) != 0)
  303. return UA_STATUSCODE_BADINTERNALERROR;
  304. /* There might be serveral addrinfos (for different network cards,
  305. * IPv4/IPv6). Add a server socket for all of them. */
  306. struct addrinfo *ai = res;
  307. for(layer->serverSocketsSize = 0;
  308. layer->serverSocketsSize < FD_SETSIZE && ai != NULL;
  309. ai = ai->ai_next)
  310. addServerSocket(layer, ai);
  311. ua_freeaddrinfo(res);
  312. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  313. "TCP network layer listening on %.*s",
  314. (int)nl->discoveryUrl.length, nl->discoveryUrl.data);
  315. return UA_STATUSCODE_GOOD;
  316. }
  317. /* After every select, reset the sockets to listen on */
  318. static UA_Int32
  319. setFDSet(ServerNetworkLayerTCP *layer, fd_set *fdset) {
  320. FD_ZERO(fdset);
  321. UA_Int32 highestfd = 0;
  322. for(UA_UInt16 i = 0; i < layer->serverSocketsSize; i++) {
  323. UA_fd_set(layer->serverSockets[i], fdset);
  324. if(layer->serverSockets[i] > highestfd)
  325. highestfd = layer->serverSockets[i];
  326. }
  327. ConnectionEntry *e;
  328. LIST_FOREACH(e, &layer->connections, pointers) {
  329. UA_fd_set(e->connection.sockfd, fdset);
  330. if(e->connection.sockfd > highestfd)
  331. highestfd = e->connection.sockfd;
  332. }
  333. return highestfd;
  334. }
  335. static UA_StatusCode
  336. ServerNetworkLayerTCP_listen(UA_ServerNetworkLayer *nl, UA_Server *server,
  337. UA_UInt16 timeout) {
  338. /* Every open socket can generate two jobs */
  339. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  340. if (layer->serverSocketsSize == 0)
  341. return UA_STATUSCODE_GOOD;
  342. /* Listen on open sockets (including the server) */
  343. fd_set fdset, errset;
  344. UA_Int32 highestfd = setFDSet(layer, &fdset);
  345. setFDSet(layer, &errset);
  346. struct timeval tmptv = {0, timeout * 1000};
  347. if (ua_select(highestfd+1, &fdset, NULL, &errset, &tmptv) < 0) {
  348. UA_LOG_SOCKET_ERRNO_WRAP(
  349. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  350. "Socket select failed with %s", errno_str));
  351. // we will retry, so do not return bad
  352. return UA_STATUSCODE_GOOD;
  353. }
  354. /* Accept new connections via the server sockets */
  355. for(UA_UInt16 i = 0; i < layer->serverSocketsSize; i++) {
  356. if(!UA_fd_isset(layer->serverSockets[i], &fdset))
  357. continue;
  358. struct sockaddr_storage remote;
  359. socklen_t remote_size = sizeof(remote);
  360. UA_SOCKET newsockfd = ua_accept((UA_SOCKET)layer->serverSockets[i],
  361. (struct sockaddr*)&remote, &remote_size);
  362. if(newsockfd == UA_INVALID_SOCKET)
  363. continue;
  364. UA_LOG_TRACE(layer->logger, UA_LOGCATEGORY_NETWORK,
  365. "Connection %i | New TCP connection on server socket %i",
  366. (int)newsockfd, layer->serverSockets[i]);
  367. ServerNetworkLayerTCP_add(layer, (UA_Int32)newsockfd, &remote);
  368. }
  369. /* Read from established sockets */
  370. ConnectionEntry *e, *e_tmp;
  371. UA_DateTime now = UA_DateTime_nowMonotonic();
  372. LIST_FOREACH_SAFE(e, &layer->connections, pointers, e_tmp) {
  373. if ((e->connection.state == UA_CONNECTION_OPENING) &&
  374. (now > (e->connection.openingDate + (NOHELLOTIMEOUT * UA_DATETIME_MSEC)))){
  375. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  376. "Connection %i | Closed by the server (no Hello Message)",
  377. e->connection.sockfd);
  378. LIST_REMOVE(e, pointers);
  379. ua_close(e->connection.sockfd);
  380. UA_Server_removeConnection(server, &e->connection);
  381. continue;
  382. }
  383. if(!UA_fd_isset(e->connection.sockfd, &errset) &&
  384. !UA_fd_isset(e->connection.sockfd, &fdset))
  385. continue;
  386. UA_LOG_TRACE(layer->logger, UA_LOGCATEGORY_NETWORK,
  387. "Connection %i | Activity on the socket",
  388. e->connection.sockfd);
  389. UA_ByteString buf = UA_BYTESTRING_NULL;
  390. UA_StatusCode retval = connection_recv(&e->connection, &buf, 0);
  391. if(retval == UA_STATUSCODE_GOOD) {
  392. /* Process packets */
  393. UA_Server_processBinaryMessage(server, &e->connection, &buf);
  394. connection_releaserecvbuffer(&e->connection, &buf);
  395. } else if(retval == UA_STATUSCODE_BADCONNECTIONCLOSED) {
  396. /* The socket is shutdown but not closed */
  397. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  398. "Connection %i | Closed",
  399. e->connection.sockfd);
  400. LIST_REMOVE(e, pointers);
  401. ua_close(e->connection.sockfd);
  402. UA_Server_removeConnection(server, &e->connection);
  403. }
  404. }
  405. return UA_STATUSCODE_GOOD;
  406. }
  407. static void
  408. ServerNetworkLayerTCP_stop(UA_ServerNetworkLayer *nl, UA_Server *server) {
  409. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  410. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  411. "Shutting down the TCP network layer");
  412. /* Close the server sockets */
  413. for(UA_UInt16 i = 0; i < layer->serverSocketsSize; i++) {
  414. ua_shutdown(layer->serverSockets[i], 2);
  415. ua_close(layer->serverSockets[i]);
  416. }
  417. layer->serverSocketsSize = 0;
  418. /* Close open connections */
  419. ConnectionEntry *e;
  420. LIST_FOREACH(e, &layer->connections, pointers)
  421. ServerNetworkLayerTCP_close(&e->connection);
  422. /* Run recv on client sockets. This picks up the closed sockets and frees
  423. * the connection. */
  424. ServerNetworkLayerTCP_listen(nl, server, 0);
  425. ua_deinitialize_architecture_network();
  426. }
  427. /* run only when the server is stopped */
  428. static void
  429. ServerNetworkLayerTCP_deleteMembers(UA_ServerNetworkLayer *nl) {
  430. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  431. UA_String_deleteMembers(&nl->discoveryUrl);
  432. /* Hard-close and remove remaining connections. The server is no longer
  433. * running. So this is safe. */
  434. ConnectionEntry *e, *e_tmp;
  435. LIST_FOREACH_SAFE(e, &layer->connections, pointers, e_tmp) {
  436. LIST_REMOVE(e, pointers);
  437. ua_close(e->connection.sockfd);
  438. UA_free(e);
  439. }
  440. /* Free the layer */
  441. UA_free(layer);
  442. }
  443. UA_ServerNetworkLayer
  444. UA_ServerNetworkLayerTCP(UA_ConnectionConfig conf, UA_UInt16 port, UA_Logger logger) {
  445. UA_ServerNetworkLayer nl;
  446. memset(&nl, 0, sizeof(UA_ServerNetworkLayer));
  447. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP*)
  448. UA_calloc(1,sizeof(ServerNetworkLayerTCP));
  449. if(!layer)
  450. return nl;
  451. layer->logger = (logger != NULL ? logger : UA_Log_Stdout);
  452. layer->conf = conf;
  453. layer->port = port;
  454. nl.handle = layer;
  455. nl.start = ServerNetworkLayerTCP_start;
  456. nl.listen = ServerNetworkLayerTCP_listen;
  457. nl.stop = ServerNetworkLayerTCP_stop;
  458. nl.deleteMembers = ServerNetworkLayerTCP_deleteMembers;
  459. return nl;
  460. }
  461. /***************************/
  462. /* Client NetworkLayer TCP */
  463. /***************************/
  464. static void
  465. ClientNetworkLayerTCP_close(UA_Connection *connection) {
  466. if (connection->state == UA_CONNECTION_CLOSED)
  467. return;
  468. ua_shutdown(connection->sockfd, 2);
  469. ua_close(connection->sockfd);
  470. connection->state = UA_CONNECTION_CLOSED;
  471. }
  472. UA_Connection
  473. UA_ClientConnectionTCP(UA_ConnectionConfig conf,
  474. const char *endpointUrl, const UA_UInt32 timeout,
  475. UA_Logger logger) {
  476. ua_initialize_architecture_network();
  477. if(logger == NULL) {
  478. logger = UA_Log_Stdout;
  479. }
  480. UA_Connection connection;
  481. memset(&connection, 0, sizeof(UA_Connection));
  482. connection.state = UA_CONNECTION_CLOSED;
  483. connection.localConf = conf;
  484. connection.remoteConf = conf;
  485. connection.send = connection_write;
  486. connection.recv = connection_recv;
  487. connection.close = ClientNetworkLayerTCP_close;
  488. connection.free = NULL;
  489. connection.getSendBuffer = connection_getsendbuffer;
  490. connection.releaseSendBuffer = connection_releasesendbuffer;
  491. connection.releaseRecvBuffer = connection_releaserecvbuffer;
  492. UA_String endpointUrlString = UA_STRING((char*)(uintptr_t)endpointUrl);
  493. UA_String hostnameString = UA_STRING_NULL;
  494. UA_String pathString = UA_STRING_NULL;
  495. UA_UInt16 port = 0;
  496. char hostname[512];
  497. UA_StatusCode parse_retval =
  498. UA_parseEndpointUrl(&endpointUrlString, &hostnameString,
  499. &port, &pathString);
  500. if(parse_retval != UA_STATUSCODE_GOOD || hostnameString.length > 511) {
  501. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  502. "Server url is invalid: %s", endpointUrl);
  503. return connection;
  504. }
  505. memcpy(hostname, hostnameString.data, hostnameString.length);
  506. hostname[hostnameString.length] = 0;
  507. if(port == 0) {
  508. port = 4840;
  509. UA_LOG_INFO(logger, UA_LOGCATEGORY_NETWORK,
  510. "No port defined, using default port %d", port);
  511. }
  512. struct addrinfo hints, *server;
  513. memset(&hints, 0, sizeof(hints));
  514. hints.ai_family = AF_UNSPEC;
  515. hints.ai_socktype = SOCK_STREAM;
  516. hints.ai_protocol = IPPROTO_TCP;
  517. char portStr[6];
  518. ua_snprintf(portStr, 6, "%d", port);
  519. int error = ua_getaddrinfo(hostname, portStr, &hints, &server);
  520. if(error != 0 || !server) {
  521. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  522. "DNS lookup of %s failed with error %s",
  523. hostname, ua_translate_error(error));
  524. return connection;
  525. }
  526. UA_Boolean connected = UA_FALSE;
  527. UA_DateTime dtTimeout = timeout * UA_DATETIME_MSEC;
  528. UA_DateTime connStart = UA_DateTime_nowMonotonic();
  529. UA_SOCKET clientsockfd;
  530. /* On linux connect may immediately return with ECONNREFUSED but we still
  531. * want to try to connect. So use a loop and retry until timeout is
  532. * reached. */
  533. do {
  534. /* Get a socket */
  535. clientsockfd = ua_socket(server->ai_family,
  536. server->ai_socktype,
  537. server->ai_protocol);
  538. if(clientsockfd == UA_INVALID_SOCKET) {
  539. UA_LOG_SOCKET_ERRNO_WRAP(UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  540. "Could not create client socket: %s", errno_str));
  541. ua_freeaddrinfo(server);
  542. return connection;
  543. }
  544. connection.state = UA_CONNECTION_OPENING;
  545. /* Connect to the server */
  546. connection.sockfd = clientsockfd;
  547. /* Non blocking connect to be able to timeout */
  548. if (socket_set_nonblocking(clientsockfd) != UA_STATUSCODE_GOOD) {
  549. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  550. "Could not set the client socket to nonblocking");
  551. ClientNetworkLayerTCP_close(&connection);
  552. ua_freeaddrinfo(server);
  553. return connection;
  554. }
  555. /* Non blocking connect */
  556. error = ua_connect(clientsockfd, server->ai_addr, (socklen_t)server->ai_addrlen);
  557. if ((error == -1) && (UA_ERRNO != UA_ERR_CONNECTION_PROGRESS)) {
  558. ClientNetworkLayerTCP_close(&connection);
  559. UA_LOG_SOCKET_ERRNO_WRAP(
  560. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  561. "Connection to %s failed with error: %s",
  562. endpointUrl, errno_str));
  563. ua_freeaddrinfo(server);
  564. return connection;
  565. }
  566. /* Use select to wait and check if connected */
  567. if (error == -1 && (UA_ERRNO == UA_ERR_CONNECTION_PROGRESS)) {
  568. /* connection in progress. Wait until connected using select */
  569. UA_DateTime timeSinceStart = UA_DateTime_nowMonotonic() - connStart;
  570. if(timeSinceStart > dtTimeout)
  571. break;
  572. fd_set fdset;
  573. FD_ZERO(&fdset);
  574. UA_fd_set(clientsockfd, &fdset);
  575. UA_DateTime timeout_usec = (dtTimeout - timeSinceStart) / UA_DATETIME_USEC;
  576. struct timeval tmptv = {(long int) (timeout_usec / 1000000),
  577. (long int) (timeout_usec % 1000000)};
  578. int resultsize = ua_select(clientsockfd + 1, NULL, &fdset, NULL, &tmptv);
  579. if(resultsize == 1) {
  580. #ifdef _WIN32
  581. /* Windows does not have any getsockopt equivalent and it is not
  582. * needed there */
  583. connected = true;
  584. break;
  585. #else
  586. OPTVAL_TYPE so_error;
  587. socklen_t len = sizeof so_error;
  588. int ret = ua_getsockopt(clientsockfd, SOL_SOCKET, SO_ERROR, &so_error, &len);
  589. if (ret != 0 || so_error != 0) {
  590. /* on connection refused we should still try to connect */
  591. /* connection refused happens on localhost or local ip without timeout */
  592. if (so_error != ECONNREFUSED) {
  593. ClientNetworkLayerTCP_close(&connection);
  594. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  595. "Connection to %s failed with error: %s",
  596. endpointUrl, strerror(ret == 0 ? so_error : UA_ERRNO));
  597. ua_freeaddrinfo(server);
  598. return connection;
  599. }
  600. /* wait until we try a again. Do not make this too small, otherwise the
  601. * timeout is somehow wrong */
  602. UA_sleep_ms(100);
  603. } else {
  604. connected = true;
  605. break;
  606. }
  607. #endif
  608. }
  609. } else {
  610. connected = true;
  611. break;
  612. }
  613. ClientNetworkLayerTCP_close(&connection);
  614. } while ((UA_DateTime_nowMonotonic() - connStart) < dtTimeout);
  615. ua_freeaddrinfo(server);
  616. if(!connected) {
  617. /* connection timeout */
  618. if (connection.state != UA_CONNECTION_CLOSED)
  619. ClientNetworkLayerTCP_close(&connection);
  620. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  621. "Trying to connect to %s timed out",
  622. endpointUrl);
  623. return connection;
  624. }
  625. /* We are connected. Reset socket to blocking */
  626. if(socket_set_blocking(clientsockfd) != UA_STATUSCODE_GOOD) {
  627. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  628. "Could not set the client socket to blocking");
  629. ClientNetworkLayerTCP_close(&connection);
  630. return connection;
  631. }
  632. #ifdef SO_NOSIGPIPE
  633. int val = 1;
  634. int sso_result = ua_setsockopt(connection.sockfd, SOL_SOCKET,
  635. SO_NOSIGPIPE, (void*)&val, sizeof(val));
  636. if(sso_result < 0)
  637. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  638. "Couldn't set SO_NOSIGPIPE");
  639. #endif
  640. return connection;
  641. }