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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
|
/* $OpenBSD: repo.c,v 1.29 2022/01/28 14:11:27 claudio Exp $ */
/*
* Copyright (c) 2021 Claudio Jeker <claudio@openbsd.org>
* Copyright (c) 2019 Kristaps Dzonsons <kristaps@bsd.lv>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <sys/queue.h>
#include <sys/tree.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <assert.h>
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <fts.h>
#include <limits.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <imsg.h>
#include "extern.h"
extern struct stats stats;
extern int noop;
extern int rrdpon;
extern int repo_timeout;
enum repo_state {
REPO_LOADING = 0,
REPO_DONE = 1,
REPO_FAILED = -1,
};
/*
* A ta, rsync or rrdp repository.
* Depending on what is needed the generic repository is backed by
* a ta, rsync or rrdp repository. Multiple repositories can use the
* same backend.
*/
struct rrdprepo {
SLIST_ENTRY(rrdprepo) entry;
char *notifyuri;
char *basedir;
struct filepath_tree deleted;
unsigned int id;
enum repo_state state;
};
static SLIST_HEAD(, rrdprepo) rrdprepos = SLIST_HEAD_INITIALIZER(rrdprepos);
struct rsyncrepo {
SLIST_ENTRY(rsyncrepo) entry;
char *repouri;
char *basedir;
unsigned int id;
enum repo_state state;
};
static SLIST_HEAD(, rsyncrepo) rsyncrepos = SLIST_HEAD_INITIALIZER(rsyncrepos);
struct tarepo {
SLIST_ENTRY(tarepo) entry;
char *descr;
char *basedir;
char *temp;
char **uri;
size_t urisz;
size_t uriidx;
unsigned int id;
enum repo_state state;
};
static SLIST_HEAD(, tarepo) tarepos = SLIST_HEAD_INITIALIZER(tarepos);
struct repo {
SLIST_ENTRY(repo) entry;
char *repouri;
char *notifyuri;
char *basedir;
const struct rrdprepo *rrdp;
const struct rsyncrepo *rsync;
const struct tarepo *ta;
struct entityq queue; /* files waiting for repo */
time_t alarm; /* sync timeout */
int talid;
unsigned int id; /* identifier */
};
static SLIST_HEAD(, repo) repos = SLIST_HEAD_INITIALIZER(repos);
/* counter for unique repo id */
unsigned int repoid;
static struct rsyncrepo *rsync_get(const char *, const char *);
static void remove_contents(char *);
/*
* Database of all file path accessed during a run.
*/
struct filepath {
RB_ENTRY(filepath) entry;
char *file;
};
static inline int
filepathcmp(struct filepath *a, struct filepath *b)
{
return strcmp(a->file, b->file);
}
RB_PROTOTYPE(filepath_tree, filepath, entry, filepathcmp);
/*
* Functions to lookup which files have been accessed during computation.
*/
int
filepath_add(struct filepath_tree *tree, char *file)
{
struct filepath *fp;
if ((fp = malloc(sizeof(*fp))) == NULL)
err(1, NULL);
if ((fp->file = strdup(file)) == NULL)
err(1, NULL);
if (RB_INSERT(filepath_tree, tree, fp) != NULL) {
/* already in the tree */
free(fp->file);
free(fp);
return 0;
}
return 1;
}
/*
* Lookup a file path in the tree and return the object if found or NULL.
*/
static struct filepath *
filepath_find(struct filepath_tree *tree, char *file)
{
struct filepath needle = { .file = file };
return RB_FIND(filepath_tree, tree, &needle);
}
/*
* Returns true if file exists in the tree.
*/
static int
filepath_exists(struct filepath_tree *tree, char *file)
{
return filepath_find(tree, file) != NULL;
}
/*
* Remove entry from tree and free it.
*/
static void
filepath_put(struct filepath_tree *tree, struct filepath *fp)
{
RB_REMOVE(filepath_tree, tree, fp);
free((void *)fp->file);
free(fp);
}
/*
* Free all elements of a filepath tree.
*/
static void
filepath_free(struct filepath_tree *tree)
{
struct filepath *fp, *nfp;
RB_FOREACH_SAFE(fp, filepath_tree, tree, nfp)
filepath_put(tree, fp);
}
RB_GENERATE(filepath_tree, filepath, entry, filepathcmp);
/*
* Function to hash a string into a unique directory name.
* Returned hash needs to be freed.
*/
static char *
hash_dir(const char *uri)
{
unsigned char m[SHA256_DIGEST_LENGTH];
SHA256(uri, strlen(uri), m);
return hex_encode(m, sizeof(m));
}
/*
* Function to build the directory name based on URI and a directory
* as prefix. Skip the proto:// in URI but keep everything else.
*/
static char *
repo_dir(const char *uri, const char *dir, int hash)
{
const char *local;
char *out, *hdir = NULL;
if (hash) {
local = hdir = hash_dir(uri);
} else {
local = strchr(uri, ':');
if (local != NULL)
local += strlen("://");
else
local = uri;
}
if (dir == NULL) {
if ((out = strdup(local)) == NULL)
err(1, NULL);
} else {
if (asprintf(&out, "%s/%s", dir, local) == -1)
err(1, NULL);
}
free(hdir);
return out;
}
/*
* Function to create all missing directories to a path.
* This functions alters the path temporarily.
*/
static int
repo_mkpath(char *file)
{
char *slash;
/* build directory hierarchy */
slash = strrchr(file, '/');
assert(slash != NULL);
*slash = '\0';
if (mkpath(file) == -1) {
warn("mkpath %s", file);
return -1;
}
*slash = '/';
return 0;
}
/*
* Return the state of a repository.
*/
static enum repo_state
repo_state(struct repo *rp)
{
if (rp->ta)
return rp->ta->state;
if (rp->rsync)
return rp->rsync->state;
if (rp->rrdp)
return rp->rrdp->state;
/* No backend so sync is by definition done. */
return REPO_DONE;
}
/*
* Function called once a repository is done with the sync. Either
* successfully or after failure.
*/
static void
repo_done(const void *vp, int ok)
{
struct repo *rp;
SLIST_FOREACH(rp, &repos, entry) {
if (vp == rp->ta)
entityq_flush(&rp->queue, rp);
if (vp == rp->rsync)
entityq_flush(&rp->queue, rp);
if (vp == rp->rrdp) {
if (!ok) {
/* try to fall back to rsync */
rp->rrdp = NULL;
rp->rsync = rsync_get(rp->repouri,
rp->basedir);
/* need to check if it was already loaded */
if (repo_state(rp) != REPO_LOADING)
entityq_flush(&rp->queue, rp);
} else
entityq_flush(&rp->queue, rp);
}
}
}
/*
* Build TA file name based on the repo info.
* If temp is set add Xs for mkostemp.
*/
static char *
ta_filename(const struct tarepo *tr, int temp)
{
const char *file;
char *nfile;
/* does not matter which URI, all end with same filename */
file = strrchr(tr->uri[0], '/');
assert(file);
if (asprintf(&nfile, "%s%s%s", tr->basedir, file,
temp ? ".XXXXXXXX": "") == -1)
err(1, NULL);
return nfile;
}
static void
ta_fetch(struct tarepo *tr)
{
if (!rrdpon) {
for (; tr->uriidx < tr->urisz; tr->uriidx++) {
if (strncasecmp(tr->uri[tr->uriidx],
"rsync://", 8) == 0)
break;
}
}
if (tr->uriidx >= tr->urisz) {
tr->state = REPO_FAILED;
logx("ta/%s: fallback to cache", tr->descr);
repo_done(tr, 0);
return;
}
logx("ta/%s: pulling from %s", tr->descr, tr->uri[tr->uriidx]);
if (strncasecmp(tr->uri[tr->uriidx], "rsync://", 8) == 0) {
/*
* Create destination location.
* Build up the tree to this point.
*/
rsync_fetch(tr->id, tr->uri[tr->uriidx], tr->basedir, NULL);
} else {
int fd;
tr->temp = ta_filename(tr, 1);
fd = mkostemp(tr->temp, O_CLOEXEC);
if (fd == -1) {
warn("mkostemp: %s", tr->temp);
http_finish(tr->id, HTTP_FAILED, NULL);
return;
}
if (fchmod(fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) == -1)
warn("fchmod: %s", tr->temp);
http_fetch(tr->id, tr->uri[tr->uriidx], NULL, fd);
}
}
static struct tarepo *
ta_get(struct tal *tal)
{
struct tarepo *tr;
/* no need to look for possible other repo */
if ((tr = calloc(1, sizeof(*tr))) == NULL)
err(1, NULL);
tr->id = ++repoid;
SLIST_INSERT_HEAD(&tarepos, tr, entry);
if ((tr->descr = strdup(tal->descr)) == NULL)
err(1, NULL);
tr->basedir = repo_dir(tal->descr, "ta", 0);
/* steal URI infromation from TAL */
tr->urisz = tal->urisz;
tr->uri = tal->uri;
tal->urisz = 0;
tal->uri = NULL;
ta_fetch(tr);
return tr;
}
static struct tarepo *
ta_find(unsigned int id)
{
struct tarepo *tr;
SLIST_FOREACH(tr, &tarepos, entry)
if (id == tr->id)
break;
return tr;
}
static void
ta_free(void)
{
struct tarepo *tr;
while ((tr = SLIST_FIRST(&tarepos)) != NULL) {
SLIST_REMOVE_HEAD(&tarepos, entry);
free(tr->descr);
free(tr->basedir);
free(tr->temp);
free(tr->uri);
free(tr);
}
}
static struct rsyncrepo *
rsync_get(const char *uri, const char *validdir)
{
struct rsyncrepo *rr;
char *repo;
if ((repo = rsync_base_uri(uri)) == NULL)
errx(1, "bad caRepository URI: %s", uri);
SLIST_FOREACH(rr, &rsyncrepos, entry)
if (strcmp(rr->repouri, repo) == 0) {
free(repo);
return rr;
}
if ((rr = calloc(1, sizeof(*rr))) == NULL)
err(1, NULL);
rr->id = ++repoid;
SLIST_INSERT_HEAD(&rsyncrepos, rr, entry);
rr->repouri = repo;
rr->basedir = repo_dir(repo, ".rsync", 0);
/* create base directory */
if (mkpath(rr->basedir) == -1) {
warn("mkpath %s", rr->basedir);
rsync_finish(rr->id, 0);
return rr;
}
logx("%s: pulling from %s", rr->basedir, rr->repouri);
rsync_fetch(rr->id, rr->repouri, rr->basedir, validdir);
return rr;
}
static struct rsyncrepo *
rsync_find(unsigned int id)
{
struct rsyncrepo *rr;
SLIST_FOREACH(rr, &rsyncrepos, entry)
if (id == rr->id)
break;
return rr;
}
static void
rsync_free(void)
{
struct rsyncrepo *rr;
while ((rr = SLIST_FIRST(&rsyncrepos)) != NULL) {
SLIST_REMOVE_HEAD(&rsyncrepos, entry);
free(rr->repouri);
free(rr->basedir);
free(rr);
}
}
/*
* Build local file name base on the URI and the rrdprepo info.
*/
static char *
rrdp_filename(const struct rrdprepo *rr, const char *uri, int valid)
{
char *nfile;
const char *dir = rr->basedir;
if (!valid_uri(uri, strlen(uri), "rsync://"))
errx(1, "%s: bad URI %s", rr->basedir, uri);
uri += strlen("rsync://"); /* skip proto */
if (valid) {
if ((nfile = strdup(uri)) == NULL)
err(1, NULL);
} else {
if (asprintf(&nfile, "%s/%s", dir, uri) == -1)
err(1, NULL);
}
return nfile;
}
/*
* Build RRDP state file name based on the repo info.
* If temp is set add Xs for mkostemp.
*/
static char *
rrdp_state_filename(const struct rrdprepo *rr, int temp)
{
char *nfile;
if (asprintf(&nfile, "%s/.state%s", rr->basedir,
temp ? ".XXXXXXXX": "") == -1)
err(1, NULL);
return nfile;
}
static struct rrdprepo *
rrdp_find(unsigned int id)
{
struct rrdprepo *rr;
SLIST_FOREACH(rr, &rrdprepos, entry)
if (id == rr->id)
break;
return rr;
}
static void
rrdp_free(void)
{
struct rrdprepo *rr;
while ((rr = SLIST_FIRST(&rrdprepos)) != NULL) {
SLIST_REMOVE_HEAD(&rrdprepos, entry);
free(rr->notifyuri);
free(rr->basedir);
filepath_free(&rr->deleted);
free(rr);
}
}
/*
* Check if a directory is an active rrdp repository.
* Returns 1 if found else 0.
*/
static int
rrdp_is_active(const char *dir)
{
struct rrdprepo *rr;
SLIST_FOREACH(rr, &rrdprepos, entry)
if (strcmp(dir, rr->basedir) == 0)
return rr->state != REPO_FAILED;
return 0;
}
/*
* Check if the URI is actually covered by one of the repositories
* that depend on this RRDP repository.
* Returns 1 if the URI is valid, 0 if no repouri matches the URI.
*/
static int
rrdp_uri_valid(struct rrdprepo *rr, const char *uri)
{
struct repo *rp;
SLIST_FOREACH(rp, &repos, entry) {
if (rp->rrdp != rr)
continue;
if (strncmp(uri, rp->repouri, strlen(rp->repouri)) == 0)
return 1;
}
return 0;
}
/*
* Allocate and insert a new repository.
*/
static struct repo *
repo_alloc(int talid)
{
struct repo *rp;
if ((rp = calloc(1, sizeof(*rp))) == NULL)
err(1, NULL);
rp->id = ++repoid;
rp->talid = talid;
rp->alarm = getmonotime() + repo_timeout;
TAILQ_INIT(&rp->queue);
SLIST_INSERT_HEAD(&repos, rp, entry);
stats.repos++;
return rp;
}
/*
* Parse the RRDP state file if it exists and set the session struct
* based on that information.
*/
static void
rrdp_parse_state(const struct rrdprepo *rr, struct rrdp_session *state)
{
FILE *f;
int fd, ln = 0;
const char *errstr;
char *line = NULL, *file;
size_t len = 0;
ssize_t n;
file = rrdp_state_filename(rr, 0);
if ((fd = open(file, O_RDONLY)) == -1) {
if (errno != ENOENT)
warn("%s: open state file", rr->basedir);
free(file);
return;
}
free(file);
f = fdopen(fd, "r");
if (f == NULL)
err(1, "fdopen");
while ((n = getline(&line, &len, f)) != -1) {
if (line[n - 1] == '\n')
line[n - 1] = '\0';
switch (ln) {
case 0:
if ((state->session_id = strdup(line)) == NULL)
err(1, NULL);
break;
case 1:
state->serial = strtonum(line, 1, LLONG_MAX, &errstr);
if (errstr)
goto fail;
break;
case 2:
if ((state->last_mod = strdup(line)) == NULL)
err(1, NULL);
break;
default:
goto fail;
}
ln++;
}
free(line);
if (ferror(f))
goto fail;
fclose(f);
return;
fail:
warnx("%s: troubles reading state file", rr->basedir);
fclose(f);
free(state->session_id);
free(state->last_mod);
memset(state, 0, sizeof(*state));
}
/*
* Carefully write the RRDP session state file back.
*/
void
rrdp_save_state(unsigned int id, struct rrdp_session *state)
{
struct rrdprepo *rr;
char *temp, *file;
FILE *f;
int fd;
rr = rrdp_find(id);
if (rr == NULL)
errx(1, "non-existant rrdp repo %u", id);
file = rrdp_state_filename(rr, 0);
temp = rrdp_state_filename(rr, 1);
if ((fd = mkostemp(temp, O_CLOEXEC)) == -1) {
warn("mkostemp %s", temp);
goto fail;
}
(void) fchmod(fd, 0644);
f = fdopen(fd, "w");
if (f == NULL)
err(1, "fdopen");
/* write session state file out */
if (fprintf(f, "%s\n%lld\n", state->session_id,
state->serial) < 0) {
fclose(f);
goto fail;
}
if (state->last_mod != NULL) {
if (fprintf(f, "%s\n", state->last_mod) < 0) {
fclose(f);
goto fail;
}
}
if (fclose(f) != 0)
goto fail;
if (rename(temp, file) == -1)
warn("%s: rename state file", rr->basedir);
free(temp);
free(file);
return;
fail:
warnx("%s: failed to save state", rr->basedir);
unlink(temp);
free(temp);
free(file);
}
static struct rrdprepo *
rrdp_get(const char *uri)
{
struct rrdp_session state = { 0 };
struct rrdprepo *rr;
SLIST_FOREACH(rr, &rrdprepos, entry)
if (strcmp(rr->notifyuri, uri) == 0) {
if (rr->state == REPO_FAILED)
return NULL;
return rr;
}
if ((rr = calloc(1, sizeof(*rr))) == NULL)
err(1, NULL);
rr->id = ++repoid;
SLIST_INSERT_HEAD(&rrdprepos, rr, entry);
if ((rr->notifyuri = strdup(uri)) == NULL)
err(1, NULL);
rr->basedir = repo_dir(uri, ".rrdp", 1);
RB_INIT(&rr->deleted);
/* create base directory */
if (mkpath(rr->basedir) == -1) {
warn("mkpath %s", rr->basedir);
rrdp_finish(rr->id, 0);
return rr;
}
/* parse state and start the sync */
rrdp_parse_state(rr, &state);
rrdp_fetch(rr->id, rr->notifyuri, rr->notifyuri, &state);
free(state.session_id);
free(state.last_mod);
logx("%s: pulling from %s", rr->notifyuri, "network");
return rr;
}
/*
* Remove RRDP repo and start over.
*/
void
rrdp_clear(unsigned int id)
{
struct rrdprepo *rr;
rr = rrdp_find(id);
if (rr == NULL)
errx(1, "non-existant rrdp repo %u", id);
/* remove rrdp repository contents */
remove_contents(rr->basedir);
}
/*
* Write a file into the temporary RRDP dir but only after checking
* its hash (if required). The function also makes sure that the file
* tracking is properly adjusted.
* Returns 1 on success, 0 if the repo is corrupt, -1 on IO error
*/
int
rrdp_handle_file(unsigned int id, enum publish_type pt, char *uri,
char *hash, size_t hlen, char *data, size_t dlen)
{
struct rrdprepo *rr;
struct filepath *fp;
ssize_t s;
char *fn = NULL;
int fd = -1, try = 0;
rr = rrdp_find(id);
if (rr == NULL)
errx(1, "non-existant rrdp repo %u", id);
if (rr->state == REPO_FAILED)
return -1;
/* check hash of original file for updates and deletes */
if (pt == PUB_UPD || pt == PUB_DEL) {
if (filepath_exists(&rr->deleted, uri)) {
warnx("%s: already deleted", uri);
return 0;
}
/* try to open file first in rrdp then in valid repo */
do {
free(fn);
if ((fn = rrdp_filename(rr, uri, try++)) == NULL)
return 0;
fd = open(fn, O_RDONLY);
} while (fd == -1 && try < 2);
if (!valid_filehash(fd, hash, hlen)) {
warnx("%s: bad file digest for %s", rr->notifyuri, fn);
free(fn);
return 0;
}
free(fn);
}
/* write new content or mark uri as deleted. */
if (pt == PUB_DEL) {
filepath_add(&rr->deleted, uri);
} else {
fp = filepath_find(&rr->deleted, uri);
if (fp != NULL)
filepath_put(&rr->deleted, fp);
/* add new file to rrdp dir */
if ((fn = rrdp_filename(rr, uri, 0)) == NULL)
return 0;
if (repo_mkpath(fn) == -1)
goto fail;
fd = open(fn, O_WRONLY|O_CREAT|O_TRUNC, 0644);
if (fd == -1) {
warn("open %s", fn);
goto fail;
}
if ((s = write(fd, data, dlen)) == -1) {
warn("write %s", fn);
goto fail;
}
close(fd);
if ((size_t)s != dlen) /* impossible */
errx(1, "short write %s", fn);
free(fn);
}
return 1;
fail:
rr->state = REPO_FAILED;
if (fd != -1)
close(fd);
free(fn);
return -1;
}
/*
* RSYNC sync finished, either with or without success.
*/
void
rsync_finish(unsigned int id, int ok)
{
struct rsyncrepo *rr;
struct tarepo *tr;
tr = ta_find(id);
if (tr != NULL) {
/* repository changed state already, ignore request */
if (tr->state != REPO_LOADING)
return;
if (ok) {
logx("ta/%s: loaded from network", tr->descr);
stats.rsync_repos++;
tr->state = REPO_DONE;
repo_done(tr, 1);
} else {
logx("ta/%s: load from network failed", tr->descr);
stats.rsync_fails++;
tr->uriidx++;
ta_fetch(tr);
}
return;
}
rr = rsync_find(id);
if (rr == NULL)
errx(1, "unknown rsync repo %u", id);
/* repository changed state already, ignore request */
if (rr->state != REPO_LOADING)
return;
if (ok) {
logx("%s: loaded from network", rr->basedir);
stats.rsync_repos++;
rr->state = REPO_DONE;
} else {
logx("%s: load from network failed, fallback to cache",
rr->basedir);
stats.rsync_fails++;
rr->state = REPO_FAILED;
/* clear rsync repo since it failed */
remove_contents(rr->basedir);
}
repo_done(rr, ok);
}
/*
* RRDP sync finshed, either with or without success.
*/
void
rrdp_finish(unsigned int id, int ok)
{
struct rrdprepo *rr;
rr = rrdp_find(id);
if (rr == NULL)
errx(1, "unknown RRDP repo %u", id);
/* repository changed state already, ignore request */
if (rr->state != REPO_LOADING)
return;
if (ok) {
logx("%s: loaded from network", rr->notifyuri);
stats.rrdp_repos++;
rr->state = REPO_DONE;
} else {
logx("%s: load from network failed, fallback to rsync",
rr->notifyuri);
stats.rrdp_fails++;
rr->state = REPO_FAILED;
/* clear the RRDP repo since it failed */
remove_contents(rr->basedir);
}
repo_done(rr, ok);
}
/*
* Handle responses from the http process. For TA file, either rename
* or delete the temporary file. For RRDP requests relay the request
* over to the rrdp process.
*/
void
http_finish(unsigned int id, enum http_result res, const char *last_mod)
{
struct tarepo *tr;
tr = ta_find(id);
if (tr == NULL) {
/* not a TA fetch therefor RRDP */
rrdp_http_done(id, res, last_mod);
return;
}
/* repository changed state already, ignore request */
if (tr->state != REPO_LOADING)
return;
/* Move downloaded TA file into place, or unlink on failure. */
if (res == HTTP_OK) {
char *file;
file = ta_filename(tr, 0);
if (rename(tr->temp, file) == -1)
warn("rename to %s", file);
free(file);
logx("ta/%s: loaded from network", tr->descr);
tr->state = REPO_DONE;
stats.http_repos++;
repo_done(tr, 1);
} else {
if (unlink(tr->temp) == -1 && errno != ENOENT)
warn("unlink %s", tr->temp);
tr->uriidx++;
logx("ta/%s: load from network failed", tr->descr);
ta_fetch(tr);
}
}
/*
* Look up a trust anchor, queueing it for download if not found.
*/
struct repo *
ta_lookup(int id, struct tal *tal)
{
struct repo *rp;
if (tal->urisz == 0)
errx(1, "TAL %s has no URI", tal->descr);
/* Look up in repository table. (Lookup should actually fail here) */
SLIST_FOREACH(rp, &repos, entry) {
if (strcmp(rp->repouri, tal->descr) == 0)
return rp;
}
rp = repo_alloc(id);
rp->basedir = repo_dir(tal->descr, "ta", 0);
if ((rp->repouri = strdup(tal->descr)) == NULL)
err(1, NULL);
/* try to create base directory */
if (mkpath(rp->basedir) == -1)
warn("mkpath %s", rp->basedir);
/* check if sync disabled ... */
if (noop) {
logx("ta/%s: using cache", rp->repouri);
entityq_flush(&rp->queue, rp);
return rp;
}
rp->ta = ta_get(tal);
/* need to check if it was already loaded */
if (repo_state(rp) != REPO_LOADING)
entityq_flush(&rp->queue, rp);
return rp;
}
/*
* Look up a repository, queueing it for discovery if not found.
*/
struct repo *
repo_lookup(int talid, const char *uri, const char *notify)
{
struct repo *rp;
char *repouri;
int nofetch = 0;
if ((repouri = rsync_base_uri(uri)) == NULL)
errx(1, "bad caRepository URI: %s", uri);
/* Look up in repository table. */
SLIST_FOREACH(rp, &repos, entry) {
if (strcmp(rp->repouri, repouri) != 0)
continue;
if (rp->notifyuri != NULL) {
if (notify == NULL)
continue;
if (strcmp(rp->notifyuri, notify) != 0)
continue;
} else if (notify != NULL)
continue;
/* found matching repo */
free(repouri);
return rp;
}
rp = repo_alloc(talid);
rp->basedir = repo_dir(repouri, NULL, 0);
rp->repouri = repouri;
if (notify != NULL)
if ((rp->notifyuri = strdup(notify)) == NULL)
err(1, NULL);
if (++talrepocnt[talid] >= MAX_REPO_PER_TAL) {
if (talrepocnt[talid] == MAX_REPO_PER_TAL)
warnx("too many repositories under %s", tals[talid]);
nofetch = 1;
}
/* try to create base directory */
if (mkpath(rp->basedir) == -1)
warn("mkpath %s", rp->basedir);
/* check if sync disabled ... */
if (noop || nofetch) {
logx("%s: using cache", rp->basedir);
entityq_flush(&rp->queue, rp);
return rp;
}
/* ... else try RRDP first if available then rsync */
if (notify != NULL)
rp->rrdp = rrdp_get(notify);
if (rp->rrdp == NULL)
rp->rsync = rsync_get(uri, rp->basedir);
/* need to check if it was already loaded */
if (repo_state(rp) != REPO_LOADING)
entityq_flush(&rp->queue, rp);
return rp;
}
/*
* Find repository by identifier.
*/
struct repo *
repo_byid(unsigned int id)
{
struct repo *rp;
SLIST_FOREACH(rp, &repos, entry) {
if (rp->id == id)
return rp;
}
return NULL;
}
/*
* Return the repository base or alternate directory.
* Returned string must be freed by caller.
*/
char *
repo_basedir(const struct repo *rp, int wantvalid)
{
char *path = NULL;
if (!wantvalid) {
if (rp->ta) {
if ((path = strdup(rp->ta->basedir)) == NULL)
err(1, NULL);
} else if (rp->rsync) {
if ((path = strdup(rp->rsync->basedir)) == NULL)
err(1, NULL);
} else if (rp->rrdp) {
path = rrdp_filename(rp->rrdp, rp->repouri, 0);
} else
path = NULL; /* only valid repo available */
} else if (rp->basedir != NULL) {
if ((path = strdup(rp->basedir)) == NULL)
err(1, NULL);
}
return path;
}
/*
* Return the repository identifier.
*/
unsigned int
repo_id(const struct repo *rp)
{
return rp->id;
}
/*
* Return the repository URI.
*/
const char *
repo_uri(const struct repo *rp)
{
return rp->repouri;
}
int
repo_queued(struct repo *rp, struct entity *p)
{
if (repo_state(rp) == REPO_LOADING) {
TAILQ_INSERT_TAIL(&rp->queue, p, entries);
return 1;
}
return 0;
}
static void
repo_fail(struct repo *rp)
{
/* reset the alarm since code may fallback to rsync */
rp->alarm = getmonotime() + repo_timeout;
if (rp->ta)
http_finish(rp->ta->id, HTTP_FAILED, NULL);
else if (rp->rsync)
rsync_finish(rp->rsync->id, 0);
else if (rp->rrdp)
rrdp_finish(rp->rrdp->id, 0);
else
errx(1, "%s: bad repo", rp->repouri);
}
int
repo_check_timeout(int timeout)
{
struct repo *rp;
time_t now;
now = getmonotime();
/* Look up in repository table. (Lookup should actually fail here) */
SLIST_FOREACH(rp, &repos, entry) {
if (repo_state(rp) == REPO_LOADING) {
if (rp->alarm <= now) {
warnx("%s: synchronisation timeout",
rp->repouri);
repo_fail(rp);
} else {
int diff = rp->alarm - now;
diff *= 1000;
if (timeout == INFTIM || diff < timeout)
timeout = diff;
}
}
}
return timeout;
}
static char **
add_to_del(char **del, size_t *dsz, char *file)
{
size_t i = *dsz;
del = reallocarray(del, i + 1, sizeof(*del));
if (del == NULL)
err(1, NULL);
if ((del[i] = strdup(file)) == NULL)
err(1, NULL);
*dsz = i + 1;
return del;
}
/*
* Delayed delete of files from RRDP. Since RRDP has no security built-in
* this code needs to check if this RRDP repository is actually allowed to
* remove the file referenced by the URI.
*/
static char **
repo_cleanup_rrdp(struct filepath_tree *tree, char **del, size_t *delsz)
{
struct rrdprepo *rr;
struct filepath *fp, *nfp;
char *fn;
SLIST_FOREACH(rr, &rrdprepos, entry) {
RB_FOREACH_SAFE(fp, filepath_tree, &rr->deleted, nfp) {
if (!rrdp_uri_valid(rr, fp->file)) {
warnx("%s: external URI %s", rr->notifyuri,
fp->file);
filepath_put(&rr->deleted, fp);
continue;
}
/* try to remove file from rrdp repo ... */
fn = rrdp_filename(rr, fp->file, 0);
del = add_to_del(del, delsz, fn);
free(fn);
/* ... and from the valid repository if unused. */
fn = rrdp_filename(rr, fp->file, 1);
if (!filepath_exists(tree, fn))
del = add_to_del(del, delsz, fn);
else
warnx("%s: referenced file supposed to be "
"deleted", fn);
free(fn);
filepath_put(&rr->deleted, fp);
}
}
return del;
}
/*
* All files in tree are valid and should be moved to the valid repository
* if not already there. Rename the files to the new path and readd the
* filepath entry with the new path if successful.
*/
static void
repo_move_valid(struct filepath_tree *tree)
{
struct filepath *fp, *nfp;
size_t rsyncsz = strlen(".rsync/");
size_t rrdpsz = strlen(".rrdp/");
char *fn, *base;
RB_FOREACH_SAFE(fp, filepath_tree, tree, nfp) {
if (strncmp(fp->file, ".rsync/", rsyncsz) != 0 &&
strncmp(fp->file, ".rrdp/", rrdpsz) != 0)
continue; /* not a temporary file path */
if (strncmp(fp->file, ".rsync/", rsyncsz) == 0) {
fn = fp->file + rsyncsz;
} else {
base = strchr(fp->file + rrdpsz, '/');
assert(base != NULL);
fn = base + 1;
}
if (repo_mkpath(fn) == -1)
continue;
if (rename(fp->file, fn) == -1) {
warn("rename %s", fp->file);
continue;
}
/* switch filepath node to new path */
RB_REMOVE(filepath_tree, tree, fp);
base = fp->file;
if ((fp->file = strdup(fn)) == NULL)
err(1, NULL);
free(base);
if (RB_INSERT(filepath_tree, tree, fp) != NULL)
errx(1, "%s: both possibilities of file present",
fp->file);
}
}
#define BASE_DIR (void *)0x62617365
#define RSYNC_DIR (void *)0x73796e63
#define RRDP_DIR (void *)0x52524450
static inline char *
skip_dotslash(char *in)
{
if (memcmp(in, "./", 2) == 0)
return in + 2;
return in;
}
void
repo_cleanup(struct filepath_tree *tree)
{
size_t i, cnt, delsz = 0, dirsz = 0;
char **del = NULL, **dir = NULL;
char *argv[2] = { ".", NULL };
FTS *fts;
FTSENT *e;
/* first move temp files which have been used to valid dir */
repo_move_valid(tree);
/* then delete files requested by rrdp */
del = repo_cleanup_rrdp(tree, del, &delsz);
if ((fts = fts_open(argv, FTS_PHYSICAL | FTS_NOSTAT, NULL)) == NULL)
err(1, "fts_open");
errno = 0;
while ((e = fts_read(fts)) != NULL) {
char *path = skip_dotslash(e->fts_path);
switch (e->fts_info) {
case FTS_NSOK:
if (filepath_exists(tree, path)) {
e->fts_parent->fts_number++;
break;
}
if (e->fts_parent->fts_pointer == RRDP_DIR) {
e->fts_parent->fts_number++;
/* handle rrdp .state files explicitly */
if (e->fts_level == 3 &&
strcmp(e->fts_name, ".state") == 0)
break;
/* can't delete these extra files */
stats.extra_files++;
if (verbose > 1)
logx("superfluous %s", path);
break;
}
if (e->fts_parent->fts_pointer == RSYNC_DIR) {
/* no need to keep rsync files */
stats.extra_files++;
if (verbose > 1)
logx("superfluous %s", path);
}
del = add_to_del(del, &delsz, path);
break;
case FTS_D:
if (e->fts_level == 1) {
if (strcmp(".rsync", e->fts_name) == 0)
e->fts_pointer = RSYNC_DIR;
else if (strcmp(".rrdp", e->fts_name) == 0)
e->fts_pointer = RRDP_DIR;
else
e->fts_pointer = BASE_DIR;
} else
e->fts_pointer = e->fts_parent->fts_pointer;
/*
* special handling for rrdp directories,
* clear them if they are not used anymore but
* only if rrdp is active.
*/
if (e->fts_pointer == RRDP_DIR && !noop &&
e->fts_level == 2) {
if (!rrdp_is_active(path))
e->fts_pointer = NULL;
}
break;
case FTS_DP:
if (e->fts_level == FTS_ROOTLEVEL)
break;
if (e->fts_level == 1)
/* do not remove .rsync and .rrdp */
if (e->fts_pointer == RRDP_DIR ||
e->fts_pointer == RSYNC_DIR)
break;
if (e->fts_number == 0)
dir = add_to_del(dir, &dirsz, path);
e->fts_parent->fts_number += e->fts_number;
break;
case FTS_SL:
case FTS_SLNONE:
warnx("symlink %s", path);
del = add_to_del(del, &delsz, path);
break;
case FTS_NS:
case FTS_ERR:
if (e->fts_errno == ENOENT &&
e->fts_level == FTS_ROOTLEVEL)
continue;
warnx("fts_read %s: %s", path,
strerror(e->fts_errno));
break;
default:
warnx("fts_read %s: unhandled[%x]", path,
e->fts_info);
break;
}
errno = 0;
}
if (errno)
err(1, "fts_read");
if (fts_close(fts) == -1)
err(1, "fts_close");
cnt = 0;
for (i = 0; i < delsz; i++) {
if (unlink(del[i]) == -1) {
if (errno != ENOENT)
warn("unlink %s", del[i]);
} else {
if (verbose > 1)
logx("deleted %s", del[i]);
cnt++;
}
free(del[i]);
}
free(del);
stats.del_files += cnt;
cnt = 0;
for (i = 0; i < dirsz; i++) {
if (rmdir(dir[i]) == -1)
warn("rmdir %s", dir[i]);
else
cnt++;
free(dir[i]);
}
free(dir);
stats.del_dirs += cnt;
}
void
repo_free(void)
{
struct repo *rp;
while ((rp = SLIST_FIRST(&repos)) != NULL) {
SLIST_REMOVE_HEAD(&repos, entry);
free(rp->repouri);
free(rp->notifyuri);
free(rp->basedir);
free(rp);
}
ta_free();
rrdp_free();
rsync_free();
}
/*
* Remove all files and directories under base but do not remove base itself.
*/
static void
remove_contents(char *base)
{
char *argv[2] = { base, NULL };
FTS *fts;
FTSENT *e;
if ((fts = fts_open(argv, FTS_PHYSICAL | FTS_NOSTAT, NULL)) == NULL)
err(1, "fts_open");
errno = 0;
while ((e = fts_read(fts)) != NULL) {
switch (e->fts_info) {
case FTS_NSOK:
case FTS_SL:
case FTS_SLNONE:
if (unlink(e->fts_accpath) == -1)
warn("unlink %s", e->fts_path);
break;
case FTS_D:
break;
case FTS_DP:
/* keep root directory */
if (e->fts_level == FTS_ROOTLEVEL)
break;
if (rmdir(e->fts_accpath) == -1)
warn("rmdir %s", e->fts_path);
break;
case FTS_NS:
case FTS_ERR:
warnx("fts_read %s: %s", e->fts_path,
strerror(e->fts_errno));
break;
default:
warnx("unhandled[%x] %s", e->fts_info,
e->fts_path);
break;
}
errno = 0;
}
if (errno)
err(1, "fts_read");
if (fts_close(fts) == -1)
err(1, "fts_close");
}
|