ua_network_tcp.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  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 "queue.h"
  14. #include <stdlib.h> // malloc, free
  15. #include <stdio.h> // snprintf
  16. #include <string.h> // memset
  17. #include <errno.h>
  18. #if UNDER_CE
  19. #define errno WSAGetLastError()
  20. #endif
  21. #ifdef _WIN32
  22. # ifndef __clang__
  23. # include <malloc.h>
  24. # endif
  25. /* inet_ntoa is deprecated on MSVC but used for compatibility */
  26. # define _WINSOCK_DEPRECATED_NO_WARNINGS
  27. # include <winsock2.h>
  28. # include <ws2tcpip.h>
  29. # define CLOSESOCKET(S) closesocket((SOCKET)S)
  30. # define ssize_t int
  31. # define WIN32_INT (int)
  32. #else
  33. # define CLOSESOCKET(S) close(S)
  34. # define SOCKET int
  35. # define WIN32_INT
  36. # include <arpa/inet.h>
  37. # include <netinet/in.h>
  38. # include <sys/select.h>
  39. # include <sys/ioctl.h>
  40. # include <fcntl.h>
  41. # include <unistd.h> // read, write, close
  42. # include <netdb.h>
  43. # ifdef __QNX__
  44. # include <sys/socket.h>
  45. # endif
  46. #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
  47. # include <sys/param.h>
  48. # if defined(BSD)
  49. # include<sys/socket.h>
  50. # endif
  51. #endif
  52. # ifndef __CYGWIN__
  53. # include <netinet/tcp.h>
  54. # endif
  55. #endif
  56. /* unsigned int for windows and workaround to a glibc bug */
  57. /* Additionally if GNU_LIBRARY is not defined, it may be using musl libc (e.g. Docker Alpine) */
  58. #if defined(_WIN32) || defined(__OpenBSD__) || \
  59. (defined(__GNU_LIBRARY__) && (__GNU_LIBRARY__ <= 6) && \
  60. (__GLIBC__ <= 2) && (__GLIBC_MINOR__ < 16) || \
  61. !defined(__GNU_LIBRARY__))
  62. # define UA_fd_set(fd, fds) FD_SET((unsigned int)fd, fds)
  63. # define UA_fd_isset(fd, fds) FD_ISSET((unsigned int)fd, fds)
  64. #else
  65. # define UA_fd_set(fd, fds) FD_SET(fd, fds)
  66. # define UA_fd_isset(fd, fds) FD_ISSET(fd, fds)
  67. #endif
  68. #ifdef UA_ENABLE_MULTITHREADING
  69. # include <urcu/uatomic.h>
  70. #endif
  71. #ifdef _WIN32
  72. #define errno__ WSAGetLastError()
  73. # define INTERRUPTED WSAEINTR
  74. # define WOULDBLOCK WSAEWOULDBLOCK
  75. # define AGAIN WSAEWOULDBLOCK
  76. #else
  77. # define errno__ errno
  78. # define INTERRUPTED EINTR
  79. # define WOULDBLOCK EWOULDBLOCK
  80. # define AGAIN EAGAIN
  81. #endif
  82. /****************************/
  83. /* Generic Socket Functions */
  84. /****************************/
  85. static void
  86. socket_close(UA_Connection *connection) {
  87. connection->state = UA_CONNECTION_CLOSED;
  88. shutdown((SOCKET)connection->sockfd,2);
  89. CLOSESOCKET(connection->sockfd);
  90. }
  91. static UA_StatusCode
  92. socket_write(UA_Connection *connection, UA_ByteString *buf) {
  93. size_t nWritten = 0;
  94. do {
  95. ssize_t n = 0;
  96. do {
  97. /* If the OS throws EMSGSIZE, force a smaller packet size:
  98. * size_t bytes_to_send = buf->length - nWritten > 1024 ? 1024 : buf->length - nWritten; */
  99. size_t bytes_to_send = buf->length - nWritten;
  100. n = send((SOCKET)connection->sockfd, (const char*)buf->data + nWritten,
  101. WIN32_INT bytes_to_send, 0);
  102. if(n < 0 && errno__ != INTERRUPTED && errno__ != AGAIN) {
  103. connection->close(connection);
  104. socket_close(connection);
  105. UA_ByteString_deleteMembers(buf);
  106. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  107. }
  108. } while(n < 0);
  109. nWritten += (size_t)n;
  110. } while(nWritten < buf->length);
  111. UA_ByteString_deleteMembers(buf);
  112. return UA_STATUSCODE_GOOD;
  113. }
  114. static UA_StatusCode
  115. socket_recv(UA_Connection *connection, UA_ByteString *response, UA_UInt32 timeout) {
  116. response->data = (UA_Byte *)malloc(connection->localConf.recvBufferSize);
  117. if(!response->data) {
  118. response->length = 0;
  119. return UA_STATUSCODE_BADOUTOFMEMORY; /* not enough memory retry */
  120. }
  121. if(timeout > 0) {
  122. /* currently, only the client uses timeouts */
  123. #ifndef _WIN32
  124. UA_UInt32 timeout_usec = timeout * 1000;
  125. # ifdef __APPLE__
  126. struct timeval tmptv = {(long int)(timeout_usec / 1000000), timeout_usec % 1000000};
  127. # else
  128. struct timeval tmptv = {(long int)(timeout_usec / 1000000), (long int)(timeout_usec % 1000000)};
  129. # endif
  130. int ret = setsockopt(connection->sockfd, SOL_SOCKET, SO_RCVTIMEO,
  131. (const char *)&tmptv, sizeof(struct timeval));
  132. #else
  133. DWORD timeout_dw = timeout;
  134. int ret = setsockopt(connection->sockfd, SOL_SOCKET, SO_RCVTIMEO,
  135. (const char*)&timeout_dw, sizeof(DWORD));
  136. #endif
  137. if(0 != ret) {
  138. UA_ByteString_deleteMembers(response);
  139. socket_close(connection);
  140. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  141. }
  142. }
  143. #ifdef __CYGWIN__
  144. /* Workaround for https://cygwin.com/ml/cygwin/2013-07/msg00107.html */
  145. ssize_t ret;
  146. if(timeout > 0) {
  147. fd_set fdset;
  148. FD_ZERO(&fdset);
  149. UA_fd_set(connection->sockfd, &fdset);
  150. UA_UInt32 timeout_usec = timeout * 1000;
  151. struct timeval tmptv = {(long int)(timeout_usec / 1000000),
  152. (long int)(timeout_usec % 1000000)};
  153. int retval = select(connection->sockfd+1, &fdset, NULL, NULL, &tmptv);
  154. if(retval && UA_fd_isset(connection->sockfd, &fdset)) {
  155. ret = recv(connection->sockfd, (char*)response->data,
  156. connection->localConf.recvBufferSize, 0);
  157. } else {
  158. ret = 0;
  159. }
  160. } else {
  161. ret = recv(connection->sockfd, (char*)response->data,
  162. connection->localConf.recvBufferSize, 0);
  163. }
  164. #else
  165. ssize_t ret = recv(connection->sockfd, (char*)response->data,
  166. connection->localConf.recvBufferSize, 0);
  167. #endif
  168. /* server has closed the connection */
  169. if(ret == 0) {
  170. UA_ByteString_deleteMembers(response);
  171. socket_close(connection);
  172. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  173. }
  174. /* error case */
  175. if(ret < 0) {
  176. UA_ByteString_deleteMembers(response);
  177. if(errno__ == INTERRUPTED || (timeout > 0) ?
  178. false : (errno__ == EAGAIN || errno__ == WOULDBLOCK))
  179. return UA_STATUSCODE_GOOD; /* statuscode_good but no data -> retry */
  180. socket_close(connection);
  181. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  182. }
  183. /* default case */
  184. response->length = (size_t)ret;
  185. return UA_STATUSCODE_GOOD;
  186. }
  187. static UA_StatusCode socket_set_nonblocking(SOCKET sockfd) {
  188. #ifdef _WIN32
  189. u_long iMode = 1;
  190. if(ioctlsocket(sockfd, FIONBIO, &iMode) != NO_ERROR)
  191. return UA_STATUSCODE_BADINTERNALERROR;
  192. #else
  193. int opts = fcntl(sockfd, F_GETFL);
  194. if(opts < 0 || fcntl(sockfd, F_SETFL, opts|O_NONBLOCK) < 0)
  195. return UA_STATUSCODE_BADINTERNALERROR;
  196. #endif
  197. return UA_STATUSCODE_GOOD;
  198. }
  199. /***************************/
  200. /* Server NetworkLayer TCP */
  201. /***************************/
  202. /**
  203. * For the multithreaded mode, assume a single thread that periodically "gets
  204. * work" from the network layer. In addition, several worker threads are
  205. * asynchronously calling into the callbacks of the UA_Connection that holds a
  206. * single connection.
  207. *
  208. * Creating a connection: When "GetJobs" encounters a new connection, it creates
  209. * a UA_Connection with the socket information. This is added to the mappings
  210. * array that links sockets to UA_Connection structs.
  211. *
  212. * Reading data: In "GetJobs", we listen on the sockets in the mappings array.
  213. * If data arrives (or the connection closes), a WorkItem is created that
  214. * carries the work and a pointer to the connection.
  215. *
  216. * Closing a connection: Closing can happen in two ways. Either it is triggered
  217. * by the server in an asynchronous callback. Or the connection is close by the
  218. * client and this is detected in "GetJobs". The server needs to do some
  219. * internal cleanups (close attached securechannels, etc.). So even when a
  220. * closed connection is detected in "GetJobs", we trigger the server to close
  221. * the connection (with a WorkItem) and continue from the callback.
  222. *
  223. * - Server calls close-callback: We close the socket, set the connection-state
  224. * to closed and add the connection to a linked list from which it is deleted
  225. * later. The connection cannot be freed right away since other threads might
  226. * still be using it.
  227. *
  228. * - GetJobs: We remove the connection from the mappings array. In the
  229. * non-multithreaded case, the connection is freed. For multithreading, we
  230. * return a workitem that is delayed, i.e. that is called only after all
  231. * workitems created before are finished in all threads. This workitems
  232. * contains a callback that goes through the linked list of connections to be
  233. * freed. */
  234. #define MAXBACKLOG 100
  235. /* UA_Connection is the first element. We can exchange pointers to the first
  236. * element and free the entire structure. */
  237. typedef struct ConnectionEntry {
  238. UA_Connection connection;
  239. LIST_ENTRY(ConnectionEntry) pointers;
  240. } ConnectionEntry;
  241. typedef struct {
  242. UA_ConnectionConfig conf;
  243. UA_UInt16 port;
  244. UA_Logger logger; // Set during start
  245. /* open sockets and connections */
  246. UA_Int32 serversockfd;
  247. LIST_HEAD(, ConnectionEntry) connections;
  248. } ServerNetworkLayerTCP;
  249. static UA_StatusCode
  250. ServerNetworkLayerGetSendBuffer(UA_Connection *connection,
  251. size_t length, UA_ByteString *buf) {
  252. if(length > connection->remoteConf.recvBufferSize)
  253. return UA_STATUSCODE_BADCOMMUNICATIONERROR;
  254. return UA_ByteString_allocBuffer(buf, length);
  255. }
  256. static void
  257. ServerNetworkLayerReleaseSendBuffer(UA_Connection *connection,
  258. UA_ByteString *buf) {
  259. UA_ByteString_deleteMembers(buf);
  260. }
  261. static void
  262. ServerNetworkLayerReleaseRecvBuffer(UA_Connection *connection,
  263. UA_ByteString *buf) {
  264. UA_ByteString_deleteMembers(buf);
  265. }
  266. static void
  267. ServerNetworkLayerTCP_freeConnection(UA_Connection *connection) {
  268. UA_Connection_deleteMembers(connection);
  269. free(connection);
  270. }
  271. /* Callback triggered from the server (any thread). Only "shutdown" here. This
  272. * triggers the select, where the connection is closed and freed in the server's
  273. * mainloop. */
  274. static void
  275. ServerNetworkLayerTCP_closeConnection(UA_Connection *connection) {
  276. connection->state = UA_CONNECTION_CLOSED;
  277. UA_LOG_INFO(((ServerNetworkLayerTCP*)connection->handle)->logger,
  278. UA_LOGCATEGORY_NETWORK,
  279. "Connection %i | Force closing the connection",
  280. connection->sockfd);
  281. shutdown(connection->sockfd, 2);
  282. }
  283. static UA_StatusCode
  284. ServerNetworkLayerTCP_add(ServerNetworkLayerTCP *layer, UA_Int32 newsockfd) {
  285. /* Look up the peer name for logging */
  286. struct sockaddr_in addr;
  287. socklen_t addrlen = sizeof(struct sockaddr_in);
  288. int res = getpeername(newsockfd, (struct sockaddr*)&addr, &addrlen);
  289. if(res == 0) {
  290. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  291. "Connection %i | New connection over TCP from %s:%d",
  292. newsockfd, inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
  293. } else {
  294. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  295. "Connection %i | New connection over TCP, "
  296. "getpeername failed with errno %i", newsockfd, errno);
  297. }
  298. /* Allocate and initialize the connection */
  299. ConnectionEntry *e = (ConnectionEntry*)malloc(sizeof(ConnectionEntry));
  300. if(!e)
  301. return UA_STATUSCODE_BADOUTOFMEMORY;
  302. UA_Connection *c = &e->connection;
  303. memset(c, 0, sizeof(UA_Connection));
  304. c->sockfd = newsockfd;
  305. c->handle = layer;
  306. c->localConf = layer->conf;
  307. c->remoteConf = layer->conf;
  308. c->send = socket_write;
  309. c->close = ServerNetworkLayerTCP_closeConnection;
  310. c->free = ServerNetworkLayerTCP_freeConnection;
  311. c->getSendBuffer = ServerNetworkLayerGetSendBuffer;
  312. c->releaseSendBuffer = ServerNetworkLayerReleaseSendBuffer;
  313. c->releaseRecvBuffer = ServerNetworkLayerReleaseRecvBuffer;
  314. c->state = UA_CONNECTION_OPENING;
  315. /* Add to the linked list */
  316. LIST_INSERT_HEAD(&layer->connections, e, pointers);
  317. return UA_STATUSCODE_GOOD;
  318. }
  319. static UA_StatusCode
  320. ServerNetworkLayerTCP_start(UA_ServerNetworkLayer *nl, UA_Logger logger) {
  321. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  322. layer->logger = logger;
  323. /* get the discovery url from the hostname */
  324. UA_String du = UA_STRING_NULL;
  325. char hostname[256];
  326. if(gethostname(hostname, 255) == 0) {
  327. char discoveryUrl[256];
  328. #ifndef _MSC_VER
  329. du.length = (size_t)snprintf(discoveryUrl, 255, "opc.tcp://%s:%d",
  330. hostname, layer->port);
  331. #else
  332. du.length = (size_t)_snprintf_s(discoveryUrl, 255, _TRUNCATE,
  333. "opc.tcp://%s:%d", hostname, layer->port);
  334. #endif
  335. du.data = (UA_Byte*)discoveryUrl;
  336. }
  337. UA_String_copy(&du, &nl->discoveryUrl);
  338. /* Create the server socket */
  339. SOCKET newsock = socket(AF_INET6, SOCK_STREAM, 0);
  340. #ifdef _WIN32
  341. if(newsock == INVALID_SOCKET)
  342. #else
  343. if(newsock < 0)
  344. #endif
  345. {
  346. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  347. "Error opening the server socket");
  348. return UA_STATUSCODE_BADINTERNALERROR;
  349. }
  350. /* Set socket options */
  351. int optval = 1;
  352. if(setsockopt(newsock, SOL_SOCKET, SO_REUSEADDR,
  353. (const char *)&optval, sizeof(optval)) == -1 ||
  354. socket_set_nonblocking(newsock) != UA_STATUSCODE_GOOD) {
  355. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  356. "Error during setting of server socket options");
  357. CLOSESOCKET(newsock);
  358. return UA_STATUSCODE_BADINTERNALERROR;
  359. }
  360. /* Bind socket to address */
  361. struct sockaddr_in6 serv_addr;
  362. memset(&serv_addr, 0, sizeof(serv_addr));
  363. serv_addr.sin6_family = AF_INET6;
  364. serv_addr.sin6_port = htons(layer->port);
  365. serv_addr.sin6_addr = in6addr_any;
  366. if(bind(newsock, (const struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
  367. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  368. "Error during binding of the server socket");
  369. CLOSESOCKET(newsock);
  370. return UA_STATUSCODE_BADINTERNALERROR;
  371. }
  372. /* Start listening */
  373. if(listen(newsock, MAXBACKLOG) < 0) {
  374. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  375. "Error listening on server socket");
  376. CLOSESOCKET(newsock);
  377. return UA_STATUSCODE_BADINTERNALERROR;
  378. }
  379. layer->serversockfd = (UA_Int32)newsock; /* cast on win32 */
  380. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  381. "TCP network layer listening on %.*s",
  382. nl->discoveryUrl.length, nl->discoveryUrl.data);
  383. return UA_STATUSCODE_GOOD;
  384. }
  385. /* Remove closed connections before going into "listen". Returns whether a
  386. * connection was removed. */
  387. static void
  388. removeClosedConnections(ServerNetworkLayerTCP *layer, UA_Server *server) {
  389. ConnectionEntry *e, *e_tmp;
  390. LIST_FOREACH_SAFE(e, &layer->connections, pointers, e_tmp) {
  391. if(e->connection.state != UA_CONNECTION_CLOSED)
  392. continue;
  393. LIST_REMOVE(e, pointers);
  394. UA_Server_removeConnection(server, &e->connection);
  395. }
  396. }
  397. /* After every select, we need to reset the sockets we want to listen on */
  398. static UA_Int32
  399. setFDSet(ServerNetworkLayerTCP *layer, fd_set *fdset) {
  400. FD_ZERO(fdset);
  401. UA_fd_set(layer->serversockfd, fdset);
  402. UA_Int32 highestfd = layer->serversockfd;
  403. ConnectionEntry *e;
  404. LIST_FOREACH(e, &layer->connections, pointers) {
  405. UA_fd_set(e->connection.sockfd, fdset);
  406. if(e->connection.sockfd > highestfd)
  407. highestfd = e->connection.sockfd;
  408. }
  409. return highestfd;
  410. }
  411. static UA_StatusCode
  412. ServerNetworkLayerTCP_listen(UA_ServerNetworkLayer *nl, UA_Server *server,
  413. UA_UInt16 timeout) {
  414. /* Every open socket can generate two jobs */
  415. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  416. /* Remove closed sockets */
  417. removeClosedConnections(layer, server);
  418. /* Listen on open sockets (including the server) */
  419. fd_set fdset, errset;
  420. UA_Int32 highestfd = setFDSet(layer, &fdset);
  421. setFDSet(layer, &errset);
  422. struct timeval tmptv = {0, timeout * 1000};
  423. UA_Int32 resultsize = select(highestfd+1, &fdset, NULL, &errset, &tmptv);
  424. /* Accept new connection via the server socket (can only be a single one) */
  425. if(UA_fd_isset(layer->serversockfd, &fdset)) {
  426. --resultsize;
  427. SOCKET newsockfd = accept((SOCKET)layer->serversockfd, NULL, NULL);
  428. #ifdef _WIN32
  429. if(newsockfd != INVALID_SOCKET)
  430. #else
  431. if(newsockfd >= 0)
  432. #endif
  433. {
  434. socket_set_nonblocking(newsockfd);
  435. /* Do not merge packets on the socket (disable Nagle's algorithm) */
  436. int i = 1;
  437. setsockopt(newsockfd, IPPROTO_TCP, TCP_NODELAY, (const char *)&i, sizeof(i));
  438. ServerNetworkLayerTCP_add(layer, (UA_Int32)newsockfd);
  439. }
  440. }
  441. /* Read from established sockets */
  442. ConnectionEntry *e, *e_tmp;
  443. LIST_FOREACH_SAFE(e, &layer->connections, pointers, e_tmp) {
  444. UA_ByteString buf = UA_BYTESTRING_NULL;
  445. if(!UA_fd_isset(e->connection.sockfd, &errset) &&
  446. !UA_fd_isset(e->connection.sockfd, &fdset))
  447. continue;
  448. UA_StatusCode retval = socket_recv(&e->connection, &buf, 0);
  449. if(retval == UA_STATUSCODE_GOOD) {
  450. UA_Server_processBinaryMessage(server, &e->connection, &buf);
  451. } else if (retval == UA_STATUSCODE_BADCONNECTIONCLOSED) {
  452. LIST_REMOVE(e, pointers);
  453. UA_Server_removeConnection(server, &e->connection);
  454. }
  455. }
  456. return UA_STATUSCODE_GOOD;
  457. }
  458. static void
  459. ServerNetworkLayerTCP_stop(UA_ServerNetworkLayer *nl, UA_Server *server) {
  460. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  461. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  462. "Shutting down the TCP network layer");
  463. shutdown((SOCKET)layer->serversockfd,2);
  464. CLOSESOCKET(layer->serversockfd);
  465. ConnectionEntry *e, *e_tmp;
  466. LIST_FOREACH_SAFE(e, &layer->connections, pointers, e_tmp) {
  467. LIST_REMOVE(e, pointers);
  468. UA_Server_removeConnection(server, &e->connection);
  469. }
  470. #ifdef _WIN32
  471. WSACleanup();
  472. #endif
  473. }
  474. /* run only when the server is stopped */
  475. static void
  476. ServerNetworkLayerTCP_deleteMembers(UA_ServerNetworkLayer *nl) {
  477. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  478. UA_String_deleteMembers(&nl->discoveryUrl);
  479. UA_free(layer);
  480. }
  481. UA_ServerNetworkLayer
  482. UA_ServerNetworkLayerTCP(UA_ConnectionConfig conf, UA_UInt16 port) {
  483. #ifdef _WIN32
  484. WORD wVersionRequested;
  485. WSADATA wsaData;
  486. wVersionRequested = MAKEWORD(2, 2);
  487. WSAStartup(wVersionRequested, &wsaData);
  488. #endif
  489. UA_ServerNetworkLayer nl;
  490. memset(&nl, 0, sizeof(UA_ServerNetworkLayer));
  491. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)calloc(1,sizeof(ServerNetworkLayerTCP));
  492. if(!layer)
  493. return nl;
  494. layer->conf = conf;
  495. layer->port = port;
  496. nl.handle = layer;
  497. nl.start = ServerNetworkLayerTCP_start;
  498. nl.listen = ServerNetworkLayerTCP_listen;
  499. nl.stop = ServerNetworkLayerTCP_stop;
  500. nl.deleteMembers = ServerNetworkLayerTCP_deleteMembers;
  501. return nl;
  502. }
  503. /***************************/
  504. /* Client NetworkLayer TCP */
  505. /***************************/
  506. static UA_StatusCode
  507. ClientNetworkLayerGetBuffer(UA_Connection *connection, size_t length,
  508. UA_ByteString *buf) {
  509. if(length > connection->remoteConf.recvBufferSize)
  510. return UA_STATUSCODE_BADCOMMUNICATIONERROR;
  511. if(connection->state == UA_CONNECTION_CLOSED)
  512. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  513. return UA_ByteString_allocBuffer(buf, connection->remoteConf.recvBufferSize);
  514. }
  515. static void
  516. ClientNetworkLayerReleaseBuffer(UA_Connection *connection, UA_ByteString *buf) {
  517. UA_ByteString_deleteMembers(buf);
  518. }
  519. static void
  520. ClientNetworkLayerClose(UA_Connection *connection) {
  521. #ifdef UA_ENABLE_MULTITHREADING
  522. if(uatomic_xchg(&connection->state, UA_CONNECTION_CLOSED) == UA_CONNECTION_CLOSED)
  523. return;
  524. #else
  525. if(connection->state == UA_CONNECTION_CLOSED)
  526. return;
  527. connection->state = UA_CONNECTION_CLOSED;
  528. #endif
  529. socket_close(connection);
  530. }
  531. /* we have no networklayer. instead, attach the reusable buffer to the handle */
  532. UA_Connection
  533. UA_ClientConnectionTCP(UA_ConnectionConfig conf, const char *endpointUrl,
  534. UA_Logger logger) {
  535. #ifdef _WIN32
  536. WORD wVersionRequested;
  537. WSADATA wsaData;
  538. wVersionRequested = MAKEWORD(2, 2);
  539. WSAStartup(wVersionRequested, &wsaData);
  540. #endif
  541. UA_Connection connection;
  542. memset(&connection, 0, sizeof(UA_Connection));
  543. connection.state = UA_CONNECTION_OPENING;
  544. connection.localConf = conf;
  545. connection.remoteConf = conf;
  546. connection.send = socket_write;
  547. connection.recv = socket_recv;
  548. connection.close = ClientNetworkLayerClose;
  549. connection.free = NULL; /* Not used in the client */
  550. connection.getSendBuffer = ClientNetworkLayerGetBuffer;
  551. connection.releaseSendBuffer = ClientNetworkLayerReleaseBuffer;
  552. connection.releaseRecvBuffer = ClientNetworkLayerReleaseBuffer;
  553. UA_String endpointUrlString = UA_STRING((char*)(uintptr_t)endpointUrl);
  554. UA_String hostnameString = UA_STRING_NULL;
  555. UA_String pathString = UA_STRING_NULL;
  556. UA_UInt16 port = 0;
  557. char hostname[512];
  558. UA_StatusCode parse_retval =
  559. UA_parseEndpointUrl(&endpointUrlString, &hostnameString, &port, &pathString);
  560. if(parse_retval != UA_STATUSCODE_GOOD || hostnameString.length > 511) {
  561. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  562. "Server url is invalid: %s", endpointUrl);
  563. return connection;
  564. }
  565. if(port == 0) {
  566. port = 4840;
  567. UA_LOG_INFO(logger, UA_LOGCATEGORY_NETWORK,
  568. "No port defined, using standard port %d", port);
  569. }
  570. memcpy(hostname, hostnameString.data, hostnameString.length);
  571. hostname[hostnameString.length] = 0;
  572. struct addrinfo hints, *server;
  573. memset(&hints, 0, sizeof(hints));
  574. hints.ai_socktype = SOCK_STREAM;
  575. hints.ai_family = AF_INET;
  576. char portStr[6];
  577. #ifndef _MSC_VER
  578. snprintf(portStr, 6, "%d", port);
  579. #else
  580. _snprintf_s(portStr, 6, _TRUNCATE, "%d", port);
  581. #endif
  582. int error = getaddrinfo(hostname, portStr, &hints, &server);
  583. if(error != 0 || !server) {
  584. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  585. "DNS lookup of %s failed with error %s",
  586. hostname, gai_strerror(error));
  587. return connection;
  588. }
  589. /* Get a socket */
  590. SOCKET clientsockfd = socket(server->ai_family, server->ai_socktype,
  591. server->ai_protocol);
  592. #ifdef _WIN32
  593. if(clientsockfd == INVALID_SOCKET) {
  594. #else
  595. if(clientsockfd < 0) {
  596. #endif
  597. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  598. "Could not create client socket");
  599. freeaddrinfo(server);
  600. return connection;
  601. }
  602. /* Connect to the server */
  603. connection.sockfd = (UA_Int32)clientsockfd; /* cast for win32 */
  604. error = connect(clientsockfd, server->ai_addr, WIN32_INT server->ai_addrlen);
  605. freeaddrinfo(server);
  606. if(error < 0) {
  607. ClientNetworkLayerClose(&connection);
  608. #ifdef _WIN32
  609. wchar_t *s = NULL;
  610. FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  611. FORMAT_MESSAGE_FROM_SYSTEM |
  612. FORMAT_MESSAGE_IGNORE_INSERTS,
  613. NULL, WSAGetLastError(),
  614. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  615. (LPWSTR)&s, 0, NULL);
  616. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  617. "Connection to %s failed. Error: %d: %S",
  618. endpointUrl, WSAGetLastError(), s);
  619. LocalFree(s);
  620. #else
  621. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  622. "Connection to %s failed. Error: %d: %s",
  623. endpointUrl, errno, strerror(errno));
  624. #endif
  625. return connection;
  626. }
  627. #ifdef SO_NOSIGPIPE
  628. int val = 1;
  629. int sso_result = setsockopt(connection.sockfd,
  630. SOL_SOCKET, SO_NOSIGPIPE,
  631. (void*)&val, sizeof(val));
  632. if(sso_result < 0)
  633. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  634. "Couldn't set SO_NOSIGPIPE");
  635. #endif
  636. return connection;
  637. }