This document describes the Click modular router's programming interface. Read this if you're interested in writing new elements for Click. You shouldn't need to read it if you are just building routers that use existing elements.

Overview
********

Packet Transfer
===============

Helper Classes
**************

String
======

The String class represents a string of characters. Strings may be constructed from C strings, characters, numbers, and so forth. They may also be added together. The underlying character arrays are dynamically allocated; operations on Strings allocate and free memory as needed. A String and its substrings will generally share memory. Strings may be assigned, stored, and passed to functions.

See the Doxygen documentation on class String for information.

StringAccum
===========

The StringAccum class, like String (see String), represents a string of characters. StringAccum is optimized for building a string through accumulation, or successively appending substrings until the whole string is ready. A StringAccum has both a length---the number of characters it currently contains---and a capacity---the maximum number of characters it could hold without reallocating memory.

Constructors
------------

 -- Constructor on StringAccum: StringAccum ()
     Creates a StringAccum with no characters.

 -- Constructor on StringAccum: StringAccum (int CAPACITY)
     Creates a StringAccum with no characters, but a capacity of CAPACITY. CAPACITY must be greater than zero.

StringAccum's copy constructor (StringAccum(const StringAccum &)) and assignment operator (operator=(const StringAccum &)) are private. Thus, StringAccums cannot be assigned or passed as arguments. Of course, references to StringAccums may be passed as arguments, and this usage is quite common.

Appending with operator<<
-------------------------

Generally, you append to a StringAccum using iostreams-like << operators, which this section describes. The next section describes the low-level interface, the append and pop_back methods.

Here is a conventional use of StringAccum's << operators:

     struct timeval tv; StringAccum sa; int n; // ...
     sa << tv << ": There are " << n << " things.\n";

 -- Function: StringAccum & operator<< (StringAccum &SA, char C)
 -- Function: StringAccum & operator<< (StringAccum &SA, unsigned char C)
     Appends the character C to the StringAccum SA and returns SA.

 -- Function: StringAccum & operator<< (StringAccum &SA, const char *S)
 -- Function: StringAccum & operator<< (StringAccum &SA, const String &S)
 -- Function: StringAccum & operator<< (StringAccum &SA, const StringAccum &SA2)
     Appends the string S, or the value of the StringAccum SA2, to SA and returns SA.

 -- Function: StringAccum & operator<< (StringAccum &SA, short N)
 -- Function: StringAccum & operator<< (StringAccum &SA, unsigned short N)
 -- Function: StringAccum & operator<< (StringAccum &SA, int N)
 -- Function: StringAccum & operator<< (StringAccum &SA, unsigned N)
 -- Function: StringAccum & operator<< (StringAccum &SA, long N)
 -- Function: StringAccum & operator<< (StringAccum &SA, unsigned long N)
 -- Function: StringAccum & operator<< (StringAccum &SA, long long N)
 -- Function: StringAccum & operator<< (StringAccum &SA, unsigned long long N)
 -- Function: StringAccum & operator<< (StringAccum &SA, double N)
     Appends an ASCII decimal representation of the number N to SA and returns SA. For example, if N is 20, then SA << N has the same effect as SA << "20". The double operator is not available in the kernel.

Appending Data Types
--------------------

StringAccum comes with operator<< definitions for the bool, struct timeval, IPAddress, and EtherAddress types. Of course, you can write your own operator<< functions for other data types, either using existing operator<<s or the manipulation functions described in the next section.

 -- Function: StringAccum & operator<< (StringAccum &SA, bool &VAL)
     Appends the string true or false to SA, according to the value of VAL.

 -- Function: StringAccum & operator<< (StringAccum &SA, const struct timeval &TV)
     Appends an ASCII decimal representation of the time value TV to SA and returns SA. The time value is printed as if by printf("%ld.%06ld", TV.tv_sec, TV.tv_usec).

 -- Function: StringAccum & operator<< (StringAccum &SA, IPAddress &ADDR)
     Appends the conventional dotted-quad representation of the IP address ADDR to SA and returns SA. For example, sa << addr might have the same effect as sa << "18.26.4.44".

 -- Function: StringAccum & operator<< (StringAccum &SA, const EtherAddress &ADDR)
     Appends the conventional colon-separated hexadecimal representation of the Ethernet address ADDR to SA and returns SA. For example, sa << addr might have the same effect as sa << "00:02:B3:06:06:36:EE".

Manipulation
------------

This section describes lower-level methods for manipulating StringAccum objects. The append methods append data to the StringAccum; the extend, reserve, and forward methods add space to the end of it; and the clear and pop_back methods remove its characters.

 -- Method on StringAccum: void append (char C)
 -- Method on StringAccum: void append (unsigned char C)
     Appends the character C to the end of this StringAccum. Equivalent to *this << C.

 -- Method on StringAccum: void append (const char *S, int LEN)
     Appends the first LEN characters of S to the end of this StringAccum. If LEN is negative, then this function treats S as a C string, effectively setting LEN to strlen(S).

 -- Method on StringAccum: char * extend (int LEN)
     Puts LEN arbitrary characters at the end of this StringAccum and returns a pointer to those characters. The return value may be a null pointer if there is not enough memory to grow the character array. This method increases the StringAccum's length by LEN, which must be greater than or equal to zero.

 -- Method on StringAccum: char * extend (int LEN, int EXTRA)
     Puts LEN arbitrary characters at the end of this StringAccum and returns a pointer to those characters. Also ensures space for EXTRA additional characters following the LEN new characters; however, these characters do not contribute to the StringAccum's length. The return value may be a null pointer if there is not enough memory to grow the character array. Increases the StringAccum's length by LEN, which must be greater than or equal to zero.

     This form of extend is generally used to compensate for the null character appended by C string functions like sprintf. For example:

          if (char *buf = string_accum.extend(4, 1))
              // 4 real characters plus one terminating null
              sprintf(buf, "\\%03o", i);

     Caution: The pointer returned by extend, or the reserve method described below, should be treated as transient. It may become invalid after the next call to a method that grows the StringAccum, such as append, extend, or one of the operator<< functions, and will definitely become invalid when the StringAccum is destroyed.

The reserve and forward methods together provide a convenient, fast interface for appending strings of unknown, but bounded, length.

 -- Method on StringAccum: char * reserve (int LEN)
     Reserves space for LEN characters at the end of this StringAccum and returns a pointer to those characters. The return value may be a null pointer if there is not enough memory to grow the character array. This method does not change the StringAccum's length, although it may change its capacity. Use forward to change the StringAccum's length.

 -- Method on StringAccum: void forward (int AMT)
     Adds AMT to the StringAccum's length without changing its data. This method is used in conjunction with reserve, above. Use reserve to get space suitable for appending a string of unknown, but bounded, length. After finding the actual length, use forward to inform the StringAccum. AMT must be greater than or equal to zero, and less than or equal to the remaining capacity.

Finally, these methods remove characters from a StringAccum rather than add characters to it.

 -- Method on StringAccum: void clear ()
     Erases the StringAccum, making its length zero (an empty string).

 -- Method on StringAccum: void pop_back ()
 -- Method on StringAccum: void pop_back (int AMT)
     Remove the last character, or the last AMT characters, of the string. AMT must be greater than or equal to zero, and less than or equal to the StringAccum's length.

Contents
--------

     Caution: The pointer returned by data and c_str should be treated as transient. It may become invalid after the next call to a method that grows the StringAccum, such as append, extend, or one of the operator<< functions, and will definitely become invalid when the StringAccum is destroyed.

 -- Method on StringAccum: const char * data () const
 -- Method on StringAccum: char * data ()
     Returns a pointer to the character data contained in this StringAccum.

 -- Method on StringAccum: int length () const
     Returns the number of characters in this StringAccum.

 -- Method on String: operator bool ()
 -- Method on String: operator bool () const
     Returns true iff this StringAccum has at least one character.

 -- Method on StringAccum: const char * c_str ()
 -- Method on StringAccum: const char * cc ()
     Returns a pointer to the character data contained in this StringAccum. Guarantees that the returned string is null-terminated: the length()th character will be '\0'. This does not affect the StringAccum's contents or length.

 -- Method on StringAccum: char operator[] (int I) const
 -- Method on StringAccum: char & operator[] (int I)
     Returns the Ith character of this StringAccum. I must be greater than or equal to zero, and less than the StringAccum's length. Note that the non-const version of this method returns a mutable character reference, which facilitates code like

          StringAccum sa; // ...
          sa[5] = 'a';

Results
-------

StringAccum's take methods return the string accumulated by a series of calls to operator<< or similar methods. Each take method makes StringAccum relinquish responsibility for its character array memory, passing that responsibility on to its caller. The caller should free the memory when it is done---either with delete[], for the take and take_bytes methods, or by relying on String to handle it, for the take_string method.

Each take method additionally restores the StringAccum to its original, empty state. Further appends or similar operations will begin building a new string from scratch.

 -- Method on StringAccum: void take (unsigned char *&S, int &LEN)
     Sets the S variable to this StringAccum's character data and LEN to its length. Then clears the StringAccum's internal state.

 -- Method on StringAccum: char * take ()
 -- Method on StringAccum: unsigned char * take_bytes ()
     Returns this StringAccum's character data, then clears the StringAccum's internal state. The methods differ only in their return types. Note that StringAccum::length will always return zero immediately after a take or take_bytes. If you need to know the string's length, call length first.

 -- Method on StringAccum: String take_string ()
     Returns this StringAccum's character data as a String object (see String), then clears the StringAccum's internal state. This method hands the character data over to the String implementation; no data copies are performed.

Out-of-Memory Conditions
------------------------

StringAccum operations are robust against out-of-memory conditions. If there is not enough memory to complete a particular operation, the StringAccum is erased and turned into a special out-of-memory indicator. This is a contagious empty string. Every operation on such a buffer (except for clear) leaves it in the out-of-memory state.

 -- Method on StringAccum: bool out_of_memory () const
     Returns true iff this StringAccum is an out-of-memory indicator.

The extend and reserve methods can return null pointers on out-of-memory; their callers should always check that their return values are non-null.

Vector
======

Bitvector
=========

HashMap
=======

BigHashMap
==========

ErrorHandler
============

All Click error messages are passed to an instance of the ErrorHandler class. ErrorHandler separates the generation of error messages from the particular way those messages should be printed. It also makes it easy to automatically decorate errors with context information.

Most Click users must know how to report errors to an ErrorHandler, and how ErrorHandlers count the messages they receive. This section also describes how to decorate error messages with error veneers, and how to write new ErrorHandlers.

ErrorHandler and its important subclasses are defined in <click/error.hh>.

Class Initialization
--------------------

The ErrorHandler class maintains some global state that must be initialized by calling static_initialize at the beginning of the program, and may be freed by calling static_cleanup when execution is complete.

 -- Static Method on ErrorHandler: void static_initialize (ErrorHandler *DEFAULT_ERRH)
     Call this function exactly once, at the beginning of the program, before any error messages are reported to any ErrorHandler. It is OK to create arbitrary ErrorHandler objects before calling this method, however. The DEFAULT_ERRH argument becomes the default ErrorHandler; see Basic ErrorHandlers.

 -- Static Method on ErrorHandler: void static_cleanup ()
     Call this function exactly once, just before the program exits. Destroys the default and silent ErrorHandlers and cleans up other ErrorHandler-related memory. It is an error to call any ErrorHandler method after calling static_cleanup.

Reporting Errors
----------------

ErrorHandler's basic error reporting methods take a format string, which may use printf-like % escape sequences, and additional arguments as required by the format string. See Error Format Strings, for more details on the format string. The five methods differ in the seriousness of the error they report.

 -- Method on ErrorHandler: void debug (const char *FORMAT, ...)
 -- Method on ErrorHandler: void message (const char *FORMAT, ...)
 -- Method on ErrorHandler: int warning (const char *FORMAT, ...)
 -- Method on ErrorHandler: int error (const char *FORMAT, ...)
 -- Method on ErrorHandler: int fatal (const char *FORMAT, ...)
     Report the error described by FORMAT and any additional arguments. The methods are listed by increasing seriousness. Use debug for debugging messages that should not be printed in a production environment; message for explanatory messages that do not indicate errors; warning for warnings (this function prepends the string warning:  to every line of the error message); error for errors; and fatal for errors so serious that they should halt the execution of the program. The three functions that indicate errors, warning, error, and fatal, always return -EINVAL. In some environments, fatal will actually exit the program with exit code 1.

Each of these methods has an analogue that additionally takes a landmark: a string representing where the error took place. A typical landmark contains a file name and line number, separated by a colon---foo.click:31, for example.

 -- Method on ErrorHandler: void ldebug (const String &LANDMARK, const char *FORMAT, ...)
 -- Method on ErrorHandler: void lmessage (const String &LANDMARK, const char *FORMAT, ...)
 -- Method on ErrorHandler: int lwarning (const String &LANDMARK, const char *FORMAT, ...)
 -- Method on ErrorHandler: int lerror (const String &LANDMARK, const char *FORMAT, ...)
 -- Method on ErrorHandler: int lfatal (const String &LANDMARK, const char *FORMAT, ...)
     Report the error described by FORMAT and any additional arguments. The error took place at LANDMARK. Most ErrorHandlers will simply prepend LANDMARK:  to each line of the error message.

These methods are all implemented as wrappers around the verror function. This function takes a landmark, a format string, a va_list packaging up any additional arguments, and a seriousness value, which encodes how serious the error was. The Seriousness enumerated type, which is defined in the ErrorHandler class, represents seriousness values. There are five constants, corresponding to the five error-reporting methods:

ERR_DEBUG
     Corresponds to debug and ldebug.

ERR_MESSAGE
     Corresponds to message and lmessage.

ERR_WARNING
     Corresponds to warning and lwarning.

ERR_ERROR
     Corresponds to error and lerror.

ERR_FATAL
     Corresponds to fatal and lfatal.

 -- Method on ErrorHandler: int verror (Seriousness SERIOUSNESS, const String &LANDMARK, const char *FORMAT, va_list VAL)
     Report the error described by FORMAT and VAL. The error took place at LANDMARK, if LANDMARK is nonempty. The SERIOUSNESS value is one of the five constants described above. Always returns -EINVAL.

