SSLConnection.cc
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033 #include <openssl/ssl.h>
00034 #include <openssl/err.h>
00035 #include <sys/socket.h>
00036 #include <netinet/in.h>
00037 #include <arpa/inet.h>
00038 #include <netdb.h>
00039
00040 #include <iostream>
00041
00042 using std::flush ;
00043
00044 #include "SSLConnection.h"
00045 #include "BESInternalError.h"
00046
00047 SSLConnection::SSLConnection( )
00048 : _method( NULL ),
00049 _context( NULL ),
00050 _connection( NULL ),
00051 _connected( false )
00052 {
00053 }
00054
00055 SSLConnection::~SSLConnection()
00056 {
00057 }
00058
00059 void
00060 SSLConnection::closeConnection()
00061 {
00062 if( _connected && _connection )
00063 {
00064 if( SSL_shutdown( _connection ) == 0 )
00065 {
00066 SSL_shutdown( _connection ) ;
00067 }
00068 }
00069 SSL_clear( _connection ) ;
00070
00071 if( _context ) SSL_CTX_free( _context ) ; _context = NULL ;
00072 _connected = false ;
00073
00074 SSL_free( _connection ) ;
00075 _connection = NULL ;
00076 }
00077
00078 void
00079 SSLConnection::send( const string &buf )
00080 {
00081 if( _connected )
00082 {
00083 int len = SSL_write( _connection, (void *)buf.c_str(), buf.length() ) ;
00084 if( len <= 0 )
00085 {
00086 string msg = "FAILED to write to SSL connection\n" ;
00087 msg += ERR_error_string( ERR_get_error(), NULL ) ;
00088 throw BESInternalError( msg, __FILE__, __LINE__ ) ;
00089 }
00090 }
00091 }
00092
00093 int
00094 SSLConnection::receive( char *buffer, unsigned int buffer_size )
00095 {
00096 bool isDone = false ;
00097 if( _connected )
00098 {
00099 int retlen = SSL_read( _connection, (void *)buffer, buffer_size ) ;
00100 if( retlen <= 0 )
00101 {
00102 if( retlen == 0 )
00103 {
00104 isDone = true ;
00105 }
00106 else
00107 {
00108 string msg = "FAILED to read from SSL connection\n" ;
00109 msg += ERR_error_string( ERR_get_error(), NULL ) ;
00110 throw BESInternalError( msg, __FILE__, __LINE__ ) ;
00111 }
00112 }
00113 else
00114 {
00115 if( retlen > buffer_size ) retlen = buffer_size ;
00116 buffer[retlen] = '\0' ;
00117 }
00118 }
00119
00120 return isDone ;
00121 }
00122
00129 void
00130 SSLConnection::dump( ostream &strm ) const
00131 {
00132 strm << BESIndent::LMarg << "SSLConnection::dump - ("
00133 << (void *)this << ")" << endl ;
00134 BESIndent::Indent() ;
00135 strm << BESIndent::LMarg << "ssl method: " << (void *)_method << endl ;
00136 strm << BESIndent::LMarg << "ssl context: " << (void *)_context << endl ;
00137 strm << BESIndent::LMarg << "ssl connection: " << (void *)_connection << endl ;
00138 strm << BESIndent::LMarg << "is connected? " << (void *)_connected << endl ;
00139 Connection::dump( strm ) ;
00140 BESIndent::UnIndent() ;
00141 }
00142