-
Notifications
You must be signed in to change notification settings - Fork 188
/
Copy pathcf-agent.c
2352 lines (2010 loc) · 75.2 KB
/
cf-agent.c
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
/*
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 <actuator.h>
#include <audit.h>
#include <cleanup.h>
#include <eval_context.h>
#include <verify_classes.h>
#include <verify_databases.h>
#include <verify_environments.h>
#include <verify_exec.h>
#include <verify_methods.h>
#include <verify_processes.h>
#include <verify_packages.h>
#include <verify_users.h>
#include <verify_services.h>
#include <verify_storage.h>
#include <verify_files.h>
#include <verify_files_utils.h>
#include <verify_vars.h>
#include <addr_lib.h>
#include <files_names.h>
#include <files_interfaces.h>
#include <files_repository.h>
#include <files_edit.h>
#include <files_properties.h>
#include <item_lib.h>
#include <vars.h>
#include <conversion.h>
#include <expand.h>
#include <locks.h>
#include <scope.h>
#include <matching.h>
#include <match_scope.h>
#include <instrumentation.h>
#include <promises.h>
#include <unix.h>
#include <attributes.h>
#include <communication.h>
#include <signals.h>
#include <nfs.h>
#include <processes_select.h>
#include <list.h>
#include <fncall.h>
#include <rlist.h>
#include <agent-diagnostics.h>
#include <known_dirs.h>
#include <cf-agent-enterprise-stubs.h>
#include <syslog_client.h>
#include <man.h>
#include <bootstrap.h>
#include <policy_server.h>
#include <misc_lib.h>
#include <buffer.h>
#include <loading.h>
#include <conn_cache.h> /* ConnCache_Init,ConnCache_Destroy */
#include <net.h>
#include <package_module.h>
#include <string_lib.h>
#include <cfnet.h>
#include <repair.h>
#include <dbm_api.h> /* CheckDBRepairFlagFile() */
#include <sys/types.h> /* checking umask on writing setxid log */
#include <sys/stat.h> /* checking umask on writing setxid log */
#include <simulate_mode.h> /* ManifestChangedFiles(), DiffChangedFiles() */
#include <ip_address.h>
#include <syntax.h> /* IsBuiltInPromiseType() */
#include <mod_common.h>
#include <mod_custom.h> /* EvaluateCustomPromise(), Intialize/FinalizeCustomPromises() */
#ifdef HAVE_AVAHI_CLIENT_CLIENT_H
#ifdef HAVE_AVAHI_COMMON_ADDRESS_H
#include <findhub.h>
#endif
#endif
#include <ornaments.h>
extern int PR_KEPT;
extern int PR_REPAIRED;
extern int PR_NOTKEPT;
static bool ALLCLASSESREPORT = false; /* GLOBAL_P */
static bool ALWAYS_VALIDATE = false; /* GLOBAL_P */
static bool CFPARANOID = false; /* GLOBAL_P */
static bool PERFORM_DB_CHECK = false;
static const Rlist *ACCESSLIST = NULL; /* GLOBAL_P */
static int CFA_BACKGROUND = 0; /* GLOBAL_X */
static int CFA_BACKGROUND_LIMIT = 1; /* GLOBAL_P */
static Item *PROCESSREFRESH = NULL; /* GLOBAL_P */
static const char *const AGENT_TYPESEQUENCE[] =
{
"meta",
"vars",
"defaults",
"classes", /* Maelstrom order 2 */
"users",
"files",
"packages",
"guest_environments",
"methods",
"processes",
"services",
"commands",
"storage",
"databases",
"reports",
NULL
};
/*******************************************************************/
/* Agent specific variables */
/*******************************************************************/
static void ThisAgentInit(void);
static GenericAgentConfig *CheckOpts(int argc, char **argv);
static char **TranslateOldBootstrapOptionsSeparate(int *argc_new, char **argv);
static char **TranslateOldBootstrapOptionsConcatenated(int argc, char **argv);
static void FreeFixedStringArray(int size, char **array);
static void CheckAgentAccess(const Rlist *list, const Policy *policy);
static void KeepControlPromises(EvalContext *ctx, const Policy *policy, GenericAgentConfig *config);
static PromiseResult KeepAgentPromise(EvalContext *ctx, const Promise *pp, void *param);
static void NewTypeContext(TypeSequence type);
static void DeleteTypeContext(EvalContext *ctx, TypeSequence type);
static PromiseResult ParallelFindAndVerifyFilesPromises(EvalContext *ctx, const Promise *pp);
static bool VerifyBootstrap(bool skip_cf_execd_check);
static void KeepPromiseBundles(EvalContext *ctx, const Policy *policy, GenericAgentConfig *config);
static void KeepPromises(EvalContext *ctx, const Policy *policy, GenericAgentConfig *config);
static int NoteBundleCompliance(const Bundle *bundle, int save_pr_kept, int save_pr_repaired, int save_pr_notkept, struct timespec start);
static void AllClassesReport(const EvalContext *ctx);
static bool HasAvahiSupport(void);
static int AutomaticBootstrap(GenericAgentConfig *config);
static void BannerStatus(PromiseResult status, const char *type, char *name);
static PromiseResult DefaultVarPromise(EvalContext *ctx, const Promise *pp);
static void WaitForBackgroundProcesses();
/*******************************************************************/
/* Command line options */
/*******************************************************************/
static const char *const CF_AGENT_SHORT_DESCRIPTION =
"evaluate CFEngine policy code and actuate change to the system.";
static const char *const CF_AGENT_MANPAGE_LONG_DESCRIPTION =
"cf-agent evaluates policy code and makes changes to the system. Policy bundles are evaluated in the order of the "
"provided bundlesequence (this is normally specified in the common control body). "
"For each bundle, cf-agent groups promise statements according to their type. Promise types are then evaluated in a preset "
"order to ensure fast system convergence to policy.\n";
static const Component COMPONENT =
{
.name = "cf-agent",
.website = CF_WEBSITE,
.copyright = CF_COPYRIGHT
};
static const struct option OPTIONS[] =
{
{"bootstrap", required_argument, 0, 'B'},
{"bundlesequence", required_argument, 0, 'b'},
{"workdir", required_argument, 0, 'w'},
{"debug", no_argument, 0, 'd'},
{"define", required_argument, 0, 'D'},
{"self-diagnostics", optional_argument, 0, 'x'},
{"dry-run", no_argument, 0, 'n'},
{"file", required_argument, 0, 'f'},
{"help", no_argument, 0, 'h'},
{"inform", no_argument, 0, 'I'},
{"log-level", required_argument, 0, 'g'},
{"negate", required_argument, 0, 'N'},
{"no-lock", no_argument, 0, 'K'},
{"verbose", no_argument, 0, 'v'},
{"version", no_argument, 0, 'V'},
{"timing-output", no_argument, 0, 't'},
{"trust-server", optional_argument, 0, 'T'},
{"color", optional_argument, 0, 'C'},
{"no-extensions", no_argument, 0, 'E'},
{"timestamp", no_argument, 0, 'l'},
/* Only long option for the rest */
{"ignore-preferred-augments", no_argument, 0, 0},
{"log-modules", required_argument, 0, 0},
{"no-augments", no_argument, 0, 0},
{"no-host-specific-data", no_argument, 0, 0},
{"show-evaluated-classes", optional_argument, 0, 0 },
{"show-evaluated-vars", optional_argument, 0, 0 },
{"skip-bootstrap-policy-run", no_argument, 0, 0 },
{"skip-bootstrap-service-start", no_argument, 0, 0 },
{"skip-db-check", optional_argument, 0, 0 },
{"simulate", required_argument, 0, 0},
{NULL, 0, 0, '\0'}
};
static const char *const HINTS[] =
{
"Bootstrap CFEngine to the given policy server IP, hostname or :avahi (automatic detection)",
"Set or override bundlesequence from command line",
"Override the default /var/cfengine work directory for testing (same as setting CFENGINE_TEST_OVERRIDE_WORKDIR)",
"Enable debugging output",
"Define a list of comma separated classes to be defined at the start of execution",
"Run checks to diagnose a CFEngine agent installation",
"All talk and no action mode - make no changes, only inform of promises not kept",
"Specify an alternative input file than the default. This option is overridden by FILE if supplied as argument.",
"Print the help message",
"Print basic information about changes made to the system, i.e. promises repaired",
"Specify how detailed logs should be. Possible values: 'error', 'warning', 'notice', 'info', 'verbose', 'debug'",
"Define a list of comma separated classes to be undefined at the start of execution",
"Ignore locking constraints during execution (ifelapsed/expireafter) if \"too soon\" to run",
"Output verbose information about the behaviour of the agent",
"Output the version of the software",
"Output timing information on console when in verbose mode",
"Possible values: 'yes' (default, trust the server when bootstrapping), 'no' (server key must already be trusted)",
"Enable colorized output. Possible values: 'always', 'auto', 'never'. If option is used, the default value is 'auto'",
"Disable extension loading (used while upgrading)",
"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",
"Do not load augments (def.json)",
"Do not load host-specific data (host_specific.json)",
"Show *final* evaluated classes, including those defined in common bundles in policy. Optionally can take a regular expression.",
"Show *final* evaluated variables, including those defined without dependency to user-defined classes in policy. Optionally can take a regular expression.",
"Do not run policy as the last step of the bootstrap process",
"Do not start CFEngine services as part of the bootstrap process",
"Do not run database integrity checks and repairs at startup",
"Run in simulate mode, either 'manifest', 'manifest-full' or 'diff'",
NULL
};
/**
@brief
Wrapper around DefaultVarPromise to silence cast-function-type compiler warning in ScheduleAgentOperations
*/
static PromiseResult DefaultVarPromiseWrapper(EvalContext *ctx, const Promise *pp, void *param) {
UNUSED(param);
return DefaultVarPromise(ctx, pp);
}
/*******************************************************************/
int main(int argc, char *argv[])
{
SetupSignalsForAgent();
#ifdef HAVE_LIBXML2
xmlInitParser();
#endif
struct timespec start = BeginMeasure();
GenericAgentConfig *config = CheckOpts(argc, argv);
bool force_repair = CheckDBRepairFlagFile();
if (force_repair || PERFORM_DB_CHECK)
{
repair_lmdb_default(force_repair);
}
EvalContext *ctx = EvalContextNew();
// Enable only for cf-agent eval context.
EvalContextAllClassesLoggingEnable(ctx, true);
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);
/* FIXME: (CFE-2709) ALWAYS_VALIDATE will always be false here, since it can
* only change in KeepPromises(), five lines later on. */
Policy *policy = SelectAndLoadPolicy(config, ctx, ALWAYS_VALIDATE, true);
if (!policy)
{
Log(LOG_LEVEL_ERR, "Error reading CFEngine policy. Exiting...");
DoCleanupAndExit(EXIT_FAILURE);
}
if ((config->agent_specific.agent.bootstrap_argument != NULL) &&
config->agent_specific.agent.skip_bootstrap_service_start &&
!EvalContextClassPutHard(ctx, "bootstrap_skip_services", "source=environment"))
{
Log(LOG_LEVEL_ERR, "Failed to define the 'bootstrap_skip_services' class");
/* not a fatal issue, let's continue the bootstrap process */
}
int ret = 0;
GenericAgentPostLoadInit(ctx);
ThisAgentInit();
ConnCache_Init();
BeginAudit();
KeepPromises(ctx, policy, config);
if (EvalAborted(ctx))
{
ret = EC_EVAL_ABORTED;
}
ConnCache_Destroy();
if (ALLCLASSESREPORT)
{
AllClassesReport(ctx);
}
Nova_TrackExecution(config->input_file);
/* Update packages cache. */
UpdatePackagesCache(ctx, false);
/* Finalize custom promises before waiting for background processes because
* they can be background processes and need special handling. */
FinalizeCustomPromises();
/* Wait for background processes before generating reports because
* GenerateReports() does nothing if it detects multiple cf-agent processes
* running. */
WaitForBackgroundProcesses();
GenerateReports(config, ctx);
PurgeLocks();
BackupLockDatabase();
if (config->agent_specific.agent.show_evaluated_classes != NULL)
{
GenericAgentShowContextsFormatted(ctx, config->agent_specific.agent.show_evaluated_classes);
free(config->agent_specific.agent.show_evaluated_classes);
}
if (config->agent_specific.agent.show_evaluated_variables != NULL)
{
GenericAgentShowVariablesFormatted(ctx, config->agent_specific.agent.show_evaluated_variables);
free(config->agent_specific.agent.show_evaluated_variables);
}
PolicyDestroy(policy); /* Can we safely do this earlier ? */
if (config->agent_specific.agent.bootstrap_argument &&
!VerifyBootstrap(config->agent_specific.agent.skip_bootstrap_service_start))
{
PolicyServerRemoveFile(GetWorkDir());
WriteAmPolicyHubFile(false);
ret = 1;
}
EndAudit(ctx, CFA_BACKGROUND);
Nova_NoteAgentExecutionPerformance(config->input_file, start);
GenericAgentFinalize(ctx, config);
StringSetDestroy(SINGLE_COPY_CACHE);
StringSet *audited_files = NULL;
if ((EVAL_MODE == EVAL_MODE_SIMULATE_MANIFEST) ||
(EVAL_MODE == EVAL_MODE_SIMULATE_MANIFEST_FULL))
{
bool success = ManifestChangedFiles(&audited_files);
if (!success)
{
Log(LOG_LEVEL_ERR, "Failed to manifest changed files");
}
if (EVAL_MODE == EVAL_MODE_SIMULATE_MANIFEST_FULL)
{
/* Skips the files already manifested above. */
success = ManifestAllFiles(&audited_files);
if (!success)
{
Log(LOG_LEVEL_ERR, "Failed to manifest unmodified files");
}
}
success = ManifestPkgOperations();
if (!success)
{
Log(LOG_LEVEL_ERR, "Failed to manifest present and absent packages");
}
}
else if (EVAL_MODE == EVAL_MODE_SIMULATE_DIFF)
{
bool success = DiffChangedFiles(&audited_files);
if (!success)
{
Log(LOG_LEVEL_ERR, "Failed to show differences for changed files");
}
success = DiffPkgOperations();
if (!success)
{
Log(LOG_LEVEL_ERR, "Failed to show differences in installed packages");
}
}
StringSetDestroy(audited_files);
#ifdef HAVE_LIBXML2
xmlCleanupParser();
#endif
CallCleanupFunctions();
return ret;
}
/*******************************************************************/
/* Level 1 */
/*******************************************************************/
static void ConfigureBootstrap(GenericAgentConfig *config, const char *argument)
{
assert(config != NULL);
if (!BootstrapAllowed())
{
Log(LOG_LEVEL_ERR, "Not enough privileges to bootstrap CFEngine");
DoCleanupAndExit(EXIT_FAILURE);
}
if(strcmp(optarg, ":avahi") == 0)
{
if(!HasAvahiSupport())
{
Log(LOG_LEVEL_ERR, "Avahi support is not built in, please see options to the configure script and rebuild CFEngine");
DoCleanupAndExit(EXIT_FAILURE);
}
int err = AutomaticBootstrap(config);
if (err < 0)
{
Log(LOG_LEVEL_ERR, "Automatic bootstrap failed, error code '%d'", err);
DoCleanupAndExit(EXIT_FAILURE);
}
return;
}
if(StringEqual(argument, "localhost") || StringIsLocalHostIP(argument))
{
Log(LOG_LEVEL_WARNING, "Bootstrapping to loopback interface (localhost), other hosts will not be able to bootstrap to this server");
}
// temporary assure that network functions are working
OpenNetwork();
config->agent_specific.agent.bootstrap_argument = xstrdup(argument);
char *host, *port;
ParseHostPort(optarg, &host, &port);
char ipaddr[CF_MAX_IP_LEN] = "";
if (Hostname2IPString(ipaddr, host,sizeof(ipaddr)) == -1)
{
Log(LOG_LEVEL_ERR,
"Could not resolve hostname '%s', unable to bootstrap",
host);
DoCleanupAndExit(EXIT_FAILURE);
}
CloseNetwork();
MINUSF = true;
config->ignore_locks = true;
GenericAgentConfigSetInputFile(config, GetInputDir(), "promises.cf");
config->agent_specific.agent.bootstrap_ip = xstrdup(ipaddr);
config->agent_specific.agent.bootstrap_host = xstrdup(host);
if (port == NULL)
{
config->agent_specific.agent.bootstrap_port = NULL;
}
else
{
config->agent_specific.agent.bootstrap_port = xstrdup(port);
}
}
static GenericAgentConfig *CheckOpts(int argc, char **argv)
{
extern char *optarg;
int c;
GenericAgentConfig *config = GenericAgentConfigNewDefault(AGENT_TYPE_AGENT, GetTTYInteractive());
bool option_trust_server = false;
;
/* DEPRECATED:
--policy-server (-s) is deprecated in community version 3.5.0.
Support rewrite from some common old bootstrap options (until community version 3.6.0?).
*/
int argc_new = argc;
char **argv_tmp = TranslateOldBootstrapOptionsSeparate(&argc_new, argv);
char **argv_new = TranslateOldBootstrapOptionsConcatenated(argc_new, argv_tmp);
FreeFixedStringArray(argc_new, argv_tmp);
int longopt_idx;
while ((c = getopt_long(argc_new, argv_new, "tdvnKIf:g:w:D:N:VxMB:b:hC::ElT::",
OPTIONS, &longopt_idx))
!= -1)
{
switch (c)
{
case 't':
TIMING = true;
break;
case 'w':
Log(LOG_LEVEL_INFO, "Setting workdir to '%s'", optarg);
setenv_wrapper("CFENGINE_TEST_OVERRIDE_WORKDIR", optarg, 1);
break;
case 'f':
GenericAgentConfigSetInputFile(config, GetInputDir(), optarg);
MINUSF = true;
break;
case 'b':
if (optarg)
{
Rlist *bundlesequence = RlistFromSplitString(optarg, ',');
GenericAgentConfigSetBundleSequence(config, bundlesequence);
RlistDestroy(bundlesequence);
}
break;
case 'd':
LogSetGlobalLevel(LOG_LEVEL_DEBUG);
break;
case 'B':
{
ConfigureBootstrap(config, optarg);
}
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 'g':
LogSetGlobalLevelArgOrExit(optarg);
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-agent", time(NULL),
CF_AGENT_SHORT_DESCRIPTION,
CF_AGENT_MANPAGE_LONG_DESCRIPTION,
OPTIONS, HINTS,
NULL, false,
true);
FileWriterDetach(out);
DoCleanupAndExit(EXIT_SUCCESS);
}
case 'x':
{
const char *workdir = GetWorkDir();
const char *inputdir = GetInputDir();
const char *logdir = GetLogDir();
const char *statedir = GetStateDir();
Writer *out = FileWriter(stdout);
WriterWriteF(out, "self-diagnostics for agent using workdir '%s'\n", workdir);
WriterWriteF(out, "self-diagnostics for agent using inputdir '%s'\n", inputdir);
WriterWriteF(out, "self-diagnostics for agent using logdir '%s'\n", logdir);
WriterWriteF(out, "self-diagnostics for agent using statedir '%s'\n", statedir);
AgentDiagnosticsRun(workdir, AgentDiagnosticsAllChecks(), out);
AgentDiagnosticsRunAllChecksNova(workdir, out, &AgentDiagnosticsRun, &AgentDiagnosticsResultNew);
FileWriterDetach(out);
}
DoCleanupAndExit(EXIT_SUCCESS);
case 'C':
if (!GenericAgentConfigParseColor(config, optarg))
{
DoCleanupAndExit(EXIT_FAILURE);
}
break;
case 'E':
extension_libraries_disable();
break;
case 'l':
LoggingEnableTimestamps(true);
break;
case 'T':
option_trust_server = true;
/* If the argument is missing, we trust by default. */
if (optarg == NULL || strcmp(optarg, "yes") == 0)
{
config->agent_specific.agent.bootstrap_trust_server = true;
}
else
{
config->agent_specific.agent.bootstrap_trust_server = false;
}
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);
}
}
else if (StringEqual(option_name, "no-augments"))
{
config->agent_specific.common.no_augments = true;
}
else if (StringEqual(option_name, "no-host-specific-data"))
{
config->agent_specific.common.no_host_specific = true;
}
else if (StringEqual(option_name, "show-evaluated-classes"))
{
if (optarg == NULL)
{
optarg = ".*";
}
config->agent_specific.agent.show_evaluated_classes = xstrdup(optarg);
}
else if (StringEqual(option_name, "show-evaluated-vars"))
{
if (optarg == NULL)
{
optarg = ".*";
}
config->agent_specific.agent.show_evaluated_variables = xstrdup(optarg);
}
else if (StringEqual(option_name, "skip-bootstrap-policy-run"))
{
config->agent_specific.agent.bootstrap_trigger_policy = false;
}
else if (StringEqual(option_name, "skip-bootstrap-service-start"))
{
config->agent_specific.agent.skip_bootstrap_service_start = true;
}
else if (StringEqual(option_name, "skip-db-check"))
{
if (optarg == NULL)
{
PERFORM_DB_CHECK = false; // Skip (no arg), check = false
}
else if (StringEqual_IgnoreCase(optarg, "yes"))
{
PERFORM_DB_CHECK = false; // Skip = yes, check = false
}
else if (StringEqual_IgnoreCase(optarg, "no"))
{
PERFORM_DB_CHECK = true; // Skip = no, check = true
}
else
{
Log(LOG_LEVEL_ERR,
"Invalid argument for --skip-db-check(yes/no): '%s'",
optarg);
DoCleanupAndExit(EXIT_FAILURE);
}
}
else if (StringEqual(option_name, "simulate"))
{
if (optarg == NULL)
{
Log(LOG_LEVEL_ERR,
"Missing argument for --simulate, 'manifest', 'manifest-full', or 'diff' required");
DoCleanupAndExit(EXIT_FAILURE);
}
else if (StringEqual_IgnoreCase(optarg, "manifest"))
{
EVAL_MODE = EVAL_MODE_SIMULATE_MANIFEST;
}
else if (StringEqual_IgnoreCase(optarg, "manifest-full"))
{
EVAL_MODE = EVAL_MODE_SIMULATE_MANIFEST_FULL;
}
else if (StringEqual_IgnoreCase(optarg, "diff"))
{
EVAL_MODE = EVAL_MODE_SIMULATE_DIFF;
}
else
{
Log(LOG_LEVEL_ERR,
"Invalid argument for --simulate, 'manifest' or 'diff' required, not '%s'",
optarg);
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_new - optind,
argv_new + optind))
{
Log(LOG_LEVEL_ERR, "Too many arguments");
DoCleanupAndExit(EXIT_FAILURE);
}
if (option_trust_server &&
config->agent_specific.agent.bootstrap_argument == NULL)
{
Log(LOG_LEVEL_ERR,
"Option --trust-server can only be used when bootstrapping");
DoCleanupAndExit(EXIT_FAILURE);
}
FreeFixedStringArray(argc_new, argv_new);
return config;
}
static char **TranslateOldBootstrapOptionsSeparate(int *argc_new, char **argv)
{
int i;
int policy_server_argnum = 0;
int server_address_argnum = 0;
int bootstrap_argnum = 0;
int argc = *argc_new;
for(i = 0; i < argc; i++)
{
if(strcmp(argv[i], "--policy-server") == 0 || strcmp(argv[i], "-s") == 0)
{
policy_server_argnum = i;
}
if(strcmp(argv[i], "--bootstrap") == 0 || strcmp(argv[i], "-B") == 0)
{
bootstrap_argnum = i;
}
}
if(policy_server_argnum > 0)
{
if(policy_server_argnum + 1 < argc)
{
server_address_argnum = policy_server_argnum + 1;
}
}
char **argv_new;
if(bootstrap_argnum > 0 && server_address_argnum > 0)
{
Log(LOG_LEVEL_WARNING, "Deprecated bootstrap options detected. The --policy-server (-s) option is deprecated from CFEngine community version 3.5.0."
"Please provide the address argument to --bootstrap (-B) instead. Rewriting your arguments now, but you need to adjust them as this support will be removed soon.");
*argc_new = argc - 1; // --policy-server deprecated
argv_new = xcalloc(1, sizeof(char *) * (*argc_new + 1));
int new_i = 0;
for(i = 0; i < argc; i++)
{
if(i == bootstrap_argnum)
{
argv_new[new_i++] = xstrdup(argv[bootstrap_argnum]);
argv_new[new_i++] = xstrdup(argv[server_address_argnum]);
}
else if(i == server_address_argnum)
{
// skip: handled above
}
else if(i == policy_server_argnum)
{
// skip: deprecated
}
else
{
argv_new[new_i++] = xstrdup(argv[i]);
}
}
}
else
{
argv_new = xcalloc(1, sizeof(char *) * (*argc_new + 1));
for(i = 0; i < argc; i++)
{
argv_new[i] = xstrdup(argv[i]);
}
}
return argv_new;
}
static char **TranslateOldBootstrapOptionsConcatenated(int argc, char **argv)
{
char **argv_new = xcalloc(1, sizeof(char *) * (argc + 1));
for(int i = 0; i < argc; i++)
{
if(strcmp(argv[i], "-Bs") == 0)
{
Log(LOG_LEVEL_WARNING, "Deprecated bootstrap options detected. The --policy-server (-s) option is deprecated from CFEngine community version 3.5.0."
"Please provide the address argument to --bootstrap (-B) instead. Rewriting your arguments now, but you need to adjust them as this support will be removed soon.");
argv_new[i] = xstrdup("-B");
}
else
{
argv_new[i] = xstrdup(argv[i]);
}
}
return argv_new;
}
static void FreeFixedStringArray(int size, char **array)
{
for(int i = 0; i < size; i++)
{
free(array[i]);
}
free(array);
}
/*******************************************************************/
static void ThisAgentInit(void)
{
char filename[CF_BUFSIZE];
#ifdef HAVE_SETSID
setsid();
#endif
CFA_MAXTHREADS = 30;
EDITFILESIZE = 100000;
/*
do not set signal(SIGCHLD,SIG_IGN) in agent near
popen() - or else pclose will fail to return
status which we need for setting returns
*/
snprintf(filename, CF_BUFSIZE, "%s/cfagent.%s.log", GetLogDir(), VSYSNAME.nodename);
ToLowerStrInplace(filename);
MapName(filename);
const mode_t current_umask = umask(0777); // Gets and changes umask
umask(current_umask); // Restores umask
Log(LOG_LEVEL_DEBUG, "Current umask is %o", current_umask);
FILE *fp = safe_fopen(filename, "a");
if (fp != NULL)
{
fclose(fp);
}
InitializeCustomPromises();
}
/*******************************************************************/
static void KeepPromises(EvalContext *ctx, const Policy *policy, GenericAgentConfig *config)
{
KeepControlPromises(ctx, policy, config);
/* Check if 'abortclasses' aborted evaluation or not. */
if (EvalAborted(ctx))
{
return;
}
KeepPromiseBundles(ctx, policy, config);
}
/*******************************************************************/
/* Level 2 */
/*******************************************************************/
static void KeepControlPromises(EvalContext *ctx, const Policy *policy, GenericAgentConfig *config)
{
Seq *constraints = ControlBodyConstraints(policy, AGENT_TYPE_AGENT);
if (constraints)
{
for (size_t i = 0; i < SeqLength(constraints); i++)
{
Constraint *cp = SeqAt(constraints, i);
if (!IsDefinedClass(ctx, cp->classes))
{
continue;
}
if (CommonControlFromString(cp->lval) != COMMON_CONTROL_MAX)
{
/* Already handled in generic_agent */
continue;
}