Esempio n. 1
0
int
main(int argc, char **argv)
{
	char buffer[0x1000] = { 0 };
	char user[0x100], pwd[0x100], cookie[0x100] = { 0 };

	(void)(argc);
	(void)(argv);

	if (
		!getenv("REQUEST_METHOD") ||
		strcmp(getenv("REQUEST_METHOD"), "POST") ||
		!fread(buffer, 1, sizeof(buffer) - 1, stdin)
	)
		login_page(NULL);

	chomp(buffer);

	if (parse_request(buffer, user, sizeof(user), pwd, sizeof(pwd)))
		login_page("Missing username or password");

	if (!match_user("db/members.csv", user, pwd))
		login_page("Incorrect username or password");

	if (set_cookie("db/loggedin.csv", user, cookie, sizeof(cookie)))
		login_page("Internal error, please try again");

	catalog_page(user, cookie);
	return 0;
}
Esempio n. 2
0
// A handler for the /authorize endpoint.
// Login page form sends user name and password to this endpoint.
static void authorize(struct mg_connection *conn,
                      const struct mg_request_info *request_info) {
  char user[32], password[32], referer[256];

  if(!strcmp(request_info->request_method, "POST")) {
    char post_data[1024];
    int post_data_len = mg_read(conn, post_data, sizeof(post_data));

    mg_get_var(post_data, post_data_len, "user", user, sizeof(user));
    mg_get_var(post_data, post_data_len, "password", password, sizeof(password));
    mg_get_var(post_data, post_data_len, "referer", referer, sizeof(referer));
  } else {
    // Fetch user name and password.
    get_qsvar(request_info, "user", user, sizeof(user));
    get_qsvar(request_info, "password", password, sizeof(password));
    get_qsvar(request_info, "ref", referer, sizeof(referer));
  }

  /* Referer url must begin with '/' */
  if((referer[0] != '/') || (strcmp(referer, AUTHORIZE_URL) == 0))
    strcpy(referer, "/");

  if(ntop->checkUserPassword(user, password)) {
    set_cookie(conn, user, referer);
  } else {
    // Authentication failure, redirect to login.
    redirect_to_login(conn, request_info);
  }
}
Esempio n. 3
0
    void http_client::set_cookie(const std::string& cookie_name, long cookie_value)
    {
        char buf[21] = { 0 };
#ifdef __WXMSW__
        ::ltoa(cookie_value, buf, 10);
#else
        sprintf(buf, "%ld", cookie_value);
#endif
        set_cookie(cookie_name, buf);
    }
