3 #define INITIAL_WEB_DATA_LENGTH 16384
4 #define WEB_REQUEST_LENGTH 16384
5 #define TOO_BIG_REQUEST 16384
7 int web_client_timeout = DEFAULT_DISCONNECT_IDLE_WEB_CLIENTS_AFTER_SECONDS;
8 int respect_web_browser_do_not_track_policy = 0;
9 char *web_x_frame_options = NULL;
11 #ifdef NETDATA_WITH_ZLIB
12 int web_enable_gzip = 1, web_gzip_level = 3, web_gzip_strategy = Z_DEFAULT_STRATEGY;
13 #endif /* NETDATA_WITH_ZLIB */
15 struct web_client *web_clients = NULL;
16 unsigned long long web_clients_count = 0;
18 static inline int web_client_crock_socket(struct web_client *w) {
20 if(likely(!w->tcp_cork && w->ofd != -1)) {
22 if(unlikely(setsockopt(w->ofd, IPPROTO_TCP, TCP_CORK, (char *) &w->tcp_cork, sizeof(int)) != 0)) {
23 error("%llu: failed to enable TCP_CORK on socket.", w->id);
33 static inline int web_client_uncrock_socket(struct web_client *w) {
35 if(likely(w->tcp_cork && w->ofd != -1)) {
37 if(unlikely(setsockopt(w->ofd, IPPROTO_TCP, TCP_CORK, (char *) &w->tcp_cork, sizeof(int)) != 0)) {
38 error("%llu: failed to disable TCP_CORK on socket.", w->id);
48 struct web_client *web_client_create(int listener) {
51 w = callocz(1, sizeof(struct web_client));
52 w->id = ++web_clients_count;
53 w->mode = WEB_CLIENT_MODE_NORMAL;
56 struct sockaddr *sadr;
59 sadr = (struct sockaddr*) &w->clientaddr;
60 addrlen = sizeof(w->clientaddr);
62 w->ifd = accept4(listener, sadr, &addrlen, SOCK_NONBLOCK);
64 error("%llu: Cannot accept new incoming connection.", w->id);
70 if(getnameinfo(sadr, addrlen, w->client_ip, NI_MAXHOST, w->client_port, NI_MAXSERV, NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
71 error("Cannot getnameinfo() on received client connection.");
72 strncpyz(w->client_ip, "UNKNOWN", NI_MAXHOST);
73 strncpyz(w->client_port, "UNKNOWN", NI_MAXSERV);
75 w->client_ip[NI_MAXHOST] = '\0';
76 w->client_port[NI_MAXSERV] = '\0';
78 switch(sadr->sa_family) {
80 debug(D_WEB_CLIENT_ACCESS, "%llu: New IPv4 web client from %s port %s on socket %d.", w->id, w->client_ip, w->client_port, w->ifd);
84 if(strncmp(w->client_ip, "::ffff:", 7) == 0) {
85 memmove(w->client_ip, &w->client_ip[7], strlen(&w->client_ip[7]) + 1);
86 debug(D_WEB_CLIENT_ACCESS, "%llu: New IPv4 web client from %s port %s on socket %d.", w->id, w->client_ip, w->client_port, w->ifd);
89 debug(D_WEB_CLIENT_ACCESS, "%llu: New IPv6 web client from %s port %s on socket %d.", w->id, w->client_ip, w->client_port, w->ifd);
93 debug(D_WEB_CLIENT_ACCESS, "%llu: New UNKNOWN web client from %s port %s on socket %d.", w->id, w->client_ip, w->client_port, w->ifd);
98 if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0)
99 error("%llu: failed to enable TCP_NODELAY on socket.", w->id);
102 if(setsockopt(w->ifd, SOL_SOCKET, SO_KEEPALIVE, (char *) &flag, sizeof(int)) != 0)
103 error("%llu: Cannot set SO_KEEPALIVE on socket.", w->id);
106 w->response.data = buffer_create(INITIAL_WEB_DATA_LENGTH);
107 w->response.header = buffer_create(HTTP_RESPONSE_HEADER_SIZE);
108 w->response.header_output = buffer_create(HTTP_RESPONSE_HEADER_SIZE);
112 if(web_clients) web_clients->prev = w;
113 w->next = web_clients;
116 web_client_connected();
121 void web_client_reset(struct web_client *w) {
122 web_client_uncrock_socket(w);
124 debug(D_WEB_CLIENT, "%llu: Resetting client.", w->id);
126 if(likely(w->last_url[0])) {
128 now_realtime_timeval(&tv);
130 size_t size = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->response.rlen:w->response.data->len;
132 #ifdef NETDATA_WITH_ZLIB
133 if(likely(w->response.zoutput)) sent = (size_t)w->response.zstream.total_out;
136 // --------------------------------------------------------------------
139 finished_web_request_statistics(dt_usec(&tv, &w->tv_in),
140 w->stats_received_bytes,
145 w->stats_received_bytes = 0;
146 w->stats_sent_bytes = 0;
149 // --------------------------------------------------------------------
152 log_access("%llu: (sent/all = %zu/%zu bytes %0.0f%%, prep/sent/total = %0.2f/%0.2f/%0.2f ms) %s: %d '%s'",
154 sent, size, -((size > 0) ? ((size - sent) / (double) size * 100.0) : 0.0),
155 dt_usec(&w->tv_ready, &w->tv_in) / 1000.0,
156 dt_usec(&tv, &w->tv_ready) / 1000.0,
157 dt_usec(&tv, &w->tv_in) / 1000.0,
158 (w->mode == WEB_CLIENT_MODE_FILECOPY) ? "filecopy" : ((w->mode == WEB_CLIENT_MODE_OPTIONS)
159 ? "options" : "data"),
165 if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY)) {
166 if(w->ifd != w->ofd) {
167 debug(D_WEB_CLIENT, "%llu: Closing filecopy input file descriptor %d.", w->id, w->ifd);
168 if(w->ifd != -1) close(w->ifd);
173 w->last_url[0] = '\0';
174 w->cookie1[0] = '\0';
175 w->cookie2[0] = '\0';
179 w->mode = WEB_CLIENT_MODE_NORMAL;
183 w->tracking_required = 0;
185 w->decoded_url[0] = '\0';
187 buffer_reset(w->response.header_output);
188 buffer_reset(w->response.header);
189 buffer_reset(w->response.data);
190 w->response.rlen = 0;
191 w->response.sent = 0;
192 w->response.code = 0;
197 w->response.zoutput = 0;
199 // if we had enabled compression, release it
200 #ifdef NETDATA_WITH_ZLIB
201 if(w->response.zinitialized) {
202 debug(D_DEFLATE, "%llu: Freeing compression resources.", w->id);
203 deflateEnd(&w->response.zstream);
204 w->response.zsent = 0;
205 w->response.zhave = 0;
206 w->response.zstream.avail_in = 0;
207 w->response.zstream.avail_out = 0;
208 w->response.zstream.total_in = 0;
209 w->response.zstream.total_out = 0;
210 w->response.zinitialized = 0;
212 #endif // NETDATA_WITH_ZLIB
215 struct web_client *web_client_free(struct web_client *w) {
218 struct web_client *n = w->next;
219 if(w == web_clients) web_clients = n;
221 debug(D_WEB_CLIENT_ACCESS, "%llu: Closing web client from %s port %s.", w->id, w->client_ip, w->client_port);
223 if(w->prev) w->prev->next = w->next;
224 if(w->next) w->next->prev = w->prev;
225 buffer_free(w->response.header_output);
226 buffer_free(w->response.header);
227 buffer_free(w->response.data);
228 if(w->ifd != -1) close(w->ifd);
229 if(w->ofd != -1 && w->ofd != w->ifd) close(w->ofd);
232 web_client_disconnected();
237 uid_t web_files_uid(void) {
238 static char *web_owner = NULL;
239 static uid_t owner_uid = 0;
241 if(unlikely(!web_owner)) {
242 web_owner = config_get(CONFIG_SECTION_WEB, "web files owner", config_get(CONFIG_SECTION_GLOBAL, "run as user", ""));
243 if(!web_owner || !*web_owner)
244 owner_uid = geteuid();
246 // getpwnam() is not thread safe,
247 // but we have called this function once
248 // while single threaded
249 struct passwd *pw = getpwnam(web_owner);
251 error("User '%s' is not present. Ignoring option.", web_owner);
252 owner_uid = geteuid();
255 debug(D_WEB_CLIENT, "Web files owner set to %s.", web_owner);
256 owner_uid = pw->pw_uid;
264 gid_t web_files_gid(void) {
265 static char *web_group = NULL;
266 static gid_t owner_gid = 0;
268 if(unlikely(!web_group)) {
269 web_group = config_get(CONFIG_SECTION_WEB, "web files group", config_get(CONFIG_SECTION_WEB, "web files owner", ""));
270 if(!web_group || !*web_group)
271 owner_gid = getegid();
273 // getgrnam() is not thread safe,
274 // but we have called this function once
275 // while single threaded
276 struct group *gr = getgrnam(web_group);
278 error("Group '%s' is not present. Ignoring option.", web_group);
279 owner_gid = getegid();
282 debug(D_WEB_CLIENT, "Web files group set to %s.", web_group);
283 owner_gid = gr->gr_gid;
291 int mysendfile(struct web_client *w, char *filename) {
292 debug(D_WEB_CLIENT, "%llu: Looking for file '%s/%s'", w->id, netdata_configured_web_dir, filename);
294 // skip leading slashes
295 while (*filename == '/') filename++;
297 // if the filename contain known paths, skip them
298 if(strncmp(filename, WEB_PATH_FILE "/", strlen(WEB_PATH_FILE) + 1) == 0)
299 filename = &filename[strlen(WEB_PATH_FILE) + 1];
302 for(s = filename; *s ;s++) {
303 if( !isalnum(*s) && *s != '/' && *s != '.' && *s != '-' && *s != '_') {
304 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
305 w->response.data->contenttype = CT_TEXT_HTML;
306 buffer_sprintf(w->response.data, "Filename contains invalid characters: ");
307 buffer_strcat_htmlescape(w->response.data, filename);
312 // if the filename contains a .. refuse to serve it
313 if(strstr(filename, "..") != 0) {
314 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
315 w->response.data->contenttype = CT_TEXT_HTML;
316 buffer_strcat(w->response.data, "Relative filenames are not supported: ");
317 buffer_strcat_htmlescape(w->response.data, filename);
322 char webfilename[FILENAME_MAX + 1];
323 snprintfz(webfilename, FILENAME_MAX, "%s/%s", netdata_configured_web_dir, filename);
325 // check if the file exists
327 if(lstat(webfilename, &stat) != 0) {
328 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not found.", w->id, webfilename);
329 w->response.data->contenttype = CT_TEXT_HTML;
330 buffer_strcat(w->response.data, "File does not exist, or is not accessible: ");
331 buffer_strcat_htmlescape(w->response.data, webfilename);
335 // check if the file is owned by expected user
336 if(stat.st_uid != web_files_uid()) {
337 error("%llu: File '%s' is owned by user %u (expected user %u). Access Denied.", w->id, webfilename, stat.st_uid, web_files_uid());
338 w->response.data->contenttype = CT_TEXT_HTML;
339 buffer_strcat(w->response.data, "Access to file is not permitted: ");
340 buffer_strcat_htmlescape(w->response.data, webfilename);
344 // check if the file is owned by expected group
345 if(stat.st_gid != web_files_gid()) {
346 error("%llu: File '%s' is owned by group %u (expected group %u). Access Denied.", w->id, webfilename, stat.st_gid, web_files_gid());
347 w->response.data->contenttype = CT_TEXT_HTML;
348 buffer_strcat(w->response.data, "Access to file is not permitted: ");
349 buffer_strcat_htmlescape(w->response.data, webfilename);
353 if((stat.st_mode & S_IFMT) == S_IFDIR) {
354 snprintfz(webfilename, FILENAME_MAX, "%s/index.html", filename);
355 return mysendfile(w, webfilename);
358 if((stat.st_mode & S_IFMT) != S_IFREG) {
359 error("%llu: File '%s' is not a regular file. Access Denied.", w->id, webfilename);
360 w->response.data->contenttype = CT_TEXT_HTML;
361 buffer_strcat(w->response.data, "Access to file is not permitted: ");
362 buffer_strcat_htmlescape(w->response.data, webfilename);
367 w->ifd = open(webfilename, O_NONBLOCK, O_RDONLY);
371 if(errno == EBUSY || errno == EAGAIN) {
372 error("%llu: File '%s' is busy, sending 307 Moved Temporarily to force retry.", w->id, webfilename);
373 w->response.data->contenttype = CT_TEXT_HTML;
374 buffer_sprintf(w->response.header, "Location: /" WEB_PATH_FILE "/%s\r\n", filename);
375 buffer_strcat(w->response.data, "File is currently busy, please try again later: ");
376 buffer_strcat_htmlescape(w->response.data, webfilename);
380 error("%llu: Cannot open file '%s'.", w->id, webfilename);
381 w->response.data->contenttype = CT_TEXT_HTML;
382 buffer_strcat(w->response.data, "Cannot open file: ");
383 buffer_strcat_htmlescape(w->response.data, webfilename);
387 if(fcntl(w->ifd, F_SETFL, O_NONBLOCK) < 0)
388 error("%llu: Cannot set O_NONBLOCK on file '%s'.", w->id, webfilename);
390 // pick a Content-Type for the file
391 if(strstr(filename, ".html") != NULL) w->response.data->contenttype = CT_TEXT_HTML;
392 else if(strstr(filename, ".js") != NULL) w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
393 else if(strstr(filename, ".css") != NULL) w->response.data->contenttype = CT_TEXT_CSS;
394 else if(strstr(filename, ".xml") != NULL) w->response.data->contenttype = CT_TEXT_XML;
395 else if(strstr(filename, ".xsl") != NULL) w->response.data->contenttype = CT_TEXT_XSL;
396 else if(strstr(filename, ".txt") != NULL) w->response.data->contenttype = CT_TEXT_PLAIN;
397 else if(strstr(filename, ".svg") != NULL) w->response.data->contenttype = CT_IMAGE_SVG_XML;
398 else if(strstr(filename, ".ttf") != NULL) w->response.data->contenttype = CT_APPLICATION_X_FONT_TRUETYPE;
399 else if(strstr(filename, ".otf") != NULL) w->response.data->contenttype = CT_APPLICATION_X_FONT_OPENTYPE;
400 else if(strstr(filename, ".woff2")!= NULL) w->response.data->contenttype = CT_APPLICATION_FONT_WOFF2;
401 else if(strstr(filename, ".woff") != NULL) w->response.data->contenttype = CT_APPLICATION_FONT_WOFF;
402 else if(strstr(filename, ".eot") != NULL) w->response.data->contenttype = CT_APPLICATION_VND_MS_FONTOBJ;
403 else if(strstr(filename, ".png") != NULL) w->response.data->contenttype = CT_IMAGE_PNG;
404 else if(strstr(filename, ".jpg") != NULL) w->response.data->contenttype = CT_IMAGE_JPG;
405 else if(strstr(filename, ".jpeg") != NULL) w->response.data->contenttype = CT_IMAGE_JPG;
406 else if(strstr(filename, ".gif") != NULL) w->response.data->contenttype = CT_IMAGE_GIF;
407 else if(strstr(filename, ".bmp") != NULL) w->response.data->contenttype = CT_IMAGE_BMP;
408 else if(strstr(filename, ".ico") != NULL) w->response.data->contenttype = CT_IMAGE_XICON;
409 else if(strstr(filename, ".icns") != NULL) w->response.data->contenttype = CT_IMAGE_ICNS;
410 else w->response.data->contenttype = CT_APPLICATION_OCTET_STREAM;
412 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending file '%s' (%ld bytes, ifd %d, ofd %d).", w->id, webfilename, stat.st_size, w->ifd, w->ofd);
414 w->mode = WEB_CLIENT_MODE_FILECOPY;
417 buffer_flush(w->response.data);
418 w->response.rlen = stat.st_size;
420 w->response.data->date = stat.st_mtimespec.tv_sec;
422 w->response.data->date = stat.st_mtim.tv_sec;
423 #endif /* __APPLE__ */
424 buffer_cacheable(w->response.data);
430 #ifdef NETDATA_WITH_ZLIB
431 void web_client_enable_deflate(struct web_client *w, int gzip) {
432 if(unlikely(w->response.zinitialized)) {
433 debug(D_DEFLATE, "%llu: Compression has already be initialized for this client.", w->id);
437 if(unlikely(w->response.sent)) {
438 error("%llu: Cannot enable compression in the middle of a conversation.", w->id);
442 w->response.zstream.zalloc = Z_NULL;
443 w->response.zstream.zfree = Z_NULL;
444 w->response.zstream.opaque = Z_NULL;
446 w->response.zstream.next_in = (Bytef *)w->response.data->buffer;
447 w->response.zstream.avail_in = 0;
448 w->response.zstream.total_in = 0;
450 w->response.zstream.next_out = w->response.zbuffer;
451 w->response.zstream.avail_out = 0;
452 w->response.zstream.total_out = 0;
454 w->response.zstream.zalloc = Z_NULL;
455 w->response.zstream.zfree = Z_NULL;
456 w->response.zstream.opaque = Z_NULL;
458 // if(deflateInit(&w->response.zstream, Z_DEFAULT_COMPRESSION) != Z_OK) {
459 // error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
463 // Select GZIP compression: windowbits = 15 + 16 = 31
464 if(deflateInit2(&w->response.zstream, web_gzip_level, Z_DEFLATED, 15 + ((gzip)?16:0), 8, web_gzip_strategy) != Z_OK) {
465 error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
469 w->response.zsent = 0;
470 w->response.zoutput = 1;
471 w->response.zinitialized = 1;
473 debug(D_DEFLATE, "%llu: Initialized compression.", w->id);
475 #endif // NETDATA_WITH_ZLIB
477 void buffer_data_options2string(BUFFER *wb, uint32_t options) {
480 if(options & RRDR_OPTION_NONZERO) {
481 if(count++) buffer_strcat(wb, " ");
482 buffer_strcat(wb, "nonzero");
485 if(options & RRDR_OPTION_REVERSED) {
486 if(count++) buffer_strcat(wb, " ");
487 buffer_strcat(wb, "flip");
490 if(options & RRDR_OPTION_JSON_WRAP) {
491 if(count++) buffer_strcat(wb, " ");
492 buffer_strcat(wb, "jsonwrap");
495 if(options & RRDR_OPTION_MIN2MAX) {
496 if(count++) buffer_strcat(wb, " ");
497 buffer_strcat(wb, "min2max");
500 if(options & RRDR_OPTION_MILLISECONDS) {
501 if(count++) buffer_strcat(wb, " ");
502 buffer_strcat(wb, "ms");
505 if(options & RRDR_OPTION_ABSOLUTE) {
506 if(count++) buffer_strcat(wb, " ");
507 buffer_strcat(wb, "absolute");
510 if(options & RRDR_OPTION_SECONDS) {
511 if(count++) buffer_strcat(wb, " ");
512 buffer_strcat(wb, "seconds");
515 if(options & RRDR_OPTION_NULL2ZERO) {
516 if(count++) buffer_strcat(wb, " ");
517 buffer_strcat(wb, "null2zero");
520 if(options & RRDR_OPTION_OBJECTSROWS) {
521 if(count++) buffer_strcat(wb, " ");
522 buffer_strcat(wb, "objectrows");
525 if(options & RRDR_OPTION_GOOGLE_JSON) {
526 if(count++) buffer_strcat(wb, " ");
527 buffer_strcat(wb, "google_json");
530 if(options & RRDR_OPTION_PERCENTAGE) {
531 if(count++) buffer_strcat(wb, " ");
532 buffer_strcat(wb, "percentage");
535 if(options & RRDR_OPTION_NOT_ALIGNED) {
536 if(count++) buffer_strcat(wb, " ");
537 buffer_strcat(wb, "unaligned");
541 const char *group_method2string(int group) {
543 case GROUP_UNDEFINED:
558 case GROUP_INCREMENTAL_SUM:
559 return "incremental-sum";
562 return "unknown-group-method";
566 static inline int check_host_and_call(RRDHOST *host, struct web_client *w, char *url, int (*func)(RRDHOST *, struct web_client *, char *)) {
567 if(unlikely(host->rrd_memory_mode == RRD_MEMORY_MODE_NONE)) {
568 buffer_flush(w->response.data);
569 buffer_strcat(w->response.data, "This host does not maintain a database");
573 return func(host, w, url);
576 int web_client_api_request(RRDHOST *host, struct web_client *w, char *url)
578 // get the api version
579 char *tok = mystrsep(&url, "/?&");
581 debug(D_WEB_CLIENT, "%llu: Searching for API version '%s'.", w->id, tok);
582 if(strcmp(tok, "v1") == 0)
583 return web_client_api_request_v1(host, w, url);
585 buffer_flush(w->response.data);
586 w->response.data->contenttype = CT_TEXT_HTML;
587 buffer_strcat(w->response.data, "Unsupported API version: ");
588 buffer_strcat_htmlescape(w->response.data, tok);
593 buffer_flush(w->response.data);
594 buffer_sprintf(w->response.data, "Which API version?");
599 const char *web_content_type_to_string(uint8_t contenttype) {
600 switch(contenttype) {
602 return "text/html; charset=utf-8";
604 case CT_APPLICATION_XML:
605 return "application/xml; charset=utf-8";
607 case CT_APPLICATION_JSON:
608 return "application/json; charset=utf-8";
610 case CT_APPLICATION_X_JAVASCRIPT:
611 return "application/x-javascript; charset=utf-8";
614 return "text/css; charset=utf-8";
617 return "text/xml; charset=utf-8";
620 return "text/xsl; charset=utf-8";
622 case CT_APPLICATION_OCTET_STREAM:
623 return "application/octet-stream";
625 case CT_IMAGE_SVG_XML:
626 return "image/svg+xml";
628 case CT_APPLICATION_X_FONT_TRUETYPE:
629 return "application/x-font-truetype";
631 case CT_APPLICATION_X_FONT_OPENTYPE:
632 return "application/x-font-opentype";
634 case CT_APPLICATION_FONT_WOFF:
635 return "application/font-woff";
637 case CT_APPLICATION_FONT_WOFF2:
638 return "application/font-woff2";
640 case CT_APPLICATION_VND_MS_FONTOBJ:
641 return "application/vnd.ms-fontobject";
653 return "image/x-icon";
662 return "text/plain; version=0.0.4";
666 return "text/plain; charset=utf-8";
671 const char *web_response_code_to_string(int code) {
677 return "Temporary Redirect";
680 return "Bad Request";
689 return "Preconditions Failed";
692 if(code >= 100 && code < 200)
693 return "Informational";
695 if(code >= 200 && code < 300)
698 if(code >= 300 && code < 400)
699 return "Redirection";
701 if(code >= 400 && code < 500)
702 return "Bad Request";
704 if(code >= 500 && code < 600)
705 return "Server Error";
707 return "Undefined Error";
711 static inline char *http_header_parse(struct web_client *w, char *s) {
712 static uint32_t hash_origin = 0, hash_connection = 0, hash_accept_encoding = 0, hash_donottrack = 0;
714 if(unlikely(!hash_origin)) {
715 hash_origin = simple_uhash("Origin");
716 hash_connection = simple_uhash("Connection");
717 hash_accept_encoding = simple_uhash("Accept-Encoding");
718 hash_donottrack = simple_uhash("DNT");
724 while(*e && *e != ':') e++;
731 char *v = e + 1, *ve;
733 // skip leading spaces from value
734 while(*v == ' ') v++;
738 while(*ve && *ve != '\r') ve++;
739 if(!*ve || ve[1] != '\n') {
744 // terminate the value
747 // fprintf(stderr, "HEADER: '%s' = '%s'\n", s, v);
748 uint32_t hash = simple_uhash(s);
750 if(hash == hash_origin && !strcasecmp(s, "Origin"))
751 strncpyz(w->origin, v, ORIGIN_MAX);
753 else if(hash == hash_connection && !strcasecmp(s, "Connection")) {
754 if(strcasestr(v, "keep-alive"))
757 else if(respect_web_browser_do_not_track_policy && hash == hash_donottrack && !strcasecmp(s, "DNT")) {
758 if(*v == '0') w->donottrack = 0;
759 else if(*v == '1') w->donottrack = 1;
761 #ifdef NETDATA_WITH_ZLIB
762 else if(hash == hash_accept_encoding && !strcasecmp(s, "Accept-Encoding")) {
763 if(web_enable_gzip) {
764 if(strcasestr(v, "gzip"))
765 web_client_enable_deflate(w, 1);
767 // does not seem to work
768 // else if(strcasestr(v, "deflate"))
769 // web_client_enable_deflate(w, 0);
772 #endif /* NETDATA_WITH_ZLIB */
779 // http_request_validate()
781 // = 0 : all good, process the request
782 // > 0 : request is not supported
783 // < 0 : request is incomplete - wait for more data
785 typedef enum http_validation {
787 HTTP_VALIDATION_NOT_SUPPORTED,
788 HTTP_VALIDATION_INCOMPLETE
791 static inline HTTP_VALIDATION http_request_validate(struct web_client *w) {
792 char *s = w->response.data->buffer, *encoded_url = NULL;
794 // is is a valid request?
795 if(!strncmp(s, "GET ", 4)) {
796 encoded_url = s = &s[4];
797 w->mode = WEB_CLIENT_MODE_NORMAL;
799 else if(!strncmp(s, "OPTIONS ", 8)) {
800 encoded_url = s = &s[8];
801 w->mode = WEB_CLIENT_MODE_OPTIONS;
803 else if(!strncmp(s, "STREAM ", 7)) {
804 encoded_url = s = &s[7];
805 w->mode = WEB_CLIENT_MODE_STREAM;
809 return HTTP_VALIDATION_NOT_SUPPORTED;
812 // find the SPACE + "HTTP/"
814 // find the next space
815 while (*s && *s != ' ') s++;
817 // is it SPACE + "HTTP/" ?
818 if(*s && !strncmp(s, " HTTP/", 6)) break;
822 // incomplete requests
825 return HTTP_VALIDATION_INCOMPLETE;
828 // we have the end of encoded_url - remember it
831 // make sure we have complete request
832 // complete requests contain: \r\n\r\n
835 while(*s && *s++ != '\r');
837 // did we reach the end?
838 if(unlikely(!*s)) break;
841 if(likely(*s++ == '\n')) {
843 // is it again \r\n ? (header end)
844 if(unlikely(*s == '\r' && s[1] == '\n')) {
845 // a valid complete HTTP request found
848 url_decode_r(w->decoded_url, encoded_url, URL_MAX + 1);
851 // copy the URL - we are going to overwrite parts of it
852 // FIXME -- we should avoid it
853 strncpyz(w->last_url, w->decoded_url, URL_MAX);
856 return HTTP_VALIDATION_OK;
859 // another header line
860 s = http_header_parse(w, s);
864 // incomplete request
866 return HTTP_VALIDATION_INCOMPLETE;
869 static inline void web_client_send_http_header(struct web_client *w) {
870 if(unlikely(w->response.code != 200))
871 buffer_no_cacheable(w->response.data);
873 // set a proper expiration date, if not already set
874 if(unlikely(!w->response.data->expires)) {
875 if(w->response.data->options & WB_CONTENT_NO_CACHEABLE)
876 w->response.data->expires = w->tv_ready.tv_sec + localhost->rrd_update_every;
878 w->response.data->expires = w->tv_ready.tv_sec + 86400;
881 // prepare the HTTP response header
882 debug(D_WEB_CLIENT, "%llu: Generating HTTP header with response %d.", w->id, w->response.code);
884 const char *content_type_string = web_content_type_to_string(w->response.data->contenttype);
885 const char *code_msg = web_response_code_to_string(w->response.code);
887 // prepare the last modified and expiration dates
888 char date[32], edate[32];
890 struct tm tmbuf, *tm;
892 tm = gmtime_r(&w->response.data->date, &tmbuf);
893 strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %Z", tm);
895 tm = gmtime_r(&w->response.data->expires, &tmbuf);
896 strftime(edate, sizeof(edate), "%a, %d %b %Y %H:%M:%S %Z", tm);
899 buffer_sprintf(w->response.header_output,
902 "Server: NetData Embedded HTTP Server\r\n"
903 "Access-Control-Allow-Origin: %s\r\n"
904 "Access-Control-Allow-Credentials: true\r\n"
905 "Content-Type: %s\r\n"
907 , w->response.code, code_msg
908 , w->keepalive?"keep-alive":"close"
910 , content_type_string
914 if(unlikely(web_x_frame_options))
915 buffer_sprintf(w->response.header_output, "X-Frame-Options: %s\r\n", web_x_frame_options);
917 if(w->cookie1[0] || w->cookie2[0]) {
919 buffer_sprintf(w->response.header_output,
920 "Set-Cookie: %s\r\n",
925 buffer_sprintf(w->response.header_output,
926 "Set-Cookie: %s\r\n",
930 if(respect_web_browser_do_not_track_policy)
931 buffer_sprintf(w->response.header_output,
932 "Tk: T;cookies\r\n");
935 if(respect_web_browser_do_not_track_policy) {
936 if(w->tracking_required)
937 buffer_sprintf(w->response.header_output,
938 "Tk: T;cookies\r\n");
940 buffer_sprintf(w->response.header_output,
945 if(w->mode == WEB_CLIENT_MODE_OPTIONS) {
946 buffer_strcat(w->response.header_output,
947 "Access-Control-Allow-Methods: GET, OPTIONS\r\n"
948 "Access-Control-Allow-Headers: accept, x-requested-with, origin, content-type, cookie, pragma, cache-control\r\n"
949 "Access-Control-Max-Age: 1209600\r\n" // 86400 * 14
953 buffer_sprintf(w->response.header_output,
954 "Cache-Control: %s\r\n"
956 (w->response.data->options & WB_CONTENT_NO_CACHEABLE)?"no-cache":"public",
960 // copy a possibly available custom header
961 if(unlikely(buffer_strlen(w->response.header)))
962 buffer_strcat(w->response.header_output, buffer_tostring(w->response.header));
964 // headers related to the transfer method
965 if(likely(w->response.zoutput)) {
966 buffer_strcat(w->response.header_output,
967 "Content-Encoding: gzip\r\n"
968 "Transfer-Encoding: chunked\r\n"
972 if(likely((w->response.data->len || w->response.rlen))) {
973 // we know the content length, put it
974 buffer_sprintf(w->response.header_output, "Content-Length: %zu\r\n", w->response.data->len? w->response.data->len: w->response.rlen);
977 // we don't know the content length, disable keep-alive
982 // end of HTTP header
983 buffer_strcat(w->response.header_output, "\r\n");
985 // sent the HTTP header
986 debug(D_WEB_DATA, "%llu: Sending response HTTP header of size %zu: '%s'"
988 , buffer_strlen(w->response.header_output)
989 , buffer_tostring(w->response.header_output)
992 web_client_crock_socket(w);
994 ssize_t bytes = send(w->ofd, buffer_tostring(w->response.header_output), buffer_strlen(w->response.header_output), 0);
995 if(bytes != (ssize_t) buffer_strlen(w->response.header_output)) {
997 w->stats_sent_bytes += bytes;
999 debug(D_WEB_CLIENT, "%llu: HTTP Header failed to be sent (I sent %zu bytes but the system sent %zd bytes). Closing web client."
1001 , buffer_strlen(w->response.header_output)
1004 WEB_CLIENT_IS_DEAD(w);
1008 w->stats_sent_bytes += bytes;
1011 static inline int web_client_process_url(RRDHOST *host, struct web_client *w, char *url);
1013 static inline int web_client_switch_host(RRDHOST *host, struct web_client *w, char *url) {
1014 static uint32_t hash_localhost = 0;
1016 if(unlikely(!hash_localhost)) {
1017 hash_localhost = simple_hash("localhost");
1020 if(host != localhost) {
1021 buffer_flush(w->response.data);
1022 buffer_strcat(w->response.data, "Nesting of hosts is not allowed.");
1026 char *tok = mystrsep(&url, "/?&");
1028 debug(D_WEB_CLIENT, "%llu: Searching for host with name '%s'.", w->id, tok);
1030 // copy the URL, we need it to serve files
1031 w->last_url[0] = '/';
1032 if(url && *url) strncpyz(&w->last_url[1], url, URL_MAX - 1);
1033 else w->last_url[1] = '\0';
1035 uint32_t hash = simple_hash(tok);
1037 if(unlikely(hash == hash_localhost && !strcmp(tok, "localhost")))
1038 return web_client_process_url(localhost, w, url);
1042 rrdhost_foreach_read(h) {
1043 if(unlikely((hash == h->hash_hostname && !strcmp(tok, h->hostname)) ||
1044 (hash == h->hash_machine_guid && !strcmp(tok, h->machine_guid)))) {
1046 return web_client_process_url(h, w, url);
1052 buffer_flush(w->response.data);
1053 w->response.data->contenttype = CT_TEXT_HTML;
1054 buffer_strcat(w->response.data, "This netdata does not maintain a database for host: ");
1055 buffer_strcat_htmlescape(w->response.data, tok?tok:"");
1059 static inline int web_client_process_url(RRDHOST *host, struct web_client *w, char *url) {
1062 hash_netdata_conf = 0,
1064 hash_datasource = 0,
1070 #ifdef NETDATA_INTERNAL_CHECKS
1071 static uint32_t hash_exit = 0, hash_debug = 0, hash_mirror = 0;
1074 if(unlikely(!hash_api)) {
1075 hash_api = simple_hash("api");
1076 hash_netdata_conf = simple_hash("netdata.conf");
1077 hash_data = simple_hash(WEB_PATH_DATA);
1078 hash_datasource = simple_hash(WEB_PATH_DATASOURCE);
1079 hash_graph = simple_hash(WEB_PATH_GRAPH);
1080 hash_list = simple_hash("list");
1081 hash_all_json = simple_hash("all.json");
1082 hash_host = simple_hash("host");
1083 #ifdef NETDATA_INTERNAL_CHECKS
1084 hash_exit = simple_hash("exit");
1085 hash_debug = simple_hash("debug");
1086 hash_mirror = simple_hash("mirror");
1090 char *tok = mystrsep(&url, "/?");
1091 if(likely(tok && *tok)) {
1092 uint32_t hash = simple_hash(tok);
1093 debug(D_WEB_CLIENT, "%llu: Processing command '%s'.", w->id, tok);
1095 if(unlikely(hash == hash_api && strcmp(tok, "api") == 0)) { // current API
1096 debug(D_WEB_CLIENT_ACCESS, "%llu: API request ...", w->id);
1097 return check_host_and_call(host, w, url, web_client_api_request);
1099 else if(unlikely(hash == hash_host && strcmp(tok, "host") == 0)) { // host switching
1100 debug(D_WEB_CLIENT_ACCESS, "%llu: host switch request ...", w->id);
1101 return web_client_switch_host(host, w, url);
1103 else if(unlikely(hash == hash_data && strcmp(tok, WEB_PATH_DATA) == 0)) { // old API "data"
1104 debug(D_WEB_CLIENT_ACCESS, "%llu: old API data request...", w->id);
1105 return check_host_and_call(host, w, url, web_client_api_old_data_request_json);
1107 else if(unlikely(hash == hash_datasource && strcmp(tok, WEB_PATH_DATASOURCE) == 0)) { // old API "datasource"
1108 debug(D_WEB_CLIENT_ACCESS, "%llu: old API datasource request...", w->id);
1109 return check_host_and_call(host, w, url, web_client_api_old_data_request_jsonp);
1111 else if(unlikely(hash == hash_graph && strcmp(tok, WEB_PATH_GRAPH) == 0)) { // old API "graph"
1112 debug(D_WEB_CLIENT_ACCESS, "%llu: old API graph request...", w->id);
1113 return check_host_and_call(host, w, url, web_client_api_old_graph_request);
1115 else if(unlikely(hash == hash_list && strcmp(tok, "list") == 0)) { // old API "list"
1116 debug(D_WEB_CLIENT_ACCESS, "%llu: old API list request...", w->id);
1117 return check_host_and_call(host, w, url, web_client_api_old_list_request);
1119 else if(unlikely(hash == hash_all_json && strcmp(tok, "all.json") == 0)) { // old API "all.json"
1120 debug(D_WEB_CLIENT_ACCESS, "%llu: old API all.json request...", w->id);
1121 return check_host_and_call(host, w, url, web_client_api_old_all_json);
1123 else if(unlikely(hash == hash_netdata_conf && strcmp(tok, "netdata.conf") == 0)) { // netdata.conf
1124 debug(D_WEB_CLIENT_ACCESS, "%llu: generating netdata.conf ...", w->id);
1125 w->response.data->contenttype = CT_TEXT_PLAIN;
1126 buffer_flush(w->response.data);
1127 config_generate(w->response.data, 0);
1130 #ifdef NETDATA_INTERNAL_CHECKS
1131 else if(unlikely(hash == hash_exit && strcmp(tok, "exit") == 0)) {
1132 w->response.data->contenttype = CT_TEXT_PLAIN;
1133 buffer_flush(w->response.data);
1136 buffer_strcat(w->response.data, "ok, will do...");
1138 buffer_strcat(w->response.data, "I am doing it already");
1140 error("web request to exit received.");
1141 netdata_cleanup_and_exit(0);
1144 else if(unlikely(hash == hash_debug && strcmp(tok, "debug") == 0)) {
1145 buffer_flush(w->response.data);
1147 // get the name of the data to show
1148 tok = mystrsep(&url, "/?&");
1150 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1152 // do we have such a data set?
1153 RRDSET *st = rrdset_find_byname(host, tok);
1154 if(!st) st = rrdset_find(host, tok);
1156 w->response.data->contenttype = CT_TEXT_HTML;
1157 buffer_strcat(w->response.data, "Chart is not found: ");
1158 buffer_strcat_htmlescape(w->response.data, tok);
1159 debug(D_WEB_CLIENT_ACCESS, "%llu: %s is not found.", w->id, tok);
1163 debug_flags |= D_RRD_STATS;
1165 if(rrdset_flag_check(st, RRDSET_FLAG_DEBUG))
1166 rrdset_flag_clear(st, RRDSET_FLAG_DEBUG);
1168 rrdset_flag_set(st, RRDSET_FLAG_DEBUG);
1170 w->response.data->contenttype = CT_TEXT_HTML;
1171 buffer_sprintf(w->response.data, "Chart has now debug %s: ", rrdset_flag_check(st, RRDSET_FLAG_DEBUG)?"enabled":"disabled");
1172 buffer_strcat_htmlescape(w->response.data, tok);
1173 debug(D_WEB_CLIENT_ACCESS, "%llu: debug for %s is %s.", w->id, tok, rrdset_flag_check(st, RRDSET_FLAG_DEBUG)?"enabled":"disabled");
1177 buffer_flush(w->response.data);
1178 buffer_strcat(w->response.data, "debug which chart?\r\n");
1181 else if(unlikely(hash == hash_mirror && strcmp(tok, "mirror") == 0)) {
1182 debug(D_WEB_CLIENT_ACCESS, "%llu: Mirroring...", w->id);
1184 // replace the zero bytes with spaces
1185 buffer_char_replace(w->response.data, '\0', ' ');
1187 // just leave the buffer as is
1188 // it will be copied back to the client
1192 #endif /* NETDATA_INTERNAL_CHECKS */
1195 char filename[FILENAME_MAX+1];
1197 strncpyz(filename, w->last_url, FILENAME_MAX);
1198 tok = mystrsep(&url, "?");
1199 buffer_flush(w->response.data);
1200 return mysendfile(w, (tok && *tok)?tok:"/");
1203 void web_client_process_request(struct web_client *w) {
1206 now_realtime_timeval(&w->tv_in);
1208 switch(http_request_validate(w)) {
1209 case HTTP_VALIDATION_OK:
1211 case WEB_CLIENT_MODE_STREAM:
1212 w->response.code = rrdpush_receiver_thread_spawn(localhost, w, w->decoded_url);
1215 case WEB_CLIENT_MODE_OPTIONS:
1216 w->response.data->contenttype = CT_TEXT_PLAIN;
1217 buffer_flush(w->response.data);
1218 buffer_strcat(w->response.data, "OK");
1219 w->response.code = 200;
1222 case WEB_CLIENT_MODE_FILECOPY:
1223 case WEB_CLIENT_MODE_NORMAL:
1224 w->response.code = web_client_process_url(localhost, w, w->decoded_url);
1229 case HTTP_VALIDATION_INCOMPLETE:
1230 if(w->response.data->len > TOO_BIG_REQUEST) {
1231 strcpy(w->last_url, "too big request");
1233 debug(D_WEB_CLIENT_ACCESS, "%llu: Received request is too big (%zu bytes).", w->id, w->response.data->len);
1235 buffer_flush(w->response.data);
1236 buffer_sprintf(w->response.data, "Received request is too big (%zu bytes).\r\n", w->response.data->len);
1237 w->response.code = 400;
1240 // wait for more data
1245 case HTTP_VALIDATION_NOT_SUPPORTED:
1246 debug(D_WEB_CLIENT_ACCESS, "%llu: Cannot understand '%s'.", w->id, w->response.data->buffer);
1248 buffer_flush(w->response.data);
1249 buffer_strcat(w->response.data, "I don't understand you...\r\n");
1250 w->response.code = 400;
1254 // keep track of the time we done processing
1255 now_realtime_timeval(&w->tv_ready);
1257 w->response.sent = 0;
1259 // set a proper last modified date
1260 if(unlikely(!w->response.data->date))
1261 w->response.data->date = w->tv_ready.tv_sec;
1263 web_client_send_http_header(w);
1265 // enable sending immediately if we have data
1266 if(w->response.data->len) w->wait_send = 1;
1267 else w->wait_send = 0;
1270 case WEB_CLIENT_MODE_STREAM:
1271 debug(D_WEB_CLIENT, "%llu: STREAM done.", w->id);
1274 case WEB_CLIENT_MODE_OPTIONS:
1275 debug(D_WEB_CLIENT, "%llu: Done preparing the OPTIONS response. Sending data (%zu bytes) to client.", w->id, w->response.data->len);
1278 case WEB_CLIENT_MODE_NORMAL:
1279 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Sending data (%zu bytes) to client.", w->id, w->response.data->len);
1282 case WEB_CLIENT_MODE_FILECOPY:
1283 if(w->response.rlen) {
1284 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending data file of %zu bytes to client.", w->id, w->response.rlen);
1285 w->wait_receive = 1;
1288 // utilize the kernel sendfile() for copying the file to the socket.
1289 // this block of code can be commented, without anything missing.
1290 // when it is commented, the program will copy the data using async I/O.
1292 long len = sendfile(w->ofd, w->ifd, NULL, w->response.data->rbytes);
1293 if(len != w->response.data->rbytes)
1294 error("%llu: sendfile() should copy %ld bytes, but copied %ld. Falling back to manual copy.", w->id, w->response.data->rbytes, len);
1296 web_client_reset(w);
1301 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending an unknown amount of bytes to client.", w->id);
1305 fatal("%llu: Unknown client mode %u.", w->id, w->mode);
1310 ssize_t web_client_send_chunk_header(struct web_client *w, size_t len)
1312 debug(D_DEFLATE, "%llu: OPEN CHUNK of %zu bytes (hex: %zx).", w->id, len, len);
1314 sprintf(buf, "%zX\r\n", len);
1316 ssize_t bytes = send(w->ofd, buf, strlen(buf), 0);
1318 debug(D_DEFLATE, "%llu: Sent chunk header %zd bytes.", w->id, bytes);
1319 w->stats_sent_bytes += bytes;
1322 else if(bytes == 0) {
1323 debug(D_WEB_CLIENT, "%llu: Did not send chunk header to the client.", w->id);
1324 WEB_CLIENT_IS_DEAD(w);
1327 debug(D_WEB_CLIENT, "%llu: Failed to send chunk header to client.", w->id);
1328 WEB_CLIENT_IS_DEAD(w);
1334 ssize_t web_client_send_chunk_close(struct web_client *w)
1336 //debug(D_DEFLATE, "%llu: CLOSE CHUNK.", w->id);
1338 ssize_t bytes = send(w->ofd, "\r\n", 2, 0);
1340 debug(D_DEFLATE, "%llu: Sent chunk suffix %zd bytes.", w->id, bytes);
1341 w->stats_sent_bytes += bytes;
1344 else if(bytes == 0) {
1345 debug(D_WEB_CLIENT, "%llu: Did not send chunk suffix to the client.", w->id);
1346 WEB_CLIENT_IS_DEAD(w);
1349 debug(D_WEB_CLIENT, "%llu: Failed to send chunk suffix to client.", w->id);
1350 WEB_CLIENT_IS_DEAD(w);
1356 ssize_t web_client_send_chunk_finalize(struct web_client *w)
1358 //debug(D_DEFLATE, "%llu: FINALIZE CHUNK.", w->id);
1360 ssize_t bytes = send(w->ofd, "\r\n0\r\n\r\n", 7, 0);
1362 debug(D_DEFLATE, "%llu: Sent chunk suffix %zd bytes.", w->id, bytes);
1363 w->stats_sent_bytes += bytes;
1366 else if(bytes == 0) {
1367 debug(D_WEB_CLIENT, "%llu: Did not send chunk finalize suffix to the client.", w->id);
1368 WEB_CLIENT_IS_DEAD(w);
1371 debug(D_WEB_CLIENT, "%llu: Failed to send chunk finalize suffix to client.", w->id);
1372 WEB_CLIENT_IS_DEAD(w);
1378 #ifdef NETDATA_WITH_ZLIB
1379 ssize_t web_client_send_deflate(struct web_client *w)
1381 ssize_t len = 0, t = 0;
1383 // when using compression,
1384 // w->response.sent is the amount of bytes passed through compression
1386 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.",
1387 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);
1389 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) {
1390 // there is nothing to send
1392 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1394 // finalize the chunk
1395 if(w->response.sent != 0) {
1396 t = web_client_send_chunk_finalize(w);
1400 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->response.rlen && w->response.rlen > w->response.data->len) {
1401 // we have to wait, more data will come
1402 debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1407 if(unlikely(!w->keepalive)) {
1408 debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %zu bytes sent.", w->id, w->response.sent);
1409 WEB_CLIENT_IS_DEAD(w);
1414 web_client_reset(w);
1415 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket.", w->id);
1419 if(w->response.zhave == w->response.zsent) {
1420 // compress more input data
1422 // close the previous open chunk
1423 if(w->response.sent != 0) {
1424 t = web_client_send_chunk_close(w);
1428 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);
1430 // give the compressor all the data not passed through the compressor yet
1431 if(w->response.data->len > w->response.sent) {
1432 w->response.zstream.next_in = (Bytef *)&w->response.data->buffer[w->response.sent - w->response.zstream.avail_in];
1433 w->response.zstream.avail_in += (uInt) (w->response.data->len - w->response.sent);
1436 // reset the compressor output buffer
1437 w->response.zstream.next_out = w->response.zbuffer;
1438 w->response.zstream.avail_out = ZLIB_CHUNK;
1440 // ask for FINISH if we have all the input
1441 int flush = Z_SYNC_FLUSH;
1442 if(w->mode == WEB_CLIENT_MODE_NORMAL
1443 || (w->mode == WEB_CLIENT_MODE_FILECOPY && !w->wait_receive && w->response.data->len == w->response.rlen)) {
1445 debug(D_DEFLATE, "%llu: Requesting Z_FINISH, if possible.", w->id);
1448 debug(D_DEFLATE, "%llu: Requesting Z_SYNC_FLUSH.", w->id);
1452 if(deflate(&w->response.zstream, flush) == Z_STREAM_ERROR) {
1453 error("%llu: Compression failed. Closing down client.", w->id);
1454 web_client_reset(w);
1458 w->response.zhave = ZLIB_CHUNK - w->response.zstream.avail_out;
1459 w->response.zsent = 0;
1461 // keep track of the bytes passed through the compressor
1462 w->response.sent = w->response.data->len;
1464 debug(D_DEFLATE, "%llu: Compression produced %zu bytes.", w->id, w->response.zhave);
1467 ssize_t t2 = web_client_send_chunk_header(w, w->response.zhave);
1468 if(t2 < 0) return t2;
1472 debug(D_WEB_CLIENT, "%llu: Sending %zu bytes of data (+%zd of chunk header).", w->id, w->response.zhave - w->response.zsent, t);
1474 len = send(w->ofd, &w->response.zbuffer[w->response.zsent], (size_t) (w->response.zhave - w->response.zsent), MSG_DONTWAIT);
1476 w->stats_sent_bytes += len;
1477 w->response.zsent += len;
1479 debug(D_WEB_CLIENT, "%llu: Sent %zd bytes.", w->id, len);
1482 debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client (zhave = %zu, zsent = %zu, need to send = %zu).",
1483 w->id, w->response.zhave, w->response.zsent, w->response.zhave - w->response.zsent);
1485 WEB_CLIENT_IS_DEAD(w);
1488 debug(D_WEB_CLIENT, "%llu: Failed to send data to client.", w->id);
1489 WEB_CLIENT_IS_DEAD(w);
1494 #endif // NETDATA_WITH_ZLIB
1496 ssize_t web_client_send(struct web_client *w) {
1497 #ifdef NETDATA_WITH_ZLIB
1498 if(likely(w->response.zoutput)) return web_client_send_deflate(w);
1499 #endif // NETDATA_WITH_ZLIB
1503 if(unlikely(w->response.data->len - w->response.sent == 0)) {
1504 // there is nothing to send
1506 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1508 // there can be two cases for this
1509 // A. we have done everything
1510 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
1512 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->response.rlen && w->response.rlen > w->response.data->len) {
1513 // we have to wait, more data will come
1514 debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1519 if(unlikely(!w->keepalive)) {
1520 debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %zu bytes sent.", w->id, w->response.sent);
1521 WEB_CLIENT_IS_DEAD(w);
1525 web_client_reset(w);
1526 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1530 bytes = send(w->ofd, &w->response.data->buffer[w->response.sent], w->response.data->len - w->response.sent, MSG_DONTWAIT);
1531 if(likely(bytes > 0)) {
1532 w->stats_sent_bytes += bytes;
1533 w->response.sent += bytes;
1534 debug(D_WEB_CLIENT, "%llu: Sent %zd bytes.", w->id, bytes);
1536 else if(likely(bytes == 0)) {
1537 debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client.", w->id);
1538 WEB_CLIENT_IS_DEAD(w);
1541 debug(D_WEB_CLIENT, "%llu: Failed to send data to client.", w->id);
1542 WEB_CLIENT_IS_DEAD(w);
1548 ssize_t web_client_receive(struct web_client *w)
1550 // do we have any space for more data?
1551 buffer_need_bytes(w->response.data, WEB_REQUEST_LENGTH);
1553 ssize_t left = w->response.data->size - w->response.data->len;
1556 if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY))
1557 bytes = read(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1));
1559 bytes = recv(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1), MSG_DONTWAIT);
1561 if(likely(bytes > 0)) {
1562 if(w->mode != WEB_CLIENT_MODE_FILECOPY)
1563 w->stats_received_bytes += bytes;
1565 size_t old = w->response.data->len;
1566 w->response.data->len += bytes;
1567 w->response.data->buffer[w->response.data->len] = '\0';
1569 debug(D_WEB_CLIENT, "%llu: Received %zd bytes.", w->id, bytes);
1570 debug(D_WEB_DATA, "%llu: Received data: '%s'.", w->id, &w->response.data->buffer[old]);
1572 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1575 if(w->response.rlen && w->response.data->len >= w->response.rlen)
1576 w->wait_receive = 0;
1579 else if(likely(bytes == 0)) {
1580 debug(D_WEB_CLIENT, "%llu: Out of input 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.
1586 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1587 // we are copying data from ifd to ofd
1588 // let it finish copying...
1589 w->wait_receive = 0;
1591 debug(D_WEB_CLIENT, "%llu: Read the whole file.", w->id);
1592 if(w->ifd != w->ofd) close(w->ifd);
1596 debug(D_WEB_CLIENT, "%llu: failed to receive data.", w->id);
1597 WEB_CLIENT_IS_DEAD(w);
1601 debug(D_WEB_CLIENT, "%llu: receive data failed.", w->id);
1602 WEB_CLIENT_IS_DEAD(w);
1609 // --------------------------------------------------------------------------------------
1610 // the thread of a single client
1612 // 1. waits for input and output, using async I/O
1613 // 2. it processes HTTP requests
1614 // 3. it generates HTTP responses
1615 // 4. it copies data from input to output if mode is FILECOPY
1617 void *web_client_main(void *ptr)
1619 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
1620 error("Cannot set pthread cancel type to DEFERRED.");
1622 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
1623 error("Cannot set pthread cancel state to ENABLE.");
1625 struct web_client *w = ptr;
1626 struct pollfd fds[2], *ifd, *ofd;
1627 int retval, timeout;
1630 log_access("%llu: %s port %s connected on thread task id %d", w->id, w->client_ip, w->client_port, gettid());
1633 if(unlikely(netdata_exit)) break;
1635 if(unlikely(w->dead)) {
1636 debug(D_WEB_CLIENT, "%llu: client is dead.", w->id);
1639 else if(unlikely(!w->wait_receive && !w->wait_send)) {
1640 debug(D_WEB_CLIENT, "%llu: client is not set for neither receiving nor sending data.", w->id);
1644 if(unlikely(w->ifd < 0 || w->ofd < 0)) {
1645 error("%llu: invalid file descriptor, ifd = %d, ofd = %d (required 0 <= fd", w->id, w->ifd, w->ofd);
1649 if(w->ifd == w->ofd) {
1654 if(w->wait_receive) fds[0].events |= POLLIN;
1655 if(w->wait_send) fds[0].events |= POLLOUT;
1661 ifd = ofd = &fds[0];
1669 if(w->wait_receive) fds[0].events |= POLLIN;
1675 if(w->wait_send) fds[1].events |= POLLOUT;
1681 debug(D_WEB_CLIENT, "%llu: Waiting socket async I/O for %s %s", w->id, w->wait_receive?"INPUT":"", w->wait_send?"OUTPUT":"");
1683 timeout = web_client_timeout * 1000;
1684 retval = poll(fds, fdmax, timeout);
1686 if(unlikely(netdata_exit)) break;
1688 if(unlikely(retval == -1)) {
1689 if(errno == EAGAIN || errno == EINTR) {
1690 debug(D_WEB_CLIENT, "%llu: EAGAIN received.", w->id);
1694 debug(D_WEB_CLIENT, "%llu: LISTENER: poll() failed (input fd = %d, output fd = %d). Closing client.", w->id, w->ifd, w->ofd);
1697 else if(unlikely(!retval)) {
1698 debug(D_WEB_CLIENT, "%llu: Timeout while waiting socket async I/O for %s %s", w->id, w->wait_receive?"INPUT":"", w->wait_send?"OUTPUT":"");
1702 if(unlikely(netdata_exit)) break;
1705 if(w->wait_send && ofd->revents & POLLOUT) {
1707 if(web_client_send(w) < 0) {
1708 debug(D_WEB_CLIENT, "%llu: Cannot send data to client. Closing client.", w->id);
1713 if(unlikely(netdata_exit)) break;
1715 if(w->wait_receive && (ifd->revents & POLLIN || ifd->revents & POLLPRI)) {
1717 if(web_client_receive(w) < 0) {
1718 debug(D_WEB_CLIENT, "%llu: Cannot receive data from client. Closing client.", w->id);
1722 if(w->mode == WEB_CLIENT_MODE_NORMAL) {
1723 debug(D_WEB_CLIENT, "%llu: Attempting to process received data.", w->id);
1724 web_client_process_request(w);
1726 // if the sockets are closed, may have transferred this client
1728 if(unlikely(w->mode == WEB_CLIENT_MODE_STREAM))
1733 if(unlikely(!used)) {
1734 debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on socket.", w->id);
1739 web_client_reset(w);
1741 log_access("%llu: %s port %s disconnected from thread task id %d", w->id, w->client_ip, w->client_port, gettid());
1742 debug(D_WEB_CLIENT, "%llu: done...", w->id);
1744 // close the sockets/files now
1745 // to free file descriptors
1746 if(w->ifd == w->ofd) {
1747 if(w->ifd != -1) close(w->ifd);
1750 if(w->ifd != -1) close(w->ifd);
1751 if(w->ofd != -1) close(w->ofd);