ua_network_tcp.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  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. /* Enable POSIX features */
  4. #ifndef _XOPEN_SOURCE
  5. # define _XOPEN_SOURCE 600
  6. #endif
  7. #ifndef _DEFAULT_SOURCE
  8. # define _DEFAULT_SOURCE
  9. #endif
  10. /* On older systems we need to define _BSD_SOURCE.
  11. * _DEFAULT_SOURCE is an alias for that. */
  12. #ifndef _BSD_SOURCE
  13. # define _BSD_SOURCE
  14. #endif
  15. /* Disable some security warnings on MSVC */
  16. #ifdef _MSC_VER
  17. # define _CRT_SECURE_NO_WARNINGS
  18. #endif
  19. /* Assume that Windows versions are newer than Windows XP */
  20. #if defined(__MINGW32__) && (!defined(WINVER) || WINVER < 0x501)
  21. # undef WINVER
  22. # undef _WIN32_WINDOWS
  23. # undef _WIN32_WINNT
  24. # define WINVER 0x0501
  25. # define _WIN32_WINDOWS 0x0501
  26. # define _WIN32_WINNT 0x0501
  27. #endif
  28. #include "ua_network_tcp.h"
  29. #include "ua_log_stdout.h"
  30. #include "queue.h"
  31. #include <stdio.h> // snprintf
  32. #include <string.h> // memset
  33. #include <errno.h>
  34. #ifdef _WIN32
  35. # include <winsock2.h>
  36. # include <ws2tcpip.h>
  37. # define CLOSESOCKET(S) closesocket((SOCKET)S)
  38. # define ssize_t int
  39. # define WIN32_INT (int)
  40. # define OPTVAL_TYPE char
  41. # define ERR_CONNECTION_PROGRESS WSAEWOULDBLOCK
  42. # define UA_sleep_ms(X) Sleep(X)
  43. #else
  44. # define CLOSESOCKET(S) close(S)
  45. # define SOCKET int
  46. # define WIN32_INT
  47. # define OPTVAL_TYPE int
  48. # define ERR_CONNECTION_PROGRESS EINPROGRESS
  49. # define UA_sleep_ms(X) usleep(X * 1000)
  50. # include <arpa/inet.h>
  51. # include <netinet/in.h>
  52. # ifndef _WRS_KERNEL
  53. # include <sys/select.h>
  54. # else
  55. # include <hostLib.h>
  56. # include <selectLib.h>
  57. # endif
  58. # include <sys/ioctl.h>
  59. # include <fcntl.h>
  60. # include <unistd.h> // read, write, close
  61. # include <netdb.h>
  62. # ifdef __QNX__
  63. # include <sys/socket.h>
  64. # endif
  65. #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
  66. # include <sys/param.h>
  67. # if defined(BSD)
  68. # include<sys/socket.h>
  69. # endif
  70. #endif
  71. # ifndef __CYGWIN__
  72. # include <netinet/tcp.h>
  73. # endif
  74. #endif
  75. /* unsigned int for windows and workaround to a glibc bug */
  76. /* Additionally if GNU_LIBRARY is not defined, it may be using
  77. * musl libc (e.g. Docker Alpine) */
  78. #if defined(_WIN32) || defined(__OpenBSD__) || \
  79. (defined(__GNU_LIBRARY__) && (__GNU_LIBRARY__ <= 6) && \
  80. (__GLIBC__ <= 2) && (__GLIBC_MINOR__ < 16) || \
  81. !defined(__GNU_LIBRARY__))
  82. # define UA_fd_set(fd, fds) FD_SET((unsigned int)fd, fds)
  83. # define UA_fd_isset(fd, fds) FD_ISSET((unsigned int)fd, fds)
  84. #else
  85. # define UA_fd_set(fd, fds) FD_SET(fd, fds)
  86. # define UA_fd_isset(fd, fds) FD_ISSET(fd, fds)
  87. #endif
  88. #ifdef UNDER_CE
  89. # define errno WSAGetLastError()
  90. #endif
  91. #ifdef _WIN32
  92. # define errno__ WSAGetLastError()
  93. # define INTERRUPTED WSAEINTR
  94. # define WOULDBLOCK WSAEWOULDBLOCK
  95. # define AGAIN WSAEWOULDBLOCK
  96. #else
  97. # define errno__ errno
  98. # define INTERRUPTED EINTR
  99. # define WOULDBLOCK EWOULDBLOCK
  100. # define AGAIN EAGAIN
  101. #endif
  102. /****************************/
  103. /* Generic Socket Functions */
  104. /****************************/
  105. static UA_StatusCode
  106. connection_getsendbuffer(UA_Connection *connection,
  107. size_t length, UA_ByteString *buf) {
  108. if(length > connection->remoteConf.recvBufferSize)
  109. return UA_STATUSCODE_BADCOMMUNICATIONERROR;
  110. return UA_ByteString_allocBuffer(buf, length);
  111. }
  112. static void
  113. connection_releasesendbuffer(UA_Connection *connection,
  114. UA_ByteString *buf) {
  115. UA_ByteString_deleteMembers(buf);
  116. }
  117. static void
  118. connection_releaserecvbuffer(UA_Connection *connection,
  119. UA_ByteString *buf) {
  120. UA_ByteString_deleteMembers(buf);
  121. }
  122. static UA_StatusCode
  123. connection_write(UA_Connection *connection, UA_ByteString *buf) {
  124. /* Prevent OS signals when sending to a closed socket */
  125. int flags = 0;
  126. #ifdef MSG_NOSIGNAL
  127. flags |= MSG_NOSIGNAL;
  128. #endif
  129. /* Send the full buffer. This may require several calls to send */
  130. size_t nWritten = 0;
  131. do {
  132. ssize_t n = 0;
  133. do {
  134. size_t bytes_to_send = buf->length - nWritten;
  135. n = send((SOCKET)connection->sockfd,
  136. (const char*)buf->data + nWritten,
  137. WIN32_INT bytes_to_send, flags);
  138. if(n < 0 && errno__ != INTERRUPTED && errno__ != AGAIN) {
  139. connection->close(connection);
  140. UA_ByteString_deleteMembers(buf);
  141. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  142. }
  143. } while(n < 0);
  144. nWritten += (size_t)n;
  145. } while(nWritten < buf->length);
  146. /* Free the buffer */
  147. UA_ByteString_deleteMembers(buf);
  148. return UA_STATUSCODE_GOOD;
  149. }
  150. static UA_StatusCode
  151. connection_recv(UA_Connection *connection, UA_ByteString *response,
  152. UA_UInt32 timeout) {
  153. response->data = (UA_Byte*)
  154. UA_malloc(connection->localConf.recvBufferSize);
  155. if(!response->data) {
  156. response->length = 0;
  157. return UA_STATUSCODE_BADOUTOFMEMORY; /* not enough memory retry */
  158. }
  159. /* Listen on the socket for the given timeout until a message arrives */
  160. if(timeout > 0) {
  161. fd_set fdset;
  162. FD_ZERO(&fdset);
  163. UA_fd_set(connection->sockfd, &fdset);
  164. UA_UInt32 timeout_usec = timeout * 1000;
  165. struct timeval tmptv = {(long int)(timeout_usec / 1000000),
  166. (long int)(timeout_usec % 1000000)};
  167. int resultsize = select(connection->sockfd+1, &fdset, NULL,
  168. NULL, &tmptv);
  169. /* No result */
  170. if(resultsize == 0)
  171. return UA_STATUSCODE_GOOD;
  172. }
  173. /* Get the received packet(s) */
  174. ssize_t ret = recv(connection->sockfd, (char*)response->data,
  175. connection->localConf.recvBufferSize, 0);
  176. /* The remote side closed the connection */
  177. if(ret == 0) {
  178. UA_ByteString_deleteMembers(response);
  179. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  180. }
  181. /* Error case */
  182. if(ret < 0) {
  183. UA_ByteString_deleteMembers(response);
  184. if(errno__ == INTERRUPTED || (timeout > 0) ?
  185. false : (errno__ == EAGAIN || errno__ == WOULDBLOCK))
  186. return UA_STATUSCODE_GOOD; /* statuscode_good but no data -> retry */
  187. connection->close(connection);
  188. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  189. }
  190. /* Set the length of the received buffer */
  191. response->length = (size_t)ret;
  192. return UA_STATUSCODE_GOOD;
  193. }
  194. static UA_StatusCode
  195. socket_set_nonblocking(SOCKET sockfd) {
  196. #ifdef _WIN32
  197. u_long iMode = 1;
  198. if(ioctlsocket(sockfd, FIONBIO, &iMode) != NO_ERROR)
  199. return UA_STATUSCODE_BADINTERNALERROR;
  200. #elif defined(_WRS_KERNEL)
  201. int on = TRUE;
  202. if(ioctl(sockfd, FIONBIO, &on) < 0)
  203. return UA_STATUSCODE_BADINTERNALERROR;
  204. #else
  205. int opts = fcntl(sockfd, F_GETFL);
  206. if(opts < 0 || fcntl(sockfd, F_SETFL, opts|O_NONBLOCK) < 0)
  207. return UA_STATUSCODE_BADINTERNALERROR;
  208. #endif
  209. return UA_STATUSCODE_GOOD;
  210. }
  211. static UA_StatusCode
  212. socket_set_blocking(SOCKET sockfd) {
  213. #ifdef _WIN32
  214. u_long iMode = 0;
  215. if(ioctlsocket(sockfd, FIONBIO, &iMode) != NO_ERROR)
  216. return UA_STATUSCODE_BADINTERNALERROR;
  217. #else
  218. int opts = fcntl(sockfd, F_GETFL);
  219. if(opts < 0 || fcntl(sockfd, F_SETFL, opts & (~O_NONBLOCK)) < 0)
  220. return UA_STATUSCODE_BADINTERNALERROR;
  221. #endif
  222. return UA_STATUSCODE_GOOD;
  223. }
  224. /***************************/
  225. /* Server NetworkLayer TCP */
  226. /***************************/
  227. #define MAXBACKLOG 100
  228. typedef struct ConnectionEntry {
  229. UA_Connection connection;
  230. LIST_ENTRY(ConnectionEntry) pointers;
  231. } ConnectionEntry;
  232. typedef struct {
  233. UA_ConnectionConfig conf;
  234. UA_UInt16 port;
  235. UA_Int32 serverSockets[FD_SETSIZE];
  236. UA_UInt16 serverSocketsSize;
  237. LIST_HEAD(, ConnectionEntry) connections;
  238. } ServerNetworkLayerTCP;
  239. static void
  240. ServerNetworkLayerTCP_freeConnection(UA_Connection *connection) {
  241. UA_Connection_deleteMembers(connection);
  242. UA_free(connection);
  243. }
  244. /* This performs only 'shutdown'. 'close' is called when the shutdown
  245. * socket is returned from select. */
  246. static void
  247. ServerNetworkLayerTCP_close(UA_Connection *connection) {
  248. shutdown((SOCKET)connection->sockfd, 2);
  249. connection->state = UA_CONNECTION_CLOSED;
  250. }
  251. static UA_StatusCode
  252. ServerNetworkLayerTCP_add(ServerNetworkLayerTCP *layer, UA_Int32 newsockfd,
  253. struct sockaddr_storage *remote) {
  254. /* Set nonblocking */
  255. socket_set_nonblocking(newsockfd);
  256. /* Do not merge packets on the socket (disable Nagle's algorithm) */
  257. int dummy = 1;
  258. if(setsockopt(newsockfd, IPPROTO_TCP, TCP_NODELAY,
  259. (const char *)&dummy, sizeof(dummy)) < 0) {
  260. UA_LOG_ERROR(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  261. "Cannot set socket option TCP_NODELAY. Error: %s",
  262. strerror(errno));
  263. return UA_STATUSCODE_BADUNEXPECTEDERROR;
  264. }
  265. /* Get the peer name for logging */
  266. char remote_name[100];
  267. int res = getnameinfo((struct sockaddr*)remote,
  268. sizeof(struct sockaddr_storage),
  269. remote_name, sizeof(remote_name),
  270. NULL, 0, NI_NUMERICHOST);
  271. if(res == 0) {
  272. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  273. "Connection %i | New connection over TCP from %s",
  274. (int)newsockfd, remote_name);
  275. } else {
  276. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  277. "Connection %i | New connection over TCP, "
  278. "getnameinfo failed with errno %i",
  279. (int)newsockfd, errno__);
  280. }
  281. /* Allocate and initialize the connection */
  282. ConnectionEntry *e = (ConnectionEntry*)UA_malloc(sizeof(ConnectionEntry));
  283. if(!e)
  284. return UA_STATUSCODE_BADOUTOFMEMORY;
  285. UA_Connection *c = &e->connection;
  286. memset(c, 0, sizeof(UA_Connection));
  287. c->sockfd = newsockfd;
  288. c->handle = layer;
  289. c->localConf = layer->conf;
  290. c->remoteConf = layer->conf;
  291. c->send = connection_write;
  292. c->close = ServerNetworkLayerTCP_close;
  293. c->free = ServerNetworkLayerTCP_freeConnection;
  294. c->getSendBuffer = connection_getsendbuffer;
  295. c->releaseSendBuffer = connection_releasesendbuffer;
  296. c->releaseRecvBuffer = connection_releaserecvbuffer;
  297. c->state = UA_CONNECTION_OPENING;
  298. /* Add to the linked list */
  299. LIST_INSERT_HEAD(&layer->connections, e, pointers);
  300. return UA_STATUSCODE_GOOD;
  301. }
  302. static void
  303. addServerSocket(ServerNetworkLayerTCP *layer, struct addrinfo *ai) {
  304. /* Create the server socket */
  305. SOCKET newsock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
  306. #ifdef _WIN32
  307. if(newsock == INVALID_SOCKET)
  308. #else
  309. if(newsock < 0)
  310. #endif
  311. {
  312. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  313. "Error opening the server socket");
  314. return;
  315. }
  316. /* Some Linux distributions have net.ipv6.bindv6only not activated. So
  317. * sockets can double-bind to IPv4 and IPv6. This leads to problems. Use
  318. * AF_INET6 sockets only for IPv6. */
  319. int optval = 1;
  320. if(ai->ai_family == AF_INET6 &&
  321. setsockopt(newsock, IPPROTO_IPV6, IPV6_V6ONLY,
  322. (const char*)&optval, sizeof(optval)) == -1) {
  323. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  324. "Could not set an IPv6 socket to IPv6 only");
  325. CLOSESOCKET(newsock);
  326. return;
  327. }
  328. if(setsockopt(newsock, SOL_SOCKET, SO_REUSEADDR,
  329. (const char *)&optval, sizeof(optval)) == -1) {
  330. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  331. "Could not make the socket reusable");
  332. CLOSESOCKET(newsock);
  333. return;
  334. }
  335. if(socket_set_nonblocking(newsock) != UA_STATUSCODE_GOOD) {
  336. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  337. "Could not set the server socket to nonblocking");
  338. CLOSESOCKET(newsock);
  339. return;
  340. }
  341. /* Bind socket to address */
  342. if(bind(newsock, ai->ai_addr, WIN32_INT ai->ai_addrlen) < 0) {
  343. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  344. "Error binding a server socket: %i", errno__);
  345. CLOSESOCKET(newsock);
  346. return;
  347. }
  348. /* Start listening */
  349. if(listen(newsock, MAXBACKLOG) < 0) {
  350. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  351. "Error listening on server socket");
  352. CLOSESOCKET(newsock);
  353. return;
  354. }
  355. layer->serverSockets[layer->serverSocketsSize] = (UA_Int32)newsock;
  356. layer->serverSocketsSize++;
  357. }
  358. static UA_StatusCode
  359. ServerNetworkLayerTCP_start(UA_ServerNetworkLayer *nl, const UA_String *customHostname) {
  360. #ifdef _WIN32
  361. WORD wVersionRequested = MAKEWORD(2, 2);
  362. WSADATA wsaData;
  363. WSAStartup(wVersionRequested, &wsaData);
  364. #endif
  365. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  366. /* Get the discovery url from the hostname */
  367. UA_String du = UA_STRING_NULL;
  368. if (customHostname->length) {
  369. char discoveryUrl[256];
  370. #ifndef _MSC_VER
  371. du.length = (size_t)snprintf(discoveryUrl, 255, "opc.tcp://%.*s:%d/",
  372. (int)customHostname->length,
  373. customHostname->data,
  374. layer->port);
  375. #else
  376. du.length = (size_t)_snprintf_s(discoveryUrl, 255, _TRUNCATE,
  377. "opc.tcp://%.*s:%d/",
  378. (int)customHostname->length,
  379. customHostname->data,
  380. layer->port);
  381. #endif
  382. du.data = (UA_Byte*)discoveryUrl;
  383. }else{
  384. char hostname[256];
  385. if(gethostname(hostname, 255) == 0) {
  386. char discoveryUrl[256];
  387. #ifndef _MSC_VER
  388. du.length = (size_t)snprintf(discoveryUrl, 255, "opc.tcp://%s:%d/",
  389. hostname, layer->port);
  390. #else
  391. du.length = (size_t)_snprintf_s(discoveryUrl, 255, _TRUNCATE,
  392. "opc.tcp://%s:%d/", hostname,
  393. layer->port);
  394. #endif
  395. du.data = (UA_Byte*)discoveryUrl;
  396. }
  397. }
  398. UA_String_copy(&du, &nl->discoveryUrl);
  399. /* Get addrinfo of the server and create server sockets */
  400. char portno[6];
  401. #ifndef _MSC_VER
  402. snprintf(portno, 6, "%d", layer->port);
  403. #else
  404. _snprintf_s(portno, 6, _TRUNCATE, "%d", layer->port);
  405. #endif
  406. struct addrinfo hints, *res;
  407. memset(&hints, 0, sizeof hints);
  408. hints.ai_family = AF_UNSPEC;
  409. hints.ai_socktype = SOCK_STREAM;
  410. hints.ai_flags = AI_PASSIVE;
  411. if(getaddrinfo(NULL, portno, &hints, &res) != 0)
  412. return UA_STATUSCODE_BADINTERNALERROR;
  413. /* There might be serveral addrinfos (for different network cards,
  414. * IPv4/IPv6). Add a server socket for all of them. */
  415. struct addrinfo *ai = res;
  416. for(layer->serverSocketsSize = 0;
  417. layer->serverSocketsSize < FD_SETSIZE && ai != NULL;
  418. ai = ai->ai_next)
  419. addServerSocket(layer, ai);
  420. freeaddrinfo(res);
  421. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  422. "TCP network layer listening on %.*s",
  423. (int)nl->discoveryUrl.length, nl->discoveryUrl.data);
  424. return UA_STATUSCODE_GOOD;
  425. }
  426. /* After every select, reset the sockets to listen on */
  427. static UA_Int32
  428. setFDSet(ServerNetworkLayerTCP *layer, fd_set *fdset) {
  429. FD_ZERO(fdset);
  430. UA_Int32 highestfd = 0;
  431. for(UA_UInt16 i = 0; i < layer->serverSocketsSize; i++) {
  432. UA_fd_set(layer->serverSockets[i], fdset);
  433. if(layer->serverSockets[i] > highestfd)
  434. highestfd = layer->serverSockets[i];
  435. }
  436. ConnectionEntry *e;
  437. LIST_FOREACH(e, &layer->connections, pointers) {
  438. UA_fd_set(e->connection.sockfd, fdset);
  439. if(e->connection.sockfd > highestfd)
  440. highestfd = e->connection.sockfd;
  441. }
  442. return highestfd;
  443. }
  444. static UA_StatusCode
  445. ServerNetworkLayerTCP_listen(UA_ServerNetworkLayer *nl, UA_Server *server,
  446. UA_UInt16 timeout) {
  447. /* Every open socket can generate two jobs */
  448. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  449. /* Listen on open sockets (including the server) */
  450. fd_set fdset, errset;
  451. UA_Int32 highestfd = setFDSet(layer, &fdset);
  452. setFDSet(layer, &errset);
  453. struct timeval tmptv = {0, timeout * 1000};
  454. if (select(highestfd+1, &fdset, NULL, &errset, &tmptv) < 0) {
  455. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  456. "Socket select failed with %s", strerror(errno));
  457. }
  458. /* Accept new connections via the server sockets */
  459. for(UA_UInt16 i = 0; i < layer->serverSocketsSize; i++) {
  460. if(!UA_fd_isset(layer->serverSockets[i], &fdset))
  461. continue;
  462. struct sockaddr_storage remote;
  463. socklen_t remote_size = sizeof(remote);
  464. SOCKET newsockfd = accept((SOCKET)layer->serverSockets[i],
  465. (struct sockaddr*)&remote, &remote_size);
  466. #ifdef _WIN32
  467. if(newsockfd == INVALID_SOCKET)
  468. #else
  469. if(newsockfd < 0)
  470. #endif
  471. continue;
  472. UA_LOG_TRACE(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  473. "Connection %i | New TCP connection on server socket %i",
  474. (int)newsockfd, layer->serverSockets[i]);
  475. ServerNetworkLayerTCP_add(layer, (UA_Int32)newsockfd, &remote);
  476. }
  477. /* Read from established sockets */
  478. ConnectionEntry *e, *e_tmp;
  479. LIST_FOREACH_SAFE(e, &layer->connections, pointers, e_tmp) {
  480. if(!UA_fd_isset(e->connection.sockfd, &errset) &&
  481. !UA_fd_isset(e->connection.sockfd, &fdset))
  482. continue;
  483. UA_LOG_TRACE(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  484. "Connection %i | Activity on the socket",
  485. e->connection.sockfd);
  486. UA_ByteString buf = UA_BYTESTRING_NULL;
  487. UA_StatusCode retval = connection_recv(&e->connection, &buf, 0);
  488. if(retval == UA_STATUSCODE_GOOD) {
  489. /* Process packets */
  490. UA_Server_processBinaryMessage(server, &e->connection, &buf);
  491. connection_releaserecvbuffer(&e->connection, &buf);
  492. } else if(retval == UA_STATUSCODE_BADCONNECTIONCLOSED) {
  493. /* The socket is shutdown but not closed */
  494. if(e->connection.state != UA_CONNECTION_CLOSED) {
  495. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  496. "Connection %i | Closed by the client",
  497. e->connection.sockfd);
  498. } else {
  499. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  500. "Connection %i | Closed by the server",
  501. e->connection.sockfd);
  502. }
  503. LIST_REMOVE(e, pointers);
  504. CLOSESOCKET(e->connection.sockfd);
  505. UA_Server_removeConnection(server, &e->connection);
  506. }
  507. }
  508. return UA_STATUSCODE_GOOD;
  509. }
  510. static void
  511. ServerNetworkLayerTCP_stop(UA_ServerNetworkLayer *nl, UA_Server *server) {
  512. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  513. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  514. "Shutting down the TCP network layer");
  515. /* Close the server sockets */
  516. for(UA_UInt16 i = 0; i < layer->serverSocketsSize; i++) {
  517. shutdown((SOCKET)layer->serverSockets[i], 2);
  518. CLOSESOCKET(layer->serverSockets[i]);
  519. }
  520. layer->serverSocketsSize = 0;
  521. /* Close open connections */
  522. ConnectionEntry *e;
  523. LIST_FOREACH(e, &layer->connections, pointers)
  524. ServerNetworkLayerTCP_close(&e->connection);
  525. /* Run recv on client sockets. This picks up the closed sockets and frees
  526. * the connection. */
  527. ServerNetworkLayerTCP_listen(nl, server, 0);
  528. #ifdef _WIN32
  529. WSACleanup();
  530. #endif
  531. }
  532. /* run only when the server is stopped */
  533. static void
  534. ServerNetworkLayerTCP_deleteMembers(UA_ServerNetworkLayer *nl) {
  535. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP *)nl->handle;
  536. UA_String_deleteMembers(&nl->discoveryUrl);
  537. /* Hard-close and remove remaining connections. The server is no longer
  538. * running. So this is safe. */
  539. ConnectionEntry *e, *e_tmp;
  540. LIST_FOREACH_SAFE(e, &layer->connections, pointers, e_tmp) {
  541. LIST_REMOVE(e, pointers);
  542. ServerNetworkLayerTCP_close(&e->connection);
  543. CLOSESOCKET(e->connection.sockfd);
  544. UA_free(e);
  545. }
  546. /* Free the layer */
  547. UA_free(layer);
  548. }
  549. UA_ServerNetworkLayer
  550. UA_ServerNetworkLayerTCP(UA_ConnectionConfig conf, UA_UInt16 port) {
  551. UA_ServerNetworkLayer nl;
  552. memset(&nl, 0, sizeof(UA_ServerNetworkLayer));
  553. ServerNetworkLayerTCP *layer = (ServerNetworkLayerTCP*)
  554. UA_calloc(1,sizeof(ServerNetworkLayerTCP));
  555. if(!layer)
  556. return nl;
  557. layer->conf = conf;
  558. layer->port = port;
  559. nl.handle = layer;
  560. nl.start = ServerNetworkLayerTCP_start;
  561. nl.listen = ServerNetworkLayerTCP_listen;
  562. nl.stop = ServerNetworkLayerTCP_stop;
  563. nl.deleteMembers = ServerNetworkLayerTCP_deleteMembers;
  564. return nl;
  565. }
  566. /***************************/
  567. /* Client NetworkLayer TCP */
  568. /***************************/
  569. static void
  570. ClientNetworkLayerTCP_close(UA_Connection *connection) {
  571. shutdown((SOCKET)connection->sockfd, 2);
  572. CLOSESOCKET(connection->sockfd);
  573. connection->state = UA_CONNECTION_CLOSED;
  574. }
  575. UA_Connection
  576. UA_ClientConnectionTCP(UA_ConnectionConfig conf,
  577. const char *endpointUrl, const UA_UInt32 timeout) {
  578. #ifdef _WIN32
  579. WORD wVersionRequested;
  580. WSADATA wsaData;
  581. wVersionRequested = MAKEWORD(2, 2);
  582. WSAStartup(wVersionRequested, &wsaData);
  583. #endif
  584. UA_Connection connection;
  585. memset(&connection, 0, sizeof(UA_Connection));
  586. connection.state = UA_CONNECTION_OPENING;
  587. connection.localConf = conf;
  588. connection.remoteConf = conf;
  589. connection.send = connection_write;
  590. connection.recv = connection_recv;
  591. connection.close = ClientNetworkLayerTCP_close;
  592. connection.free = NULL;
  593. connection.getSendBuffer = connection_getsendbuffer;
  594. connection.releaseSendBuffer = connection_releasesendbuffer;
  595. connection.releaseRecvBuffer = connection_releaserecvbuffer;
  596. UA_String endpointUrlString = UA_STRING((char*)(uintptr_t)endpointUrl);
  597. UA_String hostnameString = UA_STRING_NULL;
  598. UA_String pathString = UA_STRING_NULL;
  599. UA_UInt16 port = 0;
  600. char hostname[512];
  601. UA_StatusCode parse_retval =
  602. UA_parseEndpointUrl(&endpointUrlString, &hostnameString,
  603. &port, &pathString);
  604. if(parse_retval != UA_STATUSCODE_GOOD || hostnameString.length > 511) {
  605. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  606. "Server url is invalid: %s", endpointUrl);
  607. return connection;
  608. }
  609. memcpy(hostname, hostnameString.data, hostnameString.length);
  610. hostname[hostnameString.length] = 0;
  611. if(port == 0) {
  612. port = 4840;
  613. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  614. "No port defined, using default port %d", port);
  615. }
  616. struct addrinfo hints, *server;
  617. memset(&hints, 0, sizeof(hints));
  618. hints.ai_family = AF_UNSPEC;
  619. hints.ai_socktype = SOCK_STREAM;
  620. char portStr[6];
  621. #ifndef _MSC_VER
  622. snprintf(portStr, 6, "%d", port);
  623. #else
  624. _snprintf_s(portStr, 6, _TRUNCATE, "%d", port);
  625. #endif
  626. int error = getaddrinfo(hostname, portStr, &hints, &server);
  627. if(error != 0 || !server) {
  628. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  629. "DNS lookup of %s failed with error %s",
  630. hostname, gai_strerror(error));
  631. return connection;
  632. }
  633. UA_Boolean connected = UA_FALSE;
  634. UA_DateTime connStart = UA_DateTime_nowMonotonic();
  635. SOCKET clientsockfd;
  636. /* On linux connect may immediately return with ECONNREFUSED but we still
  637. * want to try to connect. So use a loop and retry until timeout is
  638. * reached. */
  639. do {
  640. /* Get a socket */
  641. clientsockfd = socket(server->ai_family,
  642. server->ai_socktype,
  643. server->ai_protocol);
  644. #ifdef _WIN32
  645. if(clientsockfd == INVALID_SOCKET) {
  646. #else
  647. if(clientsockfd < 0) {
  648. #endif
  649. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  650. "Could not create client socket: %s", strerror(errno__));
  651. freeaddrinfo(server);
  652. return connection;
  653. }
  654. /* Connect to the server */
  655. connection.sockfd = (UA_Int32) clientsockfd; /* cast for win32 */
  656. /* Non blocking connect to be able to timeout */
  657. if (socket_set_nonblocking(clientsockfd) != UA_STATUSCODE_GOOD) {
  658. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  659. "Could not set the client socket to nonblocking");
  660. ClientNetworkLayerTCP_close(&connection);
  661. freeaddrinfo(server);
  662. return connection;
  663. }
  664. /* Non blocking connect */
  665. error = connect(clientsockfd, server->ai_addr,
  666. WIN32_INT server->ai_addrlen);
  667. if ((error == -1) && (errno__ != ERR_CONNECTION_PROGRESS)) {
  668. ClientNetworkLayerTCP_close(&connection);
  669. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  670. "Connection to %s failed with error: %s",
  671. endpointUrl, strerror(errno__));
  672. freeaddrinfo(server);
  673. return connection;
  674. }
  675. /* Use select to wait and check if connected */
  676. if (error == -1 && (errno__ == ERR_CONNECTION_PROGRESS)) {
  677. /* connection in progress. Wait until connected using select */
  678. UA_UInt32 timeSinceStart = (UA_UInt32)
  679. ((UA_Double)(UA_DateTime_nowMonotonic() - connStart) * UA_DATETIME_TO_MSEC);
  680. if(timeSinceStart > timeout)
  681. break;
  682. fd_set fdset;
  683. FD_ZERO(&fdset);
  684. UA_fd_set(clientsockfd, &fdset);
  685. UA_UInt32 timeout_usec = (timeout - timeSinceStart) * 1000;
  686. struct timeval tmptv = {(long int) (timeout_usec / 1000000),
  687. (long int) (timeout_usec % 1000000)};
  688. int resultsize = select((UA_Int32)(clientsockfd + 1), NULL, &fdset,
  689. NULL, &tmptv);
  690. if (resultsize == 1) {
  691. /* Windows does not have any getsockopt equivalent and it is not
  692. * needed there */
  693. #ifdef _WIN32
  694. connected = true;
  695. break;
  696. #else
  697. OPTVAL_TYPE so_error;
  698. socklen_t len = sizeof so_error;
  699. int ret = getsockopt(clientsockfd, SOL_SOCKET, SO_ERROR, &so_error, &len);
  700. if (ret != 0 || so_error != 0) {
  701. /* on connection refused we should still try to connect */
  702. /* connection refused happens on localhost or local ip without timeout */
  703. if (so_error != ECONNREFUSED) {
  704. ClientNetworkLayerTCP_close(&connection);
  705. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  706. "Connection to %s failed with error: %s",
  707. endpointUrl, strerror(ret == 0 ? so_error : errno__));
  708. freeaddrinfo(server);
  709. return connection;
  710. }
  711. /* wait until we try a again. Do not make this too small, otherwise the
  712. * timeout is somehow wrong */
  713. UA_sleep_ms(100);
  714. } else {
  715. connected = true;
  716. break;
  717. }
  718. #endif
  719. }
  720. } else {
  721. connected = true;
  722. break;
  723. }
  724. ClientNetworkLayerTCP_close(&connection);
  725. } while ((UA_Double)(UA_DateTime_nowMonotonic() - connStart)*UA_DATETIME_TO_MSEC < timeout);
  726. freeaddrinfo(server);
  727. if (!connected) {
  728. /* connection timeout */
  729. ClientNetworkLayerTCP_close(&connection);
  730. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  731. "Trying to connect to %s timed out",
  732. endpointUrl);
  733. return connection;
  734. }
  735. /* We are connected. Reset socket to blocking */
  736. if(socket_set_blocking(clientsockfd) != UA_STATUSCODE_GOOD) {
  737. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  738. "Could not set the client socket to blocking");
  739. ClientNetworkLayerTCP_close(&connection);
  740. return connection;
  741. }
  742. #ifdef SO_NOSIGPIPE
  743. int val = 1;
  744. int sso_result = setsockopt(connection.sockfd, SOL_SOCKET,
  745. SO_NOSIGPIPE, (void*)&val, sizeof(val));
  746. if(sso_result < 0)
  747. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_NETWORK,
  748. "Couldn't set SO_NOSIGPIPE");
  749. #endif
  750. return connection;
  751. }