summaryrefslogtreecommitdiffstats
path: root/epan/wslua/init_wslua.c
blob: 065eaf38972854e4ec1a53bca09b241d2bc12d72 (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
/*
 * init_wslua.c
 *
 * Wireshark's interface to the Lua Programming Language
 *
 * (c) 2006, Luis E. Garcia Ontanon <luis@ontanon.org>
 *
 * Wireshark - Network traffic analyzer
 * By Gerald Combs <gerald@wireshark.org>
 * Copyright 1998 Gerald Combs
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 */

#include "config.h"
#define WS_LOG_DOMAIN LOG_DOMAIN_WSLUA

#include "wslua.h"
#include "init_wslua.h"

#include <errno.h>
#include <stdio.h>
#include <epan/expert.h>
#include <epan/ex-opt.h>
#include <epan/introspection.h>
#include <wiretap/introspection.h>
#include <wsutil/privileges.h>
#include <wsutil/file_util.h>
#include <wsutil/wslog.h>
#include <wsutil/array.h>

/* linked list of Lua plugins */
typedef struct _wslua_plugin {
    char       *name;            /**< plugin name */
    char       *version;         /**< plugin version */
    char       *filename;        /**< plugin filename */
    struct _wslua_plugin *next;
} wslua_plugin;

static wslua_plugin *wslua_plugin_list;

static lua_State* L;

static void (*wslua_gui_print_func_ptr)(const char *, void *);
static void *wslua_gui_print_data_ptr;
static int wslua_lua_print_func_ref = LUA_NOREF;

/* XXX: global variables? Really?? Yuck. These could be done differently,
   using the Lua registry */
packet_info* lua_pinfo;
struct _wslua_treeitem* lua_tree;
tvbuff_t* lua_tvb;
int lua_dissectors_table_ref = LUA_NOREF;
int lua_heur_dissectors_table_ref = LUA_NOREF;

static int proto_lua;

static int hf_wslua_fake;
static int hf_wslua_text;

static expert_field ei_lua_error;

static expert_field ei_lua_proto_checksum_comment;
static expert_field ei_lua_proto_checksum_chat;
static expert_field ei_lua_proto_checksum_note;
static expert_field ei_lua_proto_checksum_warn;
static expert_field ei_lua_proto_checksum_error;

static expert_field ei_lua_proto_sequence_comment;
static expert_field ei_lua_proto_sequence_chat;
static expert_field ei_lua_proto_sequence_note;
static expert_field ei_lua_proto_sequence_warn;
static expert_field ei_lua_proto_sequence_error;

static expert_field ei_lua_proto_response_comment;
static expert_field ei_lua_proto_response_chat;
static expert_field ei_lua_proto_response_note;
static expert_field ei_lua_proto_response_warn;
static expert_field ei_lua_proto_response_error;

static expert_field ei_lua_proto_request_comment;
static expert_field ei_lua_proto_request_chat;
static expert_field ei_lua_proto_request_note;
static expert_field ei_lua_proto_request_warn;
static expert_field ei_lua_proto_request_error;

static expert_field ei_lua_proto_undecoded_comment;
static expert_field ei_lua_proto_undecoded_chat;
static expert_field ei_lua_proto_undecoded_note;
static expert_field ei_lua_proto_undecoded_warn;
static expert_field ei_lua_proto_undecoded_error;

static expert_field ei_lua_proto_reassemble_comment;
static expert_field ei_lua_proto_reassemble_chat;
static expert_field ei_lua_proto_reassemble_note;
static expert_field ei_lua_proto_reassemble_warn;
static expert_field ei_lua_proto_reassemble_error;

static expert_field ei_lua_proto_malformed_comment;
static expert_field ei_lua_proto_malformed_chat;
static expert_field ei_lua_proto_malformed_note;
static expert_field ei_lua_proto_malformed_warn;
static expert_field ei_lua_proto_malformed_error;

static expert_field ei_lua_proto_debug_comment;
static expert_field ei_lua_proto_debug_chat;
static expert_field ei_lua_proto_debug_note;
static expert_field ei_lua_proto_debug_warn;
static expert_field ei_lua_proto_debug_error;

static expert_field ei_lua_proto_protocol_comment;
static expert_field ei_lua_proto_protocol_chat;
static expert_field ei_lua_proto_protocol_note;
static expert_field ei_lua_proto_protocol_warn;
static expert_field ei_lua_proto_protocol_error;

static expert_field ei_lua_proto_security_comment;
static expert_field ei_lua_proto_security_chat;
static expert_field ei_lua_proto_security_note;
static expert_field ei_lua_proto_security_warn;
static expert_field ei_lua_proto_security_error;

static expert_field ei_lua_proto_comments_comment;
static expert_field ei_lua_proto_comments_chat;
static expert_field ei_lua_proto_comments_note;
static expert_field ei_lua_proto_comments_warn;
static expert_field ei_lua_proto_comments_error;

static expert_field ei_lua_proto_decryption_comment;
static expert_field ei_lua_proto_decryption_chat;
static expert_field ei_lua_proto_decryption_note;
static expert_field ei_lua_proto_decryption_warn;
static expert_field ei_lua_proto_decryption_error;

static expert_field ei_lua_proto_assumption_comment;
static expert_field ei_lua_proto_assumption_chat;
static expert_field ei_lua_proto_assumption_note;
static expert_field ei_lua_proto_assumption_warn;
static expert_field ei_lua_proto_assumption_error;

static expert_field ei_lua_proto_deprecated_comment;
static expert_field ei_lua_proto_deprecated_chat;
static expert_field ei_lua_proto_deprecated_note;
static expert_field ei_lua_proto_deprecated_warn;
static expert_field ei_lua_proto_deprecated_error;

static expert_field ei_lua_proto_receive_comment;
static expert_field ei_lua_proto_receive_chat;
static expert_field ei_lua_proto_receive_note;
static expert_field ei_lua_proto_receive_warn;
static expert_field ei_lua_proto_receive_error;

static expert_field ei_lua_proto_interface_comment;
static expert_field ei_lua_proto_interface_chat;
static expert_field ei_lua_proto_interface_note;
static expert_field ei_lua_proto_interface_warn;
static expert_field ei_lua_proto_interface_error;

static int ett_wslua_traceback;

static bool
lua_pinfo_end(wmem_allocator_t *allocator _U_, wmem_cb_event_t event _U_,
        void *user_data _U_)
{
    clear_outstanding_Tvb();
    clear_outstanding_TvbRange();
    clear_outstanding_Pinfo();
    clear_outstanding_Column();
    clear_outstanding_Columns();
    clear_outstanding_PrivateTable();
    clear_outstanding_TreeItem();
    clear_outstanding_FieldInfo();
    clear_outstanding_FuncSavers();

    /* keep invoking this callback later? */
    return false;
}

static int wslua_not_register_menu(lua_State* LS) {
    luaL_error(LS,"too late to register a menu");
    return 0;
}

/* a getter for wslua_tree.c's TreeItem_add_item_any() to use */
int get_hf_wslua_text(void) {
    return hf_wslua_text;
}


// Attach the lua traceback to the proto_tree
static int dissector_error_handler(lua_State *LS) {
    // Entering, stack: [ error_handler, dissector, errmsg ]

    proto_item *tb_item;
    proto_tree *tb_tree;

    // Add the expert info Lua error message
    proto_tree_add_expert_format(lua_tree->tree, lua_pinfo, &ei_lua_error, lua_tvb, 0, 0,
            "Lua Error: %s", lua_tostring(LS,-1));

    // Create a new proto sub_tree for the traceback
    tb_item = proto_tree_add_text_internal(lua_tree->tree, lua_tvb, 0, 0, "Lua Traceback");
    tb_tree = proto_item_add_subtree(tb_item, ett_wslua_traceback);

    // Push the traceback onto the stack
    // After call, stack: [ error_handler, dissector, errmsg, tb_string ]
    luaL_traceback(LS, LS, NULL, 1);

    // Get the string length of the traceback. Note that the string
    // has a terminating NUL, but string_length doesn't include it.
    // The lua docs say the string can have NULs in it too, but we
    // ignore that because the traceback string shouldn't have them.
    // This function does not own the string; it's still owned by lua.
    size_t string_length;
    const char *orig_tb_string = lua_tolstring(LS, -1, &string_length);

    // We make the copy so we can modify the string. Don't forget the
    // extra byte for the terminating NUL!
    char *tb_string = (char*) g_memdup2(orig_tb_string, string_length+1);

    // The string has tabs and new lines in it
    // We will add proto_items for each new-line-delimited sub-string.
    // We also convert tabs to spaces, because the Wireshark GUI
    // shows tabs literally as "\t".

    // 'beginning' is the beginning of the sub-string
    char *beginning = tb_string;

    // 'p' is the pointer to the byte as we iterate over the string
    char *p = tb_string;

    size_t i;
    bool skip_initial_tabs = true;
    size_t last_eol_i = 0;
    for (i = 0 ; i < string_length ; i++) {
        // At the beginning of a sub-string, we will convert tabs to spaces
        if (skip_initial_tabs) {
            if (*p == '\t') {
                *p = ' ';
            } else {
                // Once we hit the first non-tab character in a substring,
                // we won't convert tabs (until the next substring)
                skip_initial_tabs = false;
            }
        }
        // If we see a newline, we add the substring to the proto tree
        if (*p == '\n') {
            // Terminate the string.
            *p = '\0';
            proto_tree_add_text_internal(tb_tree, lua_tvb, 0, 0, "%s", beginning);
            beginning = ++p;
            skip_initial_tabs = true;
            last_eol_i = i;
        } else {
            ++p;
        }
    }

    // The last portion of the string doesn't have a newline, so add it here
    // after the loop. But to be sure, check that we didn't just add it, in
    // case lua decides to change it in the future.
    if ( last_eol_i < i-1 ) {
        proto_tree_add_text_internal(tb_tree, lua_tvb, 0, 0, "%s", beginning);
    }

    // Cleanup
    g_free(tb_string);

    // Return the same original error message
    return -2;
}


int dissect_lua(tvbuff_t* tvb, packet_info* pinfo, proto_tree* tree, void* data _U_) {
    int consumed_bytes = tvb_captured_length(tvb);
    tvbuff_t *saved_lua_tvb = lua_tvb;
    packet_info *saved_lua_pinfo = lua_pinfo;
    struct _wslua_treeitem *saved_lua_tree = lua_tree;
    lua_pinfo = pinfo;
    lua_tvb = tvb;

    /*
     * almost equivalent to Lua:
     * dissectors[current_proto](tvb,pinfo,tree)
     */

    // set the stack top be index 0
    lua_settop(L,0);

    // After call, stack: [ error_handler_func ]
    lua_pushcfunction(L, dissector_error_handler);

    // Push the dissectors table onto the the stack
    // After call, stack: [ error_handler_func, dissectors_table ]
    lua_rawgeti(L, LUA_REGISTRYINDEX, lua_dissectors_table_ref);

    // Push a copy of the current_proto string onto the stack
    // After call, stack: [ error_handler_func, dissectors_table, current_proto ]
    lua_pushstring(L, pinfo->current_proto);

    // dissectors_table[current_proto], a dissector, goes into the stack
    // The key (current_proto) is popped off the stack.
    // After call, stack: [ error_handler_func, dissectors_table, dissector ]
    lua_gettable(L, -2);

    // We don't need the dissectors_table in the stack
    // After call, stack: [ error_handler_func, dissector ]
    lua_remove(L,2);

    // Is the dissector a function?
    if (lua_isfunction(L,2)) {

        // After call, stack: [ error_handler_func, dissector, tvb ]
        push_Tvb(L,tvb);
        // After call, stack: [ error_handler_func, dissector, tvb, pinfo ]
        push_Pinfo(L,pinfo);
        // After call, stack: [ error_handler_func, dissector, tvb, pinfo, TreeItem ]
        lua_tree = push_TreeItem(L, tree, proto_tree_add_item(tree, hf_wslua_fake, tvb, 0, 0, ENC_NA));
        proto_item_set_hidden(lua_tree->item);

        if  ( lua_pcall(L, /*num_args=*/3, /*num_results=*/1, /*error_handler_func_stack_position=*/1) ) {
            // do nothing; the traceback error message handler function does everything
        } else {

            /* if the Lua dissector reported the consumed bytes, pass it to our caller */
            if (lua_isnumber(L, -1)) {
                /* we got the consumed bytes or the missing bytes as a negative number */
                consumed_bytes = wslua_toint(L, -1);
                lua_pop(L, 1);
            }
        }

    } else {
        proto_tree_add_expert_format(tree, pinfo, &ei_lua_error, tvb, 0, 0,
                    "Lua Error: did not find the %s dissector in the dissectors table", pinfo->current_proto);
    }

    wmem_register_callback(pinfo->pool, lua_pinfo_end, NULL);

    lua_pinfo = saved_lua_pinfo;
    lua_tree = saved_lua_tree;
    lua_tvb = saved_lua_tvb;

    return consumed_bytes;

}

/** Type of a heuristic dissector, used in heur_dissector_add().
 *
 * @param tvb the tvbuff with the (remaining) packet data
 * @param pinfo the packet info of this packet (additional info)
 * @param tree the protocol tree to be build or NULL
 * @return true if the packet was recognized by the sub-dissector (stop dissection here)
 */
bool heur_dissect_lua(tvbuff_t* tvb, packet_info* pinfo, proto_tree* tree, void* data _U_) {
    bool result = false;
    tvbuff_t *saved_lua_tvb = lua_tvb;
    packet_info *saved_lua_pinfo = lua_pinfo;
    struct _wslua_treeitem *saved_lua_tree = lua_tree;
    lua_tvb = tvb;
    lua_pinfo = pinfo;

    ws_assert(tvb && pinfo);

    if (!pinfo->heur_list_name || !pinfo->current_proto) {
        proto_tree_add_expert_format(tree, pinfo, &ei_lua_error, tvb, 0, 0,
                "internal error in heur_dissect_lua: NULL list name or current proto");
        return false;
    }

    /* heuristic functions are stored in a table in the registry; the registry has a
     * table at reference lua_heur_dissectors_table_ref, and that table has keys for
     * the heuristic listname (e.g., "udp", "tcp", etc.), and that key's value is a
     * table of keys of the Proto->name, and their value is the function.
     * So it's like registry[table_ref][heur_list_name][proto_name] = func
     */

    lua_settop(L,0);

    /* get the table of all lua heuristic dissector lists */
    lua_rawgeti(L, LUA_REGISTRYINDEX, lua_heur_dissectors_table_ref);

    /* get the table inside that, for the lua heuristic dissectors of the requested heur list */
    if (!wslua_get_table(L, -1, pinfo->heur_list_name)) {
        /* this shouldn't happen */
        lua_settop(L,0);
        proto_tree_add_expert_format(tree, pinfo, &ei_lua_error, tvb, 0, 0,
                "internal error in heur_dissect_lua: no %s heur list table", pinfo->heur_list_name);
        return false;
    }

    /* get the table inside that, for the specific lua heuristic dissector */
    if (!wslua_get_field(L,-1,pinfo->current_proto)) {
        /* this shouldn't happen */
        lua_settop(L,0);
        proto_tree_add_expert_format(tree, pinfo, &ei_lua_error, tvb, 0, 0,
                "internal error in heur_dissect_lua: no %s heuristic dissector for list %s",
                        pinfo->current_proto, pinfo->heur_list_name);
        return false;
    }

    /* remove the table of all lists (the one in the registry) */
    lua_remove(L,1);
    /* remove the heur_list_name heur list table */
    lua_remove(L,1);

    if (!lua_isfunction(L,-1)) {
        /* this shouldn't happen */
        lua_settop(L,0);
        proto_tree_add_expert_format(tree, pinfo, &ei_lua_error, tvb, 0, 0,
                "internal error in heur_dissect_lua: %s heuristic dissector is not a function", pinfo->current_proto);
        return false;
    }

    push_Tvb(L,tvb);
    push_Pinfo(L,pinfo);
    lua_tree = push_TreeItem(L, tree, proto_tree_add_item(tree, hf_wslua_fake, tvb, 0, 0, ENC_NA));
    proto_item_set_hidden(lua_tree->item);

    if  ( lua_pcall(L,3,1,0) ) {
        proto_tree_add_expert_format(tree, pinfo, &ei_lua_error, tvb, 0, 0,
                "Lua Error: error calling %s heuristic dissector: %s", pinfo->current_proto, lua_tostring(L,-1));
        lua_settop(L,0);
    } else {
        if (lua_isboolean(L, -1) || lua_isnil(L, -1)) {
            result = lua_toboolean(L, -1);
        } else if (lua_type(L, -1) == LUA_TNUMBER) {
            result = lua_tointeger(L,-1) != 0 ? true : false;
        } else {
            proto_tree_add_expert_format(tree, pinfo, &ei_lua_error, tvb, 0, 0,
                    "Lua Error: invalid return value from Lua %s heuristic dissector", pinfo->current_proto);
        }
        lua_pop(L, 1);
    }

    wmem_register_callback(pinfo->pool, lua_pinfo_end, NULL);

    lua_pinfo = saved_lua_pinfo;
    lua_tree = saved_lua_tree;
    lua_tvb = saved_lua_tvb;

    return result;
}

static void iter_table_and_call(lua_State* LS, const char* table_name, lua_CFunction error_handler) {
    lua_settop(LS,0);

    lua_pushcfunction(LS,error_handler);
    lua_getglobal(LS, table_name);

    if (!lua_istable(LS, 2)) {
        report_failure("Lua: either `%s' does not exist or it is not a table!\n",table_name);
        lua_close(LS);
        L = NULL;
        return;
    }

    lua_pushnil(LS);

    while (lua_next(LS, 2)) {
        const char* name = lua_tostring(L,-2);

        if (lua_isfunction(LS,-1)) {

            if ( lua_pcall(LS,0,0,1) ) {
                    lua_pop(LS,1);
            }

        } else {
            report_failure("Lua: Something not a function got its way into the %s.%s",table_name,name);
            lua_close(LS);
            L = NULL;
            return;
        }
    }

    lua_settop(LS,0);
}


static int init_error_handler(lua_State* LS) {
    const char* error =  lua_tostring(LS,1);
    report_failure("Lua: Error during execution of initialization:\n %s",error);
    return 0;
}


static bool init_routine_initialized;
static void wslua_init_routine(void) {

    if ( ! init_routine_initialized ) {
        /*
         * This must be done only once during the entire life of
         * tshark/wireshark, because it must be done only once per the life of
         * the Lua state/engine, so we guard this with the boolean above;
         * otherwise it would occur every time a file is opened (every time
         * epan_new() is called).
         *
         * If we ever allow the Lua state to be restarted, or to have multiple
         * Lua states, we'll need to change this.
         */
        lua_prime_all_fields(NULL);
        init_routine_initialized = true;
    }

    if (L) {
        iter_table_and_call(L, WSLUA_INIT_ROUTINES,init_error_handler);
    }

}

static void wslua_cleanup_routine(void) {
    if (L) {
        iter_table_and_call(L, WSLUA_INIT_ROUTINES,init_error_handler);
    }
}

static int prefs_changed_error_handler(lua_State* LS) {
    const char* error =  lua_tostring(LS,1);
    report_failure("Lua: Error during execution of prefs apply callback:\n %s",error);
    return 0;
}

void wslua_prefs_changed(void) {
    if (L) {
        iter_table_and_call(L, WSLUA_PREFS_CHANGED,prefs_changed_error_handler);
    }
}

static const char *getF(lua_State *LS _U_, void *ud, size_t *size)
{
    FILE *f=(FILE *)ud;
    static char buff[512];
    if (feof(f)) return NULL;
    *size=fread(buff,1,sizeof(buff),f);
    return (*size>0) ? buff : NULL;
}

static int error_handler_with_callback(lua_State *LS) {
    const char *msg = lua_tostring(LS, 1);
    luaL_traceback(LS, LS, msg, 1);     /* push message with traceback.  */
    lua_remove(LS, -2);                 /* remove original msg */
    return 1;
}

static void wslua_add_plugin(const char *name, const char *version, const char *filename)
{
    wslua_plugin *new_plug, *lua_plug;

    lua_plug = wslua_plugin_list;
    new_plug = g_new(wslua_plugin, 1);

    if (!lua_plug) { /* the list is empty */
        wslua_plugin_list = new_plug;
    } else {
        while (lua_plug->next != NULL) {
            lua_plug = lua_plug->next;
        }
        lua_plug->next = new_plug;
    }

    new_plug->name = g_strdup(name);
    new_plug->version = g_strdup(version);
    new_plug->filename = g_strdup(filename);
    new_plug->next = NULL;
}

static void wslua_clear_plugin_list(void)
{
    wslua_plugin *lua_plug;

    while (wslua_plugin_list) {
        lua_plug = wslua_plugin_list;
        wslua_plugin_list = wslua_plugin_list->next;
        g_free (lua_plug->name);
        g_free (lua_plug->version);
        g_free (lua_plug->filename);
        g_free (lua_plug);
    }
}

static int lua_script_push_args(const int script_num) {
    char* argname = ws_strdup_printf("lua_script%d", script_num);
    const char* argvalue = NULL;
    int i, count = ex_opt_count(argname);

    for (i = 0; i < count; i++) {
        argvalue = ex_opt_get_nth(argname, i);
        lua_pushstring(L,argvalue);
    }

    g_free(argname);
    return count;
}

/* Prepends a path to the global package path (used by require)
 * We could add a custom loader to package.searchers instead, which
 * might be more useful in some way. We could also have some method of
 * saving and restoring the path, instead of constantly adding to it. */
static void prepend_path(const char* dirname) {
    const char* path;

    /* prepend the directory name to _G.package.path */
    lua_getglobal(L, "package"); /* get the package table from the global table */
    lua_getfield(L, -1, "path");    /* get the path field from the package table */
    path = luaL_checkstring(L, -1); /* get the path string */
    lua_pop(L, 1);                  /* pop the path string */
    /* prepend the path */
    /* We could also add "?/init.lua" for packages. */
    lua_pushfstring(L, "%s" G_DIR_SEPARATOR_S "?.lua;%s",
                    dirname, path);
    lua_setfield(L, -2, "path");
    lua_pop(L, 1);
}

#define FILE_NAME_KEY "__FILE__"
#define DIR_NAME_KEY "__DIR__"
#define DIR_SEP_NAME_KEY "__DIR_SEPARATOR__"
/* assumes a loaded chunk's function is on top of stack */
static void set_file_environment(const char* filename, const char* dirname) {
    lua_newtable(L); /* environment for script (index 3) */

    /* XXX - Do we need this? A script can get the filename and path from
     * debug.getinfo/lua_Debug source */
    lua_pushstring(L, filename); /* tell the script about its filename */
    lua_setfield(L, -2, FILE_NAME_KEY); /* make it accessible at __FILE__ */

    lua_pushstring(L, dirname); /* tell the script about its dirname */
    lua_setfield(L, -2, DIR_NAME_KEY); /* make it accessible at __DIR__ */

    /* XXX - Do we need this? package.config:sub(1,1) is the directory separator */
    lua_pushstring(L, G_DIR_SEPARATOR_S); /* tell the script the directory separator */
    lua_setfield(L, -2, DIR_SEP_NAME_KEY); /* make it accessible at __DIR_SEPARATOR__ */

    lua_newtable(L); /* new metatable */

    lua_pushglobaltable(L);

    lua_setfield(L, -2, "__index"); /* make metatable's __index point to global table */

    lua_setmetatable(L, -2); /* pop metatable, set it as metatable of environment */

    lua_setupvalue(L, -2, 1); /* pop environment and assign it to upvalue 1 */

    /* The result of this is a new environment that falls back to reading from
     * the global environment for any entry not in the new environment, but
     * can't change the global environment while running.
     *
     * Unfortunately, while we could create a file-local package.path, it
     * wouldn't have any effect on the path actually used by requires, since
     * the requires function has as an upvalue the original package table;
     * we can't change the behavior of requires without changing it for
     * the global environment and for all scripts.
     *
     * For some of the same reasons, if the script itself calls require(),
     * that actually affects the original global environment too, so this
     * sandboxing doesn't completely work to keep the global environment
     * unchanged. Is it worth it?
     */
}

/* This loads plugins like Lua modules / libraries, using require().
 * It has the advantage that loaded files get add to the package.loaded
 * table, so files aren't run again by require() either.
 */
static bool lua_load_plugin(const char* filename) {
    int status;
    char *trimmed;

    const char *basename = get_basename(filename);
    char *dot = strrchr(basename, '.');
    if (dot) {
        trimmed = g_strndup(basename, dot - basename);
    } else {
        trimmed = g_strdup(basename);
    }

    lua_settop(L, 0);

    lua_pushcfunction(L, error_handler_with_callback);

    lua_getglobal(L, "require");

    lua_pushstring(L, trimmed);
    g_free(trimmed);

    /* Ignore the return from "require" by passing 0 as nresults to lua_pcall
     * (we could add it to the global table using the name as dolibrary() does,
     * but that is deprecated style in modern Lua.)
     */
    status = lua_pcall(L, 1, 0, 1);
    if (status != LUA_OK) {
        switch (status) {
            case LUA_ERRRUN:
                report_failure("Lua: Error during loading:\n%s", lua_tostring(L, -1));
                break;
            case LUA_ERRMEM:
                report_failure("Lua: Error during loading: out of memory");
                break;
            case LUA_ERRERR:
                report_failure("Lua: Error during loading: error while retrieving error message");
                break;
            default:
                report_failure("Lua: Error during loading: unknown error %d", status);
                break;
        }
    }
    return status == LUA_OK;
}

/* If file_count > 0 then it's a command-line-added user script, and the count
 * represents which user script it is (first=1, second=2, etc.).
 * If dirname != NULL, then it's a user script and the dirname will get put in a file environment
 * If dirname == NULL then it's a wireshark script and no file environment is created
 */
static bool lua_load_script(const char* filename, const char* dirname, const int file_count) {
    FILE* file;
    int error;
    int numargs = 0;

    if (! ( file = ws_fopen(filename,"r")) ) {
        report_open_failure(filename,errno,false);
        return false;
    }

    lua_settop(L,0);

    lua_pushcfunction(L, error_handler_with_callback);
    /* The source argument should start with '@' to indicate a file. */
    lua_pushfstring(L, "@%s", filename);

    error = lua_load(L, getF, file, lua_tostring(L, -1), NULL);

    switch (error) {
        case 0: /* LUA_OK */
            if (dirname) {
                set_file_environment(filename, dirname);
            }
            if (file_count > 0) {
                numargs = lua_script_push_args(file_count);
            }
            error = lua_pcall(L, numargs, 0, 1);
            if (error) {
                switch (error) {
                    case LUA_ERRRUN:
                        report_failure("Lua: Error during loading:\n%s", lua_tostring(L, -1));
                        break;
                    case LUA_ERRMEM:
                        report_failure("Lua: Error during loading: out of memory");
                        break;
                    case LUA_ERRERR:
                        report_failure("Lua: Error during loading: error while retrieving error message");
                        break;
                    default:
                        report_failure("Lua: Error during loading: unknown error %d", error);
                        break;
                }
            }
            break;

        case LUA_ERRSYNTAX:
            report_failure("Lua: syntax error: %s", lua_tostring(L, -1));
            break;

        case LUA_ERRMEM:
            report_failure("Lua: memory allocation error during precompilation of %s", filename);
            break;

        default:
            report_failure("Lua: unknown error during precompilation of %s: %d", filename, error);
            break;
    }
    fclose(file);
    lua_pop(L, 2);  /* pop the filename and error handler */
    return error == 0;
}

/* This one is used to load the init.lua scripts, or anything else
 * that shouldn't really be considered a real plugin.
 */
static bool lua_load_internal_script(const char* filename) {
    return lua_load_script(filename, NULL, 0);
}

/* This one is used to load plugins from the plugin directories,
 *   or scripts from the command line. The latter have file_count > 0.
 */
static bool lua_load_plugin_script(const char* name,
                                   const char* filename,
                                   const char* dirname,
                                   const int file_count)
{
    ws_debug("Loading lua script: %s", filename);
    if (file_count > 0 ? lua_load_script(filename, dirname, file_count) :
                         lua_load_plugin(filename)) {
        wslua_add_plugin(name, get_current_plugin_version(), filename);
        clear_current_plugin_version();
        return true;
    }
    return false;
}

static int wslua_panic(lua_State* LS) {
    ws_error("LUA PANIC: %s",lua_tostring(LS,-1));
    /** ws_error() does an abort() and thus never returns **/
    return 0; /* keep gcc happy */
}

static int string_compare(const void *a, const void *b) {
    return strcmp((const char*)a, (const char*)b);
}

static int lua_load_plugins(const char *dirname, register_cb cb, void *client_data,
                            bool count_only, const bool is_user, GHashTable *loaded_files,
                            int depth)
{
    WS_DIR        *dir;             /* scanned directory */
    WS_DIRENT     *file;            /* current file */
    char          *filename, *dot;
    const char    *name;
    int            plugins_counter = 0;
    GList         *sorted_dirnames = NULL;
    GList         *sorted_filenames = NULL;
    GList         *l = NULL;

    if ((dir = ws_dir_open(dirname, 0, NULL)) != NULL) {
        while ((file = ws_dir_read_name(dir)) != NULL) {
            name = ws_dir_get_name(file);

            if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
                /* skip "." and ".." */
                continue;
            }
            if (depth == 0 && strcmp(name, "init.lua") == 0) {
                /* If we are in the root directory skip the special "init.lua"
                 * file that was already loaded before every other user script.
                 * (If we are below the root script directory we just treat it like any other
                 * lua script.) */
                continue;
            }

            filename = ws_strdup_printf("%s" G_DIR_SEPARATOR_S "%s", dirname, name);
            if (test_for_directory(filename) == EISDIR) {
                sorted_dirnames = g_list_prepend(sorted_dirnames, (void *)filename);
                continue;
            }

            /* skip files starting with . */
            if (name[0] == '.') {
                g_free(filename);
                continue;
            }

            /* skip anything but files with .lua suffix */
            dot = strrchr(name, '.');
            if (dot == NULL || g_ascii_strcasecmp(dot+1, "lua") != 0) {
                g_free(filename);
                continue;
            }

            if (file_exists(filename)) {
                sorted_filenames = g_list_prepend(sorted_filenames, (void *)filename);
            }
            else {
                g_free(filename);
            }
        }
        ws_dir_close(dir);
    }

    /* Depth first; ie, process subdirectories (in ASCIIbetical order) before files */
    if (sorted_dirnames != NULL) {
        sorted_dirnames = g_list_sort(sorted_dirnames, string_compare);
        for (l = sorted_dirnames; l != NULL; l = l->next) {
            plugins_counter += lua_load_plugins((const char *)l->data, cb, client_data, count_only, is_user, loaded_files, depth + 1);
        }
        g_list_free_full(sorted_dirnames, g_free);
    }

    /* Process files in ASCIIbetical order */
    if (sorted_filenames != NULL) {
        /* If this is not the root of the plugin directory, add it to the path.
         * XXX - Should we remove it after we're done with this directory? */
        if (depth > 0) {
            prepend_path(dirname);
        }
        sorted_filenames = g_list_sort(sorted_filenames, string_compare);
        for (l = sorted_filenames; l != NULL; l = l->next) {
            filename = (char *)l->data;
            name = strrchr(filename, G_DIR_SEPARATOR) + 1;

            /* Check if we have already loaded this file name, if provided with a set */
            if (loaded_files && g_hash_table_lookup_extended(loaded_files, name, NULL, NULL)) {
                continue;
            }

            if (!count_only) {
                if (cb)
                    (*cb)(RA_LUA_PLUGINS, name, client_data);
                lua_load_plugin_script(name, filename, is_user ? dirname : NULL, 0);

                if (loaded_files) {
                    g_hash_table_insert(loaded_files, g_strdup(name), NULL);
                }
            }
            plugins_counter++;
        }
        g_list_free_full(sorted_filenames, g_free);
    }

    return plugins_counter;
}

