web_client.c 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955
  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. finished_web_request_statistics(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) ? ((size - sent) / (double) size * 100.0) : 0.0)
  105. , dt_usec(&w->tv_ready, &w->tv_in) / 1000.0
  106. , dt_usec(&tv, &w->tv_ready) / 1000.0
  107. , 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 .. 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. }
  407. static inline int check_host_and_call(RRDHOST *host, struct web_client *w, char *url, int (*func)(RRDHOST *, struct web_client *, char *)) {
  408. //if(unlikely(host->rrd_memory_mode == RRD_MEMORY_MODE_NONE)) {
  409. // buffer_flush(w->response.data);
  410. // buffer_strcat(w->response.data, "This host does not maintain a database");
  411. // return HTTP_RESP_BAD_REQUEST;
  412. //}
  413. return func(host, w, url);
  414. }
  415. 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 *)) {
  416. if(!web_client_can_access_dashboard(w))
  417. return web_client_permission_denied(w);
  418. return check_host_and_call(host, w, url, func);
  419. }
  420. 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 *)) {
  421. if(!web_client_can_access_mgmt(w))
  422. return web_client_permission_denied(w);
  423. return check_host_and_call(host, w, url, func);
  424. }
  425. int web_client_api_request(RRDHOST *host, struct web_client *w, char *url)
  426. {
  427. // get the api version
  428. char *tok = mystrsep(&url, "/");
  429. if(tok && *tok) {
  430. debug(D_WEB_CLIENT, "%llu: Searching for API version '%s'.", w->id, tok);
  431. if(strcmp(tok, "v1") == 0)
  432. return web_client_api_request_v1(host, w, url);
  433. else {
  434. buffer_flush(w->response.data);
  435. w->response.data->contenttype = CT_TEXT_HTML;
  436. buffer_strcat(w->response.data, "Unsupported API version: ");
  437. buffer_strcat_htmlescape(w->response.data, tok);
  438. return HTTP_RESP_NOT_FOUND;
  439. }
  440. }
  441. else {
  442. buffer_flush(w->response.data);
  443. buffer_sprintf(w->response.data, "Which API version?");
  444. return HTTP_RESP_BAD_REQUEST;
  445. }
  446. }
  447. const char *web_content_type_to_string(uint8_t contenttype) {
  448. switch(contenttype) {
  449. case CT_TEXT_HTML:
  450. return "text/html; charset=utf-8";
  451. case CT_APPLICATION_XML:
  452. return "application/xml; charset=utf-8";
  453. case CT_APPLICATION_JSON:
  454. return "application/json; charset=utf-8";
  455. case CT_APPLICATION_X_JAVASCRIPT:
  456. return "application/x-javascript; charset=utf-8";
  457. case CT_TEXT_CSS:
  458. return "text/css; charset=utf-8";
  459. case CT_TEXT_XML:
  460. return "text/xml; charset=utf-8";
  461. case CT_TEXT_XSL:
  462. return "text/xsl; charset=utf-8";
  463. case CT_APPLICATION_OCTET_STREAM:
  464. return "application/octet-stream";
  465. case CT_IMAGE_SVG_XML:
  466. return "image/svg+xml";
  467. case CT_APPLICATION_X_FONT_TRUETYPE:
  468. return "application/x-font-truetype";
  469. case CT_APPLICATION_X_FONT_OPENTYPE:
  470. return "application/x-font-opentype";
  471. case CT_APPLICATION_FONT_WOFF:
  472. return "application/font-woff";
  473. case CT_APPLICATION_FONT_WOFF2:
  474. return "application/font-woff2";
  475. case CT_APPLICATION_VND_MS_FONTOBJ:
  476. return "application/vnd.ms-fontobject";
  477. case CT_IMAGE_PNG:
  478. return "image/png";
  479. case CT_IMAGE_JPG:
  480. return "image/jpeg";
  481. case CT_IMAGE_GIF:
  482. return "image/gif";
  483. case CT_IMAGE_XICON:
  484. return "image/x-icon";
  485. case CT_IMAGE_BMP:
  486. return "image/bmp";
  487. case CT_IMAGE_ICNS:
  488. return "image/icns";
  489. case CT_PROMETHEUS:
  490. return "text/plain; version=0.0.4";
  491. default:
  492. case CT_TEXT_PLAIN:
  493. return "text/plain; charset=utf-8";
  494. }
  495. }
  496. const char *web_response_code_to_string(int code) {
  497. switch(code) {
  498. case HTTP_RESP_OK:
  499. return "OK";
  500. case HTTP_RESP_MOVED_PERM:
  501. return "Moved Permanently";
  502. case HTTP_RESP_REDIR_TEMP:
  503. return "Temporary Redirect";
  504. case HTTP_RESP_BAD_REQUEST:
  505. return "Bad Request";
  506. case HTTP_RESP_FORBIDDEN:
  507. return "Forbidden";
  508. case HTTP_RESP_NOT_FOUND:
  509. return "Not Found";
  510. case HTTP_RESP_PRECOND_FAIL:
  511. return "Preconditions Failed";
  512. default:
  513. if(code >= 100 && code < 200)
  514. return "Informational";
  515. if(code >= 200 && code < 300)
  516. return "Successful";
  517. if(code >= 300 && code < 400)
  518. return "Redirection";
  519. if(code >= 400 && code < 500)
  520. return "Bad Request";
  521. if(code >= 500 && code < 600)
  522. return "Server Error";
  523. return "Undefined Error";
  524. }
  525. }
  526. static inline char *http_header_parse(struct web_client *w, char *s, int parse_useragent) {
  527. static uint32_t hash_origin = 0, hash_connection = 0, hash_donottrack = 0, hash_useragent = 0,
  528. hash_authorization = 0, hash_host = 0, hash_forwarded_proto = 0, hash_forwarded_host = 0;
  529. #ifdef NETDATA_WITH_ZLIB
  530. static uint32_t hash_accept_encoding = 0;
  531. #endif
  532. if(unlikely(!hash_origin)) {
  533. hash_origin = simple_uhash("Origin");
  534. hash_connection = simple_uhash("Connection");
  535. #ifdef NETDATA_WITH_ZLIB
  536. hash_accept_encoding = simple_uhash("Accept-Encoding");
  537. #endif
  538. hash_donottrack = simple_uhash("DNT");
  539. hash_useragent = simple_uhash("User-Agent");
  540. hash_authorization = simple_uhash("X-Auth-Token");
  541. hash_host = simple_uhash("Host");
  542. hash_forwarded_proto = simple_uhash("X-Forwarded-Proto");
  543. hash_forwarded_host = simple_uhash("X-Forwarded-Host");
  544. }
  545. char *e = s;
  546. // find the :
  547. while(*e && *e != ':') e++;
  548. if(!*e) return e;
  549. // get the name
  550. *e = '\0';
  551. // find the value
  552. char *v = e + 1, *ve;
  553. // skip leading spaces from value
  554. while(*v == ' ') v++;
  555. ve = v;
  556. // find the \r
  557. while(*ve && *ve != '\r') ve++;
  558. if(!*ve || ve[1] != '\n') {
  559. *e = ':';
  560. return ve;
  561. }
  562. // terminate the value
  563. *ve = '\0';
  564. uint32_t hash = simple_uhash(s);
  565. if(hash == hash_origin && !strcasecmp(s, "Origin"))
  566. strncpyz(w->origin, v, NETDATA_WEB_REQUEST_ORIGIN_HEADER_SIZE);
  567. else if(hash == hash_connection && !strcasecmp(s, "Connection")) {
  568. if(strcasestr(v, "keep-alive"))
  569. web_client_enable_keepalive(w);
  570. }
  571. else if(respect_web_browser_do_not_track_policy && hash == hash_donottrack && !strcasecmp(s, "DNT")) {
  572. if(*v == '0') web_client_disable_donottrack(w);
  573. else if(*v == '1') web_client_enable_donottrack(w);
  574. }
  575. else if(parse_useragent && hash == hash_useragent && !strcasecmp(s, "User-Agent")) {
  576. w->user_agent = strdupz(v);
  577. } else if(hash == hash_authorization&& !strcasecmp(s, "X-Auth-Token")) {
  578. w->auth_bearer_token = strdupz(v);
  579. }
  580. else if(hash == hash_host && !strcasecmp(s, "Host")){
  581. strncpyz(w->server_host, v, ((size_t)(ve - v) < sizeof(w->server_host)-1 ? (size_t)(ve - v) : sizeof(w->server_host)-1));
  582. }
  583. #ifdef NETDATA_WITH_ZLIB
  584. else if(hash == hash_accept_encoding && !strcasecmp(s, "Accept-Encoding")) {
  585. if(web_enable_gzip) {
  586. if(strcasestr(v, "gzip"))
  587. web_client_enable_deflate(w, 1);
  588. //
  589. // does not seem to work
  590. // else if(strcasestr(v, "deflate"))
  591. // web_client_enable_deflate(w, 0);
  592. }
  593. }
  594. #endif /* NETDATA_WITH_ZLIB */
  595. #ifdef ENABLE_HTTPS
  596. else if(hash == hash_forwarded_proto && !strcasecmp(s, "X-Forwarded-Proto")) {
  597. if(strcasestr(v, "https"))
  598. w->ssl.flags |= NETDATA_SSL_PROXY_HTTPS;
  599. }
  600. #endif
  601. else if(hash == hash_forwarded_host && !strcasecmp(s, "X-Forwarded-Host")){
  602. strncpyz(w->forwarded_host, v, ((size_t)(ve - v) < sizeof(w->server_host)-1 ? (size_t)(ve - v) : sizeof(w->server_host)-1));
  603. }
  604. *e = ':';
  605. *ve = '\r';
  606. return ve;
  607. }
  608. /**
  609. * Valid Method
  610. *
  611. * Netdata accepts only three methods, including one of these three(STREAM) is an internal method.
  612. *
  613. * @param w is the structure with the client request
  614. * @param s is the start string to parse
  615. *
  616. * @return it returns the next address to parse case the method is valid and NULL otherwise.
  617. */
  618. static inline char *web_client_valid_method(struct web_client *w, char *s) {
  619. // is is a valid request?
  620. if(!strncmp(s, "GET ", 4)) {
  621. s = &s[4];
  622. w->mode = WEB_CLIENT_MODE_NORMAL;
  623. }
  624. else if(!strncmp(s, "OPTIONS ", 8)) {
  625. s = &s[8];
  626. w->mode = WEB_CLIENT_MODE_OPTIONS;
  627. }
  628. else if(!strncmp(s, "STREAM ", 7)) {
  629. s = &s[7];
  630. #ifdef ENABLE_HTTPS
  631. if (w->ssl.flags && web_client_is_using_ssl_force(w)){
  632. w->header_parse_tries = 0;
  633. w->header_parse_last_size = 0;
  634. web_client_disable_wait_receive(w);
  635. char hostname[256];
  636. char *copyme = strstr(s,"hostname=");
  637. if ( copyme ){
  638. copyme += 9;
  639. char *end = strchr(copyme,'&');
  640. if(end){
  641. size_t length = MIN(255, end - copyme);
  642. memcpy(hostname,copyme,length);
  643. hostname[length] = 0X00;
  644. }
  645. else{
  646. memcpy(hostname,"not available",13);
  647. hostname[13] = 0x00;
  648. }
  649. }
  650. else{
  651. memcpy(hostname,"not available",13);
  652. hostname[13] = 0x00;
  653. }
  654. error("The server is configured to always use encrypted connections, please enable the SSL on child with hostname '%s'.",hostname);
  655. s = NULL;
  656. }
  657. #endif
  658. w->mode = WEB_CLIENT_MODE_STREAM;
  659. }
  660. else {
  661. s = NULL;
  662. }
  663. return s;
  664. }
  665. /**
  666. * Set Path Query
  667. *
  668. * Set the pointers to the path and query string according to the input.
  669. *
  670. * @param w is the structure with the client request
  671. * @param s is the first address of the string.
  672. * @param ptr is the address of the separator.
  673. */
  674. static void web_client_set_path_query(struct web_client *w, char *s, char *ptr) {
  675. w->url_path_length = (size_t)(ptr -s);
  676. w->url_search_path = ptr;
  677. }
  678. /**
  679. * Split path query
  680. *
  681. * Do the separation between path and query string
  682. *
  683. * @param w is the structure with the client request
  684. * @param s is the string to parse
  685. */
  686. void web_client_split_path_query(struct web_client *w, char *s) {
  687. //I am assuming here that the separator character(?) is not encoded
  688. char *ptr = strchr(s, '?');
  689. if(ptr) {
  690. w->separator = '?';
  691. web_client_set_path_query(w, s, ptr);
  692. return;
  693. }
  694. //Here I test the second possibility, the URL is completely encoded by the user.
  695. //I am not using the strcasestr, because it is fastest to check %3f and compare
  696. //the next character.
  697. //We executed some tests with "encodeURI(uri);" described in https://www.w3schools.com/jsref/jsref_encodeuri.asp
  698. //on July 1st, 2019, that show us that URLs won't have '?','=' and '&' encoded, but we decided to move in front
  699. //with the next part, because users can develop their own encoded that won't follow this rule.
  700. char *moveme = s;
  701. while (moveme) {
  702. ptr = strchr(moveme, '%');
  703. if(ptr) {
  704. char *test = (ptr+1);
  705. if (!strncmp(test, "3f", 2) || !strncmp(test, "3F", 2)) {
  706. w->separator = *ptr;
  707. web_client_set_path_query(w, s, ptr);
  708. return;
  709. }
  710. ptr++;
  711. }
  712. moveme = ptr;
  713. }
  714. w->separator = 0x00;
  715. w->url_path_length = strlen(s);
  716. }
  717. /**
  718. * Request validate
  719. *
  720. * @param w is the structure with the client request
  721. *
  722. * @return It returns HTTP_VALIDATION_OK on success and another code present
  723. * in the enum HTTP_VALIDATION otherwise.
  724. */
  725. static inline HTTP_VALIDATION http_request_validate(struct web_client *w) {
  726. char *s = (char *)buffer_tostring(w->response.data), *encoded_url = NULL;
  727. size_t last_pos = w->header_parse_last_size;
  728. w->header_parse_tries++;
  729. w->header_parse_last_size = buffer_strlen(w->response.data);
  730. int is_it_valid;
  731. if(w->header_parse_tries > 1) {
  732. if(last_pos > 4) last_pos -= 4; // allow searching for \r\n\r\n
  733. else last_pos = 0;
  734. if(w->header_parse_last_size < last_pos)
  735. last_pos = 0;
  736. is_it_valid = url_is_request_complete(s, &s[last_pos], w->header_parse_last_size);
  737. if(!is_it_valid) {
  738. if(w->header_parse_tries > 10) {
  739. info("Disabling slow client after %zu attempts to read the request (%zu bytes received)", w->header_parse_tries, buffer_strlen(w->response.data));
  740. w->header_parse_tries = 0;
  741. w->header_parse_last_size = 0;
  742. web_client_disable_wait_receive(w);
  743. return HTTP_VALIDATION_NOT_SUPPORTED;
  744. }
  745. return HTTP_VALIDATION_INCOMPLETE;
  746. }
  747. is_it_valid = 1;
  748. } else {
  749. last_pos = w->header_parse_last_size;
  750. is_it_valid = url_is_request_complete(s, &s[last_pos], w->header_parse_last_size);
  751. }
  752. s = web_client_valid_method(w, s);
  753. if (!s) {
  754. w->header_parse_tries = 0;
  755. w->header_parse_last_size = 0;
  756. web_client_disable_wait_receive(w);
  757. return HTTP_VALIDATION_NOT_SUPPORTED;
  758. } else if (!is_it_valid) {
  759. //Invalid request, we have more data after the end of message
  760. char *check = strstr((char *)buffer_tostring(w->response.data), "\r\n\r\n");
  761. if(check) {
  762. check += 4;
  763. if (*check) {
  764. w->header_parse_tries = 0;
  765. w->header_parse_last_size = 0;
  766. web_client_disable_wait_receive(w);
  767. return HTTP_VALIDATION_NOT_SUPPORTED;
  768. }
  769. }
  770. web_client_enable_wait_receive(w);
  771. return HTTP_VALIDATION_INCOMPLETE;
  772. }
  773. //After the method we have the path and query string together
  774. encoded_url = s;
  775. //we search for the position where we have " HTTP/", because it finishes the user request
  776. s = url_find_protocol(s);
  777. // incomplete requests
  778. if(unlikely(!*s)) {
  779. web_client_enable_wait_receive(w);
  780. return HTTP_VALIDATION_INCOMPLETE;
  781. }
  782. // we have the end of encoded_url - remember it
  783. char *ue = s;
  784. //Variables used to map the variables in the query string case it is present
  785. int total_variables;
  786. char *ptr_variables[WEB_FIELDS_MAX];
  787. // make sure we have complete request
  788. // complete requests contain: \r\n\r\n
  789. while(*s) {
  790. // find a line feed
  791. while(*s && *s++ != '\r');
  792. // did we reach the end?
  793. if(unlikely(!*s)) break;
  794. // is it \r\n ?
  795. if(likely(*s++ == '\n')) {
  796. // is it again \r\n ? (header end)
  797. if(unlikely(*s == '\r' && s[1] == '\n')) {
  798. // a valid complete HTTP request found
  799. *ue = '\0';
  800. //This is to avoid crash in line
  801. w->url_search_path = NULL;
  802. if(w->mode != WEB_CLIENT_MODE_NORMAL) {
  803. if(!url_decode_r(w->decoded_url, encoded_url, NETDATA_WEB_REQUEST_URL_SIZE + 1))
  804. return HTTP_VALIDATION_MALFORMED_URL;
  805. } else {
  806. web_client_split_path_query(w, encoded_url);
  807. if (w->url_search_path && w->separator) {
  808. *w->url_search_path = 0x00;
  809. }
  810. if(!url_decode_r(w->decoded_url, encoded_url, NETDATA_WEB_REQUEST_URL_SIZE + 1))
  811. return HTTP_VALIDATION_MALFORMED_URL;
  812. if (w->url_search_path && w->separator) {
  813. *w->url_search_path = w->separator;
  814. char *from = (encoded_url + w->url_path_length);
  815. total_variables = url_map_query_string(ptr_variables, from);
  816. if (url_parse_query_string(w->decoded_query_string, NETDATA_WEB_REQUEST_URL_SIZE + 1, ptr_variables, total_variables)) {
  817. return HTTP_VALIDATION_MALFORMED_URL;
  818. }
  819. } else {
  820. //make sure there's no leftovers from previous request on the same web client
  821. w->decoded_query_string[1]='\0';
  822. }
  823. }
  824. *ue = ' ';
  825. // copy the URL - we are going to overwrite parts of it
  826. // TODO -- ideally we we should avoid copying buffers around
  827. strncpyz(w->last_url, w->decoded_url, NETDATA_WEB_REQUEST_URL_SIZE);
  828. #ifdef ENABLE_HTTPS
  829. if ( (!web_client_check_unix(w)) && (netdata_srv_ctx) ) {
  830. 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)) ) {
  831. w->header_parse_tries = 0;
  832. w->header_parse_last_size = 0;
  833. // The client will be redirected for Netdata and we are preserving the original request.
  834. *ue = '\0';
  835. strncpyz(w->last_url, encoded_url, NETDATA_WEB_REQUEST_URL_SIZE);
  836. *ue = ' ';
  837. web_client_disable_wait_receive(w);
  838. return HTTP_VALIDATION_REDIRECT;
  839. }
  840. }
  841. #endif
  842. w->header_parse_tries = 0;
  843. w->header_parse_last_size = 0;
  844. web_client_disable_wait_receive(w);
  845. return HTTP_VALIDATION_OK;
  846. }
  847. // another header line
  848. s = http_header_parse(w, s,
  849. (w->mode == WEB_CLIENT_MODE_STREAM) // parse user agent
  850. );
  851. }
  852. }
  853. // incomplete request
  854. web_client_enable_wait_receive(w);
  855. return HTTP_VALIDATION_INCOMPLETE;
  856. }
  857. static inline ssize_t web_client_send_data(struct web_client *w,const void *buf,size_t len, int flags)
  858. {
  859. ssize_t bytes;
  860. #ifdef ENABLE_HTTPS
  861. if ( (!web_client_check_unix(w)) && (netdata_srv_ctx) ) {
  862. if ( ( w->ssl.conn ) && ( !w->ssl.flags ) ){
  863. bytes = SSL_write(w->ssl.conn,buf, len) ;
  864. } else {
  865. bytes = send(w->ofd,buf, len , flags);
  866. }
  867. } else {
  868. bytes = send(w->ofd,buf, len , flags);
  869. }
  870. #else
  871. bytes = send(w->ofd, buf, len, flags);
  872. #endif
  873. return bytes;
  874. }
  875. void web_client_build_http_header(struct web_client *w) {
  876. if(unlikely(w->response.code != HTTP_RESP_OK))
  877. buffer_no_cacheable(w->response.data);
  878. // set a proper expiration date, if not already set
  879. if(unlikely(!w->response.data->expires)) {
  880. if(w->response.data->options & WB_CONTENT_NO_CACHEABLE)
  881. w->response.data->expires = w->tv_ready.tv_sec + localhost->rrd_update_every;
  882. else
  883. w->response.data->expires = w->tv_ready.tv_sec + 86400;
  884. }
  885. // prepare the HTTP response header
  886. debug(D_WEB_CLIENT, "%llu: Generating HTTP header with response %d.", w->id, w->response.code);
  887. const char *content_type_string = web_content_type_to_string(w->response.data->contenttype);
  888. const char *code_msg = web_response_code_to_string(w->response.code);
  889. // prepare the last modified and expiration dates
  890. char date[32], edate[32];
  891. {
  892. struct tm tmbuf, *tm;
  893. tm = gmtime_r(&w->response.data->date, &tmbuf);
  894. strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %Z", tm);
  895. tm = gmtime_r(&w->response.data->expires, &tmbuf);
  896. strftime(edate, sizeof(edate), "%a, %d %b %Y %H:%M:%S %Z", tm);
  897. }
  898. if (w->response.code == HTTP_RESP_MOVED_PERM) {
  899. buffer_sprintf(w->response.header_output,
  900. "HTTP/1.1 %d %s\r\n"
  901. "Location: https://%s%s\r\n",
  902. w->response.code, code_msg,
  903. w->server_host,
  904. w->last_url);
  905. }else {
  906. buffer_sprintf(w->response.header_output,
  907. "HTTP/1.1 %d %s\r\n"
  908. "Connection: %s\r\n"
  909. "Server: Netdata Embedded HTTP Server %s\r\n"
  910. "Access-Control-Allow-Origin: %s\r\n"
  911. "Access-Control-Allow-Credentials: true\r\n"
  912. "Content-Type: %s\r\n"
  913. "Date: %s\r\n",
  914. w->response.code,
  915. code_msg,
  916. web_client_has_keepalive(w)?"keep-alive":"close",
  917. VERSION,
  918. w->origin,
  919. content_type_string,
  920. date);
  921. }
  922. if(unlikely(web_x_frame_options))
  923. buffer_sprintf(w->response.header_output, "X-Frame-Options: %s\r\n", web_x_frame_options);
  924. if(w->cookie1[0] || w->cookie2[0]) {
  925. if(w->cookie1[0]) {
  926. buffer_sprintf(w->response.header_output,
  927. "Set-Cookie: %s\r\n",
  928. w->cookie1);
  929. }
  930. if(w->cookie2[0]) {
  931. buffer_sprintf(w->response.header_output,
  932. "Set-Cookie: %s\r\n",
  933. w->cookie2);
  934. }
  935. if(respect_web_browser_do_not_track_policy)
  936. buffer_sprintf(w->response.header_output,
  937. "Tk: T;cookies\r\n");
  938. }
  939. else {
  940. if(respect_web_browser_do_not_track_policy) {
  941. if(web_client_has_tracking_required(w))
  942. buffer_sprintf(w->response.header_output,
  943. "Tk: T;cookies\r\n");
  944. else
  945. buffer_sprintf(w->response.header_output,
  946. "Tk: N\r\n");
  947. }
  948. }
  949. if(w->mode == WEB_CLIENT_MODE_OPTIONS) {
  950. buffer_strcat(w->response.header_output,
  951. "Access-Control-Allow-Methods: GET, OPTIONS\r\n"
  952. "Access-Control-Allow-Headers: accept, x-requested-with, origin, content-type, cookie, pragma, cache-control, x-auth-token\r\n"
  953. "Access-Control-Max-Age: 1209600\r\n" // 86400 * 14
  954. );
  955. }
  956. else {
  957. buffer_sprintf(w->response.header_output,
  958. "Cache-Control: %s\r\n"
  959. "Expires: %s\r\n",
  960. (w->response.data->options & WB_CONTENT_NO_CACHEABLE)?"no-cache, no-store, must-revalidate\r\nPragma: no-cache":"public",
  961. edate);
  962. }
  963. // copy a possibly available custom header
  964. if(unlikely(buffer_strlen(w->response.header)))
  965. buffer_strcat(w->response.header_output, buffer_tostring(w->response.header));
  966. // headers related to the transfer method
  967. if(likely(w->response.zoutput))
  968. buffer_strcat(w->response.header_output, "Content-Encoding: gzip\r\n");
  969. if(likely(w->flags & WEB_CLIENT_CHUNKED_TRANSFER))
  970. buffer_strcat(w->response.header_output, "Transfer-Encoding: chunked\r\n");
  971. else {
  972. if(likely((w->response.data->len || w->response.rlen))) {
  973. // we know the content length, put it
  974. buffer_sprintf(w->response.header_output, "Content-Length: %zu\r\n", w->response.data->len? w->response.data->len: w->response.rlen);
  975. }
  976. else {
  977. // we don't know the content length, disable keep-alive
  978. web_client_disable_keepalive(w);
  979. }
  980. }
  981. // end of HTTP header
  982. buffer_strcat(w->response.header_output, "\r\n");
  983. }
  984. static inline void web_client_send_http_header(struct web_client *w) {
  985. web_client_build_http_header(w);
  986. // sent the HTTP header
  987. debug(D_WEB_DATA, "%llu: Sending response HTTP header of size %zu: '%s'"
  988. , w->id
  989. , buffer_strlen(w->response.header_output)
  990. , buffer_tostring(w->response.header_output)
  991. );
  992. web_client_crock_socket(w);
  993. size_t count = 0;
  994. ssize_t bytes;
  995. #ifdef ENABLE_HTTPS
  996. if ( (!web_client_check_unix(w)) && (netdata_srv_ctx) ) {
  997. if ( ( w->ssl.conn ) && ( !w->ssl.flags ) ){
  998. while((bytes = SSL_write(w->ssl.conn, buffer_tostring(w->response.header_output), buffer_strlen(w->response.header_output))) < 0) {
  999. count++;
  1000. if(count > 100 || (errno != EAGAIN && errno != EWOULDBLOCK)) {
  1001. error("Cannot send HTTPS headers to web client.");
  1002. break;
  1003. }
  1004. }
  1005. } else {
  1006. while((bytes = send(w->ofd, buffer_tostring(w->response.header_output), buffer_strlen(w->response.header_output), 0)) == -1) {
  1007. count++;
  1008. if(count > 100 || (errno != EAGAIN && errno != EWOULDBLOCK)) {
  1009. error("Cannot send HTTP headers to web client.");
  1010. break;
  1011. }
  1012. }
  1013. }
  1014. } else {
  1015. while((bytes = send(w->ofd, buffer_tostring(w->response.header_output), buffer_strlen(w->response.header_output), 0)) == -1) {
  1016. count++;
  1017. if(count > 100 || (errno != EAGAIN && errno != EWOULDBLOCK)) {
  1018. error("Cannot send HTTP headers to web client.");
  1019. break;
  1020. }
  1021. }
  1022. }
  1023. #else
  1024. while((bytes = send(w->ofd, buffer_tostring(w->response.header_output), buffer_strlen(w->response.header_output), 0)) == -1) {
  1025. count++;
  1026. if(count > 100 || (errno != EAGAIN && errno != EWOULDBLOCK)) {
  1027. error("Cannot send HTTP headers to web client.");
  1028. break;
  1029. }
  1030. }
  1031. #endif
  1032. if(bytes != (ssize_t) buffer_strlen(w->response.header_output)) {
  1033. if(bytes > 0)
  1034. w->stats_sent_bytes += bytes;
  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. else
  1042. w->stats_sent_bytes += bytes;
  1043. }
  1044. static inline int web_client_process_url(RRDHOST *host, struct web_client *w, char *url);
  1045. static inline int web_client_switch_host(RRDHOST *host, struct web_client *w, char *url) {
  1046. static uint32_t hash_localhost = 0;
  1047. if(unlikely(!hash_localhost)) {
  1048. hash_localhost = simple_hash("localhost");
  1049. }
  1050. if(host != localhost) {
  1051. buffer_flush(w->response.data);
  1052. buffer_strcat(w->response.data, "Nesting of hosts is not allowed.");
  1053. return HTTP_RESP_BAD_REQUEST;
  1054. }
  1055. char *tok = mystrsep(&url, "/");
  1056. if(tok && *tok) {
  1057. debug(D_WEB_CLIENT, "%llu: Searching for host with name '%s'.", w->id, tok);
  1058. if(!url) { //no delim found
  1059. debug(D_WEB_CLIENT, "%llu: URL doesn't end with / generating redirect.", w->id);
  1060. char *protocol, *url_host;
  1061. #ifdef ENABLE_HTTPS
  1062. protocol = ((w->ssl.conn && !w->ssl.flags) || w->ssl.flags & NETDATA_SSL_PROXY_HTTPS) ? "https" : "http";
  1063. #else
  1064. protocol = "http";
  1065. #endif
  1066. url_host = (!w->forwarded_host[0])?w->server_host:w->forwarded_host;
  1067. buffer_sprintf(w->response.header, "Location: %s://%s%s/\r\n", protocol, url_host, w->last_url);
  1068. buffer_strcat(w->response.data, "Permanent redirect");
  1069. return HTTP_RESP_REDIR_PERM;
  1070. }
  1071. // copy the URL, we need it to serve files
  1072. w->last_url[0] = '/';
  1073. if(url && *url) strncpyz(&w->last_url[1], url, NETDATA_WEB_REQUEST_URL_SIZE - 1);
  1074. else w->last_url[1] = '\0';
  1075. uint32_t hash = simple_hash(tok);
  1076. host = rrdhost_find_by_hostname(tok, hash);
  1077. if (!host)
  1078. host = rrdhost_find_by_guid(tok, hash);
  1079. if (!host) {
  1080. host = sql_create_host_by_uuid(tok);
  1081. if (likely(host)) {
  1082. int rc = web_client_process_url(host, w, url);
  1083. freez(host->hostname);
  1084. freez((char *)host->os);
  1085. freez((char *)host->tags);
  1086. freez((char *)host->timezone);
  1087. freez(host->program_name);
  1088. freez(host->program_version);
  1089. freez(host->registry_hostname);
  1090. freez(host->system_info);
  1091. freez(host);
  1092. return rc;
  1093. }
  1094. }
  1095. if (host) return web_client_process_url(host, w, url);
  1096. }
  1097. buffer_flush(w->response.data);
  1098. w->response.data->contenttype = CT_TEXT_HTML;
  1099. buffer_strcat(w->response.data, "This netdata does not maintain a database for host: ");
  1100. buffer_strcat_htmlescape(w->response.data, tok?tok:"");
  1101. return HTTP_RESP_NOT_FOUND;
  1102. }
  1103. static inline int web_client_process_url(RRDHOST *host, struct web_client *w, char *url) {
  1104. static uint32_t
  1105. hash_api = 0,
  1106. hash_netdata_conf = 0,
  1107. hash_host = 0;
  1108. #ifdef NETDATA_INTERNAL_CHECKS
  1109. static uint32_t hash_exit = 0, hash_debug = 0, hash_mirror = 0;
  1110. #endif
  1111. if(unlikely(!hash_api)) {
  1112. hash_api = simple_hash("api");
  1113. hash_netdata_conf = simple_hash("netdata.conf");
  1114. hash_host = simple_hash("host");
  1115. #ifdef NETDATA_INTERNAL_CHECKS
  1116. hash_exit = simple_hash("exit");
  1117. hash_debug = simple_hash("debug");
  1118. hash_mirror = simple_hash("mirror");
  1119. #endif
  1120. }
  1121. char *tok = mystrsep(&url, "/?");
  1122. if(likely(tok && *tok)) {
  1123. uint32_t hash = simple_hash(tok);
  1124. debug(D_WEB_CLIENT, "%llu: Processing command '%s'.", w->id, tok);
  1125. if(unlikely(hash == hash_api && strcmp(tok, "api") == 0)) { // current API
  1126. debug(D_WEB_CLIENT_ACCESS, "%llu: API request ...", w->id);
  1127. return check_host_and_call(host, w, url, web_client_api_request);
  1128. }
  1129. else if(unlikely(hash == hash_host && strcmp(tok, "host") == 0)) { // host switching
  1130. debug(D_WEB_CLIENT_ACCESS, "%llu: host switch request ...", w->id);
  1131. return web_client_switch_host(host, w, url);
  1132. }
  1133. else if(unlikely(hash == hash_netdata_conf && strcmp(tok, "netdata.conf") == 0)) { // netdata.conf
  1134. if(unlikely(!web_client_can_access_netdataconf(w)))
  1135. return web_client_permission_denied(w);
  1136. debug(D_WEB_CLIENT_ACCESS, "%llu: generating netdata.conf ...", w->id);
  1137. w->response.data->contenttype = CT_TEXT_PLAIN;
  1138. buffer_flush(w->response.data);
  1139. config_generate(w->response.data, 0);
  1140. return HTTP_RESP_OK;
  1141. }
  1142. #ifdef NETDATA_INTERNAL_CHECKS
  1143. else if(unlikely(hash == hash_exit && strcmp(tok, "exit") == 0)) {
  1144. if(unlikely(!web_client_can_access_netdataconf(w)))
  1145. return web_client_permission_denied(w);
  1146. w->response.data->contenttype = CT_TEXT_PLAIN;
  1147. buffer_flush(w->response.data);
  1148. if(!netdata_exit)
  1149. buffer_strcat(w->response.data, "ok, will do...");
  1150. else
  1151. buffer_strcat(w->response.data, "I am doing it already");
  1152. error("web request to exit received.");
  1153. netdata_cleanup_and_exit(0);
  1154. return HTTP_RESP_OK;
  1155. }
  1156. else if(unlikely(hash == hash_debug && strcmp(tok, "debug") == 0)) {
  1157. if(unlikely(!web_client_can_access_netdataconf(w)))
  1158. return web_client_permission_denied(w);
  1159. buffer_flush(w->response.data);
  1160. // get the name of the data to show
  1161. tok = mystrsep(&url, "&");
  1162. if(tok && *tok) {
  1163. debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
  1164. // do we have such a data set?
  1165. RRDSET *st = rrdset_find_byname(host, tok);
  1166. if(!st) st = rrdset_find(host, tok);
  1167. if(!st) {
  1168. w->response.data->contenttype = CT_TEXT_HTML;
  1169. buffer_strcat(w->response.data, "Chart is not found: ");
  1170. buffer_strcat_htmlescape(w->response.data, tok);
  1171. debug(D_WEB_CLIENT_ACCESS, "%llu: %s is not found.", w->id, tok);
  1172. return HTTP_RESP_NOT_FOUND;
  1173. }
  1174. debug_flags |= D_RRD_STATS;
  1175. if(rrdset_flag_check(st, RRDSET_FLAG_DEBUG))
  1176. rrdset_flag_clear(st, RRDSET_FLAG_DEBUG);
  1177. else
  1178. rrdset_flag_set(st, RRDSET_FLAG_DEBUG);
  1179. w->response.data->contenttype = CT_TEXT_HTML;
  1180. buffer_sprintf(w->response.data, "Chart has now debug %s: ", rrdset_flag_check(st, RRDSET_FLAG_DEBUG)?"enabled":"disabled");
  1181. buffer_strcat_htmlescape(w->response.data, tok);
  1182. debug(D_WEB_CLIENT_ACCESS, "%llu: debug for %s is %s.", w->id, tok, rrdset_flag_check(st, RRDSET_FLAG_DEBUG)?"enabled":"disabled");
  1183. return HTTP_RESP_OK;
  1184. }
  1185. buffer_flush(w->response.data);
  1186. buffer_strcat(w->response.data, "debug which chart?\r\n");
  1187. return HTTP_RESP_BAD_REQUEST;
  1188. }
  1189. else if(unlikely(hash == hash_mirror && strcmp(tok, "mirror") == 0)) {
  1190. if(unlikely(!web_client_can_access_netdataconf(w)))
  1191. return web_client_permission_denied(w);
  1192. debug(D_WEB_CLIENT_ACCESS, "%llu: Mirroring...", w->id);
  1193. // replace the zero bytes with spaces
  1194. buffer_char_replace(w->response.data, '\0', ' ');
  1195. // just leave the buffer as is
  1196. // it will be copied back to the client
  1197. return HTTP_RESP_OK;
  1198. }
  1199. #endif /* NETDATA_INTERNAL_CHECKS */
  1200. }
  1201. char filename[FILENAME_MAX+1];
  1202. url = filename;
  1203. strncpyz(filename, w->last_url, FILENAME_MAX);
  1204. tok = mystrsep(&url, "?");
  1205. buffer_flush(w->response.data);
  1206. return mysendfile(w, (tok && *tok)?tok:"/");
  1207. }
  1208. void web_client_process_request(struct web_client *w) {
  1209. // start timing us
  1210. now_realtime_timeval(&w->tv_in);
  1211. switch(http_request_validate(w)) {
  1212. case HTTP_VALIDATION_OK:
  1213. switch(w->mode) {
  1214. case WEB_CLIENT_MODE_STREAM:
  1215. if(unlikely(!web_client_can_access_stream(w))) {
  1216. web_client_permission_denied(w);
  1217. return;
  1218. }
  1219. w->response.code = rrdpush_receiver_thread_spawn(w, w->decoded_url);
  1220. return;
  1221. case WEB_CLIENT_MODE_OPTIONS:
  1222. if(unlikely(
  1223. !web_client_can_access_dashboard(w) &&
  1224. !web_client_can_access_registry(w) &&
  1225. !web_client_can_access_badges(w) &&
  1226. !web_client_can_access_mgmt(w) &&
  1227. !web_client_can_access_netdataconf(w)
  1228. )) {
  1229. web_client_permission_denied(w);
  1230. break;
  1231. }
  1232. w->response.data->contenttype = CT_TEXT_PLAIN;
  1233. buffer_flush(w->response.data);
  1234. buffer_strcat(w->response.data, "OK");
  1235. w->response.code = HTTP_RESP_OK;
  1236. break;
  1237. case WEB_CLIENT_MODE_FILECOPY:
  1238. case WEB_CLIENT_MODE_NORMAL:
  1239. if(unlikely(
  1240. !web_client_can_access_dashboard(w) &&
  1241. !web_client_can_access_registry(w) &&
  1242. !web_client_can_access_badges(w) &&
  1243. !web_client_can_access_mgmt(w) &&
  1244. !web_client_can_access_netdataconf(w)
  1245. )) {
  1246. web_client_permission_denied(w);
  1247. break;
  1248. }
  1249. w->response.code = web_client_process_url(localhost, w, w->decoded_url);
  1250. break;
  1251. }
  1252. break;
  1253. case HTTP_VALIDATION_INCOMPLETE:
  1254. if(w->response.data->len > NETDATA_WEB_REQUEST_MAX_SIZE) {
  1255. strcpy(w->last_url, "too big request");
  1256. debug(D_WEB_CLIENT_ACCESS, "%llu: Received request is too big (%zu bytes).", w->id, w->response.data->len);
  1257. buffer_flush(w->response.data);
  1258. buffer_sprintf(w->response.data, "Received request is too big (%zu bytes).\r\n", w->response.data->len);
  1259. w->response.code = HTTP_RESP_BAD_REQUEST;
  1260. }
  1261. else {
  1262. // wait for more data
  1263. return;
  1264. }
  1265. break;
  1266. #ifdef ENABLE_HTTPS
  1267. case HTTP_VALIDATION_REDIRECT:
  1268. {
  1269. buffer_flush(w->response.data);
  1270. w->response.data->contenttype = CT_TEXT_HTML;
  1271. buffer_strcat(w->response.data,
  1272. "<!DOCTYPE html><!-- SPDX-License-Identifier: GPL-3.0-or-later --><html>"
  1273. "<body onload=\"window.location.href ='https://'+ window.location.hostname +"
  1274. " ':' + window.location.port + window.location.pathname + window.location.search\">"
  1275. "Redirecting to safety connection, case your browser does not support redirection, please"
  1276. " click <a onclick=\"window.location.href ='https://'+ window.location.hostname + ':' "
  1277. " + window.location.port + window.location.pathname + window.location.search\">here</a>."
  1278. "</body></html>");
  1279. w->response.code = HTTP_RESP_MOVED_PERM;
  1280. break;
  1281. }
  1282. #endif
  1283. case HTTP_VALIDATION_MALFORMED_URL:
  1284. debug(D_WEB_CLIENT_ACCESS, "%llu: URL parsing failed (malformed URL). Cannot understand '%s'.", w->id, w->response.data->buffer);
  1285. buffer_flush(w->response.data);
  1286. buffer_strcat(w->response.data, "URL not valid. I don't understand you...\r\n");
  1287. w->response.code = HTTP_RESP_BAD_REQUEST;
  1288. break;
  1289. case HTTP_VALIDATION_NOT_SUPPORTED:
  1290. debug(D_WEB_CLIENT_ACCESS, "%llu: Cannot understand '%s'.", w->id, w->response.data->buffer);
  1291. buffer_flush(w->response.data);
  1292. buffer_strcat(w->response.data, "I don't understand you...\r\n");
  1293. w->response.code = HTTP_RESP_BAD_REQUEST;
  1294. break;
  1295. }
  1296. // keep track of the time we done processing
  1297. now_realtime_timeval(&w->tv_ready);
  1298. w->response.sent = 0;
  1299. // set a proper last modified date
  1300. if(unlikely(!w->response.data->date))
  1301. w->response.data->date = w->tv_ready.tv_sec;
  1302. web_client_send_http_header(w);
  1303. // enable sending immediately if we have data
  1304. if(w->response.data->len) web_client_enable_wait_send(w);
  1305. else web_client_disable_wait_send(w);
  1306. switch(w->mode) {
  1307. case WEB_CLIENT_MODE_STREAM:
  1308. debug(D_WEB_CLIENT, "%llu: STREAM done.", w->id);
  1309. break;
  1310. case WEB_CLIENT_MODE_OPTIONS:
  1311. debug(D_WEB_CLIENT, "%llu: Done preparing the OPTIONS response. Sending data (%zu bytes) to client.", w->id, w->response.data->len);
  1312. break;
  1313. case WEB_CLIENT_MODE_NORMAL:
  1314. debug(D_WEB_CLIENT, "%llu: Done preparing the response. Sending data (%zu bytes) to client.", w->id, w->response.data->len);
  1315. break;
  1316. case WEB_CLIENT_MODE_FILECOPY:
  1317. if(w->response.rlen) {
  1318. debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending data file of %zu bytes to client.", w->id, w->response.rlen);
  1319. web_client_enable_wait_receive(w);
  1320. /*
  1321. // utilize the kernel sendfile() for copying the file to the socket.
  1322. // this block of code can be commented, without anything missing.
  1323. // when it is commented, the program will copy the data using async I/O.
  1324. {
  1325. long len = sendfile(w->ofd, w->ifd, NULL, w->response.data->rbytes);
  1326. if(len != w->response.data->rbytes)
  1327. error("%llu: sendfile() should copy %ld bytes, but copied %ld. Falling back to manual copy.", w->id, w->response.data->rbytes, len);
  1328. else
  1329. web_client_request_done(w);
  1330. }
  1331. */
  1332. }
  1333. else
  1334. debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending an unknown amount of bytes to client.", w->id);
  1335. break;
  1336. default:
  1337. fatal("%llu: Unknown client mode %u.", w->id, w->mode);
  1338. break;
  1339. }
  1340. }
  1341. ssize_t web_client_send_chunk_header(struct web_client *w, size_t len)
  1342. {
  1343. debug(D_DEFLATE, "%llu: OPEN CHUNK of %zu bytes (hex: %zx).", w->id, len, len);
  1344. char buf[24];
  1345. ssize_t bytes;
  1346. bytes = (ssize_t)sprintf(buf, "%zX\r\n", len);
  1347. buf[bytes] = 0x00;
  1348. bytes = web_client_send_data(w,buf,strlen(buf),0);
  1349. if(bytes > 0) {
  1350. debug(D_DEFLATE, "%llu: Sent chunk header %zd bytes.", w->id, bytes);
  1351. w->stats_sent_bytes += bytes;
  1352. }
  1353. else if(bytes == 0) {
  1354. debug(D_WEB_CLIENT, "%llu: Did not send chunk header to the client.", w->id);
  1355. WEB_CLIENT_IS_DEAD(w);
  1356. }
  1357. else {
  1358. debug(D_WEB_CLIENT, "%llu: Failed to send chunk header to client.", w->id);
  1359. WEB_CLIENT_IS_DEAD(w);
  1360. }
  1361. return bytes;
  1362. }
  1363. ssize_t web_client_send_chunk_close(struct web_client *w)
  1364. {
  1365. //debug(D_DEFLATE, "%llu: CLOSE CHUNK.", w->id);
  1366. ssize_t bytes;
  1367. bytes = web_client_send_data(w,"\r\n",2,0);
  1368. if(bytes > 0) {
  1369. debug(D_DEFLATE, "%llu: Sent chunk suffix %zd bytes.", w->id, bytes);
  1370. w->stats_sent_bytes += bytes;
  1371. }
  1372. else if(bytes == 0) {
  1373. debug(D_WEB_CLIENT, "%llu: Did not send chunk suffix to the client.", w->id);
  1374. WEB_CLIENT_IS_DEAD(w);
  1375. }
  1376. else {
  1377. debug(D_WEB_CLIENT, "%llu: Failed to send chunk suffix to client.", w->id);
  1378. WEB_CLIENT_IS_DEAD(w);
  1379. }
  1380. return bytes;
  1381. }
  1382. ssize_t web_client_send_chunk_finalize(struct web_client *w)
  1383. {
  1384. //debug(D_DEFLATE, "%llu: FINALIZE CHUNK.", w->id);
  1385. ssize_t bytes;
  1386. bytes = web_client_send_data(w,"\r\n0\r\n\r\n",7,0);
  1387. if(bytes > 0) {
  1388. debug(D_DEFLATE, "%llu: Sent chunk suffix %zd bytes.", w->id, bytes);
  1389. w->stats_sent_bytes += bytes;
  1390. }
  1391. else if(bytes == 0) {
  1392. debug(D_WEB_CLIENT, "%llu: Did not send chunk finalize suffix to the client.", w->id);
  1393. WEB_CLIENT_IS_DEAD(w);
  1394. }
  1395. else {
  1396. debug(D_WEB_CLIENT, "%llu: Failed to send chunk finalize suffix to client.", w->id);
  1397. WEB_CLIENT_IS_DEAD(w);
  1398. }
  1399. return bytes;
  1400. }
  1401. #ifdef NETDATA_WITH_ZLIB
  1402. ssize_t web_client_send_deflate(struct web_client *w)
  1403. {
  1404. ssize_t len = 0, t = 0;
  1405. // when using compression,
  1406. // w->response.sent is the amount of bytes passed through compression
  1407. 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.",
  1408. 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);
  1409. 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) {
  1410. // there is nothing to send
  1411. debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
  1412. // finalize the chunk
  1413. if(w->response.sent != 0) {
  1414. t = web_client_send_chunk_finalize(w);
  1415. if(t < 0) return t;
  1416. }
  1417. if(w->mode == WEB_CLIENT_MODE_FILECOPY && web_client_has_wait_receive(w) && w->response.rlen && w->response.rlen > w->response.data->len) {
  1418. // we have to wait, more data will come
  1419. debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
  1420. web_client_disable_wait_send(w);
  1421. return t;
  1422. }
  1423. if(unlikely(!web_client_has_keepalive(w))) {
  1424. debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %zu bytes sent.", w->id, w->response.sent);
  1425. WEB_CLIENT_IS_DEAD(w);
  1426. return t;
  1427. }
  1428. // reset the client
  1429. web_client_request_done(w);
  1430. debug(D_WEB_CLIENT, "%llu: Done sending all data on socket.", w->id);
  1431. return t;
  1432. }
  1433. if(w->response.zhave == w->response.zsent) {
  1434. // compress more input data
  1435. // close the previous open chunk
  1436. if(w->response.sent != 0) {
  1437. t = web_client_send_chunk_close(w);
  1438. if(t < 0) return t;
  1439. }
  1440. 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);
  1441. // give the compressor all the data not passed through the compressor yet
  1442. if(w->response.data->len > w->response.sent) {
  1443. w->response.zstream.next_in = (Bytef *)&w->response.data->buffer[w->response.sent - w->response.zstream.avail_in];
  1444. w->response.zstream.avail_in += (uInt) (w->response.data->len - w->response.sent);
  1445. }
  1446. // reset the compressor output buffer
  1447. w->response.zstream.next_out = w->response.zbuffer;
  1448. w->response.zstream.avail_out = NETDATA_WEB_RESPONSE_ZLIB_CHUNK_SIZE;
  1449. // ask for FINISH if we have all the input
  1450. int flush = Z_SYNC_FLUSH;
  1451. if(w->mode == WEB_CLIENT_MODE_NORMAL
  1452. || (w->mode == WEB_CLIENT_MODE_FILECOPY && !web_client_has_wait_receive(w) && w->response.data->len == w->response.rlen)) {
  1453. flush = Z_FINISH;
  1454. debug(D_DEFLATE, "%llu: Requesting Z_FINISH, if possible.", w->id);
  1455. }
  1456. else {
  1457. debug(D_DEFLATE, "%llu: Requesting Z_SYNC_FLUSH.", w->id);
  1458. }
  1459. // compress
  1460. if(deflate(&w->response.zstream, flush) == Z_STREAM_ERROR) {
  1461. error("%llu: Compression failed. Closing down client.", w->id);
  1462. web_client_request_done(w);
  1463. return(-1);
  1464. }
  1465. w->response.zhave = NETDATA_WEB_RESPONSE_ZLIB_CHUNK_SIZE - w->response.zstream.avail_out;
  1466. w->response.zsent = 0;
  1467. // keep track of the bytes passed through the compressor
  1468. w->response.sent = w->response.data->len;
  1469. debug(D_DEFLATE, "%llu: Compression produced %zu bytes.", w->id, w->response.zhave);
  1470. // open a new chunk
  1471. ssize_t t2 = web_client_send_chunk_header(w, w->response.zhave);
  1472. if(t2 < 0) return t2;
  1473. t += t2;
  1474. }
  1475. debug(D_WEB_CLIENT, "%llu: Sending %zu bytes of data (+%zd of chunk header).", w->id, w->response.zhave - w->response.zsent, t);
  1476. len = web_client_send_data(w,&w->response.zbuffer[w->response.zsent], (size_t) (w->response.zhave - w->response.zsent), MSG_DONTWAIT);
  1477. if(len > 0) {
  1478. w->stats_sent_bytes += len;
  1479. w->response.zsent += len;
  1480. len += t;
  1481. debug(D_WEB_CLIENT, "%llu: Sent %zd bytes.", w->id, len);
  1482. }
  1483. else if(len == 0) {
  1484. debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client (zhave = %zu, zsent = %zu, need to send = %zu).",
  1485. w->id, w->response.zhave, w->response.zsent, w->response.zhave - w->response.zsent);
  1486. WEB_CLIENT_IS_DEAD(w);
  1487. }
  1488. else {
  1489. debug(D_WEB_CLIENT, "%llu: Failed to send data to client.", w->id);
  1490. WEB_CLIENT_IS_DEAD(w);
  1491. }
  1492. return(len);
  1493. }
  1494. #endif // NETDATA_WITH_ZLIB
  1495. ssize_t web_client_send(struct web_client *w) {
  1496. #ifdef NETDATA_WITH_ZLIB
  1497. if(likely(w->response.zoutput)) return web_client_send_deflate(w);
  1498. #endif // NETDATA_WITH_ZLIB
  1499. ssize_t bytes;
  1500. if(unlikely(w->response.data->len - w->response.sent == 0)) {
  1501. // there is nothing to send
  1502. debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
  1503. // there can be two cases for this
  1504. // A. we have done everything
  1505. // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
  1506. if(w->mode == WEB_CLIENT_MODE_FILECOPY && web_client_has_wait_receive(w) && w->response.rlen && w->response.rlen > w->response.data->len) {
  1507. // we have to wait, more data will come
  1508. debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
  1509. web_client_disable_wait_send(w);
  1510. return 0;
  1511. }
  1512. if(unlikely(!web_client_has_keepalive(w))) {
  1513. debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %zu bytes sent.", w->id, w->response.sent);
  1514. WEB_CLIENT_IS_DEAD(w);
  1515. return 0;
  1516. }
  1517. web_client_request_done(w);
  1518. debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
  1519. return 0;
  1520. }
  1521. bytes = web_client_send_data(w,&w->response.data->buffer[w->response.sent], w->response.data->len - w->response.sent, MSG_DONTWAIT);
  1522. if(likely(bytes > 0)) {
  1523. w->stats_sent_bytes += bytes;
  1524. w->response.sent += bytes;
  1525. debug(D_WEB_CLIENT, "%llu: Sent %zd bytes.", w->id, bytes);
  1526. }
  1527. else if(likely(bytes == 0)) {
  1528. debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client.", w->id);
  1529. WEB_CLIENT_IS_DEAD(w);
  1530. }
  1531. else {
  1532. debug(D_WEB_CLIENT, "%llu: Failed to send data to client.", w->id);
  1533. WEB_CLIENT_IS_DEAD(w);
  1534. }
  1535. return(bytes);
  1536. }
  1537. ssize_t web_client_read_file(struct web_client *w)
  1538. {
  1539. if(unlikely(w->response.rlen > w->response.data->size))
  1540. buffer_need_bytes(w->response.data, w->response.rlen - w->response.data->size);
  1541. if(unlikely(w->response.rlen <= w->response.data->len))
  1542. return 0;
  1543. ssize_t left = w->response.rlen - w->response.data->len;
  1544. ssize_t bytes = read(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t)left);
  1545. if(likely(bytes > 0)) {
  1546. size_t old = w->response.data->len;
  1547. (void)old;
  1548. w->response.data->len += bytes;
  1549. w->response.data->buffer[w->response.data->len] = '\0';
  1550. debug(D_WEB_CLIENT, "%llu: Read %zd bytes.", w->id, bytes);
  1551. debug(D_WEB_DATA, "%llu: Read data: '%s'.", w->id, &w->response.data->buffer[old]);
  1552. web_client_enable_wait_send(w);
  1553. if(w->response.rlen && w->response.data->len >= w->response.rlen)
  1554. web_client_disable_wait_receive(w);
  1555. }
  1556. else if(likely(bytes == 0)) {
  1557. debug(D_WEB_CLIENT, "%llu: Out of input file data.", w->id);
  1558. // if we cannot read, it means we have an error on input.
  1559. // if however, we are copying a file from ifd to ofd, we should not return an error.
  1560. // in this case, the error should be generated when the file has been sent to the client.
  1561. // we are copying data from ifd to ofd
  1562. // let it finish copying...
  1563. web_client_disable_wait_receive(w);
  1564. debug(D_WEB_CLIENT, "%llu: Read the whole file.", w->id);
  1565. if(web_server_mode != WEB_SERVER_MODE_STATIC_THREADED) {
  1566. if (w->ifd != w->ofd) close(w->ifd);
  1567. }
  1568. w->ifd = w->ofd;
  1569. }
  1570. else {
  1571. debug(D_WEB_CLIENT, "%llu: read data failed.", w->id);
  1572. WEB_CLIENT_IS_DEAD(w);
  1573. }
  1574. return(bytes);
  1575. }
  1576. ssize_t web_client_receive(struct web_client *w)
  1577. {
  1578. if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY))
  1579. return web_client_read_file(w);
  1580. ssize_t bytes;
  1581. ssize_t left = w->response.data->size - w->response.data->len;
  1582. // do we have any space for more data?
  1583. buffer_need_bytes(w->response.data, NETDATA_WEB_REQUEST_RECEIVE_SIZE);
  1584. #ifdef ENABLE_HTTPS
  1585. if ( (!web_client_check_unix(w)) && (netdata_srv_ctx) ) {
  1586. if ( ( w->ssl.conn ) && (!w->ssl.flags)) {
  1587. bytes = SSL_read(w->ssl.conn, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1));
  1588. }else {
  1589. bytes = recv(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1), MSG_DONTWAIT);
  1590. }
  1591. }
  1592. else{
  1593. bytes = recv(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1), MSG_DONTWAIT);
  1594. }
  1595. #else
  1596. bytes = recv(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1), MSG_DONTWAIT);
  1597. #endif
  1598. if(likely(bytes > 0)) {
  1599. w->stats_received_bytes += bytes;
  1600. size_t old = w->response.data->len;
  1601. (void)old;
  1602. w->response.data->len += bytes;
  1603. w->response.data->buffer[w->response.data->len] = '\0';
  1604. debug(D_WEB_CLIENT, "%llu: Received %zd bytes.", w->id, bytes);
  1605. debug(D_WEB_DATA, "%llu: Received data: '%s'.", w->id, &w->response.data->buffer[old]);
  1606. }
  1607. else {
  1608. debug(D_WEB_CLIENT, "%llu: receive data failed.", w->id);
  1609. WEB_CLIENT_IS_DEAD(w);
  1610. }
  1611. return(bytes);
  1612. }