ua_network_tcp.c 33 KB

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