static int lua_load_global_plugins(register_cb cb, void *client_data,
                                    bool count_only)
{
    return lua_load_plugins(get_plugins_dir(), cb, client_data, count_only, false, NULL, 0);
}

static int lua_load_pers_plugins(register_cb cb, void *client_data,
                                    bool count_only)
{
    int plugins_counter = 0;

    /* aux table (set) to make sure we only load each file once (by name) */
    /* XXX - This doesn't prevent users from loading a file a second time
     * via a different method, e.g., require() or dofile().
     *
     * It shouldn't be needed now that we're calling require for the plugins.
     */
    GHashTable *loaded_user_scripts = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);

    /* load user scripts */
    plugins_counter += lua_load_plugins(get_plugins_pers_dir(), cb, client_data, count_only, true, loaded_user_scripts, 0);

    /* for backward compatibility check old plugin directory */
    char *old_path = get_persconffile_path("plugins", false);
    if (strcmp(get_plugins_pers_dir(), old_path) != 0) {
        plugins_counter += lua_load_plugins(old_path, cb, client_data, count_only, true, loaded_user_scripts, 0);
    }
    g_free(old_path);

    g_hash_table_destroy(loaded_user_scripts);

    return plugins_counter;
}

int wslua_count_plugins(void) {
    int plugins_counter;

    /* count global scripts */
    plugins_counter = lua_load_global_plugins(NULL, NULL, true);

    /* count user scripts */
    plugins_counter += lua_load_pers_plugins(NULL, NULL, true);

    /* count scripts from command line */
    plugins_counter += ex_opt_count("lua_script");

    return plugins_counter;
}

