socket.c 68 KB

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