Imported Upstream version 1.33.1
[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 = (fake_handshaker_result*)self;
528   *bytes_size = result->unused_bytes_size;
529   *bytes = result->unused_bytes;
530   return TSI_OK;
531 }
532
533 static void fake_handshaker_result_destroy(tsi_handshaker_result* self) {
534   fake_handshaker_result* result =
535       reinterpret_cast<fake_handshaker_result*>(self);
536   gpr_free(result->unused_bytes);
537   gpr_free(self);
538 }
539
540 static const tsi_handshaker_result_vtable handshaker_result_vtable = {
541     fake_handshaker_result_extract_peer,
542     fake_handshaker_result_create_zero_copy_grpc_protector,
543     fake_handshaker_result_create_frame_protector,
544     fake_handshaker_result_get_unused_bytes,
545     fake_handshaker_result_destroy,
546 };
547
548 static tsi_result fake_handshaker_result_create(
549     const unsigned char* unused_bytes, size_t unused_bytes_size,
550     tsi_handshaker_result** handshaker_result) {
551   if ((unused_bytes_size > 0 && unused_bytes == nullptr) ||
552       handshaker_result == nullptr) {
553     return TSI_INVALID_ARGUMENT;
554   }
555   fake_handshaker_result* result =
556       static_cast<fake_handshaker_result*>(gpr_zalloc(sizeof(*result)));
557   result->base.vtable = &handshaker_result_vtable;
558   if (unused_bytes_size > 0) {
559     result->unused_bytes =
560         static_cast<unsigned char*>(gpr_malloc(unused_bytes_size));
561     memcpy(result->unused_bytes, unused_bytes, unused_bytes_size);
562   }
563   result->unused_bytes_size = unused_bytes_size;
564   *handshaker_result = &result->base;
565   return TSI_OK;
566 }
567
568 /* --- tsi_handshaker methods implementation. ---*/
569
570 static tsi_result fake_handshaker_get_bytes_to_send_to_peer(
571     tsi_handshaker* self, unsigned char* bytes, size_t* bytes_size) {
572   tsi_fake_handshaker* impl = reinterpret_cast<tsi_fake_handshaker*>(self);
573   tsi_result result = TSI_OK;
574   if (impl->needs_incoming_message || impl->result == TSI_OK) {
575     *bytes_size = 0;
576     return TSI_OK;
577   }
578   if (!impl->outgoing_frame.needs_draining) {
579     tsi_fake_handshake_message next_message_to_send =
580         static_cast<tsi_fake_handshake_message>(impl->next_message_to_send + 2);
581     const char* msg_string =
582         tsi_fake_handshake_message_to_string(impl->next_message_to_send);
583     result = tsi_fake_frame_set_data((unsigned char*)msg_string,
584                                      strlen(msg_string), &impl->outgoing_frame);
585     if (result != TSI_OK) return result;
586     if (next_message_to_send > TSI_FAKE_HANDSHAKE_MESSAGE_MAX) {
587       next_message_to_send = TSI_FAKE_HANDSHAKE_MESSAGE_MAX;
588     }
589     if (GRPC_TRACE_FLAG_ENABLED(tsi_tracing_enabled)) {
590       gpr_log(GPR_INFO, "%s prepared %s.",
591               impl->is_client ? "Client" : "Server",
592               tsi_fake_handshake_message_to_string(impl->next_message_to_send));
593     }
594     impl->next_message_to_send = next_message_to_send;
595   }
596   result = tsi_fake_frame_encode(bytes, bytes_size, &impl->outgoing_frame);
597   if (result != TSI_OK) return result;
598   if (!impl->is_client &&
599       impl->next_message_to_send == TSI_FAKE_HANDSHAKE_MESSAGE_MAX) {
600     /* We're done. */
601     if (GRPC_TRACE_FLAG_ENABLED(tsi_tracing_enabled)) {
602       gpr_log(GPR_INFO, "Server is done.");
603     }
604     impl->result = TSI_OK;
605   } else {
606     impl->needs_incoming_message = 1;
607   }
608   return TSI_OK;
609 }
610
611 static tsi_result fake_handshaker_process_bytes_from_peer(
612     tsi_handshaker* self, const unsigned char* bytes, size_t* bytes_size) {
613   tsi_result result = TSI_OK;
614   tsi_fake_handshaker* impl = reinterpret_cast<tsi_fake_handshaker*>(self);
615   tsi_fake_handshake_message expected_msg =
616       static_cast<tsi_fake_handshake_message>(impl->next_message_to_send - 1);
617   tsi_fake_handshake_message received_msg;
618
619   if (!impl->needs_incoming_message || impl->result == TSI_OK) {
620     *bytes_size = 0;
621     return TSI_OK;
622   }
623   result = tsi_fake_frame_decode(bytes, bytes_size, &impl->incoming_frame);
624   if (result != TSI_OK) return result;
625
626   /* We now have a complete frame. */
627   result = tsi_fake_handshake_message_from_string(
628       reinterpret_cast<const char*>(impl->incoming_frame.data) +
629           TSI_FAKE_FRAME_HEADER_SIZE,
630       &received_msg);
631   if (result != TSI_OK) {
632     impl->result = result;
633     return result;
634   }
635   if (received_msg != expected_msg) {
636     gpr_log(GPR_ERROR, "Invalid received message (%s instead of %s)",
637             tsi_fake_handshake_message_to_string(received_msg),
638             tsi_fake_handshake_message_to_string(expected_msg));
639   }
640   if (GRPC_TRACE_FLAG_ENABLED(tsi_tracing_enabled)) {
641     gpr_log(GPR_INFO, "%s received %s.", impl->is_client ? "Client" : "Server",
642             tsi_fake_handshake_message_to_string(received_msg));
643   }
644   tsi_fake_frame_reset(&impl->incoming_frame, 0 /* needs_draining */);
645   impl->needs_incoming_message = 0;
646   if (impl->next_message_to_send == TSI_FAKE_HANDSHAKE_MESSAGE_MAX) {
647     /* We're done. */
648     if (GRPC_TRACE_FLAG_ENABLED(tsi_tracing_enabled)) {
649       gpr_log(GPR_INFO, "%s is done.", impl->is_client ? "Client" : "Server");
650     }
651     impl->result = TSI_OK;
652   }
653   return TSI_OK;
654 }
655
656 static tsi_result fake_handshaker_get_result(tsi_handshaker* self) {
657   tsi_fake_handshaker* impl = reinterpret_cast<tsi_fake_handshaker*>(self);
658   return impl->result;
659 }
660
661 static void fake_handshaker_destroy(tsi_handshaker* self) {
662   tsi_fake_handshaker* impl = reinterpret_cast<tsi_fake_handshaker*>(self);
663   tsi_fake_frame_destruct(&impl->incoming_frame);
664   tsi_fake_frame_destruct(&impl->outgoing_frame);
665   gpr_free(impl->outgoing_bytes_buffer);
666   gpr_free(self);
667 }
668
669 static tsi_result fake_handshaker_next(
670     tsi_handshaker* self, const unsigned char* received_bytes,
671     size_t received_bytes_size, const unsigned char** bytes_to_send,
672     size_t* bytes_to_send_size, tsi_handshaker_result** handshaker_result,
673     tsi_handshaker_on_next_done_cb /*cb*/, void* /*user_data*/) {
674   /* Sanity check the arguments. */
675   if ((received_bytes_size > 0 && received_bytes == nullptr) ||
676       bytes_to_send == nullptr || bytes_to_send_size == nullptr ||
677       handshaker_result == nullptr) {
678     return TSI_INVALID_ARGUMENT;
679   }
680   tsi_fake_handshaker* handshaker =
681       reinterpret_cast<tsi_fake_handshaker*>(self);
682   tsi_result result = TSI_OK;
683
684   /* Decode and process a handshake frame from the peer. */
685   size_t consumed_bytes_size = received_bytes_size;
686   if (received_bytes_size > 0) {
687     result = fake_handshaker_process_bytes_from_peer(self, received_bytes,
688                                                      &consumed_bytes_size);
689     if (result != TSI_OK) return result;
690   }
691
692   /* Create a handshake message to send to the peer and encode it as a fake
693    * frame. */
694   size_t offset = 0;
695   do {
696     size_t sent_bytes_size = handshaker->outgoing_bytes_buffer_size - offset;
697     result = fake_handshaker_get_bytes_to_send_to_peer(
698         self, handshaker->outgoing_bytes_buffer + offset, &sent_bytes_size);
699     offset += sent_bytes_size;
700     if (result == TSI_INCOMPLETE_DATA) {
701       handshaker->outgoing_bytes_buffer_size *= 2;
702       handshaker->outgoing_bytes_buffer = static_cast<unsigned char*>(
703           gpr_realloc(handshaker->outgoing_bytes_buffer,
704                       handshaker->outgoing_bytes_buffer_size));
705     }
706   } while (result == TSI_INCOMPLETE_DATA);
707   if (result != TSI_OK) return result;
708   *bytes_to_send = handshaker->outgoing_bytes_buffer;
709   *bytes_to_send_size = offset;
710
711   /* Check if the handshake was completed. */
712   if (fake_handshaker_get_result(self) == TSI_HANDSHAKE_IN_PROGRESS) {
713     *handshaker_result = nullptr;
714   } else {
715     /* Calculate the unused bytes. */
716     const unsigned char* unused_bytes = nullptr;
717     size_t unused_bytes_size = received_bytes_size - consumed_bytes_size;
718     if (unused_bytes_size > 0) {
719       unused_bytes = received_bytes + consumed_bytes_size;
720     }
721
722     /* Create a handshaker_result containing the unused bytes. */
723     result = fake_handshaker_result_create(unused_bytes, unused_bytes_size,
724                                            handshaker_result);
725     if (result == TSI_OK) {
726       /* Indicate that the handshake has completed and that a handshaker_result
727        * has been created. */
728       self->handshaker_result_created = true;
729     }
730   }
731   return result;
732 }
733
734 static const tsi_handshaker_vtable handshaker_vtable = {
735     nullptr, /* get_bytes_to_send_to_peer -- deprecated */
736     nullptr, /* process_bytes_from_peer   -- deprecated */
737     nullptr, /* get_result                -- deprecated */
738     nullptr, /* extract_peer              -- deprecated */
739     nullptr, /* create_frame_protector    -- deprecated */
740     fake_handshaker_destroy,
741     fake_handshaker_next,
742     nullptr, /* shutdown */
743 };
744
745 tsi_handshaker* tsi_create_fake_handshaker(int is_client) {
746   tsi_fake_handshaker* impl =
747       static_cast<tsi_fake_handshaker*>(gpr_zalloc(sizeof(*impl)));
748   impl->base.vtable = &handshaker_vtable;
749   impl->is_client = is_client;
750   impl->result = TSI_HANDSHAKE_IN_PROGRESS;
751   impl->outgoing_bytes_buffer_size =
752       TSI_FAKE_HANDSHAKER_OUTGOING_BUFFER_INITIAL_SIZE;
753   impl->outgoing_bytes_buffer =
754       static_cast<unsigned char*>(gpr_malloc(impl->outgoing_bytes_buffer_size));
755   if (is_client) {
756     impl->needs_incoming_message = 0;
757     impl->next_message_to_send = TSI_FAKE_CLIENT_INIT;
758   } else {
759     impl->needs_incoming_message = 1;
760     impl->next_message_to_send = TSI_FAKE_SERVER_INIT;
761   }
762   return &impl->base;
763 }
764
765 tsi_frame_protector* tsi_create_fake_frame_protector(
766     size_t* max_protected_frame_size) {
767   tsi_fake_frame_protector* impl =
768       static_cast<tsi_fake_frame_protector*>(gpr_zalloc(sizeof(*impl)));
769   impl->max_frame_size = (max_protected_frame_size == nullptr)
770                              ? TSI_FAKE_DEFAULT_FRAME_SIZE
771                              : *max_protected_frame_size;
772   impl->base.vtable = &frame_protector_vtable;
773   return &impl->base;
774 }
775
776 tsi_zero_copy_grpc_protector* tsi_create_fake_zero_copy_grpc_protector(
777     size_t* max_protected_frame_size) {
778   tsi_fake_zero_copy_grpc_protector* impl =
779       static_cast<tsi_fake_zero_copy_grpc_protector*>(
780           gpr_zalloc(sizeof(*impl)));
781   grpc_slice_buffer_init(&impl->header_sb);
782   grpc_slice_buffer_init(&impl->protected_sb);
783   impl->max_frame_size = (max_protected_frame_size == nullptr)
784                              ? TSI_FAKE_DEFAULT_FRAME_SIZE
785                              : *max_protected_frame_size;
786   impl->parsed_frame_size = 0;
787   impl->base.vtable = &zero_copy_grpc_protector_vtable;
788   return &impl->base;
789 }