aboutsummaryrefslogtreecommitdiffstats
path: root/src/bogo_shim/bogo_shim.cpp
blob: 9266fe5a5b967284a2ae461c301c27208f18eee4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
/*
* (C) 2019 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

/*
* This is a shim for testing Botan against BoringSSL's test TLS stack (BoGo).
*
* Instructions on use should go here.
*/

#include <botan/tls_client.h>
#include <botan/tls_server.h>
#include <botan/tls_exceptn.h>
#include <botan/tls_algos.h>
#include <botan/data_src.h>
#include <botan/pkcs8.h>
#include <botan/oids.h>
#include <botan/chacha_rng.h>
#include <botan/base64.h>
#include <botan/hex.h>
#include <botan/parsing.h>
#include <botan/mem_ops.h>
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <ctime>
#include <unordered_map>

#if defined(BOTAN_TARGET_OS_HAS_SOCKETS)
  #include <sys/socket.h>
  #include <sys/time.h>
  #include <netinet/in.h>
  #include <netdb.h>
  #include <string.h>
  #include <unistd.h>
  #include <errno.h>
  #include <fcntl.h>
#endif

namespace {

int shim_output(const std::string& s, int rc = 0)
   {
   std::cout << s << "\n";
   return rc;
   }

void shim_exit_with_error(const std::string& s, int rc = 1)
   {
   std::cerr << s << "\n";
   std::exit(rc);
   }

void shim_log(const std::string& s)
   {
   static FILE* f = fopen("/tmp/bogo_shim.log", "w");
   fprintf(f, "%d: %s\n", (int)time(nullptr), s.c_str());
   fflush(f);
   }

std::string map_to_bogo_error(const std::string& e)
   {
   static const std::unordered_map<std::string, std::string> err_map
      {
         { "Application data before handshake done", ":APPLICATION_DATA_INSTEAD_OF_HANDSHAKE:" },
         { "Bad Hello_Request, has non-zero size", ":BAD_HELLO_REQUEST:" },
         { "Bad code for TLS alert level", ":UNKNOWN_ALERT_TYPE:" },
         { "Bad extension size", ":DECODE_ERROR:" },
         { "Bad signature on server key exchange", ":BAD_SIGNATURE:" },
         { "Bad size (1) for TLS alert message", ":BAD_ALERT:" },
         { "Bad size (4) for TLS alert message", ":BAD_ALERT:" },
         { "CERTIFICATE decoding failed with PEM: No PEM header found", ":CANNOT_PARSE_LEAF_CERT:" },
         { "Can't agree on a ciphersuite with client", ":NO_SHARED_CIPHER:" },
         { "Can't interleave application and handshake data", ":UNEXPECTED_RECORD:" },
         { "Certificate chain exceeds policy specified maximum size", ":EXCESSIVE_MESSAGE_SIZE:" },
         { "Certificate key type did not match ciphersuite", ":WRONG_CERTIFICATE_TYPE:" },
         { "Certificate: Message malformed", ":DECODE_ERROR:" },
         { "Client cert verify failed", ":BAD_SIGNATURE:" },
         { "Client did not offer NULL compression", ":INVALID_COMPRESSION_LIST:" },
         { "Client offered version with major version under 3", ":UNSUPPORTED_PROTOCOL:" },
         { "Client policy prohibits insecure renegotiation", ":RENEGOTIATION_MISMATCH:" },
         { "Client policy prohibits renegotiation", ":NO_RENEGOTIATION:" },
         { "Client resumed extended ms session without sending extension", ":RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION:" },
         { "Client signalled fallback SCSV, possible attack", ":INAPPROPRIATE_FALLBACK:" },
         { "Client version TLS v1.0 is unacceptable by policy", ":UNSUPPORTED_PROTOCOL:" },
         { "Client version TLS v1.1 is unacceptable by policy", ":UNSUPPORTED_PROTOCOL:" },
         { "Client: No certificates sent by server", ":DECODE_ERROR:" },
         { "Counterparty sent inconsistent key and sig types", ":WRONG_SIGNATURE_TYPE:" },
         { "Empty ALPN protocol not allowed", ":PARSE_TLSEXT:" },
         { "Encoding error: Cannot encode PSS string, output length too small", ":NO_COMMON_SIGNATURE_ALGORITHMS:" },
         { "Finished message didn't verify", ":DIGEST_CHECK_FAILED:" },
         { "Inconsistent length in certificate request", ":DECODE_ERROR:" },
         { "Invalid CertificateRequest: Length field outside parameters", ":DECODE_ERROR:" },
         { "Invalid CertificateVerify: Extra bytes at end of message", ":DECODE_ERROR:" },
         { "Invalid Certificate_Status: invalid length field", ":DECODE_ERROR:" },
         { "Invalid ChangeCipherSpec", ":BAD_CHANGE_CIPHER_SPEC:" },
         { "Invalid ClientKeyExchange: Extra bytes at end of message", ":DECODE_ERROR:" },
         { "Invalid ServerKeyExchange: Extra bytes at end of message", ":DECODE_ERROR:" },
         { "Invalid SessionTicket: Extra bytes at end of message", ":DECODE_ERROR:" },
         { "Invalid authentication tag: ChaCha20Poly1305 tag check failed", ":DECRYPTION_FAILED_OR_BAD_RECORD_MAC:" },
         { "Invalid authentication tag: GCM tag check failed", ":DECRYPTION_FAILED_OR_BAD_RECORD_MAC:" },
         { "Message authentication failure", ":DECRYPTION_FAILED_OR_BAD_RECORD_MAC:" },
         { "OS2ECP: Unknown format type 251", ":BAD_ECPOINT:" },
         { "Policy forbids all available TLS version", ":NO_SUPPORTED_VERSIONS_ENABLED:" },
         { "Policy refuses to accept signing with any hash supported by peer", ":NO_COMMON_SIGNATURE_ALGORITHMS:" },
         { "Policy requires client send a certificate, but it did not", ":PEER_DID_NOT_RETURN_A_CERTIFICATE:" },
         { "Received a record that exceeds maximum size", ":ENCRYPTED_LENGTH_TOO_LONG:" },
         { "Received unexpected record version in initial record", ":WRONG_VERSION_NUMBER:" },
         { "Received unexpected record version", ":WRONG_VERSION_NUMBER:" },
         { "Server certificate changed during renegotiation", ":SERVER_CERT_CHANGED:" },
         { "Server changed its mind about extended master secret", ":RENEGOTIATION_EMS_MISMATCH:" },
         { "Server changed its mind about secure renegotiation", ":RENEGOTIATION_MISMATCH:" },
         { "Server changed version after renegotiation", ":WRONG_SSL_VERSION:" },
         { "Server downgraded version after renegotiation", ":WRONG_SSL_VERSION:" },
         { "Server replied using a ciphersuite not allowed in version it offered", ":WRONG_CIPHER_RETURNED:" },
         { "Server replied with ciphersuite we didn't send", ":WRONG_CIPHER_RETURNED:" },
         { "Server replied with later version than client offered", ":UNSUPPORTED_PROTOCOL:" },
         { "Server replied with non-null compression method", ":UNSUPPORTED_COMPRESSION_ALGORITHM:" },
         { "Server replied with some unknown ciphersuite", ":UNKNOWN_CIPHER_RETURNED:" },
         { "Server replied with unsupported extensions: 0", ":UNEXPECTED_EXTENSION:" },
         { "Server replied with unsupported extensions: 1234", ":UNEXPECTED_EXTENSION:" },
         { "Server replied with unsupported extensions: 16", ":UNEXPECTED_EXTENSION:" },
         { "Server replied with unsupported extensions: 43", ":UNEXPECTED_EXTENSION:" },
         { "Server replied with unsupported extensions: 5", ":UNEXPECTED_EXTENSION:" },
         { "Server resumed session and removed extended master secret", ":RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION:" },
         { "Server resumed session but added extended master secret", ":RESUMED_NON_EMS_SESSION_WITH_EMS_EXTENSION:" },
         { "Server resumed session but with wrong version", ":OLD_SESSION_VERSION_NOT_RETURNED:" },
         { "Server sent ECC curve prohibited by policy", ":WRONG_CURVE:" },
         { "Server sent an unsupported extension", ":UNEXPECTED_EXTENSION:" },
         { "Server sent bad values for secure renegotiation", ":RENEGOTIATION_MISMATCH:" },
         { "Server version TLS v1.0 is unacceptable by policy", ":UNSUPPORTED_PROTOCOL:" },
         { "Server version TLS v1.1 is unacceptable by policy", ":UNSUPPORTED_PROTOCOL:" },
         { "Server_Hello_Done: Must be empty, and is not", ":DECODE_ERROR:" },
         { "Simulated OCSP callback failure", ":OCSP_CB_ERROR:" },
         { "Simulating cert verify callback failure", ":CERT_CB_ERROR:" },
         { "TLS plaintext record is larger than allowed maximum", ":DATA_LENGTH_TOO_LONG:" },
         { "TLS signature extension did not allow for RSA/SHA-256 signature", ":WRONG_SIGNATURE_TYPE:", },
         { "Test requires rejecting cert", ":CERTIFICATE_VERIFY_FAILED:" },
         { "Unexpected ALPN protocol", ":INVALID_ALPN_PROTOCOL:" },
         { "Unexpected record type 42 from counterparty", ":UNEXPECTED_RECORD:" },
         { "Unexpected state transition in handshake, expected  received hello_request", ":UNEXPECTED_MESSAGE:" },
         { "Unexpected state transition in handshake, expected  received server_key_exchange", ":BAD_HELLO_REQUEST:" },
         { "Unexpected state transition in handshake, expected certificate received certificate_status", ":UNEXPECTED_MESSAGE:" },
         { "Unexpected state transition in handshake, expected certificate received client_hello+client_key_exchange", ":UNEXPECTED_MESSAGE:" },
         { "Unexpected state transition in handshake, expected certificate_request|server_hello_done received certificate+certificate_status+server_key_exchange", ":UNEXPECTED_MESSAGE:" },
         { "Unexpected state transition in handshake, expected certificate_verify received client_hello+certificate+client_key_exchange+change_cipher_spec", ":UNEXPECTED_RECORD:" },
         { "Unexpected state transition in handshake, expected change_cipher_spec received certificate+certificate_status+server_hello_done+new_session_ticket+finished", ":UNEXPECTED_RECORD:" },
         { "Unexpected state transition in handshake, expected change_cipher_spec received certificate+certificate_status+server_key_exchange+server_hello_done+new_session_ticket+finished", ":UNEXPECTED_RECORD:" },
         { "Unexpected state transition in handshake, expected change_cipher_spec received client_hello+client_key_exchange+finished", ":UNEXPECTED_RECORD:" },
         { "Unexpected state transition in handshake, expected change_cipher_spec received client_hello+finished", ":UNEXPECTED_RECORD:" },
         { "Unexpected state transition in handshake, expected change_cipher_spec received finished", ":UNEXPECTED_RECORD:" },
         { "Unexpected state transition in handshake, expected client_key_exchange received client_hello+change_cipher_spec", ":UNEXPECTED_RECORD:" },
         { "Unexpected state transition in handshake, expected new_session_ticket received certificate+certificate_status+server_hello_done+change_cipher_spec", ":UNEXPECTED_RECORD:" },
         { "Unexpected state transition in handshake, expected new_session_ticket received certificate+certificate_status+server_key_exchange+server_hello_done+change_cipher_spec", ":UNEXPECTED_RECORD:" },
         { "Unexpected state transition in handshake, expected server_hello_done received server_key_exchange+certificate_request", ":UNEXPECTED_MESSAGE:" },
         { "Unexpected state transition in handshake, expected server_key_exchange received certificate", ":WRONG_CIPHER_RETURNED:" },
         { "Unexpected state transition in handshake, expected server_key_exchange received certificate+certificate_status+server_hello_done", ":UNEXPECTED_MESSAGE:" },
         { "Unexpected state transition in handshake, expected server_key_exchange|server_hello_done received certificate_request", ":UNEXPECTED_MESSAGE:" },
         { "Unknown TLS handshake message type 43", ":UNEXPECTED_MESSAGE:" },
         { "Unknown TLS handshake message type 44", ":UNEXPECTED_MESSAGE:" },
         { "Unknown TLS handshake message type 46", ":UNEXPECTED_MESSAGE:" },
         { "Unknown TLS handshake message type 53", ":UNEXPECTED_MESSAGE:" },
         { "Unknown TLS handshake message type 54", ":UNEXPECTED_MESSAGE:" },
         { "Unknown TLS handshake message type 55", ":UNEXPECTED_MESSAGE:" },
         { "Unknown TLS handshake message type 56", ":UNEXPECTED_MESSAGE:" },
         { "Unknown TLS handshake message type 57", ":UNEXPECTED_MESSAGE:" },
         { "Unknown TLS handshake message type 58", ":UNEXPECTED_MESSAGE:" },
         { "Unknown TLS handshake message type 6", ":UNEXPECTED_MESSAGE:" },
         { "Unknown TLS handshake message type 62", ":UNEXPECTED_MESSAGE:" },
         { "Unknown TLS handshake message type 64", ":UNEXPECTED_MESSAGE:" },
         { "signature_algorithm_of_scheme: Unknown signature algorithm enum", ":WRONG_SIGNATURE_TYPE:" },
      };

   auto err_map_i = err_map.find(e);
   if(err_map_i != err_map.end())
      return err_map_i->second;

   return "Unmapped error: " + e;
   }

class Shim_Exception final : public std::exception
   {
   public:
      Shim_Exception(const std::string& msg, int rc = 1) :
         m_msg(msg), m_rc(rc) {}