void wslua_plugins_get_descriptions(wslua_plugin_description_callback callback, void *user_data) {
    wslua_plugin  *lua_plug;

    for (lua_plug = wslua_plugin_list; lua_plug != NULL; lua_plug = lua_plug->next)
    {
        callback(lua_plug->name, lua_plug->version, wslua_plugin_type_name(),
                 lua_plug->filename, user_data);
    }
}

static void
print_wslua_plugin_description(const char *name, const char *version,
                               const char *description, const char *filename,
                               void *user_data _U_)
{
    printf("%s\t%s\t%s\t%s\n", name, version, description, filename);
}

void
wslua_plugins_dump_all(void)
{
    wslua_plugins_get_descriptions(print_wslua_plugin_description, NULL);
}

const char *wslua_plugin_type_name(void) {
    return "lua script";
}

static ei_register_info* ws_lua_ei;
static int ws_lua_ei_len;

expert_field*
wslua_get_expert_field(const int group, const int severity)
{
    int i;
    const ei_register_info *ei = ws_lua_ei;

    ws_assert(ei);

    for (i=0; i < ws_lua_ei_len; i++, ei++) {
        if (ei->eiinfo.group == group && ei->eiinfo.severity == severity)
            return ei->ids;
    }

    return &ei_lua_error;
}

