6092cccca163d7867a13c071a8759c226ff4e2f6
[senf.git] / senf / Socket / SocketProtocol.hh
1 // $Id$
2 //
3 // Copyright (C) 2006
4 // Fraunhofer Institute for Open Communication Systems (FOKUS)
5 // Competence Center NETwork research (NET), St. Augustin, GERMANY
6 //     Stefan Bund <g0dil@berlios.de>
7 //
8 // This program is free software; you can redistribute it and/or modify
9 // it under the terms of the GNU General Public License as published by
10 // the Free Software Foundation; either version 2 of the License, or
11 // (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 // GNU General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the
20 // Free Software Foundation, Inc.,
21 // 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22
23 /** \file
24     \brief SocketProtocol and ConcreteSocketProtocol public header
25  */
26
27 // The private inheritance idea should indeed work very well: We just need to change the
28 // implementations of body() and protocol() and that of the ProtocolClient/ServerSocketHandle
29 // constructors and the SocketBody constructor. The body and the protocol would still be visible
30 // like several instances because of the private inheritance but we would save the backwards
31 // pointer.
32
33 /** \defgroup protocol_group The Protocol Classes
34
35     \diaimage Protocols.dia
36
37     The socket handle classes and templates only implement the most important socket API methods
38     using the policy framework. To access the complete API, the protocol interface is
39     provided. Access to the protocol interface is only possible via senf::ProtocolClientSocketHandle
40     and senf::ProtocolServerSocketHandle which have the necessary \c protocol() member. This member
41     returns a reference to the protocol class instance which contains members covering all the API
42     functions (mostly setsockopt/getsockopt related calls but there may be more, this is completely
43     up to the implementor of the protocol class) not found in the SocketHandle interface. The
44     protocol interface is specific to the protocol. It's implementation is quite free. The standard
45     protocols are implemented using a simple multiple-inheritance hierarchy as shown above.
46
47     Since the protocol class is protocol specific (how intelligent ...), the protocol class also
48     defines the \e complete socket policy to be used with it's protocol. Complete meaning, that
49     every policy axis must be assigned it's the most specific (that is derived) policy class to be
50     used with the protocol and that no policy axis is allowed to be left unspecified.
51
52     \see
53         \ref handle_group \n
54         \ref policy_group
55  */
56
57 /** \defgroup concrete_protocol_group Protocol Implementations (Concrete Protocol Classes)
58     \ingroup protocol_group
59
60     Theese protocol classes define concrete and complete protocol implementations. They inherit from
61     ConcreteSocketProtocol and are used with the ProtocolClientSocketHandle and
62     ProtocolServerSocketHandle templates to instantiate socket handles. Appropriate typedefs are
63     always provided.
64
65     Every protocol defines both the protocol and the policy interface provided by that protocol. See
66     the documentation of the protocol classes listed below for more information on the supported
67     protocols. Every protocol class documents it's policy interface. Use the 'list all members' link
68     of the protocol class to find the complete policy interface.
69  */
70
71 /** \defgroup protocol_facets_group Protocol Facets
72     \ingroup protocol_group
73
74     The protocol facets are classes used as building blocks to build concrete protocol classes. Each
75     protocol facet will implement some functional part of the protocol interface. The protocol
76     facets all inherit from SocketProtocol by public \e virtual inheritance. This ensures the
77     accessibility of the socket body from all facets.
78  */
79
80 #ifndef HH_SENF_Socket_SocketProtocol_
81 #define HH_SENF_Socket_SocketProtocol_ 1
82
83 // Custom includes
84 #include <boost/utility.hpp>
85 // Hrmpf ... I have tried very hard, but I just can't find a nice, generic way to clean
86 // up this include
87 #include "SocketHandle.ih"
88
89 //#include "SocketProtocol.mpp"
90 ///////////////////////////////hh.p////////////////////////////////////////
91
92 namespace senf {
93
94     /// \addtogroup protocol_group
95     /// @{
96
97     class SocketPolicyBase;
98
99     /** \brief Socket Protocol base class
100
101         This is the base class of all socket protocol classes. Every protocol class must directly or
102         indirectly inherit from SocketProtocol
103
104         \attention SocketProtocol must \e always be inherited using public \e virtual inheritance.
105      */
106     class SocketProtocol
107         : boost::noncopyable
108     {
109     public:
110         ///////////////////////////////////////////////////////////////////////////
111         // Types
112
113         ///////////////////////////////////////////////////////////////////////////
114         ///\name Structors and default members
115         ///@{
116
117         SocketProtocol();
118         virtual ~SocketProtocol() = 0;
119
120         // default default constructor
121         // no copy
122         // no conversion constructors
123
124         ///@}
125         ///////////////////////////////////////////////////////////////////////////
126
127         virtual SocketPolicyBase const & policy() const = 0;
128         ///< Access the policy instance
129
130         ///////////////////////////////////////////////////////////////////////////
131         // Virtual interface
132
133         virtual unsigned available() const = 0;
134                                         ///< Return (maximum) number of bytes available for reading
135                                         ///< without < blocking
136                                         /**< This member will check in a (very, sigh) protocol
137                                              dependent way, how many bytes may be read from a socket
138                                              in a single (non-blocking) read operation. If the
139                                              socket does not support reading (viz. NotReadablePolicy
140                                              is set), this member should always return \c 0.
141
142                                              Depending on the protocol, it may not be possible to
143                                              return a good value. In this case, an upper bound may
144                                              be returned (e.g.: When reading from a socket which
145                                              returns ethernet frames, returning 1500 from
146                                              available() is ok). However, this should only be done
147                                              as a last resort. Also beware, that this number should
148                                              not be too large since the socket layer will always
149                                              need to allocate that number of bytes for the data to
150                                              be read. */
151
152         virtual bool eof() const = 0;   ///< Check for end-of-file condition
153                                         /**< This is another check which (like available()) is
154                                              extremely protocol dependent. This member will return
155                                              \c true only, if at end-of-file. If the protocol does
156                                              not support the notion of EOF, this member should
157                                              always return \c false. */
158
159         virtual void close();           ///< Close socket
160                                         /**< This override will automatically \c shutdown() the
161                                              socket whenever it is closed.
162                                              \throws senf::SystemException
163                                              \fixme Move into (at least) BSDSOcketProtocol */
164
165         virtual void terminate() const; ///< Forcibly close socket
166                                         /**< This override will automatically \c shutdown() the
167                                              socket whenever it is called. Additionally it will
168                                              disable SO_LINGER to ensure, that v_terminate will not
169                                              block. Like the overriden method, this member will ignore
170                                              failures and will never throw. It is therefore safe to be
171                                              called from a destructor.
172                                              \fixme Move into (at least) BSDSocketProtocol */
173
174         virtual void state(SocketStateMap & map, unsigned lod) const;
175                                         ///< Return socket state information
176                                         /**< This member is called to add state information to the
177                                              status \a map. The protocol map should provide as
178                                              detailed information as possible. The amount of
179                                              information to be added to the map is selected by the
180                                              \a lod value with a default value of 0. The
181                                              interpretation of the \a lod value is completely
182                                              implementation defined.
183
184                                              Every class derived from SocketProtocol should
185                                              reimplement state(). The reimplemented method should
186                                              call (all) baseclass-implementations of this
187                                              member.
188
189                                              The \a map Argument is a map which associates
190                                              std:string keys with std:string-like values. The map
191                                              keys are interpreted as hierarchical strings with '.'
192                                              as a separator (like hostnames or struct or class
193                                              members). They are automatically sorted correctly.
194
195                                              The values are std:string with one additional feature:
196                                              they allow assignment or conversion from *any* type as
197                                              long as that type is streamable. This simplifies
198                                              assigning non-string values to the map:
199
200                                              \code
201                                                  map["socket.protocol.ip.address"] << peer();
202                                                  map["socket.protocol.tcp.backlog"] << backlog();
203                                              \endcode
204
205                                              This will work even if peer() returns an ip-address
206                                              object or backlog() returns an integer. The values are
207                                              automatically converted to their string representation.
208
209                                              Additionally, if the slot the date is written to is not
210                                              empty, the <tt>\<\<</tt> operator will add add a comma
211                                              as separator. */
212
213     protected:
214         FileHandle fh() const;          ///< Get a FileHandle for this instance
215                                         /**< This member will re turn a FileHandle instance for this
216                                              protocol instance. You may cast this FileHandle
217                                              instance to a ClientSocketHandle / ServerSocketHandle
218                                              as long as you know some of the socket policy using
219                                              static_socket_cast or dynamic_socket_cast */
220
221         int fd() const;                 ///< Get file descriptor
222                                         /**< Returns the file descriptor this protocol instance
223                                              references. This is the same as <tt>fh().fd()</tt> but
224                                              is implemented here since it is needed so often. */
225
226         void fd(int) const;             ///< Initialize file descriptor
227                                         /**< Assigns the file descriptor to the file handle, this
228                                              protocol instance references. Only valid, if the file
229                                              handle has not yet been assigned any descriptor (To
230                                              change the file descriptor association later, use \c
231                                              ::dup2()). */
232
233     private:
234         virtual std::auto_ptr<SocketBody> clone(bool isServer) const = 0;
235         virtual std::auto_ptr<SocketBody> clone(int fd, bool isServer) const = 0;
236         virtual SocketBody & body() const = 0;
237
238         friend class SocketBody;
239     };
240
241     template <class SPolicy> class ClientSocketHandle;
242     template <class SPolicy> class ServerSocketHandle;
243
244     /** \brief Concrete Socket Protocol implementation base class
245
246         ConcreteSocketProtocol is the base class of a concrete socket protocol implementation. The
247         final protocol class must inherit from ConcreteSocketProtocol. The template argument \a
248         SocketPolicy must be set to the complete socket policy of the protocol. \a Self is the name
249         of the final protocol class which inherits this class.
250
251         A protocol implementation may define the protocol interface directly. It can also
252         (additionally) make use of multiple inheritance to combine a set of protocol facets into a
253         specific protocol implementation (i.e. TCPv4SocketProtocol inherits from
254         ConcreteSocketProtocol and from the protocol facets IPv4SocketProtocol, TCPSocketProtocol,
255         BSDSocketProtocol and AddressableBSDSocketProtocol). The protocol facets are not concrete
256         protocols themselves, they are combined to build concrete protocols. This structure will
257         remove a lot of code duplication. It is important to ensure, that the protocol facets do not
258         overlap, since otherwise there will be problems resolving overlapping members.
259
260         \doc init_client init_server
261      */
262     template <class SocketPolicy, class Self>
263     class ConcreteSocketProtocol
264         : public virtual SocketProtocol
265     {
266     public:
267         ///////////////////////////////////////////////////////////////////////////
268         // Types
269
270         typedef SocketPolicy Policy;    ///< The protocols policy
271
272         ///////////////////////////////////////////////////////////////////////////
273         ///\name Structors and default members
274         ///@{
275
276         ~ConcreteSocketProtocol() = 0;
277
278         // no default constructor
279         // no copy
280         // no conversion constructors
281
282         ///@}
283         ///////////////////////////////////////////////////////////////////////////
284
285         Policy const & policy() const;
286
287     protected:
288         ClientSocketHandle<Policy> clientHandle() const;
289                                         ///< Get client handle for associated socket
290                                         /**< Returns a client handle for the socket associated with
291                                              this protocol instance */
292         ServerSocketHandle<Policy> serverHandle() const;
293                                         ///< Get server handle for associated socket
294                                         /**< Returns a server handle for the socket associated with
295                                              this protocol instance */
296
297     private:
298         virtual std::auto_ptr<SocketBody> clone(bool isServer) const;
299         virtual std::auto_ptr<SocketBody> clone(int fd, bool isServer) const;
300         virtual SocketBody & body() const;
301
302         Policy policy_;
303     };
304
305     /// @}
306 }
307
308 ///////////////////////////////hh.e////////////////////////////////////////
309 #include "SocketProtocol.cci"
310 //#include "SocketProtocol.ct"
311 #include "SocketProtocol.cti"
312 #endif
313
314 \f
315 // Local Variables:
316 // mode: c++
317 // fill-column: 100
318 // c-file-style: "senf"
319 // indent-tabs-mode: nil
320 // ispell-local-dictionary: "american"
321 // compile-command: "scons -u test"
322 // comment-column: 40
323 // End: