File: promises.c

package info (click to toggle)
cfengine3 3.24.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 37,552 kB
  • sloc: ansic: 163,161; sh: 10,296; python: 2,950; makefile: 1,744; lex: 784; yacc: 633; perl: 211; pascal: 157; xml: 21; sed: 13
file content (941 lines) | stat: -rw-r--r-- 33,912 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
/*
  Copyright 2024 Northern.tech AS

  This file is part of CFEngine 3 - written and maintained by Northern.tech AS.

  This program is free software; you can redistribute it and/or modify it
  under the terms of the GNU General Public License as published by the
  Free Software Foundation; version 3.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA

  To the extent this program is licensed as part of the Enterprise
  versions of CFEngine, the applicable Commercial Open Source License
  (COSL) may apply to this file if you as a licensee so wish it. See
  included file COSL.txt.
*/

#include <promises.h>

#include <policy.h>
#include <syntax.h>
#include <expand.h>
#include <files_names.h>
#include <scope.h>
#include <vars.h>
#include <locks.h>
#include <misc_lib.h>
#include <fncall.h>
#include <eval_context.h>
#include <string_lib.h>
#include <audit.h>

static void AddDefaultBodiesToPromise(EvalContext *ctx, Promise *promise, const PromiseTypeSyntax *syntax);

void CopyBodyConstraintsToPromise(EvalContext *ctx, Promise *pp,
                                  const Body *bp)
{
    for (size_t k = 0; k < SeqLength(bp->conlist); k++)
    {
        Constraint *scp = SeqAt(bp->conlist, k);

        if (IsDefinedClass(ctx, scp->classes))
        {
            Rval returnval = ExpandPrivateRval(ctx, NULL, "body",
                                               scp->rval.item, scp->rval.type);
            PromiseAppendConstraint(pp, scp->lval, returnval, false);
        }
    }
}

/**
 * Get a map that rewrites body according to parameters.
 *
 * @NOTE make sure you free the returned map with JsonDestroy().
 */
static JsonElement *GetBodyRewriter(const EvalContext *ctx,
                                    const Body *current_body,
                                    const Rval *called_rval,
                                    bool in_inheritance_chain)
{
    size_t given_args = 0;
    JsonElement *arg_rewriter = JsonObjectCreate(2);

    if (called_rval == NULL)
    {
        // nothing needed, this is not an inherit_from rval
    }
    else if (called_rval->type == RVAL_TYPE_SCALAR)
    {
        // We leave the parameters as they were.

        // Unless the current body matches the
        // parameters of the inherited body, there
        // will be unexpanded variables. But the
        // alternative is to match up body and fncall
        // arguments, which is not trivial.
    }
    else if (called_rval->type == RVAL_TYPE_FNCALL)
    {
        const Rlist *call_args = RvalFnCallValue(*called_rval)->args;
        const Rlist *body_args = current_body->args;

        given_args = RlistLen(call_args);

        while (call_args != NULL &&
               body_args != NULL)
        {
            JsonObjectAppendString(arg_rewriter,
                                   RlistScalarValue(body_args),
                                   RlistScalarValue(call_args));
            call_args = call_args->next;
            body_args = body_args->next;
        }
    }

    size_t required_args = RlistLen(current_body->args);
    // only check arguments for inherited bodies
    if (in_inheritance_chain && required_args != given_args)
    {
        FatalError(ctx,
                   "Argument count mismatch for body "
                   "(gave %zu arguments) vs. inherited body '%s:%s' "
                   "(requires %zu arguments)",
                   given_args,
                   current_body->ns, current_body->name, required_args);
    }

    return arg_rewriter;
}

/**
 * Appends expanded bodies to the promise #pcopy. It expands the bodies based
 * on arguments, inheritance, and it can optionally flatten the '@' slists and
 * expand the variables in the body according to the EvalContext.
 */
