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