E-MailRelay
gsimpleclient.h
Go to the documentation of this file.
1 //
2 // Copyright (C) 2001-2018 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 gsimpleclient.h
19 ///
20 
21 #ifndef G_NET_SIMPLE_CLIENT__H
22 #define G_NET_SIMPLE_CLIENT__H
23 
24 #include "gdef.h"
25 #include "gaddress.h"
26 #include "gsocks.h"
27 #include "gconnection.h"
28 #include "gexception.h"
29 #include "geventhandler.h"
30 #include "gresolver.h"
31 #include "glocation.h"
32 #include "gtimer.h"
33 #include "gsocket.h"
34 #include "gsocketprotocol.h"
35 #include "gevent.h"
36 #include <string>
37 
38 namespace GNet
39 {
40  class SimpleClient ;
41 }
42 
43 /// \class GNet::SimpleClient
44 /// A class for making an outgoing connection to a remote server, with
45 /// support for socket-level protocols such as TLS/SSL and SOCKS 4a.
46 ///
47 /// The class handles name-to-address resolution, deals with
48 /// connection issues, reads incoming data, and manages flow-control
49 /// when sending. The implementation uses the SocketProtocol class
50 /// in order to do TLS/SSL; see secureConnect().
51 ///
52 /// Name-to-address lookup is performed if the supplied Location
53 /// object does not contain an address. This can be done synchronously
54 /// or asynchronously. The results of the lookup can be obtained via
55 /// the remoteLocation() method and possibly fed back to the next
56 /// SimpleClient that connects to the same host/service in order to
57 /// implement name lookup cacheing (see GNet::ClientPtr). However,
58 /// most operating systems implement their own name lookup cacheing,
59 /// so this is not terribly useful in practice.
60 ///
62 {
63 public:
64  enum ConnectStatus { Success , Failure , ImmediateSuccess } ;
65  enum State { Idle , Resolving , Connecting , Connected , Socksing , Testing } ;
66  G_EXCEPTION( DnsError , "dns error" ) ;
67  G_EXCEPTION( ConnectError , "connect failure" ) ;
68  G_EXCEPTION( NotConnected , "socket not connected" ) ;
69  typedef std::string::size_type size_type ;
70 
72  const Location & remote_info , bool bind_local_address = false ,
73  const Address & local_address = Address::defaultAddress() ,
74  bool sync_dns = synchronousDnsDefault() ,
75  unsigned int secure_connection_timeout = 0U ) ;
76  ///< Constructor. Call connect() to start connecting.
77 
78  void connect() ;
79  ///< Initates a connection to the remote server. Calls back
80  ///< to onConnect() when complete (non-reentrantly). Throws
81  ///< on error.
82 
83  bool connected() const ;
84  ///< Returns true if connected to the peer.
85 
86  virtual std::pair<bool,Address> localAddress() const override ;
87  ///< Override from Connection. Returns the local
88  ///< address. Pair.first is false on error.
89  ///< Override from GNet::Connection.
90 
91  virtual std::pair<bool,Address> peerAddress() const override ;
92  ///< Override from Connection. Returns the peer
93  ///< address. Pair.first is false on error.
94  ///< Override from GNet::Connection.
95 
96  virtual std::string connectionState() const override ;
97  ///< Returns the connection state display string.
98  ///< Override from GNet::Connection.
99 
100  virtual std::string peerCertificate() const override ;
101  ///< Returns the peer's TLS certificate.
102  ///< Override from GNet::Connection.
103 
104  static bool synchronousDnsDefault() ;
105  ///< Returns true if DNS queries should normally be
106  ///< synchronous on this platform. Used to default the
107  ///< relevant constructor parameter.
108 
109  Location remoteLocation() const ;
110  ///< Returns a Location structure containing the
111  ///< result of host() and service() name lookup if
112  ///< available.
113 
114  void updateLocation( const Location & ) ;
115  ///< Updates the constructor's Location object with
116  ///< the given one as long as both objects have the
117  ///< same host and service name. This is only useful
118  ///< immediately after construction and before
119  ///< re-entering the event loop.
120 
121  virtual void readEvent() override ;
122  ///< Override from GNet::EventHandler.
123 
124  virtual void writeEvent() override ;
125  ///< Override from GNet::EventHandler.
126 
127  virtual void otherEvent( EventHandler::Reason ) override ;
128  ///< Override from GNet::EventHandler.
129 
130  bool send( const std::string & data , std::string::size_type offset = 0 ) ;
131  ///< Sends data to the peer. Returns true if all sent,
132  ///< or false if flow control was asserted. Throws on
133  ///< error.
134 
135 protected:
136  virtual ~SimpleClient() ;
137  ///< Destructor.
138 
139  StreamSocket & socket() ;
140  ///< Returns a reference to the socket. Throws if not connected.
141 
142  const StreamSocket & socket() const ;
143  ///< Returns a const reference to the socket. Throws if not connected.
144 
145  virtual void onConnect() = 0 ;
146  ///< Called once connected.
147 
148  virtual void onConnectImp() ;
149  ///< An alternative to onConnect() for private implementation
150  ///< classes. The default implementation does nothing.
151 
152  virtual void onSendComplete() = 0 ;
153  ///< Called when all residual data from send() has been sent.
154 
155  virtual void onSendImp() ;
156  ///< Called from within send().
157 
158  void secureConnect() ;
159  ///< Starts TLS/SSL client-side negotiation. Uses a profile
160  ///< called "client"; see GSsl::Library::addProfile().
161  ///< The callback GNet::SocketProtocolSink::onSecure() is
162  ///< triggered when the secure session is established.
163 
164  static bool connectError( const std::string & reason ) ;
165  ///< Returns true if the reason string implies the
166  ///< SimpleClient::connect() failed.
167 
168  std::string logId() const ;
169  ///< Returns a identification string for logging purposes.
170  ///< Not guaranteed to stay the same during the lifetime
171  ///< of the object.
172 
173 private:
174  SimpleClient( const SimpleClient& ) ; // not implemented
175  void operator=( const SimpleClient& ) ; // not implemented
176  void close() ;
177  void startConnecting() ;
178  void bindLocalAddress( const Address & ) ;
179  void setState( State ) ;
180  void logFlowControlAsserted() const ;
181  void logFlowControlReleased() const ;
182  virtual void onResolved( std::string , Location ) override ; // Override from GNet::Resolver.
183  void onConnectTimer() ;
184  void onWriteable() ;
185 
186 private:
187  ExceptionHandler & m_eh ;
188  unique_ptr<StreamSocket> m_socket ;
189  unique_ptr<SocketProtocol> m_sp ;
190  unique_ptr<Socks> m_socks ;
191  Resolver m_resolver ;
192  Location m_remote_location ;
193  bool m_bind_local_address ;
194  Address m_local_address ;
195  State m_state ;
196  bool m_sync_dns ;
197  unsigned int m_secure_connection_timeout ;
198  Timer<SimpleClient> m_on_connect_timer ; // zero-length timer
199 } ;
200 
201 #endif
virtual void onConnect()=0
Called once connected.
virtual void writeEvent() override
Override from GNet::EventHandler.
virtual void readEvent() override
Override from GNet::EventHandler.
A class for making an outgoing connection to a remote server, with support for socket-level protocols...
Definition: gsimpleclient.h:61
bool send(const std::string &data, std::string::size_type offset=0)
Sends data to the peer.
Network classes.
Definition: gaddress.h:29
void secureConnect()
Starts TLS/SSL client-side negotiation.
A class for synchronous or asynchronous network name to address resolution.
Definition: gresolver.h:42
The GNet::Address class encapsulates a TCP/UDP transport address.
Definition: gaddress.h:54
virtual std::string peerCertificate() const override
Returns the peer's TLS certificate.
bool connected() const
Returns true if connected to the peer.
virtual void onConnectImp()
An alternative to onConnect() for private implementation classes.
An interface used for GNet::Resolver callbacks.
Definition: gresolver.h:48
An abstract interface for handling exceptions thrown out of event-loop callbacks (socket events...
virtual void onSendComplete()=0
Called when all residual data from send() has been sent.
A class that holds a host/service name pair and the preferred address family (if any), and also the results of a name-to-address lookup, ie.
Definition: glocation.h:50
void connect()
Initates a connection to the remote server.
A derivation of GNet::Socket for a stream socket.
Definition: gsocket.h:246
static Address defaultAddress()
Returns a default address, being the IPv4 wildcard address with a zero port number.
Location remoteLocation() const
Returns a Location structure containing the result of host() and service() name lookup if available...
virtual std::pair< bool, Address > localAddress() const override
Override from Connection.
A base class for classes that handle asynchronous events from the event loop.
Definition: geventhandler.h:47
virtual std::string connectionState() const override
Returns the connection state display string.
std::string logId() const
Returns a identification string for logging purposes.
static bool synchronousDnsDefault()
Returns true if DNS queries should normally be synchronous on this platform.
virtual void onSendImp()
Called from within send().
An abstract interface which provides address information for a network connection.
Definition: gconnection.h:37
virtual ~SimpleClient()
Destructor.
virtual std::pair< bool, Address > peerAddress() const override
Override from Connection.
virtual void otherEvent(EventHandler::Reason) override
Override from GNet::EventHandler.
static bool connectError(const std::string &reason)
Returns true if the reason string implies the SimpleClient::connect() failed.
void updateLocation(const Location &)
Updates the constructor's Location object with the given one as long as both objects have the same ho...
SimpleClient(ExceptionHandler &, const Location &remote_info, bool bind_local_address=false, const Address &local_address=Address::defaultAddress(), bool sync_dns=synchronousDnsDefault(), unsigned int secure_connection_timeout=0U)
Constructor. Call connect() to start connecting.
A timer class template in which the timeout is delivered to the specified method. ...
Definition: gtimer.h:115
An interface used by GNet::SocketProtocol to deliver data from a socket.
StreamSocket & socket()
Returns a reference to the socket. Throws if not connected.