7 #include <sys/socket.h>
8 #include <netinet/in.h>
14 #include <netinet/tcp.h>
22 #include "appconfig.h"
24 #include "web_buffer.h"
25 #include "web_server.h"
26 #include "global_statistics.h"
31 #include "web_client.h"
32 #include "../config.h"
34 #define INITIAL_WEB_DATA_LENGTH 16384
35 #define WEB_REQUEST_LENGTH 16384
36 #define TOO_BIG_REQUEST 16384
38 int web_client_timeout = DEFAULT_DISCONNECT_IDLE_WEB_CLIENTS_AFTER_SECONDS;
39 int web_enable_gzip = 1;
41 extern int netdata_exit;
43 struct web_client *web_clients = NULL;
44 unsigned long long web_clients_count = 0;
46 struct web_client *web_client_create(int listener)
50 w = calloc(1, sizeof(struct web_client));
52 error("Cannot allocate new web_client memory.");
56 w->id = ++web_clients_count;
57 w->mode = WEB_CLIENT_MODE_NORMAL;
60 struct sockaddr *sadr;
63 sadr = (struct sockaddr*) &w->clientaddr;
64 addrlen = sizeof(w->clientaddr);
66 w->ifd = accept(listener, sadr, &addrlen);
68 error("%llu: Cannot accept new incoming connection.", w->id);
74 if(getnameinfo(sadr, addrlen, w->client_ip, NI_MAXHOST, w->client_port, NI_MAXSERV, NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
75 error("Cannot getnameinfo() on received client connection.");
76 strncpyz(w->client_ip, "UNKNOWN", NI_MAXHOST);
77 strncpyz(w->client_port, "UNKNOWN", NI_MAXSERV);
79 w->client_ip[NI_MAXHOST] = '\0';
80 w->client_port[NI_MAXSERV] = '\0';
82 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 strcpy(w->client_ip, &w->client_ip[7]);
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);
93 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);
97 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);
102 if(setsockopt(w->ifd, SOL_SOCKET, SO_KEEPALIVE, (char *) &flag, sizeof(int)) != 0) error("%llu: Cannot set SO_KEEPALIVE on socket.", w->id);
105 w->response.data = buffer_create(INITIAL_WEB_DATA_LENGTH);
106 if(unlikely(!w->response.data)) {
107 // no need for error log - web_buffer_create already logged the error
113 w->response.header = buffer_create(HTTP_RESPONSE_HEADER_SIZE);
114 if(unlikely(!w->response.header)) {
115 // no need for error log - web_buffer_create already logged the error
116 buffer_free(w->response.data);
122 w->response.header_output = buffer_create(HTTP_RESPONSE_HEADER_SIZE);
123 if(unlikely(!w->response.header_output)) {
124 // no need for error log - web_buffer_create already logged the error
125 buffer_free(w->response.header);
126 buffer_free(w->response.data);
135 if(web_clients) web_clients->prev = w;
136 w->next = web_clients;
139 global_statistics.connected_clients++;
144 void web_client_reset(struct web_client *w)
147 gettimeofday(&tv, NULL);
149 debug(D_WEB_CLIENT, "%llu: Reseting client.", w->id);
151 if(w->stats_received_bytes || w->stats_sent_bytes) {
152 global_statistics_lock();
153 global_statistics.web_requests++;
154 global_statistics.web_usec += usecdiff(&tv, &w->tv_in);
155 global_statistics.bytes_received += w->stats_received_bytes;
156 global_statistics.bytes_sent += w->stats_sent_bytes;
157 global_statistics_unlock();
159 w->stats_received_bytes = 0;
160 w->stats_sent_bytes = 0;
162 long sent = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->response.rlen:w->response.data->len;
164 #ifdef NETDATA_WITH_ZLIB
165 if(likely(w->response.zoutput)) sent = (long)w->response.zstream.total_out;
168 long size = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->response.rlen:w->response.data->len;
170 if(likely(w->last_url[0]))
171 log_access("%llu: (sent/all = %ld/%ld bytes %0.0f%%, prep/sent/total = %0.2f/%0.2f/%0.2f ms) %s: %d '%s'",
173 sent, size, -((size>0)?((float)(size-sent)/(float)size * 100.0):0.0),
174 (float)usecdiff(&w->tv_ready, &w->tv_in) / 1000.0,
175 (float)usecdiff(&tv, &w->tv_ready) / 1000.0,
176 (float)usecdiff(&tv, &w->tv_in) / 1000.0,
177 (w->mode == WEB_CLIENT_MODE_FILECOPY)?"filecopy":((w->mode == WEB_CLIENT_MODE_OPTIONS)?"options":"data"),
182 if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY)) {
183 debug(D_WEB_CLIENT, "%llu: Closing filecopy input file.", w->id);
188 w->last_url[0] = '\0';
189 w->cookie1[0] = '\0';
190 w->cookie2[0] = '\0';
194 w->mode = WEB_CLIENT_MODE_NORMAL;
197 w->decoded_url[0] = '\0';
199 buffer_reset(w->response.header_output);
200 buffer_reset(w->response.header);
201 buffer_reset(w->response.data);
202 w->response.rlen = 0;
203 w->response.sent = 0;
204 w->response.code = 0;
209 w->response.zoutput = 0;
211 // if we had enabled compression, release it
212 #ifdef NETDATA_WITH_ZLIB
213 if(w->response.zinitialized) {
214 debug(D_DEFLATE, "%llu: Reseting compression.", w->id);
215 deflateEnd(&w->response.zstream);
216 w->response.zsent = 0;
217 w->response.zhave = 0;
218 w->response.zstream.avail_in = 0;
219 w->response.zstream.avail_out = 0;
220 w->response.zstream.total_in = 0;
221 w->response.zstream.total_out = 0;
222 w->response.zinitialized = 0;
224 #endif // NETDATA_WITH_ZLIB
227 struct web_client *web_client_free(struct web_client *w)
229 struct web_client *n = w->next;
231 debug(D_WEB_CLIENT_ACCESS, "%llu: Closing web client from %s port %s.", w->id, w->client_ip, w->client_port);
233 if(w->prev) w->prev->next = w->next;
234 if(w->next) w->next->prev = w->prev;
236 if(w == web_clients) web_clients = w->next;
238 if(w->response.header_output) buffer_free(w->response.header_output);
239 if(w->response.header) buffer_free(w->response.header);
240 if(w->response.data) buffer_free(w->response.data);
242 if(w->ofd != w->ifd) close(w->ofd);
245 global_statistics.connected_clients--;
250 uid_t web_files_uid(void)
252 static char *web_owner = NULL;
253 static uid_t owner_uid = 0;
255 if(unlikely(!web_owner)) {
256 web_owner = config_get("global", "web files owner", config_get("global", "run as user", ""));
257 if(!web_owner || !*web_owner)
258 owner_uid = geteuid();
260 // getpwnam() is not thread safe,
261 // but we have called this function once
262 // while single threaded
263 struct passwd *pw = getpwnam(web_owner);
265 error("User %s is not present. Ignoring option.", web_owner);
266 owner_uid = geteuid();
269 debug(D_WEB_CLIENT, "Web files owner set to %s.\n", web_owner);
270 owner_uid = pw->pw_uid;
278 gid_t web_files_gid(void)
280 static char *web_group = NULL;
281 static gid_t owner_gid = 0;
283 if(unlikely(!web_group)) {
284 web_group = config_get("global", "web files group", config_get("global", "web files owner", ""));
285 if(!web_group || !*web_group)
286 owner_gid = getegid();
288 // getgrnam() is not thread safe,
289 // but we have called this function once
290 // while single threaded
291 struct group *gr = getgrnam(web_group);
293 error("Group %s is not present. Ignoring option.", web_group);
294 owner_gid = getegid();
297 debug(D_WEB_CLIENT, "Web files group set to %s.\n", web_group);
298 owner_gid = gr->gr_gid;
306 int mysendfile(struct web_client *w, char *filename)
308 static char *web_dir = NULL;
310 // initialize our static data
311 if(unlikely(!web_dir)) web_dir = config_get("global", "web files directory", WEB_DIR);
313 debug(D_WEB_CLIENT, "%llu: Looking for file '%s/%s'", w->id, web_dir, filename);
315 // skip leading slashes
316 while (*filename == '/') filename++;
318 // if the filename contain known paths, skip them
319 if(strncmp(filename, WEB_PATH_FILE "/", strlen(WEB_PATH_FILE) + 1) == 0) filename = &filename[strlen(WEB_PATH_FILE) + 1];
322 for(s = filename; *s ;s++) {
323 if( !isalnum(*s) && *s != '/' && *s != '.' && *s != '-' && *s != '_') {
324 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
325 buffer_sprintf(w->response.data, "File '%s' cannot be served. Filename contains invalid character '%c'", filename, *s);
330 // if the filename contains a .. refuse to serve it
331 if(strstr(filename, "..") != 0) {
332 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
333 buffer_sprintf(w->response.data, "File '%s' cannot be served. Relative filenames with '..' in them are not supported.", filename);
338 char webfilename[FILENAME_MAX + 1];
339 snprintfz(webfilename, FILENAME_MAX, "%s/%s", web_dir, filename);
341 // check if the file exists
343 if(lstat(webfilename, &stat) != 0) {
344 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not found.", w->id, webfilename);
345 buffer_sprintf(w->response.data, "File '%s' does not exist, or is not accessible.", webfilename);
349 // check if the file is owned by expected user
350 if(stat.st_uid != web_files_uid()) {
351 error("%llu: File '%s' is owned by user %d (expected user %d). Access Denied.", w->id, webfilename, stat.st_uid, web_files_uid());
352 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", webfilename);
356 // check if the file is owned by expected group
357 if(stat.st_gid != web_files_gid()) {
358 error("%llu: File '%s' is owned by group %d (expected group %d). Access Denied.", w->id, webfilename, stat.st_gid, web_files_gid());
359 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", webfilename);
363 if((stat.st_mode & S_IFMT) == S_IFDIR) {
364 snprintfz(webfilename, FILENAME_MAX, "%s/index.html", filename);
365 return mysendfile(w, webfilename);
368 if((stat.st_mode & S_IFMT) != S_IFREG) {
369 error("%llu: File '%s' is not a regular file. Access Denied.", w->id, webfilename);
370 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", webfilename);
375 w->ifd = open(webfilename, O_NONBLOCK, O_RDONLY);
379 if(errno == EBUSY || errno == EAGAIN) {
380 error("%llu: File '%s' is busy, sending 307 Moved Temporarily to force retry.", w->id, webfilename);
381 buffer_sprintf(w->response.header, "Location: /" WEB_PATH_FILE "/%s\r\n", filename);
382 buffer_sprintf(w->response.data, "The file '%s' is currently busy. Please try again later.", webfilename);
386 error("%llu: Cannot open file '%s'.", w->id, webfilename);
387 buffer_sprintf(w->response.data, "Cannot open file '%s'.", webfilename);
392 // pick a Content-Type for the file
393 if(strstr(filename, ".html") != NULL) w->response.data->contenttype = CT_TEXT_HTML;
394 else if(strstr(filename, ".js") != NULL) w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
395 else if(strstr(filename, ".css") != NULL) w->response.data->contenttype = CT_TEXT_CSS;
396 else if(strstr(filename, ".xml") != NULL) w->response.data->contenttype = CT_TEXT_XML;
397 else if(strstr(filename, ".xsl") != NULL) w->response.data->contenttype = CT_TEXT_XSL;
398 else if(strstr(filename, ".txt") != NULL) w->response.data->contenttype = CT_TEXT_PLAIN;
399 else if(strstr(filename, ".svg") != NULL) w->response.data->contenttype = CT_IMAGE_SVG_XML;
400 else if(strstr(filename, ".ttf") != NULL) w->response.data->contenttype = CT_APPLICATION_X_FONT_TRUETYPE;
401 else if(strstr(filename, ".otf") != NULL) w->response.data->contenttype = CT_APPLICATION_X_FONT_OPENTYPE;
402 else if(strstr(filename, ".woff2")!= NULL) w->response.data->contenttype = CT_APPLICATION_FONT_WOFF2;
403 else if(strstr(filename, ".woff") != NULL) w->response.data->contenttype = CT_APPLICATION_FONT_WOFF;
404 else if(strstr(filename, ".eot") != NULL) w->response.data->contenttype = CT_APPLICATION_VND_MS_FONTOBJ;
405 else if(strstr(filename, ".png") != NULL) w->response.data->contenttype = CT_IMAGE_PNG;
406 else if(strstr(filename, ".jpg") != NULL) w->response.data->contenttype = CT_IMAGE_JPG;
407 else if(strstr(filename, ".jpeg") != NULL) w->response.data->contenttype = CT_IMAGE_JPG;
408 else if(strstr(filename, ".gif") != NULL) w->response.data->contenttype = CT_IMAGE_GIF;
409 else if(strstr(filename, ".bmp") != NULL) w->response.data->contenttype = CT_IMAGE_BMP;
410 else if(strstr(filename, ".ico") != NULL) w->response.data->contenttype = CT_IMAGE_XICON;
411 else if(strstr(filename, ".icns") != NULL) w->response.data->contenttype = CT_IMAGE_ICNS;
412 else w->response.data->contenttype = CT_APPLICATION_OCTET_STREAM;
414 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);
416 w->mode = WEB_CLIENT_MODE_FILECOPY;
419 buffer_flush(w->response.data);
420 w->response.rlen = stat.st_size;
421 w->response.data->date = stat.st_mtim.tv_sec;
427 #ifdef NETDATA_WITH_ZLIB
428 void web_client_enable_deflate(struct web_client *w) {
429 if(w->response.zinitialized == 1) {
430 error("%llu: Compression has already be initialized for this client.", w->id);
434 if(w->response.sent) {
435 error("%llu: Cannot enable compression in the middle of a conversation.", w->id);
439 w->response.zstream.zalloc = Z_NULL;
440 w->response.zstream.zfree = Z_NULL;
441 w->response.zstream.opaque = Z_NULL;
443 w->response.zstream.next_in = (Bytef *)w->response.data->buffer;
444 w->response.zstream.avail_in = 0;
445 w->response.zstream.total_in = 0;
447 w->response.zstream.next_out = w->response.zbuffer;
448 w->response.zstream.avail_out = 0;
449 w->response.zstream.total_out = 0;
451 w->response.zstream.zalloc = Z_NULL;
452 w->response.zstream.zfree = Z_NULL;
453 w->response.zstream.opaque = Z_NULL;
455 // if(deflateInit(&w->response.zstream, Z_DEFAULT_COMPRESSION) != Z_OK) {
456 // error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
460 // Select GZIP compression: windowbits = 15 + 16 = 31
461 if(deflateInit2(&w->response.zstream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY) != Z_OK) {
462 error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
466 w->response.zsent = 0;
467 w->response.zoutput = 1;
468 w->response.zinitialized = 1;
470 debug(D_DEFLATE, "%llu: Initialized compression.", w->id);
472 #endif // NETDATA_WITH_ZLIB
474 uint32_t web_client_api_request_v1_data_options(char *o)
476 uint32_t ret = 0x00000000;
479 while(o && *o && (tok = mystrsep(&o, ", |"))) {
482 if(!strcmp(tok, "nonzero"))
483 ret |= RRDR_OPTION_NONZERO;
484 else if(!strcmp(tok, "flip") || !strcmp(tok, "reversed") || !strcmp(tok, "reverse"))
485 ret |= RRDR_OPTION_REVERSED;
486 else if(!strcmp(tok, "jsonwrap"))
487 ret |= RRDR_OPTION_JSON_WRAP;
488 else if(!strcmp(tok, "min2max"))
489 ret |= RRDR_OPTION_MIN2MAX;
490 else if(!strcmp(tok, "ms") || !strcmp(tok, "milliseconds"))
491 ret |= RRDR_OPTION_MILLISECONDS;
492 else if(!strcmp(tok, "abs") || !strcmp(tok, "absolute") || !strcmp(tok, "absolute_sum") || !strcmp(tok, "absolute-sum"))
493 ret |= RRDR_OPTION_ABSOLUTE;
494 else if(!strcmp(tok, "seconds"))
495 ret |= RRDR_OPTION_SECONDS;
496 else if(!strcmp(tok, "null2zero"))
497 ret |= RRDR_OPTION_NULL2ZERO;
498 else if(!strcmp(tok, "objectrows"))
499 ret |= RRDR_OPTION_OBJECTSROWS;
500 else if(!strcmp(tok, "google_json"))
501 ret |= RRDR_OPTION_GOOGLE_JSON;
502 else if(!strcmp(tok, "percentage"))
503 ret |= RRDR_OPTION_PERCENTAGE;
509 uint32_t web_client_api_request_v1_data_format(char *name)
511 if(!strcmp(name, DATASOURCE_FORMAT_DATATABLE_JSON)) // datatable
512 return DATASOURCE_DATATABLE_JSON;
514 else if(!strcmp(name, DATASOURCE_FORMAT_DATATABLE_JSONP)) // datasource
515 return DATASOURCE_DATATABLE_JSONP;
517 else if(!strcmp(name, DATASOURCE_FORMAT_JSON)) // json
518 return DATASOURCE_JSON;
520 else if(!strcmp(name, DATASOURCE_FORMAT_JSONP)) // jsonp
521 return DATASOURCE_JSONP;
523 else if(!strcmp(name, DATASOURCE_FORMAT_SSV)) // ssv
524 return DATASOURCE_SSV;
526 else if(!strcmp(name, DATASOURCE_FORMAT_CSV)) // csv
527 return DATASOURCE_CSV;
529 else if(!strcmp(name, DATASOURCE_FORMAT_TSV) || !strcmp(name, "tsv-excel")) // tsv
530 return DATASOURCE_TSV;
532 else if(!strcmp(name, DATASOURCE_FORMAT_HTML)) // html
533 return DATASOURCE_HTML;
535 else if(!strcmp(name, DATASOURCE_FORMAT_JS_ARRAY)) // array
536 return DATASOURCE_JS_ARRAY;
538 else if(!strcmp(name, DATASOURCE_FORMAT_SSV_COMMA)) // ssvcomma
539 return DATASOURCE_SSV_COMMA;
541 else if(!strcmp(name, DATASOURCE_FORMAT_CSV_JSON_ARRAY)) // csvjsonarray
542 return DATASOURCE_CSV_JSON_ARRAY;
544 return DATASOURCE_JSON;
547 uint32_t web_client_api_request_v1_data_google_format(char *name)
549 if(!strcmp(name, "json"))
550 return DATASOURCE_DATATABLE_JSONP;
552 else if(!strcmp(name, "html"))
553 return DATASOURCE_HTML;
555 else if(!strcmp(name, "csv"))
556 return DATASOURCE_CSV;
558 else if(!strcmp(name, "tsv-excel"))
559 return DATASOURCE_TSV;
561 return DATASOURCE_JSON;
564 int web_client_api_request_v1_data_group(char *name)
566 if(!strcmp(name, "max"))
569 else if(!strcmp(name, "average"))
570 return GROUP_AVERAGE;
575 int web_client_api_request_v1_charts(struct web_client *w, char *url)
579 buffer_flush(w->response.data);
580 w->response.data->contenttype = CT_APPLICATION_JSON;
581 rrd_stats_api_v1_charts(w->response.data);
585 int web_client_api_request_v1_chart(struct web_client *w, char *url)
590 buffer_flush(w->response.data);
593 char *value = mystrsep(&url, "?&[]");
594 if(!value || !*value) continue;
596 char *name = mystrsep(&value, "=");
597 if(!name || !*name) continue;
598 if(!value || !*value) continue;
600 // name and value are now the parameters
601 // they are not null and not empty
603 if(!strcmp(name, "chart")) chart = value;
605 /// buffer_sprintf(w->response.data, "Unknown parameter '%s' in request.", name);
610 if(!chart || !*chart) {
611 buffer_sprintf(w->response.data, "No chart id is given at the request.");
615 RRDSET *st = rrdset_find(chart);
616 if(!st) st = rrdset_find_byname(chart);
618 buffer_sprintf(w->response.data, "Chart '%s' is not found.", chart);
623 w->response.data->contenttype = CT_APPLICATION_JSON;
624 rrd_stats_api_v1_chart(st, w->response.data);
631 // returns the HTTP code
632 int web_client_api_request_v1_data(struct web_client *w, char *url)
634 debug(D_WEB_CLIENT, "%llu: API v1 data with URL '%s'", w->id, url);
637 BUFFER *dimensions = NULL;
639 buffer_flush(w->response.data);
641 char *google_version = "0.6",
644 *google_out = "json",
645 *responseHandler = NULL,
648 time_t last_timestamp_in_data = 0, google_timestamp = 0;
653 , *points_str = NULL;
655 int group = GROUP_MAX;
656 uint32_t format = DATASOURCE_JSON;
657 uint32_t options = 0x00000000;
660 char *value = mystrsep(&url, "?&[]");
661 if(!value || !*value) continue;
663 char *name = mystrsep(&value, "=");
664 if(!name || !*name) continue;
665 if(!value || !*value) continue;
667 debug(D_WEB_CLIENT, "%llu: API v1 data query param '%s' with value '%s'", w->id, name, value);
669 // name and value are now the parameters
670 // they are not null and not empty
672 if(!strcmp(name, "chart")) chart = value;
673 else if(!strcmp(name, "dimension") || !strcmp(name, "dim") || !strcmp(name, "dimensions") || !strcmp(name, "dims")) {
674 if(!dimensions) dimensions = buffer_create(strlen(value));
676 buffer_strcat(dimensions, "|");
677 buffer_strcat(dimensions, value);
680 else if(!strcmp(name, "after")) after_str = value;
681 else if(!strcmp(name, "before")) before_str = value;
682 else if(!strcmp(name, "points")) points_str = value;
683 else if(!strcmp(name, "group")) {
684 group = web_client_api_request_v1_data_group(value);
686 else if(!strcmp(name, "format")) {
687 format = web_client_api_request_v1_data_format(value);
689 else if(!strcmp(name, "options")) {
690 options |= web_client_api_request_v1_data_options(value);
692 else if(!strcmp(name, "callback")) {
693 responseHandler = value;
695 else if(!strcmp(name, "filename")) {
698 else if(!strcmp(name, "tqx")) {
699 // parse Google Visualization API options
700 // https://developers.google.com/chart/interactive/docs/dev/implementing_data_source
701 char *tqx_name, *tqx_value;
704 tqx_value = mystrsep(&value, ";");
705 if(!tqx_value || !*tqx_value) continue;
707 tqx_name = mystrsep(&tqx_value, ":");
708 if(!tqx_name || !*tqx_name) continue;
709 if(!tqx_value || !*tqx_value) continue;
711 if(!strcmp(tqx_name, "version"))
712 google_version = tqx_value;
713 else if(!strcmp(tqx_name, "reqId"))
714 google_reqId = tqx_value;
715 else if(!strcmp(tqx_name, "sig")) {
716 google_sig = tqx_value;
717 google_timestamp = strtoul(google_sig, NULL, 0);
719 else if(!strcmp(tqx_name, "out")) {
720 google_out = tqx_value;
721 format = web_client_api_request_v1_data_google_format(google_out);
723 else if(!strcmp(tqx_name, "responseHandler"))
724 responseHandler = tqx_value;
725 else if(!strcmp(tqx_name, "outFileName"))
726 outFileName = tqx_value;
731 if(!chart || !*chart) {
732 buffer_sprintf(w->response.data, "No chart id is given at the request.");
736 RRDSET *st = rrdset_find(chart);
737 if(!st) st = rrdset_find_byname(chart);
739 buffer_sprintf(w->response.data, "Chart '%s' is not found.", chart);
744 long long before = (before_str && *before_str)?atol(before_str):0;
745 long long after = (after_str && *after_str) ?atol(after_str):0;
746 int points = (points_str && *points_str)?atoi(points_str):0;
748 debug(D_WEB_CLIENT, "%llu: API command 'data' for chart '%s', dimensions '%s', after '%lld', before '%lld', points '%d', group '%u', format '%u', options '0x%08x'"
751 , (dimensions)?buffer_tostring(dimensions):""
760 if(outFileName && *outFileName) {
761 buffer_sprintf(w->response.header, "Content-Disposition: attachment; filename=\"%s\"\r\n", outFileName);
762 error("generating outfilename header: '%s'", outFileName);
765 if(format == DATASOURCE_DATATABLE_JSONP) {
766 if(responseHandler == NULL)
767 responseHandler = "google.visualization.Query.setResponse";
769 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSON/JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
770 w->id, google_version, google_reqId, google_sig, google_out, responseHandler, outFileName
773 buffer_sprintf(w->response.data,
774 "%s({version:'%s',reqId:'%s',status:'ok',sig:'%lu',table:",
775 responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
777 else if(format == DATASOURCE_JSONP) {
778 if(responseHandler == NULL)
779 responseHandler = "callback";
781 buffer_strcat(w->response.data, responseHandler);
782 buffer_strcat(w->response.data, "(");
785 ret = rrd2format(st, w->response.data, dimensions, format, points, after, before, group, options, &last_timestamp_in_data);
787 if(format == DATASOURCE_DATATABLE_JSONP) {
788 if(google_timestamp < last_timestamp_in_data)
789 buffer_strcat(w->response.data, "});");
792 // the client already has the latest data
793 buffer_flush(w->response.data);
794 buffer_sprintf(w->response.data,
795 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
796 responseHandler, google_version, google_reqId);
799 else if(format == DATASOURCE_JSONP)
800 buffer_strcat(w->response.data, ");");
803 if(dimensions) buffer_free(dimensions);
807 int web_client_api_request_v1_registry(struct web_client *w, char *url)
809 char person_guid[36 + 1] = "";
811 debug(D_WEB_CLIENT, "%llu: API v1 registry with URL '%s'", w->id, url);
814 // The browser may send multiple cookies with our id
816 char *cookie = strstr(w->response.data->buffer, " " NETDATA_REGISTRY_COOKIE_NAME "=");
818 strncpyz(person_guid, &cookie[sizeof(NETDATA_REGISTRY_COOKIE_NAME) + 1], 36);
821 char *machine_guid = NULL,
824 *search_machine_guid = NULL,
826 *to_person_guid = NULL;
829 char *value = mystrsep(&url, "?&[]");
830 if (!value || !*value) continue;
832 char *name = mystrsep(&value, "=");
833 if (!name || !*name) continue;
834 if (!value || !*value) continue;
836 debug(D_WEB_CLIENT, "%llu: API v1 registry query param '%s' with value '%s'", w->id, name, value);
838 if(!strcmp(name, "action")) {
839 if(!strcmp(value, "access")) action = 'A';
840 else if(!strcmp(value, "hello")) action = 'H';
841 else if(!strcmp(value, "delete")) action = 'D';
842 else if(!strcmp(value, "search")) action = 'S';
843 else if(!strcmp(value, "switch")) action = 'W';
845 else if(!strcmp(name, "machine"))
846 machine_guid = value;
848 else if(!strcmp(name, "url"))
851 else if(action == 'A') {
852 if(!strcmp(name, "name"))
855 else if(action == 'D') {
856 if(!strcmp(name, "delete_url"))
859 else if(action == 'S') {
860 if(!strcmp(name, "for"))
861 search_machine_guid = value;
863 else if(action == 'W') {
864 if(!strcmp(name, "to"))
865 to_person_guid = value;
869 if(action == 'A' && (!machine_guid || !machine_url || !url_name)) {
870 buffer_flush(w->response.data);
871 buffer_sprintf(w->response.data, "Invalid registry request - access requires these parameters: machine ('%s'), url ('%s'), name ('%s')",
872 machine_guid?machine_guid:"UNSET", machine_url?machine_url:"UNSET", url_name?url_name:"UNSET");
875 else if(action == 'D' && (!machine_guid || !machine_url || !delete_url)) {
876 buffer_flush(w->response.data);
877 buffer_sprintf(w->response.data, "Invalid registry request - delete requires these parameters: machine ('%s'), url ('%s'), delete_url ('%s')",
878 machine_guid?machine_guid:"UNSET", machine_url?machine_url:"UNSET", delete_url?delete_url:"UNSET");
881 else if(action == 'S' && (!machine_guid || !machine_url || !search_machine_guid)) {
882 buffer_flush(w->response.data);
883 buffer_sprintf(w->response.data, "Invalid registry request - search requires these parameters: machine ('%s'), url ('%s'), for ('%s')",
884 machine_guid?machine_guid:"UNSET", machine_url?machine_url:"UNSET", search_machine_guid?search_machine_guid:"UNSET");
887 else if(action == 'W' && (!machine_guid || !machine_url || !to_person_guid)) {
888 buffer_flush(w->response.data);
889 buffer_sprintf(w->response.data, "Invalid registry request - switching identity requires these parameters: machine ('%s'), url ('%s'), to ('%s')",
890 machine_guid?machine_guid:"UNSET", machine_url?machine_url:"UNSET", to_person_guid?to_person_guid:"UNSET");
896 return registry_request_access_json(w, person_guid, machine_guid, machine_url, url_name, time(NULL));
899 return registry_request_delete_json(w, person_guid, machine_guid, machine_url, delete_url, time(NULL));
902 return registry_request_search_json(w, person_guid, machine_guid, machine_url, search_machine_guid, time(NULL));
905 return registry_request_switch_json(w, person_guid, machine_guid, machine_url, to_person_guid, time(NULL));
908 return registry_request_hello_json(w);
911 buffer_flush(w->response.data);
912 buffer_sprintf(w->response.data, "Invalid registry request - you need to set an action: hello, access, delete, search");
916 buffer_flush(w->response.data);
917 buffer_sprintf(w->response.data, "Invalid or no registry action.");
921 int web_client_api_request_v1(struct web_client *w, char *url)
923 static uint32_t data_hash = 0, chart_hash = 0, charts_hash = 0, registry_hash = 0;
925 if(unlikely(data_hash == 0)) {
926 data_hash = simple_hash("data");
927 chart_hash = simple_hash("chart");
928 charts_hash = simple_hash("charts");
929 registry_hash = simple_hash("registry");
933 char *tok = mystrsep(&url, "/?&");
935 debug(D_WEB_CLIENT, "%llu: Searching for API v1 command '%s'.", w->id, tok);
936 uint32_t hash = simple_hash(tok);
938 if(hash == data_hash && !strcmp(tok, "data"))
939 return web_client_api_request_v1_data(w, url);
941 else if(hash == chart_hash && !strcmp(tok, "chart"))
942 return web_client_api_request_v1_chart(w, url);
944 else if(hash == charts_hash && !strcmp(tok, "charts"))
945 return web_client_api_request_v1_charts(w, url);
947 else if(hash == registry_hash && !strcmp(tok, "registry"))
948 return web_client_api_request_v1_registry(w, url);
951 buffer_flush(w->response.data);
952 buffer_sprintf(w->response.data, "Unsupported v1 API command: %s", tok);
957 buffer_flush(w->response.data);
958 buffer_sprintf(w->response.data, "API v1 command?");
963 int web_client_api_request(struct web_client *w, char *url)
965 // get the api version
966 char *tok = mystrsep(&url, "/?&");
968 debug(D_WEB_CLIENT, "%llu: Searching for API version '%s'.", w->id, tok);
969 if(strcmp(tok, "v1") == 0)
970 return web_client_api_request_v1(w, url);
972 buffer_flush(w->response.data);
973 buffer_sprintf(w->response.data, "Unsupported API version: %s", tok);
978 buffer_flush(w->response.data);
979 buffer_sprintf(w->response.data, "Which API version?");
984 int web_client_data_request(struct web_client *w, char *url, int datasource_type)
988 char *args = strchr(url, '?');
994 // get the name of the data to show
995 char *tok = mystrsep(&url, "/");
997 // do we have such a data set?
999 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1000 st = rrdset_find_byname(tok);
1001 if(!st) st = rrdset_find(tok);
1006 // try to send a file with that name
1007 buffer_flush(w->response.data);
1008 return(mysendfile(w, tok));
1012 debug(D_WEB_CLIENT, "%llu: Found RRD data with name '%s'.", w->id, tok);
1014 // how many entries does the client want?
1015 long lines = rrd_default_history_entries;
1016 long group_count = 1;
1017 time_t after = 0, before = 0;
1018 int group_method = GROUP_AVERAGE;
1022 // parse the lines required
1023 tok = mystrsep(&url, "/");
1024 if(tok) lines = atoi(tok);
1025 if(lines < 1) lines = 1;
1028 // parse the group count required
1029 tok = mystrsep(&url, "/");
1030 if(tok && *tok) group_count = atoi(tok);
1031 if(group_count < 1) group_count = 1;
1032 //if(group_count > save_history / 20) group_count = save_history / 20;
1035 // parse the grouping method required
1036 tok = mystrsep(&url, "/");
1038 if(strcmp(tok, "max") == 0) group_method = GROUP_MAX;
1039 else if(strcmp(tok, "average") == 0) group_method = GROUP_AVERAGE;
1040 else if(strcmp(tok, "sum") == 0) group_method = GROUP_SUM;
1041 else debug(D_WEB_CLIENT, "%llu: Unknown group method '%s'", w->id, tok);
1046 tok = mystrsep(&url, "/");
1047 if(tok && *tok) after = strtoul(tok, NULL, 10);
1048 if(after < 0) after = 0;
1051 // parse before time
1052 tok = mystrsep(&url, "/");
1053 if(tok && *tok) before = strtoul(tok, NULL, 10);
1054 if(before < 0) before = 0;
1058 tok = mystrsep(&url, "/");
1059 if(tok && *tok && strcmp(tok, "nonzero") == 0) nonzero = 1;
1062 w->response.data->contenttype = CT_APPLICATION_JSON;
1063 buffer_flush(w->response.data);
1065 char *google_version = "0.6";
1066 char *google_reqId = "0";
1067 char *google_sig = "0";
1068 char *google_out = "json";
1069 char *google_responseHandler = "google.visualization.Query.setResponse";
1070 char *google_outFileName = NULL;
1071 time_t last_timestamp_in_data = 0;
1072 if(datasource_type == DATASOURCE_DATATABLE_JSON || datasource_type == DATASOURCE_DATATABLE_JSONP) {
1074 w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
1077 tok = mystrsep(&args, "&");
1079 char *name = mystrsep(&tok, "=");
1080 if(name && *name && strcmp(name, "tqx") == 0) {
1081 char *key = mystrsep(&tok, ":");
1082 char *value = mystrsep(&tok, ";");
1083 if(key && value && *key && *value) {
1084 if(strcmp(key, "version") == 0)
1085 google_version = value;
1087 else if(strcmp(key, "reqId") == 0)
1088 google_reqId = value;
1090 else if(strcmp(key, "sig") == 0)
1093 else if(strcmp(key, "out") == 0)
1096 else if(strcmp(key, "responseHandler") == 0)
1097 google_responseHandler = value;
1099 else if(strcmp(key, "outFileName") == 0)
1100 google_outFileName = value;
1106 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
1107 w->id, google_version, google_reqId, google_sig, google_out, google_responseHandler, google_outFileName
1110 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
1111 last_timestamp_in_data = strtoul(google_sig, NULL, 0);
1113 // check the client wants json
1114 if(strcmp(google_out, "json") != 0) {
1115 buffer_sprintf(w->response.data,
1116 "%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.'}]});",
1117 google_responseHandler, google_version, google_reqId, google_out);
1123 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
1124 buffer_sprintf(w->response.data,
1125 "%s({version:'%s',reqId:'%s',status:'ok',sig:'%lu',table:",
1126 google_responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
1129 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending RRD data '%s' (id %s, %d lines, %d group, %d group_method, %lu after, %lu before).", w->id, st->name, st->id, lines, group_count, group_method, after, before);
1130 time_t timestamp_in_data = rrd_stats_json(datasource_type, st, w->response.data, lines, group_count, group_method, after, before, nonzero);
1132 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
1133 if(timestamp_in_data > last_timestamp_in_data)
1134 buffer_strcat(w->response.data, "});");
1137 // the client already has the latest data
1138 buffer_flush(w->response.data);
1139 buffer_sprintf(w->response.data,
1140 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
1141 google_responseHandler, google_version, google_reqId);
1149 int web_client_parse_request(struct web_client *w) {
1153 // query string name-value
1156 // http request headers name-value
1158 web_client_clean_request(w);
1160 debug(D_WEB_DATA, "%llu: Processing data buffer of %d bytes: '%s'.", w->id, w->response.data->bytes, w->response.data->buffer);
1162 char *buf = w->response.data->buffer;
1165 // ------------------------------------------------------------------------
1168 if(buf && (line = strsep(&buf, "\r\n"))) {
1170 if(line && (tok = strsep(&line, " "))) {
1171 w->request.protocol = strdup(tok);
1179 // ------------------------------------------------------------------------
1180 // the rest of the lines
1182 while(buf && (line = strsep(&buf, "\r\n"))) {
1183 while(line && (tok = strsep(&line, ": "))) {
1191 web_client_clean_request(w);
1197 static inline char *http_header_parse(struct web_client *w, char *s) {
1201 while(*e && *e != ':') e++;
1202 if(!*e || e[1] != ' ') return e;
1212 while(*ve && *ve != '\r') ve++;
1213 if(!*ve || ve[1] != '\n') {
1218 // terminate the value
1221 // fprintf(stderr, "HEADER: '%s' = '%s'\n", s, v);
1223 if(!strcasecmp(s, "Origin"))
1224 strncpyz(w->origin, v, ORIGIN_MAX);
1226 else if(!strcasecmp(s, "Connection")) {
1227 if(strcasestr(v, "keep-alive"))
1230 #ifdef NETDATA_WITH_ZLIB
1231 else if(!strcasecmp(s, "Accept-Encoding")) {
1232 if(web_enable_gzip && strcasestr(v, "gzip")) {
1236 #endif /* NETDATA_WITH_ZLIB */
1243 // http_request_validate()
1245 // = 0 : all good, process the request
1246 // > 0 : request is not supported
1247 // < 0 : request is incomplete - wait for more data
1249 static inline int http_request_validate(struct web_client *w) {
1250 char *s = w->response.data->buffer, *encoded_url = NULL;
1252 // is is a valid request?
1253 if(!strncmp(s, "GET ", 4)) {
1254 encoded_url = s = &s[4];
1255 w->mode = WEB_CLIENT_MODE_NORMAL;
1257 else if(!strncmp(s, "OPTIONS ", 8)) {
1258 encoded_url = s = &s[8];
1259 w->mode = WEB_CLIENT_MODE_OPTIONS;
1262 w->wait_receive = 0;
1266 // find the SPACE + "HTTP/"
1268 // find the next space
1269 while (*s && *s != ' ') s++;
1271 // is it SPACE + "HTTP/" ?
1272 if(*s && !strncmp(s, " HTTP/", 6)) break;
1276 // incomplete requests
1278 w->wait_receive = 1;
1282 // we have the end of encoded_url - remember it
1285 // make sure we have complete request
1286 // complete requests contain: \r\n\r\n
1289 while(*s && *s++ != '\r');
1291 // did we reach the end?
1292 if(unlikely(!*s)) break;
1295 if(likely(*s++ == '\n')) {
1297 // is it again \r\n ? (header end)
1298 if(unlikely(*s == '\r' && s[1] == '\n')) {
1299 // a valid complete HTTP request found
1302 url_decode_r(w->decoded_url, encoded_url, URL_MAX + 1);
1305 // copy the URL - we are going to overwrite parts of it
1306 // FIXME -- we should avoid it
1307 strncpyz(w->last_url, w->decoded_url, URL_MAX);
1309 w->wait_receive = 0;
1313 // another header line
1314 s = http_header_parse(w, s);
1318 // incomplete request
1319 w->wait_receive = 1;
1323 void web_client_process(struct web_client *w) {
1327 int what_to_do = http_request_validate(w);
1329 // wait for more data
1330 if(what_to_do < 0) {
1331 if(w->response.data->len > TOO_BIG_REQUEST) {
1332 strcpy(w->last_url, "too big request");
1334 debug(D_WEB_CLIENT_ACCESS, "%llu: Received request is too big (%zd bytes).", w->id, w->response.data->len);
1337 buffer_flush(w->response.data);
1338 buffer_sprintf(w->response.data, "Received request is too big (%zd bytes).\r\n", w->response.data->len);
1341 // wait for more data
1345 else if(what_to_do > 0) {
1346 strcpy(w->last_url, "not a valid response");
1348 debug(D_WEB_CLIENT_ACCESS, "%llu: Cannot understand '%s'.", w->id, w->response.data->buffer);
1351 buffer_flush(w->response.data);
1352 buffer_strcat(w->response.data, "I don't understand you...\r\n");
1354 else { // what_to_do == 0
1355 gettimeofday(&w->tv_in, NULL);
1357 if(w->mode == WEB_CLIENT_MODE_OPTIONS) {
1359 w->response.data->contenttype = CT_TEXT_PLAIN;
1360 buffer_flush(w->response.data);
1361 buffer_strcat(w->response.data, "OK");
1364 #ifdef NETDATA_WITH_ZLIB
1366 web_client_enable_deflate(w);
1369 char *url = w->decoded_url;
1370 char *tok = mystrsep(&url, "/?");
1372 debug(D_WEB_CLIENT, "%llu: Processing command '%s'.", w->id, tok);
1374 if(strcmp(tok, "api") == 0) {
1375 // the client is requesting api access
1376 code = web_client_api_request(w, url);
1378 else if(strcmp(tok, "netdata.conf") == 0) {
1380 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending netdata.conf ...", w->id);
1382 w->response.data->contenttype = CT_TEXT_PLAIN;
1383 buffer_flush(w->response.data);
1384 generate_config(w->response.data, 0);
1386 else if(strcmp(tok, WEB_PATH_DATA) == 0) { // "data"
1387 // the client is requesting rrd data -- OLD API
1388 code = web_client_data_request(w, url, DATASOURCE_JSON);
1390 else if(strcmp(tok, WEB_PATH_DATASOURCE) == 0) { // "datasource"
1391 // the client is requesting google datasource -- OLD API
1392 code = web_client_data_request(w, url, DATASOURCE_DATATABLE_JSONP);
1394 else if(strcmp(tok, WEB_PATH_GRAPH) == 0) { // "graph"
1395 // the client is requesting an rrd graph -- OLD API
1397 // get the name of the data to show
1398 tok = mystrsep(&url, "/?&");
1400 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1402 // do we have such a data set?
1403 RRDSET *st = rrdset_find_byname(tok);
1404 if(!st) st = rrdset_find(tok);
1407 // try to send a file with that name
1408 buffer_flush(w->response.data);
1409 code = mysendfile(w, tok);
1413 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending %s.json of RRD_STATS...", w->id, st->name);
1414 w->response.data->contenttype = CT_APPLICATION_JSON;
1415 buffer_flush(w->response.data);
1416 rrd_stats_graph_json(st, url, w->response.data);
1421 buffer_flush(w->response.data);
1422 buffer_strcat(w->response.data, "Graph name?\r\n");
1425 else if(strcmp(tok, "list") == 0) {
1429 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending list of RRD_STATS...", w->id);
1431 buffer_flush(w->response.data);
1432 RRDSET *st = rrdset_root;
1434 for ( ; st ; st = st->next )
1435 buffer_sprintf(w->response.data, "%s\n", st->name);
1437 else if(strcmp(tok, "all.json") == 0) {
1440 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending JSON list of all monitors of RRD_STATS...", w->id);
1442 w->response.data->contenttype = CT_APPLICATION_JSON;
1443 buffer_flush(w->response.data);
1444 rrd_stats_all_json(w->response.data);
1446 #ifdef NETDATA_INTERNAL_CHECKS
1447 else if(strcmp(tok, "exit") == 0) {
1449 w->response.data->contenttype = CT_TEXT_PLAIN;
1450 buffer_flush(w->response.data);
1453 buffer_strcat(w->response.data, "ok, will do...");
1455 buffer_strcat(w->response.data, "I am doing it already");
1459 else if(strcmp(tok, "debug") == 0) {
1460 buffer_flush(w->response.data);
1462 // get the name of the data to show
1463 tok = mystrsep(&url, "/?&");
1465 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1467 // do we have such a data set?
1468 RRDSET *st = rrdset_find_byname(tok);
1469 if(!st) st = rrdset_find(tok);
1472 buffer_sprintf(w->response.data, "Chart %s is not found.\r\n", tok);
1473 debug(D_WEB_CLIENT_ACCESS, "%llu: %s is not found.", w->id, tok);
1477 debug_flags |= D_RRD_STATS;
1478 st->debug = !st->debug;
1479 buffer_sprintf(w->response.data, "Chart %s has now debug %s.\r\n", tok, st->debug?"enabled":"disabled");
1480 debug(D_WEB_CLIENT_ACCESS, "%llu: debug for %s is %s.", w->id, tok, st->debug?"enabled":"disabled");
1485 buffer_flush(w->response.data);
1486 buffer_strcat(w->response.data, "debug which chart?\r\n");
1489 else if(strcmp(tok, "mirror") == 0) {
1492 debug(D_WEB_CLIENT_ACCESS, "%llu: Mirroring...", w->id);
1494 // replace the zero bytes with spaces
1495 buffer_char_replace(w->response.data, '\0', ' ');
1497 // just leave the buffer as is
1498 // it will be copied back to the client
1500 #endif /* NETDATA_INTERNAL_CHECKS */
1502 char filename[FILENAME_MAX+1];
1504 strncpyz(filename, w->last_url, FILENAME_MAX);
1505 tok = mystrsep(&url, "?");
1506 buffer_flush(w->response.data);
1507 code = mysendfile(w, (tok && *tok)?tok:"/");
1511 char filename[FILENAME_MAX+1];
1513 strncpyz(filename, w->last_url, FILENAME_MAX);
1514 tok = mystrsep(&url, "?");
1515 buffer_flush(w->response.data);
1516 code = mysendfile(w, (tok && *tok)?tok:"/");
1521 gettimeofday(&w->tv_ready, NULL);
1522 w->response.data->date = time(NULL);
1523 w->response.sent = 0;
1524 w->response.code = code;
1526 // prepare the HTTP response header
1527 debug(D_WEB_CLIENT, "%llu: Generating HTTP header with response %d.", w->id, code);
1529 char *content_type_string;
1530 switch(w->response.data->contenttype) {
1532 content_type_string = "text/html; charset=utf-8";
1535 case CT_APPLICATION_XML:
1536 content_type_string = "application/xml; charset=utf-8";
1539 case CT_APPLICATION_JSON:
1540 content_type_string = "application/json; charset=utf-8";
1543 case CT_APPLICATION_X_JAVASCRIPT:
1544 content_type_string = "application/x-javascript; charset=utf-8";
1548 content_type_string = "text/css; charset=utf-8";
1552 content_type_string = "text/xml; charset=utf-8";
1556 content_type_string = "text/xsl; charset=utf-8";
1559 case CT_APPLICATION_OCTET_STREAM:
1560 content_type_string = "application/octet-stream";
1563 case CT_IMAGE_SVG_XML:
1564 content_type_string = "image/svg+xml";
1567 case CT_APPLICATION_X_FONT_TRUETYPE:
1568 content_type_string = "application/x-font-truetype";
1571 case CT_APPLICATION_X_FONT_OPENTYPE:
1572 content_type_string = "application/x-font-opentype";
1575 case CT_APPLICATION_FONT_WOFF:
1576 content_type_string = "application/font-woff";
1579 case CT_APPLICATION_FONT_WOFF2:
1580 content_type_string = "application/font-woff2";
1583 case CT_APPLICATION_VND_MS_FONTOBJ:
1584 content_type_string = "application/vnd.ms-fontobject";
1588 content_type_string = "image/png";
1592 content_type_string = "image/jpeg";
1596 content_type_string = "image/gif";
1599 case CT_IMAGE_XICON:
1600 content_type_string = "image/x-icon";
1604 content_type_string = "image/bmp";
1608 content_type_string = "image/icns";
1613 content_type_string = "text/plain; charset=utf-8";
1624 code_msg = "Temporary Redirect";
1628 code_msg = "Bad Request";
1632 code_msg = "Forbidden";
1636 code_msg = "Not Found";
1640 code_msg = "Preconditions Failed";
1644 code_msg = "Internal Server Error";
1649 struct tm tmbuf, *tm = gmtime_r(&w->response.data->date, &tmbuf);
1650 strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %Z", tm);
1652 buffer_sprintf(w->response.header_output,
1653 "HTTP/1.1 %d %s\r\n"
1654 "Connection: %s\r\n"
1655 "Server: NetData Embedded HTTP Server\r\n"
1656 "Access-Control-Allow-Origin: %s\r\n"
1657 "Access-Control-Allow-Credentials: true\r\n"
1658 "Content-Type: %s\r\n"
1661 , w->keepalive?"keep-alive":"close"
1663 , content_type_string
1668 buffer_sprintf(w->response.header_output,
1669 "Set-Cookie: %s\r\n",
1674 buffer_sprintf(w->response.header_output,
1675 "Set-Cookie: %s\r\n",
1679 if(w->mode == WEB_CLIENT_MODE_OPTIONS) {
1680 buffer_strcat(w->response.header_output,
1681 "Access-Control-Allow-Methods: GET, OPTIONS\r\n"
1682 "Access-Control-Allow-Headers: accept, x-requested-with, origin, content-type, cookie\r\n"
1683 "Access-Control-Max-Age: 1209600\r\n" // 86400 * 14
1687 if(buffer_strlen(w->response.header))
1688 buffer_strcat(w->response.header_output, buffer_tostring(w->response.header));
1690 if(w->mode == WEB_CLIENT_MODE_NORMAL && (w->response.data->options & WB_CONTENT_NO_CACHEABLE)) {
1691 buffer_sprintf(w->response.header_output,
1693 "Cache-Control: no-cache\r\n"
1696 else if(w->mode != WEB_CLIENT_MODE_OPTIONS) {
1698 time_t et = w->response.data->date + (86400 * 14);
1699 struct tm etmbuf, *etm = gmtime_r(&et, &etmbuf);
1700 strftime(edate, sizeof(edate), "%a, %d %b %Y %H:%M:%S %Z", etm);
1702 buffer_sprintf(w->response.header_output,
1704 "Cache-Control: public\r\n"
1708 // if we know the content length, put it
1709 if(!w->response.zoutput && (w->response.data->len || w->response.rlen))
1710 buffer_sprintf(w->response.header_output,
1711 "Content-Length: %ld\r\n"
1712 , w->response.data->len? w->response.data->len: w->response.rlen
1714 else if(!w->response.zoutput)
1715 w->keepalive = 0; // content-length is required for keep-alive
1717 if(w->response.zoutput) {
1718 buffer_strcat(w->response.header_output,
1719 "Content-Encoding: gzip\r\n"
1720 "Transfer-Encoding: chunked\r\n"
1724 buffer_strcat(w->response.header_output, "\r\n");
1726 // disable TCP_NODELAY, to buffer the header
1728 if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0)
1729 error("%llu: failed to disable TCP_NODELAY on socket.", w->id);
1731 // sent the HTTP header
1732 debug(D_WEB_DATA, "%llu: Sending response HTTP header of size %d: '%s'"
1734 , buffer_strlen(w->response.header_output)
1735 , buffer_tostring(w->response.header_output)
1738 bytes = send(w->ofd, buffer_tostring(w->response.header_output), buffer_strlen(w->response.header_output), 0);
1739 if(bytes != (ssize_t) buffer_strlen(w->response.header_output))
1740 error("%llu: HTTP Header failed to be sent (I sent %d bytes but the system sent %d bytes)."
1742 , buffer_strlen(w->response.header_output)
1745 w->stats_sent_bytes += bytes;
1747 // enable TCP_NODELAY, to send all data immediately at the next send()
1749 if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0) error("%llu: failed to enable TCP_NODELAY on socket.", w->id);
1751 // enable sending immediately if we have data
1752 if(w->response.data->len) w->wait_send = 1;
1753 else w->wait_send = 0;
1757 case WEB_CLIENT_MODE_OPTIONS:
1758 debug(D_WEB_CLIENT, "%llu: Done preparing the OPTIONS response. Sending data (%d bytes) to client.", w->id, w->response.data->len);
1761 case WEB_CLIENT_MODE_NORMAL:
1762 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Sending data (%d bytes) to client.", w->id, w->response.data->len);
1765 case WEB_CLIENT_MODE_FILECOPY:
1766 if(w->response.rlen) {
1767 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending data file of %d bytes to client.", w->id, w->response.rlen);
1768 w->wait_receive = 1;
1771 // utilize the kernel sendfile() for copying the file to the socket.
1772 // this block of code can be commented, without anything missing.
1773 // when it is commented, the program will copy the data using async I/O.
1775 long len = sendfile(w->ofd, w->ifd, NULL, w->response.data->rbytes);
1776 if(len != w->response.data->rbytes) error("%llu: sendfile() should copy %ld bytes, but copied %ld. Falling back to manual copy.", w->id, w->response.data->rbytes, len);
1777 else web_client_reset(w);
1782 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending an unknown amount of bytes to client.", w->id);
1786 fatal("%llu: Unknown client mode %d.", w->id, w->mode);
1791 long web_client_send_chunk_header(struct web_client *w, long len)
1793 debug(D_DEFLATE, "%llu: OPEN CHUNK of %d bytes (hex: %x).", w->id, len, len);
1795 sprintf(buf, "%lX\r\n", len);
1796 ssize_t bytes = send(w->ofd, buf, strlen(buf), MSG_DONTWAIT);
1798 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk header %d bytes.", w->id, bytes);
1799 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk header to the client.", w->id);
1800 else debug(D_DEFLATE, "%llu: Failed to send chunk header to client.", w->id);
1805 long web_client_send_chunk_close(struct web_client *w)
1807 //debug(D_DEFLATE, "%llu: CLOSE CHUNK.", w->id);
1809 ssize_t bytes = send(w->ofd, "\r\n", 2, MSG_DONTWAIT);
1811 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
1812 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
1813 else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client.", w->id);
1818 long web_client_send_chunk_finalize(struct web_client *w)
1820 //debug(D_DEFLATE, "%llu: FINALIZE CHUNK.", w->id);
1822 ssize_t bytes = send(w->ofd, "\r\n0\r\n\r\n", 7, MSG_DONTWAIT);
1824 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
1825 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
1826 else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client.", w->id);
1831 #ifdef NETDATA_WITH_ZLIB
1832 long web_client_send_deflate(struct web_client *w)
1834 long len = 0, t = 0;
1836 // when using compression,
1837 // w->response.sent is the amount of bytes passed through compression
1839 debug(D_DEFLATE, "%llu: web_client_send_deflate(): w->response.data->len = %d, w->response.sent = %d, w->response.zhave = %d, w->response.zsent = %d, w->response.zstream.avail_in = %d, w->response.zstream.avail_out = %d, w->response.zstream.total_in = %d, w->response.zstream.total_out = %d.", 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);
1841 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) {
1842 // there is nothing to send
1844 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1846 // finalize the chunk
1847 if(w->response.sent != 0)
1848 t += web_client_send_chunk_finalize(w);
1850 // there can be two cases for this
1851 // A. we have done everything
1852 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
1854 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->response.rlen && w->response.rlen > w->response.data->len) {
1855 // we have to wait, more data will come
1856 debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1861 if(w->keepalive == 0) {
1862 debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->response.sent);
1868 web_client_reset(w);
1869 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1873 if(w->response.zhave == w->response.zsent) {
1874 // compress more input data
1876 // close the previous open chunk
1877 if(w->response.sent != 0) t += web_client_send_chunk_close(w);
1879 debug(D_DEFLATE, "%llu: Compressing %d new bytes starting from %d (and %d left behind).", w->id, (w->response.data->len - w->response.sent), w->response.sent, w->response.zstream.avail_in);
1881 // give the compressor all the data not passed through the compressor yet
1882 if(w->response.data->len > w->response.sent) {
1883 #ifdef NETDATA_INTERNAL_CHECKS
1884 if((long)w->response.sent - (long)w->response.zstream.avail_in < 0)
1885 error("internal error: avail_in is corrupted.");
1887 w->response.zstream.next_in = (Bytef *)&w->response.data->buffer[w->response.sent - w->response.zstream.avail_in];
1888 w->response.zstream.avail_in += (uInt) (w->response.data->len - w->response.sent);
1891 // reset the compressor output buffer
1892 w->response.zstream.next_out = w->response.zbuffer;
1893 w->response.zstream.avail_out = ZLIB_CHUNK;
1895 // ask for FINISH if we have all the input
1896 int flush = Z_SYNC_FLUSH;
1897 if(w->mode == WEB_CLIENT_MODE_NORMAL
1898 || (w->mode == WEB_CLIENT_MODE_FILECOPY && !w->wait_receive && w->response.data->len == w->response.rlen)) {
1900 debug(D_DEFLATE, "%llu: Requesting Z_FINISH, if possible.", w->id);
1903 debug(D_DEFLATE, "%llu: Requesting Z_SYNC_FLUSH.", w->id);
1907 if(deflate(&w->response.zstream, flush) == Z_STREAM_ERROR) {
1908 error("%llu: Compression failed. Closing down client.", w->id);
1909 web_client_reset(w);
1913 w->response.zhave = ZLIB_CHUNK - w->response.zstream.avail_out;
1914 w->response.zsent = 0;
1916 // keep track of the bytes passed through the compressor
1917 w->response.sent = w->response.data->len;
1919 debug(D_DEFLATE, "%llu: Compression produced %d bytes.", w->id, w->response.zhave);
1922 t += web_client_send_chunk_header(w, w->response.zhave);
1925 debug(D_WEB_CLIENT, "%llu: Sending %d bytes of data (+%d of chunk header).", w->id, w->response.zhave - w->response.zsent, t);
1927 len = send(w->ofd, &w->response.zbuffer[w->response.zsent], (size_t) (w->response.zhave - w->response.zsent), MSG_DONTWAIT);
1929 w->response.zsent += len;
1931 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, len);
1933 else if(len == 0) debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client (zhave = %ld, zsent = %ld, need to send = %ld).", w->id, w->response.zhave, w->response.zsent, w->response.zhave - w->response.zsent);
1934 else debug(D_WEB_CLIENT, "%llu: Failed to send data to client. Reason: %s", w->id, strerror(errno));
1938 #endif // NETDATA_WITH_ZLIB
1940 long web_client_send(struct web_client *w)
1942 #ifdef NETDATA_WITH_ZLIB
1943 if(likely(w->response.zoutput)) return web_client_send_deflate(w);
1944 #endif // NETDATA_WITH_ZLIB
1948 if(unlikely(w->response.data->len - w->response.sent == 0)) {
1949 // there is nothing to send
1951 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1953 // there can be two cases for this
1954 // A. we have done everything
1955 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
1957 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->response.rlen && w->response.rlen > w->response.data->len) {
1958 // we have to wait, more data will come
1959 debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1964 if(unlikely(w->keepalive == 0)) {
1965 debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->response.sent);
1970 web_client_reset(w);
1971 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1975 bytes = send(w->ofd, &w->response.data->buffer[w->response.sent], w->response.data->len - w->response.sent, MSG_DONTWAIT);
1976 if(likely(bytes > 0)) {
1977 w->response.sent += bytes;
1978 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, bytes);
1980 else if(likely(bytes == 0)) debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client.", w->id);
1981 else debug(D_WEB_CLIENT, "%llu: Failed to send data to client.", w->id);
1986 long web_client_receive(struct web_client *w)
1988 // do we have any space for more data?
1989 buffer_need_bytes(w->response.data, WEB_REQUEST_LENGTH);
1991 long left = w->response.data->size - w->response.data->len;
1994 if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY))
1995 bytes = read(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1));
1997 bytes = recv(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1), MSG_DONTWAIT);
1999 if(likely(bytes > 0)) {
2000 size_t old = w->response.data->len;
2001 w->response.data->len += bytes;
2002 w->response.data->buffer[w->response.data->len] = '\0';
2004 debug(D_WEB_CLIENT, "%llu: Received %d bytes.", w->id, bytes);
2005 debug(D_WEB_DATA, "%llu: Received data: '%s'.", w->id, &w->response.data->buffer[old]);
2007 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
2009 if(w->response.rlen && w->response.data->len >= w->response.rlen) w->wait_receive = 0;
2012 else if(likely(bytes == 0)) {
2013 debug(D_WEB_CLIENT, "%llu: Out of input data.", w->id);
2015 // if we cannot read, it means we have an error on input.
2016 // if however, we are copying a file from ifd to ofd, we should not return an error.
2017 // in this case, the error should be generated when the file has been sent to the client.
2019 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
2020 // we are copying data from ifd to ofd
2021 // let it finish copying...
2022 w->wait_receive = 0;
2023 debug(D_WEB_CLIENT, "%llu: Disabling input.", w->id);
2035 // --------------------------------------------------------------------------------------
2036 // the thread of a single client
2038 // 1. waits for input and output, using async I/O
2039 // 2. it processes HTTP requests
2040 // 3. it generates HTTP responses
2041 // 4. it copies data from input to output if mode is FILECOPY
2043 void *web_client_main(void *ptr)
2045 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
2046 error("Cannot set pthread cancel type to DEFERRED.");
2048 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
2049 error("Cannot set pthread cancel state to ENABLE.");
2052 struct web_client *w = ptr;
2054 fd_set ifds, ofds, efds;
2057 log_access("%llu: %s port %s connected on thread task id %d", w->id, w->client_ip, w->client_port, gettid());
2064 FD_SET(w->ifd, &efds);
2066 if(w->ifd != w->ofd)
2067 FD_SET(w->ofd, &efds);
2069 if (w->wait_receive) {
2070 FD_SET(w->ifd, &ifds);
2071 if(w->ifd > fdmax) fdmax = w->ifd;
2075 FD_SET(w->ofd, &ofds);
2076 if(w->ofd > fdmax) fdmax = w->ofd;
2079 tv.tv_sec = web_client_timeout;
2082 debug(D_WEB_CLIENT, "%llu: Waiting socket async I/O for %s %s", w->id, w->wait_receive?"INPUT":"", w->wait_send?"OUTPUT":"");
2083 retval = select(fdmax+1, &ifds, &ofds, &efds, &tv);
2086 debug(D_WEB_CLIENT_ACCESS, "%llu: LISTENER: select() failed.", w->id);
2091 debug(D_WEB_CLIENT_ACCESS, "%llu: LISTENER: timeout.", w->id);
2095 if(FD_ISSET(w->ifd, &efds)) {
2096 debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on input socket.", w->id);
2100 if(FD_ISSET(w->ofd, &efds)) {
2101 debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on output socket.", w->id);
2105 if(w->wait_send && FD_ISSET(w->ofd, &ofds)) {
2107 if((bytes = web_client_send(w)) < 0) {
2108 debug(D_WEB_CLIENT, "%llu: Cannot send data to client. Closing client.", w->id);
2113 w->stats_sent_bytes += bytes;
2116 if(w->wait_receive && FD_ISSET(w->ifd, &ifds)) {
2118 if((bytes = web_client_receive(w)) < 0) {
2119 debug(D_WEB_CLIENT, "%llu: Cannot receive data from client. Closing client.", w->id);
2124 w->stats_received_bytes += bytes;
2126 if(w->mode == WEB_CLIENT_MODE_NORMAL) {
2127 debug(D_WEB_CLIENT, "%llu: Attempting to process received data (%ld bytes).", w->id, bytes);
2128 // info("%llu: Attempting to process received data (%ld bytes).", w->id, bytes);
2129 web_client_process(w);
2135 log_access("%llu: %s port %s disconnected from thread task id %d", w->id, w->client_ip, w->client_port, gettid());
2136 debug(D_WEB_CLIENT, "%llu: done...", w->id);
2138 web_client_reset(w);