summaryrefslogtreecommitdiffstats
path: root/src/libsystemd/sd-journal/sd-journal.c
blob: 852c37338a222ed9fc430ae6339a7bd0f92540ca (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
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
/* SPDX-License-Identifier: LGPL-2.1-or-later */

#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <linux/magic.h>
#include <poll.h>
#include <stddef.h>
#include <sys/inotify.h>
#include <sys/vfs.h>
#include <unistd.h>

#include "sd-journal.h"

#include "alloc-util.h"
#include "catalog.h"
#include "compress.h"
#include "dirent-util.h"
#include "env-file.h"
#include "escape.h"
#include "fd-util.h"
#include "fileio.h"
#include "format-util.h"
#include "fs-util.h"
#include "hashmap.h"
#include "hostname-util.h"
#include "id128-util.h"
#include "inotify-util.h"
#include "io-util.h"
#include "journal-def.h"
#include "journal-file.h"
#include "journal-internal.h"
#include "list.h"
#include "lookup3.h"
#include "nulstr-util.h"
#include "path-util.h"
#include "process-util.h"
#include "replace-var.h"
#include "stat-util.h"
#include "stdio-util.h"
#include "string-util.h"
#include "strv.h"
#include "syslog-util.h"

#define JOURNAL_FILES_RECHECK_USEC (2 * USEC_PER_SEC)

/* The maximum size of variable values we'll expand in catalog entries. We bind this to PATH_MAX for now, as
 * we want to be able to show all officially valid paths at least */
#define REPLACE_VAR_MAX PATH_MAX

#define DEFAULT_DATA_THRESHOLD (64*1024)

static void remove_file_real(sd_journal *j, JournalFile *f);

static bool journal_pid_changed(sd_journal *j) {
        assert(j);

        /* We don't support people creating a journal object and
         * keeping it around over a fork(). Let's complain. */

        return j->original_pid != getpid_cached();
}

static int journal_put_error(sd_journal *j, int r, const char *path) {
        _cleanup_free_ char *copy = NULL;
        int k;

        /* Memorize an error we encountered, and store which
         * file/directory it was generated from. Note that we store
         * only *one* path per error code, as the error code is the
         * key into the hashmap, and the path is the value. This means
         * we keep track only of all error kinds, but not of all error
         * locations. This has the benefit that the hashmap cannot
         * grow beyond bounds.
         *
         * We return an error here only if we didn't manage to
         * memorize the real error. */

        if (r >= 0)
                return r;

        if (path) {
                copy = strdup(path);
                if (!copy)
                        return -ENOMEM;
        }

        k = hashmap_ensure_put(&j->errors, NULL, INT_TO_PTR(r), copy);
        if (k < 0) {
                if (k == -EEXIST)
                        return 0;

                return k;
        }

        TAKE_PTR(copy);
        return 0;
}

static void detach_location(sd_journal *j) {
        JournalFile *f;

        assert(j);

        j->current_file = NULL;
        j->current_field = 0;

        ORDERED_HASHMAP_FOREACH(f, j->files)
                journal_file_reset_location(f);
}

static void init_location(Location *l, LocationType type, JournalFile *f, Object *o) {
        assert(l);
        assert(IN_SET(type, LOCATION_DISCRETE, LOCATION_SEEK));
        assert(f);

        *l = (Location) {
                .type = type,
                .seqnum = le64toh(o->entry.seqnum),
                .seqnum_id = f->header->seqnum_id,
                .realtime = le64toh(o->entry.realtime),
                .monotonic = le64toh(o->entry.monotonic),
                .boot_id = o->entry.boot_id,
                .xor_hash = le64toh(o->entry.xor_hash),
                .seqnum_set = true,
                .realtime_set = true,
                .monotonic_set = true,
                .xor_hash_set = true,
        };
}

static void set_location(sd_journal *j, JournalFile *f, Object *o) {
        assert(j);
        assert(f);
        assert(o);

        init_location(&j->current_location, LOCATION_DISCRETE, f, o);

        j->current_file = f;
        j->current_field = 0;

        /* Let f know its candidate entry was picked. */
        assert(f->location_type == LOCATION_SEEK);
        f->location_type = LOCATION_DISCRETE;
}

static int match_is_valid(const void *data, size_t size) {
        const char *b = ASSERT_PTR(data);

        if (size < 2)
                return false;

        if (((char*) data)[0] == '_' && ((char*) data)[1] == '_')
                return false;

        for (const char *p = b; p < b + size; p++) {

                if (*p == '=')
                        return p > b;

                if (*p == '_')
                        continue;

                if (*p >= 'A' && *p <= 'Z')
                        continue;

                if (ascii_isdigit(*p))
                        continue;

                return false;
        }

        return false;
}

static bool same_field(const void *_a, size_t s, const void *_b, size_t t) {
        const uint8_t *a = _a, *b = _b;

        for (size_t j = 0; j < s && j < t; j++) {

                if (a[j] != b[j])
                        return false;

                if (a[j] == '=')
                        return true;
        }

        assert_not_reached();
}

static Match *match_new(Match *p, MatchType t) {
        Match *m;

        m = new(Match, 1);
        if (!m)
                return NULL;

        *m = (Match) {
                .type = t,
                .parent = p,
        };

        if (p)
                LIST_PREPEND(matches, p->matches, m);

        return m;
}

static Match *match_free(Match *m) {
        assert(m);

        while (m->matches)
                match_free(m->matches);

        if (m->parent)
                LIST_REMOVE(matches, m->parent->matches, m);

        free(m->data);
        return mfree(m);
}

static Match *match_free_if_empty(Match *m) {
        if (!m || m->matches)
                return m;

        return match_free(m);
}

_public_ int sd_journal_add_match(sd_journal *j, const void *data, size_t size) {
        Match *add_here = NULL, *m = NULL;
        uint64_t hash;

        assert_return(j, -EINVAL);
        assert_return(!journal_pid_changed(j), -ECHILD);
        assert_return(data, -EINVAL);

        if (size == 0)
                size = strlen(data);

        if (!match_is_valid(data, size))
                return -EINVAL;

        /* level 0: AND term
         * level 1: OR terms
         * level 2: AND terms
         * level 3: OR terms
         * level 4: concrete matches */

        if (!j->level0) {
                j->level0 = match_new(NULL, MATCH_AND_TERM);
                if (!j->level0)
                        return -ENOMEM;
        }

        if (!j->level1) {
                j->level1 = match_new(j->level0, MATCH_OR_TERM);
                if (!j->level1)
                        return -ENOMEM;
        }

        if (!j->level2) {
                j->level2 = match_new(j->level1, MATCH_AND_TERM);
                if (!j->level2)
                        return -ENOMEM;
        }

        assert(j->level0->type == MATCH_AND_TERM);
        assert(j->level1->type == MATCH_OR_TERM);
        assert(j->level2->type == MATCH_AND_TERM);

        /* Old-style Jenkins (unkeyed) hashing only here. We do not cover new-style siphash (keyed) hashing
         * here, since it's different for each file, and thus can't be pre-calculated in the Match object. */
        hash = jenkins_hash64(data, size);

        LIST_FOREACH(matches, l3, j->level2->matches) {
                assert(l3->type == MATCH_OR_TERM);

                LIST_FOREACH(matches, l4, l3->matches) {
                        assert(l4->type == MATCH_DISCRETE);

                        /* Exactly the same match already? Then ignore
                         * this addition */
                        if (l4->hash == hash &&
                            l4->size == size &&
                            memcmp(l4->data, data, size) == 0)
                                return 0;

                        /* Same field? Then let's add this to this OR term */
                        if (same_field(data, size, l4->data, l4->size)) {
                                add_here = l3;
                                break;
                        }
                }

                if (add_here)
                        break;
        }

        if (!add_here) {
                add_here = match_new(j->level2, MATCH_OR_TERM);
                if (!add_here)
                        goto fail;
        }

        m = match_new(add_here, MATCH_DISCRETE);
        if (!m)
                goto fail;

        m->hash = hash;
        m->size = size;
        m->data = memdup(data, size);
        if (!m->data)
                goto fail;

        detach_location(j);

        return 0;

fail:
        match_free(m);
        match_free_if_empty(add_here);
        j->level2 = match_free_if_empty(j->level2);
        j->level1 = match_free_if_empty(j->level1);
        j->level0 = match_free_if_empty(j->level0);

        return -ENOMEM;
}

_public_ int sd_journal_add_conjunction(sd_journal *j) {
        assert_return(j, -EINVAL);
        assert_return(!journal_pid_changed(j), -ECHILD);

        if (!j->level0)
                return 0;

        if (!j->level1)
                return 0;

        if (!j->level1->matches)
                return 0;

        j->level1 = NULL;
        j->level2 = NULL;

        return 0;
}

_public_ int sd_journal_add_disjunction(sd_journal *j) {
        assert_return(j, -EINVAL);
        assert_return(!journal_pid_changed(j), -ECHILD);

        if (!j->level0)
                return 0;

        if (!j->level1)
                return 0;

        if (!j->level2)
                return 0;

        if (!j->level2->matches)
                return 0;

        j->level2 = NULL;
        return 0;
}

static char *match_make_string(Match *m) {
        char *p = NULL, *r;
        bool enclose = false;

        if (!m)
                return strdup("none");

        if (m->type == MATCH_DISCRETE)
                return cescape_length(m->data, m->size);

        LIST_FOREACH(matches, i, m->matches) {
                char *t, *k;

                t = match_make_string(i);
                if (!t)
                        return mfree(p);

                if (p) {
                        k = strjoin(p, m->type == MATCH_OR_TERM ? " OR " : " AND ", t);
                        free(p);
                        free(t);

                        if (!k)
                                return NULL;

                        p = k;

                        enclose = true;
                } else
                        p = t;
        }

        if (enclose) {
                r = strjoin("(", p, ")");
                free(p);
                return r;
        }

        return p;
}

char *journal_make_match_string(sd_journal *j) {
        assert(j);

        return match_make_string(j->level0);
}

_public_ void sd_journal_flush_matches(sd_journal *j) {
        if (!j)
                return;

        if (j->level0)
                match_free(j->level0);

        j->level0 = j->level1 = j->level2 = NULL;

        detach_location(j);
}

_pure_ static int compare_with_location(const JournalFile *f, const Location *l, const JournalFile *current_file) {
        int r;

        assert(f);
        assert(l);
        assert(f->location_type == LOCATION_SEEK);
        assert(IN_SET(l->type, LOCATION_DISCRETE, LOCATION_SEEK));

        if (l->monotonic_set &&
            sd_id128_equal(f->current_boot_id, l->boot_id) &&
            l->realtime_set &&
            f->current_realtime == l->realtime &&
            l->xor_hash_set &&
            f->current_xor_hash == l->xor_hash &&
            l->seqnum_set &&
            sd_id128_equal(f->header->seqnum_id, l->seqnum_id) &&
            f->current_seqnum == l->seqnum &&
            f != current_file)
                return 0;

        if (l->seqnum_set &&
            sd_id128_equal(f->header->seqnum_id, l->seqnum_id)) {

                r = CMP(f->current_seqnum, l->seqnum);
                if (r != 0)
                        return r;
        }

        if (l->monotonic_set &&
            sd_id128_equal(f->current_boot_id, l->boot_id)) {

                r = CMP(f->current_monotonic, l->monotonic);
                if (r != 0)
                        return r;
        }

        if (l->realtime_set) {

                r = CMP(f->current_realtime, l->realtime);
                if (r != 0)
                        return r;
        }

        if (l->xor_hash_set) {

                r = CMP(f->current_xor_hash, l->xor_hash);
                if (r != 0)
                        return r;
        }

        return 0;
}

static int next_for_match(
                sd_journal *j,
                Match *m,
                JournalFile *f,
                uint64_t after_offset,
                direction_t direction,
                Object **ret,
                uint64_t *offset) {

        int r;
        uint64_t np = 0;

        assert(j);
        assert(m);
        assert(f);

        if (m->type == MATCH_DISCRETE) {
                Object *d;
                uint64_t hash;

                /* If the keyed hash logic is used, we need to calculate the hash fresh per file. Otherwise
                 * we can use what we pre-calculated. */
                if (JOURNAL_HEADER_KEYED_HASH(f->header))
                        hash = journal_file_hash_data(f, m->data, m->size);
                else
                        hash = m->hash;

                r = journal_file_find_data_object_with_hash(f, m->data, m->size, hash, &d, NULL);
                if (r <= 0)
                        return r;

                return journal_file_move_to_entry_by_offset_for_data(f, d, after_offset, direction, ret, offset);

        } else if (m->type == MATCH_OR_TERM) {

                /* Find the earliest match beyond after_offset */

                LIST_FOREACH(matches, i, m->matches) {
                        uint64_t cp;

                        r = next_for_match(j, i, f, after_offset, direction, NULL, &cp);
                        if (r < 0)
                                return r;
                        else if (r > 0) {
                                if (np == 0 || (direction == DIRECTION_DOWN ? cp < np : cp > np))
                                        np = cp;
                        }
                }

                if (np == 0)
                        return 0;

        } else if (m->type == MATCH_AND_TERM) {
                Match *last_moved;

                /* Always jump to the next matching entry and repeat
                 * this until we find an offset that matches for all
                 * matches. */

                if (!m->matches)
                        return 0;

                r = next_for_match(j, m->matches, f, after_offset, direction, NULL, &np);
                if (r <= 0)
                        return r;

                assert(direction == DIRECTION_DOWN ? np >= after_offset : np <= after_offset);
                last_moved = m->matches;

                LIST_LOOP_BUT_ONE(matches, i, m->matches, last_moved) {
                        uint64_t cp;

                        r = next_for_match(j, i, f, np, direction, NULL, &cp);
                        if (r <= 0)
                                return r;

                        assert(direction == DIRECTION_DOWN ? cp >= np : cp <= np);
                        if (direction == DIRECTION_DOWN ? cp > np : cp < np) {
                                np = cp;
                                last_moved = i;
                        }
                }
        }

        assert(np > 0);

        if (ret) {
                r = journal_file_move_to_object(f, OBJECT_ENTRY, np, ret);
                if (r < 0)
                        return r;
        }

        if (offset)
                *offset = np;

        return 1;
}

static int find_location_for_match(
                sd_journal *j,
                Match *m,
                JournalFile *f,
                direction_t direction,
                Object **ret,
                uint64_t *offset) {

        int r;

        assert(j);
        assert(m);
        assert(f);

        if (m->type == MATCH_DISCRETE) {
                Object *d;
                uint64_t dp, hash;

                if (JOURNAL_HEADER_KEYED_HASH(f->header))
                        hash = journal_file_hash_data(f, m->data, m->size);
                else
                        hash = m->hash;

                r = journal_file_find_data_object_with_hash(f, m->data, m->size, hash, &d, &dp);
                if (r <= 0)
                        return r;

                /* FIXME: missing: find by monotonic */

                if (j->current_location.type == LOCATION_HEAD)
                        return journal_file_next_entry_for_data(f, d, DIRECTION_DOWN, ret, offset);
                if (j->current_location.type == LOCATION_TAIL)
                        return journal_file_next_entry_for_data(f, d, DIRECTION_UP, ret, offset);
                if (j->current_location.seqnum_set && sd_id128_equal(j->current_location.seqnum_id, f->header->seqnum_id))
                        return journal_file_move_to_entry_by_seqnum_for_data(f, d, j->current_location.seqnum, direction, ret, offset);
                if (j->current_location.monotonic_set) {
                        r = journal_file_move_to_entry_by_monotonic_for_data(f, d, j->current_location.boot_id, j->current_location.monotonic, direction, ret, offset);
                        if (r != 0)
                                return r;

                        /* The data object might have been invalidated. */
                        r = journal_file_move_to_object(f, OBJECT_DATA, dp, &d);
                        if (r < 0)
                                return r;
                }
                if (j->current_location.realtime_set)
                        return journal_file_move_to_entry_by_realtime_for_data(f, d, j->current_location.realtime, direction, ret, offset);

                return journal_file_next_entry_for_data(f, d, direction, ret, offset);

        } else if (m->type == MATCH_OR_TERM) {
                uint64_t np = 0;

                /* Find the earliest match */

                LIST_FOREACH(matches, i, m->matches) {
                        uint64_t cp;

                        r = find_location_for_match(j, i, f, direction, NULL, &cp);
                        if (r < 0)
                                return r;
                        else if (r > 0) {
                                if (np == 0 || (direction == DIRECTION_DOWN ? np > cp : np < cp))
                                        np = cp;
                        }
                }

                if (np == 0)
                        return 0;

                if (ret) {
                        r = journal_file_move_to_object(f, OBJECT_ENTRY, np, ret);
                        if (r < 0)
                                return r;
                }

                if (offset)
                        *offset = np;

                return 1;

        } else {
                uint64_t np = 0;

                assert(m->type == MATCH_AND_TERM);

                /* First jump to the last match, and then find the
                 * next one where all matches match */

                if (!m->matches)
                        return 0;

                LIST_FOREACH(matches, i, m->matches) {
                        uint64_t cp;

                        r = find_location_for_match(j, i, f, direction, NULL, &cp);
                        if (r <= 0)
                                return r;

                        if (np == 0 || (direction == DIRECTION_DOWN ? cp > np : cp < np))
                                np = cp;
                }

                return next_for_match(j, m, f, np, direction, ret, offset);
        }
}

static int find_location_with_matches(
                sd_journal *j,
                JournalFile *f,
                direction_t direction,
                Object **ret,
                uint64_t *offset) {

        int r;

        assert(j);
        assert(f);
        assert(ret);
        assert(offset);

        if (!j->level0) {
                /* No matches is simple */

                if (j->current_location.type == LOCATION_HEAD)
                        return journal_file_next_entry(f, 0, DIRECTION_DOWN, ret, offset);
                if (j->current_location.type == LOCATION_TAIL)
                        return journal_file_next_entry(f, 0, DIRECTION_UP, ret, offset);
                if (j->current_location.seqnum_set && sd_id128_equal(j->current_location.seqnum_id, f->header->seqnum_id))
                        return journal_file_move_to_entry_by_seqnum(f, j->current_location.seqnum, direction, ret, offset);
                if (j->current_location.monotonic_set) {
                        r = journal_file_move_to_entry_by_monotonic(f, j->current_location.boot_id, j->current_location.monotonic, direction, ret, offset);
                        if (r != 0)
                                return r;
                }
                if (j->current_location.realtime_set)
                        return journal_file_move_to_entry_by_realtime(f, j->current_location.realtime, direction, ret, offset);

                return journal_file_next_entry(f, 0, direction, ret, offset);
        } else
                return find_location_for_match(j, j->level0, f, direction, ret, offset);
}

static int next_with_matches(
                sd_journal *j,
                JournalFile *f,
                direction_t direction,
                Object **ret,
                uint64_t *offset) {

        assert(j);
        assert(f);
        assert(ret);
        assert(offset);

        /* No matches is easy. We simple advance the file
         * pointer by one. */
        if (!j->level0)
                return journal_file_next_entry(f, f->current_offset, direction, ret, offset);

        /* If we have a match then we look for the next matching entry
         * with an offset at least one step larger */
        return next_for_match(j, j->level0, f,
                              direction == DIRECTION_DOWN ? f->current_offset + 1
                                                          : f->current_offset - 1,
                              direction, ret, offset);
}

static int next_beyond_location(sd_journal *j, JournalFile *f, direction_t direction) {
        Object *c;
        uint64_t cp, n_entries;
        int r;

        assert(j);
        assert(f);

        n_entries = le64toh(f->header->n_entries);

        /* If we hit EOF before, we don't need to look into this file again
         * unless direction changed or new entries appeared. */
        if (f->last_direction == direction && f->location_type == LOCATION_TAIL &&
            n_entries == f->last_n_entries)
                return 0;

        f->last_n_entries = n_entries;

        if (f->last_direction == direction && f->current_offset > 0) {
                /* LOCATION_SEEK here means we did the work in a previous
                 * iteration and the current location already points to a
                 * candidate entry. */
                if (f->location_type != LOCATION_SEEK) {
                        r = next_with_matches(j, f, direction, &c, &cp);
                        if (r <= 0)
                                return r;

                        journal_file_save_location(f, c, cp);
                }
        } else {
                f->last_direction = direction;

                r = find_location_with_matches(j, f, direction, &c, &cp);
                if (r <= 0)
                        return r;

                journal_file_save_location(f, c, cp);
        }

        /* OK, we found the spot, now let's advance until an entry
         * that is actually different from what we were previously
         * looking at. This is necessary to handle entries which exist
         * in two (or more) journal files, and which shall all be
         * suppressed but one. */

        for (;;) {
                bool found;

                if (j->current_location.type == LOCATION_DISCRETE) {
                        int k;

                        k = compare_with_location(f, &j->current_location, j->current_file);

                        found = direction == DIRECTION_DOWN ? k > 0 : k < 0;
                } else
                        found = true;

                if (found)
                        return 1;

                r = next_with_matches(j, f, direction, &c, &cp);
                if (r <= 0)
                        return r;

                journal_file_save_location(f, c, cp);
        }
}

static int real_journal_next(sd_journal *j, direction_t direction) {
        JournalFile *new_file = NULL;
        unsigned n_files;
        const void **files;
        Object *o;
        int r;

        assert_return(j, -EINVAL);
        assert_return(!journal_pid_changed(j), -ECHILD);

        r = iterated_cache_get(j->files_cache, NULL, &files, &n_files);
        if (r < 0)
                return r;

        for (unsigned i = 0; i < n_files; i++) {
                JournalFile *f = (JournalFile *)files[i];
                bool found;

                r = next_beyond_location(j, f, direction);
                if (r < 0) {
                        log_debug_errno(r, "Can't iterate through %s, ignoring: %m", f->path);
                        remove_file_real(j, f);
                        continue;
                } else if (r == 0) {
                        f->location_type = LOCATION_TAIL;
                        continue;
                }

                if (!new_file)
                        found = true;
                else {
                        int k;

                        k = journal_file_compare_locations(f, new_file);

                        found = direction == DIRECTION_DOWN ? k < 0 : k > 0;
                }

                if (found)
                        new_file = f;
        }

        if (!new_file)
                return 0;

        r = journal_file_move_to_object(new_file, OBJECT_ENTRY, new_file->current_offset, &o);
        if (r < 0)
                return r;

        set_location(j, new_file, o);

        return 1;
}

_public_ int sd_journal_next(sd_journal *j) {
        return real_journal_next(j, DIRECTION_DOWN);
}

_public_ int sd_journal_previous(sd_journal *j) {
        return real_journal_next(j, DIRECTION_UP);
}

static int real_journal_next_skip(sd_journal *j, direction_t direction, uint64_t skip) {
        int c = 0, r;

        assert_return(j, -EINVAL);
        assert_return(!journal_pid_changed(j), -ECHILD);
        assert_return(skip <= INT_MAX, -ERANGE);

        if (skip == 0) {
                /* If this is not a discrete skip, then at least
                 * resolve the current location */
                if (j->current_location.type != LOCATION_DISCRETE) {
                        r = real_journal_next(j, direction);
                        if (r < 0)
                                return r;
                }

                return 0;
        }

        do {
                r = real_journal_next(j, direction);
                if (r < 0)
                        return r;

                if (r == 0)
                        return c;

                skip--;
                c++;
        } while (skip > 0);

        return c;
}

_public_ int sd_journal_next_skip(sd_journal *j, uint64_t skip) {
        return real_journal_next_skip(j, DIRECTION_DOWN, skip);
}

_public_ int sd_journal_previous_skip(sd_journal *j, uint64_t skip) {
        return real_journal_next_skip(j, DIRECTION_UP, skip);
}

_public_ int sd_journal_get_cursor(sd_journal *j, char **cursor) {
        Object *o;
        int r;

        assert_return(j, -EINVAL);
        assert_return(!journal_pid_changed(j), -ECHILD);
        assert_return(cursor, -EINVAL);

        if (!j->current_file || j->current_file->current_offset <= 0)
                return -EADDRNOTAVAIL;

        r = journal_file_move_to_object(j->current_file, OBJECT_ENTRY, j->current_file->current_offset, &o);
        if (r < 0)
                return r;

        if (asprintf(cursor,
                     "s=%s;i=%"PRIx64";b=%s;m=%"PRIx64";t=%"PRIx64";x=%"PRIx64,
                     SD_ID128_TO_STRING(j->current_file->header->seqnum_id), le64toh(o->entry.seqnum),
                     SD_ID128_TO_STRING(o->entry.boot_id), le64toh(o->entry.monotonic),
                     le64toh(o->entry.realtime),
                     le64toh(o->entry.xor_hash)) < 0)
                return -ENOMEM;

        return 0;
}

_public_ int sd_journal_seek_cursor(sd_journal *j, const char *cursor) {
        unsigned long long seqnum, monotonic, realtime, xor_hash;
        bool seqnum_id_set = false,
             seqnum_set = false,
             boot_id_set = false,
             monotonic_set = false,
             realtime_set = false,
             xor_hash_set = false;
        sd_id128_t seqnum_id, boot_id;
        int r;

        assert_return(j, -EINVAL);
        assert_return(!journal_pid_changed(j), -ECHILD);
        assert_return(!isempty(cursor), -EINVAL);

        for (const char *p = cursor;;) {
                _cleanup_free_ char *word = NULL;

                r = extract_first_word(&p, &word, ";", EXTRACT_DONT_COALESCE_SEPARATORS);
                if (r < 0)
                        return r;
                if (r == 0)
                        break;

                if (word[0] == '\0' || word[1] != '=')
                        return -EINVAL;

                switch (word[0]) {
                case 's':
                        seqnum_id_set = true;
                        r = sd_id128_from_string(word + 2, &seqnum_id);
                        if (r < 0)
                                return r;
                        break;

                case 'i':
                        seqnum_set = true;
                        if (sscanf(word + 2, "%llx", &seqnum) != 1)
                                return -EINVAL;
                        break;

                case 'b':
                        boot_id_set = true;
                        r = sd_id128_from_string(word + 2, &boot_id);
                        if (r < 0)
                                return r;
                        break;

                case 'm':
                        monotonic_set = true;
                        if (sscanf(word + 2, "%llx", &monotonic) != 1)
                                return -EINVAL;
                        break;

                case 't':
                        realtime_set = true;
                        if (sscanf(word + 2, "%llx", &realtime) != 1)
                                return -EINVAL;
                        break;

                case 'x':
                        xor_hash_set = true;
                        if (sscanf(word + 2, "%llx", &xor_hash) != 1)
                                return -EINVAL;
                        break;
                }
        }

        if ((!seqnum_set || !seqnum_id_set) &&
            (!monotonic_set || !boot_id_set) &&
            !realtime_set)
                return -EINVAL;

        detach_location(j);
        j->current_location = (Location) {
                .type = LOCATION_SEEK,
        };

        if (realtime_set) {
                j->current_location.realtime = (uint64_t) realtime;
                j->current_location.realtime_set = true;
        }

        if (seqnum_set && seqnum_id_set) {
                j->current_location.seqnum = (uint64_t) seqnum;
                j->current_location.seqnum_id = seqnum_id;
                j->current_location.seqnum_set = true;
        }

        if (monotonic_set && boot_id_set) {
                j->current_location.monotonic = (uint64_t) monotonic;
                j->current_location.boot_id = boot_id;
                j->current_location.monotonic_set = true;
        }

        if (xor_hash_set) {
                j->current_location.xor_hash = (uint64_t) xor_hash;
                j->current_location.xor_hash_set = true;
        }

        return 0;
}

_public_ int sd_journal_test_cursor(sd_journal *j, const char *cursor) {
        int r;
        Object *o;

        assert_return(j, -EINVAL);
        assert_return(!journal_pid_changed(j), -ECHILD);
        assert_return(!isempty(cursor), -EINVAL);

        if (!j->current_file || j->current_file->current_offset <= 0)
                return -EADDRNOTAVAIL;

        r = journal_file_move_to_object(j->current_file, OBJECT_ENTRY, j->current_file->current_offset, &o);
        if (r < 0)
                return r;

        for (;;) {
                _cleanup_free_ char *item = NULL;
                unsigned long long ll;
                sd_id128_t id;
                int k = 0;

                r = extract_first_word(&cursor, &item, ";", EXTRACT_DONT_COALESCE_SEPARATORS);
                if (r < 0)
                        return r;

                if (r == 0)
                        break;

                if (strlen(item) < 2 || item[1] != '=')
                        return -EINVAL;

                switch (item[0]) {

                case 's':
                        k = sd_id128_from_string(item+2, &id);
                        if (k < 0)
                                return k;
                        if (!sd_id128_equal(id, j->current_file->header->seqnum_id))
                                return 0;
                        break;

                case 'i':
                        if (sscanf(item+2, "%llx", &ll) != 1)
                                return -EINVAL;
                        if (ll != le64toh(o->entry.seqnum))
                                return 0;
                        break;

                case 'b':
                        k = sd_id128_from_string(item+2, &id);
                        if (k < 0)
                                return k;
                        if (!sd_id128_equal(id, o->entry.boot_id))
                                return 0;
                        break;

                case 'm':
                        if (sscanf(item+2, "%llx", &ll) != 1)
                                return -EINVAL;
                        if (ll != le64toh(o->entry.monotonic))
                                return 0;
                        break;

                case 't':
                        if (sscanf(item+2, "%llx", &ll) != 1)
                                return -EINVAL;
                        if (ll != le64toh(o->entry.realtime))
                                return 0;
                        break;

                case 'x':
                        if (sscanf(item+2, "%llx", &ll) != 1)
                                return -EINVAL;
                        if (ll != le64toh(o->entry.xor_hash))
                                return 0;
                        break;
                }
        }

        return 1;
}

_public_ int sd_journal_seek_monotonic_usec(sd_journal *j, sd_id128_t boot_id, uint64_t usec) {
        assert_return(j, -EINVAL);
        assert_return(!journal_pid_changed(j), -ECHILD);

        detach_location(j);

        j->current_location = (Location) {
                .type = LOCATION_SEEK,
                .boot_id = boot_id,
                .monotonic = usec,
                .monotonic_set = true,
        };

        return 0;
}

_public_ int sd_journal_seek_realtime_usec(sd_journal *j, uint64_t usec) {
        assert_return(j, -EINVAL);
        assert_return(!journal_pid_changed(j), -ECHILD);

        detach_location(j);

        j->current_location = (Location) {
                .type = LOCATION_SEEK,
                .realtime = usec,
                .realtime_set = true,
        };

        return 0;
}

_public_ int sd_journal_seek_head(sd_journal *j) {
        assert_return(j, -EINVAL);
        assert_return(!journal_pid_changed(j), -ECHILD);

        detach_location(j);

        j->current_location = (Location) {
                .type = LOCATION_HEAD,
        };

        return 0;
}

_public_ int sd_journal_seek_tail(sd_journal *j) {
        assert_return(j, -EINVAL);
        assert_return(!journal_pid_changed(j), -ECHILD);

        detach_location(j);

        j->current_location = (Location) {
                .type = LOCATION_TAIL,
        };

        return 0;
}

static void check_network(sd_journal *j, int fd) {
        assert(j);

        if (j->on_network)
                return;

        j->on_network = fd_is_network_fs(fd);
}

static bool file_has_type_prefix(const char *prefix, const char *filename) {
        const char *full, *tilded, *atted;

        full = strjoina(prefix, ".journal");
        tilded = strjoina(full, "~");
        atted = strjoina(prefix, "@");

        return STR_IN_SET(filename, full, tilded) ||
               startswith(filename, atted);
}

static bool file_type_wanted(int flags, const char *filename) {
        assert(filename);

        if (!endswith(filename, ".journal") && !endswith(filename, ".journal~"))
                return false;

        /* no flags set → every type is OK */
        if (!(flags & (SD_JOURNAL_SYSTEM | SD_JOURNAL_CURRENT_USER)))
                return true;

        if (flags & SD_JOURNAL_SYSTEM && file_has_type_prefix("system", filename))
                return true;

        if (flags & SD_JOURNAL_CURRENT_USER) {
                char prefix[5 + DECIMAL_STR_MAX(uid_t) + 1];

                xsprintf(prefix, "user-"UID_FMT, getuid());

                if (file_has_type_prefix(prefix, filename))
                        return true;
        }

        return false;
}

static bool path_has_prefix(sd_journal *j, const char *path, const char *prefix) {
        assert(j);
        assert(path);
        assert(prefix);

        if (j->toplevel_fd >= 0)
                return false;

        return path_startswith(path, prefix);
}

static void track_file_disposition(sd_journal *j, JournalFile *f) {
        assert(j);
        assert(f);

        if (!j->has_runtime_files && path_has_prefix(j, f->path, "/run"))
                j->has_runtime_files = true;
        else if (!j->has_persistent_files && path_has_prefix(j, f->path, "/var"))
                j->has_persistent_files = true;
}

static const char *skip_slash(const char *p) {

        if (!p)
                return NULL;

        while (*p == '/')
                p++;

        return p;
}

static int add_any_file(
                sd_journal *j,
                int fd,
                const char *path) {

        _cleanup_close_ int our_fd = -1;
        JournalFile *f;
        struct stat st;
        int r;

        assert(j);
        assert(fd >= 0 || path);

        if (fd < 0) {
                assert(path);  /* For gcc. */
                if (j->toplevel_fd >= 0)
                        /* If there's a top-level fd defined make the path relative, explicitly, since otherwise
                         * openat() ignores the first argument. */

                        fd = our_fd = openat(j->toplevel_fd, skip_slash(path), O_RDONLY|O_CLOEXEC|O_NONBLOCK);
                else
                        fd = our_fd = open(path, O_RDONLY|O_CLOEXEC|O_NONBLOCK);
                if (fd < 0) {
                        r = log_debug_errno(errno, "Failed to open journal file %s: %m", path);
                        goto error;
                }

                r = fd_nonblock(fd, false);
                if (r < 0) {
                        r = log_debug_errno(errno, "Failed to turn off O_NONBLOCK for %s: %m", path);
                        goto error;
                }
        }

        if (fstat(fd, &st) < 0) {
                r = log_debug_errno(errno, "Failed to fstat %s: %m", path ?: "fd");
                goto error;
        }

        r = stat_verify_regular(&st);
        if (r < 0) {
                log_debug_errno(r, "Refusing to open %s: %m", path ?: "fd");
                goto error;
        }

        if (path) {
                f = ordered_hashmap_get(j->files, path);
                if (f) {
                        if (stat_inode_same(&f->last_stat, &st)) {
                                /* We already track this file, under the same path and with the same
                                 * device/inode numbers, it's hence really the same. Mark this file as seen
                                 * in this generation. This is used to GC old files in process_q_overflow()
                                 * to detect journal files that are still there and discern them from those
                                 * which are gone. */

                                f->last_seen_generation = j->generation;
                                return 0;
                        }

                        /* So we tracked a file under this name, but it has a different inode/device. In that
                         * case, it got replaced (probably due to rotation?), let's drop it hence from our
                         * list. */
                        remove_file_real(j, f);
                        f = NULL;
                }
        }

        if (ordered_hashmap_size(j->files) >= JOURNAL_FILES_MAX) {
                r = log_debug_errno(SYNTHETIC_ERRNO(ETOOMANYREFS),
                                    "Too many open journal files, not adding %s.", path ?: "fd");
                goto error;
        }

        r = journal_file_open(fd, path, O_RDONLY, 0, 0, 0, NULL, j->mmap, NULL, &f);
        if (r < 0) {
                log_debug_errno(r, "Failed to open journal file %s: %m", path ?: "from fd");
                goto error;
        }

        /* journal_file_dump(f); */

        /* journal_file_open() generates an replacement fname if necessary, so we can use f->path. */
        r = ordered_hashmap_put(j->files, f->path, f);
        if (r < 0) {
                f->close_fd = false; /* Make sure journal_file_close() doesn't close the caller's fd
                                      * (or our own). The caller or we will do that ourselves. */
                (void) journal_file_close(f);
                goto error;
        }

        TAKE_FD(our_fd); /* the fd is now owned by the JournalFile object */

        f->last_seen_generation = j->generation;

        track_file_disposition(j, f);
        check_network(j, f->fd);

        j->current_invalidate_counter++;

        log_debug("File %s added.", f->path);

        return 0;

error:
        (void) journal_put_error(j, r, path);   /* path==NULL is OK. */
        return r;
}

static int add_file_by_name(
                sd_journal *j,
                const char *prefix,
                const char *filename) {

        _cleanup_free_ char *path = NULL;

        assert(j);
        assert(prefix);
        assert(filename);

        if (j->no_new_files)
                return 0;

        if (!file_type_wanted(j->flags, filename))
                return 0;

        path = path_join(prefix, filename);
        if (!path)
                return -ENOMEM;

        return add_any_file(j, -1, path);
}

static int remove_file_by_name(
                sd_journal *j,
                const char *prefix,
                const char *filename) {

        _cleanup_free_ char *path = NULL;
        JournalFile *f;

        assert(j);
        assert(prefix);
        assert(filename);

        path = path_join(prefix, filename);
        if (!path)
                return -ENOMEM;

        f = ordered_hashmap_get(j->files, path);
        if (!f)
                return 0;

        remove_file_real(j, f);
        return 1;
}

static void remove_file_real(sd_journal *j, JournalFile *f) {
        assert(j);
        assert(f);

        (void) ordered_hashmap_remove(j->files, f->path);

        log_debug("File %s removed.", f->path);

        if (j->current_file == f) {
                j->current_file = NULL;
                j->current_field = 0;
        }

        if (j->unique_file == f) {
                /* Jump to the next unique_file or NULL if that one was last */
                j->unique_file = ordered_hashmap_next(j->files, j->unique_file->path);
                j->unique_offset = 0;
                if (!j->unique_file)
                        j->unique_file_lost = true;
        }

        if (j->fields_file == f) {
                j->fields_file = ordered_hashmap_next(j->files, j->fields_file->path);
                j->fields_offset = 0;
                if (!j->fields_file)
                        j->fields_file_lost = true;
        }

        (void) journal_file_close(f);

        j->current_invalidate_counter++;
}

static int dirname_is_machine_id(const char *fn) {
        sd_id128_t id, machine;
        const char *e;
        int r;

        /* Returns true if the specified directory name matches the local machine ID */

        r = sd_id128_get_machine(&machine);
        if (r < 0)
                return r;

        e = strchr(fn, '.');
        if (e) {
                const char *k;

                /* Looks like it has a namespace suffix. Verify that. */
                if (!log_namespace_name_valid(e + 1))
                        return false;

                k = strndupa_safe(fn, e - fn);
                r = sd_id128_from_string(k, &id);
        } else
                r = sd_id128_from_string(fn, &id);
        if (r < 0)
                return r;

        return sd_id128_equal(id, machine);
}

static int dirname_has_namespace(const char *fn, const char *namespace) {
        const char *e;

        /* Returns true if the specified directory name matches the specified namespace */

        e = strchr(fn, '.');
        if (e) {
                const char *k;

                if (!namespace)
                        return false;

                if (!streq(e + 1, namespace))
                        return false;

                k = strndupa_safe(fn, e - fn);
                return id128_is_valid(k);
        }

        if (namespace)
                return false;

        return id128_is_valid(fn);
}

static bool dirent_is_journal_file(const struct dirent *de) {
        assert(de);

        /* Returns true if the specified directory entry looks like a journal file we might be interested in */

        if (!IN_SET(de->d_type, DT_REG, DT_LNK, DT_UNKNOWN))
                return false;

        return endswith(de->d_name, ".journal") ||
                endswith(de->d_name, ".journal~");
}

static bool dirent_is_journal_subdir(const struct dirent *de) {
        const char *e, *n;
        assert(de);

        /* returns true if the specified directory entry looks like a directory that might contain journal
         * files we might be interested in, i.e. is either a 128bit ID or a 128bit ID suffixed by a
         * namespace. */

        if (!IN_SET(de->d_type, DT_DIR, DT_LNK, DT_UNKNOWN))
                return false;

        e = strchr(de->d_name, '.');
        if (!e)
                return id128_is_valid(de->d_name); /* No namespace */

        n = strndupa_safe(de->d_name, e - de->d_name);
        if (!id128_is_valid(n))
                return false;

        return log_namespace_name_valid(e + 1);
}

static int directory_open(sd_journal *j, const char *path, DIR **ret) {
        DIR *d;

        assert(j);
        assert(path);
        assert(ret);

        if (j->toplevel_fd < 0)
                d = opendir(path);
        else
                /* Open the specified directory relative to the toplevel fd. Enforce that the path specified is
                 * relative, by dropping the initial slash */
                d = xopendirat(j->toplevel_fd, skip_slash(path), 0);
        if (!d)
                return -errno;

        *ret = d;
        return 0;
}

static int add_directory(sd_journal *j, const char *prefix, const char *dirname);

static void directory_enumerate(sd_journal *j, Directory *m, DIR *d) {
        assert(j);
        assert(m);
        assert(d);

        FOREACH_DIRENT_ALL(de, d, goto fail) {
                if (dirent_is_journal_file(de))
                        (void) add_file_by_name(j, m->path, de->d_name);

                if (m->is_root && dirent_is_journal_subdir(de))
                        (void) add_directory(j, m->path, de->d_name);
        }

        return;
fail:
        log_debug_errno(errno, "Failed to enumerate directory %s, ignoring: %m", m->path);
}

static void directory_watch(sd_journal *j, Directory *m, int fd, uint32_t mask) {
        int r;

        assert(j);
        assert(m);
        assert(fd >= 0);

        /* Watch this directory if that's enabled and if it not being watched yet. */

        if (m->wd > 0) /* Already have a watch? */
                return;
        if (j->inotify_fd < 0) /* Not watching at all? */
                return;

        m->wd = inotify_add_watch_fd(j->inotify_fd, fd, mask);
        if (m->wd < 0) {
                log_debug_errno(m->wd, "Failed to watch journal directory '%s', ignoring: %m", m->path);
                return;
        }

        r = hashmap_put(j->directories_by_wd, INT_TO_PTR(m->wd), m);
        if (r == -EEXIST)
                log_debug_errno(r, "Directory '%s' already being watched under a different path, ignoring: %m", m->path);
        if (r < 0) {
                log_debug_errno(r, "Failed to add watch for journal directory '%s' to hashmap, ignoring: %m", m->path);
                (void) inotify_rm_watch(j->inotify_fd, m->wd);
                m->wd = -1;
        }
}

static int add_directory(
                sd_journal *j,
                const char *prefix,
                const char *dirname) {

        _cleanup_free_ char *path = NULL;
        _cleanup_closedir_ DIR *d = NULL;
        Directory *m;
        int r, k;

        assert(j);
        assert(prefix);

        /* Adds a journal file directory to watch. If the directory is already tracked this updates the inotify watch
         * and reenumerates directory contents */

        path = path_join(prefix, dirname);
        if (!path) {
                r = -ENOMEM;
                goto fail;
        }

        log_debug("Considering directory '%s'.", path);

        /* We consider everything local that is in a directory for the local machine ID, or that is stored in /run */
        if ((j->flags & SD_JOURNAL_LOCAL_ONLY) &&
            !((dirname && dirname_is_machine_id(dirname) > 0) || path_has_prefix(j, path, "/run")))
                return 0;

        if (dirname &&
            (!(FLAGS_SET(j->flags, SD_JOURNAL_ALL_NAMESPACES) ||
               dirname_has_namespace(dirname, j->namespace) > 0 ||
               (FLAGS_SET(j->flags, SD_JOURNAL_INCLUDE_DEFAULT_NAMESPACE) && dirname_has_namespace(dirname, NULL) > 0))))
                return 0;

        r = directory_open(j, path, &d);
        if (r < 0) {
                log_debug_errno(r, "Failed to open directory '%s': %m", path);
                goto fail;
        }

        m = hashmap_get(j->directories_by_path, path);
        if (!m) {
                m = new(Directory, 1);
                if (!m) {
                        r = -ENOMEM;
                        goto fail;
                }

                *m = (Directory) {
                        .is_root = false,
                        .path = path,
                };

                if (hashmap_put(j->directories_by_path, m->path, m) < 0) {
                        free(m);
                        r = -ENOMEM;
                        goto fail;
                }

                path = NULL; /* avoid freeing in cleanup */
                j->current_invalidate_counter++;

                log_debug("Directory %s added.", m->path);

        } else if (m->is_root)
                return 0; /* Don't 'downgrade' from root directory */

        m->last_seen_generation = j->generation;

        directory_watch(j, m, dirfd(d),
                        IN_CREATE|IN_MOVED_TO|IN_MODIFY|IN_ATTRIB|IN_DELETE|
                        IN_DELETE_SELF|IN_MOVE_SELF|IN_UNMOUNT|IN_MOVED_FROM|
                        IN_ONLYDIR);

        if (!j->no_new_files)
                directory_enumerate(j, m, d);

        check_network(j, dirfd(d));

        return 0;

fail:
        k = journal_put_error(j, r, path ?: prefix);
        if (k < 0)
                return k;

        return r;
}

static int add_root_directory(sd_journal *j, const char *p, bool missing_ok) {

        _cleanup_closedir_ DIR *d = NULL;
        Directory *m;
        int r, k;

        assert(j);

        /* Adds a root directory to our set of directories to use. If the root directory is already in the set, we
         * update the inotify logic, and renumerate the directory entries. This call may hence be called to initially
         * populate the set, as well as to update it later. */

        if (p) {
                /* If there's a path specified, use it. */

                log_debug("Considering root directory '%s'.", p);

                if ((j->flags & SD_JOURNAL_RUNTIME_ONLY) &&
                    !path_has_prefix(j, p, "/run"))
                        return -EINVAL;

                if (j->prefix)
                        p = strjoina(j->prefix, p);

                r = directory_open(j, p, &d);
                if (r == -ENOENT && missing_ok)
                        return 0;
                if (r < 0) {
                        log_debug_errno(r, "Failed to open root directory %s: %m", p);
                        goto fail;
                }
        } else {
                _cleanup_close_ int dfd = -1;

                /* If there's no path specified, then we use the top-level fd itself. We duplicate the fd here, since
                 * opendir() will take possession of the fd, and close it, which we don't want. */

                p = "."; /* store this as "." in the directories hashmap */

                dfd = fcntl(j->toplevel_fd, F_DUPFD_CLOEXEC, 3);
                if (dfd < 0) {
                        r = -errno;
                        goto fail;
                }

                d = take_fdopendir(&dfd);
                if (!d) {
                        r = -errno;
                        goto fail;
                }

                rewinddir(d);
        }

        m = hashmap_get(j->directories_by_path, p);
        if (!m) {
                m = new0(Directory, 1);
                if (!m) {
                        r = -ENOMEM;
                        goto fail;
                }

                m->is_root = true;

                m->path = strdup(p);
                if (!m->path) {
                        free(m);
                        r = -ENOMEM;
                        goto fail;
                }

                if (hashmap_put(j->directories_by_path, m->path, m) < 0) {
                        free(m->path);
                        free(m);
                        r = -ENOMEM;
                        goto fail;
                }

                j->current_invalidate_counter++;

                log_debug("Root directory %s added.", m->path);

        } else if (!m->is_root)
                return 0;

        directory_watch(j, m, dirfd(d),
                        IN_CREATE|IN_MOVED_TO|IN_MODIFY|IN_ATTRIB|IN_DELETE|
                        IN_ONLYDIR);

        if (!j->no_new_files)
                directory_enumerate(j, m, d);

        check_network(j, dirfd(d));

        return 0;

fail:
        k = journal_put_error(j, r, p);
        if (k < 0)
                return k;

        return r;
}

static void remove_directory(sd_journal *j, Directory *d) {
        assert(j);

        if (d->wd > 0) {
                hashmap_remove(j->directories_by_wd, INT_TO_PTR(d->wd));

                if (j->inotify_fd >= 0)
                        (void) inotify_rm_watch(j->inotify_fd, d->wd);
        }

        hashmap_remove(j->directories_by_path, d->path);

        if (d->is_root)
                log_debug("Root directory %s removed.", d->path);
        else
                log_debug("Directory %s removed.", d->path);

        free(d->path);
        free(d);
}

static int add_search_paths(sd_journal *j) {

        static const char search_paths[] =
                "/run/log/journal\0"
                "/var/log/journal\0";
        const char *p;

        assert(j);

        /* We ignore most errors here, since the idea is to only open
         * what's actually accessible, and ignore the rest. */

        NULSTR_FOREACH(p, search_paths)
                (void) add_root_directory(j, p, true);

        if (!(j->flags & SD_JOURNAL_LOCAL_ONLY))
                (void) add_root_directory(j, "/var/log/journal/remote", true);

        return 0;
}

static int add_current_paths(sd_journal *j) {
        JournalFile *f;

        assert(j);
        assert(j->no_new_files);

        /* Simply adds all directories for files we have open as directories. We don't expect errors here, so we
         * treat them as fatal. */

        ORDERED_HASHMAP_FOREACH(f, j->files) {
                _cleanup_free_ char *dir = NULL;
                int r;

                r = path_extract_directory(f->path, &dir);
                if (r < 0)
                        return r;

                r = add_directory(j, dir, NULL);
                if (r < 0)
                        return r;
        }

        return 0;
}

static int allocate_inotify(sd_journal *j) {
        assert(j);

        if (j->inotify_fd < 0) {
                j->inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
                if (j->inotify_fd < 0)
                        return -errno;
        }

        return hashmap_ensure_allocated(&j->directories_by_wd, NULL);
}

static sd_journal *journal_new(int flags, const char *path, const char *namespace) {
        _cleanup_(sd_journal_closep) sd_journal *j = NULL;

        j = new0(sd_journal, 1);
        if (!j)
                return NULL;

        j->original_pid = getpid_cached();
        j->toplevel_fd = -1;
        j->inotify_fd = -1;
        j->flags = flags;
        j->data_threshold = DEFAULT_DATA_THRESHOLD;

        if (path) {
                char *t;

                t = strdup(path);
                if (!t)
                        return NULL;

                if (flags & SD_JOURNAL_OS_ROOT)
                        j->prefix = t;
                else
                        j->path = t;
        }

        if (namespace) {
                j->namespace = strdup(namespace);
                if (!j->namespace)
                        return NULL;
        }

        j->files = ordered_hashmap_new(&path_hash_ops);
        if (!j->files)
                return NULL;

        j->files_cache = ordered_hashmap_iterated_cache_new(j->files);
        j->directories_by_path = hashmap_new(&path_hash_ops);
        j->mmap = mmap_cache_new();
        if (!j->files_cache || !j->directories_by_path || !j->mmap)
                return NULL;

        return TAKE_PTR(j);
}

#define OPEN_ALLOWED_FLAGS                              \
        (SD_JOURNAL_LOCAL_ONLY |                        \
         SD_JOURNAL_RUNTIME_ONLY |                      \
         SD_JOURNAL_SYSTEM |                            \
         SD_JOURNAL_CURRENT_USER |                      \
         SD_JOURNAL_ALL_NAMESPACES |                    \
         SD_JOURNAL_INCLUDE_DEFAULT_NAMESPACE)

_public_ int sd_journal_open_namespace(sd_journal **ret, const char *namespace, int flags) {
        _cleanup_(sd_journal_closep) sd_journal *j = NULL;
        int r;

        assert_return(ret, -EINVAL);
        assert_return((flags & ~OPEN_ALLOWED_FLAGS) == 0, -EINVAL);

        j = journal_new(flags, NULL, namespace);
        if (!j)
                return -ENOMEM;

        r = add_search_paths(j);
        if (r < 0)
                return r;

        *ret = TAKE_PTR(j);
        return 0;
}

_public_ int sd_journal_open(sd_journal **ret, int flags) {
        return sd_journal_open_namespace(ret, NULL, flags);
}

#define OPEN_CONTAINER_ALLOWED_FLAGS                    \
        (SD_JOURNAL_LOCAL_ONLY | SD_JOURNAL_SYSTEM)

_public_ int sd_journal_open_container(sd_journal **ret, const char *machine, int flags) {
        _cleanup_free_ char *root = NULL, *class = NULL;
        _cleanup_(sd_journal_closep) sd_journal *j = NULL;
        char *p;
        int r;

        /* This is deprecated, people should use machined's OpenMachineRootDirectory() call instead in
         * combination with sd_journal_open_directory_fd(). */

        assert_return(machine, -EINVAL);
        assert_return(ret, -EINVAL);
        assert_return((flags & ~OPEN_CONTAINER_ALLOWED_FLAGS) == 0, -EINVAL);
        assert_return(hostname_is_valid(machine, 0), -EINVAL);

        p = strjoina("/run/systemd/machines/", machine);
        r = parse_env_file(NULL, p,
                           "ROOT", &root,
                           "CLASS", &class);
        if (r == -ENOENT)
                return -EHOSTDOWN;
        if (r < 0)
                return r;
        if (!root)
                return -ENODATA;

        if (!streq_ptr(class, "container"))
                return -EIO;

        j = journal_new(flags, root, NULL);
        if (!j)
                return -ENOMEM;

        r = add_search_paths(j);
        if (r < 0)
                return r;

        *ret = TAKE_PTR(j);
        return 0;
}

#define OPEN_DIRECTORY_ALLOWED_FLAGS                    \
        (SD_JOURNAL_OS_ROOT |                           \
         SD_JOURNAL_SYSTEM | SD_JOURNAL_CURRENT_USER )

_public_ int sd_journal_open_directory(sd_journal **ret, const char *path, int flags) {
        _cleanup_(sd_journal_closep) sd_journal *j = NULL;
        int r;

        assert_return(ret, -EINVAL);
        assert_return(path, -EINVAL);
        assert_return((flags & ~OPEN_DIRECTORY_ALLOWED_FLAGS) == 0, -EINVAL);

        j = journal_new(flags, path, NULL);
        if (!j)
                return -ENOMEM;

        if (flags & SD_JOURNAL_OS_ROOT)
                r = add_search_paths(j);
        else
                r = add_root_directory(j, path, false);
        if (r < 0)
                return r;

        *ret = TAKE_PTR(j);
        return 0;
}

_public_ int sd_journal_open_files(sd_journal **ret, const char **paths, int flags) {
        _cleanup_(sd_journal_closep) sd_journal *j = NULL;
        int r;

        assert_return(ret, -EINVAL);
        assert_return(flags == 0, -EINVAL);

        j = journal_new(flags, NULL, NULL);
        if (!j)
                return -ENOMEM;

        STRV_FOREACH(path, paths) {
                r = add_any_file(j, -1, *path);
                if (r < 0)
                        return r;
        }

        j->no_new_files = true;

        *ret = TAKE_PTR(j);
        return 0;
}

#define OPEN_DIRECTORY_FD_ALLOWED_FLAGS         \
        (SD_JOURNAL_OS_ROOT |                           \
         SD_JOURNAL_SYSTEM | SD_JOURNAL_CURRENT_USER )

_public_ int sd_journal_open_directory_fd(sd_journal **ret, int fd, int flags) {
        _cleanup_(sd_journal_closep) sd_journal *j = NULL;
        struct stat st;
        int r;

        assert_return(ret, -EINVAL);
        assert_return(fd >= 0, -EBADF);
        assert_return((flags & ~OPEN_DIRECTORY_FD_ALLOWED_FLAGS) == 0, -EINVAL);

        if (fstat(fd, &st) < 0)
                return -errno;

        if (!S_ISDIR(st.st_mode))
                return -EBADFD;

        j = journal_new(flags, NULL, NULL);
        if (!j)
                return -ENOMEM;

        j->toplevel_fd = fd;

        if (flags & SD_JOURNAL_OS_ROOT)
                r = add_search_paths(j);
        else
                r = add_root_directory(j, NULL, false);
        if (r < 0)
                return r;

        *ret = TAKE_PTR(j);
        return 0;
}

_public_ int sd_journal_open_files_fd(sd_journal **ret, int fds[], unsigned n_fds, int flags) {
        JournalFile *f;
        _cleanup_(sd_journal_closep) sd_journal *j = NULL;
        int r;

        assert_return(ret, -EINVAL);
        assert_return(n_fds > 0, -EBADF);
        assert_return(flags == 0, -EINVAL);

        j = journal_new(flags, NULL, NULL);
        if (!j)
                return -ENOMEM;

        for (unsigned i = 0; i < n_fds; i++) {
                struct stat st;

                if (fds[i] < 0) {
                        r = -EBADF;
                        goto fail;
                }

                if (fstat(fds[i], &st) < 0) {
                        r = -errno;
                        goto fail;
                }

                r = stat_verify_regular(&st);
                if (r < 0)
                        goto fail;

                r = add_any_file(j, fds[i], NULL);
                if (r < 0)
                        goto fail;
        }

        j->no_new_files = true;
        j->no_inotify = true;

        *ret = TAKE_PTR(j);
        return 0;

fail:
        /* If we fail, make sure we don't take possession of the files we managed to make use of successfully, and they
         * remain open */
        ORDERED_HASHMAP_FOREACH(f, j->files)
                f->close_fd = false;

        return r;
}

_public_ void sd_journal_close(sd_journal *j) {
        Directory *d;

        if (!j)
                return;

        sd_journal_flush_matches(j);

        ordered_hashmap_free_with_destructor(j->files, journal_file_close);
        iterated_cache_free(j->files_cache);

        while ((d = hashmap_first(j->directories_by_path)))
                remove_directory(j, d);

        while ((d = hashmap_first(j->directories_by_wd)))
                remove_directory(j, d);

        hashmap_free(j->directories_by_path);
        hashmap_free(j->directories_by_wd);

        safe_close(j->inotify_fd);

        if (j->mmap) {
                mmap_cache_stats_log_debug(j->mmap);
                mmap_cache_unref(j->mmap);
        }

        hashmap_free_free(j->errors);

        free(j->path);
        free(j->prefix);
        free(j->namespace);
        free(j->unique_field);
        free(j->fields_buffer);
        free(j);
}

_public_ int sd_journal_get_realtime_usec(sd_journal *j, uint64_t *ret) {
        Object *o;
        JournalFile *f;
        int r;

        assert_return(j, -EINVAL);
        assert_return(!journal_pid_changed(j), -ECHILD);
        assert_return(ret, -EINVAL);

        f = j->current_file;
        if (!f)
                return -EADDRNOTAVAIL;

        if (f->current_offset <= 0)
                return -EADDRNOTAVAIL;

        r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
        if (r < 0)
                return r;

        *ret = le64toh(o->entry.realtime);
        return 0;
}

_public_ int sd_journal_get_monotonic_usec(sd_journal *j, uint64_t *ret, sd_id128_t *ret_boot_id) {
        Object *o;
        JournalFile *f;
        int r;

        assert_return(j, -EINVAL);
        assert_return(!journal_pid_changed(j), -ECHILD);

        f = j->current_file;
        if (!f)
                return -EADDRNOTAVAIL;

        if (f->current_offset <= 0)
                return -EADDRNOTAVAIL;

        r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
        if (r < 0)
                return r;

        if (!ret_boot_id) {
                sd_id128_t id;

                r = sd_id128_get_boot(&id);
                if (r < 0)
                        return r;

                if (!sd_id128_equal(id, o->entry.boot_id))
                        return -ESTALE;
        }

        if (ret)
                *ret = le64toh(o->entry.monotonic);
        if (ret_boot_id)
                *ret_boot_id = o->entry.boot_id;

        return 0;
}

static bool field_is_valid(const char *field) {
        assert(field);

        if (isempty(field))
                return false;

        if (startswith(field, "__"))
                return false;

        for (const char *p = field; *p; p++) {

                if (*p == '_')
                        continue;

                if (*p >= 'A' && *p <= 'Z')
                        continue;

                if (ascii_isdigit(*p))
                        continue;

                return false;
        }

        return true;
}

_public_ int sd_journal_get_data(sd_journal *j, const char *field, const void **data, size_t *size) {
        JournalFile *f;
        size_t field_length;
        Object *o;
        int r;

        assert_return(j, -EINVAL);
        assert_return(!journal_pid_changed(j), -ECHILD);
        assert_return(field, -EINVAL);
        assert_return(data, -EINVAL);
        assert_return(size, -EINVAL);
        assert_return(field_is_valid(field), -EINVAL);

        f = j->current_file;
        if (!f)
                return -EADDRNOTAVAIL;

        if (f->current_offset <= 0)
                return -EADDRNOTAVAIL;

        r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
        if (r < 0)
                return r;

        field_length = strlen(field);

        uint64_t n = journal_file_entry_n_items(f, o);
        for (uint64_t i = 0; i < n; i++) {
                uint64_t p;
                void *d;
                size_t l;

                p = journal_file_entry_item_object_offset(f, o, i);
                r = journal_file_data_payload(f, NULL, p, field, field_length, j->data_threshold, &d, &l);
                if (r == 0)
                        goto next;
                if (IN_SET(r, -EADDRNOTAVAIL, -EBADMSG)) {
                        log_debug_errno(r, "Entry item %"PRIu64" data object is bad, skipping over it: %m", i);
                        goto next;
                }
                if (r < 0)
                        return r;

                *data = d;
                *size = l;

                return 0;

        next:
                /* journal_file_data_payload() may clear or overwrite cached object. */
                r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
                if (r < 0)
                        return r;
        }

        return -ENOENT;
}

_public_ int sd_journal_enumerate_data(sd_journal *j, const void **data, size_t *size) {
        JournalFile *f;
        Object *o;
        int r;

        assert_return(j, -EINVAL);
        assert_return(!journal_pid_changed(j), -ECHILD);
        assert_return(data, -EINVAL);
        assert_return(size, -EINVAL);

        f = j->current_file;
        if (!f)
                return -EADDRNOTAVAIL;

        if (f->current_offset <= 0)
                return -EADDRNOTAVAIL;

        r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
        if (r < 0)
                return r;

        for (uint64_t n = journal_file_entry_n_items(f, o); j->current_field < n; j->current_field++) {
                uint64_t p;
                void *d;
                size_t l;

                p = journal_file_entry_item_object_offset(f, o, j->current_field);
                r = journal_file_data_payload(f, NULL, p, NULL, 0, j->data_threshold, &d, &l);
                if (IN_SET(r, -EADDRNOTAVAIL, -EBADMSG)) {
                        log_debug_errno(r, "Entry item %"PRIu64" data object is bad, skipping over it: %m", j->current_field);
                        goto next;
                }
                if (r < 0)
                        return r;
                assert(r > 0);

                *data = d;
                *size = l;

                j->current_field++;

                return 1;

        next:
                /* journal_file_data_payload() may clear or overwrite cached object. */
                r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
                if (r < 0)
                        return r;
        }

        return 0;
}

_public_ int sd_journal_enumerate_available_data(sd_journal *j, const void **data, size_t *size) {
        for (;;) {
                int r;

                r = sd_journal_enumerate_data(j, data, size);
                if (r >= 0)
                        return r;
                if (!JOURNAL_ERRNO_IS_UNAVAILABLE_FIELD(r))
                        return r;
                j->current_field++; /* Try with the next field */
        }
}

_public_ void sd_journal_restart_data(sd_journal *j) {
        if (!j)
                return;

        j->current_field = 0;
}

static int reiterate_all_paths(sd_journal *j) {
        assert(j);

        if (j->no_new_files)
                return add_current_paths(j);

        if (j->flags & SD_JOURNAL_OS_ROOT)
                return add_search_paths(j);

        if (j->toplevel_fd >= 0)
                return add_root_directory(j, NULL, false);

        if (j->path)
                return add_root_directory(j, j->path, true);

        return add_search_paths(j);
}

_public_ int sd_journal_get_fd(sd_journal *j) {
        int r;

        assert_return(j, -EINVAL);
        assert_return(!journal_pid_changed(j), -ECHILD);

        if (j->no_inotify)
                return -EMEDIUMTYPE;

        if (j->inotify_fd >= 0)
                return j->inotify_fd;

        r = allocate_inotify(j);
        if (r < 0)
                return r;

        log_debug("Reiterating files to get inotify watches established.");

        /* Iterate through all dirs again, to add them to the inotify */
        r = reiterate_all_paths(j);
        if (r < 0)
                return r;

        return j->inotify_fd;
}

_public_ int sd_journal_get_events(sd_journal *j) {
        int fd;

        assert_return(j, -EINVAL);
        assert_return(!journal_pid_changed(j), -ECHILD);

        fd = sd_journal_get_fd(j);
        if (fd < 0)
                return fd;

        return POLLIN;
}

_public_ int sd_journal_get_timeout(sd_journal *j, uint64_t *timeout_usec) {
        int fd;

        assert_return(j, -EINVAL);
        assert_return(!journal_pid_changed(j), -ECHILD);
        assert_return(timeout_usec, -EINVAL);

        fd = sd_journal_get_fd(j);
        if (fd < 0)
                return fd;

        if (!j->on_network) {
                *timeout_usec = UINT64_MAX;
                return 0;
        }

        /* If we are on the network we need to regularly check for
         * changes manually */

        *timeout_usec = j->last_process_usec + JOURNAL_FILES_RECHECK_USEC;
        return 1;
}

static void process_q_overflow(sd_journal *j) {
        JournalFile *f;
        Directory *m;

        assert(j);

        /* When the inotify queue overruns we need to enumerate and re-validate all journal files to bring our list
         * back in sync with what's on disk. For this we pick a new generation counter value. It'll be assigned to all
         * journal files we encounter. All journal files and all directories that don't carry it after reenumeration
         * are subject for unloading. */

        log_debug("Inotify queue overrun, reiterating everything.");

        j->generation++;
        (void) reiterate_all_paths(j);

        ORDERED_HASHMAP_FOREACH(f, j->files) {

                if (f->last_seen_generation == j->generation)
                        continue;

                log_debug("File '%s' hasn't been seen in this enumeration, removing.", f->path);
                remove_file_real(j, f);
        }

        HASHMAP_FOREACH(m, j->directories_by_path) {

                if (m->last_seen_generation == j->generation)
                        continue;

                if (m->is_root) /* Never GC root directories */
                        continue;

                log_debug("Directory '%s' hasn't been seen in this enumeration, removing.", f->path);
                remove_directory(j, m);
        }

        log_debug("Reiteration complete.");
}

static void process_inotify_event(sd_journal *j, const struct inotify_event *e) {
        Directory *d;

        assert(j);
        assert(e);

        if (e->mask & IN_Q_OVERFLOW) {
                process_q_overflow(j);
                return;
        }

        /* Is this a subdirectory we watch? */
        d = hashmap_get(j->directories_by_wd, INT_TO_PTR(e->wd));
        if (d) {
                if (!(e->mask & IN_ISDIR) && e->len > 0 &&
                    (endswith(e->name, ".journal") ||
                     endswith(e->name, ".journal~"))) {

                        /* Event for a journal file */

                        if (e->mask & (IN_CREATE|IN_MOVED_TO|IN_MODIFY|IN_ATTRIB))
                                (void) add_file_by_name(j, d->path, e->name);
                        else if (e->mask & (IN_DELETE|IN_MOVED_FROM|IN_UNMOUNT))
                                (void) remove_file_by_name(j, d->path, e->name);

                } else if (!d->is_root && e->len == 0) {

                        /* Event for a subdirectory */

                        if (e->mask & (IN_DELETE_SELF|IN_MOVE_SELF|IN_UNMOUNT))
                                remove_directory(j, d);

                } else if (d->is_root && (e->mask & IN_ISDIR) && e->len > 0 && id128_is_valid(e->name)) {

                        /* Event for root directory */

                        if (e->mask & (IN_CREATE|IN_MOVED_TO|IN_MODIFY|IN_ATTRIB))
                                (void) add_directory(j, d->path, e->name);
                }

                return;
        }

        if (e->mask & IN_IGNORED)
                return;

        log_debug("Unexpected inotify event.");
}

static int determine_change(sd_journal *j) {
        bool b;

        assert(j);

        b = j->current_invalidate_counter != j->last_invalidate_counter;
        j->last_invalidate_counter = j->current_invalidate_counter;

        return b ? SD_JOURNAL_INVALIDATE : SD_JOURNAL_APPEND;
}

_public_ int sd_journal_process(sd_journal *j) {
        bool got_something = false;

        assert_return(j, -EINVAL);
        assert_return(!journal_pid_changed(j), -ECHILD);

        if (j->inotify_fd < 0) /* We have no inotify fd yet? Then there's noting to process. */
                return 0;

        j->last_process_usec = now(CLOCK_MONOTONIC);
        j->last_invalidate_counter = j->current_invalidate_counter;

        for (;;) {
                union inotify_event_buffer buffer;
                ssize_t l;

                l = read(j->inotify_fd, &buffer, sizeof(buffer));
                if (l < 0) {
                        if (ERRNO_IS_TRANSIENT(errno))
                                return got_something ? determine_change(j) : SD_JOURNAL_NOP;

                        return -errno;
                }

                got_something = true;

                FOREACH_INOTIFY_EVENT(e, buffer, l)
                        process_inotify_event(j, e);
        }
}

_public_ int sd_journal_wait(sd_journal *j, uint64_t timeout_usec) {
        int r;
        uint64_t t;

        assert_return(j, -EINVAL);
        assert_return(!journal_pid_changed(j), -ECHILD);

        if (j->inotify_fd < 0) {
                JournalFile *f;

                /* This is the first invocation, hence create the
                 * inotify watch */
                r = sd_journal_get_fd(j);
                if (r < 0)
                        return r;

                /* Server might have done some vacuuming while we weren't watching.
                   Get rid of the deleted files now so they don't stay around indefinitely. */
                ORDERED_HASHMAP_FOREACH(f, j->files) {
                        r = journal_file_fstat(f);
                        if (r == -EIDRM)
                                remove_file_real(j, f);
                        else if (r < 0) {
                                log_debug_errno(r,"Failed to fstat() journal file '%s' : %m", f->path);
                                continue;
                        }
                }

                /* The journal might have changed since the context
                 * object was created and we weren't watching before,
                 * hence don't wait for anything, and return
                 * immediately. */
                return determine_change(j);
        }

        r = sd_journal_get_timeout(j, &t);
        if (r < 0)
                return r;

        if (t != UINT64_MAX) {
                t = usec_sub_unsigned(t, now(CLOCK_MONOTONIC));

                if (timeout_usec == UINT64_MAX || timeout_usec > t)
                        timeout_usec = t;
        }

        do {
                r = fd_wait_for_event(j->inotify_fd, POLLIN, timeout_usec);
        } while (r == -EINTR);

        if (r < 0)
                return r;

        return sd_journal_process(j);
}

_public_ int sd_journal_get_cutoff_realtime_usec(sd_journal *j, uint64_t *from, uint64_t *to) {
        JournalFile *f;
        bool first = true;
        uint64_t fmin = 0, tmax = 0;
        int r;

        assert_return(j, -EINVAL);
        assert_return(!journal_pid_changed(j), -ECHILD);
        assert_return(from || to, -EINVAL);
        assert_return(from != to, -EINVAL);

        ORDERED_HASHMAP_FOREACH(f, j->files) {
                usec_t fr, t;

                r = journal_file_get_cutoff_realtime_usec(f, &fr, &t);
                if (r == -ENOENT)
                        continue;
                if (r < 0)
                        return r;
                if (r == 0)
                        continue;

                if (first) {
                        fmin = fr;
                        tmax = t;
                        first = false;
                } else {
                        fmin = MIN(fr, fmin);
                        tmax = MAX(t, tmax);
                }
        }

        if (from)
                *from = fmin;
        if (to)
                *to = tmax;

        return first ? 0 : 1;
}

_public_ int sd_journal_get_cutoff_monotonic_usec(
                sd_journal *j,
                sd_id128_t boot_id,
                uint64_t *ret_from,
                uint64_t *ret_to) {

        uint64_t from = UINT64_MAX, to = UINT64_MAX;
        bool found = false;
        JournalFile *f;
        int r;

        assert_return(j, -EINVAL);
        assert_return(!journal_pid_changed(j), -ECHILD);
        assert_return(ret_from != ret_to, -EINVAL);

        ORDERED_HASHMAP_FOREACH(f, j->files) {
                usec_t ff, tt;

                r = journal_file_get_cutoff_monotonic_usec(f, boot_id, &ff, &tt);
                if (r == -ENOENT)
                        continue;
                if (r < 0)
                        return r;
                if (r == 0)
                        continue;

                if (found) {
                        from = MIN(ff, from);
                        to = MAX(tt, to);
                } else {
                        from = ff;
                        to = tt;
                        found = true;
                }
        }

        if (ret_from)
                *ret_from = from;
        if (ret_to)
                *ret_to = to;

        return found;
}

void journal_print_header(sd_journal *j) {
        JournalFile *f;
        bool newline = false;

        assert(j);

        ORDERED_HASHMAP_FOREACH(f, j->files) {
                if (newline)
                        putchar('\n');
                else
                        newline = true;

                journal_file_print_header(f);
        }
}

_public_ int sd_journal_get_usage(sd_journal *j, uint64_t *ret) {
        JournalFile *f;
        uint64_t sum = 0;

        assert_return(j, -EINVAL);
        assert_return(!journal_pid_changed(j), -ECHILD);
        assert_return(ret, -EINVAL);

        ORDERED_HASHMAP_FOREACH(f, j->files) {
                struct stat st;
                uint64_t b;

                if (fstat(f->fd, &st) < 0)
                        return -errno;

                b = (uint64_t) st.st_blocks;
                if (b > UINT64_MAX / 512)
                        return -EOVERFLOW;
                b *= 512;

                if (sum > UINT64_MAX - b)
                        return -EOVERFLOW;
                sum += b;
        }

        *ret = sum;
        return 0;
}

_public_ int sd_journal_query_unique(sd_journal *j, const char *field) {
        int r;

        assert_return(j, -EINVAL);
        assert_return(!journal_pid_changed(j), -ECHILD);
        assert_return(!isempty(field), -EINVAL);

        if (!field_is_valid(field))
                return -EINVAL;

        r = free_and_strdup(&j->unique_field, field);
        if (r < 0)
                return r;

        j->unique_file = NULL;
        j->unique_offset = 0;
        j->unique_file_lost = false;

        return 0;
}

_public_ int sd_journal_enumerate_unique(
                sd_journal *j,
                const void **ret_data,
                size_t *ret_size) {

        size_t k;

        assert_return(j, -EINVAL);
        assert_return(!journal_pid_changed(j), -ECHILD);
        assert_return(j->unique_field, -EINVAL);

        k = strlen(j->unique_field);

        if (!j->unique_file) {
                if (j->unique_file_lost)
                        return 0;

                j->unique_file = ordered_hashmap_first(j->files);
                if (!j->unique_file)
                        return 0;

                j->unique_offset = 0;
        }

        for (;;) {
                JournalFile *of;
                Object *o;
                void *odata;
                size_t ol;
                bool found;
                int r;

                /* Proceed to next data object in the field's linked list */
                if (j->unique_offset == 0) {
                        r = journal_file_find_field_object(j->unique_file, j->unique_field, k, &o, NULL);
                        if (r < 0)
                                return r;

                        j->unique_offset = r > 0 ? le64toh(o->field.head_data_offset) : 0;
                } else {
                        r = journal_file_move_to_object(j->unique_file, OBJECT_DATA, j->unique_offset, &o);
                        if (r < 0)
                                return r;

                        j->unique_offset = le64toh(o->data.next_field_offset);
                }

                /* We reached the end of the list? Then start again, with the next file */
                if (j->unique_offset == 0) {
                        j->unique_file = ordered_hashmap_next(j->files, j->unique_file->path);
                        if (!j->unique_file)
                                return 0;

                        continue;
                }

                /* We do not use OBJECT_DATA context here, but OBJECT_UNUSED
                 * instead, so that we can look at this data object at the same
                 * time as one on another file */
                r = journal_file_move_to_object(j->unique_file, OBJECT_UNUSED, j->unique_offset, &o);
                if (r < 0)
                        return r;

                /* Let's do the type check by hand, since we used 0 context above. */
                if (o->object.type != OBJECT_DATA)
                        return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
                                               "%s:offset " OFSfmt ": object has type %d, expected %d",
                                               j->unique_file->path,
                                               j->unique_offset,
                                               o->object.type, OBJECT_DATA);

                r = journal_file_data_payload(j->unique_file, o, j->unique_offset, NULL, 0,
                                              j->data_threshold, &odata, &ol);
                if (r < 0)
                        return r;

                /* Check if we have at least the field name and "=". */
                if (ol <= k)
                        return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
                                               "%s:offset " OFSfmt ": object has size %zu, expected at least %zu",
                                               j->unique_file->path,
                                               j->unique_offset, ol, k + 1);

                if (memcmp(odata, j->unique_field, k) != 0 || ((const char*) odata)[k] != '=')
                        return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
                                               "%s:offset " OFSfmt ": object does not start with \"%s=\"",
                                               j->unique_file->path,
                                               j->unique_offset,
                                               j->unique_field);

                /* OK, now let's see if we already returned this data object by checking if it exists in the
                 * earlier traversed files. */
                found = false;
                ORDERED_HASHMAP_FOREACH(of, j->files) {
                        if (of == j->unique_file)
                                break;

                        /* Skip this file it didn't have any fields indexed */
                        if (JOURNAL_HEADER_CONTAINS(of->header, n_fields) && le64toh(of->header->n_fields) <= 0)
                                continue;

                        /* We can reuse the hash from our current file only on old-style journal files
                         * without keyed hashes. On new-style files we have to calculate the hash anew, to
                         * take the per-file hash seed into consideration. */
                        if (!JOURNAL_HEADER_KEYED_HASH(j->unique_file->header) && !JOURNAL_HEADER_KEYED_HASH(of->header))
                                r = journal_file_find_data_object_with_hash(of, odata, ol, le64toh(o->data.hash), NULL, NULL);
                        else
                                r = journal_file_find_data_object(of, odata, ol, NULL, NULL);
                        if (r < 0)
                                return r;
                        if (r > 0) {
                                found = true;
                                break;
                        }
                }

                if (found)
                        continue;

                *ret_data = odata;
                *ret_size = ol;

                return 1;
        }
}

