ua_network_tcp.c 26 KB

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