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