networklayer_tcp.c 23 KB

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