Esempio n. 4
0
int
main(int argc, char **argv)
{
    struct cookie c;
    struct cookie_jar *cj;

    if(argv[1]) {
        printf("Raw Cookie: [%s]\n", argv[1]);
        parse_cookie(&c, argv[1], strlen(argv[1]));
        print_cookie(&c);
        set_cookie(&cj, &c);
        print_cookie_jar(cj);
    }
}
Esempio n. 5
0
void AdminLoginHandler::main(std::string url) {
    std::string username = request().post("username");
    std::string password = request().post("password");
    Login *login = new Login();
    std::string usercode = login->user_login(username, password, 2);
    cppcms::json::value json_result;
    if (usercode.size() > 0){
        json_result["result"] = "login success";
        set_cookie("usercode", usercode);
        set_session(usercode, "admin");
    }
    else {
        json_result["result"] = "login failed";
    }
    response_as_json(json_result);
    delete login;
}
Esempio n. 6
0
static am_status_t add_header_in_response(am_request_t *rq, const char *key, const char *value) {
    am_status_t status = AM_ERROR;
    request_rec *r = (request_rec *) (rq != NULL ? rq->ctx : NULL);
    if (r == NULL || !ISVALID(key)) return AM_EINVAL;
    if (!ISVALID(value)) {
        /*value is empty, sdk is setting a cookie in response*/
        status = set_cookie(rq, key);
    } else {
        /* Apache HTTPD keeps two separate server response header tables in the request 
         * record — one for normal response headers and one for error headers. 
         * The difference between them is the error headers are sent to 
         * the client even (not only) on an error response (REDIRECT is one of them)
         */
        apr_table_add(r->err_headers_out, key, value);
        status = AM_SUCCESS;
    }
    return status;
}
getdns_return_t parse_args(int argc, char **argv)
{
	getdns_return_t r = GETDNS_RETURN_GOOD;
	size_t i;
	char *arg, *c, *endptr;
	int t, print_api_info = 0;
	getdns_list *upstream_list = NULL;
	size_t upstream_count = 0;

	for (i = 1; i < argc; i++) {
		arg = argv[i];
		if ((t = get_rrtype(arg)) >= 0) {
			request_type = t;
			continue;

		} else if (arg[0] == '+') {
			if (arg[1] == 's' && arg[2] == 'i' && arg[3] == 't' &&
			   (arg[4] == '=' || arg[4] == '\0')) {
				if ((r = set_cookie(extensions, arg+4))) {
					fprintf(stderr, "Could not set cookie:"
					    " %d", r);
					break;
				}
			} else if ((r = getdns_dict_set_int(extensions, arg+1,
			    GETDNS_EXTENSION_TRUE))) {
				fprintf(stderr, "Could not set extension "
				    "\"%s\": %d\n", argv[i], r);
				break;
			}
			continue;

		} else if (arg[0] == '@') {
			getdns_dict *upstream = ipaddr_dict(context, arg + 1);
			if (upstream) {
				if (!upstream_list &&
				    !(upstream_list =
				    getdns_list_create_with_context(context))){
					fprintf(stderr, "Could not create upstream list\n");
					return GETDNS_RETURN_MEMORY_ERROR;
				}
				getdns_list_set_dict(upstream_list,
				    upstream_count++, upstream);
			}
			continue;
		} else if (arg[0] != '-') {
			name = arg;
			continue;
		}
		for (c = arg+1; *c; c++) {
			switch (*c) {
			case 'a':
				async = 1;
				break;
			case 'A':
				calltype = ADDRESS;
				break;
			case 'b':
				if (c[1] != 0 || ++i >= argc || !*argv[i]) {
					fprintf(stderr, "max_udp_payload_size "
					    "expected after -b\n");
					return GETDNS_RETURN_GENERIC_ERROR;
				}
				edns0_size = strtol(argv[i], &endptr, 10);
				if (*endptr || edns0_size < 0) {
					fprintf(stderr, "positive "
					    "numeric max_udp_payload_size "
					    "expected after -b\n");
					return GETDNS_RETURN_GENERIC_ERROR;
				}
				getdns_context_set_edns_maximum_udp_payload_size(
				    context, (uint16_t) edns0_size);
				goto next;
			case 'D':
				(void) getdns_context_set_edns_do_bit(context, 1);
				break;
			case 'd':
				(void) getdns_context_set_edns_do_bit(context, 0);
				break;
			case 'F':
				if (c[1] != 0 || ++i >= argc || !*argv[i]) {
					fprintf(stderr, "file name expected "
					    "after -F\n");
					return GETDNS_RETURN_GENERIC_ERROR;
				}
				query_file = argv[i];
				interactive = 1;
				break;
			case 'G':
				calltype = GENERAL;
				break;
			case 'H':
				calltype = HOSTNAME;
				break;
			case 'h':
				print_usage(stdout, argv[0]);
				return CONTINUE;
			case 'i':
				print_api_info = 1;
				break;
			case 'I':
				interactive = 1;
				break;
			case 'j':
				json = 2;
				break;
			case 'J':
				json = 1;
				break;
			case 'p':
				json = 0;
			case 'q':
				quiet = 1;
				break;
			case 'r':
				getdns_context_set_resolution_type(
				    context,
				    GETDNS_RESOLUTION_RECURSING);
				break;
			case 's':
				getdns_context_set_resolution_type(
				    context, GETDNS_RESOLUTION_STUB);
				break;
			case 'S':
				calltype = SERVICE;
				break;
			case 't':
				if (c[1] != 0 || ++i >= argc || !*argv[i]) {
					fprintf(stderr, "ttl expected "
					    "after -t\n");
					return GETDNS_RETURN_GENERIC_ERROR;
				}
				timeout = strtol(argv[i], &endptr, 10);
				if (*endptr || timeout < 0) {
					fprintf(stderr, "positive "
					    "numeric ttl expected "
					    "after -t\n");
					return GETDNS_RETURN_GENERIC_ERROR;
				}
				getdns_context_set_timeout(
					context, timeout);
				goto next;
			case 'T':
				getdns_context_set_dns_transport(context,
				    GETDNS_TRANSPORT_TCP_ONLY);
				break;
			case 'O':
				getdns_context_set_dns_transport(context,
				    GETDNS_TRANSPORT_TCP_ONLY_KEEP_CONNECTIONS_OPEN);
				break;
			case 'L':
				getdns_context_set_dns_transport(context,
				    GETDNS_TRANSPORT_TLS_ONLY_KEEP_CONNECTIONS_OPEN);
				break;
			case 'E':
				getdns_context_set_dns_transport(context,
				    GETDNS_TRANSPORT_TLS_FIRST_AND_FALL_BACK_TO_TCP_KEEP_CONNECTIONS_OPEN);
				break;
			case 'u':
				getdns_context_set_dns_transport(context,
				    GETDNS_TRANSPORT_UDP_FIRST_AND_FALL_BACK_TO_TCP);
				break;
			case 'U':
				getdns_context_set_dns_transport(context,
				    GETDNS_TRANSPORT_UDP_ONLY);
				break;
			case 'B':
				batch_mode = 1;
			break;


			default:
				fprintf(stderr, "Unknown option "
				    "\"%c\"\n", *c);
				for (i = 0; i < argc; i++)
					fprintf(stderr, "%d: \"%s\"\n", (int)i, argv[i]);
				return GETDNS_RETURN_GENERIC_ERROR;
			}
		}
next:		;
	}
	if (r)
		return r;
	if (upstream_count &&
	    (r = getdns_context_set_upstream_recursive_servers(
	    context, upstream_list))) {
		fprintf(stderr, "Error setting upstream recursive servers\n");
	}
	if (print_api_info) {
		fprintf(stdout, "%s\n", getdns_pretty_print_dict(
		    getdns_context_get_api_information(context)));
		return CONTINUE;
	}
	return r;
}
Esempio n. 8
0
void http_got_header(struct connection *c, struct read_buffer *rb)
{
    int cf;
    int state = c->state != S_PROC ? S_GETH : S_PROC;
    unsigned char *head;
    unsigned char *cookie, *ch;
    int a, h, version;
    unsigned char *d;
    struct cache_entry *e;
    struct http_connection_info *info;
    unsigned char *host = upcase(c->url[0]) != 'P' ? c->url : get_url_data(c->url);
    set_timeout(c);
    info = c->info;
    if (rb->close == 2) {
        unsigned char *h;
        if (!c->tries && (h = get_host_name(host))) {
            if (info->bl_flags & BL_NO_CHARSET) {
                del_blacklist_entry(h, BL_NO_CHARSET);
            } else {
                add_blacklist_entry(h, BL_NO_CHARSET);
                c->tries = -1;
            }
            mem_free(h);
        }
        setcstate(c, S_CANT_READ);
        retry_connection(c);
        return;
    }
    rb->close = 0;
again:
    if ((a = get_header(rb)) == -1) {
        setcstate(c, S_HTTP_ERROR);
        abort_connection(c);
        return;
    }
    if (!a) {
        read_from_socket(c, c->sock1, rb, http_got_header);
        setcstate(c, state);
        return;
    }
    if (a != -2) {
        head = mem_alloc(a + 1);
        memcpy(head, rb->data, a);
        head[a] = 0;
        kill_buffer_data(rb, a);
    } else {
        head = stracpy("HTTP/0.9 200 OK\r\nContent-Type: text/html\r\n\r\n");
    }
    if (get_http_code(head, &h, &version) || h == 101) {
        mem_free(head);
        setcstate(c, S_HTTP_ERROR);
        abort_connection(c);
        return;
    }
    if (check_http_server_bugs(host, c->info, head) && is_connection_restartable(c)) {
        mem_free(head);
        setcstate(c, S_RESTART);
        retry_connection(c);
        return;
    }
    ch = head;
    while ((cookie = parse_http_header(ch, "Set-Cookie", &ch))) {
        unsigned char *host = upcase(c->url[0]) != 'P' ? c->url : get_url_data(c->url);
        set_cookie(NULL, host, cookie);
        mem_free(cookie);
    }
    if (h == 100) {
        mem_free(head);
        state = S_PROC;
        goto again;
    }
    if (h < 200) {
        mem_free(head);
        setcstate(c, S_HTTP_ERROR);
        abort_connection(c);
        return;
    }
    if (h == 204) {
        mem_free(head);
        setcstate(c, S_HTTP_204);
        http_end_request(c, 0);
        return;
    }
    if (h == 304) {
        mem_free(head);
        setcstate(c, S_OK);
        http_end_request(c, 1);
        return;
    }
    if ((h == 500 || h == 502 || h == 503 || h == 504) && http_bugs.retry_internal_errors && is_connection_restartable(c)) {
        /* !!! FIXME: wait some time ... */
        mem_free(head);
        setcstate(c, S_RESTART);
        retry_connection(c);
        return;
    }
    if (!c->cache && get_cache_entry(c->url, &c->cache)) {
        mem_free(head);
        setcstate(c, S_OUT_OF_MEM);
        abort_connection(c);
        return;
    }
    e = c->cache;
    e->http_code = h;
    if (e->head) mem_free(e->head);
    e->head = head;
    if ((d = parse_http_header(head, "Expires", NULL))) {
        time_t t = parse_http_date(d);
        if (t && e->expire_time != 1) e->expire_time = t;
        mem_free(d);
    }
    if ((d = parse_http_header(head, "Pragma", NULL))) {
        if (!casecmp(d, "no-cache", 8)) e->expire_time = 1;
        mem_free(d);
    }
    if ((d = parse_http_header(head, "Cache-Control", NULL))) {
        char *f = d;
        while (1) {
            while (*f && (*f == ' ' || *f == ',')) f++;
            if (!*f) break;
            if (!casecmp(f, "no-cache", 8) || !casecmp(f, "must-revalidate", 15)) {
                e->expire_time = 1;
            }
            if (!casecmp(f, "max-age=", 8)) {
                if (e->expire_time != 1) e->expire_time = time(NULL) + atoi(f + 8);
            }
            while (*f && *f != ',') f++;
        }
        mem_free(d);
    }
#ifdef HAVE_SSL
    if (c->ssl) {
        int l = 0;
        if (e->ssl_info) mem_free(e->ssl_info);
        e->ssl_info = init_str();
        add_num_to_str(&e->ssl_info, &l, SSL_get_cipher_bits(c->ssl, NULL));
        add_to_str(&e->ssl_info, &l, "-bit ");
        add_to_str(&e->ssl_info, &l, SSL_get_cipher_version(c->ssl));
        add_to_str(&e->ssl_info, &l, " ");
        add_to_str(&e->ssl_info, &l, (unsigned  char *)SSL_get_cipher_name(c->ssl));
    }
#endif
    if (e->redirect) mem_free(e->redirect), e->redirect = NULL;
    if (h == 301 || h == 302 || h == 303 || h == 307) {
        if ((h == 302 || h == 307) && !e->expire_time) e->expire_time = 1;
        if ((d = parse_http_header(e->head, "Location", NULL))) {
            unsigned char *user, *ins;
            unsigned char *newuser, *newpassword;
            if (!parse_url(d, NULL, &user, NULL, NULL, NULL, &ins, NULL, NULL, NULL, NULL, NULL, NULL) && !user && ins && (newuser = get_user_name(host))) {
                if (*newuser) {
                    int ins_off = ins - d;
                    newpassword = get_pass(host);
                    if (!newpassword) newpassword = stracpy("");
                    add_to_strn(&newuser, ":");
                    add_to_strn(&newuser, newpassword);
                    add_to_strn(&newuser, "@");
                    extend_str(&d, strlen(newuser));
                    ins = d + ins_off;
                    memmove(ins + strlen(newuser), ins, strlen(ins) + 1);
                    memcpy(ins, newuser, strlen(newuser));
                    mem_free(newpassword);
                }
                mem_free(newuser);
            }
            if (e->redirect) mem_free(e->redirect);
            e->redirect = d;
            e->redirect_get = h == 303;
        }
    }
    if (!e->expire_time && strchr(c->url, POST_CHAR)) e->expire_time = 1;
    info->close = 0;
    info->length = -1;
    info->version = version;
    if ((d = parse_http_header(e->head, "Connection", NULL)) || (d = parse_http_header(e->head, "Proxy-Connection", NULL))) {
        if (!strcasecmp(d, "close")) info->close = 1;
        mem_free(d);
    } else if (version < 11) info->close = 1;
    cf = c->from;
    c->from = 0;
    if ((d = parse_http_header(e->head, "Content-Range", NULL))) {
        if (strlen(d) > 6) {
            d[5] = 0;
            if (!(strcasecmp(d, "bytes")) && d[6] >= '0' && d[6] <= '9') {
#if defined(HAVE_STRTOLL)
                long long f = strtoll(d + 6, NULL, 10);
#elif defined(HAVE_STRTOQ)
                longlong f = strtoq(d + 6, NULL, 10);
#else
                long f = strtol(d + 6, NULL, 10);
                if (f == MAXLONG) f = -1;
#endif
                if (f >= 0 && (off_t)f >= 0 && (off_t)f == f) c->from = f;
            }
        }
        mem_free(d);
    }
    if (cf && !c->from && !c->unrestartable) c->unrestartable = 1;
    if (c->from > cf || c->from < 0) {
        setcstate(c, S_HTTP_ERROR);
        abort_connection(c);
        return;
    }
    if ((d = parse_http_header(e->head, "Content-Length", NULL))) {
        unsigned char *ep;
#if defined(HAVE_STRTOLL)
        long long l = strtoll(d, (char **)(void *)&ep, 10);
#elif defined(HAVE_STRTOQ)
        longlong l = strtoq(d, (char **)(void *)&ep, 10);
#else
        long l = strtol(d, (char **)(void *)&ep, 10);
        if (l == MAXLONG) l = -1;
#endif
        if (!*ep && l >= 0 && (off_t)l >= 0 && (off_t)l == l) {
            if (!info->close || version >= 11) info->length = l;
            if (c->from + l >= 0) c->est_length = c->from + l;
        }
        mem_free(d);
    }
    if ((d = parse_http_header(e->head, "Accept-Ranges", NULL))) {
        if (!strcasecmp(d, "none") && !c->unrestartable) c->unrestartable = 1;
        mem_free(d);
    } else {
        if (!c->unrestartable && !c->from) c->unrestartable = 1;
    }
    if (info->bl_flags & BL_NO_RANGE && !c->unrestartable) c->unrestartable = 1;
    if ((d = parse_http_header(e->head, "Transfer-Encoding", NULL))) {
        if (!strcasecmp(d, "chunked")) {
            info->length = -2;
            info->chunk_remaining = -1;
        }
        mem_free(d);
    }
    if (!info->close && info->length == -1) info->close = 1;
    if ((d = parse_http_header(e->head, "Last-Modified", NULL))) {
        if (e->last_modified && strcasecmp(e->last_modified, d)) {
            delete_entry_content(e);
            if (c->from) {
                c->from = 0;
                mem_free(d);
                setcstate(c, S_MODIFIED);
                retry_connection(c);
                return;
            }
        }
        if (!e->last_modified) e->last_modified = d;
        else mem_free(d);
    }
    if (!e->last_modified && (d = parse_http_header(e->head, "Date", NULL)))
        e->last_modified = d;
    if (info->length == -1 || (version < 11 && info->close)) rb->close = 1;
    read_http_data(c, rb);
}
Esempio n. 9
0
		void delete_cookie(const std::string& name)
		{
			set_cookie(name, std::string());
		}
