7 #include <sys/socket.h>
8 #include <netinet/in.h>
14 #include <netinet/tcp.h>
22 #include "appconfig.h"
24 #include "web_buffer.h"
25 #include "web_server.h"
26 #include "global_statistics.h"
30 #include "web_client.h"
31 #include "../config.h"
33 #define INITIAL_WEB_DATA_LENGTH 16384
34 #define WEB_REQUEST_LENGTH 16384
35 #define TOO_BIG_REQUEST 16384
37 int web_client_timeout = DEFAULT_DISCONNECT_IDLE_WEB_CLIENTS_AFTER_SECONDS;
38 int web_enable_gzip = 1;
40 extern int netdata_exit;
42 struct web_client *web_clients = NULL;
43 unsigned long long web_clients_count = 0;
45 struct web_client *web_client_create(int listener)
49 w = calloc(1, sizeof(struct web_client));
51 error("Cannot allocate new web_client memory.");
55 w->id = ++web_clients_count;
56 w->mode = WEB_CLIENT_MODE_NORMAL;
59 struct sockaddr *sadr;
62 sadr = (struct sockaddr*) &w->clientaddr;
63 addrlen = sizeof(w->clientaddr);
65 w->ifd = accept(listener, sadr, &addrlen);
67 error("%llu: Cannot accept new incoming connection.", w->id);
73 if(getnameinfo(sadr, addrlen, w->client_ip, NI_MAXHOST, w->client_port, NI_MAXSERV, NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
74 error("Cannot getnameinfo() on received client connection.");
75 strncpy(w->client_ip, "UNKNOWN", NI_MAXHOST);
76 strncpy(w->client_port, "UNKNOWN", NI_MAXSERV);
78 w->client_ip[NI_MAXHOST] = '\0';
79 w->client_port[NI_MAXSERV] = '\0';
81 switch(sadr->sa_family) {
84 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);
88 if(strncmp(w->client_ip, "::ffff:", 7) == 0) {
89 strcpy(w->client_ip, &w->client_ip[7]);
90 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);
92 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);
96 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);
101 if(setsockopt(w->ifd, SOL_SOCKET, SO_KEEPALIVE, (char *) &flag, sizeof(int)) != 0) error("%llu: Cannot set SO_KEEPALIVE on socket.", w->id);
104 w->response.data = buffer_create(INITIAL_WEB_DATA_LENGTH);
105 if(unlikely(!w->response.data)) {
106 // no need for error log - web_buffer_create already logged the error
112 w->response.header = buffer_create(HTTP_RESPONSE_HEADER_SIZE);
113 if(unlikely(!w->response.header)) {
114 // no need for error log - web_buffer_create already logged the error
115 buffer_free(w->response.data);
121 w->response.header_output = buffer_create(HTTP_RESPONSE_HEADER_SIZE);
122 if(unlikely(!w->response.header_output)) {
123 // no need for error log - web_buffer_create already logged the error
124 buffer_free(w->response.header);
125 buffer_free(w->response.data);
133 if(web_clients) web_clients->prev = w;
134 w->next = web_clients;
137 global_statistics.connected_clients++;
142 void web_client_reset(struct web_client *w)
145 gettimeofday(&tv, NULL);
147 long sent = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->response.rlen:w->response.data->len;
149 #ifdef NETDATA_WITH_ZLIB
150 if(likely(w->response.zoutput)) sent = (long)w->response.zstream.total_out;
153 long size = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->response.rlen:w->response.data->len;
155 if(likely(w->last_url[0]))
156 log_access("%llu: (sent/all = %ld/%ld bytes %0.0f%%, prep/sent/total = %0.2f/%0.2f/%0.2f ms) %s: %d '%s'",
158 sent, size, -((size>0)?((float)(size-sent)/(float)size * 100.0):0.0),
159 (float)usecdiff(&w->tv_ready, &w->tv_in) / 1000.0,
160 (float)usecdiff(&tv, &w->tv_ready) / 1000.0,
161 (float)usecdiff(&tv, &w->tv_in) / 1000.0,
162 (w->mode == WEB_CLIENT_MODE_FILECOPY)?"filecopy":((w->mode == WEB_CLIENT_MODE_OPTIONS)?"options":"data"),
167 debug(D_WEB_CLIENT, "%llu: Reseting client.", w->id);
169 if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY)) {
170 debug(D_WEB_CLIENT, "%llu: Closing filecopy input file.", w->id);
175 w->last_url[0] = '\0';
177 w->mode = WEB_CLIENT_MODE_NORMAL;
179 buffer_reset(w->response.header_output);
180 buffer_reset(w->response.header);
181 buffer_reset(w->response.data);
182 w->response.rlen = 0;
183 w->response.sent = 0;
184 w->response.code = 0;
189 w->response.zoutput = 0;
191 // if we had enabled compression, release it
192 #ifdef NETDATA_WITH_ZLIB
193 if(w->response.zinitialized) {
194 debug(D_DEFLATE, "%llu: Reseting compression.", w->id);
195 deflateEnd(&w->response.zstream);
196 w->response.zsent = 0;
197 w->response.zhave = 0;
198 w->response.zstream.avail_in = 0;
199 w->response.zstream.avail_out = 0;
200 w->response.zstream.total_in = 0;
201 w->response.zstream.total_out = 0;
202 w->response.zinitialized = 0;
204 #endif // NETDATA_WITH_ZLIB
207 struct web_client *web_client_free(struct web_client *w)
209 struct web_client *n = w->next;
211 debug(D_WEB_CLIENT_ACCESS, "%llu: Closing web client from %s port %s.", w->id, w->client_ip, w->client_port);
213 if(w->prev) w->prev->next = w->next;
214 if(w->next) w->next->prev = w->prev;
216 if(w == web_clients) web_clients = w->next;
218 if(w->response.header_output) buffer_free(w->response.header_output);
219 if(w->response.header) buffer_free(w->response.header);
220 if(w->response.data) buffer_free(w->response.data);
222 if(w->ofd != w->ifd) close(w->ofd);
225 global_statistics.connected_clients--;
230 uid_t web_files_uid(void)
232 static char *web_owner = NULL;
233 static uid_t owner_uid = 0;
235 if(unlikely(!web_owner)) {
236 web_owner = config_get("global", "web files owner", config_get("global", "run as user", ""));
237 if(!web_owner || !*web_owner)
238 owner_uid = geteuid();
240 // getpwnam() is not thread safe,
241 // but we have called this function once
242 // while single threaded
243 struct passwd *pw = getpwnam(web_owner);
245 error("User %s is not present. Ignoring option.", web_owner);
246 owner_uid = geteuid();
249 debug(D_WEB_CLIENT, "Web files owner set to %s.\n", web_owner);
250 owner_uid = pw->pw_uid;
258 gid_t web_files_gid(void)
260 static char *web_group = NULL;
261 static gid_t owner_gid = 0;
263 if(unlikely(!web_group)) {
264 web_group = config_get("global", "web files group", config_get("global", "web files owner", ""));
265 if(!web_group || !*web_group)
266 owner_gid = getegid();
268 // getgrnam() is not thread safe,
269 // but we have called this function once
270 // while single threaded
271 struct group *gr = getgrnam(web_group);
273 error("Group %s is not present. Ignoring option.", web_group);
274 owner_gid = getegid();
277 debug(D_WEB_CLIENT, "Web files group set to %s.\n", web_group);
278 owner_gid = gr->gr_gid;
286 int mysendfile(struct web_client *w, char *filename)
288 static char *web_dir = NULL;
290 // initialize our static data
291 if(unlikely(!web_dir)) web_dir = config_get("global", "web files directory", WEB_DIR);
293 debug(D_WEB_CLIENT, "%llu: Looking for file '%s/%s'", w->id, web_dir, filename);
295 // skip leading slashes
296 while (*filename == '/') filename++;
298 // if the filename contain known paths, skip them
299 if(strncmp(filename, WEB_PATH_FILE "/", strlen(WEB_PATH_FILE) + 1) == 0) filename = &filename[strlen(WEB_PATH_FILE) + 1];
302 for(s = filename; *s ;s++) {
303 if( !isalnum(*s) && *s != '/' && *s != '.' && *s != '-' && *s != '_') {
304 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
305 buffer_sprintf(w->response.data, "File '%s' cannot be served. Filename contains invalid character '%c'", filename, *s);
310 // if the filename contains a .. refuse to serve it
311 if(strstr(filename, "..") != 0) {
312 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
313 buffer_sprintf(w->response.data, "File '%s' cannot be served. Relative filenames with '..' in them are not supported.", filename);
318 char webfilename[FILENAME_MAX + 1];
319 snprintf(webfilename, FILENAME_MAX, "%s/%s", web_dir, filename);
321 // check if the file exists
323 if(lstat(webfilename, &stat) != 0) {
324 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not found.", w->id, webfilename);
325 buffer_sprintf(w->response.data, "File '%s' does not exist, or is not accessible.", webfilename);
329 // check if the file is owned by expected user
330 if(stat.st_uid != web_files_uid()) {
331 error("%llu: File '%s' is owned by user %d (expected user %d). Access Denied.", w->id, webfilename, stat.st_uid, web_files_uid());
332 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", webfilename);
336 // check if the file is owned by expected group
337 if(stat.st_gid != web_files_gid()) {
338 error("%llu: File '%s' is owned by group %d (expected group %d). Access Denied.", w->id, webfilename, stat.st_gid, web_files_gid());
339 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", webfilename);
343 if((stat.st_mode & S_IFMT) == S_IFDIR) {
344 snprintf(webfilename, FILENAME_MAX+1, "%s/index.html", filename);
345 return mysendfile(w, webfilename);
348 if((stat.st_mode & S_IFMT) != S_IFREG) {
349 error("%llu: File '%s' is not a regular file. Access Denied.", w->id, webfilename);
350 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", webfilename);
355 w->ifd = open(webfilename, O_NONBLOCK, O_RDONLY);
359 if(errno == EBUSY || errno == EAGAIN) {
360 error("%llu: File '%s' is busy, sending 307 Moved Temporarily to force retry.", w->id, webfilename);
361 buffer_sprintf(w->response.header, "Location: /" WEB_PATH_FILE "/%s\r\n", filename);
362 buffer_sprintf(w->response.data, "The file '%s' is currently busy. Please try again later.", webfilename);
366 error("%llu: Cannot open file '%s'.", w->id, webfilename);
367 buffer_sprintf(w->response.data, "Cannot open file '%s'.", webfilename);
372 // pick a Content-Type for the file
373 if(strstr(filename, ".html") != NULL) w->response.data->contenttype = CT_TEXT_HTML;
374 else if(strstr(filename, ".js") != NULL) w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
375 else if(strstr(filename, ".css") != NULL) w->response.data->contenttype = CT_TEXT_CSS;
376 else if(strstr(filename, ".xml") != NULL) w->response.data->contenttype = CT_TEXT_XML;
377 else if(strstr(filename, ".xsl") != NULL) w->response.data->contenttype = CT_TEXT_XSL;
378 else if(strstr(filename, ".txt") != NULL) w->response.data->contenttype = CT_TEXT_PLAIN;
379 else if(strstr(filename, ".svg") != NULL) w->response.data->contenttype = CT_IMAGE_SVG_XML;
380 else if(strstr(filename, ".ttf") != NULL) w->response.data->contenttype = CT_APPLICATION_X_FONT_TRUETYPE;
381 else if(strstr(filename, ".otf") != NULL) w->response.data->contenttype = CT_APPLICATION_X_FONT_OPENTYPE;
382 else if(strstr(filename, ".woff2")!= NULL) w->response.data->contenttype = CT_APPLICATION_FONT_WOFF2;
383 else if(strstr(filename, ".woff") != NULL) w->response.data->contenttype = CT_APPLICATION_FONT_WOFF;
384 else if(strstr(filename, ".eot") != NULL) w->response.data->contenttype = CT_APPLICATION_VND_MS_FONTOBJ;
385 else if(strstr(filename, ".png") != NULL) w->response.data->contenttype = CT_IMAGE_PNG;
386 else if(strstr(filename, ".jpg") != NULL) w->response.data->contenttype = CT_IMAGE_JPG;
387 else if(strstr(filename, ".jpeg") != NULL) w->response.data->contenttype = CT_IMAGE_JPG;
388 else if(strstr(filename, ".gif") != NULL) w->response.data->contenttype = CT_IMAGE_GIF;
389 else if(strstr(filename, ".bmp") != NULL) w->response.data->contenttype = CT_IMAGE_BMP;
390 else if(strstr(filename, ".ico") != NULL) w->response.data->contenttype = CT_IMAGE_XICON;
391 else if(strstr(filename, ".icns") != NULL) w->response.data->contenttype = CT_IMAGE_ICNS;
392 else w->response.data->contenttype = CT_APPLICATION_OCTET_STREAM;
394 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);
396 w->mode = WEB_CLIENT_MODE_FILECOPY;
399 buffer_flush(w->response.data);
400 w->response.rlen = stat.st_size;
401 w->response.data->date = stat.st_mtim.tv_sec;
407 #ifdef NETDATA_WITH_ZLIB
408 void web_client_enable_deflate(struct web_client *w) {
409 if(w->response.zinitialized == 1) {
410 error("%llu: Compression has already be initialized for this client.", w->id);
414 if(w->response.sent) {
415 error("%llu: Cannot enable compression in the middle of a conversation.", w->id);
419 w->response.zstream.zalloc = Z_NULL;
420 w->response.zstream.zfree = Z_NULL;
421 w->response.zstream.opaque = Z_NULL;
423 w->response.zstream.next_in = (Bytef *)w->response.data->buffer;
424 w->response.zstream.avail_in = 0;
425 w->response.zstream.total_in = 0;
427 w->response.zstream.next_out = w->response.zbuffer;
428 w->response.zstream.avail_out = 0;
429 w->response.zstream.total_out = 0;
431 w->response.zstream.zalloc = Z_NULL;
432 w->response.zstream.zfree = Z_NULL;
433 w->response.zstream.opaque = Z_NULL;
435 // if(deflateInit(&w->response.zstream, Z_DEFAULT_COMPRESSION) != Z_OK) {
436 // error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
440 // Select GZIP compression: windowbits = 15 + 16 = 31
441 if(deflateInit2(&w->response.zstream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY) != Z_OK) {
442 error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
446 w->response.zsent = 0;
447 w->response.zoutput = 1;
448 w->response.zinitialized = 1;
450 debug(D_DEFLATE, "%llu: Initialized compression.", w->id);
452 #endif // NETDATA_WITH_ZLIB
454 uint32_t web_client_api_request_v1_data_options(char *o)
456 uint32_t ret = 0x00000000;
459 while(o && *o && (tok = mystrsep(&o, ", |"))) {
462 if(!strcmp(tok, "nonzero"))
463 ret |= RRDR_OPTION_NONZERO;
464 else if(!strcmp(tok, "flip") || !strcmp(tok, "reversed") || !strcmp(tok, "reverse"))
465 ret |= RRDR_OPTION_REVERSED;
466 else if(!strcmp(tok, "jsonwrap"))
467 ret |= RRDR_OPTION_JSON_WRAP;
468 else if(!strcmp(tok, "min2max"))
469 ret |= RRDR_OPTION_MIN2MAX;
470 else if(!strcmp(tok, "ms") || !strcmp(tok, "milliseconds"))
471 ret |= RRDR_OPTION_MILLISECONDS;
472 else if(!strcmp(tok, "abs") || !strcmp(tok, "absolute") || !strcmp(tok, "absolute_sum") || !strcmp(tok, "absolute-sum"))
473 ret |= RRDR_OPTION_ABSOLUTE;
474 else if(!strcmp(tok, "seconds"))
475 ret |= RRDR_OPTION_SECONDS;
476 else if(!strcmp(tok, "null2zero"))
477 ret |= RRDR_OPTION_NULL2ZERO;
478 else if(!strcmp(tok, "objectrows"))
479 ret |= RRDR_OPTION_OBJECTSROWS;
480 else if(!strcmp(tok, "google_json"))
481 ret |= RRDR_OPTION_GOOGLE_JSON;
482 else if(!strcmp(tok, "percentage"))
483 ret |= RRDR_OPTION_PERCENTAGE;
489 uint32_t web_client_api_request_v1_data_format(char *name)
491 if(!strcmp(name, DATASOURCE_FORMAT_DATATABLE_JSON)) // datatable
492 return DATASOURCE_DATATABLE_JSON;
494 else if(!strcmp(name, DATASOURCE_FORMAT_DATATABLE_JSONP)) // datasource
495 return DATASOURCE_DATATABLE_JSONP;
497 else if(!strcmp(name, DATASOURCE_FORMAT_JSON)) // json
498 return DATASOURCE_JSON;
500 else if(!strcmp(name, DATASOURCE_FORMAT_JSONP)) // jsonp
501 return DATASOURCE_JSONP;
503 else if(!strcmp(name, DATASOURCE_FORMAT_SSV)) // ssv
504 return DATASOURCE_SSV;
506 else if(!strcmp(name, DATASOURCE_FORMAT_CSV)) // csv
507 return DATASOURCE_CSV;
509 else if(!strcmp(name, DATASOURCE_FORMAT_TSV) || !strcmp(name, "tsv-excel")) // tsv
510 return DATASOURCE_TSV;
512 else if(!strcmp(name, DATASOURCE_FORMAT_HTML)) // html
513 return DATASOURCE_HTML;
515 else if(!strcmp(name, DATASOURCE_FORMAT_JS_ARRAY)) // array
516 return DATASOURCE_JS_ARRAY;
518 else if(!strcmp(name, DATASOURCE_FORMAT_SSV_COMMA)) // ssvcomma
519 return DATASOURCE_SSV_COMMA;
521 else if(!strcmp(name, DATASOURCE_FORMAT_CSV_JSON_ARRAY)) // csvjsonarray
522 return DATASOURCE_CSV_JSON_ARRAY;
524 return DATASOURCE_JSON;
527 uint32_t web_client_api_request_v1_data_google_format(char *name)
529 if(!strcmp(name, "json"))
530 return DATASOURCE_DATATABLE_JSONP;
532 else if(!strcmp(name, "html"))
533 return DATASOURCE_HTML;
535 else if(!strcmp(name, "csv"))
536 return DATASOURCE_CSV;
538 else if(!strcmp(name, "tsv-excel"))
539 return DATASOURCE_TSV;
541 return DATASOURCE_JSON;
544 int web_client_api_request_v1_data_group(char *name)
546 if(!strcmp(name, "max"))
549 else if(!strcmp(name, "average"))
550 return GROUP_AVERAGE;
555 int web_client_api_request_v1_charts(struct web_client *w, char *url)
559 buffer_flush(w->response.data);
560 w->response.data->contenttype = CT_APPLICATION_JSON;
561 rrd_stats_api_v1_charts(w->response.data);
565 int web_client_api_request_v1_chart(struct web_client *w, char *url)
570 buffer_flush(w->response.data);
573 char *value = mystrsep(&url, "?&[]");
574 if(!value || !*value) continue;
576 char *name = mystrsep(&value, "=");
577 if(!name || !*name) continue;
578 if(!value || !*value) continue;
580 // name and value are now the parameters
581 // they are not null and not empty
583 if(!strcmp(name, "chart")) chart = value;
585 /// buffer_sprintf(w->response.data, "Unknown parameter '%s' in request.", name);
590 if(!chart || !*chart) {
591 buffer_sprintf(w->response.data, "No chart id is given at the request.");
595 RRDSET *st = rrdset_find(chart);
596 if(!st) st = rrdset_find_byname(chart);
598 buffer_sprintf(w->response.data, "Chart '%s' is not found.", chart);
603 w->response.data->contenttype = CT_APPLICATION_JSON;
604 rrd_stats_api_v1_chart(st, w->response.data);
611 // returns the HTTP code
612 int web_client_api_request_v1_data(struct web_client *w, char *url)
614 debug(D_WEB_CLIENT, "%llu: API v1 data with URL '%s'", w->id, url);
617 BUFFER *dimensions = NULL;
619 buffer_flush(w->response.data);
621 char *google_version = "0.6",
624 *google_out = "json",
625 *responseHandler = NULL,
628 time_t last_timestamp_in_data = 0, google_timestamp = 0;
633 , *points_str = NULL;
635 int group = GROUP_MAX;
636 uint32_t format = DATASOURCE_JSON;
637 uint32_t options = 0x00000000;
640 char *value = mystrsep(&url, "?&[]");
641 if(!value || !*value) continue;
643 char *name = mystrsep(&value, "=");
644 if(!name || !*name) continue;
645 if(!value || !*value) continue;
647 debug(D_WEB_CLIENT, "%llu: API v1 query param '%s' with value '%s'", w->id, name, value);
649 // name and value are now the parameters
650 // they are not null and not empty
652 if(!strcmp(name, "chart")) chart = value;
653 else if(!strcmp(name, "dimension") || !strcmp(name, "dim") || !strcmp(name, "dimensions") || !strcmp(name, "dims")) {
654 if(!dimensions) dimensions = buffer_create(strlen(value));
656 buffer_strcat(dimensions, "|");
657 buffer_strcat(dimensions, value);
660 else if(!strcmp(name, "after")) after_str = value;
661 else if(!strcmp(name, "before")) before_str = value;
662 else if(!strcmp(name, "points")) points_str = value;
663 else if(!strcmp(name, "group")) {
664 group = web_client_api_request_v1_data_group(value);
666 else if(!strcmp(name, "format")) {
667 format = web_client_api_request_v1_data_format(value);
669 else if(!strcmp(name, "options")) {
670 options |= web_client_api_request_v1_data_options(value);
672 else if(!strcmp(name, "callback")) {
673 responseHandler = value;
675 else if(!strcmp(name, "filename")) {
678 else if(!strcmp(name, "tqx")) {
679 // parse Google Visualization API options
680 // https://developers.google.com/chart/interactive/docs/dev/implementing_data_source
681 char *tqx_name, *tqx_value;
684 tqx_value = mystrsep(&value, ";");
685 if(!tqx_value || !*tqx_value) continue;
687 tqx_name = mystrsep(&tqx_value, ":");
688 if(!tqx_name || !*tqx_name) continue;
689 if(!tqx_value || !*tqx_value) continue;
691 if(!strcmp(tqx_name, "version"))
692 google_version = tqx_value;
693 else if(!strcmp(tqx_name, "reqId"))
694 google_reqId = tqx_value;
695 else if(!strcmp(tqx_name, "sig")) {
696 google_sig = tqx_value;
697 google_timestamp = strtoul(google_sig, NULL, 0);
699 else if(!strcmp(tqx_name, "out")) {
700 google_out = tqx_value;
701 format = web_client_api_request_v1_data_google_format(google_out);
703 else if(!strcmp(tqx_name, "responseHandler"))
704 responseHandler = tqx_value;
705 else if(!strcmp(tqx_name, "outFileName"))
706 outFileName = tqx_value;
711 if(!chart || !*chart) {
712 buffer_sprintf(w->response.data, "No chart id is given at the request.");
716 RRDSET *st = rrdset_find(chart);
717 if(!st) st = rrdset_find_byname(chart);
719 buffer_sprintf(w->response.data, "Chart '%s' is not found.", chart);
724 long long before = (before_str && *before_str)?atol(before_str):0;
725 long long after = (after_str && *after_str) ?atol(after_str):0;
726 int points = (points_str && *points_str)?atoi(points_str):0;
728 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'"
731 , (dimensions)?buffer_tostring(dimensions):""
740 if(outFileName && *outFileName) {
741 buffer_sprintf(w->response.header, "Content-Disposition: attachment; filename=\"%s\"\r\n", outFileName);
742 error("generating outfilename header: '%s'", outFileName);
745 if(format == DATASOURCE_DATATABLE_JSONP) {
746 if(responseHandler == NULL)
747 responseHandler = "google.visualization.Query.setResponse";
749 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSON/JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
750 w->id, google_version, google_reqId, google_sig, google_out, responseHandler, outFileName
753 buffer_sprintf(w->response.data,
754 "%s({version:'%s',reqId:'%s',status:'ok',sig:'%lu',table:",
755 responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
757 else if(format == DATASOURCE_JSONP) {
758 if(responseHandler == NULL)
759 responseHandler = "callback";
761 buffer_strcat(w->response.data, responseHandler);
762 buffer_strcat(w->response.data, "(");
765 ret = rrd2format(st, w->response.data, dimensions, format, points, after, before, group, options, &last_timestamp_in_data);
767 if(format == DATASOURCE_DATATABLE_JSONP) {
768 if(google_timestamp < last_timestamp_in_data)
769 buffer_strcat(w->response.data, "});");
772 // the client already has the latest data
773 buffer_flush(w->response.data);
774 buffer_sprintf(w->response.data,
775 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
776 responseHandler, google_version, google_reqId);
779 else if(format == DATASOURCE_JSONP)
780 buffer_strcat(w->response.data, ");");
783 if(dimensions) buffer_free(dimensions);
787 int web_client_api_request_v1(struct web_client *w, char *url)
790 char *tok = mystrsep(&url, "/?&");
792 debug(D_WEB_CLIENT, "%llu: Searching for API v1 command '%s'.", w->id, tok);
794 if(strcmp(tok, "data") == 0)
795 return web_client_api_request_v1_data(w, url);
796 else if(strcmp(tok, "chart") == 0)
797 return web_client_api_request_v1_chart(w, url);
798 else if(strcmp(tok, "charts") == 0)
799 return web_client_api_request_v1_charts(w, url);
801 buffer_flush(w->response.data);
802 buffer_sprintf(w->response.data, "Unsupported v1 API command: %s", tok);
807 buffer_flush(w->response.data);
808 buffer_sprintf(w->response.data, "API v1 command?");
813 int web_client_api_request(struct web_client *w, char *url)
815 // get the api version
816 char *tok = mystrsep(&url, "/?&");
818 debug(D_WEB_CLIENT, "%llu: Searching for API version '%s'.", w->id, tok);
819 if(strcmp(tok, "v1") == 0)
820 return web_client_api_request_v1(w, url);
822 buffer_flush(w->response.data);
823 buffer_sprintf(w->response.data, "Unsupported API version: %s", tok);
828 buffer_flush(w->response.data);
829 buffer_sprintf(w->response.data, "Which API version?");
834 int web_client_data_request(struct web_client *w, char *url, int datasource_type)
838 char *args = strchr(url, '?');
844 // get the name of the data to show
845 char *tok = mystrsep(&url, "/");
847 // do we have such a data set?
849 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
850 st = rrdset_find_byname(tok);
851 if(!st) st = rrdset_find(tok);
856 // try to send a file with that name
857 buffer_flush(w->response.data);
858 return(mysendfile(w, tok));
862 debug(D_WEB_CLIENT, "%llu: Found RRD data with name '%s'.", w->id, tok);
864 // how many entries does the client want?
865 long lines = rrd_default_history_entries;
866 long group_count = 1;
867 time_t after = 0, before = 0;
868 int group_method = GROUP_AVERAGE;
872 // parse the lines required
873 tok = mystrsep(&url, "/");
874 if(tok) lines = atoi(tok);
875 if(lines < 1) lines = 1;
878 // parse the group count required
879 tok = mystrsep(&url, "/");
880 if(tok && *tok) group_count = atoi(tok);
881 if(group_count < 1) group_count = 1;
882 //if(group_count > save_history / 20) group_count = save_history / 20;
885 // parse the grouping method required
886 tok = mystrsep(&url, "/");
888 if(strcmp(tok, "max") == 0) group_method = GROUP_MAX;
889 else if(strcmp(tok, "average") == 0) group_method = GROUP_AVERAGE;
890 else if(strcmp(tok, "sum") == 0) group_method = GROUP_SUM;
891 else debug(D_WEB_CLIENT, "%llu: Unknown group method '%s'", w->id, tok);
896 tok = mystrsep(&url, "/");
897 if(tok && *tok) after = strtoul(tok, NULL, 10);
898 if(after < 0) after = 0;
902 tok = mystrsep(&url, "/");
903 if(tok && *tok) before = strtoul(tok, NULL, 10);
904 if(before < 0) before = 0;
908 tok = mystrsep(&url, "/");
909 if(tok && *tok && strcmp(tok, "nonzero") == 0) nonzero = 1;
912 w->response.data->contenttype = CT_APPLICATION_JSON;
913 buffer_flush(w->response.data);
915 char *google_version = "0.6";
916 char *google_reqId = "0";
917 char *google_sig = "0";
918 char *google_out = "json";
919 char *google_responseHandler = "google.visualization.Query.setResponse";
920 char *google_outFileName = NULL;
921 time_t last_timestamp_in_data = 0;
922 if(datasource_type == DATASOURCE_DATATABLE_JSON || datasource_type == DATASOURCE_DATATABLE_JSONP) {
924 w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
927 tok = mystrsep(&args, "&");
929 char *name = mystrsep(&tok, "=");
930 if(name && *name && strcmp(name, "tqx") == 0) {
931 char *key = mystrsep(&tok, ":");
932 char *value = mystrsep(&tok, ";");
933 if(key && value && *key && *value) {
934 if(strcmp(key, "version") == 0)
935 google_version = value;
937 else if(strcmp(key, "reqId") == 0)
938 google_reqId = value;
940 else if(strcmp(key, "sig") == 0)
943 else if(strcmp(key, "out") == 0)
946 else if(strcmp(key, "responseHandler") == 0)
947 google_responseHandler = value;
949 else if(strcmp(key, "outFileName") == 0)
950 google_outFileName = value;
956 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
957 w->id, google_version, google_reqId, google_sig, google_out, google_responseHandler, google_outFileName
960 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
961 last_timestamp_in_data = strtoul(google_sig, NULL, 0);
963 // check the client wants json
964 if(strcmp(google_out, "json") != 0) {
965 buffer_sprintf(w->response.data,
966 "%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.'}]});",
967 google_responseHandler, google_version, google_reqId, google_out);
973 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
974 buffer_sprintf(w->response.data,
975 "%s({version:'%s',reqId:'%s',status:'ok',sig:'%lu',table:",
976 google_responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
979 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);
980 time_t timestamp_in_data = rrd_stats_json(datasource_type, st, w->response.data, lines, group_count, group_method, after, before, nonzero);
982 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
983 if(timestamp_in_data > last_timestamp_in_data)
984 buffer_strcat(w->response.data, "});");
987 // the client already has the latest data
988 buffer_flush(w->response.data);
989 buffer_sprintf(w->response.data,
990 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
991 google_responseHandler, google_version, google_reqId);
999 int web_client_parse_request(struct web_client *w) {
1003 // query string name-value
1006 // http request headers name-value
1008 web_client_clean_request(w);
1010 debug(D_WEB_DATA, "%llu: Processing data buffer of %d bytes: '%s'.", w->id, w->response.data->bytes, w->response.data->buffer);
1012 char *buf = w->response.data->buffer;
1015 // ------------------------------------------------------------------------
1018 if(buf && (line = strsep(&buf, "\r\n"))) {
1020 if(line && (tok = strsep(&line, " "))) {
1021 w->request.protocol = strdup(tok);
1029 // ------------------------------------------------------------------------
1030 // the rest of the lines
1032 while(buf && (line = strsep(&buf, "\r\n"))) {
1033 while(line && (tok = strsep(&line, ": "))) {
1041 web_client_clean_request(w);
1046 void web_client_process(struct web_client *w) {
1049 int enable_gzip = 0;
1051 w->wait_receive = 0;
1053 // check if we have an empty line (end of HTTP header)
1054 if(strstr(w->response.data->buffer, "\r\n\r\n")) {
1055 global_statistics_lock();
1056 global_statistics.web_requests++;
1057 global_statistics_unlock();
1059 gettimeofday(&w->tv_in, NULL);
1060 debug(D_WEB_DATA, "%llu: Processing data buffer of %d bytes: '%s'.", w->id, w->response.data->len, w->response.data->buffer);
1062 // check if the client requested keep-alive HTTP
1063 if(strcasestr(w->response.data->buffer, "Connection: keep-alive")) w->keepalive = 1;
1064 else w->keepalive = 0;
1066 #ifdef NETDATA_WITH_ZLIB
1067 // check if the client accepts deflate
1068 if(web_enable_gzip && strstr(w->response.data->buffer, "gzip"))
1070 #endif // NETDATA_WITH_ZLIB
1072 int datasource_type = DATASOURCE_DATATABLE_JSONP;
1073 //if(strstr(w->response.data->buffer, "X-DataSource-Auth"))
1074 // datasource_type = DATASOURCE_GOOGLE_JSON;
1076 char *buf = (char *)buffer_tostring(w->response.data);
1077 char *tok = strsep(&buf, " \r\n");
1079 char *pointer_to_free = NULL; // keep url_decode() allocated buffer
1081 w->mode = WEB_CLIENT_MODE_NORMAL;
1083 if(buf && strcmp(tok, "GET") == 0) {
1084 tok = strsep(&buf, " \r\n");
1085 pointer_to_free = url = url_decode(tok);
1086 debug(D_WEB_CLIENT, "%llu: Processing HTTP GET on url '%s'.", w->id, url);
1088 else if(buf && strcmp(tok, "OPTIONS") == 0) {
1089 tok = strsep(&buf, " \r\n");
1090 pointer_to_free = url = url_decode(tok);
1091 debug(D_WEB_CLIENT, "%llu: Processing HTTP OPTIONS on url '%s'.", w->id, url);
1092 w->mode = WEB_CLIENT_MODE_OPTIONS;
1094 else if (buf && strcmp(tok, "POST") == 0) {
1096 tok = strsep(&buf, " \r\n");
1097 pointer_to_free = url = url_decode(tok);
1098 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);
1101 w->last_url[0] = '\0';
1103 if(w->mode == WEB_CLIENT_MODE_OPTIONS) {
1104 strncpy(w->last_url, url, URL_MAX);
1105 w->last_url[URL_MAX] = '\0';
1108 w->response.data->contenttype = CT_TEXT_PLAIN;
1109 buffer_flush(w->response.data);
1110 buffer_strcat(w->response.data, "OK");
1113 #ifdef NETDATA_WITH_ZLIB
1115 web_client_enable_deflate(w);
1118 strncpy(w->last_url, url, URL_MAX);
1119 w->last_url[URL_MAX] = '\0';
1121 tok = mystrsep(&url, "/?");
1123 debug(D_WEB_CLIENT, "%llu: Processing command '%s'.", w->id, tok);
1125 if(strcmp(tok, "api") == 0) {
1126 // the client is requesting api access
1127 datasource_type = DATASOURCE_JSON;
1128 code = web_client_api_request(w, url);
1130 #ifdef NETDATA_INTERNAL_CHECKS
1131 else if(strcmp(tok, "exit") == 0) {
1134 w->response.data->contenttype = CT_TEXT_PLAIN;
1135 buffer_flush(w->response.data);
1136 buffer_strcat(w->response.data, "will do");
1139 else if(strcmp(tok, WEB_PATH_DATA) == 0) { // "data"
1140 // the client is requesting rrd data
1141 datasource_type = DATASOURCE_JSON;
1142 code = web_client_data_request(w, url, datasource_type);
1144 else if(strcmp(tok, WEB_PATH_DATASOURCE) == 0) { // "datasource"
1145 // the client is requesting google datasource
1146 code = web_client_data_request(w, url, datasource_type);
1148 else if(strcmp(tok, WEB_PATH_GRAPH) == 0) { // "graph"
1149 // the client is requesting an rrd graph
1151 // get the name of the data to show
1152 tok = mystrsep(&url, "/?&");
1154 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1156 // do we have such a data set?
1157 RRDSET *st = rrdset_find_byname(tok);
1158 if(!st) st = rrdset_find(tok);
1161 // try to send a file with that name
1162 buffer_flush(w->response.data);
1163 code = mysendfile(w, tok);
1167 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending %s.json of RRD_STATS...", w->id, st->name);
1168 w->response.data->contenttype = CT_APPLICATION_JSON;
1169 buffer_flush(w->response.data);
1170 rrd_stats_graph_json(st, url, w->response.data);
1175 buffer_flush(w->response.data);
1176 buffer_strcat(w->response.data, "Graph name?\r\n");
1179 #ifdef NETDATA_INTERNAL_CHECKS
1180 else if(strcmp(tok, "debug") == 0) {
1181 buffer_flush(w->response.data);
1183 // get the name of the data to show
1184 tok = mystrsep(&url, "/?&");
1186 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1188 // do we have such a data set?
1189 RRDSET *st = rrdset_find_byname(tok);
1190 if(!st) st = rrdset_find(tok);
1193 buffer_sprintf(w->response.data, "Chart %s is not found.\r\n", tok);
1194 debug(D_WEB_CLIENT_ACCESS, "%llu: %s is not found.", w->id, tok);
1198 debug_flags |= D_RRD_STATS;
1199 st->debug = !st->debug;
1200 buffer_sprintf(w->response.data, "Chart %s has now debug %s.\r\n", tok, st->debug?"enabled":"disabled");
1201 debug(D_WEB_CLIENT_ACCESS, "%llu: debug for %s is %s.", w->id, tok, st->debug?"enabled":"disabled");
1206 buffer_flush(w->response.data);
1207 buffer_strcat(w->response.data, "debug which chart?\r\n");
1210 else if(strcmp(tok, "mirror") == 0) {
1213 debug(D_WEB_CLIENT_ACCESS, "%llu: Mirroring...", w->id);
1215 // replace the zero bytes with spaces
1216 buffer_char_replace(w->response.data, '\0', ' ');
1218 // just leave the buffer as is
1219 // it will be copied back to the client
1222 else if(strcmp(tok, "list") == 0) {
1225 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending list of RRD_STATS...", w->id);
1227 buffer_flush(w->response.data);
1228 RRDSET *st = rrdset_root;
1230 for ( ; st ; st = st->next )
1231 buffer_sprintf(w->response.data, "%s\n", st->name);
1233 else if(strcmp(tok, "all.json") == 0) {
1235 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending JSON list of all monitors of RRD_STATS...", w->id);
1237 w->response.data->contenttype = CT_APPLICATION_JSON;
1238 buffer_flush(w->response.data);
1239 rrd_stats_all_json(w->response.data);
1241 else if(strcmp(tok, "netdata.conf") == 0) {
1243 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending netdata.conf ...", w->id);
1245 w->response.data->contenttype = CT_TEXT_PLAIN;
1246 buffer_flush(w->response.data);
1247 generate_config(w->response.data, 0);
1250 char filename[FILENAME_MAX+1];
1252 strncpy(filename, w->last_url, FILENAME_MAX);
1253 filename[FILENAME_MAX] = '\0';
1254 tok = mystrsep(&url, "?");
1255 buffer_flush(w->response.data);
1256 code = mysendfile(w, (tok && *tok)?tok:"/");
1260 char filename[FILENAME_MAX+1];
1262 strncpy(filename, w->last_url, FILENAME_MAX);
1263 filename[FILENAME_MAX] = '\0';
1264 tok = mystrsep(&url, "?");
1265 buffer_flush(w->response.data);
1266 code = mysendfile(w, (tok && *tok)?tok:"/");
1270 strcpy(w->last_url, "not a valid response");
1272 if(buf) debug(D_WEB_CLIENT_ACCESS, "%llu: Cannot understand '%s'.", w->id, buf);
1275 buffer_flush(w->response.data);
1276 buffer_strcat(w->response.data, "I don't understand you...\r\n");
1279 // free url_decode() buffer
1280 if(pointer_to_free) {
1281 free(pointer_to_free);
1282 pointer_to_free = NULL;
1285 else if(w->response.data->len > TOO_BIG_REQUEST) {
1286 strcpy(w->last_url, "too big request");
1288 debug(D_WEB_CLIENT_ACCESS, "%llu: Received request is too big (%zd bytes).", w->id, w->response.data->len);
1291 buffer_flush(w->response.data);
1292 buffer_sprintf(w->response.data, "Received request is too big (%zd bytes).\r\n", w->response.data->len);
1295 // wait for more data
1296 w->wait_receive = 1;
1300 gettimeofday(&w->tv_ready, NULL);
1301 w->response.data->date = time(NULL);
1302 w->response.sent = 0;
1303 w->response.code = code;
1305 // prepare the HTTP response header
1306 debug(D_WEB_CLIENT, "%llu: Generating HTTP header with response %d.", w->id, code);
1308 char *content_type_string;
1309 switch(w->response.data->contenttype) {
1311 content_type_string = "text/html; charset=utf-8";
1314 case CT_APPLICATION_XML:
1315 content_type_string = "application/xml; charset=utf-8";
1318 case CT_APPLICATION_JSON:
1319 content_type_string = "application/json; charset=utf-8";
1322 case CT_APPLICATION_X_JAVASCRIPT:
1323 content_type_string = "application/x-javascript; charset=utf-8";
1327 content_type_string = "text/css; charset=utf-8";
1331 content_type_string = "text/xml; charset=utf-8";
1335 content_type_string = "text/xsl; charset=utf-8";
1338 case CT_APPLICATION_OCTET_STREAM:
1339 content_type_string = "application/octet-stream";
1342 case CT_IMAGE_SVG_XML:
1343 content_type_string = "image/svg+xml";
1346 case CT_APPLICATION_X_FONT_TRUETYPE:
1347 content_type_string = "application/x-font-truetype";
1350 case CT_APPLICATION_X_FONT_OPENTYPE:
1351 content_type_string = "application/x-font-opentype";
1354 case CT_APPLICATION_FONT_WOFF:
1355 content_type_string = "application/font-woff";
1358 case CT_APPLICATION_FONT_WOFF2:
1359 content_type_string = "application/font-woff2";
1362 case CT_APPLICATION_VND_MS_FONTOBJ:
1363 content_type_string = "application/vnd.ms-fontobject";
1367 content_type_string = "image/png";
1371 content_type_string = "image/jpeg";
1375 content_type_string = "image/gif";
1378 case CT_IMAGE_XICON:
1379 content_type_string = "image/x-icon";
1383 content_type_string = "image/bmp";
1387 content_type_string = "image/icns";
1392 content_type_string = "text/plain; charset=utf-8";
1403 code_msg = "Temporary Redirect";
1407 code_msg = "Bad Request";
1411 code_msg = "Forbidden";
1415 code_msg = "Not Found";
1419 code_msg = "Internal Server Error";
1424 struct tm tmbuf, *tm = gmtime_r(&w->response.data->date, &tmbuf);
1425 strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %Z", tm);
1427 buffer_sprintf(w->response.header_output,
1428 "HTTP/1.1 %d %s\r\n"
1429 "Connection: %s\r\n"
1430 "Server: NetData Embedded HTTP Server\r\n"
1431 "Access-Control-Allow-Origin: *\r\n"
1432 "Content-Type: %s\r\n"
1435 , w->keepalive?"keep-alive":"close"
1436 , content_type_string
1440 if(w->mode == WEB_CLIENT_MODE_OPTIONS) {
1441 buffer_strcat(w->response.header_output,
1442 "Access-Control-Allow-Methods: GET, OPTIONS\r\n"
1443 "Access-Control-Allow-Headers: accept, x-requested-with\r\n"
1444 "Access-Control-Max-Age: 1209600\r\n" // 86400 * 14
1448 if(buffer_strlen(w->response.header))
1449 buffer_strcat(w->response.header_output, buffer_tostring(w->response.header));
1451 if(w->mode == WEB_CLIENT_MODE_NORMAL && (w->response.data->options & WB_CONTENT_NO_CACHEABLE)) {
1452 buffer_sprintf(w->response.header_output,
1454 "Cache-Control: no-cache\r\n"
1457 else if(w->mode != WEB_CLIENT_MODE_OPTIONS) {
1459 time_t et = w->response.data->date + (86400 * 14);
1460 struct tm etmbuf, *etm = gmtime_r(&et, &etmbuf);
1461 strftime(edate, sizeof(edate), "%a, %d %b %Y %H:%M:%S %Z", etm);
1463 buffer_sprintf(w->response.header_output,
1465 "Cache-Control: public\r\n"
1469 // if we know the content length, put it
1470 if(!w->response.zoutput && (w->response.data->len || w->response.rlen))
1471 buffer_sprintf(w->response.header_output,
1472 "Content-Length: %ld\r\n"
1473 , w->response.data->len? w->response.data->len: w->response.rlen
1475 else if(!w->response.zoutput)
1476 w->keepalive = 0; // content-length is required for keep-alive
1478 if(w->response.zoutput) {
1479 buffer_strcat(w->response.header_output,
1480 "Content-Encoding: gzip\r\n"
1481 "Transfer-Encoding: chunked\r\n"
1485 buffer_strcat(w->response.header_output, "\r\n");
1487 // disable TCP_NODELAY, to buffer the header
1489 if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0)
1490 error("%llu: failed to disable TCP_NODELAY on socket.", w->id);
1492 // sent the HTTP header
1493 debug(D_WEB_DATA, "%llu: Sending response HTTP header of size %d: '%s'"
1495 , buffer_strlen(w->response.header_output)
1496 , buffer_tostring(w->response.header_output)
1499 bytes = send(w->ofd, buffer_tostring(w->response.header_output), buffer_strlen(w->response.header_output), 0);
1500 if(bytes != (ssize_t) buffer_strlen(w->response.header_output))
1501 error("%llu: HTTP Header failed to be sent (I sent %d bytes but the system sent %d bytes)."
1503 , buffer_strlen(w->response.header_output)
1506 global_statistics_lock();
1507 global_statistics.bytes_sent += bytes;
1508 global_statistics_unlock();
1511 // enable TCP_NODELAY, to send all data immediately at the next send()
1513 if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0) error("%llu: failed to enable TCP_NODELAY on socket.", w->id);
1515 // enable sending immediately if we have data
1516 if(w->response.data->len) w->wait_send = 1;
1517 else w->wait_send = 0;
1521 case WEB_CLIENT_MODE_OPTIONS:
1522 debug(D_WEB_CLIENT, "%llu: Done preparing the OPTIONS response. Sending data (%d bytes) to client.", w->id, w->response.data->len);
1525 case WEB_CLIENT_MODE_NORMAL:
1526 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Sending data (%d bytes) to client.", w->id, w->response.data->len);
1529 case WEB_CLIENT_MODE_FILECOPY:
1530 if(w->response.rlen) {
1531 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending data file of %d bytes to client.", w->id, w->response.rlen);
1532 w->wait_receive = 1;
1535 // utilize the kernel sendfile() for copying the file to the socket.
1536 // this block of code can be commented, without anything missing.
1537 // when it is commented, the program will copy the data using async I/O.
1539 long len = sendfile(w->ofd, w->ifd, NULL, w->response.data->rbytes);
1540 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);
1541 else web_client_reset(w);
1546 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending an unknown amount of bytes to client.", w->id);
1550 fatal("%llu: Unknown client mode %d.", w->id, w->mode);
1555 long web_client_send_chunk_header(struct web_client *w, long len)
1557 debug(D_DEFLATE, "%llu: OPEN CHUNK of %d bytes (hex: %x).", w->id, len, len);
1559 sprintf(buf, "%lX\r\n", len);
1560 ssize_t bytes = send(w->ofd, buf, strlen(buf), MSG_DONTWAIT);
1562 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk header %d bytes.", w->id, bytes);
1563 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk header to the client.", w->id);
1564 else debug(D_DEFLATE, "%llu: Failed to send chunk header to client.", w->id);
1569 long web_client_send_chunk_close(struct web_client *w)
1571 //debug(D_DEFLATE, "%llu: CLOSE CHUNK.", w->id);
1573 ssize_t bytes = send(w->ofd, "\r\n", 2, MSG_DONTWAIT);
1575 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
1576 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
1577 else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client.", w->id);
1582 long web_client_send_chunk_finalize(struct web_client *w)
1584 //debug(D_DEFLATE, "%llu: FINALIZE CHUNK.", w->id);
1586 ssize_t bytes = send(w->ofd, "\r\n0\r\n\r\n", 7, MSG_DONTWAIT);
1588 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
1589 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
1590 else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client.", w->id);
1595 #ifdef NETDATA_WITH_ZLIB
1596 long web_client_send_deflate(struct web_client *w)
1598 long len = 0, t = 0;
1600 // when using compression,
1601 // w->response.sent is the amount of bytes passed through compression
1603 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);
1605 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) {
1606 // there is nothing to send
1608 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1610 // finalize the chunk
1611 if(w->response.sent != 0)
1612 t += web_client_send_chunk_finalize(w);
1614 // there can be two cases for this
1615 // A. we have done everything
1616 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
1618 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->response.rlen && w->response.rlen > w->response.data->len) {
1619 // we have to wait, more data will come
1620 debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1625 if(w->keepalive == 0) {
1626 debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->response.sent);
1632 web_client_reset(w);
1633 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1637 if(w->response.zhave == w->response.zsent) {
1638 // compress more input data
1640 // close the previous open chunk
1641 if(w->response.sent != 0) t += web_client_send_chunk_close(w);
1643 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);
1645 // give the compressor all the data not passed through the compressor yet
1646 if(w->response.data->len > w->response.sent) {
1647 #ifdef NETDATA_INTERNAL_CHECKS
1648 if((long)w->response.sent - (long)w->response.zstream.avail_in < 0)
1649 error("internal error: avail_in is corrupted.");
1651 w->response.zstream.next_in = (Bytef *)&w->response.data->buffer[w->response.sent - w->response.zstream.avail_in];
1652 w->response.zstream.avail_in += (uInt) (w->response.data->len - w->response.sent);
1655 // reset the compressor output buffer
1656 w->response.zstream.next_out = w->response.zbuffer;
1657 w->response.zstream.avail_out = ZLIB_CHUNK;
1659 // ask for FINISH if we have all the input
1660 int flush = Z_SYNC_FLUSH;
1661 if(w->mode == WEB_CLIENT_MODE_NORMAL
1662 || (w->mode == WEB_CLIENT_MODE_FILECOPY && !w->wait_receive && w->response.data->len == w->response.rlen)) {
1664 debug(D_DEFLATE, "%llu: Requesting Z_FINISH, if possible.", w->id);
1667 debug(D_DEFLATE, "%llu: Requesting Z_SYNC_FLUSH.", w->id);
1671 if(deflate(&w->response.zstream, flush) == Z_STREAM_ERROR) {
1672 error("%llu: Compression failed. Closing down client.", w->id);
1673 web_client_reset(w);
1677 w->response.zhave = ZLIB_CHUNK - w->response.zstream.avail_out;
1678 w->response.zsent = 0;
1680 // keep track of the bytes passed through the compressor
1681 w->response.sent = w->response.data->len;
1683 debug(D_DEFLATE, "%llu: Compression produced %d bytes.", w->id, w->response.zhave);
1686 t += web_client_send_chunk_header(w, w->response.zhave);
1689 debug(D_WEB_CLIENT, "%llu: Sending %d bytes of data (+%d of chunk header).", w->id, w->response.zhave - w->response.zsent, t);
1691 len = send(w->ofd, &w->response.zbuffer[w->response.zsent], (size_t) (w->response.zhave - w->response.zsent), MSG_DONTWAIT);
1693 w->response.zsent += len;
1695 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, len);
1697 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);
1698 else debug(D_WEB_CLIENT, "%llu: Failed to send data to client. Reason: %s", w->id, strerror(errno));
1702 #endif // NETDATA_WITH_ZLIB
1704 long web_client_send(struct web_client *w)
1706 #ifdef NETDATA_WITH_ZLIB
1707 if(likely(w->response.zoutput)) return web_client_send_deflate(w);
1708 #endif // NETDATA_WITH_ZLIB
1712 if(unlikely(w->response.data->len - w->response.sent == 0)) {
1713 // there is nothing to send
1715 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1717 // there can be two cases for this
1718 // A. we have done everything
1719 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
1721 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->response.rlen && w->response.rlen > w->response.data->len) {
1722 // we have to wait, more data will come
1723 debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1728 if(unlikely(w->keepalive == 0)) {
1729 debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->response.sent);
1734 web_client_reset(w);
1735 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1739 bytes = send(w->ofd, &w->response.data->buffer[w->response.sent], w->response.data->len - w->response.sent, MSG_DONTWAIT);
1740 if(likely(bytes > 0)) {
1741 w->response.sent += bytes;
1742 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, bytes);
1744 else if(likely(bytes == 0)) debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client.", w->id);
1745 else debug(D_WEB_CLIENT, "%llu: Failed to send data to client.", w->id);
1750 long web_client_receive(struct web_client *w)
1752 // do we have any space for more data?
1753 buffer_need_bytes(w->response.data, WEB_REQUEST_LENGTH);
1755 long left = w->response.data->size - w->response.data->len;
1758 if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY))
1759 bytes = read(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1));
1761 bytes = recv(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1), MSG_DONTWAIT);
1763 if(likely(bytes > 0)) {
1764 size_t old = w->response.data->len;
1765 w->response.data->len += bytes;
1766 w->response.data->buffer[w->response.data->len] = '\0';
1768 debug(D_WEB_CLIENT, "%llu: Received %d bytes.", w->id, bytes);
1769 debug(D_WEB_DATA, "%llu: Received data: '%s'.", w->id, &w->response.data->buffer[old]);
1771 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1773 if(w->response.rlen && w->response.data->len >= w->response.rlen) w->wait_receive = 0;
1776 else if(likely(bytes == 0)) {
1777 debug(D_WEB_CLIENT, "%llu: Out of input data.", w->id);
1779 // if we cannot read, it means we have an error on input.
1780 // if however, we are copying a file from ifd to ofd, we should not return an error.
1781 // in this case, the error should be generated when the file has been sent to the client.
1783 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1784 // we are copying data from ifd to ofd
1785 // let it finish copying...
1786 w->wait_receive = 0;
1787 debug(D_WEB_CLIENT, "%llu: Disabling input.", w->id);
1799 // --------------------------------------------------------------------------------------
1800 // the thread of a single client
1802 // 1. waits for input and output, using async I/O
1803 // 2. it processes HTTP requests
1804 // 3. it generates HTTP responses
1805 // 4. it copies data from input to output if mode is FILECOPY
1807 void *web_client_main(void *ptr)
1809 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
1810 error("Cannot set pthread cancel type to DEFERRED.");
1812 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
1813 error("Cannot set pthread cancel state to ENABLE.");
1816 struct web_client *w = ptr;
1818 fd_set ifds, ofds, efds;
1821 log_access("%llu: %s port %s connected on thread task id %d", w->id, w->client_ip, w->client_port, gettid());
1828 FD_SET(w->ifd, &efds);
1830 if(w->ifd != w->ofd)
1831 FD_SET(w->ofd, &efds);
1833 if (w->wait_receive) {
1834 FD_SET(w->ifd, &ifds);
1835 if(w->ifd > fdmax) fdmax = w->ifd;
1839 FD_SET(w->ofd, &ofds);
1840 if(w->ofd > fdmax) fdmax = w->ofd;
1843 tv.tv_sec = web_client_timeout;
1846 debug(D_WEB_CLIENT, "%llu: Waiting socket async I/O for %s %s", w->id, w->wait_receive?"INPUT":"", w->wait_send?"OUTPUT":"");
1847 retval = select(fdmax+1, &ifds, &ofds, &efds, &tv);
1850 debug(D_WEB_CLIENT_ACCESS, "%llu: LISTENER: select() failed.", w->id);
1855 debug(D_WEB_CLIENT_ACCESS, "%llu: LISTENER: timeout.", w->id);
1859 if(FD_ISSET(w->ifd, &efds)) {
1860 debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on input socket.", w->id);
1864 if(FD_ISSET(w->ofd, &efds)) {
1865 debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on output socket.", w->id);
1869 if(w->wait_send && FD_ISSET(w->ofd, &ofds)) {
1871 if((bytes = web_client_send(w)) < 0) {
1872 debug(D_WEB_CLIENT, "%llu: Cannot send data to client. Closing client.", w->id);
1877 global_statistics_lock();
1878 global_statistics.bytes_sent += bytes;
1879 global_statistics_unlock();
1882 if(w->wait_receive && FD_ISSET(w->ifd, &ifds)) {
1884 if((bytes = web_client_receive(w)) < 0) {
1885 debug(D_WEB_CLIENT, "%llu: Cannot receive data from client. Closing client.", w->id);
1890 if(w->mode == WEB_CLIENT_MODE_NORMAL) {
1891 debug(D_WEB_CLIENT, "%llu: Attempting to process received data (%ld bytes).", w->id, bytes);
1892 // info("%llu: Attempting to process received data (%ld bytes).", w->id, bytes);
1893 web_client_process(w);
1896 global_statistics_lock();
1897 global_statistics.bytes_received += bytes;
1898 global_statistics_unlock();
1902 log_access("%llu: %s port %s disconnected from thread task id %d", w->id, w->client_ip, w->client_port, gettid());
1903 debug(D_WEB_CLIENT, "%llu: done...", w->id);
1905 web_client_reset(w);