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