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