web_client.c 68 KB

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