static void *
wslua_allocf(void *ud _U_, void *ptr, size_t osize _U_, size_t nsize)
{
    /* g_realloc frees ptr if nsize==0 and returns NULL (as desired).
     * Furthermore it simplifies error handling by aborting on OOM */
    return g_realloc(ptr, nsize);
}

#define WSLUA_EPAN_ENUMS_TABLE  "_EPAN"
#define WSLUA_WTAP_ENUMS_TABLE  "_WTAP"

#define WSLUA_BASE_TABLE        "base"
#define WSLUA_FTYPE_TABLE       "ftypes"
#define WSLUA_FRAMETYPE_TABLE   "frametype"
#define WSLUA_EXPERT_TABLE      "expert"
#define WSLUA_EXPERT_GROUP_TABLE    "group"
#define WSLUA_EXPERT_SEVERITY_TABLE "severity"
#define WSLUA_WTAP_ENCAPS_TABLE     "wtap_encaps"
#define WSLUA_WTAP_TSPREC_TABLE     "wtap_tsprecs"
#define WSLUA_WTAP_COMMENTS_TABLE   "wtap_comments"
#define WSLUA_WTAP_RECTYPES_TABLE   "wtap_rec_types"
#define WSLUA_WTAP_PRESENCE_FLAGS_TABLE "wtap_presence_flags"

static void
add_table_symbol(const char *table, const char *name, int value)
{
    /* Get table from the global environment. */
    lua_getglobal(L, table);
    /* Set symbol in table. */
    lua_pushstring(L, name);
    lua_pushinteger(L, value);
    lua_settable(L, -3);
    /* Pop table from stack. */
    lua_pop(L, 1);
}

static void
add_global_symbol(const char *name, int value)
{
    /* Set symbol in global environment. */
    lua_pushinteger(L, value);
    lua_setglobal(L, name);
}

static void
add_pi_severity_symbol(const char *name, int value)
{
    lua_getglobal(L, WSLUA_EXPERT_TABLE);
    lua_getfield(L, -1, WSLUA_EXPERT_SEVERITY_TABLE);
    lua_pushinteger(L, value);
    lua_setfield(L, -2, name);
    lua_pop(L, 2);
}

static void
add_pi_group_symbol(const char *name, int value)
{
    lua_getglobal(L, WSLUA_EXPERT_TABLE);
    lua_getfield(L, -1, WSLUA_EXPERT_GROUP_TABLE);
    lua_pushinteger(L, value);
    lua_setfield(L, -2, name);
    lua_pop(L, 2);
}

static void
add_menu_group_symbol(const char *name, int value)
{
    /* Set symbol in global environment. */
    lua_pushinteger(L, value);
    char *str = g_strdup(name);
    char *s = strstr(str, "_GROUP_");
    if (s == NULL) {
        g_free(str);
        return;
    }
    *s = '\0';
    s += strlen("_GROUP_");
    char *str2 = ws_strdup_printf("MENU_%s_%s", str, s);
    lua_setglobal(L, str2);
    g_free(str);
    g_free(str2);
}

/*
 * Read introspection constants and add them according to the historical
 * (sometimes arbitrary) rules of make-init-lua.py. For efficiency reasons
 * we only loop the enums array once.
 */
static void
wslua_add_introspection(void)
{
    const ws_enum_t *ep;

    /* Add empty tables to be populated. */
    lua_newtable(L);
    lua_setglobal(L, WSLUA_BASE_TABLE);
    lua_newtable(L);
    lua_setglobal(L, WSLUA_FTYPE_TABLE);
    lua_newtable(L);
    lua_setglobal(L, WSLUA_FRAMETYPE_TABLE);
    lua_newtable(L);
    lua_pushstring(L, WSLUA_EXPERT_GROUP_TABLE);
    lua_newtable(L);
    lua_settable(L, -3);
    lua_pushstring(L, WSLUA_EXPERT_SEVERITY_TABLE);
    lua_newtable(L);
    lua_settable(L, -3);
    lua_setglobal(L, WSLUA_EXPERT_TABLE);
    /* Add catch-all _EPAN table. */
    lua_newtable(L);
    lua_setglobal(L, WSLUA_EPAN_ENUMS_TABLE);

    for (ep = epan_inspect_enums(); ep->symbol != NULL; ep++) {

        if (g_str_has_prefix(ep->symbol, "BASE_")) {
            add_table_symbol(WSLUA_BASE_TABLE, ep->symbol + strlen("BASE_"), ep->value);
        }
        else if (g_str_has_prefix(ep->symbol, "SEP_")) {
            add_table_symbol(WSLUA_BASE_TABLE, ep->symbol + strlen("SEP_"), ep->value);
        }
        else if (g_str_has_prefix(ep->symbol, "ABSOLUTE_TIME_")) {
            add_table_symbol(WSLUA_BASE_TABLE, ep->symbol + strlen("ABSOLUTE_TIME_"), ep->value);
        }
        else if (g_str_has_prefix(ep->symbol, "ENC_")) {
            add_global_symbol(ep->symbol, ep->value);
        }
        else if (g_str_has_prefix(ep->symbol, "FT_FRAMENUM_")) {
            add_table_symbol(WSLUA_FRAMETYPE_TABLE, ep->symbol + strlen("FT_FRAMENUM_"), ep->value);
        }
        else if (g_str_has_prefix(ep->symbol, "FT_")) {
            add_table_symbol(WSLUA_FTYPE_TABLE, ep->symbol + strlen("FT_"), ep->value);
        }
        else if (g_str_has_prefix(ep->symbol, "PI_")) {
            if (ep->value & PI_SEVERITY_MASK) {
                add_pi_severity_symbol(ep->symbol + strlen("PI_"), ep->value);
            }
            else {
                 add_pi_group_symbol(ep->symbol + strlen("PI_"), ep->value);
            }
            /* For backward compatibility. */
            add_global_symbol(ep->symbol, ep->value);
        }
        else if (g_str_has_prefix(ep->symbol, "REGISTER_")) {
            add_menu_group_symbol(ep->symbol + strlen("REGISTER_"), ep->value);
        }
        add_table_symbol(WSLUA_EPAN_ENUMS_TABLE, ep->symbol, ep->value);
    }

    /* Add empty tables to be populated. */
    lua_newtable(L);
    lua_setglobal(L, WSLUA_WTAP_ENCAPS_TABLE);
    lua_newtable(L);
    lua_setglobal(L, WSLUA_WTAP_TSPREC_TABLE);
    lua_newtable(L);
    lua_setglobal(L, WSLUA_WTAP_COMMENTS_TABLE);
    lua_newtable(L);
    lua_setglobal(L, WSLUA_WTAP_RECTYPES_TABLE);
    lua_newtable(L);
    lua_setglobal(L, WSLUA_WTAP_PRESENCE_FLAGS_TABLE);
    /* Add catch-all _WTAP table. */
    lua_newtable(L);
    lua_setglobal(L, WSLUA_WTAP_ENUMS_TABLE);

    for (ep = wtap_inspect_enums(); ep->symbol != NULL; ep++) {

        if (g_str_has_prefix(ep->symbol, "WTAP_ENCAP_")) {
            add_table_symbol(WSLUA_WTAP_ENCAPS_TABLE, ep->symbol + strlen("WTAP_ENCAP_"), ep->value);
        }
        else if (g_str_has_prefix(ep->symbol, "WTAP_TSPREC_")) {
            add_table_symbol(WSLUA_WTAP_TSPREC_TABLE, ep->symbol + strlen("WTAP_TSPREC_"), ep->value);
        }
        else if (g_str_has_prefix(ep->symbol, "WTAP_COMMENT_")) {
            add_table_symbol(WSLUA_WTAP_COMMENTS_TABLE, ep->symbol + strlen("WTAP_COMMENT_"), ep->value);
        }
        else if (g_str_has_prefix(ep->symbol, "REC_TYPE_")) {
            add_table_symbol(WSLUA_WTAP_RECTYPES_TABLE, ep->symbol + strlen("REC_TYPE_"), ep->value);
        }
        else if (g_str_has_prefix(ep->symbol, "WTAP_HAS_")) {
            add_table_symbol(WSLUA_WTAP_PRESENCE_FLAGS_TABLE, ep->symbol + strlen("WTAP_HAS_"), ep->value);
        }
        add_table_symbol(WSLUA_WTAP_ENUMS_TABLE, ep->symbol, ep->value);
    }
}

static void wslua_add_deprecated(void)
{
    /* For backward compatibility. */
    lua_getglobal(L, "wtap_encaps");
    lua_setglobal(L, "wtap");

    /*
     * Generate the wtap_filetypes items for file types, for backwards
     * compatibility.
     * We no longer have WTAP_FILE_TYPE_SUBTYPE_ #defines;
     * built-in file types are registered the same way that
     * plugin file types are registered.
     *
     * New code should use wtap_name_to_file_type_subtype to
     * look up file types by name.
     */
    wslua_init_wtap_filetypes(L);

    /* Old / deprecated menu groups. These shoudn't be used in new code. */
    lua_getglobal(L, "MENU_PACKET_ANALYZE_UNSORTED");
    lua_setglobal(L, "MENU_ANALYZE_UNSORTED");
    lua_getglobal(L, "MENU_ANALYZE_CONVERSATION_FILTER");
    lua_setglobal(L, "MENU_ANALYZE_CONVERSATION");
    lua_getglobal(L, "MENU_STAT_CONVERSATION_LIST");
    lua_setglobal(L, "MENU_STAT_CONVERSATION");
    lua_getglobal(L, "MENU_STAT_ENDPOINT_LIST");
    lua_setglobal(L, "MENU_STAT_ENDPOINT");
    lua_getglobal(L, "MENU_STAT_RESPONSE_TIME");
    lua_setglobal(L, "MENU_STAT_RESPONSE");
    lua_getglobal(L, "MENU_PACKET_STAT_UNSORTED");
    lua_setglobal(L, "MENU_STAT_UNSORTED");
    lua_getglobal(L, "MENU_TELEPHONY_UNSORTED");
    lua_setglobal(L, "MENU_STAT_TELEPHONY");
    lua_getglobal(L, "MENU_TELEPHONY_ANSI");
    lua_setglobal(L, "MENU_STAT_TELEPHONY_ANSI");
    lua_getglobal(L, "MENU_TELEPHONY_GSM");
    lua_setglobal(L, "MENU_STAT_TELEPHONY_GSM");
    lua_getglobal(L, "MENU_TELEPHONY_3GPP_UU");
    lua_setglobal(L, "MENU_STAT_TELEPHONY_3GPP_UU");
    lua_getglobal(L, "MENU_TELEPHONY_MTP3");
    lua_setglobal(L, "MENU_STAT_TELEPHONY_MTP3");
    lua_getglobal(L, "MENU_TELEPHONY_SCTP");
    lua_setglobal(L, "MENU_STAT_TELEPHONY_SCTP");

    /* deprecated function names */
    lua_getglobal(L, "Dir");
    lua_getfield(L, -1, "global_config_path");
    lua_setglobal(L, "datafile_path");
    lua_getfield(L, -1, "personal_config_path");
    lua_setglobal(L, "persconffile_path");
    lua_pop(L, 1);
}

static int wslua_console_print(lua_State *_L);

static const char *lua_error_msg(int code)
{
    switch (code) {
        case LUA_ERRSYNTAX: return "syntax error during precompilation";
        case LUA_ERRMEM:    return "memory allocation error";
#if LUA_VERSION_NUM == 502
        case LUA_ERRGCMM:   return "error while running a __gc metamethod";
#endif
        case LUA_ERRRUN:    return "runtime error";
        case LUA_ERRERR:    return "error while running the message handler";
        default:            break; /* Should not happen. */
    }
    return "unknown error";
}

static int lua_funnel_console_eval(const char *console_input,
                                        char **error_ptr,
                                        char **error_hint,
                                        void *callback_data _U_)
{
    int lcode;

    const int curr_top = lua_gettop(L);

    // If it starts with an equals sign replace it with "return"
    char *codestr;
    while (g_ascii_isspace(*console_input))
        console_input++;
    if (*console_input == '=')
        codestr = ws_strdup_printf("return %s", console_input+1);
    else
        codestr = (char *)console_input; /* Violate const safety to avoid a strdup() */

    ws_noisy("Console input: %s", codestr);
    lcode = luaL_loadstring(L, codestr);
    /* Free only if we called strdup(). */
    if (codestr != console_input)
        g_free(codestr);
    codestr = NULL;

    if (lcode != LUA_OK) {
        ws_debug("luaL_loadstring(): %s (%d)", lua_error_msg(lcode), lcode);
        if (error_hint) {
            *error_hint = g_strdup(lua_error_msg(lcode));
        }
        /* If we have an error message return it. */
        if (error_ptr && !lua_isnil(L, -1)) {
            *error_ptr = g_strdup(lua_tostring(L, -1));
        }
        return -1;
    }

    lcode = lua_pcall(L, 0, LUA_MULTRET, 0);
    if (lcode != LUA_OK) {
        ws_debug("lua_pcall(): %s (%d)", lua_error_msg(lcode), lcode);
        if (error_hint) {
            *error_hint = g_strdup(lua_error_msg(lcode));
        }
        /* If we have an error message return it. */
        if (error_ptr && !lua_isnil(L, -1)) {
            *error_ptr = g_strdup(lua_tostring(L, -1));
        }
        return 1;
    }

    // If we have values returned print them all
    if (lua_gettop(L) > curr_top) {  /* any arguments? */
        lua_pushcfunction(L, wslua_console_print);
        lua_insert(L, curr_top+1);
        lcode = lua_pcall(L, lua_gettop(L)-curr_top-1, 0, 0);
        if (lcode != LUA_OK) {
            /* Error printing result */
            if (error_hint)
                *error_hint = ws_strdup_printf("error printing return values: %s", lua_error_msg(lcode));
            return 1;
        }
    }

    // For any new Protos, register their ProtoFields and ProtoExperts with epan
    lua_pushcfunction(L, Proto_commit);
    lcode = lua_pcall(L, 0, 0, 0);
    if (lcode != LUA_OK) {
        /* Error initializing new ProtoFields */
        if (error_hint)
            *error_hint = ws_strdup_printf("error initialzing protocol fields: %s", lua_error_msg(lcode));
        /* If we have an error message return it. */
        if (error_ptr && !lua_isnil(L, -1)) {
            *error_ptr = g_strdup(lua_tostring(L, -1));
        }
        return 1;
    }

    // Maintain stack discipline
    if (lua_gettop(L) != curr_top) {
        ws_critical("Expected stack top == %d, have %d", curr_top, lua_gettop(L));
    }

    ws_noisy("Success");
    return 0;
}

