Welcome to mirror list, hosted at ThFree Co, Russian Federation.

fd_plugins.cc « filed « src « core - github.com/bareos/bareos.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 07ffdefd323d45659a90df48d7a657c0ce11d9db (plain)
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
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
/*
   BAREOS® - Backup Archiving REcovery Open Sourced

   Copyright (C) 2007-2012 Free Software Foundation Europe e.V.
   Copyright (C) 2011-2012 Planets Communications B.V.
   Copyright (C) 2013-2022 Bareos GmbH & Co. KG

   This program is Free Software; you can redistribute it and/or
   modify it under the terms of version three of the GNU Affero General Public
   License as published by the Free Software Foundation, which is
   listed in the file LICENSE.

   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
   Affero General Public License for more details.

   You should have received a copy of the GNU Affero General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
   02110-1301, USA.
*/
// Kern Sibbald, October 2007
/**
 * @file
 * Bareos pluginloader
 */
#include "include/bareos.h"
#include "filed/filed.h"
#include "filed/filed_globals.h"
#include "filed/accurate.h"
#include "filed/heartbeat.h"
#include "filed/fileset.h"
#include "filed/heartbeat.h"
#include "filed/jcr_private.h"
#include "findlib/attribs.h"
#include "findlib/find.h"
#include "findlib/find_one.h"
#include "findlib/hardlink.h"
#include "lib/berrno.h"
#include "lib/bsock.h"

// Function pointers to be set here (findlib)
extern int (*plugin_bopen)(BareosWinFilePacket* bfd,
                           const char* fname,
                           int flags,
                           mode_t mode);
extern int (*plugin_bclose)(BareosWinFilePacket* bfd);
extern ssize_t (*plugin_bread)(BareosWinFilePacket* bfd,
                               void* buf,
                               size_t count);
extern ssize_t (*plugin_bwrite)(BareosWinFilePacket* bfd,
                                void* buf,
                                size_t count);
extern boffset_t (*plugin_blseek)(BareosWinFilePacket* bfd,
                                  boffset_t offset,
                                  int whence);

extern char* exepath;

