3 * Copyright 2016 gRPC authors.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <grpc/support/port_platform.h>
21 #include "src/core/ext/filters/client_channel/http_connect_handshaker.h"
25 #include <grpc/slice_buffer.h>
26 #include <grpc/support/alloc.h>
27 #include <grpc/support/log.h>
28 #include <grpc/support/string_util.h>
30 #include "src/core/ext/filters/client_channel/client_channel.h"
31 #include "src/core/ext/filters/client_channel/resolver_registry.h"
32 #include "src/core/lib/channel/channel_args.h"
33 #include "src/core/lib/channel/handshaker_registry.h"
34 #include "src/core/lib/gpr/string.h"
35 #include "src/core/lib/gprpp/sync.h"
36 #include "src/core/lib/http/format_request.h"
37 #include "src/core/lib/http/parser.h"
38 #include "src/core/lib/slice/slice_internal.h"
39 #include "src/core/lib/uri/uri_parser.h"
45 class HttpConnectHandshaker : public Handshaker {
47 HttpConnectHandshaker();
48 void Shutdown(grpc_error* why) override;
49 void DoHandshake(grpc_tcp_server_acceptor* acceptor,
50 grpc_closure* on_handshake_done,
51 HandshakerArgs* args) override;
52 const char* name() const override { return "http_connect"; }
55 virtual ~HttpConnectHandshaker();
56 void CleanupArgsForFailureLocked();
57 void HandshakeFailedLocked(grpc_error* error);
58 static void OnWriteDone(void* arg, grpc_error* error);
59 static void OnReadDone(void* arg, grpc_error* error);
63 bool is_shutdown_ = false;
64 // Endpoint and read buffer to destroy after a shutdown.
65 grpc_endpoint* endpoint_to_destroy_ = nullptr;
66 grpc_slice_buffer* read_buffer_to_destroy_ = nullptr;
68 // State saved while performing the handshake.
69 HandshakerArgs* args_ = nullptr;
70 grpc_closure* on_handshake_done_ = nullptr;
72 // Objects for processing the HTTP CONNECT request and response.
73 grpc_slice_buffer write_buffer_;
74 grpc_closure request_done_closure_;
75 grpc_closure response_read_closure_;
76 grpc_http_parser http_parser_;
77 grpc_http_response http_response_;
80 HttpConnectHandshaker::~HttpConnectHandshaker() {
82 if (endpoint_to_destroy_ != nullptr) {
83 grpc_endpoint_destroy(endpoint_to_destroy_);
85 if (read_buffer_to_destroy_ != nullptr) {
86 grpc_slice_buffer_destroy_internal(read_buffer_to_destroy_);
87 gpr_free(read_buffer_to_destroy_);
89 grpc_slice_buffer_destroy_internal(&write_buffer_);
90 grpc_http_parser_destroy(&http_parser_);
91 grpc_http_response_destroy(&http_response_);
94 // Set args fields to nullptr, saving the endpoint and read buffer for
96 void HttpConnectHandshaker::CleanupArgsForFailureLocked() {
97 endpoint_to_destroy_ = args_->endpoint;
98 args_->endpoint = nullptr;
99 read_buffer_to_destroy_ = args_->read_buffer;
100 args_->read_buffer = nullptr;
101 grpc_channel_args_destroy(args_->args);
102 args_->args = nullptr;
105 // If the handshake failed or we're shutting down, clean up and invoke the
106 // callback with the error.
107 void HttpConnectHandshaker::HandshakeFailedLocked(grpc_error* error) {
108 if (error == GRPC_ERROR_NONE) {
109 // If we were shut down after an endpoint operation succeeded but
110 // before the endpoint callback was invoked, we need to generate our
112 error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Handshaker shutdown");
115 // TODO(ctiller): It is currently necessary to shutdown endpoints
116 // before destroying them, even if we know that there are no
117 // pending read/write callbacks. This should be fixed, at which
118 // point this can be removed.
119 grpc_endpoint_shutdown(args_->endpoint, GRPC_ERROR_REF(error));
120 // Not shutting down, so the handshake failed. Clean up before
121 // invoking the callback.
122 CleanupArgsForFailureLocked();
123 // Set shutdown to true so that subsequent calls to
124 // http_connect_handshaker_shutdown() do nothing.
128 GRPC_CLOSURE_SCHED(on_handshake_done_, error);
131 // Callback invoked when finished writing HTTP CONNECT request.
132 void HttpConnectHandshaker::OnWriteDone(void* arg, grpc_error* error) {
133 auto* handshaker = static_cast<HttpConnectHandshaker*>(arg);
134 gpr_mu_lock(&handshaker->mu_);
135 if (error != GRPC_ERROR_NONE || handshaker->is_shutdown_) {
136 // If the write failed or we're shutting down, clean up and invoke the
137 // callback with the error.
138 handshaker->HandshakeFailedLocked(GRPC_ERROR_REF(error));
139 gpr_mu_unlock(&handshaker->mu_);
142 // Otherwise, read the response.
143 // The read callback inherits our ref to the handshaker.
144 grpc_endpoint_read(handshaker->args_->endpoint,
145 handshaker->args_->read_buffer,
146 &handshaker->response_read_closure_, /*urgent=*/true);
147 gpr_mu_unlock(&handshaker->mu_);
151 // Callback invoked for reading HTTP CONNECT response.
152 void HttpConnectHandshaker::OnReadDone(void* arg, grpc_error* error) {
153 auto* handshaker = static_cast<HttpConnectHandshaker*>(arg);
155 gpr_mu_lock(&handshaker->mu_);
156 if (error != GRPC_ERROR_NONE || handshaker->is_shutdown_) {
157 // If the read failed or we're shutting down, clean up and invoke the
158 // callback with the error.
159 handshaker->HandshakeFailedLocked(GRPC_ERROR_REF(error));
162 // Add buffer to parser.
163 for (size_t i = 0; i < handshaker->args_->read_buffer->count; ++i) {
164 if (GRPC_SLICE_LENGTH(handshaker->args_->read_buffer->slices[i]) > 0) {
165 size_t body_start_offset = 0;
166 error = grpc_http_parser_parse(&handshaker->http_parser_,
167 handshaker->args_->read_buffer->slices[i],
169 if (error != GRPC_ERROR_NONE) {
170 handshaker->HandshakeFailedLocked(error);
173 if (handshaker->http_parser_.state == GRPC_HTTP_BODY) {
174 // Remove the data we've already read from the read buffer,
175 // leaving only the leftover bytes (if any).
176 grpc_slice_buffer tmp_buffer;
177 grpc_slice_buffer_init(&tmp_buffer);
178 if (body_start_offset <
179 GRPC_SLICE_LENGTH(handshaker->args_->read_buffer->slices[i])) {
180 grpc_slice_buffer_add(
182 grpc_slice_split_tail(&handshaker->args_->read_buffer->slices[i],
185 grpc_slice_buffer_addn(&tmp_buffer,
186 &handshaker->args_->read_buffer->slices[i + 1],
187 handshaker->args_->read_buffer->count - i - 1);
188 grpc_slice_buffer_swap(handshaker->args_->read_buffer, &tmp_buffer);
189 grpc_slice_buffer_destroy_internal(&tmp_buffer);
194 // If we're not done reading the response, read more data.
195 // TODO(roth): In practice, I suspect that the response to a CONNECT
196 // request will never include a body, in which case this check is
197 // sufficient. However, the language of RFC-2817 doesn't explicitly
198 // forbid the response from including a body. If there is a body,
199 // it's possible that we might have parsed part but not all of the
200 // body, in which case this check will cause us to fail to parse the
201 // remainder of the body. If that ever becomes an issue, we may
202 // need to fix the HTTP parser to understand when the body is
203 // complete (e.g., handling chunked transfer encoding or looking
204 // at the Content-Length: header).
205 if (handshaker->http_parser_.state != GRPC_HTTP_BODY) {
206 grpc_slice_buffer_reset_and_unref_internal(handshaker->args_->read_buffer);
207 grpc_endpoint_read(handshaker->args_->endpoint,
208 handshaker->args_->read_buffer,
209 &handshaker->response_read_closure_, /*urgent=*/true);
210 gpr_mu_unlock(&handshaker->mu_);
213 // Make sure we got a 2xx response.
214 if (handshaker->http_response_.status < 200 ||
215 handshaker->http_response_.status >= 300) {
217 gpr_asprintf(&msg, "HTTP proxy returned response code %d",
218 handshaker->http_response_.status);
219 error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
221 handshaker->HandshakeFailedLocked(error);
224 // Success. Invoke handshake-done callback.
225 GRPC_CLOSURE_SCHED(handshaker->on_handshake_done_, error);
227 // Set shutdown to true so that subsequent calls to
228 // http_connect_handshaker_shutdown() do nothing.
229 handshaker->is_shutdown_ = true;
230 gpr_mu_unlock(&handshaker->mu_);
235 // Public handshaker methods
238 void HttpConnectHandshaker::Shutdown(grpc_error* why) {
242 grpc_endpoint_shutdown(args_->endpoint, GRPC_ERROR_REF(why));
243 CleanupArgsForFailureLocked();
246 GRPC_ERROR_UNREF(why);
249 void HttpConnectHandshaker::DoHandshake(grpc_tcp_server_acceptor* acceptor,
250 grpc_closure* on_handshake_done,
251 HandshakerArgs* args) {
252 // Check for HTTP CONNECT channel arg.
253 // If not found, invoke on_handshake_done without doing anything.
254 const grpc_arg* arg =
255 grpc_channel_args_find(args->args, GRPC_ARG_HTTP_CONNECT_SERVER);
256 char* server_name = grpc_channel_arg_get_string(arg);
257 if (server_name == nullptr) {
258 // Set shutdown to true so that subsequent calls to
259 // http_connect_handshaker_shutdown() do nothing.
263 GRPC_CLOSURE_SCHED(on_handshake_done, GRPC_ERROR_NONE);
266 // Get headers from channel args.
267 arg = grpc_channel_args_find(args->args, GRPC_ARG_HTTP_CONNECT_HEADERS);
268 char* arg_header_string = grpc_channel_arg_get_string(arg);
269 grpc_http_header* headers = nullptr;
270 size_t num_headers = 0;
271 char** header_strings = nullptr;
272 size_t num_header_strings = 0;
273 if (arg_header_string != nullptr) {
274 gpr_string_split(arg_header_string, "\n", &header_strings,
275 &num_header_strings);
276 headers = static_cast<grpc_http_header*>(
277 gpr_malloc(sizeof(grpc_http_header) * num_header_strings));
278 for (size_t i = 0; i < num_header_strings; ++i) {
279 char* sep = strchr(header_strings[i], ':');
281 if (sep == nullptr) {
282 gpr_log(GPR_ERROR, "skipping unparseable HTTP CONNECT header: %s",
287 headers[num_headers].key = header_strings[i];
288 headers[num_headers].value = sep + 1;
292 // Save state in the handshaker object.
293 MutexLock lock(&mu_);
295 on_handshake_done_ = on_handshake_done;
296 // Log connection via proxy.
297 char* proxy_name = grpc_endpoint_get_peer(args->endpoint);
298 gpr_log(GPR_INFO, "Connecting to server %s via HTTP proxy %s", server_name,
300 gpr_free(proxy_name);
301 // Construct HTTP CONNECT request.
302 grpc_httpcli_request request;
303 request.host = server_name;
304 request.ssl_host_override = nullptr;
305 request.http.method = (char*)"CONNECT";
306 request.http.path = server_name;
307 request.http.version = GRPC_HTTP_HTTP10; // Set by OnReadDone
308 request.http.hdrs = headers;
309 request.http.hdr_count = num_headers;
310 request.http.body_length = 0;
311 request.http.body = nullptr;
312 request.handshaker = &grpc_httpcli_plaintext;
313 grpc_slice request_slice = grpc_httpcli_format_connect_request(&request);
314 grpc_slice_buffer_add(&write_buffer_, request_slice);
317 for (size_t i = 0; i < num_header_strings; ++i) {
318 gpr_free(header_strings[i]);
320 gpr_free(header_strings);
321 // Take a new ref to be held by the write callback.
323 grpc_endpoint_write(args->endpoint, &write_buffer_, &request_done_closure_,
327 HttpConnectHandshaker::HttpConnectHandshaker() {
329 grpc_slice_buffer_init(&write_buffer_);
330 GRPC_CLOSURE_INIT(&request_done_closure_, &HttpConnectHandshaker::OnWriteDone,
331 this, grpc_schedule_on_exec_ctx);
332 GRPC_CLOSURE_INIT(&response_read_closure_, &HttpConnectHandshaker::OnReadDone,
333 this, grpc_schedule_on_exec_ctx);
334 grpc_http_parser_init(&http_parser_, GRPC_HTTP_RESPONSE, &http_response_);
338 // handshaker factory
341 class HttpConnectHandshakerFactory : public HandshakerFactory {
343 void AddHandshakers(const grpc_channel_args* args,
344 grpc_pollset_set* interested_parties,
345 HandshakeManager* handshake_mgr) override {
346 handshake_mgr->Add(MakeRefCounted<HttpConnectHandshaker>());
348 ~HttpConnectHandshakerFactory() override = default;
353 } // namespace grpc_core
355 void grpc_http_connect_register_handshaker_factory() {
356 using namespace grpc_core;
357 HandshakerRegistry::RegisterHandshakerFactory(
358 true /* at_start */, HANDSHAKER_CLIENT,
359 UniquePtr<HandshakerFactory>(New<HttpConnectHandshakerFactory>()));