ua_network_tcp.c 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211
  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. typedef struct TCPClientConnection {
  676. struct addrinfo hints, *server;
  677. UA_DateTime connStart;
  678. char* endpointURL;
  679. UA_UInt32 timeout;
  680. } TCPClientConnection;
  681. /***************************/
  682. /* Client NetworkLayer TCP */
  683. /***************************/
  684. static void
  685. ClientNetworkLayerTCP_close(UA_Connection *connection) {
  686. if (connection->state == UA_CONNECTION_CLOSED)
  687. return;
  688. shutdown((SOCKET)connection->sockfd, 2);
  689. CLOSESOCKET(connection->sockfd);
  690. connection->state = UA_CONNECTION_CLOSED;
  691. }
  692. static void
  693. ClientNetworkLayerTCP_free(UA_Connection *connection) {
  694. if (connection->handle){
  695. TCPClientConnection *tcpConnection = (TCPClientConnection *)connection->handle;
  696. if(tcpConnection->server)
  697. freeaddrinfo(tcpConnection->server);
  698. free(tcpConnection);
  699. }
  700. }
  701. UA_StatusCode UA_ClientConnectionTCP_poll(UA_Client *client, void *data) {
  702. UA_Connection *connection = (UA_Connection*) data;
  703. if (connection->state == UA_CONNECTION_CLOSED)
  704. return UA_STATUSCODE_BADDISCONNECT;
  705. TCPClientConnection *tcpConnection =
  706. (TCPClientConnection*) connection->handle;
  707. UA_DateTime connStart = UA_DateTime_nowMonotonic();
  708. SOCKET clientsockfd;
  709. if (connection->state == UA_CONNECTION_ESTABLISHED) {
  710. UA_Client_removeRepeatedCallback(client, connection->connectCallbackID);
  711. connection->connectCallbackID = 0;
  712. return UA_STATUSCODE_GOOD;
  713. }
  714. if ((UA_Double) (UA_DateTime_nowMonotonic() - tcpConnection->connStart)
  715. > tcpConnection->timeout* UA_DATETIME_MSEC ) {
  716. // connection timeout
  717. ClientNetworkLayerTCP_close(connection);
  718. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  719. "Timed out");
  720. return UA_STATUSCODE_BADDISCONNECT;
  721. }
  722. /* On linux connect may immediately return with ECONNREFUSED but we still want to try to connect */
  723. /* Thus use a loop and retry until timeout is reached */
  724. /* Get a socket */
  725. clientsockfd = socket(tcpConnection->server->ai_family,
  726. tcpConnection->server->ai_socktype,
  727. tcpConnection->server->ai_protocol);
  728. connection->sockfd = (UA_Int32) clientsockfd; /* cast for win32 */
  729. #ifdef _WIN32
  730. if(clientsockfd == INVALID_SOCKET) {
  731. #else
  732. if (clientsockfd < 0) {
  733. #endif
  734. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  735. "Could not create client socket: %s", strerror(errno__));
  736. ClientNetworkLayerTCP_close(connection);
  737. return UA_STATUSCODE_BADDISCONNECT;
  738. }
  739. /* Non blocking connect to be able to timeout */
  740. if (socket_set_nonblocking(clientsockfd) != UA_STATUSCODE_GOOD) {
  741. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  742. "Could not set the client socket to nonblocking");
  743. ClientNetworkLayerTCP_close(connection);
  744. return UA_STATUSCODE_BADDISCONNECT;
  745. }
  746. /* Non blocking connect */
  747. int error = connect(clientsockfd, tcpConnection->server->ai_addr,
  748. WIN32_INT tcpConnection->server->ai_addrlen);
  749. if ((error == -1) && (errno__ != ERR_CONNECTION_PROGRESS)) {
  750. ClientNetworkLayerTCP_close(connection);
  751. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  752. "Connection to failed with error: %s", strerror(errno__));
  753. return UA_STATUSCODE_BADDISCONNECT;
  754. }
  755. /* Use select to wait and check if connected */
  756. if (error == -1 && (errno__ == ERR_CONNECTION_PROGRESS)) {
  757. /* connection in progress. Wait until connected using select */
  758. UA_UInt32 timeSinceStart =
  759. (UA_UInt32) ((UA_Double) (UA_DateTime_nowMonotonic() - connStart)
  760. * UA_DATETIME_MSEC);
  761. fd_set fdset;
  762. FD_ZERO(&fdset);
  763. UA_fd_set(clientsockfd, &fdset);
  764. UA_UInt32 timeout_usec = (tcpConnection->timeout - timeSinceStart)
  765. * 1000;
  766. struct timeval tmptv = { (long int) (timeout_usec / 1000000),
  767. (long int) (timeout_usec % 1000000) };
  768. int resultsize = select((UA_Int32) (clientsockfd + 1), NULL, &fdset,
  769. NULL, &tmptv);
  770. if (resultsize == 1) {
  771. /* Windows does not have any getsockopt equivalent and it is not needed there */
  772. #ifdef _WIN32
  773. connection->sockfd = clientsockfd;
  774. connection->state = UA_CONNECTION_ESTABLISHED;
  775. return UA_STATUSCODE_GOOD;
  776. #else
  777. OPTVAL_TYPE so_error;
  778. socklen_t len = sizeof so_error;
  779. int ret = getsockopt(clientsockfd, SOL_SOCKET, SO_ERROR, &so_error,
  780. &len);
  781. if (ret != 0 || so_error != 0) {
  782. /* on connection refused we should still try to connect */
  783. /* connection refused happens on localhost or local ip without timeout */
  784. if (so_error != ECONNREFUSED) {
  785. // general error
  786. ClientNetworkLayerTCP_close(connection);
  787. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  788. "Connection to failed with error: %s",
  789. strerror(ret == 0 ? so_error : errno__));
  790. return UA_STATUSCODE_BADDISCONNECT;
  791. }
  792. /* wait until we try a again. Do not make this too small, otherwise the
  793. * timeout is somehow wrong */
  794. } else {
  795. connection->state = UA_CONNECTION_ESTABLISHED;
  796. return UA_STATUSCODE_GOOD;
  797. }
  798. #endif
  799. }
  800. } else {
  801. connection->state = UA_CONNECTION_ESTABLISHED;
  802. return UA_STATUSCODE_GOOD;
  803. }
  804. #ifdef SO_NOSIGPIPE
  805. int val = 1;
  806. int sso_result = setsockopt(connection->sockfd, SOL_SOCKET,
  807. SO_NOSIGPIPE, (void*)&val, sizeof(val));
  808. if(sso_result < 0)
  809. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  810. "Couldn't set SO_NOSIGPIPE");
  811. #endif
  812. return UA_STATUSCODE_GOOD;
  813. }
  814. UA_Connection UA_ClientConnectionTCP_init(UA_ConnectionConfig conf,
  815. const char *endpointUrl, const UA_UInt32 timeout,
  816. UA_Logger logger) {
  817. UA_Connection connection;
  818. memset(&connection, 0, sizeof(UA_Connection));
  819. connection.state = UA_CONNECTION_OPENING;
  820. connection.localConf = conf;
  821. connection.remoteConf = conf;
  822. connection.send = connection_write;
  823. connection.recv = connection_recv;
  824. connection.close = ClientNetworkLayerTCP_close;
  825. connection.free = ClientNetworkLayerTCP_free;
  826. connection.getSendBuffer = connection_getsendbuffer;
  827. connection.releaseSendBuffer = connection_releasesendbuffer;
  828. connection.releaseRecvBuffer = connection_releaserecvbuffer;
  829. TCPClientConnection *tcpClientConnection = (TCPClientConnection*) malloc(
  830. sizeof(TCPClientConnection));
  831. connection.handle = (void*) tcpClientConnection;
  832. tcpClientConnection->timeout = timeout;
  833. UA_String endpointUrlString = UA_STRING((char*) (uintptr_t) endpointUrl);
  834. UA_String hostnameString = UA_STRING_NULL;
  835. UA_String pathString = UA_STRING_NULL;
  836. UA_UInt16 port = 0;
  837. char hostname[512];
  838. tcpClientConnection->connStart = UA_DateTime_nowMonotonic();
  839. UA_StatusCode parse_retval = UA_parseEndpointUrl(&endpointUrlString,
  840. &hostnameString, &port, &pathString);
  841. if (parse_retval != UA_STATUSCODE_GOOD || hostnameString.length > 511) {
  842. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  843. "Server url is invalid: %s", endpointUrl);
  844. return connection;
  845. }
  846. memcpy(hostname, hostnameString.data, hostnameString.length);
  847. hostname[hostnameString.length] = 0;
  848. if (port == 0) {
  849. port = 4840;
  850. UA_LOG_INFO(logger, UA_LOGCATEGORY_NETWORK,
  851. "No port defined, using default port %d", port);
  852. }
  853. memset(&tcpClientConnection->hints, 0, sizeof(tcpClientConnection->hints));
  854. tcpClientConnection->hints.ai_family = AF_UNSPEC;
  855. tcpClientConnection->hints.ai_socktype = SOCK_STREAM;
  856. char portStr[6];
  857. #ifndef _MSC_VER
  858. snprintf(portStr, 6, "%d", port);
  859. #else
  860. _snprintf_s(portStr, 6, _TRUNCATE, "%d", port);
  861. #endif
  862. int error = getaddrinfo(hostname, portStr, &tcpClientConnection->hints,
  863. &tcpClientConnection->server);
  864. if (error != 0 || !tcpClientConnection->server) {
  865. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  866. "DNS lookup of %s failed with error %s", hostname,
  867. gai_strerror(error));
  868. return connection;
  869. }
  870. return connection;
  871. }
  872. UA_Connection
  873. UA_ClientConnectionTCP(UA_ConnectionConfig conf,
  874. const char *endpointUrl, const UA_UInt32 timeout,
  875. UA_Logger logger) {
  876. #ifdef _WIN32
  877. WORD wVersionRequested;
  878. WSADATA wsaData;
  879. wVersionRequested = MAKEWORD(2, 2);
  880. WSAStartup(wVersionRequested, &wsaData);
  881. #endif
  882. if(logger == NULL) {
  883. logger = UA_Log_Stdout;
  884. }
  885. UA_Connection connection;
  886. memset(&connection, 0, sizeof(UA_Connection));
  887. connection.state = UA_CONNECTION_CLOSED;
  888. connection.localConf = conf;
  889. connection.remoteConf = conf;
  890. connection.send = connection_write;
  891. connection.recv = connection_recv;
  892. connection.close = ClientNetworkLayerTCP_close;
  893. connection.free = ClientNetworkLayerTCP_free;
  894. connection.getSendBuffer = connection_getsendbuffer;
  895. connection.releaseSendBuffer = connection_releasesendbuffer;
  896. connection.releaseRecvBuffer = connection_releaserecvbuffer;
  897. connection.handle = NULL;
  898. UA_String endpointUrlString = UA_STRING((char*)(uintptr_t)endpointUrl);
  899. UA_String hostnameString = UA_STRING_NULL;
  900. UA_String pathString = UA_STRING_NULL;
  901. UA_UInt16 port = 0;
  902. char hostname[512];
  903. UA_StatusCode parse_retval =
  904. UA_parseEndpointUrl(&endpointUrlString, &hostnameString,
  905. &port, &pathString);
  906. if(parse_retval != UA_STATUSCODE_GOOD || hostnameString.length > 511) {
  907. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  908. "Server url is invalid: %s", endpointUrl);
  909. return connection;
  910. }
  911. memcpy(hostname, hostnameString.data, hostnameString.length);
  912. hostname[hostnameString.length] = 0;
  913. if(port == 0) {
  914. port = 4840;
  915. UA_LOG_INFO(logger, UA_LOGCATEGORY_NETWORK,
  916. "No port defined, using default port %d", port);
  917. }
  918. struct addrinfo hints, *server;
  919. memset(&hints, 0, sizeof(hints));
  920. hints.ai_family = AF_UNSPEC;
  921. hints.ai_socktype = SOCK_STREAM;
  922. #if defined(UA_FREERTOS)
  923. hints.ai_protocol = IPPROTO_TCP;
  924. #endif
  925. char portStr[6];
  926. #ifndef _MSC_VER
  927. snprintf(portStr, 6, "%d", port);
  928. #else
  929. _snprintf_s(portStr, 6, _TRUNCATE, "%d", port);
  930. #endif
  931. int error = getaddrinfo(hostname, portStr, &hints, &server);
  932. if(error != 0 || !server) {
  933. #if !defined(UA_FREERTOS)
  934. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  935. "DNS lookup of %s failed with error %s",
  936. hostname, gai_strerror(error));
  937. #else
  938. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  939. "DNS lookup of %s failed with error",
  940. hostname);
  941. #endif
  942. return connection;
  943. }
  944. UA_Boolean connected = UA_FALSE;
  945. UA_DateTime dtTimeout = timeout * UA_DATETIME_MSEC;
  946. UA_DateTime connStart = UA_DateTime_nowMonotonic();
  947. SOCKET clientsockfd;
  948. /* On linux connect may immediately return with ECONNREFUSED but we still
  949. * want to try to connect. So use a loop and retry until timeout is
  950. * reached. */
  951. do {
  952. /* Get a socket */
  953. clientsockfd = socket(server->ai_family,
  954. server->ai_socktype,
  955. server->ai_protocol);
  956. #ifdef _WIN32
  957. if(clientsockfd == INVALID_SOCKET) {
  958. #else
  959. if(clientsockfd < 0) {
  960. #endif
  961. UA_LOG_SOCKET_ERRNO_WRAP(UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  962. "Could not create client socket: %s", errno_str));
  963. freeaddrinfo(server);
  964. return connection;
  965. }
  966. connection.state = UA_CONNECTION_OPENING;
  967. /* Connect to the server */
  968. connection.sockfd = (UA_Int32) clientsockfd; /* cast for win32 */
  969. /* Non blocking connect to be able to timeout */
  970. if (socket_set_nonblocking(clientsockfd) != UA_STATUSCODE_GOOD) {
  971. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  972. "Could not set the client socket to nonblocking");
  973. ClientNetworkLayerTCP_close(&connection);
  974. freeaddrinfo(server);
  975. return connection;
  976. }
  977. /* Non blocking connect */
  978. error = connect(clientsockfd, server->ai_addr, WIN32_INT server->ai_addrlen);
  979. if ((error == -1) && (errno__ != ERR_CONNECTION_PROGRESS)) {
  980. ClientNetworkLayerTCP_close(&connection);
  981. UA_LOG_SOCKET_ERRNO_WRAP(
  982. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  983. "Connection to %s failed with error: %s",
  984. endpointUrl, errno_str));
  985. freeaddrinfo(server);
  986. return connection;
  987. }
  988. /* Use select to wait and check if connected */
  989. if (error == -1 && (errno__ == ERR_CONNECTION_PROGRESS)) {
  990. /* connection in progress. Wait until connected using select */
  991. UA_DateTime timeSinceStart = UA_DateTime_nowMonotonic() - connStart;
  992. if(timeSinceStart > dtTimeout)
  993. break;
  994. fd_set fdset;
  995. FD_ZERO(&fdset);
  996. UA_fd_set(clientsockfd, &fdset);
  997. UA_DateTime timeout_usec = (dtTimeout - timeSinceStart) / UA_DATETIME_USEC;
  998. struct timeval tmptv = {(long int) (timeout_usec / 1000000),
  999. (long int) (timeout_usec % 1000000)};
  1000. int resultsize = select((UA_Int32)(clientsockfd + 1), NULL, &fdset, NULL, &tmptv);
  1001. if(resultsize == 1) {
  1002. #ifdef _WIN32
  1003. /* Windows does not have any getsockopt equivalent and it is not
  1004. * needed there */
  1005. connected = true;
  1006. break;
  1007. #else
  1008. OPTVAL_TYPE so_error;
  1009. socklen_t len = sizeof so_error;
  1010. int ret = getsockopt(clientsockfd, SOL_SOCKET, SO_ERROR, &so_error, &len);
  1011. if (ret != 0 || so_error != 0) {
  1012. /* on connection refused we should still try to connect */
  1013. /* connection refused happens on localhost or local ip without timeout */
  1014. if (so_error != ECONNREFUSED) {
  1015. ClientNetworkLayerTCP_close(&connection);
  1016. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  1017. "Connection to %s failed with error: %s",
  1018. endpointUrl, strerror(ret == 0 ? so_error : errno__));
  1019. freeaddrinfo(server);
  1020. return connection;
  1021. }
  1022. /* wait until we try a again. Do not make this too small, otherwise the
  1023. * timeout is somehow wrong */
  1024. UA_sleep_ms(100);
  1025. } else {
  1026. connected = true;
  1027. break;
  1028. }
  1029. #endif
  1030. }
  1031. } else {
  1032. connected = true;
  1033. break;
  1034. }
  1035. ClientNetworkLayerTCP_close(&connection);
  1036. } while ((UA_DateTime_nowMonotonic() - connStart) < dtTimeout);
  1037. freeaddrinfo(server);
  1038. if(!connected) {
  1039. /* connection timeout */
  1040. if (connection.state != UA_CONNECTION_CLOSED)
  1041. ClientNetworkLayerTCP_close(&connection);
  1042. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  1043. "Trying to connect to %s timed out",
  1044. endpointUrl);
  1045. return connection;
  1046. }
  1047. /* We are connected. Reset socket to blocking */
  1048. if(socket_set_blocking(clientsockfd) != UA_STATUSCODE_GOOD) {
  1049. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  1050. "Could not set the client socket to blocking");
  1051. ClientNetworkLayerTCP_close(&connection);
  1052. return connection;
  1053. }
  1054. #ifdef SO_NOSIGPIPE
  1055. int val = 1;
  1056. int sso_result = setsockopt(connection.sockfd, SOL_SOCKET,
  1057. SO_NOSIGPIPE, (void*)&val, sizeof(val));
  1058. if(sso_result < 0)
  1059. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  1060. "Couldn't set SO_NOSIGPIPE");
  1061. #endif
  1062. return connection;
  1063. }