socket.c 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530
  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. (void)pSadrIn6;
  478. 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",
  479. pSadrIn6->sin6_family,
  480. AF_INET,
  481. AF_INET6,
  482. hostBfr,
  483. servBfr,
  484. pSadrIn6->sin6_flowinfo,
  485. pSadrIn6->sin6_scope_id);
  486. break;
  487. }
  488. default: {
  489. debug(D_CONNECT_TO, "Unknown protocol family %d.", ai->ai_family);
  490. continue;
  491. }
  492. }
  493. fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
  494. if(fd != -1) {
  495. if(timeout) {
  496. if(setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (char *) timeout, sizeof(struct timeval)) < 0)
  497. error("Failed to set timeout on the socket to ip '%s' port '%s'", hostBfr, servBfr);
  498. }
  499. errno = 0;
  500. if(connect(fd, ai->ai_addr, ai->ai_addrlen) < 0) {
  501. if(errno == EALREADY || errno == EINPROGRESS) {
  502. info("Waiting for connection to ip %s port %s to be established", hostBfr, servBfr);
  503. fd_set fds;
  504. FD_ZERO(&fds);
  505. FD_SET(0, &fds);
  506. int rc = select (1, NULL, &fds, NULL, timeout);
  507. if(rc > 0 && FD_ISSET(fd, &fds)) {
  508. info("connect() to ip %s port %s completed successfully", hostBfr, servBfr);
  509. }
  510. else if(rc == -1) {
  511. error("Failed to connect to '%s', port '%s'. select() returned %d", hostBfr, servBfr, rc);
  512. close(fd);
  513. fd = -1;
  514. }
  515. else {
  516. error("Timed out while connecting to '%s', port '%s'. select() returned %d", hostBfr, servBfr, rc);
  517. close(fd);
  518. fd = -1;
  519. }
  520. }
  521. else {
  522. error("Failed to connect to '%s', port '%s'", hostBfr, servBfr);
  523. close(fd);
  524. fd = -1;
  525. }
  526. }
  527. if(fd != -1)
  528. debug(D_CONNECT_TO, "Connected to '%s' on port '%s'.", hostBfr, servBfr);
  529. }
  530. }
  531. freeaddrinfo(ai_head);
  532. return fd;
  533. }
  534. // connect_to_this()
  535. //
  536. // definition format:
  537. //
  538. // [PROTOCOL:]IP[%INTERFACE][:PORT]
  539. //
  540. // PROTOCOL = tcp or udp
  541. // IP = IPv4 or IPv6 IP or hostname, optionally enclosed in [] (required for IPv6)
  542. // INTERFACE = for IPv6 only, the network interface to use
  543. // PORT = port number or service name
  544. int connect_to_this(const char *definition, int default_port, struct timeval *timeout) {
  545. char buffer[strlen(definition) + 1];
  546. strcpy(buffer, definition);
  547. char default_service[10 + 1];
  548. snprintfz(default_service, 10, "%d", default_port);
  549. char *host = buffer, *service = default_service, *interface = "";
  550. int protocol = IPPROTO_TCP, socktype = SOCK_STREAM;
  551. uint32_t scope_id = 0;
  552. if(strncmp(host, "tcp:", 4) == 0) {
  553. host += 4;
  554. protocol = IPPROTO_TCP;
  555. socktype = SOCK_STREAM;
  556. }
  557. else if(strncmp(host, "udp:", 4) == 0) {
  558. host += 4;
  559. protocol = IPPROTO_UDP;
  560. socktype = SOCK_DGRAM;
  561. }
  562. else if(strncmp(host, "unix:", 5) == 0) {
  563. char *path = host + 5;
  564. return connect_to_unix(path, timeout);
  565. }
  566. char *e = host;
  567. if(*e == '[') {
  568. e = ++host;
  569. while(*e && *e != ']') e++;
  570. if(*e == ']') {
  571. *e = '\0';
  572. e++;
  573. }
  574. }
  575. else {
  576. while(*e && *e != ':' && *e != '%') e++;
  577. }
  578. if(*e == '%') {
  579. *e = '\0';
  580. e++;
  581. interface = e;
  582. while(*e && *e != ':') e++;
  583. }
  584. if(*e == ':') {
  585. *e = '\0';
  586. e++;
  587. service = e;
  588. }
  589. 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);
  590. if(!*host) {
  591. error("Definition '%s' does not specify a host.", definition);
  592. return -1;
  593. }
  594. if(*interface) {
  595. scope_id = if_nametoindex(interface);
  596. if(!scope_id)
  597. error("Cannot find a network interface named '%s'. Continuing with limiting the network interface", interface);
  598. }
  599. if(!*service)
  600. service = default_service;
  601. return connect_to_this_ip46(protocol, socktype, host, scope_id, service, timeout);
  602. }
  603. 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) {
  604. int sock = -1;
  605. const char *s = destination;
  606. while(*s) {
  607. const char *e = s;
  608. // skip separators, moving both s(tart) and e(nd)
  609. while(isspace(*e) || *e == ',') s = ++e;
  610. // move e(nd) to the first separator
  611. while(*e && !isspace(*e) && *e != ',') e++;
  612. // is there anything?
  613. if(!*s || s == e) break;
  614. char buf[e - s + 1];
  615. strncpyz(buf, s, e - s);
  616. if(reconnects_counter) *reconnects_counter += 1;
  617. sock = connect_to_this(buf, default_port, timeout);
  618. if(sock != -1) {
  619. if(connected_to && connected_to_size) {
  620. strncpy(connected_to, buf, connected_to_size);
  621. connected_to[connected_to_size - 1] = '\0';
  622. }
  623. break;
  624. }
  625. s = e;
  626. }
  627. return sock;
  628. }
  629. // --------------------------------------------------------------------------------------------------------------------
  630. // helpers to send/receive data in one call, in blocking mode, with a timeout
  631. ssize_t recv_timeout(int sockfd, void *buf, size_t len, int flags, int timeout) {
  632. for(;;) {
  633. struct pollfd fd = {
  634. .fd = sockfd,
  635. .events = POLLIN,
  636. .revents = 0
  637. };
  638. errno = 0;
  639. int retval = poll(&fd, 1, timeout * 1000);
  640. if(retval == -1) {
  641. // failed
  642. if(errno == EINTR || errno == EAGAIN)
  643. continue;
  644. return -1;
  645. }
  646. if(!retval) {
  647. // timeout
  648. return 0;
  649. }
  650. if(fd.events & POLLIN) break;
  651. }
  652. return recv(sockfd, buf, len, flags);
  653. }
  654. ssize_t send_timeout(int sockfd, void *buf, size_t len, int flags, int timeout) {
  655. for(;;) {
  656. struct pollfd fd = {
  657. .fd = sockfd,
  658. .events = POLLOUT,
  659. .revents = 0
  660. };
  661. errno = 0;
  662. int retval = poll(&fd, 1, timeout * 1000);
  663. if(retval == -1) {
  664. // failed
  665. if(errno == EINTR || errno == EAGAIN)
  666. continue;
  667. return -1;
  668. }
  669. if(!retval) {
  670. // timeout
  671. return 0;
  672. }
  673. if(fd.events & POLLOUT) break;
  674. }
  675. return send(sockfd, buf, len, flags);
  676. }
  677. // --------------------------------------------------------------------------------------------------------------------
  678. // accept4() replacement for systems that do not have one
  679. #ifndef HAVE_ACCEPT4
  680. int accept4(int sock, struct sockaddr *addr, socklen_t *addrlen, int flags) {
  681. int fd = accept(sock, addr, addrlen);
  682. int newflags = 0;
  683. if (fd < 0) return fd;
  684. if (flags & SOCK_NONBLOCK) {
  685. newflags |= O_NONBLOCK;
  686. flags &= ~SOCK_NONBLOCK;
  687. }
  688. #ifdef SOCK_CLOEXEC
  689. #ifdef O_CLOEXEC
  690. if (flags & SOCK_CLOEXEC) {
  691. newflags |= O_CLOEXEC;
  692. flags &= ~SOCK_CLOEXEC;
  693. }
  694. #endif
  695. #endif
  696. if (flags) {
  697. close(fd);
  698. errno = EINVAL;
  699. return -1;
  700. }
  701. if (fcntl(fd, F_SETFL, newflags) < 0) {
  702. int saved_errno = errno;
  703. close(fd);
  704. errno = saved_errno;
  705. return -1;
  706. }
  707. return fd;
  708. }
  709. #endif
  710. // --------------------------------------------------------------------------------------------------------------------
  711. // accept_socket() - accept a socket and store client IP and port
  712. int accept_socket(int fd, int flags, char *client_ip, size_t ipsize, char *client_port, size_t portsize, SIMPLE_PATTERN *access_list) {
  713. struct sockaddr_storage sadr;
  714. socklen_t addrlen = sizeof(sadr);
  715. int nfd = accept4(fd, (struct sockaddr *)&sadr, &addrlen, flags);
  716. if (likely(nfd >= 0)) {
  717. if (getnameinfo((struct sockaddr *)&sadr, addrlen, client_ip, (socklen_t)ipsize, client_port, (socklen_t)portsize, NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
  718. error("LISTENER: cannot getnameinfo() on received client connection.");
  719. strncpyz(client_ip, "UNKNOWN", ipsize - 1);
  720. strncpyz(client_port, "UNKNOWN", portsize - 1);
  721. }
  722. client_ip[ipsize - 1] = '\0';
  723. client_port[portsize - 1] = '\0';
  724. switch (((struct sockaddr *)&sadr)->sa_family) {
  725. case AF_UNIX:
  726. debug(D_LISTENER, "New UNIX domain web client from %s on socket %d.", client_ip, fd);
  727. // set the port - certain versions of libc return garbage on unix sockets
  728. strncpy(client_port, "UNIX", portsize);
  729. client_port[portsize - 1] = '\0';
  730. break;
  731. case AF_INET:
  732. debug(D_LISTENER, "New IPv4 web client from %s port %s on socket %d.", client_ip, client_port, fd);
  733. break;
  734. case AF_INET6:
  735. if (strncmp(client_ip, "::ffff:", 7) == 0) {
  736. memmove(client_ip, &client_ip[7], strlen(&client_ip[7]) + 1);
  737. debug(D_LISTENER, "New IPv4 web client from %s port %s on socket %d.", client_ip, client_port, fd);
  738. }
  739. else
  740. debug(D_LISTENER, "New IPv6 web client from %s port %s on socket %d.", client_ip, client_port, fd);
  741. break;
  742. default:
  743. debug(D_LISTENER, "New UNKNOWN web client from %s port %s on socket %d.", client_ip, client_port, fd);
  744. break;
  745. }
  746. if(access_list) {
  747. if(!strcmp(client_ip, "127.0.0.1") || !strcmp(client_ip, "::1")) {
  748. strncpy(client_ip, "localhost", ipsize);
  749. client_ip[ipsize - 1] = '\0';
  750. }
  751. if(unlikely(!simple_pattern_matches(access_list, client_ip))) {
  752. errno = 0;
  753. debug(D_LISTENER, "Permission denied for client '%s', port '%s'", client_ip, client_port);
  754. error("DENIED ACCESS to client '%s'", client_ip);
  755. close(nfd);
  756. nfd = -1;
  757. errno = EPERM;
  758. }
  759. }
  760. }
  761. #ifdef HAVE_ACCEPT4
  762. else if(errno == ENOSYS)
  763. 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 ...");
  764. #endif
  765. return nfd;
  766. }
  767. // --------------------------------------------------------------------------------------------------------------------
  768. // poll() based listener
  769. // this should be the fastest possible listener for up to 100 sockets
  770. // above 100, an epoll() interface is needed on Linux
  771. #define POLL_FDS_INCREASE_STEP 10
  772. inline POLLINFO *poll_add_fd(POLLJOB *p
  773. , int fd
  774. , int socktype
  775. , uint32_t flags
  776. , const char *client_ip
  777. , const char *client_port
  778. , void *(*add_callback)(POLLINFO * /*pi*/, short int * /*events*/, void * /*data*/)
  779. , void (*del_callback)(POLLINFO * /*pi*/)
  780. , int (*rcv_callback)(POLLINFO * /*pi*/, short int * /*events*/)
  781. , int (*snd_callback)(POLLINFO * /*pi*/, short int * /*events*/)
  782. , void *data
  783. ) {
  784. 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);
  785. if(unlikely(fd < 0)) return NULL;
  786. //if(p->limit && p->used >= p->limit) {
  787. // info("Max sockets limit reached (%zu sockets), dropping connection", p->used);
  788. // close(fd);
  789. // return NULL;
  790. //}
  791. if(unlikely(!p->first_free)) {
  792. size_t new_slots = p->slots + POLL_FDS_INCREASE_STEP;
  793. 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);
  794. p->fds = reallocz(p->fds, sizeof(struct pollfd) * new_slots);
  795. p->inf = reallocz(p->inf, sizeof(POLLINFO) * new_slots);
  796. // reset all the newly added slots
  797. ssize_t i;
  798. for(i = new_slots - 1; i >= (ssize_t)p->slots ; i--) {
  799. debug(D_POLLFD, "POLLFD: ADD: resetting new slot %zd", i);
  800. p->fds[i].fd = -1;
  801. p->fds[i].events = 0;
  802. p->fds[i].revents = 0;
  803. p->inf[i].p = p;
  804. p->inf[i].slot = (size_t)i;
  805. p->inf[i].flags = 0;
  806. p->inf[i].socktype = -1;
  807. p->inf[i].client_ip = NULL;
  808. p->inf[i].client_port = NULL;
  809. p->inf[i].del_callback = p->del_callback;
  810. p->inf[i].rcv_callback = p->rcv_callback;
  811. p->inf[i].snd_callback = p->snd_callback;
  812. p->inf[i].data = NULL;
  813. // link them so that the first free will be earlier in the array
  814. // (we loop decrementing i)
  815. p->inf[i].next = p->first_free;
  816. p->first_free = &p->inf[i];
  817. }
  818. p->slots = new_slots;
  819. }
  820. POLLINFO *pi = p->first_free;
  821. p->first_free = p->first_free->next;
  822. 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);
  823. struct pollfd *pf = &p->fds[pi->slot];
  824. pf->fd = fd;
  825. pf->events = POLLIN;
  826. pf->revents = 0;
  827. pi->fd = fd;
  828. pi->p = p;
  829. pi->socktype = socktype;
  830. pi->flags = flags;
  831. pi->next = NULL;
  832. pi->client_ip = strdupz(client_ip);
  833. pi->client_port = strdupz(client_port);
  834. pi->del_callback = del_callback;
  835. pi->rcv_callback = rcv_callback;
  836. pi->snd_callback = snd_callback;
  837. pi->connected_t = now_boottime_sec();
  838. pi->last_received_t = 0;
  839. pi->last_sent_t = 0;
  840. pi->last_sent_t = 0;
  841. pi->recv_count = 0;
  842. pi->send_count = 0;
  843. netdata_thread_disable_cancelability();
  844. p->used++;
  845. if(unlikely(pi->slot > p->max))
  846. p->max = pi->slot;
  847. if(pi->flags & POLLINFO_FLAG_CLIENT_SOCKET) {
  848. pi->data = add_callback(pi, &pf->events, data);
  849. }
  850. if(pi->flags & POLLINFO_FLAG_SERVER_SOCKET) {
  851. p->min = pi->slot;
  852. }
  853. netdata_thread_enable_cancelability();
  854. 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);
  855. return pi;
  856. }
  857. inline void poll_close_fd(POLLINFO *pi) {
  858. POLLJOB *p = pi->p;
  859. struct pollfd *pf = &p->fds[pi->slot];
  860. 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);
  861. if(unlikely(pf->fd == -1)) return;
  862. netdata_thread_disable_cancelability();
  863. if(pi->flags & POLLINFO_FLAG_CLIENT_SOCKET) {
  864. pi->del_callback(pi);
  865. if(likely(!(pi->flags & POLLINFO_FLAG_DONT_CLOSE))) {
  866. if(close(pf->fd) == -1)
  867. error("Failed to close() poll_events() socket %d", pf->fd);
  868. }
  869. }
  870. pf->fd = -1;
  871. pf->events = 0;
  872. pf->revents = 0;
  873. pi->fd = -1;
  874. pi->socktype = -1;
  875. pi->flags = 0;
  876. pi->data = NULL;
  877. pi->del_callback = NULL;
  878. pi->rcv_callback = NULL;
  879. pi->snd_callback = NULL;
  880. freez(pi->client_ip);
  881. pi->client_ip = NULL;
  882. freez(pi->client_port);
  883. pi->client_port = NULL;
  884. pi->next = p->first_free;
  885. p->first_free = pi;
  886. p->used--;
  887. if(unlikely(p->max == pi->slot)) {
  888. p->max = p->min;
  889. ssize_t i;
  890. for(i = (ssize_t)pi->slot; i > (ssize_t)p->min ;i--) {
  891. if (unlikely(p->fds[i].fd != -1)) {
  892. p->max = (size_t)i;
  893. break;
  894. }
  895. }
  896. }
  897. netdata_thread_enable_cancelability();
  898. 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);
  899. }
  900. void *poll_default_add_callback(POLLINFO *pi, short int *events, void *data) {
  901. (void)pi;
  902. (void)events;
  903. (void)data;
  904. // error("POLLFD: internal error: poll_default_add_callback() called");
  905. return NULL;
  906. }
  907. void poll_default_del_callback(POLLINFO *pi) {
  908. if(pi->data)
  909. error("POLLFD: internal error: del_callback_default() called with data pointer - possible memory leak");
  910. }
  911. int poll_default_rcv_callback(POLLINFO *pi, short int *events) {
  912. *events |= POLLIN;
  913. char buffer[1024 + 1];
  914. ssize_t rc;
  915. do {
  916. rc = recv(pi->fd, buffer, 1024, MSG_DONTWAIT);
  917. if (rc < 0) {
  918. // read failed
  919. if (errno != EWOULDBLOCK && errno != EAGAIN) {
  920. error("POLLFD: poll_default_rcv_callback(): recv() failed with %zd.", rc);
  921. return -1;
  922. }
  923. } else if (rc) {
  924. // data received
  925. info("POLLFD: internal error: poll_default_rcv_callback() is discarding %zd bytes received on socket %d", rc, pi->fd);
  926. }
  927. } while (rc != -1);
  928. return 0;
  929. }
  930. int poll_default_snd_callback(POLLINFO *pi, short int *events) {
  931. *events &= ~POLLOUT;
  932. info("POLLFD: internal error: poll_default_snd_callback(): nothing to send on socket %d", pi->fd);
  933. return 0;
  934. }
  935. void poll_default_tmr_callback(void *timer_data) {
  936. (void)timer_data;
  937. }
  938. static void poll_events_cleanup(void *data) {
  939. POLLJOB *p = (POLLJOB *)data;
  940. size_t i;
  941. for(i = 0 ; i <= p->max ; i++) {
  942. POLLINFO *pi = &p->inf[i];
  943. poll_close_fd(pi);
  944. }
  945. freez(p->fds);
  946. freez(p->inf);
  947. }
  948. static void poll_events_process(POLLJOB *p, POLLINFO *pi, struct pollfd *pf, short int revents, time_t now) {
  949. short int events = pf->events;
  950. int fd = pf->fd;
  951. pf->revents = 0;
  952. size_t i = pi->slot;
  953. if(unlikely(fd == -1)) {
  954. debug(D_POLLFD, "POLLFD: LISTENER: ignoring slot %zu, it does not have an fd", i);
  955. return;
  956. }
  957. debug(D_POLLFD, "POLLFD: LISTENER: processing events for slot %zu (events = %d, revents = %d)", i, events, revents);
  958. if(revents & POLLIN || revents & POLLPRI) {
  959. // receiving data
  960. pi->last_received_t = now;
  961. pi->recv_count++;
  962. if(likely(pi->flags & POLLINFO_FLAG_CLIENT_SOCKET)) {
  963. // read data from client TCP socket
  964. debug(D_POLLFD, "POLLFD: LISTENER: reading data from TCP client slot %zu (fd %d)", i, fd);
  965. pf->events = 0;
  966. if (pi->rcv_callback(pi, &pf->events) == -1) {
  967. poll_close_fd(&p->inf[i]);
  968. return;
  969. }
  970. pf = &p->fds[i];
  971. pi = &p->inf[i];
  972. #ifdef NETDATA_INTERNAL_CHECKS
  973. // this is common - it is used for web server file copies
  974. if(unlikely(!(pf->events & (POLLIN|POLLOUT)))) {
  975. 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>");
  976. //poll_close_fd(pi);
  977. //return;
  978. }
  979. #endif
  980. }
  981. else if(likely(pi->flags & POLLINFO_FLAG_SERVER_SOCKET)) {
  982. // new connection
  983. // debug(D_POLLFD, "POLLFD: LISTENER: accepting connections from slot %zu (fd %d)", i, fd);
  984. switch(pi->socktype) {
  985. case SOCK_STREAM: {
  986. // a TCP socket
  987. // we accept the connection
  988. int nfd;
  989. do {
  990. char client_ip[NI_MAXHOST + 1];
  991. char client_port[NI_MAXSERV + 1];
  992. debug(D_POLLFD, "POLLFD: LISTENER: calling accept4() slot %zu (fd %d)", i, fd);
  993. nfd = accept_socket(fd, SOCK_NONBLOCK, client_ip, NI_MAXHOST + 1, client_port, NI_MAXSERV + 1, p->access_list);
  994. if (unlikely(nfd < 0)) {
  995. // accept failed
  996. debug(D_POLLFD, "POLLFD: LISTENER: accept4() slot %zu (fd %d) failed.", i, fd);
  997. if(unlikely(errno == EMFILE)) {
  998. error("POLLFD: LISTENER: too many open files - sleeping for 1ms - used by this thread %zu, max for this thread %zu", p->used, p->limit);
  999. usleep(1000); // 10ms
  1000. }
  1001. else if(unlikely(errno != EWOULDBLOCK && errno != EAGAIN))
  1002. error("POLLFD: LISTENER: accept() failed.");
  1003. break;
  1004. }
  1005. else {
  1006. // accept ok
  1007. // info("POLLFD: LISTENER: client '[%s]:%s' connected to '%s' on fd %d", client_ip, client_port, sockets->fds_names[i], nfd);
  1008. poll_add_fd(p
  1009. , nfd
  1010. , SOCK_STREAM
  1011. , POLLINFO_FLAG_CLIENT_SOCKET
  1012. , client_ip
  1013. , client_port
  1014. , p->add_callback
  1015. , p->del_callback
  1016. , p->rcv_callback
  1017. , p->snd_callback
  1018. , NULL
  1019. );
  1020. // it may have reallocated them, so refresh our pointers
  1021. pf = &p->fds[i];
  1022. pi = &p->inf[i];
  1023. }
  1024. } while (nfd >= 0 && (!p->limit || p->used < p->limit));
  1025. break;
  1026. }
  1027. case SOCK_DGRAM: {
  1028. // a UDP socket
  1029. // we read data from the server socket
  1030. debug(D_POLLFD, "POLLFD: LISTENER: reading data from UDP slot %zu (fd %d)", i, fd);
  1031. // TODO: access_list is not applied to UDP
  1032. // but checking the access list on every UDP packet will destroy
  1033. // performance, especially for statsd.
  1034. pf->events = 0;
  1035. pi->rcv_callback(pi, &pf->events);
  1036. break;
  1037. }
  1038. default: {
  1039. error("POLLFD: LISTENER: Unknown socktype %d on slot %zu", pi->socktype, pi->slot);
  1040. break;
  1041. }
  1042. }
  1043. }
  1044. }
  1045. if(unlikely(revents & POLLOUT)) {
  1046. // sending data
  1047. debug(D_POLLFD, "POLLFD: LISTENER: sending data to socket on slot %zu (fd %d)", i, fd);
  1048. pi->last_sent_t = now;
  1049. pi->send_count++;
  1050. pf->events = 0;
  1051. if (pi->snd_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 streaming
  1059. if(unlikely(pi->flags & POLLINFO_FLAG_CLIENT_SOCKET && !(pf->events & (POLLIN|POLLOUT)))) {
  1060. 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>");
  1061. //poll_close_fd(pi);
  1062. //return;
  1063. }
  1064. #endif
  1065. }
  1066. if(unlikely(revents & POLLERR)) {
  1067. error("POLLFD: LISTENER: processing POLLERR events for slot %zu fd %d (events = %d, revents = %d)", i, events, revents, fd);
  1068. pf->events = 0;
  1069. poll_close_fd(pi);
  1070. return;
  1071. }
  1072. if(unlikely(revents & POLLHUP)) {
  1073. error("POLLFD: LISTENER: processing POLLHUP events for slot %zu fd %d (events = %d, revents = %d)", i, events, revents, fd);
  1074. pf->events = 0;
  1075. poll_close_fd(pi);
  1076. return;
  1077. }
  1078. if(unlikely(revents & POLLNVAL)) {
  1079. error("POLLFD: LISTENER: processing POLLNVAL events for slot %zu fd %d (events = %d, revents = %d)", i, events, revents, fd);
  1080. pf->events = 0;
  1081. poll_close_fd(pi);
  1082. return;
  1083. }
  1084. }
  1085. void poll_events(LISTEN_SOCKETS *sockets
  1086. , void *(*add_callback)(POLLINFO * /*pi*/, short int * /*events*/, void * /*data*/)
  1087. , void (*del_callback)(POLLINFO * /*pi*/)
  1088. , int (*rcv_callback)(POLLINFO * /*pi*/, short int * /*events*/)
  1089. , int (*snd_callback)(POLLINFO * /*pi*/, short int * /*events*/)
  1090. , void (*tmr_callback)(void * /*timer_data*/)
  1091. , SIMPLE_PATTERN *access_list
  1092. , void *data
  1093. , time_t tcp_request_timeout_seconds
  1094. , time_t tcp_idle_timeout_seconds
  1095. , time_t timer_milliseconds
  1096. , void *timer_data
  1097. , size_t max_tcp_sockets
  1098. ) {
  1099. if(!sockets || !sockets->opened) {
  1100. error("POLLFD: internal error: no listening sockets are opened");
  1101. return;
  1102. }
  1103. if(timer_milliseconds <= 0) timer_milliseconds = 0;
  1104. int retval;
  1105. POLLJOB p = {
  1106. .slots = 0,
  1107. .used = 0,
  1108. .max = 0,
  1109. .limit = max_tcp_sockets,
  1110. .fds = NULL,
  1111. .inf = NULL,
  1112. .first_free = NULL,
  1113. .complete_request_timeout = tcp_request_timeout_seconds,
  1114. .idle_timeout = tcp_idle_timeout_seconds,
  1115. .checks_every = (tcp_idle_timeout_seconds / 3) + 1,
  1116. .access_list = access_list,
  1117. .timer_milliseconds = timer_milliseconds,
  1118. .timer_data = timer_data,
  1119. .add_callback = add_callback?add_callback:poll_default_add_callback,
  1120. .del_callback = del_callback?del_callback:poll_default_del_callback,
  1121. .rcv_callback = rcv_callback?rcv_callback:poll_default_rcv_callback,
  1122. .snd_callback = snd_callback?snd_callback:poll_default_snd_callback,
  1123. .tmr_callback = tmr_callback?tmr_callback:poll_default_tmr_callback
  1124. };
  1125. size_t i;
  1126. for(i = 0; i < sockets->opened ;i++) {
  1127. POLLINFO *pi = poll_add_fd(&p
  1128. , sockets->fds[i]
  1129. , sockets->fds_types[i]
  1130. , POLLINFO_FLAG_SERVER_SOCKET
  1131. , (sockets->fds_names[i])?sockets->fds_names[i]:"UNKNOWN"
  1132. , ""
  1133. , p.add_callback
  1134. , p.del_callback
  1135. , p.rcv_callback
  1136. , p.snd_callback
  1137. , NULL
  1138. );
  1139. pi->data = data;
  1140. info("POLLFD: LISTENER: listening on '%s'", (sockets->fds_names[i])?sockets->fds_names[i]:"UNKNOWN");
  1141. }
  1142. int listen_sockets_active = 1;
  1143. int timeout_ms = 1000; // in milliseconds
  1144. time_t last_check = now_boottime_sec();
  1145. usec_t timer_usec = timer_milliseconds * USEC_PER_MS;
  1146. usec_t now_usec = 0, next_timer_usec = 0, last_timer_usec = 0;
  1147. (void)last_timer_usec;
  1148. if(unlikely(timer_usec)) {
  1149. now_usec = now_boottime_usec();
  1150. next_timer_usec = now_usec - (now_usec % timer_usec) + timer_usec;
  1151. }
  1152. netdata_thread_cleanup_push(poll_events_cleanup, &p);
  1153. while(!netdata_exit) {
  1154. if(unlikely(timer_usec)) {
  1155. now_usec = now_boottime_usec();
  1156. if(unlikely(timer_usec && now_usec >= next_timer_usec)) {
  1157. debug(D_POLLFD, "Calling timer callback after %zu usec", (size_t)(now_usec - last_timer_usec));
  1158. last_timer_usec = now_usec;
  1159. p.tmr_callback(p.timer_data);
  1160. now_usec = now_boottime_usec();
  1161. next_timer_usec = now_usec - (now_usec % timer_usec) + timer_usec;
  1162. }
  1163. usec_t dt_usec = next_timer_usec - now_usec;
  1164. if(dt_usec > 1000 * USEC_PER_MS)
  1165. timeout_ms = 1000;
  1166. else
  1167. timeout_ms = (int)(dt_usec / USEC_PER_MS);
  1168. }
  1169. // enable or disable the TCP listening sockets, based on the current number of sockets used and the limit set
  1170. if((listen_sockets_active && (p.limit && p.used >= p.limit)) || (!listen_sockets_active && (!p.limit || p.used < p.limit))) {
  1171. listen_sockets_active = !listen_sockets_active;
  1172. info("%s listening sockets (used TCP sockets %zu, max allowed for this worker %zu)", (listen_sockets_active)?"ENABLING":"DISABLING", p.used, p.limit);
  1173. for (i = 0; i <= p.max; i++) {
  1174. if(p.inf[i].flags & POLLINFO_FLAG_SERVER_SOCKET && p.inf[i].socktype == SOCK_STREAM) {
  1175. p.fds[i].events = (short int) ((listen_sockets_active) ? POLLIN : 0);
  1176. }
  1177. }
  1178. }
  1179. debug(D_POLLFD, "POLLFD: LISTENER: Waiting on %zu sockets for %zu ms...", p.max + 1, (size_t)timeout_ms);
  1180. retval = poll(p.fds, p.max + 1, timeout_ms);
  1181. time_t now = now_boottime_sec();
  1182. if(unlikely(retval == -1)) {
  1183. error("POLLFD: LISTENER: poll() failed while waiting on %zu sockets.", p.max + 1);
  1184. break;
  1185. }
  1186. else if(unlikely(!retval)) {
  1187. debug(D_POLLFD, "POLLFD: LISTENER: poll() timeout.");
  1188. }
  1189. else {
  1190. for (i = 0; i <= p.max; i++) {
  1191. struct pollfd *pf = &p.fds[i];
  1192. short int revents = pf->revents;
  1193. if (unlikely(revents))
  1194. poll_events_process(&p, &p.inf[i], pf, revents, now);
  1195. }
  1196. }
  1197. if(unlikely(p.checks_every > 0 && now - last_check > p.checks_every)) {
  1198. last_check = now;
  1199. // security checks
  1200. for(i = 0; i <= p.max; i++) {
  1201. POLLINFO *pi = &p.inf[i];
  1202. if(likely(pi->flags & POLLINFO_FLAG_CLIENT_SOCKET)) {
  1203. if (unlikely(pi->send_count == 0 && p.complete_request_timeout > 0 && (now - pi->connected_t) >= p.complete_request_timeout)) {
  1204. info("POLLFD: LISTENER: client slot %zu (fd %d) from '%s:%s' has not sent a complete request in %zu seconds - closing it. "
  1205. , i
  1206. , pi->fd
  1207. , pi->client_ip ? pi->client_ip : "<undefined-ip>"
  1208. , pi->client_port ? pi->client_port : "<undefined-port>"
  1209. , (size_t) p.complete_request_timeout
  1210. );
  1211. poll_close_fd(pi);
  1212. }
  1213. 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 )) {
  1214. info("POLLFD: LISTENER: client slot %zu (fd %d) from '%s:%s' is idle for more than %zu seconds - closing it. "
  1215. , i
  1216. , pi->fd
  1217. , pi->client_ip ? pi->client_ip : "<undefined-ip>"
  1218. , pi->client_port ? pi->client_port : "<undefined-port>"
  1219. , (size_t) p.idle_timeout
  1220. );
  1221. poll_close_fd(pi);
  1222. }
  1223. }
  1224. }
  1225. }
  1226. }
  1227. netdata_thread_cleanup_pop(1);
  1228. debug(D_POLLFD, "POLLFD: LISTENER: cleanup completed");
  1229. }