Repository navigation
Expand file tree
/
Copy pathhttps_hello.cpp
More file actions
133 lines (119 loc) · 5.71 KB
/
Copy pathhttps_hello.cpp
File metadata and controls
133 lines (119 loc) · 5.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
// A minimal HTTPS server (#33): the HTTP/1.1 server of http_hello.cpp over TLS 1.3, written twice:
// with the TAPS layer (the portable surface: listen with security_parameters) and with the
// tls::stream adaptor of the socket layer (a stdnet extension).
//
// https_hello cert.pem key.pem [port] [--stream] then: curl --cacert cert.pem https://localhost:8443/
//
// The test identity of tests/fixtures/tls serves localhost and 127.0.0.1.
#include <charconv>
#include <coroutine> // std::coroutine_traits must be visible to define a coroutine, also after import stdnet;
#include <cstdio>
#include <cstring>
#include <exception>
#include <format>
#include <fstream>
#include <sstream>
#include <string>
#include <string_view>
#include <network>
namespace net = stdnet;
namespace ex = stdnet::ex;
using net::ip::tcp;
namespace {
// One HTTP/1.1 exchange loop over any byte stream: tcp::socket, tls::stream or connection.
template <class Stream>
ex::task<void> serve_http(Stream& stream) {
std::string request;
char buf[4096];
for (;;) {
while (request.find("\r\n\r\n") == std::string::npos) {
std::size_t n = co_await net::async_receive(stream, net::buffer(buf));
if (n == 0) co_return; // close_notify: authenticated end of stream
request.append(buf, n);
if (request.size() > 64 * 1024) co_return;
}
auto head_end = request.find("\r\n\r\n") + 4;
std::string_view line(request.data(), request.find("\r\n"));
bool keep_alive = request.find("Connection: close") == std::string::npos;
std::string body = std::format("Hello over TLS from stdnet!\nYou asked: {}\n", line);
std::string head = std::format("HTTP/1.1 200 OK\r\nContent-Type: text/plain; charset=utf-8\r\n"
"Content-Length: {}\r\nConnection: {}\r\n\r\n",
body.size(), keep_alive ? "keep-alive" : "close");
std::array<net::const_buffer, 2> response{net::buffer(std::string_view(head)), net::buffer(std::string_view(body))};
co_await net::async_send(stream, response);
request.erase(0, head_end);
if (!keep_alive) co_return;
}
}
template <class Sndr>
auto log_errors(Sndr&& sndr, const char* what) {
return ex::upon_error(std::forward<Sndr>(sndr), [what](std::exception_ptr e) noexcept {
try {
std::rethrow_exception(e);
} catch (const std::exception& x) {
std::fprintf(stderr, "%s: %s\n", what, x.what());
}
});
}
// TAPS: the listener performs the handshakes; async_accept delivers authenticated connections.
ex::task<void> serve_connection(net::connection c) {
co_await serve_http(c);
c.close(); // sends close_notify
}
ex::task<void> taps_accept_loop(net::listener& l, ex::counting_scope& scope, net::io_context::scheduler_type sch) {
for (;;) {
net::connection c = co_await net::async_accept(l);
ex::spawn(ex::starts_on(sch, log_errors(serve_connection(std::move(c)), "connection")), scope.get_token());
}
}
// Socket layer: one tls::stream per accepted socket; the program runs the handshake.
ex::task<void> serve_stream(tcp::socket s, std::shared_ptr<const net::tls::engine_config> config) {
net::tls::stream<tcp::socket> tls(std::move(s), std::move(config));
co_await net::tls::async_handshake(tls, net::tls::role::server, std::chrono::seconds(10));
co_await serve_http(tls);
co_await net::tls::async_shutdown(tls);
}
ex::task<void> stream_accept_loop(tcp::acceptor& acc, std::shared_ptr<const net::tls::engine_config> config,
ex::counting_scope& scope, net::io_context::scheduler_type sch) {
for (;;) {
tcp::socket s = co_await net::async_accept(acc);
ex::spawn(ex::starts_on(sch, log_errors(serve_stream(std::move(s), config), "connection")), scope.get_token());
}
}
std::string read_file(const char* path) {
std::ifstream f(path, std::ios::binary);
std::stringstream ss;
ss << f.rdbuf();
return ss.str();
}
} // namespace
int main(int argc, char** argv) {
if (argc < 3) {
std::fprintf(stderr, "usage: %s cert.pem key.pem [port] [--stream]\n", argv[0]);
return 2;
}
net::ip::port_type port = 8443;
if (argc > 3) std::from_chars(argv[3], argv[3] + std::strlen(argv[3]), port);
const bool use_stream = argc > 4 && std::string_view(argv[4]) == "--stream";
// Credentials come from memory; reading the files is the program's business.
auto identity = net::tls::credentials::from_pem(read_file(argv[1]), read_file(argv[2]));
net::io_context ctx;
ex::counting_scope scope;
auto sch = ctx.get_scheduler();
if (use_stream) {
auto config = std::make_shared<net::tls::engine_config>();
config->identity = identity;
config->alpn = {"http/1.1"};
static tcp::acceptor acceptor(ctx, tcp::endpoint(net::ip::address_v4::any(), port));
std::printf("listening on %s (tls::stream)\n", acceptor.local_endpoint().to_string().c_str());
ex::spawn(ex::starts_on(sch, log_errors(stream_accept_loop(acceptor, config, scope, sch), "accept")), scope.get_token());
ctx.run();
} else {
net::listener l = net::listen(ctx, net::preconnection(net::local_endpoint().with_port(port),
net::transport_properties::reliable_stream(),
net::security_parameters{}.local_identity(identity).alpn({"http/1.1"})));
std::printf("listening on port %u (TAPS)\n", static_cast<unsigned>(l.local_port()));
ex::spawn(ex::starts_on(sch, log_errors(taps_accept_loop(l, scope, sch), "accept")), scope.get_token());
ctx.run();
}
}