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 strncpy(w->client_ip, "UNKNOWN", NI_MAXHOST);
77 strncpy(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);
134 if(web_clients) web_clients->prev = w;
135 w->next = web_clients;
138 global_statistics.connected_clients++;
143 void web_client_reset(struct web_client *w)
146 gettimeofday(&tv, NULL);
148 long sent = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->response.rlen:w->response.data->len;
150 #ifdef NETDATA_WITH_ZLIB
151 if(likely(w->response.zoutput)) sent = (long)w->response.zstream.total_out;
154 long size = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->response.rlen:w->response.data->len;
156 if(likely(w->last_url[0]))
157 log_access("%llu: (sent/all = %ld/%ld bytes %0.0f%%, prep/sent/total = %0.2f/%0.2f/%0.2f ms) %s: %d '%s'",
159 sent, size, -((size>0)?((float)(size-sent)/(float)size * 100.0):0.0),
160 (float)usecdiff(&w->tv_ready, &w->tv_in) / 1000.0,
161 (float)usecdiff(&tv, &w->tv_ready) / 1000.0,
162 (float)usecdiff(&tv, &w->tv_in) / 1000.0,
163 (w->mode == WEB_CLIENT_MODE_FILECOPY)?"filecopy":((w->mode == WEB_CLIENT_MODE_OPTIONS)?"options":"data"),
168 debug(D_WEB_CLIENT, "%llu: Reseting client.", w->id);
170 if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY)) {
171 debug(D_WEB_CLIENT, "%llu: Closing filecopy input file.", w->id);
176 w->last_url[0] = '\0';
179 w->mode = WEB_CLIENT_MODE_NORMAL;
181 buffer_reset(w->response.header_output);
182 buffer_reset(w->response.header);
183 buffer_reset(w->response.data);
184 w->response.rlen = 0;
185 w->response.sent = 0;
186 w->response.code = 0;
191 w->response.zoutput = 0;
193 // if we had enabled compression, release it
194 #ifdef NETDATA_WITH_ZLIB
195 if(w->response.zinitialized) {
196 debug(D_DEFLATE, "%llu: Reseting compression.", w->id);
197 deflateEnd(&w->response.zstream);
198 w->response.zsent = 0;
199 w->response.zhave = 0;
200 w->response.zstream.avail_in = 0;
201 w->response.zstream.avail_out = 0;
202 w->response.zstream.total_in = 0;
203 w->response.zstream.total_out = 0;
204 w->response.zinitialized = 0;
206 #endif // NETDATA_WITH_ZLIB
209 struct web_client *web_client_free(struct web_client *w)
211 struct web_client *n = w->next;
213 debug(D_WEB_CLIENT_ACCESS, "%llu: Closing web client from %s port %s.", w->id, w->client_ip, w->client_port);
215 if(w->prev) w->prev->next = w->next;
216 if(w->next) w->next->prev = w->prev;
218 if(w == web_clients) web_clients = w->next;
220 if(w->response.header_output) buffer_free(w->response.header_output);
221 if(w->response.header) buffer_free(w->response.header);
222 if(w->response.data) buffer_free(w->response.data);
224 if(w->ofd != w->ifd) close(w->ofd);
227 global_statistics.connected_clients--;
232 uid_t web_files_uid(void)
234 static char *web_owner = NULL;
235 static uid_t owner_uid = 0;
237 if(unlikely(!web_owner)) {
238 web_owner = config_get("global", "web files owner", config_get("global", "run as user", ""));
239 if(!web_owner || !*web_owner)
240 owner_uid = geteuid();
242 // getpwnam() is not thread safe,
243 // but we have called this function once
244 // while single threaded
245 struct passwd *pw = getpwnam(web_owner);
247 error("User %s is not present. Ignoring option.", web_owner);
248 owner_uid = geteuid();
251 debug(D_WEB_CLIENT, "Web files owner set to %s.\n", web_owner);
252 owner_uid = pw->pw_uid;
260 gid_t web_files_gid(void)
262 static char *web_group = NULL;
263 static gid_t owner_gid = 0;
265 if(unlikely(!web_group)) {
266 web_group = config_get("global", "web files group", config_get("global", "web files owner", ""));
267 if(!web_group || !*web_group)
268 owner_gid = getegid();
270 // getgrnam() is not thread safe,
271 // but we have called this function once
272 // while single threaded
273 struct group *gr = getgrnam(web_group);
275 error("Group %s is not present. Ignoring option.", web_group);
276 owner_gid = getegid();
279 debug(D_WEB_CLIENT, "Web files group set to %s.\n", web_group);
280 owner_gid = gr->gr_gid;
288 int mysendfile(struct web_client *w, char *filename)
290 static char *web_dir = NULL;
292 // initialize our static data
293 if(unlikely(!web_dir)) web_dir = config_get("global", "web files directory", WEB_DIR);
295 debug(D_WEB_CLIENT, "%llu: Looking for file '%s/%s'", w->id, web_dir, filename);
297 // skip leading slashes
298 while (*filename == '/') filename++;
300 // if the filename contain known paths, skip them
301 if(strncmp(filename, WEB_PATH_FILE "/", strlen(WEB_PATH_FILE) + 1) == 0) filename = &filename[strlen(WEB_PATH_FILE) + 1];
304 for(s = filename; *s ;s++) {
305 if( !isalnum(*s) && *s != '/' && *s != '.' && *s != '-' && *s != '_') {
306 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
307 buffer_sprintf(w->response.data, "File '%s' cannot be served. Filename contains invalid character '%c'", filename, *s);
312 // if the filename contains a .. refuse to serve it
313 if(strstr(filename, "..") != 0) {
314 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
315 buffer_sprintf(w->response.data, "File '%s' cannot be served. Relative filenames with '..' in them are not supported.", filename);
320 char webfilename[FILENAME_MAX + 1];
321 snprintf(webfilename, FILENAME_MAX, "%s/%s", web_dir, filename);
323 // check if the file exists
325 if(lstat(webfilename, &stat) != 0) {
326 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not found.", w->id, webfilename);
327 buffer_sprintf(w->response.data, "File '%s' does not exist, or is not accessible.", webfilename);
331 // check if the file is owned by expected user
332 if(stat.st_uid != web_files_uid()) {
333 error("%llu: File '%s' is owned by user %d (expected user %d). Access Denied.", w->id, webfilename, stat.st_uid, web_files_uid());
334 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", webfilename);
338 // check if the file is owned by expected group
339 if(stat.st_gid != web_files_gid()) {
340 error("%llu: File '%s' is owned by group %d (expected group %d). Access Denied.", w->id, webfilename, stat.st_gid, web_files_gid());
341 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", webfilename);
345 if((stat.st_mode & S_IFMT) == S_IFDIR) {
346 snprintf(webfilename, FILENAME_MAX+1, "%s/index.html", filename);
347 return mysendfile(w, webfilename);
350 if((stat.st_mode & S_IFMT) != S_IFREG) {
351 error("%llu: File '%s' is not a regular file. Access Denied.", w->id, webfilename);
352 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", webfilename);
357 w->ifd = open(webfilename, O_NONBLOCK, O_RDONLY);
361 if(errno == EBUSY || errno == EAGAIN) {
362 error("%llu: File '%s' is busy, sending 307 Moved Temporarily to force retry.", w->id, webfilename);
363 buffer_sprintf(w->response.header, "Location: /" WEB_PATH_FILE "/%s\r\n", filename);
364 buffer_sprintf(w->response.data, "The file '%s' is currently busy. Please try again later.", webfilename);
368 error("%llu: Cannot open file '%s'.", w->id, webfilename);
369 buffer_sprintf(w->response.data, "Cannot open file '%s'.", webfilename);
374 // pick a Content-Type for the file
375 if(strstr(filename, ".html") != NULL) w->response.data->contenttype = CT_TEXT_HTML;
376 else if(strstr(filename, ".js") != NULL) w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
377 else if(strstr(filename, ".css") != NULL) w->response.data->contenttype = CT_TEXT_CSS;
378 else if(strstr(filename, ".xml") != NULL) w->response.data->contenttype = CT_TEXT_XML;
379 else if(strstr(filename, ".xsl") != NULL) w->response.data->contenttype = CT_TEXT_XSL;
380 else if(strstr(filename, ".txt") != NULL) w->response.data->contenttype = CT_TEXT_PLAIN;
381 else if(strstr(filename, ".svg") != NULL) w->response.data->contenttype = CT_IMAGE_SVG_XML;
382 else if(strstr(filename, ".ttf") != NULL) w->response.data->contenttype = CT_APPLICATION_X_FONT_TRUETYPE;
383 else if(strstr(filename, ".otf") != NULL) w->response.data->contenttype = CT_APPLICATION_X_FONT_OPENTYPE;
384 else if(strstr(filename, ".woff2")!= NULL) w->response.data->contenttype = CT_APPLICATION_FONT_WOFF2;
385 else if(strstr(filename, ".woff") != NULL) w->response.data->contenttype = CT_APPLICATION_FONT_WOFF;
386 else if(strstr(filename, ".eot") != NULL) w->response.data->contenttype = CT_APPLICATION_VND_MS_FONTOBJ;
387 else if(strstr(filename, ".png") != NULL) w->response.data->contenttype = CT_IMAGE_PNG;
388 else if(strstr(filename, ".jpg") != NULL) w->response.data->contenttype = CT_IMAGE_JPG;
389 else if(strstr(filename, ".jpeg") != NULL) w->response.data->contenttype = CT_IMAGE_JPG;
390 else if(strstr(filename, ".gif") != NULL) w->response.data->contenttype = CT_IMAGE_GIF;
391 else if(strstr(filename, ".bmp") != NULL) w->response.data->contenttype = CT_IMAGE_BMP;
392 else if(strstr(filename, ".ico") != NULL) w->response.data->contenttype = CT_IMAGE_XICON;
393 else if(strstr(filename, ".icns") != NULL) w->response.data->contenttype = CT_IMAGE_ICNS;
394 else w->response.data->contenttype = CT_APPLICATION_OCTET_STREAM;
396 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);
398 w->mode = WEB_CLIENT_MODE_FILECOPY;
401 buffer_flush(w->response.data);
402 w->response.rlen = stat.st_size;
403 w->response.data->date = stat.st_mtim.tv_sec;
409 #ifdef NETDATA_WITH_ZLIB
410 void web_client_enable_deflate(struct web_client *w) {
411 if(w->response.zinitialized == 1) {
412 error("%llu: Compression has already be initialized for this client.", w->id);
416 if(w->response.sent) {
417 error("%llu: Cannot enable compression in the middle of a conversation.", w->id);
421 w->response.zstream.zalloc = Z_NULL;
422 w->response.zstream.zfree = Z_NULL;
423 w->response.zstream.opaque = Z_NULL;
425 w->response.zstream.next_in = (Bytef *)w->response.data->buffer;
426 w->response.zstream.avail_in = 0;
427 w->response.zstream.total_in = 0;
429 w->response.zstream.next_out = w->response.zbuffer;
430 w->response.zstream.avail_out = 0;
431 w->response.zstream.total_out = 0;
433 w->response.zstream.zalloc = Z_NULL;
434 w->response.zstream.zfree = Z_NULL;
435 w->response.zstream.opaque = Z_NULL;
437 // if(deflateInit(&w->response.zstream, Z_DEFAULT_COMPRESSION) != Z_OK) {
438 // error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
442 // Select GZIP compression: windowbits = 15 + 16 = 31
443 if(deflateInit2(&w->response.zstream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY) != Z_OK) {
444 error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
448 w->response.zsent = 0;
449 w->response.zoutput = 1;
450 w->response.zinitialized = 1;
452 debug(D_DEFLATE, "%llu: Initialized compression.", w->id);
454 #endif // NETDATA_WITH_ZLIB
456 uint32_t web_client_api_request_v1_data_options(char *o)
458 uint32_t ret = 0x00000000;
461 while(o && *o && (tok = mystrsep(&o, ", |"))) {
464 if(!strcmp(tok, "nonzero"))
465 ret |= RRDR_OPTION_NONZERO;
466 else if(!strcmp(tok, "flip") || !strcmp(tok, "reversed") || !strcmp(tok, "reverse"))
467 ret |= RRDR_OPTION_REVERSED;
468 else if(!strcmp(tok, "jsonwrap"))
469 ret |= RRDR_OPTION_JSON_WRAP;
470 else if(!strcmp(tok, "min2max"))
471 ret |= RRDR_OPTION_MIN2MAX;
472 else if(!strcmp(tok, "ms") || !strcmp(tok, "milliseconds"))
473 ret |= RRDR_OPTION_MILLISECONDS;
474 else if(!strcmp(tok, "abs") || !strcmp(tok, "absolute") || !strcmp(tok, "absolute_sum") || !strcmp(tok, "absolute-sum"))
475 ret |= RRDR_OPTION_ABSOLUTE;
476 else if(!strcmp(tok, "seconds"))
477 ret |= RRDR_OPTION_SECONDS;
478 else if(!strcmp(tok, "null2zero"))
479 ret |= RRDR_OPTION_NULL2ZERO;
480 else if(!strcmp(tok, "objectrows"))
481 ret |= RRDR_OPTION_OBJECTSROWS;
482 else if(!strcmp(tok, "google_json"))
483 ret |= RRDR_OPTION_GOOGLE_JSON;
484 else if(!strcmp(tok, "percentage"))
485 ret |= RRDR_OPTION_PERCENTAGE;
491 uint32_t web_client_api_request_v1_data_format(char *name)
493 if(!strcmp(name, DATASOURCE_FORMAT_DATATABLE_JSON)) // datatable
494 return DATASOURCE_DATATABLE_JSON;
496 else if(!strcmp(name, DATASOURCE_FORMAT_DATATABLE_JSONP)) // datasource
497 return DATASOURCE_DATATABLE_JSONP;
499 else if(!strcmp(name, DATASOURCE_FORMAT_JSON)) // json
500 return DATASOURCE_JSON;
502 else if(!strcmp(name, DATASOURCE_FORMAT_JSONP)) // jsonp
503 return DATASOURCE_JSONP;
505 else if(!strcmp(name, DATASOURCE_FORMAT_SSV)) // ssv
506 return DATASOURCE_SSV;
508 else if(!strcmp(name, DATASOURCE_FORMAT_CSV)) // csv
509 return DATASOURCE_CSV;
511 else if(!strcmp(name, DATASOURCE_FORMAT_TSV) || !strcmp(name, "tsv-excel")) // tsv
512 return DATASOURCE_TSV;
514 else if(!strcmp(name, DATASOURCE_FORMAT_HTML)) // html
515 return DATASOURCE_HTML;
517 else if(!strcmp(name, DATASOURCE_FORMAT_JS_ARRAY)) // array
518 return DATASOURCE_JS_ARRAY;
520 else if(!strcmp(name, DATASOURCE_FORMAT_SSV_COMMA)) // ssvcomma
521 return DATASOURCE_SSV_COMMA;
523 else if(!strcmp(name, DATASOURCE_FORMAT_CSV_JSON_ARRAY)) // csvjsonarray
524 return DATASOURCE_CSV_JSON_ARRAY;
526 return DATASOURCE_JSON;
529 uint32_t web_client_api_request_v1_data_google_format(char *name)
531 if(!strcmp(name, "json"))
532 return DATASOURCE_DATATABLE_JSONP;
534 else if(!strcmp(name, "html"))
535 return DATASOURCE_HTML;
537 else if(!strcmp(name, "csv"))
538 return DATASOURCE_CSV;
540 else if(!strcmp(name, "tsv-excel"))
541 return DATASOURCE_TSV;
543 return DATASOURCE_JSON;
546 int web_client_api_request_v1_data_group(char *name)
548 if(!strcmp(name, "max"))
551 else if(!strcmp(name, "average"))
552 return GROUP_AVERAGE;
557 int web_client_api_request_v1_charts(struct web_client *w, char *url)
561 buffer_flush(w->response.data);
562 w->response.data->contenttype = CT_APPLICATION_JSON;
563 rrd_stats_api_v1_charts(w->response.data);
567 int web_client_api_request_v1_chart(struct web_client *w, char *url)
572 buffer_flush(w->response.data);
575 char *value = mystrsep(&url, "?&[]");
576 if(!value || !*value) continue;
578 char *name = mystrsep(&value, "=");
579 if(!name || !*name) continue;
580 if(!value || !*value) continue;
582 // name and value are now the parameters
583 // they are not null and not empty
585 if(!strcmp(name, "chart")) chart = value;
587 /// buffer_sprintf(w->response.data, "Unknown parameter '%s' in request.", name);
592 if(!chart || !*chart) {
593 buffer_sprintf(w->response.data, "No chart id is given at the request.");
597 RRDSET *st = rrdset_find(chart);
598 if(!st) st = rrdset_find_byname(chart);
600 buffer_sprintf(w->response.data, "Chart '%s' is not found.", chart);
605 w->response.data->contenttype = CT_APPLICATION_JSON;
606 rrd_stats_api_v1_chart(st, w->response.data);
613 // returns the HTTP code
614 int web_client_api_request_v1_data(struct web_client *w, char *url)
616 debug(D_WEB_CLIENT, "%llu: API v1 data with URL '%s'", w->id, url);
619 BUFFER *dimensions = NULL;
621 buffer_flush(w->response.data);
623 char *google_version = "0.6",
626 *google_out = "json",
627 *responseHandler = NULL,
630 time_t last_timestamp_in_data = 0, google_timestamp = 0;
635 , *points_str = NULL;
637 int group = GROUP_MAX;
638 uint32_t format = DATASOURCE_JSON;
639 uint32_t options = 0x00000000;
642 char *value = mystrsep(&url, "?&[]");
643 if(!value || !*value) continue;
645 char *name = mystrsep(&value, "=");
646 if(!name || !*name) continue;
647 if(!value || !*value) continue;
649 debug(D_WEB_CLIENT, "%llu: API v1 data query param '%s' with value '%s'", w->id, name, value);
651 // name and value are now the parameters
652 // they are not null and not empty
654 if(!strcmp(name, "chart")) chart = value;
655 else if(!strcmp(name, "dimension") || !strcmp(name, "dim") || !strcmp(name, "dimensions") || !strcmp(name, "dims")) {
656 if(!dimensions) dimensions = buffer_create(strlen(value));
658 buffer_strcat(dimensions, "|");
659 buffer_strcat(dimensions, value);
662 else if(!strcmp(name, "after")) after_str = value;
663 else if(!strcmp(name, "before")) before_str = value;
664 else if(!strcmp(name, "points")) points_str = value;
665 else if(!strcmp(name, "group")) {
666 group = web_client_api_request_v1_data_group(value);
668 else if(!strcmp(name, "format")) {
669 format = web_client_api_request_v1_data_format(value);
671 else if(!strcmp(name, "options")) {
672 options |= web_client_api_request_v1_data_options(value);
674 else if(!strcmp(name, "callback")) {
675 responseHandler = value;
677 else if(!strcmp(name, "filename")) {
680 else if(!strcmp(name, "tqx")) {
681 // parse Google Visualization API options
682 // https://developers.google.com/chart/interactive/docs/dev/implementing_data_source
683 char *tqx_name, *tqx_value;
686 tqx_value = mystrsep(&value, ";");
687 if(!tqx_value || !*tqx_value) continue;
689 tqx_name = mystrsep(&tqx_value, ":");
690 if(!tqx_name || !*tqx_name) continue;
691 if(!tqx_value || !*tqx_value) continue;
693 if(!strcmp(tqx_name, "version"))
694 google_version = tqx_value;
695 else if(!strcmp(tqx_name, "reqId"))
696 google_reqId = tqx_value;
697 else if(!strcmp(tqx_name, "sig")) {
698 google_sig = tqx_value;
699 google_timestamp = strtoul(google_sig, NULL, 0);
701 else if(!strcmp(tqx_name, "out")) {
702 google_out = tqx_value;
703 format = web_client_api_request_v1_data_google_format(google_out);
705 else if(!strcmp(tqx_name, "responseHandler"))
706 responseHandler = tqx_value;
707 else if(!strcmp(tqx_name, "outFileName"))
708 outFileName = tqx_value;
713 if(!chart || !*chart) {
714 buffer_sprintf(w->response.data, "No chart id is given at the request.");
718 RRDSET *st = rrdset_find(chart);
719 if(!st) st = rrdset_find_byname(chart);
721 buffer_sprintf(w->response.data, "Chart '%s' is not found.", chart);
726 long long before = (before_str && *before_str)?atol(before_str):0;
727 long long after = (after_str && *after_str) ?atol(after_str):0;
728 int points = (points_str && *points_str)?atoi(points_str):0;
730 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'"
733 , (dimensions)?buffer_tostring(dimensions):""
742 if(outFileName && *outFileName) {
743 buffer_sprintf(w->response.header, "Content-Disposition: attachment; filename=\"%s\"\r\n", outFileName);
744 error("generating outfilename header: '%s'", outFileName);
747 if(format == DATASOURCE_DATATABLE_JSONP) {
748 if(responseHandler == NULL)
749 responseHandler = "google.visualization.Query.setResponse";
751 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSON/JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
752 w->id, google_version, google_reqId, google_sig, google_out, responseHandler, outFileName
755 buffer_sprintf(w->response.data,
756 "%s({version:'%s',reqId:'%s',status:'ok',sig:'%lu',table:",
757 responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
759 else if(format == DATASOURCE_JSONP) {
760 if(responseHandler == NULL)
761 responseHandler = "callback";
763 buffer_strcat(w->response.data, responseHandler);
764 buffer_strcat(w->response.data, "(");
767 ret = rrd2format(st, w->response.data, dimensions, format, points, after, before, group, options, &last_timestamp_in_data);
769 if(format == DATASOURCE_DATATABLE_JSONP) {
770 if(google_timestamp < last_timestamp_in_data)
771 buffer_strcat(w->response.data, "});");
774 // the client already has the latest data
775 buffer_flush(w->response.data);
776 buffer_sprintf(w->response.data,
777 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
778 responseHandler, google_version, google_reqId);
781 else if(format == DATASOURCE_JSONP)
782 buffer_strcat(w->response.data, ");");
785 if(dimensions) buffer_free(dimensions);
789 int web_client_api_request_v1_registry(struct web_client *w, char *url)
791 char person_guid[36 + 1] = "";
793 debug(D_WEB_CLIENT, "%llu: API v1 registry with URL '%s'", w->id, url);
795 char *cookie = strstr(w->response.data->buffer, " " NETDATA_REGISTRY_COOKIE_NAME "=");
797 strncpy(person_guid, &cookie[sizeof(NETDATA_REGISTRY_COOKIE_NAME) + 2], 36);
798 person_guid[36] = '\0';
802 char *machine_guid = NULL,
805 *search_machine_guid = NULL,
809 char *value = mystrsep(&url, "?&[]");
810 if (!value || !*value) continue;
812 char *name = mystrsep(&value, "=");
813 if (!name || !*name) continue;
814 if (!value || !*value) continue;
816 debug(D_WEB_CLIENT, "%llu: API v1 registry query param '%s' with value '%s'", w->id, name, value);
818 if(!strcmp(name, "action")) {
819 if(!strcmp(value, "access")) action = 'A';
820 else if(!strcmp(value, "delete")) action = 'D';
821 else if(!strcmp(value, "search")) action = 'S';
823 else if(!strcmp(name, "machine"))
824 machine_guid = value;
826 else if(!strcmp(name, "url"))
829 else if(action == 'A') {
830 if(!strcmp(name, "name"))
833 else if(action == 'D') {
834 if(!strcmp(name, "delete_url"))
837 else if(action == 'S') {
838 if(!strcmp(name, "for"))
839 search_machine_guid = value;
843 if((!action || !machine_guid || !machine_url) || (action == 'A' && !url_name) || (action == 'D' && !delete_url) || (action == 'S' && !search_machine_guid)) {
844 buffer_flush(w->response.data);
845 buffer_sprintf(w->response.data, "Invalid registry request - required parameters missing.");
851 return registry_request_access_json(w, person_guid, machine_guid, machine_url, url_name, time(NULL));
854 return registry_request_delete_json(w, person_guid, machine_guid, machine_url, delete_url, time(NULL));
857 return registry_request_search_json(w, person_guid, machine_guid, machine_url, search_machine_guid, time(NULL));
860 buffer_flush(w->response.data);
861 buffer_sprintf(w->response.data, "Invalid or no registry action.");
865 int web_client_api_request_v1(struct web_client *w, char *url)
867 static uint32_t data_hash = 0, chart_hash = 0, charts_hash = 0, registry_hash = 0;
869 if(unlikely(data_hash == 0)) {
870 data_hash = simple_hash("data");
871 chart_hash = simple_hash("chart");
872 charts_hash = simple_hash("charts");
873 registry_hash = simple_hash("registry");
877 char *tok = mystrsep(&url, "/?&");
879 debug(D_WEB_CLIENT, "%llu: Searching for API v1 command '%s'.", w->id, tok);
880 uint32_t hash = simple_hash(tok);
882 if(hash == data_hash && !strcmp(tok, "data"))
883 return web_client_api_request_v1_data(w, url);
885 else if(hash == chart_hash && !strcmp(tok, "chart"))
886 return web_client_api_request_v1_chart(w, url);
888 else if(hash == charts_hash && !strcmp(tok, "charts"))
889 return web_client_api_request_v1_charts(w, url);
891 else if(hash == registry_hash && !strcmp(tok, "registry"))
892 return web_client_api_request_v1_registry(w, url);
895 buffer_flush(w->response.data);
896 buffer_sprintf(w->response.data, "Unsupported v1 API command: %s", tok);
901 buffer_flush(w->response.data);
902 buffer_sprintf(w->response.data, "API v1 command?");
907 int web_client_api_request(struct web_client *w, char *url)
909 // get the api version
910 char *tok = mystrsep(&url, "/?&");
912 debug(D_WEB_CLIENT, "%llu: Searching for API version '%s'.", w->id, tok);
913 if(strcmp(tok, "v1") == 0)
914 return web_client_api_request_v1(w, url);
916 buffer_flush(w->response.data);
917 buffer_sprintf(w->response.data, "Unsupported API version: %s", tok);
922 buffer_flush(w->response.data);
923 buffer_sprintf(w->response.data, "Which API version?");
928 int web_client_data_request(struct web_client *w, char *url, int datasource_type)
932 char *args = strchr(url, '?');
938 // get the name of the data to show
939 char *tok = mystrsep(&url, "/");
941 // do we have such a data set?
943 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
944 st = rrdset_find_byname(tok);
945 if(!st) st = rrdset_find(tok);
950 // try to send a file with that name
951 buffer_flush(w->response.data);
952 return(mysendfile(w, tok));
956 debug(D_WEB_CLIENT, "%llu: Found RRD data with name '%s'.", w->id, tok);
958 // how many entries does the client want?
959 long lines = rrd_default_history_entries;
960 long group_count = 1;
961 time_t after = 0, before = 0;
962 int group_method = GROUP_AVERAGE;
966 // parse the lines required
967 tok = mystrsep(&url, "/");
968 if(tok) lines = atoi(tok);
969 if(lines < 1) lines = 1;
972 // parse the group count required
973 tok = mystrsep(&url, "/");
974 if(tok && *tok) group_count = atoi(tok);
975 if(group_count < 1) group_count = 1;
976 //if(group_count > save_history / 20) group_count = save_history / 20;
979 // parse the grouping method required
980 tok = mystrsep(&url, "/");
982 if(strcmp(tok, "max") == 0) group_method = GROUP_MAX;
983 else if(strcmp(tok, "average") == 0) group_method = GROUP_AVERAGE;
984 else if(strcmp(tok, "sum") == 0) group_method = GROUP_SUM;
985 else debug(D_WEB_CLIENT, "%llu: Unknown group method '%s'", w->id, tok);
990 tok = mystrsep(&url, "/");
991 if(tok && *tok) after = strtoul(tok, NULL, 10);
992 if(after < 0) after = 0;
996 tok = mystrsep(&url, "/");
997 if(tok && *tok) before = strtoul(tok, NULL, 10);
998 if(before < 0) before = 0;
1002 tok = mystrsep(&url, "/");
1003 if(tok && *tok && strcmp(tok, "nonzero") == 0) nonzero = 1;
1006 w->response.data->contenttype = CT_APPLICATION_JSON;
1007 buffer_flush(w->response.data);
1009 char *google_version = "0.6";
1010 char *google_reqId = "0";
1011 char *google_sig = "0";
1012 char *google_out = "json";
1013 char *google_responseHandler = "google.visualization.Query.setResponse";
1014 char *google_outFileName = NULL;
1015 time_t last_timestamp_in_data = 0;
1016 if(datasource_type == DATASOURCE_DATATABLE_JSON || datasource_type == DATASOURCE_DATATABLE_JSONP) {
1018 w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
1021 tok = mystrsep(&args, "&");
1023 char *name = mystrsep(&tok, "=");
1024 if(name && *name && strcmp(name, "tqx") == 0) {
1025 char *key = mystrsep(&tok, ":");
1026 char *value = mystrsep(&tok, ";");
1027 if(key && value && *key && *value) {
1028 if(strcmp(key, "version") == 0)
1029 google_version = value;
1031 else if(strcmp(key, "reqId") == 0)
1032 google_reqId = value;
1034 else if(strcmp(key, "sig") == 0)
1037 else if(strcmp(key, "out") == 0)
1040 else if(strcmp(key, "responseHandler") == 0)
1041 google_responseHandler = value;
1043 else if(strcmp(key, "outFileName") == 0)
1044 google_outFileName = value;
1050 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
1051 w->id, google_version, google_reqId, google_sig, google_out, google_responseHandler, google_outFileName
1054 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
1055 last_timestamp_in_data = strtoul(google_sig, NULL, 0);
1057 // check the client wants json
1058 if(strcmp(google_out, "json") != 0) {
1059 buffer_sprintf(w->response.data,
1060 "%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.'}]});",
1061 google_responseHandler, google_version, google_reqId, google_out);
1067 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
1068 buffer_sprintf(w->response.data,
1069 "%s({version:'%s',reqId:'%s',status:'ok',sig:'%lu',table:",
1070 google_responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
1073 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);
1074 time_t timestamp_in_data = rrd_stats_json(datasource_type, st, w->response.data, lines, group_count, group_method, after, before, nonzero);
1076 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
1077 if(timestamp_in_data > last_timestamp_in_data)
1078 buffer_strcat(w->response.data, "});");
1081 // the client already has the latest data
1082 buffer_flush(w->response.data);
1083 buffer_sprintf(w->response.data,
1084 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
1085 google_responseHandler, google_version, google_reqId);
1093 int web_client_parse_request(struct web_client *w) {
1097 // query string name-value
1100 // http request headers name-value
1102 web_client_clean_request(w);
1104 debug(D_WEB_DATA, "%llu: Processing data buffer of %d bytes: '%s'.", w->id, w->response.data->bytes, w->response.data->buffer);
1106 char *buf = w->response.data->buffer;
1109 // ------------------------------------------------------------------------
1112 if(buf && (line = strsep(&buf, "\r\n"))) {
1114 if(line && (tok = strsep(&line, " "))) {
1115 w->request.protocol = strdup(tok);
1123 // ------------------------------------------------------------------------
1124 // the rest of the lines
1126 while(buf && (line = strsep(&buf, "\r\n"))) {
1127 while(line && (tok = strsep(&line, ": "))) {
1135 web_client_clean_request(w);
1140 // get the request buffer, just after the GET or OPTIONS
1141 // and find the url to be decoded, decode it and return
1142 // a newly allocated buffer with it
1143 static inline char *find_url_and_decode_it(char *request) {
1144 char *e = request, *url = NULL;
1146 // find the SPACE + "HTTP/"
1149 while (*e && *e != ' ') e++;
1151 // is it SPACE + "HTTP/" ?
1152 if(*e && !strncmp(e, " HTTP/", 6))
1159 url = url_decode(request);
1166 void web_client_process(struct web_client *w) {
1169 int enable_gzip = 0;
1171 w->wait_receive = 0;
1173 // check if we have an empty line (end of HTTP header)
1174 if(strstr(w->response.data->buffer, "\r\n\r\n")) {
1175 global_statistics_lock();
1176 global_statistics.web_requests++;
1177 global_statistics_unlock();
1179 gettimeofday(&w->tv_in, NULL);
1180 debug(D_WEB_DATA, "%llu: Processing data buffer of %d bytes: '%s'.", w->id, w->response.data->len, w->response.data->buffer);
1182 // check if the client requested keep-alive HTTP
1183 if(strcasestr(w->response.data->buffer, "Connection: keep-alive")) w->keepalive = 1;
1184 else w->keepalive = 0;
1186 #ifdef NETDATA_WITH_ZLIB
1187 // check if the client accepts deflate
1188 if(web_enable_gzip && strstr(w->response.data->buffer, "gzip"))
1190 #endif // NETDATA_WITH_ZLIB
1192 w->mode = WEB_CLIENT_MODE_NORMAL;
1194 char *tok = (char *)buffer_tostring(w->response.data);
1195 char *url = NULL, *encoded_url = NULL;
1196 char *pointer_to_free = NULL; // keep url_decode() allocated buffer
1198 if(!strncmp(tok, "GET ", 4))
1199 encoded_url = &tok[4];
1200 else if(!strncmp(tok, "OPTIONS ", 8)) {
1201 encoded_url = &tok[8];
1202 w->mode = WEB_CLIENT_MODE_OPTIONS;
1206 pointer_to_free = url = find_url_and_decode_it(encoded_url);
1208 if(url) debug(D_WEB_CLIENT, "%llu: Processing url '%s'.", w->id, url);
1209 else debug(D_WEB_CLIENT, "%llu: Cannot find a valid URL in '%s'", w->id, encoded_url);
1212 w->last_url[0] = '\0';
1214 if(w->mode == WEB_CLIENT_MODE_OPTIONS) {
1215 strncpy(w->last_url, url, URL_MAX);
1216 w->last_url[URL_MAX] = '\0';
1219 w->response.data->contenttype = CT_TEXT_PLAIN;
1220 buffer_flush(w->response.data);
1221 buffer_strcat(w->response.data, "OK");
1224 #ifdef NETDATA_WITH_ZLIB
1226 web_client_enable_deflate(w);
1229 strncpy(w->last_url, url, URL_MAX);
1230 w->last_url[URL_MAX] = '\0';
1232 tok = mystrsep(&url, "/?");
1234 debug(D_WEB_CLIENT, "%llu: Processing command '%s'.", w->id, tok);
1236 if(strcmp(tok, "api") == 0) {
1237 // the client is requesting api access
1238 code = web_client_api_request(w, url);
1240 #ifdef NETDATA_INTERNAL_CHECKS
1241 else if(strcmp(tok, "exit") == 0) {
1243 w->response.data->contenttype = CT_TEXT_PLAIN;
1244 buffer_flush(w->response.data);
1247 buffer_strcat(w->response.data, "ok, will do...");
1249 buffer_strcat(w->response.data, "I am doing it already");
1254 else if(strcmp(tok, WEB_PATH_DATA) == 0) { // "data"
1255 // the client is requesting rrd data
1256 code = web_client_data_request(w, url, DATASOURCE_JSON);
1258 else if(strcmp(tok, WEB_PATH_DATASOURCE) == 0) { // "datasource"
1259 // the client is requesting google datasource
1260 code = web_client_data_request(w, url, DATASOURCE_DATATABLE_JSONP);
1262 else if(strcmp(tok, WEB_PATH_GRAPH) == 0) { // "graph"
1263 // the client is requesting an rrd graph
1265 // get the name of the data to show
1266 tok = mystrsep(&url, "/?&");
1268 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1270 // do we have such a data set?
1271 RRDSET *st = rrdset_find_byname(tok);
1272 if(!st) st = rrdset_find(tok);
1275 // try to send a file with that name
1276 buffer_flush(w->response.data);
1277 code = mysendfile(w, tok);
1281 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending %s.json of RRD_STATS...", w->id, st->name);
1282 w->response.data->contenttype = CT_APPLICATION_JSON;
1283 buffer_flush(w->response.data);
1284 rrd_stats_graph_json(st, url, w->response.data);
1289 buffer_flush(w->response.data);
1290 buffer_strcat(w->response.data, "Graph name?\r\n");
1293 #ifdef NETDATA_INTERNAL_CHECKS
1294 else if(strcmp(tok, "debug") == 0) {
1295 buffer_flush(w->response.data);
1297 // get the name of the data to show
1298 tok = mystrsep(&url, "/?&");
1300 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1302 // do we have such a data set?
1303 RRDSET *st = rrdset_find_byname(tok);
1304 if(!st) st = rrdset_find(tok);
1307 buffer_sprintf(w->response.data, "Chart %s is not found.\r\n", tok);
1308 debug(D_WEB_CLIENT_ACCESS, "%llu: %s is not found.", w->id, tok);
1312 debug_flags |= D_RRD_STATS;
1313 st->debug = st->debug?0:1;
1314 buffer_sprintf(w->response.data, "Chart %s has now debug %s.\r\n", tok, st->debug?"enabled":"disabled");
1315 debug(D_WEB_CLIENT_ACCESS, "%llu: debug for %s is %s.", w->id, tok, st->debug?"enabled":"disabled");
1320 buffer_flush(w->response.data);
1321 buffer_strcat(w->response.data, "debug which chart?\r\n");
1324 else if(strcmp(tok, "mirror") == 0) {
1327 debug(D_WEB_CLIENT_ACCESS, "%llu: Mirroring...", w->id);
1329 // replace the zero bytes with spaces
1330 buffer_char_replace(w->response.data, '\0', ' ');
1332 // just leave the buffer as is
1333 // it will be copied back to the client
1336 else if(strcmp(tok, "list") == 0) {
1339 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending list of RRD_STATS...", w->id);
1341 buffer_flush(w->response.data);
1342 RRDSET *st = rrdset_root;
1344 for ( ; st ; st = st->next )
1345 buffer_sprintf(w->response.data, "%s\n", st->name);
1347 else if(strcmp(tok, "all.json") == 0) {
1349 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending JSON list of all monitors of RRD_STATS...", w->id);
1351 w->response.data->contenttype = CT_APPLICATION_JSON;
1352 buffer_flush(w->response.data);
1353 rrd_stats_all_json(w->response.data);
1355 else if(strcmp(tok, "netdata.conf") == 0) {
1357 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending netdata.conf ...", w->id);
1359 w->response.data->contenttype = CT_TEXT_PLAIN;
1360 buffer_flush(w->response.data);
1361 generate_config(w->response.data, 0);
1364 char filename[FILENAME_MAX+1];
1366 strncpy(filename, w->last_url, FILENAME_MAX);
1367 filename[FILENAME_MAX] = '\0';
1368 tok = mystrsep(&url, "?");
1369 buffer_flush(w->response.data);
1370 code = mysendfile(w, (tok && *tok)?tok:"/");
1374 char filename[FILENAME_MAX+1];
1376 strncpy(filename, w->last_url, FILENAME_MAX);
1377 filename[FILENAME_MAX] = '\0';
1378 tok = mystrsep(&url, "?");
1379 buffer_flush(w->response.data);
1380 code = mysendfile(w, (tok && *tok)?tok:"/");
1384 strcpy(w->last_url, "not a valid response");
1386 debug(D_WEB_CLIENT_ACCESS, "%llu: Cannot understand '%s'.", w->id, w->response.data->buffer);
1389 buffer_flush(w->response.data);
1390 buffer_strcat(w->response.data, "I don't understand you...\r\n");
1393 // free url_decode() buffer
1394 if(pointer_to_free) {
1395 free(pointer_to_free);
1396 pointer_to_free = NULL;
1399 else if(w->response.data->len > TOO_BIG_REQUEST) {
1400 strcpy(w->last_url, "too big request");
1402 debug(D_WEB_CLIENT_ACCESS, "%llu: Received request is too big (%zd bytes).", w->id, w->response.data->len);
1405 buffer_flush(w->response.data);
1406 buffer_sprintf(w->response.data, "Received request is too big (%zd bytes).\r\n", w->response.data->len);
1409 // wait for more data
1410 w->wait_receive = 1;
1414 gettimeofday(&w->tv_ready, NULL);
1415 w->response.data->date = time(NULL);
1416 w->response.sent = 0;
1417 w->response.code = code;
1419 // prepare the HTTP response header
1420 debug(D_WEB_CLIENT, "%llu: Generating HTTP header with response %d.", w->id, code);
1422 char *content_type_string;
1423 switch(w->response.data->contenttype) {
1425 content_type_string = "text/html; charset=utf-8";
1428 case CT_APPLICATION_XML:
1429 content_type_string = "application/xml; charset=utf-8";
1432 case CT_APPLICATION_JSON:
1433 content_type_string = "application/json; charset=utf-8";
1436 case CT_APPLICATION_X_JAVASCRIPT:
1437 content_type_string = "application/x-javascript; charset=utf-8";
1441 content_type_string = "text/css; charset=utf-8";
1445 content_type_string = "text/xml; charset=utf-8";
1449 content_type_string = "text/xsl; charset=utf-8";
1452 case CT_APPLICATION_OCTET_STREAM:
1453 content_type_string = "application/octet-stream";
1456 case CT_IMAGE_SVG_XML:
1457 content_type_string = "image/svg+xml";
1460 case CT_APPLICATION_X_FONT_TRUETYPE:
1461 content_type_string = "application/x-font-truetype";
1464 case CT_APPLICATION_X_FONT_OPENTYPE:
1465 content_type_string = "application/x-font-opentype";
1468 case CT_APPLICATION_FONT_WOFF:
1469 content_type_string = "application/font-woff";
1472 case CT_APPLICATION_FONT_WOFF2:
1473 content_type_string = "application/font-woff2";
1476 case CT_APPLICATION_VND_MS_FONTOBJ:
1477 content_type_string = "application/vnd.ms-fontobject";
1481 content_type_string = "image/png";
1485 content_type_string = "image/jpeg";
1489 content_type_string = "image/gif";
1492 case CT_IMAGE_XICON:
1493 content_type_string = "image/x-icon";
1497 content_type_string = "image/bmp";
1501 content_type_string = "image/icns";
1506 content_type_string = "text/plain; charset=utf-8";
1517 code_msg = "Temporary Redirect";
1521 code_msg = "Bad Request";
1525 code_msg = "Forbidden";
1529 code_msg = "Not Found";
1533 code_msg = "Internal Server Error";
1538 struct tm tmbuf, *tm = gmtime_r(&w->response.data->date, &tmbuf);
1539 strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %Z", tm);
1541 buffer_sprintf(w->response.header_output,
1542 "HTTP/1.1 %d %s\r\n"
1543 "Connection: %s\r\n"
1544 "Server: NetData Embedded HTTP Server\r\n"
1545 "Access-Control-Allow-Origin: *\r\n"
1546 "Content-Type: %s\r\n"
1549 , w->keepalive?"keep-alive":"close"
1550 , content_type_string
1555 buffer_sprintf(w->response.header_output,
1556 "Set-Cookie: %s\r\n",
1560 if(w->mode == WEB_CLIENT_MODE_OPTIONS) {
1561 buffer_strcat(w->response.header_output,
1562 "Access-Control-Allow-Methods: GET, OPTIONS\r\n"
1563 "Access-Control-Allow-Credentials: true\r\n"
1564 "Access-Control-Allow-Headers: Accept, X-Requested-With, Content-Type, Cookie\r\n"
1565 "Access-Control-Max-Age: 1209600\r\n" // 86400 * 14
1569 if(buffer_strlen(w->response.header))
1570 buffer_strcat(w->response.header_output, buffer_tostring(w->response.header));
1572 if(w->mode == WEB_CLIENT_MODE_NORMAL && (w->response.data->options & WB_CONTENT_NO_CACHEABLE)) {
1573 buffer_sprintf(w->response.header_output,
1575 "Cache-Control: no-cache\r\n"
1578 else if(w->mode != WEB_CLIENT_MODE_OPTIONS) {
1580 time_t et = w->response.data->date + (86400 * 14);
1581 struct tm etmbuf, *etm = gmtime_r(&et, &etmbuf);
1582 strftime(edate, sizeof(edate), "%a, %d %b %Y %H:%M:%S %Z", etm);
1584 buffer_sprintf(w->response.header_output,
1586 "Cache-Control: public\r\n"
1590 // if we know the content length, put it
1591 if(!w->response.zoutput && (w->response.data->len || w->response.rlen))
1592 buffer_sprintf(w->response.header_output,
1593 "Content-Length: %ld\r\n"
1594 , w->response.data->len? w->response.data->len: w->response.rlen
1596 else if(!w->response.zoutput)
1597 w->keepalive = 0; // content-length is required for keep-alive
1599 if(w->response.zoutput) {
1600 buffer_strcat(w->response.header_output,
1601 "Content-Encoding: gzip\r\n"
1602 "Transfer-Encoding: chunked\r\n"
1606 buffer_strcat(w->response.header_output, "\r\n");
1608 // disable TCP_NODELAY, to buffer the header
1610 if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0)
1611 error("%llu: failed to disable TCP_NODELAY on socket.", w->id);
1613 // sent the HTTP header
1614 debug(D_WEB_DATA, "%llu: Sending response HTTP header of size %d: '%s'"
1616 , buffer_strlen(w->response.header_output)
1617 , buffer_tostring(w->response.header_output)
1620 bytes = send(w->ofd, buffer_tostring(w->response.header_output), buffer_strlen(w->response.header_output), 0);
1621 if(bytes != (ssize_t) buffer_strlen(w->response.header_output))
1622 error("%llu: HTTP Header failed to be sent (I sent %d bytes but the system sent %d bytes)."
1624 , buffer_strlen(w->response.header_output)
1627 global_statistics_lock();
1628 global_statistics.bytes_sent += bytes;
1629 global_statistics_unlock();
1632 // enable TCP_NODELAY, to send all data immediately at the next send()
1634 if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0) error("%llu: failed to enable TCP_NODELAY on socket.", w->id);
1636 // enable sending immediately if we have data
1637 if(w->response.data->len) w->wait_send = 1;
1638 else w->wait_send = 0;
1642 case WEB_CLIENT_MODE_OPTIONS:
1643 debug(D_WEB_CLIENT, "%llu: Done preparing the OPTIONS response. Sending data (%d bytes) to client.", w->id, w->response.data->len);
1646 case WEB_CLIENT_MODE_NORMAL:
1647 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Sending data (%d bytes) to client.", w->id, w->response.data->len);
1650 case WEB_CLIENT_MODE_FILECOPY:
1651 if(w->response.rlen) {
1652 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending data file of %d bytes to client.", w->id, w->response.rlen);
1653 w->wait_receive = 1;
1656 // utilize the kernel sendfile() for copying the file to the socket.
1657 // this block of code can be commented, without anything missing.
1658 // when it is commented, the program will copy the data using async I/O.
1660 long len = sendfile(w->ofd, w->ifd, NULL, w->response.data->rbytes);
1661 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);
1662 else web_client_reset(w);
1667 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending an unknown amount of bytes to client.", w->id);
1671 fatal("%llu: Unknown client mode %d.", w->id, w->mode);
1676 long web_client_send_chunk_header(struct web_client *w, long len)
1678 debug(D_DEFLATE, "%llu: OPEN CHUNK of %d bytes (hex: %x).", w->id, len, len);
1680 sprintf(buf, "%lX\r\n", len);
1681 ssize_t bytes = send(w->ofd, buf, strlen(buf), MSG_DONTWAIT);
1683 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk header %d bytes.", w->id, bytes);
1684 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk header to the client.", w->id);
1685 else debug(D_DEFLATE, "%llu: Failed to send chunk header to client.", w->id);
1690 long web_client_send_chunk_close(struct web_client *w)
1692 //debug(D_DEFLATE, "%llu: CLOSE CHUNK.", w->id);
1694 ssize_t bytes = send(w->ofd, "\r\n", 2, MSG_DONTWAIT);
1696 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
1697 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
1698 else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client.", w->id);
1703 long web_client_send_chunk_finalize(struct web_client *w)
1705 //debug(D_DEFLATE, "%llu: FINALIZE CHUNK.", w->id);
1707 ssize_t bytes = send(w->ofd, "\r\n0\r\n\r\n", 7, MSG_DONTWAIT);
1709 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
1710 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
1711 else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client.", w->id);
1716 #ifdef NETDATA_WITH_ZLIB
1717 long web_client_send_deflate(struct web_client *w)
1719 long len = 0, t = 0;
1721 // when using compression,
1722 // w->response.sent is the amount of bytes passed through compression
1724 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);
1726 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) {
1727 // there is nothing to send
1729 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1731 // finalize the chunk
1732 if(w->response.sent != 0)
1733 t += web_client_send_chunk_finalize(w);
1735 // there can be two cases for this
1736 // A. we have done everything
1737 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
1739 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->response.rlen && w->response.rlen > w->response.data->len) {
1740 // we have to wait, more data will come
1741 debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1746 if(w->keepalive == 0) {
1747 debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->response.sent);
1753 web_client_reset(w);
1754 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1758 if(w->response.zhave == w->response.zsent) {
1759 // compress more input data
1761 // close the previous open chunk
1762 if(w->response.sent != 0) t += web_client_send_chunk_close(w);
1764 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);
1766 // give the compressor all the data not passed through the compressor yet
1767 if(w->response.data->len > w->response.sent) {
1768 #ifdef NETDATA_INTERNAL_CHECKS
1769 if((long)w->response.sent - (long)w->response.zstream.avail_in < 0)
1770 error("internal error: avail_in is corrupted.");
1772 w->response.zstream.next_in = (Bytef *)&w->response.data->buffer[w->response.sent - w->response.zstream.avail_in];
1773 w->response.zstream.avail_in += (uInt) (w->response.data->len - w->response.sent);
1776 // reset the compressor output buffer
1777 w->response.zstream.next_out = w->response.zbuffer;
1778 w->response.zstream.avail_out = ZLIB_CHUNK;
1780 // ask for FINISH if we have all the input
1781 int flush = Z_SYNC_FLUSH;
1782 if(w->mode == WEB_CLIENT_MODE_NORMAL
1783 || (w->mode == WEB_CLIENT_MODE_FILECOPY && !w->wait_receive && w->response.data->len == w->response.rlen)) {
1785 debug(D_DEFLATE, "%llu: Requesting Z_FINISH, if possible.", w->id);
1788 debug(D_DEFLATE, "%llu: Requesting Z_SYNC_FLUSH.", w->id);
1792 if(deflate(&w->response.zstream, flush) == Z_STREAM_ERROR) {
1793 error("%llu: Compression failed. Closing down client.", w->id);
1794 web_client_reset(w);
1798 w->response.zhave = ZLIB_CHUNK - w->response.zstream.avail_out;
1799 w->response.zsent = 0;
1801 // keep track of the bytes passed through the compressor
1802 w->response.sent = w->response.data->len;
1804 debug(D_DEFLATE, "%llu: Compression produced %d bytes.", w->id, w->response.zhave);
1807 t += web_client_send_chunk_header(w, w->response.zhave);
1810 debug(D_WEB_CLIENT, "%llu: Sending %d bytes of data (+%d of chunk header).", w->id, w->response.zhave - w->response.zsent, t);
1812 len = send(w->ofd, &w->response.zbuffer[w->response.zsent], (size_t) (w->response.zhave - w->response.zsent), MSG_DONTWAIT);
1814 w->response.zsent += len;
1816 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, len);
1818 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);
1819 else debug(D_WEB_CLIENT, "%llu: Failed to send data to client. Reason: %s", w->id, strerror(errno));
1823 #endif // NETDATA_WITH_ZLIB
1825 long web_client_send(struct web_client *w)
1827 #ifdef NETDATA_WITH_ZLIB
1828 if(likely(w->response.zoutput)) return web_client_send_deflate(w);
1829 #endif // NETDATA_WITH_ZLIB
1833 if(unlikely(w->response.data->len - w->response.sent == 0)) {
1834 // there is nothing to send
1836 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1838 // there can be two cases for this
1839 // A. we have done everything
1840 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
1842 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->response.rlen && w->response.rlen > w->response.data->len) {
1843 // we have to wait, more data will come
1844 debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1849 if(unlikely(w->keepalive == 0)) {
1850 debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->response.sent);
1855 web_client_reset(w);
1856 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1860 bytes = send(w->ofd, &w->response.data->buffer[w->response.sent], w->response.data->len - w->response.sent, MSG_DONTWAIT);
1861 if(likely(bytes > 0)) {
1862 w->response.sent += bytes;
1863 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, bytes);
1865 else if(likely(bytes == 0)) debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client.", w->id);
1866 else debug(D_WEB_CLIENT, "%llu: Failed to send data to client.", w->id);
1871 long web_client_receive(struct web_client *w)
1873 // do we have any space for more data?
1874 buffer_need_bytes(w->response.data, WEB_REQUEST_LENGTH);
1876 long left = w->response.data->size - w->response.data->len;
1879 if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY))
1880 bytes = read(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1));
1882 bytes = recv(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1), MSG_DONTWAIT);
1884 if(likely(bytes > 0)) {
1885 size_t old = w->response.data->len;
1886 w->response.data->len += bytes;
1887 w->response.data->buffer[w->response.data->len] = '\0';
1889 debug(D_WEB_CLIENT, "%llu: Received %d bytes.", w->id, bytes);
1890 debug(D_WEB_DATA, "%llu: Received data: '%s'.", w->id, &w->response.data->buffer[old]);
1892 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1894 if(w->response.rlen && w->response.data->len >= w->response.rlen) w->wait_receive = 0;
1897 else if(likely(bytes == 0)) {
1898 debug(D_WEB_CLIENT, "%llu: Out of input data.", w->id);
1900 // if we cannot read, it means we have an error on input.
1901 // if however, we are copying a file from ifd to ofd, we should not return an error.
1902 // in this case, the error should be generated when the file has been sent to the client.
1904 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1905 // we are copying data from ifd to ofd
1906 // let it finish copying...
1907 w->wait_receive = 0;
1908 debug(D_WEB_CLIENT, "%llu: Disabling input.", w->id);
1920 // --------------------------------------------------------------------------------------
1921 // the thread of a single client
1923 // 1. waits for input and output, using async I/O
1924 // 2. it processes HTTP requests
1925 // 3. it generates HTTP responses
1926 // 4. it copies data from input to output if mode is FILECOPY
1928 void *web_client_main(void *ptr)
1930 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
1931 error("Cannot set pthread cancel type to DEFERRED.");
1933 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
1934 error("Cannot set pthread cancel state to ENABLE.");
1937 struct web_client *w = ptr;
1939 fd_set ifds, ofds, efds;
1942 log_access("%llu: %s port %s connected on thread task id %d", w->id, w->client_ip, w->client_port, gettid());
1949 FD_SET(w->ifd, &efds);
1951 if(w->ifd != w->ofd)
1952 FD_SET(w->ofd, &efds);
1954 if (w->wait_receive) {
1955 FD_SET(w->ifd, &ifds);
1956 if(w->ifd > fdmax) fdmax = w->ifd;
1960 FD_SET(w->ofd, &ofds);
1961 if(w->ofd > fdmax) fdmax = w->ofd;
1964 tv.tv_sec = web_client_timeout;
1967 debug(D_WEB_CLIENT, "%llu: Waiting socket async I/O for %s %s", w->id, w->wait_receive?"INPUT":"", w->wait_send?"OUTPUT":"");
1968 retval = select(fdmax+1, &ifds, &ofds, &efds, &tv);
1971 debug(D_WEB_CLIENT_ACCESS, "%llu: LISTENER: select() failed.", w->id);
1976 debug(D_WEB_CLIENT_ACCESS, "%llu: LISTENER: timeout.", w->id);
1980 if(FD_ISSET(w->ifd, &efds)) {
1981 debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on input socket.", w->id);
1985 if(FD_ISSET(w->ofd, &efds)) {
1986 debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on output socket.", w->id);
1990 if(w->wait_send && FD_ISSET(w->ofd, &ofds)) {
1992 if((bytes = web_client_send(w)) < 0) {
1993 debug(D_WEB_CLIENT, "%llu: Cannot send data to client. Closing client.", w->id);
1998 global_statistics_lock();
1999 global_statistics.bytes_sent += bytes;
2000 global_statistics_unlock();
2003 if(w->wait_receive && FD_ISSET(w->ifd, &ifds)) {
2005 if((bytes = web_client_receive(w)) < 0) {
2006 debug(D_WEB_CLIENT, "%llu: Cannot receive data from client. Closing client.", w->id);
2011 if(w->mode == WEB_CLIENT_MODE_NORMAL) {
2012 debug(D_WEB_CLIENT, "%llu: Attempting to process received data (%ld bytes).", w->id, bytes);
2013 // info("%llu: Attempting to process received data (%ld bytes).", w->id, bytes);
2014 web_client_process(w);
2017 global_statistics_lock();
2018 global_statistics.bytes_received += bytes;
2019 global_statistics_unlock();
2023 log_access("%llu: %s port %s disconnected from thread task id %d", w->id, w->client_ip, w->client_port, gettid());
2024 debug(D_WEB_CLIENT, "%llu: done...", w->id);
2026 web_client_reset(w);