web_client.c 70 KB

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