IBR-DTNSuite  0.8
ibrcommon/ibrcommon/net/TLSStream.h
Go to the documentation of this file.
00001 /*
00002  * TLSStream.h
00003  *
00004  *  Created on: Mar 24, 2011
00005  *      Author: roettger
00006  */
00007 
00008 #ifndef TLSSTREAM_H_
00009 #define TLSSTREAM_H_
00010 
00011 #include <streambuf>
00012 #include <iostream>
00013 #include <memory>
00014 #include <openssl/ssl.h>
00015 #include "ibrcommon/thread/Mutex.h"
00016 #include "ibrcommon/data/File.h"
00017 #include "ibrcommon/net/iostreamBIO.h"
00018 
00019 namespace ibrcommon
00020 {
00027         class TLSStream : public std::basic_streambuf<char, std::char_traits<char> >, public std::iostream
00028         {
00029         public:
00030                 typedef std::char_traits<char> traits;
00031 
00037                 TLSStream(std::iostream *stream);
00041                 virtual ~TLSStream();
00042 
00047                 void setServer(bool val);
00048 
00061             static void init(X509 *certificate, EVP_PKEY *privateKey, ibrcommon::File trustedCAPath, bool enableEncryption = false);
00062 
00066             static void flushInitialization();
00067 
00072             static bool isInitialized();
00073 
00078             void close();
00079 
00081                 static const size_t BUFF_SIZE = 5120;
00082 
00087                 X509 *activate();
00088 
00089         protected:
00090                 virtual int sync();
00091                 virtual traits::int_type overflow(traits::int_type = traits::eof());
00092                 virtual traits::int_type underflow();
00093 
00094         private:
00095                 std::string log_error_msg(int errnumber);
00096                 void log_error(std::string tag, int errnumber);
00097                 void log_debug(std::string tag, int errnumber);
00098 
00099                 static bool _initialized;
00100                 /* this second initialized variable is needed, because init() can fail and SSL_library_init() is not reentrant. */
00101                 static bool _SSL_initialized;
00102                 static ibrcommon::Mutex _initialization_lock;
00103 
00104                 bool _activated;
00105                 ibrcommon::Mutex _activation_lock;
00106 
00107                 // Input buffer
00108                 char *in_buf_;
00109                 // Output buffer
00110                 char *out_buf_;
00111 
00112                 std::iostream *_stream;
00113                 /* indicates if this node is the server in the underlying tcp connection */
00114                 bool _server;
00115 
00116                 static SSL_CTX *_ssl_ctx;
00117                 SSL *_ssl;
00118                 X509 *_peer_cert;
00119                 iostreamBIO *_iostreamBIO;
00120         };
00121 }
00122 
00123 #endif /* TLSSTREAM_H_ */