载入中...
搜索中...
未找到
HttpRequest.cpp
浏览该文件的文档.
1// eve-hot-path: HTTP completion polling; network I/O runs in owned jobs.
3#include "data/ByteData.h"
4#include "network/Network.h"
6
7#include <Poco/Exception.h>
8#include <Poco/File.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>
19#include <Poco/URI.h>
20#include <openssl/ssl.h>
21#include <algorithm>
22#include <chrono>
23#include <cstdlib>
24#include <sstream>
25
26namespace eve::network {
27
28// Only the owning thread restores a live event handle after checking this
29// cancellation cookie. Background jobs do not retain request pointers.
30struct HttpOrigin {
31 explicit HttpOrigin(std::uintptr_t value) : address(value) {}
32 const std::uintptr_t address;
33 bool active = true; // Protected by HttpRuntime::mu_.
34};
35
36namespace {
37
38Poco::Net::Context::Ptr tlsContext(const HttpPolicy& policy) {
39 try {
40 using Context = Poco::Net::Context;
41 Context::Ptr 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");
48 if (!policy.verifySsl) return context;
49 if (!policy.caLocation.empty()) {
50 if (policy.caLocation.find('\0') != std::string::npos)
51 throw Poco::Net::SSLContextException("Invalid CA location");
52 const bool directory = Poco::File(policy.caLocation).isDirectory();
53 if (SSL_CTX_load_verify_locations(ssl, directory ? nullptr : policy.caLocation.c_str(),
54 directory ? policy.caLocation.c_str() : nullptr) != 1)
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");
59 } else {
60#ifdef _WIN32
61 if (SSL_CTX_load_verify_store(ssl, "org.openssl.winstore:") != 1)
62 throw Poco::Net::SSLContextException("Cannot load Windows certificate roots");
63#else
64 // The bundled OpenSSL prefix does not supply a root bundle.
65 bool loaded = false;
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");
71 loaded = true;
72 break;
73 }
74 }
75 if (!loaded && SSL_CTX_set_default_verify_paths(ssl) != 1)
76 throw Poco::Net::SSLContextException("Cannot load default certificate roots");
77#endif
78 }
79 return context;
80 } catch (const Poco::Net::SSLException&) {
81 throw;
82 } catch (const Poco::Exception& ex) {
83 throw Poco::Net::SSLContextException("Cannot initialize HTTPS trust", ex.displayText());
84 }
85}
86
87HttpResult performHttp(const HttpOptions& options) {
88 HttpResult result;
89 auto& c = result.completion;
90 c.kind = NetKind::Http;
91 c.type = NetEvType::Err;
92 try {
93 Poco::URI uri(options.url);
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(),
99 tlsContext(options.policy));
100 else
101 session = std::make_unique<Poco::Net::HTTPClientSession>(uri.getHost(), uri.getPort());
102 session->setTimeout(
103 Poco::Timespan(static_cast<Poco::Timespan::TimeDiff>((std::max)(1, options.policy.timeoutMs)) * 1000));
104 std::string path = uri.getPathAndQuery();
105 if (path.empty()) path = "/";
106 Poco::Net::HTTPRequest request(options.method, path, Poco::Net::HTTPMessage::HTTP_1_1);
107 request.setHost(uri.getHost(), uri.getPort());
108 for (const auto& [key, value] : options.headers) request.set(key, value);
109 if (options.body) request.setContentLength(static_cast<std::streamsize>(options.body->size()));
110 auto& output = session->sendRequest(request);
111 if (options.body && !options.body->empty()) {
112 output.write(options.body->data(), static_cast<std::streamsize>(options.body->size()));
113 if (!output) throw Poco::IOException("Cannot send HTTP body");
114 result.sentBytes = options.body->size();
115 }
116 Poco::Net::HTTPResponse response;
117 auto& input = session->receiveResponse(response);
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 &&
124 !response.getChunkedTransferEncoding() && response.hasContentLength() &&
125 copied != response.getContentLength64())
126 throw Poco::IOException("Truncated HTTP response body");
127 const auto bytes = body.str();
128 c.type = NetEvType::HttpResp;
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&) {
132 c.reason = "tls";
133 } catch (const Poco::TimeoutException&) {
134 c.reason = "timeout";
135 } catch (const Poco::Net::DNSException&) {
136 c.reason = "dns";
137 } catch (...) {
138 c.reason = "refused";
139 }
140 return result;
141}
142
143} // namespace
144
147 std::lock_guard lock(mu_);
148 return policy_;
149}
151 std::lock_guard lock(mu_);
152 policy_.timeoutMs = ms;
153}
155 std::lock_guard lock(mu_);
156 return policy_.timeoutMs;
157}
158void HttpRuntime::setVerifySsl(bool verify) {
159 std::lock_guard lock(mu_);
160 policy_.verifySsl = verify;
161}
163 std::lock_guard lock(mu_);
164 return policy_.verifySsl;
165}
166void HttpRuntime::setCaLocation(std::string location) {
167 std::lock_guard lock(mu_);
168 policy_.caLocation = std::move(location);
169}
171 std::lock_guard lock(mu_);
172 return closed_;
173}
174
176 std::lock_guard lock(mu_);
177 if (closed_) return SubmitStatus::Closed;
178 try {
179 jobs_.reserve(jobs_.size() + 1);
180 const auto address = reinterpret_cast<std::uintptr_t>(origin);
181 auto& lifetime = origins_[address];
182 if (!lifetime) lifetime = std::make_shared<HttpOrigin>(address);
183 auto job = std::async(std::launch::async, [snapshot = std::move(options)] { return performHttp(snapshot); });
184 jobs_.push_back({lifetime, std::move(job)});
186 } catch (...) {
188 }
189}
190
192 std::lock_guard lock(mu_);
193 if (closed_) return PollStatus::Closed;
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;
199 result.completion.handle = origin;
200 jobs_.erase(job);
201 return PollStatus::Ready;
202 }
203 }
204 return PollStatus::Pending;
205}
206
207void HttpRuntime::drain(std::vector<HttpResult>& out) {
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) {
211 ++job;
212 continue;
213 }
214 auto result = job->future.get();
215 if (job->lifetime->active && !closed_) {
216 result.origin_ = job->lifetime;
217 out.push_back(std::move(result));
218 }
219 job = jobs_.erase(job);
220 }
221}
222
224 std::lock_guard lock(mu_);
225 if (closed_ || !result.origin_ || !result.origin_->active) return DeliveryStatus::Retired;
226 result.completion.handle = reinterpret_cast<void*>(result.origin_->address);
228}
229
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;
235 origins_.erase(it);
236 }
237}
238
240 std::vector<Job> pending;
241 {
242 std::lock_guard lock(mu_);
243 closed_ = true;
244 for (auto& [origin, lifetime] : origins_) {
245 (void)origin;
246 lifetime->active = false;
247 }
248 origins_.clear();
249 pending.swap(jobs_);
250 }
251 // Future destruction joins outside the lock. Each job owns its SSL session.
252}
253
254HttpRequest::HttpRequest(Network* net, std::string method, std::string url)
255 : net_(net),
256 runtime_(net ? net->http_ : std::weak_ptr<HttpRuntime>{}),
257 method_(std::move(method)),
258 url_(std::move(url)) {}
260 if (auto runtime = runtime_.lock()) runtime->cancel(this);
261}
263 : net_(other.net_),
264 runtime_(other.runtime_),
265 method_(other.method_),
266 url_(other.url_),
267 headers_(other.headers_),
268 body_(other.body_),
269 timeoutMs_(other.timeoutMs_),
270 verifySsl_(other.verifySsl_),
271 caLocation_(other.caLocation_) {}
272
274 if (this == &other) return *this;
275 if (auto runtime = runtime_.lock()) runtime->cancel(this);
276 net_ = other.net_;
277 runtime_ = other.runtime_;
278 method_ = other.method_;
279 url_ = other.url_;
280 headers_ = other.headers_;
281 body_ = other.body_;
282 timeoutMs_ = other.timeoutMs_;
283 verifySsl_ = other.verifySsl_;
284 caLocation_ = other.caLocation_;
285 return *this;
286}
287
289 const auto runtime = runtime_.lock();
290 return runtime && !runtime->isClosed() ? net_ : nullptr;
291}
292void HttpRequest::setHeader(std::string key, std::string value) { headers_[std::move(key)] = std::move(value); }
294 if (!data || data->getSize() == 0) {
295 body_.reset();
296 return;
297 }
298 const auto* begin = static_cast<const char*>(data->getData());
299 body_ = std::make_shared<std::vector<char>>(begin, begin + data->getSize());
300}
302 body_ = std::make_shared<std::vector<char>>(body.begin(), body.end());
303}
304void HttpRequest::setTimeout(int ms) { timeoutMs_ = ms; }
305void HttpRequest::setVerifySsl(bool verify) { verifySsl_ = verify ? 1 : 0; }
306void HttpRequest::setCaLocation(std::string location) { caLocation_ = std::move(location); }
307
309 const auto runtime = runtime_.lock();
310 if (!runtime) return false;
311 HttpOptions options{method_, url_, headers_, body_, runtime->policy()};
312 if (timeoutMs_ >= 0) options.policy.timeoutMs = timeoutMs_;
313 if (verifySsl_ >= 0) options.policy.verifySsl = verifySsl_ != 0;
314 if (caLocation_) options.policy.caLocation = *caLocation_;
315 return runtime->submit(this, std::move(options)) == HttpRuntime::SubmitStatus::Accepted;
316}
317
318} // namespace eve::network
std::string output
std::filesystem::path directory
std::vector< QuestEvent > pending
SQObjectPtr key
Definition ECS.cpp:155
std::uint16_t method
EvpackChunkInput input
Definition Evpack.cpp:170
const GltfImportRequest & request
std::int32_t c
std::weak_ptr< const void > lifetime
std::string response
Poco::JSON::Object::Ptr result
Snapshot snapshot
std::uint64_t bytes
glm::dvec3 origin
std::string path
Definition PlayHost.cpp:111
std::unordered_set< std::string > loaded
Definition Plugins.cpp:24
std::string uri
std::string file
std::string body
Object::Ptr value
ScriptStructure out
size_t begin
const SquirrelValueOptions & options
std::optional< InteractionSession > session
Definition Tactics.cpp:39
const VegetationPresetContext & context
In-memory byte buffer implementing eve::Data (ref-counted).
Definition ByteData.h:13
Asynchronous HTTP request (Poco-based). Configure headers/body, call submit(), then receive the respo...
Definition HttpRequest.h:33
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....
Definition Network.h:39
HttpOrigin(std::uintptr_t value)
const std::uintptr_t address