static void AppendExpandedBodies(EvalContext *ctx, Promise *pcopy,
                                 const Seq *bodies_and_args,
                                 bool flatten_slists, bool expand_body_vars)
{
    size_t ba_len = SeqLength(bodies_and_args);

    /* Iterate over all parent bodies, and finally over the body of the
     * promise itself, expanding arguments.  We have already reversed the Seq
     * so we start with the most distant parent in the inheritance tree. */
    for (size_t i = 0; i < ba_len; i += 2)
    {
        const Rval *called_rval  = SeqAt(bodies_and_args, i);
        const Body *current_body = SeqAt(bodies_and_args, i + 1);
        bool in_inheritance_chain= (ba_len - i > 2);

        JsonElement *arg_rewriter =
            GetBodyRewriter(ctx, current_body, called_rval,
                            in_inheritance_chain);

        size_t constraints_num = SeqLength(current_body->conlist);
        for (size_t k = 0; k < constraints_num; k++)
        {
            const Constraint *scp = SeqAt(current_body->conlist, k);

            // we don't copy the inherit_from attribute or associated call
            if (strcmp("inherit_from", scp->lval) == 0)
            {
                continue;
            }

            if (IsDefinedClass(ctx, scp->classes))
            {
                /* We copy the Rval expanding all, including inherited,
                 * body arguments. */
                Rval newrv = RvalCopyRewriter(scp->rval, arg_rewriter);

                /* Expand '@' slists. */
                if (flatten_slists && newrv.type == RVAL_TYPE_LIST)
                {
                    RlistFlatten(ctx, (Rlist **) &newrv.item);
                }

                /* Expand body vars; note it has to happen ONLY ONCE. */
                if (expand_body_vars)
                {
                    Rval newrv2 = ExpandPrivateRval(ctx, NULL, "body",
                                                    newrv.item, newrv.type);
                    RvalDestroy(newrv);
                    newrv = newrv2;
                }

                /* PromiseAppendConstraint() overwrites existing constraints,
                   thus inheritance just works, as it correctly overwrites
                   parents' constraints. */
                Constraint *scp_copy =
                    PromiseAppendConstraint(pcopy, scp->lval,
                                            newrv, false);
                scp_copy->offset = scp->offset;

                char *rval_s     = RvalToString(scp->rval);
                char *rval_exp_s = RvalToString(scp_copy->rval);
                Log(LOG_LEVEL_DEBUG, "DeRefCopyPromise():         "
                    "expanding constraint '%s': '%s' -> '%s'",
                    scp->lval, rval_s, rval_exp_s);
                free(rval_exp_s);
                free(rval_s);
            }
        } /* for all body constraints */

        JsonDestroy(arg_rewriter);
    }
}

static Rval GetExpandedBodyAsContainer(EvalContext *ctx,
                                       const Seq *bodies_and_args,
                                       bool flatten_slists,
                                       bool expand_body_vars)
{
    const size_t ba_len = SeqLength(bodies_and_args);
    JsonElement *body = JsonObjectCreate(ba_len / 2);

    /* Iterate over all parent bodies, and finally over the body of the
     * promise itself, expanding arguments.  We have already reversed the Seq
     * so we start with the most distant parent in the inheritance tree. */
    for (size_t i = 0; i < ba_len; i += 2)
    {
        const Rval *called_rval  = SeqAt(bodies_and_args, i);
        const Body *current_body = SeqAt(bodies_and_args, i + 1);
        bool in_inheritance_chain = (ba_len - i > 2);

        JsonElement *arg_rewriter =
            GetBodyRewriter(ctx, current_body, called_rval,
                            in_inheritance_chain);

        const size_t constraints_num = SeqLength(current_body->conlist);
        for (size_t k = 0; k < constraints_num; k++)
        {
            const Constraint *scp = SeqAt(current_body->conlist, k);

            // we don't copy the inherit_from attribute or associated call
            if (StringEqual("inherit_from", scp->lval))
            {
                continue;
            }

            if (IsDefinedClass(ctx, scp->classes))
            {
                /* We copy the Rval expanding all, including inherited,
                 * body arguments. */
                Rval newrv = RvalCopyRewriter(scp->rval, arg_rewriter);

                /* Expand '@' slists. */
                if (flatten_slists && newrv.type == RVAL_TYPE_LIST)
                {
                    RlistFlatten(ctx, (Rlist **) &newrv.item);
                }

                /* Expand body vars; note it has to happen ONLY ONCE. */
                if (expand_body_vars)
                {
                    Rval newrv2 = ExpandPrivateRval(ctx, NULL, "body",
                                                    newrv.item, newrv.type);
                    RvalDestroy(newrv);
                    newrv = newrv2;
                }

                /* JsonObjectAppendElement() overwrites existing constraints,
                   thus inheritance just works, as it correctly overwrites
                   parents' constraints. */
                JsonObjectAppendElement(body, scp->lval, RvalToJson(newrv));

                if (WouldLog(LOG_LEVEL_DEBUG))
                {
                    char *rval_s     = RvalToString(scp->rval);
                    char *rval_exp_s = RvalToString(newrv);
                    Log(LOG_LEVEL_DEBUG, "DeRefCopyPromise():         "
                        "expanding constraint '%s': '%s' -> '%s'",
                        scp->lval, rval_s, rval_exp_s);
                    free(rval_exp_s);
                    free(rval_s);
                }
            }
        } /* for all body constraints */

        JsonDestroy(arg_rewriter);
    }

    return RvalNew((void *) body, RVAL_TYPE_CONTAINER);
}

