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