ua_network_tcp.c 23 KB

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