7#include <Poco/Exception.h>
9#include <Poco/Net/Context.h>
10#include <Poco/Net/HTTPClientSession.h>
11#include <Poco/Net/HTTPRequest.h>
12#include <Poco/Net/HTTPResponse.h>
13#include <Poco/Net/HTTPSClientSession.h>
14#include <Poco/Net/NetException.h>
15#include <Poco/Net/RejectCertificateHandler.h>
16#include <Poco/Net/SSLException.h>
17#include <Poco/StreamCopier.h>
18#include <Poco/Timespan.h>
20#include <openssl/ssl.h>
38Poco::Net::Context::Ptr tlsContext(
const HttpPolicy& policy) {
40 using Context = Poco::Net::Context;
42 new Context(Context::CLIENT_USE,
"",
"",
"",
43 policy.
verifySsl ? Context::VERIFY_STRICT : Context::VERIFY_NONE, 9,
false,
"DEFAULT");
44 context->setInvalidCertificateHandler(
new Poco::Net::RejectCertificateHandler(
false));
45 auto* ssl =
context->sslContext();
46 if (SSL_CTX_set_min_proto_version(ssl, TLS1_2_VERSION) != 1)
47 throw Poco::Net::SSLContextException(
"Cannot require TLS 1.2");
50 if (policy.
caLocation.find(
'\0') != std::string::npos)
51 throw Poco::Net::SSLContextException(
"Invalid CA location");
55 throw Poco::Net::SSLContextException(
"Cannot load custom CA location");
56 }
else if (std::getenv(
"SSL_CERT_FILE") || std::getenv(
"SSL_CERT_DIR")) {
57 if (SSL_CTX_set_default_verify_paths(ssl) != 1)
58 throw Poco::Net::SSLContextException(
"Cannot load environment CA locations");
61 if (SSL_CTX_load_verify_store(ssl,
"org.openssl.winstore:") != 1)
62 throw Poco::Net::SSLContextException(
"Cannot load Windows certificate roots");
66 for (
const char*
file :
67 {
"/etc/ssl/certs/ca-certificates.crt",
"/etc/pki/tls/certs/ca-bundle.crt",
"/etc/ssl/cert.pem"}) {
68 if (Poco::File(
file).exists()) {
69 if (SSL_CTX_load_verify_locations(ssl,
file,
nullptr) != 1)
70 throw Poco::Net::SSLContextException(
"Cannot load system certificate roots");
75 if (!
loaded && SSL_CTX_set_default_verify_paths(ssl) != 1)
76 throw Poco::Net::SSLContextException(
"Cannot load default certificate roots");
80 }
catch (
const Poco::Net::SSLException&) {
82 }
catch (
const Poco::Exception& ex) {
83 throw Poco::Net::SSLContextException(
"Cannot initialize HTTPS trust", ex.displayText());
87HttpResult performHttp(
const HttpOptions&
options) {
94 if ((
uri.getScheme() !=
"http" &&
uri.getScheme() !=
"https") ||
uri.getHost().empty())
95 throw Poco::InvalidArgumentException(
"Expected an absolute HTTP(S) URL");
96 std::unique_ptr<Poco::Net::HTTPClientSession>
session;
97 if (
uri.getScheme() ==
"https")
98 session = std::make_unique<Poco::Net::HTTPSClientSession>(
uri.getHost(),
uri.getPort(),
101 session = std::make_unique<Poco::Net::HTTPClientSession>(
uri.getHost(),
uri.getPort());
103 Poco::Timespan(
static_cast<Poco::Timespan::TimeDiff
>((std::max)(1,
options.policy.timeoutMs)) * 1000));
104 std::string
path =
uri.getPathAndQuery();
106 Poco::Net::HTTPRequest
request(
options.method,
path, Poco::Net::HTTPMessage::HTTP_1_1);
113 if (!
output)
throw Poco::IOException(
"Cannot send HTTP body");
118 std::ostringstream
body;
119 const auto copied = Poco::StreamCopier::copyStream(
input,
body);
120 if (
input.bad() || !
body)
throw Poco::IOException(
"Cannot read HTTP response body");
121 if (
options.method != Poco::Net::HTTPRequest::HTTP_HEAD &&
122 response.getStatus() != Poco::Net::HTTPResponse::HTTP_NO_CONTENT &&
123 response.getStatus() != Poco::Net::HTTPResponse::HTTP_NOT_MODIFIED &&
125 copied !=
response.getContentLength64())
126 throw Poco::IOException(
"Truncated HTTP response body");
129 c.status =
static_cast<int>(
response.getStatus());
130 c.bytes = std::make_shared<std::vector<char>>(
bytes.begin(),
bytes.end());
131 }
catch (
const Poco::Net::SSLException&) {
133 }
catch (
const Poco::TimeoutException&) {
134 c.reason =
"timeout";
135 }
catch (
const Poco::Net::DNSException&) {
138 c.reason =
"refused";
147 std::lock_guard lock(mu_);
151 std::lock_guard lock(mu_);
155 std::lock_guard lock(mu_);
159 std::lock_guard lock(mu_);
163 std::lock_guard lock(mu_);
167 std::lock_guard lock(mu_);
171 std::lock_guard lock(mu_);
176 std::lock_guard lock(mu_);
179 jobs_.reserve(jobs_.size() + 1);
180 const auto address =
reinterpret_cast<std::uintptr_t
>(
origin);
184 jobs_.push_back({
lifetime, std::move(job)});
192 std::lock_guard lock(mu_);
194 for (
auto job = jobs_.begin(); job != jobs_.end(); ++job) {
195 if (job->lifetime->address ==
reinterpret_cast<std::uintptr_t
>(
origin) && job->lifetime->active &&
196 job->future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) {
197 result = job->future.get();
198 result.origin_ = job->lifetime;
208 std::lock_guard lock(mu_);
209 for (
auto job = jobs_.begin(); job != jobs_.end();) {
210 if (job->future.wait_for(std::chrono::seconds(0)) != std::future_status::ready) {
214 auto result = job->future.get();
215 if (job->lifetime->active && !closed_) {
216 result.origin_ = job->lifetime;
219 job = jobs_.erase(job);
224 std::lock_guard lock(mu_);
226 result.completion.handle =
reinterpret_cast<void*
>(
result.origin_->address);
231 std::lock_guard lock(mu_);
232 auto it = origins_.find(
reinterpret_cast<std::uintptr_t
>(
origin));
233 if (it != origins_.end()) {
234 it->second->active =
false;
242 std::lock_guard lock(mu_);
257 method_(std::move(
method)),
258 url_(std::move(url)) {}
260 if (
auto runtime = runtime_.lock()) runtime->cancel(
this);
264 runtime_(other.runtime_),
265 method_(other.method_),
267 headers_(other.headers_),
269 timeoutMs_(other.timeoutMs_),
270 verifySsl_(other.verifySsl_),
271 caLocation_(other.caLocation_) {}
274 if (
this == &other)
return *
this;
275 if (
auto runtime = runtime_.lock()) runtime->cancel(
this);
277 runtime_ = other.runtime_;
278 method_ = other.method_;
280 headers_ = other.headers_;
282 timeoutMs_ = other.timeoutMs_;
283 verifySsl_ = other.verifySsl_;
284 caLocation_ = other.caLocation_;
289 const auto runtime = runtime_.lock();
290 return runtime && !runtime->isClosed() ? net_ :
nullptr;
294 if (!data || data->getSize() == 0) {
298 const auto*
begin =
static_cast<const char*
>(data->getData());
299 body_ = std::make_shared<std::vector<char>>(
begin,
begin + data->getSize());
302 body_ = std::make_shared<std::vector<char>>(
body.begin(),
body.end());
309 const auto runtime = runtime_.lock();
310 if (!runtime)
return false;
312 if (timeoutMs_ >= 0)
options.policy.timeoutMs = timeoutMs_;
313 if (verifySsl_ >= 0)
options.policy.verifySsl = verifySsl_ != 0;
314 if (caLocation_)
options.policy.caLocation = *caLocation_;
std::filesystem::path directory
std::vector< QuestEvent > pending
const GltfImportRequest & request
std::weak_ptr< const void > lifetime
std::unordered_set< std::string > loaded
const SquirrelValueOptions & options
std::optional< InteractionSession > session
const VegetationPresetContext & context
In-memory byte buffer implementing eve::Data (ref-counted).
Asynchronous HTTP request (Poco-based). Configure headers/body, call submit(), then receive the respo...
void setBodyString(std::string s)
Sets the request body as a string.
void setTimeout(int ms)
Overrides the module default timeout for this request (ms).
Network * network() const
Returns the live module, or null after module destruction. @ownership Borrowed; the Network owner ret...
HttpRequest(Network *net, std::string method, std::string url)
Creates a request; method is e.g. "GET"/"POST", url is absolute.
~HttpRequest()
Drops undelivered results; in-flight I/O finishes under its timeout.
void setCaLocation(std::string location)
Overrides the CA file or hashed CA directory with an owning UTF-8 path. Empty selects system/default ...
void setBody(eve::data::ByteData *data)
Sets the request body bytes.
HttpRequest & operator=(const HttpRequest &other)
Cancels this handle's jobs before copying the other configuration.
void setHeader(std::string k, std::string v)
Sets one request header.
bool submit()
Queues an immutable request snapshot; true reports acceptance only. @cost Starts a thread and perform...
void setVerifySsl(bool verify)
Overrides TLS verification for this request.
bool getVerifySsl() const
Returns default certificate verification.
void close()
Cancels all origins, then joins jobs without holding the registry lock. @cost Waits for in-flight I/O...
void setVerifySsl(bool verify)
Changes default certificate verification for subsequent jobs.
HttpPolicy policy() const
Copies the authoritative policy for one submission.
int timeout() const
Returns the default I/O timeout.
~HttpRuntime()
Joins remaining jobs after canceling undelivered results.
void cancel(void *origin)
Retires all jobs for the borrowed origin without blocking its destructor. @ownership Origin is identi...
void drain(std::vector< HttpResult > &out)
Transfers ready, still-live results without invoking callbacks. @cost Scans pending requests once per...
SubmitStatus submit(void *origin, HttpOptions options)
Starts an owning snapshot without retaining the handle. @ownership Origin is borrowed identity,...
void setTimeout(int ms)
Changes the default I/O timeout.
void setCaLocation(std::string location)
Owns a custom CA path for subsequent jobs.
PollStatus take(void *origin, HttpResult &result)
Takes only this origin's next ready result. @ownership Origin is a borrowed identity; result transfer...
DeliveryStatus prepareDelivery(HttpResult &result)
Rechecks lifetime immediately before queuing an event, after any reentrant callbacks.
bool isClosed() const
Reports whether the owning module has shut down.
Network module: TCP/UDP/HTTP factories, background worker, and completion event plumbing....
HttpOrigin(std::uintptr_t value)
const std::uintptr_t address