/* Receives C print function pointer as first upvalue. */
/* Receives C print function data pointer as second upvalue. */
static int wslua_console_print(lua_State *_L)
{
    GString *gstr = g_string_new(NULL);
    const char *repr;

    /* Print arguments. */
    for (int i = 1; i <= lua_gettop(_L); i++) {
            repr = luaL_tolstring(_L, i, NULL);
            if (i > 1)
                g_string_append_c(gstr, '\t');
            g_string_append(gstr, repr);
            lua_pop(_L, 1);
    }
    g_string_append_c(gstr, '\n');

    if (wslua_gui_print_func_ptr == NULL) {
        ws_critical("GUI print function not registered; Trying to print: %s", gstr->str);
    }
    else {
        wslua_gui_print_func_ptr(gstr->str, wslua_gui_print_data_ptr);
    }
    g_string_free(gstr, TRUE);
    return 0;
}

// Replace lua print function with a custom print function.
// We will place the original function in the Lua registry and return the reference.
static void lua_funnel_console_open(void (*print_func_ptr)(const char *, void *),
                                        void *print_data_ptr,
                                        void *callback_data _U_)
{
    /* Store original print value in the registry (even if it is nil). */
    lua_getglobal(L, "print");
    wslua_lua_print_func_ref = luaL_ref(L, LUA_REGISTRYINDEX);

    /* Set new "print" function (to output to the GUI) */
    lua_pushcfunction(L, wslua_console_print);
    lua_setglobal(L, "print");

    /* Save the globals */
    ws_assert(print_func_ptr);
    wslua_gui_print_func_ptr = print_func_ptr;
    wslua_gui_print_data_ptr = print_data_ptr;
}

// Restore original Lua print function. Clean state.
static void lua_funnel_console_close(void *callback_data _U_)
{
    /* Restore the original print function. */
    int ref = (int)wslua_lua_print_func_ref;
    /* push original function into stack */
    lua_rawgeti(L, LUA_REGISTRYINDEX, ref);
    lua_setglobal(L, "print");
    /* Release reference */
    luaL_unref(L, LUA_REGISTRYINDEX, ref);

    /* Clear the globals. */
    wslua_gui_print_func_ptr = NULL;
    wslua_gui_print_data_ptr = NULL;
    wslua_lua_print_func_ref = LUA_NOREF;
}

static int wslua_file_exists(lua_State *_L)
{
    const char *path = luaL_checkstring(_L, 1);
    lua_pushboolean(_L, g_file_test(path, G_FILE_TEST_EXISTS));
    return 1;
}

static int wslua_lua_typeof(lua_State *_L)
{
    const char *classname = wslua_typeof(_L, 1);
    lua_pushstring(_L, classname);
    return 1;
}

/* Other useful constants */
void wslua_add_useful_constants(void)
{
    const funnel_ops_t *ops = funnel_get_funnel_ops();
    char *path;

    WSLUA_REG_GLOBAL_BOOL(L,"GUI_ENABLED",ops && ops->new_dialog);

    /* DATA_DIR has a trailing directory separator. */
    path = get_datafile_path("");
    lua_pushfstring(L, "%s"G_DIR_SEPARATOR_S, path);
    g_free(path);
    lua_setglobal(L, "DATA_DIR");

    /* USER_DIR has a trailing directory separator. */
    path = get_persconffile_path("", false);
    lua_pushfstring(L, "%s"G_DIR_SEPARATOR_S, path);
    g_free(path);
    lua_setglobal(L, "USER_DIR");

    lua_pushcfunction(L, wslua_file_exists);
    lua_setglobal(L, "file_exists");

    lua_pushcfunction(L, wslua_lua_typeof);
    lua_setglobal(L, "typeof");
}

