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