6 #include <sys/socket.h>
7 #include <netinet/in.h>
13 #include <netinet/tcp.h>
19 #include "web_buffer.h"
20 #include "web_client.h"
21 #include "web_server.h"
22 #include "global_statistics.h"
27 int listen_port = LISTEN_PORT;
29 int create_listen_socket(int port)
33 struct sockaddr_in name;
35 debug(D_LISTENER, "Creating new listening socket on port %d", port);
37 sock = socket(AF_INET, SOCK_STREAM, 0);
39 fatal("socket() failed, errno=%d", errno);
41 /* avoid "address already in use" */
42 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*)&sockopt, sizeof(sockopt));
44 memset(&name, 0, sizeof(struct sockaddr_in));
45 name.sin_family = AF_INET;
46 name.sin_port = htons (port);
47 name.sin_addr.s_addr = htonl (INADDR_ANY);
48 if (bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0)
49 fatal("bind() failed, errno=%d", errno);
51 if (listen(sock, LISTEN_BACKLOG) < 0)
52 fatal("listen() failed, errno=%d", errno);
54 debug(D_LISTENER, "Listening Port %d created", port);
59 int mysendfile(struct web_client *w, char *filename)
61 static char *web_dir = NULL;
62 if(!web_dir) web_dir = config_get("global", "web files directory", "web");
64 debug(D_WEB_CLIENT, "%llu: Looking for file '%s'...", w->id, filename);
66 // skip leading slashes
67 while (*filename == '/') filename++;
69 // if the filename contain known paths, skip them
70 if(strncmp(filename, WEB_PATH_DATA "/", strlen(WEB_PATH_DATA) + 1) == 0) filename = &filename[strlen(WEB_PATH_DATA) + 1];
71 else if(strncmp(filename, WEB_PATH_DATASOURCE "/", strlen(WEB_PATH_DATASOURCE) + 1) == 0) filename = &filename[strlen(WEB_PATH_DATASOURCE) + 1];
72 else if(strncmp(filename, WEB_PATH_GRAPH "/", strlen(WEB_PATH_GRAPH) + 1) == 0) filename = &filename[strlen(WEB_PATH_GRAPH) + 1];
73 else if(strncmp(filename, WEB_PATH_FILE "/", strlen(WEB_PATH_FILE) + 1) == 0) filename = &filename[strlen(WEB_PATH_FILE) + 1];
75 // if the filename contains a / or a .., refuse to serve it
76 if(strchr(filename, '/') != 0 || strstr(filename, "..") != 0) {
77 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
78 web_buffer_printf(w->data, "File '%s' cannot be served. Filenames cannot contain / or ..", filename);
83 char webfilename[FILENAME_MAX + 1];
84 snprintf(webfilename, FILENAME_MAX, "%s/%s", web_dir, filename);
86 // check if the file exists
88 if(lstat(webfilename, &stat) != 0) {
89 error("%llu: File '%s' is not found.", w->id, webfilename);
90 web_buffer_printf(w->data, "File '%s' does not exist, or is not accessible.", filename);
94 // check if the file is owned by us
95 if(stat.st_uid != getuid() && stat.st_uid != geteuid()) {
96 error("%llu: File '%s' is owned by user %d (I run as user %d). Access Denied.", w->id, webfilename, stat.st_uid, getuid());
97 web_buffer_printf(w->data, "Access to file '%s' is not permitted.", filename);
102 w->ifd = open(webfilename, O_NONBLOCK, O_RDONLY);
106 if(errno == EBUSY || errno == EAGAIN) {
107 error("%llu: File '%s' is busy, sending 307 Moved Temporarily to force retry.", w->id, webfilename);
108 snprintf(w->response_header, MAX_HTTP_HEADER_SIZE, "Location: /" WEB_PATH_FILE "/%s\r\n", filename);
109 web_buffer_printf(w->data, "The file '%s' is currently busy. Please try again later.", filename);
113 error("%llu: Cannot open file '%s'.", w->id, webfilename);
114 web_buffer_printf(w->data, "Cannot open file '%s'.", filename);
119 // pick a Content-Type for the file
120 if(strstr(filename, ".html") != NULL) w->data->contenttype = CT_TEXT_HTML;
121 else if(strstr(filename, ".js") != NULL) w->data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
122 else if(strstr(filename, ".css") != NULL) w->data->contenttype = CT_TEXT_CSS;
123 else if(strstr(filename, ".xml") != NULL) w->data->contenttype = CT_TEXT_XML;
124 else if(strstr(filename, ".xsl") != NULL) w->data->contenttype = CT_TEXT_XSL;
125 else if(strstr(filename, ".txt") != NULL) w->data->contenttype = CT_TEXT_PLAIN;
126 else if(strstr(filename, ".svg") != NULL) w->data->contenttype = CT_IMAGE_SVG_XML;
127 else if(strstr(filename, ".ttf") != NULL) w->data->contenttype = CT_APPLICATION_X_FONT_TRUETYPE;
128 else if(strstr(filename, ".otf") != NULL) w->data->contenttype = CT_APPLICATION_X_FONT_OPENTYPE;
129 else if(strstr(filename, ".woff") != NULL) w->data->contenttype = CT_APPLICATION_FONT_WOFF;
130 else if(strstr(filename, ".eot") != NULL) w->data->contenttype = CT_APPLICATION_VND_MS_FONTOBJ;
131 else w->data->contenttype = CT_APPLICATION_OCTET_STREAM;
133 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending file '%s' (%ld bytes, ifd %d, ofd %d).", w->id, webfilename, stat.st_size, w->ifd, w->ofd);
135 w->mode = WEB_CLIENT_MODE_FILECOPY;
139 w->data->buffer[0] = '\0';
140 w->data->rbytes = stat.st_size;
141 w->data->date = stat.st_mtim.tv_sec;
146 void web_client_reset(struct web_client *w)
149 gettimeofday(&tv, NULL);
151 long sent = w->zoutput?(long)w->zstream.total_out:((w->mode == WEB_CLIENT_MODE_FILECOPY)?w->data->rbytes:w->data->bytes);
152 long size = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->data->rbytes:w->data->bytes;
154 if(w->last_url[0]) log_access("%llu: (sent/all = %ld/%ld bytes %0.0f%%, prep/sent/total = %0.2f/%0.2f/%0.2f ms) %s: '%s'",
156 sent, size, -((size>0)?((float)(size-sent)/(float)size * 100.0):0.0),
157 (float)usecdiff(&w->tv_ready, &w->tv_in) / 1000.0,
158 (float)usecdiff(&tv, &w->tv_ready) / 1000.0,
159 (float)usecdiff(&tv, &w->tv_in) / 1000.0,
160 (w->mode == WEB_CLIENT_MODE_FILECOPY)?"filecopy":"data",
164 debug(D_WEB_CLIENT, "%llu: Reseting client.", w->id);
166 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
167 debug(D_WEB_CLIENT, "%llu: Closing filecopy input file.", w->id);
172 w->last_url[0] = '\0';
174 w->data->contenttype = CT_TEXT_PLAIN;
175 w->mode = WEB_CLIENT_MODE_NORMAL;
181 w->response_header[0] = '\0';
182 w->data->buffer[0] = '\0';
187 // if we had enabled compression, release it
188 if(w->zinitialized) {
189 debug(D_DEFLATE, "%llu: Reseting compression.", w->id);
190 deflateEnd(&w->zstream);
194 w->zstream.avail_in = 0;
195 w->zstream.avail_out = 0;
196 w->zstream.total_in = 0;
197 w->zstream.total_out = 0;
202 void web_client_enable_deflate(struct web_client *w) {
203 if(w->zinitialized == 1) {
204 error("%llu: Compression has already be initialized for this client.", w->id);
209 error("%llu: Cannot enable compression in the middle of a conversation.", w->id);
213 w->zstream.zalloc = Z_NULL;
214 w->zstream.zfree = Z_NULL;
215 w->zstream.opaque = Z_NULL;
217 w->zstream.next_in = (Bytef *)w->data->buffer;
218 w->zstream.avail_in = 0;
219 w->zstream.total_in = 0;
221 w->zstream.next_out = w->zbuffer;
222 w->zstream.avail_out = 0;
223 w->zstream.total_out = 0;
225 w->zstream.zalloc = Z_NULL;
226 w->zstream.zfree = Z_NULL;
227 w->zstream.opaque = Z_NULL;
229 // if(deflateInit(&w->zstream, Z_DEFAULT_COMPRESSION) != Z_OK) {
230 // error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
234 // Select GZIP compression: windowbits = 15 + 16 = 31
235 if(deflateInit2(&w->zstream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY) != Z_OK) {
236 error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
244 debug(D_DEFLATE, "%llu: Initialized compression.", w->id);
247 int web_client_data_request(struct web_client *w, char *url, int datasource_type)
249 char *args = strchr(url, '?');
255 // get the name of the data to show
256 char *tok = mystrsep(&url, "/");
257 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
259 // do we have such a data set?
260 RRD_STATS *st = rrd_stats_find_byname(tok);
261 if(!st) st = rrd_stats_find(tok);
264 // try to send a file with that name
266 return(mysendfile(w, tok));
270 debug(D_WEB_CLIENT, "%llu: Found RRD data with name '%s'.", w->id, tok);
272 // how many entries does the client want?
273 long lines = save_history;
274 long group_count = 1;
275 time_t after = 0, before = 0;
276 int group_method = GROUP_AVERAGE;
280 // parse the lines required
281 tok = mystrsep(&url, "/");
282 if(tok) lines = atoi(tok);
283 if(lines < 1) lines = 1;
286 // parse the group count required
287 tok = mystrsep(&url, "/");
288 if(tok) group_count = atoi(tok);
289 if(group_count < 1) group_count = 1;
290 //if(group_count > save_history / 20) group_count = save_history / 20;
293 // parse the grouping method required
294 tok = mystrsep(&url, "/");
295 if(strcmp(tok, "max") == 0) group_method = GROUP_MAX;
296 else if(strcmp(tok, "average") == 0) group_method = GROUP_AVERAGE;
297 else if(strcmp(tok, "sum") == 0) group_method = GROUP_SUM;
298 else debug(D_WEB_CLIENT, "%llu: Unknown group method '%s'", w->id, tok);
302 tok = mystrsep(&url, "/");
303 if(tok) after = strtoul(tok, NULL, 10);
304 if(after < 0) after = 0;
308 tok = mystrsep(&url, "/");
309 if(tok) before = strtoul(tok, NULL, 10);
310 if(before < 0) before = 0;
314 tok = mystrsep(&url, "/");
315 if(tok && strcmp(tok, "nonzero") == 0) nonzero = 1;
318 w->data->contenttype = CT_APPLICATION_JSON;
321 char *google_version = "0.6";
322 char *google_reqId = "0";
323 char *google_sig = "0";
324 char *google_out = "json";
325 char *google_responseHandler = "google.visualization.Query.setResponse";
326 char *google_outFileName = NULL;
327 unsigned long last_timestamp_in_data = 0;
328 if(datasource_type == DATASOURCE_GOOGLE_JSON || datasource_type == DATASOURCE_GOOGLE_JSONP) {
330 w->data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
333 tok = mystrsep(&args, "&");
335 char *name = mystrsep(&tok, "=");
336 if(name && strcmp(name, "tqx") == 0) {
337 char *key = mystrsep(&tok, ":");
338 char *value = mystrsep(&tok, ";");
339 if(key && value && *key && *value) {
340 if(strcmp(key, "version") == 0)
341 google_version = value;
343 else if(strcmp(key, "reqId") == 0)
344 google_reqId = value;
346 else if(strcmp(key, "sig") == 0)
349 else if(strcmp(key, "out") == 0)
352 else if(strcmp(key, "responseHandler") == 0)
353 google_responseHandler = value;
355 else if(strcmp(key, "outFileName") == 0)
356 google_outFileName = value;
362 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
363 w->id, google_version, google_reqId, google_sig, google_out, google_responseHandler, google_outFileName
366 if(datasource_type == DATASOURCE_GOOGLE_JSONP) {
367 last_timestamp_in_data = strtoul(google_sig, NULL, 0);
369 // check the client wants json
370 if(strcmp(google_out, "json") != 0) {
371 w->data->bytes = snprintf(w->data->buffer, w->data->size,
372 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'invalid_query',message:'output format is not supported',detailed_message:'the format %s requested is not supported by netdata.'}]});",
373 google_responseHandler, google_version, google_reqId, google_out);
379 if(datasource_type == DATASOURCE_GOOGLE_JSONP) {
380 w->data->bytes = snprintf(w->data->buffer, w->data->size,
381 "%s({version:'%s',reqId:'%s',status:'ok',sig:'%lu',table:",
382 google_responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
385 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending RRD data '%s' (id %s, %d lines, %d group, %d group_method, %lu after, %lu before).", w->id, st->name, st->id, lines, group_count, group_method, after, before);
386 unsigned long timestamp_in_data = rrd_stats_json(datasource_type, st, w->data, lines, group_count, group_method, after, before, nonzero);
388 if(datasource_type == DATASOURCE_GOOGLE_JSONP) {
389 if(timestamp_in_data > last_timestamp_in_data)
390 w->data->bytes += snprintf(&w->data->buffer[w->data->bytes], w->data->size - w->data->bytes, "});");
393 // the client already has the latest data
394 w->data->bytes = snprintf(w->data->buffer, w->data->size,
395 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
396 google_responseHandler, google_version, google_reqId);
403 void web_client_process(struct web_client *w)
410 // check if we have an empty line (end of HTTP header)
411 if(strstr(w->data->buffer, "\r\n\r\n")) {
412 global_statistics_lock();
413 global_statistics.web_requests++;
414 global_statistics_unlock();
416 gettimeofday(&w->tv_in, NULL);
417 debug(D_WEB_DATA, "%llu: Processing data buffer of %d bytes: '%s'.", w->id, w->data->bytes, w->data->buffer);
419 // check if the client requested keep-alive HTTP
420 if(strcasestr(w->data->buffer, "Connection: keep-alive")) w->keepalive = 1;
421 else w->keepalive = 0;
423 // check if the client accepts deflate
424 if(strstr(w->data->buffer, "gzip"))
425 web_client_enable_deflate(w);
427 int datasource_type = DATASOURCE_GOOGLE_JSONP;
428 //if(strstr(w->data->buffer, "X-DataSource-Auth"))
429 // datasource_type = DATASOURCE_GOOGLE_JSON;
431 char *buf = w->data->buffer;
432 char *tok = strsep(&buf, " \r\n");
434 char *pointer_to_free = NULL; // keep url_decode() allocated buffer
436 if(buf && strcmp(tok, "GET") == 0) {
437 tok = strsep(&buf, " \r\n");
438 pointer_to_free = url = url_decode(tok);
439 debug(D_WEB_CLIENT, "%llu: Processing HTTP GET on url '%s'.", w->id, url);
441 else if (buf && strcmp(tok, "POST") == 0) {
443 tok = strsep(&buf, " \r\n");
444 pointer_to_free = url = url_decode(tok);
446 debug(D_WEB_CLIENT, "%llu: I don't know how to handle POST with form data. Assuming it is a GET on url '%s'.", w->id, url);
449 w->last_url[0] = '\0';
451 strncpy(w->last_url, url, URL_MAX);
452 w->last_url[URL_MAX] = '\0';
454 tok = mystrsep(&url, "/?&");
456 debug(D_WEB_CLIENT, "%llu: Processing command '%s'.", w->id, tok);
458 if(strcmp(tok, WEB_PATH_DATA) == 0) { // "data"
459 // the client is requesting rrd data
460 datasource_type = DATASOURCE_JSON;
461 code = web_client_data_request(w, url, datasource_type);
463 else if(strcmp(tok, WEB_PATH_DATASOURCE) == 0) { // "datasource"
464 // the client is requesting google datasource
465 code = web_client_data_request(w, url, datasource_type);
467 else if(strcmp(tok, WEB_PATH_GRAPH) == 0) { // "graph"
468 // the client is requesting an rrd graph
470 // get the name of the data to show
471 tok = mystrsep(&url, "/?&");
472 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
474 // do we have such a data set?
475 RRD_STATS *st = rrd_stats_find_byname(tok);
478 // try to send a file with that name
480 code = mysendfile(w, tok);
484 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending %s.json of RRD_STATS...", w->id, st->name);
485 w->data->contenttype = CT_APPLICATION_JSON;
487 rrd_stats_graph_json(st, url, w->data);
490 else if(strcmp(tok, "debug") == 0) {
493 // get the name of the data to show
494 tok = mystrsep(&url, "/?&");
495 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
497 // do we have such a data set?
498 RRD_STATS *st = rrd_stats_find_byname(tok);
501 web_buffer_printf(w->data, "Chart %s is not found.\r\n", tok);
502 debug(D_WEB_CLIENT_ACCESS, "%llu: %s is not found.", w->id, tok);
506 debug_flags |= D_RRD_STATS;
507 st->debug = st->debug?0:1;
508 web_buffer_printf(w->data, "Chart %s has now debug %s.\r\n", tok, st->debug?"enabled":"disabled");
509 debug(D_WEB_CLIENT_ACCESS, "%llu: debug for %s is %s.", w->id, tok, st->debug?"enabled":"disabled");
512 else if(strcmp(tok, "mirror") == 0) {
515 debug(D_WEB_CLIENT_ACCESS, "%llu: Mirroring...", w->id);
517 // replace the zero bytes with spaces
519 for(i = 0; i < w->data->size; i++)
520 if(w->data->buffer[i] == '\0') w->data->buffer[i] = ' ';
522 // just leave the buffer as is
523 // it will be copied back to the client
525 else if(strcmp(tok, "list") == 0) {
528 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending list of RRD_STATS...", w->id);
531 RRD_STATS *st = root;
533 for ( ; st ; st = st->next )
534 web_buffer_printf(w->data, "%s\n", st->name);
536 else if(strcmp(tok, "all.json") == 0) {
538 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending JSON list of all monitors of RRD_STATS...", w->id);
540 w->data->contenttype = CT_APPLICATION_JSON;
542 rrd_stats_all_json(w->data);
544 else if(strcmp(tok, "netdata.conf") == 0) {
546 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending netdata.conf ...", w->id);
548 w->data->contenttype = CT_TEXT_PLAIN;
550 generate_config(w->data, 0);
552 else if(strcmp(tok, WEB_PATH_FILE) == 0) { // "file"
553 tok = mystrsep(&url, "/?&");
554 if(tok && *tok) code = mysendfile(w, tok);
558 strcpy(w->data->buffer, "You have to give a filename to get.\r\n");
559 w->data->bytes = strlen(w->data->buffer);
564 code = mysendfile(w, "index.html");
568 code = mysendfile(w, tok);
573 strcpy(w->last_url, "not a valid response");
575 if(buf) debug(D_WEB_CLIENT_ACCESS, "%llu: Cannot understand '%s'.", w->id, buf);
579 strcpy(w->data->buffer, "I don't understand you...\r\n");
580 w->data->bytes = strlen(w->data->buffer);
583 // free url_decode() buffer
584 if(pointer_to_free) free(pointer_to_free);
586 else if(w->data->bytes > 8192) {
587 strcpy(w->last_url, "too big request");
589 debug(D_WEB_CLIENT_ACCESS, "%llu: Received request is too big.", w->id);
593 strcpy(w->data->buffer, "Received request is too big.\r\n");
594 w->data->bytes = strlen(w->data->buffer);
597 // wait for more data
602 if(w->data->bytes > w->data->size) {
603 error("%llu: memory overflow encountered (size is %ld, written %ld).", w->data->size, w->data->bytes);
606 gettimeofday(&w->tv_ready, NULL);
607 w->data->date = time(NULL);
610 // prepare the HTTP response header
611 debug(D_WEB_CLIENT, "%llu: Generating HTTP header with response %d.", w->id, code);
613 char *content_type_string = "";
614 switch(w->data->contenttype) {
616 content_type_string = "text/html";
619 case CT_APPLICATION_XML:
620 content_type_string = "application/xml";
623 case CT_APPLICATION_JSON:
624 content_type_string = "application/json";
627 case CT_APPLICATION_X_JAVASCRIPT:
628 content_type_string = "application/x-javascript";
632 content_type_string = "text/css";
636 content_type_string = "text/xml";
640 content_type_string = "text/xsl";
643 case CT_APPLICATION_OCTET_STREAM:
644 content_type_string = "application/octet-stream";
647 case CT_IMAGE_SVG_XML:
648 content_type_string = "image/svg+xml";
651 case CT_APPLICATION_X_FONT_TRUETYPE:
652 content_type_string = "application/x-font-truetype";
655 case CT_APPLICATION_X_FONT_OPENTYPE:
656 content_type_string = "application/x-font-opentype";
659 case CT_APPLICATION_FONT_WOFF:
660 content_type_string = "application/font-woff";
663 case CT_APPLICATION_VND_MS_FONTOBJ:
664 content_type_string = "application/vnd.ms-fontobject";
669 content_type_string = "text/plain";
680 code_msg = "Temporary Redirect";
684 code_msg = "Bad Request";
688 code_msg = "Forbidden";
692 code_msg = "Not Found";
696 code_msg = "Internal Server Error";
701 struct tm tm = *gmtime(&w->data->date);
702 strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %Z", &tm);
704 char custom_header[MAX_HTTP_HEADER_SIZE + 1] = "";
705 if(w->response_header[0])
706 strcpy(custom_header, w->response_header);
709 headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen,
712 "Server: NetData Embedded HTTP Server\r\n"
713 "Content-Type: %s\r\n"
714 "Access-Control-Allow-Origin: *\r\n"
717 , w->keepalive?"keep-alive":"close"
718 , content_type_string
723 headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen, "%s", custom_header);
725 if(w->mode == WEB_CLIENT_MODE_NORMAL) {
726 headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen,
728 "Cache-Control: no-cache\r\n"
733 headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen,
734 "Cache-Control: public\r\n"
738 // if we know the content length, put it
739 if(!w->zoutput && (w->data->bytes || w->data->rbytes))
740 headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen,
741 "Content-Length: %ld\r\n"
742 , w->data->bytes?w->data->bytes:w->data->rbytes
745 w->keepalive = 0; // content-length is required for keep-alive
748 headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen,
749 "Content-Encoding: gzip\r\n"
750 "Transfer-Encoding: chunked\r\n"
754 headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen, "\r\n");
756 // disable TCP_NODELAY, to buffer the header
758 if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0) error("%llu: failed to disable TCP_NODELAY on socket.", w->id);
760 // sent the HTTP header
761 debug(D_WEB_DATA, "%llu: Sending response HTTP header of size %d: '%s'", w->id, headerlen, w->response_header);
763 bytes = send(w->ofd, w->response_header, headerlen, 0);
764 if(bytes != headerlen)
765 error("%llu: HTTP Header failed to be sent (I sent %d bytes but the system sent %d bytes).", w->id, headerlen, bytes);
767 global_statistics_lock();
768 global_statistics.bytes_sent += bytes;
769 global_statistics_unlock();
772 // enable TCP_NODELAY, to send all data immediately at the next send()
774 if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0) error("%llu: failed to enable TCP_NODELAY on socket.", w->id);
776 // enable sending immediately if we have data
777 if(w->data->bytes) w->wait_send = 1;
778 else w->wait_send = 0;
782 case WEB_CLIENT_MODE_NORMAL:
783 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Sending data (%d bytes) to client.", w->id, w->data->bytes);
786 case WEB_CLIENT_MODE_FILECOPY:
787 if(w->data->rbytes) {
788 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending data file of %d bytes to client.", w->id, w->data->rbytes);
792 // utilize the kernel sendfile() for copying the file to the socket.
793 // this block of code can be commented, without anything missing.
794 // when it is commented, the program will copy the data using async I/O.
796 long len = sendfile(w->ofd, w->ifd, NULL, w->data->rbytes);
797 if(len != w->data->rbytes) error("%llu: sendfile() should copy %ld bytes, but copied %ld. Falling back to manual copy.", w->id, w->data->rbytes, len);
798 else web_client_reset(w);
803 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending an unknown amount of bytes to client.", w->id);
807 fatal("%llu: Unknown client mode %d.", w->id, w->mode);
812 long web_client_send_chunk_header(struct web_client *w, int len)
814 debug(D_DEFLATE, "%llu: OPEN CHUNK of %d bytes (hex: %x).", w->id, len, len);
816 sprintf(buf, "%X\r\n", len);
817 int bytes = send(w->ofd, buf, strlen(buf), MSG_DONTWAIT);
819 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk header %d bytes.", w->id, bytes);
820 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk header to the client.", w->id);
821 else debug(D_DEFLATE, "%llu: Failed to send chunk header to client. Reason: %s", w->id, strerror(errno));
826 long web_client_send_chunk_close(struct web_client *w)
828 //debug(D_DEFLATE, "%llu: CLOSE CHUNK.", w->id);
830 int bytes = send(w->ofd, "\r\n", 2, MSG_DONTWAIT);
832 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
833 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
834 else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client. Reason: %s", w->id, strerror(errno));
839 long web_client_send_chunk_finalize(struct web_client *w)
841 //debug(D_DEFLATE, "%llu: FINALIZE CHUNK.", w->id);
843 int bytes = send(w->ofd, "\r\n0\r\n\r\n", 7, MSG_DONTWAIT);
845 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
846 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
847 else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client. Reason: %s", w->id, strerror(errno));
852 long web_client_send_deflate(struct web_client *w)
854 long bytes = 0, t = 0;
856 // when using compression,
857 // w->data->sent is the amount of bytes passed through compression
859 // debug(D_DEFLATE, "%llu: TEST w->data->bytes = %d, w->data->sent = %d, w->zhave = %d, w->zsent = %d, w->zstream.avail_in = %d, w->zstream.avail_out = %d, w->zstream.total_in = %d, w->zstream.total_out = %d.", w->id, w->data->bytes, w->data->sent, w->zhave, w->zsent, w->zstream.avail_in, w->zstream.avail_out, w->zstream.total_in, w->zstream.total_out);
861 if(w->data->bytes - w->data->sent == 0 && w->zstream.avail_in == 0 && w->zhave == w->zsent && w->zstream.avail_out != 0) {
862 // there is nothing to send
864 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
866 // finalize the chunk
867 if(w->data->sent != 0)
868 t += web_client_send_chunk_finalize(w);
870 // there can be two cases for this
871 // A. we have done everything
872 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
874 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->data->rbytes && w->data->rbytes > w->data->bytes) {
875 // we have to wait, more data will come
876 debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
881 if(w->keepalive == 0) {
882 debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->data->sent);
889 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
893 if(w->zstream.avail_out == 0 && w->zhave == w->zsent) {
894 // compress more input data
896 // close the previous open chunk
897 if(w->data->sent != 0) t += web_client_send_chunk_close(w);
899 debug(D_DEFLATE, "%llu: Compressing %d bytes starting from %d.", w->id, (w->data->bytes - w->data->sent), w->data->sent);
901 // give the compressor all the data not passed through the compressor yet
902 if(w->data->bytes > w->data->sent) {
903 w->zstream.next_in = (Bytef *)&w->data->buffer[w->data->sent];
904 w->zstream.avail_in = (w->data->bytes - w->data->sent);
907 // reset the compressor output buffer
908 w->zstream.next_out = w->zbuffer;
909 w->zstream.avail_out = ZLIB_CHUNK;
911 // ask for FINISH if we have all the input
912 int flush = Z_SYNC_FLUSH;
913 if(w->mode == WEB_CLIENT_MODE_NORMAL
914 || (w->mode == WEB_CLIENT_MODE_FILECOPY && w->data->bytes == w->data->rbytes)) {
916 debug(D_DEFLATE, "%llu: Requesting Z_FINISH.", w->id);
919 debug(D_DEFLATE, "%llu: Requesting Z_SYNC_FLUSH.", w->id);
923 if(deflate(&w->zstream, flush) == Z_STREAM_ERROR) {
924 error("%llu: Compression failed. Closing down client.", w->id);
929 w->zhave = ZLIB_CHUNK - w->zstream.avail_out;
932 // keep track of the bytes passed through the compressor
933 w->data->sent = w->data->bytes;
935 debug(D_DEFLATE, "%llu: Compression produced %d bytes.", w->id, w->zhave);
938 t += web_client_send_chunk_header(w, w->zhave);
941 bytes = send(w->ofd, &w->zbuffer[w->zsent], w->zhave - w->zsent, MSG_DONTWAIT);
944 if(t > 0) bytes += t;
945 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, bytes);
947 else if(bytes == 0) debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client.", w->id);
948 else debug(D_WEB_CLIENT, "%llu: Failed to send data to client. Reason: %s", w->id, strerror(errno));
953 long web_client_send(struct web_client *w)
955 if(w->zoutput) return web_client_send_deflate(w);
959 if(w->data->bytes - w->data->sent == 0) {
960 // there is nothing to send
962 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
964 // there can be two cases for this
965 // A. we have done everything
966 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
968 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->data->rbytes && w->data->rbytes > w->data->bytes) {
969 // we have to wait, more data will come
970 debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
975 if(w->keepalive == 0) {
976 debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->data->sent);
982 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
986 bytes = send(w->ofd, &w->data->buffer[w->data->sent], w->data->bytes - w->data->sent, MSG_DONTWAIT);
988 w->data->sent += bytes;
989 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, bytes);
991 else if(bytes == 0) debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client.", w->id);
992 else debug(D_WEB_CLIENT, "%llu: Failed to send data to client. Reason: %s", w->id, strerror(errno));
998 long web_client_receive(struct web_client *w)
1000 // do we have any space for more data?
1001 web_buffer_increase(w->data, WEB_DATA_LENGTH_INCREASE_STEP);
1003 long left = w->data->size - w->data->bytes;
1006 if(w->mode == WEB_CLIENT_MODE_FILECOPY)
1007 bytes = read(w->ifd, &w->data->buffer[w->data->bytes], (left-1));
1009 bytes = recv(w->ifd, &w->data->buffer[w->data->bytes], left-1, MSG_DONTWAIT);
1012 int old = w->data->bytes;
1013 w->data->bytes += bytes;
1014 w->data->buffer[w->data->bytes] = '\0';
1016 debug(D_WEB_CLIENT, "%llu: Received %d bytes.", w->id, bytes);
1017 debug(D_WEB_DATA, "%llu: Received data: '%s'.", w->id, &w->data->buffer[old]);
1019 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1021 if(w->data->rbytes && w->data->bytes >= w->data->rbytes) w->wait_receive = 0;
1024 else if(bytes == 0) {
1025 debug(D_WEB_CLIENT, "%llu: Out of input data.", w->id);
1027 // if we cannot read, it means we have an error on input.
1028 // if however, we are copying a file from ifd to ofd, we should not return an error.
1029 // in this case, the error should be generated when the file has been sent to the client.
1031 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1032 // we are copying data fron ifd to ofd
1033 // let it finish copying...
1034 w->wait_receive = 0;
1035 debug(D_WEB_CLIENT, "%llu: Disabling input.", w->id);
1047 // --------------------------------------------------------------------------------------
1048 // the thread of a single client
1050 // 1. waits for input and output, using async I/O
1051 // 2. it processes HTTP requests
1052 // 3. it generates HTTP responses
1053 // 4. it copies data from input to output if mode is FILECOPY
1055 void *new_client(void *ptr)
1057 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
1058 error("Cannot set pthread cancel type to DEFERRED.");
1060 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
1061 error("Cannot set pthread cancel state to ENABLE.");
1064 struct web_client *w = ptr;
1066 fd_set ifds, ofds, efds;
1074 FD_SET(w->ifd, &efds);
1075 if(w->ifd != w->ofd) FD_SET(w->ofd, &efds);
1076 if (w->wait_receive) {
1077 FD_SET(w->ifd, &ifds);
1078 if(w->ifd > fdmax) fdmax = w->ifd;
1081 FD_SET(w->ofd, &ofds);
1082 if(w->ofd > fdmax) fdmax = w->ofd;
1088 debug(D_WEB_CLIENT, "%llu: Waiting socket async I/O for %s %s", w->id, w->wait_receive?"INPUT":"", w->wait_send?"OUTPUT":"");
1089 retval = select(fdmax+1, &ifds, &ofds, &efds, &tv);
1092 error("%llu: LISTENER: select() failed.", w->id);
1097 web_client_reset(w);
1102 if(FD_ISSET(w->ifd, &efds)) {
1103 debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on input socket (%s).", w->id, strerror(errno));
1104 web_client_reset(w);
1109 if(FD_ISSET(w->ofd, &efds)) {
1110 debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on output socket (%s).", w->id, strerror(errno));
1111 web_client_reset(w);
1116 if(w->wait_send && FD_ISSET(w->ofd, &ofds)) {
1118 if((bytes = web_client_send(w)) < 0) {
1119 debug(D_WEB_CLIENT, "%llu: Closing client (input: %s).", w->id, strerror(errno));
1120 web_client_reset(w);
1126 global_statistics_lock();
1127 global_statistics.bytes_sent += bytes;
1128 global_statistics_unlock();
1132 if(w->wait_receive && FD_ISSET(w->ifd, &ifds)) {
1134 if((bytes = web_client_receive(w)) < 0) {
1135 debug(D_WEB_CLIENT, "%llu: Closing client (output: %s).", w->id, strerror(errno));
1136 web_client_reset(w);
1142 if(w->mode != WEB_CLIENT_MODE_FILECOPY) {
1143 global_statistics_lock();
1144 global_statistics.bytes_received += bytes;
1145 global_statistics_unlock();
1149 if(w->mode == WEB_CLIENT_MODE_NORMAL) web_client_process(w);
1152 debug(D_WEB_CLIENT, "%llu: done...", w->id);
1157 // --------------------------------------------------------------------------------------
1158 // the main socket listener
1160 // 1. it accepts new incoming requests on our port
1161 // 2. creates a new web_client for each connection received
1162 // 3. spawns a new pthread to serve the client (this is optimal for keep-alive clients)
1163 // 4. cleans up old web_clients that their pthreads have been exited
1165 void *socket_listen_main(void *ptr)
1168 struct web_client *w;
1174 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
1175 error("Cannot set pthread cancel type to DEFERRED.");
1177 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
1178 error("Cannot set pthread cancel state to ENABLE.");
1180 // int listener = create_listen_socket(listen_port);
1181 int listener = listen_fd;
1182 if(listener == -1) fatal("LISTENER: Cannot create listening socket on port 19999.");
1184 fd_set ifds, ofds, efds;
1185 int fdmax = listener;
1193 tv.tv_usec = 200000;
1195 FD_SET(listener, &ifds);
1196 FD_SET(listener, &efds);
1198 // debug(D_WEB_CLIENT, "LISTENER: Waiting...");
1199 retval = select(fdmax+1, &ifds, &ofds, &efds, &tv);
1202 error("LISTENER: select() failed.");
1206 // check for new incoming connections
1207 if(FD_ISSET(listener, &ifds)) {
1208 w = web_client_create(listener);
1210 if(pthread_create(&w->thread, NULL, new_client, w) != 0) {
1211 error("%llu: failed to create new thread for web client.");
1214 else if(pthread_detach(w->thread) != 0) {
1215 error("%llu: Cannot request detach of newly created web client thread.", w->id);
1219 log_access("%llu: %s connected", w->id, w->client_ip);
1221 else debug(D_WEB_CLIENT, "LISTENER: select() didn't do anything.");
1225 // debug(D_WEB_CLIENT, "LISTENER: select() timeout.");
1228 // cleanup unused clients
1229 for(w = web_clients; w ; w = w?w->next:NULL) {
1231 log_access("%llu: %s disconnected", w->id, w->client_ip);
1232 debug(D_WEB_CLIENT, "%llu: Removing client.", w->id);
1233 // pthread_join(w->thread, NULL);
1234 w = web_client_free(w);
1240 error("LISTENER: exit!");