      const char* what() const noexcept { return m_msg.c_str(); }

      int rc() const { return m_rc; }
   private:
      const std::string m_msg;
      int m_rc;
   };

#if defined(BOTAN_TARGET_OS_HAS_SOCKETS)

class Shim_Socket final
   {
   private:
      typedef int socket_type;
      typedef ssize_t socket_op_ret_type;
      static void close_socket(socket_type s) { ::close(s); }
      static std::string get_last_socket_error() { return ::strerror(errno); }

   public:
      Shim_Socket(const std::string& hostname, int port) : m_socket(-1)
         {
         addrinfo hints;
         std::memset(&hints, 0, sizeof(hints));
         hints.ai_family = AF_UNSPEC;
         hints.ai_socktype = SOCK_STREAM;
         hints.ai_flags = AI_NUMERICSERV;
         addrinfo* res;

         const std::string service = std::to_string(port);
         int rc = ::getaddrinfo(hostname.c_str(), service.c_str(), &hints, &res);
         shim_log("Connecting " + hostname + ":" + service);

         if(rc != 0)
            {
            throw Shim_Exception("Name resolution failed for " + hostname);
            }

         for(addrinfo* rp = res; (m_socket == -1) && (rp != nullptr); rp = rp->ai_next)
            {
            if(rp->ai_family != AF_INET && rp->ai_family != AF_INET6)
               continue;

            m_socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);

            if(m_socket == -1)
               {
               // unsupported socket type?
               continue;
               }

            int err = ::connect(m_socket, rp->ai_addr, rp->ai_addrlen);

            if(err != 0)
               {
               ::close(m_socket);
               m_socket = -1;
               }
            }

