]> arthur.barton.de Git - netdata.git/blob - src/web_client.c
first complete API implementation - it now supports multiple different visualizations
[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 <ctype.h>
18
19 #include "common.h"
20 #include "log.h"
21 #include "appconfig.h"
22 #include "url.h"
23 #include "web_buffer.h"
24 #include "web_server.h"
25 #include "global_statistics.h"
26 #include "rrd.h"
27 #include "rrd2json.h"
28
29 #include "web_client.h"
30
31 #define INITIAL_WEB_DATA_LENGTH 16384
32 #define WEB_REQUEST_LENGTH 16384
33
34 int web_client_timeout = DEFAULT_DISCONNECT_IDLE_WEB_CLIENTS_AFTER_SECONDS;
35 int web_enable_gzip = 1;
36
37 struct web_client *web_clients = NULL;
38 unsigned long long web_clients_count = 0;
39
40 struct web_client *web_client_create(int listener)
41 {
42         struct web_client *w;
43         
44         w = calloc(1, sizeof(struct web_client));
45         if(!w) {
46                 error("Cannot allocate new web_client memory.");
47                 return NULL;
48         }
49
50         w->id = ++web_clients_count;
51         w->mode = WEB_CLIENT_MODE_NORMAL;
52
53         {
54                 struct sockaddr *sadr;
55                 socklen_t addrlen;
56
57                 sadr = (struct sockaddr*) &w->clientaddr;
58                 addrlen = sizeof(w->clientaddr);
59
60                 w->ifd = accept(listener, sadr, &addrlen);
61                 if (w->ifd == -1) {
62                         error("%llu: Cannot accept new incoming connection.", w->id);
63                         free(w);
64                         return NULL;
65                 }
66                 w->ofd = w->ifd;
67
68                 if(getnameinfo(sadr, addrlen, w->client_ip, NI_MAXHOST, w->client_port, NI_MAXSERV, NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
69                         error("Cannot getnameinfo() on received client connection.");
70                         strncpy(w->client_ip,   "UNKNOWN", NI_MAXHOST);
71                         strncpy(w->client_port, "UNKNOWN", NI_MAXSERV);
72                 }
73                 w->client_ip[NI_MAXHOST]   = '\0';
74                 w->client_port[NI_MAXSERV] = '\0';
75
76                 switch(sadr->sa_family) {
77
78                 case AF_INET:
79                         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);
80                         break;
81
82                 case AF_INET6:
83                         if(strncmp(w->client_ip, "::ffff:", 7) == 0) {
84                                 strcpy(w->client_ip, &w->client_ip[7]);
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                         }
87                         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);
88                         break;
89
90                 default:
91                         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);
92                         break;
93                 }
94
95                 int flag = 1;
96                 if(setsockopt(w->ifd, SOL_SOCKET, SO_KEEPALIVE, (char *) &flag, sizeof(int)) != 0) error("%llu: Cannot set SO_KEEPALIVE on socket.", w->id);
97         }
98
99         w->response.data = buffer_create(INITIAL_WEB_DATA_LENGTH);
100         if(unlikely(!w->response.data)) {
101                 // no need for error log - web_buffer_create already logged the error
102                 close(w->ifd);
103                 free(w);
104                 return NULL;
105         }
106
107         w->response.header = buffer_create(HTTP_RESPONSE_HEADER_SIZE);
108         if(unlikely(!w->response.header)) {
109                 // no need for error log - web_buffer_create already logged the error
110                 buffer_free(w->response.data);
111                 close(w->ifd);
112                 free(w);
113                 return NULL;
114         }
115
116         w->response.header_output = buffer_create(HTTP_RESPONSE_HEADER_SIZE);
117         if(unlikely(!w->response.header_output)) {
118                 // no need for error log - web_buffer_create already logged the error
119                 buffer_free(w->response.header);
120                 buffer_free(w->response.data);
121                 close(w->ifd);
122                 free(w);
123                 return NULL;
124         }
125
126         w->wait_receive = 1;
127
128         if(web_clients) web_clients->prev = w;
129         w->next = web_clients;
130         web_clients = w;
131
132         global_statistics.connected_clients++;
133
134         return(w);
135 }
136
137 void web_client_reset(struct web_client *w)
138 {
139         struct timeval tv;
140         gettimeofday(&tv, NULL);
141
142         long sent = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->response.rlen:w->response.data->len;
143
144 #ifdef NETDATA_WITH_ZLIB
145         if(likely(w->response.zoutput)) sent = (long)w->response.zstream.total_out;
146 #endif
147
148         long size = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->response.rlen:w->response.data->len;
149
150         if(likely(w->last_url[0]))
151                 log_access("%llu: (sent/all = %ld/%ld bytes %0.0f%%, prep/sent/total = %0.2f/%0.2f/%0.2f ms) %s: %d '%s'",
152                         w->id,
153                         sent, size, -((size>0)?((float)(size-sent)/(float)size * 100.0):0.0),
154                         (float)usecdiff(&w->tv_ready, &w->tv_in) / 1000.0,
155                         (float)usecdiff(&tv, &w->tv_ready) / 1000.0,
156                         (float)usecdiff(&tv, &w->tv_in) / 1000.0,
157                         (w->mode == WEB_CLIENT_MODE_FILECOPY)?"filecopy":"data",
158                         w->response.code,
159                         w->last_url
160                 );
161
162         debug(D_WEB_CLIENT, "%llu: Reseting client.", w->id);
163
164         if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY)) {
165                 debug(D_WEB_CLIENT, "%llu: Closing filecopy input file.", w->id);
166                 close(w->ifd);
167                 w->ifd = w->ofd;
168         }
169
170         w->last_url[0] = '\0';
171
172         w->mode = WEB_CLIENT_MODE_NORMAL;
173
174         buffer_reset(w->response.header_output);
175         buffer_reset(w->response.header);
176         buffer_reset(w->response.data);
177         w->response.rlen = 0;
178         w->response.sent = 0;
179         w->response.code = 0;
180
181         w->wait_receive = 1;
182         w->wait_send = 0;
183
184         w->response.zoutput = 0;
185
186         // if we had enabled compression, release it
187 #ifdef NETDATA_WITH_ZLIB
188         if(w->response.zinitialized) {
189                 debug(D_DEFLATE, "%llu: Reseting compression.", w->id);
190                 deflateEnd(&w->response.zstream);
191                 w->response.zsent = 0;
192                 w->response.zhave = 0;
193                 w->response.zstream.avail_in = 0;
194                 w->response.zstream.avail_out = 0;
195                 w->response.zstream.total_in = 0;
196                 w->response.zstream.total_out = 0;
197                 w->response.zinitialized = 0;
198         }
199 #endif // NETDATA_WITH_ZLIB
200 }
201
202 struct web_client *web_client_free(struct web_client *w)
203 {
204         struct web_client *n = w->next;
205
206         debug(D_WEB_CLIENT_ACCESS, "%llu: Closing web client from %s port %s.", w->id, w->client_ip, w->client_port);
207
208         if(w->prev)     w->prev->next = w->next;
209         if(w->next) w->next->prev = w->prev;
210
211         if(w == web_clients) web_clients = w->next;
212
213         if(w->response.header) buffer_free(w->response.header);
214         if(w->response.data) buffer_free(w->response.data);
215         close(w->ifd);
216         if(w->ofd != w->ifd) close(w->ofd);
217         free(w);
218
219         global_statistics.connected_clients--;
220
221         return(n);
222 }
223
224 uid_t web_files_uid(void)
225 {
226         static char *web_owner = NULL;
227         static uid_t owner_uid = 0;
228
229         if(unlikely(!web_owner)) {
230                 web_owner = config_get("global", "web files owner", NETDATA_USER);
231                 if(!web_owner || !*web_owner)
232                         owner_uid = geteuid();
233                 else {
234                         struct passwd *pw = getpwnam(web_owner);
235                         if(!pw) {
236                                 error("User %s is not present. Ignoring option. Error: %s\n", web_owner, strerror(errno));
237                                 owner_uid = geteuid();
238                         }
239                         else {
240                                 debug(D_WEB_CLIENT, "Web files owner set to %s.\n", web_owner);
241                                 owner_uid = pw->pw_uid;
242                         }
243                 }
244         }
245
246         return(owner_uid);
247 }
248
249 int mysendfile(struct web_client *w, char *filename)
250 {
251         static char *web_dir = NULL;
252
253         // initialize our static data
254         if(unlikely(!web_dir)) web_dir = config_get("global", "web files directory", WEB_DIR);
255
256         debug(D_WEB_CLIENT, "%llu: Looking for file '%s/%s'", w->id, web_dir, filename);
257
258         // skip leading slashes
259         while (*filename == '/') filename++;
260
261         // if the filename contain known paths, skip them
262         if(strncmp(filename, WEB_PATH_FILE "/", strlen(WEB_PATH_FILE) + 1) == 0) filename = &filename[strlen(WEB_PATH_FILE) + 1];
263
264         char *s;
265         for(s = filename; *s ;s++) {
266                 if( !isalnum(*s) && *s != '/' && *s != '.' && *s != '-' && *s != '_') {
267                         debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
268                         buffer_sprintf(w->response.data, "File '%s' cannot be served. Filename contains invalid character '%c'", *s);
269                         return 400;
270                 }
271         }
272
273         // if the filename contains a .. refuse to serve it
274         if(strstr(filename, "..") != 0) {
275                 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
276                 buffer_sprintf(w->response.data, "File '%s' cannot be served. Relative filenames with '..' in them are not supported.", filename);
277                 return 400;
278         }
279
280         // access the file
281         char webfilename[FILENAME_MAX + 1];
282         snprintf(webfilename, FILENAME_MAX, "%s/%s", web_dir, filename);
283
284         // check if the file exists
285         struct stat stat;
286         if(lstat(webfilename, &stat) != 0) {
287                 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not found.", w->id, webfilename);
288                 buffer_sprintf(w->response.data, "File '%s' does not exist, or is not accessible.", filename);
289                 return 404;
290         }
291
292         // check if the file is owned by us
293         if(stat.st_uid != web_files_uid()) {
294                 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is owned by user %d (I run as user %d). Access Denied.", w->id, webfilename, stat.st_uid, getuid());
295                 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", filename);
296                 return 403;
297         }
298
299         if((stat.st_mode & S_IFMT) == S_IFDIR) {
300                 snprintf(webfilename, FILENAME_MAX+1, "%s/index.html", filename);
301                 return mysendfile(w, webfilename);
302         }
303
304         if((stat.st_mode & S_IFMT) != S_IFREG) {
305                 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not a regular file. Access Denied.", w->id, webfilename);
306                 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", filename);
307                 return 403;
308         }
309
310         // open the file
311         w->ifd = open(webfilename, O_NONBLOCK, O_RDONLY);
312         if(w->ifd == -1) {
313                 w->ifd = w->ofd;
314
315                 if(errno == EBUSY || errno == EAGAIN) {
316                         error("%llu: File '%s' is busy, sending 307 Moved Temporarily to force retry.", w->id, webfilename);
317                         buffer_sprintf(w->response.header, "Location: /" WEB_PATH_FILE "/%s\r\n", filename);
318                         buffer_sprintf(w->response.data, "The file '%s' is currently busy. Please try again later.", filename);
319                         return 307;
320                 }
321                 else {
322                         error("%llu: Cannot open file '%s'.", w->id, webfilename);
323                         buffer_sprintf(w->response.data, "Cannot open file '%s'.", filename);
324                         return 404;
325                 }
326         }
327
328         // pick a Content-Type for the file
329                  if(strstr(filename, ".html") != NULL)  w->response.data->contenttype = CT_TEXT_HTML;
330         else if(strstr(filename, ".js")   != NULL)      w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
331         else if(strstr(filename, ".css")  != NULL)      w->response.data->contenttype = CT_TEXT_CSS;
332         else if(strstr(filename, ".xml")  != NULL)      w->response.data->contenttype = CT_TEXT_XML;
333         else if(strstr(filename, ".xsl")  != NULL)      w->response.data->contenttype = CT_TEXT_XSL;
334         else if(strstr(filename, ".txt")  != NULL)  w->response.data->contenttype = CT_TEXT_PLAIN;
335         else if(strstr(filename, ".svg")  != NULL)  w->response.data->contenttype = CT_IMAGE_SVG_XML;
336         else if(strstr(filename, ".ttf")  != NULL)  w->response.data->contenttype = CT_APPLICATION_X_FONT_TRUETYPE;
337         else if(strstr(filename, ".otf")  != NULL)  w->response.data->contenttype = CT_APPLICATION_X_FONT_OPENTYPE;
338         else if(strstr(filename, ".woff") != NULL)  w->response.data->contenttype = CT_APPLICATION_FONT_WOFF;
339         else if(strstr(filename, ".eot")  != NULL)  w->response.data->contenttype = CT_APPLICATION_VND_MS_FONTOBJ;
340         else w->response.data->contenttype = CT_APPLICATION_OCTET_STREAM;
341
342         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);
343
344         w->mode = WEB_CLIENT_MODE_FILECOPY;
345         w->wait_receive = 1;
346         w->wait_send = 0;
347         buffer_flush(w->response.data);
348         w->response.rlen = stat.st_size;
349         w->response.data->date = stat.st_mtim.tv_sec;
350
351         return 200;
352 }
353
354
355 #ifdef NETDATA_WITH_ZLIB
356 void web_client_enable_deflate(struct web_client *w) {
357         if(w->response.zinitialized == 1) {
358                 error("%llu: Compression has already be initialized for this client.", w->id);
359                 return;
360         }
361
362         if(w->response.sent) {
363                 error("%llu: Cannot enable compression in the middle of a conversation.", w->id);
364                 return;
365         }
366
367         w->response.zstream.zalloc = Z_NULL;
368         w->response.zstream.zfree = Z_NULL;
369         w->response.zstream.opaque = Z_NULL;
370
371         w->response.zstream.next_in = (Bytef *)w->response.data->buffer;
372         w->response.zstream.avail_in = 0;
373         w->response.zstream.total_in = 0;
374
375         w->response.zstream.next_out = w->response.zbuffer;
376         w->response.zstream.avail_out = 0;
377         w->response.zstream.total_out = 0;
378
379         w->response.zstream.zalloc = Z_NULL;
380         w->response.zstream.zfree = Z_NULL;
381         w->response.zstream.opaque = Z_NULL;
382
383 //      if(deflateInit(&w->response.zstream, Z_DEFAULT_COMPRESSION) != Z_OK) {
384 //              error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
385 //              return;
386 //      }
387
388         // Select GZIP compression: windowbits = 15 + 16 = 31
389         if(deflateInit2(&w->response.zstream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY) != Z_OK) {
390                 error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
391                 return;
392         }
393
394         w->response.zsent = 0;
395         w->response.zoutput = 1;
396         w->response.zinitialized = 1;
397
398         debug(D_DEFLATE, "%llu: Initialized compression.", w->id);
399 }
400 #endif // NETDATA_WITH_ZLIB
401
402 uint32_t web_client_api_request_v1_data_options(char *o)
403 {
404         uint32_t ret = 0x00000000;
405         char *tok;
406
407         while(o && *o && (tok = mystrsep(&o, ", |"))) {
408                 if(!*tok) continue;
409
410                 if(!strcmp(tok, "nonzero"))
411                         ret |= RRDR_OPTION_NONZERO;
412                 else if(!strcmp(tok, "flip") || !strcmp(tok, "reversed") || !strcmp(tok, "reverse"))
413                         ret |= RRDR_OPTION_REVERSED;
414                 else if(!strcmp(tok, "abs") || !strcmp(tok, "absolute") || !strcmp(tok, "absolute_sum") || !strcmp(tok, "absolute-sum"))
415                         ret |= RRDR_OPTION_ABSOLUTE;
416                 else if(!strcmp(tok, "min2max"))
417                         ret |= RRDR_OPTION_MIN2MAX;
418                 else if(!strcmp(tok, "seconds"))
419                         ret |= RRDR_OPTION_SECONDS;
420                 else if(!strcmp(tok, "ms") || !strcmp(tok, "milliseconds"))
421                         ret |= RRDR_OPTION_MILLISECONDS;
422                 else if(!strcmp(tok, "null2zero"))
423                         ret |= RRDR_OPTION_NULL2ZERO;
424         }
425
426         return ret;
427 }
428
429 int web_client_api_request_v1_data_format(char *name)
430 {
431         if(!strcmp(name, "datatable"))
432                 return DATASOURCE_GOOGLE_JSON;
433
434         else if(!strcmp(name, "datasource"))
435                 return DATASOURCE_GOOGLE_JSONP;
436
437         else if(!strcmp(name, "json"))
438                 return DATASOURCE_JSON;
439
440         else if(!strcmp(name, "jsonp"))
441                 return DATASOURCE_JSONP;
442
443         else if(!strcmp(name, "ssv"))
444                 return DATASOURCE_SSV;
445
446         else if(!strcmp(name, "csv"))
447                 return DATASOURCE_CSV;
448
449         else if(!strcmp(name, "tsv"))
450                 return DATASOURCE_TSV;
451
452         else if(!strcmp(name, "tsv-excel"))
453                 return DATASOURCE_TSV;
454
455         else if(!strcmp(name, "html"))
456                 return DATASOURCE_HTML;
457
458         else if(!strcmp(name, "array"))
459                 return DATASOURCE_JS_ARRAY;
460
461         else if(!strcmp(name, "ssvcomma"))
462                 return DATASOURCE_SSV_COMMA;
463
464         return DATASOURCE_JSON;
465 }
466
467 int web_client_api_request_v1_data_google_format(char *name)
468 {
469         if(!strcmp(name, "json"))
470                 return DATASOURCE_GOOGLE_JSONP;
471
472         else if(!strcmp(name, "html"))
473                 return DATASOURCE_HTML;
474
475         else if(!strcmp(name, "csv"))
476                 return DATASOURCE_CSV;
477
478         else if(!strcmp(name, "tsv-excel"))
479                 return DATASOURCE_TSV;
480
481         return DATASOURCE_JSON;
482 }
483
484 int web_client_api_request_v1_data_group(char *name)
485 {
486         if(!strcmp(name, "max"))
487                 return GROUP_MAX;
488
489         else if(!strcmp(name, "average"))
490                 return GROUP_AVERAGE;
491
492         return GROUP_MAX;
493 }
494
495 int web_client_api_request_v1_charts(struct web_client *w, char *url)
496 {
497         if(url) { ; }
498
499         buffer_flush(w->response.data);
500         rrd_stats_api_v1_charts(w->response.data);
501         return 200;
502 }
503
504 int web_client_api_request_v1_chart(struct web_client *w, char *url)
505 {
506         int ret = 400;
507         char *chart = NULL;
508
509         buffer_flush(w->response.data);
510
511         while(url) {
512                 char *value = mystrsep(&url, "?&[]");
513                 if(!value || !*value) continue;
514
515                 char *name = mystrsep(&value, "=");
516                 if(!name || !*name) continue;
517                 if(!value || !*value) continue;
518
519                 // name and value are now the parameters
520                 // they are not null and not empty
521
522                 if(!strcmp(name, "chart")) chart = value;
523                 else {
524                         buffer_sprintf(w->response.data, "Unknown parameter '%s' in request.", name);
525                         goto cleanup;
526                 }
527         }
528
529         if(!chart || !*chart) {
530                 buffer_sprintf(w->response.data, "No chart id is given at the request.");
531                 goto cleanup;
532         }
533
534         RRDSET *st = rrdset_find(chart);
535         if(!st) st = rrdset_find_byname(chart);
536         if(!st) {
537                 buffer_sprintf(w->response.data, "Chart '%s' is not found.", chart);
538                 ret = 404;
539                 goto cleanup;
540         }
541
542         w->response.data->contenttype = CT_APPLICATION_JSON;
543         rrd_stats_api_v1_chart(st, w->response.data);
544         return 200;
545
546 cleanup:
547         return ret;
548 }
549
550 // returns the HTTP code
551 int web_client_api_request_v1_data(struct web_client *w, char *url)
552 {
553         debug(D_WEB_CLIENT, "%llu: API v1 data with URL '%s'", w->id, url);
554
555         int ret = 400;
556         BUFFER *dimensions = NULL;
557
558         buffer_flush(w->response.data);
559
560         char    *google_version = "0.6",
561                         *google_reqId = "0",
562                         *google_sig = "0",
563                         *google_out = "json",
564                         *google_responseHandler = "google.visualization.Query.setResponse",
565                         *google_outFileName = NULL;
566
567         time_t last_timestamp_in_data = 0, google_timestamp = 0;
568
569         char *chart = NULL
570                         , *before_str = NULL
571                         , *after_str = NULL
572                         , *points_str = NULL;
573
574         int format = DATASOURCE_JSON, group = GROUP_MAX;
575         uint32_t options = 0x00000000;
576
577         while(url) {
578                 char *value = mystrsep(&url, "?&[]");
579                 if(!value || !*value) continue;
580
581                 char *name = mystrsep(&value, "=");
582                 if(!name || !*name) continue;
583                 if(!value || !*value) continue;
584
585                 debug(D_WEB_CLIENT, "%llu: API v1 query param '%s' with value '%s'", w->id, name, value);
586
587                 // name and value are now the parameters
588                 // they are not null and not empty
589
590                 if(!strcmp(name, "chart")) chart = value;
591                 else if(!strcmp(name, "dimension") || !strcmp(name, "dim") || !strcmp(name, "dimensions") || !strcmp(name, "dims")) {
592                         if(!dimensions) dimensions = buffer_create(strlen(value));
593                         if(dimensions) {
594                                 buffer_strcat(dimensions, "|");
595                                 buffer_strcat(dimensions, value);
596                         }
597                 }
598                 else if(!strcmp(name, "after")) after_str = value;
599                 else if(!strcmp(name, "before")) before_str = value;
600                 else if(!strcmp(name, "points")) points_str = value;
601                 else if(!strcmp(name, "group")) {
602                         group = web_client_api_request_v1_data_group(value);
603                 }
604                 else if(!strcmp(name, "format")) {
605                         format = web_client_api_request_v1_data_format(value);
606                 }
607                 else if(!strcmp(name, "options")) {
608                         options |= web_client_api_request_v1_data_options(value);
609                 }
610                 else if(!strcmp(name, "tqx")) {
611                         // parse Google Visualization API options
612                         // https://developers.google.com/chart/interactive/docs/dev/implementing_data_source
613                         char *tqx_name, *tqx_value;
614
615                         while(value) {
616                                 tqx_value = mystrsep(&value, ";");
617                                 if(!tqx_value || !*tqx_value) continue;
618
619                                 tqx_name = mystrsep(&tqx_value, ":");
620                                 if(!tqx_name || !*tqx_name) continue;
621                                 if(!tqx_value || !*tqx_value) continue;
622
623                                 if(!strcmp(tqx_name, "version"))
624                                         google_version = tqx_value;
625                                 else if(!strcmp(tqx_name, "reqId"))
626                                         google_reqId = tqx_value;
627                                 else if(!strcmp(tqx_name, "sig")) {
628                                         google_sig = tqx_value;
629                                         google_timestamp = strtoul(google_sig, NULL, 0);
630                                 }
631                                 else if(!strcmp(tqx_name, "out")) {
632                                         google_out = tqx_value;
633                                         format = web_client_api_request_v1_data_google_format(google_out);
634                                 }
635                                 else if(!strcmp(tqx_name, "responseHandler"))
636                                         google_responseHandler = tqx_value;
637                                 else if(!strcmp(tqx_name, "outFileName"))
638                                         google_outFileName = tqx_value;
639                         }
640                 }
641         }
642
643         if(!chart || !*chart) {
644                 buffer_sprintf(w->response.data, "No chart id is given at the request.");
645                 goto cleanup;
646         }
647
648         RRDSET *st = rrdset_find(chart);
649         if(!st) st = rrdset_find_byname(chart);
650         if(!st) {
651                 buffer_sprintf(w->response.data, "Chart '%s' is not found.", chart);
652                 ret = 404;
653                 goto cleanup;
654         }
655
656         long long before = (before_str && *before_str)?atol(before_str):0;
657         long long after  = (after_str  && *after_str) ?atol(after_str):0;
658         int       points = (points_str && *points_str)?atoi(points_str):0;
659
660         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'"
661                         , w->id
662                         , chart
663                         , (dimensions)?buffer_tostring(dimensions):""
664                         , after
665                         , before
666                         , points
667                         , group
668                         , format
669                         , options
670                         );
671
672         if(google_outFileName && *google_outFileName) {
673                 buffer_sprintf(w->response.header, "Content-Disposition: attachment; filename=\"%s\"\r\n", google_outFileName);
674                 error("generating outfilename header: '%s'", google_outFileName);
675         }
676
677         if(format == DATASOURCE_GOOGLE_JSONP) {
678                 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSON/JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
679                                 w->id, google_version, google_reqId, google_sig, google_out, google_responseHandler, google_outFileName
680                         );
681
682                 buffer_sprintf(w->response.data,
683                         "%s({version:'%s',reqId:'%s',status:'ok',sig:'%lu',table:",
684                         google_responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
685         }
686
687         ret = rrd2format(st, w->response.data, dimensions, format, points, after, before, group, options, &last_timestamp_in_data);
688
689         if(format == DATASOURCE_GOOGLE_JSONP) {
690                 if(google_timestamp < last_timestamp_in_data)
691                         buffer_strcat(w->response.data, "});");
692
693                 else {
694                         // the client already has the latest data
695                         buffer_flush(w->response.data);
696                         buffer_sprintf(w->response.data,
697                                 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
698                                 google_responseHandler, google_version, google_reqId);
699                 }
700         }
701
702 cleanup:
703         if(dimensions) buffer_free(dimensions);
704         return ret;
705 }
706
707 int web_client_api_request_v1(struct web_client *w, char *url)
708 {
709         // get the command
710         char *tok = mystrsep(&url, "/?&");
711         debug(D_WEB_CLIENT, "%llu: Searching for API v1 command '%s'.", w->id, tok);
712
713         if(strcmp(tok, "data") == 0)
714                 return web_client_api_request_v1_data(w, url);
715         else if(strcmp(tok, "chart") == 0)
716                 return web_client_api_request_v1_chart(w, url);
717         else if(strcmp(tok, "charts") == 0)
718                 return web_client_api_request_v1_charts(w, url);
719
720         buffer_flush(w->response.data);
721         buffer_sprintf(w->response.data, "Unsupported v1 API command: %s", tok);
722         return 404;
723 }
724
725 int web_client_api_request(struct web_client *w, char *url)
726 {
727         // get the api version
728         char *tok = mystrsep(&url, "/?&");
729         debug(D_WEB_CLIENT, "%llu: Searching for API version '%s'.", w->id, tok);
730
731         if(strcmp(tok, "v1") == 0)
732                 return web_client_api_request_v1(w, url);
733
734         buffer_flush(w->response.data);
735         buffer_sprintf(w->response.data, "Unsupported API version: %s", tok);
736         return 404;
737 }
738
739 int web_client_data_request(struct web_client *w, char *url, int datasource_type)
740 {
741         char *args = strchr(url, '?');
742         if(args) {
743                 *args='\0';
744                 args = &args[1];
745         }
746
747         // get the name of the data to show
748         char *tok = mystrsep(&url, "/");
749         debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
750
751         // do we have such a data set?
752         RRDSET *st = rrdset_find_byname(tok);
753         if(!st) st = rrdset_find(tok);
754         if(!st) {
755                 // we don't have it
756                 // try to send a file with that name
757                 buffer_flush(w->response.data);
758                 return(mysendfile(w, tok));
759         }
760
761         // we have it
762         debug(D_WEB_CLIENT, "%llu: Found RRD data with name '%s'.", w->id, tok);
763
764         // how many entries does the client want?
765         long lines = rrd_default_history_entries;
766         long group_count = 1;
767         time_t after = 0, before = 0;
768         int group_method = GROUP_AVERAGE;
769         int nonzero = 0;
770
771         if(url) {
772                 // parse the lines required
773                 tok = mystrsep(&url, "/");
774                 if(tok) lines = atoi(tok);
775                 if(lines < 1) lines = 1;
776         }
777         if(url) {
778                 // parse the group count required
779                 tok = mystrsep(&url, "/");
780                 if(tok) group_count = atoi(tok);
781                 if(group_count < 1) group_count = 1;
782                 //if(group_count > save_history / 20) group_count = save_history / 20;
783         }
784         if(url) {
785                 // parse the grouping method required
786                 tok = mystrsep(&url, "/");
787                 if(strcmp(tok, "max") == 0) group_method = GROUP_MAX;
788                 else if(strcmp(tok, "average") == 0) group_method = GROUP_AVERAGE;
789                 else if(strcmp(tok, "sum") == 0) group_method = GROUP_SUM;
790                 else debug(D_WEB_CLIENT, "%llu: Unknown group method '%s'", w->id, tok);
791         }
792         if(url) {
793                 // parse after time
794                 tok = mystrsep(&url, "/");
795                 if(tok) after = strtoul(tok, NULL, 10);
796                 if(after < 0) after = 0;
797         }
798         if(url) {
799                 // parse before time
800                 tok = mystrsep(&url, "/");
801                 if(tok) before = strtoul(tok, NULL, 10);
802                 if(before < 0) before = 0;
803         }
804         if(url) {
805                 // parse nonzero
806                 tok = mystrsep(&url, "/");
807                 if(tok && strcmp(tok, "nonzero") == 0) nonzero = 1;
808         }
809
810         w->response.data->contenttype = CT_APPLICATION_JSON;
811         buffer_flush(w->response.data);
812
813         char *google_version = "0.6";
814         char *google_reqId = "0";
815         char *google_sig = "0";
816         char *google_out = "json";
817         char *google_responseHandler = "google.visualization.Query.setResponse";
818         char *google_outFileName = NULL;
819         unsigned long last_timestamp_in_data = 0;
820         if(datasource_type == DATASOURCE_GOOGLE_JSON || datasource_type == DATASOURCE_GOOGLE_JSONP) {
821
822                 w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
823
824                 while(args) {
825                         tok = mystrsep(&args, "&");
826                         if(tok) {
827                                 char *name = mystrsep(&tok, "=");
828                                 if(name && strcmp(name, "tqx") == 0) {
829                                         char *key = mystrsep(&tok, ":");
830                                         char *value = mystrsep(&tok, ";");
831                                         if(key && value && *key && *value) {
832                                                 if(strcmp(key, "version") == 0)
833                                                         google_version = value;
834
835                                                 else if(strcmp(key, "reqId") == 0)
836                                                         google_reqId = value;
837
838                                                 else if(strcmp(key, "sig") == 0)
839                                                         google_sig = value;
840
841                                                 else if(strcmp(key, "out") == 0)
842                                                         google_out = value;
843
844                                                 else if(strcmp(key, "responseHandler") == 0)
845                                                         google_responseHandler = value;
846
847                                                 else if(strcmp(key, "outFileName") == 0)
848                                                         google_outFileName = value;
849                                         }
850                                 }
851                         }
852                 }
853
854                 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
855                         w->id, google_version, google_reqId, google_sig, google_out, google_responseHandler, google_outFileName
856                         );
857
858                 if(datasource_type == DATASOURCE_GOOGLE_JSONP) {
859                         last_timestamp_in_data = strtoul(google_sig, NULL, 0);
860
861                         // check the client wants json
862                         if(strcmp(google_out, "json") != 0) {
863                                 buffer_sprintf(w->response.data,
864                                         "%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.'}]});",
865                                         google_responseHandler, google_version, google_reqId, google_out);
866                                         return 200;
867                         }
868                 }
869         }
870
871         if(datasource_type == DATASOURCE_GOOGLE_JSONP) {
872                 buffer_sprintf(w->response.data,
873                         "%s({version:'%s',reqId:'%s',status:'ok',sig:'%lu',table:",
874                         google_responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
875         }
876
877         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);
878         unsigned long timestamp_in_data = rrd_stats_json(datasource_type, st, w->response.data, lines, group_count, group_method, after, before, nonzero);
879
880         if(datasource_type == DATASOURCE_GOOGLE_JSONP) {
881                 if(timestamp_in_data > last_timestamp_in_data)
882                         buffer_strcat(w->response.data, "});");
883
884                 else {
885                         // the client already has the latest data
886                         buffer_flush(w->response.data);
887                         buffer_sprintf(w->response.data,
888                                 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
889                                 google_responseHandler, google_version, google_reqId);
890                 }
891         }
892
893         return 200;
894 }
895
896 /*
897 int web_client_parse_request(struct web_client *w) {
898         // protocol
899         // hostname
900         // path
901         // query string name-value
902         // http version
903         // method
904         // http request headers name-value
905
906         web_client_clean_request(w);
907
908         debug(D_WEB_DATA, "%llu: Processing data buffer of %d bytes: '%s'.", w->id, w->response.data->bytes, w->response.data->buffer);
909
910         char *buf = w->response.data->buffer;
911         char *line, *tok;
912
913         // ------------------------------------------------------------------------
914         // the first line
915
916         if(buf && (line = strsep(&buf, "\r\n"))) {
917                 // method
918                 if(line && (tok = strsep(&line, " "))) {
919                         w->request.protocol = strdup(tok);
920                 }
921                 else goto cleanup;
922
923                 // url
924         }
925         else goto cleanup;
926
927         // ------------------------------------------------------------------------
928         // the rest of the lines
929
930         while(buf && (line = strsep(&buf, "\r\n"))) {
931                 while(line && (tok = strsep(&line, ": "))) {
932                 }
933         }
934
935         char *url = NULL;
936
937
938 cleanup:
939         web_client_clean_request(w);
940         return 0;
941 }
942 */
943
944 void web_client_process(struct web_client *w) {
945         int code = 500;
946         int bytes;
947
948         w->wait_receive = 0;
949
950         // check if we have an empty line (end of HTTP header)
951         if(strstr(w->response.data->buffer, "\r\n\r\n")) {
952                 global_statistics_lock();
953                 global_statistics.web_requests++;
954                 global_statistics_unlock();
955
956                 gettimeofday(&w->tv_in, NULL);
957                 debug(D_WEB_DATA, "%llu: Processing data buffer of %d bytes: '%s'.", w->id, w->response.data->len, w->response.data->buffer);
958
959                 // check if the client requested keep-alive HTTP
960                 if(strcasestr(w->response.data->buffer, "Connection: keep-alive")) w->keepalive = 1;
961                 else w->keepalive = 0;
962
963 #ifdef NETDATA_WITH_ZLIB
964                 // check if the client accepts deflate
965                 if(web_enable_gzip && strstr(w->response.data->buffer, "gzip"))
966                         web_client_enable_deflate(w);
967 #endif // NETDATA_WITH_ZLIB
968
969                 int datasource_type = DATASOURCE_GOOGLE_JSONP;
970                 //if(strstr(w->response.data->buffer, "X-DataSource-Auth"))
971                 //      datasource_type = DATASOURCE_GOOGLE_JSON;
972
973                 char *buf = w->response.data->buffer;
974                 char *tok = strsep(&buf, " \r\n");
975                 char *url = NULL;
976                 char *pointer_to_free = NULL; // keep url_decode() allocated buffer
977
978                 if(buf && strcmp(tok, "GET") == 0) {
979                         tok = strsep(&buf, " \r\n");
980                         pointer_to_free = url = url_decode(tok);
981                         debug(D_WEB_CLIENT, "%llu: Processing HTTP GET on url '%s'.", w->id, url);
982                 }
983                 else if (buf && strcmp(tok, "POST") == 0) {
984                         w->keepalive = 0;
985                         tok = strsep(&buf, " \r\n");
986                         pointer_to_free = url = url_decode(tok);
987
988                         debug(D_WEB_CLIENT, "%llu: I don't know how to handle POST with form data. Assuming it is a GET on url '%s'.", w->id, url);
989                 }
990
991                 w->last_url[0] = '\0';
992                 if(url) {
993                         strncpy(w->last_url, url, URL_MAX);
994                         w->last_url[URL_MAX] = '\0';
995
996                         tok = mystrsep(&url, "/?");
997
998                         debug(D_WEB_CLIENT, "%llu: Processing command '%s'.", w->id, tok);
999
1000                         if(strcmp(tok, "api") == 0) {
1001                                 // the client is requesting api access
1002                                 datasource_type = DATASOURCE_JSON;
1003                                 code = web_client_api_request(w, url);
1004                         }
1005                         else if(strcmp(tok, WEB_PATH_DATA) == 0) { // "data"
1006                                 // the client is requesting rrd data
1007                                 datasource_type = DATASOURCE_JSON;
1008                                 code = web_client_data_request(w, url, datasource_type);
1009                         }
1010                         else if(strcmp(tok, WEB_PATH_DATASOURCE) == 0) { // "datasource"
1011                                 // the client is requesting google datasource
1012                                 code = web_client_data_request(w, url, datasource_type);
1013                         }
1014                         else if(strcmp(tok, WEB_PATH_GRAPH) == 0) { // "graph"
1015                                 // the client is requesting an rrd graph
1016
1017                                 // get the name of the data to show
1018                                 tok = mystrsep(&url, "/?&");
1019                                 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1020
1021                                 // do we have such a data set?
1022                                 RRDSET *st = rrdset_find_byname(tok);
1023                                 if(!st) st = rrdset_find(tok);
1024                                 if(!st) {
1025                                         // we don't have it
1026                                         // try to send a file with that name
1027                                         buffer_flush(w->response.data);
1028                                         code = mysendfile(w, tok);
1029                                 }
1030                                 else {
1031                                         code = 200;
1032                                         debug(D_WEB_CLIENT_ACCESS, "%llu: Sending %s.json of RRD_STATS...", w->id, st->name);
1033                                         w->response.data->contenttype = CT_APPLICATION_JSON;
1034                                         buffer_flush(w->response.data);
1035                                         rrd_stats_graph_json(st, url, w->response.data);
1036                                 }
1037                         }
1038                         else if(strcmp(tok, "debug") == 0) {
1039                                 buffer_flush(w->response.data);
1040
1041                                 // get the name of the data to show
1042                                 tok = mystrsep(&url, "/?&");
1043                                 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1044
1045                                 // do we have such a data set?
1046                                 RRDSET *st = rrdset_find_byname(tok);
1047                                 if(!st) st = rrdset_find(tok);
1048                                 if(!st) {
1049                                         code = 404;
1050                                         buffer_sprintf(w->response.data, "Chart %s is not found.\r\n", tok);
1051                                         debug(D_WEB_CLIENT_ACCESS, "%llu: %s is not found.", w->id, tok);
1052                                 }
1053                                 else {
1054                                         code = 200;
1055                                         debug_flags |= D_RRD_STATS;
1056                                         st->debug = st->debug?0:1;
1057                                         buffer_sprintf(w->response.data, "Chart %s has now debug %s.\r\n", tok, st->debug?"enabled":"disabled");
1058                                         debug(D_WEB_CLIENT_ACCESS, "%llu: debug for %s is %s.", w->id, tok, st->debug?"enabled":"disabled");
1059                                 }
1060                         }
1061                         else if(strcmp(tok, "mirror") == 0) {
1062                                 code = 200;
1063
1064                                 debug(D_WEB_CLIENT_ACCESS, "%llu: Mirroring...", w->id);
1065
1066                                 // replace the zero bytes with spaces
1067                                 buffer_char_replace(w->response.data, '\0', ' ');
1068
1069                                 // just leave the buffer as is
1070                                 // it will be copied back to the client
1071                         }
1072                         else if(strcmp(tok, "list") == 0) {
1073                                 code = 200;
1074
1075                                 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending list of RRD_STATS...", w->id);
1076
1077                                 buffer_flush(w->response.data);
1078                                 RRDSET *st = rrdset_root;
1079
1080                                 for ( ; st ; st = st->next )
1081                                         buffer_sprintf(w->response.data, "%s\n", st->name);
1082                         }
1083                         else if(strcmp(tok, "all.json") == 0) {
1084                                 code = 200;
1085                                 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending JSON list of all monitors of RRD_STATS...", w->id);
1086
1087                                 w->response.data->contenttype = CT_APPLICATION_JSON;
1088                                 buffer_flush(w->response.data);
1089                                 rrd_stats_all_json(w->response.data);
1090                         }
1091                         else if(strcmp(tok, "netdata.conf") == 0) {
1092                                 code = 200;
1093                                 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending netdata.conf ...", w->id);
1094
1095                                 w->response.data->contenttype = CT_TEXT_PLAIN;
1096                                 buffer_flush(w->response.data);
1097                                 generate_config(w->response.data, 0);
1098                         }
1099                         else {
1100                                 char filename[FILENAME_MAX+1];
1101                                 url = filename;
1102                                 strncpy(filename, w->last_url, FILENAME_MAX);
1103                                 filename[FILENAME_MAX] = '\0';
1104                                 tok = mystrsep(&url, "?");
1105                                 buffer_flush(w->response.data);
1106                                 code = mysendfile(w, (tok && *tok)?tok:"/");
1107                         }
1108                 }
1109                 else {
1110                         strcpy(w->last_url, "not a valid response");
1111
1112                         if(buf) debug(D_WEB_CLIENT_ACCESS, "%llu: Cannot understand '%s'.", w->id, buf);
1113
1114                         code = 500;
1115                         buffer_flush(w->response.data);
1116                         buffer_strcat(w->response.data, "I don't understand you...\r\n");
1117                 }
1118
1119                 // free url_decode() buffer
1120                 if(pointer_to_free) free(pointer_to_free);
1121         }
1122         else if(w->response.data->len > 8192) {
1123                 strcpy(w->last_url, "too big request");
1124
1125                 debug(D_WEB_CLIENT_ACCESS, "%llu: Received request is too big.", w->id);
1126
1127                 code = 400;
1128                 buffer_flush(w->response.data);
1129                 buffer_strcat(w->response.data, "Received request is too big.\r\n");
1130         }
1131         else {
1132                 // wait for more data
1133                 w->wait_receive = 1;
1134                 return;
1135         }
1136
1137         gettimeofday(&w->tv_ready, NULL);
1138         w->response.data->date = time(NULL);
1139         w->response.sent = 0;
1140         w->response.code = code;
1141
1142         // prepare the HTTP response header
1143         debug(D_WEB_CLIENT, "%llu: Generating HTTP header with response %d.", w->id, code);
1144
1145         char *content_type_string = "";
1146         switch(w->response.data->contenttype) {
1147                 case CT_TEXT_HTML:
1148                         content_type_string = "text/html; charset=utf-8";
1149                         break;
1150
1151                 case CT_APPLICATION_XML:
1152                         content_type_string = "application/xml; charset=utf-8";
1153                         break;
1154
1155                 case CT_APPLICATION_JSON:
1156                         content_type_string = "application/json; charset=utf-8";
1157                         break;
1158
1159                 case CT_APPLICATION_X_JAVASCRIPT:
1160                         content_type_string = "application/x-javascript; charset=utf-8";
1161                         break;
1162
1163                 case CT_TEXT_CSS:
1164                         content_type_string = "text/css; charset=utf-8";
1165                         break;
1166
1167                 case CT_TEXT_XML:
1168                         content_type_string = "text/xml; charset=utf-8";
1169                         break;
1170
1171                 case CT_TEXT_XSL:
1172                         content_type_string = "text/xsl; charset=utf-8";
1173                         break;
1174
1175                 case CT_APPLICATION_OCTET_STREAM:
1176                         content_type_string = "application/octet-stream";
1177                         break;
1178
1179                 case CT_IMAGE_SVG_XML:
1180                         content_type_string = "image/svg+xml";
1181                         break;
1182
1183                 case CT_APPLICATION_X_FONT_TRUETYPE:
1184                         content_type_string = "application/x-font-truetype";
1185                         break;
1186
1187                 case CT_APPLICATION_X_FONT_OPENTYPE:
1188                         content_type_string = "application/x-font-opentype";
1189                         break;
1190
1191                 case CT_APPLICATION_FONT_WOFF:
1192                         content_type_string = "application/font-woff";
1193                         break;
1194
1195                 case CT_APPLICATION_VND_MS_FONTOBJ:
1196                         content_type_string = "application/vnd.ms-fontobject";
1197                         break;
1198
1199                 default:
1200                 case CT_TEXT_PLAIN:
1201                         content_type_string = "text/plain; charset=utf-8";
1202                         break;
1203         }
1204
1205         char *code_msg = "";
1206         switch(code) {
1207                 case 200:
1208                         code_msg = "OK";
1209                         break;
1210
1211                 case 307:
1212                         code_msg = "Temporary Redirect";
1213                         break;
1214
1215                 case 400:
1216                         code_msg = "Bad Request";
1217                         break;
1218
1219                 case 403:
1220                         code_msg = "Forbidden";
1221                         break;
1222
1223                 case 404:
1224                         code_msg = "Not Found";
1225                         break;
1226
1227                 default:
1228                         code_msg = "Internal Server Error";
1229                         break;
1230         }
1231
1232         char date[100];
1233         struct tm tm = *gmtime(&w->response.data->date);
1234         strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %Z", &tm);
1235
1236         buffer_sprintf(w->response.header_output,
1237                 "HTTP/1.1 %d %s\r\n"
1238                 "Connection: %s\r\n"
1239                 "Server: NetData Embedded HTTP Server\r\n"
1240                 "Content-Type: %s\r\n"
1241                 "Access-Control-Allow-Origin: *\r\n"
1242                 "Date: %s\r\n"
1243                 , code, code_msg
1244                 , w->keepalive?"keep-alive":"close"
1245                 , content_type_string
1246                 , date
1247                 );
1248
1249         if(buffer_strlen(w->response.header))
1250                 buffer_strcat(w->response.header_output, buffer_tostring(w->response.header));
1251
1252         if(w->mode == WEB_CLIENT_MODE_NORMAL) {
1253                 buffer_sprintf(w->response.header_output,
1254                         "Expires: %s\r\n"
1255                         "Cache-Control: no-cache\r\n"
1256                         , date);
1257         }
1258         else
1259                 buffer_strcat(w->response.header_output, "Cache-Control: public\r\n");
1260
1261         // if we know the content length, put it
1262         if(!w->response.zoutput && (w->response.data->len || w->response.rlen))
1263                 buffer_sprintf(w->response.header_output,
1264                         "Content-Length: %ld\r\n"
1265                         , w->response.data->len?w->response.data->len:w->response.rlen
1266                         );
1267         else if(!w->response.zoutput)
1268                 w->keepalive = 0;       // content-length is required for keep-alive
1269
1270         if(w->response.zoutput) {
1271                 buffer_strcat(w->response.header_output,
1272                         "Content-Encoding: gzip\r\n"
1273                         "Transfer-Encoding: chunked\r\n"
1274                         );
1275         }
1276
1277         buffer_strcat(w->response.header_output, "\r\n");
1278
1279         // disable TCP_NODELAY, to buffer the header
1280         int flag = 0;
1281         if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0)
1282                 error("%llu: failed to disable TCP_NODELAY on socket.", w->id);
1283
1284         // sent the HTTP header
1285         debug(D_WEB_DATA, "%llu: Sending response HTTP header of size %d: '%s'"
1286                         , w->id
1287                         , buffer_strlen(w->response.header_output)
1288                         , buffer_tostring(w->response.header_output)
1289                         );
1290
1291         bytes = send(w->ofd, buffer_tostring(w->response.header_output), buffer_strlen(w->response.header_output), 0);
1292         if(bytes != buffer_strlen(w->response.header_output))
1293                 error("%llu: HTTP Header failed to be sent (I sent %d bytes but the system sent %d bytes)."
1294                                 , w->id
1295                                 , buffer_strlen(w->response.header_output)
1296                                 , bytes);
1297         else {
1298                 global_statistics_lock();
1299                 global_statistics.bytes_sent += bytes;
1300                 global_statistics_unlock();
1301         }
1302
1303         // enable TCP_NODELAY, to send all data immediately at the next send()
1304         flag = 1;
1305         if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0) error("%llu: failed to enable TCP_NODELAY on socket.", w->id);
1306
1307         // enable sending immediately if we have data
1308         if(w->response.data->len) w->wait_send = 1;
1309         else w->wait_send = 0;
1310
1311         // pretty logging
1312         switch(w->mode) {
1313                 case WEB_CLIENT_MODE_NORMAL:
1314                         debug(D_WEB_CLIENT, "%llu: Done preparing the response. Sending data (%d bytes) to client.", w->id, w->response.data->len);
1315                         break;
1316
1317                 case WEB_CLIENT_MODE_FILECOPY:
1318                         if(w->response.rlen) {
1319                                 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending data file of %d bytes to client.", w->id, w->response.rlen);
1320                                 w->wait_receive = 1;
1321
1322                                 /*
1323                                 // utilize the kernel sendfile() for copying the file to the socket.
1324                                 // this block of code can be commented, without anything missing.
1325                                 // when it is commented, the program will copy the data using async I/O.
1326                                 {
1327                                         long len = sendfile(w->ofd, w->ifd, NULL, w->response.data->rbytes);
1328                                         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);
1329                                         else web_client_reset(w);
1330                                 }
1331                                 */
1332                         }
1333                         else
1334                                 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending an unknown amount of bytes to client.", w->id);
1335                         break;
1336
1337                 default:
1338                         fatal("%llu: Unknown client mode %d.", w->id, w->mode);
1339                         break;
1340         }
1341 }
1342
1343 long web_client_send_chunk_header(struct web_client *w, int len)
1344 {
1345         debug(D_DEFLATE, "%llu: OPEN CHUNK of %d bytes (hex: %x).", w->id, len, len);
1346         char buf[1024];
1347         sprintf(buf, "%X\r\n", len);
1348         int bytes = send(w->ofd, buf, strlen(buf), MSG_DONTWAIT);
1349
1350         if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk header %d bytes.", w->id, bytes);
1351         else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk header to the client.", w->id);
1352         else debug(D_DEFLATE, "%llu: Failed to send chunk header to client. Reason: %s", w->id, strerror(errno));
1353
1354         return bytes;
1355 }
1356
1357 long web_client_send_chunk_close(struct web_client *w)
1358 {
1359         //debug(D_DEFLATE, "%llu: CLOSE CHUNK.", w->id);
1360
1361         int bytes = send(w->ofd, "\r\n", 2, MSG_DONTWAIT);
1362
1363         if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
1364         else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
1365         else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client. Reason: %s", w->id, strerror(errno));
1366
1367         return bytes;
1368 }
1369
1370 long web_client_send_chunk_finalize(struct web_client *w)
1371 {
1372         //debug(D_DEFLATE, "%llu: FINALIZE CHUNK.", w->id);
1373
1374         int bytes = send(w->ofd, "\r\n0\r\n\r\n", 7, MSG_DONTWAIT);
1375
1376         if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
1377         else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
1378         else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client. Reason: %s", w->id, strerror(errno));
1379
1380         return bytes;
1381 }
1382
1383 #ifdef NETDATA_WITH_ZLIB
1384 long web_client_send_deflate(struct web_client *w)
1385 {
1386         long len = 0, t = 0;
1387
1388         // when using compression,
1389         // w->response.sent is the amount of bytes passed through compression
1390
1391         debug(D_DEFLATE, "%llu: TEST 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);
1392
1393         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) {
1394                 // there is nothing to send
1395
1396                 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1397
1398                 // finalize the chunk
1399                 if(w->response.sent != 0)
1400                         t += web_client_send_chunk_finalize(w);
1401
1402                 // there can be two cases for this
1403                 // A. we have done everything
1404                 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
1405
1406                 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->response.rlen && w->response.rlen > w->response.data->len) {
1407                         // we have to wait, more data will come
1408                         debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1409                         w->wait_send = 0;
1410                         return(0);
1411                 }
1412
1413                 if(w->keepalive == 0) {
1414                         debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->response.sent);
1415                         errno = 0;
1416                         return(-1);
1417                 }
1418
1419                 // reset the client
1420                 web_client_reset(w);
1421                 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1422                 return(0);
1423         }
1424
1425         if(w->response.zhave == w->response.zsent) {
1426                 // compress more input data
1427
1428                 // close the previous open chunk
1429                 if(w->response.sent != 0) t += web_client_send_chunk_close(w);
1430
1431                 debug(D_DEFLATE, "%llu: Compressing %d bytes starting from %d.", w->id, (w->response.data->len - w->response.sent), w->response.sent);
1432
1433                 // give the compressor all the data not passed through the compressor yet
1434                 if(w->response.data->len > w->response.sent) {
1435                         w->response.zstream.next_in = (Bytef *)&w->response.data->buffer[w->response.sent];
1436                         w->response.zstream.avail_in = (w->response.data->len - w->response.sent);
1437                 }
1438
1439                 // reset the compressor output buffer
1440                 w->response.zstream.next_out = w->response.zbuffer;
1441                 w->response.zstream.avail_out = ZLIB_CHUNK;
1442
1443                 // ask for FINISH if we have all the input
1444                 int flush = Z_SYNC_FLUSH;
1445                 if(w->mode == WEB_CLIENT_MODE_NORMAL
1446                         || (w->mode == WEB_CLIENT_MODE_FILECOPY && w->response.data->len == w->response.rlen)) {
1447                         flush = Z_FINISH;
1448                         debug(D_DEFLATE, "%llu: Requesting Z_FINISH.", w->id);
1449                 }
1450                 else {
1451                         debug(D_DEFLATE, "%llu: Requesting Z_SYNC_FLUSH.", w->id);
1452                 }
1453
1454                 // compress
1455                 if(deflate(&w->response.zstream, flush) == Z_STREAM_ERROR) {
1456                         error("%llu: Compression failed. Closing down client.", w->id);
1457                         web_client_reset(w);
1458                         return(-1);
1459                 }
1460
1461                 w->response.zhave = ZLIB_CHUNK - w->response.zstream.avail_out;
1462                 w->response.zsent = 0;
1463
1464                 // keep track of the bytes passed through the compressor
1465                 w->response.sent = w->response.data->len;
1466
1467                 debug(D_DEFLATE, "%llu: Compression produced %d bytes.", w->id, w->response.zhave);
1468
1469                 // open a new chunk
1470                 t += web_client_send_chunk_header(w, w->response.zhave);
1471         }
1472
1473         len = send(w->ofd, &w->response.zbuffer[w->response.zsent], w->response.zhave - w->response.zsent, MSG_DONTWAIT);
1474         if(len > 0) {
1475                 w->response.zsent += len;
1476                 if(t > 0) len += t;
1477                 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, len);
1478         }
1479         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);
1480         else debug(D_WEB_CLIENT, "%llu: Failed to send data to client. Reason: %s", w->id, strerror(errno));
1481
1482         return(len);
1483 }
1484 #endif // NETDATA_WITH_ZLIB
1485
1486 long web_client_send(struct web_client *w)
1487 {
1488 #ifdef NETDATA_WITH_ZLIB
1489         if(likely(w->response.zoutput)) return web_client_send_deflate(w);
1490 #endif // NETDATA_WITH_ZLIB
1491
1492         long bytes;
1493
1494         if(unlikely(w->response.data->len - w->response.sent == 0)) {
1495                 // there is nothing to send
1496
1497                 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1498
1499                 // there can be two cases for this
1500                 // A. we have done everything
1501                 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
1502
1503                 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->response.rlen && w->response.rlen > w->response.data->len) {
1504                         // we have to wait, more data will come
1505                         debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1506                         w->wait_send = 0;
1507                         return(0);
1508                 }
1509
1510                 if(unlikely(w->keepalive == 0)) {
1511                         debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->response.sent);
1512                         errno = 0;
1513                         return(-1);
1514                 }
1515
1516                 web_client_reset(w);
1517                 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1518                 return(0);
1519         }
1520
1521         bytes = send(w->ofd, &w->response.data->buffer[w->response.sent], w->response.data->len - w->response.sent, MSG_DONTWAIT);
1522         if(likely(bytes > 0)) {
1523                 w->response.sent += bytes;
1524                 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, bytes);
1525         }
1526         else if(likely(bytes == 0)) debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client.", w->id);
1527         else debug(D_WEB_CLIENT, "%llu: Failed to send data to client. Reason: %s", w->id, strerror(errno));
1528
1529         return(bytes);
1530 }
1531
1532 long web_client_receive(struct web_client *w)
1533 {
1534         // do we have any space for more data?
1535         buffer_need_bytes(w->response.data, WEB_REQUEST_LENGTH);
1536
1537         long left = w->response.data->size - w->response.data->len;
1538         long bytes;
1539
1540         if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY))
1541                 bytes = read(w->ifd, &w->response.data->buffer[w->response.data->len], (left-1));
1542         else
1543                 bytes = recv(w->ifd, &w->response.data->buffer[w->response.data->len], left-1, MSG_DONTWAIT);
1544
1545         if(likely(bytes > 0)) {
1546                 int old = w->response.data->len;
1547                 w->response.data->len += bytes;
1548                 w->response.data->buffer[w->response.data->len] = '\0';
1549
1550                 debug(D_WEB_CLIENT, "%llu: Received %d bytes.", w->id, bytes);
1551                 debug(D_WEB_DATA, "%llu: Received data: '%s'.", w->id, &w->response.data->buffer[old]);
1552
1553                 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1554                         w->wait_send = 1;
1555                         if(w->response.rlen && w->response.data->len >= w->response.rlen) w->wait_receive = 0;
1556                 }
1557         }
1558         else if(likely(bytes == 0)) {
1559                 debug(D_WEB_CLIENT, "%llu: Out of input data.", w->id);
1560
1561                 // if we cannot read, it means we have an error on input.
1562                 // if however, we are copying a file from ifd to ofd, we should not return an error.
1563                 // in this case, the error should be generated when the file has been sent to the client.
1564
1565                 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1566                         // we are copying data from ifd to ofd
1567                         // let it finish copying...
1568                         w->wait_receive = 0;
1569                         debug(D_WEB_CLIENT, "%llu: Disabling input.", w->id);
1570                 }
1571                 else {
1572                         bytes = -1;
1573                         errno = 0;
1574                 }
1575         }
1576
1577         return(bytes);
1578 }
1579
1580
1581 // --------------------------------------------------------------------------------------
1582 // the thread of a single client
1583
1584 // 1. waits for input and output, using async I/O
1585 // 2. it processes HTTP requests
1586 // 3. it generates HTTP responses
1587 // 4. it copies data from input to output if mode is FILECOPY
1588
1589 void *web_client_main(void *ptr)
1590 {
1591         if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
1592                 error("Cannot set pthread cancel type to DEFERRED.");
1593
1594         if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
1595                 error("Cannot set pthread cancel state to ENABLE.");
1596
1597         struct timeval tv;
1598         struct web_client *w = ptr;
1599         int retval;
1600         fd_set ifds, ofds, efds;
1601         int fdmax = 0;
1602
1603         log_access("%llu: %s port %s connected on thread task id %d", w->id, w->client_ip, w->client_port, gettid());
1604
1605         for(;;) {
1606                 FD_ZERO (&ifds);
1607                 FD_ZERO (&ofds);
1608                 FD_ZERO (&efds);
1609
1610                 FD_SET(w->ifd, &efds);
1611
1612                 if(w->ifd != w->ofd)
1613                         FD_SET(w->ofd, &efds);
1614
1615                 if (w->wait_receive) {
1616                         FD_SET(w->ifd, &ifds);
1617                         if(w->ifd > fdmax) fdmax = w->ifd;
1618                 }
1619
1620                 if (w->wait_send) {
1621                         FD_SET(w->ofd, &ofds);
1622                         if(w->ofd > fdmax) fdmax = w->ofd;
1623                 }
1624
1625                 tv.tv_sec = web_client_timeout;
1626                 tv.tv_usec = 0;
1627
1628                 debug(D_WEB_CLIENT, "%llu: Waiting socket async I/O for %s %s", w->id, w->wait_receive?"INPUT":"", w->wait_send?"OUTPUT":"");
1629                 retval = select(fdmax+1, &ifds, &ofds, &efds, &tv);
1630
1631                 if(retval == -1) {
1632                         debug(D_WEB_CLIENT_ACCESS, "%llu: LISTENER: select() failed.", w->id);
1633                         continue;
1634                 }
1635                 else if(!retval) {
1636                         // timeout
1637                         debug(D_WEB_CLIENT_ACCESS, "%llu: LISTENER: timeout.", w->id);
1638                         break;
1639                 }
1640
1641                 if(FD_ISSET(w->ifd, &efds)) {
1642                         debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on input socket (%s).", w->id, strerror(errno));
1643                         break;
1644                 }
1645
1646                 if(FD_ISSET(w->ofd, &efds)) {
1647                         debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on output socket (%s).", w->id, strerror(errno));
1648                         break;
1649                 }
1650
1651                 if(w->wait_send && FD_ISSET(w->ofd, &ofds)) {
1652                         long bytes;
1653                         if((bytes = web_client_send(w)) < 0) {
1654                                 debug(D_WEB_CLIENT, "%llu: Cannot send data to client. Closing client (ouput: %s).", w->id, strerror(errno));
1655                                 errno = 0;
1656                                 break;
1657                         }
1658
1659                         global_statistics_lock();
1660                         global_statistics.bytes_sent += bytes;
1661                         global_statistics_unlock();
1662                 }
1663
1664                 if(w->wait_receive && FD_ISSET(w->ifd, &ifds)) {
1665                         long bytes;
1666                         if((bytes = web_client_receive(w)) < 0) {
1667                                 debug(D_WEB_CLIENT, "%llu: Cannot receive data from client. Closing client (input: %s).", w->id, strerror(errno));
1668                                 errno = 0;
1669                                 break;
1670                         }
1671
1672                         global_statistics_lock();
1673                         global_statistics.bytes_received += bytes;
1674                         global_statistics_unlock();
1675
1676                         if(w->mode == WEB_CLIENT_MODE_NORMAL) {
1677                                 debug(D_WEB_CLIENT, "%llu: Attempting to process received data.", w->id);
1678                                 web_client_process(w);
1679                         }
1680                 }
1681         }
1682
1683         log_access("%llu: %s port %s disconnected from thread task id %d", w->id, w->client_ip, w->client_port, gettid());
1684         debug(D_WEB_CLIENT, "%llu: done...", w->id);
1685
1686         web_client_reset(w);
1687         w->obsolete = 1;
1688
1689         return NULL;
1690 }