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
34 int web_client_timeout = DEFAULT_DISCONNECT_IDLE_WEB_CLIENTS_AFTER_SECONDS;
35 int web_enable_gzip = 1;
37 struct web_client *web_clients = NULL;
38 unsigned long long web_clients_count = 0;
40 struct web_client *web_client_create(int listener)
44 w = calloc(1, sizeof(struct web_client));
46 error("Cannot allocate new web_client memory.");
50 w->id = ++web_clients_count;
51 w->mode = WEB_CLIENT_MODE_NORMAL;
54 struct sockaddr *sadr;
57 sadr = (struct sockaddr*) &w->clientaddr;
58 addrlen = sizeof(w->clientaddr);
60 w->ifd = accept(listener, sadr, &addrlen);
62 error("%llu: Cannot accept new incoming connection.", w->id);
68 if(getnameinfo(sadr, addrlen, w->client_ip, NI_MAXHOST, w->client_port, NI_MAXSERV, NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
69 error("Cannot getnameinfo() on received client connection.");
70 strncpy(w->client_ip, "UNKNOWN", NI_MAXHOST);
71 strncpy(w->client_port, "UNKNOWN", NI_MAXSERV);
73 w->client_ip[NI_MAXHOST] = '\0';
74 w->client_port[NI_MAXSERV] = '\0';
76 switch(sadr->sa_family) {
79 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);
83 if(strncmp(w->client_ip, "::ffff:", 7) == 0) {
84 strcpy(w->client_ip, &w->client_ip[7]);
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);
87 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);
91 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);
96 if(setsockopt(w->ifd, SOL_SOCKET, SO_KEEPALIVE, (char *) &flag, sizeof(int)) != 0) error("%llu: Cannot set SO_KEEPALIVE on socket.", w->id);
99 w->response.data = buffer_create(INITIAL_WEB_DATA_LENGTH);
100 if(unlikely(!w->response.data)) {
101 // no need for error log - web_buffer_create already logged the error
107 w->response.header = buffer_create(HTTP_RESPONSE_HEADER_SIZE);
108 if(unlikely(!w->response.header)) {
109 // no need for error log - web_buffer_create already logged the error
110 buffer_free(w->response.data);
116 w->response.header_output = buffer_create(HTTP_RESPONSE_HEADER_SIZE);
117 if(unlikely(!w->response.header_output)) {
118 // no need for error log - web_buffer_create already logged the error
119 buffer_free(w->response.header);
120 buffer_free(w->response.data);
128 if(web_clients) web_clients->prev = w;
129 w->next = web_clients;
132 global_statistics.connected_clients++;
137 void web_client_reset(struct web_client *w)
140 gettimeofday(&tv, NULL);
142 long sent = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->response.rlen:w->response.data->len;
144 #ifdef NETDATA_WITH_ZLIB
145 if(likely(w->response.zoutput)) sent = (long)w->response.zstream.total_out;
148 long size = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->response.rlen:w->response.data->len;
150 if(likely(w->last_url[0]))
151 log_access("%llu: (sent/all = %ld/%ld bytes %0.0f%%, prep/sent/total = %0.2f/%0.2f/%0.2f ms) %s: %d '%s'",
153 sent, size, -((size>0)?((float)(size-sent)/(float)size * 100.0):0.0),
154 (float)usecdiff(&w->tv_ready, &w->tv_in) / 1000.0,
155 (float)usecdiff(&tv, &w->tv_ready) / 1000.0,
156 (float)usecdiff(&tv, &w->tv_in) / 1000.0,
157 (w->mode == WEB_CLIENT_MODE_FILECOPY)?"filecopy":"data",
162 debug(D_WEB_CLIENT, "%llu: Reseting client.", w->id);
164 if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY)) {
165 debug(D_WEB_CLIENT, "%llu: Closing filecopy input file.", w->id);
170 w->last_url[0] = '\0';
172 w->mode = WEB_CLIENT_MODE_NORMAL;
174 buffer_reset(w->response.header_output);
175 buffer_reset(w->response.header);
176 buffer_reset(w->response.data);
177 w->response.rlen = 0;
178 w->response.sent = 0;
179 w->response.code = 0;
184 w->response.zoutput = 0;
186 // if we had enabled compression, release it
187 #ifdef NETDATA_WITH_ZLIB
188 if(w->response.zinitialized) {
189 debug(D_DEFLATE, "%llu: Reseting compression.", w->id);
190 deflateEnd(&w->response.zstream);
191 w->response.zsent = 0;
192 w->response.zhave = 0;
193 w->response.zstream.avail_in = 0;
194 w->response.zstream.avail_out = 0;
195 w->response.zstream.total_in = 0;
196 w->response.zstream.total_out = 0;
197 w->response.zinitialized = 0;
199 #endif // NETDATA_WITH_ZLIB
202 struct web_client *web_client_free(struct web_client *w)
204 struct web_client *n = w->next;
206 debug(D_WEB_CLIENT_ACCESS, "%llu: Closing web client from %s port %s.", w->id, w->client_ip, w->client_port);
208 if(w->prev) w->prev->next = w->next;
209 if(w->next) w->next->prev = w->prev;
211 if(w == web_clients) web_clients = w->next;
213 if(w->response.header) buffer_free(w->response.header);
214 if(w->response.data) buffer_free(w->response.data);
216 if(w->ofd != w->ifd) close(w->ofd);
219 global_statistics.connected_clients--;
224 uid_t web_files_uid(void)
226 static char *web_owner = NULL;
227 static uid_t owner_uid = 0;
229 if(unlikely(!web_owner)) {
230 web_owner = config_get("global", "web files owner", NETDATA_USER);
231 if(!web_owner || !*web_owner)
232 owner_uid = geteuid();
234 struct passwd *pw = getpwnam(web_owner);
236 error("User %s is not present. Ignoring option. Error: %s\n", web_owner, strerror(errno));
237 owner_uid = geteuid();
240 debug(D_WEB_CLIENT, "Web files owner set to %s.\n", web_owner);
241 owner_uid = pw->pw_uid;
249 int mysendfile(struct web_client *w, char *filename)
251 static char *web_dir = NULL;
253 // initialize our static data
254 if(unlikely(!web_dir)) web_dir = config_get("global", "web files directory", WEB_DIR);
256 debug(D_WEB_CLIENT, "%llu: Looking for file '%s/%s'", w->id, web_dir, filename);
258 // skip leading slashes
259 while (*filename == '/') filename++;
261 // if the filename contain known paths, skip them
262 if(strncmp(filename, WEB_PATH_FILE "/", strlen(WEB_PATH_FILE) + 1) == 0) filename = &filename[strlen(WEB_PATH_FILE) + 1];
265 for(s = filename; *s ;s++) {
266 if( !isalnum(*s) && *s != '/' && *s != '.' && *s != '-' && *s != '_') {
267 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
268 buffer_sprintf(w->response.data, "File '%s' cannot be served. Filename contains invalid character '%c'", *s);
273 // if the filename contains a .. refuse to serve it
274 if(strstr(filename, "..") != 0) {
275 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
276 buffer_sprintf(w->response.data, "File '%s' cannot be served. Relative filenames with '..' in them are not supported.", filename);
281 char webfilename[FILENAME_MAX + 1];
282 snprintf(webfilename, FILENAME_MAX, "%s/%s", web_dir, filename);
284 // check if the file exists
286 if(lstat(webfilename, &stat) != 0) {
287 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not found.", w->id, webfilename);
288 buffer_sprintf(w->response.data, "File '%s' does not exist, or is not accessible.", filename);
292 // check if the file is owned by us
293 if(stat.st_uid != web_files_uid()) {
294 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is owned by user %d (I run as user %d). Access Denied.", w->id, webfilename, stat.st_uid, getuid());
295 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", filename);
299 if((stat.st_mode & S_IFMT) == S_IFDIR) {
300 snprintf(webfilename, FILENAME_MAX+1, "%s/index.html", filename);
301 return mysendfile(w, webfilename);
304 if((stat.st_mode & S_IFMT) != S_IFREG) {
305 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not a regular file. Access Denied.", w->id, webfilename);
306 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", filename);
311 w->ifd = open(webfilename, O_NONBLOCK, O_RDONLY);
315 if(errno == EBUSY || errno == EAGAIN) {
316 error("%llu: File '%s' is busy, sending 307 Moved Temporarily to force retry.", w->id, webfilename);
317 buffer_sprintf(w->response.header, "Location: /" WEB_PATH_FILE "/%s\r\n", filename);
318 buffer_sprintf(w->response.data, "The file '%s' is currently busy. Please try again later.", filename);
322 error("%llu: Cannot open file '%s'.", w->id, webfilename);
323 buffer_sprintf(w->response.data, "Cannot open file '%s'.", filename);
328 // pick a Content-Type for the file
329 if(strstr(filename, ".html") != NULL) w->response.data->contenttype = CT_TEXT_HTML;
330 else if(strstr(filename, ".js") != NULL) w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
331 else if(strstr(filename, ".css") != NULL) w->response.data->contenttype = CT_TEXT_CSS;
332 else if(strstr(filename, ".xml") != NULL) w->response.data->contenttype = CT_TEXT_XML;
333 else if(strstr(filename, ".xsl") != NULL) w->response.data->contenttype = CT_TEXT_XSL;
334 else if(strstr(filename, ".txt") != NULL) w->response.data->contenttype = CT_TEXT_PLAIN;
335 else if(strstr(filename, ".svg") != NULL) w->response.data->contenttype = CT_IMAGE_SVG_XML;
336 else if(strstr(filename, ".ttf") != NULL) w->response.data->contenttype = CT_APPLICATION_X_FONT_TRUETYPE;
337 else if(strstr(filename, ".otf") != NULL) w->response.data->contenttype = CT_APPLICATION_X_FONT_OPENTYPE;
338 else if(strstr(filename, ".woff") != NULL) w->response.data->contenttype = CT_APPLICATION_FONT_WOFF;
339 else if(strstr(filename, ".eot") != NULL) w->response.data->contenttype = CT_APPLICATION_VND_MS_FONTOBJ;
340 else w->response.data->contenttype = CT_APPLICATION_OCTET_STREAM;
342 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);
344 w->mode = WEB_CLIENT_MODE_FILECOPY;
347 buffer_flush(w->response.data);
348 w->response.rlen = stat.st_size;
349 w->response.data->date = stat.st_mtim.tv_sec;
355 #ifdef NETDATA_WITH_ZLIB
356 void web_client_enable_deflate(struct web_client *w) {
357 if(w->response.zinitialized == 1) {
358 error("%llu: Compression has already be initialized for this client.", w->id);
362 if(w->response.sent) {
363 error("%llu: Cannot enable compression in the middle of a conversation.", w->id);
367 w->response.zstream.zalloc = Z_NULL;
368 w->response.zstream.zfree = Z_NULL;
369 w->response.zstream.opaque = Z_NULL;
371 w->response.zstream.next_in = (Bytef *)w->response.data->buffer;
372 w->response.zstream.avail_in = 0;
373 w->response.zstream.total_in = 0;
375 w->response.zstream.next_out = w->response.zbuffer;
376 w->response.zstream.avail_out = 0;
377 w->response.zstream.total_out = 0;
379 w->response.zstream.zalloc = Z_NULL;
380 w->response.zstream.zfree = Z_NULL;
381 w->response.zstream.opaque = Z_NULL;
383 // if(deflateInit(&w->response.zstream, Z_DEFAULT_COMPRESSION) != Z_OK) {
384 // error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
388 // Select GZIP compression: windowbits = 15 + 16 = 31
389 if(deflateInit2(&w->response.zstream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY) != Z_OK) {
390 error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
394 w->response.zsent = 0;
395 w->response.zoutput = 1;
396 w->response.zinitialized = 1;
398 debug(D_DEFLATE, "%llu: Initialized compression.", w->id);
400 #endif // NETDATA_WITH_ZLIB
402 uint32_t web_client_api_request_v1_data_options(char *o)
404 uint32_t ret = 0x00000000;
407 while(o && *o && (tok = mystrsep(&o, ", |"))) {
410 if(!strcmp(tok, "nonzero"))
411 ret |= RRDR_OPTION_NONZERO;
412 else if(!strcmp(tok, "flip") || !strcmp(tok, "reversed") || !strcmp(tok, "reverse"))
413 ret |= RRDR_OPTION_REVERSED;
414 else if(!strcmp(tok, "abs") || !strcmp(tok, "absolute") || !strcmp(tok, "absolute_sum") || !strcmp(tok, "absolute-sum"))
415 ret |= RRDR_OPTION_ABSOLUTE;
416 else if(!strcmp(tok, "min2max"))
417 ret |= RRDR_OPTION_MIN2MAX;
418 else if(!strcmp(tok, "seconds"))
419 ret |= RRDR_OPTION_SECONDS;
420 else if(!strcmp(tok, "ms") || !strcmp(tok, "milliseconds"))
421 ret |= RRDR_OPTION_MILLISECONDS;
422 else if(!strcmp(tok, "null2zero"))
423 ret |= RRDR_OPTION_NULL2ZERO;
429 int web_client_api_request_v1_data_format(char *name)
431 if(!strcmp(name, "datatable"))
432 return DATASOURCE_GOOGLE_JSON;
434 else if(!strcmp(name, "datasource"))
435 return DATASOURCE_GOOGLE_JSONP;
437 else if(!strcmp(name, "json"))
438 return DATASOURCE_JSON;
440 else if(!strcmp(name, "jsonp"))
441 return DATASOURCE_JSONP;
443 else if(!strcmp(name, "ssv"))
444 return DATASOURCE_SSV;
446 else if(!strcmp(name, "csv"))
447 return DATASOURCE_CSV;
449 else if(!strcmp(name, "tsv"))
450 return DATASOURCE_TSV;
452 else if(!strcmp(name, "tsv-excel"))
453 return DATASOURCE_TSV;
455 else if(!strcmp(name, "html"))
456 return DATASOURCE_HTML;
458 else if(!strcmp(name, "array"))
459 return DATASOURCE_JS_ARRAY;
461 else if(!strcmp(name, "ssvcomma"))
462 return DATASOURCE_SSV_COMMA;
464 return DATASOURCE_JSON;
467 int web_client_api_request_v1_data_google_format(char *name)
469 if(!strcmp(name, "json"))
470 return DATASOURCE_GOOGLE_JSONP;
472 else if(!strcmp(name, "html"))
473 return DATASOURCE_HTML;
475 else if(!strcmp(name, "csv"))
476 return DATASOURCE_CSV;
478 else if(!strcmp(name, "tsv-excel"))
479 return DATASOURCE_TSV;
481 return DATASOURCE_JSON;
484 int web_client_api_request_v1_data_group(char *name)
486 if(!strcmp(name, "max"))
489 else if(!strcmp(name, "average"))
490 return GROUP_AVERAGE;
495 int web_client_api_request_v1_charts(struct web_client *w, char *url)
499 buffer_flush(w->response.data);
500 rrd_stats_api_v1_charts(w->response.data);
504 int web_client_api_request_v1_chart(struct web_client *w, char *url)
509 buffer_flush(w->response.data);
512 char *value = mystrsep(&url, "?&[]");
513 if(!value || !*value) continue;
515 char *name = mystrsep(&value, "=");
516 if(!name || !*name) continue;
517 if(!value || !*value) continue;
519 // name and value are now the parameters
520 // they are not null and not empty
522 if(!strcmp(name, "chart")) chart = value;
524 buffer_sprintf(w->response.data, "Unknown parameter '%s' in request.", name);
529 if(!chart || !*chart) {
530 buffer_sprintf(w->response.data, "No chart id is given at the request.");
534 RRDSET *st = rrdset_find(chart);
535 if(!st) st = rrdset_find_byname(chart);
537 buffer_sprintf(w->response.data, "Chart '%s' is not found.", chart);
542 w->response.data->contenttype = CT_APPLICATION_JSON;
543 rrd_stats_api_v1_chart(st, w->response.data);
550 // returns the HTTP code
551 int web_client_api_request_v1_data(struct web_client *w, char *url)
553 debug(D_WEB_CLIENT, "%llu: API v1 data with URL '%s'", w->id, url);
556 BUFFER *dimensions = NULL;
558 buffer_flush(w->response.data);
560 char *google_version = "0.6",
563 *google_out = "json",
564 *google_responseHandler = "google.visualization.Query.setResponse",
565 *google_outFileName = NULL;
567 time_t last_timestamp_in_data = 0, google_timestamp = 0;
572 , *points_str = NULL;
574 int format = DATASOURCE_JSON, group = GROUP_MAX;
575 uint32_t options = 0x00000000;
578 char *value = mystrsep(&url, "?&[]");
579 if(!value || !*value) continue;
581 char *name = mystrsep(&value, "=");
582 if(!name || !*name) continue;
583 if(!value || !*value) continue;
585 debug(D_WEB_CLIENT, "%llu: API v1 query param '%s' with value '%s'", w->id, name, value);
587 // name and value are now the parameters
588 // they are not null and not empty
590 if(!strcmp(name, "chart")) chart = value;
591 else if(!strcmp(name, "dimension") || !strcmp(name, "dim") || !strcmp(name, "dimensions") || !strcmp(name, "dims")) {
592 if(!dimensions) dimensions = buffer_create(strlen(value));
594 buffer_strcat(dimensions, "|");
595 buffer_strcat(dimensions, value);
598 else if(!strcmp(name, "after")) after_str = value;
599 else if(!strcmp(name, "before")) before_str = value;
600 else if(!strcmp(name, "points")) points_str = value;
601 else if(!strcmp(name, "group")) {
602 group = web_client_api_request_v1_data_group(value);
604 else if(!strcmp(name, "format")) {
605 format = web_client_api_request_v1_data_format(value);
607 else if(!strcmp(name, "options")) {
608 options |= web_client_api_request_v1_data_options(value);
610 else if(!strcmp(name, "tqx")) {
611 // parse Google Visualization API options
612 // https://developers.google.com/chart/interactive/docs/dev/implementing_data_source
613 char *tqx_name, *tqx_value;
616 tqx_value = mystrsep(&value, ";");
617 if(!tqx_value || !*tqx_value) continue;
619 tqx_name = mystrsep(&tqx_value, ":");
620 if(!tqx_name || !*tqx_name) continue;
621 if(!tqx_value || !*tqx_value) continue;
623 if(!strcmp(tqx_name, "version"))
624 google_version = tqx_value;
625 else if(!strcmp(tqx_name, "reqId"))
626 google_reqId = tqx_value;
627 else if(!strcmp(tqx_name, "sig")) {
628 google_sig = tqx_value;
629 google_timestamp = strtoul(google_sig, NULL, 0);
631 else if(!strcmp(tqx_name, "out")) {
632 google_out = tqx_value;
633 format = web_client_api_request_v1_data_google_format(google_out);
635 else if(!strcmp(tqx_name, "responseHandler"))
636 google_responseHandler = tqx_value;
637 else if(!strcmp(tqx_name, "outFileName"))
638 google_outFileName = tqx_value;
643 if(!chart || !*chart) {
644 buffer_sprintf(w->response.data, "No chart id is given at the request.");
648 RRDSET *st = rrdset_find(chart);
649 if(!st) st = rrdset_find_byname(chart);
651 buffer_sprintf(w->response.data, "Chart '%s' is not found.", chart);
656 long long before = (before_str && *before_str)?atol(before_str):0;
657 long long after = (after_str && *after_str) ?atol(after_str):0;
658 int points = (points_str && *points_str)?atoi(points_str):0;
660 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'"
663 , (dimensions)?buffer_tostring(dimensions):""
672 if(google_outFileName && *google_outFileName) {
673 buffer_sprintf(w->response.header, "Content-Disposition: attachment; filename=\"%s\"\r\n", google_outFileName);
674 error("generating outfilename header: '%s'", google_outFileName);
677 if(format == DATASOURCE_GOOGLE_JSONP) {
678 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSON/JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
679 w->id, google_version, google_reqId, google_sig, google_out, google_responseHandler, google_outFileName
682 buffer_sprintf(w->response.data,
683 "%s({version:'%s',reqId:'%s',status:'ok',sig:'%lu',table:",
684 google_responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
687 ret = rrd2format(st, w->response.data, dimensions, format, points, after, before, group, options, &last_timestamp_in_data);
689 if(format == DATASOURCE_GOOGLE_JSONP) {
690 if(google_timestamp < last_timestamp_in_data)
691 buffer_strcat(w->response.data, "});");
694 // the client already has the latest data
695 buffer_flush(w->response.data);
696 buffer_sprintf(w->response.data,
697 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
698 google_responseHandler, google_version, google_reqId);
703 if(dimensions) buffer_free(dimensions);
707 int web_client_api_request_v1(struct web_client *w, char *url)
710 char *tok = mystrsep(&url, "/?&");
711 debug(D_WEB_CLIENT, "%llu: Searching for API v1 command '%s'.", w->id, tok);
713 if(strcmp(tok, "data") == 0)
714 return web_client_api_request_v1_data(w, url);
715 else if(strcmp(tok, "chart") == 0)
716 return web_client_api_request_v1_chart(w, url);
717 else if(strcmp(tok, "charts") == 0)
718 return web_client_api_request_v1_charts(w, url);
720 buffer_flush(w->response.data);
721 buffer_sprintf(w->response.data, "Unsupported v1 API command: %s", tok);
725 int web_client_api_request(struct web_client *w, char *url)
727 // get the api version
728 char *tok = mystrsep(&url, "/?&");
729 debug(D_WEB_CLIENT, "%llu: Searching for API version '%s'.", w->id, tok);
731 if(strcmp(tok, "v1") == 0)
732 return web_client_api_request_v1(w, url);
734 buffer_flush(w->response.data);
735 buffer_sprintf(w->response.data, "Unsupported API version: %s", tok);
739 int web_client_data_request(struct web_client *w, char *url, int datasource_type)
741 char *args = strchr(url, '?');
747 // get the name of the data to show
748 char *tok = mystrsep(&url, "/");
749 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
751 // do we have such a data set?
752 RRDSET *st = rrdset_find_byname(tok);
753 if(!st) st = rrdset_find(tok);
756 // try to send a file with that name
757 buffer_flush(w->response.data);
758 return(mysendfile(w, tok));
762 debug(D_WEB_CLIENT, "%llu: Found RRD data with name '%s'.", w->id, tok);
764 // how many entries does the client want?
765 long lines = rrd_default_history_entries;
766 long group_count = 1;
767 time_t after = 0, before = 0;
768 int group_method = GROUP_AVERAGE;
772 // parse the lines required
773 tok = mystrsep(&url, "/");
774 if(tok) lines = atoi(tok);
775 if(lines < 1) lines = 1;
778 // parse the group count required
779 tok = mystrsep(&url, "/");
780 if(tok) group_count = atoi(tok);
781 if(group_count < 1) group_count = 1;
782 //if(group_count > save_history / 20) group_count = save_history / 20;
785 // parse the grouping method required
786 tok = mystrsep(&url, "/");
787 if(strcmp(tok, "max") == 0) group_method = GROUP_MAX;
788 else if(strcmp(tok, "average") == 0) group_method = GROUP_AVERAGE;
789 else if(strcmp(tok, "sum") == 0) group_method = GROUP_SUM;
790 else debug(D_WEB_CLIENT, "%llu: Unknown group method '%s'", w->id, tok);
794 tok = mystrsep(&url, "/");
795 if(tok) after = strtoul(tok, NULL, 10);
796 if(after < 0) after = 0;
800 tok = mystrsep(&url, "/");
801 if(tok) before = strtoul(tok, NULL, 10);
802 if(before < 0) before = 0;
806 tok = mystrsep(&url, "/");
807 if(tok && strcmp(tok, "nonzero") == 0) nonzero = 1;
810 w->response.data->contenttype = CT_APPLICATION_JSON;
811 buffer_flush(w->response.data);
813 char *google_version = "0.6";
814 char *google_reqId = "0";
815 char *google_sig = "0";
816 char *google_out = "json";
817 char *google_responseHandler = "google.visualization.Query.setResponse";
818 char *google_outFileName = NULL;
819 unsigned long last_timestamp_in_data = 0;
820 if(datasource_type == DATASOURCE_GOOGLE_JSON || datasource_type == DATASOURCE_GOOGLE_JSONP) {
822 w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
825 tok = mystrsep(&args, "&");
827 char *name = mystrsep(&tok, "=");
828 if(name && strcmp(name, "tqx") == 0) {
829 char *key = mystrsep(&tok, ":");
830 char *value = mystrsep(&tok, ";");
831 if(key && value && *key && *value) {
832 if(strcmp(key, "version") == 0)
833 google_version = value;
835 else if(strcmp(key, "reqId") == 0)
836 google_reqId = value;
838 else if(strcmp(key, "sig") == 0)
841 else if(strcmp(key, "out") == 0)
844 else if(strcmp(key, "responseHandler") == 0)
845 google_responseHandler = value;
847 else if(strcmp(key, "outFileName") == 0)
848 google_outFileName = value;
854 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
855 w->id, google_version, google_reqId, google_sig, google_out, google_responseHandler, google_outFileName
858 if(datasource_type == DATASOURCE_GOOGLE_JSONP) {
859 last_timestamp_in_data = strtoul(google_sig, NULL, 0);
861 // check the client wants json
862 if(strcmp(google_out, "json") != 0) {
863 buffer_sprintf(w->response.data,
864 "%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.'}]});",
865 google_responseHandler, google_version, google_reqId, google_out);
871 if(datasource_type == DATASOURCE_GOOGLE_JSONP) {
872 buffer_sprintf(w->response.data,
873 "%s({version:'%s',reqId:'%s',status:'ok',sig:'%lu',table:",
874 google_responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
877 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);
878 unsigned long timestamp_in_data = rrd_stats_json(datasource_type, st, w->response.data, lines, group_count, group_method, after, before, nonzero);
880 if(datasource_type == DATASOURCE_GOOGLE_JSONP) {
881 if(timestamp_in_data > last_timestamp_in_data)
882 buffer_strcat(w->response.data, "});");
885 // the client already has the latest data
886 buffer_flush(w->response.data);
887 buffer_sprintf(w->response.data,
888 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
889 google_responseHandler, google_version, google_reqId);
897 int web_client_parse_request(struct web_client *w) {
901 // query string name-value
904 // http request headers name-value
906 web_client_clean_request(w);
908 debug(D_WEB_DATA, "%llu: Processing data buffer of %d bytes: '%s'.", w->id, w->response.data->bytes, w->response.data->buffer);
910 char *buf = w->response.data->buffer;
913 // ------------------------------------------------------------------------
916 if(buf && (line = strsep(&buf, "\r\n"))) {
918 if(line && (tok = strsep(&line, " "))) {
919 w->request.protocol = strdup(tok);
927 // ------------------------------------------------------------------------
928 // the rest of the lines
930 while(buf && (line = strsep(&buf, "\r\n"))) {
931 while(line && (tok = strsep(&line, ": "))) {
939 web_client_clean_request(w);
944 void web_client_process(struct web_client *w) {
950 // check if we have an empty line (end of HTTP header)
951 if(strstr(w->response.data->buffer, "\r\n\r\n")) {
952 global_statistics_lock();
953 global_statistics.web_requests++;
954 global_statistics_unlock();
956 gettimeofday(&w->tv_in, NULL);
957 debug(D_WEB_DATA, "%llu: Processing data buffer of %d bytes: '%s'.", w->id, w->response.data->len, w->response.data->buffer);
959 // check if the client requested keep-alive HTTP
960 if(strcasestr(w->response.data->buffer, "Connection: keep-alive")) w->keepalive = 1;
961 else w->keepalive = 0;
963 #ifdef NETDATA_WITH_ZLIB
964 // check if the client accepts deflate
965 if(web_enable_gzip && strstr(w->response.data->buffer, "gzip"))
966 web_client_enable_deflate(w);
967 #endif // NETDATA_WITH_ZLIB
969 int datasource_type = DATASOURCE_GOOGLE_JSONP;
970 //if(strstr(w->response.data->buffer, "X-DataSource-Auth"))
971 // datasource_type = DATASOURCE_GOOGLE_JSON;
973 char *buf = w->response.data->buffer;
974 char *tok = strsep(&buf, " \r\n");
976 char *pointer_to_free = NULL; // keep url_decode() allocated buffer
978 if(buf && strcmp(tok, "GET") == 0) {
979 tok = strsep(&buf, " \r\n");
980 pointer_to_free = url = url_decode(tok);
981 debug(D_WEB_CLIENT, "%llu: Processing HTTP GET on url '%s'.", w->id, url);
983 else if (buf && strcmp(tok, "POST") == 0) {
985 tok = strsep(&buf, " \r\n");
986 pointer_to_free = url = url_decode(tok);
988 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);
991 w->last_url[0] = '\0';
993 strncpy(w->last_url, url, URL_MAX);
994 w->last_url[URL_MAX] = '\0';
996 tok = mystrsep(&url, "/?");
998 debug(D_WEB_CLIENT, "%llu: Processing command '%s'.", w->id, tok);
1000 if(strcmp(tok, "api") == 0) {
1001 // the client is requesting api access
1002 datasource_type = DATASOURCE_JSON;
1003 code = web_client_api_request(w, url);
1005 else if(strcmp(tok, WEB_PATH_DATA) == 0) { // "data"
1006 // the client is requesting rrd data
1007 datasource_type = DATASOURCE_JSON;
1008 code = web_client_data_request(w, url, datasource_type);
1010 else if(strcmp(tok, WEB_PATH_DATASOURCE) == 0) { // "datasource"
1011 // the client is requesting google datasource
1012 code = web_client_data_request(w, url, datasource_type);
1014 else if(strcmp(tok, WEB_PATH_GRAPH) == 0) { // "graph"
1015 // the client is requesting an rrd graph
1017 // get the name of the data to show
1018 tok = mystrsep(&url, "/?&");
1019 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1021 // do we have such a data set?
1022 RRDSET *st = rrdset_find_byname(tok);
1023 if(!st) st = rrdset_find(tok);
1026 // try to send a file with that name
1027 buffer_flush(w->response.data);
1028 code = mysendfile(w, tok);
1032 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending %s.json of RRD_STATS...", w->id, st->name);
1033 w->response.data->contenttype = CT_APPLICATION_JSON;
1034 buffer_flush(w->response.data);
1035 rrd_stats_graph_json(st, url, w->response.data);
1038 else if(strcmp(tok, "debug") == 0) {
1039 buffer_flush(w->response.data);
1041 // get the name of the data to show
1042 tok = mystrsep(&url, "/?&");
1043 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1045 // do we have such a data set?
1046 RRDSET *st = rrdset_find_byname(tok);
1047 if(!st) st = rrdset_find(tok);
1050 buffer_sprintf(w->response.data, "Chart %s is not found.\r\n", tok);
1051 debug(D_WEB_CLIENT_ACCESS, "%llu: %s is not found.", w->id, tok);
1055 debug_flags |= D_RRD_STATS;
1056 st->debug = st->debug?0:1;
1057 buffer_sprintf(w->response.data, "Chart %s has now debug %s.\r\n", tok, st->debug?"enabled":"disabled");
1058 debug(D_WEB_CLIENT_ACCESS, "%llu: debug for %s is %s.", w->id, tok, st->debug?"enabled":"disabled");
1061 else if(strcmp(tok, "mirror") == 0) {
1064 debug(D_WEB_CLIENT_ACCESS, "%llu: Mirroring...", w->id);
1066 // replace the zero bytes with spaces
1067 buffer_char_replace(w->response.data, '\0', ' ');
1069 // just leave the buffer as is
1070 // it will be copied back to the client
1072 else if(strcmp(tok, "list") == 0) {
1075 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending list of RRD_STATS...", w->id);
1077 buffer_flush(w->response.data);
1078 RRDSET *st = rrdset_root;
1080 for ( ; st ; st = st->next )
1081 buffer_sprintf(w->response.data, "%s\n", st->name);
1083 else if(strcmp(tok, "all.json") == 0) {
1085 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending JSON list of all monitors of RRD_STATS...", w->id);
1087 w->response.data->contenttype = CT_APPLICATION_JSON;
1088 buffer_flush(w->response.data);
1089 rrd_stats_all_json(w->response.data);
1091 else if(strcmp(tok, "netdata.conf") == 0) {
1093 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending netdata.conf ...", w->id);
1095 w->response.data->contenttype = CT_TEXT_PLAIN;
1096 buffer_flush(w->response.data);
1097 generate_config(w->response.data, 0);
1100 char filename[FILENAME_MAX+1];
1102 strncpy(filename, w->last_url, FILENAME_MAX);
1103 filename[FILENAME_MAX] = '\0';
1104 tok = mystrsep(&url, "?");
1105 buffer_flush(w->response.data);
1106 code = mysendfile(w, (tok && *tok)?tok:"/");
1110 strcpy(w->last_url, "not a valid response");
1112 if(buf) debug(D_WEB_CLIENT_ACCESS, "%llu: Cannot understand '%s'.", w->id, buf);
1115 buffer_flush(w->response.data);
1116 buffer_strcat(w->response.data, "I don't understand you...\r\n");
1119 // free url_decode() buffer
1120 if(pointer_to_free) free(pointer_to_free);
1122 else if(w->response.data->len > 8192) {
1123 strcpy(w->last_url, "too big request");
1125 debug(D_WEB_CLIENT_ACCESS, "%llu: Received request is too big.", w->id);
1128 buffer_flush(w->response.data);
1129 buffer_strcat(w->response.data, "Received request is too big.\r\n");
1132 // wait for more data
1133 w->wait_receive = 1;
1137 gettimeofday(&w->tv_ready, NULL);
1138 w->response.data->date = time(NULL);
1139 w->response.sent = 0;
1140 w->response.code = code;
1142 // prepare the HTTP response header
1143 debug(D_WEB_CLIENT, "%llu: Generating HTTP header with response %d.", w->id, code);
1145 char *content_type_string = "";
1146 switch(w->response.data->contenttype) {
1148 content_type_string = "text/html; charset=utf-8";
1151 case CT_APPLICATION_XML:
1152 content_type_string = "application/xml; charset=utf-8";
1155 case CT_APPLICATION_JSON:
1156 content_type_string = "application/json; charset=utf-8";
1159 case CT_APPLICATION_X_JAVASCRIPT:
1160 content_type_string = "application/x-javascript; charset=utf-8";
1164 content_type_string = "text/css; charset=utf-8";
1168 content_type_string = "text/xml; charset=utf-8";
1172 content_type_string = "text/xsl; charset=utf-8";
1175 case CT_APPLICATION_OCTET_STREAM:
1176 content_type_string = "application/octet-stream";
1179 case CT_IMAGE_SVG_XML:
1180 content_type_string = "image/svg+xml";
1183 case CT_APPLICATION_X_FONT_TRUETYPE:
1184 content_type_string = "application/x-font-truetype";
1187 case CT_APPLICATION_X_FONT_OPENTYPE:
1188 content_type_string = "application/x-font-opentype";
1191 case CT_APPLICATION_FONT_WOFF:
1192 content_type_string = "application/font-woff";
1195 case CT_APPLICATION_VND_MS_FONTOBJ:
1196 content_type_string = "application/vnd.ms-fontobject";
1201 content_type_string = "text/plain; charset=utf-8";
1205 char *code_msg = "";
1212 code_msg = "Temporary Redirect";
1216 code_msg = "Bad Request";
1220 code_msg = "Forbidden";
1224 code_msg = "Not Found";
1228 code_msg = "Internal Server Error";
1233 struct tm tm = *gmtime(&w->response.data->date);
1234 strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %Z", &tm);
1236 buffer_sprintf(w->response.header_output,
1237 "HTTP/1.1 %d %s\r\n"
1238 "Connection: %s\r\n"
1239 "Server: NetData Embedded HTTP Server\r\n"
1240 "Content-Type: %s\r\n"
1241 "Access-Control-Allow-Origin: *\r\n"
1244 , w->keepalive?"keep-alive":"close"
1245 , content_type_string
1249 if(buffer_strlen(w->response.header))
1250 buffer_strcat(w->response.header_output, buffer_tostring(w->response.header));
1252 if(w->mode == WEB_CLIENT_MODE_NORMAL) {
1253 buffer_sprintf(w->response.header_output,
1255 "Cache-Control: no-cache\r\n"
1259 buffer_strcat(w->response.header_output, "Cache-Control: public\r\n");
1261 // if we know the content length, put it
1262 if(!w->response.zoutput && (w->response.data->len || w->response.rlen))
1263 buffer_sprintf(w->response.header_output,
1264 "Content-Length: %ld\r\n"
1265 , w->response.data->len?w->response.data->len:w->response.rlen
1267 else if(!w->response.zoutput)
1268 w->keepalive = 0; // content-length is required for keep-alive
1270 if(w->response.zoutput) {
1271 buffer_strcat(w->response.header_output,
1272 "Content-Encoding: gzip\r\n"
1273 "Transfer-Encoding: chunked\r\n"
1277 buffer_strcat(w->response.header_output, "\r\n");
1279 // disable TCP_NODELAY, to buffer the header
1281 if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0)
1282 error("%llu: failed to disable TCP_NODELAY on socket.", w->id);
1284 // sent the HTTP header
1285 debug(D_WEB_DATA, "%llu: Sending response HTTP header of size %d: '%s'"
1287 , buffer_strlen(w->response.header_output)
1288 , buffer_tostring(w->response.header_output)
1291 bytes = send(w->ofd, buffer_tostring(w->response.header_output), buffer_strlen(w->response.header_output), 0);
1292 if(bytes != buffer_strlen(w->response.header_output))
1293 error("%llu: HTTP Header failed to be sent (I sent %d bytes but the system sent %d bytes)."
1295 , buffer_strlen(w->response.header_output)
1298 global_statistics_lock();
1299 global_statistics.bytes_sent += bytes;
1300 global_statistics_unlock();
1303 // enable TCP_NODELAY, to send all data immediately at the next send()
1305 if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0) error("%llu: failed to enable TCP_NODELAY on socket.", w->id);
1307 // enable sending immediately if we have data
1308 if(w->response.data->len) w->wait_send = 1;
1309 else w->wait_send = 0;
1313 case WEB_CLIENT_MODE_NORMAL:
1314 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Sending data (%d bytes) to client.", w->id, w->response.data->len);
1317 case WEB_CLIENT_MODE_FILECOPY:
1318 if(w->response.rlen) {
1319 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending data file of %d bytes to client.", w->id, w->response.rlen);
1320 w->wait_receive = 1;
1323 // utilize the kernel sendfile() for copying the file to the socket.
1324 // this block of code can be commented, without anything missing.
1325 // when it is commented, the program will copy the data using async I/O.
1327 long len = sendfile(w->ofd, w->ifd, NULL, w->response.data->rbytes);
1328 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);
1329 else web_client_reset(w);
1334 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending an unknown amount of bytes to client.", w->id);
1338 fatal("%llu: Unknown client mode %d.", w->id, w->mode);
1343 long web_client_send_chunk_header(struct web_client *w, int len)
1345 debug(D_DEFLATE, "%llu: OPEN CHUNK of %d bytes (hex: %x).", w->id, len, len);
1347 sprintf(buf, "%X\r\n", len);
1348 int bytes = send(w->ofd, buf, strlen(buf), MSG_DONTWAIT);
1350 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk header %d bytes.", w->id, bytes);
1351 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk header to the client.", w->id);
1352 else debug(D_DEFLATE, "%llu: Failed to send chunk header to client. Reason: %s", w->id, strerror(errno));
1357 long web_client_send_chunk_close(struct web_client *w)
1359 //debug(D_DEFLATE, "%llu: CLOSE CHUNK.", w->id);
1361 int bytes = send(w->ofd, "\r\n", 2, MSG_DONTWAIT);
1363 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
1364 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
1365 else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client. Reason: %s", w->id, strerror(errno));
1370 long web_client_send_chunk_finalize(struct web_client *w)
1372 //debug(D_DEFLATE, "%llu: FINALIZE CHUNK.", w->id);
1374 int bytes = send(w->ofd, "\r\n0\r\n\r\n", 7, MSG_DONTWAIT);
1376 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
1377 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
1378 else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client. Reason: %s", w->id, strerror(errno));
1383 #ifdef NETDATA_WITH_ZLIB
1384 long web_client_send_deflate(struct web_client *w)
1386 long len = 0, t = 0;
1388 // when using compression,
1389 // w->response.sent is the amount of bytes passed through compression
1391 debug(D_DEFLATE, "%llu: TEST 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);
1393 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) {
1394 // there is nothing to send
1396 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1398 // finalize the chunk
1399 if(w->response.sent != 0)
1400 t += web_client_send_chunk_finalize(w);
1402 // there can be two cases for this
1403 // A. we have done everything
1404 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
1406 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->response.rlen && w->response.rlen > w->response.data->len) {
1407 // we have to wait, more data will come
1408 debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1413 if(w->keepalive == 0) {
1414 debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->response.sent);
1420 web_client_reset(w);
1421 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1425 if(w->response.zhave == w->response.zsent) {
1426 // compress more input data
1428 // close the previous open chunk
1429 if(w->response.sent != 0) t += web_client_send_chunk_close(w);
1431 debug(D_DEFLATE, "%llu: Compressing %d bytes starting from %d.", w->id, (w->response.data->len - w->response.sent), w->response.sent);
1433 // give the compressor all the data not passed through the compressor yet
1434 if(w->response.data->len > w->response.sent) {
1435 w->response.zstream.next_in = (Bytef *)&w->response.data->buffer[w->response.sent];
1436 w->response.zstream.avail_in = (w->response.data->len - w->response.sent);
1439 // reset the compressor output buffer
1440 w->response.zstream.next_out = w->response.zbuffer;
1441 w->response.zstream.avail_out = ZLIB_CHUNK;
1443 // ask for FINISH if we have all the input
1444 int flush = Z_SYNC_FLUSH;
1445 if(w->mode == WEB_CLIENT_MODE_NORMAL
1446 || (w->mode == WEB_CLIENT_MODE_FILECOPY && w->response.data->len == w->response.rlen)) {
1448 debug(D_DEFLATE, "%llu: Requesting Z_FINISH.", w->id);
1451 debug(D_DEFLATE, "%llu: Requesting Z_SYNC_FLUSH.", w->id);
1455 if(deflate(&w->response.zstream, flush) == Z_STREAM_ERROR) {
1456 error("%llu: Compression failed. Closing down client.", w->id);
1457 web_client_reset(w);
1461 w->response.zhave = ZLIB_CHUNK - w->response.zstream.avail_out;
1462 w->response.zsent = 0;
1464 // keep track of the bytes passed through the compressor
1465 w->response.sent = w->response.data->len;
1467 debug(D_DEFLATE, "%llu: Compression produced %d bytes.", w->id, w->response.zhave);
1470 t += web_client_send_chunk_header(w, w->response.zhave);
1473 len = send(w->ofd, &w->response.zbuffer[w->response.zsent], w->response.zhave - w->response.zsent, MSG_DONTWAIT);
1475 w->response.zsent += len;
1477 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, len);
1479 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);
1480 else debug(D_WEB_CLIENT, "%llu: Failed to send data to client. Reason: %s", w->id, strerror(errno));
1484 #endif // NETDATA_WITH_ZLIB
1486 long web_client_send(struct web_client *w)
1488 #ifdef NETDATA_WITH_ZLIB
1489 if(likely(w->response.zoutput)) return web_client_send_deflate(w);
1490 #endif // NETDATA_WITH_ZLIB
1494 if(unlikely(w->response.data->len - w->response.sent == 0)) {
1495 // there is nothing to send
1497 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1499 // there can be two cases for this
1500 // A. we have done everything
1501 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
1503 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->response.rlen && w->response.rlen > w->response.data->len) {
1504 // we have to wait, more data will come
1505 debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1510 if(unlikely(w->keepalive == 0)) {
1511 debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->response.sent);
1516 web_client_reset(w);
1517 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1521 bytes = send(w->ofd, &w->response.data->buffer[w->response.sent], w->response.data->len - w->response.sent, MSG_DONTWAIT);
1522 if(likely(bytes > 0)) {
1523 w->response.sent += bytes;
1524 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, bytes);
1526 else if(likely(bytes == 0)) debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client.", w->id);
1527 else debug(D_WEB_CLIENT, "%llu: Failed to send data to client. Reason: %s", w->id, strerror(errno));
1532 long web_client_receive(struct web_client *w)
1534 // do we have any space for more data?
1535 buffer_need_bytes(w->response.data, WEB_REQUEST_LENGTH);
1537 long left = w->response.data->size - w->response.data->len;
1540 if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY))
1541 bytes = read(w->ifd, &w->response.data->buffer[w->response.data->len], (left-1));
1543 bytes = recv(w->ifd, &w->response.data->buffer[w->response.data->len], left-1, MSG_DONTWAIT);
1545 if(likely(bytes > 0)) {
1546 int old = w->response.data->len;
1547 w->response.data->len += bytes;
1548 w->response.data->buffer[w->response.data->len] = '\0';
1550 debug(D_WEB_CLIENT, "%llu: Received %d bytes.", w->id, bytes);
1551 debug(D_WEB_DATA, "%llu: Received data: '%s'.", w->id, &w->response.data->buffer[old]);
1553 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1555 if(w->response.rlen && w->response.data->len >= w->response.rlen) w->wait_receive = 0;
1558 else if(likely(bytes == 0)) {
1559 debug(D_WEB_CLIENT, "%llu: Out of input data.", w->id);
1561 // if we cannot read, it means we have an error on input.
1562 // if however, we are copying a file from ifd to ofd, we should not return an error.
1563 // in this case, the error should be generated when the file has been sent to the client.
1565 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1566 // we are copying data from ifd to ofd
1567 // let it finish copying...
1568 w->wait_receive = 0;
1569 debug(D_WEB_CLIENT, "%llu: Disabling input.", w->id);
1581 // --------------------------------------------------------------------------------------
1582 // the thread of a single client
1584 // 1. waits for input and output, using async I/O
1585 // 2. it processes HTTP requests
1586 // 3. it generates HTTP responses
1587 // 4. it copies data from input to output if mode is FILECOPY
1589 void *web_client_main(void *ptr)
1591 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
1592 error("Cannot set pthread cancel type to DEFERRED.");
1594 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
1595 error("Cannot set pthread cancel state to ENABLE.");
1598 struct web_client *w = ptr;
1600 fd_set ifds, ofds, efds;
1603 log_access("%llu: %s port %s connected on thread task id %d", w->id, w->client_ip, w->client_port, gettid());
1610 FD_SET(w->ifd, &efds);
1612 if(w->ifd != w->ofd)
1613 FD_SET(w->ofd, &efds);
1615 if (w->wait_receive) {
1616 FD_SET(w->ifd, &ifds);
1617 if(w->ifd > fdmax) fdmax = w->ifd;
1621 FD_SET(w->ofd, &ofds);
1622 if(w->ofd > fdmax) fdmax = w->ofd;
1625 tv.tv_sec = web_client_timeout;
1628 debug(D_WEB_CLIENT, "%llu: Waiting socket async I/O for %s %s", w->id, w->wait_receive?"INPUT":"", w->wait_send?"OUTPUT":"");
1629 retval = select(fdmax+1, &ifds, &ofds, &efds, &tv);
1632 debug(D_WEB_CLIENT_ACCESS, "%llu: LISTENER: select() failed.", w->id);
1637 debug(D_WEB_CLIENT_ACCESS, "%llu: LISTENER: timeout.", w->id);
1641 if(FD_ISSET(w->ifd, &efds)) {
1642 debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on input socket (%s).", w->id, strerror(errno));
1646 if(FD_ISSET(w->ofd, &efds)) {
1647 debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on output socket (%s).", w->id, strerror(errno));
1651 if(w->wait_send && FD_ISSET(w->ofd, &ofds)) {
1653 if((bytes = web_client_send(w)) < 0) {
1654 debug(D_WEB_CLIENT, "%llu: Cannot send data to client. Closing client (ouput: %s).", w->id, strerror(errno));
1659 global_statistics_lock();
1660 global_statistics.bytes_sent += bytes;
1661 global_statistics_unlock();
1664 if(w->wait_receive && FD_ISSET(w->ifd, &ifds)) {
1666 if((bytes = web_client_receive(w)) < 0) {
1667 debug(D_WEB_CLIENT, "%llu: Cannot receive data from client. Closing client (input: %s).", w->id, strerror(errno));
1672 global_statistics_lock();
1673 global_statistics.bytes_received += bytes;
1674 global_statistics_unlock();
1676 if(w->mode == WEB_CLIENT_MODE_NORMAL) {
1677 debug(D_WEB_CLIENT, "%llu: Attempting to process received data.", w->id);
1678 web_client_process(w);
1683 log_access("%llu: %s port %s disconnected from thread task id %d", w->id, w->client_ip, w->client_port, gettid());
1684 debug(D_WEB_CLIENT, "%llu: done...", w->id);
1686 web_client_reset(w);