ua_network_tcp.c 33 KB

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