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