ua_network_tcp.c 30 KB

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