socket.c 65 KB

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