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