ua_network_tcp.c 37 KB

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