ua_network_tcp.c 37 KB

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