File: cf-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 (527 lines) | stat: -rw-r--r-- 18,674 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
/*
  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 <platform.h>
#include <getopt.h>

#include <generic_agent.h>

#include <eval_context.h>
#include <conversion.h>
#include <syntax.h>
#include <rlist.h>
#include <parser.h>
#include <known_dirs.h>
#include <man.h>
#include <bootstrap.h>
#include <string_lib.h>
#include <file_lib.h>                                     /* FILE_SEPARATOR */
#include <loading.h>
#include <regex.h>                                        /* CompileRegex */
#include <match_scope.h>
#include <cleanup.h>

#include <time.h>

static GenericAgentConfig *CheckOpts(int argc, char **argv);

/*******************************************************************/
/* Command line options                                            */
/*******************************************************************/

static const char *const CF_PROMISES_SHORT_DESCRIPTION =
    "validate and analyze CFEngine policy code";

static const char *const CF_PROMISES_MANPAGE_LONG_DESCRIPTION = "cf-promises is a tool for checking CFEngine policy code. "
    "It operates by first parsing policy code checing for syntax errors. Second, it validates the integrity of "
    "policy consisting of multiple files. Third, it checks for semantic errors, e.g. specific attribute set rules. "
    "Finally, cf-promises attempts to expose errors by partially evaluating the policy, resolving as many variable and "
    "classes promise statements as possible. At no point does cf-promises make any changes to the system.";

static const Component COMPONENT =
{
    .name = "cf-promises",
    .website = CF_WEBSITE,
    .copyright = CF_COPYRIGHT
};

/* Long-style only options, values must start above max ASCII value. */
enum
{
    OPT_EVAL_FUNCTIONS = 256,
    OPT_SHOW_CLASSES,
    OPT_SHOW_VARS
};

static const struct option OPTIONS[] =
{
    {"workdir", required_argument, 0, 'w'},
    {"eval-functions", optional_argument, 0, OPT_EVAL_FUNCTIONS },
    {"show-classes", optional_argument, 0, OPT_SHOW_CLASSES },
    {"show-vars", optional_argument, 0, OPT_SHOW_VARS },
    {"help", no_argument, 0, 'h'},
    {"bundlesequence", required_argument, 0, 'b'},
    {"debug", no_argument, 0, 'd'},
    {"verbose", no_argument, 0, 'v'},
    {"log-level", required_argument, 0, 'g'},
    {"dry-run", no_argument, 0, 'n'},
    {"version", no_argument, 0, 'V'},
    {"file", required_argument, 0, 'f'},
    {"define", required_argument, 0, 'D'},
    {"negate", required_argument, 0, 'N'},
    {"inform", no_argument, 0, 'I'},
    {"diagnostic", no_argument, 0, 'x'},
    {"policy-output-format", required_argument, 0, 'p'},
    {"syntax-description", required_argument, 0, 's'},
    {"full-check", no_argument, 0, 'c'},
    {"warn", required_argument, 0, 'W'},
    {"color", optional_argument, 0, 'C'},
    {"tag-release", required_argument, 0, 'T'},
    {"timestamp", no_argument, 0, 'l'},
    /* Only long option for the rest */
    {"ignore-preferred-augments", no_argument, 0, 0},
    {"log-modules", required_argument, 0, 0},
    {NULL, 0, 0, '\0'}
};

static const char *const HINTS[] =
{
    "Override the work directory for testing (same as setting CFENGINE_TEST_OVERRIDE_WORKDIR)",
    "Evaluate functions during syntax checking (may catch more run-time errors). Possible values: 'yes', 'no'. Default is 'yes'",
    "Show discovered classes, including those defined in common bundles in policy. Optionally can take a regular expression.",
    "Show discovered variables, including those defined without dependency to user-defined classes in policy. Optionally can take a regular expression.",
    "Print the help message",
    "Use the specified bundlesequence for verification",
    "Enable debugging output",
    "Output verbose information about the behaviour of cf-promises",
    "Specify how detailed logs should be. Possible values: 'error', 'warning', 'notice', 'info', 'verbose', 'debug'",
    "All talk and no action mode - make no changes, only inform of promises not kept",
    "Output the version of the software",
    "Specify an alternative input file than the default. This option is overridden by FILE if supplied as argument.",
    "Define a list of comma separated classes to be defined at the start of execution",
    "Define a list of comma separated classes to be undefined at the start of execution",
    "Print basic information about changes made to the system, i.e. promises repaired",
    "Activate internal diagnostics (developers only)",
    "Output the parsed policy. Possible values: 'none', 'cf', 'json' (this file only), 'cf-full', 'json-full' (all parsed promises). Default is 'none'. (experimental)",
    "Output a document describing the available syntax elements of CFEngine. Possible values: 'none', 'json'. Default is 'none'.",
    "Ensure full policy integrity checks",
    "Pass comma-separated <warnings>|all to enable non-default warnings, or error=<warnings>|all",
    "Enable colorized output. Possible values: 'always', 'auto', 'never'. If option is used, the default value is 'auto'",
    "Tag a directory with promises.cf with cf_promises_validated and cf_promises_release_id",
    "Log timestamps on each line of log output",
    "Ignore def_preferred.json file in favor of def.json",
    "Enable even more detailed debug logging for specific areas of the implementation. Use together with '-d'. Use --log-modules=help for a list of available modules",
    NULL
};

