ua_network_tcp.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  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. #if defined(__MINGW32__) && (!defined(WINVER) || WINVER < 0x501)
  4. /* Assume the target is newer than Windows XP */
  5. # undef WINVER
  6. # undef _WIN32_WINDOWS
  7. # undef _WIN32_WINNT
  8. # define WINVER 0x0501
  9. # define _WIN32_WINDOWS 0x0501
  10. # define _WIN32_WINNT 0x0501
  11. #endif
  12. #include "ua_network_tcp.h"
  13. #include "ua_log_stdout.h"
  14. #include "queue.h"
  15. #include <stdlib.h> // malloc, free
  16. #include <stdio.h> // snprintf
  17. #include <string.h> // memset
  18. #include <errno.h>
  19. #ifdef _WIN32
  20. # include <winsock2.h>
  21. # include <ws2tcpip.h>
  22. # define CLOSESOCKET(S) closesocket((SOCKET)S)
  23. # define ssize_t int
  24. # define WIN32_INT (int)
  25. #else
  26. # define CLOSESOCKET(S) close(S)
  27. # define SOCKET int
  28. # define WIN32_INT
  29. # include <arpa/inet.h>
  30. # include <netinet/in.h>
  31. # include <sys/select.h>
  32. # include <sys/ioctl.h>
  33. # include <fcntl.h>
  34. # include <unistd.h> // read, write, close
  35. # include <netdb.h>
  36. # ifdef __QNX__
  37. # include <sys/socket.h>
  38. # endif
  39. #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
  40. # include <sys/param.h>
  41. # if defined(BSD)
  42. # include<sys/socket.h>
  43. # endif
  44. #endif
  45. # ifndef __CYGWIN__
  46. # include <netinet/tcp.h>
  47. # endif
  48. #endif
  49. /* unsigned int for windows and workaround to a glibc bug */
  50. /* Additionally if GNU_LIBRARY is not defined, it may be using musl libc (e.g. Docker Alpine) */
  51. #if defined(_WIN32) || defined(__OpenBSD__) || \
  52. (defined(__GNU_LIBRARY__) && (__GNU_LIBRARY__ <= 6) && \
  53. (__GLIBC__ <= 2) && (__GLIBC_MINOR__ < 16) || \
  54. !defined(__GNU_LIBRARY__))
  55. # define UA_fd_set(fd, fds) FD_SET((unsigned int)fd, fds)
  56. # define UA_fd_isset(fd, fds) FD_ISSET((unsigned int)fd, fds)
  57. #else
  58. # define UA_fd_set(fd, fds) FD_SET(fd, fds)
  59. # define UA_fd_isset(fd, fds) FD_ISSET(fd, fds)
  60. #endif
  61. #if UNDER_CE
  62. # define errno WSAGetLastError()
  63. #endif
  64. #ifdef _WIN32
  65. #define errno__ WSAGetLastError()
  66. # define INTERRUPTED WSAEINTR
  67. # define WOULDBLOCK WSAEWOULDBLOCK
  68. # define AGAIN WSAEWOULDBLOCK
  69. #else
  70. # define errno__ errno
  71. # define INTERRUPTED EINTR
  72. # define WOULDBLOCK EWOULDBLOCK
  73. # define AGAIN EAGAIN
  74. #endif
  75. /****************************/
  76. /* Generic Socket Functions */
  77. /****************************/
  78. /* This performs only 'shutdown'. 'close' is called after the next recv on the
  79. * socket. */
  80. static void
  81. connection_close(UA_Connection *connection) {
  82. shutdown((SOCKET)connection->sockfd, 2);
  83. connection->state = UA_CONNECTION_CLOSED;
  84. }
  85. static UA_StatusCode
  86. connection_getsendbuffer(UA_Connection *connection,
  87. size_t length, UA_ByteString *buf) {
  88. if(length > connection->remoteConf.recvBufferSize)
  89. return UA_STATUSCODE_BADCOMMUNICATIONERROR;
  90. return UA_ByteString_allocBuffer(buf, length);
  91. }
  92. static void
  93. connection_releasesendbuffer(UA_Connection *connection,
  94. UA_ByteString *buf) {
  95. UA_ByteString_deleteMembers(buf);
  96. }
  97. static void
  98. connection_releaserecvbuffer(UA_Connection *connection,
  99. UA_ByteString *buf) {
  100. UA_ByteString_deleteMembers(buf);
  101. }
  102. static UA_StatusCode
  103. connection_write(UA_Connection *connection, UA_ByteString *buf) {
  104. /* Prevent OS signals when sending to a closed socket */
  105. int flags = 0;
  106. #ifdef MSG_NOSIGNAL
  107. flags |= MSG_NOSIGNAL;
  108. #endif
  109. /* Send the full buffer. This may require several calls to send */
  110. size_t nWritten = 0;
  111. do {
  112. ssize_t n = 0;
  113. do {
  114. size_t bytes_to_send = buf->length - nWritten;
  115. n = send((SOCKET)connection->sockfd,
  116. (const char*)buf->data + nWritten,
  117. WIN32_INT bytes_to_send, flags);
  118. if(n < 0 && errno__ != INTERRUPTED && errno__ != AGAIN) {
  119. connection_close(connection);
  120. UA_ByteString_deleteMembers(buf);
  121. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  122. }
  123. } while(n < 0);
  124. nWritten += (size_t)n;
  125. } while(nWritten < buf->length);
  126. /* Free the buffer */
  127. UA_ByteString_deleteMembers(buf);
  128. return UA_STATUSCODE_GOOD;
  129. }
  130. static UA_StatusCode
  131. connection_recv(UA_Connection *connection, UA_ByteString *response,
  132. UA_UInt32 timeout) {
  133. response->data =
  134. (UA_Byte*)malloc(connection->localConf.recvBufferSize);
  135. if(!response->data) {
  136. response->length = 0;
  137. return UA_STATUSCODE_BADOUTOFMEMORY; /* not enough memory retry */
  138. }
  139. /* Listen on the socket for the given timeout until a message arrives */
  140. if(timeout > 0) {
  141. fd_set fdset;
  142. FD_ZERO(&fdset);
  143. UA_fd_set(connection->sockfd, &fdset);
  144. UA_UInt32 timeout_usec = timeout * 1000;
  145. struct timeval tmptv = {(long int)(timeout_usec / 1000000),
  146. (long int)(timeout_usec % 1000000)};
  147. int resultsize = select(connection->sockfd+1, &fdset, NULL, NULL, &tmptv);
  148. /* No result */
  149. if(resultsize == 0)
  150. return UA_STATUSCODE_GOOD;
  151. }
  152. /* Get the received packet(s) */
  153. ssize_t ret = recv(connection->sockfd, (char*)response->data,
  154. connection->localConf.recvBufferSize, 0);
  155. /* The remote side closed the connection */
  156. if(ret == 0) {
  157. UA_ByteString_deleteMembers(response);
  158. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  159. }
  160. /* Error case */
  161. if(ret < 0) {
  162. UA_ByteString_deleteMembers(response);
  163. if(errno__ == INTERRUPTED || (timeout > 0) ?
  164. false : (errno__ == EAGAIN || errno__ == WOULDBLOCK))
  165. return UA_STATUSCODE_GOOD; /* statuscode_good but no data -> retry */
  166. connection_close(connection);
  167. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  168. }
  169. /* Set the length of the received buffer */
  170. response->length = (size_t)ret;
  171. return UA_STATUSCODE_GOOD;
  172. }
  173. static UA_StatusCode
  174. socket_set_nonblocking(SOCKET sockfd) {
  175. #ifdef _WIN32
  176. u_long iMode = 1;
  177. if(ioctlsocket(sockfd, FIONBIO, &iMode) != NO_ERROR)
  178. return UA_STATUSCODE_BADINTERNALERROR;
  179. #else
  180. int opts = fcntl(sockfd, F_GETFL);
  181. if(opts < 0 || fcntl(sockfd, F_SETFL, opts|O_NONBLOCK) < 0)
  182. return UA_STATUSCODE_BADINTERNALERROR;
  183. #endif
  184. return UA_STATUSCODE_GOOD;
  185. }
  186. /***************************/
  187. /* Server NetworkLayer TCP */
  188. /***************************/
  189. #define MAXBACKLOG 100
  190. typedef struct ConnectionEntry {
  191. UA_Connection connection;
  192. LIST_ENTRY(ConnectionEntry) pointers;
  193. } ConnectionEntry;
  194. typedef struct {
  195. UA_ConnectionConfig conf;
  196. UA_UInt16 port;
  197. UA_Int32 serverSockets[FD_SETSIZE];
  198. UA_UInt16 serverSocketsSize;
  199. LIST_HEAD(, ConnectionEntry) connections;
  200. } ServerNetworkLayerTCP;
  201. static void
  202. ServerNetworkLayerTCP_freeConnection(UA_Connection *connection) {
  203. UA_Connection_deleteMembers(connection);
  204. free(connection);
  205. }
  206. static UA_StatusCode
  207. ServerNetworkLayerTCP_add(ServerNetworkLayerTCP *layer, UA_Int32 newsockfd,
  208. struct sockaddr_storage *remote) {
  209. /* Get the peer name for logging */
  210. char remote_name[100];
  211. if(getnameinfo((struct sockaddr*)remote, sizeof(struct sockaddr_storage), remote_name,
  212. sizeof(remote_name), NULL, 0, 0) == 0) {
  213. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  214. "Connection %i | New connection over TCP from %s",
  215. newsockfd, remote_name);
  216. } else {
  217. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  218. "Connection %i | New connection over TCP, "
  219. "getnameinfo failed with errno %i", newsockfd, errno__);
  220. }
  221. /* Allocate and initialize the connection */
  222. ConnectionEntry *e = (ConnectionEntry*)malloc(sizeof(ConnectionEntry));
  223. if(!e)
  224. return UA_STATUSCODE_BADOUTOFMEMORY;
  225. UA_Connection *c = &e->connection;
  226. memset(c, 0, sizeof(UA_Connection));
  227. c->sockfd = newsockfd;
  228. c->handle = layer;
  229. c->localConf = layer->conf;
  230. c->remoteConf = layer->conf;
  231. c->send = connection_write;
  232. c->close = connection_close;
  233. c->free = ServerNetworkLayerTCP_freeConnection;
  234. c->getSendBuffer = connection_getsendbuffer;
  235. c->releaseSendBuffer = connection_releasesendbuffer;
  236. c->releaseRecvBuffer = connection_releaserecvbuffer;
  237. c->state = UA_CONNECTION_OPENING;
  238. /* Add to the linked list */
  239. LIST_INSERT_HEAD(&layer->connections, e, pointers);
  240. return UA_STATUSCODE_GOOD;
  241. }
  242. static void
  243. addServerSockets(ServerNetworkLayerTCP *layer, struct addrinfo *ai) {
  244. /* There might be serveral addrinfos (for different network cards,
  245. * IPv4/IPv6). Add a server socket for all of them. */
  246. for(layer->serverSocketsSize = 0;
  247. layer->serverSocketsSize < FD_SETSIZE && ai != NULL;
  248. ai = ai->ai_next) {
  249. /* Create the server socket */
  250. SOCKET newsock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
  251. #ifdef _WIN32
  252. if(newsock == INVALID_SOCKET)
  253. #else
  254. if(newsock < 0)
  255. #endif
  256. {
  257. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  258. "Error opening the server socket");
  259. continue;
  260. }
  261. /* Some Linux distributions have net.ipv6.bindv6only not activated. So
  262. * sockets can double-bind to IPv4 and IPv6. This leads to problems. Use
  263. * AF_INET6 sockets only for IPv6. */
  264. int optval = 1;
  265. if(ai->ai_family == AF_INET6 &&
  266. setsockopt(newsock, IPPROTO_IPV6, IPV6_V6ONLY,
  267. (const char*)&optval, sizeof(optval)) == -1) {
  268. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  269. "Could not set an IPv6 socket to IPv6 only");
  270. CLOSESOCKET(newsock);
  271. continue;
  272. }
  273. if(setsockopt(newsock, SOL_SOCKET, SO_REUSEADDR,
  274. (const char *)&optval, sizeof(optval)) == -1) {
  275. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  276. "Could not make the socket reusable");
  277. CLOSESOCKET(newsock);
  278. continue;
  279. }
  280. if(socket_set_nonblocking(newsock) != UA_STATUSCODE_GOOD) {
  281. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  282. "Could not set the server socket to nonblocking");
  283. CLOSESOCKET(newsock);
  284. continue;
  285. }
  286. /* Bind socket to address */
  287. if(bind(newsock, ai->ai_addr, WIN32_INT ai->ai_addrlen) < 0) {
  288. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  289. "Error binding a server socket: %i", errno__);
  290. CLOSESOCKET(newsock);
  291. continue;
  292. }
  293. /* Start listening */
  294. if(listen(newsock, MAXBACKLOG) < 0) {
  295. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  296. "Error listening on server socket");
  297. CLOSESOCKET(newsock);
  298. continue;
  299. }
  300. layer->serverSockets[layer->serverSocketsSize] = (UA_Int32)newsock;
  301. layer->serverSocketsSize++;
  302. }
  303. }
  304. static UA_StatusCode
  305. ServerNetworkLayerTCP_start(UA_ServerNetworkLayer *nl) {
  306. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  307. /* Get the discovery url from the hostname */
  308. UA_String du = UA_STRING_NULL;
  309. char hostname[256];
  310. if(gethostname(hostname, 255) == 0) {
  311. char discoveryUrl[256];
  312. #ifndef _MSC_VER
  313. du.length = (size_t)snprintf(discoveryUrl, 255, "opc.tcp://%s:%d",
  314. hostname, layer->port);
  315. #else
  316. du.length = (size_t)_snprintf_s(discoveryUrl, 255, _TRUNCATE,
  317. "opc.tcp://%s:%d", hostname, layer->port);
  318. #endif
  319. du.data = (UA_Byte*)discoveryUrl;
  320. }
  321. UA_String_copy(&du, &nl->discoveryUrl);
  322. /* Get addrinfo of the server and create server sockets */
  323. char portno[6];
  324. #ifndef _MSC_VER
  325. snprintf(portno, 6, "%d", layer->port);
  326. #else
  327. _snprintf_s(portno, 6, _TRUNCATE, "%d", layer->port);
  328. #endif
  329. struct addrinfo hints, *res;
  330. memset(&hints, 0, sizeof hints);
  331. hints.ai_family = AF_UNSPEC;
  332. hints.ai_socktype = SOCK_STREAM;
  333. hints.ai_flags = AI_PASSIVE;
  334. getaddrinfo(NULL, portno, &hints, &res);
  335. addServerSockets(layer, res);
  336. freeaddrinfo(res);
  337. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  338. "TCP network layer listening on %.*s",
  339. nl->discoveryUrl.length, nl->discoveryUrl.data);
  340. return UA_STATUSCODE_GOOD;
  341. }
  342. /* After every select, reset the sockets to listen on */
  343. static UA_Int32
  344. setFDSet(ServerNetworkLayerTCP *layer, fd_set *fdset) {
  345. FD_ZERO(fdset);
  346. UA_Int32 highestfd = 0;
  347. for(UA_UInt16 i = 0; i < layer->serverSocketsSize; i++) {
  348. UA_fd_set(layer->serverSockets[i], fdset);
  349. if(layer->serverSockets[i] > highestfd)
  350. highestfd = layer->serverSockets[i];
  351. }
  352. ConnectionEntry *e;
  353. LIST_FOREACH(e, &layer->connections, pointers) {
  354. UA_fd_set(e->connection.sockfd, fdset);
  355. if(e->connection.sockfd > highestfd)
  356. highestfd = e->connection.sockfd;
  357. }
  358. return highestfd;
  359. }
  360. static UA_StatusCode
  361. ServerNetworkLayerTCP_listen(UA_ServerNetworkLayer *nl, UA_Server *server,
  362. UA_UInt16 timeout) {
  363. /* Every open socket can generate two jobs */
  364. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  365. /* Listen on open sockets (including the server) */
  366. fd_set fdset, errset;
  367. UA_Int32 highestfd = setFDSet(layer, &fdset);
  368. setFDSet(layer, &errset);
  369. struct timeval tmptv = {0, timeout * 1000};
  370. select(highestfd+1, &fdset, NULL, &errset, &tmptv);
  371. /* Accept new connections via the server sockets */
  372. for(UA_UInt16 i = 0; i < layer->serverSocketsSize; i++) {
  373. if(!UA_fd_isset(layer->serverSockets[i], &fdset))
  374. continue;
  375. struct sockaddr_storage remote;
  376. socklen_t remote_size = sizeof(remote);
  377. SOCKET newsockfd = accept((SOCKET)layer->serverSockets[i],
  378. (struct sockaddr*)&remote, &remote_size);
  379. #ifdef _WIN32
  380. if(newsockfd == INVALID_SOCKET)
  381. #else
  382. if(newsockfd < 0)
  383. #endif
  384. continue;
  385. socket_set_nonblocking(newsockfd);
  386. /* Do not merge packets on the socket (disable Nagle's algorithm) */
  387. int dummy = 1;
  388. setsockopt(newsockfd, IPPROTO_TCP, TCP_NODELAY,
  389. (const char *)&dummy, sizeof(dummy));
  390. ServerNetworkLayerTCP_add(layer, (UA_Int32)newsockfd, &remote);
  391. }
  392. /* Read from established sockets */
  393. ConnectionEntry *e, *e_tmp;
  394. LIST_FOREACH_SAFE(e, &layer->connections, pointers, e_tmp) {
  395. if(!UA_fd_isset(e->connection.sockfd, &errset) &&
  396. !UA_fd_isset(e->connection.sockfd, &fdset))
  397. continue;
  398. UA_ByteString buf = UA_BYTESTRING_NULL;
  399. UA_StatusCode retval = connection_recv(&e->connection, &buf, 0);
  400. if(retval == UA_STATUSCODE_GOOD) {
  401. /* Process packets */
  402. UA_Server_processBinaryMessage(server, &e->connection, &buf);
  403. } else if(retval == UA_STATUSCODE_BADCONNECTIONCLOSED) {
  404. /* The socket is shutdown but not closed */
  405. if(e->connection.state != UA_CONNECTION_CLOSED) {
  406. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  407. "Connection %d was closed by the client",
  408. e->connection.sockfd);
  409. } else {
  410. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  411. "Connection %d was closed by the server",
  412. e->connection.sockfd);
  413. }
  414. LIST_REMOVE(e, pointers);
  415. CLOSESOCKET(e->connection.sockfd);
  416. UA_Server_removeConnection(server, &e->connection);
  417. }
  418. }
  419. return UA_STATUSCODE_GOOD;
  420. }
  421. static void
  422. ServerNetworkLayerTCP_stop(UA_ServerNetworkLayer *nl, UA_Server *server) {
  423. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  424. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  425. "Shutting down the TCP network layer");
  426. /* Close the server sockets */
  427. for(UA_UInt16 i = 0; i < layer->serverSocketsSize; i++) {
  428. shutdown((SOCKET)layer->serverSockets[i], 2);
  429. CLOSESOCKET(layer->serverSockets[i]);
  430. }
  431. layer->serverSocketsSize = 0;
  432. /* Close open connections */
  433. ConnectionEntry *e;
  434. LIST_FOREACH(e, &layer->connections, pointers)
  435. connection_close(&e->connection);
  436. /* Run recv on client sockets. This picks up the closed sockets and frees
  437. * the connection. */
  438. ServerNetworkLayerTCP_listen(nl, server, 0);
  439. #ifdef _WIN32
  440. WSACleanup();
  441. #endif
  442. }
  443. /* run only when the server is stopped */
  444. static void
  445. ServerNetworkLayerTCP_deleteMembers(UA_ServerNetworkLayer *nl) {
  446. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  447. UA_String_deleteMembers(&nl->discoveryUrl);
  448. /* Hard-close and remove remaining connections. The server is no longer
  449. * running. So this is safe. */
  450. ConnectionEntry *e, *e_tmp;
  451. LIST_FOREACH_SAFE(e, &layer->connections, pointers, e_tmp) {
  452. LIST_REMOVE(e, pointers);
  453. connection_close(&e->connection);
  454. CLOSESOCKET(e->connection.sockfd);
  455. free(e);
  456. }
  457. /* Free the layer */
  458. free(layer);
  459. }
  460. UA_ServerNetworkLayer
  461. UA_ServerNetworkLayerTCP(UA_ConnectionConfig conf, UA_UInt16 port) {
  462. #ifdef _WIN32
  463. WORD wVersionRequested;
  464. WSADATA wsaData;
  465. wVersionRequested = MAKEWORD(2, 2);
  466. WSAStartup(wVersionRequested, &wsaData);
  467. #endif
  468. UA_ServerNetworkLayer nl;
  469. memset(&nl, 0, sizeof(UA_ServerNetworkLayer));
  470. ServerNetworkLayerTCP *layer =
  471. (ServerNetworkLayerTCP *)calloc(1,sizeof(ServerNetworkLayerTCP));
  472. if(!layer)
  473. return nl;
  474. layer->conf = conf;
  475. layer->port = port;
  476. nl.handle = layer;
  477. nl.start = ServerNetworkLayerTCP_start;
  478. nl.listen = ServerNetworkLayerTCP_listen;
  479. nl.stop = ServerNetworkLayerTCP_stop;
  480. nl.deleteMembers = ServerNetworkLayerTCP_deleteMembers;
  481. return nl;
  482. }
  483. /***************************/
  484. /* Client NetworkLayer TCP */
  485. /***************************/
  486. UA_Connection
  487. UA_ClientConnectionTCP(UA_ConnectionConfig conf, const char *endpointUrl) {
  488. #ifdef _WIN32
  489. WORD wVersionRequested;
  490. WSADATA wsaData;
  491. wVersionRequested = MAKEWORD(2, 2);
  492. WSAStartup(wVersionRequested, &wsaData);
  493. #endif
  494. UA_Connection connection;
  495. memset(&connection, 0, sizeof(UA_Connection));
  496. connection.state = UA_CONNECTION_OPENING;
  497. connection.localConf = conf;
  498. connection.remoteConf = conf;
  499. connection.send = connection_write;
  500. connection.recv = connection_recv;
  501. connection.close = connection_close;
  502. connection.free = NULL;
  503. connection.getSendBuffer = connection_getsendbuffer;
  504. connection.releaseSendBuffer = connection_releasesendbuffer;
  505. connection.releaseRecvBuffer = connection_releaserecvbuffer;
  506. UA_String endpointUrlString = UA_STRING((char*)(uintptr_t)endpointUrl);
  507. UA_String hostnameString = UA_STRING_NULL;
  508. UA_String pathString = UA_STRING_NULL;
  509. UA_UInt16 port = 0;
  510. char hostname[512];
  511. UA_StatusCode parse_retval =
  512. UA_parseEndpointUrl(&endpointUrlString, &hostnameString, &port, &pathString);
  513. if(parse_retval != UA_STATUSCODE_GOOD || hostnameString.length > 511) {
  514. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  515. "Server url is invalid: %s", endpointUrl);
  516. return connection;
  517. }
  518. memcpy(hostname, hostnameString.data, hostnameString.length);
  519. hostname[hostnameString.length] = 0;
  520. if(port == 0) {
  521. port = 4840;
  522. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  523. "No port defined, using default port %d", port);
  524. }
  525. struct addrinfo hints, *server;
  526. memset(&hints, 0, sizeof(hints));
  527. hints.ai_family = AF_UNSPEC;
  528. hints.ai_socktype = SOCK_STREAM;
  529. char portStr[6];
  530. #ifndef _MSC_VER
  531. snprintf(portStr, 6, "%d", port);
  532. #else
  533. _snprintf_s(portStr, 6, _TRUNCATE, "%d", port);
  534. #endif
  535. int error = getaddrinfo(hostname, portStr, &hints, &server);
  536. if(error != 0 || !server) {
  537. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  538. "DNS lookup of %s failed with error %s",
  539. hostname, gai_strerror(error));
  540. return connection;
  541. }
  542. /* Get a socket */
  543. SOCKET clientsockfd = socket(server->ai_family, server->ai_socktype,
  544. server->ai_protocol);
  545. #ifdef _WIN32
  546. if(clientsockfd == INVALID_SOCKET) {
  547. #else
  548. if(clientsockfd < 0) {
  549. #endif
  550. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  551. "Could not create client socket");
  552. freeaddrinfo(server);
  553. return connection;
  554. }
  555. /* Connect to the server */
  556. connection.sockfd = (UA_Int32)clientsockfd; /* cast for win32 */
  557. error = connect(clientsockfd, server->ai_addr, WIN32_INT server->ai_addrlen);
  558. freeaddrinfo(server);
  559. if(error < 0) {
  560. connection_close(&connection);
  561. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  562. "Connection to %s failed with error %d",
  563. endpointUrl, errno__);
  564. return connection;
  565. }
  566. #ifdef SO_NOSIGPIPE
  567. int val = 1;
  568. int sso_result = setsockopt(connection.sockfd, SOL_SOCKET,
  569. SO_NOSIGPIPE, (void*)&val, sizeof(val));
  570. if(sso_result < 0)
  571. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  572. "Couldn't set SO_NOSIGPIPE");
  573. #endif
  574. return connection;
  575. }