ua_network_tcp.c 41 KB

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