]> arthur.barton.de Git - netdata.git/blob - src/web_client.c
code cleanup and re-arrangements for better scalability
[netdata.git] / src / web_client.c
1 #ifdef HAVE_CONFIG_H
2 #include <config.h>
3 #endif
4 #include <unistd.h>
5 #include <stdlib.h>
6 #include <sys/types.h>
7 #include <sys/socket.h>
8 #include <netinet/in.h>
9 #include <arpa/inet.h>
10 #include <errno.h>
11 #include <pthread.h>
12 #include <sys/stat.h>
13 #include <fcntl.h>
14 #include <netinet/tcp.h>
15 #include <malloc.h>
16
17 #include "common.h"
18 #include "log.h"
19 #include "appconfig.h"
20 #include "url.h"
21 #include "web_buffer.h"
22 #include "web_server.h"
23 #include "global_statistics.h"
24 #include "rrd.h"
25 #include "rrd2json.h"
26
27 #include "web_client.h"
28
29 #define INITIAL_WEB_DATA_LENGTH 16384
30 #define WEB_REQUEST_LENGTH 16384
31
32 int web_client_timeout = DEFAULT_DISCONNECT_IDLE_WEB_CLIENTS_AFTER_SECONDS;
33 int web_enable_gzip = 1;
34
35 struct web_client *web_clients = NULL;
36 unsigned long long web_clients_count = 0;
37
38 struct web_client *web_client_create(int listener)
39 {
40         struct web_client *w;
41         
42         w = calloc(1, sizeof(struct web_client));
43         if(!w) {
44                 error("Cannot allocate new web_client memory.");
45                 return NULL;
46         }
47
48         w->id = ++web_clients_count;
49         w->mode = WEB_CLIENT_MODE_NORMAL;
50
51         {
52                 struct sockaddr *sadr;
53                 socklen_t addrlen;
54
55                 sadr = (struct sockaddr*) &w->clientaddr;
56                 addrlen = sizeof(w->clientaddr);
57
58                 w->ifd = accept(listener, sadr, &addrlen);
59                 if (w->ifd == -1) {
60                         error("%llu: Cannot accept new incoming connection.", w->id);
61                         free(w);
62                         return NULL;
63                 }
64                 w->ofd = w->ifd;
65
66                 if(getnameinfo(sadr, addrlen, w->client_ip, NI_MAXHOST, w->client_port, NI_MAXSERV, NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
67                         error("Cannot getnameinfo() on received client connection.");
68                         strncpy(w->client_ip,   "UNKNOWN", NI_MAXHOST);
69                         strncpy(w->client_port, "UNKNOWN", NI_MAXSERV);
70                 }
71                 w->client_ip[NI_MAXHOST]   = '\0';
72                 w->client_port[NI_MAXSERV] = '\0';
73
74                 switch(sadr->sa_family) {
75
76                 case AF_INET:
77                         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);
78                         break;
79
80                 case AF_INET6:
81                         if(strncmp(w->client_ip, "::ffff:", 7) == 0) {
82                                 strcpy(w->client_ip, &w->client_ip[7]);
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);
84                         }
85                         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);
86                         break;
87
88                 default:
89                         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);
90                         break;
91                 }
92
93                 int flag = 1;
94                 if(setsockopt(w->ifd, SOL_SOCKET, SO_KEEPALIVE, (char *) &flag, sizeof(int)) != 0) error("%llu: Cannot set SO_KEEPALIVE on socket.", w->id);
95         }
96
97         w->response.data = buffer_create(INITIAL_WEB_DATA_LENGTH);
98         if(unlikely(!w->response.data)) {
99                 // no need for error log - web_buffer_create already logged the error
100                 close(w->ifd);
101                 free(w);
102                 return NULL;
103         }
104
105         w->response.header = buffer_create(HTTP_RESPONSE_HEADER_SIZE);
106         if(unlikely(!w->response.header)) {
107                 // no need for error log - web_buffer_create already logged the error
108                 buffer_free(w->response.data);
109                 close(w->ifd);
110                 free(w);
111                 return NULL;
112         }
113
114         w->response.header_output = buffer_create(HTTP_RESPONSE_HEADER_SIZE);
115         if(unlikely(!w->response.header_output)) {
116                 // no need for error log - web_buffer_create already logged the error
117                 buffer_free(w->response.header);
118                 buffer_free(w->response.data);
119                 close(w->ifd);
120                 free(w);
121                 return NULL;
122         }
123
124         w->wait_receive = 1;
125
126         if(web_clients) web_clients->prev = w;
127         w->next = web_clients;
128         web_clients = w;
129
130         global_statistics.connected_clients++;
131
132         return(w);
133 }
134
135 void web_client_reset(struct web_client *w)
136 {
137         struct timeval tv;
138         gettimeofday(&tv, NULL);
139
140         long sent = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->response.rlen:w->response.data->len;
141
142 #ifdef NETDATA_WITH_ZLIB
143         if(likely(w->response.zoutput)) sent = (long)w->response.zstream.total_out;
144 #endif
145
146         long size = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->response.rlen:w->response.data->len;
147
148         if(likely(w->last_url[0]))
149                 log_access("%llu: (sent/all = %ld/%ld bytes %0.0f%%, prep/sent/total = %0.2f/%0.2f/%0.2f ms) %s: '%s'",
150                         w->id,
151                         sent, size, -((size>0)?((float)(size-sent)/(float)size * 100.0):0.0),
152                         (float)usecdiff(&w->tv_ready, &w->tv_in) / 1000.0,
153                         (float)usecdiff(&tv, &w->tv_ready) / 1000.0,
154                         (float)usecdiff(&tv, &w->tv_in) / 1000.0,
155                         (w->mode == WEB_CLIENT_MODE_FILECOPY)?"filecopy":"data",
156                                         w->last_url
157                 );
158
159         debug(D_WEB_CLIENT, "%llu: Reseting client.", w->id);
160
161         if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY)) {
162                 debug(D_WEB_CLIENT, "%llu: Closing filecopy input file.", w->id);
163                 close(w->ifd);
164                 w->ifd = w->ofd;
165         }
166
167         w->last_url[0] = '\0';
168
169         w->mode = WEB_CLIENT_MODE_NORMAL;
170
171         buffer_reset(w->response.header_output);
172         buffer_reset(w->response.header);
173         buffer_reset(w->response.data);
174         w->response.rlen = 0;
175         w->response.sent = 0;
176
177         w->wait_receive = 1;
178         w->wait_send = 0;
179
180         w->response.zoutput = 0;
181
182         // if we had enabled compression, release it
183 #ifdef NETDATA_WITH_ZLIB
184         if(w->response.zinitialized) {
185                 debug(D_DEFLATE, "%llu: Reseting compression.", w->id);
186                 deflateEnd(&w->response.zstream);
187                 w->response.zsent = 0;
188                 w->response.zhave = 0;
189                 w->response.zstream.avail_in = 0;
190                 w->response.zstream.avail_out = 0;
191                 w->response.zstream.total_in = 0;
192                 w->response.zstream.total_out = 0;
193                 w->response.zinitialized = 0;
194         }
195 #endif // NETDATA_WITH_ZLIB
196 }
197
198 struct web_client *web_client_free(struct web_client *w)
199 {
200         struct web_client *n = w->next;
201
202         debug(D_WEB_CLIENT_ACCESS, "%llu: Closing web client from %s port %s.", w->id, w->client_ip, w->client_port);
203
204         if(w->prev)     w->prev->next = w->next;
205         if(w->next) w->next->prev = w->prev;
206
207         if(w == web_clients) web_clients = w->next;
208
209         if(w->response.header) buffer_free(w->response.header);
210         if(w->response.data) buffer_free(w->response.data);
211         close(w->ifd);
212         if(w->ofd != w->ifd) close(w->ofd);
213         free(w);
214
215         global_statistics.connected_clients--;
216
217         return(n);
218 }
219
220 int mysendfile(struct web_client *w, char *filename)
221 {
222         static char *web_dir = NULL;
223         if(!web_dir) web_dir = config_get("global", "web files directory", WEB_DIR);
224
225         debug(D_WEB_CLIENT, "%llu: Looking for file '%s'...", w->id, filename);
226
227         // skip leading slashes
228         while (*filename == '/') filename++;
229
230         // if the filename contain known paths, skip them
231                  if(strncmp(filename, WEB_PATH_DATA       "/", strlen(WEB_PATH_DATA)       + 1) == 0) filename = &filename[strlen(WEB_PATH_DATA)       + 1];
232         else if(strncmp(filename, WEB_PATH_DATASOURCE "/", strlen(WEB_PATH_DATASOURCE) + 1) == 0) filename = &filename[strlen(WEB_PATH_DATASOURCE) + 1];
233         else if(strncmp(filename, WEB_PATH_GRAPH      "/", strlen(WEB_PATH_GRAPH)      + 1) == 0) filename = &filename[strlen(WEB_PATH_GRAPH)      + 1];
234         else if(strncmp(filename, WEB_PATH_FILE       "/", strlen(WEB_PATH_FILE)       + 1) == 0) filename = &filename[strlen(WEB_PATH_FILE)       + 1];
235
236         // if the filename contains a / or a .., refuse to serve it
237         if(strchr(filename, '/') != 0 || strstr(filename, "..") != 0) {
238                 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
239                 buffer_sprintf(w->response.data, "File '%s' cannot be served. Filenames cannot contain / or ..", filename);
240                 return 400;
241         }
242
243         // access the file
244         char webfilename[FILENAME_MAX + 1];
245         snprintf(webfilename, FILENAME_MAX, "%s/%s", web_dir, filename);
246
247         // check if the file exists
248         struct stat stat;
249         if(lstat(webfilename, &stat) != 0) {
250                 error("%llu: File '%s' is not found.", w->id, webfilename);
251                 buffer_sprintf(w->response.data, "File '%s' does not exist, or is not accessible.", filename);
252                 return 404;
253         }
254
255         // check if the file is owned by us
256         if(stat.st_uid != getuid() && stat.st_uid != geteuid()) {
257                 error("%llu: File '%s' is owned by user %d (I run as user %d). Access Denied.", w->id, webfilename, stat.st_uid, getuid());
258                 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", filename);
259                 return 403;
260         }
261
262         // open the file
263         w->ifd = open(webfilename, O_NONBLOCK, O_RDONLY);
264         if(w->ifd == -1) {
265                 w->ifd = w->ofd;
266
267                 if(errno == EBUSY || errno == EAGAIN) {
268                         error("%llu: File '%s' is busy, sending 307 Moved Temporarily to force retry.", w->id, webfilename);
269                         buffer_sprintf(w->response.header, "Location: /" WEB_PATH_FILE "/%s\r\n", filename);
270                         buffer_sprintf(w->response.data, "The file '%s' is currently busy. Please try again later.", filename);
271                         return 307;
272                 }
273                 else {
274                         error("%llu: Cannot open file '%s'.", w->id, webfilename);
275                         buffer_sprintf(w->response.data, "Cannot open file '%s'.", filename);
276                         return 404;
277                 }
278         }
279
280         // pick a Content-Type for the file
281                  if(strstr(filename, ".html") != NULL)  w->response.data->contenttype = CT_TEXT_HTML;
282         else if(strstr(filename, ".js")   != NULL)      w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
283         else if(strstr(filename, ".css")  != NULL)      w->response.data->contenttype = CT_TEXT_CSS;
284         else if(strstr(filename, ".xml")  != NULL)      w->response.data->contenttype = CT_TEXT_XML;
285         else if(strstr(filename, ".xsl")  != NULL)      w->response.data->contenttype = CT_TEXT_XSL;
286         else if(strstr(filename, ".txt")  != NULL)  w->response.data->contenttype = CT_TEXT_PLAIN;
287         else if(strstr(filename, ".svg")  != NULL)  w->response.data->contenttype = CT_IMAGE_SVG_XML;
288         else if(strstr(filename, ".ttf")  != NULL)  w->response.data->contenttype = CT_APPLICATION_X_FONT_TRUETYPE;
289         else if(strstr(filename, ".otf")  != NULL)  w->response.data->contenttype = CT_APPLICATION_X_FONT_OPENTYPE;
290         else if(strstr(filename, ".woff") != NULL)  w->response.data->contenttype = CT_APPLICATION_FONT_WOFF;
291         else if(strstr(filename, ".eot")  != NULL)  w->response.data->contenttype = CT_APPLICATION_VND_MS_FONTOBJ;
292         else w->response.data->contenttype = CT_APPLICATION_OCTET_STREAM;
293
294         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);
295
296         w->mode = WEB_CLIENT_MODE_FILECOPY;
297         w->wait_receive = 1;
298         w->wait_send = 0;
299         buffer_flush(w->response.data);
300         w->response.rlen = stat.st_size;
301         w->response.data->date = stat.st_mtim.tv_sec;
302
303         return 200;
304 }
305
306
307 #ifdef NETDATA_WITH_ZLIB
308 void web_client_enable_deflate(struct web_client *w) {
309         if(w->response.zinitialized == 1) {
310                 error("%llu: Compression has already be initialized for this client.", w->id);
311                 return;
312         }
313
314         if(w->response.sent) {
315                 error("%llu: Cannot enable compression in the middle of a conversation.", w->id);
316                 return;
317         }
318
319         w->response.zstream.zalloc = Z_NULL;
320         w->response.zstream.zfree = Z_NULL;
321         w->response.zstream.opaque = Z_NULL;
322
323         w->response.zstream.next_in = (Bytef *)w->response.data->buffer;
324         w->response.zstream.avail_in = 0;
325         w->response.zstream.total_in = 0;
326
327         w->response.zstream.next_out = w->response.zbuffer;
328         w->response.zstream.avail_out = 0;
329         w->response.zstream.total_out = 0;
330
331         w->response.zstream.zalloc = Z_NULL;
332         w->response.zstream.zfree = Z_NULL;
333         w->response.zstream.opaque = Z_NULL;
334
335 //      if(deflateInit(&w->response.zstream, Z_DEFAULT_COMPRESSION) != Z_OK) {
336 //              error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
337 //              return;
338 //      }
339
340         // Select GZIP compression: windowbits = 15 + 16 = 31
341         if(deflateInit2(&w->response.zstream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY) != Z_OK) {
342                 error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
343                 return;
344         }
345
346         w->response.zsent = 0;
347         w->response.zoutput = 1;
348         w->response.zinitialized = 1;
349
350         debug(D_DEFLATE, "%llu: Initialized compression.", w->id);
351 }
352 #endif // NETDATA_WITH_ZLIB
353
354 int rrdset_validate_dimensions(RRDSET *st, BUFFER *dimensions)
355 {
356         ;
357 }
358
359 int web_client_api_request_v1_data_format(char *name)
360 {
361         if(!strcmp(name, "datatable"))
362                 return DATASOURCE_GOOGLE_JSON;
363
364         else if(!strcmp(name, "datasource"))
365                 return DATASOURCE_GOOGLE_JSONP;
366
367         else if(!strcmp(name, "json"))
368                 return DATASOURCE_JSON;
369
370         else if(!strcmp(name, "ssv"))
371                 return DATASOURCE_SSV;
372
373         else if(!strcmp(name, "csv"))
374                 return DATASOURCE_CSV;
375
376         return DATASOURCE_INVALID;
377 }
378
379 int web_client_api_request_v1_charts(struct web_client *w, char *url)
380 {
381         buffer_flush(w->response.data);
382         rrd_stats_api_v1_charts(w->response.data);
383         return 200;
384 }
385
386 int web_client_api_request_v1_chart(struct web_client *w, char *url)
387 {
388         int ret = 400;
389         char *chart = NULL;
390
391         buffer_flush(w->response.data);
392
393         while(url) {
394                 char *value = mystrsep(&url, "?&[]");
395                 if(!value || !*value) continue;
396
397                 char *name = mystrsep(&value, "=");
398                 if(!name || !*name) continue;
399                 if(!value || !*value) continue;
400
401                 // name and value are now the parameters
402                 // they are not null and not empty
403
404                 if(!strcmp(name, "chart")) chart = value;
405                 else {
406                         buffer_sprintf(w->response.data, "Unknown parameter '%s' in request.", name);
407                         goto cleanup;
408                 }
409         }
410
411         if(!chart || !*chart) {
412                 buffer_sprintf(w->response.data, "No chart id is given at the request.");
413                 goto cleanup;
414         }
415
416         RRDSET *st = rrdset_find(chart);
417         if(!st) st = rrdset_find_byname(chart);
418         if(!st) {
419                 buffer_sprintf(w->response.data, "Chart '%s' is not found.", chart);
420                 ret = 404;
421                 goto cleanup;
422         }
423
424         w->response.data->contenttype = CT_APPLICATION_JSON;
425         rrd_stats_api_v1_chart(st, w->response.data);
426         return 200;
427
428 cleanup:
429         return ret;
430 }
431
432 int web_client_api_request_v1_data(struct web_client *w, char *url)
433 {
434         int ret = 400;
435         BUFFER *dimensions = NULL;
436
437         buffer_flush(w->response.data);
438
439         char *chart = NULL
440                         , *dim = NULL
441                         , *before_str = NULL
442                         , *after_str = NULL
443                         , *points_str = NULL
444                         , *group_str = NULL
445                         , *options = NULL;
446
447         int format = DATASOURCE_JSON;
448
449         while(url) {
450                 char *value = mystrsep(&url, "?&[]");
451                 if(!value || !*value) continue;
452
453                 char *name = mystrsep(&value, "=");
454                 if(!name || !*name) continue;
455                 if(!value || !*value) continue;
456
457                 // name and value are now the parameters
458                 // they are not null and not empty
459
460                 if(!strcmp(name, "chart")) chart = value;
461                 else if(!strcmp(name, "dimension") || !strcmp(name, "dim")) {
462                         if(!dimensions) dimensions = buffer_create(strlen(value));
463                         if(dimensions) {
464                                 buffer_strcat(dimensions, "|");
465                                 buffer_strcat(dimensions, value);
466                         }
467                 }
468                 else if(!strcmp(name, "after")) after_str = value;
469                 else if(!strcmp(name, "before")) before_str = value;
470                 else if(!strcmp(name, "points")) points_str = value;
471                 else if(!strcmp(name, "group")) group_str = value;
472                 else if(!strcmp(name, "format")) {
473                         format = web_client_api_request_v1_data_format(value);
474                 }
475                 else if(!strcmp(name, "options")) {
476                         options = value;
477                 }
478                 else {
479                         buffer_sprintf(w->response.data, "Unknown parameter '%s' in request.", name);
480                         goto cleanup;
481                 }
482         }
483
484         if(!chart || !*chart) {
485                 buffer_sprintf(w->response.data, "No chart id is given at the request.");
486                 goto cleanup;
487         }
488
489         RRDSET *st = rrdset_find(chart);
490         if(!st) st = rrdset_find_byname(chart);
491         if(!st) {
492                 buffer_sprintf(w->response.data, "Chart '%s' is not found.", chart);
493                 ret = 404;
494                 goto cleanup;
495         }
496
497         uint32_t before = (before_str && *before_str)?atol(before_str):0;
498         uint32_t after  = (after_str  && *after_str) ?atol(after_str):0;
499         int      points = (points_str && *points_str)?atoi(points_str):0;
500         int      group  = (group_str  && *group_str) ?atoi(group_str):0;
501
502         buffer_sprintf(w->response.data, "API command 'data' for chart '%s', dimensions '%s', after '%s', before '%s', points '%s', group '%s', format '%s', options '%s'", chart, dim, after_str, before_str, points_str, group_str, format, options);
503
504 cleanup:
505         if(dimensions) buffer_free(dimensions);
506         return ret;
507 }
508
509 int web_client_api_request_v1(struct web_client *w, char *url)
510 {
511         // get the command
512         char *tok = mystrsep(&url, "/?&");
513         debug(D_WEB_CLIENT, "%llu: Searching for API v1 command '%s'.", w->id, tok);
514
515         if(strcmp(tok, "data") == 0)
516                 return web_client_api_request_v1_data(w, url);
517         else if(strcmp(tok, "chart") == 0)
518                 return web_client_api_request_v1_chart(w, url);
519         else if(strcmp(tok, "charts") == 0)
520                 return web_client_api_request_v1_charts(w, url);
521
522         buffer_flush(w->response.data);
523         buffer_sprintf(w->response.data, "Unsupported v1 API command: %s", tok);
524         return 404;
525 }
526
527 int web_client_api_request(struct web_client *w, char *url)
528 {
529         // get the api version
530         char *tok = mystrsep(&url, "/?&");
531         debug(D_WEB_CLIENT, "%llu: Searching for API version '%s'.", w->id, tok);
532
533         if(strcmp(tok, "v1") == 0)
534                 return web_client_api_request_v1(w, url);
535
536         buffer_flush(w->response.data);
537         buffer_sprintf(w->response.data, "Unsupported API version: %s", tok);
538         return 404;
539 }
540
541 int web_client_data_request(struct web_client *w, char *url, int datasource_type)
542 {
543         char *args = strchr(url, '?');
544         if(args) {
545                 *args='\0';
546                 args = &args[1];
547         }
548
549         // get the name of the data to show
550         char *tok = mystrsep(&url, "/");
551         debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
552
553         // do we have such a data set?
554         RRDSET *st = rrdset_find_byname(tok);
555         if(!st) st = rrdset_find(tok);
556         if(!st) {
557                 // we don't have it
558                 // try to send a file with that name
559                 buffer_flush(w->response.data);
560                 return(mysendfile(w, tok));
561         }
562
563         // we have it
564         debug(D_WEB_CLIENT, "%llu: Found RRD data with name '%s'.", w->id, tok);
565
566         // how many entries does the client want?
567         long lines = rrd_default_history_entries;
568         long group_count = 1;
569         time_t after = 0, before = 0;
570         int group_method = GROUP_AVERAGE;
571         int nonzero = 0;
572
573         if(url) {
574                 // parse the lines required
575                 tok = mystrsep(&url, "/");
576                 if(tok) lines = atoi(tok);
577                 if(lines < 1) lines = 1;
578         }
579         if(url) {
580                 // parse the group count required
581                 tok = mystrsep(&url, "/");
582                 if(tok) group_count = atoi(tok);
583                 if(group_count < 1) group_count = 1;
584                 //if(group_count > save_history / 20) group_count = save_history / 20;
585         }
586         if(url) {
587                 // parse the grouping method required
588                 tok = mystrsep(&url, "/");
589                 if(strcmp(tok, "max") == 0) group_method = GROUP_MAX;
590                 else if(strcmp(tok, "average") == 0) group_method = GROUP_AVERAGE;
591                 else if(strcmp(tok, "sum") == 0) group_method = GROUP_SUM;
592                 else debug(D_WEB_CLIENT, "%llu: Unknown group method '%s'", w->id, tok);
593         }
594         if(url) {
595                 // parse after time
596                 tok = mystrsep(&url, "/");
597                 if(tok) after = strtoul(tok, NULL, 10);
598                 if(after < 0) after = 0;
599         }
600         if(url) {
601                 // parse before time
602                 tok = mystrsep(&url, "/");
603                 if(tok) before = strtoul(tok, NULL, 10);
604                 if(before < 0) before = 0;
605         }
606         if(url) {
607                 // parse nonzero
608                 tok = mystrsep(&url, "/");
609                 if(tok && strcmp(tok, "nonzero") == 0) nonzero = 1;
610         }
611
612         w->response.data->contenttype = CT_APPLICATION_JSON;
613         buffer_flush(w->response.data);
614
615         char *google_version = "0.6";
616         char *google_reqId = "0";
617         char *google_sig = "0";
618         char *google_out = "json";
619         char *google_responseHandler = "google.visualization.Query.setResponse";
620         char *google_outFileName = NULL;
621         unsigned long last_timestamp_in_data = 0;
622         if(datasource_type == DATASOURCE_GOOGLE_JSON || datasource_type == DATASOURCE_GOOGLE_JSONP) {
623
624                 w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
625
626                 while(args) {
627                         tok = mystrsep(&args, "&");
628                         if(tok) {
629                                 char *name = mystrsep(&tok, "=");
630                                 if(name && strcmp(name, "tqx") == 0) {
631                                         char *key = mystrsep(&tok, ":");
632                                         char *value = mystrsep(&tok, ";");
633                                         if(key && value && *key && *value) {
634                                                 if(strcmp(key, "version") == 0)
635                                                         google_version = value;
636
637                                                 else if(strcmp(key, "reqId") == 0)
638                                                         google_reqId = value;
639
640                                                 else if(strcmp(key, "sig") == 0)
641                                                         google_sig = value;
642
643                                                 else if(strcmp(key, "out") == 0)
644                                                         google_out = value;
645
646                                                 else if(strcmp(key, "responseHandler") == 0)
647                                                         google_responseHandler = value;
648
649                                                 else if(strcmp(key, "outFileName") == 0)
650                                                         google_outFileName = value;
651                                         }
652                                 }
653                         }
654                 }
655
656                 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
657                         w->id, google_version, google_reqId, google_sig, google_out, google_responseHandler, google_outFileName
658                         );
659
660                 if(datasource_type == DATASOURCE_GOOGLE_JSONP) {
661                         last_timestamp_in_data = strtoul(google_sig, NULL, 0);
662
663                         // check the client wants json
664                         if(strcmp(google_out, "json") != 0) {
665                                 buffer_sprintf(w->response.data,
666                                         "%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.'}]});",
667                                         google_responseHandler, google_version, google_reqId, google_out);
668                                         return 200;
669                         }
670                 }
671         }
672
673         if(datasource_type == DATASOURCE_GOOGLE_JSONP) {
674                 buffer_sprintf(w->response.data,
675                         "%s({version:'%s',reqId:'%s',status:'ok',sig:'%lu',table:",
676                         google_responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
677         }
678
679         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);
680         unsigned long timestamp_in_data = rrd_stats_json(datasource_type, st, w->response.data, lines, group_count, group_method, after, before, nonzero);
681
682         if(datasource_type == DATASOURCE_GOOGLE_JSONP) {
683                 if(timestamp_in_data > last_timestamp_in_data)
684                         buffer_strcat(w->response.data, "});");
685
686                 else {
687                         // the client already has the latest data
688                         buffer_sprintf(w->response.data,
689                                 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
690                                 google_responseHandler, google_version, google_reqId);
691                 }
692         }
693
694         return 200;
695 }
696
697 /*
698 int web_client_parse_request(struct web_client *w) {
699         // protocol
700         // hostname
701         // path
702         // query string name-value
703         // http version
704         // method
705         // http request headers name-value
706
707         web_client_clean_request(w);
708
709         debug(D_WEB_DATA, "%llu: Processing data buffer of %d bytes: '%s'.", w->id, w->response.data->bytes, w->response.data->buffer);
710
711         char *buf = w->response.data->buffer;
712         char *line, *tok;
713
714         // ------------------------------------------------------------------------
715         // the first line
716
717         if(buf && (line = strsep(&buf, "\r\n"))) {
718                 // method
719                 if(line && (tok = strsep(&line, " "))) {
720                         w->request.protocol = strdup(tok);
721                 }
722                 else goto cleanup;
723
724                 // url
725         }
726         else goto cleanup;
727
728         // ------------------------------------------------------------------------
729         // the rest of the lines
730
731         while(buf && (line = strsep(&buf, "\r\n"))) {
732                 while(line && (tok = strsep(&line, ": "))) {
733                 }
734         }
735
736         char *url = NULL;
737
738
739 cleanup:
740         web_client_clean_request(w);
741         return 0;
742 }
743 */
744
745 void web_client_process(struct web_client *w) {
746         int code = 500;
747         int bytes;
748
749         w->wait_receive = 0;
750
751         // check if we have an empty line (end of HTTP header)
752         if(strstr(w->response.data->buffer, "\r\n\r\n")) {
753                 global_statistics_lock();
754                 global_statistics.web_requests++;
755                 global_statistics_unlock();
756
757                 gettimeofday(&w->tv_in, NULL);
758                 debug(D_WEB_DATA, "%llu: Processing data buffer of %d bytes: '%s'.", w->id, w->response.data->len, w->response.data->buffer);
759
760                 // check if the client requested keep-alive HTTP
761                 if(strcasestr(w->response.data->buffer, "Connection: keep-alive")) w->keepalive = 1;
762                 else w->keepalive = 0;
763
764 #ifdef NETDATA_WITH_ZLIB
765                 // check if the client accepts deflate
766                 if(web_enable_gzip && strstr(w->response.data->buffer, "gzip"))
767                         web_client_enable_deflate(w);
768 #endif // NETDATA_WITH_ZLIB
769
770                 int datasource_type = DATASOURCE_GOOGLE_JSONP;
771                 //if(strstr(w->response.data->buffer, "X-DataSource-Auth"))
772                 //      datasource_type = DATASOURCE_GOOGLE_JSON;
773
774                 char *buf = w->response.data->buffer;
775                 char *tok = strsep(&buf, " \r\n");
776                 char *url = NULL;
777                 char *pointer_to_free = NULL; // keep url_decode() allocated buffer
778
779                 if(buf && strcmp(tok, "GET") == 0) {
780                         tok = strsep(&buf, " \r\n");
781                         pointer_to_free = url = url_decode(tok);
782                         debug(D_WEB_CLIENT, "%llu: Processing HTTP GET on url '%s'.", w->id, url);
783                 }
784                 else if (buf && strcmp(tok, "POST") == 0) {
785                         w->keepalive = 0;
786                         tok = strsep(&buf, " \r\n");
787                         pointer_to_free = url = url_decode(tok);
788
789                         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);
790                 }
791
792                 w->last_url[0] = '\0';
793                 if(url) {
794                         strncpy(w->last_url, url, URL_MAX);
795                         w->last_url[URL_MAX] = '\0';
796
797                         tok = mystrsep(&url, "/?&");
798
799                         debug(D_WEB_CLIENT, "%llu: Processing command '%s'.", w->id, tok);
800
801                         if(strcmp(tok, "api") == 0) {
802                                 // the client is requesting api access
803                                 datasource_type = DATASOURCE_JSON;
804                                 code = web_client_api_request(w, url);
805                         }
806                         else if(strcmp(tok, WEB_PATH_DATA) == 0) { // "data"
807                                 // the client is requesting rrd data
808                                 datasource_type = DATASOURCE_JSON;
809                                 code = web_client_data_request(w, url, datasource_type);
810                         }
811                         else if(strcmp(tok, WEB_PATH_DATASOURCE) == 0) { // "datasource"
812                                 // the client is requesting google datasource
813                                 code = web_client_data_request(w, url, datasource_type);
814                         }
815                         else if(strcmp(tok, WEB_PATH_GRAPH) == 0) { // "graph"
816                                 // the client is requesting an rrd graph
817
818                                 // get the name of the data to show
819                                 tok = mystrsep(&url, "/?&");
820                                 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
821
822                                 // do we have such a data set?
823                                 RRDSET *st = rrdset_find_byname(tok);
824                                 if(!st) st = rrdset_find(tok);
825                                 if(!st) {
826                                         // we don't have it
827                                         // try to send a file with that name
828                                         buffer_flush(w->response.data);
829                                         code = mysendfile(w, tok);
830                                 }
831                                 else {
832                                         code = 200;
833                                         debug(D_WEB_CLIENT_ACCESS, "%llu: Sending %s.json of RRD_STATS...", w->id, st->name);
834                                         w->response.data->contenttype = CT_APPLICATION_JSON;
835                                         buffer_flush(w->response.data);
836                                         rrd_stats_graph_json(st, url, w->response.data);
837                                 }
838                         }
839                         else if(strcmp(tok, "debug") == 0) {
840                                 buffer_flush(w->response.data);
841
842                                 // get the name of the data to show
843                                 tok = mystrsep(&url, "/?&");
844                                 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
845
846                                 // do we have such a data set?
847                                 RRDSET *st = rrdset_find_byname(tok);
848                                 if(!st) st = rrdset_find(tok);
849                                 if(!st) {
850                                         code = 404;
851                                         buffer_sprintf(w->response.data, "Chart %s is not found.\r\n", tok);
852                                         debug(D_WEB_CLIENT_ACCESS, "%llu: %s is not found.", w->id, tok);
853                                 }
854                                 else {
855                                         code = 200;
856                                         debug_flags |= D_RRD_STATS;
857                                         st->debug = st->debug?0:1;
858                                         buffer_sprintf(w->response.data, "Chart %s has now debug %s.\r\n", tok, st->debug?"enabled":"disabled");
859                                         debug(D_WEB_CLIENT_ACCESS, "%llu: debug for %s is %s.", w->id, tok, st->debug?"enabled":"disabled");
860                                 }
861                         }
862                         else if(strcmp(tok, "mirror") == 0) {
863                                 code = 200;
864
865                                 debug(D_WEB_CLIENT_ACCESS, "%llu: Mirroring...", w->id);
866
867                                 // replace the zero bytes with spaces
868                                 buffer_char_replace(w->response.data, '\0', ' ');
869
870                                 // just leave the buffer as is
871                                 // it will be copied back to the client
872                         }
873                         else if(strcmp(tok, "list") == 0) {
874                                 code = 200;
875
876                                 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending list of RRD_STATS...", w->id);
877
878                                 buffer_flush(w->response.data);
879                                 RRDSET *st = rrdset_root;
880
881                                 for ( ; st ; st = st->next )
882                                         buffer_sprintf(w->response.data, "%s\n", st->name);
883                         }
884                         else if(strcmp(tok, "all.json") == 0) {
885                                 code = 200;
886                                 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending JSON list of all monitors of RRD_STATS...", w->id);
887
888                                 w->response.data->contenttype = CT_APPLICATION_JSON;
889                                 buffer_flush(w->response.data);
890                                 rrd_stats_all_json(w->response.data);
891                         }
892                         else if(strcmp(tok, "netdata.conf") == 0) {
893                                 code = 200;
894                                 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending netdata.conf ...", w->id);
895
896                                 w->response.data->contenttype = CT_TEXT_PLAIN;
897                                 buffer_flush(w->response.data);
898                                 generate_config(w->response.data, 0);
899                         }
900                         else if(strcmp(tok, WEB_PATH_FILE) == 0) { // "file"
901                                 tok = mystrsep(&url, "/?&");
902                                 if(tok && *tok) code = mysendfile(w, tok);
903                                 else {
904                                         code = 400;
905                                         buffer_flush(w->response.data);
906                                         buffer_strcat(w->response.data, "You have to give a filename to get.\r\n");
907                                 }
908                         }
909                         else if(!tok[0]) {
910                                 buffer_flush(w->response.data);
911                                 code = mysendfile(w, "index.html");
912                         }
913                         else {
914                                 buffer_flush(w->response.data);
915                                 code = mysendfile(w, tok);
916                         }
917
918                 }
919                 else {
920                         strcpy(w->last_url, "not a valid response");
921
922                         if(buf) debug(D_WEB_CLIENT_ACCESS, "%llu: Cannot understand '%s'.", w->id, buf);
923
924                         code = 500;
925                         buffer_flush(w->response.data);
926                         buffer_strcat(w->response.data, "I don't understand you...\r\n");
927                 }
928
929                 // free url_decode() buffer
930                 if(pointer_to_free) free(pointer_to_free);
931         }
932         else if(w->response.data->len > 8192) {
933                 strcpy(w->last_url, "too big request");
934
935                 debug(D_WEB_CLIENT_ACCESS, "%llu: Received request is too big.", w->id);
936
937                 code = 400;
938                 buffer_flush(w->response.data);
939                 buffer_strcat(w->response.data, "Received request is too big.\r\n");
940         }
941         else {
942                 // wait for more data
943                 w->wait_receive = 1;
944                 return;
945         }
946
947         if(w->response.data->len > w->response.data->size) {
948                 error("%llu: memory overflow encountered (size is %ld, written %ld).", w->response.data->size, w->response.data->len);
949         }
950
951         gettimeofday(&w->tv_ready, NULL);
952         w->response.data->date = time(NULL);
953         w->response.sent = 0;
954
955         // prepare the HTTP response header
956         debug(D_WEB_CLIENT, "%llu: Generating HTTP header with response %d.", w->id, code);
957
958         char *content_type_string = "";
959         switch(w->response.data->contenttype) {
960                 case CT_TEXT_HTML:
961                         content_type_string = "text/html; charset=utf-8";
962                         break;
963
964                 case CT_APPLICATION_XML:
965                         content_type_string = "application/xml; charset=utf-8";
966                         break;
967
968                 case CT_APPLICATION_JSON:
969                         content_type_string = "application/json; charset=utf-8";
970                         break;
971
972                 case CT_APPLICATION_X_JAVASCRIPT:
973                         content_type_string = "application/x-javascript; charset=utf-8";
974                         break;
975
976                 case CT_TEXT_CSS:
977                         content_type_string = "text/css; charset=utf-8";
978                         break;
979
980                 case CT_TEXT_XML:
981                         content_type_string = "text/xml; charset=utf-8";
982                         break;
983
984                 case CT_TEXT_XSL:
985                         content_type_string = "text/xsl; charset=utf-8";
986                         break;
987
988                 case CT_APPLICATION_OCTET_STREAM:
989                         content_type_string = "application/octet-stream";
990                         break;
991
992                 case CT_IMAGE_SVG_XML:
993                         content_type_string = "image/svg+xml";
994                         break;
995
996                 case CT_APPLICATION_X_FONT_TRUETYPE:
997                         content_type_string = "application/x-font-truetype";
998                         break;
999
1000                 case CT_APPLICATION_X_FONT_OPENTYPE:
1001                         content_type_string = "application/x-font-opentype";
1002                         break;
1003
1004                 case CT_APPLICATION_FONT_WOFF:
1005                         content_type_string = "application/font-woff";
1006                         break;
1007
1008                 case CT_APPLICATION_VND_MS_FONTOBJ:
1009                         content_type_string = "application/vnd.ms-fontobject";
1010                         break;
1011
1012                 default:
1013                 case CT_TEXT_PLAIN:
1014                         content_type_string = "text/plain; charset=utf-8";
1015                         break;
1016         }
1017
1018         char *code_msg = "";
1019         switch(code) {
1020                 case 200:
1021                         code_msg = "OK";
1022                         break;
1023
1024                 case 307:
1025                         code_msg = "Temporary Redirect";
1026                         break;
1027
1028                 case 400:
1029                         code_msg = "Bad Request";
1030                         break;
1031
1032                 case 403:
1033                         code_msg = "Forbidden";
1034                         break;
1035
1036                 case 404:
1037                         code_msg = "Not Found";
1038                         break;
1039
1040                 default:
1041                         code_msg = "Internal Server Error";
1042                         break;
1043         }
1044
1045         char date[100];
1046         struct tm tm = *gmtime(&w->response.data->date);
1047         strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %Z", &tm);
1048
1049         buffer_sprintf(w->response.header_output,
1050                 "HTTP/1.1 %d %s\r\n"
1051                 "Connection: %s\r\n"
1052                 "Server: NetData Embedded HTTP Server\r\n"
1053                 "Content-Type: %s\r\n"
1054                 "Access-Control-Allow-Origin: *\r\n"
1055                 "Date: %s\r\n"
1056                 , code, code_msg
1057                 , w->keepalive?"keep-alive":"close"
1058                 , content_type_string
1059                 , date
1060                 );
1061
1062         if(buffer_strlen(w->response.header))
1063                 buffer_strcat(w->response.header_output, buffer_tostring(w->response.header));
1064
1065         if(w->mode == WEB_CLIENT_MODE_NORMAL) {
1066                 buffer_sprintf(w->response.header_output,
1067                         "Expires: %s\r\n"
1068                         "Cache-Control: no-cache\r\n"
1069                         , date);
1070         }
1071         else
1072                 buffer_strcat(w->response.header_output, "Cache-Control: public\r\n");
1073
1074         // if we know the content length, put it
1075         if(!w->response.zoutput && (w->response.data->len || w->response.rlen))
1076                 buffer_sprintf(w->response.header_output,
1077                         "Content-Length: %ld\r\n"
1078                         , w->response.data->len?w->response.data->len:w->response.rlen
1079                         );
1080         else if(!w->response.zoutput)
1081                 w->keepalive = 0;       // content-length is required for keep-alive
1082
1083         if(w->response.zoutput) {
1084                 buffer_strcat(w->response.header_output,
1085                         "Content-Encoding: gzip\r\n"
1086                         "Transfer-Encoding: chunked\r\n"
1087                         );
1088         }
1089
1090         buffer_strcat(w->response.header_output, "\r\n");
1091
1092         // disable TCP_NODELAY, to buffer the header
1093         int flag = 0;
1094         if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0)
1095                 error("%llu: failed to disable TCP_NODELAY on socket.", w->id);
1096
1097         // sent the HTTP header
1098         debug(D_WEB_DATA, "%llu: Sending response HTTP header of size %d: '%s'"
1099                         , w->id
1100                         , buffer_strlen(w->response.header_output)
1101                         , buffer_tostring(w->response.header_output)
1102                         );
1103
1104         bytes = send(w->ofd, buffer_tostring(w->response.header_output), buffer_strlen(w->response.header_output), 0);
1105         if(bytes != buffer_strlen(w->response.header_output))
1106                 error("%llu: HTTP Header failed to be sent (I sent %d bytes but the system sent %d bytes)."
1107                                 , w->id
1108                                 , buffer_strlen(w->response.header_output)
1109                                 , bytes);
1110         else {
1111                 global_statistics_lock();
1112                 global_statistics.bytes_sent += bytes;
1113                 global_statistics_unlock();
1114         }
1115
1116         // enable TCP_NODELAY, to send all data immediately at the next send()
1117         flag = 1;
1118         if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0) error("%llu: failed to enable TCP_NODELAY on socket.", w->id);
1119
1120         // enable sending immediately if we have data
1121         if(w->response.data->len) w->wait_send = 1;
1122         else w->wait_send = 0;
1123
1124         // pretty logging
1125         switch(w->mode) {
1126                 case WEB_CLIENT_MODE_NORMAL:
1127                         debug(D_WEB_CLIENT, "%llu: Done preparing the response. Sending data (%d bytes) to client.", w->id, w->response.data->len);
1128                         break;
1129
1130                 case WEB_CLIENT_MODE_FILECOPY:
1131                         if(w->response.rlen) {
1132                                 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending data file of %d bytes to client.", w->id, w->response.rlen);
1133                                 w->wait_receive = 1;
1134
1135                                 /*
1136                                 // utilize the kernel sendfile() for copying the file to the socket.
1137                                 // this block of code can be commented, without anything missing.
1138                                 // when it is commented, the program will copy the data using async I/O.
1139                                 {
1140                                         long len = sendfile(w->ofd, w->ifd, NULL, w->response.data->rbytes);
1141                                         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);
1142                                         else web_client_reset(w);
1143                                 }
1144                                 */
1145                         }
1146                         else
1147                                 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending an unknown amount of bytes to client.", w->id);
1148                         break;
1149
1150                 default:
1151                         fatal("%llu: Unknown client mode %d.", w->id, w->mode);
1152                         break;
1153         }
1154 }
1155
1156 long web_client_send_chunk_header(struct web_client *w, int len)
1157 {
1158         debug(D_DEFLATE, "%llu: OPEN CHUNK of %d bytes (hex: %x).", w->id, len, len);
1159         char buf[1024];
1160         sprintf(buf, "%X\r\n", len);
1161         int bytes = send(w->ofd, buf, strlen(buf), MSG_DONTWAIT);
1162
1163         if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk header %d bytes.", w->id, bytes);
1164         else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk header to the client.", w->id);
1165         else debug(D_DEFLATE, "%llu: Failed to send chunk header to client. Reason: %s", w->id, strerror(errno));
1166
1167         return bytes;
1168 }
1169
1170 long web_client_send_chunk_close(struct web_client *w)
1171 {
1172         //debug(D_DEFLATE, "%llu: CLOSE CHUNK.", w->id);
1173
1174         int bytes = send(w->ofd, "\r\n", 2, MSG_DONTWAIT);
1175
1176         if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
1177         else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
1178         else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client. Reason: %s", w->id, strerror(errno));
1179
1180         return bytes;
1181 }
1182
1183 long web_client_send_chunk_finalize(struct web_client *w)
1184 {
1185         //debug(D_DEFLATE, "%llu: FINALIZE CHUNK.", w->id);
1186
1187         int bytes = send(w->ofd, "\r\n0\r\n\r\n", 7, MSG_DONTWAIT);
1188
1189         if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
1190         else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
1191         else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client. Reason: %s", w->id, strerror(errno));
1192
1193         return bytes;
1194 }
1195
1196 #ifdef NETDATA_WITH_ZLIB
1197 long web_client_send_deflate(struct web_client *w)
1198 {
1199         long len = 0, t = 0;
1200
1201         // when using compression,
1202         // w->response.sent is the amount of bytes passed through compression
1203
1204         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);
1205
1206         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) {
1207                 // there is nothing to send
1208
1209                 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1210
1211                 // finalize the chunk
1212                 if(w->response.sent != 0)
1213                         t += web_client_send_chunk_finalize(w);
1214
1215                 // there can be two cases for this
1216                 // A. we have done everything
1217                 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
1218
1219                 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->response.rlen && w->response.rlen > w->response.data->len) {
1220                         // we have to wait, more data will come
1221                         debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1222                         w->wait_send = 0;
1223                         return(0);
1224                 }
1225
1226                 if(w->keepalive == 0) {
1227                         debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->response.sent);
1228                         errno = 0;
1229                         return(-1);
1230                 }
1231
1232                 // reset the client
1233                 web_client_reset(w);
1234                 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1235                 return(0);
1236         }
1237
1238         if(w->response.zhave == w->response.zsent) {
1239                 // compress more input data
1240
1241                 // close the previous open chunk
1242                 if(w->response.sent != 0) t += web_client_send_chunk_close(w);
1243
1244                 debug(D_DEFLATE, "%llu: Compressing %d bytes starting from %d.", w->id, (w->response.data->len - w->response.sent), w->response.sent);
1245
1246                 // give the compressor all the data not passed through the compressor yet
1247                 if(w->response.data->len > w->response.sent) {
1248                         w->response.zstream.next_in = (Bytef *)&w->response.data->buffer[w->response.sent];
1249                         w->response.zstream.avail_in = (w->response.data->len - w->response.sent);
1250                 }
1251
1252                 // reset the compressor output buffer
1253                 w->response.zstream.next_out = w->response.zbuffer;
1254                 w->response.zstream.avail_out = ZLIB_CHUNK;
1255
1256                 // ask for FINISH if we have all the input
1257                 int flush = Z_SYNC_FLUSH;
1258                 if(w->mode == WEB_CLIENT_MODE_NORMAL
1259                         || (w->mode == WEB_CLIENT_MODE_FILECOPY && w->response.data->len == w->response.rlen)) {
1260                         flush = Z_FINISH;
1261                         debug(D_DEFLATE, "%llu: Requesting Z_FINISH.", w->id);
1262                 }
1263                 else {
1264                         debug(D_DEFLATE, "%llu: Requesting Z_SYNC_FLUSH.", w->id);
1265                 }
1266
1267                 // compress
1268                 if(deflate(&w->response.zstream, flush) == Z_STREAM_ERROR) {
1269                         error("%llu: Compression failed. Closing down client.", w->id);
1270                         web_client_reset(w);
1271                         return(-1);
1272                 }
1273
1274                 w->response.zhave = ZLIB_CHUNK - w->response.zstream.avail_out;
1275                 w->response.zsent = 0;
1276
1277                 // keep track of the bytes passed through the compressor
1278                 w->response.sent = w->response.data->len;
1279
1280                 debug(D_DEFLATE, "%llu: Compression produced %d bytes.", w->id, w->response.zhave);
1281
1282                 // open a new chunk
1283                 t += web_client_send_chunk_header(w, w->response.zhave);
1284         }
1285
1286         len = send(w->ofd, &w->response.zbuffer[w->response.zsent], w->response.zhave - w->response.zsent, MSG_DONTWAIT);
1287         if(len > 0) {
1288                 w->response.zsent += len;
1289                 if(t > 0) len += t;
1290                 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, len);
1291         }
1292         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);
1293         else debug(D_WEB_CLIENT, "%llu: Failed to send data to client. Reason: %s", w->id, strerror(errno));
1294
1295         return(len);
1296 }
1297 #endif // NETDATA_WITH_ZLIB
1298
1299 long web_client_send(struct web_client *w)
1300 {
1301 #ifdef NETDATA_WITH_ZLIB
1302         if(likely(w->response.zoutput)) return web_client_send_deflate(w);
1303 #endif // NETDATA_WITH_ZLIB
1304
1305         long bytes;
1306
1307         if(unlikely(w->response.data->len - w->response.sent == 0)) {
1308                 // there is nothing to send
1309
1310                 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1311
1312                 // there can be two cases for this
1313                 // A. we have done everything
1314                 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
1315
1316                 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->response.rlen && w->response.rlen > w->response.data->len) {
1317                         // we have to wait, more data will come
1318                         debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1319                         w->wait_send = 0;
1320                         return(0);
1321                 }
1322
1323                 if(unlikely(w->keepalive == 0)) {
1324                         debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->response.sent);
1325                         errno = 0;
1326                         return(-1);
1327                 }
1328
1329                 web_client_reset(w);
1330                 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1331                 return(0);
1332         }
1333
1334         bytes = send(w->ofd, &w->response.data->buffer[w->response.sent], w->response.data->len - w->response.sent, MSG_DONTWAIT);
1335         if(likely(bytes > 0)) {
1336                 w->response.sent += bytes;
1337                 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, bytes);
1338         }
1339         else if(likely(bytes == 0)) debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client.", w->id);
1340         else debug(D_WEB_CLIENT, "%llu: Failed to send data to client. Reason: %s", w->id, strerror(errno));
1341
1342         return(bytes);
1343 }
1344
1345 long web_client_receive(struct web_client *w)
1346 {
1347         // do we have any space for more data?
1348         buffer_need_bytes(w->response.data, WEB_REQUEST_LENGTH);
1349
1350         long left = w->response.data->size - w->response.data->len;
1351         long bytes;
1352
1353         if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY))
1354                 bytes = read(w->ifd, &w->response.data->buffer[w->response.data->len], (left-1));
1355         else
1356                 bytes = recv(w->ifd, &w->response.data->buffer[w->response.data->len], left-1, MSG_DONTWAIT);
1357
1358         if(likely(bytes > 0)) {
1359                 int old = w->response.data->len;
1360                 w->response.data->len += bytes;
1361                 w->response.data->buffer[w->response.data->len] = '\0';
1362
1363                 debug(D_WEB_CLIENT, "%llu: Received %d bytes.", w->id, bytes);
1364                 debug(D_WEB_DATA, "%llu: Received data: '%s'.", w->id, &w->response.data->buffer[old]);
1365
1366                 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1367                         w->wait_send = 1;
1368                         if(w->response.rlen && w->response.data->len >= w->response.rlen) w->wait_receive = 0;
1369                 }
1370         }
1371         else if(likely(bytes == 0)) {
1372                 debug(D_WEB_CLIENT, "%llu: Out of input data.", w->id);
1373
1374                 // if we cannot read, it means we have an error on input.
1375                 // if however, we are copying a file from ifd to ofd, we should not return an error.
1376                 // in this case, the error should be generated when the file has been sent to the client.
1377
1378                 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1379                         // we are copying data from ifd to ofd
1380                         // let it finish copying...
1381                         w->wait_receive = 0;
1382                         debug(D_WEB_CLIENT, "%llu: Disabling input.", w->id);
1383                 }
1384                 else {
1385                         bytes = -1;
1386                         errno = 0;
1387                 }
1388         }
1389
1390         return(bytes);
1391 }
1392
1393
1394 // --------------------------------------------------------------------------------------
1395 // the thread of a single client
1396
1397 // 1. waits for input and output, using async I/O
1398 // 2. it processes HTTP requests
1399 // 3. it generates HTTP responses
1400 // 4. it copies data from input to output if mode is FILECOPY
1401
1402 void *web_client_main(void *ptr)
1403 {
1404         if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
1405                 error("Cannot set pthread cancel type to DEFERRED.");
1406
1407         if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
1408                 error("Cannot set pthread cancel state to ENABLE.");
1409
1410         struct timeval tv;
1411         struct web_client *w = ptr;
1412         int retval;
1413         fd_set ifds, ofds, efds;
1414         int fdmax = 0;
1415
1416         log_access("%llu: %s port %s connected on thread task id %d", w->id, w->client_ip, w->client_port, gettid());
1417
1418         for(;;) {
1419                 FD_ZERO (&ifds);
1420                 FD_ZERO (&ofds);
1421                 FD_ZERO (&efds);
1422
1423                 FD_SET(w->ifd, &efds);
1424
1425                 if(w->ifd != w->ofd)
1426                         FD_SET(w->ofd, &efds);
1427
1428                 if (w->wait_receive) {
1429                         FD_SET(w->ifd, &ifds);
1430                         if(w->ifd > fdmax) fdmax = w->ifd;
1431                 }
1432
1433                 if (w->wait_send) {
1434                         FD_SET(w->ofd, &ofds);
1435                         if(w->ofd > fdmax) fdmax = w->ofd;
1436                 }
1437
1438                 tv.tv_sec = web_client_timeout;
1439                 tv.tv_usec = 0;
1440
1441                 debug(D_WEB_CLIENT, "%llu: Waiting socket async I/O for %s %s", w->id, w->wait_receive?"INPUT":"", w->wait_send?"OUTPUT":"");
1442                 retval = select(fdmax+1, &ifds, &ofds, &efds, &tv);
1443
1444                 if(retval == -1) {
1445                         debug(D_WEB_CLIENT_ACCESS, "%llu: LISTENER: select() failed.", w->id);
1446                         continue;
1447                 }
1448                 else if(!retval) {
1449                         // timeout
1450                         debug(D_WEB_CLIENT_ACCESS, "%llu: LISTENER: timeout.", w->id);
1451                         break;
1452                 }
1453
1454                 if(FD_ISSET(w->ifd, &efds)) {
1455                         debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on input socket (%s).", w->id, strerror(errno));
1456                         break;
1457                 }
1458
1459                 if(FD_ISSET(w->ofd, &efds)) {
1460                         debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on output socket (%s).", w->id, strerror(errno));
1461                         break;
1462                 }
1463
1464                 if(w->wait_send && FD_ISSET(w->ofd, &ofds)) {
1465                         long bytes;
1466                         if((bytes = web_client_send(w)) < 0) {
1467                                 debug(D_WEB_CLIENT, "%llu: Cannot send data to client. Closing client (ouput: %s).", w->id, strerror(errno));
1468                                 errno = 0;
1469                                 break;
1470                         }
1471
1472                         global_statistics_lock();
1473                         global_statistics.bytes_sent += bytes;
1474                         global_statistics_unlock();
1475                 }
1476
1477                 if(w->wait_receive && FD_ISSET(w->ifd, &ifds)) {
1478                         long bytes;
1479                         if((bytes = web_client_receive(w)) < 0) {
1480                                 debug(D_WEB_CLIENT, "%llu: Cannot receive data from client. Closing client (input: %s).", w->id, strerror(errno));
1481                                 errno = 0;
1482                                 break;
1483                         }
1484
1485                         global_statistics_lock();
1486                         global_statistics.bytes_received += bytes;
1487                         global_statistics_unlock();
1488
1489                         if(w->mode == WEB_CLIENT_MODE_NORMAL) {
1490                                 debug(D_WEB_CLIENT, "%llu: Attempting to process received data.", w->id);
1491                                 web_client_process(w);
1492                         }
1493                 }
1494         }
1495
1496         log_access("%llu: %s port %s disconnected from thread task id %d", w->id, w->client_ip, w->client_port, gettid());
1497         debug(D_WEB_CLIENT, "%llu: done...", w->id);
1498
1499         web_client_reset(w);
1500         w->obsolete = 1;
1501
1502         return NULL;
1503 }