File: blf.c

package info (click to toggle)
wireshark 4.6.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 351,244 kB
  • sloc: ansic: 3,101,885; cpp: 129,710; xml: 100,972; python: 56,512; perl: 24,575; sh: 5,874; lex: 4,383; pascal: 4,304; makefile: 165; ruby: 113; objc: 91; tcl: 35
file content (5165 lines) | stat: -rw-r--r-- 203,791 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
/* blf.c
 *
 * Wiretap Library
 * Copyright (c) 1998 by Gilbert Ramirez <gram@alumni.rice.edu>
 *
 * File format support for the Binary Log File (BLF) file format from
 * Vector Informatik decoder
 * Copyright (c) 2021-2025 by Dr. Lars Völker <lars.voelker@technica-engineering.de>
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 */

 /*
  * The following was used as a reference for the file format:
  *     https://bitbucket.org/tobylorenz/vector_blf
  * The repo above includes multiple examples files as well.
  */

#include <config.h>
#define WS_LOG_DOMAIN LOG_DOMAIN_WIRETAP

#include "blf.h"

#include <epan/dissectors/packet-socketcan.h>
#include <epan/dissectors/packet-flexray.h>
#include <epan/dissectors/packet-lin.h>
#include <string.h>
#include <errno.h>
#include <wsutil/value_string.h>
#include <wiretap/wtap.h>
#include <wiretap/wtap_opttypes.h>
#include <wsutil/wslog.h>
#include <wsutil/exported_pdu_tlvs.h>
#include <wsutil/pint.h>
#include <wsutil/report_message.h>
#include <wsutil/strtoi.h>
#include <wsutil/time_util.h>
#include <wsutil/zlib_compat.h>
#include <libxml/tree.h>
#include <libxml/parser.h>
#include <libxml/xpath.h>
#include "file_wrappers.h"
#include "wtap-int.h"

static const uint8_t blf_magic[] = { 'L', 'O', 'G', 'G' };
static const uint8_t blf_obj_magic[] = { 'L', 'O', 'B', 'J' };

static const value_string blf_application_names[] = {
    { 0,    "Unknown" },
    { 1,    "Vector CANalyzer" },
    { 2,    "Vector CANoe" },
    { 3,    "Vector CANstress" },
    { 4,    "Vector CANlog" },
    { 5,    "Vector CANape" },
    { 6,    "Vector CANcaseXL log" },
    { 7,    "Vector Logger Configurator" },
    { 200,  "Porsche Logger" },
    { 201,  "CAETEC Logger" },
    { 202,  "Vector Network Simulator" },
    { 203,  "IPETRONIK logger" },
    { 204,  "RT PK" },
    { 205,  "PikeTec" },
    { 206,  "Sparks" },
    { 0, NULL }
};

static int blf_file_type_subtype = -1;

void register_blf(void);

static bool blf_read(wtap *wth, wtap_rec *rec, int *err, char **err_info, int64_t *data_offset);
static bool blf_seek_read(wtap *wth, int64_t seek_off, wtap_rec* rec, int *err, char **err_info);
static void blf_close(wtap *wth);

/*
 * The virtual buffer looks like this (skips all headers):
 * uncompressed log container data
 * uncompressed log container data
 * ...
 *
 * The "real" positions, length, etc. reference this layout and not the file.
 */
typedef struct blf_log_container {
    int64_t  infile_start_pos;        /* start position of log container in file */
    uint64_t infile_length;           /* length of log container in file */
    uint64_t infile_data_start;       /* start position of data in log container in file */

    uint64_t real_start_pos;          /* decompressed (virtual) start position including header */
    uint64_t real_length;             /* decompressed length */

    uint16_t compression_method;      /* 0: uncompressed, 2: zlib */

    unsigned char  *real_data;        /* cache for decompressed data */
} blf_log_container_t;

typedef struct blf_data {
    int64_t     start_of_last_obj;
    int64_t     current_real_seek_pos;
    uint64_t    start_offset_ns;

    GArray     *log_containers;

    GHashTable *channel_to_iface_ht;
    GHashTable *channel_to_name_ht;
    uint32_t    next_interface_id;
} blf_t;

typedef struct blf_params {
    wtap     *wth;
    wtap_rec *rec;
    FILE_T    fh;
    bool      random;
    bool      pipe;

    blf_t    *blf_data;
} blf_params_t;

typedef struct blf_channel_to_iface_entry {
    int             pkt_encap;
    uint16_t        channel;
    uint16_t        hwchannel;
    uint32_t        interface_id;
} blf_channel_to_iface_entry_t;

typedef struct blf_metadata_info {
    size_t  metadata_cont;
    size_t  payload_start;
    bool    valid;
} blf_metadata_info_t;

static void
blf_free_key(void *key) {
    g_free(key);
}

static void
blf_free_channel_to_iface_entry(void *data) {
     g_free(data);
}

static void
blf_free_channel_to_name_entry(void *data) {
    g_free(data);
}

static int64_t
blf_calc_key_value(int pkt_encap, uint16_t channel, uint16_t hwchannel) {
    return (int64_t)(((uint64_t)pkt_encap << 32) | ((uint64_t)hwchannel << 16) | (uint64_t)channel);
}

/** Return the Epoch ns time of the capture start
 *
 * This is not intended to fully validate the date and time,
 * but just to check if the values are plausible.
 */
static uint64_t
blf_get_start_offset_ns(const blf_date_t* start_date) {
    struct tm timestamp;
    time_t start_offset_s;

    if (start_date != NULL &&
        (start_date->month >= 1 && start_date->month <= 12) &&
        (start_date->day >= 1 && start_date->day <= 31) &&
        (start_date->hour <= 23) && (start_date->mins <= 59) &&
        (start_date->sec <= 61)  /* Apparently can be up to 61 on certain systems */
        ) { /* Not checking if milliseconds are actually less than 1000 */
        timestamp.tm_year = (start_date->year > 1970) ? start_date->year - 1900 : 70;
        timestamp.tm_mon = start_date->month - 1;
        timestamp.tm_mday = start_date->day;
        timestamp.tm_hour = start_date->hour;
        timestamp.tm_min = start_date->mins;
        timestamp.tm_sec = start_date->sec;
        timestamp.tm_isdst = -1;
        start_offset_s = mktime(&timestamp);
        if (start_offset_s >= 0) {
            return (1000 * 1000 * (start_date->ms + (1000 * (uint64_t)start_offset_s)));
        }
    }

    return 0;
}

static void add_interface_name(wtap_block_t int_data, int pkt_encap, uint16_t channel, uint16_t hwchannel, char *name) {
    if (name != NULL) {
        wtap_block_add_string_option_format(int_data, OPT_IDB_NAME, "%s", name);
    } else {
        switch (pkt_encap) {
        case WTAP_ENCAP_ETHERNET:
            /* we use UINT16_MAX to encode no hwchannel */
            if (hwchannel == UINT16_MAX) {
                wtap_block_add_string_option_format(int_data, OPT_IDB_NAME, "ETH-%u", channel);
            } else {
                wtap_block_add_string_option_format(int_data, OPT_IDB_NAME, "ETH-%u-%u", channel, hwchannel);
            }
            break;
        case WTAP_ENCAP_IEEE_802_11:
            wtap_block_add_string_option_format(int_data, OPT_IDB_NAME, "WLAN-%u", channel);
            break;
        case WTAP_ENCAP_FLEXRAY:
            wtap_block_add_string_option_format(int_data, OPT_IDB_NAME, "FR-%u", channel);
            break;
        case WTAP_ENCAP_LIN:
            wtap_block_add_string_option_format(int_data, OPT_IDB_NAME, "LIN-%u", channel);
            break;
        case WTAP_ENCAP_SOCKETCAN:
            wtap_block_add_string_option_format(int_data, OPT_IDB_NAME, "CAN-%u", channel);
            break;
        default:
            wtap_block_add_string_option_format(int_data, OPT_IDB_NAME, "ENCAP_%d-%u", pkt_encap, channel);
        }
    }

    /* Add a defined description format to recover the original channel/hwchannel mapping, when we ever convert back to BLF */
    /* Changing the names might break the BLF writing! */
    switch (pkt_encap) {
    case WTAP_ENCAP_ETHERNET:
        wtap_block_add_string_option_format(int_data, OPT_IDB_DESCRIPTION, "BLF-ETH-0x%04x-0x%04x", channel, hwchannel);
        break;
    case WTAP_ENCAP_IEEE_802_11:
        wtap_block_add_string_option_format(int_data, OPT_IDB_DESCRIPTION, "BLF-WLAN-0x%04x", channel);
        break;
    case WTAP_ENCAP_FLEXRAY:
        wtap_block_add_string_option_format(int_data, OPT_IDB_DESCRIPTION, "BLF-FR-0x%04x", channel);
        break;
    case WTAP_ENCAP_LIN:
        wtap_block_add_string_option_format(int_data, OPT_IDB_DESCRIPTION, "BLF-LIN-0x%04x", channel);
        break;
    case WTAP_ENCAP_SOCKETCAN:
        wtap_block_add_string_option_format(int_data, OPT_IDB_DESCRIPTION, "BLF-CAN-0x%04x", channel);
        break;
    default:
        wtap_block_add_string_option_format(int_data, OPT_IDB_DESCRIPTION, "BLF-ENCAP_%d-0x%04x-0x%04x", pkt_encap, channel, hwchannel);
    }
}

static uint32_t
blf_add_interface(blf_params_t *params, int pkt_encap, uint32_t channel, uint16_t hwchannel, char *name) {
    wtap_block_t int_data = wtap_block_create(WTAP_BLOCK_IF_ID_AND_INFO);
    wtapng_if_descr_mandatory_t *if_descr_mand = (wtapng_if_descr_mandatory_t*)wtap_block_get_mandatory_data(int_data);
    blf_channel_to_iface_entry_t *item = NULL;

    if_descr_mand->wtap_encap = pkt_encap;
    add_interface_name(int_data, pkt_encap, channel, hwchannel, name);
    /*
     * The time stamp resolution in these files can be per-record;
     * the maximum resolution is nanoseconds, so we specify that
     * as the interface's resolution.
     *
     * We set the resolution for a record on a per-record basis,
     * based on what the record specifies.
     */
    if_descr_mand->time_units_per_second = 1000 * 1000 * 1000;
    if_descr_mand->tsprecision = WTAP_TSPREC_NSEC;
    wtap_block_add_uint8_option(int_data, OPT_IDB_TSRESOL, 9);
    if_descr_mand->snap_len = WTAP_MAX_PACKET_SIZE_STANDARD;
    if_descr_mand->num_stat_entries = 0;
    if_descr_mand->interface_statistics = NULL;
    wtap_add_idb(params->wth, int_data);

    if (params->wth->file_encap == WTAP_ENCAP_NONE) {
        params->wth->file_encap = if_descr_mand->wtap_encap;
    } else {
        if (params->wth->file_encap != if_descr_mand->wtap_encap) {
            params->wth->file_encap = WTAP_ENCAP_PER_PACKET;
        }
    }

    int64_t *key = NULL;
    key = g_new(int64_t, 1);
    *key = blf_calc_key_value(pkt_encap, channel, hwchannel);

    item = g_new(blf_channel_to_iface_entry_t, 1);
    item->channel = channel;
    item->hwchannel = hwchannel;
    item->pkt_encap = pkt_encap;
    item->interface_id = params->blf_data->next_interface_id++;
    g_hash_table_insert(params->blf_data->channel_to_iface_ht, key, item);

    return item->interface_id;
}

/** This is used to save the interface name without creating it.
 *
 * This approach allows up to update the name of the interface
 * up until the first captured packet.
 */
static bool
// NOLINTNEXTLINE(misc-no-recursion)
blf_prepare_interface_name(blf_params_t* params, int pkt_encap, uint16_t channel, uint16_t hwchannel, const char* name, bool force_new_name) {
    int64_t key = blf_calc_key_value(pkt_encap, channel, hwchannel);
    char* old_name;
    char* new_name;
    char* iface_name;
    int64_t* new_key;
    bool ret;

    if (params->blf_data->channel_to_name_ht == NULL) {
        return false;
    }

    old_name = (char *)g_hash_table_lookup(params->blf_data->channel_to_name_ht, &key);

    if (old_name != NULL && force_new_name) {
        if (!g_hash_table_remove(params->blf_data->channel_to_name_ht, &key)) {
            return false;
        }

        old_name = NULL;
    }

    if (old_name == NULL && name != NULL) {
        new_key = g_new(int64_t, 1);
        *new_key = key;
        new_name = ws_strdup(name);
        if (!g_hash_table_insert(params->blf_data->channel_to_name_ht, new_key, new_name)) {
            return false;
        }
    }
    else {
        new_name = old_name;
    }

    if (pkt_encap == WTAP_ENCAP_ETHERNET) {
        /* Just for Ethernet, prepare the equivalent STATUS interface */
        iface_name = new_name != NULL ? ws_strdup_printf("STATUS-%s", new_name) : NULL;

        // We recurse here once.
        ret = blf_prepare_interface_name(params, WTAP_ENCAP_WIRESHARK_UPPER_PDU, channel, hwchannel, iface_name, force_new_name);
        if (iface_name) {
            g_free(iface_name);
        }
        if (!ret) {
            return false;
        }
    }

    return true;
}

static uint32_t
blf_lookup_interface(blf_params_t *params, int pkt_encap, uint16_t channel, uint16_t hwchannel, char *name) {
    int64_t key = blf_calc_key_value(pkt_encap, channel, hwchannel);
    blf_channel_to_iface_entry_t* item;
    char* saved_name;
    uint32_t ret;

    if (params->blf_data->channel_to_iface_ht == NULL) {
        return 0;
    }

    item = (blf_channel_to_iface_entry_t *)g_hash_table_lookup(params->blf_data->channel_to_iface_ht, &key);

    if (item != NULL) {
        return item->interface_id;
    }
    else {
        saved_name = (char*)g_hash_table_lookup(params->blf_data->channel_to_name_ht, &key);

        if (saved_name != NULL) {
            ret = blf_add_interface(params, pkt_encap, channel, hwchannel, saved_name);
            g_hash_table_remove(params->blf_data->channel_to_name_ht, &key);

            return ret;
        }
        else {
            return blf_add_interface(params, pkt_encap, channel, hwchannel, name);
        }
    }
}

static void
fix_endianness_blf_date(blf_date_t *date) {
    date->year = GUINT16_FROM_LE(date->year);
    date->month = GUINT16_FROM_LE(date->month);
    date->dayofweek = GUINT16_FROM_LE(date->dayofweek);
    date->day = GUINT16_FROM_LE(date->day);
    date->hour = GUINT16_FROM_LE(date->hour);
    date->mins = GUINT16_FROM_LE(date->mins);
    date->sec = GUINT16_FROM_LE(date->sec);
    date->ms = GUINT16_FROM_LE(date->ms);
}

static void
fix_endianness_blf_fileheader(blf_fileheader_t *header) {
    header->header_length = GUINT32_FROM_LE(header->header_length);
    header->api_version = GUINT32_FROM_LE(header->api_version);
    header->len_compressed = GUINT64_FROM_LE(header->len_compressed);
    header->len_uncompressed = GUINT64_FROM_LE(header->len_uncompressed);
    header->obj_count = GUINT32_FROM_LE(header->obj_count);
    header->application_build = GUINT32_FROM_LE(header->application_build);
    fix_endianness_blf_date(&(header->start_date));
    fix_endianness_blf_date(&(header->end_date));
    header->restore_point_offset = GUINT32_FROM_LE(header->restore_point_offset);
}

static void
fix_endianness_blf_blockheader(blf_blockheader_t *header) {
    header->header_length = GUINT16_FROM_LE(header->header_length);
    header->header_type = GUINT16_FROM_LE(header->header_type);
    header->object_length = GUINT32_FROM_LE(header->object_length);
    header->object_type = GUINT32_FROM_LE(header->object_type);
}

static void
fix_endianness_blf_logcontainerheader(blf_logcontainerheader_t *header) {
    header->compression_method = GUINT16_FROM_LE(header->compression_method);
    header->res1 = GUINT16_FROM_LE(header->res1);
    header->res2 = GUINT32_FROM_LE(header->res2);
    header->uncompressed_size = GUINT32_FROM_LE(header->uncompressed_size);
    header->res4 = GUINT32_FROM_LE(header->res4);
}

static void
fix_endianness_blf_logobjectheader(blf_logobjectheader_t *header) {
    header->flags = GUINT32_FROM_LE(header->flags);
    header->client_index = GUINT16_FROM_LE(header->client_index);
    header->object_version = GUINT16_FROM_LE(header->object_version);
    header->object_timestamp = GUINT64_FROM_LE(header->object_timestamp);
}

static void
fix_endianness_blf_logobjectheader2(blf_logobjectheader2_t *header) {
    header->flags = GUINT32_FROM_LE(header->flags);
    header->object_version = GUINT16_FROM_LE(header->object_version);
    header->object_timestamp = GUINT64_FROM_LE(header->object_timestamp);
    header->original_timestamp = GUINT64_FROM_LE(header->object_timestamp);
}

static void
fix_endianness_blf_logobjectheader3(blf_logobjectheader3_t *header) {
    header->flags = GUINT32_FROM_LE(header->flags);
    header->static_size = GUINT16_FROM_LE(header->static_size);
    header->object_version = GUINT16_FROM_LE(header->object_version);
    header->object_timestamp = GUINT64_FROM_LE(header->object_timestamp);
}

static void
fix_endianness_blf_ethernetframeheader(blf_ethernetframeheader_t *header) {
    header->channel = GUINT16_FROM_LE(header->channel);
    header->direction = GUINT16_FROM_LE(header->direction);
    header->ethtype = GUINT16_FROM_LE(header->ethtype);
    header->tpid = GUINT16_FROM_LE(header->tpid);
    header->tci = GUINT16_FROM_LE(header->tci);
    header->payloadlength = GUINT16_FROM_LE(header->payloadlength);
}

static void
fix_endianness_blf_ethernetframeheader_ex(blf_ethernetframeheader_ex_t *header) {
    header->struct_length = GUINT16_FROM_LE(header->struct_length);
    header->flags = GUINT16_FROM_LE(header->flags);
    header->channel = GUINT16_FROM_LE(header->channel);
    header->hw_channel = GUINT16_FROM_LE(header->hw_channel);
    header->frame_duration = GUINT64_FROM_LE(header->frame_duration);
    header->frame_checksum = GUINT32_FROM_LE(header->frame_checksum);
    header->direction = GUINT16_FROM_LE(header->direction);
    header->frame_length = GUINT16_FROM_LE(header->frame_length);
    header->frame_handle = GUINT32_FROM_LE(header->frame_handle);
    header->error = GUINT32_FROM_LE(header->error);
}

static void
fix_endianness_blf_ethernet_rxerror(blf_ethernet_rxerror_t* header) {
    header->struct_length = GUINT16_FROM_LE(header->struct_length);
    header->channel = GUINT16_FROM_LE(header->channel);
    header->direction = GUINT16_FROM_LE(header->direction);
    header->hw_channel = GUINT16_FROM_LE(header->hw_channel);
    header->frame_checksum = GUINT32_FROM_LE(header->frame_checksum);
    header->frame_length = GUINT16_FROM_LE(header->frame_length);
    header->error = GUINT32_FROM_LE(header->error);
}

static void
fix_endianness_blf_wlanframeheader(blf_wlanframeheader_t* header) {
    header->channel = GUINT16_FROM_LE(header->channel);
    header->flags = GUINT16_FROM_LE(header->flags);
    header->signal_strength = GUINT16_FROM_LE(header->signal_strength);
    header->signal_quality = GUINT16_FROM_LE(header->signal_quality);
    header->frame_length = GUINT16_FROM_LE(header->frame_length);
}

static void
fix_endianness_blf_canmessage(blf_canmessage_t *header) {
    header->channel = GUINT16_FROM_LE(header->channel);
    header->id = GUINT32_FROM_LE(header->id);
}

static void
fix_endianness_blf_canmessage2_trailer(blf_canmessage2_trailer_t *header) {
    header->frameLength_in_ns = GUINT32_FROM_LE(header->frameLength_in_ns);
    header->reserved2 = GUINT16_FROM_LE(header->reserved1);
}

static void
fix_endianness_blf_canfdmessage(blf_canfdmessage_t *header) {
    header->channel = GUINT16_FROM_LE(header->channel);
    header->id = GUINT32_FROM_LE(header->id);
    header->frameLength_in_ns = GUINT32_FROM_LE(header->frameLength_in_ns);
    header->reservedCanFdMessage2 = GUINT32_FROM_LE(header->reservedCanFdMessage2);
}

static void
fix_endianness_blf_canfdmessage64(blf_canfdmessage64_t *header) {
    header->id = GUINT32_FROM_LE(header->id);
    header->frameLength_in_ns = GUINT32_FROM_LE(header->frameLength_in_ns);
    header->flags = GUINT32_FROM_LE(header->flags);
    header->btrCfgArb = GUINT32_FROM_LE(header->btrCfgArb);
    header->btrCfgData = GUINT32_FROM_LE(header->btrCfgData);
    header->timeOffsetBrsNs = GUINT32_FROM_LE(header->timeOffsetBrsNs);
    header->timeOffsetCrcDelNs = GUINT32_FROM_LE(header->timeOffsetCrcDelNs);
    header->bitCount = GUINT16_FROM_LE(header->bitCount);
    header->crc = GUINT32_FROM_LE(header->crc);
}

static void
fix_endianness_blf_canerror(blf_canerror_t *header) {
    header->channel = GUINT16_FROM_LE(header->channel);
    header->length = GUINT16_FROM_LE(header->length);
}

static void
fix_endianness_blf_canerrorext(blf_canerrorext_t *header) {
    header->channel = GUINT16_FROM_LE(header->channel);
    header->length = GUINT16_FROM_LE(header->length);
    header->flags = GUINT32_FROM_LE(header->flags);
    header->frameLength_in_ns = GUINT32_FROM_LE(header->frameLength_in_ns);
    header->id = GUINT32_FROM_LE(header->id);
    header->errorCodeExt = GUINT16_FROM_LE(header->errorCodeExt);
}

static void
fix_endianness_blf_canfderror64(blf_canfderror64_t *header) {
    header->flags = GUINT16_FROM_LE(header->flags);
    header->errorCodeExt = GUINT16_FROM_LE(header->errorCodeExt);
    header->extFlags = GUINT16_FROM_LE(header->extFlags);
    header->id = GUINT32_FROM_LE(header->id);
    header->frameLength_in_ns = GUINT32_FROM_LE(header->frameLength_in_ns);
    header->btrCfgArb = GUINT32_FROM_LE(header->btrCfgArb);
    header->btrCfgData = GUINT32_FROM_LE(header->btrCfgData);
    header->timeOffsetBrsNs = GUINT32_FROM_LE(header->timeOffsetBrsNs);
    header->timeOffsetCrcDelNs = GUINT32_FROM_LE(header->timeOffsetCrcDelNs);
    header->crc = GUINT32_FROM_LE(header->crc);
    header->errorPosition = GUINT16_FROM_LE(header->errorPosition);
}

static void
fix_endianness_blf_flexraydata(blf_flexraydata_t *header) {
    header->channel = GUINT16_FROM_LE(header->channel);
    header->messageId = GUINT16_FROM_LE(header->messageId);
    header->crc = GUINT16_FROM_LE(header->crc);
    header->reservedFlexRayData2 = GUINT16_FROM_LE(header->reservedFlexRayData2);
}

static void
fix_endianness_blf_flexraymessage(blf_flexraymessage_t *header) {
    header->channel = GUINT16_FROM_LE(header->channel);
    header->fpgaTick = GUINT32_FROM_LE(header->fpgaTick);
    header->fpgaTickOverflow = GUINT32_FROM_LE(header->fpgaTickOverflow);
    header->clientIndexFlexRayV6Message = GUINT32_FROM_LE(header->clientIndexFlexRayV6Message);
    header->clusterTime = GUINT32_FROM_LE(header->clusterTime);
    header->frameId = GUINT16_FROM_LE(header->frameId);
    header->headerCrc = GUINT16_FROM_LE(header->headerCrc);
    header->frameState = GUINT16_FROM_LE(header->frameState);
    header->reservedFlexRayV6Message2 = GUINT16_FROM_LE(header->reservedFlexRayV6Message2);
}

static void
fix_endianness_blf_flexrayrcvmessage(blf_flexrayrcvmessage_t *header) {
    header->channel = GUINT16_FROM_LE(header->channel);
    header->version = GUINT16_FROM_LE(header->version);
    header->channelMask = GUINT16_FROM_LE(header->channelMask);
    header->dir = GUINT16_FROM_LE(header->dir);
    header->clientIndex = GUINT32_FROM_LE(header->clientIndex);
    header->clusterNo = GUINT32_FROM_LE(header->clusterNo);
    header->frameId = GUINT16_FROM_LE(header->frameId);
    header->headerCrc1 = GUINT16_FROM_LE(header->headerCrc1);
    header->headerCrc2 = GUINT16_FROM_LE(header->headerCrc2);
    header->payloadLength = GUINT16_FROM_LE(header->payloadLength);
    header->payloadLengthValid = GUINT16_FROM_LE(header->payloadLengthValid);
    header->cycle = GUINT16_FROM_LE(header->cycle);
    header->tag = GUINT32_FROM_LE(header->tag);
    header->data = GUINT32_FROM_LE(header->data);
    header->frameFlags = GUINT32_FROM_LE(header->frameFlags);
    header->appParameter = GUINT32_FROM_LE(header->appParameter);
/*  this would be extra for ext format:
    header->frameCRC = GUINT32_FROM_LE(header->frameCRC);
    header->frameLengthInNs = GUINT32_FROM_LE(header->frameLengthInNs);
    header->frameId1 = GUINT16_FROM_LE(header->frameId1);
    header->pduOffset = GUINT16_FROM_LE(header->pduOffset);
    header->blfLogMask = GUINT16_FROM_LE(header->blfLogMask);
*/
}

static void
fix_endianness_blf_linmessage(blf_linmessage_t* message) {
    message->channel = GUINT16_FROM_LE(message->channel);
    message->crc = GUINT16_FROM_LE(message->crc);
/*  skip the optional part
    message->res2 = GUINT32_FROM_LE(message->res2);
*/
}

static void
fix_endianness_blf_linbusevent(blf_linbusevent_t* linbusevent) {
    linbusevent->sof = GUINT64_FROM_LE(linbusevent->sof);
    linbusevent->eventBaudrate = GUINT32_FROM_LE(linbusevent->eventBaudrate);
    linbusevent->channel = GUINT16_FROM_LE(linbusevent->channel);
}

static void
fix_endianness_blf_linsynchfieldevent(blf_linsynchfieldevent_t* linsynchfieldevent) {
    fix_endianness_blf_linbusevent(&linsynchfieldevent->linBusEvent);
    linsynchfieldevent->synchBreakLength = GUINT64_FROM_LE(linsynchfieldevent->synchBreakLength);
    linsynchfieldevent->synchDelLength = GUINT64_FROM_LE(linsynchfieldevent->synchDelLength);
}

static void
fix_endianness_blf_linmessagedescriptor(blf_linmessagedescriptor_t* linmessagedescriptor) {
    fix_endianness_blf_linsynchfieldevent(&linmessagedescriptor->linSynchFieldEvent);
    linmessagedescriptor->supplierId = GUINT16_FROM_LE(linmessagedescriptor->supplierId);
    linmessagedescriptor->messageId = GUINT16_FROM_LE(linmessagedescriptor->messageId);
}

