ua_network_tcp.c 37 KB

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