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