ua_network_tcp.c 26 KB

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