Format Strings
--------------

ErrorHandler's format strings closely follow C's standard printf format strings. Most characters in the format string are printed verbatim. The % character introduces a conversion, which prints data read from the remaining arguments. The format string may contain newlines \n, but it need not end with a newline; ErrorHandler will add a final newline if one does not exist.

Each conversion, or formatting escape, follows this pattern:

  * First, the % character introduces each conversion.

  * Next comes zero or more flag characters;

  * then an optional field width;

  * then an optional precision;

  * then an optional length modifier;

  * and finally, the mandatory conversion specifier, which is usually a single character, but may be a name enclosed in braces.

We discuss each of these is turn.

Any conversion may be modified by zero or more of these flag characters.

#
     The value should be converted to an ``alternate form''. For o conversions, the first character of the output string is made 0, by prepending a 0 if there was not one already. For x and X conversions, nonzero values have 0x or 0X prepended, respectively.

0
     The value should be zero padded. For d, i, u, o, x, and X conversions, the converted value is padded on the left with 0 characters rather than spaces.

-
     The value should be left-justified within the field width.

  (a space)
     Leave a blank before a nonnegative number produced by a signed conversion.

+
     Print a + character before a nonnegative number produced by a signed conversion.

The optional field width, a decimal digit string, forces the conversion to use a minimum number of characters. The result of a conversion is padded on the left with space characters to reach the minimum field width, unless one of the 0 or - flags was supplied.

The optional precision is a decimal digit string preceded by a period .. For d, i, u, o, x, and X conversions, the precision specifies the minimum number of digits that must appear; results with fewer digits are padded on the left with 0 characters. For the s conversion, the precision specifies the maximum number of characters that can be printed. For e, f, E, and F conversions, it specifies the number of digits to appear after the radix character; for g and G conversions, the number of significant digits.

If either the field width or precision is specified as a star *, ErrorHandler reads the next argument as an integer and uses that instead.

Length modifiers affect the argument type read by the conversion. There are three modifiers:

h
     The next argument is a short or unsigned short. Affects the d, i, u, o, x, and X conversions.

l
     The next argument is a long or unsigned long. Affects the d, i, u, o, x, and X conversions.

ll
     The next argument is a long long or unsigned long long. Affects the d, i, u, o, x, and X conversions.

Finally, these are the conversions themselves.

s
     Print the const char * argument, treated as a C string.

c
     The int argument is treated as a character constant. Printable ASCII characters (values between 32 and 126) are printed verbatim. Characters \n, \t, \r, and \0 use those C escape representations. Other characters use the representation \%03o.

d, i
     The argument is an int; print its decimal representation.

u
     The argument is an unsigned int; print its decimal representation.

o
     The argument is an unsigned int; print its octal representation.

x, X
     The argument is an unsigned int; print its hexadecimal representation. The %x conversion uses lowercase letters; %X uses uppercase letters.

e, f, g, E, F, G
     The argument is a double; print its representation as if by printf (user-level drivers only).

p
     The void * argument is cast to unsigned long and printed as by %#lx.

%
     Print a literal % character.

{element}
     The argument is an Element *. Print that element's declaration.

Note that ErrorHandler does not support the n conversion.

Counting Errors
---------------

ErrorHandler objects count the number of errors and warnings they have received and make those values available to the user.

 -- Method on ErrorHandler: virtual int nwarnings () const
 -- Method on ErrorHandler: virtual int nerrors () const
     Returns the number of warnings or errors received by this ErrorHandler so far.

 -- Method on ErrorHandler: virtual void reset_counts ()
     Resets the nwarnings and nerrors counters to zero.

These counters are typically used to determine whether an error has taken place in some complex piece of code. For example:

     int before_nerrors = errh->nerrors();
     // ... complex code that may report errors to errh ...
     if (errh->nerrors() != before_nerrors) {
         // an error has taken place
     }

Basic ErrorHandlers
-------------------

Every Click error message eventually reaches some basic ErrorHandler, which generally prints the messages it receives. The user-level driver's basic ErrorHandler prints error messages to standard error, while in the Linux kernel module, the basic ErrorHandler logs messages to the syslog and stores them for access via /proc/click/errors.

Two basic ErrorHandlers are always accessible via static methods: the default ErrorHandler, returned by default_handler and set by set_default_handler; and the silent ErrorHandler, returned by silent_handler, which ignores any error messages it receives.

 -- Static Method on ErrorHandler: ErrorHandler * default_handler ()
     Returns the default ErrorHandler.

 -- Static Method on ErrorHandler: void set_default_handler (ErrorHandler *errh)
     Sets the default ErrorHandler to ERRH. The static_initialize method also sets the default ErrorHandler; see ErrorHandler Initialization.

 -- Static Method on ErrorHandler: ErrorHandler * silent_handler ()
     Returns the silent ErrorHandler. This handler ignores any error messages it receives. It maintains correct nwarnings and nerrors counts, however.

FileErrorHandler, a kind of basic ErrorHandler, is available in any user-level program. It prints every message it receives to some file, usually standard error. It can also prepend an optional context string to every line of every error message.

 -- Constructor on FileErrorHandler: FileErrorHandler (FILE *F, const String &PREFIX = "")
     Constructs a FileErrorHandler that prints error messages to file F. If PREFIX is nonempty, then every line of every error message is prepended by PREFIX.

Error Veneers
-------------

Error veneers wrap around basic ErrorHandler objects and change how error text is generated. An error veneer generally changes each error message's text in some way, perhaps by adding a context message or some indentation. It then passes the altered text to the basic ErrorHandler for printing. Error veneers can be easily nested.

The first argument to each error veneer constructor is a pointer to another ErrorHandler object. The veneer will pass altered error text to this handler, the base handler, for further processing and printing. It also delegates nwarnings() and nerrors() calls to the base handler.

Click comes with three error veneers: one for adding context, one for prepending text to every line, and one for supplying missing landmarks. It is easy to write others; see Writing ErrorHandlers, for details.

 -- Constructor on ContextErrorHandler: ContextErrorHandler (ErrorHandler *BASE_ERRH, const String &CONTEXT, const String &INDENT = "  ")
     Constructs a ContextErrorHandler with BASE_ERRH as base.

     The first time this handler receives an error message, it will precede the message with the CONTEXT string---generally more detailed information about where the error has occurred. Every line in every received error message is prepended with INDENT, two spaces by default, to set off the message from its context.

 -- Constructor on PrefixErrorHandler: PrefixErrorHandler (ErrorHandler *BASE_ERRH, const String &PREFIX)
     Constructs a PrefixErrorHandler with BASE_ERRH as base.

     This handler precedes every line of every error message with PREFIX.

 -- Constructor on LandmarkErrorHandler: LandmarkErrorHandler (ErrorHandler *BASE_ERRH, const String &LANDMARK)
     Constructs a LandmarkErrorHandler with BASE_ERRH as base.

     This handler supplies LANDMARK in place of any blank landmark passed to it. This will cause the base handler to include LANDMARK in its error message.

To demonstrate these veneers in practice, we'll use the following function, which prints two error messages:

     void f(ErrorHandler *errh) {
         errh->error("First line\nSecond line");
         errh->lwarning("here", "Third line");
     }

A simple FileErrorHandler shows the base case.

     FileErrorHandler errh1(stderr);
     f(&errh1);
         -| First line
         -| Second line
         -| here: warning: Third line

The simplest error veneer, PrefixErrorHandler, just prepends text to every line.

     PrefixErrorHandler errh2(&errh1, "prefix - ");
     f(&errh2);
         -| prefix - First line
         -| prefix - Second line
         -| prefix - here: warning: Third line

ContextErrorHandler supplies a line of context before the first error message, and indents all messages except the context.

     ContextErrorHandler errh3(&errh1, "This was called from ...", "** ");
     f(&errh3);
         -| This was called from ...
         -| ** First line
         -| ** Second line
         -| here: ** warning: Third line

Note that the indentation **  is printed after the landmark. This often looks better than the alternative.

Of course, an error veneer can take another error veneer as its ``base handler'', leading to cumulative effects.

     ContextErrorHandler errh4(&errh2, "This was called from ...", "** ");
     f(&errh4);
         -| prefix - This was called from ...
         -| prefix - ** First line
         -| prefix - ** Second line
         -| prefix - here: ** warning: Third line

Writing ErrorHandlers
---------------------

ErrorHandler constructs an error message using three virtual functions. The first, make_text, parses a format string and argument list into a single String. This is passed to the second function, decorate_text, which may transform the string. The final function, handle_text, prints the resulting error message. This structure makes ErrorHandler easy to extend. To write a new basic ErrorHandler, you will need to override just handle_text and the counting functions (nwarnings, nerrors, and reset_counts). The ErrorVeneer helper class, described below, lets you override just decorate_text when writing an error veneer.

 -- Method on ErrorHandler: virtual String make_text (Seriousness S, const char *FORMAT, va_list VAL)
     Parses the format string FORMAT with arguments from VAL, returning the results as a STRING object.

     The default implementation processes the formatting escapes described above (see Error Format Strings). It also prepends every line of the error message with warning:  if S equals ERR_WARNING.

 -- Method on ErrorHandler: virtual String decorate_text (Seriousness S, const String &PREFIX, const String &LANDMARK, const String &TEXT)
     Decorates the error message TEXT as appropriate and returns the result. At minimum, every line of the result should be prepended by PREFIX and, if it is nonempty, the landmark string LANDMARK.

     The default implementation creates lines like this:

          PREFIXLANDMARK: TEXT     (if LANDMARK is nonempty)
          PREFIXTEXT               (if LANDMARK is empty)

     Any spaces and/or a final colon are stripped from the end of LANDMARK. Special landmarks, which begin and end with a backslash \, are ignored.

 -- Method on ErrorHandler: virtual void handle_text (Seriousness S, const String &TEXT)
     This method is responsible for printing or otherwise informing the user about the error message TEXT. If S equals ERR_FATAL, the method should exit the program or perform some other drastic action. It should also maintain the nwarnings() and nerrors() counters. In most cases, it should ensure that the last character in TEXT is a newline.

     This method has no default implementation.

The ErrorVeneer class, a subclass of ErrorHandler, supplies default implementations for these functions that ease the construction of new error veneers. ErrorVeneer's single instance variable, ErrorHandler *_errh, is the base handler. ErrorVeneer overrides all the relevant virtual functions---nwarnings, nerrors, reset_counts, make_text, decorate_text, and handle_text. Its versions simply delegate to the corresponding methods on _errh. An error veneer designer will generally subclass ErrorVeneer rather than ErrorHandler; then she will override only the methods she cares about (usually decorate_text), relying on ErrorVeneer's default implementations for the rest.

 -- Constructor on ErrorVeneer: ErrorVeneer (ErrorHandler *BASE_ERRH)
     Constructs an ErrorVeneer helper class with BASE_ERRH as its base error handler. This constructor simply sets _errh = base_errh.

IPAddress
=========

The IPAddress type represents an IPv4 address. It supports bitwise operations like & and | and provides methods for unparsing IP addresses into ASCII dotted-quad form.

See the Doxygen documentation on class IPAddress for information.

IP6Address
==========

Packets
*******

The Packet class represents Click packets. The single Packet interface has multiple implementations, one per driver. Inside the Linux kernel driver, a Packet object is equivalent to a Linux sk_buff structure; most Packet methods are inline functions that expand to sk_buff calls. The user-level driver, however, uses a purpose-built Packet implementation.

Click packets separate header information from data. The Packet * pointer points to a header structure, which holds pointers to the actual packet data and a set of annotations. Packet data may be shared by two or more packet headers. Packet headers, however, should never be shared.

Packets come in two flavors, Packet and WritablePacket. A Packet object represents a packet header whose data might be shared with other packets. Because of this potential sharing, Packet data is read-only, and its methods return const pointers to data. A WritablePacket object, in contrast, represents a packet header whose data is known not to be shared. Its methods return non-const pointers. The uniqueify method turns a Packet into a WritablePacket, possibly by making a copy of the packet's data. WritablePacket is a subclass of Packet, so you can turn a WritablePacket into a Packet implicitly.

The Packet and WritablePacket classes are defined in <click/packet.hh>.

Structure and Contents
======================

Packet data is stored in a single flat array of bytes. There is no support for linked chains à la BSD mbuf. The actual packet data is embedded inside a buffer that may be much larger, leaving unused spaces called headroom and tailroom before and after the data proper. Therefore, tasks like prepending a header need not always reallocate memory. If the headroom is big enough, prepending space for a new header just requires bumping a pointer.

This diagram shows how a typical packet is laid out, with the relevant Packet methods' names.

                           data
             |<- headroom ->|<----- length ----->|<- tailroom ->|
             |              |                    |              |
             +==============+====================+==============+
             |XXXXXXXXXXXXXX| PACKET CONTENTS... |XXXXXXXXXXXXXX|
             +==============+====================+==============+
             |                                                  |
             |<---------------- buffer_length ----------------->|
        buffer_data

And here are those methods' descriptions.

 -- Method on Packet: const unsigned char * data () const
     Returns a pointer to the packet data proper.

 -- Method on Packet: unsigned length () const
     Returns the length of the packet data proper.

 -- Method on Packet: const unsigned char * buffer_data () const
     Returns a pointer to the buffer that contains the packet data.

 -- Method on Packet: unsigned headroom () const
 -- Method on Packet: unsigned tailroom () const
 -- Method on Packet: unsigned buffer_length () const
     Returns the length of the headroom area, the tailroom area, and the whole buffer, respectively.

 -- Method on WritablePacket: unsigned char * data () const
 -- Method on WritablePacket: unsigned char * buffer_data () const
     These WritablePacket methods are identical to Packet's data and buffer_data methods except for their non-const return type.

Two invariants relate these methods' values:

     buffer_length() = headroom() + length() + tailroom()
     data() = buffer_data() + headroom()

Creation and Destruction
========================

Packets are created with the Packet::make static methods, and destroyed with the Packet::kill method. (The Packet and WritablePacket classes have private constructors and destructors; you cannot create or destroy packets with new or delete.)

Packet::make
------------

The make methods always take the length of the packet data; some of them take the packet contents and the headroom and tailroom lengths as well. (The contents of any headroom and tailroom areas are always undefined.) Most of them return a WritablePacket *, since new packets are not shared.

