ua_network_tcp.c 33 KB

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