File: mod_custom.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 (1348 lines) | stat: -rw-r--r-- 43,480 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
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
/*
  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 <mod_custom.h>

#include <syntax.h>
#include <string_lib.h>      // StringStartsWith()
#include <string_sequence.h> // SeqStrginFromString()
#include <policy.h>          // Promise
#include <eval_context.h>    // cfPS(), EvalContextVariableGet()
#include <attributes.h>      // GetClassContextAttributes(), IsClassesBodyConstraint()
#include <expand.h>          // ExpandScalar()
#include <var_expressions.h> // StringContainsUnresolved(), StringIsBareNonScalarRef()
#include <map.h>             // Map*
#include <locks.h>           // AcquireLock()
#include <process_lib.h>     // GracefulTerminate(), GetProcessStartTime()

static Map *custom_modules = NULL;

static const ConstraintSyntax promise_constraints[] = {
    CONSTRAINT_SYNTAX_GLOBAL,
    ConstraintSyntaxNewString(
        "path", "", "Path to promise module", SYNTAX_STATUS_NORMAL),
    ConstraintSyntaxNewString(
        "interpreter", "", "Path to interpreter", SYNTAX_STATUS_NORMAL),
    ConstraintSyntaxNewNull()};

const BodySyntax CUSTOM_PROMISE_BLOCK_SYNTAX =
    BodySyntaxNew("promise", promise_constraints, NULL, SYNTAX_STATUS_NORMAL);

const BodySyntax CUSTOM_BODY_BLOCK_SYNTAX =
    BodySyntaxNew("custom", NULL, NULL, SYNTAX_STATUS_CUSTOM);

Body *FindCustomPromiseType(const Promise *promise)
{
    assert(promise != NULL);

    const char *const promise_type = PromiseGetPromiseType(promise);
    const Policy *const policy =
        promise->parent_section->parent_bundle->parent_policy;
    Seq *custom_promise_types = policy->custom_promise_types;
    const size_t length = SeqLength(custom_promise_types);
    for (size_t i = 0; i < length; ++i)
    {
        Body *current = SeqAt(custom_promise_types, i);
        if (StringEqual(current->name, promise_type))
        {
            return current;
        }
    }
    return NULL;
}

static bool GetInterpreterAndPath(
    EvalContext *ctx,
    Body *promise_block,
    char **interpreter_out,
    char **path_out)
{
    assert(promise_block != NULL);
    assert(interpreter_out != NULL);
    assert(path_out != NULL);

    char *interpreter = NULL;
    char *path = NULL;

    const char *promise_type = promise_block->name;
    Seq *promise_block_attributes = promise_block->conlist;
    const size_t length = SeqLength(promise_block_attributes);

    for (size_t i = 0; i < length; ++i)
    {
        Constraint *attribute = SeqAt(promise_block_attributes, i);
        const char *name = attribute->lval;
        const char *value = RvalScalarValue(attribute->rval);

        if (StringEqual("interpreter", name))
        {
            free(interpreter);
            interpreter = ExpandScalar(ctx, NULL, NULL, value, NULL);
        }
        else if (StringEqual("path", name))
        {
            free(path);
            path = ExpandScalar(ctx, NULL, NULL, value, NULL);
        }
        else
        {
            debug_abort_if_reached();
        }
    }

    if (path == NULL)
    {
        Log(LOG_LEVEL_ERR,
            "Custom promise type '%s' missing path",
            promise_type);
        free(interpreter);
        free(path);
        return false;
    }

    *interpreter_out = interpreter;
    *path_out = path;
    return true;
}

static inline LogLevel PromiseModule_LogJson(JsonElement *object, const Promise *pp, const char *promise_log_level)
{
    const char *level_string = JsonObjectGetAsString(object, "level");
    const char *message = JsonObjectGetAsString(object, "message");

    assert(level_string != NULL && message != NULL);
    const LogLevel level = LogLevelFromString(level_string);
    assert(level != LOG_LEVEL_NOTHING);

    /* Check if there is a log level specified for the particular promise. */
    if ((pp != NULL) && (promise_log_level != NULL))
    {
        LogLevel specific = ActionAttributeLogLevelFromString(promise_log_level);
        if (specific < level)
        {
            /* Do not log messages that have a higher log level than the log
             * level specified for the promise (e.g. 'info' messages when
             * 'error' was requested for the promise). */
            return level;
        }
    }

    Log(level, "%s", message);

    return level;
}

static inline JsonElement *PromiseModule_ParseResultClasses(char *value)
{
    JsonElement *result_classes = JsonArrayCreate(1);
    char *delim = strchr(value, ',');
    while (delim != NULL)
    {
        *delim = '\0';
        JsonArrayAppendString(result_classes, value);
        value = delim + 1;
        delim = strchr(value, ',');
    }
    JsonArrayAppendString(result_classes, value);
    return result_classes;
}