The Packet class defines two constants related to packet creation, DEFAULT_HEADROOM and MIN_BUFFER_LENGTH. Those make methods that do not take an explicit headroom parameter use DEFAULT_HEADROOM instead. Furthermore, no make method will create a packet with buffer length less than MIN_BUFFER_LENGTH. If the sum of a packet's headroom and length is less than this, the packet buffer is given extra tailroom to bump the buffer length up to MIN_BUFFER_LENGTH. These constants have the values DEFAULT_HEADROOM = 28 and MIN_BUFFER_LENGTH = 64.

 -- Static Method on Packet: WritablePacket * make (unsigned LEN)
     Returns a new packet containing LEN bytes of undefined data.

 -- Static Method on Packet: WritablePacket * make (const char *DATA, unsigned LEN)
 -- Static Method on Packet: WritablePacket * make (const unsigned char *DATA, unsigned LEN)
     Returns a new packet whose contents equal the first LEN bytes of DATA. DATA may be a null pointer, in which case the packet contains LEN bytes of undefined data.

 -- Static Method on Packet: WritablePacket * make (unsigned HEADROOM, const unsigned char *DATA, unsigned LEN, unsigned TAILROOM)
     Returns a new packet containing HEADROOM bytes of headroom, LEN bytes of contents, and at least TAILROOM bytes of tailroom. The packet contents will equal the first LEN bytes of DATA unless DATA is a null pointer, in which case the contents are undefined.

The following make method is only available in the user-level driver.

 -- Static Method on Packet: WritablePacket * make (unsigned char *DATA, unsigned LEN, void (*DESTRUCTOR)(unsigned char *, size_t))
     Returns a new packet that uses DATA as a buffer. That is, the new packet will have the following characteristics:

     buffer_data
     DATA
     buffer_length
     LEN
     headroom
     0
     length
     LEN
     tailroom
     0

     When the resulting packet is destroyed, the function DESTRUCTOR will be called with DATA and LEN as arguments. DESTRUCTOR may be a null pointer, in which case Packet calls delete[] DATA instead.

     This method lets a user-level element manage packet memory itself, rather than relying on Packet.

See Packets and sk_buffs, for a make method only available in the Linux kernel driver.

Packet::kill
------------

To destroy a Packet, simply call its kill method.

 -- Method on Packet: void kill ()
     Frees this packet. If this packet contained the last reference to its data buffer, then frees the data buffer as well.

Packets and sk_buffs
====================

In the Linux kernel driver, Packet objects are equivalent to struct sk_buffs. This avoids indirection overhead and makes it cheap to pass packets back and forth between Linux and Click. The Packet operations described in this section are mostly inline functions that expand to conventional sk_buff calls like skb_clone().

Click Packet sk_buffs should always have skb->users equal to 1. That is, the sk_buff headers should not be shared, although the data buffers they point to may be shared.

The make, skb, and steal_skb methods described in this section convert Packets to sk_buffs and vice versa.

 -- Static Method on Packet: Packet * make (struct sk_buff *SKB)
     Returns a new packet equivalent to the sk_buff SKB. All of SKB's data pointers and annotations are left unchanged. This method generally does nothing, since Packets and sk_buffs are equivalent in the Linux kernel. However, if SKB->users field is bigger than 1, the method will return a clone of SKB. This method returns a Packet *, not a WritablePacket *, because the SKB argument might share data with some other sk_buff.

     Do not use or manipulate SKB after passing it to this method, since Click and the Packet implementation now own SKB.

 -- Method on Packet: struct sk_buff * skb ()
 -- Method on Packet: const struct sk_buff * skb () const
     Returns the sk_buff corresponding to this packet. Use this method to examine the sk_buff version of a Packet.

     Do not pass the result to a function that might free it or increment its users field; use steal_skb for that.

 -- Method on Packet: struct sk_buff * steal_skb ()
     Returns the sk_buff corresponding to this packet. Use this method to permanently change a Packet into an sk_buff---for example, to create an sk_buff you'd like to send to Linux.

     Do not use or manipulate a Packet after calling its steal_skb method, since Linux now owns the resulting sk_buff.

Sharing---clone and uniqueify
=============================

The clone method creates a new packet header that shares data with an existing packet. The uniqueify method, in contrast, ensures that a packet's data is not shared by anyone, perhaps by making a copy of the data.

 -- Method on Packet: Packet * clone ()
     Creates and returns a new packet header that shares this packet's data. The new packet's annotations are copied from this packet's annotations.

     The result may be a null pointer if there was not enough memory to make a new packet header.

 -- Method on Packet: WritablePacket * uniqueify ()
     Ensures that this packet does not share data with any other packet. This may involve copying the packet data, and perhaps creating a new packet header, but if this packet is already unshared, no real work is required. Returns a WritablePacket * because the new packet is unshared.

     Do not use, manipulate, or free a Packet after calling its uniqueify method. Manipulate the returned WritablePacket * instead.

     The result may be a null pointer if there was not enough memory to make a required data copy. In this case, the old packet is freed.

 -- Method on Packet: bool shared () const
     Returns true if and only if this packet shares data with some other packet.

Buffer Manipulation---push, pull, put, and take
===============================================

The push, pull, put, and take methods manipulate a packet's contents by adding or removing space from its headroom or tailroom. Given a packet, use push to add space to its beginning, pull to remove space from its beginning, put to add space to its end, and take to remove space from its end. The methods that add space, push and put, uniqueify the relevant packet as a side effect. This ensures that the packet's data is unshared so you can immediately manipulate the added space.

 -- Method on Packet: WritablePacket * push (unsigned AMT)
     Adds AMT bytes of space to the beginning of the packet's data and returns the resulting packet. The new space is uninitialized. The result will not share data with any other packet; thus, it is a WritablePacket *. If this packet is unshared and its headroom is bigger than AMT, then this operation is cheap, amounting to a bit of pointer arithmetic. Otherwise, it requires copying the packet data and possibly creating a new packet header.

     Do not use, manipulate, or free a Packet after calling its push method. Manipulate the returned WritablePacket * instead.

     The result may be a null pointer if there was not enough memory to make a required new packet. In this case, the old packet is freed.

 -- Method on Packet: void pull (unsigned AMT)
     Removes AMT bytes of space from the beginning of the packet's data. AMT must be less than or equal to the packet's length(). This operation is always cheap, amounting to a bit of pointer arithmetic.

 -- Method on Packet: WritablePacket * put (unsigned AMT)
     Adds AMT bytes of space to the end of the packet's data and returns the resulting packet. The new space is uninitialized. The result will not share data with any other packet; thus, it is a WritablePacket *. If this packet is unshared and its tailroom is bigger than AMT, then this operation is cheap, amounting to a bit of pointer arithmetic. Otherwise, it requires copying the packet data and possibly creating a new packet header.

     Do not use, manipulate, or free a Packet after calling its put method. Manipulate the returned WritablePacket * instead.

     The result may be a null pointer if there was not enough memory to make a required new packet. In this case, the old packet is freed.

 -- Method on Packet: void take (unsigned AMT)
     Removes AMT bytes of space from the end of the packet's data. AMT must be less than or equal to the packet's length(). This operation is always cheap, amounting to a bit of pointer arithmetic.

The push and put methods have ``nonunique'' variants, nonunique_push and nonunique_put, which do not have the side effect of uniqueifying their resulting packet. These methods are rarely used.

 -- Method on Packet: Packet * nonunique_push (unsigned AMT)
     Adds AMT bytes of space to the beginning of the packet's data and returns the resulting packet. The new space is uninitialized. The result may share data with other packets. If this packet's headroom is bigger than AMT, then this operation is cheap, amounting to a bit of pointer arithmetic. Otherwise, it requires copying the packet data and possibly creating a new packet header.

     Do not use, manipulate, or free a Packet after calling its nonunique_push method. Manipulate the returned Packet * instead.

     The result may be a null pointer if there was not enough memory to make a required new packet. In this case, the old packet is freed.

 -- Method on Packet: Packet * nonunique_put (unsigned AMT)
     Adds AMT bytes of space to the end of the packet's data, returning the resulting packet. The new space is uninitialized. The result may share data with other packets. If this packet's tailroom is bigger than AMT, then this operation is cheap, amounting to a bit of pointer arithmetic. Otherwise, it requires copying the packet data and possibly creating a new packet header.

     Do not use, manipulate, or free a Packet after calling its nonunique_put method. Manipulate the returned Packet * instead.

     The result may be a null pointer if there was not enough memory to make a required new packet. In this case, the old packet is freed.

Annotations
===========

Each packet header has space for a number of annotations, extra information about the packet that is not contained in its data. Click supports header annotations, which indicate where in the packet a network header, such as an IP header, is located; user annotations, whose semantics are left undefined by Click---different elements can treat them in different ways; and other specialized annotations, such as the timestamp annotation, the destination IP address annotation, and so forth.

New packets begin with all annotations cleared: numeric annotations are zero, pointer annotations are null pointers. clone, uniqueify, and their equivalents always copy each of the original packet's annotations in the appropriate way. (For example, the new header annotations will point into the new data, if a data copy was made.)

Header Annotations
------------------

Many packets contain a network header of some kind, such as an IP header. This header may be located anywhere in the packet depending on how the packet was encapsulated. Furthermore, the data encapsulated by that network header may be located anywhere after the network header, given the presence of options. With the network header annotation and the transport header annotation, one element can determine where a network header is and how long it is, then store this information for other elements to use. For example, the ->CheckIPHeader element sets the header annotations on packets it receives. Elements like ->SetIPDSCP then require a non-null IP header annotation on their input packets.

The header annotations on new packets are each set to a null pointer.

 -- Method on Packet: const unsigned char * network_header () const
 -- Method on WritablePacket: unsigned char * network_header () const
     Returns the network header annotation. The resulting pointer is read-only on Packets and read/write on WritablePackets.

 -- Method on Packet: const unsigned char * transport_header () const
 -- Method on WritablePacket: unsigned char * transport_header () const
     Returns the transport header annotation. The resulting pointer is read-only on Packets and read/write on WritablePackets.

 -- Method on Packet: int network_header_offset () const
     Returns the offset from data() to network_header(). The result might be negative, since the data pointer may have been advanced past the network header annotation with the pull method.

 -- Method on Packet: int network_header_length () const
     Returns the network header's length. This equals transport_header() - network_header().

 -- Method on Packet: unsigned transport_header_offset () const
     Returns the offset from data() to transport_header(). The result might be negative, since the data pointer may have been advanced past the transport header annotation with the pull method.

Several invariants relate these methods' values whenever the header annotations are non-null:

     buffer_data() ≤ network_header() ≤ transport_header()
                  ≤ buffer_data() + buffer_length()
     network_header_offset() = network_header() - data()
     transport_header_offset() = transport_header() - data()
     network_header_length() = transport_header() - network_header()

Set the network and transport header annotations simultaneously with the set_network_header method.

 -- Method on Packet: void set_network_header (const unsigned char *HEADER, unsigned LEN)
     Sets the network header annotation to HEADER, which must lie between buffer_data() and buffer_data() + buffer_length(). The network header is LEN bytes long, so network_header_length() will equal LEN and transport_header() will equal HEADER + LEN.

Typed Header Annotations
........................

For convenience, Packet provides methods for accessing and setting the network header annotation as an IP or IPv6 header. These methods use the same annotations as the generic network_header methods; they are just typed differently.

 -- Method on Packet: const click_ip * ip_header () const
 -- Method on WritablePacket: click_ip * ip_header () const
 -- Method on Packet: const click_ip6 * ip6_header () const
 -- Method on WritablePacket: click_ip6 * ip6_header () const
     Returns network_header() as a pointer to an IP or IPv6 header structure.

 -- Method on Packet: int ip_header_offset () const
 -- Method on Packet: unsigned ip_header_length () const
 -- Method on Packet: int ip6_header_offset () const
 -- Method on Packet: unsigned ip6_header_length () const
     Equivalent to network_header_offset() and network_header_length().

 -- Method on Packet: void set_ip_header (const click_ip *HEADER, unsigned LEN)
 -- Method on Packet: void set_ip6_header (const click_ip6 *HEADER, unsigned LEN)
     Equivalent to set_network_header(HEADER, LEN).

 -- Method on Packet: void set_ip6_header (const click_ip6 *HEADER)
     Equivalent to set_ip6_header(HEADER, 40).

 -- Method on Packet: const click_tcp * tcp_header () const
 -- Method on WritablePacket: click_tcp * tcp_header () const
 -- Method on Packet: const click_udp * udp_header () const
 -- Method on WritablePacket: click_udp * udp_header () const
     Returns transport_header() as a pointer to a TCP or UDP header structure.

User Annotations
----------------

Each packet header has a user annotation area, space reserved for arbitrary annotations. Different methods access this space as an array of bytes, integers, or unsigned integers. The Packet class does not assign semantics to any particular byte in the user annotation area. Instead, macros in <click/packet_anno.hh> provide names for particular bytes. Some of these names have overlapping byte ranges; the user must take care not to define a configuration whose elements use an annotation byte on a packet for different purposes. The next section describes the macros in Click's default <click/packet_anno.hh>.

These constants define the size of the annotation area.

Packet::USER_ANNO_SIZE
     The size of the annotation area in bytes.

Packet::USER_ANNO_US_SIZE
     The size of the annotation area in unsigned shorts.

Packet::USER_ANNO_S_SIZE
     The size of the annotation area in shorts.

Packet::USER_ANNO_U_SIZE
     The size of the annotation area in unsigned ints.

Packet::USER_ANNO_I_SIZE
     The size of the annotation area in ints.

Currently, USER_ANNO_SIZE is 24, USER_ANNO_U_SIZE and USER_ANNO_I_SIZE are both 6, and USER_ANNO_US_SIZE and USER_ANNO_S_SIZE are both 12.

