ua_network_tcp.c 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259
  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. #ifdef _OS9000
  763. /* OS-9 can't use select for checking write sockets.
  764. * Therefore, we need to use connect until success or failed
  765. */
  766. UA_UInt32 timeout_usec = (tcpConnection->timeout - timeSinceStart)
  767. * 1000;
  768. int resultsize = 0;
  769. do {
  770. u_int32 time = 0x80000001;
  771. signal_code sig;
  772. timeout_usec -= 1000000/256; // Sleep 1/256 second
  773. if (timeout_usec < 0)
  774. break;
  775. _os_sleep(&time,&sig);
  776. error = connect(clientsockfd, tcpConnection->server->ai_addr,
  777. WIN32_INT tcpConnection->server->ai_addrlen);
  778. if ((error == -1 && errno__ == EISCONN) || (error == 0))
  779. resultsize = 1;
  780. if (error == -1 && errno__ != EALREADY && errno__ != EINPROGRESS)
  781. break;
  782. }
  783. while(resultsize == 0);
  784. #else
  785. fd_set fdset;
  786. FD_ZERO(&fdset);
  787. UA_fd_set(clientsockfd, &fdset);
  788. UA_UInt32 timeout_usec = (tcpConnection->timeout - timeSinceStart)
  789. * 1000;
  790. struct timeval tmptv = { (long int) (timeout_usec / 1000000),
  791. (long int) (timeout_usec % 1000000) };
  792. int resultsize = select((UA_Int32) (clientsockfd + 1), NULL, &fdset,
  793. NULL, &tmptv);
  794. #endif
  795. if (resultsize == 1) {
  796. /* Windows does not have any getsockopt equivalent and it is not needed there */
  797. #ifdef _WIN32
  798. connection->sockfd = clientsockfd;
  799. connection->state = UA_CONNECTION_ESTABLISHED;
  800. return UA_STATUSCODE_GOOD;
  801. #else
  802. OPTVAL_TYPE so_error;
  803. socklen_t len = sizeof so_error;
  804. int ret = getsockopt(clientsockfd, SOL_SOCKET, SO_ERROR, &so_error,
  805. &len);
  806. if (ret != 0 || so_error != 0) {
  807. /* on connection refused we should still try to connect */
  808. /* connection refused happens on localhost or local ip without timeout */
  809. if (so_error != ECONNREFUSED) {
  810. // general error
  811. ClientNetworkLayerTCP_close(connection);
  812. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  813. "Connection to failed with error: %s",
  814. strerror(ret == 0 ? so_error : errno__));
  815. return UA_STATUSCODE_BADDISCONNECT;
  816. }
  817. /* wait until we try a again. Do not make this too small, otherwise the
  818. * timeout is somehow wrong */
  819. } else {
  820. connection->state = UA_CONNECTION_ESTABLISHED;
  821. return UA_STATUSCODE_GOOD;
  822. }
  823. #endif
  824. }
  825. } else {
  826. connection->state = UA_CONNECTION_ESTABLISHED;
  827. return UA_STATUSCODE_GOOD;
  828. }
  829. #ifdef SO_NOSIGPIPE
  830. int val = 1;
  831. int sso_result = setsockopt(connection->sockfd, SOL_SOCKET,
  832. SO_NOSIGPIPE, (void*)&val, sizeof(val));
  833. if(sso_result < 0)
  834. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  835. "Couldn't set SO_NOSIGPIPE");
  836. #endif
  837. return UA_STATUSCODE_GOOD;
  838. }
  839. UA_Connection UA_ClientConnectionTCP_init(UA_ConnectionConfig conf,
  840. const char *endpointUrl, const UA_UInt32 timeout,
  841. UA_Logger logger) {
  842. UA_Connection connection;
  843. memset(&connection, 0, sizeof(UA_Connection));
  844. connection.state = UA_CONNECTION_OPENING;
  845. connection.localConf = conf;
  846. connection.remoteConf = conf;
  847. connection.send = connection_write;
  848. connection.recv = connection_recv;
  849. connection.close = ClientNetworkLayerTCP_close;
  850. connection.free = ClientNetworkLayerTCP_free;
  851. connection.getSendBuffer = connection_getsendbuffer;
  852. connection.releaseSendBuffer = connection_releasesendbuffer;
  853. connection.releaseRecvBuffer = connection_releaserecvbuffer;
  854. TCPClientConnection *tcpClientConnection = (TCPClientConnection*) malloc(
  855. sizeof(TCPClientConnection));
  856. connection.handle = (void*) tcpClientConnection;
  857. tcpClientConnection->timeout = timeout;
  858. UA_String endpointUrlString = UA_STRING((char*) (uintptr_t) endpointUrl);
  859. UA_String hostnameString = UA_STRING_NULL;
  860. UA_String pathString = UA_STRING_NULL;
  861. UA_UInt16 port = 0;
  862. char hostname[512];
  863. tcpClientConnection->connStart = UA_DateTime_nowMonotonic();
  864. UA_StatusCode parse_retval = UA_parseEndpointUrl(&endpointUrlString,
  865. &hostnameString, &port, &pathString);
  866. if (parse_retval != UA_STATUSCODE_GOOD || hostnameString.length > 511) {
  867. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  868. "Server url is invalid: %s", endpointUrl);
  869. return connection;
  870. }
  871. memcpy(hostname, hostnameString.data, hostnameString.length);
  872. hostname[hostnameString.length] = 0;
  873. if (port == 0) {
  874. port = 4840;
  875. UA_LOG_INFO(logger, UA_LOGCATEGORY_NETWORK,
  876. "No port defined, using default port %d", port);
  877. }
  878. memset(&tcpClientConnection->hints, 0, sizeof(tcpClientConnection->hints));
  879. tcpClientConnection->hints.ai_family = AF_UNSPEC;
  880. tcpClientConnection->hints.ai_socktype = SOCK_STREAM;
  881. char portStr[6];
  882. #ifndef _MSC_VER
  883. snprintf(portStr, 6, "%d", port);
  884. #else
  885. _snprintf_s(portStr, 6, _TRUNCATE, "%d", port);
  886. #endif
  887. int error = getaddrinfo(hostname, portStr, &tcpClientConnection->hints,
  888. &tcpClientConnection->server);
  889. if (error != 0 || !tcpClientConnection->server) {
  890. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  891. "DNS lookup of %s failed with error %s", hostname,
  892. gai_strerror(error));
  893. return connection;
  894. }
  895. return connection;
  896. }
  897. UA_Connection
  898. UA_ClientConnectionTCP(UA_ConnectionConfig conf,
  899. const char *endpointUrl, const UA_UInt32 timeout,
  900. UA_Logger logger) {
  901. #ifdef _WIN32
  902. WORD wVersionRequested;
  903. WSADATA wsaData;
  904. wVersionRequested = MAKEWORD(2, 2);
  905. WSAStartup(wVersionRequested, &wsaData);
  906. #endif
  907. if(logger == NULL) {
  908. logger = UA_Log_Stdout;
  909. }
  910. UA_Connection connection;
  911. memset(&connection, 0, sizeof(UA_Connection));
  912. connection.state = UA_CONNECTION_CLOSED;
  913. connection.localConf = conf;
  914. connection.remoteConf = conf;
  915. connection.send = connection_write;
  916. connection.recv = connection_recv;
  917. connection.close = ClientNetworkLayerTCP_close;
  918. connection.free = ClientNetworkLayerTCP_free;
  919. connection.getSendBuffer = connection_getsendbuffer;
  920. connection.releaseSendBuffer = connection_releasesendbuffer;
  921. connection.releaseRecvBuffer = connection_releaserecvbuffer;
  922. connection.handle = NULL;
  923. UA_String endpointUrlString = UA_STRING((char*)(uintptr_t)endpointUrl);
  924. UA_String hostnameString = UA_STRING_NULL;
  925. UA_String pathString = UA_STRING_NULL;
  926. UA_UInt16 port = 0;
  927. char hostname[512];
  928. UA_StatusCode parse_retval =
  929. UA_parseEndpointUrl(&endpointUrlString, &hostnameString,
  930. &port, &pathString);
  931. if(parse_retval != UA_STATUSCODE_GOOD || hostnameString.length > 511) {
  932. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  933. "Server url is invalid: %s", endpointUrl);
  934. return connection;
  935. }
  936. memcpy(hostname, hostnameString.data, hostnameString.length);
  937. hostname[hostnameString.length] = 0;
  938. if(port == 0) {
  939. port = 4840;
  940. UA_LOG_INFO(logger, UA_LOGCATEGORY_NETWORK,
  941. "No port defined, using default port %d", port);
  942. }
  943. struct addrinfo hints, *server;
  944. memset(&hints, 0, sizeof(hints));
  945. hints.ai_family = AF_UNSPEC;
  946. hints.ai_socktype = SOCK_STREAM;
  947. #if defined(UA_FREERTOS)
  948. hints.ai_protocol = IPPROTO_TCP;
  949. #endif
  950. char portStr[6];
  951. #ifndef _MSC_VER
  952. snprintf(portStr, 6, "%d", port);
  953. #else
  954. _snprintf_s(portStr, 6, _TRUNCATE, "%d", port);
  955. #endif
  956. int error = getaddrinfo(hostname, portStr, &hints, &server);
  957. if(error != 0 || !server) {
  958. #if !defined(UA_FREERTOS)
  959. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  960. "DNS lookup of %s failed with error %s",
  961. hostname, gai_strerror(error));
  962. #else
  963. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  964. "DNS lookup of %s failed with error",
  965. hostname);
  966. #endif
  967. return connection;
  968. }
  969. UA_Boolean connected = UA_FALSE;
  970. UA_DateTime dtTimeout = timeout * UA_DATETIME_MSEC;
  971. UA_DateTime connStart = UA_DateTime_nowMonotonic();
  972. SOCKET clientsockfd;
  973. /* On linux connect may immediately return with ECONNREFUSED but we still
  974. * want to try to connect. So use a loop and retry until timeout is
  975. * reached. */
  976. do {
  977. /* Get a socket */
  978. clientsockfd = socket(server->ai_family,
  979. server->ai_socktype,
  980. server->ai_protocol);
  981. #ifdef _WIN32
  982. if(clientsockfd == INVALID_SOCKET) {
  983. #else
  984. if(clientsockfd < 0) {
  985. #endif
  986. UA_LOG_SOCKET_ERRNO_WRAP(UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  987. "Could not create client socket: %s", errno_str));
  988. freeaddrinfo(server);
  989. return connection;
  990. }
  991. connection.state = UA_CONNECTION_OPENING;
  992. /* Connect to the server */
  993. connection.sockfd = (UA_Int32) clientsockfd; /* cast for win32 */
  994. /* Non blocking connect to be able to timeout */
  995. if (socket_set_nonblocking(clientsockfd) != UA_STATUSCODE_GOOD) {
  996. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  997. "Could not set the client socket to nonblocking");
  998. ClientNetworkLayerTCP_close(&connection);
  999. freeaddrinfo(server);
  1000. return connection;
  1001. }
  1002. /* Non blocking connect */
  1003. error = connect(clientsockfd, server->ai_addr, WIN32_INT server->ai_addrlen);
  1004. if ((error == -1) && (errno__ != ERR_CONNECTION_PROGRESS)) {
  1005. ClientNetworkLayerTCP_close(&connection);
  1006. UA_LOG_SOCKET_ERRNO_WRAP(
  1007. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  1008. "Connection to %s failed with error: %s",
  1009. endpointUrl, errno_str));
  1010. freeaddrinfo(server);
  1011. return connection;
  1012. }
  1013. /* Use select to wait and check if connected */
  1014. if (error == -1 && (errno__ == ERR_CONNECTION_PROGRESS)) {
  1015. /* connection in progress. Wait until connected using select */
  1016. UA_DateTime timeSinceStart = UA_DateTime_nowMonotonic() - connStart;
  1017. if(timeSinceStart > dtTimeout)
  1018. break;
  1019. #ifdef _OS9000
  1020. /* OS-9 can't use select for checking write sockets.
  1021. * Therefore, we need to use connect until success or failed
  1022. */
  1023. UA_DateTime timeout_usec = (dtTimeout - timeSinceStart) / UA_DATETIME_USEC;
  1024. int resultsize = 0;
  1025. do {
  1026. u_int32 time = 0x80000001;
  1027. signal_code sig;
  1028. timeout_usec -= 1000000/256; // Sleep 1/256 second
  1029. if (timeout_usec < 0)
  1030. break;
  1031. _os_sleep(&time,&sig);
  1032. error = connect(clientsockfd, server->ai_addr, WIN32_INT server->ai_addrlen);
  1033. if ((error == -1 && errno__ == EISCONN) || (error == 0))
  1034. resultsize = 1;
  1035. if (error == -1 && errno__ != EALREADY && errno__ != EINPROGRESS)
  1036. break;
  1037. }
  1038. while(resultsize == 0);
  1039. #else
  1040. fd_set fdset;
  1041. FD_ZERO(&fdset);
  1042. UA_fd_set(clientsockfd, &fdset);
  1043. UA_DateTime timeout_usec = (dtTimeout - timeSinceStart) / UA_DATETIME_USEC;
  1044. struct timeval tmptv = {(long int) (timeout_usec / 1000000),
  1045. (long int) (timeout_usec % 1000000)};
  1046. int resultsize = select((UA_Int32)(clientsockfd + 1), NULL, &fdset, NULL, &tmptv);
  1047. #endif
  1048. if(resultsize == 1) {
  1049. #ifdef _WIN32
  1050. /* Windows does not have any getsockopt equivalent and it is not
  1051. * needed there */
  1052. connected = true;
  1053. break;
  1054. #else
  1055. OPTVAL_TYPE so_error;
  1056. socklen_t len = sizeof so_error;
  1057. int ret = getsockopt(clientsockfd, SOL_SOCKET, SO_ERROR, &so_error, &len);
  1058. if (ret != 0 || so_error != 0) {
  1059. /* on connection refused we should still try to connect */
  1060. /* connection refused happens on localhost or local ip without timeout */
  1061. if (so_error != ECONNREFUSED) {
  1062. ClientNetworkLayerTCP_close(&connection);
  1063. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  1064. "Connection to %s failed with error: %s",
  1065. endpointUrl, strerror(ret == 0 ? so_error : errno__));
  1066. freeaddrinfo(server);
  1067. return connection;
  1068. }
  1069. /* wait until we try a again. Do not make this too small, otherwise the
  1070. * timeout is somehow wrong */
  1071. UA_sleep_ms(100);
  1072. } else {
  1073. connected = true;
  1074. break;
  1075. }
  1076. #endif
  1077. }
  1078. } else {
  1079. connected = true;
  1080. break;
  1081. }
  1082. ClientNetworkLayerTCP_close(&connection);
  1083. } while ((UA_DateTime_nowMonotonic() - connStart) < dtTimeout);
  1084. freeaddrinfo(server);
  1085. if(!connected) {
  1086. /* connection timeout */
  1087. if (connection.state != UA_CONNECTION_CLOSED)
  1088. ClientNetworkLayerTCP_close(&connection);
  1089. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  1090. "Trying to connect to %s timed out",
  1091. endpointUrl);
  1092. return connection;
  1093. }
  1094. /* We are connected. Reset socket to blocking */
  1095. if(socket_set_blocking(clientsockfd) != UA_STATUSCODE_GOOD) {
  1096. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  1097. "Could not set the client socket to blocking");
  1098. ClientNetworkLayerTCP_close(&connection);
  1099. return connection;
  1100. }
  1101. #ifdef SO_NOSIGPIPE
  1102. int val = 1;
  1103. int sso_result = setsockopt(connection.sockfd, SOL_SOCKET,
  1104. SO_NOSIGPIPE, (void*)&val, sizeof(val));
  1105. if(sso_result < 0)
  1106. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  1107. "Couldn't set SO_NOSIGPIPE");
  1108. #endif
  1109. return connection;
  1110. }