socket.c 64 KB

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