2 // Fraunhofer Institut fuer offene Kommunikationssysteme (FOKUS)
3 // Kompetenzzentrum fuer Satelitenkommunikation (SatCom)
4 // Stefan Bund <g0dil@berlios.de>
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.
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.
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.
22 \brief Packet public header */
28 #include <boost/operators.hpp>
30 #include "../Utils/Exception.hh"
31 #include "../Utils/SafeBool.hh"
32 #include "PacketInterpreter.hh"
34 //#include "Packet.mpp"
35 ///////////////////////////////hh.p////////////////////////////////////////
39 /** \defgroup packet_module Packet Handling
41 The basic groundwork of the Packet library is the packet handling:
43 \li The packet classes provide access to a chain of packet headers (more generically called
45 \li They automatically manage the required memory resources and the shared packet data.
47 \section packet_module_chain The Interpreter Chain
49 The central data structure for a packet is the interpreter chain
51 \image html structure.png The Interpreter Chain
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.
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.
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.
69 \section packet_module_management Resource Management
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
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).
93 template <class PackeType> class ConcretePacket;
95 ///\addtogroup packet_module
98 /** \brief Main Packet class
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.
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.
109 \section packet_semantics Semantics
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.
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.
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
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 >).
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
138 : public SafeBool<Packet>,
139 public boost::equality_comparable<Packet>
142 ///////////////////////////////////////////////////////////////////////////
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)
149 /// Special argument flag
150 /** Used in some ConcretePacket constructors */
151 enum NoInit_t { noinit };
153 ///////////////////////////////////////////////////////////////////////////
154 ///\name Structors and default members
157 // default copy constructor
158 // default copy assignment
159 // default destructor
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
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
171 // conversion constructors
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. */
180 ///////////////////////////////////////////////////////////////////////////
182 ///\name Interpreter chain access
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
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
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
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
208 \returns in-valid() packet, if no such packet is found */
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
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
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
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
234 \returns in-valid() packet, if no such packet is found */
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
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
247 \returns in-valid() packet, if no such packet is found */
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
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
259 \returns in-valid() packet, if no such packet is found */
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
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
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(). */
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
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. */
315 ///\name Other methods
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()
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. */
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().
337 finalize() will automatically process all
338 packets/headers/interpreters from the end of the chain
339 backwards up to \c this. */
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. */
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. */
363 explicit Packet(PacketInterpreterBase::ptr packet);
365 PacketInterpreterBase::ptr ptr() const;
368 Packet checkNext() const;
369 Packet checkLast() const;
371 PacketInterpreterBase::ptr packet_;
373 template <class PacketType>
374 friend class ConcretePacket;
377 /** \brief Protocol specific packet handle
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.
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 >).
387 The new members provided by ConcretePacket over packet are mostly comprised of the packet
388 constructors. These come in three major flavors:
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.
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
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.
406 \see \ref PacketTypeBase for a specification of the interface to be provided by the \a
407 PacketType policy class.
409 template <class PacketType>
414 ///////////////////////////////////////////////////////////////////////////
417 typedef PacketType type;
419 ///////////////////////////////////////////////////////////////////////////
420 ///\name Structors and default members
423 // default copy constructor
424 // default copy assignment
425 // default destructor
426 // no conversion constructors
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
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 */
437 // Create completely new packet
439 static ConcretePacket create(); ///< Create default initialized packet
440 /**< The packet will be initialized to it's default empty
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
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
456 static ConcretePacket create(size_type size, NoInit_t); ///< Create uninitialized packet
457 /**< Creates an uninitialized (all-zero) packet of the exact
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.
470 href="http://www.boost.org/libs/range/index.html">Boost.Range</a>
471 of data to construct packet from. */
473 // Create packet as new packet after a given packet
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
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
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
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
523 \param[in] packet Packet to append new packet to.
525 href="http://www.boost.org/libs/range/index.html">Boost.Range</a>
526 of data to construct packet from. */
528 // Create packet as new packet (header) before a given packet
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
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. */
544 // Create a clone of the current packet
546 ConcretePacket clone() const;
549 ///////////////////////////////////////////////////////////////////////////
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
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
563 \see \ref packetparser for the parser interface. */
568 typedef PacketInterpreter<PacketType> interpreter;
570 ConcretePacket(typename interpreter::ptr packet_);
572 typename interpreter::ptr ptr() const;
575 friend class PacketInterpreter<PacketType>;
582 ///////////////////////////////hh.e////////////////////////////////////////
584 #if !defined(SENF_PACKETS_DECL_ONLY) && !defined(HH_Packet_i_)
586 #include "Packet.cci"
588 #include "Packet.cti"
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