         if(m_socket < 0)
            throw Shim_Exception("Failed to connect to host");
         }

      ~Shim_Socket()
         {
         ::close(m_socket);
         m_socket = -1;
         }

      void write(const uint8_t buf[], size_t len)
         {
         if(m_socket < 0)
            throw Shim_Exception("Socket was bad on write");
         size_t sent_so_far = 0;
         while(sent_so_far != len)
            {
            const size_t left = len - sent_so_far;
            socket_op_ret_type sent = ::send(m_socket, Botan::cast_uint8_ptr_to_char(&buf[sent_so_far]), left, 0);
            if(sent < 0)
               throw Shim_Exception("Socket write failed", errno);
            else
               sent_so_far += static_cast<size_t>(sent);
            }
         }

      size_t read(uint8_t buf[], size_t len)
         {
         if(m_socket < 0)
            throw Shim_Exception("Socket was bad on read");
         socket_op_ret_type got = ::recv(m_socket, Botan::cast_uint8_ptr_to_char(buf), len, 0);
         //shim_log("Read returned " + std::to_string(got));

         if(got < 0)
            {
            if(errno == ECONNRESET)
               return 0;
            throw Shim_Exception("Socket read failed: " + std::string(strerror(errno)));
            }

         return static_cast<size_t>(got);
         }

   private:
      socket_type m_socket;
   };

#endif

std::set<std::string> combine_options(
   const std::set<std::string>& a,
   const std::set<std::string>& b,
   const std::set<std::string>& c,
   const std::set<std::string>& d)
   {
   std::set<std::string> combined;

   for(auto i : a)
      combined.insert(i);
   for(auto i : b)
      combined.insert(i);
   for(auto i : c)
      combined.insert(i);
   for(auto i : d)
      combined.insert(i);

   return combined;
   }

class Shim_Arguments final
   {
   public:
      Shim_Arguments(const std::set<std::string>& flags,
                     const std::set<std::string>& string_opts,
                     const std::set<std::string>& base64_opts,
                     const std::set<std::string>& int_opts,
                     const std::set<std::string>& int_vec_opts) :
         m_flags(flags),
         m_string_opts(string_opts),
         m_base64_opts(base64_opts),
         m_int_opts(int_opts),
         m_int_vec_opts(int_vec_opts),
         m_all_options(combine_options(string_opts, base64_opts, int_opts, int_vec_opts))
         {}

      void parse_args(char* argv[]);

      bool flag_set(const std::string& flag) const
         {
         if(m_flags.count(flag) == 0)
            throw Shim_Exception("Unknown bool flag " + flag);

         return m_parsed_flags.count(flag);
         }

      std::string get_string_opt(const std::string& key) const
         {
         if(m_string_opts.count(key) == 0)
            throw Shim_Exception("Unknown string key " + key);
         return get_opt(key);
         }

      std::string get_string_opt_or_else(const std::string& key, const std::string& def) const
         {
         if(m_string_opts.count(key) == 0)
            throw Shim_Exception("Unknown string key " + key);
         if(!option_used(key))
            return def;
         return get_opt(key);
         }

      std::vector<uint8_t> get_b64_opt(const std::string& key) const
         {
         if(m_base64_opts.count(key) == 0)
            throw Shim_Exception("Unknown base64 key " + key);
         return Botan::unlock(Botan::base64_decode(get_opt(key)));
         }

      size_t get_int_opt(const std::string& key) const
         {
         if(m_int_opts.count(key) == 0)
            throw Shim_Exception("Unknown int key " + key);
         return Botan::to_u32bit(get_opt(key));
         }

      size_t get_int_opt_or_else(const std::string& key, size_t def) const
         {
         if(m_int_opts.count(key) == 0)
            throw Shim_Exception("Unknown int key " + key);
         if(!option_used(key))
            return def;

         return Botan::to_u32bit(get_opt(key));
         }

      std::vector<size_t> get_int_vec_opt(const std::string& key) const
         {
         if(m_int_vec_opts.count(key) == 0)
            throw Shim_Exception("Unknown int vec key " + key);

         auto i = m_parsed_int_vec_opts.find(key);
         if(i == m_parsed_int_vec_opts.end())
            return std::vector<size_t>();
         else
            return i->second;
         }

      std::vector<std::string> get_alpn_string_vec_opt(const std::string& option) const
         {
         // hack used for alpn list (relies on all ALPNs being 3 chars long...)
         char delim = 0x03;

         if(option_used(option))
            return Botan::split_on(get_string_opt(option), delim);
         else
            return std::vector<std::string>();
         }

      bool option_used(const std::string& key) const
         {
         if(m_parsed_opts.find(key) != m_parsed_opts.end())
            return true;
         if(m_parsed_int_vec_opts.find(key) != m_parsed_int_vec_opts.end())
            return true;
         return false;
         }

   private:
      std::string get_opt(const std::string& key) const
         {
         auto i = m_parsed_opts.find(key);
         if(i == m_parsed_opts.end())
            throw Shim_Exception("Option " + key + " was not provided");
         return i->second;
         }

      const std::set<std::string> m_flags;
      const std::set<std::string> m_string_opts;
      const std::set<std::string> m_base64_opts;
      const std::set<std::string> m_int_opts;
      const std::set<std::string> m_int_vec_opts;
      const std::set<std::string> m_all_options;

      std::set<std::string> m_parsed_flags;
      std::map<std::string, std::string> m_parsed_opts;
      std::map<std::string, std::vector<size_t>> m_parsed_int_vec_opts;
   };

