summaryrefslogtreecommitdiffstats
path: root/sharkd_session.c
blob: 4465788a1a2257127694b4dd2ee4aebfac3bb3ae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
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
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
/* sharkd_session.c
 *
 * Copyright (C) 2016 Jakub Zawadzki
 *
 * Wireshark - Network traffic analyzer
 * By Gerald Combs <gerald@wireshark.org>
 * Copyright 1998 Gerald Combs
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 */

#include "wtap_opttypes.h"
#include <config.h>

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <inttypes.h>

#include <glib.h>

#include <wsutil/wsjson.h>
#include <wsutil/json_dumper.h>
#include <wsutil/ws_assert.h>
#include <wsutil/wsgcrypt.h>

#include <file.h>
#include <epan/epan_dissect.h>
#include <epan/exceptions.h>
#include <epan/color_filters.h>
#include <epan/prefs.h>
#include <epan/prefs-int.h>
#include <epan/uat-int.h>
#include <wiretap/wtap.h>

#include <epan/column.h>
#include <epan/column-info.h>

#include <ui/ssl_key_export.h>

#include <ui/io_graph_item.h>
#include <epan/stats_tree_priv.h>
#include <epan/stat_tap_ui.h>
#include <epan/conversation_table.h>
#include <epan/sequence_analysis.h>
#include <epan/expert.h>
#include <epan/export_object.h>
#include <epan/follow.h>
#include <epan/rtd_table.h>
#include <epan/srt_table.h>
#include <epan/to_str.h>

#include <epan/dissectors/packet-h225.h>
#include <epan/rtp_pt.h>
#include <ui/voip_calls.h>
#include <ui/rtp_stream.h>
#include <ui/tap-rtp-common.h>
#include <ui/tap-rtp-analysis.h>
#include <ui/cli/tap-protohierstat.h>
#include <ui/cli/tap-voip.h>
#include <wsutil/version_info.h>
#include <epan/to_str.h>

#include <epan/addr_resolv.h>
#include <epan/dissectors/packet-rtp.h>
#include <ui/rtp_media.h>
#include <ui/mcast_stream.h>
#include <speex/speex_resampler.h>

#include <epan/maxmind_db.h>

#include <wsutil/pint.h>
#include <wsutil/strnatcmp.h>
#include <wsutil/strtoi.h>

#include "globals.h"

#include "sharkd.h"

struct sharkd_filter_item
{
    uint8_t *filtered; /* can be NULL if all frames are matching for given filter. */
};

static GHashTable *filter_table;

static int mode;
static uint32_t rpcid;

static json_dumper dumper;


static const char *
json_find_attr(const char *buf, const jsmntok_t *tokens, int count, const char *attr)
{
    int i;

    for (i = 0; i < count; i += 2)
    {
        const char *tok_attr  = &buf[tokens[i + 0].start];
        const char *tok_value = &buf[tokens[i + 1].start];

        if (!strcmp(tok_attr, attr))
            return tok_value;
    }

    return NULL;
}

static void
json_print_base64(const uint8_t *data, size_t len)
{
    json_dumper_begin_base64(&dumper);
    json_dumper_write_base64(&dumper, data, len);
    json_dumper_end_base64(&dumper);
}

static void G_GNUC_PRINTF(2, 3)
sharkd_json_value_anyf(const char *key, const char *format, ...)
{
    if (key)
        json_dumper_set_member_name(&dumper, key);

    va_list ap;
    va_start(ap, format);
    json_dumper_value_va_list(&dumper, format, ap);
    va_end(ap);
}

static void
sharkd_json_value_string(const char *key, const char *str)
{
    if (key)
        json_dumper_set_member_name(&dumper, key);
    json_dumper_value_string(&dumper, str);
}

static void
sharkd_json_value_base64(const char *key, const uint8_t *data, size_t len)
{
    if (key)
        json_dumper_set_member_name(&dumper, key);
    json_print_base64(data, len);
}

static void G_GNUC_PRINTF(2, 3)
sharkd_json_value_stringf(const char *key, const char *format, ...)
{
    if (key)
        json_dumper_set_member_name(&dumper, key);

    va_list ap;
    va_start(ap, format);
    char* sformat = ws_strdup_printf("\"%s\"", format);
    json_dumper_value_va_list(&dumper, sformat, ap);
    g_free(sformat);
    va_end(ap);
}

static void
sharkd_json_array_open(const char *key)
{
    if (key)
        json_dumper_set_member_name(&dumper, key);
    json_dumper_begin_array(&dumper);
}

static void
sharkd_json_array_close(void)
{
    json_dumper_end_array(&dumper);
}

static void
sharkd_json_object_open(const char *key)
{
    if (key)
        json_dumper_set_member_name(&dumper, key);
    json_dumper_begin_object(&dumper);
}

static void
sharkd_json_object_close(void)
{
    json_dumper_end_object(&dumper);
}

static void
sharkd_json_response_open(uint32_t id)
{
    json_dumper_begin_object(&dumper);  // start the message
    sharkd_json_value_string("jsonrpc", "2.0");
    sharkd_json_value_anyf("id", "%d", id);
}

static void
sharkd_json_response_close(void)
{
    json_dumper_end_object(&dumper);  // end the message

    json_dumper_finish(&dumper);

    /*
     * We do an explicit fflush after every line, because
     * we want output to be written to the socket as soon
     * as the line is complete.
     *
     * The stream is fully-buffered by default, so it's
     * only flushed when the buffer fills or the FILE *
     * is closed.  On UN*X, we could set it to be line
     * buffered, but the MSVC standard I/O routines don't
     * support line buffering - they only support *byte*
     * buffering, doing a write for every byte written,
     * which is too inefficient, and full buffering,
     * which is what you get if you request line buffering.
     */
    fflush(stdout);
}

static void
sharkd_json_result_prologue(uint32_t id)
{
    sharkd_json_response_open(id);
    sharkd_json_object_open("result");  // start the result object
}

static void
sharkd_json_result_epilogue(void)
{
    json_dumper_end_object(&dumper);  // end the result object
    sharkd_json_response_close();
}

static void
sharkd_json_result_array_prologue(uint32_t id)
{
    sharkd_json_response_open(id);
    sharkd_json_array_open("result");   // start the result array
}

static void
sharkd_json_result_array_epilogue(void)
{
    sharkd_json_array_close();        // end of result array
    sharkd_json_response_close();
}

static void
sharkd_json_simple_ok(uint32_t id)
{
    sharkd_json_result_prologue(id);
    sharkd_json_value_string("status", "OK");
    sharkd_json_result_epilogue();
}

static void
sharkd_json_warning(uint32_t id, char *warning)
{
    sharkd_json_result_prologue(id);
    sharkd_json_value_string("status", "Warning");
    sharkd_json_value_string("warning", warning);
    sharkd_json_result_epilogue();
}

static void G_GNUC_PRINTF(4, 5)
sharkd_json_error(uint32_t id, int code, char* data, char* format, ...)
{
    sharkd_json_response_open(id);
    sharkd_json_object_open("error");
    sharkd_json_value_anyf("code", "%d", code);

    if (format)
    {
        // format the text message
        va_list args;

        va_start(args, format);
        char *error_msg = ws_strdup_vprintf(format, args);
        va_end(args);

        sharkd_json_value_string("message", error_msg);

        g_free(error_msg);
    }

    sharkd_json_object_close();

    if (data)
        sharkd_json_value_string("data", data);

    sharkd_json_response_close();
}

static bool
is_param_match(const char *param_in, const char *valid_param)
{
    char* ptr;

    if ((ptr = g_strrstr(valid_param, "*")))
    {
        size_t prefix_len = ptr - valid_param;
        return !strncmp(param_in, valid_param, prefix_len);
    }
    else
        return !strcmp(param_in, valid_param);
}

/*
 * json_prep does four things:
 *
 *   1. check the syntax of the root and parameter members
 *   2. tokenize the names and values by zero terminating them
 *   3. unescape the names and values
 *   4. extracts and saves the rpcid
 *      - we have to do it here as it's needed for the error messages
 *
 * The objective is to minimise the validation work in the functions
 * that process each called method.
 *
 * This gets a little messy as the JSON parser creates a flat list
 * of all members rather than create a tree.
 */
