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"
27 int listen_backlog = LISTEN_BACKLOG;
30 int listen_port = LISTEN_PORT;
32 #define DEFAULT_DISCONNECT_IDLE_WEB_CLIENTS_AFTER_SECONDS 60
34 int web_client_timeout = DEFAULT_DISCONNECT_IDLE_WEB_CLIENTS_AFTER_SECONDS;
36 static void log_allocations(void)
43 if(mi.uordblks > mem) {
46 for(w = web_clients; w ; w = w->next) clients++;
48 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);
53 int create_listen_socket4(int port, int listen_backlog)
57 struct sockaddr_in name;
59 debug(D_LISTENER, "IPv4 creating new listening socket on port %d", port);
61 sock = socket(AF_INET, SOCK_STREAM, 0);
63 error("IPv4 socket() failed.");
67 /* avoid "address already in use" */
68 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*)&sockopt, sizeof(sockopt));
70 memset(&name, 0, sizeof(struct sockaddr_in));
71 name.sin_family = AF_INET;
72 name.sin_port = htons (port);
73 name.sin_addr.s_addr = htonl (INADDR_ANY);
75 if(bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) {
77 error("IPv4 bind() failed.");
81 if(listen(sock, listen_backlog) < 0) {
83 fatal("IPv4 listen() failed.");
87 debug(D_LISTENER, "IPv4 listening port %d created", port);
91 int create_listen_socket6(int port, int listen_backlog)
95 struct sockaddr_in6 name;
97 debug(D_LISTENER, "IPv6 creating new listening socket on port %d", port);
99 sock = socket(AF_INET6, SOCK_STREAM, 0);
101 error("IPv6 socket() failed.");
105 /* avoid "address already in use" */
106 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*)&sockopt, sizeof(sockopt));
108 memset(&name, 0, sizeof(struct sockaddr_in6));
109 name.sin6_family = AF_INET6;
110 name.sin6_port = htons (port);
111 name.sin6_addr = in6addr_any;
112 name.sin6_scope_id = 0;
114 if (bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) {
116 error("IPv6 bind() failed.");
120 if (listen(sock, listen_backlog) < 0) {
122 fatal("IPv6 listen() failed.");
126 debug(D_LISTENER, "IPv6 listening port %d created", port);
131 int mysendfile(struct web_client *w, char *filename)
133 static char *web_dir = NULL;
134 if(!web_dir) web_dir = config_get("global", "web files directory", "web");
136 debug(D_WEB_CLIENT, "%llu: Looking for file '%s'...", w->id, filename);
138 // skip leading slashes
139 while (*filename == '/') filename++;
141 // if the filename contain known paths, skip them
142 if(strncmp(filename, WEB_PATH_DATA "/", strlen(WEB_PATH_DATA) + 1) == 0) filename = &filename[strlen(WEB_PATH_DATA) + 1];
143 else if(strncmp(filename, WEB_PATH_DATASOURCE "/", strlen(WEB_PATH_DATASOURCE) + 1) == 0) filename = &filename[strlen(WEB_PATH_DATASOURCE) + 1];
144 else if(strncmp(filename, WEB_PATH_GRAPH "/", strlen(WEB_PATH_GRAPH) + 1) == 0) filename = &filename[strlen(WEB_PATH_GRAPH) + 1];
145 else if(strncmp(filename, WEB_PATH_FILE "/", strlen(WEB_PATH_FILE) + 1) == 0) filename = &filename[strlen(WEB_PATH_FILE) + 1];
147 // if the filename contains a / or a .., refuse to serve it
148 if(strchr(filename, '/') != 0 || strstr(filename, "..") != 0) {
149 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
150 web_buffer_printf(w->data, "File '%s' cannot be served. Filenames cannot contain / or ..", filename);
155 char webfilename[FILENAME_MAX + 1];
156 snprintf(webfilename, FILENAME_MAX, "%s/%s", web_dir, filename);
158 // check if the file exists
160 if(lstat(webfilename, &stat) != 0) {
161 error("%llu: File '%s' is not found.", w->id, webfilename);
162 web_buffer_printf(w->data, "File '%s' does not exist, or is not accessible.", filename);
166 // check if the file is owned by us
167 if(stat.st_uid != getuid() && stat.st_uid != geteuid()) {
168 error("%llu: File '%s' is owned by user %d (I run as user %d). Access Denied.", w->id, webfilename, stat.st_uid, getuid());
169 web_buffer_printf(w->data, "Access to file '%s' is not permitted.", filename);
174 w->ifd = open(webfilename, O_NONBLOCK, O_RDONLY);
178 if(errno == EBUSY || errno == EAGAIN) {
179 error("%llu: File '%s' is busy, sending 307 Moved Temporarily to force retry.", w->id, webfilename);
180 snprintf(w->response_header, MAX_HTTP_HEADER_SIZE, "Location: /" WEB_PATH_FILE "/%s\r\n", filename);
181 web_buffer_printf(w->data, "The file '%s' is currently busy. Please try again later.", filename);
185 error("%llu: Cannot open file '%s'.", w->id, webfilename);
186 web_buffer_printf(w->data, "Cannot open file '%s'.", filename);
191 // pick a Content-Type for the file
192 if(strstr(filename, ".html") != NULL) w->data->contenttype = CT_TEXT_HTML;
193 else if(strstr(filename, ".js") != NULL) w->data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
194 else if(strstr(filename, ".css") != NULL) w->data->contenttype = CT_TEXT_CSS;
195 else if(strstr(filename, ".xml") != NULL) w->data->contenttype = CT_TEXT_XML;
196 else if(strstr(filename, ".xsl") != NULL) w->data->contenttype = CT_TEXT_XSL;
197 else if(strstr(filename, ".txt") != NULL) w->data->contenttype = CT_TEXT_PLAIN;
198 else if(strstr(filename, ".svg") != NULL) w->data->contenttype = CT_IMAGE_SVG_XML;
199 else if(strstr(filename, ".ttf") != NULL) w->data->contenttype = CT_APPLICATION_X_FONT_TRUETYPE;
200 else if(strstr(filename, ".otf") != NULL) w->data->contenttype = CT_APPLICATION_X_FONT_OPENTYPE;
201 else if(strstr(filename, ".woff") != NULL) w->data->contenttype = CT_APPLICATION_FONT_WOFF;
202 else if(strstr(filename, ".eot") != NULL) w->data->contenttype = CT_APPLICATION_VND_MS_FONTOBJ;
203 else w->data->contenttype = CT_APPLICATION_OCTET_STREAM;
205 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);
207 w->mode = WEB_CLIENT_MODE_FILECOPY;
211 w->data->buffer[0] = '\0';
212 w->data->rbytes = stat.st_size;
213 w->data->date = stat.st_mtim.tv_sec;
218 void web_client_reset(struct web_client *w)
221 gettimeofday(&tv, NULL);
223 long sent = w->zoutput?(long)w->zstream.total_out:((w->mode == WEB_CLIENT_MODE_FILECOPY)?w->data->rbytes:w->data->bytes);
224 long size = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->data->rbytes:w->data->bytes;
226 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'",
228 sent, size, -((size>0)?((float)(size-sent)/(float)size * 100.0):0.0),
229 (float)usecdiff(&w->tv_ready, &w->tv_in) / 1000.0,
230 (float)usecdiff(&tv, &w->tv_ready) / 1000.0,
231 (float)usecdiff(&tv, &w->tv_in) / 1000.0,
232 (w->mode == WEB_CLIENT_MODE_FILECOPY)?"filecopy":"data",
236 debug(D_WEB_CLIENT, "%llu: Reseting client.", w->id);
238 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
239 debug(D_WEB_CLIENT, "%llu: Closing filecopy input file.", w->id);
244 w->last_url[0] = '\0';
246 w->data->contenttype = CT_TEXT_PLAIN;
247 w->mode = WEB_CLIENT_MODE_NORMAL;
253 w->response_header[0] = '\0';
254 w->data->buffer[0] = '\0';
259 // if we had enabled compression, release it
260 if(w->zinitialized) {
261 debug(D_DEFLATE, "%llu: Reseting compression.", w->id);
262 deflateEnd(&w->zstream);
266 w->zstream.avail_in = 0;
267 w->zstream.avail_out = 0;
268 w->zstream.total_in = 0;
269 w->zstream.total_out = 0;
274 void web_client_enable_deflate(struct web_client *w) {
275 if(w->zinitialized == 1) {
276 error("%llu: Compression has already be initialized for this client.", w->id);
281 error("%llu: Cannot enable compression in the middle of a conversation.", w->id);
285 w->zstream.zalloc = Z_NULL;
286 w->zstream.zfree = Z_NULL;
287 w->zstream.opaque = Z_NULL;
289 w->zstream.next_in = (Bytef *)w->data->buffer;
290 w->zstream.avail_in = 0;
291 w->zstream.total_in = 0;
293 w->zstream.next_out = w->zbuffer;
294 w->zstream.avail_out = 0;
295 w->zstream.total_out = 0;
297 w->zstream.zalloc = Z_NULL;
298 w->zstream.zfree = Z_NULL;
299 w->zstream.opaque = Z_NULL;
301 // if(deflateInit(&w->zstream, Z_DEFAULT_COMPRESSION) != Z_OK) {
302 // error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
306 // Select GZIP compression: windowbits = 15 + 16 = 31
307 if(deflateInit2(&w->zstream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY) != Z_OK) {
308 error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
316 debug(D_DEFLATE, "%llu: Initialized compression.", w->id);
319 int web_client_data_request(struct web_client *w, char *url, int datasource_type)
321 char *args = strchr(url, '?');
327 // get the name of the data to show
328 char *tok = mystrsep(&url, "/");
329 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
331 // do we have such a data set?
332 RRDSET *st = rrdset_find_byname(tok);
333 if(!st) st = rrdset_find(tok);
336 // try to send a file with that name
338 return(mysendfile(w, tok));
342 debug(D_WEB_CLIENT, "%llu: Found RRD data with name '%s'.", w->id, tok);
344 // how many entries does the client want?
345 long lines = rrd_default_history_entries;
346 long group_count = 1;
347 time_t after = 0, before = 0;
348 int group_method = GROUP_AVERAGE;
352 // parse the lines required
353 tok = mystrsep(&url, "/");
354 if(tok) lines = atoi(tok);
355 if(lines < 1) lines = 1;
358 // parse the group count required
359 tok = mystrsep(&url, "/");
360 if(tok) group_count = atoi(tok);
361 if(group_count < 1) group_count = 1;
362 //if(group_count > save_history / 20) group_count = save_history / 20;
365 // parse the grouping method required
366 tok = mystrsep(&url, "/");
367 if(strcmp(tok, "max") == 0) group_method = GROUP_MAX;
368 else if(strcmp(tok, "average") == 0) group_method = GROUP_AVERAGE;
369 else if(strcmp(tok, "sum") == 0) group_method = GROUP_SUM;
370 else debug(D_WEB_CLIENT, "%llu: Unknown group method '%s'", w->id, tok);
374 tok = mystrsep(&url, "/");
375 if(tok) after = strtoul(tok, NULL, 10);
376 if(after < 0) after = 0;
380 tok = mystrsep(&url, "/");
381 if(tok) before = strtoul(tok, NULL, 10);
382 if(before < 0) before = 0;
386 tok = mystrsep(&url, "/");
387 if(tok && strcmp(tok, "nonzero") == 0) nonzero = 1;
390 w->data->contenttype = CT_APPLICATION_JSON;
393 char *google_version = "0.6";
394 char *google_reqId = "0";
395 char *google_sig = "0";
396 char *google_out = "json";
397 char *google_responseHandler = "google.visualization.Query.setResponse";
398 char *google_outFileName = NULL;
399 unsigned long last_timestamp_in_data = 0;
400 if(datasource_type == DATASOURCE_GOOGLE_JSON || datasource_type == DATASOURCE_GOOGLE_JSONP) {
402 w->data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
405 tok = mystrsep(&args, "&");
407 char *name = mystrsep(&tok, "=");
408 if(name && strcmp(name, "tqx") == 0) {
409 char *key = mystrsep(&tok, ":");
410 char *value = mystrsep(&tok, ";");
411 if(key && value && *key && *value) {
412 if(strcmp(key, "version") == 0)
413 google_version = value;
415 else if(strcmp(key, "reqId") == 0)
416 google_reqId = value;
418 else if(strcmp(key, "sig") == 0)
421 else if(strcmp(key, "out") == 0)
424 else if(strcmp(key, "responseHandler") == 0)
425 google_responseHandler = value;
427 else if(strcmp(key, "outFileName") == 0)
428 google_outFileName = value;
434 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
435 w->id, google_version, google_reqId, google_sig, google_out, google_responseHandler, google_outFileName
438 if(datasource_type == DATASOURCE_GOOGLE_JSONP) {
439 last_timestamp_in_data = strtoul(google_sig, NULL, 0);
441 // check the client wants json
442 if(strcmp(google_out, "json") != 0) {
443 w->data->bytes = snprintf(w->data->buffer, w->data->size,
444 "%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.'}]});",
445 google_responseHandler, google_version, google_reqId, google_out);
451 if(datasource_type == DATASOURCE_GOOGLE_JSONP) {
452 w->data->bytes = snprintf(w->data->buffer, w->data->size,
453 "%s({version:'%s',reqId:'%s',status:'ok',sig:'%lu',table:",
454 google_responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
457 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);
458 unsigned long timestamp_in_data = rrd_stats_json(datasource_type, st, w->data, lines, group_count, group_method, after, before, nonzero);
460 if(datasource_type == DATASOURCE_GOOGLE_JSONP) {
461 if(timestamp_in_data > last_timestamp_in_data)
462 w->data->bytes += snprintf(&w->data->buffer[w->data->bytes], w->data->size - w->data->bytes, "});");
465 // the client already has the latest data
466 w->data->bytes = snprintf(w->data->buffer, w->data->size,
467 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
468 google_responseHandler, google_version, google_reqId);
475 void web_client_process(struct web_client *w)
482 // check if we have an empty line (end of HTTP header)
483 if(strstr(w->data->buffer, "\r\n\r\n")) {
484 global_statistics_lock();
485 global_statistics.web_requests++;
486 global_statistics_unlock();
488 gettimeofday(&w->tv_in, NULL);
489 debug(D_WEB_DATA, "%llu: Processing data buffer of %d bytes: '%s'.", w->id, w->data->bytes, w->data->buffer);
491 // check if the client requested keep-alive HTTP
492 if(strcasestr(w->data->buffer, "Connection: keep-alive")) w->keepalive = 1;
493 else w->keepalive = 0;
495 // check if the client accepts deflate
496 if(strstr(w->data->buffer, "gzip"))
497 web_client_enable_deflate(w);
499 int datasource_type = DATASOURCE_GOOGLE_JSONP;
500 //if(strstr(w->data->buffer, "X-DataSource-Auth"))
501 // datasource_type = DATASOURCE_GOOGLE_JSON;
503 char *buf = w->data->buffer;
504 char *tok = strsep(&buf, " \r\n");
506 char *pointer_to_free = NULL; // keep url_decode() allocated buffer
508 if(buf && strcmp(tok, "GET") == 0) {
509 tok = strsep(&buf, " \r\n");
510 pointer_to_free = url = url_decode(tok);
511 debug(D_WEB_CLIENT, "%llu: Processing HTTP GET on url '%s'.", w->id, url);
513 else if (buf && strcmp(tok, "POST") == 0) {
515 tok = strsep(&buf, " \r\n");
516 pointer_to_free = url = url_decode(tok);
518 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);
521 w->last_url[0] = '\0';
523 strncpy(w->last_url, url, URL_MAX);
524 w->last_url[URL_MAX] = '\0';
526 tok = mystrsep(&url, "/?&");
528 debug(D_WEB_CLIENT, "%llu: Processing command '%s'.", w->id, tok);
530 if(strcmp(tok, WEB_PATH_DATA) == 0) { // "data"
531 // the client is requesting rrd data
532 datasource_type = DATASOURCE_JSON;
533 code = web_client_data_request(w, url, datasource_type);
535 else if(strcmp(tok, WEB_PATH_DATASOURCE) == 0) { // "datasource"
536 // the client is requesting google datasource
537 code = web_client_data_request(w, url, datasource_type);
539 else if(strcmp(tok, WEB_PATH_GRAPH) == 0) { // "graph"
540 // the client is requesting an rrd graph
542 // get the name of the data to show
543 tok = mystrsep(&url, "/?&");
544 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
546 // do we have such a data set?
547 RRDSET *st = rrdset_find_byname(tok);
548 if(!st) st = rrdset_find(tok);
551 // try to send a file with that name
553 code = mysendfile(w, tok);
557 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending %s.json of RRD_STATS...", w->id, st->name);
558 w->data->contenttype = CT_APPLICATION_JSON;
560 rrd_stats_graph_json(st, url, w->data);
563 else if(strcmp(tok, "debug") == 0) {
566 // get the name of the data to show
567 tok = mystrsep(&url, "/?&");
568 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
570 // do we have such a data set?
571 RRDSET *st = rrdset_find_byname(tok);
572 if(!st) st = rrdset_find(tok);
575 web_buffer_printf(w->data, "Chart %s is not found.\r\n", tok);
576 debug(D_WEB_CLIENT_ACCESS, "%llu: %s is not found.", w->id, tok);
580 debug_flags |= D_RRD_STATS;
581 st->debug = st->debug?0:1;
582 web_buffer_printf(w->data, "Chart %s has now debug %s.\r\n", tok, st->debug?"enabled":"disabled");
583 debug(D_WEB_CLIENT_ACCESS, "%llu: debug for %s is %s.", w->id, tok, st->debug?"enabled":"disabled");
586 else if(strcmp(tok, "mirror") == 0) {
589 debug(D_WEB_CLIENT_ACCESS, "%llu: Mirroring...", w->id);
591 // replace the zero bytes with spaces
593 for(i = 0; i < w->data->size; i++)
594 if(w->data->buffer[i] == '\0') w->data->buffer[i] = ' ';
596 // just leave the buffer as is
597 // it will be copied back to the client
599 else if(strcmp(tok, "list") == 0) {
602 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending list of RRD_STATS...", w->id);
605 RRDSET *st = rrdset_root;
607 for ( ; st ; st = st->next )
608 web_buffer_printf(w->data, "%s\n", st->name);
610 else if(strcmp(tok, "all.json") == 0) {
612 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending JSON list of all monitors of RRD_STATS...", w->id);
614 w->data->contenttype = CT_APPLICATION_JSON;
616 rrd_stats_all_json(w->data);
618 else if(strcmp(tok, "netdata.conf") == 0) {
620 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending netdata.conf ...", w->id);
622 w->data->contenttype = CT_TEXT_PLAIN;
624 generate_config(w->data, 0);
626 else if(strcmp(tok, WEB_PATH_FILE) == 0) { // "file"
627 tok = mystrsep(&url, "/?&");
628 if(tok && *tok) code = mysendfile(w, tok);
632 strcpy(w->data->buffer, "You have to give a filename to get.\r\n");
633 w->data->bytes = strlen(w->data->buffer);
638 code = mysendfile(w, "index.html");
642 code = mysendfile(w, tok);
647 strcpy(w->last_url, "not a valid response");
649 if(buf) debug(D_WEB_CLIENT_ACCESS, "%llu: Cannot understand '%s'.", w->id, buf);
653 strcpy(w->data->buffer, "I don't understand you...\r\n");
654 w->data->bytes = strlen(w->data->buffer);
657 // free url_decode() buffer
658 if(pointer_to_free) free(pointer_to_free);
660 else if(w->data->bytes > 8192) {
661 strcpy(w->last_url, "too big request");
663 debug(D_WEB_CLIENT_ACCESS, "%llu: Received request is too big.", w->id);
667 strcpy(w->data->buffer, "Received request is too big.\r\n");
668 w->data->bytes = strlen(w->data->buffer);
671 // wait for more data
676 if(w->data->bytes > w->data->size) {
677 error("%llu: memory overflow encountered (size is %ld, written %ld).", w->data->size, w->data->bytes);
680 gettimeofday(&w->tv_ready, NULL);
681 w->data->date = time(NULL);
684 // prepare the HTTP response header
685 debug(D_WEB_CLIENT, "%llu: Generating HTTP header with response %d.", w->id, code);
687 char *content_type_string = "";
688 switch(w->data->contenttype) {
690 content_type_string = "text/html";
693 case CT_APPLICATION_XML:
694 content_type_string = "application/xml";
697 case CT_APPLICATION_JSON:
698 content_type_string = "application/json";
701 case CT_APPLICATION_X_JAVASCRIPT:
702 content_type_string = "application/x-javascript";
706 content_type_string = "text/css";
710 content_type_string = "text/xml";
714 content_type_string = "text/xsl";
717 case CT_APPLICATION_OCTET_STREAM:
718 content_type_string = "application/octet-stream";
721 case CT_IMAGE_SVG_XML:
722 content_type_string = "image/svg+xml";
725 case CT_APPLICATION_X_FONT_TRUETYPE:
726 content_type_string = "application/x-font-truetype";
729 case CT_APPLICATION_X_FONT_OPENTYPE:
730 content_type_string = "application/x-font-opentype";
733 case CT_APPLICATION_FONT_WOFF:
734 content_type_string = "application/font-woff";
737 case CT_APPLICATION_VND_MS_FONTOBJ:
738 content_type_string = "application/vnd.ms-fontobject";
743 content_type_string = "text/plain";
754 code_msg = "Temporary Redirect";
758 code_msg = "Bad Request";
762 code_msg = "Forbidden";
766 code_msg = "Not Found";
770 code_msg = "Internal Server Error";
775 struct tm tm = *gmtime(&w->data->date);
776 strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %Z", &tm);
778 char custom_header[MAX_HTTP_HEADER_SIZE + 1] = "";
779 if(w->response_header[0])
780 strcpy(custom_header, w->response_header);
783 headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen,
786 "Server: NetData Embedded HTTP Server\r\n"
787 "Content-Type: %s\r\n"
788 "Access-Control-Allow-Origin: *\r\n"
791 , w->keepalive?"keep-alive":"close"
792 , content_type_string
797 headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen, "%s", custom_header);
799 if(w->mode == WEB_CLIENT_MODE_NORMAL) {
800 headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen,
802 "Cache-Control: no-cache\r\n"
807 headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen,
808 "Cache-Control: public\r\n"
812 // if we know the content length, put it
813 if(!w->zoutput && (w->data->bytes || w->data->rbytes))
814 headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen,
815 "Content-Length: %ld\r\n"
816 , w->data->bytes?w->data->bytes:w->data->rbytes
819 w->keepalive = 0; // content-length is required for keep-alive
822 headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen,
823 "Content-Encoding: gzip\r\n"
824 "Transfer-Encoding: chunked\r\n"
828 headerlen += snprintf(&w->response_header[headerlen], MAX_HTTP_HEADER_SIZE - headerlen, "\r\n");
830 // disable TCP_NODELAY, to buffer the header
832 if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0) error("%llu: failed to disable TCP_NODELAY on socket.", w->id);
834 // sent the HTTP header
835 debug(D_WEB_DATA, "%llu: Sending response HTTP header of size %d: '%s'", w->id, headerlen, w->response_header);
837 bytes = send(w->ofd, w->response_header, headerlen, 0);
838 if(bytes != headerlen)
839 error("%llu: HTTP Header failed to be sent (I sent %d bytes but the system sent %d bytes).", w->id, headerlen, bytes);
841 global_statistics_lock();
842 global_statistics.bytes_sent += bytes;
843 global_statistics_unlock();
846 // enable TCP_NODELAY, to send all data immediately at the next send()
848 if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0) error("%llu: failed to enable TCP_NODELAY on socket.", w->id);
850 // enable sending immediately if we have data
851 if(w->data->bytes) w->wait_send = 1;
852 else w->wait_send = 0;
856 case WEB_CLIENT_MODE_NORMAL:
857 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Sending data (%d bytes) to client.", w->id, w->data->bytes);
860 case WEB_CLIENT_MODE_FILECOPY:
861 if(w->data->rbytes) {
862 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending data file of %d bytes to client.", w->id, w->data->rbytes);
866 // utilize the kernel sendfile() for copying the file to the socket.
867 // this block of code can be commented, without anything missing.
868 // when it is commented, the program will copy the data using async I/O.
870 long len = sendfile(w->ofd, w->ifd, NULL, w->data->rbytes);
871 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);
872 else web_client_reset(w);
877 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending an unknown amount of bytes to client.", w->id);
881 fatal("%llu: Unknown client mode %d.", w->id, w->mode);
886 long web_client_send_chunk_header(struct web_client *w, int len)
888 debug(D_DEFLATE, "%llu: OPEN CHUNK of %d bytes (hex: %x).", w->id, len, len);
890 sprintf(buf, "%X\r\n", len);
891 int bytes = send(w->ofd, buf, strlen(buf), MSG_DONTWAIT);
893 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk header %d bytes.", w->id, bytes);
894 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk header to the client.", w->id);
895 else debug(D_DEFLATE, "%llu: Failed to send chunk header to client. Reason: %s", w->id, strerror(errno));
900 long web_client_send_chunk_close(struct web_client *w)
902 //debug(D_DEFLATE, "%llu: CLOSE CHUNK.", w->id);
904 int bytes = send(w->ofd, "\r\n", 2, MSG_DONTWAIT);
906 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
907 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
908 else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client. Reason: %s", w->id, strerror(errno));
913 long web_client_send_chunk_finalize(struct web_client *w)
915 //debug(D_DEFLATE, "%llu: FINALIZE CHUNK.", w->id);
917 int bytes = send(w->ofd, "\r\n0\r\n\r\n", 7, MSG_DONTWAIT);
919 if(bytes > 0) debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
920 else if(bytes == 0) debug(D_DEFLATE, "%llu: Did not send chunk suffix to the client.", w->id);
921 else debug(D_DEFLATE, "%llu: Failed to send chunk suffix to client. Reason: %s", w->id, strerror(errno));
926 long web_client_send_deflate(struct web_client *w)
928 long bytes = 0, t = 0;
930 // when using compression,
931 // w->data->sent is the amount of bytes passed through compression
933 // 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);
935 if(w->data->bytes - w->data->sent == 0 && w->zstream.avail_in == 0 && w->zhave == w->zsent && w->zstream.avail_out != 0) {
936 // there is nothing to send
938 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
940 // finalize the chunk
941 if(w->data->sent != 0)
942 t += web_client_send_chunk_finalize(w);
944 // there can be two cases for this
945 // A. we have done everything
946 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
948 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->data->rbytes && w->data->rbytes > w->data->bytes) {
949 // we have to wait, more data will come
950 debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
955 if(w->keepalive == 0) {
956 debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->data->sent);
963 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
967 if(w->zstream.avail_out == 0 && w->zhave == w->zsent) {
968 // compress more input data
970 // close the previous open chunk
971 if(w->data->sent != 0) t += web_client_send_chunk_close(w);
973 debug(D_DEFLATE, "%llu: Compressing %d bytes starting from %d.", w->id, (w->data->bytes - w->data->sent), w->data->sent);
975 // give the compressor all the data not passed through the compressor yet
976 if(w->data->bytes > w->data->sent) {
977 w->zstream.next_in = (Bytef *)&w->data->buffer[w->data->sent];
978 w->zstream.avail_in = (w->data->bytes - w->data->sent);
981 // reset the compressor output buffer
982 w->zstream.next_out = w->zbuffer;
983 w->zstream.avail_out = ZLIB_CHUNK;
985 // ask for FINISH if we have all the input
986 int flush = Z_SYNC_FLUSH;
987 if(w->mode == WEB_CLIENT_MODE_NORMAL
988 || (w->mode == WEB_CLIENT_MODE_FILECOPY && w->data->bytes == w->data->rbytes)) {
990 debug(D_DEFLATE, "%llu: Requesting Z_FINISH.", w->id);
993 debug(D_DEFLATE, "%llu: Requesting Z_SYNC_FLUSH.", w->id);
997 if(deflate(&w->zstream, flush) == Z_STREAM_ERROR) {
998 error("%llu: Compression failed. Closing down client.", w->id);
1003 w->zhave = ZLIB_CHUNK - w->zstream.avail_out;
1006 // keep track of the bytes passed through the compressor
1007 w->data->sent = w->data->bytes;
1009 debug(D_DEFLATE, "%llu: Compression produced %d bytes.", w->id, w->zhave);
1012 t += web_client_send_chunk_header(w, w->zhave);
1015 bytes = send(w->ofd, &w->zbuffer[w->zsent], w->zhave - w->zsent, MSG_DONTWAIT);
1018 if(t > 0) bytes += t;
1019 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, bytes);
1021 else if(bytes == 0) debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client.", w->id);
1022 else debug(D_WEB_CLIENT, "%llu: Failed to send data to client. Reason: %s", w->id, strerror(errno));
1027 long web_client_send(struct web_client *w)
1029 if(w->zoutput) return web_client_send_deflate(w);
1033 if(w->data->bytes - w->data->sent == 0) {
1034 // there is nothing to send
1036 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1038 // there can be two cases for this
1039 // A. we have done everything
1040 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
1042 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->ifd != w->ofd && w->data->rbytes && w->data->rbytes > w->data->bytes) {
1043 // we have to wait, more data will come
1044 debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1049 if(w->keepalive == 0) {
1050 debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->data->sent);
1055 web_client_reset(w);
1056 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
1060 bytes = send(w->ofd, &w->data->buffer[w->data->sent], w->data->bytes - w->data->sent, MSG_DONTWAIT);
1062 w->data->sent += bytes;
1063 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, bytes);
1065 else if(bytes == 0) debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client.", w->id);
1066 else debug(D_WEB_CLIENT, "%llu: Failed to send data to client. Reason: %s", w->id, strerror(errno));
1072 long web_client_receive(struct web_client *w)
1074 // do we have any space for more data?
1075 web_buffer_increase(w->data, WEB_DATA_LENGTH_INCREASE_STEP);
1077 long left = w->data->size - w->data->bytes;
1080 if(w->mode == WEB_CLIENT_MODE_FILECOPY)
1081 bytes = read(w->ifd, &w->data->buffer[w->data->bytes], (left-1));
1083 bytes = recv(w->ifd, &w->data->buffer[w->data->bytes], left-1, MSG_DONTWAIT);
1086 int old = w->data->bytes;
1087 w->data->bytes += bytes;
1088 w->data->buffer[w->data->bytes] = '\0';
1090 debug(D_WEB_CLIENT, "%llu: Received %d bytes.", w->id, bytes);
1091 debug(D_WEB_DATA, "%llu: Received data: '%s'.", w->id, &w->data->buffer[old]);
1093 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1095 if(w->data->rbytes && w->data->bytes >= w->data->rbytes) w->wait_receive = 0;
1098 else if(bytes == 0) {
1099 debug(D_WEB_CLIENT, "%llu: Out of input data.", w->id);
1101 // if we cannot read, it means we have an error on input.
1102 // if however, we are copying a file from ifd to ofd, we should not return an error.
1103 // in this case, the error should be generated when the file has been sent to the client.
1105 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
1106 // we are copying data fron ifd to ofd
1107 // let it finish copying...
1108 w->wait_receive = 0;
1109 debug(D_WEB_CLIENT, "%llu: Disabling input.", w->id);
1121 // --------------------------------------------------------------------------------------
1122 // the thread of a single client
1124 // 1. waits for input and output, using async I/O
1125 // 2. it processes HTTP requests
1126 // 3. it generates HTTP responses
1127 // 4. it copies data from input to output if mode is FILECOPY
1129 void *new_client(void *ptr)
1131 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
1132 error("Cannot set pthread cancel type to DEFERRED.");
1134 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
1135 error("Cannot set pthread cancel state to ENABLE.");
1138 struct web_client *w = ptr;
1140 fd_set ifds, ofds, efds;
1148 FD_SET(w->ifd, &efds);
1150 if(w->ifd != w->ofd)
1151 FD_SET(w->ofd, &efds);
1153 if (w->wait_receive) {
1154 FD_SET(w->ifd, &ifds);
1155 if(w->ifd > fdmax) fdmax = w->ifd;
1159 FD_SET(w->ofd, &ofds);
1160 if(w->ofd > fdmax) fdmax = w->ofd;
1163 tv.tv_sec = web_client_timeout;
1166 debug(D_WEB_CLIENT, "%llu: Waiting socket async I/O for %s %s", w->id, w->wait_receive?"INPUT":"", w->wait_send?"OUTPUT":"");
1167 retval = select(fdmax+1, &ifds, &ofds, &efds, &tv);
1170 debug(D_WEB_CLIENT_ACCESS, "%llu: LISTENER: select() failed.", w->id);
1175 web_client_reset(w);
1180 if(FD_ISSET(w->ifd, &efds)) {
1181 debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on input socket (%s).", w->id, strerror(errno));
1182 web_client_reset(w);
1187 if(FD_ISSET(w->ofd, &efds)) {
1188 debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on output socket (%s).", w->id, strerror(errno));
1189 web_client_reset(w);
1194 if(w->wait_send && FD_ISSET(w->ofd, &ofds)) {
1196 if((bytes = web_client_send(w)) < 0) {
1197 debug(D_WEB_CLIENT, "%llu: Closing client (input: %s).", w->id, strerror(errno));
1198 web_client_reset(w);
1204 global_statistics_lock();
1205 global_statistics.bytes_sent += bytes;
1206 global_statistics_unlock();
1210 if(w->wait_receive && FD_ISSET(w->ifd, &ifds)) {
1212 if((bytes = web_client_receive(w)) < 0) {
1213 debug(D_WEB_CLIENT, "%llu: Closing client (output: %s).", w->id, strerror(errno));
1214 web_client_reset(w);
1220 if(w->mode != WEB_CLIENT_MODE_FILECOPY) {
1221 global_statistics_lock();
1222 global_statistics.bytes_received += bytes;
1223 global_statistics_unlock();
1227 if(w->mode == WEB_CLIENT_MODE_NORMAL) web_client_process(w);
1230 debug(D_WEB_CLIENT, "%llu: done...", w->id);
1235 // --------------------------------------------------------------------------------------
1236 // the main socket listener
1238 // 1. it accepts new incoming requests on our port
1239 // 2. creates a new web_client for each connection received
1240 // 3. spawns a new pthread to serve the client (this is optimal for keep-alive clients)
1241 // 4. cleans up old web_clients that their pthreads have been exited
1243 void *socket_listen_main(void *ptr)
1246 struct web_client *w;
1252 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
1253 error("Cannot set pthread cancel type to DEFERRED.");
1255 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
1256 error("Cannot set pthread cancel state to ENABLE.");
1258 web_client_timeout = config_get_number("global", "disconnect idle web clients after seconds", DEFAULT_DISCONNECT_IDLE_WEB_CLIENTS_AFTER_SECONDS);
1260 if(listen_fd < 0) fatal("LISTENER: Listen socket is not ready.");
1262 fd_set ifds, ofds, efds;
1263 int fdmax = listen_fd;
1271 tv.tv_usec = 200000;
1273 if(listen_fd >= 0) {
1274 FD_SET(listen_fd, &ifds);
1275 FD_SET(listen_fd, &efds);
1278 // debug(D_WEB_CLIENT, "LISTENER: Waiting...");
1279 retval = select(fdmax+1, &ifds, &ofds, &efds, &tv);
1282 error("LISTENER: select() failed.");
1286 // check for new incoming connections
1287 if(FD_ISSET(listen_fd, &ifds)) {
1288 w = web_client_create(listen_fd);
1290 if(pthread_create(&w->thread, NULL, new_client, w) != 0) {
1291 error("%llu: failed to create new thread for web client.");
1294 else if(pthread_detach(w->thread) != 0) {
1295 error("%llu: Cannot request detach of newly created web client thread.", w->id);
1299 log_access("%llu: %s connected", w->id, w->client_ip);
1301 else debug(D_WEB_CLIENT, "LISTENER: select() didn't do anything.");
1305 // debug(D_WEB_CLIENT, "LISTENER: select() timeout.");
1308 // cleanup unused clients
1309 for(w = web_clients; w ; w = w?w->next:NULL) {
1311 log_access("%llu: %s disconnected", w->id, w->client_ip);
1312 debug(D_WEB_CLIENT, "%llu: Removing client.", w->id);
1313 // pthread_join(w->thread, NULL);
1314 w = web_client_free(w);
1320 error("LISTENER: exit!");
1322 if(listen_fd >= 0) close(listen_fd);