/**
 * Copies the promise, expanding the constraints.
 *
 * 1. copy the promise itself
 * 2. copy constraints: copy the bodies expanding arguments passed
 *    (arg_rewrite), copy the bundles, copy the rest of the constraints
 * 3. flatten '@' slists everywhere
 * 4. handle body inheritance
 */
Promise *DeRefCopyPromise(EvalContext *ctx, const Promise *pp)
{
    Log(LOG_LEVEL_DEBUG,
        "DeRefCopyPromise(): promiser:'%s'",
        SAFENULL(pp->promiser));

    Promise *pcopy = xcalloc(1, sizeof(Promise));

    if (pp->promiser)
    {
        pcopy->promiser = xstrdup(pp->promiser);
    }

    /* Copy promisee (if not NULL) while expanding '@' slists. */
    pcopy->promisee = RvalCopy(pp->promisee);
    if (pcopy->promisee.type == RVAL_TYPE_LIST)
    {
        RlistFlatten(ctx, (Rlist **) &pcopy->promisee.item);
    }

    if (pp->promisee.item != NULL)
    {
        char *promisee_string = RvalToString(pp->promisee);

        CF_ASSERT(pcopy->promisee.item != NULL,
                  "DeRefCopyPromise: Failed to copy promisee: %s",
                  promisee_string);
        Log(LOG_LEVEL_DEBUG, "DeRefCopyPromise():     "
            "expanded promisee: '%s'",
            promisee_string);
        free(promisee_string);
    }

    assert(pp->classes);
    pcopy->classes             = xstrdup(pp->classes);
    pcopy->parent_section      = pp->parent_section;
    pcopy->offset.line         = pp->offset.line;
    pcopy->comment             = pp->comment ? xstrdup(pp->comment) : NULL;
    pcopy->conlist             = SeqNew(10, ConstraintDestroy);
    pcopy->org_pp              = pp->org_pp;
    pcopy->offset              = pp->offset;

/* No further type checking should be necessary here, already done by CheckConstraintTypeMatch */

    for (size_t i = 0; i < SeqLength(pp->conlist); i++)
    {
        Constraint *cp = SeqAt(pp->conlist, i);
        const Policy *policy = PolicyFromPromise(pp);

        /* bodies_and_args: Do we have body to expand, possibly with arguments?
         * At position 0 we'll have the body, then its rval, then the same for
         * each of its inherit_from parents. */
        Seq *bodies_and_args       = NULL;
        const Rlist *args          = NULL;
        const char *body_reference = NULL;

        /* A body template reference could look like a scalar or fn to the parser w/w () */
        switch (cp->rval.type)
        {
        case RVAL_TYPE_SCALAR:
            if (cp->references_body)
            {
                body_reference = RvalScalarValue(cp->rval);
                bodies_and_args = EvalContextResolveBodyExpression(ctx, policy, body_reference, cp->lval);
            }
            args = NULL;
            break;
        case RVAL_TYPE_FNCALL:
            body_reference = RvalFnCallValue(cp->rval)->name;
            bodies_and_args = EvalContextResolveBodyExpression(ctx, policy, body_reference, cp->lval);
            args = RvalFnCallValue(cp->rval)->args;
            break;
        default:
            break;
        }

        /* First case is: we have a body to expand lval = body(args). */

        if (bodies_and_args != NULL &&
            SeqLength(bodies_and_args) > 0)
        {
            const Body *bp = SeqAt(bodies_and_args, 0);
            assert(bp != NULL);

            SeqReverse(bodies_and_args); // when we iterate, start with the furthest parent

            EvalContextStackPushBodyFrame(ctx, pcopy, bp, args);

            if (strcmp(bp->type, cp->lval) != 0)
            {
                Log(LOG_LEVEL_ERR,
                    "Body type mismatch for body reference '%s' in promise "
                    "at line %zu of file '%s', '%s' does not equal '%s'",
                    body_reference, pp->offset.line,
                    PromiseGetBundle(pp)->source_path, bp->type, cp->lval);
            }

            Log(LOG_LEVEL_DEBUG, "DeRefCopyPromise():     "
                "copying body %s: '%s'",
                cp->lval, body_reference);

            if (IsDefinedClass(ctx, cp->classes) && !bp->is_custom)
            {
                /* For new package promises we need to have name of the
                 * package_manager body. */
                char body_name[strlen(cp->lval) + 6];
                xsnprintf(body_name, sizeof(body_name), "%s_name", cp->lval);
                PromiseAppendConstraint(pcopy, body_name,
                       (Rval) {xstrdup(bp->name), RVAL_TYPE_SCALAR }, false);

                /* Keep the referent body type as a boolean for convenience
                 * when checking later. */
                PromiseAppendConstraint(pcopy, cp->lval,
                       (Rval) {xstrdup("true"), RVAL_TYPE_SCALAR }, false);
            }

            if (bp->args)                  /* There are arguments to insert */
            {
                if (!args)
                {
                    Log(LOG_LEVEL_ERR,
                        "Argument mismatch for body reference '%s' in promise "
                        "at line %zu of file '%s'",
                        body_reference, pp->offset.line,
                        PromiseGetBundle(pp)->source_path);
                }

                if (bp->is_custom)
                {
                    PromiseAppendConstraint(pcopy, cp->lval,
                        GetExpandedBodyAsContainer(ctx, bodies_and_args,
                                                   false, true), false);
                }
                else
                {
                    AppendExpandedBodies(ctx, pcopy, bodies_and_args,
                                         false, true);
                }
            }
            else                    /* No body arguments or body undeclared */
            {
                if (args)                                /* body undeclared */
                {
                    Log(LOG_LEVEL_ERR,
                        "Apparent body '%s' was undeclared or could "
                        "have incorrect args, but used in a promise near "
                        "line %zu of %s (possible unquoted literal value)",
                        RvalScalarValue(cp->rval), pp->offset.line,
                        PromiseGetBundle(pp)->source_path);
                }
                else /* no body arguments, but maybe the inherited bodies have */
                {
                    if (bp->is_custom)
                    {
                        PromiseAppendConstraint(pcopy, cp->lval,
                            GetExpandedBodyAsContainer(ctx, bodies_and_args,
                                                       true, false), false);
                    }
                    else
                    {
                        AppendExpandedBodies(ctx, pcopy, bodies_and_args,
                                             true, false);
                    }
                }
            }

            EvalContextStackPopFrame(ctx);
            SeqDestroy(bodies_and_args);
        }
        else                                    /* constraint is not a body */
        {
            if (cp->references_body)
            {
                // assume this is a typed bundle (e.g. edit_line)
                const Bundle *callee =
                    EvalContextResolveBundleExpression(ctx, policy,
                                                       body_reference,
                                                       cp->lval);
                if (!callee)
                {
                    // otherwise, assume this is a method-type call
                    callee = EvalContextResolveBundleExpression(ctx, policy,
                                                                body_reference,
                                                                "agent");
                    if (!callee)
                    {
                        callee = EvalContextResolveBundleExpression(ctx, policy,
                                                                    body_reference,
                                                                    "common");
                    }
                }

                if (callee == NULL &&
                    cp->rval.type != RVAL_TYPE_FNCALL &&
                    strcmp("ifvarclass", cp->lval) != 0 &&
                    strcmp("if",         cp->lval) != 0)
                {
                    char *rval_string = RvalToString(cp->rval);
                    Log(LOG_LEVEL_ERR,
                        "Apparent bundle '%s' was undeclared, but "
                        "used in a promise near line %zu of %s "
                        "(possible unquoted literal value)",
                        rval_string, pp->offset.line,
                        PromiseGetBundle(pp)->source_path);
                    free(rval_string);
                }

                Log(LOG_LEVEL_DEBUG,
                    "DeRefCopyPromise():     copying bundle: '%s'",
                    body_reference);
            }
            else
            {
                Log(LOG_LEVEL_DEBUG,
                    "DeRefCopyPromise():     copying constraint: '%s'",
                    cp->lval);
            }

            /* For all non-body constraints: copy the Rval expanding the
             * '@' list variables. */

            if (IsDefinedClass(ctx, cp->classes))
            {
                Rval newrv = RvalCopy(cp->rval);
                if (newrv.type == RVAL_TYPE_LIST)
                {
                    RlistFlatten(ctx, (Rlist **) &newrv.item);
                }

                PromiseAppendConstraint(pcopy, cp->lval, newrv, false);
            }
        }

    } /* for all constraints */

    // Add default body for promise body types that are not present
    char *bundle_type = pcopy->parent_section->parent_bundle->type;
    const char *promise_type = PromiseGetPromiseType(pcopy);
    const PromiseTypeSyntax *syntax = PromiseTypeSyntaxGet(bundle_type, promise_type);
    AddDefaultBodiesToPromise(ctx, pcopy, syntax);

    // Add default body for global body types that are not present
    const PromiseTypeSyntax *global_syntax = PromiseTypeSyntaxGet("*", "*");
    AddDefaultBodiesToPromise(ctx, pcopy, global_syntax);

    return pcopy;
}

