E-MailRelay

- Main Page
- Namespaces
- Classes
- Files

- File List
- File Members

gserver.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 gserver.h
19 ///
20
21 #ifndef G_NET_SERVER__H
22 #define G_NET_SERVER__H
23
24 #include "gdef.h"
25 #include "gsocket.h"
26 #include "gsocketprotocol.h"
27 #include "gtimer.h"
28 #include "gconnection.h"
29 #include "gevent.h"
30 #include <utility>
31 #include <list>
32 #include <memory>
33 #include <string>
34
35 namespace GNet
36 {
37 class Server ;
38 class ServerPeer ;
39 class ServerPeerTimer ;
40 class ServerPeerHandle ;
41 }
42
43 /// \class GNet::ServerPeerHandle
44 /// A structure used in the implementation of GNet::Server. The server holds
45 /// a list of handles which refer to all its peer objects. When a peer object
46 /// deletes itself it resets the handle, without changing the server's list.
47 /// The server uses its list to delete all peer objects from within its
48 /// destructor. The server does garbage collection occasionally, deleting
49 /// handles which have been reset.
50 ///
51 class GNet::ServerPeerHandle
52 {
53 public:
54 ServerPeerHandle() ;
55 ///< Default constructor.
56
57 void set( ServerPeer * p ) ;
58 ///< Sets the pointer.
59
60 void reset() ;
61 ///< Resets the pointer.
62
63 ServerPeer * peer() ;
64 ///< Returns the pointer.
65
66 ServerPeer * old() ;
67 ///< Returns the pointer value before it was reset().
68 ///< Used in debugging.
69
70 private:
71 ServerPeer * m_p ;
72 ServerPeer * m_old ;
73 } ;
74
75 /// \class GNet::Server
76 /// A network server class which listens on a specific port and spins off
77 /// ServerPeer objects for each incoming connection.
78 /// \see GNet::ServerPeer
79 ///
80 class GNet::Server : public EventHandler
81 {
82 public:
83 G_EXCEPTION( CannotBind , "cannot bind the listening port" ) ;
84
85 struct PeerInfo /// A structure used in GNet::Server::newPeer().
86 {
87 shared_ptr<StreamSocket> m_socket ;
88 Address m_address ;
89 ServerPeerHandle * m_handle ;
90 PeerInfo() ;
91 } ;
92
93 Server( ExceptionHandler & , const Address & listening_address ) ;
94 ///< Constructor. The server listens on the given address,
95 ///< which can be the 'any' address.
96
97 explicit Server( ExceptionHandler & ) ;
98 ///< Constructor; initialise with init().
99
100 void init( const Address & listening_address ) ;
101 ///< Initilisation after default construction.
102
103 virtual ~Server() ;
104 ///< Destructor.
105
106 std::pair<bool,Address> address() const ;
107 ///< Returns the listening address. Pair.first
108 ///< is false if not properly init()ialised.
109
110 virtual void readEvent() override ;
111 ///< Override from GNet::EventHandler.
112
113 virtual void writeEvent() override ;
114 ///< Override from GNet::EventHandler.
115
116 static bool canBind( const Address & listening_address , bool do_throw ) ;
117 ///< Checks that the specified address can be
118 ///< bound. Throws CannotBind if the address cannot
119 ///< be bound and 'do_throw' is true.
120
121 protected:
122 virtual ServerPeer * newPeer( PeerInfo ) = 0 ;
123 ///< A factory method which new()s a ServerPeer-derived
124 ///< object. This method is called when a new connection
125 ///< comes into this server. The new ServerPeer object
126 ///< is used to represent the state of the client/server
127 ///< connection.
128 ///<
129 ///< The new ServerPeer object manages its own lifetime
130 ///< doing a "delete this" when the network connection
131 ///< disappears. But the Server also deletes remaining
132 ///< peers during its destruction.
133 ///<
134 ///< The implementation should pass the 'PeerInfo'
135 ///< parameter through to the ServerPeer base-class
136 ///< constructor.
137 ///<
138 ///< Should return nullptr for non-fatal errors. It is
139 ///< expected that a typical server process will
140 ///< terminate if newPeer() throws, so most
141 ///< implementations will catch any exceptions and
142 ///< return nullptr.
143
144 void serverCleanup() ;
145 ///< May be called from the derived class destructor
146 ///< in order to trigger early deletion of peer objects,
147 ///< before the derived part of the server disappears.
148 ///< If this is called from the most-derived Server
149 ///< class then it allows ServerPeer objects to use
150 ///< their Server object safely during destruction.
151
152 private:
153 Server( const Server & ) ; // not implemented
154 void operator=( const Server & ) ; // not implemented
155 void serverCleanupCore() ;
156 void collectGarbage() ;
157 void accept( PeerInfo & ) ;
158
159 private:
160 typedef std::list<ServerPeerHandle> PeerList ;
161 ExceptionHandler & m_eh ;
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 ///
173 class GNet::ServerPeer : public ExceptionHandler , public EventHandler , public Connection , public SocketProtocolSink
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 ///< Calls onDelete() and schedules a "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 connectionState() const override ;
209 ///< Returns the connection state display string.
210 ///< Override from GNet::Connection.
211
212 virtual std::string peerCertificate() const override ;
213 ///< Returns the peer's TLS certificate.
214 ///< Override from GNet::Connection.
215
216 virtual void readEvent() override ;
217 ///< Override from GNet::EventHandler.
218 ///< Calls GNet::SocketProtocol::readEvent().
219
220 virtual void writeEvent() override ;
221 ///< Override from GNet::EventHandler.
222 ///< Calls GNet::SocketProtocol::writeEvent().
223
224 virtual void otherEvent( EventHandler::Reason ) override ;
225 ///< Override from GNet::EventHandler.
226 ///< Calls GNet::SocketProtocol::otherEvent().
227
228 void doDeleteThis( int ) ;
229 ///< Does delete this. Should only be used by the GNet::Server class.
230
231 protected:
232 virtual ~ServerPeer() ;
233 ///< Destructor. Note that objects will delete themselves
234 ///< when they detect that the connection has been
235 ///< lost -- see doDelete().
236
237 virtual void onDelete( const std::string & reason ) = 0 ;
238 ///< Called just before destruction. (Note that the
239 ///< object typically deletes itself.)
240
241 virtual void onSendComplete() = 0 ;
242 ///< Called after flow-control has been released and all
243 ///< residual data sent.
244 ///<
245 ///< If an exception is thrown in the override then this
246 ///< object catches it and deletes iteself by calling
247 ///< doDelete().
248
249 void secureAccept() ;
250 ///< Waits for the peer to start a secure session. Uses a
251 ///< profile called "server"; see GSsl::Library::addProfile().
252 ///< The callback GNet::SocketProtocolSink::onSecure() is
253 ///< triggered when the secure session is established.
254
255 StreamSocket & socket() ;
256 ///< Returns a reference to the client-server connection
257 ///< socket.
258
259 Server * server() ;
260 ///< Returns a pointer to the associated server object.
261 ///< Returns nullptr if the server has been destroyed.
262
263 virtual void onException( std::exception & ) override ;
264 ///< Override from GNet::ExceptionHandler.
265
266 private:
267 ServerPeer( const ServerPeer & ) ; // not implemented
268 void operator=( const ServerPeer & ) ; // not implemented
269 void onTimeout() ;
270
271 private:
272 Address m_address ;
273 shared_ptr<StreamSocket> m_socket ; // order dependency -- first
274 SocketProtocol m_sp ; // order dependency -- second
275 ServerPeerHandle * m_handle ;
276 Timer<ServerPeer> m_delete_timer ;
277 } ;
278
279 #endif
GNet::Server::newPeer
virtual ServerPeer * newPeer(PeerInfo)=0
A factory method which new()s a ServerPeer-derived object.
GNet::ServerPeer
An abstract base class for the GNet::Server's connection to a remote client.
Definition: gserver.h:173
GNet::Server::canBind
static bool canBind(const Address &listening_address, bool do_throw)
Checks that the specified address can be bound.
Definition: gserver.cpp:166
GNet
Network classes.
Definition: gaddress.h:29
GNet::Server::Server
Server(ExceptionHandler &, const Address &listening_address)
Constructor.
Definition: gserver.cpp:141
GNet::ServerPeer::connectionState
virtual std::string connectionState() const override
Returns the connection state display string.
Definition: gserver.cpp:98
gsocketprotocol.h
GNet::ServerPeer::ServerPeer
ServerPeer(Server::PeerInfo)
Constructor.
Definition: gserver.cpp:31
GNet::Address
The GNet::Address class encapsulates a TCP/UDP transport address.
Definition: gaddress.h:54
GNet::ServerPeer::onSendComplete
virtual void onSendComplete()=0
Called after flow-control has been released and all residual data sent.
GNet::ServerPeer::server
Server * server()
Returns a pointer to the associated server object.
GNet::ServerPeerHandle::set
void set(ServerPeer *p)
Sets the pointer.
Definition: gserver.cpp:324
GNet::ServerPeer::onException
virtual void onException(std::exception &) override
Override from GNet::ExceptionHandler.
Definition: gserver.cpp:134
GNet::ServerPeer::readEvent
virtual void readEvent() override
Override from GNet::EventHandler.
Definition: gserver.cpp:76
GNet::Server
A network server class which listens on a specific port and spins off ServerPeer objects for each inc...
Definition: gserver.h:80
GNet::Server::writeEvent
virtual void writeEvent() override
Override from GNet::EventHandler.
Definition: gserver.cpp:288
GNet::ServerPeerHandle
A structure used in the implementation of GNet::Server.
Definition: gserver.h:51
GNet::ExceptionHandler
An abstract interface for handling exceptions thrown out of event-loop callbacks (socket events...
Definition: gexceptionhandler.h:44
GNet::ServerPeer::otherEvent
virtual void otherEvent(EventHandler::Reason) override
Override from GNet::EventHandler.
Definition: gserver.cpp:71
GNet::StreamSocket
A derivation of GNet::Socket for a stream socket.
Definition: gsocket.h:246
GNet::ServerPeer::send
bool send(const std::string &data, std::string::size_type offset=0U)
Sends data down the socket to the peer.
Definition: gserver.cpp:118
GNet::ServerPeer::socket
StreamSocket & socket()
Returns a reference to the client-server connection socket.
Definition: gserver.cpp:65
gtimer.h
GNet::ServerPeer::doDelete
void doDelete(const std::string &=std::string())
Calls onDelete() and schedules a "delete this".
Definition: gserver.cpp:81
GNet::ServerPeer::onDelete
virtual void onDelete(const std::string &reason)=0
Called just before destruction.
gevent.h
GNet::Server::~Server
virtual ~Server()
Destructor.
Definition: gserver.cpp:179
GNet::EventHandler
A base class for classes that handle asynchronous events from the event loop.
Definition: geventhandler.h:47
GNet::ServerPeer::doDeleteThis
void doDeleteThis(int)
Does delete this. Should only be used by the GNet::Server class.
Definition: gserver.cpp:113
gsocket.h
GNet::ServerPeer::peerCertificate
virtual std::string peerCertificate() const override
Returns the peer's TLS certificate.
Definition: gserver.cpp:103
GNet::Connection
An abstract interface which provides address information for a network connection.
Definition: gconnection.h:37
GNet::ServerPeerHandle::reset
void reset()
Resets the pointer.
Definition: gserver.cpp:309
GNet::ServerPeer::peerAddress
virtual std::pair< bool, Address > peerAddress() const override
Returns the peer address.
Definition: gserver.cpp:93
GNet::ServerPeerHandle::old
ServerPeer * old()
Returns the pointer value before it was reset().
Definition: gserver.cpp:319
GNet::ServerPeer::writeEvent
virtual void writeEvent() override
Override from GNet::EventHandler.
Definition: gserver.cpp:128
GNet::ServerPeer::logId
std::string logId() const
Returns an identification string for logging purposes.
Definition: gserver.cpp:55
GNet::Timer
A timer class template in which the timeout is delivered to the specified method. ...
Definition: gtimer.h:115
GNet::Server::serverCleanup
void serverCleanup()
May be called from the derived class destructor in order to trigger early deletion of peer objects...
Definition: gserver.cpp:184
GNet::ServerPeer::secureAccept
void secureAccept()
Waits for the peer to start a secure session.
Definition: gserver.cpp:60
GNet::Server::init
void init(const Address &listening_address)
Initilisation after default construction.
Definition: gserver.cpp:153
GNet::SocketProtocolSink
An interface used by GNet::SocketProtocol to deliver data from a socket.
Definition: gsocketprotocol.h:134
GNet::SocketProtocol
An interface for implementing a low-level TLS/SSL protocol layer on top of a connected non-blocking s...
Definition: gsocketprotocol.h:53
GNet::ServerPeer::~ServerPeer
virtual ~ServerPeer()
Destructor.
Definition: gserver.cpp:46
GNet::Server::PeerInfo
A structure used in GNet::Server::newPeer().
Definition: gserver.h:85
GNet::ServerPeerHandle::ServerPeerHandle
ServerPeerHandle()
Default constructor.
Definition: gserver.cpp:303
GNet::Server::readEvent
virtual void readEvent() override
Override from GNet::EventHandler.
Definition: gserver.cpp:220
GNet::Server::address
std::pair< bool, Address > address() const
Returns the listening address.
Definition: gserver.cpp:212
GNet::ServerPeer::localAddress
virtual std::pair< bool, Address > localAddress() const override
Returns the local address.
Definition: gserver.cpp:87
GNet::ServerPeerHandle::peer
ServerPeer * peer()
Returns the pointer.
Definition: gserver.cpp:314
gconnection.h