ua_network_tcp.c 27 KB

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