static void
fix_endianness_blf_lindatabytetimestampevent(blf_lindatabytetimestampevent_t* lindatabytetimestampevent) {
    int i;
    fix_endianness_blf_linmessagedescriptor(&lindatabytetimestampevent->linMessageDescriptor);
    for (i = 0; i < 9; i++) {
        lindatabytetimestampevent->databyteTimestamps[i] = GUINT64_FROM_LE(lindatabytetimestampevent->databyteTimestamps[i]);
    }
}

static void
fix_endianness_blf_linmessage2(blf_linmessage2_t* message) {
    fix_endianness_blf_lindatabytetimestampevent(&message->linDataByteTimestampEvent);
    message->crc = GUINT16_FROM_LE(message->crc);
/*  skip the optional part
    message->respBaudrate = GUINT32_FROM_LE(message->respBaudrate);
    message->exactHeaderBaudrate = GUINT64_FROM_LE(message->exactHeaderBaudrate);
    message->earlyStopBitOffset = GUINT32_FROM_LE(message->earlyStopBitOffset);
    message->earlyStopBitOffsetResponse = GUINT32_FROM_LE(message->earlyStopBitOffsetResponse);
*/
}

static void
fix_endianness_blf_lincrcerror2(blf_lincrcerror2_t* message) {
    fix_endianness_blf_lindatabytetimestampevent(&message->linDataByteTimestampEvent);
    message->crc = GUINT16_FROM_LE(message->crc);
/*  skip the optional part
    message->respBaudrate = GUINT32_FROM_LE(message->respBaudrate);
    message->exactHeaderBaudrate = GUINT64_FROM_LE(message->exactHeaderBaudrate);
    message->earlyStopBitOffset = GUINT32_FROM_LE(message->earlyStopBitOffset);
    message->earlyStopBitOffsetResponse = GUINT32_FROM_LE(message->earlyStopBitOffsetResponse);
*/
}

static void
fix_endianness_blf_linrcverror2(blf_linrcverror2_t* message) {
    fix_endianness_blf_lindatabytetimestampevent(&message->linDataByteTimestampEvent);
/*  skip the optional part
    message->respBaudrate = GUINT32_FROM_LE(message->respBaudrate);
    message->exactHeaderBaudrate = GUINT64_FROM_LE(message->exactHeaderBaudrate);
    message->earlyStopBitOffset = GUINT32_FROM_LE(message->earlyStopBitOffset);
    message->earlyStopBitOffsetResponse = GUINT32_FROM_LE(message->earlyStopBitOffsetResponse);
*/
}

static void
fix_endianness_blf_linsenderror2(blf_linsenderror2_t* message) {
    fix_endianness_blf_linmessagedescriptor(&message->linMessageDescriptor);
    message->eoh = GUINT64_FROM_LE(message->eoh);
/*  skip the optional part
    message->exactHeaderBaudrate = GUINT64_FROM_LE(message->exactHeaderBaudrate);
    message->earlyStopBitOffset = GUINT32_FROM_LE(message->earlyStopBitOffset);
*/
}

static void
fix_endianness_blf_linwakeupevent2(blf_linwakeupevent2_t* message) {
    fix_endianness_blf_linbusevent(&message->linBusEvent);
}

static void
fix_endianness_blf_apptext_header(blf_apptext_t *header) {
    header->source = GUINT32_FROM_LE(header->source);
    header->reservedAppText1 = GUINT32_FROM_LE(header->reservedAppText1);
    header->textLength = GUINT32_FROM_LE(header->textLength);
    header->reservedAppText2 = GUINT32_FROM_LE(header->reservedAppText2);
}

static void
fix_endianness_blf_ethernet_status_header(blf_ethernet_status_t* header) {
    header->channel = GUINT16_FROM_LE(header->channel);
    header->flags = GUINT16_FROM_LE(header->flags);
    /*uint8_t linkStatus;*/
    /*uint8_t ethernetPhy;*/
    /*uint8_t duplex;*/
    /*uint8_t mdi;*/
    /*uint8_t connector;*/
    /*uint8_t clockMode;*/
    /*uint8_t pairs;*/
    /*uint8_t hardwareChannel;*/
    header->bitrate = GUINT32_FROM_LE(header->bitrate);
}

static void
fix_endianness_blf_ethernet_phystate_header(blf_ethernet_phystate_t* header) {
    header->channel = GUINT16_FROM_LE(header->channel);
    header->flags = GUINT16_FROM_LE(header->flags);
}

static void
blf_init_logcontainer(blf_log_container_t *tmp) {
    tmp->infile_start_pos = 0;
    tmp->infile_length = 0;
    tmp->infile_data_start = 0;
    tmp->real_start_pos = 0;
    tmp->real_length = 0;
    tmp->real_data = NULL;
    tmp->compression_method = 0;
}

int
blf_logcontainers_cmp(const void *a, const void *b) {
    const blf_log_container_t* container_a = (blf_log_container_t*)a;
    const blf_log_container_t* container_b = (blf_log_container_t*)b;

    if (container_a->real_start_pos < container_b->real_start_pos) {
        return -1;
    }
    else if (container_a->real_start_pos > container_b->real_start_pos) {
        return 1;
    }
    else {
        return 0;
    }
}

int
blf_logcontainers_search(const void *a, const void *b) {
    const blf_log_container_t* container_a = (blf_log_container_t*)a;
    uint64_t pos = *(uint64_t*)b;

    if (container_a->real_start_pos > pos) {
        return 1;
    }
    else if (pos >= container_a->real_start_pos + container_a->real_length) {
        return -1;
    }
    else {
        return 0;
    }
}

/** Ensures the given log container is in memory
 *
 * If the log container already is not already in memory,
 * it reads it from the current seek position, allocating a
 * properly sized buffer.
 * The file offset must be set to the start of the container
 * data (container->infile_data_start) before calling this function.
 */
static bool
blf_pull_logcontainer_into_memory(blf_params_t *params, blf_log_container_t *container, int *err, char **err_info) {

    if (container == NULL) {
        *err = WTAP_ERR_INTERNAL;
        *err_info = ws_strdup("blf_pull_logcontainer_into_memory called with NULL container");
        return false;
    }

    if (container->real_data != NULL) {
        return true;
    }

    /* pull compressed data into buffer */
    if (container->infile_start_pos < 0) {
        /*
         * XXX - does this represent a bug (WTAP_ERR_INTERNAL) or a
         * malformed file (WTAP_ERR_BAD_FILE)?
         */
        *err = WTAP_ERR_INTERNAL;
        *err_info = ws_strdup_printf("blf_pull_logcontainer_into_memory: container.infile_start_pos (%" PRId64 ") < 0",
            container->infile_start_pos);
        return false;
    }
    if (container->infile_data_start < (uint64_t)container->infile_start_pos) {
        /*
         * XXX - does this represent a bug (WTAP_ERR_INTERNAL) or a
         * malformed file (WTAP_ERR_BAD_FILE)?
         */
        *err = WTAP_ERR_INTERNAL;
        *err_info = ws_strdup_printf("blf_pull_logcontainer_into_memory: container.infile_data_start (%" PRIu64 ") < container.infile_start_pos (%" PRId64 ")",
            container->infile_data_start, container->infile_start_pos);
        return false;
    }
    if (container->infile_length < container->infile_data_start - (uint64_t)container->infile_start_pos) {
        /*
         * XXX - does this represent a bug (WTAP_ERR_INTERNAL) or a
         * malformed file (WTAP_ERR_BAD_FILE)?
         */
        *err = WTAP_ERR_INTERNAL;
        *err_info = ws_strdup_printf("blf_pull_logcontainer_into_memory: container.infile_length (%" PRIu64 ") < (container.infile_data_start (%" PRIu64 ") - container.infile_start_pos (%" PRId64 ")) = %" PRIu64,
            container->infile_length,
            container->infile_data_start, container->infile_start_pos,
            container->infile_data_start - (uint64_t)container->infile_start_pos);
        return false;
    }
    uint64_t data_length = container->infile_length - (container->infile_data_start - (uint64_t)container->infile_start_pos);
    if (data_length > UINT_MAX) {
        /*
         * XXX - does this represent a bug (WTAP_ERR_INTERNAL) or a
         * malformed file (WTAP_ERR_BAD_FILE)?
         */
        *err = WTAP_ERR_INTERNAL;
        *err_info = ws_strdup_printf("blf_pull_logcontainer_into_memory: data_length (%" PRIu64 ") > UINT_MAX",
            data_length);
        return false;
    }

    if (container->real_length == 0) {
        ws_info("blf_pull_logcontainer_into_memory: found container with 0 length");
        /* Skip empty container */
        if (!wtap_read_bytes_or_eof(params->fh, NULL, (unsigned int)data_length, err, err_info)) {
            if (*err == WTAP_ERR_SHORT_READ) {
                /*
                 * XXX - our caller will turn this into an EOF.
                 * How *should* it be treated?
                 * For now, we turn it into Yet Another Internal Error,
                 * pending having better documentation of the file
                 * format.
                 */
                *err = WTAP_ERR_INTERNAL;
                *err_info = ws_strdup("blf_pull_logcontainer_into_memory: short read on 0-length container");
            }
            return false;
        }
        return true;
    }

    if (container->compression_method == BLF_COMPRESSION_NONE) {
        unsigned char* buf = g_try_malloc((size_t)container->real_length);
        if (buf == NULL) {
            *err = WTAP_ERR_INTERNAL;
            *err_info = ws_strdup("blf_pull_logcontainer_into_memory: cannot allocate memory");
            return false;
        }
        if (!wtap_read_bytes_or_eof(params->fh, buf, (unsigned int)data_length, err, err_info)) {
            g_free(buf);
            if (*err == WTAP_ERR_SHORT_READ) {
                /*
                 * XXX - our caller will turn this into an EOF.
                 * How *should* it be treated?
                 * For now, we turn it into Yet Another Internal Error,
                 * pending having better documentation of the file
                 * format.
                 */
                *err = WTAP_ERR_INTERNAL;
                *err_info = ws_strdup("blf_pull_logcontainer_into_memory: short read on uncompressed data");
            }
            return false;
        }
        container->real_data = buf;
        return true;

    }
    else if (container->compression_method == BLF_COMPRESSION_ZLIB) {
#ifdef USE_ZLIB_OR_ZLIBNG
        unsigned char *compressed_data = g_try_malloc((size_t)data_length);
        if (compressed_data == NULL) {
            *err = WTAP_ERR_INTERNAL;
            *err_info = ws_strdup("blf_pull_logcontainer_into_memory: cannot allocate memory");
            return false;
        }
        if (!wtap_read_bytes_or_eof(params->fh, compressed_data, (unsigned int)data_length, err, err_info)) {
            g_free(compressed_data);
            if (*err == WTAP_ERR_SHORT_READ) {
                /*
                 * XXX - our caller will turn this into an EOF.
                 * How *should* it be treated?
                 * For now, we turn it into Yet Another Internal Error,
                 * pending having better documentation of the file
                 * format.
                 */
                *err = WTAP_ERR_INTERNAL;
                *err_info = ws_strdup("blf_pull_logcontainer_into_memory: short read on compressed data");
            }
            return false;
        }

        unsigned char *buf = g_try_malloc((size_t)container->real_length);
        if (buf == NULL) {
            g_free(compressed_data);
            *err = WTAP_ERR_INTERNAL;
            *err_info = ws_strdup("blf_pull_logcontainer_into_memory: cannot allocate memory");
            return false;
        }
        zlib_stream infstream = {0};

        infstream.avail_in  = (unsigned int)data_length;
        infstream.next_in   = compressed_data;
        infstream.avail_out = (unsigned int)container->real_length;
        infstream.next_out  = buf;

        /* the actual DE-compression work. */
        if (Z_OK != ZLIB_PREFIX(inflateInit)(&infstream)) {
            /*
             * XXX - check the error code and handle this appropriately.
             */
            g_free(buf);
            g_free(compressed_data);
            *err = WTAP_ERR_INTERNAL;
            if (infstream.msg != NULL) {
                *err_info = ws_strdup_printf("blf_pull_logcontainer_into_memory: inflateInit failed for LogContainer, message\"%s\"",
                                              infstream.msg);
            } else {
                *err_info = ws_strdup("blf_pull_logcontainer_into_memory: inflateInit failed for LogContainer");
            }
            ws_debug("inflateInit failed for LogContainer");
            if (infstream.msg != NULL) {
                ws_debug("inflateInit returned: \"%s\"", infstream.msg);
            }
            return false;
        }

        int ret = ZLIB_PREFIX(inflate)(&infstream, Z_NO_FLUSH);
        /* Z_OK should not happen here since we know how big the buffer should be */
        if (Z_STREAM_END != ret) {
            switch (ret) {

            case Z_NEED_DICT:
                *err = WTAP_ERR_DECOMPRESS;
                *err_info = ws_strdup("preset dictionary needed");
                break;

            case Z_STREAM_ERROR:
                *err = WTAP_ERR_INTERNAL;
                *err_info = ws_strdup_printf("blf_pull_logcontainer_into_memory: Z_STREAM_ERROR from inflate(), message \"%s\"",
                                             (infstream.msg != NULL) ? infstream.msg : "(none)");
                break;

            case Z_MEM_ERROR:
                /* This means "not enough memory". */
                *err = ENOMEM;
                *err_info = NULL;
                break;

            case Z_DATA_ERROR:
                /* This means "deflate stream invalid" */
                *err = WTAP_ERR_DECOMPRESS;
                *err_info = (infstream.msg != NULL) ? ws_strdup(infstream.msg) : NULL;
                break;

            case Z_BUF_ERROR:
                /* XXX - this is recoverable; what should we do here? */
                *err = WTAP_ERR_INTERNAL;
                *err_info = ws_strdup_printf("blf_pull_logcontainer_into_memory: Z_BUF_ERROR from inflate(), message \"%s\"",
                                             (infstream.msg != NULL) ? infstream.msg : "(none)");
                break;

            case Z_VERSION_ERROR:
                *err = WTAP_ERR_INTERNAL;
                *err_info = ws_strdup_printf("blf_pull_logcontainer_into_memory: Z_VERSION_ERROR from inflate(), message \"%s\"",
                                             (infstream.msg != NULL) ? infstream.msg : "(none)");
                break;

            default:
                *err = WTAP_ERR_INTERNAL;
                *err_info = ws_strdup_printf("blf_pull_logcontainer_into_memory: unexpected error %d from inflate(), message \"%s\"",
                                             ret,
                                             (infstream.msg != NULL) ? infstream.msg : "(none)");
                break;
            }
            g_free(buf);
            g_free(compressed_data);
            ws_debug("inflate failed (return code %d) for LogContainer", ret);
            if (infstream.msg != NULL) {
                ws_debug("inflate returned: \"%s\"", infstream.msg);
            }
            /* Free up any dynamically-allocated memory in infstream */
            ZLIB_PREFIX(inflateEnd)(&infstream);
            return false;
        }

        if (Z_OK != ZLIB_PREFIX(inflateEnd)(&infstream)) {
            /*
             * The zlib manual says this only returns Z_OK on success
             * and Z_STREAM_ERROR if the stream state was inconsistent.
             *
             * It's not clear what useful information can be reported
             * for Z_STREAM_ERROR; a look at the 1.2.11 source indicates
             * that no string is returned to indicate what the problem
             * was.
             *
             * It's also not clear what to do about infstream if this
             * fails.
             */
            *err = WTAP_ERR_INTERNAL;
            *err_info = ws_strdup("blf_pull_logcontainer_into_memory: inflateEnd failed for LogContainer");
            g_free(buf);
            g_free(compressed_data);
            ws_debug("inflateEnd failed for LogContainer");
            if (infstream.msg != NULL) {
                ws_debug("inflateEnd returned: \"%s\"", infstream.msg);
            }
            return false;
        }

        g_free(compressed_data);
        container->real_data = buf;
        return true;
#else /* USE_ZLIB_OR_ZLIBNG */
        (void) params;
        *err = WTAP_ERR_DECOMPRESSION_NOT_SUPPORTED;
        *err_info = ws_strdup("blf_pull_logcontainer_into_memory: reading gzip-compressed containers isn't supported");
        return false;
#endif /* USE_ZLIB_OR_ZLIBNG */
    }

    return false;
}

/** Finds the next log container starting at the current file offset
 *
 * Adds the container to the containers array for later access
 */
static bool
blf_find_next_logcontainer(blf_params_t* params, int* err, char** err_info) {
    blf_blockheader_t           header;
    blf_logcontainerheader_t    logcontainer_header;
    blf_log_container_t         tmp;
    unsigned char*              header_ptr;
    unsigned int                i;

    uint64_t current_real_start;
    if (params->blf_data->log_containers->len == 0) {
        current_real_start = 0;
    }
    else {
        const blf_log_container_t* container = &g_array_index(params->blf_data->log_containers, blf_log_container_t, params->blf_data->log_containers->len - 1);
        current_real_start = container->real_start_pos + container->real_length;
    }

    header_ptr = (unsigned char*)&header;
    i = 0;

    /** Find Object
     *
     * We read one byte at a time so that we don't have to seek backward (allows us to do a linear read)
     */
    while (i < sizeof(blf_obj_magic)) {
        if (!wtap_read_bytes_or_eof(params->fh, &header_ptr[i], 1, err, err_info)) {
            ws_debug("we found end of file");
            return false;
        }
        if (header_ptr[i] != blf_obj_magic[i]) {
            if (params->pipe) {
                ws_debug("container object magic is not LOBJ");
            }
            else {
                ws_debug("container object magic is not LOBJ (pos: 0x%" PRIx64 ")", file_tell(params->fh) - 1);
            }
            if (i > 0) {
                int j = i;

                while (memcmp(&header_ptr[i - j + 1], blf_obj_magic, j)) {
                    /* Check if the last j bytes match the first j bytes of the magic */
                    j--;
                }

                /* The last j bytes match, and the first j bytes are already in the buffer, since j<=i */
                i = j;
            }
        }
        else {
            /* Character matches */
            i++;
        }
    }

    if (!wtap_read_bytes_or_eof(params->fh, &header.header_length, sizeof(blf_blockheader_t) - sizeof(blf_obj_magic), err, err_info)) {
        ws_debug("we found end of file");
        return false;
    }

    fix_endianness_blf_blockheader(&header);

    if (header.header_length < sizeof(blf_blockheader_t)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup("blf: header length too short while looking for object");
        return false;
    }

    if (header.header_type != BLF_HEADER_TYPE_DEFAULT) {
        *err = WTAP_ERR_UNSUPPORTED;
        *err_info = ws_strdup_printf("blf: unknown header type (%u), I know only BLF_HEADER_TYPE_DEFAULT (1)", header.header_type);
        return false;
    }

    if (header.object_length < header.header_length) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup("blf: header object length less than header length while looking for objects");
        return false;
    }

    if (header.object_type == BLF_OBJTYPE_LOG_CONTAINER) {
        /* skip unknown header part if needed */
        if (header.header_length > sizeof(blf_blockheader_t)) {
            /* seek over unknown header part */
            if (!wtap_read_bytes(params->fh, NULL, header.header_length - sizeof(blf_blockheader_t), err, err_info)) {
                ws_debug("error skipping unknown header bytes in log container");
                return false;
            }
        }

        /* Read the log container header */
        if (!wtap_read_bytes_or_eof(params->fh, &logcontainer_header, sizeof(blf_logcontainerheader_t), err, err_info)) {
            ws_debug("not enough bytes for log container header");
            return false;
        }

        fix_endianness_blf_logcontainerheader(&logcontainer_header);

        blf_init_logcontainer(&tmp);

        if (params->pipe) {
            tmp.infile_start_pos = 0;
            tmp.infile_data_start = sizeof(blf_logcontainerheader_t) + header.header_length;
        }
        else {
            tmp.infile_data_start = file_tell(params->fh);
            tmp.infile_start_pos = tmp.infile_data_start - sizeof(blf_logcontainerheader_t) - header.header_length;
        }
        tmp.infile_length = header.object_length;

        tmp.real_start_pos = current_real_start;
        tmp.real_length = logcontainer_header.uncompressed_size;
        tmp.compression_method = logcontainer_header.compression_method;

        ws_debug("found log container with real_pos=0x%" PRIx64 ", real_length=0x%" PRIx64, tmp.real_start_pos, tmp.real_length);
    }
    else {
        ws_debug("found BLF object without log container");

        /* Create a fake log container for the lone object.
         * In order to avoid seeking backwards, we need to pull the fake log container now.
         */
        unsigned char* buf = g_try_malloc((size_t)header.object_length);
        if (buf == NULL) {
            /*
             * XXX - we need an "out of memory" error code here.
             */
            *err = WTAP_ERR_INTERNAL;
            *err_info = ws_strdup("blf_find_next_logcontainer: cannot allocate memory");
            return false;
        }

        memcpy(buf, &header, sizeof(blf_blockheader_t));

        if (header.object_length > sizeof(blf_blockheader_t)) {
            if (!wtap_read_bytes(params->fh, buf + sizeof(blf_blockheader_t), header.object_length - sizeof(blf_blockheader_t), err, err_info)) {
                g_free(buf);
                ws_debug("cannot pull object without log container");
                return false;
            }
        }

        blf_init_logcontainer(&tmp);

        tmp.infile_start_pos = params->pipe ? 0 : (file_tell(params->fh) - header.object_length);
        tmp.infile_data_start = tmp.infile_start_pos;
        tmp.infile_length = header.object_length;

        tmp.real_start_pos = current_real_start;
        tmp.real_length = header.object_length;
        tmp.compression_method = BLF_COMPRESSION_NONE;

        tmp.real_data = buf;

        ws_debug("found non-log-container object with real_pos=0x%" PRIx64 ", real_length=0x%" PRIx64, tmp.real_start_pos, tmp.real_length);
    }

    g_array_append_val(params->blf_data->log_containers, tmp);

    return true;
}

static bool
// NOLINTNEXTLINE(misc-no-recursion)
blf_pull_next_logcontainer(blf_params_t* params, int* err, char** err_info) {
    blf_log_container_t* container;

    if (!blf_find_next_logcontainer(params, err, err_info)) {
        return false;
    }

    /* Is there a next log container to pull? */
    if (params->blf_data->log_containers->len == 0) {
        /* No. */
        return false;
    }

    container = &g_array_index(params->blf_data->log_containers, blf_log_container_t, params->blf_data->log_containers->len - 1);
    if (!blf_pull_logcontainer_into_memory(params, container, err, err_info)) {
        if (*err == WTAP_ERR_DECOMPRESS) {
            report_warning("Error while decompressing BLF log container number %u (file pos. 0x%" PRIx64 "): %s",
                            params->blf_data->log_containers->len - 1, container->infile_start_pos, *err_info ? *err_info : "(none)");
            *err = 0;
            g_free(*err_info);
            *err_info = NULL;

            /* Skip this log container and try to get the next one. */
            g_array_remove_index(params->blf_data->log_containers, params->blf_data->log_containers->len - 1);
            /* Calling blf_pull_logcontainer_into_memory advances the file pointer. Eventually we will reach the end of the file and stop recursing. */
            return blf_pull_next_logcontainer(params, err, err_info);
        }

        return false;
    }

    return true;
}

static bool
blf_read_bytes_or_eof(blf_params_t *params, uint64_t real_pos, void *target_buffer, uint64_t count, int *err, char **err_info) {
    blf_log_container_t*    container;
    unsigned container_index;

    uint64_t end_pos = real_pos + count;

    uint64_t copied = 0;
    uint64_t data_left;
    uint64_t start_in_buf;

    unsigned char *buf = (unsigned char *)target_buffer;

    if (count == 0) {
        ws_debug("called blf_read_bytes_or_eof with 0 count");
        return false;
    }

    if (count > UINT32_MAX) {
        ws_debug("trying to read too many bytes");
        return false;
    }

    if (params->random) {
        /*
         * Do a binary search for the container in which real_pos
         * is included.
         */
        if (!g_array_binary_search(params->blf_data->log_containers, &real_pos, blf_logcontainers_search, &container_index)) {
            /*
             * XXX - why is this treated as an EOF rather than an error?
             * *err appears to be 0, which means our caller treats it as an
             * EOF, at least when reading the log object header.
             */
            ws_debug("cannot read data because start position cannot be mapped");
            return false;
        }
        container = &g_array_index(params->blf_data->log_containers, blf_log_container_t, container_index);
    }
    else {
        if (params->blf_data->log_containers->len == 0) {
            /*
             * This is the first (linear) pass, and we haven't yet
             * added any containers.  Pull the next log container
             * into memory, so that the array isn't empty.
             */
            if (!blf_pull_next_logcontainer(params, err, err_info)) {
                return false;
            }
        }

        /*
         * Search backwards in the array, from the last entry to the
         * first, to find the log container in which real_pos is
         * included.
         */
        container_index = params->blf_data->log_containers->len;
        do {
            container = &g_array_index(params->blf_data->log_containers, blf_log_container_t, --container_index);
        } while (real_pos < container->real_start_pos && container_index > 0);  /* For some reason we skipped past the correct container */
    }

    while (real_pos < end_pos) {

        while (real_pos >= container->real_start_pos + container->real_length) {
            container_index++;
            if (!params->random) {  /* First (linear) pass */
                if (!blf_pull_next_logcontainer(params, err, err_info)) {
                    return false;
                }
            }
            if (container_index >= params->blf_data->log_containers->len) {
                ws_debug("cannot find real_pos in container");
                return false;
            }
            container = &g_array_index(params->blf_data->log_containers, blf_log_container_t, container_index);
            if (real_pos < container->real_start_pos) {
                ws_debug("cannot find real_pos in container");
                return false;
            }
        }

        if (real_pos < container->real_start_pos) {
            ws_debug("cannot find real_pos in container");
            return false;
        }

        start_in_buf = real_pos - container->real_start_pos;

        if (params->random) {
            if (file_seek(params->fh, container->infile_data_start, SEEK_SET, err) == -1) {
                return false;
            }
            if (!blf_pull_logcontainer_into_memory(params, container, err, err_info)) {
                return false;
            }
        }

        data_left = container->real_length - start_in_buf;

        if (data_left < (count - copied)) {
            memcpy(buf + copied, container->real_data + start_in_buf, data_left);
            copied += data_left;
            real_pos += data_left;
        }
        else {
            memcpy(buf + copied, container->real_data + start_in_buf, count - copied);
            return true;
        }

    }

    /*
     * XXX - does this represent a bug (WTAP_ERR_INTERNAL) or a
     * malformed file (WTAP_ERR_BAD_FILE)?
     */
    *err = WTAP_ERR_INTERNAL;
    *err_info = ws_strdup("blf_read_bytes_or_eof: ran out of containers");
    return false;
}

static bool
blf_read_bytes(blf_params_t *params, uint64_t real_pos, void *target_buffer, uint64_t count, int *err, char **err_info) {
    if (!blf_read_bytes_or_eof(params, real_pos, target_buffer, count, err, err_info)) {
        if (*err == 0) {
            *err = WTAP_ERR_SHORT_READ;
        }
        return false;
    }
    return true;
}

