ua_network_tcp.c 23 KB

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