static JsonElement *PromiseModule_Receive(PromiseModule *module, const Promise *pp,
                                          uint16_t n_log_msgs[LOG_LEVEL_DEBUG + 1])
{
    assert(module != NULL);

    bool line_based = !(module->json);

    char *line = NULL;
    size_t size = 0;
    bool empty_line = false;
    JsonElement *log_array = JsonArrayCreate(10);
    JsonElement *response = NULL;

    if (line_based)
    {
        response = JsonObjectCreate(10);
    }

    const char *promise_log_level = NULL;
    if (pp != NULL)
    {
        promise_log_level = PromiseGetConstraintAsRval(pp, "log_level", RVAL_TYPE_SCALAR);
    }

    ssize_t bytes;
    while (!empty_line
           && ((bytes = getline(&line, &size, module->output)) > 0))
    {
        assert(bytes > 0);
        assert(line != NULL);

        assert(line[bytes] == '\0');
        assert(line[bytes - 1] == '\n');
        line[bytes - 1] = '\0';

        // Log only non-empty lines:
        if (bytes > 1)
        {
            Log(LOG_LEVEL_DEBUG, "Received line from module: '%s'", line);
        }

        if (line[0] == '\0')
        {
            empty_line = true;
        }
        else if (StringStartsWith(line, "log_"))
        {
            const char *const equal_sign = strchr(line, '=');
            assert(equal_sign != NULL);
            if (equal_sign == NULL)
            {
                Log(LOG_LEVEL_ERR,
                    "Promise module sent invalid log line: '%s'",
                    line);
                // Skip this line but keep parsing
                FREE_AND_NULL(line);
                size = 0;
                continue;
            }
            const char *const message = equal_sign + 1;
            const char *const level_start = line + strlen("log_");
            const size_t level_length = equal_sign - level_start;
            char *const level = xstrndup(level_start, level_length);
            assert(strlen(level) == level_length);

            JsonElement *log_message = JsonObjectCreate(2);
            JsonObjectAppendString(log_message, "level", level);
            JsonObjectAppendString(log_message, "message", message);
            LogLevel log_level = PromiseModule_LogJson(log_message, pp, promise_log_level);
            if (log_level > LOG_LEVEL_NOTHING)
            {
                n_log_msgs[log_level]++;
            }
            JsonArrayAppendObject(log_array, log_message);

            free(level);
        }
        else if (line_based)
        {
            const char *const equal_sign = strchr(line, '=');
            assert(equal_sign != NULL);
            if (equal_sign == NULL)
            {
                Log(LOG_LEVEL_ERR,
                    "Promise module sent invalid line: '%s'",
                    line);
            }
            else
            {
                const char *const value = equal_sign + 1;
                const size_t key_length = equal_sign - line;
                char *const key = xstrndup(line, key_length);
                assert(strlen(key) == key_length);
                if (StringEqual(key, "result_classes"))
                {
                    char *result_classes_str = xstrdup(value);
                    JsonElement *result_classes = PromiseModule_ParseResultClasses(result_classes_str);
                    JsonObjectAppendArray(response, key, result_classes);
                    free(result_classes_str);
                }
                else
                {
                    JsonObjectAppendString(response, key, value);
                }
                free(key);
            }
        }
        else // JSON protocol:
        {
            assert(strlen(line) > 0);
            assert(response == NULL); // Should be first and only line
            const char *data = line;  // JsonParse() moves this while parsing
            JsonParseError err = JsonParse(&data, &response);
            if (err != JSON_PARSE_OK)
            {
                assert(response == NULL);
                Log(LOG_LEVEL_ERR,
                    "Promise module '%s' sent invalid JSON",
                    module->path);
                free(line);
                return NULL;
            }
            assert(response != NULL);
        }

        FREE_AND_NULL(line);
        size = 0;
    }

    if (response == NULL)
    {
        // This can happen if using the JSON protocol, and the module sends
        // nothing (newlines) or only log= lines.
        assert(!line_based);
        Log(LOG_LEVEL_ERR,
            "The '%s' promise module sent an invalid/incomplete response with JSON based protocol",
            module->path);
        return NULL;
    }

    if (line_based)
    {
        JsonObjectAppendArray(response, "log", log_array);
        log_array = NULL;
    }
    else
    {
        JsonElement *json_log_messages = JsonObjectGet(response, "log");

        // Log messages inside JSON data haven't been printed yet,
        // do it now:
        if (json_log_messages != NULL)
        {
            size_t length = JsonLength(json_log_messages);
            for (size_t i = 0; i < length; ++i)
            {
                LogLevel log_level = PromiseModule_LogJson(JsonArrayGet(json_log_messages, i),
                                                           pp, promise_log_level);
                if (log_level > LOG_LEVEL_NOTHING)
                {
                    n_log_msgs[log_level]++;
                }
            }
        }

        JsonElement *merged = NULL;
        bool had_log_lines = (log_array != NULL && JsonLength(log_array) > 0);
        if (json_log_messages == NULL && !had_log_lines)
        {
            // No log messages at all, no need to add anything to JSON
        }
        else if (!had_log_lines)
        {
            // No separate log lines before JSON data, leave JSON as is
        }
        else if (had_log_lines && (json_log_messages == NULL))
        {
            // Separate log lines, but no log messages in JSON data
            JsonObjectAppendArray(response, "log", log_array);
            log_array = NULL;
        }
        else
        {
            // both log messages as separate lines and in JSON, merge:
            merged = JsonMerge(log_array, json_log_messages);
            JsonObjectAppendArray(response, "log", merged);
            // json_log_messages will be destroyed since we append over it
        }
    }
    JsonDestroy(log_array);

    assert(response != NULL);
    return response;
}

