ua_network_tcp.c 27 KB

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