// Try to add default bodies to promise for every body type found in syntax
static void AddDefaultBodiesToPromise(EvalContext *ctx, Promise *promise, const PromiseTypeSyntax *syntax)
{
    // do nothing if syntax is not defined
    if (syntax == NULL) {
        return;
    }

    // iterate over possible constraints
    for (int i = 0; syntax->constraints[i].lval; i++)
    {
        // of type body
        if(syntax->constraints[i].dtype == CF_DATA_TYPE_BODY) {
            const char *constraint_type = syntax->constraints[i].lval;
            // if there is no matching body in this promise
            if(!PromiseBundleOrBodyConstraintExists(ctx, constraint_type, promise)) {
                const Policy *policy = PolicyFromPromise(promise);
                // default format is <promise_type>_<body_type>
                char* default_body_name = StringConcatenate(3, PromiseGetPromiseType(promise), "_", constraint_type);
                const Body *bp = EvalContextFindFirstMatchingBody(policy, constraint_type, "bodydefault", default_body_name);
                if(bp) {
                    Log(LOG_LEVEL_VERBOSE, "Using the default body: %60s", default_body_name);
                    CopyBodyConstraintsToPromise(ctx, promise, bp);
                }
                free(default_body_name);
            }
        }
    }
}

/*****************************************************************************/

