socket.c 66 KB

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