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