Use "const char *" instead of "char *" for filenames passed to functions.
[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         }
656
657 long SSL_CTX_ctrl(SSL_CTX *ctx,int cmd,long larg,char *parg)
658         {
659         long l;
660
661         switch (cmd)
662                 {
663         case SSL_CTRL_GET_READ_AHEAD:
664                 return(ctx->read_ahead);
665         case SSL_CTRL_SET_READ_AHEAD:
666                 l=ctx->read_ahead;
667                 ctx->read_ahead=larg;
668                 return(l);
669
670         case SSL_CTRL_SET_SESS_CACHE_SIZE:
671                 l=ctx->session_cache_size;
672                 ctx->session_cache_size=larg;
673                 return(l);
674         case SSL_CTRL_GET_SESS_CACHE_SIZE:
675                 return(ctx->session_cache_size);
676         case SSL_CTRL_SET_SESS_CACHE_MODE:
677                 l=ctx->session_cache_mode;
678                 ctx->session_cache_mode=larg;
679                 return(l);
680         case SSL_CTRL_GET_SESS_CACHE_MODE:
681                 return(ctx->session_cache_mode);
682
683         case SSL_CTRL_SESS_NUMBER:
684                 return(ctx->sessions->num_items);
685         case SSL_CTRL_SESS_CONNECT:
686                 return(ctx->stats.sess_connect);
687         case SSL_CTRL_SESS_CONNECT_GOOD:
688                 return(ctx->stats.sess_connect_good);
689         case SSL_CTRL_SESS_CONNECT_RENEGOTIATE:
690                 return(ctx->stats.sess_connect_renegotiate);
691         case SSL_CTRL_SESS_ACCEPT:
692                 return(ctx->stats.sess_accept);
693         case SSL_CTRL_SESS_ACCEPT_GOOD:
694                 return(ctx->stats.sess_accept_good);
695         case SSL_CTRL_SESS_ACCEPT_RENEGOTIATE:
696                 return(ctx->stats.sess_accept_renegotiate);
697         case SSL_CTRL_SESS_HIT:
698                 return(ctx->stats.sess_hit);
699         case SSL_CTRL_SESS_CB_HIT:
700                 return(ctx->stats.sess_cb_hit);
701         case SSL_CTRL_SESS_MISSES:
702                 return(ctx->stats.sess_miss);
703         case SSL_CTRL_SESS_TIMEOUTS:
704                 return(ctx->stats.sess_timeout);
705         case SSL_CTRL_SESS_CACHE_FULL:
706                 return(ctx->stats.sess_cache_full);
707         case SSL_CTRL_OPTIONS:
708                 return(ctx->options|=larg);
709         default:
710                 return(ctx->method->ssl_ctx_ctrl(ctx,cmd,larg,parg));
711                 }
712         }
713
714 int ssl_cipher_id_cmp(SSL_CIPHER *a,SSL_CIPHER *b)
715         {
716         long l;
717
718         l=a->id-b->id;
719         if (l == 0L)
720                 return(0);
721         else
722                 return((l > 0)?1:-1);
723         }
724
725 int ssl_cipher_ptr_id_cmp(SSL_CIPHER **ap,SSL_CIPHER **bp)
726         {
727         long l;
728
729         l=(*ap)->id-(*bp)->id;
730         if (l == 0L)
731                 return(0);
732         else
733                 return((l > 0)?1:-1);
734         }
735
736 /** return a STACK of the ciphers available for the SSL and in order of
737  * preference */
738 STACK_OF(SSL_CIPHER) *SSL_get_ciphers(SSL *s)
739         {
740         if ((s != NULL) && (s->cipher_list != NULL))
741                 {
742                 return(s->cipher_list);
743                 }
744         else if ((s->ctx != NULL) &&
745                 (s->ctx->cipher_list != NULL))
746                 {
747                 return(s->ctx->cipher_list);
748                 }
749         return(NULL);
750         }
751
752 /** return a STACK of the ciphers available for the SSL and in order of
753  * algorithm id */
754 STACK_OF(SSL_CIPHER) *ssl_get_ciphers_by_id(SSL *s)
755         {
756         if ((s != NULL) && (s->cipher_list_by_id != NULL))
757                 {
758                 return(s->cipher_list_by_id);
759                 }
760         else if ((s != NULL) && (s->ctx != NULL) &&
761                 (s->ctx->cipher_list_by_id != NULL))
762                 {
763                 return(s->ctx->cipher_list_by_id);
764                 }
765         return(NULL);
766         }
767
768 /** The old interface to get the same thing as SSL_get_ciphers() */
769 const char *SSL_get_cipher_list(SSL *s,int n)
770         {
771         SSL_CIPHER *c;
772         STACK_OF(SSL_CIPHER) *sk;
773
774         if (s == NULL) return(NULL);
775         sk=SSL_get_ciphers(s);
776         if ((sk == NULL) || (sk_SSL_CIPHER_num(sk) <= n))
777                 return(NULL);
778         c=sk_SSL_CIPHER_value(sk,n);
779         if (c == NULL) return(NULL);
780         return(c->name);
781         }
782
783 /** specify the ciphers to be used by defaut by the SSL_CTX */
784 int SSL_CTX_set_cipher_list(SSL_CTX *ctx,char *str)
785         {
786         STACK_OF(SSL_CIPHER) *sk;
787         
788         sk=ssl_create_cipher_list(ctx->method,&ctx->cipher_list,
789                 &ctx->cipher_list_by_id,str);
790 /* XXXX */
791         return((sk == NULL)?0:1);
792         }
793
794 /** specify the ciphers to be used by the SSL */
795 int SSL_set_cipher_list(SSL *s,char *str)
796         {
797         STACK_OF(SSL_CIPHER) *sk;
798         
799         sk=ssl_create_cipher_list(s->ctx->method,&s->cipher_list,
800                 &s->cipher_list_by_id,str);
801 /* XXXX */
802         return((sk == NULL)?0:1);
803         }
804
805 /* works well for SSLv2, not so good for SSLv3 */
806 char *SSL_get_shared_ciphers(SSL *s,char *buf,int len)
807         {
808         char *p;
809         const char *cp;
810         STACK_OF(SSL_CIPHER) *sk;
811         SSL_CIPHER *c;
812         int i;
813
814         if ((s->session == NULL) || (s->session->ciphers == NULL) ||
815                 (len < 2))
816                 return(NULL);
817
818         p=buf;
819         sk=s->session->ciphers;
820         for (i=0; i<sk_SSL_CIPHER_num(sk); i++)
821                 {
822                 /* Decrement for either the ':' or a '\0' */
823                 len--;
824                 c=sk_SSL_CIPHER_value(sk,i);
825                 for (cp=c->name; *cp; )
826                         {
827                         if (len-- == 0)
828                                 {
829                                 *p='\0';
830                                 return(buf);
831                                 }
832                         else
833                                 *(p++)= *(cp++);
834                         }
835                 *(p++)=':';
836                 }
837         p[-1]='\0';
838         return(buf);
839         }
840
841 int ssl_cipher_list_to_bytes(SSL *s,STACK_OF(SSL_CIPHER) *sk,unsigned char *p)
842         {
843         int i,j=0;
844         SSL_CIPHER *c;
845         unsigned char *q;
846
847         if (sk == NULL) return(0);
848         q=p;
849
850         for (i=0; i<sk_SSL_CIPHER_num(sk); i++)
851                 {
852                 c=sk_SSL_CIPHER_value(sk,i);
853                 j=ssl_put_cipher_by_char(s,c,p);
854                 p+=j;
855                 }
856         return(p-q);
857         }
858
859 STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list(SSL *s,unsigned char *p,int num,
860                                                STACK_OF(SSL_CIPHER) **skp)
861         {
862         SSL_CIPHER *c;
863         STACK_OF(SSL_CIPHER) *sk;
864         int i,n;
865
866         n=ssl_put_cipher_by_char(s,NULL,NULL);
867         if ((num%n) != 0)
868                 {
869                 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
870                 return(NULL);
871                 }
872         if ((skp == NULL) || (*skp == NULL))
873                 sk=sk_SSL_CIPHER_new(NULL); /* change perhaps later */
874         else
875                 {
876                 sk= *skp;
877                 sk_SSL_CIPHER_zero(sk);
878                 }
879
880         for (i=0; i<num; i+=n)
881                 {
882                 c=ssl_get_cipher_by_char(s,p);
883                 p+=n;
884                 if (c != NULL)
885                         {
886                         if (!sk_SSL_CIPHER_push(sk,c))
887                                 {
888                                 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,ERR_R_MALLOC_FAILURE);
889                                 goto err;
890                                 }
891                         }
892                 }
893
894         if (skp != NULL)
895                 *skp=sk;
896         return(sk);
897 err:
898         if ((skp == NULL) || (*skp == NULL))
899                 sk_SSL_CIPHER_free(sk);
900         return(NULL);
901         }
902
903 unsigned long SSL_SESSION_hash(SSL_SESSION *a)
904         {
905         unsigned long l;
906
907         l=(unsigned long)
908                 ((unsigned int) a->session_id[0]     )|
909                 ((unsigned int) a->session_id[1]<< 8L)|
910                 ((unsigned long)a->session_id[2]<<16L)|
911                 ((unsigned long)a->session_id[3]<<24L);
912         return(l);
913         }
914
915 int SSL_SESSION_cmp(SSL_SESSION *a,SSL_SESSION *b)
916         {
917         if (a->ssl_version != b->ssl_version)
918                 return(1);
919         if (a->session_id_length != b->session_id_length)
920                 return(1);
921         return(memcmp(a->session_id,b->session_id,a->session_id_length));
922         }
923
924 SSL_CTX *SSL_CTX_new(SSL_METHOD *meth)
925         {
926         SSL_CTX *ret=NULL;
927         
928         if (meth == NULL)
929                 {
930                 SSLerr(SSL_F_SSL_CTX_NEW,SSL_R_NULL_SSL_METHOD_PASSED);
931                 return(NULL);
932                 }
933
934         if (SSL_get_ex_data_X509_STORE_CTX_idx() < 0)
935                 {
936                 SSLerr(SSL_F_SSL_CTX_NEW,SSL_R_X509_VERIFICATION_SETUP_PROBLEMS);
937                 goto err;
938                 }
939         ret=(SSL_CTX *)Malloc(sizeof(SSL_CTX));
940         if (ret == NULL)
941                 goto err;
942
943         memset(ret,0,sizeof(SSL_CTX));
944
945         ret->method=meth;
946
947         ret->cert_store=NULL;
948         ret->session_cache_mode=SSL_SESS_CACHE_SERVER;
949         ret->session_cache_size=SSL_SESSION_CACHE_MAX_SIZE_DEFAULT;
950         ret->session_cache_head=NULL;
951         ret->session_cache_tail=NULL;
952
953         /* We take the system default */
954         ret->session_timeout=meth->get_timeout();
955
956         ret->new_session_cb=NULL;
957         ret->remove_session_cb=NULL;
958         ret->get_session_cb=NULL;
959
960         memset((char *)&ret->stats,0,sizeof(ret->stats));
961
962         ret->references=1;
963         ret->quiet_shutdown=0;
964
965 /*      ret->cipher=NULL;*/
966 /*      ret->s2->challenge=NULL;
967         ret->master_key=NULL;
968         ret->key_arg=NULL;
969         ret->s2->conn_id=NULL; */
970
971         ret->info_callback=NULL;
972
973         ret->app_verify_callback=NULL;
974         ret->app_verify_arg=NULL;
975
976         ret->read_ahead=0;
977         ret->verify_mode=SSL_VERIFY_NONE;
978         ret->verify_depth=-1; /* Don't impose a limit (but x509_lu.c does) */
979         ret->default_verify_callback=NULL;
980         if ((ret->default_cert=ssl_cert_new()) == NULL)
981                 goto err;
982
983         ret->default_passwd_callback=NULL;
984         ret->client_cert_cb=NULL;
985
986         ret->sessions=lh_new(SSL_SESSION_hash,SSL_SESSION_cmp);
987         if (ret->sessions == NULL) goto err;
988         ret->cert_store=X509_STORE_new();
989         if (ret->cert_store == NULL) goto err;
990
991         ssl_create_cipher_list(ret->method,
992                 &ret->cipher_list,&ret->cipher_list_by_id,
993                 SSL_DEFAULT_CIPHER_LIST);
994         if (ret->cipher_list == NULL
995             || sk_SSL_CIPHER_num(ret->cipher_list) <= 0)
996                 {
997                 SSLerr(SSL_F_SSL_CTX_NEW,SSL_R_LIBRARY_HAS_NO_CIPHERS);
998                 goto err2;
999                 }
1000
1001         if ((ret->rsa_md5=EVP_get_digestbyname("ssl2-md5")) == NULL)
1002                 {
1003                 SSLerr(SSL_F_SSL_CTX_NEW,SSL_R_UNABLE_TO_LOAD_SSL2_MD5_ROUTINES);
1004                 goto err2;
1005                 }
1006         if ((ret->md5=EVP_get_digestbyname("ssl3-md5")) == NULL)
1007                 {
1008                 SSLerr(SSL_F_SSL_CTX_NEW,SSL_R_UNABLE_TO_LOAD_SSL3_MD5_ROUTINES);
1009                 goto err2;
1010                 }
1011         if ((ret->sha1=EVP_get_digestbyname("ssl3-sha1")) == NULL)
1012                 {
1013                 SSLerr(SSL_F_SSL_CTX_NEW,SSL_R_UNABLE_TO_LOAD_SSL3_SHA1_ROUTINES);
1014                 goto err2;
1015                 }
1016
1017         if ((ret->client_CA=sk_X509_NAME_new_null()) == NULL)
1018                 goto err;
1019
1020         CRYPTO_new_ex_data(ssl_ctx_meth,(char *)ret,&ret->ex_data);
1021
1022         ret->extra_certs=NULL;
1023         ret->comp_methods=SSL_COMP_get_compression_methods();
1024
1025         return(ret);
1026 err:
1027         SSLerr(SSL_F_SSL_CTX_NEW,ERR_R_MALLOC_FAILURE);
1028 err2:
1029         if (ret != NULL) SSL_CTX_free(ret);
1030         return(NULL);
1031         }
1032
1033 static void SSL_COMP_free(SSL_COMP *comp)
1034     { Free(comp); }
1035
1036 void SSL_CTX_free(SSL_CTX *a)
1037         {
1038         int i;
1039
1040         if (a == NULL) return;
1041
1042         i=CRYPTO_add(&a->references,-1,CRYPTO_LOCK_SSL_CTX);
1043 #ifdef REF_PRINT
1044         REF_PRINT("SSL_CTX",a);
1045 #endif
1046         if (i > 0) return;
1047 #ifdef REF_CHECK
1048         if (i < 0)
1049                 {
1050                 fprintf(stderr,"SSL_CTX_free, bad reference count\n");
1051                 abort(); /* ok */
1052                 }
1053 #endif
1054         CRYPTO_free_ex_data(ssl_ctx_meth,(char *)a,&a->ex_data);
1055
1056         if (a->sessions != NULL)
1057                 {
1058                 SSL_CTX_flush_sessions(a,0);
1059                 lh_free(a->sessions);
1060                 }
1061         if (a->cert_store != NULL)
1062                 X509_STORE_free(a->cert_store);
1063         if (a->cipher_list != NULL)
1064                 sk_SSL_CIPHER_free(a->cipher_list);
1065         if (a->cipher_list_by_id != NULL)
1066                 sk_SSL_CIPHER_free(a->cipher_list_by_id);
1067         if (a->default_cert != NULL)
1068                 ssl_cert_free(a->default_cert);
1069         if (a->client_CA != NULL)
1070                 sk_X509_NAME_pop_free(a->client_CA,X509_NAME_free);
1071         if (a->extra_certs != NULL)
1072                 sk_X509_pop_free(a->extra_certs,X509_free);
1073         if (a->comp_methods != NULL)
1074                 sk_SSL_COMP_pop_free(a->comp_methods,SSL_COMP_free);
1075         Free((char *)a);
1076         }
1077
1078 void SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx,int (*cb)())
1079         {
1080         ctx->default_passwd_callback=cb;
1081         }
1082
1083 void SSL_CTX_set_cert_verify_cb(SSL_CTX *ctx,int (*cb)(),char *arg)
1084         {
1085         ctx->app_verify_callback=cb;
1086         ctx->app_verify_arg=arg;
1087         }
1088
1089 void SSL_CTX_set_verify(SSL_CTX *ctx,int mode,int (*cb)(int, X509_STORE_CTX *))
1090         {
1091         ctx->verify_mode=mode;
1092         ctx->default_verify_callback=cb;
1093         /* This needs cleaning up EAY EAY EAY */
1094         X509_STORE_set_verify_cb_func(ctx->cert_store,cb);
1095         }
1096
1097 void SSL_CTX_set_verify_depth(SSL_CTX *ctx,int depth)
1098         {
1099         ctx->verify_depth=depth;
1100         }
1101
1102 /* Need default_cert to check for callbacks, for now (see comment in CERT
1103    strucure)
1104 */
1105 void ssl_set_cert_masks(CERT *c,CERT *default_cert,SSL_CIPHER *cipher)
1106         {
1107         CERT_PKEY *cpk;
1108         int rsa_enc,rsa_tmp,rsa_sign,dh_tmp,dh_rsa,dh_dsa,dsa_sign;
1109         int rsa_enc_export,dh_rsa_export,dh_dsa_export;
1110         int rsa_tmp_export,dh_tmp_export,kl;
1111         unsigned long mask,emask;
1112
1113         if (c == NULL) return;
1114
1115         kl=SSL_C_EXPORT_PKEYLENGTH(cipher);
1116
1117 #ifndef NO_RSA
1118         rsa_tmp=(c->rsa_tmp != NULL || default_cert->rsa_tmp_cb != NULL);
1119         rsa_tmp_export=(default_cert->rsa_tmp_cb != NULL ||
1120                 (rsa_tmp && RSA_size(c->rsa_tmp)*8 <= kl));
1121 #else
1122         rsa_tmp=rsa_tmp_export=0;
1123 #endif
1124 #ifndef NO_DH
1125         dh_tmp=(c->dh_tmp != NULL || default_cert->dh_tmp_cb != NULL);
1126         dh_tmp_export=(default_cert->dh_tmp_cb != NULL ||
1127                 (dh_tmp && DH_size(c->dh_tmp)*8 <= kl));
1128 #else
1129         dh_tmp=dh_tmp_export=0;
1130 #endif
1131
1132         cpk= &(c->pkeys[SSL_PKEY_RSA_ENC]);
1133         rsa_enc= (cpk->x509 != NULL && cpk->privatekey != NULL);
1134         rsa_enc_export=(rsa_enc && EVP_PKEY_size(cpk->privatekey)*8 <= kl);
1135         cpk= &(c->pkeys[SSL_PKEY_RSA_SIGN]);
1136         rsa_sign=(cpk->x509 != NULL && cpk->privatekey != NULL);
1137         cpk= &(c->pkeys[SSL_PKEY_DSA_SIGN]);
1138         dsa_sign=(cpk->x509 != NULL && cpk->privatekey != NULL);
1139         cpk= &(c->pkeys[SSL_PKEY_DH_RSA]);
1140         dh_rsa=  (cpk->x509 != NULL && cpk->privatekey != NULL);
1141         dh_rsa_export=(dh_rsa && EVP_PKEY_size(cpk->privatekey)*8 <= kl);
1142         cpk= &(c->pkeys[SSL_PKEY_DH_DSA]);
1143 /* FIX THIS EAY EAY EAY */
1144         dh_dsa=  (cpk->x509 != NULL && cpk->privatekey != NULL);
1145         dh_dsa_export=(dh_dsa && EVP_PKEY_size(cpk->privatekey)*8 <= kl);
1146
1147         mask=0;
1148         emask=0;
1149
1150 #ifdef CIPHER_DEBUG
1151         printf("rt=%d rte=%d dht=%d re=%d ree=%d rs=%d ds=%d dhr=%d dhd=%d\n",
1152                 rsa_tmp,rsa_tmp_export,dh_tmp,
1153                 rsa_enc,rsa_enc_export,rsa_sign,dsa_sign,dh_rsa,dh_dsa);
1154 #endif
1155
1156         if (rsa_enc || (rsa_tmp && rsa_sign))
1157                 mask|=SSL_kRSA;
1158         if (rsa_enc_export || (rsa_tmp_export && (rsa_sign || rsa_enc)))
1159                 emask|=SSL_kRSA;
1160
1161 #if 0
1162         /* The match needs to be both kEDH and aRSA or aDSA, so don't worry */
1163         if (    (dh_tmp || dh_rsa || dh_dsa) && 
1164                 (rsa_enc || rsa_sign || dsa_sign))
1165                 mask|=SSL_kEDH;
1166         if ((dh_tmp_export || dh_rsa_export || dh_dsa_export) &&
1167                 (rsa_enc || rsa_sign || dsa_sign))
1168                 emask|=SSL_kEDH;
1169 #endif
1170
1171         if (dh_tmp_export) 
1172                 emask|=SSL_kEDH;
1173
1174         if (dh_tmp)
1175                 mask|=SSL_kEDH;
1176
1177         if (dh_rsa) mask|=SSL_kDHr;
1178         if (dh_rsa_export) emask|=SSL_kDHr;
1179
1180         if (dh_dsa) mask|=SSL_kDHd;
1181         if (dh_dsa_export) emask|=SSL_kDHd;
1182
1183         if (rsa_enc || rsa_sign)
1184                 {
1185                 mask|=SSL_aRSA;
1186                 emask|=SSL_aRSA;
1187                 }
1188
1189         if (dsa_sign)
1190                 {
1191                 mask|=SSL_aDSS;
1192                 emask|=SSL_aDSS;
1193                 }
1194
1195 #ifdef SSL_ALLOW_ADH
1196         mask|=SSL_aNULL;
1197         emask|=SSL_aNULL;
1198 #endif
1199
1200         c->mask=mask;
1201         c->export_mask=emask;
1202         c->valid=1;
1203         }
1204
1205 /* THIS NEEDS CLEANING UP */
1206 X509 *ssl_get_server_send_cert(SSL *s)
1207         {
1208         unsigned long alg,mask,kalg;
1209         CERT *c;
1210         int i,export;
1211
1212         c=s->cert;
1213         ssl_set_cert_masks(c,s->ctx->default_cert,s->s3->tmp.new_cipher);
1214         alg=s->s3->tmp.new_cipher->algorithms;
1215         export=SSL_IS_EXPORT(alg);
1216         mask=export?c->export_mask:c->mask;
1217         kalg=alg&(SSL_MKEY_MASK|SSL_AUTH_MASK);
1218
1219         if      (kalg & SSL_kDHr)
1220                 i=SSL_PKEY_DH_RSA;
1221         else if (kalg & SSL_kDHd)
1222                 i=SSL_PKEY_DH_DSA;
1223         else if (kalg & SSL_aDSS)
1224                 i=SSL_PKEY_DSA_SIGN;
1225         else if (kalg & SSL_aRSA)
1226                 {
1227                 if (c->pkeys[SSL_PKEY_RSA_ENC].x509 == NULL)
1228                         i=SSL_PKEY_RSA_SIGN;
1229                 else
1230                         i=SSL_PKEY_RSA_ENC;
1231                 }
1232         else /* if (kalg & SSL_aNULL) */
1233                 {
1234                 SSLerr(SSL_F_SSL_GET_SERVER_SEND_CERT,SSL_R_INTERNAL_ERROR);
1235                 return(NULL);
1236                 }
1237         if (c->pkeys[i].x509 == NULL) return(NULL);
1238         return(c->pkeys[i].x509);
1239         }
1240
1241 EVP_PKEY *ssl_get_sign_pkey(SSL *s,SSL_CIPHER *cipher)
1242         {
1243         unsigned long alg;
1244         CERT *c;
1245
1246         alg=cipher->algorithms;
1247         c=s->cert;
1248
1249         if ((alg & SSL_aDSS) &&
1250                 (c->pkeys[SSL_PKEY_DSA_SIGN].privatekey != NULL))
1251                 return(c->pkeys[SSL_PKEY_DSA_SIGN].privatekey);
1252         else if (alg & SSL_aRSA)
1253                 {
1254                 if (c->pkeys[SSL_PKEY_RSA_SIGN].privatekey != NULL)
1255                         return(c->pkeys[SSL_PKEY_RSA_SIGN].privatekey);
1256                 else if (c->pkeys[SSL_PKEY_RSA_ENC].privatekey != NULL)
1257                         return(c->pkeys[SSL_PKEY_RSA_ENC].privatekey);
1258                 else
1259                         return(NULL);
1260                 }
1261         else /* if (alg & SSL_aNULL) */
1262                 {
1263                 SSLerr(SSL_F_SSL_GET_SIGN_PKEY,SSL_R_INTERNAL_ERROR);
1264                 return(NULL);
1265                 }
1266         }
1267
1268 void ssl_update_cache(SSL *s,int mode)
1269         {
1270         int i;
1271
1272         /* If the session_id_length is 0, we are not supposed to cache it,
1273          * and it would be rather hard to do anyway :-) */
1274         if (s->session->session_id_length == 0) return;
1275
1276         if ((s->ctx->session_cache_mode & mode)
1277                 && (!s->hit)
1278                 && SSL_CTX_add_session(s->ctx,s->session)
1279                 && (s->ctx->new_session_cb != NULL))
1280                 {
1281                 CRYPTO_add(&s->session->references,1,CRYPTO_LOCK_SSL_SESSION);
1282                 if (!s->ctx->new_session_cb(s,s->session))
1283                         SSL_SESSION_free(s->session);
1284                 }
1285
1286         /* auto flush every 255 connections */
1287         i=s->ctx->session_cache_mode;
1288         if ((!(i & SSL_SESS_CACHE_NO_AUTO_CLEAR)) &&
1289                 ((i & mode) == mode))
1290                 {
1291                 if (  (((mode & SSL_SESS_CACHE_CLIENT)
1292                         ?s->ctx->stats.sess_connect_good
1293                         :s->ctx->stats.sess_accept_good) & 0xff) == 0xff)
1294                         {
1295                         SSL_CTX_flush_sessions(s->ctx,time(NULL));
1296                         }
1297                 }
1298         }
1299
1300 SSL_METHOD *SSL_get_ssl_method(SSL *s)
1301         {
1302         return(s->method);
1303         }
1304
1305 int SSL_set_ssl_method(SSL *s,SSL_METHOD *meth)
1306         {
1307         int conn= -1;
1308         int ret=1;
1309
1310         if (s->method != meth)
1311                 {
1312                 if (s->handshake_func != NULL)
1313                         conn=(s->handshake_func == s->method->ssl_connect);
1314
1315                 if (s->method->version == meth->version)
1316                         s->method=meth;
1317                 else
1318                         {
1319                         s->method->ssl_free(s);
1320                         s->method=meth;
1321                         ret=s->method->ssl_new(s);
1322                         }
1323
1324                 if (conn == 1)
1325                         s->handshake_func=meth->ssl_connect;
1326                 else if (conn == 0)
1327                         s->handshake_func=meth->ssl_accept;
1328                 }
1329         return(ret);
1330         }
1331
1332 int SSL_get_error(SSL *s,int i)
1333         {
1334         int reason;
1335         unsigned long l;
1336         BIO *bio;
1337
1338         if (i > 0) return(SSL_ERROR_NONE);
1339
1340         /* Make things return SSL_ERROR_SYSCALL when doing SSL_do_handshake
1341          * etc, where we do encode the error */
1342         if ((l=ERR_peek_error()) != 0)
1343                 {
1344                 if (ERR_GET_LIB(l) == ERR_LIB_SYS)
1345                         return(SSL_ERROR_SYSCALL);
1346                 else
1347                         return(SSL_ERROR_SSL);
1348                 }
1349
1350         if ((i < 0) && SSL_want_read(s))
1351                 {
1352                 bio=SSL_get_rbio(s);
1353                 if (BIO_should_read(bio))
1354                         return(SSL_ERROR_WANT_READ);
1355                 else if (BIO_should_write(bio))
1356                         return(SSL_ERROR_WANT_WRITE);
1357                 else if (BIO_should_io_special(bio))
1358                         {
1359                         reason=BIO_get_retry_reason(bio);
1360                         if (reason == BIO_RR_CONNECT)
1361                                 return(SSL_ERROR_WANT_CONNECT);
1362                         else
1363                                 return(SSL_ERROR_SYSCALL); /* unknown */
1364                         }
1365                 }
1366
1367         if ((i < 0) && SSL_want_write(s))
1368                 {
1369                 bio=SSL_get_wbio(s);
1370                 if (BIO_should_write(bio))
1371                         return(SSL_ERROR_WANT_WRITE);
1372                 else if (BIO_should_read(bio))
1373                         return(SSL_ERROR_WANT_READ);
1374                 else if (BIO_should_io_special(bio))
1375                         {
1376                         reason=BIO_get_retry_reason(bio);
1377                         if (reason == BIO_RR_CONNECT)
1378                                 return(SSL_ERROR_WANT_CONNECT);
1379                         else
1380                                 return(SSL_ERROR_SYSCALL);
1381                         }
1382                 }
1383         if ((i < 0) && SSL_want_x509_lookup(s))
1384                 {
1385                 return(SSL_ERROR_WANT_X509_LOOKUP);
1386                 }
1387
1388         if (i == 0)
1389                 {
1390                 if (s->version == SSL2_VERSION)
1391                         {
1392                         /* assume it is the socket being closed */
1393                         return(SSL_ERROR_ZERO_RETURN);
1394                         }
1395                 else
1396                         {
1397                         if ((s->shutdown & SSL_RECEIVED_SHUTDOWN) &&
1398                                 (s->s3->warn_alert == SSL_AD_CLOSE_NOTIFY))
1399                                 return(SSL_ERROR_ZERO_RETURN);
1400                         }
1401                 }
1402         return(SSL_ERROR_SYSCALL);
1403         }
1404
1405 int SSL_do_handshake(SSL *s)
1406         {
1407         int ret=1;
1408
1409         if (s->handshake_func == NULL)
1410                 {
1411                 SSLerr(SSL_F_SSL_DO_HANDSHAKE,SSL_R_CONNECTION_TYPE_NOT_SET);
1412                 return(-1);
1413                 }
1414
1415         s->method->ssl_renegotiate_check(s);
1416
1417         if (SSL_in_init(s) || SSL_in_before(s))
1418                 {
1419                 ret=s->handshake_func(s);
1420                 }
1421         return(ret);
1422         }
1423
1424 /* For the next 2 functions, SSL_clear() sets shutdown and so
1425  * one of these calls will reset it */
1426 void SSL_set_accept_state(SSL *s)
1427         {
1428         s->server=1;
1429         s->shutdown=0;
1430         s->state=SSL_ST_ACCEPT|SSL_ST_BEFORE;
1431         s->handshake_func=s->method->ssl_accept;
1432         /* clear the current cipher */
1433         ssl_clear_cipher_ctx(s);
1434         }
1435
1436 void SSL_set_connect_state(SSL *s)
1437         {
1438         s->server=0;
1439         s->shutdown=0;
1440         s->state=SSL_ST_CONNECT|SSL_ST_BEFORE;
1441         s->handshake_func=s->method->ssl_connect;
1442         /* clear the current cipher */
1443         ssl_clear_cipher_ctx(s);
1444         }
1445
1446 int ssl_undefined_function(SSL *s)
1447         {
1448         SSLerr(SSL_F_SSL_UNDEFINED_FUNCTION,ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1449         return(0);
1450         }
1451
1452 SSL_METHOD *ssl_bad_method(int ver)
1453         {
1454         SSLerr(SSL_F_SSL_BAD_METHOD,ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1455         return(NULL);
1456         }
1457
1458 char *SSL_get_version(SSL *s)
1459         {
1460         if (s->version == TLS1_VERSION)
1461                 return("TLSv1");
1462         else if (s->version == SSL3_VERSION)
1463                 return("SSLv3");
1464         else if (s->version == SSL2_VERSION)
1465                 return("SSLv2");
1466         else
1467                 return("unknown");
1468         }
1469
1470 SSL *SSL_dup(SSL *s)
1471         {
1472         STACK_OF(X509_NAME) *sk;
1473         X509_NAME *xn;
1474         SSL *ret;
1475         int i;
1476                  
1477         if ((ret=SSL_new(SSL_get_SSL_CTX(s))) == NULL)
1478             return(NULL);
1479                           
1480         /* This copies version, session-id, SSL_METHOD and 'cert' */
1481         SSL_copy_session_id(ret,s);
1482
1483         SSL_set_read_ahead(ret,SSL_get_read_ahead(s));
1484         SSL_set_verify(ret,SSL_get_verify_mode(s),
1485                 SSL_get_verify_callback(s));
1486         SSL_set_verify_depth(ret,SSL_get_verify_depth(s));
1487
1488         SSL_set_info_callback(ret,SSL_get_info_callback(s));
1489         
1490         ret->debug=s->debug;
1491         ret->options=s->options;
1492
1493         /* copy app data, a little dangerous perhaps */
1494         if (!CRYPTO_dup_ex_data(ssl_meth,&ret->ex_data,&s->ex_data))
1495                 goto err;
1496
1497         /* setup rbio, and wbio */
1498         if (s->rbio != NULL)
1499                 {
1500                 if (!BIO_dup_state(s->rbio,(char *)&ret->rbio))
1501                         goto err;
1502                 }
1503         if (s->wbio != NULL)
1504                 {
1505                 if (s->wbio != s->rbio)
1506                         {
1507                         if (!BIO_dup_state(s->wbio,(char *)&ret->wbio))
1508                                 goto err;
1509                         }
1510                 else
1511                         ret->wbio=ret->rbio;
1512                 }
1513
1514         /* dup the cipher_list and cipher_list_by_id stacks */
1515         if (s->cipher_list != NULL)
1516                 {
1517                 if ((ret->cipher_list=sk_SSL_CIPHER_dup(s->cipher_list)) == NULL)
1518                         goto err;
1519                 }
1520         if (s->cipher_list_by_id != NULL)
1521                 if ((ret->cipher_list_by_id=sk_SSL_CIPHER_dup(s->cipher_list_by_id))
1522                         == NULL)
1523                         goto err;
1524
1525         /* Dup the client_CA list */
1526         if (s->client_CA != NULL)
1527                 {
1528                 if ((sk=sk_X509_NAME_dup(s->client_CA)) == NULL) goto err;
1529                 ret->client_CA=sk;
1530                 for (i=0; i<sk_X509_NAME_num(sk); i++)
1531                         {
1532                         xn=sk_X509_NAME_value(sk,i);
1533                         if (sk_X509_NAME_set(sk,i,X509_NAME_dup(xn)) == NULL)
1534                                 {
1535                                 X509_NAME_free(xn);
1536                                 goto err;
1537                                 }
1538                         }
1539                 }
1540
1541         ret->shutdown=s->shutdown;
1542         ret->state=s->state;
1543         ret->handshake_func=s->handshake_func;
1544         ret->server=s->server;
1545
1546         if (0)
1547                 {
1548 err:
1549                 if (ret != NULL) SSL_free(ret);
1550                 ret=NULL;
1551                 }
1552         return(ret);
1553         }
1554
1555 void ssl_clear_cipher_ctx(SSL *s)
1556         {
1557         if (s->enc_read_ctx != NULL)
1558                 {
1559                 EVP_CIPHER_CTX_cleanup(s->enc_read_ctx);
1560                 Free(s->enc_read_ctx);
1561                 s->enc_read_ctx=NULL;
1562                 }
1563         if (s->enc_write_ctx != NULL)
1564                 {
1565                 EVP_CIPHER_CTX_cleanup(s->enc_write_ctx);
1566                 Free(s->enc_write_ctx);
1567                 s->enc_write_ctx=NULL;
1568                 }
1569         if (s->expand != NULL)
1570                 {
1571                 COMP_CTX_free(s->expand);
1572                 s->expand=NULL;
1573                 }
1574         if (s->compress != NULL)
1575                 {
1576                 COMP_CTX_free(s->compress);
1577                 s->compress=NULL;
1578                 }
1579         }
1580
1581 /* Fix this function so that it takes an optional type parameter */
1582 X509 *SSL_get_certificate(SSL *s)
1583         {
1584         if (s->cert != NULL)
1585                 return(s->cert->key->x509);
1586         else
1587                 return(NULL);
1588         }
1589
1590 /* Fix this function so that it takes an optional type parameter */
1591 EVP_PKEY *SSL_get_privatekey(SSL *s)
1592         {
1593         if (s->cert != NULL)
1594                 return(s->cert->key->privatekey);
1595         else
1596                 return(NULL);
1597         }
1598
1599 SSL_CIPHER *SSL_get_current_cipher(SSL *s)
1600         {
1601         if ((s->session != NULL) && (s->session->cipher != NULL))
1602                 return(s->session->cipher);
1603         return(NULL);
1604         }
1605
1606 int ssl_init_wbio_buffer(SSL *s,int push)
1607         {
1608         BIO *bbio;
1609
1610         if (s->bbio == NULL)
1611                 {
1612                 bbio=BIO_new(BIO_f_buffer());
1613                 if (bbio == NULL) return(0);
1614                 s->bbio=bbio;
1615                 }
1616         else
1617                 {
1618                 bbio=s->bbio;
1619                 if (s->bbio == s->wbio)
1620                         s->wbio=BIO_pop(s->wbio);
1621                 }
1622         BIO_reset(bbio);
1623 /*      if (!BIO_set_write_buffer_size(bbio,16*1024)) */
1624         if (!BIO_set_read_buffer_size(bbio,1))
1625                 {
1626                 SSLerr(SSL_F_SSL_INIT_WBIO_BUFFER,ERR_R_BUF_LIB);
1627                 return(0);
1628                 }
1629         if (push)
1630                 {
1631                 if (s->wbio != bbio)
1632                         s->wbio=BIO_push(bbio,s->wbio);
1633                 }
1634         else
1635                 {
1636                 if (s->wbio == bbio)
1637                         s->wbio=BIO_pop(bbio);
1638                 }
1639         return(1);
1640         }
1641
1642 void ssl_free_wbio_buffer(SSL *s)
1643         {
1644         BIO *under;
1645
1646         if (s->bbio == NULL) return;
1647
1648         if (s->bbio == s->wbio)
1649                 {
1650                 /* remove buffering */
1651                 under=BIO_pop(s->wbio);
1652                 if (under != NULL)
1653                         s->wbio=under;
1654                 else
1655                         abort(); /* ok */
1656                 }
1657         BIO_free(s->bbio);
1658         s->bbio=NULL;
1659         }
1660         
1661 void SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx,int mode)
1662         {
1663         ctx->quiet_shutdown=mode;
1664         }
1665
1666 int SSL_CTX_get_quiet_shutdown(SSL_CTX *ctx)
1667         {
1668         return(ctx->quiet_shutdown);
1669         }
1670
1671 void SSL_set_quiet_shutdown(SSL *s,int mode)
1672         {
1673         s->quiet_shutdown=mode;
1674         }
1675
1676 int SSL_get_quiet_shutdown(SSL *s)
1677         {
1678         return(s->quiet_shutdown);
1679         }
1680
1681 void SSL_set_shutdown(SSL *s,int mode)
1682         {
1683         s->shutdown=mode;
1684         }
1685
1686 int SSL_get_shutdown(SSL *s)
1687         {
1688         return(s->shutdown);
1689         }
1690
1691 int SSL_version(SSL *s)
1692         {
1693         return(s->version);
1694         }
1695
1696 SSL_CTX *SSL_get_SSL_CTX(SSL *ssl)
1697         {
1698         return(ssl->ctx);
1699         }
1700
1701 #ifndef NO_STDIO
1702 int SSL_CTX_set_default_verify_paths(SSL_CTX *ctx)
1703         {
1704         return(X509_STORE_set_default_paths(ctx->cert_store));
1705         }
1706
1707 int SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile,
1708                 const char *CApath)
1709         {
1710         return(X509_STORE_load_locations(ctx->cert_store,CAfile,CApath));
1711         }
1712 #endif
1713
1714 void SSL_set_info_callback(SSL *ssl,void (*cb)())
1715         {
1716         ssl->info_callback=cb;
1717         }
1718
1719 void (*SSL_get_info_callback(SSL *ssl))(void)
1720         {
1721         return((void (*)())ssl->info_callback);
1722         }
1723
1724 int SSL_state(SSL *ssl)
1725         {
1726         return(ssl->state);
1727         }
1728
1729 void SSL_set_verify_result(SSL *ssl,long arg)
1730         {
1731         ssl->verify_result=arg;
1732         }
1733
1734 long SSL_get_verify_result(SSL *ssl)
1735         {
1736         return(ssl->verify_result);
1737         }
1738
1739 int SSL_get_ex_new_index(long argl,char *argp,int (*new_func)(),
1740                          int (*dup_func)(),void (*free_func)())
1741         {
1742         ssl_meth_num++;
1743         return(CRYPTO_get_ex_new_index(ssl_meth_num-1,
1744                 &ssl_meth,argl,argp,new_func,dup_func,free_func));
1745         }
1746
1747 int SSL_set_ex_data(SSL *s,int idx,void *arg)
1748         {
1749         return(CRYPTO_set_ex_data(&s->ex_data,idx,arg));
1750         }
1751
1752 void *SSL_get_ex_data(SSL *s,int idx)
1753         {
1754         return(CRYPTO_get_ex_data(&s->ex_data,idx));
1755         }
1756
1757 int SSL_CTX_get_ex_new_index(long argl,char *argp,int (*new_func)(),
1758                              int (*dup_func)(),void (*free_func)())
1759         {
1760         ssl_ctx_meth_num++;
1761         return(CRYPTO_get_ex_new_index(ssl_ctx_meth_num-1,
1762                 &ssl_ctx_meth,argl,argp,new_func,dup_func,free_func));
1763         }
1764
1765 int SSL_CTX_set_ex_data(SSL_CTX *s,int idx,void *arg)
1766         {
1767         return(CRYPTO_set_ex_data(&s->ex_data,idx,arg));
1768         }
1769
1770 void *SSL_CTX_get_ex_data(SSL_CTX *s,int idx)
1771         {
1772         return(CRYPTO_get_ex_data(&s->ex_data,idx));
1773         }
1774
1775 int ssl_ok(SSL *s)
1776         {
1777         return(1);
1778         }
1779
1780 X509_STORE *SSL_CTX_get_cert_store(SSL_CTX *ctx)
1781         {
1782         return(ctx->cert_store);
1783         }
1784
1785 void SSL_CTX_set_cert_store(SSL_CTX *ctx,X509_STORE *store)
1786         {
1787         if (ctx->cert_store != NULL)
1788                 X509_STORE_free(ctx->cert_store);
1789         ctx->cert_store=store;
1790         }
1791
1792 int SSL_want(SSL *s)
1793         {
1794         return(s->rwstate);
1795         }
1796
1797 /*!
1798  * \brief Set the callback for generating temporary RSA keys.
1799  * \param ctx the SSL context.
1800  * \param cb the callback
1801  */
1802
1803 #ifndef NO_RSA
1804 void SSL_CTX_set_tmp_rsa_callback(SSL_CTX *ctx,RSA *(*cb)(SSL *ssl,int export,
1805                                                           int keylength))
1806     { SSL_CTX_ctrl(ctx,SSL_CTRL_SET_TMP_RSA_CB,0,(char *)cb); }
1807 #endif
1808
1809 #ifndef NO_RSA
1810 void SSL_set_tmp_rsa_callback(SSL *ssl,RSA *(*cb)(SSL *ssl,int export,
1811                                                           int keylength))
1812     { SSL_ctrl(ssl,SSL_CTRL_SET_TMP_RSA_CB,0,(char *)cb); }
1813 #endif
1814
1815 #ifdef DOXYGEN
1816 /*!
1817  * \brief The RSA temporary key callback function.
1818  * \param ssl the SSL session.
1819  * \param export \c TRUE if the temp RSA key is for an export ciphersuite.
1820  * \param keylength if \c export is \c TRUE, then \c keylength is the size of
1821  * the required key in bits.
1822  * \return the temporary RSA key.
1823  * \sa SSL_CTX_set_tmp_rsa_callback, SSL_set_tmp_rsa_callback
1824  */
1825
1826 RSA *cb(SSL *ssl,int export,int keylength)
1827     {}
1828 #endif
1829
1830 /*!
1831  * \brief Set the callback for generating temporary DH keys.
1832  * \param ctx the SSL context.
1833  * \param dh the callback
1834  */
1835
1836 #ifndef NO_DH
1837 void SSL_CTX_set_tmp_dh_callback(SSL_CTX *ctx,DH *(*dh)(SSL *ssl,int export,
1838                                                         int keylength))
1839     { SSL_CTX_ctrl(ctx,SSL_CTRL_SET_TMP_DH_CB,0,(char *)dh); }
1840
1841 void SSL_set_tmp_dh_callback(SSL *ssl,DH *(*dh)(SSL *ssl,int export,
1842                                                         int keylength))
1843     { SSL_ctrl(ssl,SSL_CTRL_SET_TMP_DH_CB,0,(char *)dh); }
1844 #endif
1845
1846 #if defined(_WINDLL) && defined(WIN16)
1847 #include "../crypto/bio/bss_file.c"
1848 #endif
1849
1850 IMPLEMENT_STACK_OF(SSL_CIPHER)
1851 IMPLEMENT_STACK_OF(SSL_COMP)