void wslua_init(register_cb cb, void *client_data) {
    char* filename;
    bool enable_lua = true;
    bool run_anyway = false;
    expert_module_t* expert_lua;
    int file_count = 1;
    static bool first_time = true;
    int i;
    int error;

    static hf_register_info hf[] = {
        { &hf_wslua_fake,
          { "Wireshark Lua fake item",     "_ws.lua.fake",
            FT_NONE, BASE_NONE, NULL, 0x0,
            "Fake internal item for Wireshark Lua", HFILL }},
        { &hf_wslua_text,
          { "Wireshark Lua text",     "_ws.lua.text",
            FT_NONE, BASE_NONE, NULL, 0x0, NULL, HFILL }},
    };
    static int *ett[] = {
            &ett_wslua_traceback,
    };

    static ei_register_info ei[] = {
        /* the following are created so we can continue to support the TreeItem_add_expert_info()
           function to Lua scripts. That function doesn't know what registered protocol to use,
           so it uses the "_ws.lua" one. */
        /* XXX: it seems to me we should not be offering PI_GROUP_MASK nor PI_SEVERITY_MASK since
           they are not real settings, so I'm not adding them below (should they also not be exported
           into Lua? they are right now.) */
        /* NOTE: do not add expert entries at the top of this array - only at the bottom. This array
           is not only used by expert.c, but also by wslua_get_expert_field() to find the appropriate
           "dummy" entry. So this array's ordering matters. */
        { &ei_lua_proto_checksum_comment,   { "_ws.lua.proto.comment", PI_CHECKSUM, PI_COMMENT ,"Protocol Comment", EXPFILL }},
        { &ei_lua_proto_checksum_chat,      { "_ws.lua.proto.chat",    PI_CHECKSUM, PI_CHAT    ,"Protocol Chat",    EXPFILL }},
        { &ei_lua_proto_checksum_note,      { "_ws.lua.proto.note",    PI_CHECKSUM, PI_NOTE    ,"Protocol Note",    EXPFILL }},
        { &ei_lua_proto_checksum_warn,      { "_ws.lua.proto.warning", PI_CHECKSUM, PI_WARN    ,"Protocol Warning", EXPFILL }},
        { &ei_lua_proto_checksum_error,     { "_ws.lua.proto.error",   PI_CHECKSUM, PI_ERROR   ,"Protocol Error",   EXPFILL }},

        { &ei_lua_proto_sequence_comment,   { "_ws.lua.proto.comment", PI_SEQUENCE, PI_COMMENT ,"Protocol Comment", EXPFILL }},
        { &ei_lua_proto_sequence_chat,      { "_ws.lua.proto.chat",    PI_SEQUENCE, PI_CHAT    ,"Protocol Chat",    EXPFILL }},
        { &ei_lua_proto_sequence_note,      { "_ws.lua.proto.note",    PI_SEQUENCE, PI_NOTE    ,"Protocol Note",    EXPFILL }},
        { &ei_lua_proto_sequence_warn,      { "_ws.lua.proto.warning", PI_SEQUENCE, PI_WARN    ,"Protocol Warning", EXPFILL }},
        { &ei_lua_proto_sequence_error,     { "_ws.lua.proto.error",   PI_SEQUENCE, PI_ERROR   ,"Protocol Error",   EXPFILL }},

        { &ei_lua_proto_response_comment,   { "_ws.lua.proto.comment", PI_RESPONSE_CODE, PI_COMMENT ,"Protocol Comment", EXPFILL }},
        { &ei_lua_proto_response_chat,      { "_ws.lua.proto.chat",    PI_RESPONSE_CODE, PI_CHAT    ,"Protocol Chat",    EXPFILL }},
        { &ei_lua_proto_response_note,      { "_ws.lua.proto.note",    PI_RESPONSE_CODE, PI_NOTE    ,"Protocol Note",    EXPFILL }},
        { &ei_lua_proto_response_warn,      { "_ws.lua.proto.warning", PI_RESPONSE_CODE, PI_WARN    ,"Protocol Warning", EXPFILL }},
        { &ei_lua_proto_response_error,     { "_ws.lua.proto.error",   PI_RESPONSE_CODE, PI_ERROR   ,"Protocol Error",   EXPFILL }},

        { &ei_lua_proto_request_comment,    { "_ws.lua.proto.comment", PI_REQUEST_CODE, PI_COMMENT ,"Protocol Comment", EXPFILL }},
        { &ei_lua_proto_request_chat,       { "_ws.lua.proto.chat",    PI_REQUEST_CODE, PI_CHAT    ,"Protocol Chat",    EXPFILL }},
        { &ei_lua_proto_request_note,       { "_ws.lua.proto.note",    PI_REQUEST_CODE, PI_NOTE    ,"Protocol Note",    EXPFILL }},
        { &ei_lua_proto_request_warn,       { "_ws.lua.proto.warning", PI_REQUEST_CODE, PI_WARN    ,"Protocol Warning", EXPFILL }},
        { &ei_lua_proto_request_error,      { "_ws.lua.proto.error",   PI_REQUEST_CODE, PI_ERROR   ,"Protocol Error",   EXPFILL }},

        { &ei_lua_proto_undecoded_comment,  { "_ws.lua.proto.comment", PI_UNDECODED, PI_COMMENT ,"Protocol Comment", EXPFILL }},
        { &ei_lua_proto_undecoded_chat,     { "_ws.lua.proto.chat",    PI_UNDECODED, PI_CHAT    ,"Protocol Chat",    EXPFILL }},
        { &ei_lua_proto_undecoded_note,     { "_ws.lua.proto.note",    PI_UNDECODED, PI_NOTE    ,"Protocol Note",    EXPFILL }},
        { &ei_lua_proto_undecoded_warn,     { "_ws.lua.proto.warning", PI_UNDECODED, PI_WARN    ,"Protocol Warning", EXPFILL }},
        { &ei_lua_proto_undecoded_error,    { "_ws.lua.proto.error",   PI_UNDECODED, PI_ERROR   ,"Protocol Error",   EXPFILL }},

        { &ei_lua_proto_reassemble_comment, { "_ws.lua.proto.comment", PI_REASSEMBLE, PI_COMMENT ,"Protocol Comment", EXPFILL }},
        { &ei_lua_proto_reassemble_chat,    { "_ws.lua.proto.chat",    PI_REASSEMBLE, PI_CHAT    ,"Protocol Chat",    EXPFILL }},
        { &ei_lua_proto_reassemble_note,    { "_ws.lua.proto.note",    PI_REASSEMBLE, PI_NOTE    ,"Protocol Note",    EXPFILL }},
        { &ei_lua_proto_reassemble_warn,    { "_ws.lua.proto.warning", PI_REASSEMBLE, PI_WARN    ,"Protocol Warning", EXPFILL }},
        { &ei_lua_proto_reassemble_error,   { "_ws.lua.proto.error",   PI_REASSEMBLE, PI_ERROR   ,"Protocol Error",   EXPFILL }},

        { &ei_lua_proto_malformed_comment,  { "_ws.lua.proto.comment", PI_MALFORMED, PI_COMMENT ,"Protocol Comment", EXPFILL }},
        { &ei_lua_proto_malformed_chat,     { "_ws.lua.proto.chat",    PI_MALFORMED, PI_CHAT    ,"Protocol Chat",    EXPFILL }},
        { &ei_lua_proto_malformed_note,     { "_ws.lua.proto.note",    PI_MALFORMED, PI_NOTE    ,"Protocol Note",    EXPFILL }},
        { &ei_lua_proto_malformed_warn,     { "_ws.lua.proto.warning", PI_MALFORMED, PI_WARN    ,"Protocol Warning", EXPFILL }},
        { &ei_lua_proto_malformed_error,    { "_ws.lua.proto.error",   PI_MALFORMED, PI_ERROR   ,"Protocol Error",   EXPFILL }},

        { &ei_lua_proto_debug_comment,      { "_ws.lua.proto.comment", PI_DEBUG, PI_COMMENT ,"Protocol Comment", EXPFILL }},
        { &ei_lua_proto_debug_chat,         { "_ws.lua.proto.chat",    PI_DEBUG, PI_CHAT    ,"Protocol Chat",    EXPFILL }},
        { &ei_lua_proto_debug_note,         { "_ws.lua.proto.note",    PI_DEBUG, PI_NOTE    ,"Protocol Note",    EXPFILL }},
        { &ei_lua_proto_debug_warn,         { "_ws.lua.proto.warning", PI_DEBUG, PI_WARN    ,"Protocol Warning", EXPFILL }},
        { &ei_lua_proto_debug_error,        { "_ws.lua.proto.error",   PI_DEBUG, PI_ERROR   ,"Protocol Error",   EXPFILL }},

        { &ei_lua_proto_protocol_comment,   { "_ws.lua.proto.comment", PI_PROTOCOL, PI_COMMENT ,"Protocol Comment", EXPFILL }},
        { &ei_lua_proto_protocol_chat,      { "_ws.lua.proto.chat",    PI_PROTOCOL, PI_CHAT    ,"Protocol Chat",    EXPFILL }},
        { &ei_lua_proto_protocol_note,      { "_ws.lua.proto.note",    PI_PROTOCOL, PI_NOTE    ,"Protocol Note",    EXPFILL }},
        { &ei_lua_proto_protocol_warn,      { "_ws.lua.proto.warning", PI_PROTOCOL, PI_WARN    ,"Protocol Warning", EXPFILL }},
        { &ei_lua_proto_protocol_error,     { "_ws.lua.proto.error",   PI_PROTOCOL, PI_ERROR   ,"Protocol Error",   EXPFILL }},

        { &ei_lua_proto_security_comment,   { "_ws.lua.proto.comment", PI_SECURITY, PI_COMMENT ,"Protocol Comment", EXPFILL }},
        { &ei_lua_proto_security_chat,      { "_ws.lua.proto.chat",    PI_SECURITY, PI_CHAT    ,"Protocol Chat",    EXPFILL }},
        { &ei_lua_proto_security_note,      { "_ws.lua.proto.note",    PI_SECURITY, PI_NOTE    ,"Protocol Note",    EXPFILL }},
        { &ei_lua_proto_security_warn,      { "_ws.lua.proto.warning", PI_SECURITY, PI_WARN    ,"Protocol Warning", EXPFILL }},
        { &ei_lua_proto_security_error,     { "_ws.lua.proto.error",   PI_SECURITY, PI_ERROR   ,"Protocol Error",   EXPFILL }},

        { &ei_lua_proto_comments_comment,   { "_ws.lua.proto.comment", PI_COMMENTS_GROUP, PI_COMMENT ,"Protocol Comment", EXPFILL }},
        { &ei_lua_proto_comments_chat,      { "_ws.lua.proto.chat",    PI_COMMENTS_GROUP, PI_CHAT    ,"Protocol Chat",    EXPFILL }},
        { &ei_lua_proto_comments_note,      { "_ws.lua.proto.note",    PI_COMMENTS_GROUP, PI_NOTE    ,"Protocol Note",    EXPFILL }},
        { &ei_lua_proto_comments_warn,      { "_ws.lua.proto.warning", PI_COMMENTS_GROUP, PI_WARN    ,"Protocol Warning", EXPFILL }},
        { &ei_lua_proto_comments_error,     { "_ws.lua.proto.error",   PI_COMMENTS_GROUP, PI_ERROR   ,"Protocol Error",   EXPFILL }},

        { &ei_lua_proto_decryption_comment, { "_ws.lua.proto.comment", PI_DECRYPTION, PI_COMMENT ,"Protocol Comment", EXPFILL }},
        { &ei_lua_proto_decryption_chat,    { "_ws.lua.proto.chat",    PI_DECRYPTION, PI_CHAT    ,"Protocol Chat",    EXPFILL }},
        { &ei_lua_proto_decryption_note,    { "_ws.lua.proto.note",    PI_DECRYPTION, PI_NOTE    ,"Protocol Note",    EXPFILL }},
        { &ei_lua_proto_decryption_warn,    { "_ws.lua.proto.warning", PI_DECRYPTION, PI_WARN    ,"Protocol Warning", EXPFILL }},
        { &ei_lua_proto_decryption_error,   { "_ws.lua.proto.error",   PI_DECRYPTION, PI_ERROR   ,"Protocol Error",   EXPFILL }},

        { &ei_lua_proto_assumption_comment, { "_ws.lua.proto.comment", PI_ASSUMPTION, PI_COMMENT ,"Protocol Comment", EXPFILL }},
        { &ei_lua_proto_assumption_chat,    { "_ws.lua.proto.chat",    PI_ASSUMPTION, PI_CHAT    ,"Protocol Chat",    EXPFILL }},
        { &ei_lua_proto_assumption_note,    { "_ws.lua.proto.note",    PI_ASSUMPTION, PI_NOTE    ,"Protocol Note",    EXPFILL }},
        { &ei_lua_proto_assumption_warn,    { "_ws.lua.proto.warning", PI_ASSUMPTION, PI_WARN    ,"Protocol Warning", EXPFILL }},
        { &ei_lua_proto_assumption_error,   { "_ws.lua.proto.error",   PI_ASSUMPTION, PI_ERROR   ,"Protocol Error",   EXPFILL }},

        { &ei_lua_proto_deprecated_comment, { "_ws.lua.proto.comment", PI_DEPRECATED, PI_COMMENT ,"Protocol Comment", EXPFILL }},
        { &ei_lua_proto_deprecated_chat,    { "_ws.lua.proto.chat",    PI_DEPRECATED, PI_CHAT    ,"Protocol Chat",    EXPFILL }},
        { &ei_lua_proto_deprecated_note,    { "_ws.lua.proto.note",    PI_DEPRECATED, PI_NOTE    ,"Protocol Note",    EXPFILL }},
        { &ei_lua_proto_deprecated_warn,    { "_ws.lua.proto.warning", PI_DEPRECATED, PI_WARN    ,"Protocol Warning", EXPFILL }},
        { &ei_lua_proto_deprecated_error,   { "_ws.lua.proto.error",   PI_DEPRECATED, PI_ERROR   ,"Protocol Error",   EXPFILL }},

        { &ei_lua_proto_receive_comment,    { "_ws.lua.proto.comment", PI_RECEIVE, PI_COMMENT    ,"Protocol Comment", EXPFILL }},
        { &ei_lua_proto_receive_chat,       { "_ws.lua.proto.chat",    PI_RECEIVE, PI_CHAT       ,"Protocol Chat",    EXPFILL }},
        { &ei_lua_proto_receive_note,       { "_ws.lua.proto.note",    PI_RECEIVE, PI_NOTE       ,"Protocol Note",    EXPFILL }},
        { &ei_lua_proto_receive_warn,       { "_ws.lua.proto.warning", PI_RECEIVE, PI_WARN       ,"Protocol Warning", EXPFILL }},
        { &ei_lua_proto_receive_error,      { "_ws.lua.proto.error",   PI_RECEIVE, PI_ERROR      ,"Protocol Error",   EXPFILL }},

        { &ei_lua_proto_interface_comment,  { "_ws.lua.proto.comment", PI_INTERFACE, PI_COMMENT  ,"Protocol Comment", EXPFILL }},
        { &ei_lua_proto_interface_chat,     { "_ws.lua.proto.chat",    PI_INTERFACE, PI_CHAT     ,"Protocol Chat",    EXPFILL }},
        { &ei_lua_proto_interface_note,     { "_ws.lua.proto.note",    PI_INTERFACE, PI_NOTE     ,"Protocol Note",    EXPFILL }},
        { &ei_lua_proto_interface_warn,     { "_ws.lua.proto.warning", PI_INTERFACE, PI_WARN     ,"Protocol Warning", EXPFILL }},
        { &ei_lua_proto_interface_error,    { "_ws.lua.proto.error",   PI_INTERFACE, PI_ERROR    ,"Protocol Error",   EXPFILL }},

        /* this one is for reporting errors executing Lua code */
        { &ei_lua_error, { "_ws.lua.error", PI_UNDECODED, PI_ERROR ,"Lua Error", EXPFILL }},
    };

    if (first_time) {
        ws_lua_ei = ei;
        ws_lua_ei_len = array_length(ei);
    }

    if (!L) {
        L = lua_newstate(wslua_allocf, NULL);
    }

    WSLUA_INIT(L);

    if (first_time) {
        proto_lua = proto_register_protocol("Lua Dissection", "Lua Dissection", "_ws.lua");
        proto_register_field_array(proto_lua, hf, array_length(hf));
        proto_register_subtree_array(ett, array_length(ett));
        expert_lua = expert_register_protocol(proto_lua);
        expert_register_field_array(expert_lua, ei, array_length(ei));
    }

    lua_atpanic(L,wslua_panic);

    /*
     * The init_routines table (accessible by the user).
     *
     * For a table a, a.init is syntactic sugar for a["init"], and
     *
     *    function t.a.b.c.f () body end
     *
     * is syntactic sugar for
     *
     *    t.a.b.c.f = function () body end
     *
     * so
     *
     *    function proto.init () body end
     *
     * means
     *
     *    proto["init"] = function () body end
     *
     * and the Proto class has an "init" method, with Proto_set_init()
     * being the setter for that method; that routine adds the Lua
     * function passed to it as a Lua argument to the WSLUA_INIT_ROUTINES
     * table - i.e., "init_routines".
     */
    lua_newtable (L);
    lua_setglobal(L, WSLUA_INIT_ROUTINES);

    /* the dissectors table goes in the registry (not accessible) */
    lua_newtable (L);
    lua_dissectors_table_ref = luaL_ref(L, LUA_REGISTRYINDEX);
    lua_newtable (L);
    lua_heur_dissectors_table_ref = luaL_ref(L, LUA_REGISTRYINDEX);

    /* the preferences apply_cb table (accessible by the user) */
    lua_newtable (L);
    lua_setglobal(L, WSLUA_PREFS_CHANGED);

    /* set running_superuser variable to its proper value */
    WSLUA_REG_GLOBAL_BOOL(L,"running_superuser",started_with_special_privs());

    /* special constant used by PDU reassembly handling */
    /* see dissect_lua() for notes */
    WSLUA_REG_GLOBAL_INTEGER(L,"DESEGMENT_ONE_MORE_SEGMENT",DESEGMENT_ONE_MORE_SEGMENT);

    /* the possible values for Pinfo's p2p_dir attribute */
    WSLUA_REG_GLOBAL_INTEGER(L,"P2P_DIR_UNKNOWN",-1);
    WSLUA_REG_GLOBAL_INTEGER(L,"P2P_DIR_SENT",0);
    WSLUA_REG_GLOBAL_INTEGER(L,"P2P_DIR_RECV",1);

    wslua_add_introspection();

    wslua_add_useful_constants();

    wslua_add_deprecated();

    // Register Lua's console menu (in the GUI)
    if (first_time) {
        funnel_register_console_menu("Lua",
                                        lua_funnel_console_eval,
                                        lua_funnel_console_open,
                                        lua_funnel_console_close,
                                        NULL, NULL);
    }
    else if (wslua_gui_print_func_ptr) {
        // If we we have an open GUI console dialog re-register the global "print to console" function
        lua_funnel_console_open(wslua_gui_print_func_ptr, wslua_gui_print_data_ptr, NULL);
    }

    /* load system's init.lua */
#if 0
    /* wslua_dofile / wslua_get_actual_filename look in the datafile dir.
     * Should we add that to the path for require() as well, for consistency?
     */
    prepend_path(get_datafile_dir());
#endif
    /* Add the global plugins path for require */
    prepend_path(get_plugins_dir());
    filename = g_build_filename(get_plugins_dir(), "init.lua", (char *)NULL);
    if (file_exists(filename)) {
        ws_debug("Loading init.lua file: %s", filename);
        lua_load_internal_script(filename);
    }
    g_free(filename);

    /* load user's init.lua */
    /* if we are indeed superuser run user scripts only if told to do so */
    if (!started_with_special_privs() || run_anyway) {
#if 0
        /* wslua_dofile / wslua_get_actual_filename look in the personal configuration
         * directory. Should we add that to the path for require() as well, for consistency?
         */
        profile_dir = get_profile_dir(NULL, false);
        prepend_path(profile_dir);
        g_free(profile_dir);
#endif
        /* Add the personal plugins path(s) for require() */
        char *old_path = get_persconffile_path("plugins", false);
        if (strcmp(get_plugins_pers_dir(), old_path) != 0) {
            prepend_path(old_path);
        }
        g_free(old_path);
        prepend_path(get_plugins_pers_dir());
        filename = g_build_filename(get_plugins_pers_dir(), "init.lua", (char *)NULL);
        if (file_exists(filename)) {
            ws_debug("Loading init.lua file: %s", filename);
            lua_load_internal_script(filename);
        }
        g_free(filename);

        /* For backward compatibility also load it from the configuration directory. */
        filename = get_persconffile_path("init.lua", false);
        if (file_exists(filename)) {
            ws_message("Loading init.lua file from deprecated path: %s", filename);
            lua_load_internal_script(filename);
        }
        g_free(filename);
    }

    filename = NULL;

    /* check if lua is to be disabled */
    lua_getglobal(L, "disable_lua"); // 2.6 and earlier, deprecated
    if (lua_isboolean(L,-1)) {
        enable_lua = ! lua_toboolean(L,-1);
    }
    lua_pop(L,1);  /* pop the getglobal result */

    lua_getglobal(L, "enable_lua"); // 3.0 and later
    if (lua_isboolean(L,-1)) {
        enable_lua = lua_toboolean(L,-1);
    }
    lua_pop(L,1);  /* pop the getglobal result */

    if (!enable_lua) {
        /* disable lua */
        lua_close(L);
        L = NULL;
        first_time = false;
        return;
    }

    /* load global scripts */
    lua_load_global_plugins(cb, client_data, false);

    /* check whether we should run other scripts even if running superuser */
    lua_getglobal(L,"run_user_scripts_when_superuser");

    if (lua_isboolean(L,-1) && lua_toboolean(L,-1)) {
        run_anyway = true;
    }
    lua_pop(L,1);  /* pop the getglobal result */

    /* if we are indeed superuser run user scripts only if told to do so */
    if (!started_with_special_privs() || run_anyway) {

        /* load user scripts */
        lua_load_pers_plugins(cb, client_data, false);

        /* load scripts from command line */
        for (i = 0; i < ex_opt_count("lua_script"); i++) {
            const char *script_filename = ex_opt_get_nth("lua_script", i);
            char* dirname = g_strdup(script_filename);
            char* dname = get_dirname(dirname);
            /* Add the command line script directory to the path (unless it's
             * the current directory, which should already be in the path by
             * default).
             * XXX - Should we remove it after we're done with this script? */
            if (dname)
                prepend_path(dname);

            if (cb)
                (*cb)(RA_LUA_PLUGINS, get_basename(script_filename), client_data);

            lua_load_plugin_script(ws_dir_get_name(script_filename),
                                   script_filename,
                                   dname ? dname : "",
                                   file_count);
            file_count++;
            g_free(dirname);
        }
    }

    if (first_time) {
        /* at this point we're set up so register the init and cleanup routines */
        register_init_routine(wslua_init_routine);
        register_cleanup_routine(wslua_cleanup_routine);
    }

    /*
     * after this point it is too late to register a menu
     * disable the function to avoid weirdness
     */
    lua_pushcfunction(L, wslua_not_register_menu);
    lua_setglobal(L, "register_menu");

    /* set up some essential globals */
    lua_pinfo = NULL;
    lua_tree = NULL;
    lua_tvb = NULL;

    /* Unfortunately, by waiting to register the hfi and ei now, Lua
     * can't figure out which file had the error and provide a traceback,
     * so no special error handler.
     */
    lua_pushcfunction(L, Proto_commit);
    error = lua_pcall(L, 0, 0, 0);
    if (error) {
        switch (error) {
            case LUA_ERRRUN:
                report_failure("Lua: Error initializing protocols:\n%s", lua_tostring(L, -1));
                break;
            case LUA_ERRMEM:
                report_failure("Lua: Error initializing protocols: out of memory");
                break;
            case LUA_ERRERR:
                report_failure("Lua: Error initializing protocols: error while retrieving error message");
                break;
            default:
                report_failure("Lua: Error initializing protocols: unknown error %d", error);
                break;
        }
    }

    first_time = false;
}

