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