ua_network_tcp.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
  2. * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. */
  3. #if defined(__MINGW32__) && (!defined(WINVER) || WINVER < 0x501)
  4. /* Assume the target is newer than Windows XP */
  5. # undef WINVER
  6. # undef _WIN32_WINDOWS
  7. # undef _WIN32_WINNT
  8. # define WINVER 0x0501
  9. # define _WIN32_WINDOWS 0x0501
  10. # define _WIN32_WINNT 0x0501
  11. #endif
  12. #include "ua_network_tcp.h"
  13. #include "ua_log_stdout.h"
  14. #include "queue.h"
  15. #include <stdlib.h> // malloc, free
  16. #include <stdio.h> // snprintf
  17. #include <string.h> // memset
  18. #include <errno.h>
  19. #ifdef _WIN32
  20. # include <winsock2.h>
  21. # include <ws2tcpip.h>
  22. # define CLOSESOCKET(S) closesocket((SOCKET)S)
  23. # define ssize_t int
  24. # define WIN32_INT (int)
  25. #else
  26. # define CLOSESOCKET(S) close(S)
  27. # define SOCKET int
  28. # define WIN32_INT
  29. # include <arpa/inet.h>
  30. # include <netinet/in.h>
  31. # include <sys/select.h>
  32. # include <sys/ioctl.h>
  33. # include <fcntl.h>
  34. # include <unistd.h> // read, write, close
  35. # include <netdb.h>
  36. # ifdef __QNX__
  37. # include <sys/socket.h>
  38. # endif
  39. #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
  40. # include <sys/param.h>
  41. # if defined(BSD)
  42. # include<sys/socket.h>
  43. # endif
  44. #endif
  45. # ifndef __CYGWIN__
  46. # include <netinet/tcp.h>
  47. # endif
  48. #endif
  49. /* unsigned int for windows and workaround to a glibc bug */
  50. /* Additionally if GNU_LIBRARY is not defined, it may be using musl libc (e.g. Docker Alpine) */
  51. #if defined(_WIN32) || defined(__OpenBSD__) || \
  52. (defined(__GNU_LIBRARY__) && (__GNU_LIBRARY__ <= 6) && \
  53. (__GLIBC__ <= 2) && (__GLIBC_MINOR__ < 16) || \
  54. !defined(__GNU_LIBRARY__))
  55. # define UA_fd_set(fd, fds) FD_SET((unsigned int)fd, fds)
  56. # define UA_fd_isset(fd, fds) FD_ISSET((unsigned int)fd, fds)
  57. #else
  58. # define UA_fd_set(fd, fds) FD_SET(fd, fds)
  59. # define UA_fd_isset(fd, fds) FD_ISSET(fd, fds)
  60. #endif
  61. #if UNDER_CE
  62. # define errno WSAGetLastError()
  63. #endif
  64. #ifdef _WIN32
  65. #define errno__ WSAGetLastError()
  66. # define INTERRUPTED WSAEINTR
  67. # define WOULDBLOCK WSAEWOULDBLOCK
  68. # define AGAIN WSAEWOULDBLOCK
  69. #else
  70. # define errno__ errno
  71. # define INTERRUPTED EINTR
  72. # define WOULDBLOCK EWOULDBLOCK
  73. # define AGAIN EAGAIN
  74. #endif
  75. /****************************/
  76. /* Generic Socket Functions */
  77. /****************************/
  78. /* This performs only 'shutdown'. 'close' is called after the next recv on the
  79. * socket. */
  80. static void
  81. connection_close(UA_Connection *connection) {
  82. shutdown((SOCKET)connection->sockfd, 2);
  83. connection->state = UA_CONNECTION_CLOSED;
  84. }
  85. static UA_StatusCode
  86. connection_getsendbuffer(UA_Connection *connection,
  87. size_t length, UA_ByteString *buf) {
  88. if(length > connection->remoteConf.recvBufferSize)
  89. return UA_STATUSCODE_BADCOMMUNICATIONERROR;
  90. return UA_ByteString_allocBuffer(buf, length);
  91. }
  92. static void
  93. connection_releasesendbuffer(UA_Connection *connection,
  94. UA_ByteString *buf) {
  95. UA_ByteString_deleteMembers(buf);
  96. }
  97. static void
  98. connection_releaserecvbuffer(UA_Connection *connection,
  99. UA_ByteString *buf) {
  100. UA_ByteString_deleteMembers(buf);
  101. }
  102. static UA_StatusCode
  103. connection_write(UA_Connection *connection, UA_ByteString *buf) {
  104. /* Prevent OS signals when sending to a closed socket */
  105. int flags = 0;
  106. #ifdef MSG_NOSIGNAL
  107. flags |= MSG_NOSIGNAL;
  108. #endif
  109. /* Send the full buffer. This may require several calls to send */
  110. size_t nWritten = 0;
  111. do {
  112. ssize_t n = 0;
  113. do {
  114. size_t bytes_to_send = buf->length - nWritten;
  115. n = send((SOCKET)connection->sockfd,
  116. (const char*)buf->data + nWritten,
  117. WIN32_INT bytes_to_send, flags);
  118. if(n < 0 && errno__ != INTERRUPTED && errno__ != AGAIN) {
  119. connection_close(connection);
  120. UA_ByteString_deleteMembers(buf);
  121. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  122. }
  123. } while(n < 0);
  124. nWritten += (size_t)n;
  125. } while(nWritten < buf->length);
  126. /* Free the buffer */
  127. UA_ByteString_deleteMembers(buf);
  128. return UA_STATUSCODE_GOOD;
  129. }
  130. static UA_StatusCode
  131. connection_recv(UA_Connection *connection, UA_ByteString *response,
  132. UA_UInt32 timeout) {
  133. response->data =
  134. (UA_Byte*)malloc(connection->localConf.recvBufferSize);
  135. if(!response->data) {
  136. response->length = 0;
  137. return UA_STATUSCODE_BADOUTOFMEMORY; /* not enough memory retry */
  138. }
  139. if(timeout > 0) {
  140. /* currently, only the client uses timeouts */
  141. #ifndef _WIN32
  142. UA_UInt32 timeout_usec = timeout * 1000;
  143. # ifdef __APPLE__
  144. struct timeval tmptv = {(long int)(timeout_usec / 1000000), timeout_usec % 1000000};
  145. # else
  146. struct timeval tmptv = {(long int)(timeout_usec / 1000000), (long int)(timeout_usec % 1000000)};
  147. # endif
  148. int ret = setsockopt(connection->sockfd, SOL_SOCKET, SO_RCVTIMEO,
  149. (const char *)&tmptv, sizeof(struct timeval));
  150. #else
  151. DWORD timeout_dw = timeout;
  152. int ret = setsockopt(connection->sockfd, SOL_SOCKET, SO_RCVTIMEO,
  153. (const char*)&timeout_dw, sizeof(DWORD));
  154. #endif
  155. if(0 != ret) {
  156. UA_ByteString_deleteMembers(response);
  157. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  158. }
  159. }
  160. #ifdef __CYGWIN__
  161. /* Workaround for https://cygwin.com/ml/cygwin/2013-07/msg00107.html */
  162. ssize_t ret;
  163. if(timeout > 0) {
  164. fd_set fdset;
  165. FD_ZERO(&fdset);
  166. UA_fd_set(connection->sockfd, &fdset);
  167. UA_UInt32 timeout_usec = timeout * 1000;
  168. struct timeval tmptv = {(long int)(timeout_usec / 1000000),
  169. (long int)(timeout_usec % 1000000)};
  170. int retval = select(connection->sockfd+1, &fdset, NULL, NULL, &tmptv);
  171. if(retval && UA_fd_isset(connection->sockfd, &fdset)) {
  172. ret = recv(connection->sockfd, (char*)response->data,
  173. connection->localConf.recvBufferSize, 0);
  174. } else {
  175. ret = 0;
  176. }
  177. } else {
  178. ret = recv(connection->sockfd, (char*)response->data,
  179. connection->localConf.recvBufferSize, 0);
  180. }
  181. #else
  182. ssize_t ret = recv(connection->sockfd, (char*)response->data,
  183. connection->localConf.recvBufferSize, 0);
  184. #endif
  185. /* The socket is shutdown */
  186. if(ret == 0) {
  187. UA_ByteString_deleteMembers(response);
  188. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  189. }
  190. /* error case */
  191. if(ret < 0) {
  192. UA_ByteString_deleteMembers(response);
  193. if(errno__ == INTERRUPTED || (timeout > 0) ?
  194. false : (errno__ == EAGAIN || errno__ == WOULDBLOCK))
  195. return UA_STATUSCODE_GOOD; /* statuscode_good but no data -> retry */
  196. connection_close(connection);
  197. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  198. }
  199. /* default case */
  200. response->length = (size_t)ret;
  201. return UA_STATUSCODE_GOOD;
  202. }
  203. static UA_StatusCode socket_set_nonblocking(SOCKET sockfd) {
  204. #ifdef _WIN32
  205. u_long iMode = 1;
  206. if(ioctlsocket(sockfd, FIONBIO, &iMode) != NO_ERROR)
  207. return UA_STATUSCODE_BADINTERNALERROR;
  208. #else
  209. int opts = fcntl(sockfd, F_GETFL);
  210. if(opts < 0 || fcntl(sockfd, F_SETFL, opts|O_NONBLOCK) < 0)
  211. return UA_STATUSCODE_BADINTERNALERROR;
  212. #endif
  213. return UA_STATUSCODE_GOOD;
  214. }
  215. /***************************/
  216. /* Server NetworkLayer TCP */
  217. /***************************/
  218. #define MAXBACKLOG 100
  219. typedef struct ConnectionEntry {
  220. UA_Connection connection;
  221. LIST_ENTRY(ConnectionEntry) pointers;
  222. } ConnectionEntry;
  223. typedef struct {
  224. UA_ConnectionConfig conf;
  225. UA_UInt16 port;
  226. UA_Int32 serverSockets[FD_SETSIZE];
  227. UA_UInt16 serverSocketsSize;
  228. LIST_HEAD(, ConnectionEntry) connections;
  229. } ServerNetworkLayerTCP;
  230. static void
  231. ServerNetworkLayerTCP_freeConnection(UA_Connection *connection) {
  232. UA_Connection_deleteMembers(connection);
  233. free(connection);
  234. }
  235. static UA_StatusCode
  236. ServerNetworkLayerTCP_add(ServerNetworkLayerTCP *layer, UA_Int32 newsockfd,
  237. struct sockaddr_storage *remote) {
  238. /* Get the peer name for logging */
  239. char remote_name[100];
  240. if(getnameinfo((struct sockaddr*)remote, sizeof(struct sockaddr_storage), remote_name,
  241. sizeof(remote_name), NULL, 0, 0) == 0) {
  242. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  243. "Connection %i | New connection over TCP from %s",
  244. newsockfd, remote_name);
  245. } else {
  246. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  247. "Connection %i | New connection over TCP, "
  248. "getnameinfo failed with errno %i", newsockfd, errno__);
  249. }
  250. /* Allocate and initialize the connection */
  251. ConnectionEntry *e = (ConnectionEntry*)malloc(sizeof(ConnectionEntry));
  252. if(!e)
  253. return UA_STATUSCODE_BADOUTOFMEMORY;
  254. UA_Connection *c = &e->connection;
  255. memset(c, 0, sizeof(UA_Connection));
  256. c->sockfd = newsockfd;
  257. c->handle = layer;
  258. c->localConf = layer->conf;
  259. c->remoteConf = layer->conf;
  260. c->send = connection_write;
  261. c->close = connection_close;
  262. c->free = ServerNetworkLayerTCP_freeConnection;
  263. c->getSendBuffer = connection_getsendbuffer;
  264. c->releaseSendBuffer = connection_releasesendbuffer;
  265. c->releaseRecvBuffer = connection_releaserecvbuffer;
  266. c->state = UA_CONNECTION_OPENING;
  267. /* Add to the linked list */
  268. LIST_INSERT_HEAD(&layer->connections, e, pointers);
  269. return UA_STATUSCODE_GOOD;
  270. }
  271. static void
  272. addServerSockets(ServerNetworkLayerTCP *layer, struct addrinfo *ai) {
  273. /* There might be serveral addrinfos (for different network cards,
  274. * IPv4/IPv6). Add a server socket for all of them. */
  275. for(layer->serverSocketsSize = 0;
  276. layer->serverSocketsSize < FD_SETSIZE && ai != NULL;
  277. ai = ai->ai_next) {
  278. /* Create the server socket */
  279. SOCKET newsock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
  280. #ifdef _WIN32
  281. if(newsock == INVALID_SOCKET)
  282. #else
  283. if(newsock < 0)
  284. #endif
  285. {
  286. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  287. "Error opening the server socket");
  288. continue;
  289. }
  290. /* Some Linux distributions have net.ipv6.bindv6only not activated. So
  291. * sockets can double-bind to IPv4 and IPv6. This leads to problems. Use
  292. * AF_INET6 sockets only for IPv6. */
  293. int optval = 1;
  294. if(ai->ai_family == AF_INET6 &&
  295. setsockopt(newsock, IPPROTO_IPV6, IPV6_V6ONLY,
  296. (const char*)&optval, sizeof(optval)) == -1) {
  297. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  298. "Could not set an IPv6 socket to IPv6 only");
  299. CLOSESOCKET(newsock);
  300. continue;
  301. }
  302. if(setsockopt(newsock, SOL_SOCKET, SO_REUSEADDR,
  303. (const char *)&optval, sizeof(optval)) == -1) {
  304. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  305. "Could not make the socket reusable");
  306. CLOSESOCKET(newsock);
  307. continue;
  308. }
  309. if(socket_set_nonblocking(newsock) != UA_STATUSCODE_GOOD) {
  310. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  311. "Could not set the server socket to nonblocking");
  312. CLOSESOCKET(newsock);
  313. continue;
  314. }
  315. /* Bind socket to address */
  316. if(bind(newsock, ai->ai_addr, WIN32_INT ai->ai_addrlen) < 0) {
  317. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  318. "Error binding a server socket: %i", errno__);
  319. CLOSESOCKET(newsock);
  320. continue;
  321. }
  322. /* Start listening */
  323. if(listen(newsock, MAXBACKLOG) < 0) {
  324. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  325. "Error listening on server socket");
  326. CLOSESOCKET(newsock);
  327. continue;
  328. }
  329. layer->serverSockets[layer->serverSocketsSize] = (UA_Int32)newsock;
  330. layer->serverSocketsSize++;
  331. }
  332. }
  333. static UA_StatusCode
  334. ServerNetworkLayerTCP_start(UA_ServerNetworkLayer *nl) {
  335. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  336. /* Get the discovery url from the hostname */
  337. UA_String du = UA_STRING_NULL;
  338. char hostname[256];
  339. if(gethostname(hostname, 255) == 0) {
  340. char discoveryUrl[256];
  341. #ifndef _MSC_VER
  342. du.length = (size_t)snprintf(discoveryUrl, 255, "opc.tcp://%s:%d",
  343. hostname, layer->port);
  344. #else
  345. du.length = (size_t)_snprintf_s(discoveryUrl, 255, _TRUNCATE,
  346. "opc.tcp://%s:%d", hostname, layer->port);
  347. #endif
  348. du.data = (UA_Byte*)discoveryUrl;
  349. }
  350. UA_String_copy(&du, &nl->discoveryUrl);
  351. /* Get addrinfo of the server and create server sockets */
  352. char portno[6];
  353. #ifndef _MSC_VER
  354. snprintf(portno, 6, "%d", layer->port);
  355. #else
  356. _snprintf_s(portno, 6, _TRUNCATE, "%d", layer->port);
  357. #endif
  358. struct addrinfo hints, *res;
  359. memset(&hints, 0, sizeof hints);
  360. hints.ai_family = AF_UNSPEC;
  361. hints.ai_socktype = SOCK_STREAM;
  362. hints.ai_flags = AI_PASSIVE;
  363. getaddrinfo(NULL, portno, &hints, &res);
  364. addServerSockets(layer, res);
  365. freeaddrinfo(res);
  366. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  367. "TCP network layer listening on %.*s",
  368. nl->discoveryUrl.length, nl->discoveryUrl.data);
  369. return UA_STATUSCODE_GOOD;
  370. }
  371. /* After every select, reset the sockets to listen on */
  372. static UA_Int32
  373. setFDSet(ServerNetworkLayerTCP *layer, fd_set *fdset) {
  374. FD_ZERO(fdset);
  375. UA_Int32 highestfd = 0;
  376. for(UA_UInt16 i = 0; i < layer->serverSocketsSize; i++) {
  377. UA_fd_set(layer->serverSockets[i], fdset);
  378. if(layer->serverSockets[i] > highestfd)
  379. highestfd = layer->serverSockets[i];
  380. }
  381. ConnectionEntry *e;
  382. LIST_FOREACH(e, &layer->connections, pointers) {
  383. UA_fd_set(e->connection.sockfd, fdset);
  384. if(e->connection.sockfd > highestfd)
  385. highestfd = e->connection.sockfd;
  386. }
  387. return highestfd;
  388. }
  389. static UA_StatusCode
  390. ServerNetworkLayerTCP_listen(UA_ServerNetworkLayer *nl, UA_Server *server,
  391. UA_UInt16 timeout) {
  392. /* Every open socket can generate two jobs */
  393. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  394. /* Listen on open sockets (including the server) */
  395. fd_set fdset, errset;
  396. UA_Int32 highestfd = setFDSet(layer, &fdset);
  397. setFDSet(layer, &errset);
  398. struct timeval tmptv = {0, timeout * 1000};
  399. select(highestfd+1, &fdset, NULL, &errset, &tmptv);
  400. /* Accept new connections via the server sockets */
  401. for(UA_UInt16 i = 0; i < layer->serverSocketsSize; i++) {
  402. if(!UA_fd_isset(layer->serverSockets[i], &fdset))
  403. continue;
  404. struct sockaddr_storage remote;
  405. socklen_t remote_size = sizeof(remote);
  406. SOCKET newsockfd = accept((SOCKET)layer->serverSockets[i],
  407. (struct sockaddr*)&remote, &remote_size);
  408. #ifdef _WIN32
  409. if(newsockfd == INVALID_SOCKET)
  410. #else
  411. if(newsockfd < 0)
  412. #endif
  413. continue;
  414. socket_set_nonblocking(newsockfd);
  415. /* Do not merge packets on the socket (disable Nagle's algorithm) */
  416. int dummy = 1;
  417. setsockopt(newsockfd, IPPROTO_TCP, TCP_NODELAY,
  418. (const char *)&dummy, sizeof(dummy));
  419. ServerNetworkLayerTCP_add(layer, (UA_Int32)newsockfd, &remote);
  420. }
  421. /* Read from established sockets */
  422. ConnectionEntry *e, *e_tmp;
  423. LIST_FOREACH_SAFE(e, &layer->connections, pointers, e_tmp) {
  424. if(!UA_fd_isset(e->connection.sockfd, &errset) &&
  425. !UA_fd_isset(e->connection.sockfd, &fdset))
  426. continue;
  427. UA_ByteString buf = UA_BYTESTRING_NULL;
  428. UA_StatusCode retval = connection_recv(&e->connection, &buf, 0);
  429. if(retval == UA_STATUSCODE_GOOD) {
  430. /* Process packets */
  431. UA_Server_processBinaryMessage(server, &e->connection, &buf);
  432. } else if(retval == UA_STATUSCODE_BADCONNECTIONCLOSED) {
  433. /* The socket is shutdown but not closed */
  434. if(e->connection.state != UA_CONNECTION_CLOSED) {
  435. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  436. "Connection %d was closed by the client",
  437. e->connection.sockfd);
  438. } else {
  439. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  440. "Connection %d was closed by the server",
  441. e->connection.sockfd);
  442. }
  443. LIST_REMOVE(e, pointers);
  444. CLOSESOCKET(e->connection.sockfd);
  445. UA_Server_removeConnection(server, &e->connection);
  446. }
  447. }
  448. return UA_STATUSCODE_GOOD;
  449. }
  450. static void
  451. ServerNetworkLayerTCP_stop(UA_ServerNetworkLayer *nl, UA_Server *server) {
  452. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  453. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  454. "Shutting down the TCP network layer");
  455. /* Close the server sockets */
  456. for(UA_UInt16 i = 0; i < layer->serverSocketsSize; i++) {
  457. shutdown((SOCKET)layer->serverSockets[i], 2);
  458. CLOSESOCKET(layer->serverSockets[i]);
  459. }
  460. layer->serverSocketsSize = 0;
  461. /* Close open connections */
  462. ConnectionEntry *e, *e_tmp;
  463. LIST_FOREACH_SAFE(e, &layer->connections, pointers, e_tmp)
  464. connection_close(&e->connection);
  465. /* Run recv on client sockets. This picks up the closed sockets and frees
  466. * the connection. */
  467. ServerNetworkLayerTCP_listen(nl, server, 0);
  468. #ifdef _WIN32
  469. WSACleanup();
  470. #endif
  471. }
  472. /* run only when the server is stopped */
  473. static void
  474. ServerNetworkLayerTCP_deleteMembers(UA_ServerNetworkLayer *nl) {
  475. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  476. UA_String_deleteMembers(&nl->discoveryUrl);
  477. UA_free(layer);
  478. }
  479. UA_ServerNetworkLayer
  480. UA_ServerNetworkLayerTCP(UA_ConnectionConfig conf, UA_UInt16 port) {
  481. #ifdef _WIN32
  482. WORD wVersionRequested;
  483. WSADATA wsaData;
  484. wVersionRequested = MAKEWORD(2, 2);
  485. WSAStartup(wVersionRequested, &wsaData);
  486. #endif
  487. UA_ServerNetworkLayer nl;
  488. memset(&nl, 0, sizeof(UA_ServerNetworkLayer));
  489. ServerNetworkLayerTCP *layer =
  490. (ServerNetworkLayerTCP *)calloc(1,sizeof(ServerNetworkLayerTCP));
  491. if(!layer)
  492. return nl;
  493. layer->conf = conf;
  494. layer->port = port;
  495. nl.handle = layer;
  496. nl.start = ServerNetworkLayerTCP_start;
  497. nl.listen = ServerNetworkLayerTCP_listen;
  498. nl.stop = ServerNetworkLayerTCP_stop;
  499. nl.deleteMembers = ServerNetworkLayerTCP_deleteMembers;
  500. return nl;
  501. }
  502. /***************************/
  503. /* Client NetworkLayer TCP */
  504. /***************************/
  505. UA_Connection
  506. UA_ClientConnectionTCP(UA_ConnectionConfig conf, const char *endpointUrl) {
  507. #ifdef _WIN32
  508. WORD wVersionRequested;
  509. WSADATA wsaData;
  510. wVersionRequested = MAKEWORD(2, 2);
  511. WSAStartup(wVersionRequested, &wsaData);
  512. #endif
  513. UA_Connection connection;
  514. memset(&connection, 0, sizeof(UA_Connection));
  515. connection.state = UA_CONNECTION_OPENING;
  516. connection.localConf = conf;
  517. connection.remoteConf = conf;
  518. connection.send = connection_write;
  519. connection.recv = connection_recv;
  520. connection.close = connection_close;
  521. connection.free = NULL;
  522. connection.getSendBuffer = connection_getsendbuffer;
  523. connection.releaseSendBuffer = connection_releasesendbuffer;
  524. connection.releaseRecvBuffer = connection_releaserecvbuffer;
  525. UA_String endpointUrlString = UA_STRING((char*)(uintptr_t)endpointUrl);
  526. UA_String hostnameString = UA_STRING_NULL;
  527. UA_String pathString = UA_STRING_NULL;
  528. UA_UInt16 port = 0;
  529. char hostname[512];
  530. UA_StatusCode parse_retval =
  531. UA_parseEndpointUrl(&endpointUrlString, &hostnameString, &port, &pathString);
  532. if(parse_retval != UA_STATUSCODE_GOOD || hostnameString.length > 511) {
  533. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  534. "Server url is invalid: %s", endpointUrl);
  535. return connection;
  536. }
  537. memcpy(hostname, hostnameString.data, hostnameString.length);
  538. hostname[hostnameString.length] = 0;
  539. if(port == 0) {
  540. port = 4840;
  541. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  542. "No port defined, using default port %d", port);
  543. }
  544. struct addrinfo hints, *server;
  545. memset(&hints, 0, sizeof(hints));
  546. hints.ai_family = AF_UNSPEC;
  547. hints.ai_socktype = SOCK_STREAM;
  548. char portStr[6];
  549. #ifndef _MSC_VER
  550. snprintf(portStr, 6, "%d", port);
  551. #else
  552. _snprintf_s(portStr, 6, _TRUNCATE, "%d", port);
  553. #endif
  554. int error = getaddrinfo(hostname, portStr, &hints, &server);
  555. if(error != 0 || !server) {
  556. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  557. "DNS lookup of %s failed with error %s",
  558. hostname, gai_strerror(error));
  559. return connection;
  560. }
  561. /* Get a socket */
  562. SOCKET clientsockfd = socket(server->ai_family, server->ai_socktype,
  563. server->ai_protocol);
  564. #ifdef _WIN32
  565. if(clientsockfd == INVALID_SOCKET) {
  566. #else
  567. if(clientsockfd < 0) {
  568. #endif
  569. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  570. "Could not create client socket");
  571. freeaddrinfo(server);
  572. return connection;
  573. }
  574. /* Connect to the server */
  575. connection.sockfd = (UA_Int32)clientsockfd; /* cast for win32 */
  576. error = connect(clientsockfd, server->ai_addr, WIN32_INT server->ai_addrlen);
  577. freeaddrinfo(server);
  578. if(error < 0) {
  579. connection_close(&connection);
  580. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  581. "Connection to %s failed with error %d",
  582. endpointUrl, errno__);
  583. return connection;
  584. }
  585. #ifdef SO_NOSIGPIPE
  586. int val = 1;
  587. int sso_result = setsockopt(connection.sockfd, SOL_SOCKET,
  588. SO_NOSIGPIPE, (void*)&val, sizeof(val));
  589. if(sso_result < 0)
  590. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  591. "Couldn't set SO_NOSIGPIPE");
  592. #endif
  593. return connection;
  594. }