ua_network_tcp.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  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
  50. * 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. #ifdef 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
  79. * recv on the 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*)UA_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,
  148. NULL, &tmptv);
  149. /* No result */
  150. if(resultsize == 0)
  151. return UA_STATUSCODE_GOOD;
  152. }
  153. /* Get the received packet(s) */
  154. ssize_t ret = recv(connection->sockfd, (char*)response->data,
  155. connection->localConf.recvBufferSize, 0);
  156. /* The remote side closed the connection */
  157. if(ret == 0) {
  158. UA_ByteString_deleteMembers(response);
  159. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  160. }
  161. /* Error case */
  162. if(ret < 0) {
  163. UA_ByteString_deleteMembers(response);
  164. if(errno__ == INTERRUPTED || (timeout > 0) ?
  165. false : (errno__ == EAGAIN || errno__ == WOULDBLOCK))
  166. return UA_STATUSCODE_GOOD; /* statuscode_good but no data -> retry */
  167. connection_close(connection);
  168. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  169. }
  170. /* Set the length of the received buffer */
  171. response->length = (size_t)ret;
  172. return UA_STATUSCODE_GOOD;
  173. }
  174. static UA_StatusCode
  175. socket_set_nonblocking(SOCKET sockfd) {
  176. #ifdef _WIN32
  177. u_long iMode = 1;
  178. if(ioctlsocket(sockfd, FIONBIO, &iMode) != NO_ERROR)
  179. return UA_STATUSCODE_BADINTERNALERROR;
  180. #else
  181. int opts = fcntl(sockfd, F_GETFL);
  182. if(opts < 0 || fcntl(sockfd, F_SETFL, opts|O_NONBLOCK) < 0)
  183. return UA_STATUSCODE_BADINTERNALERROR;
  184. #endif
  185. return UA_STATUSCODE_GOOD;
  186. }
  187. /***************************/
  188. /* Server NetworkLayer TCP */
  189. /***************************/
  190. #define MAXBACKLOG 100
  191. typedef struct ConnectionEntry {
  192. UA_Connection connection;
  193. LIST_ENTRY(ConnectionEntry) pointers;
  194. } ConnectionEntry;
  195. typedef struct {
  196. UA_ConnectionConfig conf;
  197. UA_UInt16 port;
  198. UA_Int32 serverSockets[FD_SETSIZE];
  199. UA_UInt16 serverSocketsSize;
  200. LIST_HEAD(, ConnectionEntry) connections;
  201. } ServerNetworkLayerTCP;
  202. static void
  203. ServerNetworkLayerTCP_freeConnection(UA_Connection *connection) {
  204. UA_Connection_deleteMembers(connection);
  205. UA_free(connection);
  206. }
  207. static UA_StatusCode
  208. ServerNetworkLayerTCP_add(ServerNetworkLayerTCP *layer,
  209. UA_Int32 newsockfd,
  210. struct sockaddr_storage *remote) {
  211. /* Set nonblocking */
  212. socket_set_nonblocking(newsockfd);
  213. /* Do not merge packets on the socket (disable Nagle's algorithm) */
  214. int dummy = 1;
  215. setsockopt(newsockfd, IPPROTO_TCP, TCP_NODELAY,
  216. (const char *)&dummy, sizeof(dummy));
  217. /* Get the peer name for logging */
  218. char remote_name[100];
  219. int res = getnameinfo((struct sockaddr*)remote,
  220. sizeof(struct sockaddr_storage),
  221. remote_name, sizeof(remote_name),
  222. NULL, 0, NI_NUMERICHOST);
  223. if(res == 0) {
  224. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  225. "Connection %i | New connection over TCP from %s",
  226. newsockfd, remote_name);
  227. } else {
  228. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  229. "Connection %i | New connection over TCP, "
  230. "getnameinfo failed with errno %i",
  231. newsockfd, errno__);
  232. }
  233. /* Allocate and initialize the connection */
  234. ConnectionEntry *e = (ConnectionEntry*)UA_malloc(sizeof(ConnectionEntry));
  235. if(!e)
  236. return UA_STATUSCODE_BADOUTOFMEMORY;
  237. UA_Connection *c = &e->connection;
  238. memset(c, 0, sizeof(UA_Connection));
  239. c->sockfd = newsockfd;
  240. c->handle = layer;
  241. c->localConf = layer->conf;
  242. c->remoteConf = layer->conf;
  243. c->send = connection_write;
  244. c->close = connection_close;
  245. c->free = ServerNetworkLayerTCP_freeConnection;
  246. c->getSendBuffer = connection_getsendbuffer;
  247. c->releaseSendBuffer = connection_releasesendbuffer;
  248. c->releaseRecvBuffer = connection_releaserecvbuffer;
  249. c->state = UA_CONNECTION_OPENING;
  250. /* Add to the linked list */
  251. LIST_INSERT_HEAD(&layer->connections, e, pointers);
  252. return UA_STATUSCODE_GOOD;
  253. }
  254. static void
  255. addServerSocket(ServerNetworkLayerTCP *layer, struct addrinfo *ai) {
  256. /* Create the server socket */
  257. SOCKET newsock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
  258. #ifdef _WIN32
  259. if(newsock == INVALID_SOCKET)
  260. #else
  261. if(newsock < 0)
  262. #endif
  263. {
  264. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  265. "Error opening the server socket");
  266. return;
  267. }
  268. /* Some Linux distributions have net.ipv6.bindv6only not activated. So
  269. * sockets can double-bind to IPv4 and IPv6. This leads to problems. Use
  270. * AF_INET6 sockets only for IPv6. */
  271. int optval = 1;
  272. if(ai->ai_family == AF_INET6 &&
  273. setsockopt(newsock, IPPROTO_IPV6, IPV6_V6ONLY,
  274. (const char*)&optval, sizeof(optval)) == -1) {
  275. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  276. "Could not set an IPv6 socket to IPv6 only");
  277. CLOSESOCKET(newsock);
  278. return;
  279. }
  280. if(setsockopt(newsock, SOL_SOCKET, SO_REUSEADDR,
  281. (const char *)&optval, sizeof(optval)) == -1) {
  282. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  283. "Could not make the socket reusable");
  284. CLOSESOCKET(newsock);
  285. return;
  286. }
  287. if(socket_set_nonblocking(newsock) != UA_STATUSCODE_GOOD) {
  288. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  289. "Could not set the server socket to nonblocking");
  290. CLOSESOCKET(newsock);
  291. return;
  292. }
  293. /* Bind socket to address */
  294. if(bind(newsock, ai->ai_addr, WIN32_INT ai->ai_addrlen) < 0) {
  295. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  296. "Error binding a server socket: %i", errno__);
  297. CLOSESOCKET(newsock);
  298. return;
  299. }
  300. /* Start listening */
  301. if(listen(newsock, MAXBACKLOG) < 0) {
  302. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  303. "Error listening on server socket");
  304. CLOSESOCKET(newsock);
  305. return;
  306. }
  307. layer->serverSockets[layer->serverSocketsSize] = (UA_Int32)newsock;
  308. layer->serverSocketsSize++;
  309. }
  310. static UA_StatusCode
  311. ServerNetworkLayerTCP_start(UA_ServerNetworkLayer *nl) {
  312. #ifdef _WIN32
  313. WORD wVersionRequested = MAKEWORD(2, 2);
  314. WSADATA wsaData;
  315. WSAStartup(wVersionRequested, &wsaData);
  316. #endif
  317. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  318. /* Get the discovery url from the hostname */
  319. UA_String du = UA_STRING_NULL;
  320. char hostname[256];
  321. if(gethostname(hostname, 255) == 0) {
  322. char discoveryUrl[256];
  323. #ifndef _MSC_VER
  324. du.length = (size_t)snprintf(discoveryUrl, 255, "opc.tcp://%s:%d",
  325. hostname, layer->port);
  326. #else
  327. du.length = (size_t)_snprintf_s(discoveryUrl, 255, _TRUNCATE,
  328. "opc.tcp://%s:%d", hostname,
  329. layer->port);
  330. #endif
  331. du.data = (UA_Byte*)discoveryUrl;
  332. }
  333. UA_String_copy(&du, &nl->discoveryUrl);
  334. /* Get addrinfo of the server and create server sockets */
  335. char portno[6];
  336. #ifndef _MSC_VER
  337. snprintf(portno, 6, "%d", layer->port);
  338. #else
  339. _snprintf_s(portno, 6, _TRUNCATE, "%d", layer->port);
  340. #endif
  341. struct addrinfo hints, *res;
  342. memset(&hints, 0, sizeof hints);
  343. hints.ai_family = AF_UNSPEC;
  344. hints.ai_socktype = SOCK_STREAM;
  345. hints.ai_flags = AI_PASSIVE;
  346. getaddrinfo(NULL, portno, &hints, &res);
  347. /* There might be serveral addrinfos (for different network cards,
  348. * IPv4/IPv6). Add a server socket for all of them. */
  349. struct addrinfo *ai = res;
  350. for(layer->serverSocketsSize = 0;
  351. layer->serverSocketsSize < FD_SETSIZE && ai != NULL;
  352. ai = ai->ai_next)
  353. addServerSocket(layer, ai);
  354. freeaddrinfo(res);
  355. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  356. "TCP network layer listening on %.*s",
  357. nl->discoveryUrl.length, nl->discoveryUrl.data);
  358. return UA_STATUSCODE_GOOD;
  359. }
  360. /* After every select, reset the sockets to listen on */
  361. static UA_Int32
  362. setFDSet(ServerNetworkLayerTCP *layer, fd_set *fdset) {
  363. FD_ZERO(fdset);
  364. UA_Int32 highestfd = 0;
  365. for(UA_UInt16 i = 0; i < layer->serverSocketsSize; i++) {
  366. UA_fd_set(layer->serverSockets[i], fdset);
  367. if(layer->serverSockets[i] > highestfd)
  368. highestfd = layer->serverSockets[i];
  369. }
  370. ConnectionEntry *e;
  371. LIST_FOREACH(e, &layer->connections, pointers) {
  372. UA_fd_set(e->connection.sockfd, fdset);
  373. if(e->connection.sockfd > highestfd)
  374. highestfd = e->connection.sockfd;
  375. }
  376. return highestfd;
  377. }
  378. static UA_StatusCode
  379. ServerNetworkLayerTCP_listen(UA_ServerNetworkLayer *nl, UA_Server *server,
  380. UA_UInt16 timeout) {
  381. /* Every open socket can generate two jobs */
  382. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  383. /* Listen on open sockets (including the server) */
  384. fd_set fdset, errset;
  385. UA_Int32 highestfd = setFDSet(layer, &fdset);
  386. setFDSet(layer, &errset);
  387. struct timeval tmptv = {0, timeout * 1000};
  388. select(highestfd+1, &fdset, NULL, &errset, &tmptv);
  389. /* Accept new connections via the server sockets */
  390. for(UA_UInt16 i = 0; i < layer->serverSocketsSize; i++) {
  391. if(!UA_fd_isset(layer->serverSockets[i], &fdset))
  392. continue;
  393. struct sockaddr_storage remote;
  394. socklen_t remote_size = sizeof(remote);
  395. SOCKET newsockfd = accept((SOCKET)layer->serverSockets[i],
  396. (struct sockaddr*)&remote, &remote_size);
  397. #ifdef _WIN32
  398. if(newsockfd == INVALID_SOCKET)
  399. #else
  400. if(newsockfd < 0)
  401. #endif
  402. continue;
  403. UA_LOG_TRACE(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  404. "Connection %i | New TCP connection on server socket %i",
  405. newsockfd, layer->serverSockets[i]);
  406. ServerNetworkLayerTCP_add(layer, (UA_Int32)newsockfd, &remote);
  407. }
  408. /* Read from established sockets */
  409. ConnectionEntry *e, *e_tmp;
  410. LIST_FOREACH_SAFE(e, &layer->connections, pointers, e_tmp) {
  411. if(!UA_fd_isset(e->connection.sockfd, &errset) &&
  412. !UA_fd_isset(e->connection.sockfd, &fdset))
  413. continue;
  414. UA_LOG_TRACE(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  415. "Connection %i | Activity on the socket",
  416. e->connection.sockfd);
  417. UA_ByteString buf = UA_BYTESTRING_NULL;
  418. UA_StatusCode retval = connection_recv(&e->connection, &buf, 0);
  419. if(retval == UA_STATUSCODE_GOOD) {
  420. /* Process packets */
  421. UA_Server_processBinaryMessage(server, &e->connection, &buf);
  422. } else if(retval == UA_STATUSCODE_BADCONNECTIONCLOSED) {
  423. /* The socket is shutdown but not closed */
  424. if(e->connection.state != UA_CONNECTION_CLOSED) {
  425. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  426. "Connection %i | Closed by the client",
  427. e->connection.sockfd);
  428. } else {
  429. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  430. "Connection %i | Closed by the server",
  431. e->connection.sockfd);
  432. }
  433. LIST_REMOVE(e, pointers);
  434. CLOSESOCKET(e->connection.sockfd);
  435. UA_Server_removeConnection(server, &e->connection);
  436. }
  437. }
  438. return UA_STATUSCODE_GOOD;
  439. }
  440. static void
  441. ServerNetworkLayerTCP_stop(UA_ServerNetworkLayer *nl, UA_Server *server) {
  442. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  443. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  444. "Shutting down the TCP network layer");
  445. /* Close the server sockets */
  446. for(UA_UInt16 i = 0; i < layer->serverSocketsSize; i++) {
  447. shutdown((SOCKET)layer->serverSockets[i], 2);
  448. CLOSESOCKET(layer->serverSockets[i]);
  449. }
  450. layer->serverSocketsSize = 0;
  451. /* Close open connections */
  452. ConnectionEntry *e;
  453. LIST_FOREACH(e, &layer->connections, pointers)
  454. connection_close(&e->connection);
  455. /* Run recv on client sockets. This picks up the closed sockets and frees
  456. * the connection. */
  457. ServerNetworkLayerTCP_listen(nl, server, 0);
  458. #ifdef _WIN32
  459. WSACleanup();
  460. #endif
  461. }
  462. /* run only when the server is stopped */
  463. static void
  464. ServerNetworkLayerTCP_deleteMembers(UA_ServerNetworkLayer *nl) {
  465. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  466. UA_String_deleteMembers(&nl->discoveryUrl);
  467. /* Hard-close and remove remaining connections. The server is no longer
  468. * running. So this is safe. */
  469. ConnectionEntry *e, *e_tmp;
  470. LIST_FOREACH_SAFE(e, &layer->connections, pointers, e_tmp) {
  471. LIST_REMOVE(e, pointers);
  472. connection_close(&e->connection);
  473. CLOSESOCKET(e->connection.sockfd);
  474. UA_free(e);
  475. }
  476. /* Free the layer */
  477. UA_free(layer);
  478. }
  479. UA_ServerNetworkLayer
  480. UA_ServerNetworkLayerTCP(UA_ConnectionConfig conf, UA_UInt16 port) {
  481. UA_ServerNetworkLayer nl;
  482. memset(&nl, 0, sizeof(UA_ServerNetworkLayer));
  483. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP*)
  484. UA_calloc(1,sizeof(ServerNetworkLayerTCP));
  485. if(!layer)
  486. return nl;
  487. layer->conf = conf;
  488. layer->port = port;
  489. nl.handle = layer;
  490. nl.start = ServerNetworkLayerTCP_start;
  491. nl.listen = ServerNetworkLayerTCP_listen;
  492. nl.stop = ServerNetworkLayerTCP_stop;
  493. nl.deleteMembers = ServerNetworkLayerTCP_deleteMembers;
  494. return nl;
  495. }
  496. /***************************/
  497. /* Client NetworkLayer TCP */
  498. /***************************/
  499. UA_Connection
  500. UA_ClientConnectionTCP(UA_ConnectionConfig conf,
  501. const char *endpointUrl) {
  502. #ifdef _WIN32
  503. WORD wVersionRequested;
  504. WSADATA wsaData;
  505. wVersionRequested = MAKEWORD(2, 2);
  506. WSAStartup(wVersionRequested, &wsaData);
  507. #endif
  508. UA_Connection connection;
  509. memset(&connection, 0, sizeof(UA_Connection));
  510. connection.state = UA_CONNECTION_OPENING;
  511. connection.localConf = conf;
  512. connection.remoteConf = conf;
  513. connection.send = connection_write;
  514. connection.recv = connection_recv;
  515. connection.close = connection_close;
  516. connection.free = NULL;
  517. connection.getSendBuffer = connection_getsendbuffer;
  518. connection.releaseSendBuffer = connection_releasesendbuffer;
  519. connection.releaseRecvBuffer = connection_releaserecvbuffer;
  520. UA_String endpointUrlString = UA_STRING((char*)(uintptr_t)endpointUrl);
  521. UA_String hostnameString = UA_STRING_NULL;
  522. UA_String pathString = UA_STRING_NULL;
  523. UA_UInt16 port = 0;
  524. char hostname[512];
  525. UA_StatusCode parse_retval =
  526. UA_parseEndpointUrl(&endpointUrlString, &hostnameString,
  527. &port, &pathString);
  528. if(parse_retval != UA_STATUSCODE_GOOD || hostnameString.length > 511) {
  529. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  530. "Server url is invalid: %s", endpointUrl);
  531. return connection;
  532. }
  533. memcpy(hostname, hostnameString.data, hostnameString.length);
  534. hostname[hostnameString.length] = 0;
  535. if(port == 0) {
  536. port = 4840;
  537. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  538. "No port defined, using default port %d", port);
  539. }
  540. struct addrinfo hints, *server;
  541. memset(&hints, 0, sizeof(hints));
  542. hints.ai_family = AF_UNSPEC;
  543. hints.ai_socktype = SOCK_STREAM;
  544. char portStr[6];
  545. #ifndef _MSC_VER
  546. snprintf(portStr, 6, "%d", port);
  547. #else
  548. _snprintf_s(portStr, 6, _TRUNCATE, "%d", port);
  549. #endif
  550. int error = getaddrinfo(hostname, portStr, &hints, &server);
  551. if(error != 0 || !server) {
  552. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  553. "DNS lookup of %s failed with error %s",
  554. hostname, gai_strerror(error));
  555. return connection;
  556. }
  557. /* Get a socket */
  558. SOCKET clientsockfd = socket(server->ai_family,
  559. server->ai_socktype,
  560. server->ai_protocol);
  561. #ifdef _WIN32
  562. if(clientsockfd == INVALID_SOCKET) {
  563. #else
  564. if(clientsockfd < 0) {
  565. #endif
  566. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  567. "Could not create client socket");
  568. freeaddrinfo(server);
  569. return connection;
  570. }
  571. /* Connect to the server */
  572. connection.sockfd = (UA_Int32)clientsockfd; /* cast for win32 */
  573. error = connect(clientsockfd, server->ai_addr,
  574. WIN32_INT server->ai_addrlen);
  575. freeaddrinfo(server);
  576. if(error < 0) {
  577. connection_close(&connection);
  578. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  579. "Connection to %s failed with error %d",
  580. endpointUrl, errno__);
  581. return connection;
  582. }
  583. #ifdef SO_NOSIGPIPE
  584. int val = 1;
  585. int sso_result = setsockopt(connection.sockfd, SOL_SOCKET,
  586. SO_NOSIGPIPE, (void*)&val, sizeof(val));
  587. if(sso_result < 0)
  588. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  589. "Couldn't set SO_NOSIGPIPE");
  590. #endif
  591. return connection;
  592. }