ua_network_tcp.c 27 KB

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