ua_network_tcp.c 32 KB

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