Imported Upstream version 1.36.0
[platform/upstream/grpc.git] / src / core / tsi / fake_transport_security.cc
1 /*
2  *
3  * Copyright 2015 gRPC authors.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18
19 #include <grpc/support/port_platform.h>
20
21 #include "src/core/tsi/fake_transport_security.h"
22
23 #include <stdlib.h>
24 #include <string.h>
25
26 #include <grpc/support/alloc.h>
27 #include <grpc/support/log.h>
28
29 #include "src/core/lib/gpr/useful.h"
30 #include "src/core/lib/slice/slice_internal.h"
31 #include "src/core/tsi/transport_security_grpc.h"
32
33 /* --- Constants. ---*/
34 #define TSI_FAKE_FRAME_HEADER_SIZE 4
35 #define TSI_FAKE_FRAME_INITIAL_ALLOCATED_SIZE 64
36 #define TSI_FAKE_DEFAULT_FRAME_SIZE 16384
37 #define TSI_FAKE_HANDSHAKER_OUTGOING_BUFFER_INITIAL_SIZE 256
38
39 /* --- Structure definitions. ---*/
40
41 /* a frame is encoded like this:
42    | size |     data    |
43    where the size field value is the size of the size field plus the size of
44    the data encoded in little endian on 4 bytes.  */
45 struct tsi_fake_frame {
46   unsigned char* data;
47   size_t size;
48   size_t allocated_size;
49   size_t offset;
50   int needs_draining;
51 };
52 typedef enum {
53   TSI_FAKE_CLIENT_INIT = 0,
54   TSI_FAKE_SERVER_INIT = 1,
55   TSI_FAKE_CLIENT_FINISHED = 2,
56   TSI_FAKE_SERVER_FINISHED = 3,
57   TSI_FAKE_HANDSHAKE_MESSAGE_MAX = 4
58 } tsi_fake_handshake_message;
59
60 struct tsi_fake_handshaker {
61   tsi_handshaker base;
62   int is_client;
63   tsi_fake_handshake_message next_message_to_send;
64   int needs_incoming_message;
65   tsi_fake_frame incoming_frame;
66   tsi_fake_frame outgoing_frame;
67   unsigned char* outgoing_bytes_buffer;
68   size_t outgoing_bytes_buffer_size;
69   tsi_result result;
70 };
71 struct tsi_fake_frame_protector {
72   tsi_frame_protector base;
73   tsi_fake_frame protect_frame;
74   tsi_fake_frame unprotect_frame;
75   size_t max_frame_size;
76 };
77 struct tsi_fake_zero_copy_grpc_protector {
78   tsi_zero_copy_grpc_protector base;
79   grpc_slice_buffer header_sb;
80   grpc_slice_buffer protected_sb;
81   size_t max_frame_size;
82   size_t parsed_frame_size;
83 };
84 /* --- Utils. ---*/
85
86 static const char* tsi_fake_handshake_message_strings[] = {
87     "CLIENT_INIT", "SERVER_INIT", "CLIENT_FINISHED", "SERVER_FINISHED"};
88
89 static const char* tsi_fake_handshake_message_to_string(int msg) {
90   if (msg < 0 || msg >= TSI_FAKE_HANDSHAKE_MESSAGE_MAX) {
91     gpr_log(GPR_ERROR, "Invalid message %d", msg);
92     return "UNKNOWN";
93   }
94   return tsi_fake_handshake_message_strings[msg];
95 }
96
97 static tsi_result tsi_fake_handshake_message_from_string(
98     const char* msg_string, tsi_fake_handshake_message* msg) {
99   for (int i = 0; i < TSI_FAKE_HANDSHAKE_MESSAGE_MAX; i++) {
100     if (strncmp(msg_string, tsi_fake_handshake_message_strings[i],
101                 strlen(tsi_fake_handshake_message_strings[i])) == 0) {
102       *msg = static_cast<tsi_fake_handshake_message>(i);
103       return TSI_OK;
104     }
105   }
106   gpr_log(GPR_ERROR, "Invalid handshake message.");
107   return TSI_DATA_CORRUPTED;
108 }
109
110 static uint32_t load32_little_endian(const unsigned char* buf) {
111   return (static_cast<uint32_t>(buf[0]) | static_cast<uint32_t>(buf[1] << 8) |
112           static_cast<uint32_t>(buf[2] << 16) |
113           static_cast<uint32_t>(buf[3] << 24));
114 }
115
116 static void store32_little_endian(uint32_t value, unsigned char* buf) {
117   buf[3] = static_cast<unsigned char>((value >> 24) & 0xFF);
118   buf[2] = static_cast<unsigned char>((value >> 16) & 0xFF);
119   buf[1] = static_cast<unsigned char>((value >> 8) & 0xFF);
120   buf[0] = static_cast<unsigned char>((value)&0xFF);
121 }
122
123 static uint32_t read_frame_size(const grpc_slice_buffer* sb) {
124   GPR_ASSERT(sb != nullptr && sb->length >= TSI_FAKE_FRAME_HEADER_SIZE);
125   uint8_t frame_size_buffer[TSI_FAKE_FRAME_HEADER_SIZE];
126   uint8_t* buf = frame_size_buffer;
127   /* Copies the first 4 bytes to a temporary buffer.  */
128   size_t remaining = TSI_FAKE_FRAME_HEADER_SIZE;
129   for (size_t i = 0; i < sb->count; i++) {
130     size_t slice_length = GRPC_SLICE_LENGTH(sb->slices[i]);
131     if (remaining <= slice_length) {
132       memcpy(buf, GRPC_SLICE_START_PTR(sb->slices[i]), remaining);
133       remaining = 0;
134       break;
135     } else {
136       memcpy(buf, GRPC_SLICE_START_PTR(sb->slices[i]), slice_length);
137       buf += slice_length;
138       remaining -= slice_length;
139     }
140   }
141   GPR_ASSERT(remaining == 0);
142   return load32_little_endian(frame_size_buffer);
143 }
144
145 static void tsi_fake_frame_reset(tsi_fake_frame* frame, int needs_draining) {
146   frame->offset = 0;
147   frame->needs_draining = needs_draining;
148   if (!needs_draining) frame->size = 0;
149 }
150
151 /* Checks if the frame's allocated size is at least frame->size, and reallocs
152  * more memory if necessary. */
153 static void tsi_fake_frame_ensure_size(tsi_fake_frame* frame) {
154   if (frame->data == nullptr) {
155     frame->allocated_size = frame->size;
156     frame->data =
157         static_cast<unsigned char*>(gpr_malloc(frame->allocated_size));
158   } else if (frame->size > frame->allocated_size) {
159     unsigned char* new_data =
160         static_cast<unsigned char*>(gpr_realloc(frame->data, frame->size));
161     frame->data = new_data;
162     frame->allocated_size = frame->size;
163   }
164 }
165
166 /* Decodes the serialized fake frame contained in incoming_bytes, and fills
167  * frame with the contents of the decoded frame.
168  * This method should not be called if frame->needs_framing is not 0.  */
169 static tsi_result tsi_fake_frame_decode(const unsigned char* incoming_bytes,
170                                         size_t* incoming_bytes_size,
171                                         tsi_fake_frame* frame) {
172   size_t available_size = *incoming_bytes_size;
173   size_t to_read_size = 0;
174   const unsigned char* bytes_cursor = incoming_bytes;
175
176   if (frame->needs_draining) return TSI_INTERNAL_ERROR;
177   if (frame->data == nullptr) {
178     frame->allocated_size = TSI_FAKE_FRAME_INITIAL_ALLOCATED_SIZE;
179     frame->data =
180         static_cast<unsigned char*>(gpr_malloc(frame->allocated_size));
181   }
182
183   if (frame->offset < TSI_FAKE_FRAME_HEADER_SIZE) {
184     to_read_size = TSI_FAKE_FRAME_HEADER_SIZE - frame->offset;
185     if (to_read_size > available_size) {
186       /* Just fill what we can and exit. */
187       memcpy(frame->data + frame->offset, bytes_cursor, available_size);
188       bytes_cursor += available_size;
189       frame->offset += available_size;
190       *incoming_bytes_size = static_cast<size_t>(bytes_cursor - incoming_bytes);
191       return TSI_INCOMPLETE_DATA;
192     }
193     memcpy(frame->data + frame->offset, bytes_cursor, to_read_size);
194     bytes_cursor += to_read_size;
195     frame->offset += to_read_size;
196     available_size -= to_read_size;
197     frame->size = load32_little_endian(frame->data);
198     tsi_fake_frame_ensure_size(frame);
199   }
200
201   to_read_size = frame->size - frame->offset;
202   if (to_read_size > available_size) {
203     memcpy(frame->data + frame->offset, bytes_cursor, available_size);
204     frame->offset += available_size;
205     bytes_cursor += available_size;
206     *incoming_bytes_size = static_cast<size_t>(bytes_cursor - incoming_bytes);
207     return TSI_INCOMPLETE_DATA;
208   }
209   memcpy(frame->data + frame->offset, bytes_cursor, to_read_size);
210   bytes_cursor += to_read_size;
211   *incoming_bytes_size = static_cast<size_t>(bytes_cursor - incoming_bytes);
212   tsi_fake_frame_reset(frame, 1 /* needs_draining */);
213   return TSI_OK;
214 }
215
216 /* Encodes a fake frame into its wire format and places the result in
217  * outgoing_bytes. outgoing_bytes_size indicates the size of the encoded frame.
218  * This method should not be called if frame->needs_framing is 0.  */
219 static tsi_result tsi_fake_frame_encode(unsigned char* outgoing_bytes,
220                                         size_t* outgoing_bytes_size,
221                                         tsi_fake_frame* frame) {
222   size_t to_write_size = frame->size - frame->offset;
223   if (!frame->needs_draining) return TSI_INTERNAL_ERROR;
224   if (*outgoing_bytes_size < to_write_size) {
225     memcpy(outgoing_bytes, frame->data + frame->offset, *outgoing_bytes_size);
226     frame->offset += *outgoing_bytes_size;
227     return TSI_INCOMPLETE_DATA;
228   }
229   memcpy(outgoing_bytes, frame->data + frame->offset, to_write_size);
230   *outgoing_bytes_size = to_write_size;
231   tsi_fake_frame_reset(frame, 0 /* needs_draining */);
232   return TSI_OK;
233 }
234
235 /* Sets the payload of a fake frame to contain the given data blob, where
236  * data_size indicates the size of data. */
237 static tsi_result tsi_fake_frame_set_data(unsigned char* data, size_t data_size,
238                                           tsi_fake_frame* frame) {
239   frame->offset = 0;
240   frame->size = data_size + TSI_FAKE_FRAME_HEADER_SIZE;
241   tsi_fake_frame_ensure_size(frame);
242   store32_little_endian(static_cast<uint32_t>(frame->size), frame->data);
243   memcpy(frame->data + TSI_FAKE_FRAME_HEADER_SIZE, data, data_size);
244   tsi_fake_frame_reset(frame, 1 /* needs draining */);
245   return TSI_OK;
246 }
247
248 /* Destroys the contents of a fake frame. */
249 static void tsi_fake_frame_destruct(tsi_fake_frame* frame) {
250   if (frame->data != nullptr) gpr_free(frame->data);
251 }
252
253 /* --- tsi_frame_protector methods implementation. ---*/
254
255 static tsi_result fake_protector_protect(tsi_frame_protector* self,
256                                          const unsigned char* unprotected_bytes,
257                                          size_t* unprotected_bytes_size,
258                                          unsigned char* protected_output_frames,
259                                          size_t* protected_output_frames_size) {
260   tsi_result result = TSI_OK;
261   tsi_fake_frame_protector* impl =
262       reinterpret_cast<tsi_fake_frame_protector*>(self);
263   unsigned char frame_header[TSI_FAKE_FRAME_HEADER_SIZE];
264   tsi_fake_frame* frame = &impl->protect_frame;
265   size_t saved_output_size = *protected_output_frames_size;
266   size_t drained_size = 0;
267   size_t* num_bytes_written = protected_output_frames_size;
268   *num_bytes_written = 0;
269
270   /* Try to drain first. */
271   if (frame->needs_draining) {
272     drained_size = saved_output_size - *num_bytes_written;
273     result =
274         tsi_fake_frame_encode(protected_output_frames, &drained_size, frame);
275     *num_bytes_written += drained_size;
276     protected_output_frames += drained_size;
277     if (result != TSI_OK) {
278       if (result == TSI_INCOMPLETE_DATA) {
279         *unprotected_bytes_size = 0;
280         result = TSI_OK;
281       }
282       return result;
283     }
284   }
285
286   /* Now process the unprotected_bytes. */
287   if (frame->needs_draining) return TSI_INTERNAL_ERROR;
288   if (frame->size == 0) {
289     /* New frame, create a header. */
290     size_t written_in_frame_size = 0;
291     store32_little_endian(static_cast<uint32_t>(impl->max_frame_size),
292                           frame_header);
293     written_in_frame_size = TSI_FAKE_FRAME_HEADER_SIZE;
294     result = tsi_fake_frame_decode(frame_header, &written_in_frame_size, frame);
295     if (result != TSI_INCOMPLETE_DATA) {
296       gpr_log(GPR_ERROR, "tsi_fake_frame_decode returned %s",
297               tsi_result_to_string(result));
298       return result;
299     }
300   }
301   result =
302       tsi_fake_frame_decode(unprotected_bytes, unprotected_bytes_size, frame);
303   if (result != TSI_OK) {
304     if (result == TSI_INCOMPLETE_DATA) result = TSI_OK;
305     return result;
306   }
307
308   /* Try to drain again. */
309   if (!frame->needs_draining) return TSI_INTERNAL_ERROR;
310   if (frame->offset != 0) return TSI_INTERNAL_ERROR;
311   drained_size = saved_output_size - *num_bytes_written;
312   result = tsi_fake_frame_encode(protected_output_frames, &drained_size, frame);
313   *num_bytes_written += drained_size;
314   if (result == TSI_INCOMPLETE_DATA) result = TSI_OK;
315   return result;
316 }
317
318 static tsi_result fake_protector_protect_flush(
319     tsi_frame_protector* self, unsigned char* protected_output_frames,
320     size_t* protected_output_frames_size, size_t* still_pending_size) {
321   tsi_result result = TSI_OK;
322   tsi_fake_frame_protector* impl =
323       reinterpret_cast<tsi_fake_frame_protector*>(self);
324   tsi_fake_frame* frame = &impl->protect_frame;
325   if (!frame->needs_draining) {
326     /* Create a short frame. */
327     frame->size = frame->offset;
328     frame->offset = 0;
329     frame->needs_draining = 1;
330     store32_little_endian(static_cast<uint32_t>(frame->size),
331                           frame->data); /* Overwrite header. */
332   }
333   result = tsi_fake_frame_encode(protected_output_frames,
334                                  protected_output_frames_size, frame);
335   if (result == TSI_INCOMPLETE_DATA) result = TSI_OK;
336   *still_pending_size = frame->size - frame->offset;
337   return result;
338 }
339
340 static tsi_result fake_protector_unprotect(
341     tsi_frame_protector* self, const unsigned char* protected_frames_bytes,
342     size_t* protected_frames_bytes_size, unsigned char* unprotected_bytes,
343     size_t* unprotected_bytes_size) {
344   tsi_result result = TSI_OK;
345   tsi_fake_frame_protector* impl =
346       reinterpret_cast<tsi_fake_frame_protector*>(self);
347   tsi_fake_frame* frame = &impl->unprotect_frame;
348   size_t saved_output_size = *unprotected_bytes_size;
349   size_t drained_size = 0;
350   size_t* num_bytes_written = unprotected_bytes_size;
351   *num_bytes_written = 0;
352
353   /* Try to drain first. */
354   if (frame->needs_draining) {
355     /* Go past the header if needed. */
356     if (frame->offset == 0) frame->offset = TSI_FAKE_FRAME_HEADER_SIZE;
357     drained_size = saved_output_size - *num_bytes_written;
358     result = tsi_fake_frame_encode(unprotected_bytes, &drained_size, frame);
359     unprotected_bytes += drained_size;
360     *num_bytes_written += drained_size;
361     if (result != TSI_OK) {
362       if (result == TSI_INCOMPLETE_DATA) {
363         *protected_frames_bytes_size = 0;
364         result = TSI_OK;
365       }
366       return result;
367     }
368   }
369
370   /* Now process the protected_bytes. */
371   if (frame->needs_draining) return TSI_INTERNAL_ERROR;
372   result = tsi_fake_frame_decode(protected_frames_bytes,
373                                  protected_frames_bytes_size, frame);
374   if (result != TSI_OK) {
375     if (result == TSI_INCOMPLETE_DATA) result = TSI_OK;
376     return result;
377   }
378
379   /* Try to drain again. */
380   if (!frame->needs_draining) return TSI_INTERNAL_ERROR;
381   if (frame->offset != 0) return TSI_INTERNAL_ERROR;
382   frame->offset = TSI_FAKE_FRAME_HEADER_SIZE; /* Go past the header. */
383   drained_size = saved_output_size - *num_bytes_written;
384   result = tsi_fake_frame_encode(unprotected_bytes, &drained_size, frame);
385   *num_bytes_written += drained_size;
386   if (result == TSI_INCOMPLETE_DATA) result = TSI_OK;
387   return result;
388 }
389
390 static void fake_protector_destroy(tsi_frame_protector* self) {
391   tsi_fake_frame_protector* impl =
392       reinterpret_cast<tsi_fake_frame_protector*>(self);
393   tsi_fake_frame_destruct(&impl->protect_frame);
394   tsi_fake_frame_destruct(&impl->unprotect_frame);
395   gpr_free(self);
396 }
397
398 static const tsi_frame_protector_vtable frame_protector_vtable = {
399     fake_protector_protect,
400     fake_protector_protect_flush,
401     fake_protector_unprotect,
402     fake_protector_destroy,
403 };
404
405 /* --- tsi_zero_copy_grpc_protector methods implementation. ---*/
406
407 static tsi_result fake_zero_copy_grpc_protector_protect(
408     tsi_zero_copy_grpc_protector* self, grpc_slice_buffer* unprotected_slices,
409     grpc_slice_buffer* protected_slices) {
410   if (self == nullptr || unprotected_slices == nullptr ||
411       protected_slices == nullptr) {
412     return TSI_INVALID_ARGUMENT;
413   }
414   tsi_fake_zero_copy_grpc_protector* impl =
415       reinterpret_cast<tsi_fake_zero_copy_grpc_protector*>(self);
416   /* Protects each frame. */
417   while (unprotected_slices->length > 0) {
418     size_t frame_length =
419         GPR_MIN(impl->max_frame_size,
420                 unprotected_slices->length + TSI_FAKE_FRAME_HEADER_SIZE);
421     grpc_slice slice = GRPC_SLICE_MALLOC(TSI_FAKE_FRAME_HEADER_SIZE);
422     store32_little_endian(static_cast<uint32_t>(frame_length),
423                           GRPC_SLICE_START_PTR(slice));
424     grpc_slice_buffer_add(protected_slices, slice);
425     size_t data_length = frame_length - TSI_FAKE_FRAME_HEADER_SIZE;
426     grpc_slice_buffer_move_first(unprotected_slices, data_length,
427                                  protected_slices);
428   }
429   return TSI_OK;
430 }
431
432 static tsi_result fake_zero_copy_grpc_protector_unprotect(
433     tsi_zero_copy_grpc_protector* self, grpc_slice_buffer* protected_slices,
434     grpc_slice_buffer* unprotected_slices) {
435   if (self == nullptr || unprotected_slices == nullptr ||
436       protected_slices == nullptr) {
437     return TSI_INVALID_ARGUMENT;
438   }
439   tsi_fake_zero_copy_grpc_protector* impl =
440       reinterpret_cast<tsi_fake_zero_copy_grpc_protector*>(self);
441   grpc_slice_buffer_move_into(protected_slices, &impl->protected_sb);
442   /* Unprotect each frame, if we get a full frame. */
443   while (impl->protected_sb.length >= TSI_FAKE_FRAME_HEADER_SIZE) {
444     if (impl->parsed_frame_size == 0) {
445       impl->parsed_frame_size = read_frame_size(&impl->protected_sb);
446       if (impl->parsed_frame_size <= 4) {
447         gpr_log(GPR_ERROR, "Invalid frame size.");
448         return TSI_DATA_CORRUPTED;
449       }
450     }
451     /* If we do not have a full frame, return with OK status. */
452     if (impl->protected_sb.length < impl->parsed_frame_size) break;
453     /* Strips header bytes. */
454     grpc_slice_buffer_move_first(&impl->protected_sb,
455                                  TSI_FAKE_FRAME_HEADER_SIZE, &impl->header_sb);
456     /* Moves data to unprotected slices. */
457     grpc_slice_buffer_move_first(
458         &impl->protected_sb,
459         impl->parsed_frame_size - TSI_FAKE_FRAME_HEADER_SIZE,
460         unprotected_slices);
461     impl->parsed_frame_size = 0;
462     grpc_slice_buffer_reset_and_unref_internal(&impl->header_sb);
463   }
464   return TSI_OK;
465 }
466
467 static void fake_zero_copy_grpc_protector_destroy(
468     tsi_zero_copy_grpc_protector* self) {
469   if (self == nullptr) return;
470   tsi_fake_zero_copy_grpc_protector* impl =
471       reinterpret_cast<tsi_fake_zero_copy_grpc_protector*>(self);
472   grpc_slice_buffer_destroy_internal(&impl->header_sb);
473   grpc_slice_buffer_destroy_internal(&impl->protected_sb);
474   gpr_free(impl);
475 }
476
477 static const tsi_zero_copy_grpc_protector_vtable
478     zero_copy_grpc_protector_vtable = {
479         fake_zero_copy_grpc_protector_protect,
480         fake_zero_copy_grpc_protector_unprotect,
481         fake_zero_copy_grpc_protector_destroy,
482         nullptr /* fake_zero_copy_grpc_protector_max_frame_size */
483 };
484
485 /* --- tsi_handshaker_result methods implementation. ---*/
486
487 struct fake_handshaker_result {
488   tsi_handshaker_result base;
489   unsigned char* unused_bytes;
490   size_t unused_bytes_size;
491 };
492 static tsi_result fake_handshaker_result_extract_peer(
493     const tsi_handshaker_result* /*self*/, tsi_peer* peer) {
494   /* Construct a tsi_peer with 1 property: certificate type, security_level. */
495   tsi_result result = tsi_construct_peer(2, peer);
496   if (result != TSI_OK) return result;
497   result = tsi_construct_string_peer_property_from_cstring(
498       TSI_CERTIFICATE_TYPE_PEER_PROPERTY, TSI_FAKE_CERTIFICATE_TYPE,
499       &peer->properties[0]);
500   if (result != TSI_OK) tsi_peer_destruct(peer);
501   result = tsi_construct_string_peer_property_from_cstring(
502       TSI_SECURITY_LEVEL_PEER_PROPERTY,
503       tsi_security_level_to_string(TSI_SECURITY_NONE), &peer->properties[1]);
504   if (result != TSI_OK) tsi_peer_destruct(peer);
505   return result;
506 }
507
508 static tsi_result fake_handshaker_result_create_zero_copy_grpc_protector(
509     const tsi_handshaker_result* /*self*/,
510     size_t* max_output_protected_frame_size,
511     tsi_zero_copy_grpc_protector** protector) {
512   *protector =
513       tsi_create_fake_zero_copy_grpc_protector(max_output_protected_frame_size);
514   return TSI_OK;
515 }
516
517 static tsi_result fake_handshaker_result_create_frame_protector(
518     const tsi_handshaker_result* /*self*/,
519     size_t* max_output_protected_frame_size, tsi_frame_protector** protector) {
520   *protector = tsi_create_fake_frame_protector(max_output_protected_frame_size);
521   return TSI_OK;
522 }
523
524 static tsi_result fake_handshaker_result_get_unused_bytes(
525     const tsi_handshaker_result* self, const unsigned char** bytes,
526     size_t* bytes_size) {
527   fake_handshaker_result* result = reinterpret_cast<fake_handshaker_result*>(
528       const_cast<tsi_handshaker_result*>(self));
529   *bytes_size = result->unused_bytes_size;
530   *bytes = result->unused_bytes;
531   return TSI_OK;
532 }
533
534 static void fake_handshaker_result_destroy(tsi_handshaker_result* self) {
535   fake_handshaker_result* result =
536       reinterpret_cast<fake_handshaker_result*>(self);
537   gpr_free(result->unused_bytes);
538   gpr_free(self);
539 }
540
541 static const tsi_handshaker_result_vtable handshaker_result_vtable = {
542     fake_handshaker_result_extract_peer,
543     fake_handshaker_result_create_zero_copy_grpc_protector,
544     fake_handshaker_result_create_frame_protector,
545     fake_handshaker_result_get_unused_bytes,
546     fake_handshaker_result_destroy,
547 };
548
549 static tsi_result fake_handshaker_result_create(
550     const unsigned char* unused_bytes, size_t unused_bytes_size,
551     tsi_handshaker_result** handshaker_result) {
552   if ((unused_bytes_size > 0 && unused_bytes == nullptr) ||
553       handshaker_result == nullptr) {
554     return TSI_INVALID_ARGUMENT;
555   }
556   fake_handshaker_result* result =
557       static_cast<fake_handshaker_result*>(gpr_zalloc(sizeof(*result)));
558   result->base.vtable = &handshaker_result_vtable;
559   if (unused_bytes_size > 0) {
560     result->unused_bytes =
561         static_cast<unsigned char*>(gpr_malloc(unused_bytes_size));
562     memcpy(result->unused_bytes, unused_bytes, unused_bytes_size);
563   }
564   result->unused_bytes_size = unused_bytes_size;
565   *handshaker_result = &result->base;
566   return TSI_OK;
567 }
568
569 /* --- tsi_handshaker methods implementation. ---*/
570
571 static tsi_result fake_handshaker_get_bytes_to_send_to_peer(
572     tsi_handshaker* self, unsigned char* bytes, size_t* bytes_size) {
573   tsi_fake_handshaker* impl = reinterpret_cast<tsi_fake_handshaker*>(self);
574   tsi_result result = TSI_OK;
575   if (impl->needs_incoming_message || impl->result == TSI_OK) {
576     *bytes_size = 0;
577     return TSI_OK;
578   }
579   if (!impl->outgoing_frame.needs_draining) {
580     tsi_fake_handshake_message next_message_to_send =
581         // NOLINTNEXTLINE(bugprone-misplaced-widening-cast)
582         static_cast<tsi_fake_handshake_message>(impl->next_message_to_send + 2);
583     const char* msg_string =
584         tsi_fake_handshake_message_to_string(impl->next_message_to_send);
585     result = tsi_fake_frame_set_data(
586         reinterpret_cast<unsigned char*>(const_cast<char*>(msg_string)),
587         strlen(msg_string), &impl->outgoing_frame);
588     if (result != TSI_OK) return result;
589     if (next_message_to_send > TSI_FAKE_HANDSHAKE_MESSAGE_MAX) {
590       next_message_to_send = TSI_FAKE_HANDSHAKE_MESSAGE_MAX;
591     }
592     if (GRPC_TRACE_FLAG_ENABLED(tsi_tracing_enabled)) {
593       gpr_log(GPR_INFO, "%s prepared %s.",
594               impl->is_client ? "Client" : "Server",
595               tsi_fake_handshake_message_to_string(impl->next_message_to_send));
596     }
597     impl->next_message_to_send = next_message_to_send;
598   }
599   result = tsi_fake_frame_encode(bytes, bytes_size, &impl->outgoing_frame);
600   if (result != TSI_OK) return result;
601   if (!impl->is_client &&
602       impl->next_message_to_send == TSI_FAKE_HANDSHAKE_MESSAGE_MAX) {
603     /* We're done. */
604     if (GRPC_TRACE_FLAG_ENABLED(tsi_tracing_enabled)) {
605       gpr_log(GPR_INFO, "Server is done.");
606     }
607     impl->result = TSI_OK;
608   } else {
609     impl->needs_incoming_message = 1;
610   }
611   return TSI_OK;
612 }
613
614 static tsi_result fake_handshaker_process_bytes_from_peer(
615     tsi_handshaker* self, const unsigned char* bytes, size_t* bytes_size) {
616   tsi_result result = TSI_OK;
617   tsi_fake_handshaker* impl = reinterpret_cast<tsi_fake_handshaker*>(self);
618   tsi_fake_handshake_message expected_msg =
619       static_cast<tsi_fake_handshake_message>(impl->next_message_to_send - 1);
620   tsi_fake_handshake_message received_msg;
621
622   if (!impl->needs_incoming_message || impl->result == TSI_OK) {
623     *bytes_size = 0;
624     return TSI_OK;
625   }
626   result = tsi_fake_frame_decode(bytes, bytes_size, &impl->incoming_frame);
627   if (result != TSI_OK) return result;
628
629   /* We now have a complete frame. */
630   result = tsi_fake_handshake_message_from_string(
631       reinterpret_cast<const char*>(impl->incoming_frame.data) +
632           TSI_FAKE_FRAME_HEADER_SIZE,
633       &received_msg);
634   if (result != TSI_OK) {
635     impl->result = result;
636     return result;
637   }
638   if (received_msg != expected_msg) {
639     gpr_log(GPR_ERROR, "Invalid received message (%s instead of %s)",
640             tsi_fake_handshake_message_to_string(received_msg),
641             tsi_fake_handshake_message_to_string(expected_msg));
642   }
643   if (GRPC_TRACE_FLAG_ENABLED(tsi_tracing_enabled)) {
644     gpr_log(GPR_INFO, "%s received %s.", impl->is_client ? "Client" : "Server",
645             tsi_fake_handshake_message_to_string(received_msg));
646   }
647   tsi_fake_frame_reset(&impl->incoming_frame, 0 /* needs_draining */);
648   impl->needs_incoming_message = 0;
649   if (impl->next_message_to_send == TSI_FAKE_HANDSHAKE_MESSAGE_MAX) {
650     /* We're done. */
651     if (GRPC_TRACE_FLAG_ENABLED(tsi_tracing_enabled)) {
652       gpr_log(GPR_INFO, "%s is done.", impl->is_client ? "Client" : "Server");
653     }
654     impl->result = TSI_OK;
655   }
656   return TSI_OK;
657 }
658
659 static tsi_result fake_handshaker_get_result(tsi_handshaker* self) {
660   tsi_fake_handshaker* impl = reinterpret_cast<tsi_fake_handshaker*>(self);
661   return impl->result;
662 }
663
664 static void fake_handshaker_destroy(tsi_handshaker* self) {
665   tsi_fake_handshaker* impl = reinterpret_cast<tsi_fake_handshaker*>(self);
666   tsi_fake_frame_destruct(&impl->incoming_frame);
667   tsi_fake_frame_destruct(&impl->outgoing_frame);
668   gpr_free(impl->outgoing_bytes_buffer);
669   gpr_free(self);
670 }
671
672 static tsi_result fake_handshaker_next(
673     tsi_handshaker* self, const unsigned char* received_bytes,
674     size_t received_bytes_size, const unsigned char** bytes_to_send,
675     size_t* bytes_to_send_size, tsi_handshaker_result** handshaker_result,
676     tsi_handshaker_on_next_done_cb /*cb*/, void* /*user_data*/) {
677   /* Sanity check the arguments. */
678   if ((received_bytes_size > 0 && received_bytes == nullptr) ||
679       bytes_to_send == nullptr || bytes_to_send_size == nullptr ||
680       handshaker_result == nullptr) {
681     return TSI_INVALID_ARGUMENT;
682   }
683   tsi_fake_handshaker* handshaker =
684       reinterpret_cast<tsi_fake_handshaker*>(self);
685   tsi_result result = TSI_OK;
686
687   /* Decode and process a handshake frame from the peer. */
688   size_t consumed_bytes_size = received_bytes_size;
689   if (received_bytes_size > 0) {
690     result = fake_handshaker_process_bytes_from_peer(self, received_bytes,
691                                                      &consumed_bytes_size);
692     if (result != TSI_OK) return result;
693   }
694
695   /* Create a handshake message to send to the peer and encode it as a fake
696    * frame. */
697   size_t offset = 0;
698   do {
699     size_t sent_bytes_size = handshaker->outgoing_bytes_buffer_size - offset;
700     result = fake_handshaker_get_bytes_to_send_to_peer(
701         self, handshaker->outgoing_bytes_buffer + offset, &sent_bytes_size);
702     offset += sent_bytes_size;
703     if (result == TSI_INCOMPLETE_DATA) {
704       handshaker->outgoing_bytes_buffer_size *= 2;
705       handshaker->outgoing_bytes_buffer = static_cast<unsigned char*>(
706           gpr_realloc(handshaker->outgoing_bytes_buffer,
707                       handshaker->outgoing_bytes_buffer_size));
708     }
709   } while (result == TSI_INCOMPLETE_DATA);
710   if (result != TSI_OK) return result;
711   *bytes_to_send = handshaker->outgoing_bytes_buffer;
712   *bytes_to_send_size = offset;
713
714   /* Check if the handshake was completed. */
715   if (fake_handshaker_get_result(self) == TSI_HANDSHAKE_IN_PROGRESS) {
716     *handshaker_result = nullptr;
717   } else {
718     /* Calculate the unused bytes. */
719     const unsigned char* unused_bytes = nullptr;
720     size_t unused_bytes_size = received_bytes_size - consumed_bytes_size;
721     if (unused_bytes_size > 0) {
722       unused_bytes = received_bytes + consumed_bytes_size;
723     }
724
725     /* Create a handshaker_result containing the unused bytes. */
726     result = fake_handshaker_result_create(unused_bytes, unused_bytes_size,
727                                            handshaker_result);
728     if (result == TSI_OK) {
729       /* Indicate that the handshake has completed and that a handshaker_result
730        * has been created. */
731       self->handshaker_result_created = true;
732     }
733   }
734   return result;
735 }
736
737 static const tsi_handshaker_vtable handshaker_vtable = {
738     nullptr, /* get_bytes_to_send_to_peer -- deprecated */
739     nullptr, /* process_bytes_from_peer   -- deprecated */
740     nullptr, /* get_result                -- deprecated */
741     nullptr, /* extract_peer              -- deprecated */
742     nullptr, /* create_frame_protector    -- deprecated */
743     fake_handshaker_destroy,
744     fake_handshaker_next,
745     nullptr, /* shutdown */
746 };
747
748 tsi_handshaker* tsi_create_fake_handshaker(int is_client) {
749   tsi_fake_handshaker* impl =
750       static_cast<tsi_fake_handshaker*>(gpr_zalloc(sizeof(*impl)));
751   impl->base.vtable = &handshaker_vtable;
752   impl->is_client = is_client;
753   impl->result = TSI_HANDSHAKE_IN_PROGRESS;
754   impl->outgoing_bytes_buffer_size =
755       TSI_FAKE_HANDSHAKER_OUTGOING_BUFFER_INITIAL_SIZE;
756   impl->outgoing_bytes_buffer =
757       static_cast<unsigned char*>(gpr_malloc(impl->outgoing_bytes_buffer_size));
758   if (is_client) {
759     impl->needs_incoming_message = 0;
760     impl->next_message_to_send = TSI_FAKE_CLIENT_INIT;
761   } else {
762     impl->needs_incoming_message = 1;
763     impl->next_message_to_send = TSI_FAKE_SERVER_INIT;
764   }
765   return &impl->base;
766 }
767
768 tsi_frame_protector* tsi_create_fake_frame_protector(
769     size_t* max_protected_frame_size) {
770   tsi_fake_frame_protector* impl =
771       static_cast<tsi_fake_frame_protector*>(gpr_zalloc(sizeof(*impl)));
772   impl->max_frame_size = (max_protected_frame_size == nullptr)
773                              ? TSI_FAKE_DEFAULT_FRAME_SIZE
774                              : *max_protected_frame_size;
775   impl->base.vtable = &frame_protector_vtable;
776   return &impl->base;
777 }
778
779 tsi_zero_copy_grpc_protector* tsi_create_fake_zero_copy_grpc_protector(
780     size_t* max_protected_frame_size) {
781   tsi_fake_zero_copy_grpc_protector* impl =
782       static_cast<tsi_fake_zero_copy_grpc_protector*>(
783           gpr_zalloc(sizeof(*impl)));
784   grpc_slice_buffer_init(&impl->header_sb);
785   grpc_slice_buffer_init(&impl->protected_sb);
786   impl->max_frame_size = (max_protected_frame_size == nullptr)
787                              ? TSI_FAKE_DEFAULT_FRAME_SIZE
788                              : *max_protected_frame_size;
789   impl->parsed_frame_size = 0;
790   impl->base.vtable = &zero_copy_grpc_protector_vtable;
791   return &impl->base;
792 }