static bool EvaluateConstraintIteration(EvalContext *ctx, const Constraint *cp, Rval *rval_out)
{
    assert(cp->type == POLICY_ELEMENT_TYPE_PROMISE);
    const Promise *pp = cp->parent.promise;

    if (!IsDefinedClass(ctx, cp->classes))
    {
        return false;
    }

    if (ExpectedDataType(cp->lval) == CF_DATA_TYPE_BUNDLE)
    {
        *rval_out = ExpandBundleReference(ctx, NULL, "this", cp->rval);
    }
    else
    {
        *rval_out = EvaluateFinalRval(ctx, PromiseGetPolicy(pp), NULL,
                                      "this", cp->rval, false, pp);
    }

    return true;
}

/**
  @brief Helper function to determine whether the Rval of ifvarclass/if/unless is defined.
  If the Rval is a function, call that function.
*/
static ExpressionValue CheckVarClassExpression(const EvalContext *ctx, const Constraint *cp, Promise *pcopy)
{
    assert(ctx);
    assert(cp);
    assert(pcopy);

    /*
      This might fail to expand if there are unexpanded variables in function arguments
      (in which case the function won't be called at all), but the function still returns true.

      If expansion fails for other reasons, assume that we don't know this class.
    */
    Rval final;
    if (!EvaluateConstraintIteration((EvalContext*)ctx, cp, &final))
    {
        return EXPRESSION_VALUE_ERROR;
    }

    char *classes = NULL;
    PromiseAppendConstraint(pcopy, cp->lval, final, false);
    switch (final.type)
    {
    case RVAL_TYPE_SCALAR:
        classes = RvalScalarValue(final);
        break;

    case RVAL_TYPE_FNCALL:
        Log(LOG_LEVEL_DEBUG, "Function call in class expression did not succeed");
        break;

    default:
        break;
    }

    if (classes == NULL)
    {
        return EXPRESSION_VALUE_ERROR;
    }
    // sanity check for unexpanded variables
    if (strchr(classes, '$') || strchr(classes, '@'))
    {
        Log(LOG_LEVEL_DEBUG, "Class expression did not evaluate");
        return EXPRESSION_VALUE_ERROR;
    }

    return CheckClassExpression(ctx, classes);
}

