ua_network_tcp.c 24 KB

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