summaryrefslogtreecommitdiffstats
path: root/wiretap/file_wrappers.c
blob: f0c42b84aabfb66fd194b036b774fdfd149d7a75 (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
/* file_wrappers.c
 *
 * Wiretap Library
 * Copyright (c) 1998 by Gilbert Ramirez <gram@alumni.rice.edu>
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 */

/* file_access interface based heavily on zlib gzread.c and gzlib.c from zlib
 * Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler
 * under licence:
 *
 * SPDX-License-Identifier: Zlib
 *
 */

#include "config.h"

#define WS_LOG_DOMAIN LOG_DOMAIN_WIRETAP

#include "file_wrappers.h"

#include <assert.h>
#include <errno.h>
#include <string.h>
#include "wtap-int.h"

#include <wsutil/file_util.h>

#if defined(HAVE_ZLIB) && !defined(HAVE_ZLIBNG)
#define USE_ZLIB_OR_ZLIBNG
#define ZLIB_CONST
#define ZLIB_PREFIX(x) x
#include <zlib.h>
typedef z_stream zlib_stream;
#endif /* defined(HAVE_ZLIB) && !defined(HAVE_ZLIBNG) */

#ifdef HAVE_ZLIBNG
#define USE_ZLIB_OR_ZLIBNG
#define HAVE_INFLATEPRIME 1
#define ZLIB_PREFIX(x) zng_ ## x
#include <zlib-ng.h>
typedef zng_stream zlib_stream;
#endif /* HAVE_ZLIBNG */

#ifdef HAVE_ZSTD
#include <zstd.h>
#endif /* HAVE_ZSTD */

#ifdef HAVE_LZ4
#include <lz4.h>

#if LZ4_VERSION_NUMBER >= 10703
#define USE_LZ4
#include <lz4frame.h>
#ifndef LZ4F_BLOCK_HEADER_SIZE /* Added in LZ4_VERSION_NUMBER 10902 */
#define LZ4F_BLOCK_HEADER_SIZE 4
#endif /* LZ4F_BLOCK_HEADER_SIZE */
#endif /* LZ4_VERSION_NUMBER >= 10703 */
#endif /* HAVE_LZ4 */

/*
 * List of compression types supported.
 */
static struct compression_type {
    wtap_compression_type  type;
    const char            *extension;
    const char            *description;
    const char            *name;
    const bool            can_write_compressed;
} compression_types[] = {
#ifdef USE_ZLIB_OR_ZLIBNG
    { WTAP_GZIP_COMPRESSED, "gz", "gzip compressed", "gzip", true },
#endif /* USE_ZLIB_OR_ZLIBNG */
#ifdef HAVE_ZSTD
    { WTAP_ZSTD_COMPRESSED, "zst", "zstd compressed", "zstd", false },
#endif /* HAVE_ZSTD */
#ifdef USE_LZ4
    { WTAP_LZ4_COMPRESSED, "lz4", "lz4 compressed", "lz4", true },
#endif /* USE_LZ4 */
    { WTAP_UNCOMPRESSED, NULL, NULL, "none", true },
    { WTAP_UNKNOWN_COMPRESSION, NULL, NULL, NULL, false },
};

static wtap_compression_type file_get_compression_type(FILE_T stream);

wtap_compression_type
wtap_name_to_compression_type(const char *name)
{
    for (struct compression_type *p = compression_types;
	    p->type != WTAP_UNKNOWN_COMPRESSION; p++) {
		if (!g_strcmp0(name, p->name))
			return p->type;
	}
    return WTAP_UNKNOWN_COMPRESSION;
}

wtap_compression_type
wtap_extension_to_compression_type(const char *ext)
{
    for (struct compression_type *p = compression_types;
	    p->type != WTAP_UNKNOWN_COMPRESSION; p++) {
		if (!g_strcmp0(ext, p->extension))
			return p->type;
	}
    return WTAP_UNKNOWN_COMPRESSION;
}

bool
wtap_can_write_compression_type(wtap_compression_type compression_type)
{
    for (struct compression_type *p = compression_types; p->type != WTAP_UNKNOWN_COMPRESSION; p++) {
		if (compression_type == p->type)
			return p->can_write_compressed;
	}

    return false;
}

wtap_compression_type
wtap_get_compression_type(wtap *wth)
{
	return file_get_compression_type((wth->fh == NULL) ? wth->random_fh : wth->fh);
}

const char *
wtap_compression_type_description(wtap_compression_type compression_type)
{
	for (struct compression_type *p = compression_types;
	    p->type != WTAP_UNCOMPRESSED; p++) {
		if (p->type == compression_type)
			return p->description;
	}
	return NULL;
}

const char *
wtap_compression_type_extension(wtap_compression_type compression_type)
{
	for (struct compression_type *p = compression_types;
	    p->type != WTAP_UNCOMPRESSED; p++) {
		if (p->type == compression_type)
			return p->extension;
	}
	return NULL;
}

GSList *
wtap_get_all_compression_type_extensions_list(void)
{
	GSList *extensions;

	extensions = NULL;	/* empty list, to start with */

	for (struct compression_type *p = compression_types;
	    p->type != WTAP_UNCOMPRESSED; p++)
		extensions = g_slist_prepend(extensions, (void *)p->extension);

	return extensions;
}

GSList *
wtap_get_all_output_compression_type_names_list(void)
{
	GSList *names;

	names = NULL;	/* empty list, to start with */

	for (struct compression_type *p = compression_types;
	    p->type != WTAP_UNCOMPRESSED; p++) {
            if (p->can_write_compressed)
                names = g_slist_prepend(names, (void *)p->name);
        }

	return names;
}

/* #define GZBUFSIZE 8192 */
#define GZBUFSIZE 4096
#define LZ4BUFSIZE 4194304 // 4MiB, maximum block size

/* values for wtap_reader compression */
typedef enum {
    UNKNOWN,       /* unknown - look for a compression header */
    UNCOMPRESSED,  /* uncompressed - copy input directly */
    ZLIB,          /* decompress a zlib stream */
    GZIP_AFTER_HEADER,
    ZSTD,
    LZ4,
} compression_t;

/*
 * We limit the size of our input and output buffers to 2^30 bytes,
 * because:
 *
 *    1) on Windows with MSVC, the return value of _read() is int,
 *       so the biggest read you can do is INT_MAX, and the biggest
 *       power of 2 below that is 2^30;
 *
 *    2) the "avail_in" and "avail_out" values in a z_stream structure
 *       in zlib are uInts, and those are unsigned ints, and that
 *       imposes a limit on the buffer size when we're reading a
 *       gzipped file.
 *
 * Thus, we use unsigned for the buffer sizes, offsets, amount available
 * from the buffer, etc.
 *
 * If we want an even bigger buffer for uncompressed data, or for
 * some other form of compression, then the unsigned-sized values should
 * be in structure values used only for reading gzipped files, and
 * other values should be used for uncompressed data or data
 * compressed using other algorithms (e.g., in a union).
 */
#define MAX_READ_BUF_SIZE	(1U << 30)

struct wtap_reader_buf {
    uint8_t *buf;  /* buffer */
    uint8_t *next; /* next byte to deliver from buffer */
    unsigned avail;  /* number of bytes available to deliver at next */
};

struct wtap_reader {
    int fd;                     /* file descriptor */
    int64_t raw_pos;            /* current position in file (just to not call lseek()) */
    int64_t pos;                /* current position in uncompressed data */
    unsigned size;              /* buffer size */

    struct wtap_reader_buf in;  /* input buffer, containing compressed data */
    struct wtap_reader_buf out; /* output buffer, containing uncompressed data */

    bool eof;                   /* true if end of input file reached */
    int64_t start;              /* where the gzip data started, for rewinding */
    int64_t raw;                /* where the raw data started, for seeking */
    compression_t compression;  /* type of compression, if any */
    compression_t last_compression; /* last known compression type */
    bool is_compressed;         /* false if completely uncompressed, true otherwise */

    /* seek request */
    int64_t skip;               /* amount to skip (already rewound if backwards) */
    bool seek_pending;          /* true if seek request pending */

    /* error information */
    int err;                    /* error code */
    const char *err_info;       /* additional error information string for some errors */

    /*
     * Decompression stream information.
     *
     * XXX - should this be a union?
     */
#ifdef USE_ZLIB_OR_ZLIBNG
    /* zlib inflate stream */
    zlib_stream strm;           /* stream structure in-place (not a pointer) */
    bool dont_check_crc;        /* true if we aren't supposed to check the CRC */
#endif /* USE_ZLIB_OR_ZLIBNG */
#ifdef HAVE_ZSTD
    ZSTD_DCtx *zstd_dctx;
#endif /* HAVE_ZSTD */
#ifdef USE_LZ4
    LZ4F_dctx *lz4_dctx;
    LZ4F_frameInfo_t lz4_info;
    unsigned char lz4_hdr[LZ4F_HEADER_SIZE_MAX];
#endif /* USE_LZ4 */

    /* fast seeking */
    GPtrArray *fast_seek;
    void *fast_seek_cur;
};

/* Current read offset within a buffer. */
static unsigned
offset_in_buffer(struct wtap_reader_buf *buf)
{
    /* buf->next points to the next byte to read, and buf->buf points
       to the first byte in the buffer, so the difference between them
       is the offset.

       This will fit in an unsigned int, because it can't be bigger
       than the size of the buffer, which is an unsigned int. */
    return (unsigned)(buf->next - buf->buf);
}

/* Number of bytes of data that are in a buffer. */
static unsigned
bytes_in_buffer(struct wtap_reader_buf *buf)
{
    /* buf->next + buf->avail points just past the last byte of data in
       the buffer.
       Thus, (buf->next + buf->avail) - buf->buf is the number of bytes
       of data in the buffer.

       This will fit in an unsigned, because it can't be bigger
       than the size of the buffer, which is a unsigned. */
    return (unsigned)((buf->next + buf->avail) - buf->buf);
}

/* Reset a buffer, discarding all data in the buffer, so we read into
   it starting at the beginning. */
static void
buf_reset(struct wtap_reader_buf *buf)
{
    buf->next = buf->buf;
    buf->avail = 0;
}

static int
buf_read(FILE_T state, struct wtap_reader_buf *buf)
{
    unsigned space_left, to_read;
    unsigned char *read_ptr;
    ssize_t ret;

    /* How much space is left at the end of the buffer?
       XXX - the output buffer actually has state->size * 2 bytes. */
    space_left = state->size - bytes_in_buffer(buf);
    if (space_left == 0) {
        /* There's no space left, so we start fresh at the beginning
           of the buffer. */
        buf_reset(buf);

        read_ptr = buf->buf;
        to_read = state->size;
    } else {
        /* There's some space left; try to read as much data as we
           can into that space.  We may get less than that if we're
           reading from a pipe or if we're near the end of the file. */
        read_ptr = buf->next + buf->avail;
        to_read = space_left;
    }

    ret = ws_read(state->fd, read_ptr, to_read);
    if (ret < 0) {
        state->err = errno;
        state->err_info = NULL;
        return -1;
    }
    if (ret == 0)
        state->eof = true;
    state->raw_pos += ret;
    buf->avail += (unsigned)ret;
    return 0;
}

static int /* gz_avail */
fill_in_buffer(FILE_T state)
{
    if (state->err != 0)
        return -1;
    if (!state->eof) {
        if (buf_read(state, &state->in) < 0)
            return -1;
    }
    return 0;
}

#define ZLIB_WINSIZE 32768
#define  LZ4_WINSIZE 65536

struct fast_seek_point {
    int64_t out;         /* corresponding offset in uncompressed data */
    int64_t in;          /* offset in input file of first full byte */

    compression_t compression;
    union {
        struct {
#ifdef HAVE_INFLATEPRIME
            int bits;   /* number of bits (1-7) from byte at in - 1, or 0 */
#endif /* HAVE_INFLATEPRIME */
            unsigned char window[ZLIB_WINSIZE]; /* preceding 32K of uncompressed data */

            /* be gentle with Z_STREAM_END, 8 bytes more... Another solution would be to comment checks out */
            uint32_t adler;
            uint32_t total_out;
        } zlib;
#ifdef USE_LZ4
        struct {
            LZ4F_frameInfo_t lz4_info;
            unsigned char lz4_hdr[LZ4F_HEADER_SIZE_MAX];
#if 0
            unsigned char window[LZ4_WINSIZE]; /* preceding 64K of uncompressed data */
#endif
        } lz4;
#endif
    } data;
};

struct zlib_cur_seek_point {
    unsigned char window[ZLIB_WINSIZE]; /* preceding 32K of uncompressed data */
    unsigned int pos;
    unsigned int have;
};

#define SPAN INT64_C(1048576)
static struct fast_seek_point *
fast_seek_find(FILE_T file, int64_t pos)
{
    struct fast_seek_point *smallest = NULL;
    struct fast_seek_point *item;
    unsigned low, i, max;

    if (!file->fast_seek)
        return NULL;

    for (low = 0, max = file->fast_seek->len; low < max; ) {
        i = (low + max) / 2;
        item = (struct fast_seek_point *)file->fast_seek->pdata[i];

        if (pos < item->out)
            max = i;
        else if (pos > item->out) {
            smallest = item;
            low = i + 1;
        } else {
            return item;
        }
    }
    return smallest;
}

static void
fast_seek_header(FILE_T file, int64_t in_pos, int64_t out_pos,
                 compression_t compression)
{
    struct fast_seek_point *item = NULL;

    if (!file->fast_seek) {
        return;
    }

    if (file->fast_seek->len != 0)
        item = (struct fast_seek_point *)file->fast_seek->pdata[file->fast_seek->len - 1];

    /* fast_seek_header always adds a fast seek point, even if less than
     * SPAN from the last one. That is because it used for new streams
     * (including concatenated streams) where the compression type
     * or, for LZ4, compression options, may change.
     */
    if (!item || item->out < out_pos) {
        struct fast_seek_point *val = g_new(struct fast_seek_point,1);
        val->in = in_pos;
        val->out = out_pos;
        val->compression = compression;

#ifdef USE_LZ4
        if (compression == LZ4) {
            val->data.lz4.lz4_info = file->lz4_info;
            memcpy(val->data.lz4.lz4_hdr, file->lz4_hdr, LZ4F_HEADER_SIZE_MAX);
        }
#endif /* USE_LZ4 */
        g_ptr_array_add(file->fast_seek, val);
    }
}

static void
fast_seek_reset(FILE_T state)
{
    switch (state->compression) {

    case UNKNOWN:
        break;

    case UNCOMPRESSED:
        /* Nothing to do */
        break;

    case ZLIB:
#ifdef USE_ZLIB_OR_ZLIBNG
        if (state->fast_seek_cur != NULL) {
            struct zlib_cur_seek_point *cur = (struct zlib_cur_seek_point *) state->fast_seek_cur;

            cur->have = 0;
        }
#else
        /* This "cannot happen" */
        ws_assert_not_reached();
#endif /* USE_ZLIB_OR_ZLIBNG */
        break;

    case GZIP_AFTER_HEADER:
        break;

    case ZSTD:
#ifdef HAVE_ZSTD
        /* Anything to do? */
#else
        /* This "cannot happen" */
        ws_assert_not_reached();
#endif /* HAVE_ZSTD */
        break;

    case LZ4:
#ifdef HAVE_LZ4
        /* Anything to do? */
#else
        /* This "cannot happen" */
        ws_assert_not_reached();
#endif /* HAVE_LZ4 */
        break;

    /* Add other compression types here */

    default:
        /* This "cannot happen" */
        ws_assert_not_reached();
        break;
    }
}

static bool
uncompressed_fill_out_buffer(FILE_T state)
{
    if (buf_read(state, &state->out) < 0)
        return false;
    return true;
}

/* Get next byte from input, or -1 if end or error.
 *
 * Note:
 *
 *      1) errors from buf_read(), and thus from fill_in_buffer(), are
 *      "sticky", and fill_in_buffer() won't do any reading if there's
 *      an error;
 *
 *      2) GZ_GETC() returns -1 on an EOF;
 *
 * so it's safe to make multiple GZ_GETC() calls and only check the
 * last one for an error. */
#define GZ_GETC() ((state->in.avail == 0 && fill_in_buffer(state) == -1) ? -1 : \
                   (state->in.avail == 0 ? -1 :                         \
                    (state->in.avail--, *(state->in.next)++)))