The user annotation area may be accessed as an array of bytes, an array of unsigned ints, or an array of ints. The elements of these arrays are numbered from 0 to K - 1, where K is the appropriate SIZE constant.

 -- Method on Packet: unsigned char user_anno_c (int I) const
     Returns the Ith byte in the user annotation area. I must be between 0 and USER_ANNO_SIZE - 1.

 -- Method on Packet: unsigned user_anno_u (int I)
 -- Method on Packet: int user_anno_i (int I)
     Returns the Ith unsigned int or int in the user annotation area. I must be between 0 and USER_ANNO_U_SIZE - 1. The Ith unsigned int or int annotation occupies bytes 4I through 4I + 3 of the user annotation area.

 -- Method on Packet: void set_user_anno_c (int I, unsigned char VALUE)
 -- Method on Packet: void set_user_anno_u (int I, unsigned VALUE)
 -- Method on Packet: void set_user_anno_i (int I, int VALUE)
     Sets the Ith byte, unsigned int, or int user annotation to VALUE.

 -- Method on Packet: unsigned * all_user_anno_u ()
     Returns a pointer to the user annotation area, treated as an array of unsigned ints.

Specific User Annotations
-------------------------

The <click/packet_anno.hh> header file defines macros for accessing a packet's user annotation area by name. These macros follow some simple guidelines. Each user annotation is given a name like PAINT or FIX_IP_SRC. Then, two macros are written for each annotation, NAME_ANNO and SET_NAME_ANNO.

 -- Macro: NAME_ANNO (const Packet *P)
     Returns the value of P's NAME annotation.

 -- Macro: SET_NAME_ANNO (Packet *P, VALUE)
     Sets P's NAME annotation to VALUE.

For example, here are the definitions of PAINT_ANNO and SET_PAINT_ANNO from Click's default <click/packet_anno.hh>.

     #define PAINT_ANNO(p)          ((p)->user_anno_c(0))
     #define SET_PAINT_ANNO(p, v)   ((p)->set_user_anno_c(0, (v)))

This table lists the annotations declared in Click's default <click/packet_anno.hh>.

Annotation name
Type
Bytes
Some relevant elements
PAINT
unsigned char
0
->Paint, ->CheckPaint, ->PaintTee
ICMP_PARAM_PROB
unsigned char
1
->IPGWOptions, ->ICMPError
FIX_IP_SRC
unsigned char
3
->ICMPError, ->FixIPSrc
FWD_RATE
int
4--7
->IPRateMonitor
REV_RATE
int
8--11
->IPRateMonitor

Other Annotations
-----------------

Packet headers have space for four other particular annotations, and special methods for accessing them. These annotations do not overlap the user annotation area. There are annotations that hold a destination IP address, a timestamp, the device on which the packet arrived, a packet type constant, and, in the Linux kernel module, a performance counter value.

Destination Address
...................

The destination address annotation stores the IP or IPv6 address of the next hop towards the packet's destination. Elements check and manipulate this address, rather than the IP header's destination address, since the next-hop address often differs from the final destination. The destination IP address and IPv6 address are different annotations, but they overlap; you may set only one at a time.

 -- Method on Packet: IPAddress dst_ip_anno () const
     Returns this packet's destination IP address annotation.

 -- Method on Packet: const IP6Address & dst_ip6_anno () const
     Returns a reference to this packet's destination IPv6 address annotation.

 -- Method on Packet: void set_dst_ip_anno (IPAddress VALUE)
 -- Method on Packet: void set_dst_ip6_anno (const IP6Address &VALUE)
     Sets this packet's destination IP or IPv6 address annotation to VALUE.

The destination IP address annotation is set by the ->GetIPAddress and ->SetIPAddress elements, manipulated by ->LookupIPRoute and its cousins, and used by ->ARPQuerier. It defaults to zero.

Timestamp
.........

The timestamp annotation generally indicates when a packet was received.

 -- Method on Packet: const struct timeval & timestamp_anno () const
 -- Method on Packet: struct timeval & timestamp_anno ()
     Returns a reference to this packet's timestamp annotation.

 -- Method on Packet: void set_timestamp_anno (const struct timeval &VALUE)
     Sets this packet's timestamp annotation to VALUE.

 -- Method on Packet: void set_timestamp_anno (int SEC, int USEC)
     Sets this packet's timestamp annotation to SEC and USEC. Equivalent to struct timeval tv; tv.tv_sec = SEC; tv.tv_usec = USEC; set_timestamp_anno(tv).

Linux device drivers set this annotation, so packets emitted by ->FromDevice and ->PollDevice in the Linux kernel driver have the annotation set. Packet sources like ->InfiniteSource and ->RatedSource also set the annotation, as does ->FromDump in the user-level driver. Debugging elements like ->Print generally take a keyword argument that makes them print packet timestamps.

The timestamp annotation defaults to zero.

Device
......

In the Linux kernel, packets received from some device are annotated with a pointer to the relevant struct net_device object. (In versions of the kernel prior to 2.3, this type was called struct device.) The Packet class provides access to this annotation. The annotation has type net_device *; Click defines net_device as a synonym for struct device in kernel versions 2.2 and prior.

 -- Method on Packet: net_device * device_anno () const
     Returns this packet's device annotation.

 -- Method on Packet: void set_device_anno (net_device *VALUE)
     Sets this packet's device annotation to VALUE.

In the user-level driver, device_anno always returns 0, and set_device_anno does nothing.

The ->ARPResponder element sets this annotation on every generated response to the value of the annotation on the relevant query. Because of this, those responses can be safely forwarded to Linux: Linux's ARP-response code requires a correct device annotation.

The device annotation defaults to a null pointer.

Packet Type
...........

The packet type annotation specifies how a packet was received. Its value is one of the following constants, which are defined in the Packet::PacketType enumeration.

HOST
     The packet was sent to this host.

BROADCAST
     The packet was sent to a link-level broadcast address.

MULTICAST
     The packet was sent to a link-level multicast address.

OTHERHOST
     The packet was sent to a different host, but received anyway. The relevant device is probably in promiscuous mode.

OUTGOING
     The packet was generated at this host and is being sent to another host.

LOOPBACK, FASTROUTE
     See the Linux kernel documentation. These values correspond to PACKET_LOOPBACK and PACKET_FASTROUTE, which are defined in <linux/if_packet.h>.

 -- Method on Packet: Packet::PacketType packet_type_anno () const
     Returns this packet's packet type annotation.

 -- Method on Packet: void set_packet_type_anno (Packet::PacketType VALUE)
     Sets this packet's packet type annotation to VALUE.

In the Linux kernel, device drivers set the packet type annotation for the packets they receive. Thus, the ->FromDevice and ->PollDevice elements generate packets with correct packet type annotations. The user-level driver's ->FromDevice also sets the packet type annotation. The ->ICMPError and ->DropBroadcasts elements use the annotation's value.

The packet type annotation defaults to Packet::HOST.

Performance Counter
...................

This annotation is available only in the Linux kernel driver. Its value is an unsigned long long that generally corresponds to some performance counter value.

 -- Method on Packet: unsigned long long perfctr_anno () const
     Returns this packet's performance counter annotation.

 -- Method on Packet: void set_perfctr_anno (unsigned long long VALUE)
     Sets this packet's performance counter annotation to VALUE.

The ->SetCycleCount, ->SetPerfCount, ->CycleCountAccum, and ->PerfCountAccum elements manipulate this annotation. Its default value is zero.

Annotations In General
----------------------

Packet provides methods for clearing a packet's annotations, and for copying all of a packet's annotations from another packet.

 -- Method on Packet: void clear_annotations ()
     Clears all of this packet's annotations to their default state, which is generally zero.

 -- Method on Packet: void copy_annotations (const Packet *P)
     Copies all of P's annotations into this packet except for its header annotations. (This packet's current header annotations are left unchanged.)

Out-of-Memory Conditions
========================

Any method that potentially allocates memory for a Packet may fail due to an out-of-memory condition. The complete list of these methods follows:

  * make variants

  * clone

  * uniqueify

  * push

  * put

  * nonunique_push

  * nonunique_put

These methods always return a null pointer on out-of-memory. Methods that manipulate existing packets---uniqueify, push, put, nonunique_push, and nonunique_put---additionally free any existing packet before returning a null pointer. You should always check the results of these methods to see if you have run out of memory.

Element Characteristics
***********************

See the Doxygen documentation on class Element for information on element characteristics.

Element Initialization
**********************

See the Doxygen documentation on class Element for information on element initialization.

Element Runtime
***************

See the Doxygen documentation on class Element for information on moving packets, handling packets, running tasks.

Handling Packets
================

Every Packet object should be single-threaded through Click: the same Packet pointer should never be in use in two different places. In particular, an element should not use a Packet after passing it downstream to the rest of the configuration (by calling output().push, for example).

This, for example, is the wrong way to write a ->Tee with two outputs.

     void
     BadTee::push(int, Packet *p)
     {
         output(0).push(p);
         output(1).push(p);
     }

The same packet pointer, p, has been pushed to two different outputs. This is always illegal; the rest of the configuration may have modified or even freed the packet before returning control to BadTee. The correct definition uses the clone method:

     void
     GoodTee::push(int, Packet *p)
     {
         output(0).push(p->clone());
         output(1).push(p);
     }

Every push or pull method must account for every packet it receives by freeing it, emitting it on some output, or perhaps explicitly storing it for later. This push method, for example, contains a memory leak:

     void
     Leaky::push(int, Packet *p)
     {
         const click_ip *iph = p->ip_header();
         // ... more processing ...
         _counter++;
         return;  // XXX Oops!
         // Must push the packet on, store it, or kill it before returning.
     }

Handlers
========

Handlers are access points through which users can interact with elements in a running Click router, or with the router as a whole. Read and write handlers behave like files in a file system, while LLRPCs provide a remote procedure call interface.

Read and Write Handler Overview
-------------------------------

Read and write handlers appear to the user like files in a file system, or alternatively, like a limited RPC mechanism that uses ASCII strings for data transfer. To the element programmer, a read handler is simply a function that takes an element and returns a String; a write handler is a function that takes an element and a String and returns an error code.

 -- Function Type: String (*ReadHandler) (Element *ELEMENT, void *THUNK)
     Read handler functions have this type. When the user accesses a read handler on an element, Click calls some ReadHandler function and passes the element as an argument. The THUNK argument contains callback data specified when the handler was added. The function's String return value is passed back to the user.

 -- Function Type: int (*WriteHandler) (const String &DATA, Element *ELEMENT, void *THUNK, ErrorHandler *ERRH)
     Write handler functions have this type. When the user accesses some element write handler by passing in a string, Click calls some WriteHandler function and passes the data and the relevant element as arguments. The THUNK argument contains callback data specified when the handler was added. The return value is an error code: zero when there are no errors, and the negative of some errno value when there is an error. More detailed information about any errors should be reported to the ERRH argument.

Each handler has an ASCII name. Handler names must be unique within each element; for example, there can be at most one x read handler in a given element. A given name can be shared by a read handler and a write handler, however. Such a handler pair is colloquially called a ``read/write handler'', although its two components need not have anything to do with one another.

There is currently no way to pass data to a read handler or return data from a write handler. Use LLRPCs if you need a more RPC-like read-write interface.

Note that read and write handler functions are regular functions, not virtual functions. Often, therefore, handler functions are defined as private static member functions in the relevant element class.

Read and write handlers need not use ASCII-formatted data. Most existing handlers do format their data in ASCII, however, and use cp_uncomment to ignore leading and trailing whitespace and comments (see Quoting and Unquoting). You may want to do the same for consistency's sake.

Be careful when writing handlers that modify element state, or read state that packet processing can modify. On an SMP machine, a handler may be called on one processor while packets are passing through the router on another processor. Furthermore, multiple read handlers and safe LLRPCs (see LLRPC Overview) may be active simultaneously on different processors. Write handlers are serialized with respect to other handlers and LLRPCs (but not packet processing). That is, no other handler or LLRPC will proceed while a write handler is active.

Adding Handlers
---------------

Use Element's add_read_handler and add_write_handler methods to add handlers for an element. You will generally call these methods only from within your element's add_handlers method, although nothing prevents you from adding handlers at any time.

 -- Method on Element: void add_read_handler (const String &NAME, ReadHandler FUNC, void *THUNK)
     Adds a read handler named NAME for this element. When the handler is accessed, FUNC will be called with this and THUNK as parameters.

 -- Method on Element: void add_write_handler (const String &NAME, WriteHandler FUNC, void *THUNK)
     Adds a write handler named NAME for this element. When the handler is accessed, FUNC will be called with the relevant data, this, THUNK, and an ErrorHandler as parameters.

To create a read/write handler, call add_read_handler and add_write_handler and supply the same handler name.

These methods simply forward their requests to static add_read_handler and add_write_handler methods on the Router class. Call those methods directly to add handlers to other elements, or to add global handlers.

 -- Static Method on Router: void add_read_handler (const Element *ELEMENT, const String &NAME, ReadHandler FUNC, void *THUNK)
 -- Static Method on Router: void add_write_handler (const Element *ELEMENT, const String &NAME, WriteHandler FUNC, void *THUNK)
     Adds a read or write handler for ELEMENT, or a global read or write handler if ELEMENT is null. The handler is named NAME.

The change_handler_flags method lets you change a handler's flags word (see Handler Objects).

 -- Static Method on Router: void change_handler_flags (Element *ELEMENT, const String &NAME, uint32_t CLEAR_FLAGS, uint32_t SET_FLAGS)
     Changes the flags for ELEMENT's NAME handler, or the global NAME handler if ELEMENT is null. The flags are changed by first clearing the bits set in CLEAR_FLAGS, then setting the bits set in SET_FLAGS. This method fails and returns -1 when the specified handler does not exist; otherwise, it returns 0.

Default Read and Write Handlers
-------------------------------

Every element automatically provides five handlers, `class', `name', `config', `ports', and `handlers'. There is no need to add these handlers yourself. The default handlers behave as follows:

`class'
     Returns the element's class name, as returned by class_name(), followed by a newline. Example result: "ARPQuerier\n".

`name'
     Returns the element's name, as returned by id(), followed by a newline. Example result: "arpq_0\n".

`config'
     Returns the element's configuration string. If the configuration string does not end in newline, the hander appends a newline itself. Example result: "18.26.7.1, 00:00:C0:4F:71:EF\n".

     If can_live_reconfigure returns true, `config' is also a write handler, and writing to it reconfigures the element.

