7 #include <sys/socket.h>
8 #include <netinet/in.h>
14 #include <netinet/tcp.h>
21 #include "appconfig.h"
23 #include "web_buffer.h"
24 #include "web_server.h"
25 #include "global_statistics.h"
29 #include "web_client.h"
31 #define INITIAL_WEB_DATA_LENGTH 16384
32 #define WEB_REQUEST_LENGTH 16384
33 #define TOO_BIG_REQUEST 16384
35 int web_client_timeout = DEFAULT_DISCONNECT_IDLE_WEB_CLIENTS_AFTER_SECONDS;
36 int web_enable_gzip = 1;
38 extern int netdata_exit;
40 struct web_client *web_clients = NULL;
41 unsigned long long web_clients_count = 0;
43 struct web_client *web_client_create(int listener)
47 w = calloc(1, sizeof(struct web_client));
49 error("Cannot allocate new web_client memory.");
53 w->id = ++web_clients_count;
54 w->mode = WEB_CLIENT_MODE_NORMAL;
57 struct sockaddr *sadr;
60 sadr = (struct sockaddr*) &w->clientaddr;
61 addrlen = sizeof(w->clientaddr);
63 w->ifd = accept(listener, sadr, &addrlen);
65 error("%llu: Cannot accept new incoming connection.", w->id);
71 if(getnameinfo(sadr, addrlen, w->client_ip, NI_MAXHOST, w->client_port, NI_MAXSERV, NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
72 error("Cannot getnameinfo() on received client connection.");
73 strncpy(w->client_ip, "UNKNOWN", NI_MAXHOST);
74 strncpy(w->client_port, "UNKNOWN", NI_MAXSERV);
76 w->client_ip[NI_MAXHOST] = '\0';
77 w->client_port[NI_MAXSERV] = '\0';
79 switch(sadr->sa_family) {
82 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);
86 if(strncmp(w->client_ip, "::ffff:", 7) == 0) {
87 strcpy(w->client_ip, &w->client_ip[7]);
88 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);
90 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);
94 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);
99 if(setsockopt(w->ifd, SOL_SOCKET, SO_KEEPALIVE, (char *) &flag, sizeof(int)) != 0) error("%llu: Cannot set SO_KEEPALIVE on socket.", w->id);
102 w->response.data = buffer_create(INITIAL_WEB_DATA_LENGTH);
103 if(unlikely(!w->response.data)) {
104 // no need for error log - web_buffer_create already logged the error
110 w->response.header = buffer_create(HTTP_RESPONSE_HEADER_SIZE);
111 if(unlikely(!w->response.header)) {
112 // no need for error log - web_buffer_create already logged the error
113 buffer_free(w->response.data);
119 w->response.header_output = buffer_create(HTTP_RESPONSE_HEADER_SIZE);
120 if(unlikely(!w->response.header_output)) {
121 // no need for error log - web_buffer_create already logged the error
122 buffer_free(w->response.header);
123 buffer_free(w->response.data);
131 if(web_clients) web_clients->prev = w;
132 w->next = web_clients;
135 global_statistics.connected_clients++;
140 void web_client_reset(struct web_client *w)
143 gettimeofday(&tv, NULL);
145 long sent = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->response.rlen:w->response.data->len;
147 #ifdef NETDATA_WITH_ZLIB
148 if(likely(w->response.zoutput)) sent = (long)w->response.zstream.total_out;
151 long size = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->response.rlen:w->response.data->len;
153 if(likely(w->last_url[0]))
154 log_access("%llu: (sent/all = %ld/%ld bytes %0.0f%%, prep/sent/total = %0.2f/%0.2f/%0.2f ms) %s: %d '%s'",
156 sent, size, -((size>0)?((float)(size-sent)/(float)size * 100.0):0.0),
157 (float)usecdiff(&w->tv_ready, &w->tv_in) / 1000.0,
158 (float)usecdiff(&tv, &w->tv_ready) / 1000.0,
159 (float)usecdiff(&tv, &w->tv_in) / 1000.0,
160 (w->mode == WEB_CLIENT_MODE_FILECOPY)?"filecopy":((w->mode == WEB_CLIENT_MODE_OPTIONS)?"options":"data"),
165 debug(D_WEB_CLIENT, "%llu: Reseting client.", w->id);
167 if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY)) {
168 debug(D_WEB_CLIENT, "%llu: Closing filecopy input file.", w->id);
173 w->last_url[0] = '\0';
175 w->mode = WEB_CLIENT_MODE_NORMAL;
177 buffer_reset(w->response.header_output);
178 buffer_reset(w->response.header);
179 buffer_reset(w->response.data);
180 w->response.rlen = 0;
181 w->response.sent = 0;
182 w->response.code = 0;
187 w->response.zoutput = 0;
189 // if we had enabled compression, release it
190 #ifdef NETDATA_WITH_ZLIB
191 if(w->response.zinitialized) {
192 debug(D_DEFLATE, "%llu: Reseting compression.", w->id);
193 deflateEnd(&w->response.zstream);
194 w->response.zsent = 0;
195 w->response.zhave = 0;
196 w->response.zstream.avail_in = 0;
197 w->response.zstream.avail_out = 0;
198 w->response.zstream.total_in = 0;
199 w->response.zstream.total_out = 0;
200 w->response.zinitialized = 0;
202 #endif // NETDATA_WITH_ZLIB
205 struct web_client *web_client_free(struct web_client *w)
207 struct web_client *n = w->next;
209 debug(D_WEB_CLIENT_ACCESS, "%llu: Closing web client from %s port %s.", w->id, w->client_ip, w->client_port);
211 if(w->prev) w->prev->next = w->next;
212 if(w->next) w->next->prev = w->prev;
214 if(w == web_clients) web_clients = w->next;
216 if(w->response.header_output) buffer_free(w->response.header_output);
217 if(w->response.header) buffer_free(w->response.header);
218 if(w->response.data) buffer_free(w->response.data);
220 if(w->ofd != w->ifd) close(w->ofd);
223 global_statistics.connected_clients--;
228 uid_t web_files_uid(void)
230 static char *web_owner = NULL;
231 static uid_t owner_uid = 0;
233 if(unlikely(!web_owner)) {
234 web_owner = config_get("global", "web files owner", NETDATA_USER);
235 if(!web_owner || !*web_owner)
236 owner_uid = geteuid();
238 struct passwd *pw = getpwnam(web_owner);
240 error("User %s is not present. Ignoring option.", web_owner);
241 owner_uid = geteuid();
244 debug(D_WEB_CLIENT, "Web files owner set to %s.\n", web_owner);
245 owner_uid = pw->pw_uid;
253 int mysendfile(struct web_client *w, char *filename)
255 static char *web_dir = NULL;
257 // initialize our static data
258 if(unlikely(!web_dir)) web_dir = config_get("global", "web files directory", WEB_DIR);
260 debug(D_WEB_CLIENT, "%llu: Looking for file '%s/%s'", w->id, web_dir, filename);
262 // skip leading slashes
263 while (*filename == '/') filename++;
265 // if the filename contain known paths, skip them
266 if(strncmp(filename, WEB_PATH_FILE "/", strlen(WEB_PATH_FILE) + 1) == 0) filename = &filename[strlen(WEB_PATH_FILE) + 1];
269 for(s = filename; *s ;s++) {
270 if( !isalnum(*s) && *s != '/' && *s != '.' && *s != '-' && *s != '_') {
271 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
272 buffer_sprintf(w->response.data, "File '%s' cannot be served. Filename contains invalid character '%c'", filename, *s);
277 // if the filename contains a .. refuse to serve it
278 if(strstr(filename, "..") != 0) {
279 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
280 buffer_sprintf(w->response.data, "File '%s' cannot be served. Relative filenames with '..' in them are not supported.", filename);
285 char webfilename[FILENAME_MAX + 1];
286 snprintf(webfilename, FILENAME_MAX, "%s/%s", web_dir, filename);
288 // check if the file exists
290 if(lstat(webfilename, &stat) != 0) {
291 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not found.", w->id, webfilename);
292 buffer_sprintf(w->response.data, "File '%s' does not exist, or is not accessible.", webfilename);
296 // check if the file is owned by expected user
297 if(stat.st_uid != web_files_uid()) {
298 error("%llu: File '%s' is owned by user %d (expected user %d). Access Denied.", w->id, webfilename, stat.st_uid, web_files_uid());
299 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", webfilename);
303 if((stat.st_mode & S_IFMT) == S_IFDIR) {
304 snprintf(webfilename, FILENAME_MAX+1, "%s/index.html", filename);
305 return mysendfile(w, webfilename);
308 if((stat.st_mode & S_IFMT) != S_IFREG) {
309 error("%llu: File '%s' is not a regular file. Access Denied.", w->id, webfilename);
310 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", webfilename);
315 w->ifd = open(webfilename, O_NONBLOCK, O_RDONLY);
319 if(errno == EBUSY || errno == EAGAIN) {
320 error("%llu: File '%s' is busy, sending 307 Moved Temporarily to force retry.", w->id, webfilename);
321 buffer_sprintf(w->response.header, "Location: /" WEB_PATH_FILE "/%s\r\n", filename);
322 buffer_sprintf(w->response.data, "The file '%s' is currently busy. Please try again later.", webfilename);
326 error("%llu: Cannot open file '%s'.", w->id, webfilename);
327 buffer_sprintf(w->response.data, "Cannot open file '%s'.", webfilename);
332 // pick a Content-Type for the file
333 if(strstr(filename, ".html") != NULL) w->response.data->contenttype = CT_TEXT_HTML;
334 else if(strstr(filename, ".js") != NULL) w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
335 else if(strstr(filename, ".css") != NULL) w->response.data->contenttype = CT_TEXT_CSS;
336 else if(strstr(filename, ".xml") != NULL) w->response.data->contenttype = CT_TEXT_XML;
337 else if(strstr(filename, ".xsl") != NULL) w->response.data->contenttype = CT_TEXT_XSL;
338 else if(strstr(filename, ".txt") != NULL) w->response.data->contenttype = CT_TEXT_PLAIN;
339 else if(strstr(filename, ".svg") != NULL) w->response.data->contenttype = CT_IMAGE_SVG_XML;
340 else if(strstr(filename, ".ttf") != NULL) w->response.data->contenttype = CT_APPLICATION_X_FONT_TRUETYPE;
341 else if(strstr(filename, ".otf") != NULL) w->response.data->contenttype = CT_APPLICATION_X_FONT_OPENTYPE;
342 else if(strstr(filename, ".woff2")!= NULL) w->response.data->contenttype = CT_APPLICATION_FONT_WOFF2;
343 else if(strstr(filename, ".woff") != NULL) w->response.data->contenttype = CT_APPLICATION_FONT_WOFF;
344 else if(strstr(filename, ".eot") != NULL) w->response.data->contenttype = CT_APPLICATION_VND_MS_FONTOBJ;
345 else if(strstr(filename, ".png") != NULL) w->response.data->contenttype = CT_IMAGE_PNG;
346 else if(strstr(filename, ".jpg") != NULL) w->response.data->contenttype = CT_IMAGE_JPG;
347 else if(strstr(filename, ".jpeg") != NULL) w->response.data->contenttype = CT_IMAGE_JPG;
348 else if(strstr(filename, ".gif") != NULL) w->response.data->contenttype = CT_IMAGE_GIF;
349 else if(strstr(filename, ".bmp") != NULL) w->response.data->contenttype = CT_IMAGE_BMP;
350 else if(strstr(filename, ".ico") != NULL) w->response.data->contenttype = CT_IMAGE_XICON;
351 else if(strstr(filename, ".icns") != NULL) w->response.data->contenttype = CT_IMAGE_ICNS;
352 else w->response.data->contenttype = CT_APPLICATION_OCTET_STREAM;
354 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);
356 w->mode = WEB_CLIENT_MODE_FILECOPY;
359 buffer_flush(w->response.data);
360 w->response.rlen = stat.st_size;
361 w->response.data->date = stat.st_mtim.tv_sec;
367 #ifdef NETDATA_WITH_ZLIB
368 void web_client_enable_deflate(struct web_client *w) {
369 if(w->response.zinitialized == 1) {
370 error("%llu: Compression has already be initialized for this client.", w->id);
374 if(w->response.sent) {
375 error("%llu: Cannot enable compression in the middle of a conversation.", w->id);
379 w->response.zstream.zalloc = Z_NULL;
380 w->response.zstream.zfree = Z_NULL;
381 w->response.zstream.opaque = Z_NULL;
383 w->response.zstream.next_in = (Bytef *)w->response.data->buffer;
384 w->response.zstream.avail_in = 0;
385 w->response.zstream.total_in = 0;
387 w->response.zstream.next_out = w->response.zbuffer;
388 w->response.zstream.avail_out = 0;
389 w->response.zstream.total_out = 0;
391 w->response.zstream.zalloc = Z_NULL;
392 w->response.zstream.zfree = Z_NULL;
393 w->response.zstream.opaque = Z_NULL;
395 // if(deflateInit(&w->response.zstream, Z_DEFAULT_COMPRESSION) != Z_OK) {
396 // error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
400 // Select GZIP compression: windowbits = 15 + 16 = 31
401 if(deflateInit2(&w->response.zstream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY) != Z_OK) {
402 error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
406 w->response.zsent = 0;
407 w->response.zoutput = 1;
408 w->response.zinitialized = 1;
410 debug(D_DEFLATE, "%llu: Initialized compression.", w->id);
412 #endif // NETDATA_WITH_ZLIB
414 uint32_t web_client_api_request_v1_data_options(char *o)
416 uint32_t ret = 0x00000000;
419 while(o && *o && (tok = mystrsep(&o, ", |"))) {
422 if(!strcmp(tok, "nonzero"))
423 ret |= RRDR_OPTION_NONZERO;
424 else if(!strcmp(tok, "flip") || !strcmp(tok, "reversed") || !strcmp(tok, "reverse"))
425 ret |= RRDR_OPTION_REVERSED;
426 else if(!strcmp(tok, "jsonwrap"))
427 ret |= RRDR_OPTION_JSON_WRAP;
428 else if(!strcmp(tok, "min2max"))
429 ret |= RRDR_OPTION_MIN2MAX;
430 else if(!strcmp(tok, "ms") || !strcmp(tok, "milliseconds"))
431 ret |= RRDR_OPTION_MILLISECONDS;
432 else if(!strcmp(tok, "abs") || !strcmp(tok, "absolute") || !strcmp(tok, "absolute_sum") || !strcmp(tok, "absolute-sum"))
433 ret |= RRDR_OPTION_ABSOLUTE;
434 else if(!strcmp(tok, "seconds"))
435 ret |= RRDR_OPTION_SECONDS;
436 else if(!strcmp(tok, "null2zero"))
437 ret |= RRDR_OPTION_NULL2ZERO;
438 else if(!strcmp(tok, "objectrows"))
439 ret |= RRDR_OPTION_OBJECTSROWS;
440 else if(!strcmp(tok, "google_json"))
441 ret |= RRDR_OPTION_GOOGLE_JSON;
442 else if(!strcmp(tok, "percentage"))
443 ret |= RRDR_OPTION_PERCENTAGE;
449 uint32_t web_client_api_request_v1_data_format(char *name)
451 if(!strcmp(name, DATASOURCE_FORMAT_DATATABLE_JSON)) // datatable
452 return DATASOURCE_DATATABLE_JSON;
454 else if(!strcmp(name, DATASOURCE_FORMAT_DATATABLE_JSONP)) // datasource
455 return DATASOURCE_DATATABLE_JSONP;
457 else if(!strcmp(name, DATASOURCE_FORMAT_JSON)) // json
458 return DATASOURCE_JSON;
460 else if(!strcmp(name, DATASOURCE_FORMAT_JSONP)) // jsonp
461 return DATASOURCE_JSONP;
463 else if(!strcmp(name, DATASOURCE_FORMAT_SSV)) // ssv
464 return DATASOURCE_SSV;
466 else if(!strcmp(name, DATASOURCE_FORMAT_CSV)) // csv
467 return DATASOURCE_CSV;
469 else if(!strcmp(name, DATASOURCE_FORMAT_TSV) || !strcmp(name, "tsv-excel")) // tsv
470 return DATASOURCE_TSV;
472 else if(!strcmp(name, DATASOURCE_FORMAT_HTML)) // html
473 return DATASOURCE_HTML;
475 else if(!strcmp(name, DATASOURCE_FORMAT_JS_ARRAY)) // array
476 return DATASOURCE_JS_ARRAY;
478 else if(!strcmp(name, DATASOURCE_FORMAT_SSV_COMMA)) // ssvcomma
479 return DATASOURCE_SSV_COMMA;
481 else if(!strcmp(name, DATASOURCE_FORMAT_CSV_JSON_ARRAY)) // csvjsonarray
482 return DATASOURCE_CSV_JSON_ARRAY;
484 return DATASOURCE_JSON;
487 uint32_t web_client_api_request_v1_data_google_format(char *name)
489 if(!strcmp(name, "json"))
490 return DATASOURCE_DATATABLE_JSONP;
492 else if(!strcmp(name, "html"))
493 return DATASOURCE_HTML;
495 else if(!strcmp(name, "csv"))
496 return DATASOURCE_CSV;
498 else if(!strcmp(name, "tsv-excel"))
499 return DATASOURCE_TSV;
501 return DATASOURCE_JSON;
504 int web_client_api_request_v1_data_group(char *name)
506 if(!strcmp(name, "max"))
509 else if(!strcmp(name, "average"))
510 return GROUP_AVERAGE;
515 int web_client_api_request_v1_charts(struct web_client *w, char *url)
519 buffer_flush(w->response.data);
520 w->response.data->contenttype = CT_APPLICATION_JSON;
521 rrd_stats_api_v1_charts(w->response.data);
525 int web_client_api_request_v1_chart(struct web_client *w, char *url)
530 buffer_flush(w->response.data);
533 char *value = mystrsep(&url, "?&[]");
534 if(!value || !*value) continue;
536 char *name = mystrsep(&value, "=");
537 if(!name || !*name) continue;
538 if(!value || !*value) continue;
540 // name and value are now the parameters
541 // they are not null and not empty
543 if(!strcmp(name, "chart")) chart = value;
545 /// buffer_sprintf(w->response.data, "Unknown parameter '%s' in request.", name);
550 if(!chart || !*chart) {
551 buffer_sprintf(w->response.data, "No chart id is given at the request.");
555 RRDSET *st = rrdset_find(chart);
556 if(!st) st = rrdset_find_byname(chart);
558 buffer_sprintf(w->response.data, "Chart '%s' is not found.", chart);
563 w->response.data->contenttype = CT_APPLICATION_JSON;
564 rrd_stats_api_v1_chart(st, w->response.data);
571 // returns the HTTP code
572 int web_client_api_request_v1_data(struct web_client *w, char *url)
574 debug(D_WEB_CLIENT, "%llu: API v1 data with URL '%s'", w->id, url);
577 BUFFER *dimensions = NULL;
579 buffer_flush(w->response.data);
581 char *google_version = "0.6",
584 *google_out = "json",
585 *responseHandler = NULL,
588 time_t last_timestamp_in_data = 0, google_timestamp = 0;
593 , *points_str = NULL;
595 int group = GROUP_MAX;
596 uint32_t format = DATASOURCE_JSON;
597 uint32_t options = 0x00000000;
600 char *value = mystrsep(&url, "?&[]");
601 if(!value || !*value) continue;
603 char *name = mystrsep(&value, "=");
604 if(!name || !*name) continue;
605 if(!value || !*value) continue;
607 debug(D_WEB_CLIENT, "%llu: API v1 query param '%s' with value '%s'", w->id, name, value);
609 // name and value are now the parameters
610 // they are not null and not empty
612 if(!strcmp(name, "chart")) chart = value;
613 else if(!strcmp(name, "dimension") || !strcmp(name, "dim") || !strcmp(name, "dimensions") || !strcmp(name, "dims")) {
614 if(!dimensions) dimensions = buffer_create(strlen(value));
616 buffer_strcat(dimensions, "|");
617 buffer_strcat(dimensions, value);
620 else if(!strcmp(name, "after")) after_str = value;
621 else if(!strcmp(name, "before")) before_str = value;
622 else if(!strcmp(name, "points")) points_str = value;
623 else if(!strcmp(name, "group")) {
624 group = web_client_api_request_v1_data_group(value);
626 else if(!strcmp(name, "format")) {
627 format = web_client_api_request_v1_data_format(value);
629 else if(!strcmp(name, "options")) {
630 options |= web_client_api_request_v1_data_options(value);
632 else if(!strcmp(name, "callback")) {
633 responseHandler = value;
635 else if(!strcmp(name, "filename")) {
638 else if(!strcmp(name, "tqx")) {
639 // parse Google Visualization API options
640 // https://developers.google.com/chart/interactive/docs/dev/implementing_data_source
641 char *tqx_name, *tqx_value;
644 tqx_value = mystrsep(&value, ";");
645 if(!tqx_value || !*tqx_value) continue;
647 tqx_name = mystrsep(&tqx_value, ":");
648 if(!tqx_name || !*tqx_name) continue;
649 if(!tqx_value || !*tqx_value) continue;
651 if(!strcmp(tqx_name, "version"))
652 google_version = tqx_value;
653 else if(!strcmp(tqx_name, "reqId"))
654 google_reqId = tqx_value;
655 else if(!strcmp(tqx_name, "sig")) {
656 google_sig = tqx_value;
657 google_timestamp = strtoul(google_sig, NULL, 0);
659 else if(!strcmp(tqx_name, "out")) {
660 google_out = tqx_value;
661 format = web_client_api_request_v1_data_google_format(google_out);
663 else if(!strcmp(tqx_name, "responseHandler"))
664 responseHandler = tqx_value;
665 else if(!strcmp(tqx_name, "outFileName"))
666 outFileName = tqx_value;
671 if(!chart || !*chart) {
672 buffer_sprintf(w->response.data, "No chart id is given at the request.");
676 RRDSET *st = rrdset_find(chart);
677 if(!st) st = rrdset_find_byname(chart);
679 buffer_sprintf(w->response.data, "Chart '%s' is not found.", chart);
684 long long before = (before_str && *before_str)?atol(before_str):0;
685 long long after = (after_str && *after_str) ?atol(after_str):0;
686 int points = (points_str && *points_str)?atoi(points_str):0;
688 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'"
691 , (dimensions)?buffer_tostring(dimensions):""
700 if(outFileName && *outFileName) {
701 buffer_sprintf(w->response.header, "Content-Disposition: attachment; filename=\"%s\"\r\n", outFileName);
702 error("generating outfilename header: '%s'", outFileName);
705 if(format == DATASOURCE_DATATABLE_JSONP) {
706 if(responseHandler == NULL)
707 responseHandler = "google.visualization.Query.setResponse";
709 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSON/JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
710 w->id, google_version, google_reqId, google_sig, google_out, responseHandler, outFileName
713 buffer_sprintf(w->response.data,
714 "%s({version:'%s',reqId:'%s',status:'ok',sig:'%lu',table:",
715 responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
717 else if(format == DATASOURCE_JSONP) {
718 if(responseHandler == NULL)
719 responseHandler = "callback";
721 buffer_strcat(w->response.data, responseHandler);
722 buffer_strcat(w->response.data, "(");
725 ret = rrd2format(st, w->response.data, dimensions, format, points, after, before, group, options, &last_timestamp_in_data);
727 if(format == DATASOURCE_DATATABLE_JSONP) {
728 if(google_timestamp < last_timestamp_in_data)
729 buffer_strcat(w->response.data, "});");
732 // the client already has the latest data
733 buffer_flush(w->response.data);
734 buffer_sprintf(w->response.data,
735 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
736 responseHandler, google_version, google_reqId);
739 else if(format == DATASOURCE_JSONP)
740 buffer_strcat(w->response.data, ");");
743 if(dimensions) buffer_free(dimensions);
747 int web_client_api_request_v1(struct web_client *w, char *url)
750 char *tok = mystrsep(&url, "/?&");
751 debug(D_WEB_CLIENT, "%llu: Searching for API v1 command '%s'.", w->id, tok);
753 if(strcmp(tok, "data") == 0)
754 return web_client_api_request_v1_data(w, url);
755 else if(strcmp(tok, "chart") == 0)
756 return web_client_api_request_v1_chart(w, url);
757 else if(strcmp(tok, "charts") == 0)
758 return web_client_api_request_v1_charts(w, url);
760 buffer_flush(w->response.data);
761 buffer_sprintf(w->response.data, "Unsupported v1 API command: %s", tok);
765 int web_client_api_request(struct web_client *w, char *url)
767 // get the api version
768 char *tok = mystrsep(&url, "/?&");
769 debug(D_WEB_CLIENT, "%llu: Searching for API version '%s'.", w->id, tok);
771 if(strcmp(tok, "v1") == 0)
772 return web_client_api_request_v1(w, url);
774 buffer_flush(w->response.data);
775 buffer_sprintf(w->response.data, "Unsupported API version: %s", tok);
779 int web_client_data_request(struct web_client *w, char *url, int datasource_type)
781 char *args = strchr(url, '?');
787 // get the name of the data to show
788 char *tok = mystrsep(&url, "/");
789 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
791 // do we have such a data set?
792 RRDSET *st = rrdset_find_byname(tok);
793 if(!st) st = rrdset_find(tok);
796 // try to send a file with that name
797 buffer_flush(w->response.data);
798 return(mysendfile(w, tok));
802 debug(D_WEB_CLIENT, "%llu: Found RRD data with name '%s'.", w->id, tok);
804 // how many entries does the client want?
805 long lines = rrd_default_history_entries;
806 long group_count = 1;
807 time_t after = 0, before = 0;
808 int group_method = GROUP_AVERAGE;
812 // parse the lines required
813 tok = mystrsep(&url, "/");
814 if(tok) lines = atoi(tok);
815 if(lines < 1) lines = 1;
818 // parse the group count required
819 tok = mystrsep(&url, "/");
820 if(tok) group_count = atoi(tok);
821 if(group_count < 1) group_count = 1;
822 //if(group_count > save_history / 20) group_count = save_history / 20;
825 // parse the grouping method required
826 tok = mystrsep(&url, "/");
827 if(strcmp(tok, "max") == 0) group_method = GROUP_MAX;
828 else if(strcmp(tok, "average") == 0) group_method = GROUP_AVERAGE;
829 else if(strcmp(tok, "sum") == 0) group_method = GROUP_SUM;
830 else debug(D_WEB_CLIENT, "%llu: Unknown group method '%s'", w->id, tok);
834 tok = mystrsep(&url, "/");
835 if(tok) after = strtoul(tok, NULL, 10);
836 if(after < 0) after = 0;
840 tok = mystrsep(&url, "/");
841 if(tok) before = strtoul(tok, NULL, 10);
842 if(before < 0) before = 0;
846 tok = mystrsep(&url, "/");
847 if(tok && strcmp(tok, "nonzero") == 0) nonzero = 1;
850 w->response.data->contenttype = CT_APPLICATION_JSON;
851 buffer_flush(w->response.data);
853 char *google_version = "0.6";
854 char *google_reqId = "0";
855 char *google_sig = "0";
856 char *google_out = "json";
857 char *google_responseHandler = "google.visualization.Query.setResponse";
858 char *google_outFileName = NULL;
859 time_t last_timestamp_in_data = 0;
860 if(datasource_type == DATASOURCE_DATATABLE_JSON || datasource_type == DATASOURCE_DATATABLE_JSONP) {
862 w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
865 tok = mystrsep(&args, "&");
867 char *name = mystrsep(&tok, "=");
868 if(name && strcmp(name, "tqx") == 0) {
869 char *key = mystrsep(&tok, ":");
870 char *value = mystrsep(&tok, ";");
871 if(key && value && *key && *value) {
872 if(strcmp(key, "version") == 0)
873 google_version = value;
875 else if(strcmp(key, "reqId") == 0)
876 google_reqId = value;
878 else if(strcmp(key, "sig") == 0)
881 else if(strcmp(key, "out") == 0)
884 else if(strcmp(key, "responseHandler") == 0)
885 google_responseHandler = value;
887 else if(strcmp(key, "outFileName") == 0)
888 google_outFileName = value;
894 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
895 w->id, google_version, google_reqId, google_sig, google_out, google_responseHandler, google_outFileName
898 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
899 last_timestamp_in_data = strtoul(google_sig, NULL, 0);
901 // check the client wants json
902 if(strcmp(google_out, "json") != 0) {
903 buffer_sprintf(w->response.data,
904 "%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.'}]});",
905 google_responseHandler, google_version, google_reqId, google_out);
911 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
912 buffer_sprintf(w->response.data,
913 "%s({version:'%s',reqId:'%s',status:'ok',sig:'%lu',table:",
914 google_responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
917 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);
918 time_t timestamp_in_data = rrd_stats_json(datasource_type, st, w->response.data, lines, group_count, group_method, after, before, nonzero);
920 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
921 if(timestamp_in_data > last_timestamp_in_data)
922 buffer_strcat(w->response.data, "});");
925 // the client already has the latest data
926 buffer_flush(w->response.data);
927 buffer_sprintf(w->response.data,
928 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
929 google_responseHandler, google_version, google_reqId);
937 int web_client_parse_request(struct web_client *w) {
941 // query string name-value
944 // http request headers name-value
946 web_client_clean_request(w);
948 debug(D_WEB_DATA, "%llu: Processing data buffer of %d bytes: '%s'.", w->id, w->response.data->bytes, w->response.data->buffer);
950 char *buf = w->response.data->buffer;
953 // ------------------------------------------------------------------------
956 if(buf && (line = strsep(&buf, "\r\n"))) {
958 if(line && (tok = strsep(&line, " "))) {
959 w->request.protocol = strdup(tok);
967 // ------------------------------------------------------------------------
968 // the rest of the lines
970 while(buf && (line = strsep(&buf, "\r\n"))) {
971 while(line && (tok = strsep(&line, ": "))) {
979 web_client_clean_request(w);
984 void web_client_process(struct web_client *w) {
991 // check if we have an empty line (end of HTTP header)
992 if(strstr(w->response.data->buffer, "\r\n\r\n")) {
993 global_statistics_lock();
994 global_statistics.web_requests++;
995 global_statistics_unlock();
997 gettimeofday(&w->tv_in, NULL);
998 debug(D_WEB_DATA, "%llu: Processing data buffer of %d bytes: '%s'.", w->id, w->response.data->len, w->response.data->buffer);
1000 // check if the client requested keep-alive HTTP
1001 if(strcasestr(w->response.data->buffer, "Connection: keep-alive")) w->keepalive = 1;
1002 else w->keepalive = 0;
1004 #ifdef NETDATA_WITH_ZLIB
1005 // check if the client accepts deflate
1006 if(web_enable_gzip && strstr(w->response.data->buffer, "gzip"))
1008 #endif // NETDATA_WITH_ZLIB
1010 int datasource_type = DATASOURCE_DATATABLE_JSONP;
1011 //if(strstr(w->response.data->buffer, "X-DataSource-Auth"))
1012 // datasource_type = DATASOURCE_GOOGLE_JSON;
1014 char *buf = (char *)buffer_tostring(w->response.data);
1015 char *tok = strsep(&buf, " \r\n");
1017 char *pointer_to_free = NULL; // keep url_decode() allocated buffer
1019 w->mode = WEB_CLIENT_MODE_NORMAL;
1021 if(buf && strcmp(tok, "GET") == 0) {
1022 tok = strsep(&buf, " \r\n");
1023 pointer_to_free = url = url_decode(tok);
1024 debug(D_WEB_CLIENT, "%llu: Processing HTTP GET on url '%s'.", w->id, url);
1026 else if(buf && strcmp(tok, "OPTIONS") == 0) {
1027 tok = strsep(&buf, " \r\n");
1028 pointer_to_free = url = url_decode(tok);
1029 debug(D_WEB_CLIENT, "%llu: Processing HTTP OPTIONS on url '%s'.", w->id, url);
1030 w->mode = WEB_CLIENT_MODE_OPTIONS;
1032 else if (buf && strcmp(tok, "POST") == 0) {
1034 tok = strsep(&buf, " \r\n");
1035 pointer_to_free = url = url_decode(tok);
1036 debug(D_WEB_CLIENT, "%llu: I don't know how to handle POST with form data. Assuming it is a GET on url '%s'.", w->id, url);
1039 w->last_url[0] = '\0';
1041 if(w->mode == WEB_CLIENT_MODE_OPTIONS) {
1042 strncpy(w->last_url, url, URL_MAX);
1043 w->last_url[URL_MAX] = '\0';
1046 w->response.data->contenttype = CT_TEXT_PLAIN;
1047 buffer_flush(w->response.data);
1048 buffer_strcat(w->response.data, "OK");
1051 #ifdef NETDATA_WITH_ZLIB
1053 web_client_enable_deflate(w);
1056 strncpy(w->last_url, url, URL_MAX);
1057 w->last_url[URL_MAX] = '\0';
1059 tok = mystrsep(&url, "/?");
1061 debug(D_WEB_CLIENT, "%llu: Processing command '%s'.", w->id, tok);
1063 if(strcmp(tok, "api") == 0) {
1064 // the client is requesting api access
1065 datasource_type = DATASOURCE_JSON;
1066 code = web_client_api_request(w, url);
1068 #ifdef NETDATA_INTERNAL_CHECKS
1069 else if(strcmp(tok, "exit") == 0) {
1072 w->response.data->contenttype = CT_TEXT_PLAIN;
1073 buffer_flush(w->response.data);
1074 buffer_strcat(w->response.data, "will do");
1077 else if(strcmp(tok, WEB_PATH_DATA) == 0) { // "data"
1078 // the client is requesting rrd data
1079 datasource_type = DATASOURCE_JSON;
1080 code = web_client_data_request(w, url, datasource_type);
1082 else if(strcmp(tok, WEB_PATH_DATASOURCE) == 0) { // "datasource"
1083 // the client is requesting google datasource
1084 code = web_client_data_request(w, url, datasource_type);
1086 else if(strcmp(tok, WEB_PATH_GRAPH) == 0) { // "graph"
1087 // the client is requesting an rrd graph
1089 // get the name of the data to show
1090 tok = mystrsep(&url, "/?&");
1091 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1093 // do we have such a data set?
1094 RRDSET *st = rrdset_find_byname(tok);
1095 if(!st) st = rrdset_find(tok);
1098 // try to send a file with that name
1099 buffer_flush(w->response.data);
1100 code = mysendfile(w, tok);
1104 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending %s.json of RRD_STATS...", w->id, st->name);
1105 w->response.data->contenttype = CT_APPLICATION_JSON;
1106 buffer_flush(w->response.data);
1107 rrd_stats_graph_json(st, url, w->response.data);
1110 #ifdef NETDATA_INTERNAL_CHECKS
1111 else if(strcmp(tok, "debug") == 0) {
1112 buffer_flush(w->response.data);
1114 // get the name of the data to show
1115 tok = mystrsep(&url, "/?&");
1116 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1118 // do we have such a data set?
1119 RRDSET *st = rrdset_find_byname(tok);
1120 if(!st) st = rrdset_find(tok);
1123 buffer_sprintf(w->response.data, "Chart %s is not found.\r\n", tok);
1124 debug(D_WEB_CLIENT_ACCESS, "%llu: %s is not found.", w->id, tok);
1128 debug_flags |= D_RRD_STATS;
1129 st->debug = st->debug?0:1;
1130 buffer_sprintf(w->response.data, "Chart %s has now debug %s.\r\n", tok, st->debug?"enabled":"disabled");
1131 debug(D_WEB_CLIENT_ACCESS, "%llu: debug for %s is %s.", w->id, tok, st->debug?"enabled":"disabled");
1134 else if(strcmp(tok, "mirror") == 0) {
1137 debug(D_WEB_CLIENT_ACCESS, "%llu: Mirroring...", w->id);
1139 // replace the zero bytes with spaces
1140 buffer_char_replace(w->response.data, '\0', ' ');
1142 // just leave the buffer as is
1143 // it will be copied back to the client
1146 else if(strcmp(tok, "list") == 0) {
1149 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending list of RRD_STATS...", w->id);
1151 buffer_flush(w->response.data);
1152 RRDSET *st = rrdset_root;
1154 for ( ; st ; st = st->next )
1155 buffer_sprintf(w->response.data, "%s\n", st->name);
1157 else if(strcmp(tok, "all.json") == 0) {
1159 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending JSON list of all monitors of RRD_STATS...", w->id);
1161 w->response.data->contenttype = CT_APPLICATION_JSON;
1162 buffer_flush(w->response.data);
1163 rrd_stats_all_json(w->response.data);
1165 else if(strcmp(tok, "netdata.conf") == 0) {
1167 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending netdata.conf ...", w->id);
1169 w->response.data->contenttype = CT_TEXT_PLAIN;
1170 buffer_flush(w->response.data);
1171 generate_config(w->response.data, 0);
1174 char filename[FILENAME_MAX+1];
1176 strncpy(filename, w->last_url, FILENAME_MAX);
1177 filename[FILENAME_MAX] = '\0';
1178 tok = mystrsep(&url, "?");
1179 buffer_flush(w->response.data);
1180 code = mysendfile(w, (tok && *tok)?tok:"/");
1184 strcpy(w->last_url, "not a valid response");
1186 if(buf) debug(D_WEB_CLIENT_ACCESS, "%llu: Cannot understand '%s'.", w->id, buf);
1189 buffer_flush(w->response.data);
1190 buffer_strcat(w->response.data, "I don't understand you...\r\n");
1193 // free url_decode() buffer
1194 if(pointer_to_free) free(pointer_to_free);
1196 else if(w->response.data->len > TOO_BIG_REQUEST) {
1197 strcpy(w->last_url, "too big request");
1199 debug(D_WEB_CLIENT_ACCESS, "%llu: Received request is too big (%zd bytes).", w->id, w->response.data->len);
1202 buffer_flush(w->response.data);
1203 buffer_sprintf(w->response.data, "Received request is too big (%zd bytes).\r\n", w->response.data->len);
1206 // wait for more data
1207 w->wait_receive = 1;
1211 gettimeofday(&w->tv_ready, NULL);
1212 w->response.data->date = time(NULL);
1213 w->response.sent = 0;
1214 w->response.code = code;
1216 // prepare the HTTP response header
1217 debug(D_WEB_CLIENT, "%llu: Generating HTTP header with response %d.", w->id, code);
1219 char *content_type_string;
1220 switch(w->response.data->contenttype) {
1222 content_type_string = "text/html; charset=utf-8";
1225 case CT_APPLICATION_XML:
1226 content_type_string = "application/xml; charset=utf-8";
1229 case CT_APPLICATION_JSON:
1230 content_type_string = "application/json; charset=utf-8";
1233 case CT_APPLICATION_X_JAVASCRIPT:
1234 content_type_string = "application/x-javascript; charset=utf-8";
1238 content_type_string = "text/css; charset=utf-8";
1242 content_type_string = "text/xml; charset=utf-8";
1246 content_type_string = "text/xsl; charset=utf-8";
1249 case CT_APPLICATION_OCTET_STREAM:
1250 content_type_string = "application/octet-stream";
1253 case CT_IMAGE_SVG_XML:
1254 content_type_string = "image/svg+xml";
1257 case CT_APPLICATION_X_FONT_TRUETYPE:
1258 content_type_string = "application/x-font-truetype";
1261 case CT_APPLICATION_X_FONT_OPENTYPE:
1262 content_type_string = "application/x-font-opentype";
1265 case CT_APPLICATION_FONT_WOFF:
1266 content_type_string = "application/font-woff";
1269 case CT_APPLICATION_FONT_WOFF2:
1270 content_type_string = "application/font-woff2";
1273 case CT_APPLICATION_VND_MS_FONTOBJ:
1274 content_type_string = "application/vnd.ms-fontobject";
1278 content_type_string = "image/png";
1282 content_type_string = "image/jpeg";
1286 content_type_string = "image/gif";
1289 case CT_IMAGE_XICON:
1290 content_type_string = "image/x-icon";
1294 content_type_string = "image/bmp";
1298 content_type_string = "image/icns";
1303 content_type_string = "text/plain; charset=utf-8";
1314 code_msg = "Temporary Redirect";
1318 code_msg = "Bad Request";
1322 code_msg = "Forbidden";
1326 code_msg = "Not Found";
1330 code_msg = "Internal Server Error";
1335 struct tm tmbuf, *tm = gmtime_r(&w->response.data->date, &tmbuf);
1336 strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %Z", tm);
1338 buffer_sprintf(w->response.header_output,
1339 "HTTP/1.1 %d %s\r\n"
1340 "Connection: %s\r\n"
1341 "Server: NetData Embedded HTTP Server\r\n"
1342 "Content-Type: %s\r\n"
1343 "Access-Control-Allow-Origin: *\r\n"
1344 "Access-Control-Allow-Methods: GET, OPTIONS\r\n"
1345 "Access-Control-Allow-Headers: accept, x-requested-with\r\n"
1346 "Access-Control-Max-Age: 86400\r\n"
1349 , w->keepalive?"keep-alive":"close"
1350 , content_type_string
1354 if(buffer_strlen(w->response.header))
1355 buffer_strcat(w->response.header_output, buffer_tostring(w->response.header));
1357 if(w->mode == WEB_CLIENT_MODE_NORMAL && (w->response.data->options & WB_CONTENT_NO_CACHEABLE)) {
1358 buffer_sprintf(w->response.header_output,
1360 "Cache-Control: no-cache\r\n"
1365 time_t et = w->response.data->date + (86400 * 14);
1366 struct tm etmbuf, *etm = gmtime_r(&et, &etmbuf);
1367 strftime(edate, sizeof(edate), "%a, %d %b %Y %H:%M:%S %Z", etm);
1369 buffer_sprintf(w->response.header_output,
1371 "Cache-Control: public\r\n"
1375 // if we know the content length, put it
1376 if(!w->response.zoutput && (w->response.data->len || w->response.rlen))
1377 buffer_sprintf(w->response.header_output,
1378 "Content-Length: %ld\r\n"
1379 , w->response.data->len? w->response.data->len: w->response.rlen
1381 else if(!w->response.zoutput)
1382 w->keepalive = 0; // content-length is required for keep-alive
1384 if(w->response.zoutput) {
1385 buffer_strcat(w->response.header_output,
1386 "Content-Encoding: gzip\r\n"
1387 "Transfer-Encoding: chunked\r\n"
1391 buffer_strcat(w->response.header_output, "\r\n");
1393 // disable TCP_NODELAY, to buffer the header
1395 if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0)
1396 error("%llu: failed to disable TCP_NODELAY on socket.", w->id);
1398 // sent the HTTP header
1399 debug(D_WEB_DATA, "%llu: Sending response HTTP header of size %d: '%s'"
1401 , buffer_strlen(w->response.header_output)
1402 , buffer_tostring(w->response.header_output)
1405 bytes = send(w->ofd, buffer_tostring(w->response.header_output), buffer_strlen(w->response.header_output), 0);
1406 if(bytes != (ssize_t) buffer_strlen(w->response.header_output))
1407 error("%llu: HTTP Header failed to be sent (I sent %d bytes but the system sent %d bytes)."
1409 , buffer_strlen(w->response.header_output)
1412 global_statistics_lock();
1413 global_statistics.bytes_sent += bytes;
1414 global_statistics_unlock();
1417 // enable TCP_NODELAY, to send all data immediately at the next send()
1419 if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0) error("%llu: failed to enable TCP_NODELAY on socket.", w->id);
1421 // enable sending immediately if we have data
1422 if(w->response.data->len) w->wait_send = 1;
1423 else w->wait_send = 0;
1427 case WEB_CLIENT_MODE_OPTIONS:
1428 debug(D_WEB_CLIENT, "%llu: Done preparing the OPTIONS response. Sending data (%d bytes) to client.", w->id, w->response.data->len);
1431 case WEB_CLIENT_MODE_NORMAL:
1432 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Sending data (%d bytes) to client.", w->id, w->response.data->len);
1435 case WEB_CLIENT_MODE_FILECOPY:
1436 if(w->response.rlen) {
1437 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending data file of %d bytes to client.", w->id, w->response.rlen);
1438 w->wait_receive = 1;
1441 // utilize the kernel sendfile() for copying the file to the socket.
1442 // this block of code can be commented, without anything missing.
1443 // when it is commented, the program will copy the data using async I/O.
1445 long len = sendfile(w->ofd, w->ifd, NULL, w->response.data->rbytes);
1446 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);
1447 else web_client_reset(w);
1452 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending an unknown amount of bytes to client.", w->id);
1456 fatal("%llu: Unknown client mode %d.", w->id, w->mode);
1461 long web_client_send_chunk_header(struct web_client *w, long len)
1463 debug(D_DEFLATE, "%llu: OPEN CHUNK of %d bytes (hex: %x).", w->id, len, len);
1465 sprintf(buf, "%lX\r\n", len);
1466 ssize_t bytes = send(w->ofd, buf, strlen(buf), MSG_DONTWAIT);
1468 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk header %d bytes.", w->id, bytes);
1469 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk header to the client.", w->id);
1470 else debug(D_DEFLATE, "%llu: Failed to send chunk header to client.", w->id);
1475 long web_client_send_chunk_close(struct web_client *w)
1477 //debug(D_DEFLATE, "%llu: CLOSE CHUNK.", w->id);
1479 ssize_t bytes = send(w->ofd, "\r\n", 2, MSG_DONTWAIT);
1481 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
1482 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
1483 else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client.", w->id);
1488 long web_client_send_chunk_finalize(struct web_client *w)
1490 //debug(D_DEFLATE, "%llu: FINALIZE CHUNK.", w->id);
1492 ssize_t bytes = send(w->ofd, "\r\n0\r\n\r\n", 7, MSG_DONTWAIT);
1494 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
1495 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
1496 else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client.", w->id);
1501 #ifdef NETDATA_WITH_ZLIB
1502 long web_client_send_deflate(struct web_client *w)
1504 long len = 0, t = 0;
1506 // when using compression,
1507 // w->response.sent is the amount of bytes passed through compression
1509 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);
1511 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) {
1512 // there is nothing to send
1514 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1516 // finalize the chunk
1517 if(w->response.sent != 0)
1518 t += web_client_send_chunk_finalize(w);
1520 // there can be two cases for this
1521 // A. we have done everything
1522 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
1524 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->response.rlen && w->response.rlen > w->response.data->len) {
1525 // we have to wait, more data will come
1526 debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1531 if(w->keepalive == 0) {
1532 debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->response.sent);
1538 web_client_reset(w);
1539 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1543 if(w->response.zhave == w->response.zsent) {
1544 // compress more input data
1546 // close the previous open chunk
1547 if(w->response.sent != 0) t += web_client_send_chunk_close(w);
1549 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);
1551 // give the compressor all the data not passed through the compressor yet
1552 if(w->response.data->len > w->response.sent) {
1553 #ifdef NETDATA_INTERNAL_CHECKS
1554 if((long)w->response.sent - (long)w->response.zstream.avail_in < 0)
1555 error("internal error: avail_in is corrupted.");
1557 w->response.zstream.next_in = (Bytef *)&w->response.data->buffer[w->response.sent - w->response.zstream.avail_in];
1558 w->response.zstream.avail_in += (uInt) (w->response.data->len - w->response.sent);
1561 // reset the compressor output buffer
1562 w->response.zstream.next_out = w->response.zbuffer;
1563 w->response.zstream.avail_out = ZLIB_CHUNK;
1565 // ask for FINISH if we have all the input
1566 int flush = Z_SYNC_FLUSH;
1567 if(w->mode == WEB_CLIENT_MODE_NORMAL
1568 || (w->mode == WEB_CLIENT_MODE_FILECOPY && !w->wait_receive && w->response.data->len == w->response.rlen)) {
1570 debug(D_DEFLATE, "%llu: Requesting Z_FINISH, if possible.", w->id);
1573 debug(D_DEFLATE, "%llu: Requesting Z_SYNC_FLUSH.", w->id);
1577 if(deflate(&w->response.zstream, flush) == Z_STREAM_ERROR) {
1578 error("%llu: Compression failed. Closing down client.", w->id);
1579 web_client_reset(w);
1583 w->response.zhave = ZLIB_CHUNK - w->response.zstream.avail_out;
1584 w->response.zsent = 0;
1586 // keep track of the bytes passed through the compressor
1587 w->response.sent = w->response.data->len;
1589 debug(D_DEFLATE, "%llu: Compression produced %d bytes.", w->id, w->response.zhave);
1592 t += web_client_send_chunk_header(w, w->response.zhave);
1595 debug(D_WEB_CLIENT, "%llu: Sending %d bytes of data (+%d of chunk header).", w->id, w->response.zhave - w->response.zsent, t);
1597 len = send(w->ofd, &w->response.zbuffer[w->response.zsent], (size_t) (w->response.zhave - w->response.zsent), MSG_DONTWAIT);
1599 w->response.zsent += len;
1601 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, len);
1603 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);
1604 else debug(D_WEB_CLIENT, "%llu: Failed to send data to client. Reason: %s", w->id, strerror(errno));
1608 #endif // NETDATA_WITH_ZLIB
1610 long web_client_send(struct web_client *w)
1612 #ifdef NETDATA_WITH_ZLIB
1613 if(likely(w->response.zoutput)) return web_client_send_deflate(w);
1614 #endif // NETDATA_WITH_ZLIB
1618 if(unlikely(w->response.data->len - w->response.sent == 0)) {
1619 // there is nothing to send
1621 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1623 // there can be two cases for this
1624 // A. we have done everything
1625 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
1627 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->response.rlen && w->response.rlen > w->response.data->len) {
1628 // we have to wait, more data will come
1629 debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1634 if(unlikely(w->keepalive == 0)) {
1635 debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->response.sent);
1640 web_client_reset(w);
1641 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1645 bytes = send(w->ofd, &w->response.data->buffer[w->response.sent], w->response.data->len - w->response.sent, MSG_DONTWAIT);
1646 if(likely(bytes > 0)) {
1647 w->response.sent += bytes;
1648 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, bytes);
1650 else if(likely(bytes == 0)) debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client.", w->id);
1651 else debug(D_WEB_CLIENT, "%llu: Failed to send data to client.", w->id);
1656 long web_client_receive(struct web_client *w)
1658 // do we have any space for more data?
1659 buffer_need_bytes(w->response.data, WEB_REQUEST_LENGTH);
1661 long left = w->response.data->size - w->response.data->len;
1664 if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY))
1665 bytes = read(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1));
1667 bytes = recv(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1), MSG_DONTWAIT);
1669 if(likely(bytes > 0)) {
1670 size_t old = w->response.data->len;
1671 w->response.data->len += bytes;
1672 w->response.data->buffer[w->response.data->len] = '\0';
1674 debug(D_WEB_CLIENT, "%llu: Received %d bytes.", w->id, bytes);
1675 debug(D_WEB_DATA, "%llu: Received data: '%s'.", w->id, &w->response.data->buffer[old]);
1677 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1679 if(w->response.rlen && w->response.data->len >= w->response.rlen) w->wait_receive = 0;
1682 else if(likely(bytes == 0)) {
1683 debug(D_WEB_CLIENT, "%llu: Out of input data.", w->id);
1685 // if we cannot read, it means we have an error on input.
1686 // if however, we are copying a file from ifd to ofd, we should not return an error.
1687 // in this case, the error should be generated when the file has been sent to the client.
1689 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1690 // we are copying data from ifd to ofd
1691 // let it finish copying...
1692 w->wait_receive = 0;
1693 debug(D_WEB_CLIENT, "%llu: Disabling input.", w->id);
1705 // --------------------------------------------------------------------------------------
1706 // the thread of a single client
1708 // 1. waits for input and output, using async I/O
1709 // 2. it processes HTTP requests
1710 // 3. it generates HTTP responses
1711 // 4. it copies data from input to output if mode is FILECOPY
1713 void *web_client_main(void *ptr)
1715 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
1716 error("Cannot set pthread cancel type to DEFERRED.");
1718 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
1719 error("Cannot set pthread cancel state to ENABLE.");
1722 struct web_client *w = ptr;
1724 fd_set ifds, ofds, efds;
1727 log_access("%llu: %s port %s connected on thread task id %d", w->id, w->client_ip, w->client_port, gettid());
1734 FD_SET(w->ifd, &efds);
1736 if(w->ifd != w->ofd)
1737 FD_SET(w->ofd, &efds);
1739 if (w->wait_receive) {
1740 FD_SET(w->ifd, &ifds);
1741 if(w->ifd > fdmax) fdmax = w->ifd;
1745 FD_SET(w->ofd, &ofds);
1746 if(w->ofd > fdmax) fdmax = w->ofd;
1749 tv.tv_sec = web_client_timeout;
1752 debug(D_WEB_CLIENT, "%llu: Waiting socket async I/O for %s %s", w->id, w->wait_receive?"INPUT":"", w->wait_send?"OUTPUT":"");
1753 retval = select(fdmax+1, &ifds, &ofds, &efds, &tv);
1756 debug(D_WEB_CLIENT_ACCESS, "%llu: LISTENER: select() failed.", w->id);
1761 debug(D_WEB_CLIENT_ACCESS, "%llu: LISTENER: timeout.", w->id);
1765 if(FD_ISSET(w->ifd, &efds)) {
1766 debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on input socket.", w->id);
1770 if(FD_ISSET(w->ofd, &efds)) {
1771 debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on output socket.", w->id);
1775 if(w->wait_send && FD_ISSET(w->ofd, &ofds)) {
1777 if((bytes = web_client_send(w)) < 0) {
1778 debug(D_WEB_CLIENT, "%llu: Cannot send data to client. Closing client.", w->id);
1783 global_statistics_lock();
1784 global_statistics.bytes_sent += bytes;
1785 global_statistics_unlock();
1788 if(w->wait_receive && FD_ISSET(w->ifd, &ifds)) {
1790 if((bytes = web_client_receive(w)) < 0) {
1791 debug(D_WEB_CLIENT, "%llu: Cannot receive data from client. Closing client.", w->id);
1796 if(w->mode == WEB_CLIENT_MODE_NORMAL) {
1797 debug(D_WEB_CLIENT, "%llu: Attempting to process received data (%ld bytes).", w->id, bytes);
1798 // info("%llu: Attempting to process received data (%ld bytes).", w->id, bytes);
1799 web_client_process(w);
1802 global_statistics_lock();
1803 global_statistics.bytes_received += bytes;
1804 global_statistics_unlock();
1808 log_access("%llu: %s port %s disconnected from thread task id %d", w->id, w->client_ip, w->client_port, gettid());
1809 debug(D_WEB_CLIENT, "%llu: done...", w->id);
1811 web_client_reset(w);