ua_network_tcp.c 29 KB

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