static bool
json_prep(char* buf, const jsmntok_t* tokens, int count)
{
    int i;
    const char* method = NULL;
    char* attr_name = NULL;
    char* attr_value = NULL;

#define SHARKD_JSON_ANY      0
#define SHARKD_JSON_STRING   1
#define SHARKD_JSON_INTEGER  2
#define SHARKD_JSON_UINTEGER 3
#define SHARKD_JSON_FLOAT    4
#define SHARKD_JSON_OBJECT   5
#define SHARKD_JSON_ARRAY    6
#define SHARKD_JSON_BOOLEAN  7
#define SHARKD_ARRAY_END     99

    struct member_attribute {
        const char* parent_ctx;
        const char* name;
        int level;
        jsmntype_t type;
        int value_type;
        bool is_mandatory;
    };

#define SHARKD_MANDATORY true
#define SHARKD_OPTIONAL false

    /*
     * The member attribute structure is key to the syntax checking.  The
     * array contains all of the root level (1) member names, the data
     * types permissible for the value and a boolean that indicates whether
     * or not the member is mandatory.
     *
     * Once we get into the next layer (2) of the json tree, we need to check
     * params member names and data types dependent in the context of the method
     * (parent_ctx).
     */

    struct member_attribute name_array[] = {
        // Root members
        {NULL,         "jsonrpc",        1, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_MANDATORY},
        {NULL,         "userid",         1, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {NULL,         "id",             1, JSMN_PRIMITIVE,    SHARKD_JSON_UINTEGER, SHARKD_MANDATORY},
        {NULL,         "method",         1, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_MANDATORY},
        {NULL,         "params",         1, JSMN_OBJECT,       SHARKD_JSON_OBJECT,   SHARKD_OPTIONAL},

        // Valid methods
        {"method",     "analyse",        1, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"method",     "bye",            1, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"method",     "check",          1, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"method",     "complete",       1, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"method",     "download",       1, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"method",     "dumpconf",       1, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"method",     "follow",         1, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"method",     "frame",          1, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"method",     "frames",         1, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"method",     "info",           1, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"method",     "intervals",      1, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"method",     "iograph",        1, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"method",     "load",           1, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"method",     "setcomment",     1, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"method",     "setconf",        1, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"method",     "status",         1, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"method",     "tap",            1, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},

        // Parameters and their method context
        {"check",      "field",          2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"check",      "filter",         2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"complete",   "field",          2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"complete",   "pref",           2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"download",   "token",          2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"dumpconf",   "pref",           2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"follow",     "follow",         2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_MANDATORY},
        {"follow",     "filter",         2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_MANDATORY},
        {"follow",     "sub_stream",     2, JSMN_PRIMITIVE,    SHARKD_JSON_UINTEGER, SHARKD_OPTIONAL},
        {"frame",      "frame",          2, JSMN_PRIMITIVE,    SHARKD_JSON_UINTEGER, SHARKD_MANDATORY},
        {"frame",      "proto",          2, JSMN_PRIMITIVE,    SHARKD_JSON_BOOLEAN,  SHARKD_OPTIONAL},
        {"frame",      "ref_frame",      2, JSMN_PRIMITIVE,    SHARKD_JSON_UINTEGER, SHARKD_OPTIONAL},
        {"frame",      "prev_frame",     2, JSMN_PRIMITIVE,    SHARKD_JSON_UINTEGER, SHARKD_OPTIONAL},
        {"frame",      "columns",        2, JSMN_PRIMITIVE,    SHARKD_JSON_BOOLEAN,  SHARKD_OPTIONAL},
        {"frame",      "color",          2, JSMN_PRIMITIVE,    SHARKD_JSON_BOOLEAN,  SHARKD_OPTIONAL},
        {"frame",      "bytes",          2, JSMN_PRIMITIVE,    SHARKD_JSON_BOOLEAN,  SHARKD_OPTIONAL},
        {"frame",      "hidden",         2, JSMN_PRIMITIVE,    SHARKD_JSON_BOOLEAN,  SHARKD_OPTIONAL},
        {"frames",     "column*",        2, JSMN_UNDEFINED,    SHARKD_JSON_ANY,      SHARKD_OPTIONAL},
        {"frames",     "filter",         2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"frames",     "skip",           2, JSMN_PRIMITIVE,    SHARKD_JSON_UINTEGER, SHARKD_OPTIONAL},
        {"frames",     "limit",          2, JSMN_PRIMITIVE,    SHARKD_JSON_UINTEGER, SHARKD_OPTIONAL},
        {"frames",     "refs",           2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"intervals",  "interval",       2, JSMN_PRIMITIVE,    SHARKD_JSON_UINTEGER, SHARKD_OPTIONAL},
        {"intervals",  "filter",         2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"iograph",    "interval",       2, JSMN_PRIMITIVE,    SHARKD_JSON_UINTEGER, SHARKD_OPTIONAL},
        {"iograph",    "interval_units", 2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"iograph",    "filter",         2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"iograph",    "graph0",         2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_MANDATORY},
        {"iograph",    "graph1",         2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"iograph",    "graph2",         2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"iograph",    "graph3",         2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"iograph",    "graph4",         2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"iograph",    "graph5",         2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"iograph",    "graph6",         2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"iograph",    "graph7",         2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"iograph",    "graph8",         2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"iograph",    "graph9",         2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"iograph",    "filter0",        2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"iograph",    "filter1",        2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"iograph",    "filter2",        2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"iograph",    "filter3",        2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"iograph",    "filter4",        2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"iograph",    "filter5",        2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"iograph",    "filter6",        2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"iograph",    "filter7",        2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"iograph",    "filter8",        2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"iograph",    "filter9",        2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"load",       "file",           2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_MANDATORY},
        {"setcomment", "frame",          2, JSMN_PRIMITIVE,    SHARKD_JSON_UINTEGER, SHARKD_MANDATORY},
        {"setcomment", "comment",        2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"setconf",    "name",           2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_MANDATORY},
        {"setconf",    "value",          2, JSMN_UNDEFINED,    SHARKD_JSON_ANY,      SHARKD_MANDATORY},
        {"tap",        "tap0",           2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_MANDATORY},
        {"tap",        "tap1",           2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"tap",        "tap2",           2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"tap",        "tap3",           2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"tap",        "tap4",           2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"tap",        "tap5",           2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"tap",        "tap6",           2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"tap",        "tap7",           2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"tap",        "tap8",           2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"tap",        "tap9",           2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"tap",        "tap10",          2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"tap",        "tap11",          2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"tap",        "tap12",          2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"tap",        "tap13",          2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"tap",        "tap14",          2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"tap",        "tap15",          2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},
        {"tap",        "filter",         2, JSMN_STRING,       SHARKD_JSON_STRING,   SHARKD_OPTIONAL},

        // End of the name_array
        {NULL,         NULL,             0, JSMN_STRING,       SHARKD_ARRAY_END,   SHARKD_OPTIONAL},
    };

    rpcid = 0;

    /* sanity check, and split strings */
    if (count < 1 || tokens[0].type != JSMN_OBJECT)
    {
        sharkd_json_error(
                rpcid, -32600, NULL,
                "The request must an object"
                );
        return false;
    }

    /* don't need [0] token */
    tokens++;
    count--;

    if (count & 1)
    {
        sharkd_json_error(
                rpcid, -32600, NULL,
                "The request must contain name/value pairs"
                );
        return false;
    }

    for (i = 0; i < count; i += 2)
    {
        buf[tokens[i + 0].end] = '\0';
        buf[tokens[i + 1].end] = '\0';
    }

    // we must get the id as soon as possible so that it's available in all future error messages
    attr_value = (char*)json_find_attr(buf, tokens, count, "id");
    if (attr_value)
    {
        if (!ws_strtou32(attr_value, NULL, &rpcid))
        {
            sharkd_json_error(
                    rpcid, -32600, NULL,
                    "The id value must be a positive integer"
                    );
            return false;
        }
    }

    method = json_find_attr(buf, tokens, count, "method");

    if (method)
    {
        bool is_supported = false;
        i = 0;  // name array index

        // check that the request method is good
        while (name_array[i].value_type != SHARKD_ARRAY_END)
        {
            if (name_array[i].parent_ctx)
            {
                if (!strcmp(method, name_array[i].name) && !strcmp(name_array[i].parent_ctx, "method"))
                    is_supported = true;  // the method is valid
            }

            i++;
        }

        if (!is_supported)
        {
            sharkd_json_error(
                    rpcid, -32601, NULL,
                    "The method %s is not supported", method
                    );
            return false;
        }
    }

    for (i = 0; i < count; i += 2)
    {
        if (tokens[i].type != JSMN_STRING)
        {
            sharkd_json_error(
                    rpcid, -32600, NULL,
                    "Member names must be a string - member %d is not string", (i / 2) + 1
                    );
            return false;
        }

        attr_name = &buf[tokens[i + 0].start];
        attr_value = &buf[tokens[i + 1].start];

        if (!strcmp(attr_name, "jsonrpc"))
        {
            if (strcmp(&buf[tokens[i + 1].start], "2.0"))
            {
                sharkd_json_error(
                        rpcid, -32600, NULL,
                        "Only JSON %s is supported", "2.0"
                        );
                return false;
            }
        }

        /* unescape only value, as keys are simple strings */
        if (tokens[i + 1].type == JSMN_STRING && !json_decode_string_inplace(attr_value))
        {
            sharkd_json_error(
                    rpcid, -32600, NULL,
                    "Cannot unescape the value string of member %d", (i / 2) + 1
                    );
            return false;
        }

        /* Confirm that the member is valid */
        bool match = false;

        // We need to check root members (level 1) and parameters (level 2), hence the for loop.

        for (int level = 1; level < 3; level++)
        {
            size_t j = 0;

            while (name_array[j].value_type != SHARKD_ARRAY_END)  // iterate through the array until we hit the end
            {
                if (is_param_match(attr_name, name_array[j].name) && name_array[j].level == level)
                {
                    // We need to be sure the match is in the correct context
                    // i.e. is this a match for a root member (level 1) or for a parameter (level 2).

                    if (level == 1)
                    {
                        // need to guard against a parameter name matching a method name
                        if (method)
                        {
                            if (name_array[j].parent_ctx)
                            {
                                j++;
                                continue;
                            }

                            if (!strcmp(method, &buf[tokens[i + 0].start]))
                            {
                                j++;
                                continue;
                            }
                        }

                        match = true;
                    }
                    else if (method)
                    {
                        if (level == 2 && !strcmp(name_array[j].parent_ctx, method))
                            match = true;
                        else
                        {
                            j++;
                            continue;
                        }
                    }
                    else
                    {
                        j++;
                        continue;
                    }

                    // The match looks good, let's now check the data types

                    if (tokens[i + 1].type != name_array[j].type && name_array[j].type != SHARKD_JSON_ANY)
                    {
                        sharkd_json_error(
                                rpcid, -32600, NULL,
                                "The data type for member %s is not valid", attr_name
                                );
                        return false;
                    }
                    else if (name_array[j].type == JSMN_PRIMITIVE && name_array[j].value_type == SHARKD_JSON_UINTEGER)
                    {
                        uint32_t temp;
                        if (!ws_strtou32(attr_value, NULL, &temp) || temp <= 0)
                        {
                            sharkd_json_error(
                                    rpcid, -32600, NULL,
                                    "The value for %s must be a positive integer", name_array[j].name
                                    );
                            return false;
                        }
                    }
                    else if (name_array[j].type == JSMN_PRIMITIVE && name_array[j].value_type == SHARKD_JSON_BOOLEAN)
                    {
                        if (strcmp(attr_value, "true") && strcmp(attr_value, "false"))
                        {
                            sharkd_json_error(
                                    rpcid, -32600, NULL,
                                    "The value for %s must be a boolean (true or false)", name_array[j].name
                                    );
                            return false;
                        }

                    }
                    break; // looks like a valid match
                }
                j++;
            }
        }

        if (!match)
        {
            sharkd_json_error(
                    rpcid, -32600, NULL,
                    "%s is not a valid member name", attr_name
                    );
            return false;
        }
    }

    /* check for mandatory members */
    size_t j = 0;

    while (name_array[j].value_type != SHARKD_ARRAY_END)
    {
        if (name_array[j].is_mandatory && name_array[j].level == 1)
        {
            if (!json_find_attr(buf, tokens, count, name_array[j].name))
            {
                sharkd_json_error(
                        rpcid, -32600, NULL,
                        "Mandatory member %s is missing", name_array[j].name
                        );
                return false;
            }
        }
        j++;
    }

    // check that the current request contains the mandatory parameters
    j = 0;

    while (name_array[j].value_type != SHARKD_ARRAY_END)
    {
        if (name_array[j].is_mandatory && name_array[j].level == 2 && !strcmp(method, name_array[j].parent_ctx))
        {
            if (!json_find_attr(buf, tokens, count, name_array[j].name))
            {
                sharkd_json_error(
                        rpcid, -32600, NULL,
                        "Mandatory parameter %s is missing", name_array[j].name
                        );
                return false;
            }
        }
        j++;
    }


    // check that the parameters for the current request are valid for the method and that the data type for the value is valid

    return true;
}

static void
sharkd_session_filter_free(void *data)
{
    struct sharkd_filter_item *l = (struct sharkd_filter_item *) data;

    g_free(l->filtered);
    g_free(l);
}

static const struct sharkd_filter_item *
sharkd_session_filter_data(const char *filter)
{
    struct sharkd_filter_item *l;

    l = (struct sharkd_filter_item *) g_hash_table_lookup(filter_table, filter);
    if (!l)
    {
        uint8_t *filtered = NULL;

        int ret = sharkd_filter(filter, &filtered);

        if (ret == -1)
            return NULL;

        l = g_new(struct sharkd_filter_item, 1);
        l->filtered = filtered;

        g_hash_table_insert(filter_table, g_strdup(filter), l);
    }

    return l;
}

static bool
sharkd_rtp_match_init(rtpstream_id_t *id, const char *init_str)
{
    bool ret = false;
    char **arr;
    uint32_t tmp_addr_src, tmp_addr_dst;
    address tmp_src_addr, tmp_dst_addr;

    memset(id, 0, sizeof(*id));

    arr = g_strsplit(init_str, "_", 7); /* pass larger value, so we'll catch incorrect input :) */
    if (g_strv_length(arr) != 5)
        goto fail;

    /* TODO, for now only IPv4 */
    if (!get_host_ipaddr(arr[0], &tmp_addr_src))
        goto fail;

    if (!ws_strtou16(arr[1], NULL, &id->src_port))
        goto fail;

    if (!get_host_ipaddr(arr[2], &tmp_addr_dst))
        goto fail;

    if (!ws_strtou16(arr[3], NULL, &id->dst_port))
        goto fail;

    if (!ws_hexstrtou32(arr[4], NULL, &id->ssrc))
        goto fail;

    set_address(&tmp_src_addr, AT_IPv4, 4, &tmp_addr_src);
    copy_address(&id->src_addr, &tmp_src_addr);
    set_address(&tmp_dst_addr, AT_IPv4, 4, &tmp_addr_dst);
    copy_address(&id->dst_addr, &tmp_dst_addr);

    ret = true;

fail:
    g_strfreev(arr);
    return ret;
}

static bool
sharkd_session_process_info_nstat_cb(const void *key, void *value, void *userdata _U_)
{
    stat_tap_table_ui *stat_tap = (stat_tap_table_ui *) value;

    json_dumper_begin_object(&dumper);
    sharkd_json_value_string("name", stat_tap->title);
    sharkd_json_value_stringf("tap", "nstat:%s", (const char *) key);
    json_dumper_end_object(&dumper);

    return false;
}

static bool
sharkd_session_process_info_conv_cb(const void* key, void* value, void* userdata _U_)
{
    struct register_ct *table = (struct register_ct *) value;

    const char *label = (const char *) key;

    if (get_conversation_packet_func(table))
    {
        json_dumper_begin_object(&dumper);
        sharkd_json_value_stringf("name", "Conversation List/%s", label);
        sharkd_json_value_stringf("tap", "conv:%s", label);
        json_dumper_end_object(&dumper);
    }

    if (get_endpoint_packet_func(table))
    {
        json_dumper_begin_object(&dumper);
        sharkd_json_value_stringf("name", "Endpoint/%s", label);
        sharkd_json_value_stringf("tap", "endpt:%s", label);
        json_dumper_end_object(&dumper);
    }
    return false;
}

static bool
sharkd_session_seq_analysis_cb(const void *key, void *value, void *userdata _U_)
{
    register_analysis_t *analysis = (register_analysis_t *) value;

    json_dumper_begin_object(&dumper);
    sharkd_json_value_string("name", sequence_analysis_get_ui_name(analysis));
    sharkd_json_value_stringf("tap", "seqa:%s", (const char *) key);
    json_dumper_end_object(&dumper);

    return false;
}

static bool
sharkd_export_object_visit_cb(const void *key _U_, void *value, void *user_data _U_)
{
    register_eo_t *eo = (register_eo_t *) value;

    const int proto_id = get_eo_proto_id(eo);
    const char *filter = proto_get_protocol_filter_name(proto_id);
    const char *label  = proto_get_protocol_short_name(find_protocol_by_id(proto_id));

    json_dumper_begin_object(&dumper);
    sharkd_json_value_stringf("name", "Export Object/%s", label);
    sharkd_json_value_stringf("tap", "eo:%s", filter);
    json_dumper_end_object(&dumper);

    return false;
}

static bool
sharkd_srt_visit_cb(const void *key _U_, void *value, void *user_data _U_)
{
    register_srt_t *srt = (register_srt_t *) value;

    const int proto_id = get_srt_proto_id(srt);
    const char *filter = proto_get_protocol_filter_name(proto_id);
    const char *label  = proto_get_protocol_short_name(find_protocol_by_id(proto_id));

    json_dumper_begin_object(&dumper);
    sharkd_json_value_stringf("name", "Service Response Time/%s", label);
    sharkd_json_value_stringf("tap", "srt:%s", filter);
    json_dumper_end_object(&dumper);

    return false;
}

static bool
sharkd_rtd_visit_cb(const void *key _U_, void *value, void *user_data _U_)
{
    register_rtd_t *rtd = (register_rtd_t *) value;

    const int proto_id = get_rtd_proto_id(rtd);
    const char *filter = proto_get_protocol_filter_name(proto_id);
    const char *label  = proto_get_protocol_short_name(find_protocol_by_id(proto_id));

    json_dumper_begin_object(&dumper);
    sharkd_json_value_stringf("name", "Response Time Delay/%s", label);
    sharkd_json_value_stringf("tap", "rtd:%s", filter);
    json_dumper_end_object(&dumper);

    return false;
}

static bool
sharkd_follower_visit_cb(const void *key _U_, void *value, void *user_data _U_)
{
    register_follow_t *follower = (register_follow_t *) value;

    const int proto_id = get_follow_proto_id(follower);
    const char *label  = proto_get_protocol_short_name(find_protocol_by_id(proto_id));
    const char *filter = label; /* correct: get_follow_by_name() is registered by short name */

    json_dumper_begin_object(&dumper);
    sharkd_json_value_stringf("name", "Follow/%s", label);
    sharkd_json_value_stringf("tap", "follow:%s", filter);
    json_dumper_end_object(&dumper);

    return false;
}

static void
sharkd_session_print_capture_types(void)
{
    unsigned i;
    GArray *writable_type_subtypes;
    writable_type_subtypes = wtap_get_writable_file_types_subtypes(FT_SORT_BY_NAME);
    for (i = 0; i < writable_type_subtypes->len; i++) {
        int ft = g_array_index(writable_type_subtypes, int, i);
        sharkd_json_object_open(NULL);
        sharkd_json_value_string("name", wtap_file_type_subtype_name(ft));
        sharkd_json_value_string("description", wtap_file_type_subtype_description(ft));
        sharkd_json_object_close();
    }
    g_array_free(writable_type_subtypes, TRUE);
}

struct encap_type_info
{
    const char *name;
    const char *description;
};

static int
encap_type_info_nat_compare(const void *a, const void *b)
{
    return ws_ascii_strnatcmp(((const struct encap_type_info *)a)->name,
                              ((const struct encap_type_info *)b)->name);
}

static void
encap_type_info_visit(void *data, void *user_data _U_)
{
    sharkd_json_object_open(NULL);
    sharkd_json_value_string("name", ((struct encap_type_info *)data)->name);
    sharkd_json_value_string("description", ((struct encap_type_info *)data)->description);
    sharkd_json_object_close();
}

static void
sharkd_session_print_encap_types(void)
{
    int i;
    struct encap_type_info *encaps;
    GSList *list = NULL;
    encaps = g_new(struct encap_type_info, WTAP_NUM_ENCAP_TYPES);
    for (i = 0; i < WTAP_NUM_ENCAP_TYPES; i++) {
        encaps[i].name = wtap_encap_name(i);
        if (encaps[i].name != NULL) {
            encaps[i].description = wtap_encap_description(i);
            list = g_slist_insert_sorted(list, &encaps[i], encap_type_info_nat_compare);
        }
    }
    g_slist_foreach(list, encap_type_info_visit, NULL);
    g_slist_free(list);
    g_free(encaps);
}

/**
 * sharkd_session_process_info()
 *
 * Process info request
 *
 * Output object with attributes:
 *   (m) version - version number
 *
 *   (m) columns - available column formats, array of object with attributes:
 *                  'name'   - column name
 *                  'format' - column format-name
 *
 *   (m) stats   - available statistics, array of object with attributes:
 *                  'name' - statistic name
 *                  'tap'  - sharkd tap-name for statistic
 *
 *   (m) convs   - available conversation list, array of object with attributes:
 *                  'name' - conversation name
 *                  'tap'  - sharkd tap-name for conversation
 *
 *   (m) eo      - available export object list, array of object with attributes:
 *                  'name' - export object name
 *                  'tap'  - sharkd tap-name for eo
 *
 *   (m) srt     - available service response time list, array of object with attributes:
 *                  'name' - service response time name
 *                  'tap'  - sharkd tap-name for srt
 *
 *   (m) rtd     - available response time delay list, array of object with attributes:
 *                  'name' - response time delay name
 *                  'tap'  - sharkd tap-name for rtd
 *
 *   (m) seqa    - available sequence analysis (flow) list, array of object with attributes:
 *                  'name' - sequence analysis name
 *                  'tap'  - sharkd tap-name
 *
 *   (m) taps    - available taps, array of object with attributes:
 *                  'name' - tap name
 *                  'tap'  - sharkd tap-name
 *
 *   (m) follow  - available followers, array of object with attributes:
 *                  'name' - tap name
 *                  'tap'  - sharkd tap-name
 *
 *   (m) ftypes  - conversation table for FT_ number to string, array of FT_xxx strings.
 *
 *   (m) nstat   - available table-based taps, array of object with attributes:
 *                  'name' - tap name
 *                  'tap'  - sharkd tap-name
 *
 *   (m) capture_types - available capture types, array of object with attributes:
 *                        'name'        - capture type name
 *                        'description' - capture type description
 *
 *   (m) encap_types   - available encapsulation types, array of object with attributes:
 *                        'name'        - encapsulation type name
 *                        'description' - encapsulation type description
 */
static void
sharkd_session_process_info(void)
{
    int i;

    sharkd_json_result_prologue(rpcid);

    sharkd_json_array_open("columns");
    for (i = 0; i < NUM_COL_FMTS; i++)
    {
        const char *col_format = col_format_to_string(i);
        const char *col_descr  = col_format_desc(i);

        json_dumper_begin_object(&dumper);
        sharkd_json_value_string("name", col_descr);
        sharkd_json_value_string("format", col_format);
        json_dumper_end_object(&dumper);
    }
    sharkd_json_array_close();

    sharkd_json_array_open("stats");
    {
        GList *cfg_list = stats_tree_get_cfg_list();
        GList *l;

        for (l = cfg_list; l; l = l->next)
        {
            stats_tree_cfg *cfg = (stats_tree_cfg *) l->data;

            json_dumper_begin_object(&dumper);
            sharkd_json_value_string("name", cfg->title);
            sharkd_json_value_stringf("tap", "stat:%s", cfg->abbr);
            json_dumper_end_object(&dumper);
        }

        g_list_free(cfg_list);
    }
    sharkd_json_array_close();

    sharkd_json_array_open("ftypes");
    for (i = 0; i < FT_NUM_TYPES; i++)
        sharkd_json_value_string(NULL, ftype_name((ftenum_t) i));
    sharkd_json_array_close();

    sharkd_json_array_open("capture_types");
    sharkd_session_print_capture_types();
    sharkd_json_array_close();

    sharkd_json_array_open("encap_types");
    sharkd_session_print_encap_types();
    sharkd_json_array_close();

    sharkd_json_value_string("version", get_ws_vcs_version_info_short());

    sharkd_json_array_open("nstat");
    i = 0;
    stat_tap_iterate_tables(sharkd_session_process_info_nstat_cb, &i);
    sharkd_json_array_close();

    sharkd_json_array_open("convs");
    i = 0;
    conversation_table_iterate_tables(sharkd_session_process_info_conv_cb, &i);
    sharkd_json_array_close();

    sharkd_json_array_open("seqa");
    i = 0;
    sequence_analysis_table_iterate_tables(sharkd_session_seq_analysis_cb, &i);
    sharkd_json_array_close();

    sharkd_json_array_open("taps");
    {
        json_dumper_begin_object(&dumper);
        sharkd_json_value_string("name", "UDP Multicast Streams");
        sharkd_json_value_string("tap", "multicast");
        json_dumper_end_object(&dumper);

        json_dumper_begin_object(&dumper);
        sharkd_json_value_string("name", "RTP streams");
        sharkd_json_value_string("tap", "rtp-streams");
        json_dumper_end_object(&dumper);

        json_dumper_begin_object(&dumper);
        sharkd_json_value_string("name", "Protocol Hierarchy Statistics");
        sharkd_json_value_string("tap", "phs");
        json_dumper_end_object(&dumper);

        json_dumper_begin_object(&dumper);
        sharkd_json_value_string("name", "VoIP Calls");
        sharkd_json_value_string("tap", "voip-calls");
        json_dumper_end_object(&dumper);

        json_dumper_begin_object(&dumper);
        sharkd_json_value_string("name", "VoIP Conversations");
        sharkd_json_value_string("tap", "voip-convs");
        json_dumper_end_object(&dumper);

        json_dumper_begin_object(&dumper);
        sharkd_json_value_string("name", "Expert Information");
        sharkd_json_value_string("tap", "expert");
        json_dumper_end_object(&dumper);
    }
    sharkd_json_array_close();

    sharkd_json_array_open("eo");
    i = 0;
    eo_iterate_tables(sharkd_export_object_visit_cb, &i);
    sharkd_json_array_close();

    sharkd_json_array_open("srt");
    i = 0;
    srt_table_iterate_tables(sharkd_srt_visit_cb, &i);
    sharkd_json_array_close();

    sharkd_json_array_open("rtd");
    i = 0;
    rtd_table_iterate_tables(sharkd_rtd_visit_cb, &i);
    sharkd_json_array_close();

    sharkd_json_array_open("follow");
    i = 0;
    follow_iterate_followers(sharkd_follower_visit_cb, &i);
    sharkd_json_array_close();

    sharkd_json_result_epilogue();
}

/**
 * sharkd_session_process_load()
 *
 * Process load request
 *
 * Input:
 *   (m) file - file to be loaded
 *
 * Output object with attributes:
 *   (m) err - error code
 */
static void
sharkd_session_process_load(const char *buf, const jsmntok_t *tokens, int count)
{
    const char *tok_file = json_find_attr(buf, tokens, count, "file");
    int err = 0;

    if (!tok_file)
        return;

    fprintf(stderr, "load: filename=%s\n", tok_file);

    if (sharkd_cf_open(tok_file, WTAP_TYPE_AUTO, false, &err) != CF_OK)
    {
        sharkd_json_error(
                rpcid, -2001, NULL,
                "Unable to open the file"
                );
        return;
    }

    TRY
    {
        err = sharkd_load_cap_file();
    }
    CATCH(OutOfMemoryError)
    {
        sharkd_json_error(
                rpcid, -32603, NULL,
                "Load failed, out of memory"
                );
        fprintf(stderr, "load: OutOfMemoryError\n");
        err = ENOMEM;
    }
    ENDTRY;

    if (err == 0)
    {
        sharkd_json_simple_ok(rpcid);
    }
    else
    {
        sharkd_json_result_prologue(rpcid);
        sharkd_json_value_string("status", wtap_strerror(err));
        sharkd_json_value_anyf("err", "%d", err);
        sharkd_json_result_epilogue();
    }

}

/**
 * sharkd_session_process_status()
 *
 * Process status request
 *
 * Output object with attributes:
 *   (m) frames      - count of currently loaded frames
 *   (m) duration    - time difference between time of first frame, and last loaded frame
 *   (o) filename    - capture filename
 *   (o) filesize    - capture filesize
 *   (o) columns     - array of column titles
 *   (o) column_info - array of column infos, array of object with attributes:
 *                      'title'    - column title
 *                      'format'   - column format (%x or %Cus:<expr>:<occurrence> if COL_CUSTOM)
 *                      'visible'  - true if column is visible
 *                      'resolved' - true if column is resolved
 */
static void
sharkd_session_process_status(void)
{
    sharkd_json_result_prologue(rpcid);

    sharkd_json_value_anyf("frames", "%u", cfile.count);
    sharkd_json_value_anyf("duration", "%.9f", nstime_to_sec(&cfile.elapsed_time));

    if (cfile.filename)
    {
        char *name = g_path_get_basename(cfile.filename);

        sharkd_json_value_string("filename", name);
        g_free(name);
    }

    if (cfile.provider.wth)
    {
        int64_t file_size = wtap_file_size(cfile.provider.wth, NULL);

        if (file_size > 0)
            sharkd_json_value_anyf("filesize", "%" PRId64, file_size);
    }

    if (cfile.cinfo.num_cols > 0)
    {
        sharkd_json_array_open("columns");
        for (int i = 0; i < cfile.cinfo.num_cols; ++i)
        {
            sharkd_json_value_string(NULL, get_column_title(i));
        }
        sharkd_json_array_close();

        sharkd_json_array_open("column_info");
        for (int i = 0; i < cfile.cinfo.num_cols; ++i)
        {
            int fmt = get_column_format(i);
            sharkd_json_object_open(NULL);
            sharkd_json_value_string("title", get_column_title(i));
            if (fmt != COL_CUSTOM)
            {
                sharkd_json_value_string("format", col_format_to_string(fmt));
            } else {
                sharkd_json_value_stringf("format", "%s:%s:%d", col_format_to_string(fmt), get_column_custom_fields(i), get_column_custom_occurrence(i));
            }
            sharkd_json_value_anyf("visible", get_column_visible(i) ? "true" : "false");
            sharkd_json_value_anyf("resolved", get_column_resolved(i) ? "true" : "false");
            sharkd_json_object_close();
        }
        sharkd_json_array_close();
    }

    sharkd_json_result_epilogue();
}

struct sharkd_analyse_data
{
    GHashTable *protocols_set;
    nstime_t *first_time;
    nstime_t *last_time;
};

static void
sharkd_session_process_analyse_cb(epan_dissect_t *edt, proto_tree *tree _U_,
        struct epan_column_info *cinfo _U_, const GSList *data_src _U_, void *data)
{
    struct sharkd_analyse_data *analyser = (struct sharkd_analyse_data *) data;
    packet_info *pi = &edt->pi;
    frame_data *fdata = pi->fd;

    if (analyser->first_time == NULL || nstime_cmp(&fdata->abs_ts, analyser->first_time) < 0)
        analyser->first_time = &fdata->abs_ts;

    if (analyser->last_time == NULL || nstime_cmp(&fdata->abs_ts, analyser->last_time) > 0)
        analyser->last_time = &fdata->abs_ts;

    if (pi->layers)
    {
        wmem_list_frame_t *frame;

        for (frame = wmem_list_head(pi->layers); frame; frame = wmem_list_frame_next(frame))
        {
            int proto_id = GPOINTER_TO_UINT(wmem_list_frame_data(frame));

            if (!g_hash_table_lookup_extended(analyser->protocols_set, GUINT_TO_POINTER(proto_id), NULL, NULL))
            {
                g_hash_table_insert(analyser->protocols_set, GUINT_TO_POINTER(proto_id), GUINT_TO_POINTER(proto_id));
                sharkd_json_value_string(NULL, proto_get_protocol_filter_name(proto_id));
            }
        }
    }

}

/**
 * sharkd_session_process_status()
 *
 * Process analyse request
 *
 * Output object with attributes:
 *   (m) frames  - count of currently loaded frames
 *   (m) protocols - protocol list
 *   (m) first     - earliest frame time
 *   (m) last      - latest frame time
 */
static void
sharkd_session_process_analyse(void)
{
    struct sharkd_analyse_data analyser;
    wtap_rec rec; /* Record metadata */
    Buffer rec_buf;   /* Record data */

    analyser.first_time = NULL;
    analyser.last_time  = NULL;
    analyser.protocols_set = g_hash_table_new(NULL /* g_direct_hash() */, NULL /* g_direct_equal */);

    sharkd_json_result_prologue(rpcid);

    sharkd_json_value_anyf("frames", "%u", cfile.count);

    sharkd_json_array_open("protocols");

    wtap_rec_init(&rec);
    ws_buffer_init(&rec_buf, 1514);

    for (uint32_t framenum = 1; framenum <= cfile.count; framenum++)
    {
        enum dissect_request_status status;
        int err;
        char *err_info;

        status = sharkd_dissect_request(framenum,
                (framenum != 1) ? 1 : 0, framenum - 1,
                &rec, &rec_buf, NULL, SHARKD_DISSECT_FLAG_NULL,
                &sharkd_session_process_analyse_cb, &analyser,
                &err, &err_info);
        switch (status) {

            case DISSECT_REQUEST_SUCCESS:
                break;

            case DISSECT_REQUEST_NO_SUCH_FRAME:
                /* XXX - report the error. */
                break;

            case DISSECT_REQUEST_READ_ERROR:
                /*
                 * Free up the error string.
                 * XXX - report the error.
                 */
                g_free(err_info);
                break;
        }
    }

    sharkd_json_array_close();

    if (analyser.first_time)
        sharkd_json_value_anyf("first", "%.9f", nstime_to_sec(analyser.first_time));

    if (analyser.last_time)
        sharkd_json_value_anyf("last", "%.9f", nstime_to_sec(analyser.last_time));

    sharkd_json_result_epilogue();

    wtap_rec_cleanup(&rec);
    ws_buffer_free(&rec_buf);

    g_hash_table_destroy(analyser.protocols_set);
}

static column_info *
sharkd_session_create_columns(column_info *cinfo, const char *buf, const jsmntok_t *tokens, int count)
{
    const char *columns_custom[32];
    uint16_t columns_fmt[32];
    int16_t columns_occur[32];

    int i, cols;

    for (i = 0; i < 32; i++)
    {
        const char *tok_column;
        char tok_column_name[64];
        char *custom_sepa;

        snprintf(tok_column_name, sizeof(tok_column_name), "column%d", i);
        tok_column = json_find_attr(buf, tokens, count, tok_column_name);
        if (tok_column == NULL)
            break;

        columns_custom[i] = NULL;
        columns_occur[i] = 0;

        if ((custom_sepa = strchr(tok_column, ':')))
        {
            *custom_sepa = '\0'; /* XXX, C abuse: discarding-const */

            columns_fmt[i] = COL_CUSTOM;
            columns_custom[i] = tok_column;

            if (!ws_strtoi16(custom_sepa + 1, NULL, &columns_occur[i]))
                return NULL;
        }
        else
        {
            if (!ws_strtou16(tok_column, NULL, &columns_fmt[i]))
                return NULL;

            if (columns_fmt[i] >= NUM_COL_FMTS)
                return NULL;

            /* if custom, that it shouldn't be just custom number -> error */
            if (columns_fmt[i] == COL_CUSTOM)
                return NULL;
        }
    }

    cols = i;

    col_setup(cinfo, cols);

    for (i = 0; i < cols; i++)
    {
        col_item_t *col_item = &cinfo->columns[i];

        col_item->col_fmt = columns_fmt[i];
        col_item->col_title = NULL; /* no need for title */

        if (col_item->col_fmt == COL_CUSTOM)
        {
            col_item->col_custom_fields = g_strdup(columns_custom[i]);
            col_item->col_custom_occurrence = columns_occur[i];
        }

        col_item->col_fence = 0;
    }

    col_finalize(cinfo);

    return cinfo;
}

static void
sharkd_session_process_frames_cb(epan_dissect_t *edt, proto_tree *tree _U_,
        struct epan_column_info *cinfo, const GSList *data_src _U_, void *data _U_)
{
    packet_info *pi = &edt->pi;
    frame_data *fdata = pi->fd;
    wtap_block_t pkt_block = NULL;
    unsigned int i;
    char *comment = NULL;

    json_dumper_begin_object(&dumper);

    sharkd_json_array_open("c");
    for (int col = 0; col < cinfo->num_cols; ++col)
    {
        sharkd_json_value_string(NULL, get_column_text(cinfo, col));
    }
    sharkd_json_array_close();

    sharkd_json_value_anyf("num", "%u", pi->num);

    /*
     * Get the block for this record, if it has one.
     */
    pkt_block = sharkd_get_packet_block(fdata);

    /*
     * Does this record have any comments?
     */
    if (pkt_block != NULL &&
            WTAP_OPTTYPE_SUCCESS == wtap_block_get_nth_string_option_value(pkt_block, OPT_COMMENT, 0, &comment))
    {
        sharkd_json_value_anyf("ct", "true");

        sharkd_json_array_open("comments");
        for (i = 0; wtap_block_get_nth_string_option_value(pkt_block, OPT_COMMENT, i, &comment) == WTAP_OPTTYPE_SUCCESS; i++) {
            sharkd_json_value_string(NULL, comment);
        }
        sharkd_json_array_close();
    }

    if (fdata->ignored)
        sharkd_json_value_anyf("i", "true");

    if (fdata->marked)
        sharkd_json_value_anyf("m", "true");

    if (fdata->color_filter)
    {
        sharkd_json_value_stringf("bg", "%06x", color_t_to_rgb(&fdata->color_filter->bg_color));
        sharkd_json_value_stringf("fg", "%06x", color_t_to_rgb(&fdata->color_filter->fg_color));
    }

    wtap_block_unref(pkt_block);
    json_dumper_end_object(&dumper);
}

/**
 * sharkd_session_process_frames()
 *
 * Process frames request
 *
 * Input:
 *   (o) column0...columnXX - requested columns either number in range [0..NUM_COL_FMTS), or custom (syntax <dfilter>:<occurrence>).
 *                            If column0 is not specified default column set will be used.
 *   (o) filter - filter to be used
 *   (o) skip=N   - skip N frames
 *   (o) limit=N  - show only N frames
 *   (o) refs  - list (comma separated) with sorted time reference frame numbers.
 *
 * Output array of frames with attributes:
 *   (m) c   - array of column data
 *   (m) num - frame number
 *   (o) i   - if frame is ignored
 *   (o) m   - if frame is marked
 *   (o) ct  - if frame is commented
 *   (o) comments - array of comment strings
 *   (o) bg  - color filter - background color in hex
 *   (o) fg  - color filter - foreground color in hex
 */
static void
sharkd_session_process_frames(const char *buf, const jsmntok_t *tokens, int count)
{
    const char *tok_filter = json_find_attr(buf, tokens, count, "filter");
    const char *tok_column = json_find_attr(buf, tokens, count, "column0");
    const char *tok_skip   = json_find_attr(buf, tokens, count, "skip");
    const char *tok_limit  = json_find_attr(buf, tokens, count, "limit");
    const char *tok_refs   = json_find_attr(buf, tokens, count, "refs");

    const uint8_t *filter_data = NULL;

    uint32_t prev_dis_num = 0;
    uint32_t current_ref_frame = 0, next_ref_frame = UINT32_MAX;
    uint32_t skip;
    uint32_t limit;

    wtap_rec rec; /* Record metadata */
    Buffer rec_buf;   /* Record data */
    column_info *cinfo = &cfile.cinfo;
    column_info user_cinfo;

    if (tok_column)
    {
        memset(&user_cinfo, 0, sizeof(user_cinfo));
        cinfo = sharkd_session_create_columns(&user_cinfo, buf, tokens, count);
        if (!cinfo)
        {
            sharkd_json_error(
                    rpcid, -13001, NULL,
                    "Column definition invalid - note column 6 requires a custom definition"
                    );
            return;
        }
    }

    if (tok_filter)
    {
        const struct sharkd_filter_item *filter_item;

        filter_item = sharkd_session_filter_data(tok_filter);
        if (!filter_item)
        {
            sharkd_json_error(
                    rpcid, -13002, NULL,
                    "Filter expression invalid"
                    );
            return;
        }

        filter_data = filter_item->filtered;
    }

    skip = 0;
    if (tok_skip)
    {
        if (!ws_strtou32(tok_skip, NULL, &skip))
            return;
    }

    limit = 0;
    if (tok_limit)
    {
        if (!ws_strtou32(tok_limit, NULL, &limit))
            return;
    }

    if (tok_refs)
    {
        if (!ws_strtou32(tok_refs, &tok_refs, &next_ref_frame))
            return;
    }

    sharkd_json_result_array_prologue(rpcid);

    wtap_rec_init(&rec);
    ws_buffer_init(&rec_buf, 1514);

    for (uint32_t framenum = 1; framenum <= cfile.count; framenum++)
    {
        frame_data *fdata;
        uint32_t ref_frame = (framenum != 1) ? 1 : 0;
        enum dissect_request_status status;
        int err;
        char *err_info;

        if (filter_data && !(filter_data[framenum / 8] & (1 << (framenum % 8))))
            continue;

        if (skip)
        {
            skip--;
            prev_dis_num = framenum;
            continue;
        }

        if (tok_refs)
        {
            if (framenum >= next_ref_frame)
            {
                current_ref_frame = next_ref_frame;

                if (*tok_refs != ',')
                    next_ref_frame = UINT32_MAX;

                while (*tok_refs == ',' && framenum >= next_ref_frame)
                {
                    current_ref_frame = next_ref_frame;

                    if (!ws_strtou32(tok_refs + 1, &tok_refs, &next_ref_frame))
                    {
                        fprintf(stderr, "sharkd_session_process_frames() wrong format for refs: %s\n", tok_refs);
                        break;
                    }
                }

                if (*tok_refs == '\0' && framenum >= next_ref_frame)
                {
                    current_ref_frame = next_ref_frame;
                    next_ref_frame = UINT32_MAX;
                }
            }

            if (current_ref_frame)
                ref_frame = current_ref_frame;
        }

        fdata = sharkd_get_frame(framenum);
        status = sharkd_dissect_request(framenum,
                ref_frame, prev_dis_num,
                &rec, &rec_buf, cinfo,
                (fdata->color_filter == NULL) ? SHARKD_DISSECT_FLAG_COLOR : SHARKD_DISSECT_FLAG_NULL,
                &sharkd_session_process_frames_cb, NULL,
                &err, &err_info);
        switch (status) {

            case DISSECT_REQUEST_SUCCESS:
                break;

            case DISSECT_REQUEST_NO_SUCH_FRAME:
                /* XXX - report the error. */
                break;

            case DISSECT_REQUEST_READ_ERROR:
                /*
                 * Free up the error string.
                 * XXX - report the error.
                 */
                g_free(err_info);
                break;
        }

        prev_dis_num = framenum;

        if (limit && --limit == 0)
            break;
    }
    sharkd_json_result_array_epilogue();

    if (cinfo != &cfile.cinfo)
        col_cleanup(cinfo);

    wtap_rec_cleanup(&rec);
    ws_buffer_free(&rec_buf);
}

static void
sharkd_session_process_tap_stats_node_cb(const char *key, const stat_node *n)
{
    stat_node *node;

    sharkd_json_array_open(key);
    for (node = n->children; node; node = node->next)
    {
        json_dumper_begin_object(&dumper);

        /* code based on stats_tree_get_values_from_node() */
        sharkd_json_value_string("name", node->name);
        sharkd_json_value_anyf("count", "%d", node->counter);
        if (node->counter && ((node->st_flags & ST_FLG_AVERAGE) || node->rng))
        {
            switch(node->datatype)
            {
                case STAT_DT_INT:
                    sharkd_json_value_anyf("avg", "%.2f", ((float)node->total.int_total) / node->counter);
                    sharkd_json_value_anyf("min", "%d", node->minvalue.int_min);
                    sharkd_json_value_anyf("max", "%d", node->maxvalue.int_max);
                    break;
                case STAT_DT_FLOAT:
                    sharkd_json_value_anyf("avg", "%.2f", node->total.float_total / node->counter);
                    sharkd_json_value_anyf("min", "%f", node->minvalue.float_min);
                    sharkd_json_value_anyf("max", "%f", node->maxvalue.float_max);
                    break;
            }
        }

        if (node->st->elapsed)
            sharkd_json_value_anyf("rate", "%.4f", ((float)node->counter) / node->st->elapsed);

        if (node->parent && node->parent->counter)
            sharkd_json_value_anyf("perc", "%.2f", (node->counter * 100.0) / node->parent->counter);
        else if (node->parent == &(node->st->root))
            sharkd_json_value_anyf("perc", "100");

        if (prefs.st_enable_burstinfo && node->max_burst)
        {
            if (prefs.st_burst_showcount)
                sharkd_json_value_anyf("burstcount", "%d", node->max_burst);
            else
                sharkd_json_value_anyf("burstrate", "%.4f", ((double)node->max_burst) / prefs.st_burst_windowlen);

            sharkd_json_value_anyf("bursttime", "%.3f", (node->burst_time / 1000.0));
        }

        if (node->children)
        {
            sharkd_session_process_tap_stats_node_cb("sub", node);
        }
        json_dumper_end_object(&dumper);
    }
    sharkd_json_array_close();
}

/**
 * sharkd_session_process_tap_stats_cb()
 *
 * Output stats tap:
 *
 *   (m) tap        - tap name
 *   (m) type:stats - tap output type
 *   (m) name       - stat name
 *   (m) stats      - array of object with attributes:
 *                  (m) name       - stat item name
 *                  (m) count      - stat item counter
 *                  (o) avg        - stat item averange value
 *                  (o) min        - stat item min value
 *                  (o) max        - stat item max value
 *                  (o) rate       - stat item rate value (ms)
 *                  (o) perc       - stat item percentage
 *                  (o) burstrate  - stat item burst rate
 *                  (o) burstcount - stat item burst count
 *                  (o) burstttme  - stat item burst start
 *                  (o) sub        - array of object with attributes like in stats node.
 */
static void
sharkd_session_process_tap_stats_cb(void *psp)
{
    stats_tree *st = (stats_tree *) psp;

    json_dumper_begin_object(&dumper);

    sharkd_json_value_stringf("tap", "stats:%s", st->cfg->abbr);
    sharkd_json_value_string("type", "stats");
    sharkd_json_value_string("name", st->cfg->path);

    sharkd_session_process_tap_stats_node_cb("stats", &st->root);

    json_dumper_end_object(&dumper);
}

static void
sharkd_session_free_tap_stats_cb(void *psp)
{
    stats_tree *st = (stats_tree *) psp;

    stats_tree_free(st);
}

struct sharkd_expert_tap
{
    GSList *details;
    GStringChunk *text;
};

/**
 * sharkd_session_process_tap_expert_cb()
 *
 * Output expert tap:
 *
 *   (m) tap         - tap name
 *   (m) type:expert - tap output type
 *   (m) details     - array of object with attributes:
 *                  (m) f - frame number, which generated expert information
 *                  (o) s - severity
 *                  (o) g - group
 *                  (m) m - expert message
 *                  (o) p - protocol
 */
static void
sharkd_session_process_tap_expert_cb(void *tapdata)
{
    struct sharkd_expert_tap *etd = (struct sharkd_expert_tap *) tapdata;
    GSList *list;

    json_dumper_begin_object(&dumper);

    sharkd_json_value_string("tap", "expert");
    sharkd_json_value_string("type", "expert");

    sharkd_json_array_open("details");
    for (list = etd->details; list; list = list->next)
    {
        expert_info_t *ei = (expert_info_t *) list->data;
        const char *tmp;

        json_dumper_begin_object(&dumper);

        sharkd_json_value_anyf("f", "%u", ei->packet_num);

        tmp = try_val_to_str(ei->severity, expert_severity_vals);
        if (tmp)
            sharkd_json_value_string("s", tmp);

        tmp = try_val_to_str(ei->group, expert_group_vals);
        if (tmp)
            sharkd_json_value_string("g", tmp);

        sharkd_json_value_string("m", ei->summary);

        if (ei->protocol)
            sharkd_json_value_string("p", ei->protocol);

        json_dumper_end_object(&dumper);
    }
    sharkd_json_array_close();

    json_dumper_end_object(&dumper);
}

static tap_packet_status
sharkd_session_packet_tap_expert_cb(void *tapdata, packet_info *pinfo _U_, epan_dissect_t *edt _U_, const void *pointer, tap_flags_t flags _U_)
{
    struct sharkd_expert_tap *etd = (struct sharkd_expert_tap *) tapdata;
    const expert_info_t *ei       = (const expert_info_t *) pointer;
    expert_info_t *ei_copy;

    if (ei == NULL)
        return TAP_PACKET_DONT_REDRAW;

    ei_copy = g_new(expert_info_t, 1);
    /* Note: this is a shallow copy */
    *ei_copy = *ei;

    /* ei->protocol, ei->summary might be allocated in packet scope, make a copy. */
    ei_copy->protocol = g_string_chunk_insert_const(etd->text, ei_copy->protocol);
    ei_copy->summary  = g_string_chunk_insert_const(etd->text, ei_copy->summary);

    etd->details = g_slist_prepend(etd->details, ei_copy);

    return TAP_PACKET_REDRAW;
}

static void
sharkd_session_free_tap_expert_cb(void *tapdata)
{
    struct sharkd_expert_tap *etd = (struct sharkd_expert_tap *) tapdata;

    g_slist_free_full(etd->details, g_free);
    g_string_chunk_free(etd->text);
    g_free(etd);
}

/**
 * sharkd_session_process_tap_flow_cb()
 *
 * Output flow tap:
 *   (m) tap         - tap name
 *   (m) type:flow   - tap output type
 *   (m) nodes       - array of strings with node address
 *   (m) flows       - array of object with attributes:
 *                  (m) t  - frame time string
 *                  (m) n  - array of two numbers with source node index and destination node index
 *                  (m) pn - array of two numbers with source and destination port
 *                  (o) c  - comment
 */
static void
sharkd_session_process_tap_flow_cb(void *tapdata)
{
    seq_analysis_info_t *graph_analysis = (seq_analysis_info_t *) tapdata;
    GList *flow_list;
    unsigned i;

    sequence_analysis_get_nodes(graph_analysis);

    json_dumper_begin_object(&dumper);
    sharkd_json_value_stringf("tap", "seqa:%s", graph_analysis->name);
    sharkd_json_value_string("type", "flow");

    sharkd_json_array_open("nodes");
    for (i = 0; i < graph_analysis->num_nodes; i++)
    {
        char *addr_str;

        addr_str = address_to_display(NULL, &(graph_analysis->nodes[i]));
        sharkd_json_value_string(NULL, addr_str);
        wmem_free(NULL, addr_str);
    }
    sharkd_json_array_close();

    sharkd_json_array_open("flows");
    flow_list = g_queue_peek_nth_link(graph_analysis->items, 0);
    while (flow_list)
    {
        seq_analysis_item_t *sai = (seq_analysis_item_t *) flow_list->data;

        flow_list = g_list_next(flow_list);

        if (!sai->display)
            continue;

        json_dumper_begin_object(&dumper);

        sharkd_json_value_string("t", sai->time_str);
        sharkd_json_value_anyf("n", "[%u,%u]", sai->src_node, sai->dst_node);
        sharkd_json_value_anyf("pn", "[%u,%u]", sai->port_src, sai->port_dst);

        if (sai->comment)
            sharkd_json_value_string("c", sai->comment);

        json_dumper_end_object(&dumper);
    }
    sharkd_json_array_close();

    json_dumper_end_object(&dumper);
}

static void
sharkd_session_free_tap_flow_cb(void *tapdata)
{
    seq_analysis_info_t *graph_analysis = (seq_analysis_info_t *) tapdata;

    sequence_analysis_info_free(graph_analysis);
}

struct sharkd_conv_tap_data
{
    const char *type;
    conv_hash_t hash;
    bool resolve_name;
    bool resolve_port;
};

static bool
sharkd_session_geoip_addr(address *addr, const char *suffix)
{
    const mmdb_lookup_t *lookup = NULL;
    bool with_geoip = false;
    char json_key[64];

    if (addr->type == AT_IPv4)
    {
        const ws_in4_addr *ip4 = (const ws_in4_addr *) addr->data;

        lookup = maxmind_db_lookup_ipv4(ip4);
    }
    else if (addr->type == AT_IPv6)
    {
        const ws_in6_addr *ip6 = (const ws_in6_addr *) addr->data;

        lookup = maxmind_db_lookup_ipv6(ip6);
    }

    if (!lookup || !lookup->found)
        return false;

    if (lookup->country)
    {
        snprintf(json_key, sizeof(json_key), "geoip_country%s", suffix);
        sharkd_json_value_string(json_key, lookup->country);
        with_geoip = true;
    }

    if (lookup->country_iso)
    {
        snprintf(json_key, sizeof(json_key), "geoip_country_iso%s", suffix);
        sharkd_json_value_string(json_key, lookup->country_iso);
        with_geoip = true;
    }

    if (lookup->city)
    {
        snprintf(json_key, sizeof(json_key), "geoip_city%s", suffix);
        sharkd_json_value_string(json_key, lookup->city);
        with_geoip = true;
    }

    if (lookup->as_org)
    {
        snprintf(json_key, sizeof(json_key), "geoip_as_org%s", suffix);
        sharkd_json_value_string(json_key, lookup->as_org);
        with_geoip = true;
    }

    if (lookup->as_number > 0)
    {
        snprintf(json_key, sizeof(json_key), "geoip_as%s", suffix);
        sharkd_json_value_anyf(json_key, "%u", lookup->as_number);
        with_geoip = true;
    }

    if (lookup->latitude >= -90.0 && lookup->latitude <= 90.0)
    {
        snprintf(json_key, sizeof(json_key), "geoip_lat%s", suffix);
        sharkd_json_value_anyf(json_key, "%f", lookup->latitude);
        with_geoip = true;
    }

    if (lookup->longitude >= -180.0 && lookup->longitude <= 180.0)
    {
        snprintf(json_key, sizeof(json_key), "geoip_lon%s", suffix);
        sharkd_json_value_anyf(json_key, "%f", lookup->longitude);
        with_geoip = true;
    }

    return with_geoip;
}

struct sharkd_analyse_rtp_items
{
    uint32_t frame_num;
    uint32_t sequence_num;

    double delta;
    double jitter;
    double skew;
    double bandwidth;
    bool marker;

    double arrive_offset;

    /* from tap_rtp_stat_t */
    uint32_t flags;
    uint16_t pt;
};

struct sharkd_analyse_rtp
{
    const char *tap_name;
    rtpstream_id_t id;

    GSList *packets;
    double start_time;
    tap_rtp_stat_t statinfo;
};

static void
sharkd_session_process_tap_rtp_free_cb(void *tapdata)
{
    struct sharkd_analyse_rtp *rtp_req = (struct sharkd_analyse_rtp *) tapdata;

    g_slist_free_full(rtp_req->packets, g_free);
    g_free(rtp_req);
}

static tap_packet_status
sharkd_session_packet_tap_rtp_analyse_cb(void *tapdata, packet_info *pinfo, epan_dissect_t *edt _U_, const void *pointer, tap_flags_t flags _U_)
{
    struct sharkd_analyse_rtp *rtp_req = (struct sharkd_analyse_rtp *) tapdata;
    const struct _rtp_info *rtp_info = (const struct _rtp_info *) pointer;

    if (rtpstream_id_equal_pinfo_rtp_info(&rtp_req->id, pinfo, rtp_info))
    {
        tap_rtp_stat_t *statinfo = &(rtp_req->statinfo);
        struct sharkd_analyse_rtp_items *item;

        rtppacket_analyse(statinfo, pinfo, rtp_info);

        item = g_new(struct sharkd_analyse_rtp_items, 1);

        if (!rtp_req->packets)
            rtp_req->start_time = nstime_to_sec(&pinfo->abs_ts);

        item->frame_num    = pinfo->num;
        item->sequence_num = rtp_info->info_seq_num;
        item->delta        = (statinfo->flags & STAT_FLAG_FIRST) ? 0.0 : statinfo->delta;
        item->jitter       = (statinfo->flags & STAT_FLAG_FIRST) ? 0.0 : statinfo->jitter;
        item->skew         = (statinfo->flags & STAT_FLAG_FIRST) ? 0.0 : statinfo->skew;
        item->bandwidth    = statinfo->bandwidth;
        item->marker       = rtp_info->info_marker_set ? true : false;
        item->arrive_offset= nstime_to_sec(&pinfo->abs_ts) - rtp_req->start_time;

        item->flags = statinfo->flags;
        item->pt    = statinfo->pt;

        /* XXX, O(n) optimize */
        rtp_req->packets = g_slist_append(rtp_req->packets, item);
    }

    return TAP_PACKET_REDRAW;
}

/**
 * sharkd_session_process_tap_rtp_analyse_cb()
 *
 * Output rtp analyse tap:
 *   (m) tap   - tap name
 *   (m) type  - tap output type
 *   (m) ssrc         - RTP SSRC
 *   (m) max_delta    - Max delta (ms)
 *   (m) max_delta_nr - Max delta packet #
 *   (m) max_jitter   - Max jitter (ms)
 *   (m) mean_jitter  - Mean jitter (ms)
 *   (m) max_skew     - Max skew (ms)
 *   (m) total_nr     - Total number of RTP packets
 *   (m) seq_err      - Number of sequence errors
 *   (m) duration     - Duration (ms)
 *   (m) items      - array of object with attributes:
 *                  (m) f    - frame number
 *                  (m) o    - arrive offset
 *                  (m) sn   - sequence number
 *                  (m) d    - delta
 *                  (m) j    - jitter
 *                  (m) sk   - skew
 *                  (m) bw   - bandwidth
 *                  (o) s    - status string
 *                  (o) t    - status type
 *                  (o) mark - rtp mark
 */
static void
sharkd_session_process_tap_rtp_analyse_cb(void *tapdata)
{
    const int RTP_TYPE_CN       = 1;
    const int RTP_TYPE_ERROR    = 2;
    const int RTP_TYPE_WARN     = 3;
    const int RTP_TYPE_PT_EVENT = 4;

    const struct sharkd_analyse_rtp *rtp_req = (struct sharkd_analyse_rtp *) tapdata;
    const tap_rtp_stat_t *statinfo = &rtp_req->statinfo;

    GSList *l;

    json_dumper_begin_object(&dumper);

    sharkd_json_value_string("tap", rtp_req->tap_name);
    sharkd_json_value_string("type", "rtp-analyse");
    sharkd_json_value_stringf("ssrc", "0x%x", rtp_req->id.ssrc);

    sharkd_json_value_anyf("max_delta", "%f", statinfo->max_delta);
    sharkd_json_value_anyf("max_delta_nr", "%u", statinfo->max_nr);
    sharkd_json_value_anyf("max_jitter", "%f", statinfo->max_jitter);
    sharkd_json_value_anyf("mean_jitter", "%f", statinfo->mean_jitter);
    sharkd_json_value_anyf("max_skew", "%f", statinfo->max_skew);
    sharkd_json_value_anyf("total_nr", "%u", statinfo->total_nr);
    sharkd_json_value_anyf("seq_err", "%u", statinfo->sequence);
    sharkd_json_value_anyf("duration", "%f", statinfo->time - statinfo->start_time);

    sharkd_json_array_open("items");
    for (l = rtp_req->packets; l; l = l->next)
    {
        struct sharkd_analyse_rtp_items *item = (struct sharkd_analyse_rtp_items *) l->data;

        json_dumper_begin_object(&dumper);

        sharkd_json_value_anyf("f", "%u", item->frame_num);
        sharkd_json_value_anyf("o", "%.9f", item->arrive_offset);
        sharkd_json_value_anyf("sn", "%u", item->sequence_num);
        sharkd_json_value_anyf("d", "%.2f", item->delta);
        sharkd_json_value_anyf("j", "%.2f", item->jitter);
        sharkd_json_value_anyf("sk", "%.2f", item->skew);
        sharkd_json_value_anyf("bw", "%.2f", item->bandwidth);

        if (item->pt == PT_CN)
        {
            sharkd_json_value_string("s", "Comfort noise (PT=13, RFC 3389)");
            sharkd_json_value_anyf("t", "%d", RTP_TYPE_CN);
        }
        else if (item->pt == PT_CN_OLD)
        {
            sharkd_json_value_string("s", "Comfort noise (PT=19, reserved)");
            sharkd_json_value_anyf("t", "%d", RTP_TYPE_CN);
        }
        else if (item->flags & STAT_FLAG_WRONG_SEQ)
        {
            sharkd_json_value_string("s", "Wrong sequence number");
            sharkd_json_value_anyf("t", "%d", RTP_TYPE_ERROR);
        }
        else if (item->flags & STAT_FLAG_DUP_PKT)
        {
            sharkd_json_value_string("s", "Suspected duplicate (MAC address) only delta time calculated");
            sharkd_json_value_anyf("t", "%d", RTP_TYPE_WARN);
        }
        else if (item->flags & STAT_FLAG_REG_PT_CHANGE)
        {
            sharkd_json_value_stringf("s", "Payload changed to PT=%u%s",
                    item->pt,
                    (item->flags & STAT_FLAG_PT_T_EVENT) ? " telephone/event" : "");
            sharkd_json_value_anyf("t", "%d", RTP_TYPE_WARN);
        }
        else if (item->flags & STAT_FLAG_WRONG_TIMESTAMP)
        {
            sharkd_json_value_string("s", "Incorrect timestamp");
            sharkd_json_value_anyf("t", "%d", RTP_TYPE_WARN);
        }
        else if ((item->flags & STAT_FLAG_PT_CHANGE)
                &&  !(item->flags & STAT_FLAG_FIRST)
                &&  !(item->flags & STAT_FLAG_PT_CN)
                &&  (item->flags & STAT_FLAG_FOLLOW_PT_CN)
                &&  !(item->flags & STAT_FLAG_MARKER))
        {
            sharkd_json_value_string("s", "Marker missing?");
            sharkd_json_value_anyf("t", "%d", RTP_TYPE_WARN);
        }
        else if (item->flags & STAT_FLAG_PT_T_EVENT)
        {
            sharkd_json_value_stringf("s", "PT=%u telephone/event", item->pt);
            sharkd_json_value_anyf("t", "%d", RTP_TYPE_PT_EVENT);
        }
        else if (item->flags & STAT_FLAG_MARKER)
        {
            sharkd_json_value_anyf("t", "%d", RTP_TYPE_WARN);
        }

        if (item->marker)
            sharkd_json_value_anyf("mark", "1");

        json_dumper_end_object(&dumper);
    }
    sharkd_json_array_close();

    json_dumper_end_object(&dumper);
}

/**
 * sharkd_session_process_tap_conv_cb()
 *
 * Output conv tap:
 *   (m) tap        - tap name
 *   (m) type       - tap output type
 *   (m) proto      - protocol short name
 *   (o) filter     - filter string
 *   (o) geoip      - whether GeoIP information is available, boolean
 *
 *   (o) convs      - array of object with attributes:
 *                  (m) saddr - source address
 *                  (m) daddr - destination address
 *                  (o) sport - source port
 *                  (o) dport - destination port
 *                  (m) txf   - TX frame count
 *                  (m) txb   - TX bytes
 *                  (m) rxf   - RX frame count
 *                  (m) rxb   - RX bytes
 *                  (m) start - (relative) first packet time
 *                  (m) stop  - (relative) last packet time
 *                  (o) filter - conversation filter
 *
 *   (o) hosts      - array of object with attributes:
 *                  (m) host - host address
 *                  (o) port - host port
 *                  (m) txf  - TX frame count
 *                  (m) txb  - TX bytes
 *                  (m) rxf  - RX frame count
 *                  (m) rxb  - RX bytes
 */
static void
sharkd_session_process_tap_conv_cb(void *arg)
{
    conv_hash_t *hash = (conv_hash_t *) arg;
    const struct sharkd_conv_tap_data *iu = (struct sharkd_conv_tap_data *) hash->user_data;
    const char *proto;
    int proto_with_port;
    unsigned i;

    int with_geoip = 0;

    json_dumper_begin_object(&dumper);
    sharkd_json_value_string("tap", iu->type);

    if (!strncmp(iu->type, "conv:", 5))
    {
        sharkd_json_value_string("type", "conv");
        sharkd_json_array_open("convs");
        proto = iu->type + 5;
    }
    else if (!strncmp(iu->type, "endpt:", 6))
    {
        sharkd_json_value_string("type", "host");
        sharkd_json_array_open("hosts");
        proto = iu->type + 6;
    }
    else
    {
        sharkd_json_value_string("type", "err");
        proto = "";
    }

    proto_with_port = (!strcmp(proto, "TCP") || !strcmp(proto, "UDP") || !strcmp(proto, "SCTP"));

    if (iu->hash.conv_array != NULL && !strncmp(iu->type, "conv:", 5))
    {
        for (i = 0; i < iu->hash.conv_array->len; i++)
        {
            conv_item_t *iui = &g_array_index(iu->hash.conv_array, conv_item_t, i);
            char *src_addr, *dst_addr;
            char *src_port, *dst_port;
            char *filter_str;

            json_dumper_begin_object(&dumper);

            sharkd_json_value_string("saddr", (src_addr = get_conversation_address(NULL, &iui->src_address, iu->resolve_name)));
            sharkd_json_value_string("daddr", (dst_addr = get_conversation_address(NULL, &iui->dst_address, iu->resolve_name)));

            if (proto_with_port)
            {
                sharkd_json_value_string("sport", (src_port = get_conversation_port(NULL, iui->src_port, iui->ctype, iu->resolve_port)));
                sharkd_json_value_string("dport", (dst_port = get_conversation_port(NULL, iui->dst_port, iui->ctype, iu->resolve_port)));

                wmem_free(NULL, src_port);
                wmem_free(NULL, dst_port);
            }

            sharkd_json_value_anyf("rxf", "%" PRIu64, iui->rx_frames);
            sharkd_json_value_anyf("rxb", "%" PRIu64, iui->rx_bytes);

            sharkd_json_value_anyf("txf", "%" PRIu64, iui->tx_frames);
            sharkd_json_value_anyf("txb", "%" PRIu64, iui->tx_bytes);

            sharkd_json_value_anyf("start", "%.9f", nstime_to_sec(&iui->start_time));
            sharkd_json_value_anyf("stop", "%.9f", nstime_to_sec(&iui->stop_time));

            filter_str = get_conversation_filter(iui, CONV_DIR_A_TO_FROM_B);
            if (filter_str)
            {
                sharkd_json_value_string("filter", filter_str);
                g_free(filter_str);
            }

            wmem_free(NULL, src_addr);
            wmem_free(NULL, dst_addr);

            if (sharkd_session_geoip_addr(&(iui->src_address), "1"))
                with_geoip = 1;
            if (sharkd_session_geoip_addr(&(iui->dst_address), "2"))
                with_geoip = 1;

            json_dumper_end_object(&dumper);
        }
    }
    else if (iu->hash.conv_array != NULL && !strncmp(iu->type, "endpt:", 6))
    {
        for (i = 0; i < iu->hash.conv_array->len; i++)
        {
            endpoint_item_t *endpoint = &g_array_index(iu->hash.conv_array, endpoint_item_t, i);
            char *host_str, *port_str;
            char *filter_str;

            json_dumper_begin_object(&dumper);

            sharkd_json_value_string("host", (host_str = get_conversation_address(NULL, &endpoint->myaddress, iu->resolve_name)));

            if (proto_with_port)
            {
                sharkd_json_value_string("port", (port_str = get_endpoint_port(NULL, endpoint, iu->resolve_port)));

                wmem_free(NULL, port_str);
            }

            sharkd_json_value_anyf("rxf", "%" PRIu64, endpoint->rx_frames);
            sharkd_json_value_anyf("rxb", "%" PRIu64, endpoint->rx_bytes);

            sharkd_json_value_anyf("txf", "%" PRIu64, endpoint->tx_frames);
            sharkd_json_value_anyf("txb", "%" PRIu64, endpoint->tx_bytes);

            filter_str = get_endpoint_filter(endpoint);
            if (filter_str)
            {
                sharkd_json_value_string("filter", filter_str);
                g_free(filter_str);
            }

            wmem_free(NULL, host_str);

            if (sharkd_session_geoip_addr(&(endpoint->myaddress), ""))
                with_geoip = 1;
            json_dumper_end_object(&dumper);
        }
    }
    sharkd_json_array_close();

    sharkd_json_value_string("proto", proto);
    sharkd_json_value_anyf("geoip", with_geoip ? "true" : "false");

    json_dumper_end_object(&dumper);
}

static void
sharkd_session_free_tap_conv_cb(void *arg)
{
    conv_hash_t *hash = (conv_hash_t *) arg;
    struct sharkd_conv_tap_data *iu = (struct sharkd_conv_tap_data *) hash->user_data;

    if (!strncmp(iu->type, "conv:", 5))
    {
        reset_conversation_table_data(hash);
    }
    else if (!strncmp(iu->type, "endpt:", 6))
    {
        reset_endpoint_table_data(hash);
    }

    g_free(iu);
}

/**
 * sharkd_session_process_tap_nstat_cb()
 *
 * Output nstat tap:
 *   (m) tap        - tap name
 *   (m) type       - tap output type
 *   (m) fields: array of objects with attributes:
 *                  (m) c - name
 *
 *   (m) tables: array of object with attributes:
 *                  (m) t - table title
 *                  (m) i - array of items
 */
static void
sharkd_session_process_tap_nstat_cb(void *arg)
{
    stat_data_t *stat_data = (stat_data_t *) arg;
    unsigned i, j, k;

    json_dumper_begin_object(&dumper);
    sharkd_json_value_stringf("tap", "nstat:%s", stat_data->stat_tap_data->cli_string);
    sharkd_json_value_string("type", "nstat");

    sharkd_json_array_open("fields");
    for (i = 0; i < stat_data->stat_tap_data->nfields; i++)
    {
        stat_tap_table_item *field = &(stat_data->stat_tap_data->fields[i]);

        json_dumper_begin_object(&dumper);
        sharkd_json_value_string("c", field->column_name);
        json_dumper_end_object(&dumper);
    }
    sharkd_json_array_close();

    sharkd_json_array_open("tables");
    for (i = 0; i < stat_data->stat_tap_data->tables->len; i++)
    {
        stat_tap_table *table = g_array_index(stat_data->stat_tap_data->tables, stat_tap_table *, i);

        json_dumper_begin_object(&dumper);

        sharkd_json_value_string("t", table->title);

        sharkd_json_array_open("i");
        for (j = 0; j < table->num_elements; j++)
        {
            stat_tap_table_item_type *field_data;

            field_data = stat_tap_get_field_data(table, j, 0);
            if (field_data == NULL || field_data->type == TABLE_ITEM_NONE) /* Nothing for us here */
                continue;

            sharkd_json_array_open(NULL);
            for (k = 0; k < table->num_fields; k++)
            {
                field_data = stat_tap_get_field_data(table, j, k);

                switch (field_data->type)
                {
                    case TABLE_ITEM_UINT:
                        sharkd_json_value_anyf(NULL, "%u", field_data->value.uint_value);
                        break;

                    case TABLE_ITEM_INT:
                        sharkd_json_value_anyf(NULL, "%d", field_data->value.int_value);
                        break;

                    case TABLE_ITEM_STRING:
                        sharkd_json_value_string(NULL, field_data->value.string_value);
                        break;

                    case TABLE_ITEM_FLOAT:
                        sharkd_json_value_anyf(NULL, "%f", field_data->value.float_value);
                        break;

                    case TABLE_ITEM_ENUM:
                        sharkd_json_value_anyf(NULL, "%d", field_data->value.enum_value);
                        break;

                    case TABLE_ITEM_NONE:
                        sharkd_json_value_anyf(NULL, "null");
                        break;
                }
            }

            sharkd_json_array_close();
        }
        sharkd_json_array_close();
        json_dumper_end_object(&dumper);
    }
    sharkd_json_array_close();

    json_dumper_end_object(&dumper);
}

static void
sharkd_session_free_tap_nstat_cb(void *arg)
{
    stat_data_t *stat_data = (stat_data_t *) arg;

    free_stat_tables(stat_data->stat_tap_data);
}

/**
 * sharkd_session_process_tap_rtd_cb()
 *
 * Output rtd tap:
 *   (m) tap        - tap name
 *   (m) type       - tap output type
 *   (m) stats - statistics rows - array object with attributes:
 *                  (m) type - statistic name
 *                  (m) num - number of messages
 *                  (m) min - minimum SRT time
 *                  (m) max - maximum SRT time
 *                  (m) tot - total SRT time
 *                  (m) min_frame - minimal SRT
 *                  (m) max_frame - maximum SRT
 *                  (o) open_req - Open Requests
 *                  (o) disc_rsp - Discarded Responses
 *                  (o) req_dup  - Duplicated Requests
 *                  (o) rsp_dup  - Duplicated Responses
 *   (o) open_req   - Open Requests
 *   (o) disc_rsp   - Discarded Responses
 *   (o) req_dup    - Duplicated Requests
 *   (o) rsp_dup    - Duplicated Responses
 */
static void
sharkd_session_process_tap_rtd_cb(void *arg)
{
    rtd_data_t *rtd_data = (rtd_data_t *) arg;
    register_rtd_t *rtd  = (register_rtd_t *) rtd_data->user_data;

    unsigned i, j;

    const char *filter = proto_get_protocol_filter_name(get_rtd_proto_id(rtd));

    /* XXX, some dissectors are having single table and multiple timestats (mgcp, megaco),
     *      some multiple table and single timestat (radius, h225)
     *      and it seems that value_string is used one for timestamp-ID, other one for table-ID
     *      I wonder how it will gonna work with multiple timestats and multiple tables...
     * (for usage grep for: register_rtd_table)
     */
    const value_string *vs = get_rtd_value_string(rtd);

    json_dumper_begin_object(&dumper);
    sharkd_json_value_stringf("tap", "rtd:%s", filter);
    sharkd_json_value_string("type", "rtd");

    if (rtd_data->stat_table.num_rtds == 1)
    {
        const rtd_timestat *ms = &rtd_data->stat_table.time_stats[0];

        sharkd_json_value_anyf("open_req", "%u", ms->open_req_num);
        sharkd_json_value_anyf("disc_rsp", "%u", ms->disc_rsp_num);
        sharkd_json_value_anyf("req_dup", "%u", ms->req_dup_num);
        sharkd_json_value_anyf("rsp_dup", "%u", ms->rsp_dup_num);
    }

    sharkd_json_array_open("stats");
    for (i = 0; i < rtd_data->stat_table.num_rtds; i++)
    {
        const rtd_timestat *ms = &rtd_data->stat_table.time_stats[i];

        for (j = 0; j < ms->num_timestat; j++)
        {
            const char *type_str;

            if (ms->rtd[j].num == 0)
                continue;

            json_dumper_begin_object(&dumper);

            if (rtd_data->stat_table.num_rtds == 1)
                type_str = val_to_str_const(j, vs, "Other"); /* 1 table - description per row */
            else
                type_str = val_to_str_const(i, vs, "Other"); /* multiple table - description per table */
            sharkd_json_value_string("type", type_str);

            sharkd_json_value_anyf("num", "%u", ms->rtd[j].num);
            sharkd_json_value_anyf("min", "%.9f", nstime_to_sec(&(ms->rtd[j].min)));
            sharkd_json_value_anyf("max", "%.9f", nstime_to_sec(&(ms->rtd[j].max)));
            sharkd_json_value_anyf("tot", "%.9f", nstime_to_sec(&(ms->rtd[j].tot)));
            sharkd_json_value_anyf("min_frame", "%u", ms->rtd[j].min_num);
            sharkd_json_value_anyf("max_frame", "%u", ms->rtd[j].max_num);

            if (rtd_data->stat_table.num_rtds != 1)
            {
                /* like in tshark, display it on every row */
                sharkd_json_value_anyf("open_req", "%u", ms->open_req_num);
                sharkd_json_value_anyf("disc_rsp", "%u", ms->disc_rsp_num);
                sharkd_json_value_anyf("req_dup", "%u", ms->req_dup_num);
                sharkd_json_value_anyf("rsp_dup", "%u", ms->rsp_dup_num);
            }

            json_dumper_end_object(&dumper);
        }
    }
    sharkd_json_array_close();

    json_dumper_end_object(&dumper);
}

static void
sharkd_session_free_tap_rtd_cb(void *arg)
{
    rtd_data_t *rtd_data = (rtd_data_t *) arg;

    free_rtd_table(&rtd_data->stat_table);
    g_free(rtd_data);
}

/**
 * sharkd_session_process_tap_srt_cb()
 *
 * Output srt tap:
 *   (m) tap        - tap name
 *   (m) type       - tap output type
 *
 *   (m) tables - array of object with attributes:
 *                  (m) n - table name
 *                  (m) f - table filter
 *                  (o) c - table column name
 *                  (m) r - table rows - array object with attributes:
 *                            (m) n   - row name
 *                            (m) idx - procedure index
 *                            (m) num - number of events
 *                            (m) min - minimum SRT time
 *                            (m) max - maximum SRT time
 *                            (m) tot - total SRT time
 */
static void
sharkd_session_process_tap_srt_cb(void *arg)
{
    srt_data_t *srt_data = (srt_data_t *) arg;
    register_srt_t *srt = (register_srt_t *) srt_data->user_data;

    const char *filter = proto_get_protocol_filter_name(get_srt_proto_id(srt));

    unsigned i;

    json_dumper_begin_object(&dumper);
    sharkd_json_value_stringf("tap", "srt:%s", filter);
    sharkd_json_value_string("type", "srt");

    sharkd_json_array_open("tables");
    for (i = 0; i < srt_data->srt_array->len; i++)
    {
        /* SRT table */
        srt_stat_table *rst = g_array_index(srt_data->srt_array, srt_stat_table *, i);

        int j;

        json_dumper_begin_object(&dumper);

        if (rst->name)
            sharkd_json_value_string("n", rst->name);
        else if (rst->short_name)
            sharkd_json_value_string("n", rst->short_name);
        else
            sharkd_json_value_stringf("n", "table%u", i);

        if (rst->filter_string)
            sharkd_json_value_string("f", rst->filter_string);

        if (rst->proc_column_name)
            sharkd_json_value_string("c", rst->proc_column_name);

        sharkd_json_array_open("r");
        for (j = 0; j < rst->num_procs; j++)
        {
            /* SRT row */
            srt_procedure_t *proc = &rst->procedures[j];

            if (proc->stats.num == 0)
                continue;

            json_dumper_begin_object(&dumper);

            sharkd_json_value_string("n", proc->procedure);

            if (rst->filter_string)
                sharkd_json_value_anyf("idx", "%d", proc->proc_index);

            sharkd_json_value_anyf("num", "%u", proc->stats.num);

            sharkd_json_value_anyf("min", "%.9f", nstime_to_sec(&proc->stats.min));
            sharkd_json_value_anyf("max", "%.9f", nstime_to_sec(&proc->stats.max));
            sharkd_json_value_anyf("tot", "%.9f", nstime_to_sec(&proc->stats.tot));

            json_dumper_end_object(&dumper);
        }
        sharkd_json_array_close();

        json_dumper_end_object(&dumper);
    }
    sharkd_json_array_close();

    json_dumper_end_object(&dumper);
}

static void
sharkd_session_free_tap_srt_cb(void *arg)
{
    srt_data_t *srt_data = (srt_data_t *) arg;
    register_srt_t *srt = (register_srt_t *) srt_data->user_data;

    free_srt_table(srt, srt_data->srt_array);
    g_array_free(srt_data->srt_array, TRUE);
    g_free(srt_data);
}

static void
sharkd_session_process_tap_phs_cb_aux(phs_t *rs)
{
    for (; rs; rs = rs->sibling) {
        if (rs->protocol == -1) {
            return;
        }
        sharkd_json_object_open(NULL);
        sharkd_json_value_string("proto", rs->proto_name);
        sharkd_json_value_anyf("frames", "%"PRIu32, rs->frames);
        sharkd_json_value_anyf("bytes", "%"PRIu64, rs->bytes);
        if (rs->child != NULL && rs->child->protocol != -1) {
            sharkd_json_array_open("protos");
            sharkd_session_process_tap_phs_cb_aux(rs->child);
            sharkd_json_array_close();
        }
        sharkd_json_object_close();
    }
}

/**
 * sharkd_session_process_tap_phs_cb()
 *
 * Output phs tap:
 *   (m) tap        - tap name
 *   (m) type       - tap output type
 *   (m) filter     - tap filter argument
 *   (m) protos     - array of proto objects
 *
 *   proto object:
 *   (m) proto      - protocol name
 *   (m) frames     - frame count
 *   (m) bytes      - bytes count
 *   (o) protos     - array of proto objects
 */
static void
sharkd_session_process_tap_phs_cb(void *arg)
{
    phs_t *rs = (phs_t *)arg;
    sharkd_json_object_open(NULL);
    sharkd_json_value_string("tap", "phs");
    sharkd_json_value_string("type", "phs");
    sharkd_json_value_string("filter", rs->filter ? rs->filter : "");
    sharkd_json_array_open("protos");
    sharkd_session_process_tap_phs_cb_aux(rs);
    sharkd_json_array_close();
    sharkd_json_object_close();
}

static void
sharkd_session_free_tap_phs_cb(void *arg)
{
    phs_t *rs = (phs_t *)arg;
    free_phs(rs);
}

struct sharkd_export_object_list
{
    struct sharkd_export_object_list *next;

    char *type;
    const char *proto;
    GSList *entries;
};

static struct sharkd_export_object_list *sharkd_eo_list;

/**
 * sharkd_session_process_tap_eo_cb()
 *
 * Output eo tap:
 *   (m) tap        - tap name
 *   (m) type       - tap output type
 *   (m) proto      - protocol short name
 *   (m) objects    - array of object with attributes:
 *                  (m) pkt - packet number
 *                  (o) hostname - hostname
 *                  (o) type - content type
 *                  (o) filename - filename
 *                  (m) len - object length
 *                  (m) sha1 - object's sha1 sum
 */
static void
sharkd_session_process_tap_eo_cb(void *tapdata)
{
    export_object_list_t *tap_object = (export_object_list_t *) tapdata;
    struct sharkd_export_object_list *object_list = (struct sharkd_export_object_list *) tap_object->gui_data;
    GSList *slist;
    int i = 0;
    char sha1sum_bytes[HASH_SHA1_LENGTH], *sha1sum_str;

    json_dumper_begin_object(&dumper);
    sharkd_json_value_string("tap", object_list->type);
    sharkd_json_value_string("type", "eo");

    sharkd_json_value_string("proto", object_list->proto);

    sharkd_json_array_open("objects");
    for (slist = object_list->entries; slist; slist = slist->next)
    {
        const export_object_entry_t *eo_entry = (export_object_entry_t *) slist->data;

        json_dumper_begin_object(&dumper);

        sharkd_json_value_anyf("pkt", "%u", eo_entry->pkt_num);

        if (eo_entry->hostname)
            sharkd_json_value_string("hostname", eo_entry->hostname);

        if (eo_entry->content_type)
            sharkd_json_value_string("type", eo_entry->content_type);

        if (eo_entry->filename)
            sharkd_json_value_string("filename", eo_entry->filename);

        sharkd_json_value_stringf("_download", "%s_%d", object_list->type, i);

        sharkd_json_value_anyf("len", "%zu", eo_entry->payload_len);

        gcry_md_hash_buffer(GCRY_MD_SHA1, sha1sum_bytes, eo_entry->payload_data, eo_entry->payload_len);
        sha1sum_str = bytes_to_str(NULL, sha1sum_bytes, HASH_SHA1_LENGTH);
        sharkd_json_value_string("sha1", sha1sum_str);
        g_free(sha1sum_str);

        json_dumper_end_object(&dumper);

        i++;
    }
    sharkd_json_array_close();

    json_dumper_end_object(&dumper);
}

static void
sharkd_eo_object_list_add_entry(void *gui_data, export_object_entry_t *entry)
{
    struct sharkd_export_object_list *object_list = (struct sharkd_export_object_list *) gui_data;

    object_list->entries = g_slist_append(object_list->entries, entry);
}

static export_object_entry_t *
sharkd_eo_object_list_get_entry(void *gui_data, int row)
{
    struct sharkd_export_object_list *object_list = (struct sharkd_export_object_list *) gui_data;

    return (export_object_entry_t *) g_slist_nth_data(object_list->entries, row);
}

static struct sharkd_export_object_list *
sharkd_eo_object_list_get_entry_by_type(void *gui_data, const char *tap_type)
{
    struct sharkd_export_object_list *object_list = (struct sharkd_export_object_list *) gui_data;
    for (; object_list; object_list = object_list->next)
    {
        if (!strcmp(object_list->type, tap_type))
            return object_list;
    }
    return NULL;
}


/**
 * sharkd_session_process_tap_rtp_cb()
 *
 * Output RTP streams tap:
 *   (m) tap        - tap name
 *   (m) type       - tap output type
 *   (m) streams    - array of object with attributes:
 *                  (m) ssrc        - RTP synchronization source identifier
 *                  (m) payload     - stream payload
 *                  (m) saddr       - source address
 *                  (m) sport       - source port
 *                  (m) daddr       - destination address
 *                  (m) dport       - destination port
 *                  (m) pkts        - packets count
 *                  (m) max_delta   - max delta (ms)
 *                  (m) max_jitter  - max jitter (ms)
 *                  (m) mean_jitter - mean jitter (ms)
 *                  (m) expectednr  -
 *                  (m) totalnr     -
 *                  (m) problem     - if analyser found the problem
 *                  (m) ipver       - address IP version (4 or 6)
 */
static void
sharkd_session_process_tap_rtp_cb(void *arg)
{
    rtpstream_tapinfo_t *rtp_tapinfo = (rtpstream_tapinfo_t *) arg;

    GList *listx;

    json_dumper_begin_object(&dumper);
    sharkd_json_value_string("tap", "rtp-streams");
    sharkd_json_value_string("type", "rtp-streams");

    sharkd_json_array_open("streams");
    for (listx = g_list_first(rtp_tapinfo->strinfo_list); listx; listx = listx->next)
    {
        rtpstream_info_t *streaminfo = (rtpstream_info_t *) listx->data;
        rtpstream_info_calc_t calc;

        rtpstream_info_calculate(streaminfo, &calc);

        json_dumper_begin_object(&dumper);

        sharkd_json_value_stringf("ssrc", "0x%x", calc.ssrc);
        sharkd_json_value_string("payload", calc.all_payload_type_names);

        sharkd_json_value_string("saddr", calc.src_addr_str);
        sharkd_json_value_anyf("sport", "%u", calc.src_port);
        sharkd_json_value_string("daddr", calc.dst_addr_str);
        sharkd_json_value_anyf("dport", "%u", calc.dst_port);

        sharkd_json_value_anyf("start_time", "%f", calc.start_time_ms);
        sharkd_json_value_anyf("duration", "%f", calc.duration_ms);

        sharkd_json_value_anyf("pkts", "%u", calc.packet_count);
        sharkd_json_value_anyf("lost", "%u", calc.lost_num);
        sharkd_json_value_anyf("lost_percent", "%f", calc.lost_perc);

        sharkd_json_value_anyf("max_delta", "%f",calc.max_delta);
        sharkd_json_value_anyf("min_delta", "%f",calc.min_delta);
        sharkd_json_value_anyf("mean_delta", "%f",calc.mean_delta);
        sharkd_json_value_anyf("min_jitter", "%f", calc.min_jitter);
        sharkd_json_value_anyf("max_jitter", "%f", calc.max_jitter);
        sharkd_json_value_anyf("mean_jitter", "%f", calc.mean_jitter);

        sharkd_json_value_anyf("expectednr", "%u", calc.packet_expected);
        sharkd_json_value_anyf("totalnr", "%u", calc.total_nr);

        sharkd_json_value_anyf("problem", calc.problem ? "true" : "false");

        /* for filter */
        sharkd_json_value_anyf("ipver", "%d", (streaminfo->id.src_addr.type == AT_IPv6) ? 6 : 4);

        rtpstream_info_calc_free(&calc);

        json_dumper_end_object(&dumper);
    }
    sharkd_json_array_close();

    json_dumper_end_object(&dumper);
}

/**
* sharkd_session_process_tap_multicast_cb()
*
* Output UDP Multicast streams tap:
*   (m) tap                     - tap name
*   (m) type                    - tap output type
*   (m) bufferThresholdBytes    - byte count for a stream where a buffer alarm should be reported
*   (m) burstIntervalMs         - analysis interval in milliseconds
*   (m) burstThresholdPackets   - count of packets in an interval that should trigger an alarm
*   (m) streams                 - array of streams with metrics:
*           (m) saddr       - source address
*           (m) sport       - source port
*           (m) daddr       - destination address
*           (m) dport       - destination port
*           (m) packets     - object group for packet metrics with attributes:
*                (m) number     - count of packets in the stream
*                (m) perSecond  - average number of packets per seconds in the stream
*           (m) bandwidth     - object group for bandwidth metrics with attributes:
*                (m) average    - average measured bitrate in the stream
*                (m) max        - max measured bitrate in the stream
*           (m) buffer       - object group for buffer metrics with attributes:
*                (m) alarms     - number of times the stream exceeded the buffer threshold
*                (m) max        - highest stream buffer utilization
*           (m) burst        - object group for burst metrics with attributes:
*                (m) alarms     - number of times the stream exceeded the burst threshold
*                (m) max        - most stream packets measured in a burst interval
*/
static void
sharkd_session_process_tap_multicast_cb(void *arg)
{
    mcaststream_tapinfo_t *tapinfo = (mcaststream_tapinfo_t *)arg;
    GList *list_item;
    char *addr_str;

    json_dumper_begin_object(&dumper);

    sharkd_json_value_string("tap", "multicast");
    sharkd_json_value_string("type", "multicast");

    sharkd_json_value_anyf("bufferThresholdBytes", "%u", mcast_stream_bufferalarm);
    sharkd_json_value_anyf("burstIntervalMs", "%u", mcast_stream_burstint);
    sharkd_json_value_anyf("burstThresholdPackets", "%u", mcast_stream_trigger);

    sharkd_json_array_open("streams");
    for (list_item = g_list_first(tapinfo->strinfo_list); list_item; list_item = list_item->next) {
        mcast_stream_info_t *stream_info = (mcast_stream_info_t *) list_item->data;
        sharkd_json_object_open(NULL);
        {
            addr_str = address_to_display(NULL, &stream_info->src_addr);
            sharkd_json_value_string("saddr", addr_str);
            wmem_free(NULL, addr_str);
            sharkd_json_value_anyf("sport", "%u", stream_info->src_port);
            addr_str = address_to_display(NULL, &stream_info->dest_addr);
            sharkd_json_value_string("daddr", addr_str);
            wmem_free(NULL, addr_str);
            sharkd_json_value_anyf("dport", "%u", stream_info->dest_port);
            sharkd_json_object_open("packets");
            {
                sharkd_json_value_anyf("number", "%u", stream_info->npackets);
                sharkd_json_value_anyf("perSecond", "%f", stream_info->apackets);
            }
            sharkd_json_object_close();
            sharkd_json_object_open("bandwidth");
            {
                sharkd_json_value_anyf("average", "%f", stream_info->average_bw);
                sharkd_json_value_anyf("max", "%f", stream_info->element.maxbw);
            }
            sharkd_json_object_close();
            sharkd_json_object_open("buffer");
            {
                sharkd_json_value_anyf("alarms", "%u", stream_info->element.numbuffalarms);
                sharkd_json_value_anyf("max", "%u", stream_info->element.topbuffusage);
            }
            sharkd_json_object_close();
            sharkd_json_object_open("burst");
            {
                sharkd_json_value_anyf("alarms", "%u", stream_info->element.numbursts);
                sharkd_json_value_anyf("max", "%u", stream_info->element.topburstsize);
            }
            sharkd_json_object_close();
        }
        sharkd_json_object_close();
    }
    sharkd_json_array_close();

    json_dumper_end_object(&dumper);
}

static void
sharkd_session_process_free_tap_multicast_cb(void *tapdata)
{
    mcaststream_tapinfo_t *tapinfo = (mcaststream_tapinfo_t *)tapdata;

    mcaststream_reset(tapinfo);

    g_free(tapinfo);
}

/**
 * sharkd_session_process_tap_voip_calls_cb()
 *
 * Output VoIP Calls tap:
 *   (m) tap                    - tap name
 *   (m) type                   - tap output type
 *   (m) calls                  - array of objects with attributes:
 *                              (m) call            - call number
 *                              (m) start_time      - start timestamp
 *                              (m) stop_time       - stop timestamp
 *                              (m) initial_speaker - address of initial speaker
 *                              (m) from            - from address
 *                              (m) to              - to address
 *                              (m) protocol        - protocol name
 *                              (m) packets         - packet count
 *                              (m) state           - state string
 *                              (m) comment         - comment string
 */
static void
sharkd_session_process_tap_voip_calls_cb(void *arg)
{
    voip_calls_tapinfo_t *tapinfo = (voip_calls_tapinfo_t *)arg;
    char *addr_str;
    GList *cur_call = g_queue_peek_nth_link(tapinfo->callsinfos, 0);
    sharkd_json_object_open(NULL);
    sharkd_json_value_string("tap", "voip-calls");
    sharkd_json_value_string("type", "voip-calls");
    sharkd_json_array_open("calls");
    while (cur_call && cur_call->data) {
        voip_calls_info_t *call_info_ = (voip_calls_info_t*) cur_call->data;
        sharkd_json_object_open(NULL);
        sharkd_json_value_anyf("call", "%hu", call_info_->call_num);
        sharkd_json_value_anyf("start_time", "%.6f", nstime_to_sec(&(call_info_->start_rel_ts)));
        sharkd_json_value_anyf("stop_time", "%.6f", nstime_to_sec(&(call_info_->stop_rel_ts)));
        addr_str = address_to_display(NULL, &(call_info_->initial_speaker));
        sharkd_json_value_string("initial_speaker", addr_str);
        wmem_free(NULL, addr_str);
        sharkd_json_value_string("from", call_info_->from_identity);
        sharkd_json_value_string("to", call_info_->to_identity);
        sharkd_json_value_string("protocol", ((call_info_->protocol == VOIP_COMMON) && call_info_->protocol_name) ?
            call_info_->protocol_name : voip_protocol_name[call_info_->protocol]);
        sharkd_json_value_anyf("packets", "%u", call_info_->npackets);
        sharkd_json_value_string("state", voip_call_state_name[call_info_->call_state]);
        sharkd_json_value_string("comment", call_info_->call_comment);
        sharkd_json_object_close();
        cur_call = g_list_next(cur_call);
    }
    sharkd_json_array_close();
    sharkd_json_object_close();
}

static void
sharkd_session_free_tap_voip_calls_cb(void *tapdata)
{
    voip_calls_tapinfo_t *tapinfo = (voip_calls_tapinfo_t *)tapdata;
    voip_calls_remove_all_tap_listeners(tapinfo);
    if (tapinfo->callsinfos != NULL) {
        g_queue_free(tapinfo->callsinfos);
    }
    if (tapinfo->graph_analysis != NULL) {
        sequence_analysis_info_free(tapinfo->graph_analysis);
    }
    memset(tapinfo, 0, sizeof(*tapinfo));
}


struct sharkd_voip_convs_req {
    voip_calls_tapinfo_t *tapinfo;
    const char *tap_name;
};

/**
 * sharkd_session_process_tap_voip_convs_cb()
 *
 * Output VoIP Conversations tap:
 *   (m) tap                    - tap name
 *   (m) type                   - tap output type
 *   (m) convs                  - array of objects with attributes:
 *                              (m) frame    - frame number
 *                              (m) call     - call number
 *                              (m) time     - timestamp
 *                              (m) dst_addr - destination address
 *                              (m) dst_port - destination port
 *                              (m) src_addr - source address
 *                              (m) src_port - source port
 *                              (m) label    - label string
 *                              (m) comment  - comment string
 */
static void
sharkd_session_process_tap_voip_convs_cb(void *arg)
{
    struct sharkd_voip_convs_req *voip_convs_req = (struct sharkd_voip_convs_req *)arg;
    voip_calls_tapinfo_t *tapinfo = voip_convs_req->tapinfo;
    seq_analysis_info_t *sainfo = tapinfo->graph_analysis;
    char *addr_str;
    sequence_analysis_list_sort(sainfo);
    sharkd_json_object_open(NULL);
    sharkd_json_value_string("tap", voip_convs_req->tap_name);
    sharkd_json_value_string("type", "voip-convs");
    sharkd_json_array_open("convs");
    for (GList *cur = g_queue_peek_nth_link(sainfo->items, 0); cur; cur = g_list_next(cur)) {
        seq_analysis_item_t *sai = (seq_analysis_item_t *) cur->data;
        if ((voip_conv_sel[sai->conv_num / VOIP_CONV_BITS] & (1 << (sai->conv_num % VOIP_CONV_BITS))) == 0)
            continue;
        sharkd_json_object_open(NULL);
        sharkd_json_value_anyf("frame", "%d", sai->frame_number);
        sharkd_json_value_anyf("call", "%d", sai->conv_num);
        sharkd_json_value_string("time", sai->time_str);
        addr_str = address_to_display(NULL, &(sai->dst_addr));
        sharkd_json_value_string("dst_addr", addr_str);
        wmem_free(NULL, addr_str);
        sharkd_json_value_anyf("dst_port", "%d", sai->port_dst);
        addr_str = address_to_display(NULL, &(sai->src_addr));
        sharkd_json_value_string("src_addr", addr_str);
        wmem_free(NULL, addr_str);
        sharkd_json_value_anyf("src_port", "%d", sai->port_src);
        sharkd_json_value_string("label", sai->frame_label);
        sharkd_json_value_string("comment", sai->comment);
        sharkd_json_object_close();
    }
    sharkd_json_array_close();
    sharkd_json_object_close();
}

static void
sharkd_session_free_tap_voip_convs_cb(void *tapdata)
{
    struct sharkd_voip_convs_req *voip_convs_req = (struct sharkd_voip_convs_req *)tapdata;
    voip_calls_tapinfo_t *tapinfo = voip_convs_req->tapinfo;
    voip_calls_remove_all_tap_listeners(tapinfo);
    if (tapinfo->callsinfos != NULL) {
        g_queue_free(tapinfo->callsinfos);
    }
    if (tapinfo->graph_analysis != NULL) {
        sequence_analysis_info_free(tapinfo->graph_analysis);
    }
    memset(tapinfo, 0, sizeof(*tapinfo));
    g_free(voip_convs_req);
}

struct sharkd_hosts_req {
    const char *tap_name;
    bool dump_v4;
    bool dump_v6;
};

static int
sharkd_session_tap_ipv4_host_compare(const void *a, const void *b)
{
    return ws_ascii_strnatcmp(((const hashipv4_t *)a)->name,
                              ((const hashipv4_t *)b)->name);
}

static int
sharkd_session_tap_ipv6_host_compare(const void *a, const void *b)
{
    return ws_ascii_strnatcmp(((const hashipv6_t *)a)->name,
                              ((const hashipv6_t *)b)->name);
}

static void
sharkd_session_tap_ipv4_host_print(void *data, void *user_data _U_)
{
    hashipv4_t *ipv4_hash_table_entry = (hashipv4_t *)data;
    sharkd_json_object_open(NULL);
    sharkd_json_value_string("name", ipv4_hash_table_entry->name);
    sharkd_json_value_string("addr", ipv4_hash_table_entry->ip);
    sharkd_json_object_close();
}

static void
sharkd_session_tap_ipv6_host_print(void *data, void *user_data _U_)
{
    hashipv6_t *ipv6_hash_table_entry = (hashipv6_t *)data;
    sharkd_json_object_open(NULL);
    sharkd_json_value_string("name", ipv6_hash_table_entry->name);
    sharkd_json_value_string("addr", ipv6_hash_table_entry->ip6);
    sharkd_json_object_close();
}

static void
sharkd_session_tap_ipv4_host_insert_sorted(void *key _U_, void *value, void *user_data)
{
    hashipv4_t *ipv4_hash_table_entry = (hashipv4_t *)value;
    GSList **list = (GSList **)user_data;
    if ((ipv4_hash_table_entry->flags & NAME_RESOLVED)) {
        *list = g_slist_insert_sorted(*list, ipv4_hash_table_entry, sharkd_session_tap_ipv4_host_compare);
    }
}

static void
sharkd_session_tap_ipv6_host_insert_sorted(void *key _U_, void *value, void *user_data)
{
    hashipv6_t *ipv6_hash_table_entry = (hashipv6_t *)value;
    GSList **list = (GSList **) user_data;
    if ((ipv6_hash_table_entry->flags & NAME_RESOLVED)) {
        *list = g_slist_insert_sorted(*list, ipv6_hash_table_entry, sharkd_session_tap_ipv6_host_compare);
    }
}

static void
sharkd_session_tap_ipv4_hosts_print(void)
{
    wmem_map_t *ipv4_hash_table = get_ipv4_hash_table();
    if (!ipv4_hash_table)
        return;
    GSList *list = NULL;
    wmem_map_foreach(ipv4_hash_table, sharkd_session_tap_ipv4_host_insert_sorted, &list);
    g_slist_foreach(list, sharkd_session_tap_ipv4_host_print, NULL);
    g_slist_free(list);
}

static void
sharkd_session_tap_ipv6_hosts_print(void)
{
    wmem_map_t *ipv6_hash_table = get_ipv6_hash_table();
    if (!ipv6_hash_table)
        return;
    GSList *list = NULL;
    wmem_map_foreach(ipv6_hash_table, sharkd_session_tap_ipv6_host_insert_sorted, &list);
    g_slist_foreach(list, sharkd_session_tap_ipv6_host_print, NULL);
    g_slist_free(list);
}

/**
 * sharkd_session_process_tap_hosts_cb()
 *
 * Output Hosts tap:
 *   (m) tap                    - tap name
 *   (m) type                   - tap output type
 *   (o) ipv4_hosts             - array of objects with attributes:
 *                              (m) addr - ipv4 address
 *                              (m) name - resolved name of address
 *   (o) ipv6_hosts             - array of objects with attributes:
 *                              (m) addr - ipv6 address
 *                              (m) name - resolved name of address
 */
static void
sharkd_session_process_tap_hosts_cb(void *arg)
{
    struct sharkd_hosts_req *hosts_req = (struct sharkd_hosts_req *)arg;
    sharkd_json_object_open(NULL);
    sharkd_json_value_string("tap", hosts_req->tap_name);
    sharkd_json_value_string("type", "hosts");
    if (hosts_req->dump_v4) {
        sharkd_json_array_open("ipv4_hosts");
        sharkd_session_tap_ipv4_hosts_print();
        sharkd_json_array_close();
    }
    if (hosts_req->dump_v6) {
        sharkd_json_array_open("ipv6_hosts");
        sharkd_session_tap_ipv6_hosts_print();
        sharkd_json_array_close();
    }
    sharkd_json_object_close();
}

static void
sharkd_session_free_tap_hosts_cb(void *tapdata)
{
    struct sharkd_hosts_req *hosts_req = (struct sharkd_hosts_req *)tapdata;
    g_free(hosts_req);
}

static GString*
sharkd_session_eo_register_tap_listener(register_eo_t *eo, const char *tap_type, const char *tap_filter, tap_draw_cb tap_draw, void **ptap_data, GFreeFunc* ptap_free)
{
    export_object_list_t *eo_object;
    struct sharkd_export_object_list *object_list;

    object_list = sharkd_eo_object_list_get_entry_by_type(sharkd_eo_list, tap_type);
    if (object_list)
    {
        g_slist_free_full(object_list->entries, (GDestroyNotify) eo_free_entry);
        object_list->entries = NULL;
    }
    else
    {
        object_list = g_new(struct sharkd_export_object_list, 1);
        object_list->type = g_strdup(tap_type);
        object_list->proto = proto_get_protocol_short_name(find_protocol_by_id(get_eo_proto_id(eo)));
        object_list->entries = NULL;
        object_list->next = sharkd_eo_list;
        sharkd_eo_list = object_list;
    }

    eo_object  = g_new0(export_object_list_t, 1);
    eo_object->add_entry = sharkd_eo_object_list_add_entry;
    eo_object->get_entry = sharkd_eo_object_list_get_entry;
    eo_object->gui_data = (void *) object_list;

    *ptap_data = eo_object;
    *ptap_free = g_free; /* need to free only eo_object, object_list need to be kept for potential download */

    return register_tap_listener(get_eo_tap_listener_name(eo), eo_object, tap_filter, 0, NULL, get_eo_packet_func(eo), tap_draw, NULL);
}

/**
 * sharkd_session_process_tap()
 *
 * Process tap request
 *
 * Input:
 *   (m) tap0         - First tap request
 *   (o) tap1...tap15 - Other tap requests
 *
 * Output object with attributes:
 *   (m) taps  - array of object with attributes:
 *                  (m) tap  - tap name
 *                  (m) type - tap output type
 *                  ...
 *                  for type:stats see sharkd_session_process_tap_stats_cb()
 *                  for type:nstat see sharkd_session_process_tap_nstat_cb()
 *                  for type:conv see sharkd_session_process_tap_conv_cb()
 *                  for type:host see sharkd_session_process_tap_conv_cb()
 *                  for type:rtp-streams see sharkd_session_process_tap_rtp_cb()
 *                  for type:rtp-analyse see sharkd_session_process_tap_rtp_analyse_cb()
 *                  for type:eo see sharkd_session_process_tap_eo_cb()
 *                  for type:expert see sharkd_session_process_tap_expert_cb()
 *                  for type:rtd see sharkd_session_process_tap_rtd_cb()
 *                  for type:srt see sharkd_session_process_tap_srt_cb()
 *                  for type:flow see sharkd_session_process_tap_flow_cb()
 *
 *   (m) err   - error code
 */
static void
sharkd_session_process_tap(char *buf, const jsmntok_t *tokens, int count)
{
    void *taps_data[16];
    GFreeFunc taps_free[16];
    int taps_count = 0;
    int i;
    const char *tap_filter = json_find_attr(buf, tokens, count, "filter");

    rtpstream_tapinfo_t rtp_tapinfo =
    { NULL, NULL, NULL, NULL, 0, NULL, NULL, 0, TAP_ANALYSE, NULL, NULL, NULL, false, false};

    for (i = 0; i < 16; i++)
    {
        char tapbuf[32];
        const char *tok_tap;

        void *tap_data = NULL;
        GFreeFunc tap_free = NULL;
        GString *tap_error = NULL;

        snprintf(tapbuf, sizeof(tapbuf), "tap%d", i);
        tok_tap = json_find_attr(buf, tokens, count, tapbuf);
        if (!tok_tap)
            break;

        if (!strncmp(tok_tap, "stat:", 5))
        {
            stats_tree_cfg *cfg = stats_tree_get_cfg_by_abbr(tok_tap + 5);
            stats_tree *st;

            if (!cfg)
            {
                sharkd_json_error(
                        rpcid, -11001, NULL,
                        "sharkd_session_process_tap() stat %s not found", tok_tap + 5
                        );
                return;
            }

            st = stats_tree_new(cfg, NULL, tap_filter);

            tap_error = register_tap_listener(st->cfg->tapname, st, st->filter, st->cfg->flags, stats_tree_reset, stats_tree_packet, sharkd_session_process_tap_stats_cb, NULL);

            if (!tap_error && cfg->init)
                cfg->init(st);

            tap_data = st;
            tap_free = sharkd_session_free_tap_stats_cb;
        }
        else if (!strcmp(tok_tap, "expert"))
        {
            struct sharkd_expert_tap *expert_tap;

            expert_tap = g_new0(struct sharkd_expert_tap, 1);
            expert_tap->text = g_string_chunk_new(100);

            tap_error = register_tap_listener("expert", expert_tap, tap_filter, 0, NULL, sharkd_session_packet_tap_expert_cb, sharkd_session_process_tap_expert_cb, NULL);

            tap_data = expert_tap;
            tap_free = sharkd_session_free_tap_expert_cb;
        }
        else if (!strncmp(tok_tap, "seqa:", 5))
        {
            seq_analysis_info_t *graph_analysis;
            register_analysis_t *analysis;
            const char *tap_name;
            tap_packet_cb tap_func;
            unsigned tap_flags;

            analysis = sequence_analysis_find_by_name(tok_tap + 5);
            if (!analysis)
            {
                sharkd_json_error(
                        rpcid, -11002, NULL,
                        "sharkd_session_process_tap() seq analysis %s not found", tok_tap + 5
                        );
                return;
            }

            graph_analysis = sequence_analysis_info_new();
            graph_analysis->name = tok_tap + 5;
            /* TODO, make configurable */
            graph_analysis->any_addr = false;

            tap_name  = sequence_analysis_get_tap_listener_name(analysis);
            tap_flags = sequence_analysis_get_tap_flags(analysis);
            tap_func  = sequence_analysis_get_packet_func(analysis);

            tap_error = register_tap_listener(tap_name, graph_analysis, tap_filter, tap_flags, NULL, tap_func, sharkd_session_process_tap_flow_cb, NULL);

            tap_data = graph_analysis;
            tap_free = sharkd_session_free_tap_flow_cb;
        }
        else if (!strncmp(tok_tap, "conv:", 5) || !strncmp(tok_tap, "endpt:", 6))
        {
            struct register_ct *ct = NULL;
            const char *ct_tapname;
            struct sharkd_conv_tap_data *ct_data;
            tap_packet_cb tap_func = NULL;

            if (!strncmp(tok_tap, "conv:", 5))
            {
                ct = get_conversation_by_proto_id(proto_get_id_by_short_name(tok_tap + 5));

                if (!ct || !(tap_func = get_conversation_packet_func(ct)))
                {
                    sharkd_json_error(
                            rpcid, -11003, NULL,
                            "sharkd_session_process_tap() conv %s not found", tok_tap + 5
                            );
                    return;
                }
            }
            else if (!strncmp(tok_tap, "endpt:", 6))
            {
                ct = get_conversation_by_proto_id(proto_get_id_by_short_name(tok_tap + 6));

                if (!ct || !(tap_func = get_endpoint_packet_func(ct)))
                {
                    sharkd_json_error(
                            rpcid, -11004, NULL,
                            "sharkd_session_process_tap() endpt %s not found", tok_tap + 6
                            );
                    return;
                }
            }
            else
            {
                sharkd_json_error(
                        rpcid, -11005, NULL,
                        "sharkd_session_process_tap() conv/endpt(?): %s not found", tok_tap
                        );
                return;
            }

            ct_tapname = proto_get_protocol_filter_name(get_conversation_proto_id(ct));

            ct_data = g_new0(struct sharkd_conv_tap_data, 1);
            ct_data->type = tok_tap;
            ct_data->hash.user_data = ct_data;

            /* XXX: make configurable */
            ct_data->resolve_name = true;
            ct_data->resolve_port = true;

            tap_error = register_tap_listener(ct_tapname, &ct_data->hash, tap_filter, 0, NULL, tap_func, sharkd_session_process_tap_conv_cb, NULL);

            tap_data = &ct_data->hash;
            tap_free = sharkd_session_free_tap_conv_cb;
        }
        else if (!strncmp(tok_tap, "nstat:", 6))
        {
            stat_tap_table_ui *stat_tap = stat_tap_by_name(tok_tap + 6);
            stat_data_t *stat_data;

            if (!stat_tap)
            {
                sharkd_json_error(
                        rpcid, -11006, NULL,
                        "sharkd_session_process_tap() nstat=%s not found", tok_tap + 6
                        );
                return;
            }

            stat_tap->stat_tap_init_cb(stat_tap);

            stat_data = g_new0(stat_data_t, 1);
            stat_data->stat_tap_data = stat_tap;
            stat_data->user_data = NULL;

            tap_error = register_tap_listener(stat_tap->tap_name, stat_data, tap_filter, 0, NULL, stat_tap->packet_func, sharkd_session_process_tap_nstat_cb, NULL);

            tap_data = stat_data;
            tap_free = sharkd_session_free_tap_nstat_cb;
        }
        else if (!strncmp(tok_tap, "rtd:", 4))
        {
            register_rtd_t *rtd = get_rtd_table_by_name(tok_tap + 4);
            rtd_data_t *rtd_data;
            char *err;

            if (!rtd)
            {
                sharkd_json_error(
                        rpcid, -11007, NULL,
                        "sharkd_session_process_tap() rtd=%s not found", tok_tap + 4
                        );
                return;
            }

            rtd_table_get_filter(rtd, "", &tap_filter, &err);
            if (err != NULL)
            {
                sharkd_json_error(
                        rpcid, -11008, NULL,
                        "sharkd_session_process_tap() rtd=%s err=%s", tok_tap + 4, err
                        );
                g_free(err);
                return;
            }

            rtd_data = g_new0(rtd_data_t, 1);
            rtd_data->user_data = rtd;
            rtd_table_dissector_init(rtd, &rtd_data->stat_table, NULL, NULL);

            tap_error = register_tap_listener(get_rtd_tap_listener_name(rtd), rtd_data, tap_filter, 0, NULL, get_rtd_packet_func(rtd), sharkd_session_process_tap_rtd_cb, NULL);

            tap_data = rtd_data;
            tap_free = sharkd_session_free_tap_rtd_cb;
        }
        else if (!strncmp(tok_tap, "srt:", 4))
        {
            register_srt_t *srt = get_srt_table_by_name(tok_tap + 4);
            srt_data_t *srt_data;
            char *err;

            if (!srt)
            {
                sharkd_json_error(
                        rpcid, -11009, NULL,
                        "sharkd_session_process_tap() srt=%s not found", tok_tap + 4
                        );
                return;
            }

            srt_table_get_filter(srt, "", &tap_filter, &err);
            if (err != NULL)
            {
                sharkd_json_error(
                        rpcid, -11010, NULL,
                        "sharkd_session_process_tap() srt=%s err=%s", tok_tap + 4, err
                        );
                g_free(err);
                return;
            }

            srt_data = g_new0(srt_data_t, 1);
            srt_data->srt_array = g_array_new(FALSE, TRUE, sizeof(srt_stat_table *));
            srt_data->user_data = srt;
            srt_table_dissector_init(srt, srt_data->srt_array);

            tap_error = register_tap_listener(get_srt_tap_listener_name(srt), srt_data, tap_filter, 0, NULL, get_srt_packet_func(srt), sharkd_session_process_tap_srt_cb, NULL);

            tap_data = srt_data;
            tap_free = sharkd_session_free_tap_srt_cb;
        }
        else if (!strncmp(tok_tap, "eo:", 3))
        {
            register_eo_t *eo = get_eo_by_name(tok_tap + 3);

            if (!eo)
            {
                sharkd_json_error(
                        rpcid, -11011, NULL,
                        "sharkd_session_process_tap() eo=%s not found", tok_tap + 3
                        );
                return;
            }

            tap_error = sharkd_session_eo_register_tap_listener(eo, tok_tap, tap_filter, sharkd_session_process_tap_eo_cb, &tap_data, &tap_free);

            /* tap_data & tap_free assigned by sharkd_session_eo_register_tap_listener */
        }
        else if (!strcmp(tok_tap, "rtp-streams"))
        {
            tap_error = register_tap_listener("rtp", &rtp_tapinfo, tap_filter, 0, rtpstream_reset_cb, rtpstream_packet_cb, sharkd_session_process_tap_rtp_cb, NULL);

            tap_data = &rtp_tapinfo;
            tap_free = rtpstream_reset_cb;
        }
        else if (!strncmp(tok_tap, "rtp-analyse:", 12))
        {
            struct sharkd_analyse_rtp *rtp_req;

            rtp_req = (struct sharkd_analyse_rtp *) g_malloc0(sizeof(*rtp_req));
            if (!sharkd_rtp_match_init(&rtp_req->id, tok_tap + 12))
            {
                rtpstream_id_free(&rtp_req->id);
                g_free(rtp_req);
                continue;
            }

            rtp_req->tap_name = tok_tap;
            rtp_req->statinfo.first_packet = true;
            rtp_req->statinfo.reg_pt = PT_UNDEFINED;

            tap_error = register_tap_listener("rtp", rtp_req, tap_filter, 0, NULL, sharkd_session_packet_tap_rtp_analyse_cb, sharkd_session_process_tap_rtp_analyse_cb, NULL);

            tap_data = rtp_req;
            tap_free = sharkd_session_process_tap_rtp_free_cb;
        }
        else if (!strcmp(tok_tap, "multicast"))
        {
            mcaststream_tapinfo_t *mcaststream_tapinfo;
            mcaststream_tapinfo = (mcaststream_tapinfo_t *) g_malloc0(sizeof(*mcaststream_tapinfo));

            tap_error = register_tap_listener("udp", mcaststream_tapinfo, tap_filter, 0, NULL, mcaststream_packet, sharkd_session_process_tap_multicast_cb, NULL);
            tap_data = mcaststream_tapinfo;
            tap_free = sharkd_session_process_free_tap_multicast_cb;
        }
        else if (!strcmp(tok_tap, "phs"))
        {
            phs_t *rs;

            pc_proto_id = proto_registrar_get_id_byname("pkt_comment");

            rs = new_phs_t(NULL, tap_filter);

            tap_error = register_tap_listener("frame", rs, tap_filter, TL_REQUIRES_PROTO_TREE, NULL,
                                              protohierstat_packet,
                                              sharkd_session_process_tap_phs_cb, NULL);

            tap_data = rs;
            tap_free = sharkd_session_free_tap_phs_cb;
        }
        else if (!strcmp(tok_tap, "voip-calls"))
        {
            voip_stat_init_tapinfo();

            tap_error = register_tap_listener("frame", &tapinfo_, tap_filter, 0, NULL, NULL, sharkd_session_process_tap_voip_calls_cb, NULL);

            tapinfo_.session = cfile.epan;
            voip_calls_init_all_taps(&tapinfo_);

            tap_data = &tapinfo_;
            tap_free = sharkd_session_free_tap_voip_calls_cb;
        }
        else if (!strncmp(tok_tap, "voip-convs:", 11))
        {
            int len;
            unsigned int min, max;
            struct sharkd_voip_convs_req *voip_convs_req;
            const char *conv_arg = tok_tap + 11;

            // parse tok_tap to get which call we are asking for
            if (*conv_arg == 0) {
                // set all bits of voip_conv_sel (-1 in binary is all 1's)
                memset(voip_conv_sel, -1, sizeof(voip_conv_sel));
            } else {
                memset(voip_conv_sel, 0, sizeof(voip_conv_sel));

                while (*conv_arg != 0) {
                    if (*conv_arg == ',') {
                        conv_arg++;
                    }
                    if (sscanf(conv_arg, "%u-%u%n", &min, &max, &len) == 2) {
                        conv_arg += len;
                    } else if (sscanf(conv_arg, "%u%n", &min, &len) == 1) {
                        max = min;
                        conv_arg += len;
                    } else {
                        sharkd_json_error(
                                rpcid, -11014, NULL,
                                "sharkd_session_process_tap() voip-convs=%s invalid 'convs' parameter", tok_tap
                        );
                        return;
                    }
                    if (min > max || min >= VOIP_CONV_MAX || max >= VOIP_CONV_MAX) {
                        sharkd_json_error(
                                rpcid, -11012, NULL,
                                "sharkd_session_process_tap() voip-convs=%s invalid 'convs' number range", tok_tap
                        );
                        return;
                    }
                    for(; min <= max; min++) {
                        voip_conv_sel[min / VOIP_CONV_BITS] |= 1 << (min % VOIP_CONV_BITS);
                    }
                }
            }

            voip_stat_init_tapinfo();

            voip_convs_req = (struct sharkd_voip_convs_req *) g_malloc0(sizeof(*voip_convs_req));
            voip_convs_req->tapinfo = &tapinfo_;
            voip_convs_req->tap_name = tok_tap;

            tap_error = register_tap_listener("frame", voip_convs_req, tap_filter, 0, NULL, NULL, sharkd_session_process_tap_voip_convs_cb, NULL);

            tapinfo_.session = cfile.epan;
            voip_calls_init_all_taps(&tapinfo_);

            tap_data = voip_convs_req;
            tap_free = sharkd_session_free_tap_voip_convs_cb;
        }
        else if (!strncmp(tok_tap, "hosts:", 6))
        {
            bool dump_v4;
            bool dump_v6;
            struct sharkd_hosts_req *hosts_req;
            const char *proto_arg;
            char **proto_tokens;
            int proto_count;

            proto_arg = tok_tap + 6;

            if (strlen(proto_arg) == 0) {
                dump_v4 = true;
                dump_v6 = true;
            } else {
                dump_v4 = false;
                dump_v6 = false;

                proto_tokens = g_strsplit(proto_arg, ",", 0);
                proto_count = 0;
                while (proto_tokens[proto_count]) {
                    if (!strcmp("ip", proto_tokens[proto_count]) ||
                        !strcmp("ipv4", proto_tokens[proto_count])) {
                        dump_v4 = true;
                    } else if (!strcmp("ipv6", proto_tokens[proto_count])) {
                        dump_v6 = true;
                    } else {
                        g_strfreev(proto_tokens);
                        sharkd_json_error(
                                rpcid, -11015, NULL,
                                "sharkd_session_process_tap() hosts=%s invalid 'protos' parameter", tok_tap
                        );
                        return;
                    }
                    proto_count++;
                }
                g_strfreev(proto_tokens);
            }

            hosts_req = (struct sharkd_hosts_req *)g_malloc0(sizeof(*hosts_req));
            hosts_req->dump_v4 = dump_v4;
            hosts_req->dump_v6 = dump_v6;
            hosts_req->tap_name = tok_tap;

            tap_error = register_tap_listener("frame", hosts_req, tap_filter, TL_REQUIRES_PROTO_TREE, NULL, NULL, sharkd_session_process_tap_hosts_cb, NULL);

            tap_data = hosts_req;
            tap_free = sharkd_session_free_tap_hosts_cb;
        }
        else
        {
            sharkd_json_error(
                    rpcid, -11012, NULL,
                    "sharkd_session_process_tap() %s not recognized", tok_tap
                    );
            return;
        }

        if (tap_error)
        {
            sharkd_json_error(
                    rpcid, -11013, NULL,
                    "sharkd_session_process_tap() name=%s error=%s", tok_tap, tap_error->str
                    );
            g_string_free(tap_error, TRUE);
            if (tap_free)
                tap_free(tap_data);
            return;
        }

        taps_data[taps_count] = tap_data;
        taps_free[taps_count] = tap_free;
        taps_count++;
    }

    fprintf(stderr, "sharkd_session_process_tap() count=%d\n", taps_count);
    if (taps_count == 0)
    {
        sharkd_json_result_prologue(rpcid);
        sharkd_json_array_open("taps");
        sharkd_json_array_close();
        sharkd_json_result_epilogue();
        return;
    }

    sharkd_json_result_prologue(rpcid);
    sharkd_json_array_open("taps");
    sharkd_retap();
    sharkd_json_array_close();
    sharkd_json_result_epilogue();

    for (i = 0; i < taps_count; i++)
    {
        if (taps_data[i])
            remove_tap_listener(taps_data[i]);

        if (taps_free[i])
            taps_free[i](taps_data[i]);
    }
}

/**
 * sharkd_session_process_follow()
 *
 * Process follow request
 *
 * Input:
 *   (m) follow     - follow protocol request (e.g. HTTP)
 *   (m) filter     - filter request (e.g. tcp.stream == 1)
 *   (m) stream     - stream index number
 *   (o) sub_stream - follow sub-stream index number (e.g. for HTTP/2 and QUIC streams)
 *
 * Output object with attributes:
 *
 *   (m) err    - error code
 *   (m) shost  - server host
 *   (m) sport  - server port
 *   (m) sbytes - server send bytes count
 *   (m) chost  - client host
 *   (m) cport  - client port
 *   (m) cbytes - client send bytes count
 *   (o) payloads - array of object with attributes:
 *                  (o) s - set if server sent, else client
 *                  (m) n - packet number
 *                  (m) d - data base64 encoded
 */
static void
sharkd_session_process_follow(char *buf, const jsmntok_t *tokens, int count)
{
    const char *tok_follow = json_find_attr(buf, tokens, count, "follow");
    const char *tok_filter = json_find_attr(buf, tokens, count, "filter");
    const char *tok_sub_stream = json_find_attr(buf, tokens, count, "sub_stream");

    register_follow_t *follower;
    GString *tap_error;

    follow_info_t *follow_info;
    const char *host;
    char *port;

    follower = get_follow_by_name(tok_follow);
    if (!follower)
    {
        sharkd_json_error(
                rpcid, -12001, NULL,
                "sharkd_session_process_follow() follower=%s not found", tok_follow
                );
        return;
    }

    uint64_t substream_id = SUBSTREAM_UNUSED;
    if (tok_sub_stream)
    {
        ws_strtou64(tok_sub_stream, NULL, &substream_id);
    }

    /* follow_reset_stream ? */
    follow_info = g_new0(follow_info_t, 1);
    follow_info->substream_id = substream_id;
    /* gui_data, filter_out_filter not set, but not used by dissector */

    tap_error = register_tap_listener(get_follow_tap_string(follower), follow_info, tok_filter, 0, NULL, get_follow_tap_handler(follower), NULL, NULL);
    if (tap_error)
    {
        sharkd_json_error(
                rpcid, -12002, NULL,
                "sharkd_session_process_follow() name=%s error=%s", tok_follow, tap_error->str
                );
        g_string_free(tap_error, TRUE);
        g_free(follow_info);
        return;
    }

    sharkd_retap();

    sharkd_json_result_prologue(rpcid);

    /* Server information: hostname, port, bytes sent */
    host = address_to_name(&follow_info->server_ip);
    sharkd_json_value_string("shost", host);

    port = get_follow_port_to_display(follower)(NULL, follow_info->server_port);
    sharkd_json_value_string("sport", port);
    wmem_free(NULL, port);

    sharkd_json_value_anyf("sbytes", "%u", follow_info->bytes_written[0]);

    /* Client information: hostname, port, bytes sent */
    host = address_to_name(&follow_info->client_ip);
    sharkd_json_value_string("chost", host);

    port = get_follow_port_to_display(follower)(NULL, follow_info->client_port);
    sharkd_json_value_string("cport", port);
    wmem_free(NULL, port);

    sharkd_json_value_anyf("cbytes", "%u", follow_info->bytes_written[1]);

    if (follow_info->payload)
    {
        follow_record_t *follow_record;
        GList *cur;

        sharkd_json_array_open("payloads");
        for (cur = g_list_last(follow_info->payload); cur; cur = g_list_previous(cur))
        {
            follow_record = (follow_record_t *) cur->data;

            json_dumper_begin_object(&dumper);

            sharkd_json_value_anyf("n", "%u", follow_record->packet_num);
            sharkd_json_value_base64("d", follow_record->data->data, follow_record->data->len);

            if (follow_record->is_server)
                sharkd_json_value_anyf("s", "%d", 1);

            json_dumper_end_object(&dumper);
        }
        sharkd_json_array_close();
    }

    sharkd_json_result_epilogue();

    remove_tap_listener(follow_info);
    follow_info_free(follow_info);
}

static void
sharkd_session_process_frame_cb_tree(const char *key, epan_dissect_t *edt, proto_tree *tree, tvbuff_t **tvbs, bool display_hidden)
{
    proto_node *node;

    sharkd_json_array_open(key);
    for (node = tree->first_child; node; node = node->next)
    {
        field_info *finfo = PNODE_FINFO(node);

        if (!finfo)
            continue;

        if (!display_hidden && FI_GET_FLAG(finfo, FI_HIDDEN))
            continue;

        json_dumper_begin_object(&dumper);

        if (!finfo->rep)
        {
            char label_str[ITEM_LABEL_LENGTH];

            label_str[0] = '\0';
            proto_item_fill_label(finfo, label_str);
            sharkd_json_value_string("l", label_str);
        }
        else
        {
            sharkd_json_value_string("l", finfo->rep->representation);
        }

        if (finfo->ds_tvb && tvbs && tvbs[0] != finfo->ds_tvb)
        {
            int idx;

            for (idx = 1; tvbs[idx]; idx++)
            {
                if (tvbs[idx] == finfo->ds_tvb)
                {
                    sharkd_json_value_anyf("ds", "%d", idx);
                    break;
                }
            }
        }

        if (finfo->start >= 0 && finfo->length > 0)
            sharkd_json_value_anyf("h", "[%d,%d]", finfo->start, finfo->length);

        if (finfo->appendix_start >= 0 && finfo->appendix_length > 0)
            sharkd_json_value_anyf("i", "[%d,%d]", finfo->appendix_start, finfo->appendix_length);


        if (finfo->hfinfo)
        {
            char *filter;

            if (finfo->hfinfo->type == FT_PROTOCOL)
            {
                sharkd_json_value_string("t", "proto");
            }
            else if (finfo->hfinfo->type == FT_FRAMENUM)
            {
                sharkd_json_value_string("t", "framenum");
                sharkd_json_value_anyf("fnum", "%u", fvalue_get_uinteger(finfo->value));
            }
            else if (FI_GET_FLAG(finfo, FI_URL) && FT_IS_STRING(finfo->hfinfo->type))
            {
                char *url = fvalue_to_string_repr(NULL, finfo->value, FTREPR_DISPLAY, finfo->hfinfo->display);

                sharkd_json_value_string("t", "url");
                sharkd_json_value_string("url", url);
                wmem_free(NULL, url);
            }

            filter = proto_construct_match_selected_string(finfo, edt);
            if (filter)
            {
                sharkd_json_value_string("f", filter);
                wmem_free(NULL, filter);
            }

            if (finfo->hfinfo->abbrev)
                    sharkd_json_value_string("fn", finfo->hfinfo->abbrev);
        }

        if (FI_GET_FLAG(finfo, FI_GENERATED))
            sharkd_json_value_anyf("g", "true");

        if (FI_GET_FLAG(finfo, FI_HIDDEN))
            sharkd_json_value_anyf("v", "true");

        if (FI_GET_FLAG(finfo, PI_SEVERITY_MASK))
        {
            const char *severity = try_val_to_str(FI_GET_FLAG(finfo, PI_SEVERITY_MASK), expert_severity_vals);

            ws_assert(severity != NULL);

            sharkd_json_value_string("s", severity);
        }

        if (((proto_tree *) node)->first_child)
        {
            if (finfo->tree_type != -1)
                sharkd_json_value_anyf("e", "%d", finfo->tree_type);

            sharkd_session_process_frame_cb_tree("n", edt, (proto_tree *) node, tvbs, display_hidden);
        }

        json_dumper_end_object(&dumper);
    }
    sharkd_json_array_close();
}

static bool
sharkd_follower_visit_layers_cb(const void *key _U_, void *value, void *user_data)
{
    register_follow_t *follower = (register_follow_t *) value;
    epan_dissect_t *edt = (epan_dissect_t *) user_data;
    packet_info *pi = &edt->pi;

    const int proto_id = get_follow_proto_id(follower);

    uint32_t ignore_stream;
    uint32_t ignore_sub_stream;

    if (proto_is_frame_protocol(pi->layers, proto_get_protocol_filter_name(proto_id)))
    {
        const char *layer_proto = proto_get_protocol_short_name(find_protocol_by_id(proto_id));
        char *follow_filter;

        follow_filter = get_follow_conv_func(follower)(edt, pi, &ignore_stream, &ignore_sub_stream);

        json_dumper_begin_array(&dumper);
        json_dumper_value_string(&dumper, layer_proto);
        json_dumper_value_string(&dumper, follow_filter);
        json_dumper_end_array(&dumper);

        g_free(follow_filter);
    }

    return false;
}

static bool
sharkd_followers_visit_layers_cb(const void *key _U_, void *value, void *user_data)
{
    register_follow_t *follower = (register_follow_t *) value;
    epan_dissect_t *edt = (epan_dissect_t *) user_data;
    packet_info *pi = &edt->pi;

    const int proto_id = get_follow_proto_id(follower);

    unsigned stream;
    unsigned sub_stream;

    if (proto_is_frame_protocol(pi->layers, proto_get_protocol_filter_name(proto_id)))
    {
        const char *layer_proto = proto_get_protocol_short_name(find_protocol_by_id(proto_id));
        char *follow_filter;

        follow_filter = get_follow_conv_func(follower)(edt, pi, &stream, &sub_stream);

        sharkd_json_object_open(NULL);
        sharkd_json_value_string("protocol", layer_proto);
        sharkd_json_value_string("filter", follow_filter);
        if (get_follow_stream_count_func(follower) != NULL)
        {
            sharkd_json_value_anyf("stream", "%u", stream);
        }
        if (get_follow_sub_stream_id_func(follower) != NULL)
        {
            sharkd_json_value_anyf("sub_stream", "%u", sub_stream);
        }
        sharkd_json_object_close();

        g_free(follow_filter);
    }

    return false;
}

struct sharkd_frame_request_data
{
    bool display_hidden;
};

static void
sharkd_session_process_frame_cb(epan_dissect_t *edt, proto_tree *tree, struct epan_column_info *cinfo, const GSList *data_src, void *data)
{
    packet_info *pi = &edt->pi;
    frame_data *fdata = pi->fd;
    wtap_block_t pkt_block = NULL;

    const struct sharkd_frame_request_data * const req_data = (const struct sharkd_frame_request_data * const) data;
    const bool display_hidden = (req_data) ? req_data->display_hidden : false;

    sharkd_json_result_prologue(rpcid);

    if (fdata->has_modified_block)
        pkt_block = sharkd_get_modified_block(fdata);
    else
        pkt_block = pi->rec->block;

    if (pkt_block)
    {
        unsigned i;
        unsigned n;
        char *comment;

        n = wtap_block_count_option(pkt_block, OPT_COMMENT);

        sharkd_json_array_open("comment");
        for (i = 0; i < n; i++) {
            if (WTAP_OPTTYPE_SUCCESS == wtap_block_get_nth_string_option_value(pkt_block, OPT_COMMENT, i, &comment)) {
                sharkd_json_value_string(NULL, comment);
            }
        }
        sharkd_json_array_close();
    }

    if (tree)
    {
        tvbuff_t **tvbs = NULL;

        /* arrayize data src, to speedup searching for ds_tvb index */
        if (data_src && data_src->next /* only needed if there are more than one data source */)
        {
            unsigned count = g_slist_length((GSList *) data_src);
            unsigned i;

            tvbs = (tvbuff_t **) g_malloc0((count + 1) * sizeof(*tvbs));

            for (i = 0; i < count; i++)
            {
                const struct data_source *src = (const struct data_source *) g_slist_nth_data((GSList *) data_src, i);

                tvbs[i] = get_data_source_tvb(src);
            }

            tvbs[count] = NULL;
        }

        sharkd_session_process_frame_cb_tree("tree", edt, tree, tvbs, display_hidden);

        g_free(tvbs);
    }

    if (cinfo)
    {
        int col;

        sharkd_json_array_open("col");
        for (col = 0; col < cinfo->num_cols; ++col)
        {
            sharkd_json_value_string(NULL, get_column_text(cinfo, col));
        }
        sharkd_json_array_close();
    }

    if (fdata->ignored)
        sharkd_json_value_anyf("i", "true");

    if (fdata->marked)
        sharkd_json_value_anyf("m", "true");

    if (fdata->color_filter)
    {
        sharkd_json_value_stringf("bg", "%06x", color_t_to_rgb(&fdata->color_filter->bg_color));
        sharkd_json_value_stringf("fg", "%06x", color_t_to_rgb(&fdata->color_filter->fg_color));
    }

    if (data_src)
    {
        struct data_source *src = (struct data_source *) data_src->data;
        bool ds_open = false;

        tvbuff_t *tvb;
        unsigned length;

        tvb = get_data_source_tvb(src);
        length = tvb_captured_length(tvb);

        if (length != 0)
        {
            const unsigned char *cp = tvb_get_ptr(tvb, 0, length);

            /* XXX pi.fd->encoding */
            sharkd_json_value_base64("bytes", cp, length);
        }
        else
        {
            sharkd_json_value_base64("bytes", "", 0);
        }

        data_src = data_src->next;
        if (data_src)
        {
            sharkd_json_array_open("ds");
            ds_open = true;
        }

        while (data_src)
        {
            src = (struct data_source *) data_src->data;

            json_dumper_begin_object(&dumper);

            {
                char *src_name = get_data_source_name(src);

                sharkd_json_value_string("name", src_name);
                wmem_free(NULL, src_name);
            }

            tvb = get_data_source_tvb(src);
            length = tvb_captured_length(tvb);

            if (length != 0)
            {
                const unsigned char *cp = tvb_get_ptr(tvb, 0, length);

                /* XXX pi.fd->encoding */
                sharkd_json_value_base64("bytes", cp, length);
            }
            else
            {
                sharkd_json_value_base64("bytes", "", 0);
            }

            json_dumper_end_object(&dumper);

            data_src = data_src->next;
        }

        /* close ds, only if was opened */
        if (ds_open)
            sharkd_json_array_close();
    }

    sharkd_json_array_open("fol");
    follow_iterate_followers(sharkd_follower_visit_layers_cb, edt);
    sharkd_json_array_close();

    sharkd_json_array_open("followers");
    follow_iterate_followers(sharkd_followers_visit_layers_cb, edt);
    sharkd_json_array_close();

    sharkd_json_result_epilogue();
}

#define SHARKD_IOGRAPH_MAX_ITEMS 1 << 25 /* 33,554,432 limit of items, same as max_io_items_ in ui/qt/io_graph_dialog.h */

struct sharkd_iograph
{
    /* config */
    int hf_index;
    io_graph_item_unit_t calc_type;
    uint32_t interval;

    /* result */
    int space_items;
    int num_items;
    io_graph_item_t *items;
    GString *error;
};

static tap_packet_status
sharkd_iograph_packet(void *g, packet_info *pinfo, epan_dissect_t *edt, const void *dummy _U_, tap_flags_t flags _U_)
{
    struct sharkd_iograph *graph = (struct sharkd_iograph *) g;
    int idx;
    bool update_succeeded;

    int64_t tmp_idx = get_io_graph_index(pinfo, graph->interval);
    if (tmp_idx < 0 || tmp_idx >= SHARKD_IOGRAPH_MAX_ITEMS)
        return TAP_PACKET_DONT_REDRAW;

    idx = (int)tmp_idx;

    if (idx + 1 > graph->num_items)
    {
        if (idx + 1 > graph->space_items)
        {
            int new_size = idx + 1024;

            graph->items = (io_graph_item_t *) g_realloc(graph->items, sizeof(io_graph_item_t) * new_size);
            reset_io_graph_items(&graph->items[graph->space_items], new_size - graph->space_items, graph->hf_index);

            graph->space_items = new_size;
        }
        else if (graph->items == NULL)
        {
            graph->items = g_new(io_graph_item_t, graph->space_items);
            reset_io_graph_items(graph->items, graph->space_items, graph->hf_index);
        }

        graph->num_items = idx + 1;
    }

    update_succeeded = update_io_graph_item(graph->items, idx, pinfo, edt, graph->hf_index, graph->calc_type, graph->interval);
    /* XXX - TAP_PACKET_FAILED if the item couldn't be updated, with an error message? */
    return update_succeeded ? TAP_PACKET_REDRAW : TAP_PACKET_DONT_REDRAW;
}

/**
 * sharkd_session_process_iograph()
 *
 * Process iograph request
 *
 * Input:
 *   (o) interval           - interval time, if not specified: 1000
 *   (o) interval_units     - units for interval time, must be 's', 'ms' or 'us', if not specified: ms
 *   (m) graph0             - First graph request
 *   (o) graph1...graph9    - Other graph requests
 *   (o) filter0            - First graph filter
 *   (o) filter1...filter9  - Other graph filters
 *
 * Graph requests can be one of: "packets", "bytes", "bits", "sum:<field>", "frames:<field>", "max:<field>", "min:<field>", "avg:<field>", "load:<field>",
 * if you use variant with <field>, you need to pass field name in filter request.
 *
 * Output object with attributes:
 *   (m) iograph - array of graph results with attributes:
 *                  errmsg - graph cannot be constructed
 *                  items  - graph values, zeros are skipped, if value is not a number it's next index encoded as hex string
 */
static void
sharkd_session_process_iograph(char *buf, const jsmntok_t *tokens, int count)
{
    const char *tok_interval = json_find_attr(buf, tokens, count, "interval");
    const char *tok_interval_units = json_find_attr(buf, tokens, count, "interval_units");
    struct sharkd_iograph graphs[10];
    bool is_any_ok = false;
    int graph_count;

    int i;

    /* default: 1000ms = one per second */
    uint32_t interval = 1000;
    const char *interval_units = "ms";

    if (tok_interval)
        ws_strtou32(tok_interval, NULL, &interval);

    if (tok_interval_units)
    {
        if (strcmp(tok_interval_units, "us") != 0 &&
            strcmp(tok_interval_units, "ms") != 0 &&
            strcmp(tok_interval_units, "s") != 0)
        {
            sharkd_json_error(
                    rpcid, -7003, NULL,
                    "Invalid interval_units parameter: '%s', must be 's', 'ms' or 'us'", tok_interval_units
            );
            return;
        }
        interval_units = tok_interval_units;
    }

    uint32_t interval_us = 0;
    if (strcmp(interval_units, "us") == 0)
    {
        interval_us = interval;
    }
    else if (strcmp(interval_units, "ms") == 0)
    {
        interval_us = 1000 * interval;
    }
    else if (strcmp(interval_units, "s") == 0)
    {
        interval_us = 1000000 * interval;
    }

    for (i = graph_count = 0; i < (int) G_N_ELEMENTS(graphs); i++)
    {
        struct sharkd_iograph *graph = &graphs[graph_count];

        const char *tok_graph;
        const char *tok_filter;
        char tok_format_buf[32];
        const char *field_name;

        snprintf(tok_format_buf, sizeof(tok_format_buf), "graph%d", i);
        tok_graph = json_find_attr(buf, tokens, count, tok_format_buf);
        if (!tok_graph)
            break;

        snprintf(tok_format_buf, sizeof(tok_format_buf), "filter%d", i);
        tok_filter = json_find_attr(buf, tokens, count, tok_format_buf);

        if (!strcmp(tok_graph, "packets"))
            graph->calc_type = IOG_ITEM_UNIT_PACKETS;
        else if (!strcmp(tok_graph, "bytes"))
            graph->calc_type = IOG_ITEM_UNIT_BYTES;
        else if (!strcmp(tok_graph, "bits"))
            graph->calc_type = IOG_ITEM_UNIT_BITS;
        else if (g_str_has_prefix(tok_graph, "sum:"))
            graph->calc_type = IOG_ITEM_UNIT_CALC_SUM;
        else if (g_str_has_prefix(tok_graph, "frames:"))
            graph->calc_type = IOG_ITEM_UNIT_CALC_FRAMES;
        else if (g_str_has_prefix(tok_graph, "fields:"))
            graph->calc_type = IOG_ITEM_UNIT_CALC_FIELDS;
        else if (g_str_has_prefix(tok_graph, "max:"))
            graph->calc_type = IOG_ITEM_UNIT_CALC_MAX;
        else if (g_str_has_prefix(tok_graph, "min:"))
            graph->calc_type = IOG_ITEM_UNIT_CALC_MIN;
        else if (g_str_has_prefix(tok_graph, "avg:"))
            graph->calc_type = IOG_ITEM_UNIT_CALC_AVERAGE;
        else if (g_str_has_prefix(tok_graph, "load:"))
            graph->calc_type = IOG_ITEM_UNIT_CALC_LOAD;
        else
            break;

        field_name = strchr(tok_graph, ':');
        if (field_name)
            field_name = field_name + 1;

        /* io_graph_item now supports microseconds (and this parameter
         * is expected to be in microseconds.) */
        graph->interval = interval_us;

        graph->hf_index = -1;
        graph->error = check_field_unit(field_name, &graph->hf_index, graph->calc_type);

        graph->space_items = 0; /* TODO, can avoid realloc()s in sharkd_iograph_packet() by calculating: capture_time / interval */
        graph->num_items = 0;
        graph->items = NULL;

        if (!graph->error)
            graph->error = register_tap_listener("frame", graph, tok_filter, TL_REQUIRES_PROTO_TREE, NULL, sharkd_iograph_packet, NULL, NULL);

        graph_count++;

        if (graph->error)
        {
            sharkd_json_error(
                    rpcid, -6001, NULL,
                    "%s", graph->error->str
                    );
            g_string_free(graph->error, TRUE);
            return;
        }

        if (graph->error == NULL)
            is_any_ok = true;
    }

    /* retap only if we have at least one ok */
    if (is_any_ok)
        sharkd_retap();

    sharkd_json_result_prologue(rpcid);

    sharkd_json_array_open("iograph");
    for (i = 0; i < graph_count; i++)
    {
        struct sharkd_iograph *graph = &graphs[i];

        json_dumper_begin_object(&dumper);

        if (graph->error)
        {
            fprintf(stderr, "SNAP 6002 - we should never get to here.\n");
            g_string_free(graph->error, TRUE);
            exit(-1);
        }
        else
        {
            int idx;
            int next_idx = 0;

            sharkd_json_array_open("items");
            for (idx = 0; idx < graph->num_items; idx++)
            {
                double val;

                val = get_io_graph_item(graph->items, graph->calc_type, idx, graph->hf_index, &cfile, graph->interval, graph->num_items);

                /* if it's zero, don't display */
                if (val == 0.0)
                    continue;

                /* cause zeros are not printed, need to output index */
                if (next_idx != idx)
                    sharkd_json_value_stringf(NULL, "%x", idx);

                sharkd_json_value_anyf(NULL, "%f", val);
                next_idx = idx + 1;
            }
            sharkd_json_array_close();
        }
        json_dumper_end_object(&dumper);

        remove_tap_listener(graph);
        g_free(graph->items);
    }
    sharkd_json_array_close();

    sharkd_json_result_epilogue();
}

/**
 * sharkd_session_process_intervals()
 *
 * Process intervals request - generate basic capture file statistics per requested interval.
 *
 * Input:
 *   (o) interval - interval time in ms, if not specified: 1000ms
 *   (o) filter   - filter for generating interval request
 *
 * Output object with attributes:
 *   (m) intervals - array of intervals, with indexes:
 *             [0] - index of interval,
 *             [1] - number of frames during interval,
 *             [2] - number of bytes during interval.
 *
 *   (m) last   - last interval number.
 *   (m) frames - total number of frames
 *   (m) bytes  - total number of bytes
 *
 * NOTE: If frames are not in order, there might be items with same interval index, or even negative one.
 */
static void
sharkd_session_process_intervals(char *buf, const jsmntok_t *tokens, int count)
{
    const char *tok_interval = json_find_attr(buf, tokens, count, "interval");
    const char *tok_filter = json_find_attr(buf, tokens, count, "filter");

    const uint8_t *filter_data = NULL;

    struct
    {
        unsigned int frames;
        uint64_t bytes;
    } st, st_total;

    nstime_t *start_ts;

    uint32_t interval_ms = 1000; /* default: one per second */

    int64_t idx;
    int64_t max_idx = 0;

    if (tok_interval)
        ws_strtou32(tok_interval, NULL, &interval_ms);  // already validated

    if (tok_filter)
    {
        const struct sharkd_filter_item *filter_item;

        filter_item = sharkd_session_filter_data(tok_filter);
        if (!filter_item)
        {
            sharkd_json_error(
                    rpcid, -7001, NULL,
                    "Invalid filter parameter: %s", tok_filter
                    );
            return;
        }
        filter_data = filter_item->filtered;
    }

    st_total.frames = 0;
    st_total.bytes  = 0;

    st.frames = 0;
    st.bytes  = 0;

    idx = 0;

    sharkd_json_result_prologue(rpcid);
    sharkd_json_array_open("intervals");

    start_ts = (cfile.count >= 1) ? &(sharkd_get_frame(1)->abs_ts) : NULL;

    for (uint32_t framenum = 1; framenum <= cfile.count; framenum++)
    {
        frame_data *fdata;
        int64_t msec_rel;
        int64_t new_idx;

        if (filter_data && !(filter_data[framenum / 8] & (1 << (framenum % 8))))
            continue;

        fdata = sharkd_get_frame(framenum);

        msec_rel = (fdata->abs_ts.secs - start_ts->secs) * (int64_t) 1000 + (fdata->abs_ts.nsecs - start_ts->nsecs) / 1000000;
        new_idx  = msec_rel / interval_ms;

        if (idx != new_idx)
        {
            if (st.frames != 0)
            {
                sharkd_json_value_anyf(NULL, "[%" PRId64 ",%u,%" PRIu64 "]", idx, st.frames, st.bytes);
            }

            idx = new_idx;
            if (idx > max_idx)
                max_idx = idx;

            st.frames = 0;
            st.bytes  = 0;
        }

        st.frames += 1;
        st.bytes  += fdata->pkt_len;

        st_total.frames += 1;
        st_total.bytes  += fdata->pkt_len;
    }

    if (st.frames != 0)
    {
        sharkd_json_value_anyf(NULL, "[%" PRId64 ",%u,%" PRIu64 "]", idx, st.frames, st.bytes);
    }
    sharkd_json_array_close();

    sharkd_json_value_anyf("last", "%" PRId64, max_idx);
    sharkd_json_value_anyf("frames", "%u", st_total.frames);
    sharkd_json_value_anyf("bytes", "%" PRIu64, st_total.bytes);

    sharkd_json_result_epilogue();
}

/**
 * sharkd_session_process_frame()
 *
 * Process frame request
 *
 * Input:
 *   (m) frame - requested frame number
 *   (o) ref_frame - time reference frame number
 *   (o) prev_frame - previously displayed frame number
 *   (o) proto - set if output frame tree
 *   (o) columns - set if output frame columns
 *   (o) color - set if output color-filter bg/fg
 *   (o) bytes - set if output frame bytes
 *   (o) hidden - set if output hidden tree fields
 *
 * Output object with attributes:
 *   (m) err   - 0 if succeed
 *   (o) tree  - array of frame nodes with attributes:
 *                  l - label
 *                  t: 'proto', 'framenum', 'url' - type of node
 *                  f - filter string
 *                  fn - field name
 *                  s - severity
 *                  e - subtree ett index
 *                  n - array of subtree nodes
 *                  h - two item array: (item start, item length)
 *                  i - two item array: (appendix start, appendix length)
 *                  p - [RESERVED] two item array: (protocol start, protocol length)
 *                  ds- data src index
 *                  url  - only for t:'url', url
 *                  fnum - only for t:'framenum', frame number
 *                  g - if field is generated by Wireshark
 *                  v - if field is hidden
 *
 *   (o) col   - array of column data
 *   (o) bytes - base64 of frame bytes
 *   (o) ds    - array of other data srcs
 *   (o) comment - frame comment
 *   (o) fol   - array of follow filters:
 *                  [0] - protocol
 *                  [1] - filter string
 *   (o) followers - array of followers with attributes:
 *                      protocol - protocol string
 *                      filter - filter string
 *                      stream - stream index number
 *                      sub_stream - sub-stream index number (optional, e.g. for HTTP/2 and QUIC streams)
 *   (o) i   - if frame is ignored
 *   (o) m   - if frame is marked
 *   (o) bg  - color filter - background color in hex
 *   (o) fg  - color filter - foreground color in hex
 */
static void
sharkd_session_process_frame(char *buf, const jsmntok_t *tokens, int count)
{
    const char *tok_frame = json_find_attr(buf, tokens, count, "frame");
    const char *tok_ref_frame = json_find_attr(buf, tokens, count, "ref_frame");
    const char *tok_prev_frame = json_find_attr(buf, tokens, count, "prev_frame");
    column_info *cinfo = NULL;

    uint32_t framenum, ref_frame_num, prev_dis_num;
    uint32_t dissect_flags = SHARKD_DISSECT_FLAG_NULL;
    struct sharkd_frame_request_data req_data;
    wtap_rec rec; /* Record metadata */
    Buffer rec_buf;   /* Record data */
    enum dissect_request_status status;
    int err;
    char *err_info;

    ws_strtou32(tok_frame, NULL, &framenum);  // we have already validated this

    ref_frame_num = (framenum != 1) ? 1 : 0;
    if (tok_ref_frame)
    {
        ws_strtou32(tok_ref_frame, NULL, &ref_frame_num);
        if (ref_frame_num > framenum)
        {
            sharkd_json_error(
                    rpcid, -8001, NULL,
                    "Invalid ref_frame - The ref_frame occurs after the frame specified"
                    );
            return;
        }
    }

    prev_dis_num = framenum - 1;
    if (tok_prev_frame)
    {
        ws_strtou32(tok_prev_frame, NULL, &prev_dis_num);
        if (prev_dis_num >= framenum)
        {
            sharkd_json_error(
                    rpcid, -8002, NULL,
                    "Invalid prev_frame - The prev_frame occurs on or after the frame specified"
                    );
            return;
        }
    }

    if (json_find_attr(buf, tokens, count, "proto") != NULL)
        dissect_flags |= SHARKD_DISSECT_FLAG_PROTO_TREE;
    if (json_find_attr(buf, tokens, count, "bytes") != NULL)
        dissect_flags |= SHARKD_DISSECT_FLAG_BYTES;
    if (json_find_attr(buf, tokens, count, "columns") != NULL) {
        dissect_flags |= SHARKD_DISSECT_FLAG_COLUMNS;
        cinfo = &cfile.cinfo;
    }
    if (json_find_attr(buf, tokens, count, "color") != NULL)
        dissect_flags |= SHARKD_DISSECT_FLAG_COLOR;

    req_data.display_hidden = (json_find_attr(buf, tokens, count, "v") != NULL);

    wtap_rec_init(&rec);
    ws_buffer_init(&rec_buf, 1514);

    status = sharkd_dissect_request(framenum, ref_frame_num, prev_dis_num,
            &rec, &rec_buf, cinfo, dissect_flags,
            &sharkd_session_process_frame_cb, &req_data, &err, &err_info);
    switch (status) {

        case DISSECT_REQUEST_SUCCESS:
            /* success */
            break;

        case DISSECT_REQUEST_NO_SUCH_FRAME:
            sharkd_json_error(
                    rpcid, -8003, NULL,
                    "Invalid frame - The frame number requested is out of range"
                    );
            break;

        case DISSECT_REQUEST_READ_ERROR:
            sharkd_json_error(
                    rpcid, -8003, NULL,
                    /* XXX - show the error details */
                    "Read error - The frame could not be read from the file"
                    );
            g_free(err_info);
            break;
    }

    wtap_rec_cleanup(&rec);
    ws_buffer_free(&rec_buf);
}

/**
 * sharkd_session_process_check()
 *
 * Process check request.
 *
 * Input:
 *   (o) filter - filter to be checked
 *   (o) field - field to be checked
 *
 * Output object with attributes:
 *   (m) err - always 0
 *   (o) filter - 'ok', 'warn' or error message
 *   (o) field - 'ok', or 'notfound'
 */
static int
sharkd_session_process_check(char *buf, const jsmntok_t *tokens, int count)
{
    const char *tok_filter = json_find_attr(buf, tokens, count, "filter");
    const char *tok_field = json_find_attr(buf, tokens, count, "field");

    if (tok_filter != NULL)
    {
        dfilter_t *dfp;
        df_error_t *df_err = NULL;

        if (dfilter_compile(tok_filter, &dfp, &df_err))
        {
            if (dfp && dfilter_deprecated_tokens(dfp))
                sharkd_json_warning(rpcid, "Filter contains deprecated tokens");
            else
                sharkd_json_simple_ok(rpcid);

            dfilter_free(dfp);
            df_error_free(&df_err);
            return 0;
        }
        else
        {
            sharkd_json_error(
                    rpcid, -5001, NULL,
                    "Filter invalid - %s", df_err->msg
                    );
            df_error_free(&df_err);
            return -5001;
        }
    }

    if (tok_field != NULL)
    {
        header_field_info *hfi = proto_registrar_get_byname(tok_field);

        if (!hfi)
        {
            sharkd_json_error(
                    rpcid, -5002, NULL,
                    "Field %s not found", tok_field
                    );
            return -5002;
        }
        else
        {
            sharkd_json_simple_ok(rpcid);
            return 0;
        }
    }

    sharkd_json_simple_ok(rpcid);
    return 0;
}

struct sharkd_session_process_complete_pref_data
{
    const char *module;
    const char *pref;
};

static unsigned
sharkd_session_process_complete_pref_cb(module_t *module, void *d)
{
    struct sharkd_session_process_complete_pref_data *data = (struct sharkd_session_process_complete_pref_data *) d;

    if (strncmp(data->pref, module->name, strlen(data->pref)) != 0)
        return 0;

    json_dumper_begin_object(&dumper);
    sharkd_json_value_string("f", module->name);
    sharkd_json_value_string("d", module->title);
    json_dumper_end_object(&dumper);

    return 0;
}

static unsigned
sharkd_session_process_complete_pref_option_cb(pref_t *pref, void *d)
{
    struct sharkd_session_process_complete_pref_data *data = (struct sharkd_session_process_complete_pref_data *) d;
    const char *pref_name = prefs_get_name(pref);
    const char *pref_title = prefs_get_title(pref);

    if (strncmp(data->pref, pref_name, strlen(data->pref)) != 0)
        return 0;

    json_dumper_begin_object(&dumper);
    sharkd_json_value_stringf("f", "%s.%s", data->module, pref_name);
    sharkd_json_value_string("d", pref_title);
    json_dumper_end_object(&dumper);

    return 0; /* continue */
}

/**
 * sharkd_session_process_complete()
 *
 * Process complete request
 *
 * Input:
 *   (o) field - field to be completed
 *   (o) pref  - preference to be completed
 *
 * Output object with attributes:
 *   (m) err - always 0
 *   (o) field - array of object with attributes:
 *                  (m) f - field text
 *                  (o) t - field type (FT_ number)
 *                  (o) n - field name
 *   (o) pref  - array of object with attributes:
 *                  (m) f - pref name
 *                  (o) d - pref description
 */
static int
sharkd_session_process_complete(char *buf, const jsmntok_t *tokens, int count)
{
    const char *tok_field = json_find_attr(buf, tokens, count, "field");
    const char *tok_pref  = json_find_attr(buf, tokens, count, "pref");

    sharkd_json_result_prologue(rpcid);

    if (tok_field != NULL && tok_field[0])
    {
        const size_t filter_length = strlen(tok_field);
        const int filter_with_dot = !!strchr(tok_field, '.');

        void *proto_cookie;
        void *field_cookie;
        int proto_id;

        sharkd_json_array_open("field");

        for (proto_id = proto_get_first_protocol(&proto_cookie); proto_id != -1; proto_id = proto_get_next_protocol(&proto_cookie))
        {
            protocol_t *protocol = find_protocol_by_id(proto_id);
            const char *protocol_filter;
            const char *protocol_name;
            header_field_info *hfinfo;

            if (!proto_is_protocol_enabled(protocol))
                continue;

            protocol_name   = proto_get_protocol_long_name(protocol);
            protocol_filter = proto_get_protocol_filter_name(proto_id);

            if (strlen(protocol_filter) >= filter_length && !g_ascii_strncasecmp(tok_field, protocol_filter, filter_length))
            {
                json_dumper_begin_object(&dumper);
                {
                    sharkd_json_value_string("f", protocol_filter);
                    sharkd_json_value_anyf("t", "%d", FT_PROTOCOL);
                    sharkd_json_value_string("n", protocol_name);
                }
                json_dumper_end_object(&dumper);
            }

            if (!filter_with_dot)
                continue;

            for (hfinfo = proto_get_first_protocol_field(proto_id, &field_cookie); hfinfo != NULL; hfinfo = proto_get_next_protocol_field(proto_id, &field_cookie))
            {
                if (hfinfo->same_name_prev_id != -1) /* ignore duplicate names */
                    continue;

                if (strlen(hfinfo->abbrev) >= filter_length && !g_ascii_strncasecmp(tok_field, hfinfo->abbrev, filter_length))
                {
                    json_dumper_begin_object(&dumper);
                    {
                        sharkd_json_value_string("f", hfinfo->abbrev);

                        /* XXX, skip displaying name, if there are multiple (to not confuse user) */
                        if (hfinfo->same_name_next == NULL)
                        {
                            sharkd_json_value_anyf("t", "%d", hfinfo->type);
                            sharkd_json_value_string("n", hfinfo->name);
                        }
                    }
                    json_dumper_end_object(&dumper);
                }
            }
        }

        sharkd_json_array_close();
    }

    if (tok_pref != NULL && tok_pref[0])
    {
        struct sharkd_session_process_complete_pref_data data;
        char *dot_sepa;

        data.module = tok_pref;
        data.pref = tok_pref;

        sharkd_json_array_open("pref");
        if ((dot_sepa = strchr(tok_pref, '.')))
        {
            module_t *pref_mod;

            *dot_sepa = '\0'; /* XXX, C abuse: discarding-const */
            data.pref = dot_sepa + 1;

            pref_mod = prefs_find_module(data.module);
            if (pref_mod)
                prefs_pref_foreach(pref_mod, sharkd_session_process_complete_pref_option_cb, &data);

            *dot_sepa = '.';
        }
        else
        {
            prefs_modules_foreach(sharkd_session_process_complete_pref_cb, &data);
        }
        sharkd_json_array_close();
    }

    sharkd_json_result_epilogue();

    return 0;
}

/**
 * sharkd_session_process_setcomment()
 *
 * Process setcomment request
 *
 * Input:
 *   (m) frame - frame number
 *   (o) comment - user comment
 *
 * Output object with attributes:
 *   (m) err   - error code: 0 succeed
 *
 * Note:
 *   For now, adds comments, doesn't remove or replace them.
 */
static void
sharkd_session_process_setcomment(char *buf, const jsmntok_t *tokens, int count)
{
    const char *tok_frame   = json_find_attr(buf, tokens, count, "frame");
    const char *tok_comment = json_find_attr(buf, tokens, count, "comment");

    uint32_t framenum;
    frame_data *fdata;
    wtap_opttype_return_val ret;
    wtap_block_t pkt_block = NULL;

    if (!tok_frame || !ws_strtou32(tok_frame, NULL, &framenum) || framenum == 0)
    {
        sharkd_json_error(
                rpcid, -3001, NULL,
                "Frame number must be a positive integer"
                );
        return;
    }

    fdata = sharkd_get_frame(framenum);  // BUG HERE - If no file loaded you get a crash
    if (!fdata)
    {
        sharkd_json_error(
                rpcid, -3002, NULL,
                "Frame number is out of range"
                );
        return;
    }

    pkt_block = sharkd_get_packet_block(fdata);

    ret = wtap_block_add_string_option(pkt_block, OPT_COMMENT, tok_comment, strlen(tok_comment));

    if (ret != WTAP_OPTTYPE_SUCCESS)
    {
        sharkd_json_error(
                rpcid, -3003, NULL,
                "Unable to set the comment"
                );
    }
    else
    {
        sharkd_set_modified_block(fdata, pkt_block);
        sharkd_json_simple_ok(rpcid);
    }
}

/**
 * sharkd_session_process_setconf()
 *
 * Process setconf request
 *
 * Input:
 *   (m) name  - preference name
 *   (m) value - preference value
 *
 * Output object with attributes:
 *   (m) err   - error code: 0 succeed
 */
static void
sharkd_session_process_setconf(char *buf, const jsmntok_t *tokens, int count)
{
    const char *tok_name = json_find_attr(buf, tokens, count, "name");
    const char *tok_value = json_find_attr(buf, tokens, count, "value");
    char pref[4096];
    char *errmsg = NULL;

    prefs_set_pref_e ret;

    if (!tok_name || tok_name[0] == '\0')
    {
        sharkd_json_error(
                rpcid, -4001, NULL,
                "Preference name missing"
                );
        return;
    }

    if (!tok_value)
    {
        sharkd_json_error(
                rpcid, -4002, NULL,
                "Preference value missing"
                );
        return;
    }

    snprintf(pref, sizeof(pref), "%s:%s", tok_name, tok_value);

    ret = prefs_set_pref(pref, &errmsg);

    switch (ret)
    {
        case PREFS_SET_OK:
            sharkd_json_simple_ok(rpcid);
            break;

        case PREFS_SET_OBSOLETE:
            sharkd_json_error(
                    rpcid, -4003, NULL,
                    "The preference specified is obsolete"
                    );
            break;

        case PREFS_SET_NO_SUCH_PREF:
            sharkd_json_error(
                    rpcid, -4004, NULL,
                    "No such preference exists"
                    );
            break;

        default:
            sharkd_json_error(
                    rpcid, -4005, NULL,
                    "Unable to set the preference"
                    );
    }

    g_free(errmsg);
}

struct sharkd_session_process_dumpconf_data
{
    module_t *module;
};

static unsigned
sharkd_session_process_dumpconf_cb(pref_t *pref, void *d)
{
    struct sharkd_session_process_dumpconf_data *data = (struct sharkd_session_process_dumpconf_data *) d;
    const char *pref_name = prefs_get_name(pref);

    char json_pref_key[512];

    snprintf(json_pref_key, sizeof(json_pref_key), "%s.%s", data->module->name, pref_name);
    sharkd_json_object_open(json_pref_key);

    switch (prefs_get_type(pref))
    {
        case PREF_UINT:
            sharkd_json_value_anyf("u", "%u", prefs_get_uint_value_real(pref, pref_current));
            if (prefs_get_uint_base(pref) != 10)
                sharkd_json_value_anyf("ub", "%u", prefs_get_uint_base(pref));
            break;

        case PREF_BOOL:
            sharkd_json_value_anyf("b", prefs_get_bool_value(pref, pref_current) ? "1" : "0");
            break;

        case PREF_STRING:
        case PREF_SAVE_FILENAME:
        case PREF_OPEN_FILENAME:
        case PREF_DIRNAME:
        case PREF_PASSWORD:
        case PREF_DISSECTOR:
            sharkd_json_value_string("s", prefs_get_string_value(pref, pref_current));
            break;

        case PREF_ENUM:
            {
                const enum_val_t *enums;

                sharkd_json_array_open("e");
                for (enums = prefs_get_enumvals(pref); enums->name; enums++)
                {
                    json_dumper_begin_object(&dumper);

                    sharkd_json_value_anyf("v", "%d", enums->value);

                    if (enums->value == prefs_get_enum_value(pref, pref_current))
                        sharkd_json_value_anyf("s", "1");

                    sharkd_json_value_string("d", enums->description);

                    json_dumper_end_object(&dumper);
                }
                sharkd_json_array_close();
                break;
            }

        case PREF_RANGE:
        case PREF_DECODE_AS_RANGE:
            {
                char *range_str = range_convert_range(NULL, prefs_get_range_value_real(pref, pref_current));
                sharkd_json_value_string("r", range_str);
                wmem_free(NULL, range_str);
                break;
            }

        case PREF_UAT:
            {
                uat_t *uat = prefs_get_uat_value(pref);
                unsigned idx;

                sharkd_json_array_open("t");
                for (idx = 0; idx < uat->raw_data->len; idx++)
                {
                    void *rec = UAT_INDEX_PTR(uat, idx);
                    unsigned colnum;

                    sharkd_json_array_open(NULL);
                    for (colnum = 0; colnum < uat->ncols; colnum++)
                    {
                        char *str = uat_fld_tostr(rec, &(uat->fields[colnum]));

                        sharkd_json_value_string(NULL, str);
                        g_free(str);
                    }

                    sharkd_json_array_close();
                }

                sharkd_json_array_close();
                break;
            }

        case PREF_COLOR:
        case PREF_CUSTOM:
        case PREF_STATIC_TEXT:
        case PREF_OBSOLETE:
            /* TODO */
            break;
    }

#if 0
    sharkd_json_value_string("t", prefs_get_title(pref));
#endif

    sharkd_json_object_close();

    return 0; /* continue */
}

static unsigned
sharkd_session_process_dumpconf_mod_cb(module_t *module, void *d)
{
    struct sharkd_session_process_dumpconf_data *data = (struct sharkd_session_process_dumpconf_data *) d;

    data->module = module;
    prefs_pref_foreach(module, sharkd_session_process_dumpconf_cb, data);

    return 0;
}

/**
 * sharkd_session_process_dumpconf()
 *
 * Process dumpconf request
 *
 * Input:
 *   (o) pref - module, or preference, NULL for all
 *
 * Output object with attributes:
 *   (o) prefs   - object with module preferences
 *                  (m) [KEY] - preference name
 *                  (o) u - preference value (for PREF_UINT)
 *                  (o) ub - preference value suggested base for display (for PREF_UINT) and if different than 10
 *                  (o) b - preference value (only for PREF_BOOL) (1 true, 0 false)
 *                  (o) s - preference value (for PREF_STRING, PREF_SAVE_FILENAME, PREF_OPEN_FILENAME, PREF_DIRNAME, PREF_PASSWORD, PREF_DISSECTOR)
 *                  (o) e - preference possible values (only for PREF_ENUM)
 *                  (o) r - preference value (for PREF_RANGE, PREF_DECODE_AS_RANGE)
 *                  (o) t - preference value (only for PREF_UAT)
 */
static void
sharkd_session_process_dumpconf(char *buf, const jsmntok_t *tokens, int count)
{
    const char *tok_pref = json_find_attr(buf, tokens, count, "pref");
    module_t *pref_mod;
    char *dot_sepa;

    if (!tok_pref)
    {
        struct sharkd_session_process_dumpconf_data data;

        data.module = NULL;

        sharkd_json_result_prologue(rpcid);

        sharkd_json_object_open("prefs");
        prefs_modules_foreach(sharkd_session_process_dumpconf_mod_cb, &data);
        sharkd_json_object_close();

        sharkd_json_result_epilogue();
        return;
    }

    if ((dot_sepa = strchr(tok_pref, '.')))
    {
        pref_t *pref = NULL;

        *dot_sepa = '\0'; /* XXX, C abuse: discarding-const */
        pref_mod = prefs_find_module(tok_pref);
        if (pref_mod)
            pref = prefs_find_preference(pref_mod, dot_sepa + 1);
        *dot_sepa = '.';

        if (pref)
        {
            struct sharkd_session_process_dumpconf_data data;

            data.module = pref_mod;

            sharkd_json_result_prologue(rpcid);

            sharkd_json_object_open("prefs");
            sharkd_session_process_dumpconf_cb(pref, &data);
            sharkd_json_object_close();

            sharkd_json_result_epilogue();
            return;
        }
        else
        {
            sharkd_json_error(
                    rpcid, -9001, NULL,
                    "Invalid pref %s.", tok_pref
                    );
            return;
        }

    }

    pref_mod = prefs_find_module(tok_pref);
    if (pref_mod)
    {
        struct sharkd_session_process_dumpconf_data data;

        data.module = pref_mod;

        sharkd_json_result_prologue(rpcid);

        sharkd_json_object_open("prefs");
        prefs_pref_foreach(pref_mod, sharkd_session_process_dumpconf_cb, &data);
        sharkd_json_object_close();

        sharkd_json_result_epilogue();
    }
    else
    {
        sharkd_json_error(
                rpcid, -9002, NULL,
                "Invalid pref %s.", tok_pref
                );
    }
}

struct sharkd_download_rtp
{
    rtpstream_id_t id;
    GSList *packets;
    double start_time;
};

static void
sharkd_rtp_download_free_items(void *ptr)
{
    rtp_packet_t *rtp_packet = (rtp_packet_t *) ptr;

    g_free(rtp_packet->info);
    g_free(rtp_packet->payload_data);
    g_free(rtp_packet);
}

static void
sharkd_rtp_download_decode(struct sharkd_download_rtp *req)
{
    /* based on RtpAudioStream::decode() 6e29d874f8b5e6ebc59f661a0bb0dab8e56f122a */
    /* TODO, for now only without silence (timing_mode_ = Uninterrupted) */

    static const int sample_bytes_ = sizeof(SAMPLE) / sizeof(char);

    uint32_t audio_out_rate_ = 0;
    struct _GHashTable *decoders_hash_ = rtp_decoder_hash_table_new();
    struct SpeexResamplerState_ *audio_resampler_ = NULL;

    size_t resample_buff_len = 0x1000;
    SAMPLE *resample_buff = (SAMPLE *) g_malloc(resample_buff_len);
    spx_uint32_t cur_in_rate = 0;
    char *write_buff = NULL;
    size_t write_bytes = 0;
    unsigned channels = 0;
    unsigned sample_rate = 0;

    GSList *l;

    for (l = req->packets; l; l = l->next)
    {
        rtp_packet_t *rtp_packet = (rtp_packet_t *) l->data;

        SAMPLE *decode_buff = NULL;
        size_t decoded_bytes;

        decoded_bytes = decode_rtp_packet(rtp_packet, &decode_buff, decoders_hash_, &channels, &sample_rate);
        if (decoded_bytes == 0 || sample_rate == 0)
        {
            /* We didn't decode anything. Clean up and prep for the next packet. */
            g_free(decode_buff);
            continue;
        }

        if (audio_out_rate_ == 0)
        {
            uint32_t tmp32;
            uint16_t tmp16;
            char wav_hdr[44];

            /* First non-zero wins */
            audio_out_rate_ = sample_rate;

            RTP_STREAM_DEBUG("Audio sample rate is %u", audio_out_rate_);

            /* write WAVE header */
            memset(&wav_hdr, 0, sizeof(wav_hdr));
            memcpy(&wav_hdr[0], "RIFF", 4);
            memcpy(&wav_hdr[4], "\xFF\xFF\xFF\xFF", 4); /* XXX, unknown */
            memcpy(&wav_hdr[8], "WAVE", 4);

            memcpy(&wav_hdr[12], "fmt ", 4);
            memcpy(&wav_hdr[16], "\x10\x00\x00\x00", 4); /* PCM */
            memcpy(&wav_hdr[20], "\x01\x00", 2);         /* PCM */
            /* # channels */
            tmp16 = channels;
            memcpy(&wav_hdr[22], &tmp16, 2);
            /* sample rate */
            tmp32 = sample_rate;
            memcpy(&wav_hdr[24], &tmp32, 4);
            /* byte rate */
            tmp32 = sample_rate * channels * sample_bytes_;
            memcpy(&wav_hdr[28], &tmp32, 4);
            /* block align */
            tmp16 = channels * sample_bytes_;
            memcpy(&wav_hdr[32], &tmp16, 2);
            /* bits per sample */
            tmp16 = 8 * sample_bytes_;
            memcpy(&wav_hdr[34], &tmp16, 2);

            memcpy(&wav_hdr[36], "data", 4);
            memcpy(&wav_hdr[40], "\xFF\xFF\xFF\xFF", 4); /* XXX, unknown */

            json_dumper_write_base64(&dumper, wav_hdr, sizeof(wav_hdr));
        }

        // Write samples to our file.
        write_buff = (char *) decode_buff;
        write_bytes = decoded_bytes;

        if (audio_out_rate_ != sample_rate)
        {
            spx_uint32_t in_len, out_len;

            /* Resample the audio to match our previous output rate. */
            if (!audio_resampler_)
            {
                audio_resampler_ = speex_resampler_init(1, sample_rate, audio_out_rate_, 10, NULL);
                speex_resampler_skip_zeros(audio_resampler_);
                RTP_STREAM_DEBUG("Started resampling from %u to (out) %u Hz.", sample_rate, audio_out_rate_);
            }
            else
            {
                spx_uint32_t audio_out_rate;
                speex_resampler_get_rate(audio_resampler_, &cur_in_rate, &audio_out_rate);

                if (sample_rate != cur_in_rate)
                {
                    speex_resampler_set_rate(audio_resampler_, sample_rate, audio_out_rate);
                    RTP_STREAM_DEBUG("Changed input rate from %u to %u Hz. Out is %u.", cur_in_rate, sample_rate, audio_out_rate_);
                }
            }
            in_len = (spx_uint32_t)rtp_packet->info->info_payload_len;
            out_len = (audio_out_rate_ * (spx_uint32_t)rtp_packet->info->info_payload_len / sample_rate) + (audio_out_rate_ % sample_rate != 0);
            if (out_len * sample_bytes_ > resample_buff_len)
            {
                while ((out_len * sample_bytes_ > resample_buff_len))
                    resample_buff_len *= 2;
                resample_buff = (SAMPLE *) g_realloc(resample_buff, resample_buff_len);
            }

            speex_resampler_process_int(audio_resampler_, 0, decode_buff, &in_len, resample_buff, &out_len);
            write_buff = (char *) resample_buff;
            write_bytes = out_len * sample_bytes_;
        }

        /* Write the decoded, possibly-resampled audio */
        json_dumper_write_base64(&dumper, write_buff, write_bytes);

        g_free(decode_buff);
    }

    g_free(resample_buff);
    g_hash_table_destroy(decoders_hash_);
}

static tap_packet_status
sharkd_session_packet_download_tap_rtp_cb(void *tapdata, packet_info *pinfo, epan_dissect_t *edt _U_, const void *data, tap_flags_t flags _U_)
{
    const struct _rtp_info *rtp_info = (const struct _rtp_info *) data;
    struct sharkd_download_rtp *req_rtp = (struct sharkd_download_rtp *) tapdata;

    /* do not consider RTP packets without a setup frame */
    if (rtp_info->info_setup_frame_num == 0)
        return TAP_PACKET_DONT_REDRAW;

    if (rtpstream_id_equal_pinfo_rtp_info(&req_rtp->id, pinfo, rtp_info))
    {
        rtp_packet_t *rtp_packet;

        rtp_packet = g_new0(rtp_packet_t, 1);
        rtp_packet->info = (struct _rtp_info *) g_memdup2(rtp_info, sizeof(struct _rtp_info));

        if (rtp_info->info_all_data_present && rtp_info->info_payload_len != 0)
            rtp_packet->payload_data = (uint8_t *) g_memdup2(&(rtp_info->info_data[rtp_info->info_payload_offset]), rtp_info->info_payload_len);

        if (!req_rtp->packets)
            req_rtp->start_time = nstime_to_sec(&pinfo->abs_ts);

        rtp_packet->frame_num = pinfo->num;
        rtp_packet->arrive_offset = nstime_to_sec(&pinfo->abs_ts) - req_rtp->start_time;

        /* XXX, O(n) optimize */
        req_rtp->packets = g_slist_append(req_rtp->packets, rtp_packet);
    }

    return TAP_PACKET_DONT_REDRAW;
}

static bool
sharkd_session_eo_retap_listener(const char *tap_type) {
    bool ok = true;
    register_eo_t *eo = NULL;
    GString *tap_error = NULL;
    void *tap_data = NULL;
    GFreeFunc tap_free = NULL;

    // get <name> from eo:<name>, get_eo_by_name only needs the name (http etc.)
    eo = get_eo_by_name(tap_type + 3);
    if (!eo)
    {
        ok = false;
        sharkd_json_error(
                rpcid, -11011, NULL,
                "sharkd_session_eo_retap_listener() eo=%s not found", tap_type + 3
        );
    }

    if (ok)
    {
        tap_error = sharkd_session_eo_register_tap_listener(eo, tap_type, NULL, NULL, &tap_data, &tap_free);
        if (tap_error)
        {
            ok = false;
            sharkd_json_error(
                    rpcid, -10002, NULL,
                    "sharkd_session_eo_retap_listener() sharkd_session_eo_register_tap_listener error %s",
                    tap_error->str);
            g_string_free(tap_error, TRUE);
        }
    }

    if (ok)
        sharkd_retap();

    if (!tap_error)
        remove_tap_listener(tap_data);

    if (tap_free)
        tap_free(tap_data);

    return ok;
}

/**
 * sharkd_session_process_download()
 *
 * Process download request
 *
 * Input:
 *   (m) token  - token to download
 *
 * Output object with attributes:
 *   (o) file - suggested name of file
 *   (o) mime - suggested content type
 *   (o) data - payload base64 encoded
 */
static void
sharkd_session_process_download(char *buf, const jsmntok_t *tokens, int count)
{
    const char *tok_token      = json_find_attr(buf, tokens, count, "token");

    if (!tok_token)
    {
        sharkd_json_error(
            rpcid, -10005, NULL,
            "missing token"
        );
        return;
    }

    if (!strncmp(tok_token, "eo:", 3))
    {
        // get eo:<name> from eo:<name>_<row>
        char *tap_type = g_strdup(tok_token);
        char *tmp = strrchr(tap_type, '_');
        if (tmp)
            *tmp = '\0';

        // if eo:<name> not in sharkd_eo_list, retap
        if (!sharkd_eo_object_list_get_entry_by_type(sharkd_eo_list, tap_type) &&
            !sharkd_session_eo_retap_listener(tap_type))
        {
            g_free(tap_type);
            // sharkd_json_error called in sharkd_session_eo_retap_listener
            return;
        }

        g_free(tap_type);

        struct sharkd_export_object_list *object_list;
        const export_object_entry_t *eo_entry = NULL;

        for (object_list = sharkd_eo_list; object_list; object_list = object_list->next)
        {
            size_t eo_type_len = strlen(object_list->type);

            if (!strncmp(tok_token, object_list->type, eo_type_len) && tok_token[eo_type_len] == '_')
            {
                int row;

                if (sscanf(&tok_token[eo_type_len + 1], "%d", &row) != 1)
                    break;

                eo_entry = (export_object_entry_t *) g_slist_nth_data(object_list->entries, row);
                break;
            }
        }

        if (eo_entry)
        {
            const char *mime     = (eo_entry->content_type) ? eo_entry->content_type : "application/octet-stream";
            const char *filename = (eo_entry->filename) ? eo_entry->filename : tok_token;

            sharkd_json_result_prologue(rpcid);
            sharkd_json_value_string("file", filename);
            sharkd_json_value_string("mime", mime);
            sharkd_json_value_base64("data", eo_entry->payload_data, eo_entry->payload_len);
            sharkd_json_result_epilogue();
        }
        else
        {
            sharkd_json_result_prologue(rpcid);
            sharkd_json_result_epilogue();
        }
    }
    else if (!strcmp(tok_token, "ssl-secrets"))
    {
        size_t str_len;
        char *str = ssl_export_sessions(&str_len);

        if (str)
        {
            const char *mime     = "text/plain";
            const char *filename = "keylog.txt";

            sharkd_json_result_prologue(rpcid);
            sharkd_json_value_string("file", filename);
            sharkd_json_value_string("mime", mime);
            sharkd_json_value_base64("data", str, str_len);
            sharkd_json_result_epilogue();
        }
        g_free(str);
    }
    else if (!strncmp(tok_token, "rtp:", 4))
    {
        struct sharkd_download_rtp rtp_req;
        GString *tap_error;

        memset(&rtp_req, 0, sizeof(rtp_req));
        if (!sharkd_rtp_match_init(&rtp_req.id, tok_token + 4))
        {
            sharkd_json_error(
                    rpcid, -10001, NULL,
                    "sharkd_session_process_download() rtp tokenizing error %s", tok_token
                    );
            return;
        }

        tap_error = register_tap_listener("rtp", &rtp_req, NULL, 0, NULL, sharkd_session_packet_download_tap_rtp_cb, NULL, NULL);
        if (tap_error)
        {
            sharkd_json_error(
                    rpcid, -10002, NULL,
                    "sharkd_session_process_download() rtp error %s", tap_error->str
                    );
            g_string_free(tap_error, TRUE);
            return;
        }

        sharkd_retap();
        remove_tap_listener(&rtp_req);

        if (rtp_req.packets)
        {
            const char *mime     = "audio/x-wav";
            const char *filename = tok_token;

            sharkd_json_result_prologue(rpcid);
            sharkd_json_value_string("file", filename);
            sharkd_json_value_string("mime", mime);

            json_dumper_set_member_name(&dumper, "data");
            json_dumper_begin_base64(&dumper);
            sharkd_rtp_download_decode(&rtp_req);
            json_dumper_end_base64(&dumper);

            sharkd_json_result_epilogue();

            g_slist_free_full(rtp_req.packets, sharkd_rtp_download_free_items);
        }
        else
        {
            sharkd_json_error(
                rpcid, -10003, NULL,
                "no rtp data available"
            );
        }
    }
    else
    {
        sharkd_json_error(
            rpcid, -10004, NULL,
            "unrecognized token"
        );
    }
}

static void
sharkd_session_process(char *buf, const jsmntok_t *tokens, int count)
{
    if (json_prep(buf, tokens, count))
    {
        /* don't need [0] token */
        tokens++;
        count--;

        const char* tok_method = json_find_attr(buf, tokens, count, "method");

        if (!tok_method) {
            sharkd_json_error(
                    rpcid, -32601, NULL,
                    "No method found");
            return;
        }
        if (!strcmp(tok_method, "load"))
            sharkd_session_process_load(buf, tokens, count);
        else if (!strcmp(tok_method, "status"))
            sharkd_session_process_status();
        else if (!strcmp(tok_method, "analyse"))
            sharkd_session_process_analyse();
        else if (!strcmp(tok_method, "info"))
            sharkd_session_process_info();
        else if (!strcmp(tok_method, "check"))
            sharkd_session_process_check(buf, tokens, count);
        else if (!strcmp(tok_method, "complete"))
            sharkd_session_process_complete(buf, tokens, count);
        else if (!strcmp(tok_method, "frames"))
            sharkd_session_process_frames(buf, tokens, count);
        else if (!strcmp(tok_method, "tap"))
            sharkd_session_process_tap(buf, tokens, count);
        else if (!strcmp(tok_method, "follow"))
            sharkd_session_process_follow(buf, tokens, count);
        else if (!strcmp(tok_method, "iograph"))
            sharkd_session_process_iograph(buf, tokens, count);
        else if (!strcmp(tok_method, "intervals"))
            sharkd_session_process_intervals(buf, tokens, count);
        else if (!strcmp(tok_method, "frame"))
            sharkd_session_process_frame(buf, tokens, count);
        else if (!strcmp(tok_method, "setcomment"))
            sharkd_session_process_setcomment(buf, tokens, count);
        else if (!strcmp(tok_method, "setconf"))
            sharkd_session_process_setconf(buf, tokens, count);
        else if (!strcmp(tok_method, "dumpconf"))
            sharkd_session_process_dumpconf(buf, tokens, count);
        else if (!strcmp(tok_method, "download"))
            sharkd_session_process_download(buf, tokens, count);
        else if (!strcmp(tok_method, "bye"))
        {
            sharkd_json_simple_ok(rpcid);
            exit(0);
        }
        else
        {
            sharkd_json_error(
                    rpcid, -32601, NULL,
                    "The method \"%s\" is unknown", tok_method
                    );
        }
    }
}

int
sharkd_session_main(int mode_setting)
{
    char buf[8 * 1024];
    jsmntok_t *tokens = NULL;
    int tokens_max = -1;

    mode = mode_setting;

    fprintf(stderr, "Hello in child.\n");

    dumper.output_file = stdout;

    filter_table = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, sharkd_session_filter_free);

#ifdef HAVE_MAXMINDDB
    /* mmdbresolve was stopped before fork(), force starting it */
    uat_get_table_by_name("MaxMind Database Paths")->post_update_cb();
#endif

    set_resolution_synchrony(true);

    while (fgets(buf, sizeof(buf), stdin))
    {
        /* every command is line separated JSON */
        int ret;

        ret = json_parse(buf, NULL, 0);
        if (ret <= 0)
        {
            sharkd_json_error(
                    rpcid, -32600, NULL,
                    "Invalid JSON(1)"
                    );
            continue;
        }

        /* fprintf(stderr, "JSON: %d tokens\n", ret); */
        ret += 1;

        if (tokens == NULL || tokens_max < ret)
        {
            tokens_max = ret;
            tokens = (jsmntok_t *) g_realloc(tokens, sizeof(jsmntok_t) * tokens_max);
        }

        memset(tokens, 0, ret * sizeof(jsmntok_t));

        ret = json_parse(buf, tokens, ret);
        if (ret <= 0)
        {
            sharkd_json_error(
                    rpcid, -32600, NULL,
                    "Invalid JSON(2)"
                    );
            continue;
        }

        host_name_lookup_process();

        sharkd_session_process(buf, tokens, ret);
    }

    g_hash_table_destroy(filter_table);
    g_free(tokens);

    return 0;
}