ua_network_tcp.c 29 KB

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