web_client.c 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include "web_client.h"
  3. // this is an async I/O implementation of the web server request parser
  4. // it is used by all netdata web servers
  5. int respect_web_browser_do_not_track_policy = 0;
  6. char *web_x_frame_options = NULL;
  7. #ifdef NETDATA_WITH_ZLIB
  8. int web_enable_gzip = 1, web_gzip_level = 3, web_gzip_strategy = Z_DEFAULT_STRATEGY;
  9. #endif /* NETDATA_WITH_ZLIB */
  10. inline int web_client_permission_denied(struct web_client *w) {
  11. w->response.data->content_type = CT_TEXT_PLAIN;
  12. buffer_flush(w->response.data);
  13. buffer_strcat(w->response.data, "You are not allowed to access this resource.");
  14. w->response.code = HTTP_RESP_FORBIDDEN;
  15. return HTTP_RESP_FORBIDDEN;
  16. }
  17. static inline int web_client_crock_socket(struct web_client *w __maybe_unused) {
  18. #ifdef TCP_CORK
  19. if(likely(web_client_is_corkable(w) && !w->tcp_cork && w->ofd != -1)) {
  20. w->tcp_cork = true;
  21. if(unlikely(setsockopt(w->ofd, IPPROTO_TCP, TCP_CORK, (char *) &w->tcp_cork, sizeof(int)) != 0)) {
  22. error("%llu: failed to enable TCP_CORK on socket.", w->id);
  23. w->tcp_cork = false;
  24. return -1;
  25. }
  26. }
  27. #endif /* TCP_CORK */
  28. return 0;
  29. }
  30. static inline void web_client_enable_wait_from_ssl(struct web_client *w, int bytes) {
  31. int ssl_err = SSL_get_error(w->ssl.conn, bytes);
  32. if (ssl_err == SSL_ERROR_WANT_READ)
  33. web_client_enable_ssl_wait_receive(w);
  34. else if (ssl_err == SSL_ERROR_WANT_WRITE)
  35. web_client_enable_ssl_wait_send(w);
  36. else {
  37. web_client_disable_ssl_wait_receive(w);
  38. web_client_disable_ssl_wait_send(w);
  39. }
  40. }
  41. static inline int web_client_uncrock_socket(struct web_client *w __maybe_unused) {
  42. #ifdef TCP_CORK
  43. if(likely(w->tcp_cork && w->ofd != -1)) {
  44. if(unlikely(setsockopt(w->ofd, IPPROTO_TCP, TCP_CORK, (char *) &w->tcp_cork, sizeof(int)) != 0)) {
  45. error("%llu: failed to disable TCP_CORK on socket.", w->id);
  46. w->tcp_cork = true;
  47. return -1;
  48. }
  49. }
  50. #endif /* TCP_CORK */
  51. w->tcp_cork = false;
  52. return 0;
  53. }
  54. char *strip_control_characters(char *url) {
  55. char *s = url;
  56. if(!s) return "";
  57. if(iscntrl(*s)) *s = ' ';
  58. while(*++s) {
  59. if(iscntrl(*s)) *s = ' ';
  60. }
  61. return url;
  62. }
  63. static void web_client_reset_allocations(struct web_client *w, bool free_all) {
  64. if(free_all) {
  65. // the web client is to be destroyed
  66. buffer_free(w->url_as_received);
  67. w->url_as_received = NULL;
  68. buffer_free(w->url_path_decoded);
  69. w->url_path_decoded = NULL;
  70. buffer_free(w->url_query_string_decoded);
  71. w->url_query_string_decoded = NULL;
  72. buffer_free(w->response.header_output);
  73. w->response.header_output = NULL;
  74. buffer_free(w->response.header);
  75. w->response.header = NULL;
  76. buffer_free(w->response.data);
  77. w->response.data = NULL;
  78. freez(w->post_payload);
  79. w->post_payload = NULL;
  80. w->post_payload_size = 0;
  81. #ifdef ENABLE_HTTPS
  82. if ((!web_client_check_unix(w)) && (netdata_ssl_srv_ctx)) {
  83. if (w->ssl.conn) {
  84. SSL_free(w->ssl.conn);
  85. w->ssl.conn = NULL;
  86. }
  87. }
  88. #endif
  89. }
  90. else {
  91. // the web client is to be re-used
  92. buffer_reset(w->url_as_received);
  93. buffer_reset(w->url_path_decoded);
  94. buffer_reset(w->url_query_string_decoded);
  95. buffer_reset(w->response.header_output);
  96. buffer_reset(w->response.header);
  97. buffer_reset(w->response.data);
  98. // leave w->post_payload
  99. // leave w->ssl
  100. }
  101. freez(w->server_host);
  102. w->server_host = NULL;
  103. freez(w->forwarded_host);
  104. w->forwarded_host = NULL;
  105. freez(w->origin);
  106. w->origin = NULL;
  107. freez(w->user_agent);
  108. w->user_agent = NULL;
  109. freez(w->auth_bearer_token);
  110. w->auth_bearer_token = NULL;
  111. // if we had enabled compression, release it
  112. #ifdef NETDATA_WITH_ZLIB
  113. if(w->response.zinitialized) {
  114. deflateEnd(&w->response.zstream);
  115. w->response.zsent = 0;
  116. w->response.zhave = 0;
  117. w->response.zstream.avail_in = 0;
  118. w->response.zstream.avail_out = 0;
  119. w->response.zstream.total_in = 0;
  120. w->response.zstream.total_out = 0;
  121. w->response.zinitialized = false;
  122. w->flags &= ~WEB_CLIENT_CHUNKED_TRANSFER;
  123. }
  124. #endif // NETDATA_WITH_ZLIB
  125. }
  126. void web_client_request_done(struct web_client *w) {
  127. web_client_uncrock_socket(w);
  128. debug(D_WEB_CLIENT, "%llu: Resetting client.", w->id);
  129. if(likely(buffer_strlen(w->url_as_received))) {
  130. struct timeval tv;
  131. now_monotonic_high_precision_timeval(&tv);
  132. size_t size = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->response.rlen:w->response.data->len;
  133. size_t sent = size;
  134. #ifdef NETDATA_WITH_ZLIB
  135. if(likely(w->response.zoutput)) sent = (size_t)w->response.zstream.total_out;
  136. #endif
  137. // --------------------------------------------------------------------
  138. // global statistics
  139. global_statistics_web_request_completed(dt_usec(&tv, &w->timings.tv_in),
  140. w->statistics.received_bytes,
  141. w->statistics.sent_bytes,
  142. size,
  143. sent);
  144. w->statistics.received_bytes = 0;
  145. w->statistics.sent_bytes = 0;
  146. // --------------------------------------------------------------------
  147. const char *mode;
  148. switch(w->mode) {
  149. case WEB_CLIENT_MODE_FILECOPY:
  150. mode = "FILECOPY";
  151. break;
  152. case WEB_CLIENT_MODE_OPTIONS:
  153. mode = "OPTIONS";
  154. break;
  155. case WEB_CLIENT_MODE_STREAM:
  156. mode = "STREAM";
  157. break;
  158. case WEB_CLIENT_MODE_POST:
  159. case WEB_CLIENT_MODE_GET:
  160. mode = "DATA";
  161. break;
  162. default:
  163. mode = "UNKNOWN";
  164. break;
  165. }
  166. // access log
  167. log_access("%llu: %d '[%s]:%s' '%s' (sent/all = %zu/%zu bytes %0.0f%%, prep/sent/total = %0.2f/%0.2f/%0.2f ms) %d '%s'",
  168. w->id
  169. , gettid()
  170. , w->client_ip
  171. , w->client_port
  172. , mode
  173. , sent
  174. , size
  175. , -((size > 0) ? ((double)(size - sent) / (double) size * 100.0) : 0.0)
  176. , (double)dt_usec(&w->timings.tv_ready, &w->timings.tv_in) / 1000.0
  177. , (double)dt_usec(&tv, &w->timings.tv_ready) / 1000.0
  178. , (double)dt_usec(&tv, &w->timings.tv_in) / 1000.0
  179. , w->response.code
  180. , strip_control_characters((char *)buffer_tostring(w->url_as_received))
  181. );
  182. }
  183. if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY)) {
  184. if(w->ifd != w->ofd) {
  185. debug(D_WEB_CLIENT, "%llu: Closing filecopy input file descriptor %d.", w->id, w->ifd);
  186. if(web_server_mode != WEB_SERVER_MODE_STATIC_THREADED) {
  187. if (w->ifd != -1){
  188. close(w->ifd);
  189. }
  190. }
  191. w->ifd = w->ofd;
  192. }
  193. }
  194. web_client_reset_allocations(w, false);
  195. w->mode = WEB_CLIENT_MODE_GET;
  196. web_client_disable_donottrack(w);
  197. web_client_disable_tracking_required(w);
  198. web_client_disable_keepalive(w);
  199. w->header_parse_tries = 0;
  200. w->header_parse_last_size = 0;
  201. web_client_enable_wait_receive(w);
  202. web_client_disable_wait_send(w);
  203. w->response.has_cookies = false;
  204. w->response.rlen = 0;
  205. w->response.sent = 0;
  206. w->response.code = 0;
  207. w->response.zoutput = false;
  208. }
  209. static struct {
  210. const char *extension;
  211. uint32_t hash;
  212. uint8_t contenttype;
  213. } mime_types[] = {
  214. { "html" , 0 , CT_TEXT_HTML}
  215. , {"js" , 0 , CT_APPLICATION_X_JAVASCRIPT}
  216. , {"css" , 0 , CT_TEXT_CSS}
  217. , {"xml" , 0 , CT_TEXT_XML}
  218. , {"xsl" , 0 , CT_TEXT_XSL}
  219. , {"txt" , 0 , CT_TEXT_PLAIN}
  220. , {"svg" , 0 , CT_IMAGE_SVG_XML}
  221. , {"ttf" , 0 , CT_APPLICATION_X_FONT_TRUETYPE}
  222. , {"otf" , 0 , CT_APPLICATION_X_FONT_OPENTYPE}
  223. , {"woff2", 0 , CT_APPLICATION_FONT_WOFF2}
  224. , {"woff" , 0 , CT_APPLICATION_FONT_WOFF}
  225. , {"eot" , 0 , CT_APPLICATION_VND_MS_FONTOBJ}
  226. , {"png" , 0 , CT_IMAGE_PNG}
  227. , {"jpg" , 0 , CT_IMAGE_JPG}
  228. , {"jpeg" , 0 , CT_IMAGE_JPG}
  229. , {"gif" , 0 , CT_IMAGE_GIF}
  230. , {"bmp" , 0 , CT_IMAGE_BMP}
  231. , {"ico" , 0 , CT_IMAGE_XICON}
  232. , {"icns" , 0 , CT_IMAGE_ICNS}
  233. , { NULL, 0, 0}
  234. };
  235. static inline uint8_t contenttype_for_filename(const char *filename) {
  236. // info("checking filename '%s'", filename);
  237. static int initialized = 0;
  238. int i;
  239. if(unlikely(!initialized)) {
  240. for (i = 0; mime_types[i].extension; i++)
  241. mime_types[i].hash = simple_hash(mime_types[i].extension);
  242. initialized = 1;
  243. }
  244. const char *s = filename, *last_dot = NULL;
  245. // find the last dot
  246. while(*s) {
  247. if(unlikely(*s == '.')) last_dot = s;
  248. s++;
  249. }
  250. if(unlikely(!last_dot || !*last_dot || !last_dot[1])) {
  251. // info("no extension for filename '%s'", filename);
  252. return CT_APPLICATION_OCTET_STREAM;
  253. }
  254. last_dot++;
  255. // info("extension for filename '%s' is '%s'", filename, last_dot);
  256. uint32_t hash = simple_hash(last_dot);
  257. for(i = 0; mime_types[i].extension ; i++) {
  258. if(unlikely(hash == mime_types[i].hash && !strcmp(last_dot, mime_types[i].extension))) {
  259. // info("matched extension for filename '%s': '%s'", filename, last_dot);
  260. return mime_types[i].contenttype;
  261. }
  262. }
  263. // info("not matched extension for filename '%s': '%s'", filename, last_dot);
  264. return CT_APPLICATION_OCTET_STREAM;
  265. }
  266. static inline int access_to_file_is_not_permitted(struct web_client *w, const char *filename) {
  267. w->response.data->content_type = CT_TEXT_HTML;
  268. buffer_strcat(w->response.data, "Access to file is not permitted: ");
  269. buffer_strcat_htmlescape(w->response.data, filename);
  270. return HTTP_RESP_FORBIDDEN;
  271. }
  272. // Work around a bug in the CMocka library by removing this function during testing.
  273. #ifndef REMOVE_MYSENDFILE
  274. int mysendfile(struct web_client *w, char *filename) {
  275. debug(D_WEB_CLIENT, "%llu: Looking for file '%s/%s'", w->id, netdata_configured_web_dir, filename);
  276. if(!web_client_can_access_dashboard(w))
  277. return web_client_permission_denied(w);
  278. // skip leading slashes
  279. while (*filename == '/') filename++;
  280. // if the filename contains "strange" characters, refuse to serve it
  281. char *s;
  282. for(s = filename; *s ;s++) {
  283. if( !isalnum(*s) && *s != '/' && *s != '.' && *s != '-' && *s != '_') {
  284. debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
  285. w->response.data->content_type = CT_TEXT_HTML;
  286. buffer_sprintf(w->response.data, "Filename contains invalid characters: ");
  287. buffer_strcat_htmlescape(w->response.data, filename);
  288. return HTTP_RESP_BAD_REQUEST;
  289. }
  290. }
  291. // if the filename contains a double dot refuse to serve it
  292. if(strstr(filename, "..") != 0) {
  293. debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
  294. w->response.data->content_type = CT_TEXT_HTML;
  295. buffer_strcat(w->response.data, "Relative filenames are not supported: ");
  296. buffer_strcat_htmlescape(w->response.data, filename);
  297. return HTTP_RESP_BAD_REQUEST;
  298. }
  299. // find the physical file on disk
  300. char webfilename[FILENAME_MAX + 1];
  301. snprintfz(webfilename, FILENAME_MAX, "%s/%s", netdata_configured_web_dir, filename);
  302. struct stat statbuf;
  303. int done = 0;
  304. while(!done) {
  305. // check if the file exists
  306. if (lstat(webfilename, &statbuf) != 0) {
  307. debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not found.", w->id, webfilename);
  308. w->response.data->content_type = CT_TEXT_HTML;
  309. buffer_strcat(w->response.data, "File does not exist, or is not accessible: ");
  310. buffer_strcat_htmlescape(w->response.data, webfilename);
  311. return HTTP_RESP_NOT_FOUND;
  312. }
  313. if ((statbuf.st_mode & S_IFMT) == S_IFDIR) {
  314. snprintfz(webfilename, FILENAME_MAX, "%s/%s/index.html", netdata_configured_web_dir, filename);
  315. continue;
  316. }
  317. if ((statbuf.st_mode & S_IFMT) != S_IFREG) {
  318. error("%llu: File '%s' is not a regular file. Access Denied.", w->id, webfilename);
  319. return access_to_file_is_not_permitted(w, webfilename);
  320. }
  321. done = 1;
  322. }
  323. // open the file
  324. w->ifd = open(webfilename, O_NONBLOCK, O_RDONLY);
  325. if(w->ifd == -1) {
  326. w->ifd = w->ofd;
  327. if(errno == EBUSY || errno == EAGAIN) {
  328. error("%llu: File '%s' is busy, sending 307 Moved Temporarily to force retry.", w->id, webfilename);
  329. w->response.data->content_type = CT_TEXT_HTML;
  330. buffer_sprintf(w->response.header, "Location: /%s\r\n", filename);
  331. buffer_strcat(w->response.data, "File is currently busy, please try again later: ");
  332. buffer_strcat_htmlescape(w->response.data, webfilename);
  333. return HTTP_RESP_REDIR_TEMP;
  334. }
  335. else {
  336. error("%llu: Cannot open file '%s'.", w->id, webfilename);
  337. w->response.data->content_type = CT_TEXT_HTML;
  338. buffer_strcat(w->response.data, "Cannot open file: ");
  339. buffer_strcat_htmlescape(w->response.data, webfilename);
  340. return HTTP_RESP_NOT_FOUND;
  341. }
  342. }
  343. sock_setnonblock(w->ifd);
  344. w->response.data->content_type = contenttype_for_filename(webfilename);
  345. debug(D_WEB_CLIENT_ACCESS, "%llu: Sending file '%s' (%"PRId64" bytes, ifd %d, ofd %d).", w->id, webfilename, (int64_t)statbuf.st_size, w->ifd, w->ofd);
  346. w->mode = WEB_CLIENT_MODE_FILECOPY;
  347. web_client_enable_wait_receive(w);
  348. web_client_disable_wait_send(w);
  349. buffer_flush(w->response.data);
  350. buffer_need_bytes(w->response.data, (size_t)statbuf.st_size);
  351. w->response.rlen = (size_t)statbuf.st_size;
  352. #ifdef __APPLE__
  353. w->response.data->date = statbuf.st_mtimespec.tv_sec;
  354. #else
  355. w->response.data->date = statbuf.st_mtim.tv_sec;
  356. #endif
  357. buffer_cacheable(w->response.data);
  358. return HTTP_RESP_OK;
  359. }
  360. #endif
  361. #ifdef NETDATA_WITH_ZLIB
  362. void web_client_enable_deflate(struct web_client *w, int gzip) {
  363. if(unlikely(w->response.zinitialized)) {
  364. debug(D_DEFLATE, "%llu: Compression has already be initialized for this client.", w->id);
  365. return;
  366. }
  367. if(unlikely(w->response.sent)) {
  368. error("%llu: Cannot enable compression in the middle of a conversation.", w->id);
  369. return;
  370. }
  371. w->response.zstream.zalloc = Z_NULL;
  372. w->response.zstream.zfree = Z_NULL;
  373. w->response.zstream.opaque = Z_NULL;
  374. w->response.zstream.next_in = (Bytef *)w->response.data->buffer;
  375. w->response.zstream.avail_in = 0;
  376. w->response.zstream.total_in = 0;
  377. w->response.zstream.next_out = w->response.zbuffer;
  378. w->response.zstream.avail_out = 0;
  379. w->response.zstream.total_out = 0;
  380. w->response.zstream.zalloc = Z_NULL;
  381. w->response.zstream.zfree = Z_NULL;
  382. w->response.zstream.opaque = Z_NULL;
  383. // if(deflateInit(&w->response.zstream, Z_DEFAULT_COMPRESSION) != Z_OK) {
  384. // error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
  385. // return;
  386. // }
  387. // Select GZIP compression: windowbits = 15 + 16 = 31
  388. if(deflateInit2(&w->response.zstream, web_gzip_level, Z_DEFLATED, 15 + ((gzip)?16:0), 8, web_gzip_strategy) != Z_OK) {
  389. error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
  390. return;
  391. }
  392. w->response.zsent = 0;
  393. w->response.zoutput = true;
  394. w->response.zinitialized = true;
  395. w->flags |= WEB_CLIENT_CHUNKED_TRANSFER;
  396. debug(D_DEFLATE, "%llu: Initialized compression.", w->id);
  397. }
  398. #endif // NETDATA_WITH_ZLIB
  399. void buffer_data_options2string(BUFFER *wb, uint32_t options) {
  400. int count = 0;
  401. if(options & RRDR_OPTION_NONZERO) {
  402. if(count++) buffer_strcat(wb, " ");
  403. buffer_strcat(wb, "nonzero");
  404. }
  405. if(options & RRDR_OPTION_REVERSED) {
  406. if(count++) buffer_strcat(wb, " ");
  407. buffer_strcat(wb, "flip");
  408. }
  409. if(options & RRDR_OPTION_JSON_WRAP) {
  410. if(count++) buffer_strcat(wb, " ");
  411. buffer_strcat(wb, "jsonwrap");
  412. }
  413. if(options & RRDR_OPTION_MIN2MAX) {
  414. if(count++) buffer_strcat(wb, " ");
  415. buffer_strcat(wb, "min2max");
  416. }
  417. if(options & RRDR_OPTION_MILLISECONDS) {
  418. if(count++) buffer_strcat(wb, " ");
  419. buffer_strcat(wb, "ms");
  420. }
  421. if(options & RRDR_OPTION_ABSOLUTE) {
  422. if(count++) buffer_strcat(wb, " ");
  423. buffer_strcat(wb, "absolute");
  424. }
  425. if(options & RRDR_OPTION_SECONDS) {
  426. if(count++) buffer_strcat(wb, " ");
  427. buffer_strcat(wb, "seconds");
  428. }
  429. if(options & RRDR_OPTION_NULL2ZERO) {
  430. if(count++) buffer_strcat(wb, " ");
  431. buffer_strcat(wb, "null2zero");
  432. }
  433. if(options & RRDR_OPTION_OBJECTSROWS) {
  434. if(count++) buffer_strcat(wb, " ");
  435. buffer_strcat(wb, "objectrows");
  436. }
  437. if(options & RRDR_OPTION_GOOGLE_JSON) {
  438. if(count++) buffer_strcat(wb, " ");
  439. buffer_strcat(wb, "google_json");
  440. }
  441. if(options & RRDR_OPTION_PERCENTAGE) {
  442. if(count++) buffer_strcat(wb, " ");
  443. buffer_strcat(wb, "percentage");
  444. }
  445. if(options & RRDR_OPTION_NOT_ALIGNED) {
  446. if(count++) buffer_strcat(wb, " ");
  447. buffer_strcat(wb, "unaligned");
  448. }
  449. if(options & RRDR_OPTION_ANOMALY_BIT) {
  450. if(count++) buffer_strcat(wb, " ");
  451. buffer_strcat(wb, "anomaly-bit");
  452. }
  453. }
  454. static inline int check_host_and_call(RRDHOST *host, struct web_client *w, char *url, int (*func)(RRDHOST *, struct web_client *, char *)) {
  455. //if(unlikely(host->rrd_memory_mode == RRD_MEMORY_MODE_NONE)) {
  456. // buffer_flush(w->response.data);
  457. // buffer_strcat(w->response.data, "This host does not maintain a database");
  458. // return HTTP_RESP_BAD_REQUEST;
  459. //}
  460. return func(host, w, url);
  461. }
  462. static inline int UNUSED_FUNCTION(check_host_and_dashboard_acl_and_call)(RRDHOST *host, struct web_client *w, char *url, int (*func)(RRDHOST *, struct web_client *, char *)) {
  463. if(!web_client_can_access_dashboard(w))
  464. return web_client_permission_denied(w);
  465. return check_host_and_call(host, w, url, func);
  466. }
  467. static inline int UNUSED_FUNCTION(check_host_and_mgmt_acl_and_call)(RRDHOST *host, struct web_client *w, char *url, int (*func)(RRDHOST *, struct web_client *, char *)) {
  468. if(!web_client_can_access_mgmt(w))
  469. return web_client_permission_denied(w);
  470. return check_host_and_call(host, w, url, func);
  471. }
  472. int web_client_api_request(RRDHOST *host, struct web_client *w, char *url_path_fragment)
  473. {
  474. // get the api version
  475. char *tok = strsep_skip_consecutive_separators(&url_path_fragment, "/");
  476. if(tok && *tok) {
  477. debug(D_WEB_CLIENT, "%llu: Searching for API version '%s'.", w->id, tok);
  478. if(strcmp(tok, "v2") == 0)
  479. return web_client_api_request_v2(host, w, url_path_fragment);
  480. else if(strcmp(tok, "v1") == 0)
  481. return web_client_api_request_v1(host, w, url_path_fragment);
  482. else {
  483. buffer_flush(w->response.data);
  484. w->response.data->content_type = CT_TEXT_HTML;
  485. buffer_strcat(w->response.data, "Unsupported API version: ");
  486. buffer_strcat_htmlescape(w->response.data, tok);
  487. return HTTP_RESP_NOT_FOUND;
  488. }
  489. }
  490. else {
  491. buffer_flush(w->response.data);
  492. buffer_sprintf(w->response.data, "Which API version?");
  493. return HTTP_RESP_BAD_REQUEST;
  494. }
  495. }
  496. const char *web_content_type_to_string(HTTP_CONTENT_TYPE content_type) {
  497. switch(content_type) {
  498. case CT_TEXT_HTML:
  499. return "text/html; charset=utf-8";
  500. case CT_APPLICATION_XML:
  501. return "application/xml; charset=utf-8";
  502. case CT_APPLICATION_JSON:
  503. return "application/json; charset=utf-8";
  504. case CT_APPLICATION_X_JAVASCRIPT:
  505. return "application/x-javascript; charset=utf-8";
  506. case CT_TEXT_CSS:
  507. return "text/css; charset=utf-8";
  508. case CT_TEXT_XML:
  509. return "text/xml; charset=utf-8";
  510. case CT_TEXT_XSL:
  511. return "text/xsl; charset=utf-8";
  512. case CT_APPLICATION_OCTET_STREAM:
  513. return "application/octet-stream";
  514. case CT_IMAGE_SVG_XML:
  515. return "image/svg+xml";
  516. case CT_APPLICATION_X_FONT_TRUETYPE:
  517. return "application/x-font-truetype";
  518. case CT_APPLICATION_X_FONT_OPENTYPE:
  519. return "application/x-font-opentype";
  520. case CT_APPLICATION_FONT_WOFF:
  521. return "application/font-woff";
  522. case CT_APPLICATION_FONT_WOFF2:
  523. return "application/font-woff2";
  524. case CT_APPLICATION_VND_MS_FONTOBJ:
  525. return "application/vnd.ms-fontobject";
  526. case CT_IMAGE_PNG:
  527. return "image/png";
  528. case CT_IMAGE_JPG:
  529. return "image/jpeg";
  530. case CT_IMAGE_GIF:
  531. return "image/gif";
  532. case CT_IMAGE_XICON:
  533. return "image/x-icon";
  534. case CT_IMAGE_BMP:
  535. return "image/bmp";
  536. case CT_IMAGE_ICNS:
  537. return "image/icns";
  538. case CT_PROMETHEUS:
  539. return "text/plain; version=0.0.4";
  540. default:
  541. case CT_TEXT_PLAIN:
  542. return "text/plain; charset=utf-8";
  543. }
  544. }
  545. const char *web_response_code_to_string(int code) {
  546. switch(code) {
  547. case HTTP_RESP_OK:
  548. return "OK";
  549. case HTTP_RESP_MOVED_PERM:
  550. return "Moved Permanently";
  551. case HTTP_RESP_REDIR_TEMP:
  552. return "Temporary Redirect";
  553. case HTTP_RESP_BAD_REQUEST:
  554. return "Bad Request";
  555. case HTTP_RESP_FORBIDDEN:
  556. return "Forbidden";
  557. case HTTP_RESP_NOT_FOUND:
  558. return "Not Found";
  559. case HTTP_RESP_PRECOND_FAIL:
  560. return "Preconditions Failed";
  561. default:
  562. if(code >= 100 && code < 200)
  563. return "Informational";
  564. if(code >= 200 && code < 300)
  565. return "Successful";
  566. if(code >= 300 && code < 400)
  567. return "Redirection";
  568. if(code >= 400 && code < 500)
  569. return "Bad Request";
  570. if(code >= 500 && code < 600)
  571. return "Server Error";
  572. return "Undefined Error";
  573. }
  574. }
  575. static inline char *http_header_parse(struct web_client *w, char *s, int parse_useragent) {
  576. static uint32_t hash_origin = 0, hash_connection = 0, hash_donottrack = 0, hash_useragent = 0,
  577. hash_authorization = 0, hash_host = 0, hash_forwarded_proto = 0, hash_forwarded_host = 0;
  578. #ifdef NETDATA_WITH_ZLIB
  579. static uint32_t hash_accept_encoding = 0;
  580. #endif
  581. if(unlikely(!hash_origin)) {
  582. hash_origin = simple_uhash("Origin");
  583. hash_connection = simple_uhash("Connection");
  584. #ifdef NETDATA_WITH_ZLIB
  585. hash_accept_encoding = simple_uhash("Accept-Encoding");
  586. #endif
  587. hash_donottrack = simple_uhash("DNT");
  588. hash_useragent = simple_uhash("User-Agent");
  589. hash_authorization = simple_uhash("X-Auth-Token");
  590. hash_host = simple_uhash("Host");
  591. hash_forwarded_proto = simple_uhash("X-Forwarded-Proto");
  592. hash_forwarded_host = simple_uhash("X-Forwarded-Host");
  593. }
  594. char *e = s;
  595. // find the :
  596. while(*e && *e != ':') e++;
  597. if(!*e) return e;
  598. // get the name
  599. *e = '\0';
  600. // find the value
  601. char *v = e + 1, *ve;
  602. // skip leading spaces from value
  603. while(*v == ' ') v++;
  604. ve = v;
  605. // find the \r
  606. while(*ve && *ve != '\r') ve++;
  607. if(!*ve || ve[1] != '\n') {
  608. *e = ':';
  609. return ve;
  610. }
  611. // terminate the value
  612. *ve = '\0';
  613. uint32_t hash = simple_uhash(s);
  614. if(hash == hash_origin && !strcasecmp(s, "Origin"))
  615. w->origin = strdupz(v);
  616. else if(hash == hash_connection && !strcasecmp(s, "Connection")) {
  617. if(strcasestr(v, "keep-alive"))
  618. web_client_enable_keepalive(w);
  619. }
  620. else if(respect_web_browser_do_not_track_policy && hash == hash_donottrack && !strcasecmp(s, "DNT")) {
  621. if(*v == '0') web_client_disable_donottrack(w);
  622. else if(*v == '1') web_client_enable_donottrack(w);
  623. }
  624. else if(parse_useragent && hash == hash_useragent && !strcasecmp(s, "User-Agent")) {
  625. w->user_agent = strdupz(v);
  626. }
  627. else if(hash == hash_authorization&& !strcasecmp(s, "X-Auth-Token")) {
  628. w->auth_bearer_token = strdupz(v);
  629. }
  630. else if(hash == hash_host && !strcasecmp(s, "Host")) {
  631. char buffer[NI_MAXHOST];
  632. strncpyz(buffer, v, ((size_t)(ve - v) < sizeof(buffer) - 1 ? (size_t)(ve - v) : sizeof(buffer) - 1));
  633. w->server_host = strdupz(buffer);
  634. }
  635. #ifdef NETDATA_WITH_ZLIB
  636. else if(hash == hash_accept_encoding && !strcasecmp(s, "Accept-Encoding")) {
  637. if(web_enable_gzip) {
  638. if(strcasestr(v, "gzip"))
  639. web_client_enable_deflate(w, 1);
  640. //
  641. // does not seem to work
  642. // else if(strcasestr(v, "deflate"))
  643. // web_client_enable_deflate(w, 0);
  644. }
  645. }
  646. #endif /* NETDATA_WITH_ZLIB */
  647. #ifdef ENABLE_HTTPS
  648. else if(hash == hash_forwarded_proto && !strcasecmp(s, "X-Forwarded-Proto")) {
  649. if(strcasestr(v, "https"))
  650. w->ssl.flags |= NETDATA_SSL_PROXY_HTTPS;
  651. }
  652. #endif
  653. else if(hash == hash_forwarded_host && !strcasecmp(s, "X-Forwarded-Host")) {
  654. char buffer[NI_MAXHOST];
  655. strncpyz(buffer, v, ((size_t)(ve - v) < sizeof(buffer) - 1 ? (size_t)(ve - v) : sizeof(buffer) - 1));
  656. w->forwarded_host = strdupz(buffer);
  657. }
  658. *e = ':';
  659. *ve = '\r';
  660. return ve;
  661. }
  662. /**
  663. * Valid Method
  664. *
  665. * Netdata accepts only three methods, including one of these three(STREAM) is an internal method.
  666. *
  667. * @param w is the structure with the client request
  668. * @param s is the start string to parse
  669. *
  670. * @return it returns the next address to parse case the method is valid and NULL otherwise.
  671. */
  672. static inline char *web_client_valid_method(struct web_client *w, char *s) {
  673. // is is a valid request?
  674. if(!strncmp(s, "GET ", 4)) {
  675. s = &s[4];
  676. w->mode = WEB_CLIENT_MODE_GET;
  677. }
  678. else if(!strncmp(s, "OPTIONS ", 8)) {
  679. s = &s[8];
  680. w->mode = WEB_CLIENT_MODE_OPTIONS;
  681. }
  682. else if(!strncmp(s, "POST ", 5)) {
  683. s = &s[5];
  684. w->mode = WEB_CLIENT_MODE_POST;
  685. }
  686. else if(!strncmp(s, "STREAM ", 7)) {
  687. s = &s[7];
  688. #ifdef ENABLE_HTTPS
  689. if (w->ssl.flags && web_client_is_using_ssl_force(w)){
  690. w->header_parse_tries = 0;
  691. w->header_parse_last_size = 0;
  692. web_client_disable_wait_receive(w);
  693. char hostname[256];
  694. char *copyme = strstr(s,"hostname=");
  695. if ( copyme ){
  696. copyme += 9;
  697. char *end = strchr(copyme,'&');
  698. if(end){
  699. size_t length = MIN(255, end - copyme);
  700. memcpy(hostname,copyme,length);
  701. hostname[length] = 0X00;
  702. }
  703. else{
  704. memcpy(hostname,"not available",13);
  705. hostname[13] = 0x00;
  706. }
  707. }
  708. else{
  709. memcpy(hostname,"not available",13);
  710. hostname[13] = 0x00;
  711. }
  712. error("The server is configured to always use encrypted connections, please enable the SSL on child with hostname '%s'.",hostname);
  713. s = NULL;
  714. }
  715. #endif
  716. w->mode = WEB_CLIENT_MODE_STREAM;
  717. }
  718. else {
  719. s = NULL;
  720. }
  721. return s;
  722. }
  723. /**
  724. * Request validate
  725. *
  726. * @param w is the structure with the client request
  727. *
  728. * @return It returns HTTP_VALIDATION_OK on success and another code present
  729. * in the enum HTTP_VALIDATION otherwise.
  730. */
  731. static inline HTTP_VALIDATION http_request_validate(struct web_client *w) {
  732. char *s = (char *)buffer_tostring(w->response.data), *encoded_url = NULL;
  733. size_t last_pos = w->header_parse_last_size;
  734. w->header_parse_tries++;
  735. w->header_parse_last_size = buffer_strlen(w->response.data);
  736. int is_it_valid;
  737. if(w->header_parse_tries > 1) {
  738. if(last_pos > 4) last_pos -= 4; // allow searching for \r\n\r\n
  739. else last_pos = 0;
  740. if(w->header_parse_last_size < last_pos)
  741. last_pos = 0;
  742. is_it_valid = url_is_request_complete(s, &s[last_pos], w->header_parse_last_size, &w->post_payload, &w->post_payload_size);
  743. if(!is_it_valid) {
  744. if(w->header_parse_tries > HTTP_REQ_MAX_HEADER_FETCH_TRIES) {
  745. info("Disabling slow client after %zu attempts to read the request (%zu bytes received)", w->header_parse_tries, buffer_strlen(w->response.data));
  746. w->header_parse_tries = 0;
  747. w->header_parse_last_size = 0;
  748. web_client_disable_wait_receive(w);
  749. return HTTP_VALIDATION_TOO_MANY_READ_RETRIES;
  750. }
  751. return HTTP_VALIDATION_INCOMPLETE;
  752. }
  753. is_it_valid = 1;
  754. } else {
  755. last_pos = w->header_parse_last_size;
  756. is_it_valid = url_is_request_complete(s, &s[last_pos], w->header_parse_last_size, &w->post_payload, &w->post_payload_size);
  757. }
  758. s = web_client_valid_method(w, s);
  759. if (!s) {
  760. w->header_parse_tries = 0;
  761. w->header_parse_last_size = 0;
  762. web_client_disable_wait_receive(w);
  763. return HTTP_VALIDATION_NOT_SUPPORTED;
  764. } else if (!is_it_valid) {
  765. //Invalid request, we have more data after the end of message
  766. char *check = strstr((char *)buffer_tostring(w->response.data), "\r\n\r\n");
  767. if(check) {
  768. check += 4;
  769. if (*check) {
  770. w->header_parse_tries = 0;
  771. w->header_parse_last_size = 0;
  772. web_client_disable_wait_receive(w);
  773. return HTTP_VALIDATION_EXCESS_REQUEST_DATA;
  774. }
  775. }
  776. web_client_enable_wait_receive(w);
  777. return HTTP_VALIDATION_INCOMPLETE;
  778. }
  779. //After the method we have the path and query string together
  780. encoded_url = s;
  781. //we search for the position where we have " HTTP/", because it finishes the user request
  782. s = url_find_protocol(s);
  783. // incomplete requests
  784. if(unlikely(!*s)) {
  785. web_client_enable_wait_receive(w);
  786. return HTTP_VALIDATION_INCOMPLETE;
  787. }
  788. // we have the end of encoded_url - remember it
  789. char *ue = s;
  790. // make sure we have complete request
  791. // complete requests contain: \r\n\r\n
  792. while(*s) {
  793. // find a line feed
  794. while(*s && *s++ != '\r');
  795. // did we reach the end?
  796. if(unlikely(!*s)) break;
  797. // is it \r\n ?
  798. if(likely(*s++ == '\n')) {
  799. // is it again \r\n ? (header end)
  800. if(unlikely(*s == '\r' && s[1] == '\n')) {
  801. // a valid complete HTTP request found
  802. char c = *ue;
  803. *ue = '\0';
  804. web_client_decode_path_and_query_string(w, encoded_url);
  805. *ue = c;
  806. #ifdef ENABLE_HTTPS
  807. if ( (!web_client_check_unix(w)) && (netdata_ssl_srv_ctx) ) {
  808. if ((w->ssl.conn) && ((w->ssl.flags & NETDATA_SSL_NO_HANDSHAKE) && (web_client_is_using_ssl_force(w) || web_client_is_using_ssl_default(w)) && (w->mode != WEB_CLIENT_MODE_STREAM)) ) {
  809. w->header_parse_tries = 0;
  810. w->header_parse_last_size = 0;
  811. web_client_disable_wait_receive(w);
  812. return HTTP_VALIDATION_REDIRECT;
  813. }
  814. }
  815. #endif
  816. w->header_parse_tries = 0;
  817. w->header_parse_last_size = 0;
  818. web_client_disable_wait_receive(w);
  819. return HTTP_VALIDATION_OK;
  820. }
  821. // another header line
  822. s = http_header_parse(w, s, (w->mode == WEB_CLIENT_MODE_STREAM)); // parse user agent
  823. }
  824. }
  825. // incomplete request
  826. web_client_enable_wait_receive(w);
  827. return HTTP_VALIDATION_INCOMPLETE;
  828. }
  829. static inline ssize_t web_client_send_data(struct web_client *w,const void *buf,size_t len, int flags)
  830. {
  831. ssize_t bytes;
  832. #ifdef ENABLE_HTTPS
  833. if ( (!web_client_check_unix(w)) && (netdata_ssl_srv_ctx) ) {
  834. if ( ( w->ssl.conn ) && ( !w->ssl.flags ) ){
  835. bytes = netdata_ssl_write(w->ssl.conn, buf, len) ;
  836. web_client_enable_wait_from_ssl(w, bytes);
  837. } else {
  838. bytes = send(w->ofd,buf, len , flags);
  839. }
  840. } else {
  841. bytes = send(w->ofd,buf, len , flags);
  842. }
  843. #else
  844. bytes = send(w->ofd, buf, len, flags);
  845. #endif
  846. return bytes;
  847. }
  848. void web_client_build_http_header(struct web_client *w) {
  849. if(unlikely(w->response.code != HTTP_RESP_OK))
  850. buffer_no_cacheable(w->response.data);
  851. // set a proper expiration date, if not already set
  852. if(unlikely(!w->response.data->expires)) {
  853. if(w->response.data->options & WB_CONTENT_NO_CACHEABLE)
  854. w->response.data->expires = w->timings.tv_ready.tv_sec + localhost->rrd_update_every;
  855. else
  856. w->response.data->expires = w->timings.tv_ready.tv_sec + 86400;
  857. }
  858. // prepare the HTTP response header
  859. debug(D_WEB_CLIENT, "%llu: Generating HTTP header with response %d.", w->id, w->response.code);
  860. const char *content_type_string = web_content_type_to_string(w->response.data->content_type);
  861. const char *code_msg = web_response_code_to_string(w->response.code);
  862. // prepare the last modified and expiration dates
  863. char date[32], edate[32];
  864. {
  865. struct tm tmbuf, *tm;
  866. tm = gmtime_r(&w->response.data->date, &tmbuf);
  867. strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %Z", tm);
  868. tm = gmtime_r(&w->response.data->expires, &tmbuf);
  869. strftime(edate, sizeof(edate), "%a, %d %b %Y %H:%M:%S %Z", tm);
  870. }
  871. if (w->response.code == HTTP_RESP_MOVED_PERM) {
  872. buffer_sprintf(w->response.header_output,
  873. "HTTP/1.1 %d %s\r\n"
  874. "Location: https://%s%s\r\n",
  875. w->response.code, code_msg,
  876. w->server_host ? w->server_host : "",
  877. buffer_tostring(w->url_as_received));
  878. }else {
  879. buffer_sprintf(w->response.header_output,
  880. "HTTP/1.1 %d %s\r\n"
  881. "Connection: %s\r\n"
  882. "Server: Netdata Embedded HTTP Server %s\r\n"
  883. "Access-Control-Allow-Origin: %s\r\n"
  884. "Access-Control-Allow-Credentials: true\r\n"
  885. "Content-Type: %s\r\n"
  886. "Date: %s\r\n",
  887. w->response.code,
  888. code_msg,
  889. web_client_has_keepalive(w)?"keep-alive":"close",
  890. VERSION,
  891. w->origin ? w->origin : "*",
  892. content_type_string,
  893. date);
  894. }
  895. if(unlikely(web_x_frame_options))
  896. buffer_sprintf(w->response.header_output, "X-Frame-Options: %s\r\n", web_x_frame_options);
  897. if(w->response.has_cookies) {
  898. if(respect_web_browser_do_not_track_policy)
  899. buffer_sprintf(w->response.header_output,
  900. "Tk: T;cookies\r\n");
  901. }
  902. else {
  903. if(respect_web_browser_do_not_track_policy) {
  904. if(web_client_has_tracking_required(w))
  905. buffer_sprintf(w->response.header_output,
  906. "Tk: T;cookies\r\n");
  907. else
  908. buffer_sprintf(w->response.header_output,
  909. "Tk: N\r\n");
  910. }
  911. }
  912. if(w->mode == WEB_CLIENT_MODE_OPTIONS) {
  913. buffer_strcat(w->response.header_output,
  914. "Access-Control-Allow-Methods: GET, OPTIONS\r\n"
  915. "Access-Control-Allow-Headers: accept, x-requested-with, origin, content-type, cookie, pragma, cache-control, x-auth-token\r\n"
  916. "Access-Control-Max-Age: 1209600\r\n" // 86400 * 14
  917. );
  918. }
  919. else {
  920. buffer_sprintf(w->response.header_output,
  921. "Cache-Control: %s\r\n"
  922. "Expires: %s\r\n",
  923. (w->response.data->options & WB_CONTENT_NO_CACHEABLE)?"no-cache, no-store, must-revalidate\r\nPragma: no-cache":"public",
  924. edate);
  925. }
  926. // copy a possibly available custom header
  927. if(unlikely(buffer_strlen(w->response.header)))
  928. buffer_strcat(w->response.header_output, buffer_tostring(w->response.header));
  929. // headers related to the transfer method
  930. if(likely(w->response.zoutput))
  931. buffer_strcat(w->response.header_output, "Content-Encoding: gzip\r\n");
  932. if(likely(w->flags & WEB_CLIENT_CHUNKED_TRANSFER))
  933. buffer_strcat(w->response.header_output, "Transfer-Encoding: chunked\r\n");
  934. else {
  935. if(likely((w->response.data->len || w->response.rlen))) {
  936. // we know the content length, put it
  937. buffer_sprintf(w->response.header_output, "Content-Length: %zu\r\n", w->response.data->len? w->response.data->len: w->response.rlen);
  938. }
  939. else {
  940. // we don't know the content length, disable keep-alive
  941. web_client_disable_keepalive(w);
  942. }
  943. }
  944. // end of HTTP header
  945. buffer_strcat(w->response.header_output, "\r\n");
  946. }
  947. static inline void web_client_send_http_header(struct web_client *w) {
  948. web_client_build_http_header(w);
  949. // sent the HTTP header
  950. debug(D_WEB_DATA, "%llu: Sending response HTTP header of size %zu: '%s'"
  951. , w->id
  952. , buffer_strlen(w->response.header_output)
  953. , buffer_tostring(w->response.header_output)
  954. );
  955. web_client_crock_socket(w);
  956. size_t count = 0;
  957. ssize_t bytes;
  958. #ifdef ENABLE_HTTPS
  959. if ( (!web_client_check_unix(w)) && (netdata_ssl_srv_ctx) ) {
  960. if ( ( w->ssl.conn ) && ( w->ssl.flags == NETDATA_SSL_HANDSHAKE_COMPLETE ) ) {
  961. bytes = netdata_ssl_write(w->ssl.conn, buffer_tostring(w->response.header_output), buffer_strlen(w->response.header_output));
  962. web_client_enable_wait_from_ssl(w, bytes);
  963. }
  964. else {
  965. while((bytes = send(w->ofd, buffer_tostring(w->response.header_output), buffer_strlen(w->response.header_output), 0)) == -1) {
  966. count++;
  967. if(count > 100 || (errno != EAGAIN && errno != EWOULDBLOCK)) {
  968. error("Cannot send HTTP headers to web client.");
  969. break;
  970. }
  971. }
  972. }
  973. }
  974. else {
  975. while((bytes = send(w->ofd, buffer_tostring(w->response.header_output), buffer_strlen(w->response.header_output), 0)) == -1) {
  976. count++;
  977. if(count > 100 || (errno != EAGAIN && errno != EWOULDBLOCK)) {
  978. error("Cannot send HTTP headers to web client.");
  979. break;
  980. }
  981. }
  982. }
  983. #else
  984. while((bytes = send(w->ofd, buffer_tostring(w->response.header_output), buffer_strlen(w->response.header_output), 0)) == -1) {
  985. count++;
  986. if(count > 100 || (errno != EAGAIN && errno != EWOULDBLOCK)) {
  987. error("Cannot send HTTP headers to web client.");
  988. break;
  989. }
  990. }
  991. #endif
  992. if(bytes != (ssize_t) buffer_strlen(w->response.header_output)) {
  993. if(bytes > 0)
  994. w->statistics.sent_bytes += bytes;
  995. if (bytes < 0) {
  996. error("HTTP headers failed to be sent (I sent %zu bytes but the system sent %zd bytes). Closing web client."
  997. , buffer_strlen(w->response.header_output)
  998. , bytes);
  999. WEB_CLIENT_IS_DEAD(w);
  1000. return;
  1001. }
  1002. }
  1003. else
  1004. w->statistics.sent_bytes += bytes;
  1005. }
  1006. static inline int web_client_switch_host(RRDHOST *host, struct web_client *w, char *url, bool nodeid, int (*func)(RRDHOST *, struct web_client *, char *)) {
  1007. static uint32_t hash_localhost = 0;
  1008. if(unlikely(!hash_localhost)) {
  1009. hash_localhost = simple_hash("localhost");
  1010. }
  1011. if(host != localhost) {
  1012. buffer_flush(w->response.data);
  1013. buffer_strcat(w->response.data, "Nesting of hosts is not allowed.");
  1014. return HTTP_RESP_BAD_REQUEST;
  1015. }
  1016. char *tok = strsep_skip_consecutive_separators(&url, "/");
  1017. if(tok && *tok) {
  1018. debug(D_WEB_CLIENT, "%llu: Searching for host with name '%s'.", w->id, tok);
  1019. if(nodeid) {
  1020. host = find_host_by_node_id(tok);
  1021. if(!host) {
  1022. host = rrdhost_find_by_hostname(tok);
  1023. if (!host)
  1024. host = rrdhost_find_by_guid(tok);
  1025. }
  1026. }
  1027. else {
  1028. host = rrdhost_find_by_hostname(tok);
  1029. if(!host) {
  1030. host = rrdhost_find_by_guid(tok);
  1031. if (!host)
  1032. host = find_host_by_node_id(tok);
  1033. }
  1034. }
  1035. if(!host) {
  1036. // we didn't find it, but it may be a uuid case mismatch for MACHINE_GUID
  1037. // so, recreate the machine guid in lower-case.
  1038. uuid_t uuid;
  1039. char txt[UUID_STR_LEN];
  1040. if (uuid_parse(tok, uuid) == 0) {
  1041. uuid_unparse_lower(uuid, txt);
  1042. host = rrdhost_find_by_guid(txt);
  1043. }
  1044. }
  1045. if (host) {
  1046. if(!url) { //no delim found
  1047. debug(D_WEB_CLIENT, "%llu: URL doesn't end with / generating redirect.", w->id);
  1048. char *protocol, *url_host;
  1049. #ifdef ENABLE_HTTPS
  1050. protocol = ((w->ssl.conn && !w->ssl.flags) || w->ssl.flags & NETDATA_SSL_PROXY_HTTPS) ? "https" : "http";
  1051. #else
  1052. protocol = "http";
  1053. #endif
  1054. url_host = w->forwarded_host;
  1055. if(!url_host) {
  1056. url_host = w->server_host;
  1057. if(!url_host) url_host = "";
  1058. }
  1059. buffer_sprintf(w->response.header, "Location: %s://%s/%s/%s/%s",
  1060. protocol, url_host, nodeid?"node":"host", tok, buffer_tostring(w->url_path_decoded));
  1061. if(buffer_strlen(w->url_query_string_decoded)) {
  1062. const char *query_string = buffer_tostring(w->url_query_string_decoded);
  1063. if(*query_string) {
  1064. if(*query_string != '?')
  1065. buffer_fast_strcat(w->response.header, "?", 1);
  1066. buffer_strcat(w->response.header, query_string);
  1067. }
  1068. }
  1069. buffer_fast_strcat(w->response.header, "\r\n", 2);
  1070. buffer_strcat(w->response.data, "Permanent redirect");
  1071. return HTTP_RESP_REDIR_PERM;
  1072. }
  1073. size_t len = strlen(url) + 2;
  1074. char buf[len];
  1075. buf[0] = '/';
  1076. strcpy(&buf[1], url);
  1077. buf[len - 1] = '\0';
  1078. buffer_flush(w->url_path_decoded);
  1079. buffer_strcat(w->url_path_decoded, buf);
  1080. return func(host, w, buf);
  1081. }
  1082. }
  1083. buffer_flush(w->response.data);
  1084. w->response.data->content_type = CT_TEXT_HTML;
  1085. buffer_strcat(w->response.data, "This netdata does not maintain a database for host: ");
  1086. buffer_strcat_htmlescape(w->response.data, tok?tok:"");
  1087. return HTTP_RESP_NOT_FOUND;
  1088. }
  1089. int web_client_api_request_with_node_selection(RRDHOST *host, struct web_client *w, char *decoded_url_path) {
  1090. static uint32_t
  1091. hash_api = 0,
  1092. hash_host = 0,
  1093. hash_node = 0;
  1094. if(unlikely(!hash_api)) {
  1095. hash_api = simple_hash("api");
  1096. hash_host = simple_hash("host");
  1097. hash_node = simple_hash("node");
  1098. }
  1099. char *tok = strsep_skip_consecutive_separators(&decoded_url_path, "/?");
  1100. if(likely(tok && *tok)) {
  1101. uint32_t hash = simple_hash(tok);
  1102. if(unlikely(hash == hash_api && strcmp(tok, "api") == 0)) {
  1103. // current API
  1104. debug(D_WEB_CLIENT_ACCESS, "%llu: API request ...", w->id);
  1105. return check_host_and_call(host, w, decoded_url_path, web_client_api_request);
  1106. }
  1107. else if(unlikely((hash == hash_host && strcmp(tok, "host") == 0) || (hash == hash_node && strcmp(tok, "node") == 0))) {
  1108. // host switching
  1109. debug(D_WEB_CLIENT_ACCESS, "%llu: host switch request ...", w->id);
  1110. return web_client_switch_host(host, w, decoded_url_path, hash == hash_node, web_client_api_request_with_node_selection);
  1111. }
  1112. }
  1113. buffer_flush(w->response.data);
  1114. buffer_strcat(w->response.data, "Unknown API endpoint.");
  1115. w->response.data->content_type = CT_TEXT_HTML;
  1116. return HTTP_RESP_NOT_FOUND;
  1117. }
  1118. static inline int web_client_process_url(RRDHOST *host, struct web_client *w, char *decoded_url_path) {
  1119. if(unlikely(!service_running(ABILITY_WEB_REQUESTS)))
  1120. return web_client_permission_denied(w);
  1121. static uint32_t
  1122. hash_api = 0,
  1123. hash_netdata_conf = 0,
  1124. hash_host = 0,
  1125. hash_node = 0;
  1126. #ifdef NETDATA_INTERNAL_CHECKS
  1127. static uint32_t hash_exit = 0, hash_debug = 0, hash_mirror = 0;
  1128. #endif
  1129. if(unlikely(!hash_api)) {
  1130. hash_api = simple_hash("api");
  1131. hash_netdata_conf = simple_hash("netdata.conf");
  1132. hash_host = simple_hash("host");
  1133. hash_node = simple_hash("node");
  1134. #ifdef NETDATA_INTERNAL_CHECKS
  1135. hash_exit = simple_hash("exit");
  1136. hash_debug = simple_hash("debug");
  1137. hash_mirror = simple_hash("mirror");
  1138. #endif
  1139. }
  1140. // keep a copy of the decoded path, in case we need to serve it as a filename
  1141. char filename[FILENAME_MAX + 1];
  1142. strncpyz(filename, buffer_tostring(w->url_path_decoded), FILENAME_MAX);
  1143. char *tok = strsep_skip_consecutive_separators(&decoded_url_path, "/?");
  1144. if(likely(tok && *tok)) {
  1145. uint32_t hash = simple_hash(tok);
  1146. debug(D_WEB_CLIENT, "%llu: Processing command '%s'.", w->id, tok);
  1147. if(unlikely(hash == hash_api && strcmp(tok, "api") == 0)) { // current API
  1148. debug(D_WEB_CLIENT_ACCESS, "%llu: API request ...", w->id);
  1149. return check_host_and_call(host, w, decoded_url_path, web_client_api_request);
  1150. }
  1151. else if(unlikely((hash == hash_host && strcmp(tok, "host") == 0) || (hash == hash_node && strcmp(tok, "node") == 0))) { // host switching
  1152. debug(D_WEB_CLIENT_ACCESS, "%llu: host switch request ...", w->id);
  1153. return web_client_switch_host(host, w, decoded_url_path, hash == hash_node, web_client_process_url);
  1154. }
  1155. else if(unlikely(hash == hash_netdata_conf && strcmp(tok, "netdata.conf") == 0)) { // netdata.conf
  1156. if(unlikely(!web_client_can_access_netdataconf(w)))
  1157. return web_client_permission_denied(w);
  1158. debug(D_WEB_CLIENT_ACCESS, "%llu: generating netdata.conf ...", w->id);
  1159. w->response.data->content_type = CT_TEXT_PLAIN;
  1160. buffer_flush(w->response.data);
  1161. config_generate(w->response.data, 0);
  1162. return HTTP_RESP_OK;
  1163. }
  1164. #ifdef NETDATA_INTERNAL_CHECKS
  1165. else if(unlikely(hash == hash_exit && strcmp(tok, "exit") == 0)) {
  1166. if(unlikely(!web_client_can_access_netdataconf(w)))
  1167. return web_client_permission_denied(w);
  1168. w->response.data->content_type = CT_TEXT_PLAIN;
  1169. buffer_flush(w->response.data);
  1170. if(!netdata_exit)
  1171. buffer_strcat(w->response.data, "ok, will do...");
  1172. else
  1173. buffer_strcat(w->response.data, "I am doing it already");
  1174. error("web request to exit received.");
  1175. netdata_cleanup_and_exit(0);
  1176. return HTTP_RESP_OK;
  1177. }
  1178. else if(unlikely(hash == hash_debug && strcmp(tok, "debug") == 0)) {
  1179. if(unlikely(!web_client_can_access_netdataconf(w)))
  1180. return web_client_permission_denied(w);
  1181. buffer_flush(w->response.data);
  1182. // get the name of the data to show
  1183. tok = strsep_skip_consecutive_separators(&decoded_url_path, "&");
  1184. if(tok && *tok) {
  1185. debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
  1186. // do we have such a data set?
  1187. RRDSET *st = rrdset_find_byname(host, tok);
  1188. if(!st) st = rrdset_find(host, tok);
  1189. if(!st) {
  1190. w->response.data->content_type = CT_TEXT_HTML;
  1191. buffer_strcat(w->response.data, "Chart is not found: ");
  1192. buffer_strcat_htmlescape(w->response.data, tok);
  1193. debug(D_WEB_CLIENT_ACCESS, "%llu: %s is not found.", w->id, tok);
  1194. return HTTP_RESP_NOT_FOUND;
  1195. }
  1196. debug_flags |= D_RRD_STATS;
  1197. if(rrdset_flag_check(st, RRDSET_FLAG_DEBUG))
  1198. rrdset_flag_clear(st, RRDSET_FLAG_DEBUG);
  1199. else
  1200. rrdset_flag_set(st, RRDSET_FLAG_DEBUG);
  1201. w->response.data->content_type = CT_TEXT_HTML;
  1202. buffer_sprintf(w->response.data, "Chart has now debug %s: ", rrdset_flag_check(st, RRDSET_FLAG_DEBUG)?"enabled":"disabled");
  1203. buffer_strcat_htmlescape(w->response.data, tok);
  1204. debug(D_WEB_CLIENT_ACCESS, "%llu: debug for %s is %s.", w->id, tok, rrdset_flag_check(st, RRDSET_FLAG_DEBUG)?"enabled":"disabled");
  1205. return HTTP_RESP_OK;
  1206. }
  1207. buffer_flush(w->response.data);
  1208. buffer_strcat(w->response.data, "debug which chart?\r\n");
  1209. return HTTP_RESP_BAD_REQUEST;
  1210. }
  1211. else if(unlikely(hash == hash_mirror && strcmp(tok, "mirror") == 0)) {
  1212. if(unlikely(!web_client_can_access_netdataconf(w)))
  1213. return web_client_permission_denied(w);
  1214. debug(D_WEB_CLIENT_ACCESS, "%llu: Mirroring...", w->id);
  1215. // replace the zero bytes with spaces
  1216. buffer_char_replace(w->response.data, '\0', ' ');
  1217. // just leave the buffer as-is
  1218. // it will be copied back to the client
  1219. return HTTP_RESP_OK;
  1220. }
  1221. #endif /* NETDATA_INTERNAL_CHECKS */
  1222. }
  1223. buffer_flush(w->response.data);
  1224. return mysendfile(w, filename);
  1225. }
  1226. void web_client_process_request(struct web_client *w) {
  1227. // start timing us
  1228. web_client_timeout_checkpoint_init(w);
  1229. switch(http_request_validate(w)) {
  1230. case HTTP_VALIDATION_OK:
  1231. switch(w->mode) {
  1232. case WEB_CLIENT_MODE_STREAM:
  1233. if(unlikely(!web_client_can_access_stream(w))) {
  1234. web_client_permission_denied(w);
  1235. return;
  1236. }
  1237. w->response.code = rrdpush_receiver_thread_spawn(w, (char *)buffer_tostring(w->url_query_string_decoded));
  1238. return;
  1239. case WEB_CLIENT_MODE_OPTIONS:
  1240. if(unlikely(
  1241. !web_client_can_access_dashboard(w) &&
  1242. !web_client_can_access_registry(w) &&
  1243. !web_client_can_access_badges(w) &&
  1244. !web_client_can_access_mgmt(w) &&
  1245. !web_client_can_access_netdataconf(w)
  1246. )) {
  1247. web_client_permission_denied(w);
  1248. break;
  1249. }
  1250. w->response.data->content_type = CT_TEXT_PLAIN;
  1251. buffer_flush(w->response.data);
  1252. buffer_strcat(w->response.data, "OK");
  1253. w->response.code = HTTP_RESP_OK;
  1254. break;
  1255. case WEB_CLIENT_MODE_FILECOPY:
  1256. case WEB_CLIENT_MODE_POST:
  1257. case WEB_CLIENT_MODE_GET:
  1258. if(unlikely(
  1259. !web_client_can_access_dashboard(w) &&
  1260. !web_client_can_access_registry(w) &&
  1261. !web_client_can_access_badges(w) &&
  1262. !web_client_can_access_mgmt(w) &&
  1263. !web_client_can_access_netdataconf(w)
  1264. )) {
  1265. web_client_permission_denied(w);
  1266. break;
  1267. }
  1268. w->response.code = web_client_process_url(localhost, w, (char *)buffer_tostring(w->url_path_decoded));
  1269. break;
  1270. }
  1271. break;
  1272. case HTTP_VALIDATION_INCOMPLETE:
  1273. if(w->response.data->len > NETDATA_WEB_REQUEST_MAX_SIZE) {
  1274. buffer_flush(w->url_as_received);
  1275. buffer_strcat(w->url_as_received, "too big request");
  1276. debug(D_WEB_CLIENT_ACCESS, "%llu: Received request is too big (%zu bytes).", w->id, w->response.data->len);
  1277. size_t len = w->response.data->len;
  1278. buffer_flush(w->response.data);
  1279. buffer_sprintf(w->response.data, "Received request is too big (received %zu bytes, max is %zu bytes).\r\n", len, (size_t)NETDATA_WEB_REQUEST_MAX_SIZE);
  1280. w->response.code = HTTP_RESP_BAD_REQUEST;
  1281. }
  1282. else {
  1283. // wait for more data
  1284. // set to normal to prevent web_server_rcv_callback
  1285. // from going into stream mode
  1286. if (w->mode == WEB_CLIENT_MODE_STREAM)
  1287. w->mode = WEB_CLIENT_MODE_GET;
  1288. return;
  1289. }
  1290. break;
  1291. #ifdef ENABLE_HTTPS
  1292. case HTTP_VALIDATION_REDIRECT:
  1293. {
  1294. buffer_flush(w->response.data);
  1295. w->response.data->content_type = CT_TEXT_HTML;
  1296. buffer_strcat(w->response.data,
  1297. "<!DOCTYPE html><!-- SPDX-License-Identifier: GPL-3.0-or-later --><html>"
  1298. "<body onload=\"window.location.href ='https://'+ window.location.hostname +"
  1299. " ':' + window.location.port + window.location.pathname + window.location.search\">"
  1300. "Redirecting to safety connection, case your browser does not support redirection, please"
  1301. " click <a onclick=\"window.location.href ='https://'+ window.location.hostname + ':' "
  1302. " + window.location.port + window.location.pathname + window.location.search\">here</a>."
  1303. "</body></html>");
  1304. w->response.code = HTTP_RESP_MOVED_PERM;
  1305. break;
  1306. }
  1307. #endif
  1308. case HTTP_VALIDATION_MALFORMED_URL:
  1309. debug(D_WEB_CLIENT_ACCESS, "%llu: Malformed URL '%s'.", w->id, w->response.data->buffer);
  1310. buffer_flush(w->response.data);
  1311. buffer_strcat(w->response.data, "Malformed URL...\r\n");
  1312. w->response.code = HTTP_RESP_BAD_REQUEST;
  1313. break;
  1314. case HTTP_VALIDATION_EXCESS_REQUEST_DATA:
  1315. debug(D_WEB_CLIENT_ACCESS, "%llu: Excess data in request '%s'.", w->id, w->response.data->buffer);
  1316. buffer_flush(w->response.data);
  1317. buffer_strcat(w->response.data, "Excess data in request.\r\n");
  1318. w->response.code = HTTP_RESP_BAD_REQUEST;
  1319. break;
  1320. case HTTP_VALIDATION_TOO_MANY_READ_RETRIES:
  1321. debug(D_WEB_CLIENT_ACCESS, "%llu: Too many retries to read request '%s'.", w->id, w->response.data->buffer);
  1322. buffer_flush(w->response.data);
  1323. buffer_strcat(w->response.data, "Too many retries to read request.\r\n");
  1324. w->response.code = HTTP_RESP_BAD_REQUEST;
  1325. break;
  1326. case HTTP_VALIDATION_NOT_SUPPORTED:
  1327. debug(D_WEB_CLIENT_ACCESS, "%llu: HTTP method requested is not supported '%s'.", w->id, w->response.data->buffer);
  1328. buffer_flush(w->response.data);
  1329. buffer_strcat(w->response.data, "HTTP method requested is not supported...\r\n");
  1330. w->response.code = HTTP_RESP_BAD_REQUEST;
  1331. break;
  1332. }
  1333. // keep track of the processing time
  1334. web_client_timeout_checkpoint_response_ready(w, NULL);
  1335. w->response.sent = 0;
  1336. // set a proper last modified date
  1337. if(unlikely(!w->response.data->date))
  1338. w->response.data->date = w->timings.tv_ready.tv_sec;
  1339. web_client_send_http_header(w);
  1340. // enable sending immediately if we have data
  1341. if(w->response.data->len) web_client_enable_wait_send(w);
  1342. else web_client_disable_wait_send(w);
  1343. switch(w->mode) {
  1344. case WEB_CLIENT_MODE_STREAM:
  1345. debug(D_WEB_CLIENT, "%llu: STREAM done.", w->id);
  1346. break;
  1347. case WEB_CLIENT_MODE_OPTIONS:
  1348. debug(D_WEB_CLIENT, "%llu: Done preparing the OPTIONS response. Sending data (%zu bytes) to client.", w->id, w->response.data->len);
  1349. break;
  1350. case WEB_CLIENT_MODE_POST:
  1351. case WEB_CLIENT_MODE_GET:
  1352. debug(D_WEB_CLIENT, "%llu: Done preparing the response. Sending data (%zu bytes) to client.", w->id, w->response.data->len);
  1353. break;
  1354. case WEB_CLIENT_MODE_FILECOPY:
  1355. if(w->response.rlen) {
  1356. debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending data file of %zu bytes to client.", w->id, w->response.rlen);
  1357. web_client_enable_wait_receive(w);
  1358. /*
  1359. // utilize the kernel sendfile() for copying the file to the socket.
  1360. // this block of code can be commented, without anything missing.
  1361. // when it is commented, the program will copy the data using async I/O.
  1362. {
  1363. long len = sendfile(w->ofd, w->ifd, NULL, w->response.data->rbytes);
  1364. if(len != w->response.data->rbytes)
  1365. error("%llu: sendfile() should copy %ld bytes, but copied %ld. Falling back to manual copy.", w->id, w->response.data->rbytes, len);
  1366. else
  1367. web_client_request_done(w);
  1368. }
  1369. */
  1370. }
  1371. else
  1372. debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending an unknown amount of bytes to client.", w->id);
  1373. break;
  1374. default:
  1375. fatal("%llu: Unknown client mode %u.", w->id, w->mode);
  1376. break;
  1377. }
  1378. }
  1379. ssize_t web_client_send_chunk_header(struct web_client *w, size_t len)
  1380. {
  1381. debug(D_DEFLATE, "%llu: OPEN CHUNK of %zu bytes (hex: %zx).", w->id, len, len);
  1382. char buf[24];
  1383. ssize_t bytes;
  1384. bytes = (ssize_t)sprintf(buf, "%zX\r\n", len);
  1385. buf[bytes] = 0x00;
  1386. bytes = web_client_send_data(w,buf,strlen(buf),0);
  1387. if(bytes > 0) {
  1388. debug(D_DEFLATE, "%llu: Sent chunk header %zd bytes.", w->id, bytes);
  1389. w->statistics.sent_bytes += bytes;
  1390. }
  1391. else if(bytes == 0) {
  1392. debug(D_WEB_CLIENT, "%llu: Did not send chunk header to the client.", w->id);
  1393. }
  1394. else {
  1395. debug(D_WEB_CLIENT, "%llu: Failed to send chunk header to client.", w->id);
  1396. WEB_CLIENT_IS_DEAD(w);
  1397. }
  1398. return bytes;
  1399. }
  1400. ssize_t web_client_send_chunk_close(struct web_client *w)
  1401. {
  1402. //debug(D_DEFLATE, "%llu: CLOSE CHUNK.", w->id);
  1403. ssize_t bytes;
  1404. bytes = web_client_send_data(w,"\r\n",2,0);
  1405. if(bytes > 0) {
  1406. debug(D_DEFLATE, "%llu: Sent chunk suffix %zd bytes.", w->id, bytes);
  1407. w->statistics.sent_bytes += bytes;
  1408. }
  1409. else if(bytes == 0) {
  1410. debug(D_WEB_CLIENT, "%llu: Did not send chunk suffix to the client.", w->id);
  1411. }
  1412. else {
  1413. debug(D_WEB_CLIENT, "%llu: Failed to send chunk suffix to client.", w->id);
  1414. WEB_CLIENT_IS_DEAD(w);
  1415. }
  1416. return bytes;
  1417. }
  1418. ssize_t web_client_send_chunk_finalize(struct web_client *w)
  1419. {
  1420. //debug(D_DEFLATE, "%llu: FINALIZE CHUNK.", w->id);
  1421. ssize_t bytes;
  1422. bytes = web_client_send_data(w,"\r\n0\r\n\r\n",7,0);
  1423. if(bytes > 0) {
  1424. debug(D_DEFLATE, "%llu: Sent chunk suffix %zd bytes.", w->id, bytes);
  1425. w->statistics.sent_bytes += bytes;
  1426. }
  1427. else if(bytes == 0) {
  1428. debug(D_WEB_CLIENT, "%llu: Did not send chunk finalize suffix to the client.", w->id);
  1429. }
  1430. else {
  1431. debug(D_WEB_CLIENT, "%llu: Failed to send chunk finalize suffix to client.", w->id);
  1432. WEB_CLIENT_IS_DEAD(w);
  1433. }
  1434. return bytes;
  1435. }
  1436. #ifdef NETDATA_WITH_ZLIB
  1437. ssize_t web_client_send_deflate(struct web_client *w)
  1438. {
  1439. ssize_t len = 0, t = 0;
  1440. // when using compression,
  1441. // w->response.sent is the amount of bytes passed through compression
  1442. debug(D_DEFLATE, "%llu: web_client_send_deflate(): w->response.data->len = %zu, w->response.sent = %zu, w->response.zhave = %zu, w->response.zsent = %zu, w->response.zstream.avail_in = %u, w->response.zstream.avail_out = %u, w->response.zstream.total_in = %lu, w->response.zstream.total_out = %lu.",
  1443. w->id, w->response.data->len, w->response.sent, w->response.zhave, w->response.zsent, w->response.zstream.avail_in, w->response.zstream.avail_out, w->response.zstream.total_in, w->response.zstream.total_out);
  1444. if(w->response.data->len - w->response.sent == 0 && w->response.zstream.avail_in == 0 && w->response.zhave == w->response.zsent && w->response.zstream.avail_out != 0) {
  1445. // there is nothing to send
  1446. debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
  1447. // finalize the chunk
  1448. if(w->response.sent != 0) {
  1449. t = web_client_send_chunk_finalize(w);
  1450. if(t < 0) return t;
  1451. }
  1452. if(w->mode == WEB_CLIENT_MODE_FILECOPY && web_client_has_wait_receive(w) && w->response.rlen && w->response.rlen > w->response.data->len) {
  1453. // we have to wait, more data will come
  1454. debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
  1455. web_client_disable_wait_send(w);
  1456. return t;
  1457. }
  1458. if(unlikely(!web_client_has_keepalive(w))) {
  1459. debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %zu bytes sent.", w->id, w->response.sent);
  1460. WEB_CLIENT_IS_DEAD(w);
  1461. return t;
  1462. }
  1463. // reset the client
  1464. web_client_request_done(w);
  1465. debug(D_WEB_CLIENT, "%llu: Done sending all data on socket.", w->id);
  1466. return t;
  1467. }
  1468. if(w->response.zhave == w->response.zsent) {
  1469. // compress more input data
  1470. // close the previous open chunk
  1471. if(w->response.sent != 0) {
  1472. t = web_client_send_chunk_close(w);
  1473. if(t < 0) return t;
  1474. }
  1475. debug(D_DEFLATE, "%llu: Compressing %zu new bytes starting from %zu (and %u left behind).", w->id, (w->response.data->len - w->response.sent), w->response.sent, w->response.zstream.avail_in);
  1476. // give the compressor all the data not passed through the compressor yet
  1477. if(w->response.data->len > w->response.sent) {
  1478. w->response.zstream.next_in = (Bytef *)&w->response.data->buffer[w->response.sent - w->response.zstream.avail_in];
  1479. w->response.zstream.avail_in += (uInt) (w->response.data->len - w->response.sent);
  1480. }
  1481. // reset the compressor output buffer
  1482. w->response.zstream.next_out = w->response.zbuffer;
  1483. w->response.zstream.avail_out = NETDATA_WEB_RESPONSE_ZLIB_CHUNK_SIZE;
  1484. // ask for FINISH if we have all the input
  1485. int flush = Z_SYNC_FLUSH;
  1486. if((w->mode == WEB_CLIENT_MODE_GET || w->mode == WEB_CLIENT_MODE_POST)
  1487. || (w->mode == WEB_CLIENT_MODE_FILECOPY && !web_client_has_wait_receive(w) && w->response.data->len == w->response.rlen)) {
  1488. flush = Z_FINISH;
  1489. debug(D_DEFLATE, "%llu: Requesting Z_FINISH, if possible.", w->id);
  1490. }
  1491. else {
  1492. debug(D_DEFLATE, "%llu: Requesting Z_SYNC_FLUSH.", w->id);
  1493. }
  1494. // compress
  1495. if(deflate(&w->response.zstream, flush) == Z_STREAM_ERROR) {
  1496. error("%llu: Compression failed. Closing down client.", w->id);
  1497. web_client_request_done(w);
  1498. return(-1);
  1499. }
  1500. w->response.zhave = NETDATA_WEB_RESPONSE_ZLIB_CHUNK_SIZE - w->response.zstream.avail_out;
  1501. w->response.zsent = 0;
  1502. // keep track of the bytes passed through the compressor
  1503. w->response.sent = w->response.data->len;
  1504. debug(D_DEFLATE, "%llu: Compression produced %zu bytes.", w->id, w->response.zhave);
  1505. // open a new chunk
  1506. ssize_t t2 = web_client_send_chunk_header(w, w->response.zhave);
  1507. if(t2 < 0) return t2;
  1508. t += t2;
  1509. }
  1510. debug(D_WEB_CLIENT, "%llu: Sending %zu bytes of data (+%zd of chunk header).", w->id, w->response.zhave - w->response.zsent, t);
  1511. len = web_client_send_data(w,&w->response.zbuffer[w->response.zsent], (size_t) (w->response.zhave - w->response.zsent), MSG_DONTWAIT);
  1512. if(len > 0) {
  1513. w->statistics.sent_bytes += len;
  1514. w->response.zsent += len;
  1515. len += t;
  1516. debug(D_WEB_CLIENT, "%llu: Sent %zd bytes.", w->id, len);
  1517. }
  1518. else if(len == 0) {
  1519. debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client (zhave = %zu, zsent = %zu, need to send = %zu).",
  1520. w->id, w->response.zhave, w->response.zsent, w->response.zhave - w->response.zsent);
  1521. }
  1522. else {
  1523. debug(D_WEB_CLIENT, "%llu: Failed to send data to client.", w->id);
  1524. WEB_CLIENT_IS_DEAD(w);
  1525. }
  1526. return(len);
  1527. }
  1528. #endif // NETDATA_WITH_ZLIB
  1529. ssize_t web_client_send(struct web_client *w) {
  1530. #ifdef NETDATA_WITH_ZLIB
  1531. if(likely(w->response.zoutput)) return web_client_send_deflate(w);
  1532. #endif // NETDATA_WITH_ZLIB
  1533. ssize_t bytes;
  1534. if(unlikely(w->response.data->len - w->response.sent == 0)) {
  1535. // there is nothing to send
  1536. debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
  1537. // there can be two cases for this
  1538. // A. we have done everything
  1539. // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
  1540. if(w->mode == WEB_CLIENT_MODE_FILECOPY && web_client_has_wait_receive(w) && w->response.rlen && w->response.rlen > w->response.data->len) {
  1541. // we have to wait, more data will come
  1542. debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
  1543. web_client_disable_wait_send(w);
  1544. return 0;
  1545. }
  1546. if(unlikely(!web_client_has_keepalive(w))) {
  1547. debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %zu bytes sent.", w->id, w->response.sent);
  1548. WEB_CLIENT_IS_DEAD(w);
  1549. return 0;
  1550. }
  1551. web_client_request_done(w);
  1552. debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
  1553. return 0;
  1554. }
  1555. bytes = web_client_send_data(w,&w->response.data->buffer[w->response.sent], w->response.data->len - w->response.sent, MSG_DONTWAIT);
  1556. if(likely(bytes > 0)) {
  1557. w->statistics.sent_bytes += bytes;
  1558. w->response.sent += bytes;
  1559. debug(D_WEB_CLIENT, "%llu: Sent %zd bytes.", w->id, bytes);
  1560. }
  1561. else if(likely(bytes == 0)) {
  1562. debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client.", w->id);
  1563. }
  1564. else {
  1565. debug(D_WEB_CLIENT, "%llu: Failed to send data to client.", w->id);
  1566. WEB_CLIENT_IS_DEAD(w);
  1567. }
  1568. return(bytes);
  1569. }
  1570. ssize_t web_client_read_file(struct web_client *w)
  1571. {
  1572. if(unlikely(w->response.rlen > w->response.data->size))
  1573. buffer_need_bytes(w->response.data, w->response.rlen - w->response.data->size);
  1574. if(unlikely(w->response.rlen <= w->response.data->len))
  1575. return 0;
  1576. ssize_t left = (ssize_t)(w->response.rlen - w->response.data->len);
  1577. ssize_t bytes = read(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t)left);
  1578. if(likely(bytes > 0)) {
  1579. size_t old = w->response.data->len;
  1580. (void)old;
  1581. w->response.data->len += bytes;
  1582. w->response.data->buffer[w->response.data->len] = '\0';
  1583. debug(D_WEB_CLIENT, "%llu: Read %zd bytes.", w->id, bytes);
  1584. debug(D_WEB_DATA, "%llu: Read data: '%s'.", w->id, &w->response.data->buffer[old]);
  1585. web_client_enable_wait_send(w);
  1586. if(w->response.rlen && w->response.data->len >= w->response.rlen)
  1587. web_client_disable_wait_receive(w);
  1588. }
  1589. else if(likely(bytes == 0)) {
  1590. debug(D_WEB_CLIENT, "%llu: Out of input file data.", w->id);
  1591. // if we cannot read, it means we have an error on input.
  1592. // if however, we are copying a file from ifd to ofd, we should not return an error.
  1593. // in this case, the error should be generated when the file has been sent to the client.
  1594. // we are copying data from ifd to ofd
  1595. // let it finish copying...
  1596. web_client_disable_wait_receive(w);
  1597. debug(D_WEB_CLIENT, "%llu: Read the whole file.", w->id);
  1598. if(web_server_mode != WEB_SERVER_MODE_STATIC_THREADED) {
  1599. if (w->ifd != w->ofd) close(w->ifd);
  1600. }
  1601. w->ifd = w->ofd;
  1602. }
  1603. else {
  1604. debug(D_WEB_CLIENT, "%llu: read data failed.", w->id);
  1605. WEB_CLIENT_IS_DEAD(w);
  1606. }
  1607. return(bytes);
  1608. }
  1609. ssize_t web_client_receive(struct web_client *w)
  1610. {
  1611. if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY))
  1612. return web_client_read_file(w);
  1613. ssize_t bytes;
  1614. ssize_t left = (ssize_t)(w->response.data->size - w->response.data->len);
  1615. // do we have any space for more data?
  1616. buffer_need_bytes(w->response.data, NETDATA_WEB_REQUEST_INITIAL_SIZE);
  1617. #ifdef ENABLE_HTTPS
  1618. if ( (!web_client_check_unix(w)) && (netdata_ssl_srv_ctx) ) {
  1619. if ( ( w->ssl.conn ) && (!w->ssl.flags)) {
  1620. bytes = netdata_ssl_read(w->ssl.conn, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1));
  1621. web_client_enable_wait_from_ssl(w, bytes);
  1622. }else {
  1623. bytes = recv(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1), MSG_DONTWAIT);
  1624. }
  1625. }
  1626. else{
  1627. bytes = recv(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1), MSG_DONTWAIT);
  1628. }
  1629. #else
  1630. bytes = recv(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1), MSG_DONTWAIT);
  1631. #endif
  1632. if(likely(bytes > 0)) {
  1633. w->statistics.received_bytes += bytes;
  1634. size_t old = w->response.data->len;
  1635. (void)old;
  1636. w->response.data->len += bytes;
  1637. w->response.data->buffer[w->response.data->len] = '\0';
  1638. debug(D_WEB_CLIENT, "%llu: Received %zd bytes.", w->id, bytes);
  1639. debug(D_WEB_DATA, "%llu: Received data: '%s'.", w->id, &w->response.data->buffer[old]);
  1640. }
  1641. else if (bytes < 0) {
  1642. debug(D_WEB_CLIENT, "%llu: receive data failed.", w->id);
  1643. WEB_CLIENT_IS_DEAD(w);
  1644. } else
  1645. debug(D_WEB_CLIENT, "%llu: Received %zd bytes.", w->id, bytes);
  1646. return(bytes);
  1647. }
  1648. int web_client_socket_is_now_used_for_streaming(struct web_client *w) {
  1649. // prevent the web_client from closing the streaming socket
  1650. WEB_CLIENT_IS_DEAD(w);
  1651. if(web_server_mode == WEB_SERVER_MODE_STATIC_THREADED) {
  1652. web_client_flag_set(w, WEB_CLIENT_FLAG_DONT_CLOSE_SOCKET);
  1653. }
  1654. else {
  1655. if(w->ifd == w->ofd)
  1656. w->ifd = w->ofd = -1;
  1657. else
  1658. w->ifd = -1;
  1659. }
  1660. buffer_flush(w->response.data);
  1661. return HTTP_RESP_OK;
  1662. }
  1663. void web_client_decode_path_and_query_string(struct web_client *w, const char *path_and_query_string) {
  1664. char buffer[NETDATA_WEB_REQUEST_URL_SIZE + 2];
  1665. buffer[0] = '\0';
  1666. buffer_flush(w->url_path_decoded);
  1667. buffer_flush(w->url_query_string_decoded);
  1668. if(buffer_strlen(w->url_as_received) == 0)
  1669. // do not overwrite this if it is already filled
  1670. buffer_strcat(w->url_as_received, path_and_query_string);
  1671. if(w->mode == WEB_CLIENT_MODE_STREAM) {
  1672. // in stream mode, there is no path
  1673. url_decode_r(buffer, path_and_query_string, NETDATA_WEB_REQUEST_URL_SIZE + 1);
  1674. buffer[NETDATA_WEB_REQUEST_URL_SIZE + 1] = '\0';
  1675. buffer_strcat(w->url_query_string_decoded, buffer);
  1676. }
  1677. else {
  1678. // in non-stream mode, there is a path
  1679. // FIXME - the way this is implemented, query string params never accept the symbol &, not even encoded as %26
  1680. // To support the symbol & in query string params, we need to turn the url_query_string_decoded into a
  1681. // dictionary and decode each of the parameters individually.
  1682. // OR: in url_query_string_decoded use as separator a control character that cannot appear in the URL.
  1683. char *question_mark_start = strchr(path_and_query_string, '?');
  1684. if (question_mark_start)
  1685. url_decode_r(buffer, question_mark_start, NETDATA_WEB_REQUEST_URL_SIZE + 1);
  1686. buffer[NETDATA_WEB_REQUEST_URL_SIZE + 1] = '\0';
  1687. buffer_strcat(w->url_query_string_decoded, buffer);
  1688. if (question_mark_start) {
  1689. char c = *question_mark_start;
  1690. *question_mark_start = '\0';
  1691. url_decode_r(buffer, path_and_query_string, NETDATA_WEB_REQUEST_URL_SIZE + 1);
  1692. *question_mark_start = c;
  1693. } else
  1694. url_decode_r(buffer, path_and_query_string, NETDATA_WEB_REQUEST_URL_SIZE + 1);
  1695. buffer[NETDATA_WEB_REQUEST_URL_SIZE + 1] = '\0';
  1696. buffer_strcat(w->url_path_decoded, buffer);
  1697. }
  1698. }
  1699. #ifdef ENABLE_HTTPS
  1700. void web_client_reuse_ssl(struct web_client *w) {
  1701. if (netdata_ssl_srv_ctx) {
  1702. if (w->ssl.conn) {
  1703. SSL_SESSION *session = SSL_get_session(w->ssl.conn);
  1704. SSL *old = w->ssl.conn;
  1705. w->ssl.conn = SSL_new(netdata_ssl_srv_ctx);
  1706. if (session) {
  1707. #if OPENSSL_VERSION_NUMBER >= OPENSSL_VERSION_111
  1708. if (SSL_SESSION_is_resumable(session))
  1709. #endif
  1710. SSL_set_session(w->ssl.conn, session);
  1711. }
  1712. SSL_free(old);
  1713. }
  1714. }
  1715. }
  1716. #endif
  1717. void web_client_zero(struct web_client *w) {
  1718. // zero everything about it - but keep the buffers
  1719. web_client_reset_allocations(w, false);
  1720. // remember the pointers to the buffers
  1721. BUFFER *b1 = w->response.data;
  1722. BUFFER *b2 = w->response.header;
  1723. BUFFER *b3 = w->response.header_output;
  1724. BUFFER *b4 = w->url_path_decoded;
  1725. BUFFER *b5 = w->url_as_received;
  1726. BUFFER *b6 = w->url_query_string_decoded;
  1727. #ifdef ENABLE_HTTPS
  1728. web_client_reuse_ssl(w);
  1729. SSL *ssl = w->ssl.conn;
  1730. #endif
  1731. size_t use_count = w->use_count;
  1732. size_t *statistics_memory_accounting = w->statistics.memory_accounting;
  1733. // zero everything
  1734. memset(w, 0, sizeof(struct web_client));
  1735. w->ifd = w->ofd = -1;
  1736. w->statistics.memory_accounting = statistics_memory_accounting;
  1737. w->use_count = use_count;
  1738. #ifdef ENABLE_HTTPS
  1739. w->ssl.conn = ssl;
  1740. w->ssl.flags = NETDATA_SSL_START;
  1741. debug(D_WEB_CLIENT_ACCESS,"Reusing SSL structure with (w->ssl = NULL, w->accepted = %u)", w->ssl.flags);
  1742. #endif
  1743. // restore the pointers of the buffers
  1744. w->response.data = b1;
  1745. w->response.header = b2;
  1746. w->response.header_output = b3;
  1747. w->url_path_decoded = b4;
  1748. w->url_as_received = b5;
  1749. w->url_query_string_decoded = b6;
  1750. }
  1751. struct web_client *web_client_create(size_t *statistics_memory_accounting) {
  1752. struct web_client *w = (struct web_client *)callocz(1, sizeof(struct web_client));
  1753. w->use_count = 1;
  1754. w->statistics.memory_accounting = statistics_memory_accounting;
  1755. w->url_as_received = buffer_create(NETDATA_WEB_DECODED_URL_INITIAL_SIZE, w->statistics.memory_accounting);
  1756. w->url_path_decoded = buffer_create(NETDATA_WEB_DECODED_URL_INITIAL_SIZE, w->statistics.memory_accounting);
  1757. w->url_query_string_decoded = buffer_create(NETDATA_WEB_DECODED_URL_INITIAL_SIZE, w->statistics.memory_accounting);
  1758. w->response.data = buffer_create(NETDATA_WEB_RESPONSE_INITIAL_SIZE, w->statistics.memory_accounting);
  1759. w->response.header = buffer_create(NETDATA_WEB_RESPONSE_HEADER_INITIAL_SIZE, w->statistics.memory_accounting);
  1760. w->response.header_output = buffer_create(NETDATA_WEB_RESPONSE_HEADER_INITIAL_SIZE, w->statistics.memory_accounting);
  1761. __atomic_add_fetch(w->statistics.memory_accounting, sizeof(struct web_client), __ATOMIC_RELAXED);
  1762. return w;
  1763. }
  1764. void web_client_free(struct web_client *w) {
  1765. web_client_reset_allocations(w, true);
  1766. __atomic_sub_fetch(w->statistics.memory_accounting, sizeof(struct web_client), __ATOMIC_RELAXED);
  1767. freez(w);
  1768. }
  1769. inline void web_client_timeout_checkpoint_init(struct web_client *w) {
  1770. now_monotonic_high_precision_timeval(&w->timings.tv_in);
  1771. }
  1772. inline void web_client_timeout_checkpoint_set(struct web_client *w, int timeout_ms) {
  1773. w->timings.timeout_ut = timeout_ms * USEC_PER_MS;
  1774. if(!w->timings.tv_in.tv_sec)
  1775. web_client_timeout_checkpoint_init(w);
  1776. if(!w->timings.tv_timeout_last_checkpoint.tv_sec)
  1777. w->timings.tv_timeout_last_checkpoint = w->timings.tv_in;
  1778. }
  1779. inline usec_t web_client_timeout_checkpoint(struct web_client *w) {
  1780. struct timeval now;
  1781. now_monotonic_high_precision_timeval(&now);
  1782. if (!w->timings.tv_timeout_last_checkpoint.tv_sec)
  1783. w->timings.tv_timeout_last_checkpoint = w->timings.tv_in;
  1784. usec_t since_last_check_ut = dt_usec(&w->timings.tv_timeout_last_checkpoint, &now);
  1785. w->timings.tv_timeout_last_checkpoint = now;
  1786. return since_last_check_ut;
  1787. }
  1788. inline usec_t web_client_timeout_checkpoint_response_ready(struct web_client *w, usec_t *usec_since_last_checkpoint) {
  1789. usec_t since_last_check_ut = web_client_timeout_checkpoint(w);
  1790. if(usec_since_last_checkpoint)
  1791. *usec_since_last_checkpoint = since_last_check_ut;
  1792. w->timings.tv_ready = w->timings.tv_timeout_last_checkpoint;
  1793. // return the total time of the query
  1794. return dt_usec(&w->timings.tv_in, &w->timings.tv_ready);
  1795. }
  1796. inline bool web_client_timeout_checkpoint_and_check(struct web_client *w, usec_t *usec_since_last_checkpoint) {
  1797. usec_t since_last_check_ut = web_client_timeout_checkpoint(w);
  1798. if(usec_since_last_checkpoint)
  1799. *usec_since_last_checkpoint = since_last_check_ut;
  1800. if(!w->timings.timeout_ut)
  1801. return false;
  1802. usec_t since_reception_ut = dt_usec(&w->timings.tv_in, &w->timings.tv_timeout_last_checkpoint);
  1803. if (since_reception_ut >= w->timings.timeout_ut) {
  1804. buffer_flush(w->response.data);
  1805. buffer_strcat(w->response.data, "Query timeout exceeded");
  1806. w->response.code = HTTP_RESP_BACKEND_FETCH_FAILED;
  1807. return true;
  1808. }
  1809. return false;
  1810. }