static void PromiseModule_SendMessage(PromiseModule *module, Seq *message)
{
    assert(module != NULL);

    const size_t length = SeqLength(message);
    for (size_t i = 0; i < length; ++i)
    {
        const char *line = SeqAt(message, i);
        NDEBUG_UNUSED const size_t line_length = strlen(line);
        assert(line_length > 0 && memchr(line, '\n', line_length) == NULL);
        fprintf(module->input, "%s\n", line);
    }
    fprintf(module->input, "\n");
    fflush(module->input);
}

static Seq *PromiseModule_ReceiveHeader(PromiseModule *module)
{
    assert(module != NULL);

    // Read header:
    char *line = NULL;
    size_t size = 0;
    ssize_t bytes = getline(&line, &size, module->output);
    if (bytes <= 0)
    {
        Log(LOG_LEVEL_ERR,
            "Did not receive header from promise module '%s'",
            module->path);
        free(line);
        return NULL;
    }
    if (line[bytes - 1] != '\n')
    {
        Log(LOG_LEVEL_ERR,
            "Promise module '%s %s' sent an invalid header with no newline: '%s'",
            module->interpreter,
            module->path,
            line);
        free(line);
        return NULL;
    }
    line[bytes - 1] = '\0';

    Log(LOG_LEVEL_DEBUG, "Received header from promise module: '%s'", line);

    Seq *header = SeqStringFromString(line, ' ');

    FREE_AND_NULL(line);
    size = 0;

    // Read empty line:
    bytes = getline(&line, &size, module->output);
    if (bytes != 1 || line[0] != '\n')
    {
        Log(LOG_LEVEL_ERR,
            "Promise module '%s %s' failed to send empty line after header: '%s'",
            module->interpreter,
            module->path,
            line);
        SeqDestroy(header);
        free(line);
        return NULL;
    }

    free(line);
    return header;
}

// Internal function, use PromiseModule_Terminate instead
static void PromiseModule_DestroyInternal(PromiseModule *module)
{
    assert(module != NULL);

    free(module->path);
    free(module->interpreter);

    cf_pclose_full_duplex(&(module->fds));
    free(module);
}

static PromiseModule *PromiseModule_Start(char *interpreter, char *path)
{
    assert(path != NULL);

    if ((interpreter != NULL) && (access(interpreter, X_OK) != 0))
    {
        Log(LOG_LEVEL_ERR,
            "Promise module interpreter '%s' is not an executable file",
            interpreter);
        return NULL;
    }

    if ((interpreter == NULL) && (access(path, X_OK) != 0))
    {
        Log(LOG_LEVEL_ERR,
            "Promise module path '%s' is not an executable file",
            path);
        return NULL;
    }

    if (access(path, F_OK) != 0)
    {
        Log(LOG_LEVEL_ERR,
            "Promise module '%s' does not exist",
            path);
        return NULL;
    }

    PromiseModule *module = xcalloc(1, sizeof(PromiseModule));

    module->interpreter = interpreter;
    module->path = path;

    char command[CF_BUFSIZE];
    if (interpreter == NULL)
    {
        snprintf(command, CF_BUFSIZE, "%s", path);
    }
    else
    {
        snprintf(command, CF_BUFSIZE, "%s %s", interpreter, path);
    }

    Log(LOG_LEVEL_VERBOSE, "Starting custom promise module '%s' with command '%s'",
        path, command);
    module->fds = cf_popen_full_duplex_streams(command, false, true);
    module->output = module->fds.read_stream;
    module->input = module->fds.write_stream;
    module->message = NULL;

    if (!PipeToPid(&module->pid, module->fds.write_stream))
    {
        Log(LOG_LEVEL_ERR, "Failed to get PID of custom promise module '%s'", path);
        PromiseModule_DestroyInternal(module);
        return NULL;
    }

    module->process_start_time = GetProcessStartTime(module->pid);
    if (module->process_start_time == PROCESS_START_TIME_UNKNOWN)
    {
        Log(LOG_LEVEL_ERR, "Failed to get process start time of custom promise module '%s'", path);
        PromiseModule_DestroyInternal(module);
        return NULL;
    }

    fprintf(module->input, "cf-agent %s v1\n\n", Version());
    fflush(module->input);

    Seq *header = PromiseModule_ReceiveHeader(module);

    if (header == NULL)
    {
        // error logged in PromiseModule_ReceiveHeader()

        /* Make sure 'path' and 'interpreter' are not free'd twice (the calling
         * code frees them if it gets NULL). */
        module->path = NULL;
        module->interpreter = NULL;
        PromiseModule_DestroyInternal(module);
        return NULL;
    }

    /* line_based is the default, but the module should specify it
     * explicitly. */
    module->json = false;
    bool protocol_specified = false;

    const size_t header_length = SeqLength(header);
    const size_t flags_offset = 3;        /* where flags start */
    assert(header_length > flags_offset); /* at least one flag required -- json_based/line_based */
    for (size_t i = flags_offset; i < header_length; ++i)
    {
        const char *const flag = SeqAt(header, i);
        if (StringEqual(flag, "json_based"))
        {
            module->json = true;
            if (protocol_specified)
            {
                Log(LOG_LEVEL_WARNING,
                    "Ambiguous protocol specification from the custom promise module '%s'."
                    " Please report this as a bug in the module",
                    module->path);
            }
            protocol_specified = true;
        }
        else if (StringEqual(flag, "line_based"))
        {
            module->json = false;
            if (protocol_specified)
            {
                Log(LOG_LEVEL_WARNING,
                    "Ambiguous protocol specification from the custom promise module '%s'."
                    " Please report this as a bug in the module",
                    module->path);
            }
            protocol_specified = true;
        }
        else if (StringEqual(flag, "action_policy"))
        {
            module->action_policy = true;
        }
    }

    if (!protocol_specified)
    {
        Log(LOG_LEVEL_WARNING,
            "Custom promise module '%s' didn't fully specify protocol."
            " Using 'line_based' as the default. Please report this as a bug in the module",
            module->path);
    }

    SeqDestroy(header);

    return module;
}

