6 #include <sys/socket.h>
7 #include <netinet/in.h>
13 #include <netinet/tcp.h>
20 #include "web_buffer.h"
21 #include "web_client.h"
22 #include "web_server.h"
23 #include "global_statistics.h"
28 int listen_port = LISTEN_PORT;
30 static void log_allocations(void)
37 if(mi.uordblks > mem) {
40 for(w = web_clients; w ; w = w->next) clients++;
42 info("Allocated memory increased from %d to %d (increased by %d bytes). There are %d web clients connected.", mem, mi.uordblks, mi.uordblks - mem, clients);
47 int create_listen_socket(int port)
51 struct sockaddr_in name;
53 debug(D_LISTENER, "Creating new listening socket on port %d", port);
55 sock = socket(AF_INET, SOCK_STREAM, 0);
57 fatal("socket() failed, errno=%d", errno);
59 /* avoid "address already in use" */
60 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*)&sockopt, sizeof(sockopt));
62 memset(&name, 0, sizeof(struct sockaddr_in));
63 name.sin_family = AF_INET;
64 name.sin_port = htons (port);
65 name.sin_addr.s_addr = htonl (INADDR_ANY);
66 if (bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0)
67 fatal("bind() failed, errno=%d", errno);
69 if (listen(sock, LISTEN_BACKLOG) < 0)
70 fatal("listen() failed, errno=%d", errno);
72 debug(D_LISTENER, "Listening Port %d created", port);
77 int mysendfile(struct web_client *w, char *filename)
79 static char *web_dir = NULL;
80 if(!web_dir) web_dir = config_get("global", "web files directory", "web");
82 debug(D_WEB_CLIENT, "%llu: Looking for file '%s'...", w->id, filename);
84 // skip leading slashes
85 while (*filename == '/') filename++;
87 // if the filename contain known paths, skip them
88 if(strncmp(filename, WEB_PATH_DATA "/", strlen(WEB_PATH_DATA) + 1) == 0) filename = &filename[strlen(WEB_PATH_DATA) + 1];
89 else if(strncmp(filename, WEB_PATH_DATASOURCE "/", strlen(WEB_PATH_DATASOURCE) + 1) == 0) filename = &filename[strlen(WEB_PATH_DATASOURCE) + 1];
90 else if(strncmp(filename, WEB_PATH_GRAPH "/", strlen(WEB_PATH_GRAPH) + 1) == 0) filename = &filename[strlen(WEB_PATH_GRAPH) + 1];
91 else if(strncmp(filename, WEB_PATH_FILE "/", strlen(WEB_PATH_FILE) + 1) == 0) filename = &filename[strlen(WEB_PATH_FILE) + 1];
93 // if the filename contains a / or a .., refuse to serve it
94 if(strchr(filename, '/') != 0 || strstr(filename, "..") != 0) {
95 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
96 web_buffer_printf(w->data, "File '%s' cannot be served. Filenames cannot contain / or ..", filename);
101 char webfilename[FILENAME_MAX + 1];
102 snprintf(webfilename, FILENAME_MAX, "%s/%s", web_dir, filename);
104 // check if the file exists
106 if(lstat(webfilename, &stat) != 0) {
107 error("%llu: File '%s' is not found.", w->id, webfilename);
108 web_buffer_printf(w->data, "File '%s' does not exist, or is not accessible.", filename);
112 // check if the file is owned by us
113 if(stat.st_uid != getuid() && stat.st_uid != geteuid()) {
114 error("%llu: File '%s' is owned by user %d (I run as user %d). Access Denied.", w->id, webfilename, stat.st_uid, getuid());
115 web_buffer_printf(w->data, "Access to file '%s' is not permitted.", filename);
120 w->ifd = open(webfilename, O_NONBLOCK, O_RDONLY);
124 if(errno == EBUSY || errno == EAGAIN) {
125 error("%llu: File '%s' is busy, sending 307 Moved Temporarily to force retry.", w->id, webfilename);
126 snprintf(w->response_header, MAX_HTTP_HEADER_SIZE, "Location: /" WEB_PATH_FILE "/%s\r\n", filename);
127 web_buffer_printf(w->data, "The file '%s' is currently busy. Please try again later.", filename);
131 error("%llu: Cannot open file '%s'.", w->id, webfilename);
132 web_buffer_printf(w->data, "Cannot open file '%s'.", filename);
137 // pick a Content-Type for the file
138 if(strstr(filename, ".html") != NULL) w->data->contenttype = CT_TEXT_HTML;
139 else if(strstr(filename, ".js") != NULL) w->data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
140 else if(strstr(filename, ".css") != NULL) w->data->contenttype = CT_TEXT_CSS;
141 else if(strstr(filename, ".xml") != NULL) w->data->contenttype = CT_TEXT_XML;
142 else if(strstr(filename, ".xsl") != NULL) w->data->contenttype = CT_TEXT_XSL;
143 else if(strstr(filename, ".txt") != NULL) w->data->contenttype = CT_TEXT_PLAIN;
144 else if(strstr(filename, ".svg") != NULL) w->data->contenttype = CT_IMAGE_SVG_XML;
145 else if(strstr(filename, ".ttf") != NULL) w->data->contenttype = CT_APPLICATION_X_FONT_TRUETYPE;
146 else if(strstr(filename, ".otf") != NULL) w->data->contenttype = CT_APPLICATION_X_FONT_OPENTYPE;
147 else if(strstr(filename, ".woff") != NULL) w->data->contenttype = CT_APPLICATION_FONT_WOFF;
148 else if(strstr(filename, ".eot") != NULL) w->data->contenttype = CT_APPLICATION_VND_MS_FONTOBJ;
149 else w->data->contenttype = CT_APPLICATION_OCTET_STREAM;
151 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending file '%s' (%ld bytes, ifd %d, ofd %d).", w->id, webfilename, stat.st_size, w->ifd, w->ofd);
153 w->mode = WEB_CLIENT_MODE_FILECOPY;
157 w->data->buffer[0] = '\0';
158 w->data->rbytes = stat.st_size;
159 w->data->date = stat.st_mtim.tv_sec;
164 void web_client_reset(struct web_client *w)
167 gettimeofday(&tv, NULL);
169 long sent = w->zoutput?(long)w->zstream.total_out:((w->mode == WEB_CLIENT_MODE_FILECOPY)?w->data->rbytes:w->data->bytes);
170 long size = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->data->rbytes:w->data->bytes;
172 if(w->last_url[0]) log_access("%llu: (sent/all = %ld/%ld bytes %0.0f%%, prep/sent/total = %0.2f/%0.2f/%0.2f ms) %s: '%s'",
174 sent, size, -((size>0)?((float)(size-sent)/(float)size * 100.0):0.0),
175 (float)usecdiff(&w->tv_ready, &w->tv_in) / 1000.0,
176 (float)usecdiff(&tv, &w->tv_ready) / 1000.0,
177 (float)usecdiff(&tv, &w->tv_in) / 1000.0,
178 (w->mode == WEB_CLIENT_MODE_FILECOPY)?"filecopy":"data",
182 debug(D_WEB_CLIENT, "%llu: Reseting client.", w->id);
184 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
185 debug(D_WEB_CLIENT, "%llu: Closing filecopy input file.", w->id);
190 w->last_url[0] = '\0';
192 w->data->contenttype = CT_TEXT_PLAIN;
193 w->mode = WEB_CLIENT_MODE_NORMAL;
199 w->response_header[0] = '\0';
200 w->data->buffer[0] = '\0';
205 // if we had enabled compression, release it
206 if(w->zinitialized) {
207 debug(D_DEFLATE, "%llu: Reseting compression.", w->id);
208 deflateEnd(&w->zstream);
212 w->zstream.avail_in = 0;
213 w->zstream.avail_out = 0;
214 w->zstream.total_in = 0;
215 w->zstream.total_out = 0;
220 void web_client_enable_deflate(struct web_client *w) {
221 if(w->zinitialized == 1) {
222 error("%llu: Compression has already be initialized for this client.", w->id);
227 error("%llu: Cannot enable compression in the middle of a conversation.", w->id);
231 w->zstream.zalloc = Z_NULL;
232 w->zstream.zfree = Z_NULL;
233 w->zstream.opaque = Z_NULL;
235 w->zstream.next_in = (Bytef *)w->data->buffer;
236 w->zstream.avail_in = 0;
237 w->zstream.total_in = 0;
239 w->zstream.next_out = w->zbuffer;
240 w->zstream.avail_out = 0;
241 w->zstream.total_out = 0;
243 w->zstream.zalloc = Z_NULL;
244 w->zstream.zfree = Z_NULL;
245 w->zstream.opaque = Z_NULL;
247 // if(deflateInit(&w->zstream, Z_DEFAULT_COMPRESSION) != Z_OK) {
248 // error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
252 // Select GZIP compression: windowbits = 15 + 16 = 31
253 if(deflateInit2(&w->zstream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY) != Z_OK) {
254 error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
262 debug(D_DEFLATE, "%llu: Initialized compression.", w->id);
265 int web_client_data_request(struct web_client *w, char *url, int datasource_type)
267 char *args = strchr(url, '?');
273 // get the name of the data to show
274 char *tok = mystrsep(&url, "/");
275 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
277 // do we have such a data set?
278 RRDSET *st = rrdset_find_byname(tok);
279 if(!st) st = rrdset_find(tok);
282 // try to send a file with that name
284 return(mysendfile(w, tok));
288 debug(D_WEB_CLIENT, "%llu: Found RRD data with name '%s'.", w->id, tok);
290 // how many entries does the client want?
291 long lines = rrd_default_history_entries;
292 long group_count = 1;
293 time_t after = 0, before = 0;
294 int group_method = GROUP_AVERAGE;
298 // parse the lines required
299 tok = mystrsep(&url, "/");
300 if(tok) lines = atoi(tok);
301 if(lines < 1) lines = 1;
304 // parse the group count required
305 tok = mystrsep(&url, "/");
306 if(tok) group_count = atoi(tok);
307 if(group_count < 1) group_count = 1;
308 //if(group_count > save_history / 20) group_count = save_history / 20;
311 // parse the grouping method required
312 tok = mystrsep(&url, "/");
313 if(strcmp(tok, "max") == 0) group_method = GROUP_MAX;
314 else if(strcmp(tok, "average") == 0) group_method = GROUP_AVERAGE;
315 else if(strcmp(tok, "sum") == 0) group_method = GROUP_SUM;
316 else debug(D_WEB_CLIENT, "%llu: Unknown group method '%s'", w->id, tok);
320 tok = mystrsep(&url, "/");
321 if(tok) after = strtoul(tok, NULL, 10);
322 if(after < 0) after = 0;
326 tok = mystrsep(&url, "/");
327 if(tok) before = strtoul(tok, NULL, 10);
328 if(before < 0) before = 0;
332 tok = mystrsep(&url, "/");
333 if(tok && strcmp(tok, "nonzero") == 0) nonzero = 1;
336 w->data->contenttype = CT_APPLICATION_JSON;
339 char *google_version = "0.6";
340 char *google_reqId = "0";
341 char *google_sig = "0";
342 char *google_out = "json";
343 char *google_responseHandler = "google.visualization.Query.setResponse";
344 char *google_outFileName = NULL;
345 unsigned long last_timestamp_in_data = 0;
346 if(datasource_type == DATASOURCE_GOOGLE_JSON || datasource_type == DATASOURCE_GOOGLE_JSONP) {
348 w->data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
351 tok = mystrsep(&args, "&");
353 char *name = mystrsep(&tok, "=");
354 if(name && strcmp(name, "tqx") == 0) {
355 char *key = mystrsep(&tok, ":");
356 char *value = mystrsep(&tok, ";");
357 if(key && value && *key && *value) {
358 if(strcmp(key, "version") == 0)
359 google_version = value;
361 else if(strcmp(key, "reqId") == 0)
362 google_reqId = value;
364 else if(strcmp(key, "sig") == 0)
367 else if(strcmp(key, "out") == 0)
370 else if(strcmp(key, "responseHandler") == 0)
371 google_responseHandler = value;
373 else if(strcmp(key, "outFileName") == 0)
374 google_outFileName = value;
380 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
381 w->id, google_version, google_reqId, google_sig, google_out, google_responseHandler, google_outFileName
384 if(datasource_type == DATASOURCE_GOOGLE_JSONP) {
385 last_timestamp_in_data = strtoul(google_sig, NULL, 0);
387 // check the client wants json
388 if(strcmp(google_out, "json") != 0) {
389 w->data->bytes = snprintf(w->data->buffer, w->data->size,
390 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'invalid_query',message:'output format is not supported',detailed_message:'the format %s requested is not supported by netdata.'}]});",
391 google_responseHandler, google_version, google_reqId, google_out);
397 if(datasource_type == DATASOURCE_GOOGLE_JSONP) {
398 w->data->bytes = snprintf(w->data->buffer, w->data->size,
399 "%s({version:'%s',reqId:'%s',status:'ok',sig:'%lu',table:",
400 google_responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
403 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending RRD data '%s' (id %s, %d lines, %d group, %d group_method, %lu after, %lu before).", w->id, st->name, st->id, lines, group_count, group_method, after, before);
404 unsigned long timestamp_in_data = rrd_stats_json(datasource_type, st, w->data, lines, group_count, group_method, after, before, nonzero);
406 if(datasource_type == DATASOURCE_GOOGLE_JSONP) {
407 if(timestamp_in_data > last_timestamp_in_data)
408 w->data->bytes += snprintf(&w->data->buffer[w->data->bytes], w->data->size - w->data->bytes, "});");
411 // the client already has the latest data
412 w->data->bytes = snprintf(w->data->buffer, w->data->size,
413 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
414 google_responseHandler, google_version, google_reqId);
421 void web_client_process(struct web_client *w)
428 // check if we have an empty line (end of HTTP header)
429 if(strstr(w->data->buffer, "\r\n\r\n")) {
430 global_statistics_lock();
431 global_statistics.web_requests++;
432 global_statistics_unlock();
434 gettimeofday(&w->tv_in, NULL);
435 debug(D_WEB_DATA, "%llu: Processing data buffer of %d bytes: '%s'.", w->id, w->data->bytes, w->data->buffer);
437 // check if the client requested keep-alive HTTP
438 if(strcasestr(w->data->buffer, "Connection: keep-alive")) w->keepalive = 1;
439 else w->keepalive = 0;
441 // check if the client accepts deflate
442 if(strstr(w->data->buffer, "gzip"))
443 web_client_enable_deflate(w);
445 int datasource_type = DATASOURCE_GOOGLE_JSONP;
446 //if(strstr(w->data->buffer, "X-DataSource-Auth"))
447 // datasource_type = DATASOURCE_GOOGLE_JSON;
449 char *buf = w->data->buffer;
450 char *tok = strsep(&buf, " \r\n");
452 char *pointer_to_free = NULL; // keep url_decode() allocated buffer
454 if(buf && strcmp(tok, "GET") == 0) {
455 tok = strsep(&buf, " \r\n");
456 pointer_to_free = url = url_decode(tok);
457 debug(D_WEB_CLIENT, "%llu: Processing HTTP GET on url '%s'.", w->id, url);
459 else if (buf && strcmp(tok, "POST") == 0) {
461 tok = strsep(&buf, " \r\n");
462 pointer_to_free = url = url_decode(tok);
464 debug(D_WEB_CLIENT, "%llu: I don't know how to handle POST with form data. Assuming it is a GET on url '%s'.", w->id, url);
467 w->last_url[0] = '\0';
469 strncpy(w->last_url, url, URL_MAX);
470 w->last_url[URL_MAX] = '\0';
472 tok = mystrsep(&url, "/?&");
474 debug(D_WEB_CLIENT, "%llu: Processing command '%s'.", w->id, tok);
476 if(strcmp(tok, WEB_PATH_DATA) == 0) { // "data"
477 // the client is requesting rrd data
478 datasource_type = DATASOURCE_JSON;
479 code = web_client_data_request(w, url, datasource_type);
481 else if(strcmp(tok, WEB_PATH_DATASOURCE) == 0) { // "datasource"
482 // the client is requesting google datasource
483 code = web_client_data_request(w, url, datasource_type);
485 else if(strcmp(tok, WEB_PATH_GRAPH) == 0) { // "graph"
486 // the client is requesting an rrd graph
488 // get the name of the data to show
489 tok = mystrsep(&url, "/?&");
490 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
492 // do we have such a data set?
493 RRDSET *st = rrdset_find_byname(tok);
496 // try to send a file with that name
498 code = mysendfile(w, tok);
502 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending %s.json of RRD_STATS...", w->id, st->name);
503 w->data->contenttype = CT_APPLICATION_JSON;
505 rrd_stats_graph_json(st, url, w->data);
508 else if(strcmp(tok, "debug") == 0) {
511 // get the name of the data to show
512 tok = mystrsep(&url, "/?&");
513 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
515 // do we have such a data set?
516 RRDSET *st = rrdset_find_byname(tok);
519 web_buffer_printf(w->data, "Chart %s is not found.\r\n", tok);
520 debug(D_WEB_CLIENT_ACCESS, "%llu: %s is not found.", w->id, tok);
524 debug_flags |= D_RRD_STATS;
525 st->debug = st->debug?0:1;
526 web_buffer_printf(w->data, "Chart %s has now debug %s.\r\n", tok, st->debug?"enabled":"disabled");
527 debug(D_WEB_CLIENT_ACCESS, "%llu: debug for %s is %s.", w->id, tok, st->debug?"enabled":"disabled");
530 else if(strcmp(tok, "mirror") == 0) {
533 debug(D_WEB_CLIENT_ACCESS, "%llu: Mirroring...", w->id);
535 // replace the zero bytes with spaces
537 for(i = 0; i < w->data->size; i++)
538 if(w->data->buffer[i] == '\0') w->data->buffer[i] = ' ';
540 // just leave the buffer as is
541 // it will be copied back to the client
543 else if(strcmp(tok, "list") == 0) {
546 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending list of RRD_STATS...", w->id);
549 RRDSET *st = rrdset_root;
551 for ( ; st ; st = st->next )
552 web_buffer_printf(w->data, "%s\n", st->name);
554 else if(strcmp(tok, "all.json") == 0) {
556 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending JSON list of all monitors of RRD_STATS...", w->id);
558 w->data->contenttype = CT_APPLICATION_JSON;
560 rrd_stats_all_json(w->data);
562 else if(strcmp(tok, "netdata.conf") == 0) {
564 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending netdata.conf ...", w->id);
566 w->data->contenttype = CT_TEXT_PLAIN;
568 generate_config(w->data, 0);
570 else if(strcmp(tok, WEB_PATH_FILE) == 0) { // "file"
571 tok = mystrsep(&url, "/?&");
572 if(tok && *tok) code = mysendfile(w, tok);
576 strcpy(w->data->buffer, "You have to give a filename to get.\r\n");
577 w->data->bytes = strlen(w->data->buffer);
582 code = mysendfile(w, "index.html");
586 code = mysendfile(w, tok);
591 strcpy(w->last_url, "not a valid response");
593 if(buf) debug(D_WEB_CLIENT_ACCESS, "%llu: Cannot understand '%s'.", w->id, buf);
597 strcpy(w->data->buffer, "I don't understand you...\r\n");
598 w->data->bytes = strlen(w->data->buffer);
601 // free url_decode() buffer
602 if(pointer_to_free) free(pointer_to_free);
604 else if(w->data->bytes > 8192) {
605 strcpy(w->last_url, "too big request");
607 debug(D_WEB_CLIENT_ACCESS, "%llu: Received request is too big.", w->id);
611 strcpy(w->data->buffer, "Received request is too big.\r\n");
612 w->data->bytes = strlen(w->data->buffer);
615 // wait for more data
620 if(w->data->bytes > w->data->size) {
621 error("%llu: memory overflow encountered (size is %ld, written %ld).", w->data->size, w->data->bytes);
624 gettimeofday(&w->tv_ready, NULL);
625 w->data->date = time(NULL);
628 // prepare the HTTP response header
629 debug(D_WEB_CLIENT, "%llu: Generating HTTP header with response %d.", w->id, code);
631 char *content_type_string = "";
632 switch(w->data->contenttype) {
634 content_type_string = "text/html";
637 case CT_APPLICATION_XML:
638 content_type_string = "application/xml";
641 case CT_APPLICATION_JSON:
642 content_type_string = "application/json";
645 case CT_APPLICATION_X_JAVASCRIPT:
646 content_type_string = "application/x-javascript";
650 content_type_string = "text/css";
654 content_type_string = "text/xml";
658 content_type_string = "text/xsl";
661 case CT_APPLICATION_OCTET_STREAM:
662 content_type_string = "application/octet-stream";
665 case CT_IMAGE_SVG_XML:
666 content_type_string = "image/svg+xml";
669 case CT_APPLICATION_X_FONT_TRUETYPE:
670 content_type_string = "application/x-font-truetype";
673 case CT_APPLICATION_X_FONT_OPENTYPE:
674 content_type_string = "application/x-font-opentype";
677 case CT_APPLICATION_FONT_WOFF:
678 content_type_string = "application/font-woff";
681 case CT_APPLICATION_VND_MS_FONTOBJ:
682 content_type_string = "application/vnd.ms-fontobject";
687 content_type_string = "text/plain";
698 code_msg = "Temporary Redirect";
702 code_msg = "Bad Request";
706 code_msg = "Forbidden";
710 code_msg = "Not Found";
714 code_msg = "Internal Server Error";
719 struct tm tm = *gmtime(&w->data->date);
720 strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %Z", &tm);
722 char custom_header[MAX_HTTP_HEADER_SIZE + 1] = "";
723 if(w->response_header[0])
724 strcpy(custom_header, w->response_header);
727 headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen,
730 "Server: NetData Embedded HTTP Server\r\n"
731 "Content-Type: %s\r\n"
732 "Access-Control-Allow-Origin: *\r\n"
735 , w->keepalive?"keep-alive":"close"
736 , content_type_string
741 headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen, "%s", custom_header);
743 if(w->mode == WEB_CLIENT_MODE_NORMAL) {
744 headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen,
746 "Cache-Control: no-cache\r\n"
751 headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen,
752 "Cache-Control: public\r\n"
756 // if we know the content length, put it
757 if(!w->zoutput && (w->data->bytes || w->data->rbytes))
758 headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen,
759 "Content-Length: %ld\r\n"
760 , w->data->bytes?w->data->bytes:w->data->rbytes
763 w->keepalive = 0; // content-length is required for keep-alive
766 headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen,
767 "Content-Encoding: gzip\r\n"
768 "Transfer-Encoding: chunked\r\n"
772 headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen, "\r\n");
774 // disable TCP_NODELAY, to buffer the header
776 if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0) error("%llu: failed to disable TCP_NODELAY on socket.", w->id);
778 // sent the HTTP header
779 debug(D_WEB_DATA, "%llu: Sending response HTTP header of size %d: '%s'", w->id, headerlen, w->response_header);
781 bytes = send(w->ofd, w->response_header, headerlen, 0);
782 if(bytes != headerlen)
783 error("%llu: HTTP Header failed to be sent (I sent %d bytes but the system sent %d bytes).", w->id, headerlen, bytes);
785 global_statistics_lock();
786 global_statistics.bytes_sent += bytes;
787 global_statistics_unlock();
790 // enable TCP_NODELAY, to send all data immediately at the next send()
792 if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0) error("%llu: failed to enable TCP_NODELAY on socket.", w->id);
794 // enable sending immediately if we have data
795 if(w->data->bytes) w->wait_send = 1;
796 else w->wait_send = 0;
800 case WEB_CLIENT_MODE_NORMAL:
801 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Sending data (%d bytes) to client.", w->id, w->data->bytes);
804 case WEB_CLIENT_MODE_FILECOPY:
805 if(w->data->rbytes) {
806 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending data file of %d bytes to client.", w->id, w->data->rbytes);
810 // utilize the kernel sendfile() for copying the file to the socket.
811 // this block of code can be commented, without anything missing.
812 // when it is commented, the program will copy the data using async I/O.
814 long len = sendfile(w->ofd, w->ifd, NULL, w->data->rbytes);
815 if(len != w->data->rbytes) error("%llu: sendfile() should copy %ld bytes, but copied %ld. Falling back to manual copy.", w->id, w->data->rbytes, len);
816 else web_client_reset(w);
821 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending an unknown amount of bytes to client.", w->id);
825 fatal("%llu: Unknown client mode %d.", w->id, w->mode);
830 long web_client_send_chunk_header(struct web_client *w, int len)
832 debug(D_DEFLATE, "%llu: OPEN CHUNK of %d bytes (hex: %x).", w->id, len, len);
834 sprintf(buf, "%X\r\n", len);
835 int bytes = send(w->ofd, buf, strlen(buf), MSG_DONTWAIT);
837 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk header %d bytes.", w->id, bytes);
838 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk header to the client.", w->id);
839 else debug(D_DEFLATE, "%llu: Failed to send chunk header to client. Reason: %s", w->id, strerror(errno));
844 long web_client_send_chunk_close(struct web_client *w)
846 //debug(D_DEFLATE, "%llu: CLOSE CHUNK.", w->id);
848 int bytes = send(w->ofd, "\r\n", 2, MSG_DONTWAIT);
850 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
851 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
852 else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client. Reason: %s", w->id, strerror(errno));
857 long web_client_send_chunk_finalize(struct web_client *w)
859 //debug(D_DEFLATE, "%llu: FINALIZE CHUNK.", w->id);
861 int bytes = send(w->ofd, "\r\n0\r\n\r\n", 7, MSG_DONTWAIT);
863 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
864 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
865 else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client. Reason: %s", w->id, strerror(errno));
870 long web_client_send_deflate(struct web_client *w)
872 long bytes = 0, t = 0;
874 // when using compression,
875 // w->data->sent is the amount of bytes passed through compression
877 // debug(D_DEFLATE, "%llu: TEST w->data->bytes = %d, w->data->sent = %d, w->zhave = %d, w->zsent = %d, w->zstream.avail_in = %d, w->zstream.avail_out = %d, w->zstream.total_in = %d, w->zstream.total_out = %d.", w->id, w->data->bytes, w->data->sent, w->zhave, w->zsent, w->zstream.avail_in, w->zstream.avail_out, w->zstream.total_in, w->zstream.total_out);
879 if(w->data->bytes - w->data->sent == 0 && w->zstream.avail_in == 0 && w->zhave == w->zsent && w->zstream.avail_out != 0) {
880 // there is nothing to send
882 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
884 // finalize the chunk
885 if(w->data->sent != 0)
886 t += web_client_send_chunk_finalize(w);
888 // there can be two cases for this
889 // A. we have done everything
890 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
892 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->data->rbytes && w->data->rbytes > w->data->bytes) {
893 // we have to wait, more data will come
894 debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
899 if(w->keepalive == 0) {
900 debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->data->sent);
907 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
911 if(w->zstream.avail_out == 0 && w->zhave == w->zsent) {
912 // compress more input data
914 // close the previous open chunk
915 if(w->data->sent != 0) t += web_client_send_chunk_close(w);
917 debug(D_DEFLATE, "%llu: Compressing %d bytes starting from %d.", w->id, (w->data->bytes - w->data->sent), w->data->sent);
919 // give the compressor all the data not passed through the compressor yet
920 if(w->data->bytes > w->data->sent) {
921 w->zstream.next_in = (Bytef *)&w->data->buffer[w->data->sent];
922 w->zstream.avail_in = (w->data->bytes - w->data->sent);
925 // reset the compressor output buffer
926 w->zstream.next_out = w->zbuffer;
927 w->zstream.avail_out = ZLIB_CHUNK;
929 // ask for FINISH if we have all the input
930 int flush = Z_SYNC_FLUSH;
931 if(w->mode == WEB_CLIENT_MODE_NORMAL
932 || (w->mode == WEB_CLIENT_MODE_FILECOPY && w->data->bytes == w->data->rbytes)) {
934 debug(D_DEFLATE, "%llu: Requesting Z_FINISH.", w->id);
937 debug(D_DEFLATE, "%llu: Requesting Z_SYNC_FLUSH.", w->id);
941 if(deflate(&w->zstream, flush) == Z_STREAM_ERROR) {
942 error("%llu: Compression failed. Closing down client.", w->id);
947 w->zhave = ZLIB_CHUNK - w->zstream.avail_out;
950 // keep track of the bytes passed through the compressor
951 w->data->sent = w->data->bytes;
953 debug(D_DEFLATE, "%llu: Compression produced %d bytes.", w->id, w->zhave);
956 t += web_client_send_chunk_header(w, w->zhave);
959 bytes = send(w->ofd, &w->zbuffer[w->zsent], w->zhave - w->zsent, MSG_DONTWAIT);
962 if(t > 0) bytes += t;
963 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, bytes);
965 else if(bytes == 0) debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client.", w->id);
966 else debug(D_WEB_CLIENT, "%llu: Failed to send data to client. Reason: %s", w->id, strerror(errno));
971 long web_client_send(struct web_client *w)
973 if(w->zoutput) return web_client_send_deflate(w);
977 if(w->data->bytes - w->data->sent == 0) {
978 // there is nothing to send
980 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
982 // there can be two cases for this
983 // A. we have done everything
984 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
986 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->data->rbytes && w->data->rbytes > w->data->bytes) {
987 // we have to wait, more data will come
988 debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
993 if(w->keepalive == 0) {
994 debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->data->sent);
1000 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1004 bytes = send(w->ofd, &w->data->buffer[w->data->sent], w->data->bytes - w->data->sent, MSG_DONTWAIT);
1006 w->data->sent += bytes;
1007 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, bytes);
1009 else if(bytes == 0) debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client.", w->id);
1010 else debug(D_WEB_CLIENT, "%llu: Failed to send data to client. Reason: %s", w->id, strerror(errno));
1016 long web_client_receive(struct web_client *w)
1018 // do we have any space for more data?
1019 web_buffer_increase(w->data, WEB_DATA_LENGTH_INCREASE_STEP);
1021 long left = w->data->size - w->data->bytes;
1024 if(w->mode == WEB_CLIENT_MODE_FILECOPY)
1025 bytes = read(w->ifd, &w->data->buffer[w->data->bytes], (left-1));
1027 bytes = recv(w->ifd, &w->data->buffer[w->data->bytes], left-1, MSG_DONTWAIT);
1030 int old = w->data->bytes;
1031 w->data->bytes += bytes;
1032 w->data->buffer[w->data->bytes] = '\0';
1034 debug(D_WEB_CLIENT, "%llu: Received %d bytes.", w->id, bytes);
1035 debug(D_WEB_DATA, "%llu: Received data: '%s'.", w->id, &w->data->buffer[old]);
1037 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1039 if(w->data->rbytes && w->data->bytes >= w->data->rbytes) w->wait_receive = 0;
1042 else if(bytes == 0) {
1043 debug(D_WEB_CLIENT, "%llu: Out of input data.", w->id);
1045 // if we cannot read, it means we have an error on input.
1046 // if however, we are copying a file from ifd to ofd, we should not return an error.
1047 // in this case, the error should be generated when the file has been sent to the client.
1049 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1050 // we are copying data fron ifd to ofd
1051 // let it finish copying...
1052 w->wait_receive = 0;
1053 debug(D_WEB_CLIENT, "%llu: Disabling input.", w->id);
1065 // --------------------------------------------------------------------------------------
1066 // the thread of a single client
1068 // 1. waits for input and output, using async I/O
1069 // 2. it processes HTTP requests
1070 // 3. it generates HTTP responses
1071 // 4. it copies data from input to output if mode is FILECOPY
1073 void *new_client(void *ptr)
1075 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
1076 error("Cannot set pthread cancel type to DEFERRED.");
1078 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
1079 error("Cannot set pthread cancel state to ENABLE.");
1082 struct web_client *w = ptr;
1084 fd_set ifds, ofds, efds;
1092 FD_SET(w->ifd, &efds);
1093 if(w->ifd != w->ofd) FD_SET(w->ofd, &efds);
1094 if (w->wait_receive) {
1095 FD_SET(w->ifd, &ifds);
1096 if(w->ifd > fdmax) fdmax = w->ifd;
1099 FD_SET(w->ofd, &ofds);
1100 if(w->ofd > fdmax) fdmax = w->ofd;
1106 debug(D_WEB_CLIENT, "%llu: Waiting socket async I/O for %s %s", w->id, w->wait_receive?"INPUT":"", w->wait_send?"OUTPUT":"");
1107 retval = select(fdmax+1, &ifds, &ofds, &efds, &tv);
1110 error("%llu: LISTENER: select() failed.", w->id);
1115 web_client_reset(w);
1120 if(FD_ISSET(w->ifd, &efds)) {
1121 debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on input socket (%s).", w->id, strerror(errno));
1122 web_client_reset(w);
1127 if(FD_ISSET(w->ofd, &efds)) {
1128 debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on output socket (%s).", w->id, strerror(errno));
1129 web_client_reset(w);
1134 if(w->wait_send && FD_ISSET(w->ofd, &ofds)) {
1136 if((bytes = web_client_send(w)) < 0) {
1137 debug(D_WEB_CLIENT, "%llu: Closing client (input: %s).", w->id, strerror(errno));
1138 web_client_reset(w);
1144 global_statistics_lock();
1145 global_statistics.bytes_sent += bytes;
1146 global_statistics_unlock();
1150 if(w->wait_receive && FD_ISSET(w->ifd, &ifds)) {
1152 if((bytes = web_client_receive(w)) < 0) {
1153 debug(D_WEB_CLIENT, "%llu: Closing client (output: %s).", w->id, strerror(errno));
1154 web_client_reset(w);
1160 if(w->mode != WEB_CLIENT_MODE_FILECOPY) {
1161 global_statistics_lock();
1162 global_statistics.bytes_received += bytes;
1163 global_statistics_unlock();
1167 if(w->mode == WEB_CLIENT_MODE_NORMAL) web_client_process(w);
1170 debug(D_WEB_CLIENT, "%llu: done...", w->id);
1175 // --------------------------------------------------------------------------------------
1176 // the main socket listener
1178 // 1. it accepts new incoming requests on our port
1179 // 2. creates a new web_client for each connection received
1180 // 3. spawns a new pthread to serve the client (this is optimal for keep-alive clients)
1181 // 4. cleans up old web_clients that their pthreads have been exited
1183 void *socket_listen_main(void *ptr)
1186 struct web_client *w;
1192 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
1193 error("Cannot set pthread cancel type to DEFERRED.");
1195 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
1196 error("Cannot set pthread cancel state to ENABLE.");
1198 // int listener = create_listen_socket(listen_port);
1199 int listener = listen_fd;
1200 if(listener == -1) fatal("LISTENER: Cannot create listening socket on port 19999.");
1202 fd_set ifds, ofds, efds;
1203 int fdmax = listener;
1211 tv.tv_usec = 200000;
1213 FD_SET(listener, &ifds);
1214 FD_SET(listener, &efds);
1216 // debug(D_WEB_CLIENT, "LISTENER: Waiting...");
1217 retval = select(fdmax+1, &ifds, &ofds, &efds, &tv);
1220 error("LISTENER: select() failed.");
1224 // check for new incoming connections
1225 if(FD_ISSET(listener, &ifds)) {
1226 w = web_client_create(listener);
1228 if(pthread_create(&w->thread, NULL, new_client, w) != 0) {
1229 error("%llu: failed to create new thread for web client.");
1232 else if(pthread_detach(w->thread) != 0) {
1233 error("%llu: Cannot request detach of newly created web client thread.", w->id);
1237 log_access("%llu: %s connected", w->id, w->client_ip);
1239 else debug(D_WEB_CLIENT, "LISTENER: select() didn't do anything.");
1243 // debug(D_WEB_CLIENT, "LISTENER: select() timeout.");
1246 // cleanup unused clients
1247 for(w = web_clients; w ; w = w?w->next:NULL) {
1249 log_access("%llu: %s disconnected", w->id, w->client_ip);
1250 debug(D_WEB_CLIENT, "%llu: Removing client.", w->id);
1251 // pthread_join(w->thread, NULL);
1252 w = web_client_free(w);
1258 error("LISTENER: exit!");