Upstream version 10.39.225.0
[platform/framework/web/crosswalk.git] / src / third_party / boringssl / src / ssl / ssl_lib.c
1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  * 
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  * 
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  * 
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from 
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  * 
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  * 
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57 /* ====================================================================
58  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
59  *
60  * Redistribution and use in source and binary forms, with or without
61  * modification, are permitted provided that the following conditions
62  * are met:
63  *
64  * 1. Redistributions of source code must retain the above copyright
65  *    notice, this list of conditions and the following disclaimer. 
66  *
67  * 2. Redistributions in binary form must reproduce the above copyright
68  *    notice, this list of conditions and the following disclaimer in
69  *    the documentation and/or other materials provided with the
70  *    distribution.
71  *
72  * 3. All advertising materials mentioning features or use of this
73  *    software must display the following acknowledgment:
74  *    "This product includes software developed by the OpenSSL Project
75  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76  *
77  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78  *    endorse or promote products derived from this software without
79  *    prior written permission. For written permission, please contact
80  *    openssl-core@openssl.org.
81  *
82  * 5. Products derived from this software may not be called "OpenSSL"
83  *    nor may "OpenSSL" appear in their names without prior written
84  *    permission of the OpenSSL Project.
85  *
86  * 6. Redistributions of any form whatsoever must retain the following
87  *    acknowledgment:
88  *    "This product includes software developed by the OpenSSL Project
89  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90  *
91  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
95  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102  * OF THE POSSIBILITY OF SUCH DAMAGE.
103  * ====================================================================
104  *
105  * This product includes cryptographic software written by Eric Young
106  * (eay@cryptsoft.com).  This product includes software written by Tim
107  * Hudson (tjh@cryptsoft.com).
108  *
109  */
110 /* ====================================================================
111  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
112  * ECC cipher suite support in OpenSSL originally developed by 
113  * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
114  */
115 /* ====================================================================
116  * Copyright 2005 Nokia. All rights reserved.
117  *
118  * The portions of the attached software ("Contribution") is developed by
119  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
120  * license.
121  *
122  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
123  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
124  * support (see RFC 4279) to OpenSSL.
125  *
126  * No patent licenses or other rights except those expressly stated in
127  * the OpenSSL open source license shall be deemed granted or received
128  * expressly, by implication, estoppel, or otherwise.
129  *
130  * No assurances are provided by Nokia that the Contribution does not
131  * infringe the patent or other intellectual property rights of any third
132  * party or that the license provides you with all the necessary rights
133  * to make use of the Contribution.
134  *
135  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
136  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
137  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
138  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
139  * OTHERWISE. */
140
141 #include <stdio.h>
142 #include <assert.h>
143
144 #include <openssl/bytestring.h>
145 #include <openssl/dh.h>
146 #include <openssl/engine.h>
147 #include <openssl/lhash.h>
148 #include <openssl/mem.h>
149 #include <openssl/obj.h>
150 #include <openssl/rand.h>
151 #include <openssl/x509v3.h>
152
153 #include "ssl_locl.h"
154
155 SSL3_ENC_METHOD ssl3_undef_enc_method={
156         /* evil casts, but these functions are only called if there's a library bug */
157         (int (*)(SSL *,int))ssl_undefined_function,
158         (int (*)(SSL *, unsigned char *, int))ssl_undefined_function,
159         ssl_undefined_function,
160         (int (*)(SSL *, unsigned char *, unsigned char *, int))ssl_undefined_function,
161         (int (*)(SSL*, int))ssl_undefined_function,
162         (int (*)(SSL *,  const char*, int, unsigned char *))ssl_undefined_function,
163         0,      /* finish_mac_length */
164         (int (*)(SSL *, int, unsigned char *))ssl_undefined_function,
165         NULL,   /* client_finished_label */
166         0,      /* client_finished_label_len */
167         NULL,   /* server_finished_label */
168         0,      /* server_finished_label_len */
169         (int (*)(int))ssl_undefined_function,
170         (int (*)(SSL *, unsigned char *, size_t, const char *,
171                  size_t, const unsigned char *, size_t,
172                  int use_context)) ssl_undefined_function,
173         };
174
175 /* Some error codes are special. Ensure the make_errors.go script
176  * never regresses this. */
177 OPENSSL_COMPILE_ASSERT(
178         SSL_R_TLSV1_ALERT_NO_RENEGOTIATION ==
179                 SSL_AD_NO_RENEGOTIATION + SSL_AD_REASON_OFFSET,
180         ssl_alert_reason_code_mismatch);
181
182 int SSL_clear(SSL *s)
183         {
184
185         if (s->method == NULL)
186                 {
187                 OPENSSL_PUT_ERROR(SSL, SSL_clear, SSL_R_NO_METHOD_SPECIFIED);
188                 return(0);
189                 }
190
191         if (ssl_clear_bad_session(s))
192                 {
193                 SSL_SESSION_free(s->session);
194                 s->session=NULL;
195                 }
196
197         s->hit=0;
198         s->shutdown=0;
199
200 #if 0 /* Disabled since version 1.10 of this file (early return not
201        * needed because SSL_clear is not called when doing renegotiation) */
202         /* This is set if we are doing dynamic renegotiation so keep
203          * the old cipher.  It is sort of a SSL_clear_lite :-) */
204         if (s->renegotiate) return(1);
205 #else
206         if (s->renegotiate)
207                 {
208                 OPENSSL_PUT_ERROR(SSL, SSL_clear, ERR_R_INTERNAL_ERROR);
209                 return 0;
210                 }
211 #endif
212
213         s->type=0;
214
215         s->state=SSL_ST_BEFORE|((s->server)?SSL_ST_ACCEPT:SSL_ST_CONNECT);
216
217         s->version=s->method->version;
218         s->client_version=s->version;
219         s->rwstate=SSL_NOTHING;
220         s->rstate=SSL_ST_READ_HEADER;
221 #if 0
222         s->read_ahead=s->ctx->read_ahead;
223 #endif
224
225         if (s->init_buf != NULL)
226                 {
227                 BUF_MEM_free(s->init_buf);
228                 s->init_buf=NULL;
229                 }
230
231         ssl_clear_cipher_ctx(s);
232         ssl_clear_hash_ctx(&s->read_hash);
233         ssl_clear_hash_ctx(&s->write_hash);
234
235         s->first_packet=0;
236
237 #if 1
238         /* Check to see if we were changed into a different method, if
239          * so, revert back if we are not doing session-id reuse. */
240         if (!s->in_handshake && (s->session == NULL) && (s->method != s->ctx->method))
241                 {
242                 s->method->ssl_free(s);
243                 s->method=s->ctx->method;
244                 if (!s->method->ssl_new(s))
245                         return(0);
246                 }
247         else
248 #endif
249                 s->method->ssl_clear(s);
250         return(1);
251         }
252
253 /** Used to change an SSL_CTXs default SSL method type */
254 int SSL_CTX_set_ssl_version(SSL_CTX *ctx,const SSL_METHOD *meth)
255         {
256         STACK_OF(SSL_CIPHER) *sk;
257
258         ctx->method=meth;
259
260         sk=ssl_create_cipher_list(
261                 ctx->method, &ctx->cipher_list, &ctx->cipher_list_by_id,
262                 meth->version == SSL2_VERSION ?
263                         "SSLv2" :
264                         SSL_DEFAULT_CIPHER_LIST,
265                 ctx->cert);
266
267         if ((sk == NULL) || (sk_SSL_CIPHER_num(sk) <= 0))
268                 {
269                 OPENSSL_PUT_ERROR(SSL, SSL_CTX_set_ssl_version, SSL_R_SSL_LIBRARY_HAS_NO_CIPHERS);
270                 return(0);
271                 }
272         return(1);
273         }
274
275 SSL *SSL_new(SSL_CTX *ctx)
276         {
277         SSL *s;
278
279         if (ctx == NULL)
280                 {
281                 OPENSSL_PUT_ERROR(SSL, SSL_new, SSL_R_NULL_SSL_CTX);
282                 return(NULL);
283                 }
284         if (ctx->method == NULL)
285                 {
286                 OPENSSL_PUT_ERROR(SSL, SSL_new, SSL_R_SSL_CTX_HAS_NO_DEFAULT_SSL_VERSION);
287                 return(NULL);
288                 }
289
290         s=(SSL *)OPENSSL_malloc(sizeof(SSL));
291         if (s == NULL) goto err;
292         memset(s,0,sizeof(SSL));
293
294         s->options=ctx->options;
295         s->mode=ctx->mode;
296         s->max_cert_list=ctx->max_cert_list;
297
298         if (ctx->cert != NULL)
299                 {
300                 /* Earlier library versions used to copy the pointer to
301                  * the CERT, not its contents; only when setting new
302                  * parameters for the per-SSL copy, ssl_cert_new would be
303                  * called (and the direct reference to the per-SSL_CTX
304                  * settings would be lost, but those still were indirectly
305                  * accessed for various purposes, and for that reason they
306                  * used to be known as s->ctx->default_cert).
307                  * Now we don't look at the SSL_CTX's CERT after having
308                  * duplicated it once. */
309
310                 s->cert = ssl_cert_dup(ctx->cert);
311                 if (s->cert == NULL)
312                         goto err;
313                 }
314         else
315                 s->cert=NULL; /* Cannot really happen (see SSL_CTX_new) */
316
317         s->read_ahead=ctx->read_ahead;
318         s->msg_callback=ctx->msg_callback;
319         s->msg_callback_arg=ctx->msg_callback_arg;
320         s->verify_mode=ctx->verify_mode;
321 #if 0
322         s->verify_depth=ctx->verify_depth;
323 #endif
324         s->sid_ctx_length=ctx->sid_ctx_length;
325         assert(s->sid_ctx_length <= sizeof s->sid_ctx);
326         memcpy(&s->sid_ctx,&ctx->sid_ctx,sizeof(s->sid_ctx));
327         s->verify_callback=ctx->default_verify_callback;
328         s->generate_session_id=ctx->generate_session_id;
329
330         s->param = X509_VERIFY_PARAM_new();
331         if (!s->param)
332                 goto err;
333         X509_VERIFY_PARAM_inherit(s->param, ctx->param);
334 #if 0
335         s->purpose = ctx->purpose;
336         s->trust = ctx->trust;
337 #endif
338         s->quiet_shutdown=ctx->quiet_shutdown;
339         s->max_send_fragment = ctx->max_send_fragment;
340
341         CRYPTO_add(&ctx->references,1,CRYPTO_LOCK_SSL_CTX);
342         s->ctx=ctx;
343         s->tlsext_debug_cb = 0;
344         s->tlsext_debug_arg = NULL;
345         s->tlsext_ticket_expected = 0;
346         CRYPTO_add(&ctx->references,1,CRYPTO_LOCK_SSL_CTX);
347         s->initial_ctx=ctx;
348         if (ctx->tlsext_ecpointformatlist)
349                 {
350                 s->tlsext_ecpointformatlist =
351                         BUF_memdup(ctx->tlsext_ecpointformatlist,
352                                         ctx->tlsext_ecpointformatlist_length);
353                 if (!s->tlsext_ecpointformatlist)
354                         goto err;
355                 s->tlsext_ecpointformatlist_length =
356                                         ctx->tlsext_ecpointformatlist_length;
357                 }
358         if (ctx->tlsext_ellipticcurvelist)
359                 {
360                 s->tlsext_ellipticcurvelist =
361                         BUF_memdup(ctx->tlsext_ellipticcurvelist,
362                                 ctx->tlsext_ellipticcurvelist_length * 2);
363                 if (!s->tlsext_ellipticcurvelist)
364                         goto err;
365                 s->tlsext_ellipticcurvelist_length = 
366                                         ctx->tlsext_ellipticcurvelist_length;
367                 }
368         s->next_proto_negotiated = NULL;
369
370         if (s->ctx->alpn_client_proto_list)
371                 {
372                 s->alpn_client_proto_list = BUF_memdup(
373                         s->ctx->alpn_client_proto_list,
374                         s->ctx->alpn_client_proto_list_len);
375                 if (s->alpn_client_proto_list == NULL)
376                         goto err;
377                 s->alpn_client_proto_list_len = s->ctx->alpn_client_proto_list_len;
378                 }
379
380         s->verify_result=X509_V_OK;
381
382         s->method=ctx->method;
383
384         if (!s->method->ssl_new(s))
385                 goto err;
386
387         s->references=1;
388         s->server=(ctx->method->ssl_accept == ssl_undefined_function)?0:1;
389
390         SSL_clear(s);
391
392         CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL, s, &s->ex_data);
393
394         s->psk_identity_hint = NULL;
395         if (ctx->psk_identity_hint)
396                 {
397                 s->psk_identity_hint = BUF_strdup(ctx->psk_identity_hint);
398                 if (s->psk_identity_hint == NULL)
399                         goto err;
400                 }
401         s->psk_client_callback=ctx->psk_client_callback;
402         s->psk_server_callback=ctx->psk_server_callback;
403
404         if (!s->server)
405                 {
406                 s->signed_cert_timestamps_enabled = s->ctx->signed_cert_timestamps_enabled;
407                 s->ocsp_stapling_enabled = s->ctx->ocsp_stapling_enabled;
408                 }
409
410         return(s);
411 err:
412         if (s != NULL)
413                 {
414                 if (s->cert != NULL)
415                         ssl_cert_free(s->cert);
416                 if (s->ctx != NULL)
417                         SSL_CTX_free(s->ctx); /* decrement reference count */
418                 OPENSSL_free(s);
419                 }
420         OPENSSL_PUT_ERROR(SSL, SSL_new, ERR_R_MALLOC_FAILURE);
421         return(NULL);
422         }
423
424 int SSL_CTX_set_session_id_context(SSL_CTX *ctx,const unsigned char *sid_ctx,
425                                    unsigned int sid_ctx_len)
426     {
427     if(sid_ctx_len > sizeof ctx->sid_ctx)
428         {
429         OPENSSL_PUT_ERROR(SSL, SSL_CTX_set_session_id_context, SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
430         return 0;
431         }
432     ctx->sid_ctx_length=sid_ctx_len;
433     memcpy(ctx->sid_ctx,sid_ctx,sid_ctx_len);
434
435     return 1;
436     }
437
438 int SSL_set_session_id_context(SSL *ssl,const unsigned char *sid_ctx,
439                                unsigned int sid_ctx_len)
440     {
441     if(sid_ctx_len > SSL_MAX_SID_CTX_LENGTH)
442         {
443         OPENSSL_PUT_ERROR(SSL, SSL_set_session_id_context, SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
444         return 0;
445         }
446     ssl->sid_ctx_length=sid_ctx_len;
447     memcpy(ssl->sid_ctx,sid_ctx,sid_ctx_len);
448
449     return 1;
450     }
451
452 int SSL_CTX_set_generate_session_id(SSL_CTX *ctx, GEN_SESSION_CB cb)
453         {
454         CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
455         ctx->generate_session_id = cb;
456         CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
457         return 1;
458         }
459
460 int SSL_set_generate_session_id(SSL *ssl, GEN_SESSION_CB cb)
461         {
462         CRYPTO_w_lock(CRYPTO_LOCK_SSL);
463         ssl->generate_session_id = cb;
464         CRYPTO_w_unlock(CRYPTO_LOCK_SSL);
465         return 1;
466         }
467
468 int SSL_has_matching_session_id(const SSL *ssl, const unsigned char *id,
469                                 unsigned int id_len)
470         {
471         /* A quick examination of SSL_SESSION_hash and SSL_SESSION_cmp shows how
472          * we can "construct" a session to give us the desired check - ie. to
473          * find if there's a session in the hash table that would conflict with
474          * any new session built out of this id/id_len and the ssl_version in
475          * use by this SSL. */
476         SSL_SESSION r, *p;
477
478         if(id_len > sizeof r.session_id)
479                 return 0;
480
481         r.ssl_version = ssl->version;
482         r.session_id_length = id_len;
483         memcpy(r.session_id, id, id_len);
484         /* NB: SSLv2 always uses a fixed 16-byte session ID, so even if a
485          * callback is calling us to check the uniqueness of a shorter ID, it
486          * must be compared as a padded-out ID because that is what it will be
487          * converted to when the callback has finished choosing it. */
488         if((r.ssl_version == SSL2_VERSION) &&
489                         (id_len < SSL2_SSL_SESSION_ID_LENGTH))
490                 {
491                 memset(r.session_id + id_len, 0,
492                         SSL2_SSL_SESSION_ID_LENGTH - id_len);
493                 r.session_id_length = SSL2_SSL_SESSION_ID_LENGTH;
494                 }
495
496         CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX);
497         p = lh_SSL_SESSION_retrieve(ssl->ctx->sessions, &r);
498         CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX);
499         return (p != NULL);
500         }
501
502 int SSL_CTX_set_purpose(SSL_CTX *s, int purpose)
503         {
504         return X509_VERIFY_PARAM_set_purpose(s->param, purpose);
505         }
506
507 int SSL_set_purpose(SSL *s, int purpose)
508         {
509         return X509_VERIFY_PARAM_set_purpose(s->param, purpose);
510         }
511
512 int SSL_CTX_set_trust(SSL_CTX *s, int trust)
513         {
514         return X509_VERIFY_PARAM_set_trust(s->param, trust);
515         }
516
517 int SSL_set_trust(SSL *s, int trust)
518         {
519         return X509_VERIFY_PARAM_set_trust(s->param, trust);
520         }
521
522 int SSL_CTX_set1_param(SSL_CTX *ctx, X509_VERIFY_PARAM *vpm)
523         {
524         return X509_VERIFY_PARAM_set1(ctx->param, vpm);
525         }
526
527 int SSL_set1_param(SSL *ssl, X509_VERIFY_PARAM *vpm)
528         {
529         return X509_VERIFY_PARAM_set1(ssl->param, vpm);
530         }
531
532 void ssl_cipher_preference_list_free(
533         struct ssl_cipher_preference_list_st *cipher_list)
534         {
535         sk_SSL_CIPHER_free(cipher_list->ciphers);
536         OPENSSL_free(cipher_list->in_group_flags);
537         OPENSSL_free(cipher_list);
538         }
539
540 struct ssl_cipher_preference_list_st*
541 ssl_cipher_preference_list_dup(
542         struct ssl_cipher_preference_list_st *cipher_list)
543         {
544         struct ssl_cipher_preference_list_st* ret = NULL;
545         size_t n = sk_SSL_CIPHER_num(cipher_list->ciphers);
546
547         ret = OPENSSL_malloc(sizeof(struct ssl_cipher_preference_list_st));
548         if (!ret)
549                 goto err;
550         ret->ciphers = NULL;
551         ret->in_group_flags = NULL;
552         ret->ciphers = sk_SSL_CIPHER_dup(cipher_list->ciphers);
553         if (!ret->ciphers)
554                 goto err;
555         ret->in_group_flags = BUF_memdup(cipher_list->in_group_flags, n);
556         if (!ret->in_group_flags)
557                 goto err;
558         return ret;
559
560 err:
561         if (ret && ret->ciphers)
562                 sk_SSL_CIPHER_free(ret->ciphers);
563         if (ret)
564                 OPENSSL_free(ret);
565         return NULL;
566         }
567
568 struct ssl_cipher_preference_list_st*
569 ssl_cipher_preference_list_from_ciphers(STACK_OF(SSL_CIPHER) *ciphers)
570         {
571         struct ssl_cipher_preference_list_st* ret = NULL;
572         size_t n = sk_SSL_CIPHER_num(ciphers);
573
574         ret = OPENSSL_malloc(sizeof(struct ssl_cipher_preference_list_st));
575         if (!ret)
576                 goto err;
577         ret->ciphers = NULL;
578         ret->in_group_flags = NULL;
579         ret->ciphers = sk_SSL_CIPHER_dup(ciphers);
580         if (!ret->ciphers)
581                 goto err;
582         ret->in_group_flags = OPENSSL_malloc(n);
583         if (!ret->in_group_flags)
584                 goto err;
585         memset(ret->in_group_flags, 0, n);
586         return ret;
587
588 err:
589         if (ret && ret->ciphers)
590                 sk_SSL_CIPHER_free(ret->ciphers);
591         if (ret)
592                 OPENSSL_free(ret);
593         return NULL;
594         }
595
596 X509_VERIFY_PARAM *SSL_CTX_get0_param(SSL_CTX *ctx)
597         {
598         return ctx->param;
599         }
600
601 X509_VERIFY_PARAM *SSL_get0_param(SSL *ssl)
602         {
603         return ssl->param;
604         }
605
606 void SSL_certs_clear(SSL *s)
607         {
608         ssl_cert_clear_certs(s->cert);
609         }
610
611 void SSL_free(SSL *s)
612         {
613         int i;
614
615         if(s == NULL)
616             return;
617
618         i=CRYPTO_add(&s->references,-1,CRYPTO_LOCK_SSL);
619 #ifdef REF_PRINT
620         REF_PRINT("SSL",s);
621 #endif
622         if (i > 0) return;
623 #ifdef REF_CHECK
624         if (i < 0)
625                 {
626                 fprintf(stderr,"SSL_free, bad reference count\n");
627                 abort(); /* ok */
628                 }
629 #endif
630
631         if (s->param)
632                 X509_VERIFY_PARAM_free(s->param);
633
634         CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL, s, &s->ex_data);
635
636         if (s->bbio != NULL)
637                 {
638                 /* If the buffering BIO is in place, pop it off */
639                 if (s->bbio == s->wbio)
640                         {
641                         s->wbio=BIO_pop(s->wbio);
642                         }
643                 BIO_free(s->bbio);
644                 s->bbio=NULL;
645                 }
646         if (s->rbio != NULL)
647                 BIO_free_all(s->rbio);
648         if ((s->wbio != NULL) && (s->wbio != s->rbio))
649                 BIO_free_all(s->wbio);
650
651         if (s->init_buf != NULL) BUF_MEM_free(s->init_buf);
652
653         /* add extra stuff */
654         if (s->cipher_list != NULL)
655                 ssl_cipher_preference_list_free(s->cipher_list);
656         if (s->cipher_list_by_id != NULL) sk_SSL_CIPHER_free(s->cipher_list_by_id);
657
658         /* Make the next call work :-) */
659         if (s->session != NULL)
660                 {
661                 ssl_clear_bad_session(s);
662                 SSL_SESSION_free(s->session);
663                 }
664
665         ssl_clear_cipher_ctx(s);
666         ssl_clear_hash_ctx(&s->read_hash);
667         ssl_clear_hash_ctx(&s->write_hash);
668
669         if (s->cert != NULL) ssl_cert_free(s->cert);
670         /* Free up if allocated */
671
672         if (s->tlsext_hostname)
673                 OPENSSL_free(s->tlsext_hostname);
674         if (s->initial_ctx) SSL_CTX_free(s->initial_ctx);
675         if (s->tlsext_ecpointformatlist) OPENSSL_free(s->tlsext_ecpointformatlist);
676         if (s->tlsext_ellipticcurvelist) OPENSSL_free(s->tlsext_ellipticcurvelist);
677         if (s->alpn_client_proto_list)
678                 OPENSSL_free(s->alpn_client_proto_list);
679         if (s->tlsext_channel_id_private)
680                 EVP_PKEY_free(s->tlsext_channel_id_private);
681
682         if (s->psk_identity_hint)
683                 OPENSSL_free(s->psk_identity_hint);
684
685         if (s->client_CA != NULL)
686                 sk_X509_NAME_pop_free(s->client_CA,X509_NAME_free);
687
688         if (s->method != NULL) s->method->ssl_free(s);
689
690         if (s->ctx) SSL_CTX_free(s->ctx);
691
692         if (s->next_proto_negotiated)
693                 OPENSSL_free(s->next_proto_negotiated);
694
695         if (s->srtp_profiles)
696             sk_SRTP_PROTECTION_PROFILE_free(s->srtp_profiles);
697
698         if (s->tlsext_session_ticket)
699                 {
700                 OPENSSL_free(s->tlsext_session_ticket);
701                 }
702
703         OPENSSL_free(s);
704         }
705
706 void SSL_set_bio(SSL *s,BIO *rbio,BIO *wbio)
707         {
708         /* If the output buffering BIO is still in place, remove it
709          */
710         if (s->bbio != NULL)
711                 {
712                 if (s->wbio == s->bbio)
713                         {
714                         s->wbio=s->wbio->next_bio;
715                         s->bbio->next_bio=NULL;
716                         }
717                 }
718         if ((s->rbio != NULL) && (s->rbio != rbio))
719                 BIO_free_all(s->rbio);
720         if ((s->wbio != NULL) && (s->wbio != wbio) && (s->rbio != s->wbio))
721                 BIO_free_all(s->wbio);
722         s->rbio=rbio;
723         s->wbio=wbio;
724         }
725
726 BIO *SSL_get_rbio(const SSL *s)
727         { return(s->rbio); }
728
729 BIO *SSL_get_wbio(const SSL *s)
730         { return(s->wbio); }
731
732 int SSL_get_fd(const SSL *s)
733         {
734         return(SSL_get_rfd(s));
735         }
736
737 int SSL_get_rfd(const SSL *s)
738         {
739         int ret= -1;
740         BIO *b,*r;
741
742         b=SSL_get_rbio(s);
743         r=BIO_find_type(b,BIO_TYPE_DESCRIPTOR);
744         if (r != NULL)
745                 BIO_get_fd(r,&ret);
746         return(ret);
747         }
748
749 int SSL_get_wfd(const SSL *s)
750         {
751         int ret= -1;
752         BIO *b,*r;
753
754         b=SSL_get_wbio(s);
755         r=BIO_find_type(b,BIO_TYPE_DESCRIPTOR);
756         if (r != NULL)
757                 BIO_get_fd(r,&ret);
758         return(ret);
759         }
760
761 #ifndef OPENSSL_NO_SOCK
762 int SSL_set_fd(SSL *s,int fd)
763         {
764         int ret=0;
765         BIO *bio=NULL;
766
767         bio=BIO_new(BIO_s_fd());
768
769         if (bio == NULL)
770                 {
771                 OPENSSL_PUT_ERROR(SSL, SSL_set_fd, ERR_R_BUF_LIB);
772                 goto err;
773                 }
774         BIO_set_fd(bio,fd,BIO_NOCLOSE);
775         SSL_set_bio(s,bio,bio);
776         ret=1;
777 err:
778         return(ret);
779         }
780
781 int SSL_set_wfd(SSL *s,int fd)
782         {
783         int ret=0;
784         BIO *bio=NULL;
785
786         if ((s->rbio == NULL) || (BIO_method_type(s->rbio) != BIO_TYPE_FD)
787                 || ((int)BIO_get_fd(s->rbio,NULL) != fd))
788                 {
789                 bio=BIO_new(BIO_s_fd());
790
791                 if (bio == NULL)
792                         {
793                         OPENSSL_PUT_ERROR(SSL, SSL_set_wfd, ERR_R_BUF_LIB);
794                         goto err;
795                         }
796                 BIO_set_fd(bio,fd,BIO_NOCLOSE);
797                 SSL_set_bio(s,SSL_get_rbio(s),bio);
798                 }
799         else
800                 SSL_set_bio(s,SSL_get_rbio(s),SSL_get_rbio(s));
801         ret=1;
802 err:
803         return(ret);
804         }
805
806 int SSL_set_rfd(SSL *s,int fd)
807         {
808         int ret=0;
809         BIO *bio=NULL;
810
811         if ((s->wbio == NULL) || (BIO_method_type(s->wbio) != BIO_TYPE_FD)
812                 || ((int)BIO_get_fd(s->wbio,NULL) != fd))
813                 {
814                 bio=BIO_new(BIO_s_fd());
815
816                 if (bio == NULL)
817                         {
818                         OPENSSL_PUT_ERROR(SSL, SSL_set_rfd, ERR_R_BUF_LIB);
819                         goto err;
820                         }
821                 BIO_set_fd(bio,fd,BIO_NOCLOSE);
822                 SSL_set_bio(s,bio,SSL_get_wbio(s));
823                 }
824         else
825                 SSL_set_bio(s,SSL_get_wbio(s),SSL_get_wbio(s));
826         ret=1;
827 err:
828         return(ret);
829         }
830 #endif
831
832
833 /* return length of latest Finished message we sent, copy to 'buf' */
834 size_t SSL_get_finished(const SSL *s, void *buf, size_t count)
835         {
836         size_t ret = 0;
837         
838         if (s->s3 != NULL)
839                 {
840                 ret = s->s3->tmp.finish_md_len;
841                 if (count > ret)
842                         count = ret;
843                 memcpy(buf, s->s3->tmp.finish_md, count);
844                 }
845         return ret;
846         }
847
848 /* return length of latest Finished message we expected, copy to 'buf' */
849 size_t SSL_get_peer_finished(const SSL *s, void *buf, size_t count)
850         {
851         size_t ret = 0;
852         
853         if (s->s3 != NULL)
854                 {
855                 ret = s->s3->tmp.peer_finish_md_len;
856                 if (count > ret)
857                         count = ret;
858                 memcpy(buf, s->s3->tmp.peer_finish_md, count);
859                 }
860         return ret;
861         }
862
863
864 int SSL_get_verify_mode(const SSL *s)
865         {
866         return(s->verify_mode);
867         }
868
869 int SSL_get_verify_depth(const SSL *s)
870         {
871         return X509_VERIFY_PARAM_get_depth(s->param);
872         }
873
874 int (*SSL_get_verify_callback(const SSL *s))(int,X509_STORE_CTX *)
875         {
876         return(s->verify_callback);
877         }
878
879 int SSL_CTX_get_verify_mode(const SSL_CTX *ctx)
880         {
881         return(ctx->verify_mode);
882         }
883
884 int SSL_CTX_get_verify_depth(const SSL_CTX *ctx)
885         {
886         return X509_VERIFY_PARAM_get_depth(ctx->param);
887         }
888
889 int (*SSL_CTX_get_verify_callback(const SSL_CTX *ctx))(int,X509_STORE_CTX *)
890         {
891         return(ctx->default_verify_callback);
892         }
893
894 void SSL_set_verify(SSL *s,int mode,
895                     int (*callback)(int ok,X509_STORE_CTX *ctx))
896         {
897         s->verify_mode=mode;
898         if (callback != NULL)
899                 s->verify_callback=callback;
900         }
901
902 void SSL_set_verify_depth(SSL *s,int depth)
903         {
904         X509_VERIFY_PARAM_set_depth(s->param, depth);
905         }
906
907 void SSL_set_read_ahead(SSL *s,int yes)
908         {
909         s->read_ahead=yes;
910         }
911
912 int SSL_get_read_ahead(const SSL *s)
913         {
914         return(s->read_ahead);
915         }
916
917 int SSL_pending(const SSL *s)
918         {
919         /* SSL_pending cannot work properly if read-ahead is enabled
920          * (SSL_[CTX_]ctrl(..., SSL_CTRL_SET_READ_AHEAD, 1, NULL)),
921          * and it is impossible to fix since SSL_pending cannot report
922          * errors that may be observed while scanning the new data.
923          * (Note that SSL_pending() is often used as a boolean value,
924          * so we'd better not return -1.)
925          */
926         return(s->method->ssl_pending(s));
927         }
928
929 X509 *SSL_get_peer_certificate(const SSL *s)
930         {
931         X509 *r;
932         
933         if ((s == NULL) || (s->session == NULL))
934                 r=NULL;
935         else
936                 r=s->session->peer;
937
938         if (r == NULL)
939                 return NULL;
940
941         return X509_up_ref(r);
942         }
943
944 STACK_OF(X509) *SSL_get_peer_cert_chain(const SSL *s)
945         {
946         STACK_OF(X509) *r;
947         
948         if ((s == NULL) || (s->session == NULL) || (s->session->sess_cert == NULL))
949                 r=NULL;
950         else
951                 r=s->session->sess_cert->cert_chain;
952
953         /* If we are a client, cert_chain includes the peer's own
954          * certificate; if we are a server, it does not. */
955         
956         return(r);
957         }
958
959 /* Fix this so it checks all the valid key/cert options */
960 int SSL_CTX_check_private_key(const SSL_CTX *ctx)
961         {
962         if (    (ctx == NULL) ||
963                 (ctx->cert == NULL) ||
964                 (ctx->cert->key->x509 == NULL))
965                 {
966                 OPENSSL_PUT_ERROR(SSL, SSL_CTX_check_private_key, SSL_R_NO_CERTIFICATE_ASSIGNED);
967                 return(0);
968                 }
969         if      (ctx->cert->key->privatekey == NULL)
970                 {
971                 OPENSSL_PUT_ERROR(SSL, SSL_CTX_check_private_key, SSL_R_NO_PRIVATE_KEY_ASSIGNED);
972                 return(0);
973                 }
974         return(X509_check_private_key(ctx->cert->key->x509, ctx->cert->key->privatekey));
975         }
976
977 /* Fix this function so that it takes an optional type parameter */
978 int SSL_check_private_key(const SSL *ssl)
979         {
980         if (ssl == NULL)
981                 {
982                 OPENSSL_PUT_ERROR(SSL, SSL_check_private_key, ERR_R_PASSED_NULL_PARAMETER);
983                 return(0);
984                 }
985         if (ssl->cert == NULL)
986                 {
987                 OPENSSL_PUT_ERROR(SSL, SSL_check_private_key, SSL_R_NO_CERTIFICATE_ASSIGNED);
988                 return 0;
989                 }
990         if (ssl->cert->key->x509 == NULL)
991                 {
992                 OPENSSL_PUT_ERROR(SSL, SSL_check_private_key, SSL_R_NO_CERTIFICATE_ASSIGNED);
993                 return(0);
994                 }
995         if (ssl->cert->key->privatekey == NULL)
996                 {
997                 OPENSSL_PUT_ERROR(SSL, SSL_check_private_key, SSL_R_NO_PRIVATE_KEY_ASSIGNED);
998                 return(0);
999                 }
1000         return(X509_check_private_key(ssl->cert->key->x509,
1001                 ssl->cert->key->privatekey));
1002         }
1003
1004 int SSL_accept(SSL *s)
1005         {
1006         if (s->handshake_func == 0)
1007                 /* Not properly initialized yet */
1008                 SSL_set_accept_state(s);
1009
1010         return(s->method->ssl_accept(s));
1011         }
1012
1013 int SSL_connect(SSL *s)
1014         {
1015         if (s->handshake_func == 0)
1016                 /* Not properly initialized yet */
1017                 SSL_set_connect_state(s);
1018
1019         return(s->method->ssl_connect(s));
1020         }
1021
1022 long SSL_get_default_timeout(const SSL *s)
1023         {
1024         return SSL_DEFAULT_SESSION_TIMEOUT;
1025         }
1026
1027 int SSL_read(SSL *s,void *buf,int num)
1028         {
1029         if (s->handshake_func == 0)
1030                 {
1031                 OPENSSL_PUT_ERROR(SSL, SSL_read, SSL_R_UNINITIALIZED);
1032                 return -1;
1033                 }
1034
1035         if (s->shutdown & SSL_RECEIVED_SHUTDOWN)
1036                 {
1037                 s->rwstate=SSL_NOTHING;
1038                 return(0);
1039                 }
1040         return(s->method->ssl_read(s,buf,num));
1041         }
1042
1043 int SSL_peek(SSL *s,void *buf,int num)
1044         {
1045         if (s->handshake_func == 0)
1046                 {
1047                 OPENSSL_PUT_ERROR(SSL, SSL_peek, SSL_R_UNINITIALIZED);
1048                 return -1;
1049                 }
1050
1051         if (s->shutdown & SSL_RECEIVED_SHUTDOWN)
1052                 {
1053                 return(0);
1054                 }
1055         return(s->method->ssl_peek(s,buf,num));
1056         }
1057
1058 int SSL_write(SSL *s,const void *buf,int num)
1059         {
1060         if (s->handshake_func == 0)
1061                 {
1062                 OPENSSL_PUT_ERROR(SSL, SSL_write, SSL_R_UNINITIALIZED);
1063                 return -1;
1064                 }
1065
1066         if (s->shutdown & SSL_SENT_SHUTDOWN)
1067                 {
1068                 s->rwstate=SSL_NOTHING;
1069                 OPENSSL_PUT_ERROR(SSL, SSL_write, SSL_R_PROTOCOL_IS_SHUTDOWN);
1070                 return(-1);
1071                 }
1072         return(s->method->ssl_write(s,buf,num));
1073         }
1074
1075 int SSL_shutdown(SSL *s)
1076         {
1077         /* Note that this function behaves differently from what one might
1078          * expect.  Return values are 0 for no success (yet),
1079          * 1 for success; but calling it once is usually not enough,
1080          * even if blocking I/O is used (see ssl3_shutdown).
1081          */
1082
1083         if (s->handshake_func == 0)
1084                 {
1085                 OPENSSL_PUT_ERROR(SSL, SSL_shutdown, SSL_R_UNINITIALIZED);
1086                 return -1;
1087                 }
1088
1089         if (!SSL_in_init(s))
1090                 return(s->method->ssl_shutdown(s));
1091         else
1092                 return(1);
1093         }
1094
1095 int SSL_renegotiate(SSL *s)
1096         {
1097         if (s->renegotiate == 0)
1098                 s->renegotiate=1;
1099
1100         s->new_session=1;
1101
1102         return(s->method->ssl_renegotiate(s));
1103         }
1104
1105 int SSL_renegotiate_abbreviated(SSL *s)
1106         {
1107         if (s->renegotiate == 0)
1108                 s->renegotiate=1;
1109
1110         s->new_session=0;
1111
1112         return(s->method->ssl_renegotiate(s));
1113         }
1114
1115 int SSL_renegotiate_pending(SSL *s)
1116         {
1117         /* becomes true when negotiation is requested;
1118          * false again once a handshake has finished */
1119         return (s->renegotiate != 0);
1120         }
1121
1122 long SSL_ctrl(SSL *s,int cmd,long larg,void *parg)
1123         {
1124         long l;
1125
1126         switch (cmd)
1127                 {
1128         case SSL_CTRL_GET_READ_AHEAD:
1129                 return(s->read_ahead);
1130         case SSL_CTRL_SET_READ_AHEAD:
1131                 l=s->read_ahead;
1132                 s->read_ahead=larg;
1133                 return(l);
1134
1135         case SSL_CTRL_SET_MSG_CALLBACK_ARG:
1136                 s->msg_callback_arg = parg;
1137                 return 1;
1138
1139         case SSL_CTRL_OPTIONS:
1140                 return(s->options|=larg);
1141         case SSL_CTRL_CLEAR_OPTIONS:
1142                 return(s->options&=~larg);
1143         case SSL_CTRL_MODE:
1144                 return(s->mode|=larg);
1145         case SSL_CTRL_CLEAR_MODE:
1146                 return(s->mode &=~larg);
1147         case SSL_CTRL_GET_MAX_CERT_LIST:
1148                 return(s->max_cert_list);
1149         case SSL_CTRL_SET_MAX_CERT_LIST:
1150                 l=s->max_cert_list;
1151                 s->max_cert_list=larg;
1152                 return(l);
1153         case SSL_CTRL_SET_MTU:
1154                 if (larg < (long)dtls1_min_mtu())
1155                         return 0;
1156                 if (SSL_IS_DTLS(s))
1157                         {
1158                         s->d1->mtu = larg;
1159                         return larg;
1160                         }
1161                 return 0;
1162         case SSL_CTRL_SET_MAX_SEND_FRAGMENT:
1163                 if (larg < 512 || larg > SSL3_RT_MAX_PLAIN_LENGTH)
1164                         return 0;
1165                 s->max_send_fragment = larg;
1166                 return 1;
1167         case SSL_CTRL_GET_RI_SUPPORT:
1168                 if (s->s3)
1169                         return s->s3->send_connection_binding;
1170                 else return 0;
1171         case SSL_CTRL_CERT_FLAGS:
1172                 return(s->cert->cert_flags|=larg);
1173         case SSL_CTRL_CLEAR_CERT_FLAGS:
1174                 return(s->cert->cert_flags &=~larg);
1175
1176         case SSL_CTRL_GET_RAW_CIPHERLIST:
1177                 if (parg)
1178                         {
1179                         if (s->cert->ciphers_raw == NULL)
1180                                 return 0;
1181                         *(unsigned char **)parg = s->cert->ciphers_raw;
1182                         return (int)s->cert->ciphers_rawlen;
1183                         }
1184                 else
1185                         {
1186                         /* Passing a NULL |parg| returns the size of a single
1187                          * cipher suite value. */
1188                         return 2;
1189                         }
1190         default:
1191                 return(s->method->ssl_ctrl(s,cmd,larg,parg));
1192                 }
1193         }
1194
1195 long SSL_callback_ctrl(SSL *s, int cmd, void (*fp)(void))
1196         {
1197         switch(cmd)
1198                 {
1199         case SSL_CTRL_SET_MSG_CALLBACK:
1200                 s->msg_callback = (void (*)(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg))(fp);
1201                 return 1;
1202                 
1203         default:
1204                 return(s->method->ssl_callback_ctrl(s,cmd,fp));
1205                 }
1206         }
1207
1208 LHASH_OF(SSL_SESSION) *SSL_CTX_sessions(SSL_CTX *ctx)
1209         {
1210         return ctx->sessions;
1211         }
1212
1213 long SSL_CTX_ctrl(SSL_CTX *ctx,int cmd,long larg,void *parg)
1214         {
1215         long l;
1216
1217         switch (cmd)
1218                 {
1219         case SSL_CTRL_GET_READ_AHEAD:
1220                 return(ctx->read_ahead);
1221         case SSL_CTRL_SET_READ_AHEAD:
1222                 l=ctx->read_ahead;
1223                 ctx->read_ahead=larg;
1224                 return(l);
1225                 
1226         case SSL_CTRL_SET_MSG_CALLBACK_ARG:
1227                 ctx->msg_callback_arg = parg;
1228                 return 1;
1229
1230         case SSL_CTRL_GET_MAX_CERT_LIST:
1231                 return(ctx->max_cert_list);
1232         case SSL_CTRL_SET_MAX_CERT_LIST:
1233                 l=ctx->max_cert_list;
1234                 ctx->max_cert_list=larg;
1235                 return(l);
1236
1237         case SSL_CTRL_SET_SESS_CACHE_SIZE:
1238                 l=ctx->session_cache_size;
1239                 ctx->session_cache_size=larg;
1240                 return(l);
1241         case SSL_CTRL_GET_SESS_CACHE_SIZE:
1242                 return(ctx->session_cache_size);
1243         case SSL_CTRL_SET_SESS_CACHE_MODE:
1244                 l=ctx->session_cache_mode;
1245                 ctx->session_cache_mode=larg;
1246                 return(l);
1247         case SSL_CTRL_GET_SESS_CACHE_MODE:
1248                 return(ctx->session_cache_mode);
1249
1250         case SSL_CTRL_SESS_NUMBER:
1251                 return(lh_SSL_SESSION_num_items(ctx->sessions));
1252         case SSL_CTRL_SESS_CONNECT:
1253                 return(ctx->stats.sess_connect);
1254         case SSL_CTRL_SESS_CONNECT_GOOD:
1255                 return(ctx->stats.sess_connect_good);
1256         case SSL_CTRL_SESS_CONNECT_RENEGOTIATE:
1257                 return(ctx->stats.sess_connect_renegotiate);
1258         case SSL_CTRL_SESS_ACCEPT:
1259                 return(ctx->stats.sess_accept);
1260         case SSL_CTRL_SESS_ACCEPT_GOOD:
1261                 return(ctx->stats.sess_accept_good);
1262         case SSL_CTRL_SESS_ACCEPT_RENEGOTIATE:
1263                 return(ctx->stats.sess_accept_renegotiate);
1264         case SSL_CTRL_SESS_HIT:
1265                 return(ctx->stats.sess_hit);
1266         case SSL_CTRL_SESS_CB_HIT:
1267                 return(ctx->stats.sess_cb_hit);
1268         case SSL_CTRL_SESS_MISSES:
1269                 return(ctx->stats.sess_miss);
1270         case SSL_CTRL_SESS_TIMEOUTS:
1271                 return(ctx->stats.sess_timeout);
1272         case SSL_CTRL_SESS_CACHE_FULL:
1273                 return(ctx->stats.sess_cache_full);
1274         case SSL_CTRL_OPTIONS:
1275                 return(ctx->options|=larg);
1276         case SSL_CTRL_CLEAR_OPTIONS:
1277                 return(ctx->options&=~larg);
1278         case SSL_CTRL_MODE:
1279                 return(ctx->mode|=larg);
1280         case SSL_CTRL_CLEAR_MODE:
1281                 return(ctx->mode&=~larg);
1282         case SSL_CTRL_SET_MAX_SEND_FRAGMENT:
1283                 if (larg < 512 || larg > SSL3_RT_MAX_PLAIN_LENGTH)
1284                         return 0;
1285                 ctx->max_send_fragment = larg;
1286                 return 1;
1287         case SSL_CTRL_CERT_FLAGS:
1288                 return(ctx->cert->cert_flags|=larg);
1289         case SSL_CTRL_CLEAR_CERT_FLAGS:
1290                 return(ctx->cert->cert_flags &=~larg);
1291         default:
1292                 return(ctx->method->ssl_ctx_ctrl(ctx,cmd,larg,parg));
1293                 }
1294         }
1295
1296 long SSL_CTX_callback_ctrl(SSL_CTX *ctx, int cmd, void (*fp)(void))
1297         {
1298         switch(cmd)
1299                 {
1300         case SSL_CTRL_SET_MSG_CALLBACK:
1301                 ctx->msg_callback = (void (*)(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg))(fp);
1302                 return 1;
1303
1304         default:
1305                 return(ctx->method->ssl_ctx_callback_ctrl(ctx,cmd,fp));
1306                 }
1307         }
1308
1309 int ssl_cipher_id_cmp(const void *in_a, const void *in_b)
1310         {
1311         long l;
1312         const SSL_CIPHER *a = in_a;
1313         const SSL_CIPHER *b = in_b;
1314         const long a_id = a->id;
1315         const long b_id = b->id;
1316
1317         l = a_id - b_id;
1318         if (l == 0L)
1319                 return(0);
1320         else
1321                 return((l > 0)?1:-1);
1322         }
1323
1324 int ssl_cipher_ptr_id_cmp(const SSL_CIPHER **ap, const SSL_CIPHER **bp)
1325         {
1326         long l;
1327         const long a_id = (*ap)->id;
1328         const long b_id = (*bp)->id;
1329
1330         l = a_id - b_id;
1331         if (l == 0)
1332                 return(0);
1333         else
1334                 return((l > 0)?1:-1);
1335         }
1336
1337 /** return a STACK of the ciphers available for the SSL and in order of
1338  * preference */
1339 STACK_OF(SSL_CIPHER) *SSL_get_ciphers(const SSL *s)
1340         {
1341         if (s == NULL)
1342                 return NULL;
1343
1344         if (s->cipher_list != NULL)
1345                 {
1346                 return(s->cipher_list->ciphers);
1347                 }
1348
1349         if (s->version >= TLS1_1_VERSION)
1350                 {
1351                 if (s->ctx != NULL && s->ctx->cipher_list_tls11 != NULL)
1352                         return s->ctx->cipher_list_tls11->ciphers;
1353                 }
1354
1355         if ((s->ctx != NULL) &&
1356                 (s->ctx->cipher_list != NULL))
1357                 {
1358                 return(s->ctx->cipher_list->ciphers);
1359                 }
1360
1361         return(NULL);
1362         }
1363
1364 /** return a STACK of the ciphers available for the SSL and in order of
1365  * algorithm id */
1366 STACK_OF(SSL_CIPHER) *ssl_get_ciphers_by_id(SSL *s)
1367         {
1368         if (s != NULL)
1369                 {
1370                 if (s->cipher_list_by_id != NULL)
1371                         {
1372                         return(s->cipher_list_by_id);
1373                         }
1374                 else if ((s->ctx != NULL) &&
1375                         (s->ctx->cipher_list_by_id != NULL))
1376                         {
1377                         return(s->ctx->cipher_list_by_id);
1378                         }
1379                 }
1380         return(NULL);
1381         }
1382
1383 /** The old interface to get the same thing as SSL_get_ciphers() */
1384 const char *SSL_get_cipher_list(const SSL *s,int n)
1385         {
1386         const SSL_CIPHER *c;
1387         STACK_OF(SSL_CIPHER) *sk;
1388
1389         if (s == NULL) return(NULL);
1390         sk=SSL_get_ciphers(s);
1391         if ((sk == NULL) || (sk_SSL_CIPHER_num(sk) <= n))
1392                 return(NULL);
1393         c=sk_SSL_CIPHER_value(sk,n);
1394         if (c == NULL) return(NULL);
1395         return(c->name);
1396         }
1397
1398 /** specify the ciphers to be used by default by the SSL_CTX */
1399 int SSL_CTX_set_cipher_list(SSL_CTX *ctx, const char *str)
1400         {
1401         STACK_OF(SSL_CIPHER) *sk;
1402         
1403         sk=ssl_create_cipher_list(ctx->method,&ctx->cipher_list,
1404                 &ctx->cipher_list_by_id,str, ctx->cert);
1405         /* ssl_create_cipher_list may return an empty stack if it
1406          * was unable to find a cipher matching the given rule string
1407          * (for example if the rule string specifies a cipher which
1408          * has been disabled). This is not an error as far as
1409          * ssl_create_cipher_list is concerned, and hence
1410          * ctx->cipher_list and ctx->cipher_list_by_id has been
1411          * updated. */
1412         if (sk == NULL)
1413                 return 0;
1414         else if (sk_SSL_CIPHER_num(sk) == 0)
1415                 {
1416                 OPENSSL_PUT_ERROR(SSL, SSL_CTX_set_cipher_list, SSL_R_NO_CIPHER_MATCH);
1417                 return 0;
1418                 }
1419         return 1;
1420         }
1421
1422 int SSL_CTX_set_cipher_list_tls11(SSL_CTX *ctx, const char *str)
1423         {
1424         STACK_OF(SSL_CIPHER) *sk;
1425         
1426         sk = ssl_create_cipher_list(ctx->method, &ctx->cipher_list_tls11, NULL, str, ctx->cert);
1427         if (sk == NULL)
1428                 return 0;
1429         else if (sk_SSL_CIPHER_num(sk) == 0)
1430                 {
1431                 OPENSSL_PUT_ERROR(SSL, SSL_CTX_set_cipher_list_tls11, SSL_R_NO_CIPHER_MATCH);
1432                 return 0;
1433                 }
1434         return 1;
1435         }
1436
1437 /** specify the ciphers to be used by the SSL */
1438 int SSL_set_cipher_list(SSL *s,const char *str)
1439         {
1440         STACK_OF(SSL_CIPHER) *sk;
1441         
1442         sk=ssl_create_cipher_list(s->ctx->method,&s->cipher_list,
1443                 &s->cipher_list_by_id,str, s->cert);
1444         /* see comment in SSL_CTX_set_cipher_list */
1445         if (sk == NULL)
1446                 return 0;
1447         else if (sk_SSL_CIPHER_num(sk) == 0)
1448                 {
1449                 OPENSSL_PUT_ERROR(SSL, SSL_set_cipher_list, SSL_R_NO_CIPHER_MATCH);
1450                 return 0;
1451                 }
1452         return 1;
1453         }
1454
1455 /* works well for SSLv2, not so good for SSLv3 */
1456 char *SSL_get_shared_ciphers(const SSL *s,char *buf,int len)
1457         {
1458         char *p;
1459         STACK_OF(SSL_CIPHER) *sk;
1460         const SSL_CIPHER *c;
1461         int i;
1462
1463         if ((s->session == NULL) || (s->session->ciphers == NULL) ||
1464                 (len < 2))
1465                 return(NULL);
1466
1467         p=buf;
1468         sk=s->session->ciphers;
1469
1470         if (sk_SSL_CIPHER_num(sk) == 0)
1471                 return NULL;
1472
1473         for (i=0; i<sk_SSL_CIPHER_num(sk); i++)
1474                 {
1475                 int n;
1476
1477                 c=sk_SSL_CIPHER_value(sk,i);
1478                 n=strlen(c->name);
1479                 if (n+1 > len)
1480                         {
1481                         if (p != buf)
1482                                 --p;
1483                         *p='\0';
1484                         return buf;
1485                         }
1486                 strcpy(p,c->name);
1487                 p+=n;
1488                 *(p++)=':';
1489                 len-=n+1;
1490                 }
1491         p[-1]='\0';
1492         return(buf);
1493         }
1494
1495 int ssl_cipher_list_to_bytes(SSL *s,STACK_OF(SSL_CIPHER) *sk,unsigned char *p)
1496         {
1497         int i;
1498         const SSL_CIPHER *c;
1499         CERT *ct = s->cert;
1500         unsigned char *q;
1501         int no_scsv = s->renegotiate;
1502         /* Set disabled masks for this session */
1503         ssl_set_client_disabled(s);
1504
1505         if (sk == NULL) return(0);
1506         q=p;
1507
1508         for (i=0; i<sk_SSL_CIPHER_num(sk); i++)
1509                 {
1510                 c=sk_SSL_CIPHER_value(sk,i);
1511                 /* Skip disabled ciphers */
1512                 if (c->algorithm_ssl & ct->mask_ssl ||
1513                         c->algorithm_mkey & ct->mask_k ||
1514                         c->algorithm_auth & ct->mask_a)
1515                         continue;
1516 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
1517                 if (c->id == SSL3_CK_SCSV)
1518                         {
1519                         if (no_scsv)
1520                                 continue;
1521                         else
1522                                 no_scsv = 1;
1523                         }
1524 #endif
1525                 s2n(ssl3_get_cipher_value(c), p);
1526                 }
1527         /* If p == q, no ciphers and caller indicates an error. Otherwise
1528          * add SCSV if not renegotiating.
1529          */
1530         if (p != q)
1531                 {
1532                 if (!no_scsv)
1533                         {
1534                         static const SSL_CIPHER scsv =
1535                                 {
1536                                 0, NULL, SSL3_CK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
1537                                 };
1538                         s2n(ssl3_get_cipher_value(&scsv), p);
1539 #ifdef OPENSSL_RI_DEBUG
1540                         fprintf(stderr, "SCSV sent by client\n");
1541 #endif
1542                         }
1543                 if (s->fallback_scsv)
1544                         {
1545                         static const SSL_CIPHER fallback_scsv =
1546                                 {
1547                                 0, NULL, SSL3_CK_FALLBACK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
1548                                 };
1549                         s2n(ssl3_get_cipher_value(&fallback_scsv), p);
1550                         }
1551                 }
1552
1553         return(p-q);
1554         }
1555
1556 STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list(SSL *s, const CBS *cbs,
1557                                                STACK_OF(SSL_CIPHER) **skp)
1558         {
1559         CBS cipher_suites = *cbs;
1560         const SSL_CIPHER *c;
1561         STACK_OF(SSL_CIPHER) *sk;
1562
1563         if (s->s3)
1564                 s->s3->send_connection_binding = 0;
1565
1566         if (CBS_len(&cipher_suites) % 2 != 0)
1567                 {
1568                 OPENSSL_PUT_ERROR(SSL, ssl_bytes_to_cipher_list, SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
1569                 return(NULL);
1570                 }
1571         if ((skp == NULL) || (*skp == NULL))
1572                 sk=sk_SSL_CIPHER_new_null(); /* change perhaps later */
1573         else
1574                 {
1575                 sk= *skp;
1576                 sk_SSL_CIPHER_zero(sk);
1577                 }
1578
1579         if (!CBS_stow(&cipher_suites,
1580                         &s->cert->ciphers_raw, &s->cert->ciphers_rawlen))
1581                 {
1582                 OPENSSL_PUT_ERROR(SSL, ssl_bytes_to_cipher_list, ERR_R_MALLOC_FAILURE);
1583                 goto err;
1584                 }
1585
1586         while (CBS_len(&cipher_suites) > 0)
1587                 {
1588                 uint16_t cipher_suite;
1589
1590                 if (!CBS_get_u16(&cipher_suites, &cipher_suite))
1591                         {
1592                         OPENSSL_PUT_ERROR(SSL, ssl_bytes_to_cipher_list, ERR_R_INTERNAL_ERROR);
1593                         goto err;
1594                         }
1595
1596                 /* Check for SCSV */
1597                 if (s->s3 && cipher_suite == (SSL3_CK_SCSV & 0xffff))
1598                         {
1599                         /* SCSV fatal if renegotiating */
1600                         if (s->renegotiate)
1601                                 {
1602                                 OPENSSL_PUT_ERROR(SSL, ssl_bytes_to_cipher_list, SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING);
1603                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); 
1604                                 goto err;
1605                                 }
1606                         s->s3->send_connection_binding = 1;
1607 #ifdef OPENSSL_RI_DEBUG
1608                         fprintf(stderr, "SCSV received by server\n");
1609 #endif
1610                         continue;
1611                         }
1612
1613                 /* Check for FALLBACK_SCSV */
1614                 if (s->s3 && cipher_suite == (SSL3_CK_FALLBACK_SCSV & 0xffff) &&
1615                         s->version < ssl_get_max_version(s))
1616                         {
1617                         OPENSSL_PUT_ERROR(SSL, ssl_bytes_to_cipher_list, SSL_R_INAPPROPRIATE_FALLBACK);
1618                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL3_AD_INAPPROPRIATE_FALLBACK);
1619                         goto err;
1620                         }
1621
1622                 c = ssl3_get_cipher_by_value(cipher_suite);
1623                 if (c != NULL)
1624                         {
1625                         if (!sk_SSL_CIPHER_push(sk,c))
1626                                 {
1627                                 OPENSSL_PUT_ERROR(SSL, ssl_bytes_to_cipher_list, ERR_R_MALLOC_FAILURE);
1628                                 goto err;
1629                                 }
1630                         }
1631                 }
1632
1633         if (skp != NULL)
1634                 *skp=sk;
1635         return(sk);
1636 err:
1637         if ((skp == NULL) || (*skp == NULL))
1638                 sk_SSL_CIPHER_free(sk);
1639         return(NULL);
1640         }
1641
1642
1643 /** return a servername extension value if provided in Client Hello, or NULL.
1644  * So far, only host_name types are defined (RFC 3546).
1645  */
1646
1647 const char *SSL_get_servername(const SSL *s, const int type)
1648         {
1649         if (type != TLSEXT_NAMETYPE_host_name)
1650                 return NULL;
1651
1652         return s->session && !s->tlsext_hostname ?
1653                 s->session->tlsext_hostname :
1654                 s->tlsext_hostname;
1655         }
1656
1657 int SSL_get_servername_type(const SSL *s)
1658         {
1659         if (s->session && (!s->tlsext_hostname ? s->session->tlsext_hostname : s->tlsext_hostname))
1660                 return TLSEXT_NAMETYPE_host_name;
1661         return -1;
1662         }
1663
1664 void SSL_CTX_enable_signed_cert_timestamps(SSL_CTX *ctx)
1665         {
1666         ctx->signed_cert_timestamps_enabled = 1;
1667         }
1668
1669 int SSL_enable_signed_cert_timestamps(SSL *ssl)
1670         {
1671         /* Currently not implemented server-side. */
1672         if (ssl->server)
1673                 return 0;
1674
1675         ssl->signed_cert_timestamps_enabled = 1;
1676         return 1;
1677         }
1678
1679 void SSL_CTX_enable_ocsp_stapling(SSL_CTX *ctx)
1680         {
1681         ctx->ocsp_stapling_enabled = 1;
1682         }
1683
1684 int SSL_enable_ocsp_stapling(SSL *ssl)
1685         {
1686         /* Currently not implemented server-side. */
1687         if (ssl->server)
1688                 return 0;
1689         ssl->ocsp_stapling_enabled = 1;
1690         return 1;
1691         }
1692
1693 void SSL_get0_signed_cert_timestamp_list(const SSL *ssl, uint8_t **out, size_t *out_len)
1694         {
1695         SSL_SESSION *session = ssl->session;
1696
1697         *out_len = 0;
1698         *out = NULL;
1699         if (ssl->server)
1700                 return;
1701         if (!session || !session->tlsext_signed_cert_timestamp_list)
1702                 return;
1703         *out = session->tlsext_signed_cert_timestamp_list;
1704         *out_len = session->tlsext_signed_cert_timestamp_list_length;
1705         }
1706
1707 void SSL_get0_ocsp_response(const SSL *ssl, uint8_t **out, size_t *out_len)
1708         {
1709         SSL_SESSION *session = ssl->session;
1710
1711         *out_len = 0;
1712         *out = NULL;
1713         if (ssl->server)
1714                 return;
1715         if (!session || !session->ocsp_response)
1716                 return;
1717         *out = session->ocsp_response;
1718         *out_len = session->ocsp_response_length;
1719         }
1720
1721 /* SSL_select_next_proto implements the standard protocol selection. It is
1722  * expected that this function is called from the callback set by
1723  * SSL_CTX_set_next_proto_select_cb.
1724  *
1725  * The protocol data is assumed to be a vector of 8-bit, length prefixed byte
1726  * strings. The length byte itself is not included in the length. A byte
1727  * string of length 0 is invalid. No byte string may be truncated.
1728  *
1729  * The current, but experimental algorithm for selecting the protocol is:
1730  *
1731  * 1) If the server doesn't support NPN then this is indicated to the
1732  * callback. In this case, the client application has to abort the connection
1733  * or have a default application level protocol.
1734  *
1735  * 2) If the server supports NPN, but advertises an empty list then the
1736  * client selects the first protcol in its list, but indicates via the
1737  * API that this fallback case was enacted.
1738  *
1739  * 3) Otherwise, the client finds the first protocol in the server's list
1740  * that it supports and selects this protocol. This is because it's
1741  * assumed that the server has better information about which protocol
1742  * a client should use.
1743  *
1744  * 4) If the client doesn't support any of the server's advertised
1745  * protocols, then this is treated the same as case 2.
1746  *
1747  * It returns either
1748  * OPENSSL_NPN_NEGOTIATED if a common protocol was found, or
1749  * OPENSSL_NPN_NO_OVERLAP if the fallback case was reached.
1750  */
1751 int SSL_select_next_proto(unsigned char **out, unsigned char *outlen, const unsigned char *server, unsigned int server_len, const unsigned char *client, unsigned int client_len)
1752         {
1753         unsigned int i, j;
1754         const unsigned char *result;
1755         int status = OPENSSL_NPN_UNSUPPORTED;
1756
1757         /* For each protocol in server preference order, see if we support it. */
1758         for (i = 0; i < server_len; )
1759                 {
1760                 for (j = 0; j < client_len; )
1761                         {
1762                         if (server[i] == client[j] &&
1763                             memcmp(&server[i+1], &client[j+1], server[i]) == 0)
1764                                 {
1765                                 /* We found a match */
1766                                 result = &server[i];
1767                                 status = OPENSSL_NPN_NEGOTIATED;
1768                                 goto found;
1769                                 }
1770                         j += client[j];
1771                         j++;
1772                         }
1773                 i += server[i];
1774                 i++;
1775                 }
1776
1777         /* There's no overlap between our protocols and the server's list. */
1778         result = client;
1779         status = OPENSSL_NPN_NO_OVERLAP;
1780
1781         found:
1782         *out = (unsigned char *) result + 1;
1783         *outlen = result[0];
1784         return status;
1785         }
1786
1787 /* SSL_get0_next_proto_negotiated sets *data and *len to point to the client's
1788  * requested protocol for this connection and returns 0. If the client didn't
1789  * request any protocol, then *data is set to NULL.
1790  *
1791  * Note that the client can request any protocol it chooses. The value returned
1792  * from this function need not be a member of the list of supported protocols
1793  * provided by the callback.
1794  */
1795 void SSL_get0_next_proto_negotiated(const SSL *s, const uint8_t **data, unsigned *len)
1796         {
1797         *data = s->next_proto_negotiated;
1798         if (!*data) {
1799                 *len = 0;
1800         } else {
1801                 *len = s->next_proto_negotiated_len;
1802         }
1803 }
1804
1805 /* SSL_CTX_set_next_protos_advertised_cb sets a callback that is called when a
1806  * TLS server needs a list of supported protocols for Next Protocol
1807  * Negotiation. The returned list must be in wire format.  The list is returned
1808  * by setting |out| to point to it and |outlen| to its length. This memory will
1809  * not be modified, but one should assume that the SSL* keeps a reference to
1810  * it.
1811  *
1812  * The callback should return SSL_TLSEXT_ERR_OK if it wishes to advertise. Otherwise, no
1813  * such extension will be included in the ServerHello. */
1814 void SSL_CTX_set_next_protos_advertised_cb(SSL_CTX *ctx, int (*cb) (SSL *ssl, const unsigned char **out, unsigned int *outlen, void *arg), void *arg)
1815         {
1816         ctx->next_protos_advertised_cb = cb;
1817         ctx->next_protos_advertised_cb_arg = arg;
1818         }
1819
1820 /* SSL_CTX_set_next_proto_select_cb sets a callback that is called when a
1821  * client needs to select a protocol from the server's provided list. |out|
1822  * must be set to point to the selected protocol (which may be within |in|).
1823  * The length of the protocol name must be written into |outlen|. The server's
1824  * advertised protocols are provided in |in| and |inlen|. The callback can
1825  * assume that |in| is syntactically valid.
1826  *
1827  * The client must select a protocol. It is fatal to the connection if this
1828  * callback returns a value other than SSL_TLSEXT_ERR_OK.
1829  */
1830 void SSL_CTX_set_next_proto_select_cb(SSL_CTX *ctx, int (*cb) (SSL *s, unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg), void *arg)
1831         {
1832         ctx->next_proto_select_cb = cb;
1833         ctx->next_proto_select_cb_arg = arg;
1834         }
1835
1836 /* SSL_CTX_set_alpn_protos sets the ALPN protocol list on |ctx| to |protos|.
1837  * |protos| must be in wire-format (i.e. a series of non-empty, 8-bit
1838  * length-prefixed strings).
1839  *
1840  * Returns 0 on success. */
1841 int SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const unsigned char* protos,
1842                             unsigned protos_len)
1843         {
1844         if (ctx->alpn_client_proto_list)
1845                 OPENSSL_free(ctx->alpn_client_proto_list);
1846
1847         ctx->alpn_client_proto_list = BUF_memdup(protos, protos_len);
1848         if (!ctx->alpn_client_proto_list)
1849                 return 1;
1850         ctx->alpn_client_proto_list_len = protos_len;
1851
1852         return 0;
1853         }
1854
1855 /* SSL_set_alpn_protos sets the ALPN protocol list on |ssl| to |protos|.
1856  * |protos| must be in wire-format (i.e. a series of non-empty, 8-bit
1857  * length-prefixed strings).
1858  *
1859  * Returns 0 on success. */
1860 int SSL_set_alpn_protos(SSL *ssl, const unsigned char* protos,
1861                         unsigned protos_len)
1862         {
1863         if (ssl->alpn_client_proto_list)
1864                 OPENSSL_free(ssl->alpn_client_proto_list);
1865
1866         ssl->alpn_client_proto_list = BUF_memdup(protos, protos_len);
1867         if (!ssl->alpn_client_proto_list)
1868                 return 1;
1869         ssl->alpn_client_proto_list_len = protos_len;
1870
1871         return 0;
1872         }
1873
1874 /* SSL_CTX_set_alpn_select_cb sets a callback function on |ctx| that is called
1875  * during ClientHello processing in order to select an ALPN protocol from the
1876  * client's list of offered protocols. */
1877 void SSL_CTX_set_alpn_select_cb(SSL_CTX* ctx,
1878                                 int (*cb) (SSL *ssl,
1879                                            const unsigned char **out,
1880                                            unsigned char *outlen,
1881                                            const unsigned char *in,
1882                                            unsigned int inlen,
1883                                            void *arg),
1884                                 void *arg)
1885         {
1886         ctx->alpn_select_cb = cb;
1887         ctx->alpn_select_cb_arg = arg;
1888         }
1889
1890 /* SSL_get0_alpn_selected gets the selected ALPN protocol (if any) from |ssl|.
1891  * On return it sets |*data| to point to |*len| bytes of protocol name (not
1892  * including the leading length-prefix byte). If the server didn't respond with
1893  * a negotiated protocol then |*len| will be zero. */
1894 void SSL_get0_alpn_selected(const SSL *ssl, const unsigned char **data,
1895                             unsigned *len)
1896         {
1897         *data = NULL;
1898         if (ssl->s3)
1899                 *data = ssl->s3->alpn_selected;
1900         if (*data == NULL)
1901                 *len = 0;
1902         else
1903                 *len = ssl->s3->alpn_selected_len;
1904         }
1905
1906 int SSL_export_keying_material(SSL *s, unsigned char *out, size_t olen,
1907         const char *label, size_t llen, const unsigned char *p, size_t plen,
1908         int use_context)
1909         {
1910         if (s->version < TLS1_VERSION)
1911                 return -1;
1912
1913         return s->method->ssl3_enc->export_keying_material(s, out, olen, label,
1914                                                            llen, p, plen,
1915                                                            use_context);
1916         }
1917
1918 static uint32_t ssl_session_hash(const SSL_SESSION *a)
1919         {
1920         uint32_t hash = ((uint32_t) a->session_id[0]) ||
1921                         ((uint32_t) a->session_id[1] << 8) ||
1922                         ((uint32_t) a->session_id[2] << 16) ||
1923                         ((uint32_t) a->session_id[3] << 24);
1924
1925         return hash;
1926         }
1927
1928 /* NB: If this function (or indeed the hash function which uses a sort of
1929  * coarser function than this one) is changed, ensure
1930  * SSL_CTX_has_matching_session_id() is checked accordingly. It relies on being
1931  * able to construct an SSL_SESSION that will collide with any existing session
1932  * with a matching session ID. */
1933 static int ssl_session_cmp(const SSL_SESSION *a, const SSL_SESSION *b)
1934         {
1935         if (a->ssl_version != b->ssl_version)
1936                 return(1);
1937         if (a->session_id_length != b->session_id_length)
1938                 return(1);
1939         return(memcmp(a->session_id,b->session_id,a->session_id_length));
1940         }
1941
1942 SSL_CTX *SSL_CTX_new(const SSL_METHOD *meth)
1943         {
1944         SSL_CTX *ret=NULL;
1945
1946         if (meth == NULL)
1947                 {
1948                 OPENSSL_PUT_ERROR(SSL, SSL_CTX_new, SSL_R_NULL_SSL_METHOD_PASSED);
1949                 return(NULL);
1950                 }
1951
1952         if (SSL_get_ex_data_X509_STORE_CTX_idx() < 0)
1953                 {
1954                 OPENSSL_PUT_ERROR(SSL, SSL_CTX_new, SSL_R_X509_VERIFICATION_SETUP_PROBLEMS);
1955                 goto err;
1956                 }
1957         ret=(SSL_CTX *)OPENSSL_malloc(sizeof(SSL_CTX));
1958         if (ret == NULL)
1959                 goto err;
1960
1961         memset(ret,0,sizeof(SSL_CTX));
1962
1963         ret->method=meth;
1964
1965         ret->cert_store=NULL;
1966         ret->session_cache_mode=SSL_SESS_CACHE_SERVER;
1967         ret->session_cache_size=SSL_SESSION_CACHE_MAX_SIZE_DEFAULT;
1968         ret->session_cache_head=NULL;
1969         ret->session_cache_tail=NULL;
1970
1971         /* We take the system default */
1972         ret->session_timeout = SSL_DEFAULT_SESSION_TIMEOUT;
1973
1974         ret->new_session_cb=0;
1975         ret->remove_session_cb=0;
1976         ret->get_session_cb=0;
1977         ret->generate_session_id=0;
1978
1979         memset((char *)&ret->stats,0,sizeof(ret->stats));
1980
1981         ret->references=1;
1982         ret->quiet_shutdown=0;
1983
1984         ret->info_callback=NULL;
1985
1986         ret->app_verify_callback=0;
1987         ret->app_verify_arg=NULL;
1988
1989         ret->max_cert_list=SSL_MAX_CERT_LIST_DEFAULT;
1990         ret->read_ahead=0;
1991         ret->msg_callback=0;
1992         ret->msg_callback_arg=NULL;
1993         ret->verify_mode=SSL_VERIFY_NONE;
1994 #if 0
1995         ret->verify_depth=-1; /* Don't impose a limit (but x509_lu.c does) */
1996 #endif
1997         ret->sid_ctx_length=0;
1998         ret->default_verify_callback=NULL;
1999         if ((ret->cert=ssl_cert_new()) == NULL)
2000                 goto err;
2001
2002         ret->default_passwd_callback=0;
2003         ret->default_passwd_callback_userdata=NULL;
2004         ret->client_cert_cb=0;
2005         ret->app_gen_cookie_cb=0;
2006         ret->app_verify_cookie_cb=0;
2007
2008         ret->sessions=lh_SSL_SESSION_new(ssl_session_hash, ssl_session_cmp);
2009         if (ret->sessions == NULL) goto err;
2010         ret->cert_store=X509_STORE_new();
2011         if (ret->cert_store == NULL) goto err;
2012
2013         ssl_create_cipher_list(ret->method,
2014                 &ret->cipher_list,&ret->cipher_list_by_id,
2015                 meth->version == SSL2_VERSION ? "SSLv2" : SSL_DEFAULT_CIPHER_LIST, ret->cert);
2016         if (ret->cipher_list == NULL
2017             || sk_SSL_CIPHER_num(ret->cipher_list->ciphers) <= 0)
2018                 {
2019                 OPENSSL_PUT_ERROR(SSL, SSL_CTX_new, SSL_R_LIBRARY_HAS_NO_CIPHERS);
2020                 goto err2;
2021                 }
2022
2023         ret->param = X509_VERIFY_PARAM_new();
2024         if (!ret->param)
2025                 goto err;
2026
2027         if ((ret->client_CA=sk_X509_NAME_new_null()) == NULL)
2028                 goto err;
2029
2030         CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_CTX, ret, &ret->ex_data);
2031
2032         ret->extra_certs=NULL;
2033
2034         ret->max_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
2035
2036         ret->tlsext_servername_callback = 0;
2037         ret->tlsext_servername_arg = NULL;
2038         /* Setup RFC4507 ticket keys */
2039         if ((RAND_pseudo_bytes(ret->tlsext_tick_key_name, 16) <= 0)
2040                 || (RAND_bytes(ret->tlsext_tick_hmac_key, 16) <= 0)
2041                 || (RAND_bytes(ret->tlsext_tick_aes_key, 16) <= 0))
2042                 ret->options |= SSL_OP_NO_TICKET;
2043
2044         ret->tlsext_status_cb = 0;
2045         ret->tlsext_status_arg = NULL;
2046
2047         ret->next_protos_advertised_cb = 0;
2048         ret->next_proto_select_cb = 0;
2049         ret->psk_identity_hint=NULL;
2050         ret->psk_client_callback=NULL;
2051         ret->psk_server_callback=NULL;
2052
2053         /* Default is to connect to non-RI servers. When RI is more widely
2054          * deployed might change this.
2055          */
2056         ret->options |= SSL_OP_LEGACY_SERVER_CONNECT;
2057
2058         return(ret);
2059 err:
2060         OPENSSL_PUT_ERROR(SSL, SSL_CTX_new, ERR_R_MALLOC_FAILURE);
2061 err2:
2062         if (ret != NULL) SSL_CTX_free(ret);
2063         return(NULL);
2064         }
2065
2066
2067 void SSL_CTX_free(SSL_CTX *a)
2068         {
2069         int i;
2070
2071         if (a == NULL) return;
2072
2073         i=CRYPTO_add(&a->references,-1,CRYPTO_LOCK_SSL_CTX);
2074 #ifdef REF_PRINT
2075         REF_PRINT("SSL_CTX",a);
2076 #endif
2077         if (i > 0) return;
2078 #ifdef REF_CHECK
2079         if (i < 0)
2080                 {
2081                 fprintf(stderr,"SSL_CTX_free, bad reference count\n");
2082                 abort(); /* ok */
2083                 }
2084 #endif
2085
2086         if (a->param)
2087                 X509_VERIFY_PARAM_free(a->param);
2088
2089         /*
2090          * Free internal session cache. However: the remove_cb() may reference
2091          * the ex_data of SSL_CTX, thus the ex_data store can only be removed
2092          * after the sessions were flushed.
2093          * As the ex_data handling routines might also touch the session cache,
2094          * the most secure solution seems to be: empty (flush) the cache, then
2095          * free ex_data, then finally free the cache.
2096          * (See ticket [openssl.org #212].)
2097          */
2098         if (a->sessions != NULL)
2099                 SSL_CTX_flush_sessions(a,0);
2100
2101         CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL_CTX, a, &a->ex_data);
2102
2103         if (a->sessions != NULL)
2104                 lh_SSL_SESSION_free(a->sessions);
2105
2106         if (a->cert_store != NULL)
2107                 X509_STORE_free(a->cert_store);
2108         if (a->cipher_list != NULL)
2109                 ssl_cipher_preference_list_free(a->cipher_list);
2110         if (a->cipher_list_by_id != NULL)
2111                 sk_SSL_CIPHER_free(a->cipher_list_by_id);
2112         if (a->cipher_list_tls11 != NULL)
2113                 ssl_cipher_preference_list_free(a->cipher_list_tls11);
2114         if (a->cert != NULL)
2115                 ssl_cert_free(a->cert);
2116         if (a->client_CA != NULL)
2117                 sk_X509_NAME_pop_free(a->client_CA,X509_NAME_free);
2118         if (a->extra_certs != NULL)
2119                 sk_X509_pop_free(a->extra_certs,X509_free);
2120
2121         if (a->srtp_profiles)
2122                 sk_SRTP_PROTECTION_PROFILE_free(a->srtp_profiles);
2123
2124         if (a->psk_identity_hint)
2125                 OPENSSL_free(a->psk_identity_hint);
2126
2127         if (a->tlsext_ecpointformatlist)
2128                 OPENSSL_free(a->tlsext_ecpointformatlist);
2129         if (a->tlsext_ellipticcurvelist)
2130                 OPENSSL_free(a->tlsext_ellipticcurvelist);
2131         if (a->alpn_client_proto_list != NULL)
2132                 OPENSSL_free(a->alpn_client_proto_list);
2133
2134         if (a->tlsext_channel_id_private)
2135                 EVP_PKEY_free(a->tlsext_channel_id_private);
2136
2137         if (a->keylog_bio)
2138                 BIO_free(a->keylog_bio);
2139
2140         OPENSSL_free(a);
2141         }
2142
2143 void SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx, pem_password_cb *cb)
2144         {
2145         ctx->default_passwd_callback=cb;
2146         }
2147
2148 void SSL_CTX_set_default_passwd_cb_userdata(SSL_CTX *ctx,void *u)
2149         {
2150         ctx->default_passwd_callback_userdata=u;
2151         }
2152
2153 void SSL_CTX_set_cert_verify_callback(SSL_CTX *ctx, int (*cb)(X509_STORE_CTX *,void *), void *arg)
2154         {
2155         ctx->app_verify_callback=cb;
2156         ctx->app_verify_arg=arg;
2157         }
2158
2159 void SSL_CTX_set_verify(SSL_CTX *ctx,int mode,int (*cb)(int, X509_STORE_CTX *))
2160         {
2161         ctx->verify_mode=mode;
2162         ctx->default_verify_callback=cb;
2163         }
2164
2165 void SSL_CTX_set_verify_depth(SSL_CTX *ctx,int depth)
2166         {
2167         X509_VERIFY_PARAM_set_depth(ctx->param, depth);
2168         }
2169
2170 void SSL_CTX_set_cert_cb(SSL_CTX *c, int (*cb)(SSL *ssl, void *arg), void *arg)
2171         {
2172         ssl_cert_set_cert_cb(c->cert, cb, arg);
2173         }
2174
2175 void SSL_set_cert_cb(SSL *s, int (*cb)(SSL *ssl, void *arg), void *arg)
2176         {
2177         ssl_cert_set_cert_cb(s->cert, cb, arg);
2178         }
2179
2180 void ssl_set_cert_masks(CERT *c, const SSL_CIPHER *cipher)
2181         {
2182         CERT_PKEY *cpk;
2183         int rsa_enc,rsa_sign,dh_tmp;
2184         unsigned long mask_k,mask_a;
2185         int have_ecc_cert, ecdsa_ok;
2186         int have_ecdh_tmp;
2187         X509 *x = NULL;
2188         if (c == NULL) return;
2189
2190         dh_tmp=(c->dh_tmp != NULL || c->dh_tmp_cb != NULL);
2191
2192         have_ecdh_tmp=(c->ecdh_tmp || c->ecdh_tmp_cb || c->ecdh_tmp_auto);
2193         cpk= &(c->pkeys[SSL_PKEY_RSA_ENC]);
2194         rsa_enc= cpk->valid_flags & CERT_PKEY_VALID;
2195         cpk= &(c->pkeys[SSL_PKEY_RSA_SIGN]);
2196         rsa_sign= cpk->valid_flags & CERT_PKEY_SIGN;
2197         cpk= &(c->pkeys[SSL_PKEY_ECC]);
2198         have_ecc_cert= cpk->valid_flags & CERT_PKEY_VALID;
2199         mask_k=0;
2200         mask_a=0;
2201
2202 #ifdef CIPHER_DEBUG
2203         printf("rt=%d rte=%d dht=%d ecdht=%d re=%d ree=%d rs=%d ds=%d dhr=%d dhd=%d\n",
2204                 rsa_tmp,rsa_tmp_export,dh_tmp,have_ecdh_tmp,
2205                 rsa_enc,rsa_enc_export,rsa_sign,dsa_sign,dh_rsa,dh_dsa);
2206 #endif
2207         
2208         if (rsa_enc)
2209                 mask_k|=SSL_kRSA;
2210
2211         if (dh_tmp)
2212                 mask_k|=SSL_kEDH;
2213
2214         if (rsa_enc || rsa_sign)
2215                 {
2216                 mask_a|=SSL_aRSA;
2217                 }
2218
2219         mask_a|=SSL_aNULL;
2220
2221         /* An ECC certificate may be usable for ECDSA cipher suites depending on
2222          * the key usage extension. */
2223         if (have_ecc_cert)
2224                 {
2225                 cpk = &c->pkeys[SSL_PKEY_ECC];
2226                 x = cpk->x509;
2227                 /* This call populates extension flags (ex_flags) */
2228                 X509_check_purpose(x, -1, 0);
2229                 ecdsa_ok = (x->ex_flags & EXFLAG_KUSAGE) ?
2230                     (x->ex_kusage & X509v3_KU_DIGITAL_SIGNATURE) : 1;
2231                 if (!(cpk->valid_flags & CERT_PKEY_SIGN))
2232                         ecdsa_ok = 0;
2233                 if (ecdsa_ok)
2234                         {
2235                         mask_a|=SSL_aECDSA;
2236                         }
2237                 }
2238
2239         if (have_ecdh_tmp)
2240                 {
2241                 mask_k|=SSL_kEECDH;
2242                 }
2243
2244         mask_k |= SSL_kPSK;
2245         mask_a |= SSL_aPSK;
2246
2247         c->mask_k=mask_k;
2248         c->mask_a=mask_a;
2249         c->valid=1;
2250         }
2251
2252 /* This handy macro borrowed from crypto/x509v3/v3_purp.c */
2253 #define ku_reject(x, usage) \
2254         (((x)->ex_flags & EXFLAG_KUSAGE) && !((x)->ex_kusage & (usage)))
2255
2256
2257 int ssl_check_srvr_ecc_cert_and_alg(X509 *x, SSL *s)
2258         {
2259         unsigned long alg_a;
2260         int signature_nid = 0, md_nid = 0, pk_nid = 0;
2261         const SSL_CIPHER *cs = s->s3->tmp.new_cipher;
2262
2263         alg_a = cs->algorithm_auth;
2264
2265         /* This call populates the ex_flags field correctly */
2266         X509_check_purpose(x, -1, 0);
2267         if ((x->sig_alg) && (x->sig_alg->algorithm))
2268                 {
2269                 signature_nid = OBJ_obj2nid(x->sig_alg->algorithm);
2270                 OBJ_find_sigid_algs(signature_nid, &md_nid, &pk_nid);
2271                 }
2272         if (alg_a & SSL_aECDSA)
2273                 {
2274                 /* key usage, if present, must allow signing */
2275                 if (ku_reject(x, X509v3_KU_DIGITAL_SIGNATURE))
2276                         {
2277                         OPENSSL_PUT_ERROR(SSL, ssl_check_srvr_ecc_cert_and_alg, SSL_R_ECC_CERT_NOT_FOR_SIGNING);
2278                         return 0;
2279                         }
2280                 }
2281
2282         return 1;  /* all checks are ok */
2283         }
2284
2285
2286 static int ssl_get_server_cert_index(const SSL *s)
2287         {
2288         int idx;
2289         idx = ssl_cipher_get_cert_index(s->s3->tmp.new_cipher);
2290         if (idx == SSL_PKEY_RSA_ENC && !s->cert->pkeys[SSL_PKEY_RSA_ENC].x509)
2291                 idx = SSL_PKEY_RSA_SIGN;
2292         if (idx == -1)
2293                 OPENSSL_PUT_ERROR(SSL, ssl_get_server_cert_index, ERR_R_INTERNAL_ERROR);
2294         return idx;
2295         }
2296
2297 CERT_PKEY *ssl_get_server_send_pkey(const SSL *s)
2298         {
2299         CERT *c;
2300         int i;
2301
2302         c = s->cert;
2303         ssl_set_cert_masks(c, s->s3->tmp.new_cipher);
2304
2305 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
2306         /* Broken protocol test: return last used certificate: which may
2307          * mismatch the one expected.
2308          */
2309         if (c->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL)
2310                 return c->key;
2311 #endif
2312
2313         i = ssl_get_server_cert_index(s);
2314
2315         /* This may or may not be an error. */
2316         if (i < 0)
2317                 return NULL;
2318
2319         /* May be NULL. */
2320         return &c->pkeys[i];
2321         }
2322
2323 EVP_PKEY *ssl_get_sign_pkey(SSL *s,const SSL_CIPHER *cipher, const EVP_MD **pmd)
2324         {
2325         unsigned long alg_a;
2326         CERT *c;
2327         int idx = -1;
2328
2329         alg_a = cipher->algorithm_auth;
2330         c=s->cert;
2331
2332 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
2333         /* Broken protocol test: use last key: which may
2334          * mismatch the one expected.
2335          */
2336         if (c->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL)
2337                 idx = c->key - c->pkeys;
2338         else
2339 #endif
2340
2341         if (alg_a & SSL_aRSA)
2342                 {
2343                 if (c->pkeys[SSL_PKEY_RSA_SIGN].privatekey != NULL)
2344                         idx = SSL_PKEY_RSA_SIGN;
2345                 else if (c->pkeys[SSL_PKEY_RSA_ENC].privatekey != NULL)
2346                         idx = SSL_PKEY_RSA_ENC;
2347                 }
2348         else if ((alg_a & SSL_aECDSA) &&
2349                  (c->pkeys[SSL_PKEY_ECC].privatekey != NULL))
2350                 idx = SSL_PKEY_ECC;
2351         if (idx == -1)
2352                 {
2353                 OPENSSL_PUT_ERROR(SSL, ssl_get_sign_pkey, ERR_R_INTERNAL_ERROR);
2354                 return(NULL);
2355                 }
2356         if (pmd)
2357                 *pmd = c->pkeys[idx].digest;
2358         return c->pkeys[idx].privatekey;
2359         }
2360
2361 void ssl_update_cache(SSL *s,int mode)
2362         {
2363         int i;
2364
2365         /* If the session_id_length is 0, we are not supposed to cache it,
2366          * and it would be rather hard to do anyway :-) */
2367         if (s->session->session_id_length == 0) return;
2368
2369         i=s->initial_ctx->session_cache_mode;
2370         if ((i & mode) && (!s->hit)
2371                 && ((i & SSL_SESS_CACHE_NO_INTERNAL_STORE)
2372                     || SSL_CTX_add_session(s->initial_ctx,s->session))
2373                 && (s->initial_ctx->new_session_cb != NULL))
2374                 {
2375                 CRYPTO_add(&s->session->references,1,CRYPTO_LOCK_SSL_SESSION);
2376                 if (!s->initial_ctx->new_session_cb(s,s->session))
2377                         SSL_SESSION_free(s->session);
2378                 }
2379
2380         /* auto flush every 255 connections */
2381         if ((!(i & SSL_SESS_CACHE_NO_AUTO_CLEAR)) &&
2382                 ((i & mode) == mode))
2383                 {
2384                 if (  (((mode & SSL_SESS_CACHE_CLIENT)
2385                         ?s->initial_ctx->stats.sess_connect_good
2386                         :s->initial_ctx->stats.sess_accept_good) & 0xff) == 0xff)
2387                         {
2388                         SSL_CTX_flush_sessions(s->initial_ctx,(unsigned long)time(NULL));
2389                         }
2390                 }
2391         }
2392
2393 const SSL_METHOD *SSL_CTX_get_ssl_method(SSL_CTX *ctx)
2394         {
2395         return ctx->method;
2396         }
2397
2398 const SSL_METHOD *SSL_get_ssl_method(SSL *s)
2399         {
2400         return(s->method);
2401         }
2402
2403 int SSL_set_ssl_method(SSL *s, const SSL_METHOD *meth)
2404         {
2405         int conn= -1;
2406         int ret=1;
2407
2408         if (s->method != meth)
2409                 {
2410                 if (s->handshake_func != NULL)
2411                         conn=(s->handshake_func == s->method->ssl_connect);
2412
2413                 if (s->method->version == meth->version)
2414                         s->method=meth;
2415                 else
2416                         {
2417                         s->method->ssl_free(s);
2418                         s->method=meth;
2419                         ret=s->method->ssl_new(s);
2420                         }
2421
2422                 if (conn == 1)
2423                         s->handshake_func=meth->ssl_connect;
2424                 else if (conn == 0)
2425                         s->handshake_func=meth->ssl_accept;
2426                 }
2427         return(ret);
2428         }
2429
2430 int SSL_get_error(const SSL *s,int i)
2431         {
2432         int reason;
2433         unsigned long l;
2434         BIO *bio;
2435
2436         if (i > 0) return(SSL_ERROR_NONE);
2437
2438         /* Make things return SSL_ERROR_SYSCALL when doing SSL_do_handshake
2439          * etc, where we do encode the error */
2440         if ((l=ERR_peek_error()) != 0)
2441                 {
2442                 if (ERR_GET_LIB(l) == ERR_LIB_SYS)
2443                         return(SSL_ERROR_SYSCALL);
2444                 else
2445                         return(SSL_ERROR_SSL);
2446                 }
2447
2448         if ((i < 0) && SSL_want_session(s))
2449                 return(SSL_ERROR_PENDING_SESSION);
2450
2451         if ((i < 0) && SSL_want_certificate(s))
2452                 return(SSL_ERROR_PENDING_CERTIFICATE);
2453
2454         if ((i < 0) && SSL_want_read(s))
2455                 {
2456                 bio=SSL_get_rbio(s);
2457                 if (BIO_should_read(bio))
2458                         return(SSL_ERROR_WANT_READ);
2459                 else if (BIO_should_write(bio))
2460                         /* This one doesn't make too much sense ... We never try
2461                          * to write to the rbio, and an application program where
2462                          * rbio and wbio are separate couldn't even know what it
2463                          * should wait for.
2464                          * However if we ever set s->rwstate incorrectly
2465                          * (so that we have SSL_want_read(s) instead of
2466                          * SSL_want_write(s)) and rbio and wbio *are* the same,
2467                          * this test works around that bug; so it might be safer
2468                          * to keep it. */
2469                         return(SSL_ERROR_WANT_WRITE);
2470                 else if (BIO_should_io_special(bio))
2471                         {
2472                         reason=BIO_get_retry_reason(bio);
2473                         if (reason == BIO_RR_CONNECT)
2474                                 return(SSL_ERROR_WANT_CONNECT);
2475                         else if (reason == BIO_RR_ACCEPT)
2476                                 return(SSL_ERROR_WANT_ACCEPT);
2477                         else
2478                                 return(SSL_ERROR_SYSCALL); /* unknown */
2479                         }
2480                 }
2481
2482         if ((i < 0) && SSL_want_write(s))
2483                 {
2484                 bio=SSL_get_wbio(s);
2485                 if (BIO_should_write(bio))
2486                         return(SSL_ERROR_WANT_WRITE);
2487                 else if (BIO_should_read(bio))
2488                         /* See above (SSL_want_read(s) with BIO_should_write(bio)) */
2489                         return(SSL_ERROR_WANT_READ);
2490                 else if (BIO_should_io_special(bio))
2491                         {
2492                         reason=BIO_get_retry_reason(bio);
2493                         if (reason == BIO_RR_CONNECT)
2494                                 return(SSL_ERROR_WANT_CONNECT);
2495                         else if (reason == BIO_RR_ACCEPT)
2496                                 return(SSL_ERROR_WANT_ACCEPT);
2497                         else
2498                                 return(SSL_ERROR_SYSCALL);
2499                         }
2500                 }
2501         if ((i < 0) && SSL_want_x509_lookup(s))
2502                 {
2503                 return(SSL_ERROR_WANT_X509_LOOKUP);
2504                 }
2505         if ((i < 0) && SSL_want_channel_id_lookup(s))
2506                 {
2507                 return(SSL_ERROR_WANT_CHANNEL_ID_LOOKUP);
2508                 }
2509
2510         if (i == 0)
2511                 {
2512                 if (s->version == SSL2_VERSION)
2513                         {
2514                         /* assume it is the socket being closed */
2515                         return(SSL_ERROR_ZERO_RETURN);
2516                         }
2517                 else
2518                         {
2519                         if ((s->shutdown & SSL_RECEIVED_SHUTDOWN) &&
2520                                 (s->s3->warn_alert == SSL_AD_CLOSE_NOTIFY))
2521                                 return(SSL_ERROR_ZERO_RETURN);
2522                         }
2523                 }
2524         return(SSL_ERROR_SYSCALL);
2525         }
2526
2527 int SSL_do_handshake(SSL *s)
2528         {
2529         int ret=1;
2530
2531         if (s->handshake_func == NULL)
2532                 {
2533                 OPENSSL_PUT_ERROR(SSL, SSL_do_handshake, SSL_R_CONNECTION_TYPE_NOT_SET);
2534                 return(-1);
2535                 }
2536
2537         s->method->ssl_renegotiate_check(s);
2538
2539         if (SSL_in_init(s) || SSL_in_before(s))
2540                 {
2541                 ret=s->handshake_func(s);
2542                 }
2543         return(ret);
2544         }
2545
2546 /* For the next 2 functions, SSL_clear() sets shutdown and so
2547  * one of these calls will reset it */
2548 void SSL_set_accept_state(SSL *s)
2549         {
2550         s->server=1;
2551         s->shutdown=0;
2552         s->state=SSL_ST_ACCEPT|SSL_ST_BEFORE;
2553         s->handshake_func=s->method->ssl_accept;
2554         /* clear the current cipher */
2555         ssl_clear_cipher_ctx(s);
2556         ssl_clear_hash_ctx(&s->read_hash);
2557         ssl_clear_hash_ctx(&s->write_hash);
2558         }
2559
2560 void SSL_set_connect_state(SSL *s)
2561         {
2562         s->server=0;
2563         s->shutdown=0;
2564         s->state=SSL_ST_CONNECT|SSL_ST_BEFORE;
2565         s->handshake_func=s->method->ssl_connect;
2566         /* clear the current cipher */
2567         ssl_clear_cipher_ctx(s);
2568         ssl_clear_hash_ctx(&s->read_hash);
2569         ssl_clear_hash_ctx(&s->write_hash);
2570         }
2571
2572 int ssl_undefined_function(SSL *s)
2573         {
2574         OPENSSL_PUT_ERROR(SSL, ssl_undefined_function, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2575         return(0);
2576         }
2577
2578 int ssl_undefined_void_function(void)
2579         {
2580         OPENSSL_PUT_ERROR(SSL, ssl_undefined_void_function, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2581         return(0);
2582         }
2583
2584 int ssl_undefined_const_function(const SSL *s)
2585         {
2586         OPENSSL_PUT_ERROR(SSL, ssl_undefined_const_function, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2587         return(0);
2588         }
2589
2590 SSL_METHOD *ssl_bad_method(int ver)
2591         {
2592         OPENSSL_PUT_ERROR(SSL, ssl_bad_method, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2593         return(NULL);
2594         }
2595
2596 static const char *ssl_get_version(int version)
2597         {
2598         if (version == TLS1_2_VERSION)
2599                 return("TLSv1.2");
2600         else if (version == TLS1_1_VERSION)
2601                 return("TLSv1.1");
2602         else if (version == TLS1_VERSION)
2603                 return("TLSv1");
2604         else if (version == SSL3_VERSION)
2605                 return("SSLv3");
2606         else if (version == SSL2_VERSION)
2607                 return("SSLv2");
2608         else
2609                 return("unknown");
2610         }
2611
2612 const char *SSL_get_version(const SSL *s)
2613         {
2614         return ssl_get_version(s->version);
2615         }
2616
2617 const char *SSL_SESSION_get_version(const SSL_SESSION *sess)
2618         {
2619         return ssl_get_version(sess->ssl_version);
2620         }
2621
2622 void ssl_clear_cipher_ctx(SSL *s)
2623         {
2624         if (s->enc_read_ctx != NULL)
2625                 {
2626                 EVP_CIPHER_CTX_cleanup(s->enc_read_ctx);
2627                 OPENSSL_free(s->enc_read_ctx);
2628                 s->enc_read_ctx=NULL;
2629                 }
2630         if (s->enc_write_ctx != NULL)
2631                 {
2632                 EVP_CIPHER_CTX_cleanup(s->enc_write_ctx);
2633                 OPENSSL_free(s->enc_write_ctx);
2634                 s->enc_write_ctx=NULL;
2635                 }
2636         if (s->aead_read_ctx != NULL)
2637                 {
2638                 EVP_AEAD_CTX_cleanup(&s->aead_read_ctx->ctx);
2639                 OPENSSL_free(s->aead_read_ctx);
2640                 s->aead_read_ctx = NULL;
2641                 }
2642         if (s->aead_write_ctx != NULL)
2643                 {
2644                 EVP_AEAD_CTX_cleanup(&s->aead_write_ctx->ctx);
2645                 OPENSSL_free(s->aead_write_ctx);
2646                 s->aead_write_ctx = NULL;
2647                 }
2648         }
2649
2650 X509 *SSL_get_certificate(const SSL *s)
2651         {
2652         if (s->cert != NULL)
2653                 return(s->cert->key->x509);
2654         else
2655                 return(NULL);
2656         }
2657
2658 EVP_PKEY *SSL_get_privatekey(const SSL *s)
2659         {
2660         if (s->cert != NULL)
2661                 return(s->cert->key->privatekey);
2662         else
2663                 return(NULL);
2664         }
2665
2666 X509 *SSL_CTX_get0_certificate(const SSL_CTX *ctx)
2667         {
2668         if (ctx->cert != NULL)
2669                 return ctx->cert->key->x509;
2670         else
2671                 return NULL;
2672         }
2673
2674 EVP_PKEY *SSL_CTX_get0_privatekey(const SSL_CTX *ctx)
2675         {
2676         if (ctx->cert != NULL)
2677                 return ctx->cert->key->privatekey;
2678         else
2679                 return NULL ;
2680         }
2681
2682 const SSL_CIPHER *SSL_get_current_cipher(const SSL *s)
2683         {
2684         if ((s->session != NULL) && (s->session->cipher != NULL))
2685                 return(s->session->cipher);
2686         return(NULL);
2687         }
2688 const void *SSL_get_current_compression(SSL *s)
2689         {
2690         return NULL;
2691         }
2692 const void *SSL_get_current_expansion(SSL *s)
2693         {
2694         return NULL;
2695         }
2696
2697 int ssl_init_wbio_buffer(SSL *s,int push)
2698         {
2699         BIO *bbio;
2700
2701         if (s->bbio == NULL)
2702                 {
2703                 bbio=BIO_new(BIO_f_buffer());
2704                 if (bbio == NULL) return(0);
2705                 s->bbio=bbio;
2706                 }
2707         else
2708                 {
2709                 bbio=s->bbio;
2710                 if (s->bbio == s->wbio)
2711                         s->wbio=BIO_pop(s->wbio);
2712                 }
2713         (void)BIO_reset(bbio);
2714 /*      if (!BIO_set_write_buffer_size(bbio,16*1024)) */
2715         if (!BIO_set_read_buffer_size(bbio,1))
2716                 {
2717                 OPENSSL_PUT_ERROR(SSL, ssl_init_wbio_buffer, ERR_R_BUF_LIB);
2718                 return(0);
2719                 }
2720         if (push)
2721                 {
2722                 if (s->wbio != bbio)
2723                         s->wbio=BIO_push(bbio,s->wbio);
2724                 }
2725         else
2726                 {
2727                 if (s->wbio == bbio)
2728                         s->wbio=BIO_pop(bbio);
2729                 }
2730         return(1);
2731         }
2732
2733 void ssl_free_wbio_buffer(SSL *s)
2734         {
2735         if (s->bbio == NULL) return;
2736
2737         if (s->bbio == s->wbio)
2738                 {
2739                 /* remove buffering */
2740                 s->wbio=BIO_pop(s->wbio);
2741 #ifdef REF_CHECK /* not the usual REF_CHECK, but this avoids adding one more preprocessor symbol */
2742                 assert(s->wbio != NULL);
2743 #endif
2744         }
2745         BIO_free(s->bbio);
2746         s->bbio=NULL;
2747         }
2748         
2749 void SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx,int mode)
2750         {
2751         ctx->quiet_shutdown=mode;
2752         }
2753
2754 int SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx)
2755         {
2756         return(ctx->quiet_shutdown);
2757         }
2758
2759 void SSL_set_quiet_shutdown(SSL *s,int mode)
2760         {
2761         s->quiet_shutdown=mode;
2762         }
2763
2764 int SSL_get_quiet_shutdown(const SSL *s)
2765         {
2766         return(s->quiet_shutdown);
2767         }
2768
2769 void SSL_set_shutdown(SSL *s,int mode)
2770         {
2771         s->shutdown=mode;
2772         }
2773
2774 int SSL_get_shutdown(const SSL *s)
2775         {
2776         return(s->shutdown);
2777         }
2778
2779 int SSL_version(const SSL *s)
2780         {
2781         return(s->version);
2782         }
2783
2784 SSL_CTX *SSL_get_SSL_CTX(const SSL *ssl)
2785         {
2786         return(ssl->ctx);
2787         }
2788
2789 SSL_CTX *SSL_set_SSL_CTX(SSL *ssl, SSL_CTX* ctx)
2790         {
2791         if (ssl->ctx == ctx)
2792                 return ssl->ctx;
2793         if (ctx == NULL)
2794                 ctx = ssl->initial_ctx;
2795         if (ssl->cert != NULL)
2796                 ssl_cert_free(ssl->cert);
2797         ssl->cert = ssl_cert_dup(ctx->cert);
2798         CRYPTO_add(&ctx->references,1,CRYPTO_LOCK_SSL_CTX);
2799         if (ssl->ctx != NULL)
2800                 SSL_CTX_free(ssl->ctx); /* decrement reference count */
2801         ssl->ctx = ctx;
2802
2803         ssl->sid_ctx_length = ctx->sid_ctx_length;
2804         assert(ssl->sid_ctx_length <= sizeof(ssl->sid_ctx));
2805         memcpy(ssl->sid_ctx, ctx->sid_ctx, sizeof(ssl->sid_ctx));
2806
2807         return(ssl->ctx);
2808         }
2809
2810 #ifndef OPENSSL_NO_STDIO
2811 int SSL_CTX_set_default_verify_paths(SSL_CTX *ctx)
2812         {
2813         return(X509_STORE_set_default_paths(ctx->cert_store));
2814         }
2815
2816 int SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile,
2817                 const char *CApath)
2818         {
2819         return(X509_STORE_load_locations(ctx->cert_store,CAfile,CApath));
2820         }
2821 #endif
2822
2823 void SSL_set_info_callback(SSL *ssl,
2824         void (*cb)(const SSL *ssl,int type,int val))
2825         {
2826         ssl->info_callback=cb;
2827         }
2828
2829 /* One compiler (Diab DCC) doesn't like argument names in returned
2830    function pointer.  */
2831 void (*SSL_get_info_callback(const SSL *ssl))(const SSL * /*ssl*/,int /*type*/,int /*val*/)
2832         {
2833         return ssl->info_callback;
2834         }
2835
2836 int SSL_state(const SSL *ssl)
2837         {
2838         return(ssl->state);
2839         }
2840
2841 void SSL_set_state(SSL *ssl, int state)
2842         {
2843         ssl->state = state;
2844         }
2845
2846 void SSL_set_verify_result(SSL *ssl,long arg)
2847         {
2848         ssl->verify_result=arg;
2849         }
2850
2851 long SSL_get_verify_result(const SSL *ssl)
2852         {
2853         return(ssl->verify_result);
2854         }
2855
2856 int SSL_get_ex_new_index(long argl,void *argp,CRYPTO_EX_new *new_func,
2857                          CRYPTO_EX_dup *dup_func,CRYPTO_EX_free *free_func)
2858         {
2859         return CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL, argl, argp,
2860                                 new_func, dup_func, free_func);
2861         }
2862
2863 int SSL_set_ex_data(SSL *s,int idx,void *arg)
2864         {
2865         return(CRYPTO_set_ex_data(&s->ex_data,idx,arg));
2866         }
2867
2868 void *SSL_get_ex_data(const SSL *s,int idx)
2869         {
2870         return(CRYPTO_get_ex_data(&s->ex_data,idx));
2871         }
2872
2873 int SSL_CTX_get_ex_new_index(long argl,void *argp,CRYPTO_EX_new *new_func,
2874                              CRYPTO_EX_dup *dup_func,CRYPTO_EX_free *free_func)
2875         {
2876         return CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL_CTX, argl, argp,
2877                                 new_func, dup_func, free_func);
2878         }
2879
2880 int SSL_CTX_set_ex_data(SSL_CTX *s,int idx,void *arg)
2881         {
2882         return(CRYPTO_set_ex_data(&s->ex_data,idx,arg));
2883         }
2884
2885 void *SSL_CTX_get_ex_data(const SSL_CTX *s,int idx)
2886         {
2887         return(CRYPTO_get_ex_data(&s->ex_data,idx));
2888         }
2889
2890 int ssl_ok(SSL *s)
2891         {
2892         return(1);
2893         }
2894
2895 X509_STORE *SSL_CTX_get_cert_store(const SSL_CTX *ctx)
2896         {
2897         return(ctx->cert_store);
2898         }
2899
2900 void SSL_CTX_set_cert_store(SSL_CTX *ctx,X509_STORE *store)
2901         {
2902         if (ctx->cert_store != NULL)
2903                 X509_STORE_free(ctx->cert_store);
2904         ctx->cert_store=store;
2905         }
2906
2907 int SSL_want(const SSL *s)
2908         {
2909         return(s->rwstate);
2910         }
2911
2912 /*!
2913  * \brief Set the callback for generating temporary RSA keys.
2914  * \param ctx the SSL context.
2915  * \param cb the callback
2916  */
2917
2918 void SSL_CTX_set_tmp_rsa_callback(SSL_CTX *ctx,RSA *(*cb)(SSL *ssl,
2919                                                           int is_export,
2920                                                           int keylength))
2921     {
2922     SSL_CTX_callback_ctrl(ctx,SSL_CTRL_SET_TMP_RSA_CB,(void (*)(void))cb);
2923     }
2924
2925 void SSL_set_tmp_rsa_callback(SSL *ssl,RSA *(*cb)(SSL *ssl,
2926                                                   int is_export,
2927                                                   int keylength))
2928     {
2929     SSL_callback_ctrl(ssl,SSL_CTRL_SET_TMP_RSA_CB,(void (*)(void))cb);
2930     }
2931
2932 #ifdef DOXYGEN
2933 /*!
2934  * \brief The RSA temporary key callback function.
2935  * \param ssl the SSL session.
2936  * \param is_export \c TRUE if the temp RSA key is for an export ciphersuite.
2937  * \param keylength if \c is_export is \c TRUE, then \c keylength is the size
2938  * of the required key in bits.
2939  * \return the temporary RSA key.
2940  * \sa SSL_CTX_set_tmp_rsa_callback, SSL_set_tmp_rsa_callback
2941  */
2942
2943 RSA *cb(SSL *ssl,int is_export,int keylength)
2944     {}
2945 #endif
2946
2947 /*!
2948  * \brief Set the callback for generating temporary DH keys.
2949  * \param ctx the SSL context.
2950  * \param dh the callback
2951  */
2952
2953 void SSL_CTX_set_tmp_dh_callback(SSL_CTX *ctx,DH *(*dh)(SSL *ssl,int is_export,
2954                                                         int keylength))
2955         {
2956         SSL_CTX_callback_ctrl(ctx,SSL_CTRL_SET_TMP_DH_CB,(void (*)(void))dh);
2957         }
2958
2959 void SSL_set_tmp_dh_callback(SSL *ssl,DH *(*dh)(SSL *ssl,int is_export,
2960                                                 int keylength))
2961         {
2962         SSL_callback_ctrl(ssl,SSL_CTRL_SET_TMP_DH_CB,(void (*)(void))dh);
2963         }
2964
2965 void SSL_CTX_set_tmp_ecdh_callback(SSL_CTX *ctx,EC_KEY *(*ecdh)(SSL *ssl,int is_export,
2966                                                                 int keylength))
2967         {
2968         SSL_CTX_callback_ctrl(ctx,SSL_CTRL_SET_TMP_ECDH_CB,(void (*)(void))ecdh);
2969         }
2970
2971 void SSL_set_tmp_ecdh_callback(SSL *ssl,EC_KEY *(*ecdh)(SSL *ssl,int is_export,
2972                                                         int keylength))
2973         {
2974         SSL_callback_ctrl(ssl,SSL_CTRL_SET_TMP_ECDH_CB,(void (*)(void))ecdh);
2975         }
2976
2977 int SSL_CTX_use_psk_identity_hint(SSL_CTX *ctx, const char *identity_hint)
2978         {
2979         if (identity_hint != NULL && strlen(identity_hint) > PSK_MAX_IDENTITY_LEN)
2980                 {
2981                 OPENSSL_PUT_ERROR(SSL, SSL_CTX_use_psk_identity_hint, SSL_R_DATA_LENGTH_TOO_LONG);
2982                 return 0;
2983                 }
2984         if (ctx->psk_identity_hint != NULL)
2985                 OPENSSL_free(ctx->psk_identity_hint);
2986         if (identity_hint != NULL)
2987                 {
2988                 ctx->psk_identity_hint = BUF_strdup(identity_hint);
2989                 if (ctx->psk_identity_hint == NULL)
2990                         return 0;
2991                 }
2992         else
2993                 ctx->psk_identity_hint = NULL;
2994         return 1;
2995         }
2996
2997 int SSL_use_psk_identity_hint(SSL *s, const char *identity_hint)
2998         {
2999         if (s == NULL)
3000                 return 0;
3001
3002         if (identity_hint != NULL && strlen(identity_hint) > PSK_MAX_IDENTITY_LEN)
3003                 {
3004                 OPENSSL_PUT_ERROR(SSL, SSL_use_psk_identity_hint, SSL_R_DATA_LENGTH_TOO_LONG);
3005                 return 0;
3006                 }
3007
3008         /* Clear hint in SSL and associated SSL_SESSION (if any). */
3009         if (s->psk_identity_hint != NULL)
3010                 {
3011                 OPENSSL_free(s->psk_identity_hint);
3012                 s->psk_identity_hint = NULL;
3013                 }
3014         if (s->session != NULL && s->session->psk_identity_hint != NULL)
3015                 {
3016                 OPENSSL_free(s->session->psk_identity_hint);
3017                 s->session->psk_identity_hint = NULL;
3018                 }
3019
3020         if (identity_hint != NULL)
3021                 {
3022                 /* The hint is stored in SSL and SSL_SESSION with the one in
3023                  * SSL_SESSION taking precedence. Thus, if SSL_SESSION is avaiable,
3024                  * we store the hint there, otherwise we store it in SSL. */
3025                 if (s->session != NULL)
3026                         {
3027                         s->session->psk_identity_hint = BUF_strdup(identity_hint);
3028                         if (s->session->psk_identity_hint == NULL)
3029                                 return 0;
3030                         }
3031                 else
3032                         {
3033                         s->psk_identity_hint = BUF_strdup(identity_hint);
3034                         if (s->psk_identity_hint == NULL)
3035                                 return 0;
3036                         }
3037                 }
3038         return 1;
3039         }
3040
3041 const char *SSL_get_psk_identity_hint(const SSL *s)
3042         {
3043         if (s == NULL)
3044                 return NULL;
3045         /* The hint is stored in SSL and SSL_SESSION with the one in SSL_SESSION
3046          * taking precedence. */
3047         if (s->session != NULL)
3048                 return(s->session->psk_identity_hint);
3049         return(s->psk_identity_hint);
3050         }
3051
3052 const char *SSL_get_psk_identity(const SSL *s)
3053         {
3054         if (s == NULL || s->session == NULL)
3055                 return NULL;
3056         return(s->session->psk_identity);
3057         }
3058
3059 void SSL_set_psk_client_callback(SSL *s,
3060     unsigned int (*cb)(SSL *ssl, const char *hint,
3061                        char *identity, unsigned int max_identity_len, unsigned char *psk,
3062                        unsigned int max_psk_len))
3063         {
3064         s->psk_client_callback = cb;
3065         }
3066
3067 void SSL_CTX_set_psk_client_callback(SSL_CTX *ctx,
3068     unsigned int (*cb)(SSL *ssl, const char *hint,
3069                        char *identity, unsigned int max_identity_len, unsigned char *psk,
3070                        unsigned int max_psk_len))
3071         {
3072         ctx->psk_client_callback = cb;
3073         }
3074
3075 void SSL_set_psk_server_callback(SSL *s,
3076     unsigned int (*cb)(SSL *ssl, const char *identity,
3077                        unsigned char *psk, unsigned int max_psk_len))
3078         {
3079         s->psk_server_callback = cb;
3080         }
3081
3082 void SSL_CTX_set_psk_server_callback(SSL_CTX *ctx,
3083     unsigned int (*cb)(SSL *ssl, const char *identity,
3084                        unsigned char *psk, unsigned int max_psk_len))
3085         {
3086         ctx->psk_server_callback = cb;
3087         }
3088
3089 void SSL_CTX_set_msg_callback(SSL_CTX *ctx, void (*cb)(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg))
3090         {
3091         SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_MSG_CALLBACK, (void (*)(void))cb);
3092         }
3093 void SSL_set_msg_callback(SSL *ssl, void (*cb)(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg))
3094         {
3095         SSL_callback_ctrl(ssl, SSL_CTRL_SET_MSG_CALLBACK, (void (*)(void))cb);
3096         }
3097
3098 void SSL_CTX_set_keylog_bio(SSL_CTX *ctx, BIO *keylog_bio)
3099         {
3100         if (ctx->keylog_bio != NULL)
3101                 BIO_free(ctx->keylog_bio);
3102         ctx->keylog_bio = keylog_bio;
3103         }
3104
3105 static int cbb_add_hex(CBB *cbb, const uint8_t *in, size_t in_len)
3106         {
3107         static const char hextable[] = "0123456789abcdef";
3108         uint8_t *out;
3109         size_t i;
3110
3111         if (!CBB_add_space(cbb, &out, in_len * 2))
3112                 {
3113                 return 0;
3114                 }
3115
3116         for (i = 0; i < in_len; i++)
3117                 {
3118                 *(out++) = (uint8_t)hextable[in[i] >> 4];
3119                 *(out++) = (uint8_t)hextable[in[i] & 0xf];
3120                 }
3121         return 1;
3122         }
3123
3124 int ssl_ctx_log_rsa_client_key_exchange(SSL_CTX *ctx,
3125         const uint8_t *encrypted_premaster, size_t encrypted_premaster_len,
3126         const uint8_t *premaster, size_t premaster_len)
3127         {
3128         BIO *bio = ctx->keylog_bio;
3129         CBB cbb;
3130         uint8_t *out;
3131         size_t out_len;
3132         int ret;
3133
3134         if (bio == NULL)
3135                 {
3136                 return 1;
3137                 }
3138
3139         if (encrypted_premaster_len < 8)
3140                 {
3141                 OPENSSL_PUT_ERROR(SSL, ssl_ctx_log_rsa_client_key_exchange, ERR_R_INTERNAL_ERROR);
3142                 return 0;
3143                 }
3144
3145         if (!CBB_init(&cbb, 4 + 16 + 1 + premaster_len*2 + 1))
3146                 {
3147                 return 0;
3148                 }
3149         if (!CBB_add_bytes(&cbb, (const uint8_t*)"RSA ", 4) ||
3150                 /* Only the first 8 bytes of the encrypted premaster secret are
3151                  * logged. */
3152                 !cbb_add_hex(&cbb, encrypted_premaster, 8) ||
3153                 !CBB_add_bytes(&cbb, (const uint8_t*)" ", 1) ||
3154                 !cbb_add_hex(&cbb, premaster, premaster_len) ||
3155                 !CBB_add_bytes(&cbb, (const uint8_t*)"\n", 1) ||
3156                 !CBB_finish(&cbb, &out, &out_len))
3157                 {
3158                 CBB_cleanup(&cbb);
3159                 return 0;
3160                 }
3161
3162         CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
3163         ret = BIO_write(bio, out, out_len) >= 0 && BIO_flush(bio);
3164         CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
3165
3166         OPENSSL_free(out);
3167         return ret;
3168         }
3169
3170 int ssl_ctx_log_master_secret(SSL_CTX *ctx,
3171         const uint8_t *client_random, size_t client_random_len,
3172         const uint8_t *master, size_t master_len)
3173         {
3174         BIO *bio = ctx->keylog_bio;
3175         CBB cbb;
3176         uint8_t *out;
3177         size_t out_len;
3178         int ret;
3179
3180         if (bio == NULL)
3181                 {
3182                 return 1;
3183                 }
3184
3185         if (client_random_len != 32)
3186                 {
3187                 OPENSSL_PUT_ERROR(SSL, ssl_ctx_log_master_secret, ERR_R_INTERNAL_ERROR);
3188                 return 0;
3189                 }
3190
3191         if (!CBB_init(&cbb, 14 + 64 + 1 + master_len*2 + 1))
3192                 {
3193                 return 0;
3194                 }
3195         if (!CBB_add_bytes(&cbb, (const uint8_t*)"CLIENT_RANDOM ", 14) ||
3196                 !cbb_add_hex(&cbb, client_random, 32) ||
3197                 !CBB_add_bytes(&cbb, (const uint8_t*)" ", 1) ||
3198                 !cbb_add_hex(&cbb, master, master_len) ||
3199                 !CBB_add_bytes(&cbb, (const uint8_t*)"\n", 1) ||
3200                 !CBB_finish(&cbb, &out, &out_len))
3201                 {
3202                 CBB_cleanup(&cbb);
3203                 return 0;
3204                 }
3205
3206         CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
3207         ret = BIO_write(bio, out, out_len) >= 0 && BIO_flush(bio);
3208         CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
3209
3210         OPENSSL_free(out);
3211         return ret;
3212         }
3213
3214 int SSL_cutthrough_complete(const SSL *s)
3215         {
3216         return (!s->server &&                 /* cutthrough only applies to clients */
3217                 !s->hit &&                        /* full-handshake */
3218                 s->version >= SSL3_VERSION &&
3219                 s->s3->in_read_app_data == 0 &&   /* cutthrough only applies to write() */
3220                 (SSL_get_mode((SSL*)s) & SSL_MODE_HANDSHAKE_CUTTHROUGH) &&  /* cutthrough enabled */
3221                 ssl3_can_cutthrough(s) &&                                   /* cutthrough allowed */
3222                 s->s3->previous_server_finished_len == 0 &&                 /* not a renegotiation handshake */
3223                 (s->state == SSL3_ST_CR_SESSION_TICKET_A ||                 /* ready to write app-data*/
3224                         s->state == SSL3_ST_CR_CHANGE ||
3225                         s->state == SSL3_ST_CR_FINISHED_A));
3226         }
3227
3228 void SSL_get_structure_sizes(size_t* ssl_size, size_t* ssl_ctx_size,
3229                              size_t* ssl_session_size)
3230 {
3231         *ssl_size = sizeof(SSL);
3232         *ssl_ctx_size = sizeof(SSL_CTX);
3233         *ssl_session_size = sizeof(SSL_SESSION);
3234 }
3235
3236 int ssl3_can_cutthrough(const SSL *s)
3237         {
3238         const SSL_CIPHER *c;
3239
3240         /* require a strong enough cipher */
3241         if (SSL_get_cipher_bits(s, NULL) < 128)
3242                 return 0;
3243
3244         /* require ALPN or NPN extension */
3245         if (!s->s3->alpn_selected && !s->s3->next_proto_neg_seen)
3246                 {
3247                 return 0;
3248                 }
3249
3250         /* require a forward-secret cipher */
3251         c = SSL_get_current_cipher(s);
3252         if (!c || (c->algorithm_mkey != SSL_kEDH &&
3253                         c->algorithm_mkey != SSL_kEECDH))
3254                 {
3255                 return 0;
3256                 }
3257
3258         return 1;
3259         }
3260
3261 /* ssl_get_max_version returns the maximum SSL/TLS version number supported by
3262  * |s|, or zero if all versions are disabled. */
3263 int ssl_get_max_version(const SSL *s)
3264         {
3265         /* Only one version supported for DTLS. */
3266         if (s->version == DTLS1_VERSION)
3267                 return DTLS1_VERSION;
3268
3269         if (!(s->options & SSL_OP_NO_TLSv1_2))
3270                 return TLS1_2_VERSION;
3271         if (!(s->options & SSL_OP_NO_TLSv1_1))
3272                 return TLS1_1_VERSION;
3273         if (!(s->options & SSL_OP_NO_TLSv1))
3274                 return TLS1_VERSION;
3275         if (!(s->options & SSL_OP_NO_SSLv3))
3276                 return SSL3_VERSION;
3277         if (!(s->options & SSL_OP_NO_SSLv2))
3278                 return SSL2_VERSION;
3279         return 0;
3280         }
3281
3282 /* Allocates new EVP_MD_CTX and sets pointer to it into given pointer
3283  * vairable, freeing  EVP_MD_CTX previously stored in that variable, if
3284  * any. If EVP_MD pointer is passed, initializes ctx with this md
3285  * Returns newly allocated ctx;
3286  */
3287
3288 EVP_MD_CTX *ssl_replace_hash(EVP_MD_CTX **hash,const EVP_MD *md) 
3289 {
3290         ssl_clear_hash_ctx(hash);
3291         *hash = EVP_MD_CTX_create();
3292         if (md) EVP_DigestInit_ex(*hash,md,NULL);
3293         return *hash;
3294 }
3295 void ssl_clear_hash_ctx(EVP_MD_CTX **hash) 
3296 {
3297
3298         if (*hash) EVP_MD_CTX_destroy(*hash);
3299         *hash=NULL;
3300 }
3301
3302 void SSL_set_debug(SSL *s, int debug)
3303         {
3304         s->debug = debug;
3305         }
3306
3307 int SSL_cache_hit(SSL *s)
3308         {
3309         return s->hit;
3310         }
3311
3312 int SSL_is_server(SSL *s)
3313         {
3314         return s->server;
3315         }