]> arthur.barton.de Git - netdata.git/blob - src/web_client.c
db82c43490ee9834688c8a8590fca38b485bda2a
[netdata.git] / src / web_client.c
1 #include "common.h"
2
3 #define INITIAL_WEB_DATA_LENGTH 16384
4 #define WEB_REQUEST_LENGTH 16384
5 #define TOO_BIG_REQUEST 16384
6
7 int web_client_timeout = DEFAULT_DISCONNECT_IDLE_WEB_CLIENTS_AFTER_SECONDS;
8 int respect_web_browser_do_not_track_policy = 0;
9 char *web_x_frame_options = NULL;
10
11 #ifdef NETDATA_WITH_ZLIB
12 int web_enable_gzip = 1, web_gzip_level = 3, web_gzip_strategy = Z_DEFAULT_STRATEGY;
13 #endif /* NETDATA_WITH_ZLIB */
14
15 struct web_client *web_clients = NULL;
16 unsigned long long web_clients_count = 0;
17
18 static inline int web_client_crock_socket(struct web_client *w) {
19 #ifdef TCP_CORK
20     if(likely(!w->tcp_cork && w->ofd != -1)) {
21         w->tcp_cork = 1;
22         if(unlikely(setsockopt(w->ofd, IPPROTO_TCP, TCP_CORK, (char *) &w->tcp_cork, sizeof(int)) != 0)) {
23             error("%llu: failed to enable TCP_CORK on socket.", w->id);
24             w->tcp_cork = 0;
25             return -1;
26         }
27     }
28 #endif /* TCP_CORK */
29
30     return 0;
31 }
32
33 static inline int web_client_uncrock_socket(struct web_client *w) {
34 #ifdef TCP_CORK
35     if(likely(w->tcp_cork && w->ofd != -1)) {
36         w->tcp_cork = 0;
37         if(unlikely(setsockopt(w->ofd, IPPROTO_TCP, TCP_CORK, (char *) &w->tcp_cork, sizeof(int)) != 0)) {
38             error("%llu: failed to disable TCP_CORK on socket.", w->id);
39             w->tcp_cork = 1;
40             return -1;
41         }
42     }
43 #endif /* TCP_CORK */
44
45     return 0;
46 }
47
48 struct web_client *web_client_create(int listener)
49 {
50     struct web_client *w;
51
52     w = callocz(1, sizeof(struct web_client));
53     w->id = ++web_clients_count;
54     w->mode = WEB_CLIENT_MODE_NORMAL;
55
56     {
57         struct sockaddr *sadr;
58         socklen_t addrlen;
59
60         sadr = (struct sockaddr*) &w->clientaddr;
61         addrlen = sizeof(w->clientaddr);
62
63         w->ifd = accept4(listener, sadr, &addrlen, SOCK_NONBLOCK);
64         if (w->ifd == -1) {
65             error("%llu: Cannot accept new incoming connection.", w->id);
66             freez(w);
67             return NULL;
68         }
69         w->ofd = w->ifd;
70
71         if(getnameinfo(sadr, addrlen, w->client_ip, NI_MAXHOST, w->client_port, NI_MAXSERV, NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
72             error("Cannot getnameinfo() on received client connection.");
73             strncpyz(w->client_ip,   "UNKNOWN", NI_MAXHOST);
74             strncpyz(w->client_port, "UNKNOWN", NI_MAXSERV);
75         }
76         w->client_ip[NI_MAXHOST]   = '\0';
77         w->client_port[NI_MAXSERV] = '\0';
78
79         switch(sadr->sa_family) {
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                 memmove(w->client_ip, &w->client_ip[7], strlen(&w->client_ip[7]) + 1);
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             else
90                 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);
91             break;
92
93         default:
94             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);
95             break;
96         }
97
98         int flag = 1;
99         if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0)
100             error("%llu: failed to enable TCP_NODELAY on socket.", w->id);
101
102         flag = 1;
103         if(setsockopt(w->ifd, SOL_SOCKET, SO_KEEPALIVE, (char *) &flag, sizeof(int)) != 0)
104             error("%llu: Cannot set SO_KEEPALIVE on socket.", w->id);
105     }
106
107     w->response.data = buffer_create(INITIAL_WEB_DATA_LENGTH);
108     w->response.header = buffer_create(HTTP_RESPONSE_HEADER_SIZE);
109     w->response.header_output = buffer_create(HTTP_RESPONSE_HEADER_SIZE);
110     w->origin[0] = '*';
111     w->wait_receive = 1;
112
113     if(web_clients) web_clients->prev = w;
114     w->next = web_clients;
115     web_clients = w;
116
117     web_client_connected();
118
119     return(w);
120 }
121
122 void web_client_reset(struct web_client *w) {
123     web_client_uncrock_socket(w);
124
125     debug(D_WEB_CLIENT, "%llu: Resetting client.", w->id);
126
127     if(likely(w->last_url[0])) {
128         struct timeval tv;
129         now_realtime_timeval(&tv);
130
131         size_t size = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->response.rlen:w->response.data->len;
132         size_t sent = size;
133 #ifdef NETDATA_WITH_ZLIB
134         if(likely(w->response.zoutput)) sent = (size_t)w->response.zstream.total_out;
135 #endif
136
137         // --------------------------------------------------------------------
138         // global statistics
139
140         finished_web_request_statistics(dt_usec(&tv, &w->tv_in),
141                                         w->stats_received_bytes,
142                                         w->stats_sent_bytes,
143                                         size,
144                                         sent);
145
146         w->stats_received_bytes = 0;
147         w->stats_sent_bytes = 0;
148
149
150         // --------------------------------------------------------------------
151         // access log
152
153         log_access("%llu: (sent/all = %zu/%zu bytes %0.0f%%, prep/sent/total = %0.2f/%0.2f/%0.2f ms) %s: %d '%s'",
154                    w->id,
155                    sent, size, -((size > 0) ? ((size - sent) / (double) size * 100.0) : 0.0),
156                    dt_usec(&w->tv_ready, &w->tv_in) / 1000.0,
157                    dt_usec(&tv, &w->tv_ready) / 1000.0,
158                    dt_usec(&tv, &w->tv_in) / 1000.0,
159                    (w->mode == WEB_CLIENT_MODE_FILECOPY) ? "filecopy" : ((w->mode == WEB_CLIENT_MODE_OPTIONS)
160                                                                          ? "options" : "data"),
161                    w->response.code,
162                    w->last_url
163         );
164     }
165
166     if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY)) {
167         if(w->ifd != w->ofd) {
168             debug(D_WEB_CLIENT, "%llu: Closing filecopy input file descriptor %d.", w->id, w->ifd);
169             if(w->ifd != -1) close(w->ifd);
170             w->ifd = w->ofd;
171         }
172     }
173
174     w->last_url[0] = '\0';
175     w->cookie1[0] = '\0';
176     w->cookie2[0] = '\0';
177     w->origin[0] = '*';
178     w->origin[1] = '\0';
179
180     w->mode = WEB_CLIENT_MODE_NORMAL;
181
182     w->tcp_cork = 0;
183     w->donottrack = 0;
184     w->tracking_required = 0;
185     w->keepalive = 0;
186     w->decoded_url[0] = '\0';
187
188     buffer_reset(w->response.header_output);
189     buffer_reset(w->response.header);
190     buffer_reset(w->response.data);
191     w->response.rlen = 0;
192     w->response.sent = 0;
193     w->response.code = 0;
194
195     w->wait_receive = 1;
196     w->wait_send = 0;
197
198     w->response.zoutput = 0;
199
200     // if we had enabled compression, release it
201 #ifdef NETDATA_WITH_ZLIB
202     if(w->response.zinitialized) {
203         debug(D_DEFLATE, "%llu: Freeing compression resources.", w->id);
204         deflateEnd(&w->response.zstream);
205         w->response.zsent = 0;
206         w->response.zhave = 0;
207         w->response.zstream.avail_in = 0;
208         w->response.zstream.avail_out = 0;
209         w->response.zstream.total_in = 0;
210         w->response.zstream.total_out = 0;
211         w->response.zinitialized = 0;
212     }
213 #endif // NETDATA_WITH_ZLIB
214 }
215
216 struct web_client *web_client_free(struct web_client *w) {
217     web_client_reset(w);
218
219     struct web_client *n = w->next;
220     if(w == web_clients) web_clients = n;
221
222     debug(D_WEB_CLIENT_ACCESS, "%llu: Closing web client from %s port %s.", w->id, w->client_ip, w->client_port);
223
224     if(w->prev) w->prev->next = w->next;
225     if(w->next) w->next->prev = w->prev;
226     if(w->response.header_output) buffer_free(w->response.header_output);
227     if(w->response.header) buffer_free(w->response.header);
228     if(w->response.data) buffer_free(w->response.data);
229     if(w->ifd != -1) close(w->ifd);
230     if(w->ofd != -1 && w->ofd != w->ifd) close(w->ofd);
231     freez(w);
232
233     web_client_disconnected();
234
235     return(n);
236 }
237
238 uid_t web_files_uid(void) {
239     static char *web_owner = NULL;
240     static uid_t owner_uid = 0;
241
242     if(unlikely(!web_owner)) {
243         web_owner = config_get("global", "web files owner", config_get("global", "run as user", ""));
244         if(!web_owner || !*web_owner)
245             owner_uid = geteuid();
246         else {
247             // getpwnam() is not thread safe,
248             // but we have called this function once
249             // while single threaded
250             struct passwd *pw = getpwnam(web_owner);
251             if(!pw) {
252                 error("User '%s' is not present. Ignoring option.", web_owner);
253                 owner_uid = geteuid();
254             }
255             else {
256                 debug(D_WEB_CLIENT, "Web files owner set to %s.", web_owner);
257                 owner_uid = pw->pw_uid;
258             }
259         }
260     }
261
262     return(owner_uid);
263 }
264
265 gid_t web_files_gid(void) {
266     static char *web_group = NULL;
267     static gid_t owner_gid = 0;
268
269     if(unlikely(!web_group)) {
270         web_group = config_get("global", "web files group", config_get("global", "web files owner", ""));
271         if(!web_group || !*web_group)
272             owner_gid = getegid();
273         else {
274             // getgrnam() is not thread safe,
275             // but we have called this function once
276             // while single threaded
277             struct group *gr = getgrnam(web_group);
278             if(!gr) {
279                 error("Group '%s' is not present. Ignoring option.", web_group);
280                 owner_gid = getegid();
281             }
282             else {
283                 debug(D_WEB_CLIENT, "Web files group set to %s.", web_group);
284                 owner_gid = gr->gr_gid;
285             }
286         }
287     }
288
289     return(owner_gid);
290 }
291
292 int mysendfile(struct web_client *w, char *filename)
293 {
294     debug(D_WEB_CLIENT, "%llu: Looking for file '%s/%s'", w->id, netdata_configured_web_dir, filename);
295
296     // skip leading slashes
297     while (*filename == '/') filename++;
298
299     // if the filename contain known paths, skip them
300     if(strncmp(filename, WEB_PATH_FILE "/", strlen(WEB_PATH_FILE) + 1) == 0)
301         filename = &filename[strlen(WEB_PATH_FILE) + 1];
302
303     char *s;
304     for(s = filename; *s ;s++) {
305         if( !isalnum(*s) && *s != '/' && *s != '.' && *s != '-' && *s != '_') {
306             debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
307             buffer_sprintf(w->response.data, "Filename contains invalid characters: ");
308             buffer_strcat_htmlescape(w->response.data, filename);
309             return 400;
310         }
311     }
312
313     // if the filename contains a .. refuse to serve it
314     if(strstr(filename, "..") != 0) {
315         debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
316         buffer_strcat(w->response.data, "Relative filenames are not supported: ");
317         buffer_strcat_htmlescape(w->response.data, filename);
318         return 400;
319     }
320
321     // access the file
322     char webfilename[FILENAME_MAX + 1];
323     snprintfz(webfilename, FILENAME_MAX, "%s/%s", netdata_configured_web_dir, filename);
324
325     // check if the file exists
326     struct stat stat;
327     if(lstat(webfilename, &stat) != 0) {
328         debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not found.", w->id, webfilename);
329         buffer_strcat(w->response.data, "File does not exist, or is not accessible: ");
330         buffer_strcat_htmlescape(w->response.data, webfilename);
331         return 404;
332     }
333
334     // check if the file is owned by expected user
335     if(stat.st_uid != web_files_uid()) {
336         error("%llu: File '%s' is owned by user %u (expected user %u). Access Denied.", w->id, webfilename, stat.st_uid, web_files_uid());
337         buffer_strcat(w->response.data, "Access to file is not permitted: ");
338         buffer_strcat_htmlescape(w->response.data, webfilename);
339         return 403;
340     }
341
342     // check if the file is owned by expected group
343     if(stat.st_gid != web_files_gid()) {
344         error("%llu: File '%s' is owned by group %u (expected group %u). Access Denied.", w->id, webfilename, stat.st_gid, web_files_gid());
345         buffer_strcat(w->response.data, "Access to file is not permitted: ");
346         buffer_strcat_htmlescape(w->response.data, webfilename);
347         return 403;
348     }
349
350     if((stat.st_mode & S_IFMT) == S_IFDIR) {
351         snprintfz(webfilename, FILENAME_MAX, "%s/index.html", filename);
352         return mysendfile(w, webfilename);
353     }
354
355     if((stat.st_mode & S_IFMT) != S_IFREG) {
356         error("%llu: File '%s' is not a regular file. Access Denied.", w->id, webfilename);
357         buffer_strcat(w->response.data, "Access to file is not permitted: ");
358         buffer_strcat_htmlescape(w->response.data, webfilename);
359         return 403;
360     }
361
362     // open the file
363     w->ifd = open(webfilename, O_NONBLOCK, O_RDONLY);
364     if(w->ifd == -1) {
365         w->ifd = w->ofd;
366
367         if(errno == EBUSY || errno == EAGAIN) {
368             error("%llu: File '%s' is busy, sending 307 Moved Temporarily to force retry.", w->id, webfilename);
369             buffer_sprintf(w->response.header, "Location: /" WEB_PATH_FILE "/%s\r\n", filename);
370             buffer_strcat(w->response.data, "File is currently busy, please try again later: ");
371             buffer_strcat_htmlescape(w->response.data, webfilename);
372             return 307;
373         }
374         else {
375             error("%llu: Cannot open file '%s'.", w->id, webfilename);
376             buffer_strcat(w->response.data, "Cannot open file: ");
377             buffer_strcat_htmlescape(w->response.data, webfilename);
378             return 404;
379         }
380     }
381     if(fcntl(w->ifd, F_SETFL, O_NONBLOCK) < 0)
382         error("%llu: Cannot set O_NONBLOCK on file '%s'.", w->id, webfilename);
383
384     // pick a Content-Type for the file
385          if(strstr(filename, ".html") != NULL)  w->response.data->contenttype = CT_TEXT_HTML;
386     else if(strstr(filename, ".js")   != NULL)  w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
387     else if(strstr(filename, ".css")  != NULL)  w->response.data->contenttype = CT_TEXT_CSS;
388     else if(strstr(filename, ".xml")  != NULL)  w->response.data->contenttype = CT_TEXT_XML;
389     else if(strstr(filename, ".xsl")  != NULL)  w->response.data->contenttype = CT_TEXT_XSL;
390     else if(strstr(filename, ".txt")  != NULL)  w->response.data->contenttype = CT_TEXT_PLAIN;
391     else if(strstr(filename, ".svg")  != NULL)  w->response.data->contenttype = CT_IMAGE_SVG_XML;
392     else if(strstr(filename, ".ttf")  != NULL)  w->response.data->contenttype = CT_APPLICATION_X_FONT_TRUETYPE;
393     else if(strstr(filename, ".otf")  != NULL)  w->response.data->contenttype = CT_APPLICATION_X_FONT_OPENTYPE;
394     else if(strstr(filename, ".woff2")!= NULL)  w->response.data->contenttype = CT_APPLICATION_FONT_WOFF2;
395     else if(strstr(filename, ".woff") != NULL)  w->response.data->contenttype = CT_APPLICATION_FONT_WOFF;
396     else if(strstr(filename, ".eot")  != NULL)  w->response.data->contenttype = CT_APPLICATION_VND_MS_FONTOBJ;
397     else if(strstr(filename, ".png")  != NULL)  w->response.data->contenttype = CT_IMAGE_PNG;
398     else if(strstr(filename, ".jpg")  != NULL)  w->response.data->contenttype = CT_IMAGE_JPG;
399     else if(strstr(filename, ".jpeg") != NULL)  w->response.data->contenttype = CT_IMAGE_JPG;
400     else if(strstr(filename, ".gif")  != NULL)  w->response.data->contenttype = CT_IMAGE_GIF;
401     else if(strstr(filename, ".bmp")  != NULL)  w->response.data->contenttype = CT_IMAGE_BMP;
402     else if(strstr(filename, ".ico")  != NULL)  w->response.data->contenttype = CT_IMAGE_XICON;
403     else if(strstr(filename, ".icns") != NULL)  w->response.data->contenttype = CT_IMAGE_ICNS;
404     else w->response.data->contenttype = CT_APPLICATION_OCTET_STREAM;
405
406     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);
407
408     w->mode = WEB_CLIENT_MODE_FILECOPY;
409     w->wait_receive = 1;
410     w->wait_send = 0;
411     buffer_flush(w->response.data);
412     w->response.rlen = stat.st_size;
413 #ifdef __APPLE__
414     w->response.data->date = stat.st_mtimespec.tv_sec;
415 #else
416     w->response.data->date = stat.st_mtim.tv_sec;
417 #endif /* __APPLE__ */
418     buffer_cacheable(w->response.data);
419
420     return 200;
421 }
422
423
424 #ifdef NETDATA_WITH_ZLIB
425 void web_client_enable_deflate(struct web_client *w, int gzip) {
426     if(unlikely(w->response.zinitialized)) {
427         debug(D_DEFLATE, "%llu: Compression has already be initialized for this client.", w->id);
428         return;
429     }
430
431     if(unlikely(w->response.sent)) {
432         error("%llu: Cannot enable compression in the middle of a conversation.", w->id);
433         return;
434     }
435
436     w->response.zstream.zalloc = Z_NULL;
437     w->response.zstream.zfree = Z_NULL;
438     w->response.zstream.opaque = Z_NULL;
439
440     w->response.zstream.next_in = (Bytef *)w->response.data->buffer;
441     w->response.zstream.avail_in = 0;
442     w->response.zstream.total_in = 0;
443
444     w->response.zstream.next_out = w->response.zbuffer;
445     w->response.zstream.avail_out = 0;
446     w->response.zstream.total_out = 0;
447
448     w->response.zstream.zalloc = Z_NULL;
449     w->response.zstream.zfree = Z_NULL;
450     w->response.zstream.opaque = Z_NULL;
451
452 //  if(deflateInit(&w->response.zstream, Z_DEFAULT_COMPRESSION) != Z_OK) {
453 //      error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
454 //      return;
455 //  }
456
457     // Select GZIP compression: windowbits = 15 + 16 = 31
458     if(deflateInit2(&w->response.zstream, web_gzip_level, Z_DEFLATED, 15 + ((gzip)?16:0), 8, web_gzip_strategy) != Z_OK) {
459         error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
460         return;
461     }
462
463     w->response.zsent = 0;
464     w->response.zoutput = 1;
465     w->response.zinitialized = 1;
466
467     debug(D_DEFLATE, "%llu: Initialized compression.", w->id);
468 }
469 #endif // NETDATA_WITH_ZLIB
470
471 void buffer_data_options2string(BUFFER *wb, uint32_t options) {
472     int count = 0;
473
474     if(options & RRDR_OPTION_NONZERO) {
475         if(count++) buffer_strcat(wb, " ");
476         buffer_strcat(wb, "nonzero");
477     }
478
479     if(options & RRDR_OPTION_REVERSED) {
480         if(count++) buffer_strcat(wb, " ");
481         buffer_strcat(wb, "flip");
482     }
483
484     if(options & RRDR_OPTION_JSON_WRAP) {
485         if(count++) buffer_strcat(wb, " ");
486         buffer_strcat(wb, "jsonwrap");
487     }
488
489     if(options & RRDR_OPTION_MIN2MAX) {
490         if(count++) buffer_strcat(wb, " ");
491         buffer_strcat(wb, "min2max");
492     }
493
494     if(options & RRDR_OPTION_MILLISECONDS) {
495         if(count++) buffer_strcat(wb, " ");
496         buffer_strcat(wb, "ms");
497     }
498
499     if(options & RRDR_OPTION_ABSOLUTE) {
500         if(count++) buffer_strcat(wb, " ");
501         buffer_strcat(wb, "absolute");
502     }
503
504     if(options & RRDR_OPTION_SECONDS) {
505         if(count++) buffer_strcat(wb, " ");
506         buffer_strcat(wb, "seconds");
507     }
508
509     if(options & RRDR_OPTION_NULL2ZERO) {
510         if(count++) buffer_strcat(wb, " ");
511         buffer_strcat(wb, "null2zero");
512     }
513
514     if(options & RRDR_OPTION_OBJECTSROWS) {
515         if(count++) buffer_strcat(wb, " ");
516         buffer_strcat(wb, "objectrows");
517     }
518
519     if(options & RRDR_OPTION_GOOGLE_JSON) {
520         if(count++) buffer_strcat(wb, " ");
521         buffer_strcat(wb, "google_json");
522     }
523
524     if(options & RRDR_OPTION_PERCENTAGE) {
525         if(count++) buffer_strcat(wb, " ");
526         buffer_strcat(wb, "percentage");
527     }
528
529     if(options & RRDR_OPTION_NOT_ALIGNED) {
530         if(count++) buffer_strcat(wb, " ");
531         buffer_strcat(wb, "unaligned");
532     }
533 }
534
535 uint32_t web_client_api_request_v1_data_options(char *o)
536 {
537     uint32_t ret = 0x00000000;
538     char *tok;
539
540     while(o && *o && (tok = mystrsep(&o, ", |"))) {
541         if(!*tok) continue;
542
543         if(!strcmp(tok, "nonzero"))
544             ret |= RRDR_OPTION_NONZERO;
545         else if(!strcmp(tok, "flip") || !strcmp(tok, "reversed") || !strcmp(tok, "reverse"))
546             ret |= RRDR_OPTION_REVERSED;
547         else if(!strcmp(tok, "jsonwrap"))
548             ret |= RRDR_OPTION_JSON_WRAP;
549         else if(!strcmp(tok, "min2max"))
550             ret |= RRDR_OPTION_MIN2MAX;
551         else if(!strcmp(tok, "ms") || !strcmp(tok, "milliseconds"))
552             ret |= RRDR_OPTION_MILLISECONDS;
553         else if(!strcmp(tok, "abs") || !strcmp(tok, "absolute") || !strcmp(tok, "absolute_sum") || !strcmp(tok, "absolute-sum"))
554             ret |= RRDR_OPTION_ABSOLUTE;
555         else if(!strcmp(tok, "seconds"))
556             ret |= RRDR_OPTION_SECONDS;
557         else if(!strcmp(tok, "null2zero"))
558             ret |= RRDR_OPTION_NULL2ZERO;
559         else if(!strcmp(tok, "objectrows"))
560             ret |= RRDR_OPTION_OBJECTSROWS;
561         else if(!strcmp(tok, "google_json"))
562             ret |= RRDR_OPTION_GOOGLE_JSON;
563         else if(!strcmp(tok, "percentage"))
564             ret |= RRDR_OPTION_PERCENTAGE;
565         else if(!strcmp(tok, "unaligned"))
566             ret |= RRDR_OPTION_NOT_ALIGNED;
567     }
568
569     return ret;
570 }
571
572 uint32_t web_client_api_request_v1_data_format(char *name)
573 {
574     if(!strcmp(name, DATASOURCE_FORMAT_DATATABLE_JSON)) // datatable
575         return DATASOURCE_DATATABLE_JSON;
576
577     else if(!strcmp(name, DATASOURCE_FORMAT_DATATABLE_JSONP)) // datasource
578         return DATASOURCE_DATATABLE_JSONP;
579
580     else if(!strcmp(name, DATASOURCE_FORMAT_JSON)) // json
581         return DATASOURCE_JSON;
582
583     else if(!strcmp(name, DATASOURCE_FORMAT_JSONP)) // jsonp
584         return DATASOURCE_JSONP;
585
586     else if(!strcmp(name, DATASOURCE_FORMAT_SSV)) // ssv
587         return DATASOURCE_SSV;
588
589     else if(!strcmp(name, DATASOURCE_FORMAT_CSV)) // csv
590         return DATASOURCE_CSV;
591
592     else if(!strcmp(name, DATASOURCE_FORMAT_TSV) || !strcmp(name, "tsv-excel")) // tsv
593         return DATASOURCE_TSV;
594
595     else if(!strcmp(name, DATASOURCE_FORMAT_HTML)) // html
596         return DATASOURCE_HTML;
597
598     else if(!strcmp(name, DATASOURCE_FORMAT_JS_ARRAY)) // array
599         return DATASOURCE_JS_ARRAY;
600
601     else if(!strcmp(name, DATASOURCE_FORMAT_SSV_COMMA)) // ssvcomma
602         return DATASOURCE_SSV_COMMA;
603
604     else if(!strcmp(name, DATASOURCE_FORMAT_CSV_JSON_ARRAY)) // csvjsonarray
605         return DATASOURCE_CSV_JSON_ARRAY;
606
607     return DATASOURCE_JSON;
608 }
609
610 uint32_t web_client_api_request_v1_data_google_format(char *name)
611 {
612     if(!strcmp(name, "json"))
613         return DATASOURCE_DATATABLE_JSONP;
614
615     else if(!strcmp(name, "html"))
616         return DATASOURCE_HTML;
617
618     else if(!strcmp(name, "csv"))
619         return DATASOURCE_CSV;
620
621     else if(!strcmp(name, "tsv-excel"))
622         return DATASOURCE_TSV;
623
624     return DATASOURCE_JSON;
625 }
626
627 const char *group_method2string(int group) {
628     switch(group) {
629         case GROUP_UNDEFINED:
630             return "";
631
632         case GROUP_AVERAGE:
633             return "average";
634
635         case GROUP_MIN:
636             return "min";
637
638         case GROUP_MAX:
639             return "max";
640
641         case GROUP_SUM:
642             return "sum";
643
644         case GROUP_INCREMENTAL_SUM:
645             return "incremental-sum";
646
647         default:
648             return "unknown-group-method";
649     }
650 }
651
652 int web_client_api_request_v1_data_group(char *name, int def)
653 {
654     if(!strcmp(name, "average"))
655         return GROUP_AVERAGE;
656
657     else if(!strcmp(name, "min"))
658         return GROUP_MIN;
659
660     else if(!strcmp(name, "max"))
661         return GROUP_MAX;
662
663     else if(!strcmp(name, "sum"))
664         return GROUP_SUM;
665
666     else if(!strcmp(name, "incremental-sum"))
667         return GROUP_INCREMENTAL_SUM;
668
669     return def;
670 }
671
672 int web_client_api_request_v1_alarms(RRDHOST *host, struct web_client *w, char *url)
673 {
674     int all = 0;
675
676     while(url) {
677         char *value = mystrsep(&url, "?&");
678         if (!value || !*value) continue;
679
680         if(!strcmp(value, "all")) all = 1;
681         else if(!strcmp(value, "active")) all = 0;
682     }
683
684     buffer_flush(w->response.data);
685     w->response.data->contenttype = CT_APPLICATION_JSON;
686     health_alarms2json(host, w->response.data, all);
687     return 200;
688 }
689
690 int web_client_api_request_v1_alarm_log(RRDHOST *host, struct web_client *w, char *url)
691 {
692     uint32_t after = 0;
693
694     while(url) {
695         char *value = mystrsep(&url, "?&");
696         if (!value || !*value) continue;
697
698         char *name = mystrsep(&value, "=");
699         if(!name || !*name) continue;
700         if(!value || !*value) continue;
701
702         if(!strcmp(name, "after")) after = (uint32_t)strtoul(value, NULL, 0);
703     }
704
705     buffer_flush(w->response.data);
706     w->response.data->contenttype = CT_APPLICATION_JSON;
707     health_alarm_log2json(host, w->response.data, after);
708     return 200;
709 }
710
711 int web_client_api_request_single_chart(RRDHOST *host, struct web_client *w, char *url, void callback(RRDSET *st, BUFFER *buf))
712 {
713     int ret = 400;
714     char *chart = NULL;
715
716     buffer_flush(w->response.data);
717
718     while(url) {
719         char *value = mystrsep(&url, "?&");
720         if(!value || !*value) continue;
721
722         char *name = mystrsep(&value, "=");
723         if(!name || !*name) continue;
724         if(!value || !*value) continue;
725
726         // name and value are now the parameters
727         // they are not null and not empty
728
729         if(!strcmp(name, "chart")) chart = value;
730         //else {
731         /// buffer_sprintf(w->response.data, "Unknown parameter '%s' in request.", name);
732         //  goto cleanup;
733         //}
734     }
735
736     if(!chart || !*chart) {
737         buffer_sprintf(w->response.data, "No chart id is given at the request.");
738         goto cleanup;
739     }
740
741     RRDSET *st = rrdset_find(host, chart);
742     if(!st) st = rrdset_find_byname(host, chart);
743     if(!st) {
744         buffer_strcat(w->response.data, "Chart is not found: ");
745         buffer_strcat_htmlescape(w->response.data, chart);
746         ret = 404;
747         goto cleanup;
748     }
749
750     w->response.data->contenttype = CT_APPLICATION_JSON;
751     callback(st, w->response.data);
752     return 200;
753
754     cleanup:
755     return ret;
756 }
757
758 int web_client_api_request_v1_alarm_variables(RRDHOST *host, struct web_client *w, char *url)
759 {
760     return web_client_api_request_single_chart(host, w, url, health_api_v1_chart_variables2json);
761 }
762
763 int web_client_api_request_v1_charts(RRDHOST *host, struct web_client *w, char *url)
764 {
765     (void)url;
766
767     buffer_flush(w->response.data);
768     w->response.data->contenttype = CT_APPLICATION_JSON;
769     rrd_stats_api_v1_charts(host, w->response.data);
770     return 200;
771 }
772
773 int web_client_api_request_v1_allmetrics(RRDHOST *host, struct web_client *w, char *url)
774 {
775     int format = ALLMETRICS_SHELL;
776
777     while(url) {
778         char *value = mystrsep(&url, "?&");
779         if (!value || !*value) continue;
780
781         char *name = mystrsep(&value, "=");
782         if(!name || !*name) continue;
783         if(!value || !*value) continue;
784
785         if(!strcmp(name, "format")) {
786             if(!strcmp(value, ALLMETRICS_FORMAT_SHELL))
787                 format = ALLMETRICS_SHELL;
788             else if(!strcmp(value, ALLMETRICS_FORMAT_PROMETHEUS))
789                 format = ALLMETRICS_PROMETHEUS;
790             else
791                 format = 0;
792         }
793     }
794
795     buffer_flush(w->response.data);
796     buffer_no_cacheable(w->response.data);
797
798     switch(format) {
799         case ALLMETRICS_SHELL:
800             w->response.data->contenttype = CT_TEXT_PLAIN;
801             rrd_stats_api_v1_charts_allmetrics_shell(host, w->response.data);
802             return 200;
803
804         case ALLMETRICS_PROMETHEUS:
805             w->response.data->contenttype = CT_PROMETHEUS;
806             rrd_stats_api_v1_charts_allmetrics_prometheus(host, w->response.data);
807             return 200;
808
809         default:
810             w->response.data->contenttype = CT_TEXT_PLAIN;
811             buffer_strcat(w->response.data, "Which format? Only '" ALLMETRICS_FORMAT_SHELL "' and '" ALLMETRICS_FORMAT_PROMETHEUS "' is currently supported.");
812             return 400;
813     }
814 }
815
816 int web_client_api_request_v1_chart(RRDHOST *host, struct web_client *w, char *url)
817 {
818     return web_client_api_request_single_chart(host, w, url, rrd_stats_api_v1_chart);
819 }
820
821 int web_client_api_request_v1_badge(RRDHOST *host, struct web_client *w, char *url) {
822     int ret = 400;
823     buffer_flush(w->response.data);
824
825     BUFFER *dimensions = NULL;
826     
827     const char *chart = NULL
828             , *before_str = NULL
829             , *after_str = NULL
830             , *points_str = NULL
831             , *multiply_str = NULL
832             , *divide_str = NULL
833             , *label = NULL
834             , *units = NULL
835             , *label_color = NULL
836             , *value_color = NULL
837             , *refresh_str = NULL
838             , *precision_str = NULL
839             , *alarm = NULL;
840
841     int group = GROUP_AVERAGE;
842     uint32_t options = 0x00000000;
843
844     while(url) {
845         char *value = mystrsep(&url, "/?&");
846         if(!value || !*value) continue;
847
848         char *name = mystrsep(&value, "=");
849         if(!name || !*name) continue;
850         if(!value || !*value) continue;
851
852         debug(D_WEB_CLIENT, "%llu: API v1 badge.svg query param '%s' with value '%s'", w->id, name, value);
853
854         // name and value are now the parameters
855         // they are not null and not empty
856
857         if(!strcmp(name, "chart")) chart = value;
858         else if(!strcmp(name, "dimension") || !strcmp(name, "dim") || !strcmp(name, "dimensions") || !strcmp(name, "dims")) {
859             if(!dimensions)
860                 dimensions = buffer_create(100);
861
862             buffer_strcat(dimensions, "|");
863             buffer_strcat(dimensions, value);
864         }
865         else if(!strcmp(name, "after")) after_str = value;
866         else if(!strcmp(name, "before")) before_str = value;
867         else if(!strcmp(name, "points")) points_str = value;
868         else if(!strcmp(name, "group")) {
869             group = web_client_api_request_v1_data_group(value, GROUP_AVERAGE);
870         }
871         else if(!strcmp(name, "options")) {
872             options |= web_client_api_request_v1_data_options(value);
873         }
874         else if(!strcmp(name, "label")) label = value;
875         else if(!strcmp(name, "units")) units = value;
876         else if(!strcmp(name, "label_color")) label_color = value;
877         else if(!strcmp(name, "value_color")) value_color = value;
878         else if(!strcmp(name, "multiply")) multiply_str = value;
879         else if(!strcmp(name, "divide")) divide_str = value;
880         else if(!strcmp(name, "refresh")) refresh_str = value;
881         else if(!strcmp(name, "precision")) precision_str = value;
882         else if(!strcmp(name, "alarm")) alarm = value;
883     }
884
885     if(!chart || !*chart) {
886         buffer_no_cacheable(w->response.data);
887         buffer_sprintf(w->response.data, "No chart id is given at the request.");
888         goto cleanup;
889     }
890
891     RRDSET *st = rrdset_find(host, chart);
892     if(!st) st = rrdset_find_byname(host, chart);
893     if(!st) {
894         buffer_no_cacheable(w->response.data);
895         buffer_svg(w->response.data, "chart not found", NAN, "", NULL, NULL, -1);
896         ret = 200;
897         goto cleanup;
898     }
899
900     RRDCALC *rc = NULL;
901     if(alarm) {
902         rc = rrdcalc_find(st, alarm);
903         if (!rc) {
904             buffer_no_cacheable(w->response.data);
905             buffer_svg(w->response.data, "alarm not found", NAN, "", NULL, NULL, -1);
906             ret = 200;
907             goto cleanup;
908         }
909     }
910
911     long long multiply  = (multiply_str  && *multiply_str )?str2l(multiply_str):1;
912     long long divide    = (divide_str    && *divide_str   )?str2l(divide_str):1;
913     long long before    = (before_str    && *before_str   )?str2l(before_str):0;
914     long long after     = (after_str     && *after_str    )?str2l(after_str):-st->update_every;
915     int       points    = (points_str    && *points_str   )?str2i(points_str):1;
916     int       precision = (precision_str && *precision_str)?str2i(precision_str):-1;
917
918     if(!multiply) multiply = 1;
919     if(!divide) divide = 1;
920
921     int refresh = 0;
922     if(refresh_str && *refresh_str) {
923         if(!strcmp(refresh_str, "auto")) {
924             if(rc) refresh = rc->update_every;
925             else if(options & RRDR_OPTION_NOT_ALIGNED)
926                 refresh = st->update_every;
927             else {
928                 refresh = (int)(before - after);
929                 if(refresh < 0) refresh = -refresh;
930             }
931         }
932         else {
933             refresh = str2i(refresh_str);
934             if(refresh < 0) refresh = -refresh;
935         }
936     }
937
938     if(!label) {
939         if(alarm) {
940             char *s = (char *)alarm;
941             while(*s) {
942                 if(*s == '_') *s = ' ';
943                 s++;
944             }
945             label = alarm;
946         }
947         else if(dimensions) {
948             const char *dim = buffer_tostring(dimensions);
949             if(*dim == '|') dim++;
950             label = dim;
951         }
952         else
953             label = st->name;
954     }
955     if(!units) {
956         if(alarm) {
957             if(rc->units)
958                 units = rc->units;
959             else
960                 units = "";
961         }
962         else if(options & RRDR_OPTION_PERCENTAGE)
963             units = "%";
964         else
965             units = st->units;
966     }
967
968     debug(D_WEB_CLIENT, "%llu: API command 'badge.svg' for chart '%s', alarm '%s', dimensions '%s', after '%lld', before '%lld', points '%d', group '%d', options '0x%08x'"
969             , w->id
970             , chart
971             , alarm?alarm:""
972             , (dimensions)?buffer_tostring(dimensions):""
973             , after
974             , before
975             , points
976             , group
977             , options
978             );
979
980     if(rc) {
981         if (refresh > 0) {
982             buffer_sprintf(w->response.header, "Refresh: %d\r\n", refresh);
983             w->response.data->expires = now_realtime_sec() + refresh;
984         }
985         else buffer_no_cacheable(w->response.data);
986
987         if(!value_color) {
988             switch(rc->status) {
989                 case RRDCALC_STATUS_CRITICAL:
990                     value_color = "red";
991                     break;
992
993                 case RRDCALC_STATUS_WARNING:
994                     value_color = "orange";
995                     break;
996
997                 case RRDCALC_STATUS_CLEAR:
998                     value_color = "brightgreen";
999                     break;
1000
1001                 case RRDCALC_STATUS_UNDEFINED:
1002                     value_color = "lightgrey";
1003                     break;
1004
1005                 case RRDCALC_STATUS_UNINITIALIZED:
1006                     value_color = "#000";
1007                     break;
1008
1009                 default:
1010                     value_color = "grey";
1011                     break;
1012             }
1013         }
1014
1015         buffer_svg(w->response.data,
1016                 label,
1017                 (isnan(rc->value)||isinf(rc->value)) ? rc->value : rc->value * multiply / divide,
1018                 units,
1019                 label_color,
1020                 value_color,
1021                 precision);
1022         ret = 200;
1023     }
1024     else {
1025         time_t latest_timestamp = 0;
1026         int value_is_null = 1;
1027         calculated_number n = NAN;
1028         ret = 500;
1029
1030         // if the collected value is too old, don't calculate its value
1031         if (rrdset_last_entry_t(st) >= (now_realtime_sec() - (st->update_every * st->gap_when_lost_iterations_above)))
1032             ret = rrd2value(st,
1033                             w->response.data,
1034                             &n,
1035                             (dimensions) ? buffer_tostring(dimensions) : NULL,
1036                             points,
1037                             after,
1038                             before,
1039                             group,
1040                             options,
1041                             NULL,
1042                             &latest_timestamp,
1043                             &value_is_null);
1044
1045         // if the value cannot be calculated, show empty badge
1046         if (ret != 200) {
1047             buffer_no_cacheable(w->response.data);
1048             value_is_null = 1;
1049             n = 0;
1050             ret = 200;
1051         }
1052         else if (refresh > 0) {
1053             buffer_sprintf(w->response.header, "Refresh: %d\r\n", refresh);
1054             w->response.data->expires = now_realtime_sec() + refresh;
1055         }
1056         else buffer_no_cacheable(w->response.data);
1057
1058         // render the badge
1059         buffer_svg(w->response.data,
1060                 label,
1061                 (value_is_null)?NAN:(n * multiply / divide),
1062                 units,
1063                 label_color,
1064                 value_color,
1065                 precision);
1066     }
1067
1068 cleanup:
1069     if(dimensions)
1070         buffer_free(dimensions);
1071     return ret;
1072 }
1073
1074 // returns the HTTP code
1075 int web_client_api_request_v1_data(RRDHOST *host, struct web_client *w, char *url)
1076 {
1077     debug(D_WEB_CLIENT, "%llu: API v1 data with URL '%s'", w->id, url);
1078
1079     int ret = 400;
1080     BUFFER *dimensions = NULL;
1081
1082     buffer_flush(w->response.data);
1083
1084     char    *google_version = "0.6",
1085             *google_reqId = "0",
1086             *google_sig = "0",
1087             *google_out = "json",
1088             *responseHandler = NULL,
1089             *outFileName = NULL;
1090
1091     time_t last_timestamp_in_data = 0, google_timestamp = 0;
1092
1093     char *chart = NULL
1094             , *before_str = NULL
1095             , *after_str = NULL
1096             , *points_str = NULL;
1097
1098     int group = GROUP_AVERAGE;
1099     uint32_t format = DATASOURCE_JSON;
1100     uint32_t options = 0x00000000;
1101
1102     while(url) {
1103         char *value = mystrsep(&url, "?&");
1104         if(!value || !*value) continue;
1105
1106         char *name = mystrsep(&value, "=");
1107         if(!name || !*name) continue;
1108         if(!value || !*value) continue;
1109
1110         debug(D_WEB_CLIENT, "%llu: API v1 data query param '%s' with value '%s'", w->id, name, value);
1111
1112         // name and value are now the parameters
1113         // they are not null and not empty
1114
1115         if(!strcmp(name, "chart")) chart = value;
1116         else if(!strcmp(name, "dimension") || !strcmp(name, "dim") || !strcmp(name, "dimensions") || !strcmp(name, "dims")) {
1117             if(!dimensions) dimensions = buffer_create(100);
1118             buffer_strcat(dimensions, "|");
1119             buffer_strcat(dimensions, value);
1120         }
1121         else if(!strcmp(name, "after")) after_str = value;
1122         else if(!strcmp(name, "before")) before_str = value;
1123         else if(!strcmp(name, "points")) points_str = value;
1124         else if(!strcmp(name, "group")) {
1125             group = web_client_api_request_v1_data_group(value, GROUP_AVERAGE);
1126         }
1127         else if(!strcmp(name, "format")) {
1128             format = web_client_api_request_v1_data_format(value);
1129         }
1130         else if(!strcmp(name, "options")) {
1131             options |= web_client_api_request_v1_data_options(value);
1132         }
1133         else if(!strcmp(name, "callback")) {
1134             responseHandler = value;
1135         }
1136         else if(!strcmp(name, "filename")) {
1137             outFileName = value;
1138         }
1139         else if(!strcmp(name, "tqx")) {
1140             // parse Google Visualization API options
1141             // https://developers.google.com/chart/interactive/docs/dev/implementing_data_source
1142             char *tqx_name, *tqx_value;
1143
1144             while(value) {
1145                 tqx_value = mystrsep(&value, ";");
1146                 if(!tqx_value || !*tqx_value) continue;
1147
1148                 tqx_name = mystrsep(&tqx_value, ":");
1149                 if(!tqx_name || !*tqx_name) continue;
1150                 if(!tqx_value || !*tqx_value) continue;
1151
1152                 if(!strcmp(tqx_name, "version"))
1153                     google_version = tqx_value;
1154                 else if(!strcmp(tqx_name, "reqId"))
1155                     google_reqId = tqx_value;
1156                 else if(!strcmp(tqx_name, "sig")) {
1157                     google_sig = tqx_value;
1158                     google_timestamp = strtoul(google_sig, NULL, 0);
1159                 }
1160                 else if(!strcmp(tqx_name, "out")) {
1161                     google_out = tqx_value;
1162                     format = web_client_api_request_v1_data_google_format(google_out);
1163                 }
1164                 else if(!strcmp(tqx_name, "responseHandler"))
1165                     responseHandler = tqx_value;
1166                 else if(!strcmp(tqx_name, "outFileName"))
1167                     outFileName = tqx_value;
1168             }
1169         }
1170     }
1171
1172     if(!chart || !*chart) {
1173         buffer_sprintf(w->response.data, "No chart id is given at the request.");
1174         goto cleanup;
1175     }
1176
1177     RRDSET *st = rrdset_find(host, chart);
1178     if(!st) st = rrdset_find_byname(host, chart);
1179     if(!st) {
1180         buffer_strcat(w->response.data, "Chart is not found: ");
1181         buffer_strcat_htmlescape(w->response.data, chart);
1182         ret = 404;
1183         goto cleanup;
1184     }
1185
1186     long long before = (before_str && *before_str)?str2l(before_str):0;
1187     long long after  = (after_str  && *after_str) ?str2l(after_str):0;
1188     int       points = (points_str && *points_str)?str2i(points_str):0;
1189
1190     debug(D_WEB_CLIENT, "%llu: API command 'data' for chart '%s', dimensions '%s', after '%lld', before '%lld', points '%d', group '%d', format '%u', options '0x%08x'"
1191             , w->id
1192             , chart
1193             , (dimensions)?buffer_tostring(dimensions):""
1194             , after
1195             , before
1196             , points
1197             , group
1198             , format
1199             , options
1200             );
1201
1202     if(outFileName && *outFileName) {
1203         buffer_sprintf(w->response.header, "Content-Disposition: attachment; filename=\"%s\"\r\n", outFileName);
1204         debug(D_WEB_CLIENT, "%llu: generating outfilename header: '%s'", w->id, outFileName);
1205     }
1206
1207     if(format == DATASOURCE_DATATABLE_JSONP) {
1208         if(responseHandler == NULL)
1209             responseHandler = "google.visualization.Query.setResponse";
1210
1211         debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSON/JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
1212                 w->id, google_version, google_reqId, google_sig, google_out, responseHandler, outFileName
1213             );
1214
1215         buffer_sprintf(w->response.data,
1216             "%s({version:'%s',reqId:'%s',status:'ok',sig:'%ld',table:",
1217             responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
1218     }
1219     else if(format == DATASOURCE_JSONP) {
1220         if(responseHandler == NULL)
1221             responseHandler = "callback";
1222
1223         buffer_strcat(w->response.data, responseHandler);
1224         buffer_strcat(w->response.data, "(");
1225     }
1226
1227     ret = rrd2format(st, w->response.data, dimensions, format, points, after, before, group, options, &last_timestamp_in_data);
1228
1229     if(format == DATASOURCE_DATATABLE_JSONP) {
1230         if(google_timestamp < last_timestamp_in_data)
1231             buffer_strcat(w->response.data, "});");
1232
1233         else {
1234             // the client already has the latest data
1235             buffer_flush(w->response.data);
1236             buffer_sprintf(w->response.data,
1237                 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
1238                 responseHandler, google_version, google_reqId);
1239         }
1240     }
1241     else if(format == DATASOURCE_JSONP)
1242         buffer_strcat(w->response.data, ");");
1243
1244 cleanup:
1245     if(dimensions) buffer_free(dimensions);
1246     return ret;
1247 }
1248
1249
1250 int web_client_api_request_v1_registry(RRDHOST *host, struct web_client *w, char *url)
1251 {
1252     static uint32_t hash_action = 0, hash_access = 0, hash_hello = 0, hash_delete = 0, hash_search = 0,
1253             hash_switch = 0, hash_machine = 0, hash_url = 0, hash_name = 0, hash_delete_url = 0, hash_for = 0,
1254             hash_to = 0 /*, hash_redirects = 0 */;
1255
1256     if(unlikely(!hash_action)) {
1257         hash_action = simple_hash("action");
1258         hash_access = simple_hash("access");
1259         hash_hello = simple_hash("hello");
1260         hash_delete = simple_hash("delete");
1261         hash_search = simple_hash("search");
1262         hash_switch = simple_hash("switch");
1263         hash_machine = simple_hash("machine");
1264         hash_url = simple_hash("url");
1265         hash_name = simple_hash("name");
1266         hash_delete_url = simple_hash("delete_url");
1267         hash_for = simple_hash("for");
1268         hash_to = simple_hash("to");
1269 /*
1270         hash_redirects = simple_hash("redirects");
1271 */
1272     }
1273
1274     char person_guid[GUID_LEN + 1] = "";
1275
1276     debug(D_WEB_CLIENT, "%llu: API v1 registry with URL '%s'", w->id, url);
1277
1278     // FIXME
1279     // The browser may send multiple cookies with our id
1280     
1281     char *cookie = strstr(w->response.data->buffer, NETDATA_REGISTRY_COOKIE_NAME "=");
1282     if(cookie)
1283         strncpyz(person_guid, &cookie[sizeof(NETDATA_REGISTRY_COOKIE_NAME)], 36);
1284
1285     char action = '\0';
1286     char *machine_guid = NULL,
1287             *machine_url = NULL,
1288             *url_name = NULL,
1289             *search_machine_guid = NULL,
1290             *delete_url = NULL,
1291             *to_person_guid = NULL;
1292 /*
1293     int redirects = 0;
1294 */
1295
1296     while(url) {
1297         char *value = mystrsep(&url, "?&");
1298         if (!value || !*value) continue;
1299
1300         char *name = mystrsep(&value, "=");
1301         if (!name || !*name) continue;
1302         if (!value || !*value) continue;
1303
1304         debug(D_WEB_CLIENT, "%llu: API v1 registry query param '%s' with value '%s'", w->id, name, value);
1305
1306         uint32_t hash = simple_hash(name);
1307
1308         if(hash == hash_action && !strcmp(name, "action")) {
1309             uint32_t vhash = simple_hash(value);
1310
1311             if(vhash == hash_access && !strcmp(value, "access")) action = 'A';
1312             else if(vhash == hash_hello && !strcmp(value, "hello")) action = 'H';
1313             else if(vhash == hash_delete && !strcmp(value, "delete")) action = 'D';
1314             else if(vhash == hash_search && !strcmp(value, "search")) action = 'S';
1315             else if(vhash == hash_switch && !strcmp(value, "switch")) action = 'W';
1316 #ifdef NETDATA_INTERNAL_CHECKS
1317             else error("unknown registry action '%s'", value);
1318 #endif /* NETDATA_INTERNAL_CHECKS */
1319         }
1320 /*
1321         else if(hash == hash_redirects && !strcmp(name, "redirects"))
1322             redirects = atoi(value);
1323 */
1324         else if(hash == hash_machine && !strcmp(name, "machine"))
1325             machine_guid = value;
1326
1327         else if(hash == hash_url && !strcmp(name, "url"))
1328             machine_url = value;
1329
1330         else if(action == 'A') {
1331             if(hash == hash_name && !strcmp(name, "name"))
1332                 url_name = value;
1333         }
1334         else if(action == 'D') {
1335             if(hash == hash_delete_url && !strcmp(name, "delete_url"))
1336                 delete_url = value;
1337         }
1338         else if(action == 'S') {
1339             if(hash == hash_for && !strcmp(name, "for"))
1340                 search_machine_guid = value;
1341         }
1342         else if(action == 'W') {
1343             if(hash == hash_to && !strcmp(name, "to"))
1344                 to_person_guid = value;
1345         }
1346 #ifdef NETDATA_INTERNAL_CHECKS
1347         else error("unused registry URL parameter '%s' with value '%s'", name, value);
1348 #endif /* NETDATA_INTERNAL_CHECKS */
1349     }
1350
1351     if(respect_web_browser_do_not_track_policy && w->donottrack) {
1352         buffer_flush(w->response.data);
1353         buffer_sprintf(w->response.data, "Your web browser is sending 'DNT: 1' (Do Not Track). The registry requires persistent cookies on your browser to work.");
1354         return 400;
1355     }
1356
1357     if(action == 'A' && (!machine_guid || !machine_url || !url_name)) {
1358         error("Invalid registry request - access requires these parameters: machine ('%s'), url ('%s'), name ('%s')",
1359                 machine_guid?machine_guid:"UNSET", machine_url?machine_url:"UNSET", url_name?url_name:"UNSET");
1360         buffer_flush(w->response.data);
1361         buffer_strcat(w->response.data, "Invalid registry Access request.");
1362         return 400;
1363     }
1364     else if(action == 'D' && (!machine_guid || !machine_url || !delete_url)) {
1365         error("Invalid registry request - delete requires these parameters: machine ('%s'), url ('%s'), delete_url ('%s')",
1366                 machine_guid?machine_guid:"UNSET", machine_url?machine_url:"UNSET", delete_url?delete_url:"UNSET");
1367         buffer_flush(w->response.data);
1368         buffer_strcat(w->response.data, "Invalid registry Delete request.");
1369         return 400;
1370     }
1371     else if(action == 'S' && (!machine_guid || !machine_url || !search_machine_guid)) {
1372         error("Invalid registry request - search requires these parameters: machine ('%s'), url ('%s'), for ('%s')",
1373                 machine_guid?machine_guid:"UNSET", machine_url?machine_url:"UNSET", search_machine_guid?search_machine_guid:"UNSET");
1374         buffer_flush(w->response.data);
1375         buffer_strcat(w->response.data, "Invalid registry Search request.");
1376         return 400;
1377     }
1378     else if(action == 'W' && (!machine_guid || !machine_url || !to_person_guid)) {
1379         error("Invalid registry request - switching identity requires these parameters: machine ('%s'), url ('%s'), to ('%s')",
1380                 machine_guid?machine_guid:"UNSET", machine_url?machine_url:"UNSET", to_person_guid?to_person_guid:"UNSET");
1381         buffer_flush(w->response.data);
1382         buffer_strcat(w->response.data, "Invalid registry Switch request.");
1383         return 400;
1384     }
1385
1386     switch(action) {
1387         case 'A':
1388             w->tracking_required = 1;
1389             return registry_request_access_json(host, w, person_guid, machine_guid, machine_url, url_name, now_realtime_sec());
1390
1391         case 'D':
1392             w->tracking_required = 1;
1393             return registry_request_delete_json(host, w, person_guid, machine_guid, machine_url, delete_url, now_realtime_sec());
1394
1395         case 'S':
1396             w->tracking_required = 1;
1397             return registry_request_search_json(host, w, person_guid, machine_guid, machine_url, search_machine_guid, now_realtime_sec());
1398
1399         case 'W':
1400             w->tracking_required = 1;
1401             return registry_request_switch_json(host, w, person_guid, machine_guid, machine_url, to_person_guid, now_realtime_sec());
1402
1403         case 'H':
1404             return registry_request_hello_json(host, w);
1405
1406         default:
1407             buffer_flush(w->response.data);
1408             buffer_strcat(w->response.data, "Invalid registry request - you need to set an action: hello, access, delete, search");
1409             return 400;
1410     }
1411 }
1412
1413 int web_client_api_request_v1(RRDHOST *host, struct web_client *w, char *url) {
1414     static uint32_t hash_data = 0, hash_chart = 0, hash_charts = 0, hash_registry = 0, hash_badge = 0, hash_alarms = 0, hash_alarm_log = 0, hash_alarm_variables = 0, hash_raw = 0;
1415
1416     if(unlikely(hash_data == 0)) {
1417         hash_data = simple_hash("data");
1418         hash_chart = simple_hash("chart");
1419         hash_charts = simple_hash("charts");
1420         hash_registry = simple_hash("registry");
1421         hash_badge = simple_hash("badge.svg");
1422         hash_alarms = simple_hash("alarms");
1423         hash_alarm_log = simple_hash("alarm_log");
1424         hash_alarm_variables = simple_hash("alarm_variables");
1425         hash_raw = simple_hash("allmetrics");
1426     }
1427
1428     // get the command
1429     char *tok = mystrsep(&url, "/?&");
1430     if(tok && *tok) {
1431         debug(D_WEB_CLIENT, "%llu: Searching for API v1 command '%s'.", w->id, tok);
1432         uint32_t hash = simple_hash(tok);
1433
1434         if(hash == hash_data && !strcmp(tok, "data"))
1435             return web_client_api_request_v1_data(host, w, url);
1436
1437         else if(hash == hash_chart && !strcmp(tok, "chart"))
1438             return web_client_api_request_v1_chart(host, w, url);
1439
1440         else if(hash == hash_charts && !strcmp(tok, "charts"))
1441             return web_client_api_request_v1_charts(host, w, url);
1442
1443         else if(hash == hash_registry && !strcmp(tok, "registry"))
1444             return web_client_api_request_v1_registry(host, w, url);
1445
1446         else if(hash == hash_badge && !strcmp(tok, "badge.svg"))
1447             return web_client_api_request_v1_badge(host, w, url);
1448
1449         else if(hash == hash_alarms && !strcmp(tok, "alarms"))
1450             return web_client_api_request_v1_alarms(host, w, url);
1451
1452         else if(hash == hash_alarm_log && !strcmp(tok, "alarm_log"))
1453             return web_client_api_request_v1_alarm_log(host, w, url);
1454
1455         else if(hash == hash_alarm_variables && !strcmp(tok, "alarm_variables"))
1456             return web_client_api_request_v1_alarm_variables(host, w, url);
1457
1458         else if(hash == hash_raw && !strcmp(tok, "allmetrics"))
1459             return web_client_api_request_v1_allmetrics(host, w, url);
1460
1461         else {
1462             buffer_flush(w->response.data);
1463             buffer_strcat(w->response.data, "Unsupported v1 API command: ");
1464             buffer_strcat_htmlescape(w->response.data, tok);
1465             return 404;
1466         }
1467     }
1468     else {
1469         buffer_flush(w->response.data);
1470         buffer_sprintf(w->response.data, "Which API v1 command?");
1471         return 400;
1472     }
1473 }
1474
1475 int web_client_api_request(RRDHOST *host, struct web_client *w, char *url)
1476 {
1477     // get the api version
1478     char *tok = mystrsep(&url, "/?&");
1479     if(tok && *tok) {
1480         debug(D_WEB_CLIENT, "%llu: Searching for API version '%s'.", w->id, tok);
1481         if(strcmp(tok, "v1") == 0)
1482             return web_client_api_request_v1(host, w, url);
1483         else {
1484             buffer_flush(w->response.data);
1485             buffer_strcat(w->response.data, "Unsupported API version: ");
1486             buffer_strcat_htmlescape(w->response.data, tok);
1487             return 404;
1488         }
1489     }
1490     else {
1491         buffer_flush(w->response.data);
1492         buffer_sprintf(w->response.data, "Which API version?");
1493         return 400;
1494     }
1495 }
1496
1497 int web_client_api_old_data_request(RRDHOST *host, struct web_client *w, char *url, int datasource_type)
1498 {
1499     if(!url || !*url) {
1500         buffer_flush(w->response.data);
1501         buffer_sprintf(w->response.data, "Incomplete request.");
1502         return 400;
1503     }
1504
1505     RRDSET *st = NULL;
1506
1507     char *args = strchr(url, '?');
1508     if(args) {
1509         *args='\0';
1510         args = &args[1];
1511     }
1512
1513     // get the name of the data to show
1514     char *tok = mystrsep(&url, "/");
1515     if(!tok) tok = "";
1516
1517     // do we have such a data set?
1518     if(*tok) {
1519         debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1520         st = rrdset_find_byname(host, tok);
1521         if(!st) st = rrdset_find(host, tok);
1522     }
1523
1524     if(!st) {
1525         // we don't have it
1526         // try to send a file with that name
1527         buffer_flush(w->response.data);
1528         return(mysendfile(w, tok));
1529     }
1530
1531     // we have it
1532     debug(D_WEB_CLIENT, "%llu: Found RRD data with name '%s'.", w->id, tok);
1533
1534     // how many entries does the client want?
1535     int lines = (int)st->entries;
1536     int group_count = 1;
1537     time_t after = 0, before = 0;
1538     int group_method = GROUP_AVERAGE;
1539     int nonzero = 0;
1540
1541     if(url) {
1542         // parse the lines required
1543         tok = mystrsep(&url, "/");
1544         if(tok) lines = str2i(tok);
1545         if(lines < 1) lines = 1;
1546     }
1547     if(url) {
1548         // parse the group count required
1549         tok = mystrsep(&url, "/");
1550         if(tok && *tok) group_count = str2i(tok);
1551         if(group_count < 1) group_count = 1;
1552         //if(group_count > save_history / 20) group_count = save_history / 20;
1553     }
1554     if(url) {
1555         // parse the grouping method required
1556         tok = mystrsep(&url, "/");
1557         if(tok && *tok) {
1558             if(strcmp(tok, "max") == 0) group_method = GROUP_MAX;
1559             else if(strcmp(tok, "average") == 0) group_method = GROUP_AVERAGE;
1560             else if(strcmp(tok, "sum") == 0) group_method = GROUP_SUM;
1561             else debug(D_WEB_CLIENT, "%llu: Unknown group method '%s'", w->id, tok);
1562         }
1563     }
1564     if(url) {
1565         // parse after time
1566         tok = mystrsep(&url, "/");
1567         if(tok && *tok) after = str2ul(tok);
1568         if(after < 0) after = 0;
1569     }
1570     if(url) {
1571         // parse before time
1572         tok = mystrsep(&url, "/");
1573         if(tok && *tok) before = str2ul(tok);
1574         if(before < 0) before = 0;
1575     }
1576     if(url) {
1577         // parse nonzero
1578         tok = mystrsep(&url, "/");
1579         if(tok && *tok && strcmp(tok, "nonzero") == 0) nonzero = 1;
1580     }
1581
1582     w->response.data->contenttype = CT_APPLICATION_JSON;
1583     buffer_flush(w->response.data);
1584
1585     char *google_version = "0.6";
1586     char *google_reqId = "0";
1587     char *google_sig = "0";
1588     char *google_out = "json";
1589     char *google_responseHandler = "google.visualization.Query.setResponse";
1590     char *google_outFileName = NULL;
1591     time_t last_timestamp_in_data = 0;
1592     if(datasource_type == DATASOURCE_DATATABLE_JSON || datasource_type == DATASOURCE_DATATABLE_JSONP) {
1593
1594         w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
1595
1596         while(args) {
1597             tok = mystrsep(&args, "&");
1598             if(tok && *tok) {
1599                 char *name = mystrsep(&tok, "=");
1600                 if(name && *name && strcmp(name, "tqx") == 0) {
1601                     char *key = mystrsep(&tok, ":");
1602                     char *value = mystrsep(&tok, ";");
1603                     if(key && value && *key && *value) {
1604                         if(strcmp(key, "version") == 0)
1605                             google_version = value;
1606
1607                         else if(strcmp(key, "reqId") == 0)
1608                             google_reqId = value;
1609
1610                         else if(strcmp(key, "sig") == 0)
1611                             google_sig = value;
1612
1613                         else if(strcmp(key, "out") == 0)
1614                             google_out = value;
1615
1616                         else if(strcmp(key, "responseHandler") == 0)
1617                             google_responseHandler = value;
1618
1619                         else if(strcmp(key, "outFileName") == 0)
1620                             google_outFileName = value;
1621                     }
1622                 }
1623             }
1624         }
1625
1626         debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
1627             w->id, google_version, google_reqId, google_sig, google_out, google_responseHandler, google_outFileName
1628             );
1629
1630         if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
1631             last_timestamp_in_data = strtoul(google_sig, NULL, 0);
1632
1633             // check the client wants json
1634             if(strcmp(google_out, "json") != 0) {
1635                 buffer_sprintf(w->response.data,
1636                     "%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.'}]});",
1637                     google_responseHandler, google_version, google_reqId, google_out);
1638                     return 200;
1639             }
1640         }
1641     }
1642
1643     if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
1644         buffer_sprintf(w->response.data,
1645             "%s({version:'%s',reqId:'%s',status:'ok',sig:'%ld',table:",
1646             google_responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
1647     }
1648
1649     debug(D_WEB_CLIENT_ACCESS, "%llu: Sending RRD data '%s' (id %s, %d lines, %d group, %d group_method, %ld after, %ld before).",
1650         w->id, st->name, st->id, lines, group_count, group_method, after, before);
1651
1652     time_t timestamp_in_data = rrd_stats_json(datasource_type, st, w->response.data, lines, group_count, group_method, (unsigned long)after, (unsigned long)before, nonzero);
1653
1654     if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
1655         if(timestamp_in_data > last_timestamp_in_data)
1656             buffer_strcat(w->response.data, "});");
1657
1658         else {
1659             // the client already has the latest data
1660             buffer_flush(w->response.data);
1661             buffer_sprintf(w->response.data,
1662                 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
1663                 google_responseHandler, google_version, google_reqId);
1664         }
1665     }
1666
1667     return 200;
1668 }
1669
1670 int validate_stream_api_key(const char *key) {
1671     return 0;
1672 }
1673
1674 int web_client_stream_request(RRDHOST *host, struct web_client *w, char *url) {
1675     info("STREAM request from client '%s:%s', starting as host '%s'", w->client_ip, w->client_port, host->hostname);
1676
1677     char *key = NULL;
1678
1679     while(url) {
1680         char *value = mystrsep(&url, "?&");
1681         if(!value || !*value) continue;
1682
1683         char *name = mystrsep(&value, "=");
1684         if(!name || !*name) continue;
1685         if(!value || !*value) continue;
1686
1687         if(!strcmp(name, "key"))
1688             key = value;
1689     }
1690
1691     if(!key || !*key) {
1692         error("STREAM [%s]:%s: request without an API key. Forbidding access.", w->client_ip, w->client_port);
1693         buffer_flush(w->response.data);
1694         buffer_sprintf(w->response.data, "You need an API key for this request.");
1695         return 401;
1696     }
1697
1698     if(!validate_stream_api_key(key)) {
1699         error("STREAM [%s]:%s: API key '%s' is not allowed. Forbidding access.", w->client_ip, w->client_port, key);
1700         buffer_flush(w->response.data);
1701         buffer_sprintf(w->response.data, "Your API key is not permitted access.");
1702         return 401;
1703     }
1704
1705     struct plugind cd = {
1706             .enabled = 1,
1707             .update_every = default_rrd_update_every,
1708             .pid = 0,
1709             .serial_failures = 0,
1710             .successful_collections = 0,
1711             .obsolete = 0,
1712             .started_t = now_realtime_sec(),
1713             .next = NULL,
1714     };
1715
1716     // put the client IP and port into the buffers used by plugins.d
1717     snprintfz(cd.id,           CONFIG_MAX_NAME,  "%s:%s", w->client_ip, w->client_port);
1718     snprintfz(cd.filename,     FILENAME_MAX,     "%s:%s", w->client_ip, w->client_port);
1719     snprintfz(cd.fullfilename, FILENAME_MAX,     "%s:%s", w->client_ip, w->client_port);
1720     snprintfz(cd.cmd,          PLUGINSD_CMD_MAX, "%s:%s", w->client_ip, w->client_port);
1721
1722     info("STREAM [%s]:%s: sending STREAM to initiate streaming...", w->client_ip, w->client_port);
1723     if(send_timeout(w->ifd, "STREAM", 6, 0, 60) != 6) {
1724         error("STREAM [%s]:%s: cannot send STREAM.", w->client_ip, w->client_port);
1725         buffer_flush(w->response.data);
1726         buffer_sprintf(w->response.data, "Failed to reply back with STREAM");
1727         return 400;
1728     }
1729
1730     // remove the non-blocking flag from the socket
1731     if(fcntl(w->ifd, F_SETFL, fcntl(w->ifd, F_GETFL, 0) & ~O_NONBLOCK) == -1)
1732         error("STREAM [%s]:%s: cannot remove the non-blocking flag from socket %d", w->client_ip, w->client_port, w->ifd);
1733
1734     /*
1735     char buffer[1000 + 1];
1736     ssize_t len;
1737     while((len = read(w->ifd, buffer, 1000)) != -1) {
1738         buffer[len] = '\0';
1739         fprintf(stderr, "BEGIN READ %zu bytes\n%s\nEND READ\n", (size_t)len, buffer);
1740     }
1741     */
1742
1743     // convert the socket to a FILE *
1744     FILE *fp = fdopen(w->ifd, "r");
1745     if(!fp) {
1746         error("STREAM [%s]:%s: failed to get a FILE for FD %d.", w->client_ip, w->client_port, w->ifd);
1747         buffer_flush(w->response.data);
1748         buffer_sprintf(w->response.data, "Failed to get a FILE for an FD.");
1749         return 500;
1750     }
1751
1752     // call the plugins.d processor to receive the metrics
1753     info("STREAM [%s]:%s: connecting client to plugins.d.", w->client_ip, w->client_port);
1754     size_t count = pluginsd_process(host, &cd, fp, 1);
1755     error("STREAM [%s]:%s: client disconnected.", w->client_ip, w->client_port);
1756
1757     // close all sockets, to let the socket worker we are done
1758     fclose(fp);
1759     w->ifd = -1;
1760     if(w->ofd != -1 && w->ofd != w->ifd) {
1761         close(w->ofd);
1762         w->ofd = -1;
1763     }
1764
1765     // this will not send anything
1766     // the socket is closed
1767     buffer_flush(w->response.data);
1768     if(count) return 200;
1769     return 400;
1770 }
1771
1772 const char *web_content_type_to_string(uint8_t contenttype) {
1773     switch(contenttype) {
1774         case CT_TEXT_HTML:
1775             return "text/html; charset=utf-8";
1776
1777         case CT_APPLICATION_XML:
1778             return "application/xml; charset=utf-8";
1779
1780         case CT_APPLICATION_JSON:
1781             return "application/json; charset=utf-8";
1782
1783         case CT_APPLICATION_X_JAVASCRIPT:
1784             return "application/x-javascript; charset=utf-8";
1785
1786         case CT_TEXT_CSS:
1787             return "text/css; charset=utf-8";
1788
1789         case CT_TEXT_XML:
1790             return "text/xml; charset=utf-8";
1791
1792         case CT_TEXT_XSL:
1793             return "text/xsl; charset=utf-8";
1794
1795         case CT_APPLICATION_OCTET_STREAM:
1796             return "application/octet-stream";
1797
1798         case CT_IMAGE_SVG_XML:
1799             return "image/svg+xml";
1800
1801         case CT_APPLICATION_X_FONT_TRUETYPE:
1802             return "application/x-font-truetype";
1803
1804         case CT_APPLICATION_X_FONT_OPENTYPE:
1805             return "application/x-font-opentype";
1806
1807         case CT_APPLICATION_FONT_WOFF:
1808             return "application/font-woff";
1809
1810         case CT_APPLICATION_FONT_WOFF2:
1811             return "application/font-woff2";
1812
1813         case CT_APPLICATION_VND_MS_FONTOBJ:
1814             return "application/vnd.ms-fontobject";
1815
1816         case CT_IMAGE_PNG:
1817             return "image/png";
1818
1819         case CT_IMAGE_JPG:
1820             return "image/jpeg";
1821
1822         case CT_IMAGE_GIF:
1823             return "image/gif";
1824
1825         case CT_IMAGE_XICON:
1826             return "image/x-icon";
1827
1828         case CT_IMAGE_BMP:
1829             return "image/bmp";
1830
1831         case CT_IMAGE_ICNS:
1832             return "image/icns";
1833
1834         case CT_PROMETHEUS:
1835             return "text/plain; version=0.0.4";
1836
1837         default:
1838         case CT_TEXT_PLAIN:
1839             return "text/plain; charset=utf-8";
1840     }
1841 }
1842
1843
1844 const char *web_response_code_to_string(int code) {
1845     switch(code) {
1846         case 200:
1847             return "OK";
1848
1849         case 307:
1850             return "Temporary Redirect";
1851
1852         case 400:
1853             return "Bad Request";
1854
1855         case 403:
1856             return "Forbidden";
1857
1858         case 404:
1859             return "Not Found";
1860
1861         case 412:
1862             return "Preconditions Failed";
1863
1864         default:
1865             if(code >= 100 && code < 200)
1866                 return "Informational";
1867
1868             if(code >= 200 && code < 300)
1869                 return "Successful";
1870
1871             if(code >= 300 && code < 400)
1872                 return "Redirection";
1873
1874             if(code >= 400 && code < 500)
1875                 return "Bad Request";
1876
1877             if(code >= 500 && code < 600)
1878                 return "Server Error";
1879
1880             return "Undefined Error";
1881     }
1882 }
1883
1884 static inline char *http_header_parse(struct web_client *w, char *s) {
1885     static uint32_t hash_origin = 0, hash_connection = 0, hash_accept_encoding = 0, hash_donottrack = 0;
1886
1887     if(unlikely(!hash_origin)) {
1888         hash_origin = simple_uhash("Origin");
1889         hash_connection = simple_uhash("Connection");
1890         hash_accept_encoding = simple_uhash("Accept-Encoding");
1891         hash_donottrack = simple_uhash("DNT");
1892     }
1893
1894     char *e = s;
1895
1896     // find the :
1897     while(*e && *e != ':') e++;
1898     if(!*e) return e;
1899
1900     // get the name
1901     *e = '\0';
1902
1903     // find the value
1904     char *v = e + 1, *ve;
1905
1906     // skip leading spaces from value
1907     while(*v == ' ') v++;
1908     ve = v;
1909
1910     // find the \r
1911     while(*ve && *ve != '\r') ve++;
1912     if(!*ve || ve[1] != '\n') {
1913         *e = ':';
1914         return ve;
1915     }
1916
1917     // terminate the value
1918     *ve = '\0';
1919
1920     // fprintf(stderr, "HEADER: '%s' = '%s'\n", s, v);
1921     uint32_t hash = simple_uhash(s);
1922
1923     if(hash == hash_origin && !strcasecmp(s, "Origin"))
1924         strncpyz(w->origin, v, ORIGIN_MAX);
1925
1926     else if(hash == hash_connection && !strcasecmp(s, "Connection")) {
1927         if(strcasestr(v, "keep-alive"))
1928             w->keepalive = 1;
1929     }
1930     else if(respect_web_browser_do_not_track_policy && hash == hash_donottrack && !strcasecmp(s, "DNT")) {
1931         if(*v == '0') w->donottrack = 0;
1932         else if(*v == '1') w->donottrack = 1;
1933     }
1934 #ifdef NETDATA_WITH_ZLIB
1935     else if(hash == hash_accept_encoding && !strcasecmp(s, "Accept-Encoding")) {
1936         if(web_enable_gzip) {
1937             if(strcasestr(v, "gzip"))
1938                 web_client_enable_deflate(w, 1);
1939             //
1940             // does not seem to work
1941             // else if(strcasestr(v, "deflate"))
1942             //  web_client_enable_deflate(w, 0);
1943         }
1944     }
1945 #endif /* NETDATA_WITH_ZLIB */
1946
1947     *e = ':';
1948     *ve = '\r';
1949     return ve;
1950 }
1951
1952 // http_request_validate()
1953 // returns:
1954 // = 0 : all good, process the request
1955 // > 0 : request is not supported
1956 // < 0 : request is incomplete - wait for more data
1957
1958 typedef enum http_validation {
1959     HTTP_VALIDATION_OK,
1960     HTTP_VALIDATION_NOT_SUPPORTED,
1961     HTTP_VALIDATION_INCOMPLETE
1962 } HTTP_VALIDATION;
1963
1964 static inline HTTP_VALIDATION http_request_validate(struct web_client *w) {
1965     char *s = w->response.data->buffer, *encoded_url = NULL;
1966
1967     // is is a valid request?
1968     if(!strncmp(s, "GET ", 4)) {
1969         encoded_url = s = &s[4];
1970         w->mode = WEB_CLIENT_MODE_NORMAL;
1971     }
1972     else if(!strncmp(s, "OPTIONS ", 8)) {
1973         encoded_url = s = &s[8];
1974         w->mode = WEB_CLIENT_MODE_OPTIONS;
1975     }
1976     else {
1977         w->wait_receive = 0;
1978         return HTTP_VALIDATION_NOT_SUPPORTED;
1979     }
1980
1981     // find the SPACE + "HTTP/"
1982     while(*s) {
1983         // find the next space
1984         while (*s && *s != ' ') s++;
1985
1986         // is it SPACE + "HTTP/" ?
1987         if(*s && !strncmp(s, " HTTP/", 6)) break;
1988         else s++;
1989     }
1990
1991     // incomplete requests
1992     if(unlikely(!*s)) {
1993         w->wait_receive = 1;
1994         return HTTP_VALIDATION_INCOMPLETE;
1995     }
1996
1997     // we have the end of encoded_url - remember it
1998     char *ue = s;
1999
2000     // make sure we have complete request
2001     // complete requests contain: \r\n\r\n
2002     while(*s) {
2003         // find a line feed
2004         while(*s && *s++ != '\r');
2005
2006         // did we reach the end?
2007         if(unlikely(!*s)) break;
2008
2009         // is it \r\n ?
2010         if(likely(*s++ == '\n')) {
2011
2012             // is it again \r\n ? (header end)
2013             if(unlikely(*s == '\r' && s[1] == '\n')) {
2014                 // a valid complete HTTP request found
2015
2016                 *ue = '\0';
2017                 url_decode_r(w->decoded_url, encoded_url, URL_MAX + 1);
2018                 *ue = ' ';
2019                 
2020                 // copy the URL - we are going to overwrite parts of it
2021                 // FIXME -- we should avoid it
2022                 strncpyz(w->last_url, w->decoded_url, URL_MAX);
2023
2024                 w->wait_receive = 0;
2025                 return HTTP_VALIDATION_OK;
2026             }
2027
2028             // another header line
2029             s = http_header_parse(w, s);
2030         }
2031     }
2032
2033     // incomplete request
2034     w->wait_receive = 1;
2035     return HTTP_VALIDATION_INCOMPLETE;
2036 }
2037
2038 static inline void web_client_send_http_header(struct web_client *w) {
2039     if(unlikely(w->response.code != 200))
2040         buffer_no_cacheable(w->response.data);
2041
2042     // set a proper expiration date, if not already set
2043     if(unlikely(!w->response.data->expires)) {
2044         if(w->response.data->options & WB_CONTENT_NO_CACHEABLE)
2045             w->response.data->expires = w->tv_ready.tv_sec + localhost->rrd_update_every;
2046         else
2047             w->response.data->expires = w->tv_ready.tv_sec + 86400;
2048     }
2049
2050     // prepare the HTTP response header
2051     debug(D_WEB_CLIENT, "%llu: Generating HTTP header with response %d.", w->id, w->response.code);
2052
2053     const char *content_type_string = web_content_type_to_string(w->response.data->contenttype);
2054     const char *code_msg = web_response_code_to_string(w->response.code);
2055
2056     // prepare the last modified and expiration dates
2057     char date[32], edate[32];
2058     {
2059         struct tm tmbuf, *tm;
2060
2061         tm = gmtime_r(&w->response.data->date, &tmbuf);
2062         strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %Z", tm);
2063
2064         tm = gmtime_r(&w->response.data->expires, &tmbuf);
2065         strftime(edate, sizeof(edate), "%a, %d %b %Y %H:%M:%S %Z", tm);
2066     }
2067
2068     buffer_sprintf(w->response.header_output,
2069             "HTTP/1.1 %d %s\r\n"
2070                     "Connection: %s\r\n"
2071                     "Server: NetData Embedded HTTP Server\r\n"
2072                     "Access-Control-Allow-Origin: %s\r\n"
2073                     "Access-Control-Allow-Credentials: true\r\n"
2074                     "Content-Type: %s\r\n"
2075                     "Date: %s\r\n"
2076                    , w->response.code, code_msg
2077                    , w->keepalive?"keep-alive":"close"
2078                    , w->origin
2079                    , content_type_string
2080                    , date
2081     );
2082
2083     if(unlikely(web_x_frame_options))
2084         buffer_sprintf(w->response.header_output, "X-Frame-Options: %s\r\n", web_x_frame_options);
2085
2086     if(w->cookie1[0] || w->cookie2[0]) {
2087         if(w->cookie1[0]) {
2088             buffer_sprintf(w->response.header_output,
2089                     "Set-Cookie: %s\r\n",
2090                     w->cookie1);
2091         }
2092
2093         if(w->cookie2[0]) {
2094             buffer_sprintf(w->response.header_output,
2095                     "Set-Cookie: %s\r\n",
2096                     w->cookie2);
2097         }
2098
2099         if(respect_web_browser_do_not_track_policy)
2100             buffer_sprintf(w->response.header_output,
2101                     "Tk: T;cookies\r\n");
2102     }
2103     else {
2104         if(respect_web_browser_do_not_track_policy) {
2105             if(w->tracking_required)
2106                 buffer_sprintf(w->response.header_output,
2107                         "Tk: T;cookies\r\n");
2108             else
2109                 buffer_sprintf(w->response.header_output,
2110                         "Tk: N\r\n");
2111         }
2112     }
2113
2114     if(w->mode == WEB_CLIENT_MODE_OPTIONS) {
2115         buffer_strcat(w->response.header_output,
2116                 "Access-Control-Allow-Methods: GET, OPTIONS\r\n"
2117                         "Access-Control-Allow-Headers: accept, x-requested-with, origin, content-type, cookie, pragma, cache-control\r\n"
2118                         "Access-Control-Max-Age: 1209600\r\n" // 86400 * 14
2119         );
2120     }
2121     else {
2122         buffer_sprintf(w->response.header_output,
2123                 "Cache-Control: %s\r\n"
2124                         "Expires: %s\r\n",
2125                 (w->response.data->options & WB_CONTENT_NO_CACHEABLE)?"no-cache":"public",
2126                 edate);
2127     }
2128
2129     // copy a possibly available custom header
2130     if(unlikely(buffer_strlen(w->response.header)))
2131         buffer_strcat(w->response.header_output, buffer_tostring(w->response.header));
2132
2133     // headers related to the transfer method
2134     if(likely(w->response.zoutput)) {
2135         buffer_strcat(w->response.header_output,
2136                 "Content-Encoding: gzip\r\n"
2137                         "Transfer-Encoding: chunked\r\n"
2138         );
2139     }
2140     else {
2141         if(likely((w->response.data->len || w->response.rlen))) {
2142             // we know the content length, put it
2143             buffer_sprintf(w->response.header_output, "Content-Length: %zu\r\n", w->response.data->len? w->response.data->len: w->response.rlen);
2144         }
2145         else {
2146             // we don't know the content length, disable keep-alive
2147             w->keepalive = 0;
2148         }
2149     }
2150
2151     // end of HTTP header
2152     buffer_strcat(w->response.header_output, "\r\n");
2153
2154     // sent the HTTP header
2155     debug(D_WEB_DATA, "%llu: Sending response HTTP header of size %zu: '%s'"
2156           , w->id
2157           , buffer_strlen(w->response.header_output)
2158           , buffer_tostring(w->response.header_output)
2159     );
2160
2161     web_client_crock_socket(w);
2162
2163     ssize_t bytes = send(w->ofd, buffer_tostring(w->response.header_output), buffer_strlen(w->response.header_output), 0);
2164     if(bytes != (ssize_t) buffer_strlen(w->response.header_output)) {
2165         if(bytes > 0)
2166             w->stats_sent_bytes += bytes;
2167
2168         debug(D_WEB_CLIENT, "%llu: HTTP Header failed to be sent (I sent %zu bytes but the system sent %zd bytes). Closing web client."
2169               , w->id
2170               , buffer_strlen(w->response.header_output)
2171               , bytes);
2172
2173         WEB_CLIENT_IS_DEAD(w);
2174         return;
2175     }
2176     else
2177         w->stats_sent_bytes += bytes;
2178 }
2179
2180 static inline int web_client_process_url(RRDHOST *host, struct web_client *w, char *url);
2181
2182 static inline int web_client_switch_host(RRDHOST *host, struct web_client *w, char *url) {
2183     static uint32_t hash_localhost = 0;
2184
2185     if(unlikely(!hash_localhost)) {
2186         hash_localhost = simple_hash("localhost");
2187     }
2188
2189     if(host != localhost) {
2190         buffer_flush(w->response.data);
2191         buffer_strcat(w->response.data, "Nesting of hosts is not allowed.");
2192         return 400;
2193     }
2194
2195     char *tok = mystrsep(&url, "/?&");
2196     if(tok && *tok) {
2197         debug(D_WEB_CLIENT, "%llu: Searching for host with name '%s'.", w->id, tok);
2198
2199         // copy the URL, we need it to serve files
2200         w->last_url[0] = '/';
2201         if(url && *url) strncpyz(&w->last_url[1], url, URL_MAX - 1);
2202         else w->last_url[1] = '\0';
2203
2204         uint32_t hash = simple_hash(tok);
2205
2206         if(unlikely(hash == hash_localhost && !strcmp(tok, "localhost")))
2207             return web_client_process_url(localhost, w, url);
2208
2209         rrd_rdlock();
2210         RRDHOST *h;
2211         rrdhost_foreach_read(h) {
2212             if(unlikely((hash == h->hash_hostname && !strcmp(tok, h->hostname)) ||
2213                         (hash == h->hash_machine_guid && !strcmp(tok, h->machine_guid)))) {
2214                 rrd_unlock();
2215                 return web_client_process_url(h, w, url);
2216             }
2217         }
2218         rrd_unlock();
2219     }
2220
2221     buffer_flush(w->response.data);
2222     buffer_strcat(w->response.data, "This netdata does not maintain a database for host: ");
2223     buffer_strcat_htmlescape(w->response.data, tok?tok:"");
2224     return 404;
2225 }
2226
2227 static inline int web_client_process_url(RRDHOST *host, struct web_client *w, char *url) {
2228     static uint32_t
2229             hash_api = 0,
2230             hash_netdata_conf = 0,
2231             hash_data = 0,
2232             hash_datasource = 0,
2233             hash_graph = 0,
2234             hash_list = 0,
2235             hash_all_json = 0,
2236             hash_host = 0,
2237             hash_stream = 0;
2238
2239 #ifdef NETDATA_INTERNAL_CHECKS
2240     static uint32_t hash_exit = 0, hash_debug = 0, hash_mirror = 0;
2241 #endif
2242
2243     if(unlikely(!hash_api)) {
2244         hash_api = simple_hash("api");
2245         hash_netdata_conf = simple_hash("netdata.conf");
2246         hash_data = simple_hash(WEB_PATH_DATA);
2247         hash_datasource = simple_hash(WEB_PATH_DATASOURCE);
2248         hash_graph = simple_hash(WEB_PATH_GRAPH);
2249         hash_list = simple_hash("list");
2250         hash_all_json = simple_hash("all.json");
2251         hash_host = simple_hash("host");
2252         hash_stream = simple_hash("stream");
2253 #ifdef NETDATA_INTERNAL_CHECKS
2254         hash_exit = simple_hash("exit");
2255         hash_debug = simple_hash("debug");
2256         hash_mirror = simple_hash("mirror");
2257 #endif
2258     }
2259
2260     char *tok = mystrsep(&url, "/?");
2261     if(likely(tok && *tok)) {
2262         uint32_t hash = simple_hash(tok);
2263         debug(D_WEB_CLIENT, "%llu: Processing command '%s'.", w->id, tok);
2264
2265         if(unlikely(hash == hash_api && strcmp(tok, "api") == 0)) {
2266             debug(D_WEB_CLIENT_ACCESS, "%llu: API request ...", w->id);
2267             return web_client_api_request(host, w, url);
2268         }
2269         else if(unlikely(hash == hash_host && strcmp(tok, "host") == 0)) {
2270             debug(D_WEB_CLIENT_ACCESS, "%llu: host switch request ...", w->id);
2271             return web_client_switch_host(host, w, url);
2272         }
2273         else if(unlikely(hash == hash_stream && strcmp(tok, "stream") == 0)) {
2274             debug(D_WEB_CLIENT_ACCESS, "%llu: stream request ...", w->id);
2275             return web_client_stream_request(host, w, url);
2276         }
2277         else if(unlikely(hash == hash_netdata_conf && strcmp(tok, "netdata.conf") == 0)) {
2278             debug(D_WEB_CLIENT_ACCESS, "%llu: Sending netdata.conf ...", w->id);
2279             w->response.data->contenttype = CT_TEXT_PLAIN;
2280             buffer_flush(w->response.data);
2281             generate_config(w->response.data, 0);
2282             return 200;
2283         }
2284         else if(unlikely(hash == hash_data && strcmp(tok, WEB_PATH_DATA) == 0)) { // "data"
2285             // the client is requesting rrd data -- OLD API
2286             return web_client_api_old_data_request(host, w, url, DATASOURCE_JSON);
2287         }
2288         else if(unlikely(hash == hash_datasource && strcmp(tok, WEB_PATH_DATASOURCE) == 0)) { // "datasource"
2289             // the client is requesting google datasource -- OLD API
2290             return web_client_api_old_data_request(host, w, url, DATASOURCE_DATATABLE_JSONP);
2291         }
2292         else if(unlikely(hash == hash_graph && strcmp(tok, WEB_PATH_GRAPH) == 0)) { // "graph"
2293             // the client is requesting an rrd graph -- OLD API
2294
2295             // get the name of the data to show
2296             tok = mystrsep(&url, "/?&");
2297             if(tok && *tok) {
2298                 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
2299
2300                 // do we have such a data set?
2301                 RRDSET *st = rrdset_find_byname(host, tok);
2302                 if(!st) st = rrdset_find(host, tok);
2303                 if(!st) {
2304                     // we don't have it
2305                     // try to send a file with that name
2306                     buffer_flush(w->response.data);
2307                     return mysendfile(w, tok);
2308                 }
2309
2310                 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending %s.json of RRD_STATS...", w->id, st->name);
2311                 w->response.data->contenttype = CT_APPLICATION_JSON;
2312                 buffer_flush(w->response.data);
2313                 rrd_stats_graph_json(st, url, w->response.data);
2314                 return 200;
2315             }
2316
2317             buffer_flush(w->response.data);
2318             buffer_strcat(w->response.data, "Graph name?\r\n");
2319             return 400;
2320         }
2321         else if(unlikely(hash == hash_list && strcmp(tok, "list") == 0)) {
2322             // OLD API
2323             debug(D_WEB_CLIENT_ACCESS, "%llu: Sending list of RRD_STATS...", w->id);
2324
2325             buffer_flush(w->response.data);
2326             RRDSET *st;
2327
2328             rrdhost_rdlock(host);
2329             rrdset_foreach_read(st, host) buffer_sprintf(w->response.data, "%s\n", st->name);
2330             rrdhost_unlock(host);
2331
2332             return 200;
2333         }
2334         else if(unlikely(hash == hash_all_json && strcmp(tok, "all.json") == 0)) {
2335             // OLD API
2336             debug(D_WEB_CLIENT_ACCESS, "%llu: Sending JSON list of all monitors of RRD_STATS...", w->id);
2337
2338             w->response.data->contenttype = CT_APPLICATION_JSON;
2339             buffer_flush(w->response.data);
2340             rrd_stats_all_json(host, w->response.data);
2341             return 200;
2342         }
2343 #ifdef NETDATA_INTERNAL_CHECKS
2344         else if(unlikely(hash == hash_exit && strcmp(tok, "exit") == 0)) {
2345             w->response.data->contenttype = CT_TEXT_PLAIN;
2346             buffer_flush(w->response.data);
2347
2348             if(!netdata_exit)
2349                 buffer_strcat(w->response.data, "ok, will do...");
2350             else
2351                 buffer_strcat(w->response.data, "I am doing it already");
2352
2353             error("web request to exit received.");
2354             netdata_cleanup_and_exit(0);
2355             return 200;
2356         }
2357         else if(unlikely(hash == hash_debug && strcmp(tok, "debug") == 0)) {
2358             buffer_flush(w->response.data);
2359
2360             // get the name of the data to show
2361             tok = mystrsep(&url, "/?&");
2362             if(tok && *tok) {
2363                 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
2364
2365                 // do we have such a data set?
2366                 RRDSET *st = rrdset_find_byname(host, tok);
2367                 if(!st) st = rrdset_find(host, tok);
2368                 if(!st) {
2369                     buffer_strcat(w->response.data, "Chart is not found: ");
2370                     buffer_strcat_htmlescape(w->response.data, tok);
2371                     debug(D_WEB_CLIENT_ACCESS, "%llu: %s is not found.", w->id, tok);
2372                     return 404;
2373                 }
2374
2375                 debug_flags |= D_RRD_STATS;
2376
2377                 if(rrdset_flag_check(st, RRDSET_FLAG_DEBUG))
2378                     rrdset_flag_clear(st, RRDSET_FLAG_DEBUG);
2379                 else
2380                     rrdset_flag_set(st, RRDSET_FLAG_DEBUG);
2381
2382                 buffer_sprintf(w->response.data, "Chart has now debug %s: ", rrdset_flag_check(st, RRDSET_FLAG_DEBUG)?"enabled":"disabled");
2383                 buffer_strcat_htmlescape(w->response.data, tok);
2384                 debug(D_WEB_CLIENT_ACCESS, "%llu: debug for %s is %s.", w->id, tok, rrdset_flag_check(st, RRDSET_FLAG_DEBUG)?"enabled":"disabled");
2385                 return 200;
2386             }
2387
2388             buffer_flush(w->response.data);
2389             buffer_strcat(w->response.data, "debug which chart?\r\n");
2390             return 400;
2391         }
2392         else if(unlikely(hash == hash_mirror && strcmp(tok, "mirror") == 0)) {
2393             debug(D_WEB_CLIENT_ACCESS, "%llu: Mirroring...", w->id);
2394
2395             // replace the zero bytes with spaces
2396             buffer_char_replace(w->response.data, '\0', ' ');
2397
2398             // just leave the buffer as is
2399             // it will be copied back to the client
2400
2401             return 200;
2402         }
2403 #endif  /* NETDATA_INTERNAL_CHECKS */
2404     }
2405
2406     char filename[FILENAME_MAX+1];
2407     url = filename;
2408     strncpyz(filename, w->last_url, FILENAME_MAX);
2409     tok = mystrsep(&url, "?");
2410     buffer_flush(w->response.data);
2411     return mysendfile(w, (tok && *tok)?tok:"/");
2412 }
2413
2414 void web_client_process_request(struct web_client *w) {
2415
2416     // start timing us
2417     now_realtime_timeval(&w->tv_in);
2418
2419     switch(http_request_validate(w)) {
2420         case HTTP_VALIDATION_OK:
2421             if(unlikely(w->mode == WEB_CLIENT_MODE_OPTIONS)) {
2422                 w->response.data->contenttype = CT_TEXT_PLAIN;
2423                 buffer_flush(w->response.data);
2424                 buffer_strcat(w->response.data, "OK");
2425                 w->response.code = 200;
2426             }
2427             else
2428                 w->response.code = web_client_process_url(localhost, w, w->decoded_url);
2429             break;
2430
2431         case HTTP_VALIDATION_INCOMPLETE:
2432             if(w->response.data->len > TOO_BIG_REQUEST) {
2433                 strcpy(w->last_url, "too big request");
2434
2435                 debug(D_WEB_CLIENT_ACCESS, "%llu: Received request is too big (%zu bytes).", w->id, w->response.data->len);
2436
2437                 buffer_flush(w->response.data);
2438                 buffer_sprintf(w->response.data, "Received request is too big  (%zu bytes).\r\n", w->response.data->len);
2439                 w->response.code = 400;
2440             }
2441             else {
2442                 // wait for more data
2443                 return;
2444             }
2445             break;
2446
2447         case HTTP_VALIDATION_NOT_SUPPORTED:
2448             debug(D_WEB_CLIENT_ACCESS, "%llu: Cannot understand '%s'.", w->id, w->response.data->buffer);
2449
2450             buffer_flush(w->response.data);
2451             buffer_strcat(w->response.data, "I don't understand you...\r\n");
2452             w->response.code = 400;
2453             break;
2454     }
2455
2456     // keep track of the time we done processing
2457     now_realtime_timeval(&w->tv_ready);
2458
2459     w->response.sent = 0;
2460
2461     // set a proper last modified date
2462     if(unlikely(!w->response.data->date))
2463         w->response.data->date = w->tv_ready.tv_sec;
2464
2465     web_client_send_http_header(w);
2466
2467     // enable sending immediately if we have data
2468     if(w->response.data->len) w->wait_send = 1;
2469     else w->wait_send = 0;
2470
2471     switch(w->mode) {
2472         case WEB_CLIENT_MODE_OPTIONS:
2473             debug(D_WEB_CLIENT, "%llu: Done preparing the OPTIONS response. Sending data (%zu bytes) to client.", w->id, w->response.data->len);
2474             break;
2475
2476         case WEB_CLIENT_MODE_NORMAL:
2477             debug(D_WEB_CLIENT, "%llu: Done preparing the response. Sending data (%zu bytes) to client.", w->id, w->response.data->len);
2478             break;
2479
2480         case WEB_CLIENT_MODE_FILECOPY:
2481             if(w->response.rlen) {
2482                 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending data file of %zu bytes to client.", w->id, w->response.rlen);
2483                 w->wait_receive = 1;
2484
2485                 /*
2486                 // utilize the kernel sendfile() for copying the file to the socket.
2487                 // this block of code can be commented, without anything missing.
2488                 // when it is commented, the program will copy the data using async I/O.
2489                 {
2490                     long len = sendfile(w->ofd, w->ifd, NULL, w->response.data->rbytes);
2491                     if(len != w->response.data->rbytes)
2492                         error("%llu: sendfile() should copy %ld bytes, but copied %ld. Falling back to manual copy.", w->id, w->response.data->rbytes, len);
2493                     else
2494                         web_client_reset(w);
2495                 }
2496                 */
2497             }
2498             else
2499                 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending an unknown amount of bytes to client.", w->id);
2500             break;
2501
2502         default:
2503             fatal("%llu: Unknown client mode %d.", w->id, w->mode);
2504             break;
2505     }
2506 }
2507
2508 ssize_t web_client_send_chunk_header(struct web_client *w, size_t len)
2509 {
2510     debug(D_DEFLATE, "%llu: OPEN CHUNK of %zu bytes (hex: %zx).", w->id, len, len);
2511     char buf[24];
2512     sprintf(buf, "%zX\r\n", len);
2513     
2514     ssize_t bytes = send(w->ofd, buf, strlen(buf), 0);
2515     if(bytes > 0) {
2516         debug(D_DEFLATE, "%llu: Sent chunk header %zd bytes.", w->id, bytes);
2517         w->stats_sent_bytes += bytes;
2518     }
2519
2520     else if(bytes == 0) {
2521         debug(D_WEB_CLIENT, "%llu: Did not send chunk header to the client.", w->id);
2522         WEB_CLIENT_IS_DEAD(w);
2523     }
2524     else {
2525         debug(D_WEB_CLIENT, "%llu: Failed to send chunk header to client.", w->id);
2526         WEB_CLIENT_IS_DEAD(w);
2527     }
2528
2529     return bytes;
2530 }
2531
2532 ssize_t web_client_send_chunk_close(struct web_client *w)
2533 {
2534     //debug(D_DEFLATE, "%llu: CLOSE CHUNK.", w->id);
2535
2536     ssize_t bytes = send(w->ofd, "\r\n", 2, 0);
2537     if(bytes > 0) {
2538         debug(D_DEFLATE, "%llu: Sent chunk suffix %zd bytes.", w->id, bytes);
2539         w->stats_sent_bytes += bytes;
2540     }
2541
2542     else if(bytes == 0) {
2543         debug(D_WEB_CLIENT, "%llu: Did not send chunk suffix to the client.", w->id);
2544         WEB_CLIENT_IS_DEAD(w);
2545     }
2546     else {
2547         debug(D_WEB_CLIENT, "%llu: Failed to send chunk suffix to client.", w->id);
2548         WEB_CLIENT_IS_DEAD(w);
2549     }
2550
2551     return bytes;
2552 }
2553
2554 ssize_t web_client_send_chunk_finalize(struct web_client *w)
2555 {
2556     //debug(D_DEFLATE, "%llu: FINALIZE CHUNK.", w->id);
2557
2558     ssize_t bytes = send(w->ofd, "\r\n0\r\n\r\n", 7, 0);
2559     if(bytes > 0) {
2560         debug(D_DEFLATE, "%llu: Sent chunk suffix %zd bytes.", w->id, bytes);
2561         w->stats_sent_bytes += bytes;
2562     }
2563
2564     else if(bytes == 0) {
2565         debug(D_WEB_CLIENT, "%llu: Did not send chunk finalize suffix to the client.", w->id);
2566         WEB_CLIENT_IS_DEAD(w);
2567     }
2568     else {
2569         debug(D_WEB_CLIENT, "%llu: Failed to send chunk finalize suffix to client.", w->id);
2570         WEB_CLIENT_IS_DEAD(w);
2571     }
2572
2573     return bytes;
2574 }
2575
2576 #ifdef NETDATA_WITH_ZLIB
2577 ssize_t web_client_send_deflate(struct web_client *w)
2578 {
2579     ssize_t len = 0, t = 0;
2580
2581     // when using compression,
2582     // w->response.sent is the amount of bytes passed through compression
2583
2584     debug(D_DEFLATE, "%llu: web_client_send_deflate(): w->response.data->len = %zu, w->response.sent = %zu, w->response.zhave = %zu, w->response.zsent = %zu, w->response.zstream.avail_in = %u, w->response.zstream.avail_out = %u, w->response.zstream.total_in = %lu, w->response.zstream.total_out = %lu.",
2585         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);
2586
2587     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) {
2588         // there is nothing to send
2589
2590         debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
2591
2592         // finalize the chunk
2593         if(w->response.sent != 0) {
2594             t = web_client_send_chunk_finalize(w);
2595             if(t < 0) return t;
2596         }
2597
2598         if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->response.rlen && w->response.rlen > w->response.data->len) {
2599             // we have to wait, more data will come
2600             debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
2601             w->wait_send = 0;
2602             return t;
2603         }
2604
2605         if(unlikely(!w->keepalive)) {
2606             debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %zu bytes sent.", w->id, w->response.sent);
2607             WEB_CLIENT_IS_DEAD(w);
2608             return t;
2609         }
2610
2611         // reset the client
2612         web_client_reset(w);
2613         debug(D_WEB_CLIENT, "%llu: Done sending all data on socket.", w->id);
2614         return t;
2615     }
2616
2617     if(w->response.zhave == w->response.zsent) {
2618         // compress more input data
2619
2620         // close the previous open chunk
2621         if(w->response.sent != 0) {
2622             t = web_client_send_chunk_close(w);
2623             if(t < 0) return t;
2624         }
2625
2626         debug(D_DEFLATE, "%llu: Compressing %zu new bytes starting from %zu (and %u left behind).", w->id, (w->response.data->len - w->response.sent), w->response.sent, w->response.zstream.avail_in);
2627
2628         // give the compressor all the data not passed through the compressor yet
2629         if(w->response.data->len > w->response.sent) {
2630             w->response.zstream.next_in = (Bytef *)&w->response.data->buffer[w->response.sent - w->response.zstream.avail_in];
2631             w->response.zstream.avail_in += (uInt) (w->response.data->len - w->response.sent);
2632         }
2633
2634         // reset the compressor output buffer
2635         w->response.zstream.next_out = w->response.zbuffer;
2636         w->response.zstream.avail_out = ZLIB_CHUNK;
2637
2638         // ask for FINISH if we have all the input
2639         int flush = Z_SYNC_FLUSH;
2640         if(w->mode == WEB_CLIENT_MODE_NORMAL
2641             || (w->mode == WEB_CLIENT_MODE_FILECOPY && !w->wait_receive && w->response.data->len == w->response.rlen)) {
2642             flush = Z_FINISH;
2643             debug(D_DEFLATE, "%llu: Requesting Z_FINISH, if possible.", w->id);
2644         }
2645         else {
2646             debug(D_DEFLATE, "%llu: Requesting Z_SYNC_FLUSH.", w->id);
2647         }
2648
2649         // compress
2650         if(deflate(&w->response.zstream, flush) == Z_STREAM_ERROR) {
2651             error("%llu: Compression failed. Closing down client.", w->id);
2652             web_client_reset(w);
2653             return(-1);
2654         }
2655
2656         w->response.zhave = ZLIB_CHUNK - w->response.zstream.avail_out;
2657         w->response.zsent = 0;
2658
2659         // keep track of the bytes passed through the compressor
2660         w->response.sent = w->response.data->len;
2661
2662         debug(D_DEFLATE, "%llu: Compression produced %zu bytes.", w->id, w->response.zhave);
2663
2664         // open a new chunk
2665         ssize_t t2 = web_client_send_chunk_header(w, w->response.zhave);
2666         if(t2 < 0) return t2;
2667         t += t2;
2668     }
2669     
2670     debug(D_WEB_CLIENT, "%llu: Sending %zu bytes of data (+%zd of chunk header).", w->id, w->response.zhave - w->response.zsent, t);
2671
2672     len = send(w->ofd, &w->response.zbuffer[w->response.zsent], (size_t) (w->response.zhave - w->response.zsent), MSG_DONTWAIT);
2673     if(len > 0) {
2674         w->stats_sent_bytes += len;
2675         w->response.zsent += len;
2676         len += t;
2677         debug(D_WEB_CLIENT, "%llu: Sent %zd bytes.", w->id, len);
2678     }
2679     else if(len == 0) {
2680         debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client (zhave = %zu, zsent = %zu, need to send = %zu).",
2681             w->id, w->response.zhave, w->response.zsent, w->response.zhave - w->response.zsent);
2682
2683         WEB_CLIENT_IS_DEAD(w);
2684     }
2685     else {
2686         debug(D_WEB_CLIENT, "%llu: Failed to send data to client.", w->id);
2687         WEB_CLIENT_IS_DEAD(w);
2688     }
2689
2690     return(len);
2691 }
2692 #endif // NETDATA_WITH_ZLIB
2693
2694 ssize_t web_client_send(struct web_client *w) {
2695 #ifdef NETDATA_WITH_ZLIB
2696     if(likely(w->response.zoutput)) return web_client_send_deflate(w);
2697 #endif // NETDATA_WITH_ZLIB
2698
2699     ssize_t bytes;
2700
2701     if(unlikely(w->response.data->len - w->response.sent == 0)) {
2702         // there is nothing to send
2703
2704         debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
2705
2706         // there can be two cases for this
2707         // A. we have done everything
2708         // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
2709
2710         if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->response.rlen && w->response.rlen > w->response.data->len) {
2711             // we have to wait, more data will come
2712             debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
2713             w->wait_send = 0;
2714             return 0;
2715         }
2716
2717         if(unlikely(!w->keepalive)) {
2718             debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %zu bytes sent.", w->id, w->response.sent);
2719             WEB_CLIENT_IS_DEAD(w);
2720             return 0;
2721         }
2722
2723         web_client_reset(w);
2724         debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
2725         return 0;
2726     }
2727
2728     bytes = send(w->ofd, &w->response.data->buffer[w->response.sent], w->response.data->len - w->response.sent, MSG_DONTWAIT);
2729     if(likely(bytes > 0)) {
2730         w->stats_sent_bytes += bytes;
2731         w->response.sent += bytes;
2732         debug(D_WEB_CLIENT, "%llu: Sent %zd bytes.", w->id, bytes);
2733     }
2734     else if(likely(bytes == 0)) {
2735         debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client.", w->id);
2736         WEB_CLIENT_IS_DEAD(w);
2737     }
2738     else {
2739         debug(D_WEB_CLIENT, "%llu: Failed to send data to client.", w->id);
2740         WEB_CLIENT_IS_DEAD(w);
2741     }
2742
2743     return(bytes);
2744 }
2745
2746 ssize_t web_client_receive(struct web_client *w)
2747 {
2748     // do we have any space for more data?
2749     buffer_need_bytes(w->response.data, WEB_REQUEST_LENGTH);
2750
2751     ssize_t left = w->response.data->size - w->response.data->len;
2752     ssize_t bytes;
2753
2754     if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY))
2755         bytes = read(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1));
2756     else
2757         bytes = recv(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1), MSG_DONTWAIT);
2758
2759     if(likely(bytes > 0)) {
2760         if(w->mode != WEB_CLIENT_MODE_FILECOPY)
2761             w->stats_received_bytes += bytes;
2762
2763         size_t old = w->response.data->len;
2764         w->response.data->len += bytes;
2765         w->response.data->buffer[w->response.data->len] = '\0';
2766
2767         debug(D_WEB_CLIENT, "%llu: Received %zd bytes.", w->id, bytes);
2768         debug(D_WEB_DATA, "%llu: Received data: '%s'.", w->id, &w->response.data->buffer[old]);
2769
2770         if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
2771             w->wait_send = 1;
2772
2773             if(w->response.rlen && w->response.data->len >= w->response.rlen)
2774                 w->wait_receive = 0;
2775         }
2776     }
2777     else if(likely(bytes == 0)) {
2778         debug(D_WEB_CLIENT, "%llu: Out of input data.", w->id);
2779
2780         // if we cannot read, it means we have an error on input.
2781         // if however, we are copying a file from ifd to ofd, we should not return an error.
2782         // in this case, the error should be generated when the file has been sent to the client.
2783
2784         if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
2785             // we are copying data from ifd to ofd
2786             // let it finish copying...
2787             w->wait_receive = 0;
2788
2789             debug(D_WEB_CLIENT, "%llu: Read the whole file.", w->id);
2790             if(w->ifd != w->ofd) close(w->ifd);
2791             w->ifd = w->ofd;
2792         }
2793         else {
2794             debug(D_WEB_CLIENT, "%llu: failed to receive data.", w->id);
2795             WEB_CLIENT_IS_DEAD(w);
2796         }
2797     }
2798     else {
2799         debug(D_WEB_CLIENT, "%llu: receive data failed.", w->id);
2800         WEB_CLIENT_IS_DEAD(w);
2801     }
2802
2803     return(bytes);
2804 }
2805
2806
2807 // --------------------------------------------------------------------------------------
2808 // the thread of a single client
2809
2810 // 1. waits for input and output, using async I/O
2811 // 2. it processes HTTP requests
2812 // 3. it generates HTTP responses
2813 // 4. it copies data from input to output if mode is FILECOPY
2814
2815 void *web_client_main(void *ptr)
2816 {
2817     if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
2818         error("Cannot set pthread cancel type to DEFERRED.");
2819
2820     if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
2821         error("Cannot set pthread cancel state to ENABLE.");
2822
2823     struct web_client *w = ptr;
2824     struct pollfd fds[2], *ifd, *ofd;
2825     int retval, timeout;
2826     nfds_t fdmax = 0;
2827
2828     log_access("%llu: %s port %s connected on thread task id %d", w->id, w->client_ip, w->client_port, gettid());
2829
2830     for(;;) {
2831         if(unlikely(netdata_exit)) break;
2832
2833         if(unlikely(w->dead)) {
2834             debug(D_WEB_CLIENT, "%llu: client is dead.", w->id);
2835             break;
2836         }
2837         else if(unlikely(!w->wait_receive && !w->wait_send)) {
2838             debug(D_WEB_CLIENT, "%llu: client is not set for neither receiving nor sending data.", w->id);
2839             break;
2840         }
2841
2842         if(unlikely(w->ifd < 0 || w->ofd < 0)) {
2843             error("%llu: invalid file descriptor, ifd = %d, ofd = %d (required 0 <= fd", w->id, w->ifd, w->ofd);
2844             break;
2845         }
2846
2847         if(w->ifd == w->ofd) {
2848             fds[0].fd = w->ifd;
2849             fds[0].events = 0;
2850             fds[0].revents = 0;
2851
2852             if(w->wait_receive) fds[0].events |= POLLIN;
2853             if(w->wait_send)    fds[0].events |= POLLOUT;
2854
2855             fds[1].fd = -1;
2856             fds[1].events = 0;
2857             fds[1].revents = 0;
2858
2859             ifd = ofd = &fds[0];
2860
2861             fdmax = 1;
2862         }
2863         else {
2864             fds[0].fd = w->ifd;
2865             fds[0].events = 0;
2866             fds[0].revents = 0;
2867             if(w->wait_receive) fds[0].events |= POLLIN;
2868             ifd = &fds[0];
2869
2870             fds[1].fd = w->ofd;
2871             fds[1].events = 0;
2872             fds[1].revents = 0;
2873             if(w->wait_send)    fds[1].events |= POLLOUT;
2874             ofd = &fds[1];
2875
2876             fdmax = 2;
2877         }
2878
2879         debug(D_WEB_CLIENT, "%llu: Waiting socket async I/O for %s %s", w->id, w->wait_receive?"INPUT":"", w->wait_send?"OUTPUT":"");
2880         errno = 0;
2881         timeout = web_client_timeout * 1000;
2882         retval = poll(fds, fdmax, timeout);
2883
2884         if(unlikely(netdata_exit)) break;
2885
2886         if(unlikely(retval == -1)) {
2887             if(errno == EAGAIN || errno == EINTR) {
2888                 debug(D_WEB_CLIENT, "%llu: EAGAIN received.", w->id);
2889                 continue;
2890             }
2891
2892             debug(D_WEB_CLIENT, "%llu: LISTENER: poll() failed (input fd = %d, output fd = %d). Closing client.", w->id, w->ifd, w->ofd);
2893             break;
2894         }
2895         else if(unlikely(!retval)) {
2896             debug(D_WEB_CLIENT, "%llu: Timeout while waiting socket async I/O for %s %s", w->id, w->wait_receive?"INPUT":"", w->wait_send?"OUTPUT":"");
2897             break;
2898         }
2899
2900         if(unlikely(netdata_exit)) break;
2901
2902         int used = 0;
2903         if(w->wait_send && ofd->revents & POLLOUT) {
2904             used++;
2905             if(web_client_send(w) < 0) {
2906                 debug(D_WEB_CLIENT, "%llu: Cannot send data to client. Closing client.", w->id);
2907                 break;
2908             }
2909         }
2910
2911         if(unlikely(netdata_exit)) break;
2912
2913         if(w->wait_receive && (ifd->revents & POLLIN || ifd->revents & POLLPRI)) {
2914             used++;
2915             if(web_client_receive(w) < 0) {
2916                 debug(D_WEB_CLIENT, "%llu: Cannot receive data from client. Closing client.", w->id);
2917                 break;
2918             }
2919
2920             if(w->mode == WEB_CLIENT_MODE_NORMAL) {
2921                 debug(D_WEB_CLIENT, "%llu: Attempting to process received data.", w->id);
2922                 web_client_process_request(w);
2923
2924                 // if the sockets are closed, may have transferred this client
2925                 // to plugins.d
2926                 if(w->ifd == -1 && w->ofd == -1) break;
2927             }
2928         }
2929
2930         if(unlikely(!used)) {
2931             debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on socket.", w->id);
2932             break;
2933         }
2934     }
2935
2936     web_client_reset(w);
2937
2938     log_access("%llu: %s port %s disconnected from thread task id %d", w->id, w->client_ip, w->client_port, gettid());
2939     debug(D_WEB_CLIENT, "%llu: done...", w->id);
2940
2941     // close the sockets/files now
2942     // to free file descriptors
2943     if(w->ifd == w->ofd) {
2944         if(w->ifd != -1) close(w->ifd);
2945     }
2946     else {
2947         if(w->ifd != -1) close(w->ifd);
2948         if(w->ofd != -1) close(w->ofd);
2949     }
2950     w->ifd = -1;
2951     w->ofd = -1;
2952
2953     w->obsolete = 1;
2954
2955     pthread_exit(NULL);
2956     return NULL;
2957 }