web_client.c 89 KB

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