static void
blf_init_rec(blf_params_t *params, uint32_t flags, uint64_t object_timestamp, int pkt_encap, uint16_t channel, uint16_t hwchannel, unsigned caplen, unsigned len) {
    wtap_setup_packet_rec(params->rec, pkt_encap);
    params->rec->block = wtap_block_create(WTAP_BLOCK_PACKET);
    params->rec->presence_flags = WTAP_HAS_CAP_LEN | WTAP_HAS_INTERFACE_ID;
    params->rec->ts_rel_cap_valid = false;
    switch (flags) {
    case BLF_TIMESTAMP_RESOLUTION_10US:
        params->rec->presence_flags |= WTAP_HAS_TS;
        params->rec->tsprec = WTAP_TSPREC_10_USEC;
        object_timestamp *= 10000;
        object_timestamp += params->blf_data->start_offset_ns;
        params->rec->ts_rel_cap_valid = true;
        break;

    case BLF_TIMESTAMP_RESOLUTION_1NS:
        params->rec->presence_flags |= WTAP_HAS_TS;
        params->rec->tsprec = WTAP_TSPREC_NSEC;
        object_timestamp += params->blf_data->start_offset_ns;
        params->rec->ts_rel_cap_valid = true;
        break;

    default:
        /* Metadata objects have both flags and timestamp equal to zero, so that combination is not an error. */
        if (flags != 0 || object_timestamp != 0) {
            /*
             * XXX - report this as an error?
             *
             * Or provide a mechanism to allow file readers to report
             * a warning (an error that the reader tries to work
             * around and that the caller should report)?
             */
            ws_debug("Unknown combination of flags and timestamp (0x%x, %" PRIu64 ")", flags, object_timestamp);
            object_timestamp = 0;
        }
        break;
    }
    params->rec->ts.secs = object_timestamp / (1000 * 1000 * 1000);
    params->rec->ts.nsecs = object_timestamp % (1000 * 1000 * 1000);
    params->rec->rec_header.packet_header.caplen = caplen;
    params->rec->rec_header.packet_header.len = len;

    nstime_t tmp_ts;
    tmp_ts.secs = params->blf_data->start_offset_ns / (1000 * 1000 * 1000);
    tmp_ts.nsecs = params->blf_data->start_offset_ns % (1000 * 1000 * 1000);
    nstime_delta(&params->rec->ts_rel_cap, &params->rec->ts, &tmp_ts);

    params->rec->rec_header.packet_header.interface_id = blf_lookup_interface(params, pkt_encap, channel, hwchannel, NULL);

    /* TODO: before we had to remove comments and verdict here to not leak memory but APIs have changed ... */
}

static void
blf_add_direction_option(blf_params_t *params, uint16_t direction) {
    uint32_t tmp = PACK_FLAGS_DIRECTION_INBOUND; /* dont care */

    switch (direction) {
    case BLF_DIR_RX:
        tmp = PACK_FLAGS_DIRECTION_INBOUND; /* inbound */
        break;
    case BLF_DIR_TX:
    case BLF_DIR_TX_RQ:
        tmp = PACK_FLAGS_DIRECTION_OUTBOUND; /* outbound */
        break;
    }

    wtap_block_add_uint32_option(params->rec->block, OPT_PKT_FLAGS, tmp);
}

static bool
blf_read_log_object_header(blf_params_t *params, int *err, char **err_info, int64_t header2_start, int64_t data_start, blf_logobjectheader_t *logheader) {
    if (data_start - header2_start < (int64_t)sizeof(blf_logobjectheader_t)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup("blf: not enough bytes for log object header");
        ws_debug("not enough bytes for timestamp header");
        return false;
    }

    if (!blf_read_bytes_or_eof(params, header2_start, logheader, sizeof(*logheader), err, err_info)) {
        ws_debug("not enough bytes for logheader");
        return false;
    }
    fix_endianness_blf_logobjectheader(logheader);
    return true;
}

static bool
blf_read_log_object_header2(blf_params_t *params, int *err, char **err_info, int64_t header2_start, int64_t data_start, blf_logobjectheader2_t *logheader) {
    if (data_start - header2_start < (int64_t)sizeof(blf_logobjectheader2_t)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup("blf: not enough bytes for log object header");
        ws_debug("not enough bytes for timestamp header");
        return false;
    }

    if (!blf_read_bytes_or_eof(params, header2_start, logheader, sizeof(*logheader), err, err_info)) {
        ws_debug("not enough bytes for logheader");
        return false;
    }
    fix_endianness_blf_logobjectheader2(logheader);
    return true;
}

static bool
blf_read_log_object_header3(blf_params_t *params, int *err, char **err_info, int64_t header2_start, int64_t data_start, blf_logobjectheader3_t *logheader) {
    if (data_start - header2_start < (int64_t)sizeof(blf_logobjectheader3_t)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup("blf: not enough bytes for log object header");
        ws_debug("not enough bytes for timestamp header");
        return false;
    }

    if (!blf_read_bytes_or_eof(params, header2_start, logheader, sizeof(*logheader), err, err_info)) {
        ws_debug("not enough bytes for logheader");
        return false;
    }
    fix_endianness_blf_logobjectheader3(logheader);
    return true;
}

static bool
blf_read_ethernetframe(blf_params_t *params, int *err, char **err_info, int64_t block_start, int64_t data_start, int64_t object_length, uint32_t flags, uint64_t object_timestamp) {
    blf_ethernetframeheader_t ethheader;
    uint8_t tmpbuf[18];
    unsigned caplen, len;

    if (object_length < (data_start - block_start) + (int) sizeof(blf_ethernetframeheader_t)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup("blf: ETHERNET_FRAME: not enough bytes for ethernet frame header in object");
        ws_debug("not enough bytes for ethernet frame header in object");
        return false;
    }

    if (!blf_read_bytes(params, data_start, &ethheader, sizeof(ethheader), err, err_info)) {
        ws_debug("not enough bytes for ethernet frame header in file");
        return false;
    }
    fix_endianness_blf_ethernetframeheader(&ethheader);

    /*
     * BLF breaks up and reorders the Ethernet header and VLAN tag fields.
     * This is a really bad design and makes this format one of the worst.
     * If you want a fast format that keeps your data intact, avoid this format!
     * So, lets hope we can reconstruct the original packet successfully.
     */

    tmpbuf[0] = ethheader.dst_addr[0];
    tmpbuf[1] = ethheader.dst_addr[1];
    tmpbuf[2] = ethheader.dst_addr[2];
    tmpbuf[3] = ethheader.dst_addr[3];
    tmpbuf[4] = ethheader.dst_addr[4];
    tmpbuf[5] = ethheader.dst_addr[5];

    tmpbuf[6] = ethheader.src_addr[0];
    tmpbuf[7] = ethheader.src_addr[1];
    tmpbuf[8] = ethheader.src_addr[2];
    tmpbuf[9] = ethheader.src_addr[3];
    tmpbuf[10] = ethheader.src_addr[4];
    tmpbuf[11] = ethheader.src_addr[5];

    if (ethheader.tpid != 0 && ethheader.tci != 0) {
        phtonu16(tmpbuf + 12, ethheader.tpid);
        phtonu16(tmpbuf + 14, ethheader.tci);
        phtonu16(tmpbuf + 16, ethheader.ethtype);
        ws_buffer_assure_space(&params->rec->data, (size_t)18 + ethheader.payloadlength);
        ws_buffer_append(&params->rec->data, tmpbuf, (size_t)18);
        caplen = ((uint32_t)18 + ethheader.payloadlength);
        len = ((uint32_t)18 + ethheader.payloadlength);
    } else {
        phtonu16(tmpbuf + 12, ethheader.ethtype);
        ws_buffer_assure_space(&params->rec->data, (size_t)14 + ethheader.payloadlength);
        ws_buffer_append(&params->rec->data, tmpbuf, (size_t)14);
        caplen = ((uint32_t)14 + ethheader.payloadlength);
        len = ((uint32_t)14 + ethheader.payloadlength);
    }

    if (!blf_read_bytes(params, data_start + sizeof(blf_ethernetframeheader_t), ws_buffer_end_ptr(&params->rec->data), ethheader.payloadlength, err, err_info)) {
        ws_debug("copying ethernet frame failed");
        return false;
    }
    ws_buffer_increase_length(&params->rec->data, ethheader.payloadlength);

    blf_init_rec(params, flags, object_timestamp, WTAP_ENCAP_ETHERNET, ethheader.channel, UINT16_MAX, caplen, len);
    blf_add_direction_option(params, ethheader.direction);

    return true;
}

static bool
blf_read_ethernetframe_ext(blf_params_t *params, int *err, char **err_info, int64_t block_start,int64_t data_start,
                            int64_t object_length, uint32_t flags, uint64_t object_timestamp, gboolean error) {
    blf_ethernetframeheader_ex_t ethheader;

    if (object_length < (data_start - block_start) + (int) sizeof(blf_ethernetframeheader_ex_t)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup_printf("blf: %s: not enough bytes for ethernet frame header in object", error ? "ETHERNET_ERROR_EX" : "ETHERNET_FRAME_EX");
        ws_debug("not enough bytes for ethernet frame header in object");
        return false;
    }

    if (!blf_read_bytes(params, data_start, &ethheader, sizeof(blf_ethernetframeheader_ex_t), err, err_info)) {
        ws_debug("not enough bytes for ethernet frame header in file");
        return false;
    }
    fix_endianness_blf_ethernetframeheader_ex(&ethheader);

    if (object_length - (data_start - block_start) - sizeof(blf_ethernetframeheader_ex_t) < ethheader.frame_length) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup_printf("blf: %s: frame too short", error ? "ETHERNET_ERROR_EX" : "ETHERNET_FRAME_EX");
        ws_debug("frame too short");
        return false;
    }

    ws_buffer_assure_space(&params->rec->data, ethheader.frame_length);

    if (!blf_read_bytes(params, data_start + sizeof(blf_ethernetframeheader_ex_t), ws_buffer_end_ptr(&params->rec->data), ethheader.frame_length, err, err_info)) {
        ws_debug("copying ethernet frame failed");
        return false;
    }
    ws_buffer_increase_length(&params->rec->data, ethheader.frame_length);

    if (ethheader.flags & BLF_ETHERNET_EX_HARDWARECHANNEL) {
        blf_init_rec(params, flags, object_timestamp, WTAP_ENCAP_ETHERNET, ethheader.channel, ethheader.hw_channel, ethheader.frame_length, ethheader.frame_length);
        wtap_block_add_uint32_option(params->rec->block, OPT_PKT_QUEUE, ethheader.hw_channel);
    }
    else {
        blf_init_rec(params, flags, object_timestamp, WTAP_ENCAP_ETHERNET, ethheader.channel, UINT16_MAX, ethheader.frame_length, ethheader.frame_length);
    }

    blf_add_direction_option(params, ethheader.direction);

    return true;
}

static bool
blf_read_ethernet_rxerror(blf_params_t* params, int* err, char** err_info, int64_t block_start, int64_t data_start, int64_t object_length, uint32_t flags, uint64_t object_timestamp) {
    blf_ethernet_rxerror_t ethheader;

    if (object_length < (data_start - block_start) + (int)sizeof(blf_ethernet_rxerror_t)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup("blf: ETHERNET_RXERROR: not enough bytes for ethernet frame header in object");
        ws_debug("not enough bytes for ethernet rx error header in object");
        return false;
    }

    if (!blf_read_bytes(params, data_start, &ethheader, sizeof(blf_ethernet_rxerror_t), err, err_info)) {
        ws_debug("not enough bytes for ethernet rx error header in file");
        return false;
    }
    fix_endianness_blf_ethernet_rxerror(&ethheader);

    if (object_length - (data_start - block_start) < ethheader.frame_length) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup("blf: ETHERNET_RXERROR: frame too short");
        ws_debug("frame too short");
        return false;
    }

    ws_buffer_assure_space(&params->rec->data, ethheader.frame_length);

    if (!blf_read_bytes(params, data_start + sizeof(blf_ethernet_rxerror_t), ws_buffer_end_ptr(&params->rec->data), ethheader.frame_length, err, err_info)) {
        ws_debug("copying ethernet rx error failed");
        return false;
    }
    ws_buffer_increase_length(&params->rec->data, ethheader.frame_length);

    if (ethheader.hw_channel != 0) {    /* In this object type, a value of 0 is considered invalid. */
        blf_init_rec(params, flags, object_timestamp, WTAP_ENCAP_ETHERNET, ethheader.channel, ethheader.hw_channel, ethheader.frame_length, ethheader.frame_length);
        wtap_block_add_uint32_option(params->rec->block, OPT_PKT_QUEUE, ethheader.hw_channel);
    }
    else {
        blf_init_rec(params, flags, object_timestamp, WTAP_ENCAP_ETHERNET, ethheader.channel, UINT16_MAX, ethheader.frame_length, ethheader.frame_length);
    }
    blf_add_direction_option(params, ethheader.direction);

    return true;
}

/*
 * XXX - provide radio information to our caller in the pseudo-header.
 */
static bool
blf_read_wlanframe(blf_params_t* params, int* err, char** err_info, int64_t block_start, int64_t data_start, int64_t object_length, uint32_t flags, uint64_t object_timestamp) {
    blf_wlanframeheader_t wlanheader;

    if (object_length < (data_start - block_start) + (int)sizeof(blf_wlanframeheader_t)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup("blf: WLAN_FRAME: not enough bytes for wlan frame header in object");
        ws_debug("not enough bytes for wlan frame header in object");
        return false;
    }

    if (!blf_read_bytes(params, data_start, &wlanheader, sizeof(blf_wlanframeheader_t), err, err_info)) {
        ws_debug("not enough bytes for wlan frame header in file");
        return false;
    }
    fix_endianness_blf_wlanframeheader(&wlanheader);

    if (object_length - (data_start - block_start) - sizeof(blf_wlanframeheader_t) < wlanheader.frame_length) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup("blf: WLAN_FRAME: frame too short");
        ws_debug("frame too short");
        return false;
    }

    ws_buffer_assure_space(&params->rec->data, wlanheader.frame_length);

    if (!blf_read_bytes(params, data_start + sizeof(blf_wlanframeheader_t), ws_buffer_end_ptr(&params->rec->data), wlanheader.frame_length, err, err_info)) {
        ws_debug("copying wlan frame failed");
        return false;
    }
    ws_buffer_increase_length(&params->rec->data, wlanheader.frame_length);

    blf_init_rec(params, flags, object_timestamp, WTAP_ENCAP_IEEE_802_11, wlanheader.channel, UINT16_MAX, wlanheader.frame_length, wlanheader.frame_length);
    blf_add_direction_option(params, wlanheader.direction);

    return true;
}

static const uint8_t can_dlc_to_length[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 8, 8, 8, 8, 8, 8 };
static const uint8_t canfd_dlc_to_length[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 16, 20, 24, 32, 48, 64 };

static bool
blf_can_fill_buf_and_rec(blf_params_t *params, int *err, char **err_info, uint32_t canid, uint8_t payload_length, uint8_t payload_length_valid, uint64_t start_position,
                         uint32_t flags, uint64_t object_timestamp, uint16_t channel, uint8_t canfd_flags) {
    uint8_t  tmpbuf[8];
    unsigned caplen, len;

    phtonu32(tmpbuf, canid);
    tmpbuf[4] = payload_length;
    tmpbuf[5] = canfd_flags;
    tmpbuf[6] = 0;
    tmpbuf[7] = 0;

    ws_buffer_assure_space(&params->rec->data, sizeof(tmpbuf) + payload_length_valid);
    ws_buffer_append(&params->rec->data, tmpbuf, sizeof(tmpbuf));
    caplen = sizeof(tmpbuf) + payload_length_valid;
    len = sizeof(tmpbuf) + payload_length;

    if (payload_length_valid > 0 && !blf_read_bytes(params, start_position, ws_buffer_end_ptr(&params->rec->data), payload_length_valid, err, err_info)) {
        ws_debug("copying can payload failed");
        return false;
    }
    ws_buffer_increase_length(&params->rec->data, payload_length_valid);

    blf_init_rec(params, flags, object_timestamp, WTAP_ENCAP_SOCKETCAN, channel, UINT16_MAX, caplen, len);

    return true;
}

static bool
blf_read_canmessage(blf_params_t *params, int *err, char **err_info, int64_t block_start, int64_t data_start, int64_t object_length, uint32_t flags, uint64_t object_timestamp, bool can_message2) {
    blf_canmessage_t canheader;
    blf_canmessage2_trailer_t can2trailer;

    uint32_t canid;
    uint8_t  payload_length;

    if (object_length < (data_start - block_start) + (int) sizeof(canheader)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup_printf("blf: %s: not enough bytes for can header in object",
                                    can_message2 ? "CAN_MESSAGE2" : "CAN_MESSAGE");
        ws_debug("not enough bytes for can header in object");
        return false;
    }

    if (!blf_read_bytes(params, data_start, &canheader, sizeof(canheader), err, err_info)) {
        ws_debug("not enough bytes for can header in file");
        return false;
    }
    fix_endianness_blf_canmessage(&canheader);

    canheader.dlc &= 0x0f;

    payload_length = canheader.dlc;
    if (payload_length > 8) {
        ws_debug("regular CAN tries more than 8 bytes? Cutting to 8!");
        payload_length = 8;
    }

    canid = canheader.id;

    if ((canheader.flags & BLF_CANMESSAGE_FLAG_RTR) == BLF_CANMESSAGE_FLAG_RTR) {
        canid |= CAN_RTR_FLAG;
        payload_length = 0;
    }

    if (!blf_can_fill_buf_and_rec(params, err, err_info, canid, payload_length, payload_length, data_start + sizeof(canheader), flags, object_timestamp, canheader.channel, 0)) {
        return false;
    }

    /* actually, we do not really need the data, right now.... */
    if (can_message2) {
        if (object_length < (data_start - block_start) + (int) sizeof(canheader) + 8 + (int) sizeof(can2trailer)) {
            *err = WTAP_ERR_BAD_FILE;
            *err_info = ws_strdup("blf: CAN_MESSAGE2: not enough bytes for can message 2 trailer");
            ws_debug("not enough bytes for can message 2 trailer");
            return false;
        }
        if (!blf_read_bytes(params, data_start + sizeof(canheader) + 8, &can2trailer, sizeof(can2trailer), err, err_info)) {
            ws_debug("not enough bytes for can message 2 trailer in file");
            return false;
        }
        fix_endianness_blf_canmessage2_trailer(&can2trailer);
    }

    blf_add_direction_option(params, (canheader.flags & BLF_CANMESSAGE_FLAG_TX) == BLF_CANMESSAGE_FLAG_TX ? BLF_DIR_TX: BLF_DIR_RX);

    return true;
}

static bool
blf_read_canfdmessage(blf_params_t *params, int *err, char **err_info, int64_t block_start, int64_t data_start, int64_t object_length, uint32_t flags, uint64_t object_timestamp) {
    blf_canfdmessage_t canheader;

    bool     canfd;
    uint32_t canid;
    uint8_t  payload_length;
    uint8_t  payload_length_valid;
    uint8_t  canfd_flags;

    if (object_length < (data_start - block_start) + (int) sizeof(canheader)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup("blf: CAN_FD_MESSAGE: not enough bytes for canfd header in object");
        ws_debug("not enough bytes for canfd header in object");
        return false;
    }

    if (!blf_read_bytes(params, data_start, &canheader, sizeof(canheader), err, err_info)) {
        ws_debug("not enough bytes for canfd header in file");
        return false;
    }
    fix_endianness_blf_canfdmessage(&canheader);

    canheader.dlc &= 0x0f;

    canfd = (canheader.canfdflags & BLF_CANFDMESSAGE_CANFDFLAG_EDL) == BLF_CANFDMESSAGE_CANFDFLAG_EDL;
    if (canfd) {
        payload_length = canfd_dlc_to_length[canheader.dlc];
        canfd_flags = (canheader.canfdflags & BLF_CANFDMESSAGE_CANFDFLAG_EDL) << 2 | (canheader.canfdflags & BLF_CANFDMESSAGE_CANFDFLAG_ESI) >> 1 | (canheader.canfdflags & BLF_CANFDMESSAGE_CANFDFLAG_BRS) >> 1;
    } else {
        if (canheader.dlc > 8) {
            ws_debug("regular CAN tries more than 8 bytes?");
        }
        payload_length = can_dlc_to_length[canheader.dlc];
        canfd_flags = 0;
    }

    if (payload_length > canheader.validDataBytes) {
        ws_debug("shortening canfd payload because valid data bytes shorter!");
        payload_length = canheader.validDataBytes;
    }

    canid = canheader.id;

    if (!canfd && (canheader.flags & BLF_CANMESSAGE_FLAG_RTR) == BLF_CANMESSAGE_FLAG_RTR) {
        canid |= CAN_RTR_FLAG;
        payload_length = 0; /* Should already be zero from validDataBytes */
    }

    payload_length_valid = payload_length;

    if (payload_length_valid > object_length - (data_start - block_start) + sizeof(canheader)) {
        ws_debug("shortening can payload because buffer is too short!");
        payload_length_valid = (uint8_t)(object_length - (data_start - block_start));
    }

    if (!blf_can_fill_buf_and_rec(params, err, err_info, canid, payload_length, payload_length_valid, data_start + sizeof(canheader), flags, object_timestamp, canheader.channel, canfd_flags)) {
        return false;
    }

    blf_add_direction_option(params, (canheader.flags & BLF_CANMESSAGE_FLAG_TX) == BLF_CANMESSAGE_FLAG_TX ? BLF_DIR_TX : BLF_DIR_RX);

    return true;
}

static bool
blf_read_canfdmessage64(blf_params_t *params, int *err, char **err_info, int64_t block_start, int64_t data_start, int64_t object_length, uint32_t flags, uint64_t object_timestamp) {
    blf_canfdmessage64_t canheader;

    bool     canfd;
    uint32_t canid;
    uint8_t  payload_length;
    uint8_t  payload_length_valid;
    uint8_t  canfd_flags;

    if (object_length < (data_start - block_start) + (int) sizeof(canheader)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup("blf: CAN_FD_MESSAGE_64: not enough bytes for canfd header in object");
        ws_debug("not enough bytes for canfd header in object");
        return false;
    }

    if (!blf_read_bytes(params, data_start, &canheader, sizeof(canheader), err, err_info)) {
        ws_debug("not enough bytes for canfd header in file");
        return false;
    }
    fix_endianness_blf_canfdmessage64(&canheader);

    canheader.dlc &= 0x0f;

    canfd = (canheader.flags & BLF_CANFDMESSAGE64_FLAG_EDL) == BLF_CANFDMESSAGE64_FLAG_EDL;
    if (canfd) {
        payload_length = canfd_dlc_to_length[canheader.dlc];
        canfd_flags = (canheader.flags & BLF_CANFDMESSAGE64_FLAG_EDL) >> 10 | (canheader.flags & BLF_CANFDMESSAGE64_FLAG_ESI) >> 13 | (canheader.flags & BLF_CANFDMESSAGE64_FLAG_BRS) >> 13;
    } else {
        if (canheader.dlc > 8) {
            ws_debug("regular CAN tries more than 8 bytes?");
        }
        payload_length = can_dlc_to_length[canheader.dlc];
        canfd_flags = 0;
    }

    if (payload_length > canheader.validDataBytes) {
        ws_debug("shortening canfd payload because valid data bytes shorter!");
        payload_length = canheader.validDataBytes;
    }

    canid = canheader.id;

    if (!canfd && (canheader.flags & BLF_CANFDMESSAGE64_FLAG_REMOTE_FRAME) == BLF_CANFDMESSAGE64_FLAG_REMOTE_FRAME) {
        canid |= CAN_RTR_FLAG;
        payload_length = 0; /* Should already be zero from validDataBytes */
    }

    payload_length_valid = payload_length;

    if (payload_length_valid > object_length - (data_start - block_start)) {
        ws_debug("shortening can payload because buffer is too short!");
        payload_length_valid = (uint8_t)(object_length - (data_start - block_start));
    }

    if (!blf_can_fill_buf_and_rec(params, err, err_info, canid, payload_length, payload_length_valid, data_start + sizeof(canheader), flags, object_timestamp, canheader.channel, canfd_flags)) {
        return false;
    }

    blf_add_direction_option(params, canheader.dir);

    return true;
}

static bool
blf_read_canerror(blf_params_t *params, int *err, char **err_info, int64_t block_start, int64_t data_start, int64_t object_length, uint32_t flags, uint64_t object_timestamp, bool overload) {
    blf_canerror_t canheader;
    uint32_t canid;
    uint8_t  payload_length;
    uint8_t  tmpbuf[16] = {0};

    if (object_length < (data_start - block_start) + (int) sizeof(canheader)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup("blf: CAN_ERROR: not enough bytes for canerror header in object");
        ws_debug("not enough bytes for canerror header in object");
        return false;
    }

    if (!blf_read_bytes(params, data_start, &canheader, sizeof(canheader), err, err_info)) {
        ws_debug("not enough bytes for canerror header in file");
        return false;
    }
    fix_endianness_blf_canerror(&canheader);

    // Set CAN_ERR_FLAG in unused bits of Can ID to indicate error in socketcan
    canid = CAN_ERR_FLAG;

    // Fixed packet data length for socketcan error messages
    payload_length = CAN_ERR_DLC;

    if (overload) {
        tmpbuf[10] = CAN_ERR_PROT_OVERLOAD;
        canid |= CAN_ERR_PROT;
    }

    phtonu32(tmpbuf, canid);
    tmpbuf[4] = payload_length;

    ws_buffer_append(&params->rec->data, tmpbuf, sizeof(tmpbuf));

    blf_init_rec(params, flags, object_timestamp, WTAP_ENCAP_SOCKETCAN, canheader.channel, UINT16_MAX, sizeof(tmpbuf), sizeof(tmpbuf));
    return true;
}

