ua_network_tcp.c 35 KB

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