networklayer_tcp.c 23 KB

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