cb9444a0bfb57cb1bb4d5c70e2b393a4dae7d050
[senf.git] / Packets / Mainpage.dox
1 // $Id$
2 //
3 // Copyright (C) 2007
4 // Fraunhofer Institute for Open Communication Systems (FOKUS)
5 // Competence Center NETwork research (NET), St. Augustin, GERMANY
6 //     Stefan Bund <g0dil@berlios.de>
7 //
8 // This program is free software; you can redistribute it and/or modify
9 // it under the terms of the GNU General Public License as published by
10 // the Free Software Foundation; either version 2 of the License, or
11 // (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 // GNU General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the
20 // Free Software Foundation, Inc.,
21 // 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22
23 /** \mainpage The SENF Packet Library
24
25     The SENF Packet library provides facilities to analyze, manipulate and create structured packet
26     oriented data (e.g. network packets).
27
28     \autotoc
29
30     
31     \section packet_intro_arch Introduction
32     \seechapter \ref packet_arch
33
34     The Packet library consists of several components:
35     
36     \li The \ref packet_module manages the packet data and provides the framework for handling the
37         chain of packet headers. The visible interface is provided by the Packet class.
38     \li \ref packetparser provides the framework for interpreting packet data. It handles
39         parsing the packet information into meaningful values.
40     \li The \ref protocolbundles provide concrete implementations for interpreting packets of
41         some protocol. The Protocol Bundles are built on top of the basic packet library.
42
43     All these components work together to provide a hopefully simple and intuitive interface to
44     packet parsing and creation.
45
46
47     \section packet_intro_usage Tutorial
48     \seechapter \ref packet_usage 
49
50     This chapter discusses the usage of the packet library from a high level view. 
51
52     
53     \section packet_intro_api The packet API
54
55     The packet library API is divided into three areas
56
57     \li the \ref senf::PacketData API for accessing the raw data container
58     \li the packet interpreter chain providing \ref packet_module
59     \li and \ref packetparser which provides access to protocol specific packet fields.
60
61    
62     \section protocolbundles Supported packet types (protocols)
63
64     Each protocol bundle provides a collection of related concrete packet classes for a group of
65     related protocols:
66
67     \li \ref protocolbundle_default : Some basic default protocols: Ethernet, Ip, TCP, UDP
68     \li \ref protocolbundle_mpegdvb : MPEG and DVB protocols
69
70     There are two ways to link with a bundle
71     
72     \li If you only work with known packets which you explicitly reference you may just link with
73         the corresponding library.
74     \li If you need to parse unknown packets and want those to be parsed as complete as possible
75         without explicitly referencing the packet type, you will need to link against the combined
76         object file built for every bundle. This way, all packets defined in the bundle will be
77         included whether they are explicitly referenced or not (and they will all automatically be
78         registered).
79
80     
81     \section packet_intro_new Defining new packet types
82     \seechapter \ref packet_new
83
84     The packet library provides the framework which allows to define arbitrary packet types. There
85     is quite some information needed to completely specify a specific type of packet.
86
87  */
88
89 /** \page packet_arch Overall Packet library Architecture
90
91     The packet library handles network packets of a large number of protocols. We work with a packet
92     on three levels
93
94     \autotoc
95
96     
97     \section packet_arch_handle The Packet handle
98
99     Whenever we are using a Packet, we are talking about a senf::Packet (or a
100     senf::ConcretePacket). This class is a \e handle referencing an internally managed packet data
101     structure. So even though we pass senf::Packet instances around by value, they work like
102     references. The packet library automatically manages all required memory resources using
103     reference counting. 
104
105     Different Packet handles may really internally share one Packet data structure if they both
106     point to the same packet.
107
108    
109     \section packet_arch_data The Packet as a 'bunch of bytes'
110
111     From the outside, a packet is just a bunch of bytes just as it is read from (or will be
112     written to) the wire. At this low-level view, we can access the data in it's raw form but
113     have no further information about what kind of packet we have.
114
115     The packet library provides a consistent container interface for this representation.
116
117     \code
118     Packet p = ...;
119
120     // Change first byte of packet to 0
121     p.data()[0] = 1u; 
122
123     // Copy packet data into a vector
124     std::vector<char> data (p.data().size());
125     std::copy(p.data().begin(), p.data().end(), data.begin());
126     \endcode
127
128     This type of access is primarily needed when reading or writing packets (e.g. to/from the
129     network).
130
131     \see senf::Packet::data() \n
132         senf::PacketData
133
134     
135     \section packet_arch_chain The Interpreter Chain
136
137     On the next level, the packet is divided into a nested list of sub-packets (or headers) called
138     interpreters. Each senf::Packet handle internally points to an interpreter or header. This
139     allows us to access one and the same packet in different ways. 
140
141     Consider an Ethernet Packet with an IP payload holding a UDP packet. We may reference either the
142     Ethernet packet as a whole or we may reference the IP or UDP interpreters (sub-packets or
143     headers). All handles really refer to the \e same data structure but provide access to a
144     different (sub-)range of the data in the packet.
145
146     We can navigate around this chained structure using appropriate members:
147
148     \code
149     // eth, ip and udp all reference the same internal packet data albeit at different data ranges
150     Packet eth = ...;
151     Packet ip = eth.next();
152     Packet udp = ip.next();
153
154     eth.next() == ip                   // true
155     eth.next().is<IPv4Packet>()        // true
156     eth.next().next() == udp           // true
157     eth.next().is<UDPPacket>()         // false
158     eth.find<UDPPacket>() == udp       // true
159
160     udp.find<EthernetPacket>()         // throws InvalidPacketChainException
161     udp.find<EthernetPacket>(senf::nothrow) // An in-valid() senf::Packet which tests as 'false'
162     udp.find<UDPPacket> == udp         // true
163     udp.first<IPv4Packet>()            // throws InvalidPacketChainException
164
165     udp.prev() == ip                   // true
166     udp.prev<EthernetPacket>()         // throws InvalidPacketChainException
167     \endcode
168     
169     \see \ref packet_module
170
171
172     \section packet_arch_parser Parsing specific Protocols
173
174     On the next level, the packet library allows us to parse the individual protocols. This gives us
175     access to the protocol specific data members of a packet and allows us to access or manipulate a
176     packet in a protocol specific way.
177
178     To access this information, we need to use a protocol specific handle, the senf::ConcretePacket
179     which takes as a template argument the specific type of packet to be interpreted. This allows us
180     to easily interpret or create packets. Here an example on how to create a new Ethernet / IP / UDP
181     / Payload packet interpreter chain:
182
183     \code
184     // EthernetPacket, IPv4Packet, UDPPacket and DataPacket are typedefs for corresponding
185     // ConcretePacket instantiations
186     senf::EthernetPacket eth      (senf::EthernetPacket::create());
187     senf::IPv4Packet     ip       (senf::IPv4Packet    ::createAfter(eth));
188     senf::UDPPacket      udp      (senf::UDPPacket     ::createAfter(ip));
189     senf::DataPacket     payload  (senf::DataPacket    ::createAfter(udp, 
190                                                                      std::string("Hello, world!")));
191
192     udp->source()      = 2000u;
193     udp->destination() = 2001u;
194     ip->ttl()          = 255u;
195     ip->source()       = senf::INet4Address::from_string("192.168.0.1");
196     ip->destination()  = senf::INet4Address::from_string("192.168.0.2");
197     eth->source()      = senf::MACAddress::from_string("00:11:22:33:44:55");
198     eth->destination() = senf::MACAddress::from_string("00:11:22:33:44:66");
199     
200     eth.finalizeAll();
201     \endcode
202
203     Again, realize, that \a eth, \a ip, \a udp and \a payload share the same internal packet
204     data structure (the respective \c data() members all provide access to the same underlying
205     container however at different byte ranges): The complete packet can be accessed at
206     <tt>eth.data()</tt> whereas <tt>payload.data()</tt> only holds UDP payload (in this case the
207     string "Hello, world!").
208
209     \see \ref packetparser \n
210         \ref protocolbundles
211  */
212
213 /** \page packet_usage Using the packet library
214
215     \autotoc
216
217     \section packet_usage_intro Includes
218
219     To use the library, you need to include the appropriate header files. This will probably happen
220     automatically when including the specific protocol headers. If needed, you may explicitly use
221
222     \code
223     #include "Packets.hh"
224     \endcode
225     
226     explicitly.
227
228     \warning Never include any other Packets library header directly, only include \c
229     Packets.hh or one (or several) protocol headers from the protocol bundles.
230
231     Most every use of the packet library starts with some concrete packet typedef. Some fundamental
232     packet types are provided by \ref protocolbundle_default. 
233
234
235     \section packet_usage_create Creating a new packet
236
237     Building on those packet types, this example will build a complex packet: This will be an
238     Ethernet packet containing an IPv4 UDP packet. We begin by building the raw packet skeleton:
239
240     \code
241     #include "Packets/DefaultBundle/EthernetPacket.hh"
242     #include "Packets/DefaultBundle/IPv4Packet.hh"
243     #include "Packets/DefaultBundle/UDPPacket.hh"
244
245     senf::EthernetPacket eth      (senf::EthernetPacket::create());
246     senf::IPv4Packet     ip       (senf::IPv4Packet    ::createAfter(eth));
247     senf::UDPPacket      udp      (senf::UDPPacket     ::createAfter(ip));
248     senf::DataPacket     payload  (senf::DataPacket    ::createAfter(udp, 
249                                                                      std::string("Hello, world!")));
250     \endcode
251
252     These commands create what is called an interpreter chain. This chain consists of four
253     interpreters. All interpreters reference the same data storage. This data storage is a random
254     access sequence which contains the data bytes of the packet.
255
256     \note The data structures allocated are automatically managed using reference counting. In this
257         example we have four packet references each referencing the same underlying data
258         structure. This data structure will be freed when the last reference to it goes out of
259         scope.
260
261     The packet created above already has the correct UDP payload (The string "Hello, world!")
262     however all protocol fields are empty. We need to set those protocol fields:
263
264     \code
265     udp->source()      = 2000u;
266     udp->destination() = 2001u;
267     ip->ttl()          = 255u;
268     ip->source()       = senf::INet4Address::from_string("192.168.0.1");
269     ip->destination()  = senf::INet4Address::from_string("192.168.0.2");
270     eth->source()      = senf::MACAddress::from_string("00:11:22:33:44:55");
271     eth->destination() = senf::MACAddress::from_string("00:11:22:33:44:66");
272     
273     eth.finalizeAll();
274     \endcode
275
276     As seen above, packet fields are accessed using the <tt>-></tt> operator whereas other packet
277     facilities (like \c finalizeAll()) are directly accessed using the member operator. The field
278     values are simply set using appropriately named accessors. As a last step, the \c finalizeAll()
279     call will update all calculated fields (fields like next-protocol, header or payload length,
280     checksums etc). Now the packet is ready. We may now send it out using a packet socket
281
282     \code
283     senf::PacketSocketHandle sock ("eth0");
284     sock.write(eth.data());
285     \endcode
286
287
288     \section packet_usage_read Reading and parsing packets
289
290     The chain navigation functions are also used to parse a packet. Let's read an Ethernet packet
291     from a packet socket handle:
292     
293     \code
294     senf::PacketSocketHandle sock ("eth0");
295     senf::EthernetPacket packet (senf::EthernetPacket::create(senf::noinit));
296     sock.read(packet.data(),0u);
297     \endcode
298
299     This first creates an uninitialized Ethernet packet and then reads into this packet. We can now
300     parse this packet. Let's find out, whether this is a UDP packet destined to port 2001:
301
302     \code
303     try {
304         senf::UDPPacket udp (packet.find<UDPPacket>());
305         if (udp->destination() == 2001u) {
306             // Voila ...
307         }
308     } catch (senf::TruncatedPacketException &) {
309         std::cerr << "Ooops !! Broken packet received\n";
310     } catch (senf::InvalidPacketChainException &) {
311         std::cerr << "Not a udp packet\n";
312     }
313     \endcode
314
315     TruncatedPacketException is thrown by <tt>udp->destination()</tt> if that field cannot be
316     accessed (that is it would be beyond the data read which means we have read a truncated
317     packet). More generally, whenever a field cannot be accessed because it would be out of bounds
318     of the data read, this exception is generated.
319
320
321     \section packet_usage_container The raw data container
322     
323     Every packet is based internally on a raw data container holding the packet data. This container
324     is accessed via senf::Packet::data() member.
325     
326     This container is a random access container. It can be used like an ordinary STL container and
327     supports all the standard container members.
328
329     \code
330     Packet p = ...;
331
332     // Insert 5 0x01 bytes
333     p.data().insert(p.data().begin()+5, 5, 0x01);
334
335     // Insert data from another container
336     p.data().insert(p.data().end(), other.begin(), other.end());
337
338     // Erase a single byte
339     p.data().erase(p.data().begin()+5);
340
341     // XOR byte 5 with 0xAA
342     p.data()[5] ^= 0xAA;
343     \endcode
344
345     A packet consists of a list of interpreters (packet headers or protocols) which all reference
346     the same data container at different byte ranges. Each packet consists of the protocol header \e
347     plus the packets payload. This means, that the data container ranges of successive packets from
348     a single interpreter chain are nested.
349
350     Example: The packet created above (the Ethernet-IP-UDP packet with payload "Hello, world!") has
351     4 Interpreters: Ethernet, IPv4, UDP and the UDP payload data. The nested data containers lead to
352     the following structure
353
354     \code
355     // The ethernet header has a size of 14 bytes
356     eth.data().begin() + 14 == ip.data().begin()
357     eth.data().end()        == ip.data().end()
358
359     // The IP header has a size of 20 bytes and therefore
360     ip.data().begin()  + 20 == udp.data().begin()
361     ip.data().end()         == udp.data().end()
362
363     // The UDP header has a size of 8 bytes and thus
364     udp.data().begin() +  8 == payload.data().begin()
365     udp.data().end()        == payload.data().end()
366     \endcode
367
368     This nesting will (and must) always hold: The data range of a subsequent packet will always be
369     within the range of it's preceding packet.
370
371     \warning It is forbidden to change the data of a subsequent packet interpreter from the
372         preceding packet even if the data container includes this data. If you do so, you may
373         corrupt the data structure (especially when changing it's size).
374
375     Every operation on a packet is considered to be \e within this packet and \e without and
376     following packet. When inserting or erasing data, the data ranges are all adjusted
377     accordingly. So the following are \e not the same even though \c eth.end(), \c ip.end() and \c
378     udp.end() are identical.
379
380     \code
381     eth.data().insert(eth.data().end(), 5, 0x01);
382     assert(    eth.data().end() == ip.data().end() + 5 
383             && ip.data().end()  == udp.data().end() );
384
385     // Or alternatively: (You could even use eth.data().end() here ... it's the same)
386     ip.data().insert(ip.data().end(), 5, 0x01);
387     assert(    eth.data().end() == ip.data().end()
388             && ip.data().end()  == udp.data().end() + 5 );
389     \endcode
390
391     \warning When accessing the packet data via the container interface, you may easily build
392         invalid packets since the packet will not be validated against it's protocol.
393
394
395     \section packet_usage_fields Field access
396
397     When working with concrete protocols, the packet library provides direct access to all the
398     protocol information.
399
400     \code
401     udp->source()      = 2000u;
402     udp->destination() = 2001u;
403     ip->ttl()          = 255u;
404     ip->source()       = senf::INet4Address::from_string("192.168.0.1");
405     ip->destination()  = senf::INet4Address::from_string("192.168.0.2");
406     eth->source()      = senf::MACAddress::from_string("00:11:22:33:44:55");
407     eth->destination() = senf::MACAddress::from_string("00:11:22:33:44:66");
408     \endcode
409
410     The protocol field members above do \e not return references, they return parser instances.
411     Protocol fields are accessed via parsers. A parser is a very lightweight class which points into
412     the raw packet data and converts between raw data bytes and it's interpreted value: For example
413     a senf::UInt16Parser accesses 2 bytes (in network byte order) and converts them to or from a 16
414     bit integer. There are a few properties about parsers which need to be understood:
415
416     \li Parsers are created only temporarily when needed. They are created when accessing a protocol
417         field and are returned by value.
418
419     \li A parser never contains a value itself, it just references a packets data container.
420
421     \li Parsers can be built using other parsers and may have members which return further parsers.
422
423     The top-level interface to a packets protocol fields is provided by a protocol parser. This
424     protocol parser is a composite parser which has members to access the protocol fields (compare
425     with the example code above). Some protocol fields may be more complex than a simple value. In
426     this case, those accessors may return other composite parsers or collection parsers. Ultimately,
427     a value parser will be returned.
428
429     The simple value parsers which return plain values (integer numbers, network addresses etc) can
430     be used like those values and can also be assigned corresponding values. More complex parsers
431     don't allow simple assignment. However, they can always be copied from another parser <em>of the
432     same type</em> using the generalized parser assignment. This type of assignment also works for
433     simple parsers and is then identical to a normal assignment.
434
435     \code
436     // Copy the complete udp parser from udp packet 2 to packet 1
437     udp1.parser() << udp2.parser();
438     \endcode
439
440     Additionally, the parsers have a parser specific API which allows to manipulate or query the
441     value. 
442
443     This is a very abstract description of the parser structure. For a more concrete description, we
444     need to differentiate between the different parser types
445
446     \subsection packet_usage_fields_value Simple fields (Value parsers)
447
448     We have already seen value parsers: These are the lowest level building blocks witch parse
449     numbers, addresses etc. They return some type of value and can be assigned such a value. More
450     formally, they have a \c value_type typedef member which gives the type of value they accept and
451     they have an overloaded \c value() member which is used to read or set the value. Some parsers
452     have additional functionality: The numeric parser for Example provide conversion and arithmetic
453     operators so they can be used like a numeric value.
454
455     If you have a value parser \c valueParser with type \c ValueParser, the following will always be
456     valid:
457     \code
458     // You can read the value and assign it to a variable of the corresponding value_type
459     ValueParser::value_type v (valueParser.value());
460
461     // You can assign that value to the parser
462     valueParser.value(v);
463
464     // The assignment can also be done using the generic parser assignment
465     valueParser << v;
466     \endcode
467
468
469     \subsection packet_usage_fields_composite Composite and protocol parsers
470
471     A composite parser is a parser which just combines several other parsers into a structure: For
472     example, the senf::EthernetPacketParser has members \c destination(), \c source() and \c
473     type_length(). Those members return parsers again (in this case value parsers) to access the
474     protocol fields.
475
476     Composite parsers can be nested; A composite parser may be returned by another composite
477     parser. The protocol parser is a composite parser which defines the field for a specific
478     protocol header like Ethernet.
479
480     \subsection packet_usage_fields_collection Collection parsers
481
482     Besides simple composites, the packet library has support for more complex collections. 
483
484     \li The senf::ArrayParser allows to repeat an arbitrary parser a fixed number of times.
485     \li senf::VectorParser and senf::ListParser are two different types of lists with variable
486         number of elements
487     \li The senf::VariantParser is a discriminated union: It will select one of several parsers
488         depending on the value of a discriminant.
489
490
491     \subsubsection packet_usage_collection_vector Vector and List Parsers
492
493     Remember, that a parser does \e not contain any data: It only points into the raw data
494     container. This is also true for the collection parsers. VectorParser and ListParser provide an
495     interface which looks like an STL container to access a sequence of elements.
496
497     We will use an \c MLDv2QueryPacket as an example (see <a
498     href="http://tools.ietf.org/html/rfc3810#section-5">RFC 3810</a>). Here an excerpt of the
499     relevant fields:
500
501     <table class="fields">
502     <tr><td>nrOfSources</td><td>Integer</td><td>Number of multicast sources in this packet</td></tr>
503     <tr><td>sources</td><td>Vector of IPv6 Addresses</td><td>Multicast sources</td></tr>
504     </table>
505
506     To demonstrate nested collections, we use the \c MLDv2ReportPacket as an example. The relevant
507     fields of this packet are;
508     
509     <table class="fields">
510     <tr><td>nrOfRecords</td><td>Integer</td><td>Number of multicast address records</td></tr>
511     <tr><td>records</td><td>List of Records</td><td>List of multicast groups and sources</td></tr>
512     </table>
513
514     Each Record is a composite with the following relevant fields:
515
516     <table class="fields">
517     <tr><td>nrOfSources</td><td>Integer</td><td>Number of sources in this record</td></tr>
518     <tr><td>sources</td><td>Vector of IPv6 Addresses</td><td>Multicast sources</td></tr>
519     </table>
520     
521     The first example will iterate over the sources in a \c MLDv2QueryPacket:
522
523     \code
524     MLDv2QueryPacket mld = ...;
525
526     // Instantiate a collection wrapper for the source list
527     MLDv2QueryPacket::Parser::sources_t::container sources (mld->sources());
528
529     // Iterate over all the addresses in that list
530     for (MLDv2QueryPacket::Parser::sources_t::container::iterator i (sources.begin()); 
531          i != sources.end(); ++i)
532         std::cout << *i << std::endl;
533     \endcode
534
535     Beside other fields, the MLDv2Query consists of a list of source addresses. The \c sources()
536     member returns a VectorParser for these addresses. The collection parsers can only be accessed
537     completely using a container wrapper. The container wrapper type is available as the \c
538     container member of the collection parser, here it is \c
539     MLDv2QueryPacket::Parser::sources_t::container.
540
541     Using this wrapper, we can not only read the data, we can also manipulate the source list. Here
542     we copy a list of addresses from an \c std::vector into the packet:
543
544     \code
545     std::vector<senf::INet6Address> addrs (...);
546
547     sources.resize(addrs.size());
548     std::copy(addrs.begin(), addrs.end(), sources.begin())
549     \endcode
550
551     Collection parsers may be nested. To access a nested collection parser, a container wrapper must
552     be allocated for each level. An MLD Report (which is a composite parser) includes a list of
553     multicast address records called \c records(). Each record is again a composite which contains a
554     list of sources called \c sources():
555
556     \code
557     MLDv2ReportPacket report = ...;
558
559     // Instantiate a collection wrapper for the list of records:
560     MLDv2ReportPacket::Parser::records_t::container records (report->records());
561
562     // Iterate over the multicast address records
563     for (MLDv2ReportPacket::Parser::records_t::container::iterator i (records.begin());
564          i != records.end(); ++i) {
565         // Allocate a collection wrapper for the multicast address record
566         typedef MLDv2ReportPacket::Parser::records_t::value_type::sources_t Sources;
567         Sources::container sources (i->sources());
568         
569         // Iterate over the sources in this record
570         for (Sources::container::iterator i (sources.begin());
571              i != sources.end(); ++i)
572             std::cout << *i << std::endl;
573     }
574     \endcode
575
576     In this example we also see how to find the type of a parser or container wrapper.
577     \li Composite parsers have typedefs for each their fields with a \c _t postfix
578     \li The vector or list parsers have a \c value_type typedef which gives the type of the
579         element.
580
581     By traversing this hierarchical structure, the types of all the fields can be found.
582
583     The container wrapper is only temporary (even though it has a longer lifetime than a
584     parser). Any change made to the packet not via the collection wrapper has the potential to
585     invalidate the wrapper if it changes the packets size.
586
587     \see 
588         senf::VectorParser_Container Interface of the vector parser container wrapper \n
589         senf::ListParser_Container Interface of the list parser container wrapper
590     
591
592     \subsubsection packet_usage_collection_variant The Variant Parser
593
594     The senf::VariantParser is a discriminated union of parsers. It is also used for optional fields
595     (using senf::VoidPacketParser as one possible variant which is a parser parsing nothing).  A
596     senf::VariantParser is not really a collection in the strict sense: It only ever contains one
597     element, the \e type of which is determined by the discriminant.
598
599     For Example, we look at the DTCP HELLO Packet as defined in the UDLR Protocol (see <a
600     href="http://tools.ietf.org/html/rfc3077">RFC 3077</a>)
601
602     \code
603     DTCPHelloPacket hello (...);
604
605     if (hello->ipVersion() == 4) {
606         typedef DTCPHelloPacket::Parser::v4fbipList_t FBIPList;
607         FBIPList::container fbips (hello->v4fbipList());
608         for (FBIPList::container::iterator i (fbips.begin()); i != fbips.end(); ++i)
609             std::cout << *i << std::endl;
610     }
611     else { // if (hello->ipVersion() == 6)
612         typedef DTCPHelloPacket::Parser::v6fbipList_t FBIPList;
613         FBIPList::container fbips (hello->v6fbipList());
614         for (FBIPList::container::iterator i (fbips.begin()); i != fbips.end(); ++i)
615             std::cout << *i << std::endl;
616     }
617     \endcode
618
619     This packet has a field \c ipVersion() which has a value of 4 or 6. Depending on the version,
620     the packet contains a list of IPv4 or IPv6 addresses. Only one of the fields \c v4fbipList() and
621     \c v6fbipList() is available at a time. Which one is decided by the value of \c
622     ipVersion(). Trying to access the wrong one will provoke undefined behavior.
623
624     Here we have used the variants discriminant (the \c ipVersion() field) to select, which field to
625     parse. More generically, every variant field should have a corresponding member to test for it's
626     existence:
627     \code
628     if (hello->has_v4fbipList()) {
629         ...
630     }
631     else { // if (hello->has_v6fbipList())
632         ...
633     }
634     \endcode
635
636     A variant can have more than 2 possible types and you can be sure, that exactly one type will be
637     accessible at any time.
638
639     It is not possible to change a variant by simply changing the discriminant:
640     \code
641     // INVALID CODE:
642     hello->ipVersion() = 6;
643     \endcode
644     Instead, for each variant field there is a special member which switches the variant to that
645     type. After switching the type, the field will be in it's initialized (that is mostly zero)
646     state.
647     \code
648     std::vector<senf::INet6Address> addrs (...);
649
650     // Initialize the IPv6 list
651     hello->init_v6fbipList();
652
653     // Copy values into that list
654     DTCPHelloPacket::Parser::v6fbipList_t::container fbips (hello->v6fbipList());
655     fbips.resize(addrs.size());
656     std::copy(addrs.begin(), addrs.end(), fbips.begin());
657     \endcode
658     
659     \note Here we have documented the default variant interface as it is preferred. It is possible
660         to define variants in a different way giving other names to the special members (\c has_\e
661         name or \c init_\e name etc.). This must be documented with the composite or protocol parser
662         which defines the variant.
663
664     \section packet_usage_annotation Annotations
665
666     Sometimes we need to store additional data with a packet. Data, which is not part of the packet
667     itself but gives us some information about the packet: A timestamp, the interface the packet was
668     received on or other processing related information.
669
670     This type of information can be stored using the annotation interface. The following example
671     will read packet data and will store the read timestamp as a packet annotation.
672
673     \code
674     struct Timestamp {
675         senf::ClockService::clock_t value;
676     };
677
678     senf::EthernetPacket packet (senf::EthernetPacket::create(senf::noinit));
679     sock.read(packet.data(), 0u);
680     packet.annotation<Timestamp>().value = senf::ClockService::now();
681     \endcode
682
683     In the same way, the annotation can be used later
684
685     \code
686     if (senf::ClockService::now() - packet.annotation<Timestamp>().value 
687             > senf::ClockService::seconds(1)) {
688         // Ouch ... this packet is to old
689         // ...
690     }
691     \endcode
692
693     It is very important to define a specific structure (or class or enum) type for each type of
694     annotation. \e Never directly store a fundamental type as an annotation: The name of the type is
695     used to look up the annotation, so you can store only one annotation for each built-in type. \c
696     typedef does not help since \c typedef does not introduce new type names, it only defines an
697     alias.
698
699     Of course, the annotation structure can be arbitrary. However, one very important caveat: If the
700     annotation is not a POD type, it needs to inherit from senf::ComplexAnnotation. A type is POD,
701     if it is really just a bunch of bytes: No (non-static) members, no constructor or destructor and
702     no base classes and all it's members must be POD too. So the following annotation is complex
703     since \c std::string is not POD
704
705     \code
706     struct ReadInfo : senf::ComplexAnnotation
707     {
708         std::string interface;
709         senf::ClockService::clock_t timestamp;
710     };
711
712     // ...
713
714     packet.annotation<ReadInfo>().interface = "eth0";
715     packet.annotation<ReadInfo>().timestamp = senf::ClockService::now();
716
717     // Or store a reference to the annotation for easier access
718
719     ReadInfo & info (packet.annotation<ReadInfo>());
720     
721     if (info.interface == "eth0") {
722         // ...
723     }
724     \endcode
725
726     Every annotation is automatically default-initialized, there is no way to query, whether a
727     packet holds a specific annotation -- every packet conceptually always holds all annotations.
728
729     You should use annotations economically: Every annotation type used in your program will
730     allocate an annotation slot in \e all packet data structures. So don't use hundreds of different
731     annotation types if this is not really necessary: Reuse annotation types where possible or
732     aggregate data into larger annotation structures. The best solution is to use annotations only
733     for a small number of packet specific informations. If you really need to manage a train-load of
734     data together with the packet consider some other way (e.g. place the packet into another class
735     which holds that data).
736
737     \see senf::Packet::annotation()
738  */
739
740 /** \page packet_new Defining new Packet types
741
742     Each packet is specified by the following two components:
743
744     \li A protocol parser which defines the protocol specific fields
745     \li A packet type class which is a policy class defining the packet
746
747     \autotoc
748
749     \see <a href="../../../HowTos/NewPacket/doc/html/index.html">NewPacket HowTo</a>
750
751     \section packet_new_parser The protocol parser
752
753     The protocol parser is simply a composite parser. It defines all the protocol
754     fields. Additionally, the protocol parser may have additional members which will then be
755     accessible via the \c -> operator of the packet. Possibilities here are e.g. checksum
756     calculation and validation, packet validation as a whole and so on.
757
758     Defining a protocol parser is quite simple:
759     \code
760     struct EthernetPacketParser : public PacketParserBase
761     {
762     #   include SENF_FIXED_PARSER()
763
764         SENF_PARSER_FIELD( destination, MACAddressParser    );
765         SENF_PARSER_FIELD( source,      MACAddressParser    );
766         SENF_PARSER_FIELD( type_length, UInt16Parser );
767
768         SENF_PARSER_FINALIZE(EthernetPacketParser);
769     };
770     \endcode
771     
772     There are a lot of other possibilities to define fields. See \ref packetparsermacros for a
773     detailed description of the macro language which is used to define composite parsers.
774
775     \see 
776         \ref packetparsermacros
777
778     \section packet_new_type The packet type policy class
779
780     This is a class which provides all the information needed to integrate the new packet type into
781     the packet library:
782
783     \li It provides the type of the protocol parser to use
784     \li It provides information on how the next protocol can be found and where the payload resides
785         in this packet
786     \li It provides methods to initialize a new packet and get information about the packet size
787
788     All this information is provided via static or typedef members. 
789
790     \code
791     struct EthernetPacketType
792         : public PacketTypeBase,
793           public PacketTypeMixin<EthernetPacketType, EtherTypes>
794     {
795         typedef PacketTypeMixin<EthernetPacketType, EtherTypes> mixin;
796         typedef ConcretePacket<EthernetPacketType> packet;
797         typedef EthernetPacketParser parser;
798
799         using mixin::nextPacketRange;
800         using mixin::initSize;
801         using mixin::init;
802
803         static factory_t nextPacketType(packet p);
804         static void dump(packet p, std::ostream & os);
805         static void finalize(packet p);
806     };
807
808     typedef EthernetPacketType::packet EthernetPacket;
809     \endcode
810
811     The definition of senf::EthernetPacket is quite straight forward. This template works for most
812     simple packet types.
813
814     \see \ref senf::PacketTypeMixin \n
815         \ref senf::PacketTypeBase \n
816         \ref senf::PacketRegistry
817  */
818
819 \f
820 // Local Variables:
821 // mode: c++
822 // fill-column: 100
823 // c-file-style: "senf"
824 // indent-tabs-mode: nil
825 // ispell-local-dictionary: "american"
826 // mode: auto-fill
827 // compile-command: "scons -u doc"
828 // End:
829