TLA Line data Source code
1 : //
2 : // Copyright (c) 2026 Steve Gerbino
3 : //
4 : // Distributed under the Boost Software License, Version 1.0. (See accompanying
5 : // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6 : //
7 : // Official repository: https://github.com/cppalliance/corosio
8 : //
9 :
10 : #ifndef BOOST_COROSIO_NATIVE_DETAIL_POSIX_POSIX_RESOLVER_HPP
11 : #define BOOST_COROSIO_NATIVE_DETAIL_POSIX_POSIX_RESOLVER_HPP
12 :
13 : #include <boost/corosio/detail/platform.hpp>
14 :
15 : #if BOOST_COROSIO_POSIX
16 :
17 : #include <boost/corosio/detail/config.hpp>
18 : #include <boost/corosio/resolver.hpp>
19 : #include <boost/capy/ex/execution_context.hpp>
20 :
21 : #include <boost/corosio/native/detail/endpoint_convert.hpp>
22 : #include <boost/corosio/detail/intrusive.hpp>
23 : #include <boost/corosio/detail/dispatch_coro.hpp>
24 : #include <boost/corosio/detail/scheduler_op.hpp>
25 : #include <boost/corosio/detail/thread_pool.hpp>
26 : #include <boost/corosio/native/detail/coro_op.hpp>
27 :
28 : #include <boost/corosio/detail/scheduler.hpp>
29 : #include <boost/capy/ex/executor_ref.hpp>
30 : #include <coroutine>
31 : #include <boost/capy/error.hpp>
32 :
33 : #include <netdb.h>
34 : #include <netinet/in.h>
35 : #include <sys/socket.h>
36 :
37 : #include <atomic>
38 : #include <memory>
39 : #include <optional>
40 : #include <stop_token>
41 : #include <string>
42 :
43 : /*
44 : POSIX Resolver Service
45 : ======================
46 :
47 : POSIX getaddrinfo() is a blocking call that cannot be monitored with
48 : epoll/kqueue/io_uring. Blocking calls are dispatched to a shared
49 : resolver_thread_pool service which reuses threads across operations.
50 :
51 : Cancellation
52 : ------------
53 : getaddrinfo() cannot be interrupted mid-call. We use an atomic flag to
54 : indicate cancellation was requested. The worker thread checks this flag
55 : after getaddrinfo() returns and reports the appropriate error.
56 :
57 : Class Hierarchy
58 : ---------------
59 : - posix_resolver_service (execution_context service, one per context)
60 : - Owns all posix_resolver instances via a recycling object_pool
61 : - Stores scheduler* for posting completions
62 : - posix_resolver (one per resolver object)
63 : - Contains embedded resolve_op and reverse_resolve_op for reuse
64 : - Each op holds an object_ref keepalive while its pool work is
65 : in flight, preventing premature destruction
66 : - resolve_op (forward resolution state)
67 : - Uses getaddrinfo() to resolve host/service to endpoints
68 : - reverse_resolve_op (reverse resolution state)
69 : - Uses getnameinfo() to resolve endpoint to host/service
70 :
71 : Completion Flow
72 : ---------------
73 : Forward resolution:
74 : 1. resolve() sets up op_, posts work to the thread pool
75 : 2. Pool thread runs getaddrinfo() (blocking)
76 : 3. Pool thread stores results in op_.stored_results
77 : 4. Pool thread calls svc_.post(&op_) to queue completion
78 : 5. Scheduler invokes op_() which resumes the coroutine
79 :
80 : Reverse resolution follows the same pattern using getnameinfo().
81 :
82 : Single-Inflight Constraint
83 : --------------------------
84 : Each resolver has ONE embedded op_ for forward and ONE reverse_op_ for
85 : reverse resolution. Concurrent operations of the same type on the same
86 : resolver would corrupt state. Users must serialize operations per-resolver.
87 :
88 : Shutdown
89 : --------
90 : The resolver service cancels all resolvers and releases the
91 : service's own reference on each; the recycling pool frees (rather
92 : than recycles) once each resolver's in-flight pool work also
93 : releases its reference. The thread pool service shuts down
94 : separately via execution_context service ordering, joining all
95 : worker threads.
96 : */
97 :
98 : namespace boost::corosio::detail {
99 :
100 : struct scheduler;
101 :
102 : namespace posix_resolver_detail {
103 :
104 : // Convert resolve_flags to addrinfo ai_flags
105 : int flags_to_hints(resolve_flags flags);
106 :
107 : // Convert reverse_flags to getnameinfo NI_* flags
108 : int flags_to_ni_flags(reverse_flags flags);
109 :
110 : // Convert addrinfo results to endpoints
111 : std::vector<endpoint> convert_results(struct addrinfo* ai);
112 :
113 : // Convert getaddrinfo error codes to std::error_code
114 : std::error_code make_gai_error(int gai_err);
115 :
116 : } // namespace posix_resolver_detail
117 :
118 : class posix_resolver_service;
119 :
120 : /** Resolver implementation for POSIX backends.
121 :
122 : Each resolver instance contains a single embedded operation object (op_)
123 : that is reused for each resolve() call. This design avoids per-operation
124 : heap allocation but imposes a critical constraint:
125 :
126 : @par Single-Inflight Contract
127 :
128 : Only ONE resolve operation may be in progress at a time per resolver
129 : instance. Calling resolve() while a previous resolve() is still pending
130 : results in undefined behavior:
131 :
132 : - The new call overwrites op_ fields (host, service, coroutine handle)
133 : - The worker thread from the first call reads corrupted state
134 : - The wrong coroutine may be resumed, or resumed multiple times
135 : - Data races occur on non-atomic op_ members
136 :
137 : @par Safe Usage Patterns
138 :
139 : @code
140 : // CORRECT: Sequential resolves
141 : auto [ec1, r1] = co_await resolver.resolve("host1", "80");
142 : auto [ec2, r2] = co_await resolver.resolve("host2", "80");
143 :
144 : // CORRECT: Parallel resolves with separate resolver instances
145 : resolver r1(ctx), r2(ctx);
146 : auto [ec1, res1] = co_await r1.resolve("host1", "80"); // in one coroutine
147 : auto [ec2, res2] = co_await r2.resolve("host2", "80"); // in another
148 :
149 : // WRONG: Concurrent resolves on same resolver
150 : // These may run concurrently if launched in parallel - UNDEFINED BEHAVIOR
151 : auto f1 = resolver.resolve("host1", "80");
152 : auto f2 = resolver.resolve("host2", "80"); // BAD: overlaps with f1
153 : @endcode
154 :
155 : @par Thread Safety
156 : Distinct objects: Safe.
157 : Shared objects: Unsafe. See single-inflight contract above.
158 : */
159 : class posix_resolver final
160 : : public resolver::implementation
161 : , public intrusive_list<posix_resolver>::node
162 : {
163 : friend class posix_resolver_service;
164 :
165 : public:
166 : // resolve_op - operation state for a single DNS resolution
167 :
168 : struct resolve_op : coro_op
169 : {
170 : /// Where the endpoints are handed back.
171 : std::vector<endpoint>* out = nullptr;
172 :
173 : // Input parameters (owned copies for thread safety)
174 : std::string host;
175 : std::string service;
176 : resolve_flags flags = resolve_flags::none;
177 :
178 : // Result storage (populated by worker thread)
179 : std::vector<endpoint> stored_results;
180 : int gai_error = 0;
181 :
182 HIT 68 : resolve_op() = default;
183 :
184 : void reset() noexcept;
185 : void operator()() override;
186 : void destroy() override;
187 : };
188 :
189 : // reverse_resolve_op - operation state for reverse DNS resolution
190 :
191 : struct reverse_resolve_op : coro_op
192 : {
193 : /// Where the name is handed back.
194 : endpoint_name* result_out = nullptr;
195 :
196 : // Input parameters
197 : endpoint ep;
198 : reverse_flags flags = reverse_flags::none;
199 :
200 : // Result storage (populated by worker thread)
201 : std::string stored_host;
202 : std::string stored_service;
203 : int gai_error = 0;
204 :
205 68 : reverse_resolve_op() = default;
206 :
207 : void reset() noexcept;
208 : void operator()() override;
209 : void destroy() override;
210 : };
211 :
212 : /// Embedded pool work item for thread pool dispatch.
213 : struct pool_op : pool_work_item
214 : {
215 : /// Resolver that owns this work item.
216 : posix_resolver* resolver_ = nullptr;
217 :
218 : /// Prevent impl destruction while work is in flight.
219 : detail::object_ref ref_;
220 : };
221 :
222 : explicit posix_resolver(posix_resolver_service& svc) noexcept;
223 :
224 : /// Recycle into the owning service's pool. Defined out-of-line
225 : /// after posix_resolver_service for its complete type.
226 : void retire() noexcept override;
227 :
228 : /** Reset for recycling.
229 :
230 : Both ops' own `reset()` already clears `host`/`service`/
231 : `stored_host`/`stored_service` via `.clear()` (preserving their
232 : allocated capacity — the whole point of recycling), run at the
233 : top of the next `resolve()`/`reverse_resolve()`. refs_ cannot
234 : reach zero while a resolve is in flight (the pool op's
235 : `object_ref` holds a reference for the duration), so asserting
236 : `stop_cb` disengaged on both ops is a precondition check, not
237 : a defensive one.
238 :
239 : @pre refs_ == 0, no resolve in flight.
240 : */
241 64 : void reuse() noexcept
242 : {
243 64 : BOOST_COROSIO_ASSERT(!op_.stop_cb);
244 64 : BOOST_COROSIO_ASSERT(!reverse_op_.stop_cb);
245 64 : }
246 :
247 : std::coroutine_handle<> resolve(
248 : std::coroutine_handle<>,
249 : capy::executor_ref,
250 : std::string_view host,
251 : std::string_view service,
252 : resolve_flags flags,
253 : std::stop_token,
254 : std::error_code*,
255 : std::vector<endpoint>*) override;
256 :
257 : std::coroutine_handle<> reverse_resolve(
258 : std::coroutine_handle<>,
259 : capy::executor_ref,
260 : endpoint const& ep,
261 : reverse_flags flags,
262 : std::stop_token,
263 : std::error_code*,
264 : endpoint_name*) override;
265 :
266 : void cancel() noexcept override;
267 :
268 : resolve_op op_;
269 : reverse_resolve_op reverse_op_;
270 :
271 : /// Pool work item for forward resolution.
272 : pool_op resolve_pool_op_;
273 :
274 : /// Pool work item for reverse resolution.
275 : pool_op reverse_pool_op_;
276 :
277 : /// Execute blocking `getaddrinfo()` on a pool thread.
278 : static void do_resolve_work(pool_work_item*) noexcept;
279 :
280 : /// Execute blocking `getnameinfo()` on a pool thread.
281 : static void do_reverse_resolve_work(pool_work_item*) noexcept;
282 :
283 : private:
284 : posix_resolver_service& svc_;
285 : };
286 :
287 : } // namespace boost::corosio::detail
288 :
289 : #endif // BOOST_COROSIO_POSIX
290 :
291 : #endif // BOOST_COROSIO_NATIVE_DETAIL_POSIX_POSIX_RESOLVER_HPP
|