-
Notifications
You must be signed in to change notification settings - Fork 187
/
evalfunction.c
10721 lines (9085 loc) · 367 KB
/
evalfunction.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 <evalfunction.h>
#include <policy_server.h>
#include <promises.h>
#include <dir.h>
#include <file_lib.h>
#include <dbm_api.h>
#include <lastseen.h>
#include <files_copy.h>
#include <files_names.h>
#include <files_interfaces.h>
#include <hash.h>
#include <vars.h>
#include <addr_lib.h>
#include <syntax.h>
#include <item_lib.h>
#include <conversion.h>
#include <expand.h>
#include <scope.h>
#include <keyring.h>
#include <matching.h>
#include <unix.h> /* GetUserName(), GetGroupName() */
#include <string_lib.h>
#include <regex.h> /* CompileRegex,StringMatchWithPrecompiledRegex */
#include <net.h> /* SocketConnect */
#include <communication.h>
#include <classic.h> /* SendSocketStream */
#include <pipes.h>
#include <exec_tools.h>
#include <policy.h>
#include <misc_lib.h>
#include <fncall.h>
#include <audit.h>
#include <sort.h>
#include <logging.h>
#include <set.h>
#include <buffer.h>
#include <files_lib.h>
#include <connection_info.h>
#include <printsize.h>
#include <csv_parser.h>
#include <json.h>
#include <json-yaml.h>
#include <json-utils.h>
#include <known_dirs.h>
#include <mustache.h>
#include <processes_select.h>
#include <sysinfo.h>
#include <string_sequence.h>
#include <string_lib.h>
#include <version_comparison.h>
#include <mutex.h> /* ThreadWait */
#include <glob_lib.h>
#include <math_eval.h>
#include <libgen.h>
#include <ctype.h>
#ifdef HAVE_LIBCURL
#include <curl/curl.h>
#endif
#ifdef HAVE_LIBCURL
static bool CURL_INITIALIZED = false; /* GLOBAL */
static JsonElement *CURL_CACHE = NULL;
#endif
#define SPLAY_PSEUDO_RANDOM_CONSTANT 8192
static FnCallResult FilterInternal(EvalContext *ctx, const FnCall *fp, const char *regex, const Rlist* rp, bool do_regex, bool invert, long max);
static char *StripPatterns(char *file_buffer, const char *pattern, const char *filename);
static int BuildLineArray(EvalContext *ctx, const Bundle *bundle, const char *array_lval, const char *file_buffer,
const char *split, int maxent, DataType type, bool int_index);
static JsonElement* BuildData(EvalContext *ctx, const char *file_buffer, const char *split, int maxent, bool make_array);
static bool ExecModule(EvalContext *ctx, char *command);
static bool CheckIDChar(const char ch);
static bool CheckID(const char *id);
static const Rlist *GetListReferenceArgument(const EvalContext *ctx, const FnCall *fp, const char *lval_str, DataType *datatype_out);
static char *CfReadFile(const char *filename, size_t maxsize);
/*******************************************************************/
int FnNumArgs(const FnCallType *call_type)
{
for (int i = 0;; i++)
{
if (call_type->args[i].pattern == NULL)
{
return i;
}
}
}
/*******************************************************************/
/* assume args are all scalar literals by the time we get here
and each handler allocates the memory it returns. There is
a protocol to be followed here:
Set args,
Eval Content,
Set rtype,
ErrorFlags
returnval = FnCallXXXResult(fp)
*/
/*
* Return successful FnCallResult with copy of str retained.
*/
static FnCallResult FnReturn(const char *str)
{
return (FnCallResult) { FNCALL_SUCCESS, { xstrdup(str), RVAL_TYPE_SCALAR } };
}
/*
* Return successful FnCallResult with str as is.
*/
static FnCallResult FnReturnNoCopy(char *str)
{
return (FnCallResult) { FNCALL_SUCCESS, { str, RVAL_TYPE_SCALAR } };
}
static FnCallResult FnReturnBuffer(Buffer *buf)
{
return (FnCallResult) { FNCALL_SUCCESS, { BufferClose(buf), RVAL_TYPE_SCALAR } };
}
static FnCallResult FnReturnContainerNoCopy(JsonElement *container)
{
return (FnCallResult) { FNCALL_SUCCESS, (Rval) { container, RVAL_TYPE_CONTAINER }};
}
// Currently only used for LIBCURL function, macro can be removed later
#ifdef HAVE_LIBCURL
static FnCallResult FnReturnContainer(JsonElement *container)
{
return FnReturnContainerNoCopy(JsonCopy(container));
}
#endif // HAVE_LIBCURL
static FnCallResult FnReturnF(const char *fmt, ...) FUNC_ATTR_PRINTF(1, 2);
static FnCallResult FnReturnF(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
char *buffer;
xvasprintf(&buffer, fmt, ap);
va_end(ap);
return FnReturnNoCopy(buffer);
}
static FnCallResult FnReturnContext(bool result)
{
return FnReturn(result ? "any" : "!any");
}
static FnCallResult FnFailure(void)
{
return (FnCallResult) { FNCALL_FAILURE, { 0 } };
}
static VarRef* ResolveAndQualifyVarName(const FnCall *fp, const char *varname)
{
VarRef *ref = NULL;
if (varname != NULL &&
IsVarList(varname) &&
strlen(varname) < CF_MAXVARSIZE)
{
char naked[CF_MAXVARSIZE] = "";
GetNaked(naked, varname);
ref = VarRefParse(naked);
}
else
{
ref = VarRefParse(varname);
}
if (!VarRefIsQualified(ref))
{
if (fp->caller)
{
const Bundle *caller_bundle = PromiseGetBundle(fp->caller);
VarRefQualify(ref, caller_bundle->ns, caller_bundle->name);
}
else
{
Log(LOG_LEVEL_WARNING,
"Function '%s' was not called from a promise; "
"the unqualified variable reference %s cannot be qualified automatically.",
fp->name,
varname);
VarRefDestroy(ref);
return NULL;
}
}
return ref;
}
static JsonElement* VarRefValueToJson(const EvalContext *ctx, const FnCall *fp, const VarRef *ref,
const DataType disallowed_datatypes[], size_t disallowed_count,
bool allow_scalars, bool *allocated)
{
assert(ref);
DataType value_type = CF_DATA_TYPE_NONE;
const void *value = EvalContextVariableGet(ctx, ref, &value_type);
bool want_type = true;
// Convenience storage for the name of the function, since fp can be NULL
const char* fp_name = (fp ? fp->name : "VarRefValueToJson");
for (size_t di = 0; di < disallowed_count; di++)
{
if (disallowed_datatypes[di] == value_type)
{
want_type = false;
break;
}
}
JsonElement *convert = NULL;
if (want_type)
{
switch (DataTypeToRvalType(value_type))
{
case RVAL_TYPE_LIST:
convert = JsonArrayCreate(RlistLen(value));
for (const Rlist *rp = value; rp != NULL; rp = rp->next)
{
if (rp->val.type == RVAL_TYPE_SCALAR) /* TODO what if it's an ilist */
{
JsonArrayAppendString(convert, RlistScalarValue(rp));
}
else
{
ProgrammingError("Ignored Rval of list type: %s",
RvalTypeToString(rp->val.type));
}
}
*allocated = true;
break;
case RVAL_TYPE_CONTAINER:
// TODO: look into optimizing this if necessary
convert = JsonCopy(value);
*allocated = true;
break;
case RVAL_TYPE_SCALAR:
{
const char* data = value;
if (allow_scalars)
{
convert = JsonStringCreate(value);
*allocated = true;
break;
}
else
{
/* regarray,mergedata,maparray,mapdata only care for arrays
* and ignore strings, so they go through this path. */
Log(LOG_LEVEL_DEBUG,
"Skipping scalar '%s' because 'allow_scalars' is false",
data);
}
}
// fallthrough
default:
*allocated = true;
{
VariableTableIterator *iter = EvalContextVariableTableFromRefIteratorNew(ctx, ref);
convert = JsonObjectCreate(10);
const size_t ref_num_indices = ref->num_indices;
char *last_key = NULL;
Variable *var;
while ((var = VariableTableIteratorNext(iter)) != NULL)
{
JsonElement *holder = convert;
JsonElement *holder_parent = NULL;
const VarRef *var_ref = VariableGetRef(var);
if (var_ref->num_indices - ref_num_indices == 1)
{
last_key = var_ref->indices[ref_num_indices];
}
else if (var_ref->num_indices - ref_num_indices > 1)
{
Log(LOG_LEVEL_DEBUG, "%s: got ref with starting depth %zu and index count %zu",
fp_name, ref_num_indices, var_ref->num_indices);
for (size_t index = ref_num_indices; index < var_ref->num_indices-1; index++)
{
JsonElement *local = JsonObjectGet(holder, var_ref->indices[index]);
if (local == NULL)
{
local = JsonObjectCreate(1);
JsonObjectAppendObject(holder, var_ref->indices[index], local);
}
last_key = var_ref->indices[index+1];
holder_parent = holder;
holder = local;
}
}
if (last_key != NULL && holder != NULL)
{
Rval var_rval = VariableGetRval(var, true);
switch (var_rval.type)
{
case RVAL_TYPE_SCALAR:
if (JsonGetElementType(holder) != JSON_ELEMENT_TYPE_CONTAINER)
{
Log(LOG_LEVEL_WARNING,
"Replacing a non-container JSON element '%s' with a new empty container"
" (for the '%s' subkey)",
JsonGetPropertyAsString(holder), last_key);
assert(holder_parent != NULL);
JsonElement *empty_container = JsonObjectCreate(10);
/* we have to duplicate 'holder->propertyName'
* instead of just using a pointer to it here
* because 'holder' is destroyed as part of the
* JsonObjectAppendElement() call below */
char *element_name = xstrdup(JsonGetPropertyAsString(holder));
JsonObjectAppendElement(holder_parent,
element_name,
empty_container);
free (element_name);
holder = empty_container;
JsonObjectAppendString(holder, last_key, var_rval.item);
}
else
{
JsonElement *child = JsonObjectGet(holder, last_key);
if (child != NULL && JsonGetElementType(child) == JSON_ELEMENT_TYPE_CONTAINER)
{
Rval var_rval_secret = VariableGetRval(var, false);
Log(LOG_LEVEL_WARNING,
"Not replacing the container '%s' with a non-container value '%s'",
JsonGetPropertyAsString(child), (char*) var_rval_secret.item);
}
else
{
/* everything ok, just append the string */
JsonObjectAppendString(holder, last_key, var_rval.item);
}
}
break;
case RVAL_TYPE_LIST:
{
JsonElement *array = JsonArrayCreate(10);
for (const Rlist *rp = RvalRlistValue(var_rval); rp != NULL; rp = rp->next)
{
if (rp->val.type == RVAL_TYPE_SCALAR)
{
JsonArrayAppendString(array, RlistScalarValue(rp));
}
}
JsonObjectAppendArray(holder, last_key, array);
}
break;
default:
break;
}
}
}
VariableTableIteratorDestroy(iter);
if (JsonLength(convert) < 1)
{
char *varname = VarRefToString(ref, true);
Log(LOG_LEVEL_VERBOSE, "%s: argument '%s' does not resolve to a container or a list or a CFEngine array",
fp_name, varname);
free(varname);
JsonDestroy(convert);
return NULL;
}
break;
} // end of default case
} // end of data type switch
}
else // !wanted_type
{
char *varname = VarRefToString(ref, true);
Log(LOG_LEVEL_DEBUG, "%s: argument '%s' resolved to an undesired data type",
fp_name, varname);
free(varname);
}
return convert;
}
static JsonElement *LookupVarRefToJson(void *ctx, const char **data)
{
Buffer* varname = NULL;
Seq *s = StringMatchCaptures("^(([a-zA-Z0-9_]+\\.)?[a-zA-Z0-9._]+)(\\[[^\\[\\]]+\\])?", *data, false);
if (s && SeqLength(s) > 0) // got a variable name
{
varname = BufferCopy((const Buffer*) SeqAt(s, 0));
}
if (s)
{
SeqDestroy(s);
}
VarRef *ref = NULL;
if (varname)
{
ref = VarRefParse(BufferData(varname));
// advance to the last character of the matched variable name
*data += strlen(BufferData(varname))-1;
BufferDestroy(varname);
}
if (!ref)
{
return NULL;
}
bool allocated = false;
JsonElement *vardata = VarRefValueToJson(ctx, NULL, ref, NULL, 0, true, &allocated);
VarRefDestroy(ref);
// This should always return a copy
if (!allocated)
{
vardata = JsonCopy(vardata);
}
return vardata;
}
static JsonElement* VarNameOrInlineToJson(EvalContext *ctx, const FnCall *fp, const Rlist* rp, bool allow_scalars, bool *allocated)
{
JsonElement *inline_data = NULL;
assert(rp);
if (rp->val.type == RVAL_TYPE_CONTAINER)
{
return (JsonElement*) rp->val.item;
}
const char* data = RlistScalarValue(rp);
JsonParseError res = JsonParseWithLookup(ctx, &LookupVarRefToJson, &data, &inline_data);
if (res == JSON_PARSE_OK)
{
if (JsonGetElementType(inline_data) == JSON_ELEMENT_TYPE_PRIMITIVE)
{
JsonDestroy(inline_data);
inline_data = NULL;
}
else
{
*allocated = true;
return inline_data;
}
}
VarRef *ref = ResolveAndQualifyVarName(fp, data);
if (!ref)
{
return NULL;
}
JsonElement *vardata = VarRefValueToJson(ctx, fp, ref, NULL, 0, allow_scalars, allocated);
VarRefDestroy(ref);
return vardata;
}
typedef struct {
char *address;
char *hostkey;
time_t lastseen;
} HostData;
static HostData *HostDataNew(const char *address, const char *hostkey, time_t lastseen)
{
HostData *data = xmalloc(sizeof(HostData));
data->address = SafeStringDuplicate(address);
data->hostkey = SafeStringDuplicate(hostkey);
data->lastseen = lastseen;
return data;
}
static void HostDataFree(HostData *hd)
{
if (hd != NULL)
{
free(hd->address);
free(hd->hostkey);
free(hd);
}
}
typedef enum {
NAME,
ADDRESS,
HOSTKEY,
NONE
} HostsSeenFieldOption;
static HostsSeenFieldOption ParseHostsSeenFieldOption(const char *field)
{
if (StringEqual(field, "name"))
{
return NAME;
}
else if (StringEqual(field, "address"))
{
return ADDRESS;
}
else if (StringEqual(field, "hostkey"))
{
return HOSTKEY;
}
else
{
return NONE;
}
}
static Rlist *GetHostsFromLastseenDB(Seq *host_data, time_t horizon, HostsSeenFieldOption return_what, bool return_recent)
{
Rlist *recent = NULL, *aged = NULL;
time_t now = time(NULL);
time_t entrytime;
char ret_host_data[CF_MAXVARSIZE]; // TODO: Could this be 1025 / NI_MAXHOST ?
const size_t length = SeqLength(host_data);
for (size_t i = 0; i < length; ++i)
{
HostData *hd = SeqAt(host_data, i);
entrytime = hd->lastseen;
if ((return_what == NAME || return_what == ADDRESS)
&& HostKeyAddressUnknown(hd->hostkey))
{
continue;
}
switch (return_what)
{
case NAME:
{
char hostname[NI_MAXHOST];
if (IPString2Hostname(hostname, hd->address, sizeof(hostname)) != -1)
{
StringCopy(hostname, ret_host_data, sizeof(ret_host_data));
}
else
{
/* Not numeric address was requested, but IP was unresolvable. */
StringCopy(hd->address, ret_host_data, sizeof(ret_host_data));
}
break;
}
case ADDRESS:
StringCopy(hd->address, ret_host_data, sizeof(ret_host_data));
break;
case HOSTKEY:
StringCopy(hd->hostkey, ret_host_data, sizeof(ret_host_data));
break;
default:
ProgrammingError("Parser allowed invalid hostsseen() field argument");
}
if (entrytime < now - horizon)
{
Log(LOG_LEVEL_DEBUG, "Old entry");
if (RlistKeyIn(recent, ret_host_data))
{
Log(LOG_LEVEL_DEBUG, "There is recent entry for this ret_host_data. Do nothing.");
}
else
{
Log(LOG_LEVEL_DEBUG, "Adding to list of aged hosts.");
RlistPrependScalarIdemp(&aged, ret_host_data);
}
}
else
{
Log(LOG_LEVEL_DEBUG, "Recent entry");
Rlist *r = RlistKeyIn(aged, ret_host_data);
if (r)
{
Log(LOG_LEVEL_DEBUG, "Purging from list of aged hosts.");
RlistDestroyEntry(&aged, r);
}
Log(LOG_LEVEL_DEBUG, "Adding to list of recent hosts.");
RlistPrependScalarIdemp(&recent, ret_host_data);
}
}
if (return_recent)
{
RlistDestroy(aged);
return recent;
}
else
{
RlistDestroy(recent);
return aged;
}
}
/*********************************************************************/
static FnCallResult FnCallAnd(EvalContext *ctx,
ARG_UNUSED const Policy *policy,
ARG_UNUSED const FnCall *fp,
const Rlist *finalargs)
{
for (const Rlist *arg = finalargs; arg; arg = arg->next)
{
SyntaxTypeMatch err = CheckConstraintTypeMatch(fp->name, arg->val, CF_DATA_TYPE_STRING, "", 1);
if (err != SYNTAX_TYPE_MATCH_OK && err != SYNTAX_TYPE_MATCH_ERROR_UNEXPANDED)
{
FatalError(ctx, "Function '%s', %s", fp->name, SyntaxTypeMatchToString(err));
}
}
for (const Rlist *arg = finalargs; arg; arg = arg->next)
{
if (!IsDefinedClass(ctx, RlistScalarValue(arg)))
{
return FnReturnContext(false);
}
}
return FnReturnContext(true);
}
/*******************************************************************/
static bool CallHostsSeenCallback(const char *hostkey, const char *address,
ARG_UNUSED bool incoming, const KeyHostSeen *quality,
void *ctx)
{
SeqAppend(ctx, HostDataNew(address, hostkey, quality->lastseen));
return true;
}
/*******************************************************************/
static FnCallResult FnCallHostsSeen(ARG_UNUSED EvalContext *ctx, ARG_UNUSED const Policy *policy, ARG_UNUSED const FnCall *fp, const Rlist *finalargs)
{
Seq *host_data = SeqNew(1, HostDataFree);
int horizon = IntFromString(RlistScalarValue(finalargs)) * 3600;
char *hostseen_policy = RlistScalarValue(finalargs->next);
char *field_str = RlistScalarValue(finalargs->next->next);
HostsSeenFieldOption field = ParseHostsSeenFieldOption(field_str);
Log(LOG_LEVEL_DEBUG, "Calling hostsseen(%d,%s,%s)",
horizon, hostseen_policy, field_str);
if (!ScanLastSeenQuality(&CallHostsSeenCallback, host_data))
{
SeqDestroy(host_data);
return FnFailure();
}
Rlist *returnlist = GetHostsFromLastseenDB(host_data, horizon,
field,
StringEqual(hostseen_policy, "lastseen"));
SeqDestroy(host_data);
{
Writer *w = StringWriter();
WriterWrite(w, "hostsseen return values:");
for (Rlist *rp = returnlist; rp; rp = rp->next)
{
WriterWriteF(w, " '%s'", RlistScalarValue(rp));
}
Log(LOG_LEVEL_DEBUG, "%s", StringWriterData(w));
WriterClose(w);
}
if (returnlist == NULL)
{
return FnFailure();
}
return (FnCallResult) { FNCALL_SUCCESS, { returnlist, RVAL_TYPE_LIST } };
}
/*********************************************************************/
static FnCallResult FnCallHostsWithClass(EvalContext *ctx, ARG_UNUSED const Policy *policy, ARG_UNUSED const FnCall *fp, const Rlist *finalargs)
{
Rlist *returnlist = NULL;
char *class_name = RlistScalarValue(finalargs);
char *return_format = RlistScalarValue(finalargs->next);
if (!ListHostsWithClass(ctx, &returnlist, class_name, return_format))
{
return FnFailure();
}
return (FnCallResult) { FNCALL_SUCCESS, { returnlist, RVAL_TYPE_LIST } };
}
/*********************************************************************/
/** @brief Convert function call from/to variables to range
*
* Swap the two integers in place if the first is bigger
* Check for CF_NOINT, indicating invalid arguments
*
* @return Absolute (positive) difference, -1 for error (0 for equal)
*/
static int int_range_convert(int *from, int *to)
{
int old_from = *from;
int old_to = *to;
if (old_from == CF_NOINT || old_to == CF_NOINT)
{
return -1;
}
if (old_from == old_to)
{
return 0;
}
if (old_from > old_to)
{
*from = old_to;
*to = old_from;
}
assert(*to > *from);
return (*to) - (*from);
}
static FnCallResult FnCallRandomInt(ARG_UNUSED EvalContext *ctx, ARG_UNUSED const Policy *policy, ARG_UNUSED const FnCall *fp, const Rlist *finalargs)
{
if (finalargs->next == NULL)
{
return FnFailure();
}
int from = IntFromString(RlistScalarValue(finalargs));
int to = IntFromString(RlistScalarValue(finalargs->next));
int range = int_range_convert(&from, &to);
if (range == -1)
{
return FnFailure();
}
if (range == 0)
{
return FnReturnF("%d", from);
}
assert(range > 0);
int result = from + (int) (drand48() * (double) range);
return FnReturnF("%d", result);
}
// Read an array of bytes as unsigned integers
// Convert to 64 bit unsigned integer
// Cross platform/arch, bytes[0] is always LSB of result
static uint64_t BytesToUInt64(uint8_t *bytes)
{
uint64_t result = 0;
size_t n = 8;
for (size_t i = 0; i<n; ++i)
{
result += ((uint64_t)(bytes[i])) << (8 * i);
}
return result;
}
static FnCallResult FnCallHashToInt(ARG_UNUSED EvalContext *ctx, ARG_UNUSED const Policy *policy, ARG_UNUSED const FnCall *fp, const Rlist *finalargs)
{
if (finalargs->next == NULL || finalargs->next->next == NULL)
{
return FnFailure();
}
signed int from = IntFromString(RlistScalarValue(finalargs));
signed int to = IntFromString(RlistScalarValue(finalargs->next));
signed int range = int_range_convert(&from, &to);
if (range == -1)
{
return FnFailure();
}
if (range == 0)
{
return FnReturnF("%d", from);
}
assert(range > 0);
const unsigned char * const inp = RlistScalarValue(finalargs->next->next);
// Use beginning of SHA checksum as basis:
unsigned char digest[EVP_MAX_MD_SIZE + 1];
memset(digest, 0, sizeof(digest));
HashString(inp, strlen(inp), digest, HASH_METHOD_SHA256);
uint64_t converted_sha = BytesToUInt64((uint8_t*)digest);
// Limit using modulo:
signed int result = from + (converted_sha % range);
return FnReturnF("%d", result);
}
/*********************************************************************/
static FnCallResult FnCallGetEnv(ARG_UNUSED EvalContext *ctx, ARG_UNUSED const Policy *policy, ARG_UNUSED const FnCall *fp, const Rlist *finalargs)
{
char buffer[CF_BUFSIZE] = "", ctrlstr[CF_SMALLBUF];
char *name = RlistScalarValue(finalargs);
int limit = IntFromString(RlistScalarValue(finalargs->next));
snprintf(ctrlstr, CF_SMALLBUF, "%%.%ds", limit); // -> %45s
if (getenv(name))
{
snprintf(buffer, CF_BUFSIZE - 1, ctrlstr, getenv(name));
}
return FnReturn(buffer);
}
/*********************************************************************/
#if defined(HAVE_GETPWENT) && !defined(__ANDROID__)
static FnCallResult FnCallGetUsers(ARG_UNUSED EvalContext *ctx, ARG_UNUSED const Policy *policy, ARG_UNUSED const FnCall *fp, const Rlist *finalargs)
{
const char *except_name = RlistScalarValue(finalargs);
const char *except_uid = RlistScalarValue(finalargs->next);
Rlist *except_names = RlistFromSplitString(except_name, ',');
Rlist *except_uids = RlistFromSplitString(except_uid, ',');
setpwent();
Rlist *newlist = NULL;
struct passwd *pw;
while ((pw = getpwent()))
{
char *pw_uid_str = StringFromLong((int)pw->pw_uid);
if (!RlistKeyIn(except_names, pw->pw_name) && !RlistKeyIn(except_uids, pw_uid_str))
{
RlistAppendScalarIdemp(&newlist, pw->pw_name);
}
free(pw_uid_str);
}
endpwent();
RlistDestroy(except_names);
RlistDestroy(except_uids);
return (FnCallResult) { FNCALL_SUCCESS, { newlist, RVAL_TYPE_LIST } };
}
#else
static FnCallResult FnCallGetUsers(ARG_UNUSED EvalContext *ctx, ARG_UNUSED const Policy *policy, ARG_UNUSED const FnCall *fp, ARG_UNUSED const Rlist *finalargs)
{
Log(LOG_LEVEL_ERR, "getusers is not implemented");
return FnFailure();
}
#endif
/*********************************************************************/
static FnCallResult FnCallEscape(ARG_UNUSED EvalContext *ctx, ARG_UNUSED const Policy *policy, ARG_UNUSED const FnCall *fp, const Rlist *finalargs)
{
char buffer[CF_BUFSIZE];
buffer[0] = '\0';
char *name = RlistScalarValue(finalargs);
EscapeSpecialChars(name, buffer, CF_BUFSIZE - 1, "", "");
return FnReturn(buffer);
}
/*********************************************************************/
static FnCallResult FnCallHost2IP(ARG_UNUSED EvalContext *ctx, ARG_UNUSED const Policy *policy, ARG_UNUSED const FnCall *fp, const Rlist *finalargs)
{
char *name = RlistScalarValue(finalargs);
char ipaddr[CF_MAX_IP_LEN];
if (Hostname2IPString(ipaddr, name, sizeof(ipaddr)) != -1)
{
return FnReturn(ipaddr);
}
else
{
/* Retain legacy behaviour,
return hostname in case resolution fails. */
return FnReturn(name);
}
}
/*********************************************************************/
static FnCallResult FnCallIP2Host(ARG_UNUSED EvalContext *ctx,
ARG_UNUSED ARG_UNUSED const Policy *policy,
ARG_UNUSED const FnCall *fp,
const Rlist *finalargs)
{
char hostname[NI_MAXHOST];
char *ip = RlistScalarValue(finalargs);
if (IPString2Hostname(hostname, ip, sizeof(hostname)) != -1)
{
return FnReturn(hostname);
}
else
{
/* Retain legacy behaviour,
return ip address in case resolution fails. */
return FnReturn(ip);
}
}
/*********************************************************************/
static FnCallResult FnCallSysctlValue(ARG_UNUSED EvalContext *ctx,
ARG_UNUSED ARG_UNUSED const Policy *policy,
ARG_LINUX_ONLY const FnCall *fp,
ARG_LINUX_ONLY const Rlist *finalargs)
{
#ifdef __linux__
const bool sysctlvalue_mode = (strcmp(fp->name, "sysctlvalue") == 0);
size_t max_sysctl_data = 16 * 1024;
Buffer *procrootbuf = BufferNew();
// Assumes that FILE_SEPARATOR is /
BufferAppendString(procrootbuf, GetRelocatedProcdirRoot());
BufferAppendString(procrootbuf, "/proc/sys");
if (sysctlvalue_mode)
{
Buffer *key = BufferNewFrom(RlistScalarValue(finalargs),
strlen(RlistScalarValue(finalargs)));