ua_network_tcp.c 24 KB

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