]> arthur.barton.de Git - netdata.git/blobdiff - src/web_client.c
registry server side operational
[netdata.git] / src / web_client.c
old mode 100755 (executable)
new mode 100644 (file)
index e132261..c4199b5
@@ -14,6 +14,7 @@
 #include <netinet/tcp.h>
 #include <malloc.h>
 #include <pwd.h>
+#include <grp.h>
 #include <ctype.h>
 
 #include "common.h"
 #include "global_statistics.h"
 #include "rrd.h"
 #include "rrd2json.h"
+#include "registry.h"
 
 #include "web_client.h"
+#include "../config.h"
 
 #define INITIAL_WEB_DATA_LENGTH 16384
 #define WEB_REQUEST_LENGTH 16384
+#define TOO_BIG_REQUEST 16384
 
 int web_client_timeout = DEFAULT_DISCONNECT_IDLE_WEB_CLIENTS_AFTER_SECONDS;
 int web_enable_gzip = 1;
@@ -156,7 +160,7 @@ void web_client_reset(struct web_client *w)
                        (float)usecdiff(&w->tv_ready, &w->tv_in) / 1000.0,
                        (float)usecdiff(&tv, &w->tv_ready) / 1000.0,
                        (float)usecdiff(&tv, &w->tv_in) / 1000.0,
-                       (w->mode == WEB_CLIENT_MODE_FILECOPY)?"filecopy":"data",
+                       (w->mode == WEB_CLIENT_MODE_FILECOPY)?"filecopy":((w->mode == WEB_CLIENT_MODE_OPTIONS)?"options":"data"),
                        w->response.code,
                        w->last_url
                );
@@ -170,6 +174,7 @@ void web_client_reset(struct web_client *w)
        }
 
        w->last_url[0] = '\0';
+       w->cookie[0] = '\0';
 
        w->mode = WEB_CLIENT_MODE_NORMAL;
 
@@ -230,13 +235,16 @@ uid_t web_files_uid(void)
        static uid_t owner_uid = 0;
 
        if(unlikely(!web_owner)) {
-               web_owner = config_get("global", "web files owner", NETDATA_USER);
+               web_owner = config_get("global", "web files owner", config_get("global", "run as user", ""));
                if(!web_owner || !*web_owner)
                        owner_uid = geteuid();
                else {
+                       // getpwnam() is not thread safe,
+                       // but we have called this function once
+                       // while single threaded
                        struct passwd *pw = getpwnam(web_owner);
                        if(!pw) {
-                               error("User %s is not present. Ignoring option. Error: %s\n", web_owner, strerror(errno));
+                               error("User %s is not present. Ignoring option.", web_owner);
                                owner_uid = geteuid();
                        }
                        else {
@@ -249,6 +257,34 @@ uid_t web_files_uid(void)
        return(owner_uid);
 }
 
+gid_t web_files_gid(void)
+{
+       static char *web_group = NULL;
+       static gid_t owner_gid = 0;
+
+       if(unlikely(!web_group)) {
+               web_group = config_get("global", "web files group", config_get("global", "web files owner", ""));
+               if(!web_group || !*web_group)
+                       owner_gid = getegid();
+               else {
+                       // getgrnam() is not thread safe,
+                       // but we have called this function once
+                       // while single threaded
+                       struct group *gr = getgrnam(web_group);
+                       if(!gr) {
+                               error("Group %s is not present. Ignoring option.", web_group);
+                               owner_gid = getegid();
+                       }
+                       else {
+                               debug(D_WEB_CLIENT, "Web files group set to %s.\n", web_group);
+                               owner_gid = gr->gr_gid;
+                       }
+               }
+       }
+
+       return(owner_gid);
+}
+
 int mysendfile(struct web_client *w, char *filename)
 {
        static char *web_dir = NULL;
@@ -268,7 +304,7 @@ int mysendfile(struct web_client *w, char *filename)
        for(s = filename; *s ;s++) {
                if( !isalnum(*s) && *s != '/' && *s != '.' && *s != '-' && *s != '_') {
                        debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
-                       buffer_sprintf(w->response.data, "File '%s' cannot be served. Filename contains invalid character '%c'", *s);
+                       buffer_sprintf(w->response.data, "File '%s' cannot be served. Filename contains invalid character '%c'", filename, *s);
                        return 400;
                }
        }
@@ -288,14 +324,21 @@ int mysendfile(struct web_client *w, char *filename)
        struct stat stat;
        if(lstat(webfilename, &stat) != 0) {
                debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not found.", w->id, webfilename);
-               buffer_sprintf(w->response.data, "File '%s' does not exist, or is not accessible.", filename);
+               buffer_sprintf(w->response.data, "File '%s' does not exist, or is not accessible.", webfilename);
                return 404;
        }
 
-       // check if the file is owned by us
+       // check if the file is owned by expected user
        if(stat.st_uid != web_files_uid()) {
-               debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is owned by user %d (I run as user %d). Access Denied.", w->id, webfilename, stat.st_uid, getuid());
-               buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", filename);
+               error("%llu: File '%s' is owned by user %d (expected user %d). Access Denied.", w->id, webfilename, stat.st_uid, web_files_uid());
+               buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", webfilename);
+               return 403;
+       }
+
+       // check if the file is owned by expected group
+       if(stat.st_gid != web_files_gid()) {
+               error("%llu: File '%s' is owned by group %d (expected group %d). Access Denied.", w->id, webfilename, stat.st_gid, web_files_gid());
+               buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", webfilename);
                return 403;
        }
 
@@ -305,8 +348,8 @@ int mysendfile(struct web_client *w, char *filename)
        }
 
        if((stat.st_mode & S_IFMT) != S_IFREG) {
-               debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not a regular file. Access Denied.", w->id, webfilename);
-               buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", filename);
+               error("%llu: File '%s' is not a regular file. Access Denied.", w->id, webfilename);
+               buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", webfilename);
                return 403;
        }
 
@@ -318,12 +361,12 @@ int mysendfile(struct web_client *w, char *filename)
                if(errno == EBUSY || errno == EAGAIN) {
                        error("%llu: File '%s' is busy, sending 307 Moved Temporarily to force retry.", w->id, webfilename);
                        buffer_sprintf(w->response.header, "Location: /" WEB_PATH_FILE "/%s\r\n", filename);
-                       buffer_sprintf(w->response.data, "The file '%s' is currently busy. Please try again later.", filename);
+                       buffer_sprintf(w->response.data, "The file '%s' is currently busy. Please try again later.", webfilename);
                        return 307;
                }
                else {
                        error("%llu: Cannot open file '%s'.", w->id, webfilename);
-                       buffer_sprintf(w->response.data, "Cannot open file '%s'.", filename);
+                       buffer_sprintf(w->response.data, "Cannot open file '%s'.", webfilename);
                        return 404;
                }
        }
@@ -338,8 +381,16 @@ int mysendfile(struct web_client *w, char *filename)
        else if(strstr(filename, ".svg")  != NULL)  w->response.data->contenttype = CT_IMAGE_SVG_XML;
        else if(strstr(filename, ".ttf")  != NULL)  w->response.data->contenttype = CT_APPLICATION_X_FONT_TRUETYPE;
        else if(strstr(filename, ".otf")  != NULL)  w->response.data->contenttype = CT_APPLICATION_X_FONT_OPENTYPE;
+       else if(strstr(filename, ".woff2")!= NULL)  w->response.data->contenttype = CT_APPLICATION_FONT_WOFF2;
        else if(strstr(filename, ".woff") != NULL)  w->response.data->contenttype = CT_APPLICATION_FONT_WOFF;
        else if(strstr(filename, ".eot")  != NULL)  w->response.data->contenttype = CT_APPLICATION_VND_MS_FONTOBJ;
+       else if(strstr(filename, ".png")  != NULL)  w->response.data->contenttype = CT_IMAGE_PNG;
+       else if(strstr(filename, ".jpg")  != NULL)  w->response.data->contenttype = CT_IMAGE_JPG;
+       else if(strstr(filename, ".jpeg") != NULL)  w->response.data->contenttype = CT_IMAGE_JPG;
+       else if(strstr(filename, ".gif")  != NULL)  w->response.data->contenttype = CT_IMAGE_GIF;
+       else if(strstr(filename, ".bmp")  != NULL)  w->response.data->contenttype = CT_IMAGE_BMP;
+       else if(strstr(filename, ".ico")  != NULL)  w->response.data->contenttype = CT_IMAGE_XICON;
+       else if(strstr(filename, ".icns") != NULL)  w->response.data->contenttype = CT_IMAGE_ICNS;
        else w->response.data->contenttype = CT_APPLICATION_OCTET_STREAM;
 
        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);
