network_tcp.c 38 KB

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