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