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":((w->mode == WEB_CLIENT_MODE_OPTIONS)?"options":"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.", web_owner);
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 expected user
296 if(stat.st_uid != web_files_uid()) {
297 error("%llu: File '%s' is owned by user %d (expected user %d). Access Denied.", w->id, webfilename, stat.st_uid, web_files_uid());
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 error("%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, ".woff2")!= NULL) w->response.data->contenttype = CT_APPLICATION_FONT_WOFF2;
342 else if(strstr(filename, ".woff") != NULL) w->response.data->contenttype = CT_APPLICATION_FONT_WOFF;
343 else if(strstr(filename, ".eot") != NULL) w->response.data->contenttype = CT_APPLICATION_VND_MS_FONTOBJ;
344 else if(strstr(filename, ".png") != NULL) w->response.data->contenttype = CT_IMAGE_PNG;
345 else if(strstr(filename, ".jpg") != NULL) w->response.data->contenttype = CT_IMAGE_JPG;
346 else if(strstr(filename, ".jpeg") != NULL) w->response.data->contenttype = CT_IMAGE_JPG;
347 else if(strstr(filename, ".gif") != NULL) w->response.data->contenttype = CT_IMAGE_GIF;
348 else if(strstr(filename, ".bmp") != NULL) w->response.data->contenttype = CT_IMAGE_BMP;
349 else if(strstr(filename, ".ico") != NULL) w->response.data->contenttype = CT_IMAGE_XICON;
350 else if(strstr(filename, ".icns") != NULL) w->response.data->contenttype = CT_IMAGE_ICNS;
351 else w->response.data->contenttype = CT_APPLICATION_OCTET_STREAM;
353 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);
355 w->mode = WEB_CLIENT_MODE_FILECOPY;
358 buffer_flush(w->response.data);
359 w->response.rlen = stat.st_size;
360 w->response.data->date = stat.st_mtim.tv_sec;
366 #ifdef NETDATA_WITH_ZLIB
367 void web_client_enable_deflate(struct web_client *w) {
368 if(w->response.zinitialized == 1) {
369 error("%llu: Compression has already be initialized for this client.", w->id);
373 if(w->response.sent) {
374 error("%llu: Cannot enable compression in the middle of a conversation.", w->id);
378 w->response.zstream.zalloc = Z_NULL;
379 w->response.zstream.zfree = Z_NULL;
380 w->response.zstream.opaque = Z_NULL;
382 w->response.zstream.next_in = (Bytef *)w->response.data->buffer;
383 w->response.zstream.avail_in = 0;
384 w->response.zstream.total_in = 0;
386 w->response.zstream.next_out = w->response.zbuffer;
387 w->response.zstream.avail_out = 0;
388 w->response.zstream.total_out = 0;
390 w->response.zstream.zalloc = Z_NULL;
391 w->response.zstream.zfree = Z_NULL;
392 w->response.zstream.opaque = Z_NULL;
394 // if(deflateInit(&w->response.zstream, Z_DEFAULT_COMPRESSION) != Z_OK) {
395 // error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
399 // Select GZIP compression: windowbits = 15 + 16 = 31
400 if(deflateInit2(&w->response.zstream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY) != Z_OK) {
401 error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
405 w->response.zsent = 0;
406 w->response.zoutput = 1;
407 w->response.zinitialized = 1;
409 debug(D_DEFLATE, "%llu: Initialized compression.", w->id);
411 #endif // NETDATA_WITH_ZLIB
413 uint32_t web_client_api_request_v1_data_options(char *o)
415 uint32_t ret = 0x00000000;
418 while(o && *o && (tok = mystrsep(&o, ", |"))) {
421 if(!strcmp(tok, "nonzero"))
422 ret |= RRDR_OPTION_NONZERO;
423 else if(!strcmp(tok, "flip") || !strcmp(tok, "reversed") || !strcmp(tok, "reverse"))
424 ret |= RRDR_OPTION_REVERSED;
425 else if(!strcmp(tok, "jsonwrap"))
426 ret |= RRDR_OPTION_JSON_WRAP;
427 else if(!strcmp(tok, "min2max"))
428 ret |= RRDR_OPTION_MIN2MAX;
429 else if(!strcmp(tok, "ms") || !strcmp(tok, "milliseconds"))
430 ret |= RRDR_OPTION_MILLISECONDS;
431 else if(!strcmp(tok, "abs") || !strcmp(tok, "absolute") || !strcmp(tok, "absolute_sum") || !strcmp(tok, "absolute-sum"))
432 ret |= RRDR_OPTION_ABSOLUTE;
433 else if(!strcmp(tok, "seconds"))
434 ret |= RRDR_OPTION_SECONDS;
435 else if(!strcmp(tok, "null2zero"))
436 ret |= RRDR_OPTION_NULL2ZERO;
437 else if(!strcmp(tok, "objectrows"))
438 ret |= RRDR_OPTION_OBJECTSROWS;
439 else if(!strcmp(tok, "google_json"))
440 ret |= RRDR_OPTION_GOOGLE_JSON;
441 else if(!strcmp(tok, "percentage"))
442 ret |= RRDR_OPTION_PERCENTAGE;
448 uint32_t web_client_api_request_v1_data_format(char *name)
450 if(!strcmp(name, DATASOURCE_FORMAT_DATATABLE_JSON)) // datatable
451 return DATASOURCE_DATATABLE_JSON;
453 else if(!strcmp(name, DATASOURCE_FORMAT_DATATABLE_JSONP)) // datasource
454 return DATASOURCE_DATATABLE_JSONP;
456 else if(!strcmp(name, DATASOURCE_FORMAT_JSON)) // json
457 return DATASOURCE_JSON;
459 else if(!strcmp(name, DATASOURCE_FORMAT_JSONP)) // jsonp
460 return DATASOURCE_JSONP;
462 else if(!strcmp(name, DATASOURCE_FORMAT_SSV)) // ssv
463 return DATASOURCE_SSV;
465 else if(!strcmp(name, DATASOURCE_FORMAT_CSV)) // csv
466 return DATASOURCE_CSV;
468 else if(!strcmp(name, DATASOURCE_FORMAT_TSV) || !strcmp(name, "tsv-excel")) // tsv
469 return DATASOURCE_TSV;
471 else if(!strcmp(name, DATASOURCE_FORMAT_HTML)) // html
472 return DATASOURCE_HTML;
474 else if(!strcmp(name, DATASOURCE_FORMAT_JS_ARRAY)) // array
475 return DATASOURCE_JS_ARRAY;
477 else if(!strcmp(name, DATASOURCE_FORMAT_SSV_COMMA)) // ssvcomma
478 return DATASOURCE_SSV_COMMA;
480 else if(!strcmp(name, DATASOURCE_FORMAT_CSV_JSON_ARRAY)) // csvjsonarray
481 return DATASOURCE_CSV_JSON_ARRAY;
483 return DATASOURCE_JSON;
486 uint32_t web_client_api_request_v1_data_google_format(char *name)
488 if(!strcmp(name, "json"))
489 return DATASOURCE_DATATABLE_JSONP;
491 else if(!strcmp(name, "html"))
492 return DATASOURCE_HTML;
494 else if(!strcmp(name, "csv"))
495 return DATASOURCE_CSV;
497 else if(!strcmp(name, "tsv-excel"))
498 return DATASOURCE_TSV;
500 return DATASOURCE_JSON;
503 int web_client_api_request_v1_data_group(char *name)
505 if(!strcmp(name, "max"))
508 else if(!strcmp(name, "average"))
509 return GROUP_AVERAGE;
514 int web_client_api_request_v1_charts(struct web_client *w, char *url)
518 buffer_flush(w->response.data);
519 w->response.data->contenttype = CT_APPLICATION_JSON;
520 rrd_stats_api_v1_charts(w->response.data);
524 int web_client_api_request_v1_chart(struct web_client *w, char *url)
529 buffer_flush(w->response.data);
532 char *value = mystrsep(&url, "?&[]");
533 if(!value || !*value) continue;
535 char *name = mystrsep(&value, "=");
536 if(!name || !*name) continue;
537 if(!value || !*value) continue;
539 // name and value are now the parameters
540 // they are not null and not empty
542 if(!strcmp(name, "chart")) chart = value;
544 /// buffer_sprintf(w->response.data, "Unknown parameter '%s' in request.", name);
549 if(!chart || !*chart) {
550 buffer_sprintf(w->response.data, "No chart id is given at the request.");
554 RRDSET *st = rrdset_find(chart);
555 if(!st) st = rrdset_find_byname(chart);
557 buffer_sprintf(w->response.data, "Chart '%s' is not found.", chart);
562 w->response.data->contenttype = CT_APPLICATION_JSON;
563 rrd_stats_api_v1_chart(st, w->response.data);
570 // returns the HTTP code
571 int web_client_api_request_v1_data(struct web_client *w, char *url)
573 debug(D_WEB_CLIENT, "%llu: API v1 data with URL '%s'", w->id, url);
576 BUFFER *dimensions = NULL;
578 buffer_flush(w->response.data);
580 char *google_version = "0.6",
583 *google_out = "json",
584 *responseHandler = NULL,
587 time_t last_timestamp_in_data = 0, google_timestamp = 0;
592 , *points_str = NULL;
594 int group = GROUP_MAX;
595 uint32_t format = DATASOURCE_JSON;
596 uint32_t options = 0x00000000;
599 char *value = mystrsep(&url, "?&[]");
600 if(!value || !*value) continue;
602 char *name = mystrsep(&value, "=");
603 if(!name || !*name) continue;
604 if(!value || !*value) continue;
606 debug(D_WEB_CLIENT, "%llu: API v1 query param '%s' with value '%s'", w->id, name, value);
608 // name and value are now the parameters
609 // they are not null and not empty
611 if(!strcmp(name, "chart")) chart = value;
612 else if(!strcmp(name, "dimension") || !strcmp(name, "dim") || !strcmp(name, "dimensions") || !strcmp(name, "dims")) {
613 if(!dimensions) dimensions = buffer_create(strlen(value));
615 buffer_strcat(dimensions, "|");
616 buffer_strcat(dimensions, value);
619 else if(!strcmp(name, "after")) after_str = value;
620 else if(!strcmp(name, "before")) before_str = value;
621 else if(!strcmp(name, "points")) points_str = value;
622 else if(!strcmp(name, "group")) {
623 group = web_client_api_request_v1_data_group(value);
625 else if(!strcmp(name, "format")) {
626 format = web_client_api_request_v1_data_format(value);
628 else if(!strcmp(name, "options")) {
629 options |= web_client_api_request_v1_data_options(value);
631 else if(!strcmp(name, "callback")) {
632 responseHandler = value;
634 else if(!strcmp(name, "filename")) {
637 else if(!strcmp(name, "tqx")) {
638 // parse Google Visualization API options
639 // https://developers.google.com/chart/interactive/docs/dev/implementing_data_source
640 char *tqx_name, *tqx_value;
643 tqx_value = mystrsep(&value, ";");
644 if(!tqx_value || !*tqx_value) continue;
646 tqx_name = mystrsep(&tqx_value, ":");
647 if(!tqx_name || !*tqx_name) continue;
648 if(!tqx_value || !*tqx_value) continue;
650 if(!strcmp(tqx_name, "version"))
651 google_version = tqx_value;
652 else if(!strcmp(tqx_name, "reqId"))
653 google_reqId = tqx_value;
654 else if(!strcmp(tqx_name, "sig")) {
655 google_sig = tqx_value;
656 google_timestamp = strtoul(google_sig, NULL, 0);
658 else if(!strcmp(tqx_name, "out")) {
659 google_out = tqx_value;
660 format = web_client_api_request_v1_data_google_format(google_out);
662 else if(!strcmp(tqx_name, "responseHandler"))
663 responseHandler = tqx_value;
664 else if(!strcmp(tqx_name, "outFileName"))
665 outFileName = tqx_value;
670 if(!chart || !*chart) {
671 buffer_sprintf(w->response.data, "No chart id is given at the request.");
675 RRDSET *st = rrdset_find(chart);
676 if(!st) st = rrdset_find_byname(chart);
678 buffer_sprintf(w->response.data, "Chart '%s' is not found.", chart);
683 long long before = (before_str && *before_str)?atol(before_str):0;
684 long long after = (after_str && *after_str) ?atol(after_str):0;
685 int points = (points_str && *points_str)?atoi(points_str):0;
687 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'"
690 , (dimensions)?buffer_tostring(dimensions):""
699 if(outFileName && *outFileName) {
700 buffer_sprintf(w->response.header, "Content-Disposition: attachment; filename=\"%s\"\r\n", outFileName);
701 error("generating outfilename header: '%s'", outFileName);
704 if(format == DATASOURCE_DATATABLE_JSONP) {
705 if(responseHandler == NULL)
706 responseHandler = "google.visualization.Query.setResponse";
708 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSON/JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
709 w->id, google_version, google_reqId, google_sig, google_out, responseHandler, outFileName
712 buffer_sprintf(w->response.data,
713 "%s({version:'%s',reqId:'%s',status:'ok',sig:'%lu',table:",
714 responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
716 else if(format == DATASOURCE_JSONP) {
717 if(responseHandler == NULL)
718 responseHandler = "callback";
720 buffer_strcat(w->response.data, responseHandler);
721 buffer_strcat(w->response.data, "(");
724 ret = rrd2format(st, w->response.data, dimensions, format, points, after, before, group, options, &last_timestamp_in_data);
726 if(format == DATASOURCE_DATATABLE_JSONP) {
727 if(google_timestamp < last_timestamp_in_data)
728 buffer_strcat(w->response.data, "});");
731 // the client already has the latest data
732 buffer_flush(w->response.data);
733 buffer_sprintf(w->response.data,
734 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
735 responseHandler, google_version, google_reqId);
738 else if(format == DATASOURCE_JSONP)
739 buffer_strcat(w->response.data, ");");
742 if(dimensions) buffer_free(dimensions);
746 int web_client_api_request_v1(struct web_client *w, char *url)
749 char *tok = mystrsep(&url, "/?&");
750 debug(D_WEB_CLIENT, "%llu: Searching for API v1 command '%s'.", w->id, tok);
752 if(strcmp(tok, "data") == 0)
753 return web_client_api_request_v1_data(w, url);
754 else if(strcmp(tok, "chart") == 0)
755 return web_client_api_request_v1_chart(w, url);
756 else if(strcmp(tok, "charts") == 0)
757 return web_client_api_request_v1_charts(w, url);
759 buffer_flush(w->response.data);
760 buffer_sprintf(w->response.data, "Unsupported v1 API command: %s", tok);
764 int web_client_api_request(struct web_client *w, char *url)
766 // get the api version
767 char *tok = mystrsep(&url, "/?&");
768 debug(D_WEB_CLIENT, "%llu: Searching for API version '%s'.", w->id, tok);
770 if(strcmp(tok, "v1") == 0)
771 return web_client_api_request_v1(w, url);
773 buffer_flush(w->response.data);
774 buffer_sprintf(w->response.data, "Unsupported API version: %s", tok);
778 int web_client_data_request(struct web_client *w, char *url, int datasource_type)
780 char *args = strchr(url, '?');
786 // get the name of the data to show
787 char *tok = mystrsep(&url, "/");
788 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
790 // do we have such a data set?
791 RRDSET *st = rrdset_find_byname(tok);
792 if(!st) st = rrdset_find(tok);
795 // try to send a file with that name
796 buffer_flush(w->response.data);
797 return(mysendfile(w, tok));
801 debug(D_WEB_CLIENT, "%llu: Found RRD data with name '%s'.", w->id, tok);
803 // how many entries does the client want?
804 long lines = rrd_default_history_entries;
805 long group_count = 1;
806 time_t after = 0, before = 0;
807 int group_method = GROUP_AVERAGE;
811 // parse the lines required
812 tok = mystrsep(&url, "/");
813 if(tok) lines = atoi(tok);
814 if(lines < 1) lines = 1;
817 // parse the group count required
818 tok = mystrsep(&url, "/");
819 if(tok) group_count = atoi(tok);
820 if(group_count < 1) group_count = 1;
821 //if(group_count > save_history / 20) group_count = save_history / 20;
824 // parse the grouping method required
825 tok = mystrsep(&url, "/");
826 if(strcmp(tok, "max") == 0) group_method = GROUP_MAX;
827 else if(strcmp(tok, "average") == 0) group_method = GROUP_AVERAGE;
828 else if(strcmp(tok, "sum") == 0) group_method = GROUP_SUM;
829 else debug(D_WEB_CLIENT, "%llu: Unknown group method '%s'", w->id, tok);
833 tok = mystrsep(&url, "/");
834 if(tok) after = strtoul(tok, NULL, 10);
835 if(after < 0) after = 0;
839 tok = mystrsep(&url, "/");
840 if(tok) before = strtoul(tok, NULL, 10);
841 if(before < 0) before = 0;
845 tok = mystrsep(&url, "/");
846 if(tok && strcmp(tok, "nonzero") == 0) nonzero = 1;
849 w->response.data->contenttype = CT_APPLICATION_JSON;
850 buffer_flush(w->response.data);
852 char *google_version = "0.6";
853 char *google_reqId = "0";
854 char *google_sig = "0";
855 char *google_out = "json";
856 char *google_responseHandler = "google.visualization.Query.setResponse";
857 char *google_outFileName = NULL;
858 time_t last_timestamp_in_data = 0;
859 if(datasource_type == DATASOURCE_DATATABLE_JSON || datasource_type == DATASOURCE_DATATABLE_JSONP) {
861 w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
864 tok = mystrsep(&args, "&");
866 char *name = mystrsep(&tok, "=");
867 if(name && strcmp(name, "tqx") == 0) {
868 char *key = mystrsep(&tok, ":");
869 char *value = mystrsep(&tok, ";");
870 if(key && value && *key && *value) {
871 if(strcmp(key, "version") == 0)
872 google_version = value;
874 else if(strcmp(key, "reqId") == 0)
875 google_reqId = value;
877 else if(strcmp(key, "sig") == 0)
880 else if(strcmp(key, "out") == 0)
883 else if(strcmp(key, "responseHandler") == 0)
884 google_responseHandler = value;
886 else if(strcmp(key, "outFileName") == 0)
887 google_outFileName = value;
893 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
894 w->id, google_version, google_reqId, google_sig, google_out, google_responseHandler, google_outFileName
897 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
898 last_timestamp_in_data = strtoul(google_sig, NULL, 0);
900 // check the client wants json
901 if(strcmp(google_out, "json") != 0) {
902 buffer_sprintf(w->response.data,
903 "%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.'}]});",
904 google_responseHandler, google_version, google_reqId, google_out);
910 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
911 buffer_sprintf(w->response.data,
912 "%s({version:'%s',reqId:'%s',status:'ok',sig:'%lu',table:",
913 google_responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
916 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);
917 time_t timestamp_in_data = rrd_stats_json(datasource_type, st, w->response.data, lines, group_count, group_method, after, before, nonzero);
919 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
920 if(timestamp_in_data > last_timestamp_in_data)
921 buffer_strcat(w->response.data, "});");
924 // the client already has the latest data
925 buffer_flush(w->response.data);
926 buffer_sprintf(w->response.data,
927 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
928 google_responseHandler, google_version, google_reqId);
936 int web_client_parse_request(struct web_client *w) {
940 // query string name-value
943 // http request headers name-value
945 web_client_clean_request(w);
947 debug(D_WEB_DATA, "%llu: Processing data buffer of %d bytes: '%s'.", w->id, w->response.data->bytes, w->response.data->buffer);
949 char *buf = w->response.data->buffer;
952 // ------------------------------------------------------------------------
955 if(buf && (line = strsep(&buf, "\r\n"))) {
957 if(line && (tok = strsep(&line, " "))) {
958 w->request.protocol = strdup(tok);
966 // ------------------------------------------------------------------------
967 // the rest of the lines
969 while(buf && (line = strsep(&buf, "\r\n"))) {
970 while(line && (tok = strsep(&line, ": "))) {
978 web_client_clean_request(w);
983 void web_client_process(struct web_client *w) {
990 // check if we have an empty line (end of HTTP header)
991 if(strstr(w->response.data->buffer, "\r\n\r\n")) {
992 global_statistics_lock();
993 global_statistics.web_requests++;
994 global_statistics_unlock();
996 gettimeofday(&w->tv_in, NULL);
997 debug(D_WEB_DATA, "%llu: Processing data buffer of %d bytes: '%s'.", w->id, w->response.data->len, w->response.data->buffer);
999 // check if the client requested keep-alive HTTP
1000 if(strcasestr(w->response.data->buffer, "Connection: keep-alive")) w->keepalive = 1;
1001 else w->keepalive = 0;
1003 #ifdef NETDATA_WITH_ZLIB
1004 // check if the client accepts deflate
1005 if(web_enable_gzip && strstr(w->response.data->buffer, "gzip"))
1007 #endif // NETDATA_WITH_ZLIB
1009 int datasource_type = DATASOURCE_DATATABLE_JSONP;
1010 //if(strstr(w->response.data->buffer, "X-DataSource-Auth"))
1011 // datasource_type = DATASOURCE_GOOGLE_JSON;
1013 char *buf = (char *)buffer_tostring(w->response.data);
1014 char *tok = strsep(&buf, " \r\n");
1016 char *pointer_to_free = NULL; // keep url_decode() allocated buffer
1018 w->mode = WEB_CLIENT_MODE_NORMAL;
1020 if(buf && strcmp(tok, "GET") == 0) {
1021 tok = strsep(&buf, " \r\n");
1022 pointer_to_free = url = url_decode(tok);
1023 debug(D_WEB_CLIENT, "%llu: Processing HTTP GET on url '%s'.", w->id, url);
1025 else if(buf && strcmp(tok, "OPTIONS") == 0) {
1026 tok = strsep(&buf, " \r\n");
1027 pointer_to_free = url = url_decode(tok);
1028 debug(D_WEB_CLIENT, "%llu: Processing HTTP OPTIONS on url '%s'.", w->id, url);
1029 w->mode = WEB_CLIENT_MODE_OPTIONS;
1031 else if (buf && strcmp(tok, "POST") == 0) {
1033 tok = strsep(&buf, " \r\n");
1034 pointer_to_free = url = url_decode(tok);
1035 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);
1038 w->last_url[0] = '\0';
1040 if(w->mode == WEB_CLIENT_MODE_OPTIONS) {
1041 strncpy(w->last_url, url, URL_MAX);
1042 w->last_url[URL_MAX] = '\0';
1045 w->response.data->contenttype = CT_TEXT_PLAIN;
1046 buffer_flush(w->response.data);
1047 buffer_strcat(w->response.data, "OK");
1050 #ifdef NETDATA_WITH_ZLIB
1052 web_client_enable_deflate(w);
1055 strncpy(w->last_url, url, URL_MAX);
1056 w->last_url[URL_MAX] = '\0';
1058 tok = mystrsep(&url, "/?");
1060 debug(D_WEB_CLIENT, "%llu: Processing command '%s'.", w->id, tok);
1062 if(strcmp(tok, "api") == 0) {
1063 // the client is requesting api access
1064 datasource_type = DATASOURCE_JSON;
1065 code = web_client_api_request(w, url);
1067 #ifdef NETDATA_INTERNAL_CHECKS
1068 else if(strcmp(tok, "exit") == 0) {
1071 w->response.data->contenttype = CT_TEXT_PLAIN;
1072 buffer_flush(w->response.data);
1073 buffer_strcat(w->response.data, "will do");
1076 else if(strcmp(tok, WEB_PATH_DATA) == 0) { // "data"
1077 // the client is requesting rrd data
1078 datasource_type = DATASOURCE_JSON;
1079 code = web_client_data_request(w, url, datasource_type);
1081 else if(strcmp(tok, WEB_PATH_DATASOURCE) == 0) { // "datasource"
1082 // the client is requesting google datasource
1083 code = web_client_data_request(w, url, datasource_type);
1085 else if(strcmp(tok, WEB_PATH_GRAPH) == 0) { // "graph"
1086 // the client is requesting an rrd graph
1088 // get the name of the data to show
1089 tok = mystrsep(&url, "/?&");
1090 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1092 // do we have such a data set?
1093 RRDSET *st = rrdset_find_byname(tok);
1094 if(!st) st = rrdset_find(tok);
1097 // try to send a file with that name
1098 buffer_flush(w->response.data);
1099 code = mysendfile(w, tok);
1103 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending %s.json of RRD_STATS...", w->id, st->name);
1104 w->response.data->contenttype = CT_APPLICATION_JSON;
1105 buffer_flush(w->response.data);
1106 rrd_stats_graph_json(st, url, w->response.data);
1109 #ifdef NETDATA_INTERNAL_CHECKS
1110 else if(strcmp(tok, "debug") == 0) {
1111 buffer_flush(w->response.data);
1113 // get the name of the data to show
1114 tok = mystrsep(&url, "/?&");
1115 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1117 // do we have such a data set?
1118 RRDSET *st = rrdset_find_byname(tok);
1119 if(!st) st = rrdset_find(tok);
1122 buffer_sprintf(w->response.data, "Chart %s is not found.\r\n", tok);
1123 debug(D_WEB_CLIENT_ACCESS, "%llu: %s is not found.", w->id, tok);
1127 debug_flags |= D_RRD_STATS;
1128 st->debug = st->debug?0:1;
1129 buffer_sprintf(w->response.data, "Chart %s has now debug %s.\r\n", tok, st->debug?"enabled":"disabled");
1130 debug(D_WEB_CLIENT_ACCESS, "%llu: debug for %s is %s.", w->id, tok, st->debug?"enabled":"disabled");
1133 else if(strcmp(tok, "mirror") == 0) {
1136 debug(D_WEB_CLIENT_ACCESS, "%llu: Mirroring...", w->id);
1138 // replace the zero bytes with spaces
1139 buffer_char_replace(w->response.data, '\0', ' ');
1141 // just leave the buffer as is
1142 // it will be copied back to the client
1145 else if(strcmp(tok, "list") == 0) {
1148 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending list of RRD_STATS...", w->id);
1150 buffer_flush(w->response.data);
1151 RRDSET *st = rrdset_root;
1153 for ( ; st ; st = st->next )
1154 buffer_sprintf(w->response.data, "%s\n", st->name);
1156 else if(strcmp(tok, "all.json") == 0) {
1158 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending JSON list of all monitors of RRD_STATS...", w->id);
1160 w->response.data->contenttype = CT_APPLICATION_JSON;
1161 buffer_flush(w->response.data);
1162 rrd_stats_all_json(w->response.data);
1164 else if(strcmp(tok, "netdata.conf") == 0) {
1166 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending netdata.conf ...", w->id);
1168 w->response.data->contenttype = CT_TEXT_PLAIN;
1169 buffer_flush(w->response.data);
1170 generate_config(w->response.data, 0);
1173 char filename[FILENAME_MAX+1];
1175 strncpy(filename, w->last_url, FILENAME_MAX);
1176 filename[FILENAME_MAX] = '\0';
1177 tok = mystrsep(&url, "?");
1178 buffer_flush(w->response.data);
1179 code = mysendfile(w, (tok && *tok)?tok:"/");
1183 strcpy(w->last_url, "not a valid response");
1185 if(buf) debug(D_WEB_CLIENT_ACCESS, "%llu: Cannot understand '%s'.", w->id, buf);
1188 buffer_flush(w->response.data);
1189 buffer_strcat(w->response.data, "I don't understand you...\r\n");
1192 // free url_decode() buffer
1193 if(pointer_to_free) free(pointer_to_free);
1195 else if(w->response.data->len > 8192) {
1196 strcpy(w->last_url, "too big request");
1198 debug(D_WEB_CLIENT_ACCESS, "%llu: Received request is too big.", w->id);
1201 buffer_flush(w->response.data);
1202 buffer_strcat(w->response.data, "Received request is too big.\r\n");
1205 // wait for more data
1206 w->wait_receive = 1;
1210 gettimeofday(&w->tv_ready, NULL);
1211 w->response.data->date = time(NULL);
1212 w->response.sent = 0;
1213 w->response.code = code;
1215 // prepare the HTTP response header
1216 debug(D_WEB_CLIENT, "%llu: Generating HTTP header with response %d.", w->id, code);
1218 char *content_type_string;
1219 switch(w->response.data->contenttype) {
1221 content_type_string = "text/html; charset=utf-8";
1224 case CT_APPLICATION_XML:
1225 content_type_string = "application/xml; charset=utf-8";
1228 case CT_APPLICATION_JSON:
1229 content_type_string = "application/json; charset=utf-8";
1232 case CT_APPLICATION_X_JAVASCRIPT:
1233 content_type_string = "application/x-javascript; charset=utf-8";
1237 content_type_string = "text/css; charset=utf-8";
1241 content_type_string = "text/xml; charset=utf-8";
1245 content_type_string = "text/xsl; charset=utf-8";
1248 case CT_APPLICATION_OCTET_STREAM:
1249 content_type_string = "application/octet-stream";
1252 case CT_IMAGE_SVG_XML:
1253 content_type_string = "image/svg+xml";
1256 case CT_APPLICATION_X_FONT_TRUETYPE:
1257 content_type_string = "application/x-font-truetype";
1260 case CT_APPLICATION_X_FONT_OPENTYPE:
1261 content_type_string = "application/x-font-opentype";
1264 case CT_APPLICATION_FONT_WOFF:
1265 content_type_string = "application/font-woff";
1268 case CT_APPLICATION_FONT_WOFF2:
1269 content_type_string = "application/font-woff2";
1272 case CT_APPLICATION_VND_MS_FONTOBJ:
1273 content_type_string = "application/vnd.ms-fontobject";
1277 content_type_string = "image/png";
1281 content_type_string = "image/jpeg";
1285 content_type_string = "image/gif";
1288 case CT_IMAGE_XICON:
1289 content_type_string = "image/x-icon";
1293 content_type_string = "image/bmp";
1297 content_type_string = "image/icns";
1302 content_type_string = "text/plain; charset=utf-8";
1313 code_msg = "Temporary Redirect";
1317 code_msg = "Bad Request";
1321 code_msg = "Forbidden";
1325 code_msg = "Not Found";
1329 code_msg = "Internal Server Error";
1334 struct tm tmbuf, *tm = gmtime_r(&w->response.data->date, &tmbuf);
1335 strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %Z", tm);
1337 buffer_sprintf(w->response.header_output,
1338 "HTTP/1.1 %d %s\r\n"
1339 "Connection: %s\r\n"
1340 "Server: NetData Embedded HTTP Server\r\n"
1341 "Content-Type: %s\r\n"
1342 "Access-Control-Allow-Origin: *\r\n"
1343 "Access-Control-Allow-Methods: GET, OPTIONS\r\n"
1344 "Access-Control-Allow-Headers: accept, x-requested-with\r\n"
1345 "Access-Control-Max-Age: 86400\r\n"
1348 , w->keepalive?"keep-alive":"close"
1349 , content_type_string
1353 if(buffer_strlen(w->response.header))
1354 buffer_strcat(w->response.header_output, buffer_tostring(w->response.header));
1356 if(w->mode == WEB_CLIENT_MODE_NORMAL && (w->response.data->options & WB_CONTENT_NO_CACHEABLE)) {
1357 buffer_sprintf(w->response.header_output,
1359 "Cache-Control: no-cache\r\n"
1364 time_t et = w->response.data->date + (86400 * 14);
1365 struct tm etmbuf, *etm = gmtime_r(&et, &etmbuf);
1366 strftime(edate, sizeof(edate), "%a, %d %b %Y %H:%M:%S %Z", etm);
1368 buffer_sprintf(w->response.header_output,
1370 "Cache-Control: public\r\n"
1374 // if we know the content length, put it
1375 if(!w->response.zoutput && (w->response.data->len || w->response.rlen))
1376 buffer_sprintf(w->response.header_output,
1377 "Content-Length: %ld\r\n"
1378 , w->response.data->len? w->response.data->len: w->response.rlen
1380 else if(!w->response.zoutput)
1381 w->keepalive = 0; // content-length is required for keep-alive
1383 if(w->response.zoutput) {
1384 buffer_strcat(w->response.header_output,
1385 "Content-Encoding: gzip\r\n"
1386 "Transfer-Encoding: chunked\r\n"
1390 buffer_strcat(w->response.header_output, "\r\n");
1392 // disable TCP_NODELAY, to buffer the header
1394 if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0)
1395 error("%llu: failed to disable TCP_NODELAY on socket.", w->id);
1397 // sent the HTTP header
1398 debug(D_WEB_DATA, "%llu: Sending response HTTP header of size %d: '%s'"
1400 , buffer_strlen(w->response.header_output)
1401 , buffer_tostring(w->response.header_output)
1404 bytes = send(w->ofd, buffer_tostring(w->response.header_output), buffer_strlen(w->response.header_output), 0);
1405 if(bytes != (ssize_t) buffer_strlen(w->response.header_output))
1406 error("%llu: HTTP Header failed to be sent (I sent %d bytes but the system sent %d bytes)."
1408 , buffer_strlen(w->response.header_output)
1411 global_statistics_lock();
1412 global_statistics.bytes_sent += bytes;
1413 global_statistics_unlock();
1416 // enable TCP_NODELAY, to send all data immediately at the next send()
1418 if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0) error("%llu: failed to enable TCP_NODELAY on socket.", w->id);
1420 // enable sending immediately if we have data
1421 if(w->response.data->len) w->wait_send = 1;
1422 else w->wait_send = 0;
1426 case WEB_CLIENT_MODE_OPTIONS:
1427 debug(D_WEB_CLIENT, "%llu: Done preparing the OPTIONS response. Sending data (%d bytes) to client.", w->id, w->response.data->len);
1430 case WEB_CLIENT_MODE_NORMAL:
1431 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Sending data (%d bytes) to client.", w->id, w->response.data->len);
1434 case WEB_CLIENT_MODE_FILECOPY:
1435 if(w->response.rlen) {
1436 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending data file of %d bytes to client.", w->id, w->response.rlen);
1437 w->wait_receive = 1;
1440 // utilize the kernel sendfile() for copying the file to the socket.
1441 // this block of code can be commented, without anything missing.
1442 // when it is commented, the program will copy the data using async I/O.
1444 long len = sendfile(w->ofd, w->ifd, NULL, w->response.data->rbytes);
1445 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);
1446 else web_client_reset(w);
1451 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending an unknown amount of bytes to client.", w->id);
1455 fatal("%llu: Unknown client mode %d.", w->id, w->mode);
1460 long web_client_send_chunk_header(struct web_client *w, long len)
1462 debug(D_DEFLATE, "%llu: OPEN CHUNK of %d bytes (hex: %x).", w->id, len, len);
1464 sprintf(buf, "%lX\r\n", len);
1465 ssize_t bytes = send(w->ofd, buf, strlen(buf), MSG_DONTWAIT);
1467 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk header %d bytes.", w->id, bytes);
1468 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk header to the client.", w->id);
1469 else debug(D_DEFLATE, "%llu: Failed to send chunk header to client.", w->id);
1474 long web_client_send_chunk_close(struct web_client *w)
1476 //debug(D_DEFLATE, "%llu: CLOSE CHUNK.", w->id);
1478 ssize_t bytes = send(w->ofd, "\r\n", 2, MSG_DONTWAIT);
1480 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
1481 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
1482 else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client.", w->id);
1487 long web_client_send_chunk_finalize(struct web_client *w)
1489 //debug(D_DEFLATE, "%llu: FINALIZE CHUNK.", w->id);
1491 ssize_t bytes = send(w->ofd, "\r\n0\r\n\r\n", 7, MSG_DONTWAIT);
1493 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
1494 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
1495 else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client.", w->id);
1500 #ifdef NETDATA_WITH_ZLIB
1501 long web_client_send_deflate(struct web_client *w)
1503 long len = 0, t = 0;
1505 // when using compression,
1506 // w->response.sent is the amount of bytes passed through compression
1508 debug(D_DEFLATE, "%llu: web_client_send_deflate(): w->response.data->len = %d, w->response.sent = %d, w->response.zhave = %d, w->response.zsent = %d, w->response.zstream.avail_in = %d, w->response.zstream.avail_out = %d, w->response.zstream.total_in = %d, w->response.zstream.total_out = %d.", w->id, w->response.data->len, w->response.sent, w->response.zhave, w->response.zsent, w->response.zstream.avail_in, w->response.zstream.avail_out, w->response.zstream.total_in, w->response.zstream.total_out);
1510 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) {
1511 // there is nothing to send
1513 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1515 // finalize the chunk
1516 if(w->response.sent != 0)
1517 t += web_client_send_chunk_finalize(w);
1519 // there can be two cases for this
1520 // A. we have done everything
1521 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
1523 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->response.rlen && w->response.rlen > w->response.data->len) {
1524 // we have to wait, more data will come
1525 debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1530 if(w->keepalive == 0) {
1531 debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->response.sent);
1537 web_client_reset(w);
1538 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1542 if(w->response.zhave == w->response.zsent) {
1543 // compress more input data
1545 // close the previous open chunk
1546 if(w->response.sent != 0) t += web_client_send_chunk_close(w);
1548 debug(D_DEFLATE, "%llu: Compressing %d new bytes starting from %d (and %d left behind).", w->id, (w->response.data->len - w->response.sent), w->response.sent, w->response.zstream.avail_in);
1550 // give the compressor all the data not passed through the compressor yet
1551 if(w->response.data->len > w->response.sent) {
1552 #ifdef NETDATA_INTERNAL_CHECKS
1553 if((long)w->response.sent - (long)w->response.zstream.avail_in < 0)
1554 error("internal error: avail_in is corrupted.");
1556 w->response.zstream.next_in = (Bytef *)&w->response.data->buffer[w->response.sent - w->response.zstream.avail_in];
1557 w->response.zstream.avail_in += (uInt) (w->response.data->len - w->response.sent);
1560 // reset the compressor output buffer
1561 w->response.zstream.next_out = w->response.zbuffer;
1562 w->response.zstream.avail_out = ZLIB_CHUNK;
1564 // ask for FINISH if we have all the input
1565 int flush = Z_SYNC_FLUSH;
1566 if(w->mode == WEB_CLIENT_MODE_NORMAL
1567 || (w->mode == WEB_CLIENT_MODE_FILECOPY && !w->wait_receive && w->response.data->len == w->response.rlen)) {
1569 debug(D_DEFLATE, "%llu: Requesting Z_FINISH, if possible.", w->id);
1572 debug(D_DEFLATE, "%llu: Requesting Z_SYNC_FLUSH.", w->id);
1576 if(deflate(&w->response.zstream, flush) == Z_STREAM_ERROR) {
1577 error("%llu: Compression failed. Closing down client.", w->id);
1578 web_client_reset(w);
1582 w->response.zhave = ZLIB_CHUNK - w->response.zstream.avail_out;
1583 w->response.zsent = 0;
1585 // keep track of the bytes passed through the compressor
1586 w->response.sent = w->response.data->len;
1588 debug(D_DEFLATE, "%llu: Compression produced %d bytes.", w->id, w->response.zhave);
1591 t += web_client_send_chunk_header(w, w->response.zhave);
1594 debug(D_WEB_CLIENT, "%llu: Sending %d bytes of data (+%d of chunk header).", w->id, w->response.zhave - w->response.zsent, t);
1596 len = send(w->ofd, &w->response.zbuffer[w->response.zsent], (size_t) (w->response.zhave - w->response.zsent), MSG_DONTWAIT);
1598 w->response.zsent += len;
1600 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, len);
1602 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);
1603 else debug(D_WEB_CLIENT, "%llu: Failed to send data to client. Reason: %s", w->id, strerror(errno));
1607 #endif // NETDATA_WITH_ZLIB
1609 long web_client_send(struct web_client *w)
1611 #ifdef NETDATA_WITH_ZLIB
1612 if(likely(w->response.zoutput)) return web_client_send_deflate(w);
1613 #endif // NETDATA_WITH_ZLIB
1617 if(unlikely(w->response.data->len - w->response.sent == 0)) {
1618 // there is nothing to send
1620 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1622 // there can be two cases for this
1623 // A. we have done everything
1624 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
1626 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->response.rlen && w->response.rlen > w->response.data->len) {
1627 // we have to wait, more data will come
1628 debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1633 if(unlikely(w->keepalive == 0)) {
1634 debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->response.sent);
1639 web_client_reset(w);
1640 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1644 bytes = send(w->ofd, &w->response.data->buffer[w->response.sent], w->response.data->len - w->response.sent, MSG_DONTWAIT);
1645 if(likely(bytes > 0)) {
1646 w->response.sent += bytes;
1647 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, bytes);
1649 else if(likely(bytes == 0)) debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client.", w->id);
1650 else debug(D_WEB_CLIENT, "%llu: Failed to send data to client.", w->id);
1655 long web_client_receive(struct web_client *w)
1657 // do we have any space for more data?
1658 buffer_need_bytes(w->response.data, WEB_REQUEST_LENGTH);
1660 long left = w->response.data->size - w->response.data->len;
1663 if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY))
1664 bytes = read(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1));
1666 bytes = recv(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1), MSG_DONTWAIT);
1668 if(likely(bytes > 0)) {
1669 size_t old = w->response.data->len;
1670 w->response.data->len += bytes;
1671 w->response.data->buffer[w->response.data->len] = '\0';
1673 debug(D_WEB_CLIENT, "%llu: Received %d bytes.", w->id, bytes);
1674 debug(D_WEB_DATA, "%llu: Received data: '%s'.", w->id, &w->response.data->buffer[old]);
1676 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1678 if(w->response.rlen && w->response.data->len >= w->response.rlen) w->wait_receive = 0;
1681 else if(likely(bytes == 0)) {
1682 debug(D_WEB_CLIENT, "%llu: Out of input data.", w->id);
1684 // if we cannot read, it means we have an error on input.
1685 // if however, we are copying a file from ifd to ofd, we should not return an error.
1686 // in this case, the error should be generated when the file has been sent to the client.
1688 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1689 // we are copying data from ifd to ofd
1690 // let it finish copying...
1691 w->wait_receive = 0;
1692 debug(D_WEB_CLIENT, "%llu: Disabling input.", w->id);
1704 // --------------------------------------------------------------------------------------
1705 // the thread of a single client
1707 // 1. waits for input and output, using async I/O
1708 // 2. it processes HTTP requests
1709 // 3. it generates HTTP responses
1710 // 4. it copies data from input to output if mode is FILECOPY
1712 void *web_client_main(void *ptr)
1714 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
1715 error("Cannot set pthread cancel type to DEFERRED.");
1717 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
1718 error("Cannot set pthread cancel state to ENABLE.");
1721 struct web_client *w = ptr;
1723 fd_set ifds, ofds, efds;
1726 log_access("%llu: %s port %s connected on thread task id %d", w->id, w->client_ip, w->client_port, gettid());
1733 FD_SET(w->ifd, &efds);
1735 if(w->ifd != w->ofd)
1736 FD_SET(w->ofd, &efds);
1738 if (w->wait_receive) {
1739 FD_SET(w->ifd, &ifds);
1740 if(w->ifd > fdmax) fdmax = w->ifd;
1744 FD_SET(w->ofd, &ofds);
1745 if(w->ofd > fdmax) fdmax = w->ofd;
1748 tv.tv_sec = web_client_timeout;
1751 debug(D_WEB_CLIENT, "%llu: Waiting socket async I/O for %s %s", w->id, w->wait_receive?"INPUT":"", w->wait_send?"OUTPUT":"");
1752 retval = select(fdmax+1, &ifds, &ofds, &efds, &tv);
1755 debug(D_WEB_CLIENT_ACCESS, "%llu: LISTENER: select() failed.", w->id);
1760 debug(D_WEB_CLIENT_ACCESS, "%llu: LISTENER: timeout.", w->id);
1764 if(FD_ISSET(w->ifd, &efds)) {
1765 debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on input socket.", w->id);
1769 if(FD_ISSET(w->ofd, &efds)) {
1770 debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on output socket.", w->id);
1774 if(w->wait_send && FD_ISSET(w->ofd, &ofds)) {
1776 if((bytes = web_client_send(w)) < 0) {
1777 debug(D_WEB_CLIENT, "%llu: Cannot send data to client. Closing client.", w->id);
1782 global_statistics_lock();
1783 global_statistics.bytes_sent += bytes;
1784 global_statistics_unlock();
1787 if(w->wait_receive && FD_ISSET(w->ifd, &ifds)) {
1789 if((bytes = web_client_receive(w)) < 0) {
1790 debug(D_WEB_CLIENT, "%llu: Cannot receive data from client. Closing client.", w->id);
1795 if(w->mode == WEB_CLIENT_MODE_NORMAL) {
1796 debug(D_WEB_CLIENT, "%llu: Attempting to process received data (%ld bytes).", w->id, bytes);
1797 // info("%llu: Attempting to process received data (%ld bytes).", w->id, bytes);
1798 web_client_process(w);
1801 global_statistics_lock();
1802 global_statistics.bytes_received += bytes;
1803 global_statistics_unlock();
1807 log_access("%llu: %s port %s disconnected from thread task id %d", w->id, w->client_ip, w->client_port, gettid());
1808 debug(D_WEB_CLIENT, "%llu: done...", w->id);
1810 web_client_reset(w);