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"
32 #define INITIAL_WEB_DATA_LENGTH 16384
33 #define WEB_REQUEST_LENGTH 16384
34 #define TOO_BIG_REQUEST 16384
36 int web_client_timeout = DEFAULT_DISCONNECT_IDLE_WEB_CLIENTS_AFTER_SECONDS;
37 int web_enable_gzip = 1;
39 extern int netdata_exit;
41 struct web_client *web_clients = NULL;
42 unsigned long long web_clients_count = 0;
44 struct web_client *web_client_create(int listener)
48 w = calloc(1, sizeof(struct web_client));
50 error("Cannot allocate new web_client memory.");
54 w->id = ++web_clients_count;
55 w->mode = WEB_CLIENT_MODE_NORMAL;
58 struct sockaddr *sadr;
61 sadr = (struct sockaddr*) &w->clientaddr;
62 addrlen = sizeof(w->clientaddr);
64 w->ifd = accept(listener, sadr, &addrlen);
66 error("%llu: Cannot accept new incoming connection.", w->id);
72 if(getnameinfo(sadr, addrlen, w->client_ip, NI_MAXHOST, w->client_port, NI_MAXSERV, NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
73 error("Cannot getnameinfo() on received client connection.");
74 strncpy(w->client_ip, "UNKNOWN", NI_MAXHOST);
75 strncpy(w->client_port, "UNKNOWN", NI_MAXSERV);
77 w->client_ip[NI_MAXHOST] = '\0';
78 w->client_port[NI_MAXSERV] = '\0';
80 switch(sadr->sa_family) {
83 debug(D_WEB_CLIENT_ACCESS, "%llu: New IPv4 web client from %s port %s on socket %d.", w->id, w->client_ip, w->client_port, w->ifd);
87 if(strncmp(w->client_ip, "::ffff:", 7) == 0) {
88 strcpy(w->client_ip, &w->client_ip[7]);
89 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);
91 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);
95 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);
100 if(setsockopt(w->ifd, SOL_SOCKET, SO_KEEPALIVE, (char *) &flag, sizeof(int)) != 0) error("%llu: Cannot set SO_KEEPALIVE on socket.", w->id);
103 w->response.data = buffer_create(INITIAL_WEB_DATA_LENGTH);
104 if(unlikely(!w->response.data)) {
105 // no need for error log - web_buffer_create already logged the error
111 w->response.header = buffer_create(HTTP_RESPONSE_HEADER_SIZE);
112 if(unlikely(!w->response.header)) {
113 // no need for error log - web_buffer_create already logged the error
114 buffer_free(w->response.data);
120 w->response.header_output = buffer_create(HTTP_RESPONSE_HEADER_SIZE);
121 if(unlikely(!w->response.header_output)) {
122 // no need for error log - web_buffer_create already logged the error
123 buffer_free(w->response.header);
124 buffer_free(w->response.data);
132 if(web_clients) web_clients->prev = w;
133 w->next = web_clients;
136 global_statistics.connected_clients++;
141 void web_client_reset(struct web_client *w)
144 gettimeofday(&tv, NULL);
146 long sent = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->response.rlen:w->response.data->len;
148 #ifdef NETDATA_WITH_ZLIB
149 if(likely(w->response.zoutput)) sent = (long)w->response.zstream.total_out;
152 long size = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->response.rlen:w->response.data->len;
154 if(likely(w->last_url[0]))
155 log_access("%llu: (sent/all = %ld/%ld bytes %0.0f%%, prep/sent/total = %0.2f/%0.2f/%0.2f ms) %s: %d '%s'",
157 sent, size, -((size>0)?((float)(size-sent)/(float)size * 100.0):0.0),
158 (float)usecdiff(&w->tv_ready, &w->tv_in) / 1000.0,
159 (float)usecdiff(&tv, &w->tv_ready) / 1000.0,
160 (float)usecdiff(&tv, &w->tv_in) / 1000.0,
161 (w->mode == WEB_CLIENT_MODE_FILECOPY)?"filecopy":((w->mode == WEB_CLIENT_MODE_OPTIONS)?"options":"data"),
166 debug(D_WEB_CLIENT, "%llu: Reseting client.", w->id);
168 if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY)) {
169 debug(D_WEB_CLIENT, "%llu: Closing filecopy input file.", w->id);
174 w->last_url[0] = '\0';
176 w->mode = WEB_CLIENT_MODE_NORMAL;
178 buffer_reset(w->response.header_output);
179 buffer_reset(w->response.header);
180 buffer_reset(w->response.data);
181 w->response.rlen = 0;
182 w->response.sent = 0;
183 w->response.code = 0;
188 w->response.zoutput = 0;
190 // if we had enabled compression, release it
191 #ifdef NETDATA_WITH_ZLIB
192 if(w->response.zinitialized) {
193 debug(D_DEFLATE, "%llu: Reseting compression.", w->id);
194 deflateEnd(&w->response.zstream);
195 w->response.zsent = 0;
196 w->response.zhave = 0;
197 w->response.zstream.avail_in = 0;
198 w->response.zstream.avail_out = 0;
199 w->response.zstream.total_in = 0;
200 w->response.zstream.total_out = 0;
201 w->response.zinitialized = 0;
203 #endif // NETDATA_WITH_ZLIB
206 struct web_client *web_client_free(struct web_client *w)
208 struct web_client *n = w->next;
210 debug(D_WEB_CLIENT_ACCESS, "%llu: Closing web client from %s port %s.", w->id, w->client_ip, w->client_port);
212 if(w->prev) w->prev->next = w->next;
213 if(w->next) w->next->prev = w->prev;
215 if(w == web_clients) web_clients = w->next;
217 if(w->response.header_output) buffer_free(w->response.header_output);
218 if(w->response.header) buffer_free(w->response.header);
219 if(w->response.data) buffer_free(w->response.data);
221 if(w->ofd != w->ifd) close(w->ofd);
224 global_statistics.connected_clients--;
229 uid_t web_files_uid(void)
231 static char *web_owner = NULL;
232 static uid_t owner_uid = 0;
234 if(unlikely(!web_owner)) {
235 web_owner = config_get("global", "web files owner", NETDATA_USER);
236 if(!web_owner || !*web_owner)
237 owner_uid = geteuid();
239 struct passwd *pw = getpwnam(web_owner);
241 error("User %s is not present. Ignoring option.", web_owner);
242 owner_uid = geteuid();
245 debug(D_WEB_CLIENT, "Web files owner set to %s.\n", web_owner);
246 owner_uid = pw->pw_uid;
254 gid_t web_files_gid(void)
256 static char *web_group = NULL;
257 static gid_t owner_gid = 0;
259 if(unlikely(!web_group)) {
260 web_group = config_get("global", "web files group", config_get("global", "web files owner", NETDATA_USER));
261 if(!web_group || !*web_group)
262 owner_gid = getegid();
264 struct group *gr = getgrnam(web_group);
266 error("Group %s is not present. Ignoring option.", web_group);
267 owner_gid = getegid();
270 debug(D_WEB_CLIENT, "Web files group set to %s.\n", web_group);
271 owner_gid = gr->gr_gid;
279 int mysendfile(struct web_client *w, char *filename)
281 static char *web_dir = NULL;
283 // initialize our static data
284 if(unlikely(!web_dir)) web_dir = config_get("global", "web files directory", WEB_DIR);
286 debug(D_WEB_CLIENT, "%llu: Looking for file '%s/%s'", w->id, web_dir, filename);
288 // skip leading slashes
289 while (*filename == '/') filename++;
291 // if the filename contain known paths, skip them
292 if(strncmp(filename, WEB_PATH_FILE "/", strlen(WEB_PATH_FILE) + 1) == 0) filename = &filename[strlen(WEB_PATH_FILE) + 1];
295 for(s = filename; *s ;s++) {
296 if( !isalnum(*s) && *s != '/' && *s != '.' && *s != '-' && *s != '_') {
297 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
298 buffer_sprintf(w->response.data, "File '%s' cannot be served. Filename contains invalid character '%c'", filename, *s);
303 // if the filename contains a .. refuse to serve it
304 if(strstr(filename, "..") != 0) {
305 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
306 buffer_sprintf(w->response.data, "File '%s' cannot be served. Relative filenames with '..' in them are not supported.", filename);
311 char webfilename[FILENAME_MAX + 1];
312 snprintf(webfilename, FILENAME_MAX, "%s/%s", web_dir, filename);
314 // check if the file exists
316 if(lstat(webfilename, &stat) != 0) {
317 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not found.", w->id, webfilename);
318 buffer_sprintf(w->response.data, "File '%s' does not exist, or is not accessible.", webfilename);
322 // check if the file is owned by expected user
323 if(stat.st_uid != web_files_uid()) {
324 error("%llu: File '%s' is owned by user %d (expected user %d). Access Denied.", w->id, webfilename, stat.st_uid, web_files_uid());
325 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", webfilename);
329 // check if the file is owned by expected group
330 if(stat.st_gid != web_files_gid()) {
331 error("%llu: File '%s' is owned by group %d (expected group %d). Access Denied.", w->id, webfilename, stat.st_gid, web_files_gid());
332 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", webfilename);
336 if((stat.st_mode & S_IFMT) == S_IFDIR) {
337 snprintf(webfilename, FILENAME_MAX+1, "%s/index.html", filename);
338 return mysendfile(w, webfilename);
341 if((stat.st_mode & S_IFMT) != S_IFREG) {
342 error("%llu: File '%s' is not a regular file. Access Denied.", w->id, webfilename);
343 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", webfilename);
348 w->ifd = open(webfilename, O_NONBLOCK, O_RDONLY);
352 if(errno == EBUSY || errno == EAGAIN) {
353 error("%llu: File '%s' is busy, sending 307 Moved Temporarily to force retry.", w->id, webfilename);
354 buffer_sprintf(w->response.header, "Location: /" WEB_PATH_FILE "/%s\r\n", filename);
355 buffer_sprintf(w->response.data, "The file '%s' is currently busy. Please try again later.", webfilename);
359 error("%llu: Cannot open file '%s'.", w->id, webfilename);
360 buffer_sprintf(w->response.data, "Cannot open file '%s'.", webfilename);
365 // pick a Content-Type for the file
366 if(strstr(filename, ".html") != NULL) w->response.data->contenttype = CT_TEXT_HTML;
367 else if(strstr(filename, ".js") != NULL) w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
368 else if(strstr(filename, ".css") != NULL) w->response.data->contenttype = CT_TEXT_CSS;
369 else if(strstr(filename, ".xml") != NULL) w->response.data->contenttype = CT_TEXT_XML;
370 else if(strstr(filename, ".xsl") != NULL) w->response.data->contenttype = CT_TEXT_XSL;
371 else if(strstr(filename, ".txt") != NULL) w->response.data->contenttype = CT_TEXT_PLAIN;
372 else if(strstr(filename, ".svg") != NULL) w->response.data->contenttype = CT_IMAGE_SVG_XML;
373 else if(strstr(filename, ".ttf") != NULL) w->response.data->contenttype = CT_APPLICATION_X_FONT_TRUETYPE;
374 else if(strstr(filename, ".otf") != NULL) w->response.data->contenttype = CT_APPLICATION_X_FONT_OPENTYPE;
375 else if(strstr(filename, ".woff2")!= NULL) w->response.data->contenttype = CT_APPLICATION_FONT_WOFF2;
376 else if(strstr(filename, ".woff") != NULL) w->response.data->contenttype = CT_APPLICATION_FONT_WOFF;
377 else if(strstr(filename, ".eot") != NULL) w->response.data->contenttype = CT_APPLICATION_VND_MS_FONTOBJ;
378 else if(strstr(filename, ".png") != NULL) w->response.data->contenttype = CT_IMAGE_PNG;
379 else if(strstr(filename, ".jpg") != NULL) w->response.data->contenttype = CT_IMAGE_JPG;
380 else if(strstr(filename, ".jpeg") != NULL) w->response.data->contenttype = CT_IMAGE_JPG;
381 else if(strstr(filename, ".gif") != NULL) w->response.data->contenttype = CT_IMAGE_GIF;
382 else if(strstr(filename, ".bmp") != NULL) w->response.data->contenttype = CT_IMAGE_BMP;
383 else if(strstr(filename, ".ico") != NULL) w->response.data->contenttype = CT_IMAGE_XICON;
384 else if(strstr(filename, ".icns") != NULL) w->response.data->contenttype = CT_IMAGE_ICNS;
385 else w->response.data->contenttype = CT_APPLICATION_OCTET_STREAM;
387 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);
389 w->mode = WEB_CLIENT_MODE_FILECOPY;
392 buffer_flush(w->response.data);
393 w->response.rlen = stat.st_size;
394 w->response.data->date = stat.st_mtim.tv_sec;
400 #ifdef NETDATA_WITH_ZLIB
401 void web_client_enable_deflate(struct web_client *w) {
402 if(w->response.zinitialized == 1) {
403 error("%llu: Compression has already be initialized for this client.", w->id);
407 if(w->response.sent) {
408 error("%llu: Cannot enable compression in the middle of a conversation.", w->id);
412 w->response.zstream.zalloc = Z_NULL;
413 w->response.zstream.zfree = Z_NULL;
414 w->response.zstream.opaque = Z_NULL;
416 w->response.zstream.next_in = (Bytef *)w->response.data->buffer;
417 w->response.zstream.avail_in = 0;
418 w->response.zstream.total_in = 0;
420 w->response.zstream.next_out = w->response.zbuffer;
421 w->response.zstream.avail_out = 0;
422 w->response.zstream.total_out = 0;
424 w->response.zstream.zalloc = Z_NULL;
425 w->response.zstream.zfree = Z_NULL;
426 w->response.zstream.opaque = Z_NULL;
428 // if(deflateInit(&w->response.zstream, Z_DEFAULT_COMPRESSION) != Z_OK) {
429 // error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
433 // Select GZIP compression: windowbits = 15 + 16 = 31
434 if(deflateInit2(&w->response.zstream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY) != Z_OK) {
435 error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
439 w->response.zsent = 0;
440 w->response.zoutput = 1;
441 w->response.zinitialized = 1;
443 debug(D_DEFLATE, "%llu: Initialized compression.", w->id);
445 #endif // NETDATA_WITH_ZLIB
447 uint32_t web_client_api_request_v1_data_options(char *o)
449 uint32_t ret = 0x00000000;
452 while(o && *o && (tok = mystrsep(&o, ", |"))) {
455 if(!strcmp(tok, "nonzero"))
456 ret |= RRDR_OPTION_NONZERO;
457 else if(!strcmp(tok, "flip") || !strcmp(tok, "reversed") || !strcmp(tok, "reverse"))
458 ret |= RRDR_OPTION_REVERSED;
459 else if(!strcmp(tok, "jsonwrap"))
460 ret |= RRDR_OPTION_JSON_WRAP;
461 else if(!strcmp(tok, "min2max"))
462 ret |= RRDR_OPTION_MIN2MAX;
463 else if(!strcmp(tok, "ms") || !strcmp(tok, "milliseconds"))
464 ret |= RRDR_OPTION_MILLISECONDS;
465 else if(!strcmp(tok, "abs") || !strcmp(tok, "absolute") || !strcmp(tok, "absolute_sum") || !strcmp(tok, "absolute-sum"))
466 ret |= RRDR_OPTION_ABSOLUTE;
467 else if(!strcmp(tok, "seconds"))
468 ret |= RRDR_OPTION_SECONDS;
469 else if(!strcmp(tok, "null2zero"))
470 ret |= RRDR_OPTION_NULL2ZERO;
471 else if(!strcmp(tok, "objectrows"))
472 ret |= RRDR_OPTION_OBJECTSROWS;
473 else if(!strcmp(tok, "google_json"))
474 ret |= RRDR_OPTION_GOOGLE_JSON;
475 else if(!strcmp(tok, "percentage"))
476 ret |= RRDR_OPTION_PERCENTAGE;
482 uint32_t web_client_api_request_v1_data_format(char *name)
484 if(!strcmp(name, DATASOURCE_FORMAT_DATATABLE_JSON)) // datatable
485 return DATASOURCE_DATATABLE_JSON;
487 else if(!strcmp(name, DATASOURCE_FORMAT_DATATABLE_JSONP)) // datasource
488 return DATASOURCE_DATATABLE_JSONP;
490 else if(!strcmp(name, DATASOURCE_FORMAT_JSON)) // json
491 return DATASOURCE_JSON;
493 else if(!strcmp(name, DATASOURCE_FORMAT_JSONP)) // jsonp
494 return DATASOURCE_JSONP;
496 else if(!strcmp(name, DATASOURCE_FORMAT_SSV)) // ssv
497 return DATASOURCE_SSV;
499 else if(!strcmp(name, DATASOURCE_FORMAT_CSV)) // csv
500 return DATASOURCE_CSV;
502 else if(!strcmp(name, DATASOURCE_FORMAT_TSV) || !strcmp(name, "tsv-excel")) // tsv
503 return DATASOURCE_TSV;
505 else if(!strcmp(name, DATASOURCE_FORMAT_HTML)) // html
506 return DATASOURCE_HTML;
508 else if(!strcmp(name, DATASOURCE_FORMAT_JS_ARRAY)) // array
509 return DATASOURCE_JS_ARRAY;
511 else if(!strcmp(name, DATASOURCE_FORMAT_SSV_COMMA)) // ssvcomma
512 return DATASOURCE_SSV_COMMA;
514 else if(!strcmp(name, DATASOURCE_FORMAT_CSV_JSON_ARRAY)) // csvjsonarray
515 return DATASOURCE_CSV_JSON_ARRAY;
517 return DATASOURCE_JSON;
520 uint32_t web_client_api_request_v1_data_google_format(char *name)
522 if(!strcmp(name, "json"))
523 return DATASOURCE_DATATABLE_JSONP;
525 else if(!strcmp(name, "html"))
526 return DATASOURCE_HTML;
528 else if(!strcmp(name, "csv"))
529 return DATASOURCE_CSV;
531 else if(!strcmp(name, "tsv-excel"))
532 return DATASOURCE_TSV;
534 return DATASOURCE_JSON;
537 int web_client_api_request_v1_data_group(char *name)
539 if(!strcmp(name, "max"))
542 else if(!strcmp(name, "average"))
543 return GROUP_AVERAGE;
548 int web_client_api_request_v1_charts(struct web_client *w, char *url)
552 buffer_flush(w->response.data);
553 w->response.data->contenttype = CT_APPLICATION_JSON;
554 rrd_stats_api_v1_charts(w->response.data);
558 int web_client_api_request_v1_chart(struct web_client *w, char *url)
563 buffer_flush(w->response.data);
566 char *value = mystrsep(&url, "?&[]");
567 if(!value || !*value) continue;
569 char *name = mystrsep(&value, "=");
570 if(!name || !*name) continue;
571 if(!value || !*value) continue;
573 // name and value are now the parameters
574 // they are not null and not empty
576 if(!strcmp(name, "chart")) chart = value;
578 /// buffer_sprintf(w->response.data, "Unknown parameter '%s' in request.", name);
583 if(!chart || !*chart) {
584 buffer_sprintf(w->response.data, "No chart id is given at the request.");
588 RRDSET *st = rrdset_find(chart);
589 if(!st) st = rrdset_find_byname(chart);
591 buffer_sprintf(w->response.data, "Chart '%s' is not found.", chart);
596 w->response.data->contenttype = CT_APPLICATION_JSON;
597 rrd_stats_api_v1_chart(st, w->response.data);
604 // returns the HTTP code
605 int web_client_api_request_v1_data(struct web_client *w, char *url)
607 debug(D_WEB_CLIENT, "%llu: API v1 data with URL '%s'", w->id, url);
610 BUFFER *dimensions = NULL;
612 buffer_flush(w->response.data);
614 char *google_version = "0.6",
617 *google_out = "json",
618 *responseHandler = NULL,
621 time_t last_timestamp_in_data = 0, google_timestamp = 0;
626 , *points_str = NULL;
628 int group = GROUP_MAX;
629 uint32_t format = DATASOURCE_JSON;
630 uint32_t options = 0x00000000;
633 char *value = mystrsep(&url, "?&[]");
634 if(!value || !*value) continue;
636 char *name = mystrsep(&value, "=");
637 if(!name || !*name) continue;
638 if(!value || !*value) continue;
640 debug(D_WEB_CLIENT, "%llu: API v1 query param '%s' with value '%s'", w->id, name, value);
642 // name and value are now the parameters
643 // they are not null and not empty
645 if(!strcmp(name, "chart")) chart = value;
646 else if(!strcmp(name, "dimension") || !strcmp(name, "dim") || !strcmp(name, "dimensions") || !strcmp(name, "dims")) {
647 if(!dimensions) dimensions = buffer_create(strlen(value));
649 buffer_strcat(dimensions, "|");
650 buffer_strcat(dimensions, value);
653 else if(!strcmp(name, "after")) after_str = value;
654 else if(!strcmp(name, "before")) before_str = value;
655 else if(!strcmp(name, "points")) points_str = value;
656 else if(!strcmp(name, "group")) {
657 group = web_client_api_request_v1_data_group(value);
659 else if(!strcmp(name, "format")) {
660 format = web_client_api_request_v1_data_format(value);
662 else if(!strcmp(name, "options")) {
663 options |= web_client_api_request_v1_data_options(value);
665 else if(!strcmp(name, "callback")) {
666 responseHandler = value;
668 else if(!strcmp(name, "filename")) {
671 else if(!strcmp(name, "tqx")) {
672 // parse Google Visualization API options
673 // https://developers.google.com/chart/interactive/docs/dev/implementing_data_source
674 char *tqx_name, *tqx_value;
677 tqx_value = mystrsep(&value, ";");
678 if(!tqx_value || !*tqx_value) continue;
680 tqx_name = mystrsep(&tqx_value, ":");
681 if(!tqx_name || !*tqx_name) continue;
682 if(!tqx_value || !*tqx_value) continue;
684 if(!strcmp(tqx_name, "version"))
685 google_version = tqx_value;
686 else if(!strcmp(tqx_name, "reqId"))
687 google_reqId = tqx_value;
688 else if(!strcmp(tqx_name, "sig")) {
689 google_sig = tqx_value;
690 google_timestamp = strtoul(google_sig, NULL, 0);
692 else if(!strcmp(tqx_name, "out")) {
693 google_out = tqx_value;
694 format = web_client_api_request_v1_data_google_format(google_out);
696 else if(!strcmp(tqx_name, "responseHandler"))
697 responseHandler = tqx_value;
698 else if(!strcmp(tqx_name, "outFileName"))
699 outFileName = tqx_value;
704 if(!chart || !*chart) {
705 buffer_sprintf(w->response.data, "No chart id is given at the request.");
709 RRDSET *st = rrdset_find(chart);
710 if(!st) st = rrdset_find_byname(chart);
712 buffer_sprintf(w->response.data, "Chart '%s' is not found.", chart);
717 long long before = (before_str && *before_str)?atol(before_str):0;
718 long long after = (after_str && *after_str) ?atol(after_str):0;
719 int points = (points_str && *points_str)?atoi(points_str):0;
721 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'"
724 , (dimensions)?buffer_tostring(dimensions):""
733 if(outFileName && *outFileName) {
734 buffer_sprintf(w->response.header, "Content-Disposition: attachment; filename=\"%s\"\r\n", outFileName);
735 error("generating outfilename header: '%s'", outFileName);
738 if(format == DATASOURCE_DATATABLE_JSONP) {
739 if(responseHandler == NULL)
740 responseHandler = "google.visualization.Query.setResponse";
742 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSON/JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
743 w->id, google_version, google_reqId, google_sig, google_out, responseHandler, outFileName
746 buffer_sprintf(w->response.data,
747 "%s({version:'%s',reqId:'%s',status:'ok',sig:'%lu',table:",
748 responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
750 else if(format == DATASOURCE_JSONP) {
751 if(responseHandler == NULL)
752 responseHandler = "callback";
754 buffer_strcat(w->response.data, responseHandler);
755 buffer_strcat(w->response.data, "(");
758 ret = rrd2format(st, w->response.data, dimensions, format, points, after, before, group, options, &last_timestamp_in_data);
760 if(format == DATASOURCE_DATATABLE_JSONP) {
761 if(google_timestamp < last_timestamp_in_data)
762 buffer_strcat(w->response.data, "});");
765 // the client already has the latest data
766 buffer_flush(w->response.data);
767 buffer_sprintf(w->response.data,
768 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
769 responseHandler, google_version, google_reqId);
772 else if(format == DATASOURCE_JSONP)
773 buffer_strcat(w->response.data, ");");
776 if(dimensions) buffer_free(dimensions);
780 int web_client_api_request_v1(struct web_client *w, char *url)
783 char *tok = mystrsep(&url, "/?&");
785 debug(D_WEB_CLIENT, "%llu: Searching for API v1 command '%s'.", w->id, tok);
787 if(strcmp(tok, "data") == 0)
788 return web_client_api_request_v1_data(w, url);
789 else if(strcmp(tok, "chart") == 0)
790 return web_client_api_request_v1_chart(w, url);
791 else if(strcmp(tok, "charts") == 0)
792 return web_client_api_request_v1_charts(w, url);
794 buffer_flush(w->response.data);
795 buffer_sprintf(w->response.data, "Unsupported v1 API command: %s", tok);
800 buffer_flush(w->response.data);
801 buffer_sprintf(w->response.data, "API v1 command?");
806 int web_client_api_request(struct web_client *w, char *url)
808 // get the api version
809 char *tok = mystrsep(&url, "/?&");
811 debug(D_WEB_CLIENT, "%llu: Searching for API version '%s'.", w->id, tok);
812 if(strcmp(tok, "v1") == 0)
813 return web_client_api_request_v1(w, url);
815 buffer_flush(w->response.data);
816 buffer_sprintf(w->response.data, "Unsupported API version: %s", tok);
821 buffer_flush(w->response.data);
822 buffer_sprintf(w->response.data, "Which API version?");
827 int web_client_data_request(struct web_client *w, char *url, int datasource_type)
831 char *args = strchr(url, '?');
837 // get the name of the data to show
838 char *tok = mystrsep(&url, "/");
840 // do we have such a data set?
842 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
843 st = rrdset_find_byname(tok);
844 if(!st) st = rrdset_find(tok);
849 // try to send a file with that name
850 buffer_flush(w->response.data);
851 return(mysendfile(w, tok));
855 debug(D_WEB_CLIENT, "%llu: Found RRD data with name '%s'.", w->id, tok);
857 // how many entries does the client want?
858 long lines = rrd_default_history_entries;
859 long group_count = 1;
860 time_t after = 0, before = 0;
861 int group_method = GROUP_AVERAGE;
865 // parse the lines required
866 tok = mystrsep(&url, "/");
867 if(tok) lines = atoi(tok);
868 if(lines < 1) lines = 1;
871 // parse the group count required
872 tok = mystrsep(&url, "/");
873 if(tok && *tok) group_count = atoi(tok);
874 if(group_count < 1) group_count = 1;
875 //if(group_count > save_history / 20) group_count = save_history / 20;
878 // parse the grouping method required
879 tok = mystrsep(&url, "/");
881 if(strcmp(tok, "max") == 0) group_method = GROUP_MAX;
882 else if(strcmp(tok, "average") == 0) group_method = GROUP_AVERAGE;
883 else if(strcmp(tok, "sum") == 0) group_method = GROUP_SUM;
884 else debug(D_WEB_CLIENT, "%llu: Unknown group method '%s'", w->id, tok);
889 tok = mystrsep(&url, "/");
890 if(tok && *tok) after = strtoul(tok, NULL, 10);
891 if(after < 0) after = 0;
895 tok = mystrsep(&url, "/");
896 if(tok && *tok) before = strtoul(tok, NULL, 10);
897 if(before < 0) before = 0;
901 tok = mystrsep(&url, "/");
902 if(tok && *tok && strcmp(tok, "nonzero") == 0) nonzero = 1;
905 w->response.data->contenttype = CT_APPLICATION_JSON;
906 buffer_flush(w->response.data);
908 char *google_version = "0.6";
909 char *google_reqId = "0";
910 char *google_sig = "0";
911 char *google_out = "json";
912 char *google_responseHandler = "google.visualization.Query.setResponse";
913 char *google_outFileName = NULL;
914 time_t last_timestamp_in_data = 0;
915 if(datasource_type == DATASOURCE_DATATABLE_JSON || datasource_type == DATASOURCE_DATATABLE_JSONP) {
917 w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
920 tok = mystrsep(&args, "&");
922 char *name = mystrsep(&tok, "=");
923 if(name && *name && strcmp(name, "tqx") == 0) {
924 char *key = mystrsep(&tok, ":");
925 char *value = mystrsep(&tok, ";");
926 if(key && value && *key && *value) {
927 if(strcmp(key, "version") == 0)
928 google_version = value;
930 else if(strcmp(key, "reqId") == 0)
931 google_reqId = value;
933 else if(strcmp(key, "sig") == 0)
936 else if(strcmp(key, "out") == 0)
939 else if(strcmp(key, "responseHandler") == 0)
940 google_responseHandler = value;
942 else if(strcmp(key, "outFileName") == 0)
943 google_outFileName = value;
949 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
950 w->id, google_version, google_reqId, google_sig, google_out, google_responseHandler, google_outFileName
953 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
954 last_timestamp_in_data = strtoul(google_sig, NULL, 0);
956 // check the client wants json
957 if(strcmp(google_out, "json") != 0) {
958 buffer_sprintf(w->response.data,
959 "%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.'}]});",
960 google_responseHandler, google_version, google_reqId, google_out);
966 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
967 buffer_sprintf(w->response.data,
968 "%s({version:'%s',reqId:'%s',status:'ok',sig:'%lu',table:",
969 google_responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
972 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);
973 time_t timestamp_in_data = rrd_stats_json(datasource_type, st, w->response.data, lines, group_count, group_method, after, before, nonzero);
975 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
976 if(timestamp_in_data > last_timestamp_in_data)
977 buffer_strcat(w->response.data, "});");
980 // the client already has the latest data
981 buffer_flush(w->response.data);
982 buffer_sprintf(w->response.data,
983 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
984 google_responseHandler, google_version, google_reqId);
992 int web_client_parse_request(struct web_client *w) {
996 // query string name-value
999 // http request headers name-value
1001 web_client_clean_request(w);
1003 debug(D_WEB_DATA, "%llu: Processing data buffer of %d bytes: '%s'.", w->id, w->response.data->bytes, w->response.data->buffer);
1005 char *buf = w->response.data->buffer;
1008 // ------------------------------------------------------------------------
1011 if(buf && (line = strsep(&buf, "\r\n"))) {
1013 if(line && (tok = strsep(&line, " "))) {
1014 w->request.protocol = strdup(tok);
1022 // ------------------------------------------------------------------------
1023 // the rest of the lines
1025 while(buf && (line = strsep(&buf, "\r\n"))) {
1026 while(line && (tok = strsep(&line, ": "))) {
1034 web_client_clean_request(w);
1039 void web_client_process(struct web_client *w) {
1042 int enable_gzip = 0;
1044 w->wait_receive = 0;
1046 // check if we have an empty line (end of HTTP header)
1047 if(strstr(w->response.data->buffer, "\r\n\r\n")) {
1048 global_statistics_lock();
1049 global_statistics.web_requests++;
1050 global_statistics_unlock();
1052 gettimeofday(&w->tv_in, NULL);
1053 debug(D_WEB_DATA, "%llu: Processing data buffer of %d bytes: '%s'.", w->id, w->response.data->len, w->response.data->buffer);
1055 // check if the client requested keep-alive HTTP
1056 if(strcasestr(w->response.data->buffer, "Connection: keep-alive")) w->keepalive = 1;
1057 else w->keepalive = 0;
1059 #ifdef NETDATA_WITH_ZLIB
1060 // check if the client accepts deflate
1061 if(web_enable_gzip && strstr(w->response.data->buffer, "gzip"))
1063 #endif // NETDATA_WITH_ZLIB
1065 int datasource_type = DATASOURCE_DATATABLE_JSONP;
1066 //if(strstr(w->response.data->buffer, "X-DataSource-Auth"))
1067 // datasource_type = DATASOURCE_GOOGLE_JSON;
1069 char *buf = (char *)buffer_tostring(w->response.data);
1070 char *tok = strsep(&buf, " \r\n");
1072 char *pointer_to_free = NULL; // keep url_decode() allocated buffer
1074 w->mode = WEB_CLIENT_MODE_NORMAL;
1076 if(buf && strcmp(tok, "GET") == 0) {
1077 tok = strsep(&buf, " \r\n");
1078 pointer_to_free = url = url_decode(tok);
1079 debug(D_WEB_CLIENT, "%llu: Processing HTTP GET on url '%s'.", w->id, url);
1081 else if(buf && strcmp(tok, "OPTIONS") == 0) {
1082 tok = strsep(&buf, " \r\n");
1083 pointer_to_free = url = url_decode(tok);
1084 debug(D_WEB_CLIENT, "%llu: Processing HTTP OPTIONS on url '%s'.", w->id, url);
1085 w->mode = WEB_CLIENT_MODE_OPTIONS;
1087 else if (buf && strcmp(tok, "POST") == 0) {
1089 tok = strsep(&buf, " \r\n");
1090 pointer_to_free = url = url_decode(tok);
1091 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);
1094 w->last_url[0] = '\0';
1096 if(w->mode == WEB_CLIENT_MODE_OPTIONS) {
1097 strncpy(w->last_url, url, URL_MAX);
1098 w->last_url[URL_MAX] = '\0';
1101 w->response.data->contenttype = CT_TEXT_PLAIN;
1102 buffer_flush(w->response.data);
1103 buffer_strcat(w->response.data, "OK");
1106 #ifdef NETDATA_WITH_ZLIB
1108 web_client_enable_deflate(w);
1111 strncpy(w->last_url, url, URL_MAX);
1112 w->last_url[URL_MAX] = '\0';
1114 tok = mystrsep(&url, "/?");
1116 debug(D_WEB_CLIENT, "%llu: Processing command '%s'.", w->id, tok);
1118 if(strcmp(tok, "api") == 0) {
1119 // the client is requesting api access
1120 datasource_type = DATASOURCE_JSON;
1121 code = web_client_api_request(w, url);
1123 #ifdef NETDATA_INTERNAL_CHECKS
1124 else if(strcmp(tok, "exit") == 0) {
1127 w->response.data->contenttype = CT_TEXT_PLAIN;
1128 buffer_flush(w->response.data);
1129 buffer_strcat(w->response.data, "will do");
1132 else if(strcmp(tok, WEB_PATH_DATA) == 0) { // "data"
1133 // the client is requesting rrd data
1134 datasource_type = DATASOURCE_JSON;
1135 code = web_client_data_request(w, url, datasource_type);
1137 else if(strcmp(tok, WEB_PATH_DATASOURCE) == 0) { // "datasource"
1138 // the client is requesting google datasource
1139 code = web_client_data_request(w, url, datasource_type);
1141 else if(strcmp(tok, WEB_PATH_GRAPH) == 0) { // "graph"
1142 // the client is requesting an rrd graph
1144 // get the name of the data to show
1145 tok = mystrsep(&url, "/?&");
1147 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1149 // do we have such a data set?
1150 RRDSET *st = rrdset_find_byname(tok);
1151 if(!st) st = rrdset_find(tok);
1154 // try to send a file with that name
1155 buffer_flush(w->response.data);
1156 code = mysendfile(w, tok);
1160 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending %s.json of RRD_STATS...", w->id, st->name);
1161 w->response.data->contenttype = CT_APPLICATION_JSON;
1162 buffer_flush(w->response.data);
1163 rrd_stats_graph_json(st, url, w->response.data);
1168 buffer_flush(w->response.data);
1169 buffer_strcat(w->response.data, "Graph name?\r\n");
1172 #ifdef NETDATA_INTERNAL_CHECKS
1173 else if(strcmp(tok, "debug") == 0) {
1174 buffer_flush(w->response.data);
1176 // get the name of the data to show
1177 tok = mystrsep(&url, "/?&");
1179 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1181 // do we have such a data set?
1182 RRDSET *st = rrdset_find_byname(tok);
1183 if(!st) st = rrdset_find(tok);
1186 buffer_sprintf(w->response.data, "Chart %s is not found.\r\n", tok);
1187 debug(D_WEB_CLIENT_ACCESS, "%llu: %s is not found.", w->id, tok);
1191 debug_flags |= D_RRD_STATS;
1192 st->debug = st->debug?0:1;
1193 buffer_sprintf(w->response.data, "Chart %s has now debug %s.\r\n", tok, st->debug?"enabled":"disabled");
1194 debug(D_WEB_CLIENT_ACCESS, "%llu: debug for %s is %s.", w->id, tok, st->debug?"enabled":"disabled");
1199 buffer_flush(w->response.data);
1200 buffer_strcat(w->response.data, "debug which chart?\r\n");
1203 else if(strcmp(tok, "mirror") == 0) {
1206 debug(D_WEB_CLIENT_ACCESS, "%llu: Mirroring...", w->id);
1208 // replace the zero bytes with spaces
1209 buffer_char_replace(w->response.data, '\0', ' ');
1211 // just leave the buffer as is
1212 // it will be copied back to the client
1215 else if(strcmp(tok, "list") == 0) {
1218 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending list of RRD_STATS...", w->id);
1220 buffer_flush(w->response.data);
1221 RRDSET *st = rrdset_root;
1223 for ( ; st ; st = st->next )
1224 buffer_sprintf(w->response.data, "%s\n", st->name);
1226 else if(strcmp(tok, "all.json") == 0) {
1228 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending JSON list of all monitors of RRD_STATS...", w->id);
1230 w->response.data->contenttype = CT_APPLICATION_JSON;
1231 buffer_flush(w->response.data);
1232 rrd_stats_all_json(w->response.data);
1234 else if(strcmp(tok, "netdata.conf") == 0) {
1236 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending netdata.conf ...", w->id);
1238 w->response.data->contenttype = CT_TEXT_PLAIN;
1239 buffer_flush(w->response.data);
1240 generate_config(w->response.data, 0);
1243 char filename[FILENAME_MAX+1];
1245 strncpy(filename, w->last_url, FILENAME_MAX);
1246 filename[FILENAME_MAX] = '\0';
1247 tok = mystrsep(&url, "?");
1248 buffer_flush(w->response.data);
1249 code = mysendfile(w, (tok && *tok)?tok:"/");
1253 char filename[FILENAME_MAX+1];
1255 strncpy(filename, w->last_url, FILENAME_MAX);
1256 filename[FILENAME_MAX] = '\0';
1257 tok = mystrsep(&url, "?");
1258 buffer_flush(w->response.data);
1259 code = mysendfile(w, (tok && *tok)?tok:"/");
1263 strcpy(w->last_url, "not a valid response");
1265 if(buf) debug(D_WEB_CLIENT_ACCESS, "%llu: Cannot understand '%s'.", w->id, buf);
1268 buffer_flush(w->response.data);
1269 buffer_strcat(w->response.data, "I don't understand you...\r\n");
1272 // free url_decode() buffer
1273 if(pointer_to_free) {
1274 free(pointer_to_free);
1275 pointer_to_free = NULL;
1278 else if(w->response.data->len > TOO_BIG_REQUEST) {
1279 strcpy(w->last_url, "too big request");
1281 debug(D_WEB_CLIENT_ACCESS, "%llu: Received request is too big (%zd bytes).", w->id, w->response.data->len);
1284 buffer_flush(w->response.data);
1285 buffer_sprintf(w->response.data, "Received request is too big (%zd bytes).\r\n", w->response.data->len);
1288 // wait for more data
1289 w->wait_receive = 1;
1293 gettimeofday(&w->tv_ready, NULL);
1294 w->response.data->date = time(NULL);
1295 w->response.sent = 0;
1296 w->response.code = code;
1298 // prepare the HTTP response header
1299 debug(D_WEB_CLIENT, "%llu: Generating HTTP header with response %d.", w->id, code);
1301 char *content_type_string;
1302 switch(w->response.data->contenttype) {
1304 content_type_string = "text/html; charset=utf-8";
1307 case CT_APPLICATION_XML:
1308 content_type_string = "application/xml; charset=utf-8";
1311 case CT_APPLICATION_JSON:
1312 content_type_string = "application/json; charset=utf-8";
1315 case CT_APPLICATION_X_JAVASCRIPT:
1316 content_type_string = "application/x-javascript; charset=utf-8";
1320 content_type_string = "text/css; charset=utf-8";
1324 content_type_string = "text/xml; charset=utf-8";
1328 content_type_string = "text/xsl; charset=utf-8";
1331 case CT_APPLICATION_OCTET_STREAM:
1332 content_type_string = "application/octet-stream";
1335 case CT_IMAGE_SVG_XML:
1336 content_type_string = "image/svg+xml";
1339 case CT_APPLICATION_X_FONT_TRUETYPE:
1340 content_type_string = "application/x-font-truetype";
1343 case CT_APPLICATION_X_FONT_OPENTYPE:
1344 content_type_string = "application/x-font-opentype";
1347 case CT_APPLICATION_FONT_WOFF:
1348 content_type_string = "application/font-woff";
1351 case CT_APPLICATION_FONT_WOFF2:
1352 content_type_string = "application/font-woff2";
1355 case CT_APPLICATION_VND_MS_FONTOBJ:
1356 content_type_string = "application/vnd.ms-fontobject";
1360 content_type_string = "image/png";
1364 content_type_string = "image/jpeg";
1368 content_type_string = "image/gif";
1371 case CT_IMAGE_XICON:
1372 content_type_string = "image/x-icon";
1376 content_type_string = "image/bmp";
1380 content_type_string = "image/icns";
1385 content_type_string = "text/plain; charset=utf-8";
1396 code_msg = "Temporary Redirect";
1400 code_msg = "Bad Request";
1404 code_msg = "Forbidden";
1408 code_msg = "Not Found";
1412 code_msg = "Internal Server Error";
1417 struct tm tmbuf, *tm = gmtime_r(&w->response.data->date, &tmbuf);
1418 strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %Z", tm);
1420 buffer_sprintf(w->response.header_output,
1421 "HTTP/1.1 %d %s\r\n"
1422 "Connection: %s\r\n"
1423 "Server: NetData Embedded HTTP Server\r\n"
1424 "Content-Type: %s\r\n"
1425 "Access-Control-Allow-Origin: *\r\n"
1426 "Access-Control-Allow-Methods: GET, OPTIONS\r\n"
1427 "Access-Control-Allow-Headers: accept, x-requested-with\r\n"
1428 "Access-Control-Max-Age: 86400\r\n"
1431 , w->keepalive?"keep-alive":"close"
1432 , content_type_string
1436 if(buffer_strlen(w->response.header))
1437 buffer_strcat(w->response.header_output, buffer_tostring(w->response.header));
1439 if(w->mode == WEB_CLIENT_MODE_NORMAL && (w->response.data->options & WB_CONTENT_NO_CACHEABLE)) {
1440 buffer_sprintf(w->response.header_output,
1442 "Cache-Control: no-cache\r\n"
1447 time_t et = w->response.data->date + (86400 * 14);
1448 struct tm etmbuf, *etm = gmtime_r(&et, &etmbuf);
1449 strftime(edate, sizeof(edate), "%a, %d %b %Y %H:%M:%S %Z", etm);
1451 buffer_sprintf(w->response.header_output,
1453 "Cache-Control: public\r\n"
1457 // if we know the content length, put it
1458 if(!w->response.zoutput && (w->response.data->len || w->response.rlen))
1459 buffer_sprintf(w->response.header_output,
1460 "Content-Length: %ld\r\n"
1461 , w->response.data->len? w->response.data->len: w->response.rlen
1463 else if(!w->response.zoutput)
1464 w->keepalive = 0; // content-length is required for keep-alive
1466 if(w->response.zoutput) {
1467 buffer_strcat(w->response.header_output,
1468 "Content-Encoding: gzip\r\n"
1469 "Transfer-Encoding: chunked\r\n"
1473 buffer_strcat(w->response.header_output, "\r\n");
1475 // disable TCP_NODELAY, to buffer the header
1477 if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0)
1478 error("%llu: failed to disable TCP_NODELAY on socket.", w->id);
1480 // sent the HTTP header
1481 debug(D_WEB_DATA, "%llu: Sending response HTTP header of size %d: '%s'"
1483 , buffer_strlen(w->response.header_output)
1484 , buffer_tostring(w->response.header_output)
1487 bytes = send(w->ofd, buffer_tostring(w->response.header_output), buffer_strlen(w->response.header_output), 0);
1488 if(bytes != (ssize_t) buffer_strlen(w->response.header_output))
1489 error("%llu: HTTP Header failed to be sent (I sent %d bytes but the system sent %d bytes)."
1491 , buffer_strlen(w->response.header_output)
1494 global_statistics_lock();
1495 global_statistics.bytes_sent += bytes;
1496 global_statistics_unlock();
1499 // enable TCP_NODELAY, to send all data immediately at the next send()
1501 if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0) error("%llu: failed to enable TCP_NODELAY on socket.", w->id);
1503 // enable sending immediately if we have data
1504 if(w->response.data->len) w->wait_send = 1;
1505 else w->wait_send = 0;
1509 case WEB_CLIENT_MODE_OPTIONS:
1510 debug(D_WEB_CLIENT, "%llu: Done preparing the OPTIONS response. Sending data (%d bytes) to client.", w->id, w->response.data->len);
1513 case WEB_CLIENT_MODE_NORMAL:
1514 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Sending data (%d bytes) to client.", w->id, w->response.data->len);
1517 case WEB_CLIENT_MODE_FILECOPY:
1518 if(w->response.rlen) {
1519 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending data file of %d bytes to client.", w->id, w->response.rlen);
1520 w->wait_receive = 1;
1523 // utilize the kernel sendfile() for copying the file to the socket.
1524 // this block of code can be commented, without anything missing.
1525 // when it is commented, the program will copy the data using async I/O.
1527 long len = sendfile(w->ofd, w->ifd, NULL, w->response.data->rbytes);
1528 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);
1529 else web_client_reset(w);
1534 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending an unknown amount of bytes to client.", w->id);
1538 fatal("%llu: Unknown client mode %d.", w->id, w->mode);
1543 long web_client_send_chunk_header(struct web_client *w, long len)
1545 debug(D_DEFLATE, "%llu: OPEN CHUNK of %d bytes (hex: %x).", w->id, len, len);
1547 sprintf(buf, "%lX\r\n", len);
1548 ssize_t bytes = send(w->ofd, buf, strlen(buf), MSG_DONTWAIT);
1550 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk header %d bytes.", w->id, bytes);
1551 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk header to the client.", w->id);
1552 else debug(D_DEFLATE, "%llu: Failed to send chunk header to client.", w->id);
1557 long web_client_send_chunk_close(struct web_client *w)
1559 //debug(D_DEFLATE, "%llu: CLOSE CHUNK.", w->id);
1561 ssize_t bytes = send(w->ofd, "\r\n", 2, MSG_DONTWAIT);
1563 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
1564 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
1565 else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client.", w->id);
1570 long web_client_send_chunk_finalize(struct web_client *w)
1572 //debug(D_DEFLATE, "%llu: FINALIZE CHUNK.", w->id);
1574 ssize_t bytes = send(w->ofd, "\r\n0\r\n\r\n", 7, MSG_DONTWAIT);
1576 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
1577 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
1578 else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client.", w->id);
1583 #ifdef NETDATA_WITH_ZLIB
1584 long web_client_send_deflate(struct web_client *w)
1586 long len = 0, t = 0;
1588 // when using compression,
1589 // w->response.sent is the amount of bytes passed through compression
1591 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);
1593 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) {
1594 // there is nothing to send
1596 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1598 // finalize the chunk
1599 if(w->response.sent != 0)
1600 t += web_client_send_chunk_finalize(w);
1602 // there can be two cases for this
1603 // A. we have done everything
1604 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
1606 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->response.rlen && w->response.rlen > w->response.data->len) {
1607 // we have to wait, more data will come
1608 debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1613 if(w->keepalive == 0) {
1614 debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->response.sent);
1620 web_client_reset(w);
1621 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1625 if(w->response.zhave == w->response.zsent) {
1626 // compress more input data
1628 // close the previous open chunk
1629 if(w->response.sent != 0) t += web_client_send_chunk_close(w);
1631 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);
1633 // give the compressor all the data not passed through the compressor yet
1634 if(w->response.data->len > w->response.sent) {
1635 #ifdef NETDATA_INTERNAL_CHECKS
1636 if((long)w->response.sent - (long)w->response.zstream.avail_in < 0)
1637 error("internal error: avail_in is corrupted.");
1639 w->response.zstream.next_in = (Bytef *)&w->response.data->buffer[w->response.sent - w->response.zstream.avail_in];
1640 w->response.zstream.avail_in += (uInt) (w->response.data->len - w->response.sent);
1643 // reset the compressor output buffer
1644 w->response.zstream.next_out = w->response.zbuffer;
1645 w->response.zstream.avail_out = ZLIB_CHUNK;
1647 // ask for FINISH if we have all the input
1648 int flush = Z_SYNC_FLUSH;
1649 if(w->mode == WEB_CLIENT_MODE_NORMAL
1650 || (w->mode == WEB_CLIENT_MODE_FILECOPY && !w->wait_receive && w->response.data->len == w->response.rlen)) {
1652 debug(D_DEFLATE, "%llu: Requesting Z_FINISH, if possible.", w->id);
1655 debug(D_DEFLATE, "%llu: Requesting Z_SYNC_FLUSH.", w->id);
1659 if(deflate(&w->response.zstream, flush) == Z_STREAM_ERROR) {
1660 error("%llu: Compression failed. Closing down client.", w->id);
1661 web_client_reset(w);
1665 w->response.zhave = ZLIB_CHUNK - w->response.zstream.avail_out;
1666 w->response.zsent = 0;
1668 // keep track of the bytes passed through the compressor
1669 w->response.sent = w->response.data->len;
1671 debug(D_DEFLATE, "%llu: Compression produced %d bytes.", w->id, w->response.zhave);
1674 t += web_client_send_chunk_header(w, w->response.zhave);
1677 debug(D_WEB_CLIENT, "%llu: Sending %d bytes of data (+%d of chunk header).", w->id, w->response.zhave - w->response.zsent, t);
1679 len = send(w->ofd, &w->response.zbuffer[w->response.zsent], (size_t) (w->response.zhave - w->response.zsent), MSG_DONTWAIT);
1681 w->response.zsent += len;
1683 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, len);
1685 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);
1686 else debug(D_WEB_CLIENT, "%llu: Failed to send data to client. Reason: %s", w->id, strerror(errno));
1690 #endif // NETDATA_WITH_ZLIB
1692 long web_client_send(struct web_client *w)
1694 #ifdef NETDATA_WITH_ZLIB
1695 if(likely(w->response.zoutput)) return web_client_send_deflate(w);
1696 #endif // NETDATA_WITH_ZLIB
1700 if(unlikely(w->response.data->len - w->response.sent == 0)) {
1701 // there is nothing to send
1703 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1705 // there can be two cases for this
1706 // A. we have done everything
1707 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
1709 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->response.rlen && w->response.rlen > w->response.data->len) {
1710 // we have to wait, more data will come
1711 debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1716 if(unlikely(w->keepalive == 0)) {
1717 debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->response.sent);
1722 web_client_reset(w);
1723 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1727 bytes = send(w->ofd, &w->response.data->buffer[w->response.sent], w->response.data->len - w->response.sent, MSG_DONTWAIT);
1728 if(likely(bytes > 0)) {
1729 w->response.sent += bytes;
1730 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, bytes);
1732 else if(likely(bytes == 0)) debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client.", w->id);
1733 else debug(D_WEB_CLIENT, "%llu: Failed to send data to client.", w->id);
1738 long web_client_receive(struct web_client *w)
1740 // do we have any space for more data?
1741 buffer_need_bytes(w->response.data, WEB_REQUEST_LENGTH);
1743 long left = w->response.data->size - w->response.data->len;
1746 if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY))
1747 bytes = read(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1));
1749 bytes = recv(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1), MSG_DONTWAIT);
1751 if(likely(bytes > 0)) {
1752 size_t old = w->response.data->len;
1753 w->response.data->len += bytes;
1754 w->response.data->buffer[w->response.data->len] = '\0';
1756 debug(D_WEB_CLIENT, "%llu: Received %d bytes.", w->id, bytes);
1757 debug(D_WEB_DATA, "%llu: Received data: '%s'.", w->id, &w->response.data->buffer[old]);
1759 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1761 if(w->response.rlen && w->response.data->len >= w->response.rlen) w->wait_receive = 0;
1764 else if(likely(bytes == 0)) {
1765 debug(D_WEB_CLIENT, "%llu: Out of input data.", w->id);
1767 // if we cannot read, it means we have an error on input.
1768 // if however, we are copying a file from ifd to ofd, we should not return an error.
1769 // in this case, the error should be generated when the file has been sent to the client.
1771 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1772 // we are copying data from ifd to ofd
1773 // let it finish copying...
1774 w->wait_receive = 0;
1775 debug(D_WEB_CLIENT, "%llu: Disabling input.", w->id);
1787 // --------------------------------------------------------------------------------------
1788 // the thread of a single client
1790 // 1. waits for input and output, using async I/O
1791 // 2. it processes HTTP requests
1792 // 3. it generates HTTP responses
1793 // 4. it copies data from input to output if mode is FILECOPY
1795 void *web_client_main(void *ptr)
1797 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
1798 error("Cannot set pthread cancel type to DEFERRED.");
1800 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
1801 error("Cannot set pthread cancel state to ENABLE.");
1804 struct web_client *w = ptr;
1806 fd_set ifds, ofds, efds;
1809 log_access("%llu: %s port %s connected on thread task id %d", w->id, w->client_ip, w->client_port, gettid());
1816 FD_SET(w->ifd, &efds);
1818 if(w->ifd != w->ofd)
1819 FD_SET(w->ofd, &efds);
1821 if (w->wait_receive) {
1822 FD_SET(w->ifd, &ifds);
1823 if(w->ifd > fdmax) fdmax = w->ifd;
1827 FD_SET(w->ofd, &ofds);
1828 if(w->ofd > fdmax) fdmax = w->ofd;
1831 tv.tv_sec = web_client_timeout;
1834 debug(D_WEB_CLIENT, "%llu: Waiting socket async I/O for %s %s", w->id, w->wait_receive?"INPUT":"", w->wait_send?"OUTPUT":"");
1835 retval = select(fdmax+1, &ifds, &ofds, &efds, &tv);
1838 debug(D_WEB_CLIENT_ACCESS, "%llu: LISTENER: select() failed.", w->id);
1843 debug(D_WEB_CLIENT_ACCESS, "%llu: LISTENER: timeout.", w->id);
1847 if(FD_ISSET(w->ifd, &efds)) {
1848 debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on input socket.", w->id);
1852 if(FD_ISSET(w->ofd, &efds)) {
1853 debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on output socket.", w->id);
1857 if(w->wait_send && FD_ISSET(w->ofd, &ofds)) {
1859 if((bytes = web_client_send(w)) < 0) {
1860 debug(D_WEB_CLIENT, "%llu: Cannot send data to client. Closing client.", w->id);
1865 global_statistics_lock();
1866 global_statistics.bytes_sent += bytes;
1867 global_statistics_unlock();
1870 if(w->wait_receive && FD_ISSET(w->ifd, &ifds)) {
1872 if((bytes = web_client_receive(w)) < 0) {
1873 debug(D_WEB_CLIENT, "%llu: Cannot receive data from client. Closing client.", w->id);
1878 if(w->mode == WEB_CLIENT_MODE_NORMAL) {
1879 debug(D_WEB_CLIENT, "%llu: Attempting to process received data (%ld bytes).", w->id, bytes);
1880 // info("%llu: Attempting to process received data (%ld bytes).", w->id, bytes);
1881 web_client_process(w);
1884 global_statistics_lock();
1885 global_statistics.bytes_received += bytes;
1886 global_statistics_unlock();
1890 log_access("%llu: %s port %s disconnected from thread task id %d", w->id, w->client_ip, w->client_port, gettid());
1891 debug(D_WEB_CLIENT, "%llu: done...", w->id);
1893 web_client_reset(w);