socket.c 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991
  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, "not connected", sizeof(peers.peer.ip) - 1);
  13. peers.peer.port = 0;
  14. strncpyz(peers.local.ip, "not connected", 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. netdata_log_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. netdata_log_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. netdata_log_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. netdata_log_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. netdata_log_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. netdata_log_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. netdata_log_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. netdata_log_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. netdata_log_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. netdata_log_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. netdata_log_error("LISTENER: failed to chmod() socket file '%s'.", path);
  188. if(listen(sock, listen_backlog) < 0) {
  189. close(sock);
  190. netdata_log_error("LISTENER: UNIX listen() on path '%s' failed.", path);
  191. return -1;
  192. }
  193. netdata_log_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. netdata_log_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. netdata_log_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. netdata_log_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. netdata_log_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. netdata_log_error("LISTENER: IPv4 listen() on ip '%s' port %d, socktype %d failed.", ip, port, socktype);
  226. return -1;
  227. }
  228. netdata_log_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. netdata_log_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. netdata_log_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. netdata_log_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. netdata_log_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. netdata_log_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. netdata_log_error("LISTENER: IPv6 listen() on ip '%s' port %d, socktype %d failed.", ip, port, socktype);
  267. return -1;
  268. }
  269. netdata_log_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. netdata_log_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. netdata_log_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. netdata_log_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. netdata_log_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. // netdata_log_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. // netdata_log_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. netdata_log_debug(D_LISTENER, "LISTENER: Unknown socket family %d", family);
  486. break;
  487. }
  488. if (fd == -1) {
  489. netdata_log_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. netdata_log_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. netdata_log_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. netdata_log_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. netdata_log_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. netdata_log_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. netdata_log_error("Cannot connect to UNIX socket on path '%s'.", path);
  553. close(fd);
  554. return -1;
  555. }
  556. netdata_log_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. netdata_log_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. netdata_log_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. netdata_log_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. netdata_log_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. netdata_log_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. netdata_log_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. netdata_log_info("Waiting for connection to ip %s port %s to be established", hostBfr, servBfr);
  653. // Convert 'struct timeval' to milliseconds for poll():
  654. int timeout_milliseconds = timeout->tv_sec * 1000 + timeout->tv_usec / 1000;
  655. struct pollfd fds[1];
  656. fds[0].fd = fd;
  657. fds[0].events = POLLOUT; // We are looking for the ability to write to the socket
  658. int ret = poll(fds, 1, timeout_milliseconds);
  659. if (ret > 0) {
  660. // poll() completed normally. We can check the revents to see what happened
  661. if (fds[0].revents & POLLOUT) {
  662. // connect() completed successfully, socket is writable.
  663. netdata_log_info("connect() to ip %s port %s completed successfully", hostBfr, servBfr);
  664. }
  665. else {
  666. // This means that the socket is in error. We will close it and set fd to -1
  667. netdata_log_error("Failed to connect to '%s', port '%s'.", hostBfr, servBfr);
  668. close(fd);
  669. fd = -1;
  670. }
  671. }
  672. else if (ret == 0) {
  673. // poll() timed out, the connection is not established within the specified timeout.
  674. netdata_log_error("Timed out while connecting to '%s', port '%s'.", hostBfr, servBfr);
  675. close(fd);
  676. fd = -1;
  677. }
  678. else {
  679. // poll() returned an error.
  680. netdata_log_error("Failed to connect to '%s', port '%s'. poll() returned %d", hostBfr, servBfr, ret);
  681. close(fd);
  682. fd = -1;
  683. }
  684. }
  685. else {
  686. netdata_log_error("Failed to connect to '%s', port '%s'", hostBfr, servBfr);
  687. close(fd);
  688. fd = -1;
  689. }
  690. }
  691. if(fd != -1)
  692. netdata_log_debug(D_CONNECT_TO, "Connected to '%s' on port '%s'.", hostBfr, servBfr);
  693. }
  694. }
  695. freeaddrinfo(ai_head);
  696. return fd;
  697. }
  698. // connect_to_this()
  699. //
  700. // definition format:
  701. //
  702. // [PROTOCOL:]IP[%INTERFACE][:PORT]
  703. //
  704. // PROTOCOL = tcp or udp
  705. // IP = IPv4 or IPv6 IP or hostname, optionally enclosed in [] (required for IPv6)
  706. // INTERFACE = for IPv6 only, the network interface to use
  707. // PORT = port number or service name
  708. int connect_to_this(const char *definition, int default_port, struct timeval *timeout) {
  709. char buffer[strlen(definition) + 1];
  710. strcpy(buffer, definition);
  711. char default_service[10 + 1];
  712. snprintfz(default_service, 10, "%d", default_port);
  713. char *host = buffer, *service = default_service, *interface = "";
  714. int protocol = IPPROTO_TCP, socktype = SOCK_STREAM;
  715. uint32_t scope_id = 0;
  716. if(strncmp(host, "tcp:", 4) == 0) {
  717. host += 4;
  718. protocol = IPPROTO_TCP;
  719. socktype = SOCK_STREAM;
  720. }
  721. else if(strncmp(host, "udp:", 4) == 0) {
  722. host += 4;
  723. protocol = IPPROTO_UDP;
  724. socktype = SOCK_DGRAM;
  725. }
  726. else if(strncmp(host, "unix:", 5) == 0) {
  727. char *path = host + 5;
  728. return connect_to_unix(path, timeout);
  729. }
  730. else if(*host == '/') {
  731. char *path = host;
  732. return connect_to_unix(path, timeout);
  733. }
  734. char *e = host;
  735. if(*e == '[') {
  736. e = ++host;
  737. while(*e && *e != ']') e++;
  738. if(*e == ']') {
  739. *e = '\0';
  740. e++;
  741. }
  742. }
  743. else {
  744. while(*e && *e != ':' && *e != '%') e++;
  745. }
  746. if(*e == '%') {
  747. *e = '\0';
  748. e++;
  749. interface = e;
  750. while(*e && *e != ':') e++;
  751. }
  752. if(*e == ':') {
  753. *e = '\0';
  754. e++;
  755. service = e;
  756. }
  757. netdata_log_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);
  758. if(!*host) {
  759. netdata_log_error("Definition '%s' does not specify a host.", definition);
  760. return -1;
  761. }
  762. if(*interface) {
  763. scope_id = if_nametoindex(interface);
  764. if(!scope_id)
  765. netdata_log_error("Cannot find a network interface named '%s'. Continuing with limiting the network interface", interface);
  766. }
  767. if(!*service)
  768. service = default_service;
  769. return connect_to_this_ip46(protocol, socktype, host, scope_id, service, timeout);
  770. }
  771. void foreach_entry_in_connection_string(const char *destination, bool (*callback)(char *entry, void *data), void *data) {
  772. const char *s = destination;
  773. while(*s) {
  774. const char *e = s;
  775. // skip separators, moving both s(tart) and e(nd)
  776. while(isspace(*e) || *e == ',') s = ++e;
  777. // move e(nd) to the first separator
  778. while(*e && !isspace(*e) && *e != ',') e++;
  779. // is there anything?
  780. if(!*s || s == e) break;
  781. char buf[e - s + 1];
  782. strncpyz(buf, s, e - s);
  783. if(callback(buf, data)) break;
  784. s = e;
  785. }
  786. }
  787. struct connect_to_one_of_data {
  788. int default_port;
  789. struct timeval *timeout;
  790. size_t *reconnects_counter;
  791. char *connected_to;
  792. size_t connected_to_size;
  793. int sock;
  794. };
  795. static bool connect_to_one_of_callback(char *entry, void *data) {
  796. struct connect_to_one_of_data *t = data;
  797. if(t->reconnects_counter)
  798. t->reconnects_counter++;
  799. t->sock = connect_to_this(entry, t->default_port, t->timeout);
  800. if(t->sock != -1) {
  801. if(t->connected_to && t->connected_to_size) {
  802. strncpyz(t->connected_to, entry, t->connected_to_size);
  803. t->connected_to[t->connected_to_size - 1] = '\0';
  804. }
  805. return true;
  806. }
  807. return false;
  808. }
  809. 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) {
  810. struct connect_to_one_of_data t = {
  811. .default_port = default_port,
  812. .timeout = timeout,
  813. .reconnects_counter = reconnects_counter,
  814. .connected_to = connected_to,
  815. .connected_to_size = connected_to_size,
  816. .sock = -1,
  817. };
  818. foreach_entry_in_connection_string(destination, connect_to_one_of_callback, &t);
  819. return t.sock;
  820. }
  821. static bool connect_to_one_of_urls_callback(char *entry, void *data) {
  822. char *s = strchr(entry, '/');
  823. if(s) *s = '\0';
  824. return connect_to_one_of_callback(entry, data);
  825. }
  826. 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) {
  827. struct connect_to_one_of_data t = {
  828. .default_port = default_port,
  829. .timeout = timeout,
  830. .reconnects_counter = reconnects_counter,
  831. .connected_to = connected_to,
  832. .connected_to_size = connected_to_size,
  833. .sock = -1,
  834. };
  835. foreach_entry_in_connection_string(destination, connect_to_one_of_urls_callback, &t);
  836. return t.sock;
  837. }
  838. // --------------------------------------------------------------------------------------------------------------------
  839. // helpers to send/receive data in one call, in blocking mode, with a timeout
  840. #ifdef ENABLE_HTTPS
  841. ssize_t recv_timeout(NETDATA_SSL *ssl,int sockfd, void *buf, size_t len, int flags, int timeout) {
  842. #else
  843. ssize_t recv_timeout(int sockfd, void *buf, size_t len, int flags, int timeout) {
  844. #endif
  845. for(;;) {
  846. struct pollfd fd = {
  847. .fd = sockfd,
  848. .events = POLLIN,
  849. .revents = 0
  850. };
  851. errno = 0;
  852. int retval = poll(&fd, 1, timeout * 1000);
  853. if(retval == -1) {
  854. // failed
  855. if(errno == EINTR || errno == EAGAIN)
  856. continue;
  857. return -1;
  858. }
  859. if(!retval) {
  860. // timeout
  861. return 0;
  862. }
  863. if(fd.revents & POLLIN)
  864. break;
  865. }
  866. #ifdef ENABLE_HTTPS
  867. if (SSL_connection(ssl)) {
  868. return netdata_ssl_read(ssl, buf, len);
  869. }
  870. #endif
  871. internal_error(true, "%s(): calling recv()", __FUNCTION__ );
  872. return recv(sockfd, buf, len, flags);
  873. }
  874. #ifdef ENABLE_HTTPS
  875. ssize_t send_timeout(NETDATA_SSL *ssl,int sockfd, void *buf, size_t len, int flags, int timeout) {
  876. #else
  877. ssize_t send_timeout(int sockfd, void *buf, size_t len, int flags, int timeout) {
  878. #endif
  879. for(;;) {
  880. struct pollfd fd = {
  881. .fd = sockfd,
  882. .events = POLLOUT,
  883. .revents = 0
  884. };
  885. errno = 0;
  886. int retval = poll(&fd, 1, timeout * 1000);
  887. if(retval == -1) {
  888. // failed
  889. if(errno == EINTR || errno == EAGAIN)
  890. continue;
  891. return -1;
  892. }
  893. if(!retval) {
  894. // timeout
  895. return 0;
  896. }
  897. if(fd.revents & POLLOUT) break;
  898. }
  899. #ifdef ENABLE_HTTPS
  900. if(ssl->conn) {
  901. if (SSL_connection(ssl)) {
  902. return netdata_ssl_write(ssl, buf, len);
  903. }
  904. else {
  905. netdata_log_error("cannot write to SSL connection - connection is not ready.");
  906. return -1;
  907. }
  908. }
  909. #endif
  910. return send(sockfd, buf, len, flags);
  911. }
  912. // --------------------------------------------------------------------------------------------------------------------
  913. // accept4() replacement for systems that do not have one
  914. #ifndef HAVE_ACCEPT4
  915. int accept4(int sock, struct sockaddr *addr, socklen_t *addrlen, int flags) {
  916. int fd = accept(sock, addr, addrlen);
  917. int newflags = 0;
  918. if (fd < 0) return fd;
  919. if (flags & SOCK_NONBLOCK) {
  920. newflags |= O_NONBLOCK;
  921. flags &= ~SOCK_NONBLOCK;
  922. }
  923. #ifdef SOCK_CLOEXEC
  924. #ifdef O_CLOEXEC
  925. if (flags & SOCK_CLOEXEC) {
  926. newflags |= O_CLOEXEC;
  927. flags &= ~SOCK_CLOEXEC;
  928. }
  929. #endif
  930. #endif
  931. if (flags) {
  932. close(fd);
  933. errno = EINVAL;
  934. return -1;
  935. }
  936. if (fcntl(fd, F_SETFL, newflags) < 0) {
  937. int saved_errno = errno;
  938. close(fd);
  939. errno = saved_errno;
  940. return -1;
  941. }
  942. return fd;
  943. }
  944. #endif
  945. /*
  946. * ---------------------------------------------------------------------------------------------------------------------
  947. * connection_allowed() - if there is an access list then check the connection matches a pattern.
  948. * Numeric patterns are checked against the IP address first, only if they
  949. * do not match is the hostname resolved (reverse-DNS) and checked. If the
  950. * hostname matches then we perform forward DNS resolution to check the IP
  951. * is really associated with the DNS record. This call is repeatable: the
  952. * web server may check more refined matches against the connection. Will
  953. * update the client_host if uninitialized - ensure the hostsize is the number
  954. * of *writable* bytes (i.e. be aware of the strdup used to compact the pollinfo).
  955. */
  956. int connection_allowed(int fd, char *client_ip, char *client_host, size_t hostsize, SIMPLE_PATTERN *access_list,
  957. const char *patname, int allow_dns)
  958. {
  959. netdata_log_debug(D_LISTENER,"checking %s... (allow_dns=%d)", patname, allow_dns);
  960. if (!access_list)
  961. return 1;
  962. if (simple_pattern_matches(access_list, client_ip))
  963. return 1;
  964. // If the hostname is unresolved (and needed) then attempt the DNS lookups.
  965. //if (client_host[0]==0 && simple_pattern_is_potential_name(access_list))
  966. if (client_host[0]==0 && allow_dns)
  967. {
  968. struct sockaddr_storage sadr;
  969. socklen_t addrlen = sizeof(sadr);
  970. int err = getpeername(fd, (struct sockaddr*)&sadr, &addrlen);
  971. if (err != 0 ||
  972. (err = getnameinfo((struct sockaddr *)&sadr, addrlen, client_host, (socklen_t)hostsize,
  973. NULL, 0, NI_NAMEREQD)) != 0) {
  974. netdata_log_error("Incoming %s on '%s' does not match a numeric pattern, and host could not be resolved (err=%s)",
  975. patname, client_ip, gai_strerror(err));
  976. if (hostsize >= 8)
  977. strcpy(client_host,"UNKNOWN");
  978. return 0;
  979. }
  980. struct addrinfo *addr_infos = NULL;
  981. if (getaddrinfo(client_host, NULL, NULL, &addr_infos) !=0 ) {
  982. netdata_log_error("LISTENER: cannot validate hostname '%s' from '%s' by resolving it",
  983. client_host, client_ip);
  984. if (hostsize >= 8)
  985. strcpy(client_host,"UNKNOWN");
  986. return 0;
  987. }
  988. struct addrinfo *scan = addr_infos;
  989. int validated = 0;
  990. while (scan) {
  991. char address[INET6_ADDRSTRLEN];
  992. address[0] = 0;
  993. switch (scan->ai_addr->sa_family) {
  994. case AF_INET:
  995. inet_ntop(AF_INET, &((struct sockaddr_in*)(scan->ai_addr))->sin_addr, address, INET6_ADDRSTRLEN);
  996. break;
  997. case AF_INET6:
  998. inet_ntop(AF_INET6, &((struct sockaddr_in6*)(scan->ai_addr))->sin6_addr, address, INET6_ADDRSTRLEN);
  999. break;
  1000. }
  1001. netdata_log_debug(D_LISTENER, "Incoming ip %s rev-resolved onto %s, validating against forward-resolution %s",
  1002. client_ip, client_host, address);
  1003. if (!strcmp(client_ip, address)) {
  1004. validated = 1;
  1005. break;
  1006. }
  1007. scan = scan->ai_next;
  1008. }
  1009. if (!validated) {
  1010. netdata_log_error("LISTENER: Cannot validate '%s' as ip of '%s', not listed in DNS", client_ip, client_host);
  1011. if (hostsize >= 8)
  1012. strcpy(client_host,"UNKNOWN");
  1013. }
  1014. if (addr_infos!=NULL)
  1015. freeaddrinfo(addr_infos);
  1016. }
  1017. if (!simple_pattern_matches(access_list, client_host)) {
  1018. netdata_log_debug(D_LISTENER, "Incoming connection on '%s' (%s) does not match allowed pattern for %s",
  1019. client_ip, client_host, patname);
  1020. return 0;
  1021. }
  1022. return 1;
  1023. }
  1024. // --------------------------------------------------------------------------------------------------------------------
  1025. // accept_socket() - accept a socket and store client IP and port
  1026. int accept_socket(int fd, int flags, char *client_ip, size_t ipsize, char *client_port, size_t portsize,
  1027. char *client_host, size_t hostsize, SIMPLE_PATTERN *access_list, int allow_dns) {
  1028. struct sockaddr_storage sadr;
  1029. socklen_t addrlen = sizeof(sadr);
  1030. int nfd = accept4(fd, (struct sockaddr *)&sadr, &addrlen, flags);
  1031. if (likely(nfd >= 0)) {
  1032. if (getnameinfo((struct sockaddr *)&sadr, addrlen, client_ip, (socklen_t)ipsize,
  1033. client_port, (socklen_t)portsize, NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
  1034. netdata_log_error("LISTENER: cannot getnameinfo() on received client connection.");
  1035. strncpyz(client_ip, "UNKNOWN", ipsize);
  1036. strncpyz(client_port, "UNKNOWN", portsize);
  1037. }
  1038. if (!strcmp(client_ip, "127.0.0.1") || !strcmp(client_ip, "::1")) {
  1039. strncpyz(client_ip, "localhost", ipsize);
  1040. }
  1041. #ifdef __FreeBSD__
  1042. if(((struct sockaddr *)&sadr)->sa_family == AF_LOCAL)
  1043. strncpyz(client_ip, "localhost", ipsize);
  1044. #endif
  1045. client_ip[ipsize - 1] = '\0';
  1046. client_port[portsize - 1] = '\0';
  1047. switch (((struct sockaddr *)&sadr)->sa_family) {
  1048. case AF_UNIX:
  1049. netdata_log_debug(D_LISTENER, "New UNIX domain web client from %s on socket %d.", client_ip, fd);
  1050. // set the port - certain versions of libc return garbage on unix sockets
  1051. strncpyz(client_port, "UNIX", portsize);
  1052. break;
  1053. case AF_INET:
  1054. netdata_log_debug(D_LISTENER, "New IPv4 web client from %s port %s on socket %d.", client_ip, client_port, fd);
  1055. break;
  1056. case AF_INET6:
  1057. if (strncmp(client_ip, "::ffff:", 7) == 0) {
  1058. memmove(client_ip, &client_ip[7], strlen(&client_ip[7]) + 1);
  1059. netdata_log_debug(D_LISTENER, "New IPv4 web client from %s port %s on socket %d.", client_ip, client_port, fd);
  1060. }
  1061. else
  1062. netdata_log_debug(D_LISTENER, "New IPv6 web client from %s port %s on socket %d.", client_ip, client_port, fd);
  1063. break;
  1064. default:
  1065. netdata_log_debug(D_LISTENER, "New UNKNOWN web client from %s port %s on socket %d.", client_ip, client_port, fd);
  1066. break;
  1067. }
  1068. if (!connection_allowed(nfd, client_ip, client_host, hostsize, access_list, "connection", allow_dns)) {
  1069. errno = 0;
  1070. netdata_log_error("Permission denied for client '%s', port '%s'", client_ip, client_port);
  1071. close(nfd);
  1072. nfd = -1;
  1073. errno = EPERM;
  1074. }
  1075. }
  1076. #ifdef HAVE_ACCEPT4
  1077. else if (errno == ENOSYS)
  1078. netdata_log_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 ...");
  1079. #endif
  1080. return nfd;
  1081. }
  1082. // --------------------------------------------------------------------------------------------------------------------
  1083. // poll() based listener
  1084. // this should be the fastest possible listener for up to 100 sockets
  1085. // above 100, an epoll() interface is needed on Linux
  1086. #define POLL_FDS_INCREASE_STEP 10
  1087. inline POLLINFO *poll_add_fd(POLLJOB *p
  1088. , int fd
  1089. , int socktype
  1090. , WEB_CLIENT_ACL port_acl
  1091. , uint32_t flags
  1092. , const char *client_ip
  1093. , const char *client_port
  1094. , const char *client_host
  1095. , void *(*add_callback)(POLLINFO * /*pi*/, short int * /*events*/, void * /*data*/)
  1096. , void (*del_callback)(POLLINFO * /*pi*/)
  1097. , int (*rcv_callback)(POLLINFO * /*pi*/, short int * /*events*/)
  1098. , int (*snd_callback)(POLLINFO * /*pi*/, short int * /*events*/)
  1099. , void *data
  1100. ) {
  1101. netdata_log_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);
  1102. if(unlikely(fd < 0)) return NULL;
  1103. //if(p->limit && p->used >= p->limit) {
  1104. // netdata_log_info("Max sockets limit reached (%zu sockets), dropping connection", p->used);
  1105. // close(fd);
  1106. // return NULL;
  1107. //}
  1108. if(unlikely(!p->first_free)) {
  1109. size_t new_slots = p->slots + POLL_FDS_INCREASE_STEP;
  1110. netdata_log_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);
  1111. p->fds = reallocz(p->fds, sizeof(struct pollfd) * new_slots);
  1112. p->inf = reallocz(p->inf, sizeof(POLLINFO) * new_slots);
  1113. // reset all the newly added slots
  1114. ssize_t i;
  1115. for(i = new_slots - 1; i >= (ssize_t)p->slots ; i--) {
  1116. netdata_log_debug(D_POLLFD, "POLLFD: ADD: resetting new slot %zd", i);
  1117. p->fds[i].fd = -1;
  1118. p->fds[i].events = 0;
  1119. p->fds[i].revents = 0;
  1120. p->inf[i].p = p;
  1121. p->inf[i].slot = (size_t)i;
  1122. p->inf[i].flags = 0;
  1123. p->inf[i].socktype = -1;
  1124. p->inf[i].port_acl = -1;
  1125. p->inf[i].client_ip = NULL;
  1126. p->inf[i].client_port = NULL;
  1127. p->inf[i].client_host = NULL;
  1128. p->inf[i].del_callback = p->del_callback;
  1129. p->inf[i].rcv_callback = p->rcv_callback;
  1130. p->inf[i].snd_callback = p->snd_callback;
  1131. p->inf[i].data = NULL;
  1132. // link them so that the first free will be earlier in the array
  1133. // (we loop decrementing i)
  1134. p->inf[i].next = p->first_free;
  1135. p->first_free = &p->inf[i];
  1136. }
  1137. p->slots = new_slots;
  1138. }
  1139. POLLINFO *pi = p->first_free;
  1140. p->first_free = p->first_free->next;
  1141. netdata_log_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);
  1142. struct pollfd *pf = &p->fds[pi->slot];
  1143. pf->fd = fd;
  1144. pf->events = POLLIN;
  1145. pf->revents = 0;
  1146. pi->fd = fd;
  1147. pi->p = p;
  1148. pi->socktype = socktype;
  1149. pi->port_acl = port_acl;
  1150. pi->flags = flags;
  1151. pi->next = NULL;
  1152. pi->client_ip = strdupz(client_ip);
  1153. pi->client_port = strdupz(client_port);
  1154. pi->client_host = strdupz(client_host);
  1155. pi->del_callback = del_callback;
  1156. pi->rcv_callback = rcv_callback;
  1157. pi->snd_callback = snd_callback;
  1158. pi->connected_t = now_boottime_sec();
  1159. pi->last_received_t = 0;
  1160. pi->last_sent_t = 0;
  1161. pi->last_sent_t = 0;
  1162. pi->recv_count = 0;
  1163. pi->send_count = 0;
  1164. netdata_thread_disable_cancelability();
  1165. p->used++;
  1166. if(unlikely(pi->slot > p->max))
  1167. p->max = pi->slot;
  1168. if(pi->flags & POLLINFO_FLAG_CLIENT_SOCKET) {
  1169. pi->data = add_callback(pi, &pf->events, data);
  1170. }
  1171. if(pi->flags & POLLINFO_FLAG_SERVER_SOCKET) {
  1172. p->min = pi->slot;
  1173. }
  1174. netdata_thread_enable_cancelability();
  1175. netdata_log_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);
  1176. return pi;
  1177. }
  1178. inline void poll_close_fd(POLLINFO *pi) {
  1179. POLLJOB *p = pi->p;
  1180. struct pollfd *pf = &p->fds[pi->slot];
  1181. netdata_log_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);
  1182. if(unlikely(pf->fd == -1)) return;
  1183. netdata_thread_disable_cancelability();
  1184. if(pi->flags & POLLINFO_FLAG_CLIENT_SOCKET) {
  1185. pi->del_callback(pi);
  1186. if(likely(!(pi->flags & POLLINFO_FLAG_DONT_CLOSE))) {
  1187. if(close(pf->fd) == -1)
  1188. netdata_log_error("Failed to close() poll_events() socket %d", pf->fd);
  1189. }
  1190. }
  1191. pf->fd = -1;
  1192. pf->events = 0;
  1193. pf->revents = 0;
  1194. pi->fd = -1;
  1195. pi->socktype = -1;
  1196. pi->flags = 0;
  1197. pi->data = NULL;
  1198. pi->del_callback = NULL;
  1199. pi->rcv_callback = NULL;
  1200. pi->snd_callback = NULL;
  1201. freez(pi->client_ip);
  1202. pi->client_ip = NULL;
  1203. freez(pi->client_port);
  1204. pi->client_port = NULL;
  1205. freez(pi->client_host);
  1206. pi->client_host = NULL;
  1207. pi->next = p->first_free;
  1208. p->first_free = pi;
  1209. p->used--;
  1210. if(unlikely(p->max == pi->slot)) {
  1211. p->max = p->min;
  1212. ssize_t i;
  1213. for(i = (ssize_t)pi->slot; i > (ssize_t)p->min ;i--) {
  1214. if (unlikely(p->fds[i].fd != -1)) {
  1215. p->max = (size_t)i;
  1216. break;
  1217. }
  1218. }
  1219. }
  1220. netdata_thread_enable_cancelability();
  1221. netdata_log_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);
  1222. }
  1223. void *poll_default_add_callback(POLLINFO *pi, short int *events, void *data) {
  1224. (void)pi;
  1225. (void)events;
  1226. (void)data;
  1227. // netdata_log_error("POLLFD: internal error: poll_default_add_callback() called");
  1228. return NULL;
  1229. }
  1230. void poll_default_del_callback(POLLINFO *pi) {
  1231. if(pi->data)
  1232. netdata_log_error("POLLFD: internal error: del_callback_default() called with data pointer - possible memory leak");
  1233. }
  1234. int poll_default_rcv_callback(POLLINFO *pi, short int *events) {
  1235. *events |= POLLIN;
  1236. char buffer[1024 + 1];
  1237. ssize_t rc;
  1238. do {
  1239. rc = recv(pi->fd, buffer, 1024, MSG_DONTWAIT);
  1240. if (rc < 0) {
  1241. // read failed
  1242. if (errno != EWOULDBLOCK && errno != EAGAIN) {
  1243. netdata_log_error("POLLFD: poll_default_rcv_callback(): recv() failed with %zd.", rc);
  1244. return -1;
  1245. }
  1246. } else if (rc) {
  1247. // data received
  1248. netdata_log_info("POLLFD: internal error: poll_default_rcv_callback() is discarding %zd bytes received on socket %d", rc, pi->fd);
  1249. }
  1250. } while (rc != -1);
  1251. return 0;
  1252. }
  1253. int poll_default_snd_callback(POLLINFO *pi, short int *events) {
  1254. *events &= ~POLLOUT;
  1255. netdata_log_info("POLLFD: internal error: poll_default_snd_callback(): nothing to send on socket %d", pi->fd);
  1256. return 0;
  1257. }
  1258. void poll_default_tmr_callback(void *timer_data) {
  1259. (void)timer_data;
  1260. }
  1261. static void poll_events_cleanup(void *data) {
  1262. POLLJOB *p = (POLLJOB *)data;
  1263. size_t i;
  1264. for(i = 0 ; i <= p->max ; i++) {
  1265. POLLINFO *pi = &p->inf[i];
  1266. poll_close_fd(pi);
  1267. }
  1268. freez(p->fds);
  1269. freez(p->inf);
  1270. }
  1271. static int poll_process_error(POLLINFO *pi, struct pollfd *pf, short int revents) {
  1272. netdata_log_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"
  1273. , revents & POLLERR ? "POLLERR" : ""
  1274. , revents & POLLHUP ? "POLLHUP" : ""
  1275. , revents & POLLNVAL ? "POLLNVAL" : ""
  1276. , pi->slot
  1277. , pi->fd
  1278. , pi->client_ip ? pi->client_ip : "<undefined-ip>"
  1279. , pi->client_port ? pi->client_port : "<undefined-port>"
  1280. , pf->events & POLLIN ? "POLLIN" : "", pf->events & POLLOUT ? "POLLOUT" : "", pf->events & POLLPRI ? "POLLPRI" : ""
  1281. , revents & POLLIN ? "POLLIN" : "", revents & POLLOUT ? "POLLOUT" : "", revents & POLLPRI ? "POLLPRI" : ""
  1282. );
  1283. pf->events = 0;
  1284. poll_close_fd(pi);
  1285. return 1;
  1286. }
  1287. static inline int poll_process_send(POLLJOB *p, POLLINFO *pi, struct pollfd *pf, time_t now) {
  1288. pi->last_sent_t = now;
  1289. pi->send_count++;
  1290. netdata_log_debug(D_POLLFD, "POLLFD: LISTENER: sending data to socket on 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 (unlikely(pi->snd_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_tcp_read(POLLJOB *p, POLLINFO *pi, struct pollfd *pf, time_t now) {
  1302. pi->last_received_t = now;
  1303. pi->recv_count++;
  1304. netdata_log_debug(D_POLLFD, "POLLFD: LISTENER: reading data from TCP client slot %zu (fd %d)", pi->slot, pf->fd);
  1305. pf->events = 0;
  1306. // remember the slot, in case we need to close it later
  1307. // the callback may manipulate the socket list and our pf and pi pointers may be invalid after that call
  1308. size_t slot = pi->slot;
  1309. if (pi->rcv_callback(pi, &pf->events) == -1)
  1310. poll_close_fd(&p->inf[slot]);
  1311. // IMPORTANT:
  1312. // pf and pi may be invalid below this point, they may have been reallocated.
  1313. return 1;
  1314. }
  1315. static inline int poll_process_udp_read(POLLINFO *pi, struct pollfd *pf, time_t now __maybe_unused) {
  1316. pi->last_received_t = now;
  1317. pi->recv_count++;
  1318. netdata_log_debug(D_POLLFD, "POLLFD: LISTENER: reading data from UDP slot %zu (fd %d)", pi->slot, pf->fd);
  1319. // TODO: access_list is not applied to UDP
  1320. // but checking the access list on every UDP packet will destroy
  1321. // performance, especially for statsd.
  1322. pf->events = 0;
  1323. if(pi->rcv_callback(pi, &pf->events) == -1)
  1324. return 0;
  1325. // IMPORTANT:
  1326. // pf and pi may be invalid below this point, they may have been reallocated.
  1327. return 1;
  1328. }
  1329. static int poll_process_new_tcp_connection(POLLJOB *p, POLLINFO *pi, struct pollfd *pf, time_t now) {
  1330. pi->last_received_t = now;
  1331. pi->recv_count++;
  1332. netdata_log_debug(D_POLLFD, "POLLFD: LISTENER: accepting connections from slot %zu (fd %d)", pi->slot, pf->fd);
  1333. char client_ip[INET6_ADDRSTRLEN] = "";
  1334. char client_port[NI_MAXSERV] = "";
  1335. char client_host[NI_MAXHOST] = "";
  1336. netdata_log_debug(D_POLLFD, "POLLFD: LISTENER: calling accept4() slot %zu (fd %d)", pi->slot, pf->fd);
  1337. int nfd = accept_socket(
  1338. pf->fd,SOCK_NONBLOCK,
  1339. client_ip, INET6_ADDRSTRLEN, client_port,NI_MAXSERV, client_host, NI_MAXHOST,
  1340. p->access_list, p->allow_dns
  1341. );
  1342. if (unlikely(nfd < 0)) {
  1343. // accept failed
  1344. netdata_log_debug(D_POLLFD, "POLLFD: LISTENER: accept4() slot %zu (fd %d) failed.", pi->slot, pf->fd);
  1345. if(unlikely(errno == EMFILE)) {
  1346. error_limit_static_global_var(erl, 10, 1000);
  1347. error_limit(&erl, "POLLFD: LISTENER: too many open files - used by this thread %zu, max for this thread %zu",
  1348. p->used, p->limit);
  1349. }
  1350. else if(unlikely(errno != EWOULDBLOCK && errno != EAGAIN))
  1351. netdata_log_error("POLLFD: LISTENER: accept() failed.");
  1352. }
  1353. else {
  1354. // accept ok
  1355. poll_add_fd(p
  1356. , nfd
  1357. , SOCK_STREAM
  1358. , pi->port_acl
  1359. , POLLINFO_FLAG_CLIENT_SOCKET
  1360. , client_ip
  1361. , client_port
  1362. , client_host
  1363. , p->add_callback
  1364. , p->del_callback
  1365. , p->rcv_callback
  1366. , p->snd_callback
  1367. , NULL
  1368. );
  1369. // IMPORTANT:
  1370. // pf and pi may be invalid below this point, they may have been reallocated.
  1371. return 1;
  1372. }
  1373. return 0;
  1374. }
  1375. void poll_events(LISTEN_SOCKETS *sockets
  1376. , void *(*add_callback)(POLLINFO * /*pi*/, short int * /*events*/, void * /*data*/)
  1377. , void (*del_callback)(POLLINFO * /*pi*/)
  1378. , int (*rcv_callback)(POLLINFO * /*pi*/, short int * /*events*/)
  1379. , int (*snd_callback)(POLLINFO * /*pi*/, short int * /*events*/)
  1380. , void (*tmr_callback)(void * /*timer_data*/)
  1381. , bool (*check_to_stop_callback)(void)
  1382. , SIMPLE_PATTERN *access_list
  1383. , int allow_dns
  1384. , void *data
  1385. , time_t tcp_request_timeout_seconds
  1386. , time_t tcp_idle_timeout_seconds
  1387. , time_t timer_milliseconds
  1388. , void *timer_data
  1389. , size_t max_tcp_sockets
  1390. ) {
  1391. if(!sockets || !sockets->opened) {
  1392. netdata_log_error("POLLFD: internal error: no listening sockets are opened");
  1393. return;
  1394. }
  1395. if(timer_milliseconds <= 0) timer_milliseconds = 0;
  1396. int retval;
  1397. POLLJOB p = {
  1398. .slots = 0,
  1399. .used = 0,
  1400. .max = 0,
  1401. .limit = max_tcp_sockets,
  1402. .fds = NULL,
  1403. .inf = NULL,
  1404. .first_free = NULL,
  1405. .complete_request_timeout = tcp_request_timeout_seconds,
  1406. .idle_timeout = tcp_idle_timeout_seconds,
  1407. .checks_every = (tcp_idle_timeout_seconds / 3) + 1,
  1408. .access_list = access_list,
  1409. .allow_dns = allow_dns,
  1410. .timer_milliseconds = timer_milliseconds,
  1411. .timer_data = timer_data,
  1412. .add_callback = add_callback?add_callback:poll_default_add_callback,
  1413. .del_callback = del_callback?del_callback:poll_default_del_callback,
  1414. .rcv_callback = rcv_callback?rcv_callback:poll_default_rcv_callback,
  1415. .snd_callback = snd_callback?snd_callback:poll_default_snd_callback,
  1416. .tmr_callback = tmr_callback?tmr_callback:poll_default_tmr_callback
  1417. };
  1418. size_t i;
  1419. for(i = 0; i < sockets->opened ;i++) {
  1420. POLLINFO *pi = poll_add_fd(&p
  1421. , sockets->fds[i]
  1422. , sockets->fds_types[i]
  1423. , sockets->fds_acl_flags[i]
  1424. , POLLINFO_FLAG_SERVER_SOCKET
  1425. , (sockets->fds_names[i])?sockets->fds_names[i]:"UNKNOWN"
  1426. , ""
  1427. , ""
  1428. , p.add_callback
  1429. , p.del_callback
  1430. , p.rcv_callback
  1431. , p.snd_callback
  1432. , NULL
  1433. );
  1434. pi->data = data;
  1435. netdata_log_info("POLLFD: LISTENER: listening on '%s'", (sockets->fds_names[i])?sockets->fds_names[i]:"UNKNOWN");
  1436. }
  1437. int listen_sockets_active = 1;
  1438. int timeout_ms = 1000; // in milliseconds
  1439. time_t last_check = now_boottime_sec();
  1440. usec_t timer_usec = timer_milliseconds * USEC_PER_MS;
  1441. usec_t now_usec = 0, next_timer_usec = 0, last_timer_usec = 0;
  1442. (void)last_timer_usec;
  1443. if(unlikely(timer_usec)) {
  1444. now_usec = now_boottime_usec();
  1445. next_timer_usec = now_usec - (now_usec % timer_usec) + timer_usec;
  1446. }
  1447. netdata_thread_cleanup_push(poll_events_cleanup, &p);
  1448. while(!check_to_stop_callback()) {
  1449. if(unlikely(timer_usec)) {
  1450. now_usec = now_boottime_usec();
  1451. if(unlikely(timer_usec && now_usec >= next_timer_usec)) {
  1452. netdata_log_debug(D_POLLFD, "Calling timer callback after %zu usec", (size_t)(now_usec - last_timer_usec));
  1453. last_timer_usec = now_usec;
  1454. p.tmr_callback(p.timer_data);
  1455. now_usec = now_boottime_usec();
  1456. next_timer_usec = now_usec - (now_usec % timer_usec) + timer_usec;
  1457. }
  1458. usec_t dt_usec = next_timer_usec - now_usec;
  1459. if(dt_usec < 1000 * USEC_PER_MS)
  1460. timeout_ms = 1000;
  1461. else
  1462. timeout_ms = (int)(dt_usec / USEC_PER_MS);
  1463. }
  1464. // enable or disable the TCP listening sockets, based on the current number of sockets used and the limit set
  1465. if((listen_sockets_active && (p.limit && p.used >= p.limit)) || (!listen_sockets_active && (!p.limit || p.used < p.limit))) {
  1466. listen_sockets_active = !listen_sockets_active;
  1467. netdata_log_info("%s listening sockets (used TCP sockets %zu, max allowed for this worker %zu)", (listen_sockets_active)?"ENABLING":"DISABLING", p.used, p.limit);
  1468. for (i = 0; i <= p.max; i++) {
  1469. if(p.inf[i].flags & POLLINFO_FLAG_SERVER_SOCKET && p.inf[i].socktype == SOCK_STREAM) {
  1470. p.fds[i].events = (short int) ((listen_sockets_active) ? POLLIN : 0);
  1471. }
  1472. }
  1473. }
  1474. netdata_log_debug(D_POLLFD, "POLLFD: LISTENER: Waiting on %zu sockets for %zu ms...", p.max + 1, (size_t)timeout_ms);
  1475. retval = poll(p.fds, p.max + 1, timeout_ms);
  1476. time_t now = now_boottime_sec();
  1477. if(unlikely(retval == -1)) {
  1478. netdata_log_error("POLLFD: LISTENER: poll() failed while waiting on %zu sockets.", p.max + 1);
  1479. break;
  1480. }
  1481. else if(unlikely(!retval)) {
  1482. netdata_log_debug(D_POLLFD, "POLLFD: LISTENER: poll() timeout.");
  1483. }
  1484. else {
  1485. POLLINFO *pi;
  1486. struct pollfd *pf;
  1487. size_t idx, processed = 0;
  1488. short int revents;
  1489. // keep fast lookup arrays per function
  1490. // to avoid looping through the entire list every time
  1491. size_t sends[p.max + 1], sends_max = 0;
  1492. size_t reads[p.max + 1], reads_max = 0;
  1493. size_t conns[p.max + 1], conns_max = 0;
  1494. size_t udprd[p.max + 1], udprd_max = 0;
  1495. for (i = 0; i <= p.max; i++) {
  1496. pi = &p.inf[i];
  1497. pf = &p.fds[i];
  1498. revents = pf->revents;
  1499. if(unlikely(revents == 0 || pf->fd == -1))
  1500. continue;
  1501. if (unlikely(revents & (POLLERR|POLLHUP|POLLNVAL))) {
  1502. // something is wrong to one of our sockets
  1503. pf->revents = 0;
  1504. processed += poll_process_error(pi, pf, revents);
  1505. }
  1506. else if (likely(revents & POLLOUT)) {
  1507. // a client is ready to receive data
  1508. sends[sends_max++] = i;
  1509. }
  1510. else if (likely(revents & (POLLIN|POLLPRI))) {
  1511. if (pi->flags & POLLINFO_FLAG_CLIENT_SOCKET) {
  1512. // a client sent data to us
  1513. reads[reads_max++] = i;
  1514. }
  1515. else if (pi->flags & POLLINFO_FLAG_SERVER_SOCKET) {
  1516. // something is coming to our server sockets
  1517. if(pi->socktype == SOCK_DGRAM) {
  1518. // UDP receive, directly on our listening socket
  1519. udprd[udprd_max++] = i;
  1520. }
  1521. else if(pi->socktype == SOCK_STREAM) {
  1522. // new TCP connection
  1523. conns[conns_max++] = i;
  1524. }
  1525. else
  1526. netdata_log_error("POLLFD: LISTENER: server slot %zu (fd %d) connection from %s port %s using unhandled socket type %d."
  1527. , i
  1528. , pi->fd
  1529. , pi->client_ip ? pi->client_ip : "<undefined-ip>"
  1530. , pi->client_port ? pi->client_port : "<undefined-port>"
  1531. , pi->socktype
  1532. );
  1533. }
  1534. else
  1535. netdata_log_error("POLLFD: LISTENER: client slot %zu (fd %d) data from %s port %s using flags %08X is neither client nor server."
  1536. , i
  1537. , pi->fd
  1538. , pi->client_ip ? pi->client_ip : "<undefined-ip>"
  1539. , pi->client_port ? pi->client_port : "<undefined-port>"
  1540. , pi->flags
  1541. );
  1542. }
  1543. else
  1544. netdata_log_error("POLLFD: LISTENER: socket slot %zu (fd %d) client %s port %s unhandled event id %d."
  1545. , i
  1546. , pi->fd
  1547. , pi->client_ip ? pi->client_ip : "<undefined-ip>"
  1548. , pi->client_port ? pi->client_port : "<undefined-port>"
  1549. , revents
  1550. );
  1551. }
  1552. // process sends
  1553. for (idx = 0; idx < sends_max; idx++) {
  1554. i = sends[idx];
  1555. pi = &p.inf[i];
  1556. pf = &p.fds[i];
  1557. pf->revents = 0;
  1558. processed += poll_process_send(&p, pi, pf, now);
  1559. }
  1560. // process UDP reads
  1561. for (idx = 0; idx < udprd_max; idx++) {
  1562. i = udprd[idx];
  1563. pi = &p.inf[i];
  1564. pf = &p.fds[i];
  1565. pf->revents = 0;
  1566. processed += poll_process_udp_read(pi, pf, now);
  1567. }
  1568. // process TCP reads
  1569. for (idx = 0; idx < reads_max; idx++) {
  1570. i = reads[idx];
  1571. pi = &p.inf[i];
  1572. pf = &p.fds[i];
  1573. pf->revents = 0;
  1574. processed += poll_process_tcp_read(&p, pi, pf, now);
  1575. }
  1576. if(!processed && (!p.limit || p.used < p.limit)) {
  1577. // nothing processed above (rcv, snd) and we have room for another TCP connection
  1578. // so, accept one TCP connection
  1579. for (idx = 0; idx < conns_max; idx++) {
  1580. i = conns[idx];
  1581. pi = &p.inf[i];
  1582. pf = &p.fds[i];
  1583. pf->revents = 0;
  1584. if (poll_process_new_tcp_connection(&p, pi, pf, now))
  1585. break;
  1586. }
  1587. }
  1588. }
  1589. if(unlikely(p.checks_every > 0 && now - last_check > p.checks_every)) {
  1590. last_check = now;
  1591. // cleanup old sockets
  1592. for(i = 0; i <= p.max; i++) {
  1593. POLLINFO *pi = &p.inf[i];
  1594. if(likely(pi->flags & POLLINFO_FLAG_CLIENT_SOCKET)) {
  1595. if (unlikely(pi->send_count == 0 && p.complete_request_timeout > 0 && (now - pi->connected_t) >= p.complete_request_timeout)) {
  1596. netdata_log_info("POLLFD: LISTENER: client slot %zu (fd %d) from %s port %s has not sent a complete request in %zu seconds - closing it. "
  1597. , i
  1598. , pi->fd
  1599. , pi->client_ip ? pi->client_ip : "<undefined-ip>"
  1600. , pi->client_port ? pi->client_port : "<undefined-port>"
  1601. , (size_t) p.complete_request_timeout
  1602. );
  1603. poll_close_fd(pi);
  1604. }
  1605. 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 )) {
  1606. netdata_log_info("POLLFD: LISTENER: client slot %zu (fd %d) from %s port %s is idle for more than %zu seconds - closing it. "
  1607. , i
  1608. , pi->fd
  1609. , pi->client_ip ? pi->client_ip : "<undefined-ip>"
  1610. , pi->client_port ? pi->client_port : "<undefined-port>"
  1611. , (size_t) p.idle_timeout
  1612. );
  1613. poll_close_fd(pi);
  1614. }
  1615. }
  1616. }
  1617. }
  1618. }
  1619. netdata_thread_cleanup_pop(1);
  1620. netdata_log_debug(D_POLLFD, "POLLFD: LISTENER: cleanup completed");
  1621. }