Imported Upstream version 1.21.0
[platform/upstream/grpc.git] / src / core / ext / filters / client_channel / http_connect_handshaker.cc
1 /*
2  *
3  * Copyright 2016 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/ext/filters/client_channel/http_connect_handshaker.h"
22
23 #include <string.h>
24
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>
29
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"
40
41 namespace grpc_core {
42
43 namespace {
44
45 class HttpConnectHandshaker : public Handshaker {
46  public:
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"; }
53
54  private:
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);
60
61   gpr_mu mu_;
62
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;
67
68   // State saved while performing the handshake.
69   HandshakerArgs* args_ = nullptr;
70   grpc_closure* on_handshake_done_ = nullptr;
71
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_;
78 };
79
80 HttpConnectHandshaker::~HttpConnectHandshaker() {
81   gpr_mu_destroy(&mu_);
82   if (endpoint_to_destroy_ != nullptr) {
83     grpc_endpoint_destroy(endpoint_to_destroy_);
84   }
85   if (read_buffer_to_destroy_ != nullptr) {
86     grpc_slice_buffer_destroy_internal(read_buffer_to_destroy_);
87     gpr_free(read_buffer_to_destroy_);
88   }
89   grpc_slice_buffer_destroy_internal(&write_buffer_);
90   grpc_http_parser_destroy(&http_parser_);
91   grpc_http_response_destroy(&http_response_);
92 }
93
94 // Set args fields to nullptr, saving the endpoint and read buffer for
95 // later destruction.
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;
103 }
104
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
111     // own error.
112     error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Handshaker shutdown");
113   }
114   if (!is_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.
125     is_shutdown_ = true;
126   }
127   // Invoke callback.
128   GRPC_CLOSURE_SCHED(on_handshake_done_, error);
129 }
130
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_);
140     handshaker->Unref();
141   } else {
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_);
148   }
149 }
150
151 // Callback invoked for reading HTTP CONNECT response.
152 void HttpConnectHandshaker::OnReadDone(void* arg, grpc_error* error) {
153   auto* handshaker = static_cast<HttpConnectHandshaker*>(arg);
154
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));
160     goto done;
161   }
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],
168                                      &body_start_offset);
169       if (error != GRPC_ERROR_NONE) {
170         handshaker->HandshakeFailedLocked(error);
171         goto done;
172       }
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(
181               &tmp_buffer,
182               grpc_slice_split_tail(&handshaker->args_->read_buffer->slices[i],
183                                     body_start_offset));
184         }
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);
190         break;
191       }
192     }
193   }
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_);
211     return;
212   }
213   // Make sure we got a 2xx response.
214   if (handshaker->http_response_.status < 200 ||
215       handshaker->http_response_.status >= 300) {
216     char* msg;
217     gpr_asprintf(&msg, "HTTP proxy returned response code %d",
218                  handshaker->http_response_.status);
219     error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
220     gpr_free(msg);
221     handshaker->HandshakeFailedLocked(error);
222     goto done;
223   }
224   // Success.  Invoke handshake-done callback.
225   GRPC_CLOSURE_SCHED(handshaker->on_handshake_done_, error);
226 done:
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_);
231   handshaker->Unref();
232 }
233
234 //
235 // Public handshaker methods
236 //
237
238 void HttpConnectHandshaker::Shutdown(grpc_error* why) {
239   gpr_mu_lock(&mu_);
240   if (!is_shutdown_) {
241     is_shutdown_ = true;
242     grpc_endpoint_shutdown(args_->endpoint, GRPC_ERROR_REF(why));
243     CleanupArgsForFailureLocked();
244   }
245   gpr_mu_unlock(&mu_);
246   GRPC_ERROR_UNREF(why);
247 }
248
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.
260     gpr_mu_lock(&mu_);
261     is_shutdown_ = true;
262     gpr_mu_unlock(&mu_);
263     GRPC_CLOSURE_SCHED(on_handshake_done, GRPC_ERROR_NONE);
264     return;
265   }
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], ':');
280
281       if (sep == nullptr) {
282         gpr_log(GPR_ERROR, "skipping unparseable HTTP CONNECT header: %s",
283                 header_strings[i]);
284         continue;
285       }
286       *sep = '\0';
287       headers[num_headers].key = header_strings[i];
288       headers[num_headers].value = sep + 1;
289       ++num_headers;
290     }
291   }
292   // Save state in the handshaker object.
293   MutexLock lock(&mu_);
294   args_ = args;
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,
299           proxy_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);
315   // Clean up.
316   gpr_free(headers);
317   for (size_t i = 0; i < num_header_strings; ++i) {
318     gpr_free(header_strings[i]);
319   }
320   gpr_free(header_strings);
321   // Take a new ref to be held by the write callback.
322   Ref().release();
323   grpc_endpoint_write(args->endpoint, &write_buffer_, &request_done_closure_,
324                       nullptr);
325 }
326
327 HttpConnectHandshaker::HttpConnectHandshaker() {
328   gpr_mu_init(&mu_);
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_);
335 }
336
337 //
338 // handshaker factory
339 //
340
341 class HttpConnectHandshakerFactory : public HandshakerFactory {
342  public:
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>());
347   }
348   ~HttpConnectHandshakerFactory() override = default;
349 };
350
351 }  // namespace
352
353 }  // namespace grpc_core
354
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>()));
360 }