ua_network_tcp.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  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_getnameinfo)
  173. /* Get the peer name for logging */
  174. char remote_name[100];
  175. int res = ua_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. #else
  190. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  191. "Connection %i | New connection over TCP",
  192. (int)newsockfd);
  193. #endif
  194. /* Allocate and initialize the connection */
  195. ConnectionEntry *e = (ConnectionEntry*)UA_malloc(sizeof(ConnectionEntry));
  196. if(!e){
  197. ua_close(newsockfd);
  198. return UA_STATUSCODE_BADOUTOFMEMORY;
  199. }
  200. UA_Connection *c = &e->connection;
  201. memset(c, 0, sizeof(UA_Connection));
  202. c->sockfd = newsockfd;
  203. c->handle = layer;
  204. c->localConf = layer->conf;
  205. c->remoteConf = layer->conf;
  206. c->send = connection_write;
  207. c->close = ServerNetworkLayerTCP_close;
  208. c->free = ServerNetworkLayerTCP_freeConnection;
  209. c->getSendBuffer = connection_getsendbuffer;
  210. c->releaseSendBuffer = connection_releasesendbuffer;
  211. c->releaseRecvBuffer = connection_releaserecvbuffer;
  212. c->state = UA_CONNECTION_OPENING;
  213. c->openingDate = UA_DateTime_nowMonotonic();
  214. /* Add to the linked list */
  215. LIST_INSERT_HEAD(&layer->connections, e, pointers);
  216. return UA_STATUSCODE_GOOD;
  217. }
  218. static void
  219. addServerSocket(ServerNetworkLayerTCP *layer, struct addrinfo *ai) {
  220. /* Create the server socket */
  221. UA_SOCKET newsock = ua_socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
  222. if(newsock == UA_INVALID_SOCKET)
  223. {
  224. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  225. "Error opening the server socket");
  226. return;
  227. }
  228. /* Some Linux distributions have net.ipv6.bindv6only not activated. So
  229. * sockets can double-bind to IPv4 and IPv6. This leads to problems. Use
  230. * AF_INET6 sockets only for IPv6. */
  231. int optval = 1;
  232. #if UA_IPV6
  233. if(ai->ai_family == AF_INET6 &&
  234. ua_setsockopt(newsock, IPPROTO_IPV6, IPV6_V6ONLY,
  235. (const char*)&optval, sizeof(optval)) == -1) {
  236. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  237. "Could not set an IPv6 socket to IPv6 only");
  238. ua_close(newsock);
  239. return;
  240. }
  241. #endif
  242. if(ua_setsockopt(newsock, SOL_SOCKET, SO_REUSEADDR,
  243. (const char *)&optval, sizeof(optval)) == -1) {
  244. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  245. "Could not make the socket reusable");
  246. ua_close(newsock);
  247. return;
  248. }
  249. if(socket_set_nonblocking(newsock) != UA_STATUSCODE_GOOD) {
  250. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  251. "Could not set the server socket to nonblocking");
  252. ua_close(newsock);
  253. return;
  254. }
  255. /* Bind socket to address */
  256. if(ua_bind(newsock, ai->ai_addr, (socklen_t)ai->ai_addrlen) < 0) {
  257. UA_LOG_SOCKET_ERRNO_WRAP(
  258. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  259. "Error binding a server socket: %s", errno_str));
  260. ua_close(newsock);
  261. return;
  262. }
  263. /* Start listening */
  264. if(ua_listen(newsock, MAXBACKLOG) < 0) {
  265. UA_LOG_SOCKET_ERRNO_WRAP(
  266. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  267. "Error listening on server socket: %s", errno_str));
  268. ua_close(newsock);
  269. return;
  270. }
  271. layer->serverSockets[layer->serverSocketsSize] = newsock;
  272. layer->serverSocketsSize++;
  273. }
  274. static UA_StatusCode
  275. ServerNetworkLayerTCP_start(UA_ServerNetworkLayer *nl, const UA_String *customHostname) {
  276. ua_initialize_architecture_network();
  277. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  278. /* Get the discovery url from the hostname */
  279. UA_String du = UA_STRING_NULL;
  280. if (customHostname->length) {
  281. char discoveryUrl[256];
  282. du.length = (size_t)ua_snprintf(discoveryUrl, 255, "opc.tcp://%.*s:%d/",
  283. (int)customHostname->length,
  284. customHostname->data,
  285. layer->port);
  286. du.data = (UA_Byte*)discoveryUrl;
  287. }else{
  288. char hostname[256];
  289. if(gethostname(hostname, 255) == 0) {
  290. char discoveryUrl[256];
  291. du.length = (size_t)ua_snprintf(discoveryUrl, 255, "opc.tcp://%s:%d/",
  292. hostname, layer->port);
  293. du.data = (UA_Byte*)discoveryUrl;
  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_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  526. "DNS lookup of %s failed with error %s",
  527. hostname, ua_translate_error(error));
  528. return connection;
  529. }
  530. UA_Boolean connected = UA_FALSE;
  531. UA_DateTime dtTimeout = timeout * UA_DATETIME_MSEC;
  532. UA_DateTime connStart = UA_DateTime_nowMonotonic();
  533. UA_SOCKET clientsockfd;
  534. /* On linux connect may immediately return with ECONNREFUSED but we still
  535. * want to try to connect. So use a loop and retry until timeout is
  536. * reached. */
  537. do {
  538. /* Get a socket */
  539. clientsockfd = ua_socket(server->ai_family,
  540. server->ai_socktype,
  541. server->ai_protocol);
  542. if(clientsockfd == UA_INVALID_SOCKET) {
  543. UA_LOG_SOCKET_ERRNO_WRAP(UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  544. "Could not create client socket: %s", errno_str));
  545. ua_freeaddrinfo(server);
  546. return connection;
  547. }
  548. connection.state = UA_CONNECTION_OPENING;
  549. /* Connect to the server */
  550. connection.sockfd = clientsockfd;
  551. /* Non blocking connect to be able to timeout */
  552. if (socket_set_nonblocking(clientsockfd) != UA_STATUSCODE_GOOD) {
  553. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  554. "Could not set the client socket to nonblocking");
  555. ClientNetworkLayerTCP_close(&connection);
  556. ua_freeaddrinfo(server);
  557. return connection;
  558. }
  559. /* Non blocking connect */
  560. error = ua_connect(clientsockfd, server->ai_addr, (socklen_t)server->ai_addrlen);
  561. if ((error == -1) && (UA_ERRNO != UA_ERR_CONNECTION_PROGRESS)) {
  562. ClientNetworkLayerTCP_close(&connection);
  563. UA_LOG_SOCKET_ERRNO_WRAP(
  564. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  565. "Connection to %s failed with error: %s",
  566. endpointUrl, errno_str));
  567. ua_freeaddrinfo(server);
  568. return connection;
  569. }
  570. /* Use select to wait and check if connected */
  571. if (error == -1 && (UA_ERRNO == UA_ERR_CONNECTION_PROGRESS)) {
  572. /* connection in progress. Wait until connected using select */
  573. UA_DateTime timeSinceStart = UA_DateTime_nowMonotonic() - connStart;
  574. if(timeSinceStart > dtTimeout)
  575. break;
  576. fd_set fdset;
  577. FD_ZERO(&fdset);
  578. UA_fd_set(clientsockfd, &fdset);
  579. UA_DateTime timeout_usec = (dtTimeout - timeSinceStart) / UA_DATETIME_USEC;
  580. struct timeval tmptv = {(long int) (timeout_usec / 1000000),
  581. (long int) (timeout_usec % 1000000)};
  582. int resultsize = ua_select(clientsockfd + 1, NULL, &fdset, NULL, &tmptv);
  583. if(resultsize == 1) {
  584. #ifdef _WIN32
  585. /* Windows does not have any getsockopt equivalent and it is not
  586. * needed there */
  587. connected = true;
  588. break;
  589. #else
  590. OPTVAL_TYPE so_error;
  591. socklen_t len = sizeof so_error;
  592. int ret = ua_getsockopt(clientsockfd, SOL_SOCKET, SO_ERROR, &so_error, &len);
  593. if (ret != 0 || so_error != 0) {
  594. /* on connection refused we should still try to connect */
  595. /* connection refused happens on localhost or local ip without timeout */
  596. if (so_error != ECONNREFUSED) {
  597. ClientNetworkLayerTCP_close(&connection);
  598. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  599. "Connection to %s failed with error: %s",
  600. endpointUrl, strerror(ret == 0 ? so_error : UA_ERRNO));
  601. ua_freeaddrinfo(server);
  602. return connection;
  603. }
  604. /* wait until we try a again. Do not make this too small, otherwise the
  605. * timeout is somehow wrong */
  606. UA_sleep_ms(100);
  607. } else {
  608. connected = true;
  609. break;
  610. }
  611. #endif
  612. }
  613. } else {
  614. connected = true;
  615. break;
  616. }
  617. ClientNetworkLayerTCP_close(&connection);
  618. } while ((UA_DateTime_nowMonotonic() - connStart) < dtTimeout);
  619. ua_freeaddrinfo(server);
  620. if(!connected) {
  621. /* connection timeout */
  622. if (connection.state != UA_CONNECTION_CLOSED)
  623. ClientNetworkLayerTCP_close(&connection);
  624. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  625. "Trying to connect to %s timed out",
  626. endpointUrl);
  627. return connection;
  628. }
  629. /* We are connected. Reset socket to blocking */
  630. if(socket_set_blocking(clientsockfd) != UA_STATUSCODE_GOOD) {
  631. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  632. "Could not set the client socket to blocking");
  633. ClientNetworkLayerTCP_close(&connection);
  634. return connection;
  635. }
  636. #ifdef SO_NOSIGPIPE
  637. int val = 1;
  638. int sso_result = ua_setsockopt(connection.sockfd, SOL_SOCKET,
  639. SO_NOSIGPIPE, (void*)&val, sizeof(val));
  640. if(sso_result < 0)
  641. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  642. "Couldn't set SO_NOSIGPIPE");
  643. #endif
  644. return connection;
  645. }