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, "/?&");
784 debug(D_WEB_CLIENT, "%llu: Searching for API v1 command '%s'.", w->id, tok);
786 if(strcmp(tok, "data") == 0)
787 return web_client_api_request_v1_data(w, url);
788 else if(strcmp(tok, "chart") == 0)
789 return web_client_api_request_v1_chart(w, url);
790 else if(strcmp(tok, "charts") == 0)
791 return web_client_api_request_v1_charts(w, url);
793 buffer_flush(w->response.data);
794 buffer_sprintf(w->response.data, "Unsupported v1 API command: %s", tok);
798 int web_client_api_request(struct web_client *w, char *url)
800 // get the api version
801 char *tok = mystrsep(&url, "/?&");
802 debug(D_WEB_CLIENT, "%llu: Searching for API version '%s'.", w->id, tok);
804 if(strcmp(tok, "v1") == 0)
805 return web_client_api_request_v1(w, url);
807 buffer_flush(w->response.data);
808 buffer_sprintf(w->response.data, "Unsupported API version: %s", tok);
812 int web_client_data_request(struct web_client *w, char *url, int datasource_type)
814 char *args = strchr(url, '?');
820 // get the name of the data to show
821 char *tok = mystrsep(&url, "/");
822 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
824 // do we have such a data set?
825 RRDSET *st = rrdset_find_byname(tok);
826 if(!st) st = rrdset_find(tok);
829 // try to send a file with that name
830 buffer_flush(w->response.data);
831 return(mysendfile(w, tok));
835 debug(D_WEB_CLIENT, "%llu: Found RRD data with name '%s'.", w->id, tok);
837 // how many entries does the client want?
838 long lines = rrd_default_history_entries;
839 long group_count = 1;
840 time_t after = 0, before = 0;
841 int group_method = GROUP_AVERAGE;
845 // parse the lines required
846 tok = mystrsep(&url, "/");
847 if(tok) lines = atoi(tok);
848 if(lines < 1) lines = 1;
851 // parse the group count required
852 tok = mystrsep(&url, "/");
853 if(tok) group_count = atoi(tok);
854 if(group_count < 1) group_count = 1;
855 //if(group_count > save_history / 20) group_count = save_history / 20;
858 // parse the grouping method required
859 tok = mystrsep(&url, "/");
860 if(strcmp(tok, "max") == 0) group_method = GROUP_MAX;
861 else if(strcmp(tok, "average") == 0) group_method = GROUP_AVERAGE;
862 else if(strcmp(tok, "sum") == 0) group_method = GROUP_SUM;
863 else debug(D_WEB_CLIENT, "%llu: Unknown group method '%s'", w->id, tok);
867 tok = mystrsep(&url, "/");
868 if(tok) after = strtoul(tok, NULL, 10);
869 if(after < 0) after = 0;
873 tok = mystrsep(&url, "/");
874 if(tok) before = strtoul(tok, NULL, 10);
875 if(before < 0) before = 0;
879 tok = mystrsep(&url, "/");
880 if(tok && strcmp(tok, "nonzero") == 0) nonzero = 1;
883 w->response.data->contenttype = CT_APPLICATION_JSON;
884 buffer_flush(w->response.data);
886 char *google_version = "0.6";
887 char *google_reqId = "0";
888 char *google_sig = "0";
889 char *google_out = "json";
890 char *google_responseHandler = "google.visualization.Query.setResponse";
891 char *google_outFileName = NULL;
892 time_t last_timestamp_in_data = 0;
893 if(datasource_type == DATASOURCE_DATATABLE_JSON || datasource_type == DATASOURCE_DATATABLE_JSONP) {
895 w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
898 tok = mystrsep(&args, "&");
900 char *name = mystrsep(&tok, "=");
901 if(name && strcmp(name, "tqx") == 0) {
902 char *key = mystrsep(&tok, ":");
903 char *value = mystrsep(&tok, ";");
904 if(key && value && *key && *value) {
905 if(strcmp(key, "version") == 0)
906 google_version = value;
908 else if(strcmp(key, "reqId") == 0)
909 google_reqId = value;
911 else if(strcmp(key, "sig") == 0)
914 else if(strcmp(key, "out") == 0)
917 else if(strcmp(key, "responseHandler") == 0)
918 google_responseHandler = value;
920 else if(strcmp(key, "outFileName") == 0)
921 google_outFileName = value;
927 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
928 w->id, google_version, google_reqId, google_sig, google_out, google_responseHandler, google_outFileName
931 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
932 last_timestamp_in_data = strtoul(google_sig, NULL, 0);
934 // check the client wants json
935 if(strcmp(google_out, "json") != 0) {
936 buffer_sprintf(w->response.data,
937 "%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.'}]});",
938 google_responseHandler, google_version, google_reqId, google_out);
944 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
945 buffer_sprintf(w->response.data,
946 "%s({version:'%s',reqId:'%s',status:'ok',sig:'%lu',table:",
947 google_responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
950 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);
951 time_t timestamp_in_data = rrd_stats_json(datasource_type, st, w->response.data, lines, group_count, group_method, after, before, nonzero);
953 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
954 if(timestamp_in_data > last_timestamp_in_data)
955 buffer_strcat(w->response.data, "});");
958 // the client already has the latest data
959 buffer_flush(w->response.data);
960 buffer_sprintf(w->response.data,
961 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
962 google_responseHandler, google_version, google_reqId);
970 int web_client_parse_request(struct web_client *w) {
974 // query string name-value
977 // http request headers name-value
979 web_client_clean_request(w);
981 debug(D_WEB_DATA, "%llu: Processing data buffer of %d bytes: '%s'.", w->id, w->response.data->bytes, w->response.data->buffer);
983 char *buf = w->response.data->buffer;
986 // ------------------------------------------------------------------------
989 if(buf && (line = strsep(&buf, "\r\n"))) {
991 if(line && (tok = strsep(&line, " "))) {
992 w->request.protocol = strdup(tok);
1000 // ------------------------------------------------------------------------
1001 // the rest of the lines
1003 while(buf && (line = strsep(&buf, "\r\n"))) {
1004 while(line && (tok = strsep(&line, ": "))) {
1012 web_client_clean_request(w);
1017 void web_client_process(struct web_client *w) {
1020 int enable_gzip = 0;
1022 w->wait_receive = 0;
1024 // check if we have an empty line (end of HTTP header)
1025 if(strstr(w->response.data->buffer, "\r\n\r\n")) {
1026 global_statistics_lock();
1027 global_statistics.web_requests++;
1028 global_statistics_unlock();
1030 gettimeofday(&w->tv_in, NULL);
1031 debug(D_WEB_DATA, "%llu: Processing data buffer of %d bytes: '%s'.", w->id, w->response.data->len, w->response.data->buffer);
1033 // check if the client requested keep-alive HTTP
1034 if(strcasestr(w->response.data->buffer, "Connection: keep-alive")) w->keepalive = 1;
1035 else w->keepalive = 0;
1037 #ifdef NETDATA_WITH_ZLIB
1038 // check if the client accepts deflate
1039 if(web_enable_gzip && strstr(w->response.data->buffer, "gzip"))
1041 #endif // NETDATA_WITH_ZLIB
1043 int datasource_type = DATASOURCE_DATATABLE_JSONP;
1044 //if(strstr(w->response.data->buffer, "X-DataSource-Auth"))
1045 // datasource_type = DATASOURCE_GOOGLE_JSON;
1047 char *buf = (char *)buffer_tostring(w->response.data);
1048 char *tok = strsep(&buf, " \r\n");
1050 char *pointer_to_free = NULL; // keep url_decode() allocated buffer
1052 w->mode = WEB_CLIENT_MODE_NORMAL;
1054 if(buf && strcmp(tok, "GET") == 0) {
1055 tok = strsep(&buf, " \r\n");
1056 pointer_to_free = url = url_decode(tok);
1057 debug(D_WEB_CLIENT, "%llu: Processing HTTP GET on url '%s'.", w->id, url);
1059 else if(buf && strcmp(tok, "OPTIONS") == 0) {
1060 tok = strsep(&buf, " \r\n");
1061 pointer_to_free = url = url_decode(tok);
1062 debug(D_WEB_CLIENT, "%llu: Processing HTTP OPTIONS on url '%s'.", w->id, url);
1063 w->mode = WEB_CLIENT_MODE_OPTIONS;
1065 else if (buf && strcmp(tok, "POST") == 0) {
1067 tok = strsep(&buf, " \r\n");
1068 pointer_to_free = url = url_decode(tok);
1069 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);
1072 w->last_url[0] = '\0';
1074 if(w->mode == WEB_CLIENT_MODE_OPTIONS) {
1075 strncpy(w->last_url, url, URL_MAX);
1076 w->last_url[URL_MAX] = '\0';
1079 w->response.data->contenttype = CT_TEXT_PLAIN;
1080 buffer_flush(w->response.data);
1081 buffer_strcat(w->response.data, "OK");
1084 #ifdef NETDATA_WITH_ZLIB
1086 web_client_enable_deflate(w);
1089 strncpy(w->last_url, url, URL_MAX);
1090 w->last_url[URL_MAX] = '\0';
1092 tok = mystrsep(&url, "/?");
1094 debug(D_WEB_CLIENT, "%llu: Processing command '%s'.", w->id, tok);
1096 if(strcmp(tok, "api") == 0) {
1097 // the client is requesting api access
1098 datasource_type = DATASOURCE_JSON;
1099 code = web_client_api_request(w, url);
1101 #ifdef NETDATA_INTERNAL_CHECKS
1102 else if(strcmp(tok, "exit") == 0) {
1105 w->response.data->contenttype = CT_TEXT_PLAIN;
1106 buffer_flush(w->response.data);
1107 buffer_strcat(w->response.data, "will do");
1110 else if(strcmp(tok, WEB_PATH_DATA) == 0) { // "data"
1111 // the client is requesting rrd data
1112 datasource_type = DATASOURCE_JSON;
1113 code = web_client_data_request(w, url, datasource_type);
1115 else if(strcmp(tok, WEB_PATH_DATASOURCE) == 0) { // "datasource"
1116 // the client is requesting google datasource
1117 code = web_client_data_request(w, url, datasource_type);
1119 else if(strcmp(tok, WEB_PATH_GRAPH) == 0) { // "graph"
1120 // the client is requesting an rrd graph
1122 // get the name of the data to show
1123 tok = mystrsep(&url, "/?&");
1124 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1126 // do we have such a data set?
1127 RRDSET *st = rrdset_find_byname(tok);
1128 if(!st) st = rrdset_find(tok);
1131 // try to send a file with that name
1132 buffer_flush(w->response.data);
1133 code = mysendfile(w, tok);
1137 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending %s.json of RRD_STATS...", w->id, st->name);
1138 w->response.data->contenttype = CT_APPLICATION_JSON;
1139 buffer_flush(w->response.data);
1140 rrd_stats_graph_json(st, url, w->response.data);
1143 #ifdef NETDATA_INTERNAL_CHECKS
1144 else if(strcmp(tok, "debug") == 0) {
1145 buffer_flush(w->response.data);
1147 // get the name of the data to show
1148 tok = mystrsep(&url, "/?&");
1149 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1151 // do we have such a data set?
1152 RRDSET *st = rrdset_find_byname(tok);
1153 if(!st) st = rrdset_find(tok);
1156 buffer_sprintf(w->response.data, "Chart %s is not found.\r\n", tok);
1157 debug(D_WEB_CLIENT_ACCESS, "%llu: %s is not found.", w->id, tok);
1161 debug_flags |= D_RRD_STATS;
1162 st->debug = st->debug?0:1;
1163 buffer_sprintf(w->response.data, "Chart %s has now debug %s.\r\n", tok, st->debug?"enabled":"disabled");
1164 debug(D_WEB_CLIENT_ACCESS, "%llu: debug for %s is %s.", w->id, tok, st->debug?"enabled":"disabled");
1167 else if(strcmp(tok, "mirror") == 0) {
1170 debug(D_WEB_CLIENT_ACCESS, "%llu: Mirroring...", w->id);
1172 // replace the zero bytes with spaces
1173 buffer_char_replace(w->response.data, '\0', ' ');
1175 // just leave the buffer as is
1176 // it will be copied back to the client
1179 else if(strcmp(tok, "list") == 0) {
1182 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending list of RRD_STATS...", w->id);
1184 buffer_flush(w->response.data);
1185 RRDSET *st = rrdset_root;
1187 for ( ; st ; st = st->next )
1188 buffer_sprintf(w->response.data, "%s\n", st->name);
1190 else if(strcmp(tok, "all.json") == 0) {
1192 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending JSON list of all monitors of RRD_STATS...", w->id);
1194 w->response.data->contenttype = CT_APPLICATION_JSON;
1195 buffer_flush(w->response.data);
1196 rrd_stats_all_json(w->response.data);
1198 else if(strcmp(tok, "netdata.conf") == 0) {
1200 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending netdata.conf ...", w->id);
1202 w->response.data->contenttype = CT_TEXT_PLAIN;
1203 buffer_flush(w->response.data);
1204 generate_config(w->response.data, 0);
1207 char filename[FILENAME_MAX+1];
1209 strncpy(filename, w->last_url, FILENAME_MAX);
1210 filename[FILENAME_MAX] = '\0';
1211 tok = mystrsep(&url, "?");
1212 buffer_flush(w->response.data);
1213 code = mysendfile(w, (tok && *tok)?tok:"/");
1217 strcpy(w->last_url, "not a valid response");
1219 if(buf) debug(D_WEB_CLIENT_ACCESS, "%llu: Cannot understand '%s'.", w->id, buf);
1222 buffer_flush(w->response.data);
1223 buffer_strcat(w->response.data, "I don't understand you...\r\n");
1226 // free url_decode() buffer
1227 if(pointer_to_free) free(pointer_to_free);
1229 else if(w->response.data->len > TOO_BIG_REQUEST) {
1230 strcpy(w->last_url, "too big request");
1232 debug(D_WEB_CLIENT_ACCESS, "%llu: Received request is too big (%zd bytes).", w->id, w->response.data->len);
1235 buffer_flush(w->response.data);
1236 buffer_sprintf(w->response.data, "Received request is too big (%zd bytes).\r\n", w->response.data->len);
1239 // wait for more data
1240 w->wait_receive = 1;
1244 gettimeofday(&w->tv_ready, NULL);
1245 w->response.data->date = time(NULL);
1246 w->response.sent = 0;
1247 w->response.code = code;
1249 // prepare the HTTP response header
1250 debug(D_WEB_CLIENT, "%llu: Generating HTTP header with response %d.", w->id, code);
1252 char *content_type_string;
1253 switch(w->response.data->contenttype) {
1255 content_type_string = "text/html; charset=utf-8";
1258 case CT_APPLICATION_XML:
1259 content_type_string = "application/xml; charset=utf-8";
1262 case CT_APPLICATION_JSON:
1263 content_type_string = "application/json; charset=utf-8";
1266 case CT_APPLICATION_X_JAVASCRIPT:
1267 content_type_string = "application/x-javascript; charset=utf-8";
1271 content_type_string = "text/css; charset=utf-8";
1275 content_type_string = "text/xml; charset=utf-8";
1279 content_type_string = "text/xsl; charset=utf-8";
1282 case CT_APPLICATION_OCTET_STREAM:
1283 content_type_string = "application/octet-stream";
1286 case CT_IMAGE_SVG_XML:
1287 content_type_string = "image/svg+xml";
1290 case CT_APPLICATION_X_FONT_TRUETYPE:
1291 content_type_string = "application/x-font-truetype";
1294 case CT_APPLICATION_X_FONT_OPENTYPE:
1295 content_type_string = "application/x-font-opentype";
1298 case CT_APPLICATION_FONT_WOFF:
1299 content_type_string = "application/font-woff";
1302 case CT_APPLICATION_FONT_WOFF2:
1303 content_type_string = "application/font-woff2";
1306 case CT_APPLICATION_VND_MS_FONTOBJ:
1307 content_type_string = "application/vnd.ms-fontobject";
1311 content_type_string = "image/png";
1315 content_type_string = "image/jpeg";
1319 content_type_string = "image/gif";
1322 case CT_IMAGE_XICON:
1323 content_type_string = "image/x-icon";
1327 content_type_string = "image/bmp";
1331 content_type_string = "image/icns";
1336 content_type_string = "text/plain; charset=utf-8";
1347 code_msg = "Temporary Redirect";
1351 code_msg = "Bad Request";
1355 code_msg = "Forbidden";
1359 code_msg = "Not Found";
1363 code_msg = "Internal Server Error";
1368 struct tm tmbuf, *tm = gmtime_r(&w->response.data->date, &tmbuf);
1369 strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %Z", tm);
1371 buffer_sprintf(w->response.header_output,
1372 "HTTP/1.1 %d %s\r\n"
1373 "Connection: %s\r\n"
1374 "Server: NetData Embedded HTTP Server\r\n"
1375 "Content-Type: %s\r\n"
1376 "Access-Control-Allow-Origin: *\r\n"
1377 "Access-Control-Allow-Methods: GET, OPTIONS\r\n"
1378 "Access-Control-Allow-Headers: accept, x-requested-with\r\n"
1379 "Access-Control-Max-Age: 86400\r\n"
1382 , w->keepalive?"keep-alive":"close"
1383 , content_type_string
1387 if(buffer_strlen(w->response.header))
1388 buffer_strcat(w->response.header_output, buffer_tostring(w->response.header));
1390 if(w->mode == WEB_CLIENT_MODE_NORMAL && (w->response.data->options & WB_CONTENT_NO_CACHEABLE)) {
1391 buffer_sprintf(w->response.header_output,
1393 "Cache-Control: no-cache\r\n"
1398 time_t et = w->response.data->date + (86400 * 14);
1399 struct tm etmbuf, *etm = gmtime_r(&et, &etmbuf);
1400 strftime(edate, sizeof(edate), "%a, %d %b %Y %H:%M:%S %Z", etm);
1402 buffer_sprintf(w->response.header_output,
1404 "Cache-Control: public\r\n"
1408 // if we know the content length, put it
1409 if(!w->response.zoutput && (w->response.data->len || w->response.rlen))
1410 buffer_sprintf(w->response.header_output,
1411 "Content-Length: %ld\r\n"
1412 , w->response.data->len? w->response.data->len: w->response.rlen
1414 else if(!w->response.zoutput)
1415 w->keepalive = 0; // content-length is required for keep-alive
1417 if(w->response.zoutput) {
1418 buffer_strcat(w->response.header_output,
1419 "Content-Encoding: gzip\r\n"
1420 "Transfer-Encoding: chunked\r\n"
1424 buffer_strcat(w->response.header_output, "\r\n");
1426 // disable TCP_NODELAY, to buffer the header
1428 if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0)
1429 error("%llu: failed to disable TCP_NODELAY on socket.", w->id);
1431 // sent the HTTP header
1432 debug(D_WEB_DATA, "%llu: Sending response HTTP header of size %d: '%s'"
1434 , buffer_strlen(w->response.header_output)
1435 , buffer_tostring(w->response.header_output)
1438 bytes = send(w->ofd, buffer_tostring(w->response.header_output), buffer_strlen(w->response.header_output), 0);
1439 if(bytes != (ssize_t) buffer_strlen(w->response.header_output))
1440 error("%llu: HTTP Header failed to be sent (I sent %d bytes but the system sent %d bytes)."
1442 , buffer_strlen(w->response.header_output)
1445 global_statistics_lock();
1446 global_statistics.bytes_sent += bytes;
1447 global_statistics_unlock();
1450 // enable TCP_NODELAY, to send all data immediately at the next send()
1452 if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0) error("%llu: failed to enable TCP_NODELAY on socket.", w->id);
1454 // enable sending immediately if we have data
1455 if(w->response.data->len) w->wait_send = 1;
1456 else w->wait_send = 0;
1460 case WEB_CLIENT_MODE_OPTIONS:
1461 debug(D_WEB_CLIENT, "%llu: Done preparing the OPTIONS response. Sending data (%d bytes) to client.", w->id, w->response.data->len);
1464 case WEB_CLIENT_MODE_NORMAL:
1465 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Sending data (%d bytes) to client.", w->id, w->response.data->len);
1468 case WEB_CLIENT_MODE_FILECOPY:
1469 if(w->response.rlen) {
1470 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending data file of %d bytes to client.", w->id, w->response.rlen);
1471 w->wait_receive = 1;
1474 // utilize the kernel sendfile() for copying the file to the socket.
1475 // this block of code can be commented, without anything missing.
1476 // when it is commented, the program will copy the data using async I/O.
1478 long len = sendfile(w->ofd, w->ifd, NULL, w->response.data->rbytes);
1479 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);
1480 else web_client_reset(w);
1485 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending an unknown amount of bytes to client.", w->id);
1489 fatal("%llu: Unknown client mode %d.", w->id, w->mode);
1494 long web_client_send_chunk_header(struct web_client *w, long len)
1496 debug(D_DEFLATE, "%llu: OPEN CHUNK of %d bytes (hex: %x).", w->id, len, len);
1498 sprintf(buf, "%lX\r\n", len);
1499 ssize_t bytes = send(w->ofd, buf, strlen(buf), MSG_DONTWAIT);
1501 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk header %d bytes.", w->id, bytes);
1502 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk header to the client.", w->id);
1503 else debug(D_DEFLATE, "%llu: Failed to send chunk header to client.", w->id);
1508 long web_client_send_chunk_close(struct web_client *w)
1510 //debug(D_DEFLATE, "%llu: CLOSE CHUNK.", w->id);
1512 ssize_t bytes = send(w->ofd, "\r\n", 2, MSG_DONTWAIT);
1514 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
1515 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
1516 else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client.", w->id);
1521 long web_client_send_chunk_finalize(struct web_client *w)
1523 //debug(D_DEFLATE, "%llu: FINALIZE CHUNK.", w->id);
1525 ssize_t bytes = send(w->ofd, "\r\n0\r\n\r\n", 7, MSG_DONTWAIT);
1527 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
1528 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
1529 else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client.", w->id);
1534 #ifdef NETDATA_WITH_ZLIB
1535 long web_client_send_deflate(struct web_client *w)
1537 long len = 0, t = 0;
1539 // when using compression,
1540 // w->response.sent is the amount of bytes passed through compression
1542 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);
1544 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) {
1545 // there is nothing to send
1547 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1549 // finalize the chunk
1550 if(w->response.sent != 0)
1551 t += web_client_send_chunk_finalize(w);
1553 // there can be two cases for this
1554 // A. we have done everything
1555 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
1557 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->response.rlen && w->response.rlen > w->response.data->len) {
1558 // we have to wait, more data will come
1559 debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1564 if(w->keepalive == 0) {
1565 debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->response.sent);
1571 web_client_reset(w);
1572 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1576 if(w->response.zhave == w->response.zsent) {
1577 // compress more input data
1579 // close the previous open chunk
1580 if(w->response.sent != 0) t += web_client_send_chunk_close(w);
1582 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);
1584 // give the compressor all the data not passed through the compressor yet
1585 if(w->response.data->len > w->response.sent) {
1586 #ifdef NETDATA_INTERNAL_CHECKS
1587 if((long)w->response.sent - (long)w->response.zstream.avail_in < 0)
1588 error("internal error: avail_in is corrupted.");
1590 w->response.zstream.next_in = (Bytef *)&w->response.data->buffer[w->response.sent - w->response.zstream.avail_in];
1591 w->response.zstream.avail_in += (uInt) (w->response.data->len - w->response.sent);
1594 // reset the compressor output buffer
1595 w->response.zstream.next_out = w->response.zbuffer;
1596 w->response.zstream.avail_out = ZLIB_CHUNK;
1598 // ask for FINISH if we have all the input
1599 int flush = Z_SYNC_FLUSH;
1600 if(w->mode == WEB_CLIENT_MODE_NORMAL
1601 || (w->mode == WEB_CLIENT_MODE_FILECOPY && !w->wait_receive && w->response.data->len == w->response.rlen)) {
1603 debug(D_DEFLATE, "%llu: Requesting Z_FINISH, if possible.", w->id);
1606 debug(D_DEFLATE, "%llu: Requesting Z_SYNC_FLUSH.", w->id);
1610 if(deflate(&w->response.zstream, flush) == Z_STREAM_ERROR) {
1611 error("%llu: Compression failed. Closing down client.", w->id);
1612 web_client_reset(w);
1616 w->response.zhave = ZLIB_CHUNK - w->response.zstream.avail_out;
1617 w->response.zsent = 0;
1619 // keep track of the bytes passed through the compressor
1620 w->response.sent = w->response.data->len;
1622 debug(D_DEFLATE, "%llu: Compression produced %d bytes.", w->id, w->response.zhave);
1625 t += web_client_send_chunk_header(w, w->response.zhave);
1628 debug(D_WEB_CLIENT, "%llu: Sending %d bytes of data (+%d of chunk header).", w->id, w->response.zhave - w->response.zsent, t);
1630 len = send(w->ofd, &w->response.zbuffer[w->response.zsent], (size_t) (w->response.zhave - w->response.zsent), MSG_DONTWAIT);
1632 w->response.zsent += len;
1634 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, len);
1636 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);
1637 else debug(D_WEB_CLIENT, "%llu: Failed to send data to client. Reason: %s", w->id, strerror(errno));
1641 #endif // NETDATA_WITH_ZLIB
1643 long web_client_send(struct web_client *w)
1645 #ifdef NETDATA_WITH_ZLIB
1646 if(likely(w->response.zoutput)) return web_client_send_deflate(w);
1647 #endif // NETDATA_WITH_ZLIB
1651 if(unlikely(w->response.data->len - w->response.sent == 0)) {
1652 // there is nothing to send
1654 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1656 // there can be two cases for this
1657 // A. we have done everything
1658 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
1660 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->response.rlen && w->response.rlen > w->response.data->len) {
1661 // we have to wait, more data will come
1662 debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1667 if(unlikely(w->keepalive == 0)) {
1668 debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->response.sent);
1673 web_client_reset(w);
1674 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1678 bytes = send(w->ofd, &w->response.data->buffer[w->response.sent], w->response.data->len - w->response.sent, MSG_DONTWAIT);
1679 if(likely(bytes > 0)) {
1680 w->response.sent += bytes;
1681 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, bytes);
1683 else if(likely(bytes == 0)) debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client.", w->id);
1684 else debug(D_WEB_CLIENT, "%llu: Failed to send data to client.", w->id);
1689 long web_client_receive(struct web_client *w)
1691 // do we have any space for more data?
1692 buffer_need_bytes(w->response.data, WEB_REQUEST_LENGTH);
1694 long left = w->response.data->size - w->response.data->len;
1697 if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY))
1698 bytes = read(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1));
1700 bytes = recv(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1), MSG_DONTWAIT);
1702 if(likely(bytes > 0)) {
1703 size_t old = w->response.data->len;
1704 w->response.data->len += bytes;
1705 w->response.data->buffer[w->response.data->len] = '\0';
1707 debug(D_WEB_CLIENT, "%llu: Received %d bytes.", w->id, bytes);
1708 debug(D_WEB_DATA, "%llu: Received data: '%s'.", w->id, &w->response.data->buffer[old]);
1710 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1712 if(w->response.rlen && w->response.data->len >= w->response.rlen) w->wait_receive = 0;
1715 else if(likely(bytes == 0)) {
1716 debug(D_WEB_CLIENT, "%llu: Out of input data.", w->id);
1718 // if we cannot read, it means we have an error on input.
1719 // if however, we are copying a file from ifd to ofd, we should not return an error.
1720 // in this case, the error should be generated when the file has been sent to the client.
1722 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1723 // we are copying data from ifd to ofd
1724 // let it finish copying...
1725 w->wait_receive = 0;
1726 debug(D_WEB_CLIENT, "%llu: Disabling input.", w->id);
1738 // --------------------------------------------------------------------------------------
1739 // the thread of a single client
1741 // 1. waits for input and output, using async I/O
1742 // 2. it processes HTTP requests
1743 // 3. it generates HTTP responses
1744 // 4. it copies data from input to output if mode is FILECOPY
1746 void *web_client_main(void *ptr)
1748 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
1749 error("Cannot set pthread cancel type to DEFERRED.");
1751 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
1752 error("Cannot set pthread cancel state to ENABLE.");
1755 struct web_client *w = ptr;
1757 fd_set ifds, ofds, efds;
1760 log_access("%llu: %s port %s connected on thread task id %d", w->id, w->client_ip, w->client_port, gettid());
1767 FD_SET(w->ifd, &efds);
1769 if(w->ifd != w->ofd)
1770 FD_SET(w->ofd, &efds);
1772 if (w->wait_receive) {
1773 FD_SET(w->ifd, &ifds);
1774 if(w->ifd > fdmax) fdmax = w->ifd;
1778 FD_SET(w->ofd, &ofds);
1779 if(w->ofd > fdmax) fdmax = w->ofd;
1782 tv.tv_sec = web_client_timeout;
1785 debug(D_WEB_CLIENT, "%llu: Waiting socket async I/O for %s %s", w->id, w->wait_receive?"INPUT":"", w->wait_send?"OUTPUT":"");
1786 retval = select(fdmax+1, &ifds, &ofds, &efds, &tv);
1789 debug(D_WEB_CLIENT_ACCESS, "%llu: LISTENER: select() failed.", w->id);
1794 debug(D_WEB_CLIENT_ACCESS, "%llu: LISTENER: timeout.", w->id);
1798 if(FD_ISSET(w->ifd, &efds)) {
1799 debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on input socket.", w->id);
1803 if(FD_ISSET(w->ofd, &efds)) {
1804 debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on output socket.", w->id);
1808 if(w->wait_send && FD_ISSET(w->ofd, &ofds)) {
1810 if((bytes = web_client_send(w)) < 0) {
1811 debug(D_WEB_CLIENT, "%llu: Cannot send data to client. Closing client.", w->id);
1816 global_statistics_lock();
1817 global_statistics.bytes_sent += bytes;
1818 global_statistics_unlock();
1821 if(w->wait_receive && FD_ISSET(w->ifd, &ifds)) {
1823 if((bytes = web_client_receive(w)) < 0) {
1824 debug(D_WEB_CLIENT, "%llu: Cannot receive data from client. Closing client.", w->id);
1829 if(w->mode == WEB_CLIENT_MODE_NORMAL) {
1830 debug(D_WEB_CLIENT, "%llu: Attempting to process received data (%ld bytes).", w->id, bytes);
1831 // info("%llu: Attempting to process received data (%ld bytes).", w->id, bytes);
1832 web_client_process(w);
1835 global_statistics_lock();
1836 global_statistics.bytes_received += bytes;
1837 global_statistics_unlock();
1841 log_access("%llu: %s port %s disconnected from thread task id %d", w->id, w->client_ip, w->client_port, gettid());
1842 debug(D_WEB_CLIENT, "%llu: done...", w->id);
1844 web_client_reset(w);