namespace filedaemon {

const int debuglevel = 150;
#ifdef HAVE_WIN32
const char* plugin_type = "-fd.dll";
#else
const char* plugin_type = "-fd.so";
#endif
static alist<Plugin*>* fd_plugin_list = NULL;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

extern int SaveFile(JobControlRecord* jcr,
                    FindFilesPacket* ff_pkt,
                    bool top_level);

// Forward referenced functions
static bRC bareosGetValue(PluginContext* ctx, bVariable var, void* value);
static bRC bareosSetValue(PluginContext* ctx, bVariable var, void* value);
static bRC bareosRegisterEvents(PluginContext* ctx, int nr_events, ...);
static bRC bareosUnRegisterEvents(PluginContext* ctx, int nr_events, ...);
static bRC bareosJobMsg(PluginContext* ctx,
                        const char* fname,
                        int line,
                        int type,
                        utime_t mtime,
                        const char* fmt,
                        ...);
static bRC bareosDebugMsg(PluginContext* ctx,
                          const char* fname,
                          int line,
                          int level,
                          const char* fmt,
                          ...);
static void* bareosMalloc(PluginContext* ctx,
                          const char* fname,
                          int line,
                          size_t size);
static void bareosFree(PluginContext* ctx,
                       const char* file,
                       int line,
                       void* mem);
static bRC bareosAddExclude(PluginContext* ctx, const char* file);
static bRC bareosAddInclude(PluginContext* ctx, const char* file);
static bRC bareosAddOptions(PluginContext* ctx, const char* opts);
static bRC bareosAddRegex(PluginContext* ctx, const char* item, int type);
static bRC bareosAddWild(PluginContext* ctx, const char* item, int type);
static bRC bareosNewOptions(PluginContext* ctx);
static bRC bareosNewInclude(PluginContext* ctx);
static bRC bareosNewPreInclude(PluginContext* ctx);
static bool IsPluginCompatible(Plugin* plugin);
static bool GetPluginName(JobControlRecord* jcr, char* cmd, int* ret);
static bRC bareosCheckChanges(PluginContext* ctx, struct save_pkt* sp);
static bRC bareosAcceptFile(PluginContext* ctx, struct save_pkt* sp);
static bRC bareosSetSeenBitmap(PluginContext* ctx, bool all, char* fname);
static bRC bareosClearSeenBitmap(PluginContext* ctx, bool all, char* fname);
static bRC bareosGetInstanceCount(PluginContext* ctx, int* ret);

// These will be plugged into the global pointer structure for the findlib.
static int MyPluginBopen(BareosWinFilePacket* bfd,
                         const char* fname,
                         int flags,
                         mode_t mode);
static int MyPluginBclose(BareosWinFilePacket* bfd);
static ssize_t MyPluginBread(BareosWinFilePacket* bfd, void* buf, size_t count);
static ssize_t MyPluginBwrite(BareosWinFilePacket* bfd,
                              void* buf,
                              size_t count);
static boffset_t MyPluginBlseek(BareosWinFilePacket* bfd,
                                boffset_t offset,
                                int whence);

/* Bareos info */
static PluginApiDefinition bareos_plugin_interface_version
    = {sizeof(PluginApiDefinition), FD_PLUGIN_INTERFACE_VERSION};

/* Bareos entry points */
static CoreFunctions bareos_core_functions = {sizeof(CoreFunctions),
                                              FD_PLUGIN_INTERFACE_VERSION,
                                              bareosRegisterEvents,
                                              bareosUnRegisterEvents,
                                              bareosGetInstanceCount,
                                              bareosGetValue,
                                              bareosSetValue,
                                              bareosJobMsg,
                                              bareosDebugMsg,
                                              bareosMalloc,
                                              bareosFree,
                                              bareosAddExclude,
                                              bareosAddInclude,
                                              bareosAddOptions,
                                              bareosAddRegex,
                                              bareosAddWild,
                                              bareosNewOptions,
                                              bareosNewInclude,
                                              bareosNewPreInclude,
                                              bareosCheckChanges,
                                              bareosAcceptFile,
                                              bareosSetSeenBitmap,
                                              bareosClearSeenBitmap};

// Bareos private context
struct b_plugin_ctx {
  JobControlRecord* jcr; /* jcr for plugin */
  bRC ret;               /* last return code */
  bool disabled;         /* set if plugin disabled */
  bool restoreFileStarted;
  bool createFileCalled;
  char events[NbytesForBits(FD_NR_EVENTS + 1)]; /* enabled events bitmask */
  findIncludeExcludeItem* exclude;              /* pointer to exclude files */
  findIncludeExcludeItem* include; /* pointer to include/exclude files */
  Plugin* plugin; /* pointer to plugin of which this is an instance off */
};

static inline bool IsEventEnabled(PluginContext* ctx, bEventType eventType)
{
  b_plugin_ctx* b_ctx;

  if (!ctx) { return false; }

  b_ctx = (b_plugin_ctx*)ctx->core_private_context;
  if (!b_ctx) { return false; }

  return BitIsSet(eventType, b_ctx->events);
}

static inline bool IsPluginDisabled(PluginContext* ctx)
{
  b_plugin_ctx* b_ctx;

  if (!ctx) { return true; }

  b_ctx = (b_plugin_ctx*)ctx->core_private_context;
  if (!b_ctx) { return true; }

  return b_ctx->disabled;
}

static bool IsCtxGood(PluginContext* ctx,
                      JobControlRecord*& jcr,
                      b_plugin_ctx*& bctx)
{
  if (!ctx) { return false; }

  bctx = (b_plugin_ctx*)ctx->core_private_context;
  if (!bctx) { return false; }

  jcr = bctx->jcr;
  if (!jcr) { return false; }

  return true;
}

// Test if event is for this plugin
static bool IsEventForThisPlugin(Plugin* plugin, char* name, int len)
{
  Dmsg4(debuglevel, "IsEventForThisPlugin? name=%s len=%d plugin=%s plen=%d\n",
        name, len, plugin->file, plugin->file_len);
  if (!name) { /* if no plugin name, all plugins get it */
    return true;
  }

  // Return global VSS job metadata to all plugins
  if (bstrcmp("job", name)) { /* old V4.0 name for VSS job metadata */
    return true;
  }

  if (bstrcmp("*all*", name)) { /* new v6.0 name for VSS job metadata */
    return true;
  }

  // Check if this is the correct plugin
  if (len == plugin->file_len && bstrncmp(plugin->file, name, len)) {
    Dmsg4(debuglevel,
          "IsEventForThisPlugin: yes, full match (plugin=%s, name=%s)\n",
          plugin->file, name);
    return true;
  }
  // To be able to restore "python" plugin streams with the "python3" plugin,
  // we check if the required name is the same as the plugin name without the
  // last character
  if (len == plugin->file_len - 1 && bstrncmp(plugin->file, name, len)) {
    Dmsg4(debuglevel,
          "IsEventForThisPlugin: yes, without last character: (plugin=%s, "
          "name=%s)\n",
          plugin->file, name);
    return true;
  }

  Dmsg4(debuglevel, "IsEventForThisPlugin: no (plugin=%s, name=%s)\n",
        plugin->file, name);

  return false;
}

// Raise a certain plugin event.
static inline bool trigger_plugin_event(JobControlRecord*,
                                        bEventType eventType,
                                        bEvent* event,
                                        PluginContext* ctx,
                                        void* value,
                                        alist<PluginContext*>*,
                                        int* index,
                                        bRC* rc)

{
  bool stop = false;

  if (!IsEventEnabled(ctx, eventType)) {
    Dmsg1(debuglevel, "Event %d disabled for this plugin.\n", eventType);
    if (rc) { *rc = bRC_OK; }
    goto bail_out;
  }

  if (IsPluginDisabled(ctx)) {
    if (rc) { *rc = bRC_OK; }
    goto bail_out;
  }

  if (eventType == bEventEndRestoreJob) {
    b_plugin_ctx* b_ctx = (b_plugin_ctx*)ctx->core_private_context;

    Dmsg0(50, "eventType == bEventEndRestoreJob\n");
    if (b_ctx && b_ctx->restoreFileStarted) {
      PlugFunc(ctx->plugin)->endRestoreFile(ctx);
    }

    if (b_ctx) {
      b_ctx->restoreFileStarted = false;
      b_ctx->createFileCalled = false;
    }
  }

  // See if we should care about the return code.
  if (rc) {
    *rc = PlugFunc(ctx->plugin)->handlePluginEvent(ctx, event, value);
    switch (*rc) {
      case bRC_OK:
        break;
      case bRC_Stop:
      case bRC_Error:
        stop = true;
        break;
      case bRC_More:
        break;
      case bRC_Term:
        /*
         * Request to unload this plugin.
         * As we remove the plugin from the list of plugins we decrement
         * the running index value so the next plugin gets triggered as
         * that moved back a position in the alist.
         */
        if (index) {
          UnloadPlugin(fd_plugin_list, ctx->plugin, *index);
          *index = ((*index) - 1);
        }
        break;
      case bRC_Seen:
        break;
      case bRC_Core:
        break;
      case bRC_Skip:
        stop = true;
        break;
      case bRC_Cancel:
        break;
      default:
        break;
    }
  } else {
    PlugFunc(ctx->plugin)->handlePluginEvent(ctx, event, value);
  }

bail_out:
  return stop;
}

/**
 * Create a plugin event When receiving bEventCancelCommand, this function is
 * called by another thread.
 */
bRC GeneratePluginEvent(JobControlRecord* jcr,
                        bEventType eventType,
                        void* value,
                        bool reverse)
{
  bEvent event;
  char* name = NULL;
  int len = 0;
  bool call_if_canceled = false;
  restore_object_pkt* rop;
  PluginContext* ctx = nullptr;
  alist<PluginContext*>* plugin_ctx_list;
  bRC rc = bRC_OK;

  if (!fd_plugin_list) {
    Dmsg0(debuglevel, "No bplugin_list: GeneratePluginEvent ignored.\n");
    goto bail_out;
  }

  if (!jcr) {
    Dmsg0(debuglevel, "No jcr: GeneratePluginEvent ignored.\n");
    goto bail_out;
  }

  if (!jcr->plugin_ctx_list) {
    Dmsg0(debuglevel, "No plugin_ctx_list: GeneratePluginEvent ignored.\n");
    goto bail_out;
  }

  plugin_ctx_list = jcr->plugin_ctx_list;

  /*
   * Some events are sent to only a particular plugin or must be called even if
   * the job is canceled.
   */
  switch (eventType) {
    case bEventPluginCommand:
    case bEventOptionPlugin:
      name = (char*)value;
      if (!GetPluginName(jcr, name, &len)) { goto bail_out; }
      break;
    case bEventRestoreObject:
      // After all RestoreObject, we have it one more time with value = NULL
      if (value) {
        // Some RestoreObjects may not have a plugin name
        rop = (restore_object_pkt*)value;
        if (*rop->plugin_name) {
          name = rop->plugin_name;
          if (!GetPluginName(jcr, name, &len)) { goto bail_out; }
        }
      }
      break;
    case bEventEndBackupJob:
    case bEventEndVerifyJob:
      call_if_canceled = true; /* plugin *must* see this call */
      break;
    case bEventStartRestoreJob:
      foreach_alist (ctx, plugin_ctx_list) {
        ((b_plugin_ctx*)ctx->core_private_context)->restoreFileStarted = false;
        ((b_plugin_ctx*)ctx->core_private_context)->createFileCalled = false;
      }
      break;
    case bEventEndRestoreJob:
      call_if_canceled = true; /* plugin *must* see this call */
      break;
    default:
      break;
  }

  // If call_if_canceled is set, we call the plugin anyway
  if (!call_if_canceled && jcr->IsJobCanceled()) { goto bail_out; }

  event.eventType = eventType;

  Dmsg2(debuglevel, "plugin_ctx=%p JobId=%d\n", plugin_ctx_list, jcr->JobId);

  /*
   * Pass event to every plugin that has requested this event type (except if
   * name is set). If name is set, we pass it only to the plugin with that name.
   *
   * See if we need to trigger the loaded plugins in reverse order.
   */
  if (reverse) {
    int i{};
    foreach_alist_rindex (i, ctx, plugin_ctx_list) {
      if (!IsEventForThisPlugin(ctx->plugin, name, len)) {
        Dmsg2(debuglevel, "Not for this plugin name=%s NULL=%d\n", name,
              (name == NULL) ? 1 : 0);
        continue;
      }

      if (trigger_plugin_event(jcr, eventType, &event, ctx, value,
                               plugin_ctx_list, &i, &rc)) {
        break;
      }
    }
  } else {
    int i{};
    foreach_alist_index (i, ctx, plugin_ctx_list) {
      if (!IsEventForThisPlugin(ctx->plugin, name, len)) {
        Dmsg2(debuglevel, "Not for this plugin name=%s NULL=%d\n", name,
              (name == NULL) ? 1 : 0);
        continue;
      }

      if (trigger_plugin_event(jcr, eventType, &event, ctx, value,
                               plugin_ctx_list, &i, &rc)) {
        break;
      }
    }
  }

  if (jcr->IsJobCanceled()) {
    Dmsg0(debuglevel, "Cancel return from GeneratePluginEvent\n");
    rc = bRC_Cancel;
  }

bail_out:
  return rc;
}

// Check if file was seen for accurate
bool PluginCheckFile(JobControlRecord* jcr, char* fname)
{
  PluginContext* ctx = nullptr;
  alist<PluginContext*>* plugin_ctx_list;
  int retval = bRC_OK;

  if (!fd_plugin_list || !jcr || !jcr->plugin_ctx_list
      || jcr->IsJobCanceled()) {
    return false; /* Return if no plugins loaded */
  }

  plugin_ctx_list = jcr->plugin_ctx_list;
  Dmsg2(debuglevel, "plugin_ctx=%p JobId=%d\n", jcr->plugin_ctx_list,
        jcr->JobId);

  // Pass event to every plugin
  foreach_alist (ctx, plugin_ctx_list) {
    if (IsPluginDisabled(ctx)) { continue; }

    jcr->plugin_ctx = ctx;
    if (PlugFunc(ctx->plugin)->checkFile == NULL) { continue; }

    retval = PlugFunc(ctx->plugin)->checkFile(ctx, fname);
    if (retval == bRC_Seen) { break; }
  }

  return retval == bRC_Seen;
}

/**
 * Get the first part of the the plugin command
 *  systemstate:/@SYSTEMSTATE/
 * => ret = 11
 * => can use IsEventForThisPlugin(plug, cmd, ret);
 *
 * The plugin command can contain only the plugin name
 *  Plugin = alldrives
 * => ret = 9
 */
static bool GetPluginName(JobControlRecord* jcr, char* cmd, int* ret)
{
  char* p;
  int len;

  if (!cmd || (*cmd == '\0')) { return false; }

  // Handle plugin command here backup
  Dmsg1(debuglevel, "plugin cmd=%s\n", cmd);
  if ((p = strchr(cmd, ':')) == NULL) {
    if (strchr(cmd, ' ') == NULL) { /* we have just the plugin name */
      len = strlen(cmd);
    } else {
      Jmsg1(jcr, M_ERROR, 0, "Malformed plugin command: %s\n", cmd);
      return false;
    }
  } else { /* plugin:argument */
    len = p - cmd;
    if (len <= 0) { return false; }
  }
  *ret = len;

  return true;
}

void PluginUpdateFfPkt(FindFilesPacket* ff_pkt, struct save_pkt* sp)
{
  ff_pkt->no_read = sp->no_read;
  ff_pkt->delta_seq = sp->delta_seq;

  if (BitIsSet(FO_DELTA, sp->flags)) {
    SetBit(FO_DELTA, ff_pkt->flags);
    ff_pkt->delta_seq++; /* make new delta sequence number */
  } else {
    ClearBit(FO_DELTA, ff_pkt->flags);
    ff_pkt->delta_seq = 0; /* clean delta sequence number */
  }

  if (BitIsSet(FO_OFFSETS, sp->flags)) {
    SetBit(FO_OFFSETS, ff_pkt->flags);
  } else {
    ClearBit(FO_OFFSETS, ff_pkt->flags);
  }

  /*
   * Sparse code doesn't work with plugins
   * that use FIFO or STDOUT/IN to communicate
   */
  if (BitIsSet(FO_SPARSE, sp->flags)) {
    SetBit(FO_SPARSE, ff_pkt->flags);
  } else {
    ClearBit(FO_SPARSE, ff_pkt->flags);
  }

  if (BitIsSet(FO_PORTABLE_DATA, sp->flags)) {
    SetBit(FO_PORTABLE_DATA, ff_pkt->flags);
  } else {
    ClearBit(FO_PORTABLE_DATA, ff_pkt->flags);
  }

  SetBit(FO_PLUGIN, ff_pkt->flags); /* data from plugin */
}

// Ask to a Option Plugin what to do with the current file
bRC PluginOptionHandleFile(JobControlRecord* jcr,
                           FindFilesPacket* ff_pkt,
                           struct save_pkt* sp)
{
  int len;
  char* cmd;
  bRC retval = bRC_Core;
  bEvent event;
  bEventType eventType;
  PluginContext* ctx = nullptr;
  alist<PluginContext*>* plugin_ctx_list;

  cmd = ff_pkt->plugin;
  eventType = bEventHandleBackupFile;
  event.eventType = eventType;

  memset(sp, 0, sizeof(struct save_pkt));
  sp->pkt_size = sp->pkt_end = sizeof(struct save_pkt);
  sp->portable = true;
  CopyBits(FO_MAX, ff_pkt->flags, sp->flags);
  sp->cmd = cmd;
  sp->link = ff_pkt->link;
  sp->statp = ff_pkt->statp;
  sp->type = ff_pkt->type;
  sp->fname = ff_pkt->fname;
  sp->delta_seq = ff_pkt->delta_seq;
  sp->accurate_found = ff_pkt->accurate_found;

  plugin_ctx_list = jcr->plugin_ctx_list;

  if (!fd_plugin_list || !plugin_ctx_list) {
    Jmsg1(jcr, M_FATAL, 0,
          "PluginOptionHandleFile: Command plugin \"%s\" requested, but is not "
          "loaded.\n",
          cmd);
    goto bail_out; /* Return if no plugins loaded */
  }

  if (jcr->IsJobCanceled()) {
    Jmsg1(jcr, M_FATAL, 0,
          "PluginOptionHandleFile: Command plugin \"%s\" requested, but job is "
          "already cancelled.\n",
          cmd);
    goto bail_out; /* Return if job is cancelled */
  }

  if (!GetPluginName(jcr, cmd, &len)) { goto bail_out; }

