ua_network_tcp.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  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].connection = c;
  333. layer->mappings[layer->mappingsSize].sockfd = newsockfd;
  334. ++layer->mappingsSize;
  335. return UA_STATUSCODE_GOOD;
  336. }
  337. static UA_StatusCode
  338. ServerNetworkLayerTCP_start(UA_ServerNetworkLayer *nl, UA_Logger logger) {
  339. ServerNetworkLayerTCP *layer = nl->handle;
  340. layer->logger = logger;
  341. /* get the discovery url from the hostname */
  342. UA_String du = UA_STRING_NULL;
  343. char hostname[256];
  344. if(gethostname(hostname, 255) == 0) {
  345. char discoveryUrl[256];
  346. #ifndef _MSC_VER
  347. du.length = (size_t)snprintf(discoveryUrl, 255, "opc.tcp://%s:%d",
  348. hostname, layer->port);
  349. #else
  350. du.length = (size_t)_snprintf_s(discoveryUrl, 255, _TRUNCATE,
  351. "opc.tcp://%s:%d", hostname, layer->port);
  352. #endif
  353. du.data = (UA_Byte*)discoveryUrl;
  354. }
  355. UA_String_copy(&du, &nl->discoveryUrl);
  356. /* Create the server socket */
  357. SOCKET newsock = socket(PF_INET, SOCK_STREAM, 0);
  358. #ifdef _WIN32
  359. if(newsock == INVALID_SOCKET)
  360. #else
  361. if(newsock < 0)
  362. #endif
  363. {
  364. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  365. "Error opening the server socket");
  366. return UA_STATUSCODE_BADINTERNALERROR;
  367. }
  368. /* Set socket options */
  369. int optval = 1;
  370. if(setsockopt(newsock, SOL_SOCKET, SO_REUSEADDR,
  371. (const char *)&optval, sizeof(optval)) == -1 ||
  372. socket_set_nonblocking(newsock) != UA_STATUSCODE_GOOD) {
  373. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  374. "Error during setting of server socket options");
  375. CLOSESOCKET(newsock);
  376. return UA_STATUSCODE_BADINTERNALERROR;
  377. }
  378. /* Bind socket to address */
  379. const struct sockaddr_in serv_addr = {
  380. .sin_family = AF_INET, .sin_addr.s_addr = INADDR_ANY,
  381. .sin_port = htons(layer->port), .sin_zero = {0}};
  382. if(bind(newsock, (const struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
  383. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  384. "Error during binding of the server socket");
  385. CLOSESOCKET(newsock);
  386. return UA_STATUSCODE_BADINTERNALERROR;
  387. }
  388. /* Start listening */
  389. if(listen(newsock, MAXBACKLOG) < 0) {
  390. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  391. "Error listening on server socket");
  392. CLOSESOCKET(newsock);
  393. return UA_STATUSCODE_BADINTERNALERROR;
  394. }
  395. layer->serversockfd = (UA_Int32)newsock; /* cast on win32 */
  396. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  397. "TCP network layer listening on %.*s",
  398. nl->discoveryUrl.length, nl->discoveryUrl.data);
  399. return UA_STATUSCODE_GOOD;
  400. }
  401. static size_t
  402. ServerNetworkLayerTCP_getJobs(UA_ServerNetworkLayer *nl, UA_Job **jobs, UA_UInt16 timeout) {
  403. ServerNetworkLayerTCP *layer = nl->handle;
  404. fd_set fdset, errset;
  405. UA_Int32 highestfd = setFDSet(layer, &fdset);
  406. setFDSet(layer, &errset);
  407. struct timeval tmptv = {0, timeout * 1000};
  408. UA_Int32 resultsize = select(highestfd+1, &fdset, NULL, &errset, &tmptv);
  409. if(resultsize < 0) {
  410. *jobs = NULL;
  411. return 0;
  412. }
  413. /* accept new connections (can only be a single one) */
  414. if(UA_fd_isset(layer->serversockfd, &fdset)) {
  415. --resultsize;
  416. SOCKET newsockfd = accept((SOCKET)layer->serversockfd, NULL, NULL);
  417. #ifdef _WIN32
  418. if(newsockfd != INVALID_SOCKET)
  419. #else
  420. if(newsockfd >= 0)
  421. #endif
  422. {
  423. socket_set_nonblocking(newsockfd);
  424. /* Send messages directly and do wait to merge packets (disable
  425. Nagle's algorithm) */
  426. int i = 1;
  427. setsockopt(newsockfd, IPPROTO_TCP, TCP_NODELAY, (void *)&i, sizeof(i));
  428. ServerNetworkLayerTCP_add(layer, (UA_Int32)newsockfd);
  429. }
  430. }
  431. /* alloc enough space for a cleanup-connection and free-connection job per
  432. resulted socket */
  433. if(resultsize == 0)
  434. return 0;
  435. UA_Job *js = malloc(sizeof(UA_Job) * (size_t)resultsize * 2);
  436. if(!js)
  437. return 0;
  438. /* read from established sockets */
  439. size_t j = 0;
  440. UA_ByteString buf = UA_BYTESTRING_NULL;
  441. for(size_t i = 0; i < layer->mappingsSize && j < (size_t)resultsize; ++i) {
  442. if(!UA_fd_isset(layer->mappings[i].sockfd, &errset) &&
  443. !UA_fd_isset(layer->mappings[i].sockfd, &fdset))
  444. continue;
  445. UA_StatusCode retval = socket_recv(layer->mappings[i].connection, &buf, 0);
  446. if(retval == UA_STATUSCODE_GOOD) {
  447. js[j].job.binaryMessage.connection = layer->mappings[i].connection;
  448. js[j].job.binaryMessage.message = buf;
  449. js[j].type = UA_JOBTYPE_BINARYMESSAGE_NETWORKLAYER;
  450. ++j;
  451. } else if (retval == UA_STATUSCODE_BADCONNECTIONCLOSED) {
  452. UA_Connection *c = layer->mappings[i].connection;
  453. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  454. "Connection %i | Connection closed from remote", c->sockfd);
  455. /* the socket was closed from remote */
  456. js[j].type = UA_JOBTYPE_DETACHCONNECTION;
  457. js[j].job.closeConnection = layer->mappings[i].connection;
  458. layer->mappings[i] = layer->mappings[layer->mappingsSize-1];
  459. --layer->mappingsSize;
  460. ++j;
  461. js[j].type = UA_JOBTYPE_METHODCALL_DELAYED;
  462. js[j].job.methodCall.method = FreeConnectionCallback;
  463. js[j].job.methodCall.data = c;
  464. ++j;
  465. }
  466. }
  467. if(j == 0) {
  468. free(js);
  469. js = NULL;
  470. }
  471. *jobs = js;
  472. return j;
  473. }
  474. static size_t
  475. ServerNetworkLayerTCP_stop(UA_ServerNetworkLayer *nl, UA_Job **jobs) {
  476. ServerNetworkLayerTCP *layer = nl->handle;
  477. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK,
  478. "Shutting down the TCP network layer with %d open connection(s)",
  479. layer->mappingsSize);
  480. shutdown((SOCKET)layer->serversockfd,2);
  481. CLOSESOCKET(layer->serversockfd);
  482. UA_Job *items = malloc(sizeof(UA_Job) * layer->mappingsSize * 2);
  483. if(!items)
  484. return 0;
  485. for(size_t i = 0; i < layer->mappingsSize; ++i) {
  486. socket_close(layer->mappings[i].connection);
  487. items[i*2].type = UA_JOBTYPE_DETACHCONNECTION;
  488. items[i*2].job.closeConnection = layer->mappings[i].connection;
  489. items[(i*2)+1].type = UA_JOBTYPE_METHODCALL_DELAYED;
  490. items[(i*2)+1].job.methodCall.method = FreeConnectionCallback;
  491. items[(i*2)+1].job.methodCall.data = layer->mappings[i].connection;
  492. }
  493. #ifdef _WIN32
  494. WSACleanup();
  495. #endif
  496. *jobs = items;
  497. return layer->mappingsSize*2;
  498. }
  499. /* run only when the server is stopped */
  500. static void ServerNetworkLayerTCP_deleteMembers(UA_ServerNetworkLayer *nl) {
  501. ServerNetworkLayerTCP *layer = nl->handle;
  502. free(layer->mappings);
  503. free(layer);
  504. UA_String_deleteMembers(&nl->discoveryUrl);
  505. }
  506. UA_ServerNetworkLayer
  507. UA_ServerNetworkLayerTCP(UA_ConnectionConfig conf, UA_UInt16 port) {
  508. #ifdef _WIN32
  509. WORD wVersionRequested;
  510. WSADATA wsaData;
  511. wVersionRequested = MAKEWORD(2, 2);
  512. WSAStartup(wVersionRequested, &wsaData);
  513. #endif
  514. UA_ServerNetworkLayer nl;
  515. memset(&nl, 0, sizeof(UA_ServerNetworkLayer));
  516. ServerNetworkLayerTCP *layer = calloc(1,sizeof(ServerNetworkLayerTCP));
  517. if(!layer)
  518. return nl;
  519. layer->conf = conf;
  520. layer->port = port;
  521. nl.handle = layer;
  522. nl.start = ServerNetworkLayerTCP_start;
  523. nl.getJobs = ServerNetworkLayerTCP_getJobs;
  524. nl.stop = ServerNetworkLayerTCP_stop;
  525. nl.deleteMembers = ServerNetworkLayerTCP_deleteMembers;
  526. return nl;
  527. }
  528. /***************************/
  529. /* Client NetworkLayer TCP */
  530. /***************************/
  531. static UA_StatusCode
  532. ClientNetworkLayerGetBuffer(UA_Connection *connection, size_t length, UA_ByteString *buf) {
  533. if(length > connection->remoteConf.recvBufferSize)
  534. return UA_STATUSCODE_BADCOMMUNICATIONERROR;
  535. if(connection->state == UA_CONNECTION_CLOSED)
  536. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  537. return UA_ByteString_allocBuffer(buf, connection->remoteConf.recvBufferSize);
  538. }
  539. static void
  540. ClientNetworkLayerReleaseBuffer(UA_Connection *connection, UA_ByteString *buf) {
  541. UA_ByteString_deleteMembers(buf);
  542. }
  543. static void
  544. ClientNetworkLayerClose(UA_Connection *connection) {
  545. #ifdef UA_ENABLE_MULTITHREADING
  546. if(uatomic_xchg(&connection->state, UA_CONNECTION_CLOSED) == UA_CONNECTION_CLOSED)
  547. return;
  548. #else
  549. if(connection->state == UA_CONNECTION_CLOSED)
  550. return;
  551. connection->state = UA_CONNECTION_CLOSED;
  552. #endif
  553. socket_close(connection);
  554. }
  555. /* we have no networklayer. instead, attach the reusable buffer to the handle */
  556. UA_Connection
  557. UA_ClientConnectionTCP(UA_ConnectionConfig localConf, const char *endpointUrl,
  558. UA_Logger logger) {
  559. #ifdef _WIN32
  560. WORD wVersionRequested;
  561. WSADATA wsaData;
  562. wVersionRequested = MAKEWORD(2, 2);
  563. WSAStartup(wVersionRequested, &wsaData);
  564. #endif
  565. UA_Connection connection;
  566. memset(&connection, 0, sizeof(UA_Connection));
  567. connection.state = UA_CONNECTION_OPENING;
  568. connection.localConf = localConf;
  569. connection.remoteConf = localConf;
  570. connection.send = socket_write;
  571. connection.recv = socket_recv;
  572. connection.close = ClientNetworkLayerClose;
  573. connection.getSendBuffer = ClientNetworkLayerGetBuffer;
  574. connection.releaseSendBuffer = ClientNetworkLayerReleaseBuffer;
  575. connection.releaseRecvBuffer = ClientNetworkLayerReleaseBuffer;
  576. char hostname[512];
  577. UA_UInt16 port = 0;
  578. const char *path = NULL;
  579. UA_StatusCode parse_retval = UA_EndpointUrl_split(endpointUrl, hostname, &port, &path);
  580. if(parse_retval != UA_STATUSCODE_GOOD) {
  581. if(parse_retval == UA_STATUSCODE_BADOUTOFRANGE)
  582. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  583. "Server url is invalid: %s", endpointUrl);
  584. else if(parse_retval == UA_STATUSCODE_BADATTRIBUTEIDINVALID)
  585. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  586. "Server url does not begin with 'opc.tcp://' '%s'", endpointUrl);
  587. return connection;
  588. }
  589. if(port == 0) {
  590. port = 4840;
  591. UA_LOG_INFO(logger, UA_LOGCATEGORY_NETWORK,
  592. "No port defined, using standard port %d", port);
  593. }
  594. struct addrinfo hints, *server;
  595. memset(&hints, 0, sizeof(hints));
  596. hints.ai_socktype = SOCK_STREAM;
  597. hints.ai_family = AF_INET;
  598. char portStr[6];
  599. #ifndef _MSC_VER
  600. snprintf(portStr, 6, "%d", port);
  601. #else
  602. _snprintf_s(portStr, 6, _TRUNCATE, "%d", port);
  603. #endif
  604. int error = getaddrinfo(hostname, portStr, &hints, &server);
  605. if(error != 0 || !server) {
  606. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK,
  607. "DNS lookup of %s failed with error %s",
  608. hostname, gai_strerror(error));
  609. return connection;
  610. }
  611. /* Get a socket */
  612. SOCKET clientsockfd = socket(server->ai_family, server->ai_socktype, server->ai_protocol);
  613. #ifdef _WIN32
  614. if(clientsockfd == INVALID_SOCKET) {
  615. #else
  616. if(clientsockfd < 0) {
  617. #endif
  618. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK, "Could not create client socket");
  619. freeaddrinfo(server);
  620. return connection;
  621. }
  622. /* Connect to the server */
  623. connection.sockfd = (UA_Int32)clientsockfd; /* cast for win32 */
  624. error = connect(clientsockfd, server->ai_addr, WIN32_INT server->ai_addrlen);
  625. freeaddrinfo(server);
  626. if(error < 0) {
  627. ClientNetworkLayerClose(&connection);
  628. #ifdef _WIN32
  629. wchar_t *s = NULL;
  630. FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  631. NULL, WSAGetLastError(),
  632. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  633. (LPWSTR)&s, 0, NULL);
  634. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK, "Connection to %s failed. Error: %d: %S", endpointUrl, WSAGetLastError(), s);
  635. LocalFree(s);
  636. #else
  637. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK, "Connection to %s failed. Error: %d: %s", endpointUrl, errno, strerror(errno));
  638. #endif
  639. return connection;
  640. }
  641. #ifdef SO_NOSIGPIPE
  642. int val = 1;
  643. if(setsockopt(connection.sockfd, SOL_SOCKET, SO_NOSIGPIPE, (void*)&val, sizeof(val)) < 0) {
  644. UA_LOG_WARNING(logger, UA_LOGCATEGORY_NETWORK, "Couldn't set SO_NOSIGPIPE");
  645. return connection;
  646. }
  647. #endif
  648. return connection;
  649. }