Support verify_depth from the SSL API without need for user-defined
[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 #include <stdio.h>
62 #include <openssl/objects.h>
63 #include <openssl/lhash.h>
64 #include "ssl_locl.h"
65
66 char *SSL_version_str=OPENSSL_VERSION_TEXT;
67
68 static STACK *ssl_meth=NULL;
69 static STACK *ssl_ctx_meth=NULL;
70 static int ssl_meth_num=0;
71 static int ssl_ctx_meth_num=0;
72
73 SSL3_ENC_METHOD ssl3_undef_enc_method={
74         ssl_undefined_function,
75         ssl_undefined_function,
76         ssl_undefined_function,
77         ssl_undefined_function,
78         ssl_undefined_function,
79         ssl_undefined_function,
80         };
81
82 int SSL_clear(SSL *s)
83         {
84         int state;
85
86         if (s->method == NULL)
87                 {
88                 SSLerr(SSL_F_SSL_CLEAR,SSL_R_NO_METHOD_SPECIFIED);
89                 return(0);
90                 }
91
92         s->error=0;
93         s->hit=0;
94         s->shutdown=0;
95
96 #if 0
97         /* This is set if we are doing dynamic renegotiation so keep
98          * the old cipher.  It is sort of a SSL_clear_lite :-) */
99         if (s->new_session) return(1);
100 #endif
101
102         state=s->state; /* Keep to check if we throw away the session-id */
103         s->type=0;
104
105         s->state=SSL_ST_BEFORE|((s->server)?SSL_ST_ACCEPT:SSL_ST_CONNECT);
106
107         s->version=s->method->version;
108         s->client_version=s->version;
109         s->rwstate=SSL_NOTHING;
110         s->rstate=SSL_ST_READ_HEADER;
111         s->read_ahead=s->ctx->read_ahead;
112
113         if (s->init_buf != NULL)
114                 {
115                 BUF_MEM_free(s->init_buf);
116                 s->init_buf=NULL;
117                 }
118
119         ssl_clear_cipher_ctx(s);
120
121         if (ssl_clear_bad_session(s))
122                 {
123                 SSL_SESSION_free(s->session);
124                 s->session=NULL;
125                 }
126
127         s->first_packet=0;
128
129 #if 1
130         /* Check to see if we were changed into a different method, if
131          * so, revert back if we are not doing session-id reuse. */
132         if ((s->session == NULL) && (s->method != s->ctx->method))
133                 {
134                 s->method->ssl_free(s);
135                 s->method=s->ctx->method;
136                 if (!s->method->ssl_new(s))
137                         return(0);
138                 }
139         else
140 #endif
141                 s->method->ssl_clear(s);
142         return(1);
143         }
144
145 /** Used to change an SSL_CTXs default SSL method type */
146 int SSL_CTX_set_ssl_version(SSL_CTX *ctx,SSL_METHOD *meth)
147         {
148         STACK_OF(SSL_CIPHER) *sk;
149
150         ctx->method=meth;
151
152         sk=ssl_create_cipher_list(ctx->method,&(ctx->cipher_list),
153                 &(ctx->cipher_list_by_id),SSL_DEFAULT_CIPHER_LIST);
154         if ((sk == NULL) || (sk_SSL_CIPHER_num(sk) <= 0))
155                 {
156                 SSLerr(SSL_F_SSL_CTX_SET_SSL_VERSION,SSL_R_SSL_LIBRARY_HAS_NO_CIPHERS);
157                 return(0);
158                 }
159         return(1);
160         }
161
162 SSL *SSL_new(SSL_CTX *ctx)
163         {
164         SSL *s;
165
166         if (ctx == NULL)
167                 {
168                 SSLerr(SSL_F_SSL_NEW,SSL_R_NULL_SSL_CTX);
169                 return(NULL);
170                 }
171         if (ctx->method == NULL)
172                 {
173                 SSLerr(SSL_F_SSL_NEW,SSL_R_SSL_CTX_HAS_NO_DEFAULT_SSL_VERSION);
174                 return(NULL);
175                 }
176
177         s=(SSL *)Malloc(sizeof(SSL));
178         if (s == NULL) goto err;
179         memset(s,0,sizeof(SSL));
180
181         if (ctx->default_cert != NULL)
182                 {
183                 CRYPTO_add(&ctx->default_cert->references,1,
184                            CRYPTO_LOCK_SSL_CERT);
185                 s->cert=ctx->default_cert;
186                 }
187         else
188                 s->cert=NULL;
189         s->sid_ctx_length=ctx->sid_ctx_length;
190         memcpy(&s->sid_ctx,&ctx->sid_ctx,sizeof(s->sid_ctx));
191         s->verify_mode=ctx->verify_mode;
192         s->verify_depth=ctx->verify_depth;
193         s->verify_callback=ctx->default_verify_callback;
194         CRYPTO_add(&ctx->references,1,CRYPTO_LOCK_SSL_CTX);
195         s->ctx=ctx;
196
197         s->verify_result=X509_V_OK;
198
199         s->method=ctx->method;
200
201         if (!s->method->ssl_new(s))
202                 {
203                 SSL_CTX_free(ctx);
204                 Free(s);
205                 goto err;
206                 }
207
208         s->quiet_shutdown=ctx->quiet_shutdown;
209         s->references=1;
210         s->server=(ctx->method->ssl_accept == ssl_undefined_function)?0:1;
211         s->options=ctx->options;
212         SSL_clear(s);
213
214         CRYPTO_new_ex_data(ssl_meth,(char *)s,&s->ex_data);
215
216         return(s);
217 err:
218         SSLerr(SSL_F_SSL_NEW,ERR_R_MALLOC_FAILURE);
219         return(NULL);
220         }
221
222 int SSL_CTX_set_session_id_context(SSL_CTX *ctx,const unsigned char *sid_ctx,
223                                    unsigned int sid_ctx_len)
224     {
225     if(sid_ctx_len > SSL_MAX_SID_CTX_LENGTH)
226         {
227         SSLerr(SSL_F_SSL_CTX_SET_SESSION_ID_CONTEXT,SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
228         return 0;
229         }
230     ctx->sid_ctx_length=sid_ctx_len;
231     memcpy(ctx->sid_ctx,sid_ctx,sid_ctx_len);
232
233     return 1;
234     }
235
236 int SSL_set_session_id_context(SSL *ssl,const unsigned char *sid_ctx,
237                                unsigned int sid_ctx_len)
238     {
239     if(sid_ctx_len > SSL_MAX_SID_CTX_LENGTH)
240         {
241         SSLerr(SSL_F_SSL_SET_SESSION_ID_CONTEXT,SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
242         return 0;
243         }
244     ssl->sid_ctx_length=sid_ctx_len;
245     memcpy(ssl->sid_ctx,sid_ctx,sid_ctx_len);
246
247     return 1;
248     }
249
250 void SSL_free(SSL *s)
251         {
252         int i;
253
254         if(s == NULL)
255             return;
256
257         i=CRYPTO_add(&s->references,-1,CRYPTO_LOCK_SSL);
258 #ifdef REF_PRINT
259         REF_PRINT("SSL",s);
260 #endif
261         if (i > 0) return;
262 #ifdef REF_CHECK
263         if (i < 0)
264                 {
265                 fprintf(stderr,"SSL_free, bad reference count\n");
266                 abort(); /* ok */
267                 }
268 #endif
269
270         CRYPTO_free_ex_data(ssl_meth,(char *)s,&s->ex_data);
271
272         if (s->bbio != NULL)
273                 {
274                 /* If the buffering BIO is in place, pop it off */
275                 if (s->bbio == s->wbio)
276                         {
277                         s->wbio=BIO_pop(s->wbio);
278                         }
279                 BIO_free(s->bbio);
280                 s->bbio=NULL;
281                 }
282         if (s->rbio != NULL)
283                 BIO_free_all(s->rbio);
284         if ((s->wbio != NULL) && (s->wbio != s->rbio))
285                 BIO_free_all(s->wbio);
286
287         if (s->init_buf != NULL) BUF_MEM_free(s->init_buf);
288
289         /* add extra stuff */
290         if (s->cipher_list != NULL) sk_SSL_CIPHER_free(s->cipher_list);
291         if (s->cipher_list_by_id != NULL) sk_SSL_CIPHER_free(s->cipher_list_by_id);
292
293         /* Make the next call work :-) */
294         if (s->session != NULL)
295                 {
296                 ssl_clear_bad_session(s);
297                 SSL_SESSION_free(s->session);
298                 }
299
300         ssl_clear_cipher_ctx(s);
301
302         if (s->cert != NULL) ssl_cert_free(s->cert);
303         /* Free up if allocated */
304
305         if (s->ctx) SSL_CTX_free(s->ctx);
306
307         if (s->client_CA != NULL)
308                 sk_X509_NAME_pop_free(s->client_CA,X509_NAME_free);
309
310         if (s->method != NULL) s->method->ssl_free(s);
311
312         Free((char *)s);
313         }
314
315 void SSL_set_bio(SSL *s,BIO *rbio,BIO *wbio)
316         {
317         /* If the output buffering BIO is still in place, remove it
318          */
319         if (s->bbio != NULL)
320                 {
321                 if (s->wbio == s->bbio)
322                         {
323                         s->wbio=s->wbio->next_bio;
324                         s->bbio->next_bio=NULL;
325                         }
326                 }
327         if ((s->rbio != NULL) && (s->rbio != rbio))
328                 BIO_free_all(s->rbio);
329         if ((s->wbio != NULL) && (s->wbio != wbio) && (s->rbio != s->wbio))
330                 BIO_free_all(s->wbio);
331         s->rbio=rbio;
332         s->wbio=wbio;
333         }
334
335 BIO *SSL_get_rbio(SSL *s)
336         { return(s->rbio); }
337
338 BIO *SSL_get_wbio(SSL *s)
339         { return(s->wbio); }
340
341 int SSL_get_fd(SSL *s)
342         {
343         int ret= -1;
344         BIO *b,*r;
345
346         b=SSL_get_rbio(s);
347         r=BIO_find_type(b,BIO_TYPE_DESCRIPTOR);
348         if (r != NULL)
349                 BIO_get_fd(r,&ret);
350         return(ret);
351         }
352
353 #ifndef NO_SOCK
354 int SSL_set_fd(SSL *s,int fd)
355         {
356         int ret=0;
357         BIO *bio=NULL;
358
359         bio=BIO_new(BIO_s_socket());
360
361         if (bio == NULL)
362                 {
363                 SSLerr(SSL_F_SSL_SET_FD,ERR_R_BUF_LIB);
364                 goto err;
365                 }
366         BIO_set_fd(bio,fd,BIO_NOCLOSE);
367         SSL_set_bio(s,bio,bio);
368         ret=1;
369 err:
370         return(ret);
371         }
372
373 int SSL_set_wfd(SSL *s,int fd)
374         {
375         int ret=0;
376         BIO *bio=NULL;
377
378         if ((s->rbio == NULL) || (BIO_method_type(s->rbio) != BIO_TYPE_SOCKET)
379                 || ((int)BIO_get_fd(s->rbio,NULL) != fd))
380                 {
381                 bio=BIO_new(BIO_s_socket());
382
383                 if (bio == NULL)
384                         { SSLerr(SSL_F_SSL_SET_WFD,ERR_R_BUF_LIB); goto err; }
385                 BIO_set_fd(bio,fd,BIO_NOCLOSE);
386                 SSL_set_bio(s,SSL_get_rbio(s),bio);
387                 }
388         else
389                 SSL_set_bio(s,SSL_get_rbio(s),SSL_get_rbio(s));
390         ret=1;
391 err:
392         return(ret);
393         }
394
395 int SSL_set_rfd(SSL *s,int fd)
396         {
397         int ret=0;
398         BIO *bio=NULL;
399
400         if ((s->wbio == NULL) || (BIO_method_type(s->wbio) != BIO_TYPE_SOCKET)
401                 || ((int)BIO_get_fd(s->wbio,NULL) != fd))
402                 {
403                 bio=BIO_new(BIO_s_socket());
404
405                 if (bio == NULL)
406                         {
407                         SSLerr(SSL_F_SSL_SET_RFD,ERR_R_BUF_LIB);
408                         goto err;
409                         }
410                 BIO_set_fd(bio,fd,BIO_NOCLOSE);
411                 SSL_set_bio(s,bio,SSL_get_wbio(s));
412                 }
413         else
414                 SSL_set_bio(s,SSL_get_wbio(s),SSL_get_wbio(s));
415         ret=1;
416 err:
417         return(ret);
418         }
419 #endif
420
421 int SSL_get_verify_mode(SSL *s)
422         {
423         return(s->verify_mode);
424         }
425
426 int SSL_get_verify_depth(SSL *s)
427         {
428         return(s->verify_depth);
429         }
430
431 int (*SSL_get_verify_callback(SSL *s))(int,X509_STORE_CTX *)
432         {
433         return(s->verify_callback);
434         }
435
436 int SSL_CTX_get_verify_mode(SSL_CTX *ctx)
437         {
438         return(ctx->verify_mode);
439         }
440
441 int SSL_CTX_get_verify_depth(SSL_CTX *ctx)
442         {
443         return(ctx->verify_depth);
444         }
445
446 int (*SSL_CTX_get_verify_callback(SSL_CTX *ctx))(int,X509_STORE_CTX *)
447         {
448         return(ctx->default_verify_callback);
449         }
450
451 void SSL_set_verify(SSL *s,int mode,
452                     int (*callback)(int ok,X509_STORE_CTX *ctx))
453         {
454         s->verify_mode=mode;
455         if (callback != NULL)
456                 s->verify_callback=callback;
457         }
458
459 void SSL_set_verify_depth(SSL *s,int depth)
460         {
461         s->verify_depth=depth;
462         }
463
464 void SSL_set_read_ahead(SSL *s,int yes)
465         {
466         s->read_ahead=yes;
467         }
468
469 int SSL_get_read_ahead(SSL *s)
470         {
471         return(s->read_ahead);
472         }
473
474 int SSL_pending(SSL *s)
475         {
476         return(s->method->ssl_pending(s));
477         }
478
479 X509 *SSL_get_peer_certificate(SSL *s)
480         {
481         X509 *r;
482         
483         if ((s == NULL) || (s->session == NULL))
484                 r=NULL;
485         else
486                 r=s->session->peer;
487
488         if (r == NULL) return(r);
489
490         CRYPTO_add(&r->references,1,CRYPTO_LOCK_X509);
491
492         return(r);
493         }
494
495 STACK_OF(X509) *SSL_get_peer_cert_chain(SSL *s)
496         {
497         STACK_OF(X509) *r;
498         
499         if ((s == NULL) || (s->session == NULL) || (s->session->cert == NULL))
500                 r=NULL;
501         else
502                 r=s->session->cert->cert_chain;
503
504         return(r);
505         }
506
507 /* Now in theory, since the calling process own 't' it should be safe to
508  * modify.  We need to be able to read f without being hassled */
509 void SSL_copy_session_id(SSL *t,SSL *f)
510         {
511         CERT *tmp;
512
513         /* Do we need to to SSL locking? */
514         SSL_set_session(t,SSL_get_session(f));
515
516         /* what if we are setup as SSLv2 but want to talk SSLv3 or
517          * vice-versa */
518         if (t->method != f->method)
519                 {
520                 t->method->ssl_free(t); /* cleanup current */
521                 t->method=f->method;    /* change method */
522                 t->method->ssl_new(t);  /* setup new */
523                 }
524
525         tmp=t->cert;
526         if (f->cert != NULL)
527                 {
528                 CRYPTO_add(&f->cert->references,1,CRYPTO_LOCK_SSL_CERT);
529                 t->cert=f->cert;
530                 }
531         else
532                 t->cert=NULL;
533         if (tmp != NULL) ssl_cert_free(tmp);
534         SSL_set_session_id_context(t,f->sid_ctx,f->sid_ctx_length);
535         }
536
537 /* Fix this so it checks all the valid key/cert options */
538 int SSL_CTX_check_private_key(SSL_CTX *ctx)
539         {
540         if (    (ctx == NULL) ||
541                 (ctx->default_cert == NULL) ||
542                 (ctx->default_cert->key->x509 == NULL))
543                 {
544                 SSLerr(SSL_F_SSL_CTX_CHECK_PRIVATE_KEY,SSL_R_NO_CERTIFICATE_ASSIGNED);
545                 return(0);
546                 }
547         if      (ctx->default_cert->key->privatekey == NULL)
548                 {
549                 SSLerr(SSL_F_SSL_CTX_CHECK_PRIVATE_KEY,SSL_R_NO_PRIVATE_KEY_ASSIGNED);
550                 return(0);
551                 }
552         return(X509_check_private_key(ctx->default_cert->key->x509, ctx->default_cert->key->privatekey));
553         }
554
555 /* Fix this function so that it takes an optional type parameter */
556 int SSL_check_private_key(SSL *ssl)
557         {
558         if (ssl == NULL)
559                 {
560                 SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY,ERR_R_PASSED_NULL_PARAMETER);
561                 return(0);
562                 }
563         if (ssl->cert == NULL)
564                 return(SSL_CTX_check_private_key(ssl->ctx));
565         if (ssl->cert->key->x509 == NULL)
566                 {
567                 SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY,SSL_R_NO_CERTIFICATE_ASSIGNED);
568                 return(0);
569                 }
570         if (ssl->cert->key->privatekey == NULL)
571                 {
572                 SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY,SSL_R_NO_PRIVATE_KEY_ASSIGNED);
573                 return(0);
574                 }
575         return(X509_check_private_key(ssl->cert->key->x509,
576                 ssl->cert->key->privatekey));
577         }
578
579 int SSL_accept(SSL *s)
580         {
581         return(s->method->ssl_accept(s));
582         }
583
584 int SSL_connect(SSL *s)
585         {
586         return(s->method->ssl_connect(s));
587         }
588
589 long SSL_get_default_timeout(SSL *s)
590         {
591         return(s->method->get_timeout());
592         }
593
594 int SSL_read(SSL *s,char *buf,int num)
595         {
596         if (s->shutdown & SSL_RECEIVED_SHUTDOWN)
597                 {
598                 s->rwstate=SSL_NOTHING;
599                 return(0);
600                 }
601         return(s->method->ssl_read(s,buf,num));
602         }
603
604 int SSL_peek(SSL *s,char *buf,int num)
605         {
606         if (s->shutdown & SSL_RECEIVED_SHUTDOWN)
607                 {
608                 return(0);
609                 }
610         return(s->method->ssl_peek(s,buf,num));
611         }
612
613 int SSL_write(SSL *s,const char *buf,int num)
614         {
615         if (s->shutdown & SSL_SENT_SHUTDOWN)
616                 {
617                 s->rwstate=SSL_NOTHING;
618                 SSLerr(SSL_F_SSL_WRITE,SSL_R_PROTOCOL_IS_SHUTDOWN);
619                 return(-1);
620                 }
621         return(s->method->ssl_write(s,buf,num));
622         }
623
624 int SSL_shutdown(SSL *s)
625         {
626         if ((s != NULL) && !SSL_in_init(s))
627                 return(s->method->ssl_shutdown(s));
628         else
629                 return(1);
630         }
631
632 int SSL_renegotiate(SSL *s)
633         {
634         s->new_session=1;
635         return(s->method->ssl_renegotiate(s));
636         }
637
638 long SSL_ctrl(SSL *s,int cmd,long larg,char *parg)
639         {
640         long l;
641
642         switch (cmd)
643                 {
644         case SSL_CTRL_GET_READ_AHEAD:
645                 return(s->read_ahead);
646         case SSL_CTRL_SET_READ_AHEAD:
647                 l=s->read_ahead;
648                 s->read_ahead=larg;
649                 return(l);
650         case SSL_CTRL_OPTIONS:
651                 return(s->options|=larg);
652         default:
653                 return(s->method->ssl_ctrl(s,cmd,larg,parg));
654                 }
655         return(0);
656         }
657
658 long SSL_CTX_ctrl(SSL_CTX *ctx,int cmd,long larg,char *parg)
659         {
660         long l;
661
662         switch (cmd)
663                 {
664         case SSL_CTRL_GET_READ_AHEAD:
665                 return(ctx->read_ahead);
666         case SSL_CTRL_SET_READ_AHEAD:
667                 l=ctx->read_ahead;
668                 ctx->read_ahead=larg;
669                 return(l);
670
671         case SSL_CTRL_SET_SESS_CACHE_SIZE:
672                 l=ctx->session_cache_size;
673                 ctx->session_cache_size=larg;
674                 return(l);
675         case SSL_CTRL_GET_SESS_CACHE_SIZE:
676                 return(ctx->session_cache_size);
677         case SSL_CTRL_SET_SESS_CACHE_MODE:
678                 l=ctx->session_cache_mode;
679                 ctx->session_cache_mode=larg;
680                 return(l);
681         case SSL_CTRL_GET_SESS_CACHE_MODE:
682                 return(ctx->session_cache_mode);
683
684         case SSL_CTRL_SESS_NUMBER:
685                 return(ctx->sessions->num_items);
686         case SSL_CTRL_SESS_CONNECT:
687                 return(ctx->stats.sess_connect);
688         case SSL_CTRL_SESS_CONNECT_GOOD:
689                 return(ctx->stats.sess_connect_good);
690         case SSL_CTRL_SESS_CONNECT_RENEGOTIATE:
691                 return(ctx->stats.sess_connect_renegotiate);
692         case SSL_CTRL_SESS_ACCEPT:
693                 return(ctx->stats.sess_accept);
694         case SSL_CTRL_SESS_ACCEPT_GOOD:
695                 return(ctx->stats.sess_accept_good);
696         case SSL_CTRL_SESS_ACCEPT_RENEGOTIATE:
697                 return(ctx->stats.sess_accept_renegotiate);
698         case SSL_CTRL_SESS_HIT:
699                 return(ctx->stats.sess_hit);
700         case SSL_CTRL_SESS_CB_HIT:
701                 return(ctx->stats.sess_cb_hit);
702         case SSL_CTRL_SESS_MISSES:
703                 return(ctx->stats.sess_miss);
704         case SSL_CTRL_SESS_TIMEOUTS:
705                 return(ctx->stats.sess_timeout);
706         case SSL_CTRL_SESS_CACHE_FULL:
707                 return(ctx->stats.sess_cache_full);
708         case SSL_CTRL_OPTIONS:
709                 return(ctx->options|=larg);
710         default:
711                 return(ctx->method->ssl_ctx_ctrl(ctx,cmd,larg,parg));
712                 }
713         return(0);
714         }
715
716 int ssl_cipher_id_cmp(SSL_CIPHER *a,SSL_CIPHER *b)
717         {
718         long l;
719
720         l=a->id-b->id;
721         if (l == 0L)
722                 return(0);
723         else
724                 return((l > 0)?1:-1);
725         }
726
727 int ssl_cipher_ptr_id_cmp(SSL_CIPHER **ap,SSL_CIPHER **bp)
728         {
729         long l;
730
731         l=(*ap)->id-(*bp)->id;
732         if (l == 0L)
733                 return(0);
734         else
735                 return((l > 0)?1:-1);
736         }
737
738 /** return a STACK of the ciphers available for the SSL and in order of
739  * preference */
740 STACK_OF(SSL_CIPHER) *SSL_get_ciphers(SSL *s)
741         {
742         if ((s != NULL) && (s->cipher_list != NULL))
743                 {
744                 return(s->cipher_list);
745                 }
746         else if ((s->ctx != NULL) &&
747                 (s->ctx->cipher_list != NULL))
748                 {
749                 return(s->ctx->cipher_list);
750                 }
751         return(NULL);
752         }
753
754 /** return a STACK of the ciphers available for the SSL and in order of
755  * algorithm id */
756 STACK_OF(SSL_CIPHER) *ssl_get_ciphers_by_id(SSL *s)
757         {
758         if ((s != NULL) && (s->cipher_list_by_id != NULL))
759                 {
760                 return(s->cipher_list_by_id);
761                 }
762         else if ((s != NULL) && (s->ctx != NULL) &&
763                 (s->ctx->cipher_list_by_id != NULL))
764                 {
765                 return(s->ctx->cipher_list_by_id);
766                 }
767         return(NULL);
768         }
769
770 /** The old interface to get the same thing as SSL_get_ciphers() */
771 const char *SSL_get_cipher_list(SSL *s,int n)
772         {
773         SSL_CIPHER *c;
774         STACK_OF(SSL_CIPHER) *sk;
775
776         if (s == NULL) return(NULL);
777         sk=SSL_get_ciphers(s);
778         if ((sk == NULL) || (sk_SSL_CIPHER_num(sk) <= n))
779                 return(NULL);
780         c=sk_SSL_CIPHER_value(sk,n);
781         if (c == NULL) return(NULL);
782         return(c->name);
783         }
784
785 /** specify the ciphers to be used by defaut by the SSL_CTX */
786 int SSL_CTX_set_cipher_list(SSL_CTX *ctx,char *str)
787         {
788         STACK_OF(SSL_CIPHER) *sk;
789         
790         sk=ssl_create_cipher_list(ctx->method,&ctx->cipher_list,
791                 &ctx->cipher_list_by_id,str);
792 /* XXXX */
793         return((sk == NULL)?0:1);
794         }
795
796 /** specify the ciphers to be used by the SSL */
797 int SSL_set_cipher_list(SSL *s,char *str)
798         {
799         STACK_OF(SSL_CIPHER) *sk;
800         
801         sk=ssl_create_cipher_list(s->ctx->method,&s->cipher_list,
802                 &s->cipher_list_by_id,str);
803 /* XXXX */
804         return((sk == NULL)?0:1);
805         }
806
807 /* works well for SSLv2, not so good for SSLv3 */
808 char *SSL_get_shared_ciphers(SSL *s,char *buf,int len)
809         {
810         char *p;
811         const char *cp;
812         STACK_OF(SSL_CIPHER) *sk;
813         SSL_CIPHER *c;
814         int i;
815
816         if ((s->session == NULL) || (s->session->ciphers == NULL) ||
817                 (len < 2))
818                 return(NULL);
819
820         p=buf;
821         sk=s->session->ciphers;
822         for (i=0; i<sk_SSL_CIPHER_num(sk); i++)
823                 {
824                 /* Decrement for either the ':' or a '\0' */
825                 len--;
826                 c=sk_SSL_CIPHER_value(sk,i);
827                 for (cp=c->name; *cp; )
828                         {
829                         if (len-- == 0)
830                                 {
831                                 *p='\0';
832                                 return(buf);
833                                 }
834                         else
835                                 *(p++)= *(cp++);
836                         }
837                 *(p++)=':';
838                 }
839         p[-1]='\0';
840         return(buf);
841         }
842
843 int ssl_cipher_list_to_bytes(SSL *s,STACK_OF(SSL_CIPHER) *sk,unsigned char *p)
844         {
845         int i,j=0;
846         SSL_CIPHER *c;
847         unsigned char *q;
848
849         if (sk == NULL) return(0);
850         q=p;
851
852         for (i=0; i<sk_SSL_CIPHER_num(sk); i++)
853                 {
854                 c=sk_SSL_CIPHER_value(sk,i);
855                 j=ssl_put_cipher_by_char(s,c,p);
856                 p+=j;
857                 }
858         return(p-q);
859         }
860
861 STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list(SSL *s,unsigned char *p,int num,
862                                                STACK_OF(SSL_CIPHER) **skp)
863         {
864         SSL_CIPHER *c;
865         STACK_OF(SSL_CIPHER) *sk;
866         int i,n;
867
868         n=ssl_put_cipher_by_char(s,NULL,NULL);
869         if ((num%n) != 0)
870                 {
871                 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
872                 return(NULL);
873                 }
874         if ((skp == NULL) || (*skp == NULL))
875                 sk=sk_SSL_CIPHER_new(NULL); /* change perhaps later */
876         else
877                 {
878                 sk= *skp;
879                 sk_SSL_CIPHER_zero(sk);
880                 }
881
882         for (i=0; i<num; i+=n)
883                 {
884                 c=ssl_get_cipher_by_char(s,p);
885                 p+=n;
886                 if (c != NULL)
887                         {
888                         if (!sk_SSL_CIPHER_push(sk,c))
889                                 {
890                                 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,ERR_R_MALLOC_FAILURE);
891                                 goto err;
892                                 }
893                         }
894                 }
895
896         if (skp != NULL)
897                 *skp=sk;
898         return(sk);
899 err:
900         if ((skp == NULL) || (*skp == NULL))
901                 sk_SSL_CIPHER_free(sk);
902         return(NULL);
903         }
904
905 unsigned long SSL_SESSION_hash(SSL_SESSION *a)
906         {
907         unsigned long l;
908
909         l=(unsigned long)
910                 ((unsigned int) a->session_id[0]     )|
911                 ((unsigned int) a->session_id[1]<< 8L)|
912                 ((unsigned long)a->session_id[2]<<16L)|
913                 ((unsigned long)a->session_id[3]<<24L);
914         return(l);
915         }
916
917 int SSL_SESSION_cmp(SSL_SESSION *a,SSL_SESSION *b)
918         {
919         if (a->ssl_version != b->ssl_version)
920                 return(1);
921         if (a->session_id_length != b->session_id_length)
922                 return(1);
923         return(memcmp(a->session_id,b->session_id,a->session_id_length));
924         }
925
926 SSL_CTX *SSL_CTX_new(SSL_METHOD *meth)
927         {
928         SSL_CTX *ret=NULL;
929         
930         if (meth == NULL)
931                 {
932                 SSLerr(SSL_F_SSL_CTX_NEW,SSL_R_NULL_SSL_METHOD_PASSED);
933                 return(NULL);
934                 }
935
936         if (SSL_get_ex_data_X509_STORE_CTX_idx() < 0)
937                 {
938                 SSLerr(SSL_F_SSL_CTX_NEW,SSL_R_X509_VERIFICATION_SETUP_PROBLEMS);
939                 goto err;
940                 }
941         ret=(SSL_CTX *)Malloc(sizeof(SSL_CTX));
942         if (ret == NULL)
943                 goto err;
944
945         memset(ret,0,sizeof(SSL_CTX));
946
947         ret->method=meth;
948
949         ret->cert_store=NULL;
950         ret->session_cache_mode=SSL_SESS_CACHE_SERVER;
951         ret->session_cache_size=SSL_SESSION_CACHE_MAX_SIZE_DEFAULT;
952         ret->session_cache_head=NULL;
953         ret->session_cache_tail=NULL;
954
955         /* We take the system default */
956         ret->session_timeout=meth->get_timeout();
957
958         ret->new_session_cb=NULL;
959         ret->remove_session_cb=NULL;
960         ret->get_session_cb=NULL;
961
962         memset((char *)&ret->stats,0,sizeof(ret->stats));
963
964         ret->references=1;
965         ret->quiet_shutdown=0;
966
967 /*      ret->cipher=NULL;*/
968 /*      ret->s2->challenge=NULL;
969         ret->master_key=NULL;
970         ret->key_arg=NULL;
971         ret->s2->conn_id=NULL; */
972
973         ret->info_callback=NULL;
974
975         ret->app_verify_callback=NULL;
976         ret->app_verify_arg=NULL;
977
978         ret->read_ahead=0;
979         ret->verify_mode=SSL_VERIFY_NONE;
980         ret->verify_depth=-1; /* Don't impose a limit (but x509_lu.c does) */
981         ret->default_verify_callback=NULL;
982         if ((ret->default_cert=ssl_cert_new()) == NULL)
983                 goto err;
984
985         ret->default_passwd_callback=NULL;
986         ret->client_cert_cb=NULL;
987
988         ret->sessions=lh_new(SSL_SESSION_hash,SSL_SESSION_cmp);
989         if (ret->sessions == NULL) goto err;
990         ret->cert_store=X509_STORE_new();
991         if (ret->cert_store == NULL) goto err;
992
993         ssl_create_cipher_list(ret->method,
994                 &ret->cipher_list,&ret->cipher_list_by_id,
995                 SSL_DEFAULT_CIPHER_LIST);
996         if (ret->cipher_list == NULL
997             || sk_SSL_CIPHER_num(ret->cipher_list) <= 0)
998                 {
999                 SSLerr(SSL_F_SSL_CTX_NEW,SSL_R_LIBRARY_HAS_NO_CIPHERS);
1000                 goto err2;
1001                 }
1002
1003         if ((ret->rsa_md5=EVP_get_digestbyname("ssl2-md5")) == NULL)
1004                 {
1005                 SSLerr(SSL_F_SSL_CTX_NEW,SSL_R_UNABLE_TO_LOAD_SSL2_MD5_ROUTINES);
1006                 goto err2;
1007                 }
1008         if ((ret->md5=EVP_get_digestbyname("ssl3-md5")) == NULL)
1009                 {
1010                 SSLerr(SSL_F_SSL_CTX_NEW,SSL_R_UNABLE_TO_LOAD_SSL3_MD5_ROUTINES);
1011                 goto err2;
1012                 }
1013         if ((ret->sha1=EVP_get_digestbyname("ssl3-sha1")) == NULL)
1014                 {
1015                 SSLerr(SSL_F_SSL_CTX_NEW,SSL_R_UNABLE_TO_LOAD_SSL3_SHA1_ROUTINES);
1016                 goto err2;
1017                 }
1018
1019         if ((ret->client_CA=sk_X509_NAME_new_null()) == NULL)
1020                 goto err;
1021
1022         CRYPTO_new_ex_data(ssl_ctx_meth,(char *)ret,&ret->ex_data);
1023
1024         ret->extra_certs=NULL;
1025         ret->comp_methods=SSL_COMP_get_compression_methods();
1026
1027         return(ret);
1028 err:
1029         SSLerr(SSL_F_SSL_CTX_NEW,ERR_R_MALLOC_FAILURE);
1030 err2:
1031         if (ret != NULL) SSL_CTX_free(ret);
1032         return(NULL);
1033         }
1034
1035 static void SSL_COMP_free(SSL_COMP *comp)
1036     { Free(comp); }
1037
1038 void SSL_CTX_free(SSL_CTX *a)
1039         {
1040         int i;
1041
1042         if (a == NULL) return;
1043
1044         i=CRYPTO_add(&a->references,-1,CRYPTO_LOCK_SSL_CTX);
1045 #ifdef REF_PRINT
1046         REF_PRINT("SSL_CTX",a);
1047 #endif
1048         if (i > 0) return;
1049 #ifdef REF_CHECK
1050         if (i < 0)
1051                 {
1052                 fprintf(stderr,"SSL_CTX_free, bad reference count\n");
1053                 abort(); /* ok */
1054                 }
1055 #endif
1056         CRYPTO_free_ex_data(ssl_ctx_meth,(char *)a,&a->ex_data);
1057
1058         if (a->sessions != NULL)
1059                 {
1060                 SSL_CTX_flush_sessions(a,0);
1061                 lh_free(a->sessions);
1062                 }
1063         if (a->cert_store != NULL)
1064                 X509_STORE_free(a->cert_store);
1065         if (a->cipher_list != NULL)
1066                 sk_SSL_CIPHER_free(a->cipher_list);
1067         if (a->cipher_list_by_id != NULL)
1068                 sk_SSL_CIPHER_free(a->cipher_list_by_id);
1069         if (a->default_cert != NULL)
1070                 ssl_cert_free(a->default_cert);
1071         if (a->client_CA != NULL)
1072                 sk_X509_NAME_pop_free(a->client_CA,X509_NAME_free);
1073         if (a->extra_certs != NULL)
1074                 sk_X509_pop_free(a->extra_certs,X509_free);
1075         if (a->comp_methods != NULL)
1076                 sk_SSL_COMP_pop_free(a->comp_methods,SSL_COMP_free);
1077         Free((char *)a);
1078         }
1079
1080 void SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx,int (*cb)())
1081         {
1082         ctx->default_passwd_callback=cb;
1083         }
1084
1085 void SSL_CTX_set_cert_verify_cb(SSL_CTX *ctx,int (*cb)(),char *arg)
1086         {
1087         ctx->app_verify_callback=cb;
1088         ctx->app_verify_arg=arg;
1089         }
1090
1091 void SSL_CTX_set_verify(SSL_CTX *ctx,int mode,int (*cb)(int, X509_STORE_CTX *))
1092         {
1093         ctx->verify_mode=mode;
1094         ctx->default_verify_callback=cb;
1095         /* This needs cleaning up EAY EAY EAY */
1096         X509_STORE_set_verify_cb_func(ctx->cert_store,cb);
1097         }
1098
1099 void SSL_CTX_set_verify_depth(SSL_CTX *ctx,int depth)
1100         {
1101         ctx->verify_depth=depth;
1102         }
1103
1104 /* Need default_cert to check for callbacks, for now (see comment in CERT
1105    strucure)
1106 */
1107 void ssl_set_cert_masks(CERT *c,CERT *default_cert,SSL_CIPHER *cipher)
1108         {
1109         CERT_PKEY *cpk;
1110         int rsa_enc,rsa_tmp,rsa_sign,dh_tmp,dh_rsa,dh_dsa,dsa_sign;
1111         int rsa_enc_export,dh_rsa_export,dh_dsa_export;
1112         int rsa_tmp_export,dh_tmp_export,kl;
1113         unsigned long mask,emask;
1114
1115         if (c == NULL) return;
1116
1117         kl=SSL_C_EXPORT_PKEYLENGTH(cipher);
1118
1119 #ifndef NO_RSA
1120         rsa_tmp=(c->rsa_tmp != NULL || default_cert->rsa_tmp_cb != NULL);
1121         rsa_tmp_export=(default_cert->rsa_tmp_cb != NULL ||
1122                 (rsa_tmp && RSA_size(c->rsa_tmp)*8 <= kl));
1123 #else
1124         rsa_tmp=rsa_tmp_export=0;
1125 #endif
1126 #ifndef NO_DH
1127         dh_tmp=(c->dh_tmp != NULL || default_cert->dh_tmp_cb != NULL);
1128         dh_tmp_export=(default_cert->dh_tmp_cb != NULL ||
1129                 (dh_tmp && DH_size(c->dh_tmp)*8 <= kl));
1130 #else
1131         dh_tmp=dh_tmp_export=0;
1132 #endif
1133
1134         cpk= &(c->pkeys[SSL_PKEY_RSA_ENC]);
1135         rsa_enc= (cpk->x509 != NULL && cpk->privatekey != NULL);
1136         rsa_enc_export=(rsa_enc && EVP_PKEY_size(cpk->privatekey)*8 <= kl);
1137         cpk= &(c->pkeys[SSL_PKEY_RSA_SIGN]);
1138         rsa_sign=(cpk->x509 != NULL && cpk->privatekey != NULL);
1139         cpk= &(c->pkeys[SSL_PKEY_DSA_SIGN]);
1140         dsa_sign=(cpk->x509 != NULL && cpk->privatekey != NULL);
1141         cpk= &(c->pkeys[SSL_PKEY_DH_RSA]);
1142         dh_rsa=  (cpk->x509 != NULL && cpk->privatekey != NULL);
1143         dh_rsa_export=(dh_rsa && EVP_PKEY_size(cpk->privatekey)*8 <= kl);
1144         cpk= &(c->pkeys[SSL_PKEY_DH_DSA]);
1145 /* FIX THIS EAY EAY EAY */
1146         dh_dsa=  (cpk->x509 != NULL && cpk->privatekey != NULL);
1147         dh_dsa_export=(dh_dsa && EVP_PKEY_size(cpk->privatekey)*8 <= kl);
1148
1149         mask=0;
1150         emask=0;
1151
1152 #ifdef CIPHER_DEBUG
1153         printf("rt=%d rte=%d dht=%d re=%d ree=%d rs=%d ds=%d dhr=%d dhd=%d\n",
1154                 rsa_tmp,rsa_tmp_export,dh_tmp,
1155                 rsa_enc,rsa_enc_export,rsa_sign,dsa_sign,dh_rsa,dh_dsa);
1156 #endif
1157
1158         if (rsa_enc || (rsa_tmp && rsa_sign))
1159                 mask|=SSL_kRSA;
1160         if (rsa_enc_export || (rsa_tmp_export && (rsa_sign || rsa_enc)))
1161                 emask|=SSL_kRSA;
1162
1163 #if 0
1164         /* The match needs to be both kEDH and aRSA or aDSA, so don't worry */
1165         if (    (dh_tmp || dh_rsa || dh_dsa) && 
1166                 (rsa_enc || rsa_sign || dsa_sign))
1167                 mask|=SSL_kEDH;
1168         if ((dh_tmp_export || dh_rsa_export || dh_dsa_export) &&
1169                 (rsa_enc || rsa_sign || dsa_sign))
1170                 emask|=SSL_kEDH;
1171 #endif
1172
1173         if (dh_tmp_export) 
1174                 emask|=SSL_kEDH;
1175
1176         if (dh_tmp)
1177                 mask|=SSL_kEDH;
1178
1179         if (dh_rsa) mask|=SSL_kDHr;
1180         if (dh_rsa_export) emask|=SSL_kDHr;
1181
1182         if (dh_dsa) mask|=SSL_kDHd;
1183         if (dh_dsa_export) emask|=SSL_kDHd;
1184
1185         if (rsa_enc || rsa_sign)
1186                 {
1187                 mask|=SSL_aRSA;
1188                 emask|=SSL_aRSA;
1189                 }
1190
1191         if (dsa_sign)
1192                 {
1193                 mask|=SSL_aDSS;
1194                 emask|=SSL_aDSS;
1195                 }
1196
1197 #ifdef SSL_ALLOW_ADH
1198         mask|=SSL_aNULL;
1199         emask|=SSL_aNULL;
1200 #endif
1201
1202         c->mask=mask;
1203         c->export_mask=emask;
1204         c->valid=1;
1205         }
1206
1207 /* THIS NEEDS CLEANING UP */
1208 X509 *ssl_get_server_send_cert(SSL *s)
1209         {
1210         unsigned long alg,mask,kalg;
1211         CERT *c;
1212         int i,export;
1213
1214         c=s->cert;
1215         ssl_set_cert_masks(c,s->ctx->default_cert,s->s3->tmp.new_cipher);
1216         alg=s->s3->tmp.new_cipher->algorithms;
1217         export=SSL_IS_EXPORT(alg);
1218         mask=export?c->export_mask:c->mask;
1219         kalg=alg&(SSL_MKEY_MASK|SSL_AUTH_MASK);
1220
1221         if      (kalg & SSL_kDHr)
1222                 i=SSL_PKEY_DH_RSA;
1223         else if (kalg & SSL_kDHd)
1224                 i=SSL_PKEY_DH_DSA;
1225         else if (kalg & SSL_aDSS)
1226                 i=SSL_PKEY_DSA_SIGN;
1227         else if (kalg & SSL_aRSA)
1228                 {
1229                 if (c->pkeys[SSL_PKEY_RSA_ENC].x509 == NULL)
1230                         i=SSL_PKEY_RSA_SIGN;
1231                 else
1232                         i=SSL_PKEY_RSA_ENC;
1233                 }
1234         else /* if (kalg & SSL_aNULL) */
1235                 {
1236                 SSLerr(SSL_F_SSL_GET_SERVER_SEND_CERT,SSL_R_INTERNAL_ERROR);
1237                 return(NULL);
1238                 }
1239         if (c->pkeys[i].x509 == NULL) return(NULL);
1240         return(c->pkeys[i].x509);
1241         }
1242
1243 EVP_PKEY *ssl_get_sign_pkey(SSL *s,SSL_CIPHER *cipher)
1244         {
1245         unsigned long alg;
1246         CERT *c;
1247
1248         alg=cipher->algorithms;
1249         c=s->cert;
1250
1251         if ((alg & SSL_aDSS) &&
1252                 (c->pkeys[SSL_PKEY_DSA_SIGN].privatekey != NULL))
1253                 return(c->pkeys[SSL_PKEY_DSA_SIGN].privatekey);
1254         else if (alg & SSL_aRSA)
1255                 {
1256                 if (c->pkeys[SSL_PKEY_RSA_SIGN].privatekey != NULL)
1257                         return(c->pkeys[SSL_PKEY_RSA_SIGN].privatekey);
1258                 else if (c->pkeys[SSL_PKEY_RSA_ENC].privatekey != NULL)
1259                         return(c->pkeys[SSL_PKEY_RSA_ENC].privatekey);
1260                 else
1261                         return(NULL);
1262                 }
1263         else /* if (alg & SSL_aNULL) */
1264                 {
1265                 SSLerr(SSL_F_SSL_GET_SIGN_PKEY,SSL_R_INTERNAL_ERROR);
1266                 return(NULL);
1267                 }
1268         }
1269
1270 void ssl_update_cache(SSL *s,int mode)
1271         {
1272         int i;
1273
1274         /* If the session_id_length is 0, we are not supposed to cache it,
1275          * and it would be rather hard to do anyway :-) */
1276         if (s->session->session_id_length == 0) return;
1277
1278         if ((s->ctx->session_cache_mode & mode)
1279                 && (!s->hit)
1280                 && SSL_CTX_add_session(s->ctx,s->session)
1281                 && (s->ctx->new_session_cb != NULL))
1282                 {
1283                 CRYPTO_add(&s->session->references,1,CRYPTO_LOCK_SSL_SESSION);
1284                 if (!s->ctx->new_session_cb(s,s->session))
1285                         SSL_SESSION_free(s->session);
1286                 }
1287
1288         /* auto flush every 255 connections */
1289         i=s->ctx->session_cache_mode;
1290         if ((!(i & SSL_SESS_CACHE_NO_AUTO_CLEAR)) &&
1291                 ((i & mode) == mode))
1292                 {
1293                 if (  (((mode & SSL_SESS_CACHE_CLIENT)
1294                         ?s->ctx->stats.sess_connect_good
1295                         :s->ctx->stats.sess_accept_good) & 0xff) == 0xff)
1296                         {
1297                         SSL_CTX_flush_sessions(s->ctx,time(NULL));
1298                         }
1299                 }
1300         }
1301
1302 SSL_METHOD *SSL_get_ssl_method(SSL *s)
1303         {
1304         return(s->method);
1305         }
1306
1307 int SSL_set_ssl_method(SSL *s,SSL_METHOD *meth)
1308         {
1309         int conn= -1;
1310         int ret=1;
1311
1312         if (s->method != meth)
1313                 {
1314                 if (s->handshake_func != NULL)
1315                         conn=(s->handshake_func == s->method->ssl_connect);
1316
1317                 if (s->method->version == meth->version)
1318                         s->method=meth;
1319                 else
1320                         {
1321                         s->method->ssl_free(s);
1322                         s->method=meth;
1323                         ret=s->method->ssl_new(s);
1324                         }
1325
1326                 if (conn == 1)
1327                         s->handshake_func=meth->ssl_connect;
1328                 else if (conn == 0)
1329                         s->handshake_func=meth->ssl_accept;
1330                 }
1331         return(ret);
1332         }
1333
1334 int SSL_get_error(SSL *s,int i)
1335         {
1336         int reason;
1337         unsigned long l;
1338         BIO *bio;
1339
1340         if (i > 0) return(SSL_ERROR_NONE);
1341
1342         /* Make things return SSL_ERROR_SYSCALL when doing SSL_do_handshake
1343          * etc, where we do encode the error */
1344         if ((l=ERR_peek_error()) != 0)
1345                 {
1346                 if (ERR_GET_LIB(l) == ERR_LIB_SYS)
1347                         return(SSL_ERROR_SYSCALL);
1348                 else
1349                         return(SSL_ERROR_SSL);
1350                 }
1351
1352         if ((i < 0) && SSL_want_read(s))
1353                 {
1354                 bio=SSL_get_rbio(s);
1355                 if (BIO_should_read(bio))
1356                         return(SSL_ERROR_WANT_READ);
1357                 else if (BIO_should_write(bio))
1358                         return(SSL_ERROR_WANT_WRITE);
1359                 else if (BIO_should_io_special(bio))
1360                         {
1361                         reason=BIO_get_retry_reason(bio);
1362                         if (reason == BIO_RR_CONNECT)
1363                                 return(SSL_ERROR_WANT_CONNECT);
1364                         else
1365                                 return(SSL_ERROR_SYSCALL); /* unknown */
1366                         }
1367                 }
1368
1369         if ((i < 0) && SSL_want_write(s))
1370                 {
1371                 bio=SSL_get_wbio(s);
1372                 if (BIO_should_write(bio))
1373                         return(SSL_ERROR_WANT_WRITE);
1374                 else if (BIO_should_read(bio))
1375                         return(SSL_ERROR_WANT_READ);
1376                 else if (BIO_should_io_special(bio))
1377                         {
1378                         reason=BIO_get_retry_reason(bio);
1379                         if (reason == BIO_RR_CONNECT)
1380                                 return(SSL_ERROR_WANT_CONNECT);
1381                         else
1382                                 return(SSL_ERROR_SYSCALL);
1383                         }
1384                 }
1385         if ((i < 0) && SSL_want_x509_lookup(s))
1386                 {
1387                 return(SSL_ERROR_WANT_X509_LOOKUP);
1388                 }
1389
1390         if (i == 0)
1391                 {
1392                 if (s->version == SSL2_VERSION)
1393                         {
1394                         /* assume it is the socket being closed */
1395                         return(SSL_ERROR_ZERO_RETURN);
1396                         }
1397                 else
1398                         {
1399                         if ((s->shutdown & SSL_RECEIVED_SHUTDOWN) &&
1400                                 (s->s3->warn_alert == SSL_AD_CLOSE_NOTIFY))
1401                                 return(SSL_ERROR_ZERO_RETURN);
1402                         }
1403                 }
1404         return(SSL_ERROR_SYSCALL);
1405         }
1406
1407 int SSL_do_handshake(SSL *s)
1408         {
1409         int ret=1;
1410
1411         if (s->handshake_func == NULL)
1412                 {
1413                 SSLerr(SSL_F_SSL_DO_HANDSHAKE,SSL_R_CONNECTION_TYPE_NOT_SET);
1414                 return(-1);
1415                 }
1416
1417         s->method->ssl_renegotiate_check(s);
1418
1419         if (SSL_in_init(s) || SSL_in_before(s))
1420                 {
1421                 ret=s->handshake_func(s);
1422                 }
1423         return(ret);
1424         }
1425
1426 /* For the next 2 functions, SSL_clear() sets shutdown and so
1427  * one of these calls will reset it */
1428 void SSL_set_accept_state(SSL *s)
1429         {
1430         s->server=1;
1431         s->shutdown=0;
1432         s->state=SSL_ST_ACCEPT|SSL_ST_BEFORE;
1433         s->handshake_func=s->method->ssl_accept;
1434         /* clear the current cipher */
1435         ssl_clear_cipher_ctx(s);
1436         }
1437
1438 void SSL_set_connect_state(SSL *s)
1439         {
1440         s->server=0;
1441         s->shutdown=0;
1442         s->state=SSL_ST_CONNECT|SSL_ST_BEFORE;
1443         s->handshake_func=s->method->ssl_connect;
1444         /* clear the current cipher */
1445         ssl_clear_cipher_ctx(s);
1446         }
1447
1448 int ssl_undefined_function(SSL *s)
1449         {
1450         SSLerr(SSL_F_SSL_UNDEFINED_FUNCTION,ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1451         return(0);
1452         }
1453
1454 SSL_METHOD *ssl_bad_method(int ver)
1455         {
1456         SSLerr(SSL_F_SSL_BAD_METHOD,ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1457         return(NULL);
1458         }
1459
1460 char *SSL_get_version(SSL *s)
1461         {
1462         if (s->version == TLS1_VERSION)
1463                 return("TLSv1");
1464         else if (s->version == SSL3_VERSION)
1465                 return("SSLv3");
1466         else if (s->version == SSL2_VERSION)
1467                 return("SSLv2");
1468         else
1469                 return("unknown");
1470         }
1471
1472 SSL *SSL_dup(SSL *s)
1473         {
1474         STACK_OF(X509_NAME) *sk;
1475         X509_NAME *xn;
1476         SSL *ret;
1477         int i;
1478                  
1479         if ((ret=SSL_new(SSL_get_SSL_CTX(s))) == NULL)
1480             return(NULL);
1481                           
1482         /* This copies version, session-id, SSL_METHOD and 'cert' */
1483         SSL_copy_session_id(ret,s);
1484
1485         SSL_set_read_ahead(ret,SSL_get_read_ahead(s));
1486         SSL_set_verify(ret,SSL_get_verify_mode(s),
1487                 SSL_get_verify_callback(s));
1488         SSL_set_verify_depth(ret,SSL_get_verify_depth(s));
1489
1490         SSL_set_info_callback(ret,SSL_get_info_callback(s));
1491         
1492         ret->debug=s->debug;
1493         ret->options=s->options;
1494
1495         /* copy app data, a little dangerous perhaps */
1496         if (!CRYPTO_dup_ex_data(ssl_meth,&ret->ex_data,&s->ex_data))
1497                 goto err;
1498
1499         /* setup rbio, and wbio */
1500         if (s->rbio != NULL)
1501                 {
1502                 if (!BIO_dup_state(s->rbio,(char *)&ret->rbio))
1503                         goto err;
1504                 }
1505         if (s->wbio != NULL)
1506                 {
1507                 if (s->wbio != s->rbio)
1508                         {
1509                         if (!BIO_dup_state(s->wbio,(char *)&ret->wbio))
1510                                 goto err;
1511                         }
1512                 else
1513                         ret->wbio=ret->rbio;
1514                 }
1515
1516         /* dup the cipher_list and cipher_list_by_id stacks */
1517         if (s->cipher_list != NULL)
1518                 {
1519                 if ((ret->cipher_list=sk_SSL_CIPHER_dup(s->cipher_list)) == NULL)
1520                         goto err;
1521                 }
1522         if (s->cipher_list_by_id != NULL)
1523                 if ((ret->cipher_list_by_id=sk_SSL_CIPHER_dup(s->cipher_list_by_id))
1524                         == NULL)
1525                         goto err;
1526
1527         /* Dup the client_CA list */
1528         if (s->client_CA != NULL)
1529                 {
1530                 if ((sk=sk_X509_NAME_dup(s->client_CA)) == NULL) goto err;
1531                 ret->client_CA=sk;
1532                 for (i=0; i<sk_X509_NAME_num(sk); i++)
1533                         {
1534                         xn=sk_X509_NAME_value(sk,i);
1535                         if (sk_X509_NAME_set(sk,i,X509_NAME_dup(xn)) == NULL)
1536                                 {
1537                                 X509_NAME_free(xn);
1538                                 goto err;
1539                                 }
1540                         }
1541                 }
1542
1543         ret->shutdown=s->shutdown;
1544         ret->state=s->state;
1545         ret->handshake_func=s->handshake_func;
1546         ret->server=s->server;
1547
1548         if (0)
1549                 {
1550 err:
1551                 if (ret != NULL) SSL_free(ret);
1552                 ret=NULL;
1553                 }
1554         return(ret);
1555         }
1556
1557 void ssl_clear_cipher_ctx(SSL *s)
1558         {
1559         if (s->enc_read_ctx != NULL)
1560                 {
1561                 EVP_CIPHER_CTX_cleanup(s->enc_read_ctx);
1562                 Free(s->enc_read_ctx);
1563                 s->enc_read_ctx=NULL;
1564                 }
1565         if (s->enc_write_ctx != NULL)
1566                 {
1567                 EVP_CIPHER_CTX_cleanup(s->enc_write_ctx);
1568                 Free(s->enc_write_ctx);
1569                 s->enc_write_ctx=NULL;
1570                 }
1571         if (s->expand != NULL)
1572                 {
1573                 COMP_CTX_free(s->expand);
1574                 s->expand=NULL;
1575                 }
1576         if (s->compress != NULL)
1577                 {
1578                 COMP_CTX_free(s->compress);
1579                 s->compress=NULL;
1580                 }
1581         }
1582
1583 /* Fix this function so that it takes an optional type parameter */
1584 X509 *SSL_get_certificate(SSL *s)
1585         {
1586         if (s->cert != NULL)
1587                 return(s->cert->key->x509);
1588         else
1589                 return(NULL);
1590         }
1591
1592 /* Fix this function so that it takes an optional type parameter */
1593 EVP_PKEY *SSL_get_privatekey(SSL *s)
1594         {
1595         if (s->cert != NULL)
1596                 return(s->cert->key->privatekey);
1597         else
1598                 return(NULL);
1599         }
1600
1601 SSL_CIPHER *SSL_get_current_cipher(SSL *s)
1602         {
1603         if ((s->session != NULL) && (s->session->cipher != NULL))
1604                 return(s->session->cipher);
1605         return(NULL);
1606         }
1607
1608 int ssl_init_wbio_buffer(SSL *s,int push)
1609         {
1610         BIO *bbio;
1611
1612         if (s->bbio == NULL)
1613                 {
1614                 bbio=BIO_new(BIO_f_buffer());
1615                 if (bbio == NULL) return(0);
1616                 s->bbio=bbio;
1617                 }
1618         else
1619                 {
1620                 bbio=s->bbio;
1621                 if (s->bbio == s->wbio)
1622                         s->wbio=BIO_pop(s->wbio);
1623                 }
1624         BIO_reset(bbio);
1625 /*      if (!BIO_set_write_buffer_size(bbio,16*1024)) */
1626         if (!BIO_set_read_buffer_size(bbio,1))
1627                 {
1628                 SSLerr(SSL_F_SSL_INIT_WBIO_BUFFER,ERR_R_BUF_LIB);
1629                 return(0);
1630                 }
1631         if (push)
1632                 {
1633                 if (s->wbio != bbio)
1634                         s->wbio=BIO_push(bbio,s->wbio);
1635                 }
1636         else
1637                 {
1638                 if (s->wbio == bbio)
1639                         s->wbio=BIO_pop(bbio);
1640                 }
1641         return(1);
1642         }
1643
1644 void ssl_free_wbio_buffer(SSL *s)
1645         {
1646         BIO *under;
1647
1648         if (s->bbio == NULL) return;
1649
1650         if (s->bbio == s->wbio)
1651                 {
1652                 /* remove buffering */
1653                 under=BIO_pop(s->wbio);
1654                 if (under != NULL)
1655                         s->wbio=under;
1656                 else
1657                         abort(); /* ok */
1658                 }
1659         BIO_free(s->bbio);
1660         s->bbio=NULL;
1661         }
1662         
1663 void SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx,int mode)
1664         {
1665         ctx->quiet_shutdown=mode;
1666         }
1667
1668 int SSL_CTX_get_quiet_shutdown(SSL_CTX *ctx)
1669         {
1670         return(ctx->quiet_shutdown);
1671         }
1672
1673 void SSL_set_quiet_shutdown(SSL *s,int mode)
1674         {
1675         s->quiet_shutdown=mode;
1676         }
1677
1678 int SSL_get_quiet_shutdown(SSL *s)
1679         {
1680         return(s->quiet_shutdown);
1681         }
1682
1683 void SSL_set_shutdown(SSL *s,int mode)
1684         {
1685         s->shutdown=mode;
1686         }
1687
1688 int SSL_get_shutdown(SSL *s)
1689         {
1690         return(s->shutdown);
1691         }
1692
1693 int SSL_version(SSL *s)
1694         {
1695         return(s->version);
1696         }
1697
1698 SSL_CTX *SSL_get_SSL_CTX(SSL *ssl)
1699         {
1700         return(ssl->ctx);
1701         }
1702
1703 #ifndef NO_STDIO
1704 int SSL_CTX_set_default_verify_paths(SSL_CTX *ctx)
1705         {
1706         return(X509_STORE_set_default_paths(ctx->cert_store));
1707         }
1708
1709 int SSL_CTX_load_verify_locations(SSL_CTX *ctx,char *CAfile,char *CApath)
1710         {
1711         return(X509_STORE_load_locations(ctx->cert_store,CAfile,CApath));
1712         }
1713 #endif
1714
1715 void SSL_set_info_callback(SSL *ssl,void (*cb)())
1716         {
1717         ssl->info_callback=cb;
1718         }
1719
1720 void (*SSL_get_info_callback(SSL *ssl))(void)
1721         {
1722         return((void (*)())ssl->info_callback);
1723         }
1724
1725 int SSL_state(SSL *ssl)
1726         {
1727         return(ssl->state);
1728         }
1729
1730 void SSL_set_verify_result(SSL *ssl,long arg)
1731         {
1732         ssl->verify_result=arg;
1733         }
1734
1735 long SSL_get_verify_result(SSL *ssl)
1736         {
1737         return(ssl->verify_result);
1738         }
1739
1740 int SSL_get_ex_new_index(long argl,char *argp,int (*new_func)(),
1741                          int (*dup_func)(),void (*free_func)())
1742         {
1743         ssl_meth_num++;
1744         return(CRYPTO_get_ex_new_index(ssl_meth_num-1,
1745                 &ssl_meth,argl,argp,new_func,dup_func,free_func));
1746         }
1747
1748 int SSL_set_ex_data(SSL *s,int idx,void *arg)
1749         {
1750         return(CRYPTO_set_ex_data(&s->ex_data,idx,arg));
1751         }
1752
1753 void *SSL_get_ex_data(SSL *s,int idx)
1754         {
1755         return(CRYPTO_get_ex_data(&s->ex_data,idx));
1756         }
1757
1758 int SSL_CTX_get_ex_new_index(long argl,char *argp,int (*new_func)(),
1759                              int (*dup_func)(),void (*free_func)())
1760         {
1761         ssl_ctx_meth_num++;
1762         return(CRYPTO_get_ex_new_index(ssl_ctx_meth_num-1,
1763                 &ssl_ctx_meth,argl,argp,new_func,dup_func,free_func));
1764         }
1765
1766 int SSL_CTX_set_ex_data(SSL_CTX *s,int idx,void *arg)
1767         {
1768         return(CRYPTO_set_ex_data(&s->ex_data,idx,arg));
1769         }
1770
1771 void *SSL_CTX_get_ex_data(SSL_CTX *s,int idx)
1772         {
1773         return(CRYPTO_get_ex_data(&s->ex_data,idx));
1774         }
1775
1776 int ssl_ok(SSL *s)
1777         {
1778         return(1);
1779         }
1780
1781 X509_STORE *SSL_CTX_get_cert_store(SSL_CTX *ctx)
1782         {
1783         return(ctx->cert_store);
1784         }
1785
1786 void SSL_CTX_set_cert_store(SSL_CTX *ctx,X509_STORE *store)
1787         {
1788         if (ctx->cert_store != NULL)
1789                 X509_STORE_free(ctx->cert_store);
1790         ctx->cert_store=store;
1791         }
1792
1793 int SSL_want(SSL *s)
1794         {
1795         return(s->rwstate);
1796         }
1797
1798 /*!
1799  * \brief Set the callback for generating temporary RSA keys.
1800  * \param ctx the SSL context.
1801  * \param cb the callback
1802  */
1803
1804 #ifndef NO_RSA
1805 void SSL_CTX_set_tmp_rsa_callback(SSL_CTX *ctx,RSA *(*cb)(SSL *ssl,int export,
1806                                                           int keylength))
1807     { SSL_CTX_ctrl(ctx,SSL_CTRL_SET_TMP_RSA_CB,0,(char *)cb); }
1808 #endif
1809
1810 #ifndef NO_RSA
1811 void SSL_set_tmp_rsa_callback(SSL *ssl,RSA *(*cb)(SSL *ssl,int export,
1812                                                           int keylength))
1813     { SSL_ctrl(ssl,SSL_CTRL_SET_TMP_RSA_CB,0,(char *)cb); }
1814 #endif
1815
1816 #ifdef DOXYGEN
1817 /*!
1818  * \brief The RSA temporary key callback function.
1819  * \param ssl the SSL session.
1820  * \param export \c TRUE if the temp RSA key is for an export ciphersuite.
1821  * \param keylength if \c export is \c TRUE, then \c keylength is the size of
1822  * the required key in bits.
1823  * \return the temporary RSA key.
1824  * \sa SSL_CTX_set_tmp_rsa_callback, SSL_set_tmp_rsa_callback
1825  */
1826
1827 RSA *cb(SSL *ssl,int export,int keylength)
1828     {}
1829 #endif
1830
1831 /*!
1832  * \brief Set the callback for generating temporary DH keys.
1833  * \param ctx the SSL context.
1834  * \param dh the callback
1835  */
1836
1837 #ifndef NO_DH
1838 void SSL_CTX_set_tmp_dh_callback(SSL_CTX *ctx,DH *(*dh)(SSL *ssl,int export,
1839                                                         int keylength))
1840     { SSL_CTX_ctrl(ctx,SSL_CTRL_SET_TMP_DH_CB,0,(char *)dh); }
1841
1842 void SSL_set_tmp_dh_callback(SSL *ssl,DH *(*dh)(SSL *ssl,int export,
1843                                                         int keylength))
1844     { SSL_ctrl(ssl,SSL_CTRL_SET_TMP_DH_CB,0,(char *)dh); }
1845 #endif
1846
1847 #if defined(_WINDLL) && defined(WIN16)
1848 #include "../crypto/bio/bss_file.c"
1849 #endif
1850
1851 IMPLEMENT_STACK_OF(SSL_CIPHER)
1852 IMPLEMENT_STACK_OF(SSL_COMP)