7 #include <sys/socket.h>
8 #include <netinet/in.h>
14 #include <netinet/tcp.h>
23 #include "appconfig.h"
25 #include "web_buffer.h"
26 #include "web_server.h"
27 #include "global_statistics.h"
32 #include "web_client.h"
34 #define INITIAL_WEB_DATA_LENGTH 16384
35 #define WEB_REQUEST_LENGTH 16384
36 #define TOO_BIG_REQUEST 16384
38 int web_client_timeout = DEFAULT_DISCONNECT_IDLE_WEB_CLIENTS_AFTER_SECONDS;
39 int web_enable_gzip = 1;
41 extern int netdata_exit;
43 struct web_client *web_clients = NULL;
44 unsigned long long web_clients_count = 0;
46 inline int web_client_crock_socket(struct web_client *w) {
48 if(likely(!w->tcp_cork && w->ofd != -1)) {
50 if(unlikely(setsockopt(w->ofd, IPPROTO_TCP, TCP_CORK, (char *) &w->tcp_cork, sizeof(int)) != 0)) {
51 error("%llu: failed to enable TCP_CORK on socket.", w->id);
61 inline int web_client_uncrock_socket(struct web_client *w) {
63 if(likely(w->tcp_cork && w->ofd != -1)) {
65 if(unlikely(setsockopt(w->ofd, IPPROTO_TCP, TCP_CORK, (char *) &w->tcp_cork, sizeof(int)) != 0)) {
66 error("%llu: failed to disable TCP_CORK on socket.", w->id);
76 struct web_client *web_client_create(int listener)
80 w = calloc(1, sizeof(struct web_client));
82 error("Cannot allocate new web_client memory.");
86 w->id = ++web_clients_count;
87 w->mode = WEB_CLIENT_MODE_NORMAL;
90 struct sockaddr *sadr;
93 sadr = (struct sockaddr*) &w->clientaddr;
94 addrlen = sizeof(w->clientaddr);
96 w->ifd = accept(listener, sadr, &addrlen);
98 error("%llu: Cannot accept new incoming connection.", w->id);
104 if(getnameinfo(sadr, addrlen, w->client_ip, NI_MAXHOST, w->client_port, NI_MAXSERV, NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
105 error("Cannot getnameinfo() on received client connection.");
106 strncpyz(w->client_ip, "UNKNOWN", NI_MAXHOST);
107 strncpyz(w->client_port, "UNKNOWN", NI_MAXSERV);
109 w->client_ip[NI_MAXHOST] = '\0';
110 w->client_port[NI_MAXSERV] = '\0';
112 switch(sadr->sa_family) {
114 debug(D_WEB_CLIENT_ACCESS, "%llu: New IPv4 web client from %s port %s on socket %d.", w->id, w->client_ip, w->client_port, w->ifd);
118 if(strncmp(w->client_ip, "::ffff:", 7) == 0) {
119 strcpy(w->client_ip, &w->client_ip[7]);
120 debug(D_WEB_CLIENT_ACCESS, "%llu: New IPv4 web client from %s port %s on socket %d.", w->id, w->client_ip, w->client_port, w->ifd);
123 debug(D_WEB_CLIENT_ACCESS, "%llu: New IPv6 web client from %s port %s on socket %d.", w->id, w->client_ip, w->client_port, w->ifd);
127 debug(D_WEB_CLIENT_ACCESS, "%llu: New UNKNOWN web client from %s port %s on socket %d.", w->id, w->client_ip, w->client_port, w->ifd);
132 if(setsockopt(w->ofd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) != 0)
133 error("%llu: failed to enable TCP_NODELAY on socket.", w->id);
136 if(setsockopt(w->ifd, SOL_SOCKET, SO_KEEPALIVE, (char *) &flag, sizeof(int)) != 0)
137 error("%llu: Cannot set SO_KEEPALIVE on socket.", w->id);
142 w->response.data = buffer_create(INITIAL_WEB_DATA_LENGTH);
143 if(unlikely(!w->response.data)) {
144 // no need for error log - web_buffer_create already logged the error
150 w->response.header = buffer_create(HTTP_RESPONSE_HEADER_SIZE);
151 if(unlikely(!w->response.header)) {
152 // no need for error log - web_buffer_create already logged the error
153 buffer_free(w->response.data);
159 w->response.header_output = buffer_create(HTTP_RESPONSE_HEADER_SIZE);
160 if(unlikely(!w->response.header_output)) {
161 // no need for error log - web_buffer_create already logged the error
162 buffer_free(w->response.header);
163 buffer_free(w->response.data);
172 if(web_clients) web_clients->prev = w;
173 w->next = web_clients;
176 global_statistics.connected_clients++;
181 void web_client_reset(struct web_client *w)
183 web_client_uncrock_socket(w);
186 gettimeofday(&tv, NULL);
188 debug(D_WEB_CLIENT, "%llu: Reseting client.", w->id);
190 if(w->stats_received_bytes || w->stats_sent_bytes) {
191 if(web_server_mode == WEB_SERVER_MODE_MULTI_THREADED)
192 global_statistics_lock();
194 global_statistics.web_requests++;
195 global_statistics.web_usec += usecdiff(&tv, &w->tv_in);
196 global_statistics.bytes_received += w->stats_received_bytes;
197 global_statistics.bytes_sent += w->stats_sent_bytes;
199 if(web_server_mode == WEB_SERVER_MODE_MULTI_THREADED)
200 global_statistics_unlock();
202 w->stats_received_bytes = 0;
203 w->stats_sent_bytes = 0;
205 size_t sent = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->response.rlen:w->response.data->len;
207 #ifdef NETDATA_WITH_ZLIB
208 if(likely(w->response.zoutput)) sent = (size_t)w->response.zstream.total_out;
211 size_t size = (w->mode == WEB_CLIENT_MODE_FILECOPY)?w->response.rlen:w->response.data->len;
213 if(likely(w->last_url[0]))
214 log_access("%llu: (sent/all = %zu/%zu bytes %0.0f%%, prep/sent/total = %0.2f/%0.2f/%0.2f ms) %s: %d '%s'",
216 sent, size, -((size>0)?((float)(size-sent)/(float)size * 100.0):0.0),
217 (float)usecdiff(&w->tv_ready, &w->tv_in) / 1000.0,
218 (float)usecdiff(&tv, &w->tv_ready) / 1000.0,
219 (float)usecdiff(&tv, &w->tv_in) / 1000.0,
220 (w->mode == WEB_CLIENT_MODE_FILECOPY)?"filecopy":((w->mode == WEB_CLIENT_MODE_OPTIONS)?"options":"data"),
225 if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY)) {
226 if(w->ifd != w->ofd) {
227 debug(D_WEB_CLIENT, "%llu: Closing filecopy input file descriptor %d.", w->id, w->ifd);
228 if(w->ifd != -1) close(w->ifd);
233 w->last_url[0] = '\0';
234 w->cookie1[0] = '\0';
235 w->cookie2[0] = '\0';
239 w->mode = WEB_CLIENT_MODE_NORMAL;
242 w->decoded_url[0] = '\0';
244 buffer_reset(w->response.header_output);
245 buffer_reset(w->response.header);
246 buffer_reset(w->response.data);
247 w->response.rlen = 0;
248 w->response.sent = 0;
249 w->response.code = 0;
254 w->response.zoutput = 0;
256 // if we had enabled compression, release it
257 #ifdef NETDATA_WITH_ZLIB
258 if(w->response.zinitialized) {
259 debug(D_DEFLATE, "%llu: Reseting compression.", w->id);
260 deflateEnd(&w->response.zstream);
261 w->response.zsent = 0;
262 w->response.zhave = 0;
263 w->response.zstream.avail_in = 0;
264 w->response.zstream.avail_out = 0;
265 w->response.zstream.total_in = 0;
266 w->response.zstream.total_out = 0;
267 w->response.zinitialized = 0;
269 #endif // NETDATA_WITH_ZLIB
272 struct web_client *web_client_free(struct web_client *w) {
273 web_client_uncrock_socket(w);
275 struct web_client *n = w->next;
276 if(w == web_clients) web_clients = n;
278 debug(D_WEB_CLIENT_ACCESS, "%llu: Closing web client from %s port %s.", w->id, w->client_ip, w->client_port);
280 #ifdef NETDATA_WITH_ZLIB
281 if(w->response.zinitialized)
282 deflateEnd(&w->response.zstream);
283 #endif // NETDATA_WITH_ZLIB
285 if(w->prev) w->prev->next = w->next;
286 if(w->next) w->next->prev = w->prev;
287 if(w->response.header_output) buffer_free(w->response.header_output);
288 if(w->response.header) buffer_free(w->response.header);
289 if(w->response.data) buffer_free(w->response.data);
290 if(w->ifd != -1) close(w->ifd);
291 if(w->ofd != -1 && w->ofd != w->ifd) close(w->ofd);
294 global_statistics.connected_clients--;
299 uid_t web_files_uid(void) {
300 static char *web_owner = NULL;
301 static uid_t owner_uid = 0;
303 if(unlikely(!web_owner)) {
304 web_owner = config_get("global", "web files owner", config_get("global", "run as user", ""));
305 if(!web_owner || !*web_owner)
306 owner_uid = geteuid();
308 // getpwnam() is not thread safe,
309 // but we have called this function once
310 // while single threaded
311 struct passwd *pw = getpwnam(web_owner);
313 error("User '%s' is not present. Ignoring option.", web_owner);
314 owner_uid = geteuid();
317 debug(D_WEB_CLIENT, "Web files owner set to %s.", web_owner);
318 owner_uid = pw->pw_uid;
326 gid_t web_files_gid(void) {
327 static char *web_group = NULL;
328 static gid_t owner_gid = 0;
330 if(unlikely(!web_group)) {
331 web_group = config_get("global", "web files group", config_get("global", "web files owner", ""));
332 if(!web_group || !*web_group)
333 owner_gid = getegid();
335 // getgrnam() is not thread safe,
336 // but we have called this function once
337 // while single threaded
338 struct group *gr = getgrnam(web_group);
340 error("Group '%s' is not present. Ignoring option.", web_group);
341 owner_gid = getegid();
344 debug(D_WEB_CLIENT, "Web files group set to %s.", web_group);
345 owner_gid = gr->gr_gid;
353 int mysendfile(struct web_client *w, char *filename)
355 static char *web_dir = NULL;
357 // initialize our static data
358 if(unlikely(!web_dir)) web_dir = config_get("global", "web files directory", WEB_DIR);
360 debug(D_WEB_CLIENT, "%llu: Looking for file '%s/%s'", w->id, web_dir, filename);
362 // skip leading slashes
363 while (*filename == '/') filename++;
365 // if the filename contain known paths, skip them
366 if(strncmp(filename, WEB_PATH_FILE "/", strlen(WEB_PATH_FILE) + 1) == 0) filename = &filename[strlen(WEB_PATH_FILE) + 1];
369 for(s = filename; *s ;s++) {
370 if( !isalnum(*s) && *s != '/' && *s != '.' && *s != '-' && *s != '_') {
371 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
372 buffer_sprintf(w->response.data, "File '%s' cannot be served. Filename contains invalid character '%c'", filename, *s);
377 // if the filename contains a .. refuse to serve it
378 if(strstr(filename, "..") != 0) {
379 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not acceptable.", w->id, filename);
380 buffer_sprintf(w->response.data, "File '%s' cannot be served. Relative filenames with '..' in them are not supported.", filename);
385 char webfilename[FILENAME_MAX + 1];
386 snprintfz(webfilename, FILENAME_MAX, "%s/%s", web_dir, filename);
388 // check if the file exists
390 if(lstat(webfilename, &stat) != 0) {
391 debug(D_WEB_CLIENT_ACCESS, "%llu: File '%s' is not found.", w->id, webfilename);
392 buffer_sprintf(w->response.data, "File '%s' does not exist, or is not accessible.", webfilename);
396 // check if the file is owned by expected user
397 if(stat.st_uid != web_files_uid()) {
398 error("%llu: File '%s' is owned by user %d (expected user %d). Access Denied.", w->id, webfilename, stat.st_uid, web_files_uid());
399 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", webfilename);
403 // check if the file is owned by expected group
404 if(stat.st_gid != web_files_gid()) {
405 error("%llu: File '%s' is owned by group %d (expected group %d). Access Denied.", w->id, webfilename, stat.st_gid, web_files_gid());
406 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", webfilename);
410 if((stat.st_mode & S_IFMT) == S_IFDIR) {
411 snprintfz(webfilename, FILENAME_MAX, "%s/index.html", filename);
412 return mysendfile(w, webfilename);
415 if((stat.st_mode & S_IFMT) != S_IFREG) {
416 error("%llu: File '%s' is not a regular file. Access Denied.", w->id, webfilename);
417 buffer_sprintf(w->response.data, "Access to file '%s' is not permitted.", webfilename);
422 w->ifd = open(webfilename, O_NONBLOCK, O_RDONLY);
426 if(errno == EBUSY || errno == EAGAIN) {
427 error("%llu: File '%s' is busy, sending 307 Moved Temporarily to force retry.", w->id, webfilename);
428 buffer_sprintf(w->response.header, "Location: /" WEB_PATH_FILE "/%s\r\n", filename);
429 buffer_sprintf(w->response.data, "The file '%s' is currently busy. Please try again later.", webfilename);
433 error("%llu: Cannot open file '%s'.", w->id, webfilename);
434 buffer_sprintf(w->response.data, "Cannot open file '%s'.", webfilename);
439 // pick a Content-Type for the file
440 if(strstr(filename, ".html") != NULL) w->response.data->contenttype = CT_TEXT_HTML;
441 else if(strstr(filename, ".js") != NULL) w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
442 else if(strstr(filename, ".css") != NULL) w->response.data->contenttype = CT_TEXT_CSS;
443 else if(strstr(filename, ".xml") != NULL) w->response.data->contenttype = CT_TEXT_XML;
444 else if(strstr(filename, ".xsl") != NULL) w->response.data->contenttype = CT_TEXT_XSL;
445 else if(strstr(filename, ".txt") != NULL) w->response.data->contenttype = CT_TEXT_PLAIN;
446 else if(strstr(filename, ".svg") != NULL) w->response.data->contenttype = CT_IMAGE_SVG_XML;
447 else if(strstr(filename, ".ttf") != NULL) w->response.data->contenttype = CT_APPLICATION_X_FONT_TRUETYPE;
448 else if(strstr(filename, ".otf") != NULL) w->response.data->contenttype = CT_APPLICATION_X_FONT_OPENTYPE;
449 else if(strstr(filename, ".woff2")!= NULL) w->response.data->contenttype = CT_APPLICATION_FONT_WOFF2;
450 else if(strstr(filename, ".woff") != NULL) w->response.data->contenttype = CT_APPLICATION_FONT_WOFF;
451 else if(strstr(filename, ".eot") != NULL) w->response.data->contenttype = CT_APPLICATION_VND_MS_FONTOBJ;
452 else if(strstr(filename, ".png") != NULL) w->response.data->contenttype = CT_IMAGE_PNG;
453 else if(strstr(filename, ".jpg") != NULL) w->response.data->contenttype = CT_IMAGE_JPG;
454 else if(strstr(filename, ".jpeg") != NULL) w->response.data->contenttype = CT_IMAGE_JPG;
455 else if(strstr(filename, ".gif") != NULL) w->response.data->contenttype = CT_IMAGE_GIF;
456 else if(strstr(filename, ".bmp") != NULL) w->response.data->contenttype = CT_IMAGE_BMP;
457 else if(strstr(filename, ".ico") != NULL) w->response.data->contenttype = CT_IMAGE_XICON;
458 else if(strstr(filename, ".icns") != NULL) w->response.data->contenttype = CT_IMAGE_ICNS;
459 else w->response.data->contenttype = CT_APPLICATION_OCTET_STREAM;
461 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);
463 w->mode = WEB_CLIENT_MODE_FILECOPY;
466 buffer_flush(w->response.data);
467 w->response.rlen = stat.st_size;
468 w->response.data->date = stat.st_mtim.tv_sec;
474 #ifdef NETDATA_WITH_ZLIB
475 void web_client_enable_deflate(struct web_client *w, int gzip) {
476 if(unlikely(w->response.zinitialized)) {
477 error("%llu: Compression has already be initialized for this client.", w->id);
481 if(unlikely(w->response.sent)) {
482 error("%llu: Cannot enable compression in the middle of a conversation.", w->id);
486 w->response.zstream.zalloc = Z_NULL;
487 w->response.zstream.zfree = Z_NULL;
488 w->response.zstream.opaque = Z_NULL;
490 w->response.zstream.next_in = (Bytef *)w->response.data->buffer;
491 w->response.zstream.avail_in = 0;
492 w->response.zstream.total_in = 0;
494 w->response.zstream.next_out = w->response.zbuffer;
495 w->response.zstream.avail_out = 0;
496 w->response.zstream.total_out = 0;
498 w->response.zstream.zalloc = Z_NULL;
499 w->response.zstream.zfree = Z_NULL;
500 w->response.zstream.opaque = Z_NULL;
502 // if(deflateInit(&w->response.zstream, Z_DEFAULT_COMPRESSION) != Z_OK) {
503 // error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
507 // Select GZIP compression: windowbits = 15 + 16 = 31
508 if(deflateInit2(&w->response.zstream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 15 + ((gzip)?16:0), 8, Z_DEFAULT_STRATEGY) != Z_OK) {
509 error("%llu: Failed to initialize zlib. Proceeding without compression.", w->id);
513 w->response.zsent = 0;
514 w->response.zoutput = 1;
515 w->response.zinitialized = 1;
517 debug(D_DEFLATE, "%llu: Initialized compression.", w->id);
519 #endif // NETDATA_WITH_ZLIB
521 uint32_t web_client_api_request_v1_data_options(char *o)
523 uint32_t ret = 0x00000000;
526 while(o && *o && (tok = mystrsep(&o, ", |"))) {
529 if(!strcmp(tok, "nonzero"))
530 ret |= RRDR_OPTION_NONZERO;
531 else if(!strcmp(tok, "flip") || !strcmp(tok, "reversed") || !strcmp(tok, "reverse"))
532 ret |= RRDR_OPTION_REVERSED;
533 else if(!strcmp(tok, "jsonwrap"))
534 ret |= RRDR_OPTION_JSON_WRAP;
535 else if(!strcmp(tok, "min2max"))
536 ret |= RRDR_OPTION_MIN2MAX;
537 else if(!strcmp(tok, "ms") || !strcmp(tok, "milliseconds"))
538 ret |= RRDR_OPTION_MILLISECONDS;
539 else if(!strcmp(tok, "abs") || !strcmp(tok, "absolute") || !strcmp(tok, "absolute_sum") || !strcmp(tok, "absolute-sum"))
540 ret |= RRDR_OPTION_ABSOLUTE;
541 else if(!strcmp(tok, "seconds"))
542 ret |= RRDR_OPTION_SECONDS;
543 else if(!strcmp(tok, "null2zero"))
544 ret |= RRDR_OPTION_NULL2ZERO;
545 else if(!strcmp(tok, "objectrows"))
546 ret |= RRDR_OPTION_OBJECTSROWS;
547 else if(!strcmp(tok, "google_json"))
548 ret |= RRDR_OPTION_GOOGLE_JSON;
549 else if(!strcmp(tok, "percentage"))
550 ret |= RRDR_OPTION_PERCENTAGE;
556 uint32_t web_client_api_request_v1_data_format(char *name)
558 if(!strcmp(name, DATASOURCE_FORMAT_DATATABLE_JSON)) // datatable
559 return DATASOURCE_DATATABLE_JSON;
561 else if(!strcmp(name, DATASOURCE_FORMAT_DATATABLE_JSONP)) // datasource
562 return DATASOURCE_DATATABLE_JSONP;
564 else if(!strcmp(name, DATASOURCE_FORMAT_JSON)) // json
565 return DATASOURCE_JSON;
567 else if(!strcmp(name, DATASOURCE_FORMAT_JSONP)) // jsonp
568 return DATASOURCE_JSONP;
570 else if(!strcmp(name, DATASOURCE_FORMAT_SSV)) // ssv
571 return DATASOURCE_SSV;
573 else if(!strcmp(name, DATASOURCE_FORMAT_CSV)) // csv
574 return DATASOURCE_CSV;
576 else if(!strcmp(name, DATASOURCE_FORMAT_TSV) || !strcmp(name, "tsv-excel")) // tsv
577 return DATASOURCE_TSV;
579 else if(!strcmp(name, DATASOURCE_FORMAT_HTML)) // html
580 return DATASOURCE_HTML;
582 else if(!strcmp(name, DATASOURCE_FORMAT_JS_ARRAY)) // array
583 return DATASOURCE_JS_ARRAY;
585 else if(!strcmp(name, DATASOURCE_FORMAT_SSV_COMMA)) // ssvcomma
586 return DATASOURCE_SSV_COMMA;
588 else if(!strcmp(name, DATASOURCE_FORMAT_CSV_JSON_ARRAY)) // csvjsonarray
589 return DATASOURCE_CSV_JSON_ARRAY;
591 return DATASOURCE_JSON;
594 uint32_t web_client_api_request_v1_data_google_format(char *name)
596 if(!strcmp(name, "json"))
597 return DATASOURCE_DATATABLE_JSONP;
599 else if(!strcmp(name, "html"))
600 return DATASOURCE_HTML;
602 else if(!strcmp(name, "csv"))
603 return DATASOURCE_CSV;
605 else if(!strcmp(name, "tsv-excel"))
606 return DATASOURCE_TSV;
608 return DATASOURCE_JSON;
611 int web_client_api_request_v1_data_group(char *name)
613 if(!strcmp(name, "max"))
616 else if(!strcmp(name, "average"))
617 return GROUP_AVERAGE;
622 int web_client_api_request_v1_charts(struct web_client *w, char *url)
626 buffer_flush(w->response.data);
627 w->response.data->contenttype = CT_APPLICATION_JSON;
628 rrd_stats_api_v1_charts(w->response.data);
632 int web_client_api_request_v1_chart(struct web_client *w, char *url)
637 buffer_flush(w->response.data);
640 char *value = mystrsep(&url, "?&[]");
641 if(!value || !*value) continue;
643 char *name = mystrsep(&value, "=");
644 if(!name || !*name) continue;
645 if(!value || !*value) continue;
647 // name and value are now the parameters
648 // they are not null and not empty
650 if(!strcmp(name, "chart")) chart = value;
652 /// buffer_sprintf(w->response.data, "Unknown parameter '%s' in request.", name);
657 if(!chart || !*chart) {
658 buffer_sprintf(w->response.data, "No chart id is given at the request.");
662 RRDSET *st = rrdset_find(chart);
663 if(!st) st = rrdset_find_byname(chart);
665 buffer_sprintf(w->response.data, "Chart '%s' is not found.", chart);
670 w->response.data->contenttype = CT_APPLICATION_JSON;
671 rrd_stats_api_v1_chart(st, w->response.data);
678 // returns the HTTP code
679 int web_client_api_request_v1_data(struct web_client *w, char *url)
681 debug(D_WEB_CLIENT, "%llu: API v1 data with URL '%s'", w->id, url);
684 BUFFER *dimensions = NULL;
686 buffer_flush(w->response.data);
688 char *google_version = "0.6",
691 *google_out = "json",
692 *responseHandler = NULL,
695 time_t last_timestamp_in_data = 0, google_timestamp = 0;
700 , *points_str = NULL;
702 int group = GROUP_MAX;
703 uint32_t format = DATASOURCE_JSON;
704 uint32_t options = 0x00000000;
707 char *value = mystrsep(&url, "?&[]");
708 if(!value || !*value) continue;
710 char *name = mystrsep(&value, "=");
711 if(!name || !*name) continue;
712 if(!value || !*value) continue;
714 debug(D_WEB_CLIENT, "%llu: API v1 data query param '%s' with value '%s'", w->id, name, value);
716 // name and value are now the parameters
717 // they are not null and not empty
719 if(!strcmp(name, "chart")) chart = value;
720 else if(!strcmp(name, "dimension") || !strcmp(name, "dim") || !strcmp(name, "dimensions") || !strcmp(name, "dims")) {
721 if(!dimensions) dimensions = buffer_create(strlen(value));
723 buffer_strcat(dimensions, "|");
724 buffer_strcat(dimensions, value);
727 else if(!strcmp(name, "after")) after_str = value;
728 else if(!strcmp(name, "before")) before_str = value;
729 else if(!strcmp(name, "points")) points_str = value;
730 else if(!strcmp(name, "group")) {
731 group = web_client_api_request_v1_data_group(value);
733 else if(!strcmp(name, "format")) {
734 format = web_client_api_request_v1_data_format(value);
736 else if(!strcmp(name, "options")) {
737 options |= web_client_api_request_v1_data_options(value);
739 else if(!strcmp(name, "callback")) {
740 responseHandler = value;
742 else if(!strcmp(name, "filename")) {
745 else if(!strcmp(name, "tqx")) {
746 // parse Google Visualization API options
747 // https://developers.google.com/chart/interactive/docs/dev/implementing_data_source
748 char *tqx_name, *tqx_value;
751 tqx_value = mystrsep(&value, ";");
752 if(!tqx_value || !*tqx_value) continue;
754 tqx_name = mystrsep(&tqx_value, ":");
755 if(!tqx_name || !*tqx_name) continue;
756 if(!tqx_value || !*tqx_value) continue;
758 if(!strcmp(tqx_name, "version"))
759 google_version = tqx_value;
760 else if(!strcmp(tqx_name, "reqId"))
761 google_reqId = tqx_value;
762 else if(!strcmp(tqx_name, "sig")) {
763 google_sig = tqx_value;
764 google_timestamp = strtoul(google_sig, NULL, 0);
766 else if(!strcmp(tqx_name, "out")) {
767 google_out = tqx_value;
768 format = web_client_api_request_v1_data_google_format(google_out);
770 else if(!strcmp(tqx_name, "responseHandler"))
771 responseHandler = tqx_value;
772 else if(!strcmp(tqx_name, "outFileName"))
773 outFileName = tqx_value;
778 if(!chart || !*chart) {
779 buffer_sprintf(w->response.data, "No chart id is given at the request.");
783 RRDSET *st = rrdset_find(chart);
784 if(!st) st = rrdset_find_byname(chart);
786 buffer_sprintf(w->response.data, "Chart '%s' is not found.", chart);
791 long long before = (before_str && *before_str)?atol(before_str):0;
792 long long after = (after_str && *after_str) ?atol(after_str):0;
793 int points = (points_str && *points_str)?atoi(points_str):0;
795 debug(D_WEB_CLIENT, "%llu: API command 'data' for chart '%s', dimensions '%s', after '%lld', before '%lld', points '%d', group '%u', format '%u', options '0x%08x'"
798 , (dimensions)?buffer_tostring(dimensions):""
807 if(outFileName && *outFileName) {
808 buffer_sprintf(w->response.header, "Content-Disposition: attachment; filename=\"%s\"\r\n", outFileName);
809 debug(D_WEB_CLIENT, "%llu: generating outfilename header: '%s'", w->id, outFileName);
812 if(format == DATASOURCE_DATATABLE_JSONP) {
813 if(responseHandler == NULL)
814 responseHandler = "google.visualization.Query.setResponse";
816 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSON/JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
817 w->id, google_version, google_reqId, google_sig, google_out, responseHandler, outFileName
820 buffer_sprintf(w->response.data,
821 "%s({version:'%s',reqId:'%s',status:'ok',sig:'%lu',table:",
822 responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
824 else if(format == DATASOURCE_JSONP) {
825 if(responseHandler == NULL)
826 responseHandler = "callback";
828 buffer_strcat(w->response.data, responseHandler);
829 buffer_strcat(w->response.data, "(");
832 ret = rrd2format(st, w->response.data, dimensions, format, points, after, before, group, options, &last_timestamp_in_data);
834 if(format == DATASOURCE_DATATABLE_JSONP) {
835 if(google_timestamp < last_timestamp_in_data)
836 buffer_strcat(w->response.data, "});");
839 // the client already has the latest data
840 buffer_flush(w->response.data);
841 buffer_sprintf(w->response.data,
842 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
843 responseHandler, google_version, google_reqId);
846 else if(format == DATASOURCE_JSONP)
847 buffer_strcat(w->response.data, ");");
850 if(dimensions) buffer_free(dimensions);
854 int web_client_api_request_v1_registry(struct web_client *w, char *url)
856 static uint32_t hash_action = 0, hash_access = 0, hash_hello = 0, hash_delete = 0, hash_search = 0,
857 hash_switch = 0, hash_machine = 0, hash_url = 0, hash_name = 0, hash_delete_url = 0, hash_for = 0,
860 if(unlikely(!hash_action)) {
861 hash_action = simple_hash("action");
862 hash_access = simple_hash("access");
863 hash_hello = simple_hash("hello");
864 hash_delete = simple_hash("delete");
865 hash_search = simple_hash("search");
866 hash_switch = simple_hash("switch");
867 hash_machine = simple_hash("machine");
868 hash_url = simple_hash("url");
869 hash_name = simple_hash("name");
870 hash_delete_url = simple_hash("delete_url");
871 hash_for = simple_hash("for");
872 hash_to = simple_hash("to");
875 char person_guid[36 + 1] = "";
877 debug(D_WEB_CLIENT, "%llu: API v1 registry with URL '%s'", w->id, url);
880 // The browser may send multiple cookies with our id
882 char *cookie = strstr(w->response.data->buffer, " " NETDATA_REGISTRY_COOKIE_NAME "=");
884 strncpyz(person_guid, &cookie[sizeof(NETDATA_REGISTRY_COOKIE_NAME) + 1], 36);
887 char *machine_guid = NULL,
890 *search_machine_guid = NULL,
892 *to_person_guid = NULL;
895 char *value = mystrsep(&url, "?&[]");
896 if (!value || !*value) continue;
898 char *name = mystrsep(&value, "=");
899 if (!name || !*name) continue;
900 if (!value || !*value) continue;
902 debug(D_WEB_CLIENT, "%llu: API v1 registry query param '%s' with value '%s'", w->id, name, value);
904 uint32_t hash = simple_hash(name);
906 if(hash == hash_action && !strcmp(name, "action")) {
907 uint32_t vhash = simple_hash(value);
909 if(vhash == hash_access && !strcmp(value, "access")) action = 'A';
910 else if(vhash == hash_hello && !strcmp(value, "hello")) action = 'H';
911 else if(vhash == hash_delete && !strcmp(value, "delete")) action = 'D';
912 else if(vhash == hash_search && !strcmp(value, "search")) action = 'S';
913 else if(vhash == hash_switch && !strcmp(value, "switch")) action = 'W';
915 else if(hash == hash_machine && !strcmp(name, "machine"))
916 machine_guid = value;
918 else if(hash == hash_url && !strcmp(name, "url"))
921 else if(action == 'A') {
922 if(hash == hash_name && !strcmp(name, "name"))
925 else if(action == 'D') {
926 if(hash == hash_delete_url && !strcmp(name, "delete_url"))
929 else if(action == 'S') {
930 if(hash == hash_for && !strcmp(name, "for"))
931 search_machine_guid = value;
933 else if(action == 'W') {
934 if(hash == hash_to && !strcmp(name, "to"))
935 to_person_guid = value;
939 if(action == 'A' && (!machine_guid || !machine_url || !url_name)) {
940 buffer_flush(w->response.data);
941 buffer_sprintf(w->response.data, "Invalid registry request - access requires these parameters: machine ('%s'), url ('%s'), name ('%s')",
942 machine_guid?machine_guid:"UNSET", machine_url?machine_url:"UNSET", url_name?url_name:"UNSET");
945 else if(action == 'D' && (!machine_guid || !machine_url || !delete_url)) {
946 buffer_flush(w->response.data);
947 buffer_sprintf(w->response.data, "Invalid registry request - delete requires these parameters: machine ('%s'), url ('%s'), delete_url ('%s')",
948 machine_guid?machine_guid:"UNSET", machine_url?machine_url:"UNSET", delete_url?delete_url:"UNSET");
951 else if(action == 'S' && (!machine_guid || !machine_url || !search_machine_guid)) {
952 buffer_flush(w->response.data);
953 buffer_sprintf(w->response.data, "Invalid registry request - search requires these parameters: machine ('%s'), url ('%s'), for ('%s')",
954 machine_guid?machine_guid:"UNSET", machine_url?machine_url:"UNSET", search_machine_guid?search_machine_guid:"UNSET");
957 else if(action == 'W' && (!machine_guid || !machine_url || !to_person_guid)) {
958 buffer_flush(w->response.data);
959 buffer_sprintf(w->response.data, "Invalid registry request - switching identity requires these parameters: machine ('%s'), url ('%s'), to ('%s')",
960 machine_guid?machine_guid:"UNSET", machine_url?machine_url:"UNSET", to_person_guid?to_person_guid:"UNSET");
966 return registry_request_access_json(w, person_guid, machine_guid, machine_url, url_name, time(NULL));
969 return registry_request_delete_json(w, person_guid, machine_guid, machine_url, delete_url, time(NULL));
972 return registry_request_search_json(w, person_guid, machine_guid, machine_url, search_machine_guid, time(NULL));
975 return registry_request_switch_json(w, person_guid, machine_guid, machine_url, to_person_guid, time(NULL));
978 return registry_request_hello_json(w);
981 buffer_flush(w->response.data);
982 buffer_sprintf(w->response.data, "Invalid registry request - you need to set an action: hello, access, delete, search");
986 buffer_flush(w->response.data);
987 buffer_sprintf(w->response.data, "Invalid or no registry action.");
991 int web_client_api_request_v1(struct web_client *w, char *url)
993 static uint32_t hash_data = 0, hash_chart = 0, hash_charts = 0, hash_registry = 0;
995 if(unlikely(hash_data == 0)) {
996 hash_data = simple_hash("data");
997 hash_chart = simple_hash("chart");
998 hash_charts = simple_hash("charts");
999 hash_registry = simple_hash("registry");
1003 char *tok = mystrsep(&url, "/?&");
1005 debug(D_WEB_CLIENT, "%llu: Searching for API v1 command '%s'.", w->id, tok);
1006 uint32_t hash = simple_hash(tok);
1008 if(hash == hash_data && !strcmp(tok, "data"))
1009 return web_client_api_request_v1_data(w, url);
1011 else if(hash == hash_chart && !strcmp(tok, "chart"))
1012 return web_client_api_request_v1_chart(w, url);
1014 else if(hash == hash_charts && !strcmp(tok, "charts"))
1015 return web_client_api_request_v1_charts(w, url);
1017 else if(hash == hash_registry && !strcmp(tok, "registry"))
1018 return web_client_api_request_v1_registry(w, url);
1021 buffer_flush(w->response.data);
1022 buffer_sprintf(w->response.data, "Unsupported v1 API command: %s", tok);
1027 buffer_flush(w->response.data);
1028 buffer_sprintf(w->response.data, "API v1 command?");
1033 int web_client_api_request(struct web_client *w, char *url)
1035 // get the api version
1036 char *tok = mystrsep(&url, "/?&");
1038 debug(D_WEB_CLIENT, "%llu: Searching for API version '%s'.", w->id, tok);
1039 if(strcmp(tok, "v1") == 0)
1040 return web_client_api_request_v1(w, url);
1042 buffer_flush(w->response.data);
1043 buffer_sprintf(w->response.data, "Unsupported API version: %s", tok);
1048 buffer_flush(w->response.data);
1049 buffer_sprintf(w->response.data, "Which API version?");
1054 int web_client_api_old_data_request(struct web_client *w, char *url, int datasource_type)
1058 char *args = strchr(url, '?');
1064 // get the name of the data to show
1065 char *tok = mystrsep(&url, "/");
1067 // do we have such a data set?
1069 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1070 st = rrdset_find_byname(tok);
1071 if(!st) st = rrdset_find(tok);
1076 // try to send a file with that name
1077 buffer_flush(w->response.data);
1078 return(mysendfile(w, tok));
1082 debug(D_WEB_CLIENT, "%llu: Found RRD data with name '%s'.", w->id, tok);
1084 // how many entries does the client want?
1085 long lines = rrd_default_history_entries;
1086 long group_count = 1;
1087 time_t after = 0, before = 0;
1088 int group_method = GROUP_AVERAGE;
1092 // parse the lines required
1093 tok = mystrsep(&url, "/");
1094 if(tok) lines = atoi(tok);
1095 if(lines < 1) lines = 1;
1098 // parse the group count required
1099 tok = mystrsep(&url, "/");
1100 if(tok && *tok) group_count = atoi(tok);
1101 if(group_count < 1) group_count = 1;
1102 //if(group_count > save_history / 20) group_count = save_history / 20;
1105 // parse the grouping method required
1106 tok = mystrsep(&url, "/");
1108 if(strcmp(tok, "max") == 0) group_method = GROUP_MAX;
1109 else if(strcmp(tok, "average") == 0) group_method = GROUP_AVERAGE;
1110 else if(strcmp(tok, "sum") == 0) group_method = GROUP_SUM;
1111 else debug(D_WEB_CLIENT, "%llu: Unknown group method '%s'", w->id, tok);
1116 tok = mystrsep(&url, "/");
1117 if(tok && *tok) after = strtoul(tok, NULL, 10);
1118 if(after < 0) after = 0;
1121 // parse before time
1122 tok = mystrsep(&url, "/");
1123 if(tok && *tok) before = strtoul(tok, NULL, 10);
1124 if(before < 0) before = 0;
1128 tok = mystrsep(&url, "/");
1129 if(tok && *tok && strcmp(tok, "nonzero") == 0) nonzero = 1;
1132 w->response.data->contenttype = CT_APPLICATION_JSON;
1133 buffer_flush(w->response.data);
1135 char *google_version = "0.6";
1136 char *google_reqId = "0";
1137 char *google_sig = "0";
1138 char *google_out = "json";
1139 char *google_responseHandler = "google.visualization.Query.setResponse";
1140 char *google_outFileName = NULL;
1141 time_t last_timestamp_in_data = 0;
1142 if(datasource_type == DATASOURCE_DATATABLE_JSON || datasource_type == DATASOURCE_DATATABLE_JSONP) {
1144 w->response.data->contenttype = CT_APPLICATION_X_JAVASCRIPT;
1147 tok = mystrsep(&args, "&");
1149 char *name = mystrsep(&tok, "=");
1150 if(name && *name && strcmp(name, "tqx") == 0) {
1151 char *key = mystrsep(&tok, ":");
1152 char *value = mystrsep(&tok, ";");
1153 if(key && value && *key && *value) {
1154 if(strcmp(key, "version") == 0)
1155 google_version = value;
1157 else if(strcmp(key, "reqId") == 0)
1158 google_reqId = value;
1160 else if(strcmp(key, "sig") == 0)
1163 else if(strcmp(key, "out") == 0)
1166 else if(strcmp(key, "responseHandler") == 0)
1167 google_responseHandler = value;
1169 else if(strcmp(key, "outFileName") == 0)
1170 google_outFileName = value;
1176 debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
1177 w->id, google_version, google_reqId, google_sig, google_out, google_responseHandler, google_outFileName
1180 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
1181 last_timestamp_in_data = strtoul(google_sig, NULL, 0);
1183 // check the client wants json
1184 if(strcmp(google_out, "json") != 0) {
1185 buffer_sprintf(w->response.data,
1186 "%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.'}]});",
1187 google_responseHandler, google_version, google_reqId, google_out);
1193 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
1194 buffer_sprintf(w->response.data,
1195 "%s({version:'%s',reqId:'%s',status:'ok',sig:'%lu',table:",
1196 google_responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
1199 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);
1200 time_t timestamp_in_data = rrd_stats_json(datasource_type, st, w->response.data, lines, group_count, group_method, after, before, nonzero);
1202 if(datasource_type == DATASOURCE_DATATABLE_JSONP) {
1203 if(timestamp_in_data > last_timestamp_in_data)
1204 buffer_strcat(w->response.data, "});");
1207 // the client already has the latest data
1208 buffer_flush(w->response.data);
1209 buffer_sprintf(w->response.data,
1210 "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
1211 google_responseHandler, google_version, google_reqId);
1218 const char *web_content_type_to_string(uint8_t contenttype) {
1219 switch(contenttype) {
1221 return "text/html; charset=utf-8";
1223 case CT_APPLICATION_XML:
1224 return "application/xml; charset=utf-8";
1226 case CT_APPLICATION_JSON:
1227 return "application/json; charset=utf-8";
1229 case CT_APPLICATION_X_JAVASCRIPT:
1230 return "application/x-javascript; charset=utf-8";
1233 return "text/css; charset=utf-8";
1236 return "text/xml; charset=utf-8";
1239 return "text/xsl; charset=utf-8";
1241 case CT_APPLICATION_OCTET_STREAM:
1242 return "application/octet-stream";
1244 case CT_IMAGE_SVG_XML:
1245 return "image/svg+xml";
1247 case CT_APPLICATION_X_FONT_TRUETYPE:
1248 return "application/x-font-truetype";
1250 case CT_APPLICATION_X_FONT_OPENTYPE:
1251 return "application/x-font-opentype";
1253 case CT_APPLICATION_FONT_WOFF:
1254 return "application/font-woff";
1256 case CT_APPLICATION_FONT_WOFF2:
1257 return "application/font-woff2";
1259 case CT_APPLICATION_VND_MS_FONTOBJ:
1260 return "application/vnd.ms-fontobject";
1266 return "image/jpeg";
1271 case CT_IMAGE_XICON:
1272 return "image/x-icon";
1278 return "image/icns";
1282 return "text/plain; charset=utf-8";
1287 const char *web_response_code_to_string(int code) {
1293 return "Temporary Redirect";
1296 return "Bad Request";
1305 return "Preconditions Failed";
1308 if(code >= 100 && code < 200)
1309 return "Informational";
1311 if(code >= 200 && code < 300)
1312 return "Successful";
1314 if(code >= 300 && code < 400)
1315 return "Redirection";
1317 if(code >= 400 && code < 500)
1318 return "Bad Request";
1320 if(code >= 500 && code < 600)
1321 return "Server Error";
1323 return "Undefined Error";
1327 static inline char *http_header_parse(struct web_client *w, char *s) {
1328 static uint32_t hash_origin = 0, hash_connection = 0, hash_accept_encoding = 0;
1330 if(unlikely(!hash_origin)) {
1331 hash_origin = simple_uhash("Origin");
1332 hash_connection = simple_uhash("Connection");
1333 hash_accept_encoding = simple_uhash("Accept-Encoding");
1339 while(*e && *e != ':') e++;
1340 if(!*e || e[1] != ' ') return e;
1350 while(*ve && *ve != '\r') ve++;
1351 if(!*ve || ve[1] != '\n') {
1356 // terminate the value
1359 // fprintf(stderr, "HEADER: '%s' = '%s'\n", s, v);
1360 uint32_t hash = simple_uhash(s);
1362 if(hash == hash_origin && !strcasecmp(s, "Origin"))
1363 strncpyz(w->origin, v, ORIGIN_MAX);
1365 else if(hash == hash_connection && !strcasecmp(s, "Connection")) {
1366 if(strcasestr(v, "keep-alive"))
1369 #ifdef NETDATA_WITH_ZLIB
1370 else if(hash == hash_accept_encoding && !strcasecmp(s, "Accept-Encoding")) {
1371 if(web_enable_gzip) {
1372 if(strcasestr(v, "gzip"))
1373 web_client_enable_deflate(w, 1);
1375 // does not seem to work
1376 // else if(strcasestr(v, "deflate"))
1377 // web_client_enable_deflate(w, 0);
1380 #endif /* NETDATA_WITH_ZLIB */
1387 // http_request_validate()
1389 // = 0 : all good, process the request
1390 // > 0 : request is not supported
1391 // < 0 : request is incomplete - wait for more data
1393 static inline int http_request_validate(struct web_client *w) {
1394 char *s = w->response.data->buffer, *encoded_url = NULL;
1396 // is is a valid request?
1397 if(!strncmp(s, "GET ", 4)) {
1398 encoded_url = s = &s[4];
1399 w->mode = WEB_CLIENT_MODE_NORMAL;
1401 else if(!strncmp(s, "OPTIONS ", 8)) {
1402 encoded_url = s = &s[8];
1403 w->mode = WEB_CLIENT_MODE_OPTIONS;
1406 w->wait_receive = 0;
1410 // find the SPACE + "HTTP/"
1412 // find the next space
1413 while (*s && *s != ' ') s++;
1415 // is it SPACE + "HTTP/" ?
1416 if(*s && !strncmp(s, " HTTP/", 6)) break;
1420 // incomplete requests
1422 w->wait_receive = 1;
1426 // we have the end of encoded_url - remember it
1429 // make sure we have complete request
1430 // complete requests contain: \r\n\r\n
1433 while(*s && *s++ != '\r');
1435 // did we reach the end?
1436 if(unlikely(!*s)) break;
1439 if(likely(*s++ == '\n')) {
1441 // is it again \r\n ? (header end)
1442 if(unlikely(*s == '\r' && s[1] == '\n')) {
1443 // a valid complete HTTP request found
1446 url_decode_r(w->decoded_url, encoded_url, URL_MAX + 1);
1449 // copy the URL - we are going to overwrite parts of it
1450 // FIXME -- we should avoid it
1451 strncpyz(w->last_url, w->decoded_url, URL_MAX);
1453 w->wait_receive = 0;
1457 // another header line
1458 s = http_header_parse(w, s);
1462 // incomplete request
1463 w->wait_receive = 1;
1467 void web_client_process(struct web_client *w) {
1468 static uint32_t hash_api = 0, hash_netdata_conf = 0, hash_data = 0, hash_datasource = 0, hash_graph = 0,
1469 hash_list = 0, hash_all_json = 0, hash_exit = 0, hash_debug = 0, hash_mirror = 0;
1471 if(unlikely(!hash_api)) {
1472 hash_api = simple_hash("api");
1473 hash_netdata_conf = simple_hash("netdata.conf");
1474 hash_data = simple_hash(WEB_PATH_DATA);
1475 hash_datasource = simple_hash(WEB_PATH_DATASOURCE);
1476 hash_graph = simple_hash(WEB_PATH_GRAPH);
1477 hash_list = simple_hash("list");
1478 hash_all_json = simple_hash("all.json");
1479 hash_exit = simple_hash("exit");
1480 hash_debug = simple_hash("debug");
1481 hash_mirror = simple_hash("mirror");
1487 int what_to_do = http_request_validate(w);
1489 // wait for more data
1490 if(what_to_do < 0) {
1491 if(w->response.data->len > TOO_BIG_REQUEST) {
1492 strcpy(w->last_url, "too big request");
1494 debug(D_WEB_CLIENT_ACCESS, "%llu: Received request is too big (%zd bytes).", w->id, w->response.data->len);
1497 buffer_flush(w->response.data);
1498 buffer_sprintf(w->response.data, "Received request is too big (%zd bytes).\r\n", w->response.data->len);
1501 // wait for more data
1505 else if(what_to_do > 0) {
1506 strcpy(w->last_url, "not a valid request");
1508 debug(D_WEB_CLIENT_ACCESS, "%llu: Cannot understand '%s'.", w->id, w->response.data->buffer);
1511 buffer_flush(w->response.data);
1512 buffer_strcat(w->response.data, "I don't understand you...\r\n");
1514 else { // what_to_do == 0
1515 gettimeofday(&w->tv_in, NULL);
1517 if(w->mode == WEB_CLIENT_MODE_OPTIONS) {
1519 w->response.data->contenttype = CT_TEXT_PLAIN;
1520 buffer_flush(w->response.data);
1521 buffer_strcat(w->response.data, "OK");
1524 char *url = w->decoded_url;
1525 char *tok = mystrsep(&url, "/?");
1527 uint32_t hash = simple_hash(tok);
1528 debug(D_WEB_CLIENT, "%llu: Processing command '%s'.", w->id, tok);
1530 if(hash == hash_api && strcmp(tok, "api") == 0) {
1531 // the client is requesting api access
1532 code = web_client_api_request(w, url);
1534 else if(hash == hash_netdata_conf && strcmp(tok, "netdata.conf") == 0) {
1536 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending netdata.conf ...", w->id);
1538 w->response.data->contenttype = CT_TEXT_PLAIN;
1539 buffer_flush(w->response.data);
1540 generate_config(w->response.data, 0);
1542 else if(hash == hash_data && strcmp(tok, WEB_PATH_DATA) == 0) { // "data"
1543 // the client is requesting rrd data -- OLD API
1544 code = web_client_api_old_data_request(w, url, DATASOURCE_JSON);
1546 else if(hash == hash_datasource && strcmp(tok, WEB_PATH_DATASOURCE) == 0) { // "datasource"
1547 // the client is requesting google datasource -- OLD API
1548 code = web_client_api_old_data_request(w, url, DATASOURCE_DATATABLE_JSONP);
1550 else if(hash == hash_graph && strcmp(tok, WEB_PATH_GRAPH) == 0) { // "graph"
1551 // the client is requesting an rrd graph -- OLD API
1553 // get the name of the data to show
1554 tok = mystrsep(&url, "/?&");
1556 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1558 // do we have such a data set?
1559 RRDSET *st = rrdset_find_byname(tok);
1560 if(!st) st = rrdset_find(tok);
1563 // try to send a file with that name
1564 buffer_flush(w->response.data);
1565 code = mysendfile(w, tok);
1569 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending %s.json of RRD_STATS...", w->id, st->name);
1570 w->response.data->contenttype = CT_APPLICATION_JSON;
1571 buffer_flush(w->response.data);
1572 rrd_stats_graph_json(st, url, w->response.data);
1577 buffer_flush(w->response.data);
1578 buffer_strcat(w->response.data, "Graph name?\r\n");
1581 else if(hash == hash_list && strcmp(tok, "list") == 0) {
1585 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending list of RRD_STATS...", w->id);
1587 buffer_flush(w->response.data);
1588 RRDSET *st = rrdset_root;
1590 for ( ; st ; st = st->next )
1591 buffer_sprintf(w->response.data, "%s\n", st->name);
1593 else if(hash == hash_all_json && strcmp(tok, "all.json") == 0) {
1596 debug(D_WEB_CLIENT_ACCESS, "%llu: Sending JSON list of all monitors of RRD_STATS...", w->id);
1598 w->response.data->contenttype = CT_APPLICATION_JSON;
1599 buffer_flush(w->response.data);
1600 rrd_stats_all_json(w->response.data);
1602 #ifdef NETDATA_INTERNAL_CHECKS
1603 else if(hash == hash_exit && strcmp(tok, "exit") == 0) {
1605 w->response.data->contenttype = CT_TEXT_PLAIN;
1606 buffer_flush(w->response.data);
1609 buffer_strcat(w->response.data, "ok, will do...");
1611 buffer_strcat(w->response.data, "I am doing it already");
1615 else if(hash == hash_debug && strcmp(tok, "debug") == 0) {
1616 buffer_flush(w->response.data);
1618 // get the name of the data to show
1619 tok = mystrsep(&url, "/?&");
1621 debug(D_WEB_CLIENT, "%llu: Searching for RRD data with name '%s'.", w->id, tok);
1623 // do we have such a data set?
1624 RRDSET *st = rrdset_find_byname(tok);
1625 if(!st) st = rrdset_find(tok);
1628 buffer_sprintf(w->response.data, "Chart %s is not found.\r\n", tok);
1629 debug(D_WEB_CLIENT_ACCESS, "%llu: %s is not found.", w->id, tok);
1633 debug_flags |= D_RRD_STATS;
1634 st->debug = !st->debug;
1635 buffer_sprintf(w->response.data, "Chart %s has now debug %s.\r\n", tok, st->debug?"enabled":"disabled");
1636 debug(D_WEB_CLIENT_ACCESS, "%llu: debug for %s is %s.", w->id, tok, st->debug?"enabled":"disabled");
1641 buffer_flush(w->response.data);
1642 buffer_strcat(w->response.data, "debug which chart?\r\n");
1645 else if(hash == hash_mirror && strcmp(tok, "mirror") == 0) {
1648 debug(D_WEB_CLIENT_ACCESS, "%llu: Mirroring...", w->id);
1650 // replace the zero bytes with spaces
1651 buffer_char_replace(w->response.data, '\0', ' ');
1653 // just leave the buffer as is
1654 // it will be copied back to the client
1656 #endif /* NETDATA_INTERNAL_CHECKS */
1658 char filename[FILENAME_MAX+1];
1660 strncpyz(filename, w->last_url, FILENAME_MAX);
1661 tok = mystrsep(&url, "?");
1662 buffer_flush(w->response.data);
1663 code = mysendfile(w, (tok && *tok)?tok:"/");
1667 char filename[FILENAME_MAX+1];
1669 strncpyz(filename, w->last_url, FILENAME_MAX);
1670 tok = mystrsep(&url, "?");
1671 buffer_flush(w->response.data);
1672 code = mysendfile(w, (tok && *tok)?tok:"/");
1677 gettimeofday(&w->tv_ready, NULL);
1678 w->response.data->date = time(NULL);
1679 w->response.sent = 0;
1680 w->response.code = code;
1682 // prepare the HTTP response header
1683 debug(D_WEB_CLIENT, "%llu: Generating HTTP header with response %d.", w->id, code);
1685 const char *content_type_string = web_content_type_to_string(w->response.data->contenttype);
1686 const char *code_msg = web_response_code_to_string(code);
1689 struct tm tmbuf, *tm = gmtime_r(&w->response.data->date, &tmbuf);
1690 strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %Z", tm);
1692 buffer_sprintf(w->response.header_output,
1693 "HTTP/1.1 %d %s\r\n"
1694 "Connection: %s\r\n"
1695 "Server: NetData Embedded HTTP Server\r\n"
1696 "Access-Control-Allow-Origin: %s\r\n"
1697 "Access-Control-Allow-Credentials: true\r\n"
1698 "Content-Type: %s\r\n"
1701 , w->keepalive?"keep-alive":"close"
1703 , content_type_string
1708 buffer_sprintf(w->response.header_output,
1709 "Set-Cookie: %s\r\n",
1714 buffer_sprintf(w->response.header_output,
1715 "Set-Cookie: %s\r\n",
1719 if(w->mode == WEB_CLIENT_MODE_OPTIONS) {
1720 buffer_strcat(w->response.header_output,
1721 "Access-Control-Allow-Methods: GET, OPTIONS\r\n"
1722 "Access-Control-Allow-Headers: accept, x-requested-with, origin, content-type, cookie\r\n"
1723 "Access-Control-Max-Age: 1209600\r\n" // 86400 * 14
1727 if(buffer_strlen(w->response.header))
1728 buffer_strcat(w->response.header_output, buffer_tostring(w->response.header));
1730 if(w->mode == WEB_CLIENT_MODE_NORMAL && (w->response.data->options & WB_CONTENT_NO_CACHEABLE)) {
1731 buffer_sprintf(w->response.header_output,
1733 "Cache-Control: no-cache\r\n"
1736 else if(w->mode != WEB_CLIENT_MODE_OPTIONS) {
1738 time_t et = w->response.data->date + (86400 * 14);
1739 struct tm etmbuf, *etm = gmtime_r(&et, &etmbuf);
1740 strftime(edate, sizeof(edate), "%a, %d %b %Y %H:%M:%S %Z", etm);
1742 buffer_sprintf(w->response.header_output,
1744 "Cache-Control: public\r\n"
1748 // if we know the content length, put it
1749 if(!w->response.zoutput && (w->response.data->len || w->response.rlen))
1750 buffer_sprintf(w->response.header_output,
1751 "Content-Length: %ld\r\n"
1752 , w->response.data->len? w->response.data->len: w->response.rlen
1754 else if(!w->response.zoutput)
1755 w->keepalive = 0; // content-length is required for keep-alive
1757 if(w->response.zoutput) {
1758 buffer_strcat(w->response.header_output,
1759 "Content-Encoding: gzip\r\n"
1760 "Transfer-Encoding: chunked\r\n"
1764 buffer_strcat(w->response.header_output, "\r\n");
1766 // sent the HTTP header
1767 debug(D_WEB_DATA, "%llu: Sending response HTTP header of size %d: '%s'"
1769 , buffer_strlen(w->response.header_output)
1770 , buffer_tostring(w->response.header_output)
1773 web_client_crock_socket(w);
1775 bytes = send(w->ofd, buffer_tostring(w->response.header_output), buffer_strlen(w->response.header_output), 0);
1776 if(bytes != (ssize_t) buffer_strlen(w->response.header_output)) {
1778 w->stats_sent_bytes += bytes;
1780 debug(D_WEB_CLIENT, "%llu: HTTP Header failed to be sent (I sent %d bytes but the system sent %d bytes). Closing web client.", w->id,
1781 buffer_strlen(w->response.header_output), bytes);
1783 WEB_CLIENT_IS_DEAD(w);
1787 w->stats_sent_bytes += bytes;
1789 // enable sending immediately if we have data
1790 if(w->response.data->len) w->wait_send = 1;
1791 else w->wait_send = 0;
1795 case WEB_CLIENT_MODE_OPTIONS:
1796 debug(D_WEB_CLIENT, "%llu: Done preparing the OPTIONS response. Sending data (%d bytes) to client.", w->id, w->response.data->len);
1799 case WEB_CLIENT_MODE_NORMAL:
1800 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Sending data (%d bytes) to client.", w->id, w->response.data->len);
1803 case WEB_CLIENT_MODE_FILECOPY:
1804 if(w->response.rlen) {
1805 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending data file of %d bytes to client.", w->id, w->response.rlen);
1806 w->wait_receive = 1;
1809 // utilize the kernel sendfile() for copying the file to the socket.
1810 // this block of code can be commented, without anything missing.
1811 // when it is commented, the program will copy the data using async I/O.
1813 long len = sendfile(w->ofd, w->ifd, NULL, w->response.data->rbytes);
1814 if(len != w->response.data->rbytes)
1815 error("%llu: sendfile() should copy %ld bytes, but copied %ld. Falling back to manual copy.", w->id, w->response.data->rbytes, len);
1817 web_client_reset(w);
1822 debug(D_WEB_CLIENT, "%llu: Done preparing the response. Will be sending an unknown amount of bytes to client.", w->id);
1826 fatal("%llu: Unknown client mode %d.", w->id, w->mode);
1831 ssize_t web_client_send_chunk_header(struct web_client *w, size_t len)
1833 debug(D_DEFLATE, "%llu: OPEN CHUNK of %d bytes (hex: %x).", w->id, len, len);
1835 sprintf(buf, "%lX\r\n", len);
1837 ssize_t bytes = send(w->ofd, buf, strlen(buf), 0);
1839 debug(D_DEFLATE, "%llu: Sent chunk header %d bytes.", w->id, bytes);
1840 w->stats_sent_bytes += bytes;
1843 else if(bytes == 0) {
1844 debug(D_WEB_CLIENT, "%llu: Did not send chunk header to the client.", w->id);
1845 WEB_CLIENT_IS_DEAD(w);
1848 debug(D_WEB_CLIENT, "%llu: Failed to send chunk header to client.", w->id);
1849 WEB_CLIENT_IS_DEAD(w);
1855 ssize_t web_client_send_chunk_close(struct web_client *w)
1857 //debug(D_DEFLATE, "%llu: CLOSE CHUNK.", w->id);
1859 ssize_t bytes = send(w->ofd, "\r\n", 2, 0);
1861 debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
1862 w->stats_sent_bytes += bytes;
1865 else if(bytes == 0) {
1866 debug(D_WEB_CLIENT, "%llu: Did not send chunk suffix to the client.", w->id);
1867 WEB_CLIENT_IS_DEAD(w);
1870 debug(D_WEB_CLIENT, "%llu: Failed to send chunk suffix to client.", w->id);
1871 WEB_CLIENT_IS_DEAD(w);
1877 ssize_t web_client_send_chunk_finalize(struct web_client *w)
1879 //debug(D_DEFLATE, "%llu: FINALIZE CHUNK.", w->id);
1881 ssize_t bytes = send(w->ofd, "\r\n0\r\n\r\n", 7, 0);
1883 debug(D_DEFLATE, "%llu: Sent chunk suffix %d bytes.", w->id, bytes);
1884 w->stats_sent_bytes += bytes;
1887 else if(bytes == 0) {
1888 debug(D_WEB_CLIENT, "%llu: Did not send chunk finalize suffix to the client.", w->id);
1889 WEB_CLIENT_IS_DEAD(w);
1892 debug(D_WEB_CLIENT, "%llu: Failed to send chunk finalize suffix to client.", w->id);
1893 WEB_CLIENT_IS_DEAD(w);
1899 #ifdef NETDATA_WITH_ZLIB
1900 ssize_t web_client_send_deflate(struct web_client *w)
1902 ssize_t len = 0, t = 0;
1904 // when using compression,
1905 // w->response.sent is the amount of bytes passed through compression
1907 debug(D_DEFLATE, "%llu: web_client_send_deflate(): w->response.data->len = %d, w->response.sent = %d, w->response.zhave = %d, w->response.zsent = %d, w->response.zstream.avail_in = %d, w->response.zstream.avail_out = %d, w->response.zstream.total_in = %d, w->response.zstream.total_out = %d.", w->id, w->response.data->len, w->response.sent, w->response.zhave, w->response.zsent, w->response.zstream.avail_in, w->response.zstream.avail_out, w->response.zstream.total_in, w->response.zstream.total_out);
1909 if(w->response.data->len - w->response.sent == 0 && w->response.zstream.avail_in == 0 && w->response.zhave == w->response.zsent && w->response.zstream.avail_out != 0) {
1910 // there is nothing to send
1912 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
1914 // finalize the chunk
1915 if(w->response.sent != 0) {
1916 t = web_client_send_chunk_finalize(w);
1920 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->response.rlen && w->response.rlen > w->response.data->len) {
1921 // we have to wait, more data will come
1922 debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
1927 if(unlikely(!w->keepalive)) {
1928 debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->response.sent);
1929 WEB_CLIENT_IS_DEAD(w);
1934 web_client_reset(w);
1935 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket.", w->id);
1939 if(w->response.zhave == w->response.zsent) {
1940 // compress more input data
1942 // close the previous open chunk
1943 if(w->response.sent != 0) {
1944 t = web_client_send_chunk_close(w);
1948 debug(D_DEFLATE, "%llu: Compressing %d new bytes starting from %d (and %d left behind).", w->id, (w->response.data->len - w->response.sent), w->response.sent, w->response.zstream.avail_in);
1950 // give the compressor all the data not passed through the compressor yet
1951 if(w->response.data->len > w->response.sent) {
1952 w->response.zstream.next_in = (Bytef *)&w->response.data->buffer[w->response.sent - w->response.zstream.avail_in];
1953 w->response.zstream.avail_in += (uInt) (w->response.data->len - w->response.sent);
1956 // reset the compressor output buffer
1957 w->response.zstream.next_out = w->response.zbuffer;
1958 w->response.zstream.avail_out = ZLIB_CHUNK;
1960 // ask for FINISH if we have all the input
1961 int flush = Z_SYNC_FLUSH;
1962 if(w->mode == WEB_CLIENT_MODE_NORMAL
1963 || (w->mode == WEB_CLIENT_MODE_FILECOPY && !w->wait_receive && w->response.data->len == w->response.rlen)) {
1965 debug(D_DEFLATE, "%llu: Requesting Z_FINISH, if possible.", w->id);
1968 debug(D_DEFLATE, "%llu: Requesting Z_SYNC_FLUSH.", w->id);
1972 if(deflate(&w->response.zstream, flush) == Z_STREAM_ERROR) {
1973 error("%llu: Compression failed. Closing down client.", w->id);
1974 web_client_reset(w);
1978 w->response.zhave = ZLIB_CHUNK - w->response.zstream.avail_out;
1979 w->response.zsent = 0;
1981 // keep track of the bytes passed through the compressor
1982 w->response.sent = w->response.data->len;
1984 debug(D_DEFLATE, "%llu: Compression produced %d bytes.", w->id, w->response.zhave);
1987 ssize_t t2 = web_client_send_chunk_header(w, w->response.zhave);
1988 if(t2 < 0) return t2;
1992 debug(D_WEB_CLIENT, "%llu: Sending %d bytes of data (+%d of chunk header).", w->id, w->response.zhave - w->response.zsent, t);
1994 len = send(w->ofd, &w->response.zbuffer[w->response.zsent], (size_t) (w->response.zhave - w->response.zsent), MSG_DONTWAIT);
1996 w->stats_sent_bytes += len;
1997 w->response.zsent += len;
1999 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, len);
2002 debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client (zhave = %ld, zsent = %ld, need to send = %ld).", w->id, w->response.zhave, w->response.zsent, w->response.zhave - w->response.zsent);
2003 WEB_CLIENT_IS_DEAD(w);
2006 debug(D_WEB_CLIENT, "%llu: Failed to send data to client.", w->id);
2007 WEB_CLIENT_IS_DEAD(w);
2012 #endif // NETDATA_WITH_ZLIB
2014 ssize_t web_client_send(struct web_client *w) {
2015 #ifdef NETDATA_WITH_ZLIB
2016 if(likely(w->response.zoutput)) return web_client_send_deflate(w);
2017 #endif // NETDATA_WITH_ZLIB
2021 if(unlikely(w->response.data->len - w->response.sent == 0)) {
2022 // there is nothing to send
2024 debug(D_WEB_CLIENT, "%llu: Out of output data.", w->id);
2026 // there can be two cases for this
2027 // A. we have done everything
2028 // B. we temporarily have nothing to send, waiting for the buffer to be filled by ifd
2030 if(w->mode == WEB_CLIENT_MODE_FILECOPY && w->wait_receive && w->response.rlen && w->response.rlen > w->response.data->len) {
2031 // we have to wait, more data will come
2032 debug(D_WEB_CLIENT, "%llu: Waiting for more data to become available.", w->id);
2037 if(unlikely(!w->keepalive)) {
2038 debug(D_WEB_CLIENT, "%llu: Closing (keep-alive is not enabled). %ld bytes sent.", w->id, w->response.sent);
2039 WEB_CLIENT_IS_DEAD(w);
2043 web_client_reset(w);
2044 debug(D_WEB_CLIENT, "%llu: Done sending all data on socket. Waiting for next request on the same socket.", w->id);
2048 bytes = send(w->ofd, &w->response.data->buffer[w->response.sent], w->response.data->len - w->response.sent, MSG_DONTWAIT);
2049 if(likely(bytes > 0)) {
2050 w->stats_sent_bytes += bytes;
2051 w->response.sent += bytes;
2052 debug(D_WEB_CLIENT, "%llu: Sent %d bytes.", w->id, bytes);
2054 else if(likely(bytes == 0)) {
2055 debug(D_WEB_CLIENT, "%llu: Did not send any bytes to the client.", w->id);
2056 WEB_CLIENT_IS_DEAD(w);
2059 debug(D_WEB_CLIENT, "%llu: Failed to send data to client.", w->id);
2060 WEB_CLIENT_IS_DEAD(w);
2066 ssize_t web_client_receive(struct web_client *w)
2068 // do we have any space for more data?
2069 buffer_need_bytes(w->response.data, WEB_REQUEST_LENGTH);
2071 ssize_t left = w->response.data->size - w->response.data->len;
2074 if(unlikely(w->mode == WEB_CLIENT_MODE_FILECOPY))
2075 bytes = read(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1));
2077 bytes = recv(w->ifd, &w->response.data->buffer[w->response.data->len], (size_t) (left - 1), MSG_DONTWAIT);
2079 if(likely(bytes > 0)) {
2080 if(w->mode != WEB_CLIENT_MODE_FILECOPY)
2081 w->stats_received_bytes += bytes;
2083 size_t old = w->response.data->len;
2084 w->response.data->len += bytes;
2085 w->response.data->buffer[w->response.data->len] = '\0';
2087 debug(D_WEB_CLIENT, "%llu: Received %d bytes.", w->id, bytes);
2088 debug(D_WEB_DATA, "%llu: Received data: '%s'.", w->id, &w->response.data->buffer[old]);
2090 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
2093 if(w->response.rlen && w->response.data->len >= w->response.rlen)
2094 w->wait_receive = 0;
2097 else if(likely(bytes == 0)) {
2098 debug(D_WEB_CLIENT, "%llu: Out of input data.", w->id);
2100 // if we cannot read, it means we have an error on input.
2101 // if however, we are copying a file from ifd to ofd, we should not return an error.
2102 // in this case, the error should be generated when the file has been sent to the client.
2104 if(w->mode == WEB_CLIENT_MODE_FILECOPY) {
2105 // we are copying data from ifd to ofd
2106 // let it finish copying...
2107 w->wait_receive = 0;
2109 debug(D_WEB_CLIENT, "%llu: Read the whole file.", w->id);
2110 if(w->ifd != w->ofd) close(w->ifd);
2114 debug(D_WEB_CLIENT, "%llu: failed to receive data.", w->id);
2115 WEB_CLIENT_IS_DEAD(w);
2119 debug(D_WEB_CLIENT, "%llu: receive data failed.", w->id);
2120 WEB_CLIENT_IS_DEAD(w);
2127 // --------------------------------------------------------------------------------------
2128 // the thread of a single client
2130 // 1. waits for input and output, using async I/O
2131 // 2. it processes HTTP requests
2132 // 3. it generates HTTP responses
2133 // 4. it copies data from input to output if mode is FILECOPY
2135 void *web_client_main(void *ptr)
2137 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
2138 error("Cannot set pthread cancel type to DEFERRED.");
2140 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
2141 error("Cannot set pthread cancel state to ENABLE.");
2143 struct web_client *w = ptr;
2144 struct pollfd fds[2], *ifd, *ofd;
2145 int retval, fdmax = 0, timeout;
2147 log_access("%llu: %s port %s connected on thread task id %d", w->id, w->client_ip, w->client_port, gettid());
2150 if(unlikely(w->dead)) {
2151 debug(D_WEB_CLIENT, "%llu: client is dead.", w->id);
2154 else if(unlikely(!w->wait_receive && !w->wait_send)) {
2155 debug(D_WEB_CLIENT, "%llu: client is not set for neither receiving nor sending data.");
2159 if(unlikely(w->ifd < 0 || w->ofd < 0)) {
2160 error("%llu: invalid file descriptor, ifd = %d, ofd = %d (required 0 <= fd", w->id, w->ifd, w->ofd);
2164 if(w->ifd == w->ofd) {
2169 if(w->wait_receive) fds[0].events |= POLLIN;
2170 if(w->wait_send) fds[0].events |= POLLOUT;
2176 ifd = ofd = &fds[0];
2184 if(w->wait_receive) fds[0].events |= POLLIN;
2190 if(w->wait_send) fds[1].events |= POLLOUT;
2196 debug(D_WEB_CLIENT, "%llu: Waiting socket async I/O for %s %s", w->id, w->wait_receive?"INPUT":"", w->wait_send?"OUTPUT":"");
2198 timeout = web_client_timeout * 1000;
2199 retval = poll(fds, fdmax, timeout);
2201 if(unlikely(retval == -1)) {
2202 if(errno == EAGAIN || errno == EINTR) {
2203 debug(D_WEB_CLIENT, "%llu: EAGAIN received.", w->id);
2207 debug(D_WEB_CLIENT, "%llu: LISTENER: poll() failed (input fd = %d, output fd = %d). Closing client.", w->id, w->ifd, w->ofd);
2210 else if(unlikely(!retval)) {
2211 debug(D_WEB_CLIENT, "%llu: Timeout while waiting socket async I/O for %s %s", w->id, w->wait_receive?"INPUT":"", w->wait_send?"OUTPUT":"");
2216 if(w->wait_send && ofd->revents & POLLOUT) {
2218 if(web_client_send(w) < 0) {
2219 debug(D_WEB_CLIENT, "%llu: Cannot send data to client. Closing client.", w->id);
2224 if(w->wait_receive && (ifd->revents & POLLIN || ifd->revents & POLLPRI)) {
2226 if(web_client_receive(w) < 0) {
2227 debug(D_WEB_CLIENT, "%llu: Cannot receive data from client. Closing client.", w->id);
2231 if(w->mode == WEB_CLIENT_MODE_NORMAL) {
2232 debug(D_WEB_CLIENT, "%llu: Attempting to process received data.", w->id);
2233 web_client_process(w);
2237 if(unlikely(!used)) {
2238 debug(D_WEB_CLIENT_ACCESS, "%llu: Received error on socket.", w->id);
2243 web_client_reset(w);
2245 log_access("%llu: %s port %s disconnected from thread task id %d", w->id, w->client_ip, w->client_port, gettid());
2246 debug(D_WEB_CLIENT, "%llu: done...", w->id);
2248 // close the sockets/files now
2249 // to free file descriptors
2250 if(w->ifd == w->ofd) {
2251 if(w->ifd != -1) close(w->ifd);
2254 if(w->ifd != -1) close(w->ifd);
2255 if(w->ofd != -1) close(w->ofd);