static bool
blf_read_canerrorext(blf_params_t *params, int *err, char **err_info, int64_t block_start, int64_t data_start, int64_t object_length, uint32_t flags, uint64_t object_timestamp) {
    blf_canerrorext_t canheader;

    bool     err_ack = false;
    bool     err_prot = false;
    bool     direction_tx;
    uint32_t canid;
    uint8_t  payload_length;
    uint8_t  tmpbuf[16] = {0};

    if (object_length < (data_start - block_start) + (int) sizeof(canheader)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup("blf: CAN_ERROR_EXT: not enough bytes for canerrorext header in object");
        ws_debug("not enough bytes for canerrorext header in object");
        return false;
    }

    if (!blf_read_bytes(params, data_start, &canheader, sizeof(canheader), err, err_info)) {
        ws_debug("not enough bytes for canerrorext header in file");
        return false;
    }
    fix_endianness_blf_canerrorext(&canheader);

    if (canheader.flags & BLF_CANERROREXT_FLAG_CANCORE) {
        // Map Vector Can Core error codes to compareable socketcan errors
        switch ((canheader.errorCodeExt >> 6) & 0x3f) {
        case BLF_CANERROREXT_ECC_MEANING_BIT_ERROR:
            err_prot = true;
            tmpbuf[10] = CAN_ERR_PROT_BIT;
            break;
        case BLF_CANERROREXT_ECC_MEANING_FORM_ERROR:
            err_prot = true;
            tmpbuf[10] = CAN_ERR_PROT_FORM;
            break;
        case BLF_CANERROREXT_ECC_MEANING_STUFF_ERROR:
            err_prot = true;
            tmpbuf[10] = CAN_ERR_PROT_STUFF;
            break;
        case BLF_CANERROREXT_ECC_MEANING_CRC_ERROR:
            err_prot = true;
            tmpbuf[11] = CAN_ERR_PROT_LOC_CRC_SEQ;
            break;
        case BLF_CANERROREXT_ECC_MEANING_NACK_ERROR:
            err_ack = true;
            tmpbuf[11] = CAN_ERR_PROT_LOC_ACK;
            break;
        case BLF_CANERROREXT_ECC_MEANING_OVERLOAD:
            err_prot = true;
            tmpbuf[10] = CAN_ERR_PROT_OVERLOAD;
            break;
        default:
            err_prot = true;
            tmpbuf[10] = CAN_ERR_PROT_UNSPEC;
            break;
        }
        err_ack = err_ack || (canheader.errorCodeExt & BLF_CANERROREXT_EXTECC_NOT_ACK) == 0x0;
        if (err_ack) {
            // Don't set protocol error on ack errors
            err_prot = false;
        }
    }

    // CanID contains error class in socketcan
    canid = CAN_ERR_FLAG;
    canid |= err_prot ? CAN_ERR_PROT : 0;
    canid |= err_ack ? CAN_ERR_ACK : 0;

    // Fixed packet data length for socketcan error messages
    payload_length = CAN_ERR_DLC;
    canheader.dlc = payload_length;

    phtonu32(tmpbuf, canid);
    tmpbuf[4] = payload_length;

    ws_buffer_append(&params->rec->data, tmpbuf, sizeof(tmpbuf));

    blf_init_rec(params, flags, object_timestamp, WTAP_ENCAP_SOCKETCAN, canheader.channel, UINT16_MAX, sizeof(tmpbuf), sizeof(tmpbuf));
    if (canheader.flags & BLF_CANERROREXT_FLAG_CANCORE) {
        direction_tx = (canheader.errorCodeExt & BLF_CANERROREXT_EXTECC_TX) == BLF_CANERROREXT_EXTECC_TX;
        blf_add_direction_option(params, direction_tx ? BLF_DIR_TX: BLF_DIR_RX);
    }
    return true;
}

static bool
blf_read_canfderror64(blf_params_t *params, int *err, char **err_info, int64_t block_start, int64_t data_start, int64_t object_length, uint32_t flags, uint64_t object_timestamp) {
    blf_canfderror64_t canheader;

    bool     err_ack = false;
    bool     err_prot = false;
    bool     direction_tx;
    uint32_t canid;
    uint8_t  payload_length;
    uint8_t  tmpbuf[16] = {0};

    if (object_length < (data_start - block_start) + (int) sizeof(canheader)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup("blf: CAN_FD_ERROR_64: not enough bytes for canfderror header in object");
        ws_debug("not enough bytes for canfderror header in object");
        return false;
    }

    if (!blf_read_bytes(params, data_start, &canheader, sizeof(canheader), err, err_info)) {
        ws_debug("not enough bytes for canfderror header in file");
        return false;
    }
    fix_endianness_blf_canfderror64(&canheader);

    if (canheader.flags & BLF_CANERROREXT_FLAG_CANCORE) {
        // Map Vector Can Core error codes to compareable socketcan errors
        switch ((canheader.errorCodeExt >> 6) & 0x3f) {
        case BLF_CANERROREXT_ECC_MEANING_BIT_ERROR:
            err_prot = true;
            tmpbuf[10] = CAN_ERR_PROT_BIT;
            break;
        case BLF_CANERROREXT_ECC_MEANING_FORM_ERROR:
            err_prot = true;
            tmpbuf[10] = CAN_ERR_PROT_FORM;
            break;
        case BLF_CANERROREXT_ECC_MEANING_STUFF_ERROR:
            err_prot = true;
            tmpbuf[10] = CAN_ERR_PROT_STUFF;
            break;
        case BLF_CANERROREXT_ECC_MEANING_CRC_ERROR:
            err_prot = true;
            tmpbuf[11] = CAN_ERR_PROT_LOC_CRC_SEQ;
            break;
        case BLF_CANERROREXT_ECC_MEANING_NACK_ERROR:
            err_ack = true;
            tmpbuf[11] = CAN_ERR_PROT_LOC_ACK;
            break;
        case BLF_CANERROREXT_ECC_MEANING_OVERLOAD:
            err_prot = true;
            tmpbuf[10] = CAN_ERR_PROT_OVERLOAD;
            break;
        default:
            err_prot = true;
            tmpbuf[10] = CAN_ERR_PROT_UNSPEC;
            break;
        }
        err_ack = err_ack || (canheader.errorCodeExt & BLF_CANERROREXT_EXTECC_NOT_ACK) == 0x0;
        if (err_ack) {
            // Don't set protocol error on ack errors
            err_prot = false;
        }
    }

    // CanID contains error class in socketcan
    canid = CAN_ERR_FLAG;
    canid |= err_prot ? CAN_ERR_PROT : 0;
    canid |= err_ack ? CAN_ERR_ACK : 0;

    // Fixed packet data length for socketcan error messages
    payload_length = CAN_ERR_DLC;
    canheader.dlc = payload_length;

    phtonu32(tmpbuf, canid);
    tmpbuf[4] = payload_length;
    // Don't set FDF, ESI and BRS flags, since error messages are always encapsulated in Classic CAN frames

    ws_buffer_append(&params->rec->data, tmpbuf, sizeof(tmpbuf));

    blf_init_rec(params, flags, object_timestamp, WTAP_ENCAP_SOCKETCAN, canheader.channel, UINT16_MAX, sizeof(tmpbuf), sizeof(tmpbuf));
    if (canheader.flags & BLF_CANERROREXT_FLAG_CANCORE) {
        direction_tx = (canheader.errorCodeExt & BLF_CANERROREXT_EXTECC_TX) == BLF_CANERROREXT_EXTECC_TX;
        blf_add_direction_option(params, direction_tx ? BLF_DIR_TX: BLF_DIR_RX);
    }
    return true;
}

static bool
blf_read_flexraydata(blf_params_t *params, int *err, char **err_info, int64_t block_start, int64_t data_start, int64_t object_length, uint32_t flags, uint64_t object_timestamp) {
    blf_flexraydata_t frheader;

    uint8_t  payload_length;
    uint8_t  payload_length_valid;
    uint8_t  tmpbuf[7];
    unsigned caplen, len;

    if (object_length < (data_start - block_start) + (int) sizeof(frheader)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup("blf: FLEXRAY_DATA: not enough bytes for flexrayheader in object");
        ws_debug("not enough bytes for flexrayheader in object");
        return false;
    }

    if (!blf_read_bytes(params, data_start, &frheader, sizeof(frheader), err, err_info)) {
        ws_debug("not enough bytes for flexrayheader header in file");
        return false;
    }
    fix_endianness_blf_flexraydata(&frheader);

    payload_length = frheader.len;
    payload_length_valid = payload_length;

    if ((frheader.len & 0x01) == 0x01) {
        ws_debug("reading odd length in FlexRay!?");
    }

    if (payload_length_valid > object_length - (data_start - block_start) - sizeof(frheader)) {
        ws_debug("shortening FlexRay payload because buffer is too short!");
        payload_length_valid = (uint8_t)(object_length - (data_start - block_start) - sizeof(frheader));
    }

    if (frheader.channel != 0 && frheader.channel != 1) {
        ws_debug("FlexRay supports only two channels.");
    }

    /* Measurement Header */
    if (frheader.channel == 0) {
        tmpbuf[0] = BLF_FLEXRAYDATA_FRAME;
    } else {
        tmpbuf[0] = BLF_FLEXRAYDATA_FRAME | BLF_FLEXRAYDATA_CHANNEL_B;
    }

    /* Error Flags */
    tmpbuf[1] = 0;

    /* Frame Header */
    tmpbuf[2] = 0x20 | ((0x0700 & frheader.messageId) >> 8);
    tmpbuf[3] = 0x00ff & frheader.messageId;
    tmpbuf[4] = (0xfe & frheader.len) | ((frheader.crc & 0x0400) >> 10);
    tmpbuf[5] = (0x03fc & frheader.crc) >> 2;
    tmpbuf[6] = ((0x0003 & frheader.crc) << 6) | (0x3f & frheader.mux);

    ws_buffer_assure_space(&params->rec->data, sizeof(tmpbuf) + payload_length_valid);
    ws_buffer_append(&params->rec->data, tmpbuf, sizeof(tmpbuf));
    caplen = sizeof(tmpbuf) + payload_length_valid;
    len = sizeof(tmpbuf) + payload_length;

    if (payload_length_valid > 0 && !blf_read_bytes(params, data_start + sizeof(frheader), ws_buffer_end_ptr(&params->rec->data), payload_length_valid, err, err_info)) {
        ws_debug("copying flexray payload failed");
        return false;
    }
    ws_buffer_increase_length(&params->rec->data, payload_length_valid);

    blf_init_rec(params, flags, object_timestamp, WTAP_ENCAP_FLEXRAY, frheader.channel, UINT16_MAX, caplen, len);
    blf_add_direction_option(params, frheader.dir);

    return true;
}

static bool
blf_read_flexraymessage(blf_params_t *params, int *err, char **err_info, int64_t block_start, int64_t data_start, int64_t object_length, uint32_t flags, uint64_t object_timestamp) {
    blf_flexraymessage_t frheader;

    uint8_t  payload_length;
    uint8_t  payload_length_valid;
    uint8_t  tmpbuf[7];
    unsigned caplen, len;

    if (object_length < (data_start - block_start) + (int) sizeof(frheader)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup("blf: FLEXRAY_MESSAGE: not enough bytes for flexrayheader in object");
        ws_debug("not enough bytes for flexrayheader in object");
        return false;
    }

    if (!blf_read_bytes(params, data_start, &frheader, sizeof(frheader), err, err_info)) {
        ws_debug("not enough bytes for flexrayheader header in file");
        return false;
    }
    fix_endianness_blf_flexraymessage(&frheader);

    payload_length = frheader.length;
    payload_length_valid = payload_length;

    if ((frheader.length & 0x01) == 0x01) {
        ws_debug("reading odd length in FlexRay!?");
    }

    if (payload_length_valid > object_length - (data_start - block_start) - sizeof(frheader)) {
        ws_debug("shortening FlexRay payload because buffer is too short!");
        payload_length_valid = (uint8_t)(object_length - (data_start - block_start) - sizeof(frheader));
    }

    if (frheader.channel != 0 && frheader.channel != 1) {
        ws_debug("FlexRay supports only two channels.");
    }

    /* Measurement Header */
    if (frheader.channel == 0) {
        tmpbuf[0] = BLF_FLEXRAYDATA_FRAME;
    } else {
        tmpbuf[0] = BLF_FLEXRAYDATA_FRAME | BLF_FLEXRAYDATA_CHANNEL_B;
    }

    /* Error Flags */
    tmpbuf[1] = 0;

    /* Frame Header */
    tmpbuf[2] = ((0x0700 & frheader.frameId) >> 8);
    if ((frheader.frameState & BLF_FLEXRAYMESSAGE_STATE_PPI) == BLF_FLEXRAYMESSAGE_STATE_PPI) {
        tmpbuf[2] |= BLF_DLT_FLEXRAY_PPI;
    }

    if ((frheader.frameState & BLF_FLEXRAYMESSAGE_STATE_SFI) == BLF_FLEXRAYMESSAGE_STATE_SFI) {
        tmpbuf[2] |= BLF_DLT_FLEXRAY_SFI;
    }

    if ((frheader.frameState & BLF_FLEXRAYMESSAGE_STATE_NFI) != BLF_FLEXRAYMESSAGE_STATE_NFI) {
        /* NFI needs to be inversed !? */
        tmpbuf[2] |= BLF_DLT_FLEXRAY_NFI;
    }

    if ((frheader.frameState & BLF_FLEXRAYMESSAGE_STATE_STFI) == BLF_FLEXRAYMESSAGE_STATE_STFI) {
        tmpbuf[2] |= BLF_DLT_FLEXRAY_STFI;
    }

    tmpbuf[3] = 0x00ff & frheader.frameId;
    tmpbuf[4] = (0xfe & frheader.length) | ((frheader.headerCrc & 0x0400) >> 10);
    tmpbuf[5] = (0x03fc & frheader.headerCrc) >> 2;
    tmpbuf[6] = ((0x0003 & frheader.headerCrc) << 6) | (0x3f & frheader.cycle);

    ws_buffer_assure_space(&params->rec->data, sizeof(tmpbuf) + payload_length_valid);
    ws_buffer_append(&params->rec->data, tmpbuf, sizeof(tmpbuf));
    caplen = sizeof(tmpbuf) + payload_length_valid;
    len = sizeof(tmpbuf) + payload_length;

    if (payload_length_valid > 0 && !blf_read_bytes(params, data_start + sizeof(frheader), ws_buffer_end_ptr(&params->rec->data), payload_length_valid, err, err_info)) {
        ws_debug("copying flexray payload failed");
        return false;
    }
    ws_buffer_increase_length(&params->rec->data, payload_length_valid);

    blf_init_rec(params, flags, object_timestamp, WTAP_ENCAP_FLEXRAY, frheader.channel, UINT16_MAX, caplen, len);
    blf_add_direction_option(params, frheader.dir);

    return true;
}

static bool
blf_read_flexrayrcvmessageex(blf_params_t *params, int *err, char **err_info, int64_t block_start, int64_t data_start, int64_t object_length, uint32_t flags, uint64_t object_timestamp, bool ext) {
    blf_flexrayrcvmessage_t frheader;

    uint16_t payload_length;
    uint16_t payload_length_valid;
    uint8_t  tmpbuf[7];
    int      frheadersize = sizeof(frheader);
    unsigned caplen, len;

    if (ext) {
        frheadersize += 40;
    }

    if ((int64_t)object_length < (data_start - block_start) + frheadersize) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup_printf("blf: %s: not enough bytes for flexrayheader in object",
                                    ext ? "FLEXRAY_RCVMESSAGE_EX" : "FLEXRAY_RCVMESSAGE");
        ws_debug("not enough bytes for flexrayheader in object");
        return false;
    }

    if (!blf_read_bytes(params, data_start, &frheader, sizeof(frheader), err, err_info)) {
        ws_debug("not enough bytes for flexrayheader header in file");
        return false;
    }
    fix_endianness_blf_flexrayrcvmessage(&frheader);

    if (!ext) {
        frheader.dir &= 0xff;
        frheader.cycle &= 0xff;
    }

    payload_length = frheader.payloadLength;
    payload_length_valid = frheader.payloadLengthValid;

    if ((frheader.payloadLength & 0x01) == 0x01) {
        ws_debug("reading odd length in FlexRay!?");
    }

    if (payload_length_valid > object_length - (data_start - block_start) - frheadersize) {
        ws_debug("shortening FlexRay payload because buffer is too short!");
        payload_length_valid = (uint8_t)(object_length - (data_start - block_start) - frheadersize);
    }

    /* Measurement Header */
    /* TODO: It seems that this format support both channels at the same time!? */
    if (frheader.channelMask == BLF_FLEXRAYRCVMSG_CHANNELMASK_A) {
        tmpbuf[0] = BLF_FLEXRAYDATA_FRAME;
    } else {
        tmpbuf[0] = BLF_FLEXRAYDATA_FRAME | BLF_FLEXRAYDATA_CHANNEL_B;
    }

    /* Error Flags */
    tmpbuf[1] = 0;

    /* Frame Header */
    tmpbuf[2] = ((0x0700 & frheader.frameId) >> 8);
    if ((frheader.frameFlags & BLF_FLEXRAYRCVMSG_FRAME_FLAG_PAYLOAD_PREAM) == BLF_FLEXRAYRCVMSG_FRAME_FLAG_PAYLOAD_PREAM) {
        tmpbuf[2] |= BLF_DLT_FLEXRAY_PPI;
    }

    if ((frheader.frameFlags & BLF_FLEXRAYRCVMSG_FRAME_FLAG_SYNC) == BLF_FLEXRAYRCVMSG_FRAME_FLAG_SYNC) {
        tmpbuf[2] |= BLF_DLT_FLEXRAY_SFI;
    }

    if ((frheader.frameFlags & BLF_FLEXRAYRCVMSG_FRAME_FLAG_NULL_FRAME) != BLF_FLEXRAYRCVMSG_FRAME_FLAG_NULL_FRAME) {
        /* NFI needs to be inversed !? */
        tmpbuf[2] |= BLF_DLT_FLEXRAY_NFI;
    }

    if ((frheader.frameFlags & BLF_FLEXRAYRCVMSG_FRAME_FLAG_STARTUP) == BLF_FLEXRAYRCVMSG_FRAME_FLAG_STARTUP) {
        tmpbuf[2] |= BLF_DLT_FLEXRAY_STFI;
    }

    tmpbuf[3] = 0x00ff & frheader.frameId;
    tmpbuf[4] = (0xfe & frheader.payloadLength) | ((frheader.headerCrc1 & 0x0400) >> 10);
    tmpbuf[5] = (0x03fc & frheader.headerCrc1) >> 2;
    tmpbuf[6] = ((0x0003 & frheader.headerCrc1) << 6) | (0x3f & frheader.cycle);

    ws_buffer_assure_space(&params->rec->data, sizeof(tmpbuf) + payload_length_valid);
    ws_buffer_append(&params->rec->data, tmpbuf, sizeof(tmpbuf));
    caplen = sizeof(tmpbuf) + payload_length_valid;
    len = sizeof(tmpbuf) + payload_length;

    if (payload_length_valid > 0 && !blf_read_bytes(params, data_start + frheadersize, ws_buffer_end_ptr(&params->rec->data), payload_length_valid, err, err_info)) {
        ws_debug("copying flexray payload failed");
        return false;
    }
    ws_buffer_increase_length(&params->rec->data, payload_length_valid);

    blf_init_rec(params, flags, object_timestamp, WTAP_ENCAP_FLEXRAY, frheader.channelMask, UINT16_MAX, caplen, len);
    blf_add_direction_option(params, frheader.dir);

    return true;
}

static bool
blf_read_linmessage(blf_params_t* params, int* err, char** err_info, int64_t block_start, int64_t data_start, int64_t object_length, uint32_t flags, uint64_t object_timestamp, bool crc_error) {
    blf_linmessage_t         linmessage;

    uint8_t  payload_length;
    unsigned len;

    if (object_length < (data_start - block_start) + (int)sizeof(linmessage)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup_printf("blf: %s: not enough bytes for %s in object", crc_error ? "LIN_CRC_ERROR" : "LIN_MESSAGE", crc_error ? "lincrcerror" : "linmessage");
        ws_debug("not enough bytes for %s in object", crc_error ? "lincrcerror" : "linmessage");
        return false;
    }

    if (!blf_read_bytes(params, data_start, &linmessage, sizeof(linmessage), err, err_info)) {
        ws_debug("not enough bytes for %s in file", crc_error ? "lincrcerror" : "linmessage");
        return false;
    }
    fix_endianness_blf_linmessage(&linmessage);

    linmessage.dlc &= 0x0f;
    linmessage.id &= 0x3f;

    payload_length = MIN(linmessage.dlc, 8);

    uint8_t tmpbuf[8];
    tmpbuf[0] = 1; /* message format rev = 1 */
    tmpbuf[1] = 0; /* reserved */
    tmpbuf[2] = 0; /* reserved */
    tmpbuf[3] = 0; /* reserved */
    tmpbuf[4] = linmessage.dlc << 4; /* dlc (4bit) | type (2bit) | checksum type (2bit) */
    tmpbuf[5] = linmessage.id; /* parity (2bit) | id (6bit) */
    tmpbuf[6] = (uint8_t)(linmessage.crc & 0xff); /* checksum */
    tmpbuf[7] = 0; /* errors */

    if (crc_error) {
        tmpbuf[7] |= 0x08;
    }

    ws_buffer_append(&params->rec->data, tmpbuf, sizeof(tmpbuf));
    ws_buffer_append(&params->rec->data, linmessage.data, payload_length);
    len = sizeof(tmpbuf) + payload_length;

    blf_init_rec(params, flags, object_timestamp, WTAP_ENCAP_LIN, linmessage.channel, UINT16_MAX, len, len);
    blf_add_direction_option(params, linmessage.dir);

    return true;
}

static bool
blf_read_linrcverror(blf_params_t* params, int* err, char** err_info, int64_t block_start, int64_t data_start, int64_t object_length, uint32_t flags, uint64_t object_timestamp) {
    blf_linrcverror_t   linmessage;

    if (object_length < (data_start - block_start) + (int)sizeof(linmessage)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup("blf: LIN_RCV_ERROR: not enough bytes for linrcverror in object");
        ws_debug("not enough bytes for linrcverror in object");
        return false;
    }

    if (!blf_read_bytes(params, data_start, &linmessage, sizeof(linmessage), err, err_info)) {
        ws_debug("not enough bytes for linrcverror in file");
        return false;
    }
    linmessage.channel = GUINT16_FROM_LE(linmessage.channel);

    linmessage.dlc &= 0x0f;
    linmessage.id &= 0x3f;

    uint8_t tmpbuf[8];
    tmpbuf[0] = 1; /* message format rev = 1 */
    tmpbuf[1] = 0; /* reserved */
    tmpbuf[2] = 0; /* reserved */
    tmpbuf[3] = 0; /* reserved */
    tmpbuf[4] = linmessage.dlc << 4; /* dlc (4bit) | type (2bit) | checksum type (2bit) */
    tmpbuf[5] = linmessage.id; /* parity (2bit) | id (6bit) */
    tmpbuf[6] = 0; /* checksum */
    /* XXX - This object can represent many different error types.
     * For now we always treat it as framing error,
     * but in the future we should expand it. */
    tmpbuf[7] = LIN_ERROR_FRAMING_ERROR; /* errors */

    ws_buffer_append(&params->rec->data, tmpbuf, sizeof(tmpbuf));

    blf_init_rec(params, flags, object_timestamp, WTAP_ENCAP_LIN, linmessage.channel, UINT16_MAX, sizeof(tmpbuf), sizeof(tmpbuf));

    return true;
}

static bool
blf_read_linsenderror(blf_params_t* params, int* err, char** err_info, int64_t block_start, int64_t data_start, int64_t object_length, uint32_t flags, uint64_t object_timestamp) {
    blf_linsenderror_t         linmessage;

    if (object_length < (data_start - block_start) + (int)sizeof(linmessage)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup("blf: LIN_SND_ERROR: not enough bytes for linsenderror in object");
        ws_debug("not enough bytes for linsenderror in object");
        return false;
    }

    if (!blf_read_bytes(params, data_start, &linmessage, sizeof(linmessage), err, err_info)) {
        ws_debug("not enough bytes for linsenderror in file");
        return false;
    }
    linmessage.channel = GUINT16_FROM_LE(linmessage.channel);

    linmessage.dlc &= 0x0f;
    linmessage.id &= 0x3f;

    uint8_t tmpbuf[8];
    tmpbuf[0] = 1; /* message format rev = 1 */
    tmpbuf[1] = 0; /* reserved */
    tmpbuf[2] = 0; /* reserved */
    tmpbuf[3] = 0; /* reserved */
    tmpbuf[4] = linmessage.dlc << 4; /* dlc (4bit) | type (2bit) | checksum type (2bit) */
    tmpbuf[5] = linmessage.id; /* parity (2bit) | id (6bit) */
    tmpbuf[6] = 0; /* checksum */
    tmpbuf[7] = LIN_ERROR_NO_SLAVE_RESPONSE; /* errors */

    ws_buffer_append(&params->rec->data, tmpbuf, sizeof(tmpbuf));

    blf_init_rec(params, flags, object_timestamp, WTAP_ENCAP_LIN, linmessage.channel, UINT16_MAX, sizeof(tmpbuf), sizeof(tmpbuf));

    return true;
}

static bool
blf_read_linwakeupevent(blf_params_t* params, int* err, char** err_info, int64_t block_start, int64_t data_start, int64_t object_length, uint32_t flags, uint64_t object_timestamp) {
    blf_linwakeupevent_t    linevent;

    if (object_length < (data_start - block_start) + (int)sizeof(linevent)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup("blf: LIN_WAKEUP: not enough bytes for linwakeup in object");
        ws_debug("not enough bytes for linwakeup in object");
        return false;
    }

    if (!blf_read_bytes(params, data_start, &linevent, sizeof(linevent), err, err_info)) {
        ws_debug("not enough bytes for linwakeup in file");
        return false;
    }
    linevent.channel = GUINT16_FROM_LE(linevent.channel);

    uint8_t tmpbuf[12]; /* LIN events have a fixed length of 12 bytes */
    tmpbuf[0] = 1; /* message format rev = 1 */
    tmpbuf[1] = 0; /* reserved */
    tmpbuf[2] = 0; /* reserved */
    tmpbuf[3] = 0; /* reserved */
    tmpbuf[4] = 3 << 2; /* dlc (4bit) | type (2bit) | checksum type (2bit) */
    tmpbuf[5] = 0; /* parity (2bit) | id (6bit) */
    tmpbuf[6] = 0; /* checksum */
    tmpbuf[7] = 0; /* errors */

    /* Wake-up event */
    tmpbuf[8] = 0xB0;
    tmpbuf[9] = 0xB0;
    tmpbuf[10] = 0x00;
    tmpbuf[11] = 0x04;

    ws_buffer_append(&params->rec->data, tmpbuf, sizeof(tmpbuf));

    blf_init_rec(params, flags, object_timestamp, WTAP_ENCAP_LIN, linevent.channel, UINT16_MAX, sizeof(tmpbuf), sizeof(tmpbuf));

    return true;
}

static bool
blf_read_linmessage2(blf_params_t* params, int* err, char** err_info, int64_t block_start, int64_t data_start, int64_t object_length, uint32_t flags, uint64_t object_timestamp, uint16_t object_version) {
    blf_linmessage2_t         linmessage;

    uint8_t  payload_length;
    unsigned len;

    if (object_length < (data_start - block_start) + (int)sizeof(linmessage)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup("blf: LIN_MESSAGE2: not enough bytes for linmessage2 in object");
        ws_debug("not enough bytes for linmessage2 in object");
        return false;
    }

    if (!blf_read_bytes(params, data_start, &linmessage, sizeof(linmessage), err, err_info)) {
        ws_debug("not enough bytes for linmessage2 in file");
        return false;
    }
    fix_endianness_blf_linmessage2(&linmessage);

    linmessage.linDataByteTimestampEvent.linMessageDescriptor.dlc &= 0x0f;
    linmessage.linDataByteTimestampEvent.linMessageDescriptor.id &= 0x3f;

    payload_length = MIN(linmessage.linDataByteTimestampEvent.linMessageDescriptor.dlc, 8);

    uint8_t tmpbuf[8];
    tmpbuf[0] = 1; /* message format rev = 1 */
    tmpbuf[1] = 0; /* reserved */
    tmpbuf[2] = 0; /* reserved */
    tmpbuf[3] = 0; /* reserved */
    tmpbuf[4] = linmessage.linDataByteTimestampEvent.linMessageDescriptor.dlc << 4; /* dlc (4bit) | type (2bit) | checksum type (2bit) */
    if (object_version >= 1) { /* The 'checksumModel' field is valid only if objectVersion >= 1 */
        switch (linmessage.linDataByteTimestampEvent.linMessageDescriptor.checksumModel) {
        case 0:
            tmpbuf[4] |= 1; /* Classic */
            break;
        case 1:
            tmpbuf[4] |= 2; /* Enhanced */
            break;
        default:
            break;
        }
    }
    tmpbuf[5] = linmessage.linDataByteTimestampEvent.linMessageDescriptor.id; /* parity (2bit) | id (6bit) */
    tmpbuf[6] = (uint8_t)(linmessage.crc & 0xff); /* checksum */
    tmpbuf[7] = 0; /* errors */

    ws_buffer_append(&params->rec->data, tmpbuf, sizeof(tmpbuf));
    ws_buffer_append(&params->rec->data, linmessage.data, payload_length);
    len = sizeof(tmpbuf) + payload_length;

    blf_init_rec(params, flags, object_timestamp, WTAP_ENCAP_LIN, linmessage.linDataByteTimestampEvent.linMessageDescriptor.linSynchFieldEvent.linBusEvent.channel, UINT16_MAX, len, len);
    blf_add_direction_option(params, linmessage.dir);

    return true;
}

