ua_network_tcp.c 37 KB

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