ua_network_tcp.c 24 KB

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