ua_network_tcp.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  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. } else if(retval == UA_STATUSCODE_BADCONNECTIONCLOSED) {
  449. /* The socket is shutdown but not closed */
  450. if(e->connection.state != UA_CONNECTION_CLOSED) {
  451. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  452. "Connection %i | Closed by the client",
  453. e->connection.sockfd);
  454. } else {
  455. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  456. "Connection %i | Closed by the server",
  457. e->connection.sockfd);
  458. }
  459. LIST_REMOVE(e, pointers);
  460. CLOSESOCKET(e->connection.sockfd);
  461. UA_Server_removeConnection(server, &e->connection);
  462. }
  463. }
  464. return UA_STATUSCODE_GOOD;
  465. }
  466. static void
  467. ServerNetworkLayerTCP_stop(UA_ServerNetworkLayer *nl, UA_Server *server) {
  468. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  469. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  470. "Shutting down the TCP network layer");
  471. /* Close the server sockets */
  472. for(UA_UInt16 i = 0; i < layer->serverSocketsSize; i++) {
  473. shutdown((SOCKET)layer->serverSockets[i], 2);
  474. CLOSESOCKET(layer->serverSockets[i]);
  475. }
  476. layer->serverSocketsSize = 0;
  477. /* Close open connections */
  478. ConnectionEntry *e;
  479. LIST_FOREACH(e, &layer->connections, pointers)
  480. connection_close(&e->connection);
  481. /* Run recv on client sockets. This picks up the closed sockets and frees
  482. * the connection. */
  483. ServerNetworkLayerTCP_listen(nl, server, 0);
  484. #ifdef _WIN32
  485. WSACleanup();
  486. #endif
  487. }
  488. /* run only when the server is stopped */
  489. static void
  490. ServerNetworkLayerTCP_deleteMembers(UA_ServerNetworkLayer *nl) {
  491. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  492. UA_String_deleteMembers(&nl->discoveryUrl);
  493. /* Hard-close and remove remaining connections. The server is no longer
  494. * running. So this is safe. */
  495. ConnectionEntry *e, *e_tmp;
  496. LIST_FOREACH_SAFE(e, &layer->connections, pointers, e_tmp) {
  497. LIST_REMOVE(e, pointers);
  498. connection_close(&e->connection);
  499. CLOSESOCKET(e->connection.sockfd);
  500. UA_free(e);
  501. }
  502. /* Free the layer */
  503. UA_free(layer);
  504. }
  505. UA_ServerNetworkLayer
  506. UA_ServerNetworkLayerTCP(UA_ConnectionConfig conf, UA_UInt16 port) {
  507. UA_ServerNetworkLayer nl;
  508. memset(&nl, 0, sizeof(UA_ServerNetworkLayer));
  509. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP*)
  510. UA_calloc(1,sizeof(ServerNetworkLayerTCP));
  511. if(!layer)
  512. return nl;
  513. layer->conf = conf;
  514. layer->port = port;
  515. nl.handle = layer;
  516. nl.start = ServerNetworkLayerTCP_start;
  517. nl.listen = ServerNetworkLayerTCP_listen;
  518. nl.stop = ServerNetworkLayerTCP_stop;
  519. nl.deleteMembers = ServerNetworkLayerTCP_deleteMembers;
  520. return nl;
  521. }
  522. /***************************/
  523. /* Client NetworkLayer TCP */
  524. /***************************/
  525. UA_Connection
  526. UA_ClientConnectionTCP(UA_ConnectionConfig conf,
  527. const char *endpointUrl, const UA_UInt32 timeout) {
  528. #ifdef _WIN32
  529. WORD wVersionRequested;
  530. WSADATA wsaData;
  531. wVersionRequested = MAKEWORD(2, 2);
  532. WSAStartup(wVersionRequested, &wsaData);
  533. #endif
  534. UA_Connection connection;
  535. memset(&connection, 0, sizeof(UA_Connection));
  536. connection.state = UA_CONNECTION_OPENING;
  537. connection.localConf = conf;
  538. connection.remoteConf = conf;
  539. connection.send = connection_write;
  540. connection.recv = connection_recv;
  541. connection.close = connection_close;
  542. connection.free = NULL;
  543. connection.getSendBuffer = connection_getsendbuffer;
  544. connection.releaseSendBuffer = connection_releasesendbuffer;
  545. connection.releaseRecvBuffer = connection_releaserecvbuffer;
  546. UA_String endpointUrlString = UA_STRING((char*)(uintptr_t)endpointUrl);
  547. UA_String hostnameString = UA_STRING_NULL;
  548. UA_String pathString = UA_STRING_NULL;
  549. UA_UInt16 port = 0;
  550. char hostname[512];
  551. UA_StatusCode parse_retval =
  552. UA_parseEndpointUrl(&endpointUrlString, &hostnameString,
  553. &port, &pathString);
  554. if(parse_retval != UA_STATUSCODE_GOOD || hostnameString.length > 511) {
  555. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  556. "Server url is invalid: %s", endpointUrl);
  557. return connection;
  558. }
  559. memcpy(hostname, hostnameString.data, hostnameString.length);
  560. hostname[hostnameString.length] = 0;
  561. if(port == 0) {
  562. port = 4840;
  563. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  564. "No port defined, using default port %d", port);
  565. }
  566. struct addrinfo hints, *server;
  567. memset(&hints, 0, sizeof(hints));
  568. hints.ai_family = AF_UNSPEC;
  569. hints.ai_socktype = SOCK_STREAM;
  570. char portStr[6];
  571. #ifndef _MSC_VER
  572. snprintf(portStr, 6, "%d", port);
  573. #else
  574. _snprintf_s(portStr, 6, _TRUNCATE, "%d", port);
  575. #endif
  576. int error = getaddrinfo(hostname, portStr, &hints, &server);
  577. if(error != 0 || !server) {
  578. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  579. "DNS lookup of %s failed with error %s",
  580. hostname, gai_strerror(error));
  581. return connection;
  582. }
  583. UA_Boolean connected = UA_FALSE;
  584. UA_DateTime connStart = UA_DateTime_nowMonotonic();
  585. SOCKET clientsockfd;
  586. /* On linux connect may immediately return with ECONNREFUSED but we still want to try to connect */
  587. /* Thus use a loop and retry until timeout is reached */
  588. do {
  589. /* Get a socket */
  590. clientsockfd = socket(server->ai_family,
  591. server->ai_socktype,
  592. server->ai_protocol);
  593. #ifdef _WIN32
  594. if(clientsockfd == INVALID_SOCKET) {
  595. #else
  596. if(clientsockfd < 0) {
  597. #endif
  598. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  599. "Could not create client socket: %s", strerror(errno__));
  600. freeaddrinfo(server);
  601. return connection;
  602. }
  603. /* Connect to the server */
  604. connection.sockfd = (UA_Int32) clientsockfd; /* cast for win32 */
  605. /* Non blocking connect to be able to timeout */
  606. if (socket_set_nonblocking(clientsockfd) != UA_STATUSCODE_GOOD) {
  607. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  608. "Could not set the client socket to nonblocking");
  609. connection_close(&connection);
  610. freeaddrinfo(server);
  611. return connection;
  612. }
  613. /* Non blocking connect */
  614. error = connect(clientsockfd, server->ai_addr,
  615. WIN32_INT server->ai_addrlen);
  616. if ((error == -1) && (errno__ != ERR_CONNECTION_PROGRESS)) {
  617. connection_close(&connection);
  618. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  619. "Connection to %s failed with error: %s",
  620. endpointUrl, strerror(errno__));
  621. freeaddrinfo(server);
  622. return connection;
  623. }
  624. /* Use select to wait and check if connected */
  625. if (error == -1 && (errno__ == ERR_CONNECTION_PROGRESS)) {
  626. /* connection in progress. Wait until connected using select */
  627. UA_UInt32 timeSinceStart = (UA_UInt32) ((UA_Double)(UA_DateTime_nowMonotonic() - connStart) * UA_DATETIME_TO_MSEC);
  628. if (timeSinceStart > timeout) {
  629. break;
  630. }
  631. fd_set fdset;
  632. FD_ZERO(&fdset);
  633. UA_fd_set(clientsockfd, &fdset);
  634. UA_UInt32 timeout_usec = (timeout - timeSinceStart) * 1000;
  635. struct timeval tmptv = {(long int) (timeout_usec / 1000000),
  636. (long int) (timeout_usec % 1000000)};
  637. int resultsize = select((UA_Int32)(clientsockfd + 1), NULL, &fdset,
  638. NULL, &tmptv);
  639. if (resultsize == 1) {
  640. /* Windows does not have any getsockopt equivalent and it is not needed there */
  641. #ifdef _WIN32
  642. connected = true;
  643. break;
  644. #else
  645. OPTVAL_TYPE so_error;
  646. socklen_t len = sizeof so_error;
  647. int ret = getsockopt(clientsockfd, SOL_SOCKET, SO_ERROR, &so_error, &len);
  648. if (ret != 0 || so_error != 0) {
  649. /* on connection refused we should still try to connect */
  650. /* connection refused happens on localhost or local ip without timeout */
  651. if (so_error != ECONNREFUSED) {
  652. // general error
  653. connection_close(&connection);
  654. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  655. "Connection to %s failed with error: %s",
  656. endpointUrl, strerror(ret == 0 ? so_error : errno__));
  657. freeaddrinfo(server);
  658. return connection;
  659. }
  660. /* wait until we try a again. Do not make this too small, otherwise the
  661. * timeout is somehow wrong */
  662. UA_sleep_ms(100);
  663. } else {
  664. connected = true;
  665. break;
  666. }
  667. #endif
  668. }
  669. } else {
  670. connected = true;
  671. break;
  672. }
  673. connection_close(&connection);
  674. } while ((UA_Double)(UA_DateTime_nowMonotonic() - connStart)*UA_DATETIME_TO_MSEC < timeout);
  675. freeaddrinfo(server);
  676. if (!connected) {
  677. // connection timeout
  678. connection_close(&connection);
  679. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  680. "Trying to connect to %s timed out",
  681. endpointUrl);
  682. return connection;
  683. }
  684. /* we are connected. Reset socket to blocking */
  685. if(socket_set_blocking(clientsockfd) != UA_STATUSCODE_GOOD) {
  686. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  687. "Could not set the client socket to blocking");
  688. connection_close(&connection);
  689. return connection;
  690. }
  691. #ifdef SO_NOSIGPIPE
  692. int val = 1;
  693. int sso_result = setsockopt(connection.sockfd, SOL_SOCKET,
  694. SO_NOSIGPIPE, (void*)&val, sizeof(val));
  695. if(sso_result < 0)
  696. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  697. "Couldn't set SO_NOSIGPIPE");
  698. #endif
  699. return connection;
  700. }