ua_network_tcp.c 37 KB

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