  // Note, we stop the loop on the first plugin that matches the name
  foreach_alist (ctx, plugin_ctx_list) {
    Dmsg4(debuglevel, "plugin=%s plen=%d cmd=%s len=%d\n", ctx->plugin->file,
          ctx->plugin->file_len, cmd, len);
    if (!IsEventForThisPlugin(ctx->plugin, cmd, len)) { continue; }

    if (!IsEventEnabled(ctx, eventType)) {
      Dmsg1(debuglevel, "Event %d disabled for this plugin.\n", eventType);
      continue;
    }

    if (IsPluginDisabled(ctx)) { goto bail_out; }

    jcr->plugin_ctx = ctx;
    retval = PlugFunc(ctx->plugin)->handlePluginEvent(ctx, &event, sp);

    goto bail_out;
  } /* end foreach loop */

bail_out:
  return retval;
}

/**
 * Sequence of calls for a backup:
 * 1. PluginSave() here is called with ff_pkt
 * 2. we find the plugin requested on the command string
 * 3. we generate a bEventBackupCommand event to the specified plugin
 *    and pass it the command string.
 * 4. we make a startPluginBackup call to the plugin, which gives
 *    us the data we need in save_pkt
 * 5. we call Bareos's SaveFile() subroutine to save the specified
 *    file.  The plugin will be called at pluginIO() to supply the
 *    file data.
 *
 * Sequence of calls for restore:
 *   See subroutine PluginNameStream() below.
 */
int PluginSave(JobControlRecord* jcr, FindFilesPacket* ff_pkt, bool)
{
  int len;
  bRC retval;
  char* cmd;
  bEvent event;
  PluginContext* ctx = nullptr;
  struct save_pkt sp;
  bEventType eventType;
  PoolMem fname(PM_FNAME);
  PoolMem link(PM_FNAME);
  alist<PluginContext*>* plugin_ctx_list;
  char flags[FOPTS_BYTES];

  cmd = ff_pkt->top_fname;
  plugin_ctx_list = jcr->plugin_ctx_list;

  if (!fd_plugin_list || !plugin_ctx_list) {
    Jmsg1(jcr, M_FATAL, 0,
          "PluginSave: Command plugin \"%s\" requested, but is not "
          "loaded.\n",
          cmd);
    goto bail_out; /* Return if no plugins loaded */
  }

  if (jcr->IsJobCanceled()) {
    Jmsg1(jcr, M_FATAL, 0,
          "PluginSave: Command plugin \"%s\" requested, but job is "
          "already cancelled.\n",
          cmd);
    goto bail_out; /* Return if job is cancelled */
  }


  jcr->cmd_plugin = true;
  eventType = bEventBackupCommand;
  event.eventType = eventType;

  if (!GetPluginName(jcr, cmd, &len)) { goto bail_out; }

  // Note, we stop the loop on the first plugin that matches the name
  foreach_alist (ctx, plugin_ctx_list) {
    Dmsg4(debuglevel, "plugin=%s plen=%d cmd=%s len=%d\n", ctx->plugin->file,
          ctx->plugin->file_len, cmd, len);
    if (!IsEventForThisPlugin(ctx->plugin, cmd, len)) { continue; }

    /*
     * We put the current plugin pointer, and the plugin context into the jcr,
     * because during SaveFile(), the plugin will be called many times and
     * these values are needed.
     */
    if (!IsEventEnabled(ctx, eventType)) {
      Dmsg1(debuglevel, "Event %d disabled for this plugin.\n", eventType);
      continue;
    }

    if (IsPluginDisabled(ctx)) { goto bail_out; }

    jcr->plugin_ctx = ctx;

    // Send the backup command to the right plugin
    Dmsg1(debuglevel, "Command plugin = %s\n", cmd);
    if (PlugFunc(ctx->plugin)->handlePluginEvent(jcr->plugin_ctx, &event, cmd)
        != bRC_OK) {
      goto bail_out;
    }

    // Loop getting filenames to backup then saving them
    while (!jcr->IsJobCanceled()) {
      memset(&sp, 0, sizeof(sp));
      sp.pkt_size = sizeof(sp);
      sp.pkt_end = sizeof(sp);
      sp.portable = true;
      sp.no_read = false;
      CopyBits(FO_MAX, ff_pkt->flags, sp.flags);
      sp.cmd = cmd;
      Dmsg3(debuglevel, "startBackup st_size=%p st_blocks=%p sp=%p\n",
            &sp.statp.st_size, &sp.statp.st_blocks, &sp);

      // Get the file save parameters. I.e. the stat pkt ...
      if (PlugFunc(ctx->plugin)->startBackupFile(ctx, &sp) != bRC_OK) {
        goto bail_out;
      }

      if (sp.type == 0) {
        Jmsg1(jcr, M_FATAL, 0,
              _("Command plugin \"%s\": no type in startBackupFile packet.\n"),
              cmd);
        goto bail_out;
      }

      jcr->impl->plugin_sp = &sp;
      ff_pkt = jcr->impl->ff;

      // Save original flags.
      CopyBits(FO_MAX, ff_pkt->flags, flags);

      /*
       * Copy fname and link because SaveFile() zaps them.  This avoids zaping
       * the plugin's strings.
       */
      ff_pkt->type = sp.type;
      if (IS_FT_OBJECT(sp.type)) {
        if (!sp.object_name) {
          Jmsg1(jcr, M_FATAL, 0,
                _("Command plugin \"%s\": no object_name in startBackupFile "
                  "packet.\n"),
                cmd);
          goto bail_out;
        }
        ff_pkt->fname = cmd; /* full plugin string */
        ff_pkt->object_name = sp.object_name;
        ff_pkt->object_index = sp.index; /* restore object index */
        ff_pkt->object_compression = 0;  /* no compression for now */
        ff_pkt->object = sp.object;
        ff_pkt->object_len = sp.object_len;
      } else {
        if (!sp.fname) {
          Jmsg1(jcr, M_FATAL, 0,
                _("Command plugin \"%s\": no fname in startBackupFile "
                  "packet.\n"),
                cmd);
          goto bail_out;
        }

        PmStrcpy(fname, sp.fname);
        PmStrcpy(link, sp.link);

        ff_pkt->fname = fname.c_str();
        ff_pkt->link = link.c_str();

        PluginUpdateFfPkt(ff_pkt, &sp);
      }

      memcpy(&ff_pkt->statp, &sp.statp, sizeof(ff_pkt->statp));
      Dmsg2(debuglevel, "startBackup returned type=%d, fname=%s\n", sp.type,
            sp.fname);
      if (sp.object) {
        Dmsg2(debuglevel, "index=%d object=%s\n", sp.index, sp.object);
      }

      /*
       * Handle hard linked files
       *
       * Maintain a list of hard linked files already backed up. This allows
       * us to ensure that the data of each file gets backed up only once.
       */
      ff_pkt->LinkFI = 0;
      if (!BitIsSet(FO_NO_HARDLINK, ff_pkt->flags)
          && ff_pkt->statp.st_nlink > 1) {
        CurLink* hl;

        switch (ff_pkt->statp.st_mode & S_IFMT) {
          case S_IFREG:
          case S_IFCHR:
          case S_IFBLK:
          case S_IFIFO:
#ifdef S_IFSOCK
          case S_IFSOCK:
#endif
            hl = lookup_hardlink(jcr, ff_pkt, ff_pkt->statp.st_ino,
                                 ff_pkt->statp.st_dev);
            if (hl) {
              /*
               * If we have already backed up the hard linked file don't do it
               * again
               */
              if (bstrcmp(hl->name, sp.fname)) {
                Dmsg2(400, "== Name identical skip FI=%d file=%s\n",
                      hl->FileIndex, fname.c_str());
                ff_pkt->no_read = true;
              } else {
                ff_pkt->link = hl->name;
                ff_pkt->type
                    = FT_LNKSAVED; /* Handle link, file already saved */
                ff_pkt->LinkFI = hl->FileIndex;
                ff_pkt->linked = NULL;
                ff_pkt->digest = hl->digest;
                ff_pkt->digest_stream = hl->digest_stream;
                ff_pkt->digest_len = hl->digest_len;

                Dmsg3(400, "FT_LNKSAVED FI=%d LinkFI=%d file=%s\n",
                      ff_pkt->FileIndex, hl->FileIndex, hl->name);

                ff_pkt->no_read = true;
              }
            } else {
              // File not previously dumped. Chain it into our list.
              hl = new_hardlink(jcr, ff_pkt, sp.fname, ff_pkt->statp.st_ino,
                                ff_pkt->statp.st_dev);
              ff_pkt->linked = hl; /* Mark saved link */
              Dmsg2(400, "Added to hash FI=%d file=%s\n", ff_pkt->FileIndex,
                    hl->name);
            }
            break;
          default:
            ff_pkt->linked = NULL;
            break;
        }
      } else {
        ff_pkt->linked = NULL;
      }

      // Call Bareos core code to backup the plugin's file
      SaveFile(jcr, ff_pkt, true);

      // Restore original flags.
      CopyBits(FO_MAX, flags, ff_pkt->flags);

      retval = PlugFunc(ctx->plugin)->endBackupFile(ctx);
      if (retval == bRC_More || retval == bRC_OK) {
        AccurateMarkFileAsSeen(jcr, fname.c_str());
      }

      if (retval == bRC_More) { continue; }

      goto bail_out;
    } /* end while loop */

    goto bail_out;
  } /* end loop over all plugins */
  Jmsg1(jcr, M_FATAL, 0, "Command plugin \"%s\" not found.\n", cmd);

bail_out:
  jcr->cmd_plugin = false;

  return 1;
}

/**
 * Sequence of calls for a estimate:
 * 1. PluginEstimate() here is called with ff_pkt
 * 2. we find the plugin requested on the command string
 * 3. we generate a bEventEstimateCommand event to the specified plugin
 *    and pass it the command string.
 * 4. we make a startPluginBackup call to the plugin, which gives
 *    us the data we need in save_pkt
 *
 */
int PluginEstimate(JobControlRecord* jcr, FindFilesPacket* ff_pkt, bool)
{
  int len;
  char* cmd = ff_pkt->top_fname;
  struct save_pkt sp;
  bEvent event;
  bEventType eventType;
  PoolMem fname(PM_FNAME);
  PoolMem link(PM_FNAME);
  PluginContext* ctx = nullptr;
  alist<PluginContext*>* plugin_ctx_list;
  Attributes attr;

  plugin_ctx_list = jcr->plugin_ctx_list;
  if (!fd_plugin_list || !plugin_ctx_list) {
    Jmsg1(jcr, M_FATAL, 0,
          "Command plugin \"%s\" requested, but is not loaded.\n", cmd);
    return 1; /* Return if no plugins loaded */
  }

  jcr->cmd_plugin = true;
  eventType = bEventEstimateCommand;
  event.eventType = eventType;

  if (!GetPluginName(jcr, cmd, &len)) { goto bail_out; }

  // Note, we stop the loop on the first plugin that matches the name
  foreach_alist (ctx, plugin_ctx_list) {
    Dmsg4(debuglevel, "plugin=%s plen=%d cmd=%s len=%d\n", ctx->plugin->file,
          ctx->plugin->file_len, cmd, len);
    if (!IsEventForThisPlugin(ctx->plugin, cmd, len)) { continue; }

    /*
     * We put the current plugin pointer, and the plugin context into the jcr,
     * because during SaveFile(), the plugin will be called many times and
     * these values are needed.
     */
    if (!IsEventEnabled(ctx, eventType)) {
      Dmsg1(debuglevel, "Event %d disabled for this plugin.\n", eventType);
      continue;
    }

    if (IsPluginDisabled(ctx)) { goto bail_out; }

    jcr->plugin_ctx = ctx;

    // Send the backup command to the right plugin
    Dmsg1(debuglevel, "Command plugin = %s\n", cmd);
    if (PlugFunc(ctx->plugin)->handlePluginEvent(ctx, &event, cmd) != bRC_OK) {
      goto bail_out;
    }

    // Loop getting filenames to backup then saving them
    while (!jcr->IsJobCanceled()) {
      memset(&sp, 0, sizeof(sp));
      sp.pkt_size = sizeof(sp);
      sp.pkt_end = sizeof(sp);
      sp.portable = true;
      CopyBits(FO_MAX, ff_pkt->flags, sp.flags);
      sp.cmd = cmd;
      Dmsg3(debuglevel, "startBackup st_size=%p st_blocks=%p sp=%p\n",
            &sp.statp.st_size, &sp.statp.st_blocks, &sp);

      // Get the file save parameters. I.e. the stat pkt ...
      if (PlugFunc(ctx->plugin)->startBackupFile(ctx, &sp) != bRC_OK) {
        goto bail_out;
      }

      if (sp.type == 0) {
        Jmsg1(jcr, M_FATAL, 0,
              _("Command plugin \"%s\": no type in startBackupFile packet.\n"),
              cmd);
        goto bail_out;
      }

      if (!IS_FT_OBJECT(sp.type)) {
        if (!sp.fname) {
          Jmsg1(jcr, M_FATAL, 0,
                _("Command plugin \"%s\": no fname in startBackupFile "
                  "packet.\n"),
                cmd);
          goto bail_out;
        }

        // Count only files backed up
        switch (sp.type) {
          case FT_REGE:
          case FT_REG:
          case FT_LNK:
          case FT_DIREND:
          case FT_SPEC:
          case FT_RAW:
          case FT_FIFO:
          case FT_LNKSAVED:
            jcr->JobFiles++; /* increment number of files backed up */
            break;
          default:
            break;
        }
        jcr->impl->num_files_examined++;

        if (sp.type != FT_LNKSAVED && S_ISREG(sp.statp.st_mode)) {
          if (sp.statp.st_size > 0) { jcr->JobBytes += sp.statp.st_size; }
        }

        if (jcr->impl->listing) {
          memcpy(&attr.statp, &sp.statp, sizeof(struct stat));
          attr.type = sp.type;
          attr.ofname = (POOLMEM*)sp.fname;
          attr.olname = (POOLMEM*)sp.link;
          PrintLsOutput(jcr, &attr);
        }
      }

      Dmsg2(debuglevel, "startBackup returned type=%d, fname=%s\n", sp.type,
            sp.fname);
      if (sp.object) {
        Dmsg2(debuglevel, "index=%d object=%s\n", sp.index, sp.object);
      }

      bRC retval = PlugFunc(ctx->plugin)->endBackupFile(ctx);
      if (retval == bRC_More || retval == bRC_OK) {
        AccurateMarkFileAsSeen(jcr, sp.fname);
      }

      if (retval == bRC_More) { continue; }

      goto bail_out;
    } /* end while loop */

    goto bail_out;
  } /* end loop over all plugins */
  Jmsg1(jcr, M_FATAL, 0, "Command plugin \"%s\" not found.\n", cmd);

bail_out:
  jcr->cmd_plugin = false;

  return 1;
}

// Send plugin name start/end record to SD
bool SendPluginName(JobControlRecord* jcr, BareosSocket* sd, bool start)
{
  int status;
  int index = jcr->JobFiles;
  struct save_pkt* sp = (struct save_pkt*)jcr->impl->plugin_sp;

  if (!sp) {
    Jmsg0(jcr, M_FATAL, 0, _("Plugin save packet not found.\n"));
    return false;
  }
  if (jcr->IsJobCanceled()) { return false; }

  if (start) { index++; /* JobFiles not incremented yet */ }
  Dmsg1(debuglevel, "SendPluginName=%s\n", sp->cmd);

  // Send stream header
  if (!sd->fsend("%ld %d 0", index, STREAM_PLUGIN_NAME)) {
    Jmsg1(jcr, M_FATAL, 0, _("Network send error to SD. ERR=%s\n"),
          sd->bstrerror());
    return false;
  }
  Dmsg1(debuglevel, "send plugin name hdr: %s\n", sd->msg);

  if (start) {
    // Send data -- not much
    status = sd->fsend("%ld 1 %d %s%c", index, sp->portable, sp->cmd, 0);
  } else {
    // Send end of data
    status = sd->fsend("%ld 0", jcr->JobFiles);
  }
  if (!status) {
    Jmsg1(jcr, M_FATAL, 0, _("Network send error to SD. ERR=%s\n"),
          sd->bstrerror());
    return false;
  }
  Dmsg1(debuglevel, "send plugin start/end: %s\n", sd->msg);
  sd->signal(BNET_EOD); /* indicate end of plugin name data */

  return true;
}

/**
 * Plugin name stream found during restore.  The record passed in argument
 * name was generated in SendPluginName() above.
 *
 * Returns: true  if start of stream
 *          false if end of steam
 */
bool PluginNameStream(JobControlRecord* jcr, char* name)
{
  int len;
  char* cmd;
  char* p = name;
  bool start;
  bool retval = true;
  PluginContext* ctx = nullptr;
  alist<PluginContext*>* plugin_ctx_list;

  Dmsg1(debuglevel, "Read plugin stream string=%s\n", name);
  SkipNonspaces(&p); /* skip over jcr->JobFiles */
  SkipSpaces(&p);
  start = *p == '1';
  if (start) {
    // Start of plugin data
    SkipNonspaces(&p); /* skip start/end flag */
    SkipSpaces(&p);
    SkipNonspaces(&p); /* skip portable flag */
    SkipSpaces(&p);
    cmd = p;
  } else {
    // End of plugin data, notify plugin, then clear flags
    if (jcr->plugin_ctx) {
      Plugin* plugin = jcr->plugin_ctx->plugin;
      b_plugin_ctx* b_ctx
          = (b_plugin_ctx*)jcr->plugin_ctx->core_private_context;

      Dmsg2(debuglevel, "End plugin data plugin=%p ctx=%p\n", plugin,
            jcr->plugin_ctx);
      if (b_ctx->restoreFileStarted) {
        /* PlugFunc(plugin)->endRestoreFile(jcr->plugin_ctx); */
        bRC ret = PlugFunc(plugin)->endRestoreFile(jcr->plugin_ctx);
        Dmsg1(debuglevel, "endRestoreFile ret: %d\n", ret);
        if (ret == PYTHON_UNDEFINED_RETURN_VALUE) {
          Jmsg2(jcr, M_FATAL, 0,
                "Return value of endRestoreFile invalid: %d, plugin=%s\n", ret,
                jcr->plugin_ctx->plugin->file);
          retval = false;
        }
      }
      b_ctx->restoreFileStarted = false;
      b_ctx->createFileCalled = false;
    }

    goto bail_out;
  }

  plugin_ctx_list = jcr->plugin_ctx_list;
  if (!plugin_ctx_list) { goto bail_out; }

  // After this point, we are dealing with a restore start
  if (!GetPluginName(jcr, cmd, &len)) { goto bail_out; }

  // Search for correct plugin as specified on the command
  foreach_alist (ctx, plugin_ctx_list) {
    bEvent event;
    bEventType eventType;
    b_plugin_ctx* b_ctx;

    Dmsg3(debuglevel, "plugin=%s cmd=%s len=%d\n", ctx->plugin->file, cmd, len);
    if (!IsEventForThisPlugin(ctx->plugin, cmd, len)) { continue; }

    if (IsPluginDisabled(ctx)) {
      Dmsg1(debuglevel, "Plugin %s disabled\n", cmd);
      goto bail_out;
    }

    Dmsg1(debuglevel, "Restore Command plugin = %s\n", cmd);
    eventType = bEventRestoreCommand;
    event.eventType = eventType;

    if (!IsEventEnabled(ctx, eventType)) {
      Dmsg1(debuglevel, "Event %d disabled for this plugin.\n", eventType);
      continue;
    }

    jcr->plugin_ctx = ctx;
    jcr->cmd_plugin = true;
    b_ctx = (b_plugin_ctx*)ctx->core_private_context;

    if (PlugFunc(ctx->plugin)->handlePluginEvent(jcr->plugin_ctx, &event, cmd)
        != bRC_OK) {
      Dmsg1(debuglevel, "Handle event failed. Plugin=%s\n", cmd);
      goto bail_out;
    }

    if (b_ctx->restoreFileStarted) {
      Jmsg2(jcr, M_FATAL, 0,
            "Second call to startRestoreFile. plugin=%s cmd=%s\n",
            ctx->plugin->file, cmd);
      b_ctx->restoreFileStarted = false;
      goto bail_out;
    }

    if (PlugFunc(ctx->plugin)->startRestoreFile(jcr->plugin_ctx, cmd)
        == bRC_OK) {
      b_ctx->restoreFileStarted = true;
      goto bail_out;
    } else {
      Dmsg1(debuglevel, "startRestoreFile failed. plugin=%s\n", cmd);
      goto bail_out;
    }
  }
  Jmsg1(jcr, M_WARNING, 0, _("Plugin=%s not found.\n"), cmd);

bail_out:
  return retval;
}

/**
 * Tell the plugin to create the file. this is called only during Restore.
 * Return values are:
 *
 * CF_ERROR    -> error
 * CF_SKIP     -> skip processing this file
 * CF_EXTRACT  -> extract the file (i.e.call i/o routines)
 * CF_CREATED  -> created, but no content to extract (typically directories)
 */
int PluginCreateFile(JobControlRecord* jcr,
                     Attributes* attr,
                     BareosWinFilePacket* bfd,
                     int)
{
  int flags;
  int retval;
  int status;
  Plugin* plugin;
  struct restore_pkt rp;
  PluginContext* ctx = jcr->plugin_ctx;
  b_plugin_ctx* b_ctx = (b_plugin_ctx*)jcr->plugin_ctx->core_private_context;

  if (!ctx || !SetCmdPlugin(bfd, jcr) || jcr->IsJobCanceled()) {
    return CF_ERROR;
  }
  plugin = ctx->plugin;

  rp.pkt_size = sizeof(rp);
  rp.pkt_end = sizeof(rp);
  rp.delta_seq = attr->delta_seq;
  rp.stream = attr->stream;
  rp.data_stream = attr->data_stream;
  rp.type = attr->type;
  rp.file_index = attr->file_index;
  rp.LinkFI = attr->LinkFI;
  rp.uid = attr->uid;
  memcpy(&rp.statp, &attr->statp, sizeof(rp.statp));
  rp.attrEx = attr->attrEx;
  rp.ofname = attr->ofname;
  rp.olname = attr->olname;
  rp.where = jcr->where;
  rp.RegexWhere = jcr->RegexWhere;
  rp.replace = jcr->impl->replace;
  rp.create_status = CF_ERROR;

  Dmsg4(debuglevel,
        "call plugin createFile stream=%d type=%d LinkFI=%d File=%s\n",
        rp.stream, rp.type, rp.LinkFI, rp.ofname);
  if (rp.attrEx) { Dmsg1(debuglevel, "attrEx=\"%s\"\n", rp.attrEx); }

  if (!b_ctx->restoreFileStarted || b_ctx->createFileCalled) {
    Jmsg2(jcr, M_FATAL, 0, "Unbalanced call to createFile=%d %d\n",
          b_ctx->createFileCalled, b_ctx->restoreFileStarted);
    b_ctx->createFileCalled = false;
    return CF_ERROR;
  }

  retval = PlugFunc(plugin)->createFile(ctx, &rp);
  if (retval != bRC_OK) {
    Qmsg2(jcr, M_ERROR, 0,
          _("Plugin createFile call failed. Stat=%d file=%s\n"), retval,
          attr->ofname);
    return CF_ERROR;
  }

  switch (rp.create_status) {
    case CF_ERROR:
      Qmsg1(jcr, M_ERROR, 0,
            _("Plugin createFile call failed. Returned CF_ERROR file=%s\n"),
            attr->ofname);
      [[fallthrough]];
    case CF_SKIP:
      [[fallthrough]];
    case CF_CORE:
      [[fallthrough]];
    case CF_CREATED:
      return rp.create_status;
  }

  flags = O_WRONLY | O_CREAT | O_TRUNC | O_BINARY;
  Dmsg0(debuglevel, "call bopen\n");

  status
      = bopen(bfd, attr->ofname, flags, S_IRUSR | S_IWUSR, attr->statp.st_rdev);
  Dmsg1(debuglevel, "bopen status=%d\n", status);

  if (status < 0) {
    BErrNo be;

    be.SetErrno(bfd->BErrNo);
    Qmsg2(jcr, M_ERROR, 0, _("Could not create %s: ERR=%s\n"), attr->ofname,
          be.bstrerror());
    Dmsg2(debuglevel, "Could not bopen file %s: ERR=%s\n", attr->ofname,
          be.bstrerror());
    return CF_ERROR;
  }

  if (!IsBopen(bfd)) { Dmsg0(000, "===== BFD is not open!!!!\n"); }

  return CF_EXTRACT;
}

/**
 * Reset the file attributes after all file I/O is done -- this allows the
 * previous access time/dates to be set properly, and it also allows us to
 * properly set directory permissions.
 */
bool PluginSetAttributes(JobControlRecord* jcr,
                         Attributes* attr,
                         BareosWinFilePacket* ofd)
{
  Plugin* plugin;
  struct restore_pkt rp;

  Dmsg0(debuglevel, "PluginSetAttributes\n");

  if (!jcr->plugin_ctx) { return false; }
  plugin = (Plugin*)jcr->plugin_ctx->plugin;

  memset(&rp, 0, sizeof(rp));
  rp.pkt_size = sizeof(rp);
  rp.pkt_end = sizeof(rp);
  rp.stream = attr->stream;
  rp.data_stream = attr->data_stream;
  rp.type = attr->type;
  rp.file_index = attr->file_index;
  rp.LinkFI = attr->LinkFI;
  rp.uid = attr->uid;
  memcpy(&rp.statp, &attr->statp, sizeof(rp.statp));
  rp.attrEx = attr->attrEx;
  rp.ofname = attr->ofname;
  rp.olname = attr->olname;
  rp.where = jcr->where;
  rp.RegexWhere = jcr->RegexWhere;
  rp.replace = jcr->impl->replace;
  rp.create_status = CF_ERROR;

  PlugFunc(plugin)->setFileAttributes(jcr->plugin_ctx, &rp);

  if (rp.create_status == CF_CORE) {
    SetAttributes(jcr, attr, ofd);
  } else {
    if (IsBopen(ofd)) { bclose(ofd); }
    PmStrcpy(attr->ofname, "*None*");
  }

  return true;
}

// Plugin specific callback for getting ACL information.
bacl_exit_code PluginBuildAclStreams(JobControlRecord* jcr,
                                     [[maybe_unused]] AclData* acl_data,
                                     FindFilesPacket*)
{
  Plugin* plugin;

  Dmsg0(debuglevel, "PluginBuildAclStreams\n");

  if (!jcr->plugin_ctx) { return bacl_exit_ok; }
  plugin = (Plugin*)jcr->plugin_ctx->plugin;

  if (PlugFunc(plugin)->getAcl == NULL) {
    return bacl_exit_ok;
  } else {
    bacl_exit_code retval = bacl_exit_error;
#if defined(HAVE_ACL)
    struct acl_pkt ap;

    memset(&ap, 0, sizeof(ap));
    ap.pkt_size = ap.pkt_end = sizeof(struct acl_pkt);
    ap.fname = acl_data->last_fname;

    switch (PlugFunc(plugin)->getAcl(jcr->plugin_ctx, &ap)) {
      case bRC_OK:
        if (ap.content_length && ap.content) {
          acl_data->u.build->content = CheckPoolMemorySize(
              acl_data->u.build->content, ap.content_length);
          memcpy(acl_data->u.build->content, ap.content, ap.content_length);
          acl_data->u.build->content_length = ap.content_length;
          free(ap.content);
          retval = SendAclStream(jcr, acl_data, STREAM_ACL_PLUGIN);
        } else {
          retval = bacl_exit_ok;
        }
        break;
      default:
        break;
    }
#endif

    return retval;
  }
}

// Plugin specific callback for setting ACL information.
bacl_exit_code plugin_parse_acl_streams(
    JobControlRecord* jcr,
    [[maybe_unused]] AclData* acl_data,
    int,
    [[maybe_unused]] char* content,
    [[maybe_unused]] uint32_t content_length)
{
  Plugin* plugin;

  Dmsg0(debuglevel, "plugin_parse_acl_streams\n");

  if (!jcr->plugin_ctx) { return bacl_exit_ok; }
  plugin = (Plugin*)jcr->plugin_ctx->plugin;

  if (PlugFunc(plugin)->setAcl == NULL) {
    return bacl_exit_error;
  } else {
    bacl_exit_code retval = bacl_exit_error;
#if defined(HAVE_ACL)
    struct acl_pkt ap;

    memset(&ap, 0, sizeof(ap));
    ap.pkt_size = ap.pkt_end = sizeof(struct acl_pkt);
    ap.fname = acl_data->last_fname;
    ap.content = content;
    ap.content_length = content_length;

    switch (PlugFunc(plugin)->setAcl(jcr->plugin_ctx, &ap)) {
      case bRC_OK:
        retval = bacl_exit_ok;
        break;
      default:
        break;
    }
#endif

    return retval;
  }
}

// Plugin specific callback for getting XATTR information.
BxattrExitCode PluginBuildXattrStreams(
    JobControlRecord* jcr,
    [[maybe_unused]] struct XattrData* xattr_data,
    FindFilesPacket*)
{
  Plugin* plugin;
#if defined(HAVE_XATTR)
  alist<xattr_t*>* xattr_value_list = NULL;
#endif
  BxattrExitCode retval = BxattrExitCode::kError;

  Dmsg0(debuglevel, "PluginBuildXattrStreams\n");

  if (!jcr->plugin_ctx) { return BxattrExitCode::kSuccess; }
  plugin = (Plugin*)jcr->plugin_ctx->plugin;

  if (PlugFunc(plugin)->getXattr == NULL) {
    return BxattrExitCode::kSuccess;
  } else {
#if defined(HAVE_XATTR)
    bool more;
    int xattr_count = 0;
    xattr_t* current_xattr;
    struct xattr_pkt xp;
    uint32_t expected_serialize_len = 0;

    while (1) {
      memset(&xp, 0, sizeof(xp));
      xp.pkt_size = xp.pkt_end = sizeof(struct xattr_pkt);
      xp.fname = xattr_data->last_fname;

      switch (PlugFunc(plugin)->getXattr(jcr->plugin_ctx, &xp)) {
        case bRC_OK:
          more = false;
          break;
        case bRC_More:
          more = true;
          break;
        default:
          goto bail_out;
      }

      /*
       * Make sure the plugin filled a XATTR name.
       * The name and value returned by the plugin need to be in allocated
       * memory and are freed by XattrDropInternalTable() function when we are
       * done processing the data.
       */
      if (xp.name_length && xp.name) {
        // Each xattr valuepair starts with a magic so we can parse it easier.
        current_xattr = (xattr_t*)malloc(sizeof(xattr_t));
        current_xattr->magic = XATTR_MAGIC;
        expected_serialize_len += sizeof(current_xattr->magic);

        current_xattr->name_length = xp.name_length;
        current_xattr->name = xp.name;
        expected_serialize_len
            += sizeof(current_xattr->name_length) + current_xattr->name_length;

        current_xattr->value_length = xp.value_length;
        current_xattr->value = xp.value;
        expected_serialize_len += sizeof(current_xattr->value_length)
                                  + current_xattr->value_length;

        if (xattr_value_list == NULL) {
          xattr_value_list = new alist<xattr_t*>(10, not_owned_by_alist);
        }

        xattr_value_list->append(current_xattr);
        xattr_count++;

        // Protect ourself against things getting out of hand.
        if (expected_serialize_len >= MAX_XATTR_STREAM) {
          Mmsg2(jcr->errmsg,
                _("Xattr stream on file \"%s\" exceeds maximum size of %d "
                  "bytes\n"),
                xattr_data->last_fname, MAX_XATTR_STREAM);
          goto bail_out;
        }
      }

      // Does the plugin have more xattrs ?
      if (!more) { break; }
    }

    // If we found any xattr send them to the SD.
    if (xattr_count > 0) {
      // Serialize the datastream.
      if (SerializeXattrStream(jcr, xattr_data, expected_serialize_len,
                               xattr_value_list)
          < expected_serialize_len) {
        Mmsg1(jcr->errmsg,
              _("Failed to Serialize extended attributes on file \"%s\"\n"),
              xattr_data->last_fname);
        Dmsg1(100, "Failed to Serialize extended attributes on file \"%s\"\n",
              xattr_data->last_fname);
        goto bail_out;
      }

      // Send the datastream to the SD.
      retval = SendXattrStream(jcr, xattr_data, STREAM_XATTR_PLUGIN);
    } else {
      retval = BxattrExitCode::kSuccess;
    }
#endif
  }

#if defined(HAVE_XATTR)
bail_out:
  if (xattr_value_list) { XattrDropInternalTable(xattr_value_list); }
#endif

  return retval;
}

// Plugin specific callback for setting XATTR information.
BxattrExitCode PluginParseXattrStreams(
    JobControlRecord* jcr,
    [[maybe_unused]] struct XattrData* xattr_data,
    int,
    [[maybe_unused]] char* content,
    [[maybe_unused]] uint32_t content_length)
{
#if defined(HAVE_XATTR)
  Plugin* plugin;
  alist<xattr_t*>* xattr_value_list = NULL;
#endif
  BxattrExitCode retval = BxattrExitCode::kError;

  Dmsg0(debuglevel, "PluginParseXattrStreams\n");

  if (!jcr->plugin_ctx) { return BxattrExitCode::kSuccess; }

#if defined(HAVE_XATTR)
  plugin = (Plugin*)jcr->plugin_ctx->plugin;
  if (PlugFunc(plugin)->setXattr != NULL) {
    xattr_t* current_xattr = nullptr;
    struct xattr_pkt xp;

    xattr_value_list = new alist<xattr_t*>(10, not_owned_by_alist);

    if (UnSerializeXattrStream(jcr, xattr_data, content, content_length,
                               xattr_value_list)
        != BxattrExitCode::kSuccess) {
      goto bail_out;
    }

    memset(&xp, 0, sizeof(xp));
    xp.pkt_size = xp.pkt_end = sizeof(struct xattr_pkt);
    xp.fname = xattr_data->last_fname;

    foreach_alist (current_xattr, xattr_value_list) {
      xp.name = current_xattr->name;
      xp.name_length = current_xattr->name_length;
      xp.value = current_xattr->value;
      xp.value_length = current_xattr->value_length;

      switch (PlugFunc(plugin)->setXattr(jcr->plugin_ctx, &xp)) {
        case bRC_OK:
          break;
        default:
          goto bail_out;
      }
    }

    retval = BxattrExitCode::kSuccess;
  }

bail_out:
  if (xattr_value_list) { XattrDropInternalTable(xattr_value_list); }
#endif

  return retval;
}

// Print to file the plugin info.
static void DumpFdPlugin(Plugin* plugin, FILE* fp)
{
  PluginInformation* info;

  if (!plugin) { return; }

  info = (PluginInformation*)plugin->plugin_information;
  if (!info) { return; }

  fprintf(fp, "\tversion=%d\n", info->version);
  fprintf(fp, "\tdate=%s\n", NPRTB(info->plugin_date));
  fprintf(fp, "\tmagic=%s\n", NPRTB(info->plugin_magic));
  fprintf(fp, "\tauthor=%s\n", NPRTB(info->plugin_author));
  fprintf(fp, "\tlicence=%s\n", NPRTB(info->plugin_license));
  fprintf(fp, "\tversion=%s\n", NPRTB(info->plugin_version));
  fprintf(fp, "\tdescription=%s\n", NPRTB(info->plugin_description));
}

static void DumpFdPlugins(FILE* fp) { DumpPlugins(fd_plugin_list, fp); }

/**
 * This entry point is called internally by Bareos to ensure that the plugin
 * IO calls come into this code.
 */
void LoadFdPlugins(const char* plugin_dir, alist<const char*>* plugin_names)
{
  Plugin* plugin;

  if (!plugin_dir) {
    Dmsg0(debuglevel, "plugin dir is NULL\n");
    return;
  }

  fd_plugin_list = new alist<Plugin*>(10, not_owned_by_alist);
  if (!LoadPlugins((void*)&bareos_plugin_interface_version,
                   (void*)&bareos_core_functions, fd_plugin_list, plugin_dir,
                   plugin_names, plugin_type, IsPluginCompatible)) {
    // Either none found, or some error
    if (fd_plugin_list->size() == 0) {
      delete fd_plugin_list;
      fd_plugin_list = NULL;
      Dmsg0(debuglevel, "No plugins loaded\n");
      return;
    }
  }

  // Plug entry points called from findlib
  plugin_bopen = MyPluginBopen;
  plugin_bclose = MyPluginBclose;
  plugin_bread = MyPluginBread;
  plugin_bwrite = MyPluginBwrite;
  plugin_blseek = MyPluginBlseek;

  // Verify that the plugin is acceptable, and print information about it.
  int i{0};
  foreach_alist_index (i, plugin, fd_plugin_list) {
    Dmsg1(debuglevel, "Loaded plugin: %s\n", plugin->file);
  }

  DbgPluginAddHook(DumpFdPlugin);
  DbgPrintPluginAddHook(DumpFdPlugins);
}

void UnloadFdPlugins(void)
{
  UnloadPlugins(fd_plugin_list);
  delete fd_plugin_list;
  fd_plugin_list = NULL;
}

int ListFdPlugins(PoolMem& msg) { return ListPlugins(fd_plugin_list, msg); }

/**
 * Check if a plugin is compatible.  Called by the load_plugin function to
 * allow us to verify the plugin.
 */
static bool IsPluginCompatible(Plugin* plugin)
{
  PluginInformation* info = (PluginInformation*)plugin->plugin_information;
  Dmsg0(debuglevel, "IsPluginCompatible called\n");
  if (!info) {
    Dmsg0(debuglevel, "IsPluginCompatible: plugin_information is empty\n");
    return false;
  }
  if (debug_level >= 50) { DumpFdPlugin(plugin, stdin); }
  if (!bstrcmp(info->plugin_magic, FD_PLUGIN_MAGIC)) {
    Jmsg(NULL, M_ERROR, 0,
         _("Plugin magic wrong. Plugin=%s wanted=%s got=%s\n"), plugin->file,
         FD_PLUGIN_MAGIC, info->plugin_magic);
    Dmsg3(50, "Plugin magic wrong. Plugin=%s wanted=%s got=%s\n", plugin->file,
          FD_PLUGIN_MAGIC, info->plugin_magic);

    return false;
  }
  if (info->version != FD_PLUGIN_INTERFACE_VERSION) {
    Jmsg(NULL, M_ERROR, 0,
         _("Plugin version incorrect. Plugin=%s wanted=%d got=%d\n"),
         plugin->file, FD_PLUGIN_INTERFACE_VERSION, info->version);
    Dmsg3(50, "Plugin version incorrect. Plugin=%s wanted=%d got=%d\n",
          plugin->file, FD_PLUGIN_INTERFACE_VERSION, info->version);
    return false;
  }
  if (!Bstrcasecmp(info->plugin_license, "Bareos AGPLv3")
      && !Bstrcasecmp(info->plugin_license, "AGPLv3")) {
    Jmsg(NULL, M_ERROR, 0,
         _("Plugin license incompatible. Plugin=%s license=%s\n"), plugin->file,
         info->plugin_license);
    Dmsg2(50, "Plugin license incompatible. Plugin=%s license=%s\n",
          plugin->file, info->plugin_license);
    return false;
  }
  if (info->size != sizeof(PluginInformation)) {
    Jmsg(NULL, M_ERROR, 0,
         _("Plugin size incorrect. Plugin=%s wanted=%d got=%d\n"), plugin->file,
         sizeof(PluginInformation), info->size);
    return false;
  }

  return true;
}

// Instantiate a new plugin instance.
static inline PluginContext* instantiate_plugin(JobControlRecord* jcr,
                                                Plugin* plugin,
                                                char instance)
{
  PluginContext* ctx;
  b_plugin_ctx* b_ctx;

  b_ctx = (b_plugin_ctx*)malloc(sizeof(b_plugin_ctx));
  b_ctx = (b_plugin_ctx*)memset(b_ctx, 0, sizeof(b_plugin_ctx));
  b_ctx->jcr = jcr;
  b_ctx->plugin = plugin;

  ctx = (PluginContext*)malloc(sizeof(PluginContext));
  ctx->instance = instance;
  ctx->plugin = plugin;
  ctx->core_private_context = (void*)b_ctx;
  ctx->plugin_private_context = NULL;

  jcr->plugin_ctx_list->append(ctx);

  if (PlugFunc(plugin)->newPlugin(ctx) != bRC_OK) { b_ctx->disabled = true; }

  return ctx;
}

/**
 * Create a new instance of each plugin for this Job
 *
 * Note, fd_plugin_list can exist but jcr->plugin_ctx_list can be NULL if no
 * plugins were loaded.
 */
void NewPlugins(JobControlRecord* jcr)
{
  Plugin* plugin;

  if (!fd_plugin_list) {
    Dmsg0(debuglevel, "plugin list is NULL\n");
    return;
  }

  if (jcr->IsJobCanceled()) { return; }

  int num;
  num = fd_plugin_list->size();
  if (num == 0) {
    Dmsg0(debuglevel, "No plugins loaded\n");
    return;
  }

  jcr->plugin_ctx_list = new alist<PluginContext*>(10, owned_by_alist);
  Dmsg2(debuglevel, "Instantiate plugin_ctx=%p JobId=%d\n",
        jcr->plugin_ctx_list, jcr->JobId);

  int i{};
  foreach_alist_index (i, plugin, fd_plugin_list) {
    // Start a new instance of each plugin
    instantiate_plugin(jcr, plugin, 0);
  }
}

// Free the plugin instances for this Job
void FreePlugins(JobControlRecord* jcr)
{
  PluginContext* ctx = nullptr;

  if (!fd_plugin_list || !jcr->plugin_ctx_list) { return; }

  Dmsg2(debuglevel, "Free instance fd-plugin_ctx_list=%p JobId=%d\n",
        jcr->plugin_ctx_list, jcr->JobId);
  foreach_alist (ctx, jcr->plugin_ctx_list) {
    // Free the plugin instance
    PlugFunc(ctx->plugin)->freePlugin(ctx);
    free(ctx->core_private_context); /* Free BAREOS private context */
  }

  delete jcr->plugin_ctx_list;
  jcr->plugin_ctx_list = NULL;
}

/**
 * Entry point for opening the file this is a wrapper around the pluginIO
 * entry point in the plugin.
 */
static int MyPluginBopen(BareosWinFilePacket* bfd,
                         const char* fname,
                         int flags,
                         mode_t mode)
{
  Plugin* plugin;
  struct io_pkt io;
  JobControlRecord* jcr = bfd->jcr;

  Dmsg1(debuglevel, "plugin_bopen flags=%08o\n", flags);
  if (!jcr->plugin_ctx) { return 0; }
  plugin = (Plugin*)jcr->plugin_ctx->plugin;

  memset(&io, 0, sizeof(io));
  io.pkt_size = sizeof(io);
  io.pkt_end = sizeof(io);

  io.func = IO_OPEN;
  io.fname = fname;
  io.flags = flags;
  io.mode = mode;

  PlugFunc(plugin)->pluginIO(jcr->plugin_ctx, &io);
  bfd->BErrNo = io.io_errno;

  if (io.win32) {
    errno = b_errno_win32;
  } else {
    errno = io.io_errno;
    bfd->lerror = io.lerror;
  }

  Dmsg1(debuglevel, "Return from plugin open status=%d\n", io.status);

  return io.status;
}

/**
 * Entry point for closing the file this is a wrapper around the pluginIO
 * entry point in the plugin.
 */
static int MyPluginBclose(BareosWinFilePacket* bfd)
{
  Plugin* plugin;
  struct io_pkt io;
  JobControlRecord* jcr = bfd->jcr;

  Dmsg0(debuglevel, "===== plugin_bclose\n");
  if (!jcr->plugin_ctx) { return 0; }
  plugin = (Plugin*)jcr->plugin_ctx->plugin;

  memset(&io, 0, sizeof(io));
  io.pkt_size = sizeof(io);
  io.pkt_end = sizeof(io);

  io.func = IO_CLOSE;

  PlugFunc(plugin)->pluginIO(jcr->plugin_ctx, &io);
  bfd->BErrNo = io.io_errno;

  if (io.win32) {
    errno = b_errno_win32;
  } else {
    errno = io.io_errno;
    bfd->lerror = io.lerror;
  }

  Dmsg1(debuglevel, "plugin_bclose stat=%d\n", io.status);

  return io.status;
}

/**
 * Entry point for reading from the file this is a wrapper around the pluginIO
 * entry point in the plugin.
 */
static ssize_t MyPluginBread(BareosWinFilePacket* bfd, void* buf, size_t count)
{
  Plugin* plugin;
  struct io_pkt io;
  JobControlRecord* jcr = bfd->jcr;

  Dmsg0(debuglevel, "plugin_bread\n");
  if (!jcr->plugin_ctx) { return 0; }
  plugin = (Plugin*)jcr->plugin_ctx->plugin;

  memset(&io, 0, sizeof(io));
  io.pkt_size = sizeof(io);
  io.pkt_end = sizeof(io);

  io.func = IO_READ;
  io.count = count;
  io.buf = (char*)buf;

  PlugFunc(plugin)->pluginIO(jcr->plugin_ctx, &io);
  bfd->offset = io.offset;
  bfd->BErrNo = io.io_errno;

  if (io.win32) {
    errno = b_errno_win32;
  } else {
    errno = io.io_errno;
    bfd->lerror = io.lerror;
  }

  return (ssize_t)io.status;
}

/**
 * Entry point for writing to the file this is a wrapper around the pluginIO
 * entry point in the plugin.
 */
static ssize_t MyPluginBwrite(BareosWinFilePacket* bfd, void* buf, size_t count)
{
  Plugin* plugin;
  struct io_pkt io;
  JobControlRecord* jcr = bfd->jcr;

  Dmsg0(debuglevel, "plugin_bwrite\n");
  if (!jcr->plugin_ctx) {
    Dmsg0(0, "No plugin context\n");
    return 0;
  }
  plugin = (Plugin*)jcr->plugin_ctx->plugin;

  memset(&io, 0, sizeof(io));
  io.pkt_size = sizeof(io);
  io.pkt_end = sizeof(io);

  io.func = IO_WRITE;
  io.count = count;
  io.buf = (char*)buf;

  PlugFunc(plugin)->pluginIO(jcr->plugin_ctx, &io);
  bfd->BErrNo = io.io_errno;

  if (io.win32) {
    errno = b_errno_win32;
  } else {
    errno = io.io_errno;
    bfd->lerror = io.lerror;
  }

  return (ssize_t)io.status;
}

/**
 * Entry point for seeking in the file this is a wrapper around the pluginIO
 * entry point in the plugin.
 */
static boffset_t MyPluginBlseek(BareosWinFilePacket* bfd,
                                boffset_t offset,
                                int whence)
{
  Plugin* plugin;
  struct io_pkt io;
  JobControlRecord* jcr = bfd->jcr;

  Dmsg0(debuglevel, "plugin_bseek\n");
  if (!jcr->plugin_ctx) { return 0; }
  plugin = (Plugin*)jcr->plugin_ctx->plugin;

  io.pkt_size = sizeof(io);
  io.pkt_end = sizeof(io);
  io.func = IO_SEEK;
  io.offset = offset;
  io.whence = whence;
  io.win32 = false;
  io.lerror = 0;
  PlugFunc(plugin)->pluginIO(jcr->plugin_ctx, &io);
  bfd->BErrNo = io.io_errno;
  if (io.win32) {
    errno = b_errno_win32;
  } else {
    errno = io.io_errno;
    bfd->lerror = io.lerror;
  }

  return (boffset_t)io.offset;
}

/* ==============================================================
 *
 * Callbacks from the plugin
 *
 * ==============================================================
 */
static bRC bareosGetValue(PluginContext* ctx, bVariable var, void* value)
{
  JobControlRecord* jcr = NULL;
  if (!value) { return bRC_Error; }

  switch (var) { /* General variables, no need of ctx */
    case bVarFDName:
      *((char**)value) = my_name;
      break;
    case bVarWorkingDir:
      *(void**)value = me->working_directory;
      break;
    case bVarExePath:
      *(char**)value = exepath;
      break;
    case bVarVersion:
      *(const char**)value = kBareosVersionStrings.FullWithDate;
      break;
    case bVarDistName:
      /* removed, as this value was never used by any plugin */
      return bRC_Error;
    default:
      if (!ctx) { /* Other variables need context */
        return bRC_Error;
      }

      jcr = ((b_plugin_ctx*)ctx->core_private_context)->jcr;
      if (!jcr) { return bRC_Error; }
      break;
  }

  if (jcr) {
    switch (var) {
      case bVarJobId:
        *((int*)value) = jcr->JobId;
        Dmsg1(debuglevel, "fd-plugin: return bVarJobId=%d\n", jcr->JobId);
        break;
      case bVarLevel:
        *((int*)value) = jcr->getJobLevel();
        Dmsg1(debuglevel, "fd-plugin: return bVarJobLevel=%d\n",
              jcr->getJobLevel());
        break;
      case bVarType:
        *((int*)value) = jcr->getJobType();
        Dmsg1(debuglevel, "fd-plugin: return bVarJobType=%d\n",
              jcr->getJobType());
        break;
      case bVarClient:
        *((char**)value) = jcr->client_name;
        Dmsg1(debuglevel, "fd-plugin: return bVarClient=%s\n",
              NPRT(*((char**)value)));
        break;
      case bVarJobName:
        *((char**)value) = jcr->Job;
        Dmsg1(debuglevel, "fd-plugin: return bVarJobName=%s\n",
              NPRT(*((char**)value)));
        break;
      case bVarPrevJobName:
        *((char**)value) = jcr->impl->PrevJob;
        Dmsg1(debuglevel, "fd-plugin: return bVarPrevJobName=%s\n",
              NPRT(*((char**)value)));
        break;
      case bVarJobStatus:
        *((int*)value) = jcr->JobStatus;
        Dmsg1(debuglevel, "fd-plugin: return bVarJobStatus=%d\n",
              jcr->JobStatus);
        break;
      case bVarSinceTime:
        *((int*)value) = (int)jcr->impl->since_time;
        Dmsg1(debuglevel, "fd-plugin: return bVarSinceTime=%d\n",
              (int)jcr->impl->since_time);
        break;
      case bVarAccurate:
        *((int*)value) = (int)jcr->accurate;
        Dmsg1(debuglevel, "fd-plugin: return bVarAccurate=%d\n",
              (int)jcr->accurate);
        break;
      case bVarFileSeen:
        break; /* a write only variable, ignore read request */
      case bVarVssClient:
#ifdef HAVE_WIN32
        if (jcr->impl->pVSSClient) {
          *(void**)value = jcr->impl->pVSSClient;
          Dmsg1(debuglevel, "fd-plugin: return bVarVssClient=%p\n",
                *(void**)value);
          break;
        }
#endif
        return bRC_Error;
      case bVarWhere:
        *(char**)value = jcr->where;
        Dmsg1(debuglevel, "fd-plugin: return bVarWhere=%s\n",
              NPRT(*((char**)value)));
        break;
      case bVarRegexWhere:
        *(char**)value = jcr->RegexWhere;
        Dmsg1(debuglevel, "fd-plugin: return bVarRegexWhere=%s\n",
              NPRT(*((char**)value)));
        break;
      case bVarPrefixLinks:
        *(int*)value = (int)jcr->prefix_links;
        Dmsg1(debuglevel, "fd-plugin: return bVarPrefixLinks=%d\n",
              (int)jcr->prefix_links);
        break;
      default:
        break;
    }
  }

  return bRC_OK;
}

static bRC bareosSetValue(PluginContext* ctx, bVariable var, void* value)
{
  JobControlRecord* jcr;

  if (!value || !ctx) { return bRC_Error; }

  jcr = ((b_plugin_ctx*)ctx->core_private_context)->jcr;
  if (!jcr) { return bRC_Error; }

  switch (var) {
    case bVarSinceTime:
      jcr->impl->since_time = (*(int*)value);
      break;
    case bVarLevel:
      jcr->setJobLevel(*(int*)value);
      break;
    case bVarFileSeen:
      if (!AccurateMarkFileAsSeen(jcr, (char*)value)) { return bRC_Error; }
      break;
    default:
      Jmsg1(jcr, M_ERROR, 0,
            "Warning: bareosSetValue not implemented for var %d.\n", var);
      break;
  }

  return bRC_OK;
}

static bRC bareosRegisterEvents(PluginContext* ctx, int nr_events, ...)
{
  int i;
  va_list args;
  uint32_t event;
  b_plugin_ctx* b_ctx;

  if (!ctx) { return bRC_Error; }
  b_ctx = (b_plugin_ctx*)ctx->core_private_context;

  va_start(args, nr_events);
  for (i = 0; i < nr_events; i++) {
    event = va_arg(args, uint32_t);
    Dmsg1(debuglevel, "fd-plugin: Plugin registered event=%u\n", event);
    SetBit(event, b_ctx->events);
  }
  va_end(args);

  return bRC_OK;
}

// Get the number of instaces instantiated of a certain plugin.
static bRC bareosGetInstanceCount(PluginContext* ctx, int* ret)
{
  int cnt;
  JobControlRecord *jcr, *njcr;
  PluginContext* nctx;
  b_plugin_ctx* bctx;
  bRC retval = bRC_Error;

  if (!IsCtxGood(ctx, jcr, bctx)) { goto bail_out; }

  lock_mutex(mutex);

  cnt = 0;
  foreach_jcr (njcr) {
    if (jcr->plugin_ctx_list) {
      foreach_alist (nctx, jcr->plugin_ctx_list) {
        if (nctx->plugin == bctx->plugin) { cnt++; }
      }
    }
  }
  endeach_jcr(njcr);

  unlock_mutex(mutex);

  *ret = cnt;
  retval = bRC_OK;

bail_out:
  return retval;
}

static bRC bareosUnRegisterEvents(PluginContext* ctx, int nr_events, ...)
{
  int i;
  va_list args;
  uint32_t event;
  b_plugin_ctx* b_ctx;

  if (!ctx) { return bRC_Error; }
  b_ctx = (b_plugin_ctx*)ctx->core_private_context;

  va_start(args, nr_events);
  for (i = 0; i < nr_events; i++) {
    event = va_arg(args, uint32_t);
    Dmsg1(debuglevel, "fd-plugin: Plugin unregistered event=%u\n", event);
    ClearBit(event, b_ctx->events);
  }
  va_end(args);

  return bRC_OK;
}

static bRC bareosJobMsg(PluginContext* ctx,
                        const char*,
                        int,
                        int type,
                        utime_t mtime,
                        const char* fmt,
                        ...)
{
  JobControlRecord* jcr;
  va_list arg_ptr;
  PoolMem buffer(PM_MESSAGE);

  if (ctx) {
    jcr = ((b_plugin_ctx*)ctx->core_private_context)->jcr;
  } else {
    jcr = NULL;
  }

  va_start(arg_ptr, fmt);
  buffer.Bvsprintf(fmt, arg_ptr);
  va_end(arg_ptr);
  Jmsg(jcr, type, mtime, "%s", buffer.c_str());

  return bRC_OK;
}

static bRC bareosDebugMsg(PluginContext*,
                          const char* fname,
                          int line,
                          int level,
                          const char* fmt,
                          ...)
{
  va_list arg_ptr;
  PoolMem buffer(PM_MESSAGE);

  va_start(arg_ptr, fmt);
  buffer.Bvsprintf(fmt, arg_ptr);
  va_end(arg_ptr);
  d_msg(fname, line, level, "%s", buffer.c_str());

  return bRC_OK;
}

static void* bareosMalloc(PluginContext*, const char*, int, size_t size)
{
  return malloc(size);
}

static void bareosFree(PluginContext*, const char*, int, void* mem)
{
  free(mem);
}

/**
 * Let the plugin define files/directories to be excluded from the main
 * backup.
 */
static bRC bareosAddExclude(PluginContext* ctx, const char* fname)
{
  JobControlRecord* jcr;
  findIncludeExcludeItem* old;
  b_plugin_ctx* bctx;

  if (!IsCtxGood(ctx, jcr, bctx)) { return bRC_Error; }
  if (!fname) { return bRC_Error; }

  // Save the include context
  old = get_incexe(jcr);

  // Not right time to add exlude
  if (!old) { return bRC_Error; }

  if (!bctx->exclude) { bctx->exclude = new_exclude(jcr->impl->ff->fileset); }

  // Set the Exclude context
  SetIncexe(jcr, bctx->exclude);

  AddFileToFileset(jcr, fname, true, jcr->impl->ff->fileset);

  // Restore the current context
  SetIncexe(jcr, old);

  Dmsg1(100, "Add exclude file=%s\n", fname);

  return bRC_OK;
}

/**
 * Let the plugin define files/directories to be excluded from the main
 * backup.
 */
static bRC bareosAddInclude(PluginContext* ctx, const char* fname)
{
  JobControlRecord* jcr;
  findIncludeExcludeItem* old;
  b_plugin_ctx* bctx;

  if (!IsCtxGood(ctx, jcr, bctx)) { return bRC_Error; }

  if (!fname) { return bRC_Error; }

  // Save the include context
  old = get_incexe(jcr);

  // Not right time to add include
  if (!old) { return bRC_Error; }

  if (!bctx->include) { bctx->include = old; }

  SetIncexe(jcr, bctx->include);
  AddFileToFileset(jcr, fname, true, jcr->impl->ff->fileset);

  // Restore the current context
  SetIncexe(jcr, old);

  Dmsg1(100, "Add include file=%s\n", fname);

  return bRC_OK;
}

static bRC bareosAddOptions(PluginContext* ctx, const char* opts)
{
  JobControlRecord* jcr;
  b_plugin_ctx* bctx;

  if (!IsCtxGood(ctx, jcr, bctx)) { return bRC_Error; }

  if (!opts) { return bRC_Error; }
  AddOptionsToFileset(jcr, opts);
  Dmsg1(1000, "Add options=%s\n", opts);

  return bRC_OK;
}

static bRC bareosAddRegex(PluginContext* ctx, const char* item, int type)
{
  JobControlRecord* jcr;
  b_plugin_ctx* bctx;

  if (!IsCtxGood(ctx, jcr, bctx)) { return bRC_Error; }

  if (!item) { return bRC_Error; }
  AddRegexToFileset(jcr, item, type);
  Dmsg1(100, "Add regex=%s\n", item);

  return bRC_OK;
}

static bRC bareosAddWild(PluginContext* ctx, const char* item, int type)
{
  JobControlRecord* jcr;
  b_plugin_ctx* bctx;

  if (!IsCtxGood(ctx, jcr, bctx)) { return bRC_Error; }

  if (!item) { return bRC_Error; }
  AddWildToFileset(jcr, item, type);
  Dmsg1(100, "Add wild=%s\n", item);

  return bRC_OK;
}

static bRC bareosNewOptions(PluginContext* ctx)
{
  JobControlRecord* jcr;
  b_plugin_ctx* bctx;

  if (!IsCtxGood(ctx, jcr, bctx)) { return bRC_Error; }
  (void)NewOptions(jcr->impl->ff, jcr->impl->ff->fileset->incexe);

  return bRC_OK;
}

static bRC bareosNewInclude(PluginContext* ctx)
{
  JobControlRecord* jcr;
  b_plugin_ctx* bctx;

  if (!IsCtxGood(ctx, jcr, bctx)) { return bRC_Error; }
  (void)new_include(jcr->impl->ff->fileset);

  return bRC_OK;
}

static bRC bareosNewPreInclude(PluginContext* ctx)
{
  JobControlRecord* jcr;
  b_plugin_ctx* bctx;

  if (!IsCtxGood(ctx, jcr, bctx)) { return bRC_Error; }

  bctx->include = new_preinclude(jcr->impl->ff->fileset);
  NewOptions(jcr->impl->ff, bctx->include);
  SetIncexe(jcr, bctx->include);

  return bRC_OK;
}

// Check if a file have to be backed up using Accurate code
static bRC bareosCheckChanges(PluginContext* ctx, struct save_pkt* sp)
{
  JobControlRecord* jcr;
  b_plugin_ctx* bctx;
  FindFilesPacket* ff_pkt;
  bRC retval = bRC_Error;

  if (!IsCtxGood(ctx, jcr, bctx)) { goto bail_out; }

  if (!sp) { goto bail_out; }

  ff_pkt = jcr->impl->ff;
  /*
   * Copy fname and link because SaveFile() zaps them.
   * This avoids zapping the plugin's strings.
   */
  ff_pkt->type = sp->type;
  if (!sp->fname) {
    Jmsg0(jcr, M_FATAL, 0,
          _("Command plugin: no fname in bareosCheckChanges packet.\n"));
    goto bail_out;
  }

  ff_pkt->fname = sp->fname;
  ff_pkt->link = sp->link;
  if (sp->save_time) {
    ff_pkt->save_time = sp->save_time;
    ff_pkt->incremental = true;
  }
  memcpy(&ff_pkt->statp, &sp->statp, sizeof(ff_pkt->statp));

  if (CheckChanges(jcr, ff_pkt)) {
    retval = bRC_OK;
  } else {
    retval = bRC_Seen;
  }

  // CheckChanges() can update delta sequence number, return it to the plugin
  sp->delta_seq = ff_pkt->delta_seq;
  sp->accurate_found = ff_pkt->accurate_found;

bail_out:
  Dmsg1(100, "checkChanges=%i\n", retval);
  return retval;
}

// Check if a file would be saved using current Include/Exclude code
static bRC bareosAcceptFile(PluginContext* ctx, struct save_pkt* sp)
{
  JobControlRecord* jcr;
  FindFilesPacket* ff_pkt;
  b_plugin_ctx* bctx;
  bRC retval = bRC_Error;

  if (!IsCtxGood(ctx, jcr, bctx)) { goto bail_out; }
  if (!sp) { goto bail_out; }

  ff_pkt = jcr->impl->ff;

  ff_pkt->fname = sp->fname;
  memcpy(&ff_pkt->statp, &sp->statp, sizeof(ff_pkt->statp));

  if (AcceptFile(ff_pkt)) {
    retval = bRC_OK;
  } else {
    retval = bRC_Skip;
  }

bail_out:
  return retval;
}

// Manipulate the accurate seen bitmap for setting bits
static bRC bareosSetSeenBitmap(PluginContext* ctx, bool all, char* fname)
{
  JobControlRecord* jcr;
  b_plugin_ctx* bctx;
  bRC retval = bRC_Error;

  if (!IsCtxGood(ctx, jcr, bctx)) { goto bail_out; }

  if (all && fname) {
    Dmsg0(debuglevel,
          "fd-plugin: API error in call to SetSeenBitmap, both all and fname "
          "set!!!\n");
    goto bail_out;
  }

  if (all) {
    if (AccurateMarkAllFilesAsSeen(jcr)) { retval = bRC_OK; }
  } else if (fname) {
    if (AccurateMarkFileAsSeen(jcr, fname)) { retval = bRC_OK; }
  }

bail_out:
  return retval;
}

// Manipulate the accurate seen bitmap for clearing bits
static bRC bareosClearSeenBitmap(PluginContext* ctx, bool all, char* fname)
{
  JobControlRecord* jcr;
  b_plugin_ctx* bctx;
  bRC retval = bRC_Error;

  if (!IsCtxGood(ctx, jcr, bctx)) { goto bail_out; }

  if (all && fname) {
    Dmsg0(debuglevel,
          "fd-plugin: API error in call to ClearSeenBitmap, both all and fname "
          "set!!!\n");
    goto bail_out;
  }

  if (all) {
    if (accurate_unMarkAllFilesAsSeen(jcr)) { retval = bRC_OK; }
  } else if (fname) {
    if (accurate_unMarkFileAsSeen(jcr, fname)) { retval = bRC_OK; }
  }

bail_out:
  return retval;
}
} /* namespace filedaemon */