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