void wslua_early_cleanup(void) {
    wslua_deregister_protocols(L);
}

void wslua_reload_plugins (register_cb cb, void *client_data) {
    const funnel_ops_t* ops = funnel_get_funnel_ops();

    if (cb)
        (*cb)(RA_LUA_DEREGISTER, NULL, client_data);

    if (ops->close_dialogs)
        ops->close_dialogs();

    wslua_deregister_heur_dissectors(L);
    wslua_deregister_protocols(L);
    wslua_deregister_dissector_tables(L);
    wslua_deregister_listeners(L);
    wslua_deregister_fields(L);
    wslua_deregister_filehandlers(L);
    wslua_deregister_menus();
    wslua_clear_plugin_list();

    wslua_cleanup();
    wslua_init(cb, client_data);    /* reinitialize */
}

void wslua_cleanup(void) {
    /* cleanup lua */
    if (L) {
        lua_close(L);
        L = NULL;
    }
    init_routine_initialized = false;
}

lua_State* wslua_state(void) { return L; }

/*
 * Editor modelines  -  https://www.wireshark.org/tools/modelines.html
 *
 * Local variables:
 * c-basic-offset: 4
 * tab-width: 8
 * indent-tabs-mode: nil
 * End:
 *
 * vi: set shiftwidth=4 tabstop=8 expandtab:
 * :indentSize=4:tabSize=8:noTabs=true:
 */