void Shim_Arguments::parse_args(char* argv[])
   {
   int i = 1; // skip argv[0]

   while(argv[i] != nullptr)
      {
      const std::string param(argv[i]);

      if(param.find("-") == 0)
         {
         const std::string flag_name = param.substr(1, std::string::npos);

         if(m_flags.count(flag_name))
            {
            shim_log("flag " + flag_name);
            m_parsed_flags.insert(flag_name);
            i += 1;
            }
         else if(m_all_options.count(flag_name))
            {
            if(argv[i+1] == nullptr)
               throw Shim_Exception("Expected argument following " + param);
            std::string val(argv[i+1]);
            shim_log("param " + flag_name + "=" + val);

            if(m_int_vec_opts.count(flag_name))
               {
               const size_t v = Botan::to_u32bit(val);
               m_parsed_int_vec_opts[flag_name].push_back(v);
               }
            else
               {
               m_parsed_opts[flag_name] = val;
               }
            i += 2;
            }
         else
            {
            shim_log("Unknown option " + param);
            throw Shim_Exception("Unknown option " + param, 89);
            }
         }
      else
         {
         shim_log("Unknown option " + param);
         throw Shim_Exception("Unknown option " + param, 89);
         }
      }
   }

std::unique_ptr<Shim_Arguments> parse_options(char* argv[])
   {
   const std::set<std::string> bogo_shim_flags = {
      "allow-false-start-without-alpn",
      "allow-unknown-alpn-protos",
      "async",
      "cbc-record-splitting",
      "check-close-notify",
      "decline-alpn",
      "decline-ocsp-callback",
      "dtls",
      "enable-all-curves",
      "enable-channel-id",
      "enable-early-data",
      "enable-ed25519",
      "enable-grease",
      "enable-ocsp-stapling",
      "enable-signed-cert-timestamps",
      //"enforce-rsa-key-usage",
      //"expect-accept-early-data",
      "expect-extended-master-secret",
      "expect-no-offer-early-data",
      "expect-no-secure-renegotiation",
      "expect-no-session",
      "expect-no-session-id",
      //"expect-reject-early-data",
      "expect-secure-renegotiation",
      "expect-session-id",
      "expect-session-miss",
      "expect-sha256-client-cert",
      "expect-ticket-renewal",
      "expect-ticket-supports-early-data",
      //"expect-tls13-downgrade",
      "expect-verify-result",
      //"export-traffic-secrets",
      "fail-cert-callback",
      //"fail-ddos-callback",
      //"fail-early-callback",
      "fail-ocsp-callback",
      "fallback-scsv",
      //"false-start",
      "forbid-renegotiation-after-handshake",
      "handoff",
      "handshake-never-done",
      "handshake-twice",
      "handshaker-resume",
      //"ignore-tls13-downgrade",
      "implicit-handshake",
      "install-cert-compression-algs",
      "install-ddos-callback",
      "is-handshaker-supported",
      //"jdk11-workaround",
      //"key-update",
      "no-op-extra-handshake",
      "no-rsa-pss-rsae-certs",
      "no-ticket",
      "no-tls1",
      "no-tls11",
      "no-tls12",
      "no-tls13", // implict due to 1.3 not being implemented
      //"on-resume-verify-fail",
      //"partial-write",
      //"peek-then-read",
      //"read-with-unfinished-write",
      "renegotiate-freely",
      "renegotiate-ignore",
      "renegotiate-once",
      //"renew-ticket",
      "require-any-client-certificate",
      "retain-only-sha256-client-cert",
      //"reverify-on-resume",
      "select-empty-alpn",
      "send-alert",
      "server",
      "server-preference",
      //"set-ocsp-in-callback",
      //"shim-shuts-down",
      "shim-writes-first",
      //"tls-unique",
      "use-custom-verify-callback",
      //"use-early-callback",
      "use-export-context",
      //"use-exporter-between-reads",
      "use-ocsp-callback",
      //"use-old-client-cert-callback",
      //"use-ticket-callback",
      "verify-fail",
      "verify-peer",
      //"verify-peer-if-no-obc",
      "write-different-record-sizes",
   };

   const std::set<std::string> bogo_shim_string_opts = {
      "advertise-alpn",
      //"advertise-npn",
      "cert-file",
      "cipher",
      //"delegated-credential",
      "expect-advertised-alpn",
      "expect-alpn",
      "expect-client-ca-list",
      "expect-late-alpn",
      "expect-msg-callback",
      //"expect-next-proto",
      "expect-peer-cert-file",
      "expect-server-name",
      "export-context",
      "export-label",
      "handshaker-path",
      "host-name",
      "key-file",
      "psk",
      "psk-identity",
      "select-alpn",
      "select-next-proto",
      //"send-channel-id",
      "srtp-profiles",
      "use-client-ca-list",
      //"write-settings",
   };

   const std::set<std::string> bogo_shim_base64_opts = {
      "expect-certificate-types",
      //"expect-channel-id",
      "expect-ocsp-response",
      //"expect-quic-transport-params",
      //"expect-signed-cert-timestamps",
      //"ocsp-response",
      //"quic-transport-params",
      //"signed-cert-timestamps",
      //"ticket-key", /* we use a different ticket format from Boring */
      //"token-binding-params",
   };

   const std::set<std::string> bogo_shim_int_opts {
      "expect-cipher-aes",
      "expect-cipher-no-aes",
      "expect-curve-id",
      "expect-peer-signature-algorithm",
      "expect-ticket-age-skew",
      "expect-token-binding-param",
      "expect-total-renegotiations",
      "expect-version",
      //"export-early-keying-material",
      "export-keying-material",
      "initial-timeout-duration-ms",
      "max-cert-list",
      //"max-send-fragment",
      "max-version",
      "min-version",
      //"mtu",
      "port",
      "read-size",
      "resume-count",
      "resumption-delay",
   };

   const std::set<std::string> bogo_shim_int_vec_opts {
      "curves",
      "expect-peer-verify-pref",
      "signing-prefs",
      "verify-prefs",
   };

   std::unique_ptr<Shim_Arguments> args(
      new Shim_Arguments(bogo_shim_flags,
                         bogo_shim_string_opts,
                         bogo_shim_base64_opts,
                         bogo_shim_int_opts,
                         bogo_shim_int_vec_opts));

   // may throw:
   args->parse_args(argv);

   return args;
   }