/*******************************************************************/
/* Level 0 : Main                                                  */
/*******************************************************************/

int main(int argc, char *argv[])
{
    SetupSignalsForAgent();

    GenericAgentConfig *config = CheckOpts(argc, argv);

    EvalContext *ctx = EvalContextNew();
    GenericAgentConfigApply(ctx, config);

    const char *program_invocation_name = argv[0];
    const char *last_dir_sep = strrchr(program_invocation_name, FILE_SEPARATOR);
    const char *program_name = (last_dir_sep != NULL ? last_dir_sep + 1 : program_invocation_name);
    GenericAgentDiscoverContext(ctx, config, program_name);

    Policy *policy = LoadPolicy(ctx, config);
    if (!policy)
    {
        Log(LOG_LEVEL_ERR, "Input files contain errors.");
        DoCleanupAndExit(EXIT_FAILURE);
    }

    GenericAgentPostLoadInit(ctx);

    if (config->tag_release_dir != NULL)
    {
        // write the validated file and the release ID
        bool tagged = GenericAgentTagReleaseDirectory(config, config->tag_release_dir, true, true);
        if (tagged)
        {
            Log(LOG_LEVEL_VERBOSE, "Release tagging done!");
        }
        else
        {
            Log(LOG_LEVEL_ERR, "The given directory could not be tagged, sorry.");
            DoCleanupAndExit(EXIT_FAILURE);
        }
    }

    const enum generic_agent_config_common_policy_output_format
        output_format = config->agent_specific.common.policy_output_format;

    switch (output_format)
    {
    case GENERIC_AGENT_CONFIG_COMMON_POLICY_OUTPUT_FORMAT_CF_FULL:
    {
        Writer *writer = FileWriter(stdout);
        PolicyToString(policy, writer);
        WriterClose(writer);
        break;
    }

    case GENERIC_AGENT_CONFIG_COMMON_POLICY_OUTPUT_FORMAT_JSON_FULL:
    {
        Writer *writer = FileWriter(stdout);
        JsonElement *json_policy = PolicyToJson(policy);
        JsonWrite(writer, json_policy, 2);
        JsonDestroy(json_policy);
        WriterClose(writer);
        break;
    }

    case GENERIC_AGENT_CONFIG_COMMON_POLICY_OUTPUT_FORMAT_CF:
    case GENERIC_AGENT_CONFIG_COMMON_POLICY_OUTPUT_FORMAT_JSON:
    {
        // If no file was provided, use 'promises.cf' by default
        if (config->input_file == NULL)
        {
            GenericAgentConfigSetInputFile(config, GetInputDir(),
                                           "promises.cf");
        }

        Policy *output_policy = Cf3ParseFile(config, config->input_file);
        CF_ASSERT_FIX(output_policy != NULL, DoCleanupAndExit(EXIT_FAILURE),
                      "File has already been parsed OK, but fails now!");

        Writer *writer = FileWriter(stdout);
        if (output_format == GENERIC_AGENT_CONFIG_COMMON_POLICY_OUTPUT_FORMAT_CF)
        {
            PolicyToString(output_policy, writer);
        }
        else
        {
            JsonElement *json_policy = PolicyToJson(output_policy);
            JsonWrite(writer, json_policy, 2);
            JsonDestroy(json_policy);
        }
        WriterClose(writer);
        PolicyDestroy(output_policy);
        break;
    }

    /* Avoids warnings. */
    case GENERIC_AGENT_CONFIG_COMMON_POLICY_OUTPUT_FORMAT_NONE:
        break;
    }

    if (config->agent_specific.common.show_classes != NULL)
    {
        GenericAgentShowContextsFormatted(ctx, config->agent_specific.common.show_classes);
        free(config->agent_specific.common.show_classes);
    }

    if (config->agent_specific.common.show_variables != NULL)
    {
        GenericAgentShowVariablesFormatted(ctx, config->agent_specific.common.show_variables);
        free(config->agent_specific.common.show_variables);
    }

    PolicyDestroy(policy);
    GenericAgentFinalize(ctx, config);
}


