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