class Shim_Policy final : public Botan::TLS::Policy
   {
   public:
      Shim_Policy(const Shim_Arguments& args) : m_args(args), m_sessions(0) {}

      void incr_session_established() { m_sessions += 1; }
      size_t sessions_established() const { return m_sessions; }

      std::vector<std::string> allowed_ciphers() const override
         {
         return {
            "AES-256/OCB(12)",
            "AES-128/OCB(12)",
            "ChaCha20Poly1305",
            "AES-256/GCM",
            "AES-128/GCM",
            "AES-256/CCM",
            "AES-128/CCM",
            "AES-256/CCM(8)",
            "AES-128/CCM(8)",
            "Camellia-256/GCM",
            "Camellia-128/GCM",
            "ARIA-256/GCM",
            "ARIA-128/GCM",
            "AES-256",
            "AES-128",
            "Camellia-256",
            "Camellia-128",
            "SEED",
            "3DES",
         };

         }

      std::vector<std::string> allowed_signature_hashes() const override
         {
         if(m_args.option_used("signing-prefs"))
            {
            std::vector<std::string> pref_hash;
            for(size_t pref : m_args.get_int_vec_opt("signing-prefs"))
               {
               const auto scheme = static_cast<Botan::TLS::Signature_Scheme>(pref);
               if(Botan::TLS::signature_scheme_is_known(scheme) == false)
                  continue;
               pref_hash.push_back(Botan::TLS::hash_function_of_scheme(scheme));
               }

            if(m_args.flag_set("server"))
               pref_hash.push_back("SHA-256");
            return pref_hash;
            }
         else
            {
            return { "SHA-512", "SHA-384", "SHA-256", "SHA-1" };
            }
         }

      //std::vector<std::string> allowed_macs() const override;

      std::vector<std::string> allowed_key_exchange_methods() const override
         {
         return {
            "ECDHE_PSK",
            "DHE_PSK",
            "PSK",
            "CECPQ1",
            "ECDH",
            "DH",
            "RSA",
         };
         }

      std::vector<std::string> allowed_signature_methods() const override
         {
         return {
            "ECDSA",
            "RSA",
            "IMPLICIT",
         };

         }

      std::vector<Botan::TLS::Signature_Scheme> allowed_signature_schemes() const override
         {
         if(m_args.option_used("signing-prefs"))
            {
            std::vector<Botan::TLS::Signature_Scheme> schemes;
            for(size_t pref : m_args.get_int_vec_opt("signing-prefs"))
               {
               schemes.push_back(static_cast<Botan::TLS::Signature_Scheme>(pref));
               }

            // BoGo gets sad if these are not included in our signature_algorithms extension

            if(!m_args.flag_set("server") && false)
               {
               schemes.push_back(Botan::TLS::Signature_Scheme::RSA_PKCS1_SHA256);
               schemes.push_back(Botan::TLS::Signature_Scheme::ECDSA_SHA256);
               }

            return schemes;
            }

         if(m_args.option_used("verify-prefs"))
            {
            std::vector<Botan::TLS::Signature_Scheme> schemes;
            for(size_t pref : m_args.get_int_vec_opt("verify-prefs"))
               {
               schemes.push_back(static_cast<Botan::TLS::Signature_Scheme>(pref));
               }

            // BoGo gets sad if these are not included in our signature_algorithms extension

            if(!m_args.flag_set("server") && false)
               {
               schemes.push_back(Botan::TLS::Signature_Scheme::RSA_PKCS1_SHA256);
               schemes.push_back(Botan::TLS::Signature_Scheme::ECDSA_SHA256);
               }

            return schemes;
            }

         return Botan::TLS::Policy::allowed_signature_schemes();
         }

      //size_t minimum_signature_strength() const override;

      //bool require_cert_revocation_info() const override;

      std::vector<Botan::TLS::Group_Params> key_exchange_groups() const override
         {
         if(m_args.option_used("curves"))
            {
            std::vector<Botan::TLS::Group_Params> groups;
            for(size_t pref : m_args.get_int_vec_opt("curves"))
               {
               groups.push_back(static_cast<Botan::TLS::Group_Params>(pref));
               }

            return groups;
            }

         return Botan::TLS::Policy::key_exchange_groups();
         }

      bool use_ecc_point_compression() const override { return false; } // BoGo expects this

      //Botan::TLS::Group_Params choose_key_exchange_group(const std::vector<Botan::TLS::Group_Params>& peer_groups) const override;

      bool require_client_certificate_authentication() const
         {
         return m_args.flag_set("require-any-client-certificate");
         }

      bool request_client_certificate_authentication() const
         {
         return m_args.flag_set("verify-peer") ||
            m_args.flag_set("fail-cert-callback") ||
            require_client_certificate_authentication();
         }

      bool allow_insecure_renegotiation() const override
         {
         if(m_args.flag_set("expect-no-secure-renegotiation"))
            return true;
         else
            return false;
         }

      //bool include_time_in_hello_random() const override;

      bool allow_client_initiated_renegotiation() const override
         {
         if(m_args.flag_set("renegotiate-freely"))
            return true;

         if(m_args.flag_set("renegotiate-once") && m_sessions <= 1)
            return true;

         return false;
         }

      bool allow_server_initiated_renegotiation() const override
         {
         return allow_client_initiated_renegotiation(); // same logic
         }

      bool allow_tls10() const override
         {
         return (!m_args.flag_set("no-tls1"));
         }

      bool allow_tls11() const override
         {
         return (!m_args.flag_set("no-tls11"));
         }

      bool allow_tls12() const override
         {
         return (!m_args.flag_set("no-tls12"));
         }

      //bool allow_dtls10() const override;

      //bool allow_dtls12() const override;

      //Botan::TLS::Group_Params default_dh_group() const override;

      //size_t minimum_dh_group_size() const override;

      size_t minimum_ecdsa_group_size() const override { return 224; }

      size_t minimum_ecdh_group_size() const override { return 224; }

      //size_t minimum_rsa_bits() const override;

      //size_t minimum_dsa_group_size() const override;

      //void check_peer_key_acceptable(const Botan::Public_Key& public_key) const override;

      //bool hide_unknown_users() const override;

      //uint32_t session_ticket_lifetime() const override;

      //std::vector<uint16_t> srtp_profiles() const override;

      bool only_resume_with_exact_version() const override
         {
         return false;
         }

      bool acceptable_protocol_version(Botan::TLS::Protocol_Version version) const override
         {
         if(!Botan::TLS::Policy::acceptable_protocol_version(version))
            return false;

         if(m_args.option_used("min-version"))
            {
            const uint16_t min_version_16 = static_cast<uint16_t>(m_args.get_int_opt("min-version"));
            Botan::TLS::Protocol_Version min_version(min_version_16 >> 8, min_version_16 & 0xFF);
            if(min_version > version)
               return false;
            }

         if(m_args.option_used("max-version"))
            {
            const uint16_t max_version_16 = static_cast<uint16_t>(m_args.get_int_opt("max-version"));
            Botan::TLS::Protocol_Version max_version(max_version_16 >> 8, max_version_16 & 0xFF);
            if(version > max_version)
               return false;
            }

         return version.known_version();
         }

      bool send_fallback_scsv(Botan::TLS::Protocol_Version) const override
         {
         return m_args.flag_set("fallback-scsv");
         }

      //bool server_uses_own_ciphersuite_preferences() const override;

      //bool negotiate_encrypt_then_mac() const override;

      bool support_cert_status_message() const override
         {
         if(m_args.flag_set("server"))
            return false;
         return true;
         }

      std::vector<uint16_t> ciphersuite_list(Botan::TLS::Protocol_Version version,
                                             bool have_srp) const override;

      //size_t dtls_default_mtu() const override;

      //size_t dtls_initial_timeout() const override;

      //size_t dtls_maximum_timeout() const override;

      bool allow_resumption_for_renegotiation() const
         {
         return false; // BoGo expects this
         }

      bool abort_connection_on_undesired_renegotiation() const
         {
         if(m_args.flag_set("renegotiate-ignore"))
            return false;
         else
            return true;
         }

      size_t maximum_certificate_chain_size() const
         {
         return m_args.get_int_opt_or_else("max-cert-list", 0);
         }

   private:
      const Shim_Arguments& m_args;
      size_t m_sessions;
   };