static bool
blf_read_lincrcerror2(blf_params_t* params, int* err, char** err_info, int64_t block_start, int64_t data_start, int64_t object_length, uint32_t flags, uint64_t object_timestamp, uint16_t object_version) {
    blf_lincrcerror2_t         linmessage;

    uint8_t  payload_length;
    unsigned len;

    if (object_length < (data_start - block_start) + (int)sizeof(linmessage)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup("blf: LIN_CRC_ERROR2: not enough bytes for lincrcerror2 in object");
        ws_debug("not enough bytes for lincrcerror2 in object");
        return false;
    }

    if (!blf_read_bytes(params, data_start, &linmessage, sizeof(linmessage), err, err_info)) {
        ws_debug("not enough bytes for lincrcerror2 in file");
        return false;
    }
    fix_endianness_blf_lincrcerror2(&linmessage);

    linmessage.linDataByteTimestampEvent.linMessageDescriptor.dlc &= 0x0f;
    linmessage.linDataByteTimestampEvent.linMessageDescriptor.id &= 0x3f;

    payload_length = MIN(linmessage.linDataByteTimestampEvent.linMessageDescriptor.dlc, 8);

    uint8_t tmpbuf[8];
    tmpbuf[0] = 1; /* message format rev = 1 */
    tmpbuf[1] = 0; /* reserved */
    tmpbuf[2] = 0; /* reserved */
    tmpbuf[3] = 0; /* reserved */
    tmpbuf[4] = linmessage.linDataByteTimestampEvent.linMessageDescriptor.dlc << 4; /* dlc (4bit) | type (2bit) | checksum type (2bit) */
    if (object_version >= 1) { /* The 'checksumModel' field is valid only if objectVersion >= 1 */
        switch (linmessage.linDataByteTimestampEvent.linMessageDescriptor.checksumModel) {
        case 0:
            tmpbuf[4] |= 1; /* Classic */
            break;
        case 1:
            tmpbuf[4] |= 2; /* Enhanced */
            break;
        default:
            break;
        }
    }
    tmpbuf[5] = linmessage.linDataByteTimestampEvent.linMessageDescriptor.id; /* parity (2bit) | id (6bit) */
    tmpbuf[6] = (uint8_t)(linmessage.crc & 0xff); /* checksum */
    tmpbuf[7] = LIN_ERROR_CHECKSUM_ERROR; /* errors */

    ws_buffer_append(&params->rec->data, tmpbuf, sizeof(tmpbuf));
    ws_buffer_append(&params->rec->data, linmessage.data, payload_length);
    len = sizeof(tmpbuf) + payload_length;

    blf_init_rec(params, flags, object_timestamp, WTAP_ENCAP_LIN, linmessage.linDataByteTimestampEvent.linMessageDescriptor.linSynchFieldEvent.linBusEvent.channel, UINT16_MAX, len, len);
    blf_add_direction_option(params, linmessage.dir);

    return true;
}

static bool
blf_read_linrcverror2(blf_params_t* params, int* err, char** err_info, int64_t block_start, int64_t data_start, int64_t object_length, uint32_t flags, uint64_t object_timestamp, uint16_t object_version) {
    blf_linrcverror2_t         linmessage;

    uint8_t  payload_length;
    unsigned len;

    if (object_length < (data_start - block_start) + (int)sizeof(linmessage)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup("blf: LIN_RCV_ERROR2: not enough bytes for linrcverror2 in object");
        ws_debug("not enough bytes for linrcverror2 in object");
        return false;
    }

    if (!blf_read_bytes(params, data_start, &linmessage, sizeof(linmessage), err, err_info)) {
        ws_debug("not enough bytes for linrcverror2 in file");
        return false;
    }
    fix_endianness_blf_linrcverror2(&linmessage);

    linmessage.linDataByteTimestampEvent.linMessageDescriptor.dlc &= 0x0f;
    linmessage.linDataByteTimestampEvent.linMessageDescriptor.id &= 0x3f;

    if (linmessage.hasDataBytes) {
        payload_length = MIN(linmessage.linDataByteTimestampEvent.linMessageDescriptor.dlc, 8);
    }
    else {
        payload_length = 0;
    }

    uint8_t tmpbuf[8];
    tmpbuf[0] = 1; /* message format rev = 1 */
    tmpbuf[1] = 0; /* reserved */
    tmpbuf[2] = 0; /* reserved */
    tmpbuf[3] = 0; /* reserved */
    tmpbuf[4] = linmessage.linDataByteTimestampEvent.linMessageDescriptor.dlc << 4; /* dlc (4bit) | type (2bit) | checksum type (2bit) */
    if (object_version >= 1) { /* The 'checksumModel' field is valid only if objectVersion >= 1 */
        switch (linmessage.linDataByteTimestampEvent.linMessageDescriptor.checksumModel) {
        case 0:
            tmpbuf[4] |= 1; /* Classic */
            break;
        case 1:
            tmpbuf[4] |= 2; /* Enhanced */
            break;
        default:
            break;
        }
    }
    tmpbuf[5] = linmessage.linDataByteTimestampEvent.linMessageDescriptor.id; /* parity (2bit) | id (6bit) */
    tmpbuf[6] = 0; /* checksum */
    /* XXX - This object can represent many different error types.
     * For now we always treat it as framing error,
     * but in the future we should expand it. */
    tmpbuf[7] = LIN_ERROR_FRAMING_ERROR; /* errors */

    ws_buffer_append(&params->rec->data, tmpbuf, sizeof(tmpbuf));
    if (payload_length > 0) {
        ws_buffer_append(&params->rec->data, linmessage.data, payload_length);
    }
    len = sizeof(tmpbuf) + payload_length;

    blf_init_rec(params, flags, object_timestamp, WTAP_ENCAP_LIN, linmessage.linDataByteTimestampEvent.linMessageDescriptor.linSynchFieldEvent.linBusEvent.channel, UINT16_MAX, len, len);

    return true;
}

static bool
blf_read_linsenderror2(blf_params_t* params, int* err, char** err_info, int64_t block_start, int64_t data_start, int64_t object_length, uint32_t flags, uint64_t object_timestamp, uint16_t object_version) {
    blf_linsenderror2_t         linmessage;

    if (object_length < (data_start - block_start) + (int)sizeof(linmessage)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup("blf: LIN_SND_ERROR2: not enough bytes for linsenderror2 in object");
        ws_debug("not enough bytes for linsenderror2 in object");
        return false;
    }

    if (!blf_read_bytes(params, data_start, &linmessage, sizeof(linmessage), err, err_info)) {
        ws_debug("not enough bytes for linsenderror2 in file");
        return false;
    }
    fix_endianness_blf_linsenderror2(&linmessage);

    linmessage.linMessageDescriptor.dlc &= 0x0f;
    linmessage.linMessageDescriptor.id &= 0x3f;

    uint8_t tmpbuf[8];
    tmpbuf[0] = 1; /* message format rev = 1 */
    tmpbuf[1] = 0; /* reserved */
    tmpbuf[2] = 0; /* reserved */
    tmpbuf[3] = 0; /* reserved */
    tmpbuf[4] = linmessage.linMessageDescriptor.dlc << 4; /* dlc (4bit) | type (2bit) | checksum type (2bit) */
    if (object_version >= 1) { /* The 'checksumModel' field is valid only if objectVersion >= 1 */
        switch (linmessage.linMessageDescriptor.checksumModel) {
        case 0:
            tmpbuf[4] |= 1; /* Classic */
            break;
        case 1:
            tmpbuf[4] |= 2; /* Enhanced */
            break;
        default:
            break;
        }
    }
    tmpbuf[5] = linmessage.linMessageDescriptor.id; /* parity (2bit) | id (6bit) */
    tmpbuf[6] = 0; /* checksum */
    tmpbuf[7] = LIN_ERROR_NO_SLAVE_RESPONSE; /* errors */

    ws_buffer_append(&params->rec->data, tmpbuf, sizeof(tmpbuf));

    blf_init_rec(params, flags, object_timestamp, WTAP_ENCAP_LIN, linmessage.linMessageDescriptor.linSynchFieldEvent.linBusEvent.channel, UINT16_MAX, sizeof(tmpbuf), sizeof(tmpbuf));

    return true;
}

static bool
blf_read_linwakeupevent2(blf_params_t* params, int* err, char** err_info, int64_t block_start, int64_t data_start, int64_t object_length, uint32_t flags, uint64_t object_timestamp) {
    blf_linwakeupevent2_t   linevent;

    if (object_length < (data_start - block_start) + (int)sizeof(linevent)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup("blf: LIN_WAKEUP2: not enough bytes for linwakeup2 in object");
        ws_debug("not enough bytes for linwakeup2 in object");
        return false;
    }

    if (!blf_read_bytes(params, data_start, &linevent, sizeof(linevent), err, err_info)) {
        ws_debug("not enough bytes for linwakeup2 in file");
        return false;
    }
    fix_endianness_blf_linwakeupevent2(&linevent);

    uint8_t tmpbuf[12]; /* LIN events have a fixed length of 12 bytes */
    tmpbuf[0] = 1; /* message format rev = 1 */
    tmpbuf[1] = 0; /* reserved */
    tmpbuf[2] = 0; /* reserved */
    tmpbuf[3] = 0; /* reserved */
    tmpbuf[4] = 3 << 2; /* dlc (4bit) | type (2bit) | checksum type (2bit) */
    tmpbuf[5] = 0; /* parity (2bit) | id (6bit) */
    tmpbuf[6] = 0; /* checksum */
    tmpbuf[7] = 0; /* errors */

    /* Wake-up event */
    tmpbuf[8] = 0xB0;
    tmpbuf[9] = 0xB0;
    tmpbuf[10] = 0x00;
    tmpbuf[11] = 0x04;

    ws_buffer_append(&params->rec->data, tmpbuf, sizeof(tmpbuf));

    blf_init_rec(params, flags, object_timestamp, WTAP_ENCAP_LIN, linevent.linBusEvent.channel, UINT16_MAX, sizeof(tmpbuf), sizeof(tmpbuf));

    return true;
}

static bool
blf_read_linsleepmodeevent(blf_params_t* params, int* err, char** err_info, int64_t block_start, int64_t data_start, int64_t object_length, uint32_t flags, uint64_t object_timestamp) {
    blf_linsleepmodeevent_t   linevent;

    if (object_length < (data_start - block_start) + (int)sizeof(linevent)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup("blf: LIN_SLEEP: not enough bytes for linsleep in object");
        ws_debug("not enough bytes for linsleep in object");
        return false;
    }

    if (!blf_read_bytes(params, data_start, &linevent, sizeof(linevent), err, err_info)) {
        ws_debug("not enough bytes for linsleep in file");
        return false;
    }
    linevent.channel = GUINT16_FROM_LE(linevent.channel);

    uint8_t tmpbuf[12]; /* LIN events have a fixed length of 12 bytes */
    tmpbuf[0] = 1; /* message format rev = 1 */
    tmpbuf[1] = 0; /* reserved */
    tmpbuf[2] = 0; /* reserved */
    tmpbuf[3] = 0; /* reserved */
    tmpbuf[4] = 3 << 2; /* dlc (4bit) | type (2bit) | checksum type (2bit) */
    tmpbuf[5] = 0; /* parity (2bit) | id (6bit) */
    tmpbuf[6] = 0; /* checksum */
    tmpbuf[7] = 0; /* errors */

    switch (linevent.reason) {
    case BLF_LIN_SLEEP_REASON_GO_TO_SLEEP_FRAME:
        /* Go-to-Sleep event by Go-to-Sleep frame */
        tmpbuf[8] = 0xB0;
        tmpbuf[9] = 0xB0;
        tmpbuf[10] = 0x00;
        tmpbuf[11] = 0x01;
        break;
    case BLF_LIN_SLEEP_REASON_BUS_IDLE_TIMEOUT:
    case BLF_LIN_SLEEP_REASON_SILENT_SLEEPMODE_CMD:
        /* Go-to-Sleep event by Inactivity for more than 4s */
        tmpbuf[8] = 0xB0;
        tmpbuf[9] = 0xB0;
        tmpbuf[10] = 0x00;
        tmpbuf[11] = 0x02;
        break;
    case BLF_LIN_WU_REASON_EXTERNAL_WAKEUP_SIG:
    case BLF_LIN_WU_REASON_INTERNAL_WAKEUP_SIG:
    case BLF_LIN_WU_REASON_BUS_TRAFFIC: /* There's no "wake-up by bus traffic" event in the LIN packet. */
        /* Wake-up event by Wake-up signal */
        tmpbuf[8] = 0xB0;
        tmpbuf[9] = 0xB0;
        tmpbuf[10] = 0x00;
        tmpbuf[11] = 0x04;
        break;
    case BLF_LIN_WU_SLEEP_REASON_START_STATE:
    case BLF_LIN_NO_SLEEP_REASON_BUS_TRAFFIC:
        /* If we're just reporting on the initial state,
         * or the interface doesn't want to go to sleep,
         * report the current state as "event". */
        if (linevent.flags & 0x2) {
            /* Wake-up event by Wake-up signal */
            tmpbuf[8] = 0xB0;
            tmpbuf[9] = 0xB0;
            tmpbuf[10] = 0x00;
            tmpbuf[11] = 0x04;
        }
        else {
            /* Go-to-Sleep event by Inactivity for more than 4s */
            tmpbuf[8] = 0xB0;
            tmpbuf[9] = 0xB0;
            tmpbuf[10] = 0x00;
            tmpbuf[11] = 0x02;
        }
        break;
    default:
        tmpbuf[8] = 0x00;
        tmpbuf[9] = 0x00;
        tmpbuf[10] = 0x00;
        tmpbuf[11] = 0x00;
        break;
    }

    ws_buffer_append(&params->rec->data, tmpbuf, sizeof(tmpbuf));

    blf_init_rec(params, flags, object_timestamp, WTAP_ENCAP_LIN, linevent.channel, UINT16_MAX, sizeof(tmpbuf), sizeof(tmpbuf));

    return true;
}

static bool
blf_parse_xml_port(const xmlChar* str, char** name, uint16_t* hwchannel, bool* simulated) {
    static const char name_magic[] = "name=";
    static const char hwchannel_magic[] = "hwchannel=";
    static const char simulated_magic[] = "simulated=";

    if (str == NULL) return false;

    char** tokens = g_strsplit_set((const gchar*)str, ";", -1);
    if (tokens == NULL) {
        ws_debug("cannot split XML port data");
        return false;
    }

    for (int i = 0; tokens[i] != NULL; i++) {
        const char* token = tokens[i];
        if (name && strncmp(token, name_magic, strlen(name_magic)) == 0) {
            if (*name == NULL) {    /* Avoid memory leak in case of repeated names */
                *name = ws_strdup(token + strlen(name_magic));
            }
        }
        else if (hwchannel && strncmp(token, hwchannel_magic, strlen(hwchannel_magic)) == 0) {
            if (!ws_strtou16(token + strlen(hwchannel_magic), NULL, hwchannel)) {
                *hwchannel = UINT16_MAX;
            }
        }
        else if (simulated && strncmp(token, simulated_magic, strlen(simulated_magic)) == 0) {
            if (strlen(token) > strlen(simulated_magic) && token[strlen(simulated_magic)] != '0') {
                *simulated = true;  /* TODO: Find a way to use this information */
            }
        }
    }

    g_strfreev(tokens);

    return true;
}

static int
blf_get_xml_pkt_encap(const xmlChar* str) {
    if (str == NULL) return 0;

    if (xmlStrcmp(str, "CAN") == 0) {
        return WTAP_ENCAP_SOCKETCAN;
    }
    if (xmlStrcmp(str, "FlexRay") == 0) {
        return WTAP_ENCAP_FLEXRAY;
    }
    if (xmlStrcmp(str, "LIN") == 0) {
        return WTAP_ENCAP_LIN;
    }
    if (xmlStrcmp(str, "Ethernet") == 0) {
        return WTAP_ENCAP_ETHERNET;
    }
    if (xmlStrcmp(str, "WLAN") == 0) {    /* Not confirmed with a real capture */
        return WTAP_ENCAP_IEEE_802_11;
    }

    return WTAP_ENCAP_UNKNOWN;
}


/** Extracts the channel and port names from a channels XML.
 *
 * A sample channels XML looks like this:
 *
 * <?xml version="1.0" encoding="UTF-8"?>
 * <channels version="1">
 *   <channel number="1" type="CAN" network="CAN01">
 *     <databases>
 *       <database file="DB.arxml" path="C:\...\" cluster="CAN01" />
 *       <database file="DB.dbc" path="C:\...\" cluster="General" />
 *     </databases>
 *   </channel>
 *   <channel number="1" type="LIN" network="LIN01">
 *     <databases>
 *       <database file="DB.dbc" path="C:\...\" cluster="General" />
 *       <database file="DB.ldf" path="C:\...\" cluster="LIN01" />
 *     </databases>
 *   </channel>
 *   <channel number="1" type="Ethernet" network="ETH01">
 *     <databases>
 *       <database file="DB.dbc" path="C:\...\" cluster="General" />
 *     </databases>
 *     <channel_properties>
 *       <elist name="ports">
 *         <eli name="port">name=Port1;hwchannel=11;simulated=1</eli>
 *         <eli name="port">name=Port2;hwchannel=12;simulated=0</eli>
 *       </elist>
 *     </channel_properties>
 *   </channel>
 * </channels>
 */
static bool
blf_set_xml_channels(blf_params_t* params, const char* text, size_t len) {
    xmlDocPtr doc;
    xmlNodePtr root_element = NULL;
    xmlNodePtr channels = NULL;

    if (text == NULL) return false;

    /* Now it can be parsed into a proper structure */
    doc = xmlParseMemory(text, (int)len);
    if (doc == NULL) {
        ws_debug("invalid xml found");
        return false;
    }

    root_element = xmlDocGetRootElement(doc);
    if (root_element == NULL) {
        ws_debug("empty xml doc");
        xmlFreeDoc(doc);
        return false;
    }

    if (xmlStrcmp(root_element->name, (const xmlChar*)"channels") == 0) {
        channels = root_element;
    } else {
        for (xmlNodePtr cur = root_element->children; cur != NULL; cur = cur->next) {
            if (cur->type == XML_ELEMENT_NODE && xmlStrcmp(cur->name, (const xmlChar*)"channels") == 0) {
                channels = cur;
                break;
            }
        }
    }

    if (channels == NULL) {
        ws_debug("No channels found");
        xmlFreeDoc(doc);
        return false;
    }

    for (xmlNodePtr current_channel_node = channels->children; current_channel_node != NULL; current_channel_node = current_channel_node->next) {
        if ((current_channel_node->type == XML_ELEMENT_NODE) && (xmlStrcmp(current_channel_node->name, (const xmlChar*)"channel") == 0)) {
            /* Reset the found attributes */
            int pkt_encap = WTAP_ENCAP_UNKNOWN;
            uint16_t channel = UINT16_MAX;
            char* channel_name = NULL;

            for (xmlAttrPtr attr = current_channel_node->properties; attr; attr = attr->next) {
                if (xmlStrcmp(attr->name, (const xmlChar*)"number") == 0) {
                    xmlChar* str_channel = xmlNodeListGetString(current_channel_node->doc, attr->children, 1);
                    if (str_channel != NULL) {
                        ws_strtou16(str_channel, NULL, &channel);
                        xmlFree(str_channel);
                    }
                }
                else if (xmlStrcmp(attr->name, (const xmlChar*)"type") == 0) {
                    xmlChar* str_type = xmlNodeListGetString(current_channel_node->doc, attr->children, 1);
                    if (str_type != NULL) {
                        pkt_encap = blf_get_xml_pkt_encap(str_type);
                        xmlFree(str_type);
                    }
                }
                else if (xmlStrcmp(attr->name, (const xmlChar*)"network") == 0) {
                    xmlChar* str_network = xmlNodeListGetString(current_channel_node->doc, attr->children, 1);
                    if (str_network != NULL) {
                        channel_name = ws_strdup((const char*)str_network);
                        xmlFree(str_network);
                    }
                }
            }

            if (pkt_encap != WTAP_ENCAP_UNKNOWN && channel != UINT16_MAX && channel_name != NULL) {
                ws_debug("Found channel in XML: PKT_ENCAP: %d, ID: %u, name: %s", pkt_encap, channel, channel_name);
                blf_prepare_interface_name(params, pkt_encap, channel, UINT16_MAX, channel_name, true);

                /* Look for ports under the channel properties */
                for (xmlNodePtr channel_property = current_channel_node->children; channel_property != NULL; channel_property = channel_property->next) {
                    if ((channel_property->type == XML_ELEMENT_NODE) && (xmlStrcmp(channel_property->name, (const xmlChar*)"channel_properties") == 0)) {
                        for (xmlNodePtr prop_child = channel_property->children; prop_child != NULL; prop_child = prop_child->next) {
                            if (prop_child->type == XML_ELEMENT_NODE && xmlStrcmp(prop_child->name, (const xmlChar*)"elist") == 0) {
                                xmlNodePtr elist_node = prop_child;
                                xmlChar* str_name = xmlGetProp(elist_node, (const xmlChar*)"name");
                                if (xmlStrcmp(str_name, (const xmlChar*)"ports") == 0) {
                                    for (xmlNodePtr eli_node = elist_node->children; eli_node != NULL; eli_node = eli_node->next) {
                                        if (eli_node->type == XML_ELEMENT_NODE && xmlStrcmp(eli_node->name, (const xmlChar*)"eli") == 0) {
                                            xmlChar* eli_name_attr = xmlGetProp(eli_node, (const xmlChar*)"name");
                                            if (xmlStrcmp(eli_name_attr, (const xmlChar*)"port") == 0) {
                                                char* port_name = NULL;
                                                uint16_t hwchannel = UINT16_MAX;
                                                bool simulated = false;
                                                char* iface_name = NULL;
                                                xmlChar* eli_content = xmlNodeGetContent(eli_node);

                                                bool res = blf_parse_xml_port(eli_content, &port_name, &hwchannel, &simulated);
                                                if (res && port_name != NULL && hwchannel != UINT16_MAX) {
                                                    iface_name = ws_strdup_printf("%s::%s", channel_name, port_name);
                                                    ws_debug("Found channel in XML: PKT_ENCAP: %d, ID: %u, HW ID: %u, name: %s", pkt_encap, channel, hwchannel, iface_name);
                                                    blf_prepare_interface_name(params, pkt_encap, channel, hwchannel, iface_name, true);
                                                    g_free(iface_name);
                                                }
                                                else {
                                                    ws_debug("port with missing or malformed info found in xml");
                                                }
                                                g_free(port_name);
                                                xmlFree(eli_content);
                                            }
                                            xmlFree(eli_name_attr);
                                        }
                                    }
                                }
                                xmlFree(str_name);
                            }
                        }
                    }
                }
            }
            g_free(channel_name);
        }
    }

    xmlFreeDoc(doc);
    return true;
}

