35 const int Result_ok = GSsl::Protocol::Result_ok ;
36 const int Result_more = GSsl::Protocol::Result_more ;
37 const int Result_read = GSsl::Protocol::Result_read ;
38 const int Result_write = GSsl::Protocol::Result_write ;
39 const int Result_error = GSsl::Protocol::Result_error ;
48 typedef std::pair<const char *,size_t> Segment ;
49 typedef std::vector<Segment> Segments ;
54 Position(
size_t segment_ ,
size_t offset_ ) : segment(segment_) , offset(offset_) {}
55 Position() : segment(0U) , offset(0U) {}
59 StreamSocket & ,
unsigned int secure_connection_timeout ) ;
63 void otherEvent( EventHandler::Reason ) ;
64 bool send(
const std::string & data ,
size_t offset ) ;
65 bool send(
const Segments & ) ;
66 void secureConnect() ;
68 std::string peerCertificate()
const ;
69 static void setReadBufferSize(
size_t ) ;
75 static void log(
int level ,
const std::string & line ) ;
78 bool rawWriteEvent() ;
79 void rawOtherEvent() ;
80 bool rawSend(
const Segments & ,
Position ,
bool =
false ) ;
83 bool sslSend(
const Segments & segments ,
Position pos ) ;
86 void secureConnectImp() ;
87 void secureAcceptImp() ;
88 void logSecure(
const std::string & )
const ;
89 void logCertificate(
const std::string & ,
const std::string & )
const ;
90 void logFlowControl(
const char * what ) ;
91 void onSecureConnectionTimeout() ;
92 static size_t size(
const Segments & ) ;
93 static bool finished(
const Segments & ,
Position ) ;
95 static const char * chunk_p(
const Segments & ,
Position ) ;
96 static size_t chunk_n(
const Segments & ,
Position ) ;
99 enum State { State_raw , State_connecting , State_accepting , State_writing , State_idle } ;
104 unsigned int m_secure_connection_timeout ;
105 Segments m_segments ;
106 Position m_position ;
107 std::string m_data_copy ;
111 std::vector<char> m_read_buffer ;
112 ssize_t m_read_buffer_n ;
114 std::string m_peer_certificate ;
115 static size_t m_read_buffer_size ;
120 std::ostream & operator<<( std::ostream & stream ,
const SocketProtocolImp::Position & pos )
122 return stream <<
"(" << pos.segment <<
"," << pos.offset <<
")" ;
124 std::ostream & operator<<( std::ostream & stream ,
const SocketProtocolImp::Segment & segment )
126 return stream <<
"(" << (
const void*)(segment.first) <<
":" << segment.second <<
")" ;
128 std::ostream & operator<<( std::ostream & stream ,
const SocketProtocolImp::Segments & segments )
131 const char * sep =
"" ;
132 for(
size_t i = 0U ; i < segments.size() ; i++ , sep =
"," )
133 stream << sep << segments.at(i) ;
139 size_t GNet::SocketProtocolImp::m_read_buffer_size = G::limits::net_buffer ;
141 GNet::SocketProtocolImp::SocketProtocolImp( EventHandler & handler , ExceptionHandler & eh ,
142 SocketProtocol::Sink & sink , StreamSocket & socket ,
143 unsigned int secure_connection_timeout ) :
148 m_secure_connection_timeout(secure_connection_timeout) ,
152 m_read_buffer(m_read_buffer_size) ,
154 m_secure_connection_timer(*this,&SocketProtocolImp::onSecureConnectionTimeout,eh)
156 G_ASSERT( m_read_buffer.size() == m_read_buffer_size ) ;
159 GNet::SocketProtocolImp::~SocketProtocolImp()
164 void GNet::SocketProtocolImp::setReadBufferSize(
size_t n )
166 m_read_buffer_size = n ;
167 if( m_read_buffer_size == 0U )
168 m_read_buffer_size = 1U ;
171 void GNet::SocketProtocolImp::onSecureConnectionTimeout()
173 G_DEBUG(
"GNet::SocketProtocolImp::onSecureConnectionTimeout: timed out" ) ;
174 throw SocketProtocol::SecureConnectionTimeout() ;
177 void GNet::SocketProtocolImp::readEvent()
179 G_DEBUG(
"SocketProtocolImp::readEvent: read event: " << m_socket.
asString() <<
": state=" << m_state ) ;
180 if( m_state == State_raw )
182 else if( m_state == State_connecting )
184 else if( m_state == State_accepting )
186 else if( m_state == State_writing )
192 bool GNet::SocketProtocolImp::writeEvent()
194 G_DEBUG(
"GNet::SocketProtocolImp::writeEvent: write event: " << m_socket.
asString() <<
": state=" << m_state ) ;
196 if( m_state == State_raw )
197 rc = rawWriteEvent() ;
198 else if( m_state == State_connecting )
200 else if( m_state == State_accepting )
202 else if( m_state == State_writing )
209 void GNet::SocketProtocolImp::otherEvent( EventHandler::Reason reason )
211 if( m_state == State_raw && reason == EventHandler::reason_closed && !
G::Test::enabled(
"socket-protocol-noflush") )
217 size_t GNet::SocketProtocolImp::size(
const Segments & segments )
220 for( Segments::const_iterator p = segments.begin() ; p != segments.end() ; ++p )
222 G_ASSERT( (*p).first !=
nullptr ) ;
223 G_ASSERT( (*p).second != 0U ) ;
231 G_ASSERT( pos.segment < s.size() ) ;
232 G_ASSERT( (pos.offset+offset) <= s.at(pos.segment).second ) ;
233 pos.offset += offset ;
234 if( pos.offset >= s.at(pos.segment).second )
242 const char * GNet::SocketProtocolImp::chunk_p(
const Segments & s , Position pos )
244 G_ASSERT( pos.segment < s.size() ) ;
245 G_ASSERT( pos.offset < s[pos.segment].second ) ;
247 const Segment & segment = s.at( pos.segment ) ;
248 return segment.first + pos.offset ;
251 size_t GNet::SocketProtocolImp::chunk_n(
const Segments & s , Position pos )
253 G_ASSERT( pos.segment < s.size() ) ;
254 G_ASSERT( pos.offset < s[pos.segment].second ) ;
256 const Segment & segment = s.at( pos.segment ) ;
257 return segment.second - pos.offset ;
260 bool GNet::SocketProtocolImp::send(
const std::string & data ,
size_t offset )
262 if( data.empty() || offset >= data.length() )
266 if( m_state == State_raw )
268 Segments segments( 1U ) ;
269 segments[0].first = data.data() ;
270 segments[0].second = data.size() ;
271 rc = rawSend( segments , Position(0U,offset) ,
true ) ;
273 else if( m_state == State_connecting || m_state == State_accepting )
275 throw SocketProtocol::SendError(
"still busy negotiating" ) ;
277 else if( m_state == State_writing )
279 throw SocketProtocol::SendError(
"still busy sending the last packet" ) ;
285 m_data_copy = data.substr( offset ) ;
287 Segments segments( 1U ) ;
288 segments[0].first = m_data_copy.data() ;
289 segments[0].second = m_data_copy.size() ;
290 rc = sslSend( segments , Position() ) ;
295 bool GNet::SocketProtocolImp::send(
const Segments & segments )
297 if( segments.empty() || size(segments) == 0U )
301 if( m_state == State_raw )
303 rc = rawSend( segments , Position() ) ;
305 else if( m_state == State_connecting || m_state == State_accepting )
307 throw SocketProtocol::SendError(
"still busy negotiating" ) ;
309 else if( m_state == State_writing )
311 throw SocketProtocol::SendError(
"still busy sending the last packet" ) ;
315 rc = sslSend( segments , Position() ) ;
320 void GNet::SocketProtocolImp::secureConnect()
322 G_DEBUG(
"SocketProtocolImp::secureConnect" ) ;
323 G_ASSERT( m_ssl ==
nullptr ) ;
325 m_ssl = newProtocol(
"client" ) ;
326 m_state = State_connecting ;
327 if( m_secure_connection_timeout != 0U )
328 m_secure_connection_timer.startTimer( m_secure_connection_timeout ) ;
332 void GNet::SocketProtocolImp::secureConnectImp()
334 G_DEBUG(
"SocketProtocolImp::secureConnectImp" ) ;
335 G_ASSERT( m_ssl !=
nullptr ) ;
336 G_ASSERT( m_state == State_connecting ) ;
338 GSsl::Protocol::Result rc = m_ssl->
connect( m_socket ) ;
340 if( rc == Result_error )
343 m_state = State_raw ;
344 throw SocketProtocol::ReadError(
"ssl connect" ) ;
346 else if( rc == Result_read )
350 else if( rc == Result_write )
357 m_state = State_idle ;
358 if( m_secure_connection_timeout != 0U )
359 m_secure_connection_timer.cancelTimer() ;
361 logSecure( m_peer_certificate ) ;
362 G_DEBUG(
"SocketProtocolImp::secureConnectImp: calling onSecure: " <<
G::Str::printable(m_peer_certificate) ) ;
363 m_sink.
onSecure( m_peer_certificate ) ;
367 void GNet::SocketProtocolImp::secureAccept()
369 G_DEBUG(
"SocketProtocolImp::secureAccept" ) ;
370 G_ASSERT( m_ssl ==
nullptr ) ;
372 m_ssl = newProtocol(
"server" ) ;
373 m_state = State_accepting ;
377 void GNet::SocketProtocolImp::secureAcceptImp()
379 G_DEBUG(
"SocketProtocolImp::secureAcceptImp" ) ;
380 G_ASSERT( m_ssl !=
nullptr ) ;
381 G_ASSERT( m_state == State_accepting ) ;
383 GSsl::Protocol::Result rc = m_ssl->
accept( m_socket ) ;
385 if( rc == Result_error )
388 m_state = State_raw ;
389 throw SocketProtocol::ReadError(
"ssl accept" ) ;
391 else if( rc == Result_read )
395 else if( rc == Result_write )
402 m_state = State_idle ;
404 logSecure( m_peer_certificate ) ;
405 G_DEBUG(
"SocketProtocolImp::secureAcceptImp: calling onSecure: " <<
G::Str::printable(m_peer_certificate) ) ;
406 m_sink.
onSecure( m_peer_certificate ) ;
410 bool GNet::SocketProtocolImp::sslSend(
const Segments & segments , Position pos )
412 if( !finished(m_segments,m_position) )
413 throw SocketProtocol::SendError(
"still busy sending the last packet" ) ;
415 G_ASSERT( m_state == State_idle ) ;
416 m_state = State_writing ;
419 bool all_sent = sslSendImp( segments , pos , pos_out ) ;
420 if( !all_sent && failed() )
423 m_position = Position() ;
424 throw SocketProtocol::SendError() ;
429 m_position = Position() ;
433 m_segments = segments ;
434 m_position = pos_out ;
439 bool GNet::SocketProtocolImp::sslSendImp()
441 return sslSendImp( m_segments , m_position , m_position ) ;
444 bool GNet::SocketProtocolImp::sslSendImp(
const Segments & segments , Position pos , Position & pos_out )
446 while( !finished(segments,pos) )
448 const char * chunk_data = chunk_p( segments , pos ) ;
449 size_t chunk_size = chunk_n( segments , pos ) ;
452 GSsl::Protocol::Result result = m_ssl->
write( chunk_data , chunk_size , nsent ) ;
453 if( result == Result_error )
456 m_state = State_idle ;
460 else if( result == Result_read )
465 else if( result == Result_write )
473 G_ASSERT( nsent >= 0 ) ;
474 pos_out = pos = newPosition( segments , pos , nsent >= 0 ? static_cast<size_t>(nsent) :
size_t(0U) ) ;
477 m_state = State_idle ;
481 void GNet::SocketProtocolImp::sslReadImp()
483 G_DEBUG(
"SocketProtocolImp::sslReadImp" ) ;
484 G_ASSERT( m_state == State_idle ) ;
485 G_ASSERT( m_ssl !=
nullptr ) ;
487 GSsl::Protocol::Result rc = GSsl::Protocol::Result_more ;
488 for(
int sanity = 0 ; rc == Result_more && sanity < 1000 ; sanity++ )
490 rc = m_ssl->
read( &m_read_buffer[0] , m_read_buffer.size() , m_read_buffer_n ) ;
492 if( rc == Result_error )
495 m_state = State_idle ;
496 throw SocketProtocol::ReadError(
"ssl read" ) ;
498 else if( rc == Result_read )
502 else if( rc == Result_write )
508 G_ASSERT( rc == GSsl::Protocol::Result_ok || rc == Result_more ) ;
509 G_ASSERT( m_read_buffer_n >= 0 ) ;
511 m_state = State_idle ;
512 size_t n =
static_cast<size_t>(m_read_buffer_n) ;
513 m_read_buffer_n = 0 ;
514 G_DEBUG(
"SocketProtocolImp::sslReadImp: calling onData(): " << n ) ;
515 if( n != 0U ) m_sink.
onData( &m_read_buffer[0] , n ) ;
517 if( rc == Result_more )
519 G_DEBUG(
"SocketProtocolImp::sslReadImp: more available to read" ) ;
524 void GNet::SocketProtocolImp::rawOtherEvent()
528 G_DEBUG(
"GNet::SocketProtocolImp::rawOtherEvent: clearing receive queue" ) ;
531 const ssize_t rc = m_socket.
read( &m_read_buffer[0] , m_read_buffer.size() ) ;
532 G_DEBUG_GROUP(
"io" ,
"GNet::SocketProtocolImp::rawOtherEvent: read " << m_socket.
asString() <<
": " << rc ) ;
536 throw SocketProtocol::ReadError( m_socket.
reason() ) ;
538 G_ASSERT( static_cast<size_t>(rc) <= m_read_buffer.size() ) ;
539 m_sink.
onData( &m_read_buffer[0] , static_cast<size_t>(rc) ) ;
543 void GNet::SocketProtocolImp::rawReadEvent()
545 const ssize_t rc = m_socket.
read( &m_read_buffer[0] , m_read_buffer.size() ) ;
546 G_DEBUG_GROUP(
"io" ,
"GNet::SocketProtocolImp::rawReadEvent: read " << m_socket.
asString() <<
": " << rc ) ;
548 if( rc == 0 || ( rc == -1 && !m_socket.
eWouldBlock() ) )
550 throw SocketProtocol::ReadError( m_socket.
reason() ) ;
554 G_ASSERT( static_cast<size_t>(rc) <= m_read_buffer.size() ) ;
555 m_sink.
onData( &m_read_buffer[0] , static_cast<size_t>(rc) ) ;
559 G_DEBUG(
"GNet::SocketProtocolImp::rawReadEvent: read event read nothing" ) ;
564 bool GNet::SocketProtocolImp::rawSend(
const Segments & segments , Position pos ,
bool do_copy )
566 G_ASSERT( !do_copy || segments.size() == 1U ) ;
568 if( !finished(m_segments,m_position) )
569 throw SocketProtocol::SendError(
"still busy sending the last packet" ) ;
572 bool all_sent = rawSendImp( segments , pos , pos_out ) ;
573 if( !all_sent && failed() )
576 m_position = Position() ;
577 m_data_copy.clear() ;
578 throw SocketProtocol::SendError() ;
583 m_position = Position() ;
584 m_data_copy.clear() ;
589 G_ASSERT( segments.size() == 1U ) ;
590 G_ASSERT( pos_out.offset < segments[0].second ) ;
591 m_segments = segments ;
592 m_data_copy.assign( segments[0].first+pos_out.offset , segments[0].second-pos_out.offset ) ;
593 m_segments[0].first = m_data_copy.data() ;
594 m_segments[0].second = m_data_copy.size() ;
595 m_position = Position() ;
598 logFlowControl(
"asserted" ) ;
603 m_segments = segments ;
604 m_data_copy.clear() ;
605 m_position = pos_out ;
608 logFlowControl(
"asserted" ) ;
613 bool GNet::SocketProtocolImp::rawWriteEvent()
616 logFlowControl(
"released" ) ;
617 bool all_sent = rawSendImp( m_segments , m_position , m_position ) ;
618 if( !all_sent && failed() )
621 m_position = Position() ;
622 m_data_copy.clear() ;
623 throw SocketProtocol::SendError() ;
628 m_position = Position() ;
629 m_data_copy.clear() ;
633 logFlowControl(
"reasserted" ) ;
639 bool GNet::SocketProtocolImp::rawSendImp(
const Segments & segments , Position pos , Position & pos_out )
641 while( !finished(segments,pos) )
643 const char * chunk_data = chunk_p( segments , pos ) ;
644 size_t chunk_size = chunk_n( segments , pos ) ;
646 ssize_t rc = m_socket.
write( chunk_data , chunk_size ) ;
647 G_DEBUG_GROUP(
"io" ,
"GNet::SocketProtocolImp::rawSendImp: write " << m_socket.
asString() <<
": " << rc ) ;
651 pos_out = Position() ;
655 else if( rc < 0 || static_cast<size_t>(rc) < chunk_size )
658 size_t nsent = rc > 0 ?
static_cast<size_t>(rc) : 0U ;
659 pos_out = newPosition( segments , pos , nsent ) ;
660 G_ASSERT( !finished(segments,pos_out) ) ;
665 pos = newPosition( segments , pos , static_cast<size_t>(rc) ) ;
671 GSsl::Protocol * GNet::SocketProtocolImp::newProtocol(
const std::string & profile_name )
674 if( library ==
nullptr )
675 throw G::Exception(
"SocketProtocolImp::newProtocol: no tls library available" ) ;
680 bool GNet::SocketProtocolImp::finished(
const Segments & segments , Position pos )
682 return pos.segment == segments.size() ;
685 bool GNet::SocketProtocolImp::failed()
const
690 std::string GNet::SocketProtocolImp::peerCertificate()
const
692 return m_peer_certificate ;
695 void GNet::SocketProtocolImp::log(
int level ,
const std::string & log_line )
698 G_DEBUG(
"GNet::SocketProtocolImp::log: tls: " << log_line ) ;
699 else if( level == 2 )
700 G_LOG(
"GNet::SocketProtocolImp::log: tls: " << log_line ) ;
702 G_WARNING(
"GNet::SocketProtocolImp::log: tls: " << log_line ) ;
705 void GNet::SocketProtocolImp::logSecure(
const std::string & certificate )
const
707 std::pair<std::string,bool> rc( std::string() ,
false ) ;
711 logCertificate( rc.first , certificate ) ;
713 G_LOG(
"GNet::SocketProtocolImp: tls/ssl protocol established with "
715 << (rc.first.empty()?
"":
" certificate ") << rc.first ) ;
718 void GNet::SocketProtocolImp::logCertificate(
const std::string & certid ,
const std::string & certificate )
const
721 lines.reserve( 30U ) ;
723 for( G::StringArray::iterator line_p = lines.begin() ; line_p != lines.end() ; ++line_p )
725 if( !(*line_p).empty() )
727 G_LOG(
"GNet::SocketProtocolImp: certificate " << certid <<
": " << *line_p ) ;
732 void GNet::SocketProtocolImp::logFlowControl(
const char * what )
734 G_LOG_GROUP(
"flow-control" ,
"GNet::SocketProtocolImp::send: flow control " << what <<
": " << m_socket.
asString() ) ;
740 Sink & sink ,
StreamSocket & socket ,
unsigned int secure_connection_timeout ) :
757 return m_imp->writeEvent() ;
762 m_imp->otherEvent( reason ) ;
767 return m_imp->send( data , offset ) ;
772 return m_imp->send( data ) ;
782 m_imp->secureConnect() ;
792 m_imp->secureAccept() ;
797 return m_imp->peerCertificate() ;
802 SocketProtocolImp::setReadBufferSize( n ) ;
static Library * instance()
Returns a pointer to a library object, if any.
An interface to an underlying TLS library.
void shutdown(int how=1)
Modifies the local socket state so that so that new sends (1 or 2) and/or receives (0 or 2) will fail...
std::string reason() const
Returns the reason for the previous error.
static std::string printable(const std::string &in, char escape= '\\')
Returns a printable represention of the given input string.
void readEvent()
Called on receipt of a read event.
virtual ssize_type read(char *buffer, size_type buffer_length) override
Override from Socket::read().
void otherEvent(EventHandler::Reason)
Called on receipt of an 'other' event.
virtual void onData(const char *, size_t)=0
Called when data is read from the socket.
std::vector< std::string > StringArray
A std::vector of std::strings.
static bool enabledAs(const std::string &profile_name)
A static convenience function that returns true if there is an enabled() Library instance() that has ...
static std::string str(Result result)
Converts a result enumeration into a printable string.
virtual ~SocketProtocolSink()
Destructor.
virtual void onSecure(const std::string &peer_certificate)=0
Called once the secure socket protocol has been successfully negotiated.
A pimple-pattern implementation class used by GNet::SocketProtocol.
void dropWriteHandler()
Reverses addWriteHandler().
An abstract interface for handling exceptions thrown out of event-loop callbacks (socket events...
std::pair< bool, Address > getPeerAddress() const
Retrieves address of socket's peer.
std::string peerCertificate() const
Returns the peer's TLS/SSL certificate or the empty string.
A derivation of GNet::Socket for a stream socket.
~SocketProtocol()
Destructor.
static bool enabled()
Returns true if test features are enabled.
void secureAccept()
Waits for the TLS/SSL handshake protocol, acting as a server.
Result read(char *buffer, size_t buffer_size_in, ssize_t &data_size_out)
Reads user data into the supplied buffer.
Result accept(G::ReadWrite &io)
Starts the protocol passively (as a server).
static Monitor * instance()
Returns the singleton pointer. Returns null if none.
Result connect(G::ReadWrite &io)
Starts the protocol actively (as a client).
bool send(const std::string &data, size_t offset=0U)
Sends data.
const Profile & profile(const std::string &profile_name) const
Returns an opaque reference to the named profile.
A base class for classes that handle asynchronous events from the event loop.
std::string peerCertificate() const
Returns the peer certificate in PEM format.
static std::string str(Reason)
Returns a printable description of the other-event reason.
void addWriteHandler(EventHandler &, ExceptionHandler &)
Adds this socket to the event source list so that the given handler receives write events when flow c...
virtual ssize_type write(const char *buf, size_type len) override
Override from Socket::write().
A pointer into the scatter/gather payload of GNet::SocketProtocolImp::send().
Result write(const char *buffer, size_t data_size_in, ssize_t &data_size_out)
Writes user data.
static bool secureAcceptCapable()
Returns true if the implementation supports TLS/SSL and a "server" profile has been configured...
A general-purpose exception class derived from std::exception and containing a std::string.
void secureConnect()
Initiates the TLS/SSL handshake, acting as a client.
std::pair< std::string, bool > findCertificate(const std::string &certificate)
Returns a short id for the given certificate and a boolean flag to indicate if it is a new certificat...
A singleton class for initialising the underlying TLS library.
SocketProtocol(EventHandler &, ExceptionHandler &, Sink &, StreamSocket &, unsigned int secure_connection_timeout)
Constructor. The references are kept.
A timer class template in which the timeout is delivered to the specified method. ...
static bool secureConnectCapable()
Returns true if the implementation supports TLS/SSL and a "client" profile has been configured...
virtual bool eWouldBlock() override
Returns true if the previous socket operation failed because the socket would have blocked...
An interface used by GNet::SocketProtocol to deliver data from a socket.
static void splitIntoFields(const std::string &in, StringArray &out, const std::string &separators, char escape= '\0', bool remove_escapes=true)
Splits the string into fields.
static void setReadBufferSize(size_t n)
Sets the read buffer size. Used in testing.
bool writeEvent()
Called on receipt of a write event.
std::string asString() const
Returns the socket handle as a string.