web_client.c 86 KB

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