ua_network_tcp.c 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
  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. #ifdef _OS9000
  549. /* OS-9 can't use select for checking write sockets.
  550. * Therefore, we need to use connect until success or failed
  551. */
  552. UA_UInt32 timeout_usec = (tcpConnection->timeout - timeSinceStart)
  553. * 1000;
  554. int resultsize = 0;
  555. do {
  556. u_int32 time = 0x80000001;
  557. signal_code sig;
  558. timeout_usec -= 1000000/256; // Sleep 1/256 second
  559. if (timeout_usec < 0)
  560. break;
  561. _os_sleep(&time,&sig);
  562. error = connect(clientsockfd, tcpConnection->server->ai_addr,
  563. WIN32_INT tcpConnection->server->ai_addrlen);
  564. if ((error == -1 && errno__ == EISCONN) || (error == 0))
  565. resultsize = 1;
  566. if (error == -1 && errno__ != EALREADY && errno__ != EINPROGRESS)
  567. break;
  568. }
  569. while(resultsize == 0);
  570. #else
  571. fd_set fdset;
  572. FD_ZERO(&fdset);
  573. UA_fd_set(clientsockfd, &fdset);
  574. UA_UInt32 timeout_usec = (tcpConnection->timeout - timeSinceStart)
  575. * 1000;
  576. struct timeval tmptv = { (long int) (timeout_usec / 1000000),
  577. (long int) (timeout_usec % 1000000) };
  578. int resultsize = UA_select((UA_Int32) (clientsockfd + 1), NULL, &fdset,
  579. NULL, &tmptv);
  580. #endif
  581. if (resultsize == 1) {
  582. /* Windows does not have any getsockopt equivalent and it is not needed there */
  583. #ifdef _WIN32
  584. connection->sockfd = clientsockfd;
  585. connection->state = UA_CONNECTION_ESTABLISHED;
  586. return UA_STATUSCODE_GOOD;
  587. #else
  588. OPTVAL_TYPE so_error;
  589. socklen_t len = sizeof so_error;
  590. int ret = UA_getsockopt(clientsockfd, SOL_SOCKET, SO_ERROR, &so_error,
  591. &len);
  592. if (ret != 0 || so_error != 0) {
  593. /* on connection refused we should still try to connect */
  594. /* connection refused happens on localhost or local ip without timeout */
  595. if (so_error != ECONNREFUSED) {
  596. // general error
  597. ClientNetworkLayerTCP_close(connection);
  598. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  599. "Connection to failed with error: %s",
  600. strerror(ret == 0 ? so_error : UA_ERRNO));
  601. return UA_STATUSCODE_BADDISCONNECT;
  602. }
  603. /* wait until we try a again. Do not make this too small, otherwise the
  604. * timeout is somehow wrong */
  605. } else {
  606. connection->state = UA_CONNECTION_ESTABLISHED;
  607. return UA_STATUSCODE_GOOD;
  608. }
  609. #endif
  610. }
  611. } else {
  612. connection->state = UA_CONNECTION_ESTABLISHED;
  613. return UA_STATUSCODE_GOOD;
  614. }
  615. #ifdef SO_NOSIGPIPE
  616. int val = 1;
  617. int sso_result = setsockopt(connection->sockfd, SOL_SOCKET,
  618. SO_NOSIGPIPE, (void*)&val, sizeof(val));
  619. if(sso_result < 0)
  620. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  621. "Couldn't set SO_NOSIGPIPE");
  622. #endif
  623. return UA_STATUSCODE_GOOD;
  624. }
  625. UA_Connection UA_ClientConnectionTCP_init(UA_ConnectionConfig conf,
  626. const char *endpointUrl, const UA_UInt32 timeout,
  627. UA_Logger logger) {
  628. UA_Connection connection;
  629. memset(&connection, 0, sizeof(UA_Connection));
  630. connection.state = UA_CONNECTION_OPENING;
  631. connection.localConf = conf;
  632. connection.remoteConf = conf;
  633. connection.send = connection_write;
  634. connection.recv = connection_recv;
  635. connection.close = ClientNetworkLayerTCP_close;
  636. connection.free = ClientNetworkLayerTCP_free;
  637. connection.getSendBuffer = connection_getsendbuffer;
  638. connection.releaseSendBuffer = connection_releasesendbuffer;
  639. connection.releaseRecvBuffer = connection_releaserecvbuffer;
  640. TCPClientConnection *tcpClientConnection = (TCPClientConnection*) malloc(
  641. sizeof(TCPClientConnection));
  642. connection.handle = (void*) tcpClientConnection;
  643. tcpClientConnection->timeout = timeout;
  644. UA_String endpointUrlString = UA_STRING((char*) (uintptr_t) endpointUrl);
  645. UA_String hostnameString = UA_STRING_NULL;
  646. UA_String pathString = UA_STRING_NULL;
  647. UA_UInt16 port = 0;
  648. char hostname[512];
  649. tcpClientConnection->connStart = UA_DateTime_nowMonotonic();
  650. UA_StatusCode parse_retval = UA_parseEndpointUrl(&endpointUrlString,
  651. &hostnameString, &port, &pathString);
  652. if (parse_retval != UA_STATUSCODE_GOOD || hostnameString.length > 511) {
  653. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  654. "Server url is invalid: %s", endpointUrl);
  655. return connection;
  656. }
  657. memcpy(hostname, hostnameString.data, hostnameString.length);
  658. hostname[hostnameString.length] = 0;
  659. if (port == 0) {
  660. port = 4840;
  661. UA_LOG_INFO(logger, UA_LOGCATEGORY_NETWORK,
  662. "No port defined, using default port %d", port);
  663. }
  664. memset(&tcpClientConnection->hints, 0, sizeof(tcpClientConnection->hints));
  665. tcpClientConnection->hints.ai_family = AF_UNSPEC;
  666. tcpClientConnection->hints.ai_socktype = SOCK_STREAM;
  667. char portStr[6];
  668. UA_snprintf(portStr, 6, "%d", port);
  669. int error = UA_getaddrinfo(hostname, portStr, &tcpClientConnection->hints,
  670. &tcpClientConnection->server);
  671. if (error != 0 || !tcpClientConnection->server) {
  672. UA_LOG_SOCKET_ERRNO_GAI_WRAP(UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  673. "DNS lookup of %s failed with error %s", hostname, errno_str));
  674. return connection;
  675. }
  676. return connection;
  677. }
  678. UA_Connection
  679. UA_ClientConnectionTCP(UA_ConnectionConfig conf,
  680. const char *endpointUrl, const UA_UInt32 timeout,
  681. UA_Logger logger) {
  682. UA_initialize_architecture_network();
  683. if(logger == NULL) {
  684. logger = UA_Log_Stdout;
  685. }
  686. UA_Connection connection;
  687. memset(&connection, 0, sizeof(UA_Connection));
  688. connection.state = UA_CONNECTION_CLOSED;
  689. connection.localConf = conf;
  690. connection.remoteConf = conf;
  691. connection.send = connection_write;
  692. connection.recv = connection_recv;
  693. connection.close = ClientNetworkLayerTCP_close;
  694. connection.free = ClientNetworkLayerTCP_free;
  695. connection.getSendBuffer = connection_getsendbuffer;
  696. connection.releaseSendBuffer = connection_releasesendbuffer;
  697. connection.releaseRecvBuffer = connection_releaserecvbuffer;
  698. connection.handle = NULL;
  699. UA_String endpointUrlString = UA_STRING((char*)(uintptr_t)endpointUrl);
  700. UA_String hostnameString = UA_STRING_NULL;
  701. UA_String pathString = UA_STRING_NULL;
  702. UA_UInt16 port = 0;
  703. char hostname[512];
  704. UA_StatusCode parse_retval =
  705. UA_parseEndpointUrl(&endpointUrlString, &hostnameString,
  706. &port, &pathString);
  707. if(parse_retval != UA_STATUSCODE_GOOD || hostnameString.length > 511) {
  708. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  709. "Server url is invalid: %s", endpointUrl);
  710. return connection;
  711. }
  712. memcpy(hostname, hostnameString.data, hostnameString.length);
  713. hostname[hostnameString.length] = 0;
  714. if(port == 0) {
  715. port = 4840;
  716. UA_LOG_INFO(logger, UA_LOGCATEGORY_NETWORK,
  717. "No port defined, using default port %d", port);
  718. }
  719. struct addrinfo hints, *server;
  720. memset(&hints, 0, sizeof(hints));
  721. hints.ai_family = AF_UNSPEC;
  722. hints.ai_socktype = SOCK_STREAM;
  723. hints.ai_protocol = IPPROTO_TCP;
  724. char portStr[6];
  725. UA_snprintf(portStr, 6, "%d", port);
  726. int error = UA_getaddrinfo(hostname, portStr, &hints, &server);
  727. if(error != 0 || !server) {
  728. UA_LOG_SOCKET_ERRNO_GAI_WRAP(UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  729. "DNS lookup of %s failed with error %s", hostname, errno_str));
  730. return connection;
  731. }
  732. UA_Boolean connected = UA_FALSE;
  733. UA_DateTime dtTimeout = timeout * UA_DATETIME_MSEC;
  734. UA_DateTime connStart = UA_DateTime_nowMonotonic();
  735. UA_SOCKET clientsockfd;
  736. /* On linux connect may immediately return with ECONNREFUSED but we still
  737. * want to try to connect. So use a loop and retry until timeout is
  738. * reached. */
  739. do {
  740. /* Get a socket */
  741. clientsockfd = UA_socket(server->ai_family,
  742. server->ai_socktype,
  743. server->ai_protocol);
  744. if(clientsockfd == UA_INVALID_SOCKET) {
  745. UA_LOG_SOCKET_ERRNO_WRAP(UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  746. "Could not create client socket: %s", errno_str));
  747. UA_freeaddrinfo(server);
  748. return connection;
  749. }
  750. connection.state = UA_CONNECTION_OPENING;
  751. /* Connect to the server */
  752. connection.sockfd = clientsockfd;
  753. /* Non blocking connect to be able to timeout */
  754. if (UA_socket_set_nonblocking(clientsockfd) != UA_STATUSCODE_GOOD) {
  755. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  756. "Could not set the client socket to nonblocking");
  757. ClientNetworkLayerTCP_close(&connection);
  758. UA_freeaddrinfo(server);
  759. return connection;
  760. }
  761. /* Non blocking connect */
  762. error = UA_connect(clientsockfd, server->ai_addr, (socklen_t)server->ai_addrlen);
  763. if ((error == -1) && (UA_ERRNO != UA_ERR_CONNECTION_PROGRESS)) {
  764. ClientNetworkLayerTCP_close(&connection);
  765. UA_LOG_SOCKET_ERRNO_WRAP(
  766. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  767. "Connection to %s failed with error: %s",
  768. endpointUrl, errno_str));
  769. UA_freeaddrinfo(server);
  770. return connection;
  771. }
  772. /* Use select to wait and check if connected */
  773. if (error == -1 && (UA_ERRNO == UA_ERR_CONNECTION_PROGRESS)) {
  774. /* connection in progress. Wait until connected using select */
  775. UA_DateTime timeSinceStart = UA_DateTime_nowMonotonic() - connStart;
  776. if(timeSinceStart > dtTimeout)
  777. break;
  778. #ifdef _OS9000
  779. /* OS-9 can't use select for checking write sockets.
  780. * Therefore, we need to use connect until success or failed
  781. */
  782. UA_DateTime timeout_usec = (dtTimeout - timeSinceStart) / UA_DATETIME_USEC;
  783. int resultsize = 0;
  784. do {
  785. u_int32 time = 0x80000001;
  786. signal_code sig;
  787. timeout_usec -= 1000000/256; // Sleep 1/256 second
  788. if (timeout_usec < 0)
  789. break;
  790. _os_sleep(&time,&sig);
  791. error = connect(clientsockfd, server->ai_addr, WIN32_INT server->ai_addrlen);
  792. if ((error == -1 && errno__ == EISCONN) || (error == 0))
  793. resultsize = 1;
  794. if (error == -1 && errno__ != EALREADY && errno__ != EINPROGRESS)
  795. break;
  796. }
  797. while(resultsize == 0);
  798. #else
  799. fd_set fdset;
  800. FD_ZERO(&fdset);
  801. UA_fd_set(clientsockfd, &fdset);
  802. UA_DateTime timeout_usec = (dtTimeout - timeSinceStart) / UA_DATETIME_USEC;
  803. struct timeval tmptv = {(long int) (timeout_usec / 1000000),
  804. (long int) (timeout_usec % 1000000)};
  805. int resultsize = UA_select((UA_Int32)(clientsockfd + 1), NULL, &fdset, NULL, &tmptv);
  806. #endif
  807. if(resultsize == 1) {
  808. #ifdef _WIN32
  809. /* Windows does not have any getsockopt equivalent and it is not
  810. * needed there */
  811. connected = true;
  812. break;
  813. #else
  814. OPTVAL_TYPE so_error;
  815. socklen_t len = sizeof so_error;
  816. int ret = UA_getsockopt(clientsockfd, SOL_SOCKET, SO_ERROR, &so_error, &len);
  817. if (ret != 0 || so_error != 0) {
  818. /* on connection refused we should still try to connect */
  819. /* connection refused happens on localhost or local ip without timeout */
  820. if (so_error != ECONNREFUSED) {
  821. ClientNetworkLayerTCP_close(&connection);
  822. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  823. "Connection to %s failed with error: %s",
  824. endpointUrl, strerror(ret == 0 ? so_error : UA_ERRNO));
  825. UA_freeaddrinfo(server);
  826. return connection;
  827. }
  828. /* wait until we try a again. Do not make this too small, otherwise the
  829. * timeout is somehow wrong */
  830. UA_sleep_ms(100);
  831. } else {
  832. connected = true;
  833. break;
  834. }
  835. #endif
  836. }
  837. } else {
  838. connected = true;
  839. break;
  840. }
  841. ClientNetworkLayerTCP_close(&connection);
  842. } while ((UA_DateTime_nowMonotonic() - connStart) < dtTimeout);
  843. UA_freeaddrinfo(server);
  844. if(!connected) {
  845. /* connection timeout */
  846. if (connection.state != UA_CONNECTION_CLOSED)
  847. ClientNetworkLayerTCP_close(&connection);
  848. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  849. "Trying to connect to %s timed out",
  850. endpointUrl);
  851. return connection;
  852. }
  853. /* We are connected. Reset socket to blocking */
  854. if(UA_socket_set_blocking(clientsockfd) != UA_STATUSCODE_GOOD) {
  855. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  856. "Could not set the client socket to blocking");
  857. ClientNetworkLayerTCP_close(&connection);
  858. return connection;
  859. }
  860. #ifdef SO_NOSIGPIPE
  861. int val = 1;
  862. int sso_result = UA_setsockopt(connection.sockfd, SOL_SOCKET,
  863. SO_NOSIGPIPE, (void*)&val, sizeof(val));
  864. if(sso_result < 0)
  865. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  866. "Couldn't set SO_NOSIGPIPE");
  867. #endif
  868. return connection;
  869. }