socket.c 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include "../libnetdata.h"
  3. // --------------------------------------------------------------------------------------------------------------------
  4. // various library calls
  5. #ifdef __gnu_linux__
  6. #define LARGE_SOCK_SIZE 33554431 // don't ask why - I found it at brubeck source - I guess it is just a large number
  7. #else
  8. #define LARGE_SOCK_SIZE 4096
  9. #endif
  10. int sock_setnonblock(int fd) {
  11. int flags;
  12. flags = fcntl(fd, F_GETFL);
  13. flags |= O_NONBLOCK;
  14. int ret = fcntl(fd, F_SETFL, flags);
  15. if(ret < 0)
  16. error("Failed to set O_NONBLOCK on socket %d", fd);
  17. return ret;
  18. }
  19. int sock_delnonblock(int fd) {
  20. int flags;
  21. flags = fcntl(fd, F_GETFL);
  22. flags &= ~O_NONBLOCK;
  23. int ret = fcntl(fd, F_SETFL, flags);
  24. if(ret < 0)
  25. error("Failed to remove O_NONBLOCK on socket %d", fd);
  26. return ret;
  27. }
  28. int sock_setreuse(int fd, int reuse) {
  29. int ret = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
  30. if(ret == -1)
  31. error("Failed to set SO_REUSEADDR on socket %d", fd);
  32. return ret;
  33. }
  34. int sock_setreuse_port(int fd, int reuse) {
  35. int ret;
  36. #ifdef SO_REUSEPORT
  37. ret = setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &reuse, sizeof(reuse));
  38. if(ret == -1 && errno != ENOPROTOOPT)
  39. error("failed to set SO_REUSEPORT on socket %d", fd);
  40. #else
  41. ret = -1;
  42. #endif
  43. return ret;
  44. }
  45. int sock_enlarge_in(int fd) {
  46. int ret, bs = LARGE_SOCK_SIZE;
  47. ret = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &bs, sizeof(bs));
  48. if(ret == -1)
  49. error("Failed to set SO_RCVBUF on socket %d", fd);
  50. return ret;
  51. }
  52. int sock_enlarge_out(int fd) {
  53. int ret, bs = LARGE_SOCK_SIZE;
  54. ret = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &bs, sizeof(bs));
  55. if(ret == -1)
  56. error("Failed to set SO_SNDBUF on socket %d", fd);
  57. return ret;
  58. }
  59. // --------------------------------------------------------------------------------------------------------------------
  60. char *strdup_client_description(int family, const char *protocol, const char *ip, uint16_t port) {
  61. char buffer[100 + 1];
  62. switch(family) {
  63. case AF_INET:
  64. snprintfz(buffer, 100, "%s:%s:%d", protocol, ip, port);
  65. break;
  66. case AF_INET6:
  67. default:
  68. snprintfz(buffer, 100, "%s:[%s]:%d", protocol, ip, port);
  69. break;
  70. case AF_UNIX:
  71. snprintfz(buffer, 100, "%s:%s", protocol, ip);
  72. break;
  73. }
  74. return strdupz(buffer);
  75. }
  76. // --------------------------------------------------------------------------------------------------------------------
  77. // listening sockets
  78. int create_listen_socket_unix(const char *path, int listen_backlog) {
  79. int sock;
  80. debug(D_LISTENER, "LISTENER: UNIX creating new listening socket on path '%s'", path);
  81. sock = socket(AF_UNIX, SOCK_STREAM, 0);
  82. if(sock < 0) {
  83. error("LISTENER: UNIX socket() on path '%s' failed.", path);
  84. return -1;
  85. }
  86. sock_setnonblock(sock);
  87. sock_enlarge_in(sock);
  88. struct sockaddr_un name;
  89. memset(&name, 0, sizeof(struct sockaddr_un));
  90. name.sun_family = AF_UNIX;
  91. strncpy(name.sun_path, path, sizeof(name.sun_path)-1);
  92. errno = 0;
  93. if (unlink(path) == -1 && errno != ENOENT)
  94. error("LISTENER: failed to remove existing (probably obsolete or left-over) file on UNIX socket path '%s'.", path);
  95. if(bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) {
  96. close(sock);
  97. error("LISTENER: UNIX bind() on path '%s' failed.", path);
  98. return -1;
  99. }
  100. // we have to chmod this to 0777 so that the client will be able
  101. // to read from and write to this socket.
  102. if(chmod(path, 0777) == -1)
  103. error("LISTENER: failed to chmod() socket file '%s'.", path);
  104. if(listen(sock, listen_backlog) < 0) {
  105. close(sock);
  106. error("LISTENER: UNIX listen() on path '%s' failed.", path);
  107. return -1;
  108. }
  109. debug(D_LISTENER, "LISTENER: Listening on UNIX path '%s'", path);
  110. return sock;
  111. }
  112. int create_listen_socket4(int socktype, const char *ip, uint16_t port, int listen_backlog) {
  113. int sock;
  114. debug(D_LISTENER, "LISTENER: IPv4 creating new listening socket on ip '%s' port %d, socktype %d", ip, port, socktype);
  115. sock = socket(AF_INET, socktype, 0);
  116. if(sock < 0) {
  117. error("LISTENER: IPv4 socket() on ip '%s' port %d, socktype %d failed.", ip, port, socktype);
  118. return -1;
  119. }
  120. sock_setreuse(sock, 1);
  121. sock_setreuse_port(sock, 1);
  122. sock_setnonblock(sock);
  123. sock_enlarge_in(sock);
  124. struct sockaddr_in name;
  125. memset(&name, 0, sizeof(struct sockaddr_in));
  126. name.sin_family = AF_INET;
  127. name.sin_port = htons (port);
  128. int ret = inet_pton(AF_INET, ip, (void *)&name.sin_addr.s_addr);
  129. if(ret != 1) {
  130. error("LISTENER: Failed to convert IP '%s' to a valid IPv4 address.", ip);
  131. close(sock);
  132. return -1;
  133. }
  134. if(bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) {
  135. close(sock);
  136. error("LISTENER: IPv4 bind() on ip '%s' port %d, socktype %d failed.", ip, port, socktype);
  137. return -1;
  138. }
  139. if(socktype == SOCK_STREAM && listen(sock, listen_backlog) < 0) {
  140. close(sock);
  141. error("LISTENER: IPv4 listen() on ip '%s' port %d, socktype %d failed.", ip, port, socktype);
  142. return -1;
  143. }
  144. debug(D_LISTENER, "LISTENER: Listening on IPv4 ip '%s' port %d, socktype %d", ip, port, socktype);
  145. return sock;
  146. }
  147. int create_listen_socket6(int socktype, uint32_t scope_id, const char *ip, int port, int listen_backlog) {
  148. int sock;
  149. int ipv6only = 1;
  150. debug(D_LISTENER, "LISTENER: IPv6 creating new listening socket on ip '%s' port %d, socktype %d", ip, port, socktype);
  151. sock = socket(AF_INET6, socktype, 0);
  152. if (sock < 0) {
  153. error("LISTENER: IPv6 socket() on ip '%s' port %d, socktype %d, failed.", ip, port, socktype);
  154. return -1;
  155. }
  156. sock_setreuse(sock, 1);
  157. sock_setreuse_port(sock, 1);
  158. sock_setnonblock(sock);
  159. sock_enlarge_in(sock);
  160. /* IPv6 only */
  161. if(setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&ipv6only, sizeof(ipv6only)) != 0)
  162. error("LISTENER: Cannot set IPV6_V6ONLY on ip '%s' port %d, socktype %d.", ip, port, socktype);
  163. struct sockaddr_in6 name;
  164. memset(&name, 0, sizeof(struct sockaddr_in6));
  165. name.sin6_family = AF_INET6;
  166. name.sin6_port = htons ((uint16_t) port);
  167. name.sin6_scope_id = scope_id;
  168. int ret = inet_pton(AF_INET6, ip, (void *)&name.sin6_addr.s6_addr);
  169. if(ret != 1) {
  170. error("LISTENER: Failed to convert IP '%s' to a valid IPv6 address.", ip);
  171. close(sock);
  172. return -1;
  173. }
  174. name.sin6_scope_id = scope_id;
  175. if (bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) {
  176. close(sock);
  177. error("LISTENER: IPv6 bind() on ip '%s' port %d, socktype %d failed.", ip, port, socktype);
  178. return -1;
  179. }
  180. if (socktype == SOCK_STREAM && listen(sock, listen_backlog) < 0) {
  181. close(sock);
  182. error("LISTENER: IPv6 listen() on ip '%s' port %d, socktype %d failed.", ip, port, socktype);
  183. return -1;
  184. }
  185. debug(D_LISTENER, "LISTENER: Listening on IPv6 ip '%s' port %d, socktype %d", ip, port, socktype);
  186. return sock;
  187. }
  188. static inline int listen_sockets_add(LISTEN_SOCKETS *sockets, int fd, int family, int socktype, const char *protocol, const char *ip, uint16_t port, int acl_flags) {
  189. if(sockets->opened >= MAX_LISTEN_FDS) {
  190. error("LISTENER: Too many listening sockets. Failed to add listening %s socket at ip '%s' port %d, protocol %s, socktype %d", protocol, ip, port, protocol, socktype);
  191. close(fd);
  192. return -1;
  193. }
  194. sockets->fds[sockets->opened] = fd;
  195. sockets->fds_types[sockets->opened] = socktype;
  196. sockets->fds_families[sockets->opened] = family;
  197. sockets->fds_names[sockets->opened] = strdup_client_description(family, protocol, ip, port);
  198. sockets->fds_acl_flags[sockets->opened] = acl_flags;
  199. sockets->opened++;
  200. return 0;
  201. }
  202. int listen_sockets_check_is_member(LISTEN_SOCKETS *sockets, int fd) {
  203. size_t i;
  204. for(i = 0; i < sockets->opened ;i++)
  205. if(sockets->fds[i] == fd) return 1;
  206. return 0;
  207. }
  208. static inline void listen_sockets_init(LISTEN_SOCKETS *sockets) {
  209. size_t i;
  210. for(i = 0; i < MAX_LISTEN_FDS ;i++) {
  211. sockets->fds[i] = -1;
  212. sockets->fds_names[i] = NULL;
  213. sockets->fds_types[i] = -1;
  214. }
  215. sockets->opened = 0;
  216. sockets->failed = 0;
  217. }
  218. void listen_sockets_close(LISTEN_SOCKETS *sockets) {
  219. size_t i;
  220. for(i = 0; i < sockets->opened ;i++) {
  221. close(sockets->fds[i]);
  222. sockets->fds[i] = -1;
  223. freez(sockets->fds_names[i]);
  224. sockets->fds_names[i] = NULL;
  225. sockets->fds_types[i] = -1;
  226. }
  227. sockets->opened = 0;
  228. sockets->failed = 0;
  229. }
  230. /*
  231. * SSL ACL
  232. *
  233. * Search the SSL acl and apply it case it is set.
  234. *
  235. * @param acl is the acl given by the user.
  236. */
  237. WEB_CLIENT_ACL socket_ssl_acl(char *acl) {
  238. char *ssl = strchr(acl,'^');
  239. if(ssl) {
  240. //Due the format of the SSL command it is always the last command,
  241. //we finish it here to avoid problems with the ACLs
  242. *ssl = '\0';
  243. #ifdef ENABLE_HTTPS
  244. ssl++;
  245. if (!strncmp("SSL=",ssl,4)) {
  246. ssl += 4;
  247. if (!strcmp(ssl,"optional")) {
  248. return WEB_CLIENT_ACL_SSL_OPTIONAL;
  249. }
  250. else if (!strcmp(ssl,"force")) {
  251. return WEB_CLIENT_ACL_SSL_FORCE;
  252. }
  253. }
  254. #endif
  255. }
  256. return WEB_CLIENT_ACL_NONE;
  257. }
  258. WEB_CLIENT_ACL read_acl(char *st) {
  259. WEB_CLIENT_ACL ret = socket_ssl_acl(st);
  260. if (!strcmp(st,"dashboard")) ret |= WEB_CLIENT_ACL_DASHBOARD;
  261. if (!strcmp(st,"registry")) ret |= WEB_CLIENT_ACL_REGISTRY;
  262. if (!strcmp(st,"badges")) ret |= WEB_CLIENT_ACL_BADGE;
  263. if (!strcmp(st,"management")) ret |= WEB_CLIENT_ACL_MGMT;
  264. if (!strcmp(st,"streaming")) ret |= WEB_CLIENT_ACL_STREAMING;
  265. if (!strcmp(st,"netdata.conf")) ret |= WEB_CLIENT_ACL_NETDATACONF;
  266. return ret;
  267. }
  268. static inline int bind_to_this(LISTEN_SOCKETS *sockets, const char *definition, uint16_t default_port, int listen_backlog) {
  269. int added = 0;
  270. WEB_CLIENT_ACL acl_flags = WEB_CLIENT_ACL_NONE;
  271. struct addrinfo hints;
  272. struct addrinfo *result = NULL, *rp = NULL;
  273. char buffer[strlen(definition) + 1];
  274. strcpy(buffer, definition);
  275. char buffer2[10 + 1];
  276. snprintfz(buffer2, 10, "%d", default_port);
  277. char *ip = buffer, *port = buffer2, *interface = "", *portconfig;;
  278. int protocol = IPPROTO_TCP, socktype = SOCK_STREAM;
  279. const char *protocol_str = "tcp";
  280. if(strncmp(ip, "tcp:", 4) == 0) {
  281. ip += 4;
  282. protocol = IPPROTO_TCP;
  283. socktype = SOCK_STREAM;
  284. protocol_str = "tcp";
  285. }
  286. else if(strncmp(ip, "udp:", 4) == 0) {
  287. ip += 4;
  288. protocol = IPPROTO_UDP;
  289. socktype = SOCK_DGRAM;
  290. protocol_str = "udp";
  291. }
  292. else if(strncmp(ip, "unix:", 5) == 0) {
  293. char *path = ip + 5;
  294. socktype = SOCK_STREAM;
  295. protocol_str = "unix";
  296. int fd = create_listen_socket_unix(path, listen_backlog);
  297. if (fd == -1) {
  298. error("LISTENER: Cannot create unix socket '%s'", path);
  299. sockets->failed++;
  300. } else {
  301. acl_flags = WEB_CLIENT_ACL_DASHBOARD | WEB_CLIENT_ACL_REGISTRY | WEB_CLIENT_ACL_BADGE | WEB_CLIENT_ACL_MGMT | WEB_CLIENT_ACL_NETDATACONF | WEB_CLIENT_ACL_STREAMING | WEB_CLIENT_ACL_SSL_DEFAULT;
  302. listen_sockets_add(sockets, fd, AF_UNIX, socktype, protocol_str, path, 0, acl_flags);
  303. added++;
  304. }
  305. return added;
  306. }
  307. char *e = ip;
  308. if(*e == '[') {
  309. e = ++ip;
  310. while(*e && *e != ']') e++;
  311. if(*e == ']') {
  312. *e = '\0';
  313. e++;
  314. }
  315. }
  316. else {
  317. while(*e && *e != ':' && *e != '%' && *e != '=') e++;
  318. }
  319. if(*e == '%') {
  320. *e = '\0';
  321. e++;
  322. interface = e;
  323. while(*e && *e != ':' && *e != '=') e++;
  324. }
  325. if(*e == ':') {
  326. port = e + 1;
  327. *e = '\0';
  328. e++;
  329. while(*e && *e != '=') e++;
  330. }
  331. if(*e == '=') {
  332. *e='\0';
  333. e++;
  334. portconfig = e;
  335. while (*e != '\0') {
  336. if (*e == '|') {
  337. *e = '\0';
  338. acl_flags |= read_acl(portconfig);
  339. e++;
  340. portconfig = e;
  341. continue;
  342. }
  343. e++;
  344. }
  345. acl_flags |= read_acl(portconfig);
  346. } else {
  347. acl_flags = WEB_CLIENT_ACL_DASHBOARD | WEB_CLIENT_ACL_REGISTRY | WEB_CLIENT_ACL_BADGE | WEB_CLIENT_ACL_MGMT | WEB_CLIENT_ACL_NETDATACONF | WEB_CLIENT_ACL_STREAMING | WEB_CLIENT_ACL_SSL_DEFAULT;
  348. }
  349. //Case the user does not set the option SSL in the "bind to", but he has
  350. //the certificates, I must redirect, so I am assuming here the default option
  351. if(!(acl_flags & WEB_CLIENT_ACL_SSL_OPTIONAL) && !(acl_flags & WEB_CLIENT_ACL_SSL_FORCE)) {
  352. acl_flags |= WEB_CLIENT_ACL_SSL_DEFAULT;
  353. }
  354. uint32_t scope_id = 0;
  355. if(*interface) {
  356. scope_id = if_nametoindex(interface);
  357. if(!scope_id)
  358. error("LISTENER: Cannot find a network interface named '%s'. Continuing with limiting the network interface", interface);
  359. }
  360. if(!*ip || *ip == '*' || !strcmp(ip, "any") || !strcmp(ip, "all"))
  361. ip = NULL;
  362. if(!*port)
  363. port = buffer2;
  364. memset(&hints, 0, sizeof(hints));
  365. hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
  366. hints.ai_socktype = socktype;
  367. hints.ai_flags = AI_PASSIVE; /* For wildcard IP address */
  368. hints.ai_protocol = protocol;
  369. hints.ai_canonname = NULL;
  370. hints.ai_addr = NULL;
  371. hints.ai_next = NULL;
  372. int r = getaddrinfo(ip, port, &hints, &result);
  373. if (r != 0) {
  374. error("LISTENER: getaddrinfo('%s', '%s'): %s\n", ip, port, gai_strerror(r));
  375. return -1;
  376. }
  377. for (rp = result; rp != NULL; rp = rp->ai_next) {
  378. int fd = -1;
  379. int family;
  380. char rip[INET_ADDRSTRLEN + INET6_ADDRSTRLEN] = "INVALID";
  381. uint16_t rport = default_port;
  382. family = rp->ai_addr->sa_family;
  383. switch (family) {
  384. case AF_INET: {
  385. struct sockaddr_in *sin = (struct sockaddr_in *) rp->ai_addr;
  386. inet_ntop(AF_INET, &sin->sin_addr, rip, INET_ADDRSTRLEN);
  387. rport = ntohs(sin->sin_port);
  388. // info("Attempting to listen on IPv4 '%s' ('%s'), port %d ('%s'), socktype %d", rip, ip, rport, port, socktype);
  389. fd = create_listen_socket4(socktype, rip, rport, listen_backlog);
  390. break;
  391. }
  392. case AF_INET6: {
  393. struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) rp->ai_addr;
  394. inet_ntop(AF_INET6, &sin6->sin6_addr, rip, INET6_ADDRSTRLEN);
  395. rport = ntohs(sin6->sin6_port);
  396. // info("Attempting to listen on IPv6 '%s' ('%s'), port %d ('%s'), socktype %d", rip, ip, rport, port, socktype);
  397. fd = create_listen_socket6(socktype, scope_id, rip, rport, listen_backlog);
  398. break;
  399. }
  400. default:
  401. debug(D_LISTENER, "LISTENER: Unknown socket family %d", family);
  402. break;
  403. }
  404. if (fd == -1) {
  405. error("LISTENER: Cannot bind to ip '%s', port %d", rip, rport);
  406. sockets->failed++;
  407. }
  408. else {
  409. listen_sockets_add(sockets, fd, family, socktype, protocol_str, rip, rport, acl_flags);
  410. added++;
  411. }
  412. }
  413. freeaddrinfo(result);
  414. return added;
  415. }
  416. int listen_sockets_setup(LISTEN_SOCKETS *sockets) {
  417. listen_sockets_init(sockets);
  418. sockets->backlog = (int) appconfig_get_number(sockets->config, sockets->config_section, "listen backlog", sockets->backlog);
  419. long long int old_port = sockets->default_port;
  420. long long int new_port = appconfig_get_number(sockets->config, sockets->config_section, "default port", sockets->default_port);
  421. if(new_port < 1 || new_port > 65535) {
  422. error("LISTENER: Invalid listen port %lld given. Defaulting to %lld.", new_port, old_port);
  423. sockets->default_port = (uint16_t) appconfig_set_number(sockets->config, sockets->config_section, "default port", old_port);
  424. }
  425. else sockets->default_port = (uint16_t)new_port;
  426. debug(D_OPTIONS, "LISTENER: Default listen port set to %d.", sockets->default_port);
  427. char *s = appconfig_get(sockets->config, sockets->config_section, "bind to", sockets->default_bind_to);
  428. while(*s) {
  429. char *e = s;
  430. // skip separators, moving both s(tart) and e(nd)
  431. while(isspace(*e) || *e == ',') s = ++e;
  432. // move e(nd) to the first separator
  433. while(*e && !isspace(*e) && *e != ',') e++;
  434. // is there anything?
  435. if(!*s || s == e) break;
  436. char buf[e - s + 1];
  437. strncpyz(buf, s, e - s);
  438. bind_to_this(sockets, buf, sockets->default_port, sockets->backlog);
  439. s = e;
  440. }
  441. if(sockets->failed) {
  442. size_t i;
  443. for(i = 0; i < sockets->opened ;i++)
  444. info("LISTENER: Listen socket %s opened successfully.", sockets->fds_names[i]);
  445. }
  446. return (int)sockets->opened;
  447. }
  448. // --------------------------------------------------------------------------------------------------------------------
  449. // connect to another host/port
  450. // connect_to_this_unix()
  451. // path the path of the unix socket
  452. // timeout the timeout for establishing a connection
  453. static inline int connect_to_unix(const char *path, struct timeval *timeout) {
  454. int fd = socket(AF_UNIX, SOCK_STREAM, 0);
  455. if(fd == -1) {
  456. error("Failed to create UNIX socket() for '%s'", path);
  457. return -1;
  458. }
  459. if(timeout) {
  460. if(setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (char *) timeout, sizeof(struct timeval)) < 0)
  461. error("Failed to set timeout on UNIX socket '%s'", path);
  462. }
  463. struct sockaddr_un addr;
  464. memset(&addr, 0, sizeof(addr));
  465. addr.sun_family = AF_UNIX;
  466. strncpy(addr.sun_path, path, sizeof(addr.sun_path)-1);
  467. if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
  468. error("Cannot connect to UNIX socket on path '%s'.", path);
  469. close(fd);
  470. return -1;
  471. }
  472. debug(D_CONNECT_TO, "Connected to UNIX socket on path '%s'.", path);
  473. return fd;
  474. }
  475. // connect_to_this_ip46()
  476. // protocol IPPROTO_TCP, IPPROTO_UDP
  477. // socktype SOCK_STREAM, SOCK_DGRAM
  478. // host the destination hostname or IP address (IPv4 or IPv6) to connect to
  479. // if it resolves to many IPs, all are tried (IPv4 and IPv6)
  480. // scope_id the if_index id of the interface to use for connecting (0 = any)
  481. // (used only under IPv6)
  482. // service the service name or port to connect to
  483. // timeout the timeout for establishing a connection
  484. int connect_to_this_ip46(int protocol, int socktype, const char *host, uint32_t scope_id, const char *service, struct timeval *timeout) {
  485. struct addrinfo hints;
  486. struct addrinfo *ai_head = NULL, *ai = NULL;
  487. memset(&hints, 0, sizeof(hints));
  488. hints.ai_family = PF_UNSPEC; /* Allow IPv4 or IPv6 */
  489. hints.ai_socktype = socktype;
  490. hints.ai_protocol = protocol;
  491. int ai_err = getaddrinfo(host, service, &hints, &ai_head);
  492. if (ai_err != 0) {
  493. error("Cannot resolve host '%s', port '%s': %s", host, service, gai_strerror(ai_err));
  494. return -1;
  495. }
  496. int fd = -1;
  497. for (ai = ai_head; ai != NULL && fd == -1; ai = ai->ai_next) {
  498. if (ai->ai_family == PF_INET6) {
  499. struct sockaddr_in6 *pSadrIn6 = (struct sockaddr_in6 *) ai->ai_addr;
  500. if(pSadrIn6->sin6_scope_id == 0) {
  501. pSadrIn6->sin6_scope_id = scope_id;
  502. }
  503. }
  504. char hostBfr[NI_MAXHOST + 1];
  505. char servBfr[NI_MAXSERV + 1];
  506. getnameinfo(ai->ai_addr,
  507. ai->ai_addrlen,
  508. hostBfr,
  509. sizeof(hostBfr),
  510. servBfr,
  511. sizeof(servBfr),
  512. NI_NUMERICHOST | NI_NUMERICSERV);
  513. debug(D_CONNECT_TO, "Address info: host = '%s', service = '%s', ai_flags = 0x%02X, ai_family = %d (PF_INET = %d, PF_INET6 = %d), ai_socktype = %d (SOCK_STREAM = %d, SOCK_DGRAM = %d), ai_protocol = %d (IPPROTO_TCP = %d, IPPROTO_UDP = %d), ai_addrlen = %lu (sockaddr_in = %lu, sockaddr_in6 = %lu)",
  514. hostBfr,
  515. servBfr,
  516. (unsigned int)ai->ai_flags,
  517. ai->ai_family,
  518. PF_INET,
  519. PF_INET6,
  520. ai->ai_socktype,
  521. SOCK_STREAM,
  522. SOCK_DGRAM,
  523. ai->ai_protocol,
  524. IPPROTO_TCP,
  525. IPPROTO_UDP,
  526. (unsigned long)ai->ai_addrlen,
  527. (unsigned long)sizeof(struct sockaddr_in),
  528. (unsigned long)sizeof(struct sockaddr_in6));
  529. switch (ai->ai_addr->sa_family) {
  530. case PF_INET: {
  531. struct sockaddr_in *pSadrIn = (struct sockaddr_in *)ai->ai_addr;
  532. (void)pSadrIn;
  533. debug(D_CONNECT_TO, "ai_addr = sin_family: %d (AF_INET = %d, AF_INET6 = %d), sin_addr: '%s', sin_port: '%s'",
  534. pSadrIn->sin_family,
  535. AF_INET,
  536. AF_INET6,
  537. hostBfr,
  538. servBfr);
  539. break;
  540. }
  541. case PF_INET6: {
  542. struct sockaddr_in6 *pSadrIn6 = (struct sockaddr_in6 *) ai->ai_addr;
  543. (void)pSadrIn6;
  544. debug(D_CONNECT_TO,"ai_addr = sin6_family: %d (AF_INET = %d, AF_INET6 = %d), sin6_addr: '%s', sin6_port: '%s', sin6_flowinfo: %u, sin6_scope_id: %u",
  545. pSadrIn6->sin6_family,
  546. AF_INET,
  547. AF_INET6,
  548. hostBfr,
  549. servBfr,
  550. pSadrIn6->sin6_flowinfo,
  551. pSadrIn6->sin6_scope_id);
  552. break;
  553. }
  554. default: {
  555. debug(D_CONNECT_TO, "Unknown protocol family %d.", ai->ai_family);
  556. continue;
  557. }
  558. }
  559. fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
  560. if(fd != -1) {
  561. if(timeout) {
  562. if(setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (char *) timeout, sizeof(struct timeval)) < 0)
  563. error("Failed to set timeout on the socket to ip '%s' port '%s'", hostBfr, servBfr);
  564. }
  565. errno = 0;
  566. if(connect(fd, ai->ai_addr, ai->ai_addrlen) < 0) {
  567. if(errno == EALREADY || errno == EINPROGRESS) {
  568. info("Waiting for connection to ip %s port %s to be established", hostBfr, servBfr);
  569. fd_set fds;
  570. FD_ZERO(&fds);
  571. FD_SET(0, &fds);
  572. int rc = select (1, NULL, &fds, NULL, timeout);
  573. if(rc > 0 && FD_ISSET(fd, &fds)) {
  574. info("connect() to ip %s port %s completed successfully", hostBfr, servBfr);
  575. }
  576. else if(rc == -1) {
  577. error("Failed to connect to '%s', port '%s'. select() returned %d", hostBfr, servBfr, rc);
  578. close(fd);
  579. fd = -1;
  580. }
  581. else {
  582. error("Timed out while connecting to '%s', port '%s'. select() returned %d", hostBfr, servBfr, rc);
  583. close(fd);
  584. fd = -1;
  585. }
  586. }
  587. else {
  588. error("Failed to connect to '%s', port '%s'", hostBfr, servBfr);
  589. close(fd);
  590. fd = -1;
  591. }
  592. }
  593. if(fd != -1)
  594. debug(D_CONNECT_TO, "Connected to '%s' on port '%s'.", hostBfr, servBfr);
  595. }
  596. }
  597. freeaddrinfo(ai_head);
  598. return fd;
  599. }
  600. // connect_to_this()
  601. //
  602. // definition format:
  603. //
  604. // [PROTOCOL:]IP[%INTERFACE][:PORT]
  605. //
  606. // PROTOCOL = tcp or udp
  607. // IP = IPv4 or IPv6 IP or hostname, optionally enclosed in [] (required for IPv6)
  608. // INTERFACE = for IPv6 only, the network interface to use
  609. // PORT = port number or service name
  610. int connect_to_this(const char *definition, int default_port, struct timeval *timeout) {
  611. char buffer[strlen(definition) + 1];
  612. strcpy(buffer, definition);
  613. char default_service[10 + 1];
  614. snprintfz(default_service, 10, "%d", default_port);
  615. char *host = buffer, *service = default_service, *interface = "";
  616. int protocol = IPPROTO_TCP, socktype = SOCK_STREAM;
  617. uint32_t scope_id = 0;
  618. if(strncmp(host, "tcp:", 4) == 0) {
  619. host += 4;
  620. protocol = IPPROTO_TCP;
  621. socktype = SOCK_STREAM;
  622. }
  623. else if(strncmp(host, "udp:", 4) == 0) {
  624. host += 4;
  625. protocol = IPPROTO_UDP;
  626. socktype = SOCK_DGRAM;
  627. }
  628. else if(strncmp(host, "unix:", 5) == 0) {
  629. char *path = host + 5;
  630. return connect_to_unix(path, timeout);
  631. }
  632. char *e = host;
  633. if(*e == '[') {
  634. e = ++host;
  635. while(*e && *e != ']') e++;
  636. if(*e == ']') {
  637. *e = '\0';
  638. e++;
  639. }
  640. }
  641. else {
  642. while(*e && *e != ':' && *e != '%') e++;
  643. }
  644. if(*e == '%') {
  645. *e = '\0';
  646. e++;
  647. interface = e;
  648. while(*e && *e != ':') e++;
  649. }
  650. if(*e == ':') {
  651. *e = '\0';
  652. e++;
  653. service = e;
  654. }
  655. debug(D_CONNECT_TO, "Attempting connection to host = '%s', service = '%s', interface = '%s', protocol = %d (tcp = %d, udp = %d)", host, service, interface, protocol, IPPROTO_TCP, IPPROTO_UDP);
  656. if(!*host) {
  657. error("Definition '%s' does not specify a host.", definition);
  658. return -1;
  659. }
  660. if(*interface) {
  661. scope_id = if_nametoindex(interface);
  662. if(!scope_id)
  663. error("Cannot find a network interface named '%s'. Continuing with limiting the network interface", interface);
  664. }
  665. if(!*service)
  666. service = default_service;
  667. return connect_to_this_ip46(protocol, socktype, host, scope_id, service, timeout);
  668. }
  669. int connect_to_one_of(const char *destination, int default_port, struct timeval *timeout, size_t *reconnects_counter, char *connected_to, size_t connected_to_size) {
  670. int sock = -1;
  671. const char *s = destination;
  672. while(*s) {
  673. const char *e = s;
  674. // skip path, moving both s(tart) and e(nd)
  675. if(*e == '/')
  676. while(!isspace(*e) && *e != ',') s = ++e;
  677. // skip separators, moving both s(tart) and e(nd)
  678. while(isspace(*e) || *e == ',') s = ++e;
  679. // move e(nd) to the first separator
  680. while(*e && !isspace(*e) && *e != ',' && *e != '/') e++;
  681. // is there anything?
  682. if(!*s || s == e) break;
  683. char buf[e - s + 1];
  684. strncpyz(buf, s, e - s);
  685. if(reconnects_counter) *reconnects_counter += 1;
  686. sock = connect_to_this(buf, default_port, timeout);
  687. if(sock != -1) {
  688. if(connected_to && connected_to_size) {
  689. strncpy(connected_to, buf, connected_to_size);
  690. connected_to[connected_to_size - 1] = '\0';
  691. }
  692. break;
  693. }
  694. s = e;
  695. }
  696. return sock;
  697. }
  698. // --------------------------------------------------------------------------------------------------------------------
  699. // helpers to send/receive data in one call, in blocking mode, with a timeout
  700. #ifdef ENABLE_HTTPS
  701. ssize_t recv_timeout(struct netdata_ssl *ssl,int sockfd, void *buf, size_t len, int flags, int timeout) {
  702. #else
  703. ssize_t recv_timeout(int sockfd, void *buf, size_t len, int flags, int timeout) {
  704. #endif
  705. for(;;) {
  706. struct pollfd fd = {
  707. .fd = sockfd,
  708. .events = POLLIN,
  709. .revents = 0
  710. };
  711. errno = 0;
  712. int retval = poll(&fd, 1, timeout * 1000);
  713. if(retval == -1) {
  714. // failed
  715. if(errno == EINTR || errno == EAGAIN)
  716. continue;
  717. return -1;
  718. }
  719. if(!retval) {
  720. // timeout
  721. return 0;
  722. }
  723. if(fd.events & POLLIN) break;
  724. }
  725. #ifdef ENABLE_HTTPS
  726. if (ssl->conn) {
  727. if (!ssl->flags) {
  728. return SSL_read(ssl->conn,buf,len);
  729. }
  730. }
  731. #endif
  732. return recv(sockfd, buf, len, flags);
  733. }
  734. #ifdef ENABLE_HTTPS
  735. ssize_t send_timeout(struct netdata_ssl *ssl,int sockfd, void *buf, size_t len, int flags, int timeout) {
  736. #else
  737. ssize_t send_timeout(int sockfd, void *buf, size_t len, int flags, int timeout) {
  738. #endif
  739. for(;;) {
  740. struct pollfd fd = {
  741. .fd = sockfd,
  742. .events = POLLOUT,
  743. .revents = 0
  744. };
  745. errno = 0;
  746. int retval = poll(&fd, 1, timeout * 1000);
  747. if(retval == -1) {
  748. // failed
  749. if(errno == EINTR || errno == EAGAIN)
  750. continue;
  751. return -1;
  752. }
  753. if(!retval) {
  754. // timeout
  755. return 0;
  756. }
  757. if(fd.events & POLLOUT) break;
  758. }
  759. #ifdef ENABLE_HTTPS
  760. if(ssl->conn) {
  761. if (!ssl->flags) {
  762. return SSL_write(ssl->conn, buf, len);
  763. }
  764. }
  765. #endif
  766. return send(sockfd, buf, len, flags);
  767. }
  768. // --------------------------------------------------------------------------------------------------------------------
  769. // accept4() replacement for systems that do not have one
  770. #ifndef HAVE_ACCEPT4
  771. int accept4(int sock, struct sockaddr *addr, socklen_t *addrlen, int flags) {
  772. int fd = accept(sock, addr, addrlen);
  773. int newflags = 0;
  774. if (fd < 0) return fd;
  775. if (flags & SOCK_NONBLOCK) {
  776. newflags |= O_NONBLOCK;
  777. flags &= ~SOCK_NONBLOCK;
  778. }
  779. #ifdef SOCK_CLOEXEC
  780. #ifdef O_CLOEXEC
  781. if (flags & SOCK_CLOEXEC) {
  782. newflags |= O_CLOEXEC;
  783. flags &= ~SOCK_CLOEXEC;
  784. }
  785. #endif
  786. #endif
  787. if (flags) {
  788. close(fd);
  789. errno = EINVAL;
  790. return -1;
  791. }
  792. if (fcntl(fd, F_SETFL, newflags) < 0) {
  793. int saved_errno = errno;
  794. close(fd);
  795. errno = saved_errno;
  796. return -1;
  797. }
  798. return fd;
  799. }
  800. #endif
  801. /*
  802. * ---------------------------------------------------------------------------------------------------------------------
  803. * connection_allowed() - if there is an access list then check the connection matches a pattern.
  804. * Numeric patterns are checked against the IP address first, only if they
  805. * do not match is the hostname resolved (reverse-DNS) and checked. If the
  806. * hostname matches then we perform forward DNS resolution to check the IP
  807. * is really associated with the DNS record. This call is repeatable: the
  808. * web server may check more refined matches against the connection. Will
  809. * update the client_host if uninitialized - ensure the hostsize is the number
  810. * of *writable* bytes (i.e. be aware of the strdup used to compact the pollinfo).
  811. */
  812. extern int connection_allowed(int fd, char *client_ip, char *client_host, size_t hostsize, SIMPLE_PATTERN *access_list,
  813. const char *patname, int allow_dns)
  814. {
  815. debug(D_LISTENER,"checking %s... (allow_dns=%d)", patname, allow_dns);
  816. if (!access_list)
  817. return 1;
  818. if (simple_pattern_matches(access_list, client_ip))
  819. return 1;
  820. // If the hostname is unresolved (and needed) then attempt the DNS lookups.
  821. //if (client_host[0]==0 && simple_pattern_is_potential_name(access_list))
  822. if (client_host[0]==0 && allow_dns)
  823. {
  824. struct sockaddr_storage sadr;
  825. socklen_t addrlen = sizeof(sadr);
  826. int err = getpeername(fd, (struct sockaddr*)&sadr, &addrlen);
  827. if (err != 0 ||
  828. (err = getnameinfo((struct sockaddr *)&sadr, addrlen, client_host, (socklen_t)hostsize,
  829. NULL, 0, NI_NAMEREQD)) != 0) {
  830. error("Incoming %s on '%s' does not match a numeric pattern, and host could not be resolved (err=%s)",
  831. patname, client_ip, gai_strerror(err));
  832. if (hostsize >= 8)
  833. strcpy(client_host,"UNKNOWN");
  834. return 0;
  835. }
  836. struct addrinfo *addr_infos = NULL;
  837. if (getaddrinfo(client_host, NULL, NULL, &addr_infos) !=0 ) {
  838. error("LISTENER: cannot validate hostname '%s' from '%s' by resolving it",
  839. client_host, client_ip);
  840. if (hostsize >= 8)
  841. strcpy(client_host,"UNKNOWN");
  842. return 0;
  843. }
  844. struct addrinfo *scan = addr_infos;
  845. int validated = 0;
  846. while (scan) {
  847. char address[INET6_ADDRSTRLEN];
  848. address[0] = 0;
  849. switch (scan->ai_addr->sa_family) {
  850. case AF_INET:
  851. inet_ntop(AF_INET, &((struct sockaddr_in*)(scan->ai_addr))->sin_addr, address, INET6_ADDRSTRLEN);
  852. break;
  853. case AF_INET6:
  854. inet_ntop(AF_INET6, &((struct sockaddr_in6*)(scan->ai_addr))->sin6_addr, address, INET6_ADDRSTRLEN);
  855. break;
  856. }
  857. debug(D_LISTENER, "Incoming ip %s rev-resolved onto %s, validating against forward-resolution %s",
  858. client_ip, client_host, address);
  859. if (!strcmp(client_ip, address)) {
  860. validated = 1;
  861. break;
  862. }
  863. scan = scan->ai_next;
  864. }
  865. if (!validated) {
  866. error("LISTENER: Cannot validate '%s' as ip of '%s', not listed in DNS", client_ip, client_host);
  867. if (hostsize >= 8)
  868. strcpy(client_host,"UNKNOWN");
  869. }
  870. if (addr_infos!=NULL)
  871. freeaddrinfo(addr_infos);
  872. }
  873. if (!simple_pattern_matches(access_list, client_host)) {
  874. debug(D_LISTENER, "Incoming connection on '%s' (%s) does not match allowed pattern for %s",
  875. client_ip, client_host, patname);
  876. return 0;
  877. }
  878. return 1;
  879. }
  880. // --------------------------------------------------------------------------------------------------------------------
  881. // accept_socket() - accept a socket and store client IP and port
  882. int accept_socket(int fd, int flags, char *client_ip, size_t ipsize, char *client_port, size_t portsize,
  883. char *client_host, size_t hostsize, SIMPLE_PATTERN *access_list, int allow_dns) {
  884. struct sockaddr_storage sadr;
  885. socklen_t addrlen = sizeof(sadr);
  886. int nfd = accept4(fd, (struct sockaddr *)&sadr, &addrlen, flags);
  887. if (likely(nfd >= 0)) {
  888. if (getnameinfo((struct sockaddr *)&sadr, addrlen, client_ip, (socklen_t)ipsize,
  889. client_port, (socklen_t)portsize, NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
  890. error("LISTENER: cannot getnameinfo() on received client connection.");
  891. strncpyz(client_ip, "UNKNOWN", ipsize - 1);
  892. strncpyz(client_port, "UNKNOWN", portsize - 1);
  893. }
  894. if (!strcmp(client_ip, "127.0.0.1") || !strcmp(client_ip, "::1")) {
  895. strncpy(client_ip, "localhost", ipsize);
  896. client_ip[ipsize - 1] = '\0';
  897. }
  898. #ifdef __FreeBSD__
  899. if(((struct sockaddr *)&sadr)->sa_family == AF_LOCAL)
  900. strncpyz(client_ip, "localhost", ipsize);
  901. #endif
  902. client_ip[ipsize - 1] = '\0';
  903. client_port[portsize - 1] = '\0';
  904. switch (((struct sockaddr *)&sadr)->sa_family) {
  905. case AF_UNIX:
  906. debug(D_LISTENER, "New UNIX domain web client from %s on socket %d.", client_ip, fd);
  907. // set the port - certain versions of libc return garbage on unix sockets
  908. strncpy(client_port, "UNIX", portsize);
  909. client_port[portsize - 1] = '\0';
  910. break;
  911. case AF_INET:
  912. debug(D_LISTENER, "New IPv4 web client from %s port %s on socket %d.", client_ip, client_port, fd);
  913. break;
  914. case AF_INET6:
  915. if (strncmp(client_ip, "::ffff:", 7) == 0) {
  916. memmove(client_ip, &client_ip[7], strlen(&client_ip[7]) + 1);
  917. debug(D_LISTENER, "New IPv4 web client from %s port %s on socket %d.", client_ip, client_port, fd);
  918. }
  919. else
  920. debug(D_LISTENER, "New IPv6 web client from %s port %s on socket %d.", client_ip, client_port, fd);
  921. break;
  922. default:
  923. debug(D_LISTENER, "New UNKNOWN web client from %s port %s on socket %d.", client_ip, client_port, fd);
  924. break;
  925. }
  926. if (!connection_allowed(nfd, client_ip, client_host, hostsize, access_list, "connection", allow_dns)) {
  927. errno = 0;
  928. error("Permission denied for client '%s', port '%s'", client_ip, client_port);
  929. close(nfd);
  930. nfd = -1;
  931. errno = EPERM;
  932. }
  933. }
  934. #ifdef HAVE_ACCEPT4
  935. else if (errno == ENOSYS)
  936. error("netdata has been compiled with the assumption that the system has the accept4() call, but it is not here. Recompile netdata like this: ./configure --disable-accept4 ...");
  937. #endif
  938. return nfd;
  939. }
  940. // --------------------------------------------------------------------------------------------------------------------
  941. // poll() based listener
  942. // this should be the fastest possible listener for up to 100 sockets
  943. // above 100, an epoll() interface is needed on Linux
  944. #define POLL_FDS_INCREASE_STEP 10
  945. inline POLLINFO *poll_add_fd(POLLJOB *p
  946. , int fd
  947. , int socktype
  948. , WEB_CLIENT_ACL port_acl
  949. , uint32_t flags
  950. , const char *client_ip
  951. , const char *client_port
  952. , const char *client_host
  953. , void *(*add_callback)(POLLINFO * /*pi*/, short int * /*events*/, void * /*data*/)
  954. , void (*del_callback)(POLLINFO * /*pi*/)
  955. , int (*rcv_callback)(POLLINFO * /*pi*/, short int * /*events*/)
  956. , int (*snd_callback)(POLLINFO * /*pi*/, short int * /*events*/)
  957. , void *data
  958. ) {
  959. debug(D_POLLFD, "POLLFD: ADD: request to add fd %d, slots = %zu, used = %zu, min = %zu, max = %zu, next free = %zd", fd, p->slots, p->used, p->min, p->max, p->first_free?(ssize_t)p->first_free->slot:(ssize_t)-1);
  960. if(unlikely(fd < 0)) return NULL;
  961. //if(p->limit && p->used >= p->limit) {
  962. // info("Max sockets limit reached (%zu sockets), dropping connection", p->used);
  963. // close(fd);
  964. // return NULL;
  965. //}
  966. if(unlikely(!p->first_free)) {
  967. size_t new_slots = p->slots + POLL_FDS_INCREASE_STEP;
  968. debug(D_POLLFD, "POLLFD: ADD: increasing size (current = %zu, new = %zu, used = %zu, min = %zu, max = %zu)", p->slots, new_slots, p->used, p->min, p->max);
  969. p->fds = reallocz(p->fds, sizeof(struct pollfd) * new_slots);
  970. p->inf = reallocz(p->inf, sizeof(POLLINFO) * new_slots);
  971. // reset all the newly added slots
  972. ssize_t i;
  973. for(i = new_slots - 1; i >= (ssize_t)p->slots ; i--) {
  974. debug(D_POLLFD, "POLLFD: ADD: resetting new slot %zd", i);
  975. p->fds[i].fd = -1;
  976. p->fds[i].events = 0;
  977. p->fds[i].revents = 0;
  978. p->inf[i].p = p;
  979. p->inf[i].slot = (size_t)i;
  980. p->inf[i].flags = 0;
  981. p->inf[i].socktype = -1;
  982. p->inf[i].port_acl = -1;
  983. p->inf[i].client_ip = NULL;
  984. p->inf[i].client_port = NULL;
  985. p->inf[i].client_host = NULL;
  986. p->inf[i].del_callback = p->del_callback;
  987. p->inf[i].rcv_callback = p->rcv_callback;
  988. p->inf[i].snd_callback = p->snd_callback;
  989. p->inf[i].data = NULL;
  990. // link them so that the first free will be earlier in the array
  991. // (we loop decrementing i)
  992. p->inf[i].next = p->first_free;
  993. p->first_free = &p->inf[i];
  994. }
  995. p->slots = new_slots;
  996. }
  997. POLLINFO *pi = p->first_free;
  998. p->first_free = p->first_free->next;
  999. debug(D_POLLFD, "POLLFD: ADD: selected slot %zu, next free is %zd", pi->slot, p->first_free?(ssize_t)p->first_free->slot:(ssize_t)-1);
  1000. struct pollfd *pf = &p->fds[pi->slot];
  1001. pf->fd = fd;
  1002. pf->events = POLLIN;
  1003. pf->revents = 0;
  1004. pi->fd = fd;
  1005. pi->p = p;
  1006. pi->socktype = socktype;
  1007. pi->port_acl = port_acl;
  1008. pi->flags = flags;
  1009. pi->next = NULL;
  1010. pi->client_ip = strdupz(client_ip);
  1011. pi->client_port = strdupz(client_port);
  1012. pi->client_host = strdupz(client_host);
  1013. pi->del_callback = del_callback;
  1014. pi->rcv_callback = rcv_callback;
  1015. pi->snd_callback = snd_callback;
  1016. pi->connected_t = now_boottime_sec();
  1017. pi->last_received_t = 0;
  1018. pi->last_sent_t = 0;
  1019. pi->last_sent_t = 0;
  1020. pi->recv_count = 0;
  1021. pi->send_count = 0;
  1022. netdata_thread_disable_cancelability();
  1023. p->used++;
  1024. if(unlikely(pi->slot > p->max))
  1025. p->max = pi->slot;
  1026. if(pi->flags & POLLINFO_FLAG_CLIENT_SOCKET) {
  1027. pi->data = add_callback(pi, &pf->events, data);
  1028. }
  1029. if(pi->flags & POLLINFO_FLAG_SERVER_SOCKET) {
  1030. p->min = pi->slot;
  1031. }
  1032. netdata_thread_enable_cancelability();
  1033. debug(D_POLLFD, "POLLFD: ADD: completed, slots = %zu, used = %zu, min = %zu, max = %zu, next free = %zd", p->slots, p->used, p->min, p->max, p->first_free?(ssize_t)p->first_free->slot:(ssize_t)-1);
  1034. return pi;
  1035. }
  1036. inline void poll_close_fd(POLLINFO *pi) {
  1037. POLLJOB *p = pi->p;
  1038. struct pollfd *pf = &p->fds[pi->slot];
  1039. debug(D_POLLFD, "POLLFD: DEL: request to clear slot %zu (fd %d), old next free was %zd", pi->slot, pf->fd, p->first_free?(ssize_t)p->first_free->slot:(ssize_t)-1);
  1040. if(unlikely(pf->fd == -1)) return;
  1041. netdata_thread_disable_cancelability();
  1042. if(pi->flags & POLLINFO_FLAG_CLIENT_SOCKET) {
  1043. pi->del_callback(pi);
  1044. if(likely(!(pi->flags & POLLINFO_FLAG_DONT_CLOSE))) {
  1045. if(close(pf->fd) == -1)
  1046. error("Failed to close() poll_events() socket %d", pf->fd);
  1047. }
  1048. }
  1049. pf->fd = -1;
  1050. pf->events = 0;
  1051. pf->revents = 0;
  1052. pi->fd = -1;
  1053. pi->socktype = -1;
  1054. pi->flags = 0;
  1055. pi->data = NULL;
  1056. pi->del_callback = NULL;
  1057. pi->rcv_callback = NULL;
  1058. pi->snd_callback = NULL;
  1059. freez(pi->client_ip);
  1060. pi->client_ip = NULL;
  1061. freez(pi->client_port);
  1062. pi->client_port = NULL;
  1063. freez(pi->client_host);
  1064. pi->client_host = NULL;
  1065. pi->next = p->first_free;
  1066. p->first_free = pi;
  1067. p->used--;
  1068. if(unlikely(p->max == pi->slot)) {
  1069. p->max = p->min;
  1070. ssize_t i;
  1071. for(i = (ssize_t)pi->slot; i > (ssize_t)p->min ;i--) {
  1072. if (unlikely(p->fds[i].fd != -1)) {
  1073. p->max = (size_t)i;
  1074. break;
  1075. }
  1076. }
  1077. }
  1078. netdata_thread_enable_cancelability();
  1079. debug(D_POLLFD, "POLLFD: DEL: completed, slots = %zu, used = %zu, min = %zu, max = %zu, next free = %zd", p->slots, p->used, p->min, p->max, p->first_free?(ssize_t)p->first_free->slot:(ssize_t)-1);
  1080. }
  1081. void *poll_default_add_callback(POLLINFO *pi, short int *events, void *data) {
  1082. (void)pi;
  1083. (void)events;
  1084. (void)data;
  1085. // error("POLLFD: internal error: poll_default_add_callback() called");
  1086. return NULL;
  1087. }
  1088. void poll_default_del_callback(POLLINFO *pi) {
  1089. if(pi->data)
  1090. error("POLLFD: internal error: del_callback_default() called with data pointer - possible memory leak");
  1091. }
  1092. int poll_default_rcv_callback(POLLINFO *pi, short int *events) {
  1093. *events |= POLLIN;
  1094. char buffer[1024 + 1];
  1095. ssize_t rc;
  1096. do {
  1097. rc = recv(pi->fd, buffer, 1024, MSG_DONTWAIT);
  1098. if (rc < 0) {
  1099. // read failed
  1100. if (errno != EWOULDBLOCK && errno != EAGAIN) {
  1101. error("POLLFD: poll_default_rcv_callback(): recv() failed with %zd.", rc);
  1102. return -1;
  1103. }
  1104. } else if (rc) {
  1105. // data received
  1106. info("POLLFD: internal error: poll_default_rcv_callback() is discarding %zd bytes received on socket %d", rc, pi->fd);
  1107. }
  1108. } while (rc != -1);
  1109. return 0;
  1110. }
  1111. int poll_default_snd_callback(POLLINFO *pi, short int *events) {
  1112. *events &= ~POLLOUT;
  1113. info("POLLFD: internal error: poll_default_snd_callback(): nothing to send on socket %d", pi->fd);
  1114. return 0;
  1115. }
  1116. void poll_default_tmr_callback(void *timer_data) {
  1117. (void)timer_data;
  1118. }
  1119. static void poll_events_cleanup(void *data) {
  1120. POLLJOB *p = (POLLJOB *)data;
  1121. size_t i;
  1122. for(i = 0 ; i <= p->max ; i++) {
  1123. POLLINFO *pi = &p->inf[i];
  1124. poll_close_fd(pi);
  1125. }
  1126. freez(p->fds);
  1127. freez(p->inf);
  1128. }
  1129. static int poll_process_error(POLLINFO *pi, struct pollfd *pf, short int revents) {
  1130. error("POLLFD: LISTENER: received %s %s %s on socket at slot %zu (fd %d) client '%s' port '%s' expecting %s %s %s, having %s %s %s"
  1131. , revents & POLLERR ? "POLLERR" : ""
  1132. , revents & POLLHUP ? "POLLHUP" : ""
  1133. , revents & POLLNVAL ? "POLLNVAL" : ""
  1134. , pi->slot
  1135. , pi->fd
  1136. , pi->client_ip ? pi->client_ip : "<undefined-ip>"
  1137. , pi->client_port ? pi->client_port : "<undefined-port>"
  1138. , pf->events & POLLIN ? "POLLIN" : "", pf->events & POLLOUT ? "POLLOUT" : "", pf->events & POLLPRI ? "POLLPRI" : ""
  1139. , revents & POLLIN ? "POLLIN" : "", revents & POLLOUT ? "POLLOUT" : "", revents & POLLPRI ? "POLLPRI" : ""
  1140. );
  1141. pf->events = 0;
  1142. poll_close_fd(pi);
  1143. return 1;
  1144. }
  1145. static inline int poll_process_send(POLLJOB *p, POLLINFO *pi, struct pollfd *pf, time_t now) {
  1146. pi->last_sent_t = now;
  1147. pi->send_count++;
  1148. debug(D_POLLFD, "POLLFD: LISTENER: sending data to socket on slot %zu (fd %d)", pi->slot, pf->fd);
  1149. pf->events = 0;
  1150. // remember the slot, in case we need to close it later
  1151. // the callback may manipulate the socket list and our pf and pi pointers may be invalid after that call
  1152. size_t slot = pi->slot;
  1153. if (unlikely(pi->snd_callback(pi, &pf->events) == -1))
  1154. poll_close_fd(&p->inf[slot]);
  1155. // IMPORTANT:
  1156. // pf and pi may be invalid below this point, they may have been reallocated.
  1157. return 1;
  1158. }
  1159. static inline int poll_process_tcp_read(POLLJOB *p, POLLINFO *pi, struct pollfd *pf, time_t now) {
  1160. pi->last_received_t = now;
  1161. pi->recv_count++;
  1162. debug(D_POLLFD, "POLLFD: LISTENER: reading data from TCP client slot %zu (fd %d)", pi->slot, pf->fd);
  1163. pf->events = 0;
  1164. // remember the slot, in case we need to close it later
  1165. // the callback may manipulate the socket list and our pf and pi pointers may be invalid after that call
  1166. size_t slot = pi->slot;
  1167. if (pi->rcv_callback(pi, &pf->events) == -1)
  1168. poll_close_fd(&p->inf[slot]);
  1169. // IMPORTANT:
  1170. // pf and pi may be invalid below this point, they may have been reallocated.
  1171. return 1;
  1172. }
  1173. static inline int poll_process_udp_read(POLLINFO *pi, struct pollfd *pf, time_t now __maybe_unused) {
  1174. pi->last_received_t = now;
  1175. pi->recv_count++;
  1176. debug(D_POLLFD, "POLLFD: LISTENER: reading data from UDP slot %zu (fd %d)", pi->slot, pf->fd);
  1177. // TODO: access_list is not applied to UDP
  1178. // but checking the access list on every UDP packet will destroy
  1179. // performance, especially for statsd.
  1180. pf->events = 0;
  1181. if(pi->rcv_callback(pi, &pf->events) == -1)
  1182. return 0;
  1183. // IMPORTANT:
  1184. // pf and pi may be invalid below this point, they may have been reallocated.
  1185. return 1;
  1186. }
  1187. static int poll_process_new_tcp_connection(POLLJOB *p, POLLINFO *pi, struct pollfd *pf, time_t now) {
  1188. pi->last_received_t = now;
  1189. pi->recv_count++;
  1190. debug(D_POLLFD, "POLLFD: LISTENER: accepting connections from slot %zu (fd %d)", pi->slot, pf->fd);
  1191. char client_ip[INET6_ADDRSTRLEN] = "";
  1192. char client_port[NI_MAXSERV] = "";
  1193. char client_host[NI_MAXHOST] = "";
  1194. debug(D_POLLFD, "POLLFD: LISTENER: calling accept4() slot %zu (fd %d)", pi->slot, pf->fd);
  1195. int nfd = accept_socket(
  1196. pf->fd,SOCK_NONBLOCK,
  1197. client_ip, INET6_ADDRSTRLEN, client_port,NI_MAXSERV, client_host, NI_MAXHOST,
  1198. p->access_list, p->allow_dns
  1199. );
  1200. if (unlikely(nfd < 0)) {
  1201. // accept failed
  1202. debug(D_POLLFD, "POLLFD: LISTENER: accept4() slot %zu (fd %d) failed.", pi->slot, pf->fd);
  1203. if(unlikely(errno == EMFILE)) {
  1204. error("POLLFD: LISTENER: too many open files - sleeping for 1ms - used by this thread %zu, max for this thread %zu", p->used, p->limit);
  1205. usleep(1000); // 1ms
  1206. }
  1207. else if(unlikely(errno != EWOULDBLOCK && errno != EAGAIN))
  1208. error("POLLFD: LISTENER: accept() failed.");
  1209. }
  1210. else {
  1211. // accept ok
  1212. poll_add_fd(p
  1213. , nfd
  1214. , SOCK_STREAM
  1215. , pi->port_acl
  1216. , POLLINFO_FLAG_CLIENT_SOCKET
  1217. , client_ip
  1218. , client_port
  1219. , client_host
  1220. , p->add_callback
  1221. , p->del_callback
  1222. , p->rcv_callback
  1223. , p->snd_callback
  1224. , NULL
  1225. );
  1226. // IMPORTANT:
  1227. // pf and pi may be invalid below this point, they may have been reallocated.
  1228. return 1;
  1229. }
  1230. return 0;
  1231. }
  1232. void poll_events(LISTEN_SOCKETS *sockets
  1233. , void *(*add_callback)(POLLINFO * /*pi*/, short int * /*events*/, void * /*data*/)
  1234. , void (*del_callback)(POLLINFO * /*pi*/)
  1235. , int (*rcv_callback)(POLLINFO * /*pi*/, short int * /*events*/)
  1236. , int (*snd_callback)(POLLINFO * /*pi*/, short int * /*events*/)
  1237. , void (*tmr_callback)(void * /*timer_data*/)
  1238. , SIMPLE_PATTERN *access_list
  1239. , int allow_dns
  1240. , void *data
  1241. , time_t tcp_request_timeout_seconds
  1242. , time_t tcp_idle_timeout_seconds
  1243. , time_t timer_milliseconds
  1244. , void *timer_data
  1245. , size_t max_tcp_sockets
  1246. ) {
  1247. if(!sockets || !sockets->opened) {
  1248. error("POLLFD: internal error: no listening sockets are opened");
  1249. return;
  1250. }
  1251. if(timer_milliseconds <= 0) timer_milliseconds = 0;
  1252. int retval;
  1253. POLLJOB p = {
  1254. .slots = 0,
  1255. .used = 0,
  1256. .max = 0,
  1257. .limit = max_tcp_sockets,
  1258. .fds = NULL,
  1259. .inf = NULL,
  1260. .first_free = NULL,
  1261. .complete_request_timeout = tcp_request_timeout_seconds,
  1262. .idle_timeout = tcp_idle_timeout_seconds,
  1263. .checks_every = (tcp_idle_timeout_seconds / 3) + 1,
  1264. .access_list = access_list,
  1265. .allow_dns = allow_dns,
  1266. .timer_milliseconds = timer_milliseconds,
  1267. .timer_data = timer_data,
  1268. .add_callback = add_callback?add_callback:poll_default_add_callback,
  1269. .del_callback = del_callback?del_callback:poll_default_del_callback,
  1270. .rcv_callback = rcv_callback?rcv_callback:poll_default_rcv_callback,
  1271. .snd_callback = snd_callback?snd_callback:poll_default_snd_callback,
  1272. .tmr_callback = tmr_callback?tmr_callback:poll_default_tmr_callback
  1273. };
  1274. size_t i;
  1275. for(i = 0; i < sockets->opened ;i++) {
  1276. POLLINFO *pi = poll_add_fd(&p
  1277. , sockets->fds[i]
  1278. , sockets->fds_types[i]
  1279. , sockets->fds_acl_flags[i]
  1280. , POLLINFO_FLAG_SERVER_SOCKET
  1281. , (sockets->fds_names[i])?sockets->fds_names[i]:"UNKNOWN"
  1282. , ""
  1283. , ""
  1284. , p.add_callback
  1285. , p.del_callback
  1286. , p.rcv_callback
  1287. , p.snd_callback
  1288. , NULL
  1289. );
  1290. pi->data = data;
  1291. info("POLLFD: LISTENER: listening on '%s'", (sockets->fds_names[i])?sockets->fds_names[i]:"UNKNOWN");
  1292. }
  1293. int listen_sockets_active = 1;
  1294. int timeout_ms = 1000; // in milliseconds
  1295. time_t last_check = now_boottime_sec();
  1296. usec_t timer_usec = timer_milliseconds * USEC_PER_MS;
  1297. usec_t now_usec = 0, next_timer_usec = 0, last_timer_usec = 0;
  1298. (void)last_timer_usec;
  1299. if(unlikely(timer_usec)) {
  1300. now_usec = now_boottime_usec();
  1301. next_timer_usec = now_usec - (now_usec % timer_usec) + timer_usec;
  1302. }
  1303. netdata_thread_cleanup_push(poll_events_cleanup, &p);
  1304. while(!netdata_exit) {
  1305. if(unlikely(timer_usec)) {
  1306. now_usec = now_boottime_usec();
  1307. if(unlikely(timer_usec && now_usec >= next_timer_usec)) {
  1308. debug(D_POLLFD, "Calling timer callback after %zu usec", (size_t)(now_usec - last_timer_usec));
  1309. last_timer_usec = now_usec;
  1310. p.tmr_callback(p.timer_data);
  1311. now_usec = now_boottime_usec();
  1312. next_timer_usec = now_usec - (now_usec % timer_usec) + timer_usec;
  1313. }
  1314. usec_t dt_usec = next_timer_usec - now_usec;
  1315. if(dt_usec < 1000 * USEC_PER_MS)
  1316. timeout_ms = 1000;
  1317. else
  1318. timeout_ms = (int)(dt_usec / USEC_PER_MS);
  1319. }
  1320. // enable or disable the TCP listening sockets, based on the current number of sockets used and the limit set
  1321. if((listen_sockets_active && (p.limit && p.used >= p.limit)) || (!listen_sockets_active && (!p.limit || p.used < p.limit))) {
  1322. listen_sockets_active = !listen_sockets_active;
  1323. info("%s listening sockets (used TCP sockets %zu, max allowed for this worker %zu)", (listen_sockets_active)?"ENABLING":"DISABLING", p.used, p.limit);
  1324. for (i = 0; i <= p.max; i++) {
  1325. if(p.inf[i].flags & POLLINFO_FLAG_SERVER_SOCKET && p.inf[i].socktype == SOCK_STREAM) {
  1326. p.fds[i].events = (short int) ((listen_sockets_active) ? POLLIN : 0);
  1327. }
  1328. }
  1329. }
  1330. debug(D_POLLFD, "POLLFD: LISTENER: Waiting on %zu sockets for %zu ms...", p.max + 1, (size_t)timeout_ms);
  1331. retval = poll(p.fds, p.max + 1, timeout_ms);
  1332. time_t now = now_boottime_sec();
  1333. if(unlikely(retval == -1)) {
  1334. error("POLLFD: LISTENER: poll() failed while waiting on %zu sockets.", p.max + 1);
  1335. break;
  1336. }
  1337. else if(unlikely(!retval)) {
  1338. debug(D_POLLFD, "POLLFD: LISTENER: poll() timeout.");
  1339. }
  1340. else {
  1341. POLLINFO *pi;
  1342. struct pollfd *pf;
  1343. size_t idx, processed = 0;
  1344. short int revents;
  1345. // keep fast lookup arrays per function
  1346. // to avoid looping through the entire list every time
  1347. size_t sends[p.max + 1], sends_max = 0;
  1348. size_t reads[p.max + 1], reads_max = 0;
  1349. size_t conns[p.max + 1], conns_max = 0;
  1350. size_t udprd[p.max + 1], udprd_max = 0;
  1351. for (i = 0; i <= p.max; i++) {
  1352. pi = &p.inf[i];
  1353. pf = &p.fds[i];
  1354. revents = pf->revents;
  1355. if(unlikely(revents == 0 || pf->fd == -1))
  1356. continue;
  1357. if (unlikely(revents & (POLLERR|POLLHUP|POLLNVAL))) {
  1358. // something is wrong to one of our sockets
  1359. pf->revents = 0;
  1360. processed += poll_process_error(pi, pf, revents);
  1361. }
  1362. else if (likely(revents & POLLOUT)) {
  1363. // a client is ready to receive data
  1364. sends[sends_max++] = i;
  1365. }
  1366. else if (likely(revents & (POLLIN|POLLPRI))) {
  1367. if (pi->flags & POLLINFO_FLAG_CLIENT_SOCKET) {
  1368. // a client sent data to us
  1369. reads[reads_max++] = i;
  1370. }
  1371. else if (pi->flags & POLLINFO_FLAG_SERVER_SOCKET) {
  1372. // something is coming to our server sockets
  1373. if(pi->socktype == SOCK_DGRAM) {
  1374. // UDP receive, directly on our listening socket
  1375. udprd[udprd_max++] = i;
  1376. }
  1377. else if(pi->socktype == SOCK_STREAM) {
  1378. // new TCP connection
  1379. conns[conns_max++] = i;
  1380. }
  1381. else
  1382. error("POLLFD: LISTENER: server slot %zu (fd %d) connection from %s port %s using unhandled socket type %d."
  1383. , i
  1384. , pi->fd
  1385. , pi->client_ip ? pi->client_ip : "<undefined-ip>"
  1386. , pi->client_port ? pi->client_port : "<undefined-port>"
  1387. , pi->socktype
  1388. );
  1389. }
  1390. else
  1391. error("POLLFD: LISTENER: client slot %zu (fd %d) data from %s port %s using flags %08X is neither client nor server."
  1392. , i
  1393. , pi->fd
  1394. , pi->client_ip ? pi->client_ip : "<undefined-ip>"
  1395. , pi->client_port ? pi->client_port : "<undefined-port>"
  1396. , pi->flags
  1397. );
  1398. }
  1399. else
  1400. error("POLLFD: LISTENER: socket slot %zu (fd %d) client %s port %s unhandled event id %d."
  1401. , i
  1402. , pi->fd
  1403. , pi->client_ip ? pi->client_ip : "<undefined-ip>"
  1404. , pi->client_port ? pi->client_port : "<undefined-port>"
  1405. , revents
  1406. );
  1407. }
  1408. // process sends
  1409. for (idx = 0; idx < sends_max; idx++) {
  1410. i = sends[idx];
  1411. pi = &p.inf[i];
  1412. pf = &p.fds[i];
  1413. pf->revents = 0;
  1414. processed += poll_process_send(&p, pi, pf, now);
  1415. }
  1416. // process UDP reads
  1417. for (idx = 0; idx < udprd_max; idx++) {
  1418. i = udprd[idx];
  1419. pi = &p.inf[i];
  1420. pf = &p.fds[i];
  1421. pf->revents = 0;
  1422. processed += poll_process_udp_read(pi, pf, now);
  1423. }
  1424. // process TCP reads
  1425. for (idx = 0; idx < reads_max; idx++) {
  1426. i = reads[idx];
  1427. pi = &p.inf[i];
  1428. pf = &p.fds[i];
  1429. pf->revents = 0;
  1430. processed += poll_process_tcp_read(&p, pi, pf, now);
  1431. }
  1432. if(!processed && (!p.limit || p.used < p.limit)) {
  1433. // nothing processed above (rcv, snd) and we have room for another TCP connection
  1434. // so, accept one TCP connection
  1435. for (idx = 0; idx < conns_max; idx++) {
  1436. i = conns[idx];
  1437. pi = &p.inf[i];
  1438. pf = &p.fds[i];
  1439. pf->revents = 0;
  1440. if (poll_process_new_tcp_connection(&p, pi, pf, now))
  1441. break;
  1442. }
  1443. }
  1444. }
  1445. if(unlikely(p.checks_every > 0 && now - last_check > p.checks_every)) {
  1446. last_check = now;
  1447. // cleanup old sockets
  1448. for(i = 0; i <= p.max; i++) {
  1449. POLLINFO *pi = &p.inf[i];
  1450. if(likely(pi->flags & POLLINFO_FLAG_CLIENT_SOCKET)) {
  1451. if (unlikely(pi->send_count == 0 && p.complete_request_timeout > 0 && (now - pi->connected_t) >= p.complete_request_timeout)) {
  1452. info("POLLFD: LISTENER: client slot %zu (fd %d) from %s port %s has not sent a complete request in %zu seconds - closing it. "
  1453. , i
  1454. , pi->fd
  1455. , pi->client_ip ? pi->client_ip : "<undefined-ip>"
  1456. , pi->client_port ? pi->client_port : "<undefined-port>"
  1457. , (size_t) p.complete_request_timeout
  1458. );
  1459. poll_close_fd(pi);
  1460. }
  1461. else if(unlikely(pi->recv_count && p.idle_timeout > 0 && now - ((pi->last_received_t > pi->last_sent_t) ? pi->last_received_t : pi->last_sent_t) >= p.idle_timeout )) {
  1462. info("POLLFD: LISTENER: client slot %zu (fd %d) from %s port %s is idle for more than %zu seconds - closing it. "
  1463. , i
  1464. , pi->fd
  1465. , pi->client_ip ? pi->client_ip : "<undefined-ip>"
  1466. , pi->client_port ? pi->client_port : "<undefined-port>"
  1467. , (size_t) p.idle_timeout
  1468. );
  1469. poll_close_fd(pi);
  1470. }
  1471. }
  1472. }
  1473. }
  1474. }
  1475. netdata_thread_cleanup_pop(1);
  1476. debug(D_POLLFD, "POLLFD: LISTENER: cleanup completed");
  1477. }