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