/*
 * Gzipped files, using compression from zlib or zlib-ng.
 *
 * https://tools.ietf.org/html/rfc1952 (RFC 1952)
 */
#ifdef USE_ZLIB_OR_ZLIBNG

/* Get a one-byte integer and return 0 on success and the value in *ret.
   Otherwise -1 is returned, state->err is set, and *ret is not modified. */
static int
gz_next1(FILE_T state, uint8_t *ret)
{
    int ch;

    ch = GZ_GETC();
    if (ch == -1) {
        if (state->err == 0) {
            /* EOF */
            state->err = WTAP_ERR_SHORT_READ;
            state->err_info = NULL;
        }
        return -1;
    }
    *ret = ch;
    return 0;
}

/* Get a two-byte little-endian integer and return 0 on success and the value
   in *ret.  Otherwise -1 is returned, state->err is set, and *ret is not
   modified. */
static int
gz_next2(FILE_T state, uint16_t *ret)
{
    uint16_t val;
    int ch;

    val = GZ_GETC();
    ch = GZ_GETC();
    if (ch == -1) {
        if (state->err == 0) {
            /* EOF */
            state->err = WTAP_ERR_SHORT_READ;
            state->err_info = NULL;
        }
        return -1;
    }
    val += (uint16_t)ch << 8;
    *ret = val;
    return 0;
}

/* Get a four-byte little-endian integer and return 0 on success and the value
   in *ret.  Otherwise -1 is returned, state->err is set, and *ret is not
   modified. */
static int
gz_next4(FILE_T state, uint32_t *ret)
{
    uint32_t val;
    int ch;

    val = GZ_GETC();
    val += (unsigned)GZ_GETC() << 8;
    val += (uint32_t)GZ_GETC() << 16;
    ch = GZ_GETC();
    if (ch == -1) {
        if (state->err == 0) {
            /* EOF */
            state->err = WTAP_ERR_SHORT_READ;
            state->err_info = NULL;
        }
        return -1;
    }
    val += (uint32_t)ch << 24;
    *ret = val;
    return 0;
}

/* Skip the specified number of bytes and return 0 on success.  Otherwise -1
   is returned. */
static int
gz_skipn(FILE_T state, size_t n)
{
    while (n != 0) {
        if (GZ_GETC() == -1) {
            if (state->err == 0) {
                /* EOF */
                state->err = WTAP_ERR_SHORT_READ;
                state->err_info = NULL;
            }
            return -1;
        }
        n--;
    }
    return 0;
}

/* Skip a null-terminated string and return 0 on success.  Otherwise -1
   is returned. */
static int
gz_skipzstr(FILE_T state)
{
    int ch;

    /* It's null-terminated, so scan until we read a byte with
       the value 0 or get an error. */
    while ((ch = GZ_GETC()) > 0)
        ;
    if (ch == -1) {
        if (state->err == 0) {
            /* EOF */
            state->err = WTAP_ERR_SHORT_READ;
            state->err_info = NULL;
        }
        return -1;
    }
    return 0;
}

static void
zlib_fast_seek_add(FILE_T file, struct zlib_cur_seek_point *point, int bits, int64_t in_pos, int64_t out_pos)
{
    /* it's for sure after gzip header, so file->fast_seek->len != 0 */
    struct fast_seek_point *item = (struct fast_seek_point *)file->fast_seek->pdata[file->fast_seek->len - 1];

#ifndef HAVE_INFLATEPRIME
    if (bits)
        return;
#endif /* HAVE_INFLATEPRIME */

    /* Glib has got Balanced Binary Trees (GTree) but I couldn't find a way to do quick search for nearest (and smaller) value to seek (It's what fast_seek_find() do)
     *      Inserting value in middle of sorted array is expensive, so we want to add only in the end.
     *      It's not big deal, cause first-read don't usually invoke seeking
     */
    if (item->out + SPAN < out_pos) {
        struct fast_seek_point *val = g_new(struct fast_seek_point,1);
        val->in = in_pos;
        val->out = out_pos;
        val->compression = ZLIB;
#ifdef HAVE_INFLATEPRIME
        val->data.zlib.bits = bits;
#endif /* HAVE_INFLATEPRIME */
        if (point->pos != 0) {
            unsigned int left = ZLIB_WINSIZE - point->pos;

            memcpy(val->data.zlib.window, point->window + point->pos, left);
            memcpy(val->data.zlib.window + left, point->window, point->pos);
        } else
            memcpy(val->data.zlib.window, point->window, ZLIB_WINSIZE);

        /*
         * XXX - strm.adler is a uLong in at least some versions
         * of zlib, and uLong is an unsigned long in at least
         * some of those versions, which means it's 64-bit
         * on LP64 platforms, even though the checksum is
         * 32-bit.  We assume the actual Adler checksum
         * is in the lower 32 bits of strm.adler; as the
         * checksum in the file is only 32 bits, we save only
         * those lower 32 bits, and cast away any additional
         * bits to squelch warnings.
         *
         * The same applies to strm.total_out.
         */
        val->data.zlib.adler = (uint32_t) file->strm.adler;
        val->data.zlib.total_out = (uint32_t) file->strm.total_out;
        g_ptr_array_add(file->fast_seek, val);
    }
}

/*
 * Based on what gz_decomp() in zlib does.
 */
static void
zlib_fill_out_buffer(FILE_T state)
{
    int ret = 0;        /* XXX */
    uint32_t crc, len;
#ifdef HAVE_ZLIBNG
    zng_streamp strm = &(state->strm);
#else /* HAVE_ZLIBNG */
    z_streamp strm = &(state->strm);
#endif /* HAVE_ZLIBNG */
    unsigned char *buf = state->out.buf;
    unsigned int count = state->size << 1;

    unsigned char *buf2 = buf;
    unsigned int count2 = count;

    strm->avail_out = count;
    strm->next_out = buf;

    /* fill output buffer up to end of deflate stream or error */
    do {
        /* get more input for inflate() */
        if (state->in.avail == 0 && fill_in_buffer(state) == -1)
            break;
        if (state->in.avail == 0) {
            /* EOF */
            state->err = WTAP_ERR_SHORT_READ;
            state->err_info = NULL;
            break;
        }

        strm->avail_in = state->in.avail;
        strm->next_in = state->in.next;
        /* decompress and handle errors */
#ifdef Z_BLOCK
        ret = ZLIB_PREFIX(inflate)(strm, Z_BLOCK);
#else /* Z_BLOCK */
        ret = ZLIB_PREFIX(inflate)(strm, Z_NO_FLUSH);
#endif /* Z_BLOCK */
        state->in.avail = strm->avail_in;
#ifdef z_const
DIAG_OFF(cast-qual)
        state->in.next = (unsigned char *)strm->next_in;
DIAG_ON(cast-qual)
#else /* z_const */
        state->in.next = strm->next_in;
#endif /* z_const */
        if (ret == Z_STREAM_ERROR) {
            state->err = WTAP_ERR_DECOMPRESS;
            state->err_info = strm->msg;
            break;
        }
        if (ret == Z_NEED_DICT) {
            state->err = WTAP_ERR_DECOMPRESS;
            state->err_info = "preset dictionary needed";
            break;
        }
        if (ret == Z_MEM_ERROR) {
            /* This means "not enough memory". */
            state->err = ENOMEM;
            state->err_info = NULL;
            break;
        }
        if (ret == Z_DATA_ERROR) {              /* deflate stream invalid */
            state->err = WTAP_ERR_DECOMPRESS;
            state->err_info = strm->msg;
            break;
        }
        /*
         * XXX - Z_BUF_ERROR?
         */

        strm->adler = ZLIB_PREFIX(crc32)(strm->adler, buf2, count2 - strm->avail_out);
#ifdef Z_BLOCK
        if (state->fast_seek_cur != NULL) {
            struct zlib_cur_seek_point *cur = (struct zlib_cur_seek_point *) state->fast_seek_cur;
            unsigned int ready = count2 - strm->avail_out;

            if (ready < ZLIB_WINSIZE) {
                unsigned left = ZLIB_WINSIZE - cur->pos;

                if (ready >= left) {
                    memcpy(cur->window + cur->pos, buf2, left);
                    if (ready != left)
                        memcpy(cur->window, buf2 + left, ready - left);

                    cur->pos = ready - left;
                    cur->have += ready;
                } else {
                    memcpy(cur->window + cur->pos, buf2, ready);
                    cur->pos += ready;
                    cur->have += ready;
                }

                if (cur->have >= ZLIB_WINSIZE)
                    cur->have = ZLIB_WINSIZE;

            } else {
                memcpy(cur->window, buf2 + (ready - ZLIB_WINSIZE), ZLIB_WINSIZE);
                cur->pos = 0;
                cur->have = ZLIB_WINSIZE;
            }

            if (cur->have >= ZLIB_WINSIZE && ret != Z_STREAM_END && (strm->data_type & 128) && !(strm->data_type & 64))
                zlib_fast_seek_add(state, cur, (strm->data_type & 7), state->raw_pos - strm->avail_in, state->pos + (count - strm->avail_out));
        }
#endif /* Z_BLOCK */
        buf2 = (buf2 + count2 - strm->avail_out);
        count2 = strm->avail_out;

    } while (strm->avail_out && ret != Z_STREAM_END);

    /* update available output and crc check value */
    state->out.next = buf;
    state->out.avail = count - strm->avail_out;

    /* Check gzip trailer if at end of deflate stream.
       We don't fail immediately here, we just set an error
       indication, so that we try to process what data we
       got before the error.  The next attempt to read
       something past that data will get the error. */
    if (ret == Z_STREAM_END) {
        if (gz_next4(state, &crc) != -1 &&
            gz_next4(state, &len) != -1) {
            if (crc != strm->adler && !state->dont_check_crc) {
                state->err = WTAP_ERR_DECOMPRESS;
                state->err_info = "bad CRC";
            } else if (len != (strm->total_out & 0xffffffffUL)) {
                state->err = WTAP_ERR_DECOMPRESS;
                state->err_info = "length field wrong";
            }
        }
        state->last_compression = state->compression;
        state->compression = UNKNOWN;      /* ready for next stream, once have is 0 */
        g_free(state->fast_seek_cur);
        state->fast_seek_cur = NULL;
    }
}
#endif /* USE_ZLIB_OR_ZLIBNG */