_public_ int sd_journal_enumerate_available_unique(sd_journal *j, const void **data, size_t *size) {
        for (;;) {
                int r;

                r = sd_journal_enumerate_unique(j, data, size);
                if (r >= 0)
                        return r;
                if (!JOURNAL_ERRNO_IS_UNAVAILABLE_FIELD(r))
                        return r;
                /* Try with the next field. sd_journal_enumerate_unique() modifies state, so on the next try
                 * we will access the next field. */
        }
}

_public_ void sd_journal_restart_unique(sd_journal *j) {
        if (!j)
                return;

        j->unique_file = NULL;
        j->unique_offset = 0;
        j->unique_file_lost = false;
}

_public_ int sd_journal_enumerate_fields(sd_journal *j, const char **field) {
        int r;

        assert_return(j, -EINVAL);
        assert_return(!journal_pid_changed(j), -ECHILD);
        assert_return(field, -EINVAL);

        if (!j->fields_file) {
                if (j->fields_file_lost)
                        return 0;

                j->fields_file = ordered_hashmap_first(j->files);
                if (!j->fields_file)
                        return 0;

                j->fields_hash_table_index = 0;
                j->fields_offset = 0;
        }

        for (;;) {
                JournalFile *f, *of;
                uint64_t m;
                Object *o;
                size_t sz;
                bool found;

                f = j->fields_file;

                if (j->fields_offset == 0) {
                        bool eof = false;

                        /* We are not yet positioned at any field. Let's pick the first one */
                        r = journal_file_map_field_hash_table(f);
                        if (r < 0)
                                return r;

                        m = le64toh(f->header->field_hash_table_size) / sizeof(HashItem);
                        for (;;) {
                                if (j->fields_hash_table_index >= m) {
                                        /* Reached the end of the hash table, go to the next file. */
                                        eof = true;
                                        break;
                                }

                                j->fields_offset = le64toh(f->field_hash_table[j->fields_hash_table_index].head_hash_offset);

                                if (j->fields_offset != 0)
                                        break;

                                /* Empty hash table bucket, go to next one */
                                j->fields_hash_table_index++;
                        }

                        if (eof) {
                                /* Proceed with next file */
                                j->fields_file = ordered_hashmap_next(j->files, f->path);
                                if (!j->fields_file) {
                                        *field = NULL;
                                        return 0;
                                }

                                j->fields_offset = 0;
                                j->fields_hash_table_index = 0;
                                continue;
                        }

                } else {
                        /* We are already positioned at a field. If so, let's figure out the next field from it */

                        r = journal_file_move_to_object(f, OBJECT_FIELD, j->fields_offset, &o);
                        if (r < 0)
                                return r;

                        j->fields_offset = le64toh(o->field.next_hash_offset);
                        if (j->fields_offset == 0) {
                                /* Reached the end of the hash table chain */
                                j->fields_hash_table_index++;
                                continue;
                        }
                }

                /* We use OBJECT_UNUSED here, so that the iterator below doesn't remove our mmap window */
                r = journal_file_move_to_object(f, OBJECT_UNUSED, j->fields_offset, &o);
                if (r < 0)
                        return r;

                /* Because we used OBJECT_UNUSED above, we need to do our type check manually */
                if (o->object.type != OBJECT_FIELD)
                        return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
                                               "%s:offset " OFSfmt ": object has type %i, expected %i",
                                               f->path, j->fields_offset,
                                               o->object.type, OBJECT_FIELD);

                sz = le64toh(o->object.size) - offsetof(Object, field.payload);

                /* Let's see if we already returned this field name before. */
                found = false;
                ORDERED_HASHMAP_FOREACH(of, j->files) {
                        if (of == f)
                                break;

                        /* Skip this file it didn't have any fields indexed */
                        if (JOURNAL_HEADER_CONTAINS(of->header, n_fields) && le64toh(of->header->n_fields) <= 0)
                                continue;

                        if (!JOURNAL_HEADER_KEYED_HASH(f->header) && !JOURNAL_HEADER_KEYED_HASH(of->header))
                                r = journal_file_find_field_object_with_hash(of, o->field.payload, sz,
                                                                             le64toh(o->field.hash), NULL, NULL);
                        else
                                r = journal_file_find_field_object(of, o->field.payload, sz, NULL, NULL);
                        if (r < 0)
                                return r;
                        if (r > 0) {
                                found = true;
                                break;
                        }
                }

                if (found)
                        continue;

                /* Check if this is really a valid string containing no NUL byte */
                if (memchr(o->field.payload, 0, sz))
                        return -EBADMSG;

                if (j->data_threshold > 0 && sz > j->data_threshold)
                        sz = j->data_threshold;

                if (!GREEDY_REALLOC(j->fields_buffer, sz + 1))
                        return -ENOMEM;

                memcpy(j->fields_buffer, o->field.payload, sz);
                j->fields_buffer[sz] = 0;

                if (!field_is_valid(j->fields_buffer))
                        return -EBADMSG;

                *field = j->fields_buffer;
                return 1;
        }
}

