Debian Codegraph @

test/core/end2end/fixtures/http_proxy_fixture.cc

raw
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 "test/core/end2end/fixtures/http_proxy_fixture.h"
20
21 #include <limits.h>
22 #include <string.h>
23
24 #include <algorithm>
25 #include <memory>
26 #include <string>
27 #include <vector>
28
29 #include "absl/status/statusor.h"
30 #include "absl/strings/str_cat.h"
31
32 #include <grpc/grpc.h>
33 #include <grpc/slice.h>
34 #include <grpc/slice_buffer.h>
35 #include <grpc/support/alloc.h>
36 #include <grpc/support/log.h>
37 #include <grpc/support/sync.h>
38
39 #include "src/core/lib/address_utils/sockaddr_utils.h"
40 #include "src/core/lib/channel/channel_args.h"
41 #include "src/core/lib/channel/channel_args_preconditioning.h"
42 #include "src/core/lib/config/core_configuration.h"
43 #include "src/core/lib/event_engine/channel_args_endpoint_config.h"
44 #include "src/core/lib/gprpp/host_port.h"
45 #include "src/core/lib/gprpp/memory.h"
46 #include "src/core/lib/gprpp/status_helper.h"
47 #include "src/core/lib/gprpp/thd.h"
48 #include "src/core/lib/gprpp/time.h"
49 #include "src/core/lib/http/parser.h"
50 #include "src/core/lib/iomgr/closure.h"
51 #include "src/core/lib/iomgr/combiner.h"
52 #include "src/core/lib/iomgr/endpoint.h"
53 #include "src/core/lib/iomgr/error.h"
54 #include "src/core/lib/iomgr/exec_ctx.h"
55 #include "src/core/lib/iomgr/iomgr_fwd.h"
56 #include "src/core/lib/iomgr/pollset.h"
57 #include "src/core/lib/iomgr/pollset_set.h"
58 #include "src/core/lib/iomgr/resolve_address.h"
59 #include "src/core/lib/iomgr/resolved_address.h"
60 #include "src/core/lib/iomgr/sockaddr.h"
61 #include "src/core/lib/iomgr/tcp_client.h"
62 #include "src/core/lib/iomgr/tcp_server.h"
63 #include "src/core/lib/slice/b64.h"
64 #include "test/core/util/port.h"
65
66 struct grpc_end2end_http_proxy {
67 grpc_end2end_http_proxy()
68 : server(nullptr), channel_args(nullptr), mu(nullptr), combiner(nullptr) {
69 gpr_ref_init(&users, 1);
70 combiner = grpc_combiner_create();
71 }
72 std::string proxy_name;
73 grpc_core::Thread thd;
74 grpc_tcp_server* server;
75 const grpc_channel_args* channel_args;
76 gpr_mu* mu;
77 std::vector<grpc_pollset*> pollset;
78 gpr_refcount users;
79
80 grpc_core::Combiner* combiner;
81 };
82
83 //
84 // Connection handling
85 //
86
87 // proxy_connection structure is only accessed in the closures which are all
88 // scheduled under the same combiner lock. So there is no need for a mutex to
89 // protect this structure.
90 typedef struct proxy_connection {
91 grpc_end2end_http_proxy* proxy;
92
93 grpc_endpoint* client_endpoint;
94 grpc_endpoint* server_endpoint;
95
96 gpr_refcount refcount;
97
98 grpc_pollset_set* pollset_set;
99
100 // NOTE: All the closures execute under proxy->combiner lock. Which means
101 // there will not be any data-races between the closures
102 grpc_closure on_read_request_done;
103 grpc_closure on_server_connect_done;
104 grpc_closure on_write_response_done;
105 grpc_closure on_client_read_done;
106 grpc_closure on_client_write_done;
107 grpc_closure on_server_read_done;
108 grpc_closure on_server_write_done;
109
110 bool client_read_failed : 1;
111 bool client_write_failed : 1;
112 bool client_shutdown : 1;
113 bool server_read_failed : 1;
114 bool server_write_failed : 1;
115 bool server_shutdown : 1;
116
117 grpc_slice_buffer client_read_buffer;
118 grpc_slice_buffer client_deferred_write_buffer;
119 bool client_is_writing;
120 grpc_slice_buffer client_write_buffer;
121 grpc_slice_buffer server_read_buffer;
122 grpc_slice_buffer server_deferred_write_buffer;
123 bool server_is_writing;
124 grpc_slice_buffer server_write_buffer;
125
126 grpc_http_parser http_parser;
127 grpc_http_request http_request;
128 } proxy_connection;
129
130 static void proxy_connection_ref(proxy_connection* conn,
131 const char* /*reason*/) {
132 gpr_ref(&conn->refcount);
133 }
134
135 // Helper function to destroy the proxy connection.
136 static void proxy_connection_unref(proxy_connection* conn,
137 const char* /*reason*/) {
138 if (gpr_unref(&conn->refcount)) {
139 gpr_log(GPR_DEBUG, "endpoints: %p %p", conn->client_endpoint,
140 conn->server_endpoint);
141 grpc_endpoint_destroy(conn->client_endpoint);
142 if (conn->server_endpoint != nullptr) {
143 grpc_endpoint_destroy(conn->server_endpoint);
144 }
145 grpc_pollset_set_destroy(conn->pollset_set);
146 grpc_slice_buffer_destroy(&conn->client_read_buffer);
147 grpc_slice_buffer_destroy(&conn->client_deferred_write_buffer);
148 grpc_slice_buffer_destroy(&conn->client_write_buffer);
149 grpc_slice_buffer_destroy(&conn->server_read_buffer);
150 grpc_slice_buffer_destroy(&conn->server_deferred_write_buffer);
151 grpc_slice_buffer_destroy(&conn->server_write_buffer);
152 grpc_http_parser_destroy(&conn->http_parser);
153 grpc_http_request_destroy(&conn->http_request);
154 gpr_unref(&conn->proxy->users);
155 gpr_free(conn);
156 }
157 }
158
159 enum failure_type {
160 SETUP_FAILED, // To be used before we start proxying.
161 CLIENT_READ_FAILED,
162 CLIENT_WRITE_FAILED,
163 SERVER_READ_FAILED,
164 SERVER_WRITE_FAILED,
165 };
166
167 // Forward declarations
168 static void on_client_write_done(void* arg, grpc_error_handle error);
169 static void on_server_write_done(void* arg, grpc_error_handle error);
170 static void on_client_read_done(void* arg, grpc_error_handle error);
171 static void on_server_read_done(void* arg, grpc_error_handle error);
172 static void on_server_connect_done(void* arg, grpc_error_handle error);
173 static void on_read_request_done(void* arg, grpc_error_handle error);
174
175 static void on_client_write_done_locked(void* arg, grpc_error_handle error);
176 static void on_server_write_done_locked(void* arg, grpc_error_handle error);
177 static void on_client_read_done_locked(void* arg, grpc_error_handle error);
178 static void on_server_read_done_locked(void* arg, grpc_error_handle error);
179 static void on_server_connect_done_locked(void* arg, grpc_error_handle error);
180 static void on_read_request_done_locked(void* arg, grpc_error_handle error);
181
182 // Helper function to shut down the proxy connection.
183 static void proxy_connection_failed(proxy_connection* conn,
184 failure_type failure, const char* prefix,
185 grpc_error_handle error) {
186 gpr_log(GPR_INFO, "%s: %s", prefix, grpc_core::StatusToString(error).c_str());
187 // Decide whether we should shut down the client and server.
188 bool shutdown_client = false;
189 bool shutdown_server = false;
190 if (failure == SETUP_FAILED) {
191 shutdown_client = true;
192 shutdown_server = true;
193 } else {
194 if ((failure == CLIENT_READ_FAILED && conn->client_write_failed) ||
195 (failure == CLIENT_WRITE_FAILED && conn->client_read_failed) ||
196 (failure == SERVER_READ_FAILED && !conn->client_is_writing)) {
197 shutdown_client = true;
198 }
199 if ((failure == SERVER_READ_FAILED && conn->server_write_failed) ||
200 (failure == SERVER_WRITE_FAILED && conn->server_read_failed) ||
201 (failure == CLIENT_READ_FAILED && !conn->server_is_writing)) {
202 shutdown_server = true;
203 }
204 }
205 // If we decided to shut down either one and have not yet done so, do so.
206 if (shutdown_client && !conn->client_shutdown) {
207 grpc_endpoint_shutdown(conn->client_endpoint, error);
208 conn->client_shutdown = true;
209 }
210 if (shutdown_server && !conn->server_shutdown &&
211 (conn->server_endpoint != nullptr)) {
212 grpc_endpoint_shutdown(conn->server_endpoint, error);
213 conn->server_shutdown = true;
214 }
215 // Unref the connection.
216 proxy_connection_unref(conn, "conn_failed");
217 }
218
219 // Callback for writing proxy data to the client.
220 static void on_client_write_done_locked(void* arg, grpc_error_handle error) {
221 proxy_connection* conn = static_cast<proxy_connection*>(arg);
222 conn->client_is_writing = false;
223 if (!error.ok()) {
224 proxy_connection_failed(conn, CLIENT_WRITE_FAILED,
225 "HTTP proxy client write", error);
226 return;
227 }
228 // Clear write buffer (the data we just wrote).
229 grpc_slice_buffer_reset_and_unref(&conn->client_write_buffer);
230 // If more data was read from the server since we started this write,
231 // write that data now.
232 if (conn->client_deferred_write_buffer.length > 0) {
233 grpc_slice_buffer_move_into(&conn->client_deferred_write_buffer,
234 &conn->client_write_buffer);
235 conn->client_is_writing = true;
236 GRPC_CLOSURE_INIT(&conn->on_client_write_done, on_client_write_done, conn,
237 grpc_schedule_on_exec_ctx);
238 grpc_endpoint_write(conn->client_endpoint, &conn->client_write_buffer,
239 &conn->on_client_write_done, nullptr,
240 /*max_frame_size=*/INT_MAX);
241 } else {
242 // No more writes. Unref the connection.
243 proxy_connection_unref(conn, "write_done");
244 }
245 }
246
247 static void on_client_write_done(void* arg, grpc_error_handle error) {
248 proxy_connection* conn = static_cast<proxy_connection*>(arg);
249 GRPC_CLOSURE_INIT(&conn->on_client_write_done, on_client_write_done_locked,
250 conn, nullptr);
251 conn->proxy->combiner->Run(&conn->on_client_write_done, error);
252 }
253
254 // Callback for writing proxy data to the backend server.
255 static void on_server_write_done_locked(void* arg, grpc_error_handle error) {
256 proxy_connection* conn = static_cast<proxy_connection*>(arg);
257 conn->server_is_writing = false;
258 if (!error.ok()) {
259 proxy_connection_failed(conn, SERVER_WRITE_FAILED,
260 "HTTP proxy server write", error);
261 return;
262 }
263 // Clear write buffer (the data we just wrote).
264 grpc_slice_buffer_reset_and_unref(&conn->server_write_buffer);
265 // If more data was read from the client since we started this write,
266 // write that data now.
267 if (conn->server_deferred_write_buffer.length > 0) {
268 grpc_slice_buffer_move_into(&conn->server_deferred_write_buffer,
269 &conn->server_write_buffer);
270 conn->server_is_writing = true;
271 GRPC_CLOSURE_INIT(&conn->on_server_write_done, on_server_write_done, conn,
272 grpc_schedule_on_exec_ctx);
273 grpc_endpoint_write(conn->server_endpoint, &conn->server_write_buffer,
274 &conn->on_server_write_done, nullptr,
275 /*max_frame_size=*/INT_MAX);
276 } else {
277 // No more writes. Unref the connection.
278 proxy_connection_unref(conn, "server_write");
279 }
280 }
281
282 static void on_server_write_done(void* arg, grpc_error_handle error) {
283 proxy_connection* conn = static_cast<proxy_connection*>(arg);
284 GRPC_CLOSURE_INIT(&conn->on_server_write_done, on_server_write_done_locked,
285 conn, nullptr);
286 conn->proxy->combiner->Run(&conn->on_server_write_done, error);
287 }
288
289 // Callback for reading data from the client, which will be proxied to
290 // the backend server.
291 static void on_client_read_done_locked(void* arg, grpc_error_handle error) {
292 proxy_connection* conn = static_cast<proxy_connection*>(arg);
293 if (!error.ok()) {
294 proxy_connection_failed(conn, CLIENT_READ_FAILED, "HTTP proxy client read",
295 error);
296 return;
297 }
298 // If there is already a pending write (i.e., server_write_buffer is
299 // not empty), then move the read data into server_deferred_write_buffer,
300 // and the next write will be requested in on_server_write_done(), when
301 // the current write is finished.
302 //
303 // Otherwise, move the read data into the write buffer and write it.
304 if (conn->server_is_writing) {
305 grpc_slice_buffer_move_into(&conn->client_read_buffer,
306 &conn->server_deferred_write_buffer);
307 } else {
308 grpc_slice_buffer_move_into(&conn->client_read_buffer,
309 &conn->server_write_buffer);
310 proxy_connection_ref(conn, "client_read");
311 conn->server_is_writing = true;
312 GRPC_CLOSURE_INIT(&conn->on_server_write_done, on_server_write_done, conn,
313 grpc_schedule_on_exec_ctx);
314 grpc_endpoint_write(conn->server_endpoint, &conn->server_write_buffer,
315 &conn->on_server_write_done, nullptr,
316 /*max_frame_size=*/INT_MAX);
317 }
318 // Read more data.
319 GRPC_CLOSURE_INIT(&conn->on_client_read_done, on_client_read_done, conn,
320 grpc_schedule_on_exec_ctx);
321 grpc_endpoint_read(conn->client_endpoint, &conn->client_read_buffer,
322 &conn->on_client_read_done, /*urgent=*/false,
323 /*min_progress_size=*/1);
324 }
325
326 static void on_client_read_done(void* arg, grpc_error_handle error) {
327 proxy_connection* conn = static_cast<proxy_connection*>(arg);
328 GRPC_CLOSURE_INIT(&conn->on_client_read_done, on_client_read_done_locked,
329 conn, nullptr);
330 conn->proxy->combiner->Run(&conn->on_client_read_done, error);
331 }
332
333 // Callback for reading data from the backend server, which will be
334 // proxied to the client.
335 static void on_server_read_done_locked(void* arg, grpc_error_handle error) {
336 proxy_connection* conn = static_cast<proxy_connection*>(arg);
337 if (!error.ok()) {
338 proxy_connection_failed(conn, SERVER_READ_FAILED, "HTTP proxy server read",
339 error);
340 return;
341 }
342 // If there is already a pending write (i.e., client_write_buffer is
343 // not empty), then move the read data into client_deferred_write_buffer,
344 // and the next write will be requested in on_client_write_done(), when
345 // the current write is finished.
346 //
347 // Otherwise, move the read data into the write buffer and write it.
348 if (conn->client_is_writing) {
349 grpc_slice_buffer_move_into(&conn->server_read_buffer,
350 &conn->client_deferred_write_buffer);
351 } else {
352 grpc_slice_buffer_move_into(&conn->server_read_buffer,
353 &conn->client_write_buffer);
354 proxy_connection_ref(conn, "server_read");
355 conn->client_is_writing = true;
356 GRPC_CLOSURE_INIT(&conn->on_client_write_done, on_client_write_done, conn,
357 grpc_schedule_on_exec_ctx);
358 grpc_endpoint_write(conn->client_endpoint, &conn->client_write_buffer,
359 &conn->on_client_write_done, nullptr,
360 /*max_frame_size=*/INT_MAX);
361 }
362 // Read more data.
363 GRPC_CLOSURE_INIT(&conn->on_server_read_done, on_server_read_done, conn,
364 grpc_schedule_on_exec_ctx);
365 grpc_endpoint_read(conn->server_endpoint, &conn->server_read_buffer,
366 &conn->on_server_read_done, /*urgent=*/false,
367 /*min_progress_size=*/1);
368 }
369
370 static void on_server_read_done(void* arg, grpc_error_handle error) {
371 proxy_connection* conn = static_cast<proxy_connection*>(arg);
372 GRPC_CLOSURE_INIT(&conn->on_server_read_done, on_server_read_done_locked,
373 conn, nullptr);
374 conn->proxy->combiner->Run(&conn->on_server_read_done, error);
375 }
376
377 // Callback to write the HTTP response for the CONNECT request.
378 static void on_write_response_done_locked(void* arg, grpc_error_handle error) {
379 proxy_connection* conn = static_cast<proxy_connection*>(arg);
380 conn->client_is_writing = false;
381 if (!error.ok()) {
382 proxy_connection_failed(conn, SETUP_FAILED, "HTTP proxy write response",
383 error);
384 return;
385 }
386 // Clear write buffer.
387 grpc_slice_buffer_reset_and_unref(&conn->client_write_buffer);
388 // Start reading from both client and server. One of the read
389 // requests inherits our ref to conn, but we need to take a new ref
390 // for the other one.
391 proxy_connection_ref(conn, "client_read");
392 proxy_connection_ref(conn, "server_read");
393 proxy_connection_unref(conn, "write_response");
394 GRPC_CLOSURE_INIT(&conn->on_client_read_done, on_client_read_done, conn,
395 grpc_schedule_on_exec_ctx);
396 grpc_endpoint_read(conn->client_endpoint, &conn->client_read_buffer,
397 &conn->on_client_read_done, /*urgent=*/false,
398 /*min_progress_size=*/1);
399 GRPC_CLOSURE_INIT(&conn->on_server_read_done, on_server_read_done, conn,
400 grpc_schedule_on_exec_ctx);
401 grpc_endpoint_read(conn->server_endpoint, &conn->server_read_buffer,
402 &conn->on_server_read_done, /*urgent=*/false,
403 /*min_progress_size=*/1);
404 }
405
406 static void on_write_response_done(void* arg, grpc_error_handle error) {
407 proxy_connection* conn = static_cast<proxy_connection*>(arg);
408 GRPC_CLOSURE_INIT(&conn->on_write_response_done,
409 on_write_response_done_locked, conn, nullptr);
410 conn->proxy->combiner->Run(&conn->on_write_response_done, error);
411 }
412
413 // Callback to connect to the backend server specified by the HTTP
414 // CONNECT request.
415 static void on_server_connect_done_locked(void* arg, grpc_error_handle error) {
416 proxy_connection* conn = static_cast<proxy_connection*>(arg);
417 if (!error.ok()) {
418 // TODO(roth): Technically, in this case, we should handle the error
419 // by returning an HTTP response to the client indicating that the
420 // connection failed. However, for the purposes of this test code,
421 // it's fine to pretend this is a client-side error, which will
422 // cause the client connection to be dropped.
423 proxy_connection_failed(conn, SETUP_FAILED, "HTTP proxy server connect",
424 error);
425 return;
426 }
427 // We've established a connection, so send back a 200 response code to
428 // the client.
429 // The write callback inherits our reference to conn.
430 grpc_slice slice =
431 grpc_slice_from_copied_string("HTTP/1.0 200 connected\r\n\r\n");
432 grpc_slice_buffer_add(&conn->client_write_buffer, slice);
433 conn->client_is_writing = true;
434 GRPC_CLOSURE_INIT(&conn->on_write_response_done, on_write_response_done, conn,
435 grpc_schedule_on_exec_ctx);
436 grpc_endpoint_write(conn->client_endpoint, &conn->client_write_buffer,
437 &conn->on_write_response_done, nullptr,
438 /*max_frame_size=*/INT_MAX);
439 }
440
441 static void on_server_connect_done(void* arg, grpc_error_handle error) {
442 proxy_connection* conn = static_cast<proxy_connection*>(arg);
443 GRPC_CLOSURE_INIT(&conn->on_server_connect_done,
444 on_server_connect_done_locked, conn, nullptr);
445 conn->proxy->combiner->Run(&conn->on_server_connect_done, error);
446 }
447
448 /**
449 * Parses the proxy auth header value to check if it matches :-
450 * Basic <base64_encoded_expected_cred>
451 * Returns true if it matches, false otherwise
452 */
453 static bool proxy_auth_header_matches(char* proxy_auth_header_val,
454 char* expected_cred) {
455 GPR_ASSERT(proxy_auth_header_val != nullptr);
456 GPR_ASSERT(expected_cred != nullptr);
457 if (strncmp(proxy_auth_header_val, "Basic ", 6) != 0) {
458 return false;
459 }
460 proxy_auth_header_val += 6;
461 grpc_slice decoded_slice = grpc_base64_decode(proxy_auth_header_val, 0);
462 const bool header_matches =
463 grpc_slice_str_cmp(decoded_slice, expected_cred) == 0;
464 grpc_slice_unref(decoded_slice);
465 return header_matches;
466 }
467
468 // Callback to read the HTTP CONNECT request.
469 // TODO(roth): Technically, for any of the failure modes handled by this
470 // function, we should handle the error by returning an HTTP response to
471 // the client indicating that the request failed. However, for the purposes
472 // of this test code, it's fine to pretend this is a client-side error,
473 // which will cause the client connection to be dropped.
474 static void on_read_request_done_locked(void* arg, grpc_error_handle error) {
475 proxy_connection* conn = static_cast<proxy_connection*>(arg);
476 gpr_log(GPR_DEBUG, "on_read_request_done: %p %s", conn,
477 grpc_core::StatusToString(error).c_str());
478 if (!error.ok()) {
479 proxy_connection_failed(conn, SETUP_FAILED, "HTTP proxy read request",
480 error);
481 return;
482 }
483 // Read request and feed it to the parser.
484 for (size_t i = 0; i < conn->client_read_buffer.count; ++i) {
485 if (GRPC_SLICE_LENGTH(conn->client_read_buffer.slices[i]) > 0) {
486 error = grpc_http_parser_parse(
487 &conn->http_parser, conn->client_read_buffer.slices[i], nullptr);
488 if (!error.ok()) {
489 proxy_connection_failed(conn, SETUP_FAILED, "HTTP proxy request parse",
490 error);
491 return;
492 }
493 }
494 }
495 grpc_slice_buffer_reset_and_unref(&conn->client_read_buffer);
496 // If we're not done reading the request, read more data.
497 if (conn->http_parser.state != GRPC_HTTP_BODY) {
498 GRPC_CLOSURE_INIT(&conn->on_read_request_done, on_read_request_done, conn,
499 grpc_schedule_on_exec_ctx);
500 grpc_endpoint_read(conn->client_endpoint, &conn->client_read_buffer,
501 &conn->on_read_request_done, /*urgent=*/false,
502 /*min_progress_size=*/1);
503 return;
504 }
505 // Make sure we got a CONNECT request.
506 if (strcmp(conn->http_request.method, "CONNECT") != 0) {
507 error = GRPC_ERROR_CREATE(absl::StrCat("HTTP proxy got request method ",
508 conn->http_request.method));
509 proxy_connection_failed(conn, SETUP_FAILED, "HTTP proxy read request",
510 error);
511 return;
512 }
513 // If proxy auth is being used, check if the header is present and as expected
514 const grpc_arg* proxy_auth_arg = grpc_channel_args_find(
515 conn->proxy->channel_args, GRPC_ARG_HTTP_PROXY_AUTH_CREDS);
516 char* proxy_auth_str = grpc_channel_arg_get_string(proxy_auth_arg);
517 if (proxy_auth_str != nullptr) {
518 bool client_authenticated = false;
519 for (size_t i = 0; i < conn->http_request.hdr_count; i++) {
520 if (strcmp(conn->http_request.hdrs[i].key, "Proxy-Authorization") == 0) {
521 client_authenticated = proxy_auth_header_matches(
522 conn->http_request.hdrs[i].value, proxy_auth_str);
523 break;
524 }
525 }
526 if (!client_authenticated) {
527 const char* msg = "HTTP Connect could not verify authentication";
528 error = GRPC_ERROR_CREATE(msg);
529 proxy_connection_failed(conn, SETUP_FAILED, "HTTP proxy read request",
530 error);
531 return;
532 }
533 }
534 // Resolve address.
535 absl::StatusOr<std::vector<grpc_resolved_address>> addresses_or =
536 grpc_core::GetDNSResolver()->LookupHostnameBlocking(
537 conn->http_request.path, "80");
538 if (!addresses_or.ok()) {
539 proxy_connection_failed(conn, SETUP_FAILED, "HTTP proxy DNS lookup", error);
540 return;
541 }
542 GPR_ASSERT(!addresses_or->empty());
543 // Connect to requested address.
544 // The connection callback inherits our reference to conn.
545 const grpc_core::Timestamp deadline =
546 grpc_core::Timestamp::Now() + grpc_core::Duration::Seconds(10);
547 GRPC_CLOSURE_INIT(&conn->on_server_connect_done, on_server_connect_done, conn,
548 grpc_schedule_on_exec_ctx);
549 auto args = grpc_core::CoreConfiguration::Get()
550 .channel_args_preconditioning()
551 .PreconditionChannelArgs(nullptr);
552 grpc_tcp_client_connect(
553 &conn->on_server_connect_done, &conn->server_endpoint, conn->pollset_set,
554 grpc_event_engine::experimental::ChannelArgsEndpointConfig(args),
555 &(*addresses_or)[0], deadline);
556 }
557
558 static void on_read_request_done(void* arg, grpc_error_handle error) {
559 proxy_connection* conn = static_cast<proxy_connection*>(arg);
560 GRPC_CLOSURE_INIT(&conn->on_read_request_done, on_read_request_done_locked,
561 conn, nullptr);
562 conn->proxy->combiner->Run(&conn->on_read_request_done, error);
563 }
564
565 static void on_accept(void* arg, grpc_endpoint* endpoint,
566 grpc_pollset* /*accepting_pollset*/,
567 grpc_tcp_server_acceptor* acceptor) {
568 gpr_free(acceptor);
569 grpc_end2end_http_proxy* proxy = static_cast<grpc_end2end_http_proxy*>(arg);
570 // Instantiate proxy_connection.
571 proxy_connection* conn = grpc_core::Zalloc<proxy_connection>();
572 gpr_ref(&proxy->users);
573 conn->client_endpoint = endpoint;
574 conn->proxy = proxy;
575 gpr_ref_init(&conn->refcount, 1);
576 conn->pollset_set = grpc_pollset_set_create();
577 grpc_pollset_set_add_pollset(conn->pollset_set, proxy->pollset[0]);
578 grpc_endpoint_add_to_pollset_set(endpoint, conn->pollset_set);
579 grpc_slice_buffer_init(&conn->client_read_buffer);
580 grpc_slice_buffer_init(&conn->client_deferred_write_buffer);
581 conn->client_is_writing = false;
582 grpc_slice_buffer_init(&conn->client_write_buffer);
583 grpc_slice_buffer_init(&conn->server_read_buffer);
584 grpc_slice_buffer_init(&conn->server_deferred_write_buffer);
585 conn->server_is_writing = false;
586 grpc_slice_buffer_init(&conn->server_write_buffer);
587 grpc_http_parser_init(&conn->http_parser, GRPC_HTTP_REQUEST,
588 &conn->http_request);
589 GRPC_CLOSURE_INIT(&conn->on_read_request_done, on_read_request_done, conn,
590 grpc_schedule_on_exec_ctx);
591 grpc_endpoint_read(conn->client_endpoint, &conn->client_read_buffer,
592 &conn->on_read_request_done, /*urgent=*/false,
593 /*min_progress_size=*/1);
594 }
595
596 //
597 // Proxy class
598 //
599
600 static void thread_main(void* arg) {
601 grpc_end2end_http_proxy* proxy = static_cast<grpc_end2end_http_proxy*>(arg);
602 grpc_core::ExecCtx exec_ctx;
603 do {
604 gpr_ref(&proxy->users);
605 grpc_pollset_worker* worker = nullptr;
606 gpr_mu_lock(proxy->mu);
607 GRPC_LOG_IF_ERROR("grpc_pollset_work",
608 grpc_pollset_work(proxy->pollset[0], &worker,
609 grpc_core::Timestamp::Now() +
610 grpc_core::Duration::Seconds(1)));
611 gpr_mu_unlock(proxy->mu);
612 grpc_core::ExecCtx::Get()->Flush();
613 } while (!gpr_unref(&proxy->users));
614 }
615
616 grpc_end2end_http_proxy* grpc_end2end_http_proxy_create(
617 const grpc_channel_args* args) {
618 grpc_core::ExecCtx exec_ctx;
619 grpc_end2end_http_proxy* proxy = new grpc_end2end_http_proxy();
620 // Construct proxy address.
621 const int proxy_port = grpc_pick_unused_port_or_die();
622 proxy->proxy_name = grpc_core::JoinHostPort("localhost", proxy_port);
623 gpr_log(GPR_INFO, "Proxy address: %s", proxy->proxy_name.c_str());
624 // Create TCP server.
625 auto channel_args = grpc_core::CoreConfiguration::Get()
626 .channel_args_preconditioning()
627 .PreconditionChannelArgs(args);
628 proxy->channel_args = channel_args.ToC().release();
629 grpc_error_handle error = grpc_tcp_server_create(
630 nullptr,
631 grpc_event_engine::experimental::ChannelArgsEndpointConfig(channel_args),
632 &proxy->server);
633 GPR_ASSERT(error.ok());
634 // Bind to port.
635 grpc_resolved_address resolved_addr;
636 grpc_sockaddr_in* addr =
637 reinterpret_cast<grpc_sockaddr_in*>(resolved_addr.addr);
638 memset(&resolved_addr, 0, sizeof(resolved_addr));
639 addr->sin_family = GRPC_AF_INET;
640 grpc_sockaddr_set_port(&resolved_addr, proxy_port);
641 int port;
642 error = grpc_tcp_server_add_port(proxy->server, &resolved_addr, &port);
643 GPR_ASSERT(error.ok());
644 GPR_ASSERT(port == proxy_port);
645 // Start server.
646 auto* pollset = static_cast<grpc_pollset*>(gpr_zalloc(grpc_pollset_size()));
647 grpc_pollset_init(pollset, &proxy->mu);
648 proxy->pollset.push_back(pollset);
649 grpc_tcp_server_start(proxy->server, &proxy->pollset, on_accept, proxy);
650
651 // Start proxy thread.
652 proxy->thd = grpc_core::Thread("grpc_http_proxy", thread_main, proxy);
653 proxy->thd.Start();
654 return proxy;
655 }
656
657 static void destroy_pollset(void* arg, grpc_error_handle /*error*/) {
658 grpc_pollset* pollset = static_cast<grpc_pollset*>(arg);
659 grpc_pollset_destroy(pollset);
660 gpr_free(pollset);
661 }
662
663 void grpc_end2end_http_proxy_destroy(grpc_end2end_http_proxy* proxy) {
664 gpr_unref(&proxy->users); // Signal proxy thread to shutdown.
665 grpc_core::ExecCtx exec_ctx;
666 proxy->thd.Join();
667 grpc_tcp_server_shutdown_listeners(proxy->server);
668 grpc_tcp_server_unref(proxy->server);
669 grpc_channel_args_destroy(proxy->channel_args);
670 grpc_pollset_shutdown(proxy->pollset[0],
671 GRPC_CLOSURE_CREATE(destroy_pollset, proxy->pollset[0],
672 grpc_schedule_on_exec_ctx));
673 GRPC_COMBINER_UNREF(proxy->combiner, "test");
674 delete proxy;
675 }
676
677 const char* grpc_end2end_http_proxy_get_proxy_name(
678 grpc_end2end_http_proxy* proxy) {
679 return proxy->proxy_name.c_str();
680 }