/* Expands "$(this.promiser)" comment if present. Writes the result to pp. */
static void DereferenceAndPutComment(Promise* pp, const char *comment)
{
    free(pp->comment);

    char *sp;
    if ((sp = strstr(comment, "$(this.promiser)")) != NULL ||
        (sp = strstr(comment, "${this.promiser}")) != NULL)
    {
        char *s;
        int this_len    = strlen("$(this.promiser)");
        int this_offset = sp - comment;
        xasprintf(&s, "%.*s%s%s",
                  this_offset, comment, pp->promiser,
                  &comment[this_offset + this_len]);

        pp->comment = s;
    }
    else
    {
        pp->comment = xstrdup(comment);
    }
}

Promise *ExpandDeRefPromise(EvalContext *ctx, const Promise *pp, bool *excluded)
{
    assert(pp != NULL);
    assert(pp->parent_section != NULL);
    assert(pp->promiser != NULL);
    assert(pp->classes != NULL);
    assert(excluded != NULL);

    *excluded = false;

    Rval returnval = ExpandPrivateRval(ctx, PromiseGetNamespace(pp),
                                       "this", pp->promiser, RVAL_TYPE_SCALAR);
    if (returnval.item == NULL)
    {
        assert(returnval.type == RVAL_TYPE_LIST ||
               returnval.type == RVAL_TYPE_NOPROMISEE);
        /* TODO Log() empty slist, promise skipped? */
        *excluded = true;
        return NULL;
    }
    Promise *pcopy = xcalloc(1, sizeof(Promise));
    pcopy->promiser = RvalScalarValue(returnval);

    /* TODO remove the conditions here for fixing redmine#7880. */
    if (!StringEqual("storage", PromiseGetPromiseType(pp)))
    {
        EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_THIS, "promiser", pcopy->promiser,
                                      CF_DATA_TYPE_STRING, "source=promise");
    }

    if (pp->promisee.item)
    {
        pcopy->promisee = EvaluateFinalRval(ctx, PromiseGetPolicy(pp), NULL, "this", pp->promisee, true, pp);
    }
    else
    {
        pcopy->promisee = (Rval) {NULL, RVAL_TYPE_NOPROMISEE };
    }

    pcopy->classes = xstrdup(pp->classes);
    pcopy->parent_section = pp->parent_section;
    pcopy->offset.line = pp->offset.line;
    pcopy->comment = pp->comment ? xstrdup(pp->comment) : NULL;
    pcopy->conlist = SeqNew(10, ConstraintDestroy);
    pcopy->org_pp = pp->org_pp;

    // if this is a class promise, check if it is already set, if so, skip
    if (strcmp("classes", PromiseGetPromiseType(pp)) == 0)
    {
        if (IsDefinedClass(ctx, CanonifyName(pcopy->promiser)))
        {
            Log(LOG_LEVEL_DEBUG,
                "Skipping evaluation of classes promise as class '%s' is already set",
                CanonifyName(pcopy->promiser));

            *excluded = true;
            return pcopy;
        }
    }

    /* Look for 'if'/'ifvarclass' exclusion. */
    {
        /* We need to make sure to check both 'if' and 'ifvarclass' constraints. */
        bool checked_if = false;
        const Constraint *ifvarclass = PromiseGetConstraint(pp, "ifvarclass");
        if (!ifvarclass)
        {
            ifvarclass = PromiseGetConstraint(pp, "if");
            checked_if = true;
        }

        // if - Skip if false or error:
        while (ifvarclass != NULL)
        {
            if (CheckVarClassExpression(ctx, ifvarclass, pcopy) != EXPRESSION_VALUE_TRUE)
            {
                if (LogGetGlobalLevel() >= LOG_LEVEL_VERBOSE)
                {
                    char *ifvarclass_string =  RvalToString(ifvarclass->rval);
                    Log(LOG_LEVEL_VERBOSE, "Skipping promise '%s'"
                        " because constraint '%s => %s' is not met",
                        pp->promiser, ifvarclass->lval, ifvarclass_string);
                    free(ifvarclass_string);
                }
                *excluded = true;
                return pcopy;
            }
            if (!checked_if)
            {
                ifvarclass = PromiseGetConstraint(pp, "if");
                checked_if = true;
            }
            else
            {
                ifvarclass = NULL;
            }
        }
    }

    /* Look for 'unless' exclusion. */
    {
        const Constraint *unless = PromiseGetConstraint(pp, "unless");

        // unless - Skip if true or error:
        if (unless != NULL)
        {
            // If the rval is a function, CheckVarClassExpression will call it
            // It will evaluate the class expression as well:
            const ExpressionValue value = CheckVarClassExpression(ctx, unless, pcopy);
            // If it returns EXPRESSION_VALUE_ERROR, it most likely means there
            // are unexpanded variables in the rval (possibly in function calls)

            if ((EvalContextGetPass(ctx) == CF_DONEPASSES-1)
                && (value == EXPRESSION_VALUE_ERROR))
            {
                char *unless_string =  RvalToString(unless->rval);
                // The rval is most likely a string or a function call,
                // with unexpanded variables, for example:
                // unless => "$(no_such_var)"
                // We default to NOT skipping (since if would skip).
                Log(LOG_LEVEL_VERBOSE,
                    "Not skipping %s promise '%s' with constraint '%s => %s' in last evaluation pass (since if would skip)",
                    PromiseGetPromiseType(pp),
                    pp->promiser,
                    unless->lval,
                    unless_string);
                free(unless_string);
            }
            else if (value != EXPRESSION_VALUE_FALSE)
            {
                if (LogGetGlobalLevel() >= LOG_LEVEL_VERBOSE)
                {
                    char *unless_string =  RvalToString(unless->rval);
                    Log(LOG_LEVEL_VERBOSE,
                        "Skipping promise '%s' because constraint '%s => %s' is not met",
                        pp->promiser, unless->lval, unless_string);
                    free(unless_string);
                }
                *excluded = true;
                return pcopy;
            }
        }
    }

    /* Look for depends_on exclusion. */
    {
        const Constraint *depends_on = PromiseGetConstraint(pp, "depends_on");
        if (depends_on)
        {
            Rval final;
            if (EvaluateConstraintIteration(ctx, depends_on, &final))
            {
                PromiseAppendConstraint(pcopy, depends_on->lval, final, false);

                if (MissingDependencies(ctx, pcopy))
                {
                    *excluded = true;
                    return pcopy;
                }
            }
        }
    }

    /* NOTE: We have to undefine the '$(this.promiser)' variable for a 'files'
     *       promise now because it is later defined for the individual
     *       expansions of the promise and so it has to be left unexpanded in
     *       the constraints/attributes. It is, however, defined above just like
     *       for any other promise so that it can be used in the common
     *       if/ifvarclass/unless checking. */
    if (StringEqual(PromiseGetPromiseType(pp), "files"))
    {
        EvalContextVariableRemoveSpecial(ctx, SPECIAL_SCOPE_THIS, "promiser");
    }

    /* Evaluate all constraints. */
    for (size_t i = 0; i < SeqLength(pp->conlist); i++)
    {
        Constraint *cp = SeqAt(pp->conlist, i);

        // special constraints ifvarclass and depends_on are evaluated before the rest of the constraints
        if (strcmp(cp->lval, "ifvarclass") == 0 ||
            strcmp(cp->lval, "if")         == 0 ||
            strcmp(cp->lval, "unless")     == 0 ||
            strcmp(cp->lval, "depends_on") == 0)
        {
            continue;
        }

        Rval final;
        if (!EvaluateConstraintIteration(ctx, cp, &final))
        {
            continue;
        }

        PromiseAppendConstraint(pcopy, cp->lval, final, false);

        if (strcmp(cp->lval, "comment") == 0)
        {
            if (final.type != RVAL_TYPE_SCALAR)
            {
                Log(LOG_LEVEL_ERR, "Comments can only be scalar objects, not '%s' in '%s'",
                    RvalTypeToString(final.type), pp->promiser);
            }
            else
            {
                assert(final.item != NULL);             /* it's SCALAR type */
                DereferenceAndPutComment(pcopy, final.item);
            }
        }
    }

    return pcopy;
}