std::vector<uint16_t> Shim_Policy::ciphersuite_list(Botan::TLS::Protocol_Version version,
                                                    bool have_srp) const
   {
   std::vector<uint16_t> ciphersuite_codes;

   const std::string cipher_limit = m_args.get_string_opt_or_else("cipher", "");
   if(cipher_limit == "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:[TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384|TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256|TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA]:TLS_RSA_WITH_AES_128_GCM_SHA256:TLS_RSA_WITH_AES_128_CBC_SHA:[TLS_RSA_WITH_AES_256_GCM_SHA384|TLS_RSA_WITH_AES_256_CBC_SHA]")
      {
      std::vector<std::string> suites = {
         "ECDHE_RSA_WITH_AES_128_GCM_SHA256",
         "ECDHE_RSA_WITH_AES_256_GCM_SHA384",
         "ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
         "ECDHE_RSA_WITH_AES_256_CBC_SHA",
         "RSA_WITH_AES_256_GCM_SHA384",
         "RSA_WITH_AES_256_CBC_SHA",
      };

      for(auto suite_name : suites)
         {
         const auto suite = Botan::TLS::Ciphersuite::from_name(suite_name);
         if(suite.valid() == false)
            shim_exit_with_error("Bad ciphersuite name " + suite_name);
         ciphersuite_codes.push_back(suite.ciphersuite_code());
         }
      }
   else
      {
      // Hack: go in reverse order to avoid preferring 3DES
      auto ciphersuites = Botan::TLS::Ciphersuite::all_known_ciphersuites();
      for(auto i = ciphersuites.rbegin(); i != ciphersuites.rend(); ++i)
         {
         const auto suite = *i;
         // Can we use it?
         if(suite.valid() == false)
            continue;

         // Are we doing SRP?
         if(!have_srp && suite.kex_method() == Botan::TLS::Kex_Algo::SRP_SHA)
            continue;

         if(cipher_limit != "")
            {
            if(cipher_limit == "DEFAULT:!AES")
               {
               const std::string suite_algo = suite.cipher_algo();

               if(suite_algo == "AES-128" || suite_algo == "AES-256" ||
                  suite_algo == "AES-128/GCM" || suite_algo == "AES-256/GCM" ||
                  suite_algo == "AES-128/CCM" || suite_algo == "AES-256/CCM" ||
                  suite_algo == "AES-128/CCM(8)" || suite_algo == "AES-256/CCM(8)" ||
                  suite_algo == "AES-128/OCB(12)" || suite_algo == "AES-256/OCB(12)")
                  {
                  continue;
                  }
               }
            else
               {
               shim_exit_with_error("Unknown cipher " + cipher_limit);
               }
            }

         if(!version.supports_aead_modes())
            {
            // Are we doing AEAD in a non-AEAD version?
            if(suite.mac_algo() == "AEAD")
               continue;

            // Older (v1.0/v1.1) versions also do not support any hash but SHA-1
            if(suite.mac_algo() != "SHA-1")
               continue;
            }

         ciphersuite_codes.push_back(suite.ciphersuite_code());
         }
      }

   return ciphersuite_codes;
   }

