Debian Codegraph @

src/core/tsi/alts/handshaker/alts_handshaker_client.cc

raw
1 /*
2 *
3 * Copyright 2018 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/tsi/alts/handshaker/alts_handshaker_client.h"
22
23 #include <list>
24
25 #include "upb/upb.hpp"
26
27 #include <grpc/byte_buffer.h>
28 #include <grpc/support/alloc.h>
29 #include <grpc/support/log.h>
30
31 #include "src/core/lib/gprpp/sync.h"
32 #include "src/core/lib/slice/slice_internal.h"
33 #include "src/core/lib/surface/call.h"
34 #include "src/core/lib/surface/channel.h"
35 #include "src/core/tsi/alts/handshaker/alts_shared_resource.h"
36 #include "src/core/tsi/alts/handshaker/alts_tsi_handshaker_private.h"
37 #include "src/core/tsi/alts/handshaker/alts_tsi_utils.h"
38
39 #define TSI_ALTS_INITIAL_BUFFER_SIZE 256
40
41 const int kHandshakerClientOpNum = 4;
42
43 struct alts_handshaker_client {
44 const alts_handshaker_client_vtable* vtable;
45 };
46
47 struct recv_message_result {
48 tsi_result status;
49 const unsigned char* bytes_to_send;
50 size_t bytes_to_send_size;
51 tsi_handshaker_result* result;
52 };
53
54 typedef struct alts_grpc_handshaker_client {
55 alts_handshaker_client base;
56 /* One ref is held by the entity that created this handshaker_client, and
57 * another ref is held by the pending RECEIVE_STATUS_ON_CLIENT op. */
58 gpr_refcount refs;
59 alts_tsi_handshaker* handshaker;
60 grpc_call* call;
61 /* A pointer to a function handling the interaction with handshaker service.
62 * That is, it points to grpc_call_start_batch_and_execute when the handshaker
63 * client is used in a non-testing use case and points to a custom function
64 * that validates the data to be sent to handshaker service in a testing use
65 * case. */
66 alts_grpc_caller grpc_caller;
67 /* A gRPC closure to be scheduled when the response from handshaker service
68 * is received. It will be initialized with the injected grpc RPC callback. */
69 grpc_closure on_handshaker_service_resp_recv;
70 /* Buffers containing information to be sent (or received) to (or from) the
71 * handshaker service. */
72 grpc_byte_buffer* send_buffer = nullptr;
73 grpc_byte_buffer* recv_buffer = nullptr;
74 // Used to inject a read failure from tests.
75 bool inject_read_failure = false;
76 /* Initial metadata to be received from handshaker service. */
77 grpc_metadata_array recv_initial_metadata;
78 /* A callback function provided by an application to be invoked when response
79 * is received from handshaker service. */
80 tsi_handshaker_on_next_done_cb cb;
81 void* user_data;
82 /* ALTS credential options passed in from the caller. */
83 grpc_alts_credentials_options* options;
84 /* target name information to be passed to handshaker service for server
85 * authorization check. */
86 grpc_slice target_name;
87 /* boolean flag indicating if the handshaker client is used at client
88 * (is_client = true) or server (is_client = false) side. */
89 bool is_client;
90 /* a temporary store for data received from handshaker service used to extract
91 * unused data. */
92 grpc_slice recv_bytes;
93 /* a buffer containing data to be sent to the grpc client or server's peer. */
94 unsigned char* buffer;
95 size_t buffer_size;
96 /** callback for receiving handshake call status */
97 grpc_closure on_status_received;
98 /** gRPC status code of handshake call */
99 grpc_status_code handshake_status_code = GRPC_STATUS_OK;
100 /** gRPC status details of handshake call */
101 grpc_slice handshake_status_details;
102 /* mu synchronizes all fields below including their internal fields. */
103 grpc_core::Mutex mu;
104 /* indicates if the handshaker call's RECV_STATUS_ON_CLIENT op is done. */
105 bool receive_status_finished = false;
106 /* if non-null, contains arguments to complete a TSI next callback. */
107 recv_message_result* pending_recv_message_result = nullptr;
108 /* Maximum frame size used by frame protector. */
109 size_t max_frame_size;
110 // If non-null, will be populated with an error string upon error.
111 std::string* error;
112 } alts_grpc_handshaker_client;
113
114 static void handshaker_client_send_buffer_destroy(
115 alts_grpc_handshaker_client* client) {
116 GPR_ASSERT(client != nullptr);
117 grpc_byte_buffer_destroy(client->send_buffer);
118 client->send_buffer = nullptr;
119 }
120
121 static bool is_handshake_finished_properly(grpc_gcp_HandshakerResp* resp) {
122 GPR_ASSERT(resp != nullptr);
123 return grpc_gcp_HandshakerResp_result(resp) != nullptr;
124 }
125
126 static void alts_grpc_handshaker_client_unref(
127 alts_grpc_handshaker_client* client) {
128 if (gpr_unref(&client->refs)) {
129 if (client->base.vtable != nullptr &&
130 client->base.vtable->destruct != nullptr) {
131 client->base.vtable->destruct(&client->base);
132 }
133 grpc_byte_buffer_destroy(client->send_buffer);
134 grpc_byte_buffer_destroy(client->recv_buffer);
135 client->send_buffer = nullptr;
136 client->recv_buffer = nullptr;
137 grpc_metadata_array_destroy(&client->recv_initial_metadata);
138 grpc_core::CSliceUnref(client->recv_bytes);
139 grpc_core::CSliceUnref(client->target_name);
140 grpc_alts_credentials_options_destroy(client->options);
141 gpr_free(client->buffer);
142 grpc_core::CSliceUnref(client->handshake_status_details);
143 delete client;
144 }
145 }
146
147 static void maybe_complete_tsi_next(
148 alts_grpc_handshaker_client* client, bool receive_status_finished,
149 recv_message_result* pending_recv_message_result) {
150 recv_message_result* r;
151 {
152 grpc_core::MutexLock lock(&client->mu);
153 client->receive_status_finished |= receive_status_finished;
154 if (pending_recv_message_result != nullptr) {
155 GPR_ASSERT(client->pending_recv_message_result == nullptr);
156 client->pending_recv_message_result = pending_recv_message_result;
157 }
158 if (client->pending_recv_message_result == nullptr) {
159 return;
160 }
161 const bool have_final_result =
162 client->pending_recv_message_result->result != nullptr ||
163 client->pending_recv_message_result->status != TSI_OK;
164 if (have_final_result && !client->receive_status_finished) {
165 // If we've received the final message from the handshake
166 // server, or we're about to invoke the TSI next callback
167 // with a status other than TSI_OK (which terminates the
168 // handshake), then first wait for the RECV_STATUS op to complete.
169 return;
170 }
171 r = client->pending_recv_message_result;
172 client->pending_recv_message_result = nullptr;
173 }
174 client->cb(r->status, client->user_data, r->bytes_to_send,
175 r->bytes_to_send_size, r->result);
176 gpr_free(r);
177 }
178
179 static void handle_response_done(alts_grpc_handshaker_client* client,
180 tsi_result status, std::string error,
181 const unsigned char* bytes_to_send,
182 size_t bytes_to_send_size,
183 tsi_handshaker_result* result) {
184 if (client->error != nullptr) *client->error = std::move(error);
185 recv_message_result* p = grpc_core::Zalloc<recv_message_result>();
186 p->status = status;
187 p->bytes_to_send = bytes_to_send;
188 p->bytes_to_send_size = bytes_to_send_size;
189 p->result = result;
190 maybe_complete_tsi_next(client, false /* receive_status_finished */,
191 p /* pending_recv_message_result */);
192 }
193
194 void alts_handshaker_client_handle_response(alts_handshaker_client* c,
195 bool is_ok) {
196 GPR_ASSERT(c != nullptr);
197 alts_grpc_handshaker_client* client =
198 reinterpret_cast<alts_grpc_handshaker_client*>(c);
199 grpc_byte_buffer* recv_buffer = client->recv_buffer;
200 alts_tsi_handshaker* handshaker = client->handshaker;
201 /* Invalid input check. */
202 if (client->cb == nullptr) {
203 gpr_log(GPR_ERROR,
204 "client->cb is nullptr in alts_tsi_handshaker_handle_response()");
205 return;
206 }
207 if (handshaker == nullptr) {
208 gpr_log(GPR_ERROR,
209 "handshaker is nullptr in alts_tsi_handshaker_handle_response()");
210 handle_response_done(
211 client, TSI_INTERNAL_ERROR,
212 "handshaker is nullptr in alts_tsi_handshaker_handle_response()",
213 nullptr, 0, nullptr);
214 return;
215 }
216 /* TSI handshake has been shutdown. */
217 if (alts_tsi_handshaker_has_shutdown(handshaker)) {
218 gpr_log(GPR_INFO, "TSI handshake shutdown");
219 handle_response_done(client, TSI_HANDSHAKE_SHUTDOWN,
220 "TSI handshake shutdown", nullptr, 0, nullptr);
221 return;
222 }
223 /* Check for failed grpc read. */
224 if (!is_ok || client->inject_read_failure) {
225 gpr_log(GPR_INFO, "read failed on grpc call to handshaker service");
226 handle_response_done(client, TSI_INTERNAL_ERROR,
227 "read failed on grpc call to handshaker service",
228 nullptr, 0, nullptr);
229 return;
230 }
231 if (recv_buffer == nullptr) {
232 gpr_log(GPR_ERROR,
233 "recv_buffer is nullptr in alts_tsi_handshaker_handle_response()");
234 handle_response_done(
235 client, TSI_INTERNAL_ERROR,
236 "recv_buffer is nullptr in alts_tsi_handshaker_handle_response()",
237 nullptr, 0, nullptr);
238 return;
239 }
240 upb::Arena arena;
241 grpc_gcp_HandshakerResp* resp =
242 alts_tsi_utils_deserialize_response(recv_buffer, arena.ptr());
243 grpc_byte_buffer_destroy(client->recv_buffer);
244 client->recv_buffer = nullptr;
245 /* Invalid handshaker response check. */
246 if (resp == nullptr) {
247 gpr_log(GPR_ERROR, "alts_tsi_utils_deserialize_response() failed");
248 handle_response_done(client, TSI_DATA_CORRUPTED,
249 "alts_tsi_utils_deserialize_response() failed",
250 nullptr, 0, nullptr);
251 return;
252 }
253 const grpc_gcp_HandshakerStatus* resp_status =
254 grpc_gcp_HandshakerResp_status(resp);
255 if (resp_status == nullptr) {
256 gpr_log(GPR_ERROR, "No status in HandshakerResp");
257 handle_response_done(client, TSI_DATA_CORRUPTED,
258 "No status in HandshakerResp", nullptr, 0, nullptr);
259 return;
260 }
261 upb_StringView out_frames = grpc_gcp_HandshakerResp_out_frames(resp);
262 unsigned char* bytes_to_send = nullptr;
263 size_t bytes_to_send_size = 0;
264 if (out_frames.size > 0) {
265 bytes_to_send_size = out_frames.size;
266 while (bytes_to_send_size > client->buffer_size) {
267 client->buffer_size *= 2;
268 client->buffer = static_cast<unsigned char*>(
269 gpr_realloc(client->buffer, client->buffer_size));
270 }
271 memcpy(client->buffer, out_frames.data, bytes_to_send_size);
272 bytes_to_send = client->buffer;
273 }
274 tsi_handshaker_result* result = nullptr;
275 if (is_handshake_finished_properly(resp)) {
276 tsi_result status =
277 alts_tsi_handshaker_result_create(resp, client->is_client, &result);
278 if (status != TSI_OK) {
279 gpr_log(GPR_ERROR, "alts_tsi_handshaker_result_create() failed");
280 handle_response_done(client, status,
281 "alts_tsi_handshaker_result_create() failed",
282 nullptr, 0, nullptr);
283 return;
284 }
285 alts_tsi_handshaker_result_set_unused_bytes(
286 result, &client->recv_bytes,
287 grpc_gcp_HandshakerResp_bytes_consumed(resp));
288 }
289 grpc_status_code code = static_cast<grpc_status_code>(
290 grpc_gcp_HandshakerStatus_code(resp_status));
291 std::string error;
292 if (code != GRPC_STATUS_OK) {
293 upb_StringView details = grpc_gcp_HandshakerStatus_details(resp_status);
294 if (details.size > 0) {
295 error = absl::StrCat("Status ", code, " from handshaker service: ",
296 absl::string_view(details.data, details.size));
297 gpr_log(GPR_ERROR, "%s", error.c_str());
298 }
299 }
300 // TODO(apolcyn): consider short ciruiting handle_response_done and
301 // invoking the TSI callback directly if we aren't done yet, if
302 // handle_response_done's allocation per message received causes
303 // a performance issue.
304 handle_response_done(client, alts_tsi_utils_convert_to_tsi_result(code),
305 std::move(error), bytes_to_send, bytes_to_send_size,
306 result);
307 }
308
309 static tsi_result continue_make_grpc_call(alts_grpc_handshaker_client* client,
310 bool is_start) {
311 GPR_ASSERT(client != nullptr);
312 grpc_op ops[kHandshakerClientOpNum];
313 memset(ops, 0, sizeof(ops));
314 grpc_op* op = ops;
315 if (is_start) {
316 op->op = GRPC_OP_RECV_STATUS_ON_CLIENT;
317 op->data.recv_status_on_client.trailing_metadata = nullptr;
318 op->data.recv_status_on_client.status = &client->handshake_status_code;
319 op->data.recv_status_on_client.status_details =
320 &client->handshake_status_details;
321 op->flags = 0;
322 op->reserved = nullptr;
323 op++;
324 GPR_ASSERT(op - ops <= kHandshakerClientOpNum);
325 gpr_ref(&client->refs);
326 grpc_call_error call_error =
327 client->grpc_caller(client->call, ops, static_cast<size_t>(op - ops),
328 &client->on_status_received);
329 // TODO(apolcyn): return the error here instead, as done for other ops?
330 GPR_ASSERT(call_error == GRPC_CALL_OK);
331 memset(ops, 0, sizeof(ops));
332 op = ops;
333 op->op = GRPC_OP_SEND_INITIAL_METADATA;
334 op->data.send_initial_metadata.count = 0;
335 op++;
336 GPR_ASSERT(op - ops <= kHandshakerClientOpNum);
337 op->op = GRPC_OP_RECV_INITIAL_METADATA;
338 op->data.recv_initial_metadata.recv_initial_metadata =
339 &client->recv_initial_metadata;
340 op++;
341 GPR_ASSERT(op - ops <= kHandshakerClientOpNum);
342 }
343 op->op = GRPC_OP_SEND_MESSAGE;
344 op->data.send_message.send_message = client->send_buffer;
345 op++;
346 GPR_ASSERT(op - ops <= kHandshakerClientOpNum);
347 op->op = GRPC_OP_RECV_MESSAGE;
348 op->data.recv_message.recv_message = &client->recv_buffer;
349 op++;
350 GPR_ASSERT(op - ops <= kHandshakerClientOpNum);
351 GPR_ASSERT(client->grpc_caller != nullptr);
352 if (client->grpc_caller(client->call, ops, static_cast<size_t>(op - ops),
353 &client->on_handshaker_service_resp_recv) !=
354 GRPC_CALL_OK) {
355 gpr_log(GPR_ERROR, "Start batch operation failed");
356 return TSI_INTERNAL_ERROR;
357 }
358 return TSI_OK;
359 }
360
361 // TODO(apolcyn): remove this global queue when we can safely rely
362 // on a MAX_CONCURRENT_STREAMS setting in the ALTS handshake server to
363 // limit the number of concurrent handshakes.
364 namespace {
365
366 class HandshakeQueue {
367 public:
368 explicit HandshakeQueue(size_t max_outstanding_handshakes)
369 : max_outstanding_handshakes_(max_outstanding_handshakes) {}
370
371 void RequestHandshake(alts_grpc_handshaker_client* client) {
372 {
373 grpc_core::MutexLock lock(&mu_);
374 if (outstanding_handshakes_ == max_outstanding_handshakes_) {
375 // Max number already running, add to queue.
376 queued_handshakes_.push_back(client);
377 return;
378 }
379 // Start the handshake immediately.
380 ++outstanding_handshakes_;
381 }
382 continue_make_grpc_call(client, true /* is_start */);
383 }
384
385 void HandshakeDone() {
386 alts_grpc_handshaker_client* client = nullptr;
387 {
388 grpc_core::MutexLock lock(&mu_);
389 if (queued_handshakes_.empty()) {
390 // Nothing more in queue. Decrement count and return immediately.
391 --outstanding_handshakes_;
392 return;
393 }
394 // Remove next entry from queue and start the handshake.
395 client = queued_handshakes_.front();
396 queued_handshakes_.pop_front();
397 }
398 continue_make_grpc_call(client, true /* is_start */);
399 }
400
401 private:
402 grpc_core::Mutex mu_;
403 std::list<alts_grpc_handshaker_client*> queued_handshakes_;
404 size_t outstanding_handshakes_ = 0;
405 const size_t max_outstanding_handshakes_;
406 };
407
408 gpr_once g_queued_handshakes_init = GPR_ONCE_INIT;
409 /* Using separate queues for client and server handshakes is a
410 * hack that's mainly intended to satisfy the alts_concurrent_connectivity_test,
411 * which runs many concurrent handshakes where both endpoints
412 * are in the same process; this situation is problematic with a
413 * single queue because we have a high chance of using up all outstanding
414 * slots in the queue, such that there aren't any
415 * mutual client/server handshakes outstanding at the same time and
416 * able to make progress. */
417 HandshakeQueue* g_client_handshake_queue;
418 HandshakeQueue* g_server_handshake_queue;
419
420 void DoHandshakeQueuesInit(void) {
421 const size_t per_queue_max_outstanding_handshakes = 40;
422 g_client_handshake_queue =
423 new HandshakeQueue(per_queue_max_outstanding_handshakes);
424 g_server_handshake_queue =
425 new HandshakeQueue(per_queue_max_outstanding_handshakes);
426 }
427
428 void RequestHandshake(alts_grpc_handshaker_client* client, bool is_client) {
429 gpr_once_init(&g_queued_handshakes_init, DoHandshakeQueuesInit);
430 HandshakeQueue* queue =
431 is_client ? g_client_handshake_queue : g_server_handshake_queue;
432 queue->RequestHandshake(client);
433 }
434
435 void HandshakeDone(bool is_client) {
436 HandshakeQueue* queue =
437 is_client ? g_client_handshake_queue : g_server_handshake_queue;
438 queue->HandshakeDone();
439 }
440
441 }; // namespace
442
443 /**
444 * Populate grpc operation data with the fields of ALTS handshaker client and
445 * make a grpc call.
446 */
447 static tsi_result make_grpc_call(alts_handshaker_client* c, bool is_start) {
448 GPR_ASSERT(c != nullptr);
449 alts_grpc_handshaker_client* client =
450 reinterpret_cast<alts_grpc_handshaker_client*>(c);
451 if (is_start) {
452 RequestHandshake(client, client->is_client);
453 return TSI_OK;
454 } else {
455 return continue_make_grpc_call(client, is_start);
456 }
457 }
458
459 static void on_status_received(void* arg, grpc_error_handle error) {
460 alts_grpc_handshaker_client* client =
461 static_cast<alts_grpc_handshaker_client*>(arg);
462 if (client->handshake_status_code != GRPC_STATUS_OK) {
463 // TODO(apolcyn): consider overriding the handshake result's
464 // status from the final ALTS message with the status here.
465 char* status_details =
466 grpc_slice_to_c_string(client->handshake_status_details);
467 gpr_log(GPR_INFO,
468 "alts_grpc_handshaker_client:%p on_status_received "
469 "status:%d details:|%s| error:|%s|",
470 client, client->handshake_status_code, status_details,
471 grpc_core::StatusToString(error).c_str());
472 gpr_free(status_details);
473 }
474 maybe_complete_tsi_next(client, true /* receive_status_finished */,
475 nullptr /* pending_recv_message_result */);
476 HandshakeDone(client->is_client);
477 alts_grpc_handshaker_client_unref(client);
478 }
479
480 /* Serializes a grpc_gcp_HandshakerReq message into a buffer and returns newly
481 * grpc_byte_buffer holding it. */
482 static grpc_byte_buffer* get_serialized_handshaker_req(
483 grpc_gcp_HandshakerReq* req, upb_Arena* arena) {
484 size_t buf_length;
485 char* buf = grpc_gcp_HandshakerReq_serialize(req, arena, &buf_length);
486 if (buf == nullptr) {
487 return nullptr;
488 }
489 grpc_slice slice = grpc_slice_from_copied_buffer(buf, buf_length);
490 grpc_byte_buffer* byte_buffer = grpc_raw_byte_buffer_create(&slice, 1);
491 grpc_core::CSliceUnref(slice);
492 return byte_buffer;
493 }
494
495 /* Create and populate a client_start handshaker request, then serialize it. */
496 static grpc_byte_buffer* get_serialized_start_client(
497 alts_handshaker_client* c) {
498 GPR_ASSERT(c != nullptr);
499 alts_grpc_handshaker_client* client =
500 reinterpret_cast<alts_grpc_handshaker_client*>(c);
501 upb::Arena arena;
502 grpc_gcp_HandshakerReq* req = grpc_gcp_HandshakerReq_new(arena.ptr());
503 grpc_gcp_StartClientHandshakeReq* start_client =
504 grpc_gcp_HandshakerReq_mutable_client_start(req, arena.ptr());
505 grpc_gcp_StartClientHandshakeReq_set_handshake_security_protocol(
506 start_client, grpc_gcp_ALTS);
507 grpc_gcp_StartClientHandshakeReq_add_application_protocols(
508 start_client, upb_StringView_FromString(ALTS_APPLICATION_PROTOCOL),
509 arena.ptr());
510 grpc_gcp_StartClientHandshakeReq_add_record_protocols(
511 start_client, upb_StringView_FromString(ALTS_RECORD_PROTOCOL),
512 arena.ptr());
513 grpc_gcp_RpcProtocolVersions* client_version =
514 grpc_gcp_StartClientHandshakeReq_mutable_rpc_versions(start_client,
515 arena.ptr());
516 grpc_gcp_RpcProtocolVersions_assign_from_struct(
517 client_version, arena.ptr(), &client->options->rpc_versions);
518 grpc_gcp_StartClientHandshakeReq_set_target_name(
519 start_client, upb_StringView_FromDataAndSize(
520 reinterpret_cast<const char*>(
521 GRPC_SLICE_START_PTR(client->target_name)),
522 GRPC_SLICE_LENGTH(client->target_name)));
523 target_service_account* ptr =
524 (reinterpret_cast<grpc_alts_credentials_client_options*>(client->options))
525 ->target_account_list_head;
526 while (ptr != nullptr) {
527 grpc_gcp_Identity* target_identity =
528 grpc_gcp_StartClientHandshakeReq_add_target_identities(start_client,
529 arena.ptr());
530 grpc_gcp_Identity_set_service_account(target_identity,
531 upb_StringView_FromString(ptr->data));
532 ptr = ptr->next;
533 }
534 grpc_gcp_StartClientHandshakeReq_set_max_frame_size(
535 start_client, static_cast<uint32_t>(client->max_frame_size));
536 return get_serialized_handshaker_req(req, arena.ptr());
537 }
538
539 static tsi_result handshaker_client_start_client(alts_handshaker_client* c) {
540 if (c == nullptr) {
541 gpr_log(GPR_ERROR, "client is nullptr in handshaker_client_start_client()");
542 return TSI_INVALID_ARGUMENT;
543 }
544 grpc_byte_buffer* buffer = get_serialized_start_client(c);
545 alts_grpc_handshaker_client* client =
546 reinterpret_cast<alts_grpc_handshaker_client*>(c);
547 if (buffer == nullptr) {
548 gpr_log(GPR_ERROR, "get_serialized_start_client() failed");
549 return TSI_INTERNAL_ERROR;
550 }
551 handshaker_client_send_buffer_destroy(client);
552 client->send_buffer = buffer;
553 tsi_result result = make_grpc_call(&client->base, true /* is_start */);
554 if (result != TSI_OK) {
555 gpr_log(GPR_ERROR, "make_grpc_call() failed");
556 }
557 return result;
558 }
559
560 /* Create and populate a start_server handshaker request, then serialize it. */
561 static grpc_byte_buffer* get_serialized_start_server(
562 alts_handshaker_client* c, grpc_slice* bytes_received) {
563 GPR_ASSERT(c != nullptr);
564 GPR_ASSERT(bytes_received != nullptr);
565 alts_grpc_handshaker_client* client =
566 reinterpret_cast<alts_grpc_handshaker_client*>(c);
567
568 upb::Arena arena;
569 grpc_gcp_HandshakerReq* req = grpc_gcp_HandshakerReq_new(arena.ptr());
570
571 grpc_gcp_StartServerHandshakeReq* start_server =
572 grpc_gcp_HandshakerReq_mutable_server_start(req, arena.ptr());
573 grpc_gcp_StartServerHandshakeReq_add_application_protocols(
574 start_server, upb_StringView_FromString(ALTS_APPLICATION_PROTOCOL),
575 arena.ptr());
576 grpc_gcp_ServerHandshakeParameters* value =
577 grpc_gcp_ServerHandshakeParameters_new(arena.ptr());
578 grpc_gcp_ServerHandshakeParameters_add_record_protocols(
579 value, upb_StringView_FromString(ALTS_RECORD_PROTOCOL), arena.ptr());
580 grpc_gcp_StartServerHandshakeReq_handshake_parameters_set(
581 start_server, grpc_gcp_ALTS, value, arena.ptr());
582 grpc_gcp_StartServerHandshakeReq_set_in_bytes(
583 start_server,
584 upb_StringView_FromDataAndSize(
585 reinterpret_cast<const char*>(GRPC_SLICE_START_PTR(*bytes_received)),
586 GRPC_SLICE_LENGTH(*bytes_received)));
587 grpc_gcp_RpcProtocolVersions* server_version =
588 grpc_gcp_StartServerHandshakeReq_mutable_rpc_versions(start_server,
589 arena.ptr());
590 grpc_gcp_RpcProtocolVersions_assign_from_struct(
591 server_version, arena.ptr(), &client->options->rpc_versions);
592 grpc_gcp_StartServerHandshakeReq_set_max_frame_size(
593 start_server, static_cast<uint32_t>(client->max_frame_size));
594 return get_serialized_handshaker_req(req, arena.ptr());
595 }
596
597 static tsi_result handshaker_client_start_server(alts_handshaker_client* c,
598 grpc_slice* bytes_received) {
599 if (c == nullptr || bytes_received == nullptr) {
600 gpr_log(GPR_ERROR, "Invalid arguments to handshaker_client_start_server()");
601 return TSI_INVALID_ARGUMENT;
602 }
603 alts_grpc_handshaker_client* client =
604 reinterpret_cast<alts_grpc_handshaker_client*>(c);
605 grpc_byte_buffer* buffer = get_serialized_start_server(c, bytes_received);
606 if (buffer == nullptr) {
607 gpr_log(GPR_ERROR, "get_serialized_start_server() failed");
608 return TSI_INTERNAL_ERROR;
609 }
610 handshaker_client_send_buffer_destroy(client);
611 client->send_buffer = buffer;
612 tsi_result result = make_grpc_call(&client->base, true /* is_start */);
613 if (result != TSI_OK) {
614 gpr_log(GPR_ERROR, "make_grpc_call() failed");
615 }
616 return result;
617 }
618
619 /* Create and populate a next handshaker request, then serialize it. */
620 static grpc_byte_buffer* get_serialized_next(grpc_slice* bytes_received) {
621 GPR_ASSERT(bytes_received != nullptr);
622 upb::Arena arena;
623 grpc_gcp_HandshakerReq* req = grpc_gcp_HandshakerReq_new(arena.ptr());
624 grpc_gcp_NextHandshakeMessageReq* next =
625 grpc_gcp_HandshakerReq_mutable_next(req, arena.ptr());
626 grpc_gcp_NextHandshakeMessageReq_set_in_bytes(
627 next,
628 upb_StringView_FromDataAndSize(
629 reinterpret_cast<const char*> GRPC_SLICE_START_PTR(*bytes_received),
630 GRPC_SLICE_LENGTH(*bytes_received)));
631 return get_serialized_handshaker_req(req, arena.ptr());
632 }
633
634 static tsi_result handshaker_client_next(alts_handshaker_client* c,
635 grpc_slice* bytes_received) {
636 if (c == nullptr || bytes_received == nullptr) {
637 gpr_log(GPR_ERROR, "Invalid arguments to handshaker_client_next()");
638 return TSI_INVALID_ARGUMENT;
639 }
640 alts_grpc_handshaker_client* client =
641 reinterpret_cast<alts_grpc_handshaker_client*>(c);
642 grpc_core::CSliceUnref(client->recv_bytes);
643 client->recv_bytes = grpc_core::CSliceRef(*bytes_received);
644 grpc_byte_buffer* buffer = get_serialized_next(bytes_received);
645 if (buffer == nullptr) {
646 gpr_log(GPR_ERROR, "get_serialized_next() failed");
647 return TSI_INTERNAL_ERROR;
648 }
649 handshaker_client_send_buffer_destroy(client);
650 client->send_buffer = buffer;
651 tsi_result result = make_grpc_call(&client->base, false /* is_start */);
652 if (result != TSI_OK) {
653 gpr_log(GPR_ERROR, "make_grpc_call() failed");
654 }
655 return result;
656 }
657
658 static void handshaker_client_shutdown(alts_handshaker_client* c) {
659 GPR_ASSERT(c != nullptr);
660 alts_grpc_handshaker_client* client =
661 reinterpret_cast<alts_grpc_handshaker_client*>(c);
662 if (client->call != nullptr) {
663 grpc_call_cancel_internal(client->call);
664 }
665 }
666
667 static void handshaker_call_unref(void* arg, grpc_error_handle /* error */) {
668 grpc_call* call = static_cast<grpc_call*>(arg);
669 grpc_call_unref(call);
670 }
671
672 static void handshaker_client_destruct(alts_handshaker_client* c) {
673 if (c == nullptr) {
674 return;
675 }
676 alts_grpc_handshaker_client* client =
677 reinterpret_cast<alts_grpc_handshaker_client*>(c);
678 if (client->call != nullptr) {
679 // Throw this grpc_call_unref over to the ExecCtx so that
680 // we invoke it at the bottom of the call stack and
681 // prevent lock inversion problems due to nested ExecCtx flushing.
682 // TODO(apolcyn): we could remove this indirection and call
683 // grpc_call_unref inline if there was an internal variant of
684 // grpc_call_unref that didn't need to flush an ExecCtx.
685 if (grpc_core::ExecCtx::Get() == nullptr) {
686 // Unref handshaker call if there is no exec_ctx, e.g., in the case of
687 // Envoy ALTS transport socket.
688 grpc_call_unref(client->call);
689 } else {
690 // Using existing exec_ctx to unref handshaker call.
691 grpc_core::ExecCtx::Run(
692 DEBUG_LOCATION,
693 GRPC_CLOSURE_CREATE(handshaker_call_unref, client->call,
694 grpc_schedule_on_exec_ctx),
695 absl::OkStatus());
696 }
697 }
698 }
699
700 static const alts_handshaker_client_vtable vtable = {
701 handshaker_client_start_client, handshaker_client_start_server,
702 handshaker_client_next, handshaker_client_shutdown,
703 handshaker_client_destruct};
704
705 alts_handshaker_client* alts_grpc_handshaker_client_create(
706 alts_tsi_handshaker* handshaker, grpc_channel* channel,
707 const char* handshaker_service_url, grpc_pollset_set* interested_parties,
708 grpc_alts_credentials_options* options, const grpc_slice& target_name,
709 grpc_iomgr_cb_func grpc_cb, tsi_handshaker_on_next_done_cb cb,
710 void* user_data, alts_handshaker_client_vtable* vtable_for_testing,
711 bool is_client, size_t max_frame_size, std::string* error) {
712 if (channel == nullptr || handshaker_service_url == nullptr) {
713 gpr_log(GPR_ERROR, "Invalid arguments to alts_handshaker_client_create()");
714 return nullptr;
715 }
716 alts_grpc_handshaker_client* client = new alts_grpc_handshaker_client();
717 memset(&client->base, 0, sizeof(client->base));
718 client->base.vtable =
719 vtable_for_testing == nullptr ? &vtable : vtable_for_testing;
720 gpr_ref_init(&client->refs, 1);
721 client->handshaker = handshaker;
722 client->grpc_caller = grpc_call_start_batch_and_execute;
723 grpc_metadata_array_init(&client->recv_initial_metadata);
724 client->cb = cb;
725 client->user_data = user_data;
726 client->options = grpc_alts_credentials_options_copy(options);
727 client->target_name = grpc_slice_copy(target_name);
728 client->is_client = is_client;
729 client->recv_bytes = grpc_empty_slice();
730 client->buffer_size = TSI_ALTS_INITIAL_BUFFER_SIZE;
731 client->buffer = static_cast<unsigned char*>(gpr_zalloc(client->buffer_size));
732 client->handshake_status_details = grpc_empty_slice();
733 client->max_frame_size = max_frame_size;
734 client->error = error;
735 grpc_slice slice = grpc_slice_from_copied_string(handshaker_service_url);
736 client->call =
737 strcmp(handshaker_service_url, ALTS_HANDSHAKER_SERVICE_URL_FOR_TESTING) ==
738 0
739 ? nullptr
740 : grpc_channel_create_pollset_set_call(
741 channel, nullptr, GRPC_PROPAGATE_DEFAULTS, interested_parties,
742 grpc_slice_from_static_string(ALTS_SERVICE_METHOD), &slice,
743 grpc_core::Timestamp::InfFuture(), nullptr);
744 grpc_core::CSliceUnref(slice);
745 GRPC_CLOSURE_INIT(&client->on_handshaker_service_resp_recv, grpc_cb, client,
746 grpc_schedule_on_exec_ctx);
747 GRPC_CLOSURE_INIT(&client->on_status_received, on_status_received, client,
748 grpc_schedule_on_exec_ctx);
749 return &client->base;
750 }
751
752 namespace grpc_core {
753 namespace internal {
754
755 void alts_handshaker_client_set_grpc_caller_for_testing(
756 alts_handshaker_client* c, alts_grpc_caller caller) {
757 GPR_ASSERT(c != nullptr && caller != nullptr);
758 alts_grpc_handshaker_client* client =
759 reinterpret_cast<alts_grpc_handshaker_client*>(c);
760 client->grpc_caller = caller;
761 }
762
763 grpc_byte_buffer* alts_handshaker_client_get_send_buffer_for_testing(
764 alts_handshaker_client* c) {
765 GPR_ASSERT(c != nullptr);
766 alts_grpc_handshaker_client* client =
767 reinterpret_cast<alts_grpc_handshaker_client*>(c);
768 return client->send_buffer;
769 }
770
771 grpc_byte_buffer** alts_handshaker_client_get_recv_buffer_addr_for_testing(
772 alts_handshaker_client* c) {
773 GPR_ASSERT(c != nullptr);
774 alts_grpc_handshaker_client* client =
775 reinterpret_cast<alts_grpc_handshaker_client*>(c);
776 return &client->recv_buffer;
777 }
778
779 grpc_metadata_array* alts_handshaker_client_get_initial_metadata_for_testing(
780 alts_handshaker_client* c) {
781 GPR_ASSERT(c != nullptr);
782 alts_grpc_handshaker_client* client =
783 reinterpret_cast<alts_grpc_handshaker_client*>(c);
784 return &client->recv_initial_metadata;
785 }
786
787 void alts_handshaker_client_set_recv_bytes_for_testing(
788 alts_handshaker_client* c, grpc_slice* recv_bytes) {
789 GPR_ASSERT(c != nullptr);
790 alts_grpc_handshaker_client* client =
791 reinterpret_cast<alts_grpc_handshaker_client*>(c);
792 client->recv_bytes = CSliceRef(*recv_bytes);
793 }
794
795 void alts_handshaker_client_set_fields_for_testing(
796 alts_handshaker_client* c, alts_tsi_handshaker* handshaker,
797 tsi_handshaker_on_next_done_cb cb, void* user_data,
798 grpc_byte_buffer* recv_buffer, bool inject_read_failure) {
799 GPR_ASSERT(c != nullptr);
800 alts_grpc_handshaker_client* client =
801 reinterpret_cast<alts_grpc_handshaker_client*>(c);
802 client->handshaker = handshaker;
803 client->cb = cb;
804 client->user_data = user_data;
805 client->recv_buffer = recv_buffer;
806 client->inject_read_failure = inject_read_failure;
807 }
808
809 void alts_handshaker_client_check_fields_for_testing(
810 alts_handshaker_client* c, tsi_handshaker_on_next_done_cb cb,
811 void* user_data, bool has_sent_start_message, grpc_slice* recv_bytes) {
812 GPR_ASSERT(c != nullptr);
813 alts_grpc_handshaker_client* client =
814 reinterpret_cast<alts_grpc_handshaker_client*>(c);
815 GPR_ASSERT(client->cb == cb);
816 GPR_ASSERT(client->user_data == user_data);
817 if (recv_bytes != nullptr) {
818 GPR_ASSERT(grpc_slice_cmp(client->recv_bytes, *recv_bytes) == 0);
819 }
820 GPR_ASSERT(alts_tsi_handshaker_get_has_sent_start_message_for_testing(
821 client->handshaker) == has_sent_start_message);
822 }
823
824 void alts_handshaker_client_set_vtable_for_testing(
825 alts_handshaker_client* c, alts_handshaker_client_vtable* vtable) {
826 GPR_ASSERT(c != nullptr);
827 GPR_ASSERT(vtable != nullptr);
828 alts_grpc_handshaker_client* client =
829 reinterpret_cast<alts_grpc_handshaker_client*>(c);
830 client->base.vtable = vtable;
831 }
832
833 alts_tsi_handshaker* alts_handshaker_client_get_handshaker_for_testing(
834 alts_handshaker_client* c) {
835 GPR_ASSERT(c != nullptr);
836 alts_grpc_handshaker_client* client =
837 reinterpret_cast<alts_grpc_handshaker_client*>(c);
838 return client->handshaker;
839 }
840
841 void alts_handshaker_client_set_cb_for_testing(
842 alts_handshaker_client* c, tsi_handshaker_on_next_done_cb cb) {
843 GPR_ASSERT(c != nullptr);
844 alts_grpc_handshaker_client* client =
845 reinterpret_cast<alts_grpc_handshaker_client*>(c);
846 client->cb = cb;
847 }
848
849 grpc_closure* alts_handshaker_client_get_closure_for_testing(
850 alts_handshaker_client* c) {
851 GPR_ASSERT(c != nullptr);
852 alts_grpc_handshaker_client* client =
853 reinterpret_cast<alts_grpc_handshaker_client*>(c);
854 return &client->on_handshaker_service_resp_recv;
855 }
856
857 void alts_handshaker_client_ref_for_testing(alts_handshaker_client* c) {
858 alts_grpc_handshaker_client* client =
859 reinterpret_cast<alts_grpc_handshaker_client*>(c);
860 gpr_ref(&client->refs);
861 }
862
863 void alts_handshaker_client_on_status_received_for_testing(
864 alts_handshaker_client* c, grpc_status_code status,
865 grpc_error_handle error) {
866 // We first make sure that the handshake queue has been initialized
867 // here because there are tests that use this API that mock out
868 // other parts of the alts_handshaker_client in such a way that the
869 // code path that would normally ensure that the handshake queue
870 // has been initialized isn't taken.
871 gpr_once_init(&g_queued_handshakes_init, DoHandshakeQueuesInit);
872 alts_grpc_handshaker_client* client =
873 reinterpret_cast<alts_grpc_handshaker_client*>(c);
874 client->handshake_status_code = status;
875 client->handshake_status_details = grpc_empty_slice();
876 Closure::Run(DEBUG_LOCATION, &client->on_status_received, error);
877 }
878
879 } // namespace internal
880 } // namespace grpc_core
881
882 tsi_result alts_handshaker_client_start_client(alts_handshaker_client* client) {
883 if (client != nullptr && client->vtable != nullptr &&
884 client->vtable->client_start != nullptr) {
885 return client->vtable->client_start(client);
886 }
887 gpr_log(GPR_ERROR,
888 "client or client->vtable has not been initialized properly");
889 return TSI_INVALID_ARGUMENT;
890 }
891
892 tsi_result alts_handshaker_client_start_server(alts_handshaker_client* client,
893 grpc_slice* bytes_received) {
894 if (client != nullptr && client->vtable != nullptr &&
895 client->vtable->server_start != nullptr) {
896 return client->vtable->server_start(client, bytes_received);
897 }
898 gpr_log(GPR_ERROR,
899 "client or client->vtable has not been initialized properly");
900 return TSI_INVALID_ARGUMENT;
901 }
902
903 tsi_result alts_handshaker_client_next(alts_handshaker_client* client,
904 grpc_slice* bytes_received) {
905 if (client != nullptr && client->vtable != nullptr &&
906 client->vtable->next != nullptr) {
907 return client->vtable->next(client, bytes_received);
908 }
909 gpr_log(GPR_ERROR,
910 "client or client->vtable has not been initialized properly");
911 return TSI_INVALID_ARGUMENT;
912 }
913
914 void alts_handshaker_client_shutdown(alts_handshaker_client* client) {
915 if (client != nullptr && client->vtable != nullptr &&
916 client->vtable->shutdown != nullptr) {
917 client->vtable->shutdown(client);
918 }
919 }
920
921 void alts_handshaker_client_destroy(alts_handshaker_client* c) {
922 if (c != nullptr) {
923 alts_grpc_handshaker_client* client =
924 reinterpret_cast<alts_grpc_handshaker_client*>(c);
925 alts_grpc_handshaker_client_unref(client);
926 }
927 }