Esempio n. 10
0
    bool http_client::grab_url(const std::string& url, const std::string& method, const std::string& post_body)
    {
        error_field.clear();
        returned_headers.clear();
        http_return = 0;
        returned_body.clear();

        std::string to_use_method = strtoupper(method);

        std::string scheme, user, pass, host, path;
        short port;
        if ( !parse_url(url, scheme, user, pass, host, port, path) )
        {
            error_field = "Couldn't parse the URL!";
            return false;
        }

        // Build request
        std::stringstream ret;
        ret << to_use_method << ' ' << path << " HTTP/1.0\r\n"
            << "Host: " << host;
        if (port != 80 && port != 443) ret << ':' << port;
        ret << "\r\n";

        bool content_length_said = false;

        set_header("Connection", "Close");
        for (stringmap::iterator ci = headers.begin(); ci != headers.end(); ++ci)
        {
            std::string head = strtolower(ci->first);

            if ( head == "content-length" )
            {
                content_length_said = true;
            }

            ret << ci->first << ':' << ' ' << ci->second << "\r\n";
        }

        if ( !content_length_said && to_use_method != "GET" )
            ret << "Content-Length: " << static_cast<unsigned int>(post_body.size()) << "\r\n";

        std::stringstream cookie_ss;
        for (stringmap::iterator ci = cookies.begin(); ci != cookies.end(); ++ci)
        {
            std::string var = ci->first ; trim(var);
            std::string val = ci->second; trim(val);

            if ( val.empty() || var.empty() )
                continue;

            if ( !cookie_ss.str().empty() )
                cookie_ss << ';' << ' ';

            cookie_ss << urlencode(var) << '=' << urlencode(val);
        }

        if ( !cookie_ss.str().empty() )
            ret << "Cookie: " << cookie_ss.str() << "\r\n";

        ret << "\r\n";
        ret << post_body;

        std::string request_build = ret.str();

        std::stringstream ss;
        {
            dlib::connection * conn(0);
            try
            {
                if (timeout > 0)
                    conn = dlib::connect(host, port, timeout);
                else
                    conn = dlib::connect(host, port);
            }
            catch (const dlib::socket_error& e)
            {
                error_field = e.what();
                return false;
            }

            // Implement a timeout
            timeout_ptr t;
            if ( timeout > 0 )
                t.reset( new dlib::timeout(*conn, &dlib::connection::shutdown, timeout) );

            // Write our request
            conn->write(request_build.c_str(), static_cast<long>(request_build.size()));

            t.reset();

            // And read the response
            char buf[512];
            long bytes_read(0), bytes_total(0);
            bool read_headers(true);

            if ( timeout > 0 )
                t.reset( new dlib::timeout(*conn, &dlib::connection::shutdown, timeout) );

            while ( (bytes_read = conn->read(buf, 512)) > 0 )
            {
                ss.write(buf, bytes_read);

                // Incremental read headers
                if ( read_headers )
                {
                    std::string body_with_headers = ss.str();
                    std::string::size_type ctr(0);

                    while ( true )
                    {
                        std::string::size_type pos = body_with_headers.find("\r\n", ctr);
                        if ( pos == std::string::npos )
                        {
                            // This is our last position of "\r\n"
                            ss.str("");
                            ss.write( body_with_headers.substr(ctr).c_str(), body_with_headers.size() - ctr );
                            break;
                        }

                        std::string header = body_with_headers.substr(ctr, pos-ctr);
                        if ( header.empty() )
                        {
                            // Ok, we're done reading the headers
                            read_headers = false;
                            // What follows now is the body
                            ss.str("");
                            ss.write( body_with_headers.substr(pos + 2).c_str(), body_with_headers.size() - pos - 2 );
                            break;
                        }
                        ctr = pos + 2;

                        if ( returned_headers.empty() )
                        {
                            if (
                                header[0] == 'H' &&
                                header[1] == 'T' &&
                                header[2] == 'T' &&
                                header[3] == 'P' &&
                                header[4] == '/' &&
                                (header[5] >= '0' && header[5] <= '9') &&
                                header[6] == '.' &&
                                (header[7] >= '0' && header[7] <= '9') &&
                                header[8] == ' '
                            )
                            {
                                http_return = (header[9 ] - '0') * 100 +
                                    (header[10] - '0') * 10 +
                                    (header[11] - '0');
                                continue;
                            }
                        }

                        std::string::size_type pos_dp = header.find_first_of(':');
                        std::string header_name, header_value;
                        if ( pos_dp == std::string::npos )
                        {
                            // **TODO** what should I do here??
                            header_name = header;
                        }
                        else
                        {
                            header_name  = trim(header.substr(0, pos_dp));
                            header_value = trim(header.substr(pos_dp+1));
                        }

                        returned_headers[ header_name ].push_back(header_value);

                        if ( BR_CASECMP(header_name.c_str(), "Content-Length", 14) == 0 )
                        {
                            bytes_total = atol( header_value.c_str() );
                        }
                        else if ( BR_CASECMP(header_name.c_str(), "Set-Cookie", 10) == 0 )
                        {
                            std::string::size_type cur_pos(0), pos_pk, pos_is;
                            std::string work, var, val;
                            for ( cur_pos = 0; cur_pos < header_value.size(); cur_pos++ )
                            {
                                pos_pk = header_value.find(';', cur_pos);
                                work   = trim( header_value.substr(cur_pos, pos_pk - cur_pos) );

                                pos_is = work.find('=');
                                if ( pos_is != std::string::npos )
                                { // Hmmm? what in the else case?
                                    var = trim( http_client::urldecode( work.substr(0, pos_is) ) );
                                    val = trim( http_client::urldecode( work.substr(pos_is + 1) ) );

                                    if ( var != "expires" && var != "domain" && var != "path" )
                                        set_cookie( var, val );
                                }
                                cur_pos = pos_pk == std::string::npos ? pos_pk - 1 : pos_pk;
                            }
                        } // Set-Cookie?

                    } // while (true)
                } // read_headers?

                // Call the OnDownload function if it's set
                if ( OnDownload && !read_headers )
                {
                    if ( (*OnDownload)(static_cast<long>(ss.tellp()), bytes_total, user_info) == false )
                    {
                        t.reset();
                        break;
                    }
                }

                if ( bytes_total != 0 && static_cast<long>(ss.tellp()) == bytes_total )
                {
                    t.reset();
                    break;
                }

                if ( timeout > 0 )
                    t.reset( new dlib::timeout(*conn, &dlib::connection::shutdown, timeout) );
            } // while still data to read

            t.reset();

            delete conn;


            switch ( bytes_read )
            {
                case dlib::TIMEOUT:      error_field = "Timeout";     return false; break;
                case dlib::WOULDBLOCK:   error_field = "Would block"; return false; break;
                case dlib::OTHER_ERROR:  error_field = "Other error"; return false; break;
                case dlib::SHUTDOWN:     error_field = "Timeout";     return false; break;
                case dlib::PORTINUSE:    error_field = "Port in use"; return false; break;
            }
        }

        returned_body = ss.str();

        return true;
    }
