1 /**
2  * @file xpath.c
3  * @author Michal Vasko <mvasko@cesnet.cz>
4  * @brief YANG XPath evaluation functions
5  *
6  * Copyright (c) 2015 - 2017 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 #define _GNU_SOURCE
16 
17 /* needed by libmath functions isfinite(), isinf(), isnan(), signbit(), ... */
18 #define _ISOC99_SOURCE
19 
20 #include <ctype.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <stdint.h>
24 #include <string.h>
25 #include <assert.h>
26 #include <limits.h>
27 #include <errno.h>
28 #include <math.h>
29 #include <pcre.h>
30 
31 #include "xpath.h"
32 #include "libyang.h"
33 #include "xml_internal.h"
34 #include "tree_schema.h"
35 #include "tree_data.h"
36 #include "context.h"
37 #include "tree_internal.h"
38 #include "common.h"
39 #include "resolve.h"
40 #include "printer.h"
41 #include "parser.h"
42 #include "hash_table.h"
43 
44 static const struct lyd_node *moveto_get_root(const struct lyd_node *cur_node, int options,
45                                               enum lyxp_node_type *root_type);
46 static int reparse_or_expr(struct ly_ctx *ctx, struct lyxp_expr *exp, uint16_t *exp_idx);
47 static int set_snode_insert_node(struct lyxp_set *set, const struct lys_node *node, enum lyxp_node_type node_type);
48 static int eval_expr_select(struct lyxp_expr *exp, uint16_t *exp_idx, enum lyxp_expr_type etype, struct lyd_node *cur_node,
49                             struct lys_module *local_mod, struct lyxp_set *set, int options);
50 
51 void
lyxp_expr_free(struct lyxp_expr * expr)52 lyxp_expr_free(struct lyxp_expr *expr)
53 {
54     uint32_t i;
55 
56     if (!expr) {
57         return;
58     }
59 
60     free(expr->expr);
61     free(expr->tokens);
62     free(expr->expr_pos);
63     free(expr->tok_len);
64     if (expr->repeat) {
65         for (i = 0; i < expr->used; ++i) {
66             free(expr->repeat[i]);
67         }
68     }
69     free(expr->repeat);
70     free(expr);
71 }
72 
73 /**
74  * @brief Print the type of an XPath \p set.
75  *
76  * @param[in] set Set to use.
77  *
78  * @return Set type string.
79  */
80 static const char *
print_set_type(struct lyxp_set * set)81 print_set_type(struct lyxp_set *set)
82 {
83     switch (set->type) {
84     case LYXP_SET_EMPTY:
85         return "empty";
86     case LYXP_SET_NODE_SET:
87         return "node set";
88     case LYXP_SET_SNODE_SET:
89         return "schema node set";
90     case LYXP_SET_BOOLEAN:
91         return "boolean";
92     case LYXP_SET_NUMBER:
93         return "number";
94     case LYXP_SET_STRING:
95         return "string";
96     }
97 
98     return NULL;
99 }
100 
101 /**
102  * @brief Print an XPath token \p tok type.
103  *
104  * @param[in] tok Token to use.
105  *
106  * @return Token type string.
107  */
108 static const char *
print_token(enum lyxp_token tok)109 print_token(enum lyxp_token tok)
110 {
111     switch (tok) {
112     case LYXP_TOKEN_PAR1:
113         return "(";
114     case LYXP_TOKEN_PAR2:
115         return ")";
116     case LYXP_TOKEN_BRACK1:
117         return "[";
118     case LYXP_TOKEN_BRACK2:
119         return "]";
120     case LYXP_TOKEN_DOT:
121         return ".";
122     case LYXP_TOKEN_DDOT:
123         return "..";
124     case LYXP_TOKEN_AT:
125         return "@";
126     case LYXP_TOKEN_COMMA:
127         return ",";
128     case LYXP_TOKEN_NAMETEST:
129         return "NameTest";
130     case LYXP_TOKEN_NODETYPE:
131         return "NodeType";
132     case LYXP_TOKEN_FUNCNAME:
133         return "FunctionName";
134     case LYXP_TOKEN_OPERATOR_LOG:
135         return "Operator(Logic)";
136     case LYXP_TOKEN_OPERATOR_COMP:
137         return "Operator(Comparison)";
138     case LYXP_TOKEN_OPERATOR_MATH:
139         return "Operator(Math)";
140     case LYXP_TOKEN_OPERATOR_UNI:
141         return "Operator(Union)";
142     case LYXP_TOKEN_OPERATOR_PATH:
143         return "Operator(Path)";
144     case LYXP_TOKEN_LITERAL:
145         return "Literal";
146     case LYXP_TOKEN_NUMBER:
147         return "Number";
148     default:
149         LOGINT(NULL);
150         return "";
151     }
152 }
153 
154 #define DBG_BUFF_SIZE 8192
155 
156 static void
dbg_sprintf_append(char * buff,size_t buff_size,const char * fmt,...)157 dbg_sprintf_append(char *buff, size_t buff_size, const char *fmt, ...)
158 {
159     va_list argptr;
160     va_start(argptr,fmt);
161     size_t offset = strlen(buff);
162     vsnprintf(buff + offset, buff_size - offset - 1, fmt, argptr);
163 }
164 
165 /**
166  * @brief Print the whole expression \p exp to debug output.
167  *
168  * @param[in] exp Expression to use.
169  */
170 static void
print_expr_struct_debug(struct lyxp_expr * exp)171 print_expr_struct_debug(struct lyxp_expr *exp)
172 {
173     uint16_t i, j;
174     char tmp[DBG_BUFF_SIZE];
175     tmp[0] = 0;
176 
177     if (!exp || (ly_log_level < LY_LLDBG)) {
178         return;
179     }
180 
181     LOGDBG(LY_LDGXPATH, "expression \"%s\":", exp->expr);
182     for (i = 0; i < exp->used; ++i) {
183         dbg_sprintf_append(tmp, DBG_BUFF_SIZE, "\ttoken %s, in expression \"%.*s\"", print_token(exp->tokens[i]), exp->tok_len[i],
184                &exp->expr[exp->expr_pos[i]]);
185         if (exp->repeat[i]) {
186             dbg_sprintf_append(tmp, DBG_BUFF_SIZE, " (repeat %d", exp->repeat[i][0]);
187             for (j = 1; exp->repeat[i][j]; ++j) {
188                 dbg_sprintf_append(tmp, DBG_BUFF_SIZE, ", %d", exp->repeat[i][j]);
189             }
190             dbg_sprintf_append(tmp, DBG_BUFF_SIZE, ")");
191         }
192         LOGDBG(LY_LDGXPATH, tmp);
193     }
194 }
195 
196 #ifndef NDEBUG
197 
198 /**
199  * @brief Print XPath set content to debug output.
200  *
201  * @param[in] set Set to print.
202  */
203 static void
print_set_debug(struct lyxp_set * set)204 print_set_debug(struct lyxp_set *set)
205 {
206     uint32_t i;
207     char *str_num;
208     struct lyxp_set_node *item;
209     struct lyxp_set_snode *sitem;
210 
211     if (ly_log_level < LY_LLDBG) {
212         return;
213     }
214 
215     switch (set->type) {
216     case LYXP_SET_NODE_SET:
217         LOGDBG(LY_LDGXPATH, "set NODE SET:");
218         for (i = 0; i < set->used; ++i) {
219             item = &set->val.nodes[i];
220 
221             switch (item->type) {
222             case LYXP_NODE_ROOT:
223                 LOGDBG(LY_LDGXPATH, "\t%d (pos %u): ROOT", i + 1, item->pos);
224                 break;
225             case LYXP_NODE_ROOT_CONFIG:
226                 LOGDBG(LY_LDGXPATH, "\t%d (pos %u): ROOT CONFIG", i + 1, item->pos);
227                 break;
228             case LYXP_NODE_ELEM:
229                 if ((item->node->schema->nodetype == LYS_LIST)
230                         && (item->node->child->schema->nodetype == LYS_LEAF)) {
231                     LOGDBG(LY_LDGXPATH, "\t%d (pos %u): ELEM %s (1st child val: %s)", i + 1, item->pos,
232                            item->node->schema->name,
233                            ((struct lyd_node_leaf_list *)item->node->child)->value_str);
234                 } else if (item->node->schema->nodetype == LYS_LEAFLIST) {
235                     LOGDBG(LY_LDGXPATH, "\t%d (pos %u): ELEM %s (val: %s)", i + 1, item->pos,
236                            item->node->schema->name,
237                            ((struct lyd_node_leaf_list *)item->node)->value_str);
238                 } else {
239                     LOGDBG(LY_LDGXPATH, "\t%d (pos %u): ELEM %s", i + 1, item->pos, item->node->schema->name);
240                 }
241                 break;
242             case LYXP_NODE_TEXT:
243                 if (item->node->schema->nodetype & LYS_ANYDATA) {
244                     LOGDBG(LY_LDGXPATH, "\t%d (pos %u): TEXT <%s>", i + 1, item->pos,
245                            item->node->schema->nodetype == LYS_ANYXML ? "anyxml" : "anydata");
246                 } else {
247                     LOGDBG(LY_LDGXPATH, "\t%d (pos %u): TEXT %s", i + 1, item->pos,
248                            ((struct lyd_node_leaf_list *)item->node)->value_str);
249                 }
250                 break;
251             case LYXP_NODE_ATTR:
252                 LOGDBG(LY_LDGXPATH, "\t%d (pos %u): ATTR %s = %s", i + 1, item->pos, set->val.attrs[i].attr->name,
253                        set->val.attrs[i].attr->value);
254                 break;
255             default:
256                 LOGINT(NULL);
257                 break;
258             }
259         }
260         break;
261 
262     case LYXP_SET_SNODE_SET:
263         LOGDBG(LY_LDGXPATH, "set SNODE SET:");
264         for (i = 0; i < set->used; ++i) {
265             sitem = &set->val.snodes[i];
266 
267             switch (sitem->type) {
268             case LYXP_NODE_ROOT:
269                 LOGDBG(LY_LDGXPATH, "\t%d (%u): ROOT", i + 1, sitem->in_ctx);
270                 break;
271             case LYXP_NODE_ROOT_CONFIG:
272                 LOGDBG(LY_LDGXPATH, "\t%d (%u): ROOT CONFIG", i + 1, sitem->in_ctx);
273                 break;
274             case LYXP_NODE_ELEM:
275                 LOGDBG(LY_LDGXPATH, "\t%d (%u): ELEM %s", i + 1, sitem->in_ctx, sitem->snode->name);
276                 break;
277             default:
278                 LOGINT(NULL);
279                 break;
280             }
281         }
282         break;
283 
284     case LYXP_SET_EMPTY:
285         LOGDBG(LY_LDGXPATH, "set EMPTY");
286         break;
287 
288     case LYXP_SET_BOOLEAN:
289         LOGDBG(LY_LDGXPATH, "set BOOLEAN");
290         LOGDBG(LY_LDGXPATH, "\t%s", (set->val.bool ? "true" : "false"));
291         break;
292 
293     case LYXP_SET_STRING:
294         LOGDBG(LY_LDGXPATH, "set STRING");
295         LOGDBG(LY_LDGXPATH, "\t%s", set->val.str);
296         break;
297 
298     case LYXP_SET_NUMBER:
299         LOGDBG(LY_LDGXPATH, "set NUMBER");
300 
301         if (isnan(set->val.num)) {
302             str_num = strdup("NaN");
303         } else if ((set->val.num == 0) || (set->val.num == -0.0f)) {
304             str_num = strdup("0");
305         } else if (isinf(set->val.num) && !signbit(set->val.num)) {
306             str_num = strdup("Infinity");
307         } else if (isinf(set->val.num) && signbit(set->val.num)) {
308             str_num = strdup("-Infinity");
309         } else if ((long long)set->val.num == set->val.num) {
310             if (asprintf(&str_num, "%lld", (long long)set->val.num) == -1) {
311                 str_num = NULL;
312             }
313         } else {
314             if (asprintf(&str_num, "%03.1Lf", set->val.num) == -1) {
315                 str_num = NULL;
316             }
317         }
318         LY_CHECK_ERR_RETURN(!str_num, LOGMEM(NULL), );
319 
320         LOGDBG(LY_LDGXPATH, "\t%s", str_num);
321         free(str_num);
322     }
323 }
324 
325 #endif
326 
327 /**
328  * @brief Realloc the string \p str.
329  *
330  * @param[in] needed How much free space is required.
331  * @param[in,out] str Pointer to the string to use.
332  * @param[in,out] used Used bytes in \p str.
333  * @param[in,out] size Allocated bytes in \p str.
334  *
335  * @return 0 on success, non-zero on error
336  */
337 static int
cast_string_realloc(struct ly_ctx * ctx,uint16_t needed,char ** str,uint16_t * used,uint16_t * size)338 cast_string_realloc(struct ly_ctx *ctx, uint16_t needed, char **str, uint16_t *used, uint16_t *size)
339 {
340     if (*size - *used < needed) {
341         do {
342             if ((UINT16_MAX - *size) < LYXP_STRING_CAST_SIZE_STEP) {
343                 LOGERR(ctx, LY_EINVAL, "XPath string length limit (%u) reached.", UINT16_MAX);
344                 return -1;
345             }
346             *size += LYXP_STRING_CAST_SIZE_STEP;
347         } while (*size - *used < needed);
348         *str = ly_realloc(*str, *size * sizeof(char));
349         LY_CHECK_ERR_RETURN(!(*str), LOGMEM(ctx), -1);
350     }
351 
352     return 0;
353 }
354 
355 /**
356  * @brief Cast nodes recursively to one string \p str.
357  *
358  * @param[in] node Node to cast.
359  * @param[in] fake_cont Whether to put the data into a "fake" container.
360  * @param[in] root_type Type of the XPath root.
361  * @param[in] indent Current indent.
362  * @param[in,out] str Resulting string.
363  * @param[in,out] used Used bytes in \p str.
364  * @param[in,out] size Allocated bytes in \p str.
365  */
366 static int
cast_string_recursive(struct lyd_node * node,struct lys_module * local_mod,int fake_cont,enum lyxp_node_type root_type,uint16_t indent,char ** str,uint16_t * used,uint16_t * size)367 cast_string_recursive(struct lyd_node *node, struct lys_module *local_mod, int fake_cont, enum lyxp_node_type root_type,
368                       uint16_t indent, char **str, uint16_t *used, uint16_t *size)
369 {
370     char *buf, *line, *ptr = NULL;
371     const char *value_str;
372     struct lyd_node *child;
373     struct lyd_node_anydata *any;
374 
375     if ((root_type == LYXP_NODE_ROOT_CONFIG) && (node->schema->flags & LYS_CONFIG_R)) {
376         return 0;
377     }
378 
379     if (fake_cont) {
380         if (cast_string_realloc(local_mod->ctx, 1, str, used, size)) {
381             return -1;
382         }
383         strcpy(*str + (*used - 1), "\n");
384         ++(*used);
385 
386         ++indent;
387     }
388 
389     switch (node->schema->nodetype) {
390     case LYS_CONTAINER:
391     case LYS_LIST:
392     case LYS_RPC:
393     case LYS_NOTIF:
394         if (cast_string_realloc(local_mod->ctx, 1, str, used, size)) {
395             return -1;
396         }
397         strcpy(*str + (*used - 1), "\n");
398         ++(*used);
399 
400         LY_TREE_FOR(node->child, child) {
401             if (cast_string_recursive(child, local_mod, 0, root_type, indent + 1, str, used, size)) {
402                 return -1;
403             }
404         }
405 
406         break;
407 
408     case LYS_LEAF:
409     case LYS_LEAFLIST:
410         value_str = ((struct lyd_node_leaf_list *)node)->value_str;
411         if (!value_str) {
412             value_str = "";
413         }
414 
415         /* print indent */
416         if (cast_string_realloc(local_mod->ctx, indent * 2 + strlen(value_str) + 1, str, used, size)) {
417             return -1;
418         }
419         memset(*str + (*used - 1), ' ', indent * 2);
420         *used += indent * 2;
421 
422         /* print value */
423         if (*used == 1) {
424             sprintf(*str + (*used - 1), "%s", value_str);
425             *used += strlen(value_str);
426         } else {
427             sprintf(*str + (*used - 1), "%s\n", value_str);
428             *used += strlen(value_str) + 1;
429         }
430 
431         break;
432 
433     case LYS_ANYXML:
434     case LYS_ANYDATA:
435         any = (struct lyd_node_anydata *)node;
436         if (!(void*)any->value.tree) {
437             /* no content */
438             buf = strdup("");
439             LY_CHECK_ERR_RETURN(!buf, LOGMEM(local_mod->ctx), -1);
440         } else {
441             switch (any->value_type) {
442             case LYD_ANYDATA_CONSTSTRING:
443             case LYD_ANYDATA_SXML:
444             case LYD_ANYDATA_JSON:
445                 buf = strdup(any->value.str);
446                 LY_CHECK_ERR_RETURN(!buf, LOGMEM(local_mod->ctx), -1);
447                 break;
448             case LYD_ANYDATA_DATATREE:
449                 if (lyd_print_mem(&buf, any->value.tree, LYD_XML, LYP_WITHSIBLINGS)) {
450                     return -1;
451                 }
452                 break;
453             case LYD_ANYDATA_XML:
454                 if (!lyxml_print_mem(&buf, any->value.xml, LYXML_PRINT_SIBLINGS)) {
455                     return -1;
456                 }
457                 break;
458             case LYD_ANYDATA_LYB:
459                 LOGERR(local_mod->ctx, LY_EINVAL, "Cannot convert LYB anydata into string.");
460                 return -1;
461             case LYD_ANYDATA_STRING:
462             case LYD_ANYDATA_SXMLD:
463             case LYD_ANYDATA_JSOND:
464             case LYD_ANYDATA_LYBD:
465                 /* dynamic strings are used only as input parameters */
466                 LOGINT(local_mod->ctx);
467                 return -1;
468             }
469         }
470 
471         line = strtok_r(buf, "\n", &ptr);
472         do {
473             if (cast_string_realloc(local_mod->ctx, indent * 2 + strlen(line) + 1, str, used, size)) {
474                 free(buf);
475                 return -1;
476             }
477             memset(*str + (*used - 1), ' ', indent * 2);
478             *used += indent * 2;
479 
480             strcpy(*str + (*used - 1), line);
481             *used += strlen(line);
482 
483             strcpy(*str + (*used - 1), "\n");
484             *used += 1;
485         } while ((line = strtok_r(NULL, "\n", &ptr)));
486 
487         free(buf);
488         break;
489 
490     default:
491         LOGINT(local_mod->ctx);
492         return -1;
493     }
494 
495     if (fake_cont) {
496         if (cast_string_realloc(local_mod->ctx, 1, str, used, size)) {
497             return -1;
498         }
499         strcpy(*str + (*used - 1), "\n");
500         ++(*used);
501 
502         --indent;
503     }
504 
505     return 0;
506 }
507 
508 /**
509  * @brief Cast an element into a string.
510  *
511  * @param[in] node Node to cast.
512  * @param[in] fake_cont Whether to put the data into a "fake" container.
513  * @param[in] root_type Type of the XPath root.
514  *
515  * @return Element cast to dynamically-allocated string.
516  */
517 static char *
cast_string_elem(struct lyd_node * node,struct lys_module * local_mod,int fake_cont,enum lyxp_node_type root_type)518 cast_string_elem(struct lyd_node *node, struct lys_module *local_mod, int fake_cont, enum lyxp_node_type root_type)
519 {
520     char *str;
521     uint16_t used, size;
522 
523     str = malloc(LYXP_STRING_CAST_SIZE_START * sizeof(char));
524     LY_CHECK_ERR_RETURN(!str, LOGMEM(local_mod->ctx), NULL);
525     str[0] = '\0';
526     used = 1;
527     size = LYXP_STRING_CAST_SIZE_START;
528 
529     if (cast_string_recursive(node, local_mod, fake_cont, root_type, 0, &str, &used, &size)) {
530         free(str);
531         return NULL;
532     }
533 
534     if (size > used) {
535         str = ly_realloc(str, used * sizeof(char));
536         LY_CHECK_ERR_RETURN(!str, free(str); LOGMEM(local_mod->ctx), NULL);
537     }
538     return str;
539 }
540 
541 /**
542  * @brief Cast a LYXP_SET_NODE_SET set into a string.
543  *        Context position aware.
544  *
545  * @param[in] set Set to cast.
546  * @param[in] cur_node Original context node.
547  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
548  *
549  * @return Cast string in the dictionary.
550  */
551 static char *
cast_node_set_to_string(struct lyxp_set * set,struct lyd_node * cur_node,struct lys_module * local_mod,int options)552 cast_node_set_to_string(struct lyxp_set *set, struct lyd_node *cur_node, struct lys_module *local_mod, int options)
553 {
554     enum lyxp_node_type root_type;
555     char *str;
556 
557     if ((set->val.nodes[0].type != LYXP_NODE_ATTR) && (set->val.nodes[0].node->validity & LYD_VAL_INUSE)) {
558         LOGVAL(local_mod->ctx, LYE_XPATH_DUMMY, LY_VLOG_LYD, set->val.nodes[0].node, set->val.nodes[0].node->schema->name);
559         return NULL;
560     }
561 
562     moveto_get_root(cur_node, options, &root_type);
563 
564     switch (set->val.nodes[0].type) {
565     case LYXP_NODE_ROOT:
566     case LYXP_NODE_ROOT_CONFIG:
567         return cast_string_elem(set->val.nodes[0].node, local_mod, 1, root_type);
568     case LYXP_NODE_ELEM:
569     case LYXP_NODE_TEXT:
570         return cast_string_elem(set->val.nodes[0].node, local_mod, 0, root_type);
571     case LYXP_NODE_ATTR:
572         str = strdup(set->val.attrs[0].attr->value_str);
573         if (!str) {
574             LOGMEM(local_mod->ctx);
575         }
576         return str;
577     default:
578         break;
579     }
580 
581     LOGINT(local_mod->ctx);
582     return NULL;
583 }
584 
585 /**
586  * @brief Cast a string into an XPath number.
587  *
588  * @param[in] str String to use.
589  *
590  * @return Cast number.
591  */
592 static long double
cast_string_to_number(const char * str)593 cast_string_to_number(const char *str)
594 {
595     long double num;
596     char *ptr;
597 
598     errno = 0;
599     num = strtold(str, &ptr);
600     if (errno || *ptr) {
601         num = NAN;
602     }
603     return num;
604 }
605 
606 /*
607  * lyxp_set manipulation functions
608  */
609 
610 #ifdef LY_ENABLED_CACHE
611 
612 static int
set_values_equal_cb(void * val1_p,void * val2_p,int UNUSED (mod),void * UNUSED (cb_data))613 set_values_equal_cb(void *val1_p, void *val2_p, int UNUSED(mod), void *UNUSED(cb_data))
614 {
615     struct lyxp_set_hash_node *val1, *val2;
616 
617     val1 = (struct lyxp_set_hash_node *)val1_p;
618     val2 = (struct lyxp_set_hash_node *)val2_p;
619 
620     if ((val1->node == val2->node) && (val1->type == val2->type)) {
621         return 1;
622     }
623 
624     return 0;
625 }
626 
627 static void
set_insert_node_hash(struct lyxp_set * set,struct lyd_node * node,enum lyxp_node_type type)628 set_insert_node_hash(struct lyxp_set *set, struct lyd_node *node, enum lyxp_node_type type)
629 {
630     int r;
631     uint32_t i, hash;
632     struct lyxp_set_hash_node hnode;
633 
634     if (!set->ht && (set->used >= LY_CACHE_HT_MIN_CHILDREN)) {
635         /* create hash table and add all the nodes */
636         set->ht = lyht_new(1, sizeof(struct lyxp_set_hash_node), set_values_equal_cb, NULL, 1);
637         for (i = 0; i < set->used; ++i) {
638             hnode.node = set->val.nodes[i].node;
639             hnode.type = set->val.nodes[i].type;
640 
641             hash = dict_hash_multi(0, (const char *)&hnode.node, sizeof hnode.node);
642             hash = dict_hash_multi(hash, (const char *)&hnode.type, sizeof hnode.type);
643             hash = dict_hash_multi(hash, NULL, 0);
644 
645             r = lyht_insert(set->ht, &hnode, hash, NULL);
646             assert(!r);
647             (void)r;
648 
649             if (hnode.node == node) {
650                 /* it was just added, do not add it twice */
651                 node = NULL;
652             }
653         }
654     }
655 
656     if (set->ht && node) {
657         /* add the new node into hash table */
658         hnode.node = node;
659         hnode.type = type;
660 
661         hash = dict_hash_multi(0, (const char *)&hnode.node, sizeof hnode.node);
662         hash = dict_hash_multi(hash, (const char *)&hnode.type, sizeof hnode.type);
663         hash = dict_hash_multi(hash, NULL, 0);
664 
665         r = lyht_insert(set->ht, &hnode, hash, NULL);
666         assert(!r);
667         (void)r;
668     }
669 }
670 
671 static void
set_remove_node_hash(struct lyxp_set * set,struct lyd_node * node,enum lyxp_node_type type)672 set_remove_node_hash(struct lyxp_set *set, struct lyd_node *node, enum lyxp_node_type type)
673 {
674     int r;
675     struct lyxp_set_hash_node hnode;
676     uint32_t hash;
677 
678     if (set->ht) {
679         hnode.node = node;
680         hnode.type = type;
681 
682         hash = dict_hash_multi(0, (const char *)&hnode.node, sizeof hnode.node);
683         hash = dict_hash_multi(hash, (const char *)&hnode.type, sizeof hnode.type);
684         hash = dict_hash_multi(hash, NULL, 0);
685 
686         r = lyht_remove(set->ht, &hnode, hash);
687         assert(!r);
688         (void)r;
689 
690         if (!set->ht->used) {
691             lyht_free(set->ht);
692             set->ht = NULL;
693         }
694     }
695 }
696 
697 static int
set_dup_node_hash_check(const struct lyxp_set * set,struct lyd_node * node,enum lyxp_node_type type,int skip_idx)698 set_dup_node_hash_check(const struct lyxp_set *set, struct lyd_node *node, enum lyxp_node_type type, int skip_idx)
699 {
700     struct lyxp_set_hash_node hnode, *match_p;
701     uint32_t hash;
702 
703     hnode.node = node;
704     hnode.type = type;
705 
706     hash = dict_hash_multi(0, (const char *)&hnode.node, sizeof hnode.node);
707     hash = dict_hash_multi(hash, (const char *)&hnode.type, sizeof hnode.type);
708     hash = dict_hash_multi(hash, NULL, 0);
709 
710     if (!lyht_find(set->ht, &hnode, hash, (void **)&match_p)) {
711         if ((skip_idx > -1) && (set->val.nodes[skip_idx].node == match_p->node) && (set->val.nodes[skip_idx].type == match_p->type)) {
712             /* we found it on the index that should be skipped, find another */
713             hnode = *match_p;
714             if (lyht_find_next(set->ht, &hnode, hash, (void **)&match_p)) {
715                 /* none other found */
716                 return 0;
717             }
718         }
719 
720         return 1;
721     }
722 
723     /* not found */
724     return 0;
725 }
726 
727 #endif
728 
729 static void
set_free_content(struct lyxp_set * set)730 set_free_content(struct lyxp_set *set)
731 {
732     if (!set) {
733         return;
734     }
735 
736     if (set->type == LYXP_SET_NODE_SET) {
737         free(set->val.nodes);
738 #ifdef LY_ENABLED_CACHE
739         lyht_free(set->ht);
740         set->ht = NULL;
741 #endif
742     } else if (set->type == LYXP_SET_SNODE_SET) {
743         free(set->val.snodes);
744     } else if (set->type == LYXP_SET_STRING) {
745         free(set->val.str);
746     }
747     set->type = LYXP_SET_EMPTY;
748 }
749 
750 void
lyxp_set_free(struct lyxp_set * set)751 lyxp_set_free(struct lyxp_set *set)
752 {
753     if (!set) {
754         return;
755     }
756 
757     set_free_content(set);
758     free(set);
759 }
760 
761 /**
762  * @brief Create a deep copy of a \p set.
763  *
764  * @param[in] set Set to copy.
765  *
766  * @return Copy of \p set.
767  */
768 static struct lyxp_set *
set_copy(struct lyxp_set * set)769 set_copy(struct lyxp_set *set)
770 {
771     struct lyxp_set *ret;
772     uint32_t i;
773 
774     if (!set) {
775         return NULL;
776     }
777 
778     ret = malloc(sizeof *ret);
779     LY_CHECK_ERR_RETURN(!ret, LOGMEM(NULL), NULL);
780 
781     if (set->type == LYXP_SET_SNODE_SET) {
782         memset(ret, 0, sizeof *ret);
783         ret->type = set->type;
784 
785         for (i = 0; i < set->used; ++i) {
786             if (set->val.snodes[i].in_ctx == 1) {
787                 if (set_snode_insert_node(ret, set->val.snodes[i].snode, set->val.snodes[i].type)) {
788                     lyxp_set_free(ret);
789                     return NULL;
790                 }
791             }
792         }
793     } else if (set->type == LYXP_SET_NODE_SET) {
794         ret->type = set->type;
795         ret->val.nodes = malloc(set->used * sizeof *ret->val.nodes);
796         LY_CHECK_ERR_RETURN(!ret->val.nodes, LOGMEM(NULL); free(ret), NULL);
797         memcpy(ret->val.nodes, set->val.nodes, set->used * sizeof *ret->val.nodes);
798 
799         ret->used = ret->size = set->used;
800         ret->ctx_pos = set->ctx_pos;
801         ret->ctx_size = set->ctx_size;
802 
803 #ifdef LY_ENABLED_CACHE
804         ret->ht = lyht_dup(set->ht);
805 #endif
806     } else {
807        memcpy(ret, set, sizeof *ret);
808        if (set->type == LYXP_SET_STRING) {
809            ret->val.str = strdup(set->val.str);
810            LY_CHECK_ERR_RETURN(!ret->val.str, LOGMEM(NULL); free(ret), NULL);
811        }
812     }
813 
814     return ret;
815 }
816 
817 /**
818  * @brief Fill XPath set with a string. Any current data are disposed of.
819  *
820  * @param[in] set Set to fill.
821  * @param[in] string String to fill into \p set.
822  * @param[in] str_len Length of \p string. 0 is a valid value!
823  * @param[in] ctx libyang context to use.
824  */
825 static void
set_fill_string(struct lyxp_set * set,const char * string,uint16_t str_len)826 set_fill_string(struct lyxp_set *set, const char *string, uint16_t str_len)
827 {
828     set_free_content(set);
829 
830     set->type = LYXP_SET_STRING;
831     if ((str_len == 0) && (string[0] != '\0')) {
832         string = "";
833     }
834     set->val.str = strndup(string, str_len);
835 }
836 
837 /**
838  * @brief Fill XPath set with a number. Any current data are disposed of.
839  *
840  * @param[in] set Set to fill.
841  * @param[in] number Number to fill into \p set.
842  */
843 static void
set_fill_number(struct lyxp_set * set,long double number)844 set_fill_number(struct lyxp_set *set, long double number)
845 {
846     set_free_content(set);
847 
848     set->type = LYXP_SET_NUMBER;
849     set->val.num = number;
850 }
851 
852 /**
853  * @brief Fill XPath set with a boolean. Any current data are disposed of.
854  *
855  * @param[in] set Set to fill.
856  * @param[in] boolean Boolean to fill into \p set.
857  */
858 static void
set_fill_boolean(struct lyxp_set * set,int boolean)859 set_fill_boolean(struct lyxp_set *set, int boolean)
860 {
861     set_free_content(set);
862 
863     set->type = LYXP_SET_BOOLEAN;
864     set->val.bool = boolean;
865 }
866 
867 /**
868  * @brief Fill XPath set with the value from another set (deep assign).
869  *        Any current data are disposed of.
870  *
871  * @param[in] trg Set to fill.
872  * @param[in] src Source set to copy into \p trg.
873  */
874 static void
set_fill_set(struct lyxp_set * trg,struct lyxp_set * src)875 set_fill_set(struct lyxp_set *trg, struct lyxp_set *src)
876 {
877     if (!trg || !src) {
878         return;
879     }
880 
881     if (src->type == LYXP_SET_SNODE_SET) {
882         trg->type = LYXP_SET_SNODE_SET;
883         trg->used = src->used;
884         trg->size = src->used;
885 
886         trg->val.snodes = ly_realloc(trg->val.snodes, trg->size * sizeof *trg->val.nodes);
887         LY_CHECK_ERR_RETURN(!trg->val.nodes, LOGMEM(NULL); memset(trg, 0, sizeof *trg), );
888         memcpy(trg->val.nodes, src->val.nodes, src->used * sizeof *src->val.nodes);
889     } else if (src->type == LYXP_SET_BOOLEAN) {
890         set_fill_boolean(trg, src->val.bool);
891     } else if (src->type ==  LYXP_SET_NUMBER) {
892         set_fill_number(trg, src->val.num);
893     } else if (src->type == LYXP_SET_STRING) {
894         set_fill_string(trg, src->val.str, strlen(src->val.str));
895     } else {
896         if (trg->type == LYXP_SET_NODE_SET) {
897             free(trg->val.nodes);
898         } else if (trg->type == LYXP_SET_STRING) {
899             free(trg->val.str);
900         }
901 
902         if (src->type == LYXP_SET_EMPTY) {
903             trg->type = LYXP_SET_EMPTY;
904         } else {
905             assert(src->type == LYXP_SET_NODE_SET);
906 
907             trg->type = LYXP_SET_NODE_SET;
908             trg->used = src->used;
909             trg->size = src->used;
910             trg->ctx_pos = src->ctx_pos;
911             trg->ctx_size = src->ctx_size;
912 
913             trg->val.nodes = malloc(trg->used * sizeof *trg->val.nodes);
914             LY_CHECK_ERR_RETURN(!trg->val.nodes, LOGMEM(NULL); memset(trg, 0, sizeof *trg), );
915             memcpy(trg->val.nodes, src->val.nodes, src->used * sizeof *src->val.nodes);
916 #ifdef LY_ENABLED_CACHE
917             trg->ht = lyht_dup(src->ht);
918 #endif
919         }
920     }
921 
922 
923 }
924 
925 static void
set_snode_clear_ctx(struct lyxp_set * set)926 set_snode_clear_ctx(struct lyxp_set *set)
927 {
928     uint32_t i;
929 
930     for (i = 0; i < set->used; ++i) {
931         if (set->val.snodes[i].in_ctx == 1) {
932             set->val.snodes[i].in_ctx = 0;
933         }
934     }
935 }
936 
937 /**
938  * @brief Remove a node from a set. Removing last node changes
939  *        \p set into LYXP_SET_EMPTY. Context position aware.
940  *
941  * @param[in] set Set to use.
942  * @param[in] idx Index from \p set of the node to be removed.
943  */
944 static void
set_remove_node(struct lyxp_set * set,uint32_t idx)945 set_remove_node(struct lyxp_set *set, uint32_t idx)
946 {
947     assert(set && (set->type == LYXP_SET_NODE_SET));
948     assert(idx < set->used);
949 
950 #ifdef LY_ENABLED_CACHE
951     set_remove_node_hash(set, set->val.nodes[idx].node, set->val.nodes[idx].type);
952 #endif
953 
954     --set->used;
955     if (set->used) {
956         memmove(&set->val.nodes[idx], &set->val.nodes[idx + 1],
957                 (set->used - idx) * sizeof *set->val.nodes);
958     } else {
959         set_free_content(set);
960         /* this changes it to LYXP_SET_EMPTY */
961         memset(set, 0, sizeof *set);
962     }
963 }
964 
965 /**
966  * @brief Remove all none node types from a set. Removing last node changes
967  *        \p set into LYXP_SET_EMPTY. Hashes are expected to be already removed. Context position aware.
968  *
969  * @param[in] set Set to use.
970  * @param[in] idx Index from \p set of the node to be removed.
971  */
972 static void
set_remove_none_nodes(struct lyxp_set * set)973 set_remove_none_nodes(struct lyxp_set *set)
974 {
975     uint32_t i, orig_used, end = 0;
976     int32_t start;
977 
978     assert(set && (set->type == LYXP_SET_NODE_SET));
979 
980     orig_used = set->used;
981     set->used = 0;
982     for (i = 0; i < orig_used;) {
983         start = -1;
984         do {
985             if ((set->val.nodes[i].type != LYXP_NODE_NONE) && (start == -1)) {
986                 start = i;
987             } else if ((start > -1) && (set->val.nodes[i].type == LYXP_NODE_NONE)) {
988                 end = i;
989                 ++i;
990                 break;
991             }
992 
993             ++i;
994             if (i == orig_used) {
995                 end = i;
996             }
997         } while (i < orig_used);
998 
999         if (start > -1) {
1000             if (set->used != (unsigned)start) {
1001                 memmove(&set->val.nodes[set->used], &set->val.nodes[start], (end - start) * sizeof *set->val.nodes);
1002             }
1003             set->used += end - start;
1004         }
1005     }
1006 
1007     if (!set->used) {
1008         set_free_content(set);
1009         /* this changes it to LYXP_SET_EMPTY */
1010         memset(set, 0, sizeof *set);
1011     }
1012 }
1013 
1014 /**
1015  * @brief Check for duplicates in a node set.
1016  *
1017  * @param[in] set Set to check.
1018  * @param[in] node Node to look for in \p set.
1019  * @param[in] node_type Type of \p node.
1020  * @param[in] skip_idx Index from \p set to skip.
1021  *
1022  * @return 0 on success, 1 on duplicate found.
1023  */
1024 static int
set_dup_node_check(const struct lyxp_set * set,const struct lyd_node * node,enum lyxp_node_type node_type,int skip_idx)1025 set_dup_node_check(const struct lyxp_set *set, const struct lyd_node *node, enum lyxp_node_type node_type, int skip_idx)
1026 {
1027     uint32_t i;
1028 
1029 #ifdef LY_ENABLED_CACHE
1030     if (set->ht) {
1031         return set_dup_node_hash_check(set, (struct lyd_node *)node, node_type, skip_idx);
1032     }
1033 #endif
1034 
1035     for (i = 0; i < set->used; ++i) {
1036         if ((skip_idx > -1) && (i == (unsigned)skip_idx)) {
1037             continue;
1038         }
1039 
1040         if ((set->val.nodes[i].node == node) && (set->val.nodes[i].type == node_type)) {
1041             return 1;
1042         }
1043     }
1044 
1045     return 0;
1046 }
1047 
1048 static int
set_snode_dup_node_check(struct lyxp_set * set,const struct lys_node * node,enum lyxp_node_type node_type,int skip_idx)1049 set_snode_dup_node_check(struct lyxp_set *set, const struct lys_node *node, enum lyxp_node_type node_type, int skip_idx)
1050 {
1051     uint32_t i;
1052 
1053     for (i = 0; i < set->used; ++i) {
1054         if ((skip_idx > -1) && (i == (unsigned)skip_idx)) {
1055             continue;
1056         }
1057 
1058         if ((set->val.snodes[i].snode == node) && (set->val.snodes[i].type == node_type)) {
1059             return i;
1060         }
1061     }
1062 
1063     return -1;
1064 }
1065 
1066 static void
set_snode_merge(struct lyxp_set * set1,struct lyxp_set * set2)1067 set_snode_merge(struct lyxp_set *set1, struct lyxp_set *set2)
1068 {
1069     uint32_t orig_used, i, j;
1070 
1071     assert(((set1->type == LYXP_SET_SNODE_SET) || (set1->type == LYXP_SET_EMPTY))
1072         && ((set2->type == LYXP_SET_SNODE_SET) || (set2->type == LYXP_SET_EMPTY)));
1073 
1074     if (set2->type == LYXP_SET_EMPTY) {
1075         return;
1076     }
1077 
1078     if (set1->type == LYXP_SET_EMPTY) {
1079         memcpy(set1, set2, sizeof *set1);
1080         return;
1081     }
1082 
1083     if (set1->used + set2->used > set1->size) {
1084         set1->size = set1->used + set2->used;
1085         set1->val.snodes = ly_realloc(set1->val.snodes, set1->size * sizeof *set1->val.snodes);
1086         LY_CHECK_ERR_RETURN(!set1->val.snodes, LOGMEM(NULL), );
1087     }
1088 
1089     orig_used = set1->used;
1090 
1091     for (i = 0; i < set2->used; ++i) {
1092         for (j = 0; j < orig_used; ++j) {
1093             /* detect duplicities */
1094             if (set1->val.snodes[j].snode == set2->val.snodes[i].snode) {
1095                 break;
1096             }
1097         }
1098 
1099         if (j == orig_used) {
1100             memcpy(&set1->val.snodes[set1->used], &set2->val.snodes[i], sizeof *set2->val.snodes);
1101             ++set1->used;
1102         }
1103     }
1104 
1105     set_free_content(set2);
1106     memset(set2, 0, sizeof *set2);
1107 }
1108 
1109 /**
1110  * @brief Insert a node into a set. Context position aware.
1111  *
1112  * @param[in] set Set to use.
1113  * @param[in] node Node to insert to \p set.
1114  * @param[in] pos Sort position of \p node. If left 0, it is filled just before sorting.
1115  * @param[in] node_type Node type of \p node.
1116  * @param[in] idx Index in \p set to insert into.
1117  */
1118 static void
set_insert_node(struct lyxp_set * set,const struct lyd_node * node,uint32_t pos,enum lyxp_node_type node_type,uint32_t idx)1119 set_insert_node(struct lyxp_set *set, const struct lyd_node *node, uint32_t pos, enum lyxp_node_type node_type, uint32_t idx)
1120 {
1121     assert(set && ((set->type == LYXP_SET_NODE_SET) || (set->type == LYXP_SET_EMPTY)));
1122 
1123     if (set->type == LYXP_SET_EMPTY) {
1124         /* first item */
1125         if (idx) {
1126             /* no real harm done, but it is a bug */
1127             LOGINT(NULL);
1128             idx = 0;
1129         }
1130         set->val.nodes = malloc(LYXP_SET_SIZE_START * sizeof *set->val.nodes);
1131         LY_CHECK_ERR_RETURN(!set->val.nodes, LOGMEM(NULL), );
1132         set->type = LYXP_SET_NODE_SET;
1133         set->used = 0;
1134         set->size = LYXP_SET_SIZE_START;
1135         set->ctx_pos = 1;
1136         set->ctx_size = 1;
1137 #ifdef LY_ENABLED_CACHE
1138         set->ht = NULL;
1139 #endif
1140     } else {
1141         /* not an empty set */
1142         if (set->used == set->size) {
1143 
1144             /* set is full */
1145             set->val.nodes = ly_realloc(set->val.nodes, (set->size + LYXP_SET_SIZE_STEP) * sizeof *set->val.nodes);
1146             LY_CHECK_ERR_RETURN(!set->val.nodes, LOGMEM(NULL), );
1147             set->size += LYXP_SET_SIZE_STEP;
1148         }
1149 
1150         if (idx > set->used) {
1151             LOGINT(NULL);
1152             idx = set->used;
1153         }
1154 
1155         /* make space for the new node */
1156         if (idx < set->used) {
1157             memmove(&set->val.nodes[idx + 1], &set->val.nodes[idx], (set->used - idx) * sizeof *set->val.nodes);
1158         }
1159     }
1160 
1161     /* finally assign the value */
1162     set->val.nodes[idx].node = (struct lyd_node *)node;
1163     set->val.nodes[idx].type = node_type;
1164     set->val.nodes[idx].pos = pos;
1165     ++set->used;
1166 
1167 #ifdef LY_ENABLED_CACHE
1168     set_insert_node_hash(set, (struct lyd_node *)node, node_type);
1169 #endif
1170 }
1171 
1172 static int
set_snode_insert_node(struct lyxp_set * set,const struct lys_node * node,enum lyxp_node_type node_type)1173 set_snode_insert_node(struct lyxp_set *set, const struct lys_node *node, enum lyxp_node_type node_type)
1174 {
1175     int ret;
1176 
1177     assert(set->type == LYXP_SET_SNODE_SET);
1178 
1179     ret = set_snode_dup_node_check(set, node, node_type, -1);
1180     if (ret > -1) {
1181         set->val.snodes[ret].in_ctx = 1;
1182     } else {
1183         if (set->used == set->size) {
1184             set->val.snodes = ly_realloc(set->val.snodes, (set->size + LYXP_SET_SIZE_STEP) * sizeof *set->val.snodes);
1185             LY_CHECK_ERR_RETURN(!set->val.snodes, LOGMEM(node->module->ctx), -1);
1186             set->size += LYXP_SET_SIZE_STEP;
1187         }
1188 
1189         ret = set->used;
1190         set->val.snodes[ret].snode = (struct lys_node *)node;
1191         set->val.snodes[ret].type = node_type;
1192         set->val.snodes[ret].in_ctx = 1;
1193         ++set->used;
1194     }
1195 
1196     return ret;
1197 }
1198 
1199 /**
1200  * @brief Replace a node in a set with another. Context position aware.
1201  *
1202  * @param[in] set Set to use.
1203  * @param[in] node Node to insert to \p set.
1204  * @param[in] pos Sort position of \p node. If left 0, it is filled just before sorting.
1205  * @param[in] node_type Node type of \p node.
1206  * @param[in] idx Index in \p set of the node to replace.
1207  */
1208 static void
set_replace_node(struct lyxp_set * set,const struct lyd_node * node,uint32_t pos,enum lyxp_node_type node_type,uint32_t idx)1209 set_replace_node(struct lyxp_set *set, const struct lyd_node *node, uint32_t pos, enum lyxp_node_type node_type, uint32_t idx)
1210 {
1211     assert(set && (idx < set->used));
1212 
1213 #ifdef LY_ENABLED_CACHE
1214     set_remove_node_hash(set, set->val.nodes[idx].node, set->val.nodes[idx].type);
1215 #endif
1216     set->val.nodes[idx].node = (struct lyd_node *)node;
1217     set->val.nodes[idx].type = node_type;
1218     set->val.nodes[idx].pos = pos;
1219 #ifdef LY_ENABLED_CACHE
1220     set_insert_node_hash(set, set->val.nodes[idx].node, set->val.nodes[idx].type);
1221 #endif
1222 }
1223 
1224 static uint32_t
set_snode_new_in_ctx(struct lyxp_set * set)1225 set_snode_new_in_ctx(struct lyxp_set *set)
1226 {
1227     uint32_t ret_ctx, i;
1228 
1229     assert(set->type == LYXP_SET_SNODE_SET);
1230 
1231     ret_ctx = 3;
1232 retry:
1233     for (i = 0; i < set->used; ++i) {
1234         if (set->val.snodes[i].in_ctx >= ret_ctx) {
1235             ret_ctx = set->val.snodes[i].in_ctx + 1;
1236             goto retry;
1237         }
1238     }
1239     for (i = 0; i < set->used; ++i) {
1240         if (set->val.snodes[i].in_ctx == 1) {
1241             set->val.snodes[i].in_ctx = ret_ctx;
1242         }
1243     }
1244 
1245     return ret_ctx;
1246 }
1247 
1248 /**
1249  * @brief Get unique \p node position in the data.
1250  *
1251  * @param[in] node Node to find.
1252  * @param[in] node_type Node type of \p node.
1253  * @param[in] root Root node.
1254  * @param[in] root_type Type of the XPath \p root node.
1255  * @param[in] prev Node that we think is before \p node in DFS from \p root. Can optionally
1256  * be used to increase efficiency and start the DFS from this node.
1257  * @param[in] prev_pos Node \p prev position. Optional, but must be set if \p prev is set.
1258  *
1259  * @return Node position.
1260  */
1261 static uint32_t
get_node_pos(const struct lyd_node * node,enum lyxp_node_type node_type,const struct lyd_node * root,enum lyxp_node_type root_type,const struct lyd_node ** prev,uint32_t * prev_pos)1262 get_node_pos(const struct lyd_node *node, enum lyxp_node_type node_type, const struct lyd_node *root,
1263              enum lyxp_node_type root_type, const struct lyd_node **prev, uint32_t *prev_pos)
1264 {
1265     const struct lyd_node *next, *elem = NULL, *top_sibling;
1266     uint32_t pos = 1;
1267 
1268     assert(prev && prev_pos && !root->prev->next);
1269 
1270     if ((node_type == LYXP_NODE_ROOT) || (node_type == LYXP_NODE_ROOT_CONFIG)) {
1271         return 0;
1272     }
1273 
1274     if (*prev) {
1275         /* start from the previous element instead from the root */
1276         elem = next = *prev;
1277         pos = *prev_pos;
1278         for (top_sibling = elem; top_sibling->parent; top_sibling = top_sibling->parent);
1279         goto dfs_search;
1280     }
1281 
1282     LY_TREE_FOR(root, top_sibling) {
1283         /* TREE DFS */
1284         LY_TREE_DFS_BEGIN(top_sibling, next, elem) {
1285 dfs_search:
1286             if ((root_type == LYXP_NODE_ROOT_CONFIG) && (elem->schema->flags & LYS_CONFIG_R)) {
1287                 goto skip_children;
1288             }
1289 
1290             if (elem == node) {
1291                 break;
1292             }
1293             ++pos;
1294 
1295             /* TREE DFS END */
1296             /* select element for the next run - children first,
1297              * child exception for lyd_node_leaf and lyd_node_leaflist, but not the root */
1298             if (elem->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) {
1299                 next = NULL;
1300             } else {
1301                 next = elem->child;
1302             }
1303             if (!next) {
1304 skip_children:
1305                 /* no children */
1306                 if (elem == top_sibling) {
1307                     /* we are done, root has no children */
1308                     elem = NULL;
1309                     break;
1310                 }
1311                 /* try siblings */
1312                 next = elem->next;
1313             }
1314             while (!next) {
1315                 /* no siblings, go back through parents */
1316                 if (elem->parent == top_sibling->parent) {
1317                     /* we are done, no next element to process */
1318                     elem = NULL;
1319                     break;
1320                 }
1321                 /* parent is already processed, go to its sibling */
1322                 elem = elem->parent;
1323                 next = elem->next;
1324             }
1325         }
1326 
1327         /* node found */
1328         if (elem) {
1329             break;
1330         }
1331     }
1332 
1333     if (!elem) {
1334         if (!(*prev)) {
1335             /* we went from root and failed to find it, cannot be */
1336             LOGINT(node->schema->module->ctx);
1337             return 0;
1338         } else {
1339             /* node is before prev, we assumed otherwise :( */
1340             //LOGDBG(LY_LDGXPATH, "get_node_pos optimalization fail.");
1341 
1342             *prev = NULL;
1343             *prev_pos = 0;
1344 
1345             elem = next = top_sibling = root;
1346             pos = 1;
1347             goto dfs_search;
1348         }
1349     }
1350 
1351     /*if (*prev) {
1352         LOGDBG(LY_LDGXPATH, "get_node_pos optimalization success.");
1353     }*/
1354 
1355     /* remember the last found node for next time */
1356     *prev = node;
1357     *prev_pos = pos;
1358 
1359     return pos;
1360 }
1361 
1362 /**
1363  * @brief Assign (fill) missing node positions.
1364  *
1365  * @param[in] set Set to fill positions in.
1366  * @param[in] root Context root node.
1367  * @param[in] root_type Context root type.
1368  *
1369  * @return 0 on success, -1 on error.
1370  */
1371 static int
set_assign_pos(struct lyxp_set * set,const struct lyd_node * root,enum lyxp_node_type root_type)1372 set_assign_pos(struct lyxp_set *set, const struct lyd_node *root, enum lyxp_node_type root_type)
1373 {
1374     const struct lyd_node *prev = NULL, *tmp_node;
1375     uint32_t i, tmp_pos = 0;
1376 
1377     for (i = 0; i < set->used; ++i) {
1378         if (!set->val.nodes[i].pos) {
1379             tmp_node = NULL;
1380             switch (set->val.nodes[i].type) {
1381             case LYXP_NODE_ATTR:
1382                 tmp_node = lyd_attr_parent(root, set->val.attrs[i].attr);
1383                 if (!tmp_node) {
1384                     LOGINT(root->schema->module->ctx);
1385                     return -1;
1386                 }
1387                 /* fallthrough */
1388             case LYXP_NODE_ELEM:
1389             case LYXP_NODE_TEXT:
1390                 if (!tmp_node) {
1391                     tmp_node = set->val.nodes[i].node;
1392                 }
1393                 set->val.nodes[i].pos = get_node_pos(tmp_node, set->val.nodes[i].type, root, root_type, &prev, &tmp_pos);
1394                 break;
1395             default:
1396                 /* all roots have position 0 */
1397                 break;
1398             }
1399         }
1400     }
1401 
1402     return 0;
1403 }
1404 
1405 /**
1406  * @brief Get unique \p attr position in the parent attributes.
1407  *
1408  * @param[in] attr Attr to use.
1409  * @param[in] parent Parent of \p attr.
1410  *
1411  * @return Attribute position.
1412  */
1413 static uint16_t
get_attr_pos(struct lyd_attr * attr,const struct lyd_node * parent)1414 get_attr_pos(struct lyd_attr *attr, const struct lyd_node *parent)
1415 {
1416     uint16_t pos = 0;
1417     struct lyd_attr *attr2;
1418 
1419     for (attr2 = parent->attr; attr2 && (attr2 != attr); attr2 = attr2->next) {
1420         ++pos;
1421     }
1422 
1423     assert(attr2);
1424     return pos;
1425 }
1426 
1427 /**
1428  * @brief Compare 2 nodes in respect to XPath document order.
1429  *
1430  * @param[in] idx1 Index of the 1st node in \p set1.
1431  * @param[in] set1 Set with the 1st node on index \p idx1.
1432  * @param[in] idx2 Index of the 2nd node in \p set2.
1433  * @param[in] set2 Set with the 2nd node on index \p idx2.
1434  * @param[in] root Context root node.
1435  *
1436  * @return If 1st > 2nd returns 1, 1st == 2nd returns 0, and 1st < 2nd returns -1.
1437  */
1438 static int
set_sort_compare(struct lyxp_set_node * item1,struct lyxp_set_node * item2,const struct lyd_node * root)1439 set_sort_compare(struct lyxp_set_node *item1, struct lyxp_set_node *item2,
1440                  const struct lyd_node *root)
1441 {
1442     const struct lyd_node *tmp_node;
1443     uint32_t attr_pos1 = 0, attr_pos2 = 0;
1444 
1445     if (item1->pos < item2->pos) {
1446         return -1;
1447     }
1448 
1449     if (item1->pos > item2->pos) {
1450         return 1;
1451     }
1452 
1453     /* node positions are equal, the fun case */
1454 
1455     /* 1st ELEM - == - 2nd TEXT, 1st TEXT - == - 2nd ELEM */
1456     /* special case since text nodes are actually saved as their parents */
1457     if ((item1->node == item2->node) && (item1->type != item2->type)) {
1458         if (item1->type == LYXP_NODE_ELEM) {
1459             assert(item2->type == LYXP_NODE_TEXT);
1460             return -1;
1461         } else {
1462             assert((item1->type == LYXP_NODE_TEXT) && (item2->type == LYXP_NODE_ELEM));
1463             return 1;
1464         }
1465     }
1466 
1467     /* we need attr positions now */
1468     if (item1->type == LYXP_NODE_ATTR) {
1469         tmp_node = lyd_attr_parent(root, (struct lyd_attr *)item1->node);
1470         if (!tmp_node) {
1471             LOGINT(root->schema->module->ctx);
1472             return -1;
1473         }
1474         attr_pos1 = get_attr_pos((struct lyd_attr *)item1->node, tmp_node);
1475     }
1476     if (item2->type == LYXP_NODE_ATTR) {
1477         tmp_node = lyd_attr_parent(root, (struct lyd_attr *)item2->node);
1478         if (!tmp_node) {
1479             LOGINT(root->schema->module->ctx);
1480             return -1;
1481         }
1482         attr_pos2 = get_attr_pos((struct lyd_attr *)item2->node, tmp_node);
1483     }
1484 
1485     /* 1st ROOT - 2nd ROOT, 1st ELEM - 2nd ELEM, 1st TEXT - 2nd TEXT, 1st ATTR - =pos= - 2nd ATTR */
1486     /* check for duplicates */
1487     if (item1->node == item2->node) {
1488         assert((item1->type == item2->type) && ((item1->type != LYXP_NODE_ATTR) || (attr_pos1 == attr_pos2)));
1489         return 0;
1490     }
1491 
1492     /* 1st ELEM - 2nd TEXT, 1st ELEM - any pos - 2nd ATTR */
1493     /* elem is always first, 2nd node is after it */
1494     if (item1->type == LYXP_NODE_ELEM) {
1495         assert(item2->type != LYXP_NODE_ELEM);
1496         return -1;
1497     }
1498 
1499     /* 1st TEXT - 2nd ELEM, 1st TEXT - any pos - 2nd ATTR, 1st ATTR - any pos - 2nd ELEM, 1st ATTR - >pos> - 2nd ATTR */
1500     /* 2nd is before 1st */
1501     if (((item1->type == LYXP_NODE_TEXT)
1502             && ((item2->type == LYXP_NODE_ELEM) || (item2->type == LYXP_NODE_ATTR)))
1503             || ((item1->type == LYXP_NODE_ATTR) && (item2->type == LYXP_NODE_ELEM))
1504             || (((item1->type == LYXP_NODE_ATTR) && (item2->type == LYXP_NODE_ATTR))
1505             && (attr_pos1 > attr_pos2))) {
1506         return 1;
1507     }
1508 
1509     /* 1st ATTR - any pos - 2nd TEXT, 1st ATTR <pos< - 2nd ATTR */
1510     /* 2nd is after 1st */
1511     return -1;
1512 }
1513 
1514 static int
set_comp_cast(struct lyxp_set * trg,struct lyxp_set * src,enum lyxp_set_type type,const struct lyd_node * cur_node,const struct lys_module * local_mod,uint32_t src_idx,int options)1515 set_comp_cast(struct lyxp_set *trg, struct lyxp_set *src, enum lyxp_set_type type, const struct lyd_node *cur_node,
1516               const struct lys_module *local_mod, uint32_t src_idx, int options)
1517 {
1518     assert(src->type == LYXP_SET_NODE_SET);
1519 
1520     memset(trg, 0, sizeof *trg);
1521 
1522     /* insert node into target set */
1523     set_insert_node(trg, src->val.nodes[src_idx].node, src->val.nodes[src_idx].pos, src->val.nodes[src_idx].type, 0);
1524 
1525     /* cast target set appropriately */
1526     if (lyxp_set_cast(trg, type, cur_node, local_mod, options)) {
1527         set_free_content(trg);
1528         return -1;
1529     }
1530 
1531     return EXIT_SUCCESS;
1532 }
1533 
1534 #ifndef NDEBUG
1535 
1536 /**
1537  * @brief Bubble sort \p set into XPath document order.
1538  *        Context position aware. Unused in the 'Release' build target.
1539  *
1540  * @param[in] set Set to sort.
1541  * @param[in] cur_node Original context node.
1542  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
1543  *
1544  * @return How many times the whole set was traversed - 1 (if set was sorted, returns 0).
1545  */
1546 static int
set_sort(struct lyxp_set * set,const struct lyd_node * cur_node,int options)1547 set_sort(struct lyxp_set *set, const struct lyd_node *cur_node, int options)
1548 {
1549     uint32_t i, j;
1550     int ret = 0, cmp, inverted, change;
1551     const struct lyd_node *root;
1552     enum lyxp_node_type root_type;
1553     struct lyxp_set_node item;
1554 
1555     if ((set->type != LYXP_SET_NODE_SET) || (set->used == 1)) {
1556         return 0;
1557     }
1558 
1559     /* get root */
1560     root = moveto_get_root(cur_node, options, &root_type);
1561 
1562     /* fill positions */
1563     if (set_assign_pos(set, root, root_type)) {
1564         return -1;
1565     }
1566 
1567     LOGDBG(LY_LDGXPATH, "SORT BEGIN");
1568     print_set_debug(set);
1569 
1570     for (i = 0; i < set->used; ++i) {
1571         inverted = 0;
1572         change = 0;
1573 
1574         for (j = 1; j < set->used - i; ++j) {
1575             /* compare node positions */
1576             if (inverted) {
1577                 cmp = set_sort_compare(&set->val.nodes[j], &set->val.nodes[j - 1], root);
1578             } else {
1579                 cmp = set_sort_compare(&set->val.nodes[j - 1], &set->val.nodes[j], root);
1580             }
1581 
1582             /* swap if needed */
1583             if ((inverted && (cmp < 0)) || (!inverted && (cmp > 0))) {
1584                 change = 1;
1585 
1586                 item = set->val.nodes[j - 1];
1587                 set->val.nodes[j - 1] = set->val.nodes[j];
1588                 set->val.nodes[j] = item;
1589             } else {
1590                 /* whether node_pos1 should be smaller than node_pos2 or the other way around */
1591                 inverted = !inverted;
1592             }
1593         }
1594 
1595         ++ret;
1596 
1597         if (!change) {
1598             break;
1599         }
1600     }
1601 
1602     LOGDBG(LY_LDGXPATH, "SORT END %d", ret);
1603     print_set_debug(set);
1604 
1605 #ifdef LY_ENABLED_CACHE
1606     struct lyxp_set_hash_node hnode;
1607     uint64_t hash;
1608 
1609     /* check node hashes */
1610     if (set->used >= LY_CACHE_HT_MIN_CHILDREN) {
1611         assert(set->ht);
1612         for (i = 0; i < set->used; ++i) {
1613             hnode.node = set->val.nodes[i].node;
1614             hnode.type = set->val.nodes[i].type;
1615 
1616             hash = dict_hash_multi(0, (const char *)&hnode.node, sizeof hnode.node);
1617             hash = dict_hash_multi(hash, (const char *)&hnode.type, sizeof hnode.type);
1618             hash = dict_hash_multi(hash, NULL, 0);
1619 
1620             assert(!lyht_find(set->ht, &hnode, hash, NULL));
1621         }
1622     }
1623 #endif
1624 
1625     return ret - 1;
1626 }
1627 
1628 /**
1629  * @brief Remove duplicate entries in a sorted node set.
1630  *
1631  * @param[in] set Sorted set to check.
1632  *
1633  * @return EXIT_SUCCESS if no duplicates were found,
1634  *         EXIT_FAILURE otherwise.
1635  */
1636 static int
set_sorted_dup_node_clean(struct lyxp_set * set)1637 set_sorted_dup_node_clean(struct lyxp_set *set)
1638 {
1639     uint32_t i = 0;
1640     int ret = EXIT_SUCCESS;
1641 
1642     if (set->used > 1) {
1643         while (i < set->used - 1) {
1644             if ((set->val.nodes[i].node == set->val.nodes[i + 1].node)
1645                     && (set->val.nodes[i].type == set->val.nodes[i + 1].type)) {
1646                 set_remove_node(set, i + 1);
1647             ret = EXIT_FAILURE;
1648             } else {
1649                 ++i;
1650             }
1651         }
1652     }
1653 
1654     return ret;
1655 }
1656 
1657 #endif
1658 
1659 /**
1660  * @brief Merge 2 sorted sets into one.
1661  *
1662  * @param[in,out] trg Set to merge into. Duplicates are removed.
1663  * @param[in] src Set to be merged into \p trg. It is cast to #LYXP_SET_EMPTY on success.
1664  * @param[in] cur_node Original context node.
1665  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
1666  *
1667  * @return 0 on success, -1 on error.
1668  */
1669 static int
set_sorted_merge(struct lyxp_set * trg,struct lyxp_set * src,struct lyd_node * cur_node,int options)1670 set_sorted_merge(struct lyxp_set *trg, struct lyxp_set *src, struct lyd_node *cur_node, int options)
1671 {
1672     uint32_t i, j, count, dup_count;
1673     int cmp;
1674     const struct lyd_node *root;
1675     enum lyxp_node_type root_type;
1676 
1677     if (((trg->type != LYXP_SET_NODE_SET) && (trg->type != LYXP_SET_EMPTY))
1678             || ((src->type != LYXP_SET_NODE_SET) && (src->type != LYXP_SET_EMPTY))) {
1679         return -1;
1680     }
1681 
1682     if (src->type == LYXP_SET_EMPTY) {
1683         return 0;
1684     } else if (trg->type == LYXP_SET_EMPTY) {
1685         set_fill_set(trg, src);
1686         lyxp_set_cast(src, LYXP_SET_EMPTY, cur_node, NULL, options);
1687         return 0;
1688     }
1689 
1690     /* get root */
1691     root = moveto_get_root(cur_node, options, &root_type);
1692 
1693     /* fill positions */
1694     if (set_assign_pos(trg, root, root_type) || set_assign_pos(src, root, root_type)) {
1695         return -1;
1696     }
1697 
1698 #ifndef NDEBUG
1699     LOGDBG(LY_LDGXPATH, "MERGE target");
1700     print_set_debug(trg);
1701     LOGDBG(LY_LDGXPATH, "MERGE source");
1702     print_set_debug(src);
1703 #endif
1704 
1705     /* make memory for the merge (duplicates are not detected yet, so space
1706      * will likely be wasted on them, too bad) */
1707     if (trg->size - trg->used < src->used) {
1708         trg->size = trg->used + src->used;
1709 
1710         trg->val.nodes = ly_realloc(trg->val.nodes, trg->size * sizeof *trg->val.nodes);
1711         LY_CHECK_ERR_RETURN(!trg->val.nodes, LOGMEM(cur_node->schema->module->ctx), -1);
1712     }
1713 
1714     i = 0;
1715     j = 0;
1716     count = 0;
1717     dup_count = 0;
1718     do {
1719         cmp = set_sort_compare(&src->val.nodes[i], &trg->val.nodes[j], root);
1720         if (!cmp) {
1721             if (!count) {
1722                 /* duplicate, just skip it */
1723                 ++i;
1724                 ++j;
1725             } else {
1726                 /* we are copying something already, so let's copy the duplicate too,
1727                  * we are hoping that afterwards there are some more nodes to
1728                  * copy and this way we can copy them all together */
1729                 ++count;
1730                 ++dup_count;
1731                 ++i;
1732                 ++j;
1733             }
1734         } else if (cmp < 0) {
1735             /* inserting src node into trg, just remember it for now */
1736             ++count;
1737             ++i;
1738 
1739 #ifdef LY_ENABLED_CACHE
1740             /* insert the hash now */
1741             set_insert_node_hash(trg, src->val.nodes[i - 1].node, src->val.nodes[i - 1].type);
1742 #endif
1743         } else if (count) {
1744 copy_nodes:
1745             /* time to actually copy the nodes, we have found the largest block of nodes */
1746             memmove(&trg->val.nodes[j + (count - dup_count)],
1747                     &trg->val.nodes[j],
1748                     (trg->used - j) * sizeof *trg->val.nodes);
1749             memcpy(&trg->val.nodes[j - dup_count], &src->val.nodes[i - count], count * sizeof *src->val.nodes);
1750 
1751             trg->used += count - dup_count;
1752             /* do not change i, except the copying above, we are basically doing exactly what is in the else branch below */
1753             j += count - dup_count;
1754 
1755             count = 0;
1756             dup_count = 0;
1757         } else {
1758             ++j;
1759         }
1760     } while ((i < src->used) && (j < trg->used));
1761 
1762     if ((i < src->used) || count) {
1763 #ifdef LY_ENABLED_CACHE
1764         uint32_t k;
1765 
1766         /* insert all the hashes first */
1767         for (k = i; k < src->used; ++k) {
1768             set_insert_node_hash(trg, src->val.nodes[k].node, src->val.nodes[k].type);
1769         }
1770 #endif
1771         /* loop ended, but we need to copy something at trg end */
1772         count += src->used - i;
1773         i = src->used;
1774         goto copy_nodes;
1775     }
1776 
1777 #ifdef LY_ENABLED_CACHE
1778     /* we are inserting hashes before the actual node insert, which causes
1779      * situations when there were initially not enough items for a hash table,
1780      * but even after some were inserted, hash table was not created (during
1781      * insertion the number of items is not updated yet) */
1782     if (!trg->ht && (trg->used >= LY_CACHE_HT_MIN_CHILDREN)) {
1783         set_insert_node_hash(trg, NULL, 0);
1784     }
1785 #endif
1786 
1787 #ifndef NDEBUG
1788     LOGDBG(LY_LDGXPATH, "MERGE result");
1789     print_set_debug(trg);
1790 #endif
1791 
1792     lyxp_set_cast(src, LYXP_SET_EMPTY, cur_node, NULL, options);
1793     return 0;
1794 }
1795 
1796 /**
1797  * @brief Canonize value in the set (can be string or number).
1798  *
1799  * @param[in] set Set to canonize.
1800  * @param[in] set2 Set to canonize for.
1801  * @param[in] schema Schema node to read YANG canonization rules from.
1802  *
1803  * @return 0 on succes, -1 on error.
1804  */
1805 static int
set_canonize(struct lyxp_set * set,const struct lyxp_set * set2)1806 set_canonize(struct lyxp_set *set, const struct lyxp_set *set2)
1807 {
1808     char *num_str, *val_can, *ptr;
1809     struct lys_node *schema;
1810     enum int_log_opts prev_ilo;
1811 
1812     assert(set2->type == LYXP_SET_NODE_SET);
1813 
1814     if ((set2->val.nodes[0].type == LYXP_NODE_ELEM) && (set2->val.nodes[0].node->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
1815         schema = set2->val.nodes[0].node->schema;
1816     } else {
1817         /* nothing to canonize/not supported */
1818         return 0;
1819     }
1820 
1821     switch (set->type) {
1822     case LYXP_SET_NUMBER:
1823         /* canonize number */
1824         if (asprintf(&num_str, "%Lf", set->val.num) == -1) {
1825             LOGMEM(schema->module->ctx);
1826             return -1;
1827         }
1828 
1829         /* ignore errors, the value may not satisfy schema constraints */
1830         ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);
1831         val_can = lyd_make_canonical(schema, num_str, strlen(num_str));
1832         ly_ilo_restore(NULL, prev_ilo, NULL, 0);
1833 
1834         free(num_str);
1835         if (!val_can) {
1836             break;
1837         }
1838         set->val.num = strtold(val_can, &ptr);
1839         if (ptr[0]) {
1840             free(val_can);
1841             LOGINT(schema->module->ctx);
1842             return -1;
1843         }
1844         free(val_can);
1845         break;
1846     case LYXP_SET_STRING:
1847         /* canonize string */
1848         ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);
1849         val_can = lyd_make_canonical(schema, set->val.str, strlen(set->val.str));
1850         ly_ilo_restore(NULL, prev_ilo, NULL, 0);
1851         if (!val_can) {
1852             break;
1853         }
1854         free(set->val.str);
1855         set->val.str = val_can;
1856         break;
1857     case LYXP_SET_BOOLEAN:
1858         /* always canonical */
1859         break;
1860     default:
1861         LOGINT(schema->module->ctx);
1862         return -1;
1863     }
1864 
1865     return 0;
1866 }
1867 
1868 /*
1869  * (re)parse functions
1870  *
1871  * Parse functions parse the expression into
1872  * tokens (syntactic analysis).
1873  *
1874  * Reparse functions perform semantic analysis
1875  * (do not save the result, just a check) of
1876  * the expression and fill repeat indices.
1877  */
1878 
1879 /**
1880  * @brief Add \p token into the expression \p exp.
1881  *
1882  * @param[in] exp Expression to use.
1883  * @param[in] token Token to add.
1884  * @param[in] expr_pos Token position in the XPath expression.
1885  * @param[in] tok_len Token length in the XPath expression.
1886  * @return 0 on success, -1 on error.
1887  */
1888 static int
exp_add_token(struct lyxp_expr * exp,enum lyxp_token token,uint16_t expr_pos,uint16_t tok_len)1889 exp_add_token(struct lyxp_expr *exp, enum lyxp_token token, uint16_t expr_pos, uint16_t tok_len)
1890 {
1891     uint32_t prev;
1892 
1893     if (exp->used == exp->size) {
1894         prev = exp->size;
1895         exp->size += LYXP_EXPR_SIZE_STEP;
1896         if (prev > exp->size) {
1897             LOGINT(NULL);
1898             return -1;
1899         }
1900 
1901         exp->tokens = ly_realloc(exp->tokens, exp->size * sizeof *exp->tokens);
1902         LY_CHECK_ERR_RETURN(!exp->tokens, LOGMEM(NULL), -1);
1903         exp->expr_pos = ly_realloc(exp->expr_pos, exp->size * sizeof *exp->expr_pos);
1904         LY_CHECK_ERR_RETURN(!exp->expr_pos, LOGMEM(NULL), -1);
1905         exp->tok_len = ly_realloc(exp->tok_len, exp->size * sizeof *exp->tok_len);
1906         LY_CHECK_ERR_RETURN(!exp->tok_len, LOGMEM(NULL), -1);
1907     }
1908 
1909     exp->tokens[exp->used] = token;
1910     exp->expr_pos[exp->used] = expr_pos;
1911     exp->tok_len[exp->used] = tok_len;
1912     ++exp->used;
1913     return 0;
1914 }
1915 
1916 /**
1917  * @brief Look at the next token and check its kind.
1918  *
1919  * @param[in] exp Expression to use.
1920  * @param[in] exp_idx Position in the expression \p exp.
1921  * @param[in] want_tok Expected token.
1922  * @param[in] strict Whether the token is strictly required (print error if
1923  * not the next one) or we simply want to check whether it is the next or not.
1924  *
1925  * @return EXIT_SUCCESS if the current token matches the expected one,
1926  *         -1 otherwise.
1927  */
1928 static int
exp_check_token(struct ly_ctx * ctx,struct lyxp_expr * exp,uint16_t exp_idx,enum lyxp_token want_tok,int strict)1929 exp_check_token(struct ly_ctx *ctx, struct lyxp_expr *exp, uint16_t exp_idx, enum lyxp_token want_tok, int strict)
1930 {
1931     if (exp->used == exp_idx) {
1932         if (strict) {
1933             LOGVAL(ctx, LYE_XPATH_EOF, LY_VLOG_NONE, NULL);
1934         }
1935         return -1;
1936     }
1937 
1938     if (want_tok && (exp->tokens[exp_idx] != want_tok)) {
1939         if (strict) {
1940             LOGVAL(ctx, LYE_XPATH_INTOK, LY_VLOG_NONE, NULL,
1941                    print_token(exp->tokens[exp_idx]), &exp->expr[exp->expr_pos[exp_idx]]);
1942         }
1943         return -1;
1944     }
1945 
1946     return EXIT_SUCCESS;
1947 }
1948 
1949 /**
1950  * @brief Stack operation push on the repeat array.
1951  *
1952  * @param[in] exp Expression to use.
1953  * @param[in] exp_idx Position in the expresion \p exp.
1954  * @param[in] repeat_op_idx Index from \p exp of the operator token. This value is pushed.
1955  */
1956 static void
exp_repeat_push(struct lyxp_expr * exp,uint16_t exp_idx,uint16_t repeat_op_idx)1957 exp_repeat_push(struct lyxp_expr *exp, uint16_t exp_idx, uint16_t repeat_op_idx)
1958 {
1959     uint16_t i;
1960 
1961     if (exp->repeat[exp_idx]) {
1962         for (i = 0; exp->repeat[exp_idx][i]; ++i);
1963         exp->repeat[exp_idx] = realloc(exp->repeat[exp_idx], (i + 2) * sizeof *exp->repeat[exp_idx]);
1964         LY_CHECK_ERR_RETURN(!exp->repeat[exp_idx], LOGMEM(NULL), );
1965         exp->repeat[exp_idx][i] = repeat_op_idx;
1966         exp->repeat[exp_idx][i + 1] = 0;
1967     } else {
1968         exp->repeat[exp_idx] = calloc(2, sizeof *exp->repeat[exp_idx]);
1969         LY_CHECK_ERR_RETURN(!exp->repeat[exp_idx], LOGMEM(NULL), );
1970         exp->repeat[exp_idx][0] = repeat_op_idx;
1971     }
1972 }
1973 
1974 /**
1975  * @brief Reparse Predicate. Logs directly on error.
1976  *
1977  * [7] Predicate ::= '[' Expr ']'
1978  *
1979  * @param[in] exp Parsed XPath expression.
1980  * @param[in] exp_idx Position in the expression \p exp.
1981  *
1982  * @return EXIT_SUCCESS on success, -1 on error.
1983  */
1984 static int
reparse_predicate(struct ly_ctx * ctx,struct lyxp_expr * exp,uint16_t * exp_idx)1985 reparse_predicate(struct ly_ctx *ctx, struct lyxp_expr *exp, uint16_t *exp_idx)
1986 {
1987     if (exp_check_token(ctx, exp, *exp_idx, LYXP_TOKEN_BRACK1, 1)) {
1988         return -1;
1989     }
1990     ++(*exp_idx);
1991 
1992     if (reparse_or_expr(ctx, exp, exp_idx)) {
1993         return -1;
1994     }
1995 
1996     if (exp_check_token(ctx, exp, *exp_idx, LYXP_TOKEN_BRACK2, 1)) {
1997         return -1;
1998     }
1999     ++(*exp_idx);
2000 
2001     return EXIT_SUCCESS;
2002 }
2003 
2004 /**
2005  * @brief Reparse RelativeLocationPath. Logs directly on error.
2006  *
2007  * [4] RelativeLocationPath ::= Step | RelativeLocationPath '/' Step | RelativeLocationPath '//' Step
2008  * [5] Step ::= '@'? NodeTest Predicate* | '.' | '..'
2009  * [6] NodeTest ::= NameTest | NodeType '(' ')'
2010  *
2011  * @param[in] exp Parsed XPath expression.
2012  * @param[in] exp_idx Position in the expression \p exp.
2013  *
2014  * @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error.
2015  */
2016 static int
reparse_relative_location_path(struct ly_ctx * ctx,struct lyxp_expr * exp,uint16_t * exp_idx)2017 reparse_relative_location_path(struct ly_ctx *ctx, struct lyxp_expr *exp, uint16_t *exp_idx)
2018 {
2019     if (exp_check_token(ctx, exp, *exp_idx, LYXP_TOKEN_NONE, 1)) {
2020         return -1;
2021     }
2022 
2023     goto step;
2024     do {
2025         /* '/' or '//' */
2026         ++(*exp_idx);
2027 
2028         if (exp_check_token(ctx, exp, *exp_idx, LYXP_TOKEN_NONE, 1)) {
2029             return -1;
2030         }
2031 step:
2032         /* Step */
2033         switch (exp->tokens[*exp_idx]) {
2034         case LYXP_TOKEN_DOT:
2035             ++(*exp_idx);
2036             break;
2037 
2038         case LYXP_TOKEN_DDOT:
2039             ++(*exp_idx);
2040             break;
2041 
2042         case LYXP_TOKEN_AT:
2043             ++(*exp_idx);
2044 
2045             if (exp_check_token(ctx, exp, *exp_idx, LYXP_TOKEN_NONE, 1)) {
2046                 return -1;
2047             }
2048             if ((exp->tokens[*exp_idx] != LYXP_TOKEN_NAMETEST) && (exp->tokens[*exp_idx] != LYXP_TOKEN_NODETYPE)) {
2049                 LOGVAL(ctx, LYE_XPATH_INTOK, LY_VLOG_NONE, NULL,
2050                        print_token(exp->tokens[*exp_idx]), &exp->expr[exp->expr_pos[*exp_idx]]);
2051                 return -1;
2052             }
2053             /* fall through */
2054         case LYXP_TOKEN_NAMETEST:
2055             ++(*exp_idx);
2056             goto reparse_predicate;
2057             break;
2058 
2059         case LYXP_TOKEN_NODETYPE:
2060             ++(*exp_idx);
2061 
2062             /* '(' */
2063             if (exp_check_token(ctx, exp, *exp_idx, LYXP_TOKEN_PAR1, 1)) {
2064                 return -1;
2065             }
2066             ++(*exp_idx);
2067 
2068             /* ')' */
2069             if (exp_check_token(ctx, exp, *exp_idx, LYXP_TOKEN_PAR2, 1)) {
2070                 return -1;
2071             }
2072             ++(*exp_idx);
2073 
2074 reparse_predicate:
2075             /* Predicate* */
2076             while ((exp->used > *exp_idx) && (exp->tokens[*exp_idx] == LYXP_TOKEN_BRACK1)) {
2077                 if (reparse_predicate(ctx, exp, exp_idx)) {
2078                     return -1;
2079                 }
2080             }
2081             break;
2082         default:
2083             LOGVAL(ctx, LYE_XPATH_INTOK, LY_VLOG_NONE, NULL,
2084                    print_token(exp->tokens[*exp_idx]), &exp->expr[exp->expr_pos[*exp_idx]]);
2085             return -1;
2086         }
2087     } while ((exp->used > *exp_idx) && (exp->tokens[*exp_idx] == LYXP_TOKEN_OPERATOR_PATH));
2088 
2089     return EXIT_SUCCESS;
2090 }
2091 
2092 /**
2093  * @brief Reparse AbsoluteLocationPath. Logs directly on error.
2094  *
2095  * [3] AbsoluteLocationPath ::= '/' RelativeLocationPath? | '//' RelativeLocationPath
2096  *
2097  * @param[in] exp Parsed XPath expression.
2098  * @param[in] exp_idx Position in the expression \p exp.
2099  *
2100  * @return EXIT_SUCCESS on success, -1 on error.
2101  */
2102 static int
reparse_absolute_location_path(struct ly_ctx * ctx,struct lyxp_expr * exp,uint16_t * exp_idx)2103 reparse_absolute_location_path(struct ly_ctx *ctx, struct lyxp_expr *exp, uint16_t *exp_idx)
2104 {
2105     if (exp_check_token(ctx, exp, *exp_idx, LYXP_TOKEN_OPERATOR_PATH, 1)) {
2106         return -1;
2107     }
2108 
2109     /* '/' RelativeLocationPath? */
2110     if (exp->tok_len[*exp_idx] == 1) {
2111         /* '/' */
2112         ++(*exp_idx);
2113 
2114         if (exp_check_token(ctx, exp, *exp_idx, LYXP_TOKEN_NONE, 0)) {
2115             return EXIT_SUCCESS;
2116         }
2117         switch (exp->tokens[*exp_idx]) {
2118         case LYXP_TOKEN_DOT:
2119         case LYXP_TOKEN_DDOT:
2120         case LYXP_TOKEN_AT:
2121         case LYXP_TOKEN_NAMETEST:
2122         case LYXP_TOKEN_NODETYPE:
2123             if (reparse_relative_location_path(ctx, exp, exp_idx)) {
2124                 return -1;
2125             }
2126             /* fall through */
2127         default:
2128             break;
2129         }
2130 
2131     /* '//' RelativeLocationPath */
2132     } else {
2133         /* '//' */
2134         ++(*exp_idx);
2135 
2136         if (reparse_relative_location_path(ctx, exp, exp_idx)) {
2137             return -1;
2138         }
2139     }
2140 
2141     return EXIT_SUCCESS;
2142 }
2143 
2144 /**
2145  * @brief Reparse FunctionCall. Logs directly on error.
2146  *
2147  * [9] FunctionCall ::= FunctionName '(' ( Expr ( ',' Expr )* )? ')'
2148  *
2149  * @param[in] exp Parsed XPath expression.
2150  * @param[in] exp_idx Position in the expression \p exp.
2151  *
2152  * @return EXIT_SUCCESS on success, -1 on error.
2153  */
2154 static int
reparse_function_call(struct ly_ctx * ctx,struct lyxp_expr * exp,uint16_t * exp_idx)2155 reparse_function_call(struct ly_ctx *ctx, struct lyxp_expr *exp, uint16_t *exp_idx)
2156 {
2157     int min_arg_count = -1, max_arg_count, arg_count;
2158     uint16_t func_exp_idx;
2159 
2160     if (exp_check_token(ctx, exp, *exp_idx, LYXP_TOKEN_FUNCNAME, 1)) {
2161         return -1;
2162     }
2163     func_exp_idx = *exp_idx;
2164     switch (exp->tok_len[*exp_idx]) {
2165     case 3:
2166         if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "not", 3)) {
2167             min_arg_count = 1;
2168             max_arg_count = 1;
2169         } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "sum", 3)) {
2170             min_arg_count = 1;
2171             max_arg_count = 1;
2172         }
2173         break;
2174     case 4:
2175         if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "lang", 4)) {
2176             min_arg_count = 1;
2177             max_arg_count = 1;
2178         } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "last", 4)) {
2179             min_arg_count = 0;
2180             max_arg_count = 0;
2181         } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "name", 4)) {
2182             min_arg_count = 0;
2183             max_arg_count = 1;
2184         } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "true", 4)) {
2185             min_arg_count = 0;
2186             max_arg_count = 0;
2187         }
2188         break;
2189     case 5:
2190         if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "count", 5)) {
2191             min_arg_count = 1;
2192             max_arg_count = 1;
2193         } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "false", 5)) {
2194             min_arg_count = 0;
2195             max_arg_count = 0;
2196         } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "floor", 5)) {
2197             min_arg_count = 1;
2198             max_arg_count = 1;
2199         } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "round", 5)) {
2200             min_arg_count = 1;
2201             max_arg_count = 1;
2202         } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "deref", 5)) {
2203             min_arg_count = 1;
2204             max_arg_count = 1;
2205         }
2206         break;
2207     case 6:
2208         if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "concat", 6)) {
2209             min_arg_count = 2;
2210             max_arg_count = INT_MAX;
2211         } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "number", 6)) {
2212             min_arg_count = 0;
2213             max_arg_count = 1;
2214         } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "string", 6)) {
2215             min_arg_count = 0;
2216             max_arg_count = 1;
2217         }
2218         break;
2219     case 7:
2220         if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "boolean", 7)) {
2221             min_arg_count = 1;
2222             max_arg_count = 1;
2223         } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "ceiling", 7)) {
2224             min_arg_count = 1;
2225             max_arg_count = 1;
2226         } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "current", 7)) {
2227             min_arg_count = 0;
2228             max_arg_count = 0;
2229         }
2230         break;
2231     case 8:
2232         if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "contains", 8)) {
2233             min_arg_count = 2;
2234             max_arg_count = 2;
2235         } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "position", 8)) {
2236             min_arg_count = 0;
2237             max_arg_count = 0;
2238         } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "re-match", 8)) {
2239             min_arg_count = 2;
2240             max_arg_count = 2;
2241         }
2242         break;
2243     case 9:
2244         if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "substring", 9)) {
2245             min_arg_count = 2;
2246             max_arg_count = 3;
2247         } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "translate", 9)) {
2248             min_arg_count = 3;
2249             max_arg_count = 3;
2250         }
2251         break;
2252     case 10:
2253         if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "local-name", 10)) {
2254             min_arg_count = 0;
2255             max_arg_count = 1;
2256         } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "enum-value", 10)) {
2257             min_arg_count = 1;
2258             max_arg_count = 1;
2259         } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "bit-is-set", 10)) {
2260             min_arg_count = 2;
2261             max_arg_count = 2;
2262         }
2263         break;
2264     case 11:
2265         if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "starts-with", 11)) {
2266             min_arg_count = 2;
2267             max_arg_count = 2;
2268         }
2269         break;
2270     case 12:
2271         if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "derived-from", 12)) {
2272             min_arg_count = 2;
2273             max_arg_count = 2;
2274         }
2275         break;
2276     case 13:
2277         if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "namespace-uri", 13)) {
2278             min_arg_count = 0;
2279             max_arg_count = 1;
2280         } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "string-length", 13)) {
2281             min_arg_count = 0;
2282             max_arg_count = 1;
2283         }
2284         break;
2285     case 15:
2286         if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "normalize-space", 15)) {
2287             min_arg_count = 0;
2288             max_arg_count = 1;
2289         } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "substring-after", 15)) {
2290             min_arg_count = 2;
2291             max_arg_count = 2;
2292         }
2293         break;
2294     case 16:
2295         if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "substring-before", 16)) {
2296             min_arg_count = 2;
2297             max_arg_count = 2;
2298         }
2299         break;
2300     case 20:
2301         if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "derived-from-or-self", 20)) {
2302             min_arg_count = 2;
2303             max_arg_count = 2;
2304         }
2305         break;
2306     }
2307     if (min_arg_count == -1) {
2308         LOGVAL(ctx, LYE_XPATH_INFUNC, LY_VLOG_NONE, NULL, exp->tok_len[*exp_idx], &exp->expr[exp->expr_pos[*exp_idx]]);
2309         return -1;
2310     }
2311     ++(*exp_idx);
2312 
2313     /* '(' */
2314     if (exp_check_token(ctx, exp, *exp_idx, LYXP_TOKEN_PAR1, 1)) {
2315         return -1;
2316     }
2317     ++(*exp_idx);
2318 
2319     /* ( Expr ( ',' Expr )* )? */
2320     arg_count = 0;
2321     if (exp_check_token(ctx, exp, *exp_idx, LYXP_TOKEN_NONE, 1)) {
2322         return -1;
2323     }
2324     if (exp->tokens[*exp_idx] != LYXP_TOKEN_PAR2) {
2325         ++arg_count;
2326         if (reparse_or_expr(ctx, exp, exp_idx)) {
2327             return -1;
2328         }
2329     }
2330     while ((exp->used > *exp_idx) && (exp->tokens[*exp_idx] == LYXP_TOKEN_COMMA)) {
2331         ++(*exp_idx);
2332 
2333         ++arg_count;
2334         if (reparse_or_expr(ctx, exp, exp_idx)) {
2335             return -1;
2336         }
2337     }
2338 
2339     /* ')' */
2340     if (exp_check_token(ctx, exp, *exp_idx, LYXP_TOKEN_PAR2, 1)) {
2341         return -1;
2342     }
2343     ++(*exp_idx);
2344 
2345     if ((arg_count < min_arg_count) || (arg_count > max_arg_count)) {
2346         LOGVAL(ctx, LYE_XPATH_INARGCOUNT, LY_VLOG_NONE, NULL, arg_count, exp->tok_len[func_exp_idx],
2347                &exp->expr[exp->expr_pos[func_exp_idx]]);
2348         return -1;
2349     }
2350 
2351     return EXIT_SUCCESS;
2352 }
2353 
2354 /**
2355  * @brief Reparse PathExpr. Logs directly on error.
2356  *
2357  * [10] PathExpr ::= LocationPath | PrimaryExpr Predicate*
2358  *                 | PrimaryExpr Predicate* '/' RelativeLocationPath
2359  *                 | PrimaryExpr Predicate* '//' RelativeLocationPath
2360  * [2] LocationPath ::= RelativeLocationPath | AbsoluteLocationPath
2361  * [8] PrimaryExpr ::= '(' Expr ')' | Literal | Number | FunctionCall
2362  *
2363  * @param[in] exp Parsed XPath expression.
2364  * @param[in] exp_idx Position in the expression \p exp.
2365  *
2366  * @return EXIT_SUCCESS on success, -1 on error.
2367  */
2368 static int
reparse_path_expr(struct ly_ctx * ctx,struct lyxp_expr * exp,uint16_t * exp_idx)2369 reparse_path_expr(struct ly_ctx *ctx, struct lyxp_expr *exp, uint16_t *exp_idx)
2370 {
2371     if (exp_check_token(ctx, exp, *exp_idx, LYXP_TOKEN_NONE, 1)) {
2372         return -1;
2373     }
2374 
2375     switch (exp->tokens[*exp_idx]) {
2376     case LYXP_TOKEN_PAR1:
2377         /* '(' Expr ')' Predicate* */
2378         ++(*exp_idx);
2379 
2380         if (reparse_or_expr(ctx, exp, exp_idx)) {
2381             return -1;
2382         }
2383 
2384         if (exp_check_token(ctx, exp, *exp_idx, LYXP_TOKEN_PAR2, 1)) {
2385             return -1;
2386         }
2387         ++(*exp_idx);
2388         goto predicate;
2389         break;
2390     case LYXP_TOKEN_DOT:
2391     case LYXP_TOKEN_DDOT:
2392     case LYXP_TOKEN_AT:
2393     case LYXP_TOKEN_NAMETEST:
2394     case LYXP_TOKEN_NODETYPE:
2395         /* RelativeLocationPath */
2396         if (reparse_relative_location_path(ctx, exp, exp_idx)) {
2397             return -1;
2398         }
2399         break;
2400     case LYXP_TOKEN_FUNCNAME:
2401         /* FunctionCall */
2402         if (reparse_function_call(ctx, exp, exp_idx)) {
2403             return -1;
2404         }
2405         goto predicate;
2406         break;
2407     case LYXP_TOKEN_OPERATOR_PATH:
2408         /* AbsoluteLocationPath */
2409         if (reparse_absolute_location_path(ctx, exp, exp_idx)) {
2410             return -1;
2411         }
2412         break;
2413     case LYXP_TOKEN_LITERAL:
2414         /* Literal */
2415         ++(*exp_idx);
2416         goto predicate;
2417         break;
2418     case LYXP_TOKEN_NUMBER:
2419         /* Number */
2420         ++(*exp_idx);
2421         goto predicate;
2422         break;
2423     default:
2424         LOGVAL(ctx, LYE_XPATH_INTOK, LY_VLOG_NONE, NULL,
2425                print_token(exp->tokens[*exp_idx]), &exp->expr[exp->expr_pos[*exp_idx]]);
2426         return -1;
2427     }
2428 
2429     return EXIT_SUCCESS;
2430 
2431 predicate:
2432     /* Predicate* */
2433     while ((exp->used > *exp_idx) && (exp->tokens[*exp_idx] == LYXP_TOKEN_BRACK1)) {
2434         if (reparse_predicate(ctx, exp, exp_idx)) {
2435             return -1;
2436         }
2437     }
2438 
2439     /* ('/' or '//') RelativeLocationPath */
2440     if ((exp->used > *exp_idx) && (exp->tokens[*exp_idx] == LYXP_TOKEN_OPERATOR_PATH)) {
2441 
2442         /* '/' or '//' */
2443         ++(*exp_idx);
2444 
2445         if (reparse_relative_location_path(ctx, exp, exp_idx)) {
2446             return -1;
2447         }
2448     }
2449 
2450     return EXIT_SUCCESS;
2451 }
2452 
2453 /**
2454  * @brief Reparse UnaryExpr. Logs directly on error.
2455  *
2456  * [17] UnaryExpr ::= UnionExpr | '-' UnaryExpr
2457  * [18] UnionExpr ::= PathExpr | UnionExpr '|' PathExpr
2458  *
2459  * @param[in] exp Parsed XPath expression.
2460  * @param[in] exp_idx Position in the expression \p exp.
2461  *
2462  * @return EXIT_SUCCESS on success, -1 on error.
2463  */
2464 static int
reparse_unary_expr(struct ly_ctx * ctx,struct lyxp_expr * exp,uint16_t * exp_idx)2465 reparse_unary_expr(struct ly_ctx *ctx, struct lyxp_expr *exp, uint16_t *exp_idx)
2466 {
2467     uint16_t prev_exp;
2468 
2469     /* ('-')* */
2470     prev_exp = *exp_idx;
2471     while (!exp_check_token(ctx, exp, *exp_idx, LYXP_TOKEN_OPERATOR_MATH, 0)
2472             && (exp->expr[exp->expr_pos[*exp_idx]] == '-')) {
2473         exp_repeat_push(exp, prev_exp, LYXP_EXPR_UNARY);
2474         ++(*exp_idx);
2475     }
2476 
2477     /* PathExpr */
2478     prev_exp = *exp_idx;
2479     if (reparse_path_expr(ctx, exp, exp_idx)) {
2480         return -1;
2481     }
2482 
2483     /* ('|' PathExpr)* */
2484     while (!exp_check_token(ctx, exp, *exp_idx, LYXP_TOKEN_OPERATOR_UNI, 0)) {
2485         exp_repeat_push(exp, prev_exp, LYXP_EXPR_UNION);
2486         ++(*exp_idx);
2487 
2488         if (reparse_path_expr(ctx, exp, exp_idx)) {
2489             return -1;
2490         }
2491     }
2492 
2493     return EXIT_SUCCESS;
2494 }
2495 
2496 /**
2497  * @brief Reparse AdditiveExpr. Logs directly on error.
2498  *
2499  * [15] AdditiveExpr ::= MultiplicativeExpr
2500  *                     | AdditiveExpr '+' MultiplicativeExpr
2501  *                     | AdditiveExpr '-' MultiplicativeExpr
2502  * [16] MultiplicativeExpr ::= UnaryExpr
2503  *                     | MultiplicativeExpr '*' UnaryExpr
2504  *                     | MultiplicativeExpr 'div' UnaryExpr
2505  *                     | MultiplicativeExpr 'mod' UnaryExpr
2506  *
2507  *
2508  * @param[in] exp Parsed XPath expression.
2509  * @param[in] exp_idx Position in the expression \p exp.
2510  *
2511  * @return EXIT_SUCCESS on success, -1 on error.
2512  */
2513 static int
reparse_additive_expr(struct ly_ctx * ctx,struct lyxp_expr * exp,uint16_t * exp_idx)2514 reparse_additive_expr(struct ly_ctx *ctx, struct lyxp_expr *exp, uint16_t *exp_idx)
2515 {
2516     uint16_t prev_add_exp, prev_mul_exp;
2517 
2518     prev_add_exp = *exp_idx;
2519     goto reparse_multiplicative_expr;
2520 
2521     /* ('+' / '-' MultiplicativeExpr)* */
2522     while (!exp_check_token(ctx, exp, *exp_idx, LYXP_TOKEN_OPERATOR_MATH, 0)
2523             && ((exp->expr[exp->expr_pos[*exp_idx]] == '+') || (exp->expr[exp->expr_pos[*exp_idx]] == '-'))) {
2524         exp_repeat_push(exp, prev_add_exp, LYXP_EXPR_ADDITIVE);
2525         ++(*exp_idx);
2526 
2527 reparse_multiplicative_expr:
2528         /* UnaryExpr */
2529         prev_mul_exp = *exp_idx;
2530         if (reparse_unary_expr(ctx, exp, exp_idx)) {
2531             return -1;
2532         }
2533 
2534         /* ('*' / 'div' / 'mod' UnaryExpr)* */
2535         while (!exp_check_token(ctx, exp, *exp_idx, LYXP_TOKEN_OPERATOR_MATH, 0)
2536                 && ((exp->expr[exp->expr_pos[*exp_idx]] == '*') || (exp->tok_len[*exp_idx] == 3))) {
2537             exp_repeat_push(exp, prev_mul_exp, LYXP_EXPR_MULTIPLICATIVE);
2538             ++(*exp_idx);
2539 
2540             if (reparse_unary_expr(ctx, exp, exp_idx)) {
2541                 return -1;
2542             }
2543         }
2544     }
2545 
2546     return EXIT_SUCCESS;
2547 }
2548 
2549 /**
2550  * @brief Reparse EqualityExpr. Logs directly on error.
2551  *
2552  * [13] EqualityExpr ::= RelationalExpr | EqualityExpr '=' RelationalExpr
2553  *                     | EqualityExpr '!=' RelationalExpr
2554  * [14] RelationalExpr ::= AdditiveExpr
2555  *                       | RelationalExpr '<' AdditiveExpr
2556  *                       | RelationalExpr '>' AdditiveExpr
2557  *                       | RelationalExpr '<=' AdditiveExpr
2558  *                       | RelationalExpr '>=' AdditiveExpr
2559  *
2560  * @param[in] exp Parsed XPath expression.
2561  * @param[in] exp_idx Position in the expression \p exp.
2562  *
2563  * @return EXIT_SUCCESS on success, -1 on error.
2564  */
2565 static int
reparse_equality_expr(struct ly_ctx * ctx,struct lyxp_expr * exp,uint16_t * exp_idx)2566 reparse_equality_expr(struct ly_ctx *ctx, struct lyxp_expr *exp, uint16_t *exp_idx)
2567 {
2568     uint16_t prev_eq_exp, prev_rel_exp;
2569 
2570     prev_eq_exp = *exp_idx;
2571     goto reparse_additive_expr;
2572 
2573     /* ('=' / '!=' RelationalExpr)* */
2574     while (!exp_check_token(ctx, exp, *exp_idx, LYXP_TOKEN_OPERATOR_COMP, 0)
2575             && ((exp->expr[exp->expr_pos[*exp_idx]] == '=') || (exp->expr[exp->expr_pos[*exp_idx]] == '!'))) {
2576         exp_repeat_push(exp, prev_eq_exp, LYXP_EXPR_EQUALITY);
2577         ++(*exp_idx);
2578 
2579 reparse_additive_expr:
2580         /* AdditiveExpr */
2581         prev_rel_exp = *exp_idx;
2582         if (reparse_additive_expr(ctx, exp, exp_idx)) {
2583             return -1;
2584         }
2585 
2586         /* ('<' / '>' / '<=' / '>=' AdditiveExpr)* */
2587         while (!exp_check_token(ctx, exp, *exp_idx, LYXP_TOKEN_OPERATOR_COMP, 0)
2588                 && ((exp->expr[exp->expr_pos[*exp_idx]] == '<') || (exp->expr[exp->expr_pos[*exp_idx]] == '>'))) {
2589             exp_repeat_push(exp, prev_rel_exp, LYXP_EXPR_RELATIONAL);
2590             ++(*exp_idx);
2591 
2592             if (reparse_additive_expr(ctx, exp, exp_idx)) {
2593                 return -1;
2594             }
2595         }
2596     }
2597 
2598     return EXIT_SUCCESS;
2599 }
2600 
2601 /**
2602  * @brief Reparse OrExpr. Logs directly on error.
2603  *
2604  * [11] OrExpr ::= AndExpr | OrExpr 'or' AndExpr
2605  * [12] AndExpr ::= EqualityExpr | AndExpr 'and' EqualityExpr
2606  *
2607  * @param[in] exp Parsed XPath expression.
2608  * @param[in] exp_idx Position in the expression \p exp.
2609  *
2610  * @return EXIT_SUCCESS on success, -1 on error.
2611  */
2612 static int
reparse_or_expr(struct ly_ctx * ctx,struct lyxp_expr * exp,uint16_t * exp_idx)2613 reparse_or_expr(struct ly_ctx *ctx, struct lyxp_expr *exp, uint16_t *exp_idx)
2614 {
2615     uint16_t prev_or_exp, prev_and_exp;
2616 
2617     prev_or_exp = *exp_idx;
2618     goto reparse_equality_expr;
2619 
2620     /* ('or' AndExpr)* */
2621     while (!exp_check_token(ctx, exp, *exp_idx, LYXP_TOKEN_OPERATOR_LOG, 0) && (exp->tok_len[*exp_idx] == 2)) {
2622         exp_repeat_push(exp, prev_or_exp, LYXP_EXPR_OR);
2623         ++(*exp_idx);
2624 
2625 reparse_equality_expr:
2626         /* EqualityExpr */
2627         prev_and_exp = *exp_idx;
2628         if (reparse_equality_expr(ctx, exp, exp_idx)) {
2629             return -1;
2630         }
2631 
2632         /* ('and' EqualityExpr)* */
2633         while (!exp_check_token(ctx, exp, *exp_idx, LYXP_TOKEN_OPERATOR_LOG, 0) && (exp->tok_len[*exp_idx] == 3)) {
2634             exp_repeat_push(exp, prev_and_exp, LYXP_EXPR_AND);
2635             ++(*exp_idx);
2636 
2637             if (reparse_equality_expr(ctx, exp, exp_idx)) {
2638                 return -1;
2639             }
2640         }
2641     }
2642 
2643     return EXIT_SUCCESS;
2644 }
2645 
2646 /**
2647  * @brief Parse NCName.
2648  *
2649  * @param[in] ncname Name to parse.
2650  *
2651  * @return Length of \p ncname valid characters.
2652  */
2653 static uint16_t
parse_ncname(struct ly_ctx * ctx,const char * ncname)2654 parse_ncname(struct ly_ctx *ctx, const char *ncname)
2655 {
2656     uint16_t parsed = 0;
2657     int uc;
2658     unsigned int size;
2659 
2660     uc = lyxml_getutf8(ctx, &ncname[parsed], &size);
2661     if (!is_xmlnamestartchar(uc) || (uc == ':')) {
2662        return parsed;
2663     }
2664 
2665     do {
2666         if ((unsigned)UINT16_MAX - parsed < size) {
2667             LOGERR(ctx, LY_EINVAL, "XPath name cannot be longer than %ud characters.", UINT16_MAX);
2668             return 0;
2669         }
2670         parsed += size;
2671         if (!ncname[parsed]) {
2672             break;
2673         }
2674         uc = lyxml_getutf8(ctx, &ncname[parsed], &size);
2675     } while (is_xmlnamechar(uc) && (uc != ':'));
2676 
2677     return parsed;
2678 }
2679 
2680 struct lyxp_expr *
lyxp_parse_expr(struct ly_ctx * ctx,const char * expr)2681 lyxp_parse_expr(struct ly_ctx *ctx, const char *expr)
2682 {
2683     struct lyxp_expr *ret;
2684     uint16_t parsed = 0, tok_len, ncname_len;
2685     enum lyxp_token tok_type;
2686     int prev_function_check = 0;
2687 
2688     if (strlen(expr) > UINT16_MAX) {
2689         LOGERR(ctx, LY_EINVAL, "XPath expression cannot be longer than %ud characters.", UINT16_MAX);
2690         return NULL;
2691     }
2692 
2693     /* init lyxp_expr structure */
2694     ret = calloc(1, sizeof *ret);
2695     LY_CHECK_ERR_GOTO(!ret, LOGMEM(ctx), error);
2696     ret->expr = strdup(expr);
2697     LY_CHECK_ERR_GOTO(!ret->expr, LOGMEM(ctx), error);
2698     ret->used = 0;
2699     ret->size = LYXP_EXPR_SIZE_START;
2700     ret->tokens = malloc(ret->size * sizeof *ret->tokens);
2701     LY_CHECK_ERR_GOTO(!ret->tokens, LOGMEM(ctx), error);
2702 
2703     ret->expr_pos = malloc(ret->size * sizeof *ret->expr_pos);
2704     LY_CHECK_ERR_GOTO(!ret->expr_pos, LOGMEM(ctx), error);
2705 
2706     ret->tok_len = malloc(ret->size * sizeof *ret->tok_len);
2707     LY_CHECK_ERR_GOTO(!ret->tok_len, LOGMEM(ctx), error);
2708 
2709     while (is_xmlws(expr[parsed])) {
2710         ++parsed;
2711     }
2712 
2713     do {
2714         if (expr[parsed] == '(') {
2715 
2716             /* '(' */
2717             tok_len = 1;
2718             tok_type = LYXP_TOKEN_PAR1;
2719 
2720             if (prev_function_check && ret->used && (ret->tokens[ret->used - 1] == LYXP_TOKEN_NAMETEST)) {
2721                 /* it is a NodeType/FunctionName after all */
2722                 if (((ret->tok_len[ret->used - 1] == 4)
2723                         && (!strncmp(&expr[ret->expr_pos[ret->used - 1]], "node", 4)
2724                         || !strncmp(&expr[ret->expr_pos[ret->used - 1]], "text", 4))) ||
2725                         ((ret->tok_len[ret->used - 1] == 7)
2726                         && !strncmp(&expr[ret->expr_pos[ret->used - 1]], "comment", 7))) {
2727                     ret->tokens[ret->used - 1] = LYXP_TOKEN_NODETYPE;
2728                 } else {
2729                     ret->tokens[ret->used - 1] = LYXP_TOKEN_FUNCNAME;
2730                 }
2731                 prev_function_check = 0;
2732             }
2733 
2734         } else if (expr[parsed] == ')') {
2735 
2736             /* ')' */
2737             tok_len = 1;
2738             tok_type = LYXP_TOKEN_PAR2;
2739 
2740         } else if (expr[parsed] == '[') {
2741 
2742             /* '[' */
2743             tok_len = 1;
2744             tok_type = LYXP_TOKEN_BRACK1;
2745 
2746         } else if (expr[parsed] == ']') {
2747 
2748             /* ']' */
2749             tok_len = 1;
2750             tok_type = LYXP_TOKEN_BRACK2;
2751 
2752         } else if (!strncmp(&expr[parsed], "..", 2)) {
2753 
2754             /* '..' */
2755             tok_len = 2;
2756             tok_type = LYXP_TOKEN_DDOT;
2757 
2758         } else if ((expr[parsed] == '.') && (!isdigit(expr[parsed + 1]))) {
2759 
2760             /* '.' */
2761             tok_len = 1;
2762             tok_type = LYXP_TOKEN_DOT;
2763 
2764         } else if (expr[parsed] == '@') {
2765 
2766             /* '@' */
2767             tok_len = 1;
2768             tok_type = LYXP_TOKEN_AT;
2769 
2770         } else if (expr[parsed] == ',') {
2771 
2772             /* ',' */
2773             tok_len = 1;
2774             tok_type = LYXP_TOKEN_COMMA;
2775 
2776         } else if (expr[parsed] == '\'') {
2777 
2778             /* Literal with ' */
2779             for (tok_len = 1; (expr[parsed + tok_len] != '\0') && (expr[parsed + tok_len] != '\''); ++tok_len);
2780             if (expr[parsed + tok_len] == '\0') {
2781                 LOGVAL(ctx, LYE_XPATH_NOEND, LY_VLOG_NONE, NULL, expr[parsed], &expr[parsed]);
2782                 goto error;
2783             }
2784             ++tok_len;
2785             tok_type = LYXP_TOKEN_LITERAL;
2786 
2787         } else if (expr[parsed] == '\"') {
2788 
2789             /* Literal with " */
2790             for (tok_len = 1; (expr[parsed + tok_len] != '\0') && (expr[parsed + tok_len] != '\"'); ++tok_len);
2791             if (expr[parsed + tok_len] == '\0') {
2792                 LOGVAL(ctx, LYE_XPATH_NOEND, LY_VLOG_NONE, NULL, expr[parsed], &expr[parsed]);
2793                 goto error;
2794             }
2795             ++tok_len;
2796             tok_type = LYXP_TOKEN_LITERAL;
2797 
2798         } else if ((expr[parsed] == '.') || (isdigit(expr[parsed]))) {
2799 
2800             /* Number */
2801             for (tok_len = 0; isdigit(expr[parsed + tok_len]); ++tok_len);
2802             if (expr[parsed + tok_len] == '.') {
2803                 ++tok_len;
2804                 for (; isdigit(expr[parsed + tok_len]); ++tok_len);
2805             }
2806             tok_type = LYXP_TOKEN_NUMBER;
2807 
2808         } else if (expr[parsed] == '/') {
2809 
2810             /* Operator '/', '//' */
2811             if (!strncmp(&expr[parsed], "//", 2)) {
2812                 tok_len = 2;
2813             } else {
2814                 tok_len = 1;
2815             }
2816             tok_type = LYXP_TOKEN_OPERATOR_PATH;
2817 
2818         } else if  (!strncmp(&expr[parsed], "!=", 2) || !strncmp(&expr[parsed], "<=", 2)
2819                 || !strncmp(&expr[parsed], ">=", 2)) {
2820 
2821             /* Operator '!=', '<=', '>=' */
2822             tok_len = 2;
2823             tok_type = LYXP_TOKEN_OPERATOR_COMP;
2824 
2825         } else if (expr[parsed] == '|') {
2826 
2827             /* Operator '|' */
2828             tok_len = 1;
2829             tok_type = LYXP_TOKEN_OPERATOR_UNI;
2830 
2831         } else if ((expr[parsed] == '+') || (expr[parsed] == '-')) {
2832 
2833             /* Operator '+', '-' */
2834             tok_len = 1;
2835             tok_type = LYXP_TOKEN_OPERATOR_MATH;
2836 
2837         } else if ((expr[parsed] == '=') || (expr[parsed] == '<') || (expr[parsed] == '>')) {
2838 
2839             /* Operator '=', '<', '>' */
2840             tok_len = 1;
2841             tok_type = LYXP_TOKEN_OPERATOR_COMP;
2842 
2843         } else if (ret->used && (ret->tokens[ret->used - 1] != LYXP_TOKEN_AT)
2844                 && (ret->tokens[ret->used - 1] != LYXP_TOKEN_PAR1)
2845                 && (ret->tokens[ret->used - 1] != LYXP_TOKEN_BRACK1)
2846                 && (ret->tokens[ret->used - 1] != LYXP_TOKEN_COMMA)
2847                 && (ret->tokens[ret->used - 1] != LYXP_TOKEN_OPERATOR_LOG)
2848                 && (ret->tokens[ret->used - 1] != LYXP_TOKEN_OPERATOR_COMP)
2849                 && (ret->tokens[ret->used - 1] != LYXP_TOKEN_OPERATOR_MATH)
2850                 && (ret->tokens[ret->used - 1] != LYXP_TOKEN_OPERATOR_UNI)
2851                 && (ret->tokens[ret->used - 1] != LYXP_TOKEN_OPERATOR_PATH)) {
2852 
2853             /* Operator '*', 'or', 'and', 'mod', or 'div' */
2854             if (expr[parsed] == '*') {
2855                 tok_len = 1;
2856                 tok_type = LYXP_TOKEN_OPERATOR_MATH;
2857 
2858             } else if (!strncmp(&expr[parsed], "or", 2)) {
2859                 tok_len = 2;
2860                 tok_type = LYXP_TOKEN_OPERATOR_LOG;
2861 
2862             } else if (!strncmp(&expr[parsed], "and", 3)) {
2863                 tok_len = 3;
2864                 tok_type = LYXP_TOKEN_OPERATOR_LOG;
2865 
2866             } else if (!strncmp(&expr[parsed], "mod", 3) || !strncmp(&expr[parsed], "div", 3)) {
2867                 tok_len = 3;
2868                 tok_type = LYXP_TOKEN_OPERATOR_MATH;
2869 
2870             } else {
2871                 LOGVAL(ctx, LYE_INCHAR, LY_VLOG_NONE, NULL, expr[parsed], &expr[parsed]);
2872                 if (prev_function_check) {
2873                     LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Perhaps \"%.*s\" is supposed to be a function call.",
2874                            ret->tok_len[ret->used - 1], &ret->expr[ret->expr_pos[ret->used - 1]]);
2875                 }
2876                 goto error;
2877             }
2878         } else if (expr[parsed] == '*') {
2879 
2880             /* NameTest '*' */
2881             tok_len = 1;
2882             tok_type = LYXP_TOKEN_NAMETEST;
2883 
2884         } else {
2885 
2886             /* NameTest (NCName ':' '*' | QName) or NodeType/FunctionName */
2887             ncname_len = parse_ncname(ctx, &expr[parsed]);
2888             if (!ncname_len) {
2889                 LOGVAL(ctx, LYE_INCHAR, LY_VLOG_NONE, NULL, expr[parsed], &expr[parsed]);
2890                 goto error;
2891             }
2892             tok_len = ncname_len;
2893 
2894             if (expr[parsed + tok_len] == ':') {
2895                 ++tok_len;
2896                 if (expr[parsed + tok_len] == '*') {
2897                     ++tok_len;
2898                 } else {
2899                     ncname_len = parse_ncname(ctx, &expr[parsed + tok_len]);
2900                     if (!ncname_len) {
2901                         LOGVAL(ctx, LYE_INCHAR, LY_VLOG_NONE, NULL, expr[parsed], &expr[parsed]);
2902                         goto error;
2903                     }
2904                     tok_len += ncname_len;
2905                 }
2906                 /* remove old flag to prevent ambiguities */
2907                 prev_function_check = 0;
2908                 tok_type = LYXP_TOKEN_NAMETEST;
2909             } else {
2910                 /* there is no prefix so it can still be NodeType/FunctionName, we can't finally decide now */
2911                 prev_function_check = 1;
2912                 tok_type = LYXP_TOKEN_NAMETEST;
2913             }
2914         }
2915 
2916         /* store the token, move on to the next one */
2917         if (exp_add_token(ret, tok_type, parsed, tok_len)) {
2918             goto error;
2919         }
2920         parsed += tok_len;
2921         while (is_xmlws(expr[parsed])) {
2922             ++parsed;
2923         }
2924 
2925     } while (expr[parsed]);
2926 
2927     /* prealloc repeat */
2928     ret->repeat = calloc(ret->size, sizeof *ret->repeat);
2929     LY_CHECK_ERR_GOTO(!ret->repeat, LOGMEM(ctx), error);
2930 
2931     return ret;
2932 
2933 error:
2934     lyxp_expr_free(ret);
2935     return NULL;
2936 }
2937 
2938 /*
2939  * warn functions
2940  *
2941  * Warn functions check specific reasonable conditions for schema XPath
2942  * and print a warning if they are not satisfied.
2943  */
2944 
2945 /**
2946  * @brief Get the last-added schema node that is currently in the context.
2947  *
2948  * @param[in] set Set to search in.
2949  *
2950  * @return Last-added schema context node, NULL if no node is in context.
2951  */
2952 static struct lys_node *
warn_get_snode_in_ctx(struct lyxp_set * set)2953 warn_get_snode_in_ctx(struct lyxp_set *set)
2954 {
2955     uint32_t i;
2956 
2957     if (!set || (set->type != LYXP_SET_SNODE_SET)) {
2958         return NULL;
2959     }
2960 
2961     i = set->used;
2962     do {
2963         --i;
2964         if (set->val.snodes[i].in_ctx == 1) {
2965             /* if there are more, simply return the first found (last added) */
2966             return set->val.snodes[i].snode;
2967         }
2968     } while (i);
2969 
2970     return NULL;
2971 }
2972 
2973 /**
2974  * @brief Test whether a type is numeric - integer type or decimal64.
2975  *
2976  * @return 1 if numeric, 0 otherwise.
2977  */
2978 static int
warn_is_numeric_type(struct lys_type * type)2979 warn_is_numeric_type(struct lys_type *type)
2980 {
2981     struct lys_node *node;
2982     struct lys_type *t = NULL;
2983     int found = 0, ret;
2984 
2985     switch (type->base) {
2986     case LY_TYPE_DEC64:
2987     case LY_TYPE_INT8:
2988     case LY_TYPE_UINT8:
2989     case LY_TYPE_INT16:
2990     case LY_TYPE_UINT16:
2991     case LY_TYPE_INT32:
2992     case LY_TYPE_UINT32:
2993     case LY_TYPE_INT64:
2994     case LY_TYPE_UINT64:
2995         return 1;
2996     case LY_TYPE_UNION:
2997         while ((t = lyp_get_next_union_type(type, t, &found))) {
2998             found = 0;
2999             ret = warn_is_numeric_type(t);
3000             if (ret) {
3001                 /* found a suitable type */
3002                 return 1;
3003             }
3004         }
3005         /* did not find any suitable type */
3006         return 0;
3007     case LY_TYPE_LEAFREF:
3008         if (!type->info.lref.target) {
3009             /* we may be in a grouping (and not directly in a typedef) */
3010             assert(&((struct lys_node_leaf *)type->parent)->type == type);
3011             for (node = ((struct lys_node *)type->parent); node && (node->nodetype != LYS_GROUPING); node = node->parent);
3012             if (!node) {
3013                 LOGINT(((struct lys_node *)type->parent)->module->ctx);
3014             }
3015             return 0;
3016         }
3017         return warn_is_numeric_type(&type->info.lref.target->type);
3018     default:
3019         return 0;
3020     }
3021 }
3022 
3023 /**
3024  * @brief Test whether a type is string-like - no integers, decimal64 or binary.
3025  *
3026  * @return 1 if string, 0 otherwise.
3027  */
3028 static int
warn_is_string_type(struct lys_type * type)3029 warn_is_string_type(struct lys_type *type)
3030 {
3031     struct lys_type *t = NULL;
3032     int found = 0, ret;
3033 
3034     switch (type->base) {
3035     case LY_TYPE_BITS:
3036     case LY_TYPE_ENUM:
3037     case LY_TYPE_IDENT:
3038     case LY_TYPE_INST:
3039     case LY_TYPE_STRING:
3040         return 1;
3041     case LY_TYPE_UNION:
3042         while ((t = lyp_get_next_union_type(type, t, &found))) {
3043             found = 0;
3044             ret = warn_is_string_type(t);
3045             if (ret) {
3046                 /* found a suitable type */
3047                 return 1;
3048             }
3049         }
3050         /* did not find any suitable type */
3051         return 0;
3052     case LY_TYPE_LEAFREF:
3053         if (!type->info.lref.target) {
3054             /* we are in a grouping */
3055             return 0;
3056         }
3057         return warn_is_string_type(&type->info.lref.target->type);
3058     default:
3059         return 0;
3060     }
3061 }
3062 
3063 /**
3064  * @brief Test whether a type is one specific type.
3065  *
3066  * @return 1 if it is, 0 otherwise.
3067  */
3068 static int
warn_is_specific_type(struct lys_type * type,LY_DATA_TYPE base)3069 warn_is_specific_type(struct lys_type *type, LY_DATA_TYPE base)
3070 {
3071     struct lys_type *t = NULL;
3072     int found = 0, ret;
3073 
3074     if (type->base == base) {
3075         return 1;
3076     } else if (type->base == LY_TYPE_UNION) {
3077         while ((t = lyp_get_next_union_type(type, t, &found))) {
3078             found = 0;
3079             ret = warn_is_specific_type(t, base);
3080             if (ret) {
3081                 /* found a suitable type */
3082                 return 1;
3083             }
3084         }
3085         /* did not find any suitable type */
3086         return 0;
3087     } else if (type->base == LY_TYPE_LEAFREF) {
3088         if (!type->info.lref.target) {
3089             /* we are in a grouping */
3090             return 1;
3091         }
3092         return warn_is_specific_type(&type->info.lref.target->type, base);
3093     }
3094 
3095     return 0;
3096 }
3097 
3098 static struct lys_type *
warn_is_equal_type_next_type(struct lys_type * type,struct lys_type * prev_type)3099 warn_is_equal_type_next_type(struct lys_type *type, struct lys_type *prev_type)
3100 {
3101     int found = 0;
3102 
3103     switch (type->base) {
3104     case LY_TYPE_UNION:
3105         /* this can, unfortunately, return leafref */
3106         return lyp_get_next_union_type(type, prev_type, &found);
3107     case LY_TYPE_LEAFREF:
3108         if (!type->info.lref.target) {
3109             /* we are in a grouping */
3110             return type;
3111         }
3112         return warn_is_equal_type_next_type(&type->info.lref.target->type, prev_type);
3113     default:
3114         if (prev_type) {
3115             assert(type == prev_type);
3116             return NULL;
3117         } else {
3118             return type;
3119         }
3120     }
3121 }
3122 
3123 /**
3124  * @brief Test whether 2 types have a common type.
3125  *
3126  * @return 1 if they do, 0 otherwise.
3127  */
3128 static int
warn_is_equal_type(struct lys_type * type1,struct lys_type * type2)3129 warn_is_equal_type(struct lys_type *type1, struct lys_type *type2)
3130 {
3131     struct lys_type *t1, *t2;
3132 
3133     t1 = NULL;
3134     while ((t1 = warn_is_equal_type_next_type(type1, t1))) {
3135         if (t1->base == LY_TYPE_LEAFREF) {
3136             /* we do not check unions with leafrefs, that is just too much... */
3137             return 1;
3138         }
3139 
3140         t2 = NULL;
3141         while ((t2 = warn_is_equal_type_next_type(type2, t2))) {
3142             if (t2->base == LY_TYPE_LEAFREF) {
3143                 return 1;
3144             }
3145 
3146             if (t2->base == t1->base) {
3147                 /* match found */
3148                 return 1;
3149             }
3150         }
3151     }
3152 
3153     return 0;
3154 }
3155 
3156 /**
3157  * @brief Check both operands of comparison operators.
3158  *
3159  * @param[in] ctx Context for errors.
3160  * @param[in] set1 First operand set.
3161  * @param[in] set2 Second operand set.
3162  * @param[in] numbers_only Whether accept only numbers or other types are fine too (for '=' and '!=').
3163  * @param[in] expr Start of the expression to print with the warning.
3164  */
3165 static void
warn_operands(struct ly_ctx * ctx,struct lyxp_set * set1,struct lyxp_set * set2,int numbers_only,const char * expr,uint16_t expr_pos)3166 warn_operands(struct ly_ctx *ctx, struct lyxp_set *set1, struct lyxp_set *set2, int numbers_only, const char *expr, uint16_t expr_pos)
3167 {
3168     struct lys_node_leaf *node1, *node2;
3169     int leaves = 1, warning = 0;
3170 
3171     node1 = (struct lys_node_leaf *)warn_get_snode_in_ctx(set1);
3172     node2 = (struct lys_node_leaf *)warn_get_snode_in_ctx(set2);
3173 
3174     if (!node1 && !node2) {
3175         /* no node-sets involved, nothing to do */
3176         return;
3177     }
3178 
3179     if (node1) {
3180         if (!(node1->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
3181             LOGWRN(ctx, "Node type %s \"%s\" used as operand.", strnodetype(node1->nodetype), node1->name);
3182             warning = 1;
3183             leaves = 0;
3184         } else if (numbers_only && !warn_is_numeric_type(&node1->type)) {
3185             LOGWRN(ctx, "Node \"%s\" is not of a numeric type, but used where it was expected.", node1->name);
3186             warning = 1;
3187         }
3188     }
3189 
3190     if (node2) {
3191         if (!(node2->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
3192             LOGWRN(ctx, "Node type %s \"%s\" used as operand.", strnodetype(node2->nodetype), node2->name);
3193             warning = 1;
3194             leaves = 0;
3195         } else if (numbers_only && !warn_is_numeric_type(&node2->type)) {
3196             LOGWRN(ctx, "Node \"%s\" is not of a numeric type, but used where it was expected.", node2->name);
3197             warning = 1;
3198         }
3199     }
3200 
3201     if (node1 && node2 && leaves && !numbers_only) {
3202         if ((warn_is_numeric_type(&node1->type) && !warn_is_numeric_type(&node2->type))
3203                 || (!warn_is_numeric_type(&node1->type) && warn_is_numeric_type(&node2->type))
3204                 || (!warn_is_numeric_type(&node1->type) && !warn_is_numeric_type(&node2->type)
3205                 && !warn_is_equal_type(&node1->type, &node2->type))) {
3206             LOGWRN(ctx, "Incompatible types of operands \"%s\" and \"%s\" for comparison.", node1->name, node2->name);
3207             warning = 1;
3208         }
3209     }
3210 
3211     if (warning) {
3212         LOGWRN(ctx, "Previous warning generated by XPath subexpression[%u] \"%.20s\".", expr_pos, expr + expr_pos);
3213     }
3214 }
3215 
3216 /**
3217  * @brief Check that a value is valid for a leaf. If not applicable, does nothing.
3218  *
3219  * @param[in] ctx Context for errors.
3220  * @param[in] exp Parsed XPath expression.
3221  * @param[in] set Set with the leaf/leaf-list.
3222  * @param[in] local_mod Local modolue of any prefixes in the value.
3223  * @param[in] val_exp Index of the value (literal/number) in \p exp.
3224  * @param[in] equal_exp Index of the start of the equality expression in \p exp.
3225  * @param[in] last_equal_exp Index of the end of the equality expression in \p exp.
3226  */
3227 static void
warn_equality_value(struct ly_ctx * ctx,struct lyxp_expr * exp,struct lyxp_set * set,struct lys_module * local_mod,uint16_t val_exp,uint16_t equal_exp,uint16_t last_equal_exp)3228 warn_equality_value(struct ly_ctx *ctx, struct lyxp_expr *exp, struct lyxp_set *set, struct lys_module *local_mod,
3229                     uint16_t val_exp, uint16_t equal_exp, uint16_t last_equal_exp)
3230 {
3231     struct lys_node *snode;
3232     char *value;
3233     int ret;
3234     enum int_log_opts prev_ilo;
3235 
3236     if ((snode = warn_get_snode_in_ctx(set)) && (snode->nodetype & (LYS_LEAF | LYS_LEAFLIST))
3237             && ((exp->tokens[val_exp] == LYXP_TOKEN_LITERAL) || (exp->tokens[val_exp] == LYXP_TOKEN_NUMBER))) {
3238         /* check that the node can have the specified value */
3239         if (exp->tokens[val_exp] == LYXP_TOKEN_LITERAL) {
3240             value = strndup(exp->expr + exp->expr_pos[val_exp] + 1, exp->tok_len[val_exp] - 2);
3241         } else {
3242             value = strndup(exp->expr + exp->expr_pos[val_exp], exp->tok_len[val_exp]);
3243         }
3244         if (!value) {
3245             LOGMEM(ctx);
3246             return;
3247         }
3248 
3249         if ((((struct lys_node_leaf *)snode)->type.base == LY_TYPE_IDENT) && !strchr(value, ':')) {
3250             LOGWRN(ctx, "Identityref \"%s\" comparison with identity \"%s\" without prefix, consider adding"
3251                    " a prefix or best using \"derived-from(-or-self)()\" functions.", snode->name, value);
3252             LOGWRN(ctx, "Previous warning generated by XPath subexpression[%u] \"%.*s\".", exp->expr_pos[equal_exp],
3253                    (exp->expr_pos[last_equal_exp] - exp->expr_pos[equal_exp]) + exp->tok_len[last_equal_exp],
3254                    exp->expr + exp->expr_pos[equal_exp]);
3255         }
3256 
3257         /* we are unable to check identityref validity if this module (and any required imports) are not implemented */
3258         if ((((struct lys_node_leaf *)snode)->type.base != LY_TYPE_IDENT) || lys_node_module(snode)->implemented) {
3259             /* we want to print our message and more importantly a warning, not an error */
3260             ly_ilo_change(NULL, ILO_ERR2WRN, &prev_ilo, NULL);
3261             ret = lyd_value_type_internal(snode, value, local_mod, NULL);
3262             ly_ilo_restore(NULL, prev_ilo, NULL, 0);
3263             if (ret) {
3264                 LOGWRN(ctx, "Previous warning generated by XPath subexpression[%u] \"%.*s\".", exp->expr_pos[equal_exp],
3265                     (exp->expr_pos[last_equal_exp] - exp->expr_pos[equal_exp]) + exp->tok_len[last_equal_exp],
3266                     exp->expr + exp->expr_pos[equal_exp]);
3267             }
3268         }
3269         free(value);
3270     }
3271 }
3272 
3273 /*
3274  * XPath functions
3275  */
3276 
3277 /**
3278  * @brief Execute the YANG 1.1 bit-is-set(node-set, string) function. Returns LYXP_SET_BOOLEAN
3279  *        depending on whether the first node bit value from the second argument is set.
3280  *
3281  * @param[in] args Array of arguments.
3282  * @param[in] arg_count Count of elements in \p args.
3283  * @param[in] cur_node Original context node.
3284  * @param[in,out] set Context and result set at the same time.
3285  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
3286  *
3287  * @return EXIT_SUCCESS on success, -1 on error.
3288  */
3289 static int
xpath_bit_is_set(struct lyxp_set ** args,uint16_t UNUSED (arg_count),struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)3290 xpath_bit_is_set(struct lyxp_set **args, uint16_t UNUSED(arg_count), struct lyd_node *cur_node, struct lys_module *local_mod,
3291                  struct lyxp_set *set, int options)
3292 {
3293     struct lyd_node_leaf_list *leaf;
3294     struct lys_node_leaf *sleaf;
3295     int i, bits_count, ret = EXIT_SUCCESS;
3296 
3297     if (options & LYXP_SNODE_ALL) {
3298         if ((args[0]->type != LYXP_SET_SNODE_SET) || !(sleaf = (struct lys_node_leaf *)warn_get_snode_in_ctx(args[0]))) {
3299             LOGWRN(local_mod->ctx, "Argument #1 of %s not a node-set as expected.", __func__);
3300             ret = EXIT_FAILURE;
3301         } else if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
3302             LOGWRN(local_mod->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, strnodetype(sleaf->nodetype), sleaf->name);
3303             ret = EXIT_FAILURE;
3304         } else if (!warn_is_specific_type(&sleaf->type, LY_TYPE_BITS)) {
3305             LOGWRN(local_mod->ctx, "Argument #1 of %s is node \"%s\", not of type \"bits\".", __func__, sleaf->name);
3306             ret = EXIT_FAILURE;
3307         }
3308 
3309         if ((args[1]->type == LYXP_SET_SNODE_SET) && (sleaf = (struct lys_node_leaf *)warn_get_snode_in_ctx(args[1]))) {
3310             if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
3311                 LOGWRN(local_mod->ctx, "Argument #2 of %s is a %s node \"%s\".", __func__, strnodetype(sleaf->nodetype), sleaf->name);
3312                 ret = EXIT_FAILURE;
3313             } else if (!warn_is_string_type(&sleaf->type)) {
3314                 LOGWRN(local_mod->ctx, "Argument #2 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
3315                 ret = EXIT_FAILURE;
3316             }
3317         }
3318         set_snode_clear_ctx(set);
3319         return ret;
3320     }
3321 
3322     if ((args[0]->type != LYXP_SET_NODE_SET) && (args[0]->type != LYXP_SET_EMPTY)) {
3323         LOGVAL(local_mod->ctx, LYE_XPATH_INARGTYPE, LY_VLOG_NONE, NULL, 1, print_set_type(args[0]), "bit-is-set(node-set, string)");
3324         return -1;
3325     }
3326     if (lyxp_set_cast(args[1], LYXP_SET_STRING, cur_node, local_mod, options)) {
3327         return -1;
3328     }
3329 
3330     set_fill_boolean(set, 0);
3331     if (args[0]->type == LYXP_SET_NODE_SET) {
3332         leaf = (struct lyd_node_leaf_list *)args[0]->val.nodes[0].node;
3333         if ((leaf->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST))
3334                 && (((struct lys_node_leaf *)leaf->schema)->type.base == LY_TYPE_BITS)) {
3335             bits_count = ((struct lys_node_leaf *)leaf->schema)->type.info.bits.count;
3336             for (i = 0; i < bits_count; ++i) {
3337                 if (leaf->value.bit[i] && ly_strequal(leaf->value.bit[i]->name, args[1]->val.str, 0)) {
3338                     set_fill_boolean(set, 1);
3339                     break;
3340                 }
3341             }
3342         }
3343     }
3344 
3345     return EXIT_SUCCESS;
3346 }
3347 
3348 /**
3349  * @brief Execute the XPath boolean(object) function. Returns LYXP_SET_BOOLEAN
3350  *        with the argument converted to boolean.
3351  *
3352  * @param[in] args Array of arguments.
3353  * @param[in] arg_count Count of elements in \p args.
3354  * @param[in] cur_node Original context node.
3355  * @param[in,out] set Context and result set at the same time.
3356  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
3357  *
3358  * @return EXIT_SUCCESS on success, -1 on error.
3359  */
3360 static int
xpath_boolean(struct lyxp_set ** args,uint16_t UNUSED (arg_count),struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)3361 xpath_boolean(struct lyxp_set **args, uint16_t UNUSED(arg_count), struct lyd_node *cur_node, struct lys_module *local_mod,
3362               struct lyxp_set *set, int options)
3363 {
3364     if (options & LYXP_SNODE_ALL) {
3365         set_snode_clear_ctx(set);
3366         return EXIT_SUCCESS;
3367     }
3368 
3369     lyxp_set_cast(args[0], LYXP_SET_BOOLEAN, cur_node, local_mod, options);
3370     set_fill_set(set, args[0]);
3371 
3372     return EXIT_SUCCESS;
3373 }
3374 
3375 /**
3376  * @brief Execute the XPath ceiling(number) function. Returns LYXP_SET_NUMBER
3377  *        with the first argument rounded up to the nearest integer.
3378  *
3379  * @param[in] args Array of arguments.
3380  * @param[in] arg_count Count of elements in \p args.
3381  * @param[in] cur_node Original context node.
3382  * @param[in,out] set Context and result set at the same time.
3383  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
3384  *
3385  * @return EXIT_SUCCESS on success, -1 on error.
3386  */
3387 static int
xpath_ceiling(struct lyxp_set ** args,uint16_t UNUSED (arg_count),struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)3388 xpath_ceiling(struct lyxp_set **args, uint16_t UNUSED(arg_count), struct lyd_node *cur_node, struct lys_module *local_mod,
3389               struct lyxp_set *set, int options)
3390 {
3391     struct lys_node_leaf *sleaf;
3392     int ret = EXIT_SUCCESS;
3393 
3394     if (options & LYXP_SNODE_ALL) {
3395         if ((args[0]->type != LYXP_SET_SNODE_SET) || !(sleaf = (struct lys_node_leaf *)warn_get_snode_in_ctx(args[0]))) {
3396             LOGWRN(local_mod->ctx, "Argument #1 of %s not a node-set as expected.", __func__);
3397             ret = EXIT_FAILURE;
3398         } else if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
3399             LOGWRN(local_mod->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, strnodetype(sleaf->nodetype), sleaf->name);
3400             ret = EXIT_FAILURE;
3401         } else if (!warn_is_specific_type(&sleaf->type, LY_TYPE_DEC64)) {
3402             LOGWRN(local_mod->ctx, "Argument #1 of %s is node \"%s\", not of type \"decimal64\".", __func__, sleaf->name);
3403             ret = EXIT_FAILURE;
3404         }
3405         set_snode_clear_ctx(set);
3406         return ret;
3407     }
3408 
3409     if (lyxp_set_cast(args[0], LYXP_SET_NUMBER, cur_node, local_mod, options)) {
3410         return -1;
3411     }
3412     if ((long long)args[0]->val.num != args[0]->val.num) {
3413         set_fill_number(set, ((long long)args[0]->val.num) + 1);
3414     } else {
3415         set_fill_number(set, args[0]->val.num);
3416     }
3417 
3418     return EXIT_SUCCESS;
3419 }
3420 
3421 /**
3422  * @brief Execute the XPath concat(string, string, string*) function.
3423  *        Returns LYXP_SET_STRING with the concatenation of all the arguments.
3424  *
3425  * @param[in] args Array of arguments.
3426  * @param[in] arg_count Count of elements in \p args.
3427  * @param[in] cur_node Original context node.
3428  * @param[in,out] set Context and result set at the same time.
3429  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
3430  *
3431  * @return EXIT_SUCCESS on success, -1 on error.
3432  */
3433 static int
xpath_concat(struct lyxp_set ** args,uint16_t arg_count,struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)3434 xpath_concat(struct lyxp_set **args, uint16_t arg_count, struct lyd_node *cur_node, struct lys_module *local_mod,
3435              struct lyxp_set *set, int options)
3436 {
3437     uint16_t i;
3438     char *str = NULL;
3439     size_t used = 1;
3440     int ret = EXIT_SUCCESS;
3441     struct lys_node_leaf *sleaf;
3442 
3443     if (options & LYXP_SNODE_ALL) {
3444         for (i = 0; i < arg_count; ++i) {
3445             if ((args[i]->type == LYXP_SET_SNODE_SET) && (sleaf = (struct lys_node_leaf *)warn_get_snode_in_ctx(args[i]))) {
3446                 if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
3447                     LOGWRN(local_mod->ctx, "Argument #%u of %s is a %s node \"%s\".",
3448                            i + 1, __func__, strnodetype(sleaf->nodetype), sleaf->name);
3449                     ret = EXIT_FAILURE;
3450                 } else if (!warn_is_string_type(&sleaf->type)) {
3451                     LOGWRN(local_mod->ctx, "Argument #%u of %s is node \"%s\", not of string-type.", i + 1, __func__, sleaf->name);
3452                     ret = EXIT_FAILURE;
3453                 }
3454             }
3455         }
3456         set_snode_clear_ctx(set);
3457         return ret;
3458     }
3459 
3460     for (i = 0; i < arg_count; ++i) {
3461         if (lyxp_set_cast(args[i], LYXP_SET_STRING, cur_node, local_mod, options)) {
3462             free(str);
3463             return -1;
3464         }
3465 
3466         str = ly_realloc(str, (used + strlen(args[i]->val.str)) * sizeof(char));
3467         LY_CHECK_ERR_RETURN(!str, LOGMEM(local_mod->ctx), -1);
3468         strcpy(str + used - 1, args[i]->val.str);
3469         used += strlen(args[i]->val.str);
3470     }
3471 
3472     /* free, kind of */
3473     lyxp_set_cast(set, LYXP_SET_EMPTY, cur_node, local_mod, options);
3474     set->type = LYXP_SET_STRING;
3475     set->val.str = str;
3476 
3477     return EXIT_SUCCESS;
3478 }
3479 
3480 /**
3481  * @brief Execute the XPath contains(string, string) function.
3482  *        Returns LYXP_SET_BOOLEAN whether the second argument can
3483  *        be found in the first or not.
3484  *
3485  * @param[in] args Array of arguments.
3486  * @param[in] arg_count Count of elements in \p args.
3487  * @param[in] cur_node Original context node.
3488  * @param[in,out] set Context and result set at the same time.
3489  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
3490  *
3491  * @return EXIT_SUCCESS on success, -1 on error.
3492  */
3493 static int
xpath_contains(struct lyxp_set ** args,uint16_t UNUSED (arg_count),struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)3494 xpath_contains(struct lyxp_set **args, uint16_t UNUSED(arg_count), struct lyd_node *cur_node, struct lys_module *local_mod,
3495                struct lyxp_set *set, int options)
3496 {
3497     struct lys_node_leaf *sleaf;
3498     int ret = EXIT_SUCCESS;
3499 
3500     if (options & LYXP_SNODE_ALL) {
3501         if ((args[0]->type == LYXP_SET_SNODE_SET) && (sleaf = (struct lys_node_leaf *)warn_get_snode_in_ctx(args[0]))) {
3502             if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
3503                 LOGWRN(local_mod->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, strnodetype(sleaf->nodetype), sleaf->name);
3504                 ret = EXIT_FAILURE;
3505             } else if (!warn_is_string_type(&sleaf->type)) {
3506                 LOGWRN(local_mod->ctx, "Argument #1 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
3507                 ret = EXIT_FAILURE;
3508             }
3509         }
3510 
3511         if ((args[1]->type == LYXP_SET_SNODE_SET) && (sleaf = (struct lys_node_leaf *)warn_get_snode_in_ctx(args[1]))) {
3512             if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
3513                 LOGWRN(local_mod->ctx, "Argument #2 of %s is a %s node \"%s\".", __func__, strnodetype(sleaf->nodetype), sleaf->name);
3514                 ret = EXIT_FAILURE;
3515             } else if (!warn_is_string_type(&sleaf->type)) {
3516                 LOGWRN(local_mod->ctx, "Argument #2 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
3517                 ret = EXIT_FAILURE;
3518             }
3519         }
3520         set_snode_clear_ctx(set);
3521         return ret;
3522     }
3523 
3524     if (lyxp_set_cast(args[0], LYXP_SET_STRING, cur_node, local_mod, options)) {
3525         return -1;
3526     }
3527     if (lyxp_set_cast(args[1], LYXP_SET_STRING, cur_node, local_mod, options)) {
3528         return -1;
3529     }
3530 
3531     if (strstr(args[0]->val.str, args[1]->val.str)) {
3532         set_fill_boolean(set, 1);
3533     } else {
3534         set_fill_boolean(set, 0);
3535     }
3536 
3537     return EXIT_SUCCESS;
3538 }
3539 
3540 /**
3541  * @brief Execute the XPath count(node-set) function. Returns LYXP_SET_NUMBER
3542  *        with the size of the node-set from the argument.
3543  *
3544  * @param[in] args Array of arguments.
3545  * @param[in] arg_count Count of elements in \p args.
3546  * @param[in] cur_node Original context node.
3547  * @param[in,out] set Context and result set at the same time.
3548  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
3549  *
3550  * @return EXIT_SUCCESS on success, -1 on error.
3551  */
3552 static int
xpath_count(struct lyxp_set ** args,uint16_t UNUSED (arg_count),struct lyd_node * UNUSED (cur_node),struct lys_module * local_mod,struct lyxp_set * set,int options)3553 xpath_count(struct lyxp_set **args, uint16_t UNUSED(arg_count), struct lyd_node *UNUSED(cur_node),
3554             struct lys_module *local_mod, struct lyxp_set *set, int options)
3555 {
3556     struct lys_node *snode = NULL;
3557     int ret = EXIT_SUCCESS;
3558 
3559     if (options & LYXP_SNODE_ALL) {
3560         if ((args[0]->type != LYXP_SET_SNODE_SET) || !(snode = warn_get_snode_in_ctx(args[0]))) {
3561             LOGWRN(local_mod->ctx, "Argument #1 of %s not a node-set as expected.", __func__);
3562             ret = EXIT_FAILURE;
3563         }
3564         set_snode_clear_ctx(set);
3565         return ret;
3566     }
3567 
3568     if (args[0]->type == LYXP_SET_EMPTY) {
3569         set_fill_number(set, 0);
3570         return EXIT_SUCCESS;
3571     }
3572 
3573     if (args[0]->type != LYXP_SET_NODE_SET) {
3574         LOGVAL(local_mod->ctx, LYE_XPATH_INARGTYPE, LY_VLOG_NONE, NULL, 1, print_set_type(args[0]), "count(node-set)");
3575         return -1;
3576     }
3577 
3578     set_fill_number(set, args[0]->used);
3579     return EXIT_SUCCESS;
3580 }
3581 
3582 /**
3583  * @brief Execute the XPath current() function. Returns LYXP_SET_NODE_SET
3584  *        with the context with the initial node.
3585  *
3586  * @param[in] args Array of arguments.
3587  * @param[in] arg_count Count of elements in \p args.
3588  * @param[in] cur_node Original context node.
3589  * @param[in,out] set Context and result set at the same time.
3590  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
3591  *
3592  * @return EXIT_SUCCESS on success, -1 on error.
3593  */
3594 static int
xpath_current(struct lyxp_set ** args,uint16_t arg_count,struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)3595 xpath_current(struct lyxp_set **args, uint16_t arg_count, struct lyd_node *cur_node, struct lys_module *local_mod,
3596               struct lyxp_set *set, int options)
3597 {
3598     if (arg_count || args) {
3599         LOGVAL(local_mod->ctx, LYE_XPATH_INARGCOUNT, LY_VLOG_NONE, NULL, arg_count, "current()");
3600         return -1;
3601     }
3602 
3603     if (options & LYXP_SNODE_ALL) {
3604         set_snode_clear_ctx(set);
3605 
3606         set_snode_insert_node(set, (struct lys_node *)cur_node, LYXP_NODE_ELEM);
3607     } else {
3608         lyxp_set_cast(set, LYXP_SET_EMPTY, cur_node, local_mod, options);
3609 
3610         /* position is filled later */
3611         set_insert_node(set, cur_node, 0, LYXP_NODE_ELEM, 0);
3612     }
3613 
3614     return EXIT_SUCCESS;
3615 }
3616 
3617 /**
3618  * @brief Execute the YANG 1.1 deref(node-set) function. Returns LYXP_SET_NODE_SET with either
3619  *        leafref or instance-identifier target node(s).
3620  *
3621  * @param[in] args Array of arguments.
3622  * @param[in] arg_count Count of elements in \p args.
3623  * @param[in] cur_node Original context node.
3624  * @param[in,out] set Context and result set at the same time.
3625  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
3626  *
3627  * @return EXIT_SUCCESS on success, -1 on error.
3628  */
3629 static int
xpath_deref(struct lyxp_set ** args,uint16_t UNUSED (arg_count),struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)3630 xpath_deref(struct lyxp_set **args, uint16_t UNUSED(arg_count), struct lyd_node *cur_node, struct lys_module *local_mod,
3631             struct lyxp_set *set, int options)
3632 {
3633     struct lyd_node_leaf_list *leaf;
3634     struct lys_node_leaf *sleaf;
3635     struct lyd_node *target;
3636     int ret = EXIT_SUCCESS;
3637 
3638     if (options & LYXP_SNODE_ALL) {
3639         if ((args[0]->type != LYXP_SET_SNODE_SET) || !(sleaf = (struct lys_node_leaf *)warn_get_snode_in_ctx(args[0]))) {
3640             LOGWRN(local_mod->ctx, "Argument #1 of %s not a node-set as expected.", __func__);
3641             ret = EXIT_FAILURE;
3642         } else if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
3643             LOGWRN(local_mod->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, strnodetype(sleaf->nodetype), sleaf->name);
3644             ret = EXIT_FAILURE;
3645         } else if (!warn_is_specific_type(&sleaf->type, LY_TYPE_LEAFREF) && !warn_is_specific_type(&sleaf->type, LY_TYPE_INST)) {
3646             LOGWRN(local_mod->ctx, "Argument #1 of %s is node \"%s\", not of type \"leafref\" neither \"instance-identifier\".",
3647                    __func__, sleaf->name);
3648             ret = EXIT_FAILURE;
3649         }
3650         set_snode_clear_ctx(set);
3651         if ((ret == EXIT_SUCCESS) && (sleaf->type.base == LY_TYPE_LEAFREF)) {
3652             assert(sleaf->type.info.lref.target);
3653             set_snode_insert_node(set, (struct lys_node *)sleaf->type.info.lref.target, LYXP_NODE_ELEM);
3654         }
3655         return ret;
3656     }
3657 
3658     if ((args[0]->type != LYXP_SET_NODE_SET) && (args[0]->type != LYXP_SET_EMPTY)) {
3659         LOGVAL(local_mod->ctx, LYE_XPATH_INARGTYPE, LY_VLOG_NONE, NULL, 1, print_set_type(args[0]), "deref(node-set)");
3660         return -1;
3661     }
3662 
3663     lyxp_set_cast(set, LYXP_SET_EMPTY, cur_node, local_mod, options);
3664     if (args[0]->type != LYXP_SET_EMPTY) {
3665         leaf = (struct lyd_node_leaf_list *)args[0]->val.nodes[0].node;
3666         sleaf = (struct lys_node_leaf *)leaf->schema;
3667         if ((sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))
3668                 && ((sleaf->type.base == LY_TYPE_LEAFREF) || (sleaf->type.base == LY_TYPE_INST))) {
3669             if (leaf->value_flags & LY_VALUE_UNRES) {
3670                 /* this means that the target may exist except it cannot be stored in the value */
3671                 if (sleaf->type.base == LY_TYPE_LEAFREF) {
3672                     resolve_leafref(leaf, sleaf->type.info.lref.path, -1, &target);
3673                 } else {
3674                     resolve_instid((struct lyd_node *)leaf, leaf->value_str, -1, &target);
3675                 }
3676             } else {
3677                 /* works for both leafref and instid */
3678                 target = leaf->value.leafref;
3679             }
3680 
3681             set_insert_node(set, target, 0, LYXP_NODE_ELEM, 0);
3682         }
3683     }
3684 
3685     return EXIT_SUCCESS;
3686 }
3687 
3688 /* return 0 - match, 1 - mismatch */
3689 static int
xpath_derived_from_ident_cmp(struct lys_ident * ident,const char * ident_str)3690 xpath_derived_from_ident_cmp(struct lys_ident *ident, const char *ident_str)
3691 {
3692     const char *ptr;
3693     int len;
3694 
3695     ptr = strchr(ident_str, ':');
3696     if (ptr) {
3697         len = ptr - ident_str;
3698         if (strncmp(ident->module->name, ident_str, len)
3699                 || ident->module->name[len]) {
3700             /* module name mismatch BUG we expect JSON format prefix, but if the 2nd argument was
3701              * not a literal, we may easily be mistaken */
3702             return 1;
3703         }
3704         ++ptr;
3705     } else {
3706         ptr = ident_str;
3707     }
3708 
3709     len = strlen(ptr);
3710     if (strncmp(ident->name, ptr, len) || ident->name[len]) {
3711         /* name mismatch */
3712         return 1;
3713     }
3714 
3715     return 0;
3716 }
3717 
3718 static int
xpath_derived_from_ident_cmp_r(struct lys_ident * ident,const char * ident_str)3719 xpath_derived_from_ident_cmp_r(struct lys_ident *ident, const char *ident_str)
3720 {
3721     uint32_t i;
3722 
3723     for (i = 0; i < ident->base_size; ++i) {
3724         if (!xpath_derived_from_ident_cmp(ident->base[i], ident_str)) {
3725             return 0;
3726         }
3727 
3728         if (!xpath_derived_from_ident_cmp_r(ident->base[i], ident_str)) {
3729             return 0;
3730         }
3731     }
3732 
3733     return 1;
3734 }
3735 
3736 /**
3737  * @brief Execute the YANG 1.1 derived-from(node-set, string) function. Returns LYXP_SET_BOOLEAN depending
3738  *        on whether the first argument nodes contain a node of an identity derived from the second
3739  *        argument identity.
3740  *
3741  * @param[in] args Array of arguments.
3742  * @param[in] arg_count Count of elements in \p args.
3743  * @param[in] cur_node Original context node.
3744  * @param[in,out] set Context and result set at the same time.
3745  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
3746  *
3747  * @return EXIT_SUCCESS on success, -1 on error.
3748  */
3749 static int
xpath_derived_from(struct lyxp_set ** args,uint16_t UNUSED (arg_count),struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)3750 xpath_derived_from(struct lyxp_set **args, uint16_t UNUSED(arg_count), struct lyd_node *cur_node, struct lys_module *local_mod,
3751                    struct lyxp_set *set, int options)
3752 {
3753     uint32_t i;
3754     struct lyd_node_leaf_list *leaf;
3755     struct lys_node_leaf *sleaf;
3756     lyd_val *val;
3757     int ret = EXIT_SUCCESS;
3758 
3759     if (options & LYXP_SNODE_ALL) {
3760         if ((args[0]->type != LYXP_SET_SNODE_SET) || !(sleaf = (struct lys_node_leaf *)warn_get_snode_in_ctx(args[0]))) {
3761             LOGWRN(local_mod->ctx, "Argument #1 of %s not a node-set as expected.", __func__);
3762             ret = EXIT_FAILURE;
3763         } else if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
3764             LOGWRN(local_mod->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, strnodetype(sleaf->nodetype), sleaf->name);
3765             ret = EXIT_FAILURE;
3766         } else if (!warn_is_specific_type(&sleaf->type, LY_TYPE_IDENT)) {
3767             LOGWRN(local_mod->ctx, "Argument #1 of %s is node \"%s\", not of type \"identityref\".", __func__, sleaf->name);
3768             ret = EXIT_FAILURE;
3769         }
3770 
3771         if ((args[1]->type == LYXP_SET_SNODE_SET) && (sleaf = (struct lys_node_leaf *)warn_get_snode_in_ctx(args[1]))) {
3772             if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
3773                 LOGWRN(local_mod->ctx, "Argument #2 of %s is a %s node \"%s\".", __func__, strnodetype(sleaf->nodetype), sleaf->name);
3774                 ret = EXIT_FAILURE;
3775             } else if (!warn_is_string_type(&sleaf->type)) {
3776                 LOGWRN(local_mod->ctx, "Argument #2 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
3777                 ret = EXIT_FAILURE;
3778             }
3779         }
3780         set_snode_clear_ctx(set);
3781         return ret;
3782     }
3783 
3784     if ((args[0]->type != LYXP_SET_NODE_SET) && (args[0]->type != LYXP_SET_EMPTY)) {
3785         LOGVAL(local_mod->ctx, LYE_XPATH_INARGTYPE, LY_VLOG_NONE, NULL, 1, print_set_type(args[0]), "derived-from(node-set, string)");
3786         return -1;
3787     }
3788     if (lyxp_set_cast(args[1], LYXP_SET_STRING, cur_node, local_mod, options)) {
3789         return -1;
3790     }
3791 
3792     set_fill_boolean(set, 0);
3793     if (args[0]->type != LYXP_SET_EMPTY) {
3794         for (i = 0; i < args[0]->used; ++i) {
3795             val = NULL;
3796             if (args[0]->val.nodes[i].type == LYXP_NODE_ELEM) {
3797                 leaf = (struct lyd_node_leaf_list *)args[0]->val.nodes[i].node;
3798                 sleaf = (struct lys_node_leaf *)leaf->schema;
3799                 if ((sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST)) && (sleaf->type.base == LY_TYPE_IDENT)) {
3800                     val = &leaf->value;
3801                 }
3802             } else if (args[0]->val.nodes[i].type == LYXP_NODE_ATTR) {
3803                 if (args[0]->val.attrs[i].attr->value_type == LY_TYPE_IDENT) {
3804                     val = &args[0]->val.attrs[i].attr->value;
3805                 }
3806             }
3807             if (val) {
3808                 if (!xpath_derived_from_ident_cmp_r(val->ident, args[1]->val.str)) {
3809                     set_fill_boolean(set, 1);
3810                     break;
3811                 }
3812             }
3813         }
3814     }
3815 
3816     return EXIT_SUCCESS;
3817 }
3818 
3819 /**
3820  * @brief Execute the YANG 1.1 derived-from-or-self(node-set, string) function. Returns LYXP_SET_BOOLEAN depending
3821  *        on whether the first argument nodes contain a node of an identity that either is or is derived from
3822  *        the second argument identity.
3823  *
3824  * @param[in] args Array of arguments.
3825  * @param[in] arg_count Count of elements in \p args.
3826  * @param[in] cur_node Original context node.
3827  * @param[in,out] set Context and result set at the same time.
3828  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
3829  *
3830  * @return EXIT_SUCCESS on success, -1 on error.
3831  */
3832 static int
xpath_derived_from_or_self(struct lyxp_set ** args,uint16_t UNUSED (arg_count),struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)3833 xpath_derived_from_or_self(struct lyxp_set **args, uint16_t UNUSED(arg_count), struct lyd_node *cur_node,
3834                            struct lys_module *local_mod, struct lyxp_set *set, int options)
3835 {
3836     uint32_t i;
3837     struct lyd_node_leaf_list *leaf;
3838     struct lys_node_leaf *sleaf;
3839     lyd_val *val;
3840     int ret = EXIT_SUCCESS;
3841 
3842     if (options & LYXP_SNODE_ALL) {
3843         if ((args[0]->type != LYXP_SET_SNODE_SET) || !(sleaf = (struct lys_node_leaf *)warn_get_snode_in_ctx(args[0]))) {
3844             LOGWRN(local_mod->ctx, "Argument #1 of %s not a node-set as expected.", __func__);
3845             ret = EXIT_FAILURE;
3846         } else if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
3847             LOGWRN(local_mod->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, strnodetype(sleaf->nodetype), sleaf->name);
3848             ret = EXIT_FAILURE;
3849         } else if (!warn_is_specific_type(&sleaf->type, LY_TYPE_IDENT)) {
3850             LOGWRN(local_mod->ctx, "Argument #1 of %s is node \"%s\", not of type \"identityref\".", __func__, sleaf->name);
3851             ret = EXIT_FAILURE;
3852         }
3853 
3854         if ((args[1]->type == LYXP_SET_SNODE_SET) && (sleaf = (struct lys_node_leaf *)warn_get_snode_in_ctx(args[1]))) {
3855             if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
3856                 LOGWRN(local_mod->ctx, "Argument #2 of %s is a %s node \"%s\".", __func__, strnodetype(sleaf->nodetype), sleaf->name);
3857                 ret = EXIT_FAILURE;
3858             } else if (!warn_is_string_type(&sleaf->type)) {
3859                 LOGWRN(local_mod->ctx, "Argument #2 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
3860                 ret = EXIT_FAILURE;
3861             }
3862         }
3863         set_snode_clear_ctx(set);
3864         return ret;
3865     }
3866 
3867     if ((args[0]->type != LYXP_SET_NODE_SET) && (args[0]->type != LYXP_SET_EMPTY)) {
3868         LOGVAL(local_mod->ctx, LYE_XPATH_INARGTYPE, LY_VLOG_NONE, NULL, 1, print_set_type(args[0]), "derived-from-or-self(node-set, string)");
3869         return -1;
3870     }
3871     if (lyxp_set_cast(args[1], LYXP_SET_STRING, cur_node, local_mod, options)) {
3872         return -1;
3873     }
3874 
3875     set_fill_boolean(set, 0);
3876     if (args[0]->type != LYXP_SET_EMPTY) {
3877         for (i = 0; i < args[0]->used; ++i) {
3878             val = NULL;
3879             if (args[0]->val.nodes[i].type == LYXP_NODE_ELEM) {
3880                 leaf = (struct lyd_node_leaf_list *)args[0]->val.nodes[i].node;
3881                 sleaf = (struct lys_node_leaf *)leaf->schema;
3882                 if ((sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST)) && (sleaf->type.base == LY_TYPE_IDENT)) {
3883                     val = &leaf->value;
3884                 }
3885             } else if (args[0]->val.nodes[i].type == LYXP_NODE_ATTR) {
3886                 if (args[0]->val.attrs[i].attr->value_type == LY_TYPE_IDENT) {
3887                     val = &args[0]->val.attrs[i].attr->value;
3888                 }
3889             }
3890             if (val) {
3891                 if (!xpath_derived_from_ident_cmp(val->ident, args[1]->val.str)) {
3892                     set_fill_boolean(set, 1);
3893                     break;
3894                 }
3895 
3896                 if (!xpath_derived_from_ident_cmp_r(val->ident, args[1]->val.str)) {
3897                     set_fill_boolean(set, 1);
3898                     break;
3899                 }
3900             }
3901         }
3902     }
3903 
3904     return EXIT_SUCCESS;
3905 }
3906 
3907 /**
3908  * @brief Execute the YANG 1.1 enum-value(node-set) function. Returns LYXP_SET_NUMBER
3909  *        with the integer value of the first node's enum value, otherwise NaN.
3910  *
3911  * @param[in] args Array of arguments.
3912  * @param[in] arg_count Count of elements in \p args.
3913  * @param[in] cur_node Original context node.
3914  * @param[in,out] set Context and result set at the same time.
3915  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
3916  *
3917  * @return EXIT_SUCCESS on success, -1 on error.
3918  */
3919 static int
xpath_enum_value(struct lyxp_set ** args,uint16_t UNUSED (arg_count),struct lyd_node * UNUSED (cur_node),struct lys_module * local_mod,struct lyxp_set * set,int options)3920 xpath_enum_value(struct lyxp_set **args, uint16_t UNUSED(arg_count), struct lyd_node *UNUSED(cur_node),
3921                  struct lys_module *local_mod, struct lyxp_set *set, int options)
3922 {
3923     struct lyd_node_leaf_list *leaf;
3924     struct lys_node_leaf *sleaf;
3925     int ret = EXIT_SUCCESS;
3926 
3927     if (options & LYXP_SNODE_ALL) {
3928         if ((args[0]->type != LYXP_SET_SNODE_SET) || !(sleaf = (struct lys_node_leaf *)warn_get_snode_in_ctx(args[0]))) {
3929             LOGWRN(local_mod->ctx, "Argument #1 of %s not a node-set as expected.", __func__);
3930             ret = EXIT_FAILURE;
3931         } else if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
3932             LOGWRN(local_mod->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, strnodetype(sleaf->nodetype), sleaf->name);
3933             ret = EXIT_FAILURE;
3934         } else if (!warn_is_specific_type(&sleaf->type, LY_TYPE_ENUM)) {
3935             LOGWRN(local_mod->ctx, "Argument #1 of %s is node \"%s\", not of type \"enumeration\".", __func__, sleaf->name);
3936             ret = EXIT_FAILURE;
3937         }
3938         set_snode_clear_ctx(set);
3939         return ret;
3940     }
3941 
3942     if ((args[0]->type != LYXP_SET_NODE_SET) && (args[0]->type != LYXP_SET_EMPTY)) {
3943         LOGVAL(local_mod->ctx, LYE_XPATH_INARGTYPE, LY_VLOG_NONE, NULL, 1, print_set_type(args[0]), "enum-value(node-set)");
3944         return -1;
3945     }
3946 
3947     set_fill_number(set, NAN);
3948     if (args[0]->type == LYXP_SET_NODE_SET) {
3949         leaf = (struct lyd_node_leaf_list *)args[0]->val.nodes[0].node;
3950         if ((leaf->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST))
3951                 && (((struct lys_node_leaf *)leaf->schema)->type.base == LY_TYPE_ENUM)) {
3952             set_fill_number(set, leaf->value.enm->value);
3953         }
3954     }
3955 
3956     return EXIT_SUCCESS;
3957 }
3958 
3959 /**
3960  * @brief Execute the XPath false() function. Returns LYXP_SET_BOOLEAN
3961  *        with false value.
3962  *
3963  * @param[in] args Array of arguments.
3964  * @param[in] arg_count Count of elements in \p args.
3965  * @param[in] cur_node Original context node.
3966  * @param[in,out] set Context and result set at the same time.
3967  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
3968  *
3969  * @return EXIT_SUCCESS on success, -1 on error.
3970  */
3971 static int
xpath_false(struct lyxp_set ** UNUSED (args),uint16_t UNUSED (arg_count),struct lyd_node * UNUSED (cur_node),struct lys_module * UNUSED (local_mod),struct lyxp_set * set,int options)3972 xpath_false(struct lyxp_set **UNUSED(args), uint16_t UNUSED(arg_count), struct lyd_node *UNUSED(cur_node),
3973             struct lys_module *UNUSED(local_mod), struct lyxp_set *set, int options)
3974 {
3975     if (options & LYXP_SNODE_ALL) {
3976         set_snode_clear_ctx(set);
3977         return EXIT_SUCCESS;
3978     }
3979 
3980     set_fill_boolean(set, 0);
3981     return EXIT_SUCCESS;
3982 }
3983 
3984 /**
3985  * @brief Execute the XPath floor(number) function. Returns LYXP_SET_NUMBER
3986  *        with the first argument floored (truncated).
3987  *
3988  * @param[in] args Array of arguments.
3989  * @param[in] arg_count Count of elements in \p args.
3990  * @param[in] cur_node Original context node.
3991  * @param[in,out] set Context and result set at the same time.
3992  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
3993  *
3994  * @return EXIT_SUCCESS on success, -1 on error.
3995  */
3996 static int
xpath_floor(struct lyxp_set ** args,uint16_t UNUSED (arg_count),struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)3997 xpath_floor(struct lyxp_set **args, uint16_t UNUSED(arg_count), struct lyd_node *cur_node, struct lys_module *local_mod,
3998             struct lyxp_set *set, int options)
3999 {
4000     if (lyxp_set_cast(args[0], LYXP_SET_NUMBER, cur_node, local_mod, options)) {
4001         return -1;
4002     }
4003     if (isfinite(args[0]->val.num)) {
4004         set_fill_number(set, (long long)args[0]->val.num);
4005     }
4006 
4007     return EXIT_SUCCESS;
4008 }
4009 
4010 /**
4011  * @brief Execute the XPath lang(string) function. Returns LYXP_SET_BOOLEAN
4012  *        whether the language of the text matches the one from the argument.
4013  *
4014  * @param[in] args Array of arguments.
4015  * @param[in] arg_count Count of elements in \p args.
4016  * @param[in] cur_node Original context node.
4017  * @param[in,out] set Context and result set at the same time.
4018  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
4019  *
4020  * @return EXIT_SUCCESS on success, -1 on error.
4021  */
4022 static int
xpath_lang(struct lyxp_set ** args,uint16_t UNUSED (arg_count),struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)4023 xpath_lang(struct lyxp_set **args, uint16_t UNUSED(arg_count), struct lyd_node *cur_node, struct lys_module *local_mod,
4024            struct lyxp_set *set, int options)
4025 {
4026     const struct lyd_node *node, *root;
4027     struct lys_node_leaf *sleaf;
4028     struct lyd_attr *attr = NULL;
4029     int i, ret = EXIT_SUCCESS;
4030 
4031     if (options & LYXP_SNODE_ALL) {
4032         if ((args[0]->type == LYXP_SET_SNODE_SET) && (sleaf = (struct lys_node_leaf *)warn_get_snode_in_ctx(args[0]))) {
4033             if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4034                 LOGWRN(local_mod->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, strnodetype(sleaf->nodetype), sleaf->name);
4035                 ret = EXIT_FAILURE;
4036             } else if (!warn_is_string_type(&sleaf->type)) {
4037                 LOGWRN(local_mod->ctx, "Argument #1 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
4038                 ret = EXIT_FAILURE;
4039             }
4040         }
4041         set_snode_clear_ctx(set);
4042         return ret;
4043     }
4044 
4045     if (lyxp_set_cast(args[0], LYXP_SET_STRING, cur_node, local_mod, options)) {
4046         return -1;
4047     }
4048 
4049     if (set->type == LYXP_SET_EMPTY) {
4050         set_fill_boolean(set, 0);
4051         return EXIT_SUCCESS;
4052     }
4053     if (set->type != LYXP_SET_NODE_SET) {
4054         LOGVAL(local_mod->ctx, LYE_XPATH_INCTX, LY_VLOG_NONE, NULL, print_set_type(set), "lang(string)");
4055         return -1;
4056     }
4057 
4058     switch (set->val.nodes[0].type) {
4059     case LYXP_NODE_ELEM:
4060     case LYXP_NODE_TEXT:
4061         node = set->val.nodes[0].node;
4062         break;
4063     case LYXP_NODE_ATTR:
4064         root = moveto_get_root(cur_node, options, NULL);
4065         node = lyd_attr_parent(root, set->val.attrs[0].attr);
4066         break;
4067     default:
4068         /* nothing to do with roots */
4069         set_fill_boolean(set, 0);
4070         return EXIT_SUCCESS;
4071     }
4072 
4073     /* find lang attribute */
4074     for (; node; node = node->parent) {
4075         for (attr = node->attr; attr; attr = attr->next) {
4076             if (attr->name && !strcmp(attr->name, "lang") && !strcmp(attr->annotation->module->name, "xml")) {
4077                 break;
4078             }
4079         }
4080 
4081         if (attr) {
4082             break;
4083         }
4084     }
4085 
4086     /* compare languages */
4087     if (!attr) {
4088         set_fill_boolean(set, 0);
4089     } else {
4090         for (i = 0; args[0]->val.str[i]; ++i) {
4091             if (tolower(args[0]->val.str[i]) != tolower(attr->value_str[i])) {
4092                 set_fill_boolean(set, 0);
4093                 break;
4094             }
4095         }
4096         if (!args[0]->val.str[i]) {
4097             if (!attr->value_str[i] || (attr->value_str[i] == '-')) {
4098                 set_fill_boolean(set, 1);
4099             } else {
4100                 set_fill_boolean(set, 0);
4101             }
4102         }
4103     }
4104 
4105     return EXIT_SUCCESS;
4106 }
4107 
4108 /**
4109  * @brief Execute the XPath last() function. Returns LYXP_SET_NUMBER
4110  *        with the context size.
4111  *
4112  * @param[in] args Array of arguments.
4113  * @param[in] arg_count Count of elements in \p args.
4114  * @param[in] cur_node Original context node.
4115  * @param[in,out] set Context and result set at the same time.
4116  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
4117  *
4118  * @return EXIT_SUCCESS on success, -1 on error.
4119  */
4120 static int
xpath_last(struct lyxp_set ** UNUSED (args),uint16_t UNUSED (arg_count),struct lyd_node * UNUSED (cur_node),struct lys_module * local_mod,struct lyxp_set * set,int options)4121 xpath_last(struct lyxp_set **UNUSED(args), uint16_t UNUSED(arg_count), struct lyd_node *UNUSED(cur_node),
4122            struct lys_module *local_mod, struct lyxp_set *set, int options)
4123 {
4124     if (options & LYXP_SNODE_ALL) {
4125         set_snode_clear_ctx(set);
4126         return EXIT_SUCCESS;
4127     }
4128 
4129     if (set->type == LYXP_SET_EMPTY) {
4130         set_fill_number(set, 0);
4131         return EXIT_SUCCESS;
4132     }
4133     if (set->type != LYXP_SET_NODE_SET) {
4134         LOGVAL(local_mod->ctx, LYE_XPATH_INCTX, LY_VLOG_NONE, NULL, print_set_type(set), "last()");
4135         return -1;
4136     }
4137 
4138     set_fill_number(set, set->ctx_size);
4139     return EXIT_SUCCESS;
4140 }
4141 
4142 /**
4143  * @brief Execute the XPath local-name(node-set?) function. Returns LYXP_SET_STRING
4144  *        with the node name without namespace from the argument or the context.
4145  *
4146  * @param[in] args Array of arguments.
4147  * @param[in] arg_count Count of elements in \p args.
4148  * @param[in] cur_node Original context node.
4149  * @param[in,out] set Context and result set at the same time.
4150  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
4151  *
4152  * @return EXIT_SUCCESS on success, -1 on error.
4153  */
4154 static int
xpath_local_name(struct lyxp_set ** args,uint16_t arg_count,struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)4155 xpath_local_name(struct lyxp_set **args, uint16_t arg_count, struct lyd_node *cur_node, struct lys_module *local_mod,
4156                  struct lyxp_set *set, int options)
4157 {
4158     struct lyxp_set_node *item;
4159     /* suppress unused variable warning */
4160     (void)cur_node;
4161     (void)options;
4162 
4163     if (options & LYXP_SNODE_ALL) {
4164         set_snode_clear_ctx(set);
4165         return EXIT_SUCCESS;
4166     }
4167 
4168     if (arg_count) {
4169         if (args[0]->type == LYXP_SET_EMPTY) {
4170             set_fill_string(set, "", 0);
4171             return EXIT_SUCCESS;
4172         }
4173         if (args[0]->type != LYXP_SET_NODE_SET) {
4174             LOGVAL(local_mod->ctx, LYE_XPATH_INARGTYPE, LY_VLOG_NONE, NULL, 1, print_set_type(args[0]), "local-name(node-set?)");
4175             return -1;
4176         }
4177 
4178         /* we need the set sorted, it affects the result */
4179         assert(!set_sort(args[0], cur_node, options));
4180 
4181         item = &args[0]->val.nodes[0];
4182     } else {
4183         if (set->type == LYXP_SET_EMPTY) {
4184             set_fill_string(set, "", 0);
4185             return EXIT_SUCCESS;
4186         }
4187         if (set->type != LYXP_SET_NODE_SET) {
4188             LOGVAL(local_mod->ctx, LYE_XPATH_INCTX, LY_VLOG_NONE, NULL, print_set_type(set), "local-name(node-set?)");
4189             return -1;
4190         }
4191 
4192         /* we need the set sorted, it affects the result */
4193         assert(!set_sort(set, cur_node, options));
4194 
4195         item = &set->val.nodes[0];
4196     }
4197 
4198     switch (item->type) {
4199     case LYXP_NODE_ROOT:
4200     case LYXP_NODE_ROOT_CONFIG:
4201     case LYXP_NODE_TEXT:
4202         set_fill_string(set, "", 0);
4203         break;
4204     case LYXP_NODE_ELEM:
4205         set_fill_string(set, item->node->schema->name, strlen(item->node->schema->name));
4206         break;
4207     case LYXP_NODE_ATTR:
4208         set_fill_string(set, ((struct lyd_attr *)item->node)->name, strlen(((struct lyd_attr *)item->node)->name));
4209         break;
4210     default:
4211         LOGINT(local_mod->ctx);
4212         return -1;
4213     }
4214 
4215     return EXIT_SUCCESS;
4216 }
4217 
4218 /**
4219  * @brief Execute the XPath name(node-set?) function. Returns LYXP_SET_STRING
4220  *        with the node name fully qualified (with namespace) from the argument or the context.
4221  *        !! This function does not follow its definition and actually copies what local-name()
4222  *           function does, for the ietf-ipfix-psamp module that uses it incorrectly. !!
4223  *
4224  * @param[in] args Array of arguments.
4225  * @param[in] arg_count Count of elements in \p args.
4226  * @param[in] cur_node Original context node.
4227  * @param[in,out] set Context and result set at the same time.
4228  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
4229  *
4230  * @return EXIT_SUCCESS on success, -1 on error.
4231  */
4232 static int
xpath_name(struct lyxp_set ** args,uint16_t arg_count,struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)4233 xpath_name(struct lyxp_set **args, uint16_t arg_count, struct lyd_node *cur_node, struct lys_module *local_mod,
4234            struct lyxp_set *set, int options)
4235 {
4236     return xpath_local_name(args, arg_count, cur_node, local_mod, set, options);
4237 }
4238 
4239 /**
4240  * @brief Execute the XPath namespace-uri(node-set?) function. Returns LYXP_SET_STRING
4241  *        with the namespace of the node from the argument or the context.
4242  *
4243  * @param[in] args Array of arguments.
4244  * @param[in] arg_count Count of elements in \p args.
4245  * @param[in] cur_node Original context node.
4246  * @param[in,out] set Context and result set at the same time.
4247  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
4248  *
4249  * @return EXIT_SUCCESS on success, -1 on error.
4250  */
4251 static int
xpath_namespace_uri(struct lyxp_set ** args,uint16_t arg_count,struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)4252 xpath_namespace_uri(struct lyxp_set **args, uint16_t arg_count, struct lyd_node *cur_node, struct lys_module *local_mod,
4253                     struct lyxp_set *set, int options)
4254 {
4255     struct lyxp_set_node *item;
4256     struct lys_module *module;
4257     /* suppress unused variable warning */
4258     (void)cur_node;
4259     (void)options;
4260 
4261     if (options & LYXP_SNODE_ALL) {
4262         set_snode_clear_ctx(set);
4263         return EXIT_SUCCESS;
4264     }
4265 
4266     if (arg_count) {
4267         if (args[0]->type == LYXP_SET_EMPTY) {
4268             set_fill_string(set, "", 0);
4269             return EXIT_SUCCESS;
4270         }
4271         if (args[0]->type != LYXP_SET_NODE_SET) {
4272             LOGVAL(local_mod->ctx, LYE_XPATH_INARGTYPE, LY_VLOG_NONE, NULL, 1, print_set_type(args[0]), "namespace-uri(node-set?)");
4273             return -1;
4274         }
4275 
4276         /* we need the set sorted, it affects the result */
4277         assert(!set_sort(args[0], cur_node, options));
4278 
4279         item = &args[0]->val.nodes[0];
4280     } else {
4281         if (set->type == LYXP_SET_EMPTY) {
4282             set_fill_string(set, "", 0);
4283             return EXIT_SUCCESS;
4284         }
4285         if (set->type != LYXP_SET_NODE_SET) {
4286             LOGVAL(local_mod->ctx, LYE_XPATH_INCTX, LY_VLOG_NONE, NULL, print_set_type(set), "namespace-uri(node-set?)");
4287             return -1;
4288         }
4289 
4290         /* we need the set sorted, it affects the result */
4291         assert(!set_sort(set, cur_node, options));
4292 
4293         item = &set->val.nodes[0];
4294     }
4295 
4296     switch (item->type) {
4297     case LYXP_NODE_ROOT:
4298     case LYXP_NODE_ROOT_CONFIG:
4299     case LYXP_NODE_TEXT:
4300         set_fill_string(set, "", 0);
4301         break;
4302     case LYXP_NODE_ELEM:
4303     case LYXP_NODE_ATTR:
4304         if (item->type == LYXP_NODE_ELEM) {
4305             module =  item->node->schema->module;
4306         } else { /* LYXP_NODE_ATTR */
4307             module = ((struct lyd_attr *)item->node)->annotation->module;
4308         }
4309 
4310         module = lys_main_module(module);
4311 
4312         set_fill_string(set, module->ns, strlen(module->ns));
4313         break;
4314     default:
4315         LOGINT(local_mod->ctx);
4316         return -1;
4317     }
4318 
4319     return EXIT_SUCCESS;
4320 }
4321 
4322 /**
4323  * @brief Execute the XPath node() function (node type). Returns LYXP_SET_NODE_SET
4324  *        with only nodes from the context. In practice it either leaves the context
4325  *        as it is or returns an empty node set.
4326  *
4327  * @param[in] args Array of arguments.
4328  * @param[in] arg_count Count of elements in \p args.
4329  * @param[in] cur_node Original context node.
4330  * @param[in,out] set Context and result set at the same time.
4331  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
4332  *
4333  * @return EXIT_SUCCESS on success, -1 on error.
4334  */
4335 static int
xpath_node(struct lyxp_set ** UNUSED (args),uint16_t UNUSED (arg_count),struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)4336 xpath_node(struct lyxp_set **UNUSED(args), uint16_t UNUSED(arg_count), struct lyd_node *cur_node,
4337            struct lys_module *local_mod, struct lyxp_set *set, int options)
4338 {
4339     if (options & LYXP_SNODE_ALL) {
4340         set_snode_clear_ctx(set);
4341         return EXIT_SUCCESS;
4342     }
4343 
4344     if (set->type != LYXP_SET_NODE_SET) {
4345         lyxp_set_cast(set, LYXP_SET_EMPTY, cur_node, local_mod, options);
4346     }
4347     return EXIT_SUCCESS;
4348 }
4349 
4350 /**
4351  * @brief Execute the XPath normalize-space(string?) function. Returns LYXP_SET_STRING
4352  *        with normalized value (no leading, trailing, double white spaces) of the node
4353  *        from the argument or the context.
4354  *
4355  * @param[in] args Array of arguments.
4356  * @param[in] arg_count Count of elements in \p args.
4357  * @param[in] cur_node Original context node.
4358  * @param[in,out] set Context and result set at the same time.
4359  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
4360  *
4361  * @return EXIT_SUCCESS on success, -1 on error.
4362  */
4363 static int
xpath_normalize_space(struct lyxp_set ** args,uint16_t arg_count,struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)4364 xpath_normalize_space(struct lyxp_set **args, uint16_t arg_count, struct lyd_node *cur_node, struct lys_module *local_mod,
4365                       struct lyxp_set *set, int options)
4366 {
4367     uint16_t i, new_used;
4368     char *new;
4369     int have_spaces = 0, space_before = 0, ret = EXIT_SUCCESS;
4370     struct lys_node_leaf *sleaf;
4371 
4372     if (options & LYXP_SNODE_ALL) {
4373         if (arg_count && (args[0]->type == LYXP_SET_SNODE_SET) && (sleaf = (struct lys_node_leaf *)warn_get_snode_in_ctx(args[0]))) {
4374             if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4375                 LOGWRN(local_mod->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, strnodetype(sleaf->nodetype), sleaf->name);
4376                 ret = EXIT_FAILURE;
4377             } else if (!warn_is_string_type(&sleaf->type)) {
4378                 LOGWRN(local_mod->ctx, "Argument #1 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
4379                 ret = EXIT_FAILURE;
4380             }
4381         }
4382         set_snode_clear_ctx(set);
4383         return ret;
4384     }
4385 
4386     if (arg_count) {
4387         set_fill_set(set, args[0]);
4388     }
4389     if (lyxp_set_cast(set, LYXP_SET_STRING, cur_node, local_mod, options)) {
4390         return -1;
4391     }
4392 
4393     /* is there any normalization necessary? */
4394     for (i = 0; set->val.str[i]; ++i) {
4395         if (is_xmlws(set->val.str[i])) {
4396             if ((i == 0) || space_before || (!set->val.str[i + 1])) {
4397                 have_spaces = 1;
4398                 break;
4399             }
4400             space_before = 1;
4401         } else {
4402             space_before = 0;
4403         }
4404     }
4405 
4406     /* yep, there is */
4407     if (have_spaces) {
4408         /* it's enough, at least one character will go, makes space for ending '\0' */
4409         new = malloc(strlen(set->val.str) * sizeof(char));
4410         LY_CHECK_ERR_RETURN(!new, LOGMEM(local_mod->ctx), -1);
4411         new_used = 0;
4412 
4413         space_before = 0;
4414         for (i = 0; set->val.str[i]; ++i) {
4415             if (is_xmlws(set->val.str[i])) {
4416                 if ((i == 0) || space_before) {
4417                     space_before = 1;
4418                     continue;
4419                 } else {
4420                     space_before = 1;
4421                 }
4422             } else {
4423                 space_before = 0;
4424             }
4425 
4426             new[new_used] = (space_before ? ' ' : set->val.str[i]);
4427             ++new_used;
4428         }
4429 
4430         /* at worst there is one trailing space now */
4431         if (new_used && is_xmlws(new[new_used - 1])) {
4432             --new_used;
4433         }
4434 
4435         new = ly_realloc(new, (new_used + 1) * sizeof(char));
4436         LY_CHECK_ERR_RETURN(!new, LOGMEM(local_mod->ctx), -1);
4437         new[new_used] = '\0';
4438 
4439         free(set->val.str);
4440         set->val.str = new;
4441     }
4442 
4443     return EXIT_SUCCESS;
4444 }
4445 
4446 /**
4447  * @brief Execute the XPath not(boolean) function. Returns LYXP_SET_BOOLEAN
4448  *        with the argument converted to boolean and logically inverted.
4449  *
4450  * @param[in] args Array of arguments.
4451  * @param[in] arg_count Count of elements in \p args.
4452  * @param[in] cur_node Original context node.
4453  * @param[in,out] set Context and result set at the same time.
4454  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
4455  *
4456  * @return EXIT_SUCCESS on success, -1 on error.
4457  */
4458 static int
xpath_not(struct lyxp_set ** args,uint16_t UNUSED (arg_count),struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)4459 xpath_not(struct lyxp_set **args, uint16_t UNUSED(arg_count), struct lyd_node *cur_node, struct lys_module *local_mod,
4460           struct lyxp_set *set, int options)
4461 {
4462     if (options & LYXP_SNODE_ALL) {
4463         set_snode_clear_ctx(set);
4464         return EXIT_SUCCESS;
4465     }
4466 
4467     lyxp_set_cast(args[0], LYXP_SET_BOOLEAN, cur_node, local_mod, options);
4468     if (args[0]->val.bool) {
4469         set_fill_boolean(set, 0);
4470     } else {
4471         set_fill_boolean(set, 1);
4472     }
4473 
4474     return EXIT_SUCCESS;
4475 }
4476 
4477 /**
4478  * @brief Execute the XPath number(object?) function. Returns LYXP_SET_NUMBER
4479  *        with the number representation of either the argument or the context.
4480  *
4481  * @param[in] args Array of arguments.
4482  * @param[in] arg_count Count of elements in \p args.
4483  * @param[in] cur_node Original context node.
4484  * @param[in,out] set Context and result set at the same time.
4485  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
4486  *
4487  * @return EXIT_SUCCESS on success, -1 on error.
4488  */
4489 static int
xpath_number(struct lyxp_set ** args,uint16_t arg_count,struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)4490 xpath_number(struct lyxp_set **args, uint16_t arg_count, struct lyd_node *cur_node, struct lys_module *local_mod,
4491              struct lyxp_set *set, int options)
4492 {
4493     if (options & LYXP_SNODE_ALL) {
4494         set_snode_clear_ctx(set);
4495         return EXIT_SUCCESS;
4496     }
4497 
4498     if (arg_count) {
4499         if (lyxp_set_cast(args[0], LYXP_SET_NUMBER, cur_node, local_mod, options)) {
4500             return -1;
4501         }
4502         set_fill_set(set, args[0]);
4503     } else {
4504         if (lyxp_set_cast(set, LYXP_SET_NUMBER, cur_node, local_mod, options)) {
4505             return -1;
4506         }
4507     }
4508 
4509     return EXIT_SUCCESS;
4510 }
4511 
4512 /**
4513  * @brief Execute the XPath position() function. Returns LYXP_SET_NUMBER
4514  *        with the context position.
4515  *
4516  * @param[in] args Array of arguments.
4517  * @param[in] arg_count Count of elements in \p args.
4518  * @param[in] cur_node Original context node.
4519  * @param[in,out] set Context and result set at the same time.
4520  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
4521  *
4522  * @return EXIT_SUCCESS on success, -1 on error.
4523  */
4524 static int
xpath_position(struct lyxp_set ** UNUSED (args),uint16_t UNUSED (arg_count),struct lyd_node * UNUSED (cur_node),struct lys_module * local_mod,struct lyxp_set * set,int options)4525 xpath_position(struct lyxp_set **UNUSED(args), uint16_t UNUSED(arg_count), struct lyd_node *UNUSED(cur_node),
4526                struct lys_module *local_mod, struct lyxp_set *set, int options)
4527 {
4528     if (options & LYXP_SNODE_ALL) {
4529         set_snode_clear_ctx(set);
4530         return EXIT_SUCCESS;
4531     }
4532 
4533     if (set->type == LYXP_SET_EMPTY) {
4534         set_fill_number(set, 0);
4535         return EXIT_SUCCESS;
4536     }
4537     if (set->type != LYXP_SET_NODE_SET) {
4538         LOGVAL(local_mod->ctx, LYE_XPATH_INCTX, LY_VLOG_NONE, NULL, print_set_type(set), "position()");
4539         return -1;
4540     }
4541 
4542     set_fill_number(set, set->ctx_pos);
4543 
4544     /* UNUSED in 'Release' build type */
4545     (void)options;
4546     return EXIT_SUCCESS;
4547 }
4548 
4549 /**
4550  * @brief Execute the YANG 1.1 re-match(string, string) function. Returns LYXP_SET_BOOLEAN
4551  *        depending on whether the second argument regex matches the first argument string. For details refer to
4552  *        YANG 1.1 RFC section 10.2.1.
4553  *
4554  * @param[in] args Array of arguments.
4555  * @param[in] arg_count Count of elements in \p args.
4556  * @param[in] cur_node Original context node.
4557  * @param[in,out] set Context and result set at the same time.
4558  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
4559  *
4560  * @return EXIT_SUCCESS on success, -1 on error.
4561  */
4562 static int
xpath_re_match(struct lyxp_set ** args,uint16_t UNUSED (arg_count),struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)4563 xpath_re_match(struct lyxp_set **args, uint16_t UNUSED(arg_count), struct lyd_node *cur_node, struct lys_module *local_mod,
4564                struct lyxp_set *set, int options)
4565 {
4566     pcre *precomp;
4567     struct lys_node_leaf *sleaf;
4568     int ret = EXIT_SUCCESS;
4569 
4570     if (options & LYXP_SNODE_ALL) {
4571         if ((args[0]->type == LYXP_SET_SNODE_SET) && (sleaf = (struct lys_node_leaf *)warn_get_snode_in_ctx(args[0]))) {
4572             if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4573                 LOGWRN(local_mod->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, strnodetype(sleaf->nodetype), sleaf->name);
4574                 ret = EXIT_FAILURE;
4575             } else if (!warn_is_string_type(&sleaf->type)) {
4576                 LOGWRN(local_mod->ctx, "Argument #1 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
4577                 ret = EXIT_FAILURE;
4578             }
4579         }
4580 
4581         if ((args[1]->type == LYXP_SET_SNODE_SET) && (sleaf = (struct lys_node_leaf *)warn_get_snode_in_ctx(args[1]))) {
4582             if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4583                 LOGWRN(local_mod->ctx, "Argument #2 of %s is a %s node \"%s\".", __func__, strnodetype(sleaf->nodetype), sleaf->name);
4584                 ret = EXIT_FAILURE;
4585             } else if (!warn_is_string_type(&sleaf->type)) {
4586                 LOGWRN(local_mod->ctx, "Argument #2 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
4587                 ret = EXIT_FAILURE;
4588             }
4589         }
4590         set_snode_clear_ctx(set);
4591         return ret;
4592     }
4593 
4594     if (lyxp_set_cast(args[0], LYXP_SET_STRING, cur_node, local_mod, options)) {
4595         return -1;
4596     }
4597     if (lyxp_set_cast(args[1], LYXP_SET_STRING, cur_node, local_mod, options)) {
4598         return -1;
4599     }
4600 
4601     if (lyp_check_pattern(local_mod->ctx, args[1]->val.str, &precomp)) {
4602         return -1;
4603     }
4604     if (pcre_exec(precomp, NULL, args[0]->val.str, strlen(args[0]->val.str), 0, 0, NULL, 0)) {
4605         set_fill_boolean(set, 0);
4606     } else {
4607         set_fill_boolean(set, 1);
4608     }
4609     free(precomp);
4610 
4611     return EXIT_SUCCESS;
4612 }
4613 
4614 /**
4615  * @brief Execute the XPath round(number) function. Returns LYXP_SET_NUMBER
4616  *        with the rounded first argument. For details refer to
4617  *        http://www.w3.org/TR/1999/REC-xpath-19991116/#function-round.
4618  *
4619  * @param[in] args Array of arguments.
4620  * @param[in] arg_count Count of elements in \p args.
4621  * @param[in] cur_node Original context node.
4622  * @param[in,out] set Context and result set at the same time.
4623  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
4624  *
4625  * @return EXIT_SUCCESS on success, -1 on error.
4626  */
4627 static int
xpath_round(struct lyxp_set ** args,uint16_t UNUSED (arg_count),struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)4628 xpath_round(struct lyxp_set **args, uint16_t UNUSED(arg_count), struct lyd_node *cur_node, struct lys_module *local_mod,
4629             struct lyxp_set *set, int options)
4630 {
4631     struct lys_node_leaf *sleaf;
4632     int ret = EXIT_SUCCESS;
4633 
4634     if (options & LYXP_SNODE_ALL) {
4635         if ((args[0]->type != LYXP_SET_SNODE_SET) || !(sleaf = (struct lys_node_leaf *)warn_get_snode_in_ctx(args[0]))) {
4636             LOGWRN(local_mod->ctx, "Argument #1 of %s not a node-set as expected.", __func__);
4637             ret = EXIT_FAILURE;
4638         } else if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4639             LOGWRN(local_mod->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, strnodetype(sleaf->nodetype), sleaf->name);
4640             ret = EXIT_FAILURE;
4641         } else if (!warn_is_specific_type(&sleaf->type, LY_TYPE_DEC64)) {
4642             LOGWRN(local_mod->ctx, "Argument #1 of %s is node \"%s\", not of type \"decimal64\".", __func__, sleaf->name);
4643             ret = EXIT_FAILURE;
4644         }
4645         set_snode_clear_ctx(set);
4646         return ret;
4647     }
4648 
4649     if (lyxp_set_cast(args[0], LYXP_SET_NUMBER, cur_node, local_mod, options)) {
4650         return -1;
4651     }
4652 
4653     /* cover only the cases where floor can't be used */
4654     if ((args[0]->val.num == -0.0f) || ((args[0]->val.num < 0) && (args[0]->val.num >= -0.5))) {
4655         set_fill_number(set, -0.0f);
4656     } else {
4657         args[0]->val.num += 0.5;
4658         if (xpath_floor(args, 1, cur_node, local_mod, args[0], options)) {
4659             return -1;
4660         }
4661         set_fill_number(set, args[0]->val.num);
4662     }
4663 
4664     return EXIT_SUCCESS;
4665 }
4666 
4667 /**
4668  * @brief Execute the XPath starts-with(string, string) function.
4669  *        Returns LYXP_SET_BOOLEAN whether the second argument is
4670  *        the prefix of the first or not.
4671  *
4672  * @param[in] args Array of arguments.
4673  * @param[in] arg_count Count of elements in \p args.
4674  * @param[in] cur_node Original context node.
4675  * @param[in,out] set Context and result set at the same time.
4676  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
4677  *
4678  * @return EXIT_SUCCESS on success, -1 on error.
4679  */
4680 static int
xpath_starts_with(struct lyxp_set ** args,uint16_t UNUSED (arg_count),struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)4681 xpath_starts_with(struct lyxp_set **args, uint16_t UNUSED(arg_count), struct lyd_node *cur_node, struct lys_module *local_mod,
4682                   struct lyxp_set *set, int options)
4683 {
4684     struct lys_node_leaf *sleaf;
4685     int ret = EXIT_SUCCESS;
4686 
4687     if (options & LYXP_SNODE_ALL) {
4688         if ((args[0]->type == LYXP_SET_SNODE_SET) && (sleaf = (struct lys_node_leaf *)warn_get_snode_in_ctx(args[0]))) {
4689             if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4690                 LOGWRN(local_mod->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, strnodetype(sleaf->nodetype), sleaf->name);
4691                 ret = EXIT_FAILURE;
4692             } else if (!warn_is_string_type(&sleaf->type)) {
4693                 LOGWRN(local_mod->ctx, "Argument #1 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
4694                 ret = EXIT_FAILURE;
4695             }
4696         }
4697 
4698         if ((args[1]->type == LYXP_SET_SNODE_SET) && (sleaf = (struct lys_node_leaf *)warn_get_snode_in_ctx(args[1]))) {
4699             if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4700                 LOGWRN(local_mod->ctx, "Argument #2 of %s is a %s node \"%s\".", __func__, strnodetype(sleaf->nodetype), sleaf->name);
4701                 ret = EXIT_FAILURE;
4702             } else if (!warn_is_string_type(&sleaf->type)) {
4703                 LOGWRN(local_mod->ctx, "Argument #2 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
4704                 ret = EXIT_FAILURE;
4705             }
4706         }
4707         set_snode_clear_ctx(set);
4708         return ret;
4709     }
4710 
4711     if (lyxp_set_cast(args[0], LYXP_SET_STRING, cur_node, local_mod, options)) {
4712         return -1;
4713     }
4714     if (lyxp_set_cast(args[1], LYXP_SET_STRING, cur_node, local_mod, options)) {
4715         return -1;
4716     }
4717 
4718     if (strncmp(args[0]->val.str, args[1]->val.str, strlen(args[1]->val.str))) {
4719         set_fill_boolean(set, 0);
4720     } else {
4721         set_fill_boolean(set, 1);
4722     }
4723 
4724     return EXIT_SUCCESS;
4725 }
4726 
4727 /**
4728  * @brief Execute the XPath string(object?) function. Returns LYXP_SET_STRING
4729  *        with the string representation of either the argument or the context.
4730  *
4731  * @param[in] args Array of arguments.
4732  * @param[in] arg_count Count of elements in \p args.
4733  * @param[in] cur_node Original context node.
4734  * @param[in,out] set Context and result set at the same time.
4735  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
4736  *
4737  * @return EXIT_SUCCESS on success, -1 on error.
4738  */
4739 static int
xpath_string(struct lyxp_set ** args,uint16_t arg_count,struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)4740 xpath_string(struct lyxp_set **args, uint16_t arg_count, struct lyd_node *cur_node, struct lys_module *local_mod,
4741              struct lyxp_set *set, int options)
4742 {
4743     if (options & LYXP_SNODE_ALL) {
4744         set_snode_clear_ctx(set);
4745         return EXIT_SUCCESS;
4746     }
4747 
4748     if (arg_count) {
4749         if (lyxp_set_cast(args[0], LYXP_SET_STRING, cur_node, local_mod, options)) {
4750             return -1;
4751         }
4752         set_fill_set(set, args[0]);
4753     } else {
4754         if (lyxp_set_cast(set, LYXP_SET_STRING, cur_node, local_mod, options)) {
4755             return -1;
4756         }
4757     }
4758 
4759     return EXIT_SUCCESS;
4760 }
4761 
4762 /**
4763  * @brief Execute the XPath string-length(string?) function. Returns LYXP_SET_NUMBER
4764  *        with the length of the string in either the argument or the context.
4765  *
4766  * @param[in] args Array of arguments.
4767  * @param[in] arg_count Count of elements in \p args.
4768  * @param[in] cur_node Original context node.
4769  * @param[in,out] set Context and result set at the same time.
4770  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
4771  *
4772  * @return EXIT_SUCCESS on success, -1 on error.
4773  */
4774 static int
xpath_string_length(struct lyxp_set ** args,uint16_t arg_count,struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)4775 xpath_string_length(struct lyxp_set **args, uint16_t arg_count, struct lyd_node *cur_node, struct lys_module *local_mod,
4776                     struct lyxp_set *set, int options)
4777 {
4778     struct lys_node_leaf *sleaf;
4779     int ret = EXIT_SUCCESS;
4780 
4781     if (options & LYXP_SNODE_ALL) {
4782         if (arg_count && (args[0]->type == LYXP_SET_SNODE_SET) && (sleaf = (struct lys_node_leaf *)warn_get_snode_in_ctx(args[0]))) {
4783             if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4784                 LOGWRN(local_mod->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, strnodetype(sleaf->nodetype), sleaf->name);
4785                 ret = EXIT_FAILURE;
4786             } else if (!warn_is_string_type(&sleaf->type)) {
4787                 LOGWRN(local_mod->ctx, "Argument #1 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
4788                 ret = EXIT_FAILURE;
4789             }
4790         }
4791         if (!arg_count && (set->type == LYXP_SET_SNODE_SET) && (sleaf = (struct lys_node_leaf *)warn_get_snode_in_ctx(set))) {
4792             if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4793                 LOGWRN(local_mod->ctx, "Argument #0 of %s is a %s node \"%s\".", __func__, strnodetype(sleaf->nodetype), sleaf->name);
4794                 ret = EXIT_FAILURE;
4795             } else if (!warn_is_string_type(&sleaf->type)) {
4796                 LOGWRN(local_mod->ctx, "Argument #0 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
4797                 ret = EXIT_FAILURE;
4798             }
4799         }
4800         set_snode_clear_ctx(set);
4801         return ret;
4802     }
4803 
4804     if (arg_count) {
4805         if (lyxp_set_cast(args[0], LYXP_SET_STRING, cur_node, local_mod, options)) {
4806             return -1;
4807         }
4808         set_fill_number(set, strlen(args[0]->val.str));
4809     } else {
4810         if (lyxp_set_cast(set, LYXP_SET_STRING, cur_node, local_mod, options)) {
4811             return -1;
4812         }
4813         set_fill_number(set, strlen(set->val.str));
4814     }
4815 
4816     return EXIT_SUCCESS;
4817 }
4818 
4819 /**
4820  * @brief Execute the XPath substring(string, number, number?) function.
4821  *        Returns LYXP_SET_STRING substring of the first argument starting
4822  *        on the second argument index ending on the third argument index,
4823  *        indexed from 1. For exact definition refer to
4824  *        http://www.w3.org/TR/1999/REC-xpath-19991116/#function-substring.
4825  *
4826  * @param[in] args Array of arguments.
4827  * @param[in] arg_count Count of elements in \p args.
4828  * @param[in] cur_node Original context node.
4829  * @param[in,out] set Context and result set at the same time.
4830  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
4831  *
4832  * @return EXIT_SUCCESS on success, -1 on error.
4833  */
4834 static int
xpath_substring(struct lyxp_set ** args,uint16_t arg_count,struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)4835 xpath_substring(struct lyxp_set **args, uint16_t arg_count, struct lyd_node *cur_node, struct lys_module *local_mod,
4836                 struct lyxp_set *set, int options)
4837 {
4838     int start, len, ret = EXIT_SUCCESS;
4839     uint16_t str_start, str_len, pos;
4840     struct lys_node_leaf *sleaf;
4841 
4842     if (options & LYXP_SNODE_ALL) {
4843         if ((args[0]->type == LYXP_SET_SNODE_SET) && (sleaf = (struct lys_node_leaf *)warn_get_snode_in_ctx(args[0]))) {
4844             if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4845                 LOGWRN(local_mod->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, strnodetype(sleaf->nodetype), sleaf->name);
4846                 ret = EXIT_FAILURE;
4847             } else if (!warn_is_string_type(&sleaf->type)) {
4848                 LOGWRN(local_mod->ctx, "Argument #1 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
4849                 ret = EXIT_FAILURE;
4850             }
4851         }
4852 
4853         if ((args[1]->type == LYXP_SET_SNODE_SET) && (sleaf = (struct lys_node_leaf *)warn_get_snode_in_ctx(args[1]))) {
4854             if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4855                 LOGWRN(local_mod->ctx, "Argument #2 of %s is a %s node \"%s\".", __func__, strnodetype(sleaf->nodetype), sleaf->name);
4856                 ret = EXIT_FAILURE;
4857             } else if (!warn_is_numeric_type(&sleaf->type)) {
4858                 LOGWRN(local_mod->ctx, "Argument #2 of %s is node \"%s\", not of numeric type.", __func__, sleaf->name);
4859                 ret = EXIT_FAILURE;
4860             }
4861         }
4862 
4863         if ((arg_count == 3) && (args[2]->type == LYXP_SET_SNODE_SET) && (sleaf = (struct lys_node_leaf *)warn_get_snode_in_ctx(args[2]))) {
4864             if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4865                 LOGWRN(local_mod->ctx, "Argument #3 of %s is a %s node \"%s\".", __func__, strnodetype(sleaf->nodetype), sleaf->name);
4866                 ret = EXIT_FAILURE;
4867             } else if (!warn_is_numeric_type(&sleaf->type)) {
4868                 LOGWRN(local_mod->ctx, "Argument #3 of %s is node \"%s\", not of numeric type.", __func__, sleaf->name);
4869                 ret = EXIT_FAILURE;
4870             }
4871         }
4872         set_snode_clear_ctx(set);
4873         return ret;
4874     }
4875 
4876     if (lyxp_set_cast(args[0], LYXP_SET_STRING, cur_node, local_mod, options)) {
4877         return -1;
4878     }
4879 
4880     /* start */
4881     if (xpath_round(&args[1], 1, cur_node, local_mod, args[1], options)) {
4882         return -1;
4883     }
4884     if (isfinite(args[1]->val.num)) {
4885         start = args[1]->val.num - 1;
4886     } else if (isinf(args[1]->val.num) && signbit(args[1]->val.num)) {
4887         start = INT_MIN;
4888     } else {
4889         start = INT_MAX;
4890     }
4891 
4892     /* len */
4893     if (arg_count == 3) {
4894         if (xpath_round(&args[2], 1, cur_node, local_mod, args[2], options)) {
4895             return -1;
4896         }
4897         if (isfinite(args[2]->val.num)) {
4898             len = args[2]->val.num;
4899         } else if (isnan(args[2]->val.num) || signbit(args[2]->val.num)) {
4900             len = 0;
4901         } else {
4902             len = INT_MAX;
4903         }
4904     } else {
4905         len = INT_MAX;
4906     }
4907 
4908     /* find matching character positions */
4909     str_start = 0;
4910     str_len = 0;
4911     for (pos = 0; args[0]->val.str[pos]; ++pos) {
4912         if (pos < start) {
4913             ++str_start;
4914         } else if (pos < start + len) {
4915             ++str_len;
4916         } else {
4917             break;
4918         }
4919     }
4920 
4921     set_fill_string(set, args[0]->val.str + str_start, str_len);
4922     return EXIT_SUCCESS;
4923 }
4924 
4925 /**
4926  * @brief Execute the XPath substring-after(string, string) function.
4927  *        Returns LYXP_SET_STRING with the string succeeding the occurrence
4928  *        of the second argument in the first or an empty string.
4929  *
4930  * @param[in] args Array of arguments.
4931  * @param[in] arg_count Count of elements in \p args.
4932  * @param[in] cur_node Original context node.
4933  * @param[in,out] set Context and result set at the same time.
4934  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
4935  *
4936  * @return EXIT_SUCCESS on success, -1 on error.
4937  */
4938 static int
xpath_substring_after(struct lyxp_set ** args,uint16_t UNUSED (arg_count),struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)4939 xpath_substring_after(struct lyxp_set **args, uint16_t UNUSED(arg_count), struct lyd_node *cur_node,
4940                       struct lys_module *local_mod, struct lyxp_set *set, int options)
4941 {
4942     char *ptr;
4943     struct lys_node_leaf *sleaf;
4944     int ret = EXIT_SUCCESS;
4945 
4946     if (options & LYXP_SNODE_ALL) {
4947         if ((args[0]->type == LYXP_SET_SNODE_SET) && (sleaf = (struct lys_node_leaf *)warn_get_snode_in_ctx(args[0]))) {
4948             if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4949                 LOGWRN(local_mod->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, strnodetype(sleaf->nodetype), sleaf->name);
4950                 ret = EXIT_FAILURE;
4951             } else if (!warn_is_string_type(&sleaf->type)) {
4952                 LOGWRN(local_mod->ctx, "Argument #1 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
4953                 ret = EXIT_FAILURE;
4954             }
4955         }
4956 
4957         if ((args[1]->type == LYXP_SET_SNODE_SET) && (sleaf = (struct lys_node_leaf *)warn_get_snode_in_ctx(args[1]))) {
4958             if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4959                 LOGWRN(local_mod->ctx, "Argument #2 of %s is a %s node \"%s\".", __func__, strnodetype(sleaf->nodetype), sleaf->name);
4960                 ret = EXIT_FAILURE;
4961             } else if (!warn_is_string_type(&sleaf->type)) {
4962                 LOGWRN(local_mod->ctx, "Argument #2 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
4963                 ret = EXIT_FAILURE;
4964             }
4965         }
4966         set_snode_clear_ctx(set);
4967         return ret;
4968     }
4969 
4970     if (lyxp_set_cast(args[0], LYXP_SET_STRING, cur_node, local_mod, options)) {
4971         return -1;
4972     }
4973     if (lyxp_set_cast(args[1], LYXP_SET_STRING, cur_node, local_mod, options)) {
4974         return -1;
4975     }
4976 
4977     ptr = strstr(args[0]->val.str, args[1]->val.str);
4978     if (ptr) {
4979         set_fill_string(set, ptr + strlen(args[1]->val.str), strlen(ptr + strlen(args[1]->val.str)));
4980     } else {
4981         set_fill_string(set, "", 0);
4982     }
4983 
4984     return EXIT_SUCCESS;
4985 }
4986 
4987 /**
4988  * @brief Execute the XPath substring-before(string, string) function.
4989  *        Returns LYXP_SET_STRING with the string preceding the occurrence
4990  *        of the second argument in the first or an empty string.
4991  *
4992  * @param[in] args Array of arguments.
4993  * @param[in] arg_count Count of elements in \p args.
4994  * @param[in] cur_node Original context node.
4995  * @param[in,out] set Context and result set at the same time.
4996  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
4997  *
4998  * @return EXIT_SUCCESS on success, -1 on error.
4999  */
5000 static int
xpath_substring_before(struct lyxp_set ** args,uint16_t UNUSED (arg_count),struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)5001 xpath_substring_before(struct lyxp_set **args, uint16_t UNUSED(arg_count), struct lyd_node *cur_node,
5002                        struct lys_module *local_mod, struct lyxp_set *set, int options)
5003 {
5004     char *ptr;
5005     struct lys_node_leaf *sleaf;
5006     int ret = EXIT_SUCCESS;
5007 
5008     if (options & LYXP_SNODE_ALL) {
5009         if ((args[0]->type == LYXP_SET_SNODE_SET) && (sleaf = (struct lys_node_leaf *)warn_get_snode_in_ctx(args[0]))) {
5010             if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
5011                 LOGWRN(local_mod->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, strnodetype(sleaf->nodetype), sleaf->name);
5012                 ret = EXIT_FAILURE;
5013             } else if (!warn_is_string_type(&sleaf->type)) {
5014                 LOGWRN(local_mod->ctx, "Argument #1 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
5015                 ret = EXIT_FAILURE;
5016             }
5017         }
5018 
5019         if ((args[1]->type == LYXP_SET_SNODE_SET) && (sleaf = (struct lys_node_leaf *)warn_get_snode_in_ctx(args[1]))) {
5020             if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
5021                 LOGWRN(local_mod->ctx, "Argument #2 of %s is a %s node \"%s\".", __func__, strnodetype(sleaf->nodetype), sleaf->name);
5022                 ret = EXIT_FAILURE;
5023             } else if (!warn_is_string_type(&sleaf->type)) {
5024                 LOGWRN(local_mod->ctx, "Argument #2 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
5025                 ret = EXIT_FAILURE;
5026             }
5027         }
5028         set_snode_clear_ctx(set);
5029         return ret;
5030     }
5031 
5032     if (lyxp_set_cast(args[0], LYXP_SET_STRING, cur_node, local_mod, options)) {
5033         return -1;
5034     }
5035     if (lyxp_set_cast(args[1], LYXP_SET_STRING, cur_node, local_mod, options)) {
5036         return -1;
5037     }
5038 
5039     ptr = strstr(args[0]->val.str, args[1]->val.str);
5040     if (ptr) {
5041         set_fill_string(set, args[0]->val.str, ptr - args[0]->val.str);
5042     } else {
5043         set_fill_string(set, "", 0);
5044     }
5045 
5046     return EXIT_SUCCESS;
5047 }
5048 
5049 /**
5050  * @brief Execute the XPath sum(node-set) function. Returns LYXP_SET_NUMBER
5051  *        with the sum of all the nodes in the context.
5052  *
5053  * @param[in] args Array of arguments.
5054  * @param[in] arg_count Count of elements in \p args.
5055  * @param[in] cur_node Original context node.
5056  * @param[in,out] set Context and result set at the same time.
5057  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
5058  *
5059  * @return EXIT_SUCCESS on success, -1 on error.
5060  */
5061 static int
xpath_sum(struct lyxp_set ** args,uint16_t UNUSED (arg_count),struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)5062 xpath_sum(struct lyxp_set **args, uint16_t UNUSED(arg_count), struct lyd_node *cur_node, struct lys_module *local_mod,
5063           struct lyxp_set *set, int options)
5064 {
5065     long double num;
5066     char *str;
5067     uint32_t i;
5068     struct lyxp_set set_item;
5069     struct lys_node_leaf *sleaf;
5070     int ret = EXIT_SUCCESS;
5071 
5072     if (options & LYXP_SNODE_ALL) {
5073         if (args[0]->type == LYXP_SET_SNODE_SET) {
5074             for (i = 0; i < args[0]->used; ++i) {
5075                 if (args[0]->val.snodes[i].in_ctx == 1) {
5076                     sleaf = (struct lys_node_leaf *)args[0]->val.snodes[i].snode;
5077                     if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
5078                         LOGWRN(local_mod->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, strnodetype(sleaf->nodetype), sleaf->name);
5079                         ret = EXIT_FAILURE;
5080                     } else if (!warn_is_numeric_type(&sleaf->type)) {
5081                         LOGWRN(local_mod->ctx, "Argument #1 of %s is node \"%s\", not of numeric type.", __func__, sleaf->name);
5082                         ret = EXIT_FAILURE;
5083                     }
5084                 }
5085             }
5086         }
5087         set_snode_clear_ctx(set);
5088         return ret;
5089     }
5090 
5091     set_fill_number(set, 0);
5092     if (args[0]->type == LYXP_SET_EMPTY) {
5093         return EXIT_SUCCESS;
5094     }
5095 
5096     if (args[0]->type != LYXP_SET_NODE_SET) {
5097         LOGVAL(local_mod->ctx, LYE_XPATH_INARGTYPE, LY_VLOG_NONE, NULL, 1, print_set_type(args[0]), "sum(node-set)");
5098         return -1;
5099     }
5100 
5101     set_item.type = LYXP_SET_NODE_SET;
5102     set_item.val.nodes = malloc(sizeof *set_item.val.nodes);
5103     LY_CHECK_ERR_RETURN(!set_item.val.nodes, LOGMEM(local_mod->ctx), -1);
5104 
5105     set_item.used = 1;
5106     set_item.size = 1;
5107 
5108     for (i = 0; i < args[0]->used; ++i) {
5109         set_item.val.nodes[0] = args[0]->val.nodes[i];
5110 
5111         str = cast_node_set_to_string(&set_item, cur_node, local_mod, options);
5112         if (!str) {
5113             return -1;
5114         }
5115         num = cast_string_to_number(str);
5116         free(str);
5117         set->val.num += num;
5118     }
5119 
5120     free(set_item.val.nodes);
5121 
5122     return EXIT_SUCCESS;
5123 }
5124 
5125 /**
5126  * @brief Execute the XPath text() function (node type). Returns LYXP_SET_NODE_SET
5127  *        with the text content of the nodes in the context.
5128  *
5129  * @param[in] args Array of arguments.
5130  * @param[in] arg_count Count of elements in \p args.
5131  * @param[in] cur_node Original context node.
5132  * @param[in,out] set Context and result set at the same time.
5133  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
5134  *
5135  * @return EXIT_SUCCESS on success, -1 on error.
5136  */
5137 static int
xpath_text(struct lyxp_set ** UNUSED (args),uint16_t UNUSED (arg_count),struct lyd_node * UNUSED (cur_node),struct lys_module * local_mod,struct lyxp_set * set,int options)5138 xpath_text(struct lyxp_set **UNUSED(args), uint16_t UNUSED(arg_count), struct lyd_node *UNUSED(cur_node),
5139            struct lys_module *local_mod, struct lyxp_set *set, int options)
5140 {
5141     uint32_t i;
5142 
5143     if (options & LYXP_SNODE_ALL) {
5144         set_snode_clear_ctx(set);
5145         return EXIT_SUCCESS;
5146     }
5147 
5148     if (set->type == LYXP_SET_EMPTY) {
5149         return EXIT_SUCCESS;
5150     }
5151     if (set->type != LYXP_SET_NODE_SET) {
5152         LOGVAL(local_mod->ctx, LYE_XPATH_INCTX, LY_VLOG_NONE, NULL, print_set_type(set), "text()");
5153         return -1;
5154     }
5155 
5156     for (i = 0; i < set->used;) {
5157         switch (set->val.nodes[i].type) {
5158         case LYXP_NODE_ELEM:
5159             if (set->val.nodes[i].node->validity & LYD_VAL_INUSE) {
5160                 LOGVAL(local_mod->ctx, LYE_XPATH_DUMMY, LY_VLOG_LYD, set->val.nodes[i].node, set->val.nodes[i].node->schema->name);
5161                 return -1;
5162             }
5163             if ((set->val.nodes[i].node->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST))
5164                     && ((struct lyd_node_leaf_list *)set->val.nodes[i].node)->value_str) {
5165                 set->val.nodes[i].type = LYXP_NODE_TEXT;
5166                 ++i;
5167                 break;
5168             }
5169             /* fall through */
5170         case LYXP_NODE_ROOT:
5171         case LYXP_NODE_ROOT_CONFIG:
5172         case LYXP_NODE_TEXT:
5173         case LYXP_NODE_ATTR:
5174             set_remove_node(set, i);
5175             break;
5176         default:
5177             LOGINT(local_mod->ctx);
5178             return -1;
5179         }
5180     }
5181 
5182     return EXIT_SUCCESS;
5183 }
5184 
5185 /**
5186  * @brief Execute the XPath translate(string, string, string) function.
5187  *        Returns LYXP_SET_STRING with the first argument with the characters
5188  *        from the second argument replaced by those on the corresponding
5189  *        positions in the third argument.
5190  *
5191  * @param[in] args Array of arguments.
5192  * @param[in] arg_count Count of elements in \p args.
5193  * @param[in] cur_node Original context node.
5194  * @param[in,out] set Context and result set at the same time.
5195  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
5196  *
5197  * @return EXIT_SUCCESS on success, -1 on error.
5198  */
5199 static int
xpath_translate(struct lyxp_set ** args,uint16_t UNUSED (arg_count),struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)5200 xpath_translate(struct lyxp_set **args, uint16_t UNUSED(arg_count), struct lyd_node *cur_node,
5201                 struct lys_module *local_mod, struct lyxp_set *set, int options)
5202 {
5203     uint16_t i, j, new_used;
5204     char *new;
5205     int found, have_removed;
5206     struct lys_node_leaf *sleaf;
5207     int ret = EXIT_SUCCESS;
5208 
5209     if (options & LYXP_SNODE_ALL) {
5210         if ((args[0]->type == LYXP_SET_SNODE_SET) && (sleaf = (struct lys_node_leaf *)warn_get_snode_in_ctx(args[0]))) {
5211             if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
5212                 LOGWRN(local_mod->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, strnodetype(sleaf->nodetype), sleaf->name);
5213                 ret = EXIT_FAILURE;
5214             } else if (!warn_is_string_type(&sleaf->type)) {
5215                 LOGWRN(local_mod->ctx, "Argument #1 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
5216                 ret = EXIT_FAILURE;
5217             }
5218         }
5219 
5220         if ((args[1]->type == LYXP_SET_SNODE_SET) && (sleaf = (struct lys_node_leaf *)warn_get_snode_in_ctx(args[1]))) {
5221             if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
5222                 LOGWRN(local_mod->ctx, "Argument #2 of %s is a %s node \"%s\".", __func__, strnodetype(sleaf->nodetype), sleaf->name);
5223                 ret = EXIT_FAILURE;
5224             } else if (!warn_is_string_type(&sleaf->type)) {
5225                 LOGWRN(local_mod->ctx, "Argument #2 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
5226                 ret = EXIT_FAILURE;
5227             }
5228         }
5229 
5230         if ((args[2]->type == LYXP_SET_SNODE_SET) && (sleaf = (struct lys_node_leaf *)warn_get_snode_in_ctx(args[2]))) {
5231             if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
5232                 LOGWRN(local_mod->ctx, "Argument #3 of %s is a %s node \"%s\".", __func__, strnodetype(sleaf->nodetype), sleaf->name);
5233                 ret = EXIT_FAILURE;
5234             } else if (!warn_is_string_type(&sleaf->type)) {
5235                 LOGWRN(local_mod->ctx, "Argument #3 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
5236                 ret = EXIT_FAILURE;
5237             }
5238         }
5239         set_snode_clear_ctx(set);
5240         return ret;
5241     }
5242 
5243     if (lyxp_set_cast(args[0], LYXP_SET_STRING, cur_node, local_mod, options)) {
5244         return -1;
5245     }
5246     if (lyxp_set_cast(args[1], LYXP_SET_STRING, cur_node, local_mod, options)) {
5247         return -1;
5248     }
5249     if (lyxp_set_cast(args[2], LYXP_SET_STRING, cur_node, local_mod, options)) {
5250         return -1;
5251     }
5252 
5253     new = malloc((strlen(args[0]->val.str) + 1) * sizeof(char));
5254     LY_CHECK_ERR_RETURN(!new, LOGMEM(local_mod->ctx), -1);
5255     new_used = 0;
5256 
5257     have_removed = 0;
5258     for (i = 0; args[0]->val.str[i]; ++i) {
5259         found = 0;
5260 
5261         for (j = 0; args[1]->val.str[j]; ++j) {
5262             if (args[0]->val.str[i] == args[1]->val.str[j]) {
5263                 /* removing this char */
5264                 if (j >= strlen(args[2]->val.str)) {
5265                     have_removed = 1;
5266                     found = 1;
5267                     break;
5268                 }
5269                 /* replacing this char */
5270                 new[new_used] = args[2]->val.str[j];
5271                 ++new_used;
5272                 found = 1;
5273                 break;
5274             }
5275         }
5276 
5277         /* copying this char */
5278         if (!found) {
5279             new[new_used] = args[0]->val.str[i];
5280             ++new_used;
5281         }
5282     }
5283 
5284     if (have_removed) {
5285         new = ly_realloc(new, (new_used + 1) * sizeof(char));
5286         LY_CHECK_ERR_RETURN(!new, LOGMEM(local_mod->ctx), -1);
5287     }
5288     new[new_used] = '\0';
5289 
5290     lyxp_set_cast(set, LYXP_SET_EMPTY, cur_node, local_mod, options);
5291     set->type = LYXP_SET_STRING;
5292     set->val.str = new;
5293 
5294     return EXIT_SUCCESS;
5295 }
5296 
5297 /**
5298  * @brief Execute the XPath true() function. Returns LYXP_SET_BOOLEAN
5299  *        with true value.
5300  *
5301  * @param[in] args Array of arguments.
5302  * @param[in] arg_count Count of elements in \p args.
5303  * @param[in] cur_node Original context node.
5304  * @param[in,out] set Context and result set at the same time.
5305  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
5306  *
5307  * @return EXIT_SUCCESS on success, -1 on error.
5308  */
5309 static int
xpath_true(struct lyxp_set ** UNUSED (args),uint16_t UNUSED (arg_count),struct lyd_node * UNUSED (cur_node),struct lys_module * UNUSED (local_mod),struct lyxp_set * set,int options)5310 xpath_true(struct lyxp_set **UNUSED(args), uint16_t UNUSED(arg_count), struct lyd_node *UNUSED(cur_node),
5311            struct lys_module *UNUSED(local_mod), struct lyxp_set *set, int options)
5312 {
5313     if (options & LYXP_SNODE_ALL) {
5314         set_snode_clear_ctx(set);
5315         return EXIT_SUCCESS;
5316     }
5317 
5318     set_fill_boolean(set, 1);
5319     return EXIT_SUCCESS;
5320 }
5321 
5322 /*
5323  * moveto functions
5324  *
5325  * They and only they actually change the context (set).
5326  */
5327 
5328 /**
5329  * @brief Resolve and find a specific model. Does not log.
5330  *
5331  * \p cur_snode is required in 2 quite specific cases concerning
5332  * XPath on schema. Problem is when we are parsing a submodule
5333  * and referencing something in the main module or parsing
5334  * a module importing another module that references back
5335  * the original module. Then the target module is still being
5336  * parsed and it not yet in the context - it fails to resolve.
5337  * In these cases we can find the module using \p cur_snode.
5338  *
5339  * @param[in] mod_name_ns Either module name or namespace.
5340  * @param[in] mon_nam_ns_len Length of \p mod_name_ns.
5341  * @param[in] ctx libyang context.
5342  * @param[in] cur_snode Current schema node, on data XPath leave NULL.
5343  * @param[in] is_name Whether \p mod_name_ns is module name (1) or namespace (0).
5344  *
5345  * @return Corresponding module or NULL on error.
5346  */
5347 static struct lys_module *
moveto_resolve_model(const char * mod_name_ns,uint16_t mod_nam_ns_len,struct ly_ctx * ctx,struct lys_node * cur_snode,int is_name,int import_and_disabled_model)5348 moveto_resolve_model(const char *mod_name_ns, uint16_t mod_nam_ns_len, struct ly_ctx *ctx, struct lys_node *cur_snode,
5349                      int is_name, int import_and_disabled_model)
5350 {
5351     uint32_t i;
5352     const char *str;
5353     struct lys_module *mod, *mainmod;
5354 
5355     if (cur_snode) {
5356         /* detect if the XPath is used in augment - in such a case the module of the context node (cur_snode)
5357          * differs from the currently processed module. Then, we have to use the currently processed module
5358          * for searching for the module/namespace instead of the module of the context node */
5359         if (ctx->models.parsing_sub_modules_count &&
5360                 cur_snode->module != ctx->models.parsing_sub_modules[ctx->models.parsing_sub_modules_count - 1]) {
5361             mod = ctx->models.parsing_sub_modules[ctx->models.parsing_sub_modules_count - 1];
5362         } else {
5363             mod = cur_snode->module;
5364         }
5365         mainmod = lys_main_module(mod);
5366 
5367         str = (is_name ? mainmod->name : mainmod->ns);
5368         if (!strncmp(str, mod_name_ns, mod_nam_ns_len) && !str[mod_nam_ns_len]) {
5369             return mainmod;
5370         }
5371 
5372         for (i = 0; i < mod->imp_size; ++i) {
5373             str = (is_name ? mod->imp[i].module->name : mod->imp[i].module->ns);
5374             if (!strncmp(str, mod_name_ns, mod_nam_ns_len) && !str[mod_nam_ns_len]) {
5375                 return mod->imp[i].module;
5376             }
5377         }
5378     }
5379 
5380     for (i = 0; i < (unsigned)ctx->models.used; ++i) {
5381         if (!import_and_disabled_model && (!ctx->models.list[i]->implemented || ctx->models.list[i]->disabled)) {
5382             /* skip not implemented or disabled modules */
5383             continue;
5384         }
5385         str = (is_name ? ctx->models.list[i]->name : ctx->models.list[i]->ns);
5386         if (!strncmp(str, mod_name_ns, mod_nam_ns_len) && !str[mod_nam_ns_len]) {
5387             return ctx->models.list[i];
5388         }
5389     }
5390 
5391     return NULL;
5392 }
5393 
5394 /**
5395  * @brief Get the context root.
5396  *
5397  * @param[in] cur_node Original context node.
5398  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
5399  * @param[out] root_type Root type, differs only in when, must evaluation.
5400  *
5401  * @return Context root.
5402  */
5403 static const struct lyd_node *
moveto_get_root(const struct lyd_node * cur_node,int options,enum lyxp_node_type * root_type)5404 moveto_get_root(const struct lyd_node *cur_node, int options, enum lyxp_node_type *root_type)
5405 {
5406     const struct lyd_node *root;
5407     const struct lys_node *op;
5408 
5409     if (!cur_node) {
5410         return NULL;
5411     }
5412 
5413     if (!options) {
5414         /* special kind of root that can access everything */
5415         for (root = cur_node; root->parent; root = root->parent);
5416         for (; root->prev->next; root = root->prev);
5417         *root_type = LYXP_NODE_ROOT;
5418         return root;
5419     }
5420 
5421     for (op = cur_node->schema; op && !(op->nodetype & (LYS_RPC | LYS_ACTION | LYS_NOTIF)); op = lys_parent(op));
5422 
5423     if (!op && (cur_node->schema->flags & LYS_CONFIG_W)) {
5424         *root_type = LYXP_NODE_ROOT_CONFIG;
5425     } else {
5426         *root_type = LYXP_NODE_ROOT;
5427     }
5428 
5429     for (root = cur_node; root->parent; root = root->parent);
5430     for (; root->prev->next; root = root->prev);
5431 
5432     return root;
5433 }
5434 
5435 static const struct lys_node *
moveto_snode_get_root(const struct lys_node * cur_node,int options,enum lyxp_node_type * root_type)5436 moveto_snode_get_root(const struct lys_node *cur_node, int options, enum lyxp_node_type *root_type)
5437 {
5438     const struct lys_node *root, *op;
5439 
5440     assert(cur_node && root_type);
5441 
5442     for (op = cur_node; op && !(op->nodetype & (LYS_RPC | LYS_ACTION | LYS_NOTIF)); op = lys_parent(op));
5443 
5444     if (options & LYXP_SNODE) {
5445         /* general root that can access everything */
5446         *root_type = LYXP_NODE_ROOT;
5447     } else if (!op && (cur_node->flags & LYS_CONFIG_W)) {
5448         *root_type = LYXP_NODE_ROOT_CONFIG;
5449     } else {
5450         *root_type = LYXP_NODE_ROOT;
5451     }
5452 
5453     root = lys_getnext(NULL, NULL, lys_node_module(cur_node), LYS_GETNEXT_NOSTATECHECK);
5454 
5455     return root;
5456 }
5457 
5458 /**
5459  * @brief Move context \p set to the root. Handles absolute path.
5460  *        Result is LYXP_SET_NODE_SET.
5461  *
5462  * @param[in,out] set Set to use.
5463  * @param[in] cur_node Original context node.
5464  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
5465  */
5466 static void
moveto_root(struct lyxp_set * set,struct lyd_node * cur_node,int options)5467 moveto_root(struct lyxp_set *set, struct lyd_node *cur_node, int options)
5468 {
5469     const struct lyd_node *root;
5470     enum lyxp_node_type root_type;
5471 
5472     if (!set) {
5473         return;
5474     }
5475 
5476     root = moveto_get_root(cur_node, options, &root_type);
5477 
5478     lyxp_set_cast(set, LYXP_SET_EMPTY, cur_node, NULL, options);
5479     if (root) {
5480         set_insert_node(set, root, 0, root_type, 0);
5481     }
5482 }
5483 
5484 static void
moveto_snode_root(struct lyxp_set * set,struct lys_node * cur_node,int options)5485 moveto_snode_root(struct lyxp_set *set, struct lys_node *cur_node, int options)
5486 {
5487     const struct lys_node *root;
5488     enum lyxp_node_type root_type;
5489 
5490     if (!set) {
5491         return;
5492     }
5493 
5494     if (!cur_node) {
5495         LOGINT(NULL);
5496         return;
5497     }
5498 
5499     root = moveto_snode_get_root(cur_node, options, &root_type);
5500     set_snode_clear_ctx(set);
5501     set_snode_insert_node(set, root, root_type);
5502 }
5503 
5504 /**
5505  * @brief Check \p node as a part of NameTest processing.
5506  *
5507  * @param[in] node Node to check.
5508  * @param[in] root_type XPath root node type.
5509  * @param[in] node_name_dict Optional parameter, contains the node name to move to when it is on the string dict.
5510  * @param[in] node_name Contains the node name to move to. Used when node_name_dict is NULL (not provided).
5511  * @param[in] node_name_len Length of \p node_name.
5512  * @param[in] moveto_mod Expected module of the node.
5513  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
5514  *
5515  * @return EXIT_SUCCESS on success, EXIT_FAILURE on unresolved when, -1 on error.
5516  */
5517 static int
moveto_node_check(struct lyd_node * node,enum lyxp_node_type root_type,const char * node_name_dict,const char * node_name,int node_name_len,struct lys_module * moveto_mod,int options)5518 moveto_node_check(struct lyd_node *node, enum lyxp_node_type root_type, const char *node_name_dict,
5519                   const char *node_name, int node_name_len, struct lys_module *moveto_mod, int options)
5520 {
5521     /* module check */
5522     if (moveto_mod && (lyd_node_module(node) != moveto_mod)) {
5523         return -1;
5524     }
5525 
5526     /* context check */
5527     if ((root_type == LYXP_NODE_ROOT_CONFIG) && (node->schema->flags & LYS_CONFIG_R)) {
5528         return -1;
5529     }
5530 
5531     /* name check */
5532     if (node_name_dict) {
5533         if (strcmp(node_name_dict, "*") && !ly_strequal(node->schema->name, node_name_dict, 1)) {
5534             return -1;
5535         }
5536     } else {
5537         if ((strncmp(node_name, "*", 1) || node_name_len != 1) &&
5538             (strncmp(node->schema->name, node_name, node_name_len) || node->schema->name[node_name_len] != '\0')) {
5539             return -1;
5540         }
5541     }
5542 
5543     /* when check */
5544     if ((options & LYXP_WHEN) && !LYD_WHEN_DONE(node->when_status)) {
5545         return EXIT_FAILURE;
5546     }
5547 
5548     /* match */
5549     return EXIT_SUCCESS;
5550 }
5551 
5552 static int
moveto_snode_check(const struct lys_node * node,enum lyxp_node_type root_type,const char * node_name,struct lys_module * moveto_mod,int options)5553 moveto_snode_check(const struct lys_node *node, enum lyxp_node_type root_type, const char *node_name,
5554                    struct lys_module *moveto_mod, int options)
5555 {
5556     struct lys_node *parent;
5557 
5558     /* RPC input/output check */
5559     for (parent = lys_parent(node); parent && (parent->nodetype == LYS_USES); parent = lys_parent(parent));
5560     if (options & LYXP_SNODE_OUTPUT) {
5561         if (parent && (parent->nodetype == LYS_INPUT)) {
5562             return -1;
5563         }
5564     } else {
5565         if (parent && (parent->nodetype == LYS_OUTPUT)) {
5566             return -1;
5567         }
5568     }
5569 
5570     /* module check */
5571     if (strcmp(node_name, "*") && (lys_node_module(node) != moveto_mod)) {
5572         return -1;
5573     }
5574 
5575     /* context check */
5576     if ((root_type == LYXP_NODE_ROOT_CONFIG) && (node->flags & LYS_CONFIG_R)) {
5577         return -1;
5578     }
5579 
5580     /* name check */
5581     if (strcmp(node_name, "*") && !ly_strequal(node->name, node_name, 1)) {
5582         return -1;
5583     }
5584 
5585     /* match */
5586     return EXIT_SUCCESS;
5587 }
5588 
5589 /**
5590  * @brief Move context \p set to a node. Handles '/' and '*', 'NAME', 'PREFIX:*', or 'PREFIX:NAME'.
5591  *        Result is LYXP_SET_NODE_SET (or LYXP_SET_EMPTY). Context position aware.
5592  *
5593  * @param[in,out] set Set to use.
5594  * @param[in] cur_node Original context node.
5595  * @param[in] qname Qualified node name to move to.
5596  * @param[in] qname_len Length of \p qname.
5597  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
5598  *
5599  * @return EXIT_SUCCESS on success, EXIT_FAILURE on unresolved when, -1 on error.
5600  */
5601 static int
moveto_node(struct lyxp_set * set,struct lyd_node * cur_node,struct lys_module * local_mod,const char * qname,uint16_t qname_len,int options)5602 moveto_node(struct lyxp_set *set, struct lyd_node *cur_node, struct lys_module *local_mod, const char *qname,
5603             uint16_t qname_len, int options)
5604 {
5605     uint32_t i;
5606     int comparison_counter = 0;
5607     int replaced, pref_len, ret;
5608     const char *ptr, *name_dict = NULL; /* optimalization - so we can do (==) instead (!strncmp(...)) in moveto_node_check() */
5609     struct lys_module *moveto_mod;
5610     struct lyd_node *sub;
5611     struct ly_ctx *ctx;
5612     enum lyxp_node_type root_type;
5613 
5614     if (!set || (set->type == LYXP_SET_EMPTY)) {
5615         return EXIT_SUCCESS;
5616     }
5617 
5618     assert(cur_node);
5619     ctx = cur_node->schema->module->ctx;
5620 
5621     if (set->type != LYXP_SET_NODE_SET) {
5622         LOGVAL(ctx, LYE_XPATH_INOP_1, LY_VLOG_NONE, NULL, "path operator", print_set_type(set));
5623         return -1;
5624     }
5625 
5626     moveto_get_root(cur_node, options, &root_type);
5627 
5628     /* prefix */
5629     if ((ptr = strnchr(qname, ':', qname_len))) {
5630         /* specific module */
5631         pref_len = ptr - qname;
5632         moveto_mod = moveto_resolve_model(qname, pref_len, ctx, NULL, 1, 0);
5633         if (!moveto_mod) {
5634             LOGVAL(ctx, LYE_XPATH_INMOD, LY_VLOG_NONE, NULL, pref_len, qname);
5635             return -1;
5636         }
5637         qname += pref_len + 1;
5638         qname_len -= pref_len + 1;
5639     } else if ((qname[0] == '*') && (qname_len == 1)) {
5640         /* all modules - special case */
5641         moveto_mod = NULL;
5642     } else {
5643         /* content node module */
5644         moveto_mod = local_mod;
5645     }
5646 
5647     for (i = 0; i < set->used; ) {
5648         replaced = 0;
5649 
5650         if ((set->val.nodes[i].type == LYXP_NODE_ROOT_CONFIG) || (set->val.nodes[i].type == LYXP_NODE_ROOT)) {
5651             LY_TREE_FOR(set->val.nodes[i].node, sub) {
5652                 /* avoid using string dict (lydict_insert call) for few node checks */
5653                 comparison_counter++;
5654                 if (!name_dict && (comparison_counter > LYXP_MIN_NODE_CHECKS_TO_USE_DICT)) {
5655                     name_dict = lydict_insert(ctx, qname, qname_len);
5656                 }
5657                 ret = moveto_node_check(sub, root_type, name_dict, qname, qname_len, moveto_mod, options);
5658                 if (!ret) {
5659                     /* pos filled later */
5660                     if (!replaced) {
5661                         set_replace_node(set, sub, 0, LYXP_NODE_ELEM, i);
5662                         replaced = 1;
5663                     } else {
5664                         set_insert_node(set, sub, 0, LYXP_NODE_ELEM, i);
5665                     }
5666                     ++i;
5667                 } else if (ret == EXIT_FAILURE) {
5668                     lydict_remove(ctx, name_dict);
5669                     return EXIT_FAILURE;
5670                 }
5671             }
5672 
5673         /* skip nodes without children - leaves, leaflists, anyxmls, and dummy nodes (ouput root will eval to true) */
5674         } else if (!(set->val.nodes[i].node->validity & LYD_VAL_INUSE)
5675                 && !(set->val.nodes[i].node->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA))) {
5676 
5677             LY_TREE_FOR(set->val.nodes[i].node->child, sub) {
5678                 /* avoid using string dict (lydict_insert call) for few node checks */
5679                 comparison_counter++;
5680                 if (!name_dict && (comparison_counter > LYXP_MIN_NODE_CHECKS_TO_USE_DICT)) {
5681                     name_dict = lydict_insert(ctx, qname, qname_len);
5682                 }
5683                 ret = moveto_node_check(sub, root_type, name_dict, qname, qname_len, moveto_mod, options);
5684                 if (!ret) {
5685                     if (!replaced) {
5686                         set_replace_node(set, sub, 0, LYXP_NODE_ELEM, i);
5687                         replaced = 1;
5688                     } else {
5689                         set_insert_node(set, sub, 0, LYXP_NODE_ELEM, i);
5690                     }
5691                     ++i;
5692                 } else if (ret == EXIT_FAILURE) {
5693                     lydict_remove(ctx, name_dict);
5694                     return EXIT_FAILURE;
5695                 }
5696             }
5697         }
5698 
5699         if (!replaced) {
5700             /* no match */
5701             set_remove_node(set, i);
5702         }
5703     }
5704     lydict_remove(ctx, name_dict);
5705 
5706     return EXIT_SUCCESS;
5707 }
5708 
5709 static int
moveto_snode(struct lyxp_set * set,struct lys_node * cur_node,struct lys_module * local_mod,const char * qname,uint16_t qname_len,int options)5710 moveto_snode(struct lyxp_set *set, struct lys_node *cur_node, struct lys_module *local_mod, const char *qname,
5711              uint16_t qname_len, int options)
5712 {
5713     int i, orig_used, pref_len, idx, temp_ctx = 0;
5714     uint32_t mod_idx;
5715     const char *ptr, *name_dict = NULL; /* optimalization - so we can do (==) instead (!strncmp(...)) in moveto_snode_check() */
5716     struct lys_module *moveto_mod, *tmp_mod;
5717     const struct lys_node *sub, *start_parent;
5718     struct lys_node_augment *last_aug;
5719     struct ly_ctx *ctx;
5720     enum lyxp_node_type root_type;
5721 
5722     if (!set || (set->type == LYXP_SET_EMPTY)) {
5723         return EXIT_SUCCESS;
5724     }
5725 
5726     ctx = cur_node->module->ctx;
5727 
5728     if (set->type != LYXP_SET_SNODE_SET) {
5729         LOGVAL(ctx, LYE_XPATH_INOP_1, LY_VLOG_NONE, NULL, "path operator", print_set_type(set));
5730         return -1;
5731     }
5732 
5733     moveto_snode_get_root(cur_node, options, &root_type);
5734 
5735     /* prefix */
5736     if ((ptr = strnchr(qname, ':', qname_len))) {
5737         pref_len = ptr - qname;
5738         moveto_mod = moveto_resolve_model(qname, pref_len, ctx, cur_node, 1, 1);
5739         if (!moveto_mod) {
5740             LOGVAL(ctx, LYE_XPATH_INMOD, LY_VLOG_NONE, NULL, pref_len, qname);
5741             return -1;
5742         }
5743         qname += pref_len + 1;
5744         qname_len -= pref_len + 1;
5745     } else if ((qname[0] == '*') && (qname_len == 1)) {
5746         /* all modules - special case */
5747         moveto_mod = NULL;
5748     } else {
5749         /* content node module */
5750         moveto_mod = local_mod;
5751     }
5752 
5753     /* name */
5754     name_dict = lydict_insert(ctx, qname, qname_len);
5755 
5756     orig_used = set->used;
5757     for (i = 0; i < orig_used; ++i) {
5758         if (set->val.snodes[i].in_ctx != 1) {
5759             continue;
5760         }
5761         set->val.snodes[i].in_ctx = 0;
5762 
5763         start_parent = set->val.snodes[i].snode;
5764 
5765         if ((set->val.snodes[i].type == LYXP_NODE_ROOT_CONFIG) || (set->val.snodes[i].type == LYXP_NODE_ROOT)) {
5766             /* it can actually be in any module, it's all <running>, but we know it's moveto_mod (if set),
5767              * so use it directly (root node itself is useless in this case) */
5768             mod_idx = 0;
5769             while (moveto_mod || (moveto_mod = (struct lys_module *)ly_ctx_get_module_iter(ctx, &mod_idx))) {
5770                 sub = NULL;
5771                 while ((sub = lys_getnext(sub, NULL, moveto_mod, LYS_GETNEXT_NOSTATECHECK))) {
5772                     if (!moveto_snode_check(sub, root_type, name_dict, moveto_mod, options)) {
5773                         idx = set_snode_insert_node(set, sub, LYXP_NODE_ELEM);
5774                         /* we need to prevent these nodes from being considered in this moveto */
5775                         if ((idx < orig_used) && (idx > i)) {
5776                             set->val.snodes[idx].in_ctx = 2;
5777                             temp_ctx = 1;
5778                         }
5779                     }
5780                 }
5781 
5782                 if (!mod_idx) {
5783                     /* moveto_mod was specified, we are not going through the whole context */
5784                     break;
5785                 }
5786                 /* next iteration */
5787                 moveto_mod = NULL;
5788             }
5789 
5790         /* skip nodes without children - leaves, leaflists, and anyxmls (ouput root will eval to true) */
5791         } else if (!(start_parent->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA))) {
5792             /* the target may be from an augment that was not connected */
5793             last_aug = NULL;
5794             tmp_mod = NULL;
5795             if ((moveto_mod && !moveto_mod->implemented) || (!moveto_mod && !local_mod->implemented)) {
5796                 if (moveto_mod) {
5797                     tmp_mod = moveto_mod;
5798                 } else {
5799                     tmp_mod = local_mod;
5800                 }
5801 
5802 get_next_augment:
5803                 last_aug = lys_getnext_target_aug(last_aug, tmp_mod, start_parent);
5804             }
5805 
5806             sub = NULL;
5807             while ((sub = lys_getnext(sub, (last_aug ? (struct lys_node *)last_aug : start_parent), NULL, LYS_GETNEXT_NOSTATECHECK))) {
5808                 if (!moveto_snode_check(sub, root_type, name_dict, (moveto_mod ? moveto_mod : local_mod), options)) {
5809                     idx = set_snode_insert_node(set, sub, LYXP_NODE_ELEM);
5810                     if ((idx < orig_used) && (idx > i)) {
5811                         set->val.snodes[idx].in_ctx = 2;
5812                         temp_ctx = 1;
5813                     }
5814                 }
5815             }
5816 
5817             if (last_aug) {
5818                 /* try also other augments */
5819                 goto get_next_augment;
5820             }
5821         }
5822     }
5823     lydict_remove(ctx, name_dict);
5824 
5825     /* correct temporary in_ctx values */
5826     if (temp_ctx) {
5827         for (i = 0; i < orig_used; ++i) {
5828             if (set->val.snodes[i].in_ctx == 2) {
5829                 set->val.snodes[i].in_ctx = 1;
5830             }
5831         }
5832     }
5833 
5834     return EXIT_SUCCESS;
5835 }
5836 
5837 /**
5838  * @brief Move context \p set to a node and all its descendants. Handles '//' and '*', 'NAME',
5839  *        'PREFIX:*', or 'PREFIX:NAME'. Result is LYXP_SET_NODE_SET (or LYXP_SET_EMPTY).
5840  *        Context position aware.
5841  *
5842  * @param[in] set Set to use.
5843  * @param[in] cur_node Original context node.
5844  * @param[in] qname Qualified node name to move to.
5845  * @param[in] qname_len Length of \p qname.
5846  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
5847  *
5848  * @return EXIT_SUCCESS on success, ECIT_FAILURE on unresolved when, -1 on error.
5849  */
5850 static int
moveto_node_alldesc(struct lyxp_set * set,struct lyd_node * cur_node,struct lys_module * local_mod,const char * qname,uint16_t qname_len,int options)5851 moveto_node_alldesc(struct lyxp_set *set, struct lyd_node *cur_node, struct lys_module *local_mod, const char *qname,
5852                     uint16_t qname_len, int options)
5853 {
5854     uint32_t i;
5855     int pref_len, all = 0, match, ret;
5856     struct lyd_node *next, *elem, *start;
5857     struct lys_module *moveto_mod;
5858     enum lyxp_node_type root_type;
5859     struct lyxp_set ret_set;
5860 
5861     if (!set || (set->type == LYXP_SET_EMPTY)) {
5862         return EXIT_SUCCESS;
5863     }
5864 
5865     if (set->type != LYXP_SET_NODE_SET) {
5866         LOGVAL(cur_node->schema->module->ctx, LYE_XPATH_INOP_1, LY_VLOG_NONE, NULL, "path operator", print_set_type(set));
5867         return -1;
5868     }
5869 
5870     moveto_get_root(cur_node, options, &root_type);
5871 
5872     /* prefix */
5873     if (strnchr(qname, ':', qname_len) && cur_node) {
5874         pref_len = strnchr(qname, ':', qname_len) - qname;
5875         moveto_mod = moveto_resolve_model(qname, pref_len, cur_node->schema->module->ctx, NULL, 1, 0);
5876         if (!moveto_mod) {
5877             LOGVAL(cur_node->schema->module->ctx, LYE_XPATH_INMOD, LY_VLOG_NONE, NULL, pref_len, qname);
5878             return -1;
5879         }
5880         qname += pref_len + 1;
5881         qname_len -= pref_len + 1;
5882     } else {
5883         moveto_mod = NULL;
5884     }
5885 
5886     /* replace the original nodes (and throws away all text and attr nodes, root is replaced by a child) */
5887     ret = moveto_node(set, cur_node, local_mod, "*", 1, options);
5888     if (ret) {
5889         return ret;
5890     }
5891 
5892     if ((qname_len == 1) && (qname[0] == '*')) {
5893         all = 1;
5894     }
5895 
5896     /* this loop traverses all the nodes in the set and addds/keeps only
5897      * those that match qname */
5898     memset(&ret_set, 0, sizeof ret_set);
5899     for (i = 0; i < set->used; ++i) {
5900 
5901         /* TREE DFS */
5902         start = set->val.nodes[i].node;
5903         for (elem = next = start; elem; elem = next) {
5904 
5905             /* when check */
5906             if ((options & LYXP_WHEN) && !LYD_WHEN_DONE(elem->when_status)) {
5907                 return EXIT_FAILURE;
5908             }
5909 
5910             /* dummy and context check */
5911             if ((elem->validity & LYD_VAL_INUSE) || ((root_type == LYXP_NODE_ROOT_CONFIG) && (elem->schema->flags & LYS_CONFIG_R))) {
5912                 goto skip_children;
5913             }
5914 
5915             match = 1;
5916 
5917             /* module check */
5918             if (!all) {
5919                 if (moveto_mod && (lys_node_module(elem->schema) != moveto_mod)) {
5920                     match = 0;
5921                 } else if (!moveto_mod && (lys_node_module(elem->schema) != local_mod)) {
5922                     match = 0;
5923                 }
5924             }
5925 
5926             /* name check */
5927             if (match && !all && (strncmp(elem->schema->name, qname, qname_len) || elem->schema->name[qname_len])) {
5928                 match = 0;
5929             }
5930 
5931             if (match) {
5932                 /* add matching node into result set */
5933                 set_insert_node(&ret_set, elem, 0, LYXP_NODE_ELEM, ret_set.used);
5934                 if (set_dup_node_check(set, elem, LYXP_NODE_ELEM, i)) {
5935                     /* the node is a duplicate, we'll process it later in the set */
5936                     goto skip_children;
5937                 }
5938             }
5939 
5940             /* TREE DFS NEXT ELEM */
5941             /* select element for the next run - children first */
5942             if (elem->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) {
5943                 next = NULL;
5944             } else {
5945                 next = elem->child;
5946             }
5947             if (!next) {
5948 skip_children:
5949                 /* no children, so try siblings, but only if it's not the start,
5950                  * that is considered to be the root and it's siblings are not traversed */
5951                 if (elem != start) {
5952                     next = elem->next;
5953                 } else {
5954                     break;
5955                 }
5956             }
5957             while (!next) {
5958                 /* no siblings, go back through the parents */
5959                 if (elem->parent == start) {
5960                     /* we are done, no next element to process */
5961                     break;
5962                 }
5963                 /* parent is already processed, go to its sibling */
5964                 elem = elem->parent;
5965                 next = elem->next;
5966             }
5967         }
5968     }
5969 
5970     /* make the temporary set the current one */
5971     ret_set.ctx_pos = set->ctx_pos;
5972     ret_set.ctx_size = set->ctx_size;
5973     set_free_content(set);
5974     memcpy(set, &ret_set, sizeof *set);
5975 
5976     return EXIT_SUCCESS;
5977 }
5978 
5979 static int
moveto_snode_alldesc(struct lyxp_set * set,struct lys_node * cur_node,struct lys_module * local_mod,const char * qname,uint16_t qname_len,int options)5980 moveto_snode_alldesc(struct lyxp_set *set, struct lys_node *cur_node, struct lys_module *local_mod, const char *qname,
5981                      uint16_t qname_len, int options)
5982 {
5983     int i, orig_used, pref_len, all = 0, match, idx;
5984     struct lys_node *next, *elem, *start;
5985     struct lys_module *moveto_mod;
5986     struct ly_ctx *ctx;
5987     enum lyxp_node_type root_type;
5988 
5989     if (!set || (set->type == LYXP_SET_EMPTY)) {
5990         return EXIT_SUCCESS;
5991     }
5992 
5993     ctx = cur_node->module->ctx;
5994 
5995     if (set->type != LYXP_SET_SNODE_SET) {
5996         LOGVAL(ctx, LYE_XPATH_INOP_1, LY_VLOG_NONE, NULL, "path operator", print_set_type(set));
5997         return -1;
5998     }
5999 
6000     moveto_snode_get_root(cur_node, options, &root_type);
6001 
6002     /* prefix */
6003     if (strnchr(qname, ':', qname_len)) {
6004         pref_len = strnchr(qname, ':', qname_len) - qname;
6005         moveto_mod = moveto_resolve_model(qname, pref_len, ctx, cur_node, 1, 1);
6006         if (!moveto_mod) {
6007             LOGVAL(ctx, LYE_XPATH_INMOD, LY_VLOG_NONE, NULL, pref_len, qname);
6008             return -1;
6009         }
6010         qname += pref_len + 1;
6011         qname_len -= pref_len + 1;
6012     } else {
6013         moveto_mod = NULL;
6014     }
6015 
6016     if ((qname_len == 1) && (qname[0] == '*')) {
6017         all = 1;
6018     }
6019 
6020     orig_used = set->used;
6021     for (i = 0; i < orig_used; ++i) {
6022         if (set->val.snodes[i].in_ctx != 1) {
6023             continue;
6024         }
6025         set->val.snodes[i].in_ctx = 0;
6026 
6027         /* TREE DFS */
6028         start = set->val.snodes[i].snode;
6029         for (elem = next = start; elem; elem = next) {
6030 
6031             /* context/nodetype check */
6032             if ((root_type == LYXP_NODE_ROOT_CONFIG) && (elem->flags & LYS_CONFIG_R)) {
6033                 /* valid node, but it is hidden in this context */
6034                 goto skip_children;
6035             }
6036             switch (elem->nodetype) {
6037             case LYS_USES:
6038             case LYS_CHOICE:
6039             case LYS_CASE:
6040                 /* schema-only nodes */
6041                 goto next_iter;
6042             case LYS_INPUT:
6043                 if (options & LYXP_SNODE_OUTPUT) {
6044                     goto skip_children;
6045                 }
6046                 goto next_iter;
6047             case LYS_OUTPUT:
6048                 if (!(options & LYXP_SNODE_OUTPUT)) {
6049                     goto skip_children;
6050                 }
6051                 goto next_iter;
6052             case LYS_GROUPING:
6053                 goto skip_children;
6054             default:
6055                 break;
6056             }
6057 
6058             match = 1;
6059 
6060             /* skip root */
6061             if (elem == start) {
6062                 match = 0;
6063             }
6064 
6065             /* module check */
6066             if (match && !all) {
6067                 if (moveto_mod && (lys_node_module(elem) != moveto_mod)) {
6068                     match = 0;
6069                 } else if (!moveto_mod && (lys_node_module(elem) != local_mod)) {
6070                     match = 0;
6071                 }
6072             }
6073 
6074             /* name check */
6075             if (match && !all && (strncmp(elem->name, qname, qname_len) || elem->name[qname_len])) {
6076                 match = 0;
6077             }
6078 
6079             if (match) {
6080                 if ((idx = set_snode_dup_node_check(set, elem, LYXP_NODE_ELEM, i)) > -1) {
6081                     set->val.snodes[idx].in_ctx = 1;
6082                     if (idx > i) {
6083                         /* we will process it later in the set */
6084                         goto skip_children;
6085                     }
6086                 } else {
6087                     set_snode_insert_node(set, elem, LYXP_NODE_ELEM);
6088                 }
6089             }
6090 
6091 next_iter:
6092             /* TREE DFS NEXT ELEM */
6093             /* select element for the next run - children first */
6094             next = elem->child;
6095             if (elem->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) {
6096                 next = NULL;
6097             }
6098             if (!next) {
6099 skip_children:
6100                 /* no children, so try siblings, but only if it's not the start,
6101                  * that is considered to be the root and it's siblings are not traversed */
6102                 if (elem != start) {
6103                     next = elem->next;
6104                 } else {
6105                     break;
6106                 }
6107             }
6108             while (!next) {
6109                 /* no siblings, go back through the parents */
6110                 if (lys_parent(elem) == start) {
6111                     /* we are done, no next element to process */
6112                     break;
6113                 }
6114                 /* parent is already processed, go to its sibling */
6115                 elem = lys_parent(elem);
6116                 next = elem->next;
6117             }
6118         }
6119     }
6120 
6121     return EXIT_SUCCESS;
6122 }
6123 
6124 /**
6125  * @brief Move context \p set to an attribute. Handles '/' and '@*', '@NAME', '@PREFIX:*',
6126  *        or '@PREFIX:NAME'. Result is LYXP_SET_NODE_SET (or LYXP_SET_EMPTY).
6127  *        Indirectly context position aware.
6128  *
6129  * @param[in,out] set Set to use.
6130  * @param[in] qname Qualified node name to move to.
6131  * @param[in] qname_len Length of \p qname.
6132  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
6133  *
6134  * @return EXIT_SUCCESS on success, -1 on error.
6135  */
6136 static int
moveto_attr(struct lyxp_set * set,struct lyd_node * cur_node,const char * qname,uint16_t qname_len,int UNUSED (options))6137 moveto_attr(struct lyxp_set *set, struct lyd_node *cur_node, const char *qname, uint16_t qname_len, int UNUSED(options))
6138 {
6139     uint32_t i;
6140     int replaced, all = 0, pref_len;
6141     struct lys_module *moveto_mod;
6142     struct lyd_attr *sub;
6143 
6144     if (!set || (set->type == LYXP_SET_EMPTY)) {
6145         return EXIT_SUCCESS;
6146     }
6147 
6148     if (set->type != LYXP_SET_NODE_SET) {
6149         LOGVAL(cur_node->schema->module->ctx, LYE_XPATH_INOP_1, LY_VLOG_NONE, NULL, "path operator", print_set_type(set));
6150         return -1;
6151     }
6152 
6153     /* prefix */
6154     if (strnchr(qname, ':', qname_len) && cur_node) {
6155         pref_len = strnchr(qname, ':', qname_len) - qname;
6156         moveto_mod = moveto_resolve_model(qname, pref_len, cur_node->schema->module->ctx, NULL, 1, 0);
6157         if (!moveto_mod) {
6158             LOGVAL(cur_node->schema->module->ctx, LYE_XPATH_INMOD, LY_VLOG_NONE, NULL, pref_len, qname);
6159             return -1;
6160         }
6161         qname += pref_len + 1;
6162         qname_len -= pref_len + 1;
6163     } else {
6164         moveto_mod = NULL;
6165     }
6166 
6167     if ((qname_len == 1) && (qname[0] == '*')) {
6168         all = 1;
6169     }
6170 
6171     for (i = 0; i < set->used; ) {
6172         replaced = 0;
6173 
6174         /* only attributes of an elem (not dummy) can be in the result, skip all the rest;
6175          * our attributes are always qualified */
6176         if ((set->val.nodes[i].type == LYXP_NODE_ELEM) && !(set->val.nodes[i].node->validity & LYD_VAL_INUSE)) {
6177             LY_TREE_FOR(set->val.nodes[i].node->attr, sub) {
6178 
6179                 /* check "namespace" */
6180                 if (moveto_mod && (sub->annotation->module != moveto_mod)) {
6181                     /* no match */
6182                     continue;
6183                 }
6184 
6185                 if (all || (!strncmp(sub->name, qname, qname_len) && !sub->name[qname_len])) {
6186                     /* match */
6187                     if (!replaced) {
6188                         set->val.attrs[i].attr = sub;
6189                         set->val.attrs[i].type = LYXP_NODE_ATTR;
6190                         /* pos does not change */
6191                         replaced = 1;
6192                     } else {
6193                         set_insert_node(set, (struct lyd_node *)sub, set->val.nodes[i].pos, LYXP_NODE_ATTR, i + 1);
6194                     }
6195                     ++i;
6196                 }
6197             }
6198         }
6199 
6200         if (!replaced) {
6201             /* no match */
6202             set_remove_node(set, i);
6203         }
6204     }
6205 
6206     return EXIT_SUCCESS;
6207 }
6208 
6209 /**
6210  * @brief Move context \p set1 to union with \p set2. \p set2 is emptied afterwards.
6211  *        Result is LYXP_SET_NODE_SET (or LYXP_SET_EMPTY). Context position aware.
6212  *
6213  * @param[in,out] set1 Set to use for the result.
6214  * @param[in] set2 Set that is copied to \p set1.
6215  * @param[in] cur_node Original context node.
6216  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
6217  *
6218  * @return EXIT_SUCCESS on success, -1 on error.
6219  */
6220 static int
moveto_union(struct lyxp_set * set1,struct lyxp_set * set2,struct lyd_node * cur_node,int options)6221 moveto_union(struct lyxp_set *set1, struct lyxp_set *set2, struct lyd_node *cur_node, int options)
6222 {
6223     struct ly_ctx *ctx = (options & LYXP_SNODE) ? ((struct lys_node *)cur_node)->module->ctx : cur_node->schema->module->ctx;
6224 
6225     if (((set1->type != LYXP_SET_NODE_SET) && (set1->type != LYXP_SET_EMPTY))
6226             || ((set2->type != LYXP_SET_NODE_SET) && (set2->type != LYXP_SET_EMPTY))) {
6227         LOGVAL(ctx, LYE_XPATH_INOP_2, LY_VLOG_NONE, NULL, "union", print_set_type(set1), print_set_type(set2));
6228         return -1;
6229     }
6230 
6231     /* set2 is empty or both set1 and set2 */
6232     if (set2->type == LYXP_SET_EMPTY) {
6233         return EXIT_SUCCESS;
6234     }
6235 
6236     if (set1->type == LYXP_SET_EMPTY) {
6237         memcpy(set1, set2, sizeof *set1);
6238         /* dynamic memory belongs to set1 now, do not free */
6239         set2->type = LYXP_SET_EMPTY;
6240         return EXIT_SUCCESS;
6241     }
6242 
6243     /* we assume sets are sorted */
6244     assert(!set_sort(set1, cur_node, options) && !set_sort(set2, cur_node, options));
6245 
6246     /* sort, remove duplicates */
6247     if (set_sorted_merge(set1, set2, cur_node, options)) {
6248         return -1;
6249     }
6250 
6251     /* final set must be sorted */
6252     assert(!set_sort(set1, cur_node, options));
6253 
6254     return EXIT_SUCCESS;
6255 }
6256 
6257 /**
6258  * @brief Move context \p set to an attribute in any of the descendants. Handles '//' and '@*',
6259  *        '@NAME', '@PREFIX:*', or '@PREFIX:NAME'. Result is LYXP_SET_NODE_SET (or LYXP_SET_EMPTY).
6260  *        Context position aware.
6261  *
6262  * @param[in,out] set Set to use.
6263  * @param[in] cur_node Original context node.
6264  * @param[in] qname Qualified node name to move to.
6265  * @param[in] qname_len Length of \p qname.
6266  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
6267  *
6268  * @return EXIT_SUCCESS on success, EXIT_FAILURE on unresolved when, -1 on error.
6269  */
6270 static int
moveto_attr_alldesc(struct lyxp_set * set,struct lyd_node * cur_node,struct lys_module * local_mod,const char * qname,uint16_t qname_len,int options)6271 moveto_attr_alldesc(struct lyxp_set *set, struct lyd_node *cur_node, struct lys_module *local_mod, const char *qname,
6272                     uint16_t qname_len, int options)
6273 {
6274     uint32_t i;
6275     int pref_len, replaced, all = 0, ret;
6276     struct lyd_attr *sub;
6277     struct lys_module *moveto_mod;
6278     struct lyxp_set *set_all_desc = NULL;
6279 
6280     if (!set || (set->type == LYXP_SET_EMPTY)) {
6281         return EXIT_SUCCESS;
6282     }
6283 
6284     if (set->type != LYXP_SET_NODE_SET) {
6285         LOGVAL(cur_node->schema->module->ctx, LYE_XPATH_INOP_1, LY_VLOG_NONE, NULL, "path operator", print_set_type(set));
6286         return -1;
6287     }
6288 
6289     /* prefix */
6290     if (strnchr(qname, ':', qname_len)) {
6291         pref_len = strnchr(qname, ':', qname_len) - qname;
6292         moveto_mod = moveto_resolve_model(qname, pref_len, cur_node->schema->module->ctx, NULL, 1, 0);
6293         if (!moveto_mod) {
6294             LOGVAL(cur_node->schema->module->ctx, LYE_XPATH_INMOD, LY_VLOG_NONE, NULL, pref_len, qname);
6295             return -1;
6296         }
6297         qname += pref_len + 1;
6298         qname_len -= pref_len + 1;
6299     } else {
6300         moveto_mod = NULL;
6301     }
6302 
6303     /* can be optimized similarly to moveto_node_alldesc() and save considerable amount of memory,
6304      * but it likely won't be used much, so it's a waste of time */
6305     /* copy the context */
6306     set_all_desc = set_copy(set);
6307     /* get all descendant nodes (the original context nodes are removed) */
6308     ret = moveto_node_alldesc(set_all_desc, cur_node, local_mod, "*", 1, options);
6309     if (ret) {
6310         lyxp_set_free(set_all_desc);
6311         return ret;
6312     }
6313     /* prepend the original context nodes */
6314     if (moveto_union(set, set_all_desc, cur_node, options)) {
6315         lyxp_set_free(set_all_desc);
6316         return -1;
6317     }
6318     lyxp_set_free(set_all_desc);
6319 
6320     if ((qname_len == 1) && (qname[0] == '*')) {
6321         all = 1;
6322     }
6323 
6324     for (i = 0; i < set->used; ) {
6325         replaced = 0;
6326 
6327         /* only attributes of an elem can be in the result, skip all the rest,
6328          * we have all attributes qualified in lyd tree */
6329         if (set->val.nodes[i].type == LYXP_NODE_ELEM) {
6330             LY_TREE_FOR(set->val.nodes[i].node->attr, sub) {
6331                 /* check "namespace" */
6332                 if (moveto_mod && (sub->annotation->module != moveto_mod)) {
6333                     /* no match */
6334                     continue;
6335                 }
6336 
6337                 if (all || (!strncmp(sub->name, qname, qname_len) && !sub->name[qname_len])) {
6338                     /* match */
6339                     if (!replaced) {
6340                         set->val.attrs[i].attr = sub;
6341                         set->val.attrs[i].type = LYXP_NODE_ATTR;
6342                         /* pos does not change */
6343                         replaced = 1;
6344                     } else {
6345                         set_insert_node(set, (struct lyd_node *)sub, set->val.attrs[i].pos, LYXP_NODE_ATTR, i + 1);
6346                     }
6347                     ++i;
6348                 }
6349             }
6350         }
6351 
6352         if (!replaced) {
6353             /* no match */
6354             set_remove_node(set, i);
6355         }
6356     }
6357 
6358     return EXIT_SUCCESS;
6359 }
6360 
6361 static int
moveto_self_add_children_r(const struct lyd_node * parent,uint32_t parent_pos,enum lyxp_node_type parent_type,struct lyxp_set * to_set,const struct lyxp_set * dup_check_set,enum lyxp_node_type root_type,int options)6362 moveto_self_add_children_r(const struct lyd_node *parent, uint32_t parent_pos, enum lyxp_node_type parent_type,
6363                            struct lyxp_set *to_set, const struct lyxp_set *dup_check_set, enum lyxp_node_type root_type,
6364                            int options)
6365 {
6366     const struct lyd_node *sub;
6367     int ret;
6368 
6369     switch (parent_type) {
6370     case LYXP_NODE_ROOT:
6371     case LYXP_NODE_ROOT_CONFIG:
6372         /* add all top-level nodes as elements */
6373         LY_TREE_FOR(parent, sub) {
6374             if ((parent_type == LYXP_NODE_ROOT_CONFIG) && (sub->schema->flags & LYS_CONFIG_R)) {
6375                 continue;
6376             }
6377 
6378             if (!set_dup_node_check(dup_check_set, sub, LYXP_NODE_ELEM, -1)) {
6379                 set_insert_node(to_set, sub, 0, LYXP_NODE_ELEM, to_set->used);
6380 
6381                 /* skip anydata/anyxml and dummy nodes */
6382                 if (!(sub->schema->nodetype & LYS_ANYDATA) && !(sub->validity & LYD_VAL_INUSE)) {
6383                     /* also add all the children of this node, recursively */
6384                     ret = moveto_self_add_children_r(sub, 0, LYXP_NODE_ELEM, to_set, dup_check_set, root_type, options);
6385                     if (ret) {
6386                         return ret;
6387                     }
6388                 }
6389             }
6390         }
6391         break;
6392     case LYXP_NODE_ELEM:
6393         /* add all the children ... */
6394         if (!(parent->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
6395             LY_TREE_FOR(parent->child, sub) {
6396                 /* context check */
6397                 if ((root_type == LYXP_NODE_ROOT_CONFIG) && (sub->schema->flags & LYS_CONFIG_R)) {
6398                     continue;
6399                 }
6400 
6401                 /* when check */
6402                 if ((options & LYXP_WHEN) && !LYD_WHEN_DONE(sub->when_status)) {
6403                     return EXIT_FAILURE;
6404                 }
6405 
6406                 if (!set_dup_node_check(dup_check_set, sub, LYXP_NODE_ELEM, -1)) {
6407                     set_insert_node(to_set, sub, 0, LYXP_NODE_ELEM, to_set->used);
6408 
6409                     /* skip anydata/anyxml and dummy nodes */
6410                     if ((sub->schema->nodetype & LYS_ANYDATA) || (sub->validity & LYD_VAL_INUSE)) {
6411                         continue;
6412                     }
6413 
6414                     /* also add all the children of this node, recursively */
6415                     ret = moveto_self_add_children_r(sub, 0, LYXP_NODE_ELEM, to_set, dup_check_set, root_type, options);
6416                     if (ret) {
6417                         return ret;
6418                     }
6419                 }
6420             }
6421 
6422         /* ... or add their text node, ... */
6423         } else {
6424             /* ... but only non-empty */
6425             if (((struct lyd_node_leaf_list *)parent)->value_str) {
6426                 if (!set_dup_node_check(dup_check_set, parent, LYXP_NODE_TEXT, -1)) {
6427                     set_insert_node(to_set, parent, parent_pos, LYXP_NODE_TEXT, to_set->used);
6428                 }
6429             }
6430         }
6431         break;
6432     default:
6433         LOGINT(lyd_node_module(parent)->ctx);
6434         return -1;
6435     }
6436 
6437     return EXIT_SUCCESS;
6438 }
6439 
6440 /**
6441  * @brief Move context \p set to self. Handles '/' or '//' and '.'. Result is LYXP_SET_NODE_SET
6442  *        (or LYXP_SET_EMPTY). Context position aware.
6443  *
6444  * @param[in,out] set Set to use.
6445  * @param[in] cur_node Original context node.
6446  * @param[in] all_desc Whether to go to all descendants ('//') or not ('/').
6447  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
6448  *
6449  * @return EXIT_SUCCESS on success, EXIT_FAILURE on unresolved when, -1 on error.
6450  */
6451 static int
moveto_self(struct lyxp_set * set,struct lyd_node * cur_node,int all_desc,int options)6452 moveto_self(struct lyxp_set *set, struct lyd_node *cur_node, int all_desc, int options)
6453 {
6454     uint32_t i;
6455     enum lyxp_node_type root_type;
6456     struct lyxp_set ret_set;
6457     int ret;
6458 
6459     if (!set || (set->type == LYXP_SET_EMPTY)) {
6460         return EXIT_SUCCESS;
6461     }
6462 
6463     if (set->type != LYXP_SET_NODE_SET) {
6464         LOGVAL(cur_node->schema->module->ctx, LYE_XPATH_INOP_1, LY_VLOG_NONE, NULL, "path operator", print_set_type(set));
6465         return -1;
6466     }
6467 
6468     /* nothing to do */
6469     if (!all_desc) {
6470         return EXIT_SUCCESS;
6471     }
6472 
6473     moveto_get_root(cur_node, options, &root_type);
6474 
6475     /* add all the children, they get added recursively */
6476     memset(&ret_set, 0, sizeof ret_set);
6477     for (i = 0; i < set->used; ++i) {
6478         /* copy the current node to tmp */
6479         set_insert_node(&ret_set, set->val.nodes[i].node, set->val.nodes[i].pos, set->val.nodes[i].type, ret_set.used);
6480 
6481         /* do not touch attributes and text nodes */
6482         if ((set->val.nodes[i].type == LYXP_NODE_TEXT) || (set->val.nodes[i].type == LYXP_NODE_ATTR)) {
6483             continue;
6484         }
6485 
6486         /* skip anydata/anyxml and dummy nodes */
6487         if ((set->val.nodes[i].node->schema->nodetype & LYS_ANYDATA) || (set->val.nodes[i].node->validity & LYD_VAL_INUSE)) {
6488             continue;
6489         }
6490 
6491         /* add all the children */
6492         ret = moveto_self_add_children_r(set->val.nodes[i].node, set->val.nodes[i].pos, set->val.nodes[i].type, &ret_set,
6493                                          set, root_type, options);
6494         if (ret) {
6495             set_free_content(&ret_set);
6496             return ret;
6497         }
6498     }
6499 
6500     /* use the temporary set as the current one */
6501     ret_set.ctx_pos = set->ctx_pos;
6502     ret_set.ctx_size = set->ctx_size;
6503     set_free_content(set);
6504     memcpy(set, &ret_set, sizeof *set);
6505 
6506     return EXIT_SUCCESS;
6507 }
6508 
6509 static int
moveto_snode_self(struct lyxp_set * set,struct lys_node * cur_node,int all_desc,int options)6510 moveto_snode_self(struct lyxp_set *set, struct lys_node *cur_node, int all_desc, int options)
6511 {
6512     const struct lys_node *sub;
6513     uint32_t i;
6514     enum lyxp_node_type root_type;
6515 
6516     if (!set || (set->type == LYXP_SET_EMPTY)) {
6517         return EXIT_SUCCESS;
6518     }
6519 
6520     if (set->type != LYXP_SET_SNODE_SET) {
6521         LOGVAL(cur_node->module->ctx, LYE_XPATH_INOP_1, LY_VLOG_NONE, NULL, "path operator", print_set_type(set));
6522         return -1;
6523     }
6524 
6525     /* nothing to do */
6526     if (!all_desc) {
6527         return EXIT_SUCCESS;
6528     }
6529 
6530     moveto_snode_get_root(cur_node, options, &root_type);
6531 
6532     /* add all the children, they get added recursively */
6533     for (i = 0; i < set->used; ++i) {
6534         if (set->val.snodes[i].in_ctx != 1) {
6535             continue;
6536         }
6537 
6538         /* add all the children */
6539         if (set->val.snodes[i].snode->nodetype & (LYS_LIST | LYS_CONTAINER)) {
6540             sub = NULL;
6541             while ((sub = lys_getnext(sub, set->val.snodes[i].snode, NULL, LYS_GETNEXT_NOSTATECHECK))) {
6542                 /* RPC input/output check */
6543                 if (options & LYXP_SNODE_OUTPUT) {
6544                     if (lys_parent(sub)->nodetype == LYS_INPUT) {
6545                         continue;
6546                     }
6547                 } else {
6548                     if (lys_parent(sub)->nodetype == LYS_OUTPUT) {
6549                         continue;
6550                     }
6551                 }
6552 
6553                 /* context check */
6554                 if ((root_type == LYXP_NODE_ROOT_CONFIG) && (sub->flags & LYS_CONFIG_R)) {
6555                     continue;
6556                 }
6557 
6558                 set_snode_insert_node(set, sub, LYXP_NODE_ELEM);
6559                 /* throw away the insert index, we want to consider that node again, recursively */
6560             }
6561         }
6562     }
6563 
6564     return EXIT_SUCCESS;
6565 }
6566 
6567 /**
6568  * @brief Move context \p set to parent. Handles '/' or '//' and '..'. Result is LYXP_SET_NODE_SET
6569  *        (or LYXP_SET_EMPTY). Context position aware.
6570  *
6571  * @param[in] set Set to use.
6572  * @param[in] cur_node Original context node.
6573  * @param[in] all_desc Whether to go to all descendants ('//') or not ('/').
6574  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
6575  *
6576  * @return EXIT_SUCCESS on success, EXIT_FAILURE on unresolved when, -1 on error.
6577  */
6578 static int
moveto_parent(struct lyxp_set * set,struct lyd_node * cur_node,int all_desc,int options)6579 moveto_parent(struct lyxp_set *set, struct lyd_node *cur_node, int all_desc, int options)
6580 {
6581     struct ly_ctx *ctx = cur_node->schema->module->ctx;
6582     int ret;
6583     uint32_t i;
6584     struct lyd_node *node, *new_node;
6585     const struct lyd_node *root;
6586     enum lyxp_node_type root_type, new_type;
6587 
6588     if (!set || (set->type == LYXP_SET_EMPTY)) {
6589         return EXIT_SUCCESS;
6590     }
6591 
6592     if (set->type != LYXP_SET_NODE_SET) {
6593         LOGVAL(ctx, LYE_XPATH_INOP_1, LY_VLOG_NONE, NULL, "path operator", print_set_type(set));
6594         return -1;
6595     }
6596 
6597     if (all_desc) {
6598         /* <path>//.. == <path>//./.. */
6599         ret = moveto_self(set, cur_node, 1, options);
6600         if (ret) {
6601             return ret;
6602         }
6603     }
6604 
6605     root = moveto_get_root(cur_node, options, &root_type);
6606 
6607     for (i = 0; i < set->used; ) {
6608         node = set->val.nodes[i].node;
6609 
6610         if (set->val.nodes[i].type == LYXP_NODE_ELEM) {
6611             new_node = node->parent;
6612         } else if (set->val.nodes[i].type == LYXP_NODE_TEXT) {
6613             new_node = node;
6614         } else if (set->val.nodes[i].type == LYXP_NODE_ATTR) {
6615             new_node = (struct lyd_node *)lyd_attr_parent(root, set->val.attrs[i].attr);
6616             if (!new_node) {
6617                 LOGINT(ctx);
6618                 return -1;
6619             }
6620         } else {
6621             /* root does not have a parent */
6622             set_remove_node(set, i);
6623             continue;
6624         }
6625 
6626         /* when check */
6627         if ((options & LYXP_WHEN) && new_node && !LYD_WHEN_DONE(new_node->when_status)) {
6628             return EXIT_FAILURE;
6629         }
6630 
6631         /* node already there can also be the root */
6632         if (root == node) {
6633             if (options && (cur_node->schema->flags & LYS_CONFIG_W)) {
6634                 new_type = LYXP_NODE_ROOT_CONFIG;
6635             } else {
6636                 new_type = LYXP_NODE_ROOT;
6637             }
6638             new_node = node;
6639 
6640         /* node has no parent */
6641         } else if (!new_node) {
6642             if (options && (cur_node->schema->flags & LYS_CONFIG_W)) {
6643                 new_type = LYXP_NODE_ROOT_CONFIG;
6644             } else {
6645                 new_type = LYXP_NODE_ROOT;
6646             }
6647 #ifndef NDEBUG
6648             for (; node->prev->next; node = node->prev);
6649             if (node != root) {
6650                 LOGINT(ctx);
6651             }
6652 #endif
6653             new_node = (struct lyd_node *)root;
6654 
6655         /* node has a standard parent (it can equal the root, it's not the root yet since they are fake) */
6656         } else {
6657             new_type = LYXP_NODE_ELEM;
6658         }
6659 
6660         assert((new_type == LYXP_NODE_ELEM) || ((new_type == root_type) && (new_node == root)));
6661 
6662         if (set_dup_node_check(set, new_node, new_type, -1)) {
6663             set_remove_node(set, i);
6664         } else {
6665             set_replace_node(set, new_node, 0, new_type, i);
6666             ++i;
6667         }
6668     }
6669 
6670     assert(!set_sort(set, cur_node, options) && !set_sorted_dup_node_clean(set));
6671 
6672     return EXIT_SUCCESS;
6673 }
6674 
6675 static int
moveto_snode_parent(struct lyxp_set * set,struct lys_node * cur_node,int all_desc,int options)6676 moveto_snode_parent(struct lyxp_set *set, struct lys_node *cur_node, int all_desc, int options)
6677 {
6678     int idx, i, orig_used, temp_ctx = 0;
6679     struct lys_node *node, *new_node;
6680     const struct lys_node *root;
6681     enum lyxp_node_type root_type, new_type;
6682 
6683     if (!set || (set->type == LYXP_SET_EMPTY)) {
6684         return EXIT_SUCCESS;
6685     }
6686 
6687     if (set->type != LYXP_SET_SNODE_SET) {
6688         LOGVAL(cur_node->module->ctx, LYE_XPATH_INOP_1, LY_VLOG_NONE, NULL, "path operator", print_set_type(set));
6689         return -1;
6690     }
6691 
6692     if (all_desc) {
6693         /* <path>//.. == <path>//./.. */
6694         idx = moveto_snode_self(set, cur_node, 1, options);
6695         if (idx) {
6696             return idx;
6697         }
6698     }
6699 
6700     root = moveto_snode_get_root(cur_node, options, &root_type);
6701 
6702     orig_used = set->used;
6703     for (i = 0; i < orig_used; ++i) {
6704         if (set->val.snodes[i].in_ctx != 1) {
6705             continue;
6706         }
6707         set->val.snodes[i].in_ctx = 0;
6708 
6709         node = set->val.snodes[i].snode;
6710 
6711         if (set->val.snodes[i].type == LYXP_NODE_ELEM) {
6712             for (new_node = lys_parent(node);
6713                  new_node && (new_node->nodetype & (LYS_USES | LYS_CHOICE | LYS_CASE | LYS_INPUT | LYS_OUTPUT));
6714                  new_node = lys_parent(new_node));
6715         } else {
6716             /* root does not have a parent */
6717             continue;
6718         }
6719 
6720         /* node already there can also be the root */
6721         if (root == node) {
6722             if ((options & (LYXP_SNODE_MUST | LYXP_SNODE_WHEN)) && (cur_node->flags & LYS_CONFIG_W)) {
6723                 new_type = LYXP_NODE_ROOT_CONFIG;
6724             } else {
6725                 new_type = LYXP_NODE_ROOT;
6726             }
6727             new_node = node;
6728 
6729         /* node has no parent */
6730         } else if (!new_node) {
6731             if ((options & (LYXP_SNODE_MUST | LYXP_SNODE_WHEN)) && (cur_node->flags & LYS_CONFIG_W)) {
6732                 new_type = LYXP_NODE_ROOT_CONFIG;
6733             } else {
6734                 new_type = LYXP_NODE_ROOT;
6735             }
6736 #ifndef NDEBUG
6737             node = (struct lys_node *)lys_getnext(NULL, NULL, lys_node_module(node), LYS_GETNEXT_NOSTATECHECK);
6738             if (node != root) {
6739                 LOGINT(cur_node->module->ctx);
6740             }
6741 #endif
6742             new_node = (struct lys_node *)root;
6743 
6744         /* node has a standard parent (it can equal the root, it's not the root yet since they are fake) */
6745         } else {
6746             new_type = LYXP_NODE_ELEM;
6747         }
6748 
6749         assert((new_type == LYXP_NODE_ELEM) || ((new_type == root_type) && (new_node == root)));
6750 
6751         idx = set_snode_insert_node(set, new_node, new_type);
6752         if ((idx < orig_used) && (idx > i)) {
6753             set->val.snodes[idx].in_ctx = 2;
6754             temp_ctx = 1;
6755         }
6756     }
6757 
6758     if (temp_ctx) {
6759         for (i = 0; i < orig_used; ++i) {
6760             if (set->val.snodes[i].in_ctx == 2) {
6761                 set->val.snodes[i].in_ctx = 1;
6762             }
6763         }
6764     }
6765 
6766     return EXIT_SUCCESS;
6767 }
6768 
6769 /**
6770  * @brief Move context \p set to the result of a comparison. Handles '=', '!=', '<=', '<', '>=', or '>'.
6771  *        Result is LYXP_SET_BOOLEAN. Indirectly context position aware.
6772  *
6773  * @param[in,out] set1 Set to use for the result.
6774  * @param[in] set2 Set acting as the second operand for \p op.
6775  * @param[in] op Comparison operator to process.
6776  * @param[in] cur_node Original context node.
6777  *
6778  * @return EXIT_SUCCESS on success, -1 on error.
6779  */
6780 static int
moveto_op_comp(struct lyxp_set * set1,struct lyxp_set * set2,const char * op,struct lyd_node * cur_node,struct lys_module * local_mod,int options)6781 moveto_op_comp(struct lyxp_set *set1, struct lyxp_set *set2, const char *op, struct lyd_node *cur_node,
6782                struct lys_module *local_mod, int options)
6783 {
6784     /*
6785      * NODE SET + NODE SET = NODE SET + STRING /(1 NODE SET) 2 STRING
6786      * NODE SET + STRING = STRING + STRING     /1 STRING (2 STRING)
6787      * NODE SET + NUMBER = NUMBER + NUMBER     /1 NUMBER (2 NUMBER)
6788      * NODE SET + BOOLEAN = BOOLEAN + BOOLEAN  /1 BOOLEAN (2 BOOLEAN)
6789      * STRING + NODE SET = STRING + STRING     /(1 STRING) 2 STRING
6790      * NUMBER + NODE SET = NUMBER + NUMBER     /(1 NUMBER) 2 NUMBER
6791      * BOOLEAN + NODE SET = BOOLEAN + BOOLEAN  /(1 BOOLEAN) 2 BOOLEAN
6792      *
6793      * '=' or '!='
6794      * BOOLEAN + BOOLEAN
6795      * BOOLEAN + STRING = BOOLEAN + BOOLEAN    /(1 BOOLEAN) 2 BOOLEAN
6796      * BOOLEAN + NUMBER = BOOLEAN + BOOLEAN    /(1 BOOLEAN) 2 BOOLEAN
6797      * STRING + BOOLEAN = BOOLEAN + BOOLEAN    /1 BOOLEAN (2 BOOLEAN)
6798      * NUMBER + BOOLEAN = BOOLEAN + BOOLEAN    /1 BOOLEAN (2 BOOLEAN)
6799      * NUMBER + NUMBER
6800      * NUMBER + STRING = NUMBER + NUMBER       /(1 NUMBER) 2 NUMBER
6801      * STRING + NUMBER = NUMBER + NUMBER       /1 NUMBER (2 NUMBER)
6802      * STRING + STRING
6803      *
6804      * '<=', '<', '>=', '>'
6805      * NUMBER + NUMBER
6806      * BOOLEAN + BOOLEAN = NUMBER + NUMBER     /1 NUMBER, 2 NUMBER
6807      * BOOLEAN + NUMBER = NUMBER + NUMBER      /1 NUMBER (2 NUMBER)
6808      * BOOLEAN + STRING = NUMBER + NUMBER      /1 NUMBER, 2 NUMBER
6809      * NUMBER + STRING = NUMBER + NUMBER       /(1 NUMBER) 2 NUMBER
6810      * STRING + STRING = NUMBER + NUMBER       /1 NUMBER, 2 NUMBER
6811      * STRING + NUMBER = NUMBER + NUMBER       /1 NUMBER (2 NUMBER)
6812      * NUMBER + BOOLEAN = NUMBER + NUMBER      /(1 NUMBER) 2 NUMBER
6813      * STRING + BOOLEAN = NUMBER + NUMBER      /(1 NUMBER) 2 NUMBER
6814      */
6815     struct lyxp_set iter1, iter2;
6816     int result;
6817     int64_t i;
6818 
6819     iter1.type = LYXP_SET_EMPTY;
6820     iter2.type = LYXP_SET_EMPTY;
6821 
6822     /* empty node-sets are always false
6823      * ref: https://www.w3.org/TR/1999/REC-xpath-19991116/#booleans 5th paragraph, first sentece */
6824     if ((set1->type == LYXP_SET_EMPTY) || (set2->type == LYXP_SET_EMPTY)) {
6825         set_fill_boolean(set1, 0);
6826         return EXIT_SUCCESS;
6827     }
6828 
6829     /* iterative evaluation with node-sets */
6830     if ((set1->type == LYXP_SET_NODE_SET) || (set2->type == LYXP_SET_NODE_SET)) {
6831         if (set1->type == LYXP_SET_NODE_SET) {
6832             if (set2->type != LYXP_SET_NODE_SET) {
6833                 /* canonize the value (wait until set1 is not node set if both are) */
6834                 if (set_canonize(set2, set1)) {
6835                     return -1;
6836                 }
6837             }
6838             for (i = 0; i < set1->used; ++i) {
6839                 switch (set2->type) {
6840                 case LYXP_SET_NUMBER:
6841                     if (set_comp_cast(&iter1, set1, LYXP_SET_NUMBER, cur_node, local_mod, i, options)) {
6842                         return -1;
6843                     }
6844                     break;
6845                 case LYXP_SET_BOOLEAN:
6846                     if (set_comp_cast(&iter1, set1, LYXP_SET_BOOLEAN, cur_node, local_mod, i, options)) {
6847                         return -1;
6848                     }
6849                     break;
6850                 default:
6851                     if (set_comp_cast(&iter1, set1, LYXP_SET_STRING, cur_node, local_mod, i, options)) {
6852                         return -1;
6853                     }
6854                     break;
6855                 }
6856 
6857                 if (moveto_op_comp(&iter1, set2, op, cur_node, local_mod, options)) {
6858                     set_free_content(&iter1);
6859                     return -1;
6860                 }
6861 
6862                 /* lazy evaluation until true */
6863                 if (iter1.val.bool) {
6864                     set_fill_boolean(set1, 1);
6865                     return EXIT_SUCCESS;
6866                 }
6867             }
6868         } else {
6869             /* canonize the value */
6870             if (set_canonize(set1, set2)) {
6871                 return -1;
6872             }
6873             for (i = 0; i < set2->used; ++i) {
6874                 switch (set1->type) {
6875                     case LYXP_SET_NUMBER:
6876                         if (set_comp_cast(&iter2, set2, LYXP_SET_NUMBER, cur_node, local_mod, i, options)) {
6877                             return -1;
6878                         }
6879                         break;
6880                     case LYXP_SET_BOOLEAN:
6881                         if (set_comp_cast(&iter2, set2, LYXP_SET_BOOLEAN, cur_node, local_mod, i, options)) {
6882                             return -1;
6883                         }
6884                         break;
6885                     default:
6886                         if (set_comp_cast(&iter2, set2, LYXP_SET_STRING, cur_node, local_mod, i, options)) {
6887                             return -1;
6888                         }
6889                         break;
6890                 }
6891 
6892                 set_fill_set(&iter1, set1);
6893 
6894                 if (moveto_op_comp(&iter1, &iter2, op, cur_node, local_mod, options)) {
6895                     set_free_content(&iter1);
6896                     set_free_content(&iter2);
6897                     return -1;
6898                 }
6899                 set_free_content(&iter2);
6900 
6901                 /* lazy evaluation until true */
6902                 if (iter1.val.bool) {
6903                     set_fill_boolean(set1, 1);
6904                     return EXIT_SUCCESS;
6905                 }
6906             }
6907         }
6908 
6909         /* false for all nodes */
6910         set_fill_boolean(set1, 0);
6911         return EXIT_SUCCESS;
6912     }
6913 
6914     /* first convert properly */
6915     if ((op[0] == '=') || (op[0] == '!')) {
6916         if ((set1->type == LYXP_SET_BOOLEAN) || (set2->type == LYXP_SET_BOOLEAN)) {
6917             lyxp_set_cast(set1, LYXP_SET_BOOLEAN, cur_node, local_mod, options);
6918             lyxp_set_cast(set2, LYXP_SET_BOOLEAN, cur_node, local_mod, options);
6919         } else if ((set1->type == LYXP_SET_NUMBER) || (set2->type == LYXP_SET_NUMBER)) {
6920             if (lyxp_set_cast(set1, LYXP_SET_NUMBER, cur_node, local_mod, options)) {
6921                 return -1;
6922             }
6923             if (lyxp_set_cast(set2, LYXP_SET_NUMBER, cur_node, local_mod, options)) {
6924                 return -1;
6925             }
6926         } /* else we have 2 strings */
6927     } else {
6928         if (lyxp_set_cast(set1, LYXP_SET_NUMBER, cur_node, local_mod, options)) {
6929             return -1;
6930         }
6931         if (lyxp_set_cast(set2, LYXP_SET_NUMBER, cur_node, local_mod, options)) {
6932             return -1;
6933         }
6934     }
6935 
6936     assert(set1->type == set2->type);
6937 
6938     /* compute result */
6939     if (op[0] == '=') {
6940         if (set1->type == LYXP_SET_BOOLEAN) {
6941             result = (set1->val.bool == set2->val.bool);
6942         } else if (set1->type == LYXP_SET_NUMBER) {
6943             result = (set1->val.num == set2->val.num);
6944         } else {
6945             assert(set1->type == LYXP_SET_STRING);
6946             result = (ly_strequal(set1->val.str, set2->val.str, 0));
6947         }
6948     } else if (op[0] == '!') {
6949         if (set1->type == LYXP_SET_BOOLEAN) {
6950             result = (set1->val.bool != set2->val.bool);
6951         } else if (set1->type == LYXP_SET_NUMBER) {
6952             result = (set1->val.num != set2->val.num);
6953         } else {
6954             assert(set1->type == LYXP_SET_STRING);
6955             result = (!ly_strequal(set1->val.str, set2->val.str, 0));
6956         }
6957     } else {
6958         assert(set1->type == LYXP_SET_NUMBER);
6959         if (op[0] == '<') {
6960             if (op[1] == '=') {
6961                 result = (set1->val.num <= set2->val.num);
6962             } else {
6963                 result = (set1->val.num < set2->val.num);
6964             }
6965         } else {
6966             if (op[1] == '=') {
6967                 result = (set1->val.num >= set2->val.num);
6968             } else {
6969                 result = (set1->val.num > set2->val.num);
6970             }
6971         }
6972     }
6973 
6974     /* assign result */
6975     if (result) {
6976         set_fill_boolean(set1, 1);
6977     } else {
6978         set_fill_boolean(set1, 0);
6979     }
6980 
6981     return EXIT_SUCCESS;
6982 }
6983 
6984 /**
6985  * @brief Move context \p set to the result of a basic operation. Handles '+', '-', unary '-', '*', 'div',
6986  *        or 'mod'. Result is LYXP_SET_NUMBER. Indirectly context position aware.
6987  *
6988  * @param[in,out] set1 Set to use for the result.
6989  * @param[in] set2 Set acting as the second operand for \p op.
6990  * @param[in] op Operator to process.
6991  * @param[in] cur_node Original context node.
6992  *
6993  * @return EXIT_SUCCESS on success, -1 on error.
6994  */
6995 static int
moveto_op_math(struct lyxp_set * set1,struct lyxp_set * set2,const char * op,struct lyd_node * cur_node,struct lys_module * local_mod,int options)6996 moveto_op_math(struct lyxp_set *set1, struct lyxp_set *set2, const char *op, struct lyd_node *cur_node,
6997                struct lys_module *local_mod, int options)
6998 {
6999     /* unary '-' */
7000     if (!set2 && (op[0] == '-')) {
7001         if (lyxp_set_cast(set1, LYXP_SET_NUMBER, cur_node, local_mod, options)) {
7002             return -1;
7003         }
7004         set1->val.num *= -1;
7005         lyxp_set_free(set2);
7006         return EXIT_SUCCESS;
7007     }
7008 
7009     assert(set1 && set2);
7010 
7011     if (lyxp_set_cast(set1, LYXP_SET_NUMBER, cur_node, local_mod, options)) {
7012         return -1;
7013     }
7014     if (lyxp_set_cast(set2, LYXP_SET_NUMBER, cur_node, local_mod, options)) {
7015         return -1;
7016     }
7017 
7018     switch (op[0]) {
7019     /* '+' */
7020     case '+':
7021         set1->val.num += set2->val.num;
7022         break;
7023 
7024     /* '-' */
7025     case '-':
7026         set1->val.num -= set2->val.num;
7027         break;
7028 
7029     /* '*' */
7030     case '*':
7031         set1->val.num *= set2->val.num;
7032         break;
7033 
7034     /* 'div' */
7035     case 'd':
7036         set1->val.num /= set2->val.num;
7037         break;
7038 
7039     /* 'mod' */
7040     case 'm':
7041         set1->val.num = ((long long)set1->val.num) % ((long long)set2->val.num);
7042         break;
7043 
7044     default:
7045         LOGINT(local_mod ? local_mod->ctx : NULL);
7046         return -1;
7047     }
7048 
7049     return EXIT_SUCCESS;
7050 }
7051 
7052 /*
7053  * eval functions
7054  *
7055  * They execute a parsed XPath expression on some data subtree.
7056  */
7057 
7058 /**
7059  * @brief Evaluate Literal. Logs directly on error.
7060  *
7061  * @param[in] exp Parsed XPath expression.
7062  * @param[in] exp_idx Position in the expression \p exp.
7063  * @param[in,out] set Context and result set. On NULL the rule is only parsed.
7064  *
7065  * @return EXIT_SUCCESS on success, -1 on error.
7066  */
7067 static void
eval_literal(struct lyxp_expr * exp,uint16_t * exp_idx,struct lyxp_set * set)7068 eval_literal(struct lyxp_expr *exp, uint16_t *exp_idx, struct lyxp_set *set)
7069 {
7070     if (set) {
7071         if (exp->tok_len[*exp_idx] == 2) {
7072             set_fill_string(set, "", 0);
7073         } else {
7074             set_fill_string(set, &exp->expr[exp->expr_pos[*exp_idx] + 1], exp->tok_len[*exp_idx] - 2);
7075         }
7076     }
7077     LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7078                print_token(exp->tokens[*exp_idx]), exp->expr_pos[*exp_idx]);
7079     ++(*exp_idx);
7080 }
7081 
7082 /**
7083  * @brief Evaluate NodeTest. Logs directly on error.
7084  *
7085  * [6] NodeTest ::= NameTest | NodeType '(' ')'
7086  *
7087  * @param[in] exp Parsed XPath expression.
7088  * @param[in] exp_idx Position in the expression \p exp.
7089  * @param[in] cur_node Start node for the expression \p exp.
7090  * @param[in] attr_axis Whether to search attributes or standard nodes.
7091  * @param[in] all_desc Whether to search all the descendants or children only.
7092  * @param[in,out] set Context and result set. On NULL the rule is only parsed.
7093  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
7094  *
7095  * @return EXIT_SUCCESS on success, EXIT_FAILURE on unresolved when, -1 on error.
7096  */
7097 static int
eval_node_test(struct lyxp_expr * exp,uint16_t * exp_idx,struct lyd_node * cur_node,struct lys_module * local_mod,int attr_axis,int all_desc,struct lyxp_set * set,int options)7098 eval_node_test(struct lyxp_expr *exp, uint16_t *exp_idx, struct lyd_node *cur_node, struct lys_module *local_mod,
7099                int attr_axis, int all_desc, struct lyxp_set *set, int options)
7100 {
7101     int i, rc = 0;
7102     char *path;
7103 
7104     switch (exp->tokens[*exp_idx]) {
7105     case LYXP_TOKEN_NAMETEST:
7106         if (attr_axis) {
7107             if (set && (options & LYXP_SNODE_ALL)) {
7108                 set_snode_clear_ctx(set);
7109             } else {
7110                 if (all_desc) {
7111                     rc = moveto_attr_alldesc(set, cur_node, local_mod, &exp->expr[exp->expr_pos[*exp_idx]],
7112                                              exp->tok_len[*exp_idx], options);
7113                 } else {
7114                     rc = moveto_attr(set, cur_node, &exp->expr[exp->expr_pos[*exp_idx]], exp->tok_len[*exp_idx],
7115                                      options);
7116                 }
7117             }
7118         } else {
7119             if (all_desc) {
7120                 if (set && (options & LYXP_SNODE_ALL)) {
7121                     rc = moveto_snode_alldesc(set, (struct lys_node *)cur_node, local_mod, &exp->expr[exp->expr_pos[*exp_idx]],
7122                                               exp->tok_len[*exp_idx], options);
7123                 } else {
7124                     rc = moveto_node_alldesc(set, cur_node, local_mod, &exp->expr[exp->expr_pos[*exp_idx]],
7125                                              exp->tok_len[*exp_idx], options);
7126                 }
7127             } else {
7128                 if (set && (options & LYXP_SNODE_ALL)) {
7129                     rc = moveto_snode(set, (struct lys_node *)cur_node, local_mod, &exp->expr[exp->expr_pos[*exp_idx]],
7130                                       exp->tok_len[*exp_idx], options);
7131                 } else {
7132                     rc = moveto_node(set, cur_node, local_mod, &exp->expr[exp->expr_pos[*exp_idx]], exp->tok_len[*exp_idx],
7133                                      options);
7134                 }
7135             }
7136 
7137             if (!rc && set && (options & LYXP_SNODE_ALL)) {
7138                 for (i = set->used - 1; i > -1; --i) {
7139                     if (set->val.snodes[i].in_ctx) {
7140                         break;
7141                     }
7142                 }
7143                 if (i == -1) {
7144                     path = lys_path((struct lys_node *)cur_node, LYS_PATH_FIRST_PREFIX);
7145                     LOGWRN(local_mod->ctx, "Schema node \"%.*s\" not found (%.*s) with context node \"%s\".",
7146                            exp->tok_len[*exp_idx], &exp->expr[exp->expr_pos[*exp_idx]],
7147                            exp->expr_pos[*exp_idx] + exp->tok_len[*exp_idx], exp->expr, path);
7148                     free(path);
7149                 }
7150             }
7151         }
7152         if (rc) {
7153             return rc;
7154         }
7155 
7156         LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7157                print_token(exp->tokens[*exp_idx]), exp->expr_pos[*exp_idx]);
7158         ++(*exp_idx);
7159         break;
7160 
7161     case LYXP_TOKEN_NODETYPE:
7162         if (set) {
7163             assert(exp->tok_len[*exp_idx] == 4);
7164             if (set->type == LYXP_SET_SNODE_SET) {
7165                 set_snode_clear_ctx(set);
7166                 /* just for the debug message underneath */
7167                 set = NULL;
7168             } else {
7169                 if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "node", 4)) {
7170                     if (xpath_node(NULL, 0, cur_node, local_mod, set, options)) {
7171                         return -1;
7172                     }
7173                 } else {
7174                     assert(!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "text", 4));
7175                     if (xpath_text(NULL, 0, cur_node, local_mod, set, options)) {
7176                         return -1;
7177                     }
7178                 }
7179             }
7180         }
7181         LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7182                print_token(exp->tokens[*exp_idx]), exp->expr_pos[*exp_idx]);
7183         ++(*exp_idx);
7184 
7185         /* '(' */
7186         assert(exp->tokens[*exp_idx] == LYXP_TOKEN_PAR1);
7187         LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7188                print_token(exp->tokens[*exp_idx]), exp->expr_pos[*exp_idx]);
7189         ++(*exp_idx);
7190 
7191         /* ')' */
7192         assert(exp->tokens[*exp_idx] == LYXP_TOKEN_PAR2);
7193         LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7194                print_token(exp->tokens[*exp_idx]), exp->expr_pos[*exp_idx]);
7195         ++(*exp_idx);
7196         break;
7197 
7198     default:
7199         LOGINT(local_mod ? local_mod->ctx : NULL);
7200         return -1;
7201     }
7202 
7203     return EXIT_SUCCESS;
7204 }
7205 
7206 /**
7207  * @brief Evaluate Predicate. Logs directly on error.
7208  *
7209  * [7] Predicate ::= '[' Expr ']'
7210  *
7211  * @param[in] exp Parsed XPath expression.
7212  * @param[in] exp_idx Position in the expression \p exp.
7213  * @param[in] cur_node Start node for the expression \p exp.
7214  * @param[in,out] set Context and result set. On NULL the rule is only parsed.
7215  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
7216  *
7217  * @return EXIT_SUCCESS on success, EXIT_FAILURE on unresolved when, -1 on error.
7218  */
7219 static int
eval_predicate(struct lyxp_expr * exp,uint16_t * exp_idx,struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options,int parent_pos_pred)7220 eval_predicate(struct lyxp_expr *exp, uint16_t *exp_idx, struct lyd_node *cur_node, struct lys_module *local_mod,
7221                struct lyxp_set *set, int options, int parent_pos_pred)
7222 {
7223     int ret;
7224     uint16_t orig_exp;
7225     uint32_t i, orig_pos, orig_size, pred_in_ctx;
7226     struct lyxp_set set2;
7227     struct lyd_node *orig_parent;
7228 
7229     /* '[' */
7230     LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7231            print_token(exp->tokens[*exp_idx]), exp->expr_pos[*exp_idx]);
7232     ++(*exp_idx);
7233 
7234     if (!set) {
7235 only_parse:
7236         ret = eval_expr_select(exp, exp_idx, 0, cur_node, local_mod, NULL, options);
7237         if (ret == -1 || ret == EXIT_FAILURE) {
7238             return ret;
7239         }
7240     } else if (set->type == LYXP_SET_NODE_SET) {
7241         /* we (possibly) need the set sorted, it can affect the result (if the predicate result is a number) */
7242         assert(!set_sort(set, cur_node, options));
7243 
7244         /* empty set, nothing to evaluate */
7245         if (!set->used) {
7246             goto only_parse;
7247         }
7248 
7249         orig_exp = *exp_idx;
7250         orig_pos = 0;
7251         orig_size = set->used;
7252         orig_parent = NULL;
7253         for (i = 0; i < set->used; ++i) {
7254             memset(&set2, 0, sizeof set2);
7255             set_insert_node(&set2, set->val.nodes[i].node, set->val.nodes[i].pos, set->val.nodes[i].type, 0);
7256             /* remember the node context position for position() and context size for last(),
7257              * predicates should always be evaluated with respect to the child axis (since we do
7258              * not support explicit axes) so we assign positions based on their parents */
7259             if (parent_pos_pred && (set->val.nodes[i].node->parent != orig_parent)) {
7260                 orig_parent = set->val.nodes[i].node->parent;
7261                 orig_pos = 1;
7262             } else {
7263                 ++orig_pos;
7264             }
7265 
7266             set2.ctx_pos = orig_pos;
7267             set2.ctx_size = orig_size;
7268             *exp_idx = orig_exp;
7269 
7270             ret = eval_expr_select(exp, exp_idx, 0, cur_node, local_mod, &set2, options);
7271             if (ret == -1 || ret == EXIT_FAILURE) {
7272                 lyxp_set_cast(&set2, LYXP_SET_EMPTY, cur_node, local_mod, options);
7273                 return ret;
7274             }
7275 
7276             /* number is a position */
7277             if (set2.type == LYXP_SET_NUMBER) {
7278                 if ((long long)set2.val.num == orig_pos) {
7279                     set2.val.num = 1;
7280                 } else {
7281                     set2.val.num = 0;
7282                 }
7283             }
7284             lyxp_set_cast(&set2, LYXP_SET_BOOLEAN, cur_node, local_mod, options);
7285 
7286             /* predicate satisfied or not? */
7287             if (!set2.val.bool) {
7288 #ifdef LY_ENABLED_CACHE
7289                 set_remove_node_hash(set, set->val.nodes[i].node, set->val.nodes[i].type);
7290 #endif
7291                 set->val.nodes[i].type = LYXP_NODE_NONE;
7292             }
7293         }
7294 
7295         /* now actually remove all nodes that have not satisfied the predicate */
7296         set_remove_none_nodes(set);
7297 
7298     } else if (set->type == LYXP_SET_SNODE_SET) {
7299         for (i = 0; i < set->used; ++i) {
7300             if (set->val.snodes[i].in_ctx == 1) {
7301                 /* there is a currently-valid node */
7302                 break;
7303             }
7304         }
7305         /* empty set, nothing to evaluate */
7306         if (i == set->used) {
7307             goto only_parse;
7308         }
7309 
7310         orig_exp = *exp_idx;
7311 
7312         /* set special in_ctx to all the valid snodes */
7313         pred_in_ctx = set_snode_new_in_ctx(set);
7314 
7315         /* use the valid snodes one-by-one */
7316         for (i = 0; i < set->used; ++i) {
7317             if (set->val.snodes[i].in_ctx != pred_in_ctx) {
7318                 continue;
7319             }
7320             set->val.snodes[i].in_ctx = 1;
7321 
7322             *exp_idx = orig_exp;
7323 
7324             ret = eval_expr_select(exp, exp_idx, 0, cur_node, local_mod, set, options);
7325             if (ret == -1 || ret == EXIT_FAILURE) {
7326                 return ret;
7327             }
7328 
7329             set->val.snodes[i].in_ctx = pred_in_ctx;
7330         }
7331 
7332         /* restore the state as it was before the predicate */
7333         for (i = 0; i < set->used; ++i) {
7334             if (set->val.snodes[i].in_ctx == 1) {
7335                 set->val.snodes[i].in_ctx = 0;
7336             } else if (set->val.snodes[i].in_ctx == pred_in_ctx) {
7337                 set->val.snodes[i].in_ctx = 1;
7338             }
7339         }
7340 
7341     } else {
7342         set2.type = LYXP_SET_EMPTY;
7343         set_fill_set(&set2, set);
7344 
7345         ret = eval_expr_select(exp, exp_idx, 0, cur_node, local_mod, &set2, options);
7346         if (ret == -1 || ret == EXIT_FAILURE) {
7347             lyxp_set_cast(&set2, LYXP_SET_EMPTY, cur_node, local_mod, options);
7348             return ret;
7349         }
7350 
7351         lyxp_set_cast(&set2, LYXP_SET_BOOLEAN, cur_node, local_mod, options);
7352         if (!set2.val.bool) {
7353             lyxp_set_cast(set, LYXP_SET_EMPTY, cur_node, local_mod, options);
7354         }
7355         lyxp_set_cast(&set2, LYXP_SET_EMPTY, cur_node, local_mod, options);
7356     }
7357 
7358     /* ']' */
7359     assert(exp->tokens[*exp_idx] == LYXP_TOKEN_BRACK2);
7360     LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7361            print_token(exp->tokens[*exp_idx]), exp->expr_pos[*exp_idx]);
7362     ++(*exp_idx);
7363 
7364     return EXIT_SUCCESS;
7365 }
7366 
7367 /**
7368  * @brief Evaluate RelativeLocationPath. Logs directly on error.
7369  *
7370  * [4] RelativeLocationPath ::= Step | RelativeLocationPath '/' Step | RelativeLocationPath '//' Step
7371  * [5] Step ::= '@'? NodeTest Predicate* | '.' | '..'
7372  *
7373  * @param[in] exp Parsed XPath expression.
7374  * @param[in] exp_idx Position in the expression \p exp.
7375  * @param[in] cur_node Start node for the expression \p exp.
7376  * @param[in] all_desc Whether to search all the descendants or children only.
7377  * @param[in,out] set Context and result set. On NULL the rule is only parsed.
7378  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
7379  *
7380  * @return EXIT_SUCCESS on success, EXIT_FAILURE on unresolved when, -1 on error.
7381  */
7382 static int
eval_relative_location_path(struct lyxp_expr * exp,uint16_t * exp_idx,struct lyd_node * cur_node,struct lys_module * local_mod,int all_desc,struct lyxp_set * set,int options)7383 eval_relative_location_path(struct lyxp_expr *exp, uint16_t *exp_idx, struct lyd_node *cur_node, struct lys_module *local_mod,
7384                             int all_desc, struct lyxp_set *set, int options)
7385 {
7386     int attr_axis, ret;
7387 
7388     goto step;
7389     do {
7390         /* evaluate '/' or '//' */
7391         if (exp->tok_len[*exp_idx] == 1) {
7392             all_desc = 0;
7393         } else {
7394             assert(exp->tok_len[*exp_idx] == 2);
7395             all_desc = 1;
7396         }
7397         LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7398                print_token(exp->tokens[*exp_idx]), exp->expr_pos[*exp_idx]);
7399         ++(*exp_idx);
7400 
7401 step:
7402         /* Step */
7403         attr_axis = 0;
7404         switch (exp->tokens[*exp_idx]) {
7405         case LYXP_TOKEN_DOT:
7406             /* evaluate '.' */
7407             if (set && (options & LYXP_SNODE_ALL)) {
7408                 ret = moveto_snode_self(set, (struct lys_node *)cur_node, all_desc, options);
7409             } else {
7410                 ret = moveto_self(set, cur_node, all_desc, options);
7411             }
7412             if (ret) {
7413                 return ret;
7414             }
7415             LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7416                print_token(exp->tokens[*exp_idx]), exp->expr_pos[*exp_idx]);
7417             ++(*exp_idx);
7418             break;
7419 
7420         case LYXP_TOKEN_DDOT:
7421             /* evaluate '..' */
7422             if (set && (options & LYXP_SNODE_ALL)) {
7423                 ret = moveto_snode_parent(set, (struct lys_node *)cur_node, all_desc, options);
7424             } else {
7425                 ret = moveto_parent(set, cur_node, all_desc, options);
7426             }
7427             if (ret) {
7428                 return ret;
7429             }
7430             LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7431                print_token(exp->tokens[*exp_idx]), exp->expr_pos[*exp_idx]);
7432             ++(*exp_idx);
7433             break;
7434 
7435         case LYXP_TOKEN_AT:
7436             /* evaluate '@' */
7437             attr_axis = 1;
7438             LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7439                print_token(exp->tokens[*exp_idx]), exp->expr_pos[*exp_idx]);
7440             ++(*exp_idx);
7441 
7442             /* fall through */
7443         case LYXP_TOKEN_NAMETEST:
7444         case LYXP_TOKEN_NODETYPE:
7445             ret = eval_node_test(exp, exp_idx, cur_node, local_mod, attr_axis, all_desc, set, options);
7446             if (ret) {
7447                 return ret;
7448             }
7449 
7450             while ((exp->used > *exp_idx) && (exp->tokens[*exp_idx] == LYXP_TOKEN_BRACK1)) {
7451                 ret = eval_predicate(exp, exp_idx, cur_node, local_mod, set, options, 1);
7452                 if (ret) {
7453                     return ret;
7454                 }
7455             }
7456             break;
7457 
7458         default:
7459             LOGINT(local_mod ? local_mod->ctx : NULL);
7460             return -1;
7461         }
7462     } while ((exp->used > *exp_idx) && (exp->tokens[*exp_idx] == LYXP_TOKEN_OPERATOR_PATH));
7463 
7464     return EXIT_SUCCESS;
7465 }
7466 
7467 /**
7468  * @brief Evaluate AbsoluteLocationPath. Logs directly on error.
7469  *
7470  * [3] AbsoluteLocationPath ::= '/' RelativeLocationPath? | '//' RelativeLocationPath
7471  *
7472  * @param[in] exp Parsed XPath expression.
7473  * @param[in] exp_idx Position in the expression \p exp.
7474  * @param[in] cur_node Start node for the expression \p exp.
7475  * @param[in,out] set Context and result set. On NULL the rule is only parsed.
7476  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
7477  *
7478  * @return EXIT_SUCCESS on success, EXIT_FAILURE on unresolved when, -1 on error.
7479  */
7480 static int
eval_absolute_location_path(struct lyxp_expr * exp,uint16_t * exp_idx,struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)7481 eval_absolute_location_path(struct lyxp_expr *exp, uint16_t *exp_idx, struct lyd_node *cur_node, struct lys_module *local_mod,
7482                             struct lyxp_set *set, int options)
7483 {
7484     int all_desc, ret;
7485 
7486     if (set) {
7487         /* no matter what tokens follow, we need to be at the root */
7488         if (options & LYXP_SNODE_ALL) {
7489             moveto_snode_root(set, (struct lys_node *)cur_node, options);
7490         } else {
7491             moveto_root(set, cur_node, options);
7492         }
7493     }
7494 
7495     /* '/' RelativeLocationPath? */
7496     if (exp->tok_len[*exp_idx] == 1) {
7497         /* evaluate '/' - deferred */
7498         all_desc = 0;
7499         LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7500                print_token(exp->tokens[*exp_idx]), exp->expr_pos[*exp_idx]);
7501         ++(*exp_idx);
7502 
7503         if (exp_check_token(local_mod->ctx, exp, *exp_idx, LYXP_TOKEN_NONE, 0)) {
7504             return EXIT_SUCCESS;
7505         }
7506         switch (exp->tokens[*exp_idx]) {
7507         case LYXP_TOKEN_DOT:
7508         case LYXP_TOKEN_DDOT:
7509         case LYXP_TOKEN_AT:
7510         case LYXP_TOKEN_NAMETEST:
7511         case LYXP_TOKEN_NODETYPE:
7512             ret = eval_relative_location_path(exp, exp_idx, cur_node, local_mod, all_desc, set, options);
7513             if (ret) {
7514                 return ret;
7515             }
7516             break;
7517         default:
7518             break;
7519         }
7520 
7521     /* '//' RelativeLocationPath */
7522     } else {
7523         /* evaluate '//' - deferred so as not to waste memory by remembering all the nodes */
7524         all_desc = 1;
7525         LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7526                print_token(exp->tokens[*exp_idx]), exp->expr_pos[*exp_idx]);
7527         ++(*exp_idx);
7528 
7529         ret =  eval_relative_location_path(exp, exp_idx, cur_node, local_mod, all_desc, set, options);
7530         if (ret) {
7531             return ret;
7532         }
7533     }
7534 
7535     return EXIT_SUCCESS;
7536 }
7537 
7538 /**
7539  * @brief Evaluate FunctionCall. Logs directly on error.
7540  *
7541  * [9] FunctionCall ::= FunctionName '(' ( Expr ( ',' Expr )* )? ')'
7542  *
7543  * @param[in] exp Parsed XPath expression.
7544  * @param[in] exp_idx Position in the expression \p exp.
7545  * @param[in] cur_node Start node for the expression \p exp.
7546  * @param[in,out] set Context and result set. On NULL the rule is only parsed.
7547  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
7548  *
7549  * @return EXIT_SUCCESS on success, EXIT_FAILURE on unresolved when, -1 on error.
7550  */
7551 static int
eval_function_call(struct lyxp_expr * exp,uint16_t * exp_idx,struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)7552 eval_function_call(struct lyxp_expr *exp, uint16_t *exp_idx, struct lyd_node *cur_node, struct lys_module *local_mod,
7553                    struct lyxp_set *set, int options)
7554 {
7555     int rc = EXIT_FAILURE;
7556     int (*xpath_func)(struct lyxp_set **, uint16_t, struct lyd_node *, struct lys_module *, struct lyxp_set *, int) = NULL;
7557     uint16_t arg_count = 0, i, func_exp = *exp_idx;
7558     struct lyxp_set **args = NULL, **args_aux;
7559 
7560     if (set) {
7561         /* FunctionName */
7562         switch (exp->tok_len[*exp_idx]) {
7563         case 3:
7564             if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "not", 3)) {
7565                 xpath_func = &xpath_not;
7566             } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "sum", 3)) {
7567                 xpath_func = &xpath_sum;
7568             }
7569             break;
7570         case 4:
7571             if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "lang", 4)) {
7572                 xpath_func = &xpath_lang;
7573             } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "last", 4)) {
7574                 xpath_func = &xpath_last;
7575             } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "name", 4)) {
7576                 xpath_func = &xpath_name;
7577             } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "true", 4)) {
7578                 xpath_func = &xpath_true;
7579             }
7580             break;
7581         case 5:
7582             if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "count", 5)) {
7583                 xpath_func = &xpath_count;
7584             } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "false", 5)) {
7585                 xpath_func = &xpath_false;
7586             } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "floor", 5)) {
7587                 xpath_func = &xpath_floor;
7588             } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "round", 5)) {
7589                 xpath_func = &xpath_round;
7590             } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "deref", 5)) {
7591                 xpath_func = &xpath_deref;
7592             }
7593             break;
7594         case 6:
7595             if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "concat", 6)) {
7596                 xpath_func = &xpath_concat;
7597             } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "number", 6)) {
7598                 xpath_func = &xpath_number;
7599             } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "string", 6)) {
7600                 xpath_func = &xpath_string;
7601             }
7602             break;
7603         case 7:
7604             if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "boolean", 7)) {
7605                 xpath_func = &xpath_boolean;
7606             } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "ceiling", 7)) {
7607                 xpath_func = &xpath_ceiling;
7608             } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "current", 7)) {
7609                 xpath_func = &xpath_current;
7610             }
7611             break;
7612         case 8:
7613             if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "contains", 8)) {
7614                 xpath_func = &xpath_contains;
7615             } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "position", 8)) {
7616                 xpath_func = &xpath_position;
7617             } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "re-match", 8)) {
7618                 xpath_func = &xpath_re_match;
7619             }
7620             break;
7621         case 9:
7622             if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "substring", 9)) {
7623                 xpath_func = &xpath_substring;
7624             } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "translate", 9)) {
7625                 xpath_func = &xpath_translate;
7626             }
7627             break;
7628         case 10:
7629             if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "local-name", 10)) {
7630                 xpath_func = &xpath_local_name;
7631             } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "enum-value", 10)) {
7632                 xpath_func = &xpath_enum_value;
7633             } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "bit-is-set", 10)) {
7634                 xpath_func = &xpath_bit_is_set;
7635             }
7636             break;
7637         case 11:
7638             if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "starts-with", 11)) {
7639                 xpath_func = &xpath_starts_with;
7640             }
7641             break;
7642         case 12:
7643             if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "derived-from", 12)) {
7644                 xpath_func = &xpath_derived_from;
7645             }
7646             break;
7647         case 13:
7648             if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "namespace-uri", 13)) {
7649                 xpath_func = &xpath_namespace_uri;
7650             } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "string-length", 13)) {
7651                 xpath_func = &xpath_string_length;
7652             }
7653             break;
7654         case 15:
7655             if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "normalize-space", 15)) {
7656                 xpath_func = &xpath_normalize_space;
7657             } else if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "substring-after", 15)) {
7658                 xpath_func = &xpath_substring_after;
7659             }
7660             break;
7661         case 16:
7662             if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "substring-before", 16)) {
7663                 xpath_func = &xpath_substring_before;
7664             }
7665             break;
7666         case 20:
7667             if (!strncmp(&exp->expr[exp->expr_pos[*exp_idx]], "derived-from-or-self", 20)) {
7668                 xpath_func = &xpath_derived_from_or_self;
7669             }
7670             break;
7671         }
7672 
7673         if (!xpath_func) {
7674             LOGVAL(local_mod->ctx, LYE_XPATH_INTOK, LY_VLOG_NONE, NULL, "Unknown", &exp->expr[exp->expr_pos[*exp_idx]]);
7675             LOGVAL(local_mod->ctx, LYE_SPEC, LY_VLOG_NONE, NULL,
7676                    "Unknown XPath function \"%.*s\".", exp->tok_len[*exp_idx], &exp->expr[exp->expr_pos[*exp_idx]]);
7677             return -1;
7678         }
7679     }
7680 
7681     LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7682                print_token(exp->tokens[*exp_idx]), exp->expr_pos[*exp_idx]);
7683     ++(*exp_idx);
7684 
7685     /* '(' */
7686     assert(exp->tokens[*exp_idx] == LYXP_TOKEN_PAR1);
7687     LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7688                print_token(exp->tokens[*exp_idx]), exp->expr_pos[*exp_idx]);
7689     ++(*exp_idx);
7690 
7691     /* ( Expr ( ',' Expr )* )? */
7692     if (exp->tokens[*exp_idx] != LYXP_TOKEN_PAR2) {
7693         if (set) {
7694             args = malloc(sizeof *args);
7695             LY_CHECK_ERR_GOTO(!args, LOGMEM(local_mod->ctx), cleanup);
7696             arg_count = 1;
7697             args[0] = set_copy(set);
7698             if (!args[0]) {
7699                 goto cleanup;
7700             }
7701 
7702             rc = eval_expr_select(exp, exp_idx, 0, cur_node, local_mod, args[0], options);
7703             if (rc == -1 || rc == EXIT_FAILURE) {
7704                 goto cleanup;
7705             }
7706         } else {
7707             rc = eval_expr_select(exp, exp_idx, 0, cur_node, local_mod, NULL, options);
7708             if (rc == -1 || rc == EXIT_FAILURE) {
7709                 goto cleanup;
7710             }
7711         }
7712     }
7713     while ((exp->used > *exp_idx) && (exp->tokens[*exp_idx] == LYXP_TOKEN_COMMA)) {
7714         LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7715                print_token(exp->tokens[*exp_idx]), exp->expr_pos[*exp_idx]);
7716         ++(*exp_idx);
7717 
7718         if (set) {
7719             ++arg_count;
7720             args_aux = realloc(args, arg_count * sizeof *args);
7721             LY_CHECK_ERR_GOTO(!args_aux, arg_count--; LOGMEM(local_mod->ctx), cleanup);
7722             args = args_aux;
7723             args[arg_count - 1] = set_copy(set);
7724             if (!args[arg_count - 1]) {
7725                 goto cleanup;
7726             }
7727 
7728             rc = eval_expr_select(exp, exp_idx, 0, cur_node, local_mod, args[arg_count - 1], options);
7729             if (rc == -1 || rc == EXIT_FAILURE) {
7730                 goto cleanup;
7731             }
7732         } else {
7733             rc = eval_expr_select(exp, exp_idx, 0, cur_node, local_mod, NULL, options);
7734             if (rc == -1 || rc == EXIT_FAILURE) {
7735                 goto cleanup;
7736             }
7737         }
7738     }
7739 
7740     /* ')' */
7741     assert(exp->tokens[*exp_idx] == LYXP_TOKEN_PAR2);
7742     LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7743                print_token(exp->tokens[*exp_idx]), exp->expr_pos[*exp_idx]);
7744     ++(*exp_idx);
7745 
7746     if (set) {
7747         /* evaluate function */
7748         rc = xpath_func(args, arg_count, cur_node, local_mod, set, options);
7749 
7750         if (options & LYXP_SNODE_ALL) {
7751             if (rc == EXIT_FAILURE) {
7752                 /* some validation warning */
7753                 LOGWRN(local_mod->ctx, "Previous warning generated by XPath function \"%.*s\".",
7754                        (exp->expr_pos[*exp_idx - 1] - exp->expr_pos[func_exp]) + 1, &exp->expr[exp->expr_pos[func_exp]]);
7755                 rc = EXIT_SUCCESS;
7756             }
7757 
7758             /* merge all nodes from arg evaluations */
7759             for (i = 0; i < arg_count; ++i) {
7760                 set_snode_clear_ctx(args[i]);
7761                 set_snode_merge(set, args[i]);
7762             }
7763         }
7764     } else {
7765         rc = EXIT_SUCCESS;
7766     }
7767 
7768 cleanup:
7769     for (i = 0; i < arg_count; ++i) {
7770         lyxp_set_free(args[i]);
7771     }
7772     free(args);
7773 
7774     return rc;
7775 }
7776 
7777 /**
7778  * @brief Evaluate Number. Logs directly on error.
7779  *
7780  * @param[in] ctx Context for errors.
7781  * @param[in] exp Parsed XPath expression.
7782  * @param[in] exp_idx Position in the expression \p exp.
7783  * @param[in,out] set Context and result set. On NULL the rule is only parsed.
7784  *
7785  * @return EXIT_SUCCESS on success, -1 on error.
7786  */
7787 static int
eval_number(struct ly_ctx * ctx,struct lyxp_expr * exp,uint16_t * exp_idx,struct lyxp_set * set)7788 eval_number(struct ly_ctx *ctx, struct lyxp_expr *exp, uint16_t *exp_idx, struct lyxp_set *set)
7789 {
7790     long double num;
7791     char *endptr;
7792 
7793     if (set) {
7794         errno = 0;
7795         num = strtold(&exp->expr[exp->expr_pos[*exp_idx]], &endptr);
7796         if (errno) {
7797             LOGVAL(ctx, LYE_XPATH_INTOK, LY_VLOG_NONE, NULL, "Unknown", &exp->expr[exp->expr_pos[*exp_idx]]);
7798             LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Failed to convert \"%.*s\" into a long double (%s).",
7799                    exp->tok_len[*exp_idx], &exp->expr[exp->expr_pos[*exp_idx]], strerror(errno));
7800             return -1;
7801         } else if (endptr - &exp->expr[exp->expr_pos[*exp_idx]] != exp->tok_len[*exp_idx]) {
7802             LOGVAL(ctx, LYE_XPATH_INTOK, LY_VLOG_NONE, NULL, "Unknown", &exp->expr[exp->expr_pos[*exp_idx]]);
7803             LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Failed to convert \"%.*s\" into a long double.",
7804                    exp->tok_len[*exp_idx], &exp->expr[exp->expr_pos[*exp_idx]]);
7805             return -1;
7806         }
7807 
7808         set_fill_number(set, num);
7809     }
7810 
7811     LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7812                print_token(exp->tokens[*exp_idx]), exp->expr_pos[*exp_idx]);
7813     ++(*exp_idx);
7814     return EXIT_SUCCESS;
7815 }
7816 
7817 /**
7818  * @brief Evaluate PathExpr. Logs directly on error.
7819  *
7820  * [10] PathExpr ::= LocationPath | PrimaryExpr Predicate*
7821  *                 | PrimaryExpr Predicate* '/' RelativeLocationPath
7822  *                 | PrimaryExpr Predicate* '//' RelativeLocationPath
7823  * [2] LocationPath ::= RelativeLocationPath | AbsoluteLocationPath
7824  * [8] PrimaryExpr ::= '(' Expr ')' | Literal | Number | FunctionCall
7825  *
7826  * @param[in] exp Parsed XPath expression.
7827  * @param[in] exp_idx Position in the expression \p exp.
7828  * @param[in] cur_node Start node for the expression \p exp.
7829  * @param[in,out] set Context and result set. On NULL the rule is only parsed.
7830  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
7831  *
7832  * @return EXIT_SUCCESS on success, EXIT_FAILURE on unresolved when, -1 on error.
7833  */
7834 static int
eval_path_expr(struct lyxp_expr * exp,uint16_t * exp_idx,struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)7835 eval_path_expr(struct lyxp_expr *exp, uint16_t *exp_idx, struct lyd_node *cur_node, struct lys_module *local_mod,
7836                struct lyxp_set *set, int options)
7837 {
7838     int all_desc, ret, parent_pos_pred;
7839 
7840     switch (exp->tokens[*exp_idx]) {
7841     case LYXP_TOKEN_PAR1:
7842         /* '(' Expr ')' */
7843 
7844         /* '(' */
7845         LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7846                print_token(exp->tokens[*exp_idx]), exp->expr_pos[*exp_idx]);
7847         ++(*exp_idx);
7848 
7849         /* Expr */
7850         ret = eval_expr_select(exp, exp_idx, 0, cur_node, local_mod, set, options);
7851         if (ret == -1 || ret == EXIT_FAILURE) {
7852             return ret;
7853         }
7854 
7855         /* ')' */
7856         assert(exp->tokens[*exp_idx] == LYXP_TOKEN_PAR2);
7857         LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7858                print_token(exp->tokens[*exp_idx]), exp->expr_pos[*exp_idx]);
7859         ++(*exp_idx);
7860 
7861         parent_pos_pred = 0;
7862         goto predicate;
7863 
7864     case LYXP_TOKEN_DOT:
7865     case LYXP_TOKEN_DDOT:
7866     case LYXP_TOKEN_AT:
7867     case LYXP_TOKEN_NAMETEST:
7868     case LYXP_TOKEN_NODETYPE:
7869         /* RelativeLocationPath */
7870         ret = eval_relative_location_path(exp, exp_idx, cur_node, local_mod, 0, set, options);
7871         if (ret) {
7872             return ret;
7873         }
7874         break;
7875 
7876     case LYXP_TOKEN_FUNCNAME:
7877         /* FunctionCall */
7878         if (!set) {
7879             ret = eval_function_call(exp, exp_idx, cur_node, local_mod, NULL, options);
7880         } else {
7881             ret = eval_function_call(exp, exp_idx, cur_node, local_mod, set, options);
7882         }
7883         if (ret) {
7884             return ret;
7885         }
7886 
7887         parent_pos_pred = 1;
7888         goto predicate;
7889 
7890     case LYXP_TOKEN_OPERATOR_PATH:
7891         /* AbsoluteLocationPath */
7892         ret = eval_absolute_location_path(exp, exp_idx, cur_node, local_mod, set, options);
7893         if (ret) {
7894             return ret;
7895         }
7896         break;
7897 
7898     case LYXP_TOKEN_LITERAL:
7899         /* Literal */
7900         if (!set || (options & LYXP_SNODE_ALL)) {
7901             if (set) {
7902                 set_snode_clear_ctx(set);
7903             }
7904             eval_literal(exp, exp_idx, NULL);
7905         } else {
7906             eval_literal(exp, exp_idx, set);
7907         }
7908 
7909         parent_pos_pred = 1;
7910         goto predicate;
7911 
7912     case LYXP_TOKEN_NUMBER:
7913         /* Number */
7914         if (!set || (options & LYXP_SNODE_ALL)) {
7915             if (set) {
7916                 set_snode_clear_ctx(set);
7917             }
7918             ret = eval_number(local_mod->ctx, exp, exp_idx, NULL);
7919         } else {
7920             ret = eval_number(local_mod->ctx, exp, exp_idx, set);
7921         }
7922         if (ret) {
7923             return ret;
7924         }
7925 
7926         parent_pos_pred = 1;
7927         goto predicate;
7928 
7929     default:
7930         LOGVAL(local_mod->ctx, LYE_XPATH_INTOK, LY_VLOG_NONE, NULL,
7931                print_token(exp->tokens[*exp_idx]), &exp->expr[exp->expr_pos[*exp_idx]]);
7932         return -1;
7933     }
7934 
7935     return EXIT_SUCCESS;
7936 
7937 predicate:
7938     /* Predicate* */
7939     while ((exp->used > *exp_idx) && (exp->tokens[*exp_idx] == LYXP_TOKEN_BRACK1)) {
7940         ret = eval_predicate(exp, exp_idx, cur_node, local_mod, set, options, parent_pos_pred);
7941         if (ret) {
7942             return ret;
7943         }
7944     }
7945 
7946     /* ('/' or '//') RelativeLocationPath */
7947     if ((exp->used > *exp_idx) && (exp->tokens[*exp_idx] == LYXP_TOKEN_OPERATOR_PATH)) {
7948 
7949         /* evaluate '/' or '//' */
7950         if (exp->tok_len[*exp_idx] == 1) {
7951             all_desc = 0;
7952         } else {
7953             assert(exp->tok_len[*exp_idx] == 2);
7954             all_desc = 1;
7955         }
7956 
7957         LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7958                print_token(exp->tokens[*exp_idx]), exp->expr_pos[*exp_idx]);
7959         ++(*exp_idx);
7960 
7961         ret = eval_relative_location_path(exp, exp_idx, cur_node, local_mod, all_desc, set, options);
7962         if (ret) {
7963             return ret;
7964         }
7965     }
7966 
7967     return EXIT_SUCCESS;
7968 }
7969 
7970 /**
7971  * @brief Evaluate UnionExpr. Logs directly on error.
7972  *
7973  * [18] UnionExpr ::= PathExpr | UnionExpr '|' PathExpr
7974  *
7975  * @param[in] exp Parsed XPath expression.
7976  * @param[in] exp_idx Position in the expression \p exp.
7977  * @param[in] cur_node Start node for the expression \p exp.
7978  * @param[in,out] set Context and result set. On NULL the rule is only parsed.
7979  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
7980  *
7981  * @return EXIT_SUCCESS on success, EXIT_FAILURE on unresolved when, -1 on error.
7982  */
7983 static int
eval_union_expr(struct lyxp_expr * exp,uint16_t * exp_idx,uint16_t repeat,struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)7984 eval_union_expr(struct lyxp_expr *exp, uint16_t *exp_idx, uint16_t repeat, struct lyd_node *cur_node,
7985                 struct lys_module *local_mod, struct lyxp_set *set, int options)
7986 {
7987     int ret;
7988     struct lyxp_set orig_set, set2;
7989     uint16_t i;
7990 
7991     assert(repeat);
7992 
7993     memset(&orig_set, 0, sizeof orig_set);
7994     memset(&set2, 0, sizeof set2);
7995 
7996     set_fill_set(&orig_set, set);
7997 
7998     ret = eval_expr_select(exp, exp_idx, LYXP_EXPR_UNION, cur_node, local_mod, set, options);
7999     if (ret) {
8000         goto finish;
8001     }
8002 
8003     /* ('|' PathExpr)* */
8004     for (i = 0; i < repeat; ++i) {
8005         assert(exp->tokens[*exp_idx] == LYXP_TOKEN_OPERATOR_UNI);
8006         LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
8007                print_token(exp->tokens[*exp_idx]), exp->expr_pos[*exp_idx]);
8008         ++(*exp_idx);
8009 
8010         if (!set) {
8011             ret = eval_expr_select(exp, exp_idx, LYXP_EXPR_UNION, cur_node, local_mod, NULL, options);
8012             if (ret) {
8013                 goto finish;
8014             }
8015             continue;
8016         }
8017 
8018         set_fill_set(&set2, &orig_set);
8019         ret = eval_expr_select(exp, exp_idx, LYXP_EXPR_UNION, cur_node, local_mod, &set2, options);
8020         if (ret) {
8021             goto finish;
8022         }
8023 
8024         /* eval */
8025         if (options & LYXP_SNODE_ALL) {
8026             set_snode_merge(set, &set2);
8027         } else if (moveto_union(set, &set2, cur_node, options)) {
8028             ret = -1;
8029             goto finish;
8030         }
8031     }
8032 
8033 finish:
8034     lyxp_set_cast(&orig_set, LYXP_SET_EMPTY, cur_node, local_mod, options);
8035     lyxp_set_cast(&set2, LYXP_SET_EMPTY, cur_node, local_mod, options);
8036     return ret;
8037 }
8038 
8039 /**
8040  * @brief Evaluate UnaryExpr. Logs directly on error.
8041  *
8042  * [17] UnaryExpr ::= UnionExpr | '-' UnaryExpr
8043  *
8044  * @param[in] exp Parsed XPath expression.
8045  * @param[in] exp_idx Position in the expression \p exp.
8046  * @param[in] cur_node Start node for the expression \p exp.
8047  * @param[in,out] set Context and result set. On NULL the rule is only parsed.
8048  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
8049  *
8050  * @return EXIT_SUCCESS on success, EXIT_FAILURE on unresolved when, -1 on error.
8051  */
8052 static int
eval_unary_expr(struct lyxp_expr * exp,uint16_t * exp_idx,uint16_t repeat,struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)8053 eval_unary_expr(struct lyxp_expr *exp, uint16_t *exp_idx, uint16_t repeat, struct lyd_node *cur_node,
8054                 struct lys_module *local_mod, struct lyxp_set *set, int options)
8055 {
8056     int ret;
8057     uint16_t this_op, i;
8058 
8059     assert(repeat);
8060 
8061     /* ('-')+ */
8062     this_op = *exp_idx;
8063     for (i = 0; i < repeat; ++i) {
8064         assert(!exp_check_token(local_mod->ctx, exp, *exp_idx, LYXP_TOKEN_OPERATOR_MATH, 0) && (exp->expr[exp->expr_pos[*exp_idx]] == '-'));
8065 
8066         LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
8067                print_token(exp->tokens[*exp_idx]), exp->expr_pos[*exp_idx]);
8068         ++(*exp_idx);
8069     }
8070 
8071     ret = eval_expr_select(exp, exp_idx, LYXP_EXPR_UNARY, cur_node, local_mod, set, options);
8072     if (ret) {
8073         return ret;
8074     }
8075 
8076     if (set && (repeat % 2)) {
8077         if (options & LYXP_SNODE_ALL) {
8078             warn_operands(local_mod->ctx, set, NULL, 1, exp->expr, exp->expr_pos[this_op]);
8079         } else {
8080             if (moveto_op_math(set, NULL, &exp->expr[exp->expr_pos[this_op]], cur_node, local_mod, options)) {
8081                 return -1;
8082             }
8083         }
8084     }
8085 
8086     return EXIT_SUCCESS;
8087 }
8088 
8089 /**
8090  * @brief Evaluate MultiplicativeExpr. Logs directly on error.
8091  *
8092  * [16] MultiplicativeExpr ::= UnaryExpr
8093  *                     | MultiplicativeExpr '*' UnaryExpr
8094  *                     | MultiplicativeExpr 'div' UnaryExpr
8095  *                     | MultiplicativeExpr 'mod' UnaryExpr
8096  *
8097  * @param[in] exp Parsed XPath expression.
8098  * @param[in] exp_idx Position in the expression \p exp.
8099  * @param[in] cur_node Start node for the expression \p exp.
8100  * @param[in,out] set Context and result set. On NULL the rule is only parsed.
8101  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
8102  *
8103  * @return EXIT_SUCCESS on success, EXIT_FAILURE on unresolved when, -1 on error.
8104  */
8105 static int
eval_multiplicative_expr(struct lyxp_expr * exp,uint16_t * exp_idx,uint16_t repeat,struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)8106 eval_multiplicative_expr(struct lyxp_expr *exp, uint16_t *exp_idx, uint16_t repeat, struct lyd_node *cur_node,
8107                          struct lys_module *local_mod, struct lyxp_set *set, int options)
8108 {
8109     int ret;
8110     uint16_t this_op;
8111     struct lyxp_set orig_set, set2;
8112     uint16_t i;
8113 
8114     assert(repeat);
8115 
8116     memset(&orig_set, 0, sizeof orig_set);
8117     memset(&set2, 0, sizeof set2);
8118 
8119     set_fill_set(&orig_set, set);
8120 
8121     ret = eval_expr_select(exp, exp_idx, LYXP_EXPR_MULTIPLICATIVE, cur_node, local_mod, set, options);
8122     if (ret) {
8123         goto finish;
8124     }
8125 
8126     /* ('*' / 'div' / 'mod' UnaryExpr)* */
8127     for (i = 0; i < repeat; ++i) {
8128         this_op = *exp_idx;
8129 
8130         assert(exp->tokens[*exp_idx] == LYXP_TOKEN_OPERATOR_MATH);
8131         LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
8132                print_token(exp->tokens[*exp_idx]), exp->expr_pos[*exp_idx]);
8133         ++(*exp_idx);
8134 
8135         if (!set) {
8136             ret = eval_expr_select(exp, exp_idx, LYXP_EXPR_MULTIPLICATIVE, cur_node, local_mod, NULL, options);
8137             if (ret) {
8138                 goto finish;
8139             }
8140             continue;
8141         }
8142 
8143         set_fill_set(&set2, &orig_set);
8144         ret = eval_expr_select(exp, exp_idx, LYXP_EXPR_MULTIPLICATIVE, cur_node, local_mod, &set2, options);
8145         if (ret) {
8146             goto finish;
8147         }
8148 
8149         /* eval */
8150         if (options & LYXP_SNODE_ALL) {
8151             warn_operands(local_mod->ctx, set, &set2, 1, exp->expr, exp->expr_pos[this_op - 1]);
8152             set_snode_merge(set, &set2);
8153             set_snode_clear_ctx(set);
8154         } else {
8155             if (moveto_op_math(set, &set2, &exp->expr[exp->expr_pos[this_op]], cur_node, local_mod, options)) {
8156                 ret = -1;
8157                 goto finish;
8158             }
8159         }
8160     }
8161 
8162 finish:
8163     lyxp_set_cast(&orig_set, LYXP_SET_EMPTY, cur_node, local_mod, options);
8164     lyxp_set_cast(&set2, LYXP_SET_EMPTY, cur_node, local_mod, options);
8165     return ret;
8166 }
8167 
8168 /**
8169  * @brief Evaluate AdditiveExpr. Logs directly on error.
8170  *
8171  * [15] AdditiveExpr ::= MultiplicativeExpr
8172  *                     | AdditiveExpr '+' MultiplicativeExpr
8173  *                     | AdditiveExpr '-' MultiplicativeExpr
8174  *
8175  * @param[in] exp Parsed XPath expression.
8176  * @param[in] exp_idx Position in the expression \p exp.
8177  * @param[in] cur_node Start node for the expression \p exp.
8178  * @param[in,out] set Context and result set. On NULL the rule is only parsed.
8179  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
8180  *
8181  * @return EXIT_SUCCESS on success, EXIT_FAILURE on unresolved when, -1 on error.
8182  */
8183 static int
eval_additive_expr(struct lyxp_expr * exp,uint16_t * exp_idx,uint16_t repeat,struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)8184 eval_additive_expr(struct lyxp_expr *exp, uint16_t *exp_idx, uint16_t repeat, struct lyd_node *cur_node,
8185                    struct lys_module *local_mod, struct lyxp_set *set, int options)
8186 {
8187     int ret;
8188     uint16_t this_op;
8189     struct lyxp_set orig_set, set2;
8190     uint16_t i;
8191 
8192     assert(repeat);
8193 
8194     memset(&orig_set, 0, sizeof orig_set);
8195     memset(&set2, 0, sizeof set2);
8196 
8197     set_fill_set(&orig_set, set);
8198 
8199     ret = eval_expr_select(exp, exp_idx, LYXP_EXPR_ADDITIVE, cur_node, local_mod, set, options);
8200     if (ret) {
8201         goto finish;
8202     }
8203 
8204     /* ('+' / '-' MultiplicativeExpr)* */
8205     for (i = 0; i < repeat; ++i) {
8206         this_op = *exp_idx;
8207 
8208         assert(exp->tokens[*exp_idx] == LYXP_TOKEN_OPERATOR_MATH);
8209         LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
8210                print_token(exp->tokens[*exp_idx]), exp->expr_pos[*exp_idx]);
8211         ++(*exp_idx);
8212 
8213         if (!set) {
8214             ret = eval_expr_select(exp, exp_idx, LYXP_EXPR_ADDITIVE, cur_node, local_mod, NULL, options);
8215             if (ret) {
8216                 goto finish;
8217             }
8218             continue;
8219         }
8220 
8221         set_fill_set(&set2, &orig_set);
8222         ret = eval_expr_select(exp, exp_idx, LYXP_EXPR_ADDITIVE, cur_node, local_mod, &set2, options);
8223         if (ret) {
8224             goto finish;
8225         }
8226 
8227         /* eval */
8228         if (options & LYXP_SNODE_ALL) {
8229             warn_operands(local_mod->ctx, set, &set2, 1, exp->expr, exp->expr_pos[this_op - 1]);
8230             set_snode_merge(set, &set2);
8231             set_snode_clear_ctx(set);
8232         } else {
8233             if (moveto_op_math(set, &set2, &exp->expr[exp->expr_pos[this_op]], cur_node, local_mod, options)) {
8234                 goto finish;
8235             }
8236         }
8237     }
8238 
8239 finish:
8240     lyxp_set_cast(&orig_set, LYXP_SET_EMPTY, cur_node, local_mod, options);
8241     lyxp_set_cast(&set2, LYXP_SET_EMPTY, cur_node, local_mod, options);
8242     return ret;
8243 }
8244 
8245 /**
8246  * @brief Evaluate RelationalExpr. Logs directly on error.
8247  *
8248  * [14] RelationalExpr ::= AdditiveExpr
8249  *                       | RelationalExpr '<' AdditiveExpr
8250  *                       | RelationalExpr '>' AdditiveExpr
8251  *                       | RelationalExpr '<=' AdditiveExpr
8252  *                       | RelationalExpr '>=' AdditiveExpr
8253  *
8254  * @param[in] exp Parsed XPath expression.
8255  * @param[in] exp_idx Position in the expression \p exp.
8256  * @param[in] cur_node Start node for the expression \p exp.
8257  * @param[in,out] set Context and result set. On NULL the rule is only parsed.
8258  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
8259  *
8260  * @return EXIT_SUCCESS on success, EXIT_FAILURE on unresolved when, -1 on error.
8261  */
8262 static int
eval_relational_expr(struct lyxp_expr * exp,uint16_t * exp_idx,uint16_t repeat,struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)8263 eval_relational_expr(struct lyxp_expr *exp, uint16_t *exp_idx, uint16_t repeat, struct lyd_node *cur_node,
8264                      struct lys_module *local_mod, struct lyxp_set *set, int options)
8265 {
8266     int ret;
8267     uint16_t this_op;
8268     struct lyxp_set orig_set, set2;
8269     uint16_t i;
8270 
8271     assert(repeat);
8272 
8273     memset(&orig_set, 0, sizeof orig_set);
8274     memset(&set2, 0, sizeof set2);
8275 
8276     set_fill_set(&orig_set, set);
8277 
8278     ret = eval_expr_select(exp, exp_idx, LYXP_EXPR_RELATIONAL, cur_node, local_mod, set, options);
8279     if (ret) {
8280         goto finish;
8281     }
8282 
8283     /* ('<' / '>' / '<=' / '>=' AdditiveExpr)* */
8284     for (i = 0; i < repeat; ++i) {
8285         this_op = *exp_idx;
8286 
8287         assert(exp->tokens[*exp_idx] == LYXP_TOKEN_OPERATOR_COMP);
8288         LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
8289                print_token(exp->tokens[*exp_idx]), exp->expr_pos[*exp_idx]);
8290         ++(*exp_idx);
8291 
8292         if (!set) {
8293             ret = eval_expr_select(exp, exp_idx, LYXP_EXPR_RELATIONAL, cur_node, local_mod, NULL, options);
8294             if (ret) {
8295                 goto finish;
8296             }
8297             continue;
8298         }
8299 
8300         set_fill_set(&set2, &orig_set);
8301         ret = eval_expr_select(exp, exp_idx, LYXP_EXPR_RELATIONAL, cur_node, local_mod, &set2, options);
8302         if (ret) {
8303             goto finish;
8304         }
8305 
8306         /* eval */
8307         if (options & LYXP_SNODE_ALL) {
8308             warn_operands(local_mod->ctx, set, &set2, 1, exp->expr, exp->expr_pos[this_op - 1]);
8309             set_snode_merge(set, &set2);
8310             set_snode_clear_ctx(set);
8311         } else {
8312             if (moveto_op_comp(set, &set2, &exp->expr[exp->expr_pos[this_op]], cur_node, local_mod, options)) {
8313                 ret = -1;
8314                 goto finish;
8315             }
8316         }
8317     }
8318 
8319 finish:
8320     lyxp_set_cast(&orig_set, LYXP_SET_EMPTY, cur_node, local_mod, options);
8321     lyxp_set_cast(&set2, LYXP_SET_EMPTY, cur_node, local_mod, options);
8322     return ret;
8323 }
8324 
8325 /**
8326  * @brief Evaluate EqualityExpr. Logs directly on error.
8327  *
8328  * [13] EqualityExpr ::= RelationalExpr | EqualityExpr '=' RelationalExpr
8329  *                     | EqualityExpr '!=' RelationalExpr
8330  *
8331  * @param[in] exp Parsed XPath expression.
8332  * @param[in] exp_idx Position in the expression \p exp.
8333  * @param[in] cur_node Start node for the expression \p exp.
8334  * @param[in,out] set Context and result set. On NULL the rule is only parsed.
8335  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
8336  *
8337  * @return EXIT_SUCCESS on success, EXIT_FAILURE on unresolved when, -1 on error.
8338  */
8339 static int
eval_equality_expr(struct lyxp_expr * exp,uint16_t * exp_idx,uint16_t repeat,struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)8340 eval_equality_expr(struct lyxp_expr *exp, uint16_t *exp_idx, uint16_t repeat, struct lyd_node *cur_node,
8341                    struct lys_module *local_mod, struct lyxp_set *set, int options)
8342 {
8343     int ret;
8344     uint16_t this_op;
8345     struct lyxp_set orig_set, set2;
8346     uint16_t i;
8347 
8348     assert(repeat);
8349 
8350     memset(&orig_set, 0, sizeof orig_set);
8351     memset(&set2, 0, sizeof set2);
8352 
8353     set_fill_set(&orig_set, set);
8354 
8355     ret = eval_expr_select(exp, exp_idx, LYXP_EXPR_EQUALITY, cur_node, local_mod, set, options);
8356     if (ret) {
8357         goto finish;
8358     }
8359 
8360     /* ('=' / '!=' RelationalExpr)* */
8361     for (i = 0; i < repeat; ++i) {
8362         this_op = *exp_idx;
8363 
8364         assert(exp->tokens[*exp_idx] == LYXP_TOKEN_OPERATOR_COMP);
8365         LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
8366                print_token(exp->tokens[*exp_idx]), exp->expr_pos[*exp_idx]);
8367         ++(*exp_idx);
8368 
8369         if (!set) {
8370             ret = eval_expr_select(exp, exp_idx, LYXP_EXPR_EQUALITY, cur_node, local_mod, NULL, options);
8371             if (ret) {
8372                 return ret;
8373             }
8374             continue;
8375         }
8376 
8377         set_fill_set(&set2, &orig_set);
8378         ret = eval_expr_select(exp, exp_idx, LYXP_EXPR_EQUALITY, cur_node, local_mod, &set2, options);
8379         if (ret) {
8380             goto finish;
8381         }
8382 
8383         /* eval */
8384         if (options & LYXP_SNODE_ALL) {
8385             warn_operands(local_mod->ctx, set, &set2, 0, exp->expr, exp->expr_pos[this_op - 1]);
8386             warn_equality_value(local_mod->ctx, exp, set, local_mod, *exp_idx - 1, this_op - 1, *exp_idx - 1);
8387             warn_equality_value(local_mod->ctx, exp, &set2, local_mod, this_op - 1, this_op - 1, *exp_idx - 1);
8388             set_snode_merge(set, &set2);
8389             set_snode_clear_ctx(set);
8390         } else {
8391             if (moveto_op_comp(set, &set2, &exp->expr[exp->expr_pos[this_op]], cur_node, local_mod, options)) {
8392                 ret = -1;
8393                 goto finish;
8394             }
8395         }
8396     }
8397 
8398 finish:
8399     lyxp_set_cast(&orig_set, LYXP_SET_EMPTY, cur_node, local_mod, options);
8400     lyxp_set_cast(&set2, LYXP_SET_EMPTY, cur_node, local_mod, options);
8401     return ret;
8402 }
8403 
8404 /**
8405  * @brief Evaluate AndExpr. Logs directly on error.
8406  *
8407  * [12] AndExpr ::= EqualityExpr | AndExpr 'and' EqualityExpr
8408  *
8409  * @param[in] exp Parsed XPath expression.
8410  * @param[in] exp_idx Position in the expression \p exp.
8411  * @param[in] cur_node Start node for the expression \p exp.
8412  * @param[in,out] set Context and result set. On NULL the rule is only parsed.
8413  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
8414  *
8415  * @return EXIT_SUCCESS on success, EXIT_FAILURE on unresolved when, -1 on error.
8416  */
8417 static int
eval_and_expr(struct lyxp_expr * exp,uint16_t * exp_idx,uint16_t repeat,struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)8418 eval_and_expr(struct lyxp_expr *exp, uint16_t *exp_idx, uint16_t repeat, struct lyd_node *cur_node,
8419               struct lys_module *local_mod, struct lyxp_set *set, int options)
8420 {
8421     int ret;
8422     struct lyxp_set orig_set, set2;
8423     uint16_t i;
8424 
8425     assert(repeat);
8426 
8427     memset(&orig_set, 0, sizeof orig_set);
8428     memset(&set2, 0, sizeof set2);
8429 
8430     set_fill_set(&orig_set, set);
8431 
8432     ret = eval_expr_select(exp, exp_idx, LYXP_EXPR_AND, cur_node, local_mod, set, options);
8433     if (ret) {
8434         goto finish;
8435     }
8436 
8437     /* cast to boolean, we know that will be the final result */
8438     if (set && (options & LYXP_SNODE_ALL)) {
8439         set_snode_clear_ctx(set);
8440     } else {
8441         lyxp_set_cast(set, LYXP_SET_BOOLEAN, cur_node, local_mod, options);
8442     }
8443 
8444     /* ('and' EqualityExpr)* */
8445     for (i = 0; i < repeat; ++i) {
8446         assert(exp->tokens[*exp_idx] == LYXP_TOKEN_OPERATOR_LOG);
8447         LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (!set || !set->val.bool ? "skipped" : "parsed"),
8448             print_token(exp->tokens[*exp_idx]), exp->expr_pos[*exp_idx]);
8449         ++(*exp_idx);
8450 
8451         /* lazy evaluation */
8452         if (!set || ((set->type == LYXP_SET_BOOLEAN) && !set->val.bool)) {
8453             ret = eval_expr_select(exp, exp_idx, LYXP_EXPR_AND, cur_node, local_mod, NULL, options);
8454             if (ret) {
8455                 goto finish;
8456             }
8457             continue;
8458         }
8459 
8460         set_fill_set(&set2, &orig_set);
8461         ret = eval_expr_select(exp, exp_idx, LYXP_EXPR_AND, cur_node, local_mod, &set2, options);
8462         if (ret) {
8463             goto finish;
8464         }
8465 
8466         /* eval - just get boolean value actually */
8467         if (set->type == LYXP_SET_SNODE_SET) {
8468             set_snode_clear_ctx(&set2);
8469             set_snode_merge(set, &set2);
8470         } else {
8471             lyxp_set_cast(&set2, LYXP_SET_BOOLEAN, cur_node, local_mod, options);
8472             set_fill_set(set, &set2);
8473         }
8474     }
8475 
8476 finish:
8477     lyxp_set_cast(&orig_set, LYXP_SET_EMPTY, cur_node, local_mod, options);
8478     lyxp_set_cast(&set2, LYXP_SET_EMPTY, cur_node, local_mod, options);
8479     return ret;
8480 }
8481 
8482 /**
8483  * @brief Evaluate OrExpr. Logs directly on error.
8484  *
8485  * [11] OrExpr ::= AndExpr | OrExpr 'or' AndExpr
8486  *
8487  * @param[in] exp Parsed XPath expression.
8488  * @param[in] exp_idx Position in the expression \p exp.
8489  * @param[in] cur_node Start node for the expression \p exp.
8490  * @param[in,out] set Context and result set. On NULL the rule is only parsed.
8491  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
8492  *
8493  * @return EXIT_SUCCESS on success, EXIT_FAILURE on unresolved when, -1 on error.
8494  */
8495 static int
eval_or_expr(struct lyxp_expr * exp,uint16_t * exp_idx,uint16_t repeat,struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)8496 eval_or_expr(struct lyxp_expr *exp, uint16_t *exp_idx, uint16_t repeat, struct lyd_node *cur_node,
8497              struct lys_module *local_mod, struct lyxp_set *set, int options)
8498 {
8499     int ret;
8500     struct lyxp_set orig_set, set2;
8501     uint16_t i;
8502 
8503     assert(repeat);
8504 
8505     memset(&orig_set, 0, sizeof orig_set);
8506     memset(&set2, 0, sizeof set2);
8507 
8508     set_fill_set(&orig_set, set);
8509 
8510     ret = eval_expr_select(exp, exp_idx, LYXP_EXPR_OR, cur_node, local_mod, set, options);
8511     if (ret) {
8512         goto finish;
8513     }
8514 
8515     /* cast to boolean, we know that will be the final result */
8516     if (set && (options & LYXP_SNODE_ALL)) {
8517         set_snode_clear_ctx(set);
8518     } else {
8519         lyxp_set_cast(set, LYXP_SET_BOOLEAN, cur_node, local_mod, options);
8520     }
8521 
8522     /* ('or' AndExpr)* */
8523     for (i = 0; i < repeat; ++i) {
8524         assert(exp->tokens[*exp_idx] == LYXP_TOKEN_OPERATOR_LOG);
8525         LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (!set || set->val.bool ? "skipped" : "parsed"),
8526             print_token(exp->tokens[*exp_idx]), exp->expr_pos[*exp_idx]);
8527         ++(*exp_idx);
8528 
8529         /* lazy evaluation */
8530         if (!set || ((set->type == LYXP_SET_BOOLEAN) && set->val.bool)) {
8531             ret = eval_expr_select(exp, exp_idx, LYXP_EXPR_OR, cur_node, local_mod, NULL, options);
8532             if (ret) {
8533                 goto finish;
8534             }
8535             continue;
8536         }
8537 
8538         set_fill_set(&set2, &orig_set);
8539         /* expr_type cound have been LYXP_EXPR_NONE in all these later calls (except for the first one),
8540          * but it does not matter */
8541         ret = eval_expr_select(exp, exp_idx, LYXP_EXPR_OR, cur_node, local_mod, &set2, options);
8542         if (ret) {
8543             goto finish;
8544         }
8545 
8546         /* eval - just get boolean value actually */
8547         if (set->type == LYXP_SET_SNODE_SET) {
8548             set_snode_clear_ctx(&set2);
8549             set_snode_merge(set, &set2);
8550         } else {
8551             lyxp_set_cast(&set2, LYXP_SET_BOOLEAN, cur_node, local_mod, options);
8552             set_fill_set(set, &set2);
8553         }
8554     }
8555 
8556 finish:
8557     lyxp_set_cast(&orig_set, LYXP_SET_EMPTY, cur_node, local_mod, options);
8558     lyxp_set_cast(&set2, LYXP_SET_EMPTY, cur_node, local_mod, options);
8559     return ret;
8560 }
8561 
8562 /**
8563  * @brief Decide what expression is at the pointer \p exp_idx and evaluate it accordingly.
8564  *
8565  * @param[in] exp Parsed XPath expression.
8566  * @param[in] exp_idx Position in the expression \p exp.
8567  * @param[in] repeat_used How many values were already used from the current token repeat array.
8568  * @param[in] cur_node Start node for the expression \p exp.
8569  * @param[in] local_mod Module considered to be local.
8570  * @param[in,out] set Context and result set. On NULL the rule is only parsed.
8571  * @param[in] options Whether to apply data node access restrictions defined for 'when' and 'must' evaluation.
8572  * @return EXIT_SUCCESS on success, EXIT_FAILURE on unresolved when, -1 on error.
8573  */
8574 static int
eval_expr_select(struct lyxp_expr * exp,uint16_t * exp_idx,enum lyxp_expr_type etype,struct lyd_node * cur_node,struct lys_module * local_mod,struct lyxp_set * set,int options)8575 eval_expr_select(struct lyxp_expr *exp, uint16_t *exp_idx, enum lyxp_expr_type etype, struct lyd_node *cur_node,
8576                  struct lys_module *local_mod, struct lyxp_set *set, int options)
8577 {
8578     int ret;
8579     uint16_t i, count;
8580     enum lyxp_expr_type next_etype;
8581 
8582     /* process operator repeats */
8583     if (!exp->repeat[*exp_idx]) {
8584         next_etype = LYXP_EXPR_NONE;
8585     } else {
8586         /* find etype repeat */
8587         for (i = 0; exp->repeat[*exp_idx][i] > etype; ++i);
8588 
8589         /* select one-priority lower because etype expression called us */
8590         if (i) {
8591             next_etype = exp->repeat[*exp_idx][i - 1];
8592             /* count repeats for that expression */
8593             for (count = 0; i && exp->repeat[*exp_idx][i - 1] == next_etype; ++count, --i);
8594         } else {
8595             next_etype = LYXP_EXPR_NONE;
8596         }
8597     }
8598 
8599     /* decide what expression are we parsing based on the repeat */
8600     switch (next_etype) {
8601     case LYXP_EXPR_OR:
8602         ret = eval_or_expr(exp, exp_idx, count, cur_node, local_mod, set, options);
8603         break;
8604     case LYXP_EXPR_AND:
8605         ret = eval_and_expr(exp, exp_idx, count, cur_node, local_mod, set, options);
8606         break;
8607     case LYXP_EXPR_EQUALITY:
8608         ret = eval_equality_expr(exp, exp_idx, count, cur_node, local_mod, set, options);
8609         break;
8610     case LYXP_EXPR_RELATIONAL:
8611         ret = eval_relational_expr(exp, exp_idx, count, cur_node, local_mod, set, options);
8612         break;
8613     case LYXP_EXPR_ADDITIVE:
8614         ret = eval_additive_expr(exp, exp_idx, count, cur_node, local_mod, set, options);
8615         break;
8616     case LYXP_EXPR_MULTIPLICATIVE:
8617         ret = eval_multiplicative_expr(exp, exp_idx, count, cur_node, local_mod, set, options);
8618         break;
8619     case LYXP_EXPR_UNARY:
8620         ret = eval_unary_expr(exp, exp_idx, count, cur_node, local_mod, set, options);
8621         break;
8622     case LYXP_EXPR_UNION:
8623         ret = eval_union_expr(exp, exp_idx, count, cur_node, local_mod, set, options);
8624         break;
8625     case LYXP_EXPR_NONE:
8626         ret = eval_path_expr(exp, exp_idx, cur_node, local_mod, set, options);
8627         break;
8628     default:
8629         ret = -1;
8630         LOGINT(local_mod ? local_mod->ctx : NULL);
8631         break;
8632     }
8633 
8634     return ret;
8635 }
8636 
8637 int
lyxp_eval(const char * expr,const struct lyd_node * cur_node,enum lyxp_node_type cur_node_type,const struct lys_module * local_mod,struct lyxp_set * set,int options)8638 lyxp_eval(const char *expr, const struct lyd_node *cur_node, enum lyxp_node_type cur_node_type,
8639           const struct lys_module *local_mod, struct lyxp_set *set, int options)
8640 {
8641     struct ly_ctx *ctx;
8642     struct lyxp_expr *exp;
8643     uint16_t exp_idx = 0;
8644     int rc = -1;
8645 
8646     if (!expr || !local_mod || !set) {
8647         LOGARG;
8648         return EXIT_FAILURE;
8649     }
8650 
8651     ctx = local_mod->ctx;
8652 
8653     exp = lyxp_parse_expr(ctx, expr);
8654     if (!exp) {
8655         rc = -1;
8656         goto finish;
8657     }
8658 
8659     rc = reparse_or_expr(ctx, exp, &exp_idx);
8660     if (rc) {
8661         goto finish;
8662     } else if (exp->used > exp_idx) {
8663         LOGVAL(ctx, LYE_XPATH_INTOK, LY_VLOG_NONE, NULL, "Unknown", &exp->expr[exp->expr_pos[exp_idx]]);
8664         LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Unparsed characters \"%s\" left at the end of an XPath expression.",
8665                &exp->expr[exp->expr_pos[exp_idx]]);
8666         rc = -1;
8667         goto finish;
8668     }
8669 
8670     print_expr_struct_debug(exp);
8671 
8672     exp_idx = 0;
8673     memset(set, 0, sizeof *set);
8674     set->type = LYXP_SET_EMPTY;
8675     if (cur_node) {
8676         set_insert_node(set, (struct lyd_node *)cur_node, 0, cur_node_type, 0);
8677     }
8678 
8679     rc = eval_expr_select(exp, &exp_idx, 0, (struct lyd_node *)cur_node, (struct lys_module *)local_mod, set, options);
8680     if (rc == 2) {
8681         rc = EXIT_SUCCESS;
8682     }
8683     if ((rc == -1) && cur_node) {
8684         LOGPATH(ctx, LY_VLOG_LYD, cur_node);
8685         lyxp_set_cast(set, LYXP_SET_EMPTY, cur_node, local_mod, options);
8686     }
8687 
8688 finish:
8689     lyxp_expr_free(exp);
8690     return rc;
8691 }
8692 
8693 #if 0
8694 
8695 /* full xml printing of set elements, not used currently */
8696 
8697 void
8698 lyxp_set_print_xml(FILE *f, struct lyxp_set *set)
8699 {
8700     uint32_t i;
8701     char *str_num;
8702     struct lyout out;
8703 
8704     memset(&out, 0, sizeof out);
8705 
8706     out.type = LYOUT_STREAM;
8707     out.method.f = f;
8708 
8709     switch (set->type) {
8710     case LYXP_SET_EMPTY:
8711         ly_print(&out, "Empty XPath set\n\n");
8712         break;
8713     case LYXP_SET_BOOLEAN:
8714         ly_print(&out, "Boolean XPath set:\n");
8715         ly_print(&out, "%s\n\n", set->value.bool ? "true" : "false");
8716         break;
8717     case LYXP_SET_STRING:
8718         ly_print(&out, "String XPath set:\n");
8719         ly_print(&out, "\"%s\"\n\n", set->value.str);
8720         break;
8721     case LYXP_SET_NUMBER:
8722         ly_print(&out, "Number XPath set:\n");
8723 
8724         if (isnan(set->value.num)) {
8725             str_num = strdup("NaN");
8726         } else if ((set->value.num == 0) || (set->value.num == -0.0f)) {
8727             str_num = strdup("0");
8728         } else if (isinf(set->value.num) && !signbit(set->value.num)) {
8729             str_num = strdup("Infinity");
8730         } else if (isinf(set->value.num) && signbit(set->value.num)) {
8731             str_num = strdup("-Infinity");
8732         } else if ((long long)set->value.num == set->value.num) {
8733             if (asprintf(&str_num, "%lld", (long long)set->value.num) == -1) {
8734                 str_num = NULL;
8735             }
8736         } else {
8737             if (asprintf(&str_num, "%03.1Lf", set->value.num) == -1) {
8738                 str_num = NULL;
8739             }
8740         }
8741         if (!str_num) {
8742             LOGMEM;
8743             return;
8744         }
8745         ly_print(&out, "%s\n\n", str_num);
8746         free(str_num);
8747         break;
8748     case LYXP_SET_NODE_SET:
8749         ly_print(&out, "Node XPath set:\n");
8750 
8751         for (i = 0; i < set->used; ++i) {
8752             ly_print(&out, "%d. ", i + 1);
8753             switch (set->node_type[i]) {
8754             case LYXP_NODE_ROOT_ALL:
8755                 ly_print(&out, "ROOT all\n\n");
8756                 break;
8757             case LYXP_NODE_ROOT_CONFIG:
8758                 ly_print(&out, "ROOT config\n\n");
8759                 break;
8760             case LYXP_NODE_ROOT_STATE:
8761                 ly_print(&out, "ROOT state\n\n");
8762                 break;
8763             case LYXP_NODE_ROOT_NOTIF:
8764                 ly_print(&out, "ROOT notification \"%s\"\n\n", set->value.nodes[i]->schema->name);
8765                 break;
8766             case LYXP_NODE_ROOT_RPC:
8767                 ly_print(&out, "ROOT rpc \"%s\"\n\n", set->value.nodes[i]->schema->name);
8768                 break;
8769             case LYXP_NODE_ROOT_OUTPUT:
8770                 ly_print(&out, "ROOT output \"%s\"\n\n", set->value.nodes[i]->schema->name);
8771                 break;
8772             case LYXP_NODE_ELEM:
8773                 ly_print(&out, "ELEM \"%s\"\n", set->value.nodes[i]->schema->name);
8774                 xml_print_node(&out, 1, set->value.nodes[i], 1, LYP_FORMAT);
8775                 ly_print(&out, "\n");
8776                 break;
8777             case LYXP_NODE_TEXT:
8778                 ly_print(&out, "TEXT \"%s\"\n\n", ((struct lyd_node_leaf_list *)set->value.nodes[i])->value_str);
8779                 break;
8780             case LYXP_NODE_ATTR:
8781                 ly_print(&out, "ATTR \"%s\" = \"%s\"\n\n", set->value.attrs[i]->name, set->value.attrs[i]->value);
8782                 break;
8783             }
8784         }
8785         break;
8786     }
8787 }
8788 
8789 #endif
8790 
8791 int
lyxp_set_cast(struct lyxp_set * set,enum lyxp_set_type target,const struct lyd_node * cur_node,const struct lys_module * local_mod,int options)8792 lyxp_set_cast(struct lyxp_set *set, enum lyxp_set_type target, const struct lyd_node *cur_node,
8793               const struct lys_module *local_mod, int options)
8794 {
8795     long double num;
8796     char *str;
8797 
8798     if (!set || (set->type == target)) {
8799         return EXIT_SUCCESS;
8800     }
8801 
8802     /* it's not possible to convert anything into a node set */
8803     assert((target != LYXP_SET_NODE_SET) && ((set->type != LYXP_SET_SNODE_SET) || (target == LYXP_SET_EMPTY)));
8804 
8805     if (set->type == LYXP_SET_SNODE_SET) {
8806         set_free_content(set);
8807         return -1;
8808     }
8809 
8810     /* to STRING */
8811     if ((target == LYXP_SET_STRING) || ((target == LYXP_SET_NUMBER)
8812             && ((set->type == LYXP_SET_NODE_SET) || (set->type == LYXP_SET_EMPTY)))) {
8813         switch (set->type) {
8814         case LYXP_SET_NUMBER:
8815             if (isnan(set->val.num)) {
8816                 set->val.str = strdup("NaN");
8817                 LY_CHECK_ERR_RETURN(!set->val.str, LOGMEM(local_mod->ctx), -1);
8818             } else if ((set->val.num == 0) || (set->val.num == -0.0f)) {
8819                 set->val.str = strdup("0");
8820                 LY_CHECK_ERR_RETURN(!set->val.str, LOGMEM(local_mod->ctx), -1);
8821             } else if (isinf(set->val.num) && !signbit(set->val.num)) {
8822                 set->val.str = strdup("Infinity");
8823                 LY_CHECK_ERR_RETURN(!set->val.str, LOGMEM(local_mod->ctx), -1);
8824             } else if (isinf(set->val.num) && signbit(set->val.num)) {
8825                 set->val.str = strdup("-Infinity");
8826                 LY_CHECK_ERR_RETURN(!set->val.str, LOGMEM(local_mod->ctx), -1);
8827             } else if ((long long)set->val.num == set->val.num) {
8828                 if (asprintf(&str, "%lld", (long long)set->val.num) == -1) {
8829                     LOGMEM(local_mod->ctx);
8830                     return -1;
8831                 }
8832                 set->val.str = str;
8833             } else {
8834                 if (asprintf(&str, "%03.1Lf", set->val.num) == -1) {
8835                     LOGMEM(local_mod->ctx);
8836                     return -1;
8837                 }
8838                 set->val.str = str;
8839             }
8840             break;
8841         case LYXP_SET_BOOLEAN:
8842             if (set->val.bool) {
8843                 set->val.str = strdup("true");
8844             } else {
8845                 set->val.str = strdup("false");
8846             }
8847             LY_CHECK_ERR_RETURN(!set->val.str, LOGMEM(local_mod->ctx), -1);
8848             break;
8849         case LYXP_SET_NODE_SET:
8850             assert(set->used);
8851 
8852             /* we need the set sorted, it affects the result */
8853             assert(!set_sort(set, cur_node, options));
8854 
8855             str = cast_node_set_to_string(set, (struct lyd_node *)cur_node, (struct lys_module *)local_mod, options);
8856             if (!str) {
8857                 return -1;
8858             }
8859             set_free_content(set);
8860             set->val.str = str;
8861             break;
8862         case LYXP_SET_EMPTY:
8863             set->val.str = strdup("");
8864             LY_CHECK_ERR_RETURN(!set->val.str, LOGMEM(local_mod->ctx), -1);
8865             break;
8866         default:
8867             LOGINT(local_mod ? local_mod->ctx : NULL);
8868             return -1;
8869         }
8870         set->type = LYXP_SET_STRING;
8871     }
8872 
8873     /* to NUMBER */
8874     if (target == LYXP_SET_NUMBER) {
8875         switch (set->type) {
8876         case LYXP_SET_STRING:
8877             num = cast_string_to_number(set->val.str);
8878             set_free_content(set);
8879             set->val.num = num;
8880             break;
8881         case LYXP_SET_BOOLEAN:
8882             if (set->val.bool) {
8883                 set->val.num = 1;
8884             } else {
8885                 set->val.num = 0;
8886             }
8887             break;
8888         default:
8889             LOGINT(local_mod ? local_mod->ctx : NULL);
8890             return -1;
8891         }
8892         set->type = LYXP_SET_NUMBER;
8893     }
8894 
8895     /* to BOOLEAN */
8896     if (target == LYXP_SET_BOOLEAN) {
8897         switch (set->type) {
8898         case LYXP_SET_NUMBER:
8899             if ((set->val.num == 0) || (set->val.num == -0.0f) || isnan(set->val.num)) {
8900                 set->val.bool = 0;
8901             } else {
8902                 set->val.bool = 1;
8903             }
8904             break;
8905         case LYXP_SET_STRING:
8906             if (set->val.str[0]) {
8907                 set_free_content(set);
8908                 set->val.bool = 1;
8909             } else {
8910                 set_free_content(set);
8911                 set->val.bool = 0;
8912             }
8913             break;
8914         case LYXP_SET_NODE_SET:
8915             set_free_content(set);
8916 
8917             assert(set->used);
8918             set->val.bool = 1;
8919             break;
8920         case LYXP_SET_EMPTY:
8921             set->val.bool = 0;
8922             break;
8923         default:
8924             LOGINT(local_mod ? local_mod->ctx : NULL);
8925             return -1;
8926         }
8927         set->type = LYXP_SET_BOOLEAN;
8928     }
8929 
8930     /* to EMPTY */
8931     if (target == LYXP_SET_EMPTY) {
8932         set_free_content(set);
8933         set->type = LYXP_SET_EMPTY;
8934     }
8935 
8936     return EXIT_SUCCESS;
8937 }
8938 
8939 int
lyxp_atomize(const char * expr,const struct lys_node * cur_snode,enum lyxp_node_type cur_snode_type,struct lyxp_set * set,int options,const struct lys_node ** ctx_snode)8940 lyxp_atomize(const char *expr, const struct lys_node *cur_snode, enum lyxp_node_type cur_snode_type,
8941              struct lyxp_set *set, int options, const struct lys_node **ctx_snode)
8942 {
8943     struct lys_node *_ctx_snode;
8944     enum lyxp_node_type ctx_snode_type;
8945     struct lyxp_expr *exp;
8946     uint16_t exp_idx = 0;
8947     int rc = -1;
8948 
8949     exp = lyxp_parse_expr(cur_snode->module->ctx, expr);
8950     if (!exp) {
8951         rc = -1;
8952         goto finish;
8953     }
8954 
8955     rc = reparse_or_expr(cur_snode->module->ctx, exp, &exp_idx);
8956     if (rc) {
8957         goto finish;
8958     } else if (exp->used > exp_idx) {
8959         LOGVAL(cur_snode->module->ctx, LYE_XPATH_INTOK, LY_VLOG_NONE, NULL, "Unknown", &exp->expr[exp->expr_pos[exp_idx]]);
8960         LOGVAL(cur_snode->module->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Unparsed characters \"%s\" left at the end of an XPath expression.",
8961                &exp->expr[exp->expr_pos[exp_idx]]);
8962         rc = -1;
8963         goto finish;
8964     }
8965 
8966     print_expr_struct_debug(exp);
8967 
8968     if (options & LYXP_SNODE_WHEN) {
8969         /* for when the context node may need to be changed */
8970         resolve_when_ctx_snode(cur_snode, &_ctx_snode, &ctx_snode_type);
8971     } else {
8972         _ctx_snode = (struct lys_node *)cur_snode;
8973         ctx_snode_type = cur_snode_type;
8974     }
8975 
8976     if (ctx_snode) {
8977         *ctx_snode = _ctx_snode;
8978     }
8979 
8980     exp_idx = 0;
8981     memset(set, 0, sizeof *set);
8982     set->type = LYXP_SET_SNODE_SET;
8983     set_snode_insert_node(set, _ctx_snode, ctx_snode_type);
8984 
8985     rc = eval_expr_select(exp, &exp_idx, 0, (struct lyd_node *)_ctx_snode, lys_node_module(cur_snode), set, options);
8986     if (rc == 2) {
8987         rc = EXIT_SUCCESS;
8988     }
8989 
8990 finish:
8991     lyxp_expr_free(exp);
8992     return rc;
8993 }
8994 
8995 int
lyxp_node_atomize(const struct lys_node * node,struct lyxp_set * set,int set_ext_dep_flags)8996 lyxp_node_atomize(const struct lys_node *node, struct lyxp_set *set, int set_ext_dep_flags)
8997 {
8998     struct lys_node *parent, *elem;
8999     const struct lys_node *ctx_snode = NULL;
9000     struct lyxp_set tmp_set;
9001     uint8_t must_size = 0;
9002     uint32_t i, j;
9003     int opts, ret = EXIT_SUCCESS;
9004     struct lys_when *when = NULL;
9005     struct lys_restr *must = NULL;
9006     char *path = NULL;
9007 
9008     memset(&tmp_set, 0, sizeof tmp_set);
9009     memset(set, 0, sizeof *set);
9010 
9011     /* check if we will be traversing RPC output */
9012     opts = 0;
9013     for (parent = (struct lys_node *)node; parent && (parent->nodetype != LYS_OUTPUT); parent = lys_parent(parent));
9014     if (parent) {
9015         opts |= LYXP_SNODE_OUTPUT;
9016     }
9017 
9018     switch (node->nodetype) {
9019     case LYS_CONTAINER:
9020         when = ((struct lys_node_container *)node)->when;
9021         must = ((struct lys_node_container *)node)->must;
9022         must_size = ((struct lys_node_container *)node)->must_size;
9023         break;
9024     case LYS_CHOICE:
9025         when = ((struct lys_node_choice *)node)->when;
9026         break;
9027     case LYS_LEAF:
9028         when = ((struct lys_node_leaf *)node)->when;
9029         must = ((struct lys_node_leaf *)node)->must;
9030         must_size = ((struct lys_node_leaf *)node)->must_size;
9031         break;
9032     case LYS_LEAFLIST:
9033         when = ((struct lys_node_leaflist *)node)->when;
9034         must = ((struct lys_node_leaflist *)node)->must;
9035         must_size = ((struct lys_node_leaflist *)node)->must_size;
9036         break;
9037     case LYS_LIST:
9038         when = ((struct lys_node_list *)node)->when;
9039         must = ((struct lys_node_list *)node)->must;
9040         must_size = ((struct lys_node_list *)node)->must_size;
9041         break;
9042     case LYS_ANYXML:
9043     case LYS_ANYDATA:
9044         when = ((struct lys_node_anydata *)node)->when;
9045         must = ((struct lys_node_anydata *)node)->must;
9046         must_size = ((struct lys_node_anydata *)node)->must_size;
9047         break;
9048     case LYS_CASE:
9049         when = ((struct lys_node_case *)node)->when;
9050         break;
9051     case LYS_NOTIF:
9052         must = ((struct lys_node_notif *)node)->must;
9053         must_size = ((struct lys_node_notif *)node)->must_size;
9054         break;
9055     case LYS_INPUT:
9056     case LYS_OUTPUT:
9057         must = ((struct lys_node_inout *)node)->must;
9058         must_size = ((struct lys_node_inout *)node)->must_size;
9059         break;
9060     case LYS_USES:
9061         when = ((struct lys_node_uses *)node)->when;
9062         break;
9063     case LYS_AUGMENT:
9064         when = ((struct lys_node_augment *)node)->when;
9065         break;
9066     default:
9067         /* nothing to check */
9068         break;
9069     }
9070 
9071     if (set_ext_dep_flags) {
9072         /* find operation if in one, used later */
9073         for (parent = (struct lys_node *)node;
9074              parent && !(parent->nodetype & (LYS_RPC | LYS_ACTION | LYS_NOTIF));
9075              parent = lys_parent(parent));
9076     }
9077 
9078     /* check "when" */
9079     if (when) {
9080         if (lyxp_atomize(when->cond, node, LYXP_NODE_ELEM, &tmp_set, LYXP_SNODE_WHEN | opts, &ctx_snode)) {
9081             free(tmp_set.val.snodes);
9082             if (ctx_snode) {
9083                 path = lys_path(ctx_snode, LYS_PATH_FIRST_PREFIX);
9084                 LOGVAL(node->module->ctx, LYE_SPEC, LY_VLOG_LYS, node,
9085                        "Invalid when condition \"%s\" with context node \"%s\".", when->cond, path);
9086             } else {
9087                 LOGVAL(node->module->ctx, LYE_SPEC, LY_VLOG_LYS, node, "Invalid when condition \"%s\".", when->cond);
9088             }
9089             ret = -1;
9090             goto finish;
9091         } else {
9092             if (set_ext_dep_flags) {
9093                 for (j = 0; j < tmp_set.used; ++j) {
9094                     /* skip roots'n'stuff */
9095                     if (tmp_set.val.snodes[j].type == LYXP_NODE_ELEM) {
9096                         /* XPath expression cannot reference "lower" status than the node that has the definition */
9097                         if (lyp_check_status(node->flags, lys_node_module(node), node->name, tmp_set.val.snodes[j].snode->flags,
9098                                 lys_node_module(tmp_set.val.snodes[j].snode), tmp_set.val.snodes[j].snode->name, node)) {
9099                             ret = -1;
9100                             goto finish;
9101                         }
9102 
9103                         if (parent) {
9104                             for (elem = tmp_set.val.snodes[j].snode; elem && (elem != parent); elem = lys_parent(elem));
9105                             if (!elem) {
9106                                 /* not in node's RPC or notification subtree, set the correct dep flag */
9107                                 if (tmp_set.val.snodes[j].snode->flags & LYS_CONFIG_W) {
9108                                     when->flags |= LYS_XPCONF_DEP;
9109                                     ((struct lys_node *)node)->flags |= LYS_XPCONF_DEP;
9110                                 } else {
9111                                     assert(tmp_set.val.snodes[j].snode->flags & LYS_CONFIG_R);
9112                                     when->flags |= LYS_XPSTATE_DEP;
9113                                     ((struct lys_node *)node)->flags |= LYS_XPSTATE_DEP;
9114                                 }
9115                             }
9116                         }
9117                     }
9118                 }
9119             }
9120             set_snode_merge(set, &tmp_set);
9121             memset(&tmp_set, 0, sizeof tmp_set);
9122         }
9123     }
9124 
9125     /* check "must" */
9126     for (i = 0; i < must_size; ++i) {
9127         if (lyxp_atomize(must[i].expr, node, LYXP_NODE_ELEM, &tmp_set, LYXP_SNODE_MUST | opts, &ctx_snode)) {
9128             free(tmp_set.val.snodes);
9129             if (ctx_snode) {
9130                 path = lys_path(ctx_snode, LYS_PATH_FIRST_PREFIX);
9131                 LOGVAL(node->module->ctx, LYE_SPEC, LY_VLOG_LYS, node,
9132                        "Invalid must restriction \"%s\" with context node \"%s\".", must[i].expr, path);
9133             } else {
9134                 LOGVAL(node->module->ctx, LYE_SPEC, LY_VLOG_LYS, node, "Invalid must restriction \"%s\".", must[i].expr);
9135             }
9136             ret = -1;
9137             goto finish;
9138         } else {
9139             if (set_ext_dep_flags) {
9140                 for (j = 0; j < tmp_set.used; ++j) {
9141                     /* skip roots'n'stuff */
9142                     if (tmp_set.val.snodes[j].type == LYXP_NODE_ELEM) {
9143                         /* XPath expression cannot reference "lower" status than the node that has the definition */
9144                         if (lyp_check_status(node->flags, lys_node_module(node), node->name, tmp_set.val.snodes[j].snode->flags,
9145                                 lys_node_module(tmp_set.val.snodes[j].snode), tmp_set.val.snodes[j].snode->name, node)) {
9146                             ret = -1;
9147                             goto finish;
9148                         }
9149 
9150                         if (parent) {
9151                             for (elem = tmp_set.val.snodes[j].snode; elem && (elem != parent); elem = lys_parent(elem));
9152                             if (!elem) {
9153                                 /* not in node's RPC or notification subtree, set the correct dep flag */
9154                                 if (tmp_set.val.snodes[j].snode->flags & LYS_CONFIG_W) {
9155                                     must[i].flags |= LYS_XPCONF_DEP;
9156                                     ((struct lys_node *)node)->flags |= LYS_XPCONF_DEP;
9157                                 } else if (tmp_set.val.snodes[j].snode->flags & LYS_CONFIG_R) {
9158                                     must[i].flags |= LYS_XPSTATE_DEP;
9159                                     ((struct lys_node *)node)->flags |= LYS_XPSTATE_DEP;
9160                                 } else {
9161                                     /* only possible if the node is in an unimplemented augment */
9162                                     elem = tmp_set.val.snodes[j].snode;
9163                                     while (elem && (elem->nodetype != LYS_AUGMENT)) {
9164                                         elem = elem->parent;
9165                                     }
9166                                     assert(elem && !lys_node_module(elem)->implemented);
9167                                 }
9168                             }
9169                         }
9170                     }
9171                 }
9172             }
9173             set_snode_merge(set, &tmp_set);
9174             memset(&tmp_set, 0, sizeof tmp_set);
9175         }
9176     }
9177 
9178 finish:
9179     if (ret) {
9180         free(set->val.snodes);
9181         memset(set, 0, sizeof *set);
9182     }
9183     set_free_content(&tmp_set);
9184     free(path);
9185     return ret;
9186 }
9187 
9188 int
lyxp_node_check_syntax(const struct lys_node * node)9189 lyxp_node_check_syntax(const struct lys_node *node)
9190 {
9191     uint8_t must_size = 0;
9192     uint16_t exp_idx;
9193     uint32_t i;
9194     struct lys_when *when = NULL;
9195     struct lys_restr *must = NULL;
9196     struct lyxp_expr *expr;
9197 
9198     switch (node->nodetype) {
9199     case LYS_CONTAINER:
9200         when = ((struct lys_node_container *)node)->when;
9201         must = ((struct lys_node_container *)node)->must;
9202         must_size = ((struct lys_node_container *)node)->must_size;
9203         break;
9204     case LYS_CHOICE:
9205         when = ((struct lys_node_choice *)node)->when;
9206         break;
9207     case LYS_LEAF:
9208         when = ((struct lys_node_leaf *)node)->when;
9209         must = ((struct lys_node_leaf *)node)->must;
9210         must_size = ((struct lys_node_leaf *)node)->must_size;
9211         break;
9212     case LYS_LEAFLIST:
9213         when = ((struct lys_node_leaflist *)node)->when;
9214         must = ((struct lys_node_leaflist *)node)->must;
9215         must_size = ((struct lys_node_leaflist *)node)->must_size;
9216         break;
9217     case LYS_LIST:
9218         when = ((struct lys_node_list *)node)->when;
9219         must = ((struct lys_node_list *)node)->must;
9220         must_size = ((struct lys_node_list *)node)->must_size;
9221         break;
9222     case LYS_ANYXML:
9223     case LYS_ANYDATA:
9224         when = ((struct lys_node_anydata *)node)->when;
9225         must = ((struct lys_node_anydata *)node)->must;
9226         must_size = ((struct lys_node_anydata *)node)->must_size;
9227         break;
9228     case LYS_CASE:
9229         when = ((struct lys_node_case *)node)->when;
9230         break;
9231     case LYS_NOTIF:
9232         must = ((struct lys_node_notif *)node)->must;
9233         must_size = ((struct lys_node_notif *)node)->must_size;
9234         break;
9235     case LYS_INPUT:
9236     case LYS_OUTPUT:
9237         must = ((struct lys_node_inout *)node)->must;
9238         must_size = ((struct lys_node_inout *)node)->must_size;
9239         break;
9240     case LYS_USES:
9241         when = ((struct lys_node_uses *)node)->when;
9242         break;
9243     case LYS_AUGMENT:
9244         when = ((struct lys_node_augment *)node)->when;
9245         break;
9246     default:
9247         /* nothing to check */
9248         break;
9249     }
9250 
9251     /* check "when" */
9252     if (when) {
9253         expr = lyxp_parse_expr(node->module->ctx, when->cond);
9254         if (!expr) {
9255             return -1;
9256         }
9257 
9258         exp_idx = 0;
9259         if (reparse_or_expr(node->module->ctx, expr, &exp_idx)) {
9260             lyxp_expr_free(expr);
9261             return -1;
9262         } else if (exp_idx != expr->used) {
9263             LOGVAL(node->module->ctx, LYE_XPATH_INTOK, LY_VLOG_NONE, NULL,
9264                    print_token(expr->tokens[exp_idx]), &expr->expr[expr->expr_pos[exp_idx]]);
9265             lyxp_expr_free(expr);
9266             return -1;
9267         }
9268         lyxp_expr_free(expr);
9269     }
9270 
9271     /* check "must" */
9272     for (i = 0; i < must_size; ++i) {
9273         expr = lyxp_parse_expr(node->module->ctx, must[i].expr);
9274         if (!expr) {
9275             return -1;
9276         }
9277 
9278         exp_idx = 0;
9279         if (reparse_or_expr(node->module->ctx, expr, &exp_idx)) {
9280             lyxp_expr_free(expr);
9281             return -1;
9282         } else if (exp_idx != expr->used) {
9283             LOGVAL(node->module->ctx, LYE_XPATH_INTOK, LY_VLOG_NONE, NULL,
9284                    print_token(expr->tokens[exp_idx]), &expr->expr[expr->expr_pos[exp_idx]]);
9285             lyxp_expr_free(expr);
9286             return -1;
9287         }
9288         lyxp_expr_free(expr);
9289     }
9290 
9291     return 0;
9292 }
9293