static void PromiseModule_AppendString(
    PromiseModule *module, const char *key, const char *value)
{
    assert(module != NULL);

    if (module->message == NULL)
    {
        module->message = JsonObjectCreate(10);
    }
    JsonObjectAppendString(module->message, key, value);
}

static void PromiseModule_AppendInteger(
    PromiseModule *module, const char *key, int64_t value)
{
    assert(module != NULL);

    if (module->message == NULL)
    {
        module->message = JsonObjectCreate(10);
    }
    JsonObjectAppendInteger64(module->message, key, value);
}

static void PromiseModule_AppendAttribute(
    PromiseModule *module, const char *key, JsonElement *value)
{
    assert(module != NULL);

    if (module->message == NULL)
    {
        module->message = JsonObjectCreate(10);
    }

    JsonElement *attributes = JsonObjectGet(module->message, "attributes");
    if (attributes == NULL)
    {
        attributes = JsonObjectCreate(10);
        JsonObjectAppendObject(module->message, "attributes", attributes);
    }

    JsonObjectAppendElement(attributes, key, value);
}

static void PromiseModule_Send(PromiseModule *module)
{
    assert(module != NULL);

    if (module->json)
    {
        Writer *w = FileWriter(module->input);
        JsonWriteCompact(w, module->message);
        FileWriterDetach(w);
        DESTROY_AND_NULL(JsonDestroy, module->message);
        fprintf(module->input, "\n\n");
        fflush(module->input);
        return;
    }

    Seq *message = SeqNew(10, free);

    JsonIterator iter = JsonIteratorInit(module->message);
    const char *key;
    while ((key = JsonIteratorNextKey(&iter)) != NULL)
    {
        if (StringEqual("attributes", key))
        {
            JsonElement *attributes = JsonIteratorCurrentValue(&iter);
            JsonIterator attr_iter = JsonIteratorInit(attributes);

            const char *attr_name;
            while ((attr_name = JsonIteratorNextKey(&attr_iter)) != NULL)
            {
                const char *attr_val = JsonPrimitiveGetAsString(
                    JsonIteratorCurrentValue(&attr_iter));
                char *attr_line = NULL;
                xasprintf(&attr_line, "attribute_%s=%s", attr_name, attr_val);
                SeqAppend(message, attr_line);
            }
        }
        else
        {
            const char *value =
                JsonPrimitiveGetAsString(JsonIteratorCurrentValue(&iter));
            char *line = NULL;
            xasprintf(&line, "%s=%s", key, value);
            SeqAppend(message, line);
        }
    }

    PromiseModule_SendMessage(module, message);
    SeqDestroy(message);
    DESTROY_AND_NULL(JsonDestroy, module->message);
}

static inline bool TryToGetContainerFromScalarRef(const EvalContext *ctx, const char *scalar, JsonElement **out)
{
    if (StringIsBareNonScalarRef(scalar))
    {
        /* Resolve a potential 'data' variable reference. */
        const size_t scalar_len = strlen(scalar);
        char *var_ref_str = xstrndup(scalar + 2, scalar_len - 3);
        VarRef *ref = VarRefParse(var_ref_str);

        DataType type = CF_DATA_TYPE_NONE;
        const void *val = EvalContextVariableGet(ctx, ref, &type);
        free(var_ref_str);
        VarRefDestroy(ref);

        if ((val != NULL) && (type == CF_DATA_TYPE_CONTAINER))
        {
            if (out != NULL)
            {
                *out = JsonCopy(val);
            }
            return true;
        }
    }
    return false;
}

