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