ua_network_tcp.c 25 KB

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