static void PromiseModule_AppendAllAttributes(
    PromiseModule *module, const EvalContext *ctx, const Promise *pp)
{
    assert(module != NULL);
    assert(pp != NULL);

    /* Need to make sure action_policy is "warn" in case of dry-run/simulate
     * modes. */
    const bool dontdo = (EVAL_MODE != EVAL_MODE_NORMAL);
    bool seen_action_policy = false;

    const size_t attributes = SeqLength(pp->conlist);
    for (size_t i = 0; i < attributes; i++)
    {
        const Constraint *attribute = SeqAt(pp->conlist, i);
        const char *const name = attribute->lval;
        assert(!StringEqual(name, "ifvarclass")); // Not allowed by validation
        if (IsClassesBodyConstraint(name)
            || StringEqual(name, "if")
            || StringEqual(name, "ifvarclass")
            || StringEqual(name, "unless")
            || StringEqual(name, "depends_on")
            || StringEqual(name, "with")
            || StringEqual(name, "meta")
            || StringEqual(name, "expireafter"))
        {
            // Evaluated by agent and not sent to module, skip
            continue;
        }

        if (StringEqual(name, "action") || StringEqual(name, "action_name"))
        {
            /* We only pass "action_policy" to the module (see below). */
            continue;
        }

        if (StringEqual(attribute->lval, "log_level"))
        {
            /* Passed to the module as 'log_level' request field, not as an attribute. */
            continue;
        }

        JsonElement *value = NULL;
        if (dontdo && StringEqual(name, "action_policy"))
        {
            /* Override the value in case of dry-run/simulate modes. */
            seen_action_policy = true;
            value = JsonStringCreate("warn");
        }
        else if (attribute->rval.type == RVAL_TYPE_SCALAR)
        {
            /* Could be a '@(container)' reference. */
            if (!TryToGetContainerFromScalarRef(ctx, RvalScalarValue(attribute->rval), &value))
            {
                /* Didn't resolve to a container value, let's just use the
                 * scalar value as-is. */
                value = RvalToJson(attribute->rval);
            }
        }
        else if ((attribute->rval.type == RVAL_TYPE_LIST) ||
                 (attribute->rval.type == RVAL_TYPE_CONTAINER))
        {
            value = RvalToJson(attribute->rval);
        }

        if (value != NULL)
        {
            PromiseModule_AppendAttribute(module, name, value);
        }
        else
        {
            Log(LOG_LEVEL_VERBOSE,
                "Unsupported type of the '%s' attribute (%c), cannot be sent to custom promise module",
                name, attribute->rval.type);
        }

        seen_action_policy = (seen_action_policy || StringEqual(name, "action_policy"));
    }

    if (dontdo && !seen_action_policy)
    {
        /* Make sure action_policy is specified in case of dry-run/simulate modes. */
        PromiseModule_AppendAttribute(module, "action_policy", JsonStringCreate("warn"));
    }
}

static bool CheckPrimitiveForUnexpandedVars(JsonElement *primitive, ARG_UNUSED void *data)
{
    assert(JsonGetElementType(primitive) == JSON_ELEMENT_TYPE_PRIMITIVE);

    /* Stop the iteration if a variable expression is found. */
    return (!StringContainsUnresolved(JsonPrimitiveGetAsString(primitive)));
}

static bool CheckObjectForUnexpandedVars(JsonElement *object, ARG_UNUSED void *data)
{
    assert(JsonGetType(object) == JSON_TYPE_OBJECT);

    /* Stop the iteration if a variable expression is found among children
     * keys. (elements inside the object are checked separately) */
    JsonIterator iter = JsonIteratorInit(object);
    while (JsonIteratorHasMore(&iter))
    {
        const char *key = JsonIteratorNextKey(&iter);
        if (StringContainsUnresolved(key))
        {
            return false;
        }
    }
    return true;
}

static inline bool CustomPromise_IsFullyResolved(const EvalContext *ctx, const Promise *pp, bool nonscalars_allowed)
{
    assert(pp != NULL);

    if (StringContainsUnresolved(pp->promiser))
    {
        return false;
    }
    const size_t attributes = SeqLength(pp->conlist);
    for (size_t i = 0; i < attributes; i++)
    {
        const Constraint *attribute = SeqAt(pp->conlist, i);
        if (IsClassesBodyConstraint(attribute->lval) ||
            StringEqual(attribute->lval, "meta"))
        {
            /* Not passed to the modules, handled on the agent side. */
            continue;
        }
        if (StringEqual(attribute->lval, "log_level"))
        {
            /* Passed to the module as 'log_level' request field, not as an attribute. */
            continue;
        }
        if (StringEqual(attribute->lval, "unless"))
        {
            /* unless can actually have unresolved variables here,
               it defaults to evaluate in case of unresolved variables,
               to be the true opposite of if. (if would skip).*/
            continue;
        }
        if ((attribute->rval.type == RVAL_TYPE_FNCALL) ||
            (!nonscalars_allowed && (attribute->rval.type != RVAL_TYPE_SCALAR)))
        {
            return false;
        }
        if (attribute->rval.type == RVAL_TYPE_SCALAR)
        {
            const char *const value = RvalScalarValue(attribute->rval);
            if (StringContainsUnresolved(value) && !TryToGetContainerFromScalarRef(ctx, value, NULL))
            {
                return false;
            }
        }
        else if (attribute->rval.type == RVAL_TYPE_LIST)
        {
            assert(nonscalars_allowed);
            for (Rlist *rl = RvalRlistValue(attribute->rval); rl != NULL; rl = rl->next)
            {
                assert(rl->val.type == RVAL_TYPE_SCALAR);
                const char *const value = RvalScalarValue(rl->val);
                if (StringContainsUnresolved(value))
                {
                    return false;
                }
            }
        }
        else
        {
            assert(nonscalars_allowed);
            assert(attribute->rval.type == RVAL_TYPE_CONTAINER);
            JsonElement *attr_data = RvalContainerValue(attribute->rval);
            return JsonWalk(attr_data, CheckObjectForUnexpandedVars, NULL,
                            CheckPrimitiveForUnexpandedVars, NULL);
        }
    }
    return true;
}