@@ -430,12 +481,14 @@ uint32_t web_client_api_request_v1_data_options(char *o)
                        ret |= RRDR_OPTION_OBJECTSROWS;
                else if(!strcmp(tok, "google_json"))
                        ret |= RRDR_OPTION_GOOGLE_JSON;
+               else if(!strcmp(tok, "percentage"))
+                       ret |= RRDR_OPTION_PERCENTAGE;
        }
 
        return ret;
 }
 
-int web_client_api_request_v1_data_format(char *name)
+uint32_t web_client_api_request_v1_data_format(char *name)
 {
        if(!strcmp(name, DATASOURCE_FORMAT_DATATABLE_JSON)) // datatable
                return DATASOURCE_DATATABLE_JSON;
@@ -467,10 +520,13 @@ int web_client_api_request_v1_data_format(char *name)
        else if(!strcmp(name, DATASOURCE_FORMAT_SSV_COMMA)) // ssvcomma
                return DATASOURCE_SSV_COMMA;
 
+       else if(!strcmp(name, DATASOURCE_FORMAT_CSV_JSON_ARRAY)) // csvjsonarray
+               return DATASOURCE_CSV_JSON_ARRAY;
+
        return DATASOURCE_JSON;
 }
 
-int web_client_api_request_v1_data_google_format(char *name)
+uint32_t web_client_api_request_v1_data_google_format(char *name)
 {
        if(!strcmp(name, "json"))
                return DATASOURCE_DATATABLE_JSONP;
@@ -527,10 +583,10 @@ int web_client_api_request_v1_chart(struct web_client *w, char *url)
                // they are not null and not empty
 
                if(!strcmp(name, "chart")) chart = value;
-               else {
-                       buffer_sprintf(w->response.data, "Unknown parameter '%s' in request.", name);
-                       goto cleanup;
-               }
+               //else {
+               ///     buffer_sprintf(w->response.data, "Unknown parameter '%s' in request.", name);
+               //      goto cleanup;
+               //}
        }
 
        if(!chart || !*chart) {
@@ -568,8 +624,8 @@ int web_client_api_request_v1_data(struct web_client *w, char *url)
                        *google_reqId = "0",
                        *google_sig = "0",
                        *google_out = "json",
-                       *google_responseHandler = "google.visualization.Query.setResponse",
-                       *google_outFileName = NULL;
+                       *responseHandler = NULL,
+                       *outFileName = NULL;
 
        time_t last_timestamp_in_data = 0, google_timestamp = 0;
 
@@ -578,7 +634,8 @@ int web_client_api_request_v1_data(struct web_client *w, char *url)
                        , *after_str = NULL
                        , *points_str = NULL;
 
-       int format = DATASOURCE_JSON, group = GROUP_MAX;
+       int group = GROUP_MAX;
+       uint32_t format = DATASOURCE_JSON;
        uint32_t options = 0x00000000;
 
        while(url) {
@@ -589,7 +646,7 @@ int web_client_api_request_v1_data(struct web_client *w, char *url)
                if(!name || !*name) continue;
                if(!value || !*value) continue;
 
-               debug(D_WEB_CLIENT, "%llu: API v1 query param '%s' with value '%s'", w->id, name, value);
+               debug(D_WEB_CLIENT, "%llu: API v1 data query param '%s' with value '%s'", w->id, name, value);
 
                // name and value are now the parameters
                // they are not null and not empty
@@ -614,6 +671,12 @@ int web_client_api_request_v1_data(struct web_client *w, char *url)
                else if(!strcmp(name, "options")) {
                        options |= web_client_api_request_v1_data_options(value);
                }
+               else if(!strcmp(name, "callback")) {
+                       responseHandler = value;
+               }
+               else if(!strcmp(name, "filename")) {
+                       outFileName = value;
+               }
                else if(!strcmp(name, "tqx")) {
                        // parse Google Visualization API options
                        // https://developers.google.com/chart/interactive/docs/dev/implementing_data_source
@@ -640,9 +703,9 @@ int web_client_api_request_v1_data(struct web_client *w, char *url)
                                        format = web_client_api_request_v1_data_google_format(google_out);
                                }
                                else if(!strcmp(tqx_name, "responseHandler"))
-                                       google_responseHandler = tqx_value;
+                                       responseHandler = tqx_value;
                                else if(!strcmp(tqx_name, "outFileName"))
-                                       google_outFileName = tqx_value;
+                                       outFileName = tqx_value;
                        }
                }
        }
@@ -676,19 +739,29 @@ int web_client_api_request_v1_data(struct web_client *w, char *url)
                        , options
                        );
 
-       if(google_outFileName && *google_outFileName) {
-               buffer_sprintf(w->response.header, "Content-Disposition: attachment; filename=\"%s\"\r\n", google_outFileName);
-               error("generating outfilename header: '%s'", google_outFileName);
+       if(outFileName && *outFileName) {
+               buffer_sprintf(w->response.header, "Content-Disposition: attachment; filename=\"%s\"\r\n", outFileName);
+               error("generating outfilename header: '%s'", outFileName);
        }
 
        if(format == DATASOURCE_DATATABLE_JSONP) {
+               if(responseHandler == NULL)
+                       responseHandler = "google.visualization.Query.setResponse";
+
                debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSON/JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
-                               w->id, google_version, google_reqId, google_sig, google_out, google_responseHandler, google_outFileName
+                               w->id, google_version, google_reqId, google_sig, google_out, responseHandler, outFileName
                        );
 
                buffer_sprintf(w->response.data,
                        "%s({version:'%s',reqId:'%s',status:'ok',sig:'%lu',table:",
-                       google_responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
+                       responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
+       }
+       else if(format == DATASOURCE_JSONP) {
+               if(responseHandler == NULL)
+                       responseHandler = "callback";
+
+               buffer_strcat(w->response.data, responseHandler);
+               buffer_strcat(w->response.data, "(");
        }
 
        ret = rrd2format(st, w->response.data, dimensions, format, points, after, before, group, options, &last_timestamp_in_data);
@@ -702,49 +775,160 @@ int web_client_api_request_v1_data(struct web_client *w, char *url)
                        buffer_flush(w->response.data);
                        buffer_sprintf(w->response.data,
                                "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
-                               google_responseHandler, google_version, google_reqId);
+                               responseHandler, google_version, google_reqId);
                }
        }