/*******************************************************************/
/* Level 1                                                         */
/*******************************************************************/

GenericAgentConfig *CheckOpts(int argc, char **argv)
{
    extern char *optarg;
    int c;
    GenericAgentConfig *config = GenericAgentConfigNewDefault(AGENT_TYPE_COMMON, GetTTYInteractive());

    int longopt_idx;
    while ((c = getopt_long(argc, argv, "dvnIw:f:g:D:N:VSrxMb:i:p:s:cg:hW:C::T:l",
                            OPTIONS, &longopt_idx))
           != -1)
    {
        switch (c)
        {
        case OPT_EVAL_FUNCTIONS:
            if (optarg == NULL)
            {
                optarg = "yes";
            }
            config->agent_specific.common.eval_functions = strcmp("yes", optarg) == 0;
            break;

        case OPT_SHOW_CLASSES:
            if (optarg == NULL)
            {
                optarg = ".*";
            }
            config->agent_specific.common.show_classes = xstrdup(optarg);
            break;

        case OPT_SHOW_VARS:
            if (optarg == NULL)
            {
                optarg = ".*";
            }
            config->agent_specific.common.show_variables = xstrdup(optarg);
            break;

        case 'w':
        {
            Log(LOG_LEVEL_INFO, "Setting workdir to '%s'", optarg);
            char *str = StringConcatenate(2, "CFENGINE_TEST_OVERRIDE_WORKDIR=", optarg);
            putenv_wrapper(str);
            free(str);
            break;
        }

        case 'c':
            config->check_runnable = true;
            break;

        case 'f':
            GenericAgentConfigSetInputFile(config, GetInputDir(), optarg);
            MINUSF = true;
            break;

        case 'd':
            LogSetGlobalLevel(LOG_LEVEL_DEBUG);
            break;

        case 'g':
            LogSetGlobalLevelArgOrExit(optarg);
            break;

        case 'b':
            if (optarg)
            {
                Rlist *bundlesequence = RlistFromSplitString(optarg, ',');
                GenericAgentConfigSetBundleSequence(config, bundlesequence);
                RlistDestroy(bundlesequence);
            }
            break;

        case 'p':
            if (strcmp("none", optarg) == 0)
            {
                config->agent_specific.common.policy_output_format = GENERIC_AGENT_CONFIG_COMMON_POLICY_OUTPUT_FORMAT_NONE;
            }
            else if (strcmp("cf", optarg) == 0)
            {
                config->agent_specific.common.policy_output_format = GENERIC_AGENT_CONFIG_COMMON_POLICY_OUTPUT_FORMAT_CF;
            }
            else if (strcmp("json", optarg) == 0)
            {
                config->agent_specific.common.policy_output_format = GENERIC_AGENT_CONFIG_COMMON_POLICY_OUTPUT_FORMAT_JSON;
            }
             else if (strcmp("cf-full", optarg) == 0)
            {
                config->agent_specific.common.policy_output_format = GENERIC_AGENT_CONFIG_COMMON_POLICY_OUTPUT_FORMAT_CF_FULL;
            }
            else if (strcmp("json-full", optarg) == 0)
            {
                config->agent_specific.common.policy_output_format = GENERIC_AGENT_CONFIG_COMMON_POLICY_OUTPUT_FORMAT_JSON_FULL;
            }
            else
            {
                Log(LOG_LEVEL_ERR, "Invalid policy output format: '%s'. Possible values are 'none', 'cf', 'json', 'cf-full', 'json-full'", optarg);
                DoCleanupAndExit(EXIT_FAILURE);
            }
            break;

        case 's':
            if (strcmp("none", optarg) == 0)
            {
                break;
            }
            else if (strcmp("json", optarg) == 0)
            {
                JsonElement *json_syntax = SyntaxToJson();
                Writer *out = FileWriter(stdout);
                JsonWrite(out, json_syntax, 0);
                FileWriterDetach(out);
                JsonDestroy(json_syntax);
                DoCleanupAndExit(EXIT_SUCCESS);
            }
            else
            {
                Log(LOG_LEVEL_ERR, "Invalid syntax description output format: '%s'. Possible values are 'none', 'json'", optarg);
                DoCleanupAndExit(EXIT_FAILURE);
            }
            break;

        case 'K':
            config->ignore_locks = true;
            break;

        case 'D':
            {
                StringSet *defined_classes = StringSetFromString(optarg, ',');
                if (! config->heap_soft)
                {
                    config->heap_soft = defined_classes;
                }
                else
                {
                    StringSetJoin(config->heap_soft, defined_classes, xstrdup);
                    StringSetDestroy(defined_classes);
                }
            }
            break;

        case 'N':
            {
                StringSet *negated_classes = StringSetFromString(optarg, ',');
                if (! config->heap_negated)
                {
                    config->heap_negated = negated_classes;
                }
                else
                {
                    StringSetJoin(config->heap_negated, negated_classes, xstrdup);
                    StringSetDestroy(negated_classes);
                }
            }
            break;

        case 'I':
            LogSetGlobalLevel(LOG_LEVEL_INFO);
            break;

        case 'v':
            LogSetGlobalLevel(LOG_LEVEL_VERBOSE);
            break;

        case 'n':
            EVAL_MODE = EVAL_MODE_DRY_RUN;
            config->ignore_locks = true;
            break;

        case 'V':
        {
            Writer *w = FileWriter(stdout);
            GenericAgentWriteVersion(w);
            FileWriterDetach(w);
        }
        DoCleanupAndExit(EXIT_SUCCESS);

        case 'h':
        {
            Writer *w = FileWriter(stdout);
            WriterWriteHelp(w, &COMPONENT, OPTIONS, HINTS, NULL, false, true);
            FileWriterDetach(w);
        }
        DoCleanupAndExit(EXIT_SUCCESS);

        case 'M':
        {
            Writer *out = FileWriter(stdout);
            ManPageWrite(out, "cf-promises", time(NULL),
                         CF_PROMISES_SHORT_DESCRIPTION,
                         CF_PROMISES_MANPAGE_LONG_DESCRIPTION,
                         OPTIONS, HINTS,
                         NULL, false,
                         true);
            FileWriterDetach(out);
            DoCleanupAndExit(EXIT_SUCCESS);
        }

        case 'r':
            Log(LOG_LEVEL_ERR, "Option '-r' has been deprecated");
            DoCleanupAndExit(EXIT_FAILURE);
            break;

        case 'W':
            if (!GenericAgentConfigParseWarningOptions(config, optarg))
            {
                Log(LOG_LEVEL_ERR, "Error parsing warning option");
                DoCleanupAndExit(EXIT_FAILURE);
            }
            break;

        case 'x':
            Log(LOG_LEVEL_ERR, "Self-diagnostic functionality is retired.");
            DoCleanupAndExit(EXIT_SUCCESS);

        case 'C':
            if (!GenericAgentConfigParseColor(config, optarg))
            {
                DoCleanupAndExit(EXIT_FAILURE);
            }
            break;

        case 'T':
            GenericAgentConfigSetInputFile(config, optarg, "promises.cf");
            MINUSF = true;
            config->tag_release_dir = xstrdup(optarg);
            break;

        case 'l':
            LoggingEnableTimestamps(true);
            break;

        /* long options only */
        case 0:
        {
            const char *const option_name = OPTIONS[longopt_idx].name;
            if (StringEqual(option_name, "ignore-preferred-augments"))
            {
                config->ignore_preferred_augments = true;
            }
            else if (StringEqual(option_name, "log-modules"))
            {
                bool ret = LogEnableModulesFromString(optarg);
                if (!ret)
                {
                    DoCleanupAndExit(EXIT_FAILURE);
                }
            }
            break;
        }
        default:
        {
            Writer *w = FileWriter(stdout);
            WriterWriteHelp(w, &COMPONENT, OPTIONS, HINTS, NULL, false, true);
            FileWriterDetach(w);
        }
        DoCleanupAndExit(EXIT_FAILURE);

        }
    }

    if (!GenericAgentConfigParseArguments(config, argc - optind, argv + optind))
    {
        Log(LOG_LEVEL_ERR, "Too many arguments");
        DoCleanupAndExit(EXIT_FAILURE);
    }

    CallCleanupFunctions();
    return config;
}