option.h 18.4 KB
Newer Older
1
// Copyright (C) 2011-2015 Internet Systems Consortium, Inc. ("ISC")
2 3 4 5 6 7 8 9 10 11 12 13 14
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.

15 16 17 18 19
#ifndef OPTION_H
#define OPTION_H

#include <util/buffer.h>

20
#include <boost/function.hpp>
21
#include <boost/shared_ptr.hpp>
22 23

#include <map>
24
#include <string>
25
#include <vector>
26 27 28 29

namespace isc {
namespace dhcp {

30 31 32
/// @brief buffer types used in DHCP code.
///
/// Dereferencing OptionBuffer iterator will point out to contiguous memory.
33 34 35 36 37 38 39 40 41
typedef std::vector<uint8_t> OptionBuffer;

/// iterator for walking over OptionBuffer
typedef OptionBuffer::iterator OptionBufferIter;

/// const_iterator for walking over OptionBuffer
typedef OptionBuffer::const_iterator OptionBufferConstIter;

/// pointer to a DHCP buffer
42
typedef boost::shared_ptr<OptionBuffer> OptionBufferPtr;
43 44 45 46 47

/// shared pointer to Option object
class Option;
typedef boost::shared_ptr<Option> OptionPtr;

48
/// A collection of DHCP (v4 or v6) options
49
typedef std::multimap<unsigned int, OptionPtr> OptionCollection;
50 51
/// A poitner to an OptionCollection
typedef boost::shared_ptr<OptionCollection> OptionCollectionPtr;
52

53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
/// @brief This type describes a callback function to parse options from buffer.
///
/// @note The last two parameters should be specified in the callback function
/// parameters list only if DHCPv6 options are parsed. Exclude these parameters
/// from the callback function defined to parse DHCPv4 options.
///
/// @param buffer A buffer holding options to be parsed.
/// @param encapsulated_space A name of the option space to which options being
/// parsed belong.
/// @param [out] options A container to which parsed options should be appended.
/// @param relay_msg_offset A pointer to a size_t value. It indicates the
/// offset to beginning of relay_msg option. This parameter should be specified
/// for DHCPv6 options only.
/// @param relay_msg_len A pointer to a size_t value. It holds the length of
/// of the relay_msg option. This parameter should be specified for DHCPv6
/// options only.
///
/// @return An offset to the first byte after last parsed option.
typedef boost::function< size_t(const OptionBuffer& buffer,
                                const std::string encapsulated_space,
                                OptionCollection& options,
                                size_t* relay_msg_offset,
                                size_t* relay_msg_len)
76 77
                         > UnpackOptionsCallback;

78

79 80
class Option {
public:
81 82 83 84 85 86 87
    /// length of the usual DHCPv4 option header (there are exceptions)
    const static size_t OPTION4_HDR_LEN = 2;

    /// length of any DHCPv6 option header
    const static size_t OPTION6_HDR_LEN = 4;

    /// defines option universe DHCPv4 or DHCPv6
88
    enum Universe { V4, V6 };
89 90 91 92 93 94 95 96


    /// @brief a factory function prototype
    ///
    /// @param u option universe (DHCPv4 or DHCPv6)
    /// @param type option type
    /// @param buf pointer to a buffer
    ///
97 98 99
    /// @todo Passing a separate buffer for each option means that a copy
    ///       was done. We can avoid it by passing 2 iterators.
    ///
100
    /// @return a pointer to a created option object
101
    typedef OptionPtr Factory(Option::Universe u, uint16_t type, const OptionBuffer& buf);
102

103 104 105 106 107 108 109 110 111
    /// @brief Factory function to create instance of option.
    ///
    /// Factory method creates instance of specified option. The option
    /// to be created has to have corresponding factory function
    /// registered with \ref LibDHCP::OptionFactoryRegister.
    ///
    /// @param u universe of the option (V4 or V6)
    /// @param type option-type
    /// @param buf option-buffer
112
    ///
113
    /// @return instance of option.
114 115 116
    ///
    /// @throw isc::InvalidOperation if there is no factory function
    ///        registered for specified option type.
117 118 119 120
    static OptionPtr factory(Option::Universe u,
                             uint16_t type,
                             const OptionBuffer& buf);

121 122 123 124 125 126 127 128 129 130
    /// @brief Factory function to create instance of option.
    ///
    /// Factory method creates instance of specified option. The option
    /// to be created has to have corresponding factory function
    /// registered with \ref LibDHCP::OptionFactoryRegister.
    /// This method creates empty \ref OptionBuffer object. Use this
    /// factory function if it is not needed to pass custom buffer.
    ///
    /// @param u universe of the option (V4 or V6)
    /// @param type option-type
131
    ///
132
    /// @return instance of option.
133 134 135
    ///
    /// @throw isc::InvalidOperation if there is no factory function
    ///        registered for specified option type.
136 137 138 139
    static OptionPtr factory(Option::Universe u, uint16_t type) {
        return factory(u, type, OptionBuffer());
    }

140 141 142 143
    /// @brief ctor, used for options constructed, usually during transmission
    ///
    /// @param u option universe (DHCPv4 or DHCPv6)
    /// @param type option type
144
    Option(Universe u, uint16_t type);
145

146 147 148 149 150
    /// @brief Constructor, used for received options.
    ///
    /// This constructor takes vector<uint8_t>& which is used in cases
    /// when content of the option will be copied and stored within
    /// option object. V4 Options follow that approach already.
151
    /// @todo Migrate V6 options to that approach.
152 153 154 155
    ///
    /// @param u specifies universe (V4 or V6)
    /// @param type option type (0-255 for V4 and 0-65535 for V6)
    /// @param data content of the option
156
    Option(Universe u, uint16_t type, const OptionBuffer& data);
157

Tomek Mrugalski's avatar
Tomek Mrugalski committed
158 159
    /// @brief Constructor, used for received options.
    ///
160
    /// This constructor is similar to the previous one, but it does not take
Tomek Mrugalski's avatar
Tomek Mrugalski committed
161 162
    /// the whole vector<uint8_t>, but rather subset of it.
    ///
163
    /// @todo This can be templated to use different containers, not just
Tomek Mrugalski's avatar
Tomek Mrugalski committed
164 165 166 167 168 169 170 171 172 173 174 175 176 177
    /// vector. Prototype should look like this:
    /// template<typename InputIterator> Option(Universe u, uint16_t type,
    /// InputIterator first, InputIterator last);
    ///
    /// vector<int8_t> myData;
    /// Example usage: new Option(V4, 123, myData.begin()+1, myData.end()-1)
    /// This will create DHCPv4 option of type 123 that contains data from
    /// trimmed (first and last byte removed) myData vector.
    ///
    /// @param u specifies universe (V4 or V6)
    /// @param type option type (0-255 for V4 and 0-65535 for V6)
    /// @param first iterator to the first element that should be copied
    /// @param last iterator to the next element after the last one
    ///        to be copied.
178 179
    Option(Universe u, uint16_t type, OptionBufferConstIter first,
           OptionBufferConstIter last);
Tomek Mrugalski's avatar
Tomek Mrugalski committed
180

181 182 183
    /// @brief returns option universe (V4 or V6)
    ///
    /// @return universe type
184
    Universe  getUniverse() const { return universe_; };
185

186
    /// @brief Writes option in wire-format to a buffer.
187 188 189
    ///
    /// Writes option in wire-format to buffer, returns pointer to first unused
    /// byte after stored option (that is useful for writing options one after
190
    /// another).
191 192
    ///
    /// @param buf pointer to a buffer
193
    ///
194
    /// @throw BadValue Universe of the option is neither V4 nor V6.
195
    virtual void pack(isc::util::OutputBuffer& buf);
196

Tomek Mrugalski's avatar
Tomek Mrugalski committed
197
    /// @brief Parses received buffer.
198
    ///
199 200 201 202
    /// @param begin iterator to first byte of option data
    /// @param end iterator to end of option data (first byte after option end)
    virtual void unpack(OptionBufferConstIter begin,
                        OptionBufferConstIter end);
203 204 205

    /// Returns string representation of the option.
    ///
206 207
    /// @param indent number of spaces before printing text
    ///
208
    /// @return string with text representation.
Tomek Mrugalski's avatar
Tomek Mrugalski committed
209
    virtual std::string toText(int indent = 0);
210

211 212 213 214 215 216 217 218
    /// @brief Returns string representation of the value
    ///
    /// This is terse repesentation used in cases where client classification
    /// refers to a specific option.
    ///
    /// @return string that represents the value of the option.
    virtual std::string toString();

219 220 221
    /// Returns option type (0-255 for DHCPv4, 0-65535 for DHCPv6)
    ///
    /// @return option type
222
    uint16_t getType() const { return (type_); }
223 224 225 226 227

    /// Returns length of the complete option (data length + DHCPv4/DHCPv6
    /// option header)
    ///
    /// @return length of the option
Tomek Mrugalski's avatar
Tomek Mrugalski committed
228
    virtual uint16_t len();
229

230 231 232
    /// @brief Returns length of header (2 for v4, 4 for v6)
    ///
    /// @return length of option header
Tomek Mrugalski's avatar
Tomek Mrugalski committed
233
    virtual uint16_t getHeaderLen();
234 235

    /// returns if option is valid (e.g. option may be truncated)
236 237
    ///
    /// @return true, if option is valid
Tomek Mrugalski's avatar
Tomek Mrugalski committed
238
    virtual bool valid();
239

240 241
    /// Returns pointer to actual data.
    ///
Tomek Mrugalski's avatar
Tomek Mrugalski committed
242 243
    /// @return pointer to actual data (or reference to an empty vector
    ///         if there is no data)
244
    virtual const OptionBuffer& getData() const { return (data_); }
245

246 247
    /// Adds a sub-option.
    ///
248 249
    /// Some DHCPv6 options can have suboptions. This method allows adding
    /// options within options.
250
    ///
251 252 253 254 255 256
    /// Note: option is passed by value. That is very convenient as it allows
    /// downcasting from any derived classes, e.g. shared_ptr<Option6_IA> type
    /// can be passed directly, without any casts. That would not be possible
    /// with passing by reference. addOption() is expected to be used in
    /// many places. Requiring casting is not feasible.
    ///
257
    /// @param opt shared pointer to a suboption that is going to be added.
258
    void addOption(OptionPtr opt);
259

260 261 262 263 264
    /// Returns shared_ptr to suboption of specific type
    ///
    /// @param type type of requested suboption
    ///
    /// @return shared_ptr to requested suoption
265
    OptionPtr getOption(uint16_t type);
266

267 268 269 270 271 272 273 274 275
    /// @brief Returns all encapsulated options.
    ///
    /// @warning This function returns a reference to the container holding
    /// encapsulated options, which is valid as long as the object which
    /// returned it exists.
    const OptionCollection& getOptions() const {
        return (options_);
    }

276 277 278 279 280
    /// Attempts to delete first suboption of requested type
    ///
    /// @param type Type of option to be deleted.
    ///
    /// @return true if option was deleted, false if no such option existed
281
    bool delOption(uint16_t type);
282

Tomek Mrugalski's avatar
Tomek Mrugalski committed
283 284
    /// @brief Returns content of first byte.
    ///
285
    /// @throw isc::OutOfRange Thrown if the option has a length of 0.
Tomek Mrugalski's avatar
Tomek Mrugalski committed
286 287
    ///
    /// @return value of the first byte
288 289
    uint8_t getUint8();

Tomek Mrugalski's avatar
Tomek Mrugalski committed
290 291
    /// @brief Returns content of first word.
    ///
292
    /// @throw isc::OutOfRange Thrown if the option has a length less than 2.
Tomek Mrugalski's avatar
Tomek Mrugalski committed
293 294
    ///
    /// @return uint16_t value stored on first two bytes
295 296
    uint16_t getUint16();

Tomek Mrugalski's avatar
Tomek Mrugalski committed
297 298
    /// @brief Returns content of first double word.
    ///
299
    /// @throw isc::OutOfRange Thrown if the option has a length less than 4.
Tomek Mrugalski's avatar
Tomek Mrugalski committed
300
    ///
Tomek Mrugalski's avatar
Tomek Mrugalski committed
301
    /// @return uint32_t value stored on first four bytes
302 303
    uint32_t getUint32();

304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
    /// @brief Sets content of this option to singe uint8 value.
    ///
    /// Option it resized appropriately (to length of 1 octet).
    ///
    /// @param value value to be set
    void setUint8(uint8_t value);

    /// @brief Sets content of this option to singe uint16 value.
    ///
    /// Option it resized appropriately (to length of 2 octets).
    ///
    /// @param value value to be set
    void setUint16(uint16_t value);

    /// @brief Sets content of this option to singe uint32 value.
    ///
    /// Option it resized appropriately (to length of 4 octets).
    ///
    /// @param value value to be set
    void setUint32(uint32_t value);

325 326 327 328
    /// @brief Sets content of this option from buffer.
    ///
    /// Option will be resized to length of buffer.
    ///
329
    /// @param first iterator pointing to beginning of buffer to copy.
330
    /// @param last iterator pointing to end of buffer to copy.
331 332 333 334 335 336 337
    ///
    /// @tparam InputIterator type of the iterator representing the
    /// limits of the buffer to be assigned to a data_ buffer.
    template<typename InputIterator>
    void setData(InputIterator first, InputIterator last) {
        data_.assign(first, last);
    }
338

339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
    /// @brief Sets the name of the option space encapsulated by this option.
    ///
    /// @param encapsulated_space name of the option space encapsulated by
    /// this option.
    void setEncapsulatedSpace(const std::string& encapsulated_space) {
        encapsulated_space_ = encapsulated_space;
    }

    /// @brief Returns the name of the option space encapsulated by this option.
    ///
    /// @return name of the option space encapsulated by this option.
    std::string getEncapsulatedSpace() const {
        return (encapsulated_space_);
    }

    /// @brief Set callback function to be used to parse options.
    ///
    /// @param callback An instance of the callback function or NULL to
    /// uninstall callback.
    void setCallback(UnpackOptionsCallback callback) {
        callback_ = callback;
    }

362
    /// just to force that every option has virtual dtor
Tomek Mrugalski's avatar
Tomek Mrugalski committed
363
    virtual ~Option();
364

365 366 367 368 369 370 371 372 373 374 375
    /// @brief Checks if options are equal.
    ///
    /// This method calls a virtual @c equals function to compare objects.
    /// This method is not meant to be overriden in the derived classes.
    /// Instead, the other @c equals function must be overriden.
    ///
    /// @param other Pointer to the option to compare this option to.
    /// @return true if both options are equal, false otherwise.
    bool equals(const OptionPtr& other) const;

    /// @brief Checks if two options are equal.
376 377 378 379 380 381 382 383
    ///
    /// Equality verifies option type and option content. Care should
    /// be taken when using this method. Implementation for derived
    /// classes should be provided when this method is expected to be
    /// used. It is safe in general, as the first check (different types)
    /// will detect differences between base Option and derived
    /// objects.
    ///
384 385 386
    /// @param other Instance of the option to compare to.
    ///
    /// @return true if options are equal, false otherwise.
387
    virtual bool equals(const Option& other) const;
388

389
protected:
390

391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
    /// @brief Store option's header in a buffer.
    ///
    /// This method writes option's header into a buffer in the
    /// on-wire format. The universe set for the particular option
    /// is used to determine whether option code and length are
    /// stored as 2-byte (for DHCPv6) or single-byte (for DHCPv4)
    /// values. For DHCPv4 options, this method checks if the
    /// length does not exceed 255 bytes and throws exception if
    /// it does.
    /// This method is used by derived classes to pack option's
    /// header into a buffer. This method should not be called
    /// directly by other classes.
    ///
    /// @param [out] buf output buffer.
    void packHeader(isc::util::OutputBuffer& buf);

407 408 409 410 411 412 413 414
    /// @brief Store sub options in a buffer.
    ///
    /// This method stores all sub-options defined for a particular
    /// option in a on-wire format in output buffer provided.
    /// This function is called by pack function in this class or
    /// derived classes that override pack.
    ///
    /// @param [out] buf output buffer.
415 416 417 418 419
    ///
    /// @todo The set of exceptions thrown by this function depend on
    /// exceptions thrown by pack methods invoked on objects
    /// representing sub options. We should consider whether to aggregate
    /// those into one exception which can be documented here.
420 421 422 423 424 425 426 427 428
    void packOptions(isc::util::OutputBuffer& buf);

    /// @brief Builds a collection of sub options from the buffer.
    ///
    /// This method parses the provided buffer and builds a collection
    /// of objects representing sub options. This function may throw
    /// different exceptions when option assembly fails.
    ///
    /// @param buf buffer to be parsed.
429 430 431 432 433
    ///
    /// @todo The set of exceptions thrown by this function depend on
    /// exceptions thrown by unpack methods invoked on objects
    /// representing sub options. We should consider whether to aggregate
    /// those into one exception which can be documented here.
434 435
    void unpackOptions(const OptionBuffer& buf);

436 437 438 439 440 441
    /// @brief Returns option header in the textual format.
    ///
    /// This protected method should be called by the derived classes in
    /// their respective @c toText implementations.
    ///
    /// @param indent Number of spaces to insert before the text.
442 443
    /// @param type_name Option type name. If empty, the option name
    /// is omitted.
444 445
    ///
    /// @return Option header in the textual format.
446 447
    std::string headerToText(const int indent = 0,
                             const std::string& type_name = "");
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463

    /// @brief Returns collection of suboptions in the textual format.
    ///
    /// This protected method should be called by the derived classes
    /// in their respective @c toText implementations to append the
    /// suboptions held by this option. Note that there are some
    /// option types which don't have suboptions because they contain
    /// variable length fields. For such options this method is not
    /// called.
    ///
    /// @param indent Number of spaces to insert before the text.
    ///
    //// @return Suboptions in the textual format.
    std::string suboptionsToText(const int indent = 0) const;

    /// @brief A protected method used for option correctness.
Tomek Mrugalski's avatar
Tomek Mrugalski committed
464 465 466 467 468 469
    ///
    /// It is used in constructors. In there are any problems detected
    /// (like specifying type > 255 for DHCPv4 option), it will throw
    /// BadValue or OutOfRange exceptions.
    void check();

470 471 472 473
    /// option universe (V4 or V6)
    Universe universe_;

    /// option type (0-255 for DHCPv4, 0-65535 for DHCPv6)
474
    uint16_t type_;
475

476
    /// contains content of this data
477
    OptionBuffer data_;
478 479

    /// collection for storing suboptions
480
    OptionCollection options_;
481

482 483 484 485 486 487
    /// Name of the option space being encapsulated by this option.
    std::string encapsulated_space_;

    /// A callback to be called to unpack options from the packet.
    UnpackOptionsCallback callback_;

488
    /// @todo probably 2 different containers have to be used for v4 (unique
489
    /// options) and v6 (options with the same type can repeat)
490 491 492 493 494
};

} // namespace isc::dhcp
} // namespace isc

495
#endif // OPTION_H