]> arthur.barton.de Git - netdata.git/blob - src/web_client.c
increased security: added option "web files group", so that netdata will also check...
[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         debug(D_WEB_CLIENT, "%llu: Searching for API v1 command '%s'.", w->id, tok);
785
786         if(strcmp(tok, "data") == 0)
787                 return web_client_api_request_v1_data(w, url);
788         else if(strcmp(tok, "chart") == 0)
789                 return web_client_api_request_v1_chart(w, url);
790         else if(strcmp(tok, "charts") == 0)
791                 return web_client_api_request_v1_charts(w, url);
792
793         buffer_flush(w->response.data);
794         buffer_sprintf(w->response.data, "Unsupported v1 API command: %s", tok);
795         return 404;
796 }
797
798 int web_client_api_request(struct web_client *w, char *url)
799 {
800         // get the api version
801         char *tok = mystrsep(&url, "/?&");
802         debug(D_WEB_CLIENT, "%llu: Searching for API version '%s'.", w->id, tok);
803
804         if(strcmp(tok, "v1") == 0)
805                 return web_client_api_request_v1(w, url);
806
807         buffer_flush(w->response.data);
808         buffer_sprintf(w->response.data, "Unsupported API version: %s", tok);
809         return 404;
810 }
811
812 int web_client_data_request(struct web_client *w, char *url, int datasource_type)
813 {
814         char *args = strchr(url, '?');
815         if(args) {
816                 *args='\0';
817                 args = &args[1];
818         }
819
820         // get the name of the data to show
821         char *tok = mystrsep(&url, "/");
822         debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
823
824         // do we have such a data set?
825         RRDSET *st = rrdset_find_byname(tok);
826         if(!st) st = rrdset_find(tok);
827         if(!st) {
828                 // we don't have it
829                 // try to send a file with that name
830                 buffer_flush(w->response.data);
831                 return(mysendfile(w, tok));
832         }
833
834         // we have it
835         debug(D_WEB_CLIENT, "%llu: Found RRD data with name '%s'.", w->id, tok);
836
837         // how many entries does the client want?
838         long lines = rrd_default_history_entries;
839         long group_count = 1;
840         time_t after = 0, before = 0;
841         int group_method = GROUP_AVERAGE;
842         int nonzero = 0;
843
844         if(url) {
845                 // parse the lines required
846                 tok = mystrsep(&url, "/");
847                 if(tok) lines = atoi(tok);
848                 if(lines < 1) lines = 1;
849         }
850         if(url) {
851                 // parse the group count required
852                 tok = mystrsep(&url, "/");
853                 if(tok) group_count = atoi(tok);
854                 if(group_count < 1) group_count = 1;
855                 //if(group_count > save_history / 20) group_count = save_history / 20;
856         }
857         if(url) {
858                 // parse the grouping method required
859                 tok = mystrsep(&url, "/");
860                 if(strcmp(tok, "max") == 0) group_method = GROUP_MAX;
861                 else if(strcmp(tok, "average") == 0) group_method = GROUP_AVERAGE;
862                 else if(strcmp(tok, "sum") == 0) group_method = GROUP_SUM;
863                 else debug(D_WEB_CLIENT, "%llu: Unknown group method '%s'", w->id, tok);
864         }
865         if(url) {
866                 // parse after time
867                 tok = mystrsep(&url, "/");
868                 if(tok) after = strtoul(tok, NULL, 10);
869                 if(after < 0) after = 0;
870         }
871         if(url) {
872                 // parse before time
873                 tok = mystrsep(&url, "/");
874                 if(tok) before = strtoul(tok, NULL, 10);
875                 if(before < 0) before = 0;
876         }
877         if(url) {
878                 // parse nonzero
879                 tok = mystrsep(&url, "/");
880                 if(tok && strcmp(tok, "nonzero") == 0) nonzero = 1;
881         }
882
883         w->response.data->contenttype = CT_APPLICATION_JSON;
884         buffer_flush(w->response.data);
885
886         char *google_version = "0.6";
887         char *google_reqId = "0";
888         char *google_sig = "0";
889         char *google_out = "json";
890         char *google_responseHandler = "google.visualization.Query.setResponse";
891         char *google_outFileName = NULL;
892         time_t last_timestamp_in_data = 0;
893         if(datasource_type == DATASOURCE_DATATABLE_JSON || datasource_type == DATASOURCE_DATATABLE_JSONP) {
894
895                 w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
896
897                 while(args) {
898                         tok = mystrsep(&args, "&");
899                         if(tok) {
900                                 char *name = mystrsep(&tok, "=");
901                                 if(name && strcmp(name, "tqx") == 0) {
902                                         char *key = mystrsep(&tok, ":");
903                                         char *value = mystrsep(&tok, ";");
904                                         if(key && value && *key && *value) {
905                                                 if(strcmp(key, "version") == 0)
906                                                         google_version = value;
907
908                                                 else if(strcmp(key, "reqId") == 0)
909                                                         google_reqId = value;
910
911                                                 else if(strcmp(key, "sig") == 0)
912                                                         google_sig = value;
913
914                                                 else if(strcmp(key, "out") == 0)
915                                                         google_out = value;
916
917                                                 else if(strcmp(key, "responseHandler") == 0)
918                                                         google_responseHandler = value;
919
920                                                 else if(strcmp(key, "outFileName") == 0)
921                                                         google_outFileName = value;
922                                         }
923                                 }
924                         }
925                 }
926
927                 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
928                         w->id, google_version, google_reqId, google_sig, google_out, google_responseHandler, google_outFileName
929                         );
930
931                 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
932                         last_timestamp_in_data = strtoul(google_sig, NULL, 0);
933
934                         // check the client wants json
935                         if(strcmp(google_out, "json") != 0) {
936                                 buffer_sprintf(w->response.data,
937                                         "%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.'}]});",
938                                         google_responseHandler, google_version, google_reqId, google_out);
939                                         return 200;
940                         }
941                 }
942         }
943
944         if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
945                 buffer_sprintf(w->response.data,
946                         "%s({version:'%s',reqId:'%s',status:'ok',sig:'%lu',table:",
947                         google_responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
948         }
949
950         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);
951         time_t timestamp_in_data = rrd_stats_json(datasource_type, st, w->response.data, lines, group_count, group_method, after, before, nonzero);
952
953         if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
954                 if(timestamp_in_data > last_timestamp_in_data)
955                         buffer_strcat(w->response.data, "});");
956
957                 else {
958                         // the client already has the latest data
959                         buffer_flush(w->response.data);
960                         buffer_sprintf(w->response.data,
961                                 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
962                                 google_responseHandler, google_version, google_reqId);
963                 }
964         }
965
966         return 200;
967 }
968
969 /*
970 int web_client_parse_request(struct web_client *w) {
971         // protocol
972         // hostname
973         // path
974         // query string name-value
975         // http version
976         // method
977         // http request headers name-value
978
979         web_client_clean_request(w);
980
981         debug(D_WEB_DATA, "%llu: Processing data buffer of %d bytes: '%s'.", w->id, w->response.data->bytes, w->response.data->buffer);
982
983         char *buf = w->response.data->buffer;
984         char *line, *tok;
985
986         // ------------------------------------------------------------------------
987         // the first line
988
989         if(buf && (line = strsep(&buf, "\r\n"))) {
990                 // method
991                 if(line && (tok = strsep(&line, " "))) {
992                         w->request.protocol = strdup(tok);
993                 }
994                 else goto cleanup;
995
996                 // url
997         }
998         else goto cleanup;
999
1000         // ------------------------------------------------------------------------
1001         // the rest of the lines
1002
1003         while(buf && (line = strsep(&buf, "\r\n"))) {
1004                 while(line && (tok = strsep(&line, ": "))) {
1005                 }
1006         }
1007
1008         char *url = NULL;
1009
1010
1011 cleanup:
1012         web_client_clean_request(w);
1013         return 0;
1014 }
1015 */
1016
1017 void web_client_process(struct web_client *w) {
1018         int code = 500;
1019         ssize_t bytes;
1020         int enable_gzip = 0;
1021
1022         w->wait_receive = 0;
1023
1024         // check if we have an empty line (end of HTTP header)
1025         if(strstr(w->response.data->buffer, "\r\n\r\n")) {
1026                 global_statistics_lock();
1027                 global_statistics.web_requests++;
1028                 global_statistics_unlock();
1029
1030                 gettimeofday(&w->tv_in, NULL);
1031                 debug(D_WEB_DATA, "%llu: Processing data buffer of %d bytes: '%s'.", w->id, w->response.data->len, w->response.data->buffer);
1032
1033                 // check if the client requested keep-alive HTTP
1034                 if(strcasestr(w->response.data->buffer, "Connection: keep-alive")) w->keepalive = 1;
1035                 else w->keepalive = 0;
1036
1037 #ifdef NETDATA_WITH_ZLIB
1038                 // check if the client accepts deflate
1039                 if(web_enable_gzip && strstr(w->response.data->buffer, "gzip"))
1040                         enable_gzip = 1;
1041 #endif // NETDATA_WITH_ZLIB
1042
1043                 int datasource_type = DATASOURCE_DATATABLE_JSONP;
1044                 //if(strstr(w->response.data->buffer, "X-DataSource-Auth"))
1045                 //      datasource_type = DATASOURCE_GOOGLE_JSON;
1046
1047                 char *buf = (char *)buffer_tostring(w->response.data);
1048                 char *tok = strsep(&buf, " \r\n");
1049                 char *url = NULL;
1050                 char *pointer_to_free = NULL; // keep url_decode() allocated buffer
1051
1052                 w->mode = WEB_CLIENT_MODE_NORMAL;
1053
1054                 if(buf && strcmp(tok, "GET") == 0) {
1055                         tok = strsep(&buf, " \r\n");
1056                         pointer_to_free = url = url_decode(tok);
1057                         debug(D_WEB_CLIENT, "%llu: Processing HTTP GET on url '%s'.", w->id, url);
1058                 }
1059                 else if(buf && strcmp(tok, "OPTIONS") == 0) {
1060                         tok = strsep(&buf, " \r\n");
1061                         pointer_to_free = url = url_decode(tok);
1062                         debug(D_WEB_CLIENT, "%llu: Processing HTTP OPTIONS on url '%s'.", w->id, url);
1063                         w->mode = WEB_CLIENT_MODE_OPTIONS;
1064                 }
1065                 else if (buf && strcmp(tok, "POST") == 0) {
1066                         w->keepalive = 0;
1067                         tok = strsep(&buf, " \r\n");
1068                         pointer_to_free = url = url_decode(tok);
1069                         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);
1070                 }
1071
1072                 w->last_url[0] = '\0';
1073
1074                 if(w->mode == WEB_CLIENT_MODE_OPTIONS) {
1075                         strncpy(w->last_url, url, URL_MAX);
1076                         w->last_url[URL_MAX] = '\0';
1077
1078                         code = 200;
1079                         w->response.data->contenttype = CT_TEXT_PLAIN;
1080                         buffer_flush(w->response.data);
1081                         buffer_strcat(w->response.data, "OK");
1082                 }
1083                 else if(url) {
1084 #ifdef NETDATA_WITH_ZLIB
1085                         if(enable_gzip)
1086                                 web_client_enable_deflate(w);
1087 #endif
1088
1089                         strncpy(w->last_url, url, URL_MAX);
1090                         w->last_url[URL_MAX] = '\0';
1091
1092                         tok = mystrsep(&url, "/?");
1093
1094                         debug(D_WEB_CLIENT, "%llu: Processing command '%s'.", w->id, tok);
1095
1096                         if(strcmp(tok, "api") == 0) {
1097                                 // the client is requesting api access
1098                                 datasource_type = DATASOURCE_JSON;
1099                                 code = web_client_api_request(w, url);
1100                         }
1101 #ifdef NETDATA_INTERNAL_CHECKS
1102                         else if(strcmp(tok, "exit") == 0) {
1103                                 netdata_exit = 1;
1104                                 code = 200;
1105                                 w->response.data->contenttype = CT_TEXT_PLAIN;
1106                                 buffer_flush(w->response.data);
1107                                 buffer_strcat(w->response.data, "will do");
1108                         }
1109 #endif
1110                         else if(strcmp(tok, WEB_PATH_DATA) == 0) { // "data"
1111                                 // the client is requesting rrd data
1112                                 datasource_type = DATASOURCE_JSON;
1113                                 code = web_client_data_request(w, url, datasource_type);
1114                         }
1115                         else if(strcmp(tok, WEB_PATH_DATASOURCE) == 0) { // "datasource"
1116                                 // the client is requesting google datasource
1117                                 code = web_client_data_request(w, url, datasource_type);
1118                         }
1119                         else if(strcmp(tok, WEB_PATH_GRAPH) == 0) { // "graph"
1120                                 // the client is requesting an rrd graph
1121
1122                                 // get the name of the data to show
1123                                 tok = mystrsep(&url, "/?&");
1124                                 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1125
1126                                 // do we have such a data set?
1127                                 RRDSET *st = rrdset_find_byname(tok);
1128                                 if(!st) st = rrdset_find(tok);
1129                                 if(!st) {
1130                                         // we don't have it
1131                                         // try to send a file with that name
1132                                         buffer_flush(w->response.data);
1133                                         code = mysendfile(w, tok);
1134                                 }
1135                                 else {
1136                                         code = 200;
1137                                         debug(D_WEB_CLIENT_ACCESS, "%llu: Sending %s.json of RRD_STATS...", w->id, st->name);
1138                                         w->response.data->contenttype = CT_APPLICATION_JSON;
1139                                         buffer_flush(w->response.data);
1140                                         rrd_stats_graph_json(st, url, w->response.data);
1141                                 }
1142                         }
1143 #ifdef NETDATA_INTERNAL_CHECKS
1144                         else if(strcmp(tok, "debug") == 0) {
1145                                 buffer_flush(w->response.data);
1146
1147                                 // get the name of the data to show
1148                                 tok = mystrsep(&url, "/?&");
1149                                 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1150
1151                                 // do we have such a data set?
1152                                 RRDSET *st = rrdset_find_byname(tok);
1153                                 if(!st) st = rrdset_find(tok);
1154                                 if(!st) {
1155                                         code = 404;
1156                                         buffer_sprintf(w->response.data, "Chart %s is not found.\r\n", tok);
1157                                         debug(D_WEB_CLIENT_ACCESS, "%llu: %s is not found.", w->id, tok);
1158                                 }
1159                                 else {
1160                                         code = 200;
1161                                         debug_flags |= D_RRD_STATS;
1162                                         st->debug = st->debug?0:1;
1163                                         buffer_sprintf(w->response.data, "Chart %s has now debug %s.\r\n", tok, st->debug?"enabled":"disabled");
1164                                         debug(D_WEB_CLIENT_ACCESS, "%llu: debug for %s is %s.", w->id, tok, st->debug?"enabled":"disabled");
1165                                 }
1166                         }
1167                         else if(strcmp(tok, "mirror") == 0) {
1168                                 code = 200;
1169
1170                                 debug(D_WEB_CLIENT_ACCESS, "%llu: Mirroring...", w->id);
1171
1172                                 // replace the zero bytes with spaces
1173                                 buffer_char_replace(w->response.data, '\0', ' ');
1174
1175                                 // just leave the buffer as is
1176                                 // it will be copied back to the client
1177                         }
1178 #endif
1179                         else if(strcmp(tok, "list") == 0) {
1180                                 code = 200;
1181
1182                                 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending list of RRD_STATS...", w->id);
1183
1184                                 buffer_flush(w->response.data);
1185                                 RRDSET *st = rrdset_root;
1186
1187                                 for ( ; st ; st = st->next )
1188                                         buffer_sprintf(w->response.data, "%s\n", st->name);
1189                         }
1190                         else if(strcmp(tok, "all.json") == 0) {
1191                                 code = 200;
1192                                 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending JSON list of all monitors of RRD_STATS...", w->id);
1193
1194                                 w->response.data->contenttype = CT_APPLICATION_JSON;
1195                                 buffer_flush(w->response.data);
1196                                 rrd_stats_all_json(w->response.data);
1197                         }
1198                         else if(strcmp(tok, "netdata.conf") == 0) {
1199                                 code = 200;
1200                                 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending netdata.conf ...", w->id);
1201
1202                                 w->response.data->contenttype = CT_TEXT_PLAIN;
1203                                 buffer_flush(w->response.data);
1204                                 generate_config(w->response.data, 0);
1205                         }
1206                         else {
1207                                 char filename[FILENAME_MAX+1];
1208                                 url = filename;
1209                                 strncpy(filename, w->last_url, FILENAME_MAX);
1210                                 filename[FILENAME_MAX] = '\0';
1211                                 tok = mystrsep(&url, "?");
1212                                 buffer_flush(w->response.data);
1213                                 code = mysendfile(w, (tok && *tok)?tok:"/");
1214                         }
1215                 }
1216                 else {
1217                         strcpy(w->last_url, "not a valid response");
1218
1219                         if(buf) debug(D_WEB_CLIENT_ACCESS, "%llu: Cannot understand '%s'.", w->id, buf);
1220
1221                         code = 500;
1222                         buffer_flush(w->response.data);
1223                         buffer_strcat(w->response.data, "I don't understand you...\r\n");
1224                 }
1225
1226                 // free url_decode() buffer
1227                 if(pointer_to_free) free(pointer_to_free);
1228         }
1229         else if(w->response.data->len > TOO_BIG_REQUEST) {
1230                 strcpy(w->last_url, "too big request");
1231
1232                 debug(D_WEB_CLIENT_ACCESS, "%llu: Received request is too big (%zd bytes).", w->id, w->response.data->len);
1233
1234                 code = 400;
1235                 buffer_flush(w->response.data);
1236                 buffer_sprintf(w->response.data, "Received request is too big  (%zd bytes).\r\n", w->response.data->len);
1237         }
1238         else {
1239                 // wait for more data
1240                 w->wait_receive = 1;
1241                 return;
1242         }
1243
1244         gettimeofday(&w->tv_ready, NULL);
1245         w->response.data->date = time(NULL);
1246         w->response.sent = 0;
1247         w->response.code = code;
1248
1249         // prepare the HTTP response header
1250         debug(D_WEB_CLIENT, "%llu: Generating HTTP header with response %d.", w->id, code);
1251
1252         char *content_type_string;
1253         switch(w->response.data->contenttype) {
1254                 case CT_TEXT_HTML:
1255                         content_type_string = "text/html; charset=utf-8";
1256                         break;
1257
1258                 case CT_APPLICATION_XML:
1259                         content_type_string = "application/xml; charset=utf-8";
1260                         break;
1261
1262                 case CT_APPLICATION_JSON:
1263                         content_type_string = "application/json; charset=utf-8";
1264                         break;
1265
1266                 case CT_APPLICATION_X_JAVASCRIPT:
1267                         content_type_string = "application/x-javascript; charset=utf-8";
1268                         break;
1269
1270                 case CT_TEXT_CSS:
1271                         content_type_string = "text/css; charset=utf-8";
1272                         break;
1273
1274                 case CT_TEXT_XML:
1275                         content_type_string = "text/xml; charset=utf-8";
1276                         break;
1277
1278                 case CT_TEXT_XSL:
1279                         content_type_string = "text/xsl; charset=utf-8";
1280                         break;
1281
1282                 case CT_APPLICATION_OCTET_STREAM:
1283                         content_type_string = "application/octet-stream";
1284                         break;
1285
1286                 case CT_IMAGE_SVG_XML:
1287                         content_type_string = "image/svg+xml";
1288                         break;
1289
1290                 case CT_APPLICATION_X_FONT_TRUETYPE:
1291                         content_type_string = "application/x-font-truetype";
1292                         break;
1293
1294                 case CT_APPLICATION_X_FONT_OPENTYPE:
1295                         content_type_string = "application/x-font-opentype";
1296                         break;
1297
1298                 case CT_APPLICATION_FONT_WOFF:
1299                         content_type_string = "application/font-woff";
1300                         break;
1301
1302                 case CT_APPLICATION_FONT_WOFF2:
1303                         content_type_string = "application/font-woff2";
1304                         break;
1305
1306                 case CT_APPLICATION_VND_MS_FONTOBJ:
1307                         content_type_string = "application/vnd.ms-fontobject";
1308                         break;
1309
1310                 case CT_IMAGE_PNG:
1311                         content_type_string = "image/png";
1312                         break;
1313
1314                 case CT_IMAGE_JPG:
1315                         content_type_string = "image/jpeg";
1316                         break;
1317
1318                 case CT_IMAGE_GIF:
1319                         content_type_string = "image/gif";
1320                         break;
1321
1322                 case CT_IMAGE_XICON:
1323                         content_type_string = "image/x-icon";
1324                         break;
1325
1326                 case CT_IMAGE_BMP:
1327                         content_type_string = "image/bmp";
1328                         break;
1329
1330                 case CT_IMAGE_ICNS:
1331                         content_type_string = "image/icns";
1332                         break;
1333
1334                 default:
1335                 case CT_TEXT_PLAIN:
1336                         content_type_string = "text/plain; charset=utf-8";
1337                         break;
1338         }
1339
1340         char *code_msg;
1341         switch(code) {
1342                 case 200:
1343                         code_msg = "OK";
1344                         break;
1345
1346                 case 307:
1347                         code_msg = "Temporary Redirect";
1348                         break;
1349
1350                 case 400:
1351                         code_msg = "Bad Request";
1352                         break;
1353
1354                 case 403:
1355                         code_msg = "Forbidden";
1356                         break;
1357
1358                 case 404:
1359                         code_msg = "Not Found";
1360                         break;
1361
1362                 default:
1363                         code_msg = "Internal Server Error";
1364                         break;
1365         }
1366
1367         char date[100];
1368         struct tm tmbuf, *tm = gmtime_r(&w->response.data->date, &tmbuf);
1369         strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %Z", tm);
1370
1371         buffer_sprintf(w->response.header_output,
1372                 "HTTP/1.1 %d %s\r\n"
1373                 "Connection: %s\r\n"
1374                 "Server: NetData Embedded HTTP Server\r\n"
1375                 "Content-Type: %s\r\n"
1376                 "Access-Control-Allow-Origin: *\r\n"
1377                 "Access-Control-Allow-Methods: GET, OPTIONS\r\n"
1378                 "Access-Control-Allow-Headers: accept, x-requested-with\r\n"
1379                 "Access-Control-Max-Age: 86400\r\n"
1380                 "Date: %s\r\n"
1381                 , code, code_msg
1382                 , w->keepalive?"keep-alive":"close"
1383                 , content_type_string
1384                 , date
1385                 );
1386
1387         if(buffer_strlen(w->response.header))
1388                 buffer_strcat(w->response.header_output, buffer_tostring(w->response.header));
1389
1390         if(w->mode == WEB_CLIENT_MODE_NORMAL && (w->response.data->options & WB_CONTENT_NO_CACHEABLE)) {
1391                 buffer_sprintf(w->response.header_output,
1392                         "Expires: %s\r\n"
1393                         "Cache-Control: no-cache\r\n"
1394                         , date);
1395         }
1396         else {
1397                 char edate[100];
1398                 time_t et = w->response.data->date + (86400 * 14);
1399                 struct tm etmbuf, *etm = gmtime_r(&et, &etmbuf);
1400                 strftime(edate, sizeof(edate), "%a, %d %b %Y %H:%M:%S %Z", etm);
1401
1402                 buffer_sprintf(w->response.header_output,
1403                         "Expires: %s\r\n"
1404                         "Cache-Control: public\r\n"
1405                         , edate);
1406         }
1407
1408         // if we know the content length, put it
1409         if(!w->response.zoutput && (w->response.data->len || w->response.rlen))
1410                 buffer_sprintf(w->response.header_output,
1411                         "Content-Length: %ld\r\n"
1412                         , w->response.data->len? w->response.data->len: w->response.rlen
1413                         );
1414         else if(!w->response.zoutput)
1415                 w->keepalive = 0;       // content-length is required for keep-alive
1416
1417         if(w->response.zoutput) {
1418                 buffer_strcat(w->response.header_output,
1419                         "Content-Encoding: gzip\r\n"
1420                         "Transfer-Encoding: chunked\r\n"
1421                         );
1422         }
1423
1424         buffer_strcat(w->response.header_output, "\r\n");
1425
1426         // disable TCP_NODELAY, to buffer the header
1427         int flag = 0;
1428         if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0)
1429                 error("%llu: failed to disable TCP_NODELAY on socket.", w->id);
1430
1431         // sent the HTTP header
1432         debug(D_WEB_DATA, "%llu: Sending response HTTP header of size %d: '%s'"
1433                         , w->id
1434                         , buffer_strlen(w->response.header_output)
1435                         , buffer_tostring(w->response.header_output)
1436                         );
1437
1438         bytes = send(w->ofd, buffer_tostring(w->response.header_output), buffer_strlen(w->response.header_output), 0);
1439         if(bytes != (ssize_t) buffer_strlen(w->response.header_output))
1440                 error("%llu: HTTP Header failed to be sent (I sent %d bytes but the system sent %d bytes)."
1441                                 , w->id
1442                                 , buffer_strlen(w->response.header_output)
1443                                 , bytes);
1444         else {
1445                 global_statistics_lock();
1446                 global_statistics.bytes_sent += bytes;
1447                 global_statistics_unlock();
1448         }
1449
1450         // enable TCP_NODELAY, to send all data immediately at the next send()
1451         flag = 1;
1452         if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0) error("%llu: failed to enable TCP_NODELAY on socket.", w->id);
1453
1454         // enable sending immediately if we have data
1455         if(w->response.data->len) w->wait_send = 1;
1456         else w->wait_send = 0;
1457
1458         // pretty logging
1459         switch(w->mode) {
1460                 case WEB_CLIENT_MODE_OPTIONS:
1461                         debug(D_WEB_CLIENT, "%llu: Done preparing the OPTIONS response. Sending data (%d bytes) to client.", w->id, w->response.data->len);
1462                         break;
1463
1464                 case WEB_CLIENT_MODE_NORMAL:
1465                         debug(D_WEB_CLIENT, "%llu: Done preparing the response. Sending data (%d bytes) to client.", w->id, w->response.data->len);
1466                         break;
1467
1468                 case WEB_CLIENT_MODE_FILECOPY:
1469                         if(w->response.rlen) {
1470                                 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending data file of %d bytes to client.", w->id, w->response.rlen);
1471                                 w->wait_receive = 1;
1472
1473                                 /*
1474                                 // utilize the kernel sendfile() for copying the file to the socket.
1475                                 // this block of code can be commented, without anything missing.
1476                                 // when it is commented, the program will copy the data using async I/O.
1477                                 {
1478                                         long len = sendfile(w->ofd, w->ifd, NULL, w->response.data->rbytes);
1479                                         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);
1480                                         else web_client_reset(w);
1481                                 }
1482                                 */
1483                         }
1484                         else
1485                                 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending an unknown amount of bytes to client.", w->id);
1486                         break;
1487
1488                 default:
1489                         fatal("%llu: Unknown client mode %d.", w->id, w->mode);
1490                         break;
1491         }
1492 }
1493
1494 long web_client_send_chunk_header(struct web_client *w, long len)
1495 {
1496         debug(D_DEFLATE, "%llu: OPEN CHUNK of %d bytes (hex: %x).", w->id, len, len);
1497         char buf[1024];
1498         sprintf(buf, "%lX\r\n", len);
1499         ssize_t bytes = send(w->ofd, buf, strlen(buf), MSG_DONTWAIT);
1500
1501         if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk header %d bytes.", w->id, bytes);
1502         else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk header to the client.", w->id);
1503         else debug(D_DEFLATE, "%llu: Failed to send chunk header to client.", w->id);
1504
1505         return bytes;
1506 }
1507
1508 long web_client_send_chunk_close(struct web_client *w)
1509 {
1510         //debug(D_DEFLATE, "%llu: CLOSE CHUNK.", w->id);
1511
1512         ssize_t bytes = send(w->ofd, "\r\n", 2, MSG_DONTWAIT);
1513
1514         if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
1515         else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
1516         else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client.", w->id);
1517
1518         return bytes;
1519 }
1520
1521 long web_client_send_chunk_finalize(struct web_client *w)
1522 {
1523         //debug(D_DEFLATE, "%llu: FINALIZE CHUNK.", w->id);
1524
1525         ssize_t bytes = send(w->ofd, "\r\n0\r\n\r\n", 7, MSG_DONTWAIT);
1526
1527         if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
1528         else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
1529         else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client.", w->id);
1530
1531         return bytes;
1532 }
1533
1534 #ifdef NETDATA_WITH_ZLIB
1535 long web_client_send_deflate(struct web_client *w)
1536 {
1537         long len = 0, t = 0;
1538
1539         // when using compression,
1540         // w->response.sent is the amount of bytes passed through compression
1541
1542         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);
1543
1544         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) {
1545                 // there is nothing to send
1546
1547                 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1548
1549                 // finalize the chunk
1550                 if(w->response.sent != 0)
1551                         t += web_client_send_chunk_finalize(w);
1552
1553                 // there can be two cases for this
1554                 // A. we have done everything
1555                 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
1556
1557                 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->response.rlen && w->response.rlen > w->response.data->len) {
1558                         // we have to wait, more data will come
1559                         debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1560                         w->wait_send = 0;
1561                         return(0);
1562                 }
1563
1564                 if(w->keepalive == 0) {
1565                         debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->response.sent);
1566                         errno = 0;
1567                         return(-1);
1568                 }
1569
1570                 // reset the client
1571                 web_client_reset(w);
1572                 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1573                 return(0);
1574         }
1575
1576         if(w->response.zhave == w->response.zsent) {
1577                 // compress more input data
1578
1579                 // close the previous open chunk
1580                 if(w->response.sent != 0) t += web_client_send_chunk_close(w);
1581
1582                 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);
1583
1584                 // give the compressor all the data not passed through the compressor yet
1585                 if(w->response.data->len > w->response.sent) {
1586 #ifdef NETDATA_INTERNAL_CHECKS
1587                         if((long)w->response.sent - (long)w->response.zstream.avail_in < 0)
1588                                 error("internal error: avail_in is corrupted.");
1589 #endif
1590                         w->response.zstream.next_in = (Bytef *)&w->response.data->buffer[w->response.sent - w->response.zstream.avail_in];
1591                         w->response.zstream.avail_in += (uInt) (w->response.data->len - w->response.sent);
1592                 }
1593
1594                 // reset the compressor output buffer
1595                 w->response.zstream.next_out = w->response.zbuffer;
1596                 w->response.zstream.avail_out = ZLIB_CHUNK;
1597
1598                 // ask for FINISH if we have all the input
1599                 int flush = Z_SYNC_FLUSH;
1600                 if(w->mode == WEB_CLIENT_MODE_NORMAL
1601                         || (w->mode == WEB_CLIENT_MODE_FILECOPY && !w->wait_receive && w->response.data->len == w->response.rlen)) {
1602                         flush = Z_FINISH;
1603                         debug(D_DEFLATE, "%llu: Requesting Z_FINISH, if possible.", w->id);
1604                 }
1605                 else {
1606                         debug(D_DEFLATE, "%llu: Requesting Z_SYNC_FLUSH.", w->id);
1607                 }
1608
1609                 // compress
1610                 if(deflate(&w->response.zstream, flush) == Z_STREAM_ERROR) {
1611                         error("%llu: Compression failed. Closing down client.", w->id);
1612                         web_client_reset(w);
1613                         return(-1);
1614                 }
1615
1616                 w->response.zhave = ZLIB_CHUNK - w->response.zstream.avail_out;
1617                 w->response.zsent = 0;
1618
1619                 // keep track of the bytes passed through the compressor
1620                 w->response.sent = w->response.data->len;
1621
1622                 debug(D_DEFLATE, "%llu: Compression produced %d bytes.", w->id, w->response.zhave);
1623
1624                 // open a new chunk
1625                 t += web_client_send_chunk_header(w, w->response.zhave);
1626         }
1627         
1628         debug(D_WEB_CLIENT, "%llu: Sending %d bytes of data (+%d of chunk header).", w->id, w->response.zhave - w->response.zsent, t);
1629
1630         len = send(w->ofd, &w->response.zbuffer[w->response.zsent], (size_t) (w->response.zhave - w->response.zsent), MSG_DONTWAIT);
1631         if(len > 0) {
1632                 w->response.zsent += len;
1633                 if(t > 0) len += t;
1634                 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, len);
1635         }
1636         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);
1637         else debug(D_WEB_CLIENT, "%llu: Failed to send data to client. Reason: %s", w->id, strerror(errno));
1638
1639         return(len);
1640 }
1641 #endif // NETDATA_WITH_ZLIB
1642
1643 long web_client_send(struct web_client *w)
1644 {
1645 #ifdef NETDATA_WITH_ZLIB
1646         if(likely(w->response.zoutput)) return web_client_send_deflate(w);
1647 #endif // NETDATA_WITH_ZLIB
1648
1649         long bytes;
1650
1651         if(unlikely(w->response.data->len - w->response.sent == 0)) {
1652                 // there is nothing to send
1653
1654                 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1655
1656                 // there can be two cases for this
1657                 // A. we have done everything
1658                 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
1659
1660                 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->response.rlen && w->response.rlen > w->response.data->len) {
1661                         // we have to wait, more data will come
1662                         debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1663                         w->wait_send = 0;
1664                         return(0);
1665                 }
1666
1667                 if(unlikely(w->keepalive == 0)) {
1668                         debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->response.sent);
1669                         errno = 0;
1670                         return(-1);
1671                 }
1672
1673                 web_client_reset(w);
1674                 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1675                 return(0);
1676         }
1677
1678         bytes = send(w->ofd, &w->response.data->buffer[w->response.sent], w->response.data->len - w->response.sent, MSG_DONTWAIT);
1679         if(likely(bytes > 0)) {
1680                 w->response.sent += bytes;
1681                 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, bytes);
1682         }
1683         else if(likely(bytes == 0)) debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client.", w->id);
1684         else debug(D_WEB_CLIENT, "%llu: Failed to send data to client.", w->id);
1685
1686         return(bytes);
1687 }
1688
1689 long web_client_receive(struct web_client *w)
1690 {
1691         // do we have any space for more data?
1692         buffer_need_bytes(w->response.data, WEB_REQUEST_LENGTH);
1693
1694         long left = w->response.data->size - w->response.data->len;
1695         long bytes;
1696
1697         if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY))
1698                 bytes = read(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1));
1699         else
1700                 bytes = recv(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1), MSG_DONTWAIT);
1701
1702         if(likely(bytes > 0)) {
1703                 size_t old = w->response.data->len;
1704                 w->response.data->len += bytes;
1705                 w->response.data->buffer[w->response.data->len] = '\0';
1706
1707                 debug(D_WEB_CLIENT, "%llu: Received %d bytes.", w->id, bytes);
1708                 debug(D_WEB_DATA, "%llu: Received data: '%s'.", w->id, &w->response.data->buffer[old]);
1709
1710                 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1711                         w->wait_send = 1;
1712                         if(w->response.rlen && w->response.data->len >= w->response.rlen) w->wait_receive = 0;
1713                 }
1714         }
1715         else if(likely(bytes == 0)) {
1716                 debug(D_WEB_CLIENT, "%llu: Out of input data.", w->id);
1717
1718                 // if we cannot read, it means we have an error on input.
1719                 // if however, we are copying a file from ifd to ofd, we should not return an error.
1720                 // in this case, the error should be generated when the file has been sent to the client.
1721
1722                 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1723                         // we are copying data from ifd to ofd
1724                         // let it finish copying...
1725                         w->wait_receive = 0;
1726                         debug(D_WEB_CLIENT, "%llu: Disabling input.", w->id);
1727                 }
1728                 else {
1729                         bytes = -1;
1730                         errno = 0;
1731                 }
1732         }
1733
1734         return(bytes);
1735 }
1736
1737
1738 // --------------------------------------------------------------------------------------
1739 // the thread of a single client
1740
1741 // 1. waits for input and output, using async I/O
1742 // 2. it processes HTTP requests
1743 // 3. it generates HTTP responses
1744 // 4. it copies data from input to output if mode is FILECOPY
1745
1746 void *web_client_main(void *ptr)
1747 {
1748         if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
1749                 error("Cannot set pthread cancel type to DEFERRED.");
1750
1751         if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
1752                 error("Cannot set pthread cancel state to ENABLE.");
1753
1754         struct timeval tv;
1755         struct web_client *w = ptr;
1756         int retval;
1757         fd_set ifds, ofds, efds;
1758         int fdmax = 0;
1759
1760         log_access("%llu: %s port %s connected on thread task id %d", w->id, w->client_ip, w->client_port, gettid());
1761
1762         for(;;) {
1763                 FD_ZERO (&ifds);
1764                 FD_ZERO (&ofds);
1765                 FD_ZERO (&efds);
1766
1767                 FD_SET(w->ifd, &efds);
1768
1769                 if(w->ifd != w->ofd)
1770                         FD_SET(w->ofd, &efds);
1771
1772                 if (w->wait_receive) {
1773                         FD_SET(w->ifd, &ifds);
1774                         if(w->ifd > fdmax) fdmax = w->ifd;
1775                 }
1776
1777                 if (w->wait_send) {
1778                         FD_SET(w->ofd, &ofds);
1779                         if(w->ofd > fdmax) fdmax = w->ofd;
1780                 }
1781
1782                 tv.tv_sec = web_client_timeout;
1783                 tv.tv_usec = 0;
1784
1785                 debug(D_WEB_CLIENT, "%llu: Waiting socket async I/O for %s %s", w->id, w->wait_receive?"INPUT":"", w->wait_send?"OUTPUT":"");
1786                 retval = select(fdmax+1, &ifds, &ofds, &efds, &tv);
1787
1788                 if(retval == -1) {
1789                         debug(D_WEB_CLIENT_ACCESS, "%llu: LISTENER: select() failed.", w->id);
1790                         continue;
1791                 }
1792                 else if(!retval) {
1793                         // timeout
1794                         debug(D_WEB_CLIENT_ACCESS, "%llu: LISTENER: timeout.", w->id);
1795                         break;
1796                 }
1797
1798                 if(FD_ISSET(w->ifd, &efds)) {
1799                         debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on input socket.", w->id);
1800                         break;
1801                 }
1802
1803                 if(FD_ISSET(w->ofd, &efds)) {
1804                         debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on output socket.", w->id);
1805                         break;
1806                 }
1807
1808                 if(w->wait_send && FD_ISSET(w->ofd, &ofds)) {
1809                         long bytes;
1810                         if((bytes = web_client_send(w)) < 0) {
1811                                 debug(D_WEB_CLIENT, "%llu: Cannot send data to client. Closing client.", w->id);
1812                                 errno = 0;
1813                                 break;
1814                         }
1815
1816                         global_statistics_lock();
1817                         global_statistics.bytes_sent += bytes;
1818                         global_statistics_unlock();
1819                 }
1820
1821                 if(w->wait_receive && FD_ISSET(w->ifd, &ifds)) {
1822                         long bytes;
1823                         if((bytes = web_client_receive(w)) < 0) {
1824                                 debug(D_WEB_CLIENT, "%llu: Cannot receive data from client. Closing client.", w->id);
1825                                 errno = 0;
1826                                 break;
1827                         }
1828
1829                         if(w->mode == WEB_CLIENT_MODE_NORMAL) {
1830                                 debug(D_WEB_CLIENT, "%llu: Attempting to process received data (%ld bytes).", w->id, bytes);
1831                                 // info("%llu: Attempting to process received data (%ld bytes).", w->id, bytes);
1832                                 web_client_process(w);
1833                         }
1834
1835                         global_statistics_lock();
1836                         global_statistics.bytes_received += bytes;
1837                         global_statistics_unlock();
1838                 }
1839         }
1840
1841         log_access("%llu: %s port %s disconnected from thread task id %d", w->id, w->client_ip, w->client_port, gettid());
1842         debug(D_WEB_CLIENT, "%llu: done...", w->id);
1843
1844         web_client_reset(w);
1845         w->obsolete = 1;
1846
1847         return NULL;
1848 }