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