static int
blf_read_apptextmessage(blf_params_t *params, int *err, char **err_info, int64_t block_start, int64_t data_start, int64_t object_length, uint32_t flags, uint64_t object_timestamp, blf_metadata_info_t* metadata_info) {
    blf_apptext_t            apptextheader;

    if (object_length < (data_start - block_start) + (int)sizeof(apptextheader)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup("blf: APP_TEXT: not enough bytes for apptext header in object");
        ws_debug("not enough bytes for apptext header in object");
        return BLF_APPTEXT_FAILED;
    }

    if (!blf_read_bytes(params, data_start, &apptextheader, sizeof(apptextheader), err, err_info)) {
        ws_debug("not enough bytes for apptext header in file");
        return BLF_APPTEXT_FAILED;
    }
    fix_endianness_blf_apptext_header(&apptextheader);

    if (metadata_info->valid && apptextheader.source != BLF_APPTEXT_METADATA) {
        /* If we're in the middle of a sequence of metadata objects,
         * but we get an AppText object from another source,
         * skip the previously incomplete object and start fresh.
         */
        metadata_info->valid = false;
    }

    /* Add an extra byte for a terminating '\0' */
    char* text = g_try_malloc((size_t)apptextheader.textLength + 1);
    if (text == NULL) {
        ws_debug("cannot allocate memory");
        return BLF_APPTEXT_FAILED;
    }

    if (!blf_read_bytes(params, data_start + sizeof(apptextheader), text, apptextheader.textLength, err, err_info)) {
        ws_debug("not enough bytes for apptext text in file");
        g_free(text);
        return BLF_APPTEXT_FAILED;
    }
    text[apptextheader.textLength] = '\0'; /* Here's the '\0' */

    switch (apptextheader.source) {
    case BLF_APPTEXT_CHANNEL:
    {

        /* returns a NULL terminated array of NULL terminates strings */
        char** tokens = g_strsplit_set(text, ";", -1);

        if (tokens == NULL || tokens[0] == NULL || tokens[1] == NULL) {
            if (tokens != NULL) {
                g_strfreev(tokens);
            }
            g_free(text);
            return BLF_APPTEXT_CHANNEL;
        }

        uint16_t channel = (apptextheader.reservedAppText1 >> 8) & 0xff;
        int pkt_encap;

        switch ((apptextheader.reservedAppText1 >> 16) & 0xff) {
        case BLF_BUSTYPE_CAN:
            pkt_encap = WTAP_ENCAP_SOCKETCAN;
            break;

        case BLF_BUSTYPE_FLEXRAY:
            pkt_encap = WTAP_ENCAP_FLEXRAY;
            break;

        case BLF_BUSTYPE_LIN:
            pkt_encap = WTAP_ENCAP_LIN;
            break;

        case BLF_BUSTYPE_ETHERNET:
            pkt_encap = WTAP_ENCAP_ETHERNET;
            break;

        case BLF_BUSTYPE_WLAN:
            pkt_encap = WTAP_ENCAP_IEEE_802_11;
            break;

        default:
            pkt_encap = WTAP_ENCAP_UNKNOWN;
            break;
        }

        if (pkt_encap != WTAP_ENCAP_UNKNOWN) {
            /* we use lookup to create interface, if not existing yet */
            blf_prepare_interface_name(params, pkt_encap, channel, UINT16_MAX, tokens[1], false);
        }

        g_strfreev(tokens);
        g_free(text);
        return BLF_APPTEXT_CHANNEL;
    }
    case BLF_APPTEXT_METADATA:
        if (metadata_info->valid) {
            /* Set the buffer pointer to the end of the previous object */
            params->rec->data.first_free = metadata_info->metadata_cont;
        }
        else {
            /* First object of a sequence of one or more */
            wtap_buffer_append_epdu_string(&params->rec->data, EXP_PDU_TAG_DISSECTOR_NAME, BLF_APPTEXT_TAG_DISS_DEFAULT);
            wtap_buffer_append_epdu_string(&params->rec->data, EXP_PDU_TAG_COL_PROT_TEXT, BLF_APPTEXT_COL_PROT_TEXT);
            switch (((apptextheader.reservedAppText1 >> 24) & 0xff)) {
            case BLF_APPTEXT_XML_GENERAL:
                wtap_buffer_append_epdu_string(&params->rec->data, EXP_PDU_TAG_COL_INFO_TEXT, BLF_APPTEXT_COL_INFO_TEXT_GENERAL);
                break;

            case BLF_APPTEXT_XML_CHANNELS:
                wtap_buffer_append_epdu_string(&params->rec->data, EXP_PDU_TAG_COL_INFO_TEXT, BLF_APPTEXT_COL_INFO_TEXT_CHANNELS);
                break;

            case BLF_APPTEXT_XML_IDENTITY:
                wtap_buffer_append_epdu_string(&params->rec->data, EXP_PDU_TAG_COL_INFO_TEXT, BLF_APPTEXT_COL_INFO_TEXT_IDENTITY);
                break;

            default:
                wtap_buffer_append_epdu_string(&params->rec->data, EXP_PDU_TAG_COL_INFO_TEXT, BLF_APPTEXT_COL_INFO_TEXT);
            }
            wtap_buffer_append_epdu_end(&params->rec->data);
            metadata_info->payload_start = params->rec->data.first_free;
        }

        ws_buffer_append(&params->rec->data, text, apptextheader.textLength);
        g_free(text);

        if ((apptextheader.reservedAppText1 & 0x00ffffff) > apptextheader.textLength) {
            /* Continues in the next object */
            return BLF_APPTEXT_CONT;
        }

        if (((apptextheader.reservedAppText1 >> 24) & 0xff) == BLF_APPTEXT_XML_CHANNELS) {
            blf_set_xml_channels(params, params->rec->data.data + metadata_info->payload_start, params->rec->data.first_free - metadata_info->payload_start);
        }

        /* Override the timestamp with 0 for metadata objects. Thay can only occur at the beginning of the file, and they usually already have a timestamp of 0. */
        blf_init_rec(params, 0, 0, WTAP_ENCAP_WIRESHARK_UPPER_PDU, 0, UINT16_MAX, (uint32_t)ws_buffer_length(&params->rec->data), (uint32_t)ws_buffer_length(&params->rec->data));
        return BLF_APPTEXT_METADATA;
    case BLF_APPTEXT_COMMENT:
    case BLF_APPTEXT_ATTACHMENT:
    case BLF_APPTEXT_TRACELINE:
    {
        wtap_buffer_append_epdu_string(&params->rec->data, EXP_PDU_TAG_DISSECTOR_NAME, BLF_APPTEXT_TAG_DISS_DEFAULT);
        wtap_buffer_append_epdu_string(&params->rec->data, EXP_PDU_TAG_COL_PROT_TEXT, BLF_APPTEXT_COL_PROT_TEXT);

        char* info_line = NULL;
        switch (apptextheader.source) {
        case BLF_APPTEXT_COMMENT:
            info_line = ws_strdup_printf("Comment: %s", text);
            break;
        case BLF_APPTEXT_ATTACHMENT:
            info_line = ws_strdup_printf("Attachment: %s", text);
            break;
        case BLF_APPTEXT_TRACELINE:
            info_line = ws_strdup_printf("Trace line%s: %s", (apptextheader.reservedAppText1 & 0x00000010) ? "" : " (hidden)", text);
            break;
        default:
            break;
        }

        wtap_buffer_append_epdu_string(&params->rec->data, EXP_PDU_TAG_COL_INFO_TEXT, info_line);
        wtap_buffer_append_epdu_end(&params->rec->data);

        size_t text_length = strlen(text);  /* The string can contain '\0' before textLength bytes */
        ws_buffer_append(&params->rec->data, text, text_length);    /* The dissector doesn't need NULL-terminated strings */

        /* We'll write this as a WS UPPER PDU packet with a text blob */
        blf_init_rec(params, flags, object_timestamp, WTAP_ENCAP_WIRESHARK_UPPER_PDU, 0, UINT16_MAX, (uint32_t)ws_buffer_length(&params->rec->data), (uint32_t)ws_buffer_length(&params->rec->data));
        g_free(text);
        if (info_line) {
            g_free(info_line);
        }
        return apptextheader.source;
    }
    default:
        g_free(text);
        return BLF_APPTEXT_CHANNEL; /* Cheat - no block to write */;
    }
    return BLF_APPTEXT_CHANNEL; /* Cheat - no block to write */
}

static bool
blf_read_ethernet_status(blf_params_t* params, int* err, char** err_info, int64_t block_start, int64_t data_start, int64_t object_length, uint32_t flags, uint64_t object_timestamp, uint16_t object_version) {
    blf_ethernet_status_t            ethernet_status_header;
    uint8_t tmpbuf[24];
    uint64_t linkUpDuration;

    if (object_length < (data_start - block_start) + (int)sizeof(ethernet_status_header) + (int)(object_version >= 1 ? 8 : 0)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup("blf: ETHERNET_STATUS: not enough bytes for ethernet status header in object");
        ws_debug("not enough bytes for ethernet status header in object");
        return false;
    }

    if (!blf_read_bytes(params, data_start, &ethernet_status_header, sizeof(ethernet_status_header), err, err_info)) {
        ws_debug("not enough bytes for ethernet_status_header header in file");
        return false;
    }

    if (object_version >= 1) {
        if (!blf_read_bytes(params, data_start + sizeof(ethernet_status_header), &linkUpDuration, 8, err, err_info)) {
            ws_debug("not enough bytes for ethernet_status_header header in file");
            return false;
        }
        linkUpDuration = GUINT64_FROM_LE(linkUpDuration);
    }

    fix_endianness_blf_ethernet_status_header(&ethernet_status_header);

    phtonu16(tmpbuf, ethernet_status_header.channel);
    phtonu16(tmpbuf + 2, ethernet_status_header.flags);
    tmpbuf[4] = (ethernet_status_header.linkStatus);
    tmpbuf[5] = (ethernet_status_header.ethernetPhy);
    tmpbuf[6] = (ethernet_status_header.duplex);
    tmpbuf[7] = (ethernet_status_header.mdi);
    tmpbuf[8] = (ethernet_status_header.connector);
    tmpbuf[9] = (ethernet_status_header.clockMode);
    tmpbuf[10] = (ethernet_status_header.pairs);
    tmpbuf[11] = (ethernet_status_header.hardwareChannel);
    phtonu32(tmpbuf + 12, ethernet_status_header.bitrate);

    if (object_version >= 1) {
        phtonu64(tmpbuf + 16, linkUpDuration);
    }

    wtap_buffer_append_epdu_string(&params->rec->data, EXP_PDU_TAG_DISSECTOR_NAME, BLF_APPTEXT_TAG_DISS_ETHSTATUS);
    wtap_buffer_append_epdu_end(&params->rec->data);

    ws_buffer_append(&params->rec->data, tmpbuf, (size_t)(object_version >= 1 ? 24 : 16));

    /* We'll write this as a WS UPPER PDU packet with a data blob */
    /* This will create an interface with the "name" of the matching
     * WTAP_ENCAP_ETHERNET interface with the same channel and hardware
     * channel prefixed with "STATUS" and with a different interface ID,
     * because IDBs in pcapng can only have one linktype.
     * The other option would be to write everything as UPPER_PDU, including
     * the Ethernet data (with one of the "eth_" dissectors.)
     */
    char* iface_name = ws_strdup_printf("STATUS-ETH-%u-%u", ethernet_status_header.channel, ethernet_status_header.hardwareChannel);
    blf_lookup_interface(params, WTAP_ENCAP_WIRESHARK_UPPER_PDU, ethernet_status_header.channel, ethernet_status_header.hardwareChannel, iface_name);
    g_free(iface_name);
    blf_init_rec(params, flags, object_timestamp, WTAP_ENCAP_WIRESHARK_UPPER_PDU, ethernet_status_header.channel, ethernet_status_header.hardwareChannel, (uint32_t)ws_buffer_length(&params->rec->data), (uint32_t)ws_buffer_length(&params->rec->data));

    if ((ethernet_status_header.flags & BLF_ETH_STATUS_HARDWARECHANNEL) == BLF_ETH_STATUS_HARDWARECHANNEL) {
        /* If HW channel valid */
        wtap_block_add_uint32_option(params->rec->block, OPT_PKT_QUEUE, ethernet_status_header.hardwareChannel);
    }

    return true;
}

static bool
blf_read_ethernet_phystate(blf_params_t* params, int* err, char** err_info, int64_t block_start, int64_t data_start, int64_t object_length, uint32_t flags, uint64_t object_timestamp) {
    blf_ethernet_phystate_t ethernet_phystate_header;
    uint8_t tmpbuf[8];

    if (object_length < (data_start - block_start) + (int)sizeof(ethernet_phystate_header)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup("blf: ETHERNET_PHY_STATE: not enough bytes for ethernet phystate header in object");
        ws_debug("not enough bytes for ethernet phystate header in object");
        return false;
    }

    if (!blf_read_bytes(params, data_start, &ethernet_phystate_header, sizeof(ethernet_phystate_header), err, err_info)) {
        ws_debug("not enough bytes for ethernet phystate header in file");
        return false;
    }

    fix_endianness_blf_ethernet_phystate_header(&ethernet_phystate_header);

    phtonu16(tmpbuf, ethernet_phystate_header.channel);
    phtonu16(tmpbuf + 2, ethernet_phystate_header.flags);
    tmpbuf[4] = (ethernet_phystate_header.phyState);
    tmpbuf[5] = (ethernet_phystate_header.phyEvent);
    tmpbuf[6] = (ethernet_phystate_header.hardwareChannel);
    tmpbuf[7] = (ethernet_phystate_header.res1);

    wtap_buffer_append_epdu_string(&params->rec->data, EXP_PDU_TAG_DISSECTOR_NAME, BLF_APPTEXT_TAG_DISS_ETHPHYSTATUS);
    wtap_buffer_append_epdu_end(&params->rec->data);

    ws_buffer_append(&params->rec->data, tmpbuf, sizeof(tmpbuf));

    /* We'll write this as a WS UPPER PDU packet with a data blob */
    /* This will create an interface with the "name" of the matching
     * WTAP_ENCAP_ETHERNET interface with the same channel and hardware
     * channel prefixed with "STATUS" and with a different interface ID,
     * because IDBs in pcapng can only have one linktype.
     * The other option would be to write everything as UPPER_PDU, including
     * the Ethernet data (with one of the "eth_" dissectors.)
     */
    char* iface_name = ws_strdup_printf("STATUS-ETH-%u-%u", ethernet_phystate_header.channel, ethernet_phystate_header.hardwareChannel);
    blf_lookup_interface(params, WTAP_ENCAP_WIRESHARK_UPPER_PDU, ethernet_phystate_header.channel, ethernet_phystate_header.hardwareChannel, iface_name);
    g_free(iface_name);
    blf_init_rec(params, flags, object_timestamp, WTAP_ENCAP_WIRESHARK_UPPER_PDU, ethernet_phystate_header.channel, ethernet_phystate_header.hardwareChannel, (uint32_t)ws_buffer_length(&params->rec->data), (uint32_t)ws_buffer_length(&params->rec->data));

    if ((ethernet_phystate_header.flags & BLF_PHY_STATE_HARDWARECHANNEL) == BLF_PHY_STATE_HARDWARECHANNEL) {
        /* If HW channel valid */
        wtap_block_add_uint32_option(params->rec->block, OPT_PKT_QUEUE, ethernet_phystate_header.hardwareChannel);
    }

    return true;
}

static bool
blf_read_block(blf_params_t *params, int64_t start_pos, int *err, char **err_info) {
    blf_blockheader_t        header;
    blf_logobjectheader_t    logheader;
    blf_logobjectheader2_t   logheader2;
    blf_logobjectheader3_t   logheader3;
    uint32_t                 flags;
    uint64_t                 object_timestamp;
    uint16_t                 object_version;
    blf_metadata_info_t      metadata_info = { 0, 0, false };
    int64_t                  last_metadata_start = 0;

    while (1) {
        /* Find Object */

        /* Resetting buffer */
        params->rec->data.first_free = params->rec->data.start;

        while (1) {
            if (!blf_read_bytes_or_eof(params, start_pos, &header, sizeof header, err, err_info)) {
                ws_debug("not enough bytes for block header or unsupported file");
                if (*err == WTAP_ERR_SHORT_READ) {
                    /* we have found the end that is not a short read therefore. */
                    *err = 0;
                    g_free(*err_info);
                    *err_info = NULL;
                }
                return false;
            }

            fix_endianness_blf_blockheader(&header);

            if (memcmp(header.magic, blf_obj_magic, sizeof(blf_obj_magic))) {
                ws_debug("object magic is not LOBJ (pos: 0x%" PRIx64 ")", start_pos);
            }
            else {
                break;
            }

            /* we are moving back and try again but 1 byte later */
            /* TODO: better understand how this paddings works... */
            start_pos++;
        }
        params->blf_data->start_of_last_obj = start_pos;

        if (!params->random) {
            /* Make sure that we start after this object next time,
             * but only if it's a linear read. We can have random reads
             * during the linear read, so we have to make sure we don't
             * lose track of our position.
             */
            params->blf_data->current_real_seek_pos = start_pos + MAX(MAX(16, header.object_length), header.header_length);
        }

        switch (header.header_type) {
        case BLF_HEADER_TYPE_DEFAULT:
            if (!blf_read_log_object_header(params, err, err_info, start_pos + sizeof(blf_blockheader_t), start_pos + header.header_length, &logheader)) {
                return false;
            }
            flags = logheader.flags;
            object_timestamp = logheader.object_timestamp;
            object_version = logheader.object_version;
            break;

        case BLF_HEADER_TYPE_2:
            if (!blf_read_log_object_header2(params, err, err_info, start_pos + sizeof(blf_blockheader_t), start_pos + header.header_length, &logheader2)) {
                return false;
            }
            flags = logheader2.flags;
            object_timestamp = logheader2.object_timestamp;
            object_version = logheader2.object_version;
            break;

        case BLF_HEADER_TYPE_3:
            if (!blf_read_log_object_header3(params, err, err_info, start_pos + sizeof(blf_blockheader_t), start_pos + header.header_length, &logheader3)) {
                return false;
            }
            flags = logheader3.flags;
            object_timestamp = logheader3.object_timestamp;
            object_version = logheader3.object_version;
            break;

        default:
            *err = WTAP_ERR_UNSUPPORTED;
            *err_info = ws_strdup_printf("blf: unknown header type %u", header.header_type);
            ws_debug("unknown header type");
            return false;
        }

        if (metadata_info.valid && header.object_type != BLF_OBJTYPE_APP_TEXT) {
            /* If we're in the middle of a sequence of AppText metadata objects,
             * but we get an AppText object from another source,
             * skip the previous incomplete packet and start fresh.
             */
            metadata_info.valid = false;
        }

        switch (header.object_type) {
        case BLF_OBJTYPE_LOG_CONTAINER:
            *err = WTAP_ERR_UNSUPPORTED;
            *err_info = ws_strdup("blf: log container in log container not supported");
            ws_debug("log container in log container not supported");
            return false;

        case BLF_OBJTYPE_ETHERNET_FRAME:
            return blf_read_ethernetframe(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, flags, object_timestamp);

        case BLF_OBJTYPE_ETHERNET_FRAME_EX:
            return blf_read_ethernetframe_ext(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, flags, object_timestamp, false);

        case BLF_OBJTYPE_ETHERNET_RX_ERROR:
            return blf_read_ethernet_rxerror(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, flags, object_timestamp);

        case BLF_OBJTYPE_ETHERNET_ERROR_EX:
            return blf_read_ethernetframe_ext(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, flags, object_timestamp, true);

        case BLF_OBJTYPE_WLAN_FRAME:
            return blf_read_wlanframe(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, flags, object_timestamp);

        case BLF_OBJTYPE_CAN_MESSAGE:
            return blf_read_canmessage(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, flags, object_timestamp, false);

        case BLF_OBJTYPE_CAN_ERROR:
            return blf_read_canerror(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, flags, object_timestamp, false);

        case BLF_OBJTYPE_CAN_OVERLOAD:
            return blf_read_canerror(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, flags, object_timestamp, true);

        case BLF_OBJTYPE_CAN_MESSAGE2:
            return blf_read_canmessage(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, flags, object_timestamp, true);

        case BLF_OBJTYPE_CAN_ERROR_EXT:
            return blf_read_canerrorext(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, flags, object_timestamp);

        case BLF_OBJTYPE_CAN_FD_MESSAGE:
            return blf_read_canfdmessage(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, flags, object_timestamp);

        case BLF_OBJTYPE_CAN_FD_MESSAGE_64:
            return blf_read_canfdmessage64(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, flags, object_timestamp);

        case BLF_OBJTYPE_CAN_FD_ERROR_64:
            return blf_read_canfderror64(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, flags, object_timestamp);

        case BLF_OBJTYPE_FLEXRAY_DATA:
            return blf_read_flexraydata(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, flags, object_timestamp);

        case BLF_OBJTYPE_FLEXRAY_MESSAGE:
            return blf_read_flexraymessage(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, flags, object_timestamp);

        case BLF_OBJTYPE_FLEXRAY_RCVMESSAGE:
            return blf_read_flexrayrcvmessageex(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, flags, object_timestamp, false);

        case BLF_OBJTYPE_FLEXRAY_RCVMESSAGE_EX:
            return blf_read_flexrayrcvmessageex(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, flags, object_timestamp, true);

        case BLF_OBJTYPE_LIN_MESSAGE:
            return blf_read_linmessage(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, flags, object_timestamp, false);

        case BLF_OBJTYPE_LIN_CRC_ERROR:
            return blf_read_linmessage(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, flags, object_timestamp, true);

        case BLF_OBJTYPE_LIN_RCV_ERROR:
            return blf_read_linrcverror(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, flags, object_timestamp);

        case BLF_OBJTYPE_LIN_SND_ERROR:
            return blf_read_linsenderror(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, flags, object_timestamp);

        case BLF_OBJTYPE_LIN_WAKEUP:
            return blf_read_linwakeupevent(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, flags, object_timestamp);

        case BLF_OBJTYPE_LIN_MESSAGE2:
            return blf_read_linmessage2(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, flags, object_timestamp, object_version);

        case BLF_OBJTYPE_LIN_CRC_ERROR2:
            return blf_read_lincrcerror2(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, flags, object_timestamp, object_version);

        case BLF_OBJTYPE_LIN_RCV_ERROR2:
            return blf_read_linrcverror2(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, flags, object_timestamp, object_version);

        case BLF_OBJTYPE_LIN_SND_ERROR2:
            return blf_read_linsenderror2(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, flags, object_timestamp, object_version);

        case BLF_OBJTYPE_LIN_WAKEUP2:
            return blf_read_linwakeupevent2(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, flags, object_timestamp);

        case BLF_OBJTYPE_LIN_SLEEP:
            return blf_read_linsleepmodeevent(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, flags, object_timestamp);

        case BLF_OBJTYPE_APP_TEXT:
        {
            int result = blf_read_apptextmessage(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, flags, object_timestamp, &metadata_info);
            if (result == BLF_APPTEXT_CONT) {
                if (!metadata_info.valid) {
                    /* First object of a sequence, save its start position */
                    last_metadata_start = start_pos;
                    metadata_info.valid = true;
                }
                /* Save a pointer to the end of the buffer */
                metadata_info.metadata_cont = params->rec->data.first_free;
            }
            else {
                if (result == BLF_APPTEXT_METADATA && metadata_info.valid) {
                    /* Last object of a sequence, restore the start position of the first object */
                    params->blf_data->start_of_last_obj = last_metadata_start;
                }
                /* Reset everything and start fresh */
                metadata_info.valid = false;
            }
            switch (result) {
                case BLF_APPTEXT_FAILED:
                    return false;
                case BLF_APPTEXT_COMMENT:
                case BLF_APPTEXT_METADATA:
                case BLF_APPTEXT_ATTACHMENT:
                case BLF_APPTEXT_TRACELINE:
                    return true;
                case BLF_APPTEXT_CHANNEL:
                case BLF_APPTEXT_CONT:
                default:
                    /* we do not return since there is no packet to show here */
                    start_pos += MAX(MAX(16, header.object_length), header.header_length);
                    break;
            }
        }
            break;

        case BLF_OBJTYPE_ETHERNET_STATUS:
            return blf_read_ethernet_status(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, flags, object_timestamp, object_version);

        case BLF_OBJTYPE_ETHERNET_PHY_STATE:
            return blf_read_ethernet_phystate(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, flags, object_timestamp);

        case BLF_OBJTYPE_ENV_INTEGER:
        case BLF_OBJTYPE_ENV_DOUBLE:
        case BLF_OBJTYPE_ENV_STRING:
        case BLF_OBJTYPE_ENV_DATA:
        case BLF_OBJTYPE_SYS_VARIABLE:
        case BLF_OBJTYPE_RESERVED5: /* Despite the name, this is actually used. Maybe it's worth investigating the content. */
        case BLF_OBJTYPE_TEST_STRUCTURE:
            ws_debug("skipping unsupported object type 0x%04x", header.object_type);
            start_pos += MAX(MAX(16, header.object_length), header.header_length);
            break;
        default:
            ws_info("unknown object type 0x%04x", header.object_type);
            start_pos += MAX(MAX(16, header.object_length), header.header_length);
            break;
        }
    }
    return true;
}

static bool blf_read(wtap *wth, wtap_rec *rec, int *err, char **err_info, int64_t *data_offset) {
    blf_params_t blf_tmp;

    blf_tmp.wth = wth;
    blf_tmp.fh  = wth->fh;
    blf_tmp.random = false;
    blf_tmp.pipe = wth->ispipe;
    blf_tmp.rec = rec;
    blf_tmp.blf_data = (blf_t *)wth->priv;

    if (!blf_read_block(&blf_tmp, blf_tmp.blf_data->current_real_seek_pos, err, err_info)) {
        return false;
    }
    *data_offset = blf_tmp.blf_data->start_of_last_obj;

    return true;
}

static bool blf_seek_read(wtap *wth, int64_t seek_off, wtap_rec *rec, int *err, char **err_info) {
    blf_params_t blf_tmp;

    blf_tmp.wth = wth;
    blf_tmp.fh  = wth->random_fh;
    blf_tmp.random = true;
    blf_tmp.pipe = wth->ispipe;
    blf_tmp.rec = rec;
    blf_tmp.blf_data = (blf_t *)wth->priv;

    if (!blf_read_block(&blf_tmp, seek_off, err, err_info)) {
        ws_debug("couldn't read packet block (err=%d).", *err);
        return false;
    }

    return true;
}

static void blf_free(blf_t *blf) {
    if (blf != NULL) {
        if (blf->log_containers != NULL) {
            for (unsigned i = 0; i < blf->log_containers->len; i++) {
                blf_log_container_t* log_container = &g_array_index(blf->log_containers, blf_log_container_t, i);
                if (log_container->real_data != NULL) {
                    g_free(log_container->real_data);
                }
            }
            g_array_free(blf->log_containers, true);
            blf->log_containers = NULL;
        }
        if (blf->channel_to_iface_ht != NULL) {
            g_hash_table_destroy(blf->channel_to_iface_ht);
            blf->channel_to_iface_ht = NULL;
        }
        if (blf->channel_to_name_ht != NULL) {
            g_hash_table_destroy(blf->channel_to_name_ht);
            blf->channel_to_name_ht = NULL;
        }
    }
}

static void blf_close(wtap *wth) {
    blf_free((blf_t *)wth->priv);

    /* TODO: do we need to reverse the wtap_add_idb? how? */
}

wtap_open_return_val
blf_open(wtap *wth, int *err, char **err_info) {
    blf_fileheader_t  header;
    blf_t            *blf;

    ws_debug("opening file");

    if (!wtap_read_bytes_or_eof(wth->fh, &header, sizeof(blf_fileheader_t), err, err_info)) {

        ws_debug("wtap_read_bytes_or_eof() failed, err = %d.", *err);
        if (*err == 0 || *err == WTAP_ERR_SHORT_READ) {
            /*
             * Short read or EOF.
             *
             * We're reading this as part of an open, so
             * the file is too short to be a blf file.
             */
            *err = 0;
            g_free(*err_info);
            *err_info = NULL;
            return WTAP_OPEN_NOT_MINE;
        }
        return WTAP_OPEN_ERROR;
    }

    fix_endianness_blf_fileheader(&header);

    if (memcmp(header.magic, blf_magic, sizeof(blf_magic))) {
        return WTAP_OPEN_NOT_MINE;
    }

    /* This seems to be an BLF! */
    /* Check for a valid header length */
    if (header.header_length < sizeof(blf_fileheader_t)) {
        *err = WTAP_ERR_BAD_FILE;
        *err_info = ws_strdup("blf: file header length too short");
        return WTAP_OPEN_ERROR;
    }

    /* skip past the header, which may include padding/reserved space */
    if (!wtap_read_bytes(wth->fh, NULL, header.header_length - sizeof(blf_fileheader_t), err, err_info)) {
        return WTAP_OPEN_ERROR;
    }

    /* Prepare our private context. */
    blf = g_new(blf_t, 1);
    blf->log_containers = g_array_new(false, false, sizeof(blf_log_container_t));
    blf->current_real_seek_pos = 0;
    blf->start_offset_ns = blf_get_start_offset_ns(&header.start_date);

    blf->channel_to_iface_ht = g_hash_table_new_full(g_int64_hash, g_int64_equal, &blf_free_key, &blf_free_channel_to_iface_entry);
    blf->channel_to_name_ht = g_hash_table_new_full(g_int64_hash, g_int64_equal, &blf_free_key, &blf_free_channel_to_name_entry);
    blf->next_interface_id = 0;

    wth->priv = (void *)blf;
    wth->file_encap = WTAP_ENCAP_NONE;
    wth->snapshot_length = 0;
    wth->file_tsprec = WTAP_TSPREC_UNKNOWN;
    wth->subtype_read = blf_read;
    wth->subtype_seek_read = blf_seek_read;
    wth->subtype_close = blf_close;
    wth->file_type_subtype = blf_file_type_subtype;

    wtap_block_t block = wtap_block_create(WTAP_BLOCK_SECTION);
    wtapng_section_mandatory_t *shb_mand = (wtapng_section_mandatory_t *)wtap_block_get_mandatory_data(block);
    shb_mand->section_length = UINT64_MAX;

    wtap_block_add_string_option_format(block, OPT_SHB_USERAPPL, "%s %d.%d.%d", try_val_to_str(header.application, blf_application_names),
                                        header.application_major, header.application_minor, header.application_build);
    wtap_block_copy(g_array_index(wth->shb_hdrs, wtap_block_t, 0), block);
    wtap_block_unref(block);

    return WTAP_OPEN_MINE;
}

/* Options for interface blocks. */
static const struct supported_option_type interface_block_options_supported[] = {
    /* No comments, just an interface name. */
    { OPT_IDB_NAME, ONE_OPTION_SUPPORTED }
};

static const struct supported_block_type blf_blocks_supported[] = {
    { WTAP_BLOCK_PACKET, MULTIPLE_BLOCKS_SUPPORTED, NO_OPTIONS_SUPPORTED },
    { WTAP_BLOCK_IF_ID_AND_INFO, MULTIPLE_BLOCKS_SUPPORTED, OPTION_TYPES_SUPPORTED(interface_block_options_supported) },
};


