ua_network_tcp.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758
  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. #ifdef _WIN32
  18. # ifndef __clang__
  19. # include <malloc.h>
  20. # endif
  21. /* Fix redefinition of SLIST_ENTRY on mingw winnt.h */
  22. # ifdef SLIST_ENTRY
  23. # undef SLIST_ENTRY
  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 = 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. static void FreeConnectionCallback(UA_Server *server, void *ptr) {
  200. UA_Connection_deleteMembers((UA_Connection*)ptr);
  201. free(ptr);
  202. }
  203. /***************************/
  204. /* Server NetworkLayer TCP */
  205. /***************************/
  206. /**
  207. * For the multithreaded mode, assume a single thread that periodically "gets
  208. * work" from the network layer. In addition, several worker threads are
  209. * asynchronously calling into the callbacks of the UA_Connection that holds a
  210. * single connection.
  211. *
  212. * Creating a connection: When "GetJobs" encounters a new connection, it creates
  213. * a UA_Connection with the socket information. This is added to the mappings
  214. * array that links sockets to UA_Connection structs.
  215. *
  216. * Reading data: In "GetJobs", we listen on the sockets in the mappings array.
  217. * If data arrives (or the connection closes), a WorkItem is created that
  218. * carries the work and a pointer to the connection.
  219. *
  220. * Closing a connection: Closing can happen in two ways. Either it is triggered
  221. * by the server in an asynchronous callback. Or the connection is close by the
  222. * client and this is detected in "GetJobs". The server needs to do some
  223. * internal cleanups (close attached securechannels, etc.). So even when a
  224. * closed connection is detected in "GetJobs", we trigger the server to close
  225. * the connection (with a WorkItem) and continue from the callback.
  226. *
  227. * - Server calls close-callback: We close the socket, set the connection-state
  228. * to closed and add the connection to a linked list from which it is deleted
  229. * later. The connection cannot be freed right away since other threads might
  230. * still be using it.
  231. *
  232. * - GetJobs: We remove the connection from the mappings array. In the
  233. * non-multithreaded case, the connection is freed. For multithreading, we
  234. * return a workitem that is delayed, i.e. that is called only after all
  235. * workitems created before are finished in all threads. This workitems
  236. * contains a callback that goes through the linked list of connections to be
  237. * freed. */
  238. #define MAXBACKLOG 100
  239. typedef struct {
  240. UA_ConnectionConfig conf;
  241. UA_UInt16 port;
  242. UA_Logger logger; // Set during start
  243. /* open sockets and connections */
  244. UA_Int32 serversockfd;
  245. size_t mappingsSize;
  246. struct ConnectionMapping {
  247. UA_Connection *connection;
  248. UA_Int32 sockfd;
  249. } *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 = 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 = 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. struct ConnectionMapping *nm;
  330. nm = realloc(layer->mappings,
  331. sizeof(struct ConnectionMapping)*(layer->mappingsSize+1));
  332. if(!nm) {
  333. UA_LOG_ERROR(layer->logger, UA_LOGCATEGORY_NETWORK,
  334. "No memory for a new Connection");
  335. free(c);
  336. return UA_STATUSCODE_BADINTERNALERROR;
  337. }
  338. layer->mappings = nm;
  339. layer->mappings[layer->mappingsSize].connection = c;
  340. layer->mappings[layer->mappingsSize].sockfd = newsockfd;
  341. ++layer->mappingsSize;
  342. return UA_STATUSCODE_GOOD;
  343. }
  344. static UA_StatusCode
  345. ServerNetworkLayerTCP_start(UA_ServerNetworkLayer *nl, UA_Logger logger) {
  346. ServerNetworkLayerTCP *layer = nl->handle;
  347. layer->logger = logger;
  348. /* get the discovery url from the hostname */
  349. UA_String du = UA_STRING_NULL;
  350. char hostname[256];
  351. if(gethostname(hostname, 255) == 0) {
  352. char discoveryUrl[256];
  353. #ifndef _MSC_VER
  354. du.length = (size_t)snprintf(discoveryUrl, 255, "opc.tcp://%s:%d",
  355. hostname, layer->port);
  356. #else
  357. du.length = (size_t)_snprintf_s(discoveryUrl, 255, _TRUNCATE,
  358. "opc.tcp://%s:%d", hostname, layer->port);
  359. #endif
  360. du.data = (UA_Byte*)discoveryUrl;
  361. }
  362. UA_String_copy(&du, &nl->discoveryUrl);
  363. /* Create the server socket */
  364. SOCKET newsock = socket(PF_INET, SOCK_STREAM, 0);
  365. #ifdef _WIN32
  366. if(newsock == INVALID_SOCKET)
  367. #else
  368. if(newsock < 0)
  369. #endif
  370. {
  371. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  372. "Error opening the server socket");
  373. return UA_STATUSCODE_BADINTERNALERROR;
  374. }
  375. /* Set socket options */
  376. int optval = 1;
  377. if(setsockopt(newsock, SOL_SOCKET, SO_REUSEADDR,
  378. (const char *)&optval, sizeof(optval)) == -1 ||
  379. socket_set_nonblocking(newsock) != UA_STATUSCODE_GOOD) {
  380. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  381. "Error during setting of server socket options");
  382. CLOSESOCKET(newsock);
  383. return UA_STATUSCODE_BADINTERNALERROR;
  384. }
  385. /* Bind socket to address */
  386. const struct sockaddr_in serv_addr = {
  387. .sin_family = AF_INET, .sin_addr.s_addr = INADDR_ANY,
  388. .sin_port = htons(layer->port), .sin_zero = {0}};
  389. if(bind(newsock, (const struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
  390. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  391. "Error during binding of the server socket");
  392. CLOSESOCKET(newsock);
  393. return UA_STATUSCODE_BADINTERNALERROR;
  394. }
  395. /* Start listening */
  396. if(listen(newsock, MAXBACKLOG) < 0) {
  397. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  398. "Error listening on server socket");
  399. CLOSESOCKET(newsock);
  400. return UA_STATUSCODE_BADINTERNALERROR;
  401. }
  402. layer->serversockfd = (UA_Int32)newsock; /* cast on win32 */
  403. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  404. "TCP network layer listening on %.*s",
  405. nl->discoveryUrl.length, nl->discoveryUrl.data);
  406. return UA_STATUSCODE_GOOD;
  407. }
  408. static size_t
  409. removeClosedConnections(ServerNetworkLayerTCP *layer, UA_Job *js) {
  410. size_t c = 0;
  411. for(size_t i = 0; i < layer->mappingsSize; ++i) {
  412. if(layer->mappings[i].connection &&
  413. layer->mappings[i].connection->state != UA_CONNECTION_CLOSED)
  414. continue;
  415. /* the socket was closed from remote */
  416. UA_Connection *conn = layer->mappings[i].connection;
  417. js[c].type = UA_JOBTYPE_DETACHCONNECTION;
  418. js[c].job.closeConnection = conn;
  419. layer->mappings[i] = layer->mappings[layer->mappingsSize-1];
  420. --layer->mappingsSize;
  421. ++c;
  422. js[c].type = UA_JOBTYPE_METHODCALL_DELAYED;
  423. js[c].job.methodCall.method = FreeConnectionCallback;
  424. js[c].job.methodCall.data = conn;
  425. ++c;
  426. }
  427. return c;
  428. }
  429. static size_t
  430. ServerNetworkLayerTCP_getJobs(UA_ServerNetworkLayer *nl, UA_Job **jobs,
  431. UA_UInt16 timeout) {
  432. /* Every open socket can generate two jobs */
  433. ServerNetworkLayerTCP *layer = nl->handle;
  434. UA_Job *js = malloc(sizeof(UA_Job) * (size_t)((layer->mappingsSize * 2)));
  435. if(!js)
  436. return UA_STATUSCODE_BADOUTOFMEMORY;
  437. /* Remove closed sockets */
  438. size_t totalJobs = removeClosedConnections(layer, js);
  439. /* Listen on open sockets (including the server) */
  440. fd_set fdset, errset;
  441. UA_Int32 highestfd = setFDSet(layer, &fdset);
  442. setFDSet(layer, &errset);
  443. struct timeval tmptv = {0, timeout * 1000};
  444. UA_Int32 resultsize = select(highestfd+1, &fdset, NULL, &errset, &tmptv);
  445. if(totalJobs == 0 && resultsize <= 0) {
  446. free(js);
  447. *jobs = NULL;
  448. return 0;
  449. }
  450. /* Accept new connection via the server socket (can only be a single one) */
  451. if(UA_fd_isset(layer->serversockfd, &fdset)) {
  452. --resultsize;
  453. SOCKET newsockfd = accept((SOCKET)layer->serversockfd, NULL, NULL);
  454. #ifdef _WIN32
  455. if(newsockfd != INVALID_SOCKET)
  456. #else
  457. if(newsockfd >= 0)
  458. #endif
  459. {
  460. socket_set_nonblocking(newsockfd);
  461. /* Do not merge packets on the socket (disable Nagle's algorithm) */
  462. int i = 1;
  463. setsockopt(newsockfd, IPPROTO_TCP, TCP_NODELAY, (void *)&i, sizeof(i));
  464. ServerNetworkLayerTCP_add(layer, (UA_Int32)newsockfd);
  465. }
  466. }
  467. /* Read from established sockets */
  468. UA_ByteString buf = UA_BYTESTRING_NULL;
  469. size_t j = 0;
  470. for(size_t i = 0; i < layer->mappingsSize && j < (size_t)resultsize; ++i) {
  471. if(!UA_fd_isset(layer->mappings[i].sockfd, &errset) &&
  472. !UA_fd_isset(layer->mappings[i].sockfd, &fdset))
  473. continue;
  474. UA_StatusCode retval = socket_recv(layer->mappings[i].connection, &buf, 0);
  475. if(retval == UA_STATUSCODE_GOOD) {
  476. js[totalJobs + j].job.binaryMessage.connection = layer->mappings[i].connection;
  477. js[totalJobs + j].job.binaryMessage.message = buf;
  478. js[totalJobs + j].type = UA_JOBTYPE_BINARYMESSAGE_NETWORKLAYER;
  479. ++j;
  480. } else if (retval == UA_STATUSCODE_BADCONNECTIONCLOSED) {
  481. UA_Connection *c = layer->mappings[i].connection;
  482. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  483. "Connection %i | Connection closed from remote", c->sockfd);
  484. /* the socket was closed from remote */
  485. js[totalJobs + j].type = UA_JOBTYPE_DETACHCONNECTION;
  486. js[totalJobs + j].job.closeConnection = c;
  487. layer->mappings[i] = layer->mappings[layer->mappingsSize-1];
  488. --layer->mappingsSize;
  489. ++totalJobs; /* increase j only once */
  490. js[totalJobs + j].type = UA_JOBTYPE_METHODCALL_DELAYED;
  491. js[totalJobs + j].job.methodCall.method = FreeConnectionCallback;
  492. js[totalJobs + j].job.methodCall.data = c;
  493. ++j;
  494. }
  495. }
  496. totalJobs += j;
  497. if(totalJobs == 0) {
  498. free(js);
  499. js = NULL;
  500. }
  501. *jobs = js;
  502. return totalJobs;
  503. }
  504. static size_t
  505. ServerNetworkLayerTCP_stop(UA_ServerNetworkLayer *nl, UA_Job **jobs) {
  506. ServerNetworkLayerTCP *layer = nl->handle;
  507. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  508. "Shutting down the TCP network layer with %d open connection(s)",
  509. layer->mappingsSize);
  510. shutdown((SOCKET)layer->serversockfd,2);
  511. CLOSESOCKET(layer->serversockfd);
  512. UA_Job *items = malloc(sizeof(UA_Job) * layer->mappingsSize * 2);
  513. if(!items)
  514. return 0;
  515. for(size_t i = 0; i < layer->mappingsSize; ++i) {
  516. socket_close(layer->mappings[i].connection);
  517. items[i*2].type = UA_JOBTYPE_DETACHCONNECTION;
  518. items[i*2].job.closeConnection = layer->mappings[i].connection;
  519. items[(i*2)+1].type = UA_JOBTYPE_METHODCALL_DELAYED;
  520. items[(i*2)+1].job.methodCall.method = FreeConnectionCallback;
  521. items[(i*2)+1].job.methodCall.data = layer->mappings[i].connection;
  522. }
  523. #ifdef _WIN32
  524. WSACleanup();
  525. #endif
  526. *jobs = items;
  527. return layer->mappingsSize*2;
  528. }
  529. /* run only when the server is stopped */
  530. static void ServerNetworkLayerTCP_deleteMembers(UA_ServerNetworkLayer *nl) {
  531. ServerNetworkLayerTCP *layer = nl->handle;
  532. free(layer->mappings);
  533. free(layer);
  534. UA_String_deleteMembers(&nl->discoveryUrl);
  535. }
  536. UA_ServerNetworkLayer
  537. UA_ServerNetworkLayerTCP(UA_ConnectionConfig conf, UA_UInt16 port) {
  538. #ifdef _WIN32
  539. WORD wVersionRequested;
  540. WSADATA wsaData;
  541. wVersionRequested = MAKEWORD(2, 2);
  542. WSAStartup(wVersionRequested, &wsaData);
  543. #endif
  544. UA_ServerNetworkLayer nl;
  545. memset(&nl, 0, sizeof(UA_ServerNetworkLayer));
  546. ServerNetworkLayerTCP *layer = calloc(1,sizeof(ServerNetworkLayerTCP));
  547. if(!layer)
  548. return nl;
  549. layer->conf = conf;
  550. layer->port = port;
  551. nl.handle = layer;
  552. nl.start = ServerNetworkLayerTCP_start;
  553. nl.getJobs = ServerNetworkLayerTCP_getJobs;
  554. nl.stop = ServerNetworkLayerTCP_stop;
  555. nl.deleteMembers = ServerNetworkLayerTCP_deleteMembers;
  556. return nl;
  557. }
  558. /***************************/
  559. /* Client NetworkLayer TCP */
  560. /***************************/
  561. static UA_StatusCode
  562. ClientNetworkLayerGetBuffer(UA_Connection *connection, size_t length,
  563. UA_ByteString *buf) {
  564. if(length > connection->remoteConf.recvBufferSize)
  565. return UA_STATUSCODE_BADCOMMUNICATIONERROR;
  566. if(connection->state == UA_CONNECTION_CLOSED)
  567. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  568. return UA_ByteString_allocBuffer(buf, connection->remoteConf.recvBufferSize);
  569. }
  570. static void
  571. ClientNetworkLayerReleaseBuffer(UA_Connection *connection, UA_ByteString *buf) {
  572. UA_ByteString_deleteMembers(buf);
  573. }
  574. static void
  575. ClientNetworkLayerClose(UA_Connection *connection) {
  576. #ifdef UA_ENABLE_MULTITHREADING
  577. if(uatomic_xchg(&connection->state, UA_CONNECTION_CLOSED) == UA_CONNECTION_CLOSED)
  578. return;
  579. #else
  580. if(connection->state == UA_CONNECTION_CLOSED)
  581. return;
  582. connection->state = UA_CONNECTION_CLOSED;
  583. #endif
  584. socket_close(connection);
  585. }
  586. /* we have no networklayer. instead, attach the reusable buffer to the handle */
  587. UA_Connection
  588. UA_ClientConnectionTCP(UA_ConnectionConfig conf, const char *endpointUrl,
  589. UA_Logger logger) {
  590. #ifdef _WIN32
  591. WORD wVersionRequested;
  592. WSADATA wsaData;
  593. wVersionRequested = MAKEWORD(2, 2);
  594. WSAStartup(wVersionRequested, &wsaData);
  595. #endif
  596. UA_Connection connection;
  597. memset(&connection, 0, sizeof(UA_Connection));
  598. connection.state = UA_CONNECTION_OPENING;
  599. connection.localConf = conf;
  600. connection.remoteConf = conf;
  601. connection.send = socket_write;
  602. connection.recv = socket_recv;
  603. connection.close = ClientNetworkLayerClose;
  604. connection.getSendBuffer = ClientNetworkLayerGetBuffer;
  605. connection.releaseSendBuffer = ClientNetworkLayerReleaseBuffer;
  606. connection.releaseRecvBuffer = ClientNetworkLayerReleaseBuffer;
  607. char hostname[512];
  608. UA_UInt16 port = 0;
  609. const char *path = NULL;
  610. UA_StatusCode parse_retval = UA_EndpointUrl_split(endpointUrl, hostname, &port, &path);
  611. if(parse_retval != UA_STATUSCODE_GOOD) {
  612. if(parse_retval == UA_STATUSCODE_BADOUTOFRANGE)
  613. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  614. "Server url is invalid: %s", endpointUrl);
  615. else if(parse_retval == UA_STATUSCODE_BADATTRIBUTEIDINVALID)
  616. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  617. "Server url does not begin with 'opc.tcp://' '%s'",
  618. endpointUrl);
  619. return connection;
  620. }
  621. if(port == 0) {
  622. port = 4840;
  623. UA_LOG_INFO(logger, UA_LOGCATEGORY_NETWORK,
  624. "No port defined, using standard port %d", port);
  625. }
  626. struct addrinfo hints, *server;
  627. memset(&hints, 0, sizeof(hints));
  628. hints.ai_socktype = SOCK_STREAM;
  629. hints.ai_family = AF_INET;
  630. char portStr[6];
  631. #ifndef _MSC_VER
  632. snprintf(portStr, 6, "%d", port);
  633. #else
  634. _snprintf_s(portStr, 6, _TRUNCATE, "%d", port);
  635. #endif
  636. int error = getaddrinfo(hostname, portStr, &hints, &server);
  637. if(error != 0 || !server) {
  638. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  639. "DNS lookup of %s failed with error %s",
  640. hostname, gai_strerror(error));
  641. return connection;
  642. }
  643. /* Get a socket */
  644. SOCKET clientsockfd = socket(server->ai_family, server->ai_socktype,
  645. server->ai_protocol);
  646. #ifdef _WIN32
  647. if(clientsockfd == INVALID_SOCKET) {
  648. #else
  649. if(clientsockfd < 0) {
  650. #endif
  651. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  652. "Could not create client socket");
  653. freeaddrinfo(server);
  654. return connection;
  655. }
  656. /* Connect to the server */
  657. connection.sockfd = (UA_Int32)clientsockfd; /* cast for win32 */
  658. error = connect(clientsockfd, server->ai_addr, WIN32_INT server->ai_addrlen);
  659. freeaddrinfo(server);
  660. if(error < 0) {
  661. ClientNetworkLayerClose(&connection);
  662. #ifdef _WIN32
  663. wchar_t *s = NULL;
  664. FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  665. FORMAT_MESSAGE_FROM_SYSTEM |
  666. FORMAT_MESSAGE_IGNORE_INSERTS,
  667. NULL, WSAGetLastError(),
  668. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  669. (LPWSTR)&s, 0, NULL);
  670. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  671. "Connection to %s failed. Error: %d: %S",
  672. endpointUrl, WSAGetLastError(), s);
  673. LocalFree(s);
  674. #else
  675. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  676. "Connection to %s failed. Error: %d: %s",
  677. endpointUrl, errno, strerror(errno));
  678. #endif
  679. return connection;
  680. }
  681. #ifdef SO_NOSIGPIPE
  682. int val = 1;
  683. int sso_result = setsockopt(connection.sockfd,
  684. SOL_SOCKET, SO_NOSIGPIPE,
  685. (void*)&val, sizeof(val));
  686. if(sso_result < 0)
  687. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  688. "Couldn't set SO_NOSIGPIPE");
  689. #endif
  690. return connection;
  691. }