static inline bool HasResultAndResultIsValid(JsonElement *response)
{
    const char *const result = JsonObjectGetAsString(response, "result");
    return ((result != NULL) && StringEqual(result, "valid"));
}

static inline const char *LogLevelToRequestFromModule(const Promise *pp)
{
    LogLevel log_level = LogGetGlobalLevel();

    /* Check if there is a log level specified for the particular promise. */
    const char *value = PromiseGetConstraintAsRval(pp, "log_level", RVAL_TYPE_SCALAR);
    if (value != NULL)
    {
        LogLevel specific = ActionAttributeLogLevelFromString(value);

        /* Promise-specific log level cannot go above the global log level
         * (e.g. no 'info' messages for a particular promise if the global level
         * is 'error'). */
        log_level = MIN(log_level, specific);
    }

    // We will never request LOG_LEVEL_NOTHING or LOG_LEVEL_CRIT from the
    // module:
    if (log_level < LOG_LEVEL_ERR)
    {
        assert((log_level == LOG_LEVEL_NOTHING) || (log_level == LOG_LEVEL_CRIT));
        return LogLevelToString(LOG_LEVEL_ERR);
    }
    return LogLevelToString(log_level);
}

static bool PromiseModule_Validate(PromiseModule *module, const EvalContext *ctx, const Promise *pp)
{
    assert(module != NULL);
    assert(pp != NULL);

    const char *const promise_type = PromiseGetPromiseType(pp);
    const char *const promiser = pp->promiser;

    const char *action_policy = PromiseGetConstraintAsRval(pp, "action_policy", RVAL_TYPE_SCALAR);
    const bool dontdo = ((EVAL_MODE != EVAL_MODE_NORMAL) ||
                         StringEqual(action_policy, "warn") || StringEqual(action_policy, "nop"));
    if (dontdo && !module->action_policy)
    {
        Log(LOG_LEVEL_ERR,
            "Not making changes to the system, but the custom promise module '%s' doesn't support action_policy",
            module->path);
        return false;
    }

    PromiseModule_AppendString(module, "operation", "validate_promise");
    PromiseModule_AppendString(module, "log_level", LogLevelToRequestFromModule(pp));
    PromiseModule_AppendString(module, "promise_type", promise_type);
    PromiseModule_AppendString(module, "promiser", promiser);
    PromiseModule_AppendInteger(module, "line_number", pp->offset.line);
    PromiseModule_AppendString(module, "filename", PromiseGetBundle(pp)->source_path);
    PromiseModule_AppendAllAttributes(module, ctx, pp);
    PromiseModule_Send(module);

    // Prints errors / log messages from module:
    uint16_t n_log_msgs[LOG_LEVEL_DEBUG + 1] = {0};
    JsonElement *response = PromiseModule_Receive(module, pp, n_log_msgs);

    if (response == NULL)
    {
        // Error already printed in PromiseModule_Receive()
        return false;
    }

    const bool valid = HasResultAndResultIsValid(response);

    JsonDestroy(response);

    if (!valid)
    {
        // Detailed error messages from module should already have been printed
        const char *const filename =
            pp->parent_section->parent_bundle->source_path;
        const size_t line = pp->offset.line;
        Log(LOG_LEVEL_VERBOSE,
            "%s promise with promiser '%s' failed validation (%s:%zu)",
            promise_type,
            promiser,
            filename,
            line);

        if ((n_log_msgs[LOG_LEVEL_ERR] == 0) && (n_log_msgs[LOG_LEVEL_CRIT] == 0))
        {
            Log(LOG_LEVEL_CRIT,
                "Bug in promise module - No error(s) logged for invalid %s promise with promiser '%s' (%s:%zu)",
                promise_type,
                promiser,
                filename,
                line);
        }
    }

    return valid;
}

