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