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