ua_network_tcp.c 24 KB

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