ua_network_tcp.c 27 KB

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