]> arthur.barton.de Git - netdata.git/blob - src/web_server.c
added libavl for supporting balanced binary trees - this improves search performance...
[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_byname(tok);
279         if(!st) st = rrdset_find(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_byname(tok);
494                                 if(!st) {
495                                         // we don't have it
496                                         // try to send a file with that name
497                                         w->data->bytes = 0;
498                                         code = mysendfile(w, tok);
499                                 }
500                                 else {
501                                         code = 200;
502                                         debug(D_WEB_CLIENT_ACCESS, "%llu: Sending %s.json of RRD_STATS...", w->id, st->name);
503                                         w->data->contenttype = CT_APPLICATION_JSON;
504                                         w->data->bytes = 0;
505                                         rrd_stats_graph_json(st, url, w->data);
506                                 }
507                         }
508                         else if(strcmp(tok, "debug") == 0) {
509                                 w->data->bytes = 0;
510
511                                 // get the name of the data to show
512                                 tok = mystrsep(&url, "/?&");
513                                 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
514
515                                 // do we have such a data set?
516                                 RRDSET *st = rrdset_find_byname(tok);
517                                 if(!st) {
518                                         code = 404;
519                                         web_buffer_printf(w->data, "Chart %s is not found.\r\n", tok);
520                                         debug(D_WEB_CLIENT_ACCESS, "%llu: %s is not found.", w->id, tok);
521                                 }
522                                 else {
523                                         code = 200;
524                                         debug_flags |= D_RRD_STATS;
525                                         st->debug = st->debug?0:1;
526                                         web_buffer_printf(w->data, "Chart %s has now debug %s.\r\n", tok, st->debug?"enabled":"disabled");
527                                         debug(D_WEB_CLIENT_ACCESS, "%llu: debug for %s is %s.", w->id, tok, st->debug?"enabled":"disabled");
528                                 }
529                         }
530                         else if(strcmp(tok, "mirror") == 0) {
531                                 code = 200;
532
533                                 debug(D_WEB_CLIENT_ACCESS, "%llu: Mirroring...", w->id);
534
535                                 // replace the zero bytes with spaces
536                                 int i;
537                                 for(i = 0; i < w->data->size; i++)
538                                         if(w->data->buffer[i] == '\0') w->data->buffer[i] = ' ';
539
540                                 // just leave the buffer as is
541                                 // it will be copied back to the client
542                         }
543                         else if(strcmp(tok, "list") == 0) {
544                                 code = 200;
545
546                                 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending list of RRD_STATS...", w->id);
547
548                                 w->data->bytes = 0;
549                                 RRDSET *st = rrdset_root;
550
551                                 for ( ; st ; st = st->next )
552                                         web_buffer_printf(w->data, "%s\n", st->name);
553                         }
554                         else if(strcmp(tok, "all.json") == 0) {
555                                 code = 200;
556                                 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending JSON list of all monitors of RRD_STATS...", w->id);
557
558                                 w->data->contenttype = CT_APPLICATION_JSON;
559                                 w->data->bytes = 0;
560                                 rrd_stats_all_json(w->data);
561                         }
562                         else if(strcmp(tok, "netdata.conf") == 0) {
563                                 code = 200;
564                                 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending netdata.conf ...", w->id);
565
566                                 w->data->contenttype = CT_TEXT_PLAIN;
567                                 w->data->bytes = 0;
568                                 generate_config(w->data, 0);
569                         }
570                         else if(strcmp(tok, WEB_PATH_FILE) == 0) { // "file"
571                                 tok = mystrsep(&url, "/?&");
572                                 if(tok && *tok) code = mysendfile(w, tok);
573                                 else {
574                                         code = 400;
575                                         w->data->bytes = 0;
576                                         strcpy(w->data->buffer, "You have to give a filename to get.\r\n");
577                                         w->data->bytes = strlen(w->data->buffer);
578                                 }
579                         }
580                         else if(!tok[0]) {
581                                 w->data->bytes = 0;
582                                 code = mysendfile(w, "index.html");
583                         }
584                         else {
585                                 w->data->bytes = 0;
586                                 code = mysendfile(w, tok);
587                         }
588
589                 }
590                 else {
591                         strcpy(w->last_url, "not a valid response");
592
593                         if(buf) debug(D_WEB_CLIENT_ACCESS, "%llu: Cannot understand '%s'.", w->id, buf);
594
595                         code = 500;
596                         w->data->bytes = 0;
597                         strcpy(w->data->buffer, "I don't understand you...\r\n");
598                         w->data->bytes = strlen(w->data->buffer);
599                 }
600                 
601                 // free url_decode() buffer
602                 if(pointer_to_free) free(pointer_to_free);
603         }
604         else if(w->data->bytes > 8192) {
605                 strcpy(w->last_url, "too big request");
606
607                 debug(D_WEB_CLIENT_ACCESS, "%llu: Received request is too big.", w->id);
608
609                 code = 400;
610                 w->data->bytes = 0;
611                 strcpy(w->data->buffer, "Received request is too big.\r\n");
612                 w->data->bytes = strlen(w->data->buffer);
613         }
614         else {
615                 // wait for more data
616                 w->wait_receive = 1;
617                 return;
618         }
619
620         if(w->data->bytes > w->data->size) {
621                 error("%llu: memory overflow encountered (size is %ld, written %ld).", w->data->size, w->data->bytes);
622         }
623
624         gettimeofday(&w->tv_ready, NULL);
625         w->data->date = time(NULL);
626         w->data->sent = 0;
627
628         // prepare the HTTP response header
629         debug(D_WEB_CLIENT, "%llu: Generating HTTP header with response %d.", w->id, code);
630
631         char *content_type_string = "";
632         switch(w->data->contenttype) {
633                 case CT_TEXT_HTML:
634                         content_type_string = "text/html";
635                         break;
636
637                 case CT_APPLICATION_XML:
638                         content_type_string = "application/xml";
639                         break;
640
641                 case CT_APPLICATION_JSON:
642                         content_type_string = "application/json";
643                         break;
644
645                 case CT_APPLICATION_X_JAVASCRIPT:
646                         content_type_string = "application/x-javascript";
647                         break;
648
649                 case CT_TEXT_CSS:
650                         content_type_string = "text/css";
651                         break;
652
653                 case CT_TEXT_XML:
654                         content_type_string = "text/xml";
655                         break;
656
657                 case CT_TEXT_XSL:
658                         content_type_string = "text/xsl";
659                         break;
660
661                 case CT_APPLICATION_OCTET_STREAM:
662                         content_type_string = "application/octet-stream";
663                         break;
664
665                 case CT_IMAGE_SVG_XML:
666                         content_type_string = "image/svg+xml";
667                         break;
668
669                 case CT_APPLICATION_X_FONT_TRUETYPE:
670                         content_type_string = "application/x-font-truetype";
671                         break;
672
673                 case CT_APPLICATION_X_FONT_OPENTYPE:
674                         content_type_string = "application/x-font-opentype";
675                         break;
676
677                 case CT_APPLICATION_FONT_WOFF:
678                         content_type_string = "application/font-woff";
679                         break;
680
681                 case CT_APPLICATION_VND_MS_FONTOBJ:
682                         content_type_string = "application/vnd.ms-fontobject";
683                         break;
684
685                 default:
686                 case CT_TEXT_PLAIN:
687                         content_type_string = "text/plain";
688                         break;
689         }
690
691         char *code_msg = "";
692         switch(code) {
693                 case 200:
694                         code_msg = "OK";
695                         break;
696
697                 case 307:
698                         code_msg = "Temporary Redirect";
699                         break;
700
701                 case 400:
702                         code_msg = "Bad Request";
703                         break;
704
705                 case 403:
706                         code_msg = "Forbidden";
707                         break;
708
709                 case 404:
710                         code_msg = "Not Found";
711                         break;
712
713                 default:
714                         code_msg = "Internal Server Error";
715                         break;
716         }
717
718         char date[100];
719         struct tm tm = *gmtime(&w->data->date);
720         strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %Z", &tm);
721
722         char custom_header[MAX_HTTP_HEADER_SIZE + 1] = "";
723         if(w->response_header[0]) 
724                 strcpy(custom_header, w->response_header);
725
726         int headerlen = 0;
727         headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen,
728                 "HTTP/1.1 %d %s\r\n"
729                 "Connection: %s\r\n"
730                 "Server: NetData Embedded HTTP Server\r\n"
731                 "Content-Type: %s\r\n"
732                 "Access-Control-Allow-Origin: *\r\n"
733                 "Date: %s\r\n"
734                 , code, code_msg
735                 , w->keepalive?"keep-alive":"close"
736                 , content_type_string
737                 , date
738                 );
739
740         if(custom_header[0])
741                 headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen, "%s", custom_header);
742
743         if(w->mode == WEB_CLIENT_MODE_NORMAL) {
744                 headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen,
745                         "Expires: %s\r\n"
746                         "Cache-Control: no-cache\r\n"
747                         , date
748                         );
749         }
750         else {
751                 headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen,
752                         "Cache-Control: public\r\n"
753                         );
754         }
755
756         // if we know the content length, put it
757         if(!w->zoutput && (w->data->bytes || w->data->rbytes))
758                 headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen,
759                         "Content-Length: %ld\r\n"
760                         , w->data->bytes?w->data->bytes:w->data->rbytes
761                         );
762         else if(!w->zoutput)
763                 w->keepalive = 0;       // content-length is required for keep-alive
764
765         if(w->zoutput) {
766                 headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen,
767                         "Content-Encoding: gzip\r\n"
768                         "Transfer-Encoding: chunked\r\n"
769                         );
770         }
771
772         headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen, "\r\n");
773
774         // disable TCP_NODELAY, to buffer the header
775         int flag = 0;
776         if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0) error("%llu: failed to disable TCP_NODELAY on socket.", w->id);
777
778         // sent the HTTP header
779         debug(D_WEB_DATA, "%llu: Sending response HTTP header of size %d: '%s'", w->id, headerlen, w->response_header);
780
781         bytes = send(w->ofd, w->response_header, headerlen, 0);
782         if(bytes != headerlen)
783                 error("%llu: HTTP Header failed to be sent (I sent %d bytes but the system sent %d bytes).", w->id, headerlen, bytes);
784         else {
785                 global_statistics_lock();
786                 global_statistics.bytes_sent += bytes;
787                 global_statistics_unlock();
788         }
789
790         // enable TCP_NODELAY, to send all data immediately at the next send()
791         flag = 1;
792         if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0) error("%llu: failed to enable TCP_NODELAY on socket.", w->id);
793
794         // enable sending immediately if we have data
795         if(w->data->bytes) w->wait_send = 1;
796         else w->wait_send = 0;
797
798         // pretty logging
799         switch(w->mode) {
800                 case WEB_CLIENT_MODE_NORMAL:
801                         debug(D_WEB_CLIENT, "%llu: Done preparing the response. Sending data (%d bytes) to client.", w->id, w->data->bytes);
802                         break;
803
804                 case WEB_CLIENT_MODE_FILECOPY:
805                         if(w->data->rbytes) {
806                                 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending data file of %d bytes to client.", w->id, w->data->rbytes);
807                                 w->wait_receive = 1;
808
809                                 /*
810                                 // utilize the kernel sendfile() for copying the file to the socket.
811                                 // this block of code can be commented, without anything missing.
812                                 // when it is commented, the program will copy the data using async I/O.
813                                 {
814                                         long len = sendfile(w->ofd, w->ifd, NULL, w->data->rbytes);
815                                         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);
816                                         else web_client_reset(w);
817                                 }
818                                 */
819                         }
820                         else
821                                 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending an unknown amount of bytes to client.", w->id);
822                         break;
823
824                 default:
825                         fatal("%llu: Unknown client mode %d.", w->id, w->mode);
826                         break;
827         }
828 }
829
830 long web_client_send_chunk_header(struct web_client *w, int len)
831 {
832         debug(D_DEFLATE, "%llu: OPEN CHUNK of %d bytes (hex: %x).", w->id, len, len);
833         char buf[1024]; 
834         sprintf(buf, "%X\r\n", len);
835         int bytes = send(w->ofd, buf, strlen(buf), MSG_DONTWAIT);
836
837         if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk header %d bytes.", w->id, bytes);
838         else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk header to the client.", w->id);
839         else debug(D_DEFLATE, "%llu: Failed to send chunk header to client. Reason: %s", w->id, strerror(errno));
840
841         return bytes;
842 }
843
844 long web_client_send_chunk_close(struct web_client *w)
845 {
846         //debug(D_DEFLATE, "%llu: CLOSE CHUNK.", w->id);
847
848         int bytes = send(w->ofd, "\r\n", 2, MSG_DONTWAIT);
849
850         if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
851         else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
852         else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client. Reason: %s", w->id, strerror(errno));
853
854         return bytes;
855 }
856
857 long web_client_send_chunk_finalize(struct web_client *w)
858 {
859         //debug(D_DEFLATE, "%llu: FINALIZE CHUNK.", w->id);
860
861         int bytes = send(w->ofd, "\r\n0\r\n\r\n", 7, MSG_DONTWAIT);
862
863         if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
864         else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
865         else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client. Reason: %s", w->id, strerror(errno));
866
867         return bytes;
868 }
869
870 long web_client_send_deflate(struct web_client *w)
871 {
872         long bytes = 0, t = 0;
873
874         // when using compression,
875         // w->data->sent is the amount of bytes passed through compression
876
877         // 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);
878
879         if(w->data->bytes - w->data->sent == 0 && w->zstream.avail_in == 0 && w->zhave == w->zsent && w->zstream.avail_out != 0) {
880                 // there is nothing to send
881
882                 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
883
884                 // finalize the chunk
885                 if(w->data->sent != 0)
886                         t += web_client_send_chunk_finalize(w);
887
888                 // there can be two cases for this
889                 // A. we have done everything
890                 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
891
892                 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->data->rbytes && w->data->rbytes > w->data->bytes) {
893                         // we have to wait, more data will come
894                         debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
895                         w->wait_send = 0;
896                         return(0);
897                 }
898
899                 if(w->keepalive == 0) {
900                         debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->data->sent);
901                         errno = 0;
902                         return(-1);
903                 }
904
905                 // reset the client
906                 web_client_reset(w);
907                 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
908                 return(0);
909         }
910
911         if(w->zstream.avail_out == 0 && w->zhave == w->zsent) {
912                 // compress more input data
913
914                 // close the previous open chunk
915                 if(w->data->sent != 0) t += web_client_send_chunk_close(w);
916
917                 debug(D_DEFLATE, "%llu: Compressing %d bytes starting from %d.", w->id, (w->data->bytes - w->data->sent), w->data->sent);
918
919                 // give the compressor all the data not passed through the compressor yet
920                 if(w->data->bytes > w->data->sent) {
921                         w->zstream.next_in = (Bytef *)&w->data->buffer[w->data->sent];
922                         w->zstream.avail_in = (w->data->bytes - w->data->sent);
923                 }
924
925                 // reset the compressor output buffer
926                 w->zstream.next_out = w->zbuffer;
927                 w->zstream.avail_out = ZLIB_CHUNK;
928
929                 // ask for FINISH if we have all the input
930                 int flush = Z_SYNC_FLUSH;
931                 if(w->mode == WEB_CLIENT_MODE_NORMAL
932                         || (w->mode == WEB_CLIENT_MODE_FILECOPY && w->data->bytes == w->data->rbytes)) {
933                         flush = Z_FINISH;
934                         debug(D_DEFLATE, "%llu: Requesting Z_FINISH.", w->id);
935                 }
936                 else {
937                         debug(D_DEFLATE, "%llu: Requesting Z_SYNC_FLUSH.", w->id);
938                 }
939
940                 // compress
941                 if(deflate(&w->zstream, flush) == Z_STREAM_ERROR) {
942                         error("%llu: Compression failed. Closing down client.", w->id);
943                         web_client_reset(w);
944                         return(-1);
945                 }
946
947                 w->zhave = ZLIB_CHUNK - w->zstream.avail_out;
948                 w->zsent = 0;
949
950                 // keep track of the bytes passed through the compressor
951                 w->data->sent = w->data->bytes;
952
953                 debug(D_DEFLATE, "%llu: Compression produced %d bytes.", w->id, w->zhave);
954
955                 // open a new chunk
956                 t += web_client_send_chunk_header(w, w->zhave);
957         }
958
959         bytes = send(w->ofd, &w->zbuffer[w->zsent], w->zhave - w->zsent, MSG_DONTWAIT);
960         if(bytes > 0) {
961                 w->zsent += bytes;
962                 if(t > 0) bytes += t;
963                 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, bytes);
964         }
965         else if(bytes == 0) debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client.", w->id);
966         else debug(D_WEB_CLIENT, "%llu: Failed to send data to client. Reason: %s", w->id, strerror(errno));
967
968         return(bytes);
969 }
970
971 long web_client_send(struct web_client *w)
972 {
973         if(w->zoutput) return web_client_send_deflate(w);
974
975         long bytes;
976
977         if(w->data->bytes - w->data->sent == 0) {
978                 // there is nothing to send
979
980                 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
981
982                 // there can be two cases for this
983                 // A. we have done everything
984                 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
985
986                 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->data->rbytes && w->data->rbytes > w->data->bytes) {
987                         // we have to wait, more data will come
988                         debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
989                         w->wait_send = 0;
990                         return(0);
991                 }
992
993                 if(w->keepalive == 0) {
994                         debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->data->sent);
995                         errno = 0;
996                         return(-1);
997                 }
998
999                 web_client_reset(w);
1000                 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1001                 return(0);
1002         }
1003
1004         bytes = send(w->ofd, &w->data->buffer[w->data->sent], w->data->bytes - w->data->sent, MSG_DONTWAIT);
1005         if(bytes > 0) {
1006                 w->data->sent += bytes;
1007                 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, bytes);
1008         }
1009         else if(bytes == 0) debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client.", w->id);
1010         else debug(D_WEB_CLIENT, "%llu: Failed to send data to client. Reason: %s", w->id, strerror(errno));
1011
1012
1013         return(bytes);
1014 }
1015
1016 long web_client_receive(struct web_client *w)
1017 {
1018         // do we have any space for more data?
1019         web_buffer_increase(w->data, WEB_DATA_LENGTH_INCREASE_STEP);
1020
1021         long left = w->data->size - w->data->bytes;
1022         long bytes;
1023
1024         if(w->mode == WEB_CLIENT_MODE_FILECOPY)
1025                 bytes = read(w->ifd, &w->data->buffer[w->data->bytes], (left-1));
1026         else
1027                 bytes = recv(w->ifd, &w->data->buffer[w->data->bytes], left-1, MSG_DONTWAIT);
1028
1029         if(bytes > 0) {
1030                 int old = w->data->bytes;
1031                 w->data->bytes += bytes;
1032                 w->data->buffer[w->data->bytes] = '\0';
1033
1034                 debug(D_WEB_CLIENT, "%llu: Received %d bytes.", w->id, bytes);
1035                 debug(D_WEB_DATA, "%llu: Received data: '%s'.", w->id, &w->data->buffer[old]);
1036
1037                 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1038                         w->wait_send = 1;
1039                         if(w->data->rbytes && w->data->bytes >= w->data->rbytes) w->wait_receive = 0;
1040                 }
1041         }
1042         else if(bytes == 0) {
1043                 debug(D_WEB_CLIENT, "%llu: Out of input data.", w->id);
1044
1045                 // if we cannot read, it means we have an error on input.
1046                 // if however, we are copying a file from ifd to ofd, we should not return an error.
1047                 // in this case, the error should be generated when the file has been sent to the client.
1048
1049                 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1050                         // we are copying data fron ifd to ofd
1051                         // let it finish copying...
1052                         w->wait_receive = 0;
1053                         debug(D_WEB_CLIENT, "%llu: Disabling input.", w->id);
1054                 }
1055                 else {
1056                         bytes = -1;
1057                         errno = 0;
1058                 }
1059         }
1060
1061         return(bytes);
1062 }
1063
1064
1065 // --------------------------------------------------------------------------------------
1066 // the thread of a single client
1067
1068 // 1. waits for input and output, using async I/O
1069 // 2. it processes HTTP requests
1070 // 3. it generates HTTP responses
1071 // 4. it copies data from input to output if mode is FILECOPY
1072
1073 void *new_client(void *ptr)
1074 {
1075         if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
1076                 error("Cannot set pthread cancel type to DEFERRED.");
1077
1078         if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
1079                 error("Cannot set pthread cancel state to ENABLE.");
1080
1081         struct timeval tv;
1082         struct web_client *w = ptr;
1083         int retval;
1084         fd_set ifds, ofds, efds;
1085         int fdmax = 0;
1086
1087         for(;;) {
1088                 FD_ZERO (&ifds);
1089                 FD_ZERO (&ofds);
1090                 FD_ZERO (&efds);
1091
1092                 FD_SET(w->ifd, &efds);
1093                 if(w->ifd != w->ofd)    FD_SET(w->ofd, &efds);
1094                 if (w->wait_receive) {
1095                         FD_SET(w->ifd, &ifds);
1096                         if(w->ifd > fdmax) fdmax = w->ifd;
1097                 }
1098                 if (w->wait_send) {
1099                         FD_SET(w->ofd, &ofds);
1100                         if(w->ofd > fdmax) fdmax = w->ofd;
1101                 }
1102
1103                 tv.tv_sec = 30;
1104                 tv.tv_usec = 0;
1105
1106                 debug(D_WEB_CLIENT, "%llu: Waiting socket async I/O for %s %s", w->id, w->wait_receive?"INPUT":"", w->wait_send?"OUTPUT":"");
1107                 retval = select(fdmax+1, &ifds, &ofds, &efds, &tv);
1108
1109                 if(retval == -1) {
1110                         error("%llu: LISTENER: select() failed.", w->id);
1111                         continue;
1112                 }
1113                 else if(!retval) {
1114                         // timeout
1115                         web_client_reset(w);
1116                         w->obsolete = 1;
1117                         return NULL;
1118                 }
1119
1120                 if(FD_ISSET(w->ifd, &efds)) {
1121                         debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on input socket (%s).", w->id, strerror(errno));
1122                         web_client_reset(w);
1123                         w->obsolete = 1;
1124                         return NULL;
1125                 }
1126
1127                 if(FD_ISSET(w->ofd, &efds)) {
1128                         debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on output socket (%s).", w->id, strerror(errno));
1129                         web_client_reset(w);
1130                         w->obsolete = 1;
1131                         return NULL;
1132                 }
1133
1134                 if(w->wait_send && FD_ISSET(w->ofd, &ofds)) {
1135                         long bytes;
1136                         if((bytes = web_client_send(w)) < 0) {
1137                                 debug(D_WEB_CLIENT, "%llu: Closing client (input: %s).", w->id, strerror(errno));
1138                                 web_client_reset(w);
1139                                 w->obsolete = 1;
1140                                 errno = 0;
1141                                 return NULL;
1142                         }
1143                         else {
1144                                 global_statistics_lock();
1145                                 global_statistics.bytes_sent += bytes;
1146                                 global_statistics_unlock();
1147                         }
1148                 }
1149
1150                 if(w->wait_receive && FD_ISSET(w->ifd, &ifds)) {
1151                         long bytes;
1152                         if((bytes = web_client_receive(w)) < 0) {
1153                                 debug(D_WEB_CLIENT, "%llu: Closing client (output: %s).", w->id, strerror(errno));
1154                                 web_client_reset(w);
1155                                 w->obsolete = 1;
1156                                 errno = 0;
1157                                 return NULL;
1158                         }
1159                         else {
1160                                 if(w->mode != WEB_CLIENT_MODE_FILECOPY) {
1161                                         global_statistics_lock();
1162                                         global_statistics.bytes_received += bytes;
1163                                         global_statistics_unlock();
1164                                 }
1165                         }
1166
1167                         if(w->mode == WEB_CLIENT_MODE_NORMAL) web_client_process(w);
1168                 }
1169         }
1170         debug(D_WEB_CLIENT, "%llu: done...", w->id);
1171
1172         return NULL;
1173 }
1174
1175 // --------------------------------------------------------------------------------------
1176 // the main socket listener
1177
1178 // 1. it accepts new incoming requests on our port
1179 // 2. creates a new web_client for each connection received
1180 // 3. spawns a new pthread to serve the client (this is optimal for keep-alive clients)
1181 // 4. cleans up old web_clients that their pthreads have been exited
1182
1183 void *socket_listen_main(void *ptr)
1184 {
1185         if(ptr) { ; }
1186         struct web_client *w;
1187         struct timeval tv;
1188         int retval;
1189
1190         if(ptr) { ; }
1191
1192         if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
1193                 error("Cannot set pthread cancel type to DEFERRED.");
1194
1195         if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
1196                 error("Cannot set pthread cancel state to ENABLE.");
1197
1198         // int listener = create_listen_socket(listen_port);
1199         int listener = listen_fd;
1200         if(listener == -1) fatal("LISTENER: Cannot create listening socket on port 19999.");
1201
1202         fd_set ifds, ofds, efds;
1203         int fdmax = listener;
1204
1205         FD_ZERO (&ifds);
1206         FD_ZERO (&ofds);
1207         FD_ZERO (&efds);
1208
1209         for(;;) {
1210                 tv.tv_sec = 0;
1211                 tv.tv_usec = 200000;
1212
1213                 FD_SET(listener, &ifds);
1214                 FD_SET(listener, &efds);
1215
1216                 // debug(D_WEB_CLIENT, "LISTENER: Waiting...");
1217                 retval = select(fdmax+1, &ifds, &ofds, &efds, &tv);
1218
1219                 if(retval == -1) {
1220                         error("LISTENER: select() failed.");
1221                         continue;
1222                 }
1223                 else if(retval) {
1224                         // check for new incoming connections
1225                         if(FD_ISSET(listener, &ifds)) {
1226                                 w = web_client_create(listener);
1227
1228                                 if(pthread_create(&w->thread, NULL, new_client, w) != 0) {
1229                                         error("%llu: failed to create new thread for web client.");
1230                                         w->obsolete = 1;
1231                                 }
1232                                 else if(pthread_detach(w->thread) != 0) {
1233                                         error("%llu: Cannot request detach of newly created web client thread.", w->id);
1234                                         w->obsolete = 1;
1235                                 }
1236                                 
1237                                 log_access("%llu: %s connected", w->id, w->client_ip);
1238                         }
1239                         else debug(D_WEB_CLIENT, "LISTENER: select() didn't do anything.");
1240
1241                 }
1242                 //else {
1243                 //      debug(D_WEB_CLIENT, "LISTENER: select() timeout.");
1244                 //}
1245
1246                 // cleanup unused clients
1247                 for(w = web_clients; w ; w = w?w->next:NULL) {
1248                         if(w->obsolete) {
1249                                 log_access("%llu: %s disconnected", w->id, w->client_ip);
1250                                 debug(D_WEB_CLIENT, "%llu: Removing client.", w->id);
1251                                 // pthread_join(w->thread,  NULL);
1252                                 w = web_client_free(w);
1253                                 log_allocations();
1254                         }
1255                 }
1256         }
1257
1258         error("LISTENER: exit!");
1259
1260         close(listener);
1261         exit(2);
1262
1263         return NULL;
1264 }
1265