networklayer_tcp.c 23 KB

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