ua_network_tcp.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  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_architecture.h"
  11. #include "ua_network_tcp.h"
  12. #include "ua_log_stdout.h"
  13. #include "../deps/queue.h"
  14. #include <stdio.h> // snprintf
  15. #include <string.h> // memset
  16. #include "ua_log_socket_error.h"
  17. /****************************/
  18. /* Generic Socket Functions */
  19. /****************************/
  20. static UA_StatusCode
  21. connection_getsendbuffer(UA_Connection *connection,
  22. size_t length, UA_ByteString *buf) {
  23. if(length > connection->remoteConf.recvBufferSize)
  24. return UA_STATUSCODE_BADCOMMUNICATIONERROR;
  25. return UA_ByteString_allocBuffer(buf, length);
  26. }
  27. static void
  28. connection_releasesendbuffer(UA_Connection *connection,
  29. UA_ByteString *buf) {
  30. UA_ByteString_deleteMembers(buf);
  31. }
  32. static void
  33. connection_releaserecvbuffer(UA_Connection *connection,
  34. UA_ByteString *buf) {
  35. UA_ByteString_deleteMembers(buf);
  36. }
  37. static UA_StatusCode
  38. connection_write(UA_Connection *connection, UA_ByteString *buf) {
  39. if(connection->state == UA_CONNECTION_CLOSED) {
  40. UA_ByteString_deleteMembers(buf);
  41. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  42. }
  43. /* Prevent OS signals when sending to a closed socket */
  44. int flags = 0;
  45. #ifdef MSG_NOSIGNAL
  46. flags |= MSG_NOSIGNAL;
  47. #endif
  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 = send((SOCKET)connection->sockfd,
  55. (const char*)buf->data + nWritten,
  56. WIN32_INT bytes_to_send, flags);
  57. if(n < 0 && errno__ != INTERRUPTED && errno__ != 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 = 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(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*)
  98. UA_malloc(connection->localConf.recvBufferSize);
  99. if(!response->data) {
  100. response->length = 0;
  101. return UA_STATUSCODE_BADOUTOFMEMORY; /* not enough memory retry */
  102. }
  103. /* Get the received packet(s) */
  104. ssize_t ret = recv(connection->sockfd, (char*)response->data,
  105. connection->localConf.recvBufferSize, 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(errno__ == INTERRUPTED || (timeout > 0) ?
  116. false : (errno__ == EAGAIN || errno__ == WOULDBLOCK))
  117. return UA_STATUSCODE_GOOD; /* statuscode_good but no data -> retry */
  118. connection->close(connection);
  119. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  120. }
  121. /* Set the length of the received buffer */
  122. response->length = (size_t)ret;
  123. return UA_STATUSCODE_GOOD;
  124. }
  125. static UA_StatusCode
  126. socket_set_nonblocking(SOCKET sockfd) {
  127. #ifdef _WIN32
  128. u_long iMode = 1;
  129. if(ioctlsocket(sockfd, FIONBIO, &iMode) != NO_ERROR)
  130. return UA_STATUSCODE_BADINTERNALERROR;
  131. #elif defined(_WRS_KERNEL) || defined(UA_FREERTOS)
  132. int on = TRUE;
  133. if(ioctl(sockfd, FIONBIO, &on) < 0)
  134. return UA_STATUSCODE_BADINTERNALERROR;
  135. #else
  136. int opts = fcntl(sockfd, F_GETFL);
  137. if(opts < 0 || fcntl(sockfd, F_SETFL, opts|O_NONBLOCK) < 0)
  138. return UA_STATUSCODE_BADINTERNALERROR;
  139. #endif
  140. return UA_STATUSCODE_GOOD;
  141. }
  142. static UA_StatusCode
  143. socket_set_blocking(SOCKET sockfd) {
  144. #ifdef _WIN32
  145. u_long iMode = 0;
  146. if(ioctlsocket(sockfd, FIONBIO, &iMode) != NO_ERROR)
  147. return UA_STATUSCODE_BADINTERNALERROR;
  148. #elif defined(_WRS_KERNEL) || defined(UA_FREERTOS)
  149. int on = FALSE;
  150. if(ioctl(sockfd, FIONBIO, &on) < 0)
  151. return UA_STATUSCODE_BADINTERNALERROR;
  152. #else
  153. int opts = fcntl(sockfd, F_GETFL);
  154. if(opts < 0 || fcntl(sockfd, F_SETFL, opts & (~O_NONBLOCK)) < 0)
  155. return UA_STATUSCODE_BADINTERNALERROR;
  156. #endif
  157. return UA_STATUSCODE_GOOD;
  158. }
  159. /***************************/
  160. /* Server NetworkLayer TCP */
  161. /***************************/
  162. #define MAXBACKLOG 100
  163. #define NOHELLOTIMEOUT 120000 /* timeout in ms before close the connection
  164. * if server does not receive Hello Message */
  165. typedef struct ConnectionEntry {
  166. UA_Connection connection;
  167. LIST_ENTRY(ConnectionEntry) pointers;
  168. } ConnectionEntry;
  169. typedef struct {
  170. UA_Logger logger;
  171. UA_ConnectionConfig conf;
  172. UA_UInt16 port;
  173. UA_Int32 serverSockets[FD_SETSIZE];
  174. UA_UInt16 serverSocketsSize;
  175. LIST_HEAD(, ConnectionEntry) connections;
  176. } ServerNetworkLayerTCP;
  177. static void
  178. ServerNetworkLayerTCP_freeConnection(UA_Connection *connection) {
  179. UA_Connection_deleteMembers(connection);
  180. UA_free(connection);
  181. }
  182. /* This performs only 'shutdown'. 'close' is called when the shutdown
  183. * socket is returned from select. */
  184. static void
  185. ServerNetworkLayerTCP_close(UA_Connection *connection) {
  186. if (connection->state == UA_CONNECTION_CLOSED)
  187. return;
  188. shutdown((SOCKET)connection->sockfd, 2);
  189. connection->state = UA_CONNECTION_CLOSED;
  190. }
  191. static UA_StatusCode
  192. ServerNetworkLayerTCP_add(ServerNetworkLayerTCP *layer, UA_Int32 newsockfd,
  193. struct sockaddr_storage *remote) {
  194. /* Set nonblocking */
  195. socket_set_nonblocking(newsockfd);
  196. /* Do not merge packets on the socket (disable Nagle's algorithm) */
  197. int dummy = 1;
  198. if(setsockopt(newsockfd, IPPROTO_TCP, TCP_NODELAY,
  199. (const char *)&dummy, sizeof(dummy)) < 0) {
  200. UA_LOG_SOCKET_ERRNO_WRAP(
  201. UA_LOG_ERROR(layer->logger, UA_LOGCATEGORY_NETWORK,
  202. "Cannot set socket option TCP_NODELAY. Error: %s",
  203. errno_str));
  204. return UA_STATUSCODE_BADUNEXPECTEDERROR;
  205. }
  206. #if !defined(UA_FREERTOS)
  207. /* Get the peer name for logging */
  208. char remote_name[100];
  209. int res = getnameinfo((struct sockaddr*)remote,
  210. sizeof(struct sockaddr_storage),
  211. remote_name, sizeof(remote_name),
  212. NULL, 0, NI_NUMERICHOST);
  213. if(res == 0) {
  214. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  215. "Connection %i | New connection over TCP from %s",
  216. (int)newsockfd, remote_name);
  217. } else {
  218. UA_LOG_SOCKET_ERRNO_WRAP(UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  219. "Connection %i | New connection over TCP, "
  220. "getnameinfo failed with error: %s",
  221. (int)newsockfd, errno_str));
  222. }
  223. #endif
  224. /* Allocate and initialize the connection */
  225. ConnectionEntry *e = (ConnectionEntry*)UA_malloc(sizeof(ConnectionEntry));
  226. if(!e){
  227. CLOSESOCKET(newsockfd);
  228. return UA_STATUSCODE_BADOUTOFMEMORY;
  229. }
  230. UA_Connection *c = &e->connection;
  231. memset(c, 0, sizeof(UA_Connection));
  232. c->sockfd = newsockfd;
  233. c->handle = layer;
  234. c->localConf = layer->conf;
  235. c->remoteConf = layer->conf;
  236. c->send = connection_write;
  237. c->close = ServerNetworkLayerTCP_close;
  238. c->free = ServerNetworkLayerTCP_freeConnection;
  239. c->getSendBuffer = connection_getsendbuffer;
  240. c->releaseSendBuffer = connection_releasesendbuffer;
  241. c->releaseRecvBuffer = connection_releaserecvbuffer;
  242. c->state = UA_CONNECTION_OPENING;
  243. c->openingDate = UA_DateTime_nowMonotonic();
  244. /* Add to the linked list */
  245. LIST_INSERT_HEAD(&layer->connections, e, pointers);
  246. return UA_STATUSCODE_GOOD;
  247. }
  248. static void
  249. addServerSocket(ServerNetworkLayerTCP *layer, struct addrinfo *ai) {
  250. /* Create the server socket */
  251. SOCKET newsock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
  252. #ifdef _WIN32
  253. if(newsock == INVALID_SOCKET)
  254. #else
  255. if(newsock < 0)
  256. #endif
  257. {
  258. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  259. "Error opening the server socket");
  260. return;
  261. }
  262. /* Some Linux distributions have net.ipv6.bindv6only not activated. So
  263. * sockets can double-bind to IPv4 and IPv6. This leads to problems. Use
  264. * AF_INET6 sockets only for IPv6. */
  265. int optval = 1;
  266. #if !defined(UA_FREERTOS)
  267. if(ai->ai_family == AF_INET6 &&
  268. setsockopt(newsock, IPPROTO_IPV6, IPV6_V6ONLY,
  269. (const char*)&optval, sizeof(optval)) == -1) {
  270. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  271. "Could not set an IPv6 socket to IPv6 only");
  272. CLOSESOCKET(newsock);
  273. return;
  274. }
  275. #endif
  276. if(setsockopt(newsock, SOL_SOCKET, SO_REUSEADDR,
  277. (const char *)&optval, sizeof(optval)) == -1) {
  278. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  279. "Could not make the socket reusable");
  280. CLOSESOCKET(newsock);
  281. return;
  282. }
  283. if(socket_set_nonblocking(newsock) != UA_STATUSCODE_GOOD) {
  284. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  285. "Could not set the server socket to nonblocking");
  286. CLOSESOCKET(newsock);
  287. return;
  288. }
  289. /* Bind socket to address */
  290. if(bind(newsock, ai->ai_addr, WIN32_INT ai->ai_addrlen) < 0) {
  291. UA_LOG_SOCKET_ERRNO_WRAP(
  292. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  293. "Error binding a server socket: %s", errno_str));
  294. CLOSESOCKET(newsock);
  295. return;
  296. }
  297. /* Start listening */
  298. if(listen(newsock, MAXBACKLOG) < 0) {
  299. UA_LOG_SOCKET_ERRNO_WRAP(
  300. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  301. "Error listening on server socket: %s", errno_str));
  302. CLOSESOCKET(newsock);
  303. return;
  304. }
  305. layer->serverSockets[layer->serverSocketsSize] = (UA_Int32)newsock;
  306. layer->serverSocketsSize++;
  307. }
  308. static UA_StatusCode
  309. ServerNetworkLayerTCP_start(UA_ServerNetworkLayer *nl, const UA_String *customHostname) {
  310. #ifdef _WIN32
  311. WORD wVersionRequested = MAKEWORD(2, 2);
  312. WSADATA wsaData;
  313. WSAStartup(wVersionRequested, &wsaData);
  314. #endif
  315. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  316. /* Get the discovery url from the hostname */
  317. UA_String du = UA_STRING_NULL;
  318. if (customHostname->length) {
  319. char discoveryUrl[256];
  320. #ifndef _MSC_VER
  321. du.length = (size_t)snprintf(discoveryUrl, 255, "opc.tcp://%.*s:%d/",
  322. (int)customHostname->length,
  323. customHostname->data,
  324. layer->port);
  325. #else
  326. du.length = (size_t)_snprintf_s(discoveryUrl, 255, _TRUNCATE,
  327. "opc.tcp://%.*s:%d/",
  328. (int)customHostname->length,
  329. customHostname->data,
  330. layer->port);
  331. #endif
  332. du.data = (UA_Byte*)discoveryUrl;
  333. }else{
  334. char hostname[256];
  335. if(gethostname(hostname, 255) == 0) {
  336. char discoveryUrl[256];
  337. #ifndef _MSC_VER
  338. du.length = (size_t)snprintf(discoveryUrl, 255, "opc.tcp://%s:%d/",
  339. hostname, layer->port);
  340. #else
  341. du.length = (size_t)_snprintf_s(discoveryUrl, 255, _TRUNCATE,
  342. "opc.tcp://%s:%d/", hostname,
  343. layer->port);
  344. #endif
  345. du.data = (UA_Byte*)discoveryUrl;
  346. }
  347. }
  348. UA_String_copy(&du, &nl->discoveryUrl);
  349. /* Get addrinfo of the server and create server sockets */
  350. char portno[6];
  351. #ifndef _MSC_VER
  352. snprintf(portno, 6, "%d", layer->port);
  353. #else
  354. _snprintf_s(portno, 6, _TRUNCATE, "%d", layer->port);
  355. #endif
  356. struct addrinfo hints, *res;
  357. memset(&hints, 0, sizeof hints);
  358. hints.ai_family = AF_UNSPEC;
  359. hints.ai_socktype = SOCK_STREAM;
  360. hints.ai_flags = AI_PASSIVE;
  361. #if defined(UA_FREERTOS)
  362. hints.ai_protocol = IPPROTO_TCP;
  363. char hostname[] = UA_FREERTOS_HOSTNAME;
  364. if(getaddrinfo(hostname, portno, &hints, &res) != 0)
  365. #else
  366. if(getaddrinfo(NULL, portno, &hints, &res) != 0)
  367. #endif
  368. return UA_STATUSCODE_BADINTERNALERROR;
  369. /* There might be serveral addrinfos (for different network cards,
  370. * IPv4/IPv6). Add a server socket for all of them. */
  371. struct addrinfo *ai = res;
  372. for(layer->serverSocketsSize = 0;
  373. layer->serverSocketsSize < FD_SETSIZE && ai != NULL;
  374. ai = ai->ai_next)
  375. addServerSocket(layer, ai);
  376. freeaddrinfo(res);
  377. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  378. "TCP network layer listening on %.*s",
  379. (int)nl->discoveryUrl.length, nl->discoveryUrl.data);
  380. return UA_STATUSCODE_GOOD;
  381. }
  382. /* After every select, reset the sockets to listen on */
  383. static UA_Int32
  384. setFDSet(ServerNetworkLayerTCP *layer, fd_set *fdset) {
  385. FD_ZERO(fdset);
  386. UA_Int32 highestfd = 0;
  387. for(UA_UInt16 i = 0; i < layer->serverSocketsSize; i++) {
  388. UA_fd_set(layer->serverSockets[i], fdset);
  389. if(layer->serverSockets[i] > highestfd)
  390. highestfd = layer->serverSockets[i];
  391. }
  392. ConnectionEntry *e;
  393. LIST_FOREACH(e, &layer->connections, pointers) {
  394. UA_fd_set(e->connection.sockfd, fdset);
  395. if(e->connection.sockfd > highestfd)
  396. highestfd = e->connection.sockfd;
  397. }
  398. return highestfd;
  399. }
  400. static UA_StatusCode
  401. ServerNetworkLayerTCP_listen(UA_ServerNetworkLayer *nl, UA_Server *server,
  402. UA_UInt16 timeout) {
  403. /* Every open socket can generate two jobs */
  404. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  405. if (layer->serverSocketsSize == 0)
  406. return UA_STATUSCODE_GOOD;
  407. /* Listen on open sockets (including the server) */
  408. fd_set fdset, errset;
  409. UA_Int32 highestfd = setFDSet(layer, &fdset);
  410. setFDSet(layer, &errset);
  411. struct timeval tmptv = {0, timeout * 1000};
  412. if (select(highestfd+1, &fdset, NULL, &errset, &tmptv) < 0) {
  413. UA_LOG_SOCKET_ERRNO_WRAP(
  414. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  415. "Socket select failed with %s", errno_str));
  416. // we will retry, so do not return bad
  417. return UA_STATUSCODE_GOOD;
  418. }
  419. /* Accept new connections via the server sockets */
  420. for(UA_UInt16 i = 0; i < layer->serverSocketsSize; i++) {
  421. if(!UA_fd_isset(layer->serverSockets[i], &fdset))
  422. continue;
  423. struct sockaddr_storage remote;
  424. socklen_t remote_size = sizeof(remote);
  425. SOCKET newsockfd = accept((SOCKET)layer->serverSockets[i],
  426. (struct sockaddr*)&remote, &remote_size);
  427. #ifdef _WIN32
  428. if(newsockfd == INVALID_SOCKET)
  429. #else
  430. if(newsockfd < 0)
  431. #endif
  432. continue;
  433. UA_LOG_TRACE(layer->logger, UA_LOGCATEGORY_NETWORK,
  434. "Connection %i | New TCP connection on server socket %i",
  435. (int)newsockfd, layer->serverSockets[i]);
  436. ServerNetworkLayerTCP_add(layer, (UA_Int32)newsockfd, &remote);
  437. }
  438. /* Read from established sockets */
  439. ConnectionEntry *e, *e_tmp;
  440. UA_DateTime now = UA_DateTime_nowMonotonic();
  441. LIST_FOREACH_SAFE(e, &layer->connections, pointers, e_tmp) {
  442. if ((e->connection.state == UA_CONNECTION_OPENING) &&
  443. (now > (e->connection.openingDate + (NOHELLOTIMEOUT * UA_DATETIME_MSEC)))){
  444. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  445. "Connection %i | Closed by the server (no Hello Message)",
  446. e->connection.sockfd);
  447. LIST_REMOVE(e, pointers);
  448. CLOSESOCKET(e->connection.sockfd);
  449. UA_Server_removeConnection(server, &e->connection);
  450. continue;
  451. }
  452. if(!UA_fd_isset(e->connection.sockfd, &errset) &&
  453. !UA_fd_isset(e->connection.sockfd, &fdset))
  454. continue;
  455. UA_LOG_TRACE(layer->logger, UA_LOGCATEGORY_NETWORK,
  456. "Connection %i | Activity on the socket",
  457. e->connection.sockfd);
  458. UA_ByteString buf = UA_BYTESTRING_NULL;
  459. UA_StatusCode retval = connection_recv(&e->connection, &buf, 0);
  460. if(retval == UA_STATUSCODE_GOOD) {
  461. /* Process packets */
  462. UA_Server_processBinaryMessage(server, &e->connection, &buf);
  463. connection_releaserecvbuffer(&e->connection, &buf);
  464. } else if(retval == UA_STATUSCODE_BADCONNECTIONCLOSED) {
  465. /* The socket is shutdown but not closed */
  466. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  467. "Connection %i | Closed",
  468. e->connection.sockfd);
  469. LIST_REMOVE(e, pointers);
  470. CLOSESOCKET(e->connection.sockfd);
  471. UA_Server_removeConnection(server, &e->connection);
  472. }
  473. }
  474. return UA_STATUSCODE_GOOD;
  475. }
  476. static void
  477. ServerNetworkLayerTCP_stop(UA_ServerNetworkLayer *nl, UA_Server *server) {
  478. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  479. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  480. "Shutting down the TCP network layer");
  481. /* Close the server sockets */
  482. for(UA_UInt16 i = 0; i < layer->serverSocketsSize; i++) {
  483. shutdown((SOCKET)layer->serverSockets[i], 2);
  484. CLOSESOCKET(layer->serverSockets[i]);
  485. }
  486. layer->serverSocketsSize = 0;
  487. /* Close open connections */
  488. ConnectionEntry *e;
  489. LIST_FOREACH(e, &layer->connections, pointers)
  490. ServerNetworkLayerTCP_close(&e->connection);
  491. /* Run recv on client sockets. This picks up the closed sockets and frees
  492. * the connection. */
  493. ServerNetworkLayerTCP_listen(nl, server, 0);
  494. #ifdef _WIN32
  495. WSACleanup();
  496. #endif
  497. }
  498. /* run only when the server is stopped */
  499. static void
  500. ServerNetworkLayerTCP_deleteMembers(UA_ServerNetworkLayer *nl) {
  501. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  502. UA_String_deleteMembers(&nl->discoveryUrl);
  503. /* Hard-close and remove remaining connections. The server is no longer
  504. * running. So this is safe. */
  505. ConnectionEntry *e, *e_tmp;
  506. LIST_FOREACH_SAFE(e, &layer->connections, pointers, e_tmp) {
  507. LIST_REMOVE(e, pointers);
  508. CLOSESOCKET(e->connection.sockfd);
  509. UA_free(e);
  510. }
  511. /* Free the layer */
  512. UA_free(layer);
  513. }
  514. UA_ServerNetworkLayer
  515. UA_ServerNetworkLayerTCP(UA_ConnectionConfig conf, UA_UInt16 port, UA_Logger logger) {
  516. UA_ServerNetworkLayer nl;
  517. memset(&nl, 0, sizeof(UA_ServerNetworkLayer));
  518. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP*)
  519. UA_calloc(1,sizeof(ServerNetworkLayerTCP));
  520. if(!layer)
  521. return nl;
  522. layer->logger = (logger != NULL ? logger : UA_Log_Stdout);
  523. layer->conf = conf;
  524. layer->port = port;
  525. nl.handle = layer;
  526. nl.start = ServerNetworkLayerTCP_start;
  527. nl.listen = ServerNetworkLayerTCP_listen;
  528. nl.stop = ServerNetworkLayerTCP_stop;
  529. nl.deleteMembers = ServerNetworkLayerTCP_deleteMembers;
  530. return nl;
  531. }
  532. /***************************/
  533. /* Client NetworkLayer TCP */
  534. /***************************/
  535. static void
  536. ClientNetworkLayerTCP_close(UA_Connection *connection) {
  537. if (connection->state == UA_CONNECTION_CLOSED)
  538. return;
  539. shutdown((SOCKET)connection->sockfd, 2);
  540. CLOSESOCKET(connection->sockfd);
  541. connection->state = UA_CONNECTION_CLOSED;
  542. }
  543. UA_Connection
  544. UA_ClientConnectionTCP(UA_ConnectionConfig conf,
  545. const char *endpointUrl, const UA_UInt32 timeout,
  546. UA_Logger logger) {
  547. #ifdef _WIN32
  548. WORD wVersionRequested;
  549. WSADATA wsaData;
  550. wVersionRequested = MAKEWORD(2, 2);
  551. WSAStartup(wVersionRequested, &wsaData);
  552. #endif
  553. if(logger == NULL) {
  554. logger = UA_Log_Stdout;
  555. }
  556. UA_Connection connection;
  557. memset(&connection, 0, sizeof(UA_Connection));
  558. connection.state = UA_CONNECTION_CLOSED;
  559. connection.localConf = conf;
  560. connection.remoteConf = conf;
  561. connection.send = connection_write;
  562. connection.recv = connection_recv;
  563. connection.close = ClientNetworkLayerTCP_close;
  564. connection.free = NULL;
  565. connection.getSendBuffer = connection_getsendbuffer;
  566. connection.releaseSendBuffer = connection_releasesendbuffer;
  567. connection.releaseRecvBuffer = connection_releaserecvbuffer;
  568. UA_String endpointUrlString = UA_STRING((char*)(uintptr_t)endpointUrl);
  569. UA_String hostnameString = UA_STRING_NULL;
  570. UA_String pathString = UA_STRING_NULL;
  571. UA_UInt16 port = 0;
  572. char hostname[512];
  573. UA_StatusCode parse_retval =
  574. UA_parseEndpointUrl(&endpointUrlString, &hostnameString,
  575. &port, &pathString);
  576. if(parse_retval != UA_STATUSCODE_GOOD || hostnameString.length > 511) {
  577. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  578. "Server url is invalid: %s", endpointUrl);
  579. return connection;
  580. }
  581. memcpy(hostname, hostnameString.data, hostnameString.length);
  582. hostname[hostnameString.length] = 0;
  583. if(port == 0) {
  584. port = 4840;
  585. UA_LOG_INFO(logger, UA_LOGCATEGORY_NETWORK,
  586. "No port defined, using default port %d", port);
  587. }
  588. struct addrinfo hints, *server;
  589. memset(&hints, 0, sizeof(hints));
  590. hints.ai_family = AF_UNSPEC;
  591. hints.ai_socktype = SOCK_STREAM;
  592. #if defined(UA_FREERTOS)
  593. hints.ai_protocol = IPPROTO_TCP;
  594. #endif
  595. char portStr[6];
  596. #ifndef _MSC_VER
  597. snprintf(portStr, 6, "%d", port);
  598. #else
  599. _snprintf_s(portStr, 6, _TRUNCATE, "%d", port);
  600. #endif
  601. int error = getaddrinfo(hostname, portStr, &hints, &server);
  602. if(error != 0 || !server) {
  603. #if !defined(UA_FREERTOS)
  604. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  605. "DNS lookup of %s failed with error %s",
  606. hostname, gai_strerror(error));
  607. #else
  608. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  609. "DNS lookup of %s failed with error",
  610. hostname);
  611. #endif
  612. return connection;
  613. }
  614. UA_Boolean connected = UA_FALSE;
  615. UA_DateTime dtTimeout = timeout * UA_DATETIME_MSEC;
  616. UA_DateTime connStart = UA_DateTime_nowMonotonic();
  617. SOCKET clientsockfd;
  618. /* On linux connect may immediately return with ECONNREFUSED but we still
  619. * want to try to connect. So use a loop and retry until timeout is
  620. * reached. */
  621. do {
  622. /* Get a socket */
  623. clientsockfd = socket(server->ai_family,
  624. server->ai_socktype,
  625. server->ai_protocol);
  626. #ifdef _WIN32
  627. if(clientsockfd == INVALID_SOCKET) {
  628. #else
  629. if(clientsockfd < 0) {
  630. #endif
  631. UA_LOG_SOCKET_ERRNO_WRAP(UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  632. "Could not create client socket: %s", errno_str));
  633. freeaddrinfo(server);
  634. return connection;
  635. }
  636. connection.state = UA_CONNECTION_OPENING;
  637. /* Connect to the server */
  638. connection.sockfd = (UA_Int32) clientsockfd; /* cast for win32 */
  639. /* Non blocking connect to be able to timeout */
  640. if (socket_set_nonblocking(clientsockfd) != UA_STATUSCODE_GOOD) {
  641. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  642. "Could not set the client socket to nonblocking");
  643. ClientNetworkLayerTCP_close(&connection);
  644. freeaddrinfo(server);
  645. return connection;
  646. }
  647. /* Non blocking connect */
  648. error = connect(clientsockfd, server->ai_addr, WIN32_INT server->ai_addrlen);
  649. if ((error == -1) && (errno__ != ERR_CONNECTION_PROGRESS)) {
  650. ClientNetworkLayerTCP_close(&connection);
  651. UA_LOG_SOCKET_ERRNO_WRAP(
  652. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  653. "Connection to %s failed with error: %s",
  654. endpointUrl, errno_str));
  655. freeaddrinfo(server);
  656. return connection;
  657. }
  658. /* Use select to wait and check if connected */
  659. if (error == -1 && (errno__ == ERR_CONNECTION_PROGRESS)) {
  660. /* connection in progress. Wait until connected using select */
  661. UA_DateTime timeSinceStart = UA_DateTime_nowMonotonic() - connStart;
  662. if(timeSinceStart > dtTimeout)
  663. break;
  664. fd_set fdset;
  665. FD_ZERO(&fdset);
  666. UA_fd_set(clientsockfd, &fdset);
  667. UA_DateTime timeout_usec = (dtTimeout - timeSinceStart) / UA_DATETIME_USEC;
  668. struct timeval tmptv = {(long int) (timeout_usec / 1000000),
  669. (long int) (timeout_usec % 1000000)};
  670. int resultsize = select((UA_Int32)(clientsockfd + 1), NULL, &fdset, NULL, &tmptv);
  671. if(resultsize == 1) {
  672. #ifdef _WIN32
  673. /* Windows does not have any getsockopt equivalent and it is not
  674. * needed there */
  675. connected = true;
  676. break;
  677. #else
  678. OPTVAL_TYPE so_error;
  679. socklen_t len = sizeof so_error;
  680. int ret = getsockopt(clientsockfd, SOL_SOCKET, SO_ERROR, &so_error, &len);
  681. if (ret != 0 || so_error != 0) {
  682. /* on connection refused we should still try to connect */
  683. /* connection refused happens on localhost or local ip without timeout */
  684. if (so_error != ECONNREFUSED) {
  685. ClientNetworkLayerTCP_close(&connection);
  686. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  687. "Connection to %s failed with error: %s",
  688. endpointUrl, strerror(ret == 0 ? so_error : errno__));
  689. freeaddrinfo(server);
  690. return connection;
  691. }
  692. /* wait until we try a again. Do not make this too small, otherwise the
  693. * timeout is somehow wrong */
  694. UA_sleep_ms(100);
  695. } else {
  696. connected = true;
  697. break;
  698. }
  699. #endif
  700. }
  701. } else {
  702. connected = true;
  703. break;
  704. }
  705. ClientNetworkLayerTCP_close(&connection);
  706. } while ((UA_DateTime_nowMonotonic() - connStart) < dtTimeout);
  707. freeaddrinfo(server);
  708. if(!connected) {
  709. /* connection timeout */
  710. if (connection.state != UA_CONNECTION_CLOSED)
  711. ClientNetworkLayerTCP_close(&connection);
  712. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  713. "Trying to connect to %s timed out",
  714. endpointUrl);
  715. return connection;
  716. }
  717. /* We are connected. Reset socket to blocking */
  718. if(socket_set_blocking(clientsockfd) != UA_STATUSCODE_GOOD) {
  719. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  720. "Could not set the client socket to blocking");
  721. ClientNetworkLayerTCP_close(&connection);
  722. return connection;
  723. }
  724. #ifdef SO_NOSIGPIPE
  725. int val = 1;
  726. int sso_result = setsockopt(connection.sockfd, SOL_SOCKET,
  727. SO_NOSIGPIPE, (void*)&val, sizeof(val));
  728. if(sso_result < 0)
  729. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  730. "Couldn't set SO_NOSIGPIPE");
  731. #endif
  732. return connection;
  733. }