ua_network_tcp.c 25 KB

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