ua_network_tcp.c 24 KB

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