ua_network_tcp.c 33 KB

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