ua_network_tcp.c 24 KB

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