+       else if(format == DATASOURCE_JSONP)
+               buffer_strcat(w->response.data, ");");
 
 cleanup:
        if(dimensions) buffer_free(dimensions);
        return ret;
 }
 
+int web_client_api_request_v1_registry(struct web_client *w, char *url)
+{
+       char person_guid[36 + 1] = "";
+
+       debug(D_WEB_CLIENT, "%llu: API v1 registry with URL '%s'", w->id, url);
+
+       char *cookie = strstr(w->response.data->buffer, " " NETDATA_REGISTRY_COOKIE_NAME "=");
+       if(cookie) {
+               strncpy(person_guid, &cookie[sizeof(NETDATA_REGISTRY_COOKIE_NAME) + 1], 36);
+               person_guid[36] = '\0';
+       }
+
+       char action = '\0';
+       char *machine_guid = NULL,
+                       *machine_url = NULL,
+                       *url_name = NULL,
+                       *search_machine_guid = NULL,
+                       *delete_url = NULL;
+
+       while(url) {
+               char *value = mystrsep(&url, "?&[]");
+               if (!value || !*value) continue;
+
+               char *name = mystrsep(&value, "=");
+               if (!name || !*name) continue;
+               if (!value || !*value) continue;
+
+               debug(D_WEB_CLIENT, "%llu: API v1 registry query param '%s' with value '%s'", w->id, name, value);
+
+               if(!strcmp(name, "action")) {
+                       if(!strcmp(value, "access")) action = 'A';
+                       else if(!strcmp(value, "delete")) action = 'D';
+                       else if(!strcmp(value, "search")) action = 'S';
+               }
+               else if(!strcmp(name, "machine"))
+                       machine_guid = value;
+
+               else if(!strcmp(name, "url"))
+                       machine_url = value;
+
+               else if(action == 'A') {
+                       if(!strcmp(name, "name"))
+                               url_name = value;
+               }
+               else if(action == 'D') {
+                       if(!strcmp(name, "delete_url"))
+                               delete_url = value;
+               }
+               else if(action == 'S') {
+                       if(!strcmp(name, "for"))
+                               search_machine_guid = value;
+               }
+       }
+
+       if((!action || !machine_guid || !machine_url) || (action == 'A' && !url_name) || (action == 'D' && !delete_url) || (action == 'S' && !search_machine_guid)) {
+               buffer_flush(w->response.data);
+               buffer_sprintf(w->response.data, "Invalid registry request - required parameters missing.");
+               return 400;
+       }
+
+       switch(action) {
+               case 'A':
+                       return registry_request_access_json(w, person_guid, machine_guid, machine_url, url_name, time(NULL));
+
+               case 'D':
+                       return registry_request_delete_json(w, person_guid, machine_guid, machine_url, delete_url, time(NULL));
+
+               case 'S':
+                       return registry_request_search_json(w, person_guid, machine_guid, machine_url, search_machine_guid, time(NULL));
+       }
+
+       buffer_flush(w->response.data);
+       buffer_sprintf(w->response.data, "Invalid or no registry action.");
+       return 400;
+}
+
 int web_client_api_request_v1(struct web_client *w, char *url)
 {
+       static uint32_t data_hash = 0, chart_hash = 0, charts_hash = 0, registry_hash = 0;
+
+       if(unlikely(data_hash == 0)) {
+               data_hash = simple_hash("data");
+               chart_hash = simple_hash("chart");
+               charts_hash = simple_hash("charts");
+               registry_hash = simple_hash("registry");
+       }
+
        // get the command
        char *tok = mystrsep(&url, "/?&");
-       debug(D_WEB_CLIENT, "%llu: Searching for API v1 command '%s'.", w->id, tok);
+       if(tok && *tok) {
+               debug(D_WEB_CLIENT, "%llu: Searching for API v1 command '%s'.", w->id, tok);
+               uint32_t hash = simple_hash(tok);
 
-       if(strcmp(tok, "data") == 0)
-               return web_client_api_request_v1_data(w, url);
-       else if(strcmp(tok, "chart") == 0)
-               return web_client_api_request_v1_chart(w, url);
-       else if(strcmp(tok, "charts") == 0)
-               return web_client_api_request_v1_charts(w, url);
+               if(hash == data_hash && !strcmp(tok, "data"))
+                       return web_client_api_request_v1_data(w, url);
 
-       buffer_flush(w->response.data);
-       buffer_sprintf(w->response.data, "Unsupported v1 API command: %s", tok);
-       return 404;
+               else if(hash == chart_hash && !strcmp(tok, "chart"))
+                       return web_client_api_request_v1_chart(w, url);
+
+               else if(hash == charts_hash && !strcmp(tok, "charts"))
+                       return web_client_api_request_v1_charts(w, url);
+
+               else if(hash == registry_hash && !strcmp(tok, "registry"))
+                       return web_client_api_request_v1_registry(w, url);
+
+               else {
+                       buffer_flush(w->response.data);
+                       buffer_sprintf(w->response.data, "Unsupported v1 API command: %s", tok);
+                       return 404;
+               }
+       }
+       else {
+               buffer_flush(w->response.data);
+               buffer_sprintf(w->response.data, "API v1 command?");
+               return 400;
+       }
 }
 
 int web_client_api_request(struct web_client *w, char *url)
 {
        // get the api version
        char *tok = mystrsep(&url, "/?&");
-       debug(D_WEB_CLIENT, "%llu: Searching for API version '%s'.", w->id, tok);
-
-       if(strcmp(tok, "v1") == 0)
-               return web_client_api_request_v1(w, url);
-
-       buffer_flush(w->response.data);
-       buffer_sprintf(w->response.data, "Unsupported API version: %s", tok);
-       return 404;
+       if(tok && *tok) {
+               debug(D_WEB_CLIENT, "%llu: Searching for API version '%s'.", w->id, tok);
+               if(strcmp(tok, "v1") == 0)
+                       return web_client_api_request_v1(w, url);
+               else {
+                       buffer_flush(w->response.data);
+                       buffer_sprintf(w->response.data, "Unsupported API version: %s", tok);
+                       return 404;
+               }
+       }
+       else {
+               buffer_flush(w->response.data);
+               buffer_sprintf(w->response.data, "Which API version?");
+               return 400;
+       }
 }
 
 int web_client_data_request(struct web_client *w, char *url, int datasource_type)
 {
+       RRDSET *st = NULL;
+
        char *args = strchr(url, '?');
        if(args) {
                *args='\0';
@@ -753,11 +937,14 @@ int web_client_data_request(struct web_client *w, char *url, int datasource_type
 
        // get the name of the data to show
        char *tok = mystrsep(&url, "/");
-       debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
 
        // do we have such a data set?
-       RRDSET *st = rrdset_find_byname(tok);
-       if(!st) st = rrdset_find(tok);
+       if(tok && *tok) {
+               debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
+               st = rrdset_find_byname(tok);
+               if(!st) st = rrdset_find(tok);
+       }
+
        if(!st) {
                // we don't have it
                // try to send a file with that name
@@ -784,34 +971,36 @@ int web_client_data_request(struct web_client *w, char *url, int datasource_type
        if(url) {
                // parse the group count required
                tok = mystrsep(&url, "/");
-               if(tok) group_count = atoi(tok);
+               if(tok && *tok) group_count = atoi(tok);
                if(group_count < 1) group_count = 1;
                //if(group_count > save_history / 20) group_count = save_history / 20;
        }
        if(url) {
                // parse the grouping method required
                tok = mystrsep(&url, "/");
-               if(strcmp(tok, "max") == 0) group_method = GROUP_MAX;
-               else if(strcmp(tok, "average") == 0) group_method = GROUP_AVERAGE;
-               else if(strcmp(tok, "sum") == 0) group_method = GROUP_SUM;
-               else debug(D_WEB_CLIENT, "%llu: Unknown group method '%s'", w->id, tok);
+               if(tok && *tok) {
+                       if(strcmp(tok, "max") == 0) group_method = GROUP_MAX;
+                       else if(strcmp(tok, "average") == 0) group_method = GROUP_AVERAGE;
+                       else if(strcmp(tok, "sum") == 0) group_method = GROUP_SUM;
+                       else debug(D_WEB_CLIENT, "%llu: Unknown group method '%s'", w->id, tok);
+               }
        }
        if(url) {
                // parse after time
                tok = mystrsep(&url, "/");
-               if(tok) after = strtoul(tok, NULL, 10);
+               if(tok && *tok) after = strtoul(tok, NULL, 10);
                if(after < 0) after = 0;
        }
        if(url) {
                // parse before time
                tok = mystrsep(&url, "/");
-               if(tok) before = strtoul(tok, NULL, 10);
+               if(tok && *tok) before = strtoul(tok, NULL, 10);
                if(before < 0) before = 0;
        }
        if(url) {
                // parse nonzero
                tok = mystrsep(&url, "/");
-               if(tok && strcmp(tok, "nonzero") == 0) nonzero = 1;
+               if(tok && *tok && strcmp(tok, "nonzero") == 0) nonzero = 1;
        }
 
        w->response.data->contenttype = CT_APPLICATION_JSON;
@@ -823,16 +1012,16 @@ int web_client_data_request(struct web_client *w, char *url, int datasource_type
        char *google_out = "json";
        char *google_responseHandler = "google.visualization.Query.setResponse";
        char *google_outFileName = NULL;
-       unsigned long last_timestamp_in_data = 0;
+       time_t last_timestamp_in_data = 0;
        if(datasource_type == DATASOURCE_DATATABLE_JSON || datasource_type == DATASOURCE_DATATABLE_JSONP) {
 
                w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
 
                while(args) {
                        tok = mystrsep(&args, "&");
-                       if(tok) {
+                       if(tok && *tok) {
                                char *name = mystrsep(&tok, "=");
-                               if(name && strcmp(name, "tqx") == 0) {
+                               if(name && *name && strcmp(name, "tqx") == 0) {
                                        char *key = mystrsep(&tok, ":");
                                        char *value = mystrsep(&tok, ";");
                                        if(key && value && *key && *value) {
@@ -882,7 +1071,7 @@ int web_client_data_request(struct web_client *w, char *url, int datasource_type
        }
 
        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);
-       unsigned long timestamp_in_data = rrd_stats_json(datasource_type, st, w->response.data, lines, group_count, group_method, after, before, nonzero);
+       time_t timestamp_in_data = rrd_stats_json(datasource_type, st, w->response.data, lines, group_count, group_method, after, before, nonzero);
 
        if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
                if(timestamp_in_data > last_timestamp_in_data)
@@ -948,9 +1137,36 @@ cleanup:
 }
 */
 
+// get the request buffer, just after the GET or OPTIONS
+// and find the url to be decoded, decode it and return
+// a newly allocated buffer with it
+static inline char *find_url_and_decode_it(char *request) {
+       char *e = request, *url = NULL;
+
+       // find the SPACE + "HTTP/"
+       while(*e) {
+               // find the space
+               while (*e && *e != ' ') e++;
+
+               // is it SPACE + "HTTP/" ?
+               if(*e && !strncmp(e, " HTTP/", 6))
+                       break;
+       }
+
+       if(*e) {
+               // we have the end
+               *e = '\0';
+               url = url_decode(request);
+               *e = ' ';
+       }
+
+       return url;
+}
+
 void web_client_process(struct web_client *w) {
        int code = 500;
-       int bytes;
+       ssize_t bytes;
+       int enable_gzip = 0;
 
        w->wait_receive = 0;
 
@@ -970,147 +1186,189 @@ void web_client_process(struct web_client *w) {
 #ifdef NETDATA_WITH_ZLIB
                // check if the client accepts deflate
                if(web_enable_gzip && strstr(w->response.data->buffer, "gzip"))
-                       web_client_enable_deflate(w);
+                       enable_gzip = 1;
 #endif // NETDATA_WITH_ZLIB
 
-               int datasource_type = DATASOURCE_DATATABLE_JSONP;
-               //if(strstr(w->response.data->buffer, "X-DataSource-Auth"))
-               //      datasource_type = DATASOURCE_GOOGLE_JSON;
+               w->mode = WEB_CLIENT_MODE_NORMAL;
 
-               char *buf = (char *)buffer_tostring(w->response.data);
-               char *tok = strsep(&buf, " \r\n");
-               char *url = NULL;
+               char *tok = (char *)buffer_tostring(w->response.data);
+               char *url = NULL, *encoded_url = NULL;
                char *pointer_to_free = NULL; // keep url_decode() allocated buffer
 
-               if(buf && strcmp(tok, "GET") == 0) {
-                       tok = strsep(&buf, " \r\n");
-                       pointer_to_free = url = url_decode(tok);
-                       debug(D_WEB_CLIENT, "%llu: Processing HTTP GET on url '%s'.", w->id, url);
+               if(!strncmp(tok, "GET ", 4))
+                       encoded_url = &tok[4];
+               else if(!strncmp(tok, "OPTIONS ", 8)) {
+                       encoded_url = &tok[8];
+                       w->mode = WEB_CLIENT_MODE_OPTIONS;
                }
-               else if (buf && strcmp(tok, "POST") == 0) {
-                       w->keepalive = 0;
-                       tok = strsep(&buf, " \r\n");
-                       pointer_to_free = url = url_decode(tok);
 
-                       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);
+               if(encoded_url) {
+                       pointer_to_free = url = find_url_and_decode_it(encoded_url);
+
+                       if(url) debug(D_WEB_CLIENT, "%llu: Processing url '%s'.", w->id, url);
+                       else debug(D_WEB_CLIENT, "%llu: Cannot find a valid URL in '%s'", w->id, encoded_url);
                }
 
                w->last_url[0] = '\0';
-               if(url) {
+
+               if(w->mode == WEB_CLIENT_MODE_OPTIONS) {
                        strncpy(w->last_url, url, URL_MAX);
                        w->last_url[URL_MAX] = '\0';
 
-                       tok = mystrsep(&url, "/?");
+                       code = 200;
+                       w->response.data->contenttype = CT_TEXT_PLAIN;
+                       buffer_flush(w->response.data);
+                       buffer_strcat(w->response.data, "OK");
+               }
+               else if(url) {
+#ifdef NETDATA_WITH_ZLIB
+                       if(enable_gzip)
+                               web_client_enable_deflate(w);
+#endif
 
-                       debug(D_WEB_CLIENT, "%llu: Processing command '%s'.", w->id, tok);
+                       strncpy(w->last_url, url, URL_MAX);
+                       w->last_url[URL_MAX] = '\0';
 
-                       if(strcmp(tok, "api") == 0) {
-                               // the client is requesting api access
-                               datasource_type = DATASOURCE_JSON;
-                               code = web_client_api_request(w, url);
-                       }
-#ifdef WEB_EXIT
-                       else if(strcmp(tok, "exit") == 0) {
-                               netdata_exit = 1;
-                               code = 200;
-                               w->response.data->contenttype = CT_TEXT_PLAIN;
-                               buffer_flush(w->response.data);
-                               buffer_strcat(w->response.data, "will do");
-                       }
-#endif
-                       else if(strcmp(tok, WEB_PATH_DATA) == 0) { // "data"
-                               // the client is requesting rrd data
-                               datasource_type = DATASOURCE_JSON;
-                               code = web_client_data_request(w, url, datasource_type);
-                       }
-                       else if(strcmp(tok, WEB_PATH_DATASOURCE) == 0) { // "datasource"
-                               // the client is requesting google datasource
-                               code = web_client_data_request(w, url, datasource_type);
-                       }
-                       else if(strcmp(tok, WEB_PATH_GRAPH) == 0) { // "graph"
-                               // the client is requesting an rrd graph
-
-                               // get the name of the data to show
-                               tok = mystrsep(&url, "/?&");
-                               debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
-
-                               // do we have such a data set?
-                               RRDSET *st = rrdset_find_byname(tok);
-                               if(!st) st = rrdset_find(tok);
-                               if(!st) {
-                                       // we don't have it
-                                       // try to send a file with that name
-                                       buffer_flush(w->response.data);
-                                       code = mysendfile(w, tok);
+                       tok = mystrsep(&url, "/?");
+                       if(tok && *tok) {
+                               debug(D_WEB_CLIENT, "%llu: Processing command '%s'.", w->id, tok);
+
+                               if(strcmp(tok, "api") == 0) {
+                                       // the client is requesting api access
+                                       code = web_client_api_request(w, url);
                                }
-                               else {
+#ifdef NETDATA_INTERNAL_CHECKS
+                               else if(strcmp(tok, "exit") == 0) {
                                        code = 200;
-                                       debug(D_WEB_CLIENT_ACCESS, "%llu: Sending %s.json of RRD_STATS...", w->id, st->name);
-                                       w->response.data->contenttype = CT_APPLICATION_JSON;
+                                       w->response.data->contenttype = CT_TEXT_PLAIN;
                                        buffer_flush(w->response.data);
-                                       rrd_stats_graph_json(st, url, w->response.data);
+
+                                       if(!netdata_exit)
+                                               buffer_strcat(w->response.data, "ok, will do...");
+                                       else
+                                               buffer_strcat(w->response.data, "I am doing it already");
+
+                                       netdata_exit = 1;
                                }
-                       }
-                       else if(strcmp(tok, "debug") == 0) {
-                               buffer_flush(w->response.data);
+#endif
+                               else if(strcmp(tok, WEB_PATH_DATA) == 0) { // "data"
+                                       // the client is requesting rrd data
+                                       code = web_client_data_request(w, url, DATASOURCE_JSON);
+                               }
+                               else if(strcmp(tok, WEB_PATH_DATASOURCE) == 0) { // "datasource"
+                                       // the client is requesting google datasource
+                                       code = web_client_data_request(w, url, DATASOURCE_DATATABLE_JSONP);
+                               }
+                               else if(strcmp(tok, WEB_PATH_GRAPH) == 0) { // "graph"
+                                       // the client is requesting an rrd graph
+
+                                       // get the name of the data to show
+                                       tok = mystrsep(&url, "/?&");
+                                       if(tok && *tok) {
+                                               debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
+
+                                               // do we have such a data set?
+                                               RRDSET *st = rrdset_find_byname(tok);
+                                               if(!st) st = rrdset_find(tok);
+                                               if(!st) {
+                                                       // we don't have it
+                                                       // try to send a file with that name
+                                                       buffer_flush(w->response.data);
+                                                       code = mysendfile(w, tok);
+                                               }
+                                               else {
+                                                       code = 200;
+                                                       debug(D_WEB_CLIENT_ACCESS, "%llu: Sending %s.json of RRD_STATS...", w->id, st->name);
+                                                       w->response.data->contenttype = CT_APPLICATION_JSON;
+                                                       buffer_flush(w->response.data);
+                                                       rrd_stats_graph_json(st, url, w->response.data);
+                                               }
+                                       }
+                                       else {
+                                               code = 400;
+                                               buffer_flush(w->response.data);
+                                               buffer_strcat(w->response.data, "Graph name?\r\n");
+                                       }
+                               }
+#ifdef NETDATA_INTERNAL_CHECKS
+                               else if(strcmp(tok, "debug") == 0) {
+                                       buffer_flush(w->response.data);
 
-                               // get the name of the data to show
-                               tok = mystrsep(&url, "/?&");
-                               debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
-
-                               // do we have such a data set?
-                               RRDSET *st = rrdset_find_byname(tok);
-                               if(!st) st = rrdset_find(tok);
-                               if(!st) {
-                                       code = 404;
-                                       buffer_sprintf(w->response.data, "Chart %s is not found.\r\n", tok);
-                                       debug(D_WEB_CLIENT_ACCESS, "%llu: %s is not found.", w->id, tok);
+                                       // get the name of the data to show
+                                       tok = mystrsep(&url, "/?&");
+                                       if(tok && *tok) {
+                                               debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
+
+                                               // do we have such a data set?
+                                               RRDSET *st = rrdset_find_byname(tok);
+                                               if(!st) st = rrdset_find(tok);
+                                               if(!st) {
+                                                       code = 404;
+                                                       buffer_sprintf(w->response.data, "Chart %s is not found.\r\n", tok);
+                                                       debug(D_WEB_CLIENT_ACCESS, "%llu: %s is not found.", w->id, tok);
+                                               }
+                                               else {
+                                                       code = 200;
+                                                       debug_flags |= D_RRD_STATS;
+                                                       st->debug = st->debug?0:1;
+                                                       buffer_sprintf(w->response.data, "Chart %s has now debug %s.\r\n", tok, st->debug?"enabled":"disabled");
+                                                       debug(D_WEB_CLIENT_ACCESS, "%llu: debug for %s is %s.", w->id, tok, st->debug?"enabled":"disabled");
+                                               }
+                                       }
+                                       else {
+                                               code = 500;
+                                               buffer_flush(w->response.data);
+                                               buffer_strcat(w->response.data, "debug which chart?\r\n");
+                                       }
                                }
-                               else {
+                               else if(strcmp(tok, "mirror") == 0) {
                                        code = 200;
-                                       debug_flags |= D_RRD_STATS;
-                                       st->debug = st->debug?0:1;
-                                       buffer_sprintf(w->response.data, "Chart %s has now debug %s.\r\n", tok, st->debug?"enabled":"disabled");
-                                       debug(D_WEB_CLIENT_ACCESS, "%llu: debug for %s is %s.", w->id, tok, st->debug?"enabled":"disabled");
-                               }
-                       }
-                       else if(strcmp(tok, "mirror") == 0) {
-                               code = 200;
 
-                               debug(D_WEB_CLIENT_ACCESS, "%llu: Mirroring...", w->id);
+                                       debug(D_WEB_CLIENT_ACCESS, "%llu: Mirroring...", w->id);
 
-                               // replace the zero bytes with spaces
-                               buffer_char_replace(w->response.data, '\0', ' ');
+                                       // replace the zero bytes with spaces
+                                       buffer_char_replace(w->response.data, '\0', ' ');
 
-                               // just leave the buffer as is
-                               // it will be copied back to the client
-                       }
-                       else if(strcmp(tok, "list") == 0) {
-                               code = 200;
+                                       // just leave the buffer as is
+                                       // it will be copied back to the client
+                               }
+#endif
+                               else if(strcmp(tok, "list") == 0) {
+                                       code = 200;
 
-                               debug(D_WEB_CLIENT_ACCESS, "%llu: Sending list of RRD_STATS...", w->id);
+                                       debug(D_WEB_CLIENT_ACCESS, "%llu: Sending list of RRD_STATS...", w->id);
 
-                               buffer_flush(w->response.data);
-                               RRDSET *st = rrdset_root;
+                                       buffer_flush(w->response.data);
+                                       RRDSET *st = rrdset_root;
 
-                               for ( ; st ; st = st->next )
-                                       buffer_sprintf(w->response.data, "%s\n", st->name);
-                       }
-                       else if(strcmp(tok, "all.json") == 0) {
-                               code = 200;
-                               debug(D_WEB_CLIENT_ACCESS, "%llu: Sending JSON list of all monitors of RRD_STATS...", w->id);
+                                       for ( ; st ; st = st->next )
+                                               buffer_sprintf(w->response.data, "%s\n", st->name);
+                               }
+                               else if(strcmp(tok, "all.json") == 0) {
+                                       code = 200;
+                                       debug(D_WEB_CLIENT_ACCESS, "%llu: Sending JSON list of all monitors of RRD_STATS...", w->id);
 
-                               w->response.data->contenttype = CT_APPLICATION_JSON;
-                               buffer_flush(w->response.data);
-                               rrd_stats_all_json(w->response.data);
-                       }
-                       else if(strcmp(tok, "netdata.conf") == 0) {
-                               code = 200;
-                               debug(D_WEB_CLIENT_ACCESS, "%llu: Sending netdata.conf ...", w->id);
+                                       w->response.data->contenttype = CT_APPLICATION_JSON;
+                                       buffer_flush(w->response.data);
+                                       rrd_stats_all_json(w->response.data);
+                               }
+                               else if(strcmp(tok, "netdata.conf") == 0) {
+                                       code = 200;
+                                       debug(D_WEB_CLIENT_ACCESS, "%llu: Sending netdata.conf ...", w->id);
 
-                               w->response.data->contenttype = CT_TEXT_PLAIN;
-                               buffer_flush(w->response.data);
-                               generate_config(w->response.data, 0);
+                                       w->response.data->contenttype = CT_TEXT_PLAIN;
+                                       buffer_flush(w->response.data);
+                                       generate_config(w->response.data, 0);
+                               }
+                               else {
+                                       char filename[FILENAME_MAX+1];
+                                       url = filename;
+                                       strncpy(filename, w->last_url, FILENAME_MAX);
+                                       filename[FILENAME_MAX] = '\0';
+                                       tok = mystrsep(&url, "?");
+                                       buffer_flush(w->response.data);
+                                       code = mysendfile(w, (tok && *tok)?tok:"/");
+                               }
                        }
                        else {
                                char filename[FILENAME_MAX+1];
@@ -1125,7 +1383,7 @@ void web_client_process(struct web_client *w) {
                else {
                        strcpy(w->last_url, "not a valid response");
 
-                       if(buf) debug(D_WEB_CLIENT_ACCESS, "%llu: Cannot understand '%s'.", w->id, buf);
+                       debug(D_WEB_CLIENT_ACCESS, "%llu: Cannot understand '%s'.", w->id, w->response.data->buffer);
 
                        code = 500;
                        buffer_flush(w->response.data);
@@ -1133,16 +1391,19 @@ void web_client_process(struct web_client *w) {
                }
 
                // free url_decode() buffer
-               if(pointer_to_free) free(pointer_to_free);
+               if(pointer_to_free) {
+                       free(pointer_to_free);
+                       pointer_to_free = NULL;
+               }
        }
-       else if(w->response.data->len > 8192) {
+       else if(w->response.data->len > TOO_BIG_REQUEST) {
                strcpy(w->last_url, "too big request");
 
-               debug(D_WEB_CLIENT_ACCESS, "%llu: Received request is too big.", w->id);
+               debug(D_WEB_CLIENT_ACCESS, "%llu: Received request is too big (%zd bytes).", w->id, w->response.data->len);
 
                code = 400;
                buffer_flush(w->response.data);
-               buffer_strcat(w->response.data, "Received request is too big.\r\n");
+               buffer_sprintf(w->response.data, "Received request is too big  (%zd bytes).\r\n", w->response.data->len);
        }
        else {
                // wait for more data
@@ -1158,7 +1419,7 @@ void web_client_process(struct web_client *w) {
        // prepare the HTTP response header
        debug(D_WEB_CLIENT, "%llu: Generating HTTP header with response %d.", w->id, code);
 
-       char *content_type_string = "";
+       char *content_type_string;
        switch(w->response.data->contenttype) {
                case CT_TEXT_HTML:
                        content_type_string = "text/html; charset=utf-8";
@@ -1208,17 +1469,45 @@ void web_client_process(struct web_client *w) {
                        content_type_string = "application/font-woff";
                        break;
 
+               case CT_APPLICATION_FONT_WOFF2:
+                       content_type_string = "application/font-woff2";
+                       break;
+
                case CT_APPLICATION_VND_MS_FONTOBJ:
                        content_type_string = "application/vnd.ms-fontobject";
                        break;
 
+               case CT_IMAGE_PNG:
+                       content_type_string = "image/png";
+                       break;
+
+               case CT_IMAGE_JPG:
+                       content_type_string = "image/jpeg";
+                       break;
+
+               case CT_IMAGE_GIF:
+                       content_type_string = "image/gif";
+                       break;
+
+               case CT_IMAGE_XICON:
+                       content_type_string = "image/x-icon";
+                       break;
+
+               case CT_IMAGE_BMP:
+                       content_type_string = "image/bmp";
+                       break;
+
+               case CT_IMAGE_ICNS:
+                       content_type_string = "image/icns";
+                       break;
+
                default:
                case CT_TEXT_PLAIN:
                        content_type_string = "text/plain; charset=utf-8";
                        break;
        }
 
-       char *code_msg = "";
+       char *code_msg;
        switch(code) {
                case 200:
                        code_msg = "OK";
@@ -1246,15 +1535,15 @@ void web_client_process(struct web_client *w) {
        }
 
        char date[100];
-       struct tm tm = *gmtime(&w->response.data->date);
-       strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %Z", &tm);
+       struct tm tmbuf, *tm = gmtime_r(&w->response.data->date, &tmbuf);
+       strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %Z", tm);
 
        buffer_sprintf(w->response.header_output,
                "HTTP/1.1 %d %s\r\n"
                "Connection: %s\r\n"
                "Server: NetData Embedded HTTP Server\r\n"
-               "Content-Type: %s\r\n"
                "Access-Control-Allow-Origin: *\r\n"
+               "Content-Type: %s\r\n"
                "Date: %s\r\n"
                , code, code_msg
                , w->keepalive?"keep-alive":"close"
@@ -1262,23 +1551,47 @@ void web_client_process(struct web_client *w) {
                , date
                );
 
+       if(w->cookie[0]) {
+               buffer_sprintf(w->response.header_output,
+                  "Set-Cookie: %s\r\n",
+                  w->cookie);
+       }
+
+       if(w->mode == WEB_CLIENT_MODE_OPTIONS) {
+               buffer_strcat(w->response.header_output,
+                       "Access-Control-Allow-Methods: GET, OPTIONS\r\n"
+                       "Access-Control-Allow-Credentials: true\r\n"
+                       "Access-Control-Allow-Headers: Accept, X-Requested-With, Content-Type, Cookie\r\n"
+                       "Access-Control-Max-Age: 1209600\r\n" // 86400 * 14
+                       );
+       }
+
        if(buffer_strlen(w->response.header))
                buffer_strcat(w->response.header_output, buffer_tostring(w->response.header));
 
-       if(w->mode == WEB_CLIENT_MODE_NORMAL) {
+       if(w->mode == WEB_CLIENT_MODE_NORMAL && (w->response.data->options & WB_CONTENT_NO_CACHEABLE)) {
                buffer_sprintf(w->response.header_output,
                        "Expires: %s\r\n"
                        "Cache-Control: no-cache\r\n"
                        , date);
        }
-       else
-               buffer_strcat(w->response.header_output, "Cache-Control: public\r\n");
+       else if(w->mode != WEB_CLIENT_MODE_OPTIONS) {
+               char edate[100];
+               time_t et = w->response.data->date + (86400 * 14);
+               struct tm etmbuf, *etm = gmtime_r(&et, &etmbuf);
+               strftime(edate, sizeof(edate), "%a, %d %b %Y %H:%M:%S %Z", etm);
+
+               buffer_sprintf(w->response.header_output,
+                       "Expires: %s\r\n"
+                       "Cache-Control: public\r\n"
+                       , edate);
+       }
 
        // if we know the content length, put it
        if(!w->response.zoutput && (w->response.data->len || w->response.rlen))
                buffer_sprintf(w->response.header_output,
                        "Content-Length: %ld\r\n"
-                       , w->response.data->len?w->response.data->len:w->response.rlen
+                       , w->response.data->len? w->response.data->len: w->response.rlen
                        );
        else if(!w->response.zoutput)
                w->keepalive = 0;       // content-length is required for keep-alive
@@ -1305,7 +1618,7 @@ void web_client_process(struct web_client *w) {
                        );
 
        bytes = send(w->ofd, buffer_tostring(w->response.header_output), buffer_strlen(w->response.header_output), 0);
-       if(bytes != buffer_strlen(w->response.header_output))
+       if(bytes != (ssize_t) buffer_strlen(w->response.header_output))
                error("%llu: HTTP Header failed to be sent (I sent %d bytes but the system sent %d bytes)."
                                , w->id
                                , buffer_strlen(w->response.header_output)
@@ -1326,6 +1639,10 @@ void web_client_process(struct web_client *w) {
 
        // pretty logging
        switch(w->mode) {
+               case WEB_CLIENT_MODE_OPTIONS:
+                       debug(D_WEB_CLIENT, "%llu: Done preparing the OPTIONS response. Sending data (%d bytes) to client.", w->id, w->response.data->len);
+                       break;
+
                case WEB_CLIENT_MODE_NORMAL:
                        debug(D_WEB_CLIENT, "%llu: Done preparing the response. Sending data (%d bytes) to client.", w->id, w->response.data->len);
                        break;
@@ -1356,16 +1673,16 @@ void web_client_process(struct web_client *w) {
        }
 }
 
-long web_client_send_chunk_header(struct web_client *w, int len)
+long web_client_send_chunk_header(struct web_client *w, long len)
 {
        debug(D_DEFLATE, "%llu: OPEN CHUNK of %d bytes (hex: %x).", w->id, len, len);
        char buf[1024];
-       sprintf(buf, "%X\r\n", len);
-       int bytes = send(w->ofd, buf, strlen(buf), MSG_DONTWAIT);
+       sprintf(buf, "%lX\r\n", len);
+       ssize_t bytes = send(w->ofd, buf, strlen(buf), MSG_DONTWAIT);
 
        if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk header %d bytes.", w->id, bytes);
        else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk header to the client.", w->id);
-       else debug(D_DEFLATE, "%llu: Failed to send chunk header to client. Reason: %s", w->id, strerror(errno));
+       else debug(D_DEFLATE, "%llu: Failed to send chunk header to client.", w->id);
 
        return bytes;
 }
@@ -1374,11 +1691,11 @@ long web_client_send_chunk_close(struct web_client *w)
 {
        //debug(D_DEFLATE, "%llu: CLOSE CHUNK.", w->id);
 
-       int bytes = send(w->ofd, "\r\n", 2, MSG_DONTWAIT);
+       ssize_t bytes = send(w->ofd, "\r\n", 2, MSG_DONTWAIT);
 
        if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
        else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
-       else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client. Reason: %s", w->id, strerror(errno));
+       else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client.", w->id);
 
        return bytes;
 }
@@ -1387,11 +1704,11 @@ long web_client_send_chunk_finalize(struct web_client *w)
 {
        //debug(D_DEFLATE, "%llu: FINALIZE CHUNK.", w->id);
 
-       int bytes = send(w->ofd, "\r\n0\r\n\r\n", 7, MSG_DONTWAIT);
+       ssize_t bytes = send(w->ofd, "\r\n0\r\n\r\n", 7, MSG_DONTWAIT);
 
        if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
        else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
-       else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client. Reason: %s", w->id, strerror(errno));
+       else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client.", w->id);
 
        return bytes;
 }
@@ -1404,7 +1721,7 @@ long web_client_send_deflate(struct web_client *w)
        // when using compression,
        // w->response.sent is the amount of bytes passed through compression
 
-       debug(D_DEFLATE, "%llu: TEST w->response.data->len = %d, w->response.sent = %d, w->response.zhave = %d, w->response.zsent = %d, w->response.zstream.avail_in = %d, w->response.zstream.avail_out = %d, w->response.zstream.total_in = %d, w->response.zstream.total_out = %d.", w->id, w->response.data->len, w->response.sent, w->response.zhave, w->response.zsent, w->response.zstream.avail_in, w->response.zstream.avail_out, w->response.zstream.total_in, w->response.zstream.total_out);
+       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);
 
        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) {
                // there is nothing to send
@@ -1444,12 +1761,16 @@ long web_client_send_deflate(struct web_client *w)
                // close the previous open chunk
                if(w->response.sent != 0) t += web_client_send_chunk_close(w);
 
-               debug(D_DEFLATE, "%llu: Compressing %d bytes starting from %d.", w->id, (w->response.data->len - w->response.sent), w->response.sent);
+               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);
 
                // give the compressor all the data not passed through the compressor yet
                if(w->response.data->len > w->response.sent) {
-                       w->response.zstream.next_in = (Bytef *)&w->response.data->buffer[w->response.sent];
-                       w->response.zstream.avail_in = (w->response.data->len - w->response.sent);
+#ifdef NETDATA_INTERNAL_CHECKS
+                       if((long)w->response.sent - (long)w->response.zstream.avail_in < 0)
+                               error("internal error: avail_in is corrupted.");
+#endif
+                       w->response.zstream.next_in = (Bytef *)&w->response.data->buffer[w->response.sent - w->response.zstream.avail_in];
+                       w->response.zstream.avail_in += (uInt) (w->response.data->len - w->response.sent);
                }
 
                // reset the compressor output buffer
@@ -1459,9 +1780,9 @@ long web_client_send_deflate(struct web_client *w)
                // ask for FINISH if we have all the input
                int flush = Z_SYNC_FLUSH;
                if(w->mode == WEB_CLIENT_MODE_NORMAL
-                       || (w->mode == WEB_CLIENT_MODE_FILECOPY && w->response.data->len == w->response.rlen)) {
+                       || (w->mode == WEB_CLIENT_MODE_FILECOPY && !w->wait_receive && w->response.data->len == w->response.rlen)) {
                        flush = Z_FINISH;
-                       debug(D_DEFLATE, "%llu: Requesting Z_FINISH.", w->id);
+                       debug(D_DEFLATE, "%llu: Requesting Z_FINISH, if possible.", w->id);
                }
                else {
                        debug(D_DEFLATE, "%llu: Requesting Z_SYNC_FLUSH.", w->id);
@@ -1485,8 +1806,10 @@ long web_client_send_deflate(struct web_client *w)
                // open a new chunk
                t += web_client_send_chunk_header(w, w->response.zhave);
        }
+       
+       debug(D_WEB_CLIENT, "%llu: Sending %d bytes of data (+%d of chunk header).", w->id, w->response.zhave - w->response.zsent, t);
 
-       len = send(w->ofd, &w->response.zbuffer[w->response.zsent], w->response.zhave - w->response.zsent, MSG_DONTWAIT);
+       len = send(w->ofd, &w->response.zbuffer[w->response.zsent], (size_t) (w->response.zhave - w->response.zsent), MSG_DONTWAIT);
        if(len > 0) {
                w->response.zsent += len;
                if(t > 0) len += t;
@@ -1540,7 +1863,7 @@ long web_client_send(struct web_client *w)
                debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, bytes);
        }
        else if(likely(bytes == 0)) debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client.", w->id);
-       else debug(D_WEB_CLIENT, "%llu: Failed to send data to client. Reason: %s", w->id, strerror(errno));
+       else debug(D_WEB_CLIENT, "%llu: Failed to send data to client.", w->id);
 
        return(bytes);
 }
@@ -1554,12 +1877,12 @@ long web_client_receive(struct web_client *w)
        long bytes;
 
        if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY))
-               bytes = read(w->ifd, &w->response.data->buffer[w->response.data->len], (left-1));
+               bytes = read(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1));
        else
-               bytes = recv(w->ifd, &w->response.data->buffer[w->response.data->len], left-1, MSG_DONTWAIT);
+               bytes = recv(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1), MSG_DONTWAIT);
 
        if(likely(bytes > 0)) {
-               int old = w->response.data->len;
+               size_t old = w->response.data->len;
                w->response.data->len += bytes;
                w->response.data->buffer[w->response.data->len] = '\0';
 
@@ -1655,19 +1978,19 @@ void *web_client_main(void *ptr)
                }
 
                if(FD_ISSET(w->ifd, &efds)) {
-                       debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on input socket (%s).", w->id, strerror(errno));
+                       debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on input socket.", w->id);
                        break;
                }
 
                if(FD_ISSET(w->ofd, &efds)) {
-                       debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on output socket (%s).", w->id, strerror(errno));
+                       debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on output socket.", w->id);
                        break;
                }
 
                if(w->wait_send && FD_ISSET(w->ofd, &ofds)) {
                        long bytes;
                        if((bytes = web_client_send(w)) < 0) {
-                               debug(D_WEB_CLIENT, "%llu: Cannot send data to client. Closing client (ouput: %s).", w->id, strerror(errno));
+                               debug(D_WEB_CLIENT, "%llu: Cannot send data to client. Closing client.", w->id);
                                errno = 0;
                                break;
                        }
@@ -1680,19 +2003,20 @@ void *web_client_main(void *ptr)
                if(w->wait_receive && FD_ISSET(w->ifd, &ifds)) {
                        long bytes;
                        if((bytes = web_client_receive(w)) < 0) {
-                               debug(D_WEB_CLIENT, "%llu: Cannot receive data from client. Closing client (input: %s).", w->id, strerror(errno));
+                               debug(D_WEB_CLIENT, "%llu: Cannot receive data from client. Closing client.", w->id);
                                errno = 0;
                                break;
                        }
 
-                       global_statistics_lock();
-                       global_statistics.bytes_received += bytes;
-                       global_statistics_unlock();
-
                        if(w->mode == WEB_CLIENT_MODE_NORMAL) {
-                               debug(D_WEB_CLIENT, "%llu: Attempting to process received data.", w->id);
+                               debug(D_WEB_CLIENT, "%llu: Attempting to process received data (%ld bytes).", w->id, bytes);
+                               // info("%llu: Attempting to process received data (%ld bytes).", w->id, bytes);
                                web_client_process(w);
                        }
+
+                       global_statistics_lock();
+                       global_statistics.bytes_received += bytes;
+                       global_statistics_unlock();
                }
        }