Packets: BUGFIX: ensure complete interpreter chain in finalize()
[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 povided.
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     class Packet
133         : public SafeBool<Packet>,
134           public boost::equality_comparable<Packet>
135     {
136     public:
137         ///////////////////////////////////////////////////////////////////////////
138         // Types
139         
140         typedef void type;              ///< Type of the packet.
141         typedef senf::detail::packet::size_type size_type; ///< Unsigned type to represent packet size
142         typedef PacketInterpreterBase::factory_t factory_t; ///< Packet factory type (see below)
143
144                                         /// Special argument flag
145                                         /** Used in some ConcretePacket constructors */
146         enum NoInit_t { noinit };       
147
148         ///////////////////////////////////////////////////////////////////////////
149         ///\name Structors and default members
150         ///@{
151
152         // default copy constructor
153         // default copy assignment
154         // default destructor
155         
156         Packet();                       ///< Create uninitialized packet handle
157                                         /**< An uninitialized handle is not valid(). It does not
158                                              allow any operation except assignment and checking for
159                                              validity. */
160         Packet clone() const;           ///< Create copy packet
161                                         /**< clone() will create a complete copy the packet. The
162                                              returned packet will have the same data and packet
163                                              chain. It does however not share any data with the
164                                              original packet. */
165
166         // conversion constructors
167
168         template <class PacketType>     
169         Packet(ConcretePacket<PacketType> packet); ///< Copy-construct Packet from ConcretePacket
170                                         /**< This constructor allows to convert an arbitrary
171                                              ConcretePacket into a general Packet, loosing the
172                                              protocol specific interface. */
173
174         ///@}
175         ///////////////////////////////////////////////////////////////////////////
176
177         ///\name Interpreter chain access
178         ///@{
179
180                                      Packet      next() const; 
181                                         ///< Get next packet in chain
182         template <class OtherPacket> OtherPacket next() const; 
183                                         ///< Get next packet of given type in chain
184                                         /**< \throws InvalidPacketChainException if no such packet
185                                              is found */
186         template <class OtherPacket> OtherPacket next(NoThrow_t) const; 
187                                         ///< Get next packet of given type in chain
188                                         /**< \param[in] nothrow This argument always has the value
189                                              \c senf::nothrow
190                                              \returns in-valid() packet, if no such packet is found */
191         template <class OtherPacket> OtherPacket findNext() const;
192                                         ///< Find next packet of given type in chain
193                                         /**< findNext() is like next(), it will however return \c
194                                              *this if it is of the given type. 
195                                              \throws InvalidPacketChainException if no such packet
196                                                  is found */
197         template <class OtherPacket> OtherPacket findNext(NoThrow_t) const;
198                                         ///< Find next packet of given type in chain
199                                         /**< findNext() is like next(), it will however return \c
200                                              *this if it is of the given type.
201                                              \param[in] nothrow This argument always has the value
202                                              \c senf::nothrow
203                                              \returns in-valid() packet, if no such packet is found */
204         
205
206                                      Packet      prev() const; 
207                                         ///< Get previous packet in chain
208         template <class OtherPacket> OtherPacket prev() const; 
209                                         ///< Get previous packet of given type in chain
210                                         /**< \throws InvalidPacketChainException if no such packet
211                                              is found */
212         template <class OtherPacket> OtherPacket prev(NoThrow_t) const;
213                                         ///< Get previous packet of given type in chain
214                                         /**< \param[in] nothrow This argument always has the value
215                                              \c senf::nothrow
216                                              \returns in-valid() packet, if no such packet is found */
217         template <class OtherPacket> OtherPacket findPrev() const;
218                                         ///< Find previous packet of given type in chain
219                                         /**< findPrev() is like prev(), it will however return \c
220                                              *this if it is of the type 
221                                              \throws InvalidPacketChainException if no such packet
222                                                  is found */
223         template <class OtherPacket> OtherPacket findPrev(NoThrow_t) const;
224                                         ///< Find previous packet of given type in chain
225                                         /**< findPrev() is like prev(), it will however return \c
226                                              *this if it is of the type 
227                                              \param[in] nothrow This argument always has the value
228                                              \c senf::nothrow
229                                              \returns in-valid() packet, if no such packet is found */
230
231
232                                      Packet      first() const;
233                                         ///< Return first packet in chain
234         template <class OtherPacket> OtherPacket first() const;
235                                         ///< Return first packet of given type in chain
236                                         /**< \throws InvalidPacketChainException if no such packet
237                                              is found */
238         template <class OtherPacket> OtherPacket first(NoThrow_t) const;
239                                         ///< Return first packet of given type in chain
240                                         /**< \param[in] nothrow This argument always has the value
241                                              \c senf::nothrow
242                                              \returns in-valid() packet, if no such packet is found */
243
244                                      Packet      last() const;
245                                         ///< Return last packet in chain
246         template <class OtherPacket> OtherPacket last() const;
247                                         ///< Return last packet of given type in chain
248                                         /**< \throws InvalidPacketChainException if no such packet
249                                              is found */
250         template <class OtherPacket> OtherPacket last(NoThrow_t) const;
251                                         ///< Return last packet of given type in chain
252                                         /**< \param[in] nothrow This argument always has the value
253                                              \c senf::nothrow
254                                              \returns in-valid() packet, if no such packet is found */
255
256
257         template <class OtherPacket> OtherPacket parseNextAs() const;
258                                         ///< Parse payload as given by \a OtherPacket and add packet
259                                         /**< parseNextAs() will throw away the packet chain after
260                                              the current packet if necessary. It will then parse the
261                                              payload section of \c this packet as given by \a
262                                              OtherPacket. The new packet is added to the chain after
263                                              \c this.
264                                              \returns new packet instance sharing the same data and
265                                                  placed after \c this packet in the chain. */
266                                      Packet      parseNextAs(factory_t factory) const;
267                                         ///< Parse payload as given by \a factory and add packet
268                                         /**< parseNextAs() will throw away the packet chain after
269                                              the current packet if necessary. It will then parse the
270                                              payload section of \c this packet as given by \a
271                                              OtherPacket. The new packet is added to the chain after
272                                              \c this.
273                                              \returns new packet instance sharing the same data and
274                                                  placed after \c this packet in the chain. */
275         template <class OtherPacket> bool        is() const;
276                                         ///< Check, whether \c this packet is of the given type
277         template <class OtherPacket> OtherPacket as() const;
278                                         ///< Cast current packet to the given type
279                                         /**< This operations returns a handle to the same packet
280                                              header/interpreter however cast to the given
281                                              ConcretePacket type. <b>This conversion is
282                                              unchecked</b>. If the packet really is of a different
283                                              type, this will wreak havoc with the packet
284                                              data-structures. You can validate whether the
285                                              conversion is valid using is(). */
286
287         Packet append(Packet packet) const; ///< Append the given packet to \c this packet
288                                         /**< This operation will replace the payload section of \c
289                                              this packet with \a packet. This operation will replace
290                                              the packet chain after \c this packet with a clone of
291                                              \a packet and will replace the raw data of the payload
292                                              of \c this with the raw data if \a packet.
293                                              \returns Packet handle to the cloned \a packet, placed
294                                                  after \c this in the packet/header/interpreter
295                                                  chain. */
296
297         ///@}
298
299         ///\name Data access
300         ///@{
301
302         PacketData & data() const;      ///< Access the packets raw data container
303         size_type size() const;         ///< Return size of packet in bytes
304                                         /**< This size does \e not include the size of any preceding
305                                              headers/packets/interpreters. It does however include
306                                              \c this packets payload. */
307         
308         ///@}
309
310         ///\name Other methods
311         ///@{
312
313         bool operator==(Packet other) const; ///< Check for packet identity
314                                         /**< Two packet handles compare equal if they really are the
315                                              same packet header in the same packet chain. */
316         bool boolean_test() const;      ///< Check, whether the packet is valid()
317                                         /**< \see valid() */
318         bool valid() const;             ///< Check, whether the packet is valid()
319                                         /**< An in-valid() packet does not allow any operation
320                                              except checking vor validity and assignment. in-valid()
321                                              packets serve the same role as 0-pointers. */
322         
323
324         void finalize() const;          ///< Update calculated fields
325                                         /**< This call will update all calculated fields of the
326                                              packet after it has been created or changed. This
327                                              includes checksums, payload size fields or other
328                                              fields, which can be set from other information in the
329                                              packet. Each concrete packet type should document,
330                                              which fields are set by finalize().
331
332                                              finalize() will automatically process all
333                                              packets/headers/interpreters from the end of the chain
334                                              backwards up to \c this. */
335
336         void dump(std::ostream & os) const; ///< Write out a printable packet representation
337                                         /**< This method is provided mostly to help debugging packet
338                                              problems. Each concrete packet should implement a dump
339                                              method writing out all fields of the packet in a
340                                              readable reresentation. dump() will call this member
341                                              for each packet/header/interpreter in the chain from \c
342                                              this packet up to the end of the chain. */
343
344         TypeIdValue typeId() const;     ///< Get id of \c this packet
345                                         /**< This value is used e.g. in the packet registry to
346                                              associate packet types with other information.
347                                              \returns A type holding the same information as a
348                                                  type_info object, albeit assignable */
349         factory_t factory() const;      ///< Return factory instance of \c this packet
350                                         /**< The returned factory instance can be used to create new
351                                              packets of the given type without knowing the concrete
352                                              type of the packet. The valid may be stored away for
353                                              later use if needed. */
354         
355         ///@}
356
357     protected:
358         explicit Packet(PacketInterpreterBase::ptr packet);
359
360         PacketInterpreterBase::ptr ptr() const;
361
362     private:
363         Packet checkNext() const;
364         Packet checkLast() const;
365         
366         PacketInterpreterBase::ptr packet_;
367         
368         template <class PacketType>
369         friend class ConcretePacket;
370     };
371
372     /** \brief Protocol specific packet handle
373
374         The ConcretePacket template class extends Packet to provide protocol/packet type specific
375         aspects. These are packet constructors and access to the parsed packet fields.
376
377         The \c PacketType template argument to ConcretePacket is a protocol specific and internal
378         policy class which defines the protocol specific behavior. To access a specific type of
379         packet, the library provides corresponding typedefs of ConcretePacket < \a SomePacketType >
380         (e.g. \ref EthernetPacket as typedef for \ref ConcretePacket < \ref EthernetPacketType >).
381
382         The new members provided by ConcretePacket over packet are mostly comprised of the packet
383         constructors. These come in three major flavors:
384         
385         \li The create() family of constructors will create completely new packets.
386         \li The createAfter() family of constructors will create new packets (with new data for the
387             packet) \e after a given existing packet.
388         \li The createBefore()  family of constructors will create new packets (again with new data)
389             \e before a given existing packet.
390         
391         Whereas create() will create a completely new packet with it's own chain and data storage,
392         createAfter() and createBefore() extend a packet with additional
393         headers/interpreters. createAfter() will set the payload of the given packet to the new
394         packet whereas createBefore() will create a new packet with the existing packet as it's
395         payload. 
396
397         createAfter() differs from Packet::parseNextAs() in that the former creates a new packet \e
398         replacing any possibly existing data whereas the latter will interpret the already \e
399         existing data as given by the type argument.
400         
401         \see \ref PacketTypeBase for a specification of the interface to be provided by the \a
402             PacketType policy class.
403       */
404     template <class PacketType>
405     class ConcretePacket 
406         : public Packet
407     {
408     public:
409         ///////////////////////////////////////////////////////////////////////////
410         // Types
411         
412         typedef PacketType type;
413
414         ///////////////////////////////////////////////////////////////////////////
415         ///\name Structors and default members
416         ///@{
417
418         // default copy constructor
419         // default copy assignment
420         // default destructor
421         // no conversion constructors
422
423         ConcretePacket();               ///< Create uninitialized packet handle
424                                         /**< An uninitialized handle is not valid(). It does not
425                                              allow any operation except assignment and checking for
426                                              validity. */
427
428         static factory_t factory();     ///< Return factory for packets of specific type
429                                         /**< This \e static member is like Packet::factory() for a
430                                              specific packet of type \a PacketType */
431
432         // Create completely new packet
433
434         static ConcretePacket create(); ///< Create default initialized packet
435                                         /**< The packet will be initialized to it's default empty
436                                              state. */
437         static ConcretePacket create(NoInit_t); ///< Create uninitialized empty packet
438                                         /**< This will create a completely empty and uninitialized
439                                              packet with <tt>size() == 0</tt>.
440                                              \param[in] noinit This parameter must always have the
441                                                  value \c senf::noinit. */
442         static ConcretePacket create(size_type size); ///< Create default initialized packet
443                                         /**< This member will create a default initialized packet
444                                              with the given size. If the size parameter is smaller
445                                              than the minimum allowed packet size an exception will
446                                              be thrown.
447                                              \param[in] size Size of the packet to create in bytes.
448                                              \throws TruncatedPacketException if \a size is smaller
449                                                  than the smallest permissible size for this type of
450                                                  packet. */
451         static ConcretePacket create(size_type size, NoInit_t); ///< Create uninitialized packet
452                                         /**< Creates an uninitialized (all-zero) packet of the exact
453                                              given size. 
454                                              \param[in] size Size of the packet to create in bytes
455                                              \param[in] noinit This parameter must always have the
456                                                  value \c senf::noinit. */
457         template <class ForwardReadableRange>
458         static ConcretePacket create(ForwardReadableRange const & range); 
459                                         ///< Create packet from given data
460                                         /**< The packet will be created from a copy of the given
461                                              data. The data from the range will be copied directly
462                                              into the packet representation. The data will \e not be
463                                              validated in any way.
464                                              \param[in] range <a
465                                                  href="http://www.boost.org/libs/range/index.html">Boost.Range</a> 
466                                                  of data to construct packet from. */
467
468         // Create packet as new packet after a given packet
469
470         static ConcretePacket createAfter(Packet packet); 
471                                         ///< Create default initialized packet after \a packet
472                                         /**< The packet will be initialized to it's default empty
473                                              state. It will be appended as next header/interpreter
474                                              after \a packet in that packets interpreter chain.
475                                              \param[in] packet Packet to append new packet to. */
476         static ConcretePacket createAfter(Packet packet, NoInit_t);
477                                         ///< Create uninitialized empty packet after\a packet
478                                         /**< This will create a completely empty and uninitialized
479                                              packet with <tt>size() == 0</tt>. It will be appended
480                                              as next header/interpreter after \a packet in that
481                                              packets interpreter chain.
482                                              \param[in] packet Packet to append new packet to.
483                                              \param[in] noinit This parameter must always have the
484                                                  value \c senf::noinit. */
485         static ConcretePacket createAfter(Packet packet, size_type size);
486                                         ///< Create default initializzed packet after \a packet
487                                         /**< This member will create a default initialized packet
488                                              with the given size. If the size parameter is smaller
489                                              than the minimum allowed packet size an exception will
490                                              be thrown. It will be appended as next
491                                              header/interpreter after \a packet in that packets
492                                              interpreter chain.
493                                              \param[in] packet Packet to append new packet to.
494                                              \param[in] size Size of the packet to create in bytes.
495                                              \throws TruncatedPacketException if \a size is smaller
496                                                  than the smallest permissible size for this type of
497                                                  packet. */
498         static ConcretePacket createAfter(Packet packet, size_type size, NoInit_t);
499                                         ///< Create uninitialized packet after \a packet
500                                         /**< Creates an uninitialized (all-zero) packet of the exact
501                                              given size.  It will be appended as next
502                                              header/interpreter after \a packet in that packets
503                                              interpreter chain.
504                                              \param[in] packet Packet to append new packet to.
505                                              \param[in] size Size of the packet to create in bytes
506                                              \param[in] noinit This parameter must always have the
507                                                  value \c senf::noinit. */
508         template <class ForwardReadableRange>
509         static ConcretePacket createAfter(Packet packet, 
510                                           ForwardReadableRange const & range);
511                                         ///< Create packet from given data after \a packet
512                                         /**< The packet will be created from a copy of the given
513                                              data. The data from the range will be copied directly
514                                              into the packet representation. The data will \e not be
515                                              validated in any way.  It will be appended as next
516                                              header/interpreter after \a packet in that packets
517                                              interpreter chain.
518                                              \param[in] packet Packet to append new packet to.
519                                              \param[in] range <a
520                                                  href="http://www.boost.org/libs/range/index.html">Boost.Range</a> 
521                                                  of data to construct packet from. */
522
523         // Create packet as new packet (header) before a given packet
524
525         static ConcretePacket createBefore(Packet packet); 
526                                         ///< Create default initialized packet before \a packet
527                                         /**< The packet will be initialized to it's default empty
528                                              state. It will be prepended as previous
529                                              header/interpreter before \a packet in that packets
530                                              interpreter chain.
531                                              \param[in] packet Packet to prepend new packet to. */
532         static ConcretePacket createBefore(Packet packet, NoInit_t);
533                                         ///< Create uninitialized empty packet before \a packet
534                                         /**< Creates a completely empty and uninitialized packet. It
535                                              will be prepended as previous header/interpreter before
536                                              \a packet in that packets interpreter chain.
537                                              \param[in] packet Packet to prepend new packet to. */
538         
539         // Create a clone of the current packet
540
541         ConcretePacket clone() const;
542
543         ///@}
544         ///////////////////////////////////////////////////////////////////////////
545
546         // Field access
547
548         typename type::parser * operator->() const; ///< Access packet fields
549                                         /**< This operator allows to access the parsed fields of the
550                                              packet using the notation <tt>packet->field()</tt>. The
551                                              fields of the packet are specified by the PacketType's
552                                              \c parser member. 
553
554                                              The members are not strictly restricted to simple field
555                                              access. The parser class may have any member which is
556                                              needed for full packet access (e.g. checksum validation
557                                              / recreation ...)
558                                              \see \ref packetparser for the parser interface. */
559
560     protected:
561
562     private:
563         typedef PacketInterpreter<PacketType> interpreter;
564
565         ConcretePacket(typename interpreter::ptr packet_);
566         
567         typename interpreter::ptr ptr() const;
568
569         friend class Packet;
570         friend class PacketInterpreter<PacketType>;
571     };
572
573     ///@}
574
575 }
576
577 ///////////////////////////////hh.e////////////////////////////////////////
578 #include "Packet.cci"
579 #include "Packet.ct"
580 #include "Packet.cti"
581 #endif
582
583 \f
584 // Local Variables:
585 // mode: c++
586 // fill-column: 100
587 // c-file-style: "senf"
588 // indent-tabs-mode: nil
589 // ispell-local-dictionary: "american"
590 // compile-command: "scons -u test"
591 // comment-column: 40
592 // End: