IBR-DTNSuite  0.10
TLSStream.h
Go to the documentation of this file.
1 /*
2  * TLSStream.h
3  *
4  * Copyright (C) 2011 IBR, TU Braunschweig
5  *
6  * Written-by: Stephen Roettger <roettger@ibr.cs.tu-bs.de>
7  *
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  */
21 
22 #ifndef TLSSTREAM_H_
23 #define TLSSTREAM_H_
24 
25 #include <streambuf>
26 #include <iostream>
27 #include <memory>
28 #include <vector>
29 #include <openssl/ssl.h>
30 #include "ibrcommon/thread/Mutex.h"
31 #include "ibrcommon/data/File.h"
33 
34 namespace ibrcommon
35 {
42  class TLSStream : public std::basic_streambuf<char, std::char_traits<char> >, public std::iostream
43  {
44  static const std::string TAG;
45 
46  public:
47  typedef std::char_traits<char> traits;
48 
54  TLSStream(std::iostream *stream);
58  virtual ~TLSStream();
59 
64  void setServer(bool val);
65 
78  static void init(X509 *certificate, EVP_PKEY *privateKey, ibrcommon::File trustedCAPath, bool enableEncryption = false);
79 
83  static void flushInitialization();
84 
89  static bool isInitialized();
90 
95  void close();
96 
98  static const size_t BUFF_SIZE = 5120;
99 
104  X509 *activate();
105 
106  protected:
107  virtual int sync();
108  virtual traits::int_type overflow(traits::int_type = traits::eof());
109  virtual traits::int_type underflow();
110 
111  private:
112  std::string log_error_msg(int errnumber);
113 
114  static bool _initialized;
115  /* this second initialized variable is needed, because init() can fail and SSL_library_init() is not reentrant. */
116  static bool _SSL_initialized;
117  static ibrcommon::Mutex _initialization_lock;
118 
119  bool _activated;
120  ibrcommon::Mutex _activation_lock;
121 
122  // Input buffer
123  std::vector<char> in_buf_;
124  // Output buffer
125  std::vector<char> out_buf_;
126 
127  std::iostream *_stream;
128  /* indicates if this node is the server in the underlying tcp connection */
129  bool _server;
130 
131  static SSL_CTX *_ssl_ctx;
132  SSL *_ssl;
133  X509 *_peer_cert;
134  iostreamBIO *_iostreamBIO;
135  };
136 }
137 
138 #endif /* TLSSTREAM_H_ */