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