]> arthur.barton.de Git - netdata.git/blob - src/web_client.c
code cleanup
[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
17 #include "common.h"
18 #include "log.h"
19 #include "appconfig.h"
20 #include "url.h"
21 #include "web_buffer.h"
22 #include "web_server.h"
23 #include "global_statistics.h"
24 #include "rrd.h"
25 #include "rrd2json.h"
26
27 #include "web_client.h"
28
29 #define INITIAL_WEB_DATA_LENGTH 65536
30
31 int web_client_timeout = DEFAULT_DISCONNECT_IDLE_WEB_CLIENTS_AFTER_SECONDS;
32 int web_enable_gzip = 1;
33
34 struct web_client *web_clients = NULL;
35 unsigned long long web_clients_count = 0;
36
37 struct web_client *web_client_create(int listener)
38 {
39         struct web_client *w;
40         
41         w = calloc(1, sizeof(struct web_client));
42         if(!w) {
43                 error("Cannot allocate new web_client memory.");
44                 return NULL;
45         }
46
47         w->id = ++web_clients_count;
48         w->mode = WEB_CLIENT_MODE_NORMAL;
49
50         {
51                 struct sockaddr *sadr;
52                 socklen_t addrlen;
53
54                 sadr = (struct sockaddr*) &w->clientaddr;
55                 addrlen = sizeof(w->clientaddr);
56
57                 w->ifd = accept(listener, sadr, &addrlen);
58                 if (w->ifd == -1) {
59                         error("%llu: Cannot accept new incoming connection.", w->id);
60                         free(w);
61                         return NULL;
62                 }
63                 w->ofd = w->ifd;
64
65                 if(getnameinfo(sadr, addrlen, w->client_ip, NI_MAXHOST, w->client_port, NI_MAXSERV, NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
66                         error("Cannot getnameinfo() on received client connection.");
67                         strncpy(w->client_ip,   "UNKNOWN", NI_MAXHOST);
68                         strncpy(w->client_port, "UNKNOWN", NI_MAXSERV);
69                 }
70                 w->client_ip[NI_MAXHOST]   = '\0';
71                 w->client_port[NI_MAXSERV] = '\0';
72
73                 switch(sadr->sa_family) {
74
75                 case AF_INET:
76                         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);
77                         break;
78
79                 case AF_INET6:
80                         if(strncmp(w->client_ip, "::ffff:", 7) == 0) {
81                                 strcpy(w->client_ip, &w->client_ip[7]);
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                         }
84                         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);
85                         break;
86
87                 default:
88                         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);
89                         break;
90                 }
91
92                 int flag = 1;
93                 if(setsockopt(w->ifd, SOL_SOCKET, SO_KEEPALIVE, (char *) &flag, sizeof(int)) != 0) error("%llu: Cannot set SO_KEEPALIVE on socket.", w->id);
94         }
95
96         w->data = web_buffer_create(INITIAL_WEB_DATA_LENGTH);
97         if(unlikely(!w->data)) {
98                 // no need for error log - web_buffer_create already logged the error
99                 close(w->ifd);
100                 free(w);
101                 return NULL;
102         }
103
104         w->wait_receive = 1;
105
106         if(web_clients) web_clients->prev = w;
107         w->next = web_clients;
108         web_clients = w;
109
110         global_statistics.connected_clients++;
111
112         return(w);
113 }
114
115 struct web_client *web_client_free(struct web_client *w)
116 {
117         struct web_client *n = w->next;
118
119         debug(D_WEB_CLIENT_ACCESS, "%llu: Closing web client from %s port %s.", w->id, w->client_ip, w->client_port);
120
121         if(w->prev)     w->prev->next = w->next;
122         if(w->next) w->next->prev = w->prev;
123
124         if(w == web_clients) web_clients = w->next;
125
126         if(w->data) web_buffer_free(w->data);
127         close(w->ifd);
128         if(w->ofd != w->ifd) close(w->ofd);
129         free(w);
130
131         global_statistics.connected_clients--;
132
133         return(n);
134 }
135
136 int mysendfile(struct web_client *w, char *filename)
137 {
138         static char *web_dir = NULL;
139         if(!web_dir) web_dir = config_get("global", "web files directory", WEB_DIR);
140
141         debug(D_WEB_CLIENT, "%llu: Looking for file '%s'...", w->id, filename);
142
143         // skip leading slashes
144         while (*filename == '/') filename++;
145
146         // if the filename contain known paths, skip them
147                  if(strncmp(filename, WEB_PATH_DATA       "/", strlen(WEB_PATH_DATA)       + 1) == 0) filename = &filename[strlen(WEB_PATH_DATA)       + 1];
148         else if(strncmp(filename, WEB_PATH_DATASOURCE "/", strlen(WEB_PATH_DATASOURCE) + 1) == 0) filename = &filename[strlen(WEB_PATH_DATASOURCE) + 1];
149         else if(strncmp(filename, WEB_PATH_GRAPH      "/", strlen(WEB_PATH_GRAPH)      + 1) == 0) filename = &filename[strlen(WEB_PATH_GRAPH)      + 1];
150         else if(strncmp(filename, WEB_PATH_FILE       "/", strlen(WEB_PATH_FILE)       + 1) == 0) filename = &filename[strlen(WEB_PATH_FILE)       + 1];
151
152         // if the filename contains a / or a .., refuse to serve it
153         if(strchr(filename, '/') != 0 || strstr(filename, "..") != 0) {
154                 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
155                 web_buffer_snprintf(w->data, FILENAME_MAX + 1024, "File '%s' cannot be served. Filenames cannot contain / or ..", filename);
156                 return 400;
157         }
158
159         // access the file
160         char webfilename[FILENAME_MAX + 1];
161         snprintf(webfilename, FILENAME_MAX, "%s/%s", web_dir, filename);
162
163         // check if the file exists
164         struct stat stat;
165         if(lstat(webfilename, &stat) != 0) {
166                 error("%llu: File '%s' is not found.", w->id, webfilename);
167                 web_buffer_snprintf(w->data, FILENAME_MAX + 1024, "File '%s' does not exist, or is not accessible.", filename);
168                 return 404;
169         }
170
171         // check if the file is owned by us
172         if(stat.st_uid != getuid() && stat.st_uid != geteuid()) {
173                 error("%llu: File '%s' is owned by user %d (I run as user %d). Access Denied.", w->id, webfilename, stat.st_uid, getuid());
174                 web_buffer_snprintf(w->data, FILENAME_MAX + 1024, "Access to file '%s' is not permitted.", filename);
175                 return 403;
176         }
177
178         // open the file
179         w->ifd = open(webfilename, O_NONBLOCK, O_RDONLY);
180         if(w->ifd == -1) {
181                 w->ifd = w->ofd;
182
183                 if(errno == EBUSY || errno == EAGAIN) {
184                         error("%llu: File '%s' is busy, sending 307 Moved Temporarily to force retry.", w->id, webfilename);
185                         snprintf(w->response_header, MAX_HTTP_HEADER_SIZE, "Location: /" WEB_PATH_FILE "/%s\r\n", filename);
186                         web_buffer_snprintf(w->data, FILENAME_MAX + 1024, "The file '%s' is currently busy. Please try again later.", filename);
187                         return 307;
188                 }
189                 else {
190                         error("%llu: Cannot open file '%s'.", w->id, webfilename);
191                         web_buffer_snprintf(w->data, FILENAME_MAX + 1024, "Cannot open file '%s'.", filename);
192                         return 404;
193                 }
194         }
195
196         // pick a Content-Type for the file
197                  if(strstr(filename, ".html") != NULL)  w->data->contenttype = CT_TEXT_HTML;
198         else if(strstr(filename, ".js")   != NULL)      w->data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
199         else if(strstr(filename, ".css")  != NULL)      w->data->contenttype = CT_TEXT_CSS;
200         else if(strstr(filename, ".xml")  != NULL)      w->data->contenttype = CT_TEXT_XML;
201         else if(strstr(filename, ".xsl")  != NULL)      w->data->contenttype = CT_TEXT_XSL;
202         else if(strstr(filename, ".txt")  != NULL)  w->data->contenttype = CT_TEXT_PLAIN;
203         else if(strstr(filename, ".svg")  != NULL)  w->data->contenttype = CT_IMAGE_SVG_XML;
204         else if(strstr(filename, ".ttf")  != NULL)  w->data->contenttype = CT_APPLICATION_X_FONT_TRUETYPE;
205         else if(strstr(filename, ".otf")  != NULL)  w->data->contenttype = CT_APPLICATION_X_FONT_OPENTYPE;
206         else if(strstr(filename, ".woff") != NULL)  w->data->contenttype = CT_APPLICATION_FONT_WOFF;
207         else if(strstr(filename, ".eot")  != NULL)  w->data->contenttype = CT_APPLICATION_VND_MS_FONTOBJ;
208         else w->data->contenttype = CT_APPLICATION_OCTET_STREAM;
209
210         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);
211
212         w->mode = WEB_CLIENT_MODE_FILECOPY;
213         w->wait_receive = 1;
214         w->wait_send = 0;
215         web_buffer_flush(w->data);
216         w->data->rlen = stat.st_size;
217         w->data->date = stat.st_mtim.tv_sec;
218
219         return 200;
220 }
221
222 void web_client_reset(struct web_client *w)
223 {
224         struct timeval tv;
225         gettimeofday(&tv, NULL);
226
227         long sent = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->data->rlen:w->data->len;
228
229 #ifdef NETDATA_WITH_ZLIB
230         if(likely(w->zoutput)) sent = (long)w->zstream.total_out;
231 #endif
232
233         long size = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->data->rlen:w->data->len;
234
235         if(likely(w->last_url[0]))
236                 log_access("%llu: (sent/all = %ld/%ld bytes %0.0f%%, prep/sent/total = %0.2f/%0.2f/%0.2f ms) %s: '%s'",
237                         w->id,
238                         sent, size, -((size>0)?((float)(size-sent)/(float)size * 100.0):0.0),
239                         (float)usecdiff(&w->tv_ready, &w->tv_in) / 1000.0,
240                         (float)usecdiff(&tv, &w->tv_ready) / 1000.0,
241                         (float)usecdiff(&tv, &w->tv_in) / 1000.0,
242                         (w->mode == WEB_CLIENT_MODE_FILECOPY)?"filecopy":"data",
243                                         w->last_url
244                 );
245
246         debug(D_WEB_CLIENT, "%llu: Reseting client.", w->id);
247
248         if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY)) {
249                 debug(D_WEB_CLIENT, "%llu: Closing filecopy input file.", w->id);
250                 close(w->ifd);
251                 w->ifd = w->ofd;
252         }
253
254         w->last_url[0] = '\0';
255
256         w->mode = WEB_CLIENT_MODE_NORMAL;
257
258         w->response_header[0] = '\0';
259
260         web_buffer_reset(w->data);
261
262         w->wait_receive = 1;
263         w->wait_send = 0;
264
265         w->zoutput = 0;
266
267         // if we had enabled compression, release it
268 #ifdef NETDATA_WITH_ZLIB
269         if(w->zinitialized) {
270                 debug(D_DEFLATE, "%llu: Reseting compression.", w->id);
271                 deflateEnd(&w->zstream);
272                 w->zsent = 0;
273                 w->zhave = 0;
274                 w->zstream.avail_in = 0;
275                 w->zstream.avail_out = 0;
276                 w->zstream.total_in = 0;
277                 w->zstream.total_out = 0;
278                 w->zinitialized = 0;
279         }
280 #endif // NETDATA_WITH_ZLIB
281 }
282
283 #ifdef NETDATA_WITH_ZLIB
284 void web_client_enable_deflate(struct web_client *w) {
285         if(w->zinitialized == 1) {
286                 error("%llu: Compression has already be initialized for this client.", w->id);
287                 return;
288         }
289
290         if(w->data->sent) {
291                 error("%llu: Cannot enable compression in the middle of a conversation.", w->id);
292                 return;
293         }
294
295         w->zstream.zalloc = Z_NULL;
296         w->zstream.zfree = Z_NULL;
297         w->zstream.opaque = Z_NULL;
298
299         w->zstream.next_in = (Bytef *)w->data->buffer;
300         w->zstream.avail_in = 0;
301         w->zstream.total_in = 0;
302
303         w->zstream.next_out = w->zbuffer;
304         w->zstream.avail_out = 0;
305         w->zstream.total_out = 0;
306
307         w->zstream.zalloc = Z_NULL;
308         w->zstream.zfree = Z_NULL;
309         w->zstream.opaque = Z_NULL;
310
311 //      if(deflateInit(&w->zstream, Z_DEFAULT_COMPRESSION) != Z_OK) {
312 //              error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
313 //              return;
314 //      }
315
316         // Select GZIP compression: windowbits = 15 + 16 = 31
317         if(deflateInit2(&w->zstream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY) != Z_OK) {
318                 error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
319                 return;
320         }
321
322         w->zsent = 0;
323         w->zoutput = 1;
324         w->zinitialized = 1;
325
326         debug(D_DEFLATE, "%llu: Initialized compression.", w->id);
327 }
328 #endif // NETDATA_WITH_ZLIB
329
330 int web_client_data_request(struct web_client *w, char *url, int datasource_type)
331 {
332         char *args = strchr(url, '?');
333         if(args) {
334                 *args='\0';
335                 args = &args[1];
336         }
337
338         // get the name of the data to show
339         char *tok = mystrsep(&url, "/");
340         debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
341
342         // do we have such a data set?
343         RRDSET *st = rrdset_find_byname(tok);
344         if(!st) st = rrdset_find(tok);
345         if(!st) {
346                 // we don't have it
347                 // try to send a file with that name
348                 web_buffer_flush(w->data);
349                 return(mysendfile(w, tok));
350         }
351
352         // we have it
353         debug(D_WEB_CLIENT, "%llu: Found RRD data with name '%s'.", w->id, tok);
354
355         // how many entries does the client want?
356         long lines = rrd_default_history_entries;
357         long group_count = 1;
358         time_t after = 0, before = 0;
359         int group_method = GROUP_AVERAGE;
360         int nonzero = 0;
361
362         if(url) {
363                 // parse the lines required
364                 tok = mystrsep(&url, "/");
365                 if(tok) lines = atoi(tok);
366                 if(lines < 1) lines = 1;
367         }
368         if(url) {
369                 // parse the group count required
370                 tok = mystrsep(&url, "/");
371                 if(tok) group_count = atoi(tok);
372                 if(group_count < 1) group_count = 1;
373                 //if(group_count > save_history / 20) group_count = save_history / 20;
374         }
375         if(url) {
376                 // parse the grouping method required
377                 tok = mystrsep(&url, "/");
378                 if(strcmp(tok, "max") == 0) group_method = GROUP_MAX;
379                 else if(strcmp(tok, "average") == 0) group_method = GROUP_AVERAGE;
380                 else if(strcmp(tok, "sum") == 0) group_method = GROUP_SUM;
381                 else debug(D_WEB_CLIENT, "%llu: Unknown group method '%s'", w->id, tok);
382         }
383         if(url) {
384                 // parse after time
385                 tok = mystrsep(&url, "/");
386                 if(tok) after = strtoul(tok, NULL, 10);
387                 if(after < 0) after = 0;
388         }
389         if(url) {
390                 // parse before time
391                 tok = mystrsep(&url, "/");
392                 if(tok) before = strtoul(tok, NULL, 10);
393                 if(before < 0) before = 0;
394         }
395         if(url) {
396                 // parse nonzero
397                 tok = mystrsep(&url, "/");
398                 if(tok && strcmp(tok, "nonzero") == 0) nonzero = 1;
399         }
400
401         w->data->contenttype = CT_APPLICATION_JSON;
402         web_buffer_flush(w->data);
403
404         char *google_version = "0.6";
405         char *google_reqId = "0";
406         char *google_sig = "0";
407         char *google_out = "json";
408         char *google_responseHandler = "google.visualization.Query.setResponse";
409         char *google_outFileName = NULL;
410         unsigned long last_timestamp_in_data = 0;
411         if(datasource_type == DATASOURCE_GOOGLE_JSON || datasource_type == DATASOURCE_GOOGLE_JSONP) {
412
413                 w->data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
414
415                 while(args) {
416                         tok = mystrsep(&args, "&");
417                         if(tok) {
418                                 char *name = mystrsep(&tok, "=");
419                                 if(name && strcmp(name, "tqx") == 0) {
420                                         char *key = mystrsep(&tok, ":");
421                                         char *value = mystrsep(&tok, ";");
422                                         if(key && value && *key && *value) {
423                                                 if(strcmp(key, "version") == 0)
424                                                         google_version = value;
425
426                                                 else if(strcmp(key, "reqId") == 0)
427                                                         google_reqId = value;
428
429                                                 else if(strcmp(key, "sig") == 0)
430                                                         google_sig = value;
431
432                                                 else if(strcmp(key, "out") == 0)
433                                                         google_out = value;
434
435                                                 else if(strcmp(key, "responseHandler") == 0)
436                                                         google_responseHandler = value;
437
438                                                 else if(strcmp(key, "outFileName") == 0)
439                                                         google_outFileName = value;
440                                         }
441                                 }
442                         }
443                 }
444
445                 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
446                         w->id, google_version, google_reqId, google_sig, google_out, google_responseHandler, google_outFileName
447                         );
448
449                 if(datasource_type == DATASOURCE_GOOGLE_JSONP) {
450                         last_timestamp_in_data = strtoul(google_sig, NULL, 0);
451
452                         // check the client wants json
453                         if(strcmp(google_out, "json") != 0) {
454                                 web_buffer_snprintf(w->data, 65536,
455                                         "%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.'}]});",
456                                         google_responseHandler, google_version, google_reqId, google_out);
457                                         return 200;
458                         }
459                 }
460         }
461
462         if(datasource_type == DATASOURCE_GOOGLE_JSONP) {
463                 web_buffer_snprintf(w->data, 65536,
464                         "%s({version:'%s',reqId:'%s',status:'ok',sig:'%lu',table:",
465                         google_responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
466         }
467
468         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);
469         unsigned long timestamp_in_data = rrd_stats_json(datasource_type, st, w->data, lines, group_count, group_method, after, before, nonzero);
470
471         if(datasource_type == DATASOURCE_GOOGLE_JSONP) {
472                 if(timestamp_in_data > last_timestamp_in_data)
473                         web_buffer_strcat(w->data, "});");
474
475                 else {
476                         // the client already has the latest data
477                         web_buffer_snprintf(w->data, 65536,
478                                 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
479                                 google_responseHandler, google_version, google_reqId);
480                 }
481         }
482
483         return 200;
484 }
485
486 /*
487 int web_client_parse_request(struct web_client *w) {
488         // protocol
489         // hostname
490         // path
491         // query string name-value
492         // http version
493         // method
494         // http request headers name-value
495
496         web_client_clean_request(w);
497
498         debug(D_WEB_DATA, "%llu: Processing data buffer of %d bytes: '%s'.", w->id, w->data->bytes, w->data->buffer);
499
500         char *buf = w->data->buffer;
501         char *line, *tok;
502
503         // ------------------------------------------------------------------------
504         // the first line
505
506         if(buf && (line = strsep(&buf, "\r\n"))) {
507                 // method
508                 if(line && (tok = strsep(&line, " "))) {
509                         w->request.protocol = strdup(tok);
510                 }
511                 else goto cleanup;
512
513                 // url
514         }
515         else goto cleanup;
516
517         // ------------------------------------------------------------------------
518         // the rest of the lines
519
520         while(buf && (line = strsep(&buf, "\r\n"))) {
521                 while(line && (tok = strsep(&line, ": "))) {
522                 }
523         }
524
525         char *url = NULL;
526
527
528 cleanup:
529         web_client_clean_request(w);
530         return 0;
531 }
532 */
533
534 void web_client_process(struct web_client *w) {
535         int code = 500;
536         int bytes;
537
538         w->wait_receive = 0;
539
540         // check if we have an empty line (end of HTTP header)
541         if(strstr(w->data->buffer, "\r\n\r\n")) {
542                 global_statistics_lock();
543                 global_statistics.web_requests++;
544                 global_statistics_unlock();
545
546                 gettimeofday(&w->tv_in, NULL);
547                 debug(D_WEB_DATA, "%llu: Processing data buffer of %d bytes: '%s'.", w->id, w->data->len, w->data->buffer);
548
549                 // check if the client requested keep-alive HTTP
550                 if(strcasestr(w->data->buffer, "Connection: keep-alive")) w->keepalive = 1;
551                 else w->keepalive = 0;
552
553 #ifdef NETDATA_WITH_ZLIB
554                 // check if the client accepts deflate
555                 if(web_enable_gzip && strstr(w->data->buffer, "gzip"))
556                         web_client_enable_deflate(w);
557 #endif // NETDATA_WITH_ZLIB
558
559                 int datasource_type = DATASOURCE_GOOGLE_JSONP;
560                 //if(strstr(w->data->buffer, "X-DataSource-Auth"))
561                 //      datasource_type = DATASOURCE_GOOGLE_JSON;
562
563                 char *buf = w->data->buffer;
564                 char *tok = strsep(&buf, " \r\n");
565                 char *url = NULL;
566                 char *pointer_to_free = NULL; // keep url_decode() allocated buffer
567
568                 if(buf && strcmp(tok, "GET") == 0) {
569                         tok = strsep(&buf, " \r\n");
570                         pointer_to_free = url = url_decode(tok);
571                         debug(D_WEB_CLIENT, "%llu: Processing HTTP GET on url '%s'.", w->id, url);
572                 }
573                 else if (buf && strcmp(tok, "POST") == 0) {
574                         w->keepalive = 0;
575                         tok = strsep(&buf, " \r\n");
576                         pointer_to_free = url = url_decode(tok);
577
578                         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);
579                 }
580
581                 w->last_url[0] = '\0';
582                 if(url) {
583                         strncpy(w->last_url, url, URL_MAX);
584                         w->last_url[URL_MAX] = '\0';
585
586                         tok = mystrsep(&url, "/?&");
587
588                         debug(D_WEB_CLIENT, "%llu: Processing command '%s'.", w->id, tok);
589
590                         if(strcmp(tok, WEB_PATH_DATA) == 0) { // "data"
591                                 // the client is requesting rrd data
592                                 datasource_type = DATASOURCE_JSON;
593                                 code = web_client_data_request(w, url, datasource_type);
594                         }
595                         else if(strcmp(tok, WEB_PATH_DATASOURCE) == 0) { // "datasource"
596                                 // the client is requesting google datasource
597                                 code = web_client_data_request(w, url, datasource_type);
598                         }
599                         else if(strcmp(tok, WEB_PATH_GRAPH) == 0) { // "graph"
600                                 // the client is requesting an rrd graph
601
602                                 // get the name of the data to show
603                                 tok = mystrsep(&url, "/?&");
604                                 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
605
606                                 // do we have such a data set?
607                                 RRDSET *st = rrdset_find_byname(tok);
608                                 if(!st) st = rrdset_find(tok);
609                                 if(!st) {
610                                         // we don't have it
611                                         // try to send a file with that name
612                                         web_buffer_flush(w->data);
613                                         code = mysendfile(w, tok);
614                                 }
615                                 else {
616                                         code = 200;
617                                         debug(D_WEB_CLIENT_ACCESS, "%llu: Sending %s.json of RRD_STATS...", w->id, st->name);
618                                         w->data->contenttype = CT_APPLICATION_JSON;
619                                         web_buffer_flush(w->data);
620                                         rrd_stats_graph_json(st, url, w->data);
621                                 }
622                         }
623                         else if(strcmp(tok, "debug") == 0) {
624                                 web_buffer_flush(w->data);
625
626                                 // get the name of the data to show
627                                 tok = mystrsep(&url, "/?&");
628                                 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
629
630                                 // do we have such a data set?
631                                 RRDSET *st = rrdset_find_byname(tok);
632                                 if(!st) st = rrdset_find(tok);
633                                 if(!st) {
634                                         code = 404;
635                                         web_buffer_snprintf(w->data, 1024, "Chart %s is not found.\r\n", tok);
636                                         debug(D_WEB_CLIENT_ACCESS, "%llu: %s is not found.", w->id, tok);
637                                 }
638                                 else {
639                                         code = 200;
640                                         debug_flags |= D_RRD_STATS;
641                                         st->debug = st->debug?0:1;
642                                         web_buffer_snprintf(w->data, 1024, "Chart %s has now debug %s.\r\n", tok, st->debug?"enabled":"disabled");
643                                         debug(D_WEB_CLIENT_ACCESS, "%llu: debug for %s is %s.", w->id, tok, st->debug?"enabled":"disabled");
644                                 }
645                         }
646                         else if(strcmp(tok, "mirror") == 0) {
647                                 code = 200;
648
649                                 debug(D_WEB_CLIENT_ACCESS, "%llu: Mirroring...", w->id);
650
651                                 // replace the zero bytes with spaces
652                                 web_buffer_char_replace(w->data, '\0', ' ');
653
654                                 // just leave the buffer as is
655                                 // it will be copied back to the client
656                         }
657                         else if(strcmp(tok, "list") == 0) {
658                                 code = 200;
659
660                                 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending list of RRD_STATS...", w->id);
661
662                                 web_buffer_flush(w->data);
663                                 RRDSET *st = rrdset_root;
664
665                                 for ( ; st ; st = st->next )
666                                         web_buffer_snprintf(w->data, 1024, "%s\n", st->name);
667                         }
668                         else if(strcmp(tok, "all.json") == 0) {
669                                 code = 200;
670                                 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending JSON list of all monitors of RRD_STATS...", w->id);
671
672                                 w->data->contenttype = CT_APPLICATION_JSON;
673                                 web_buffer_flush(w->data);
674                                 rrd_stats_all_json(w->data);
675                         }
676                         else if(strcmp(tok, "netdata.conf") == 0) {
677                                 code = 200;
678                                 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending netdata.conf ...", w->id);
679
680                                 w->data->contenttype = CT_TEXT_PLAIN;
681                                 web_buffer_flush(w->data);
682                                 generate_config(w->data, 0);
683                         }
684                         else if(strcmp(tok, WEB_PATH_FILE) == 0) { // "file"
685                                 tok = mystrsep(&url, "/?&");
686                                 if(tok && *tok) code = mysendfile(w, tok);
687                                 else {
688                                         code = 400;
689                                         web_buffer_flush(w->data);
690                                         web_buffer_strcat(w->data, "You have to give a filename to get.\r\n");
691                                 }
692                         }
693                         else if(!tok[0]) {
694                                 web_buffer_flush(w->data);
695                                 code = mysendfile(w, "index.html");
696                         }
697                         else {
698                                 web_buffer_flush(w->data);
699                                 code = mysendfile(w, tok);
700                         }
701
702                 }
703                 else {
704                         strcpy(w->last_url, "not a valid response");
705
706                         if(buf) debug(D_WEB_CLIENT_ACCESS, "%llu: Cannot understand '%s'.", w->id, buf);
707
708                         code = 500;
709                         web_buffer_flush(w->data);
710                         web_buffer_strcat(w->data, "I don't understand you...\r\n");
711                 }
712
713                 // free url_decode() buffer
714                 if(pointer_to_free) free(pointer_to_free);
715         }
716         else if(w->data->len > 8192) {
717                 strcpy(w->last_url, "too big request");
718
719                 debug(D_WEB_CLIENT_ACCESS, "%llu: Received request is too big.", w->id);
720
721                 code = 400;
722                 web_buffer_flush(w->data);
723                 web_buffer_strcat(w->data, "Received request is too big.\r\n");
724         }
725         else {
726                 // wait for more data
727                 w->wait_receive = 1;
728                 return;
729         }
730
731         if(w->data->len > w->data->size) {
732                 error("%llu: memory overflow encountered (size is %ld, written %ld).", w->data->size, w->data->len);
733         }
734
735         gettimeofday(&w->tv_ready, NULL);
736         w->data->date = time(NULL);
737         w->data->sent = 0;
738
739         // prepare the HTTP response header
740         debug(D_WEB_CLIENT, "%llu: Generating HTTP header with response %d.", w->id, code);
741
742         char *content_type_string = "";
743         switch(w->data->contenttype) {
744                 case CT_TEXT_HTML:
745                         content_type_string = "text/html; charset=utf-8";
746                         break;
747
748                 case CT_APPLICATION_XML:
749                         content_type_string = "application/xml; charset=utf-8";
750                         break;
751
752                 case CT_APPLICATION_JSON:
753                         content_type_string = "application/json; charset=utf-8";
754                         break;
755
756                 case CT_APPLICATION_X_JAVASCRIPT:
757                         content_type_string = "application/x-javascript; charset=utf-8";
758                         break;
759
760                 case CT_TEXT_CSS:
761                         content_type_string = "text/css; charset=utf-8";
762                         break;
763
764                 case CT_TEXT_XML:
765                         content_type_string = "text/xml; charset=utf-8";
766                         break;
767
768                 case CT_TEXT_XSL:
769                         content_type_string = "text/xsl; charset=utf-8";
770                         break;
771
772                 case CT_APPLICATION_OCTET_STREAM:
773                         content_type_string = "application/octet-stream";
774                         break;
775
776                 case CT_IMAGE_SVG_XML:
777                         content_type_string = "image/svg+xml";
778                         break;
779
780                 case CT_APPLICATION_X_FONT_TRUETYPE:
781                         content_type_string = "application/x-font-truetype";
782                         break;
783
784                 case CT_APPLICATION_X_FONT_OPENTYPE:
785                         content_type_string = "application/x-font-opentype";
786                         break;
787
788                 case CT_APPLICATION_FONT_WOFF:
789                         content_type_string = "application/font-woff";
790                         break;
791
792                 case CT_APPLICATION_VND_MS_FONTOBJ:
793                         content_type_string = "application/vnd.ms-fontobject";
794                         break;
795
796                 default:
797                 case CT_TEXT_PLAIN:
798                         content_type_string = "text/plain; charset=utf-8";
799                         break;
800         }
801
802         char *code_msg = "";
803         switch(code) {
804                 case 200:
805                         code_msg = "OK";
806                         break;
807
808                 case 307:
809                         code_msg = "Temporary Redirect";
810                         break;
811
812                 case 400:
813                         code_msg = "Bad Request";
814                         break;
815
816                 case 403:
817                         code_msg = "Forbidden";
818                         break;
819
820                 case 404:
821                         code_msg = "Not Found";
822                         break;
823
824                 default:
825                         code_msg = "Internal Server Error";
826                         break;
827         }
828
829         char date[100];
830         struct tm tm = *gmtime(&w->data->date);
831         strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %Z", &tm);
832
833         char custom_header[MAX_HTTP_HEADER_SIZE + 1] = "";
834         if(w->response_header[0])
835                 strcpy(custom_header, w->response_header);
836
837         int headerlen = 0;
838         headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen,
839                 "HTTP/1.1 %d %s\r\n"
840                 "Connection: %s\r\n"
841                 "Server: NetData Embedded HTTP Server\r\n"
842                 "Content-Type: %s\r\n"
843                 "Access-Control-Allow-Origin: *\r\n"
844                 "Date: %s\r\n"
845                 , code, code_msg
846                 , w->keepalive?"keep-alive":"close"
847                 , content_type_string
848                 , date
849                 );
850
851         if(custom_header[0])
852                 headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen, "%s", custom_header);
853
854         if(w->mode == WEB_CLIENT_MODE_NORMAL) {
855                 headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen,
856                         "Expires: %s\r\n"
857                         "Cache-Control: no-cache\r\n"
858                         , date
859                         );
860         }
861         else {
862                 headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen,
863                         "Cache-Control: public\r\n"
864                         );
865         }
866
867         // if we know the content length, put it
868         if(!w->zoutput && (w->data->len || w->data->rlen))
869                 headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen,
870                         "Content-Length: %ld\r\n"
871                         , w->data->len?w->data->len:w->data->rlen
872                         );
873         else if(!w->zoutput)
874                 w->keepalive = 0;       // content-length is required for keep-alive
875
876         if(w->zoutput) {
877                 headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen,
878                         "Content-Encoding: gzip\r\n"
879                         "Transfer-Encoding: chunked\r\n"
880                         );
881         }
882
883         headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen, "\r\n");
884
885         // disable TCP_NODELAY, to buffer the header
886         int flag = 0;
887         if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0) error("%llu: failed to disable TCP_NODELAY on socket.", w->id);
888
889         // sent the HTTP header
890         debug(D_WEB_DATA, "%llu: Sending response HTTP header of size %d: '%s'", w->id, headerlen, w->response_header);
891
892         bytes = send(w->ofd, w->response_header, headerlen, 0);
893         if(bytes != headerlen)
894                 error("%llu: HTTP Header failed to be sent (I sent %d bytes but the system sent %d bytes).", w->id, headerlen, bytes);
895         else {
896                 global_statistics_lock();
897                 global_statistics.bytes_sent += bytes;
898                 global_statistics_unlock();
899         }
900
901         // enable TCP_NODELAY, to send all data immediately at the next send()
902         flag = 1;
903         if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0) error("%llu: failed to enable TCP_NODELAY on socket.", w->id);
904
905         // enable sending immediately if we have data
906         if(w->data->len) w->wait_send = 1;
907         else w->wait_send = 0;
908
909         // pretty logging
910         switch(w->mode) {
911                 case WEB_CLIENT_MODE_NORMAL:
912                         debug(D_WEB_CLIENT, "%llu: Done preparing the response. Sending data (%d bytes) to client.", w->id, w->data->len);
913                         break;
914
915                 case WEB_CLIENT_MODE_FILECOPY:
916                         if(w->data->rlen) {
917                                 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending data file of %d bytes to client.", w->id, w->data->rlen);
918                                 w->wait_receive = 1;
919
920                                 /*
921                                 // utilize the kernel sendfile() for copying the file to the socket.
922                                 // this block of code can be commented, without anything missing.
923                                 // when it is commented, the program will copy the data using async I/O.
924                                 {
925                                         long len = sendfile(w->ofd, w->ifd, NULL, w->data->rbytes);
926                                         if(len != w->data->rbytes) error("%llu: sendfile() should copy %ld bytes, but copied %ld. Falling back to manual copy.", w->id, w->data->rbytes, len);
927                                         else web_client_reset(w);
928                                 }
929                                 */
930                         }
931                         else
932                                 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending an unknown amount of bytes to client.", w->id);
933                         break;
934
935                 default:
936                         fatal("%llu: Unknown client mode %d.", w->id, w->mode);
937                         break;
938         }
939 }
940
941 long web_client_send_chunk_header(struct web_client *w, int len)
942 {
943         debug(D_DEFLATE, "%llu: OPEN CHUNK of %d bytes (hex: %x).", w->id, len, len);
944         char buf[1024];
945         sprintf(buf, "%X\r\n", len);
946         int bytes = send(w->ofd, buf, strlen(buf), MSG_DONTWAIT);
947
948         if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk header %d bytes.", w->id, bytes);
949         else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk header to the client.", w->id);
950         else debug(D_DEFLATE, "%llu: Failed to send chunk header to client. Reason: %s", w->id, strerror(errno));
951
952         return bytes;
953 }
954
955 long web_client_send_chunk_close(struct web_client *w)
956 {
957         //debug(D_DEFLATE, "%llu: CLOSE CHUNK.", w->id);
958
959         int bytes = send(w->ofd, "\r\n", 2, MSG_DONTWAIT);
960
961         if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
962         else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
963         else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client. Reason: %s", w->id, strerror(errno));
964
965         return bytes;
966 }
967
968 long web_client_send_chunk_finalize(struct web_client *w)
969 {
970         //debug(D_DEFLATE, "%llu: FINALIZE CHUNK.", w->id);
971
972         int bytes = send(w->ofd, "\r\n0\r\n\r\n", 7, MSG_DONTWAIT);
973
974         if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
975         else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
976         else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client. Reason: %s", w->id, strerror(errno));
977
978         return bytes;
979 }
980
981 #ifdef NETDATA_WITH_ZLIB
982 long web_client_send_deflate(struct web_client *w)
983 {
984         long len = 0, t = 0;
985
986         // when using compression,
987         // w->data->sent is the amount of bytes passed through compression
988
989         // debug(D_DEFLATE, "%llu: TEST w->data->bytes = %d, w->data->sent = %d, w->zhave = %d, w->zsent = %d, w->zstream.avail_in = %d, w->zstream.avail_out = %d, w->zstream.total_in = %d, w->zstream.total_out = %d.", w->id, w->data->bytes, w->data->sent, w->zhave, w->zsent, w->zstream.avail_in, w->zstream.avail_out, w->zstream.total_in, w->zstream.total_out);
990
991         if(w->data->len - w->data->sent == 0 && w->zstream.avail_in == 0 && w->zhave == w->zsent && w->zstream.avail_out != 0) {
992                 // there is nothing to send
993
994                 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
995
996                 // finalize the chunk
997                 if(w->data->sent != 0)
998                         t += web_client_send_chunk_finalize(w);
999
1000                 // there can be two cases for this
1001                 // A. we have done everything
1002                 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
1003
1004                 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->data->rlen && w->data->rlen > w->data->len) {
1005                         // we have to wait, more data will come
1006                         debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1007                         w->wait_send = 0;
1008                         return(0);
1009                 }
1010
1011                 if(w->keepalive == 0) {
1012                         debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->data->sent);
1013                         errno = 0;
1014                         return(-1);
1015                 }
1016
1017                 // reset the client
1018                 web_client_reset(w);
1019                 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1020                 return(0);
1021         }
1022
1023         if(w->zstream.avail_out == 0 && w->zhave == w->zsent) {
1024                 // compress more input data
1025
1026                 // close the previous open chunk
1027                 if(w->data->sent != 0) t += web_client_send_chunk_close(w);
1028
1029                 debug(D_DEFLATE, "%llu: Compressing %d bytes starting from %d.", w->id, (w->data->len - w->data->sent), w->data->sent);
1030
1031                 // give the compressor all the data not passed through the compressor yet
1032                 if(w->data->len > w->data->sent) {
1033                         w->zstream.next_in = (Bytef *)&w->data->buffer[w->data->sent];
1034                         w->zstream.avail_in = (w->data->len - w->data->sent);
1035                 }
1036
1037                 // reset the compressor output buffer
1038                 w->zstream.next_out = w->zbuffer;
1039                 w->zstream.avail_out = ZLIB_CHUNK;
1040
1041                 // ask for FINISH if we have all the input
1042                 int flush = Z_SYNC_FLUSH;
1043                 if(w->mode == WEB_CLIENT_MODE_NORMAL
1044                         || (w->mode == WEB_CLIENT_MODE_FILECOPY && w->data->len == w->data->rlen)) {
1045                         flush = Z_FINISH;
1046                         debug(D_DEFLATE, "%llu: Requesting Z_FINISH.", w->id);
1047                 }
1048                 else {
1049                         debug(D_DEFLATE, "%llu: Requesting Z_SYNC_FLUSH.", w->id);
1050                 }
1051
1052                 // compress
1053                 if(deflate(&w->zstream, flush) == Z_STREAM_ERROR) {
1054                         error("%llu: Compression failed. Closing down client.", w->id);
1055                         web_client_reset(w);
1056                         return(-1);
1057                 }
1058
1059                 w->zhave = ZLIB_CHUNK - w->zstream.avail_out;
1060                 w->zsent = 0;
1061
1062                 // keep track of the bytes passed through the compressor
1063                 w->data->sent = w->data->len;
1064
1065                 debug(D_DEFLATE, "%llu: Compression produced %d bytes.", w->id, w->zhave);
1066
1067                 // open a new chunk
1068                 t += web_client_send_chunk_header(w, w->zhave);
1069         }
1070
1071         len = send(w->ofd, &w->zbuffer[w->zsent], w->zhave - w->zsent, MSG_DONTWAIT);
1072         if(len > 0) {
1073                 w->zsent += len;
1074                 if(t > 0) len += t;
1075                 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, len);
1076         }
1077         else if(len == 0) debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client.", w->id);
1078         else debug(D_WEB_CLIENT, "%llu: Failed to send data to client. Reason: %s", w->id, strerror(errno));
1079
1080         return(len);
1081 }
1082 #endif // NETDATA_WITH_ZLIB
1083
1084 long web_client_send(struct web_client *w)
1085 {
1086 #ifdef NETDATA_WITH_ZLIB
1087         if(likely(w->zoutput)) return web_client_send_deflate(w);
1088 #endif // NETDATA_WITH_ZLIB
1089
1090         long bytes;
1091
1092         if(unlikely(w->data->len - w->data->sent == 0)) {
1093                 // there is nothing to send
1094
1095                 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1096
1097                 // there can be two cases for this
1098                 // A. we have done everything
1099                 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
1100
1101                 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->data->rlen && w->data->rlen > w->data->len) {
1102                         // we have to wait, more data will come
1103                         debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1104                         w->wait_send = 0;
1105                         return(0);
1106                 }
1107
1108                 if(unlikely(w->keepalive == 0)) {
1109                         debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->data->sent);
1110                         errno = 0;
1111                         return(-1);
1112                 }
1113
1114                 web_client_reset(w);
1115                 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1116                 return(0);
1117         }
1118
1119         bytes = send(w->ofd, &w->data->buffer[w->data->sent], w->data->len - w->data->sent, MSG_DONTWAIT);
1120         if(likely(bytes > 0)) {
1121                 w->data->sent += bytes;
1122                 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, bytes);
1123         }
1124         else if(likely(bytes == 0)) debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client.", w->id);
1125         else debug(D_WEB_CLIENT, "%llu: Failed to send data to client. Reason: %s", w->id, strerror(errno));
1126
1127         return(bytes);
1128 }
1129
1130 long web_client_receive(struct web_client *w)
1131 {
1132         // do we have any space for more data?
1133         web_buffer_need_bytes(w->data, WEB_DATA_LENGTH_INCREASE_STEP);
1134
1135         long left = w->data->size - w->data->len;
1136         long bytes;
1137
1138         if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY))
1139                 bytes = read(w->ifd, &w->data->buffer[w->data->len], (left-1));
1140         else
1141                 bytes = recv(w->ifd, &w->data->buffer[w->data->len], left-1, MSG_DONTWAIT);
1142
1143         if(likely(bytes > 0)) {
1144                 int old = w->data->len;
1145                 w->data->len += bytes;
1146                 w->data->buffer[w->data->len] = '\0';
1147
1148                 debug(D_WEB_CLIENT, "%llu: Received %d bytes.", w->id, bytes);
1149                 debug(D_WEB_DATA, "%llu: Received data: '%s'.", w->id, &w->data->buffer[old]);
1150
1151                 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1152                         w->wait_send = 1;
1153                         if(w->data->rlen && w->data->len >= w->data->rlen) w->wait_receive = 0;
1154                 }
1155         }
1156         else if(likely(bytes == 0)) {
1157                 debug(D_WEB_CLIENT, "%llu: Out of input data.", w->id);
1158
1159                 // if we cannot read, it means we have an error on input.
1160                 // if however, we are copying a file from ifd to ofd, we should not return an error.
1161                 // in this case, the error should be generated when the file has been sent to the client.
1162
1163                 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1164                         // we are copying data from ifd to ofd
1165                         // let it finish copying...
1166                         w->wait_receive = 0;
1167                         debug(D_WEB_CLIENT, "%llu: Disabling input.", w->id);
1168                 }
1169                 else {
1170                         bytes = -1;
1171                         errno = 0;
1172                 }
1173         }
1174
1175         return(bytes);
1176 }
1177
1178
1179 // --------------------------------------------------------------------------------------
1180 // the thread of a single client
1181
1182 // 1. waits for input and output, using async I/O
1183 // 2. it processes HTTP requests
1184 // 3. it generates HTTP responses
1185 // 4. it copies data from input to output if mode is FILECOPY
1186
1187 void *web_client_main(void *ptr)
1188 {
1189         if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
1190                 error("Cannot set pthread cancel type to DEFERRED.");
1191
1192         if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
1193                 error("Cannot set pthread cancel state to ENABLE.");
1194
1195         struct timeval tv;
1196         struct web_client *w = ptr;
1197         int retval;
1198         fd_set ifds, ofds, efds;
1199         int fdmax = 0;
1200
1201         log_access("%llu: %s port %s connected on thread task id %d", w->id, w->client_ip, w->client_port, gettid());
1202
1203         for(;;) {
1204                 FD_ZERO (&ifds);
1205                 FD_ZERO (&ofds);
1206                 FD_ZERO (&efds);
1207
1208                 FD_SET(w->ifd, &efds);
1209
1210                 if(w->ifd != w->ofd)
1211                         FD_SET(w->ofd, &efds);
1212
1213                 if (w->wait_receive) {
1214                         FD_SET(w->ifd, &ifds);
1215                         if(w->ifd > fdmax) fdmax = w->ifd;
1216                 }
1217
1218                 if (w->wait_send) {
1219                         FD_SET(w->ofd, &ofds);
1220                         if(w->ofd > fdmax) fdmax = w->ofd;
1221                 }
1222
1223                 tv.tv_sec = web_client_timeout;
1224                 tv.tv_usec = 0;
1225
1226                 debug(D_WEB_CLIENT, "%llu: Waiting socket async I/O for %s %s", w->id, w->wait_receive?"INPUT":"", w->wait_send?"OUTPUT":"");
1227                 retval = select(fdmax+1, &ifds, &ofds, &efds, &tv);
1228
1229                 if(retval == -1) {
1230                         debug(D_WEB_CLIENT_ACCESS, "%llu: LISTENER: select() failed.", w->id);
1231                         continue;
1232                 }
1233                 else if(!retval) {
1234                         // timeout
1235                         debug(D_WEB_CLIENT_ACCESS, "%llu: LISTENER: timeout.", w->id);
1236                         break;
1237                 }
1238
1239                 if(FD_ISSET(w->ifd, &efds)) {
1240                         debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on input socket (%s).", w->id, strerror(errno));
1241                         break;
1242                 }
1243
1244                 if(FD_ISSET(w->ofd, &efds)) {
1245                         debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on output socket (%s).", w->id, strerror(errno));
1246                         break;
1247                 }
1248
1249                 if(w->wait_send && FD_ISSET(w->ofd, &ofds)) {
1250                         long bytes;
1251                         if((bytes = web_client_send(w)) < 0) {
1252                                 debug(D_WEB_CLIENT, "%llu: Cannot send data to client. Closing client (ouput: %s).", w->id, strerror(errno));
1253                                 errno = 0;
1254                                 break;
1255                         }
1256
1257                         global_statistics_lock();
1258                         global_statistics.bytes_sent += bytes;
1259                         global_statistics_unlock();
1260                 }
1261
1262                 if(w->wait_receive && FD_ISSET(w->ifd, &ifds)) {
1263                         long bytes;
1264                         if((bytes = web_client_receive(w)) < 0) {
1265                                 debug(D_WEB_CLIENT, "%llu: Cannot receive data from client. Closing client (input: %s).", w->id, strerror(errno));
1266                                 errno = 0;
1267                                 break;
1268                         }
1269
1270                         global_statistics_lock();
1271                         global_statistics.bytes_received += bytes;
1272                         global_statistics_unlock();
1273
1274                         if(w->mode == WEB_CLIENT_MODE_NORMAL) {
1275                                 debug(D_WEB_CLIENT, "%llu: Attempting to process received data.", w->id);
1276                                 web_client_process(w);
1277                         }
1278                 }
1279         }
1280
1281         log_access("%llu: %s port %s disconnected from thread task id %d", w->id, w->client_ip, w->client_port, gettid());
1282         debug(D_WEB_CLIENT, "%llu: done...", w->id);
1283
1284         web_client_reset(w);
1285         w->obsolete = 1;
1286
1287         return NULL;
1288 }