static PromiseResult PromiseModule_Evaluate(
    PromiseModule *module, EvalContext *ctx, const Promise *pp)
{
    assert(module != NULL);
    assert(pp != NULL);

    const char *const promise_type = PromiseGetPromiseType(pp);
    const char *const promiser = pp->promiser;

    PromiseModule_AppendString(module, "operation", "evaluate_promise");
    PromiseModule_AppendString(
        module, "log_level", LogLevelToRequestFromModule(pp));
    PromiseModule_AppendString(module, "promise_type", promise_type);
    PromiseModule_AppendString(module, "promiser", promiser);
    PromiseModule_AppendInteger(module, "line_number", pp->offset.line);
    PromiseModule_AppendString(module, "filename", PromiseGetBundle(pp)->source_path);

    PromiseModule_AppendAllAttributes(module, ctx, pp);
    PromiseModule_Send(module);

    const char *action_policy = PromiseGetConstraintAsRval(pp, "action_policy", RVAL_TYPE_SCALAR);
    const bool dontdo = ((EVAL_MODE != EVAL_MODE_NORMAL) ||
                         StringEqual(action_policy, "warn") || StringEqual(action_policy, "nop"));

    uint16_t n_log_msgs[LOG_LEVEL_DEBUG + 1] = {0};
    JsonElement *response = PromiseModule_Receive(module, pp, n_log_msgs);
    if (response == NULL)
    {
        // Log from PromiseModule_Receive
        return PROMISE_RESULT_FAIL;
    }

    JsonElement *result_classes = JsonObjectGetAsArray(response, "result_classes");
    if (result_classes != NULL)
    {
        const size_t n_classes = JsonLength(result_classes);
        for (size_t i = 0; i < n_classes; i++)
        {
            const char *class_name = JsonArrayGetAsString(result_classes, i);
            assert(class_name != NULL);
            EvalContextClassPutSoft(ctx, class_name, CONTEXT_SCOPE_BUNDLE, "source=promise-module");
        }
    }

    PromiseResult result;
    const char *const result_str = JsonObjectGetAsString(response, "result");

    /* Attributes needed for setting outcome classes etc. */
    Attributes a = GetClassContextAttributes(ctx, pp);

    const char *const filename = pp->parent_section->parent_bundle->source_path;
    const size_t line = pp->offset.line;

    if (dontdo && (n_log_msgs[LOG_LEVEL_INFO] > 0))
    {
        Log(LOG_LEVEL_CRIT,
            "Bug in promise module - 'info:' log messages reported for %s promise with promiser '%s' (%s:%zu)"
            " while making changes on the system disabled",
            promise_type,
            promiser,
            filename,
            line);
    }

    if (result_str == NULL)
    {
        result = PROMISE_RESULT_FAIL;
        cfPS(
            ctx,
            LOG_LEVEL_ERR,
            result,
            pp,
            &a,
            "Promise module did not return a result for promise evaluation (%s promise, promiser: '%s' module: '%s')",
            promise_type,
            promiser,
            module->path);
    }
    else if (StringEqual(result_str, "kept"))
    {
        result = PROMISE_RESULT_NOOP;
        cfPS(
            ctx,
            LOG_LEVEL_VERBOSE,
            result,
            pp,
            &a,
            "Promise with promiser '%s' was kept by promise module '%s'",
            promiser,
            module->path);
    }
    else if (StringEqual(result_str, "not_kept"))
    {
        result = PROMISE_RESULT_FAIL;
        cfPS(
            ctx,
            LOG_LEVEL_VERBOSE,
            result,
            pp,
            &a,
            "Promise with promiser '%s' was not kept by promise module '%s'",
            promiser,
            module->path);

        if (!dontdo && (n_log_msgs[LOG_LEVEL_ERR] == 0) && (n_log_msgs[LOG_LEVEL_CRIT] == 0))
        {
            Log(LOG_LEVEL_CRIT,
                "Bug in promise module - Failed to log errors for not kept %s promise with promiser '%s' (%s:%zu)",
                promise_type,
                promiser,
                filename,
                line);
        }
        else if (dontdo &&
                 ((n_log_msgs[LOG_LEVEL_WARNING] + n_log_msgs[LOG_LEVEL_ERR] + n_log_msgs[LOG_LEVEL_CRIT]) == 0))
        {
            Log(LOG_LEVEL_CRIT,
                "Bug in promise module - Failed to log warnings for not kept %s promise with promiser '%s' (%s:%zu)"
                " while making changes on the system disabled",
                promise_type,
                promiser,
                filename,
                line);
        }
    }
    else if (StringEqual(result_str, "repaired"))
    {
        result = PROMISE_RESULT_CHANGE;
        cfPS(
            ctx,
            LOG_LEVEL_VERBOSE,
            result,
            pp,
            &a,
            "Promise with promiser '%s' was repaired by promise module '%s'",
            promiser,
            module->path);

        if (dontdo)
        {
            Log(LOG_LEVEL_CRIT,
                "Bug in promise module - %s promise with promiser '%s' (%s:%zu)"
                " repaired while making changes on the system disabled",
                promise_type,
                promiser,
                filename,
                line);
        }

        if (n_log_msgs[LOG_LEVEL_INFO] == 0)
        {
            Log(LOG_LEVEL_CRIT,
                "Bug in promise module - Failed to log about changes made by a repaired %s promise with promiser '%s' (%s:%zu)",
                promise_type,
                promiser,
                filename,
                line);
        }
    }
    else if (StringEqual(result_str, "error"))
    {
        result = PROMISE_RESULT_FAIL;
        cfPS(
            ctx,
            LOG_LEVEL_ERR,
            result,
            pp,
            &a,
            "An unexpected error occured in promise module (%s promise, promiser: '%s' module: '%s')",
            promise_type,
            promiser,
            module->path);
    }
    else
    {
        result = PROMISE_RESULT_FAIL;
        cfPS(
            ctx,
            LOG_LEVEL_ERR,
            result,
            pp,
            &a,
            "Promise module returned unacceptable result: '%s' (%s promise, promiser: '%s' module: '%s')",
            result_str,
            promise_type,
            promiser,
            module->path);
    }

    JsonDestroy(response);
    return result;
}

static void PromiseModule_Terminate(PromiseModule *module, const Promise *pp)
{
    if (module != NULL)
    {
        PromiseModule_AppendString(module, "operation", "terminate");
        PromiseModule_Send(module);

        uint16_t n_log_msgs[LOG_LEVEL_DEBUG + 1] = {0};
        JsonElement *response = PromiseModule_Receive(module, pp, n_log_msgs);
        JsonDestroy(response);

        PromiseModule_DestroyInternal(module);
    }
}

