VideoTools
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
gserver.h
Go to the documentation of this file.
1 //
2 // Copyright (C) 2017 Graeme Walker
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 gserver.h
19 ///
20 
21 #ifndef G_SERVER_H
22 #define G_SERVER_H
23 
24 #include "gdef.h"
25 #include "gnet.h"
26 #include "gsocket.h"
27 #include "gsocketprotocol.h"
28 #include "gtimer.h"
29 #include "gconnection.h"
30 #include "gevent.h"
31 #include <utility>
32 #include <list>
33 #include <memory>
34 #include <string>
35 
36 namespace GNet
37 {
38  class Server ;
39  class ServerPeer ;
40  class ServerPeerTimer ;
41  class ServerPeerHandle ;
42 }
43 
44 /// \class GNet::ServerPeerHandle
45 /// A structure used in the implementation of GNet::Server. The server holds
46 /// a list of handles which refer to all its peer objects. When a peer object
47 /// deletes itself it resets the handle, without changing the server's list.
48 /// The server uses its list to delete all peer objects from within its
49 /// destructor. The server does garbage collection occasionally, deleting
50 /// handles which have been reset.
51 ///
53 {
54 public:
56  ///< Default constructor.
57 
58  void set( ServerPeer * p ) ;
59  ///< Sets the pointer.
60 
61  void reset() ;
62  ///< Resets the pointer.
63 
64  ServerPeer * peer() ;
65  ///< Returns the pointer.
66 
67  ServerPeer * old() ;
68  ///< Returns the pointer value before it was reset().
69  ///< Used in debugging.
70 
71 private:
72  ServerPeer * m_p ;
73  ServerPeer * m_old ;
74 } ;
75 
76 /// \class GNet::Server
77 /// A network server class which listens on a specific port and spins off
78 /// ServerPeer objects for each incoming connection.
79 /// \see GNet::ServerPeer
80 ///
81 class GNet::Server : public EventHandler
82 {
83 public:
84  G_EXCEPTION( CannotBind , "cannot bind the listening port" ) ;
85 
86  struct PeerInfo /// A structure used in GNet::Server::newPeer().
87  {
88  shared_ptr<StreamSocket> m_socket ;
89  Address m_address ;
90  ServerPeerHandle * m_handle ;
91  PeerInfo() ;
92  } ;
93 
94  static bool canBind( const Address & listening_address , bool do_throw ) ;
95  ///< Checks that the specified address can be
96  ///< bound. Throws CannotBind if the address cannot
97  ///< be bound and 'do_throw' is true.
98 
99  explicit Server( const Address & listening_address ) ;
100  ///< Constructor. The server listens on the given address,
101  ///< which can be the 'any' address.
102 
103  Server() ;
104  ///< Default constructor. Initialise with init().
105 
106  void init( const Address & listening_address ) ;
107  ///< Initilisation after default construction.
108 
109  virtual ~Server() ;
110  ///< Destructor.
111 
112  std::pair<bool,Address> address() const ;
113  ///< Returns the listening address. Pair.first
114  ///< is false if not properly init()ialised.
115 
116  virtual void readEvent() override ;
117  ///< Override from GNet::EventHandler.
118 
119  virtual void writeEvent() override ;
120  ///< Override from GNet::EventHandler.
121 
122 protected:
123  virtual ServerPeer * newPeer( PeerInfo ) = 0 ;
124  ///< A factory method which new()s a ServerPeer-derived
125  ///< object. This method is called when a new connection
126  ///< comes into this server. The new ServerPeer object
127  ///< is used to represent the state of the client/server
128  ///< connection.
129  ///<
130  ///< The new ServerPeer object manages its own lifetime
131  ///< doing a "delete this" when the network connection
132  ///< disappears. But the Server also deletes remaining
133  ///< peers during its destruction.
134  ///<
135  ///< The implementation should pass the 'PeerInfo'
136  ///< parameter through to the ServerPeer base-class
137  ///< constructor.
138  ///<
139  ///< Should return nullptr for non-fatal errors. It is
140  ///< expected that a typical server process will
141  ///< terminate if newPeer() throws, so most
142  ///< implementations will catch any exceptions and
143  ///< return nullptr.
144 
145  void serverCleanup() ;
146  ///< May be called from the derived class destructor
147  ///< in order to trigger early deletion of peer objects,
148  ///< before the derived part of the server disappears.
149  ///< If this is called from the most-derived Server
150  ///< class then it allows ServerPeer objects to use
151  ///< their Server object safely during destruction.
152 
153 private:
154  Server( const Server & ) ; // not implemented
155  void operator=( const Server & ) ; // not implemented
156  void serverCleanupCore() ;
157  void collectGarbage() ;
158  void accept( PeerInfo & ) ;
159 
160 private:
161  typedef std::list<ServerPeerHandle> PeerList ;
162  unique_ptr<StreamSocket> m_socket ; // listening socket
163  PeerList m_peer_list ;
164  bool m_cleaned_up ;
165 } ;
166 
167 /// \class GNet::ServerPeer
168 /// An abstract base class for the GNet::Server's connection to a remote
169 /// client. Instances are created on the heap by the Server::newPeer()
170 /// override, and they delete themselves when the connection is lost.
171 /// \see GNet::Server, GNet::EventHandler
172 ///
174 {
175 public:
176  typedef std::string::size_type size_type ;
177 
178  explicit ServerPeer( Server::PeerInfo ) ;
179  ///< Constructor. This constructor is only used from within the
180  ///< override of GServer::newPeer().
181 
182  bool send( const std::string & data , std::string::size_type offset = 0U ) ;
183  ///< Sends data down the socket to the peer. Returns true if completely
184  ///< sent; returns false if flow control asserted (see onSendComplete()).
185  ///< If flow control is asserted then there should be no new calls to
186  ///< send() until onSendComplete() is triggered.
187  ///< Throws on error.
188 
189  bool send( const std::vector<std::pair<const char *,size_t> > & data ) ;
190  ///< Overload to send data using scatter-gather segments. If false is
191  ///< returned then segment data pointers must stay valid until
192  ///< onSendComplete() is triggered.
193 
194  void doDelete( const std::string & = std::string() ) ;
195  ///< Does "onDelete(); delete this".
196 
197  std::string logId() const ;
198  ///< Returns an identification string for logging purposes.
199 
200  virtual std::pair<bool,Address> localAddress() const override ;
201  ///< Returns the local address. Pair.first is false on error.
202  ///< Override from GNet::Connection.
203 
204  virtual std::pair<bool,Address> peerAddress() const override ;
205  ///< Returns the peer address.
206  ///< Override from GNet::Connection.
207 
208  virtual std::string peerCertificate() const override ;
209  ///< Returns the peer's TLS certificate.
210  ///< Override from GNet::Connection.
211 
212  virtual void readEvent() override ;
213  ///< Override from GNet::EventHandler.
214 
215  virtual void writeEvent() override ;
216  ///< Override from GNet::EventHandler.
217 
218  void doDeleteThis( int ) ;
219  ///< Does delete this. Should only be used by the GNet::Server class.
220 
221  virtual void onException( std::exception & ) g__final override ;
222  ///< Override from GNet::EventHandler. Calls doDelete(). Note
223  ///< that the exception text is available via onDelete().
224  ///< (This is public so that a derived-class server containing
225  ///< something like a HeapClient can merge its exception
226  ///< events.)
227 
228 protected:
229  virtual ~ServerPeer() ;
230  ///< Destructor. Note that objects will delete themselves
231  ///< when they detect that the connection has been
232  ///< lost -- see doDelete().
233 
234  virtual void onDelete( const std::string & reason ) = 0 ;
235  ///< Called just before destruction. (Note that the
236  ///< object typically deletes itself.)
237 
238  virtual void onSendComplete() = 0 ;
239  ///< Called after flow-control has been released and all
240  ///< residual data sent.
241  ///<
242  ///< If an exception is thrown in the override then this
243  ///< object catches it and deletes iteself by calling
244  ///< doDelete().
245 
246  void sslAccept() ;
247  ///< Waits for the peer to start a secure session.
248  ///< See also GNet::SocketProtocolSink::onSecure().
249 
250  StreamSocket & socket() ;
251  ///< Returns a reference to the client-server connection
252  ///< socket.
253 
254  Server * server() ;
255  ///< Returns a pointer to the associated server object.
256  ///< Returns nullptr if the server has been destroyed.
257 
258 private:
259  ServerPeer( const ServerPeer & ) ; // not implemented
260  void operator=( const ServerPeer & ) ; // not implemented
261  void onTimeout() ;
262 
263 private:
264  Address m_address ;
265  shared_ptr<StreamSocket> m_socket ; // order dependency -- first
266  SocketProtocol m_sp ; // order dependency -- second
267  ServerPeerHandle * m_handle ;
268  Timer<ServerPeer> m_delete_timer ;
269 } ;
270 
271 #endif
virtual ServerPeer * newPeer(PeerInfo)=0
A factory method which new()s a ServerPeer-derived object.
An abstract base class for the GNet::Server's connection to a remote client.
Definition: gserver.h:173
static bool canBind(const Address &listening_address, bool do_throw)
Checks that the specified address can be bound.
Definition: gserver.cpp:164
ServerPeer(Server::PeerInfo)
Constructor.
Definition: gserver.cpp:32
The GNet::Address class encapsulates a TCP/UDP transport address.
Definition: gaddress.h:55
virtual void onSendComplete()=0
Called after flow-control has been released and all residual data sent.
Server * server()
Returns a pointer to the associated server object.
void set(ServerPeer *p)
Sets the pointer.
Definition: gserver.cpp:322
virtual void readEvent() override
Override from GNet::EventHandler.
Definition: gserver.cpp:72
A network server class which listens on a specific port and spins off ServerPeer objects for each inc...
Definition: gserver.h:81
virtual void writeEvent() override
Override from GNet::EventHandler.
Definition: gserver.cpp:286
A structure used in the implementation of GNet::Server.
Definition: gserver.h:52
A derivation of GNet::Socket for a stream socket.
Definition: gsocket.h:245
bool send(const std::string &data, std::string::size_type offset=0U)
Sends data down the socket to the peer.
Definition: gserver.cpp:115
Server()
Default constructor. Initialise with init().
Definition: gserver.cpp:146
StreamSocket & socket()
Returns a reference to the client-server connection socket.
Definition: gserver.cpp:66
void doDelete(const std::string &=std::string())
Does "onDelete(); delete this".
Definition: gserver.cpp:83
virtual void onDelete(const std::string &reason)=0
Called just before destruction.
virtual ~Server()
Destructor.
Definition: gserver.cpp:177
A base class for classes that handle asynchronous events from the event loop.
Definition: geventhandler.h:78
void doDeleteThis(int)
Does delete this. Should only be used by the GNet::Server class.
Definition: gserver.cpp:110
virtual std::string peerCertificate() const override
Returns the peer's TLS certificate.
Definition: gserver.cpp:100
An interface which provides address information for a network connection.
Definition: gconnection.h:37
void reset()
Resets the pointer.
Definition: gserver.cpp:307
virtual std::pair< bool, Address > peerAddress() const override
Returns the peer address.
Definition: gserver.cpp:95
virtual void onException(std::exception &) g__final override
Override from GNet::EventHandler.
Definition: gserver.cpp:77
ServerPeer * old()
Returns the pointer value before it was reset().
Definition: gserver.cpp:317
virtual void writeEvent() override
Override from GNet::EventHandler.
Definition: gserver.cpp:125
std::string logId() const
Returns an identification string for logging purposes.
Definition: gserver.cpp:56
A timer class template in which the timeout is delivered to the specified method. ...
Definition: gtimer.h:110
void serverCleanup()
May be called from the derived class destructor in order to trigger early deletion of peer objects...
Definition: gserver.cpp:182
void sslAccept()
Waits for the peer to start a secure session.
Definition: gserver.cpp:61
void init(const Address &listening_address)
Initilisation after default construction.
Definition: gserver.cpp:151
to deliver data from a socket.
An interface for implementing a low-level TLS/SSL protocol layer on top of a connected non-blocking s...
virtual ~ServerPeer()
Destructor.
Definition: gserver.cpp:47
A structure used in GNet::Server::newPeer().
Definition: gserver.h:86
ServerPeerHandle()
Default constructor.
Definition: gserver.cpp:301
virtual void readEvent() override
Override from GNet::EventHandler.
Definition: gserver.cpp:218
std::pair< bool, Address > address() const
Returns the listening address.
Definition: gserver.cpp:210
virtual std::pair< bool, Address > localAddress() const override
Returns the local address.
Definition: gserver.cpp:89
ServerPeer * peer()
Returns the pointer.
Definition: gserver.cpp:312