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 "PPTException.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 PPTException( msg ) ;
00089 }
00090 }
00091 }
00092
00093 bool
00094 SSLConnection::receive( ostream *strm )
00095 {
00096 bool isDone = false ;
00097 if( _connected )
00098 {
00099 char retbuf[1025] ;
00100 int retlen = SSL_read( _connection, (void *)retbuf, 1024 ) ;
00101 if( retlen <= 0 )
00102 {
00103 if( retlen == 0 )
00104 {
00105 isDone = true ;
00106 }
00107 else
00108 {
00109 string msg = "FAILED to read from SSL connection\n" ;
00110 msg += ERR_error_string( ERR_get_error(), NULL ) ;
00111 throw PPTException( msg ) ;
00112 }
00113 }
00114 else
00115 {
00116 if( retlen > 1024 ) retlen = 1024 ;
00117 retbuf[retlen] = '\0' ;
00118 *strm << retbuf << flush ;
00119 }
00120 }
00121
00122 return isDone ;
00123 }
00124
00131 void
00132 SSLConnection::dump( ostream &strm ) const
00133 {
00134 strm << BESIndent::LMarg << "SSLConnection::dump - ("
00135 << (void *)this << ")" << endl ;
00136 BESIndent::Indent() ;
00137 strm << BESIndent::LMarg << "ssl method: " << (void *)_method << endl ;
00138 strm << BESIndent::LMarg << "ssl context: " << (void *)_context << endl ;
00139 strm << BESIndent::LMarg << "ssl connection: " << (void *)_connection << endl ;
00140 strm << BESIndent::LMarg << "is connected? " << (void *)_connected << endl ;
00141 Connection::dump( strm ) ;
00142 BESIndent::UnIndent() ;
00143 }
00144