ua_network_tcp.c 29 KB

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