ua_network_tcp.c 25 KB

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