ua_network_tcp.c 23 KB

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