]> arthur.barton.de Git - netdata.git/blob - src/web_client.c
prevent multiple locks per web requests
[netdata.git] / src / web_client.c
1 #ifdef HAVE_CONFIG_H
2 #include <config.h>
3 #endif
4 #include <unistd.h>
5 #include <stdlib.h>
6 #include <sys/types.h>
7 #include <sys/socket.h>
8 #include <netinet/in.h>
9 #include <arpa/inet.h>
10 #include <errno.h>
11 #include <pthread.h>
12 #include <sys/stat.h>
13 #include <fcntl.h>
14 #include <netinet/tcp.h>
15 #include <malloc.h>
16 #include <pwd.h>
17 #include <grp.h>
18 #include <ctype.h>
19
20 #include "common.h"
21 #include "log.h"
22 #include "appconfig.h"
23 #include "url.h"
24 #include "web_buffer.h"
25 #include "web_server.h"
26 #include "global_statistics.h"
27 #include "rrd.h"
28 #include "rrd2json.h"
29 #include "registry.h"
30
31 #include "web_client.h"
32 #include "../config.h"
33
34 #define INITIAL_WEB_DATA_LENGTH 16384
35 #define WEB_REQUEST_LENGTH 16384
36 #define TOO_BIG_REQUEST 16384
37
38 int web_client_timeout = DEFAULT_DISCONNECT_IDLE_WEB_CLIENTS_AFTER_SECONDS;
39 int web_enable_gzip = 1;
40
41 extern int netdata_exit;
42
43 struct web_client *web_clients = NULL;
44 unsigned long long web_clients_count = 0;
45
46 struct web_client *web_client_create(int listener)
47 {
48         struct web_client *w;
49
50         w = calloc(1, sizeof(struct web_client));
51         if(!w) {
52                 error("Cannot allocate new web_client memory.");
53                 return NULL;
54         }
55
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 = accept(listener, sadr, &addrlen);
67                 if (w->ifd == -1) {
68                         error("%llu: Cannot accept new incoming connection.", w->id);
69                         free(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
84                 case AF_INET:
85                         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);
86                         break;
87
88                 case AF_INET6:
89                         if(strncmp(w->client_ip, "::ffff:", 7) == 0) {
90                                 strcpy(w->client_ip, &w->client_ip[7]);
91                                 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);
92                         }
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->ifd, SOL_SOCKET, SO_KEEPALIVE, (char *) &flag, sizeof(int)) != 0) error("%llu: Cannot set SO_KEEPALIVE on socket.", w->id);
103         }
104
105         w->response.data = buffer_create(INITIAL_WEB_DATA_LENGTH);
106         if(unlikely(!w->response.data)) {
107                 // no need for error log - web_buffer_create already logged the error
108                 close(w->ifd);
109                 free(w);
110                 return NULL;
111         }
112
113         w->response.header = buffer_create(HTTP_RESPONSE_HEADER_SIZE);
114         if(unlikely(!w->response.header)) {
115                 // no need for error log - web_buffer_create already logged the error
116                 buffer_free(w->response.data);
117                 close(w->ifd);
118                 free(w);
119                 return NULL;
120         }
121
122         w->response.header_output = buffer_create(HTTP_RESPONSE_HEADER_SIZE);
123         if(unlikely(!w->response.header_output)) {
124                 // no need for error log - web_buffer_create already logged the error
125                 buffer_free(w->response.header);
126                 buffer_free(w->response.data);
127                 close(w->ifd);
128                 free(w);
129                 return NULL;
130         }
131
132         w->origin[0] = '*';
133         w->wait_receive = 1;
134
135         if(web_clients) web_clients->prev = w;
136         w->next = web_clients;
137         web_clients = w;
138
139         global_statistics.connected_clients++;
140
141         return(w);
142 }
143
144 void web_client_reset(struct web_client *w)
145 {
146         struct timeval tv;
147         gettimeofday(&tv, NULL);
148
149         debug(D_WEB_CLIENT, "%llu: Reseting client.", w->id);
150
151         if(w->stats_received_bytes || w->stats_sent_bytes) {
152                 global_statistics_lock();
153                 global_statistics.web_requests++;
154                 global_statistics.web_usec += usecdiff(&tv, &w->tv_in);
155                 global_statistics.bytes_received += w->stats_received_bytes;
156                 global_statistics.bytes_sent += w->stats_sent_bytes;
157                 global_statistics_unlock();
158         }
159         w->stats_received_bytes = 0;
160         w->stats_sent_bytes = 0;
161
162         long sent = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->response.rlen:w->response.data->len;
163
164 #ifdef NETDATA_WITH_ZLIB
165         if(likely(w->response.zoutput)) sent = (long)w->response.zstream.total_out;
166 #endif
167
168         long size = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->response.rlen:w->response.data->len;
169
170         if(likely(w->last_url[0]))
171                 log_access("%llu: (sent/all = %ld/%ld bytes %0.0f%%, prep/sent/total = %0.2f/%0.2f/%0.2f ms) %s: %d '%s'",
172                         w->id,
173                         sent, size, -((size>0)?((float)(size-sent)/(float)size * 100.0):0.0),
174                         (float)usecdiff(&w->tv_ready, &w->tv_in) / 1000.0,
175                         (float)usecdiff(&tv, &w->tv_ready) / 1000.0,
176                         (float)usecdiff(&tv, &w->tv_in) / 1000.0,
177                         (w->mode == WEB_CLIENT_MODE_FILECOPY)?"filecopy":((w->mode == WEB_CLIENT_MODE_OPTIONS)?"options":"data"),
178                         w->response.code,
179                         w->last_url
180                 );
181
182         if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY)) {
183                 debug(D_WEB_CLIENT, "%llu: Closing filecopy input file.", w->id);
184                 close(w->ifd);
185                 w->ifd = w->ofd;
186         }
187
188         w->last_url[0] = '\0';
189         w->cookie1[0] = '\0';
190         w->cookie2[0] = '\0';
191         w->origin[0] = '*';
192         w->origin[1] = '\0';
193
194         w->mode = WEB_CLIENT_MODE_NORMAL;
195         w->enable_gzip = 0;
196         w->keepalive = 0;
197         if(w->decoded_url) {
198                 free(w->decoded_url);
199                 w->decoded_url = NULL;
200         }
201
202         buffer_reset(w->response.header_output);
203         buffer_reset(w->response.header);
204         buffer_reset(w->response.data);
205         w->response.rlen = 0;
206         w->response.sent = 0;
207         w->response.code = 0;
208
209         w->wait_receive = 1;
210         w->wait_send = 0;
211
212         w->response.zoutput = 0;
213
214         // if we had enabled compression, release it
215 #ifdef NETDATA_WITH_ZLIB
216         if(w->response.zinitialized) {
217                 debug(D_DEFLATE, "%llu: Reseting compression.", w->id);
218                 deflateEnd(&w->response.zstream);
219                 w->response.zsent = 0;
220                 w->response.zhave = 0;
221                 w->response.zstream.avail_in = 0;
222                 w->response.zstream.avail_out = 0;
223                 w->response.zstream.total_in = 0;
224                 w->response.zstream.total_out = 0;
225                 w->response.zinitialized = 0;
226         }
227 #endif // NETDATA_WITH_ZLIB
228 }
229
230 struct web_client *web_client_free(struct web_client *w)
231 {
232         struct web_client *n = w->next;
233
234         debug(D_WEB_CLIENT_ACCESS, "%llu: Closing web client from %s port %s.", w->id, w->client_ip, w->client_port);
235
236         if(w->prev)     w->prev->next = w->next;
237         if(w->next) w->next->prev = w->prev;
238
239         if(w == web_clients) web_clients = w->next;
240
241         if(w->response.header_output) buffer_free(w->response.header_output);
242         if(w->response.header) buffer_free(w->response.header);
243         if(w->response.data) buffer_free(w->response.data);
244         close(w->ifd);
245         if(w->ofd != w->ifd) close(w->ofd);
246         free(w);
247
248         global_statistics.connected_clients--;
249
250         return(n);
251 }
252
253 uid_t web_files_uid(void)
254 {
255         static char *web_owner = NULL;
256         static uid_t owner_uid = 0;
257
258         if(unlikely(!web_owner)) {
259                 web_owner = config_get("global", "web files owner", config_get("global", "run as user", ""));
260                 if(!web_owner || !*web_owner)
261                         owner_uid = geteuid();
262                 else {
263                         // getpwnam() is not thread safe,
264                         // but we have called this function once
265                         // while single threaded
266                         struct passwd *pw = getpwnam(web_owner);
267                         if(!pw) {
268                                 error("User %s is not present. Ignoring option.", web_owner);
269                                 owner_uid = geteuid();
270                         }
271                         else {
272                                 debug(D_WEB_CLIENT, "Web files owner set to %s.\n", web_owner);
273                                 owner_uid = pw->pw_uid;
274                         }
275                 }
276         }
277
278         return(owner_uid);
279 }
280
281 gid_t web_files_gid(void)
282 {
283         static char *web_group = NULL;
284         static gid_t owner_gid = 0;
285
286         if(unlikely(!web_group)) {
287                 web_group = config_get("global", "web files group", config_get("global", "web files owner", ""));
288                 if(!web_group || !*web_group)
289                         owner_gid = getegid();
290                 else {
291                         // getgrnam() is not thread safe,
292                         // but we have called this function once
293                         // while single threaded
294                         struct group *gr = getgrnam(web_group);
295                         if(!gr) {
296                                 error("Group %s is not present. Ignoring option.", web_group);
297                                 owner_gid = getegid();
298                         }
299                         else {
300                                 debug(D_WEB_CLIENT, "Web files group set to %s.\n", web_group);
301                                 owner_gid = gr->gr_gid;
302                         }
303                 }
304         }
305
306         return(owner_gid);
307 }
308
309 int mysendfile(struct web_client *w, char *filename)
310 {
311         static char *web_dir = NULL;
312
313         // initialize our static data
314         if(unlikely(!web_dir)) web_dir = config_get("global", "web files directory", WEB_DIR);
315
316         debug(D_WEB_CLIENT, "%llu: Looking for file '%s/%s'", w->id, web_dir, filename);
317
318         // skip leading slashes
319         while (*filename == '/') filename++;
320
321         // if the filename contain known paths, skip them
322         if(strncmp(filename, WEB_PATH_FILE "/", strlen(WEB_PATH_FILE) + 1) == 0) filename = &filename[strlen(WEB_PATH_FILE) + 1];
323
324         char *s;
325         for(s = filename; *s ;s++) {
326                 if( !isalnum(*s) && *s != '/' && *s != '.' && *s != '-' && *s != '_') {
327                         debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
328                         buffer_sprintf(w->response.data, "File '%s' cannot be served. Filename contains invalid character '%c'", filename, *s);
329                         return 400;
330                 }
331         }
332
333         // if the filename contains a .. refuse to serve it
334         if(strstr(filename, "..") != 0) {
335                 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
336                 buffer_sprintf(w->response.data, "File '%s' cannot be served. Relative filenames with '..' in them are not supported.", filename);
337                 return 400;
338         }
339
340         // access the file
341         char webfilename[FILENAME_MAX + 1];
342         snprintfz(webfilename, FILENAME_MAX, "%s/%s", web_dir, filename);
343
344         // check if the file exists
345         struct stat stat;
346         if(lstat(webfilename, &stat) != 0) {
347                 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not found.", w->id, webfilename);
348                 buffer_sprintf(w->response.data, "File '%s' does not exist, or is not accessible.", webfilename);
349                 return 404;
350         }
351
352         // check if the file is owned by expected user
353         if(stat.st_uid != web_files_uid()) {
354                 error("%llu: File '%s' is owned by user %d (expected user %d). Access Denied.", w->id, webfilename, stat.st_uid, web_files_uid());
355                 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", webfilename);
356                 return 403;
357         }
358
359         // check if the file is owned by expected group
360         if(stat.st_gid != web_files_gid()) {
361                 error("%llu: File '%s' is owned by group %d (expected group %d). Access Denied.", w->id, webfilename, stat.st_gid, web_files_gid());
362                 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", webfilename);
363                 return 403;
364         }
365
366         if((stat.st_mode & S_IFMT) == S_IFDIR) {
367                 snprintfz(webfilename, FILENAME_MAX, "%s/index.html", filename);
368                 return mysendfile(w, webfilename);
369         }
370
371         if((stat.st_mode & S_IFMT) != S_IFREG) {
372                 error("%llu: File '%s' is not a regular file. Access Denied.", w->id, webfilename);
373                 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", webfilename);
374                 return 403;
375         }
376
377         // open the file
378         w->ifd = open(webfilename, O_NONBLOCK, O_RDONLY);
379         if(w->ifd == -1) {
380                 w->ifd = w->ofd;
381
382                 if(errno == EBUSY || errno == EAGAIN) {
383                         error("%llu: File '%s' is busy, sending 307 Moved Temporarily to force retry.", w->id, webfilename);
384                         buffer_sprintf(w->response.header, "Location: /" WEB_PATH_FILE "/%s\r\n", filename);
385                         buffer_sprintf(w->response.data, "The file '%s' is currently busy. Please try again later.", webfilename);
386                         return 307;
387                 }
388                 else {
389                         error("%llu: Cannot open file '%s'.", w->id, webfilename);
390                         buffer_sprintf(w->response.data, "Cannot open file '%s'.", webfilename);
391                         return 404;
392                 }
393         }
394
395         // pick a Content-Type for the file
396                  if(strstr(filename, ".html") != NULL)  w->response.data->contenttype = CT_TEXT_HTML;
397         else if(strstr(filename, ".js")   != NULL)      w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
398         else if(strstr(filename, ".css")  != NULL)      w->response.data->contenttype = CT_TEXT_CSS;
399         else if(strstr(filename, ".xml")  != NULL)      w->response.data->contenttype = CT_TEXT_XML;
400         else if(strstr(filename, ".xsl")  != NULL)      w->response.data->contenttype = CT_TEXT_XSL;
401         else if(strstr(filename, ".txt")  != NULL)  w->response.data->contenttype = CT_TEXT_PLAIN;
402         else if(strstr(filename, ".svg")  != NULL)  w->response.data->contenttype = CT_IMAGE_SVG_XML;
403         else if(strstr(filename, ".ttf")  != NULL)  w->response.data->contenttype = CT_APPLICATION_X_FONT_TRUETYPE;
404         else if(strstr(filename, ".otf")  != NULL)  w->response.data->contenttype = CT_APPLICATION_X_FONT_OPENTYPE;
405         else if(strstr(filename, ".woff2")!= NULL)  w->response.data->contenttype = CT_APPLICATION_FONT_WOFF2;
406         else if(strstr(filename, ".woff") != NULL)  w->response.data->contenttype = CT_APPLICATION_FONT_WOFF;
407         else if(strstr(filename, ".eot")  != NULL)  w->response.data->contenttype = CT_APPLICATION_VND_MS_FONTOBJ;
408         else if(strstr(filename, ".png")  != NULL)  w->response.data->contenttype = CT_IMAGE_PNG;
409         else if(strstr(filename, ".jpg")  != NULL)  w->response.data->contenttype = CT_IMAGE_JPG;
410         else if(strstr(filename, ".jpeg") != NULL)  w->response.data->contenttype = CT_IMAGE_JPG;
411         else if(strstr(filename, ".gif")  != NULL)  w->response.data->contenttype = CT_IMAGE_GIF;
412         else if(strstr(filename, ".bmp")  != NULL)  w->response.data->contenttype = CT_IMAGE_BMP;
413         else if(strstr(filename, ".ico")  != NULL)  w->response.data->contenttype = CT_IMAGE_XICON;
414         else if(strstr(filename, ".icns") != NULL)  w->response.data->contenttype = CT_IMAGE_ICNS;
415         else w->response.data->contenttype = CT_APPLICATION_OCTET_STREAM;
416
417         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);
418
419         w->mode = WEB_CLIENT_MODE_FILECOPY;
420         w->wait_receive = 1;
421         w->wait_send = 0;
422         buffer_flush(w->response.data);
423         w->response.rlen = stat.st_size;
424         w->response.data->date = stat.st_mtim.tv_sec;
425
426         return 200;
427 }
428
429
430 #ifdef NETDATA_WITH_ZLIB
431 void web_client_enable_deflate(struct web_client *w) {
432         if(w->response.zinitialized == 1) {
433                 error("%llu: Compression has already be initialized for this client.", w->id);
434                 return;
435         }
436
437         if(w->response.sent) {
438                 error("%llu: Cannot enable compression in the middle of a conversation.", w->id);
439                 return;
440         }
441
442         w->response.zstream.zalloc = Z_NULL;
443         w->response.zstream.zfree = Z_NULL;
444         w->response.zstream.opaque = Z_NULL;
445
446         w->response.zstream.next_in = (Bytef *)w->response.data->buffer;
447         w->response.zstream.avail_in = 0;
448         w->response.zstream.total_in = 0;
449
450         w->response.zstream.next_out = w->response.zbuffer;
451         w->response.zstream.avail_out = 0;
452         w->response.zstream.total_out = 0;
453
454         w->response.zstream.zalloc = Z_NULL;
455         w->response.zstream.zfree = Z_NULL;
456         w->response.zstream.opaque = Z_NULL;
457
458 //      if(deflateInit(&w->response.zstream, Z_DEFAULT_COMPRESSION) != Z_OK) {
459 //              error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
460 //              return;
461 //      }
462
463         // Select GZIP compression: windowbits = 15 + 16 = 31
464         if(deflateInit2(&w->response.zstream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY) != Z_OK) {
465                 error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
466                 return;
467         }
468
469         w->response.zsent = 0;
470         w->response.zoutput = 1;
471         w->response.zinitialized = 1;
472
473         debug(D_DEFLATE, "%llu: Initialized compression.", w->id);
474 }
475 #endif // NETDATA_WITH_ZLIB
476
477 uint32_t web_client_api_request_v1_data_options(char *o)
478 {
479         uint32_t ret = 0x00000000;
480         char *tok;
481
482         while(o && *o && (tok = mystrsep(&o, ", |"))) {
483                 if(!*tok) continue;
484
485                 if(!strcmp(tok, "nonzero"))
486                         ret |= RRDR_OPTION_NONZERO;
487                 else if(!strcmp(tok, "flip") || !strcmp(tok, "reversed") || !strcmp(tok, "reverse"))
488                         ret |= RRDR_OPTION_REVERSED;
489                 else if(!strcmp(tok, "jsonwrap"))
490                         ret |= RRDR_OPTION_JSON_WRAP;
491                 else if(!strcmp(tok, "min2max"))
492                         ret |= RRDR_OPTION_MIN2MAX;
493                 else if(!strcmp(tok, "ms") || !strcmp(tok, "milliseconds"))
494                         ret |= RRDR_OPTION_MILLISECONDS;
495                 else if(!strcmp(tok, "abs") || !strcmp(tok, "absolute") || !strcmp(tok, "absolute_sum") || !strcmp(tok, "absolute-sum"))
496                         ret |= RRDR_OPTION_ABSOLUTE;
497                 else if(!strcmp(tok, "seconds"))
498                         ret |= RRDR_OPTION_SECONDS;
499                 else if(!strcmp(tok, "null2zero"))
500                         ret |= RRDR_OPTION_NULL2ZERO;
501                 else if(!strcmp(tok, "objectrows"))
502                         ret |= RRDR_OPTION_OBJECTSROWS;
503                 else if(!strcmp(tok, "google_json"))
504                         ret |= RRDR_OPTION_GOOGLE_JSON;
505                 else if(!strcmp(tok, "percentage"))
506                         ret |= RRDR_OPTION_PERCENTAGE;
507         }
508
509         return ret;
510 }
511
512 uint32_t web_client_api_request_v1_data_format(char *name)
513 {
514         if(!strcmp(name, DATASOURCE_FORMAT_DATATABLE_JSON)) // datatable
515                 return DATASOURCE_DATATABLE_JSON;
516
517         else if(!strcmp(name, DATASOURCE_FORMAT_DATATABLE_JSONP)) // datasource
518                 return DATASOURCE_DATATABLE_JSONP;
519
520         else if(!strcmp(name, DATASOURCE_FORMAT_JSON)) // json
521                 return DATASOURCE_JSON;
522
523         else if(!strcmp(name, DATASOURCE_FORMAT_JSONP)) // jsonp
524                 return DATASOURCE_JSONP;
525
526         else if(!strcmp(name, DATASOURCE_FORMAT_SSV)) // ssv
527                 return DATASOURCE_SSV;
528
529         else if(!strcmp(name, DATASOURCE_FORMAT_CSV)) // csv
530                 return DATASOURCE_CSV;
531
532         else if(!strcmp(name, DATASOURCE_FORMAT_TSV) || !strcmp(name, "tsv-excel")) // tsv
533                 return DATASOURCE_TSV;
534
535         else if(!strcmp(name, DATASOURCE_FORMAT_HTML)) // html
536                 return DATASOURCE_HTML;
537
538         else if(!strcmp(name, DATASOURCE_FORMAT_JS_ARRAY)) // array
539                 return DATASOURCE_JS_ARRAY;
540
541         else if(!strcmp(name, DATASOURCE_FORMAT_SSV_COMMA)) // ssvcomma
542                 return DATASOURCE_SSV_COMMA;
543
544         else if(!strcmp(name, DATASOURCE_FORMAT_CSV_JSON_ARRAY)) // csvjsonarray
545                 return DATASOURCE_CSV_JSON_ARRAY;
546
547         return DATASOURCE_JSON;
548 }
549
550 uint32_t web_client_api_request_v1_data_google_format(char *name)
551 {
552         if(!strcmp(name, "json"))
553                 return DATASOURCE_DATATABLE_JSONP;
554
555         else if(!strcmp(name, "html"))
556                 return DATASOURCE_HTML;
557
558         else if(!strcmp(name, "csv"))
559                 return DATASOURCE_CSV;
560
561         else if(!strcmp(name, "tsv-excel"))
562                 return DATASOURCE_TSV;
563
564         return DATASOURCE_JSON;
565 }
566
567 int web_client_api_request_v1_data_group(char *name)
568 {
569         if(!strcmp(name, "max"))
570                 return GROUP_MAX;
571
572         else if(!strcmp(name, "average"))
573                 return GROUP_AVERAGE;
574
575         return GROUP_MAX;
576 }
577
578 int web_client_api_request_v1_charts(struct web_client *w, char *url)
579 {
580         if(url) { ; }
581
582         buffer_flush(w->response.data);
583         w->response.data->contenttype = CT_APPLICATION_JSON;
584         rrd_stats_api_v1_charts(w->response.data);
585         return 200;
586 }
587
588 int web_client_api_request_v1_chart(struct web_client *w, char *url)
589 {
590         int ret = 400;
591         char *chart = NULL;
592
593         buffer_flush(w->response.data);
594
595         while(url) {
596                 char *value = mystrsep(&url, "?&[]");
597                 if(!value || !*value) continue;
598
599                 char *name = mystrsep(&value, "=");
600                 if(!name || !*name) continue;
601                 if(!value || !*value) continue;
602
603                 // name and value are now the parameters
604                 // they are not null and not empty
605
606                 if(!strcmp(name, "chart")) chart = value;
607                 //else {
608                 ///     buffer_sprintf(w->response.data, "Unknown parameter '%s' in request.", name);
609                 //      goto cleanup;
610                 //}
611         }
612
613         if(!chart || !*chart) {
614                 buffer_sprintf(w->response.data, "No chart id is given at the request.");
615                 goto cleanup;
616         }
617
618         RRDSET *st = rrdset_find(chart);
619         if(!st) st = rrdset_find_byname(chart);
620         if(!st) {
621                 buffer_sprintf(w->response.data, "Chart '%s' is not found.", chart);
622                 ret = 404;
623                 goto cleanup;
624         }
625
626         w->response.data->contenttype = CT_APPLICATION_JSON;
627         rrd_stats_api_v1_chart(st, w->response.data);
628         return 200;
629
630 cleanup:
631         return ret;
632 }
633
634 // returns the HTTP code
635 int web_client_api_request_v1_data(struct web_client *w, char *url)
636 {
637         debug(D_WEB_CLIENT, "%llu: API v1 data with URL '%s'", w->id, url);
638
639         int ret = 400;
640         BUFFER *dimensions = NULL;
641
642         buffer_flush(w->response.data);
643
644         char    *google_version = "0.6",
645                         *google_reqId = "0",
646                         *google_sig = "0",
647                         *google_out = "json",
648                         *responseHandler = NULL,
649                         *outFileName = NULL;
650
651         time_t last_timestamp_in_data = 0, google_timestamp = 0;
652
653         char *chart = NULL
654                         , *before_str = NULL
655                         , *after_str = NULL
656                         , *points_str = NULL;
657
658         int group = GROUP_MAX;
659         uint32_t format = DATASOURCE_JSON;
660         uint32_t options = 0x00000000;
661
662         while(url) {
663                 char *value = mystrsep(&url, "?&[]");
664                 if(!value || !*value) continue;
665
666                 char *name = mystrsep(&value, "=");
667                 if(!name || !*name) continue;
668                 if(!value || !*value) continue;
669
670                 debug(D_WEB_CLIENT, "%llu: API v1 data query param '%s' with value '%s'", w->id, name, value);
671
672                 // name and value are now the parameters
673                 // they are not null and not empty
674
675                 if(!strcmp(name, "chart")) chart = value;
676                 else if(!strcmp(name, "dimension") || !strcmp(name, "dim") || !strcmp(name, "dimensions") || !strcmp(name, "dims")) {
677                         if(!dimensions) dimensions = buffer_create(strlen(value));
678                         if(dimensions) {
679                                 buffer_strcat(dimensions, "|");
680                                 buffer_strcat(dimensions, value);
681                         }
682                 }
683                 else if(!strcmp(name, "after")) after_str = value;
684                 else if(!strcmp(name, "before")) before_str = value;
685                 else if(!strcmp(name, "points")) points_str = value;
686                 else if(!strcmp(name, "group")) {
687                         group = web_client_api_request_v1_data_group(value);
688                 }
689                 else if(!strcmp(name, "format")) {
690                         format = web_client_api_request_v1_data_format(value);
691                 }
692                 else if(!strcmp(name, "options")) {
693                         options |= web_client_api_request_v1_data_options(value);
694                 }
695                 else if(!strcmp(name, "callback")) {
696                         responseHandler = value;
697                 }
698                 else if(!strcmp(name, "filename")) {
699                         outFileName = value;
700                 }
701                 else if(!strcmp(name, "tqx")) {
702                         // parse Google Visualization API options
703                         // https://developers.google.com/chart/interactive/docs/dev/implementing_data_source
704                         char *tqx_name, *tqx_value;
705
706                         while(value) {
707                                 tqx_value = mystrsep(&value, ";");
708                                 if(!tqx_value || !*tqx_value) continue;
709
710                                 tqx_name = mystrsep(&tqx_value, ":");
711                                 if(!tqx_name || !*tqx_name) continue;
712                                 if(!tqx_value || !*tqx_value) continue;
713
714                                 if(!strcmp(tqx_name, "version"))
715                                         google_version = tqx_value;
716                                 else if(!strcmp(tqx_name, "reqId"))
717                                         google_reqId = tqx_value;
718                                 else if(!strcmp(tqx_name, "sig")) {
719                                         google_sig = tqx_value;
720                                         google_timestamp = strtoul(google_sig, NULL, 0);
721                                 }
722                                 else if(!strcmp(tqx_name, "out")) {
723                                         google_out = tqx_value;
724                                         format = web_client_api_request_v1_data_google_format(google_out);
725                                 }
726                                 else if(!strcmp(tqx_name, "responseHandler"))
727                                         responseHandler = tqx_value;
728                                 else if(!strcmp(tqx_name, "outFileName"))
729                                         outFileName = tqx_value;
730                         }
731                 }
732         }
733
734         if(!chart || !*chart) {
735                 buffer_sprintf(w->response.data, "No chart id is given at the request.");
736                 goto cleanup;
737         }
738
739         RRDSET *st = rrdset_find(chart);
740         if(!st) st = rrdset_find_byname(chart);
741         if(!st) {
742                 buffer_sprintf(w->response.data, "Chart '%s' is not found.", chart);
743                 ret = 404;
744                 goto cleanup;
745         }
746
747         long long before = (before_str && *before_str)?atol(before_str):0;
748         long long after  = (after_str  && *after_str) ?atol(after_str):0;
749         int       points = (points_str && *points_str)?atoi(points_str):0;
750
751         debug(D_WEB_CLIENT, "%llu: API command 'data' for chart '%s', dimensions '%s', after '%lld', before '%lld', points '%d', group '%u', format '%u', options '0x%08x'"
752                         , w->id
753                         , chart
754                         , (dimensions)?buffer_tostring(dimensions):""
755                         , after
756                         , before
757                         , points
758                         , group
759                         , format
760                         , options
761                         );
762
763         if(outFileName && *outFileName) {
764                 buffer_sprintf(w->response.header, "Content-Disposition: attachment; filename=\"%s\"\r\n", outFileName);
765                 error("generating outfilename header: '%s'", outFileName);
766         }
767
768         if(format == DATASOURCE_DATATABLE_JSONP) {
769                 if(responseHandler == NULL)
770                         responseHandler = "google.visualization.Query.setResponse";
771
772                 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSON/JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
773                                 w->id, google_version, google_reqId, google_sig, google_out, responseHandler, outFileName
774                         );
775
776                 buffer_sprintf(w->response.data,
777                         "%s({version:'%s',reqId:'%s',status:'ok',sig:'%lu',table:",
778                         responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
779         }
780         else if(format == DATASOURCE_JSONP) {
781                 if(responseHandler == NULL)
782                         responseHandler = "callback";
783
784                 buffer_strcat(w->response.data, responseHandler);
785                 buffer_strcat(w->response.data, "(");
786         }
787
788         ret = rrd2format(st, w->response.data, dimensions, format, points, after, before, group, options, &last_timestamp_in_data);
789
790         if(format == DATASOURCE_DATATABLE_JSONP) {
791                 if(google_timestamp < last_timestamp_in_data)
792                         buffer_strcat(w->response.data, "});");
793
794                 else {
795                         // the client already has the latest data
796                         buffer_flush(w->response.data);
797                         buffer_sprintf(w->response.data,
798                                 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
799                                 responseHandler, google_version, google_reqId);
800                 }
801         }
802         else if(format == DATASOURCE_JSONP)
803                 buffer_strcat(w->response.data, ");");
804
805 cleanup:
806         if(dimensions) buffer_free(dimensions);
807         return ret;
808 }
809
810 int web_client_api_request_v1_registry(struct web_client *w, char *url)
811 {
812         char person_guid[36 + 1] = "";
813
814         debug(D_WEB_CLIENT, "%llu: API v1 registry with URL '%s'", w->id, url);
815
816         // FIXME
817         // The browser may send multiple cookies with our id
818         
819         char *cookie = strstr(w->response.data->buffer, " " NETDATA_REGISTRY_COOKIE_NAME "=");
820         if(cookie)
821                 strncpyz(person_guid, &cookie[sizeof(NETDATA_REGISTRY_COOKIE_NAME) + 1], 36);
822
823         char action = '\0';
824         char *machine_guid = NULL,
825                         *machine_url = NULL,
826                         *url_name = NULL,
827                         *search_machine_guid = NULL,
828                         *delete_url = NULL,
829                         *to_person_guid = NULL;
830
831         while(url) {
832                 char *value = mystrsep(&url, "?&[]");
833                 if (!value || !*value) continue;
834
835                 char *name = mystrsep(&value, "=");
836                 if (!name || !*name) continue;
837                 if (!value || !*value) continue;
838
839                 debug(D_WEB_CLIENT, "%llu: API v1 registry query param '%s' with value '%s'", w->id, name, value);
840
841                 if(!strcmp(name, "action")) {
842                         if(!strcmp(value, "access")) action = 'A';
843                         else if(!strcmp(value, "hello")) action = 'H';
844                         else if(!strcmp(value, "delete")) action = 'D';
845                         else if(!strcmp(value, "search")) action = 'S';
846                         else if(!strcmp(value, "switch")) action = 'W';
847                 }
848                 else if(!strcmp(name, "machine"))
849                         machine_guid = value;
850
851                 else if(!strcmp(name, "url"))
852                         machine_url = value;
853
854                 else if(action == 'A') {
855                         if(!strcmp(name, "name"))
856                                 url_name = value;
857                 }
858                 else if(action == 'D') {
859                         if(!strcmp(name, "delete_url"))
860                                 delete_url = value;
861                 }
862                 else if(action == 'S') {
863                         if(!strcmp(name, "for"))
864                                 search_machine_guid = value;
865                 }
866                 else if(action == 'W') {
867                         if(!strcmp(name, "to"))
868                                 to_person_guid = value;
869                 }
870         }
871
872         if(action == 'A' && (!machine_guid || !machine_url || !url_name)) {
873                 buffer_flush(w->response.data);
874                 buffer_sprintf(w->response.data, "Invalid registry request - access requires these parameters: machine ('%s'), url ('%s'), name ('%s')",
875                                            machine_guid?machine_guid:"UNSET", machine_url?machine_url:"UNSET", url_name?url_name:"UNSET");
876                 return 400;
877         }
878         else if(action == 'D' && (!machine_guid || !machine_url || !delete_url)) {
879                 buffer_flush(w->response.data);
880                 buffer_sprintf(w->response.data, "Invalid registry request - delete requires these parameters: machine ('%s'), url ('%s'), delete_url ('%s')",
881                                            machine_guid?machine_guid:"UNSET", machine_url?machine_url:"UNSET", delete_url?delete_url:"UNSET");
882                 return 400;
883         }
884         else if(action == 'S' && (!machine_guid || !machine_url || !search_machine_guid)) {
885                 buffer_flush(w->response.data);
886                 buffer_sprintf(w->response.data, "Invalid registry request - search requires these parameters: machine ('%s'), url ('%s'), for ('%s')",
887                                            machine_guid?machine_guid:"UNSET", machine_url?machine_url:"UNSET", search_machine_guid?search_machine_guid:"UNSET");
888                 return 400;
889         }
890         else if(action == 'W' && (!machine_guid || !machine_url || !to_person_guid)) {
891                 buffer_flush(w->response.data);
892                 buffer_sprintf(w->response.data, "Invalid registry request - switching identity requires these parameters: machine ('%s'), url ('%s'), to ('%s')",
893                                            machine_guid?machine_guid:"UNSET", machine_url?machine_url:"UNSET", to_person_guid?to_person_guid:"UNSET");
894                 return 400;
895         }
896
897         switch(action) {
898                 case 'A':
899                         return registry_request_access_json(w, person_guid, machine_guid, machine_url, url_name, time(NULL));
900
901                 case 'D':
902                         return registry_request_delete_json(w, person_guid, machine_guid, machine_url, delete_url, time(NULL));
903
904                 case 'S':
905                         return registry_request_search_json(w, person_guid, machine_guid, machine_url, search_machine_guid, time(NULL));
906
907                 case 'W':
908                         return registry_request_switch_json(w, person_guid, machine_guid, machine_url, to_person_guid, time(NULL));
909
910                 case 'H':
911                         return registry_request_hello_json(w);
912
913                 default:
914                         buffer_flush(w->response.data);
915                         buffer_sprintf(w->response.data, "Invalid registry request - you need to set an action: hello, access, delete, search");
916                         return 400;
917         }
918
919         buffer_flush(w->response.data);
920         buffer_sprintf(w->response.data, "Invalid or no registry action.");
921         return 400;
922 }
923
924 int web_client_api_request_v1(struct web_client *w, char *url)
925 {
926         static uint32_t data_hash = 0, chart_hash = 0, charts_hash = 0, registry_hash = 0;
927
928         if(unlikely(data_hash == 0)) {
929                 data_hash = simple_hash("data");
930                 chart_hash = simple_hash("chart");
931                 charts_hash = simple_hash("charts");
932                 registry_hash = simple_hash("registry");
933         }
934
935         // get the command
936         char *tok = mystrsep(&url, "/?&");
937         if(tok && *tok) {
938                 debug(D_WEB_CLIENT, "%llu: Searching for API v1 command '%s'.", w->id, tok);
939                 uint32_t hash = simple_hash(tok);
940
941                 if(hash == data_hash && !strcmp(tok, "data"))
942                         return web_client_api_request_v1_data(w, url);
943
944                 else if(hash == chart_hash && !strcmp(tok, "chart"))
945                         return web_client_api_request_v1_chart(w, url);
946
947                 else if(hash == charts_hash && !strcmp(tok, "charts"))
948                         return web_client_api_request_v1_charts(w, url);
949
950                 else if(hash == registry_hash && !strcmp(tok, "registry"))
951                         return web_client_api_request_v1_registry(w, url);
952
953                 else {
954                         buffer_flush(w->response.data);
955                         buffer_sprintf(w->response.data, "Unsupported v1 API command: %s", tok);
956                         return 404;
957                 }
958         }
959         else {
960                 buffer_flush(w->response.data);
961                 buffer_sprintf(w->response.data, "API v1 command?");
962                 return 400;
963         }
964 }
965
966 int web_client_api_request(struct web_client *w, char *url)
967 {
968         // get the api version
969         char *tok = mystrsep(&url, "/?&");
970         if(tok && *tok) {
971                 debug(D_WEB_CLIENT, "%llu: Searching for API version '%s'.", w->id, tok);
972                 if(strcmp(tok, "v1") == 0)
973                         return web_client_api_request_v1(w, url);
974                 else {
975                         buffer_flush(w->response.data);
976                         buffer_sprintf(w->response.data, "Unsupported API version: %s", tok);
977                         return 404;
978                 }
979         }
980         else {
981                 buffer_flush(w->response.data);
982                 buffer_sprintf(w->response.data, "Which API version?");
983                 return 400;
984         }
985 }
986
987 int web_client_data_request(struct web_client *w, char *url, int datasource_type)
988 {
989         RRDSET *st = NULL;
990
991         char *args = strchr(url, '?');
992         if(args) {
993                 *args='\0';
994                 args = &args[1];
995         }
996
997         // get the name of the data to show
998         char *tok = mystrsep(&url, "/");
999
1000         // do we have such a data set?
1001         if(tok && *tok) {
1002                 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1003                 st = rrdset_find_byname(tok);
1004                 if(!st) st = rrdset_find(tok);
1005         }
1006
1007         if(!st) {
1008                 // we don't have it
1009                 // try to send a file with that name
1010                 buffer_flush(w->response.data);
1011                 return(mysendfile(w, tok));
1012         }
1013
1014         // we have it
1015         debug(D_WEB_CLIENT, "%llu: Found RRD data with name '%s'.", w->id, tok);
1016
1017         // how many entries does the client want?
1018         long lines = rrd_default_history_entries;
1019         long group_count = 1;
1020         time_t after = 0, before = 0;
1021         int group_method = GROUP_AVERAGE;
1022         int nonzero = 0;
1023
1024         if(url) {
1025                 // parse the lines required
1026                 tok = mystrsep(&url, "/");
1027                 if(tok) lines = atoi(tok);
1028                 if(lines < 1) lines = 1;
1029         }
1030         if(url) {
1031                 // parse the group count required
1032                 tok = mystrsep(&url, "/");
1033                 if(tok && *tok) group_count = atoi(tok);
1034                 if(group_count < 1) group_count = 1;
1035                 //if(group_count > save_history / 20) group_count = save_history / 20;
1036         }
1037         if(url) {
1038                 // parse the grouping method required
1039                 tok = mystrsep(&url, "/");
1040                 if(tok && *tok) {
1041                         if(strcmp(tok, "max") == 0) group_method = GROUP_MAX;
1042                         else if(strcmp(tok, "average") == 0) group_method = GROUP_AVERAGE;
1043                         else if(strcmp(tok, "sum") == 0) group_method = GROUP_SUM;
1044                         else debug(D_WEB_CLIENT, "%llu: Unknown group method '%s'", w->id, tok);
1045                 }
1046         }
1047         if(url) {
1048                 // parse after time
1049                 tok = mystrsep(&url, "/");
1050                 if(tok && *tok) after = strtoul(tok, NULL, 10);
1051                 if(after < 0) after = 0;
1052         }
1053         if(url) {
1054                 // parse before time
1055                 tok = mystrsep(&url, "/");
1056                 if(tok && *tok) before = strtoul(tok, NULL, 10);
1057                 if(before < 0) before = 0;
1058         }
1059         if(url) {
1060                 // parse nonzero
1061                 tok = mystrsep(&url, "/");
1062                 if(tok && *tok && strcmp(tok, "nonzero") == 0) nonzero = 1;
1063         }
1064
1065         w->response.data->contenttype = CT_APPLICATION_JSON;
1066         buffer_flush(w->response.data);
1067
1068         char *google_version = "0.6";
1069         char *google_reqId = "0";
1070         char *google_sig = "0";
1071         char *google_out = "json";
1072         char *google_responseHandler = "google.visualization.Query.setResponse";
1073         char *google_outFileName = NULL;
1074         time_t last_timestamp_in_data = 0;
1075         if(datasource_type == DATASOURCE_DATATABLE_JSON || datasource_type == DATASOURCE_DATATABLE_JSONP) {
1076
1077                 w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
1078
1079                 while(args) {
1080                         tok = mystrsep(&args, "&");
1081                         if(tok && *tok) {
1082                                 char *name = mystrsep(&tok, "=");
1083                                 if(name && *name && strcmp(name, "tqx") == 0) {
1084                                         char *key = mystrsep(&tok, ":");
1085                                         char *value = mystrsep(&tok, ";");
1086                                         if(key && value && *key && *value) {
1087                                                 if(strcmp(key, "version") == 0)
1088                                                         google_version = value;
1089
1090                                                 else if(strcmp(key, "reqId") == 0)
1091                                                         google_reqId = value;
1092
1093                                                 else if(strcmp(key, "sig") == 0)
1094                                                         google_sig = value;
1095
1096                                                 else if(strcmp(key, "out") == 0)
1097                                                         google_out = value;
1098
1099                                                 else if(strcmp(key, "responseHandler") == 0)
1100                                                         google_responseHandler = value;
1101
1102                                                 else if(strcmp(key, "outFileName") == 0)
1103                                                         google_outFileName = value;
1104                                         }
1105                                 }
1106                         }
1107                 }
1108
1109                 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
1110                         w->id, google_version, google_reqId, google_sig, google_out, google_responseHandler, google_outFileName
1111                         );
1112
1113                 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
1114                         last_timestamp_in_data = strtoul(google_sig, NULL, 0);
1115
1116                         // check the client wants json
1117                         if(strcmp(google_out, "json") != 0) {
1118                                 buffer_sprintf(w->response.data,
1119                                         "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'invalid_query',message:'output format is not supported',detailed_message:'the format %s requested is not supported by netdata.'}]});",
1120                                         google_responseHandler, google_version, google_reqId, google_out);
1121                                         return 200;
1122                         }
1123                 }
1124         }
1125
1126         if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
1127                 buffer_sprintf(w->response.data,
1128                         "%s({version:'%s',reqId:'%s',status:'ok',sig:'%lu',table:",
1129                         google_responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
1130         }
1131
1132         debug(D_WEB_CLIENT_ACCESS, "%llu: Sending RRD data '%s' (id %s, %d lines, %d group, %d group_method, %lu after, %lu before).", w->id, st->name, st->id, lines, group_count, group_method, after, before);
1133         time_t timestamp_in_data = rrd_stats_json(datasource_type, st, w->response.data, lines, group_count, group_method, after, before, nonzero);
1134
1135         if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
1136                 if(timestamp_in_data > last_timestamp_in_data)
1137                         buffer_strcat(w->response.data, "});");
1138
1139                 else {
1140                         // the client already has the latest data
1141                         buffer_flush(w->response.data);
1142                         buffer_sprintf(w->response.data,
1143                                 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
1144                                 google_responseHandler, google_version, google_reqId);
1145                 }
1146         }
1147
1148         return 200;
1149 }
1150
1151 /*
1152 int web_client_parse_request(struct web_client *w) {
1153         // protocol
1154         // hostname
1155         // path
1156         // query string name-value
1157         // http version
1158         // method
1159         // http request headers name-value
1160
1161         web_client_clean_request(w);
1162
1163         debug(D_WEB_DATA, "%llu: Processing data buffer of %d bytes: '%s'.", w->id, w->response.data->bytes, w->response.data->buffer);
1164
1165         char *buf = w->response.data->buffer;
1166         char *line, *tok;
1167
1168         // ------------------------------------------------------------------------
1169         // the first line
1170
1171         if(buf && (line = strsep(&buf, "\r\n"))) {
1172                 // method
1173                 if(line && (tok = strsep(&line, " "))) {
1174                         w->request.protocol = strdup(tok);
1175                 }
1176                 else goto cleanup;
1177
1178                 // url
1179         }
1180         else goto cleanup;
1181
1182         // ------------------------------------------------------------------------
1183         // the rest of the lines
1184
1185         while(buf && (line = strsep(&buf, "\r\n"))) {
1186                 while(line && (tok = strsep(&line, ": "))) {
1187                 }
1188         }
1189
1190         char *url = NULL;
1191
1192
1193 cleanup:
1194         web_client_clean_request(w);
1195         return 0;
1196 }
1197 */
1198
1199
1200 static inline char *http_header_parse(struct web_client *w, char *s) {
1201         char *e = s;
1202
1203         // find the :
1204         while(*e && *e != ':') e++;
1205         if(!*e || e[1] != ' ') return e;
1206
1207         // get the name
1208         *e = '\0';
1209
1210         // find the value
1211         char *v, *ve;
1212         v = ve = e + 2;
1213
1214         // find the \r
1215         while(*ve && *ve != '\r') ve++;
1216         if(!*ve || ve[1] != '\n') {
1217                 *e = ':';
1218                 return ve;
1219         }
1220
1221         // terminate the value
1222         *ve = '\0';
1223
1224         // fprintf(stderr, "HEADER: '%s' = '%s'\n", s, v);
1225
1226         if(!strcasecmp(s, "Origin"))
1227                 strncpyz(w->origin, v, ORIGIN_MAX);
1228
1229         else if(!strcasecmp(s, "Connection")) {
1230                 if(strcasestr(v, "keep-alive"))
1231                         w->keepalive = 1;
1232         }
1233 #ifdef NETDATA_WITH_ZLIB
1234         else if(!strcasecmp(s, "Accept-Encoding")) {
1235                 if(web_enable_gzip && strcasestr(v, "gzip")) {
1236                         w->enable_gzip = 1;
1237                 }
1238         }
1239 #endif /* NETDATA_WITH_ZLIB */
1240
1241         *e = ':';
1242         *ve = '\r';
1243         return ve;
1244 }
1245
1246 // http_request_validate()
1247 // returns:
1248 // = 0 : all good, process the request
1249 // > 0 : request is complete, but is not supported
1250 // < 0 : request is incomplete - wait for more data
1251
1252 static inline int http_request_validate(struct web_client *w) {
1253         char *s = w->response.data->buffer, *encoded_url = NULL;
1254
1255         // is is a valid request?
1256         if(!strncmp(s, "GET ", 4)) {
1257                 encoded_url = s = &s[4];
1258                 w->mode = WEB_CLIENT_MODE_NORMAL;
1259         }
1260         else if(!strncmp(s, "OPTIONS ", 8)) {
1261                 encoded_url = s = &s[8];
1262                 w->mode = WEB_CLIENT_MODE_OPTIONS;
1263         }
1264         else {
1265                 w->wait_receive = 0;
1266                 return 1;
1267         }
1268
1269         // find the SPACE + "HTTP/"
1270         while(*s) {
1271                 // find the space
1272                 while (*s && *s != ' ') s++;
1273
1274                 // is it SPACE + "HTTP/" ?
1275                 if(*s && !strncmp(s, " HTTP/", 6)) break;
1276                 else s++;
1277         }
1278
1279         // incomplete requests
1280         if(!*s) {
1281                 w->wait_receive = 1;
1282                 return -2;
1283         }
1284
1285         // we have the end of encoded_url - remember it
1286         char *ue = s;
1287
1288         while(*s) {
1289                 // find a line feed
1290                 while (*s && *s != '\r') s++;
1291
1292                 // did we reach the end?
1293                 if(unlikely(!*s)) break;
1294
1295                 // is it \r\n ?
1296                 if (likely(s[1] == '\n')) {
1297
1298                         // is it again \r\n ? (header end)
1299                         if(unlikely(s[2] == '\r' && s[3] == '\n')) {
1300                                 // a valid complete HTTP request found
1301
1302                                 *ue = '\0';
1303                                 w->decoded_url = url_decode(encoded_url);
1304                                 *ue = ' ';
1305
1306                                 w->wait_receive = 0;
1307                                 return 0;
1308                         }
1309
1310                         // another header line
1311                         s = http_header_parse(w, &s[2]);
1312                 }
1313                 else s++;
1314         }
1315
1316         // incomplete request
1317         w->wait_receive = 1;
1318         return -3;
1319 }
1320
1321 void web_client_process(struct web_client *w) {
1322         int code = 500;
1323         ssize_t bytes;
1324
1325         int what_to_do = http_request_validate(w);
1326
1327         // wait for more data
1328         if(what_to_do < 0) {
1329                 if(w->response.data->len > TOO_BIG_REQUEST) {
1330                         strcpy(w->last_url, "too big request");
1331
1332                         debug(D_WEB_CLIENT_ACCESS, "%llu: Received request is too big (%zd bytes).", w->id, w->response.data->len);
1333
1334                         code = 400;
1335                         buffer_flush(w->response.data);
1336                         buffer_sprintf(w->response.data, "Received request is too big  (%zd bytes).\r\n", w->response.data->len);
1337                 }
1338                 else {
1339                         // wait for more data
1340                         return;
1341                 }
1342         }
1343         else if(what_to_do > 0) {
1344                 strcpy(w->last_url, "not a valid response");
1345
1346                 debug(D_WEB_CLIENT_ACCESS, "%llu: Cannot understand '%s'.", w->id, w->response.data->buffer);
1347
1348                 code = 500;
1349                 buffer_flush(w->response.data);
1350                 buffer_strcat(w->response.data, "I don't understand you...\r\n");
1351         }
1352         else { // what_to_do == 0
1353                 gettimeofday(&w->tv_in, NULL);
1354
1355                 // copy the URL - we are going to overwrite parts of it
1356                 // FIXME -- we should avoid it
1357                 strncpyz(w->last_url, w->decoded_url, URL_MAX);
1358
1359                 if(w->mode == WEB_CLIENT_MODE_OPTIONS) {
1360                         code = 200;
1361                         w->response.data->contenttype = CT_TEXT_PLAIN;
1362                         buffer_flush(w->response.data);
1363                         buffer_strcat(w->response.data, "OK");
1364                 }
1365                 else {
1366 #ifdef NETDATA_WITH_ZLIB
1367                         if(w->enable_gzip)
1368                                 web_client_enable_deflate(w);
1369 #endif
1370
1371                         char *url = w->decoded_url;
1372                         char *tok = mystrsep(&url, "/?");
1373                         if(tok && *tok) {
1374                                 debug(D_WEB_CLIENT, "%llu: Processing command '%s'.", w->id, tok);
1375
1376                                 if(strcmp(tok, "api") == 0) {
1377                                         // the client is requesting api access
1378                                         code = web_client_api_request(w, url);
1379                                 }
1380                                 else if(strcmp(tok, "netdata.conf") == 0) {
1381                                         code = 200;
1382                                         debug(D_WEB_CLIENT_ACCESS, "%llu: Sending netdata.conf ...", w->id);
1383
1384                                         w->response.data->contenttype = CT_TEXT_PLAIN;
1385                                         buffer_flush(w->response.data);
1386                                         generate_config(w->response.data, 0);
1387                                 }
1388                                 else if(strcmp(tok, WEB_PATH_DATA) == 0) { // "data"
1389                                         // the client is requesting rrd data -- OLD API
1390                                         code = web_client_data_request(w, url, DATASOURCE_JSON);
1391                                 }
1392                                 else if(strcmp(tok, WEB_PATH_DATASOURCE) == 0) { // "datasource"
1393                                         // the client is requesting google datasource -- OLD API
1394                                         code = web_client_data_request(w, url, DATASOURCE_DATATABLE_JSONP);
1395                                 }
1396                                 else if(strcmp(tok, WEB_PATH_GRAPH) == 0) { // "graph"
1397                                         // the client is requesting an rrd graph -- OLD API
1398
1399                                         // get the name of the data to show
1400                                         tok = mystrsep(&url, "/?&");
1401                                         if(tok && *tok) {
1402                                                 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1403
1404                                                 // do we have such a data set?
1405                                                 RRDSET *st = rrdset_find_byname(tok);
1406                                                 if(!st) st = rrdset_find(tok);
1407                                                 if(!st) {
1408                                                         // we don't have it
1409                                                         // try to send a file with that name
1410                                                         buffer_flush(w->response.data);
1411                                                         code = mysendfile(w, tok);
1412                                                 }
1413                                                 else {
1414                                                         code = 200;
1415                                                         debug(D_WEB_CLIENT_ACCESS, "%llu: Sending %s.json of RRD_STATS...", w->id, st->name);
1416                                                         w->response.data->contenttype = CT_APPLICATION_JSON;
1417                                                         buffer_flush(w->response.data);
1418                                                         rrd_stats_graph_json(st, url, w->response.data);
1419                                                 }
1420                                         }
1421                                         else {
1422                                                 code = 400;
1423                                                 buffer_flush(w->response.data);
1424                                                 buffer_strcat(w->response.data, "Graph name?\r\n");
1425                                         }
1426                                 }
1427                                 else if(strcmp(tok, "list") == 0) {
1428                                         // OLD API
1429                                         code = 200;
1430
1431                                         debug(D_WEB_CLIENT_ACCESS, "%llu: Sending list of RRD_STATS...", w->id);
1432
1433                                         buffer_flush(w->response.data);
1434                                         RRDSET *st = rrdset_root;
1435
1436                                         for ( ; st ; st = st->next )
1437                                                 buffer_sprintf(w->response.data, "%s\n", st->name);
1438                                 }
1439                                 else if(strcmp(tok, "all.json") == 0) {
1440                                         // OLD API
1441                                         code = 200;
1442                                         debug(D_WEB_CLIENT_ACCESS, "%llu: Sending JSON list of all monitors of RRD_STATS...", w->id);
1443
1444                                         w->response.data->contenttype = CT_APPLICATION_JSON;
1445                                         buffer_flush(w->response.data);
1446                                         rrd_stats_all_json(w->response.data);
1447                                 }
1448 #ifdef NETDATA_INTERNAL_CHECKS
1449                                 else if(strcmp(tok, "exit") == 0) {
1450                                         code = 200;
1451                                         w->response.data->contenttype = CT_TEXT_PLAIN;
1452                                         buffer_flush(w->response.data);
1453
1454                                         if(!netdata_exit)
1455                                                 buffer_strcat(w->response.data, "ok, will do...");
1456                                         else
1457                                                 buffer_strcat(w->response.data, "I am doing it already");
1458
1459                                         netdata_exit = 1;
1460                                 }
1461                                 else if(strcmp(tok, "debug") == 0) {
1462                                         buffer_flush(w->response.data);
1463
1464                                         // get the name of the data to show
1465                                         tok = mystrsep(&url, "/?&");
1466                                         if(tok && *tok) {
1467                                                 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1468
1469                                                 // do we have such a data set?
1470                                                 RRDSET *st = rrdset_find_byname(tok);
1471                                                 if(!st) st = rrdset_find(tok);
1472                                                 if(!st) {
1473                                                         code = 404;
1474                                                         buffer_sprintf(w->response.data, "Chart %s is not found.\r\n", tok);
1475                                                         debug(D_WEB_CLIENT_ACCESS, "%llu: %s is not found.", w->id, tok);
1476                                                 }
1477                                                 else {
1478                                                         code = 200;
1479                                                         debug_flags |= D_RRD_STATS;
1480                                                         st->debug = !st->debug;
1481                                                         buffer_sprintf(w->response.data, "Chart %s has now debug %s.\r\n", tok, st->debug?"enabled":"disabled");
1482                                                         debug(D_WEB_CLIENT_ACCESS, "%llu: debug for %s is %s.", w->id, tok, st->debug?"enabled":"disabled");
1483                                                 }
1484                                         }
1485                                         else {
1486                                                 code = 500;
1487                                                 buffer_flush(w->response.data);
1488                                                 buffer_strcat(w->response.data, "debug which chart?\r\n");
1489                                         }
1490                                 }
1491                                 else if(strcmp(tok, "mirror") == 0) {
1492                                         code = 200;
1493
1494                                         debug(D_WEB_CLIENT_ACCESS, "%llu: Mirroring...", w->id);
1495
1496                                         // replace the zero bytes with spaces
1497                                         buffer_char_replace(w->response.data, '\0', ' ');
1498
1499                                         // just leave the buffer as is
1500                                         // it will be copied back to the client
1501                                 }
1502 #endif  /* NETDATA_INTERNAL_CHECKS */
1503                                 else {
1504                                         char filename[FILENAME_MAX+1];
1505                                         url = filename;
1506                                         strncpyz(filename, w->last_url, FILENAME_MAX);
1507                                         tok = mystrsep(&url, "?");
1508                                         buffer_flush(w->response.data);
1509                                         code = mysendfile(w, (tok && *tok)?tok:"/");
1510                                 }
1511                         }
1512                         else {
1513                                 char filename[FILENAME_MAX+1];
1514                                 url = filename;
1515                                 strncpyz(filename, w->last_url, FILENAME_MAX);
1516                                 tok = mystrsep(&url, "?");
1517                                 buffer_flush(w->response.data);
1518                                 code = mysendfile(w, (tok && *tok)?tok:"/");
1519                         }
1520                 }
1521         }
1522
1523         gettimeofday(&w->tv_ready, NULL);
1524         w->response.data->date = time(NULL);
1525         w->response.sent = 0;
1526         w->response.code = code;
1527
1528         // prepare the HTTP response header
1529         debug(D_WEB_CLIENT, "%llu: Generating HTTP header with response %d.", w->id, code);
1530
1531         char *content_type_string;
1532         switch(w->response.data->contenttype) {
1533                 case CT_TEXT_HTML:
1534                         content_type_string = "text/html; charset=utf-8";
1535                         break;
1536
1537                 case CT_APPLICATION_XML:
1538                         content_type_string = "application/xml; charset=utf-8";
1539                         break;
1540
1541                 case CT_APPLICATION_JSON:
1542                         content_type_string = "application/json; charset=utf-8";
1543                         break;
1544
1545                 case CT_APPLICATION_X_JAVASCRIPT:
1546                         content_type_string = "application/x-javascript; charset=utf-8";
1547                         break;
1548
1549                 case CT_TEXT_CSS:
1550                         content_type_string = "text/css; charset=utf-8";
1551                         break;
1552
1553                 case CT_TEXT_XML:
1554                         content_type_string = "text/xml; charset=utf-8";
1555                         break;
1556
1557                 case CT_TEXT_XSL:
1558                         content_type_string = "text/xsl; charset=utf-8";
1559                         break;
1560
1561                 case CT_APPLICATION_OCTET_STREAM:
1562                         content_type_string = "application/octet-stream";
1563                         break;
1564
1565                 case CT_IMAGE_SVG_XML:
1566                         content_type_string = "image/svg+xml";
1567                         break;
1568
1569                 case CT_APPLICATION_X_FONT_TRUETYPE:
1570                         content_type_string = "application/x-font-truetype";
1571                         break;
1572
1573                 case CT_APPLICATION_X_FONT_OPENTYPE:
1574                         content_type_string = "application/x-font-opentype";
1575                         break;
1576
1577                 case CT_APPLICATION_FONT_WOFF:
1578                         content_type_string = "application/font-woff";
1579                         break;
1580
1581                 case CT_APPLICATION_FONT_WOFF2:
1582                         content_type_string = "application/font-woff2";
1583                         break;
1584
1585                 case CT_APPLICATION_VND_MS_FONTOBJ:
1586                         content_type_string = "application/vnd.ms-fontobject";
1587                         break;
1588
1589                 case CT_IMAGE_PNG:
1590                         content_type_string = "image/png";
1591                         break;
1592
1593                 case CT_IMAGE_JPG:
1594                         content_type_string = "image/jpeg";
1595                         break;
1596
1597                 case CT_IMAGE_GIF:
1598                         content_type_string = "image/gif";
1599                         break;
1600
1601                 case CT_IMAGE_XICON:
1602                         content_type_string = "image/x-icon";
1603                         break;
1604
1605                 case CT_IMAGE_BMP:
1606                         content_type_string = "image/bmp";
1607                         break;
1608
1609                 case CT_IMAGE_ICNS:
1610                         content_type_string = "image/icns";
1611                         break;
1612
1613                 default:
1614                 case CT_TEXT_PLAIN:
1615                         content_type_string = "text/plain; charset=utf-8";
1616                         break;
1617         }
1618
1619         char *code_msg;
1620         switch(code) {
1621                 case 200:
1622                         code_msg = "OK";
1623                         break;
1624
1625                 case 307:
1626                         code_msg = "Temporary Redirect";
1627                         break;
1628
1629                 case 400:
1630                         code_msg = "Bad Request";
1631                         break;
1632
1633                 case 403:
1634                         code_msg = "Forbidden";
1635                         break;
1636
1637                 case 404:
1638                         code_msg = "Not Found";
1639                         break;
1640
1641                 case 412:
1642                         code_msg = "Preconditions Failed";
1643                         break;
1644
1645                 default:
1646                         code_msg = "Internal Server Error";
1647                         break;
1648         }
1649
1650         char date[100];
1651         struct tm tmbuf, *tm = gmtime_r(&w->response.data->date, &tmbuf);
1652         strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %Z", tm);
1653
1654         buffer_sprintf(w->response.header_output,
1655                 "HTTP/1.1 %d %s\r\n"
1656                 "Connection: %s\r\n"
1657                 "Server: NetData Embedded HTTP Server\r\n"
1658                 "Access-Control-Allow-Origin: %s\r\n"
1659                 "Access-Control-Allow-Credentials: true\r\n"
1660                 "Content-Type: %s\r\n"
1661                 "Date: %s\r\n"
1662                 , code, code_msg
1663                 , w->keepalive?"keep-alive":"close"
1664                 , w->origin
1665                 , content_type_string
1666                 , date
1667                 );
1668
1669         if(w->cookie1[0]) {
1670                 buffer_sprintf(w->response.header_output,
1671                    "Set-Cookie: %s\r\n",
1672                    w->cookie1);
1673         }
1674
1675         if(w->cookie2[0]) {
1676                 buffer_sprintf(w->response.header_output,
1677                    "Set-Cookie: %s\r\n",
1678                    w->cookie2);
1679         }
1680
1681         if(w->mode == WEB_CLIENT_MODE_OPTIONS) {
1682                 buffer_strcat(w->response.header_output,
1683                         "Access-Control-Allow-Methods: GET, OPTIONS\r\n"
1684                         "Access-Control-Allow-Headers: accept, x-requested-with, origin, content-type, cookie\r\n"
1685                         "Access-Control-Max-Age: 1209600\r\n" // 86400 * 14
1686                         );
1687         }
1688
1689         if(buffer_strlen(w->response.header))
1690                 buffer_strcat(w->response.header_output, buffer_tostring(w->response.header));
1691
1692         if(w->mode == WEB_CLIENT_MODE_NORMAL && (w->response.data->options & WB_CONTENT_NO_CACHEABLE)) {
1693                 buffer_sprintf(w->response.header_output,
1694                         "Expires: %s\r\n"
1695                         "Cache-Control: no-cache\r\n"
1696                         , date);
1697         }
1698         else if(w->mode != WEB_CLIENT_MODE_OPTIONS) {
1699                 char edate[100];
1700                 time_t et = w->response.data->date + (86400 * 14);
1701                 struct tm etmbuf, *etm = gmtime_r(&et, &etmbuf);
1702                 strftime(edate, sizeof(edate), "%a, %d %b %Y %H:%M:%S %Z", etm);
1703
1704                 buffer_sprintf(w->response.header_output,
1705                         "Expires: %s\r\n"
1706                         "Cache-Control: public\r\n"
1707                         , edate);
1708         }
1709
1710         // if we know the content length, put it
1711         if(!w->response.zoutput && (w->response.data->len || w->response.rlen))
1712                 buffer_sprintf(w->response.header_output,
1713                         "Content-Length: %ld\r\n"
1714                         , w->response.data->len? w->response.data->len: w->response.rlen
1715                         );
1716         else if(!w->response.zoutput)
1717                 w->keepalive = 0;       // content-length is required for keep-alive
1718
1719         if(w->response.zoutput) {
1720                 buffer_strcat(w->response.header_output,
1721                         "Content-Encoding: gzip\r\n"
1722                         "Transfer-Encoding: chunked\r\n"
1723                         );
1724         }
1725
1726         buffer_strcat(w->response.header_output, "\r\n");
1727
1728         // disable TCP_NODELAY, to buffer the header
1729         int flag = 0;
1730         if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0)
1731                 error("%llu: failed to disable TCP_NODELAY on socket.", w->id);
1732
1733         // sent the HTTP header
1734         debug(D_WEB_DATA, "%llu: Sending response HTTP header of size %d: '%s'"
1735                         , w->id
1736                         , buffer_strlen(w->response.header_output)
1737                         , buffer_tostring(w->response.header_output)
1738                         );
1739
1740         bytes = send(w->ofd, buffer_tostring(w->response.header_output), buffer_strlen(w->response.header_output), 0);
1741         if(bytes != (ssize_t) buffer_strlen(w->response.header_output))
1742                 error("%llu: HTTP Header failed to be sent (I sent %d bytes but the system sent %d bytes)."
1743                                 , w->id
1744                                 , buffer_strlen(w->response.header_output)
1745                                 , bytes);
1746         else 
1747                 w->stats_sent_bytes += bytes;
1748
1749         // enable TCP_NODELAY, to send all data immediately at the next send()
1750         flag = 1;
1751         if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0) error("%llu: failed to enable TCP_NODELAY on socket.", w->id);
1752
1753         // enable sending immediately if we have data
1754         if(w->response.data->len) w->wait_send = 1;
1755         else w->wait_send = 0;
1756
1757         // pretty logging
1758         switch(w->mode) {
1759                 case WEB_CLIENT_MODE_OPTIONS:
1760                         debug(D_WEB_CLIENT, "%llu: Done preparing the OPTIONS response. Sending data (%d bytes) to client.", w->id, w->response.data->len);
1761                         break;
1762
1763                 case WEB_CLIENT_MODE_NORMAL:
1764                         debug(D_WEB_CLIENT, "%llu: Done preparing the response. Sending data (%d bytes) to client.", w->id, w->response.data->len);
1765                         break;
1766
1767                 case WEB_CLIENT_MODE_FILECOPY:
1768                         if(w->response.rlen) {
1769                                 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending data file of %d bytes to client.", w->id, w->response.rlen);
1770                                 w->wait_receive = 1;
1771
1772                                 /*
1773                                 // utilize the kernel sendfile() for copying the file to the socket.
1774                                 // this block of code can be commented, without anything missing.
1775                                 // when it is commented, the program will copy the data using async I/O.
1776                                 {
1777                                         long len = sendfile(w->ofd, w->ifd, NULL, w->response.data->rbytes);
1778                                         if(len != w->response.data->rbytes) error("%llu: sendfile() should copy %ld bytes, but copied %ld. Falling back to manual copy.", w->id, w->response.data->rbytes, len);
1779                                         else web_client_reset(w);
1780                                 }
1781                                 */
1782                         }
1783                         else
1784                                 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending an unknown amount of bytes to client.", w->id);
1785                         break;
1786
1787                 default:
1788                         fatal("%llu: Unknown client mode %d.", w->id, w->mode);
1789                         break;
1790         }
1791 }
1792
1793 long web_client_send_chunk_header(struct web_client *w, long len)
1794 {
1795         debug(D_DEFLATE, "%llu: OPEN CHUNK of %d bytes (hex: %x).", w->id, len, len);
1796         char buf[1024];
1797         sprintf(buf, "%lX\r\n", len);
1798         ssize_t bytes = send(w->ofd, buf, strlen(buf), MSG_DONTWAIT);
1799
1800         if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk header %d bytes.", w->id, bytes);
1801         else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk header to the client.", w->id);
1802         else debug(D_DEFLATE, "%llu: Failed to send chunk header to client.", w->id);
1803
1804         return bytes;
1805 }
1806
1807 long web_client_send_chunk_close(struct web_client *w)
1808 {
1809         //debug(D_DEFLATE, "%llu: CLOSE CHUNK.", w->id);
1810
1811         ssize_t bytes = send(w->ofd, "\r\n", 2, MSG_DONTWAIT);
1812
1813         if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
1814         else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
1815         else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client.", w->id);
1816
1817         return bytes;
1818 }
1819
1820 long web_client_send_chunk_finalize(struct web_client *w)
1821 {
1822         //debug(D_DEFLATE, "%llu: FINALIZE CHUNK.", w->id);
1823
1824         ssize_t bytes = send(w->ofd, "\r\n0\r\n\r\n", 7, MSG_DONTWAIT);
1825
1826         if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
1827         else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
1828         else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client.", w->id);
1829
1830         return bytes;
1831 }
1832
1833 #ifdef NETDATA_WITH_ZLIB
1834 long web_client_send_deflate(struct web_client *w)
1835 {
1836         long len = 0, t = 0;
1837
1838         // when using compression,
1839         // w->response.sent is the amount of bytes passed through compression
1840
1841         debug(D_DEFLATE, "%llu: web_client_send_deflate(): w->response.data->len = %d, w->response.sent = %d, w->response.zhave = %d, w->response.zsent = %d, w->response.zstream.avail_in = %d, w->response.zstream.avail_out = %d, w->response.zstream.total_in = %d, w->response.zstream.total_out = %d.", w->id, w->response.data->len, w->response.sent, w->response.zhave, w->response.zsent, w->response.zstream.avail_in, w->response.zstream.avail_out, w->response.zstream.total_in, w->response.zstream.total_out);
1842
1843         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) {
1844                 // there is nothing to send
1845
1846                 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1847
1848                 // finalize the chunk
1849                 if(w->response.sent != 0)
1850                         t += web_client_send_chunk_finalize(w);
1851
1852                 // there can be two cases for this
1853                 // A. we have done everything
1854                 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
1855
1856                 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->response.rlen && w->response.rlen > w->response.data->len) {
1857                         // we have to wait, more data will come
1858                         debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1859                         w->wait_send = 0;
1860                         return(0);
1861                 }
1862
1863                 if(w->keepalive == 0) {
1864                         debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->response.sent);
1865                         errno = 0;
1866                         return(-1);
1867                 }
1868
1869                 // reset the client
1870                 web_client_reset(w);
1871                 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1872                 return(0);
1873         }
1874
1875         if(w->response.zhave == w->response.zsent) {
1876                 // compress more input data
1877
1878                 // close the previous open chunk
1879                 if(w->response.sent != 0) t += web_client_send_chunk_close(w);
1880
1881                 debug(D_DEFLATE, "%llu: Compressing %d new bytes starting from %d (and %d left behind).", w->id, (w->response.data->len - w->response.sent), w->response.sent, w->response.zstream.avail_in);
1882
1883                 // give the compressor all the data not passed through the compressor yet
1884                 if(w->response.data->len > w->response.sent) {
1885 #ifdef NETDATA_INTERNAL_CHECKS
1886                         if((long)w->response.sent - (long)w->response.zstream.avail_in < 0)
1887                                 error("internal error: avail_in is corrupted.");
1888 #endif
1889                         w->response.zstream.next_in = (Bytef *)&w->response.data->buffer[w->response.sent - w->response.zstream.avail_in];
1890                         w->response.zstream.avail_in += (uInt) (w->response.data->len - w->response.sent);
1891                 }
1892
1893                 // reset the compressor output buffer
1894                 w->response.zstream.next_out = w->response.zbuffer;
1895                 w->response.zstream.avail_out = ZLIB_CHUNK;
1896
1897                 // ask for FINISH if we have all the input
1898                 int flush = Z_SYNC_FLUSH;
1899                 if(w->mode == WEB_CLIENT_MODE_NORMAL
1900                         || (w->mode == WEB_CLIENT_MODE_FILECOPY && !w->wait_receive && w->response.data->len == w->response.rlen)) {
1901                         flush = Z_FINISH;
1902                         debug(D_DEFLATE, "%llu: Requesting Z_FINISH, if possible.", w->id);
1903                 }
1904                 else {
1905                         debug(D_DEFLATE, "%llu: Requesting Z_SYNC_FLUSH.", w->id);
1906                 }
1907
1908                 // compress
1909                 if(deflate(&w->response.zstream, flush) == Z_STREAM_ERROR) {
1910                         error("%llu: Compression failed. Closing down client.", w->id);
1911                         web_client_reset(w);
1912                         return(-1);
1913                 }
1914
1915                 w->response.zhave = ZLIB_CHUNK - w->response.zstream.avail_out;
1916                 w->response.zsent = 0;
1917
1918                 // keep track of the bytes passed through the compressor
1919                 w->response.sent = w->response.data->len;
1920
1921                 debug(D_DEFLATE, "%llu: Compression produced %d bytes.", w->id, w->response.zhave);
1922
1923                 // open a new chunk
1924                 t += web_client_send_chunk_header(w, w->response.zhave);
1925         }
1926         
1927         debug(D_WEB_CLIENT, "%llu: Sending %d bytes of data (+%d of chunk header).", w->id, w->response.zhave - w->response.zsent, t);
1928
1929         len = send(w->ofd, &w->response.zbuffer[w->response.zsent], (size_t) (w->response.zhave - w->response.zsent), MSG_DONTWAIT);
1930         if(len > 0) {
1931                 w->response.zsent += len;
1932                 if(t > 0) len += t;
1933                 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, len);
1934         }
1935         else if(len == 0) debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client (zhave = %ld, zsent = %ld, need to send = %ld).", w->id, w->response.zhave, w->response.zsent, w->response.zhave - w->response.zsent);
1936         else debug(D_WEB_CLIENT, "%llu: Failed to send data to client. Reason: %s", w->id, strerror(errno));
1937
1938         return(len);
1939 }
1940 #endif // NETDATA_WITH_ZLIB
1941
1942 long web_client_send(struct web_client *w)
1943 {
1944 #ifdef NETDATA_WITH_ZLIB
1945         if(likely(w->response.zoutput)) return web_client_send_deflate(w);
1946 #endif // NETDATA_WITH_ZLIB
1947
1948         long bytes;
1949
1950         if(unlikely(w->response.data->len - w->response.sent == 0)) {
1951                 // there is nothing to send
1952
1953                 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1954
1955                 // there can be two cases for this
1956                 // A. we have done everything
1957                 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
1958
1959                 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->response.rlen && w->response.rlen > w->response.data->len) {
1960                         // we have to wait, more data will come
1961                         debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1962                         w->wait_send = 0;
1963                         return(0);
1964                 }
1965
1966                 if(unlikely(w->keepalive == 0)) {
1967                         debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->response.sent);
1968                         errno = 0;
1969                         return(-1);
1970                 }
1971
1972                 web_client_reset(w);
1973                 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1974                 return(0);
1975         }
1976
1977         bytes = send(w->ofd, &w->response.data->buffer[w->response.sent], w->response.data->len - w->response.sent, MSG_DONTWAIT);
1978         if(likely(bytes > 0)) {
1979                 w->response.sent += bytes;
1980                 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, bytes);
1981         }
1982         else if(likely(bytes == 0)) debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client.", w->id);
1983         else debug(D_WEB_CLIENT, "%llu: Failed to send data to client.", w->id);
1984
1985         return(bytes);
1986 }
1987
1988 long web_client_receive(struct web_client *w)
1989 {
1990         // do we have any space for more data?
1991         buffer_need_bytes(w->response.data, WEB_REQUEST_LENGTH);
1992
1993         long left = w->response.data->size - w->response.data->len;
1994         long bytes;
1995
1996         if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY))
1997                 bytes = read(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1));
1998         else
1999                 bytes = recv(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1), MSG_DONTWAIT);
2000
2001         if(likely(bytes > 0)) {
2002                 size_t old = w->response.data->len;
2003                 w->response.data->len += bytes;
2004                 w->response.data->buffer[w->response.data->len] = '\0';
2005
2006                 debug(D_WEB_CLIENT, "%llu: Received %d bytes.", w->id, bytes);
2007                 debug(D_WEB_DATA, "%llu: Received data: '%s'.", w->id, &w->response.data->buffer[old]);
2008
2009                 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
2010                         w->wait_send = 1;
2011                         if(w->response.rlen && w->response.data->len >= w->response.rlen) w->wait_receive = 0;
2012                 }
2013         }
2014         else if(likely(bytes == 0)) {
2015                 debug(D_WEB_CLIENT, "%llu: Out of input data.", w->id);
2016
2017                 // if we cannot read, it means we have an error on input.
2018                 // if however, we are copying a file from ifd to ofd, we should not return an error.
2019                 // in this case, the error should be generated when the file has been sent to the client.
2020
2021                 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
2022                         // we are copying data from ifd to ofd
2023                         // let it finish copying...
2024                         w->wait_receive = 0;
2025                         debug(D_WEB_CLIENT, "%llu: Disabling input.", w->id);
2026                 }
2027                 else {
2028                         bytes = -1;
2029                         errno = 0;
2030                 }
2031         }
2032
2033         return(bytes);
2034 }
2035
2036
2037 // --------------------------------------------------------------------------------------
2038 // the thread of a single client
2039
2040 // 1. waits for input and output, using async I/O
2041 // 2. it processes HTTP requests
2042 // 3. it generates HTTP responses
2043 // 4. it copies data from input to output if mode is FILECOPY
2044
2045 void *web_client_main(void *ptr)
2046 {
2047         if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
2048                 error("Cannot set pthread cancel type to DEFERRED.");
2049
2050         if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
2051                 error("Cannot set pthread cancel state to ENABLE.");
2052
2053         struct timeval tv;
2054         struct web_client *w = ptr;
2055         int retval;
2056         fd_set ifds, ofds, efds;
2057         int fdmax = 0;
2058
2059         log_access("%llu: %s port %s connected on thread task id %d", w->id, w->client_ip, w->client_port, gettid());
2060
2061         for(;;) {
2062                 FD_ZERO (&ifds);
2063                 FD_ZERO (&ofds);
2064                 FD_ZERO (&efds);
2065
2066                 FD_SET(w->ifd, &efds);
2067
2068                 if(w->ifd != w->ofd)
2069                         FD_SET(w->ofd, &efds);
2070
2071                 if (w->wait_receive) {
2072                         FD_SET(w->ifd, &ifds);
2073                         if(w->ifd > fdmax) fdmax = w->ifd;
2074                 }
2075
2076                 if (w->wait_send) {
2077                         FD_SET(w->ofd, &ofds);
2078                         if(w->ofd > fdmax) fdmax = w->ofd;
2079                 }
2080
2081                 tv.tv_sec = web_client_timeout;
2082                 tv.tv_usec = 0;
2083
2084                 debug(D_WEB_CLIENT, "%llu: Waiting socket async I/O for %s %s", w->id, w->wait_receive?"INPUT":"", w->wait_send?"OUTPUT":"");
2085                 retval = select(fdmax+1, &ifds, &ofds, &efds, &tv);
2086
2087                 if(retval == -1) {
2088                         debug(D_WEB_CLIENT_ACCESS, "%llu: LISTENER: select() failed.", w->id);
2089                         continue;
2090                 }
2091                 else if(!retval) {
2092                         // timeout
2093                         debug(D_WEB_CLIENT_ACCESS, "%llu: LISTENER: timeout.", w->id);
2094                         break;
2095                 }
2096
2097                 if(FD_ISSET(w->ifd, &efds)) {
2098                         debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on input socket.", w->id);
2099                         break;
2100                 }
2101
2102                 if(FD_ISSET(w->ofd, &efds)) {
2103                         debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on output socket.", w->id);
2104                         break;
2105                 }
2106
2107                 if(w->wait_send && FD_ISSET(w->ofd, &ofds)) {
2108                         long bytes;
2109                         if((bytes = web_client_send(w)) < 0) {
2110                                 debug(D_WEB_CLIENT, "%llu: Cannot send data to client. Closing client.", w->id);
2111                                 errno = 0;
2112                                 break;
2113                         }
2114                         else
2115                                 w->stats_sent_bytes += bytes;
2116                 }
2117
2118                 if(w->wait_receive && FD_ISSET(w->ifd, &ifds)) {
2119                         long bytes;
2120                         if((bytes = web_client_receive(w)) < 0) {
2121                                 debug(D_WEB_CLIENT, "%llu: Cannot receive data from client. Closing client.", w->id);
2122                                 errno = 0;
2123                                 break;
2124                         }
2125                         else
2126                                 w->stats_received_bytes += bytes;
2127
2128                         if(w->mode == WEB_CLIENT_MODE_NORMAL) {
2129                                 debug(D_WEB_CLIENT, "%llu: Attempting to process received data (%ld bytes).", w->id, bytes);
2130                                 // info("%llu: Attempting to process received data (%ld bytes).", w->id, bytes);
2131                                 web_client_process(w);
2132                         }
2133
2134                 }
2135         }
2136
2137         log_access("%llu: %s port %s disconnected from thread task id %d", w->id, w->client_ip, w->client_port, gettid());
2138         debug(D_WEB_CLIENT, "%llu: done...", w->id);
2139
2140         web_client_reset(w);
2141         w->obsolete = 1;
2142
2143         return NULL;
2144 }