Move include files in debian packge into 'senf' subdirectory
[senf.git] / Packets / Packet.hh
1 // Copyright (C) 2007 
2 // Fraunhofer Institut fuer offene Kommunikationssysteme (FOKUS)
3 // Kompetenzzentrum fuer Satelitenkommunikation (SatCom)
4 //     Stefan Bund <g0dil@berlios.de>
5 //
6 // This program is free software; you can redistribute it and/or modify
7 // it under the terms of the GNU General Public License as published by
8 // the Free Software Foundation; either version 2 of the License, or
9 // (at your option) any later version.
10 //
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 // GNU General Public License for more details.
15 //
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the
18 // Free Software Foundation, Inc.,
19 // 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
20
21 /** \file
22     \brief Packet public header */
23
24 #ifndef HH_Packet_
25 #define HH_Packet_ 1
26
27 // Custom includes
28 #include <boost/operators.hpp>
29
30 #include "../Utils/Exception.hh"
31 #include "../Utils/SafeBool.hh"
32 #include "PacketInterpreter.hh"
33
34 //#include "Packet.mpp"
35 ///////////////////////////////hh.p////////////////////////////////////////
36
37 namespace senf {
38
39     /** \defgroup packet_module Packet Handling
40
41         The basic groundwork of the Packet library is the packet handling:
42
43         \li The packet classes provide access to a chain of packet headers (more generically called
44             interpreters).
45         \li They automatically manage the required memory resources and the shared packet data.
46
47         \section packet_module_chain The Interpreter Chain
48
49         The central data structure for a packet is the interpreter chain
50
51         \image html structure.png The Interpreter Chain
52
53         This image depicts a packet with several headers. Each interpreter is responsible for a
54         specific sub-range of the complete packet. This range always \e includes the packets payload
55         (This is, why we call the data structure interpreter and not header: The interpreter is
56         responsible for interpreting a range of the packet according to a specific protocol), the
57         packet interpreters are nested inside each other.
58     
59         For each interpreter, this structure automatically divides the packet into three areas (each
60         of which are optional): The header, the payload and the trailer. Every packet will have
61         either a header or a payload section while most don't have a trailer.
62
63         As user of the library you always interact with the chain through one (or more) of the
64         interpreters. The interpreter provides methods to traverse to the following or preceding
65         header (interpreter) and provides two levels of access to the packet data: Generic low-level
66         access in the form of an STL compatible sequence and access to the parsed fields which are
67         provided by the parser associated with the concrete packet type.
68
69         \section packet_module_management Resource Management
70
71         The interface to the packet library is provided using a handle class (\ref Packet for
72         generic, protocol agnostic access and \ref ConcretePacket derived from \ref Packet to access
73         a specific protocol). This handle automatically manages the resources associated with the
74         packet (the interpreter chain and the data storage holding the packet data). The resources
75         are automatically released when the last packet handle referencing a specific packet is
76         destroyed.
77
78         \implementation The packet chain is provided on two levels: The internal representation \ref
79             PacketInterpreterBase and \ref PacketInterpreter which are referenced by the Handle
80             classes \ref Packet and \ref ConcretePacket. \n
81             The internal representation classes are pertinent in the sense, that they exist
82             regardless of the existence of a handle referencing them (as long as the packet
83             exists). Still the interpreter chain is lazy and packet interpreters beside the first
84             are only created dynamically when accessed (this is implemented in the handle not in the
85             internal representation). \n
86             The packet interpreters make use of a pool allocator. This provides extremely efficient
87             creation and destruction of packet interpreter's and removes the dynamic memory
88             management overhead from the packet interpreter management. The packet implementation
89             class (\ref PacketImpl which holds the packet data itself) however is still dynamically
90             managed (however there is only a single instance for each packet).
91      */
92
93     template <class PackeType> class ConcretePacket;
94
95     ///\addtogroup packet_module
96     ///@{
97     
98     /** \brief Main Packet class
99
100         Packet is the main externally visible class of the packet library. Packet is a handle into
101         the internal packet representation. From Packet you may access the data of that specific
102         sub-packet/header/interpreter and navigate to the neighboring
103         sub-packets/headers/interpreters.
104
105         Packet is protocol agnostic. This class only provides non-protocol dependent members. To
106         access the protocol specific features of a packet (like header fields) the ConcretePacket
107         class extending Packet is provided.
108
109         \section packet_semantics Semantics
110         
111         All operations accessing the data of \c this packet in some way will ignore any preceding
112         packets/headers/interpreters in the chain. It does not matter, whether a given packet is
113         taken from the middle or the beginning of the chain, all operations (except those explicitly
114         accessing the chain of course) should work the same.
115         
116         This especially includes members like clone() or append(): clone() will clone \e only from
117         \c this packet until the end of the chain, append() will append the given packet \e ignoring
118         any possibly preceding packets/headers/interpreters.
119
120         In the same way, the data() member provides an STL-sequence compatible view of the packet
121         data. This only includes the data which is part of \c this packet including header, trailer
122         \e and payload but \e not the headers or trailers of packets \e before \c this packet in the
123         packet/header/interpreter chain (nonetheless, this data overlaps with the data of other
124         packets).
125
126         Several members are member templates taking an \a OtherPacket template parameter. This
127         parameter must be the ConcretePacket instantiation associated with some concrete packet type
128         (protocol). For each implemented protocol, typedefs should be provided for these
129         instantiations (Example: \ref EthernetPacket is a typedef for
130         \ref ConcretePacket < \ref EthernetPacketType >).
131
132         \see 
133             \ref ConcretePacket for the type specific interface\n
134             \ref PacketData for the sequence interface\n
135             \ref packetparser for a specification of the parser interface
136       */
137     class Packet
138         : public SafeBool<Packet>,
139           public boost::equality_comparable<Packet>
140     {
141     public:
142         ///////////////////////////////////////////////////////////////////////////
143         // Types
144         
145         typedef void type;              ///< Type of the packet.
146         typedef senf::detail::packet::size_type size_type; ///< Unsigned type to represent packet size
147         typedef PacketInterpreterBase::factory_t factory_t; ///< Packet factory type (see below)
148
149                                         /// Special argument flag
150                                         /** Used in some ConcretePacket constructors */
151         enum NoInit_t { noinit };       
152
153         ///////////////////////////////////////////////////////////////////////////
154         ///\name Structors and default members
155         ///@{
156
157         // default copy constructor
158         // default copy assignment
159         // default destructor
160         
161         Packet();                       ///< Create uninitialized packet handle
162                                         /**< An uninitialized handle is not valid(). It does not
163                                              allow any operation except assignment and checking for
164                                              validity. */
165         Packet clone() const;           ///< Create copy packet
166                                         /**< clone() will create a complete copy the packet. The
167                                              returned packet will have the same data and packet
168                                              chain. It does however not share any data with the
169                                              original packet. */
170
171         // conversion constructors
172
173         template <class PacketType>     
174         Packet(ConcretePacket<PacketType> packet); ///< Copy-construct Packet from ConcretePacket
175                                         /**< This constructor allows to convert an arbitrary
176                                              ConcretePacket into a general Packet, loosing the
177                                              protocol specific interface. */
178
179         ///@}
180         ///////////////////////////////////////////////////////////////////////////
181
182         ///\name Interpreter chain access
183         ///@{
184
185                                      Packet      next() const; 
186                                         ///< Get next packet in chain
187         template <class OtherPacket> OtherPacket next() const; 
188                                         ///< Get next packet of given type in chain
189                                         /**< \throws InvalidPacketChainException if no such packet
190                                              is found */
191         template <class OtherPacket> OtherPacket next(NoThrow_t) const; 
192                                         ///< Get next packet of given type in chain
193                                         /**< \param[in] nothrow This argument always has the value
194                                              \c senf::nothrow
195                                              \returns in-valid() packet, if no such packet is found */
196         template <class OtherPacket> OtherPacket findNext() const;
197                                         ///< Find next packet of given type in chain
198                                         /**< findNext() is like next(), it will however return \c
199                                              *this if it is of the given type. 
200                                              \throws InvalidPacketChainException if no such packet
201                                                  is found */
202         template <class OtherPacket> OtherPacket findNext(NoThrow_t) const;
203                                         ///< Find next packet of given type in chain
204                                         /**< findNext() is like next(), it will however return \c
205                                              *this if it is of the given type.
206                                              \param[in] nothrow This argument always has the value
207                                              \c senf::nothrow
208                                              \returns in-valid() packet, if no such packet is found */
209         
210
211                                      Packet      prev() const; 
212                                         ///< Get previous packet in chain
213         template <class OtherPacket> OtherPacket prev() const; 
214                                         ///< Get previous packet of given type in chain
215                                         /**< \throws InvalidPacketChainException if no such packet
216                                              is found */
217         template <class OtherPacket> OtherPacket prev(NoThrow_t) const;
218                                         ///< Get previous packet of given type in chain
219                                         /**< \param[in] nothrow This argument always has the value
220                                              \c senf::nothrow
221                                              \returns in-valid() packet, if no such packet is found */
222         template <class OtherPacket> OtherPacket findPrev() const;
223                                         ///< Find previous packet of given type in chain
224                                         /**< findPrev() is like prev(), it will however return \c
225                                              *this if it is of the type 
226                                              \throws InvalidPacketChainException if no such packet
227                                                  is found */
228         template <class OtherPacket> OtherPacket findPrev(NoThrow_t) const;
229                                         ///< Find previous packet of given type in chain
230                                         /**< findPrev() is like prev(), it will however return \c
231                                              *this if it is of the type 
232                                              \param[in] nothrow This argument always has the value
233                                              \c senf::nothrow
234                                              \returns in-valid() packet, if no such packet is found */
235
236
237                                      Packet      first() const;
238                                         ///< Return first packet in chain
239         template <class OtherPacket> OtherPacket first() const;
240                                         ///< Return first packet of given type in chain
241                                         /**< \throws InvalidPacketChainException if no such packet
242                                              is found */
243         template <class OtherPacket> OtherPacket first(NoThrow_t) const;
244                                         ///< Return first packet of given type in chain
245                                         /**< \param[in] nothrow This argument always has the value
246                                              \c senf::nothrow
247                                              \returns in-valid() packet, if no such packet is found */
248
249                                      Packet      last() const;
250                                         ///< Return last packet in chain
251         template <class OtherPacket> OtherPacket last() const;
252                                         ///< Return last packet of given type in chain
253                                         /**< \throws InvalidPacketChainException if no such packet
254                                              is found */
255         template <class OtherPacket> OtherPacket last(NoThrow_t) const;
256                                         ///< Return last packet of given type in chain
257                                         /**< \param[in] nothrow This argument always has the value
258                                              \c senf::nothrow
259                                              \returns in-valid() packet, if no such packet is found */
260
261
262         template <class OtherPacket> OtherPacket parseNextAs() const;
263                                         ///< Parse payload as given by \a OtherPacket and add packet
264                                         /**< parseNextAs() will throw away the packet chain after
265                                              the current packet if necessary. It will then parse the
266                                              payload section of \c this packet as given by \a
267                                              OtherPacket. The new packet is added to the chain after
268                                              \c this.
269                                              \returns new packet instance sharing the same data and
270                                                  placed after \c this packet in the chain. */
271                                      Packet      parseNextAs(factory_t factory) const;
272                                         ///< Parse payload as given by \a factory and add packet
273                                         /**< parseNextAs() will throw away the packet chain after
274                                              the current packet if necessary. It will then parse the
275                                              payload section of \c this packet as given by \a
276                                              OtherPacket. The new packet is added to the chain after
277                                              \c this.
278                                              \returns new packet instance sharing the same data and
279                                                  placed after \c this packet in the chain. */
280         template <class OtherPacket> bool        is() const;
281                                         ///< Check, whether \c this packet is of the given type
282         template <class OtherPacket> OtherPacket as() const;
283                                         ///< Cast current packet to the given type
284                                         /**< This operations returns a handle to the same packet
285                                              header/interpreter however cast to the given
286                                              ConcretePacket type. <b>This conversion is
287                                              unchecked</b>. If the packet really is of a different
288                                              type, this will wreak havoc with the packet
289                                              data-structures. You can validate whether the
290                                              conversion is valid using is(). */
291
292         Packet append(Packet packet) const; ///< Append the given packet to \c this packet
293                                         /**< This operation will replace the payload section of \c
294                                              this packet with \a packet. This operation will replace
295                                              the packet chain after \c this packet with a clone of
296                                              \a packet and will replace the raw data of the payload
297                                              of \c this with the raw data if \a packet.
298                                              \returns Packet handle to the cloned \a packet, placed
299                                                  after \c this in the packet/header/interpreter
300                                                  chain. */
301
302         ///@}
303
304         ///\name Data access
305         ///@{
306
307         PacketData & data() const;      ///< Access the packets raw data container
308         size_type size() const;         ///< Return size of packet in bytes
309                                         /**< This size does \e not include the size of any preceding
310                                              headers/packets/interpreters. It does however include
311                                              \c this packets payload. */
312         
313         ///@}
314
315         ///\name Other methods
316         ///@{
317
318         bool operator==(Packet other) const; ///< Check for packet identity
319                                         /**< Two packet handles compare equal if they really are the
320                                              same packet header in the same packet chain. */
321         bool boolean_test() const;      ///< Check, whether the packet is valid()
322                                         /**< \see valid() */
323         bool valid() const;             ///< Check, whether the packet is valid()
324                                         /**< An in-valid() packet does not allow any operation
325                                              except checking for validity and assignment. in-valid()
326                                              packets serve the same role as 0-pointers. */
327         
328
329         void finalize() const;          ///< Update calculated fields
330                                         /**< This call will update all calculated fields of the
331                                              packet after it has been created or changed. This
332                                              includes checksums, payload size fields or other
333                                              fields, which can be set from other information in the
334                                              packet. Each concrete packet type should document,
335                                              which fields are set by finalize().
336
337                                              finalize() will automatically process all
338                                              packets/headers/interpreters from the end of the chain
339                                              backwards up to \c this. */
340
341         void dump(std::ostream & os) const; ///< Write out a printable packet representation
342                                         /**< This method is provided mostly to help debugging packet
343                                              problems. Each concrete packet should implement a dump
344                                              method writing out all fields of the packet in a
345                                              readable representation. dump() will call this member
346                                              for each packet/header/interpreter in the chain from \c
347                                              this packet up to the end of the chain. */
348
349         TypeIdValue typeId() const;     ///< Get id of \c this packet
350                                         /**< This value is used e.g. in the packet registry to
351                                              associate packet types with other information.
352                                              \returns A type holding the same information as a
353                                                  type_info object, albeit assignable */
354         factory_t factory() const;      ///< Return factory instance of \c this packet
355                                         /**< The returned factory instance can be used to create new
356                                              packets of the given type without knowing the concrete
357                                              type of the packet. The value may be stored away for
358                                              later use if needed. */
359         
360         ///@}
361
362     protected:
363         explicit Packet(PacketInterpreterBase::ptr packet);
364
365         PacketInterpreterBase::ptr ptr() const;
366
367     private:
368         Packet checkNext() const;
369         Packet checkLast() const;
370         
371         PacketInterpreterBase::ptr packet_;
372         
373         template <class PacketType>
374         friend class ConcretePacket;
375     };
376
377     /** \brief Protocol specific packet handle
378
379         The ConcretePacket template class extends Packet to provide protocol/packet type specific
380         aspects. These are packet constructors and access to the parsed packet fields.
381
382         The \c PacketType template argument to ConcretePacket is a protocol specific and internal
383         policy class which defines the protocol specific behavior. To access a specific type of
384         packet, the library provides corresponding typedefs of ConcretePacket < \a SomePacketType >
385         (e.g. \ref EthernetPacket as typedef for \ref ConcretePacket < \ref EthernetPacketType >).
386
387         The new members provided by ConcretePacket over packet are mostly comprised of the packet
388         constructors. These come in three major flavors:
389         
390         \li The create() family of constructors will create completely new packets.
391         \li The createAfter() family of constructors will create new packets (with new data for the
392             packet) \e after a given existing packet.
393         \li The createBefore()  family of constructors will create new packets (again with new data)
394             \e before a given existing packet.
395         
396         Whereas create() will create a completely new packet with it's own chain and data storage,
397         createAfter() and createBefore() extend a packet with additional
398         headers/interpreters. createAfter() will set the payload of the given packet to the new
399         packet whereas createBefore() will create a new packet with the existing packet as it's
400         payload. 
401
402         createAfter() differs from Packet::parseNextAs() in that the former creates a new packet \e
403         replacing any possibly existing data whereas the latter will interpret the already \e
404         existing data as given by the type argument.
405         
406         \see \ref PacketTypeBase for a specification of the interface to be provided by the \a
407             PacketType policy class.
408       */
409     template <class PacketType>
410     class ConcretePacket 
411         : public Packet
412     {
413     public:
414         ///////////////////////////////////////////////////////////////////////////
415         // Types
416         
417         typedef PacketType type;
418
419         ///////////////////////////////////////////////////////////////////////////
420         ///\name Structors and default members
421         ///@{
422
423         // default copy constructor
424         // default copy assignment
425         // default destructor
426         // no conversion constructors
427
428         ConcretePacket();               ///< Create uninitialized packet handle
429                                         /**< An uninitialized handle is not valid(). It does not
430                                              allow any operation except assignment and checking for
431                                              validity. */
432
433         static factory_t factory();     ///< Return factory for packets of specific type
434                                         /**< This \e static member is like Packet::factory() for a
435                                              specific packet of type \a PacketType */
436
437         // Create completely new packet
438
439         static ConcretePacket create(); ///< Create default initialized packet
440                                         /**< The packet will be initialized to it's default empty
441                                              state. */
442         static ConcretePacket create(NoInit_t); ///< Create uninitialized empty packet
443                                         /**< This will create a completely empty and uninitialized
444                                              packet with <tt>size() == 0</tt>.
445                                              \param[in] noinit This parameter must always have the
446                                                  value \c senf::noinit. */
447         static ConcretePacket create(size_type size); ///< Create default initialized packet
448                                         /**< This member will create a default initialized packet
449                                              with the given size. If the size parameter is smaller
450                                              than the minimum allowed packet size an exception will
451                                              be thrown.
452                                              \param[in] size Size of the packet to create in bytes.
453                                              \throws TruncatedPacketException if \a size is smaller
454                                                  than the smallest permissible size for this type of
455                                                  packet. */
456         static ConcretePacket create(size_type size, NoInit_t); ///< Create uninitialized packet
457                                         /**< Creates an uninitialized (all-zero) packet of the exact
458                                              given size. 
459                                              \param[in] size Size of the packet to create in bytes
460                                              \param[in] noinit This parameter must always have the
461                                                  value \c senf::noinit. */
462         template <class ForwardReadableRange>
463         static ConcretePacket create(ForwardReadableRange const & range); 
464                                         ///< Create packet from given data
465                                         /**< The packet will be created from a copy of the given
466                                              data. The data from the range will be copied directly
467                                              into the packet representation. The data will \e not be
468                                              validated in any way.
469                                              \param[in] range <a
470                                                  href="http://www.boost.org/libs/range/index.html">Boost.Range</a> 
471                                                  of data to construct packet from. */
472
473         // Create packet as new packet after a given packet
474
475         static ConcretePacket createAfter(Packet packet); 
476                                         ///< Create default initialized packet after \a packet
477                                         /**< The packet will be initialized to it's default empty
478                                              state. It will be appended as next header/interpreter
479                                              after \a packet in that packets interpreter chain.
480                                              \param[in] packet Packet to append new packet to. */
481         static ConcretePacket createAfter(Packet packet, NoInit_t);
482                                         ///< Create uninitialized empty packet after\a packet
483                                         /**< This will create a completely empty and uninitialized
484                                              packet with <tt>size() == 0</tt>. It will be appended
485                                              as next header/interpreter after \a packet in that
486                                              packets interpreter chain.
487                                              \param[in] packet Packet to append new packet to.
488                                              \param[in] noinit This parameter must always have the
489                                                  value \c senf::noinit. */
490         static ConcretePacket createAfter(Packet packet, size_type size);
491                                         ///< Create default initialized packet after \a packet
492                                         /**< This member will create a default initialized packet
493                                              with the given size. If the size parameter is smaller
494                                              than the minimum allowed packet size an exception will
495                                              be thrown. It will be appended as next
496                                              header/interpreter after \a packet in that packets
497                                              interpreter chain.
498                                              \param[in] packet Packet to append new packet to.
499                                              \param[in] size Size of the packet to create in bytes.
500                                              \throws TruncatedPacketException if \a size is smaller
501                                                  than the smallest permissible size for this type of
502                                                  packet. */
503         static ConcretePacket createAfter(Packet packet, size_type size, NoInit_t);
504                                         ///< Create uninitialized packet after \a packet
505                                         /**< Creates an uninitialized (all-zero) packet of the exact
506                                              given size.  It will be appended as next
507                                              header/interpreter after \a packet in that packets
508                                              interpreter chain.
509                                              \param[in] packet Packet to append new packet to.
510                                              \param[in] size Size of the packet to create in bytes
511                                              \param[in] noinit This parameter must always have the
512                                                  value \c senf::noinit. */
513         template <class ForwardReadableRange>
514         static ConcretePacket createAfter(Packet packet, 
515                                           ForwardReadableRange const & range);
516                                         ///< Create packet from given data after \a packet
517                                         /**< The packet will be created from a copy of the given
518                                              data. The data from the range will be copied directly
519                                              into the packet representation. The data will \e not be
520                                              validated in any way.  It will be appended as next
521                                              header/interpreter after \a packet in that packets
522                                              interpreter chain.
523                                              \param[in] packet Packet to append new packet to.
524                                              \param[in] range <a
525                                                  href="http://www.boost.org/libs/range/index.html">Boost.Range</a> 
526                                                  of data to construct packet from. */
527
528         // Create packet as new packet (header) before a given packet
529
530         static ConcretePacket createBefore(Packet packet); 
531                                         ///< Create default initialized packet before \a packet
532                                         /**< The packet will be initialized to it's default empty
533                                              state. It will be prepended as previous
534                                              header/interpreter before \a packet in that packets
535                                              interpreter chain.
536                                              \param[in] packet Packet to prepend new packet to. */
537         static ConcretePacket createBefore(Packet packet, NoInit_t);
538                                         ///< Create uninitialized empty packet before \a packet
539                                         /**< Creates a completely empty and uninitialized packet. It
540                                              will be prepended as previous header/interpreter before
541                                              \a packet in that packets interpreter chain.
542                                              \param[in] packet Packet to prepend new packet to. */
543         
544         // Create a clone of the current packet
545
546         ConcretePacket clone() const;
547
548         ///@}
549         ///////////////////////////////////////////////////////////////////////////
550
551         // Field access
552
553         typename type::parser * operator->() const; ///< Access packet fields
554                                         /**< This operator allows to access the parsed fields of the
555                                              packet using the notation <tt>packet->field()</tt>. The
556                                              fields of the packet are specified by the PacketType's
557                                              \c parser member. 
558
559                                              The members are not strictly restricted to simple field
560                                              access. The parser class may have any member which is
561                                              needed for full packet access (e.g. checksum validation
562                                              / recreation ...)
563                                              \see \ref packetparser for the parser interface. */
564
565     protected:
566
567     private:
568         typedef PacketInterpreter<PacketType> interpreter;
569
570         ConcretePacket(typename interpreter::ptr packet_);
571         
572         typename interpreter::ptr ptr() const;
573
574         friend class Packet;
575         friend class PacketInterpreter<PacketType>;
576     };
577
578     ///@}
579
580 }
581
582 ///////////////////////////////hh.e////////////////////////////////////////
583 #endif
584 #if !defined(SENF_PACKETS_DECL_ONLY) && !defined(HH_Packet_i_)
585 #define HH_Packet_i_
586 #include "Packet.cci"
587 #include "Packet.ct"
588 #include "Packet.cti"
589 #endif
590
591 \f
592 // Local Variables:
593 // mode: c++
594 // fill-column: 100
595 // c-file-style: "senf"
596 // indent-tabs-mode: nil
597 // ispell-local-dictionary: "american"
598 // compile-command: "scons -u test"
599 // comment-column: 40
600 // End:
601