Debian Codegraph @

src/core/lib/http/httpcli.cc

raw
1 /*
2 *
3 * Copyright 2015 gRPC authors.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19 #include <grpc/support/port_platform.h>
20
21 #include "src/core/lib/http/httpcli.h"
22
23 #include <limits.h>
24
25 #include <string>
26 #include <utility>
27
28 #include "absl/functional/bind_front.h"
29 #include "absl/status/status.h"
30 #include "absl/strings/str_format.h"
31
32 #include <grpc/grpc.h>
33 #include <grpc/grpc_security.h>
34 #include <grpc/slice_buffer.h>
35 #include <grpc/support/alloc.h>
36 #include <grpc/support/log.h>
37
38 #include "src/core/lib/address_utils/sockaddr_utils.h"
39 #include "src/core/lib/channel/channel_args.h"
40 #include "src/core/lib/channel/channel_args_preconditioning.h"
41 #include "src/core/lib/config/core_configuration.h"
42 #include "src/core/lib/gprpp/status_helper.h"
43 #include "src/core/lib/http/format_request.h"
44 #include "src/core/lib/http/parser.h"
45 #include "src/core/lib/iomgr/endpoint.h"
46 #include "src/core/lib/iomgr/iomgr_internal.h"
47 #include "src/core/lib/iomgr/pollset_set.h"
48 #include "src/core/lib/iomgr/resolve_address.h"
49 #include "src/core/lib/resource_quota/api.h"
50 #include "src/core/lib/security/credentials/credentials.h"
51 #include "src/core/lib/security/security_connector/security_connector.h"
52 #include "src/core/lib/slice/slice.h"
53 #include "src/core/lib/transport/error_utils.h"
54 #include "src/core/lib/transport/handshaker_registry.h"
55 #include "src/core/lib/transport/tcp_connect_handshaker.h"
56
57 namespace grpc_core {
58
59 namespace {
60
61 grpc_httpcli_get_override g_get_override;
62 grpc_httpcli_post_override g_post_override;
63 grpc_httpcli_put_override g_put_override;
64 void (*g_test_only_on_handshake_done_intercept)(HttpRequest* req);
65
66 } // namespace
67
68 OrphanablePtr<HttpRequest> HttpRequest::Get(
69 URI uri, const grpc_channel_args* channel_args,
70 grpc_polling_entity* pollent, const grpc_http_request* request,
71 Timestamp deadline, grpc_closure* on_done, grpc_http_response* response,
72 RefCountedPtr<grpc_channel_credentials> channel_creds) {
73 absl::optional<std::function<void()>> test_only_generate_response;
74 if (g_get_override != nullptr) {
75 test_only_generate_response = [request, uri, deadline, on_done,
76 response]() {
77 // Note that capturing request here assumes it will remain alive
78 // until after Start is called. This avoids making a copy as this
79 // code path is only used for test mocks.
80 g_get_override(request, uri.authority().c_str(), uri.path().c_str(),
81 deadline, on_done, response);
82 };
83 }
84 std::string name =
85 absl::StrFormat("HTTP:GET:%s:%s", uri.authority(), uri.path());
86 const grpc_slice request_text = grpc_httpcli_format_get_request(
87 request, uri.authority().c_str(), uri.path().c_str());
88 return MakeOrphanable<HttpRequest>(
89 std::move(uri), request_text, response, deadline, channel_args, on_done,
90 pollent, name.c_str(), std::move(test_only_generate_response),
91 std::move(channel_creds));
92 }
93
94 OrphanablePtr<HttpRequest> HttpRequest::Post(
95 URI uri, const grpc_channel_args* channel_args,
96 grpc_polling_entity* pollent, const grpc_http_request* request,
97 Timestamp deadline, grpc_closure* on_done, grpc_http_response* response,
98 RefCountedPtr<grpc_channel_credentials> channel_creds) {
99 absl::optional<std::function<void()>> test_only_generate_response;
100 if (g_post_override != nullptr) {
101 test_only_generate_response = [request, uri, deadline, on_done,
102 response]() {
103 g_post_override(request, uri.authority().c_str(), uri.path().c_str(),
104 request->body, request->body_length, deadline, on_done,
105 response);
106 };
107 }
108 std::string name =
109 absl::StrFormat("HTTP:POST:%s:%s", uri.authority(), uri.path());
110 const grpc_slice request_text = grpc_httpcli_format_post_request(
111 request, uri.authority().c_str(), uri.path().c_str());
112 return MakeOrphanable<HttpRequest>(
113 std::move(uri), request_text, response, deadline, channel_args, on_done,
114 pollent, name.c_str(), std::move(test_only_generate_response),
115 std::move(channel_creds));
116 }
117
118 OrphanablePtr<HttpRequest> HttpRequest::Put(
119 URI uri, const grpc_channel_args* channel_args,
120 grpc_polling_entity* pollent, const grpc_http_request* request,
121 Timestamp deadline, grpc_closure* on_done, grpc_http_response* response,
122 RefCountedPtr<grpc_channel_credentials> channel_creds) {
123 absl::optional<std::function<void()>> test_only_generate_response;
124 if (g_put_override != nullptr) {
125 test_only_generate_response = [request, uri, deadline, on_done,
126 response]() {
127 g_put_override(request, uri.authority().c_str(), uri.path().c_str(),
128 request->body, request->body_length, deadline, on_done,
129 response);
130 };
131 }
132 std::string name =
133 absl::StrFormat("HTTP:PUT:%s:%s", uri.authority(), uri.path());
134 const grpc_slice request_text = grpc_httpcli_format_put_request(
135 request, uri.authority().c_str(), uri.path().c_str());
136 return MakeOrphanable<HttpRequest>(
137 std::move(uri), request_text, response, deadline, channel_args, on_done,
138 pollent, name.c_str(), std::move(test_only_generate_response),
139 std::move(channel_creds));
140 }
141
142 void HttpRequest::SetOverride(grpc_httpcli_get_override get,
143 grpc_httpcli_post_override post,
144 grpc_httpcli_put_override put) {
145 g_get_override = get;
146 g_post_override = post;
147 g_put_override = put;
148 }
149
150 void HttpRequest::TestOnlySetOnHandshakeDoneIntercept(
151 void (*intercept)(HttpRequest* req)) {
152 g_test_only_on_handshake_done_intercept = intercept;
153 }
154
155 HttpRequest::HttpRequest(
156 URI uri, const grpc_slice& request_text, grpc_http_response* response,
157 Timestamp deadline, const grpc_channel_args* channel_args,
158 grpc_closure* on_done, grpc_polling_entity* pollent, const char* name,
159 absl::optional<std::function<void()>> test_only_generate_response,
160 RefCountedPtr<grpc_channel_credentials> channel_creds)
161 : uri_(std::move(uri)),
162 request_text_(request_text),
163 deadline_(deadline),
164 channel_args_(CoreConfiguration::Get()
165 .channel_args_preconditioning()
166 .PreconditionChannelArgs(channel_args)
167 .ToC()
168 .release()),
169 channel_creds_(std::move(channel_creds)),
170 on_done_(on_done),
171 resource_quota_(ResourceQuotaFromChannelArgs(channel_args_)),
172 pollent_(pollent),
173 pollset_set_(grpc_pollset_set_create()),
174 test_only_generate_response_(std::move(test_only_generate_response)),
175 resolver_(GetDNSResolver()) {
176 grpc_http_parser_init(&parser_, GRPC_HTTP_RESPONSE, response);
177 grpc_slice_buffer_init(&incoming_);
178 grpc_slice_buffer_init(&outgoing_);
179 grpc_iomgr_register_object(&iomgr_obj_, name);
180 GRPC_CLOSURE_INIT(&on_read_, OnRead, this, grpc_schedule_on_exec_ctx);
181 GRPC_CLOSURE_INIT(&continue_on_read_after_schedule_on_exec_ctx_,
182 ContinueOnReadAfterScheduleOnExecCtx, this,
183 grpc_schedule_on_exec_ctx);
184 GRPC_CLOSURE_INIT(&done_write_, DoneWrite, this, grpc_schedule_on_exec_ctx);
185 GRPC_CLOSURE_INIT(&continue_done_write_after_schedule_on_exec_ctx_,
186 ContinueDoneWriteAfterScheduleOnExecCtx, this,
187 grpc_schedule_on_exec_ctx);
188 GPR_ASSERT(pollent);
189 grpc_polling_entity_add_to_pollset_set(pollent, pollset_set_);
190 }
191
192 HttpRequest::~HttpRequest() {
193 grpc_channel_args_destroy(channel_args_);
194 grpc_http_parser_destroy(&parser_);
195 if (own_endpoint_ && ep_ != nullptr) {
196 grpc_endpoint_destroy(ep_);
197 }
198 CSliceUnref(request_text_);
199 grpc_iomgr_unregister_object(&iomgr_obj_);
200 grpc_slice_buffer_destroy(&incoming_);
201 grpc_slice_buffer_destroy(&outgoing_);
202 grpc_pollset_set_destroy(pollset_set_);
203 }
204
205 void HttpRequest::Start() {
206 MutexLock lock(&mu_);
207 if (test_only_generate_response_.has_value()) {
208 test_only_generate_response_.value()();
209 return;
210 }
211 Ref().release(); // ref held by pending DNS resolution
212 dns_request_handle_ = resolver_->LookupHostname(
213 absl::bind_front(&HttpRequest::OnResolved, this), uri_.authority(),
214 uri_.scheme(), kDefaultDNSRequestTimeout, pollset_set_,
215 /*name_server=*/"");
216 }
217
218 void HttpRequest::Orphan() {
219 {
220 MutexLock lock(&mu_);
221 GPR_ASSERT(!cancelled_);
222 cancelled_ = true;
223 // cancel potentially pending DNS resolution.
224 if (dns_request_handle_.has_value() &&
225 resolver_->Cancel(dns_request_handle_.value())) {
226 Finish(GRPC_ERROR_CREATE("cancelled during DNS resolution"));
227 Unref();
228 }
229 if (handshake_mgr_ != nullptr) {
230 // Shutdown will cancel any ongoing tcp connect.
231 handshake_mgr_->Shutdown(
232 GRPC_ERROR_CREATE("HTTP request cancelled during handshake"));
233 }
234 if (own_endpoint_ && ep_ != nullptr) {
235 grpc_endpoint_shutdown(ep_, GRPC_ERROR_CREATE("HTTP request cancelled"));
236 }
237 }
238 Unref();
239 }
240
241 void HttpRequest::AppendError(grpc_error_handle error) {
242 if (overall_error_.ok()) {
243 overall_error_ = GRPC_ERROR_CREATE("Failed HTTP/1 client request");
244 }
245 const grpc_resolved_address* addr = &addresses_[next_address_ - 1];
246 auto addr_text = grpc_sockaddr_to_uri(addr);
247 overall_error_ = grpc_error_add_child(
248 overall_error_,
249 grpc_error_set_str(
250 error, StatusStrProperty::kTargetAddress,
251 addr_text.ok() ? addr_text.value() : addr_text.status().ToString()));
252 }
253
254 void HttpRequest::OnReadInternal(grpc_error_handle error) {
255 for (size_t i = 0; i < incoming_.count; i++) {
256 if (GRPC_SLICE_LENGTH(incoming_.slices[i])) {
257 have_read_byte_ = 1;
258 grpc_error_handle err =
259 grpc_http_parser_parse(&parser_, incoming_.slices[i], nullptr);
260 if (!err.ok()) {
261 Finish(err);
262 return;
263 }
264 }
265 }
266 if (cancelled_) {
267 Finish(GRPC_ERROR_CREATE_REFERENCING("HTTP1 request cancelled during read",
268 &overall_error_, 1));
269 } else if (error.ok()) {
270 DoRead();
271 } else if (!have_read_byte_) {
272 NextAddress(error);
273 } else {
274 Finish(grpc_http_parser_eof(&parser_));
275 }
276 }
277
278 void HttpRequest::ContinueDoneWriteAfterScheduleOnExecCtx(
279 void* arg, grpc_error_handle error) {
280 RefCountedPtr<HttpRequest> req(static_cast<HttpRequest*>(arg));
281 MutexLock lock(&req->mu_);
282 if (error.ok() && !req->cancelled_) {
283 req->OnWritten();
284 } else {
285 req->NextAddress(error);
286 }
287 }
288
289 void HttpRequest::StartWrite() {
290 CSliceRef(request_text_);
291 grpc_slice_buffer_add(&outgoing_, request_text_);
292 Ref().release(); // ref held by pending write
293 grpc_endpoint_write(ep_, &outgoing_, &done_write_, nullptr,
294 /*max_frame_size=*/INT_MAX);
295 }
296
297 void HttpRequest::OnHandshakeDone(void* arg, grpc_error_handle error) {
298 auto* args = static_cast<HandshakerArgs*>(arg);
299 RefCountedPtr<HttpRequest> req(static_cast<HttpRequest*>(args->user_data));
300 if (g_test_only_on_handshake_done_intercept != nullptr) {
301 // Run this testing intercept before the lock so that it has a chance to
302 // do things like calling Orphan on the request
303 g_test_only_on_handshake_done_intercept(req.get());
304 }
305 MutexLock lock(&req->mu_);
306 req->own_endpoint_ = true;
307 if (!error.ok()) {
308 req->handshake_mgr_.reset();
309 req->NextAddress(error);
310 return;
311 }
312 // Handshake completed, so we own fields in args
313 grpc_slice_buffer_destroy(args->read_buffer);
314 gpr_free(args->read_buffer);
315 req->ep_ = args->endpoint;
316 req->handshake_mgr_.reset();
317 if (req->cancelled_) {
318 req->NextAddress(
319 GRPC_ERROR_CREATE("HTTP request cancelled during handshake"));
320 return;
321 }
322 req->StartWrite();
323 }
324
325 void HttpRequest::DoHandshake(const grpc_resolved_address* addr) {
326 // Create the security connector using the credentials and target name.
327 ChannelArgs args = ChannelArgs::FromC(channel_args_);
328 RefCountedPtr<grpc_channel_security_connector> sc =
329 channel_creds_->create_security_connector(
330 nullptr /*call_creds*/, uri_.authority().c_str(), &args);
331 if (sc == nullptr) {
332 Finish(GRPC_ERROR_CREATE_REFERENCING("failed to create security connector",
333 &overall_error_, 1));
334 return;
335 }
336 absl::StatusOr<std::string> address = grpc_sockaddr_to_uri(addr);
337 if (!address.ok()) {
338 Finish(GRPC_ERROR_CREATE_REFERENCING("Failed to extract URI from address",
339 &overall_error_, 1));
340 return;
341 }
342 args = args.SetObject(std::move(sc))
343 .Set(GRPC_ARG_TCP_HANDSHAKER_RESOLVED_ADDRESS, address.value());
344 // Start the handshake
345 handshake_mgr_ = MakeRefCounted<HandshakeManager>();
346 CoreConfiguration::Get().handshaker_registry().AddHandshakers(
347 HANDSHAKER_CLIENT, args, pollset_set_, handshake_mgr_.get());
348 Ref().release(); // ref held by pending handshake
349 grpc_endpoint* ep = ep_;
350 ep_ = nullptr;
351 own_endpoint_ = false;
352 handshake_mgr_->DoHandshake(ep, args, deadline_,
353 /*acceptor=*/nullptr, OnHandshakeDone,
354 /*user_data=*/this);
355 }
356
357 void HttpRequest::NextAddress(grpc_error_handle error) {
358 if (!error.ok()) {
359 AppendError(error);
360 }
361 if (cancelled_) {
362 Finish(GRPC_ERROR_CREATE_REFERENCING("HTTP request was cancelled",
363 &overall_error_, 1));
364 return;
365 }
366 if (next_address_ == addresses_.size()) {
367 Finish(GRPC_ERROR_CREATE_REFERENCING("Failed HTTP requests to all targets",
368 &overall_error_, 1));
369 return;
370 }
371 const grpc_resolved_address* addr = &addresses_[next_address_++];
372 DoHandshake(addr);
373 }
374
375 void HttpRequest::OnResolved(
376 absl::StatusOr<std::vector<grpc_resolved_address>> addresses_or) {
377 RefCountedPtr<HttpRequest> unreffer(this);
378 MutexLock lock(&mu_);
379 dns_request_handle_.reset();
380 if (cancelled_) {
381 Finish(GRPC_ERROR_CREATE("cancelled during DNS resolution"));
382 return;
383 }
384 if (!addresses_or.ok()) {
385 Finish(absl_status_to_grpc_error(addresses_or.status()));
386 return;
387 }
388 addresses_ = std::move(*addresses_or);
389 next_address_ = 0;
390 NextAddress(absl::OkStatus());
391 }
392
393 } // namespace grpc_core