`ports'
     Returns a multi-line string describing the element's ports and what they are connected to. The string has the form

          M input[s]
          ... M input port descriptions, one per line ...
          N output[s]
          ... N output port descriptions, one per line ...

     Each port description lists the port's processing type, a dash, and then a comma-separated list of all the ports to which this port is connected. The processing type is either push or pull; formerly agnostic ports are indicated by a trailing tilde (push~ or pull~). Example result:

          1 input
          push~   -       Strip@2 [0]
          2 outputs
          push~   -       [0] GetIPAddress@4
          push    -       [0] Print@7

     If Click was compiled with statistics collection enabled, the dash on each line is replaced by a packet count.

`handlers'
     Returns a string listing the element's visible handlers, one per line. Each line contains the handler name, a tab, and then either r, w, or rw, depending on whether the handler is read-only, write-only, or read/write. Example result for an ->InfiniteSource element, which has many handlers:

          scheduled       r
          tickets r
          reset   w
          count   r
          active  rw
          burstsize       rw
          limit   rw
          data    rw
          handlers        r
          ports   r
          config  rw
          name    r
          class   r

Accessing Handlers Internally
-----------------------------

Element handlers are stored in the relevant Router as objects of type Router::Handler. (This design allows handler objects to be shared between elements when possible.) Handlers are often referred to by index; indexes between 0 and Router::FIRST_GLOBAL_HANDLER - 1 refer to element handlers, while indexes above Router::FIRST_GLOBAL_HANDLER refer to global handlers. Indexes less than 0 are used for error returns, such as nonexistent handlers. Router methods translate between handler indexes and Router::Handler objects, and find handlers or handler indexes given handler names.

The Router::Handler Type
........................

The Router::Handler type allows you to check a handler's properties and call the handler. All of its methods are const; you must go through Router to change a handler's properties. Router::Handler objects do not contain element references, since they are shared among elements. That means you can't easily find the element (if any) to which a particular Router::Handler is attached.

 -- Method on Router::Handler: const String & name () const
     Returns the handler's name.

 -- Method on Router::Handler: uint32_t flags () const
     Returns the handler's flags as an integer. The lower bits of the flags word are reserved for the system, and four bits are reserved for drivers, but the upper bits (at least 16) are left uninterpreted, and may be used by elements. The first user flag bit is called Router::Handler::USER_FLAG_0; its position in the word equals Router::Handler::USER_FLAG_SHIFT. To change a handler's flags, use the Router::change_handler_flags method (see Changing Handler Flags).

 -- Method on Router::Handler: bool readable () const
     Returns true iff this handler is readable.

 -- Method on Router::Handler: bool read_visible () const
     Returns true iff this handler is readable, and that read handler should be externally visible. Drivers and the ControlSocket element use read_visible rather than readable when deciding whether to tell the user that a read handler exists. Inter-element communication within the router, however, may use readable rather than read_visible.

 -- Method on Router::Handler: bool writable () const
 -- Method on Router::Handler: bool write_visible () const
     The analogous methods for write handlers.

 -- Method on Router::Handler: bool visible () const
     Equivalent to read_visible() || write_visible().

 -- Method on Router::Handler: String unparse_name (Element *ELEMENT) const
     Returns the handler's name, including its attached element's name if ELEMENT is non-null. For example, calling unparse_name on element e's foo handler would return e.foo, while calling it on a global bar handler would return bar.

 -- Static Method on Router::Handler: String unparse_name (Element *ELEMENT, const String &NAME)
     Returns a string representing ELEMENT's hypothetical NAME handler, or the global NAME handler if ELEMENT is null.

 -- Method on Router::Handler: String call_read (Element *ELEMENT) const
     Calls this read handler on ELEMENT and returns the result. Do not use this method unless you know the handler is readable().

 -- Method on Router::Handler: int call_write (const String &DATA, Element *ELEMENT, ErrorHandler *ERRH) const
     Calls this write handler on ELEMENT, passing it DATA and ERRH, and returns the result. Do not use this method unless you know the handler is writable().

Handlers By Name or Index
.........................

These Router methods locate handlers by name, returning either a pointer to a handler object or a handler index. The methods are static to allow access to global handlers outside the context of a running router.

 -- Static Method on Router: const Router::Handler * handler (const Element *ELEMENT, const String &NAME)
     Returns a pointer to the handler object for ELEMENT's handler named NAME, or null if no such handler exists. ELEMENT may be null, in which case the method looks for a global handler named NAME.

     Caution: Handler pointers returned by Router::handler and similar methods should be treated as transient, since they may become invalid when new handlers are added.

 -- Static Method on Router: int hindex (const Element *ELEMENT, const String &NAME)
     Like Router::handler, above, but returns an integer handler index for the named handler, or a negative number if no such handler exists. All valid handler indexes are nonnegative.

 -- Static Method on Router: const Router::Handler * handler (const Router *ROUTER, int HINDEX)
     Returns ROUTER's handler object corresponding to HINDEX, or a null pointer if HINDEX is invalid with respect to ROUTER. There are three possibilities: (1) HINDEX coresponds to a valid global handler, which is returned. In this case, ROUTER need not be valid. (2) HINDEX corresponds to a valid local handler in class ROUTER, which is returned. (3) Otherwise, a null pointer is returned.

 -- Static Method on Router: const Router::Handler * handler (const Element *ELEMENT, int HINDEX)
     Convenience function equivalent to handler(ELEMENT->router(), HINDEX). Note that HINDEX need not refer to one of ELEMENT's handlers.

 -- Method on Router: const Router::Handler * handler (int HINDEX) const
     Convenience function equivalent to handler(this, HINDEX).

Finally, the element_hindexes static method returns all the handler indices that apply to a given element.

 -- Static Method on Router: void element_hindexes (const Element *ELEMENT, Vector<int> &RESULTS)
     Appends to RESULTS all the handler indexes for ELEMENT's handlers, or all global handlers if ELEMENT is null.

LLRPC Overview
--------------

Configuration Strings
*********************

Structure
=========

Configuration strings consist of a list of comma-separated arguments. For example, this configuration string has three arguments, a, b, and c:

     a,    b          , c

Leading and trailing whitespace is trimmed from each argument.

Configuration strings can contain two kinds of comments and three kinds of quoted strings. Comments let you document a configuration string; they behave like spaces. With quoted strings, you can protect special characters like whitespace, commas, and comment-starting sequences from interpretation.

// comments
     Begins with two adjacent slashes, //, and continues up to and including the next end-of-line (\n, \r, or \r\n). Comment starters (// and /*) and the quote sequences (', ", and \<) have no special meaning inside // comments.

/* ... */ comments
     Begins with slash-star, /*, and continues up to and including the next star-slash, */. Comment starters (/* and //) and the quote sequences (', ", and \<) have no special meaning inside /* comments.

Single-quoted strings ' ... '
     Begins with a single-quote character ' and continues up to the next single quote. Comments, double quotes, and backslashes have no special meaning inside single quotes. There is no way to include a single quote in a single-quoted string.

Double-quoted strings " ... "
     Begins with a double-quote character " and continues up to the next unescaped double quote. Backslash \ acts as an escape character inside double quotes, as in C. Click's escape sequences are described below. Comments and single quotes have no special meaning inside double quotes. \< retains its usual meaning, however.

Hex strings \< ... >
     The \< sequence begins a string of hexadecimal digits terminated by >. Each pair of digits expands to the corresponding character value. For example, \<48454c4c4F> expands to HELLO. Whitespace and comments (either // or /* style) may be arbitrarily interleaved with the hex digits; any > characters inside comments are ignored. Characters other than whitespace, hex digits, comments, and > should not appear inside a hex string.

     Hex strings may be placed within double-quoted strings.

Escape Sequences
................

Most of Click's escape sequences are borrowed from C, and behave the same way. The \< ... > escape sequence is new, however.

\END-OF-LINE
     A backslash followed by an end-of-line sequence---\n, \r, or \r\n---is removed from the string. This string

          "a\
          b"

     is equivalent to "ab".

\a, \b, \t, \n, \v, \f, \r
     These escape sequences produce the characters with decimal ASCII values 7, 8, 9, 10, 11, 12, and 13, respectively.

\\, \", \', \$
     These escape sequences expand to a literal backslash, double quote, single quote, and dollar sign, respectively.

\1 TO 3 OCTAL DIGITS
     A backslash followed by 1 to 3 octal digits (0 ... 7) expands to the character with that octal value. For example, \046 expands to &.

\xHEX DIGITS
     \x followed by an arbitrary number of hexadecimal digits expands to the single character whose value equals the lower 8 bits of that number. Thus, \x45 and \x94839E89DB00ACF45 both expand to E.

\< HEX DIGITS >
     \< introduces a hex string, as described above.

Any other escape sequence \CHAR is an error. Currently, such sequences expand to CHAR, but their semantics may eventually change.

Quoting and Unquoting
=====================

These functions interpret quote sequences and comments in configuration strings. cp_uncomment removes comments and leading and trailing whitespace, but does not expand quote sequences. cp_unquote both removes comments and expands quote sequences. Finally, cp_quote protects special characters, such as whitespace and commas, within double quotes.

 -- Function: String cp_uncomment (const String &STR)
     Replaces any comments in STR by single spaces, then removes any leading and trailing whitespace and returns the result.

 -- Function: String cp_unquote (const String &STR)
     Replaces any comments in STR by single spaces, then removes any leading and trailing whitespace. Finally, replaces every quoted string by its expansion and returns the result.

 -- Function: String cp_quote (const String &STR, bool ALLOW_NEWLINES = false)
     Returns a quoted version of STR. Any whitespace, commas, comments, quote sequences, and non-ASCII characters in STR are protected within double quotes. If ALLOW_NEWLINES is true, then the result may contain newline characters (within double quotes); otherwise, any newline characters in STR are replaced by \n sequences. The returned result is never empty (unless Click has run out of memory). If STR is the empty string, cp_quote will return "" (a string containing two double quotes).

For example:

     cp_uncomment(``  /* blah */ "quote"/*xx*/\<2 c>'') => ``"quote" \<2 c>''
     cp_unquote(``  /* blah */ "quote"/*xx*/\<2 c>'') => ``quote ,''
     cp_quote(``quote ,'') => ``"quote ,"''

Splitting and Combining
=======================

 -- Function: void cp_argvec (const String &STR, Vector<String> &CONF)
     Splits STR into arguments by breaking it at every comma not part of a quote or comment. Comments and leading and trailing whitespace are removed from each argument, as by cp_uncomment, and the results are pushed, in order, onto the vector CONF. If STR contains only whitespace and comments, nothing is pushed onto CONF.

 -- Function: void cp_spacevec (const String &STR, Vector<String> &CONF)
     Splits STR into arguments by breaking it at every sequence of whitespace characters and/or comments. Leading and trailing whitespace is removed from each argument, as by cp_uncomment, and the results are pushed, in order, onto the vector CONF. If STR contains only whitespace and comments, nothing is pushed onto CONF.

For example:

     cp_argvec(``  x/* ,,, */ab" c",  \<de>  , ',''', VEC)
            => 3 arguments:   ``x ab" c"''   ``\<de>''   ``','''
     cp_argvec(``  /* blah, blah, blah, blah */  '', VEC)
            => 0 arguments
     cp_argvec(``  /* blah, blah, blah, blah */,  '', VEC)
            => 2 empty arguments:   ``''   ``''
     cp_spacevec(``  x/* ,,, */yz" w"  \<d e>  ""'', VEC)
            => 4 arguments:   ``x''   ``yz" w"''   ``\<d e>''   ``""''
     cp_spacevec(``  /* blah, blah, blah, blah */  '', VEC)
            => 0 arguments
     cp_spacevec(``  /* blah, blah, blah, blah */,  '', VEC)
            => 1 argument:   ``,''

Since the const Vector<String> &CONF arguments passed to elements' configure methods have been processed by cp_argvec, there is no need to process them with cp_uncomment.

The cp_unargvec and cp_unspacevec functions take a vector of arguments and combine them into a single string. These functions do not protect their arguments by quoting; use cp_quote explicitly when necessary (see Quoting and Unquoting). If the arguments are properly quoted, then calling cp_argvec(cp_unargvec(CONF), CONF2) or cp_spacevec(cp_unspacevec(CONF), CONF2) will produce a new vector of arguments equal to the original.

 -- Function: String cp_unargvec (const Vector<String> &CONF)
     Returns a string consisting of the elements of CONF separated by , .

 -- Function: String cp_unspacevec (const Vector<String> &CONF)
     Returns a string consisting of the elements of CONF separated by .

For example:

     cp_unargvec([``x ab" c"'', ``\<de>'', ``','''])
            => ``x ab" c", \<de>, ','''
     cp_unargvec([``whatever''])
            => ``whatever''
     cp_unargvec([ ])
            => ``''
     cp_unargvec([``,'', ``,''])
            (Probably a mistake: caller should have quoted the arguments!)
            => ``,, ,''
     cp_unspacevec([``xy" z"'', ``\<de>'', ``','''])
            => ``xy" z" \<de> ','''

Parsing Functions
=================

Click's parsing functions parse strings into various kinds of data, such as integers, fixed-point real numbers, and IP addresses. Parsing functions follow some consistent conventions:

  * Their first argument, const String &STR, contains the string to be parsed.

  * At least one additional argument points to a location where any parsed result should be stored. These RESULT arguments have pointer type.

  * Their return type is bool.

  * They return true if and only if parsing succeeds.

  * The values pointed to by the RESULT arguments are modified only if parsing succeeds.

  * Most parsing functions expect to parse the entire supplied string. Any extraneous characters, such as trailing whitespace, cause parsing to fail.

  * Parsing functions never report errors to any source; they simply return false when parsing fails.

Strings and Words
-----------------

