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