ua_network_tcp.c 27 KB

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