web_client.c 68 KB

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