void PromiseRef(LogLevel level, const Promise *pp)
{
    if (pp == NULL)
    {
        return;
    }

    if (PromiseGetBundle(pp)->source_path)
    {
        Log(level, "Promise belongs to bundle '%s' in file '%s' near line %zu", PromiseGetBundle(pp)->name,
            PromiseGetBundle(pp)->source_path, pp->offset.line);
    }
    else
    {
        Log(level, "Promise belongs to bundle '%s' near line %zu", PromiseGetBundle(pp)->name,
            pp->offset.line);
    }

    if (pp->comment)
    {
        Log(level, "Comment is '%s'", pp->comment);
    }

    switch (pp->promisee.type)
    {
    case RVAL_TYPE_SCALAR:
        Log(level, "This was a promise to '%s'", (char *)(pp->promisee.item));
        break;
    case RVAL_TYPE_LIST:
    {
        Writer *w = StringWriter();
        RlistWrite(w, pp->promisee.item);
        char *p = StringWriterClose(w);
        Log(level, "This was a promise to '%s'", p);
        free(p);
        break;
    }
    default:
        break;
    }
}

/*******************************************************************/

/* Old legacy function from Enterprise, TODO remove static string. */
const char *PromiseID(const Promise *pp)
{
    static char id[CF_MAXVARSIZE];
    char vbuff[CF_MAXVARSIZE];
    const char *handle = PromiseGetHandle(pp);

    if (handle)
    {
        snprintf(id, CF_MAXVARSIZE, "%s", CanonifyName(handle));
    }
    else if (pp && PromiseGetBundle(pp)->source_path)
    {
        snprintf(vbuff, CF_MAXVARSIZE, "%s", ReadLastNode(PromiseGetBundle(pp)->source_path));
        snprintf(id, CF_MAXVARSIZE, "promise_%s_%zu", CanonifyName(vbuff), pp->offset.line);
    }
    else
    {
        snprintf(id, CF_MAXVARSIZE, "unlabelled_promise");
    }

    return id;
}