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 web_donotrack_comply = 0;
10 #ifdef NETDATA_WITH_ZLIB
11 int web_enable_gzip = 1, web_gzip_level = 3, web_gzip_strategy = Z_DEFAULT_STRATEGY;
12 #endif /* NETDATA_WITH_ZLIB */
14 struct web_client *web_clients = NULL;
15 unsigned long long web_clients_count = 0;
17 inline int web_client_crock_socket(struct web_client *w) {
19 if(likely(!w->tcp_cork && w->ofd != -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);
32 inline int web_client_uncrock_socket(struct web_client *w) {
34 if(likely(w->tcp_cork && w->ofd != -1)) {
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);
47 struct web_client *web_client_create(int listener)
51 w = calloc(1, sizeof(struct web_client));
53 error("Cannot allocate new web_client memory.");
57 w->id = ++web_clients_count;
58 w->mode = WEB_CLIENT_MODE_NORMAL;
61 struct sockaddr *sadr;
64 sadr = (struct sockaddr*) &w->clientaddr;
65 addrlen = sizeof(w->clientaddr);
67 w->ifd = accept4(listener, sadr, &addrlen, SOCK_NONBLOCK);
69 error("%llu: Cannot accept new incoming connection.", w->id);
75 if(getnameinfo(sadr, addrlen, w->client_ip, NI_MAXHOST, w->client_port, NI_MAXSERV, NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
76 error("Cannot getnameinfo() on received client connection.");
77 strncpyz(w->client_ip, "UNKNOWN", NI_MAXHOST);
78 strncpyz(w->client_port, "UNKNOWN", NI_MAXSERV);
80 w->client_ip[NI_MAXHOST] = '\0';
81 w->client_port[NI_MAXSERV] = '\0';
83 switch(sadr->sa_family) {
85 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 if(strncmp(w->client_ip, "::ffff:", 7) == 0) {
90 memmove(w->client_ip, &w->client_ip[7], strlen(&w->client_ip[7]) + 1);
91 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);
94 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);
98 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);
103 if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0)
104 error("%llu: failed to enable TCP_NODELAY on socket.", w->id);
107 if(setsockopt(w->ifd, SOL_SOCKET, SO_KEEPALIVE, (char *) &flag, sizeof(int)) != 0)
108 error("%llu: Cannot set SO_KEEPALIVE on socket.", w->id);
111 w->response.data = buffer_create(INITIAL_WEB_DATA_LENGTH);
112 if(unlikely(!w->response.data)) {
113 // no need for error log - web_buffer_create already logged the error
119 w->response.header = buffer_create(HTTP_RESPONSE_HEADER_SIZE);
120 if(unlikely(!w->response.header)) {
121 // no need for error log - web_buffer_create already logged the error
122 buffer_free(w->response.data);
128 w->response.header_output = buffer_create(HTTP_RESPONSE_HEADER_SIZE);
129 if(unlikely(!w->response.header_output)) {
130 // no need for error log - web_buffer_create already logged the error
131 buffer_free(w->response.header);
132 buffer_free(w->response.data);
141 if(web_clients) web_clients->prev = w;
142 w->next = web_clients;
145 global_statistics.connected_clients++;
150 void web_client_reset(struct web_client *w) {
151 web_client_uncrock_socket(w);
153 debug(D_WEB_CLIENT, "%llu: Reseting client.", w->id);
155 if(likely(w->last_url[0])) {
157 gettimeofday(&tv, NULL);
159 size_t size = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->response.rlen:w->response.data->len;
161 #ifdef NETDATA_WITH_ZLIB
162 if(likely(w->response.zoutput)) sent = (size_t)w->response.zstream.total_out;
165 // --------------------------------------------------------------------
168 if(web_server_mode == WEB_SERVER_MODE_MULTI_THREADED)
169 global_statistics_lock();
171 global_statistics.web_requests++;
172 global_statistics.web_usec += usecdiff(&tv, &w->tv_in);
173 global_statistics.bytes_received += w->stats_received_bytes;
174 global_statistics.bytes_sent += w->stats_sent_bytes;
175 global_statistics.content_size += size;
176 global_statistics.compressed_content_size += sent;
178 if(web_server_mode == WEB_SERVER_MODE_MULTI_THREADED)
179 global_statistics_unlock();
181 w->stats_received_bytes = 0;
182 w->stats_sent_bytes = 0;
185 // --------------------------------------------------------------------
188 log_access("%llu: (sent/all = %zu/%zu bytes %0.0f%%, prep/sent/total = %0.2f/%0.2f/%0.2f ms) %s: %d '%s'",
190 sent, size, -((size > 0) ? ((size - sent) / (double) size * 100.0) : 0.0),
191 usecdiff(&w->tv_ready, &w->tv_in) / 1000.0,
192 usecdiff(&tv, &w->tv_ready) / 1000.0,
193 usecdiff(&tv, &w->tv_in) / 1000.0,
194 (w->mode == WEB_CLIENT_MODE_FILECOPY) ? "filecopy" : ((w->mode == WEB_CLIENT_MODE_OPTIONS)
195 ? "options" : "data"),
201 if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY)) {
202 if(w->ifd != w->ofd) {
203 debug(D_WEB_CLIENT, "%llu: Closing filecopy input file descriptor %d.", w->id, w->ifd);
204 if(w->ifd != -1) close(w->ifd);
209 w->last_url[0] = '\0';
210 w->cookie1[0] = '\0';
211 w->cookie2[0] = '\0';
215 w->mode = WEB_CLIENT_MODE_NORMAL;
219 w->tracking_required = 0;
221 w->decoded_url[0] = '\0';
223 buffer_reset(w->response.header_output);
224 buffer_reset(w->response.header);
225 buffer_reset(w->response.data);
226 w->response.rlen = 0;
227 w->response.sent = 0;
228 w->response.code = 0;
233 w->response.zoutput = 0;
235 // if we had enabled compression, release it
236 #ifdef NETDATA_WITH_ZLIB
237 if(w->response.zinitialized) {
238 debug(D_DEFLATE, "%llu: Freeing compression resources.", w->id);
239 deflateEnd(&w->response.zstream);
240 w->response.zsent = 0;
241 w->response.zhave = 0;
242 w->response.zstream.avail_in = 0;
243 w->response.zstream.avail_out = 0;
244 w->response.zstream.total_in = 0;
245 w->response.zstream.total_out = 0;
246 w->response.zinitialized = 0;
248 #endif // NETDATA_WITH_ZLIB
251 struct web_client *web_client_free(struct web_client *w) {
254 struct web_client *n = w->next;
255 if(w == web_clients) web_clients = n;
257 debug(D_WEB_CLIENT_ACCESS, "%llu: Closing web client from %s port %s.", w->id, w->client_ip, w->client_port);
259 if(w->prev) w->prev->next = w->next;
260 if(w->next) w->next->prev = w->prev;
261 if(w->response.header_output) buffer_free(w->response.header_output);
262 if(w->response.header) buffer_free(w->response.header);
263 if(w->response.data) buffer_free(w->response.data);
264 if(w->ifd != -1) close(w->ifd);
265 if(w->ofd != -1 && w->ofd != w->ifd) close(w->ofd);
268 global_statistics.connected_clients--;
273 uid_t web_files_uid(void) {
274 static char *web_owner = NULL;
275 static uid_t owner_uid = 0;
277 if(unlikely(!web_owner)) {
278 web_owner = config_get("global", "web files owner", config_get("global", "run as user", ""));
279 if(!web_owner || !*web_owner)
280 owner_uid = geteuid();
282 // getpwnam() is not thread safe,
283 // but we have called this function once
284 // while single threaded
285 struct passwd *pw = getpwnam(web_owner);
287 error("User '%s' is not present. Ignoring option.", web_owner);
288 owner_uid = geteuid();
291 debug(D_WEB_CLIENT, "Web files owner set to %s.", web_owner);
292 owner_uid = pw->pw_uid;
300 gid_t web_files_gid(void) {
301 static char *web_group = NULL;
302 static gid_t owner_gid = 0;
304 if(unlikely(!web_group)) {
305 web_group = config_get("global", "web files group", config_get("global", "web files owner", ""));
306 if(!web_group || !*web_group)
307 owner_gid = getegid();
309 // getgrnam() is not thread safe,
310 // but we have called this function once
311 // while single threaded
312 struct group *gr = getgrnam(web_group);
314 error("Group '%s' is not present. Ignoring option.", web_group);
315 owner_gid = getegid();
318 debug(D_WEB_CLIENT, "Web files group set to %s.", web_group);
319 owner_gid = gr->gr_gid;
327 int mysendfile(struct web_client *w, char *filename)
329 static char *web_dir = NULL;
331 // initialize our static data
332 if(unlikely(!web_dir)) web_dir = config_get("global", "web files directory", WEB_DIR);
334 debug(D_WEB_CLIENT, "%llu: Looking for file '%s/%s'", w->id, web_dir, filename);
336 // skip leading slashes
337 while (*filename == '/') filename++;
339 // if the filename contain known paths, skip them
340 if(strncmp(filename, WEB_PATH_FILE "/", strlen(WEB_PATH_FILE) + 1) == 0)
341 filename = &filename[strlen(WEB_PATH_FILE) + 1];
344 for(s = filename; *s ;s++) {
345 if( !isalnum(*s) && *s != '/' && *s != '.' && *s != '-' && *s != '_') {
346 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
347 buffer_sprintf(w->response.data, "File '%s' cannot be served. Filename contains invalid character '%c'", filename, *s);
352 // if the filename contains a .. refuse to serve it
353 if(strstr(filename, "..") != 0) {
354 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
355 buffer_sprintf(w->response.data, "File '%s' cannot be served. Relative filenames with '..' in them are not supported.", filename);
360 char webfilename[FILENAME_MAX + 1];
361 snprintfz(webfilename, FILENAME_MAX, "%s/%s", web_dir, filename);
363 // check if the file exists
365 if(lstat(webfilename, &stat) != 0) {
366 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not found.", w->id, webfilename);
367 buffer_sprintf(w->response.data, "File '%s' does not exist, or is not accessible.", webfilename);
371 // check if the file is owned by expected user
372 if(stat.st_uid != web_files_uid()) {
373 error("%llu: File '%s' is owned by user %u (expected user %u). Access Denied.", w->id, webfilename, stat.st_uid, web_files_uid());
374 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", webfilename);
378 // check if the file is owned by expected group
379 if(stat.st_gid != web_files_gid()) {
380 error("%llu: File '%s' is owned by group %u (expected group %u). Access Denied.", w->id, webfilename, stat.st_gid, web_files_gid());
381 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", webfilename);
385 if((stat.st_mode & S_IFMT) == S_IFDIR) {
386 snprintfz(webfilename, FILENAME_MAX, "%s/index.html", filename);
387 return mysendfile(w, webfilename);
390 if((stat.st_mode & S_IFMT) != S_IFREG) {
391 error("%llu: File '%s' is not a regular file. Access Denied.", w->id, webfilename);
392 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", webfilename);
397 w->ifd = open(webfilename, O_NONBLOCK, O_RDONLY);
401 if(errno == EBUSY || errno == EAGAIN) {
402 error("%llu: File '%s' is busy, sending 307 Moved Temporarily to force retry.", w->id, webfilename);
403 buffer_sprintf(w->response.header, "Location: /" WEB_PATH_FILE "/%s\r\n", filename);
404 buffer_sprintf(w->response.data, "The file '%s' is currently busy. Please try again later.", webfilename);
408 error("%llu: Cannot open file '%s'.", w->id, webfilename);
409 buffer_sprintf(w->response.data, "Cannot open file '%s'.", webfilename);
413 if(fcntl(w->ifd, F_SETFL, O_NONBLOCK) < 0)
414 error("%llu: Cannot set O_NONBLOCK on file '%s'.", w->id, webfilename);
416 // pick a Content-Type for the file
417 if(strstr(filename, ".html") != NULL) w->response.data->contenttype = CT_TEXT_HTML;
418 else if(strstr(filename, ".js") != NULL) w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
419 else if(strstr(filename, ".css") != NULL) w->response.data->contenttype = CT_TEXT_CSS;
420 else if(strstr(filename, ".xml") != NULL) w->response.data->contenttype = CT_TEXT_XML;
421 else if(strstr(filename, ".xsl") != NULL) w->response.data->contenttype = CT_TEXT_XSL;
422 else if(strstr(filename, ".txt") != NULL) w->response.data->contenttype = CT_TEXT_PLAIN;
423 else if(strstr(filename, ".svg") != NULL) w->response.data->contenttype = CT_IMAGE_SVG_XML;
424 else if(strstr(filename, ".ttf") != NULL) w->response.data->contenttype = CT_APPLICATION_X_FONT_TRUETYPE;
425 else if(strstr(filename, ".otf") != NULL) w->response.data->contenttype = CT_APPLICATION_X_FONT_OPENTYPE;
426 else if(strstr(filename, ".woff2")!= NULL) w->response.data->contenttype = CT_APPLICATION_FONT_WOFF2;
427 else if(strstr(filename, ".woff") != NULL) w->response.data->contenttype = CT_APPLICATION_FONT_WOFF;
428 else if(strstr(filename, ".eot") != NULL) w->response.data->contenttype = CT_APPLICATION_VND_MS_FONTOBJ;
429 else if(strstr(filename, ".png") != NULL) w->response.data->contenttype = CT_IMAGE_PNG;
430 else if(strstr(filename, ".jpg") != NULL) w->response.data->contenttype = CT_IMAGE_JPG;
431 else if(strstr(filename, ".jpeg") != NULL) w->response.data->contenttype = CT_IMAGE_JPG;
432 else if(strstr(filename, ".gif") != NULL) w->response.data->contenttype = CT_IMAGE_GIF;
433 else if(strstr(filename, ".bmp") != NULL) w->response.data->contenttype = CT_IMAGE_BMP;
434 else if(strstr(filename, ".ico") != NULL) w->response.data->contenttype = CT_IMAGE_XICON;
435 else if(strstr(filename, ".icns") != NULL) w->response.data->contenttype = CT_IMAGE_ICNS;
436 else w->response.data->contenttype = CT_APPLICATION_OCTET_STREAM;
438 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);
440 w->mode = WEB_CLIENT_MODE_FILECOPY;
443 buffer_flush(w->response.data);
444 w->response.rlen = stat.st_size;
445 w->response.data->date = stat.st_mtim.tv_sec;
451 #ifdef NETDATA_WITH_ZLIB
452 void web_client_enable_deflate(struct web_client *w, int gzip) {
453 if(unlikely(w->response.zinitialized)) {
454 error("%llu: Compression has already be initialized for this client.", w->id);
458 if(unlikely(w->response.sent)) {
459 error("%llu: Cannot enable compression in the middle of a conversation.", w->id);
463 w->response.zstream.zalloc = Z_NULL;
464 w->response.zstream.zfree = Z_NULL;
465 w->response.zstream.opaque = Z_NULL;
467 w->response.zstream.next_in = (Bytef *)w->response.data->buffer;
468 w->response.zstream.avail_in = 0;
469 w->response.zstream.total_in = 0;
471 w->response.zstream.next_out = w->response.zbuffer;
472 w->response.zstream.avail_out = 0;
473 w->response.zstream.total_out = 0;
475 w->response.zstream.zalloc = Z_NULL;
476 w->response.zstream.zfree = Z_NULL;
477 w->response.zstream.opaque = Z_NULL;
479 // if(deflateInit(&w->response.zstream, Z_DEFAULT_COMPRESSION) != Z_OK) {
480 // error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
484 // Select GZIP compression: windowbits = 15 + 16 = 31
485 if(deflateInit2(&w->response.zstream, web_gzip_level, Z_DEFLATED, 15 + ((gzip)?16:0), 8, web_gzip_strategy) != Z_OK) {
486 error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
490 w->response.zsent = 0;
491 w->response.zoutput = 1;
492 w->response.zinitialized = 1;
494 debug(D_DEFLATE, "%llu: Initialized compression.", w->id);
496 #endif // NETDATA_WITH_ZLIB
498 uint32_t web_client_api_request_v1_data_options(char *o)
500 uint32_t ret = 0x00000000;
503 while(o && *o && (tok = mystrsep(&o, ", |"))) {
506 if(!strcmp(tok, "nonzero"))
507 ret |= RRDR_OPTION_NONZERO;
508 else if(!strcmp(tok, "flip") || !strcmp(tok, "reversed") || !strcmp(tok, "reverse"))
509 ret |= RRDR_OPTION_REVERSED;
510 else if(!strcmp(tok, "jsonwrap"))
511 ret |= RRDR_OPTION_JSON_WRAP;
512 else if(!strcmp(tok, "min2max"))
513 ret |= RRDR_OPTION_MIN2MAX;
514 else if(!strcmp(tok, "ms") || !strcmp(tok, "milliseconds"))
515 ret |= RRDR_OPTION_MILLISECONDS;
516 else if(!strcmp(tok, "abs") || !strcmp(tok, "absolute") || !strcmp(tok, "absolute_sum") || !strcmp(tok, "absolute-sum"))
517 ret |= RRDR_OPTION_ABSOLUTE;
518 else if(!strcmp(tok, "seconds"))
519 ret |= RRDR_OPTION_SECONDS;
520 else if(!strcmp(tok, "null2zero"))
521 ret |= RRDR_OPTION_NULL2ZERO;
522 else if(!strcmp(tok, "objectrows"))
523 ret |= RRDR_OPTION_OBJECTSROWS;
524 else if(!strcmp(tok, "google_json"))
525 ret |= RRDR_OPTION_GOOGLE_JSON;
526 else if(!strcmp(tok, "percentage"))
527 ret |= RRDR_OPTION_PERCENTAGE;
528 else if(!strcmp(tok, "unaligned"))
529 ret |= RRDR_OPTION_NOT_ALIGNED;
535 uint32_t web_client_api_request_v1_data_format(char *name)
537 if(!strcmp(name, DATASOURCE_FORMAT_DATATABLE_JSON)) // datatable
538 return DATASOURCE_DATATABLE_JSON;
540 else if(!strcmp(name, DATASOURCE_FORMAT_DATATABLE_JSONP)) // datasource
541 return DATASOURCE_DATATABLE_JSONP;
543 else if(!strcmp(name, DATASOURCE_FORMAT_JSON)) // json
544 return DATASOURCE_JSON;
546 else if(!strcmp(name, DATASOURCE_FORMAT_JSONP)) // jsonp
547 return DATASOURCE_JSONP;
549 else if(!strcmp(name, DATASOURCE_FORMAT_SSV)) // ssv
550 return DATASOURCE_SSV;
552 else if(!strcmp(name, DATASOURCE_FORMAT_CSV)) // csv
553 return DATASOURCE_CSV;
555 else if(!strcmp(name, DATASOURCE_FORMAT_TSV) || !strcmp(name, "tsv-excel")) // tsv
556 return DATASOURCE_TSV;
558 else if(!strcmp(name, DATASOURCE_FORMAT_HTML)) // html
559 return DATASOURCE_HTML;
561 else if(!strcmp(name, DATASOURCE_FORMAT_JS_ARRAY)) // array
562 return DATASOURCE_JS_ARRAY;
564 else if(!strcmp(name, DATASOURCE_FORMAT_SSV_COMMA)) // ssvcomma
565 return DATASOURCE_SSV_COMMA;
567 else if(!strcmp(name, DATASOURCE_FORMAT_CSV_JSON_ARRAY)) // csvjsonarray
568 return DATASOURCE_CSV_JSON_ARRAY;
570 return DATASOURCE_JSON;
573 uint32_t web_client_api_request_v1_data_google_format(char *name)
575 if(!strcmp(name, "json"))
576 return DATASOURCE_DATATABLE_JSONP;
578 else if(!strcmp(name, "html"))
579 return DATASOURCE_HTML;
581 else if(!strcmp(name, "csv"))
582 return DATASOURCE_CSV;
584 else if(!strcmp(name, "tsv-excel"))
585 return DATASOURCE_TSV;
587 return DATASOURCE_JSON;
590 int web_client_api_request_v1_data_group(char *name)
592 if(!strcmp(name, "max"))
595 else if(!strcmp(name, "average"))
596 return GROUP_AVERAGE;
598 else if(!strcmp(name, "sum"))
601 else if(!strcmp(name, "incremental-sum"))
602 return GROUP_INCREMENTAL_SUM;
604 return GROUP_AVERAGE;
607 int web_client_api_request_v1_charts(struct web_client *w, char *url)
611 buffer_flush(w->response.data);
612 w->response.data->contenttype = CT_APPLICATION_JSON;
613 rrd_stats_api_v1_charts(w->response.data);
617 int web_client_api_request_v1_chart(struct web_client *w, char *url)
622 buffer_flush(w->response.data);
625 char *value = mystrsep(&url, "?&[]");
626 if(!value || !*value) continue;
628 char *name = mystrsep(&value, "=");
629 if(!name || !*name) continue;
630 if(!value || !*value) continue;
632 // name and value are now the parameters
633 // they are not null and not empty
635 if(!strcmp(name, "chart")) chart = value;
637 /// buffer_sprintf(w->response.data, "Unknown parameter '%s' in request.", name);
642 if(!chart || !*chart) {
643 buffer_sprintf(w->response.data, "No chart id is given at the request.");
647 RRDSET *st = rrdset_find(chart);
648 if(!st) st = rrdset_find_byname(chart);
650 buffer_sprintf(w->response.data, "Chart '%s' is not found.", chart);
655 w->response.data->contenttype = CT_APPLICATION_JSON;
656 rrd_stats_api_v1_chart(st, w->response.data);
663 int web_client_api_v1_badge(struct web_client *w, char *url) {
665 buffer_flush(w->response.data);
667 BUFFER *dimensions = NULL;
669 const char *chart = NULL
673 , *multiply_str = NULL
677 , *label_color = NULL
678 , *value_color = NULL
679 , *refresh_str = NULL
680 , *precision_str = NULL;
682 int group = GROUP_AVERAGE;
683 uint32_t options = 0x00000000;
686 char *value = mystrsep(&url, "/?&[]");
687 if(!value || !*value) continue;
689 char *name = mystrsep(&value, "=");
690 if(!name || !*name) continue;
691 if(!value || !*value) continue;
693 debug(D_WEB_CLIENT, "%llu: API v1 badge.svg query param '%s' with value '%s'", w->id, name, value);
695 // name and value are now the parameters
696 // they are not null and not empty
698 if(!strcmp(name, "chart")) chart = value;
699 else if(!strcmp(name, "dimension") || !strcmp(name, "dim") || !strcmp(name, "dimensions") || !strcmp(name, "dims")) {
701 dimensions = buffer_create(strlen(value));
704 buffer_strcat(dimensions, "|");
705 buffer_strcat(dimensions, value);
708 else if(!strcmp(name, "after")) after_str = value;
709 else if(!strcmp(name, "before")) before_str = value;
710 else if(!strcmp(name, "points")) points_str = value;
711 else if(!strcmp(name, "group")) {
712 group = web_client_api_request_v1_data_group(value);
714 else if(!strcmp(name, "options")) {
715 options |= web_client_api_request_v1_data_options(value);
717 else if(!strcmp(name, "label")) label = value;
718 else if(!strcmp(name, "units")) units = value;
719 else if(!strcmp(name, "label_color")) label_color = value;
720 else if(!strcmp(name, "value_color")) value_color = value;
721 else if(!strcmp(name, "multiply")) multiply_str = value;
722 else if(!strcmp(name, "divide")) divide_str = value;
723 else if(!strcmp(name, "refresh")) refresh_str = value;
724 else if(!strcmp(name, "precision")) precision_str = value;
727 if(!chart || !*chart) {
728 buffer_sprintf(w->response.data, "No chart id is given at the request.");
732 RRDSET *st = rrdset_find(chart);
733 if(!st) st = rrdset_find_byname(chart);
735 buffer_svg(w->response.data, "chart not found", 0, "", NULL, NULL, 1, -1);
740 long long multiply = (multiply_str && *multiply_str )?atol(multiply_str):1;
741 long long divide = (divide_str && *divide_str )?atol(divide_str):1;
742 long long before = (before_str && *before_str )?atol(before_str):0;
743 long long after = (after_str && *after_str )?atol(after_str):-st->update_every;
744 int points = (points_str && *points_str )?atoi(points_str):1;
745 int precision = (precision_str && *precision_str)?atoi(precision_str):-1;
747 if(!multiply) multiply = 1;
748 if(!divide) divide = 1;
751 if(refresh_str && *refresh_str) {
752 if(!strcmp(refresh_str, "auto")) {
753 if(options & RRDR_OPTION_NOT_ALIGNED)
754 refresh = st->update_every;
756 refresh = (before - after);
757 if(refresh < 0) refresh = -refresh;
761 refresh = atoi(refresh_str);
762 if(refresh < 0) refresh = -refresh;
768 const char *dim = buffer_tostring(dimensions);
769 if(*dim == '|') dim++;
776 if(options & RRDR_OPTION_PERCENTAGE)
782 debug(D_WEB_CLIENT, "%llu: API command 'badge.svg' for chart '%s', dimensions '%s', after '%lld', before '%lld', points '%d', group '%d', options '0x%08x'"
785 , (dimensions)?buffer_tostring(dimensions):""
793 time_t latest_timestamp = 0;
794 int value_is_null = 1;
795 calculated_number n = 0;
798 // if the collected value is too old, don't calculate its value
799 if(rrdset_last_entry_t(st) >= (time(NULL) - (st->update_every * st->gap_when_lost_iterations_above)))
800 ret = rrd2value(st, w->response.data, &n, dimensions, points, after, before, group, options, &latest_timestamp, &value_is_null);
802 // if the value cannot be calculated, show empty badge
809 buffer_sprintf(w->response.header, "Refresh: %d\r\n", refresh);
812 buffer_svg(w->response.data, label, n * multiply / divide, units, label_color, value_color, value_is_null, precision);
816 buffer_free(dimensions);
820 // returns the HTTP code
821 int web_client_api_request_v1_data(struct web_client *w, char *url)
823 debug(D_WEB_CLIENT, "%llu: API v1 data with URL '%s'", w->id, url);
826 BUFFER *dimensions = NULL;
828 buffer_flush(w->response.data);
830 char *google_version = "0.6",
833 *google_out = "json",
834 *responseHandler = NULL,
837 time_t last_timestamp_in_data = 0, google_timestamp = 0;
842 , *points_str = NULL;
844 int group = GROUP_AVERAGE;
845 uint32_t format = DATASOURCE_JSON;
846 uint32_t options = 0x00000000;
849 char *value = mystrsep(&url, "?&[]");
850 if(!value || !*value) continue;
852 char *name = mystrsep(&value, "=");
853 if(!name || !*name) continue;
854 if(!value || !*value) continue;
856 debug(D_WEB_CLIENT, "%llu: API v1 data query param '%s' with value '%s'", w->id, name, value);
858 // name and value are now the parameters
859 // they are not null and not empty
861 if(!strcmp(name, "chart")) chart = value;
862 else if(!strcmp(name, "dimension") || !strcmp(name, "dim") || !strcmp(name, "dimensions") || !strcmp(name, "dims")) {
863 if(!dimensions) dimensions = buffer_create(strlen(value));
865 buffer_strcat(dimensions, "|");
866 buffer_strcat(dimensions, value);
869 else if(!strcmp(name, "after")) after_str = value;
870 else if(!strcmp(name, "before")) before_str = value;
871 else if(!strcmp(name, "points")) points_str = value;
872 else if(!strcmp(name, "group")) {
873 group = web_client_api_request_v1_data_group(value);
875 else if(!strcmp(name, "format")) {
876 format = web_client_api_request_v1_data_format(value);
878 else if(!strcmp(name, "options")) {
879 options |= web_client_api_request_v1_data_options(value);
881 else if(!strcmp(name, "callback")) {
882 responseHandler = value;
884 else if(!strcmp(name, "filename")) {
887 else if(!strcmp(name, "tqx")) {
888 // parse Google Visualization API options
889 // https://developers.google.com/chart/interactive/docs/dev/implementing_data_source
890 char *tqx_name, *tqx_value;
893 tqx_value = mystrsep(&value, ";");
894 if(!tqx_value || !*tqx_value) continue;
896 tqx_name = mystrsep(&tqx_value, ":");
897 if(!tqx_name || !*tqx_name) continue;
898 if(!tqx_value || !*tqx_value) continue;
900 if(!strcmp(tqx_name, "version"))
901 google_version = tqx_value;
902 else if(!strcmp(tqx_name, "reqId"))
903 google_reqId = tqx_value;
904 else if(!strcmp(tqx_name, "sig")) {
905 google_sig = tqx_value;
906 google_timestamp = strtoul(google_sig, NULL, 0);
908 else if(!strcmp(tqx_name, "out")) {
909 google_out = tqx_value;
910 format = web_client_api_request_v1_data_google_format(google_out);
912 else if(!strcmp(tqx_name, "responseHandler"))
913 responseHandler = tqx_value;
914 else if(!strcmp(tqx_name, "outFileName"))
915 outFileName = tqx_value;
920 if(!chart || !*chart) {
921 buffer_sprintf(w->response.data, "No chart id is given at the request.");
925 RRDSET *st = rrdset_find(chart);
926 if(!st) st = rrdset_find_byname(chart);
928 buffer_sprintf(w->response.data, "Chart '%s' is not found.", chart);
933 long long before = (before_str && *before_str)?atol(before_str):0;
934 long long after = (after_str && *after_str) ?atol(after_str):0;
935 int points = (points_str && *points_str)?atoi(points_str):0;
937 debug(D_WEB_CLIENT, "%llu: API command 'data' for chart '%s', dimensions '%s', after '%lld', before '%lld', points '%d', group '%d', format '%u', options '0x%08x'"
940 , (dimensions)?buffer_tostring(dimensions):""
949 if(outFileName && *outFileName) {
950 buffer_sprintf(w->response.header, "Content-Disposition: attachment; filename=\"%s\"\r\n", outFileName);
951 debug(D_WEB_CLIENT, "%llu: generating outfilename header: '%s'", w->id, outFileName);
954 if(format == DATASOURCE_DATATABLE_JSONP) {
955 if(responseHandler == NULL)
956 responseHandler = "google.visualization.Query.setResponse";
958 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSON/JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
959 w->id, google_version, google_reqId, google_sig, google_out, responseHandler, outFileName
962 buffer_sprintf(w->response.data,
963 "%s({version:'%s',reqId:'%s',status:'ok',sig:'%ld',table:",
964 responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
966 else if(format == DATASOURCE_JSONP) {
967 if(responseHandler == NULL)
968 responseHandler = "callback";
970 buffer_strcat(w->response.data, responseHandler);
971 buffer_strcat(w->response.data, "(");
974 ret = rrd2format(st, w->response.data, dimensions, format, points, after, before, group, options, &last_timestamp_in_data);
976 if(format == DATASOURCE_DATATABLE_JSONP) {
977 if(google_timestamp < last_timestamp_in_data)
978 buffer_strcat(w->response.data, "});");
981 // the client already has the latest data
982 buffer_flush(w->response.data);
983 buffer_sprintf(w->response.data,
984 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
985 responseHandler, google_version, google_reqId);
988 else if(format == DATASOURCE_JSONP)
989 buffer_strcat(w->response.data, ");");
992 if(dimensions) buffer_free(dimensions);
996 int web_client_api_request_v1_registry(struct web_client *w, char *url)
998 static uint32_t hash_action = 0, hash_access = 0, hash_hello = 0, hash_delete = 0, hash_search = 0,
999 hash_switch = 0, hash_machine = 0, hash_url = 0, hash_name = 0, hash_delete_url = 0, hash_for = 0,
1000 hash_to = 0 /*, hash_redirects = 0 */;
1002 if(unlikely(!hash_action)) {
1003 hash_action = simple_hash("action");
1004 hash_access = simple_hash("access");
1005 hash_hello = simple_hash("hello");
1006 hash_delete = simple_hash("delete");
1007 hash_search = simple_hash("search");
1008 hash_switch = simple_hash("switch");
1009 hash_machine = simple_hash("machine");
1010 hash_url = simple_hash("url");
1011 hash_name = simple_hash("name");
1012 hash_delete_url = simple_hash("delete_url");
1013 hash_for = simple_hash("for");
1014 hash_to = simple_hash("to");
1016 hash_redirects = simple_hash("redirects");
1020 char person_guid[36 + 1] = "";
1022 debug(D_WEB_CLIENT, "%llu: API v1 registry with URL '%s'", w->id, url);
1025 // The browser may send multiple cookies with our id
1027 char *cookie = strstr(w->response.data->buffer, NETDATA_REGISTRY_COOKIE_NAME "=");
1029 strncpyz(person_guid, &cookie[sizeof(NETDATA_REGISTRY_COOKIE_NAME)], 36);
1032 char *machine_guid = NULL,
1033 *machine_url = NULL,
1035 *search_machine_guid = NULL,
1037 *to_person_guid = NULL;
1043 char *value = mystrsep(&url, "?&[]");
1044 if (!value || !*value) continue;
1046 char *name = mystrsep(&value, "=");
1047 if (!name || !*name) continue;
1048 if (!value || !*value) continue;
1050 debug(D_WEB_CLIENT, "%llu: API v1 registry query param '%s' with value '%s'", w->id, name, value);
1052 uint32_t hash = simple_hash(name);
1054 if(hash == hash_action && !strcmp(name, "action")) {
1055 uint32_t vhash = simple_hash(value);
1057 if(vhash == hash_access && !strcmp(value, "access")) action = 'A';
1058 else if(vhash == hash_hello && !strcmp(value, "hello")) action = 'H';
1059 else if(vhash == hash_delete && !strcmp(value, "delete")) action = 'D';
1060 else if(vhash == hash_search && !strcmp(value, "search")) action = 'S';
1061 else if(vhash == hash_switch && !strcmp(value, "switch")) action = 'W';
1062 #ifdef NETDATA_INTERNAL_CHECKS
1063 else error("unknown registry action '%s'", value);
1064 #endif /* NETDATA_INTERNAL_CHECKS */
1067 else if(hash == hash_redirects && !strcmp(name, "redirects"))
1068 redirects = atoi(value);
1070 else if(hash == hash_machine && !strcmp(name, "machine"))
1071 machine_guid = value;
1073 else if(hash == hash_url && !strcmp(name, "url"))
1074 machine_url = value;
1076 else if(action == 'A') {
1077 if(hash == hash_name && !strcmp(name, "name"))
1080 else if(action == 'D') {
1081 if(hash == hash_delete_url && !strcmp(name, "delete_url"))
1084 else if(action == 'S') {
1085 if(hash == hash_for && !strcmp(name, "for"))
1086 search_machine_guid = value;
1088 else if(action == 'W') {
1089 if(hash == hash_to && !strcmp(name, "to"))
1090 to_person_guid = value;
1092 #ifdef NETDATA_INTERNAL_CHECKS
1093 else error("unused registry URL parameter '%s' with value '%s'", name, value);
1094 #endif /* NETDATA_INTERNAL_CHECKS */
1097 if(web_donotrack_comply && w->donottrack) {
1098 buffer_flush(w->response.data);
1099 buffer_sprintf(w->response.data, "Your web browser is sending 'DNT: 1' (Do Not Track). The registry requires persistent cookies on your browser to work.");
1103 if(action == 'A' && (!machine_guid || !machine_url || !url_name)) {
1104 buffer_flush(w->response.data);
1105 buffer_sprintf(w->response.data, "Invalid registry request - access requires these parameters: machine ('%s'), url ('%s'), name ('%s')",
1106 machine_guid?machine_guid:"UNSET", machine_url?machine_url:"UNSET", url_name?url_name:"UNSET");
1109 else if(action == 'D' && (!machine_guid || !machine_url || !delete_url)) {
1110 buffer_flush(w->response.data);
1111 buffer_sprintf(w->response.data, "Invalid registry request - delete requires these parameters: machine ('%s'), url ('%s'), delete_url ('%s')",
1112 machine_guid?machine_guid:"UNSET", machine_url?machine_url:"UNSET", delete_url?delete_url:"UNSET");
1115 else if(action == 'S' && (!machine_guid || !machine_url || !search_machine_guid)) {
1116 buffer_flush(w->response.data);
1117 buffer_sprintf(w->response.data, "Invalid registry request - search requires these parameters: machine ('%s'), url ('%s'), for ('%s')",
1118 machine_guid?machine_guid:"UNSET", machine_url?machine_url:"UNSET", search_machine_guid?search_machine_guid:"UNSET");
1121 else if(action == 'W' && (!machine_guid || !machine_url || !to_person_guid)) {
1122 buffer_flush(w->response.data);
1123 buffer_sprintf(w->response.data, "Invalid registry request - switching identity requires these parameters: machine ('%s'), url ('%s'), to ('%s')",
1124 machine_guid?machine_guid:"UNSET", machine_url?machine_url:"UNSET", to_person_guid?to_person_guid:"UNSET");
1130 w->tracking_required = 1;
1131 if(registry_verify_cookies_redirects() > 0 && (!cookie || !person_guid[0])) {
1132 buffer_flush(w->response.data);
1134 registry_set_cookie(w, "give-me-back-this-cookie-please");
1135 w->response.data->contenttype = CT_APPLICATION_JSON;
1136 buffer_sprintf(w->response.data, "{ \"status\": \"redirect\", \"registry\": \"%s\" }", registry_to_announce());
1140 * it seems that web browsers are ignoring 307 (Moved Temporarily)
1141 * under certain conditions, when using CORS
1142 * so this is commented and we use application level redirects instead
1146 if(redirects > registry_verify_cookies_redirects()) {
1147 buffer_flush(w->response.data);
1148 buffer_sprintf(w->response.data, "Your browser does not support cookies");
1152 char *encoded_url = url_encode(machine_url);
1154 error("%llu: Cannot URL encode string '%s'", w->id, machine_url);
1158 char *encoded_name = url_encode(url_name);
1161 error("%llu: Cannot URL encode string '%s'", w->id, url_name);
1165 char *encoded_guid = url_encode(machine_guid);
1169 error("%llu: Cannot URL encode string '%s'", w->id, machine_guid);
1173 buffer_sprintf(w->response.header, "Location: %s/api/v1/registry?action=access&machine=%s&name=%s&url=%s&redirects=%d\r\n",
1174 registry_to_announce(), encoded_guid, encoded_name, encoded_url, redirects);
1182 return registry_request_access_json(w, person_guid, machine_guid, machine_url, url_name, time(NULL));
1185 w->tracking_required = 1;
1186 return registry_request_delete_json(w, person_guid, machine_guid, machine_url, delete_url, time(NULL));
1189 w->tracking_required = 1;
1190 return registry_request_search_json(w, person_guid, machine_guid, machine_url, search_machine_guid, time(NULL));
1193 w->tracking_required = 1;
1194 return registry_request_switch_json(w, person_guid, machine_guid, machine_url, to_person_guid, time(NULL));
1197 return registry_request_hello_json(w);
1200 buffer_flush(w->response.data);
1201 buffer_sprintf(w->response.data, "Invalid registry request - you need to set an action: hello, access, delete, search");
1205 buffer_flush(w->response.data);
1206 buffer_sprintf(w->response.data, "Invalid or no registry action.");
1210 int web_client_api_request_v1(struct web_client *w, char *url) {
1211 static uint32_t hash_data = 0, hash_chart = 0, hash_charts = 0, hash_registry = 0, hash_badge = 0;
1213 if(unlikely(hash_data == 0)) {
1214 hash_data = simple_hash("data");
1215 hash_chart = simple_hash("chart");
1216 hash_charts = simple_hash("charts");
1217 hash_registry = simple_hash("registry");
1218 hash_badge = simple_hash("badge.svg");
1222 char *tok = mystrsep(&url, "/?&");
1224 debug(D_WEB_CLIENT, "%llu: Searching for API v1 command '%s'.", w->id, tok);
1225 uint32_t hash = simple_hash(tok);
1227 if(hash == hash_data && !strcmp(tok, "data"))
1228 return web_client_api_request_v1_data(w, url);
1230 else if(hash == hash_chart && !strcmp(tok, "chart"))
1231 return web_client_api_request_v1_chart(w, url);
1233 else if(hash == hash_charts && !strcmp(tok, "charts"))
1234 return web_client_api_request_v1_charts(w, url);
1236 else if(hash == hash_registry && !strcmp(tok, "registry"))
1237 return web_client_api_request_v1_registry(w, url);
1239 else if(hash == hash_badge && !strcmp(tok, "badge.svg"))
1240 return web_client_api_v1_badge(w, url);
1243 buffer_flush(w->response.data);
1244 buffer_sprintf(w->response.data, "Unsupported v1 API command: %s", tok);
1249 buffer_flush(w->response.data);
1250 buffer_sprintf(w->response.data, "API v1 command?");
1255 int web_client_api_request(struct web_client *w, char *url)
1257 // get the api version
1258 char *tok = mystrsep(&url, "/?&");
1260 debug(D_WEB_CLIENT, "%llu: Searching for API version '%s'.", w->id, tok);
1261 if(strcmp(tok, "v1") == 0)
1262 return web_client_api_request_v1(w, url);
1264 buffer_flush(w->response.data);
1265 buffer_sprintf(w->response.data, "Unsupported API version: %s", tok);
1270 buffer_flush(w->response.data);
1271 buffer_sprintf(w->response.data, "Which API version?");
1276 int web_client_api_old_data_request(struct web_client *w, char *url, int datasource_type)
1280 char *args = strchr(url, '?');
1286 // get the name of the data to show
1287 char *tok = mystrsep(&url, "/");
1290 // do we have such a data set?
1292 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1293 st = rrdset_find_byname(tok);
1294 if(!st) st = rrdset_find(tok);
1299 // try to send a file with that name
1300 buffer_flush(w->response.data);
1301 return(mysendfile(w, tok));
1305 debug(D_WEB_CLIENT, "%llu: Found RRD data with name '%s'.", w->id, tok);
1307 // how many entries does the client want?
1308 int lines = rrd_default_history_entries;
1309 int group_count = 1;
1310 time_t after = 0, before = 0;
1311 int group_method = GROUP_AVERAGE;
1315 // parse the lines required
1316 tok = mystrsep(&url, "/");
1317 if(tok) lines = atoi(tok);
1318 if(lines < 1) lines = 1;
1321 // parse the group count required
1322 tok = mystrsep(&url, "/");
1323 if(tok && *tok) group_count = atoi(tok);
1324 if(group_count < 1) group_count = 1;
1325 //if(group_count > save_history / 20) group_count = save_history / 20;
1328 // parse the grouping method required
1329 tok = mystrsep(&url, "/");
1331 if(strcmp(tok, "max") == 0) group_method = GROUP_MAX;
1332 else if(strcmp(tok, "average") == 0) group_method = GROUP_AVERAGE;
1333 else if(strcmp(tok, "sum") == 0) group_method = GROUP_SUM;
1334 else debug(D_WEB_CLIENT, "%llu: Unknown group method '%s'", w->id, tok);
1339 tok = mystrsep(&url, "/");
1340 if(tok && *tok) after = strtoul(tok, NULL, 10);
1341 if(after < 0) after = 0;
1344 // parse before time
1345 tok = mystrsep(&url, "/");
1346 if(tok && *tok) before = strtoul(tok, NULL, 10);
1347 if(before < 0) before = 0;
1351 tok = mystrsep(&url, "/");
1352 if(tok && *tok && strcmp(tok, "nonzero") == 0) nonzero = 1;
1355 w->response.data->contenttype = CT_APPLICATION_JSON;
1356 buffer_flush(w->response.data);
1358 char *google_version = "0.6";
1359 char *google_reqId = "0";
1360 char *google_sig = "0";
1361 char *google_out = "json";
1362 char *google_responseHandler = "google.visualization.Query.setResponse";
1363 char *google_outFileName = NULL;
1364 time_t last_timestamp_in_data = 0;
1365 if(datasource_type == DATASOURCE_DATATABLE_JSON || datasource_type == DATASOURCE_DATATABLE_JSONP) {
1367 w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
1370 tok = mystrsep(&args, "&");
1372 char *name = mystrsep(&tok, "=");
1373 if(name && *name && strcmp(name, "tqx") == 0) {
1374 char *key = mystrsep(&tok, ":");
1375 char *value = mystrsep(&tok, ";");
1376 if(key && value && *key && *value) {
1377 if(strcmp(key, "version") == 0)
1378 google_version = value;
1380 else if(strcmp(key, "reqId") == 0)
1381 google_reqId = value;
1383 else if(strcmp(key, "sig") == 0)
1386 else if(strcmp(key, "out") == 0)
1389 else if(strcmp(key, "responseHandler") == 0)
1390 google_responseHandler = value;
1392 else if(strcmp(key, "outFileName") == 0)
1393 google_outFileName = value;
1399 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
1400 w->id, google_version, google_reqId, google_sig, google_out, google_responseHandler, google_outFileName
1403 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
1404 last_timestamp_in_data = strtoul(google_sig, NULL, 0);
1406 // check the client wants json
1407 if(strcmp(google_out, "json") != 0) {
1408 buffer_sprintf(w->response.data,
1409 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'invalid_query',message:'output format is not supported',detailed_message:'the format %s requested is not supported by netdata.'}]});",
1410 google_responseHandler, google_version, google_reqId, google_out);
1416 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
1417 buffer_sprintf(w->response.data,
1418 "%s({version:'%s',reqId:'%s',status:'ok',sig:'%ld',table:",
1419 google_responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
1422 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending RRD data '%s' (id %s, %d lines, %d group, %d group_method, %ld after, %ld before).",
1423 w->id, st->name, st->id, lines, group_count, group_method, after, before);
1425 time_t timestamp_in_data = rrd_stats_json(datasource_type, st, w->response.data, lines, group_count, group_method, (unsigned long)after, (unsigned long)before, nonzero);
1427 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
1428 if(timestamp_in_data > last_timestamp_in_data)
1429 buffer_strcat(w->response.data, "});");
1432 // the client already has the latest data
1433 buffer_flush(w->response.data);
1434 buffer_sprintf(w->response.data,
1435 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
1436 google_responseHandler, google_version, google_reqId);
1443 const char *web_content_type_to_string(uint8_t contenttype) {
1444 switch(contenttype) {
1446 return "text/html; charset=utf-8";
1448 case CT_APPLICATION_XML:
1449 return "application/xml; charset=utf-8";
1451 case CT_APPLICATION_JSON:
1452 return "application/json; charset=utf-8";
1454 case CT_APPLICATION_X_JAVASCRIPT:
1455 return "application/x-javascript; charset=utf-8";
1458 return "text/css; charset=utf-8";
1461 return "text/xml; charset=utf-8";
1464 return "text/xsl; charset=utf-8";
1466 case CT_APPLICATION_OCTET_STREAM:
1467 return "application/octet-stream";
1469 case CT_IMAGE_SVG_XML:
1470 return "image/svg+xml";
1472 case CT_APPLICATION_X_FONT_TRUETYPE:
1473 return "application/x-font-truetype";
1475 case CT_APPLICATION_X_FONT_OPENTYPE:
1476 return "application/x-font-opentype";
1478 case CT_APPLICATION_FONT_WOFF:
1479 return "application/font-woff";
1481 case CT_APPLICATION_FONT_WOFF2:
1482 return "application/font-woff2";
1484 case CT_APPLICATION_VND_MS_FONTOBJ:
1485 return "application/vnd.ms-fontobject";
1491 return "image/jpeg";
1496 case CT_IMAGE_XICON:
1497 return "image/x-icon";
1503 return "image/icns";
1507 return "text/plain; charset=utf-8";
1512 const char *web_response_code_to_string(int code) {
1518 return "Temporary Redirect";
1521 return "Bad Request";
1530 return "Preconditions Failed";
1533 if(code >= 100 && code < 200)
1534 return "Informational";
1536 if(code >= 200 && code < 300)
1537 return "Successful";
1539 if(code >= 300 && code < 400)
1540 return "Redirection";
1542 if(code >= 400 && code < 500)
1543 return "Bad Request";
1545 if(code >= 500 && code < 600)
1546 return "Server Error";
1548 return "Undefined Error";
1552 static inline char *http_header_parse(struct web_client *w, char *s) {
1553 static uint32_t hash_origin = 0, hash_connection = 0, hash_accept_encoding = 0, hash_donottrack = 0;
1555 if(unlikely(!hash_origin)) {
1556 hash_origin = simple_uhash("Origin");
1557 hash_connection = simple_uhash("Connection");
1558 hash_accept_encoding = simple_uhash("Accept-Encoding");
1559 hash_donottrack = simple_uhash("DNT");
1565 while(*e && *e != ':') e++;
1572 char *v = e + 1, *ve;
1574 // skip leading spaces from value
1575 while(*v == ' ') v++;
1579 while(*ve && *ve != '\r') ve++;
1580 if(!*ve || ve[1] != '\n') {
1585 // terminate the value
1588 // fprintf(stderr, "HEADER: '%s' = '%s'\n", s, v);
1589 uint32_t hash = simple_uhash(s);
1591 if(hash == hash_origin && !strcasecmp(s, "Origin"))
1592 strncpyz(w->origin, v, ORIGIN_MAX);
1594 else if(hash == hash_connection && !strcasecmp(s, "Connection")) {
1595 if(strcasestr(v, "keep-alive"))
1598 else if(web_donotrack_comply && hash == hash_donottrack && !strcasecmp(s, "DNT")) {
1599 if(*v == '0') w->donottrack = 0;
1600 else if(*v == '1') w->donottrack = 1;
1602 #ifdef NETDATA_WITH_ZLIB
1603 else if(hash == hash_accept_encoding && !strcasecmp(s, "Accept-Encoding")) {
1604 if(web_enable_gzip) {
1605 if(strcasestr(v, "gzip"))
1606 web_client_enable_deflate(w, 1);
1608 // does not seem to work
1609 // else if(strcasestr(v, "deflate"))
1610 // web_client_enable_deflate(w, 0);
1613 #endif /* NETDATA_WITH_ZLIB */
1620 // http_request_validate()
1622 // = 0 : all good, process the request
1623 // > 0 : request is not supported
1624 // < 0 : request is incomplete - wait for more data
1626 static inline int http_request_validate(struct web_client *w) {
1627 char *s = w->response.data->buffer, *encoded_url = NULL;
1629 // is is a valid request?
1630 if(!strncmp(s, "GET ", 4)) {
1631 encoded_url = s = &s[4];
1632 w->mode = WEB_CLIENT_MODE_NORMAL;
1634 else if(!strncmp(s, "OPTIONS ", 8)) {
1635 encoded_url = s = &s[8];
1636 w->mode = WEB_CLIENT_MODE_OPTIONS;
1639 w->wait_receive = 0;
1643 // find the SPACE + "HTTP/"
1645 // find the next space
1646 while (*s && *s != ' ') s++;
1648 // is it SPACE + "HTTP/" ?
1649 if(*s && !strncmp(s, " HTTP/", 6)) break;
1653 // incomplete requests
1655 w->wait_receive = 1;
1659 // we have the end of encoded_url - remember it
1662 // make sure we have complete request
1663 // complete requests contain: \r\n\r\n
1666 while(*s && *s++ != '\r');
1668 // did we reach the end?
1669 if(unlikely(!*s)) break;
1672 if(likely(*s++ == '\n')) {
1674 // is it again \r\n ? (header end)
1675 if(unlikely(*s == '\r' && s[1] == '\n')) {
1676 // a valid complete HTTP request found
1679 url_decode_r(w->decoded_url, encoded_url, URL_MAX + 1);
1682 // copy the URL - we are going to overwrite parts of it
1683 // FIXME -- we should avoid it
1684 strncpyz(w->last_url, w->decoded_url, URL_MAX);
1686 w->wait_receive = 0;
1690 // another header line
1691 s = http_header_parse(w, s);
1695 // incomplete request
1696 w->wait_receive = 1;
1700 void web_client_process(struct web_client *w) {
1701 static uint32_t hash_api = 0, hash_netdata_conf = 0, hash_data = 0, hash_datasource = 0, hash_graph = 0,
1702 hash_list = 0, hash_all_json = 0, hash_exit = 0, hash_debug = 0, hash_mirror = 0;
1704 if(unlikely(!hash_api)) {
1705 hash_api = simple_hash("api");
1706 hash_netdata_conf = simple_hash("netdata.conf");
1707 hash_data = simple_hash(WEB_PATH_DATA);
1708 hash_datasource = simple_hash(WEB_PATH_DATASOURCE);
1709 hash_graph = simple_hash(WEB_PATH_GRAPH);
1710 hash_list = simple_hash("list");
1711 hash_all_json = simple_hash("all.json");
1712 hash_exit = simple_hash("exit");
1713 hash_debug = simple_hash("debug");
1714 hash_mirror = simple_hash("mirror");
1720 int what_to_do = http_request_validate(w);
1722 // wait for more data
1723 if(what_to_do < 0) {
1724 if(w->response.data->len > TOO_BIG_REQUEST) {
1725 strcpy(w->last_url, "too big request");
1727 debug(D_WEB_CLIENT_ACCESS, "%llu: Received request is too big (%zu bytes).", w->id, w->response.data->len);
1730 buffer_flush(w->response.data);
1731 buffer_sprintf(w->response.data, "Received request is too big (%zu bytes).\r\n", w->response.data->len);
1734 // wait for more data
1738 else if(what_to_do > 0) {
1739 strcpy(w->last_url, "not a valid request");
1741 debug(D_WEB_CLIENT_ACCESS, "%llu: Cannot understand '%s'.", w->id, w->response.data->buffer);
1744 buffer_flush(w->response.data);
1745 buffer_strcat(w->response.data, "I don't understand you...\r\n");
1747 else { // what_to_do == 0
1748 gettimeofday(&w->tv_in, NULL);
1750 if(w->mode == WEB_CLIENT_MODE_OPTIONS) {
1752 w->response.data->contenttype = CT_TEXT_PLAIN;
1753 buffer_flush(w->response.data);
1754 buffer_strcat(w->response.data, "OK");
1757 char *url = w->decoded_url;
1758 char *tok = mystrsep(&url, "/?");
1760 uint32_t hash = simple_hash(tok);
1761 debug(D_WEB_CLIENT, "%llu: Processing command '%s'.", w->id, tok);
1763 if(hash == hash_api && strcmp(tok, "api") == 0) {
1764 // the client is requesting api access
1765 code = web_client_api_request(w, url);
1767 else if(hash == hash_netdata_conf && strcmp(tok, "netdata.conf") == 0) {
1769 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending netdata.conf ...", w->id);
1771 w->response.data->contenttype = CT_TEXT_PLAIN;
1772 buffer_flush(w->response.data);
1773 generate_config(w->response.data, 0);
1775 else if(hash == hash_data && strcmp(tok, WEB_PATH_DATA) == 0) { // "data"
1776 // the client is requesting rrd data -- OLD API
1777 code = web_client_api_old_data_request(w, url, DATASOURCE_JSON);
1779 else if(hash == hash_datasource && strcmp(tok, WEB_PATH_DATASOURCE) == 0) { // "datasource"
1780 // the client is requesting google datasource -- OLD API
1781 code = web_client_api_old_data_request(w, url, DATASOURCE_DATATABLE_JSONP);
1783 else if(hash == hash_graph && strcmp(tok, WEB_PATH_GRAPH) == 0) { // "graph"
1784 // the client is requesting an rrd graph -- OLD API
1786 // get the name of the data to show
1787 tok = mystrsep(&url, "/?&");
1789 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1791 // do we have such a data set?
1792 RRDSET *st = rrdset_find_byname(tok);
1793 if(!st) st = rrdset_find(tok);
1796 // try to send a file with that name
1797 buffer_flush(w->response.data);
1798 code = mysendfile(w, tok);
1802 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending %s.json of RRD_STATS...", w->id, st->name);
1803 w->response.data->contenttype = CT_APPLICATION_JSON;
1804 buffer_flush(w->response.data);
1805 rrd_stats_graph_json(st, url, w->response.data);
1810 buffer_flush(w->response.data);
1811 buffer_strcat(w->response.data, "Graph name?\r\n");
1814 else if(hash == hash_list && strcmp(tok, "list") == 0) {
1818 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending list of RRD_STATS...", w->id);
1820 buffer_flush(w->response.data);
1821 RRDSET *st = localhost.rrdset_root;
1823 for ( ; st ; st = st->next )
1824 buffer_sprintf(w->response.data, "%s\n", st->name);
1826 else if(hash == hash_all_json && strcmp(tok, "all.json") == 0) {
1829 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending JSON list of all monitors of RRD_STATS...", w->id);
1831 w->response.data->contenttype = CT_APPLICATION_JSON;
1832 buffer_flush(w->response.data);
1833 rrd_stats_all_json(w->response.data);
1835 #ifdef NETDATA_INTERNAL_CHECKS
1836 else if(hash == hash_exit && strcmp(tok, "exit") == 0) {
1838 w->response.data->contenttype = CT_TEXT_PLAIN;
1839 buffer_flush(w->response.data);
1842 buffer_strcat(w->response.data, "ok, will do...");
1844 buffer_strcat(w->response.data, "I am doing it already");
1846 error("web request to exit received.");
1847 netdata_cleanup_and_exit(0);
1850 else if(hash == hash_debug && strcmp(tok, "debug") == 0) {
1851 buffer_flush(w->response.data);
1853 // get the name of the data to show
1854 tok = mystrsep(&url, "/?&");
1856 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1858 // do we have such a data set?
1859 RRDSET *st = rrdset_find_byname(tok);
1860 if(!st) st = rrdset_find(tok);
1863 buffer_sprintf(w->response.data, "Chart %s is not found.\r\n", tok);
1864 debug(D_WEB_CLIENT_ACCESS, "%llu: %s is not found.", w->id, tok);
1868 debug_flags |= D_RRD_STATS;
1869 st->debug = !st->debug;
1870 buffer_sprintf(w->response.data, "Chart %s has now debug %s.\r\n", tok, st->debug?"enabled":"disabled");
1871 debug(D_WEB_CLIENT_ACCESS, "%llu: debug for %s is %s.", w->id, tok, st->debug?"enabled":"disabled");
1876 buffer_flush(w->response.data);
1877 buffer_strcat(w->response.data, "debug which chart?\r\n");
1880 else if(hash == hash_mirror && strcmp(tok, "mirror") == 0) {
1883 debug(D_WEB_CLIENT_ACCESS, "%llu: Mirroring...", w->id);
1885 // replace the zero bytes with spaces
1886 buffer_char_replace(w->response.data, '\0', ' ');
1888 // just leave the buffer as is
1889 // it will be copied back to the client
1891 #endif /* NETDATA_INTERNAL_CHECKS */
1893 char filename[FILENAME_MAX+1];
1895 strncpyz(filename, w->last_url, FILENAME_MAX);
1896 tok = mystrsep(&url, "?");
1897 buffer_flush(w->response.data);
1898 code = mysendfile(w, (tok && *tok)?tok:"/");
1902 char filename[FILENAME_MAX+1];
1904 strncpyz(filename, w->last_url, FILENAME_MAX);
1905 tok = mystrsep(&url, "?");
1906 buffer_flush(w->response.data);
1907 code = mysendfile(w, (tok && *tok)?tok:"/");
1912 gettimeofday(&w->tv_ready, NULL);
1913 w->response.data->date = time(NULL);
1914 w->response.sent = 0;
1915 w->response.code = code;
1917 // prepare the HTTP response header
1918 debug(D_WEB_CLIENT, "%llu: Generating HTTP header with response %d.", w->id, code);
1920 const char *content_type_string = web_content_type_to_string(w->response.data->contenttype);
1921 const char *code_msg = web_response_code_to_string(code);
1924 struct tm tmbuf, *tm = gmtime_r(&w->response.data->date, &tmbuf);
1925 strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %Z", tm);
1927 buffer_sprintf(w->response.header_output,
1928 "HTTP/1.1 %d %s\r\n"
1929 "Connection: %s\r\n"
1930 "Server: NetData Embedded HTTP Server\r\n"
1931 "Access-Control-Allow-Origin: %s\r\n"
1932 "Access-Control-Allow-Credentials: true\r\n"
1933 "Content-Type: %s\r\n"
1936 , w->keepalive?"keep-alive":"close"
1938 , content_type_string
1942 if(w->cookie1[0] || w->cookie2[0]) {
1944 buffer_sprintf(w->response.header_output,
1945 "Set-Cookie: %s\r\n",
1950 buffer_sprintf(w->response.header_output,
1951 "Set-Cookie: %s\r\n",
1955 if(web_donotrack_comply)
1956 buffer_sprintf(w->response.header_output,
1957 "Tk: T;cookies\r\n");
1960 if(web_donotrack_comply) {
1961 if(w->tracking_required)
1962 buffer_sprintf(w->response.header_output,
1963 "Tk: T;cookies\r\n");
1965 buffer_sprintf(w->response.header_output,
1970 if(w->mode == WEB_CLIENT_MODE_OPTIONS) {
1971 buffer_strcat(w->response.header_output,
1972 "Access-Control-Allow-Methods: GET, OPTIONS\r\n"
1973 "Access-Control-Allow-Headers: accept, x-requested-with, origin, content-type, cookie\r\n"
1974 "Access-Control-Max-Age: 1209600\r\n" // 86400 * 14
1978 if(buffer_strlen(w->response.header))
1979 buffer_strcat(w->response.header_output, buffer_tostring(w->response.header));
1981 if(w->mode == WEB_CLIENT_MODE_NORMAL && (w->response.data->options & WB_CONTENT_NO_CACHEABLE)) {
1982 buffer_sprintf(w->response.header_output,
1984 "Cache-Control: no-cache\r\n"
1987 else if(w->mode != WEB_CLIENT_MODE_OPTIONS) {
1989 time_t et = w->response.data->date + (86400 * 14);
1990 struct tm etmbuf, *etm = gmtime_r(&et, &etmbuf);
1991 strftime(edate, sizeof(edate), "%a, %d %b %Y %H:%M:%S %Z", etm);
1993 buffer_sprintf(w->response.header_output,
1995 "Cache-Control: public\r\n"
1999 // if we know the content length, put it
2000 if(!w->response.zoutput && (w->response.data->len || w->response.rlen))
2001 buffer_sprintf(w->response.header_output,
2002 "Content-Length: %zu\r\n"
2003 , w->response.data->len? w->response.data->len: w->response.rlen
2005 else if(!w->response.zoutput)
2006 w->keepalive = 0; // content-length is required for keep-alive
2008 if(w->response.zoutput) {
2009 buffer_strcat(w->response.header_output,
2010 "Content-Encoding: gzip\r\n"
2011 "Transfer-Encoding: chunked\r\n"
2015 buffer_strcat(w->response.header_output, "\r\n");
2017 // sent the HTTP header
2018 debug(D_WEB_DATA, "%llu: Sending response HTTP header of size %zu: '%s'"
2020 , buffer_strlen(w->response.header_output)
2021 , buffer_tostring(w->response.header_output)
2024 web_client_crock_socket(w);
2026 bytes = send(w->ofd, buffer_tostring(w->response.header_output), buffer_strlen(w->response.header_output), 0);
2027 if(bytes != (ssize_t) buffer_strlen(w->response.header_output)) {
2029 w->stats_sent_bytes += bytes;
2031 debug(D_WEB_CLIENT, "%llu: HTTP Header failed to be sent (I sent %zu bytes but the system sent %zd bytes). Closing web client."
2033 , buffer_strlen(w->response.header_output)
2036 WEB_CLIENT_IS_DEAD(w);
2040 w->stats_sent_bytes += bytes;
2042 // enable sending immediately if we have data
2043 if(w->response.data->len) w->wait_send = 1;
2044 else w->wait_send = 0;
2048 case WEB_CLIENT_MODE_OPTIONS:
2049 debug(D_WEB_CLIENT, "%llu: Done preparing the OPTIONS response. Sending data (%zu bytes) to client.", w->id, w->response.data->len);
2052 case WEB_CLIENT_MODE_NORMAL:
2053 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Sending data (%zu bytes) to client.", w->id, w->response.data->len);
2056 case WEB_CLIENT_MODE_FILECOPY:
2057 if(w->response.rlen) {
2058 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending data file of %zu bytes to client.", w->id, w->response.rlen);
2059 w->wait_receive = 1;
2062 // utilize the kernel sendfile() for copying the file to the socket.
2063 // this block of code can be commented, without anything missing.
2064 // when it is commented, the program will copy the data using async I/O.
2066 long len = sendfile(w->ofd, w->ifd, NULL, w->response.data->rbytes);
2067 if(len != w->response.data->rbytes)
2068 error("%llu: sendfile() should copy %ld bytes, but copied %ld. Falling back to manual copy.", w->id, w->response.data->rbytes, len);
2070 web_client_reset(w);
2075 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending an unknown amount of bytes to client.", w->id);
2079 fatal("%llu: Unknown client mode %d.", w->id, w->mode);
2084 ssize_t web_client_send_chunk_header(struct web_client *w, size_t len)
2086 debug(D_DEFLATE, "%llu: OPEN CHUNK of %zu bytes (hex: %zx).", w->id, len, len);
2088 sprintf(buf, "%zX\r\n", len);
2090 ssize_t bytes = send(w->ofd, buf, strlen(buf), 0);
2092 debug(D_DEFLATE, "%llu: Sent chunk header %zd bytes.", w->id, bytes);
2093 w->stats_sent_bytes += bytes;
2096 else if(bytes == 0) {
2097 debug(D_WEB_CLIENT, "%llu: Did not send chunk header to the client.", w->id);
2098 WEB_CLIENT_IS_DEAD(w);
2101 debug(D_WEB_CLIENT, "%llu: Failed to send chunk header to client.", w->id);
2102 WEB_CLIENT_IS_DEAD(w);
2108 ssize_t web_client_send_chunk_close(struct web_client *w)
2110 //debug(D_DEFLATE, "%llu: CLOSE CHUNK.", w->id);
2112 ssize_t bytes = send(w->ofd, "\r\n", 2, 0);
2114 debug(D_DEFLATE, "%llu: Sent chunk suffix %zd bytes.", w->id, bytes);
2115 w->stats_sent_bytes += bytes;
2118 else if(bytes == 0) {
2119 debug(D_WEB_CLIENT, "%llu: Did not send chunk suffix to the client.", w->id);
2120 WEB_CLIENT_IS_DEAD(w);
2123 debug(D_WEB_CLIENT, "%llu: Failed to send chunk suffix to client.", w->id);
2124 WEB_CLIENT_IS_DEAD(w);
2130 ssize_t web_client_send_chunk_finalize(struct web_client *w)
2132 //debug(D_DEFLATE, "%llu: FINALIZE CHUNK.", w->id);
2134 ssize_t bytes = send(w->ofd, "\r\n0\r\n\r\n", 7, 0);
2136 debug(D_DEFLATE, "%llu: Sent chunk suffix %zd bytes.", w->id, bytes);
2137 w->stats_sent_bytes += bytes;
2140 else if(bytes == 0) {
2141 debug(D_WEB_CLIENT, "%llu: Did not send chunk finalize suffix to the client.", w->id);
2142 WEB_CLIENT_IS_DEAD(w);
2145 debug(D_WEB_CLIENT, "%llu: Failed to send chunk finalize suffix to client.", w->id);
2146 WEB_CLIENT_IS_DEAD(w);
2152 #ifdef NETDATA_WITH_ZLIB
2153 ssize_t web_client_send_deflate(struct web_client *w)
2155 ssize_t len = 0, t = 0;
2157 // when using compression,
2158 // w->response.sent is the amount of bytes passed through compression
2160 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.",
2161 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);
2163 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) {
2164 // there is nothing to send
2166 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
2168 // finalize the chunk
2169 if(w->response.sent != 0) {
2170 t = web_client_send_chunk_finalize(w);
2174 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->response.rlen && w->response.rlen > w->response.data->len) {
2175 // we have to wait, more data will come
2176 debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
2181 if(unlikely(!w->keepalive)) {
2182 debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %zu bytes sent.", w->id, w->response.sent);
2183 WEB_CLIENT_IS_DEAD(w);
2188 web_client_reset(w);
2189 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket.", w->id);
2193 if(w->response.zhave == w->response.zsent) {
2194 // compress more input data
2196 // close the previous open chunk
2197 if(w->response.sent != 0) {
2198 t = web_client_send_chunk_close(w);
2202 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);
2204 // give the compressor all the data not passed through the compressor yet
2205 if(w->response.data->len > w->response.sent) {
2206 w->response.zstream.next_in = (Bytef *)&w->response.data->buffer[w->response.sent - w->response.zstream.avail_in];
2207 w->response.zstream.avail_in += (uInt) (w->response.data->len - w->response.sent);
2210 // reset the compressor output buffer
2211 w->response.zstream.next_out = w->response.zbuffer;
2212 w->response.zstream.avail_out = ZLIB_CHUNK;
2214 // ask for FINISH if we have all the input
2215 int flush = Z_SYNC_FLUSH;
2216 if(w->mode == WEB_CLIENT_MODE_NORMAL
2217 || (w->mode == WEB_CLIENT_MODE_FILECOPY && !w->wait_receive && w->response.data->len == w->response.rlen)) {
2219 debug(D_DEFLATE, "%llu: Requesting Z_FINISH, if possible.", w->id);
2222 debug(D_DEFLATE, "%llu: Requesting Z_SYNC_FLUSH.", w->id);
2226 if(deflate(&w->response.zstream, flush) == Z_STREAM_ERROR) {
2227 error("%llu: Compression failed. Closing down client.", w->id);
2228 web_client_reset(w);
2232 w->response.zhave = ZLIB_CHUNK - w->response.zstream.avail_out;
2233 w->response.zsent = 0;
2235 // keep track of the bytes passed through the compressor
2236 w->response.sent = w->response.data->len;
2238 debug(D_DEFLATE, "%llu: Compression produced %zu bytes.", w->id, w->response.zhave);
2241 ssize_t t2 = web_client_send_chunk_header(w, w->response.zhave);
2242 if(t2 < 0) return t2;
2246 debug(D_WEB_CLIENT, "%llu: Sending %zu bytes of data (+%zd of chunk header).", w->id, w->response.zhave - w->response.zsent, t);
2248 len = send(w->ofd, &w->response.zbuffer[w->response.zsent], (size_t) (w->response.zhave - w->response.zsent), MSG_DONTWAIT);
2250 w->stats_sent_bytes += len;
2251 w->response.zsent += len;
2253 debug(D_WEB_CLIENT, "%llu: Sent %zd bytes.", w->id, len);
2256 debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client (zhave = %zu, zsent = %zu, need to send = %zu).",
2257 w->id, w->response.zhave, w->response.zsent, w->response.zhave - w->response.zsent);
2259 WEB_CLIENT_IS_DEAD(w);
2262 debug(D_WEB_CLIENT, "%llu: Failed to send data to client.", w->id);
2263 WEB_CLIENT_IS_DEAD(w);
2268 #endif // NETDATA_WITH_ZLIB
2270 ssize_t web_client_send(struct web_client *w) {
2271 #ifdef NETDATA_WITH_ZLIB
2272 if(likely(w->response.zoutput)) return web_client_send_deflate(w);
2273 #endif // NETDATA_WITH_ZLIB
2277 if(unlikely(w->response.data->len - w->response.sent == 0)) {
2278 // there is nothing to send
2280 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
2282 // there can be two cases for this
2283 // A. we have done everything
2284 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
2286 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->response.rlen && w->response.rlen > w->response.data->len) {
2287 // we have to wait, more data will come
2288 debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
2293 if(unlikely(!w->keepalive)) {
2294 debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %zu bytes sent.", w->id, w->response.sent);
2295 WEB_CLIENT_IS_DEAD(w);
2299 web_client_reset(w);
2300 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
2304 bytes = send(w->ofd, &w->response.data->buffer[w->response.sent], w->response.data->len - w->response.sent, MSG_DONTWAIT);
2305 if(likely(bytes > 0)) {
2306 w->stats_sent_bytes += bytes;
2307 w->response.sent += bytes;
2308 debug(D_WEB_CLIENT, "%llu: Sent %zd bytes.", w->id, bytes);
2310 else if(likely(bytes == 0)) {
2311 debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client.", w->id);
2312 WEB_CLIENT_IS_DEAD(w);
2315 debug(D_WEB_CLIENT, "%llu: Failed to send data to client.", w->id);
2316 WEB_CLIENT_IS_DEAD(w);
2322 ssize_t web_client_receive(struct web_client *w)
2324 // do we have any space for more data?
2325 buffer_need_bytes(w->response.data, WEB_REQUEST_LENGTH);
2327 ssize_t left = w->response.data->size - w->response.data->len;
2330 if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY))
2331 bytes = read(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1));
2333 bytes = recv(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1), MSG_DONTWAIT);
2335 if(likely(bytes > 0)) {
2336 if(w->mode != WEB_CLIENT_MODE_FILECOPY)
2337 w->stats_received_bytes += bytes;
2339 size_t old = w->response.data->len;
2340 w->response.data->len += bytes;
2341 w->response.data->buffer[w->response.data->len] = '\0';
2343 debug(D_WEB_CLIENT, "%llu: Received %zd bytes.", w->id, bytes);
2344 debug(D_WEB_DATA, "%llu: Received data: '%s'.", w->id, &w->response.data->buffer[old]);
2346 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
2349 if(w->response.rlen && w->response.data->len >= w->response.rlen)
2350 w->wait_receive = 0;
2353 else if(likely(bytes == 0)) {
2354 debug(D_WEB_CLIENT, "%llu: Out of input data.", w->id);
2356 // if we cannot read, it means we have an error on input.
2357 // if however, we are copying a file from ifd to ofd, we should not return an error.
2358 // in this case, the error should be generated when the file has been sent to the client.
2360 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
2361 // we are copying data from ifd to ofd
2362 // let it finish copying...
2363 w->wait_receive = 0;
2365 debug(D_WEB_CLIENT, "%llu: Read the whole file.", w->id);
2366 if(w->ifd != w->ofd) close(w->ifd);
2370 debug(D_WEB_CLIENT, "%llu: failed to receive data.", w->id);
2371 WEB_CLIENT_IS_DEAD(w);
2375 debug(D_WEB_CLIENT, "%llu: receive data failed.", w->id);
2376 WEB_CLIENT_IS_DEAD(w);
2383 // --------------------------------------------------------------------------------------
2384 // the thread of a single client
2386 // 1. waits for input and output, using async I/O
2387 // 2. it processes HTTP requests
2388 // 3. it generates HTTP responses
2389 // 4. it copies data from input to output if mode is FILECOPY
2391 void *web_client_main(void *ptr)
2393 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
2394 error("Cannot set pthread cancel type to DEFERRED.");
2396 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
2397 error("Cannot set pthread cancel state to ENABLE.");
2399 struct web_client *w = ptr;
2400 struct pollfd fds[2], *ifd, *ofd;
2401 int retval, fdmax = 0, timeout;
2403 log_access("%llu: %s port %s connected on thread task id %d", w->id, w->client_ip, w->client_port, gettid());
2406 if(unlikely(w->dead)) {
2407 debug(D_WEB_CLIENT, "%llu: client is dead.", w->id);
2410 else if(unlikely(!w->wait_receive && !w->wait_send)) {
2411 debug(D_WEB_CLIENT, "%llu: client is not set for neither receiving nor sending data.", w->id);
2415 if(unlikely(w->ifd < 0 || w->ofd < 0)) {
2416 error("%llu: invalid file descriptor, ifd = %d, ofd = %d (required 0 <= fd", w->id, w->ifd, w->ofd);
2420 if(w->ifd == w->ofd) {
2425 if(w->wait_receive) fds[0].events |= POLLIN;
2426 if(w->wait_send) fds[0].events |= POLLOUT;
2432 ifd = ofd = &fds[0];
2440 if(w->wait_receive) fds[0].events |= POLLIN;
2446 if(w->wait_send) fds[1].events |= POLLOUT;
2452 debug(D_WEB_CLIENT, "%llu: Waiting socket async I/O for %s %s", w->id, w->wait_receive?"INPUT":"", w->wait_send?"OUTPUT":"");
2454 timeout = web_client_timeout * 1000;
2455 retval = poll(fds, fdmax, timeout);
2457 if(unlikely(retval == -1)) {
2458 if(errno == EAGAIN || errno == EINTR) {
2459 debug(D_WEB_CLIENT, "%llu: EAGAIN received.", w->id);
2463 debug(D_WEB_CLIENT, "%llu: LISTENER: poll() failed (input fd = %d, output fd = %d). Closing client.", w->id, w->ifd, w->ofd);
2466 else if(unlikely(!retval)) {
2467 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":"");
2472 if(w->wait_send && ofd->revents & POLLOUT) {
2474 if(web_client_send(w) < 0) {
2475 debug(D_WEB_CLIENT, "%llu: Cannot send data to client. Closing client.", w->id);
2480 if(w->wait_receive && (ifd->revents & POLLIN || ifd->revents & POLLPRI)) {
2482 if(web_client_receive(w) < 0) {
2483 debug(D_WEB_CLIENT, "%llu: Cannot receive data from client. Closing client.", w->id);
2487 if(w->mode == WEB_CLIENT_MODE_NORMAL) {
2488 debug(D_WEB_CLIENT, "%llu: Attempting to process received data.", w->id);
2489 web_client_process(w);
2493 if(unlikely(!used)) {
2494 debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on socket.", w->id);
2499 web_client_reset(w);
2501 log_access("%llu: %s port %s disconnected from thread task id %d", w->id, w->client_ip, w->client_port, gettid());
2502 debug(D_WEB_CLIENT, "%llu: done...", w->id);
2504 // close the sockets/files now
2505 // to free file descriptors
2506 if(w->ifd == w->ofd) {
2507 if(w->ifd != -1) close(w->ifd);
2510 if(w->ifd != -1) close(w->ifd);
2511 if(w->ofd != -1) close(w->ofd);