ua_network_tcp.c 31 KB

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