src/common/packet.h
author Mathieu Lacage <mathieu.lacage@sophia.inria.fr>
Thu Nov 12 13:01:01 2009 +0100 (2009-11-12)
changeset 5505 c0ac392289c3
parent 5492 5718e4171536
child 5751 b50011dc95b1
permissions -rw-r--r--
replace RefCountBase with SimpleRefCount<> to avoid duplicate refcounting implementations.
     1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
     2 /*
     3  * Copyright (c) 2005,2006 INRIA
     4  *
     5  * This program is free software; you can redistribute it and/or modify
     6  * it under the terms of the GNU General Public License version 2 as
     7  * published by the Free Software Foundation;
     8  *
     9  * This program is distributed in the hope that it will be useful,
    10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12  * GNU General Public License for more details.
    13  *
    14  * You should have received a copy of the GNU General Public License
    15  * along with this program; if not, write to the Free Software
    16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    17  *
    18  * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr>
    19  */
    20 #ifndef PACKET_H
    21 #define PACKET_H
    22 
    23 #include <stdint.h>
    24 #include "buffer.h"
    25 #include "header.h"
    26 #include "trailer.h"
    27 #include "packet-metadata.h"
    28 #include "tag.h"
    29 #include "byte-tag-list.h"
    30 #include "packet-tag-list.h"
    31 #include "nix-vector.h"
    32 #include "ns3/callback.h"
    33 #include "ns3/assert.h"
    34 #include "ns3/ptr.h"
    35 
    36 namespace ns3 {
    37 
    38 /**
    39  * \ingroup common
    40  * \defgroup packet Packet
    41  */
    42 
    43 /**
    44  * \ingroup packet
    45  * \brief Iterator over the set of tags in a packet
    46  *
    47  * This is a java-style iterator.
    48  */
    49 class ByteTagIterator
    50 {
    51 public:
    52   /**
    53    * Identifies a tag and a set of bytes within a packet
    54    * to which the tag applies.
    55    */
    56   class Item
    57   {
    58   public:
    59     /**
    60      * \returns the ns3::TypeId associated to this tag.
    61      */
    62     TypeId GetTypeId (void) const;
    63     /**
    64      * \returns the index of the first byte tagged by this tag.
    65      *
    66      * The index is an offset from the start of the packet.
    67      */
    68     uint32_t GetStart (void) const;
    69     /**
    70      * \returns the index of the last byte tagged by this tag.
    71      *
    72      * The index is an offset from the start of the packet.
    73      */
    74     uint32_t GetEnd (void) const;
    75     /**
    76      * \param tag the user tag to which the data should be copied.
    77      *
    78      * Read the requested tag and store it in the user-provided
    79      * tag instance. This method will crash if the type of the
    80      * tag provided by the user does not match the type of
    81      * the underlying tag.
    82      */
    83     void GetTag (Tag &tag) const;
    84   private:
    85     friend class ByteTagIterator;
    86     Item (TypeId tid, uint32_t start, uint32_t end, TagBuffer buffer);
    87     TypeId m_tid;
    88     uint32_t m_start;
    89     uint32_t m_end;
    90     TagBuffer m_buffer;
    91   };
    92   /**
    93    * \returns true if calling Next is safe, false otherwise.
    94    */
    95   bool HasNext (void) const;
    96   /**
    97    * \returns the next item found and prepare for the next one.
    98    */
    99   Item Next (void);
   100 private:
   101   friend class Packet;
   102   ByteTagIterator (ByteTagList::Iterator i);
   103   ByteTagList::Iterator m_current;
   104 };
   105 
   106 /**
   107  * \ingroup packet
   108  * \brief Iterator over the set of 'packet' tags in a packet
   109  *
   110  * This is a java-style iterator.
   111  */
   112 class PacketTagIterator
   113 {
   114 public:
   115   /**
   116    * Identifies a tag within a packet.
   117    */
   118   class Item 
   119   {
   120   public:
   121     /**
   122      * \returns the ns3::TypeId associated to this tag.
   123      */
   124     TypeId GetTypeId (void) const;
   125     /**
   126      * \param tag the user tag to which the data should be copied.
   127      *
   128      * Read the requested tag and store it in the user-provided
   129      * tag instance. This method will crash if the type of the
   130      * tag provided by the user does not match the type of
   131      * the underlying tag.
   132      */
   133     void GetTag (Tag &tag) const;
   134   private:
   135     friend class PacketTagIterator;
   136     Item (const struct PacketTagList::TagData *data);
   137     const struct PacketTagList::TagData *m_data;
   138   };
   139   /**
   140    * \returns true if calling Next is safe, false otherwise.
   141    */
   142   bool HasNext (void) const;
   143   /**
   144    * \returns the next item found and prepare for the next one.
   145    */
   146   Item Next (void);
   147 private:
   148   friend class Packet;
   149   PacketTagIterator (const struct PacketTagList::TagData *head);
   150   const struct PacketTagList::TagData *m_current;
   151 };
   152 
   153 /**
   154  * \ingroup packet
   155  * \brief network packets
   156  *
   157  * Each network packet contains a byte buffer, a set of byte tags, a set of
   158  * packet tags, and metadata.
   159  *
   160  * - The byte buffer stores the serialized content of the headers and trailers 
   161  * added to a packet. The serialized representation of these headers is expected
   162  * to match that of real network packets bit for bit (although nothing
   163  * forces you to do this) which means that the content of a packet buffer
   164  * is expected to be that of a real packet.
   165  *
   166  * - The metadata describes the type of the headers and trailers which
   167  * were serialized in the byte buffer. The maintenance of metadata is
   168  * optional and disabled by default. To enable it, you must call
   169  * Packet::EnablePrinting and this will allow you to get non-empty
   170  * output from Packet::Print and Packet::Print. If you wish to only enable
   171  * checking of metadata, and do not need any printing capability, you can
   172  * call Packet::EnableChecking: its runtime cost is lower than Packet::EnablePrinting.
   173  *
   174  * - The set of tags contain simulation-specific information which cannot
   175  * be stored in the packet byte buffer because the protocol headers or trailers
   176  * have no standard-conformant field for this information. So-called
   177  * 'byte' tags are used to tag a subset of the bytes in the packet byte buffer
   178  * while 'packet' tags are used to tag the packet itself. The main difference
   179  * between these two kinds of tags is what happens when packets are copied,
   180  * fragmented, and reassembled: 'byte' tags follow bytes while 'packet' tags
   181  * follow packets. Another important difference between these two kinds of tags
   182  * is that byte tags cannot be removed and are expected to be written once,
   183  * and read many times, while packet tags are expected to be written once,
   184  * read many times, and removed exactly once. An example of a 'byte' 
   185  * tag is a FlowIdTag which contains a flow id and is set by the application
   186  * generating traffic. An example of a 'packet' tag is a cross-layer 
   187  * qos class id set by an application and processed by a lower-level MAC 
   188  * layer.
   189  *
   190  * Implementing a new type of Header or Trailer for a new protocol is 
   191  * pretty easy and is a matter of creating a subclass of the ns3::Header 
   192  * or of the ns3::Trailer base class, and implementing the methods
   193  * described in their respective API documentation.
   194  *
   195  * Implementing a new type of Tag requires roughly the same amount of
   196  * work and this work is described in the ns3::Tag API documentation.
   197  *
   198  * The performance aspects of the Packet API are discussed in 
   199  * \ref packetperf
   200  */
   201 class Packet : public SimpleRefCount<Packet>
   202 {
   203 public:
   204   Ptr<Packet> Copy (void) const;
   205 
   206   /**
   207    * Create an empty packet with a new uid (as returned
   208    * by getUid).
   209    */
   210   Packet ();
   211   Packet (const Packet &o);
   212   Packet &operator = (const Packet &o);  
   213   /**
   214    * Create a packet with a zero-filled payload.
   215    * The memory necessary for the payload is not allocated:
   216    * it will be allocated at any later point if you attempt
   217    * to fragment this packet or to access the zero-filled
   218    * bytes. The packet is allocated with a new uid (as 
   219    * returned by getUid).
   220    * 
   221    * \param size the size of the zero-filled payload
   222    */
   223   Packet (uint32_t size);
   224   /**
   225    * Create a packet with payload filled with the content
   226    * of this buffer. The input data is copied: the input
   227    * buffer is untouched.
   228    *
   229    * \param buffer the data to store in the packet.
   230    * \param size the size of the input buffer.
   231    */
   232   Packet (uint8_t const*buffer, uint32_t size);
   233   /**
   234    * Create a new packet which contains a fragment of the original
   235    * packet. The returned packet shares the same uid as this packet.
   236    *
   237    * \param start offset from start of packet to start of fragment to create
   238    * \param length length of fragment to create
   239    * \returns a fragment of the original packet
   240    */
   241   Ptr<Packet> CreateFragment (uint32_t start, uint32_t length) const;
   242   /**
   243    * \returns the size in bytes of the packet (including the zero-filled
   244    *          initial payload)
   245    */
   246   uint32_t GetSize (void) const;
   247   /**
   248    * Add header to this packet. This method invokes the
   249    * Header::GetSerializedSize and Header::Serialize
   250    * methods to reserve space in the buffer and request the 
   251    * header to serialize itself in the packet buffer.
   252    *
   253    * \param header a reference to the header to add to this packet.
   254    */
   255   void AddHeader (const Header & header);
   256   /**
   257    * Deserialize and remove the header from the internal buffer.
   258    * This method invokes Header::Deserialize.
   259    *
   260    * \param header a reference to the header to remove from the internal buffer.
   261    * \returns the number of bytes removed from the packet.
   262    */
   263   uint32_t RemoveHeader (Header &header);
   264   /**
   265    * Deserialize but does _not_ remove the header from the internal buffer.
   266    * This method invokes Header::Deserialize.
   267    *
   268    * \param header a reference to the header to read from the internal buffer.
   269    * \returns the number of bytes read from the packet.
   270    */  
   271   uint32_t PeekHeader (Header &header) const;
   272   /**
   273    * Add trailer to this packet. This method invokes the
   274    * Trailer::GetSerializedSize and Trailer::Serialize
   275    * methods to reserve space in the buffer and request the trailer 
   276    * to serialize itself in the packet buffer.
   277    *
   278    * \param trailer a reference to the trailer to add to this packet.
   279    */
   280   void AddTrailer (const Trailer &trailer);
   281   /**
   282    * Remove a deserialized trailer from the internal buffer.
   283    * This method invokes the Deserialize method.
   284    *
   285    * \param trailer a reference to the trailer to remove from the internal buffer.
   286    * \returns the number of bytes removed from the end of the packet.
   287    */
   288   uint32_t RemoveTrailer (Trailer &trailer);
   289   /**
   290    * Deserialize but does _not_ remove a trailer from the internal buffer.
   291    * This method invokes the Trailer::Deserialize method.
   292    *
   293    * \param trailer a reference to the trailer to read from the internal buffer.
   294    * \returns the number of bytes read from the end of the packet.
   295    */
   296   uint32_t PeekTrailer (Trailer &trailer);
   297 
   298   /**
   299    * Concatenate the input packet at the end of the current
   300    * packet. This does not alter the uid of either packet.
   301    *
   302    * \param packet packet to concatenate
   303    */
   304   void AddAtEnd (Ptr<const Packet> packet);
   305   /**
   306    * \param size number of padding bytes to add.
   307    */
   308   void AddPaddingAtEnd (uint32_t size);
   309   /** 
   310    * Remove size bytes from the end of the current packet
   311    * It is safe to remove more bytes that what is present in
   312    * the packet.
   313    *
   314    * \param size number of bytes from remove
   315    */
   316   void RemoveAtEnd (uint32_t size);
   317   /** 
   318    * Remove size bytes from the start of the current packet.
   319    * It is safe to remove more bytes that what is present in
   320    * the packet.
   321    *
   322    * \param size number of bytes from remove
   323    */
   324   void RemoveAtStart (uint32_t size);
   325   
   326   /**
   327    * If you try to change the content of the buffer
   328    * returned by this method, you will die.
   329    *
   330    * \returns a pointer to the internal buffer of the packet.
   331    */
   332   uint8_t const *PeekData (void) const;
   333 
   334   /**
   335    * \param buffer a pointer to a byte buffer where the packet data 
   336    *        should be copied.
   337    * \param size the size of the byte buffer. 
   338    * \returns the number of bytes read from the packet
   339    *
   340    * No more than \b size bytes will be copied by this function.
   341    */
   342   uint32_t CopyData (uint8_t *buffer, uint32_t size) const;
   343 
   344   void CopyData(std::ostream *os, uint32_t size) const;
   345 
   346   /**
   347    * A packet is allocated a new uid when it is created
   348    * empty or with zero-filled payload.
   349    *
   350    * Note: This uid is an internal uid and cannot be counted on to
   351    * provide an accurate counter of how many "simulated packets" of a
   352    * particular protocol are in the system. It is not trivial to make
   353    * this uid into such a counter, because of questions such as what
   354    * should the uid be when the packet is sent over broadcast media, or
   355    * when fragmentation occurs. If a user wants to trace actual packet
   356    * counts, he or she should look at e.g. the IP ID field or transport
   357    * sequence numbers, or other packet or frame counters at other
   358    * protocol layers.
   359    *
   360    * \returns an integer identifier which uniquely
   361    *          identifies this packet.
   362    */
   363   uint32_t GetUid (void) const;
   364 
   365   /**
   366    * \param os output stream in which the data should be printed.
   367    *
   368    * Iterate over the headers and trailers present in this packet, 
   369    * from the first header to the last trailer and invoke, for
   370    * each of them, the user-provided method Header::DoPrint or 
   371    * Trailer::DoPrint methods.
   372    */
   373   void Print (std::ostream &os) const;
   374 
   375   PacketMetadata::ItemIterator BeginItem (void) const;
   376 
   377   /**
   378    * By default, packets do not keep around enough metadata to
   379    * perform the operations requested by the Print methods. If you
   380    * want to be able to invoke any of the two ::Print methods, 
   381    * you need to invoke this method at least once during the 
   382    * simulation setup and before any packet is created.
   383    */
   384   static void EnablePrinting (void);
   385   /**
   386    * The packet metadata is also used to perform extensive
   387    * sanity checks at runtime when performing operations on a 
   388    * Packet. For example, this metadata is used to verify that
   389    * when you remove a header from a packet, this same header
   390    * was actually present at the front of the packet. These
   391    * errors will be detected and will abort the program.
   392    */
   393   static void EnableChecking (void);
   394 
   395   /**
   396    * \returns a byte buffer
   397    *
   398    * This method creates a serialized representation of a Packet object
   399    * ready to be transmitted over a network to another system. This
   400    * serialized representation contains a copy of the packet byte buffer,
   401    * the tag list, and the packet metadata (if there is one).
   402    *
   403    * This method will trigger calls to the Serialize and GetSerializedSize
   404    * methods of each tag stored in this packet.
   405    *
   406    * This method will typically be used by parallel simulations where
   407    * the simulated system is partitioned and each partition runs on
   408    * a different CPU.
   409    */
   410   Buffer Serialize (void) const;
   411   /**
   412    * \param buffer a byte buffer
   413    *
   414    * This method reads a byte buffer as created by Packet::Serialize
   415    * and restores the state of the Packet to what it was prior to
   416    * calling Serialize.
   417    *
   418    * This method will trigger calls to the Deserialize method
   419    * of each tag stored in this packet.
   420    *
   421    * This method will typically be used by parallel simulations where
   422    * the simulated system is partitioned and each partition runs on
   423    * a different CPU.
   424    */
   425   void Deserialize (Buffer buffer);
   426 
   427   /**
   428    * \param tag the new tag to add to this packet
   429    *
   430    * Tag each byte included in this packet with the
   431    * new tag.
   432    *
   433    * Note that adding a tag is a const operation which is pretty 
   434    * un-intuitive. The rationale is that the content and behavior of
   435    * a packet is _not_ changed when a tag is added to a packet: any
   436    * code which was not aware of the new tag is going to work just
   437    * the same if the new tag is added. The real reason why adding a
   438    * tag was made a const operation is to allow a trace sink which gets
   439    * a packet to tag the packet, even if the packet is const (and most
   440    * trace sources should use const packets because it would be
   441    * totally evil to allow a trace sink to modify the content of a
   442    * packet).
   443    */
   444   void AddByteTag (const Tag &tag) const;
   445   /**
   446    * \returns an iterator over the set of byte tags included in this packet.
   447    */
   448   ByteTagIterator GetByteTagIterator (void) const;
   449   /**
   450    * \param tag the tag to search in this packet
   451    * \returns true if the requested tag type was found, false otherwise.
   452    *
   453    * If the requested tag type is found, it is copied in the user's 
   454    * provided tag instance.
   455    */
   456   bool FindFirstMatchingByteTag (Tag &tag) const;
   457 
   458   /**
   459    * Remove all the tags stored in this packet.
   460    */
   461   void RemoveAllByteTags (void);
   462 
   463   /**
   464    * \param os output stream in which the data should be printed.
   465    *
   466    * Iterate over the tags present in this packet, and
   467    * invoke the Print method of each tag stored in the packet.
   468    */
   469   void PrintByteTags (std::ostream &os) const;
   470 
   471   /**
   472    * \param tag the tag to store in this packet
   473    *
   474    * Add a tag to this packet. This method calls the
   475    * Tag::GetSerializedSize and, then, Tag::Serialize.
   476    *
   477    * Note that this method is const, that is, it does not
   478    * modify the state of this packet, which is fairly
   479    * un-intuitive.
   480    */
   481   void AddPacketTag (const Tag &tag) const;
   482   /**
   483    * \param tag the tag to remove from this packet
   484    * \returns true if the requested tag is found, false
   485    *          otherwise.
   486    *
   487    * Remove a tag from this packet. This method calls
   488    * Tag::Deserialize if the tag is found.
   489    */
   490   bool RemovePacketTag (Tag &tag);
   491   /**
   492    * \param tag the tag to search in this packet
   493    * \returns true if the requested tag is found, false
   494    *          otherwise.
   495    *
   496    * Search a matching tag and call Tag::Deserialize if it is found.
   497    */
   498   bool PeekPacketTag (Tag &tag) const;
   499   /**
   500    * Remove all packet tags.
   501    */
   502   void RemoveAllPacketTags (void);
   503 
   504   /**
   505    * \param os the stream in which we want to print data.
   506    *
   507    * Print the list of 'packet' tags.
   508    *
   509    * \sa Packet::AddPacketTag, Packet::RemovePacketTag, Packet::PeekPacketTag,
   510    *  Packet::RemoveAllPacketTags
   511    */
   512   void PrintPacketTags (std::ostream &os) const;
   513 
   514   /**
   515    * \returns an object which can be used to iterate over the list of
   516    *  packet tags.
   517    */
   518   PacketTagIterator GetPacketTagIterator (void) const;
   519 
   520   /* Note: These functions support a temporary solution 
   521    * to a specific problem in this generic class, i.e. 
   522    * how to associate something specific like nix-vector 
   523    * with a packet.  This design methodology 
   524    * should _not_ be followed, and is only here as an 
   525    * impetus to fix this general issue. */
   526   void SetNixVector (Ptr<NixVector>);
   527   Ptr<NixVector> GetNixVector (void) const; 
   528 
   529 private:
   530   Packet (const Buffer &buffer, const ByteTagList &byteTagList, 
   531           const PacketTagList &packetTagList, const PacketMetadata &metadata);
   532   Buffer m_buffer;
   533   ByteTagList m_byteTagList;
   534   PacketTagList m_packetTagList;
   535   PacketMetadata m_metadata;
   536 
   537   /* Please see comments above about nix-vector */
   538   Ptr<NixVector> m_nixVector;
   539 
   540   static uint32_t m_globalUid;
   541 };
   542 
   543 std::ostream& operator<< (std::ostream& os, const Packet &packet);
   544 
   545 /**
   546  * \ingroup common
   547  * \defgroup packetperf Packet Performance
   548  * The current implementation of the byte buffers and tag list is based
   549  * on COW (Copy On Write. An introduction to COW can be found in Scott 
   550  * Meyer's "More Effective C++", items 17 and 29). What this means is that
   551  * copying packets without modifying them is very cheap (in terms of cpu
   552  * and memory usage) and modifying them can be also very cheap. What is 
   553  * key for proper COW implementations is being
   554  * able to detect when a given modification of the state of a packet triggers
   555  * a full copy of the data prior to the modification: COW systems need
   556  * to detect when an operation is "dirty".
   557  *
   558  * Dirty operations:
   559  *   - ns3::Packet::AddHeader
   560  *   - ns3::Packet::AddTrailer
   561  *   - both versions of ns3::Packet::AddAtEnd
   562  *   - ns3::Packet::RemovePacketTag
   563  *
   564  * Non-dirty operations:
   565  *   - ns3::Packet::AddPacketTag
   566  *   - ns3::Packet::PeekPacketTag
   567  *   - ns3::Packet::RemoveAllPacketTags
   568  *   - ns3::Packet::AddByteTag
   569  *   - ns3::Packet::FindFirstMatchingByteTag
   570  *   - ns3::Packet::RemoveAllByteTags
   571  *   - ns3::Packet::RemoveHeader
   572  *   - ns3::Packet::RemoveTrailer
   573  *   - ns3::Packet::CreateFragment
   574  *   - ns3::Packet::RemoveAtStart
   575  *   - ns3::Packet::RemoveAtEnd
   576  *   - ns3::Packet::CopyData
   577  *
   578  * Dirty operations will always be slower than non-dirty operations,
   579  * sometimes by several orders of magnitude. However, even the
   580  * dirty operations have been optimized for common use-cases which
   581  * means that most of the time, these operations will not trigger
   582  * data copies and will thus be still very fast.
   583  */
   584 
   585 } // namespace ns3
   586 
   587 #endif /* PACKET_H */