ua_network_tcp.c 38 KB

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