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 extern int netdata_exit;
39 struct web_client *web_clients = NULL;
40 unsigned long long web_clients_count = 0;
42 struct web_client *web_client_create(int listener)
46 w = calloc(1, sizeof(struct web_client));
48 error("Cannot allocate new web_client memory.");
52 w->id = ++web_clients_count;
53 w->mode = WEB_CLIENT_MODE_NORMAL;
56 struct sockaddr *sadr;
59 sadr = (struct sockaddr*) &w->clientaddr;
60 addrlen = sizeof(w->clientaddr);
62 w->ifd = accept(listener, sadr, &addrlen);
64 error("%llu: Cannot accept new incoming connection.", w->id);
70 if(getnameinfo(sadr, addrlen, w->client_ip, NI_MAXHOST, w->client_port, NI_MAXSERV, NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
71 error("Cannot getnameinfo() on received client connection.");
72 strncpy(w->client_ip, "UNKNOWN", NI_MAXHOST);
73 strncpy(w->client_port, "UNKNOWN", NI_MAXSERV);
75 w->client_ip[NI_MAXHOST] = '\0';
76 w->client_port[NI_MAXSERV] = '\0';
78 switch(sadr->sa_family) {
81 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);
85 if(strncmp(w->client_ip, "::ffff:", 7) == 0) {
86 strcpy(w->client_ip, &w->client_ip[7]);
87 debug(D_WEB_CLIENT_ACCESS, "%llu: New IPv4 web client from %s port %s on socket %d.", w->id, w->client_ip, w->client_port, w->ifd);
89 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);
93 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);
98 if(setsockopt(w->ifd, SOL_SOCKET, SO_KEEPALIVE, (char *) &flag, sizeof(int)) != 0) error("%llu: Cannot set SO_KEEPALIVE on socket.", w->id);
101 w->response.data = buffer_create(INITIAL_WEB_DATA_LENGTH);
102 if(unlikely(!w->response.data)) {
103 // no need for error log - web_buffer_create already logged the error
109 w->response.header = buffer_create(HTTP_RESPONSE_HEADER_SIZE);
110 if(unlikely(!w->response.header)) {
111 // no need for error log - web_buffer_create already logged the error
112 buffer_free(w->response.data);
118 w->response.header_output = buffer_create(HTTP_RESPONSE_HEADER_SIZE);
119 if(unlikely(!w->response.header_output)) {
120 // no need for error log - web_buffer_create already logged the error
121 buffer_free(w->response.header);
122 buffer_free(w->response.data);
130 if(web_clients) web_clients->prev = w;
131 w->next = web_clients;
134 global_statistics.connected_clients++;
139 void web_client_reset(struct web_client *w)
142 gettimeofday(&tv, NULL);
144 long sent = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->response.rlen:w->response.data->len;
146 #ifdef NETDATA_WITH_ZLIB
147 if(likely(w->response.zoutput)) sent = (long)w->response.zstream.total_out;
150 long size = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->response.rlen:w->response.data->len;
152 if(likely(w->last_url[0]))
153 log_access("%llu: (sent/all = %ld/%ld bytes %0.0f%%, prep/sent/total = %0.2f/%0.2f/%0.2f ms) %s: %d '%s'",
155 sent, size, -((size>0)?((float)(size-sent)/(float)size * 100.0):0.0),
156 (float)usecdiff(&w->tv_ready, &w->tv_in) / 1000.0,
157 (float)usecdiff(&tv, &w->tv_ready) / 1000.0,
158 (float)usecdiff(&tv, &w->tv_in) / 1000.0,
159 (w->mode == WEB_CLIENT_MODE_FILECOPY)?"filecopy":"data",
164 debug(D_WEB_CLIENT, "%llu: Reseting client.", w->id);
166 if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY)) {
167 debug(D_WEB_CLIENT, "%llu: Closing filecopy input file.", w->id);
172 w->last_url[0] = '\0';
174 w->mode = WEB_CLIENT_MODE_NORMAL;
176 buffer_reset(w->response.header_output);
177 buffer_reset(w->response.header);
178 buffer_reset(w->response.data);
179 w->response.rlen = 0;
180 w->response.sent = 0;
181 w->response.code = 0;
186 w->response.zoutput = 0;
188 // if we had enabled compression, release it
189 #ifdef NETDATA_WITH_ZLIB
190 if(w->response.zinitialized) {
191 debug(D_DEFLATE, "%llu: Reseting compression.", w->id);
192 deflateEnd(&w->response.zstream);
193 w->response.zsent = 0;
194 w->response.zhave = 0;
195 w->response.zstream.avail_in = 0;
196 w->response.zstream.avail_out = 0;
197 w->response.zstream.total_in = 0;
198 w->response.zstream.total_out = 0;
199 w->response.zinitialized = 0;
201 #endif // NETDATA_WITH_ZLIB
204 struct web_client *web_client_free(struct web_client *w)
206 struct web_client *n = w->next;
208 debug(D_WEB_CLIENT_ACCESS, "%llu: Closing web client from %s port %s.", w->id, w->client_ip, w->client_port);
210 if(w->prev) w->prev->next = w->next;
211 if(w->next) w->next->prev = w->prev;
213 if(w == web_clients) web_clients = w->next;
215 if(w->response.header_output) buffer_free(w->response.header_output);
216 if(w->response.header) buffer_free(w->response.header);
217 if(w->response.data) buffer_free(w->response.data);
219 if(w->ofd != w->ifd) close(w->ofd);
222 global_statistics.connected_clients--;
227 uid_t web_files_uid(void)
229 static char *web_owner = NULL;
230 static uid_t owner_uid = 0;
232 if(unlikely(!web_owner)) {
233 web_owner = config_get("global", "web files owner", NETDATA_USER);
234 if(!web_owner || !*web_owner)
235 owner_uid = geteuid();
237 struct passwd *pw = getpwnam(web_owner);
239 error("User %s is not present. Ignoring option. Error: %s\n", web_owner, strerror(errno));
240 owner_uid = geteuid();
243 debug(D_WEB_CLIENT, "Web files owner set to %s.\n", web_owner);
244 owner_uid = pw->pw_uid;
252 int mysendfile(struct web_client *w, char *filename)
254 static char *web_dir = NULL;
256 // initialize our static data
257 if(unlikely(!web_dir)) web_dir = config_get("global", "web files directory", WEB_DIR);
259 debug(D_WEB_CLIENT, "%llu: Looking for file '%s/%s'", w->id, web_dir, filename);
261 // skip leading slashes
262 while (*filename == '/') filename++;
264 // if the filename contain known paths, skip them
265 if(strncmp(filename, WEB_PATH_FILE "/", strlen(WEB_PATH_FILE) + 1) == 0) filename = &filename[strlen(WEB_PATH_FILE) + 1];
268 for(s = filename; *s ;s++) {
269 if( !isalnum(*s) && *s != '/' && *s != '.' && *s != '-' && *s != '_') {
270 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
271 buffer_sprintf(w->response.data, "File '%s' cannot be served. Filename contains invalid character '%c'", *s);
276 // if the filename contains a .. refuse to serve it
277 if(strstr(filename, "..") != 0) {
278 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
279 buffer_sprintf(w->response.data, "File '%s' cannot be served. Relative filenames with '..' in them are not supported.", filename);
284 char webfilename[FILENAME_MAX + 1];
285 snprintf(webfilename, FILENAME_MAX, "%s/%s", web_dir, filename);
287 // check if the file exists
289 if(lstat(webfilename, &stat) != 0) {
290 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not found.", w->id, webfilename);
291 buffer_sprintf(w->response.data, "File '%s' does not exist, or is not accessible.", filename);
295 // check if the file is owned by us
296 if(stat.st_uid != web_files_uid()) {
297 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());
298 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", filename);
302 if((stat.st_mode & S_IFMT) == S_IFDIR) {
303 snprintf(webfilename, FILENAME_MAX+1, "%s/index.html", filename);
304 return mysendfile(w, webfilename);
307 if((stat.st_mode & S_IFMT) != S_IFREG) {
308 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not a regular file. Access Denied.", w->id, webfilename);
309 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", filename);
314 w->ifd = open(webfilename, O_NONBLOCK, O_RDONLY);
318 if(errno == EBUSY || errno == EAGAIN) {
319 error("%llu: File '%s' is busy, sending 307 Moved Temporarily to force retry.", w->id, webfilename);
320 buffer_sprintf(w->response.header, "Location: /" WEB_PATH_FILE "/%s\r\n", filename);
321 buffer_sprintf(w->response.data, "The file '%s' is currently busy. Please try again later.", filename);
325 error("%llu: Cannot open file '%s'.", w->id, webfilename);
326 buffer_sprintf(w->response.data, "Cannot open file '%s'.", filename);
331 // pick a Content-Type for the file
332 if(strstr(filename, ".html") != NULL) w->response.data->contenttype = CT_TEXT_HTML;
333 else if(strstr(filename, ".js") != NULL) w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
334 else if(strstr(filename, ".css") != NULL) w->response.data->contenttype = CT_TEXT_CSS;
335 else if(strstr(filename, ".xml") != NULL) w->response.data->contenttype = CT_TEXT_XML;
336 else if(strstr(filename, ".xsl") != NULL) w->response.data->contenttype = CT_TEXT_XSL;
337 else if(strstr(filename, ".txt") != NULL) w->response.data->contenttype = CT_TEXT_PLAIN;
338 else if(strstr(filename, ".svg") != NULL) w->response.data->contenttype = CT_IMAGE_SVG_XML;
339 else if(strstr(filename, ".ttf") != NULL) w->response.data->contenttype = CT_APPLICATION_X_FONT_TRUETYPE;
340 else if(strstr(filename, ".otf") != NULL) w->response.data->contenttype = CT_APPLICATION_X_FONT_OPENTYPE;
341 else if(strstr(filename, ".woff") != NULL) w->response.data->contenttype = CT_APPLICATION_FONT_WOFF;
342 else if(strstr(filename, ".eot") != NULL) w->response.data->contenttype = CT_APPLICATION_VND_MS_FONTOBJ;
343 else w->response.data->contenttype = CT_APPLICATION_OCTET_STREAM;
345 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);
347 w->mode = WEB_CLIENT_MODE_FILECOPY;
350 buffer_flush(w->response.data);
351 w->response.rlen = stat.st_size;
352 w->response.data->date = stat.st_mtim.tv_sec;
358 #ifdef NETDATA_WITH_ZLIB
359 void web_client_enable_deflate(struct web_client *w) {
360 if(w->response.zinitialized == 1) {
361 error("%llu: Compression has already be initialized for this client.", w->id);
365 if(w->response.sent) {
366 error("%llu: Cannot enable compression in the middle of a conversation.", w->id);
370 w->response.zstream.zalloc = Z_NULL;
371 w->response.zstream.zfree = Z_NULL;
372 w->response.zstream.opaque = Z_NULL;
374 w->response.zstream.next_in = (Bytef *)w->response.data->buffer;
375 w->response.zstream.avail_in = 0;
376 w->response.zstream.total_in = 0;
378 w->response.zstream.next_out = w->response.zbuffer;
379 w->response.zstream.avail_out = 0;
380 w->response.zstream.total_out = 0;
382 w->response.zstream.zalloc = Z_NULL;
383 w->response.zstream.zfree = Z_NULL;
384 w->response.zstream.opaque = Z_NULL;
386 // if(deflateInit(&w->response.zstream, Z_DEFAULT_COMPRESSION) != Z_OK) {
387 // error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
391 // Select GZIP compression: windowbits = 15 + 16 = 31
392 if(deflateInit2(&w->response.zstream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY) != Z_OK) {
393 error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
397 w->response.zsent = 0;
398 w->response.zoutput = 1;
399 w->response.zinitialized = 1;
401 debug(D_DEFLATE, "%llu: Initialized compression.", w->id);
403 #endif // NETDATA_WITH_ZLIB
405 uint32_t web_client_api_request_v1_data_options(char *o)
407 uint32_t ret = 0x00000000;
410 while(o && *o && (tok = mystrsep(&o, ", |"))) {
413 if(!strcmp(tok, "nonzero"))
414 ret |= RRDR_OPTION_NONZERO;
415 else if(!strcmp(tok, "flip") || !strcmp(tok, "reversed") || !strcmp(tok, "reverse"))
416 ret |= RRDR_OPTION_REVERSED;
417 else if(!strcmp(tok, "abs") || !strcmp(tok, "absolute") || !strcmp(tok, "absolute_sum") || !strcmp(tok, "absolute-sum"))
418 ret |= RRDR_OPTION_ABSOLUTE;
419 else if(!strcmp(tok, "min2max"))
420 ret |= RRDR_OPTION_MIN2MAX;
421 else if(!strcmp(tok, "seconds"))
422 ret |= RRDR_OPTION_SECONDS;
423 else if(!strcmp(tok, "ms") || !strcmp(tok, "milliseconds"))
424 ret |= RRDR_OPTION_MILLISECONDS;
425 else if(!strcmp(tok, "null2zero"))
426 ret |= RRDR_OPTION_NULL2ZERO;
427 else if(!strcmp(tok, "objectrows"))
428 ret |= RRDR_OPTION_OBJECTSROWS;
429 else if(!strcmp(tok, "google_json"))
430 ret |= RRDR_OPTION_GOOGLE_JSON;
436 int web_client_api_request_v1_data_format(char *name)
438 if(!strcmp(name, "datatable"))
439 return DATASOURCE_DATATABLE_JSON;
441 else if(!strcmp(name, "datasource"))
442 return DATASOURCE_DATATABLE_JSONP;
444 else if(!strcmp(name, "json"))
445 return DATASOURCE_JSON;
447 else if(!strcmp(name, "jsonp"))
448 return DATASOURCE_JSONP;
450 else if(!strcmp(name, "ssv"))
451 return DATASOURCE_SSV;
453 else if(!strcmp(name, "csv"))
454 return DATASOURCE_CSV;
456 else if(!strcmp(name, "tsv"))
457 return DATASOURCE_TSV;
459 else if(!strcmp(name, "tsv-excel"))
460 return DATASOURCE_TSV;
462 else if(!strcmp(name, "html"))
463 return DATASOURCE_HTML;
465 else if(!strcmp(name, "array"))
466 return DATASOURCE_JS_ARRAY;
468 else if(!strcmp(name, "ssvcomma"))
469 return DATASOURCE_SSV_COMMA;
471 return DATASOURCE_JSON;
474 int web_client_api_request_v1_data_google_format(char *name)
476 if(!strcmp(name, "json"))
477 return DATASOURCE_DATATABLE_JSONP;
479 else if(!strcmp(name, "html"))
480 return DATASOURCE_HTML;
482 else if(!strcmp(name, "csv"))
483 return DATASOURCE_CSV;
485 else if(!strcmp(name, "tsv-excel"))
486 return DATASOURCE_TSV;
488 return DATASOURCE_JSON;
491 int web_client_api_request_v1_data_group(char *name)
493 if(!strcmp(name, "max"))
496 else if(!strcmp(name, "average"))
497 return GROUP_AVERAGE;
502 int web_client_api_request_v1_charts(struct web_client *w, char *url)
506 buffer_flush(w->response.data);
507 rrd_stats_api_v1_charts(w->response.data);
511 int web_client_api_request_v1_chart(struct web_client *w, char *url)
516 buffer_flush(w->response.data);
519 char *value = mystrsep(&url, "?&[]");
520 if(!value || !*value) continue;
522 char *name = mystrsep(&value, "=");
523 if(!name || !*name) continue;
524 if(!value || !*value) continue;
526 // name and value are now the parameters
527 // they are not null and not empty
529 if(!strcmp(name, "chart")) chart = value;
531 buffer_sprintf(w->response.data, "Unknown parameter '%s' in request.", name);
536 if(!chart || !*chart) {
537 buffer_sprintf(w->response.data, "No chart id is given at the request.");
541 RRDSET *st = rrdset_find(chart);
542 if(!st) st = rrdset_find_byname(chart);
544 buffer_sprintf(w->response.data, "Chart '%s' is not found.", chart);
549 w->response.data->contenttype = CT_APPLICATION_JSON;
550 rrd_stats_api_v1_chart(st, w->response.data);
557 // returns the HTTP code
558 int web_client_api_request_v1_data(struct web_client *w, char *url)
560 debug(D_WEB_CLIENT, "%llu: API v1 data with URL '%s'", w->id, url);
563 BUFFER *dimensions = NULL;
565 buffer_flush(w->response.data);
567 char *google_version = "0.6",
570 *google_out = "json",
571 *google_responseHandler = "google.visualization.Query.setResponse",
572 *google_outFileName = NULL;
574 time_t last_timestamp_in_data = 0, google_timestamp = 0;
579 , *points_str = NULL;
581 int format = DATASOURCE_JSON, group = GROUP_MAX;
582 uint32_t options = 0x00000000;
585 char *value = mystrsep(&url, "?&[]");
586 if(!value || !*value) continue;
588 char *name = mystrsep(&value, "=");
589 if(!name || !*name) continue;
590 if(!value || !*value) continue;
592 debug(D_WEB_CLIENT, "%llu: API v1 query param '%s' with value '%s'", w->id, name, value);
594 // name and value are now the parameters
595 // they are not null and not empty
597 if(!strcmp(name, "chart")) chart = value;
598 else if(!strcmp(name, "dimension") || !strcmp(name, "dim") || !strcmp(name, "dimensions") || !strcmp(name, "dims")) {
599 if(!dimensions) dimensions = buffer_create(strlen(value));
601 buffer_strcat(dimensions, "|");
602 buffer_strcat(dimensions, value);
605 else if(!strcmp(name, "after")) after_str = value;
606 else if(!strcmp(name, "before")) before_str = value;
607 else if(!strcmp(name, "points")) points_str = value;
608 else if(!strcmp(name, "group")) {
609 group = web_client_api_request_v1_data_group(value);
611 else if(!strcmp(name, "format")) {
612 format = web_client_api_request_v1_data_format(value);
614 else if(!strcmp(name, "options")) {
615 options |= web_client_api_request_v1_data_options(value);
617 else if(!strcmp(name, "tqx")) {
618 // parse Google Visualization API options
619 // https://developers.google.com/chart/interactive/docs/dev/implementing_data_source
620 char *tqx_name, *tqx_value;
623 tqx_value = mystrsep(&value, ";");
624 if(!tqx_value || !*tqx_value) continue;
626 tqx_name = mystrsep(&tqx_value, ":");
627 if(!tqx_name || !*tqx_name) continue;
628 if(!tqx_value || !*tqx_value) continue;
630 if(!strcmp(tqx_name, "version"))
631 google_version = tqx_value;
632 else if(!strcmp(tqx_name, "reqId"))
633 google_reqId = tqx_value;
634 else if(!strcmp(tqx_name, "sig")) {
635 google_sig = tqx_value;
636 google_timestamp = strtoul(google_sig, NULL, 0);
638 else if(!strcmp(tqx_name, "out")) {
639 google_out = tqx_value;
640 format = web_client_api_request_v1_data_google_format(google_out);
642 else if(!strcmp(tqx_name, "responseHandler"))
643 google_responseHandler = tqx_value;
644 else if(!strcmp(tqx_name, "outFileName"))
645 google_outFileName = tqx_value;
650 if(!chart || !*chart) {
651 buffer_sprintf(w->response.data, "No chart id is given at the request.");
655 RRDSET *st = rrdset_find(chart);
656 if(!st) st = rrdset_find_byname(chart);
658 buffer_sprintf(w->response.data, "Chart '%s' is not found.", chart);
663 long long before = (before_str && *before_str)?atol(before_str):0;
664 long long after = (after_str && *after_str) ?atol(after_str):0;
665 int points = (points_str && *points_str)?atoi(points_str):0;
667 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'"
670 , (dimensions)?buffer_tostring(dimensions):""
679 if(google_outFileName && *google_outFileName) {
680 buffer_sprintf(w->response.header, "Content-Disposition: attachment; filename=\"%s\"\r\n", google_outFileName);
681 error("generating outfilename header: '%s'", google_outFileName);
684 if(format == DATASOURCE_DATATABLE_JSONP) {
685 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSON/JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
686 w->id, google_version, google_reqId, google_sig, google_out, google_responseHandler, google_outFileName
689 buffer_sprintf(w->response.data,
690 "%s({version:'%s',reqId:'%s',status:'ok',sig:'%lu',table:",
691 google_responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
694 ret = rrd2format(st, w->response.data, dimensions, format, points, after, before, group, options, &last_timestamp_in_data);
696 if(format == DATASOURCE_DATATABLE_JSONP) {
697 if(google_timestamp < last_timestamp_in_data)
698 buffer_strcat(w->response.data, "});");
701 // the client already has the latest data
702 buffer_flush(w->response.data);
703 buffer_sprintf(w->response.data,
704 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
705 google_responseHandler, google_version, google_reqId);
710 if(dimensions) buffer_free(dimensions);
714 int web_client_api_request_v1(struct web_client *w, char *url)
717 char *tok = mystrsep(&url, "/?&");
718 debug(D_WEB_CLIENT, "%llu: Searching for API v1 command '%s'.", w->id, tok);
720 if(strcmp(tok, "data") == 0)
721 return web_client_api_request_v1_data(w, url);
722 else if(strcmp(tok, "chart") == 0)
723 return web_client_api_request_v1_chart(w, url);
724 else if(strcmp(tok, "charts") == 0)
725 return web_client_api_request_v1_charts(w, url);
727 buffer_flush(w->response.data);
728 buffer_sprintf(w->response.data, "Unsupported v1 API command: %s", tok);
732 int web_client_api_request(struct web_client *w, char *url)
734 // get the api version
735 char *tok = mystrsep(&url, "/?&");
736 debug(D_WEB_CLIENT, "%llu: Searching for API version '%s'.", w->id, tok);
738 if(strcmp(tok, "v1") == 0)
739 return web_client_api_request_v1(w, url);
741 buffer_flush(w->response.data);
742 buffer_sprintf(w->response.data, "Unsupported API version: %s", tok);
746 int web_client_data_request(struct web_client *w, char *url, int datasource_type)
748 char *args = strchr(url, '?');
754 // get the name of the data to show
755 char *tok = mystrsep(&url, "/");
756 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
758 // do we have such a data set?
759 RRDSET *st = rrdset_find_byname(tok);
760 if(!st) st = rrdset_find(tok);
763 // try to send a file with that name
764 buffer_flush(w->response.data);
765 return(mysendfile(w, tok));
769 debug(D_WEB_CLIENT, "%llu: Found RRD data with name '%s'.", w->id, tok);
771 // how many entries does the client want?
772 long lines = rrd_default_history_entries;
773 long group_count = 1;
774 time_t after = 0, before = 0;
775 int group_method = GROUP_AVERAGE;
779 // parse the lines required
780 tok = mystrsep(&url, "/");
781 if(tok) lines = atoi(tok);
782 if(lines < 1) lines = 1;
785 // parse the group count required
786 tok = mystrsep(&url, "/");
787 if(tok) group_count = atoi(tok);
788 if(group_count < 1) group_count = 1;
789 //if(group_count > save_history / 20) group_count = save_history / 20;
792 // parse the grouping method required
793 tok = mystrsep(&url, "/");
794 if(strcmp(tok, "max") == 0) group_method = GROUP_MAX;
795 else if(strcmp(tok, "average") == 0) group_method = GROUP_AVERAGE;
796 else if(strcmp(tok, "sum") == 0) group_method = GROUP_SUM;
797 else debug(D_WEB_CLIENT, "%llu: Unknown group method '%s'", w->id, tok);
801 tok = mystrsep(&url, "/");
802 if(tok) after = strtoul(tok, NULL, 10);
803 if(after < 0) after = 0;
807 tok = mystrsep(&url, "/");
808 if(tok) before = strtoul(tok, NULL, 10);
809 if(before < 0) before = 0;
813 tok = mystrsep(&url, "/");
814 if(tok && strcmp(tok, "nonzero") == 0) nonzero = 1;
817 w->response.data->contenttype = CT_APPLICATION_JSON;
818 buffer_flush(w->response.data);
820 char *google_version = "0.6";
821 char *google_reqId = "0";
822 char *google_sig = "0";
823 char *google_out = "json";
824 char *google_responseHandler = "google.visualization.Query.setResponse";
825 char *google_outFileName = NULL;
826 unsigned long last_timestamp_in_data = 0;
827 if(datasource_type == DATASOURCE_DATATABLE_JSON || datasource_type == DATASOURCE_DATATABLE_JSONP) {
829 w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
832 tok = mystrsep(&args, "&");
834 char *name = mystrsep(&tok, "=");
835 if(name && strcmp(name, "tqx") == 0) {
836 char *key = mystrsep(&tok, ":");
837 char *value = mystrsep(&tok, ";");
838 if(key && value && *key && *value) {
839 if(strcmp(key, "version") == 0)
840 google_version = value;
842 else if(strcmp(key, "reqId") == 0)
843 google_reqId = value;
845 else if(strcmp(key, "sig") == 0)
848 else if(strcmp(key, "out") == 0)
851 else if(strcmp(key, "responseHandler") == 0)
852 google_responseHandler = value;
854 else if(strcmp(key, "outFileName") == 0)
855 google_outFileName = value;
861 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
862 w->id, google_version, google_reqId, google_sig, google_out, google_responseHandler, google_outFileName
865 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
866 last_timestamp_in_data = strtoul(google_sig, NULL, 0);
868 // check the client wants json
869 if(strcmp(google_out, "json") != 0) {
870 buffer_sprintf(w->response.data,
871 "%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.'}]});",
872 google_responseHandler, google_version, google_reqId, google_out);
878 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
879 buffer_sprintf(w->response.data,
880 "%s({version:'%s',reqId:'%s',status:'ok',sig:'%lu',table:",
881 google_responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
884 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);
885 unsigned long timestamp_in_data = rrd_stats_json(datasource_type, st, w->response.data, lines, group_count, group_method, after, before, nonzero);
887 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
888 if(timestamp_in_data > last_timestamp_in_data)
889 buffer_strcat(w->response.data, "});");
892 // the client already has the latest data
893 buffer_flush(w->response.data);
894 buffer_sprintf(w->response.data,
895 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
896 google_responseHandler, google_version, google_reqId);
904 int web_client_parse_request(struct web_client *w) {
908 // query string name-value
911 // http request headers name-value
913 web_client_clean_request(w);
915 debug(D_WEB_DATA, "%llu: Processing data buffer of %d bytes: '%s'.", w->id, w->response.data->bytes, w->response.data->buffer);
917 char *buf = w->response.data->buffer;
920 // ------------------------------------------------------------------------
923 if(buf && (line = strsep(&buf, "\r\n"))) {
925 if(line && (tok = strsep(&line, " "))) {
926 w->request.protocol = strdup(tok);
934 // ------------------------------------------------------------------------
935 // the rest of the lines
937 while(buf && (line = strsep(&buf, "\r\n"))) {
938 while(line && (tok = strsep(&line, ": "))) {
946 web_client_clean_request(w);
951 void web_client_process(struct web_client *w) {
957 // check if we have an empty line (end of HTTP header)
958 if(strstr(w->response.data->buffer, "\r\n\r\n")) {
959 global_statistics_lock();
960 global_statistics.web_requests++;
961 global_statistics_unlock();
963 gettimeofday(&w->tv_in, NULL);
964 debug(D_WEB_DATA, "%llu: Processing data buffer of %d bytes: '%s'.", w->id, w->response.data->len, w->response.data->buffer);
966 // check if the client requested keep-alive HTTP
967 if(strcasestr(w->response.data->buffer, "Connection: keep-alive")) w->keepalive = 1;
968 else w->keepalive = 0;
970 #ifdef NETDATA_WITH_ZLIB
971 // check if the client accepts deflate
972 if(web_enable_gzip && strstr(w->response.data->buffer, "gzip"))
973 web_client_enable_deflate(w);
974 #endif // NETDATA_WITH_ZLIB
976 int datasource_type = DATASOURCE_DATATABLE_JSONP;
977 //if(strstr(w->response.data->buffer, "X-DataSource-Auth"))
978 // datasource_type = DATASOURCE_GOOGLE_JSON;
980 char *buf = (char *)buffer_tostring(w->response.data);
981 char *tok = strsep(&buf, " \r\n");
983 char *pointer_to_free = NULL; // keep url_decode() allocated buffer
985 if(buf && strcmp(tok, "GET") == 0) {
986 tok = strsep(&buf, " \r\n");
987 pointer_to_free = url = url_decode(tok);
988 debug(D_WEB_CLIENT, "%llu: Processing HTTP GET on url '%s'.", w->id, url);
990 else if (buf && strcmp(tok, "POST") == 0) {
992 tok = strsep(&buf, " \r\n");
993 pointer_to_free = url = url_decode(tok);
995 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);
998 w->last_url[0] = '\0';
1000 strncpy(w->last_url, url, URL_MAX);
1001 w->last_url[URL_MAX] = '\0';
1003 tok = mystrsep(&url, "/?");
1005 debug(D_WEB_CLIENT, "%llu: Processing command '%s'.", w->id, tok);
1007 if(strcmp(tok, "api") == 0) {
1008 // the client is requesting api access
1009 datasource_type = DATASOURCE_JSON;
1010 code = web_client_api_request(w, url);
1013 else if(strcmp(tok, "exit") == 0) {
1016 w->response.data->contenttype = CT_TEXT_PLAIN;
1017 buffer_flush(w->response.data);
1018 buffer_strcat(w->response.data, "will do");
1021 else if(strcmp(tok, WEB_PATH_DATA) == 0) { // "data"
1022 // the client is requesting rrd data
1023 datasource_type = DATASOURCE_JSON;
1024 code = web_client_data_request(w, url, datasource_type);
1026 else if(strcmp(tok, WEB_PATH_DATASOURCE) == 0) { // "datasource"
1027 // the client is requesting google datasource
1028 code = web_client_data_request(w, url, datasource_type);
1030 else if(strcmp(tok, WEB_PATH_GRAPH) == 0) { // "graph"
1031 // the client is requesting an rrd graph
1033 // get the name of the data to show
1034 tok = mystrsep(&url, "/?&");
1035 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1037 // do we have such a data set?
1038 RRDSET *st = rrdset_find_byname(tok);
1039 if(!st) st = rrdset_find(tok);
1042 // try to send a file with that name
1043 buffer_flush(w->response.data);
1044 code = mysendfile(w, tok);
1048 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending %s.json of RRD_STATS...", w->id, st->name);
1049 w->response.data->contenttype = CT_APPLICATION_JSON;
1050 buffer_flush(w->response.data);
1051 rrd_stats_graph_json(st, url, w->response.data);
1054 else if(strcmp(tok, "debug") == 0) {
1055 buffer_flush(w->response.data);
1057 // get the name of the data to show
1058 tok = mystrsep(&url, "/?&");
1059 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1061 // do we have such a data set?
1062 RRDSET *st = rrdset_find_byname(tok);
1063 if(!st) st = rrdset_find(tok);
1066 buffer_sprintf(w->response.data, "Chart %s is not found.\r\n", tok);
1067 debug(D_WEB_CLIENT_ACCESS, "%llu: %s is not found.", w->id, tok);
1071 debug_flags |= D_RRD_STATS;
1072 st->debug = st->debug?0:1;
1073 buffer_sprintf(w->response.data, "Chart %s has now debug %s.\r\n", tok, st->debug?"enabled":"disabled");
1074 debug(D_WEB_CLIENT_ACCESS, "%llu: debug for %s is %s.", w->id, tok, st->debug?"enabled":"disabled");
1077 else if(strcmp(tok, "mirror") == 0) {
1080 debug(D_WEB_CLIENT_ACCESS, "%llu: Mirroring...", w->id);
1082 // replace the zero bytes with spaces
1083 buffer_char_replace(w->response.data, '\0', ' ');
1085 // just leave the buffer as is
1086 // it will be copied back to the client
1088 else if(strcmp(tok, "list") == 0) {
1091 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending list of RRD_STATS...", w->id);
1093 buffer_flush(w->response.data);
1094 RRDSET *st = rrdset_root;
1096 for ( ; st ; st = st->next )
1097 buffer_sprintf(w->response.data, "%s\n", st->name);
1099 else if(strcmp(tok, "all.json") == 0) {
1101 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending JSON list of all monitors of RRD_STATS...", w->id);
1103 w->response.data->contenttype = CT_APPLICATION_JSON;
1104 buffer_flush(w->response.data);
1105 rrd_stats_all_json(w->response.data);
1107 else if(strcmp(tok, "netdata.conf") == 0) {
1109 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending netdata.conf ...", w->id);
1111 w->response.data->contenttype = CT_TEXT_PLAIN;
1112 buffer_flush(w->response.data);
1113 generate_config(w->response.data, 0);
1116 char filename[FILENAME_MAX+1];
1118 strncpy(filename, w->last_url, FILENAME_MAX);
1119 filename[FILENAME_MAX] = '\0';
1120 tok = mystrsep(&url, "?");
1121 buffer_flush(w->response.data);
1122 code = mysendfile(w, (tok && *tok)?tok:"/");
1126 strcpy(w->last_url, "not a valid response");
1128 if(buf) debug(D_WEB_CLIENT_ACCESS, "%llu: Cannot understand '%s'.", w->id, buf);
1131 buffer_flush(w->response.data);
1132 buffer_strcat(w->response.data, "I don't understand you...\r\n");
1135 // free url_decode() buffer
1136 if(pointer_to_free) free(pointer_to_free);
1138 else if(w->response.data->len > 8192) {
1139 strcpy(w->last_url, "too big request");
1141 debug(D_WEB_CLIENT_ACCESS, "%llu: Received request is too big.", w->id);
1144 buffer_flush(w->response.data);
1145 buffer_strcat(w->response.data, "Received request is too big.\r\n");
1148 // wait for more data
1149 w->wait_receive = 1;
1153 gettimeofday(&w->tv_ready, NULL);
1154 w->response.data->date = time(NULL);
1155 w->response.sent = 0;
1156 w->response.code = code;
1158 // prepare the HTTP response header
1159 debug(D_WEB_CLIENT, "%llu: Generating HTTP header with response %d.", w->id, code);
1161 char *content_type_string = "";
1162 switch(w->response.data->contenttype) {
1164 content_type_string = "text/html; charset=utf-8";
1167 case CT_APPLICATION_XML:
1168 content_type_string = "application/xml; charset=utf-8";
1171 case CT_APPLICATION_JSON:
1172 content_type_string = "application/json; charset=utf-8";
1175 case CT_APPLICATION_X_JAVASCRIPT:
1176 content_type_string = "application/x-javascript; charset=utf-8";
1180 content_type_string = "text/css; charset=utf-8";
1184 content_type_string = "text/xml; charset=utf-8";
1188 content_type_string = "text/xsl; charset=utf-8";
1191 case CT_APPLICATION_OCTET_STREAM:
1192 content_type_string = "application/octet-stream";
1195 case CT_IMAGE_SVG_XML:
1196 content_type_string = "image/svg+xml";
1199 case CT_APPLICATION_X_FONT_TRUETYPE:
1200 content_type_string = "application/x-font-truetype";
1203 case CT_APPLICATION_X_FONT_OPENTYPE:
1204 content_type_string = "application/x-font-opentype";
1207 case CT_APPLICATION_FONT_WOFF:
1208 content_type_string = "application/font-woff";
1211 case CT_APPLICATION_VND_MS_FONTOBJ:
1212 content_type_string = "application/vnd.ms-fontobject";
1217 content_type_string = "text/plain; charset=utf-8";
1221 char *code_msg = "";
1228 code_msg = "Temporary Redirect";
1232 code_msg = "Bad Request";
1236 code_msg = "Forbidden";
1240 code_msg = "Not Found";
1244 code_msg = "Internal Server Error";
1249 struct tm tm = *gmtime(&w->response.data->date);
1250 strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %Z", &tm);
1252 buffer_sprintf(w->response.header_output,
1253 "HTTP/1.1 %d %s\r\n"
1254 "Connection: %s\r\n"
1255 "Server: NetData Embedded HTTP Server\r\n"
1256 "Content-Type: %s\r\n"
1257 "Access-Control-Allow-Origin: *\r\n"
1260 , w->keepalive?"keep-alive":"close"
1261 , content_type_string
1265 if(buffer_strlen(w->response.header))
1266 buffer_strcat(w->response.header_output, buffer_tostring(w->response.header));
1268 if(w->mode == WEB_CLIENT_MODE_NORMAL) {
1269 buffer_sprintf(w->response.header_output,
1271 "Cache-Control: no-cache\r\n"
1275 buffer_strcat(w->response.header_output, "Cache-Control: public\r\n");
1277 // if we know the content length, put it
1278 if(!w->response.zoutput && (w->response.data->len || w->response.rlen))
1279 buffer_sprintf(w->response.header_output,
1280 "Content-Length: %ld\r\n"
1281 , w->response.data->len?w->response.data->len:w->response.rlen
1283 else if(!w->response.zoutput)
1284 w->keepalive = 0; // content-length is required for keep-alive
1286 if(w->response.zoutput) {
1287 buffer_strcat(w->response.header_output,
1288 "Content-Encoding: gzip\r\n"
1289 "Transfer-Encoding: chunked\r\n"
1293 buffer_strcat(w->response.header_output, "\r\n");
1295 // disable TCP_NODELAY, to buffer the header
1297 if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0)
1298 error("%llu: failed to disable TCP_NODELAY on socket.", w->id);
1300 // sent the HTTP header
1301 debug(D_WEB_DATA, "%llu: Sending response HTTP header of size %d: '%s'"
1303 , buffer_strlen(w->response.header_output)
1304 , buffer_tostring(w->response.header_output)
1307 bytes = send(w->ofd, buffer_tostring(w->response.header_output), buffer_strlen(w->response.header_output), 0);
1308 if(bytes != buffer_strlen(w->response.header_output))
1309 error("%llu: HTTP Header failed to be sent (I sent %d bytes but the system sent %d bytes)."
1311 , buffer_strlen(w->response.header_output)
1314 global_statistics_lock();
1315 global_statistics.bytes_sent += bytes;
1316 global_statistics_unlock();
1319 // enable TCP_NODELAY, to send all data immediately at the next send()
1321 if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0) error("%llu: failed to enable TCP_NODELAY on socket.", w->id);
1323 // enable sending immediately if we have data
1324 if(w->response.data->len) w->wait_send = 1;
1325 else w->wait_send = 0;
1329 case WEB_CLIENT_MODE_NORMAL:
1330 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Sending data (%d bytes) to client.", w->id, w->response.data->len);
1333 case WEB_CLIENT_MODE_FILECOPY:
1334 if(w->response.rlen) {
1335 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending data file of %d bytes to client.", w->id, w->response.rlen);
1336 w->wait_receive = 1;
1339 // utilize the kernel sendfile() for copying the file to the socket.
1340 // this block of code can be commented, without anything missing.
1341 // when it is commented, the program will copy the data using async I/O.
1343 long len = sendfile(w->ofd, w->ifd, NULL, w->response.data->rbytes);
1344 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);
1345 else web_client_reset(w);
1350 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending an unknown amount of bytes to client.", w->id);
1354 fatal("%llu: Unknown client mode %d.", w->id, w->mode);
1359 long web_client_send_chunk_header(struct web_client *w, int len)
1361 debug(D_DEFLATE, "%llu: OPEN CHUNK of %d bytes (hex: %x).", w->id, len, len);
1363 sprintf(buf, "%X\r\n", len);
1364 int bytes = send(w->ofd, buf, strlen(buf), MSG_DONTWAIT);
1366 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk header %d bytes.", w->id, bytes);
1367 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk header to the client.", w->id);
1368 else debug(D_DEFLATE, "%llu: Failed to send chunk header to client. Reason: %s", w->id, strerror(errno));
1373 long web_client_send_chunk_close(struct web_client *w)
1375 //debug(D_DEFLATE, "%llu: CLOSE CHUNK.", w->id);
1377 int bytes = send(w->ofd, "\r\n", 2, MSG_DONTWAIT);
1379 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
1380 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
1381 else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client. Reason: %s", w->id, strerror(errno));
1386 long web_client_send_chunk_finalize(struct web_client *w)
1388 //debug(D_DEFLATE, "%llu: FINALIZE CHUNK.", w->id);
1390 int bytes = send(w->ofd, "\r\n0\r\n\r\n", 7, MSG_DONTWAIT);
1392 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
1393 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
1394 else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client. Reason: %s", w->id, strerror(errno));
1399 #ifdef NETDATA_WITH_ZLIB
1400 long web_client_send_deflate(struct web_client *w)
1402 long len = 0, t = 0;
1404 // when using compression,
1405 // w->response.sent is the amount of bytes passed through compression
1407 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);
1409 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) {
1410 // there is nothing to send
1412 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1414 // finalize the chunk
1415 if(w->response.sent != 0)
1416 t += web_client_send_chunk_finalize(w);
1418 // there can be two cases for this
1419 // A. we have done everything
1420 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
1422 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->response.rlen && w->response.rlen > w->response.data->len) {
1423 // we have to wait, more data will come
1424 debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1429 if(w->keepalive == 0) {
1430 debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->response.sent);
1436 web_client_reset(w);
1437 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1441 if(w->response.zhave == w->response.zsent) {
1442 // compress more input data
1444 // close the previous open chunk
1445 if(w->response.sent != 0) t += web_client_send_chunk_close(w);
1447 debug(D_DEFLATE, "%llu: Compressing %d bytes starting from %d.", w->id, (w->response.data->len - w->response.sent), w->response.sent);
1449 // give the compressor all the data not passed through the compressor yet
1450 if(w->response.data->len > w->response.sent) {
1451 w->response.zstream.next_in = (Bytef *)&w->response.data->buffer[w->response.sent];
1452 w->response.zstream.avail_in = (w->response.data->len - w->response.sent);
1455 // reset the compressor output buffer
1456 w->response.zstream.next_out = w->response.zbuffer;
1457 w->response.zstream.avail_out = ZLIB_CHUNK;
1459 // ask for FINISH if we have all the input
1460 int flush = Z_SYNC_FLUSH;
1461 if(w->mode == WEB_CLIENT_MODE_NORMAL
1462 || (w->mode == WEB_CLIENT_MODE_FILECOPY && w->response.data->len == w->response.rlen)) {
1464 debug(D_DEFLATE, "%llu: Requesting Z_FINISH.", w->id);
1467 debug(D_DEFLATE, "%llu: Requesting Z_SYNC_FLUSH.", w->id);
1471 if(deflate(&w->response.zstream, flush) == Z_STREAM_ERROR) {
1472 error("%llu: Compression failed. Closing down client.", w->id);
1473 web_client_reset(w);
1477 w->response.zhave = ZLIB_CHUNK - w->response.zstream.avail_out;
1478 w->response.zsent = 0;
1480 // keep track of the bytes passed through the compressor
1481 w->response.sent = w->response.data->len;
1483 debug(D_DEFLATE, "%llu: Compression produced %d bytes.", w->id, w->response.zhave);
1486 t += web_client_send_chunk_header(w, w->response.zhave);
1489 len = send(w->ofd, &w->response.zbuffer[w->response.zsent], w->response.zhave - w->response.zsent, MSG_DONTWAIT);
1491 w->response.zsent += len;
1493 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, len);
1495 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);
1496 else debug(D_WEB_CLIENT, "%llu: Failed to send data to client. Reason: %s", w->id, strerror(errno));
1500 #endif // NETDATA_WITH_ZLIB
1502 long web_client_send(struct web_client *w)
1504 #ifdef NETDATA_WITH_ZLIB
1505 if(likely(w->response.zoutput)) return web_client_send_deflate(w);
1506 #endif // NETDATA_WITH_ZLIB
1510 if(unlikely(w->response.data->len - w->response.sent == 0)) {
1511 // there is nothing to send
1513 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1515 // there can be two cases for this
1516 // A. we have done everything
1517 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
1519 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->response.rlen && w->response.rlen > w->response.data->len) {
1520 // we have to wait, more data will come
1521 debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1526 if(unlikely(w->keepalive == 0)) {
1527 debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->response.sent);
1532 web_client_reset(w);
1533 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1537 bytes = send(w->ofd, &w->response.data->buffer[w->response.sent], w->response.data->len - w->response.sent, MSG_DONTWAIT);
1538 if(likely(bytes > 0)) {
1539 w->response.sent += bytes;
1540 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, bytes);
1542 else if(likely(bytes == 0)) debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client.", w->id);
1543 else debug(D_WEB_CLIENT, "%llu: Failed to send data to client. Reason: %s", w->id, strerror(errno));
1548 long web_client_receive(struct web_client *w)
1550 // do we have any space for more data?
1551 buffer_need_bytes(w->response.data, WEB_REQUEST_LENGTH);
1553 long left = w->response.data->size - w->response.data->len;
1556 if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY))
1557 bytes = read(w->ifd, &w->response.data->buffer[w->response.data->len], (left-1));
1559 bytes = recv(w->ifd, &w->response.data->buffer[w->response.data->len], left-1, MSG_DONTWAIT);
1561 if(likely(bytes > 0)) {
1562 int old = w->response.data->len;
1563 w->response.data->len += bytes;
1564 w->response.data->buffer[w->response.data->len] = '\0';
1566 debug(D_WEB_CLIENT, "%llu: Received %d bytes.", w->id, bytes);
1567 debug(D_WEB_DATA, "%llu: Received data: '%s'.", w->id, &w->response.data->buffer[old]);
1569 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1571 if(w->response.rlen && w->response.data->len >= w->response.rlen) w->wait_receive = 0;
1574 else if(likely(bytes == 0)) {
1575 debug(D_WEB_CLIENT, "%llu: Out of input data.", w->id);
1577 // if we cannot read, it means we have an error on input.
1578 // if however, we are copying a file from ifd to ofd, we should not return an error.
1579 // in this case, the error should be generated when the file has been sent to the client.
1581 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1582 // we are copying data from ifd to ofd
1583 // let it finish copying...
1584 w->wait_receive = 0;
1585 debug(D_WEB_CLIENT, "%llu: Disabling input.", w->id);
1597 // --------------------------------------------------------------------------------------
1598 // the thread of a single client
1600 // 1. waits for input and output, using async I/O
1601 // 2. it processes HTTP requests
1602 // 3. it generates HTTP responses
1603 // 4. it copies data from input to output if mode is FILECOPY
1605 void *web_client_main(void *ptr)
1607 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
1608 error("Cannot set pthread cancel type to DEFERRED.");
1610 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
1611 error("Cannot set pthread cancel state to ENABLE.");
1614 struct web_client *w = ptr;
1616 fd_set ifds, ofds, efds;
1619 log_access("%llu: %s port %s connected on thread task id %d", w->id, w->client_ip, w->client_port, gettid());
1626 FD_SET(w->ifd, &efds);
1628 if(w->ifd != w->ofd)
1629 FD_SET(w->ofd, &efds);
1631 if (w->wait_receive) {
1632 FD_SET(w->ifd, &ifds);
1633 if(w->ifd > fdmax) fdmax = w->ifd;
1637 FD_SET(w->ofd, &ofds);
1638 if(w->ofd > fdmax) fdmax = w->ofd;
1641 tv.tv_sec = web_client_timeout;
1644 debug(D_WEB_CLIENT, "%llu: Waiting socket async I/O for %s %s", w->id, w->wait_receive?"INPUT":"", w->wait_send?"OUTPUT":"");
1645 retval = select(fdmax+1, &ifds, &ofds, &efds, &tv);
1648 debug(D_WEB_CLIENT_ACCESS, "%llu: LISTENER: select() failed.", w->id);
1653 debug(D_WEB_CLIENT_ACCESS, "%llu: LISTENER: timeout.", w->id);
1657 if(FD_ISSET(w->ifd, &efds)) {
1658 debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on input socket (%s).", w->id, strerror(errno));
1662 if(FD_ISSET(w->ofd, &efds)) {
1663 debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on output socket (%s).", w->id, strerror(errno));
1667 if(w->wait_send && FD_ISSET(w->ofd, &ofds)) {
1669 if((bytes = web_client_send(w)) < 0) {
1670 debug(D_WEB_CLIENT, "%llu: Cannot send data to client. Closing client (ouput: %s).", w->id, strerror(errno));
1675 global_statistics_lock();
1676 global_statistics.bytes_sent += bytes;
1677 global_statistics_unlock();
1680 if(w->wait_receive && FD_ISSET(w->ifd, &ifds)) {
1682 if((bytes = web_client_receive(w)) < 0) {
1683 debug(D_WEB_CLIENT, "%llu: Cannot receive data from client. Closing client (input: %s).", w->id, strerror(errno));
1688 global_statistics_lock();
1689 global_statistics.bytes_received += bytes;
1690 global_statistics_unlock();
1692 if(w->mode == WEB_CLIENT_MODE_NORMAL) {
1693 debug(D_WEB_CLIENT, "%llu: Attempting to process received data.", w->id);
1694 web_client_process(w);
1699 log_access("%llu: %s port %s disconnected from thread task id %d", w->id, w->client_ip, w->client_port, gettid());
1700 debug(D_WEB_CLIENT, "%llu: done...", w->id);
1702 web_client_reset(w);