network_tcp.c 38 KB

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