1 /**
2  * @file tree_data.h
3  * @author Radek Krejci <rkrejci@cesnet.cz>
4  * @brief libyang representation of data trees.
5  *
6  * Copyright (c) 2015 CESNET, z.s.p.o.
7  *
8  * This source code is licensed under BSD 3-Clause License (the "License").
9  * You may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *     https://opensource.org/licenses/BSD-3-Clause
13  */
14 
15 #ifndef LY_TREE_DATA_H_
16 #define LY_TREE_DATA_H_
17 
18 #include <stddef.h>
19 #include <stdint.h>
20 
21 #include "libyang.h"
22 #include "tree_schema.h"
23 #include "xml.h"
24 
25 #ifdef __cplusplus
26 extern "C" {
27 #endif
28 
29 /**
30  * @defgroup datatree Data Tree
31  * @{
32  *
33  * Data structures and functions to manipulate and access instance data tree.
34  */
35 
36 /**
37  * @brief Data input/output formats supported by libyang [parser](@ref howtodataparsers) and
38  * [printer](@ref howtodataprinters) functions.
39  */
40 typedef enum {
41     LYD_UNKNOWN,         /**< unknown format, used as return value in case of error */
42     LYD_XML,             /**< XML format of the instance data */
43     LYD_JSON,            /**< JSON format of the instance data */
44     LYD_LYB,             /**< LYB format of the instance data */
45 } LYD_FORMAT;
46 
47 /**
48  * @brief List of possible value types stored in ::lyd_node_anydata.
49  */
50 typedef enum {
51     LYD_ANYDATA_CONSTSTRING = 0x00, /**< value is constant string (const char *) which is internally duplicated for
52                                          storing in the anydata structure; XML sensitive characters (such as & or \>)
53                                          are automatically escaped when the anydata is printed in XML format. */
54     LYD_ANYDATA_STRING = 0x01,      /**< value is dynamically allocated string (char*), so the data are used directly
55                                          without duplication and caller is supposed to not manipulate with the data
56                                          after a successful call (including calling free() on the provided data); XML
57                                          sensitive characters (such as & or \>) are automatically escaped when the
58                                          anydata is printed in XML format */
59     LYD_ANYDATA_JSON = 0x02,        /**< value is string containing the data modeled by YANG and encoded as I-JSON. The
60                                          string is handled as constant string. In case of using the value as input
61                                          parameter, the #LYD_ANYDATA_JSOND can be used for dynamically allocated
62                                          string. */
63     LYD_ANYDATA_JSOND = 0x03,       /**< In case of using value as input parameter, this enumeration is supposed to be
64                                          used for dynamically allocated strings (it is actually combination of
65                                          #LYD_ANYDATA_JSON and #LYD_ANYDATA_STRING (and it can be also specified as
66                                          ORed value of the mentioned values. */
67     LYD_ANYDATA_SXML = 0x04,        /**< value is string containing the serialized XML data. The string is handled as
68                                          constant string. In case of using the value as input parameter, the
69                                          #LYD_ANYDATA_SXMLD can be used for dynamically allocated string. */
70     LYD_ANYDATA_SXMLD = 0x05,       /**< In case of using serialized XML value as input parameter, this enumeration is
71                                          supposed to be used for dynamically allocated strings (it is actually
72                                          combination of #LYD_ANYDATA_SXML and #LYD_ANYDATA_STRING (and it can be also
73                                          specified as ORed value of the mentioned values). */
74     LYD_ANYDATA_XML = 0x08,         /**< value is struct lyxml_elem*, the structure is directly connected into the
75                                          anydata node without duplication, caller is supposed to not manipulate with the
76                                          data after a successful call (including calling lyxml_free() on the provided
77                                          data) */
78     LYD_ANYDATA_DATATREE = 0x10,    /**< value is struct lyd_node* (first sibling), the structure is directly connected
79                                          into the anydata node without duplication, caller is supposed to not manipulate
80                                          with the data after a successful call (including calling lyd_free() on the
81                                          provided data) */
82     LYD_ANYDATA_LYB = 0x20,         /**< value is a memory with serialized data tree in LYB format. The data are handled
83                                          as a constant string. In case of using the value as input parameter,
84                                          the #LYD_ANYDATA_LYBD can be used for dynamically allocated string. */
85     LYD_ANYDATA_LYBD = 0x21,        /**< In case of using LYB value as input parameter, this enumeration is
86                                          supposed to be used for dynamically allocated strings (it is actually
87                                          combination of #LYD_ANYDATA_LYB and #LYD_ANYDATA_STRING (and it can be also
88                                          specified as ORed value of the mentioned values). */
89 } LYD_ANYDATA_VALUETYPE;
90 
91 /**
92  * @brief node's value representation
93  */
94 typedef union lyd_value_u {
95     const char *binary;          /**< base64 encoded, NULL terminated string */
96     struct lys_type_bit **bit;   /**< bitmap of pointers to the schema definition of the bit value that are set,
97                                       its size is always the number of defined bits in the schema */
98     int8_t bln;                  /**< 0 as false, 1 as true */
99     int64_t dec64;               /**< decimal64: value = dec64 / 10^fraction-digits  */
100     struct lys_type_enum *enm;   /**< pointer to the schema definition of the enumeration value */
101     struct lys_ident *ident;     /**< pointer to the schema definition of the identityref value */
102     struct lyd_node *instance;   /**< pointer to the instance-identifier target, note that if the tree was modified,
103                                       the target (address) can be invalid - the pointer is correctly checked and updated
104                                       by lyd_validate() */
105     int8_t int8;                 /**< 8-bit signed integer */
106     int16_t int16;               /**< 16-bit signed integer */
107     int32_t int32;               /**< 32-bit signed integer */
108     int64_t int64;               /**< 64-bit signed integer */
109     struct lyd_node *leafref;    /**< pointer to the referenced leaf/leaflist instance in data tree */
110     const char *string;          /**< string */
111     uint8_t uint8;               /**< 8-bit unsigned integer */
112     uint16_t uint16;             /**< 16-bit signed integer */
113     uint32_t uint32;             /**< 32-bit signed integer */
114     uint64_t uint64;             /**< 64-bit signed integer */
115     void *ptr;                   /**< arbitrary data stored using a type plugin */
116 } lyd_val;
117 
118 /**
119  * @brief Attribute structure.
120  *
121  * The structure provides information about attributes of a data element. Such attributes must map to
122  * annotations as specified in RFC 7952. The only exception is the filter type (in NETCONF get operations)
123  * and edit-config's operation attributes. In XML, they are represented as standard XML attributes. In JSON,
124  * they are represented as JSON elements starting with the '@' character (for more information, see the
125  * YANG metadata RFC.
126  *
127  */
128 struct lyd_attr {
129     struct lyd_node *parent;         /**< data node where the attribute is placed */
130     struct lyd_attr *next;           /**< pointer to the next attribute of the same element */
131     struct lys_ext_instance_complex *annotation; /**< pointer to the attribute/annotation's definition */
132     const char *name;                /**< attribute name */
133     const char *value_str;           /**< string representation of value (for comparison, printing,...), always corresponds to value_type */
134     lyd_val value;                   /**< node's value representation, always corresponds to schema->type.base */
135     LY_DATA_TYPE _PACKED value_type; /**< type of the value in the node, mainly for union to avoid repeating of type detection */
136     uint8_t value_flags;             /**< value type flags */
137 };
138 
139 /**
140  * @defgroup validityflags Validity flags
141  * @ingroup datatree
142  *
143  * Validity flags for data nodes.
144  *
145  * @{
146  */
147 #define LYD_VAL_OK       0x00    /**< Node is successfully validated including whole subtree */
148 #define LYD_VAL_DUP      0x01    /**< Instance duplication must be checked again, applicable only to ::lys_node_list and
149                                       ::lys_node_leaf_list data nodes */
150 #define LYD_VAL_UNIQUE   0x02    /**< Unique value(s) changed, applicable only to ::lys_node_list data nodes */
151 #define LYD_VAL_MAND     0x04    /**< Some child added/removed and it is needed to perform check for mandatory
152                                       node or min/max constraints of direct list/leaflist children, applicable only
153                                       to ::lys_node_list and ::lys_node_container data nodes, but if on any other node
154                                       except ::lys_node_leaflist, it means checking that data node for duplicities.
155                                       Additionally, it can be set on truly any node type and then status references
156                                       are checked for this node if flag #LYD_OPT_OBSOLETE is used. */
157 #define LYD_VAL_INUSE    0x80    /**< Internal flag for note about various processing on data, should be used only
158                                       internally and removed before libyang returns the node to the caller */
159 /**
160  * @}
161  */
162 
163 /**
164  * @brief Generic structure for a data node, directly applicable to the data nodes defined as #LYS_CONTAINER, #LYS_LIST
165  * and #LYS_CHOICE.
166  *
167  * Completely fits to containers and choices and is compatible (can be used interchangeably except the #child member)
168  * with all other lyd_node_* structures. All data nodes are provides as ::lyd_node structure by default.
169  * According to the schema's ::lys_node#nodetype member, the specific object is supposed to be cast to
170  * ::lyd_node_leaf_list or ::lyd_node_anydata structures. This structure fits only to #LYS_CONTAINER, #LYS_LIST and
171  * #LYS_CHOICE values.
172  *
173  * To traverse all the child elements or attributes, use #LY_TREE_FOR or #LY_TREE_FOR_SAFE macro. To traverse
174  * the whole subtree, use #LY_TREE_DFS_BEGIN macro.
175  */
176 struct lyd_node {
177     struct lys_node *schema;         /**< pointer to the schema definition of this node */
178     uint8_t validity;                /**< [validity flags](@ref validityflags) */
179     uint8_t dflt:1;                  /**< flag for implicit default node */
180     uint8_t when_status:3;           /**< bit for checking if the when-stmt condition is resolved - internal use only,
181                                           do not use this value! */
182 
183     struct lyd_attr *attr;           /**< pointer to the list of attributes of this node */
184     struct lyd_node *next;           /**< pointer to the next sibling node (NULL if there is no one) */
185     struct lyd_node *prev;           /**< pointer to the previous sibling node \note Note that this pointer is
186                                           never NULL. If there is no sibling node, pointer points to the node
187                                           itself. In case of the first node, this pointer points to the last
188                                           node in the list. */
189     struct lyd_node *parent;         /**< pointer to the parent node, NULL in case of root node */
190 
191 #ifdef LY_ENABLED_LYD_PRIV
192     void *priv;                      /**< private user data, not used by libyang */
193 #endif
194 
195 #ifdef LY_ENABLED_CACHE
196     uint32_t hash;                   /**< hash of this particular node (module name + schema name + key string values if list) */
197     struct hash_table *ht;           /**< hash table with all the direct children (except keys for a list, lists without keys) */
198 #endif
199 
200     struct lyd_node *child;          /**< pointer to the first child node \note Since other lyd_node_*
201                                           structures represent end nodes, this member
202                                           is replaced in those structures. Therefore, be careful with accessing
203                                           this member without having information about the node type from the schema's
204                                           ::lys_node#nodetype member. */
205 };
206 
207 /**
208  * @brief Structure for data nodes defined as #LYS_LEAF or #LYS_LEAFLIST.
209  *
210  * Extension for ::lyd_node structure. It replaces the ::lyd_node#child member by
211  * three new members (#value, #value_str and #value_type) to provide
212  * information about the value. The first five members (#schema, #attr, #next,
213  * #prev and #parent) are compatible with the ::lyd_node's members.
214  *
215  * To traverse through all the child elements or attributes, use #LY_TREE_FOR or #LY_TREE_FOR_SAFE macro.
216  */
217 struct lyd_node_leaf_list {
218     struct lys_node *schema;         /**< pointer to the schema definition of this node which is ::lys_node_leaflist
219                                           structure */
220     uint8_t validity;                /**< [validity flags](@ref validityflags) */
221     uint8_t dflt:1;                  /**< flag for implicit default node */
222     uint8_t when_status:3;           /**< bit for checking if the when-stmt condition is resolved - internal use only,
223                                           do not use this value! */
224 
225     struct lyd_attr *attr;           /**< pointer to the list of attributes of this node */
226     struct lyd_node *next;           /**< pointer to the next sibling node (NULL if there is no one) */
227     struct lyd_node *prev;           /**< pointer to the previous sibling node \note Note that this pointer is
228                                           never NULL. If there is no sibling node, pointer points to the node
229                                           itself. In case of the first node, this pointer points to the last
230                                           node in the list. */
231     struct lyd_node *parent;         /**< pointer to the parent node, NULL in case of root node */
232 
233 #ifdef LY_ENABLED_LYD_PRIV
234     void *priv;                      /**< private user data, not used by libyang */
235 #endif
236 
237 #ifdef LY_ENABLED_CACHE
238     uint32_t hash;                   /**< hash of this particular node (module name + schema name + string value if leaf-list) */
239 #endif
240 
241     /* struct lyd_node *child; should be here, but is not */
242 
243     /* leaflist's specific members */
244     const char *value_str;           /**< string representation of value (for comparison, printing,...), always corresponds to value_type */
245     lyd_val value;                   /**< node's value representation, always corresponds to schema->type.base */
246     LY_DATA_TYPE _PACKED value_type; /**< type of the value in the node, mainly for union to avoid repeating of type detection */
247     uint8_t value_flags;             /**< value type flags */
248 };
249 
250 /**
251  * @brief Flags for values
252  */
253 #define LY_VALUE_UNRES 0x01   /**< flag for unresolved leafref or instance-identifier,
254                                    leafref - value union is filled as if being the target node's type,
255                                    instance-identifier - value union should not be accessed */
256 #define LY_VALUE_USER 0x02    /**< flag for a user type stored value */
257 /* 0x80 is reserved for internal use */
258 
259 /**
260  * @brief Anydata value union
261  */
262 typedef union {
263     const char *str;             /**< string value, in case of printing as XML, characters like '<' or '&' are escaped */
264     char *mem;                   /**< raw memory (used for LYB format) */
265     struct lyxml_elem *xml;      /**< xml tree */
266     struct lyd_node *tree;       /**< libyang data tree, does not change the root's parent, so it is not possible
267                                       to get from the data tree into the anydata/anyxml */
268 } lyd_anydata_value;
269 
270 /**
271  * @brief Structure for data nodes defined as #LYS_ANYDATA or #LYS_ANYXML.
272  *
273  * Extension for ::lyd_node structure - replaces the ::lyd_node#child member by new #value member. The first five
274  * members (#schema, #attr, #next, #prev and #parent) are compatible with the ::lyd_node's members.
275  *
276  * To traverse through all the child elements or attributes, use #LY_TREE_FOR or #LY_TREE_FOR_SAFE macro.
277  */
278 struct lyd_node_anydata {
279     struct lys_node *schema;         /**< pointer to the schema definition of this node which is ::lys_node_anydata
280                                           structure */
281     uint8_t validity;                /**< [validity flags](@ref validityflags) */
282     uint8_t dflt:1;                  /**< flag for implicit default node */
283     uint8_t when_status:3;           /**< bit for checking if the when-stmt condition is resolved - internal use only,
284                                           do not use this value! */
285 
286     struct lyd_attr *attr;           /**< pointer to the list of attributes of this node */
287     struct lyd_node *next;           /**< pointer to the next sibling node (NULL if there is no one) */
288     struct lyd_node *prev;           /**< pointer to the previous sibling node \note Note that this pointer is
289                                           never NULL. If there is no sibling node, pointer points to the node
290                                           itself. In case of the first node, this pointer points to the last
291                                           node in the list. */
292     struct lyd_node *parent;         /**< pointer to the parent node, NULL in case of root node */
293 
294 #ifdef LY_ENABLED_LYD_PRIV
295     void *priv;                      /**< private user data, not used by libyang */
296 #endif
297 
298 #ifdef LY_ENABLED_CACHE
299     uint32_t hash;                   /**< hash of this particular node (module name + schema name) */
300 #endif
301 
302     /* struct lyd_node *child; should be here, but is not */
303 
304     /* anyxml's specific members */
305     LYD_ANYDATA_VALUETYPE value_type;/**< type of the stored anydata value */
306     lyd_anydata_value value;/**< stored anydata value */
307 };
308 
309 /**
310  * @brief list of possible types of differences in #lyd_difflist
311  */
312 typedef enum {
313     LYD_DIFF_END = 0,        /**< end of the differences list */
314     LYD_DIFF_DELETED,        /**< deleted node
315                                   - Node is present in the first tree, but not in the second tree.
316                                   - To make both trees the same the node in lyd_difflist::first can be deleted from the
317                                     first tree. The pointer at the same index in the lyd_difflist::second array is
318                                     NULL.
319                                   - If the deleted node has some children, these do not appear in the resulting diff
320                                     separately. In other words, a deleted node is considered deleted with all
321                                     its children. */
322     LYD_DIFF_CHANGED,        /**< value of a leaf or anyxml is changed, the lyd_difflist::first and lyd_difflist::second
323                                   points to the leaf/anyxml instances in the first and the second tree respectively. */
324     LYD_DIFF_MOVEDAFTER1,    /**< user-ordered (leaf-)list item was moved.
325                                   - To make both trees the same, all #LYD_DIFF_MOVEDAFTER1 transactions must be applied
326                                   to the first tree in the strict order they appear in the difflist. The
327                                   lyd_difflist::first points to the first tree node being moved and the
328                                   lyd_difflist::second points to the first tree node after which the first node is
329                                   supposed to be moved. If the second pointer is NULL, the node is being moved into
330                                   the beginning as the first node of the (leaf-)list instances. */
331     LYD_DIFF_CREATED,        /**< newly created node
332                                   - Node is present in the second tree, but not in the first tree.
333                                   - To make both trees the same the node in lyd_difflist::second is supposed to be
334                                     inserted (copied via lyd_dup()) into the node (as a child) at the same index in the
335                                     lyd_difflist::first array (where is its parent). If the lyd_difflist::first at the
336                                     index is NULL, the missing node is top-level.
337                                   - If the created node has some children, these do not appear in the resulting diff
338                                     separately. In other words, a created node is considered created with all
339                                     its children. */
340     LYD_DIFF_MOVEDAFTER2     /**< similar to LYD_DIFF_MOVEDAFTER1, but this time the moved item is in the second tree.
341                                   This type is always used in combination with (as a successor of) #LYD_DIFF_CREATED
342                                   as an instruction to move the newly created node to a specific position. If it is not
343                                   present, it means that even the parent of the user-ordered instances did not exist
344                                   (or was empty) so it is safe to just create the instances in the same order. Note,
345                                   that due to applicability to the second tree, the meaning of lyd_difflist:first and
346                                   lyd_difflist:second is inverse in comparison to #LYD_DIFF_MOVEDAFTER1. The
347                                   lyd_difflist::second points to the (previously) created node in the second tree and
348                                   the lyd_difflist::first points to the predecessor node in the second tree. If the
349                                   predecessor is NULL, the node is supposed to bes the first sibling. */
350 } LYD_DIFFTYPE;
351 
352 /**
353  * @brief Structure for the result of lyd_diff(), describing differences between two data trees.
354  */
355 struct lyd_difflist {
356     LYD_DIFFTYPE *type;      /**< array of the differences types, terminated by #LYD_DIFF_END value. */
357     struct lyd_node **first; /**< array of nodes in the first tree for the specific type of difference, see the
358                                   description of #LYD_DIFFTYPE values for more information. */
359     struct lyd_node **second;/**< array of nodes in the second tree for the specific type of difference, see the
360                                   description of #LYD_DIFFTYPE values for more information. */
361 };
362 
363 /**
364  * @brief Free the result of lyd_diff(). It frees the structure of the lyd_diff() result, not the referenced nodes.
365  *
366  * @param[in] diff The lyd_diff() result to free.
367  */
368 void lyd_free_diff(struct lyd_difflist *diff);
369 
370 /**
371  * @brief Compare two data trees and provide list of differences.
372  *
373  * Note, that the \p first and the \p second must have the same schema parent (or they must be top-level elements).
374  * In case of using #LYD_OPT_NOSIBLINGS, they both must be instances of the same schema node.
375  *
376  * Order of the resulting set follows these rules:
377  * - To change the first tree into the second tree, the resulting transactions are supposed to be applied in the order
378  *   they appear in the result. First, the changed (#LYD_DIFF_CHANGED) nodes are described followed by the deleted
379  *   (#LYD_DIFF_DELETED) nodes. Then, the moving of the user-ordered nodes present in both trees (#LYD_DIFF_MOVEDAFTER1)
380  *   follows and the last transactions in the results are the newly created (#LYD_DIFF_CREATED) nodes. These nodes are
381  *   supposed to be added as the last siblings, but in some case they can need additional move. In such a case, the
382  *   #LYD_DIFF_MOVEDAFTER2 transactions can appear.
383  * - The order of the changed (#LYD_DIFF_CHANGED) and created (#LYD_DIFF_CREATED) follows the nodes order in the
384  *   second tree - the current siblings are processed first and then the children are processed. Note, that this is
385  *   actually not the BFS:
386  *
387  *           1     2
388  *          / \   / \
389  *         3   4 7   8
390  *        / \
391  *       5   6
392  *
393  * - The order of the deleted (#LYD_DIFF_DELETED) nodes is the DFS:
394  *
395  *           1     6
396  *          / \   / \
397  *         2   5 7   8
398  *        / \
399  *       3   4
400  *
401  * To change the first tree into the second one, it is necessary to follow the order of transactions described in
402  * the result. Note, that it is not possible just to use the transactions in the reverse order to transform the
403  * second tree into the first one. The transactions can be generalized (to be used on a different instance of the
404  * first tree) using lyd_path() to get identifiers for the nodes used in the transactions.
405  *
406  * @param[in] first The first (sub)tree to compare. Without #LYD_OPT_NOSIBLINGS option, all siblings are
407  *            taken into comparison. If NULL, all the \p second nodes are supposed to be top level and they will
408  *            be marked as #LYD_DIFF_CREATED.
409  * @param[in] second The second (sub)tree to compare. Without #LYD_OPT_NOSIBLINGS option, all siblings are
410  *            taken into comparison. If NULL, all the \p first nodes will be marked as #LYD_DIFF_DELETED.
411  * @param[in] options The @ref diffoptions are accepted.
412  * @return NULL on error, the list of differences on success. In case the trees are the same, the first item in the
413  *         lyd_difflist::type array is #LYD_DIFF_END. The returned structure is supposed to be freed by lyd_free_diff().
414  */
415 struct lyd_difflist *lyd_diff(struct lyd_node *first, struct lyd_node *second, int options);
416 
417 /**
418  * @defgroup diffoptions Diff options
419  * @ingroup datatree
420  *
421  * @{
422  */
423 /* LYD_DIFFOPT_NOSIBLINGS value is the same as LYD_OPT_NOSIBLINGS due to backward compatibility. The LYD_OPT_NOSIBLINGS
424  * was used previously as an option for lyd_diff(). */
425 #define LYD_DIFFOPT_NOSIBLINGS   0x0800 /**< The both trees to diff have to instantiate the same schema node so only the
426                                              single subtree is compared. */
427 #define LYD_DIFFOPT_WITHDEFAULTS 0x0001 /**< Take default nodes with their values into account and handle them as part
428                                              of both trees. Summary of the modified behavior:
429                                              - deleted node is replaced with implicit default node - #LYD_DIFF_CHANGED instead delete
430                                              - created node replaces an implicit default node - #LYD_DIFF_CHANGED instead create
431                                              - in both cases even if the values match - #LYD_DIFF_CHANGED is still returned, because dlft flag was changed
432                                              Note that in this case, applying the resulting
433                                              transactions on the first tree does not result to the exact second tree,
434                                              because instead of having implicit default nodes you are going to have
435                                              explicit default nodes. */
436 /**@} diffoptions */
437 
438 /**
439  * @brief Build data path (usable as path, see @ref howtoxpath) of the data node.
440  * @param[in] node Data node to be processed. Note that the node should be from a complete data tree, having a subtree
441  *            (after using lyd_unlink()) can cause generating invalid paths.
442  * @return NULL on error, on success the buffer for the resulting path is allocated and caller is supposed to free it
443  * with free().
444  */
445 char *lyd_path(const struct lyd_node *node);
446 
447 /**
448  * @defgroup parseroptions Data parser options
449  * @ingroup datatree
450  *
451  * Various options to change the data tree parsers behavior.
452  *
453  * Default behavior:
454  * - in case of XML, parser reads all data from its input (file, memory, XML tree) including the case of not well-formed
455  * XML document (multiple top-level elements) and if there is an unknown element, it is skipped including its subtree
456  * (see the next point). This can be changed by the #LYD_OPT_NOSIBLINGS option which make parser to read only a single
457  * tree (with a single root element) from its input.
458  * - parser silently ignores the data without a matching node in schema trees. If the caller want to stop
459  * parsing in case of presence of unknown data, the #LYD_OPT_STRICT can be used. The strict mode is useful for
460  * NETCONF servers, since NETCONF clients should always send data according to the capabilities announced by the server.
461  * On the other hand, the default non-strict mode is useful for clients receiving data from NETCONF server since
462  * clients are not required to understand everything the server does. Of course, the optimal strategy for clients is
463  * to use filtering to get only the required data. Having an unknown element of the known namespace is always an error.
464  * The behavior can be changed by #LYD_OPT_STRICT option.
465  * - using obsolete statements (status set to obsolete) just generates a warning, but the processing continues. The
466  * behavior can be changed by #LYD_OPT_OBSOLETE option.
467  * - parser expects that the provided data provides complete datastore content (both the configuration and state data)
468  * and performs data validation according to all YANG rules. This can be a problem in case of representing NETCONF's
469  * subtree filter data, edit-config's data or other type of data set - such data do not represent a complete data set
470  * and some of the validation rules can fail. Therefore there are other options (within lower 8 bits) to make parser
471  * to accept such a data.
472  * - when parser evaluates when-stmt condition to false, a validation error is raised. If the
473  * #LYD_OPT_WHENAUTODEL is used, the invalid node is silently removed instead of an error. The option (and also this default
474  * behavior) takes effect only in case of #LYD_OPT_DATA or #LYD_OPT_CONFIG type of data.
475  * @{
476  */
477 
478 #define LYD_OPT_DATA       0x00 /**< Default type of data - complete datastore content with configuration as well as
479                                      state data. To handle possibly missing (but by default required) ietf-yang-library
480                                      data, use #LYD_OPT_DATA_NO_YANGLIB or #LYD_OPT_DATA_ADD_YANGLIB options. */
481 #define LYD_OPT_CONFIG     0x01 /**< A configuration datastore - complete datastore without state data.
482                                      Validation modifications:
483                                      - status data are not allowed */
484 #define LYD_OPT_GET        0x02 /**< Data content from a NETCONF reply message to the NETCONF \<get\> operation.
485                                      Validation modifications:
486                                      - mandatory nodes can be omitted
487                                      - leafrefs and instance-identifier resolution is allowed to fail
488                                      - list's keys/unique nodes are not required (so duplication is not checked)
489                                      - must and when evaluation skipped */
490 #define LYD_OPT_GETCONFIG  0x04 /**< Data content from a NETCONF reply message to the NETCONF \<get-config\> operation
491                                      Validation modifications:
492                                      - mandatory nodes can be omitted
493                                      - leafrefs and instance-identifier resolution is allowed to fail
494                                      - list's keys/unique nodes are not required (so duplication is not checked)
495                                      - must and when evaluation skipped
496                                      - status data are not allowed */
497 #define LYD_OPT_EDIT       0x08 /**< Content of the NETCONF \<edit-config\>'s config element.
498                                      Validation modifications:
499                                      - mandatory nodes can be omitted
500                                      - leafrefs and instance-identifier resolution is allowed to fail
501                                      - must and when evaluation skipped
502                                      - status data are not allowed */
503 #define LYD_OPT_RPC        0x10 /**< Data represents RPC or action input parameters. In case of an action, **only**
504                                      the parent nodes are expected ([RFC ref](https://tools.ietf.org/html/rfc7950#section-7.15.2)).
505                                      For validation an additional data tree with the references should be provided. */
506 #define LYD_OPT_RPCREPLY   0x20 /**< Data represents RPC or action output parameters (maps to NETCONF <rpc-reply> data). */
507 #define LYD_OPT_NOTIF      0x40 /**< Data represents an event notification data. In case of a nested notification, **only**
508                                      the parent nodes are expected ([RFC ref](https://tools.ietf.org/html/rfc7950#section-7.16.2)).
509                                      For validation an additional data tree with the references should be provided. */
510 #define LYD_OPT_NOTIF_FILTER 0x80 /**< Data represents a filtered event notification data.
511                                        Validation modification:
512                                        - the only requirement is that the data tree matches the schema tree */
513 #define LYD_OPT_TYPEMASK   0x10000ff /**< Mask to filter data type options. Always only a single data type option (only
514                                           single bit from the lower 8 bits) can be set. */
515 
516 /* 0x100 reserved, used internally */
517 #define LYD_OPT_STRICT     0x0200 /**< Instead of silent ignoring data without schema definition, raise an error. */
518 #define LYD_OPT_DESTRUCT   0x0400 /**< Free the provided XML tree during parsing the data. With this option, the
519                                        provided XML tree is affected and all successfully parsed data are freed.
520                                        This option is applicable only to lyd_parse_xml() function. */
521 #define LYD_OPT_OBSOLETE   0x0800 /**< Raise an error when an obsolete statement (status set to obsolete) is used. */
522 #define LYD_OPT_NOSIBLINGS 0x1000 /**< Parse only a single XML tree from the input. This option applies only to
523                                        XML input data. */
524 #define LYD_OPT_TRUSTED    0x2000 /**< Data comes from a trusted source and it is not needed to validate them. Data
525                                        are connected with the schema, but the most validation checks (mandatory nodes,
526                                        list instance uniqueness, etc.) are not performed. This option does not make
527                                        sense for lyd_validate() so it is ignored by this function. */
528 #define LYD_OPT_WHENAUTODEL 0x4000 /**< Automatically delete subtrees with false when-stmt condition. The flag is
529                                         applicable only in combination with #LYD_OPT_DATA and #LYD_OPT_CONFIG flags.
530                                         If used, libyang will not generate a validation error. */
531 #define LYD_OPT_NOEXTDEPS  0x8000 /**< Allow external dependencies (external leafrefs, instance-identifiers, must,
532                                        and when) to not be resolved/satisfied during validation. */
533 #define LYD_OPT_DATA_NO_YANGLIB  0x10000 /**< Ignore (possibly) missing ietf-yang-library data. Applicable only with #LYD_OPT_DATA. */
534 #define LYD_OPT_DATA_ADD_YANGLIB 0x20000 /**< Add missing ietf-yang-library data into the validated data tree. Applicable
535                                               only with #LYD_OPT_DATA. If some ietf-yang-library data are present, they are
536                                               preserved and option is ignored. */
537 #define LYD_OPT_VAL_DIFF 0x40000 /**< Flag only for validation, store all the data node changes performed by the validation
538                                       in a diff structure. */
539 #define LYD_OPT_LYB_MOD_UPDATE 0x80000 /**< Allow to parse data using an updated revision of a module, relevant only for LYB format. */
540 #define LYD_OPT_DATA_TEMPLATE 0x1000000 /**< Data represents YANG data template. */
541 #define LYD_OPT_MULTI_ERRORS  0x2000000 /**< Report all validation errors instead of the first one.
542                                              Applicable only in combination with #LYD_OPT_DATA and #LYD_OPT_CONFIG flags.
543                                              And, the @ref logopts need support storing multiple error messages.
544                                              NOTE: Only some kinds of validation error are supported:
545                                                    must, unique, unresolved union and unresolved instance-identifier.  */
546 
547 /**@} parseroptions */
548 
549 /**
550  * @brief Parse (and validate) data from memory.
551  *
552  * In case of LY_XML format, the data string is parsed completely. It means that when it contains
553  * a non well-formed XML with multiple root elements, all those sibling XML trees are parsed. The
554  * returned data node is a root of the first tree with other trees connected via the next pointer.
555  * This behavior can be changed by #LYD_OPT_NOSIBLINGS option.
556  *
557  * @param[in] ctx Context to connect with the data tree being built here.
558  * @param[in] data Serialized data in the specified format.
559  * @param[in] format Format of the input data to be parsed.
560  * @param[in] options Parser options, see @ref parseroptions.
561  * @param[in] ... Variable arguments depend on \p options. If they include:
562  *                - #LYD_OPT_DATA:
563  *                - #LYD_OPT_CONFIG:
564  *                - #LYD_OPT_GET:
565  *                - #LYD_OPT_GETCONFIG:
566  *                - #LYD_OPT_EDIT:
567  *                  - no variable arguments expected.
568  *                - #LYD_OPT_RPC:
569  *                - #LYD_OPT_NOTIF:
570  *                  - struct ::lyd_node *data_tree - additional **validated** top-level siblings of a data tree that
571  *                    will be used when checking any references ("when", "must" conditions, leafrefs, ...)
572  *                    **in the action/nested notification subtree** that require some nodes outside their subtree.
573  *                    It is assumed that **all parents** of the action/nested notification exist as required
574  *                    ([RFC ref](https://tools.ietf.org/html/rfc8342#section-6.2)).
575  *                - #LYD_OPT_RPCREPLY:
576  *                  - const struct ::lyd_node *rpc_act - pointer to the whole RPC or (top-level) action operation
577  *                    data tree (the request) of the reply.
578  *                  - const struct ::lyd_node *data_tree - additional **validated** top-level siblings of a data tree that
579  *                    will be used when checking any references ("when", "must" conditions, leafrefs, ...)
580  *                    that require some nodes outside their subtree.
581  * @return Pointer to the built data tree or NULL in case of empty \p data. To free the returned structure,
582  *         use lyd_free(). In these cases, the function sets #ly_errno to LY_SUCCESS. In case of error,
583  *         #ly_errno contains appropriate error code (see #LY_ERR).
584  */
585 struct lyd_node *lyd_parse_mem(struct ly_ctx *ctx, const char *data, LYD_FORMAT format, int options, ...);
586 
587 /**
588  * @brief Read (and validate) data from the given file descriptor.
589  *
590  * \note Current implementation supports only reading data from standard (disk) file, not from sockets, pipes, etc.
591  *
592  * In case of LY_XML format, the file content is parsed completely. It means that when it contains
593  * a non well-formed XML with multiple root elements, all those sibling XML trees are parsed. The
594  * returned data node is a root of the first tree with other trees connected via the next pointer.
595  * This behavior can be changed by #LYD_OPT_NOSIBLINGS option.
596  *
597  * @param[in] ctx Context to connect with the data tree being built here.
598  * @param[in] fd The standard file descriptor of the file containing the data tree in the specified format.
599  * @param[in] format Format of the input data to be parsed.
600  * @param[in] options Parser options, see @ref parseroptions.
601  * @param[in] ... Variable arguments depend on \p options. If they include:
602  *                - #LYD_OPT_DATA:
603  *                - #LYD_OPT_CONFIG:
604  *                - #LYD_OPT_GET:
605  *                - #LYD_OPT_GETCONFIG:
606  *                - #LYD_OPT_EDIT:
607  *                  - no variable arguments expected.
608  *                - #LYD_OPT_RPC:
609  *                - #LYD_OPT_NOTIF:
610  *                  - struct ::lyd_node *data_tree - additional **validated** top-level siblings of a data tree that
611  *                    will be used when checking any references ("when", "must" conditions, leafrefs, ...)
612  *                    **in the action/nested notification subtree** that require some nodes outside their subtree.
613  *                    It is assumed that **all parents** of the action/nested notification exist as required
614  *                    ([RFC ref](https://tools.ietf.org/html/rfc8342#section-6.2)).
615  *                - #LYD_OPT_RPCREPLY:
616  *                  - const struct ::lyd_node *rpc_act - pointer to the whole RPC or action operation data
617  *                    tree (the request) of the reply.
618  *                  - const struct ::lyd_node *data_tree - additional **validated** top-level siblings of a data tree that
619  *                    will be used when checking any references ("when", "must" conditions, leafrefs, ...)
620  *                    that require some nodes outside their subtree.
621  * @return Pointer to the built data tree or NULL in case of empty file. To free the returned structure,
622  *         use lyd_free(). In these cases, the function sets #ly_errno to LY_SUCCESS. In case of error,
623  *         #ly_errno contains appropriate error code (see #LY_ERR).
624  */
625 struct lyd_node *lyd_parse_fd(struct ly_ctx *ctx, int fd, LYD_FORMAT format, int options, ...);
626 
627 /**
628  * @brief Read (and validate) data from the given file path.
629  *
630  * In case of LY_XML format, the file content is parsed completely. It means that when it contains
631  * a non well-formed XML with multiple root elements, all those sibling XML trees are parsed. The
632  * returned data node is a root of the first tree with other trees connected via the next pointer.
633  * This behavior can be changed by #LYD_OPT_NOSIBLINGS option.
634  *
635  * @param[in] ctx Context to connect with the data tree being built here.
636  * @param[in] path Path to the file containing the data tree in the specified format.
637  * @param[in] format Format of the input data to be parsed.
638  * @param[in] options Parser options, see @ref parseroptions.
639  * @param[in] ... Variable arguments depend on \p options. If they include:
640  *                - #LYD_OPT_DATA:
641  *                - #LYD_OPT_CONFIG:
642  *                - #LYD_OPT_GET:
643  *                - #LYD_OPT_GETCONFIG:
644  *                - #LYD_OPT_EDIT:
645  *                  - no variable arguments expected.
646  *                - #LYD_OPT_RPC:
647  *                - #LYD_OPT_NOTIF:
648  *                  - struct ::lyd_node *data_tree - additional **validated** top-level siblings of a data tree that
649  *                    will be used when checking any references ("when", "must" conditions, leafrefs, ...)
650  *                    **in the action/nested notification subtree** that require some nodes outside their subtree.
651  *                    It is assumed that **all parents** of the action/nested notification exist as required
652  *                    ([RFC ref](https://tools.ietf.org/html/rfc8342#section-6.2)).
653  *                - #LYD_OPT_RPCREPLY:
654  *                  - const struct ::lyd_node *rpc_act - pointer to the whole RPC or action operation data
655  *                    tree (the request) of the reply.
656  *                  - const struct ::lyd_node *data_tree - additional **validated** top-level siblings of a data tree that
657  *                    will be used when checking any references ("when", "must" conditions, leafrefs, ...)
658  *                    that require some nodes outside their subtree.
659  * @return Pointer to the built data tree or NULL in case of empty file. To free the returned structure,
660  *         use lyd_free(). In these cases, the function sets #ly_errno to LY_SUCCESS. In case of error,
661  *         #ly_errno contains appropriate error code (see #LY_ERR).
662  */
663 struct lyd_node *lyd_parse_path(struct ly_ctx *ctx, const char *path, LYD_FORMAT format, int options, ...);
664 
665 /**
666  * @brief Parse (and validate) XML tree.
667  *
668  * The output data tree is parsed from the given XML tree previously parsed by one of the
669  * lyxml_read* functions.
670  *
671  * If there are some sibling elements of the \p root (data were read with #LYXML_PARSE_MULTIROOT option
672  * or the provided root is a root element of a subtree), all the sibling nodes (previous as well as
673  * following) are processed as well. The returned data node is a root of the first tree with other
674  * trees connected via the next pointer. This behavior can be changed by #LYD_OPT_NOSIBLINGS option.
675  *
676  * When the function is used with #LYD_OPT_DESTRUCT, all the successfully parsed data including the
677  * XML \p root and all its siblings (if #LYD_OPT_NOSIBLINGS is not used) are freed. Only with
678  * #LYD_OPT_DESTRUCT option the \p root pointer is changed - if all the data are parsed, it is set
679  * to NULL, otherwise it will hold the XML tree without the successfully parsed elements.
680  *
681  * The context must be the same as the context used to parse XML tree by lyxml_read* function.
682  *
683  * @param[in] ctx Context to connect with the data tree being built here.
684  * @param[in,out] root XML tree to parse (convert) to data tree. By default, parser do not change the XML tree. However,
685  *            when #LYD_OPT_DESTRUCT is specified in \p options, parser frees all successfully parsed data.
686  * @param[in] options Parser options, see @ref parseroptions.
687  * @param[in] ... Variable arguments depend on \p options. If they include:
688  *                - #LYD_OPT_DATA:
689  *                - #LYD_OPT_CONFIG:
690  *                - #LYD_OPT_GET:
691  *                - #LYD_OPT_GETCONFIG:
692  *                - #LYD_OPT_EDIT:
693  *                  - no variable arguments expected.
694  *                - #LYD_OPT_RPC:
695  *                - #LYD_OPT_NOTIF:
696  *                  - struct ::lyd_node *data_tree - additional **validated** top-level siblings of a data tree that
697  *                    will be used when checking any references ("when", "must" conditions, leafrefs, ...)
698  *                    **in the action/nested notification subtree** that require some nodes outside their subtree.
699  *                    It is assumed that **all parents** of the action/nested notification exist as required
700  *                    ([RFC ref](https://tools.ietf.org/html/rfc8342#section-6.2)).
701  *                - #LYD_OPT_RPCREPLY:
702  *                  - const struct ::lyd_node *rpc_act - pointer to the whole RPC or action operation data
703  *                    tree (the request) of the reply.
704  *                  - const struct ::lyd_node *data_tree - additional **validated** top-level siblings of a data tree that
705  *                    will be used when checking any references ("when", "must" conditions, leafrefs, ...)
706  *                    that require some nodes outside their subtree.
707  * @return Pointer to the built data tree or NULL in case of empty \p root. To free the returned structure,
708  *         use lyd_free(). In these cases, the function sets #ly_errno to LY_SUCCESS. In case of error,
709  *         #ly_errno contains appropriate error code (see #LY_ERR).
710  */
711 struct lyd_node *lyd_parse_xml(struct ly_ctx *ctx, struct lyxml_elem **root, int options,...);
712 
713 /**
714  * @brief Create a new container node in a data tree.
715  *
716  * __PARTIAL CHANGE__ - validate after the final change on the data tree (see @ref howtodatamanipulators).
717  *
718  * @param[in] parent Parent node for the node being created. NULL in case of creating top level element.
719  * @param[in] module Module with the node being created.
720  * @param[in] name Schema node name of the new data node. The node can be #LYS_CONTAINER, #LYS_LIST,
721  * #LYS_NOTIF, #LYS_RPC, or #LYS_ACTION.
722  * @return New node, NULL on error.
723  */
724 struct lyd_node *lyd_new(struct lyd_node *parent, const struct lys_module *module, const char *name);
725 
726 /**
727  * @brief Create a new leaf or leaflist node in a data tree with a string value that is converted to
728  * the actual value.
729  *
730  * __PARTIAL CHANGE__ - validate after the final change on the data tree (see @ref howtodatamanipulators).
731  *
732  * @param[in] parent Parent node for the node being created. NULL in case of creating top level element.
733  * @param[in] module Module with the node being created.
734  * @param[in] name Schema node name of the new data node.
735  * @param[in] val_str String form of the value of the node being created. In case the type is #LY_TYPE_INST
736  * or #LY_TYPE_IDENT, JSON node-id format is expected (nodes are prefixed with module names, not XML namespaces).
737  * @return New node, NULL on error.
738  */
739 struct lyd_node *lyd_new_leaf(struct lyd_node *parent, const struct lys_module *module, const char *name,
740                               const char *val_str);
741 
742 /**
743  * @brief Change value of a leaf node.
744  *
745  * __PARTIAL CHANGE__ - validate after the final change on the data tree (see @ref howtodatamanipulators).
746  *
747  * Despite the prototype allows to provide a leaflist node as \p leaf parameter, only leafs are accepted.
748  * Also, the leaf will never be default after calling this function successfully.
749  *
750  * @param[in] leaf A leaf node to change.
751  * @param[in] val_str String form of the new value to be set to the \p leaf. In case the type is #LY_TYPE_INST
752  * or #LY_TYPE_IDENT, JSON node-id format is expected (nodes are prefixed with module names, not XML namespaces).
753  * @return 0 if the leaf was changed successfully (either its value changed or at least its default flag was cleared),
754  *         <0 on error,
755  *         1 if the (canonical) value matched the original one and no value neither default flag change occurred.
756  */
757 int lyd_change_leaf(struct lyd_node_leaf_list *leaf, const char *val_str);
758 
759 /**
760  * @brief Create a new anydata or anyxml node in a data tree.
761  *
762  * __PARTIAL CHANGE__ - validate after the final change on the data tree (see @ref howtodatamanipulators).
763  *
764  * This function is supposed to be a replacement for the lyd_new_anyxml_str() and lyd_new_anyxml_xml().
765  *
766  * @param[in] parent Parent node for the node being created. NULL in case of creating top level element.
767  * @param[in] module Module with the node being created.
768  * @param[in] name Schema node name of the new data node. The schema node determines if the anydata or anyxml node
769  *            is created.
770  * @param[in] value Pointer to the value data to be stored in the anydata/anyxml node. The type of the data is
771  *            determined according to the \p value_type parameter.
772  * @param[in] value_type Type of the provided data \p value.
773  * @return New node, NULL on error.
774  */
775 struct lyd_node *lyd_new_anydata(struct lyd_node *parent, const struct lys_module *module, const char *name,
776                                  void *value, LYD_ANYDATA_VALUETYPE value_type);
777 
778 /**
779  * @brief Create a new container node in a data tree. Ignore RPC/action input nodes and instead use RPC/action output ones.
780  *
781  * __PARTIAL CHANGE__ - validate after the final change on the data tree (see @ref howtodatamanipulators).
782  *
783  * @param[in] parent Parent node for the node being created. NULL in case of creating top level element.
784  * @param[in] module Module with the node being created.
785  * @param[in] name Schema node name of the new data node. The node should only be #LYS_CONTAINER or #LYS_LIST,
786  * but accepted are also #LYS_NOTIF, #LYS_RPC, or #LYS_ACTION.
787  * @return New node, NULL on error.
788  */
789 struct lyd_node *lyd_new_output(struct lyd_node *parent, const struct lys_module *module, const char *name);
790 
791 /**
792  * @brief Create a new leaf or leaflist node in a data tree with a string value that is converted to
793  * the actual value. Ignore RPC/action input nodes and instead use RPC/action output ones.
794  *
795  * __PARTIAL CHANGE__ - validate after the final change on the data tree (see @ref howtodatamanipulators).
796  *
797  * @param[in] parent Parent node for the node being created. NULL in case of creating top level element.
798  * @param[in] module Module with the node being created.
799  * @param[in] name Schema node name of the new data node.
800  * @param[in] val_str String form of the value of the node being created. In case the type is #LY_TYPE_INST
801  * or #LY_TYPE_IDENT, JSON node-id format is expected (nodes are prefixed with module names, not XML namespaces).
802  * @return New node, NULL on error.
803  */
804 struct lyd_node *lyd_new_output_leaf(struct lyd_node *parent, const struct lys_module *module, const char *name,
805                                      const char *val_str);
806 
807 /**
808  * @brief Create a new anydata or anyxml node in a data tree. Ignore RPC/action input nodes and instead use
809  * RPC/action output ones.
810  *
811  * __PARTIAL CHANGE__ - validate after the final change on the data tree (see @ref howtodatamanipulators).
812  *
813  * @param[in] parent Parent node for the node being created. NULL in case of creating top level element.
814  * @param[in] module Module with the node being created.
815  * @param[in] name Schema node name of the new data node. The schema node determines if the anydata or anyxml node
816  *            is created.
817  * @param[in] value Pointer to the value data to be stored in the anydata/anyxml node. The type of the data is
818  *            determined according to the \p value_type parameter. Data are supposed to be dynamically allocated.
819  *            Since it is directly attached into the created data node, caller is supposed to not manipulate with
820  *            the data after a successful call (including calling free() on the provided data).
821  * @param[in] value_type Type of the provided data \p value.
822  * @return New node, NULL on error.
823  */
824 struct lyd_node *lyd_new_output_anydata(struct lyd_node *parent, const struct lys_module *module, const char *name,
825                                         void *value, LYD_ANYDATA_VALUETYPE value_type);
826 
827 /**
828  * @brief Create a new yang-data template in a data tree. It creates container, which name is in third parameter.
829  *
830  * __PARTIAL CHANGE__ - validate after the final change on the data tree (see @ref howtodatamanipulators).
831  *
832  * @param[in] module Module with the node being created.
833  * @param[in] name_template Yang-data template name. This name is used for searching of yang-data instance.
834  * @param[in] name Schema node name of the new data node. This node is container.
835  * @return New node, NULL on error.
836  */
837 struct lyd_node *lyd_new_yangdata(const struct lys_module *module, const char *name_template, const char *name);
838 
839 /**
840  * @defgroup pathoptions Data path creation options
841  * @ingroup datatree
842  *
843  * Various options to change lyd_new_path() behavior.
844  *
845  * Default behavior:
846  * - if the target node already exists (and is not default), an error is returned.
847  * - the whole path to the target node is created (with any missing parents) if necessary.
848  * - RPC output schema children are completely ignored in all modules. Input is searched and nodes created normally.
849  * @{
850  */
851 
852 #define LYD_PATH_OPT_UPDATE   0x01 /**< If the target node exists, is a leaf, and it is updated with a new value or its
853                                         default flag is changed, it is returned. If the target node exists and is not
854                                         a leaf or generally no change occurs in the \p data_tree, NULL is returned and no error set. */
855 #define LYD_PATH_OPT_NOPARENT 0x02 /**< If any parents of the target node do not exist, return an error instead of implicitly
856                                         creating them. */
857 #define LYD_PATH_OPT_OUTPUT   0x04 /**< Changes the behavior to ignoring RPC/action input schema nodes and using only output ones. */
858 #define LYD_PATH_OPT_DFLT     0x08 /**< The created node (nodes, if also creating the parents) is a default one. If working with
859                                         data tree of type #LYD_OPT_DATA, #LYD_OPT_CONFIG, #LYD_OPT_RPC, #LYD_OPT_RPCREPLY, or
860                                         #LYD_OPT_NOTIF, this flag is never needed and therefore should not be used. However, if
861                                         the tree is #LYD_OPT_GET, #LYD_OPT_GETCONFIG, or #LYD_OPT_EDIT, the default nodes are not
862                                         created during validation and using this flag one can set them (see @ref howtodatawd). */
863 #define LYD_PATH_OPT_NOPARENTRET 0x10 /**< Changes the return value in the way that even if some parents were created in
864                                         addition to the path-referenced node, the path-referenced node will always be returned. */
865 #define LYD_PATH_OPT_EDIT     0x20 /**< Allows the creation of special leaves without value. These leaves are valid if used
866                                         in a NETCONF edit-config with delete/remove operation. */
867 
868 /** @} pathoptions */
869 
870 /**
871  * @brief Create a new data node based on a simple XPath.
872  *
873  * __PARTIAL CHANGE__ - validate after the final change on the data tree (see @ref howtodatamanipulators).
874  *
875  * The new node is normally inserted at the end, either as the last child of a parent or as the last sibling
876  * if working with top-level elements. However, when manipulating RPC input or output, schema ordering is
877  * required and always guaranteed.
878  *
879  * If \p path points to a list key and the list does not exist, the key value from the predicate is used
880  * and \p value is ignored.
881  *
882  * @param[in] data_tree Existing data tree to add to/modify (including siblings). If creating RPCs/actions, there
883  * should only be one RPC/action and either input or output, not both. Can be NULL.
884  * @param[in] ctx Context to use. Mandatory if \p data_tree is NULL.
885  * @param[in] path Simple data path (see @ref howtoxpath). List nodes can have predicates, one for each list key
886  * in the correct order and with its value as well or using specific instance position, leaves and leaf-lists
887  * can have predicates too that have preference over \p value. When specifying an identityref value in a predicate,
888  * you MUST use the module name as the value prefix!
889  * @param[in] value Value of the new leaf/lealf-list (const char*). If creating anydata or anyxml, the following
890  * \p value_type parameter is required to be specified correctly. If creating nodes of other types, the
891  * parameter is ignored.
892  * @param[in] value_type Type of the provided \p value parameter in case of creating anydata or anyxml node.
893  * @param[in] options Bitmask of options flags, see @ref pathoptions.
894  * @return First created (or updated with #LYD_PATH_OPT_UPDATE) node,
895  * NULL if #LYD_PATH_OPT_UPDATE was used and the full path exists or the leaf original value matches \p value,
896  * NULL and ly_errno is set on error.
897  */
898 struct lyd_node *lyd_new_path(struct lyd_node *data_tree, const struct ly_ctx *ctx, const char *path, void *value,
899                               LYD_ANYDATA_VALUETYPE value_type, int options);
900 
901 /**
902  * @brief Learn the relative instance position of a list or leaf-list within other instances of the
903  * same schema node.
904  *
905  * @param[in] node List or leaf-list to get the position of.
906  * @return 0 on error or positive integer of the instance position.
907  */
908 unsigned int lyd_list_pos(const struct lyd_node *node);
909 
910 /**
911  * @defgroup dupoptions Data duplication options
912  * @ingroup datatree
913  *
914  * Various options to change lyd_dup() behavior.
915  *
916  * Default behavior:
917  * - only the specified node is duplicated without siblings, parents, or children.
918  * - all the attributes of the duplicated nodes are also duplicated.
919  * @{
920  */
921 
922 #define LYD_DUP_OPT_RECURSIVE    0x01 /**< Duplicate not just the node but also all the children. */
923 #define LYD_DUP_OPT_NO_ATTR      0x02 /**< Do not duplicate attributes of any node. */
924 #define LYD_DUP_OPT_WITH_PARENTS 0x04 /**< If a nested node is being duplicated, duplicate also all the parents.
925                                            Keys are also duplicated for lists. Return value does not change! */
926 #define LYD_DUP_OPT_WITH_KEYS    0x08 /**< If a lits key is being duplicated non-recursively, duplicate its keys.
927                                            Ignored if used with #LYD_DUP_OPT_RECURSIVE. Return value does not change! */
928 #define LYD_DUP_OPT_WITH_WHEN    0x10 /**< Also copy any when evaluation state flags. This is useful in case the copied
929                                            nodes are actually still part of the same datastore meaning no dependency data
930                                            could have changed. Otherwise nothing is assumed about the copied node when
931                                            state and it is evaluated from scratch during validation. */
932 
933 /** @} dupoptions */
934 
935 /**
936  * @brief Create a copy of the specified data tree \p node. Schema references are kept the same. Use carefully,
937  * since libyang silently creates default nodes, it is always better to use lyd_dup_withsiblings() to duplicate
938  * the complete data tree.
939  *
940  * __PARTIAL CHANGE__ - validate after the final change on the data tree (see @ref howtodatamanipulators).
941  *
942  * @param[in] node Data tree node to be duplicated.
943  * @param[in] options Bitmask of options flags, see @ref dupoptions.
944  * @return Created copy of the provided data \p node.
945  */
946 struct lyd_node *lyd_dup(const struct lyd_node *node, int options);
947 
948 /**
949  * @brief Create a copy of the specified data tree and all its siblings (preceding as well as following).
950  * Schema references are kept the same.
951  *
952  * __PARTIAL CHANGE__ - validate after the final change on the data tree (see @ref howtodatamanipulators).
953  *
954  * @param[in] node Data tree sibling node to be duplicated.
955  * @param[in] options Bitmask of options flags, see @ref dupoptions.
956  * @return Created copy of the provided data \p node and all of its siblings.
957  */
958 struct lyd_node *lyd_dup_withsiblings(const struct lyd_node *node, int options);
959 
960 /**
961  * @brief Create a copy of the specified data tree \p node in the different context. All the
962  * schema references and strings are re-mapped into the specified context.
963  *
964  * If the target context does not contain the schemas used in the source data tree, error
965  * is raised and the new data tree is not created.
966  *
967  * @param[in] node Data tree node to be duplicated.
968  * @param[in] options Bitmask of options flags, see @ref dupoptions.
969  * @param[in] ctx Target context for the duplicated data.
970  * @return Created copy of the provided data \p node.
971  */
972 struct lyd_node *lyd_dup_to_ctx(const struct lyd_node *node, int options, struct ly_ctx *ctx);
973 
974 /**
975  * @brief Merge a (sub)tree into a data tree.
976  *
977  * __PARTIAL CHANGE__ - validate after the final change on the data tree (see @ref howtodatamanipulators).
978  *
979  * Missing nodes are merged, leaf values updated. Any attributes on the data nodes are strictly tied
980  * to the nodes - if the node is merged, its attributes are merged with it, if the node is not merged,
981  * its attributes are not merged either.
982  *
983  * If \p target and \p source do not share the top-level schema node, even if they
984  * are from different modules, \p source parents up to top-level node will be created and
985  * linked to the \p target (but only containers can be created this way, lists need keys,
986  * so if lists are missing, an error will be returned).
987  *
988  * If the source data tree is in a different context, the resulting data are placed into the context
989  * of the target tree.
990  *
991  * @param[in] target Top-level (or an RPC output child) data tree to merge to. Must be valid.
992  * @param[in] source Data tree to merge \p target with. Must be valid (at least as a subtree).
993  * @param[in] options Bitmask of the following option flags:
994  * - #LYD_OPT_DESTRUCT - spend \p source in the function, otherwise \p source is left untouched,
995  * - #LYD_OPT_NOSIBLINGS - merge only the \p source subtree (ignore siblings), otherwise merge
996  * \p source and all its succeeding siblings (preceding ones are still ignored!),
997  * - #LYD_OPT_EXPLICIT - when merging an explicitly set node and a default node, always put
998  * the explicit node into \p target, otherwise the node which is in \p source is used.
999  * @return 0 on success, nonzero in case of an error.
1000  */
1001 int lyd_merge(struct lyd_node *target, const struct lyd_node *source, int options);
1002 
1003 /**
1004  * @brief Same as lyd_merge(), but moves the resulting data into the specified context.
1005  *
1006  * __PARTIAL CHANGE__ - validate after the final change on the data tree (see @ref howtodatamanipulators).
1007  *
1008  * @param[in] trg Top-level (or an RPC output child) data tree to merge to. Must be valid. If its context
1009  *            differs from the specified \p ctx of the result, the provided data tree is freed and the new
1010  *            tree in the required context is returned on success. To keep the \p trg tree, convert it to the
1011  *            target context using lyd_dup_to_ctx() and then call lyd_merge() instead of lyd_merge_to_ctx().
1012  * @param[in] src Data tree to merge \p target with. Must be valid (at least as a subtree).
1013  * @param[in] options Bitmask of the following option flags:
1014  * - #LYD_OPT_DESTRUCT - spend \p source in the function, otherwise \p source is left untouched,
1015  * - #LYD_OPT_NOSIBLINGS - merge only the \p source subtree (ignore siblings), otherwise merge
1016  * \p source and all its succeeding siblings (preceding ones are still ignored!),
1017  * - #LYD_OPT_EXPLICIT - when merging an explicitly set node and a default node, always put
1018  * the explicit node into \p target, otherwise the node which is in \p source is used.
1019  * @param[in] ctx Target context in which the result will be created. Note that the successful merge requires to have
1020  *            all the used modules in the source and target data trees loaded in the target context.
1021  * @return 0 on success, nonzero in case of an error.
1022  */
1023 int lyd_merge_to_ctx(struct lyd_node **trg, const struct lyd_node *src, int options, struct ly_ctx *ctx);
1024 
1025 #define LYD_OPT_EXPLICIT 0x0100
1026 
1027 /**
1028  * @brief Insert the \p node element as child to the \p parent element. The \p node is inserted as a last child of the
1029  * \p parent.
1030  *
1031  * __PARTIAL CHANGE__ - validate after the final change on the data tree (see @ref howtodatamanipulators).
1032  *
1033  * - if the node is part of some other tree, it is automatically unlinked.
1034  * - if the node is the first node of a node list (with no parent), all the subsequent nodes are also inserted.
1035  * - if the key of a list is being inserted, it is placed into a correct position instead of being placed as the last
1036  * element.
1037  * - if the target tree includes the default instance of the node being inserted, the default node is silently replaced
1038  * by the new node.
1039  * - if a default node is being inserted and the target tree already contains non-default instance, the existing
1040  * instance is silently replaced. If it contains the exact same default node, it is replaced as well.
1041  * - if a non-default node is being inserted and there is already its non-default instance in the target tree, the new
1042  * node is inserted and it is up to the caller to solve the presence of multiple instances afterwards.
1043  *
1044  * Note that this function differs from lyd_insert_before() and lyd_insert_after() because the position of the
1045  * node being inserted is determined automatically according to the rules described above. In contrast to
1046  * lyd_insert_parent(), lyd_insert() can not be used for top-level elements since the \p parent parameter must not be
1047  * NULL. If inserting something larger and not fitting the mentioned use-cases (or simply if unsure), you can always
1048  * use lyd_merge(), it should be able to handle any situation.
1049  *
1050  * @param[in] parent Parent node for the \p node being inserted.
1051  * @param[in] node The node being inserted.
1052  * @return 0 on success, nonzero in case of error, e.g. when the node is being inserted to an inappropriate place
1053  * in the data tree.
1054  */
1055 int lyd_insert(struct lyd_node *parent, struct lyd_node *node);
1056 
1057 /**
1058  * @brief Insert the \p node element as a last sibling of the specified \p sibling element.
1059  *
1060  * __PARTIAL CHANGE__ - validate after the final change on the data tree (see @ref howtodatamanipulators).
1061  *
1062  * - if the node is part of some other tree, it is automatically unlinked.
1063  * - if the node is the first node of a node list (with no parent), all the subsequent nodes are also inserted.
1064  * - if the key of a list is being inserted, it is placed into a correct position instead of being placed as the last
1065  * element.
1066  * - if the target tree includes the default instance of the node being inserted, the default node is silently replaced
1067  * by the new node.
1068  * - if a default node is being inserted and the target tree already contains non-default instance, the existing
1069  * instance is silently replaced. If it contains the exact same default node, it is replaced as well.
1070  * - if a non-default node is being inserted and there is already its non-default instance in the target tree, the new
1071  * node is inserted and it is up to the caller to solve the presence of multiple instances afterwards.
1072  *
1073  * Note that this function differs from lyd_insert_before() and lyd_insert_after() because the position of the
1074  * node being inserted is determined automatically as in the case of lyd_insert(). In contrast to lyd_insert(),
1075  * lyd_insert_sibling() can be used to insert top-level elements. If inserting something larger and not fitting
1076  * the mentioned use-cases (or simply if unsure), you can always use lyd_merge(), it should be able to handle
1077  * any situation.
1078  *
1079  * @param[in,out] sibling Sibling node as a reference where to insert the \p node. When function succeeds, the sibling
1080  * is always set to point to the first sibling node. Note that in some cases described above, the provided sibling
1081  * node could be removed from the tree.
1082  * @param[in] node The node being inserted.
1083  * @return 0 on success, nonzero in case of error, e.g. when the node is being inserted to an inappropriate place
1084  * in the data tree.
1085  */
1086 int lyd_insert_sibling(struct lyd_node **sibling, struct lyd_node *node);
1087 
1088 /**
1089  * @brief Insert the \p node element after the \p sibling element. If \p node and \p siblings are already
1090  * siblings (just moving \p node position).
1091  *
1092  * __PARTIAL CHANGE__ - validate after the final change on the data tree (see @ref howtodatamanipulators).
1093  *
1094  * - if the target tree includes the default instance of the node being inserted, the default node is silently removed.
1095  * - if a default node is being inserted and the target tree already contains non-default instance, the existing
1096  * instance is removed. If it contains the exact same default node, it is removed as well.
1097  * - if a non-default node is being inserted and there is already its non-default instance in the target tree, the new
1098  * node is inserted and it is up to the caller to solve the presence of multiple instances afterwards.
1099  *
1100  * @param[in] sibling The data tree node before which the \p node will be inserted.
1101  * @param[in] node The data tree node to be inserted. If the node is connected somewhere, it is unlinked first.
1102  * @return 0 on success, nonzero in case of error, e.g. when the node is being inserted to an inappropriate place
1103  * in the data tree.
1104  */
1105 int lyd_insert_before(struct lyd_node *sibling, struct lyd_node *node);
1106 
1107 /**
1108  * @brief Insert the \p node element after the \p sibling element. If \p node and \p siblings are already
1109  * siblings (just moving \p node position).
1110  *
1111  * __PARTIAL CHANGE__ - validate after the final change on the data tree (see @ref howtodatamanipulators).
1112  *
1113  * - if the target tree includes the default instance of the node being inserted, the default node is silently removed.
1114  * - if a default node is being inserted and the target tree already contains non-default instance, the existing
1115  * instance is removed. If it contains the exact same default node, it is removed as well.
1116  * - if a non-default node is being inserted and there is already its non-default instance in the target tree, the new
1117  * node is inserted and it is up to the caller to solve the presence of multiple instances afterwards.
1118  *
1119  * @param[in] sibling The data tree node before which the \p node will be inserted. If \p node and \p siblings
1120  * are already siblings (just moving \p node position), skip validation.
1121  * @param[in] node The data tree node to be inserted. If the node is connected somewhere, it is unlinked first.
1122  * @return 0 on success, nonzero in case of error, e.g. when the node is being inserted to an inappropriate place
1123  * in the data tree.
1124  */
1125 int lyd_insert_after(struct lyd_node *sibling, struct lyd_node *node);
1126 
1127 /**
1128  * @brief Order siblings according to the schema node ordering.
1129  *
1130  * __PARTIAL CHANGE__ - validate after the final change on the data tree (see @ref howtodatamanipulators).
1131  *
1132  * If the siblings include data nodes from other modules, they are
1133  * sorted based on the module order in the context.
1134  *
1135  * @param[in] sibling Node, whose siblings will be sorted.
1136  * @param[in] recursive Whether sort all siblings of siblings, recursively.
1137  * @return 0 on success, nonzero in case of an error.
1138  */
1139 int lyd_schema_sort(struct lyd_node *sibling, int recursive);
1140 
1141 /**
1142  * @brief Search in the given data for instances of nodes matching the provided path.
1143  *
1144  * Learn more about the path format on page @ref howtoxpath.
1145  *
1146  * @param[in] ctx_node Path context node.
1147  * @param[in] path Data path expression filtering the matching nodes.
1148  * @return Set of found data nodes. If no nodes are matching \p path or the result
1149  * would be a number, a string, or a boolean, the returned set is empty. In case of an error, NULL is returned.
1150  */
1151 struct ly_set *lyd_find_path(const struct lyd_node *ctx_node, const char *path);
1152 
1153 /**
1154  * @brief Search in the given data for instances of the provided schema node.
1155  *
1156  * The \p data is used to find the data root and function then searches in the whole tree and all sibling trees.
1157  *
1158  * @param[in] data A node in the data tree to search.
1159  * @param[in] schema Schema node of the data nodes caller want to find.
1160  * @return Set of found data nodes. If no data node is found, the returned set is empty.
1161  * In case of error, NULL is returned.
1162  */
1163 struct ly_set *lyd_find_instance(const struct lyd_node *data, const struct lys_node *schema);
1164 
1165 /**
1166  * @brief Search in the given siblings for the target instance. If cache is enabled and the siblings
1167  * are NOT top-level nodes, this function finds the node in a constant time!
1168  *
1169  * @param[in] siblings Siblings to search in including preceding and succeeding nodes.
1170  * @param[in] target Target node to find. Lists must have all the keys.
1171  * Invalid argument - key-less list or state (config false) leaf-list, use ::lyd_find_sibling_set instead.
1172  * @param[out] match Found data node, NULL if not found.
1173  * @return 0 on success (even on not found), -1 on error.
1174  */
1175 int lyd_find_sibling(const struct lyd_node *siblings, const struct lyd_node *target, struct lyd_node **match);
1176 
1177 /**
1178  * @brief Search in the given siblings for all target instances. If cache is enabled and the siblings
1179  * are NOT top-level nodes, this function finds the node(s) in a constant time!
1180  *
1181  * @param[in] siblings Siblings to search in including preceding and succeeding nodes.
1182  * @param[in] target Target node to find. Lists must have all the keys. Key-less lists are compared based on
1183  * all its descendants (both direct and indirect).
1184  * @param[out] set Found nodes in a set, can be empty.
1185  * @return 0 on success (even on no nodes found), -1 on error.
1186  * If an error occurs, NULL is returned.
1187  */
1188 int lyd_find_sibling_set(const struct lyd_node *siblings, const struct lyd_node *target, struct ly_set **set);
1189 
1190 /**
1191  * @brief Search in the given siblings for the schema instance. If cache is enabled and the siblings
1192  * are NOT top-level nodes, this function finds the node in a constant time!
1193  *
1194  * @param[in] siblings Siblings to search in including preceding and succeeding nodes.
1195  * @param[in] schema Schema node of the data node to find.
1196  * Invalid argument - key-less list or state (config false) leaf-list, use ::lyd_find_sibling_set instead.
1197  * @param[in] key_or_value Expected value depends on the type of \p schema:
1198  *              LYS_CONTAINER:
1199  *              LYS_LEAF:
1200  *              LYS_ANYXML:
1201  *              LYS_ANYDATA:
1202  *              LYS_NOTIF:
1203  *              LYS_RPC:
1204  *              LYS_ACTION:
1205  *                  NULL should be always set, will be ignored.
1206  *              LYS_LEAFLIST:
1207  *                  Searched instance value.
1208  *              LYS_LIST:
1209  *                  Searched instance all ordered key values in the form of "[key1='val1'][key2='val2']...",
1210  *                  while the key name may have optional prefixes their module names.
1211  * @param[out] match Found data node, NULL if not found.
1212  * @return 0 on success (even on not found), -1 on error.
1213  */
1214 int lyd_find_sibling_val(const struct lyd_node *siblings, const struct lys_node *schema, const char *key_or_value,
1215                          struct lyd_node **match);
1216 
1217 /**
1218  * @brief Get the first sibling of the given node.
1219  *
1220  * @param[in] node Node which first sibling is going to be the result.
1221  * @return The first sibling of the given node or the node itself if it is the first child of the parent.
1222  */
1223 struct lyd_node *lyd_first_sibling(struct lyd_node *node);
1224 
1225 /**
1226  * @brief Validate \p node data subtree.
1227  *
1228  * @param[in,out] node Data tree to be validated. In case the \p options includes #LYD_OPT_WHENAUTODEL, libyang
1229  *                     can modify the provided tree including the root \p node.
1230  * @param[in] options Options for the inserting data to the target data tree options, see @ref parseroptions.
1231  * @param[in] var_arg Variable argument depends on \p options. If they include:
1232  *                - #LYD_OPT_DATA:
1233  *                - #LYD_OPT_CONFIG:
1234  *                - #LYD_OPT_GET:
1235  *                - #LYD_OPT_GETCONFIG:
1236  *                - #LYD_OPT_EDIT:
1237  *                  - struct ly_ctx *ctx - context to use when \p node is NULL (for checking an empty tree),
1238  *                    otherwise can be NULL.
1239  *                - #LYD_OPT_RPC:
1240  *                - #LYD_OPT_RPCREPLY:
1241  *                - #LYD_OPT_NOTIF:
1242  *                  - struct ::lyd_node *data_tree - additional **validated** top-level siblings of a data tree that
1243  *                    will be used when checking any references ("when", "must" conditions, leafrefs, ...)
1244  *                    **in the operation subtree** that require some nodes outside their subtree.
1245  *                    It is assumed that **all parents** of the action/nested notification exist as required
1246  *                    ([RFC ref](https://tools.ietf.org/html/rfc8342#section-6.2)).
1247  * @param[in] ... Used only if options include #LYD_OPT_VAL_DIFF. In that case a (struct lyd_difflist **)
1248  *                is expected into which all data node changes performed by the validation will be stored.
1249  *                Needs to be properly freed. Meaning of diff type is following:
1250  *                   - LYD_DIFF_CREATED:
1251  *                      - first - Path identifying the parent node (format of lyd_path()).
1252  *                      - second - Duplicated subtree of the created nodes.
1253  *                   - LYD_DIFF_DELETED:
1254  *                      - first - Unlinked subtree of the deleted nodes.
1255  *                      - second - Path identifying the original parent (format of lyd_path()).
1256  * @return 0 on success, nonzero in case of an error.
1257  */
1258 int lyd_validate(struct lyd_node **node, int options, void *var_arg, ...);
1259 
1260 /**
1261  * @brief Validate \p node data tree but only subtrees that belong to the schema found in \p modules. All other
1262  *        schemas are effectively disabled for the validation.
1263  *
1264  * @param[in,out] node Data tree to be validated. In case the \p options includes #LYD_OPT_WHENAUTODEL, libyang
1265  *                     can modify the provided tree including the root \p node.
1266  * @param[in] modules List of module names to validate.
1267  * @param[in] mod_count Number of modules in \p modules.
1268  * @param[in] options Options for the inserting data to the target data tree options, see @ref parseroptions.
1269  *                    Accepted data type values include #LYD_OPT_DATA, #LYD_OPT_CONFIG, #LYD_OPT_GET,
1270  *                    #LYD_OPT_GETCONFIG, and #LYD_OPT_EDIT.
1271  * @param[in] ... Used only if options include #LYD_OPT_VAL_DIFF. In that case a (struct lyd_difflist **)
1272  *                is expected into which all data node changes performed by the validation will be stored.
1273  *                Needs to be properly freed. Meaning of diff type is following:
1274  *                   - LYD_DIFF_CREATED:
1275  *                      - first - Path identifying the parent node (format of lyd_path()).
1276  *                      - second - Duplicated subtree of the created nodes.
1277  *                   - LYD_DIFF_DELETED:
1278  *                      - first - Unlinked subtree of the deleted nodes.
1279  *                      - second - Path identifying the original parent (format of lyd_path()).
1280  * @return 0 on success, nonzero in case of an error.
1281  */
1282 int lyd_validate_modules(struct lyd_node **node, const struct lys_module **modules, int mod_count, int options, ...);
1283 
1284 /**
1285  * @brief Free special diff that was returned by lyd_validate() or lyd_validate_modules().
1286  *
1287  * @param[in] diff Diff to free.
1288  */
1289 void lyd_free_val_diff(struct lyd_difflist *diff);
1290 
1291 /**
1292  * @brief Check restrictions applicable to the particular leaf/leaf-list on the given string value.
1293  *
1294  * Validates the value only using the types' restrictions. Do not check the rest of restrictions dependent on the
1295  * data tree (must, when statements or uniqueness of the leaf-list item).
1296  *
1297  * The format of the data must follow rules for the lexical representation of the specific YANG type. Note
1298  * that if there are some extensions of the lexical representation for the YANG module (default value), they are
1299  * not supported by this function - it strictly follows rules for the lexical representations in data trees.
1300  *
1301  * @param[in] node Schema node of the leaf or leaf-list eventually holding the \p value.
1302  * @param[in] value Value to be checked (NULL is checked as empty string).
1303  * @return EXIT_SUCCESS if the \p value conforms to the restrictions, EXIT_FAILURE otherwise.
1304  */
1305 int lyd_validate_value(struct lys_node *node, const char *value);
1306 
1307 /**
1308  * @brief Check restrictions applicable to the particular leaf/leaf-list on the given string value and optionally
1309  * return its final type.
1310  *
1311  * Validates the value only using the types' restrictions. Do not check the rest of restrictions dependent on the
1312  * data tree (must, when statements or uniqueness of the leaf-list item).
1313  *
1314  * The format of the data must follow rules for the lexical representation of the specific YANG type. Note
1315  * that if there are some extensions of the lexical representation for the YANG module (default value), they are
1316  * not supported by this function - it strictly follows rules for the lexical representations in data trees.
1317  *
1318  * @param[in] node Schema node of the leaf or leaf-list eventually holding the \p value.
1319  * @param[in] value Value to be checked (NULL is checked as empty string).
1320  * @param[out] type Optional resolved value type, useful mainly for unions.
1321  * @return EXIT_SUCCESS if the \p value conforms to the restrictions, EXIT_FAILURE otherwise.
1322  */
1323 int lyd_value_type(struct lys_node *node, const char *value, struct lys_type **type);
1324 
1325 /**
1326  * @brief Get know if the node contain (despite implicit or explicit) default value.
1327  *
1328  * @param[in] node The leaf or leaf-list to check. Note, that leaf-list is marked as default only when the complete
1329  *                 and only the default set is present (node's siblings are also checked).
1330  * @return 1 if the node contains the default value, 0 otherwise.
1331  */
1332 int lyd_wd_default(struct lyd_node_leaf_list *node);
1333 
1334 /**
1335  * @brief Learn if a node is supposed to be printed based on the options.
1336  *
1337  * @param[in] node Data node to examine.
1338  * @param[in] options [printer flags](@ref printerflags). With-defaults flags and ::LYP_KEEPEMPTYCONT are relevant.
1339  * @return non-zero if should be printed, 0 if not.
1340  */
1341 int lyd_node_should_print(const struct lyd_node *node, int options);
1342 
1343 /**
1344  * @brief Unlink the specified data subtree. All referenced namespaces are copied.
1345  *
1346  * __PARTIAL CHANGE__ - validate after the final change on the data tree (see @ref howtodatamanipulators).
1347  *
1348  * Note, that the node's connection with the schema tree is kept. Therefore, in case of
1349  * reconnecting the node to a data tree using lyd_paste() it is necessary to paste it
1350  * to the appropriate place in the data tree following the schema.
1351  *
1352  * @param[in] node Data tree node to be unlinked (together with all children).
1353  * @return 0 for success, nonzero for error
1354  */
1355 int lyd_unlink(struct lyd_node *node);
1356 
1357 /**
1358  * @brief Free (and unlink) the specified data subtree. Use carefully, since libyang silently creates default nodes,
1359  * it is always better to use lyd_free_withsiblings() to free the complete data tree.
1360  *
1361  * __PARTIAL CHANGE__ - validate after the final change on the data tree (see @ref howtodatamanipulators).
1362  *
1363  * @param[in] node Root of the (sub)tree to be freed.
1364  */
1365 void lyd_free(struct lyd_node *node);
1366 
1367 /**
1368  * @brief Free (and unlink) the specified data tree and all its siblings (preceding as well as following).
1369  *
1370  * If used on a top-level node it means that the whole data tree is being freed and unnecessary operations
1371  * are skipped. Always use this function for freeing a whole data tree to achieve better performance.
1372  *
1373  * __PARTIAL CHANGE__ - validate after the final change on the data tree (see @ref howtodatamanipulators).
1374  *
1375  * @param[in] node One of the siblings root element of the (sub)trees to be freed.
1376  */
1377 void lyd_free_withsiblings(struct lyd_node *node);
1378 
1379 /**
1380  * @brief Insert attribute into the data node.
1381  *
1382  * @param[in] parent Data node where to place the attribute
1383  * @param[in] mod An alternative way to specify attribute's module (namespace) used in case the \p name does
1384  *            not include prefix. If neither prefix in the \p name nor mod is specified, the attribute's
1385  *            module is inherited from the \p parent node. It is not allowed to have attributes with no
1386  *            module (namespace).
1387  * @param[in] name Attribute name. The string can include the attribute's module (namespace) as the name's
1388  *            prefix (prefix:name). Prefix must be the name of one of the schema in the \p parent's context.
1389  *            If the prefix is not specified, the \p mod parameter is used. If neither of these parameters is
1390  *            usable, attribute inherits module (namespace) from the \p parent node. It is not allowed to
1391  *            have attributes with no module (namespace).
1392  * @param[in] value Attribute value
1393  * @return pointer to the created attribute (which is already connected in \p parent) or NULL on error.
1394  */
1395 struct lyd_attr *lyd_insert_attr(struct lyd_node *parent, const struct lys_module *mod, const char *name,
1396                                  const char *value);
1397 
1398 /**
1399  * @brief Destroy data attribute
1400  *
1401  * If the attribute to destroy is a member of a node attribute list, it is necessary to
1402  * provide the node itself as \p parent to keep the list consistent.
1403  *
1404  * @param[in] ctx Context where the attribute was created (usually it is the context of the \p parent)
1405  * @param[in] parent Parent node where the attribute is placed
1406  * @param[in] attr Attribute to destroy
1407  * @param[in] recursive Zero to destroy only the attribute, non-zero to destroy also all the subsequent attributes
1408  *            in the list.
1409  */
1410 void lyd_free_attr(struct ly_ctx *ctx, struct lyd_node *parent, struct lyd_attr *attr, int recursive);
1411 
1412 /**
1413  * @brief Return main module of the data tree node.
1414  *
1415  * In case of regular YANG module, it returns ::lys_node#module pointer,
1416  * but in case of submodule, it returns pointer to the main module.
1417  *
1418  * @param[in] node Data tree node to be examined
1419  * @return pointer to the main module (schema structure), NULL in case of error.
1420  */
1421 struct lys_module *lyd_node_module(const struct lyd_node *node);
1422 
1423 /**
1424  * @brief Get the type structure of a leaf.
1425  *
1426  * In case of a union, the correct specific type is found.
1427  * In case of a leafref, the final (if there is a chain of leafrefs) target's type is found.
1428  *
1429  * @param[in] leaf Leaf to examine.
1430  * @return Found type, NULL on error.
1431  */
1432 const struct lys_type *lyd_leaf_type(const struct lyd_node_leaf_list *leaf);
1433 
1434 /**
1435 * @brief Print data tree in the specified format.
1436 *
1437 * @param[out] strp Pointer to store the resulting dump.
1438 * @param[in] root Root node of the data tree to print. It can be actually any (not only real root)
1439 * node of the data tree to print the specific subtree.
1440 * @param[in] format Data output format.
1441 * @param[in] options [printer flags](@ref printerflags). \p format LYD_LYB accepts only #LYP_WITHSIBLINGS option.
1442 * @return 0 on success, 1 on failure (#ly_errno is set).
1443 */
1444 int lyd_print_mem(char **strp, const struct lyd_node *root, LYD_FORMAT format, int options);
1445 
1446 /**
1447  * @brief Print data tree in the specified format.
1448  *
1449  * @param[in] fd File descriptor where to print the data.
1450  * @param[in] root Root node of the data tree to print. It can be actually any (not only real root)
1451  * node of the data tree to print the specific subtree.
1452  * @param[in] format Data output format.
1453  * @param[in] options [printer flags](@ref printerflags). \p format LYD_LYB accepts only #LYP_WITHSIBLINGS option.
1454  * @return 0 on success, 1 on failure (#ly_errno is set).
1455  */
1456 int lyd_print_fd(int fd, const struct lyd_node *root, LYD_FORMAT format, int options);
1457 
1458 /**
1459  * @brief Print data tree in the specified format.
1460  *
1461  * @param[in] f File stream where to print the data.
1462  * @param[in] root Root node of the data tree to print. It can be actually any (not only real root)
1463  * node of the data tree to print the specific subtree.
1464  * @param[in] format Data output format.
1465  * @param[in] options [printer flags](@ref printerflags). \p format LYD_LYB accepts only #LYP_WITHSIBLINGS option.
1466  * @return 0 on success, 1 on failure (#ly_errno is set).
1467  */
1468 int lyd_print_file(FILE *f, const struct lyd_node *root, LYD_FORMAT format, int options);
1469 
1470 /**
1471  * @brief Print data tree in the specified format.
1472  *
1473  * @param[in] path File path where to print the data.
1474  * @param[in] root Root node of the data tree to print. It can be actually any (not only real root)
1475  * node of the data tree to print the specific subtree.
1476  * @param[in] format Data output format.
1477  * @param[in] options [printer flags](@ref printerflags). \p format LYD_LYB accepts only #LYP_WITHSIBLINGS option.
1478  * @return 0 on success, 1 on failure (#ly_errno is set).
1479  */
1480 int lyd_print_path(const char *path, const struct lyd_node *root, LYD_FORMAT format, int options);
1481 
1482 /**
1483  * @brief Print data tree in the specified format.
1484  *
1485  * @param[in] writeclb Callback function to write the data (see write(1)).
1486  * @param[in] root Root node of the data tree to print. It can be actually any (not only real root)
1487  * node of the data tree to print the specific subtree.
1488  * @param[in] arg Optional caller-specific argument to be passed to the \p writeclb callback.
1489  * @param[in] format Data output format.
1490  * @param[in] options [printer flags](@ref printerflags). \p format LYD_LYB accepts only #LYP_WITHSIBLINGS option.
1491  * @return 0 on success, 1 on failure (#ly_errno is set).
1492  */
1493 int lyd_print_clb(ssize_t (*writeclb)(void *arg, const void *buf, size_t count), void *arg,
1494                   const struct lyd_node *root, LYD_FORMAT format, int options);
1495 
1496 /**
1497  * @brief Get the double value of a decimal64 leaf/leaf-list.
1498  *
1499  * YANG decimal64 type enables higher precision numbers than IEEE 754 double-precision
1500  * format, so this conversion does not have to be lossless.
1501  *
1502  * @param[in] node Leaf/leaf-list of type decimal64.
1503  * @return Closest double equivalent to the decimal64 value.
1504  */
1505 double lyd_dec64_to_double(const struct lyd_node *node);
1506 
1507 /**
1508  * @brief Get the length of a printed LYB data tree.
1509  *
1510  * @param[in] data LYB data.
1511  * @return \p data length or -1 on error.
1512  */
1513 int lyd_lyb_data_length(const char *data);
1514 
1515 #ifdef LY_ENABLED_LYD_PRIV
1516 
1517 /**
1518  * @brief Set a schema private pointer to a user pointer.
1519  *
1520  * @param[in] node Data node, whose private field will be assigned.
1521  * @param[in] priv Arbitrary user-specified pointer.
1522  * @return Previous private object of the \p node (NULL if this is the first call on the \p node). Note, that
1523  * the caller is in this case responsible (if it is necessary) for freeing the replaced private object. In case
1524  * of invalid (NULL) \p node, NULL is returned and #ly_errno is set to #LY_EINVAL.
1525  */
1526 void *lyd_set_private(const struct lyd_node *node, void *priv);
1527 
1528 /**
1529  * @brief Get the data node based on a simple XPath.
1530  * This API returns the closest parent of the node (or the node itself)
1531  * identified by the nodeid (path). This API uses lyd_find_sibling() If cache is
1532  * enabled and the siblings are NOT top-level nodes, this function finds the
1533  * node in a constant time.
1534  * @param[in] data_tree Existing data tree to get.
1535  * @param[in] ctx Context to use.
1536  * @param[in] path Simple data path (see @ref howtoxpath).
1537  * @param[in] output possible values are 1 and 0.
1538  * when set to 1, changes the behavior to ignoring RPC/action input schema nodes and using only output ones.
1539  * @return NULL If no lyd_node exists for the given xpath.
1540  */
1541 struct lyd_node *lyd_find_path_hash_based(struct lyd_node *data_tree, const struct ly_ctx *ctx, const char *path,
1542                                           int output);
1543 
1544 #endif
1545 
1546 /**@} */
1547 
1548 #ifdef __cplusplus
1549 }
1550 #endif
1551 
1552 #endif /* LY_TREE_DATA_H_ */
1553