]> WPIA git - cassiopeia.git/blob - src/io/bios.h
b866264a3e802b0c64cdf6e05f1da369e311b00a
[cassiopeia.git] / src / io / bios.h
1 #pragma once
2
3 #include <openssl/bio.h>
4
5 struct bio_st {
6     const BIO_METHOD *method;
7     /* bio, mode, argp, argi, argl, ret */
8     long ( *callback )( struct bio_st *, int, const char *, int, long, long );
9     char *cb_arg;               /* first argument for the callback */
10     int init;
11     int shutdown;
12     int flags;                  /* extra storage */
13     int retry_reason;
14     int num;
15     void *ptr;
16     struct bio_st *next_bio;    /* used by filter BIOs */
17     struct bio_st *prev_bio;    /* used by filter BIOs */
18     int references;
19     uint64_t num_read;
20     uint64_t num_write;
21     CRYPTO_EX_DATA ex_data;
22     CRYPTO_RWLOCK *lock;
23 };
24
25
26 #define BIO_TYPE_CUSTOM 0xff
27
28 class OpensslBIO {
29 public:
30     static const int typeID = BIO_TYPE_CUSTOM;
31     virtual ~OpensslBIO();
32
33     virtual int write( const char *buf, int num ) = 0;
34     virtual int read( char *buf, int size ) = 0;
35     virtual int puts( const char *str );
36     virtual int gets( char *str, int size );
37     virtual long ctrl( int cmod, long arg1, void *arg2 ) = 0;
38 };
39
40 namespace BIOWrapper {
41
42     int write( BIO *b, const char *buf, int num );
43
44     int read( BIO *b, char *buf, int size );
45
46     int puts( BIO *b, const char *str );
47
48     int gets( BIO *b, char *str, int size );
49
50     long ctrl( BIO *b, int cmod, long arg1, void *arg2 );
51
52     template <typename T>
53     int bio_new( BIO *b ) {
54         b->init = 1;
55         b->num = 0;
56         b->ptr = new T();
57         return 1;
58     }
59
60     int free( BIO *b );
61
62 }
63
64 template <typename T>
65 BIO_METHOD *toBio() {
66     return toBio<T>( BIOWrapper::bio_new<T> );
67 }
68
69 template <typename T>
70 BIO_METHOD *toBio( int ( *newfunc )( BIO * ) ) {
71     BIO_METHOD *meth = BIO_meth_new( T::typeID, T::getName() );
72     BIO_meth_set_write( meth, BIOWrapper::write );
73     BIO_meth_set_read( meth, BIOWrapper::read );
74     BIO_meth_set_puts( meth, BIOWrapper::puts );
75     BIO_meth_set_gets( meth, BIOWrapper::gets );
76     BIO_meth_set_ctrl( meth, BIOWrapper::ctrl );
77     BIO_meth_set_destroy( meth, BIOWrapper::free );
78     BIO_meth_set_create( meth, newfunc );
79
80     return meth;
81 }