/*
 * Check for a gzip header.
 *
 * Based on the gzip-specific stuff gz_head() from zlib does.
 */
static int
check_for_zlib_compression(FILE_T state)
{
    /*
     * Look for the gzip header.  The first two bytes are 31 and 139,
     * and if we find it, return success if we support gzip and an
     * error if we don't.
     */
    if (state->in.next[0] == 31) {
        state->in.avail--;
        state->in.next++;

        /* Make sure the byte after the first byte is present */
        if (state->in.avail == 0 && fill_in_buffer(state) == -1) {
            /* Read error. */
            return -1;
        }
        if (state->in.avail != 0) {
            if (state->in.next[0] == 139) {
                /*
                 * We have what looks like the ID1 and ID2 bytes of a gzip
                 * header.
                 * Continue processing the file.
                 *
                 * XXX - some capture file formats (I'M LOOKING AT YOU,
                 * ENDACE!) can have 31 in the first byte of the file
                 * and 139 in the second byte of the file.  For now, in
                 * those cases, you lose.
                 */
#ifdef USE_ZLIB_OR_ZLIBNG
                uint8_t cm;
                uint8_t flags;
                uint16_t len;
                uint16_t hcrc;

                state->in.avail--;
                state->in.next++;

                /* read rest of header */

                /* compression method (CM) */
                if (gz_next1(state, &cm) == -1)
                    return -1;
                if (cm != 8) {
                    state->err = WTAP_ERR_DECOMPRESS;
                    state->err_info = "unknown compression method";
                    return -1;
                }

                /* flags (FLG) */
                if (gz_next1(state, &flags) == -1) {
                    /* Read error. */
                    return -1;
                }
                if (flags & 0xe0) {     /* reserved flag bits */
                    state->err = WTAP_ERR_DECOMPRESS;
                    state->err_info = "reserved flag bits set";
                    return -1;
                }

                /* modification time (MTIME) */
                if (gz_skipn(state, 4) == -1) {
                    /* Read error. */
                    return -1;
                }

                /* extra flags (XFL) */
                if (gz_skipn(state, 1) == -1) {
                    /* Read error. */
                    return -1;
                }

                /* operating system (OS) */
                if (gz_skipn(state, 1) == -1) {
                    /* Read error. */
                    return -1;
                }

                if (flags & 4) {
                    /* extra field - get XLEN */
                    if (gz_next2(state, &len) == -1) {
                        /* Read error. */
                        return -1;
                    }

                    /* skip the extra field */
                    if (gz_skipn(state, len) == -1) {
                        /* Read error. */
                        return -1;
                    }
                }
                if (flags & 8) {
                    /* file name */
                    if (gz_skipzstr(state) == -1) {
                        /* Read error. */
                        return -1;
                    }
                }
                if (flags & 16) {
                    /* comment */
                    if (gz_skipzstr(state) == -1) {
                        /* Read error. */
                        return -1;
                    }
                }
                if (flags & 2) {
                    /* header crc */
                    if (gz_next2(state, &hcrc) == -1) {
                        /* Read error. */
                        return -1;
                    }
                    /* XXX - check the CRC? */
                }

                /* set up for decompression */
                ZLIB_PREFIX(inflateReset)(&(state->strm));
                state->strm.adler = ZLIB_PREFIX(crc32)(0L, Z_NULL, 0);
                state->compression = ZLIB;
                state->is_compressed = true;
#ifdef Z_BLOCK
                if (state->fast_seek) {
                    struct zlib_cur_seek_point *cur = g_new(struct zlib_cur_seek_point,1);

                    cur->pos = cur->have = 0;
                    g_free(state->fast_seek_cur);
                    state->fast_seek_cur = cur;
                    fast_seek_header(state, state->raw_pos - state->in.avail, state->pos, GZIP_AFTER_HEADER);
                }
#endif /* Z_BLOCK */
                return 1;
#else /* USE_ZLIB_OR_ZLIBNG */
                state->err = WTAP_ERR_DECOMPRESSION_NOT_SUPPORTED;
                state->err_info = "reading gzip-compressed files isn't supported";
                return -1;
#endif /* USE_ZLIB_OR_ZLIBNG */
            }

            /*
             * Not a gzip file.  "Unget" the first character; either:
             *
             *    1) we read both of the first two bytes into the
             *    buffer with the first ws_read, so we can just back
             *    up by one byte;
             *
             *    2) we only read the first byte into the buffer with
             *    the first ws_read (e.g., because we're reading from
             *    a pipe and only the first byte had been written to
             *    the pipe at that point), and read the second byte
             *    into the buffer after the first byte in the
             *    fill_in_buffer call, so we now have two bytes in
             *    the buffer, and can just back up by one byte.
             */
            state->in.avail++;
            state->in.next--;
        }
    }
    return 0;
}


/*
 * Zstandard compression.
 *
 * https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md
 */
#ifdef HAVE_ZSTD
static bool
zstd_fill_out_buffer(FILE_T state)
{
    ws_assert(state->out.avail == 0);

    if (state->in.avail == 0 && fill_in_buffer(state) == -1)
        return false;

    ZSTD_outBuffer output = {state->out.buf, state->size << 1, 0};
    ZSTD_inBuffer input = {state->in.next, state->in.avail, 0};
    const size_t ret = ZSTD_decompressStream(state->zstd_dctx, &output, &input);
    if (ZSTD_isError(ret)) {
        state->err = WTAP_ERR_DECOMPRESS;
        state->err_info = ZSTD_getErrorName(ret);
        return false;
    }

    state->in.next = state->in.next + input.pos;
    state->in.avail -= (unsigned)input.pos;

    state->out.next = output.dst;
    state->out.avail = (unsigned)output.pos;

    if (ret == 0) {
        state->last_compression = state->compression;
        state->compression = UNKNOWN;
    }
    return true;
}
#endif /* HAVE_ZSTD */

/*
 * Check for a Zstandard header.
 */
static int
check_for_zstd_compression(FILE_T state)
{
    /*
     * Look for the Zstandard header, and, if we find it, return
     * success if we support Zstandard and an error if we don't.
     */
    if (state->in.avail >= 4
        && state->in.next[0] == 0x28 && state->in.next[1] == 0xb5
        && state->in.next[2] == 0x2f && state->in.next[3] == 0xfd) {
#ifdef HAVE_ZSTD
        const size_t ret = ZSTD_initDStream(state->zstd_dctx);
        if (ZSTD_isError(ret)) {
            state->err = WTAP_ERR_DECOMPRESS;
            state->err_info = ZSTD_getErrorName(ret);
            return -1;
        }

        fast_seek_header(state, state->raw_pos - state->in.avail, state->pos, ZSTD);
        state->compression = ZSTD;
        state->is_compressed = true;
        return 1;
#else /* HAVE_ZSTD */
        state->err = WTAP_ERR_DECOMPRESSION_NOT_SUPPORTED;
        state->err_info = "reading zstd-compressed files isn't supported";
        return -1;
#endif /* HAVE_ZSTD */
    }
    return 0;
}

/*
 * lz4 compression.
 *
 * https://github.com/lz4/lz4/blob/dev/doc/lz4_Frame_format.md
 */
#ifdef USE_LZ4
static void
lz4_fast_seek_add(FILE_T file, struct zlib_cur_seek_point *point _U_, int64_t in_pos, int64_t out_pos)
{
    if (!file->fast_seek) {
        return;
    }

    struct fast_seek_point *item = NULL;

    if (file->fast_seek->len != 0)
        item = (struct fast_seek_point *)file->fast_seek->pdata[file->fast_seek->len - 1];

    /* As of Glib 2.68 GTree has g_tree_upper_bound, or we could use a
     * wmem_tree. However, since our initial read is usually sequential
     * only adding seek points at the end of the ptr array is fast and fine.
     */

    /* don't bother adding jump points between very small blocks (min SPAN) */
    if (!item || item->out + SPAN < out_pos) {
        struct fast_seek_point *val = g_new(struct fast_seek_point,1);
        val->in = in_pos;
        val->out = out_pos;
        val->compression = LZ4;
#if 0
        if (point->pos != 0) {
            unsigned int left = LZ4_WINSIZE - point->pos;

            memcpy(val->data.zlib.window, point->window + point->pos, left);
            memcpy(val->data.zlib.window + left, point->window, point->pos);
        } else
            memcpy(val->data.zlib.window, point->window, ZZ4_WINSIZE);
#endif

        val->data.lz4.lz4_info = file->lz4_info;
        memcpy(val->data.lz4.lz4_hdr, file->lz4_hdr, LZ4F_HEADER_SIZE_MAX);
        g_ptr_array_add(file->fast_seek, val);
    }
}

static bool
lz4_fill_out_buffer(FILE_T state)
{
    ws_assert(state->out.avail == 0);

    if (state->in.avail == 0 && fill_in_buffer(state) == -1)
        return false;

    /*
     * We should be at the start of a block. First, determine the size of
     * the block. We tell LZ4F_decompress that there's no room to put
     * the decompressed block; this will make it read the block size
     * header and stop, returning the size of the block (plus next
     * header) as hint of how much input to hand next.
     */

    size_t outBufSize = 0; // Zero so we don't actually consume the block
    size_t inBufSize;

    size_t compressedSize = 0;

    do {
        /* get more input for decompress() */
        if (state->in.avail == 0 && fill_in_buffer(state) == -1)
            break;
        if (state->eof) {
            state->err = WTAP_ERR_SHORT_READ;
            state->err_info = NULL;
            break;
        }

        inBufSize = state->in.avail;
        compressedSize = LZ4F_decompress(state->lz4_dctx, state->out.buf, &outBufSize, state->in.next, &inBufSize, NULL);

        if (LZ4F_isError(compressedSize)) {
            state->err = WTAP_ERR_DECOMPRESS;
            state->err_info = LZ4F_getErrorName(compressedSize);
            return false;
        }

        state->in.next  += inBufSize;
        state->in.avail -= inBufSize;

        if (compressedSize == 0) {
            /* End of Frame */
            state->last_compression = state->compression;
            state->compression = UNKNOWN;
            return true;
        }

        ws_assert(outBufSize == 0);

    } while (compressedSize < LZ4F_BLOCK_HEADER_SIZE);

    /*
     * We don't want to add a fast seek point for the end of frame,
     * especially if there's another frame or other stream after it,
     * which would have the same out position. So add it after the
     * reading the block size - but point to where the block size
     * is so that we'll fast seek to the block size again.
     */
    if (state->lz4_info.blockMode == LZ4F_blockIndependent) {
        /*
         * XXX - If state->lz4_info.blockMode == LZ4F_blockLinked, it doesn't
         * seem like the LZ4 Frame API can handle this, we would need to use
         * the low level Block API and pass the last 64KiB window of data to
         * LZ4_setStreamDecode and use LZ4_decompress_safe_continue (similar
         * to gzip). So for now we can't do fast seek with it (we do add one
         * header at the frame beginning so that concatenated frames and other
         * decompression streams work.)
         */
        lz4_fast_seek_add(state, NULL, state->raw_pos - state->in.avail - LZ4F_BLOCK_HEADER_SIZE, state->pos);
    }

    // Now actually read the entire next block - but not the next header
    compressedSize -= LZ4F_BLOCK_HEADER_SIZE;
    state->out.next = state->out.buf;

    if (compressedSize > state->size) {
        /*
         * What is this? Either bogus, or some new variant of LZ4 Frames with
         * a larger block size we don't support. We could have a buffer
         * overrun if we try to process it.
         *
         * TODO - We could realloc here.
         */
        state->err = WTAP_ERR_DECOMPRESSION_NOT_SUPPORTED;
        state->err_info = "lz4 compressed block size too large";
        return false;
    }

    size_t ret;
    do {
        /* get more input for decompress() */
        if (state->in.avail == 0 && fill_in_buffer(state) == -1)
            break;
        if (state->eof) {
            state->err = WTAP_ERR_SHORT_READ;
            state->err_info = NULL;
            break;
        }

        outBufSize = (state->size << 1) - offset_in_buffer(&state->out);
        inBufSize = MIN(state->in.avail, compressedSize);
        ret = LZ4F_decompress(state->lz4_dctx, state->out.next, &outBufSize, state->in.next, &inBufSize, NULL);

        if (LZ4F_isError(ret)) {
            state->err = WTAP_ERR_DECOMPRESS;
            state->err_info = LZ4F_getErrorName(ret);
            return false;
        }
        state->in.next  += inBufSize;
        state->in.avail -= inBufSize;
        compressedSize -= inBufSize;

        state->out.next += outBufSize;
        state->out.avail += outBufSize;
    } while (compressedSize != 0);

    state->out.next  = state->out.buf;

#if 0
    /* This is an alternative implementation using the lower-level
     * LZ4 Block API. Doing something like this might be necessary
     * to handle linked blocks, because the Frame API doesn't have
     * a method to reset the dictionary / window.
     */
    int outBufSize = state->size << 1;
    uint32_t compressedSize;
    if (gz_next4(state, &compressedSize) == -1) {
        return false;
    }
    if (compressedSize == 0) {
        /* EndMark */
        if (state->lz4_info.contentChecksumFlag) {
            uint32_t xxHash;
            if (gz_next4(state, &xxHash) == -1) {
                return false;
            }
            /* XXX - check hash? */
        }
        state->last_compression = state->compression;
        state->compression = UNKNOWN;
        return true;
    }
    bool uncompressed = compressedSize >> 31;
    compressedSize &= 0x7FFFFFFF;
    if (compressedSize > state->size) {
        // TODO - we could realloc here
        state->err = WTAP_ERR_DECOMPRESSION_NOT_SUPPORTED;
        state->err_info = "lz4 compressed block size too large";
        return false;
    }

    /*
     * We have to read an entire block as we're using the low-level
     * Block API instead of the LZ4 Frame API.
     */
    if (compressedSize > (unsigned)state->in.avail) {
        memmove(state->in.buf, state->in.next, state->in.avail);
        state->in.next = state->in.buf;
        while ((unsigned)state->in.avail < compressedSize) {
            if (state->eof) {
                state->err = WTAP_ERR_SHORT_READ;
                state->err_info = NULL;
                return false;
            }
            if (fill_in_buffer(state) == -1) {
                return false;
            }
        }
    }

    int decompressedSize;
    if (uncompressed) {
        memcpy(state->out.buf, state->in.buf, compressedSize);
        decompressedSize = compressedSize;
    } else {
        decompressedSize = LZ4_decompress_safe(state->in.next, state->out.buf, compressedSize, outBufSize);
        //const size_t ret = LZ4F_decompress(state->lz4_dctx, state->out.buf, &outBufSize, state->in.next, &inBufSize, NULL);
        if (LZ4F_isError(decompressedSize)) {
            state->err = WTAP_ERR_DECOMPRESS;
            state->err_info = LZ4F_getErrorName(decompressedSize);
            return false;
        }
    }

    /*
     * We assume LZ4F_decompress() will not set inBufSize to a
     * value > state->in.avail.
     */
    state->in.next  += compressedSize;
    state->in.avail -= compressedSize;

    state->out.next  = state->out.buf;
    state->out.avail = (unsigned)decompressedSize;

    if (state->lz4_info.blockChecksumFlag == LZ4F_blockChecksumEnabled) {
        uint32_t xxHash;
        if (gz_next4(state, &xxHash) == -1) {
            return false;
        }
        /* XXX - check hash? */
    }
#endif
    return true;
}
#endif /* USE_LZ4 */

/*
 * Check for an lz4 header.
 */
static int
check_for_lz4_compression(FILE_T state)
{
    /*
     * Look for the lz4 header, and, if we find it, return success
     * if we support lz4 and an error if we don't.
     */
    if (state->in.avail >= 4
        && state->in.next[0] == 0x04 && state->in.next[1] == 0x22
        && state->in.next[2] == 0x4d && state->in.next[3] == 0x18) {
#ifdef USE_LZ4
#if LZ4_VERSION_NUMBER >= 10800
        LZ4F_resetDecompressionContext(state->lz4_dctx);
#else /* LZ4_VERSION_NUMBER >= 10800 */
        LZ4F_freeDecompressionContext(state->lz4_dctx);
        const LZ4F_errorCode_t ret = LZ4F_createDecompressionContext(&state->lz4_dctx, LZ4F_VERSION);
        if (LZ4F_isError(ret)) {
            state->err = WTAP_ERR_INTERNAL;
            state->err_info = LZ4F_getErrorName(ret);
            return -1;
        }
#endif /* LZ4_VERSION_NUMBER >= 10800 */
        size_t headerSize = LZ4F_HEADER_SIZE_MAX;
#if LZ4_VERSION_NUMBER >= 10903
        /*
         * In 1.9.3+ we can handle a silly edge case of a tiny valid
         * frame at the end of a file that is smaller than the maximum
         * header size. (lz4frame.h added the function in 1.9.0, but
         * only for the static library; it wasn't exported until 1.9.3)
         */
        while (state->in.avail < LZ4F_MIN_SIZE_TO_KNOW_HEADER_LENGTH) {
            if (fill_in_buffer(state) == -1) {
                return -1;
            }
            if (state->eof) {
                state->err = WTAP_ERR_SHORT_READ;
                state->err_info = NULL;
                return 0;
            }
        }
        headerSize = LZ4F_headerSize(state->in.next, state->in.avail);
        if (LZ4F_isError(headerSize)) {
            state->err = WTAP_ERR_DECOMPRESS;
            state->err_info = LZ4F_getErrorName(headerSize);
            return -1;
        }
#endif /* LZ4_VERSION_NUMBER >= 10903 */
        while (state->in.avail < headerSize) {
            if (fill_in_buffer(state) == -1) {
                return -1;
            }
            if (state->eof) {
                state->err = WTAP_ERR_SHORT_READ;
                state->err_info = NULL;
                return 0;
            }
        }
        size_t inBufSize = state->in.avail;
        memcpy(state->lz4_hdr, state->in.next, headerSize);
        const LZ4F_errorCode_t err = LZ4F_getFrameInfo(state->lz4_dctx, &state->lz4_info, state->in.next, &inBufSize);
        if (LZ4F_isError(err)) {
            state->err = WTAP_ERR_DECOMPRESS;
            state->err_info = LZ4F_getErrorName(err);
            return -1;
        }

        /*
         * XXX - We could check state->lz4_info.blockSizeID here, and
         * only realloc the buffers to a larger value if the max
         * block size is bigger than state->size. Also we could fail
         * on unknown values?
         */
        state->in.avail -= inBufSize;
        state->in.next += inBufSize;

        fast_seek_header(state, state->raw_pos - state->in.avail, state->pos, LZ4);
        state->compression = LZ4;
        state->is_compressed = true;
        return 1;
#else /* USE_LZ4 */
        state->err = WTAP_ERR_DECOMPRESSION_NOT_SUPPORTED;
        state->err_info = "reading lz4-compressed files isn't supported";
        return -1;
#endif /* USE_LZ4 */
    }
    return 0;
}

typedef int (*compression_type_test)(FILE_T);

static compression_type_test const compression_type_tests[] = {
    check_for_zlib_compression,
    check_for_zstd_compression,
    check_for_lz4_compression,
};

/*
 * Used when we haven't yet determined whether we have a compressed file
 * and, if we do, what sort of compressed file it is.
 *
 * Based on the non-gzip-specific stuff that gz_head() from zlib does.
 */
static int
check_for_compression(FILE_T state)
{
    /*
     * If this isn't the first frame / compressed stream, ensure that
     * we're starting at the beginning of the buffer. This shouldn't
     * get called much.
     *
     * This is to avoid edge cases where a previous frame finished but
     * state->in.next is close to the end of the buffer so there isn't
     * much room to put the start of the next frame.
     * This also lets us put back bytes if things go wrong.
     */
    if (state->in.next != state->in.buf) {
        memmove(state->in.buf, state->in.next, state->in.avail);
        state->in.next = state->in.buf;
    }

    /* get some data in the input buffer */
    if (state->in.avail == 0) {
        if (fill_in_buffer(state) == -1)
            return -1;
        if (state->in.avail == 0)
            return 0;
    }

    /*
     * Check for the compression types we support.
     */
    for (size_t i = 0; i < G_N_ELEMENTS(compression_type_tests); i++) {
        int ret;

        ret = compression_type_tests[i](state);
        if (ret == -1)
            return -1;    /* error */
        if (ret == 1)
            return 0;     /* found it */
    }

    /*
     * Some other compressed file formats we might want to support:
     *
     *   XZ format:
     *     https://tukaani.org/xz/
     *     https://github.com/tukaani-project/xz
     *     https://github.com/tukaani-project/xz/blob/master/doc/xz-file-format.txt
     *
     *    Bzip2 format:
     *      https://www.sourceware.org/bzip2/
     *      https://gitlab.com/bzip2/bzip2/
     *      https://github.com/dsnet/compress/blob/master/doc/bzip2-format.pdf
     *        (GitHub won't render it; download and open it)
     *
     *    Lzip format:
     *      https://www.nongnu.org/lzip/
     */

    /*
     * We didn't see anything that looks like a header for any type of
     * compressed file that we support, so just do uncompressed I/O.
     *
     * XXX - This fast seek data is for the case where a compressed stream
     * ends and is followed by an uncompressed portion.  It only works if
     * the uncompressed portion is at the end, as we don't constantly scan
     * for magic bytes in the middle of uncompressed data. (Concatenated
     * compressed streams _do_ work, even streams of different compression types.)
     */
    if (state->fast_seek)
        fast_seek_header(state, state->raw_pos - state->in.avail, state->pos, UNCOMPRESSED);


    /* doing raw i/o, save start of raw data for seeking, copy any leftover
       input to output -- this assumes that the output buffer is larger than
       the input buffer, which also assures space for gzungetc() */
    state->raw = state->pos;
    state->out.next = state->out.buf;
    /* not a compressed file -- copy everything we've read into the
       input buffer to the output buffer and fall to raw i/o */
    if (state->in.avail) {
        memcpy(state->out.buf, state->in.next, state->in.avail);
        state->out.avail = state->in.avail;

        /* Now discard everything in the input buffer */
        buf_reset(&state->in);
    }
    state->compression = UNCOMPRESSED;
    return 0;
}

/*
 * Based on what gz_make() in zlib does.
 */
static int
fill_out_buffer(FILE_T state)
{
    if (state->compression == UNKNOWN) {
        /*
         * We don't yet know whether the file is compressed,
         * so check for a compressed-file header.
         */
        if (check_for_compression(state) == -1)
            return -1;
        if (state->out.avail != 0)                /* got some data from check_for_compression() */
            return 0;
    }

    /*
     * We got no data from check_for_compression(), or we didn't call
     * it as we already know the compression type, so read some more
     * data.
     */
    switch (state->compression) {

    case UNCOMPRESSED:
        /* straight copy */
        if (!uncompressed_fill_out_buffer(state))
            return -1;
        break;

#ifdef USE_ZLIB_OR_ZLIBNG
    case ZLIB:
        /* zlib (gzip) decompress */
        zlib_fill_out_buffer(state);
        break;
#endif /* USE_ZLIB_OR_ZLIBNG */

#ifdef HAVE_ZSTD
    case ZSTD:
        /* zstd decompress */
        if (!zstd_fill_out_buffer(state))
            return -1;
        break;
#endif /* HAVE_ZSTD */

#ifdef USE_LZ4
    case LZ4:
        /* lz4 decompress */
        if (!lz4_fill_out_buffer(state))
            return -1;
        break;
#endif /* USE_LZ4 */

    default:
        /* Unknown compression type; keep reading */
        break;
    }
    return 0;
}

static int
gz_skip(FILE_T state, int64_t len)
{
    unsigned n;

    /* skip over len bytes or reach end-of-file, whichever comes first */
    while (len)
        if (state->out.avail != 0) {
            /* We have stuff in the output buffer; skip over
               it. */
            n = (int64_t)state->out.avail > len ? (unsigned)len : state->out.avail;
            state->out.avail -= n;
            state->out.next += n;
            state->pos += n;
            len -= n;
        } else if (state->err != 0) {
            /* We have nothing in the output buffer, and
               we have an error that may not have been
               reported yet; that means we can't generate
               any more data into the output buffer, so
               return an error indication. */
            return -1;
        } else if (state->eof && state->in.avail == 0) {
            /* We have nothing in the output buffer, and
               we're at the end of the input; just return. */
            break;
        } else {
            /* We have nothing in the output buffer, and
               we can generate more data; get more output,
               looking for header if required. */
            if (fill_out_buffer(state) == -1)
                return -1;
        }
    return 0;
}

static void
gz_reset(FILE_T state)
{
    buf_reset(&state->out);       /* no output data available */
    state->eof = false;           /* not at end of file */
    state->compression = UNKNOWN; /* look for compression header */

    state->seek_pending = false;  /* no seek request pending */
    state->err = 0;               /* clear error */
    state->err_info = NULL;
    state->pos = 0;               /* no uncompressed data yet */
    buf_reset(&state->in);        /* no input data yet */
}

FILE_T
file_fdopen(int fd)
{
    /*
     * XXX - we now check whether we have st_blksize in struct stat;
     * it's not available on all platforms.
     *
     * I'm not sure why we're testing _STATBUF_ST_BLKSIZE; it's not
     * set on all platforms that have st_blksize in struct stat.
     * (Not all platforms have st_blksize in struct stat.)
     *
     * Is there some reason *not* to make the buffer size the maximum
     * of GBUFSIZE and st_blksize?  On most UN*Xes, the standard I/O
     * library does I/O with st_blksize as the buffer size; on others,
     * and on Windows, it's a 4K buffer size.  If st_blksize is bigger
     * than GBUFSIZE (which is currently 4KB), that's probably a
     * hint that reading in st_blksize chunks is considered a good
     * idea (e.g., an 8K/1K Berkeley fast file system with st_blksize
     * being 8K, or APFS, where st_blksize is big on at least some
     * versions of macOS).
     */
#ifdef _STATBUF_ST_BLKSIZE
    ws_statb64 st;
#endif /* _STATBUF_ST_BLKSIZE */
#ifdef HAVE_ZSTD
    size_t zstd_buf_size;
#endif /* HAVE_ZSTD */
    unsigned want = GZBUFSIZE;
    FILE_T state;
#ifdef USE_LZ4
    size_t ret;
#endif /* USE_LZ4 */

    if (fd == -1)
        return NULL;

    /* allocate FILE_T structure to return */
    state = (FILE_T)g_try_malloc0(sizeof *state);
    if (state == NULL)
        return NULL;

    state->fast_seek_cur = NULL;
    state->fast_seek = NULL;

    /* open the file with the appropriate mode (or just use fd) */
    state->fd = fd;

    /* we don't yet know whether it's compressed */
    state->is_compressed = false;
    state->last_compression = UNKNOWN;

    /* save the current position for rewinding (only if reading) */
    state->start = ws_lseek64(state->fd, 0, SEEK_CUR);
    if (state->start == -1) state->start = 0;
    state->raw_pos = state->start;

    /* initialize stream */
    gz_reset(state);

#ifdef _STATBUF_ST_BLKSIZE
    /*
     * See what I/O size the file system recommends using, and if
     * it's bigger than what we're using and isn't too big, use
     * it.
     */
    if (ws_fstat64(fd, &st) >= 0) {
        /*
         * Yes, st_blksize can be bigger than an int; apparently,
         * it's a long on LP64 Linux, for example.
         *
         * If the value is too big to fit into a unsigned,
         * just use the maximum read buffer size.
         *
         * On top of that, the Single UNIX Speification says that
         * st_blksize is of type blksize_t, which is a *signed*
         * integer type, and, at minimum, macOS 11.6 and Linux 5.14.11's
         * include/uapi/asm-generic/stat.h define it as such.
         *
         * However, other OSes might make it unsigned, and older versions
         * of OSes that currently make it signed might make it unsigned,
         * so we try to avoid warnings from that.
         *
         * We cast MAX_READ_BUF_SIZE to long in order to avoid the
         * warning, although it might introduce warnings on platforms
         * where st_blocksize is unsigned; we'll deal with that if
         * it ever shows up as an issue.
         *
         * MAX_READ_BUF_SIZE is < the largest *signed* 32-bt integer,
         * so casting it to long won't turn it into a negative number.
         * (We only support 32-bit and 64-bit 2's-complement platforms.)
         */
        if (st.st_blksize <= (long)MAX_READ_BUF_SIZE)
            want = (unsigned)st.st_blksize;
        else
            want = MAX_READ_BUF_SIZE;
        /* XXX, verify result? */
    }
#endif /* _STATBUF_ST_BLKSIZE */
#ifdef HAVE_ZSTD
    /* we should have separate input and output buf sizes */
    zstd_buf_size = ZSTD_DStreamInSize();
    if (zstd_buf_size > want) {
        if (zstd_buf_size <= MAX_READ_BUF_SIZE)
            want = (unsigned)zstd_buf_size;
        else
            want = MAX_READ_BUF_SIZE;
    }
    zstd_buf_size = ZSTD_DStreamOutSize();
    if (zstd_buf_size > want) {
        if (zstd_buf_size <= MAX_READ_BUF_SIZE)
            want = (unsigned)zstd_buf_size;
        else
            want = MAX_READ_BUF_SIZE;
    }
#endif /* HAVE_ZSTD */
#ifdef USE_LZ4
    if (LZ4BUFSIZE > want) {
        if (LZ4BUFSIZE <= MAX_READ_BUF_SIZE) {
            want = LZ4BUFSIZE;
        } else {
            goto err;
        }
    }
#endif /* USE_LZ4 */

    /* allocate buffers */
    state->in.buf = (unsigned char *)g_try_malloc(want);
    state->in.next = state->in.buf;
    state->in.avail = 0;
    state->out.buf = (unsigned char *)g_try_malloc(want << 1);
    state->out.next = state->out.buf;
    state->out.avail = 0;
    state->size = want;
    if (state->in.buf == NULL || state->out.buf == NULL) {
       goto err;
    }

#ifdef USE_ZLIB_OR_ZLIBNG
    /* allocate inflate memory */
    state->strm.zalloc = Z_NULL;
    state->strm.zfree = Z_NULL;
    state->strm.opaque = Z_NULL;
    state->strm.avail_in = 0;
    state->strm.next_in = Z_NULL;
    if (ZLIB_PREFIX(inflateInit2)(&(state->strm), -15) != Z_OK) {    /* raw inflate */
        goto err;
    }

    /* for now, assume we should check the crc */
    state->dont_check_crc = false;
#endif /* USE_ZLIB_OR_ZLIBNG */

#ifdef HAVE_ZSTD
    state->zstd_dctx = ZSTD_createDCtx();
    if (state->zstd_dctx == NULL) {
        goto err;
    }
#endif /* HAVE_ZSTD */

#ifdef USE_LZ4
    ret = LZ4F_createDecompressionContext(&state->lz4_dctx, LZ4F_VERSION);
    if (LZ4F_isError(ret)) {
        goto err;
    }
#endif /* USE_LZ4 */

    /* return stream */
    return state;

err:
#ifdef USE_ZLIB_OR_ZLIBNG
    ZLIB_PREFIX(inflateEnd)(&state->strm);
#endif /* USE_ZLIB_OR_ZLIBNG */
#ifdef HAVE_ZSTD
    ZSTD_freeDCtx(state->zstd_dctx);
#endif /* HAVE_ZSTD */
#ifdef USE_LZ4
    LZ4F_freeDecompressionContext(state->lz4_dctx);
#endif /* USE_LZ4 */
    g_free(state->out.buf);
    g_free(state->in.buf);
    g_free(state);
    errno = ENOMEM;
    return NULL;
}

FILE_T
file_open(const char *path)
{
    int fd;
    FILE_T ft;
#ifdef USE_ZLIB_OR_ZLIBNG
    const char *suffixp;
#endif /* USE_ZLIB_OR_ZLIBNG */

    /* open file and do correct filename conversions.

       XXX - do we need O_LARGEFILE?  On UN*X, if we need to do
       something special to get large file support, the configure
       script should have set us up with the appropriate #defines,
       so we should be getting a large-file-enabled file descriptor
       here.  Pre-Large File Summit UN*Xes, and possibly even some
       post-LFS UN*Xes, might require O_LARGEFILE here, though.
       If so, we should probably handle that in ws_open(). */
    if ((fd = ws_open(path, O_RDONLY|O_BINARY, 0000)) == -1)
        return NULL;

    /* open file handle */
    ft = file_fdopen(fd);
    if (ft == NULL) {
        ws_close(fd);
        return NULL;
    }

#ifdef USE_ZLIB_OR_ZLIBNG
    /*
     * If this file's name ends in ".caz", it's probably a compressed
     * Windows Sniffer file.  The compression is gzip, but if we
     * process the CRC as specified by RFC 1952, the computed CRC
     * doesn't match the stored CRC.
     *
     * Compressed Windows Sniffer files don't all have the same CRC
     * value; is it just random crap, or are they running the CRC on
     * a different set of data than you're supposed to (e.g., not
     * CRCing some of the data), or something such as that?
     *
     * For now, we just set a flag to ignore CRC errors.
     */
    suffixp = strrchr(path, '.');
    if (suffixp != NULL) {
        if (g_ascii_strcasecmp(suffixp, ".caz") == 0)
            ft->dont_check_crc = true;
    }
#endif /* USE_ZLIB_OR_ZLIBNG */

    return ft;
}

void
file_set_random_access(FILE_T stream, bool random_flag _U_, GPtrArray *seek)
{
    stream->fast_seek = seek;
}

int64_t
file_seek(FILE_T file, int64_t offset, int whence, int *err)
{
    struct fast_seek_point *here;
    unsigned n;

    if (whence != SEEK_SET && whence != SEEK_CUR && whence != SEEK_END) {
        ws_assert_not_reached();
/*
 *err = EINVAL;
 return -1;
*/
    }

    /* Normalize offset to a SEEK_CUR specification */
    if (whence == SEEK_END) {
        /* Seek relative to the end of the file; given that we might be
           reading from a compressed file, we do that by seeking to the
           end of the file, making an offset relative to the end of
           the file an offset relative to the current position.

           XXX - we don't actually use this yet, but, for uncompressed
           files, we could optimize it, if desired, by directly using
           ws_lseek64(). */
        if (gz_skip(file, INT64_MAX) == -1) {
            *err = file->err;
            return -1;
        }
        if (offset == 0) {
            /* We are done */
            return file->pos;
        }
    } else if (whence == SEEK_SET)
        offset -= file->pos;
    else if (file->seek_pending) {
        /* There's a forward-skip pending, so file->pos doesn't reflect
           the actual file position, it represents the position from
           which we're skipping; update the offset to include that. */
        offset += file->skip;
    }
    file->seek_pending = false;

    /*
     * Are we moving at all?
     */
    if (offset == 0) {
        /* No.  Just return the current position. */
        return file->pos;
    }

    /*
     * Are we seeking backwards?
     */
    if (offset < 0) {
        /*
         * Yes.
         *
         * Do we have enough data before the current position in the
         * buffer that we can seek backwards within the buffer?
         */
        if (-offset <= offset_in_buffer(&file->out)) {
            /*
             * Yes.  Adjust appropriately.
             *
             * offset is negative, so -offset is non-negative, and
             * -offset is <= an unsigned and thus fits in an unsigned.
             * Get that value and adjust appropriately.
             *
             * (Casting offset to unsigned makes it positive, which
             * is not what we would want, so we cast -offset instead.)
             *
             * XXX - this won't work with -offset = 2^63, as its
             * negative isn't a valid 64-bit integer, but we are
             * not at all likely to see files big enough to ever
             * see a negative offset that large.
             */
            unsigned adjustment = (unsigned)(-offset);

            file->out.avail += adjustment;
            file->out.next -= adjustment;
            file->pos -= adjustment;
            return file->pos;
        }
    } else {
        /*
         * No.  Offset is positive; we're seeking forwards.
         *
         * Do we have enough data after the current position in the
         * buffer that we can seek forwards within the buffer?
         */
        if (offset < file->out.avail) {
            /*
             * Yes.  Adjust appropriately.
             *
             * offset is < an unsigned and thus fits in an unsigned,
             * so we can cast it to unsigned safely.
             */
            file->out.avail -= (unsigned)offset;
            file->out.next += offset;
            file->pos += offset;
            return file->pos;
        }
    }

    /*
     * We're not seeking within the buffer.  Do we have "fast seek" data
     * for the location to which we will be seeking, and are we either
     * seeking backwards or is the fast seek point past what is in the
     * buffer? (We don't want to "fast seek" backwards to a point that
     * we've already read and buffered if we're actually seeking forwards.)
     *
     * It might in certain cases be faster to continue reading linearly
     * foward rather than jump to the fast seek point if the distance
     * to the fast seek point is small, but we might only be able to do that
     * if the compression context doesn't change (which for LZ4 includes if
     * we jump to a LZ4 with different options.)
     * XXX - profile different buffer and SPAN sizes
     */
    if ((here = fast_seek_find(file, file->pos + offset)) &&
        (offset < 0 || here->out >= file->pos + file->out.avail)) {
        int64_t off, off2;

        /*
         * Yes.  Use that data to do the seek.
         * Note that this will be true only if file_set_random_access()
         * has been called on this file, which should never be the case
         * for a pipe.
         */
        switch (here->compression) {

#ifdef USE_ZLIB_OR_ZLIBNG
        case ZLIB:
#ifdef HAVE_INFLATEPRIME
            off = here->in - (here->data.zlib.bits ? 1 : 0);
#else /* HAVE_INFLATEPRIME */
            off = here->in;
#endif /* HAVE_INFLATEPRIME */
            off2 = here->out;
            break;

        case GZIP_AFTER_HEADER:
            off = here->in;
            off2 = here->out;
            break;
#endif /* USE_ZLIB_OR_ZLIBNG */

#ifdef USE_LZ4
        case LZ4:
            ws_debug("fast seek lz4");
            off = here->in;
            off2 = here->out;
            break;
#endif /* USE_LZ4 */

        case UNCOMPRESSED:
            /* In an uncompressed portion, seek directly to the offset */
            off2 = (file->pos + offset);
            off = here->in + (off2 - here->out);
            break;

        default:
            /* Otherwise, seek to the fast seek point to do any needed setup. */
            off = here->in;
            off2 = here->out;
            break;
        }

        if (ws_lseek64(file->fd, off, SEEK_SET) == -1) {
            *err = errno;
            return -1;
        }
        fast_seek_reset(file);

        file->raw_pos = off;
        buf_reset(&file->out);
        file->eof = false;
        file->seek_pending = false;
        file->err = 0;
        file->err_info = NULL;
        buf_reset(&file->in);

        switch (here->compression) {

#ifdef USE_ZLIB_OR_ZLIBNG
        case ZLIB: {
            zlib_stream*strm = &file->strm;
            ZLIB_PREFIX(inflateReset)(strm);
            strm->adler = here->data.zlib.adler;
            strm->total_out = here->data.zlib.total_out;
#ifdef HAVE_INFLATEPRIME
            if (here->data.zlib.bits) {
                FILE_T state = file;
                int ret = GZ_GETC();

                if (ret == -1) {
                    if (state->err == 0) {
                        /* EOF */
                        *err = WTAP_ERR_SHORT_READ;
                    } else
                        *err = state->err;
                    return -1;
                }
                (void)ZLIB_PREFIX(inflatePrime)(strm, here->data.zlib.bits, ret >> (8 - here->data.zlib.bits));
            }
#endif /* HAVE_INFLATEPRIME */
            (void)ZLIB_PREFIX(inflateSetDictionary)(strm, here->data.zlib.window, ZLIB_WINSIZE);
            file->compression = ZLIB;
            break;
        }

        case GZIP_AFTER_HEADER: {
            zlib_stream* strm = &file->strm;
            ZLIB_PREFIX(inflateReset)(strm);
            strm->adler = ZLIB_PREFIX(crc32)(0L, Z_NULL, 0);
            file->compression = ZLIB;
            break;
        }
#endif /* USE_ZLIB_OR_ZLIBNG */

#ifdef USE_LZ4
        case LZ4:
            /* If the frame information seems to have changed (i.e., we fast
             * seeked into a different frame that also has different flags
             * and options), then reset the context and re-read it.
             * Unfortunately the API doesn't provide a method to set the
             * context options explicitly based on an already read
             * LZ4F_frameInfo_t.
             */
            if (memcmp(&file->lz4_info, &here->data.lz4.lz4_info, sizeof(LZ4F_frameInfo_t)) != 0) {
#if LZ4_VERSION_NUMBER >= 10800
                LZ4F_resetDecompressionContext(file->lz4_dctx);
#else /* LZ4_VERSION_NUMBER >= 10800 */
                LZ4F_freeDecompressionContext(file->lz4_dctx);
                const LZ4F_errorCode_t ret = LZ4F_createDecompressionContext(&file->lz4_dctx, LZ4F_VERSION);
                if (LZ4F_isError(ret)) {
                    file->err = WTAP_ERR_INTERNAL;
                    file->err_info = LZ4F_getErrorName(ret);
                    return -1;
                }
#endif /* LZ4_VERSION_NUMBER >= 10800 */
                size_t hdr_size = LZ4F_HEADER_SIZE_MAX;
                const LZ4F_errorCode_t frame_err = LZ4F_getFrameInfo(file->lz4_dctx, &file->lz4_info, here->data.lz4.lz4_hdr, &hdr_size);
                if (LZ4F_isError(frame_err)) {
                    file->err = WTAP_ERR_DECOMPRESS;
                    file->err_info = LZ4F_getErrorName(frame_err);
                    return -1;
                }
            }
            file->lz4_info = here->data.lz4.lz4_info;
            file->compression = LZ4;
            break;
#endif /* USE_LZ4 */

#ifdef HAVE_ZSTD
        case ZSTD:
        {
            const size_t ret = ZSTD_initDStream(file->zstd_dctx);
            if (ZSTD_isError(ret)) {
                file->err = WTAP_ERR_DECOMPRESS;
                file->err_info = ZSTD_getErrorName(ret);
                return -1;
            }
            file->compression = ZSTD;
            break;
        }
#endif /* HAVE_ZSTD */

        default:
            file->compression = here->compression;
            break;
        }

        offset = (file->pos + offset) - off2;
        file->pos = off2;
        ws_debug("Fast seek OK! %"PRId64, offset);

        if (offset) {
            /* Don't skip forward yet, wait until we want to read from
               the file; that way, if we do multiple seeks in a row,
               all involving forward skips, they will be combined. */
            file->seek_pending = true;
            file->skip = offset;
        }
        return file->pos + offset;
    }

    /*
     * Is this an uncompressed file, are we within the raw area,
     * are we either seeking backwards or seeking past the end
     * of the buffer, and are we set up for random access with
     * file_set_random_access()?
     *
     * Again, note that this will never be true on a pipe, as
     * file_set_random_access() should never be called if we're
     * reading from a pipe.
     */
    if (file->compression == UNCOMPRESSED && file->pos + offset >= file->raw
        && (offset < 0 || offset >= file->out.avail)
        && (file->fast_seek != NULL))
    {
        /*
         * Yes.  Just seek there within the file.
         */
        if (ws_lseek64(file->fd, offset - file->out.avail, SEEK_CUR) == -1) {
            *err = errno;
            return -1;
        }
        file->raw_pos += (offset - file->out.avail);
        buf_reset(&file->out);
        file->eof = false;
        file->seek_pending = false;
        file->err = 0;
        file->err_info = NULL;
        buf_reset(&file->in);
        file->pos += offset;
        return file->pos;
    }

    /*
     * Are we seeking backwards?
     */
    if (offset < 0) {
        /*
         * Yes.  We have no fast seek data, so we have to rewind and
         * seek forward.
         * XXX - true only for compressed files.
         *
         * Calculate the amount to skip forward after rewinding.
         */
        offset += file->pos;
        if (offset < 0) {                    /* before start of file! */
            *err = EINVAL;
            return -1;
        }
        /* rewind, then skip to offset */

        /* back up and start over */
        if (ws_lseek64(file->fd, file->start, SEEK_SET) == -1) {
            *err = errno;
            return -1;
        }
        fast_seek_reset(file);
        file->raw_pos = file->start;
        gz_reset(file);
    }

    /*
     * Either we're seeking backwards, but have rewound and now need to
     * skip forwards, or we're seeking forwards.
     *
     * Skip what's in output buffer (one less gzgetc() check).
     */
    n = (int64_t)file->out.avail > offset ? (unsigned)offset : file->out.avail;
    file->out.avail -= n;
    file->out.next += n;
    file->pos += n;
    offset -= n;

    /* request skip (if not zero) */
    if (offset) {
        /* Don't skip forward yet, wait until we want to read from
           the file; that way, if we do multiple seeks in a row,
           all involving forward skips, they will be combined. */
        file->seek_pending = true;
        file->skip = offset;
    }
    return file->pos + offset;
}

int64_t
file_tell(FILE_T stream)
{
    /* return position */
    return stream->pos + (stream->seek_pending ? stream->skip : 0);
}

int64_t
file_tell_raw(FILE_T stream)
{
    return stream->raw_pos;
}

int
file_fstat(FILE_T stream, ws_statb64 *statb, int *err)
{
    if (ws_fstat64(stream->fd, statb) == -1) {
        if (err != NULL)
            *err = errno;
        return -1;
    }
    return 0;
}

bool
file_iscompressed(FILE_T stream)
{
    return stream->is_compressed;
}

/* Returns a wtap compression type. If we don't know the compression type,
 * return WTAP_UNCOMPRESSED, but if our compression state is temporarily
 * UNKNOWN because we need to reread compression headers, return the last
 * known compression type.
 */
static wtap_compression_type
file_get_compression_type(FILE_T stream)
{
    if (stream->is_compressed) {
        switch ((stream->compression == UNKNOWN) ? stream->last_compression : stream->compression) {

        case ZLIB:
        case GZIP_AFTER_HEADER:
            return WTAP_GZIP_COMPRESSED;

        case ZSTD:
            return WTAP_ZSTD_COMPRESSED;

        case LZ4:
            return WTAP_LZ4_COMPRESSED;

        case UNCOMPRESSED:
            return WTAP_UNCOMPRESSED;

        default: /* UNKNOWN, should never happen if is_compressed is set */
            ws_assert_not_reached();
            return WTAP_UNCOMPRESSED;
        }
    }
    return WTAP_UNCOMPRESSED;
}

int
file_read(void *buf, unsigned int len, FILE_T file)
{
    unsigned got, n;

    /* if len is zero, avoid unnecessary operations */
    if (len == 0)
        return 0;

    /* process a skip request */
    if (file->seek_pending) {
        file->seek_pending = false;
        if (gz_skip(file, file->skip) == -1)
            return -1;
    }

    /*
     * Get len bytes to buf, or less than len if at the end;
     * if buf is null, just throw the bytes away.
     */
    got = 0;
    do {
        if (file->out.avail != 0) {
            /* We have stuff in the output buffer; copy
               what we have. */
            n = file->out.avail > len ? len : file->out.avail;
            if (buf != NULL) {
                memcpy(buf, file->out.next, n);
                buf = (char *)buf + n;
            }
            file->out.next += n;
            file->out.avail -= n;
            len -= n;
            got += n;
            file->pos += n;
        } else if (file->err != 0) {
            /* We have nothing in the output buffer, and
               we have an error that may not have been
               reported yet; that means we can't generate
               any more data into the output buffer, so
               return an error indication. */
            return -1;
        } else if (file->eof && file->in.avail == 0) {
            /* We have nothing in the output buffer, and
               we're at the end of the input; just return
               with what we've gotten so far. */
            break;
        } else {
            /* We have nothing in the output buffer, and
               we can generate more data; get more output,
               looking for header if required, and
               keep looping to process the new stuff
               in the output buffer. */
            if (fill_out_buffer(file) == -1)
                return -1;
        }
    } while (len);

    return (int)got;
}

/*
 * XXX - this *peeks* at next byte, not a character.
 */
int
file_peekc(FILE_T file)
{
    int ret = 0;

    /* check that we're reading and that there's no error */
    if (file->err != 0)
        return -1;

    /* try output buffer (no need to check for skip request) */
    if (file->out.avail != 0) {
        return *(file->out.next);
    }

    /* process a skip request */
    if (file->seek_pending) {
        file->seek_pending = false;
        if (gz_skip(file, file->skip) == -1)
            return -1;
    }
    /* if we processed a skip request, there may be data in the buffer,
     * or an error could have occurred; likewise if we didn't do seek but
     * now call fill_out_buffer, the errors can occur.  So we do this while
     * loop to check before and after - this is basically the logic from
     * file_read() but only for peeking not consuming a byte
     */
    while (1) {
        if (file->out.avail != 0) {
            return *(file->out.next);
        }
        else if (file->err != 0) {
            return -1;
        }
        else if (file->eof && file->in.avail == 0) {
            return -1;
        }
        else if (fill_out_buffer(file) == -1) {
            return -1;
        }
    }
    /* it's actually impossible to get here */
    return ret;
}

/*
 * XXX - this gets a byte, not a character.
 */
int
file_getc(FILE_T file)
{
    unsigned char buf[1];
    int ret;

    /* check that we're reading and that there's no error */
    if (file->err != 0)
        return -1;

    /* try output buffer (no need to check for skip request) */
    if (file->out.avail != 0) {
        file->out.avail--;
        file->pos++;
        return *(file->out.next)++;
    }

    ret = file_read(buf, 1, file);
    return ret < 1 ? -1 : buf[0];
}

/* Like file_gets, but returns a pointer to the terminating NUL. */
char *
file_getsp(char *buf, int len, FILE_T file)
{
    unsigned left, n;
    char *str;
    unsigned char *eol;

    /* check parameters */
    if (buf == NULL || len < 1)
        return NULL;

    /* check that there's no error */
    if (file->err != 0)
        return NULL;

    /* process a skip request */
    if (file->seek_pending) {
        file->seek_pending = false;
        if (gz_skip(file, file->skip) == -1)
            return NULL;
    }

    /* copy output bytes up to new line or len - 1, whichever comes first --
       append a terminating zero to the string (we don't check for a zero in
       the contents, let the user worry about that) */
    str = buf;
    left = (unsigned)len - 1;
    if (left) do {
            /* assure that something is in the output buffer */
            if (file->out.avail == 0) {
                /* We have nothing in the output buffer. */
                if (file->err != 0) {
                    /* We have an error that may not have
                       been reported yet; that means we
                       can't generate any more data into
                       the output buffer, so return an
                       error indication. */
                    return NULL;
                }
                if (fill_out_buffer(file) == -1)
                    return NULL;            /* error */
                if (file->out.avail == 0)  {     /* end of file */
                    if (buf == str)         /* got bupkus */
                        return NULL;
                    break;                  /* got something -- return it */
                }
            }

            /* look for end-of-line in current output buffer */
            n = file->out.avail > left ? left : file->out.avail;
            eol = (unsigned char *)memchr(file->out.next, '\n', n);
            if (eol != NULL)
                n = (unsigned)(eol - file->out.next) + 1;

            /* copy through end-of-line, or remainder if not found */
            memcpy(buf, file->out.next, n);
            file->out.avail -= n;
            file->out.next += n;
            file->pos += n;
            left -= n;
            buf += n;
        } while (left && eol == NULL);

    /* found end-of-line or out of space -- add a terminator and return
       a pointer to it */
    buf[0] = 0;
    return buf;
}

char *
file_gets(char *buf, int len, FILE_T file)
{
    if (!file_getsp(buf, len, file)) return NULL;
    return buf;
}

int
file_eof(FILE_T file)
{
    /* return end-of-file state */
    return (file->eof && file->in.avail == 0 && file->out.avail == 0);
}

/*
 * Routine to return a Wiretap error code (0 for no error, an errno
 * for a file error, or a WTAP_ERR_ code for other errors) for an
 * I/O stream.  Also returns an error string for some errors.
 */
int
file_error(FILE_T fh, char **err_info)
{
    if (fh->err!=0 && err_info) {
        /* g_strdup() returns NULL for NULL argument */
        *err_info = g_strdup(fh->err_info);
    }
    return fh->err;
}

void
file_clearerr(FILE_T stream)
{
    /* clear error and end-of-file */
    stream->err = 0;
    stream->err_info = NULL;
    stream->eof = false;
}

void
file_fdclose(FILE_T file)
{
    if (file->fd != -1)
        ws_close(file->fd);
    file->fd = -1;
}

bool
file_fdreopen(FILE_T file, const char *path)
{
    int fd;

    if ((fd = ws_open(path, O_RDONLY|O_BINARY, 0000)) == -1)
        return false;
    file->fd = fd;
    return true;
}

void
file_close(FILE_T file)
{
    int fd = file->fd;

    /* free memory and close file */
    if (file->size) {
#ifdef USE_ZLIB_OR_ZLIBNG
        ZLIB_PREFIX(inflateEnd)(&(file->strm));
#endif /* USE_ZLIB_OR_ZLIBNG */
#ifdef HAVE_ZSTD
        ZSTD_freeDCtx(file->zstd_dctx);
#endif /* HAVE_ZSTD */
#ifdef USE_LZ4
        LZ4F_freeDecompressionContext(file->lz4_dctx);
#endif /* USE_LZ4 */
        g_free(file->out.buf);
        g_free(file->in.buf);
    }
    g_free(file->fast_seek_cur);
    file->err = 0;
    file->err_info = NULL;
    g_free(file);
    /*
     * If fd is -1, somebody's done a file_closefd() on us, so
     * we don't need to close the FD itself, and shouldn't do
     * so.
     */
    if (fd != -1)
        ws_close(fd);
}

#ifdef USE_ZLIB_OR_ZLIBNG
/* internal gzip file state data structure for writing */
struct wtap_writer {
    int fd;                 /* file descriptor */
    int64_t pos;            /* current position in uncompressed data */
    unsigned size;          /* buffer size, zero if not allocated yet */
    unsigned want;          /* requested buffer size, default is GZBUFSIZE */
    unsigned char *in;      /* input buffer */
    unsigned char *out;     /* output buffer (double-sized when reading) */
    unsigned char *next;    /* next output data to deliver or write */
    int level;              /* compression level */
    int strategy;           /* compression strategy */
    int err;                /* error code */
    const char *err_info;   /* additional error information string for some errors */
    /* zlib deflate stream */
    zlib_stream strm;          /* stream structure in-place (not a pointer) */
};

GZWFILE_T
gzwfile_open(const char *path)
{
    int fd;
    GZWFILE_T state;
    int save_errno;

    fd = ws_open(path, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0666);
    if (fd == -1)
        return NULL;
    state = gzwfile_fdopen(fd);
    if (state == NULL) {
        save_errno = errno;
        ws_close(fd);
        errno = save_errno;
    }
    return state;
}

GZWFILE_T
gzwfile_fdopen(int fd)
{
    GZWFILE_T state;

    /* allocate wtap_writer structure to return */
    state = (GZWFILE_T)g_try_malloc(sizeof *state);
    if (state == NULL)
        return NULL;
    state->fd = fd;
    state->size = 0;            /* no buffers allocated yet */
    state->want = GZBUFSIZE;    /* requested buffer size */

    state->level = Z_DEFAULT_COMPRESSION;
    state->strategy = Z_DEFAULT_STRATEGY;

    /* initialize stream */
    state->err = Z_OK;              /* clear error */
    state->err_info = NULL;         /* clear additional error information */
    state->pos = 0;                 /* no uncompressed data yet */
    state->strm.avail_in = 0;       /* no input data yet */

    /* return stream */
    return state;
}

/* Initialize state for writing a gzip file.  Mark initialization by setting
   state->size to non-zero.  Return -1, and set state->err and possibly
   state->err_info, on failure; return 0 on success. */
static int
gz_init(GZWFILE_T state)
{
    int ret;
#ifdef HAVE_ZLIBNG
    zng_streamp strm = &(state->strm);
#else /* HAVE_ZLIBNG */
    z_streamp strm = &(state->strm);
#endif /* HAVE_ZLIBNG */

    /* allocate input and output buffers */
    state->in = (unsigned char *)g_try_malloc(state->want);
    state->out = (unsigned char *)g_try_malloc(state->want);
    if (state->in == NULL || state->out == NULL) {
        g_free(state->out);
        g_free(state->in);
        state->err = ENOMEM;
        return -1;
    }

    /* allocate deflate memory, set up for gzip compression */
    strm->zalloc = Z_NULL;
    strm->zfree = Z_NULL;
    strm->opaque = Z_NULL;
    ret = ZLIB_PREFIX(deflateInit2)(strm, state->level, Z_DEFLATED,
                       15 + 16, 8, state->strategy);
    if (ret != Z_OK) {
        g_free(state->out);
        g_free(state->in);
        if (ret == Z_MEM_ERROR) {
            /* This means "not enough memory". */
            state->err = ENOMEM;
        } else {
            /* This "shouldn't happen". */
            state->err = WTAP_ERR_INTERNAL;
            state->err_info = "Unknown error from deflateInit2()";
        }
        return -1;
    }

    /* mark state as initialized */
    state->size = state->want;

    /* initialize write buffer */
    strm->avail_out = state->size;
    strm->next_out = state->out;
    state->next = strm->next_out;
    return 0;
}

/* Compress whatever is at avail_in and next_in and write to the output file.
   Return -1, and set state->err and possibly state->err_info, if there is
   an error writing to the output file; return 0 on success.
   flush is assumed to be a valid deflate() flush value.  If flush is Z_FINISH,
   then the deflate() state is reset to start a new gzip stream. */
static int
gz_comp(GZWFILE_T state, int flush)
{
    int ret;
    ssize_t got;
    ptrdiff_t have;
#ifdef HAVE_ZLIBNG
    zng_streamp strm = &(state->strm);
#else /* HAVE_ZLIBNG */
    z_streamp strm = &(state->strm);
#endif /* HAVE_ZLIBNG */
    /* allocate memory if this is the first time through */
    if (state->size == 0 && gz_init(state) == -1)
        return -1;

    /* run deflate() on provided input until it produces no more output */
    ret = Z_OK;
    do {
        /* write out current buffer contents if full, or if flushing, but if
           doing Z_FINISH then don't write until we get to Z_STREAM_END */
        if (strm->avail_out == 0 || (flush != Z_NO_FLUSH &&
                                     (flush != Z_FINISH || ret == Z_STREAM_END))) {
            have = strm->next_out - state->next;
            if (have) {
                got = ws_write(state->fd, state->next, (unsigned int)have);
                if (got < 0) {
                    state->err = errno;
                    return -1;
                }
                if ((ptrdiff_t)got != have) {
                    state->err = WTAP_ERR_SHORT_WRITE;
                    return -1;
                }
            }
            if (strm->avail_out == 0) {
                strm->avail_out = state->size;
                strm->next_out = state->out;
            }
            state->next = strm->next_out;
        }

        /* compress */
        have = strm->avail_out;
        ret = ZLIB_PREFIX(deflate)(strm, flush);
        if (ret == Z_STREAM_ERROR) {
            /* This "shouldn't happen". */
            state->err = WTAP_ERR_INTERNAL;
            state->err_info = "Z_STREAM_ERROR from deflate()";
            return -1;
        }
        have -= strm->avail_out;
    } while (have);

    /* if that completed a deflate stream, allow another to start */
    if (flush == Z_FINISH)
        ZLIB_PREFIX(deflateReset)(strm);

    /* all done, no errors */
    return 0;
}