/***********************/
/* BLF Writing Support */
/***********************/

/* 10MB = 10485760 */
#define LOG_CONTAINER_BUFFER_SIZE 10485760

#define LOG_CONTAINER_NONE UINT64_MAX

typedef struct _blf_writer_data {
    GArray *iface_to_channel_array;
    bool iface_to_channel_names_recovered;

    blf_fileheader_t *fileheader;
    uint32_t object_count;
    uint64_t start_time;
    bool start_time_set;
    uint64_t end_time;

    uint64_t logcontainer_start;
    blf_blockheader_t logcontainer_block_header;
    blf_logcontainerheader_t logcontainer_header;
} blf_writer_data_t;

static void
blf_dump_init_channel_to_iface_entry(blf_channel_to_iface_entry_t* tmp, unsigned int if_id) {
    tmp->channel = 0;
    tmp->hwchannel = UINT16_MAX;
    tmp->interface_id = if_id;
    tmp->pkt_encap = WTAP_ENCAP_NONE;
}

static void
blf_dump_expand_interface_mapping(wtap_dumper *wdh, int new_size) {
    blf_writer_data_t *writer_data = (blf_writer_data_t *)wdh->priv;

    int old_size = writer_data->iface_to_channel_array->len;

    if (old_size < new_size) {
        /* we need to expand array */
        unsigned int number_of_new_elements = new_size - old_size;

        blf_channel_to_iface_entry_t *newdata = g_new0(blf_channel_to_iface_entry_t, number_of_new_elements);
        g_array_append_vals(writer_data->iface_to_channel_array, newdata, number_of_new_elements);

        for (unsigned int i = old_size; i < writer_data->iface_to_channel_array->len; i++) {
            blf_channel_to_iface_entry_t *tmp = &g_array_index(writer_data->iface_to_channel_array, blf_channel_to_iface_entry_t, i);
            blf_dump_init_channel_to_iface_entry(tmp, i);
        }
    }
}

static bool
blf_dump_set_interface_mapping(wtap_dumper *wdh, uint32_t interface_id, int pkt_encap, uint16_t channel, uint16_t hw_channel) {
    if (channel == 0) {
        ws_warning("Trying to set channel to 0! That will probably lead to an unreadable file! Replacing by 1 to limit problem!");
        channel = 1;
    }

    blf_writer_data_t *writer_data = (blf_writer_data_t *)wdh->priv;

    blf_dump_expand_interface_mapping(wdh, interface_id + 1);

    blf_channel_to_iface_entry_t *tmp = &g_array_index(writer_data->iface_to_channel_array, blf_channel_to_iface_entry_t, interface_id);
    tmp->channel = channel;
    tmp->hwchannel = hw_channel;
    tmp->interface_id = interface_id;
    tmp->pkt_encap = pkt_encap;

    return true;
}

static blf_channel_to_iface_entry_t *
blf_dump_get_interface_mapping(wtap_dumper *wdh, const wtap_rec *rec, int *err, char **err_info) {
    blf_writer_data_t *writer_data = (blf_writer_data_t *)wdh->priv;

    uint32_t interface_id = rec->rec_header.packet_header.interface_id;
    if (interface_id < writer_data->iface_to_channel_array->len) {
        return &g_array_index(writer_data->iface_to_channel_array, blf_channel_to_iface_entry_t, interface_id);
    }

    *err = WTAP_ERR_INTERNAL;
    *err_info = ws_strdup_printf("blf: cannot find interface mapping for %u", interface_id);
    ws_critical("BLF Interface Mapping cannot be found!");

    return NULL;
}

static bool
blf_init_file_header(wtap_dumper *wdh, int *err) {
    if (wdh == NULL || wdh->priv == NULL) {
        *err = WTAP_ERR_INTERNAL;
        ws_debug("internal error: blf private data not found!");
        return false;
    }

    blf_writer_data_t *writer_data = (blf_writer_data_t *)wdh->priv;

    writer_data->fileheader = g_new0(blf_fileheader_t, 1);

    /* set magic */
    int i;
    for (i = 0; i < 4; i++) {
        writer_data->fileheader->magic[i] = blf_magic[i];
    }

    /* currently only support 144 byte length*/
    writer_data->fileheader->header_length = 144;

    writer_data->fileheader->application_major = WIRESHARK_VERSION_MAJOR;
    writer_data->fileheader->application_minor = WIRESHARK_VERSION_MINOR;
    writer_data->fileheader->application_build = WIRESHARK_VERSION_MICRO;

    return true;
}

static bool
blf_write_add_padding(wtap_dumper *wdh, int *err, uint8_t count) {
    if (count > 0 && count < 4) {
        uint8_t padding[3] = { 0 };
        if (!wtap_dump_file_write(wdh, &padding, count, err)) {
            return false;
        }
    }
    return true;
}

static bool
blf_write_file_header_zeros(wtap_dumper *wdh, int *err) {
    /* lets add 144 bytes for the header and padding */
    uint8_t padding[144] = { 0 };
    if (!wtap_dump_file_write(wdh, &padding, 144, err)) {
        return false;
    }

    return true;
}

static void
blf_write_date_to_blf_header(blf_fileheader_t *fileheader, bool start, uint64_t ns_timestamp) {
    struct tm tmp;
    const time_t date = (time_t)(ns_timestamp / (1000 * 1000 * 1000));

    if (ws_localtime_r(&date, &tmp) != NULL) {
        blf_date_t *target = start ? &(fileheader->start_date) : &(fileheader->end_date);
        target->year = 1900 + tmp.tm_year;
        target->month = tmp.tm_mon + 1;
        target->day = tmp.tm_mday;
        target->hour = tmp.tm_hour;
        target->mins = tmp.tm_min;
        target->sec = tmp.tm_sec;

        uint64_t tmp_date = blf_get_start_offset_ns((const blf_date_t *)target);

        target->ms = (uint16_t)((ns_timestamp - tmp_date) / (1000 * 1000));
    }

}

static bool
blf_finalize_file_header(wtap_dumper *wdh, int *err) {
    blf_writer_data_t *writer_data = (blf_writer_data_t *)wdh->priv;
    blf_fileheader_t *fileheader = writer_data->fileheader;
    int64_t bytes_written = wtap_dump_file_tell(wdh, err);

    /* update the header and convert all to LE */
    fileheader->api_version = (((WIRESHARK_VERSION_MAJOR * 100) + WIRESHARK_VERSION_MINOR) * 100 + WIRESHARK_VERSION_MICRO) * 100;
    fileheader->application_major = WIRESHARK_VERSION_MAJOR;
    fileheader->application_minor = WIRESHARK_VERSION_MINOR;
    fileheader->application_build = WIRESHARK_VERSION_MICRO;

    fileheader->len_compressed = (uint64_t)bytes_written;
    fileheader->len_uncompressed = (uint64_t)bytes_written;

    fileheader->obj_count = writer_data->object_count;

    if (writer_data->start_time_set) {
        blf_write_date_to_blf_header(fileheader, true, writer_data->start_time);
    }

    blf_write_date_to_blf_header(fileheader, false, writer_data->end_time);

    fix_endianness_blf_fileheader(fileheader);

    /* seek to start of file */
    int64_t tmp = wtap_dump_file_seek(wdh, 0, SEEK_SET, err);
    if (*err != 0 || tmp != 0) {
        return false;
    }

    if (!wtap_dump_file_write(wdh, fileheader, fileheader->header_length, err)) {
        return false;
    }

    return true;
}

static bool blf_dump_write_logcontainer(wtap_dumper *wdh, int *err, char **err_info) {
    blf_writer_data_t *writer_data = (blf_writer_data_t *)wdh->priv;

    if (!wtap_dump_file_write(wdh, &(writer_data->logcontainer_block_header), sizeof(blf_blockheader_t), err)) {
        *err = WTAP_ERR_INTERNAL;
        *err_info = ws_strdup_printf("blf: cannot write Log Container Block Header");
        ws_warning("Cannot write Log Container Block Header");
        return false;
    }

    if (!wtap_dump_file_write(wdh, &(writer_data->logcontainer_header), sizeof(blf_logcontainerheader_t), err)) {
        *err = WTAP_ERR_INTERNAL;
        *err_info = ws_strdup_printf("blf: cannot write Log Container");
        ws_warning("Cannot write Log Container");
        return false;
    }

    return true;
}

static bool blf_dump_close_logcontainer(wtap_dumper *wdh, int *err, char **err_info) {
    blf_writer_data_t *writer_data = (blf_writer_data_t *)wdh->priv;

    int64_t current_position = wtap_dump_file_tell(wdh, err);

    int64_t tmp = wtap_dump_file_seek(wdh, writer_data->logcontainer_start, SEEK_SET, err);
    if (*err != 0 || tmp != 0) {
        return false;
    }

    int64_t logcontainer_length = current_position - writer_data->logcontainer_start;
    if (logcontainer_length < 32) {
        *err = WTAP_ERR_INTERNAL;
    }
    writer_data->logcontainer_block_header.object_length = GUINT32_TO_LE((uint32_t)logcontainer_length);
    writer_data->logcontainer_header.uncompressed_size = GUINT32_TO_LE((uint32_t)(logcontainer_length - 32));

    if (!blf_dump_write_logcontainer(wdh, err, err_info)) {
        return false;
    }

    tmp = wtap_dump_file_seek(wdh, current_position, SEEK_SET, err);
    if (*err != 0 || tmp != 0) {
        return false;
    }

    return true;
}

static bool blf_dump_start_logcontainer(wtap_dumper *wdh, int *err, char **err_info) {
    blf_writer_data_t *writer_data = (blf_writer_data_t *)wdh->priv;

    if (writer_data->logcontainer_start != LOG_CONTAINER_NONE) {
        if (!blf_dump_close_logcontainer(wdh, err, err_info)) {
            return false;
        }
    }

    /* start new log container */
    /* set magic */
    int i;
    for (i = 0; i < 4; i++) {
        writer_data->logcontainer_block_header.magic[i] = blf_obj_magic[i];
    }
    writer_data->logcontainer_block_header.header_length = 16;
    writer_data->logcontainer_block_header.header_type = 1;
    writer_data->logcontainer_block_header.object_length = 32;
    writer_data->logcontainer_block_header.object_type = BLF_OBJTYPE_LOG_CONTAINER;
    fix_endianness_blf_blockheader(&(writer_data->logcontainer_block_header));

    writer_data->logcontainer_header.compression_method = 0;
    writer_data->logcontainer_header.res1 = 0;
    writer_data->logcontainer_header.res2 = 0;
    writer_data->logcontainer_header.uncompressed_size = 0;
    writer_data->logcontainer_header.res4 = 0;
    fix_endianness_blf_logcontainerheader(&(writer_data->logcontainer_header));

    writer_data->logcontainer_start = wtap_dump_file_tell(wdh, err);

    return blf_dump_write_logcontainer(wdh, err, err_info);
}

static bool blf_dump_check_logcontainer_full(wtap_dumper *wdh, int *err, char **err_info, uint32_t length) {
    const blf_writer_data_t *writer_data = (blf_writer_data_t *)wdh->priv;

    uint64_t position = (uint64_t)wtap_dump_file_tell(wdh, err);
    if (position - writer_data->logcontainer_start + length <= LOG_CONTAINER_BUFFER_SIZE) {
        return true;
    }

    return blf_dump_start_logcontainer(wdh, err, err_info);
}

static bool blf_dump_objheader(wtap_dumper *wdh, int *err, uint64_t obj_timestamp, uint32_t obj_type, uint32_t obj_length) {
    blf_logobjectheader_t logheader;
    logheader.flags = BLF_TIMESTAMP_RESOLUTION_1NS;
    logheader.client_index = 0;
    logheader.object_version = 1;
    logheader.object_timestamp = obj_timestamp;
    fix_endianness_blf_logobjectheader(&logheader);

    blf_blockheader_t blockheader;
    /* set magic */
    int i;
    for (i = 0; i < 4; i++) {
        blockheader.magic[i] = blf_obj_magic[i];
    }
    blockheader.header_length = sizeof(blf_blockheader_t) + sizeof(blf_logobjectheader_t);
    blockheader.header_type = 1;
    blockheader.object_length = sizeof(blf_blockheader_t) + sizeof(blf_logobjectheader_t) + obj_length;
    blockheader.object_type = obj_type;
    fix_endianness_blf_blockheader(&blockheader);

    if (!wtap_dump_file_write(wdh, &(blockheader), sizeof(blf_blockheader_t), err)) {
        return false;
    }

    if (!wtap_dump_file_write(wdh, &(logheader), sizeof(blf_logobjectheader_t), err)) {
        return false;
    }

    return true;
}

/* return standard direction format of BLF, RX on error or unknown */
static uint8_t blf_get_direction(const wtap_rec *rec) {
    uint32_t tmp_direction = 0;
    if (WTAP_OPTTYPE_SUCCESS != wtap_block_get_uint32_option_value(rec->block, OPT_PKT_FLAGS, &tmp_direction)) {
        return BLF_DIR_RX;
    }

    if (tmp_direction == PACK_FLAGS_DIRECTION_OUTBOUND) {
        return BLF_DIR_TX;
    }

    return BLF_DIR_RX;
}

static bool blf_dump_ethernet(wtap_dumper *wdh, const wtap_rec *rec, int *err, char **err_info, uint64_t obj_timestamp) {
    /* LINKTYPE_ETHERNET */
    /* https://www.tcpdump.org/linktypes/LINKTYPE_LINUX_SLL.html */

    //blf_writer_data_t *writer_data = (blf_writer_data_t *)wdh->priv;
    const blf_channel_to_iface_entry_t *iface_entry = blf_dump_get_interface_mapping(wdh, rec, err, err_info);

    const uint8_t *pd = ws_buffer_start_ptr(&rec->data);
    size_t length = ws_buffer_length(&rec->data);

    /* 14 bytes is the full Ethernet Header up to EtherType */
    if (length < 14) {
        *err = WTAP_ERR_INTERNAL;
        *err_info = ws_strdup_printf("blf: record length %u for Ethernet message is lower than minimum of 14", (uint32_t)length);
        ws_warning("LINKTYPE_ETHERNET Data is too short!");
        return false;
    }

    uint32_t offset = 12;

    blf_ethernetframeheader_t ethheader;
    ethheader.src_addr[0] = pd[6];
    ethheader.src_addr[1] = pd[7];
    ethheader.src_addr[2] = pd[8];
    ethheader.src_addr[3] = pd[9];
    ethheader.src_addr[4] = pd[10];
    ethheader.src_addr[5] = pd[11];

    ethheader.channel = iface_entry->channel;

    ethheader.dst_addr[0] = pd[0];
    ethheader.dst_addr[1] = pd[1];
    ethheader.dst_addr[2] = pd[2];
    ethheader.dst_addr[3] = pd[3];
    ethheader.dst_addr[4] = pd[4];
    ethheader.dst_addr[5] = pd[5];

    ethheader.direction = blf_get_direction(rec);

    uint16_t eth_type = pntohu16(pd + offset);
    offset += 2;

    if (eth_type == 0x8100 || eth_type == 0x9100 || eth_type == 0x88a8) {
        ethheader.tpid = eth_type;
        ethheader.tci = pntohu16(pd + offset);
        offset += 2;

        eth_type = pntohu16(pd + offset);
        offset += 2;
    } else {
        ethheader.tpid = 0;
        ethheader.tci = 0;
    }

    ethheader.ethtype = eth_type;
    ethheader.payloadlength = rec->rec_header.packet_header.caplen - offset;
    ethheader.res = 0;
    fix_endianness_blf_ethernetframeheader(&ethheader);

    if (!blf_dump_objheader(wdh, err, obj_timestamp, BLF_OBJTYPE_ETHERNET_FRAME, sizeof(blf_ethernetframeheader_t) + ethheader.payloadlength)) {
        return false;
    }

    if (!wtap_dump_file_write(wdh, &(ethheader), sizeof(blf_ethernetframeheader_t), err)) {
        return false;
    }

    if (!wtap_dump_file_write(wdh, &(pd[offset]), ethheader.payloadlength, err)) {
        return false;
    }

    /* Add strange padding to 4 bytes. */
    uint8_t padding_needed = (sizeof(blf_ethernetframeheader_t) + ethheader.payloadlength) % 4;
    return blf_write_add_padding(wdh, err, padding_needed);
}

static const uint8_t canfd_length_to_dlc[] = { 0, 1, 2, 3,   4, 5, 6, 7,   8, 0, 0, 0,  9, 0, 0, 0,
                                              10, 0, 0, 0,  11, 0, 0, 0,  12, 0, 0, 0,  0, 0, 0, 0,
                                              13, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0,  0, 0, 0, 0,
                                              14, 0, 0, 0,   0, 0, 0, 0,   0, 0, 0, 0,  0, 0, 0, 0,
                                              15 };

static bool blf_dump_socketcan(wtap_dumper *wdh, const wtap_rec *rec, int *err, char **err_info, uint64_t obj_timestamp,
                               const uint8_t *pd, size_t length, bool is_can, bool is_canfd, bool is_rx, bool is_tx) {
    /* LINKTYPE_CAN_SOCKETCAN */
    /* https://www.tcpdump.org/linktypes/LINKTYPE_CAN_SOCKETCAN.html */

    //blf_writer_data_t *writer_data = (blf_writer_data_t *)wdh->priv;
    blf_channel_to_iface_entry_t *iface_entry = blf_dump_get_interface_mapping(wdh, rec, err, err_info);

    if (length < 8) {
        *err = WTAP_ERR_INTERNAL;
        *err_info = ws_strdup_printf("blf: record length %u for Socket CAN message header is lower than minimum of 8", (uint32_t)length);
        ws_warning("LINKTYPE_CAN_SOCKETCAN header is too short!");
        return false;
    }

    /* check for CAN-XL */
    if ((pd[4] & CANXL_XLF) == CANXL_XLF) {
        ws_message("CAN-XL not supported yet! Skipping.");
        return true;
    }

    uint8_t payload_length = pd[4];

    if (length < (size_t)payload_length + 8) {
        *err = WTAP_ERR_INTERNAL;
        *err_info = ws_strdup_printf("blf: Socket CAN message (length %u) does not contain full payload (%u)", (uint32_t)length, payload_length);
        ws_warning("LINKTYPE_CAN_SOCKETCAN header is too short!");
        return false;
    }

    /* LINKTYPE_LINUX_SLL would have set is_tx or is_rx */
    uint8_t frame_dir = is_tx ? BLF_DIR_TX : BLF_DIR_RX;
    if (!is_rx && !is_tx) {
        frame_dir = blf_get_direction(rec);
    }

    bool canfd = is_canfd;

    /* LINKTYPE_LINUX_SLL would have set one */
    if (!is_can && !is_canfd) {
        if ((pd[5] & CANFD_FDF) == CANFD_FDF) {
            canfd = true;
        } else {
            /* heuristic. if longer than header + 8 bytes data, its CAN-FD*/
            canfd = rec->rec_header.packet_header.caplen > 16;
        }
    }

    /* XXX endianess is not defined. Assuming BE as this seems the common choice*/
    uint32_t can_id = pntohu32(pd);

    /* lets check if can_id makes sense
     * 29bit CAN ID mask 0x1fffffff CAN_EFF_MASK
     * 11bit CAN ID mask 0x000007ff CAN_SFF_MASK
     * 29 only bits      0x1ffff800 CAN_EFF_MASK & !CAN_SFF_MASK
     */
    if (((can_id & CAN_EFF_FLAG) == 0) && ((can_id & (CAN_EFF_MASK & (!CAN_SFF_MASK))) != 0)) {
        ws_message("CAN-ID 0x%08x seems to be in wrong byte order, changing to little-endian", can_id);
        can_id = pletohu32(pd);
    }

    bool err_flag = (can_id & CAN_ERR_FLAG) == CAN_ERR_FLAG;
    bool rtr_flag = (can_id & CAN_RTR_FLAG) == CAN_RTR_FLAG;
    //bool ext_id_flag = (can_id & CAN_EFF_FLAG) == CAN_EFF_FLAG;
    can_id &= (CAN_EFF_MASK | CAN_EFF_FLAG);

    if (canfd) {
        /* CAN-FD */
        bool brs_flag = (pd[5] & CANFD_BRS) == CANFD_BRS;
        bool esi_flag = (pd[5] & CANFD_ESI) == CANFD_ESI;
        bool fdf_flag = (pd[5] & CANFD_FDF) == CANFD_FDF;

        blf_canfdmessage64_t canfdmsg;
        canfdmsg.channel = (uint8_t)iface_entry->channel;

        canfdmsg.dlc = (payload_length <= 64) ? canfd_length_to_dlc[payload_length] : 0;
        canfdmsg.validDataBytes = payload_length;
        canfdmsg.txCount = 0;
        canfdmsg.id = can_id;
        canfdmsg.frameLength_in_ns = 0;
        canfdmsg.flags = 0;

        /* TODO: fdf_flag is not always set for CAN-FD */
        if (fdf_flag) {
            canfdmsg.flags = BLF_CANFDMESSAGE64_FLAG_EDL; // CAN-FD
        } else {
            ws_warning("CAN-FD has not CANFD_FDF set. File not correct.");
        }
        if (brs_flag) {
            canfdmsg.flags |= BLF_CANFDMESSAGE64_FLAG_BRS;
        }
        if (esi_flag) {
            canfdmsg.flags |= BLF_CANFDMESSAGE64_FLAG_ESI;
        }

        canfdmsg.btrCfgArb = 0;
        canfdmsg.btrCfgData = 0;
        canfdmsg.timeOffsetBrsNs = 0;
        canfdmsg.timeOffsetCrcDelNs = 0;
        canfdmsg.bitCount = 0;
        canfdmsg.dir = frame_dir;
        canfdmsg.extDataOffset = 0;
        canfdmsg.crc = 0;

        fix_endianness_blf_canfdmessage64(&canfdmsg);

        if (!blf_dump_objheader(wdh, err, obj_timestamp, BLF_OBJTYPE_CAN_FD_MESSAGE_64, sizeof(blf_canfdmessage64_t) + payload_length)) {
            return false;
        }

        if (!wtap_dump_file_write(wdh, &(canfdmsg), sizeof(blf_canfdmessage64_t), err)) {
            return false;
        }
    } else {
        /* CAN */
        blf_canmessage_t canmsg;

        if (payload_length > 8) {
            ws_warning("CAN frames can only have up to 8 bytes of payload! We have %d bytes", payload_length);
            payload_length = 8;
        }

        canmsg.dlc = payload_length;
        canmsg.channel = iface_entry->channel;

        canmsg.flags = 0;
        if (frame_dir == BLF_DIR_TX) {
            canmsg.flags |= BLF_CANMESSAGE_FLAG_TX;
        }

        if (err_flag) {
            // TODO: we need to implement CAN ERROR, ignore for now
            return true;
            //canmsg.flags |= BLF_CANMESSAGE_FLAG_NERR; - NERR is not error
        }

        if (rtr_flag) {
            canmsg.flags |= BLF_CANMESSAGE_FLAG_RTR;
        }

        canmsg.id = can_id;

        fix_endianness_blf_canmessage(&canmsg);

        if (!blf_dump_objheader(wdh, err, obj_timestamp, BLF_OBJTYPE_CAN_MESSAGE, sizeof(blf_canmessage_t) + 8)) {
            return false;
        }

        if (!wtap_dump_file_write(wdh, &(canmsg), sizeof(blf_canmessage_t), err)) {
            return false;
        }
    }

    if (!wtap_dump_file_write(wdh, &(pd[8]), payload_length, err)) {
        return false;
    }

    if (!canfd && payload_length < 8) {
        uint8_t padding[8] = { 0 };
        if (!wtap_dump_file_write(wdh, &padding, 8 - payload_length, err)) {
            return false;
        }
    }

    /* no padding */

    return true;
}

static bool blf_dump_sll(wtap_dumper *wdh, const wtap_rec *rec, int *err, char **err_info, uint64_t obj_timestamp) {
    /* Linux Cooked CAN / CAN-FD */
    /* https://www.tcpdump.org/linktypes/LINKTYPE_LINUX_SLL.html */

    const uint8_t *pd = ws_buffer_start_ptr(&rec->data);
    size_t length = ws_buffer_length(&rec->data);

    if (length < 16) {
        *err = WTAP_ERR_INTERNAL;
        *err_info = ws_strdup_printf("blf: record length %u for CAN message header (LINKTYPE_LINUX_SLL) is lower than minimum of 16", (uint32_t)length);
        ws_warning("LINKTYPE_LINUX_SLL header is too short!");
        return false;
    }

    bool frame_tx = false;
    if (pd[0] == 0 && pd[1] == 4) {
        frame_tx = true;
    }

    uint16_t protocol_type = pntohu16(pd + 14);

    switch (protocol_type) {
    case 0x000C: /* CAN */
        return blf_dump_socketcan(wdh, rec, err, err_info, obj_timestamp, &(pd[16]), length - 16, true, false, !frame_tx, frame_tx);
        break;
    case 0x000D: /* CAN-FD */
        return blf_dump_socketcan(wdh, rec, err, err_info, obj_timestamp, &(pd[16]), length - 16, false, true, !frame_tx, frame_tx);
        break;
    default:
        return false;
    }

    /* not reachable? */
    return true;
}

