ua_network_tcp.c 30 KB

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