ua_network_tcp.c 31 KB

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