Repository navigation
Expand file tree
/
Copy pathstore.c
More file actions
837 lines (771 loc) · 27.7 KB
/
Copy pathstore.c
File metadata and controls
837 lines (771 loc) · 27.7 KB
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
#define _POSIX_C_SOURCE 200809L
#include "store.h"
#include "blake3.h"
#include "print.h"
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <stdatomic.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#define STIGI_CACHE_MAGIC "STGCACHE"
#define STIGI_CACHE_VERSION 2U
static void hex64(const uint8_t id[32], char out[65]) {
static const char H[] = "0123456789abcdef";
for (int i = 0; i < 32; i++) {
out[i * 2] = H[(id[i] >> 4) & 0x0f];
out[i * 2 + 1] = H[id[i] & 0x0f];
}
out[64] = '\0';
}
static bool is_hex64(const char *s, size_t len) {
if (len != 64U) return false;
for (size_t i = 0; i < 64U; i++) {
char c = s[i];
if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'))) return false;
}
return true;
}
static const char *unit_kind_str(StigiDeclKind k) {
switch (k) {
case STIGI_DECL_ENUM: return "Enum";
case STIGI_DECL_TYPE: return "Type";
case STIGI_DECL_DEF: return "Def";
case STIGI_DECL_LEMMA_DEF: return "Lemma";
case STIGI_DECL_VAL: return "Val";
case STIGI_DECL_CAPABILITY: return "Capability";
case STIGI_DECL_HANDLER: return "Handler";
case STIGI_DECL_TRAIT: return "Trait";
case STIGI_DECL_GIVEN: return "Given";
case STIGI_DECL_EXTERN: return "Extern";
case STIGI_DECL_RELATION: return "Relation";
case STIGI_DECL_RULE: return "Rule";
case STIGI_DECL_TEST: return "Test";
case STIGI_DECL_NEG_TEST: return "NegTest";
}
return "Unknown";
}
static bool is_valid_kind_str(const char *s, size_t len) {
static const char *const KINDS[] = {
"Enum", "Type", "Def", "Lemma", "Val", "Capability",
"Handler", "Trait", "Given", "Extern", "Relation", "Rule", "Test", "NegTest"
};
for (size_t i = 0; i < sizeof(KINDS) / sizeof(KINDS[0]); i++) {
if (strlen(KINDS[i]) == len && memcmp(KINDS[i], s, len) == 0) return true;
}
return false;
}
static bool is_safe_unit_name(const char *name, size_t len) {
if (name == NULL || len == 0) return false;
if (name[0] == '.' || name[len - 1U] == '.') return false;
for (size_t i = 0; i < len; i++) {
unsigned char c = (unsigned char)name[i];
if (c == '/' || c == '\\' || c < 0x20U || c == 0x7FU) return false;
if (c == '.' && i + 1U < len && name[i + 1U] == '.') return false;
}
return true;
}
static int cmp_unit_name(const void *pa, const void *pb) {
const StigiImageUnit *a = *(const StigiImageUnit *const *)pa;
const StigiImageUnit *b = *(const StigiImageUnit *const *)pb;
return strcmp(a->name, b->name);
}
static int cmp_key32(const void *pa, const void *pb) {
return memcmp(pa, pb, 32U);
}
static void put_u32_le(uint8_t *p, uint32_t v) {
p[0] = (uint8_t)(v & 0xFFU);
p[1] = (uint8_t)((v >> 8) & 0xFFU);
p[2] = (uint8_t)((v >> 16) & 0xFFU);
p[3] = (uint8_t)((v >> 24) & 0xFFU);
}
static uint32_t get_u32_le(const uint8_t *p) {
return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}
static Status ensure_parent_dirs(const char *path, char *err_buf, size_t err_cap) {
if (path == NULL) {
if (err_buf != NULL && err_cap > 0) (void)snprintf(err_buf, err_cap, "null path");
return STIGI_ERR_INVALID;
}
size_t len = strlen(path);
if (len == 0 || len >= 1024U) {
if (err_buf != NULL && err_cap > 0) (void)snprintf(err_buf, err_cap, "invalid path length");
return STIGI_ERR_INVALID;
}
char tmp[1024];
memcpy(tmp, path, len + 1U);
for (char *p = tmp + 1; *p != '\0'; p++) {
if (*p == '/') {
*p = '\0';
if (mkdir(tmp, 0755) != 0 && errno != EEXIST) {
if (err_buf != NULL && err_cap > 0) {
(void)snprintf(err_buf, err_cap, "cannot create directory '%s'", tmp);
}
return STIGI_ERR_IO;
}
*p = '/';
}
}
return STIGI_OK;
}
static atomic_uint_fast64_t g_tmp_seq = 0;
static Status atomic_write_file(const char *path, const void *data, size_t len,
char *err_buf, size_t err_cap) {
char tmp_path[1100];
uint64_t seq = (uint64_t)atomic_fetch_add(&g_tmp_seq, 1U) + 1ULL;
int tn = snprintf(tmp_path, sizeof tmp_path, "%s.tmp.%ld.%llu",
path, (long)getpid(), (unsigned long long)seq);
if (tn < 0 || (size_t)tn >= sizeof tmp_path) {
if (err_buf != NULL && err_cap > 0) (void)snprintf(err_buf, err_cap, "path too long");
return STIGI_ERR_INVALID;
}
int fd = open(tmp_path, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0644);
if (fd < 0) {
if (err_buf != NULL && err_cap > 0) {
(void)snprintf(err_buf, err_cap, "cannot create temp file '%s'", tmp_path);
}
return STIGI_ERR_IO;
}
FILE *f = fdopen(fd, "wb");
if (f == NULL) {
(void)close(fd);
(void)unlink(tmp_path);
if (err_buf != NULL && err_cap > 0) {
(void)snprintf(err_buf, err_cap, "fdopen failed for '%s'", tmp_path);
}
return STIGI_ERR_IO;
}
if (len > 0 && fwrite(data, 1, len, f) != len) {
(void)fclose(f);
(void)unlink(tmp_path);
if (err_buf != NULL && err_cap > 0) {
(void)snprintf(err_buf, err_cap, "write failed for '%s'", path);
}
return STIGI_ERR_IO;
}
if (fflush(f) != 0 || fsync(fileno(f)) != 0) {
(void)fclose(f);
(void)unlink(tmp_path);
if (err_buf != NULL && err_cap > 0) {
(void)snprintf(err_buf, err_cap, "fsync failed for '%s'", path);
}
return STIGI_ERR_IO;
}
if (fclose(f) != 0) {
(void)unlink(tmp_path);
if (err_buf != NULL && err_cap > 0) {
(void)snprintf(err_buf, err_cap, "fclose failed for '%s'", path);
}
return STIGI_ERR_IO;
}
if (rename(tmp_path, path) != 0) {
(void)unlink(tmp_path);
if (err_buf != NULL && err_cap > 0) {
(void)snprintf(err_buf, err_cap, "rename failed for '%s'", path);
}
return STIGI_ERR_IO;
}
return STIGI_OK;
}
typedef struct {
char **paths;
uint32_t count;
uint32_t cap;
} PathList;
static void pathlist_free(PathList *pl) {
for (uint32_t i = 0; i < pl->count; i++) free(pl->paths[i]);
free(pl->paths);
pl->paths = NULL;
pl->count = 0;
pl->cap = 0;
}
static Status pathlist_push(PathList *pl, const char *path, Diag *diag) {
if (pl->count == pl->cap) {
uint32_t ncap = pl->cap == 0 ? 16U : pl->cap * 2U;
if (ncap <= pl->cap) return diag_set(diag, STIGI_ERR_OVERFLOW, -1, "pathlist overflow");
char **np = realloc(pl->paths, (size_t)ncap * sizeof *np);
if (np == NULL) return diag_set(diag, STIGI_ERR_OOM, -1, "OOM");
pl->paths = np;
pl->cap = ncap;
}
size_t clen = strlen(path);
pl->paths[pl->count] = malloc(clen + 1U);
if (pl->paths[pl->count] == NULL) return diag_set(diag, STIGI_ERR_OOM, -1, "OOM");
memcpy(pl->paths[pl->count], path, clen + 1U);
pl->count++;
return STIGI_OK;
}
static Status collect_sc_files(const char *dir, PathList *pl, Diag *diag) {
DIR *dp = opendir(dir);
if (dp == NULL) {
return diag_set(diag, STIGI_ERR_IO, errno, "cannot open directory '%s'", dir);
}
struct dirent *ent;
Status st = STIGI_OK;
while ((ent = readdir(dp)) != NULL && st == STIGI_OK) {
if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue;
char child[1024];
int cn = snprintf(child, sizeof child, "%s/%s", dir, ent->d_name);
if (cn < 0 || (size_t)cn >= sizeof child) {
st = diag_set(diag, STIGI_ERR_INVALID, -1, "path too long under '%s'", dir);
break;
}
struct stat cst;
if (lstat(child, &cst) != 0) continue;
if (S_ISLNK(cst.st_mode)) continue; /* never follow symlinks */
if (S_ISDIR(cst.st_mode)) {
st = collect_sc_files(child, pl, diag);
} else if (S_ISREG(cst.st_mode)) {
size_t n = strlen(ent->d_name);
if (n > 3U && strcmp(ent->d_name + n - 3U, ".sc") == 0) {
st = pathlist_push(pl, child, diag);
}
}
}
(void)closedir(dp);
return st;
}
static Status read_whole_file(const char *path, char **out_buf, size_t *out_len, Diag *diag) {
int fd = open(path, O_RDONLY | O_NOFOLLOW);
if (fd < 0) {
return diag_set(diag, STIGI_ERR_IO, errno, "cannot read '%s'", path);
}
struct stat fst;
if (fstat(fd, &fst) != 0 || !S_ISREG(fst.st_mode)) {
(void)close(fd);
return diag_set(diag, STIGI_ERR_INVALID, -1, "'%s' is not a regular file", path);
}
FILE *f = fdopen(fd, "rb");
if (f == NULL) {
(void)close(fd);
return diag_set(diag, STIGI_ERR_IO, errno, "fdopen failed on '%s'", path);
}
if (fseek(f, 0, SEEK_END) != 0) {
(void)fclose(f);
return diag_set(diag, STIGI_ERR_IO, errno, "fseek failed on '%s'", path);
}
long sz = ftell(f);
if (sz < 0) {
(void)fclose(f);
return diag_set(diag, STIGI_ERR_IO, errno, "ftell failed on '%s'", path);
}
if (fseek(f, 0, SEEK_SET) != 0) {
(void)fclose(f);
return diag_set(diag, STIGI_ERR_IO, errno, "fseek rewind failed on '%s'", path);
}
char *buf = malloc((size_t)sz + 1U);
if (buf == NULL) {
(void)fclose(f);
return diag_set(diag, STIGI_ERR_OOM, -1, "OOM");
}
size_t nr = sz > 0 ? fread(buf, 1, (size_t)sz, f) : 0U;
if (nr != (size_t)sz || ferror(f)) {
free(buf);
(void)fclose(f);
return diag_set(diag, STIGI_ERR_IO, errno, "fread failed on '%s'", path);
}
if (fclose(f) != 0) {
free(buf);
return diag_set(diag, STIGI_ERR_IO, errno, "fclose failed on '%s'", path);
}
buf[nr] = '\0';
*out_buf = buf;
*out_len = nr;
return STIGI_OK;
}
/* Cache file v2: magic, version, verdict key count, test key count, decision record count, the sorted verdict
* keys, the sorted test keys, the decision records (key, access count, four relation counts, one masked byte per
* access row; sorted by key), BLAKE3 of all that (S132, S134 e). */
#define STIGI_CACHE_DECISION_FIXED (32U + 6U * 4U)
static Status write_cache_file(const StigiDoor *door, const char *dir,
char *err_buf, size_t err_cap) {
uint32_t vcnt = door->verdict_cache.count;
uint32_t tcnt = door->test_cache.count;
uint32_t dcnt = door->decisions.count;
size_t total_keys = (size_t)vcnt + (size_t)tcnt;
size_t dec_len = 0;
for (uint32_t i = 0; i < dcnt; i++) {
dec_len += STIGI_CACHE_DECISION_FIXED + door->decisions.recs[i].dec.access_count;
}
size_t payload_len = 8U + 4U + 4U + 4U + 4U + total_keys * 32U + dec_len;
size_t total_len = payload_len + 32U;
uint8_t *buf = malloc(total_len);
if (buf == NULL) return STIGI_ERR_OOM;
memcpy(buf, STIGI_CACHE_MAGIC, 8U);
put_u32_le(buf + 8U, STIGI_CACHE_VERSION);
put_u32_le(buf + 12U, vcnt);
put_u32_le(buf + 16U, tcnt);
put_u32_le(buf + 20U, dcnt);
uint8_t *vptr = buf + 24U;
uint32_t vi = 0;
for (uint32_t i = 0; i < door->verdict_cache.cap && vi < vcnt; i++) {
if (door->verdict_cache.slots[i].used) {
memcpy(vptr + (size_t)vi * 32U, door->verdict_cache.slots[i].key, 32U);
vi++;
}
}
if (vcnt > 1U) qsort(vptr, vcnt, 32U, cmp_key32);
uint8_t *tptr = vptr + (size_t)vcnt * 32U;
uint32_t ti = 0;
for (uint32_t i = 0; i < door->test_cache.cap && ti < tcnt; i++) {
if (door->test_cache.slots[i].used) {
memcpy(tptr + (size_t)ti * 32U, door->test_cache.slots[i].key, 32U);
ti++;
}
}
if (tcnt > 1U) qsort(tptr, tcnt, 32U, cmp_key32);
uint8_t *dptr = tptr + (size_t)tcnt * 32U;
for (uint32_t i = 0; i < dcnt; i++) {
const StigiDecisionRec *r = &door->decisions.recs[i];
memcpy(dptr, r->key, 32U);
put_u32_le(dptr + 32U, r->dec.access_count);
put_u32_le(dptr + 36U, r->dec.tracked);
put_u32_le(dptr + 40U, r->dec.free_edges);
put_u32_le(dptr + 44U, r->dec.free_at_exit);
put_u32_le(dptr + 48U, r->dec.reuses);
put_u32_le(dptr + 52U, r->dec.stack_objects);
if (r->dec.access_count > 0) memcpy(dptr + STIGI_CACHE_DECISION_FIXED, r->dec.masked, r->dec.access_count);
dptr += STIGI_CACHE_DECISION_FIXED + r->dec.access_count;
}
blake3_hash(buf, payload_len, buf + payload_len);
char cache_path[1024];
int cn = snprintf(cache_path, sizeof cache_path, "%s/cache", dir);
if (cn < 0 || (size_t)cn >= sizeof cache_path) {
free(buf);
if (err_buf != NULL && err_cap > 0) (void)snprintf(err_buf, err_cap, "cache path too long");
return STIGI_ERR_INVALID;
}
Status st = atomic_write_file(cache_path, buf, total_len, err_buf, err_cap);
free(buf);
return st;
}
static int cmp_cstr(const void *pa, const void *pb) {
return strcmp(*(const char *const *)pa, *(const char *const *)pb);
}
static bool sorted_path_contains(char *const *paths, uint32_t count, const char *key) {
uint32_t lo = 0, hi = count;
while (lo < hi) {
uint32_t mid = lo + (hi - lo) / 2U;
int c = strcmp(paths[mid], key);
if (c == 0) return true;
if (c < 0) lo = mid + 1U;
else hi = mid;
}
return false;
}
static bool unit_selected(const char *name, const char *const *names, uint32_t name_count) {
if (name_count == 0 || names == NULL) return true;
for (uint32_t i = 0; i < name_count; i++) {
if (names[i] != NULL && strcmp(name, names[i]) == 0) return true;
}
return false;
}
Status stigi_store_dir_subset(const StigiDoor *door, const char *dir,
const char *const *names, uint32_t name_count,
char *err_buf, size_t err_cap) {
if (door == NULL || dir == NULL || dir[0] == '\0') {
if (err_buf != NULL && err_cap > 0) (void)snprintf(err_buf, err_cap, "invalid arguments");
return STIGI_ERR_INVALID;
}
/* Validate named subset entries exist in image before writing anything */
for (uint32_t i = 0; i < name_count; i++) {
if (names[i] == NULL ||
stigi_image_find(&door->image, names[i], strlen(names[i])) < 0) {
if (err_buf != NULL && err_cap > 0) {
(void)snprintf(err_buf, err_cap, "unknown unit '%s'", names[i] ? names[i] : "");
}
return STIGI_ERR_INVALID;
}
}
/* door.md:124: missing directory is a typed error (never auto-create dir) */
struct stat st_dir;
if (stat(dir, &st_dir) != 0 || !S_ISDIR(st_dir.st_mode)) {
if (err_buf != NULL && err_cap > 0) {
(void)snprintf(err_buf, err_cap, "store directory does not exist or is not a directory: '%s'", dir);
}
return STIGI_ERR_IO;
}
/* Collect existing .sc files so stale files can be pruned when storing full image */
PathList old_files = {NULL, 0, 0};
if (name_count == 0) {
Diag tmp_diag;
diag_clear(&tmp_diag);
Status col_st = collect_sc_files(dir, &old_files, &tmp_diag);
if (col_st != STIGI_OK) {
pathlist_free(&old_files);
if (err_buf != NULL && err_cap > 0) (void)snprintf(err_buf, err_cap, "%s", tmp_diag.msg);
return col_st;
}
}
const StigiImage *img = &door->image;
const StigiImageUnit **sorted = NULL;
uint32_t sel_count = 0;
if (img->unit_count > 0) {
sorted = malloc((size_t)img->unit_count * sizeof *sorted);
if (sorted == NULL) {
pathlist_free(&old_files);
return STIGI_ERR_OOM;
}
for (uint32_t i = 0; i < img->unit_count; i++) {
if (unit_selected(img->units[i].name, names, name_count)) {
sorted[sel_count++] = &img->units[i];
}
}
if (sel_count > 1U) qsort(sorted, sel_count, sizeof *sorted, cmp_unit_name);
}
size_t idx_cap = 1024U;
size_t idx_len = 0;
char *idx_buf = malloc(idx_cap);
if (idx_buf == NULL) {
free(sorted);
pathlist_free(&old_files);
return STIGI_ERR_OOM;
}
idx_buf[0] = '\0';
PathList written_files = {NULL, 0, 0};
Arena tmp;
arena_init(&tmp);
Status res = STIGI_OK;
for (uint32_t i = 0; i < sel_count && res == STIGI_OK; i++) {
const StigiImageUnit *u = sorted[i];
if (!is_safe_unit_name(u->name, u->name_len)) {
if (err_buf != NULL && err_cap > 0) {
(void)snprintf(err_buf, err_cap, "unsafe unit name '%s'", u->name);
}
res = STIGI_ERR_INVALID;
break;
}
char rel[512];
if (u->name_len + 4U > sizeof rel) {
if (err_buf != NULL && err_cap > 0) (void)snprintf(err_buf, err_cap, "unit name too long");
res = STIGI_ERR_INVALID;
break;
}
for (size_t k = 0; k < u->name_len; k++) {
rel[k] = u->name[k] == '.' ? '/' : u->name[k];
}
memcpy(rel + u->name_len, ".sc", 4U);
char fpath[1024];
int fn = snprintf(fpath, sizeof fpath, "%s/%s", dir, rel);
if (fn < 0 || (size_t)fn >= sizeof fpath) {
if (err_buf != NULL && err_cap > 0) (void)snprintf(err_buf, err_cap, "unit path too long");
res = STIGI_ERR_INVALID;
break;
}
res = ensure_parent_dirs(fpath, err_buf, err_cap);
if (res != STIGI_OK) break;
arena_reset(&tmp);
char *printed = NULL;
size_t plen = 0;
Diag d;
diag_clear(&d);
res = stigi_print_unit(u->ast, &printed, &plen, &tmp, &d);
if (res != STIGI_OK) {
if (err_buf != NULL && err_cap > 0) (void)snprintf(err_buf, err_cap, "%s", d.msg);
break;
}
res = atomic_write_file(fpath, printed, plen, err_buf, err_cap);
if (res != STIGI_OK) break;
res = pathlist_push(&written_files, fpath, &d);
if (res != STIGI_OK) {
if (err_buf != NULL && err_cap > 0) (void)snprintf(err_buf, err_cap, "%s", d.msg);
break;
}
char h[65];
hex64(u->unit_id, h);
const char *kstr = unit_kind_str(u->ast->decl->kind);
char line[512];
int ln = snprintf(line, sizeof line, "%s\t%s\t%s\n", u->name, h, kstr);
if (ln < 0 || (size_t)ln >= sizeof line) {
if (err_buf != NULL && err_cap > 0) (void)snprintf(err_buf, err_cap, "index line too long");
res = STIGI_ERR_INVALID;
break;
}
if (idx_len + (size_t)ln + 1U > idx_cap) {
while (idx_len + (size_t)ln + 1U > idx_cap) {
if (idx_cap > SIZE_MAX / 2U) { res = STIGI_ERR_OOM; break; }
idx_cap *= 2U;
}
if (res != STIGI_OK) break;
char *nb = realloc(idx_buf, idx_cap);
if (nb == NULL) { res = STIGI_ERR_OOM; break; }
idx_buf = nb;
}
memcpy(idx_buf + idx_len, line, (size_t)ln);
idx_len += (size_t)ln;
idx_buf[idx_len] = '\0';
}
if (res == STIGI_OK && name_count == 0) {
char idx_path[1024];
int in = snprintf(idx_path, sizeof idx_path, "%s/index", dir);
if (in < 0 || (size_t)in >= sizeof idx_path) {
if (err_buf != NULL && err_cap > 0) (void)snprintf(err_buf, err_cap, "index path too long");
res = STIGI_ERR_INVALID;
} else {
res = atomic_write_file(idx_path, idx_buf, idx_len, err_buf, err_cap);
}
}
if (res == STIGI_OK && name_count == 0) {
res = write_cache_file(door, dir, err_buf, err_cap);
}
/* O(N log N) prune of stale .sc files when storing a non-empty full image */
if (res == STIGI_OK && name_count == 0 && old_files.count > 0 && door->image.unit_count > 0) {
if (written_files.count > 1U) {
qsort(written_files.paths, written_files.count, sizeof *written_files.paths, cmp_cstr);
}
for (uint32_t i = 0; i < old_files.count; i++) {
if (!sorted_path_contains(written_files.paths, written_files.count, old_files.paths[i])) {
(void)unlink(old_files.paths[i]);
}
}
}
free(idx_buf);
arena_free(&tmp);
free(sorted);
pathlist_free(&written_files);
pathlist_free(&old_files);
return res;
}
Status stigi_store_dir(const StigiDoor *door, const char *dir,
char *err_buf, size_t err_cap) {
return stigi_store_dir_subset(door, dir, NULL, 0, err_buf, err_cap);
}
static Status verify_index_file(const char *dir, Diag *diag) {
char idx_path[1024];
int in = snprintf(idx_path, sizeof idx_path, "%s/index", dir);
if (in < 0 || (size_t)in >= sizeof idx_path) {
return diag_set(diag, STIGI_ERR_INVALID, -1, "index path too long");
}
struct stat st;
if (lstat(idx_path, &st) != 0) {
if (errno == ENOENT) return STIGI_OK;
return diag_set(diag, STIGI_ERR_IO, errno, "cannot stat index '%s'", idx_path);
}
if (!S_ISREG(st.st_mode)) {
return diag_set(diag, STIGI_ERR_INVALID, -1, "index '%s' is not a regular file", idx_path);
}
char *buf = NULL;
size_t len = 0;
Status rs = read_whole_file(idx_path, &buf, &len, diag);
if (rs != STIGI_OK) return rs;
if (memchr(buf, '\0', len) != NULL) {
free(buf);
return diag_set(diag, STIGI_ERR_INVALID, -1, "corrupt index: embedded NUL byte");
}
const char *p = buf;
const char *end = buf + len;
while (p < end) {
const char *nl = memchr(p, '\n', (size_t)(end - p));
if (nl == NULL) {
free(buf);
return diag_set(diag, STIGI_ERR_INVALID, -1, "corrupt index: unterminated line");
}
const char *t1 = memchr(p, '\t', (size_t)(nl - p));
if (t1 == NULL) {
free(buf);
return diag_set(diag, STIGI_ERR_INVALID, -1, "corrupt index: missing tab");
}
const char *t2 = memchr(t1 + 1, '\t', (size_t)(nl - (t1 + 1)));
if (t2 == NULL) {
free(buf);
return diag_set(diag, STIGI_ERR_INVALID, -1, "corrupt index: missing second tab");
}
if (!is_safe_unit_name(p, (size_t)(t1 - p)) ||
!is_hex64(t1 + 1, (size_t)(t2 - (t1 + 1))) ||
!is_valid_kind_str(t2 + 1, (size_t)(nl - (t2 + 1)))) {
free(buf);
return diag_set(diag, STIGI_ERR_INVALID, -1, "corrupt index: invalid entry format");
}
p = nl + 1;
}
free(buf);
return STIGI_OK;
}
static Status load_and_verify_cache(StigiDoor *door, const char *dir, Diag *diag) {
char cache_path[1024];
int cn = snprintf(cache_path, sizeof cache_path, "%s/cache", dir);
if (cn < 0 || (size_t)cn >= sizeof cache_path) {
return diag_set(diag, STIGI_ERR_INVALID, -1, "cache path too long");
}
struct stat st;
if (lstat(cache_path, &st) != 0) {
if (errno == ENOENT) return STIGI_OK;
return diag_set(diag, STIGI_ERR_IO, errno, "cannot stat cache '%s'", cache_path);
}
if (!S_ISREG(st.st_mode)) {
return diag_set(diag, STIGI_ERR_INVALID, -1, "cache '%s' is not a regular file", cache_path);
}
char *buf = NULL;
size_t len = 0;
Status rs = read_whole_file(cache_path, &buf, &len, diag);
if (rs != STIGI_OK) return rs;
if (len < 24U + 32U) {
free(buf);
return diag_set(diag, STIGI_ERR_INVALID, -1, "corrupt cache: file too short");
}
const uint8_t *u = (const uint8_t *)buf;
if (memcmp(u, STIGI_CACHE_MAGIC, 8U) != 0) {
free(buf);
return diag_set(diag, STIGI_ERR_INVALID, -1, "corrupt cache: invalid magic");
}
uint32_t ver = get_u32_le(u + 8U);
if (ver < STIGI_CACHE_VERSION) { /* an older derived format is no cache: everything is computed again */
free(buf);
return STIGI_OK;
}
if (ver != STIGI_CACHE_VERSION) {
free(buf);
return diag_set(diag, STIGI_ERR_INVALID, -1, "corrupt cache: unsupported version %u", ver);
}
uint32_t vcnt = get_u32_le(u + 12U);
uint32_t tcnt = get_u32_le(u + 16U);
uint32_t dcnt = get_u32_le(u + 20U);
uint64_t total_keys = (uint64_t)vcnt + (uint64_t)tcnt;
if (total_keys > (SIZE_MAX - 52U) / 32U || (uint64_t)dcnt > (len - 56U) / STIGI_CACHE_DECISION_FIXED) {
free(buf);
return diag_set(diag, STIGI_ERR_INVALID, -1, "corrupt cache: count overflow");
}
size_t keys_end = 24U + (size_t)total_keys * 32U;
if (keys_end + 32U > len) {
free(buf);
return diag_set(diag, STIGI_ERR_INVALID, -1, "corrupt cache: length mismatch");
}
uint8_t digest[32];
blake3_hash(u, len - 32U, digest);
if (memcmp(digest, u + (len - 32U), 32U) != 0) {
free(buf);
return diag_set(diag, STIGI_ERR_INVALID, -1, "corrupt cache: BLAKE3 checksum mismatch");
}
/* the decision records fill exactly the bytes between the keys and the checksum */
size_t pos = keys_end;
for (uint32_t i = 0; i < dcnt; i++) {
if (pos + STIGI_CACHE_DECISION_FIXED > len - 32U) {
free(buf);
return diag_set(diag, STIGI_ERR_INVALID, -1, "corrupt cache: decision record truncated");
}
uint32_t ac = get_u32_le(u + pos + 32U);
if ((uint64_t)pos + STIGI_CACHE_DECISION_FIXED + ac > len - 32U) {
free(buf);
return diag_set(diag, STIGI_ERR_INVALID, -1, "corrupt cache: decision record truncated");
}
pos += STIGI_CACHE_DECISION_FIXED + ac;
}
if (pos != len - 32U) {
free(buf);
return diag_set(diag, STIGI_ERR_INVALID, -1, "corrupt cache: length mismatch");
}
Status is = STIGI_OK;
const uint8_t *vptr = u + 24U;
for (uint32_t i = 0; i < vcnt && is == STIGI_OK; i++) {
is = stigi_door_cache_add_verdict(door, vptr + (size_t)i * 32U, diag);
}
const uint8_t *tptr = vptr + (size_t)vcnt * 32U;
for (uint32_t i = 0; i < tcnt && is == STIGI_OK; i++) {
is = stigi_door_cache_add_test(door, tptr + (size_t)i * 32U, diag);
}
pos = keys_end;
for (uint32_t i = 0; i < dcnt && is == STIGI_OK; i++) {
StigiUnitDecision dec;
memset(&dec, 0, sizeof dec);
dec.access_count = get_u32_le(u + pos + 32U);
dec.tracked = get_u32_le(u + pos + 36U);
dec.free_edges = get_u32_le(u + pos + 40U);
dec.free_at_exit = get_u32_le(u + pos + 44U);
dec.reuses = get_u32_le(u + pos + 48U);
dec.stack_objects = get_u32_le(u + pos + 52U);
if (dec.access_count > 0) {
dec.masked = malloc(dec.access_count);
if (dec.masked == NULL) {
is = diag_set(diag, STIGI_ERR_OOM, -1, "cache decision OOM");
break;
}
memcpy(dec.masked, u + pos + STIGI_CACHE_DECISION_FIXED, dec.access_count);
}
is = stigi_decisions_insert(&door->decisions, u + pos, &dec, diag);
free(dec.masked);
pos += STIGI_CACHE_DECISION_FIXED + get_u32_le(u + pos + 32U);
}
free(buf);
return is;
}
static Status snapshot_keyset(const StigiKeySet *src, StigiKeySet *dst, Diag *diag) {
memset(dst, 0, sizeof *dst);
if (src->cap == 0 || src->slots == NULL) return STIGI_OK;
dst->slots = malloc((size_t)src->cap * sizeof *dst->slots);
if (dst->slots == NULL) return diag_set(diag, STIGI_ERR_OOM, -1, "cache snapshot OOM");
memcpy(dst->slots, src->slots, (size_t)src->cap * sizeof *dst->slots);
dst->cap = src->cap;
dst->count = src->count;
return STIGI_OK;
}
Status stigi_load_dir(StigiDoor *door, const char *dir,
StigiDoorResult *out, Diag *diag) {
if (door == NULL || dir == NULL || out == NULL) {
return diag_set(diag, STIGI_ERR_INVALID, -1, "stigi_load_dir: invalid arguments");
}
Status vs = verify_index_file(dir, diag);
if (vs != STIGI_OK) return vs;
PathList pl = {NULL, 0, 0};
Status st = collect_sc_files(dir, &pl, diag);
if (st != STIGI_OK) {
pathlist_free(&pl);
return st;
}
if (pl.count > 1U) qsort(pl.paths, pl.count, sizeof *pl.paths, cmp_cstr);
char **srcs = calloc(pl.count > 0 ? pl.count : 1U, sizeof *srcs);
size_t *lens = calloc(pl.count > 0 ? pl.count : 1U, sizeof *lens);
if (srcs == NULL || lens == NULL) {
free(srcs);
free(lens);
pathlist_free(&pl);
return diag_set(diag, STIGI_ERR_OOM, -1, "OOM");
}
for (uint32_t i = 0; i < pl.count && st == STIGI_OK; i++) {
st = read_whole_file(pl.paths[i], &srcs[i], &lens[i], diag);
}
/* T0 atomicity: snapshot caches before loading disk cache; restore verbatim on any error/reject */
StigiKeySet saved_vc = {NULL, 0, 0};
StigiKeySet saved_tc = {NULL, 0, 0};
StigiDecisionStore saved_ds = {NULL, 0, 0};
bool snapped = false;
if (st == STIGI_OK) {
st = snapshot_keyset(&door->verdict_cache, &saved_vc, diag);
if (st == STIGI_OK) st = snapshot_keyset(&door->test_cache, &saved_tc, diag);
if (st == STIGI_OK) st = stigi_decisions_copy(&door->decisions, &saved_ds, diag);
if (st == STIGI_OK) {
snapped = true;
st = load_and_verify_cache(door, dir, diag);
}
}
if (st == STIGI_OK) {
st = stigi_door_replace_all(door, (const char *const *)srcs, lens, pl.count, out, diag);
}
if (snapped) {
if (st != STIGI_OK || !out->accepted) {
free(door->verdict_cache.slots);
free(door->test_cache.slots);
door->verdict_cache = saved_vc;
stigi_decisions_free(&door->decisions);
door->decisions = saved_ds;
door->test_cache = saved_tc;
} else {
free(saved_vc.slots);
free(saved_tc.slots);
stigi_decisions_free(&saved_ds);
}
} else {
free(saved_vc.slots);
free(saved_tc.slots);
stigi_decisions_free(&saved_ds);
}
for (uint32_t i = 0; i < pl.count; i++) {
free(srcs[i]);
}
free(srcs);
free(lens);
pathlist_free(&pl);
return st;
}