-
Notifications
You must be signed in to change notification settings - Fork 187
/
files_editline.c
2550 lines (2159 loc) · 80.2 KB
/
files_editline.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 <files_editline.h>
#include <actuator.h>
#include <eval_context.h>
#include <promises.h>
#include <files_names.h>
#include <files_interfaces.h>
#include <vars.h>
#include <item_lib.h>
#include <sort.h>
#include <conversion.h>
#include <expand.h>
#include <scope.h>
#include <matching.h>
#include <match_scope.h>
#include <attributes.h>
#include <locks.h>
#include <string_lib.h>
#include <misc_lib.h>
#include <file_lib.h>
#include <rlist.h>
#include <policy.h>
#include <ornaments.h>
#include <verify_classes.h>
#define CF_MAX_REPLACE 20
/*****************************************************************************/
enum editlinetypesequence
{
elp_vars,
elp_classes,
elp_delete,
elp_columns,
elp_insert,
elp_replace,
elp_reports,
elp_none
};
static const char *const EDITLINETYPESEQUENCE[] =
{
"vars",
"classes",
"delete_lines",
"field_edits",
"insert_lines",
"replace_patterns",
"reports",
NULL
};
static PromiseResult KeepEditLinePromise(EvalContext *ctx, const Promise *pp, void *param);
static PromiseResult VerifyLineDeletions(EvalContext *ctx, const Promise *pp, EditContext *edcontext);
static PromiseResult VerifyColumnEdits(EvalContext *ctx, const Promise *pp, EditContext *edcontext);
static PromiseResult VerifyPatterns(EvalContext *ctx, const Promise *pp, EditContext *edcontext);
static PromiseResult VerifyLineInsertions(EvalContext *ctx, const Promise *pp, EditContext *edcontext);
static bool InsertMultipleLinesToRegion(EvalContext *ctx, Item **start, Item *begin_ptr, Item *end_ptr, const Attributes *a, const Promise *pp, EditContext *edcontext, PromiseResult *result);
static bool InsertMultipleLinesAtLocation(EvalContext *ctx, Item **start, Item *begin_ptr, Item *end_ptr, Item *location, Item *prev, const Attributes *a, const Promise *pp, EditContext *edcontext, PromiseResult *result);
static bool DeletePromisedLinesMatching(EvalContext *ctx, Item **start, Item *begin, Item *end, const Attributes *a, const Promise *pp, EditContext *edcontext, PromiseResult *result);
static bool InsertLineAtLocation(EvalContext *ctx, char *newline, Item **start, Item *location, Item *prev, const Attributes *a, const Promise *pp, EditContext *edcontext, PromiseResult *result);
static bool InsertCompoundLineAtLocation(EvalContext *ctx, const char *newline, Item **start, Item *begin_ptr, Item *end_ptr, Item *location, Item *prev, const Attributes *a, const Promise *pp, EditContext *edcontext, PromiseResult *result);
static bool ReplacePatterns(EvalContext *ctx, Item *start, Item *end, const Attributes *a, const Promise *pp, EditContext *edcontext, PromiseResult *result);
static bool EditColumns(EvalContext *ctx, Item *file_start, Item *file_end, const Attributes *a, const Promise *pp, EditContext *edcontext, PromiseResult *result);
static bool EditLineByColumn(EvalContext *ctx, Rlist **columns, const Attributes *a, const Promise *pp, EditContext *edcontext, PromiseResult *result);
static bool DoEditColumn(Rlist **columns, EditContext *edcontext,
EvalContext *ctx, const Promise *pp, const Attributes *a,
PromiseResult *result);
static bool SanityCheckInsertions(const Attributes *a);
static bool SanityCheckDeletions(const Attributes *a, const Promise *pp);
static bool SelectLine(EvalContext *ctx, const char *line, const Attributes *a);
static bool NotAnchored(char *s);
static bool SelectRegion(EvalContext *ctx, Item *start, Item **begin_ptr, Item **end_ptr, const Attributes *a, EditContext *edcontext);
static bool MultiLineString(char *s);
static bool InsertFileAtLocation(EvalContext *ctx, Item **start, Item *begin_ptr, Item *end_ptr, Item *location, Item *prev, const Attributes *a, const Promise *pp, EditContext *edcontext, PromiseResult *result);
/*****************************************************************************/
/* Level */
/*****************************************************************************/
bool ScheduleEditLineOperations(EvalContext *ctx, const Bundle *bp, const Attributes *a, const Promise *parentp, EditContext *edcontext)
{
assert(a != NULL);
assert(bp != NULL);
assert(edcontext != NULL);
enum editlinetypesequence type;
char lockname[CF_BUFSIZE];
CfLock thislock;
int pass;
assert(StringEqual(bp->type, "edit_line"));
snprintf(lockname, CF_BUFSIZE - 1, "masterfilelock-%s", edcontext->filename);
thislock = AcquireLock(ctx, lockname, VUQNAME, CFSTARTTIME, a->transaction.ifelapsed, a->transaction.expireafter, parentp, true);
if (thislock.lock == NULL)
{
return false;
}
EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_EDIT, "filename", edcontext->filename, CF_DATA_TYPE_STRING, "source=promise");
EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_EDIT, "empty_before_use",
(a->edits.empty_before_use ? "true" : "false"),
CF_DATA_TYPE_STRING, "source=promise");
for (pass = 1; pass < CF_DONEPASSES; pass++)
{
for (type = 0; EDITLINETYPESEQUENCE[type] != NULL; type++)
{
const BundleSection *sp = BundleGetSection(bp, EDITLINETYPESEQUENCE[type]);
if (!sp)
{
continue;
}
EvalContextStackPushBundleSectionFrame(ctx, sp);
const size_t length = SeqLength(sp->promises);
for (size_t ppi = 0; ppi < length; ppi++)
{
Promise *pp = SeqAt(sp->promises, ppi);
ExpandPromise(ctx, pp, KeepEditLinePromise, edcontext);
if (BundleAbort(ctx))
{
YieldCurrentLock(thislock);
EvalContextStackPopFrame(ctx);
return false;
}
}
EvalContextStackPopFrame(ctx);
}
}
YieldCurrentLock(thislock);
return true;
}
/*****************************************************************************/
Bundle *MakeTemporaryBundleFromTemplate(EvalContext *ctx, Policy *policy, const Attributes *a, const Promise *pp, PromiseResult *result)
{
assert(a != NULL);
assert(pp != NULL);
FILE *fp = NULL;
if ((fp = safe_fopen(a->edit_template, "rt" )) == NULL)
{
cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_INTERRUPTED, pp, a, "Unable to open template file '%s' to make '%s'", a->edit_template, pp->promiser);
*result = PromiseResultUpdate(*result, PROMISE_RESULT_INTERRUPTED);
return NULL;
}
Bundle *bp = NULL;
{
char bundlename[CF_MAXVARSIZE];
snprintf(bundlename, CF_MAXVARSIZE, "temp_cf_bundle_%s", CanonifyName(a->edit_template));
bp = PolicyAppendBundle(policy, "default", bundlename, "edit_line", NULL, NULL);
}
assert(bp);
{
BundleSection *bsp = BundleAppendSection(bp, "insert_lines");
Promise *np = NULL;
Item *lines = NULL;
Item *stack = NULL;
char context[CF_BUFSIZE] = "any";
int lineno = 0;
size_t level = 0;
size_t buffer_size = CF_BUFSIZE;
char *buffer = xmalloc(buffer_size);
for (;;)
{
if (getline(&buffer, &buffer_size, fp) == -1)
{
if (!feof(fp))
{
Log(LOG_LEVEL_ERR, "While constructing template for '%s', error reading. (getline %s)",
pp->promiser, GetErrorStr());
break;
}
else /* feof */
{
break;
}
}
lineno++;
// Check closing syntax
// Get Action operator
if (StringEqualN(buffer, "[%CFEngine", strlen("[%CFEngine")))
{
char op[CF_BUFSIZE] = "";
char brack[4] = "";
sscanf(buffer+strlen("[%CFEngine"), "%1024s %3s", op, brack);
if (!StringEqual(brack, "%]"))
{
cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_INTERRUPTED, pp, a, "Template file '%s' syntax error, missing close \"%%]\" at line %d", a->edit_template, lineno);
*result = PromiseResultUpdate(*result, PROMISE_RESULT_INTERRUPTED);
return NULL;
}
if (StringEqual(op, "BEGIN"))
{
PrependItem(&stack, context, NULL);
if (++level > 1)
{
cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_INTERRUPTED, pp, a, "Template file '%s' contains nested blocks which are not allowed, near line %d", a->edit_template, lineno);
*result = PromiseResultUpdate(*result, PROMISE_RESULT_INTERRUPTED);
return NULL;
}
continue;
}
if (StringEqual(op, "END"))
{
level--;
if (stack != NULL)
{
strcpy(context, stack->name);
DeleteItem(&stack, stack);
}
}
if (StringEqual(op + strlen(op)-2, "::"))
{
*(op + strlen(op)-2) = '\0';
strcpy(context, op);
continue;
}
size_t size = 0;
for (const Item *ip = lines; ip != NULL; ip = ip->next)
{
size += strlen(ip->name);
}
char *promiser = NULL;
char *sp = promiser = xcalloc(1, size+1);
for (const Item *ip = lines; ip != NULL; ip = ip->next)
{
const int len = strlen(ip->name);
memcpy(sp, ip->name, len);
sp += len;
}
int nl = StripTrailingNewline(promiser, size);
CF_ASSERT(nl != -1, "StripTrailingNewline failure");
np = BundleSectionAppendPromise(bsp, promiser, (Rval) { NULL, RVAL_TYPE_NOPROMISEE }, context, NULL);
np->offset.line = lineno;
PromiseAppendConstraint(np, "insert_type", RvalNew("preserve_all_lines", RVAL_TYPE_SCALAR), false);
DeleteItemList(lines);
free(promiser);
lines = NULL;
}
else
{
if (IsDefinedClass(ctx, context))
{
if (level > 0)
{
AppendItem(&lines, buffer, context);
}
else
{
//install independent promise line
StripTrailingNewline(buffer, buffer_size);
np = BundleSectionAppendPromise(bsp, buffer, (Rval) { NULL, RVAL_TYPE_NOPROMISEE }, context, NULL);
np->offset.line = lineno;
PromiseAppendConstraint(np, "insert_type", RvalNew("preserve_all_lines", RVAL_TYPE_SCALAR), false);
}
}
}
}
free(buffer);
}
fclose(fp);
return bp;
}
/***************************************************************************/
/* Level */
/***************************************************************************/
static PromiseResult KeepEditLinePromise(EvalContext *ctx, const Promise *pp, void *param)
{
EditContext *edcontext = param;
PromiseBanner(ctx, pp);
if (StringEqual("classes", PromiseGetPromiseType(pp)))
{
return VerifyClassPromise(ctx, pp, NULL);
}
else if (StringEqual("delete_lines", PromiseGetPromiseType(pp)))
{
return VerifyLineDeletions(ctx, pp, edcontext);
}
else if (StringEqual("field_edits", PromiseGetPromiseType(pp)))
{
return VerifyColumnEdits(ctx, pp, edcontext);
}
else if (StringEqual("insert_lines", PromiseGetPromiseType(pp)))
{
return VerifyLineInsertions(ctx, pp, edcontext);
}
else if (StringEqual("replace_patterns", PromiseGetPromiseType(pp)))
{
return VerifyPatterns(ctx, pp, edcontext);
}
else if (StringEqual("reports", PromiseGetPromiseType(pp)))
{
return VerifyReportPromise(ctx, pp);
}
return PROMISE_RESULT_NOOP;
}
/***************************************************************************/
/* Level */
/***************************************************************************/
static PromiseResult VerifyLineDeletions(EvalContext *ctx, const Promise *pp, EditContext *edcontext)
{
assert(pp != NULL);
assert(edcontext != NULL);
Item **start = &(edcontext->file_start);
Item *begin_ptr, *end_ptr;
CfLock thislock;
char lockname[CF_BUFSIZE];
Attributes a = GetDeletionAttributes(ctx, pp);
a.transaction.ifelapsed = CF_EDIT_IFELAPSED;
if (!SanityCheckDeletions(&a, pp))
{
cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_INTERRUPTED, pp, &a,
"The promised line deletion '%s' is inconsistent", pp->promiser);
return PROMISE_RESULT_INTERRUPTED;
}
/* Are we working in a restricted region? */
PromiseResult result = PROMISE_RESULT_NOOP;
if (!a.haveregion)
{
begin_ptr = NULL;
end_ptr = NULL;
}
else if (!SelectRegion(ctx, *start, &begin_ptr, &end_ptr, &a, edcontext))
{
if (a.region.include_end || a.region.include_start)
{
cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_INTERRUPTED, pp, &a,
"The promised line deletion '%s' could not select an edit region in '%s'"
" (this is a good thing, as policy suggests deleting the markers)",
pp->promiser, edcontext->filename);
}
else
{
cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_INTERRUPTED, pp, &a,
"The promised line deletion '%s' could not select an edit region in '%s'"
" (but the delimiters were expected in the file)",
pp->promiser, edcontext->filename);
}
result = PromiseResultUpdate(result, PROMISE_RESULT_INTERRUPTED);
return result;
}
if (!end_ptr && a.region.select_end && !a.region.select_end_match_eof)
{
cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_INTERRUPTED, pp, &a,
"The promised end pattern '%s' was not found when selecting region to delete in '%s'",
a.region.select_end, edcontext->filename);
result = PromiseResultUpdate(result, PROMISE_RESULT_INTERRUPTED);
return result;
}
snprintf(lockname, CF_BUFSIZE - 1, "deleteline-%s-%s", pp->promiser, edcontext->filename);
thislock = AcquireLock(ctx, lockname, VUQNAME, CFSTARTTIME, a.transaction.ifelapsed, a.transaction.expireafter, pp, true);
if (thislock.lock == NULL)
{
return PROMISE_RESULT_SKIPPED;
}
if (DeletePromisedLinesMatching(ctx, start, begin_ptr, end_ptr, &a, pp, edcontext, &result))
{
(edcontext->num_edits)++;
}
switch(result)
{
case PROMISE_RESULT_NOOP:
cfPS(ctx, LOG_LEVEL_VERBOSE, result, pp, &a,
"No changes done for the delete_lines promise '%s'", pp->promiser);
break;
case PROMISE_RESULT_CHANGE:
cfPS(ctx, LOG_LEVEL_INFO, result, pp, &a,
"delete_lines promise '%s' repaired", pp->promiser);
break;
case PROMISE_RESULT_WARN:
cfPS(ctx, LOG_LEVEL_WARNING, result, pp, &a,
"Warnings encountered when actuating delete_lines promise '%s'", pp->promiser);
break;
default:
cfPS(ctx, LOG_LEVEL_ERR, result, pp, &a,
"Errors encountered when actuating delete_lines promise '%s'", pp->promiser);
break;
}
YieldCurrentLock(thislock);
return result;
}
/***************************************************************************/
static PromiseResult VerifyColumnEdits(EvalContext *ctx, const Promise *pp, EditContext *edcontext)
{
assert(pp != NULL);
assert(edcontext != NULL);
Item **start = &(edcontext->file_start);
Item *begin_ptr, *end_ptr;
CfLock thislock;
char lockname[CF_BUFSIZE];
Attributes a = GetColumnAttributes(ctx, pp);
a.transaction.ifelapsed = CF_EDIT_IFELAPSED;
if (a.column.column_separator == NULL)
{
cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_FAIL, pp, &a,
"No field_separator in promise to edit by column for '%s'", pp->promiser);
PromiseRef(LOG_LEVEL_ERR, pp);
return PROMISE_RESULT_FAIL;
}
if (a.column.select_column <= 0)
{
cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_FAIL, pp, &a,
"No select_field in promise to edit '%s'", pp->promiser);
PromiseRef(LOG_LEVEL_ERR, pp);
return PROMISE_RESULT_FAIL;
}
if (!a.column.column_value)
{
cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_FAIL, pp, &a,
"No field_value is promised to column_edit '%s'", pp->promiser);
PromiseRef(LOG_LEVEL_ERR, pp);
return PROMISE_RESULT_FAIL;
}
/* Are we working in a restricted region? */
PromiseResult result = PROMISE_RESULT_NOOP;
if (!a.haveregion)
{
begin_ptr = *start;
end_ptr = NULL; // EndOfList(*start);
}
else if (!SelectRegion(ctx, *start, &begin_ptr, &end_ptr, &a, edcontext))
{
cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_INTERRUPTED, pp, &a,
"The promised column edit '%s' could not select an edit region in '%s'",
pp->promiser, edcontext->filename);
result = PromiseResultUpdate(result, PROMISE_RESULT_INTERRUPTED);
return result;
}
/* locate and split line */
snprintf(lockname, CF_BUFSIZE - 1, "column-%s-%s", pp->promiser, edcontext->filename);
thislock = AcquireLock(ctx, lockname, VUQNAME, CFSTARTTIME, a.transaction.ifelapsed, a.transaction.expireafter, pp, true);
if (thislock.lock == NULL)
{
return PROMISE_RESULT_SKIPPED;
}
if (EditColumns(ctx, begin_ptr, end_ptr, &a, pp, edcontext, &result))
{
(edcontext->num_edits)++;
}
switch(result)
{
case PROMISE_RESULT_NOOP:
cfPS(ctx, LOG_LEVEL_VERBOSE, result, pp, &a,
"No changes done for the fields_edit promise '%s'", pp->promiser);
break;
case PROMISE_RESULT_CHANGE:
cfPS(ctx, LOG_LEVEL_INFO, result, pp, &a,
"fields_edit promise '%s' repaired", pp->promiser);
break;
case PROMISE_RESULT_WARN:
cfPS(ctx, LOG_LEVEL_WARNING, result, pp, &a,
"Warnings encountered when actuating fields_edit promise '%s'", pp->promiser);
break;
default:
cfPS(ctx, LOG_LEVEL_ERR, result, pp, &a,
"Errors encountered when actuating fields_edit promise '%s'", pp->promiser);
break;
}
YieldCurrentLock(thislock);
return result;
}
/***************************************************************************/
static PromiseResult VerifyPatterns(EvalContext *ctx, const Promise *pp, EditContext *edcontext)
{
assert(pp != NULL);
assert(edcontext != NULL);
Item **start = &(edcontext->file_start);
Item *begin_ptr, *end_ptr;
CfLock thislock;
char lockname[CF_BUFSIZE];
Log(LOG_LEVEL_VERBOSE, "Looking at pattern '%s'", pp->promiser);
/* Are we working in a restricted region? */
Attributes a = GetReplaceAttributes(ctx, pp);
a.transaction.ifelapsed = CF_EDIT_IFELAPSED;
if (!a.replace.replace_value)
{
cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_FAIL, pp, &a,
"The promised pattern replace '%s' has no replacement string", pp->promiser);
return PROMISE_RESULT_FAIL;
}
PromiseResult result = PROMISE_RESULT_NOOP;
if (!a.haveregion)
{
begin_ptr = *start;
end_ptr = NULL; //EndOfList(*start);
}
else if (!SelectRegion(ctx, *start, &begin_ptr, &end_ptr, &a, edcontext))
{
cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_INTERRUPTED, pp, &a,
"The promised pattern replace '%s' could not select an edit region in '%s'",
pp->promiser, edcontext->filename);
result = PromiseResultUpdate(result, PROMISE_RESULT_INTERRUPTED);
return result;
}
snprintf(lockname, CF_BUFSIZE - 1, "replace-%s-%s", pp->promiser, edcontext->filename);
thislock = AcquireLock(ctx, lockname, VUQNAME, CFSTARTTIME, a.transaction.ifelapsed, a.transaction.expireafter, pp, true);
if (thislock.lock == NULL)
{
return PROMISE_RESULT_SKIPPED;
}
/* Make sure back references are expanded */
if (ReplacePatterns(ctx, begin_ptr, end_ptr, &a, pp, edcontext, &result))
{
(edcontext->num_edits)++;
}
EvalContextVariableClearMatch(ctx);
switch(result)
{
case PROMISE_RESULT_NOOP:
cfPS(ctx, LOG_LEVEL_VERBOSE, result, pp, &a,
"No changes done for the replace_patterns promise '%s'", pp->promiser);
break;
case PROMISE_RESULT_CHANGE:
cfPS(ctx, LOG_LEVEL_INFO, result, pp, &a,
"replace_patterns promise '%s' repaired", pp->promiser);
break;
case PROMISE_RESULT_WARN:
cfPS(ctx, LOG_LEVEL_WARNING, result, pp, &a,
"Warnings encountered when actuating replace_patterns promise '%s'", pp->promiser);
break;
default:
cfPS(ctx, LOG_LEVEL_ERR, result, pp, &a,
"Errors encountered when actuating replace_patterns promise '%s'", pp->promiser);
break;
}
YieldCurrentLock(thislock);
return result;
}
/***************************************************************************/
static bool SelectNextItemMatching(EvalContext *ctx, const char *regexp, Item *begin, Item *end, Item **match, Item **prev)
{
Item *ip_prev = NULL;
*match = NULL;
*prev = NULL;
for (Item *ip = begin; ip != end; ip = ip->next)
{
if (ip->name == NULL)
{
continue;
}
if (FullTextMatch(ctx, regexp, ip->name))
{
*match = ip;
*prev = ip_prev;
return true;
}
ip_prev = ip;
}
return false;
}
/***************************************************************************/
static bool SelectLastItemMatching(EvalContext *ctx, const char *regexp, Item *begin, Item *end, Item **match, Item **prev)
{
assert(match != NULL);
assert(prev != NULL);
Item *ip, *ip_last = NULL, *ip_prev = NULL;
*match = NULL;
*prev = NULL;
for (ip = begin; ip != end; ip = ip->next)
{
if (ip->name == NULL)
{
continue;
}
if (FullTextMatch(ctx, regexp, ip->name))
{
*prev = ip_prev;
ip_last = ip;
}
ip_prev = ip;
}
if (ip_last)
{
*match = ip_last;
return true;
}
return false;
}
/***************************************************************************/
static bool SelectItemMatching(EvalContext *ctx, Item *start, char *regex, Item *begin_ptr, Item *end_ptr, Item **match, Item **prev, char *fl)
{
assert(match != NULL);
assert(prev != NULL);
Item *ip;
bool ret = false;
*match = NULL;
*prev = NULL;
if (regex == NULL)
{
return false;
}
if (StringEqual(fl, "first"))
{
if (SelectNextItemMatching(ctx, regex, begin_ptr, end_ptr, match, prev))
{
ret = true;
}
}
else
{
if (SelectLastItemMatching(ctx, regex, begin_ptr, end_ptr, match, prev))
{
ret = true;
}
}
if ((*match != NULL) && (*prev == NULL))
{
for (ip = start; (ip != NULL) && (ip != *match); ip = ip->next)
{
*prev = ip;
}
}
return ret;
}
/***************************************************************************/
static PromiseResult VerifyLineInsertions(EvalContext *ctx, const Promise *pp, EditContext *edcontext)
{
assert(pp != NULL);
assert(edcontext != NULL);
Item **start = &(edcontext->file_start), *match, *prev;
Item *begin_ptr, *end_ptr;
CfLock thislock;
char lockname[CF_BUFSIZE];
Attributes a = GetInsertionAttributes(ctx, pp);
int allow_multi_lines = StringEqual(a.sourcetype, "preserve_all_lines");
a.transaction.ifelapsed = CF_EDIT_IFELAPSED;
if (!SanityCheckInsertions(&a))
{
cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_FAIL, pp, &a,
"The promised line insertion '%s' breaks its own promises", pp->promiser);
return PROMISE_RESULT_FAIL;
}
/* Are we working in a restricted region? */
PromiseResult result = PROMISE_RESULT_NOOP;
if (!a.haveregion)
{
begin_ptr = *start;
end_ptr = NULL; //EndOfList(*start);
}
else if (!SelectRegion(ctx, *start, &begin_ptr, &end_ptr, &a, edcontext))
{
cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_INTERRUPTED, pp, &a,
"The promised line insertion '%s' could not select an edit region in '%s'",
pp->promiser, edcontext->filename);
result = PromiseResultUpdate(result, PROMISE_RESULT_INTERRUPTED);
return result;
}
if (!end_ptr && a.region.select_end && !a.region.select_end_match_eof)
{
cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_INTERRUPTED, pp, &a,
"The promised end pattern '%s' was not found when selecting region to insert in '%s'",
a.region.select_end, edcontext->filename);
result = PromiseResultUpdate(result, PROMISE_RESULT_INTERRUPTED);
return result;
}
if (allow_multi_lines)
{
// promise to insert duplicates on first pass only
snprintf(lockname, CF_BUFSIZE - 1, "insertline-%s-%s-%lu", pp->promiser, edcontext->filename, (long unsigned int) pp->offset.line);
}
else
{
snprintf(lockname, CF_BUFSIZE - 1, "insertline-%s-%s", pp->promiser, edcontext->filename);
}
thislock = AcquireLock(ctx, lockname, VUQNAME, CFSTARTTIME, a.transaction.ifelapsed, a.transaction.expireafter, pp, true);
if (thislock.lock == NULL)
{
return PROMISE_RESULT_SKIPPED;
}
/* Are we looking for an anchored line inside the region? */
if (a.location.line_matching == NULL)
{
if (InsertMultipleLinesToRegion(ctx, start, begin_ptr, end_ptr, &a, pp, edcontext, &result))
{
(edcontext->num_edits)++;
}
}
else
{
if (!SelectItemMatching(ctx, *start, a.location.line_matching, begin_ptr, end_ptr, &match, &prev, a.location.first_last))
{
cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_INTERRUPTED, pp, &a,
"The promised line insertion '%s' could not select a locator matching regex '%s' in '%s'",
pp->promiser, a.location.line_matching, edcontext->filename);
result = PromiseResultUpdate(result, PROMISE_RESULT_INTERRUPTED);
YieldCurrentLock(thislock);
return result;
}
if (InsertMultipleLinesAtLocation(ctx, start, begin_ptr, end_ptr, match, prev, &a, pp, edcontext, &result))
{
(edcontext->num_edits)++;
}
}
switch(result)
{
case PROMISE_RESULT_NOOP:
cfPS(ctx, LOG_LEVEL_VERBOSE, result, pp, &a,
"No changes done for the insert_lines promise '%s'", pp->promiser);
break;
case PROMISE_RESULT_CHANGE:
cfPS(ctx, LOG_LEVEL_INFO, result, pp, &a,
"insert_lines promise '%s' repaired", pp->promiser);
break;
case PROMISE_RESULT_WARN:
cfPS(ctx, LOG_LEVEL_WARNING, result, pp, &a,
"Warnings encountered when actuating insert_lines promise '%s'", pp->promiser);
break;
default:
cfPS(ctx, LOG_LEVEL_ERR, result, pp, &a,
"Errors encountered when actuating insert_lines promise '%s'", pp->promiser);
break;
}
YieldCurrentLock(thislock);
return result;
}
/***************************************************************************/
/* Level */
/***************************************************************************/
static bool SelectRegion(EvalContext *ctx, Item *start,
Item **begin_ptr, Item **end_ptr,
const Attributes *a, EditContext *edcontext)
/*
This should provide pointers to the first and last line of text that include the
delimiters, since we need to include those in case they are being deleted, etc.
It returns true if a match was identified, else false.
If no such region matches, begin_ptr and end_ptr should point to NULL
*/
{
assert(a != NULL);
assert(edcontext != NULL);
assert(begin_ptr != NULL);
assert(end_ptr != NULL);
const char *const select_start = a->region.select_start;
const char *const select_end = a->region.select_end;
const int include_start = a->region.include_start;
Item *ip, *beg = NULL, *end = NULL;
for (ip = start; ip != NULL; ip = ip->next)
{
if (select_start)
{
if (!beg && FullTextMatch(ctx, select_start, ip->name))
{
if (!include_start)
{
if (ip->next == NULL)
{
Log(LOG_LEVEL_VERBOSE,
"The promised start pattern '%s' found an empty region at the end of file '%s'",
select_start, edcontext->filename);
return false;
}
}
beg = ip;
continue;
}
}
if (select_end && beg)
{
if (!end && FullTextMatch(ctx, select_end, ip->name))
{
end = ip;
break;
}
}
if (beg && end)
{
break;
}
}
if (!beg && select_start)
{
Log(LOG_LEVEL_VERBOSE,
"The promised start pattern '%s' was not found when selecting edit region in '%s'",
select_start, edcontext->filename);
return false;
}
*begin_ptr = beg;
*end_ptr = end;
return true;
}
/*****************************************************************************/
static int MatchRegion(EvalContext *ctx, const char *chunk, const Item *begin, const Item *end, bool regex)
/*
Match a region in between the selection delimiters. It is
called after SelectRegion. The end delimiter will be visible
here so we have to check for it. Can handle multi-line chunks
*/
{
const Item *ip = begin;
const size_t chunk_len = strlen(chunk);
size_t buf_size = chunk_len + 1;
char *buf = xmalloc(buf_size);
int lines = 0;
for (const char *sp = chunk; sp <= chunk + chunk_len; sp++)
{
buf[0] = '\0';
sscanf(sp, "%[^\n]", buf);
sp += strlen(buf);
if (ip == NULL)
{
lines = 0;
goto bad;
}
if (!regex && !StringEqual(buf, ip->name))
{
lines = 0;
goto bad;
}
if (regex && !FullTextMatch(ctx, buf, ip->name))
{
lines = 0;
goto bad;
}
lines++;
// We have to manually exclude the marked terminator
if (ip == end)
{
lines = 0;
goto bad;
}
// Now see if there is more
if (ip->next)
{
ip = ip->next;
}
else // if the region runs out before the end
{
if (++sp <= chunk + chunk_len)
{
lines = 0;
goto bad;
}