ua_network_tcp.c 22 KB

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