ua_network_tcp.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  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,
  237. "Cannot set socket option TCP_NODELAY. Error: %s",
  238. strerror(errno));
  239. return UA_STATUSCODE_BADUNEXPECTEDERROR;
  240. }
  241. /* Get the peer name for logging */
  242. char remote_name[100];
  243. int res = getnameinfo((struct sockaddr*)remote,
  244. sizeof(struct sockaddr_storage),
  245. remote_name, sizeof(remote_name),
  246. NULL, 0, NI_NUMERICHOST);
  247. if(res == 0) {
  248. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  249. "Connection %i | New connection over TCP from %s",
  250. (int)newsockfd, remote_name);
  251. } else {
  252. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  253. "Connection %i | New connection over TCP, "
  254. "getnameinfo failed with errno %i",
  255. (int)newsockfd, errno__);
  256. }
  257. /* Allocate and initialize the connection */
  258. ConnectionEntry *e = (ConnectionEntry*)UA_malloc(sizeof(ConnectionEntry));
  259. if(!e)
  260. return UA_STATUSCODE_BADOUTOFMEMORY;
  261. UA_Connection *c = &e->connection;
  262. memset(c, 0, sizeof(UA_Connection));
  263. c->sockfd = newsockfd;
  264. c->handle = layer;
  265. c->localConf = layer->conf;
  266. c->remoteConf = layer->conf;
  267. c->send = connection_write;
  268. c->close = connection_close;
  269. c->free = ServerNetworkLayerTCP_freeConnection;
  270. c->getSendBuffer = connection_getsendbuffer;
  271. c->releaseSendBuffer = connection_releasesendbuffer;
  272. c->releaseRecvBuffer = connection_releaserecvbuffer;
  273. c->state = UA_CONNECTION_OPENING;
  274. /* Add to the linked list */
  275. LIST_INSERT_HEAD(&layer->connections, e, pointers);
  276. return UA_STATUSCODE_GOOD;
  277. }
  278. static void
  279. addServerSocket(ServerNetworkLayerTCP *layer, struct addrinfo *ai) {
  280. /* Create the server socket */
  281. SOCKET newsock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
  282. #ifdef _WIN32
  283. if(newsock == INVALID_SOCKET)
  284. #else
  285. if(newsock < 0)
  286. #endif
  287. {
  288. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  289. "Error opening the server socket");
  290. return;
  291. }
  292. /* Some Linux distributions have net.ipv6.bindv6only not activated. So
  293. * sockets can double-bind to IPv4 and IPv6. This leads to problems. Use
  294. * AF_INET6 sockets only for IPv6. */
  295. int optval = 1;
  296. if(ai->ai_family == AF_INET6 &&
  297. setsockopt(newsock, IPPROTO_IPV6, IPV6_V6ONLY,
  298. (const char*)&optval, sizeof(optval)) == -1) {
  299. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  300. "Could not set an IPv6 socket to IPv6 only");
  301. CLOSESOCKET(newsock);
  302. return;
  303. }
  304. if(setsockopt(newsock, SOL_SOCKET, SO_REUSEADDR,
  305. (const char *)&optval, sizeof(optval)) == -1) {
  306. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  307. "Could not make the socket reusable");
  308. CLOSESOCKET(newsock);
  309. return;
  310. }
  311. if(socket_set_nonblocking(newsock) != UA_STATUSCODE_GOOD) {
  312. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  313. "Could not set the server socket to nonblocking");
  314. CLOSESOCKET(newsock);
  315. return;
  316. }
  317. /* Bind socket to address */
  318. if(bind(newsock, ai->ai_addr, WIN32_INT ai->ai_addrlen) < 0) {
  319. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  320. "Error binding a server socket: %i", errno__);
  321. CLOSESOCKET(newsock);
  322. return;
  323. }
  324. /* Start listening */
  325. if(listen(newsock, MAXBACKLOG) < 0) {
  326. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  327. "Error listening on server socket");
  328. CLOSESOCKET(newsock);
  329. return;
  330. }
  331. layer->serverSockets[layer->serverSocketsSize] = (UA_Int32)newsock;
  332. layer->serverSocketsSize++;
  333. }
  334. static UA_StatusCode
  335. ServerNetworkLayerTCP_start(UA_ServerNetworkLayer *nl) {
  336. #ifdef _WIN32
  337. WORD wVersionRequested = MAKEWORD(2, 2);
  338. WSADATA wsaData;
  339. WSAStartup(wVersionRequested, &wsaData);
  340. #endif
  341. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  342. /* Get the discovery url from the hostname */
  343. UA_String du = UA_STRING_NULL;
  344. char hostname[256];
  345. if(gethostname(hostname, 255) == 0) {
  346. char discoveryUrl[256];
  347. #ifndef _MSC_VER
  348. du.length = (size_t)snprintf(discoveryUrl, 255, "opc.tcp://%s:%d",
  349. hostname, layer->port);
  350. #else
  351. du.length = (size_t)_snprintf_s(discoveryUrl, 255, _TRUNCATE,
  352. "opc.tcp://%s:%d", hostname,
  353. layer->port);
  354. #endif
  355. du.data = (UA_Byte*)discoveryUrl;
  356. }
  357. UA_String_copy(&du, &nl->discoveryUrl);
  358. /* Get addrinfo of the server and create server sockets */
  359. char portno[6];
  360. #ifndef _MSC_VER
  361. snprintf(portno, 6, "%d", layer->port);
  362. #else
  363. _snprintf_s(portno, 6, _TRUNCATE, "%d", layer->port);
  364. #endif
  365. struct addrinfo hints, *res;
  366. memset(&hints, 0, sizeof hints);
  367. hints.ai_family = AF_UNSPEC;
  368. hints.ai_socktype = SOCK_STREAM;
  369. hints.ai_flags = AI_PASSIVE;
  370. if(getaddrinfo(NULL, portno, &hints, &res) != 0)
  371. return UA_STATUSCODE_BADINTERNALERROR;
  372. /* There might be serveral addrinfos (for different network cards,
  373. * IPv4/IPv6). Add a server socket for all of them. */
  374. struct addrinfo *ai = res;
  375. for(layer->serverSocketsSize = 0;
  376. layer->serverSocketsSize < FD_SETSIZE && ai != NULL;
  377. ai = ai->ai_next)
  378. addServerSocket(layer, ai);
  379. freeaddrinfo(res);
  380. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  381. "TCP network layer listening on %.*s",
  382. (int)nl->discoveryUrl.length, nl->discoveryUrl.data);
  383. return UA_STATUSCODE_GOOD;
  384. }
  385. /* After every select, reset the sockets to listen on */
  386. static UA_Int32
  387. setFDSet(ServerNetworkLayerTCP *layer, fd_set *fdset) {
  388. FD_ZERO(fdset);
  389. UA_Int32 highestfd = 0;
  390. for(UA_UInt16 i = 0; i < layer->serverSocketsSize; i++) {
  391. UA_fd_set(layer->serverSockets[i], fdset);
  392. if(layer->serverSockets[i] > highestfd)
  393. highestfd = layer->serverSockets[i];
  394. }
  395. ConnectionEntry *e;
  396. LIST_FOREACH(e, &layer->connections, pointers) {
  397. UA_fd_set(e->connection.sockfd, fdset);
  398. if(e->connection.sockfd > highestfd)
  399. highestfd = e->connection.sockfd;
  400. }
  401. return highestfd;
  402. }
  403. static UA_StatusCode
  404. ServerNetworkLayerTCP_listen(UA_ServerNetworkLayer *nl, UA_Server *server,
  405. UA_UInt16 timeout) {
  406. /* Every open socket can generate two jobs */
  407. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  408. /* Listen on open sockets (including the server) */
  409. fd_set fdset, errset;
  410. UA_Int32 highestfd = setFDSet(layer, &fdset);
  411. setFDSet(layer, &errset);
  412. struct timeval tmptv = {0, timeout * 1000};
  413. if (select(highestfd+1, &fdset, NULL, &errset, &tmptv) < 0) {
  414. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  415. "Socket select failed with %s", strerror(errno));
  416. }
  417. /* Accept new connections via the server sockets */
  418. for(UA_UInt16 i = 0; i < layer->serverSocketsSize; i++) {
  419. if(!UA_fd_isset(layer->serverSockets[i], &fdset))
  420. continue;
  421. struct sockaddr_storage remote;
  422. socklen_t remote_size = sizeof(remote);
  423. SOCKET newsockfd = accept((SOCKET)layer->serverSockets[i],
  424. (struct sockaddr*)&remote, &remote_size);
  425. #ifdef _WIN32
  426. if(newsockfd == INVALID_SOCKET)
  427. #else
  428. if(newsockfd < 0)
  429. #endif
  430. continue;
  431. UA_LOG_TRACE(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  432. "Connection %i | New TCP connection on server socket %i",
  433. (int)newsockfd, layer->serverSockets[i]);
  434. ServerNetworkLayerTCP_add(layer, (UA_Int32)newsockfd, &remote);
  435. }
  436. /* Read from established sockets */
  437. ConnectionEntry *e, *e_tmp;
  438. LIST_FOREACH_SAFE(e, &layer->connections, pointers, e_tmp) {
  439. if(!UA_fd_isset(e->connection.sockfd, &errset) &&
  440. !UA_fd_isset(e->connection.sockfd, &fdset))
  441. continue;
  442. UA_LOG_TRACE(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  443. "Connection %i | Activity on the socket",
  444. e->connection.sockfd);
  445. UA_ByteString buf = UA_BYTESTRING_NULL;
  446. UA_StatusCode retval = connection_recv(&e->connection, &buf, 0);
  447. if(retval == UA_STATUSCODE_GOOD) {
  448. /* Process packets */
  449. UA_Server_processBinaryMessage(server, &e->connection, &buf);
  450. connection_releaserecvbuffer(&e->connection, &buf);
  451. } else if(retval == UA_STATUSCODE_BADCONNECTIONCLOSED) {
  452. /* The socket is shutdown but not closed */
  453. if(e->connection.state != UA_CONNECTION_CLOSED) {
  454. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  455. "Connection %i | Closed by the client",
  456. e->connection.sockfd);
  457. } else {
  458. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  459. "Connection %i | Closed by the server",
  460. e->connection.sockfd);
  461. }
  462. LIST_REMOVE(e, pointers);
  463. CLOSESOCKET(e->connection.sockfd);
  464. UA_Server_removeConnection(server, &e->connection);
  465. }
  466. }
  467. return UA_STATUSCODE_GOOD;
  468. }
  469. static void
  470. ServerNetworkLayerTCP_stop(UA_ServerNetworkLayer *nl, UA_Server *server) {
  471. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  472. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  473. "Shutting down the TCP network layer");
  474. /* Close the server sockets */
  475. for(UA_UInt16 i = 0; i < layer->serverSocketsSize; i++) {
  476. shutdown((SOCKET)layer->serverSockets[i], 2);
  477. CLOSESOCKET(layer->serverSockets[i]);
  478. }
  479. layer->serverSocketsSize = 0;
  480. /* Close open connections */
  481. ConnectionEntry *e;
  482. LIST_FOREACH(e, &layer->connections, pointers)
  483. connection_close(&e->connection);
  484. /* Run recv on client sockets. This picks up the closed sockets and frees
  485. * the connection. */
  486. ServerNetworkLayerTCP_listen(nl, server, 0);
  487. #ifdef _WIN32
  488. WSACleanup();
  489. #endif
  490. }
  491. /* run only when the server is stopped */
  492. static void
  493. ServerNetworkLayerTCP_deleteMembers(UA_ServerNetworkLayer *nl) {
  494. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  495. UA_String_deleteMembers(&nl->discoveryUrl);
  496. /* Hard-close and remove remaining connections. The server is no longer
  497. * running. So this is safe. */
  498. ConnectionEntry *e, *e_tmp;
  499. LIST_FOREACH_SAFE(e, &layer->connections, pointers, e_tmp) {
  500. LIST_REMOVE(e, pointers);
  501. connection_close(&e->connection);
  502. CLOSESOCKET(e->connection.sockfd);
  503. UA_free(e);
  504. }
  505. /* Free the layer */
  506. UA_free(layer);
  507. }
  508. UA_ServerNetworkLayer
  509. UA_ServerNetworkLayerTCP(UA_ConnectionConfig conf, UA_UInt16 port) {
  510. UA_ServerNetworkLayer nl;
  511. memset(&nl, 0, sizeof(UA_ServerNetworkLayer));
  512. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP*)
  513. UA_calloc(1,sizeof(ServerNetworkLayerTCP));
  514. if(!layer)
  515. return nl;
  516. layer->conf = conf;
  517. layer->port = port;
  518. nl.handle = layer;
  519. nl.start = ServerNetworkLayerTCP_start;
  520. nl.listen = ServerNetworkLayerTCP_listen;
  521. nl.stop = ServerNetworkLayerTCP_stop;
  522. nl.deleteMembers = ServerNetworkLayerTCP_deleteMembers;
  523. return nl;
  524. }
  525. /***************************/
  526. /* Client NetworkLayer TCP */
  527. /***************************/
  528. UA_Connection
  529. UA_ClientConnectionTCP(UA_ConnectionConfig conf,
  530. const char *endpointUrl, const UA_UInt32 timeout) {
  531. #ifdef _WIN32
  532. WORD wVersionRequested;
  533. WSADATA wsaData;
  534. wVersionRequested = MAKEWORD(2, 2);
  535. WSAStartup(wVersionRequested, &wsaData);
  536. #endif
  537. UA_Connection connection;
  538. memset(&connection, 0, sizeof(UA_Connection));
  539. connection.state = UA_CONNECTION_OPENING;
  540. connection.localConf = conf;
  541. connection.remoteConf = conf;
  542. connection.send = connection_write;
  543. connection.recv = connection_recv;
  544. connection.close = connection_close;
  545. connection.free = NULL;
  546. connection.getSendBuffer = connection_getsendbuffer;
  547. connection.releaseSendBuffer = connection_releasesendbuffer;
  548. connection.releaseRecvBuffer = connection_releaserecvbuffer;
  549. UA_String endpointUrlString = UA_STRING((char*)(uintptr_t)endpointUrl);
  550. UA_String hostnameString = UA_STRING_NULL;
  551. UA_String pathString = UA_STRING_NULL;
  552. UA_UInt16 port = 0;
  553. char hostname[512];
  554. UA_StatusCode parse_retval =
  555. UA_parseEndpointUrl(&endpointUrlString, &hostnameString,
  556. &port, &pathString);
  557. if(parse_retval != UA_STATUSCODE_GOOD || hostnameString.length > 511) {
  558. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  559. "Server url is invalid: %s", endpointUrl);
  560. return connection;
  561. }
  562. memcpy(hostname, hostnameString.data, hostnameString.length);
  563. hostname[hostnameString.length] = 0;
  564. if(port == 0) {
  565. port = 4840;
  566. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  567. "No port defined, using default port %d", port);
  568. }
  569. struct addrinfo hints, *server;
  570. memset(&hints, 0, sizeof(hints));
  571. hints.ai_family = AF_UNSPEC;
  572. hints.ai_socktype = SOCK_STREAM;
  573. char portStr[6];
  574. #ifndef _MSC_VER
  575. snprintf(portStr, 6, "%d", port);
  576. #else
  577. _snprintf_s(portStr, 6, _TRUNCATE, "%d", port);
  578. #endif
  579. int error = getaddrinfo(hostname, portStr, &hints, &server);
  580. if(error != 0 || !server) {
  581. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  582. "DNS lookup of %s failed with error %s",
  583. hostname, gai_strerror(error));
  584. return connection;
  585. }
  586. UA_Boolean connected = UA_FALSE;
  587. UA_DateTime connStart = UA_DateTime_nowMonotonic();
  588. SOCKET clientsockfd;
  589. /* On linux connect may immediately return with ECONNREFUSED but we still want to try to connect */
  590. /* Thus use a loop and retry until timeout is reached */
  591. do {
  592. /* Get a socket */
  593. clientsockfd = socket(server->ai_family,
  594. server->ai_socktype,
  595. server->ai_protocol);
  596. #ifdef _WIN32
  597. if(clientsockfd == INVALID_SOCKET) {
  598. #else
  599. if(clientsockfd < 0) {
  600. #endif
  601. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  602. "Could not create client socket: %s", strerror(errno__));
  603. freeaddrinfo(server);
  604. return connection;
  605. }
  606. /* Connect to the server */
  607. connection.sockfd = (UA_Int32) clientsockfd; /* cast for win32 */
  608. /* Non blocking connect to be able to timeout */
  609. if (socket_set_nonblocking(clientsockfd) != UA_STATUSCODE_GOOD) {
  610. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  611. "Could not set the client socket to nonblocking");
  612. connection_close(&connection);
  613. freeaddrinfo(server);
  614. return connection;
  615. }
  616. /* Non blocking connect */
  617. error = connect(clientsockfd, server->ai_addr,
  618. WIN32_INT server->ai_addrlen);
  619. if ((error == -1) && (errno__ != ERR_CONNECTION_PROGRESS)) {
  620. connection_close(&connection);
  621. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  622. "Connection to %s failed with error: %s",
  623. endpointUrl, strerror(errno__));
  624. freeaddrinfo(server);
  625. return connection;
  626. }
  627. /* Use select to wait and check if connected */
  628. if (error == -1 && (errno__ == ERR_CONNECTION_PROGRESS)) {
  629. /* connection in progress. Wait until connected using select */
  630. UA_UInt32 timeSinceStart = (UA_UInt32) ((UA_Double)(UA_DateTime_nowMonotonic() - connStart) * UA_DATETIME_TO_MSEC);
  631. if (timeSinceStart > timeout) {
  632. break;
  633. }
  634. fd_set fdset;
  635. FD_ZERO(&fdset);
  636. UA_fd_set(clientsockfd, &fdset);
  637. UA_UInt32 timeout_usec = (timeout - timeSinceStart) * 1000;
  638. struct timeval tmptv = {(long int) (timeout_usec / 1000000),
  639. (long int) (timeout_usec % 1000000)};
  640. int resultsize = select((UA_Int32)(clientsockfd + 1), NULL, &fdset,
  641. NULL, &tmptv);
  642. if (resultsize == 1) {
  643. /* Windows does not have any getsockopt equivalent and it is not needed there */
  644. #ifdef _WIN32
  645. connected = true;
  646. break;
  647. #else
  648. OPTVAL_TYPE so_error;
  649. socklen_t len = sizeof so_error;
  650. int ret = getsockopt(clientsockfd, SOL_SOCKET, SO_ERROR, &so_error, &len);
  651. if (ret != 0 || so_error != 0) {
  652. /* on connection refused we should still try to connect */
  653. /* connection refused happens on localhost or local ip without timeout */
  654. if (so_error != ECONNREFUSED) {
  655. // general error
  656. connection_close(&connection);
  657. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  658. "Connection to %s failed with error: %s",
  659. endpointUrl, strerror(ret == 0 ? so_error : errno__));
  660. freeaddrinfo(server);
  661. return connection;
  662. }
  663. /* wait until we try a again. Do not make this too small, otherwise the
  664. * timeout is somehow wrong */
  665. UA_sleep_ms(100);
  666. } else {
  667. connected = true;
  668. break;
  669. }
  670. #endif
  671. }
  672. } else {
  673. connected = true;
  674. break;
  675. }
  676. connection_close(&connection);
  677. } while ((UA_Double)(UA_DateTime_nowMonotonic() - connStart)*UA_DATETIME_TO_MSEC < timeout);
  678. freeaddrinfo(server);
  679. if (!connected) {
  680. // connection timeout
  681. connection_close(&connection);
  682. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  683. "Trying to connect to %s timed out",
  684. endpointUrl);
  685. return connection;
  686. }
  687. /* we are connected. Reset socket to blocking */
  688. if(socket_set_blocking(clientsockfd) != UA_STATUSCODE_GOOD) {
  689. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  690. "Could not set the client socket to blocking");
  691. connection_close(&connection);
  692. return connection;
  693. }
  694. #ifdef SO_NOSIGPIPE
  695. int val = 1;
  696. int sso_result = setsockopt(connection.sockfd, SOL_SOCKET,
  697. SO_NOSIGPIPE, (void*)&val, sizeof(val));
  698. if(sso_result < 0)
  699. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  700. "Couldn't set SO_NOSIGPIPE");
  701. #endif
  702. return connection;
  703. }