/* Write out len bytes from buf.  Return 0, and set state->err, on
   failure or on an attempt to write 0 bytes (in which case state->err
   is Z_OK); return the number of bytes written on success. */
unsigned
gzwfile_write(GZWFILE_T state, const void *buf, unsigned len)
{
    unsigned put = len;
    unsigned n;
#ifdef HAVE_ZLIBNG
    zng_streamp strm;
#else /* HAVE_ZLIBNG */
    z_streamp strm;
#endif /* HAVE_ZLIBNG */

    strm = &(state->strm);

    /* check that there's no error */
    if (state->err != Z_OK)
        return 0;

    /* if len is zero, avoid unnecessary operations */
    if (len == 0)
        return 0;

    /* allocate memory if this is the first time through */
    if (state->size == 0 && gz_init(state) == -1)
        return 0;

    /* for small len, copy to input buffer, otherwise compress directly */
    if (len < state->size) {
        /* copy to input buffer, compress when full */
        do {
            if (strm->avail_in == 0)
                strm->next_in = state->in;
            n = state->size - strm->avail_in;
            if (n > len)
                n = len;
#ifdef z_const
DIAG_OFF(cast-qual)
            memcpy((Bytef *)strm->next_in + strm->avail_in, buf, n);
DIAG_ON(cast-qual)
#else /* z_const */
            memcpy(strm->next_in + strm->avail_in, buf, n);
#endif /* z_const */
            strm->avail_in += n;
            state->pos += n;
            buf = (const char *)buf + n;
            len -= n;
            if (len && gz_comp(state, Z_NO_FLUSH) == -1)
                return 0;
        } while (len);
    }
    else {
        /* consume whatever's left in the input buffer */
        if (strm->avail_in != 0 && gz_comp(state, Z_NO_FLUSH) == -1)
            return 0;

        /* directly compress user buffer to file */
        strm->avail_in = len;
#ifdef z_const
        strm->next_in = (z_const Bytef *)buf;
#else /* z_const */
DIAG_OFF(cast-qual)
        strm->next_in = (Bytef *)buf;
DIAG_ON(cast-qual)
#endif /* z_const */
        state->pos += len;
        if (gz_comp(state, Z_NO_FLUSH) == -1)
            return 0;
    }

    /* input was all buffered or compressed (put will fit in int) */
    return (int)put;
}

/* Flush out what we've written so far.  Returns -1, and sets state->err,
   on failure; returns 0 on success. */
int
gzwfile_flush(GZWFILE_T state)
{
    /* check that there's no error */
    if (state->err != Z_OK)
        return -1;

    /* compress remaining data with Z_SYNC_FLUSH */
    gz_comp(state, Z_SYNC_FLUSH);
    if (state->err != Z_OK)
        return -1;
    return 0;
}

/* Flush out all data written, and close the file.  Returns a Wiretap
   error on failure; returns 0 on success. */
int
gzwfile_close(GZWFILE_T state)
{
    int ret = 0;

    /* flush, free memory, and close file */
    if (gz_comp(state, Z_FINISH) == -1)
        ret = state->err;
    (void)ZLIB_PREFIX(deflateEnd)(&(state->strm));
    g_free(state->out);
    g_free(state->in);
    state->err = Z_OK;
    if (ws_close(state->fd) == -1 && ret == 0)
        ret = errno;
    g_free(state);
    return ret;
}

int
gzwfile_geterr(GZWFILE_T state)
{
    return state->err;
}
#endif /* USE_ZLIB_OR_ZLIBNG */

#ifdef USE_LZ4
/* internal lz4 file state data structure for writing */
struct lz4_writer {
    int fd;                 /* file descriptor */
    int64_t pos;            /* current position in uncompressed data */
    int64_t pos_out;
    size_t size_out;      /* buffer size, zero if not allocated yet */
    size_t want;          /* requested buffer size, default is LZ4BUFSIZE */
    size_t want_out;      /* requested output buffer size, determined from want */
    unsigned char *out; /* output buffer, containing uncompressed data */
    int err;                /* error code */
    const char *err_info;   /* additional error information string for some errors */
    LZ4F_preferences_t lz4_prefs;
    LZ4F_cctx *lz4_cctx;
};

LZ4WFILE_T
lz4wfile_open(const char *path)
{
    int fd;
    LZ4WFILE_T state;
    int save_errno;

    fd = ws_open(path, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0666);
    if (fd == -1)
        return NULL;
    state = lz4wfile_fdopen(fd);
    if (state == NULL) {
        save_errno = errno;
        ws_close(fd);
        errno = save_errno;
    }
    return state;
}

LZ4WFILE_T
lz4wfile_fdopen(int fd)
{
    LZ4WFILE_T state;

    /* allocate wtap_writer structure to return */
    state = (LZ4WFILE_T)g_try_malloc(sizeof *state);
    if (state == NULL)
        return NULL;
    state->fd = fd;
    state->size_out = 0;         /* no buffer allocated yet */
    state->want = LZ4BUFSIZE;    /* max input size (a block) */
    state->want_out = LZ4F_compressBound(state->want, &state->lz4_prefs);
    /*
     * This size guarantees that we will always have enough room to
     * write the result of LZ4F_compressUpdate (or Flush or End),
     * so long as the output buffer is empty (i.e., we immediately
     * write to the output file anything the compressor hands back
     * instead of buffering.)
     */

    memset(&state->lz4_prefs, 0, sizeof(LZ4F_preferences_t));
    /* Use the same prefs as the lz4 command line utility defaults. */
    state->lz4_prefs.frameInfo.blockMode = LZ4F_blockIndependent; /* Allows fast seek */
    state->lz4_prefs.frameInfo.contentChecksumFlag = 1;
    state->lz4_prefs.frameInfo.blockSizeID = LZ4F_max4MB;
    /* XXX - What should we set state->lz4_prefs.compressionLevel to?
     * The command line utility uses 1, recommends 9 as another option, and
     * also there's 12 (max).
     *
     * We could provide an API call or perhaps two or three preset options.
     */
    state->lz4_prefs.compressionLevel = 1;

    /* initialize stream */
    state->err = 0;              /* clear error */
    state->err_info = NULL;         /* clear additional error information */
    state->pos = 0;                 /* no uncompressed data yet */
    state->pos_out = 0;

    /* return stream */
    return state;
}

/* Writes len bytes from the output buffer to the file.
 * Return true on success; returns false and sets state->err on failure.
 */
static bool
lz4_write_out(LZ4WFILE_T state, size_t len)
{
    if (len > 0) {
        ssize_t got = ws_write(state->fd, state->out, len);
        if (got < 0) {
            state->err = errno;
            return false;
        }
        if ((unsigned)got != len) {
            state->err = WTAP_ERR_SHORT_WRITE;
            return false;
        }
        state->pos_out += got;
    }
    return true;
}

/* Initialize state for writing an lz4 file.  Mark initialization by setting
   state->size to non-zero.  Return -1, and set state->err and possibly
   state->err_info, on failure; return 0 on success. */
static int
lz4_init(LZ4WFILE_T state)
{
    LZ4F_errorCode_t ret;

    /* create Compression context */
    ret = LZ4F_createCompressionContext(&state->lz4_cctx, LZ4F_VERSION);
    if (LZ4F_isError(ret)) {
        state->err = WTAP_ERR_CANT_WRITE; // XXX - WTAP_ERR_COMPRESS?
        state->err_info = LZ4F_getErrorName(ret);
        return -1;
    }

    /* allocate buffer */
    state->out = (unsigned char *)g_try_malloc(state->want_out);
    if (state->out == NULL) {
        g_free(state->out);
        LZ4F_freeCompressionContext(state->lz4_cctx);
        state->err = ENOMEM;
        return -1;
    }

    ret = LZ4F_compressBegin(state->lz4_cctx, state->out, state->want_out, &state->lz4_prefs);
    if (LZ4F_isError(ret)) {
        state->err = WTAP_ERR_CANT_WRITE; // XXX - WTAP_ERR_COMPRESS?
        state->err_info = LZ4F_getErrorName(ret);
        return -1;
    }
    if (!lz4_write_out(state, ret)) {
        return -1;
    }

    /* mark state as initialized */
    state->size_out = state->want_out;

    return 0;
}

/* Write out len bytes from buf.  Return 0, and set state->err, on
   failure or on an attempt to write 0 bytes (in which case state->err
   is 0); return the number of bytes written on success. */
size_t
lz4wfile_write(LZ4WFILE_T state, const void *buf, size_t len)
{
    size_t to_write;
    size_t put = len;

    /* check that there's no error */
    if (state->err != 0)
        return 0;

    /* if len is zero, avoid unnecessary operations */
    if (len == 0)
        return 0;

    /* allocate memory if this is the first time through */
    if (state->size_out == 0 && lz4_init(state) == -1)
        return 0;

    do {
        to_write = MIN(len, state->want);
        size_t bytesWritten = LZ4F_compressUpdate(state->lz4_cctx, state->out, state->size_out,
            buf, to_write, NULL);
        if (LZ4F_isError(bytesWritten)) {
            state->err = WTAP_ERR_CANT_WRITE; // XXX - WTAP_ERR_COMPRESS?
            state->err_info = LZ4F_getErrorName(bytesWritten);
            return 0;
        }
        if (!lz4_write_out(state, bytesWritten)) {
            return 0;
        }
        state->pos += to_write;
        len -= to_write;
    } while (len);

    /* input was all buffered or compressed */
    return put;
}

/* Flush out what we've written so far.  Returns -1, and sets state->err,
   on failure; returns 0 on success. */
int
lz4wfile_flush(LZ4WFILE_T state)
{
    size_t bytesWritten;
    /* check that there's no error */
    if (state->err != 0)
        return -1;

    bytesWritten = LZ4F_flush(state->lz4_cctx, state->out, state->size_out, NULL);
    if (LZ4F_isError(bytesWritten)) {
        // Should never happen if size_out >= LZ4F_compressBound(0, prefsPtr)
        state->err = WTAP_ERR_INTERNAL;
        return -1;
    }
    if (!lz4_write_out(state, bytesWritten)) {
        return -1;
    }
    return 0;
}

/* Flush out all data written, and close the file.  Returns a Wiretap
   error on failure; returns 0 on success. */
int
lz4wfile_close(LZ4WFILE_T state)
{
    int ret = 0;

    /* flush, free memory, and close file */
    size_t bytesWritten = LZ4F_compressEnd(state->lz4_cctx, state->out, state->size_out, NULL);
    if (LZ4F_isError(bytesWritten)) {
        // Should never happen if size_out >= LZ4F_compressBound(0, prefsPtr)
        ret = WTAP_ERR_INTERNAL;
    }
    if (!lz4_write_out(state, bytesWritten)) {
        ret = state->err;
    }
    g_free(state->out);
    LZ4F_freeCompressionContext(state->lz4_cctx);
    if (ws_close(state->fd) == -1 && ret == 0)
        ret = errno;
    g_free(state);
    return ret;
}

int
lz4wfile_geterr(LZ4WFILE_T state)
{
    return state->err;
}
#endif /* USE_LZ4 */
/*
 * Editor modelines  -  https://www.wireshark.org/tools/modelines.html
 *
 * Local variables:
 * c-basic-offset: 4
 * tab-width: 8
 * indent-tabs-mode: nil
 * End:
 *
 * vi: set shiftwidth=4 tabstop=8 expandtab:
 * :indentSize=4:tabSize=8:noTabs=true:
 */