Esempio n. 11
0
// Return 1 if request is authorized, 0 otherwise.
static int is_authorized(const struct mg_connection *conn,
                         const struct mg_request_info *request_info,
			 char *username, u_int username_len) {
  char session_id[33], buf[128];
  char key[64], user[32];
  char password[32];
  const char *auth_header_p;
  string auth_type = "", auth_string = "";
  bool user_login_disabled = !ntop->getPrefs()->is_users_login_enabled() ||
    authorized_localhost_users_login_disabled(conn);

  if(user_login_disabled) {
    mg_get_cookie(conn, "user", username, username_len);
    if(strncmp(username, NTOP_NOLOGIN_USER, username_len)) {
      set_cookie(conn, (char *)NTOP_NOLOGIN_USER, NULL);
    }
    return 1;
  }

  // Always authorize accesses to login page and to authorize URI
  if((!strcmp(request_info->uri, LOGIN_URL))
     || (!strcmp(request_info->uri, AUTHORIZE_URL))) {
    return 1;
  }

  if((!strcmp(request_info->uri, Utils::getURL((char*)LOGIN_URL, buf, sizeof(buf))))
     || (!strcmp(request_info->uri, Utils::getURL((char*)AUTHORIZE_URL, buf, sizeof(buf))))) {
    return 1;
  }

  /* Try to decode Authorization header if present */
  auth_header_p = mg_get_header(conn, "Authorization");
  string auth_header = auth_header_p ? auth_header_p  : "";
  istringstream iss(auth_header);
  getline(iss, auth_type, ' ');
  if(auth_type == "Basic") {
    string decoded_auth, user_s = "", pword_s = "";
    /* In case auth type is Basic, info are encoded in base64 */
    getline(iss, auth_string, ' ');
    decoded_auth = Utils::base64_decode(auth_string);
    istringstream authss(decoded_auth);
    getline(authss, user_s, ':');
    getline(authss, pword_s, ':');

    return ntop->checkUserPassword(user_s.c_str(), pword_s.c_str());
  }

  mg_get_cookie(conn, "user", username, username_len);
  mg_get_cookie(conn, "session", session_id, sizeof(session_id));

  if(!strcmp(username, NTOP_NOLOGIN_USER) && !user_login_disabled)
    /* Trying to access web interface with nologin after ntopng restart
       with different settings */
    return 0;

  if(session_id[0] == '\0') {
    /* Last resort: see if we have a user and password matching */
    mg_get_cookie(conn, "password", password, sizeof(password));

    return(ntop->checkUserPassword(username, password));
  }

  // ntop->getTrace()->traceEvent(TRACE_WARNING, "[HTTP] Received session %s/%s", session_id, username);

  snprintf(key, sizeof(key), CONST_RUNTIME_IS_AUTOLOGOUT_ENABLED);
  ntop->getRedis()->get(key, buf, sizeof(buf));
  // do_auto_logout() is the getter for the command-line specified
  // preference that defaults to true (i.e., auto_logout is enabled by default)
  // If do_auto_logout() is disabled, then the runtime auto logout preference
  // is taken into accout.
  // If do_auto_logout() is false, then the auto logout is disabled regardless
  // of runtime preferences.
  if(ntop->getPrefs()->do_auto_logout() && strncmp(buf, (char*)"1", 1) == 0) {
    snprintf(key, sizeof(key), "sessions.%s", session_id);
    if((ntop->getRedis()->get(key, user, sizeof(user)) < 0)
       || strcmp(user, username) /* Users don't match */) {
      ntop->getTrace()->traceEvent(TRACE_INFO, "[HTTP] Session %s/%s is expired or empty user",
				   session_id, username);
      return(0);
    } else {
      ntop->getRedis()->expire(key, HTTP_SESSION_DURATION); /* Extend session */
      ntop->getTrace()->traceEvent(TRACE_INFO, "[HTTP] Session %s is OK: extended for %u sec",
				   session_id, HTTP_SESSION_DURATION);
      return(1);
    }
  } else
    return(1);
}