Socket: BUGFIX: Move incorrect v-function call out of FileBody destructor
[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                                              \fixme Move into (at least) BSDSOcketProtocol */
179         
180         virtual void terminate() const; ///< Forcibly close socket
181                                         /**< This override will automatically \c shutdown() the
182                                              socket whenever it is called. Additionally it will
183                                              disable SO_LINGER to ensure, that v_terminate will not
184                                              block. Like the overriden method, this member will ignore
185                                              failures and will never throw. It is therefore safe to be
186                                              called from a destructor. 
187                                              \fixme Move into (at least) BSDSocketProtocol */
188
189         virtual void state(SocketStateMap & map, unsigned lod) const;
190                                         ///< Return socket state information
191                                         /**< This member is called to add state information to the
192                                              status \a map. The protocol map should provide as
193                                              detailed information as possible. The amount of
194                                              information to be added to the map is selected by the
195                                              \a lod value with a default value of 0. The
196                                              interpretation of the \a lod value is completely
197                                              implementation defined.
198                                              
199                                              Every class derived from SocketProtocol should
200                                              reimplement state(). The reimplemented method should
201                                              call (all) baseclass-implementations of this
202                                              member.
203
204                                              The \a map Argument is a map which associates
205                                              std:string keys with std:string-like values. The map
206                                              keys are interpreted as hierarchical strings with '.'
207                                              as a separator (like hostnames or struct or class
208                                              members). They are automatically sorted correctly.
209                                              
210                                              The values are std:string with one additional feature:
211                                              they allow assignment or conversion from *any* type as
212                                              long as that type is streamable. This simplifies
213                                              assigning non-string values to the map:
214                                              
215                                              \code
216                                                  map["socket.protocol.ip.address"] << peer();
217                                                  map["socket.protocol.tcp.backlog"] << backlog();
218                                              \endcode
219                                              
220                                              This will work even if peer() returns an ip-address
221                                              object or backlog() returns an integer. The values are
222                                              automatically converted to their string representation.
223                                              
224                                              Additionally, if the slot the date is written to is not
225                                              empty, the <tt>\<\<</tt> operator will add add a comma
226                                              as separator. */
227
228     protected:
229         FileHandle fh() const;          ///< Get a FileHandle for this instance
230                                         /**< This member will re turn a FileHandle instance for this
231                                              protocol instance. You may cast this FileHandle
232                                              instance to a ClientSocketHandle / ServerSocketHandle
233                                              as long as you know some of the socket policy using
234                                              static_socket_cast or dynamic_socket_cast */
235
236         int fd() const;                 ///< Get file descriptor
237                                         /**< Returns the file descriptor this protocol instance
238                                              references. This is the same as <tt>fh().fd()</tt> but
239                                              is implemented here since it is needed so often. */
240
241         void fd(int) const;             ///< Initialize file descriptor
242                                         /**< Assigns the file descriptor to the file handle, this
243                                              protocol instance references. Only valid, if the file
244                                              handle has not yet been assigned any descriptor (To
245                                              change the file descriptor association later, use \c
246                                              ::dup2()). */
247
248     private:
249         virtual std::auto_ptr<SocketBody> clone(bool isServer) const = 0;
250         virtual std::auto_ptr<SocketBody> clone(int fd, bool isServer) const = 0;
251         virtual SocketBody & body() const = 0;
252
253         friend class SocketBody;
254     };
255     
256     template <class SPolicy> class ClientSocketHandle;
257     template <class SPolicy> class ServerSocketHandle;
258
259     /** \brief Concrete Socket Protocol implementation base class
260
261         ConcreteSocketProtocol is the base class of a concrete socket protocol implementation. The
262         final protocol class must inherit from ConcreteSocketProtocol. The template argument \a
263         SocketPolicy must be set to the complete socket policy of the protocol. \a Self is the name
264         of the final protocol class which inherits this class.
265
266         A protocol implementation may define the protocol interface directly. It can also
267         (additionally) make use of multiple inheritance to combine a set of protocol facets into a
268         specific protocol implementation (i.e. TCPv4SocketProtocol inherits from
269         ConcreteSocketProtocol and from the protocol facets IPv4Protocol, TCPProtocol,
270         BSDSocketProtocol and AddressableBSDSocketProtocol). The protocol facets are not concrete
271         protocols themselves, they are combined to build concrete protocols. This structure will
272         remove a lot of code duplication. It is important to ensure, that the protocol facets do not
273         overlap, since otherwise there will be problems resolving overlapping members.
274         
275         \doc init_client init_server
276      */
277     template <class SocketPolicy, class Self>
278     class ConcreteSocketProtocol
279         : public virtual SocketProtocol
280     {
281     public:
282         ///////////////////////////////////////////////////////////////////////////
283         // Types
284
285         typedef SocketPolicy Policy;    ///< The protocols policy
286
287         ///////////////////////////////////////////////////////////////////////////
288         ///\name Structors and default members
289         ///@{
290
291         ~ConcreteSocketProtocol() = 0;
292
293         // no default constructor
294         // no copy
295         // no conversion constructors
296
297         ///@}
298         ///////////////////////////////////////////////////////////////////////////
299
300         Policy const & policy() const;
301         
302     protected:
303         ClientSocketHandle<Policy> clientHandle() const; 
304                                         ///< Get client handle for associated socket
305                                         /**< Returns a client handle for the socket associated with
306                                              this protocol instance */
307         ServerSocketHandle<Policy> serverHandle() const;
308                                         ///< Get server handle for associated socket
309                                         /**< Returns a server handle for the socket associated with
310                                              this protocol instance */
311
312     private:
313         virtual std::auto_ptr<SocketBody> clone(bool isServer) const;
314         virtual std::auto_ptr<SocketBody> clone(int fd, bool isServer) const;
315         virtual SocketBody & body() const;
316
317         Policy policy_;
318     };
319
320     /// @}
321 }
322
323 ///////////////////////////////hh.e////////////////////////////////////////
324 #include "SocketProtocol.cci"
325 //#include "SocketProtocol.ct"
326 #include "SocketProtocol.cti"
327 #endif
328
329 \f
330 // Local Variables:
331 // mode: c++
332 // fill-column: 100
333 // c-file-style: "senf"
334 // indent-tabs-mode: nil
335 // ispell-local-dictionary: "american"
336 // compile-command: "scons -u test"
337 // comment-column: 40
338 // End: