Coverage Report

Created: 2025-12-31 07:33

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/kea/src/lib/cc/data.h
Line
Count
Source
1
// Copyright (C) 2010-2025 Internet Systems Consortium, Inc. ("ISC")
2
//
3
// This Source Code Form is subject to the terms of the Mozilla Public
4
// License, v. 2.0. If a copy of the MPL was not distributed with this
5
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7
#ifndef ISC_DATA_H
8
#define ISC_DATA_H 1
9
10
#include <util/bigints.h>
11
12
#include <iostream>
13
#include <map>
14
#include <stdexcept>
15
#include <string>
16
#include <vector>
17
18
#include <boost/shared_ptr.hpp>
19
20
#include <stdint.h>
21
22
#include <exceptions/exceptions.h>
23
24
namespace isc { namespace data {
25
26
class Element;
27
// todo: describe the rationale behind ElementPtr?
28
typedef boost::shared_ptr<Element> ElementPtr;
29
typedef boost::shared_ptr<const Element> ConstElementPtr;
30
31
///
32
/// @brief A standard Data module exception that is thrown if a function
33
/// is called for an Element that has a wrong type (e.g. int_value on a
34
/// ListElement)
35
///
36
class TypeError : public isc::Exception {
37
public:
38
    TypeError(const char* file, size_t line, const char* what) :
39
88.6k
        isc::Exception(file, line, what) {}
40
};
41
42
///
43
/// @brief A standard Data module exception that is thrown if a parse
44
/// error is encountered when constructing an Element from a string
45
///
46
// i'd like to use Exception here but we need one that is derived from
47
// runtime_error (as this one is directly based on external data, and
48
// i want to add some values to any static data string that is provided)
49
class JSONError : public isc::Exception {
50
public:
51
    JSONError(const char* file, size_t line, const char* what) :
52
77.1k
        isc::Exception(file, line, what) {}
53
};
54
55
///
56
/// @brief The @c Element class represents a piece of data, used by
57
/// the command channel and configuration parts.
58
///
59
/// An @c Element can contain simple types (int, real, string, bool and
60
/// None), and composite types (list and string->element maps)
61
///
62
/// Elements should in calling functions usually be referenced through
63
/// an @c ElementPtr, which can be created using the factory functions
64
/// @c Element::create() and @c Element::fromJSON()
65
///
66
/// Notes to developers: Element is a base class, implemented by a
67
/// specific subclass for each type (IntElement, BoolElement, etc).
68
/// Element does define all functions for all types, and defaults to
69
/// raising a @c TypeError for functions that are not supported for
70
/// the type in question.
71
///
72
class Element {
73
74
public:
75
    /// @brief Represents the position of the data element within a
76
    /// configuration string.
77
    ///
78
    /// Position comprises a file name, line number and an offset within this
79
    /// line where the element value starts. For example, if the JSON string is
80
    ///
81
    /// @code
82
    /// { "foo": "some string",
83
    ///   "bar": 123 }
84
    /// \endcode
85
    ///
86
    /// the position of the element "bar" is: line_ = 2; pos_ = 9, because
87
    /// beginning of the value "123" is at offset 9 from the beginning of
88
    /// the second line, including whitespaces.
89
    ///
90
    /// Note that the @c Position structure is used as an argument to @c Element
91
    /// constructors and factory functions to avoid ambiguity and so that the
92
    /// uint32_t arguments holding line number and position within the line are
93
    /// not confused with the @c Element values passed to these functions.
94
    struct Position {
95
        std::string file_; ///< File name.
96
        uint32_t line_;    ///< Line number.
97
        uint32_t pos_;     ///< Position within the line.
98
99
        /// @brief Default constructor.
100
0
        Position() : file_(""), line_(0), pos_(0) {
101
0
        }
102
103
        /// @brief Constructor.
104
        ///
105
        /// @param file File name.
106
        /// @param line Line number.
107
        /// @param pos Position within the line.
108
        Position(const std::string& file, const uint32_t line,
109
                 const uint32_t pos)
110
5.82M
            : file_(file), line_(line), pos_(pos) {
111
5.82M
        }
112
113
        /// @brief Returns the position in the textual format.
114
        ///
115
        /// The returned position has the following format: file:line:pos.
116
        std::string str() const;
117
    };
118
119
    /// @brief Returns @c Position object with line_ and pos_ set to 0, and
120
    /// with an empty file name.
121
    ///
122
    /// The object containing two zeros is a default for most of the
123
    /// methods creating @c Element objects. The returned value is static
124
    /// so as it is not created everytime the function with the default
125
    /// position argument is called.
126
12.9M
    static const Position& ZERO_POSITION() {
127
12.9M
        static Position position("", 0, 0);
128
12.9M
        return (position);
129
12.9M
    }
130
131
    /// @brief The types that an Element can hold
132
    ///
133
    /// Some of these types need to match their associated integer from the
134
    /// parameter_data_type database table, so let the enums be explicitly
135
    /// mapped to integers, to reduce the chance of messing up.
136
    ///
137
    /// any is a special type used in list specifications, specifying that the
138
    /// elements can be of any type.
139
    enum types : uint16_t {
140
        integer = 0,
141
        real = 1,
142
        boolean = 2,
143
        null = 3,
144
        string = 4,
145
        bigint = 5,
146
        list = 6,
147
        map = 7,
148
        any = 8,
149
    };
150
151
private:
152
    // technically the type could be omitted; is it useful?
153
    // should we remove it or replace it with a pure virtual
154
    // function getType?
155
    types type_;
156
157
    /// @brief Position of the element in the configuration string.
158
    Position position_;
159
160
protected:
161
162
    /// @brief Constructor.
163
    ///
164
    /// @param t Element type.
165
    /// @param pos Structure holding position of the value of the data element.
166
    /// It comprises the line number and the position within this line. The values
167
    /// held in this structure are used for error logging purposes.
168
    Element(types t, const Position& pos = ZERO_POSITION())
169
19.2M
        : type_(t), position_(pos) {
170
19.2M
    }
171
172
173
public:
174
    // base class; make dtor virtual
175
19.2M
    virtual ~Element() {}
176
177
    /// @return the type of this element
178
2.25M
    types getType() const { return (type_); }
179
180
    /// @brief Returns position where the data element's value starts in a
181
    /// configuration string.
182
    ///
183
    /// @warning The returned reference is valid as long as the object which
184
    /// created it lives.
185
272k
    const Position& getPosition() const { return (position_); }
186
187
    /// Returns a string representing the Element and all its
188
    /// child elements; note that this is different from stringValue(),
189
    /// which only returns the single value of a StringElement
190
    ///
191
    /// The resulting string will contain the Element in JSON format.
192
    ///
193
    /// @return std::string containing the string representation
194
    std::string str() const;
195
196
    /// Returns the wireformat for the Element and all its child
197
    /// elements.
198
    ///
199
    /// @return std::string containing the element in wire format
200
    std::string toWire() const;
201
    void toWire(std::ostream& out) const;
202
203
    /// @brief Add the position to a TypeError message
204
    /// should be used in place of isc_throw(TypeError, error)
205
#define throwTypeError(error)                   \
206
88.4k
    {                                           \
207
88.4k
        std::string msg_ = error;               \
208
88.4k
        if ((position_.file_ != "") ||          \
209
88.4k
            (position_.line_ != 0) ||           \
210
88.4k
            (position_.pos_ != 0)) {            \
211
77.2k
            msg_ += " in (" + position_.str() + ")";   \
212
77.2k
        }                                       \
213
88.4k
        isc_throw(TypeError, msg_);             \
214
88.4k
    }
215
216
    /// @name pure virtuals, every derived class must implement these
217
218
    /// @return true if the other ElementPtr has the same value and the same
219
    /// type (or a different and compatible type), false otherwise.
220
    virtual bool equals(const Element& other) const = 0;
221
222
    /// Converts the Element to JSON format and appends it to
223
    /// the given stringstream.
224
    virtual void toJSON(std::ostream& ss) const = 0;
225
226
    /// @name Type-specific getters
227
    ///
228
    /// @brief These functions only
229
    /// work on their corresponding Element type. For all other
230
    /// types, a TypeError is thrown.
231
    /// If you want an exception-safe getter method, use
232
    /// getValue() below
233
    //@{
234
    virtual int64_t intValue() const
235
6
    { throwTypeError("intValue() called on non-integer Element"); }
236
0
    virtual isc::util::int128_t bigIntValue() const {
237
0
        throwTypeError("bigIntValue() called on non-big-integer Element");
238
0
    }
239
    virtual double doubleValue() const
240
0
    { throwTypeError("doubleValue() called on non-double Element"); }
241
    virtual bool boolValue() const
242
3
    { throwTypeError("boolValue() called on non-Bool Element"); }
243
    virtual std::string stringValue() const
244
3.54k
    { throwTypeError("stringValue() called on non-string Element"); }
245
22.9k
    virtual const std::vector<ElementPtr>& listValue() const {
246
        // replace with real exception or empty vector?
247
22.9k
        throwTypeError("listValue() called on non-list Element");
248
0
    }
249
18.5k
    virtual const std::map<std::string, ConstElementPtr>& mapValue() const {
250
        // replace with real exception or empty map?
251
18.5k
        throwTypeError("mapValue() called on non-map Element");
252
0
    }
253
    //@}
254
255
    /// @name Exception-safe getters
256
    ///
257
    /// @brief The getValue() functions return false if the given reference
258
    /// is of another type than the element contains
259
    /// By default it always returns false; the derived classes
260
    /// override the function for their type, copying their
261
    /// data to the given reference and returning true
262
    ///
263
    //@{
264
    virtual bool getValue(int64_t& t) const;
265
    virtual bool getValue(double& t) const;
266
    virtual bool getValue(bool& t) const;
267
    virtual bool getValue(std::string& t) const;
268
    virtual bool getValue(std::vector<ElementPtr>& t) const;
269
    virtual bool getValue(std::map<std::string, ConstElementPtr>& t) const;
270
    //@}
271
272
    ///
273
    /// @name Exception-safe setters.
274
    ///
275
    /// @brief Return false if the Element is not
276
    /// the right type. Set the value and return true if the Elements
277
    /// is of the correct type
278
    ///
279
    /// Notes: Read notes of IntElement definition about the use of
280
    ///        long long int, long int and int.
281
    //@{
282
    virtual bool setValue(const long long int v);
283
    virtual bool setValue(const isc::util::int128_t& v);
284
0
    bool setValue(const long int i) { return (setValue(static_cast<long long int>(i))); }
285
0
    bool setValue(const int i) { return (setValue(static_cast<long long int>(i))); }
286
    virtual bool setValue(const double v);
287
    virtual bool setValue(const bool t);
288
    virtual bool setValue(const std::string& v);
289
    virtual bool setValue(const std::vector<ElementPtr>& v);
290
    virtual bool setValue(const std::map<std::string, ConstElementPtr>& v);
291
    //@}
292
293
    // Other functions for specific subtypes
294
295
    /// @name ListElement functions
296
    ///
297
    /// @brief If the Element on which these functions are called are not
298
    /// an instance of ListElement, a TypeError exception is thrown.
299
    //@{
300
    /// Returns the ElementPtr at the given index. If the index is out
301
    /// of bounds, this function throws an std::out_of_range exception.
302
    /// @param i The position of the ElementPtr to return
303
    virtual ConstElementPtr get(const int i) const;
304
305
    /// @brief returns element as non-const pointer
306
    ///
307
    /// @param i The position of the ElementPtr to retrieve
308
    /// @return specified element pointer
309
    virtual ElementPtr getNonConst(const int i) const;
310
311
    /// Sets the ElementPtr at the given index. If the index is out
312
    /// of bounds, this function throws an std::out_of_range exception.
313
    /// @param i The position of the ElementPtr to set
314
    /// @param element The ElementPtr to set at the position
315
    virtual void set(const size_t i, ElementPtr element);
316
317
    /// Adds an ElementPtr to the list
318
    /// @param element The ElementPtr to add
319
    virtual void add(ElementPtr element);
320
321
    /// Removes the element at the given position. If the index is out
322
    /// of nothing happens.
323
    /// @param i The index of the element to remove.
324
    virtual void remove(const int i);
325
326
    /// Returns the number of elements in the list.
327
    virtual size_t size() const;
328
329
    /// Return true if there are no elements in the list.
330
    virtual bool empty() const;
331
    //@}
332
333
334
    /// @name MapElement functions
335
    ///
336
    /// @brief If the Element on which these functions are called are not
337
    /// an instance of MapElement, a TypeError exception is thrown.
338
    //@{
339
    /// Returns the ElementPtr at the given key
340
    /// @param name The key of the Element to return
341
    /// @return The ElementPtr at the given key, or null if not present
342
    virtual ConstElementPtr get(const std::string& name) const;
343
344
    /// Sets the ElementPtr at the given key
345
    /// @param name The key of the Element to set
346
    /// @param element The ElementPtr to set at the given key.
347
    virtual void set(const std::string& name, ConstElementPtr element);
348
349
    /// Remove the ElementPtr at the given key
350
    /// @param name The key of the Element to remove
351
    virtual void remove(const std::string& name);
352
353
    /// Checks if there is data at the given key
354
    /// @param name The key of the Element checked for existence
355
    /// @return true if there is data at the key, false if not.
356
    virtual bool contains(const std::string& name) const;
357
358
    /// Recursively finds any data at the given identifier. The
359
    /// identifier is a /-separated list of names of nested maps, with
360
    /// the last name being the leaf that is returned.
361
    ///
362
    /// For instance, if you have a MapElement that contains another
363
    /// MapElement at the key "foo", and that second MapElement contains
364
    /// Another Element at key "bar", the identifier for that last
365
    /// element from the first is "foo/bar".
366
    ///
367
    /// @param identifier The identifier of the element to find
368
    /// @return The ElementPtr at the given identifier. Returns a
369
    /// null ElementPtr if it is not found, which can be checked with
370
    /// Element::is_null(ElementPtr e).
371
    virtual ConstElementPtr find(const std::string& identifier) const;
372
373
    /// See @c Element::find()
374
    /// @param identifier The identifier of the element to find
375
    /// @param t Reference to store the resulting ElementPtr, if found.
376
    /// @return true if the element was found, false if not.
377
    virtual bool find(const std::string& identifier, ConstElementPtr& t) const;
378
    //@}
379
380
    /// @name Factory functions
381
382
    // TODO: should we move all factory functions to a different class
383
    // so as not to burden the Element base with too many functions?
384
    // and/or perhaps even to a separate header?
385
386
    /// @name Direct factory functions
387
    /// @brief These functions simply wrap the given data directly
388
    /// in an Element object, and return a reference to it, in the form
389
    /// of an @c ElementPtr.
390
    /// These factory functions are exception-free (unless there is
391
    /// no memory available, in which case bad_alloc is raised by the
392
    /// underlying system).
393
    /// (Note that that is different from an NullElement, which
394
    /// represents an empty value, and is created with Element::create())
395
    ///
396
    /// Notes: Read notes of IntElement definition about the use of
397
    ///        long long int, long int and int.
398
    //@{
399
    static ElementPtr create(const Position& pos = ZERO_POSITION());
400
    static ElementPtr create(const long long int i,
401
                             const Position& pos = ZERO_POSITION());
402
    static ElementPtr create(const isc::util::int128_t& i,
403
                             const Position& pos = ZERO_POSITION());
404
    static ElementPtr create(const int i,
405
                             const Position& pos = ZERO_POSITION());
406
    static ElementPtr create(const long int i,
407
                             const Position& pos = ZERO_POSITION());
408
    static ElementPtr create(const uint32_t i,
409
                             const Position& pos = ZERO_POSITION());
410
    static ElementPtr create(const double d,
411
                             const Position& pos = ZERO_POSITION());
412
    static ElementPtr create(const bool b,
413
                             const Position& pos = ZERO_POSITION());
414
    static ElementPtr create(const std::string& s,
415
                             const Position& pos = ZERO_POSITION());
416
    // need both std:string and char *, since c++ will match
417
    // bool before std::string when you pass it a char *
418
    static ElementPtr create(const char *s,
419
                             const Position& pos = ZERO_POSITION());
420
421
    /// @brief Creates an empty ListElement type ElementPtr.
422
    ///
423
    /// @param pos A structure holding position of the data element value
424
    /// in the configuration string. It is used for error logging purposes.
425
    static ElementPtr createList(const Position& pos = ZERO_POSITION());
426
427
    /// @brief Creates an empty MapElement type ElementPtr.
428
    ///
429
    /// @param pos A structure holding position of the data element value
430
    /// in the configuration string. It is used for error logging purposes.
431
    static ElementPtr createMap(const Position& pos = ZERO_POSITION());
432
    //@}
433
434
    /// @name Compound factory functions
435
436
    /// @brief These functions will parse the given string (JSON)
437
    /// representation  of a compound element. If there is a parse
438
    /// error, an exception of the type isc::data::JSONError is thrown.
439
440
    //@{
441
    /// Creates an Element from the given JSON string
442
    /// @param in The string to parse the element from
443
    /// @param preproc specified whether preprocessing (e.g. comment removal)
444
    ///                should be performed
445
    /// @return An ElementPtr that contains the element(s) specified
446
    /// in the given string.
447
    static ElementPtr fromJSON(const std::string& in, bool preproc = false);
448
449
    /// Creates an Element from the given input stream containing JSON
450
    /// formatted data.
451
    ///
452
    /// @param in The string to parse the element from
453
    /// @param preproc specified whether preprocessing (e.g. comment removal)
454
    ///                should be performed
455
    /// @throw JSONError
456
    /// @return An ElementPtr that contains the element(s) specified
457
    /// in the given input stream.
458
    static ElementPtr fromJSON(std::istream& in, bool preproc = false);
459
460
    /// Creates an Element from the given input stream containing JSON
461
    /// formatted data.
462
    ///
463
    /// @param in The string to parse the element from
464
    /// @param file_name specified input file name (used in error reporting)
465
    /// @param preproc specified whether preprocessing (e.g. comment removal)
466
    ///                should be performed
467
    /// @throw JSONError
468
    /// @return An ElementPtr that contains the element(s) specified
469
    /// in the given input stream.
470
    /// @throw JSONError
471
    static ElementPtr fromJSON(std::istream& in, const std::string& file_name,
472
                               bool preproc = false);
473
474
    /// Creates an Element from the given input stream, where we keep
475
    /// track of the location in the stream for error reporting.
476
    ///
477
    /// @param in The string to parse the element from.
478
    /// @param file The input file name.
479
    /// @param line A reference to the int where the function keeps
480
    /// track of the current line.
481
    /// @param pos A reference to the int where the function keeps
482
    /// track of the current position within the current line.
483
    /// @throw JSONError
484
    /// @return An ElementPtr that contains the element(s) specified
485
    /// in the given input stream.
486
    // make this one private?
487
    /// @throw JSONError
488
    static ElementPtr fromJSON(std::istream& in, const std::string& file,
489
                               int& line, int &pos);
490
491
    /// Reads contents of specified file and interprets it as JSON.
492
    ///
493
    /// @param file_name name of the file to read
494
    /// @param preproc specified whether preprocessing (e.g. comment removal)
495
    ///                should be performed
496
    /// @return An ElementPtr that contains the element(s) specified
497
    /// if the given file.
498
    static ElementPtr fromJSONFile(const std::string& file_name,
499
                                   bool preproc = false);
500
    //@}
501
502
    /// @name Type name conversion functions
503
504
    /// Returns the name of the given type as a string
505
    ///
506
    /// @param type The type to return the name of
507
    /// @return The name of the type, or "unknown" if the type
508
    ///         is not known.
509
    static std::string typeToName(Element::types type);
510
511
    /// Converts the string to the corresponding type
512
    /// Throws a TypeError if the name is unknown.
513
    ///
514
    /// @param type_name The name to get the type of
515
    /// @return the corresponding type value
516
    static Element::types nameToType(const std::string& type_name);
517
518
    /// @brief input text preprocessor
519
    ///
520
    /// This method performs preprocessing of the input stream (which is
521
    /// expected to contain a text version of to be parsed JSON). For now the
522
    /// sole supported operation is bash-style (line starting with #) comment
523
    /// removal, but it will be extended later to cover more cases (C, C++ style
524
    /// comments, file inclusions, maybe macro replacements?).
525
    ///
526
    /// This method processes the whole input stream. It reads all contents of
527
    /// the input stream, filters the content and returns the result in a
528
    /// different stream.
529
    ///
530
    /// @param in input stream to be preprocessed
531
    /// @param out output stream (filtered content will be written here)
532
    static void preprocess(std::istream& in, std::stringstream& out);
533
534
    /// @name Wire format factory functions
535
536
    /// These function pparse the wireformat at the given stringstream
537
    /// (of the given length). If there is a parse error an exception
538
    /// of the type isc::cc::DecodeError is raised.
539
540
    //@{
541
    /// Creates an Element from the wire format in the given
542
    /// stringstream of the given length.
543
    /// Since the wire format is JSON, this is the same as
544
    /// fromJSON, and could be removed.
545
    ///
546
    /// @param in The input stringstream.
547
    /// @param length The length of the wireformat data in the stream
548
    /// @return ElementPtr with the data that is parsed.
549
    static ElementPtr fromWire(std::stringstream& in, int length);
550
551
    /// Creates an Element from the wire format in the given string
552
    /// Since the wire format is JSON, this is the same as
553
    /// fromJSON, and could be removed.
554
    ///
555
    /// @param s The input string
556
    /// @return ElementPtr with the data that is parsed.
557
    static ElementPtr fromWire(const std::string& s);
558
    //@}
559
560
    /// @brief Remove all empty maps and lists from this Element and its
561
    /// descendants.
562
0
    void removeEmptyContainersRecursively() {
563
0
        if (type_ == list || type_ == map) {
564
0
            size_t s(size());
565
0
            for (size_t i = 0; i < s; ++i) {
566
0
                // Get child.
567
0
                ElementPtr child;
568
0
                if (type_ == list) {
569
0
                    child = getNonConst(i);
570
0
                } else if (type_ == map) {
571
0
                    std::string const key(get(i)->stringValue());
572
0
                    // The ElementPtr - ConstElementPtr disparity between
573
0
                    // ListElement and MapElement is forcing a const cast here.
574
0
                    // It's undefined behavior to modify it after const casting.
575
0
                    // The options are limited. I've tried templating, moving
576
0
                    // this function from a member function to free-standing and
577
0
                    // taking the Element template as argument. I've tried
578
0
                    // making it a virtual function with overridden
579
0
                    // implementations in ListElement and MapElement. Nothing
580
0
                    // works.
581
0
                    child = boost::const_pointer_cast<Element>(get(key));
582
0
                }
583
0
584
0
                // Makes no sense to continue for non-container children.
585
0
                if (child->getType() != list && child->getType() != map) {
586
0
                    continue;
587
0
                }
588
0
589
0
                // Recurse if not empty.
590
0
                if (!child->empty()){
591
0
                    child->removeEmptyContainersRecursively();
592
0
                }
593
0
594
0
                // When returning from recursion, remove if empty.
595
0
                if (child->empty()) {
596
0
                    remove(i);
597
0
                    --i;
598
0
                    --s;
599
0
                }
600
0
            }
601
0
        }
602
0
    }
603
};
604
605
/// Notes: IntElement type is changed to int64_t.
606
///        Due to C++ problems on overloading and automatic type conversion,
607
///          (C++ tries to convert integer type values and reference/pointer
608
///           if value types do not match exactly)
609
///        We decided the storage as int64_t,
610
///           three (long long, long, int) override function definitions
611
///           and cast int/long/long long to int64_t via long long.
612
///        Therefore, call by value methods (create, setValue) have three
613
///        (int,long,long long) definitions. Others use int64_t.
614
///
615
class IntElement : public Element {
616
    int64_t i;
617
public:
618
    IntElement(int64_t v, const Position& pos = ZERO_POSITION())
619
3.14M
        : Element(integer, pos), i(v) { }
620
2.31M
    int64_t intValue() const { return (i); }
621
    using Element::getValue;
622
0
    bool getValue(int64_t& t) const { t = i; return (true); }
623
    using Element::setValue;
624
0
    bool setValue(long long int v) { i = v; return (true); }
625
    void toJSON(std::ostream& ss) const;
626
    bool equals(const Element& other) const;
627
};
628
629
/// @brief Wrapper over int128_t
630
class BigIntElement : public Element {
631
    using int128_t = isc::util::int128_t;
632
    using Element::getValue;
633
    using Element::setValue;
634
635
public:
636
    /// @brief Constructor
637
    BigIntElement(const int128_t& v, const Position& pos = ZERO_POSITION())
638
122k
        : Element(bigint, pos), i_(v) {
639
122k
    }
640
641
    /// @brief Retrieve the underlying big integer value.
642
    ///
643
    /// @return the underlying value
644
223
    int128_t bigIntValue() const override {
645
223
        return (i_);
646
223
    }
647
648
    /// @brief Sets the underlying big integer value.
649
    ///
650
    /// @return true for no reason
651
0
    bool setValue(const int128_t& v) override {
652
0
        i_ = v;
653
0
        return (true);
654
0
    }
655
656
    /// @brief Converts the Element to JSON format and appends it to the given
657
    /// stringstream.
658
    void toJSON(std::ostream& ss) const override;
659
660
    /// @brief Checks whether the other Element is equal.
661
    ///
662
    /// @return true if the other ElementPtr has the same value and the same
663
    /// type (or a different and compatible type), false otherwise.
664
    bool equals(const Element& other) const override;
665
666
private:
667
    /// @brief the underlying stored value
668
    int128_t i_;
669
};
670
671
class DoubleElement : public Element {
672
    double d;
673
674
public:
675
    DoubleElement(double v, const Position& pos = ZERO_POSITION())
676
179k
        : Element(real, pos), d(v) {}
677
115k
    double doubleValue() const { return (d); }
678
    using Element::getValue;
679
0
    bool getValue(double& t) const { t = d; return (true); }
680
    using Element::setValue;
681
0
    bool setValue(const double v) { d = v; return (true); }
682
    void toJSON(std::ostream& ss) const;
683
    bool equals(const Element& other) const;
684
};
685
686
class BoolElement : public Element {
687
    bool b;
688
689
public:
690
    BoolElement(const bool v, const Position& pos = ZERO_POSITION())
691
4.78M
        : Element(boolean, pos), b(v) {}
692
4.89M
    bool boolValue() const { return (b); }
693
    using Element::getValue;
694
0
    bool getValue(bool& t) const { t = b; return (true); }
695
    using Element::setValue;
696
0
    bool setValue(const bool v) { b = v; return (true); }
697
    void toJSON(std::ostream& ss) const;
698
    bool equals(const Element& other) const;
699
};
700
701
class NullElement : public Element {
702
public:
703
    NullElement(const Position& pos = ZERO_POSITION())
704
11.3k
        : Element(null, pos) {}
705
    void toJSON(std::ostream& ss) const;
706
    bool equals(const Element& other) const;
707
};
708
709
class StringElement : public Element {
710
    std::string s;
711
712
public:
713
    StringElement(std::string v, const Position& pos = ZERO_POSITION())
714
5.68M
        : Element(string, pos), s(v) {}
715
5.32M
    std::string stringValue() const { return (s); }
716
    using Element::getValue;
717
1.92k
    bool getValue(std::string& t) const { t = s; return (true); }
718
    using Element::setValue;
719
0
    bool setValue(const std::string& v) { s = v; return (true); }
720
    void toJSON(std::ostream& ss) const;
721
    bool equals(const Element& other) const;
722
};
723
724
class ListElement : public Element {
725
    std::vector<ElementPtr> l;
726
727
public:
728
    ListElement(const Position& pos = ZERO_POSITION())
729
2.71M
        : Element(list, pos) {}
730
468k
    const std::vector<ElementPtr>& listValue() const { return (l); }
731
    using Element::getValue;
732
0
    bool getValue(std::vector<ElementPtr>& t) const {
733
0
        t = l;
734
0
        return (true);
735
0
    }
736
    using Element::setValue;
737
0
    bool setValue(const std::vector<ElementPtr>& v) {
738
0
        l = v;
739
0
        return (true);
740
0
    }
741
    using Element::get;
742
1.44k
    ConstElementPtr get(int i) const { return (l.at(i)); }
743
0
    ElementPtr getNonConst(int i) const  { return (l.at(i)); }
744
    using Element::set;
745
0
    void set(size_t i, ElementPtr e) {
746
0
        l.at(i) = e;
747
0
    }
748
2.64M
    void add(ElementPtr e) { l.push_back(e); }
749
    using Element::remove;
750
0
    void remove(int i) { l.erase(l.begin() + i); }
751
    void toJSON(std::ostream& ss) const;
752
80.0k
    size_t size() const { return (l.size()); }
753
43.2k
    bool empty() const { return (l.empty()); }
754
    bool equals(const Element& other) const;
755
756
    /// @brief Sorts the elements inside the list.
757
    ///
758
    /// The list must contain elements of the same type.
759
    /// Call with the key by which you want to sort when the list contains maps.
760
    /// Nested lists are not supported.
761
    /// Call without a parameter when sorting any other type.
762
    ///
763
    /// @param index the key by which you want to sort when the list contains
764
    /// maps
765
    void sort(std::string const& index = std::string());
766
};
767
768
class MapElement : public Element {
769
    std::map<std::string, ConstElementPtr> m;
770
771
public:
772
2.64M
    MapElement(const Position& pos = ZERO_POSITION()) : Element(map, pos) {}
773
    // @todo should we have direct iterators instead of exposing the std::map
774
    // here?
775
299k
    const std::map<std::string, ConstElementPtr>& mapValue() const override {
776
299k
        return (m);
777
299k
    }
778
    using Element::getValue;
779
0
    bool getValue(std::map<std::string, ConstElementPtr>& t) const override {
780
0
        t = m;
781
0
        return (true);
782
0
    }
783
    using Element::setValue;
784
199
    bool setValue(const std::map<std::string, ConstElementPtr>& v) override {
785
199
        m = v;
786
199
        return (true);
787
199
    }
788
    using Element::get;
789
5.56M
    ConstElementPtr get(const std::string& s) const override {
790
5.56M
        auto found = m.find(s);
791
5.56M
        return (found != m.end() ? found->second : ConstElementPtr());
792
5.56M
    }
793
794
    /// @brief Get the i-th element in the map.
795
    ///
796
    /// Useful when required to iterate with an index.
797
    ///
798
    /// @param i the position of the element you want to return
799
    /// @return the element at position i
800
1
    ConstElementPtr get(int const i) const override {
801
1
        auto it(m.begin());
802
1
        std::advance(it, i);
803
1
        return create(it->first);
804
1
    }
805
806
    using Element::set;
807
    void set(const std::string& key, ConstElementPtr value) override;
808
    using Element::remove;
809
6.06k
    void remove(const std::string& s) override { m.erase(s); }
810
811
    /// @brief Remove the i-th element from the map.
812
    ///
813
    /// @param i the position of the element you want to remove
814
0
    void remove(int const i) override {
815
0
        auto it(m.begin());
816
0
        std::advance(it, i);
817
0
        m.erase(it);
818
0
    }
819
820
813k
    bool contains(const std::string& s) const override {
821
813k
        return (m.find(s) != m.end());
822
813k
    }
823
    void toJSON(std::ostream& ss) const override;
824
825
    // we should name the two finds better...
826
    // find the element at id; raises TypeError if one of the
827
    // elements at path except the one we're looking for is not a
828
    // mapelement.
829
    // returns an empty element if the item could not be found
830
    ConstElementPtr find(const std::string& id) const override;
831
832
    // find the Element at 'id', and store the element pointer in t
833
    // returns true if found, or false if not found (either because
834
    // it doesn't exist or one of the elements in the path is not
835
    // a MapElement)
836
    bool find(const std::string& id, ConstElementPtr& t) const override;
837
838
    /// @brief Returns number of stored elements
839
    ///
840
    /// @return number of elements.
841
22.5k
    size_t size() const override {
842
22.5k
        return (m.size());
843
22.5k
    }
844
845
    bool equals(const Element& other) const override;
846
847
47.2k
    bool empty() const override { return (m.empty()); }
848
};
849
850
/// Checks whether the given ElementPtr is a NULL pointer
851
/// @param p The ElementPtr to check
852
/// @return true if it is NULL, false if not.
853
bool isNull(ConstElementPtr p);
854
855
///
856
/// @brief Remove all values from the first ElementPtr that are
857
/// equal in the second. Both ElementPtrs MUST be MapElements
858
/// The use for this function is to end up with a MapElement that
859
/// only contains new and changed values (for ModuleCCSession and
860
/// configuration update handlers)
861
/// Raises a TypeError if a or b are not MapElements
862
void removeIdentical(ElementPtr a, ConstElementPtr b);
863
864
/// @brief Create a new ElementPtr from the first ElementPtr, removing all
865
/// values that are equal in the second. Both ElementPtrs MUST be MapElements.
866
/// The returned ElementPtr will be a MapElement that only contains new and
867
/// changed values (for ModuleCCSession and configuration update handlers).
868
/// Raises a TypeError if a or b are not MapElements
869
ConstElementPtr removeIdentical(ConstElementPtr a, ConstElementPtr b);
870
871
/// @brief Merges the data from other into element. (on the first level). Both
872
/// elements must be MapElements. Every string, value pair in other is copied
873
/// into element (the ElementPtr of value is copied, this is not a new object)
874
/// Unless the value is a NullElement, in which case the key is removed from
875
/// element, rather than setting the value to the given NullElement.
876
/// This way, we can remove values from for instance maps with configuration
877
/// data (which would then result in reverting back to the default).
878
/// Raises a TypeError if either ElementPtr is not a MapElement
879
void merge(ElementPtr element, ConstElementPtr other);
880
881
/// @brief Function used to check if two MapElements refer to the same
882
/// configuration data. It can check if the two MapElements have the same or
883
/// have equivalent value for some members.
884
/// e.g.
885
/// (
886
///  left->get("prefix")->stringValue() == right->get("prefix")->stringValue() &&
887
///  left->get("prefix-len")->intValue() == right->get("prefix-len")->intValue() &&
888
///  left->get("delegated-len")->intValue() == right->get("delegated-len")->intValue()
889
/// )
890
typedef std::function<bool (ElementPtr&, ElementPtr&)> MatchTestFunc;
891
892
/// @brief Function used to check if the data provided for the element contains
893
/// only information used for identification, or it contains extra useful data.
894
typedef std::function<bool (ElementPtr&)> NoDataTestFunc;
895
896
/// @brief Function used to check if the key is used for identification
897
typedef std::function<bool (const std::string&)> IsKeyTestFunc;
898
899
/// @brief Structure holding the test functions used to traverse the element
900
/// hierarchy.
901
struct HierarchyTraversalTest {
902
    MatchTestFunc match_;
903
    NoDataTestFunc no_data_;
904
    IsKeyTestFunc is_key_;
905
};
906
907
/// @brief Mapping between a container name and functions used to match elements
908
/// inside the container.
909
typedef std::map<std::string, HierarchyTraversalTest> FunctionMap;
910
911
/// @brief Hierarchy descriptor of the containers in a specific Element
912
/// hierarchy tree. The position inside the vector indicates the level at which
913
/// the respective containers are located.
914
///
915
/// e.g.
916
/// {
917
///   { { "pools", { ... , ... } }, { "pd-pools", { ... , ... } }, { "option-data", { ... , ... } } },
918
///   { { "option-data", { ... , ... } } }
919
/// }
920
/// At first subnet level the 'pools', 'pd-pools' and 'option-data' containers
921
/// can be found.
922
/// At second subnet level the 'option-data' container can be found
923
/// (obviously only inside 'pools' and 'pd-pools' containers).
924
typedef std::vector<FunctionMap> HierarchyDescriptor;
925
926
/// @brief Merges the diff data by adding the missing elements from 'other'
927
/// to 'element' (recursively). Both elements must be the same Element type.
928
/// Raises a TypeError if elements are not the same Element type.
929
/// @note
930
/// for non map and list elements the values are updated with the new values
931
/// for maps:
932
///     - non map and list elements are added/updated with the new values
933
///     - list and map elements are processed recursively
934
/// for lists:
935
///     - regardless of the element type, all elements from 'other' are added to
936
///       'element'
937
///
938
/// @param element The element to which new data is added.
939
/// @param other The element containing the data which needs to be added.
940
/// @param hierarchy The hierarchy describing the elements relations and
941
/// identification keys.
942
/// @param key The container holding the current element.
943
/// @param idx The level inside the hierarchy the current element is located.
944
void mergeDiffAdd(ElementPtr& element, ElementPtr& other,
945
                  HierarchyDescriptor& hierarchy, std::string key,
946
                  size_t idx = 0);
947
948
/// @brief Merges the diff data by removing the data present in 'other' from
949
/// 'element' (recursively). Both elements must be the same Element type.
950
/// Raises a TypeError if elements are not the same Element type.
951
/// for non map and list elements the values are set to NullElement
952
/// for maps:
953
///     - non map and list elements are removed from the map
954
///     - list and map elements are processed recursively
955
/// for lists:
956
///     - regardless of the element type, all elements from 'other' matching
957
///       elements in 'element' are removed
958
///
959
/// @param element The element from which new data is removed.
960
/// @param other The element containing the data which needs to be removed.
961
/// @param hierarchy The hierarchy describing the elements relations and
962
/// identification keys.
963
/// @param key The container holding the current element.
964
/// @param idx The level inside the hierarchy the current element is located.
965
void mergeDiffDel(ElementPtr& element, ElementPtr& other,
966
                  HierarchyDescriptor& hierarchy, std::string key,
967
                  size_t idx = 0);
968
969
/// @brief Extends data by adding the specified 'extension' elements from
970
/// 'other' inside the 'container' element (recursively). Both elements must be
971
/// the same Element type.
972
/// Raises a TypeError if elements are not the same Element type.
973
///
974
/// @param container The container holding the data that must be extended.
975
/// @param extension The name of the element that contains the data that must be
976
/// added (if not already present) in order to extend the initial data.
977
/// @param element The element from which new data is added.
978
/// @param other The element containing the data which needs to be added.
979
/// @param hierarchy The hierarchy describing the elements relations and
980
/// identification keys.
981
/// @param key The container holding the current element.
982
/// @param idx The level inside the hierarchy the current element is located.
983
/// @param alter The flag which indicates if the current element should be
984
/// updated.
985
void extend(const std::string& container, const std::string& extension,
986
            ElementPtr& element, ElementPtr& other,
987
            HierarchyDescriptor& hierarchy, std::string key, size_t idx = 0,
988
            bool alter = false);
989
990
/// @brief Copy the data up to a nesting level.
991
///
992
/// The copy is a deep copy so nothing is shared if it is not
993
/// under the given nesting level.
994
///
995
/// @param from the pointer to the element to copy
996
/// @param level nesting level (default is 100, 0 means shallow copy,
997
/// negative means outbound and perhaps looping forever).
998
/// @return a pointer to a fresh copy
999
/// @throw raises a BadValue is a null pointer occurs.
1000
ElementPtr copy(ConstElementPtr from, int level = 100);
1001
1002
/// @brief Compares the data with other using unordered lists
1003
///
1004
/// This comparison function handles lists (JSON arrays) as
1005
/// unordered multi sets (multi means an item can occurs more
1006
/// than once as soon as it occurs the same number of times).
1007
bool isEquivalent(ConstElementPtr a, ConstElementPtr b);
1008
1009
/// @brief Pretty prints the data into stream.
1010
///
1011
/// This operator converts the @c ConstElementPtr into a string and
1012
/// inserts it into the output stream @c out with an initial
1013
/// indentation @c indent and add at each level @c step spaces.
1014
/// For maps if there is a comment property it is printed first.
1015
///
1016
/// @param element A @c ConstElementPtr to pretty print
1017
/// @param out A @c std::ostream on which the print operation is performed
1018
/// @param indent An initial number of spaces to add each new line
1019
/// @param step A number of spaces to add to indentation at a new level
1020
void prettyPrint(ConstElementPtr element, std::ostream& out,
1021
                 unsigned indent = 0, unsigned step = 2);
1022
1023
/// @brief Pretty prints the data into string
1024
///
1025
/// This operator converts the @c ConstElementPtr into a string with
1026
/// an initial indentation @c indent and add at each level @c step spaces.
1027
/// For maps if there is a comment property it is printed first.
1028
///
1029
/// @param element A @c ConstElementPtr to pretty print
1030
/// @param indent An initial number of spaces to add each new line
1031
/// @param step A number of spaces to add to indentation at a new level
1032
/// @return a string where element was pretty printed
1033
std::string prettyPrint(ConstElementPtr element,
1034
                        unsigned indent = 0, unsigned step = 2);
1035
1036
/// @brief Insert Element::Position as a string into stream.
1037
///
1038
/// This operator converts the @c Element::Position into a string and
1039
/// inserts it into the output stream @c out.
1040
///
1041
/// @param out A @c std::ostream object on which the insertion operation is
1042
/// performed.
1043
/// @param pos The @c Element::Position structure to insert.
1044
/// @return A reference to the same @c std::ostream object referenced by
1045
/// parameter @c out after the insertion operation.
1046
std::ostream& operator<<(std::ostream& out, const Element::Position& pos);
1047
1048
/// @brief Insert the Element as a string into stream.
1049
///
1050
/// This method converts the @c ElementPtr into a string with
1051
/// @c Element::str() and inserts it into the
1052
/// output stream @c out.
1053
///
1054
/// This function overloads the global operator<< to behave as described in
1055
/// ostream::operator<< but applied to @c ElementPtr objects.
1056
///
1057
/// @param out A @c std::ostream object on which the insertion operation is
1058
/// performed.
1059
/// @param e The @c ElementPtr object to insert.
1060
/// @return A reference to the same @c std::ostream object referenced by
1061
/// parameter @c out after the insertion operation.
1062
std::ostream& operator<<(std::ostream& out, const Element& e);
1063
1064
bool operator==(const Element& a, const Element& b);
1065
bool operator!=(const Element& a, const Element& b);
1066
bool operator<(const Element& a, const Element& b);
1067
1068
}  // namespace data
1069
}  // namespace isc
1070
1071
#endif // ISC_DATA_H