socket.c 54 KB

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