socket.c 50 KB

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