ua_network_tcp.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  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. #include "ua_network_tcp.h"
  4. #include <stdlib.h> // malloc, free
  5. #include <stdio.h> // snprintf
  6. #include <string.h> // memset
  7. #include <errno.h>
  8. #ifdef _WIN32
  9. # include <malloc.h>
  10. # include <winsock2.h>
  11. # include <ws2tcpip.h>
  12. # define CLOSESOCKET(S) closesocket(S)
  13. # define ssize_t long
  14. #else
  15. # include <fcntl.h>
  16. # include <sys/select.h>
  17. # include <netinet/in.h>
  18. # ifndef __CYGWIN__
  19. # include <netinet/tcp.h>
  20. # endif
  21. # include <sys/ioctl.h>
  22. # include <netdb.h> //gethostbyname for the client
  23. # include <unistd.h> // read, write, close
  24. # include <arpa/inet.h>
  25. # ifdef __QNX__
  26. # include <sys/socket.h>
  27. # endif
  28. # define CLOSESOCKET(S) close(S)
  29. #endif
  30. /* workaround a glibc bug where an integer conversion is required */
  31. #if !defined(_WIN32)
  32. # if defined(__GNU_LIBRARY__) && (__GNU_LIBRARY__ >= 6) && (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 16)
  33. # define UA_fd_set(fd, fds) FD_SET(fd, fds)
  34. # define UA_fd_isset(fd, fds) FD_ISSET(fd, fds)
  35. # else
  36. # define UA_fd_set(fd, fds) FD_SET((unsigned int)fd, fds)
  37. # define UA_fd_isset(fd, fds) FD_ISSET((unsigned int)fd, fds)
  38. # endif
  39. #else
  40. # define UA_fd_set(fd, fds) FD_SET((unsigned int)fd, fds)
  41. # define UA_fd_isset(fd, fds) FD_ISSET((unsigned int)fd, fds)
  42. #endif
  43. #ifdef UA_ENABLE_MULTITHREADING
  44. # include <urcu/uatomic.h>
  45. #endif
  46. #ifndef MSG_NOSIGNAL
  47. #define MSG_NOSIGNAL 0
  48. #endif
  49. /****************************/
  50. /* Generic Socket Functions */
  51. /****************************/
  52. static void
  53. socket_close(UA_Connection *connection) {
  54. connection->state = UA_CONNECTION_CLOSED;
  55. shutdown(connection->sockfd,2);
  56. CLOSESOCKET(connection->sockfd);
  57. }
  58. static UA_StatusCode
  59. socket_write(UA_Connection *connection, UA_ByteString *buf) {
  60. size_t nWritten = 0;
  61. do {
  62. ssize_t n = 0;
  63. do {
  64. /*
  65. * If the OS throws EMSGSIZE, force a smaller packet size:
  66. * size_t bytes_to_send = buf->length - nWritten > 1024 ? 1024 : buf->length - nWritten;
  67. */
  68. size_t bytes_to_send = buf->length - nWritten;
  69. #ifdef _WIN32
  70. n = send((SOCKET)connection->sockfd, (const char*)buf->data + nWritten, bytes_to_send, 0);
  71. const int last_error = WSAGetLastError();
  72. if(n < 0 && last_error != WSAEINTR && last_error != WSAEWOULDBLOCK) {
  73. connection->close(connection);
  74. socket_close(connection);
  75. UA_ByteString_deleteMembers(buf);
  76. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  77. }
  78. #else
  79. n = send(connection->sockfd, (const char*)buf->data + nWritten, bytes_to_send, MSG_NOSIGNAL);
  80. if(n == -1L && errno != EINTR && errno != EAGAIN) {
  81. connection->close(connection);
  82. socket_close(connection);
  83. UA_ByteString_deleteMembers(buf);
  84. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  85. }
  86. #endif
  87. } while(n == -1L);
  88. nWritten += (size_t)n;
  89. } while(nWritten < buf->length);
  90. UA_ByteString_deleteMembers(buf);
  91. return UA_STATUSCODE_GOOD;
  92. }
  93. static UA_StatusCode
  94. socket_recv(UA_Connection *connection, UA_ByteString *response, UA_UInt32 timeout) {
  95. response->data = malloc(connection->localConf.recvBufferSize);
  96. if(!response->data) {
  97. response->length = 0;
  98. return UA_STATUSCODE_BADOUTOFMEMORY; /* not enough memory retry */
  99. }
  100. if(timeout > 0) {
  101. /* currently, only the client uses timeouts */
  102. #ifndef _WIN32
  103. UA_UInt32 timeout_usec = timeout * 1000;
  104. #ifdef __APPLE__
  105. struct timeval tmptv = {(long int)(timeout_usec / 1000000), timeout_usec % 1000000};
  106. #else
  107. struct timeval tmptv = {(long int)(timeout_usec / 1000000), (long int)(timeout_usec % 1000000)};
  108. #endif
  109. int ret = setsockopt(connection->sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char *)&tmptv, sizeof(struct timeval));
  110. #else
  111. DWORD timeout_dw = timeout;
  112. int ret = setsockopt(connection->sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout_dw, sizeof(DWORD));
  113. #endif
  114. if(0 != ret) {
  115. UA_ByteString_deleteMembers(response);
  116. socket_close(connection);
  117. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  118. }
  119. }
  120. #ifdef __CYGWIN__
  121. /* WORKAROUND for https://cygwin.com/ml/cygwin/2013-07/msg00107.html */
  122. ssize_t ret;
  123. if (timeout > 0) {
  124. fd_set fdset;
  125. UA_UInt32 timeout_usec = timeout * 1000;
  126. #ifdef __APPLE__
  127. struct timeval tmptv = {(long int)(timeout_usec / 1000000), timeout_usec % 1000000};
  128. #else
  129. struct timeval tmptv = {(long int)(timeout_usec / 1000000), (long int)(timeout_usec % 1000000)};
  130. #endif
  131. UA_Int32 retval;
  132. FD_ZERO(&fdset);
  133. UA_fd_set(connection->sockfd, &fdset);
  134. retval = select(connection->sockfd+1, &fdset, NULL, NULL, &tmptv);
  135. if(retval && UA_fd_isset(connection->sockfd, &fdset)) {
  136. ret = recv(connection->sockfd, (char*)response->data, connection->localConf.recvBufferSize, 0);
  137. } else {
  138. ret = 0;
  139. }
  140. } else {
  141. ret = recv(connection->sockfd, (char*)response->data, connection->localConf.recvBufferSize, 0);
  142. }
  143. #else
  144. ssize_t ret = recv(connection->sockfd, (char*)response->data, connection->localConf.recvBufferSize, 0);
  145. #endif
  146. if(ret == 0) {
  147. /* server has closed the connection */
  148. UA_ByteString_deleteMembers(response);
  149. socket_close(connection);
  150. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  151. } else if(ret < 0) {
  152. UA_ByteString_deleteMembers(response);
  153. #ifdef _WIN32
  154. const int last_error = WSAGetLastError();
  155. #define TEST_RETRY (last_error == WSAEINTR || (timeout > 0) ? 0 : (last_error == WSAEWOULDBLOCK))
  156. #else
  157. #define TEST_RETRY (errno == EINTR || (timeout > 0) ? 0 : (errno == EAGAIN || errno == EWOULDBLOCK))
  158. #endif
  159. if (TEST_RETRY)
  160. return UA_STATUSCODE_GOOD; /* retry */
  161. else {
  162. socket_close(connection);
  163. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  164. }
  165. }
  166. response->length = (size_t)ret;
  167. return UA_STATUSCODE_GOOD;
  168. }
  169. static UA_StatusCode socket_set_nonblocking(UA_Int32 sockfd) {
  170. #ifdef _WIN32
  171. u_long iMode = 1;
  172. if(ioctlsocket(sockfd, FIONBIO, &iMode) != NO_ERROR)
  173. return UA_STATUSCODE_BADINTERNALERROR;
  174. #else
  175. int opts = fcntl(sockfd, F_GETFL);
  176. if(opts < 0 || fcntl(sockfd, F_SETFL, opts|O_NONBLOCK) < 0)
  177. return UA_STATUSCODE_BADINTERNALERROR;
  178. #endif
  179. return UA_STATUSCODE_GOOD;
  180. }
  181. static void FreeConnectionCallback(UA_Server *server, void *ptr) {
  182. UA_Connection_deleteMembers((UA_Connection*)ptr);
  183. free(ptr);
  184. }
  185. /***************************/
  186. /* Server NetworkLayer TCP */
  187. /***************************/
  188. /**
  189. * For the multithreaded mode, assume a single thread that periodically "gets work" from the network
  190. * layer. In addition, several worker threads are asynchronously calling into the callbacks of the
  191. * UA_Connection that holds a single connection.
  192. *
  193. * Creating a connection: When "GetWork" encounters a new connection, it creates a UA_Connection
  194. * with the socket information. This is added to the mappings array that links sockets to
  195. * UA_Connection structs.
  196. *
  197. * Reading data: In "GetWork", we listen on the sockets in the mappings array. If data arrives (or
  198. * the connection closes), a WorkItem is created that carries the work and a pointer to the
  199. * connection.
  200. *
  201. * Closing a connection: Closing can happen in two ways. Either it is triggered by the server in an
  202. * asynchronous callback. Or the connection is close by the client and this is detected in
  203. * "GetWork". The server needs to do some internal cleanups (close attached securechannels, etc.).
  204. * So even when a closed connection is detected in "GetWork", we trigger the server to close the
  205. * connection (with a WorkItem) and continue from the callback.
  206. *
  207. * - Server calls close-callback: We close the socket, set the connection-state to closed and add
  208. * the connection to a linked list from which it is deleted later. The connection cannot be freed
  209. * right away since other threads might still be using it.
  210. *
  211. * - GetWork: We remove the connection from the mappings array. In the non-multithreaded case, the
  212. * connection is freed. For multithreading, we return a workitem that is delayed, i.e. that is
  213. * called only after all workitems created before are finished in all threads. This workitems
  214. * contains a callback that goes through the linked list of connections to be freed.
  215. *
  216. */
  217. #define MAXBACKLOG 100
  218. typedef struct {
  219. UA_ConnectionConfig conf;
  220. UA_UInt16 port;
  221. UA_Logger logger; // Set during start
  222. /* open sockets and connections */
  223. UA_Int32 serversockfd;
  224. size_t mappingsSize;
  225. struct ConnectionMapping {
  226. UA_Connection *connection;
  227. UA_Int32 sockfd;
  228. } *mappings;
  229. } ServerNetworkLayerTCP;
  230. static UA_StatusCode
  231. ServerNetworkLayerGetSendBuffer(UA_Connection *connection, size_t length, UA_ByteString *buf) {
  232. if(length > connection->remoteConf.recvBufferSize)
  233. return UA_STATUSCODE_BADCOMMUNICATIONERROR;
  234. return UA_ByteString_allocBuffer(buf, length);
  235. }
  236. static void
  237. ServerNetworkLayerReleaseSendBuffer(UA_Connection *connection, UA_ByteString *buf) {
  238. UA_ByteString_deleteMembers(buf);
  239. }
  240. static void
  241. ServerNetworkLayerReleaseRecvBuffer(UA_Connection *connection, UA_ByteString *buf) {
  242. UA_ByteString_deleteMembers(buf);
  243. }
  244. /* after every select, we need to reset the sockets we want to listen on */
  245. static UA_Int32
  246. setFDSet(ServerNetworkLayerTCP *layer, fd_set *fdset) {
  247. FD_ZERO(fdset);
  248. UA_fd_set(layer->serversockfd, fdset);
  249. UA_Int32 highestfd = layer->serversockfd;
  250. for(size_t i = 0; i < layer->mappingsSize; i++) {
  251. UA_fd_set(layer->mappings[i].sockfd, fdset);
  252. if(layer->mappings[i].sockfd > highestfd)
  253. highestfd = layer->mappings[i].sockfd;
  254. }
  255. return highestfd;
  256. }
  257. /* callback triggered from the server */
  258. static void
  259. ServerNetworkLayerTCP_closeConnection(UA_Connection *connection) {
  260. #ifdef UA_ENABLE_MULTITHREADING
  261. if(uatomic_xchg(&connection->state, UA_CONNECTION_CLOSED) == UA_CONNECTION_CLOSED)
  262. return;
  263. #else
  264. if(connection->state == UA_CONNECTION_CLOSED)
  265. return;
  266. connection->state = UA_CONNECTION_CLOSED;
  267. #endif
  268. #if UA_LOGLEVEL <= 300
  269. //cppcheck-suppress unreadVariable
  270. ServerNetworkLayerTCP *layer = connection->handle;
  271. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK, "Connection %i | Force closing the connection",
  272. connection->sockfd);
  273. #endif
  274. /* only "shutdown" here. this triggers the select, where the socket is
  275. "closed" in the mainloop */
  276. shutdown(connection->sockfd, 2);
  277. }
  278. /* call only from the single networking thread */
  279. static UA_StatusCode
  280. ServerNetworkLayerTCP_add(ServerNetworkLayerTCP *layer, UA_Int32 newsockfd) {
  281. UA_Connection *c = malloc(sizeof(UA_Connection));
  282. if(!c)
  283. return UA_STATUSCODE_BADINTERNALERROR;
  284. struct sockaddr_in addr;
  285. socklen_t addrlen = sizeof(struct sockaddr_in);
  286. int res = getpeername(newsockfd, (struct sockaddr*)&addr, &addrlen);
  287. if(res == 0) {
  288. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK, "Connection %i | New connection over TCP from %s:%d",
  289. newsockfd, inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
  290. } else {
  291. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK, "Connection %i | New connection over TCP, getpeername failed with errno %i",
  292. newsockfd, errno);
  293. }
  294. UA_Connection_init(c);
  295. c->sockfd = newsockfd;
  296. c->handle = layer;
  297. c->localConf = layer->conf;
  298. c->send = socket_write;
  299. c->close = ServerNetworkLayerTCP_closeConnection;
  300. c->getSendBuffer = ServerNetworkLayerGetSendBuffer;
  301. c->releaseSendBuffer = ServerNetworkLayerReleaseSendBuffer;
  302. c->releaseRecvBuffer = ServerNetworkLayerReleaseRecvBuffer;
  303. c->state = UA_CONNECTION_OPENING;
  304. struct ConnectionMapping *nm;
  305. nm = realloc(layer->mappings, sizeof(struct ConnectionMapping)*(layer->mappingsSize+1));
  306. if(!nm) {
  307. UA_LOG_ERROR(layer->logger, UA_LOGCATEGORY_NETWORK, "No memory for a new Connection");
  308. free(c);
  309. return UA_STATUSCODE_BADINTERNALERROR;
  310. }
  311. layer->mappings = nm;
  312. layer->mappings[layer->mappingsSize] = (struct ConnectionMapping){c, newsockfd};
  313. layer->mappingsSize++;
  314. return UA_STATUSCODE_GOOD;
  315. }
  316. static UA_StatusCode
  317. ServerNetworkLayerTCP_start(UA_ServerNetworkLayer *nl, UA_Logger logger) {
  318. ServerNetworkLayerTCP *layer = nl->handle;
  319. layer->logger = logger;
  320. /* get the discovery url from the hostname */
  321. UA_String du = UA_STRING_NULL;
  322. char hostname[256];
  323. if(gethostname(hostname, 255) == 0) {
  324. char discoveryUrl[256];
  325. #ifndef _MSC_VER
  326. du.length = (size_t)snprintf(discoveryUrl, 255, "opc.tcp://%s:%d", hostname, layer->port);
  327. #else
  328. du.length = (size_t)_snprintf_s(discoveryUrl, 255, _TRUNCATE,
  329. "opc.tcp://%s:%d", hostname, layer->port);
  330. #endif
  331. du.data = (UA_Byte*)discoveryUrl;
  332. }
  333. UA_String_copy(&du, &nl->discoveryUrl);
  334. /* open the server socket */
  335. #ifdef _WIN32
  336. if((layer->serversockfd = socket(PF_INET, SOCK_STREAM,0)) == (UA_Int32)INVALID_SOCKET) {
  337. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK, "Error opening socket, code: %d",
  338. WSAGetLastError());
  339. return UA_STATUSCODE_BADINTERNALERROR;
  340. }
  341. #else
  342. if((layer->serversockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
  343. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK, "Error opening socket");
  344. return UA_STATUSCODE_BADINTERNALERROR;
  345. }
  346. #endif
  347. const struct sockaddr_in serv_addr =
  348. {.sin_family = AF_INET, .sin_addr.s_addr = INADDR_ANY,
  349. .sin_port = htons(layer->port), .sin_zero = {0}};
  350. int optval = 1;
  351. if(setsockopt(layer->serversockfd, SOL_SOCKET,
  352. SO_REUSEADDR, (const char *)&optval, sizeof(optval)) == -1) {
  353. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
  354. "Error during setting of socket options");
  355. CLOSESOCKET(layer->serversockfd);
  356. return UA_STATUSCODE_BADINTERNALERROR;
  357. }
  358. if(bind(layer->serversockfd, (const struct sockaddr *)&serv_addr,
  359. sizeof(serv_addr)) < 0) {
  360. UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK, "Error during socket binding");
  361. CLOSESOCKET(layer->serversockfd);
  362. return UA_STATUSCODE_BADINTERNALERROR;
  363. }
  364. socket_set_nonblocking(layer->serversockfd);
  365. listen(layer->serversockfd, MAXBACKLOG);
  366. UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK, "TCP network layer listening on %.*s",
  367. nl->discoveryUrl.length, nl->discoveryUrl.data);
  368. return UA_STATUSCODE_GOOD;
  369. }
  370. static size_t
  371. ServerNetworkLayerTCP_getJobs(UA_ServerNetworkLayer *nl, UA_Job **jobs, UA_UInt16 timeout) {
  372. ServerNetworkLayerTCP *layer = nl->handle;
  373. fd_set fdset, errset;
  374. UA_Int32 highestfd = setFDSet(layer, &fdset);
  375. setFDSet(layer, &errset);
  376. struct timeval tmptv = {0, timeout * 1000};
  377. UA_Int32 resultsize = select(highestfd+1, &fdset, NULL, &errset, &tmptv);
  378. if(resultsize < 0) {
  379. *jobs = NULL;
  380. return 0;
  381. }
  382. /* accept new connections (can only be a single one) */
  383. if(UA_fd_isset(layer->serversockfd, &fdset)) {
  384. resultsize--;
  385. struct sockaddr_in cli_addr;
  386. socklen_t cli_len = sizeof(cli_addr);
  387. int newsockfd = accept(layer->serversockfd, (struct sockaddr *) &cli_addr, &cli_len);
  388. int i = 1;
  389. if(newsockfd >= 0) {
  390. /* Send messages directly and do wait to merge packets (disable Nagle's algorithm) */
  391. setsockopt(newsockfd, IPPROTO_TCP, TCP_NODELAY, (void *)&i, sizeof(i));
  392. socket_set_nonblocking(newsockfd);
  393. ServerNetworkLayerTCP_add(layer, 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(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. UA_Connection connection;
  522. UA_Connection_init(&connection);
  523. connection.localConf = localConf;
  524. //socket_set_nonblocking(connection.sockfd);
  525. connection.send = socket_write;
  526. connection.recv = socket_recv;
  527. connection.close = ClientNetworkLayerClose;
  528. connection.getSendBuffer = ClientNetworkLayerGetBuffer;
  529. connection.releaseSendBuffer = ClientNetworkLayerReleaseBuffer;
  530. connection.releaseRecvBuffer = ClientNetworkLayerReleaseBuffer;
  531. size_t urlLength = strlen(endpointUrl);
  532. if(urlLength < 11 || urlLength >= 512) {
  533. UA_LOG_WARNING((*logger), UA_LOGCATEGORY_NETWORK, "Server url size invalid");
  534. return connection;
  535. }
  536. if(strncmp(endpointUrl, "opc.tcp://", 10) != 0) {
  537. UA_LOG_WARNING((*logger), UA_LOGCATEGORY_NETWORK, "Server url does not begin with opc.tcp://");
  538. return connection;
  539. }
  540. UA_UInt16 portpos = 9;
  541. UA_UInt16 port;
  542. for(port = 0; portpos < urlLength-1; portpos++) {
  543. if(endpointUrl[portpos] == ':') {
  544. char *endPtr = NULL;
  545. unsigned long int tempulong = strtoul(&endpointUrl[portpos+1], &endPtr, 10);
  546. if (ERANGE != errno && tempulong < UINT16_MAX && endPtr != &endpointUrl[portpos+1])
  547. port = (UA_UInt16)tempulong;
  548. break;
  549. }
  550. }
  551. if(port == 0) {
  552. UA_LOG_WARNING((*logger), UA_LOGCATEGORY_NETWORK, "Port invalid");
  553. return connection;
  554. }
  555. char hostname[512];
  556. for(int i=10; i < portpos; i++)
  557. hostname[i-10] = endpointUrl[i];
  558. hostname[portpos-10] = 0;
  559. #ifdef _WIN32
  560. WORD wVersionRequested;
  561. WSADATA wsaData;
  562. wVersionRequested = MAKEWORD(2, 2);
  563. WSAStartup(wVersionRequested, &wsaData);
  564. if((connection.sockfd = socket(PF_INET, SOCK_STREAM,0)) == (UA_Int32)INVALID_SOCKET) {
  565. #else
  566. if((connection.sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
  567. #endif
  568. UA_LOG_WARNING((*logger), UA_LOGCATEGORY_NETWORK, "Could not create socket");
  569. return connection;
  570. }
  571. struct hostent *server = gethostbyname(hostname);
  572. if(!server) {
  573. UA_LOG_WARNING((*logger), UA_LOGCATEGORY_NETWORK, "DNS lookup of %s failed", hostname);
  574. return connection;
  575. }
  576. struct sockaddr_in server_addr;
  577. memset(&server_addr, 0, sizeof(server_addr));
  578. memcpy((char *)&server_addr.sin_addr.s_addr, (char *)server->h_addr_list[0], (size_t)server->h_length);
  579. server_addr.sin_family = AF_INET;
  580. server_addr.sin_port = htons(port);
  581. connection.state = UA_CONNECTION_OPENING;
  582. if(connect(connection.sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
  583. ClientNetworkLayerClose(&connection);
  584. UA_LOG_WARNING((*logger), UA_LOGCATEGORY_NETWORK, "Connection failed");
  585. return connection;
  586. }
  587. #ifdef SO_NOSIGPIPE
  588. int val = 1;
  589. if(setsockopt(connection.sockfd, SOL_SOCKET, SO_NOSIGPIPE, (void*)&val, sizeof(val)) < 0) {
  590. UA_LOG_WARNING((*logger), UA_LOGCATEGORY_NETWORK, "Couldn't set SO_NOSIGPIPE");
  591. return connection;
  592. }
  593. #endif
  594. return connection;
  595. }