E-MailRelay

gclient.cpp
Go to the documentation of this file.
1//
2// Copyright (C) 2001-2024 Graeme Walker <graeme_walker@users.sourceforge.net>
3//
4// This program is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// This program is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with this program. If not, see <http://www.gnu.org/licenses/>.
16// ===
17///
18/// \file gclient.cpp
19///
20
21#include "gdef.h"
22#include "gaddress.h"
23#include "gsocket.h"
24#include "gdatetime.h"
25#include "gexception.h"
26#include "gresolver.h"
27#include "groot.h"
28#include "gmonitor.h"
29#include "gclient.h"
30#include "gassert.h"
31#include "gtest.h"
32#include "glog.h"
33#include <numeric>
34#include <sstream>
35#include <cstdlib>
36
37 GNet::Client::Client( EventState es , const Location & remote , const Config & config ) :
38 m_es(es) ,
39 m_config(config) ,
40 m_line_buffer(config.line_buffer_config) ,
41 m_remote_location(remote) ,
42 m_start_timer(*this,&GNet::Client::onStartTimeout,es) ,
43 m_connect_timer(*this,&GNet::Client::onConnectTimeout,es) ,
44 m_connected_timer(*this,&GNet::Client::onConnectedTimeout,es) ,
45 m_response_timer(*this,&GNet::Client::onResponseTimeout,es) ,
46 m_idle_timer(*this,&GNet::Client::onIdleTimeout,es)
47{
48 G_DEBUG( "Client::ctor" ) ;
49 if( m_config.auto_start )
50 m_start_timer.startTimer( 0U ) ;
51 Monitor::addClient( *this ) ;
52}
53
54 GNet::Client::~Client()
55{
56 Monitor::removeClient( *this ) ;
57}
58
59#ifndef G_LIB_SMALL
60 void GNet::Client::disconnect()
61{
62 G_DEBUG( "GNet::Client::disconnect" ) ;
63
64 m_start_timer.cancelTimer() ;
65 m_connect_timer.cancelTimer() ;
66 m_connected_timer.cancelTimer() ;
67 m_response_timer.cancelTimer() ;
68 m_idle_timer.cancelTimer() ;
69
70 m_state = State::Disconnected ;
71 m_finished = true ;
72
73 m_sp.reset() ;
74 m_socket.reset() ;
75 m_resolver.reset() ;
76}
77#endif
78
79 G::Slot::Signal<const std::string&,const std::string&,const std::string&> & GNet::Client::eventSignal() noexcept
80{
81 return m_event_signal ;
82}
83
84 GNet::Location GNet::Client::remoteLocation() const
85{
86 return m_remote_location ;
87}
88
89 GNet::StreamSocket & GNet::Client::socket()
90{
91 if( m_socket == nullptr )
92 throw NotConnected() ;
93 return *m_socket ;
94}
95
96 const GNet::StreamSocket & GNet::Client::socket() const
97{
98 if( m_socket == nullptr )
99 throw NotConnected() ;
100 return *m_socket ;
101}
102
103 void GNet::Client::clearInput()
104{
105 m_line_buffer.clear() ;
106 m_response_timer.cancelTimer() ;
107}
108
109 void GNet::Client::onStartTimeout()
110{
111 G_DEBUG( "GNet::Client::onStartTimeout: auto-start connecting" ) ;
112 connect() ;
113}
114
115 void GNet::Client::connect()
116{
117 G_DEBUG( "GNet::Client::connect: [" << m_remote_location.displayString() << "] "
118 << "(" << static_cast<int>(m_state) << ")" ) ;
119 if( m_state != State::Idle )
120 throw ConnectError( "wrong state" ) ;
121
122 // (one timer covers dns resolution and socket connection)
123 if( m_config.connection_timeout )
124 m_connect_timer.startTimer( m_config.connection_timeout ) ;
125
126 m_remote_location.resolveTrivially() ; // if host:service is already address:port
127 if( m_remote_location.resolved() )
128 {
129 setState( State::Connecting ) ;
130 startConnecting() ;
131 }
132 else if( m_config.sync_dns || !Resolver::async() )
133 {
134 std::string error = Resolver::resolve( m_remote_location ) ;
135 if( !error.empty() )
136 throw DnsError( error ) ;
137
138 setState( State::Connecting ) ;
139 startConnecting() ;
140 }
141 else
142 {
143 setState( State::Resolving ) ;
144 if( m_resolver == nullptr )
145 {
146 Resolver::Callback & resolver_callback = *this ;
147 m_resolver = std::make_unique<Resolver>( resolver_callback , m_es ) ;
148 }
149 m_resolver->start( m_remote_location ) ;
150 emit( "resolving" ) ;
151 }
152}
153
154 void GNet::Client::onResolved( std::string error , Location location )
155{
156 if( !error.empty() )
157 throw DnsError( error ) ;
158
159 G_DEBUG( "GNet::Client::onResolved: " << location.displayString() ) ;
160 m_remote_location.update( location.address() ) ;
161 setState( State::Connecting ) ;
162 startConnecting() ;
163}
164
165 void GNet::Client::startConnecting()
166{
167 G_DEBUG( "GNet::Client::startConnecting: local: " << m_config.local_address.displayString() ) ;
168 G_DEBUG( "GNet::Client::startConnecting: remote: " << m_remote_location.displayString() ) ;
169 if( G::Test::enabled("client-slow-connect") )
170 setState( State::Testing ) ;
171
172 // create and open a socket
173 //
174 m_sp.reset() ;
175 m_socket = std::make_unique<StreamSocket>( m_remote_location.address().family() , m_config.stream_socket_config ) ;
176 socket().addWriteHandler( *this , m_es ) ;
177 socket().addOtherHandler( *this , m_es ) ;
178
179 // create a socket protocol object
180 //
181 EventHandler & eh = *this ;
182 SocketProtocolSink & sp_sink = *this ;
183 m_sp = std::make_unique<SocketProtocol>( eh , m_es , sp_sink , *m_socket , m_config.socket_protocol_config ) ;
184
185 // bind a local address to the socket (throws on failure)
186 //
187 if( m_config.bind_local_address )
188 bindLocalAddress( m_config.local_address ) ;
189
190 // start connecting
191 //
192 bool immediate = false ;
193 if( !socket().connect( m_remote_location.address() , &immediate ) )
194 throw ConnectError( "cannot connect to " + m_remote_location.address().displayString() + ": " + socket().reason() ) ;
195
196 // deal with immediate connection (typically if connecting locally)
197 //
198 if( immediate )
199 {
200 socket().dropWriteHandler() ;
201 m_connected_timer.startTimer( 0U ) ; // -> onConnectedTimeout()
202 }
203 else
204 {
205 emit( "connecting" ) ;
206 }
207}
208
209 void GNet::Client::finish()
210{
211 m_finished = true ;
212 if( m_sp != nullptr )
213 {
214 m_sp->shutdown() ;
215 }
216 else if( m_socket != nullptr )
217 {
218 m_socket->dropWriteHandler() ;
219 m_socket->shutdown() ;
220 }
221}
222
223 bool GNet::Client::finished() const
224{
225 return m_finished ;
226}
227
228 bool GNet::Client::hasConnected() const
229{
230 return m_has_connected ;
231}
232
233 void GNet::Client::doOnDelete( const std::string & reason , bool done )
234{
235 onDelete( (done||m_finished) ? std::string() : reason ) ;
236}
237
238 void GNet::Client::emit( const std::string & action )
239{
240 m_event_signal.emit( std::string(action) , m_remote_location.displayString() , std::string() ) ;
241}
242
243 void GNet::Client::onConnectTimeout()
244{
245 std::ostringstream ss ;
246 ss << "cannot connect to " << m_remote_location << ": timed out out after " << m_config.connection_timeout << "s" ;
247 G_DEBUG( "GNet::Client::onConnectTimeout: " << ss.str() ) ;
248 throw ConnectError( ss.str() ) ;
249}
250
251 void GNet::Client::onResponseTimeout()
252{
253 std::ostringstream ss ;
254 ss << "no response after " << m_config.response_timeout << "s while connected to " << m_remote_location ;
255 G_DEBUG( "GNet::Client::onResponseTimeout: response timeout: " << ss.str() ) ;
256 throw ResponseTimeout( ss.str() ) ;
257}
258
259 void GNet::Client::onIdleTimeout()
260{
261 std::ostringstream ss ;
262 ss << "no activity after " << m_config.idle_timeout << "s while connected to " << m_remote_location ;
263 throw IdleTimeout( ss.str() ) ;
264}
265
266 void GNet::Client::onConnectedTimeout()
267{
268 G_DEBUG( "GNet::Client::onConnectedTimeout: immediate connection" ) ;
269 onWriteable() ;
270}
271
272 void GNet::Client::writeEvent()
273{
274 G_DEBUG( "GNet::Client::writeEvent" ) ;
275 onWriteable() ;
276}
277
278 void GNet::Client::onWriteable()
279{
280 bool has_peer = m_state == State::Connecting && socket().getPeerAddress().first ;
281 if( m_state == State::Connected )
282 {
283 if( m_sp->writeEvent() )
284 onSendComplete() ;
285 }
286 else if( m_state == State::Testing )
287 {
288 socket().dropWriteHandler() ;
289 setState( State::Connecting ) ;
290 m_connected_timer.startTimer( 2U , 100000U ) ; // -> onConnectedTimeout()
291 }
292 else if( m_state == State::Connecting && has_peer && m_remote_location.socks() )
293 {
294 setState( State::Socksing ) ;
295 m_socks = std::make_unique<Socks>( m_remote_location ) ;
296 if( m_socks->send( socket() ) )
297 {
298 socket().dropWriteHandler() ;
299 socket().addReadHandler( *this , m_es ) ; // wait for the socks response
300 }
301 else
302 {
303 socket().addWriteHandler( *this , m_es ) ;
304 socket().dropReadHandler() ;
305 }
306 }
307 else if( m_state == State::Connecting && has_peer )
308 {
309 socket().dropWriteHandler() ;
310 socket().addReadHandler( *this , m_es ) ;
311
312 setState( State::Connected ) ;
313 doOnConnect() ;
314 }
315 else if( m_state == State::Connecting )
316 {
317 socket().dropWriteHandler() ;
318 throw ConnectError( "cannot connect to " + m_remote_location.address().displayString() ) ;
319 }
320 else if( m_state == State::Socksing )
321 {
322 G_ASSERT( m_socks != nullptr ) ;
323 if( m_socks->send( socket() ) )
324 {
325 socket().dropWriteHandler() ;
326 socket().addReadHandler( *this , m_es ) ;
327
328 setState( State::Connected ) ;
329 doOnConnect() ;
330 }
331 }
332 else if( m_state == State::Disconnected )
333 {
334 // never gets here
335 }
336}
337
338 void GNet::Client::doOnConnect()
339{
340 G::CallFrame this_( m_call_stack ) ;
341 onConnect() ;
342 if( this_.deleted() ) return ;
343 emit( "connected" ) ;
344}
345
346 void GNet::Client::otherEvent( EventHandler::Reason reason )
347{
348 if( m_state == State::Socksing || m_sp == nullptr )
349 EventHandler::otherEvent( reason ) ; // default implementation throws
350 else
351 m_sp->otherEvent( reason , m_config.no_throw_on_peer_disconnect ) ;
352}
353
354 void GNet::Client::readEvent()
355{
356 if( m_state == State::Socksing )
357 {
358 G_ASSERT( m_socks != nullptr ) ;
359 bool complete = m_socks->read( socket() ) ;
360 if( complete )
361 {
362 setState( State::Connected ) ;
363 doOnConnect() ;
364 }
365 }
366 else
367 {
368 G_ASSERT( m_sp != nullptr ) ;
369 if( m_sp->readEvent( m_config.no_throw_on_peer_disconnect ) )
370 onSendComplete() ;
371 }
372}
373
374 void GNet::Client::onData( const char * data , std::size_t size )
375{
376 if( m_config.response_timeout && m_line_buffer.transparent() ) // anything will do if transparent
377 m_response_timer.cancelTimer() ;
378
379 if( m_config.idle_timeout )
380 m_idle_timer.startTimer( m_config.idle_timeout ) ;
381
382 bool fragments = m_line_buffer.transparent() ;
383 m_line_buffer.apply( this , &Client::onDataImp , data , size , fragments ) ;
384}
385
386 bool GNet::Client::onDataImp( const char * data , std::size_t size , std::size_t eolsize ,
387 std::size_t linesize , char c0 )
388{
389 if( m_config.response_timeout && eolsize ) // end of a complete line
390 m_response_timer.cancelTimer() ;
391
392 return onReceive( data , size , eolsize , linesize , c0 ) ;
393}
394
395 bool GNet::Client::connected() const
396{
397 return m_state == State::Connected ;
398}
399
400 void GNet::Client::bindLocalAddress( const Address & local_address )
401{
402 {
403 G::Root claim_root ;
404 socket().bind( local_address ) ;
405 }
406
407 if( local_address.isLoopback() && !m_remote_location.address().isLoopback() )
408 G_WARNING_ONCE( "GNet::Client::bindLocalAddress: binding the loopback address for "
409 "outgoing connections may result in connection failures" ) ;
410}
411
412 void GNet::Client::setState( State new_state )
413{
414 if( new_state != State::Connecting && new_state != State::Resolving )
415 m_connect_timer.cancelTimer() ;
416
417 if( new_state == State::Connected )
418 m_has_connected = true ;
419
420 if( new_state == State::Connected && m_config.idle_timeout )
421 m_idle_timer.startTimer( m_config.idle_timeout ) ;
422
423 m_state = new_state ;
424}
425
426 GNet::Address GNet::Client::localAddress() const
427{
428 return socket().getLocalAddress() ;
429}
430
431 GNet::Address GNet::Client::peerAddress() const
432{
433 if( m_state != State::Connected )
434 throw NotConnected() ;
435
436 auto pair = socket().getPeerAddress() ;
437 if( !pair.first )
438 throw NotConnected() ;
439
440 return pair.second ;
441}
442
443std::string GNet::Client::peerAddressString( bool with_port ) const
444{
445 if( m_state == State::Connected )
446 {
447 auto pair = socket().getPeerAddress() ;
448 if( pair.first && with_port )
449 return pair.second.displayString() ;
450 else if( pair.first )
451 return pair.second.hostPartString() ;
452 }
453 return {} ;
454}
455
456std::string GNet::Client::connectionState() const
457{
458 if( m_state == State::Connected )
459 return socket().getPeerAddress().second.displayString() ;
460 else
461 return "("+m_remote_location.displayString()+")" ;
462}
463
464std::string GNet::Client::peerCertificate() const
465{
466 return m_sp->peerCertificate() ;
467}
468
469#ifndef G_LIB_SMALL
470 bool GNet::Client::secureConnectCapable() const
471{
472 return m_sp && m_sp->secureConnectCapable() ;
473}
474#endif
475
476 void GNet::Client::secureConnect()
477{
478 if( m_sp == nullptr )
479 throw NotConnected( "for secure-connect" ) ;
480 m_sp->secureConnect() ;
481}
482
483 bool GNet::Client::send( const std::string & data )
484{
485 if( m_config.response_timeout )
486 m_response_timer.startTimer( m_config.response_timeout ) ;
487 return m_sp->send( data , 0U ) ;
488}
489
490 bool GNet::Client::send( std::string_view data )
491{
492 if( m_config.response_timeout )
493 m_response_timer.startTimer( m_config.response_timeout ) ;
494 return m_sp->send( data ) ;
495}
496
497#ifndef G_LIB_SMALL
498 bool GNet::Client::send( const std::vector<std::string_view> & data , std::size_t offset )
499{
500 std::size_t total_size = std::accumulate( data.begin() , data.end() , std::size_t(0) ,
501 [](std::size_t n,std::string_view s){return n+s.size();} ) ;
502 if( m_config.response_timeout && offset < total_size )
503 m_response_timer.startTimer( m_config.response_timeout ) ;
504 return m_sp->send( data , offset ) ;
505}
506#endif
507
508#ifndef G_LIB_SMALL
509 GNet::LineBufferState GNet::Client::lineBuffer() const
510{
511 return m_line_buffer.state() ;
512}
513#endif
514
515 void GNet::Client::onPeerDisconnect()
516{
517}
518
519// ==
520
521#ifndef G_LIB_SMALL
522 GNet::Client::Config & GNet::Client::Config::set_all_timeouts( unsigned int all_timeouts ) noexcept
523{
524 socket_protocol_config.secure_connection_timeout = all_timeouts ;
525 connection_timeout = all_timeouts ;
526 response_timeout = all_timeouts ;
527 idle_timeout = all_timeouts * 2U ;
528 return *this ;
529}
530#endif
531
GNet::Address
The GNet::Address class encapsulates a TCP/UDP transport address.
Definition: gaddress.h:63
GNet::Address::isLoopback
bool isLoopback() const
Returns true if this is a loopback address.
Definition: gaddress.cpp:256
GNet::Client
A class for making an outgoing connection to a remote server, with support for socket-level protocols...
Definition: gclient.h:78
GNet::Client::disconnect
void disconnect()
Aborts the connection and destroys the object's internal state, resulting in a zombie object.
Definition: gclient.cpp:60
GNet::Client::peerCertificate
std::string peerCertificate() const override
Returns the peer's TLS certificate.
Definition: gclient.cpp:464
GNet::Client::peerAddressString
std::string peerAddressString(bool with_port=true) const
Returns the peer address display string or the empty string if not connected().
Definition: gclient.cpp:443
GNet::Client::secureConnect
void secureConnect()
Starts TLS/SSL client-side negotiation.
Definition: gclient.cpp:476
GNet::Client::~Client
~Client() override
Destructor.
Definition: gclient.cpp:54
GNet::Client::secureConnectCapable
bool secureConnectCapable() const
Returns true if currently connected and secureConnect() can be used.
Definition: gclient.cpp:470
GNet::Client::eventSignal
G::Slot::Signal< const std::string &, const std::string &, const std::string & > & eventSignal() noexcept
Returns a signal that indicates that something interesting has happened.
Definition: gclient.cpp:79
GNet::Client::Client
Client(EventState, const Location &remote_location, const Config &)
Constructor.
Definition: gclient.cpp:37
GNet::Client::localAddress
Address localAddress() const override
Returns the local address.
Definition: gclient.cpp:426
GNet::Client::socket
StreamSocket & socket()
Returns a reference to the socket. Throws if not connected.
Definition: gclient.cpp:89
GNet::Client::connectionState
std::string connectionState() const override
Returns the connection state display string.
Definition: gclient.cpp:456
GNet::Client::finished
bool finished() const
Returns true if finish() has been called.
Definition: gclient.cpp:223
GNet::Client::finish
void finish()
Indicates that the last data has been sent and the client is expecting a peer disconnect.
Definition: gclient.cpp:209
GNet::Client::lineBuffer
LineBufferState lineBuffer() const
Returns information about the state of the internal line-buffer.
Definition: gclient.cpp:509
GNet::Client::hasConnected
bool hasConnected() const
Returns true if ever connected().
Definition: gclient.cpp:228
GNet::Client::connected
bool connected() const
Returns true if connected to the peer.
Definition: gclient.cpp:395
GNet::Client::remoteLocation
Location remoteLocation() const
Returns a Location structure, including the result of name lookup if available.
Definition: gclient.cpp:84
GNet::Client::peerAddress
Address peerAddress() const override
Returns the peer address.
Definition: gclient.cpp:431
GNet::Client::send
bool send(const std::string &data)
Sends data to the peer and starts the response timer (if configured).
Definition: gclient.cpp:483
GNet::Client::connect
void connect()
Initiates a connection to the remote server.
Definition: gclient.cpp:115
GNet::Client::doOnDelete
void doOnDelete(const std::string &reason, bool done)
This should be called by the Client owner (typically ClientPtr) just before this Client object is del...
Definition: gclient.cpp:233
GNet::Client::clearInput
void clearInput()
Clears the input LineBuffer and cancels the response timer if running.
Definition: gclient.cpp:103
GNet::EventHandler::otherEvent
virtual void otherEvent(Reason)
Called for a socket-exception event, or a socket-close event on windows.
Definition: geventhandler.cpp:49
GNet::EventState
A lightweight object containing an ExceptionHandler pointer, optional ExceptionSource pointer and opt...
Definition: geventstate.h:131
GNet::LineBufferState
Provides information about the state of a line buffer.
Definition: glinebuffer.h:341
GNet::Location
A class that represents the remote target for out-going client connections.
Definition: glocation.h:70
GNet::Location::displayString
std::string displayString() const
Returns a string representation for logging and debug.
Definition: glocation.cpp:182
GNet::Location::address
Address address() const
Returns the remote address.
Definition: glocation.cpp:153
GNet::Monitor::removeClient
static void removeClient(const Connection &client) noexcept
Removes a client connection.
Definition: gmonitor.cpp:113
GNet::Monitor::addClient
static void addClient(const Connection &client)
Adds a client connection.
Definition: gmonitor.cpp:104
GNet::Resolver::resolve
static std::pair< std::string, std::string > resolve(Location &, const Config &)
Does synchronous name resolution.
Definition: gresolver.cpp:198
GNet::Resolver::async
static bool async()
Returns true if the resolver supports asynchronous operation.
Definition: gresolver.cpp:260
GNet::StreamSocket
A derivation of GNet::Socket for a stream socket.
Definition: gsocket.h:356
G::CallFrame
An object to represent a nested execution context.
Definition: gcall.h:86
G::Root
A class which acquires the process's special privileges on construction and releases them on destruct...
Definition: groot.h:52
G::Test::enabled
static bool enabled() noexcept
Returns true if test features are enabled.
Definition: gtest.cpp:79
gaddress.h
gassert.h
gclient.h
gdatetime.h
gexception.h
glog.h
gmonitor.h
gresolver.h
groot.h
gsocket.h
gtest.h
GNet
Network classes.
Definition: gdef.h:1243
GNet::Client::Config
A structure containing GNet::Client configuration parameters.
Definition: gclient.h:87
GNet::Resolver::Callback
An interface used for GNet::Resolver callbacks.
Definition: gresolver.h:67
G::Slot::Signal< const std::string &, const std::string &, const std::string & >