ua_network_tcp.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  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. }
  293. }
  294. UA_String_copy(&du, &nl->discoveryUrl);
  295. /* Get addrinfo of the server and create server sockets */
  296. char portno[6];
  297. UA_snprintf(portno, 6, "%d", layer->port);
  298. struct addrinfo hints, *res;
  299. memset(&hints, 0, sizeof hints);
  300. hints.ai_family = AF_UNSPEC;
  301. hints.ai_socktype = SOCK_STREAM;
  302. hints.ai_flags = AI_PASSIVE;
  303. hints.ai_protocol = IPPROTO_TCP;
  304. if(UA_getaddrinfo(NULL, portno, &hints, &res) != 0)
  305. return UA_STATUSCODE_BADINTERNALERROR;
  306. /* There might be serveral addrinfos (for different network cards,
  307. * IPv4/IPv6). Add a server socket for all of them. */
  308. struct addrinfo *ai = res;
  309. for(layer->serverSocketsSize = 0;
  310. layer->serverSocketsSize < FD_SETSIZE && ai != NULL;
  311. ai = ai->ai_next)
  312. addServerSocket(layer, ai);
  313. UA_freeaddrinfo(res);
  314. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  315. "TCP network layer listening on %.*s",
  316. (int)nl->discoveryUrl.length, nl->discoveryUrl.data);
  317. return UA_STATUSCODE_GOOD;
  318. }
  319. /* After every select, reset the sockets to listen on */
  320. static UA_Int32
  321. setFDSet(ServerNetworkLayerTCP *layer, fd_set *fdset) {
  322. FD_ZERO(fdset);
  323. UA_Int32 highestfd = 0;
  324. for(UA_UInt16 i = 0; i < layer->serverSocketsSize; i++) {
  325. UA_fd_set(layer->serverSockets[i], fdset);
  326. if(layer->serverSockets[i] > highestfd)
  327. highestfd = layer->serverSockets[i];
  328. }
  329. ConnectionEntry *e;
  330. LIST_FOREACH(e, &layer->connections, pointers) {
  331. UA_fd_set(e->connection.sockfd, fdset);
  332. if(e->connection.sockfd > highestfd)
  333. highestfd = e->connection.sockfd;
  334. }
  335. return highestfd;
  336. }
  337. static UA_StatusCode
  338. ServerNetworkLayerTCP_listen(UA_ServerNetworkLayer *nl, UA_Server *server,
  339. UA_UInt16 timeout) {
  340. /* Every open socket can generate two jobs */
  341. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  342. if (layer->serverSocketsSize == 0)
  343. return UA_STATUSCODE_GOOD;
  344. /* Listen on open sockets (including the server) */
  345. fd_set fdset, errset;
  346. UA_Int32 highestfd = setFDSet(layer, &fdset);
  347. setFDSet(layer, &errset);
  348. struct timeval tmptv = {0, timeout * 1000};
  349. if (UA_select(highestfd+1, &fdset, NULL, &errset, &tmptv) < 0) {
  350. UA_LOG_SOCKET_ERRNO_WRAP(
  351. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  352. "Socket select failed with %s", errno_str));
  353. // we will retry, so do not return bad
  354. return UA_STATUSCODE_GOOD;
  355. }
  356. /* Accept new connections via the server sockets */
  357. for(UA_UInt16 i = 0; i < layer->serverSocketsSize; i++) {
  358. if(!UA_fd_isset(layer->serverSockets[i], &fdset))
  359. continue;
  360. struct sockaddr_storage remote;
  361. socklen_t remote_size = sizeof(remote);
  362. UA_SOCKET newsockfd = UA_accept((UA_SOCKET)layer->serverSockets[i],
  363. (struct sockaddr*)&remote, &remote_size);
  364. if(newsockfd == UA_INVALID_SOCKET)
  365. continue;
  366. UA_LOG_TRACE(layer->logger, UA_LOGCATEGORY_NETWORK,
  367. "Connection %i | New TCP connection on server socket %i",
  368. (int)newsockfd, layer->serverSockets[i]);
  369. ServerNetworkLayerTCP_add(layer, (UA_Int32)newsockfd, &remote);
  370. }
  371. /* Read from established sockets */
  372. ConnectionEntry *e, *e_tmp;
  373. UA_DateTime now = UA_DateTime_nowMonotonic();
  374. LIST_FOREACH_SAFE(e, &layer->connections, pointers, e_tmp) {
  375. if ((e->connection.state == UA_CONNECTION_OPENING) &&
  376. (now > (e->connection.openingDate + (NOHELLOTIMEOUT * UA_DATETIME_MSEC)))){
  377. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  378. "Connection %i | Closed by the server (no Hello Message)",
  379. e->connection.sockfd);
  380. LIST_REMOVE(e, pointers);
  381. UA_close(e->connection.sockfd);
  382. UA_Server_removeConnection(server, &e->connection);
  383. continue;
  384. }
  385. if(!UA_fd_isset(e->connection.sockfd, &errset) &&
  386. !UA_fd_isset(e->connection.sockfd, &fdset))
  387. continue;
  388. UA_LOG_TRACE(layer->logger, UA_LOGCATEGORY_NETWORK,
  389. "Connection %i | Activity on the socket",
  390. e->connection.sockfd);
  391. UA_ByteString buf = UA_BYTESTRING_NULL;
  392. UA_StatusCode retval = connection_recv(&e->connection, &buf, 0);
  393. if(retval == UA_STATUSCODE_GOOD) {
  394. /* Process packets */
  395. UA_Server_processBinaryMessage(server, &e->connection, &buf);
  396. connection_releaserecvbuffer(&e->connection, &buf);
  397. } else if(retval == UA_STATUSCODE_BADCONNECTIONCLOSED) {
  398. /* The socket is shutdown but not closed */
  399. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  400. "Connection %i | Closed",
  401. e->connection.sockfd);
  402. LIST_REMOVE(e, pointers);
  403. UA_close(e->connection.sockfd);
  404. UA_Server_removeConnection(server, &e->connection);
  405. }
  406. }
  407. return UA_STATUSCODE_GOOD;
  408. }
  409. static void
  410. ServerNetworkLayerTCP_stop(UA_ServerNetworkLayer *nl, UA_Server *server) {
  411. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  412. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  413. "Shutting down the TCP network layer");
  414. /* Close the server sockets */
  415. for(UA_UInt16 i = 0; i < layer->serverSocketsSize; i++) {
  416. UA_shutdown(layer->serverSockets[i], 2);
  417. UA_close(layer->serverSockets[i]);
  418. }
  419. layer->serverSocketsSize = 0;
  420. /* Close open connections */
  421. ConnectionEntry *e;
  422. LIST_FOREACH(e, &layer->connections, pointers)
  423. ServerNetworkLayerTCP_close(&e->connection);
  424. /* Run recv on client sockets. This picks up the closed sockets and frees
  425. * the connection. */
  426. ServerNetworkLayerTCP_listen(nl, server, 0);
  427. UA_deinitialize_architecture_network();
  428. }
  429. /* run only when the server is stopped */
  430. static void
  431. ServerNetworkLayerTCP_deleteMembers(UA_ServerNetworkLayer *nl) {
  432. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  433. UA_String_deleteMembers(&nl->discoveryUrl);
  434. /* Hard-close and remove remaining connections. The server is no longer
  435. * running. So this is safe. */
  436. ConnectionEntry *e, *e_tmp;
  437. LIST_FOREACH_SAFE(e, &layer->connections, pointers, e_tmp) {
  438. LIST_REMOVE(e, pointers);
  439. UA_close(e->connection.sockfd);
  440. UA_free(e);
  441. }
  442. /* Free the layer */
  443. UA_free(layer);
  444. }
  445. UA_ServerNetworkLayer
  446. UA_ServerNetworkLayerTCP(UA_ConnectionConfig conf, UA_UInt16 port, UA_Logger logger) {
  447. UA_ServerNetworkLayer nl;
  448. memset(&nl, 0, sizeof(UA_ServerNetworkLayer));
  449. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP*)
  450. UA_calloc(1,sizeof(ServerNetworkLayerTCP));
  451. if(!layer)
  452. return nl;
  453. layer->logger = (logger != NULL ? logger : UA_Log_Stdout);
  454. layer->conf = conf;
  455. layer->port = port;
  456. nl.handle = layer;
  457. nl.start = ServerNetworkLayerTCP_start;
  458. nl.listen = ServerNetworkLayerTCP_listen;
  459. nl.stop = ServerNetworkLayerTCP_stop;
  460. nl.deleteMembers = ServerNetworkLayerTCP_deleteMembers;
  461. return nl;
  462. }
  463. /***************************/
  464. /* Client NetworkLayer TCP */
  465. /***************************/
  466. static void
  467. ClientNetworkLayerTCP_close(UA_Connection *connection) {
  468. if (connection->state == UA_CONNECTION_CLOSED)
  469. return;
  470. UA_shutdown(connection->sockfd, 2);
  471. UA_close(connection->sockfd);
  472. connection->state = UA_CONNECTION_CLOSED;
  473. }
  474. UA_Connection
  475. UA_ClientConnectionTCP(UA_ConnectionConfig conf,
  476. const char *endpointUrl, const UA_UInt32 timeout,
  477. UA_Logger logger) {
  478. UA_initialize_architecture_network();
  479. if(logger == NULL) {
  480. logger = UA_Log_Stdout;
  481. }
  482. UA_Connection connection;
  483. memset(&connection, 0, sizeof(UA_Connection));
  484. connection.state = UA_CONNECTION_CLOSED;
  485. connection.localConf = conf;
  486. connection.remoteConf = conf;
  487. connection.send = connection_write;
  488. connection.recv = connection_recv;
  489. connection.close = ClientNetworkLayerTCP_close;
  490. connection.free = NULL;
  491. connection.getSendBuffer = connection_getsendbuffer;
  492. connection.releaseSendBuffer = connection_releasesendbuffer;
  493. connection.releaseRecvBuffer = connection_releaserecvbuffer;
  494. UA_String endpointUrlString = UA_STRING((char*)(uintptr_t)endpointUrl);
  495. UA_String hostnameString = UA_STRING_NULL;
  496. UA_String pathString = UA_STRING_NULL;
  497. UA_UInt16 port = 0;
  498. char hostname[512];
  499. UA_StatusCode parse_retval =
  500. UA_parseEndpointUrl(&endpointUrlString, &hostnameString,
  501. &port, &pathString);
  502. if(parse_retval != UA_STATUSCODE_GOOD || hostnameString.length > 511) {
  503. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  504. "Server url is invalid: %s", endpointUrl);
  505. return connection;
  506. }
  507. memcpy(hostname, hostnameString.data, hostnameString.length);
  508. hostname[hostnameString.length] = 0;
  509. if(port == 0) {
  510. port = 4840;
  511. UA_LOG_INFO(logger, UA_LOGCATEGORY_NETWORK,
  512. "No port defined, using default port %d", port);
  513. }
  514. struct addrinfo hints, *server;
  515. memset(&hints, 0, sizeof(hints));
  516. hints.ai_family = AF_UNSPEC;
  517. hints.ai_socktype = SOCK_STREAM;
  518. hints.ai_protocol = IPPROTO_TCP;
  519. char portStr[6];
  520. UA_snprintf(portStr, 6, "%d", port);
  521. int error = UA_getaddrinfo(hostname, portStr, &hints, &server);
  522. if(error != 0 || !server) {
  523. UA_LOG_SOCKET_ERRNO_GAI_WRAP(UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  524. "DNS lookup of %s failed with error %s", hostname, errno_str));
  525. return connection;
  526. }
  527. UA_Boolean connected = UA_FALSE;
  528. UA_DateTime dtTimeout = timeout * UA_DATETIME_MSEC;
  529. UA_DateTime connStart = UA_DateTime_nowMonotonic();
  530. UA_SOCKET clientsockfd;
  531. /* On linux connect may immediately return with ECONNREFUSED but we still
  532. * want to try to connect. So use a loop and retry until timeout is
  533. * reached. */
  534. do {
  535. /* Get a socket */
  536. clientsockfd = UA_socket(server->ai_family,
  537. server->ai_socktype,
  538. server->ai_protocol);
  539. if(clientsockfd == UA_INVALID_SOCKET) {
  540. UA_LOG_SOCKET_ERRNO_WRAP(UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  541. "Could not create client socket: %s", errno_str));
  542. UA_freeaddrinfo(server);
  543. return connection;
  544. }
  545. connection.state = UA_CONNECTION_OPENING;
  546. /* Connect to the server */
  547. connection.sockfd = clientsockfd;
  548. /* Non blocking connect to be able to timeout */
  549. if (UA_socket_set_nonblocking(clientsockfd) != UA_STATUSCODE_GOOD) {
  550. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  551. "Could not set the client socket to nonblocking");
  552. ClientNetworkLayerTCP_close(&connection);
  553. UA_freeaddrinfo(server);
  554. return connection;
  555. }
  556. /* Non blocking connect */
  557. error = UA_connect(clientsockfd, server->ai_addr, (socklen_t)server->ai_addrlen);
  558. if ((error == -1) && (UA_ERRNO != UA_ERR_CONNECTION_PROGRESS)) {
  559. ClientNetworkLayerTCP_close(&connection);
  560. UA_LOG_SOCKET_ERRNO_WRAP(
  561. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  562. "Connection to %s failed with error: %s",
  563. endpointUrl, errno_str));
  564. UA_freeaddrinfo(server);
  565. return connection;
  566. }
  567. /* Use select to wait and check if connected */
  568. if (error == -1 && (UA_ERRNO == UA_ERR_CONNECTION_PROGRESS)) {
  569. /* connection in progress. Wait until connected using select */
  570. UA_DateTime timeSinceStart = UA_DateTime_nowMonotonic() - connStart;
  571. if(timeSinceStart > dtTimeout)
  572. break;
  573. fd_set fdset;
  574. FD_ZERO(&fdset);
  575. UA_fd_set(clientsockfd, &fdset);
  576. UA_DateTime timeout_usec = (dtTimeout - timeSinceStart) / UA_DATETIME_USEC;
  577. struct timeval tmptv = {(long int) (timeout_usec / 1000000),
  578. (long int) (timeout_usec % 1000000)};
  579. int resultsize = UA_select(clientsockfd + 1, NULL, &fdset, NULL, &tmptv);
  580. if(resultsize == 1) {
  581. #ifdef _WIN32
  582. /* Windows does not have any getsockopt equivalent and it is not
  583. * needed there */
  584. connected = true;
  585. break;
  586. #else
  587. OPTVAL_TYPE so_error;
  588. socklen_t len = sizeof so_error;
  589. int ret = UA_getsockopt(clientsockfd, SOL_SOCKET, SO_ERROR, &so_error, &len);
  590. if (ret != 0 || so_error != 0) {
  591. /* on connection refused we should still try to connect */
  592. /* connection refused happens on localhost or local ip without timeout */
  593. if (so_error != ECONNREFUSED) {
  594. ClientNetworkLayerTCP_close(&connection);
  595. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  596. "Connection to %s failed with error: %s",
  597. endpointUrl, strerror(ret == 0 ? so_error : UA_ERRNO));
  598. UA_freeaddrinfo(server);
  599. return connection;
  600. }
  601. /* wait until we try a again. Do not make this too small, otherwise the
  602. * timeout is somehow wrong */
  603. UA_sleep_ms(100);
  604. } else {
  605. connected = true;
  606. break;
  607. }
  608. #endif
  609. }
  610. } else {
  611. connected = true;
  612. break;
  613. }
  614. ClientNetworkLayerTCP_close(&connection);
  615. } while ((UA_DateTime_nowMonotonic() - connStart) < dtTimeout);
  616. UA_freeaddrinfo(server);
  617. if(!connected) {
  618. /* connection timeout */
  619. if (connection.state != UA_CONNECTION_CLOSED)
  620. ClientNetworkLayerTCP_close(&connection);
  621. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  622. "Trying to connect to %s timed out",
  623. endpointUrl);
  624. return connection;
  625. }
  626. /* We are connected. Reset socket to blocking */
  627. if(UA_socket_set_blocking(clientsockfd) != UA_STATUSCODE_GOOD) {
  628. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  629. "Could not set the client socket to blocking");
  630. ClientNetworkLayerTCP_close(&connection);
  631. return connection;
  632. }
  633. #ifdef SO_NOSIGPIPE
  634. int val = 1;
  635. int sso_result = UA_setsockopt(connection.sockfd, SOL_SOCKET,
  636. SO_NOSIGPIPE, (void*)&val, sizeof(val));
  637. if(sso_result < 0)
  638. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  639. "Couldn't set SO_NOSIGPIPE");
  640. #endif
  641. return connection;
  642. }