ua_network_tcp.c 28 KB

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