class Shim_Credentials final : public Botan::Credentials_Manager
   {
   public:
      Shim_Credentials(const Shim_Arguments& args) : m_args(args)
         {
         m_psk_identity = m_args.get_string_opt_or_else("psk-identity", "");

         const std::string psk_str = m_args.get_string_opt_or_else("psk", "");
         m_psk = Botan::SymmetricKey(reinterpret_cast<const uint8_t*>(psk_str.data()), psk_str.size());

         if(m_args.option_used("key-file") && m_args.option_used("cert-file"))
            {
            Botan::DataSource_Stream key_stream(m_args.get_string_opt("key-file"));
            m_key = Botan::PKCS8::load_key(key_stream);

            Botan::DataSource_Stream cert_stream(m_args.get_string_opt("cert-file"));

            while(!cert_stream.end_of_data())
               {
               try
                  {
                  m_cert_chain.push_back(Botan::X509_Certificate(cert_stream));
                  }
               catch(...) {}
               }
            }
         }

      std::string psk_identity(const std::string& /*type*/,
                               const std::string& /*context*/,
                               const std::string& /*identity_hint*/) override
         {
         return m_psk_identity;
         }

      std::string psk_identity_hint(const std::string& /*type*/,
                                    const std::string& /*context*/)
         {
         return m_psk_identity;
         }

      Botan::SymmetricKey psk(const std::string& type,
                              const std::string& context,
                              const std::string& identity) override
         {
         if(!m_args.flag_set("no-ticket") && type == "tls-server" && context == "session-ticket")
            return Botan::SymmetricKey("ABCDEF0123456789");

         if(identity != m_psk_identity)
            throw Shim_Exception("Unexpected PSK identity");
         return m_psk;
         }

      std::vector<Botan::X509_Certificate> cert_chain(
         const std::vector<std::string>& cert_key_types,
         const std::string& /*type*/,
         const std::string& /*context*/)
         {
         if(m_args.flag_set("fail-cert-callback"))
            throw std::runtime_error("Simulating cert verify callback failure");

         if(m_key != nullptr && m_cert_chain.size() > 0)
            {
            for(std::string t : cert_key_types)
               {
               if(t == m_key->algo_name())
                  return m_cert_chain;
               }
            }

         return {};
         }

      Botan::Private_Key* private_key_for(const Botan::X509_Certificate& /*cert*/,
                                          const std::string& /*type*/,
                                          const std::string& /*context*/) override
         {
         // assumes cert == m_cert
         return m_key.get();
         }

   private:
      const Shim_Arguments& m_args;
      Botan::SymmetricKey m_psk;
      std::string m_psk_identity;
      std::unique_ptr<Botan::Private_Key> m_key;
      std::vector<Botan::X509_Certificate> m_cert_chain;
   };

class Shim_Callbacks final : public Botan::TLS::Callbacks
   {
   public:
      Shim_Callbacks(const Shim_Arguments& args, Shim_Socket& socket, Shim_Policy& policy) :
         m_channel(nullptr),
         m_args(args),
         m_policy(policy),
         m_socket(socket),
         m_is_datagram(args.flag_set("dtls")),
         m_warning_alerts(0),
         m_empty_records(0),
         m_should_exit(false),
         m_first_write_pending(true),
         m_sent_close(false)
         {}

      void set_channel(Botan::TLS::Channel* channel)
         {
         m_channel = channel;
         }

      void tls_emit_data(const uint8_t data[], size_t size) override
         {
         //shim_log("Emit data len" + std::to_string(size));
         m_socket.write(data, size);
         }

      void tls_record_received(uint64_t /*seq_no*/, const uint8_t data[], size_t size) override
         {

         if(size == 0)
            {
            m_empty_records += 1;
            if(m_empty_records > 32)
               shim_exit_with_error(":TOO_MANY_EMPTY_FRAGMENTS:");
            }
         else
            {
            m_empty_records = 0;
            }
         shim_log("Got a record len " + std::to_string(size));
         if(m_first_write_pending)
            {

            //m_channel->send("hello");
            m_first_write_pending = false;
            }

         std::vector<uint8_t> buf(data, data + size);
         for(size_t i = 0; i != size; ++i)
            buf[i] ^= 0xFF;

         shim_log("Sending " + std::to_string(size) + " bytes of blob");
         m_channel->send(buf);
         }

      bool tls_verify_message(const Botan::Public_Key& key,
                              const std::string& emsa,
                              Botan::Signature_Format format,
                              const std::vector<uint8_t>& msg,
                              const std::vector<uint8_t>& sig)
         {
         if(m_args.option_used("expect-peer-signature-algorithm"))
            {
            const auto scheme = static_cast<Botan::TLS::Signature_Scheme>(m_args.get_int_opt("expect-peer-signature-algorithm"));
            if(scheme != Botan::TLS::Signature_Scheme::NONE)
               {
               const std::string exp_emsa = Botan::TLS::padding_string_for_scheme(scheme);
               if(emsa != exp_emsa)
                  shim_exit_with_error("Unexpected signature scheme got " + emsa + " expected " + exp_emsa);
               }
            }
         return Botan::TLS::Callbacks::tls_verify_message(key, emsa, format, msg, sig);
         }

      void tls_verify_cert_chain(const std::vector<Botan::X509_Certificate>& /*cert_chain*/,
                                 const std::vector<std::shared_ptr<const Botan::OCSP::Response>>& /*ocsp_responses*/,
                                 const std::vector<Botan::Certificate_Store*>& /*trusted_roots*/,
                                 Botan::Usage_Type /*usage*/,
                                 const std::string& /*hostname*/,
                                 const Botan::TLS::Policy& /*policy*/) override
         {
         if(m_args.flag_set("enable-ocsp-stapling") &&
            m_args.flag_set("use-ocsp-callback") &&
            m_args.flag_set("fail-ocsp-callback"))
            {
            throw Botan::TLS::TLS_Exception(Botan::TLS::Alert::BAD_CERTIFICATE_STATUS_RESPONSE,
                                            "Simulated OCSP callback failure");
            }

         if(m_args.flag_set("verify-peer") && m_args.flag_set("verify-fail"))
            {
            throw Botan::TLS::TLS_Exception(Botan::TLS::Alert::BAD_CERTIFICATE,
                                            "Test requires rejecting cert");
            }
         }

      std::string tls_server_choose_app_protocol(const std::vector<std::string>& client_protos)
         {
         if(client_protos.empty())
            return ""; // shouldn't happen?

         if(m_args.flag_set("decline-alpn"))
            return "";

         if(m_args.option_used("expect-advertised-alpn"))
            {
            const std::vector<std::string> expected = m_args.get_alpn_string_vec_opt("expect-advertised-alpn");

            if(client_protos != expected)
               shim_exit_with_error("Bad ALPN from client");
            }

         if(m_args.option_used("select-alpn"))
            return m_args.get_string_opt("select-alpn");

         return client_protos[0]; // if not configured just pick something
         }

      void tls_alert(Botan::TLS::Alert alert) override
         {
         shim_log("Got an alert " + alert.type_string());

         if(alert.type() == Botan::TLS::Alert::RECORD_OVERFLOW)
            {
            shim_exit_with_error(":TLSV1_ALERT_RECORD_OVERFLOW:");
            }

         if(!alert.is_fatal())
            {
            m_warning_alerts++;
            if(m_warning_alerts > 5)
               shim_exit_with_error(":TOO_MANY_WARNING_ALERTS:");
            }

         if(alert.type() == Botan::TLS::Alert::CLOSE_NOTIFY && m_sent_close == false)
            {
            m_channel->send_alert(alert);
            m_sent_close = true;
            }
         }

      bool tls_session_established(const Botan::TLS::Session& session) override
         {
         shim_log("Session established: " + Botan::hex_encode(session.session_id()) +
                  " version " + session.version().to_string() +
                  " cipher " + session.ciphersuite().to_string() +
                  " EMS " + std::to_string(session.supports_extended_master_secret()));
         // probably need tests here?

         m_policy.incr_session_established();

         if(m_args.option_used("expect-no-session-id"))
            {
            if(session.session_id().size() > 0)
               shim_exit_with_error("GOT UNEXPECTED SESSION ID");
            }

         if(m_args.option_used("expect-version"))
            {
            if(session.version().version_code() != m_args.get_int_opt("expect-version"))
               shim_exit_with_error("UNEXPECTED VERSION");
            }

         if(m_args.flag_set("expect-secure-renegotiation"))
            {
            if(m_channel->secure_renegotiation_supported() == false)
               shim_exit_with_error("EXPECTED SECURE RENEGOTIATION");
            }
         else if(m_args.flag_set("expect-no-secure-renegotiation"))
            {
            if(m_channel->secure_renegotiation_supported() == true)
               shim_exit_with_error("EXPECTED NO SECURE RENEGOTIATION");
            }

         if(m_args.flag_set("expect-extended-master-secret"))
            {
            if(session.supports_extended_master_secret() == false)
               shim_exit_with_error("NO ETM");
            }

         return true;
         }

      void tls_session_activated() override
         {
         if(m_args.flag_set("send-alert"))
            {
            m_channel->send_fatal_alert(Botan::TLS::Alert::DECOMPRESSION_FAILURE);
            return;
            }

         if(size_t length = m_args.get_int_opt_or_else("export-keying-material", 0))
            {
            const std::string label = m_args.get_string_opt("export-label");
            const std::string context = m_args.get_string_opt("export-context");
            const auto exported = m_channel->key_material_export(label, context, length);
            m_channel->send(exported.bits_of());
            shim_log("Sending " + std::to_string(length) + " bytes of export");
            }

         const std::string alpn = m_channel->application_protocol();

         if(m_args.option_used("expect-alpn"))
            {
            if(alpn != m_args.get_string_opt("expect-alpn"))
               shim_exit_with_error("Got unexpected ALPN");
            }

         if(alpn == "baz" && !m_args.flag_set("allow-unknown-alpn-protos"))
            {
            throw Botan::TLS::TLS_Exception(Botan::TLS::Alert::ILLEGAL_PARAMETER,
                                            "Unexpected ALPN protocol");
            }

         if(m_args.flag_set("write-different-record-sizes"))
            {
            static const size_t record_sizes[] = {
               0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769
            };

            std::vector<uint8_t> buf(32769, 0x42);

            for(size_t sz : record_sizes)
               {
               m_channel->send(buf.data(), sz);
               }

            m_channel->close();
            }
         }

      bool should_exit() const
         {
         return m_should_exit;
         }

   private:
      Botan::TLS::Channel* m_channel;
      const Shim_Arguments& m_args;
      Shim_Policy& m_policy;
      Shim_Socket& m_socket;
      const bool m_is_datagram;
      size_t m_warning_alerts;
      size_t m_empty_records;
      bool m_should_exit;
      bool m_first_write_pending;
      bool m_sent_close;
   };

}

