Rebase shim against latest boringssl code
[openssl.git] / test / ossl_shim / ossl_shim.cc
1 /* Copyright (c) 2014, Google Inc.
2  *
3  * Permission to use, copy, modify, and/or distribute this software for any
4  * purpose with or without fee is hereby granted, provided that the above
5  * copyright notice and this permission notice appear in all copies.
6  *
7  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10  * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14
15 #if !defined(__STDC_FORMAT_MACROS)
16 #define __STDC_FORMAT_MACROS
17 #endif
18
19 #include <openssl/e_os2.h>
20
21 #if !defined(OPENSSL_SYS_WINDOWS)
22 #include <arpa/inet.h>
23 #include <netinet/in.h>
24 #include <netinet/tcp.h>
25 #include <signal.h>
26 #include <sys/socket.h>
27 #include <sys/time.h>
28 #include <unistd.h>
29 #else
30 #include <io.h>
31 OPENSSL_MSVC_PRAGMA(warning(push, 3))
32 #include <winsock2.h>
33 #include <ws2tcpip.h>
34 OPENSSL_MSVC_PRAGMA(warning(pop))
35
36 OPENSSL_MSVC_PRAGMA(comment(lib, "Ws2_32.lib"))
37 #endif
38
39 #include <assert.h>
40 #include <inttypes.h>
41 #include <string.h>
42
43 #include <openssl/bio.h>
44 #include <openssl/buffer.h>
45 #include <openssl/crypto.h>
46 #include <openssl/dh.h>
47 #include <openssl/err.h>
48 #include <openssl/evp.h>
49 #include <openssl/hmac.h>
50 #include <openssl/objects.h>
51 #include <openssl/rand.h>
52 #include <openssl/ssl.h>
53 #include <openssl/x509.h>
54
55 #include <memory>
56 #include <string>
57 #include <vector>
58
59 #include "async_bio.h"
60 #include "packeted_bio.h"
61 #include "test_config.h"
62
63 namespace bssl {
64
65 #if !defined(OPENSSL_SYS_WINDOWS)
66 static int closesocket(int sock) {
67   return close(sock);
68 }
69
70 static void PrintSocketError(const char *func) {
71   perror(func);
72 }
73 #else
74 static void PrintSocketError(const char *func) {
75   fprintf(stderr, "%s: %d\n", func, WSAGetLastError());
76 }
77 #endif
78
79 static int Usage(const char *program) {
80   fprintf(stderr, "Usage: %s [flags...]\n", program);
81   return 1;
82 }
83
84 struct TestState {
85   // async_bio is async BIO which pauses reads and writes.
86   BIO *async_bio = nullptr;
87   // packeted_bio is the packeted BIO which simulates read timeouts.
88   BIO *packeted_bio = nullptr;
89   bssl::UniquePtr<EVP_PKEY> channel_id;
90   bool cert_ready = false;
91   bssl::UniquePtr<SSL_SESSION> session;
92   bssl::UniquePtr<SSL_SESSION> pending_session;
93   bool early_callback_called = false;
94   bool handshake_done = false;
95   // private_key is the underlying private key used when testing custom keys.
96   bssl::UniquePtr<EVP_PKEY> private_key;
97   std::vector<uint8_t> private_key_result;
98   // private_key_retries is the number of times an asynchronous private key
99   // operation has been retried.
100   unsigned private_key_retries = 0;
101   bool got_new_session = false;
102   bssl::UniquePtr<SSL_SESSION> new_session;
103   bool ticket_decrypt_done = false;
104   bool alpn_select_done = false;
105 };
106
107 static void TestStateExFree(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
108                             int index, long argl, void *argp) {
109   delete ((TestState *)ptr);
110 }
111
112 static int g_config_index = 0;
113 static int g_state_index = 0;
114
115 static bool SetTestConfig(SSL *ssl, const TestConfig *config) {
116   return SSL_set_ex_data(ssl, g_config_index, (void *)config) == 1;
117 }
118
119 static const TestConfig *GetTestConfig(const SSL *ssl) {
120   return (const TestConfig *)SSL_get_ex_data(ssl, g_config_index);
121 }
122
123 static bool SetTestState(SSL *ssl, std::unique_ptr<TestState> state) {
124   // |SSL_set_ex_data| takes ownership of |state| only on success.
125   if (SSL_set_ex_data(ssl, g_state_index, state.get()) == 1) {
126     state.release();
127     return true;
128   }
129   return false;
130 }
131
132 static TestState *GetTestState(const SSL *ssl) {
133   return (TestState *)SSL_get_ex_data(ssl, g_state_index);
134 }
135
136 static bssl::UniquePtr<X509> LoadCertificate(const std::string &file) {
137   bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
138   if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
139     return nullptr;
140   }
141   return bssl::UniquePtr<X509>(PEM_read_bio_X509(bio.get(), NULL, NULL, NULL));
142 }
143
144 static bssl::UniquePtr<EVP_PKEY> LoadPrivateKey(const std::string &file) {
145   bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
146   if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
147     return nullptr;
148   }
149   return bssl::UniquePtr<EVP_PKEY>(
150       PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL));
151 }
152
153 template<typename T>
154 struct Free {
155   void operator()(T *buf) {
156     free(buf);
157   }
158 };
159
160 static bool GetCertificate(SSL *ssl, bssl::UniquePtr<X509> *out_x509,
161                            bssl::UniquePtr<EVP_PKEY> *out_pkey) {
162   const TestConfig *config = GetTestConfig(ssl);
163
164   if (!config->digest_prefs.empty()) {
165     fprintf(stderr, "Digest prefs not supported.\n");
166     return false;
167   }
168
169   if (!config->signing_prefs.empty()) {
170     fprintf(stderr, "Set signing algorithm prefs not supported\n");
171     return false;
172   }
173
174   if (!config->key_file.empty()) {
175     *out_pkey = LoadPrivateKey(config->key_file.c_str());
176     if (!*out_pkey) {
177       return false;
178     }
179   }
180   if (!config->cert_file.empty()) {
181     *out_x509 = LoadCertificate(config->cert_file.c_str());
182     if (!*out_x509) {
183       return false;
184     }
185   }
186   if (!config->ocsp_response.empty()) {
187     fprintf(stderr, "OCSP response not supported.\n");
188     return false;
189   }
190   return true;
191 }
192
193 static bool InstallCertificate(SSL *ssl) {
194   bssl::UniquePtr<X509> x509;
195   bssl::UniquePtr<EVP_PKEY> pkey;
196   if (!GetCertificate(ssl, &x509, &pkey)) {
197     return false;
198   }
199
200   if (pkey) {
201     TestState *test_state = GetTestState(ssl);
202     const TestConfig *config = GetTestConfig(ssl);
203     if (!SSL_use_PrivateKey(ssl, pkey.get())) {
204       return false;
205     }
206   }
207
208   if (x509 && !SSL_use_certificate(ssl, x509.get())) {
209     return false;
210   }
211
212   return true;
213 }
214
215 static int ClientCertCallback(SSL *ssl, X509 **out_x509, EVP_PKEY **out_pkey) {
216   if (GetTestConfig(ssl)->async && !GetTestState(ssl)->cert_ready) {
217     return -1;
218   }
219
220   bssl::UniquePtr<X509> x509;
221   bssl::UniquePtr<EVP_PKEY> pkey;
222   if (!GetCertificate(ssl, &x509, &pkey)) {
223     return -1;
224   }
225
226   // Return zero for no certificate.
227   if (!x509) {
228     return 0;
229   }
230
231   // Asynchronous private keys are not supported with client_cert_cb.
232   *out_x509 = x509.release();
233   *out_pkey = pkey.release();
234   return 1;
235 }
236
237 static int VerifySucceed(X509_STORE_CTX *store_ctx, void *arg) {
238   return 1;
239 }
240
241 static int VerifyFail(X509_STORE_CTX *store_ctx, void *arg) {
242   X509_STORE_CTX_set_error(store_ctx, X509_V_ERR_APPLICATION_VERIFICATION);
243   return 0;
244 }
245
246 static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out,
247                                         unsigned int *out_len, void *arg) {
248   const TestConfig *config = GetTestConfig(ssl);
249   if (config->advertise_npn.empty()) {
250     return SSL_TLSEXT_ERR_NOACK;
251   }
252
253   *out = (const uint8_t*)config->advertise_npn.data();
254   *out_len = config->advertise_npn.size();
255   return SSL_TLSEXT_ERR_OK;
256 }
257
258 static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
259                                    const uint8_t* in, unsigned inlen, void* arg) {
260   const TestConfig *config = GetTestConfig(ssl);
261   if (config->select_next_proto.empty()) {
262     return SSL_TLSEXT_ERR_NOACK;
263   }
264
265   *out = (uint8_t*)config->select_next_proto.data();
266   *outlen = config->select_next_proto.size();
267   return SSL_TLSEXT_ERR_OK;
268 }
269
270 static int AlpnSelectCallback(SSL* ssl, const uint8_t** out, uint8_t* outlen,
271                               const uint8_t* in, unsigned inlen, void* arg) {
272   if (GetTestState(ssl)->alpn_select_done) {
273     fprintf(stderr, "AlpnSelectCallback called after completion.\n");
274     exit(1);
275   }
276
277   GetTestState(ssl)->alpn_select_done = true;
278
279   const TestConfig *config = GetTestConfig(ssl);
280   if (config->decline_alpn) {
281     return SSL_TLSEXT_ERR_NOACK;
282   }
283
284   if (!config->expected_advertised_alpn.empty() &&
285       (config->expected_advertised_alpn.size() != inlen ||
286        memcmp(config->expected_advertised_alpn.data(),
287               in, inlen) != 0)) {
288     fprintf(stderr, "bad ALPN select callback inputs\n");
289     exit(1);
290   }
291
292   *out = (const uint8_t*)config->select_alpn.data();
293   *outlen = config->select_alpn.size();
294   return SSL_TLSEXT_ERR_OK;
295 }
296
297 static unsigned PskClientCallback(SSL *ssl, const char *hint,
298                                   char *out_identity,
299                                   unsigned max_identity_len,
300                                   uint8_t *out_psk, unsigned max_psk_len) {
301   const TestConfig *config = GetTestConfig(ssl);
302
303   if (config->psk_identity.empty()) {
304     if (hint != nullptr) {
305       fprintf(stderr, "Server PSK hint was non-null.\n");
306       return 0;
307     }
308   } else if (hint == nullptr ||
309              strcmp(hint, config->psk_identity.c_str()) != 0) {
310     fprintf(stderr, "Server PSK hint did not match.\n");
311     return 0;
312   }
313
314   // Account for the trailing '\0' for the identity.
315   if (config->psk_identity.size() >= max_identity_len ||
316       config->psk.size() > max_psk_len) {
317     fprintf(stderr, "PSK buffers too small\n");
318     return 0;
319   }
320
321   BUF_strlcpy(out_identity, config->psk_identity.c_str(),
322               max_identity_len);
323   memcpy(out_psk, config->psk.data(), config->psk.size());
324   return config->psk.size();
325 }
326
327 static unsigned PskServerCallback(SSL *ssl, const char *identity,
328                                   uint8_t *out_psk, unsigned max_psk_len) {
329   const TestConfig *config = GetTestConfig(ssl);
330
331   if (strcmp(identity, config->psk_identity.c_str()) != 0) {
332     fprintf(stderr, "Client PSK identity did not match.\n");
333     return 0;
334   }
335
336   if (config->psk.size() > max_psk_len) {
337     fprintf(stderr, "PSK buffers too small\n");
338     return 0;
339   }
340
341   memcpy(out_psk, config->psk.data(), config->psk.size());
342   return config->psk.size();
343 }
344
345 static int CertCallback(SSL *ssl, void *arg) {
346   const TestConfig *config = GetTestConfig(ssl);
347
348   // Check the CertificateRequest metadata is as expected.
349   //
350   // TODO(davidben): Test |SSL_get_client_CA_list|.
351   if (!SSL_is_server(ssl) &&
352       !config->expected_certificate_types.empty()) {
353     const uint8_t *certificate_types;
354     size_t certificate_types_len =
355         SSL_get0_certificate_types(ssl, &certificate_types);
356     if (certificate_types_len != config->expected_certificate_types.size() ||
357         memcmp(certificate_types,
358                config->expected_certificate_types.data(),
359                certificate_types_len) != 0) {
360       fprintf(stderr, "certificate types mismatch\n");
361       return 0;
362     }
363   }
364
365   // The certificate will be installed via other means.
366   if (!config->async || config->use_early_callback ||
367       config->use_old_client_cert_callback) {
368     return 1;
369   }
370
371   if (!GetTestState(ssl)->cert_ready) {
372     return -1;
373   }
374   if (!InstallCertificate(ssl)) {
375     return 0;
376   }
377   return 1;
378 }
379
380 static void InfoCallback(const SSL *ssl, int type, int val) {
381   if (type == SSL_CB_HANDSHAKE_DONE) {
382     if (GetTestConfig(ssl)->handshake_never_done) {
383       fprintf(stderr, "Handshake unexpectedly completed.\n");
384       // Abort before any expected error code is printed, to ensure the overall
385       // test fails.
386       abort();
387     }
388     GetTestState(ssl)->handshake_done = true;
389
390     // Callbacks may be called again on a new handshake.
391     GetTestState(ssl)->ticket_decrypt_done = false;
392     GetTestState(ssl)->alpn_select_done = false;
393   }
394 }
395
396 static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
397   GetTestState(ssl)->got_new_session = true;
398   GetTestState(ssl)->new_session.reset(session);
399   return 1;
400 }
401
402 static int TicketKeyCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv,
403                              EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
404                              int encrypt) {
405   if (!encrypt) {
406     if (GetTestState(ssl)->ticket_decrypt_done) {
407       fprintf(stderr, "TicketKeyCallback called after completion.\n");
408       return -1;
409     }
410
411     GetTestState(ssl)->ticket_decrypt_done = true;
412   }
413
414   // This is just test code, so use the all-zeros key.
415   static const uint8_t kZeros[16] = {0};
416
417   if (encrypt) {
418     memcpy(key_name, kZeros, sizeof(kZeros));
419     RAND_bytes(iv, 16);
420   } else if (memcmp(key_name, kZeros, 16) != 0) {
421     return 0;
422   }
423
424   if (!HMAC_Init_ex(hmac_ctx, kZeros, sizeof(kZeros), EVP_sha256(), NULL) ||
425       !EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, kZeros, iv, encrypt)) {
426     return -1;
427   }
428
429   if (!encrypt) {
430     return GetTestConfig(ssl)->renew_ticket ? 2 : 1;
431   }
432   return 1;
433 }
434
435 // kCustomExtensionValue is the extension value that the custom extension
436 // callbacks will add.
437 static const uint16_t kCustomExtensionValue = 1234;
438 static void *const kCustomExtensionAddArg =
439     reinterpret_cast<void *>(kCustomExtensionValue);
440 static void *const kCustomExtensionParseArg =
441     reinterpret_cast<void *>(kCustomExtensionValue + 1);
442 static const char kCustomExtensionContents[] = "custom extension";
443
444 static int CustomExtensionAddCallback(SSL *ssl, unsigned extension_value,
445                                       const uint8_t **out, size_t *out_len,
446                                       int *out_alert_value, void *add_arg) {
447   if (extension_value != kCustomExtensionValue ||
448       add_arg != kCustomExtensionAddArg) {
449     abort();
450   }
451
452   if (GetTestConfig(ssl)->custom_extension_skip) {
453     return 0;
454   }
455   if (GetTestConfig(ssl)->custom_extension_fail_add) {
456     return -1;
457   }
458
459   *out = reinterpret_cast<const uint8_t*>(kCustomExtensionContents);
460   *out_len = sizeof(kCustomExtensionContents) - 1;
461
462   return 1;
463 }
464
465 static void CustomExtensionFreeCallback(SSL *ssl, unsigned extension_value,
466                                         const uint8_t *out, void *add_arg) {
467   if (extension_value != kCustomExtensionValue ||
468       add_arg != kCustomExtensionAddArg ||
469       out != reinterpret_cast<const uint8_t *>(kCustomExtensionContents)) {
470     abort();
471   }
472 }
473
474 static int CustomExtensionParseCallback(SSL *ssl, unsigned extension_value,
475                                         const uint8_t *contents,
476                                         size_t contents_len,
477                                         int *out_alert_value, void *parse_arg) {
478   if (extension_value != kCustomExtensionValue ||
479       parse_arg != kCustomExtensionParseArg) {
480     abort();
481   }
482
483   if (contents_len != sizeof(kCustomExtensionContents) - 1 ||
484       memcmp(contents, kCustomExtensionContents, contents_len) != 0) {
485     *out_alert_value = SSL_AD_DECODE_ERROR;
486     return 0;
487   }
488
489   return 1;
490 }
491
492 // Connect returns a new socket connected to localhost on |port| or -1 on
493 // error.
494 static int Connect(uint16_t port) {
495   int sock = socket(AF_INET, SOCK_STREAM, 0);
496   if (sock == -1) {
497     PrintSocketError("socket");
498     return -1;
499   }
500   int nodelay = 1;
501   if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
502           reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
503     PrintSocketError("setsockopt");
504     closesocket(sock);
505     return -1;
506   }
507   sockaddr_in sin;
508   memset(&sin, 0, sizeof(sin));
509   sin.sin_family = AF_INET;
510   sin.sin_port = htons(port);
511   if (!inet_pton(AF_INET, "127.0.0.1", &sin.sin_addr)) {
512     PrintSocketError("inet_pton");
513     closesocket(sock);
514     return -1;
515   }
516   if (connect(sock, reinterpret_cast<const sockaddr*>(&sin),
517               sizeof(sin)) != 0) {
518     PrintSocketError("connect");
519     closesocket(sock);
520     return -1;
521   }
522   return sock;
523 }
524
525 class SocketCloser {
526  public:
527   explicit SocketCloser(int sock) : sock_(sock) {}
528   ~SocketCloser() {
529     // Half-close and drain the socket before releasing it. This seems to be
530     // necessary for graceful shutdown on Windows. It will also avoid write
531     // failures in the test runner.
532 #if defined(OPENSSL_WINDOWS)
533     shutdown(sock_, SD_SEND);
534 #else
535     shutdown(sock_, SHUT_WR);
536 #endif
537     while (true) {
538       char buf[1024];
539       if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
540         break;
541       }
542     }
543     closesocket(sock_);
544   }
545
546  private:
547   const int sock_;
548 };
549
550 static bssl::UniquePtr<SSL_CTX> SetupCtx(const TestConfig *config) {
551   bssl::UniquePtr<SSL_CTX> ssl_ctx(SSL_CTX_new(
552       config->is_dtls ? DTLS_method() : TLS_method()));
553   if (!ssl_ctx) {
554     return nullptr;
555   }
556
557   SSL_CTX_set_security_level(ssl_ctx.get(), 0);
558 #if 0
559   /* Disabled for now until we have some TLS1.3 support */
560   // Enable TLS 1.3 for tests.
561   if (!config->is_dtls &&
562       !SSL_CTX_set_max_proto_version(ssl_ctx.get(), TLS1_3_VERSION)) {
563     return nullptr;
564   }
565 #endif
566
567   std::string cipher_list = "ALL";
568   if (!config->cipher.empty()) {
569     cipher_list = config->cipher;
570     SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE);
571   }
572   if (!SSL_CTX_set_cipher_list(ssl_ctx.get(), cipher_list.c_str())) {
573     return nullptr;
574   }
575
576   if (!config->cipher_tls10.empty() || !config->cipher_tls11.empty()) {
577     fprintf(stderr, "version-specific cipher lists not supported.\n");
578     return nullptr;
579   }
580
581   DH *tmpdh;
582
583   if (config->use_sparse_dh_prime) {
584     BIGNUM *p, *g;
585     p = BN_new();
586     g = BN_new();
587     tmpdh = DH_new();
588     if (p == NULL || g == NULL || tmpdh == NULL) {
589         BN_free(p);
590         BN_free(g);
591         DH_free(tmpdh);
592         return nullptr;
593     }
594     // This prime number is 2^1024 + 643 â€“ a value just above a power of two.
595     // Because of its form, values modulo it are essentially certain to be one
596     // byte shorter. This is used to test padding of these values.
597     if (BN_hex2bn(
598             &p,
599             "1000000000000000000000000000000000000000000000000000000000000000"
600             "0000000000000000000000000000000000000000000000000000000000000000"
601             "0000000000000000000000000000000000000000000000000000000000000000"
602             "0000000000000000000000000000000000000000000000000000000000000028"
603             "3") == 0 ||
604         !BN_set_word(g, 2)) {
605       BN_free(p);
606       BN_free(g);
607       DH_free(tmpdh);
608       return nullptr;
609     }
610     DH_set0_pqg(tmpdh, p, NULL, g);
611   } else {
612       tmpdh = DH_get_2048_256();
613   }
614
615   bssl::UniquePtr<DH> dh(tmpdh);
616
617   if (!dh || !SSL_CTX_set_tmp_dh(ssl_ctx.get(), dh.get())) {
618     return nullptr;
619   }
620
621   SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
622
623   if (config->use_old_client_cert_callback) {
624     SSL_CTX_set_client_cert_cb(ssl_ctx.get(), ClientCertCallback);
625   }
626
627   SSL_CTX_set_next_protos_advertised_cb(
628       ssl_ctx.get(), NextProtosAdvertisedCallback, NULL);
629   if (!config->select_next_proto.empty()) {
630     SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
631                                      NULL);
632   }
633
634   if (!config->select_alpn.empty() || config->decline_alpn) {
635     SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
636   }
637
638   SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
639   SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback);
640
641   if (config->use_ticket_callback) {
642     SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx.get(), TicketKeyCallback);
643   }
644
645   if (config->enable_client_custom_extension &&
646       !SSL_CTX_add_client_custom_ext(
647           ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
648           CustomExtensionFreeCallback, kCustomExtensionAddArg,
649           CustomExtensionParseCallback, kCustomExtensionParseArg)) {
650     return nullptr;
651   }
652
653   if (config->enable_server_custom_extension &&
654       !SSL_CTX_add_server_custom_ext(
655           ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
656           CustomExtensionFreeCallback, kCustomExtensionAddArg,
657           CustomExtensionParseCallback, kCustomExtensionParseArg)) {
658     return nullptr;
659   }
660
661   if (config->verify_fail) {
662     SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifyFail, NULL);
663   } else {
664     SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifySucceed, NULL);
665   }
666
667   if (!config->signed_cert_timestamps.empty()) {
668     fprintf(stderr, "SCTs not supported.\n");
669     return nullptr;
670   }
671
672   if (config->use_null_client_ca_list) {
673     SSL_CTX_set_client_CA_list(ssl_ctx.get(), nullptr);
674   }
675
676   return ssl_ctx;
677 }
678
679 // RetryAsync is called after a failed operation on |ssl| with return code
680 // |ret|. If the operation should be retried, it simulates one asynchronous
681 // event and returns true. Otherwise it returns false.
682 static bool RetryAsync(SSL *ssl, int ret) {
683   // No error; don't retry.
684   if (ret >= 0) {
685     return false;
686   }
687
688   TestState *test_state = GetTestState(ssl);
689   assert(GetTestConfig(ssl)->async);
690
691   if (test_state->packeted_bio != nullptr &&
692       PacketedBioAdvanceClock(test_state->packeted_bio)) {
693     // The DTLS retransmit logic silently ignores write failures. So the test
694     // may progress, allow writes through synchronously.
695     AsyncBioEnforceWriteQuota(test_state->async_bio, false);
696     int timeout_ret = DTLSv1_handle_timeout(ssl);
697     AsyncBioEnforceWriteQuota(test_state->async_bio, true);
698
699     if (timeout_ret < 0) {
700       fprintf(stderr, "Error retransmitting.\n");
701       return false;
702     }
703     return true;
704   }
705
706   // See if we needed to read or write more. If so, allow one byte through on
707   // the appropriate end to maximally stress the state machine.
708   switch (SSL_get_error(ssl, ret)) {
709     case SSL_ERROR_WANT_READ:
710       AsyncBioAllowRead(test_state->async_bio, 1);
711       return true;
712     case SSL_ERROR_WANT_WRITE:
713       AsyncBioAllowWrite(test_state->async_bio, 1);
714       return true;
715     case SSL_ERROR_WANT_X509_LOOKUP:
716       test_state->cert_ready = true;
717       return true;
718     default:
719       return false;
720   }
721 }
722
723 // DoRead reads from |ssl|, resolving any asynchronous operations. It returns
724 // the result value of the final |SSL_read| call.
725 static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
726   const TestConfig *config = GetTestConfig(ssl);
727   TestState *test_state = GetTestState(ssl);
728   int ret;
729   do {
730     if (config->async) {
731       // The DTLS retransmit logic silently ignores write failures. So the test
732       // may progress, allow writes through synchronously. |SSL_read| may
733       // trigger a retransmit, so disconnect the write quota.
734       AsyncBioEnforceWriteQuota(test_state->async_bio, false);
735     }
736     ret = config->peek_then_read ? SSL_peek(ssl, out, max_out)
737                                  : SSL_read(ssl, out, max_out);
738     if (config->async) {
739       AsyncBioEnforceWriteQuota(test_state->async_bio, true);
740     }
741   } while (config->async && RetryAsync(ssl, ret));
742
743   if (config->peek_then_read && ret > 0) {
744     std::unique_ptr<uint8_t[]> buf(new uint8_t[static_cast<size_t>(ret)]);
745
746     // SSL_peek should synchronously return the same data.
747     int ret2 = SSL_peek(ssl, buf.get(), ret);
748     if (ret2 != ret ||
749         memcmp(buf.get(), out, ret) != 0) {
750       fprintf(stderr, "First and second SSL_peek did not match.\n");
751       return -1;
752     }
753
754     // SSL_read should synchronously return the same data and consume it.
755     ret2 = SSL_read(ssl, buf.get(), ret);
756     if (ret2 != ret ||
757         memcmp(buf.get(), out, ret) != 0) {
758       fprintf(stderr, "SSL_peek and SSL_read did not match.\n");
759       return -1;
760     }
761   }
762
763   return ret;
764 }
765
766 // WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
767 // operations. It returns the result of the final |SSL_write| call.
768 static int WriteAll(SSL *ssl, const uint8_t *in, size_t in_len) {
769   const TestConfig *config = GetTestConfig(ssl);
770   int ret;
771   do {
772     ret = SSL_write(ssl, in, in_len);
773     if (ret > 0) {
774       in += ret;
775       in_len -= ret;
776     }
777   } while ((config->async && RetryAsync(ssl, ret)) || (ret > 0 && in_len > 0));
778   return ret;
779 }
780
781 // DoShutdown calls |SSL_shutdown|, resolving any asynchronous operations. It
782 // returns the result of the final |SSL_shutdown| call.
783 static int DoShutdown(SSL *ssl) {
784   const TestConfig *config = GetTestConfig(ssl);
785   int ret;
786   do {
787     ret = SSL_shutdown(ssl);
788   } while (config->async && RetryAsync(ssl, ret));
789   return ret;
790 }
791
792 static uint16_t GetProtocolVersion(const SSL *ssl) {
793   uint16_t version = SSL_version(ssl);
794   if (!SSL_is_dtls(ssl)) {
795     return version;
796   }
797   return 0x0201 + ~version;
798 }
799
800 // CheckHandshakeProperties checks, immediately after |ssl| completes its
801 // initial handshake (or False Starts), whether all the properties are
802 // consistent with the test configuration and invariants.
803 static bool CheckHandshakeProperties(SSL *ssl, bool is_resume) {
804   const TestConfig *config = GetTestConfig(ssl);
805
806   if (SSL_get_current_cipher(ssl) == nullptr) {
807     fprintf(stderr, "null cipher after handshake\n");
808     return false;
809   }
810
811   if (is_resume &&
812       (!!SSL_session_reused(ssl) == config->expect_session_miss)) {
813     fprintf(stderr, "session was%s reused\n",
814             SSL_session_reused(ssl) ? "" : " not");
815     return false;
816   }
817
818   bool expect_handshake_done = is_resume || !config->false_start;
819   if (expect_handshake_done != GetTestState(ssl)->handshake_done) {
820     fprintf(stderr, "handshake was%s completed\n",
821             GetTestState(ssl)->handshake_done ? "" : " not");
822     return false;
823   }
824
825   if (expect_handshake_done && !config->is_server) {
826     bool expect_new_session =
827         !config->expect_no_session &&
828         (!SSL_session_reused(ssl) || config->expect_ticket_renewal) &&
829         // Session tickets are sent post-handshake in TLS 1.3.
830         GetProtocolVersion(ssl) < TLS1_3_VERSION;
831     if (expect_new_session != GetTestState(ssl)->got_new_session) {
832       fprintf(stderr,
833               "new session was%s cached, but we expected the opposite\n",
834               GetTestState(ssl)->got_new_session ? "" : " not");
835       return false;
836     }
837   }
838
839   if (!config->expected_server_name.empty()) {
840     const char *server_name =
841         SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
842     if (server_name != config->expected_server_name) {
843       fprintf(stderr, "servername mismatch (got %s; want %s)\n",
844               server_name, config->expected_server_name.c_str());
845       return false;
846     }
847   }
848
849   if (!config->expected_next_proto.empty()) {
850     const uint8_t *next_proto;
851     unsigned next_proto_len;
852     SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
853     if (next_proto_len != config->expected_next_proto.size() ||
854         memcmp(next_proto, config->expected_next_proto.data(),
855                next_proto_len) != 0) {
856       fprintf(stderr, "negotiated next proto mismatch\n");
857       return false;
858     }
859   }
860
861   if (!config->expected_alpn.empty()) {
862     const uint8_t *alpn_proto;
863     unsigned alpn_proto_len;
864     SSL_get0_alpn_selected(ssl, &alpn_proto, &alpn_proto_len);
865     if (alpn_proto_len != config->expected_alpn.size() ||
866         memcmp(alpn_proto, config->expected_alpn.data(),
867                alpn_proto_len) != 0) {
868       fprintf(stderr, "negotiated alpn proto mismatch\n");
869       return false;
870     }
871   }
872
873   if (config->expect_extended_master_secret) {
874     if (!SSL_get_extms_support(ssl)) {
875       fprintf(stderr, "No EMS for connection when expected");
876       return false;
877     }
878   }
879
880   if (config->expect_verify_result) {
881     int expected_verify_result = config->verify_fail ?
882       X509_V_ERR_APPLICATION_VERIFICATION :
883       X509_V_OK;
884
885     if (SSL_get_verify_result(ssl) != expected_verify_result) {
886       fprintf(stderr, "Wrong certificate verification result\n");
887       return false;
888     }
889   }
890
891   if (!config->psk.empty()) {
892     if (SSL_get_peer_cert_chain(ssl) != nullptr) {
893       fprintf(stderr, "Received peer certificate on a PSK cipher.\n");
894       return false;
895     }
896   } else if (!config->is_server || config->require_any_client_certificate) {
897     if (SSL_get_peer_cert_chain(ssl) == nullptr) {
898       fprintf(stderr, "Received no peer certificate but expected one.\n");
899       return false;
900     }
901   }
902
903   return true;
904 }
905
906 // DoExchange runs a test SSL exchange against the peer. On success, it returns
907 // true and sets |*out_session| to the negotiated SSL session. If the test is a
908 // resumption attempt, |is_resume| is true and |session| is the session from the
909 // previous exchange.
910 static bool DoExchange(bssl::UniquePtr<SSL_SESSION> *out_session,
911                        SSL_CTX *ssl_ctx, const TestConfig *config,
912                        bool is_resume, SSL_SESSION *session) {
913   bssl::UniquePtr<SSL> ssl(SSL_new(ssl_ctx));
914   if (!ssl) {
915     return false;
916   }
917
918   if (!SetTestConfig(ssl.get(), config) ||
919       !SetTestState(ssl.get(), std::unique_ptr<TestState>(new TestState))) {
920     return false;
921   }
922
923   if (config->fallback_scsv &&
924       !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
925     return false;
926   }
927   // Install the certificate synchronously if nothing else will handle it.
928   if (!config->use_early_callback &&
929       !config->use_old_client_cert_callback &&
930       !config->async &&
931       !InstallCertificate(ssl.get())) {
932     return false;
933   }
934   SSL_set_cert_cb(ssl.get(), CertCallback, nullptr);
935   if (config->require_any_client_certificate) {
936     SSL_set_verify(ssl.get(), SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
937                    NULL);
938   }
939   if (config->verify_peer) {
940     SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, NULL);
941   }
942   if (config->false_start) {
943     fprintf(stderr, "False Start not supported\n");
944     return false;
945   }
946   if (config->partial_write) {
947     SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
948   }
949   if (config->no_tls13) {
950     SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_3);
951   }
952   if (config->no_tls12) {
953     SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
954   }
955   if (config->no_tls11) {
956     SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
957   }
958   if (config->no_tls1) {
959     SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
960   }
961   if (config->no_ssl3) {
962     SSL_set_options(ssl.get(), SSL_OP_NO_SSLv3);
963   }
964   if (!config->expected_channel_id.empty()) {
965     fprintf(stderr, "Channel ID not supported\n");
966     return false;
967   }
968   if (!config->send_channel_id.empty()) {
969     fprintf(stderr, "Channel ID not supported\n");
970     return false;
971   }
972   if (!config->host_name.empty() &&
973       !SSL_set_tlsext_host_name(ssl.get(), config->host_name.c_str())) {
974     return false;
975   }
976   if (!config->advertise_alpn.empty() &&
977       SSL_set_alpn_protos(ssl.get(),
978                           (const uint8_t *)config->advertise_alpn.data(),
979                           config->advertise_alpn.size()) != 0) {
980     return false;
981   }
982   if (!config->psk.empty()) {
983     SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
984     SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
985   }
986   if (!config->psk_identity.empty() &&
987       !SSL_use_psk_identity_hint(ssl.get(), config->psk_identity.c_str())) {
988     return false;
989   }
990   if (!config->srtp_profiles.empty() &&
991       SSL_set_tlsext_use_srtp(ssl.get(), config->srtp_profiles.c_str())) {
992     return false;
993   }
994   if (config->enable_ocsp_stapling) {
995     fprintf(stderr, "OCSP stapling not supported (with the same API).\n");
996     return false;
997   }
998   if (config->enable_signed_cert_timestamps) {
999     fprintf(stderr, "SCTs not supported (with the same API).\n");
1000     return false;
1001   }
1002   if (config->min_version != 0 &&
1003       !SSL_set_min_proto_version(ssl.get(), (uint16_t)config->min_version)) {
1004     return false;
1005   }
1006   if (config->max_version != 0 &&
1007       !SSL_set_max_proto_version(ssl.get(), (uint16_t)config->max_version)) {
1008     return false;
1009   }
1010   if (config->mtu != 0) {
1011     SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
1012     SSL_set_mtu(ssl.get(), config->mtu);
1013   }
1014   if (config->install_ddos_callback) {
1015     fprintf(stderr, "DDoS callback not supported.\n");
1016     return false;
1017   }
1018   if (config->renegotiate_once) {
1019     fprintf(stderr, "renegotiate_once not supported.\n");
1020     return false;
1021   }
1022   if (config->renegotiate_freely) {
1023     // This is always on for OpenSSL.
1024   }
1025   if (config->renegotiate_ignore) {
1026     fprintf(stderr, "renegotiate_ignore not supported.\n");
1027     return false;
1028   }
1029   if (!config->check_close_notify) {
1030     SSL_set_quiet_shutdown(ssl.get(), 1);
1031   }
1032   if (config->disable_npn) {
1033     fprintf(stderr, "SSL_OP_DISABLE_NPN not supported.\n");
1034     return false;
1035   }
1036   if (config->p384_only) {
1037     int nid = NID_secp384r1;
1038     if (!SSL_set1_curves(ssl.get(), &nid, 1)) {
1039       return false;
1040     }
1041   }
1042   if (config->enable_all_curves) {
1043     static const int kAllCurves[] = {
1044       NID_X9_62_prime256v1, NID_secp384r1, NID_secp521r1, NID_X25519,
1045     };
1046     if (!SSL_set1_curves(ssl.get(), kAllCurves,
1047                          OPENSSL_ARRAY_SIZE(kAllCurves))) {
1048       return false;
1049     }
1050   }
1051   if (config->initial_timeout_duration_ms > 0) {
1052     fprintf(stderr, "Setting DTLS initial timeout duration not supported.\n");
1053     return false;
1054   }
1055   if (config->max_cert_list > 0) {
1056     SSL_set_max_cert_list(ssl.get(), config->max_cert_list);
1057   }
1058
1059   int sock = Connect(config->port);
1060   if (sock == -1) {
1061     return false;
1062   }
1063   SocketCloser closer(sock);
1064
1065   bssl::UniquePtr<BIO> bio(BIO_new_socket(sock, BIO_NOCLOSE));
1066   if (!bio) {
1067     return false;
1068   }
1069   if (config->is_dtls) {
1070     bssl::UniquePtr<BIO> packeted = PacketedBioCreate(!config->async);
1071     if (!packeted) {
1072       return false;
1073     }
1074     GetTestState(ssl.get())->packeted_bio = packeted.get();
1075     BIO_push(packeted.get(), bio.release());
1076     bio = std::move(packeted);
1077   }
1078   if (config->async) {
1079     bssl::UniquePtr<BIO> async_scoped =
1080         config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
1081     if (!async_scoped) {
1082       return false;
1083     }
1084     BIO_push(async_scoped.get(), bio.release());
1085     GetTestState(ssl.get())->async_bio = async_scoped.get();
1086     bio = std::move(async_scoped);
1087   }
1088   SSL_set_bio(ssl.get(), bio.get(), bio.get());
1089   bio.release();  // SSL_set_bio takes ownership.
1090
1091   if (session != NULL) {
1092     if (!config->is_server) {
1093       if (SSL_set_session(ssl.get(), session) != 1) {
1094         return false;
1095       }
1096     }
1097   }
1098
1099 #if 0
1100   // KNOWN BUG: OpenSSL's SSL_get_current_cipher behaves incorrectly when
1101   // offering resumption.
1102   if (SSL_get_current_cipher(ssl.get()) != nullptr) {
1103     fprintf(stderr, "non-null cipher before handshake\n");
1104     return false;
1105   }
1106 #endif
1107
1108   int ret;
1109   if (config->implicit_handshake) {
1110     if (config->is_server) {
1111       SSL_set_accept_state(ssl.get());
1112     } else {
1113       SSL_set_connect_state(ssl.get());
1114     }
1115   } else {
1116     do {
1117       if (config->is_server) {
1118         ret = SSL_accept(ssl.get());
1119       } else {
1120         ret = SSL_connect(ssl.get());
1121       }
1122     } while (config->async && RetryAsync(ssl.get(), ret));
1123     if (ret != 1 ||
1124         !CheckHandshakeProperties(ssl.get(), is_resume)) {
1125       return false;
1126     }
1127
1128     // Reset the state to assert later that the callback isn't called in
1129     // renegotations.
1130     GetTestState(ssl.get())->got_new_session = false;
1131   }
1132
1133   if (config->export_keying_material > 0) {
1134     std::vector<uint8_t> result(
1135         static_cast<size_t>(config->export_keying_material));
1136     if (SSL_export_keying_material(
1137             ssl.get(), result.data(), result.size(),
1138             config->export_label.data(), config->export_label.size(),
1139             reinterpret_cast<const uint8_t*>(config->export_context.data()),
1140             config->export_context.size(), config->use_export_context) != 1) {
1141       fprintf(stderr, "failed to export keying material\n");
1142       return false;
1143     }
1144     if (WriteAll(ssl.get(), result.data(), result.size()) < 0) {
1145       return false;
1146     }
1147   }
1148
1149   if (config->tls_unique) {
1150     fprintf(stderr, "tls_unique not supported\n");
1151     return false;
1152   }
1153
1154   if (config->send_alert) {
1155     fprintf(stderr, "Sending an alert not supported\n");
1156     return false;
1157   }
1158
1159   if (config->write_different_record_sizes) {
1160     if (config->is_dtls) {
1161       fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
1162       return false;
1163     }
1164     // This mode writes a number of different record sizes in an attempt to
1165     // trip up the CBC record splitting code.
1166     static const size_t kBufLen = 32769;
1167     std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1168     memset(buf.get(), 0x42, kBufLen);
1169     static const size_t kRecordSizes[] = {
1170         0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
1171     for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kRecordSizes); i++) {
1172       const size_t len = kRecordSizes[i];
1173       if (len > kBufLen) {
1174         fprintf(stderr, "Bad kRecordSizes value.\n");
1175         return false;
1176       }
1177       if (WriteAll(ssl.get(), buf.get(), len) < 0) {
1178         return false;
1179       }
1180     }
1181   } else {
1182     if (config->shim_writes_first) {
1183       if (WriteAll(ssl.get(), reinterpret_cast<const uint8_t *>("hello"),
1184                    5) < 0) {
1185         return false;
1186       }
1187     }
1188     if (!config->shim_shuts_down) {
1189       for (;;) {
1190         static const size_t kBufLen = 16384;
1191         std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1192
1193         // Read only 512 bytes at a time in TLS to ensure records may be
1194         // returned in multiple reads.
1195         int n = DoRead(ssl.get(), buf.get(), config->is_dtls ? kBufLen : 512);
1196         int err = SSL_get_error(ssl.get(), n);
1197         if (err == SSL_ERROR_ZERO_RETURN ||
1198             (n == 0 && err == SSL_ERROR_SYSCALL)) {
1199           if (n != 0) {
1200             fprintf(stderr, "Invalid SSL_get_error output\n");
1201             return false;
1202           }
1203           // Stop on either clean or unclean shutdown.
1204           break;
1205         } else if (err != SSL_ERROR_NONE) {
1206           if (n > 0) {
1207             fprintf(stderr, "Invalid SSL_get_error output\n");
1208             return false;
1209           }
1210           return false;
1211         }
1212         // Successfully read data.
1213         if (n <= 0) {
1214           fprintf(stderr, "Invalid SSL_get_error output\n");
1215           return false;
1216         }
1217
1218         // After a successful read, with or without False Start, the handshake
1219         // must be complete.
1220         if (!GetTestState(ssl.get())->handshake_done) {
1221           fprintf(stderr, "handshake was not completed after SSL_read\n");
1222           return false;
1223         }
1224
1225         for (int i = 0; i < n; i++) {
1226           buf[i] ^= 0xff;
1227         }
1228         if (WriteAll(ssl.get(), buf.get(), n) < 0) {
1229           return false;
1230         }
1231       }
1232     }
1233   }
1234
1235   if (!config->is_server && !config->false_start &&
1236       !config->implicit_handshake &&
1237       // Session tickets are sent post-handshake in TLS 1.3.
1238       GetProtocolVersion(ssl.get()) < TLS1_3_VERSION &&
1239       GetTestState(ssl.get())->got_new_session) {
1240     fprintf(stderr, "new session was established after the handshake\n");
1241     return false;
1242   }
1243
1244   if (GetProtocolVersion(ssl.get()) >= TLS1_3_VERSION && !config->is_server) {
1245     bool expect_new_session =
1246         !config->expect_no_session && !config->shim_shuts_down;
1247     if (expect_new_session != GetTestState(ssl.get())->got_new_session) {
1248       fprintf(stderr,
1249               "new session was%s cached, but we expected the opposite\n",
1250               GetTestState(ssl.get())->got_new_session ? "" : " not");
1251       return false;
1252     }
1253   }
1254
1255   if (out_session) {
1256     *out_session = std::move(GetTestState(ssl.get())->new_session);
1257   }
1258
1259   ret = DoShutdown(ssl.get());
1260
1261   if (config->shim_shuts_down && config->check_close_notify) {
1262     // We initiate shutdown, so |SSL_shutdown| will return in two stages. First
1263     // it returns zero when our close_notify is sent, then one when the peer's
1264     // is received.
1265     if (ret != 0) {
1266       fprintf(stderr, "Unexpected SSL_shutdown result: %d != 0\n", ret);
1267       return false;
1268     }
1269     ret = DoShutdown(ssl.get());
1270   }
1271
1272   if (ret != 1) {
1273     fprintf(stderr, "Unexpected SSL_shutdown result: %d != 1\n", ret);
1274     return false;
1275   }
1276
1277   if (SSL_total_renegotiations(ssl.get()) !=
1278       config->expect_total_renegotiations) {
1279     fprintf(stderr, "Expected %d renegotiations, got %ld\n",
1280             config->expect_total_renegotiations,
1281             SSL_total_renegotiations(ssl.get()));
1282     return false;
1283   }
1284
1285   return true;
1286 }
1287
1288 class StderrDelimiter {
1289  public:
1290   ~StderrDelimiter() { fprintf(stderr, "--- DONE ---\n"); }
1291 };
1292
1293 static int Main(int argc, char **argv) {
1294   // To distinguish ASan's output from ours, add a trailing message to stderr.
1295   // Anything following this line will be considered an error.
1296   StderrDelimiter delimiter;
1297
1298 #if defined(OPENSSL_WINDOWS)
1299   /* Initialize Winsock. */
1300   WORD wsa_version = MAKEWORD(2, 2);
1301   WSADATA wsa_data;
1302   int wsa_err = WSAStartup(wsa_version, &wsa_data);
1303   if (wsa_err != 0) {
1304     fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
1305     return 1;
1306   }
1307   if (wsa_data.wVersion != wsa_version) {
1308     fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
1309     return 1;
1310   }
1311 #else
1312   signal(SIGPIPE, SIG_IGN);
1313 #endif
1314
1315   OPENSSL_init_crypto(0, NULL);
1316   OPENSSL_init_ssl(0, NULL);
1317   g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
1318   g_state_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, TestStateExFree);
1319   if (g_config_index < 0 || g_state_index < 0) {
1320     return 1;
1321   }
1322
1323   TestConfig config;
1324   if (!ParseConfig(argc - 1, argv + 1, &config)) {
1325     return Usage(argv[0]);
1326   }
1327
1328   bssl::UniquePtr<SSL_CTX> ssl_ctx = SetupCtx(&config);
1329   if (!ssl_ctx) {
1330     ERR_print_errors_fp(stderr);
1331     return 1;
1332   }
1333
1334   bssl::UniquePtr<SSL_SESSION> session;
1335   for (int i = 0; i < config.resume_count + 1; i++) {
1336     bool is_resume = i > 0;
1337     if (is_resume && !config.is_server && !session) {
1338       fprintf(stderr, "No session to offer.\n");
1339       return 1;
1340     }
1341
1342     bssl::UniquePtr<SSL_SESSION> offer_session = std::move(session);
1343     if (!DoExchange(&session, ssl_ctx.get(), &config, is_resume,
1344                     offer_session.get())) {
1345       fprintf(stderr, "Connection %d failed.\n", i + 1);
1346       ERR_print_errors_fp(stderr);
1347       return 1;
1348     }
1349   }
1350
1351   return 0;
1352 }
1353
1354 }  // namespace bssl
1355
1356 int main(int argc, char **argv) {
1357   return bssl::Main(argc, argv);
1358 }