static void PromiseModule_Terminate_untyped(void *data)
{
    PromiseModule *module = data;
    PromiseModule_Terminate(module, NULL);
}

void TerminateCustomPromises(void)
{
    MapIterator iter = MapIteratorInit(custom_modules);

    for (const MapKeyValue *item = MapIteratorNext(&iter); item != NULL; item = MapIteratorNext(&iter))
    {
        const char *const path = item->key;
        const PromiseModule *const module = item->value;

        if (!GracefulTerminate(module->pid, module->process_start_time))
        {
            Log(LOG_LEVEL_ERR, "Failed to terminate custom promise module '%s'", path);
        }
    }
}

bool InitializeCustomPromises()
{
    /* module_path -> PromiseModule map */
    custom_modules = MapNew(StringHash_untyped,
                            StringEqual_untyped,
                            free,
                            PromiseModule_Terminate_untyped);
    assert(custom_modules != NULL);

    return (custom_modules != NULL);
}

void FinalizeCustomPromises()
{
    MapDestroy(custom_modules);
}

PromiseResult EvaluateCustomPromise(EvalContext *ctx, const Promise *pp)
{
    assert(ctx != NULL);
    assert(pp != NULL);

    Body *promise_block = FindCustomPromiseType(pp);
    if (promise_block == NULL)
    {
        Log(LOG_LEVEL_ERR,
            "Undefined promise type '%s'",
            PromiseGetPromiseType(pp));
        return PROMISE_RESULT_FAIL;
    }

    /* Attributes needed for setting outcome classes etc. */
    Attributes a = GetClassContextAttributes(ctx, pp);

    char *interpreter = NULL;
    char *path = NULL;

    bool success = GetInterpreterAndPath(ctx, promise_block, &interpreter, &path);

    if (!success)
    {
        assert(interpreter == NULL && path == NULL);
        /* Details logged in GetInterpreterAndPath() */
        cfPS(ctx, LOG_LEVEL_NOTHING, PROMISE_RESULT_FAIL, pp, &a, NULL);
        return PROMISE_RESULT_FAIL;
    }

    /* Used below, constructed here while path and interpreter are definitely
     * valid pointers. */
    char custom_promise_id[CF_BUFSIZE];
    NDEBUG_UNUSED size_t ret = snprintf(custom_promise_id,
                                        sizeof(custom_promise_id),
                                        "%s-%s-%s", pp->promiser, path,
                                        interpreter ? interpreter : "(null)");
    assert((ret > 0) && (ret < sizeof(custom_promise_id)));

    PromiseModule *module = MapGet(custom_modules, path);
    if (module == NULL)
    {
        /* Takes ownership of interpreter and path. */
        module = PromiseModule_Start(interpreter, path);
        if (module != NULL)
        {
            MapInsert(custom_modules, xstrdup(path), module);
        }
        else
        {
            free(interpreter);
            free(path);
            // Error logged in PromiseModule_Start()
            cfPS(ctx, LOG_LEVEL_NOTHING, PROMISE_RESULT_FAIL, pp, &a, NULL);
            return PROMISE_RESULT_FAIL;
        }
    }
    else
    {
        if (!StringEqual(interpreter, module->interpreter))
        {
            Log(LOG_LEVEL_ERR, "Conflicting interpreter specifications for custom promise module '%s'"
                " (started with '%s' and '%s' requested for promise '%s' of type '%s')",
                path, module->interpreter, interpreter, pp->promiser, PromiseGetPromiseType(pp));
            free(interpreter);
            free(path);
            cfPS(ctx, LOG_LEVEL_NOTHING, PROMISE_RESULT_FAIL, pp, &a, NULL);
            return PROMISE_RESULT_FAIL;
        }
        free(interpreter);
        free(path);
    }

    // TODO: Do validation earlier (cf-promises --full-check)
    bool valid = CustomPromise_IsFullyResolved(ctx, pp, module->json);
    if ((!valid) && (EvalContextGetPass(ctx) == CF_DONEPASSES - 1))
    {
        Log(LOG_LEVEL_ERR,
            "%s promise with promiser '%s' has unresolved/unexpanded variables",
            PromiseGetPromiseType(pp),
            pp->promiser);
    }

    CfLock promise_lock = AcquireLock(ctx, custom_promise_id, VUQNAME, CFSTARTTIME,
                                      a.transaction.ifelapsed, a.transaction.expireafter,
                                      pp, false);
    if (promise_lock.lock == NULL)
    {
        return PROMISE_RESULT_SKIPPED;
    }

    if (valid)
    {
        valid = PromiseModule_Validate(module, ctx, pp);
    }

    PromiseResult result;
    if (valid)
    {
        result = PromiseModule_Evaluate(module, ctx, pp);
    }
    else
    {
        // PromiseModule_Validate() already printed an error
        Log(LOG_LEVEL_VERBOSE,
            "%s promise with promiser '%s' will be skipped because it failed validation",
            PromiseGetPromiseType(pp),
            pp->promiser);
        cfPS(ctx, LOG_LEVEL_NOTHING, PROMISE_RESULT_FAIL, pp, &a, NULL);
        result = PROMISE_RESULT_FAIL; // TODO: Investigate if DENIED is more
                                      // appropriate
    }

    YieldCurrentLock(promise_lock);
    return result;
}