_public_ void sd_journal_restart_fields(sd_journal *j) {
        if (!j)
                return;

        j->fields_file = NULL;
        j->fields_hash_table_index = 0;
        j->fields_offset = 0;
        j->fields_file_lost = false;
}

_public_ int sd_journal_reliable_fd(sd_journal *j) {
        assert_return(j, -EINVAL);
        assert_return(!journal_pid_changed(j), -ECHILD);

        return !j->on_network;
}

static char *lookup_field(const char *field, void *userdata) {
        sd_journal *j = ASSERT_PTR(userdata);
        const void *data;
        size_t size, d;
        int r;

        assert(field);

        r = sd_journal_get_data(j, field, &data, &size);
        if (r < 0 ||
            size > REPLACE_VAR_MAX)
                return strdup(field);

        d = strlen(field) + 1;

        return strndup((const char*) data + d, size - d);
}

_public_ int sd_journal_get_catalog(sd_journal *j, char **ret) {
        const void *data;
        size_t size;
        sd_id128_t id;
        _cleanup_free_ char *text = NULL, *cid = NULL;
        char *t;
        int r;

        assert_return(j, -EINVAL);
        assert_return(!journal_pid_changed(j), -ECHILD);
        assert_return(ret, -EINVAL);

        r = sd_journal_get_data(j, "MESSAGE_ID", &data, &size);
        if (r < 0)
                return r;

        cid = strndup((const char*) data + 11, size - 11);
        if (!cid)
                return -ENOMEM;

        r = sd_id128_from_string(cid, &id);
        if (r < 0)
                return r;

        r = catalog_get(CATALOG_DATABASE, id, &text);
        if (r < 0)
                return r;

        t = replace_var(text, lookup_field, j);
        if (!t)
                return -ENOMEM;

        *ret = t;
        return 0;
}

_public_ int sd_journal_get_catalog_for_message_id(sd_id128_t id, char **ret) {
        assert_return(ret, -EINVAL);

        return catalog_get(CATALOG_DATABASE, id, ret);
}

_public_ int sd_journal_set_data_threshold(sd_journal *j, size_t sz) {
        assert_return(j, -EINVAL);
        assert_return(!journal_pid_changed(j), -ECHILD);

        j->data_threshold = sz;
        return 0;
}

_public_ int sd_journal_get_data_threshold(sd_journal *j, size_t *sz) {
        assert_return(j, -EINVAL);
        assert_return(!journal_pid_changed(j), -ECHILD);
        assert_return(sz, -EINVAL);

        *sz = j->data_threshold;
        return 0;
}

_public_ int sd_journal_has_runtime_files(sd_journal *j) {
        assert_return(j, -EINVAL);

        return j->has_runtime_files;
}

_public_ int sd_journal_has_persistent_files(sd_journal *j) {
        assert_return(j, -EINVAL);

        return j->has_persistent_files;
}