int main(int /*argc*/, char* argv[])
   {
   const std::chrono::milliseconds timeout(1000); // ??

   try
      {
      std::unique_ptr<Shim_Arguments> args = parse_options(argv);

      if(args->flag_set("is-handshaker-supported"))
         {
         return shim_output("No\n");
         }

      const uint16_t port = static_cast<uint16_t>(args->get_int_opt("port"));
      const size_t resume_count = args->get_int_opt_or_else("resume-count", 0);
      const bool is_server = args->flag_set("server");
      const bool is_datagram = args->flag_set("dtls");

      /*
      if(is_server)
         throw Shim_Exception("No support for server yet", 89);
      */
      if(is_datagram)
         throw Shim_Exception("No support for DTLS yet", 89);

      Botan::ChaCha_RNG rng(Botan::secure_vector<uint8_t>(64));
      Botan::TLS::Session_Manager_In_Memory session_manager(rng, 1024);
      Shim_Credentials creds(*args);

      for(size_t i = 0; i != resume_count+1; ++i)
         {
         Shim_Socket socket("localhost", port);

         Shim_Policy policy(*args);
         Shim_Callbacks callbacks(*args, socket, policy);

         std::unique_ptr<Botan::TLS::Channel> chan;

         if(is_server)
            {
            chan.reset(new Botan::TLS::Server(callbacks, session_manager, creds, policy, rng, is_datagram));
            }
         else
            {
            Botan::TLS::Protocol_Version offer_version = policy.latest_supported_version(is_datagram);
            shim_log("Offering " + offer_version.to_string());
            Botan::TLS::Server_Information server_info(args->get_string_opt_or_else("host-name", "localhost"), port);
            const std::vector<std::string> next_protocols = args->get_alpn_string_vec_opt("advertise-alpn");
            chan.reset(new Botan::TLS::Client(callbacks, session_manager, creds, policy, rng,
                                              server_info, offer_version, next_protocols));
            }

         callbacks.set_channel(chan.get());

         shim_log("Starting read loop");

         std::vector<uint8_t> buf(args->get_int_opt_or_else("read-size", 18*1024));
         size_t need_to_read = 5; // header len

         while(!callbacks.should_exit())
            {
            size_t got = socket.read(buf.data(), buf.size());
            if(got == 0)
               {
               shim_log("EOF on socket");
               break;
               }

            need_to_read = chan->received_data(buf.data(), got);

            if(need_to_read == 0)
               need_to_read = 5;
            }

         if(args->option_used("expect-total-renegotiations"))
            {
            const size_t exp = args->get_int_opt("expect-total-renegotiations");

            if(exp != policy.sessions_established() - 1)
               throw Shim_Exception("Unexpected number of renegotiations: saw " +
                                    std::to_string(policy.sessions_established() - 1) +
                                    " exp " + std::to_string(exp));
            }
         }

      }
   catch(Shim_Exception& e)
      {
      shim_exit_with_error(e.what(), e.rc());
      }
   catch(std::exception& e)
      {
      shim_exit_with_error(map_to_bogo_error(e.what()));
      }
   catch(...)
      {
      shim_exit_with_error("Unknown exception", 3);
      }
   return 0;
   }