static bool blf_dump_flexray(wtap_dumper *wdh, const wtap_rec *rec, int *err, char **err_info, uint64_t obj_timestamp) {
    /* FlexRay */
    /* https://www.tcpdump.org/linktypes/LINKTYPE_FLEXRAY.html */

    //blf_writer_data_t *writer_data = (blf_writer_data_t *)wdh->priv;
    blf_channel_to_iface_entry_t *iface_entry = blf_dump_get_interface_mapping(wdh, rec, err, err_info);

    const uint8_t *pd = ws_buffer_start_ptr(&rec->data);
    size_t length = ws_buffer_length(&rec->data);

    if (length < 1) {
        *err = WTAP_ERR_INTERNAL;
        *err_info = ws_strdup_printf("blf: record length %u for FlexRay header (LINKTYPE_FLEXRAY) is lower than minimum of 1", (uint32_t)length);
        ws_warning("LINKTYPE_FLEXRAY header is too short (< 1 Byte)!");
        return false;
    }

    /* Check Measurement Header for Type */
    if ((pd[0] & FLEXRAY_TYPE_MASK) == FLEXRAY_SYMBOL) {
        /* Symbol */

        if (length < 2) {
            *err = WTAP_ERR_INTERNAL;
            *err_info = ws_strdup_printf("blf: record length %u for FlexRay Symbol (LINKTYPE_FLEXRAY) is lower than minimum of 2", (uint32_t)length);
            ws_warning("LINKTYPE_FLEXRAY Symbol is too short (< 2 Byte)!");
            return false;
        }

        /* TODO: SYMBOL */

        return true;
    }

    if ((pd[0] & FLEXRAY_TYPE_MASK) == FLEXRAY_FRAME) {
        /* Frame */

        if (length < 2 + FLEXRAY_HEADER_LENGTH) {
            *err = WTAP_ERR_INTERNAL;
            *err_info = ws_strdup_printf("blf: record length %u for FlexRay Frame header (LINKTYPE_FLEXRAY) is lower than minimum of 7", (uint32_t)length);
            ws_warning("LINKTYPE_FLEXRAY Frame Header is too short (< 7 Byte)!");
            return false;
        }

        uint8_t payload_length = pd[4] & FLEXRAY_LENGTH_MASK;

        /* FLEXRAY FRAME */
        blf_flexrayrcvmessage_t frmsg;

        frmsg.channel = (uint16_t)iface_entry->channel;
        frmsg.version = 1;

        uint32_t header_crc = (pntohu24(pd + 4) & FLEXRAY_HEADER_CRC_MASK) >> FLEXRAY_HEADER_CRC_SHFT;

        if ((pd[0] & FLEXRAY_CHANNEL_MASK) == 0) {
            frmsg.channelMask = BLF_FLEXRAYRCVMSG_CHANNELMASK_A;
            frmsg.headerCrc1 = header_crc;
            frmsg.headerCrc2 = 0;
        } else {
            frmsg.channelMask = BLF_FLEXRAYRCVMSG_CHANNELMASK_B;
            frmsg.headerCrc1 = 0;
            frmsg.headerCrc2 = header_crc;
        }

        frmsg.dir = blf_get_direction(rec);
        frmsg.clientIndex = 0;
        frmsg.clusterNo = 0;
        frmsg.frameId = (pntohu16(pd + 2)) & FLEXRAY_ID_MASK;
        frmsg.payloadLength = payload_length;
        frmsg.payloadLengthValid = payload_length;
        frmsg.cycle = pd[6] & FLEXRAY_CC_MASK;
        frmsg.tag = 0;
        frmsg.data = 0;
        frmsg.frameFlags = 0;

        /* The NULL Flag 1 -> False */
        bool null_frame = (pd[2] & FLEXRAY_NFI_MASK) != FLEXRAY_NFI_MASK;

        if (null_frame) {
            frmsg.frameFlags &= BLF_FLEXRAYRCVMSG_FRAME_FLAG_NULL_FRAME;
            /* LINKTYPE_FLEXRAY has no payload for Null Frames present */
            payload_length = 0;
        }

        /* TODO: check truncated data */
        if (payload_length > 0) {
            /* Data Valid*/
            frmsg.frameFlags &= BLF_FLEXRAYRCVMSG_FRAME_FLAG_VALID_DATA;
        }

        if ((pd[2] & FLEXRAY_SFI_MASK) == FLEXRAY_SFI_MASK) {
            frmsg.frameFlags &= BLF_FLEXRAYRCVMSG_FRAME_FLAG_SYNC;
        }

        if ((pd[2] & FLEXRAY_STFI_MASK) == FLEXRAY_STFI_MASK) {
            frmsg.frameFlags &= BLF_FLEXRAYRCVMSG_FRAME_FLAG_STARTUP;
        }

        if ((pd[2] & FLEXRAY_PPI_MASK) == FLEXRAY_PPI_MASK) {
            frmsg.frameFlags &= BLF_FLEXRAYRCVMSG_FRAME_FLAG_PAYLOAD_PREAM;
        }

        if ((pd[2] & FLEXRAY_RES_MASK) == FLEXRAY_RES_MASK) {
            frmsg.frameFlags &= BLF_FLEXRAYRCVMSG_FRAME_FLAG_RES_20;
        }

        /* if any error flag is set */
        if ((pd[1] & FLEXRAY_ERRORS_DEFINED) != 0x00) {
            frmsg.frameFlags &= BLF_FLEXRAYRCVMSG_FRAME_FLAG_ERROR;
        }

        /* Not sure how to determine this as we do not know the low level parameters */
        //if ( ) {
        //    /* DYNAMIC SEG =1 (Bit 20)*/
        //    frmsg.frameFlags &= 0x100000;
        //}

        frmsg.appParameter = 0;

        fix_endianness_blf_flexrayrcvmessage(&frmsg);

        if (!blf_dump_objheader(wdh, err, obj_timestamp, BLF_OBJTYPE_FLEXRAY_RCVMESSAGE, sizeof(blf_flexrayrcvmessage_t) + 254)) {
            return false;
        }

        if (!wtap_dump_file_write(wdh, &(frmsg), sizeof(blf_flexrayrcvmessage_t), err)) {
            return false;
        }

        if (length < (size_t)payload_length + 2 + FLEXRAY_HEADER_LENGTH) {
            *err = WTAP_ERR_INTERNAL;
            *err_info = ws_strdup_printf("blf: record length %u for FlexRay Frame (LINKTYPE_FLEXRAY) is truncated", (uint32_t)length);
            ws_warning("LINKTYPE_FLEXRAY Frame truncated!");
            return false;
        }

        if (payload_length > 0) {
            if (!wtap_dump_file_write(wdh, &(pd[7]), payload_length, err)) {
                return false;
            }
        }

        const uint8_t zero_bytes[256] = { 0 };

        if (payload_length < 254) {
            if (!wtap_dump_file_write(wdh, &zero_bytes[0], 254 - payload_length, err)) {
                return false;
            }
        }

        return true;
    }

    /* no padding */

    return true;
}

static bool blf_dump_lin(wtap_dumper *wdh, const wtap_rec *rec, int *err, char **err_info, uint64_t obj_timestamp) {
    /* LIN */
    /* https://www.tcpdump.org/linktypes/LINKTYPE_LIN.html */

    //blf_writer_data_t *writer_data = (blf_writer_data_t *)wdh->priv;
    blf_channel_to_iface_entry_t *iface_entry = blf_dump_get_interface_mapping(wdh, rec, err, err_info);

    const uint8_t *pd = ws_buffer_start_ptr(&rec->data);
    size_t length = ws_buffer_length(&rec->data);

    if (length < 8) {
        *err = WTAP_ERR_INTERNAL;
        *err_info = ws_strdup_printf("blf: record length %u for LIN message/symbol/error is lower than minimum of 8", (uint32_t)length);
        ws_warning("LIN Data is too short (less than 8 bytes)!");
        return false;
    }

    uint8_t lin_err = pd[7] & 0x3f;
    if (lin_err != 0) {
        // TODO: handle LIN errors
        return true;
    }

    int i;
    uint8_t dlc = (pd[4] & LIN_PAYLOAD_LENGTH_MASK) >> 4;
    uint8_t msg_type = (pd[4] & LIN_MSG_TYPE_MASK) >> 2;

    if (msg_type != LIN_MSG_TYPE_FRAME) {
        // TODO: handle LIN events
        return true;
    }

    /* we need to have at least the data */
    if (length < (size_t)dlc + 8) {
        *err = WTAP_ERR_INTERNAL;
        *err_info = ws_strdup_printf("blf: record length %u for LIN message is too low for data. DLC: %u.", (uint32_t)length, dlc);
        ws_error("LIN Data is too short (less than needed)!");
        return false;
    }

    /* we ignore padding as we do not need it anyhow */

    blf_linmessage_t linmsg;
    linmsg.channel = (uint16_t)iface_entry->channel;
    linmsg.id = pd[5];
    linmsg.dlc = dlc;
    for (i = 0; i < 8; i++) {
        if (i < dlc) {
            linmsg.data[i] = pd[i + 8];
        } else {
            linmsg.data[i] = 0;
        }
    }
    linmsg.fsmId = 0;
    linmsg.fsmState = 0;
    linmsg.headerTime = 0;
    linmsg.fullTime = 0;
    linmsg.crc = pd[6];
    linmsg.dir = blf_get_direction(rec);
    linmsg.res1 = 0;

    fix_endianness_blf_linmessage(&linmsg);

    if (!blf_dump_objheader(wdh, err, obj_timestamp, BLF_OBJTYPE_LIN_MESSAGE, sizeof(blf_linmessage_t) + 4)) {
        return false;
    }

    if (!wtap_dump_file_write(wdh, &(linmsg), sizeof(blf_linmessage_t), err)) {
        return false;
    }

    uint8_t rest_of_header[4] = { 0, 0, 0, 0};

    if (!wtap_dump_file_write(wdh, &(rest_of_header), 4, err)) {
        return false;
    }

    /* no padding! */

    return true;
}

static bool blf_dump_upper_pdu(wtap_dumper *wdh, const wtap_rec *rec, int *err, char **err_info, uint64_t obj_timestamp) {
    const blf_writer_data_t *writer_data = (blf_writer_data_t *)wdh->priv;

    const uint8_t *pd = ws_buffer_start_ptr(&rec->data);
    size_t length = ws_buffer_length(&rec->data);

    unsigned tag_diss_pos = 0;
    size_t tag_diss_len = 0;
    unsigned col_proto_pos = 0;
    size_t col_proto_len = 0;
    unsigned col_info_pos = 0;
    size_t col_info_len = 0;

    /* parse the tags */
    size_t pos = 0;
    bool done = false;
    while (!done) {
        if (length - pos < 4) {
            *err = WTAP_ERR_INTERNAL;
            *err_info = ws_strdup_printf("blf: Upper PDU has no or truncated tags (pos: %u, length: %u)", (uint32_t)pos, (uint32_t)length);
            ws_warning("Upper PDU has truncated tags!");
            return false;
        }

        uint16_t tag_type = pntohu16(pd + pos);
        uint16_t tag_len = pntohu16(pd + pos + 2);

        if ((length - pos) < (size_t)tag_len + 4) {
            *err = WTAP_ERR_INTERNAL;
            *err_info = ws_strdup_printf("blf: Upper PDU has truncated tags (pos: %u, tag_type: %u, tag_len: %u)", (uint32_t)pos, tag_type, tag_len);
            ws_warning("Upper PDU has truncated tags!");
            return false;
        }

        switch (tag_type) {
        case EXP_PDU_TAG_DISSECTOR_NAME:
            tag_diss_pos = (unsigned)pos + 4;
            tag_diss_len = tag_len;
            break;

        case EXP_PDU_TAG_COL_PROT_TEXT:
            col_proto_pos = (unsigned)pos + 4;
            col_proto_len = tag_len;
            break;

        case EXP_PDU_TAG_COL_INFO_TEXT:
            col_info_pos = (unsigned)pos + 4;
            col_info_len = tag_len;
            break;

        case EXP_PDU_TAG_END_OF_OPT:
            done = true;
            break;
        }

        pos += 4;
        pos += tag_len;
    }

    /* strip zero termination, if existing */
    while (pd[tag_diss_pos + tag_diss_len - 1] == 0) {
        tag_diss_len -= 1;
    }

    while (pd[col_proto_pos + col_proto_len - 1] == 0) {
        col_proto_len -= 1;
    }

    while (pd[col_info_pos + col_info_len - 1] == 0) {
        col_info_len -= 1;
    }

    if (tag_diss_len == strlen(BLF_APPTEXT_TAG_DISS_DEFAULT) && 0 == strncmp(BLF_APPTEXT_TAG_DISS_DEFAULT, &pd[tag_diss_pos], tag_diss_len)) {
        if (col_proto_len == strlen(BLF_APPTEXT_COL_PROT_TEXT) && 0 == strncmp(BLF_APPTEXT_COL_PROT_TEXT, &pd[col_proto_pos], col_proto_len)) {
            blf_apptext_t apptext_header;
            apptext_header.source = BLF_APPTEXT_METADATA;
            apptext_header.reservedAppText1 = 0;
            apptext_header.reservedAppText2 = 412; /* not sure what to put in but this is commonly used!? */
            uint32_t payload_len = (uint32_t)(length - pos);
            apptext_header.textLength = payload_len;

            /* Metadata */
            /* tags: BLF_APPTEXT_TAG_DISS_DEFAULT, BLF_APPTEXT_COL_PROT_TEXT, BLF_APPTEXT_COL_INFO_TEXT_... */
            if (col_info_len == strlen(BLF_APPTEXT_COL_INFO_TEXT_GENERAL) && 0 == strncmp(BLF_APPTEXT_COL_INFO_TEXT_GENERAL, &pd[col_info_pos], col_info_len)) {
                /* BLF_APPTEXT_METADATA: BLF_APPTEXT_XML_GENERAL */
                apptext_header.reservedAppText1 = (BLF_APPTEXT_XML_GENERAL << 24) | (0xffffff & payload_len);
            } else if (col_info_len == strlen(BLF_APPTEXT_COL_INFO_TEXT_CHANNELS) && 0 == strncmp(BLF_APPTEXT_COL_INFO_TEXT_CHANNELS, &pd[col_info_pos], col_info_len)) {
                /* BLF_APPTEXT_METADATA: BLF_APPTEXT_XML_CHANNELS */
                    if (writer_data->iface_to_channel_names_recovered) {
                    apptext_header.reservedAppText1 = (BLF_APPTEXT_XML_CHANNELS << 24) | (0xffffff & payload_len);
                }
            } else if (col_info_len == strlen(BLF_APPTEXT_COL_INFO_TEXT_IDENTITY) && 0 == strncmp(BLF_APPTEXT_COL_INFO_TEXT_IDENTITY, &pd[col_info_pos], col_info_len)) {
                /* BLF_APPTEXT_METADATA: BLF_APPTEXT_XML_IDENTITY */
                apptext_header.reservedAppText1 = (BLF_APPTEXT_XML_IDENTITY << 24) | (0xffffff & payload_len);

            // else if
                /* BLF_APPTEXT_COMMENT */
                /* tags: BLF_APPTEXT_TAG_DISS_DEFAULT, BLF_APPTEXT_COL_PROT_TEXT, "Comment: %s" */
                // TODO            } else {
            // else if
                /* BLF_APPTEXT_ATTACHMENT */
                /* tags: BLF_APPTEXT_TAG_DISS_DEFAULT, BLF_APPTEXT_COL_PROT_TEXT, "Attachment: %s" */
                // TODO            } else {
            // else if
                /* BLF_APPTEXT_TRACELINE */
                /* tags: BLF_APPTEXT_TAG_DISS_DEFAULT, BLF_APPTEXT_COL_PROT_TEXT, "Trace line%s: %s" */
                // TODO
            } else {
                return true; /* just leave */
            }

            if (payload_len > 2048 && (apptext_header.source != BLF_APPTEXT_METADATA)) {
                ws_warning("Only Meta Data can be broken into smaller chunks!");
            }

            uint32_t chunk_size = payload_len;
            bool last_round = false;
            do {
                if (payload_len > 2048 && apptext_header.source == BLF_APPTEXT_METADATA) {
                    chunk_size = 2048;
                } else {
                    chunk_size = payload_len;
                    last_round = true;
                }

                if (!blf_dump_objheader(wdh, err, obj_timestamp, BLF_OBJTYPE_APP_TEXT, sizeof(blf_apptext_t) + chunk_size)) {
                    return false;
                }

                if (apptext_header.source == BLF_APPTEXT_METADATA) {
                    apptext_header.reservedAppText1 = (0xff000000 & apptext_header.reservedAppText1) | (0x00ffffff & payload_len);
                }

                apptext_header.textLength = chunk_size;
                fix_endianness_blf_apptext_header(&apptext_header);
                if (!wtap_dump_file_write(wdh, &(apptext_header), sizeof(blf_apptext_t), err)) {
                    return false;
                }
                if (!last_round) {
                    fix_endianness_blf_apptext_header(&apptext_header);
                }

                if (!wtap_dump_file_write(wdh, &(pd[pos]), chunk_size, err)) {
                    return false;
                }
                pos += chunk_size;

                /* Add strange padding to 4 bytes. */
                uint8_t padding_needed = (sizeof(blf_apptext_t) + chunk_size) % 4;
                if (!blf_write_add_padding(wdh, err, padding_needed)) {
                    return false;
                }

                if (!last_round) {
                    payload_len -= 2048;
                }
            } while (!last_round);

            return true;
        }
        // else if
        /* BLF_OBJTYPE_ETHERNET_STATUS */
        /* tags: BLF_APPTEXT_TAG_DISS_ETHSTATUS */
        // TODO

        // else if
        /* BLF_OBJTYPE_ETHERNET_PHY_STATE */
        /* tags: BLF_APPTEXT_TAG_DISS_ETHPHYSTATUS */
        // TODO
    }

    return true;
}

static bool blf_dump_interface_setup_by_blf_based_idb_desc(wtap_dumper *wdh, int *err _U_) {
    blf_writer_data_t *writer_data = (blf_writer_data_t *)wdh->priv;
    bool iface_descr_found;

    /* check all interfaces first to avoid inconstistent state */
    for (unsigned i = 0; i < wdh->interface_data->len; i++) {
        ws_debug("interface: %d (pass 1)", i);

        /* get interface data */
        wtap_block_t idb = g_array_index(wdh->interface_data, wtap_block_t, i);
        if (idb == NULL) {
            return false;
        }

        char *iface_descr = NULL;
        iface_descr_found = wtap_block_get_string_option_value(idb, OPT_IDB_DESCRIPTION, &iface_descr) == WTAP_OPTTYPE_SUCCESS;

        if (!iface_descr_found) {
            ws_debug("IDB interface description not found! We need to map the interfaces.");
            return false;
        }

        if (strncmp(iface_descr, "BLF-", 4) != 0) {
            ws_debug("IDB interface description found but not BLF format! We have to map freely the interfaces.");
            return false;
        }
    }

    for (unsigned i = 0; i < wdh->interface_data->len; i++) {
        ws_debug("interface: %d (pass 2)", i);

        /* get interface data */
        wtap_block_t idb = g_array_index(wdh->interface_data, wtap_block_t, i);
        if (idb == NULL) {
            return false;
        }

        char *iface_descr = NULL;
        iface_descr_found = wtap_block_get_string_option_value(idb, OPT_IDB_DESCRIPTION, &iface_descr);

        if (!iface_descr_found) {
            /* This cannot be reached but it removes a warning. */
            ws_debug("IDB interface description not found! We need to map the interfaces.");
            return false;
        }

        if (strncmp(iface_descr, "BLF-ETH-", 8) == 0) {
            char *endptr;
            uint16_t channel = (uint16_t)strtol(&iface_descr[8], &endptr, 16);
            uint16_t hwchannel = (uint16_t)strtol(&endptr[1], NULL, 16);

            if (!blf_dump_set_interface_mapping(wdh, i, WTAP_ENCAP_ETHERNET, channel, hwchannel)) {
                return false;
            }
        } else if (strncmp(iface_descr, "BLF-CAN-", 8) == 0) {
            uint16_t channel = (uint16_t)strtol(&iface_descr[8], NULL, 16);

            if (!blf_dump_set_interface_mapping(wdh, i, WTAP_ENCAP_SOCKETCAN, channel, UINT16_MAX)) {
                return false;
            }
        } else if (strncmp(iface_descr, "BLF-LIN-", 8) == 0) {
            uint16_t channel = (uint16_t)strtol(&iface_descr[8], NULL, 16);

            if (!blf_dump_set_interface_mapping(wdh, i, WTAP_ENCAP_LIN, channel, UINT16_MAX)) {
                return false;
            }
        } else if (strncmp(iface_descr, "BLF-FR-", 7) == 0) {
            uint16_t channel = (uint16_t)strtol(&iface_descr[7], NULL, 16);

            if (!blf_dump_set_interface_mapping(wdh, i, WTAP_ENCAP_FLEXRAY, channel, UINT16_MAX)) {
                return false;
            }
        }
    }

    writer_data->iface_to_channel_names_recovered = true;
    return true;
}

static bool blf_dump_interface_setup(wtap_dumper *wdh, int *err) {
    //blf_writer_data_t *writer_data = (blf_writer_data_t *)wdh->priv;

    /* Try 1: BLF details in Interface Description */
    if (blf_dump_interface_setup_by_blf_based_idb_desc(wdh, err)) {
        return true;
    }

    /* Try 2: Generate new IDs by mapping Interface IDs and also add names to BLF */
    for (unsigned i = 0; i < wdh->interface_data->len; i++) {
        ws_debug("i: %d", i);

        /* get interface data */
        wtap_block_t idb = g_array_index(wdh->interface_data, wtap_block_t, i);
        if (idb == NULL) {
            return false;
        }

        const wtapng_if_descr_mandatory_t *mand_data = (wtapng_if_descr_mandatory_t *) idb->mandatory_data;

        if (mand_data->wtap_encap == WTAP_ENCAP_ETHERNET || mand_data->wtap_encap == WTAP_ENCAP_SLL ||
            mand_data->wtap_encap == WTAP_ENCAP_LIN || mand_data->wtap_encap == WTAP_ENCAP_SOCKETCAN) {

            char *iface_name = NULL;
            bool iface_name_found = wtap_block_get_string_option_value(idb, OPT_IDB_NAME, &iface_name) == WTAP_OPTTYPE_SUCCESS;

            /* BLF can only support 255 channels */
            if (iface_name_found && iface_name != NULL && (i) < 255) {
                uint8_t iface_id = (uint8_t)(i + 1);

                /* we are not even trying to create APPTEXT CHANNELS as we are missing too much information */

                /* mapping up to 255 interface ids to channels directly */
                if (!blf_dump_set_interface_mapping(wdh, i, mand_data->wtap_encap, (uint16_t)iface_id, UINT16_MAX)) {
                    return false;
                }
            }
        }
    }

    return true;
}

static bool blf_dump(wtap_dumper *wdh, const wtap_rec *rec, int *err, char **err_info) {
    blf_writer_data_t *writer_data = (blf_writer_data_t *)wdh->priv;
    ws_debug("encap = %d (%s) rec type = %u", rec->rec_header.packet_header.pkt_encap,
        wtap_encap_description(rec->rec_header.packet_header.pkt_encap), rec->rec_type);

    /* TODO */
    switch (rec->rec_type) {
    case REC_TYPE_PACKET:
        break;
    default:
        *err = WTAP_ERR_UNWRITABLE_REC_TYPE;
        return false;
    }

    /* logcontainer full already? we just estimate the headers/overhead to be less than 100 */
    blf_dump_check_logcontainer_full(wdh, err, err_info, rec->rec_header.packet_header.len + 100);

    if (!writer_data->start_time_set) {
        /* TODO: consider to set trace start time to first packet time stamp - is this the lowest timestamp? how to know? */
        writer_data->start_time = 0;
        writer_data->start_time_set = true;
    }

    uint64_t obj_timestamp = (rec->ts.secs * 1000 * 1000 * 1000 + rec->ts.nsecs);

    if (writer_data->end_time < obj_timestamp) {
        writer_data->end_time = obj_timestamp;
    }

    /* reduce by BLF start offset */
    obj_timestamp = obj_timestamp - writer_data->start_time;
    writer_data->object_count += 1;

    switch (rec->rec_header.packet_header.pkt_encap) {
    case WTAP_ENCAP_ETHERNET: /* 1 */
        return blf_dump_ethernet(wdh, rec, err, err_info, obj_timestamp);
        break;

    case WTAP_ENCAP_SLL: /* 25 */
        return blf_dump_sll(wdh, rec, err, err_info, obj_timestamp);
        break;

    case WTAP_ENCAP_FLEXRAY: /* 106 */
        return blf_dump_flexray(wdh, rec, err, err_info, obj_timestamp);
        break;

    case WTAP_ENCAP_LIN: /* 107 */
        return blf_dump_lin(wdh, rec, err, err_info, obj_timestamp);
        break;

    case WTAP_ENCAP_SOCKETCAN: { /* 125 */
        const uint8_t *pd = ws_buffer_start_ptr(&rec->data);
        size_t length = ws_buffer_length(&rec->data);
        return blf_dump_socketcan(wdh, rec, err, err_info, obj_timestamp, pd, length, false, false, false, false);
    }
        break;

    case WTAP_ENCAP_WIRESHARK_UPPER_PDU: /* 155 */
        return blf_dump_upper_pdu(wdh, rec, err, err_info, obj_timestamp);
        break;

    default:
        /* we did not write, so correct count */
        writer_data->object_count -= 1;
    }

    return true;
}

/* Returns 0 if we could write the specified encapsulation type,
   an error indication otherwise. */
static int blf_dump_can_write_encap(int wtap_encap) {
    ws_debug("encap = %d (%s)", wtap_encap, wtap_encap_description(wtap_encap));

    /* Per-packet encapsulation is supported. */
    if (wtap_encap == WTAP_ENCAP_PER_PACKET)
        return 0;

    switch (wtap_encap) {
    /* fall through */
    case WTAP_ENCAP_ETHERNET:
    case WTAP_ENCAP_SLL:
    case WTAP_ENCAP_FLEXRAY:
    case WTAP_ENCAP_LIN:
    case WTAP_ENCAP_SOCKETCAN:
    case WTAP_ENCAP_WIRESHARK_UPPER_PDU:
        return 0;
    }

    return WTAP_ERR_UNWRITABLE_ENCAP;
}

static bool blf_add_idb(wtap_dumper *wdh _U_, wtap_block_t idb _U_, int *err _U_, char **err_info _U_) {
    ws_debug("entering function");
    /* TODO: is there any reason to keep this? */

    return true;
}

/* Finish writing to a dump file.
   Returns true on success, false on failure. */
static bool blf_dump_finish(wtap_dumper *wdh, int *err, char **err_info) {
    if (!blf_dump_close_logcontainer(wdh, err, err_info)) {
        return false;
    }

    if (!blf_finalize_file_header(wdh, err)) {
        return false;
    }

    /* File is finished, do not touch anymore ! */

    ws_debug("leaving function");
    return true;
}

/* Returns true on success, false on failure; sets "*err" to an error code on
   failure */
static bool
blf_dump_open(wtap_dumper *wdh, int *err, char **err_info) {
    ws_debug("entering function");

    if (wdh == NULL || wdh->priv != NULL) {
        *err = WTAP_ERR_INTERNAL;
        ws_debug("internal error: blf wdh is NULL or private data already set!");
        return false;
    }

    wdh->subtype_add_idb = blf_add_idb;
    wdh->subtype_write = blf_dump;
    wdh->subtype_finish = blf_dump_finish;

    /* set up priv data */
    blf_writer_data_t *writer_data = g_new(blf_writer_data_t, 1);
    wdh->priv = writer_data;

    /* set up and init interface mappings */
    writer_data->iface_to_channel_array = g_array_new(true, true, sizeof(blf_channel_to_iface_entry_t));
    blf_dump_expand_interface_mapping(wdh, wdh->interface_data->len);
    writer_data->iface_to_channel_names_recovered = false;

    writer_data->fileheader = NULL;
    writer_data->object_count = 0;
    writer_data->start_time = 0;
    writer_data->start_time_set = false;
    writer_data->end_time = 0;

    writer_data->logcontainer_start = LOG_CONTAINER_NONE;

    /* create the blf header structure and attach to wdh */
    if (!blf_init_file_header(wdh, err)) {
        return false;
    }

    /* write space in output file for header */
    if (!blf_write_file_header_zeros(wdh, err)) {
        return false;
    }

    ws_debug("wrote blf file header");

    /* Create first log_container */
    if (!blf_dump_start_logcontainer(wdh, err, err_info)) {
        return false;
    }

    if (!blf_dump_interface_setup(wdh, err)) {
        return false;
    }

    return true;
}

static const struct file_type_subtype_info blf_info = {
        "Vector Informatik Binary Logging Format (BLF) logfile", "blf", "blf", NULL,
        false, BLOCKS_SUPPORTED(blf_blocks_supported),
        blf_dump_can_write_encap, blf_dump_open, NULL
};

void register_blf(void) {

    blf_file_type_subtype = wtap_register_file_type_subtype(&blf_info);

    /*
     * Register name for backwards compatibility with the
     * wtap_filetypes table in Lua.
     */
    wtap_register_backwards_compatibility_lua_name("BLF", blf_file_type_subtype);
}

/*
 * 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:
 */