These functions parse strings from their input strings. The resulting strings may be arbitrary (cp_string) or constrained (cp_word, cp_keyword). As noted above (see Parsing Functions), the functions have bool return type; they return true if parsing was successful.

 -- Parsing Function: bool cp_string (const String &STR, String *RESULT, String *REST = 0)
     Parses a string from the beginning of STR and stores the result in *RESULT. The parsed string may contain single and double quotes and hex strings (``\< ... >''), which are processed as by cp_unquote (see Quoting and Unquoting).

     If the REST argument is null and STR contains any unquoted whitespace, then parsing will fail. If REST is not null, then parsing stops at the first unquoted whitespace character, and any leftover portion of STR is stored in *REST.

     For example:

          cp_string(``"a b c d"'', RESULT) => true
                 *RESULT = ``a b c d''
          cp_string(``'', RESULT) => false
          cp_string(``""'', RESULT) => true
                 *RESULT = ``''
          cp_string(`` "a b c d"'', RESULT) => false
                 (STR began with an unquoted space)
          cp_string(``"a b c d" e'', RESULT) => false
                 (STR contained an unquoted space)
          cp_string(``"a b c d" e'', RESULT, REST) => true
                 *RESULT = ``a b c d'', *REST = `` e''

 -- Parsing Function: bool cp_word (const String &STR, String *RESULT, String *REST = 0)
     Parses a word from the beginning of STR and stores the result in *RESULT. A word is a string that does not contain whitespace, control characters, non-ASCII characters (with values 127 or higher), or special characters (', ", \, or ,). STR may contain single and double quotes and hex strings (``\< ... >''), which are processed as by cp_unquote (see Quoting and Unquoting). The unquoted result must not contain quote marks, whitespace, or other special characters, however. Returns true if and only if STR contained a valid word.

     If the REST argument is null and STR contains any unquoted whitespace, then parsing will fail. If REST is not null, then parsing stops at the first unquoted whitespace character, and any leftover portion of STR is stored in *REST.

     For example:

          cp_word(``word'', RESULT) => true
                 *RESULT = ``word''
          cp_word(``"wor"\<64>'', RESULT) => true
                 *RESULT = ``word''
          cp_word(``"wor d"'', RESULT) => false
                 (processed string contained a space)

 -- Parsing Function: bool cp_keyword (const String &STR, String *RESULT, String *REST = 0)
     Parses a keyword from the beginning of STR and stores the result in *RESULT. A keyword is a string consisting of one or more letters, numbers, underscores (_), periods (.), and colons (:). Keywords may not contain quoted substrings---', ", and \< are not allowed. Returns true if and only if STR contained a valid keyword.

     If the REST argument is null and STR contains any unquoted whitespace, then parsing will fail. If REST is not null, then parsing stops at the first unquoted whitespace character, and any leftover portion of STR is stored in *REST.

     For example:

          cp_keyword(``word'', RESULT) => true
                 *RESULT = ``word''
          cp_keyword(``"wor"\<64>'', RESULT) => false
                 (quotes not allowed in keywords)

To summarize:

  * cp_string and cp_word allow quoted substrings; cp_keyword does not.

  * cp_string results may contain arbitrary characters; cp_word and cp_keyword restrict the characters allowed in their results.

  * If cp_keyword(STR, RESULT) is true, then cp_word(STR, RESULT) is true.

  * If cp_word(STR, RESULT) is true, then cp_string(STR, RESULT) is true.

Booleans
--------

The cp_bool function parses a string into a Boolean value.

 -- Parsing Function: bool cp_bool (const String &STR, bool *RESULT)
     Parses STR into a Boolean value and stores the result in *RESULT. Allowable Boolean strings are as follows:

     0, false, no
          *RESULT becomes false.

     1, true, yes
          *RESULT becomes true.

     The words must be all lower case.

Integers
--------

cp_integer and cp_unsigned parse strings into int and unsigned int values, respectively.

Each function comes in two variants, one with a BASE parameter and one without. If BASE is 0 or unspecified, then the function examines the string to determine the relevant base. Strings beginning with 0x or 0X (after the optional sign) use base 16; other strings beginning with 0 use base 8; and all other strings use base 10. Nonzero BASEs must be at least 2 and no more than 36.

The functions accept the same strings as C's strtol function, except that strtol will accept leading whitespace and trailing characters that are not part of the parsed integer. The string should contain, in order:

  * An optional + or - sign. (The cp_unsigned functions do not accept a minus sign.)

  * An optional 0x or 0X, if the BASE argument is 0 or 16.

  * One or more alphanumeric digits. The maximum allowed digit is specified by BASE.

If a string contains a valid number too large (or small) to represent, the parsing function sets cp_errno to CPE_OVERFLOW, stores the largest (or smallest) allowable number in RESULT, and returns true. If a function succeeds without overflow, cp_errno is set to CPE_OK.

 -- Parsing Function: bool cp_integer (const String &STR, int *RESULT)
 -- Parsing Function: bool cp_integer (const String &STR, int BASE, int *RESULT)
     Parses STR into a signed integer in base BASE and stores the result in *RESULT. Detects overflow on numbers greater than 2147483647 or less than -2147483648.

 -- Parsing Function: bool cp_unsigned (const String &STR, unsigned *RESULT)
 -- Parsing Function: bool cp_unsigned (const String &STR, int BASE, unsigned *RESULT)
     Parses STR into an unsigned integer in base BASE and stores the result in *RESULT. Detects overflow on numbers greater than 4294967295.

For example:

     cp_integer(-0x8000, RESULT) => true
            *RESULT = -32768, cp_errno = CPE_OK
     cp_integer(-0x8000 , RESULT) => false
            (trailing whitespace not allowed)
     cp_unsigned(3333333333333333, 4, RESULT) => true
            *RESULT = 4294967295, cp_errno = CPE_OK
     cp_unsigned(33333333333333333, 4, RESULT) => true
            *RESULT = 4294967295, cp_errno = CPE_OVERFLOW

Real Numbers
------------

Several functions parse real numbers into fixed-point integers. (Some drivers, such as the Linux kernel driver, can't use floating point arithmetic, so doubles are not allowed.)

Each function takes an integer argument that determines how many digits of fraction the result should have. Since the result is a single fixed-point number, the more digits of fraction in the result, the fewer digits are available for the integer part.

You may request binary or decimal digits of fraction. The real10 function variants use decimal digits, while the real2 variants use binary digits: bits. For example, cp_real10(1, 2, RESULT), which parses the string 1 with 2 decimal digits of fraction, yields the number 100 (10^2). The similar call to a binary-digit function, cp_real2(1, 2, RESULT), yields 4 (2^2). Parsing 0.5 with the same functions yields 50 and 2, respectively.

A real number string should contain, in order:

  * An optional + or - sign. (The unsigned variants do not accept minus signs.)

  * An optional sequence of decimal digits representing the integer part.

  * An optional fraction point ..

  * An optional sequence of decimal digits representing the fraction part.

  * An optional exponent---an E or e character followed by a signed decimal integer.

The string must contain at least one digit in either the integer part or the fraction part.

All the parsing functions round to the nearest relevant number. For example, cp_real10(0.59, 1, RESULT) stores 6 in RESULT, since 0.59 rounded to one digit of fraction is 0.6.

If a string contains a real number too large in magnitude for the specified format, the parsing function will set cp_errno to CPE_OVERFLOW, store the largest representable number in RESULT, and return true. For example, the largest number representable as an unsigned integer with 16 bits of fraction is 65535.99998, which has the bit pattern 0xFFFFFFFF. Therefore, cp_unsigned_real2(65536, 16, RESULT) stores 0xFFFFFFFF in RESULT and sets cp_errno to CPE_OVERFLOW. If there was no overflow or other error, cp_errno is set to CPE_OK.

 -- Parsing Function: bool cp_unsigned_real10 (const String &STR, int FRAC_DIGITS, unsigned *RESULT)
     Parses STR into an unsigned real number, and stores the result in RESULT as an unsigned integer with FRAC_DIGITS decimal digits of fraction.

 -- Parsing Function: bool cp_real10 (const String &STR, int FRAC_DIGITS, int *RESULT)
     Parses STR into a unsigned real number, and stores the result in RESULT as an integer with FRAC_DIGITS decimal digits of fraction.

 -- Parsing Function: bool cp_unsigned_real2 (const String &STR, int FRAC_BITS, unsigned *RESULT)
     Parses STR into an unsigned real number, and stores the result in RESULT as an unsigned integer with FRAC_BITS bits of fraction.

 -- Parsing Function: bool cp_real2 (const String &STR, int FRAC_BITS, int *RESULT)
     Parses STR into a real number, and stores the result in RESULT as an integer with FRAC_BITS bits of fraction.

The fixed-point real parsing functions are built on a lower-level variant that returns the integer and fraction parts in two different unsigned ints.

 -- Parsing Function: bool cp_unsigned_real10 (const String &STR, int FRAC_DIGITS, unsigned *INT_RESULT, unsigned *FRAC_RESULT)
     Parses STR into an unsigned real number and stores the result in INT_RESULT and FRAC_RESULT. INT_RESULT holds the integral part of the resulting real, while FRAC_RESULT holds its fractional part as a fixed-point number with FRAC_DIGITS decimal digits of fraction. FRAC_RESULT is always less than 10^FRAC_DIGITS.

For example:

     cp_unsigned_real10(10.952, 3, INT_RESULT, FRAC_RESULT) => true
            *INT_RESULT = 10, *FRAC_RESULT = 952
     cp_unsigned_real10(10.9526, 3, INT_RESULT, FRAC_RESULT) => true
            *INT_RESULT = 10, *FRAC_RESULT = 953
            (note rounding)
     cp_unsigned_real10(10.9996, 3, INT_RESULT, FRAC_RESULT) => true
            *INT_RESULT = 11, *FRAC_RESULT = 0

IP Addresses
------------

The cp_ip_address functions parse strings into IP addresses. Related cp_ip_prefix and cp_ip_address_set functions parse strings into IP address/netmask pairs and sets of IP addresses, respectively.

Parsable IP addresses are simply dotted quads like 18.26.4.44. IP prefixes may be specified using CIDR notation, such as 18.26.4.44/16; as explicit address/netmask pairs, such as 18.26.4.44/255.255.0.0; or, optionally, as bare IP addresses, such as 18.26.4.44 (which means 18.26.4.44/255.255.255.255).

Besides these conventional forms, the cp_ip functions understand user-defined shorthand names for IP addresses and prefixes. Shorthand names are router-specific; users define them with ->AddressInfo elements. Furthermore, a name's meaning is dependent on its context: an ->AddressInfo inside a compound element defines shorthand names local to that compound element. The cp_ip functions, then, take optional Element *CONTEXT arguments to specify any router and compound-element context. If a cp_ip function's CONTEXT argument is null, it will parse only the conventional IP address forms described above.

 -- Parsing Function: bool cp_ip_address (const String &STR, unsigned char *RESULT, Element *CONTEXT = 0)
 -- Parsing Function: bool cp_ip_address (const String &STR, IPAddress *RESULT, Element *CONTEXT = 0)
     Parses STR into an IP address and stores the result in *RESULT. CONTEXT supplies any element context.

 -- Parsing Function: bool cp_ip_prefix (const String &STR, unsigned char *RESULT_ADDR, unsigned char *RESULT_MASK, Element *CONTEXT = 0)
 -- Parsing Function: bool cp_ip_prefix (const String &STR, IPAddress *RESULT_ADDR, IPAddress *RESULT_MASK, Element *CONTEXT = 0)
     Parses STR into an IP address/netmask pair and stores the resulting address in *RESULT_ADDR, and the resulting netmask in *RESULT_MASK. The resulting address is not pre-masked by the resulting mask. For example, cp_ip_prefix(18.26.4.44/16, RESULT_ADDR, RESULT_MASK) stores 18.26.4.44 in RESULT_ADDR, not 18.26.0.0. Bare addresses, such as 18.26.4.44, are never allowed.

 -- Parsing Function: bool cp_ip_prefix (const String &STR, unsigned char *RESULT_ADDR, unsigned char *RESULT_MASK, bool ALLOW_BARE_ADDR, Element *CONTEXT = 0)
 -- Parsing Function: bool cp_ip_prefix (const String &STR, IPAddress *RESULT_ADDR, IPAddress *RESULT_MASK, bool ALLOW_BARE_ADDR, Element *CONTEXT = 0)
     Parses STR into an IP address/netmask pair and stores the resulting address in *RESULT_ADDR and netmask in *RESULT_MASK. Bare addresses, such as 18.26.4.44, are allowed if and only if ALLOW_BARE_ADDR is true. The netmask corresponding to a bare address is 255.255.255.255.

Finally, the cp_ip_address_list function parses a whitespace-separated list of IP addresses into to an IPAddressList object.

 -- Parsing Function: bool cp_ip_address_list (const String &STR, IPAddressList *RESULT, Element *CONTEXT = 0)
     Parses STR into a list of IP addresses and stores the result in *RESULT. STR must be a whitespace-separated list of IP addresses, which can take any of the forms accepted by cp_ip_address.

IPv6 Addresses
--------------

The cp_ip6_address functions parse strings into IPv6 addresses. Related cp_ip6_prefix functions parse strings into IPv6 address/netmask pairs.

Parsable IPv6 addresses and prefixes take any of the forms described in RFC 2373, IP Version 6 Addressing Architecture. A nonabbreviated address consists of eight colon-separated 16-bit hexadecimal numbers, as in 1080:0:0:0:8:800:200C:417A. Strings of zero bits may be abbreviated with two colons, as in 1080::8:800:200C:417A, and an address may end in an embedded IPv4 address, as in ::13.1.68.3 and ::FFFF:129.144.52.38. IPv6 prefixes are written in ADDRESS/PREFIXLEN form, like 12AB:0:0:CD30::/60. Click also supports ADDRESS/NETMASK syntax, where NETMASK is an IPv6 address. NETMASK must correspond to some contiguous prefix, however: 12AB:0:0:CD30::/60 and 12AB:0:0:CD30::/FFFF:FFFF:FFFF:FFF0:: are equivalent, but 12AB:0:0:CD30::/FFFF::1 is illegal.

Analogously to the cp_ip functions (see Parsing IP Addresses), the cp_ip6 functions understand ->AddressInfo's shorthand names for IPv6 addresses, and take optional Element *CONTEXT arguments to specify any router and compound-element context.

 -- Parsing Function: bool cp_ip6_address (const String &STR, unsigned char *RESULT, Element *CONTEXT = 0)
 -- Parsing Function: bool cp_ip6_address (const String &STR, IP6Address *RESULT, Element *CONTEXT = 0)
     Parses STR into an IPv6 address and stores the result in *RESULT. CONTEXT supplies any element context.

 -- Parsing Function: bool cp_ip6_prefix (const String &STR, unsigned char *RESULT_ADDR, int *RESULT_PREFIX_LEN, bool ALLOW_BARE_ADDR, Element *CONTEXT = 0)
 -- Parsing Function: bool cp_ip6_prefix (const String &STR, IP6Address *RESULT_ADDR, int *RESULT_PREFIX_LEN, bool ALLOW_BARE_ADDR, Element *CONTEXT = 0)
     Parse STR into an IPv6 address/prefix length pair and stores the resulting address in *RESULT_ADDR, and the resulting prefix length in *RESULT_PREFIX_LEN. Bare addresses, such as 1080::8:800:200C:417A, are allowed if and only if ALLOW_BARE_ADDR is true. The prefix length corresponding to a bare address is 128.

 -- Parsing Function: bool cp_ip6_prefix (const String &STR, unsigned char *RESULT_ADDR, unsigned char *RESULT_MASK, bool ALLOW_BARE_ADDR, Element *CONTEXT = 0)
 -- Parsing Function: bool cp_ip6_prefix (const String &STR, IP6Address *RESULT_ADDR, IP6Address *RESULT_MASK, bool ALLOW_BARE_ADDR, Element *CONTEXT = 0)
     Parse STR into an IPv6 address/prefix length pair and stores the resulting address in *RESULT_ADDR, and the netmask corresponding to the resulting prefix length in *RESULT_MASK. Bare addresses are allowed if and only if ALLOW_BARE_ADDR is true.

Ethernet Addresses
------------------

The cp_ethernet_address functions parse strings into Ethernet addresses. A parsable Ethernet address consists of six colon-separated 8-bit hexadecimal numbers, as in 0:2:B3:06:36:EE.

Analogously to the cp_ip functions (see Parsing IP Addresses), the cp_ethernet_address functions understand ->AddressInfo's shorthand names for Ethernet addresses, and take optional Element *CONTEXT arguments to specify any router and compound-element context.

 -- Parsing Function: bool cp_ethernet_address (const String &STR, unsigned char *RESULT, Element *CONTEXT = 0)
 -- Parsing Function: bool cp_ethernet_address (const String &STR, EtherAddress *RESULT, Element *CONTEXT = 0)
     Parses STR into an Ethernet address and stores the result in *RESULT. CONTEXT supplies any element context.

Elements
--------

cp_element parses an element name into a pointer to an element in some router configuration. It differs from other parsing functions in two important ways. First, it returns its result, or a null pointer on error; parsing functions store their results in some pointer. Second, it reports errors to the supplied ErrorHandler.

The cp_element function follows lexical scoping rules when called from a compound element: it will check for components of that compound element first. For instance, say you've called cp_element on the string e. Normally, this would check the router for an element named, simply, e. However, if called within a compound element x, cp_element will first check for an element named x/e before looking for the global e element. The function uses its CONTEXT argument, an element pointer, to determine both the relevant router object and any compound element context.

More explicitly, the cp_element function uses the following procedure to search for an element named STR:

 1. Set PREFIX to CONTEXT->id().

 2. Remove the final component of PREFIX.

 3. Search for an element named PREFIXSTR in CONTEXT->router(). If one is found, return it.

 4. Otherwise, no element was found. If PREFIX is already empty, parsing fails; report an error to ERRH and return a null pointer. Otherwise, return to step 2.

 -- Function: Element * cp_element (const String &STR, Element *CONTEXT, ErrorHandler *ERRH)
     Returns a element named STR in CONTEXT's router configuration. STR is first processed as by cp_unquote. CONTEXT determines both the relevant router configuration and any compound element context. Returns a null pointer if no element is found; if ERRH is nonnull and no element is found, additionally reports an error to ERRH.

A variant function does not perform a lexically scoped search, so its STR argument must contain a fully-qualified element name.

 -- Function: Element * cp_element (const String &STR, Router *ROUTER, ErrorHandler *ERRH)
     Returns a element named STR in ROUTER. STR is first processed as by cp_unquote. Returns a null pointer if no element is found; if ERRH is nonnull and no element is found, additionally reports an error to ERRH.

Handlers
--------

The cp_handler functions parse a handler specification, such as e.config, into the relevant pair of element and handler ID. Unlike most other parsing functions, it can report errors to an ErrorHandler, if one is supplied.

Most handler specifications consists of an element name and a handler name separated by a period: ELEMENT.HANDLER. The simplest cp_handler function parses such a specification into an element pointer, corresponding to ELEMENT, and the handler name, HANDLER. Like cp_element (see Parsing Elements), cp_handler uses a lexically-scoped search to find the element corresponding to a given name.

Click also supports a few global handlers, such as config. cp_handler will also parse global handler names, returning null for the element pointer.

 -- Parsing Function: bool cp_handler (const String &STR, Element *CONTEXT, Element **RESULT_ELEMENT, String *RESULT_HNAME, ErrorHandler *ERRH)
     Parses STR into a handler specification, storing the resulting element (if any) in *RESULT_ELEMENT and handler name in *RESULT_HNAME. STR is first processed as by cp_unquote. CONTEXT determines both the relevant router configuration and any compound element context. Returns true if and only if STR contained a valid handler specification whose element part named an actual element. Note that this function will not check whether *RESULT_ELEMENT actually has a handler named *RESULT_HNAME---or, for global handlers, whether the global handler *RESULT_HNAME actually exists.

The other cp_handler variants ensure that the input string names an actual handler. These variants are useless until handlers are added to the router configuration. Therefore, they should be called in elements' initialize methods, not their configure methods, since handlers are not added until initialize time.

 -- Parsing Function: bool cp_handler (const String &STR, Element *CONTEXT, Element **RESULT_ELEMENT, int *RESULT_HID, ErrorHandler *ERRH)
     Parses STR into a handler specification, storing the resulting element in *RESULT_ELEMENT and handler ID in *RESULT_HID. This function just calls the simpler cp_handler, above, then checks that the resulting element has the named handler.

 -- Parsing Function: bool cp_handler (const String &STR, Element *CONTEXT, bool NEED_READ, bool NEED_WRITE, Element **RESULT_ELEMENT, int *RESULT_HID, ErrorHandler *ERRH)
     Similar, but additionally checks for read and/or write handlers. If NEED_READ is true, then STR must name a valid read handler; if NEED_WRITE is true, then STR must name a valid write handler. Returns false if these checks aren't met.

Miscellaneous
-------------

The cp_seconds_as and cp_timeval functions parse strings into time.

 -- Parsing Function: bool cp_seconds_as (int P, const String &STR, int *RESULT)
     Parses STR as a possibly fractional length of time in seconds. The returned RESULT is measured in (seconds * 10^-P); for example, if P is 3, then RESULT is measured in milliseconds, and cp_seconds_as(3, "8", RESULT) stores 8000 in *RESULT.

     STR may contain an optional time unit suffix. Valid units are h or hr for hours, m/min for minutes, s/sec for seconds, ms/msec for milliseconds, us/usec for microseconds, and ns/nsec for nanoseconds. For example, cp_seconds_as(0, "1h", RESULT) stores 3600 in *RESULT.

     Negative values are not allowed.

 -- Parsing Function: bool cp_seconds_as_milli (const String &STR, int *RESULT)
 -- Parsing Function: bool cp_seconds_as_micro (const String &STR, int *RESULT)
     Same as cp_seconds_as(3, S, RESULT) and cp_seconds_as(6, S, RESULT), respectively.

 -- Parsing Function: bool cp_timeval (const String &STR, struct timeval *RESULT)
     Parses STR as a struct timeval representing some number of seconds and microseconds. Textually, this looks like a nonnegative real number with 6 decimal digits of fraction. Stores the integer part of the result in RESULT->tv_sec and the fraction part in RESULT->tv_usec. Basically equivalent to cp_unsigned_real10(STR, 6, 0, &RESULT->tv_sec, &RESULT->tv_usec).

Parsing Argument Lists
======================

Concepts
--------

Global Initialization
---------------------

The cp_va functions maintain some private global state---for example, a list of the data types they understand. You must explicitly initialize this state with cp_va_static_initialize before calling any other cp_va function. You can free this state, if you'd like, with cp_va_static_cleanup.

 -- Function: void cp_va_static_initialize ()
     Call this function exactly once, at the beginning of the program, before calling any other cp_va functions.

 -- Function: void cp_va_static_cleanup ()
     Call this function exactly once, at the end of the program. It is an error to call any cp_va function after calling cp_va_static_cleanup.

Constant
Storage Arguments

cpArgument
String *RESULT
cpString
String *RESULT
cpWord
String *RESULT
cpKeyword
String *RESULT

cpByte
unsigned char *RESULT
cpShort
short *RESULT
cpUnsignedShort
unsigned short *RESULT
cpInteger
int *RESULT
cpUnsigned
unsigned *RESULT

cpReal2
int FRAC_BITS, int *RESULT
cpUnsignedReal2
int FRAC_BITS, unsigned *RESULT
cpReal10
int FRAC_DIGITS, int *RESULT
cpUnsignedReal10
int FRAC_DIGITS, unsigned *RESULT

cpIPAddress
IPAddress *RESULT
cpIPPrefix
IPAddress *RESULT_ADDRESS, IPAddress *RESULT_MASK
cpIPAddressOrPrefix
IPAddress *RESULT_ADDRESS, IPAddress *RESULT_MASK
cpIPAddressList
IPAddressList *RESULT
cpEtherAddress
EtherAddress *RESULT
cpIP6Address
IP6Address *RESULT
cpIP6Prefix
IP6Address *RESULT_ADDRESS, IP6Address *RESULT_MASK
cpIP6AddressOrPrefix
IP6Address *RESULT_ADDRESS, IP6Address *RESULT_MASK

cpElement
Element **RESULT
cpHandlerName
Element **RESULT_ELEMENT, String
*RESULT_HNAME
cpHandler
Element **RESULT_ELEMENT, int *RESULT_HID
cpReadHandler
Element **RESULT_ELEMENT, int *RESULT_HID
cpWriteHandler
Element **RESULT_ELEMENT, int *RESULT_HID

cpBool
bool *RESULT
cpSeconds
int *RESULT
cpSecondsAsMilli
int *RESULT
cpSecondsAsMicro
int *RESULT
cpTimeval
struct timeval *RESULT

Constant
Corresponding Parsing Function

cpArgument
*RESULT = arg
cpString
cp_string(arg, RESULT)
cpWord
cp_string(arg, RESULT)
cpKeyword
cp_keyword(arg, RESULT)

cpByte
cp_unsigned(arg, &tmp), check range, store in
RESULT
cpShort
cp_integer(arg, &tmp), check range, store in
RESULT
cpUnsignedShort
cp_unsigned(arg, &tmp), check range, store in
RESULT
cpInteger
cp_integer(arg, RESULT)
cpUnsigned
cp_unsigned(arg, RESULT)

cpReal2
cp_real2(arg, FRAC_BITS, RESULT)
cpUnsignedReal2
cp_unsigned_real2(arg, FRAC_BITS, RESULT)
cpReal10
cp_real10(arg, FRAC_DIGITS, RESULT)
cpUnsignedReal10
cp_unsigned_real10(arg, FRAC_DIGITS, RESULT)

cpIPAddress
cp_ip_address(arg, RESULT, context)
cpIPPrefix
cp_ip_prefix(arg, RESULT_ADDRESS,
RESULT_MASK, false, context)
cpIPAddressOrPrefix
cp_ip_prefix(arg, RESULT_ADDRESS,
RESULT_MASK, true, context)
cpIPAddressList
cp_ip_address_list(arg, RESULT, context)
cpEtherAddress
cp_ether_address(arg, RESULT, context)
cpIP6Address
cp_ip6_address(arg, RESULT, context)
cpIP6Prefix
cp_ip6_prefix(arg, RESULT_ADDRESS,
RESULT_MASK, false, context)
cpIP6AddressOrPrefix
cp_ip6_prefix(arg, RESULT_ADDRESS,
RESULT_MASK, false, context)

cpElement
cp_element(arg, context, RESULT)
cpHandlerName
cp_handler(arg, context, RESULT_ELEMENT,
RESULT_HNAME)
cpHandler
cp_handler(arg, context, RESULT_ELEMENT,
RESULT_HID)
cpReadHandler
cp_handler(arg, context, true, false, RESULT_ELEMENT,
RESULT_HID)
cpWriteHandler
cp_handler(arg, context, false, true, RESULT_ELEMENT,
RESULT_HID)

cpBool
cp_bool(arg, RESULT)
cpSeconds
cp_seconds_as(0, arg, RESULT)
cpSecondsAsMilli
cp_seconds_as(3, arg, RESULT)
cpSecondsAsMicro
cp_seconds_as(6, arg, RESULT)
cpTimeval
cp_timeval(arg, RESULT)

Tasks
*****

Click schedules a router's CPU or CPUs with one or more task queues. These queues are simply lists of tasks, which represent functions that would like access to the CPU. Tasks are generally associated with elements. When scheduled, most tasks call some element's run_task method.

Click tasks are represented by Task objects. An element that would like special access to a router's CPU should include and initialize a Task instance variable.

Tasks are generally called very frequently, up to tens of thousands of times per second. For infrequent events, it is far more efficient to use timers than to use tasks; see Timers.

Executing a task should not take a long time. The Click driver loop is not currently adaptive, so very long tasks can inappropriately delay timers and other periodic events. We may address this problem in a future release, but for now, keep tasks short.

See the Doxygen documentation on class Task for more information.

The Task class is defined in the <click/task.hh> header file.

Task Initialization
===================

Task initialization is a two-step process. First, when a Task object is constructed, you must supply information about the function that it should call when it is scheduled. Second, when the router is initialized, you must initialize the task by supplying it with the relevant router. (You must initialize the task even if it will not be scheduled right away.)

Task has two constructors. One of them asks the task to call an element's run_task method when scheduled; the other asks it to call an arbitrary function pointer.

 -- Constructor on Task: Task (Element *E)
     When this task is scheduled, call E->run_task().

 -- Constructor on Task: Task (TaskHook HOOK, void *THUNK)
     When this task is scheduled, call HOOK(this, THUNK). The HOOK argument is a function pointer with type void (*)(Task *, void *).

The Task::initialize method places the task on a router-wide list of Tasks, associates the task with a particular task queue, and, optionally, schedules it. Typically, an element's initialize method calls Task::initialize.

 -- Method on Task: void initialize (Router *R, bool SCHEDULED)
 -- Method on Task: void initialize (Element *E, bool SCHEDULED)
     Attaches the task to the router object R (or E->router()). Additionally sets the task's tickets to a default value, and schedules the task if SCHEDULED is true.

Many elements call ScheduleInfo::initialize_task instead of calling Task::initialize directly. This method queries any ->ScheduleInfo elements in the configuration to determine the task's scheduling parameters, sets those parameters, and calls Task::initialize to schedule the task. The ScheduleInfo::initialize_task method is defined in the <click/standard/scheduleinfo.hh> header file.

 -- Static Method on ScheduleInfo: void initialize_task (Element *E, Task *TASK, bool SCHEDULE, ErrorHandler *ERRH)
     Sets TASK's scheduling parameters as specified by any ->ScheduleInfo elements in the router configuration. The element E is used to find the correct router, and provides the relevant name for parameter lookup---the user supplies parameters to ->ScheduleInfo by element name. If SCHEDULE is true, also schedules TASK on E->router()'s task queue. Reports any errors to ERRH.

 -- Static Method on ScheduleInfo: void initialize_task (Element *E, Task *TASK, ErrorHandler *ERRH)
     A synonym for initialize_task(E, TASK, true, ERRH).

 -- Static Method on ScheduleInfo: void join_scheduler (Element *E, Task *TASK, ErrorHandler *ERRH)
     A synonym for initialize_task(E, TASK, true, ERRH).

The initialize_task method is generally called like this:

     int
     SomeElement::initialize(ErrorHandler *errh)
     {
         ScheduleInfo::initialize_task(this, &_task, errh);
     }

Here, _task, a Task object, is one of SomeElement's instance variables.

Scheduling Tasks
================

The user may take a task off its task queue with the unschedule method, and place it back onto its task queue with the reschedule method. As tasks move to the head of the task queue, they are unscheduled and their callbacks are called. Within these callback functions, the user will typically call fast_reschedule, which is like reschedule without the locking overhead.

 -- Method on Task: void unschedule ()
     Unschedules the task by removing it from its task queue. Does nothing if if the task is currently unscheduled, or if it was never initialized. When this function returns, the task will not be scheduled.

 -- Method on Task: void reschedule ()
     Reschedules the task by placing it on its task queue. If the task is already scheduled, then this method does nothing.

All three functions lock the task queue before manipulating it. This avoids corruption when there are multiple processors executing simultaneously. If reschedule cannot immediately lock a task queue---perhaps because it is being used on another processor---then they register a task request, which will be executed in the near future. In contrast, the unschedule function will wait until it can lock the task queue.

Sometimes unscheduling a task is not enough: you don't want the task to run, even if someone else (an upstream queue, for example) were to reschedule it. The strong_unschedule method both unschedules the task and shifts the task to the quiescent thread, which never runs. Thus, a strong_unscheduled task will not run until someone calls strong_reschedule, which reschedules the task on its original preferred thread.

 -- Method on Task: void strong_unschedule ()
     Unschedules the task by removing it from its task queue and shifting it to the quiescent thread. Does nothing if if the task is currently unscheduled, or if it was never initialized. When this function returns, the task will not be scheduled.

 -- Method on Task: void strong_reschedule ()
     Reschedules the task by placing it on the task queue corresponding to its thread preference. The task will not be scheduled immediately upon return, but it will become scheduled soon---strong_reschedule uses a task request to avoid locking.

The fast_reschedule method avoids locking overhead in the common case that a task must be rescheduled from within its callback.

 -- Method on Task: void fast_reschedule ()
     Reschedules the task by placing it on its preferred task queue. This method avoids locking overhead, so it is faster than reschedule.

          Caution: You may call a Task's fast_reschedule method only from within its callback function. For instance, if an element has a task, _task, that calls the element's run_task method when scheduled, and if run_task is called only by that task's callback, then that element's run_task method should call _task.fast_reschedule() instead of _task.reschedule().

The fast_unschedule method is to unschedule as fast_reschedule is to reschedule. It is rarely used, since tasks are automatically unscheduled before they are run.

 -- Method on Task: void fast_unschedule ()
     Unschedules the task by removing it from its task queue. Does nothing if if the task is currently unscheduled, or if it was never initialized. This method avoids locking overhead, so it is faster than unschedule.

          Caution: You may call a Task's fast_unschedule method only from within its callback function.

Tickets
=======

Click tasks are scheduled using the flexible, lightweight stride scheduling algorithm. (For more information, see MIT Laboratory for Computer Science Technical Memo MIT/LCS/TM-528, Stride scheduling: deterministic proportional-share resource management, by Carl A. Waldspurger and William E. Weihl, June 1995.) This algorithm assigns each task a parameter called its tickets. A task with twice as many tickets as usual is scheduled twice as frequently.

Tasks have methods for querying, setting, and adjusting their tickets.

 -- Method on Task: int tickets () const
     Returns this task's tickets. This number will be at least 1 and no more than Task::MAX_TICKETS, which equals 32768.

 -- Method on Task: void set_tickets (int T)
     Sets this task's tickets to T. The T parameter should lie between 1 and Task::MAX_TICKETS, inclusive; numbers outside this range are constrained to the nearest valid value.

 -- Method on Task: void adj_tickets (int DELTA)
     Equivalent to set_tickets(tickets() + DELTA).

Choosing a Thread
=================

Each task belongs to some task queue, which generally corresponds to a thread of control. Single-threaded Click has one active thread, and therefore one task queue, but multithreaded Click can have an arbitrary number of threads. Either Click has a special thread, the quiescent thread, numbered -1; tasks belonging to the quiescent thread never run, whether or not they are scheduled. Every task starts out belonging to the first thread, thread 0. The change_thread method moves a task to another thread.

 -- Method on Task: void change_thread (int THREAD_ID)
     Move this task to thread THREAD_ID, which should be a number between -1 and the relevant Router's nthreads().

     The task is scheduled on the new task queue if and only if it was scheduled on the old task queue.

Like reschedule, change_thread must lock the task queue before manipulating it. (Unlike those methods, change_thread must lock two task queues, the old and the new.) If change_thread cannot lock a task queue, then it registers a task request that will be executed in the near future. This implies that a task may remain on the same thread, or become unscheduled, for some time after change_thread is called.

Task Status Methods
===================

These methods let a user check various properties of a task---for instance, whether it is initialized or scheduled.

 -- Method on Task: bool initialized () const
     Returns true iff the task has been initialized---that is, if it is associated with some router.

 -- Method on Task: bool scheduled () const
     Returns true iff the task is currently scheduled on some task queue.

 -- Method on Task: RouterThread * scheduled_list () const
     Returns the task queue with which this task is associated. Even unscheduled tasks are associated with some task queue; this is the task queue on which the task will be placed if reschedule is called.

 -- Method on Task: TaskHook hook () const
     Returns the callback function that is called when the task is scheduled. If the task is associated with some element, this method returns a null pointer.

 -- Method on Task: void * thunk () const
     Returns the extra data passed to the callback function when the task is scheduled.

 -- Method on Task: Element * element () const
     If the task is associated with some element, this method returns that element. Otherwise, returns a null pointer.

Task Handlers
=============

By convention, elements with tasks should provide handlers that access task properties. The Element::add_task_handlers method automatically adds these handlers for a given Task object.

 -- Method on Element: void add_task_handlers (Task *TASK, const String &PREFIX = String())
     Adds task handlers for TASK to this element. The string PREFIX is prepended to every handler name.

This method adds at least the following handlers:

`scheduled'
     Returns a Boolean value saying whether the task is currently scheduled on some task queue. Example result: "true\n".

`tickets'
     Returns or sets the task's currently allocated tickets. This handler is only available if Click was compiled to support stride scheduling. Example result: "1024\n".

`thread_preference'
     Returns the task's thread preference. This handler is only available on multithreaded Click. Example result: "2\n".

Task Cleanup
============

You generally don't need to worry about destroying Task objects: they are automatically unscheduled and removed when the Router is destroyed. This only works if the Task objects have the same lifetime as the Router, however. This includes the normal case, when Tasks are element instance variables. If you create and destroy Task objects as the router runs, however, you will need to call the following method before deleting the Task.

 -- Method on Task: void cleanup ()
     Cleans up the Task object.

Timers
******

Click timers, like Click tasks, represent callback functions that the driver calls when appropriate. Unlike tasks, however, you schedule timers to go off at a specified time. Timers are intended for more infrequent and/or slower tasks.

As with Task, most Timer objects are declared as instance variables of elements and scheduled when needed.

Timers may be scheduled with microsecond precision, but on current hardware, only millisecond precision is likely to be achievable.

The Timer class is defined in the <click/timer.hh> header file.

Timer Initialization
====================

Timer initialization resembles task initialization. When the timer is constructed, you must supply it with information about its callback function. Later, after the router is initialized, you must initialize and, optionally, schedule it.

 -- Constructor on Timer: Timer (Element *E)
     When this timer goes off, call E->run_timer().

 -- Constructor on Timer: Timer (Task *T)
     When this timer goes off, call T->reschedule().

 -- Constructor on Timer: Timer (TimerHook HOOK, void *THUNK)
     When this timer goes off, call HOOK(this, THUNK). The HOOK argument is a function pointer with type void (*)(Timer *, void *).

 -- Method on Timer: void initialize (Router *R)
 -- Method on Timer: void initialize (Element *E)
     Attaches the timer to the router object R (or E->router()).

Typically, an element's initialize method calls Timer::initialize, and possibly one of the schedule functions described below.

Scheduling Timers
=================

A variety of methods schedule timers to go off at specified times. The basic method is schedule_at, which schedules the timer for a specified time. Subsidiary methods schedule the timer relative to the current time (the schedule_after methods), or relative to the last time the timer was scheduled to run (the reschedule_after methods). Finally, unschedule unschedules the timer.

All schedule and reschedule functions first unschedule the timer if it was already scheduled.

The reschedule methods are particularly useful for timers that should occur periodically. For example, this callback function will cause its timer to go off at 20-second intervals:

     void timer_callback(Timer *t, void *) {
         t->reschedule_after_s(20);
     }

 -- Method on Timer: void schedule_at (const struct timeval &WHEN)
     Schedule the timer to go off at WHEN. You must have initialized the timer earlier.

 -- Method on Timer: void schedule_now ()
     Schedule the timer to go off as soon as possible.

 -- Method on Timer: void schedule_after (const struct timeval &DELAY)
     Schedule the timer to go off DELAY after the current time.

 -- Method on Timer: void schedule_after_s (uint32_t DELAY)
     Schedule the timer to go off DELAY seconds after the current time.

 -- Method on Timer: void schedule_after_ms (uint32_t DELAY)
     Schedule the timer to go off DELAY milliseconds after the current time.

 -- Method on Timer: void reschedule_after (const struct timeval &DELAY)
     Schedule the timer to go off DELAY after it was last scheduled to go off. If the timer was never previously scheduled, this method will schedule the timer for some arbitrary time.

 -- Method on Timer: void reschedule_after_s (uint32_t DELAY)
     Schedule the timer to go off DELAY seconds after it was last scheduled to go off.

 -- Method on Timer: void reschedule_after_ms (uint32_t DELAY)
     Schedule the timer to go off DELAY milliseconds after it was last scheduled to go off.

 -- Method on Timer: void unschedule ()
     Unschedules the timer, if it was scheduled.

Timer Status Methods
====================

These methods return information about a timer, including when it is scheduled to expire.

 -- Method on Timer: bool initialized () const
     Returns true iff the timer has been initialized with a call to initialize(). Uninitialized timers must not be scheduled.

 -- Method on Timer: bool scheduled () const
     Returns true iff the timer is scheduled to expire some time in the future.

 -- Method on Timer: const struct timeval & expiry () const
     Returns the time that the timer is set to expire. If the timer has never been scheduled, the value is garbage. If the timer was scheduled but is not scheduled currently, the value is most recently set expiry time.

Timer Cleanup
=============

You don't need to worry about cleaning up Timer objects. They are automatically unscheduled and removed when the Router is destroyed, and deleting a Timer automatically removes it from any relevant lists. The following function is nevertheless provided for consistency with Tasks, which do need to be cleaned up in certain circumstances (see Task Cleanup).

 -- Method on Timer: void cleanup ()
     Cleans up the Timer object.

Notification
************

Coding Standards
****************

Upper and Lower Case in Names
=============================

Keep to the following consistent scheme for choosing between upper and lower case when naming variables, types, and functions.

Classes
     Use mixed case with an initial capital letter and no underscores: LookupIPRoute.

Methods
     Use all lower case with underscores separating words: negation_is_simple.

Constants
     Use all upper case with underscores separating words: TYPE_ICMP_TYPE.

Instance variables
     Begin with an underscore, then use all lower case with underscores separating words: _length.

Regular variables
     Use all lower case with underscores separating words: i, the_handler.

Class variables
     These variables are declared as static in the class header. Name them like regular variables: nelements_allocated.

Functions
     Name them like methods: quicksort_hook.

Other types
     This includes typedefs and enumerated types. Name them like classes: CpVaParseCmd, ConfigurePhase.

There are exceptions to these guidelines. In particular:

  * Instance variables in C structs---that is, classes with few methods whose instance variables are mostly public---may be named like regular variables, without a preceding underscore. The same goes for the components of unions.

  * Classes that act like simple types, such as uatomic32_t, take names similar to the types they replace (in this case uint32_t).

Common Name Patterns
====================

  * Many instance variables have associated getter methods that return their values, and/or setter methods that change their values. For an instance variable named _x, the getter method should be named x() and the setter method should be named set_x().

  * A variable or method which counts something is often named nOBJECTs---for instance, _nwarnings, ninputs(), _npackets.

  * Use a bare 0 for a null pointer, except where some ambiguity might arise (for example, where an incorrect overloading might be selected).