web_client.c 68 KB

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