ua_network_tcp.c 35 KB

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