web_client.c 77 KB

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