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 long sent = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->response.rlen:w->response.data->len;
151 #ifdef NETDATA_WITH_ZLIB
152 if(likely(w->response.zoutput)) sent = (long)w->response.zstream.total_out;
155 long size = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->response.rlen:w->response.data->len;
157 if(likely(w->last_url[0]))
158 log_access("%llu: (sent/all = %ld/%ld bytes %0.0f%%, prep/sent/total = %0.2f/%0.2f/%0.2f ms) %s: %d '%s'",
160 sent, size, -((size>0)?((float)(size-sent)/(float)size * 100.0):0.0),
161 (float)usecdiff(&w->tv_ready, &w->tv_in) / 1000.0,
162 (float)usecdiff(&tv, &w->tv_ready) / 1000.0,
163 (float)usecdiff(&tv, &w->tv_in) / 1000.0,
164 (w->mode == WEB_CLIENT_MODE_FILECOPY)?"filecopy":((w->mode == WEB_CLIENT_MODE_OPTIONS)?"options":"data"),
169 debug(D_WEB_CLIENT, "%llu: Reseting client.", w->id);
171 if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY)) {
172 debug(D_WEB_CLIENT, "%llu: Closing filecopy input file.", w->id);
177 w->last_url[0] = '\0';
182 w->mode = WEB_CLIENT_MODE_NORMAL;
186 free(w->decoded_url);
187 w->decoded_url = NULL;
190 buffer_reset(w->response.header_output);
191 buffer_reset(w->response.header);
192 buffer_reset(w->response.data);
193 w->response.rlen = 0;
194 w->response.sent = 0;
195 w->response.code = 0;
200 w->response.zoutput = 0;
202 // if we had enabled compression, release it
203 #ifdef NETDATA_WITH_ZLIB
204 if(w->response.zinitialized) {
205 debug(D_DEFLATE, "%llu: Reseting compression.", w->id);
206 deflateEnd(&w->response.zstream);
207 w->response.zsent = 0;
208 w->response.zhave = 0;
209 w->response.zstream.avail_in = 0;
210 w->response.zstream.avail_out = 0;
211 w->response.zstream.total_in = 0;
212 w->response.zstream.total_out = 0;
213 w->response.zinitialized = 0;
215 #endif // NETDATA_WITH_ZLIB
218 struct web_client *web_client_free(struct web_client *w)
220 struct web_client *n = w->next;
222 debug(D_WEB_CLIENT_ACCESS, "%llu: Closing web client from %s port %s.", w->id, w->client_ip, w->client_port);
224 if(w->prev) w->prev->next = w->next;
225 if(w->next) w->next->prev = w->prev;
227 if(w == web_clients) web_clients = w->next;
229 if(w->response.header_output) buffer_free(w->response.header_output);
230 if(w->response.header) buffer_free(w->response.header);
231 if(w->response.data) buffer_free(w->response.data);
233 if(w->ofd != w->ifd) close(w->ofd);
236 global_statistics.connected_clients--;
241 uid_t web_files_uid(void)
243 static char *web_owner = NULL;
244 static uid_t owner_uid = 0;
246 if(unlikely(!web_owner)) {
247 web_owner = config_get("global", "web files owner", config_get("global", "run as user", ""));
248 if(!web_owner || !*web_owner)
249 owner_uid = geteuid();
251 // getpwnam() is not thread safe,
252 // but we have called this function once
253 // while single threaded
254 struct passwd *pw = getpwnam(web_owner);
256 error("User %s is not present. Ignoring option.", web_owner);
257 owner_uid = geteuid();
260 debug(D_WEB_CLIENT, "Web files owner set to %s.\n", web_owner);
261 owner_uid = pw->pw_uid;
269 gid_t web_files_gid(void)
271 static char *web_group = NULL;
272 static gid_t owner_gid = 0;
274 if(unlikely(!web_group)) {
275 web_group = config_get("global", "web files group", config_get("global", "web files owner", ""));
276 if(!web_group || !*web_group)
277 owner_gid = getegid();
279 // getgrnam() is not thread safe,
280 // but we have called this function once
281 // while single threaded
282 struct group *gr = getgrnam(web_group);
284 error("Group %s is not present. Ignoring option.", web_group);
285 owner_gid = getegid();
288 debug(D_WEB_CLIENT, "Web files group set to %s.\n", web_group);
289 owner_gid = gr->gr_gid;
297 int mysendfile(struct web_client *w, char *filename)
299 static char *web_dir = NULL;
301 // initialize our static data
302 if(unlikely(!web_dir)) web_dir = config_get("global", "web files directory", WEB_DIR);
304 debug(D_WEB_CLIENT, "%llu: Looking for file '%s/%s'", w->id, web_dir, filename);
306 // skip leading slashes
307 while (*filename == '/') filename++;
309 // if the filename contain known paths, skip them
310 if(strncmp(filename, WEB_PATH_FILE "/", strlen(WEB_PATH_FILE) + 1) == 0) filename = &filename[strlen(WEB_PATH_FILE) + 1];
313 for(s = filename; *s ;s++) {
314 if( !isalnum(*s) && *s != '/' && *s != '.' && *s != '-' && *s != '_') {
315 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
316 buffer_sprintf(w->response.data, "File '%s' cannot be served. Filename contains invalid character '%c'", filename, *s);
321 // if the filename contains a .. refuse to serve it
322 if(strstr(filename, "..") != 0) {
323 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
324 buffer_sprintf(w->response.data, "File '%s' cannot be served. Relative filenames with '..' in them are not supported.", filename);
329 char webfilename[FILENAME_MAX + 1];
330 snprintfz(webfilename, FILENAME_MAX, "%s/%s", web_dir, filename);
332 // check if the file exists
334 if(lstat(webfilename, &stat) != 0) {
335 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not found.", w->id, webfilename);
336 buffer_sprintf(w->response.data, "File '%s' does not exist, or is not accessible.", webfilename);
340 // check if the file is owned by expected user
341 if(stat.st_uid != web_files_uid()) {
342 error("%llu: File '%s' is owned by user %d (expected user %d). Access Denied.", w->id, webfilename, stat.st_uid, web_files_uid());
343 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", webfilename);
347 // check if the file is owned by expected group
348 if(stat.st_gid != web_files_gid()) {
349 error("%llu: File '%s' is owned by group %d (expected group %d). Access Denied.", w->id, webfilename, stat.st_gid, web_files_gid());
350 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", webfilename);
354 if((stat.st_mode & S_IFMT) == S_IFDIR) {
355 snprintfz(webfilename, FILENAME_MAX, "%s/index.html", filename);
356 return mysendfile(w, webfilename);
359 if((stat.st_mode & S_IFMT) != S_IFREG) {
360 error("%llu: File '%s' is not a regular file. Access Denied.", w->id, webfilename);
361 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", webfilename);
366 w->ifd = open(webfilename, O_NONBLOCK, O_RDONLY);
370 if(errno == EBUSY || errno == EAGAIN) {
371 error("%llu: File '%s' is busy, sending 307 Moved Temporarily to force retry.", w->id, webfilename);
372 buffer_sprintf(w->response.header, "Location: /" WEB_PATH_FILE "/%s\r\n", filename);
373 buffer_sprintf(w->response.data, "The file '%s' is currently busy. Please try again later.", webfilename);
377 error("%llu: Cannot open file '%s'.", w->id, webfilename);
378 buffer_sprintf(w->response.data, "Cannot open file '%s'.", webfilename);
383 // pick a Content-Type for the file
384 if(strstr(filename, ".html") != NULL) w->response.data->contenttype = CT_TEXT_HTML;
385 else if(strstr(filename, ".js") != NULL) w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
386 else if(strstr(filename, ".css") != NULL) w->response.data->contenttype = CT_TEXT_CSS;
387 else if(strstr(filename, ".xml") != NULL) w->response.data->contenttype = CT_TEXT_XML;
388 else if(strstr(filename, ".xsl") != NULL) w->response.data->contenttype = CT_TEXT_XSL;
389 else if(strstr(filename, ".txt") != NULL) w->response.data->contenttype = CT_TEXT_PLAIN;
390 else if(strstr(filename, ".svg") != NULL) w->response.data->contenttype = CT_IMAGE_SVG_XML;
391 else if(strstr(filename, ".ttf") != NULL) w->response.data->contenttype = CT_APPLICATION_X_FONT_TRUETYPE;
392 else if(strstr(filename, ".otf") != NULL) w->response.data->contenttype = CT_APPLICATION_X_FONT_OPENTYPE;
393 else if(strstr(filename, ".woff2")!= NULL) w->response.data->contenttype = CT_APPLICATION_FONT_WOFF2;
394 else if(strstr(filename, ".woff") != NULL) w->response.data->contenttype = CT_APPLICATION_FONT_WOFF;
395 else if(strstr(filename, ".eot") != NULL) w->response.data->contenttype = CT_APPLICATION_VND_MS_FONTOBJ;
396 else if(strstr(filename, ".png") != NULL) w->response.data->contenttype = CT_IMAGE_PNG;
397 else if(strstr(filename, ".jpg") != NULL) w->response.data->contenttype = CT_IMAGE_JPG;
398 else if(strstr(filename, ".jpeg") != NULL) w->response.data->contenttype = CT_IMAGE_JPG;
399 else if(strstr(filename, ".gif") != NULL) w->response.data->contenttype = CT_IMAGE_GIF;
400 else if(strstr(filename, ".bmp") != NULL) w->response.data->contenttype = CT_IMAGE_BMP;
401 else if(strstr(filename, ".ico") != NULL) w->response.data->contenttype = CT_IMAGE_XICON;
402 else if(strstr(filename, ".icns") != NULL) w->response.data->contenttype = CT_IMAGE_ICNS;
403 else w->response.data->contenttype = CT_APPLICATION_OCTET_STREAM;
405 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);
407 w->mode = WEB_CLIENT_MODE_FILECOPY;
410 buffer_flush(w->response.data);
411 w->response.rlen = stat.st_size;
412 w->response.data->date = stat.st_mtim.tv_sec;
418 #ifdef NETDATA_WITH_ZLIB
419 void web_client_enable_deflate(struct web_client *w) {
420 if(w->response.zinitialized == 1) {
421 error("%llu: Compression has already be initialized for this client.", w->id);
425 if(w->response.sent) {
426 error("%llu: Cannot enable compression in the middle of a conversation.", w->id);
430 w->response.zstream.zalloc = Z_NULL;
431 w->response.zstream.zfree = Z_NULL;
432 w->response.zstream.opaque = Z_NULL;
434 w->response.zstream.next_in = (Bytef *)w->response.data->buffer;
435 w->response.zstream.avail_in = 0;
436 w->response.zstream.total_in = 0;
438 w->response.zstream.next_out = w->response.zbuffer;
439 w->response.zstream.avail_out = 0;
440 w->response.zstream.total_out = 0;
442 w->response.zstream.zalloc = Z_NULL;
443 w->response.zstream.zfree = Z_NULL;
444 w->response.zstream.opaque = Z_NULL;
446 // if(deflateInit(&w->response.zstream, Z_DEFAULT_COMPRESSION) != Z_OK) {
447 // error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
451 // Select GZIP compression: windowbits = 15 + 16 = 31
452 if(deflateInit2(&w->response.zstream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY) != Z_OK) {
453 error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
457 w->response.zsent = 0;
458 w->response.zoutput = 1;
459 w->response.zinitialized = 1;
461 debug(D_DEFLATE, "%llu: Initialized compression.", w->id);
463 #endif // NETDATA_WITH_ZLIB
465 uint32_t web_client_api_request_v1_data_options(char *o)
467 uint32_t ret = 0x00000000;
470 while(o && *o && (tok = mystrsep(&o, ", |"))) {
473 if(!strcmp(tok, "nonzero"))
474 ret |= RRDR_OPTION_NONZERO;
475 else if(!strcmp(tok, "flip") || !strcmp(tok, "reversed") || !strcmp(tok, "reverse"))
476 ret |= RRDR_OPTION_REVERSED;
477 else if(!strcmp(tok, "jsonwrap"))
478 ret |= RRDR_OPTION_JSON_WRAP;
479 else if(!strcmp(tok, "min2max"))
480 ret |= RRDR_OPTION_MIN2MAX;
481 else if(!strcmp(tok, "ms") || !strcmp(tok, "milliseconds"))
482 ret |= RRDR_OPTION_MILLISECONDS;
483 else if(!strcmp(tok, "abs") || !strcmp(tok, "absolute") || !strcmp(tok, "absolute_sum") || !strcmp(tok, "absolute-sum"))
484 ret |= RRDR_OPTION_ABSOLUTE;
485 else if(!strcmp(tok, "seconds"))
486 ret |= RRDR_OPTION_SECONDS;
487 else if(!strcmp(tok, "null2zero"))
488 ret |= RRDR_OPTION_NULL2ZERO;
489 else if(!strcmp(tok, "objectrows"))
490 ret |= RRDR_OPTION_OBJECTSROWS;
491 else if(!strcmp(tok, "google_json"))
492 ret |= RRDR_OPTION_GOOGLE_JSON;
493 else if(!strcmp(tok, "percentage"))
494 ret |= RRDR_OPTION_PERCENTAGE;
500 uint32_t web_client_api_request_v1_data_format(char *name)
502 if(!strcmp(name, DATASOURCE_FORMAT_DATATABLE_JSON)) // datatable
503 return DATASOURCE_DATATABLE_JSON;
505 else if(!strcmp(name, DATASOURCE_FORMAT_DATATABLE_JSONP)) // datasource
506 return DATASOURCE_DATATABLE_JSONP;
508 else if(!strcmp(name, DATASOURCE_FORMAT_JSON)) // json
509 return DATASOURCE_JSON;
511 else if(!strcmp(name, DATASOURCE_FORMAT_JSONP)) // jsonp
512 return DATASOURCE_JSONP;
514 else if(!strcmp(name, DATASOURCE_FORMAT_SSV)) // ssv
515 return DATASOURCE_SSV;
517 else if(!strcmp(name, DATASOURCE_FORMAT_CSV)) // csv
518 return DATASOURCE_CSV;
520 else if(!strcmp(name, DATASOURCE_FORMAT_TSV) || !strcmp(name, "tsv-excel")) // tsv
521 return DATASOURCE_TSV;
523 else if(!strcmp(name, DATASOURCE_FORMAT_HTML)) // html
524 return DATASOURCE_HTML;
526 else if(!strcmp(name, DATASOURCE_FORMAT_JS_ARRAY)) // array
527 return DATASOURCE_JS_ARRAY;
529 else if(!strcmp(name, DATASOURCE_FORMAT_SSV_COMMA)) // ssvcomma
530 return DATASOURCE_SSV_COMMA;
532 else if(!strcmp(name, DATASOURCE_FORMAT_CSV_JSON_ARRAY)) // csvjsonarray
533 return DATASOURCE_CSV_JSON_ARRAY;
535 return DATASOURCE_JSON;
538 uint32_t web_client_api_request_v1_data_google_format(char *name)
540 if(!strcmp(name, "json"))
541 return DATASOURCE_DATATABLE_JSONP;
543 else if(!strcmp(name, "html"))
544 return DATASOURCE_HTML;
546 else if(!strcmp(name, "csv"))
547 return DATASOURCE_CSV;
549 else if(!strcmp(name, "tsv-excel"))
550 return DATASOURCE_TSV;
552 return DATASOURCE_JSON;
555 int web_client_api_request_v1_data_group(char *name)
557 if(!strcmp(name, "max"))
560 else if(!strcmp(name, "average"))
561 return GROUP_AVERAGE;
566 int web_client_api_request_v1_charts(struct web_client *w, char *url)
570 buffer_flush(w->response.data);
571 w->response.data->contenttype = CT_APPLICATION_JSON;
572 rrd_stats_api_v1_charts(w->response.data);
576 int web_client_api_request_v1_chart(struct web_client *w, char *url)
581 buffer_flush(w->response.data);
584 char *value = mystrsep(&url, "?&[]");
585 if(!value || !*value) continue;
587 char *name = mystrsep(&value, "=");
588 if(!name || !*name) continue;
589 if(!value || !*value) continue;
591 // name and value are now the parameters
592 // they are not null and not empty
594 if(!strcmp(name, "chart")) chart = value;
596 /// buffer_sprintf(w->response.data, "Unknown parameter '%s' in request.", name);
601 if(!chart || !*chart) {
602 buffer_sprintf(w->response.data, "No chart id is given at the request.");
606 RRDSET *st = rrdset_find(chart);
607 if(!st) st = rrdset_find_byname(chart);
609 buffer_sprintf(w->response.data, "Chart '%s' is not found.", chart);
614 w->response.data->contenttype = CT_APPLICATION_JSON;
615 rrd_stats_api_v1_chart(st, w->response.data);
622 // returns the HTTP code
623 int web_client_api_request_v1_data(struct web_client *w, char *url)
625 debug(D_WEB_CLIENT, "%llu: API v1 data with URL '%s'", w->id, url);
628 BUFFER *dimensions = NULL;
630 buffer_flush(w->response.data);
632 char *google_version = "0.6",
635 *google_out = "json",
636 *responseHandler = NULL,
639 time_t last_timestamp_in_data = 0, google_timestamp = 0;
644 , *points_str = NULL;
646 int group = GROUP_MAX;
647 uint32_t format = DATASOURCE_JSON;
648 uint32_t options = 0x00000000;
651 char *value = mystrsep(&url, "?&[]");
652 if(!value || !*value) continue;
654 char *name = mystrsep(&value, "=");
655 if(!name || !*name) continue;
656 if(!value || !*value) continue;
658 debug(D_WEB_CLIENT, "%llu: API v1 data query param '%s' with value '%s'", w->id, name, value);
660 // name and value are now the parameters
661 // they are not null and not empty
663 if(!strcmp(name, "chart")) chart = value;
664 else if(!strcmp(name, "dimension") || !strcmp(name, "dim") || !strcmp(name, "dimensions") || !strcmp(name, "dims")) {
665 if(!dimensions) dimensions = buffer_create(strlen(value));
667 buffer_strcat(dimensions, "|");
668 buffer_strcat(dimensions, value);
671 else if(!strcmp(name, "after")) after_str = value;
672 else if(!strcmp(name, "before")) before_str = value;
673 else if(!strcmp(name, "points")) points_str = value;
674 else if(!strcmp(name, "group")) {
675 group = web_client_api_request_v1_data_group(value);
677 else if(!strcmp(name, "format")) {
678 format = web_client_api_request_v1_data_format(value);
680 else if(!strcmp(name, "options")) {
681 options |= web_client_api_request_v1_data_options(value);
683 else if(!strcmp(name, "callback")) {
684 responseHandler = value;
686 else if(!strcmp(name, "filename")) {
689 else if(!strcmp(name, "tqx")) {
690 // parse Google Visualization API options
691 // https://developers.google.com/chart/interactive/docs/dev/implementing_data_source
692 char *tqx_name, *tqx_value;
695 tqx_value = mystrsep(&value, ";");
696 if(!tqx_value || !*tqx_value) continue;
698 tqx_name = mystrsep(&tqx_value, ":");
699 if(!tqx_name || !*tqx_name) continue;
700 if(!tqx_value || !*tqx_value) continue;
702 if(!strcmp(tqx_name, "version"))
703 google_version = tqx_value;
704 else if(!strcmp(tqx_name, "reqId"))
705 google_reqId = tqx_value;
706 else if(!strcmp(tqx_name, "sig")) {
707 google_sig = tqx_value;
708 google_timestamp = strtoul(google_sig, NULL, 0);
710 else if(!strcmp(tqx_name, "out")) {
711 google_out = tqx_value;
712 format = web_client_api_request_v1_data_google_format(google_out);
714 else if(!strcmp(tqx_name, "responseHandler"))
715 responseHandler = tqx_value;
716 else if(!strcmp(tqx_name, "outFileName"))
717 outFileName = tqx_value;
722 if(!chart || !*chart) {
723 buffer_sprintf(w->response.data, "No chart id is given at the request.");
727 RRDSET *st = rrdset_find(chart);
728 if(!st) st = rrdset_find_byname(chart);
730 buffer_sprintf(w->response.data, "Chart '%s' is not found.", chart);
735 long long before = (before_str && *before_str)?atol(before_str):0;
736 long long after = (after_str && *after_str) ?atol(after_str):0;
737 int points = (points_str && *points_str)?atoi(points_str):0;
739 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'"
742 , (dimensions)?buffer_tostring(dimensions):""
751 if(outFileName && *outFileName) {
752 buffer_sprintf(w->response.header, "Content-Disposition: attachment; filename=\"%s\"\r\n", outFileName);
753 error("generating outfilename header: '%s'", outFileName);
756 if(format == DATASOURCE_DATATABLE_JSONP) {
757 if(responseHandler == NULL)
758 responseHandler = "google.visualization.Query.setResponse";
760 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSON/JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
761 w->id, google_version, google_reqId, google_sig, google_out, responseHandler, outFileName
764 buffer_sprintf(w->response.data,
765 "%s({version:'%s',reqId:'%s',status:'ok',sig:'%lu',table:",
766 responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
768 else if(format == DATASOURCE_JSONP) {
769 if(responseHandler == NULL)
770 responseHandler = "callback";
772 buffer_strcat(w->response.data, responseHandler);
773 buffer_strcat(w->response.data, "(");
776 ret = rrd2format(st, w->response.data, dimensions, format, points, after, before, group, options, &last_timestamp_in_data);
778 if(format == DATASOURCE_DATATABLE_JSONP) {
779 if(google_timestamp < last_timestamp_in_data)
780 buffer_strcat(w->response.data, "});");
783 // the client already has the latest data
784 buffer_flush(w->response.data);
785 buffer_sprintf(w->response.data,
786 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
787 responseHandler, google_version, google_reqId);
790 else if(format == DATASOURCE_JSONP)
791 buffer_strcat(w->response.data, ");");
794 if(dimensions) buffer_free(dimensions);
798 int web_client_api_request_v1_registry(struct web_client *w, char *url)
800 char person_guid[36 + 1] = "";
802 debug(D_WEB_CLIENT, "%llu: API v1 registry with URL '%s'", w->id, url);
804 char *cookie = strstr(w->response.data->buffer, " " NETDATA_REGISTRY_COOKIE_NAME "=");
806 strncpy(person_guid, &cookie[sizeof(NETDATA_REGISTRY_COOKIE_NAME) + 1], 36);
807 person_guid[36] = '\0';
811 char *machine_guid = NULL,
814 *search_machine_guid = NULL,
816 *to_person_guid = NULL;
819 char *value = mystrsep(&url, "?&[]");
820 if (!value || !*value) continue;
822 char *name = mystrsep(&value, "=");
823 if (!name || !*name) continue;
824 if (!value || !*value) continue;
826 debug(D_WEB_CLIENT, "%llu: API v1 registry query param '%s' with value '%s'", w->id, name, value);
828 if(!strcmp(name, "action")) {
829 if(!strcmp(value, "access")) action = 'A';
830 else if(!strcmp(value, "hello")) action = 'H';
831 else if(!strcmp(value, "delete")) action = 'D';
832 else if(!strcmp(value, "search")) action = 'S';
833 else if(!strcmp(value, "switch")) action = 'W';
835 else if(!strcmp(name, "machine"))
836 machine_guid = value;
838 else if(!strcmp(name, "url"))
841 else if(action == 'A') {
842 if(!strcmp(name, "name"))
845 else if(action == 'D') {
846 if(!strcmp(name, "delete_url"))
849 else if(action == 'S') {
850 if(!strcmp(name, "for"))
851 search_machine_guid = value;
853 else if(action == 'W') {
854 if(!strcmp(name, "to"))
855 to_person_guid = value;
859 if(action == 'A' && (!machine_guid || !machine_url || !url_name)) {
860 buffer_flush(w->response.data);
861 buffer_sprintf(w->response.data, "Invalid registry request - access requires these parameters: machine ('%s'), url ('%s'), name ('%s')",
862 machine_guid?machine_guid:"UNSET", machine_url?machine_url:"UNSET", url_name?url_name:"UNSET");
865 else if(action == 'D' && (!machine_guid || !machine_url || !delete_url)) {
866 buffer_flush(w->response.data);
867 buffer_sprintf(w->response.data, "Invalid registry request - delete requires these parameters: machine ('%s'), url ('%s'), delete_url ('%s')",
868 machine_guid?machine_guid:"UNSET", machine_url?machine_url:"UNSET", delete_url?delete_url:"UNSET");
871 else if(action == 'S' && (!machine_guid || !machine_url || !search_machine_guid)) {
872 buffer_flush(w->response.data);
873 buffer_sprintf(w->response.data, "Invalid registry request - search requires these parameters: machine ('%s'), url ('%s'), for ('%s')",
874 machine_guid?machine_guid:"UNSET", machine_url?machine_url:"UNSET", search_machine_guid?search_machine_guid:"UNSET");
877 else if(action == 'W' && (!machine_guid || !machine_url || !to_person_guid)) {
878 buffer_flush(w->response.data);
879 buffer_sprintf(w->response.data, "Invalid registry request - switching identity requires these parameters: machine ('%s'), url ('%s'), to ('%s')",
880 machine_guid?machine_guid:"UNSET", machine_url?machine_url:"UNSET", to_person_guid?to_person_guid:"UNSET");
886 return registry_request_access_json(w, person_guid, machine_guid, machine_url, url_name, time(NULL));
889 return registry_request_delete_json(w, person_guid, machine_guid, machine_url, delete_url, time(NULL));
892 return registry_request_search_json(w, person_guid, machine_guid, machine_url, search_machine_guid, time(NULL));
895 return registry_request_switch_json(w, person_guid, machine_guid, machine_url, to_person_guid, time(NULL));
898 return registry_request_hello_json(w);
901 buffer_flush(w->response.data);
902 buffer_sprintf(w->response.data, "Invalid registry request - you need to set an action: hello, access, delete, search");
906 buffer_flush(w->response.data);
907 buffer_sprintf(w->response.data, "Invalid or no registry action.");
911 int web_client_api_request_v1(struct web_client *w, char *url)
913 static uint32_t data_hash = 0, chart_hash = 0, charts_hash = 0, registry_hash = 0;
915 if(unlikely(data_hash == 0)) {
916 data_hash = simple_hash("data");
917 chart_hash = simple_hash("chart");
918 charts_hash = simple_hash("charts");
919 registry_hash = simple_hash("registry");
923 char *tok = mystrsep(&url, "/?&");
925 debug(D_WEB_CLIENT, "%llu: Searching for API v1 command '%s'.", w->id, tok);
926 uint32_t hash = simple_hash(tok);
928 if(hash == data_hash && !strcmp(tok, "data"))
929 return web_client_api_request_v1_data(w, url);
931 else if(hash == chart_hash && !strcmp(tok, "chart"))
932 return web_client_api_request_v1_chart(w, url);
934 else if(hash == charts_hash && !strcmp(tok, "charts"))
935 return web_client_api_request_v1_charts(w, url);
937 else if(hash == registry_hash && !strcmp(tok, "registry"))
938 return web_client_api_request_v1_registry(w, url);
941 buffer_flush(w->response.data);
942 buffer_sprintf(w->response.data, "Unsupported v1 API command: %s", tok);
947 buffer_flush(w->response.data);
948 buffer_sprintf(w->response.data, "API v1 command?");
953 int web_client_api_request(struct web_client *w, char *url)
955 // get the api version
956 char *tok = mystrsep(&url, "/?&");
958 debug(D_WEB_CLIENT, "%llu: Searching for API version '%s'.", w->id, tok);
959 if(strcmp(tok, "v1") == 0)
960 return web_client_api_request_v1(w, url);
962 buffer_flush(w->response.data);
963 buffer_sprintf(w->response.data, "Unsupported API version: %s", tok);
968 buffer_flush(w->response.data);
969 buffer_sprintf(w->response.data, "Which API version?");
974 int web_client_data_request(struct web_client *w, char *url, int datasource_type)
978 char *args = strchr(url, '?');
984 // get the name of the data to show
985 char *tok = mystrsep(&url, "/");
987 // do we have such a data set?
989 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
990 st = rrdset_find_byname(tok);
991 if(!st) st = rrdset_find(tok);
996 // try to send a file with that name
997 buffer_flush(w->response.data);
998 return(mysendfile(w, tok));
1002 debug(D_WEB_CLIENT, "%llu: Found RRD data with name '%s'.", w->id, tok);
1004 // how many entries does the client want?
1005 long lines = rrd_default_history_entries;
1006 long group_count = 1;
1007 time_t after = 0, before = 0;
1008 int group_method = GROUP_AVERAGE;
1012 // parse the lines required
1013 tok = mystrsep(&url, "/");
1014 if(tok) lines = atoi(tok);
1015 if(lines < 1) lines = 1;
1018 // parse the group count required
1019 tok = mystrsep(&url, "/");
1020 if(tok && *tok) group_count = atoi(tok);
1021 if(group_count < 1) group_count = 1;
1022 //if(group_count > save_history / 20) group_count = save_history / 20;
1025 // parse the grouping method required
1026 tok = mystrsep(&url, "/");
1028 if(strcmp(tok, "max") == 0) group_method = GROUP_MAX;
1029 else if(strcmp(tok, "average") == 0) group_method = GROUP_AVERAGE;
1030 else if(strcmp(tok, "sum") == 0) group_method = GROUP_SUM;
1031 else debug(D_WEB_CLIENT, "%llu: Unknown group method '%s'", w->id, tok);
1036 tok = mystrsep(&url, "/");
1037 if(tok && *tok) after = strtoul(tok, NULL, 10);
1038 if(after < 0) after = 0;
1041 // parse before time
1042 tok = mystrsep(&url, "/");
1043 if(tok && *tok) before = strtoul(tok, NULL, 10);
1044 if(before < 0) before = 0;
1048 tok = mystrsep(&url, "/");
1049 if(tok && *tok && strcmp(tok, "nonzero") == 0) nonzero = 1;
1052 w->response.data->contenttype = CT_APPLICATION_JSON;
1053 buffer_flush(w->response.data);
1055 char *google_version = "0.6";
1056 char *google_reqId = "0";
1057 char *google_sig = "0";
1058 char *google_out = "json";
1059 char *google_responseHandler = "google.visualization.Query.setResponse";
1060 char *google_outFileName = NULL;
1061 time_t last_timestamp_in_data = 0;
1062 if(datasource_type == DATASOURCE_DATATABLE_JSON || datasource_type == DATASOURCE_DATATABLE_JSONP) {
1064 w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
1067 tok = mystrsep(&args, "&");
1069 char *name = mystrsep(&tok, "=");
1070 if(name && *name && strcmp(name, "tqx") == 0) {
1071 char *key = mystrsep(&tok, ":");
1072 char *value = mystrsep(&tok, ";");
1073 if(key && value && *key && *value) {
1074 if(strcmp(key, "version") == 0)
1075 google_version = value;
1077 else if(strcmp(key, "reqId") == 0)
1078 google_reqId = value;
1080 else if(strcmp(key, "sig") == 0)
1083 else if(strcmp(key, "out") == 0)
1086 else if(strcmp(key, "responseHandler") == 0)
1087 google_responseHandler = value;
1089 else if(strcmp(key, "outFileName") == 0)
1090 google_outFileName = value;
1096 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
1097 w->id, google_version, google_reqId, google_sig, google_out, google_responseHandler, google_outFileName
1100 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
1101 last_timestamp_in_data = strtoul(google_sig, NULL, 0);
1103 // check the client wants json
1104 if(strcmp(google_out, "json") != 0) {
1105 buffer_sprintf(w->response.data,
1106 "%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.'}]});",
1107 google_responseHandler, google_version, google_reqId, google_out);
1113 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
1114 buffer_sprintf(w->response.data,
1115 "%s({version:'%s',reqId:'%s',status:'ok',sig:'%lu',table:",
1116 google_responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
1119 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);
1120 time_t timestamp_in_data = rrd_stats_json(datasource_type, st, w->response.data, lines, group_count, group_method, after, before, nonzero);
1122 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
1123 if(timestamp_in_data > last_timestamp_in_data)
1124 buffer_strcat(w->response.data, "});");
1127 // the client already has the latest data
1128 buffer_flush(w->response.data);
1129 buffer_sprintf(w->response.data,
1130 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
1131 google_responseHandler, google_version, google_reqId);
1139 int web_client_parse_request(struct web_client *w) {
1143 // query string name-value
1146 // http request headers name-value
1148 web_client_clean_request(w);
1150 debug(D_WEB_DATA, "%llu: Processing data buffer of %d bytes: '%s'.", w->id, w->response.data->bytes, w->response.data->buffer);
1152 char *buf = w->response.data->buffer;
1155 // ------------------------------------------------------------------------
1158 if(buf && (line = strsep(&buf, "\r\n"))) {
1160 if(line && (tok = strsep(&line, " "))) {
1161 w->request.protocol = strdup(tok);
1169 // ------------------------------------------------------------------------
1170 // the rest of the lines
1172 while(buf && (line = strsep(&buf, "\r\n"))) {
1173 while(line && (tok = strsep(&line, ": "))) {
1181 web_client_clean_request(w);
1187 static inline char *http_header_parse(struct web_client *w, char *s) {
1191 while(*e && *e != ':') e++;
1192 if(!*e || e[1] != ' ') return e;
1202 while(*ve && *ve != '\r') ve++;
1203 if(!*ve || ve[1] != '\n') {
1208 // terminate the value
1211 // fprintf(stderr, "HEADER: '%s' = '%s'\n", s, v);
1213 if(!strcasecmp(s, "Origin")) {
1214 strncpy(w->origin, v, ORIGIN_MAX);
1216 else if(!strcasecmp(s, "Connection")) {
1217 if(strcasestr(v, "keep-alive"))
1220 #ifdef NETDATA_WITH_ZLIB
1221 else if(!strcasecmp(s, "Accept-Encoding")) {
1222 if(web_enable_gzip && strcasestr(v, "gzip")) {
1226 #endif /* NETDATA_WITH_ZLIB */
1233 // http_request_validate()
1235 // = 0 : all good, process the request
1236 // > 0 : request is complete, but is not supported
1237 // < 0 : request is incomplete - wait for more data
1239 static inline int http_request_validate(struct web_client *w) {
1240 char *s = w->response.data->buffer, *encoded_url = NULL;
1242 // is is a valid request?
1243 if(!strncmp(s, "GET ", 4)) {
1244 encoded_url = s = &s[4];
1245 w->mode = WEB_CLIENT_MODE_NORMAL;
1247 else if(!strncmp(s, "OPTIONS ", 8)) {
1248 encoded_url = s = &s[8];
1249 w->mode = WEB_CLIENT_MODE_OPTIONS;
1252 w->wait_receive = 0;
1256 // find the SPACE + "HTTP/"
1259 while (*s && *s != ' ') s++;
1261 // is it SPACE + "HTTP/" ?
1262 if(*s && !strncmp(s, " HTTP/", 6)) break;
1266 // incomplete requests
1268 w->wait_receive = 1;
1272 // we have the end of encoded_url - remember it
1277 while (*s && *s != '\r') s++;
1279 // did we reach the end?
1280 if(unlikely(!*s)) break;
1283 if (likely(s[1] == '\n')) {
1285 // is it again \r\n ? (header end)
1286 if(unlikely(s[2] == '\r' && s[3] == '\n')) {
1287 // a valid complete HTTP request found
1290 w->decoded_url = url_decode(encoded_url);
1293 w->wait_receive = 0;
1297 // another header line
1298 s = http_header_parse(w, &s[2]);
1303 // incomplete request
1304 w->wait_receive = 1;
1308 void web_client_process(struct web_client *w) {
1312 int what_to_do = http_request_validate(w);
1314 // wait for more data
1315 if(what_to_do < 0) {
1316 if(w->response.data->len > TOO_BIG_REQUEST) {
1317 strcpy(w->last_url, "too big request");
1319 debug(D_WEB_CLIENT_ACCESS, "%llu: Received request is too big (%zd bytes).", w->id, w->response.data->len);
1322 buffer_flush(w->response.data);
1323 buffer_sprintf(w->response.data, "Received request is too big (%zd bytes).\r\n", w->response.data->len);
1326 // wait for more data
1330 else if(what_to_do > 0) {
1331 strcpy(w->last_url, "not a valid response");
1333 debug(D_WEB_CLIENT_ACCESS, "%llu: Cannot understand '%s'.", w->id, w->response.data->buffer);
1337 buffer_flush(w->response.data);
1338 buffer_strcat(w->response.data, "I don't understand you...\r\n");
1340 else { // what_to_do == 0
1341 gettimeofday(&w->tv_in, NULL);
1343 global_statistics_lock();
1344 global_statistics.web_requests++;
1345 global_statistics_unlock();
1347 if(w->mode == WEB_CLIENT_MODE_OPTIONS) {
1348 strncpyz(w->last_url, url, URL_MAX);
1349 >>>>>>> fredericopissarra/changes
1351 // copy the URL - we are going to overwrite parts of it
1352 // FIXME -- we should avoid it
1353 strncpy(w->last_url, w->decoded_url, URL_MAX);
1354 w->last_url[URL_MAX] = '\0';
1356 if(w->mode == WEB_CLIENT_MODE_OPTIONS) {
1358 w->response.data->contenttype = CT_TEXT_PLAIN;
1359 buffer_flush(w->response.data);
1360 buffer_strcat(w->response.data, "OK");
1363 #ifdef NETDATA_WITH_ZLIB
1365 web_client_enable_deflate(w);
1369 char *url = w->decoded_url;
1370 char *tok = mystrsep(&url, "/?");
1372 strncpyz(w->last_url, url, URL_MAX);
1374 tok = mystrsep(&url, "/?");
1375 >>>>>>> fredericopissarra/changes
1377 debug(D_WEB_CLIENT, "%llu: Processing command '%s'.", w->id, tok);
1379 if(strcmp(tok, "api") == 0) {
1380 // the client is requesting api access
1381 code = web_client_api_request(w, url);
1383 else if(strcmp(tok, "netdata.conf") == 0) {
1385 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending netdata.conf ...", w->id);
1387 w->response.data->contenttype = CT_TEXT_PLAIN;
1388 buffer_flush(w->response.data);
1389 generate_config(w->response.data, 0);
1391 else if(strcmp(tok, WEB_PATH_DATA) == 0) { // "data"
1392 // the client is requesting rrd data -- OLD API
1393 code = web_client_data_request(w, url, DATASOURCE_JSON);
1395 else if(strcmp(tok, WEB_PATH_DATASOURCE) == 0) { // "datasource"
1396 // the client is requesting google datasource -- OLD API
1397 code = web_client_data_request(w, url, DATASOURCE_DATATABLE_JSONP);
1399 else if(strcmp(tok, WEB_PATH_GRAPH) == 0) { // "graph"
1400 // the client is requesting an rrd graph -- OLD API
1402 // get the name of the data to show
1403 tok = mystrsep(&url, "/?&");
1405 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1407 // do we have such a data set?
1408 RRDSET *st = rrdset_find_byname(tok);
1409 if(!st) st = rrdset_find(tok);
1412 // try to send a file with that name
1413 buffer_flush(w->response.data);
1414 code = mysendfile(w, tok);
1418 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending %s.json of RRD_STATS...", w->id, st->name);
1419 w->response.data->contenttype = CT_APPLICATION_JSON;
1420 buffer_flush(w->response.data);
1421 rrd_stats_graph_json(st, url, w->response.data);
1426 buffer_flush(w->response.data);
1427 buffer_strcat(w->response.data, "Graph name?\r\n");
1430 else if(strcmp(tok, "list") == 0) {
1434 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending list of RRD_STATS...", w->id);
1436 buffer_flush(w->response.data);
1437 RRDSET *st = rrdset_root;
1439 for ( ; st ; st = st->next )
1440 buffer_sprintf(w->response.data, "%s\n", st->name);
1442 else if(strcmp(tok, "all.json") == 0) {
1445 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending JSON list of all monitors of RRD_STATS...", w->id);
1447 w->response.data->contenttype = CT_APPLICATION_JSON;
1448 buffer_flush(w->response.data);
1449 rrd_stats_all_json(w->response.data);
1451 #ifdef NETDATA_INTERNAL_CHECKS
1452 else if(strcmp(tok, "exit") == 0) {
1454 w->response.data->contenttype = CT_TEXT_PLAIN;
1455 buffer_flush(w->response.data);
1458 buffer_strcat(w->response.data, "ok, will do...");
1460 buffer_strcat(w->response.data, "I am doing it already");
1464 else if(strcmp(tok, "debug") == 0) {
1465 buffer_flush(w->response.data);
1467 // get the name of the data to show
1468 tok = mystrsep(&url, "/?&");
1470 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1472 // do we have such a data set?
1473 RRDSET *st = rrdset_find_byname(tok);
1474 if(!st) st = rrdset_find(tok);
1477 buffer_sprintf(w->response.data, "Chart %s is not found.\r\n", tok);
1478 debug(D_WEB_CLIENT_ACCESS, "%llu: %s is not found.", w->id, tok);
1482 debug_flags |= D_RRD_STATS;
1483 st->debug = !st->debug;
1484 buffer_sprintf(w->response.data, "Chart %s has now debug %s.\r\n", tok, st->debug?"enabled":"disabled");
1485 debug(D_WEB_CLIENT_ACCESS, "%llu: debug for %s is %s.", w->id, tok, st->debug?"enabled":"disabled");
1490 buffer_flush(w->response.data);
1491 buffer_strcat(w->response.data, "debug which chart?\r\n");
1494 else if(strcmp(tok, "mirror") == 0) {
1497 debug(D_WEB_CLIENT_ACCESS, "%llu: Mirroring...", w->id);
1499 // replace the zero bytes with spaces
1500 buffer_char_replace(w->response.data, '\0', ' ');
1502 // just leave the buffer as is
1503 // it will be copied back to the client
1505 #endif /* NETDATA_INTERNAL_CHECKS */
1507 char filename[FILENAME_MAX+1];
1509 strncpyz(filename, w->last_url, FILENAME_MAX);
1510 tok = mystrsep(&url, "?");
1511 buffer_flush(w->response.data);
1512 code = mysendfile(w, (tok && *tok)?tok:"/");
1516 char filename[FILENAME_MAX+1];
1518 strncpyz(filename, w->last_url, FILENAME_MAX);
1519 tok = mystrsep(&url, "?");
1520 buffer_flush(w->response.data);
1521 code = mysendfile(w, (tok && *tok)?tok:"/");
1526 gettimeofday(&w->tv_ready, NULL);
1527 w->response.data->date = time(NULL);
1528 w->response.sent = 0;
1529 w->response.code = code;
1531 // prepare the HTTP response header
1532 debug(D_WEB_CLIENT, "%llu: Generating HTTP header with response %d.", w->id, code);
1534 char *content_type_string;
1535 switch(w->response.data->contenttype) {
1537 content_type_string = "text/html; charset=utf-8";
1540 case CT_APPLICATION_XML:
1541 content_type_string = "application/xml; charset=utf-8";
1544 case CT_APPLICATION_JSON:
1545 content_type_string = "application/json; charset=utf-8";
1548 case CT_APPLICATION_X_JAVASCRIPT:
1549 content_type_string = "application/x-javascript; charset=utf-8";
1553 content_type_string = "text/css; charset=utf-8";
1557 content_type_string = "text/xml; charset=utf-8";
1561 content_type_string = "text/xsl; charset=utf-8";
1564 case CT_APPLICATION_OCTET_STREAM:
1565 content_type_string = "application/octet-stream";
1568 case CT_IMAGE_SVG_XML:
1569 content_type_string = "image/svg+xml";
1572 case CT_APPLICATION_X_FONT_TRUETYPE:
1573 content_type_string = "application/x-font-truetype";
1576 case CT_APPLICATION_X_FONT_OPENTYPE:
1577 content_type_string = "application/x-font-opentype";
1580 case CT_APPLICATION_FONT_WOFF:
1581 content_type_string = "application/font-woff";
1584 case CT_APPLICATION_FONT_WOFF2:
1585 content_type_string = "application/font-woff2";
1588 case CT_APPLICATION_VND_MS_FONTOBJ:
1589 content_type_string = "application/vnd.ms-fontobject";
1593 content_type_string = "image/png";
1597 content_type_string = "image/jpeg";
1601 content_type_string = "image/gif";
1604 case CT_IMAGE_XICON:
1605 content_type_string = "image/x-icon";
1609 content_type_string = "image/bmp";
1613 content_type_string = "image/icns";
1618 content_type_string = "text/plain; charset=utf-8";
1629 code_msg = "Temporary Redirect";
1633 code_msg = "Bad Request";
1637 code_msg = "Forbidden";
1641 code_msg = "Not Found";
1645 code_msg = "Preconditions Failed";
1649 code_msg = "Internal Server Error";
1654 struct tm tmbuf, *tm = gmtime_r(&w->response.data->date, &tmbuf);
1655 strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %Z", tm);
1657 buffer_sprintf(w->response.header_output,
1658 "HTTP/1.1 %d %s\r\n"
1659 "Connection: %s\r\n"
1660 "Server: NetData Embedded HTTP Server\r\n"
1661 "Access-Control-Allow-Origin: %s\r\n"
1662 "Access-Control-Allow-Credentials: true\r\n"
1663 "Content-Type: %s\r\n"
1666 , w->keepalive?"keep-alive":"close"
1668 , content_type_string
1673 buffer_sprintf(w->response.header_output,
1674 "Set-Cookie: %s\r\n",
1678 if(w->mode == WEB_CLIENT_MODE_OPTIONS) {
1679 buffer_strcat(w->response.header_output,
1680 "Access-Control-Allow-Methods: GET, OPTIONS\r\n"
1681 "Access-Control-Allow-Headers: accept, x-requested-with, origin, content-type, cookie\r\n"
1682 "Access-Control-Max-Age: 1209600\r\n" // 86400 * 14
1686 if(buffer_strlen(w->response.header))
1687 buffer_strcat(w->response.header_output, buffer_tostring(w->response.header));
1689 if(w->mode == WEB_CLIENT_MODE_NORMAL && (w->response.data->options & WB_CONTENT_NO_CACHEABLE)) {
1690 buffer_sprintf(w->response.header_output,
1692 "Cache-Control: no-cache\r\n"
1695 else if(w->mode != WEB_CLIENT_MODE_OPTIONS) {
1697 time_t et = w->response.data->date + (86400 * 14);
1698 struct tm etmbuf, *etm = gmtime_r(&et, &etmbuf);
1699 strftime(edate, sizeof(edate), "%a, %d %b %Y %H:%M:%S %Z", etm);
1701 buffer_sprintf(w->response.header_output,
1703 "Cache-Control: public\r\n"
1707 // if we know the content length, put it
1708 if(!w->response.zoutput && (w->response.data->len || w->response.rlen))
1709 buffer_sprintf(w->response.header_output,
1710 "Content-Length: %ld\r\n"
1711 , w->response.data->len? w->response.data->len: w->response.rlen
1713 else if(!w->response.zoutput)
1714 w->keepalive = 0; // content-length is required for keep-alive
1716 if(w->response.zoutput) {
1717 buffer_strcat(w->response.header_output,
1718 "Content-Encoding: gzip\r\n"
1719 "Transfer-Encoding: chunked\r\n"
1723 buffer_strcat(w->response.header_output, "\r\n");
1725 // disable TCP_NODELAY, to buffer the header
1727 if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0)
1728 error("%llu: failed to disable TCP_NODELAY on socket.", w->id);
1730 // sent the HTTP header
1731 debug(D_WEB_DATA, "%llu: Sending response HTTP header of size %d: '%s'"
1733 , buffer_strlen(w->response.header_output)
1734 , buffer_tostring(w->response.header_output)
1737 bytes = send(w->ofd, buffer_tostring(w->response.header_output), buffer_strlen(w->response.header_output), 0);
1738 if(bytes != (ssize_t) buffer_strlen(w->response.header_output))
1739 error("%llu: HTTP Header failed to be sent (I sent %d bytes but the system sent %d bytes)."
1741 , buffer_strlen(w->response.header_output)
1744 global_statistics_lock();
1745 global_statistics.bytes_sent += bytes;
1746 global_statistics_unlock();
1749 // enable TCP_NODELAY, to send all data immediately at the next send()
1751 if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0) error("%llu: failed to enable TCP_NODELAY on socket.", w->id);
1753 // enable sending immediately if we have data
1754 if(w->response.data->len) w->wait_send = 1;
1755 else w->wait_send = 0;
1759 case WEB_CLIENT_MODE_OPTIONS:
1760 debug(D_WEB_CLIENT, "%llu: Done preparing the OPTIONS response. Sending data (%d bytes) to client.", w->id, w->response.data->len);
1763 case WEB_CLIENT_MODE_NORMAL:
1764 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Sending data (%d bytes) to client.", w->id, w->response.data->len);
1767 case WEB_CLIENT_MODE_FILECOPY:
1768 if(w->response.rlen) {
1769 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending data file of %d bytes to client.", w->id, w->response.rlen);
1770 w->wait_receive = 1;
1773 // utilize the kernel sendfile() for copying the file to the socket.
1774 // this block of code can be commented, without anything missing.
1775 // when it is commented, the program will copy the data using async I/O.
1777 long len = sendfile(w->ofd, w->ifd, NULL, w->response.data->rbytes);
1778 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);
1779 else web_client_reset(w);
1784 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending an unknown amount of bytes to client.", w->id);
1788 fatal("%llu: Unknown client mode %d.", w->id, w->mode);
1793 long web_client_send_chunk_header(struct web_client *w, long len)
1795 debug(D_DEFLATE, "%llu: OPEN CHUNK of %d bytes (hex: %x).", w->id, len, len);
1797 sprintf(buf, "%lX\r\n", len);
1798 ssize_t bytes = send(w->ofd, buf, strlen(buf), MSG_DONTWAIT);
1800 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk header %d bytes.", w->id, bytes);
1801 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk header to the client.", w->id);
1802 else debug(D_DEFLATE, "%llu: Failed to send chunk header to client.", w->id);
1807 long web_client_send_chunk_close(struct web_client *w)
1809 //debug(D_DEFLATE, "%llu: CLOSE CHUNK.", w->id);
1811 ssize_t bytes = send(w->ofd, "\r\n", 2, MSG_DONTWAIT);
1813 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
1814 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
1815 else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client.", w->id);
1820 long web_client_send_chunk_finalize(struct web_client *w)
1822 //debug(D_DEFLATE, "%llu: FINALIZE CHUNK.", w->id);
1824 ssize_t bytes = send(w->ofd, "\r\n0\r\n\r\n", 7, MSG_DONTWAIT);
1826 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
1827 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
1828 else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client.", w->id);
1833 #ifdef NETDATA_WITH_ZLIB
1834 long web_client_send_deflate(struct web_client *w)
1836 long len = 0, t = 0;
1838 // when using compression,
1839 // w->response.sent is the amount of bytes passed through compression
1841 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);
1843 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) {
1844 // there is nothing to send
1846 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1848 // finalize the chunk
1849 if(w->response.sent != 0)
1850 t += web_client_send_chunk_finalize(w);
1852 // there can be two cases for this
1853 // A. we have done everything
1854 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
1856 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->response.rlen && w->response.rlen > w->response.data->len) {
1857 // we have to wait, more data will come
1858 debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1863 if(w->keepalive == 0) {
1864 debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->response.sent);
1870 web_client_reset(w);
1871 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1875 if(w->response.zhave == w->response.zsent) {
1876 // compress more input data
1878 // close the previous open chunk
1879 if(w->response.sent != 0) t += web_client_send_chunk_close(w);
1881 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);
1883 // give the compressor all the data not passed through the compressor yet
1884 if(w->response.data->len > w->response.sent) {
1885 #ifdef NETDATA_INTERNAL_CHECKS
1886 if((long)w->response.sent - (long)w->response.zstream.avail_in < 0)
1887 error("internal error: avail_in is corrupted.");
1889 w->response.zstream.next_in = (Bytef *)&w->response.data->buffer[w->response.sent - w->response.zstream.avail_in];
1890 w->response.zstream.avail_in += (uInt) (w->response.data->len - w->response.sent);
1893 // reset the compressor output buffer
1894 w->response.zstream.next_out = w->response.zbuffer;
1895 w->response.zstream.avail_out = ZLIB_CHUNK;
1897 // ask for FINISH if we have all the input
1898 int flush = Z_SYNC_FLUSH;
1899 if(w->mode == WEB_CLIENT_MODE_NORMAL
1900 || (w->mode == WEB_CLIENT_MODE_FILECOPY && !w->wait_receive && w->response.data->len == w->response.rlen)) {
1902 debug(D_DEFLATE, "%llu: Requesting Z_FINISH, if possible.", w->id);
1905 debug(D_DEFLATE, "%llu: Requesting Z_SYNC_FLUSH.", w->id);
1909 if(deflate(&w->response.zstream, flush) == Z_STREAM_ERROR) {
1910 error("%llu: Compression failed. Closing down client.", w->id);
1911 web_client_reset(w);
1915 w->response.zhave = ZLIB_CHUNK - w->response.zstream.avail_out;
1916 w->response.zsent = 0;
1918 // keep track of the bytes passed through the compressor
1919 w->response.sent = w->response.data->len;
1921 debug(D_DEFLATE, "%llu: Compression produced %d bytes.", w->id, w->response.zhave);
1924 t += web_client_send_chunk_header(w, w->response.zhave);
1927 debug(D_WEB_CLIENT, "%llu: Sending %d bytes of data (+%d of chunk header).", w->id, w->response.zhave - w->response.zsent, t);
1929 len = send(w->ofd, &w->response.zbuffer[w->response.zsent], (size_t) (w->response.zhave - w->response.zsent), MSG_DONTWAIT);
1931 w->response.zsent += len;
1933 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, len);
1935 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);
1936 else debug(D_WEB_CLIENT, "%llu: Failed to send data to client. Reason: %s", w->id, strerror(errno));
1940 #endif // NETDATA_WITH_ZLIB
1942 long web_client_send(struct web_client *w)
1944 #ifdef NETDATA_WITH_ZLIB
1945 if(likely(w->response.zoutput)) return web_client_send_deflate(w);
1946 #endif // NETDATA_WITH_ZLIB
1950 if(unlikely(w->response.data->len - w->response.sent == 0)) {
1951 // there is nothing to send
1953 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1955 // there can be two cases for this
1956 // A. we have done everything
1957 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
1959 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->response.rlen && w->response.rlen > w->response.data->len) {
1960 // we have to wait, more data will come
1961 debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1966 if(unlikely(w->keepalive == 0)) {
1967 debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->response.sent);
1972 web_client_reset(w);
1973 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1977 bytes = send(w->ofd, &w->response.data->buffer[w->response.sent], w->response.data->len - w->response.sent, MSG_DONTWAIT);
1978 if(likely(bytes > 0)) {
1979 w->response.sent += bytes;
1980 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, bytes);
1982 else if(likely(bytes == 0)) debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client.", w->id);
1983 else debug(D_WEB_CLIENT, "%llu: Failed to send data to client.", w->id);
1988 long web_client_receive(struct web_client *w)
1990 // do we have any space for more data?
1991 buffer_need_bytes(w->response.data, WEB_REQUEST_LENGTH);
1993 long left = w->response.data->size - w->response.data->len;
1996 if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY))
1997 bytes = read(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1));
1999 bytes = recv(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1), MSG_DONTWAIT);
2001 if(likely(bytes > 0)) {
2002 size_t old = w->response.data->len;
2003 w->response.data->len += bytes;
2004 w->response.data->buffer[w->response.data->len] = '\0';
2006 debug(D_WEB_CLIENT, "%llu: Received %d bytes.", w->id, bytes);
2007 debug(D_WEB_DATA, "%llu: Received data: '%s'.", w->id, &w->response.data->buffer[old]);
2009 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
2011 if(w->response.rlen && w->response.data->len >= w->response.rlen) w->wait_receive = 0;
2014 else if(likely(bytes == 0)) {
2015 debug(D_WEB_CLIENT, "%llu: Out of input data.", w->id);
2017 // if we cannot read, it means we have an error on input.
2018 // if however, we are copying a file from ifd to ofd, we should not return an error.
2019 // in this case, the error should be generated when the file has been sent to the client.
2021 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
2022 // we are copying data from ifd to ofd
2023 // let it finish copying...
2024 w->wait_receive = 0;
2025 debug(D_WEB_CLIENT, "%llu: Disabling input.", w->id);
2037 // --------------------------------------------------------------------------------------
2038 // the thread of a single client
2040 // 1. waits for input and output, using async I/O
2041 // 2. it processes HTTP requests
2042 // 3. it generates HTTP responses
2043 // 4. it copies data from input to output if mode is FILECOPY
2045 void *web_client_main(void *ptr)
2047 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
2048 error("Cannot set pthread cancel type to DEFERRED.");
2050 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
2051 error("Cannot set pthread cancel state to ENABLE.");
2054 struct web_client *w = ptr;
2056 fd_set ifds, ofds, efds;
2059 log_access("%llu: %s port %s connected on thread task id %d", w->id, w->client_ip, w->client_port, gettid());
2066 FD_SET(w->ifd, &efds);
2068 if(w->ifd != w->ofd)
2069 FD_SET(w->ofd, &efds);
2071 if (w->wait_receive) {
2072 FD_SET(w->ifd, &ifds);
2073 if(w->ifd > fdmax) fdmax = w->ifd;
2077 FD_SET(w->ofd, &ofds);
2078 if(w->ofd > fdmax) fdmax = w->ofd;
2081 tv.tv_sec = web_client_timeout;
2084 debug(D_WEB_CLIENT, "%llu: Waiting socket async I/O for %s %s", w->id, w->wait_receive?"INPUT":"", w->wait_send?"OUTPUT":"");
2085 retval = select(fdmax+1, &ifds, &ofds, &efds, &tv);
2088 debug(D_WEB_CLIENT_ACCESS, "%llu: LISTENER: select() failed.", w->id);
2093 debug(D_WEB_CLIENT_ACCESS, "%llu: LISTENER: timeout.", w->id);
2097 if(FD_ISSET(w->ifd, &efds)) {
2098 debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on input socket.", w->id);
2102 if(FD_ISSET(w->ofd, &efds)) {
2103 debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on output socket.", w->id);
2107 if(w->wait_send && FD_ISSET(w->ofd, &ofds)) {
2109 if((bytes = web_client_send(w)) < 0) {
2110 debug(D_WEB_CLIENT, "%llu: Cannot send data to client. Closing client.", w->id);
2115 global_statistics_lock();
2116 global_statistics.bytes_sent += bytes;
2117 global_statistics_unlock();
2120 if(w->wait_receive && FD_ISSET(w->ifd, &ifds)) {
2122 if((bytes = web_client_receive(w)) < 0) {
2123 debug(D_WEB_CLIENT, "%llu: Cannot receive data from client. Closing client.", w->id);
2128 if(w->mode == WEB_CLIENT_MODE_NORMAL) {
2129 debug(D_WEB_CLIENT, "%llu: Attempting to process received data (%ld bytes).", w->id, bytes);
2130 // info("%llu: Attempting to process received data (%ld bytes).", w->id, bytes);
2131 web_client_process(w);
2134 global_statistics_lock();
2135 global_statistics.bytes_received += bytes;
2136 global_statistics_unlock();
2140 log_access("%llu: %s port %s disconnected from thread task id %d", w->id, w->client_ip, w->client_port, gettid());
2141 debug(D_WEB_CLIENT, "%llu: done...", w->id);
2143 web_client_reset(w);