ua_network_tcp.c 21 KB

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