1[[wsluarm]] 2 3// Attributes 4:build_dir: . 5 6== Lua Support in Wireshark 7 8[[wsluarm_intro]] 9 10=== Introduction 11 12Lua is a powerful light-weight programming language designed for extending 13applications. Wireshark contains an embedded Lua 5.2 interpreter which 14can be used to write dissectors, taps, and capture file readers 15and writers. 16 17Wireshark’s Lua interpreter starts by loading a file named `init.lua` from 18Wireshark's link:{wireshark-users-guide-url}ChAppFilesConfigurationSection.html[_global configuration directory_]. 19The _global configuration directory_'s `init.lua` controls whether or not Lua 20scripts are enabled via the 21_$$enable_lua$$_ variable. Lua scripts are enabled by 22default. To disable Lua scripts, set the _$$enable_lua$$_ variable to _false_. 23Wireshark 2.6 and earlier enabled or disabled Lua scripts using 24the variable _$$disable_lua$$_ (deprecated). If both _$$enable_lua$$_ and 25_$$disable_lua$$_ are present, _$$disable_lua$$_ is ignored. 26 27If Lua is enabled, Wireshark will try to load a file named `init.lua` 28from the user’s 29link:{wireshark-users-guide-url}ChAppFilesConfigurationSection.html[_personal configuration directory_] 30and all files ending with _.lua_ in the global and the personal 31link:{wireshark-users-guide-url}ChPluginFolders.html[_plugins directory_]. 32 33The command line option _$$-X lua_script:$$++file.lua++_ can also be used to load 34specific Lua scripts. 35 36The Lua code is executed after all protocol dissectors are 37initialized and before reading any file. 38 39Wireshark for Windows uses a modified Lua runtime 40(link:https://github.com/Lekensteyn/lua-unicode[lua-unicode]) to 41support Unicode (UTF-8) filesystem paths. This brings consistency with other 42platforms (for example, Linux and macOS). 43 44[[wslua_menu_example]] 45 46=== Example: Creating a Menu with Lua 47 48The code below adds a menu "Lua Dialog Test" under the Tools menu. 49When selected, it opens a dialog prompting the user for input 50and then opens a text window with the output. 51 52[source,lua] 53---- 54 55-- Define the menu entry's callback 56local function dialog_menu() 57 local function dialog_func(person,eyes,hair) 58 local window = TextWindow.new("Person Info"); 59 local message = string.format("Person %s with %s eyes and %s hair.", person, eyes, hair); 60 window:set(message); 61 end 62 63 new_dialog("Dialog Test",dialog_func,"A Person","Eyes","Hair") 64end 65 66-- Create the menu entry 67register_menu("Lua Dialog Test",dialog_menu,MENU_TOOLS_UNSORTED) 68 69-- Notify the user that the menu was created 70if gui_enabled() then 71 local splash = TextWindow.new("Hello!"); 72 splash:set("Wireshark has been enhanced with a useless feature.\n") 73 splash:append("Go to 'Tools->Lua Dialog Test' and check it out!") 74end 75 76---- 77 78[[wslua_dissector_example]] 79 80=== Example: Dissector written in Lua 81 82[source,lua] 83---- 84local p_multi = Proto("multi", "MultiProto"); 85 86local vs_protos = { 87 [2] = "mtp2", 88 [3] = "mtp3", 89 [4] = "alcap", 90 [5] = "h248", 91 [6] = "ranap", 92 [7] = "rnsap", 93 [8] = "nbap" 94} 95 96local f_proto = ProtoField.uint8("multi.protocol", "Protocol", base.DEC, vs_protos) 97local f_dir = ProtoField.uint8("multi.direction", "Direction", base.DEC, { [1] = "incoming", [0] = "outgoing"}) 98local f_text = ProtoField.string("multi.text", "Text") 99 100p_multi.fields = { f_proto, f_dir, f_text } 101 102local data_dis = Dissector.get("data") 103 104local protos = { 105 [2] = Dissector.get("mtp2"), 106 [3] = Dissector.get("mtp3"), 107 [4] = Dissector.get("alcap"), 108 [5] = Dissector.get("h248"), 109 [6] = Dissector.get("ranap"), 110 [7] = Dissector.get("rnsap"), 111 [8] = Dissector.get("nbap"), 112 [9] = Dissector.get("rrc"), 113 [10] = DissectorTable.get("sctp.ppi"):get_dissector(3), -- m3ua 114 [11] = DissectorTable.get("ip.proto"):get_dissector(132), -- sctp 115} 116 117function p_multi.dissector(buf, pkt, tree) 118 119 local subtree = tree:add(p_multi, buf(0,2)) 120 subtree:add(f_proto, buf(0,1)) 121 subtree:add(f_dir, buf(1,1)) 122 123 local proto_id = buf(0,1):uint() 124 125 local dissector = protos[proto_id] 126 127 if dissector ~= nil then 128 -- Dissector was found, invoke subdissector with a new Tvb, 129 -- created from the current buffer (skipping first two bytes). 130 dissector:call(buf(2):tvb(), pkt, tree) 131 elseif proto_id < 2 then 132 subtree:add(f_text, buf(2)) 133 -- pkt.cols.info:set(buf(2, buf:len() - 3):string()) 134 else 135 -- fallback dissector that just shows the raw data. 136 data_dis:call(buf(2):tvb(), pkt, tree) 137 end 138 139end 140 141local wtap_encap_table = DissectorTable.get("wtap_encap") 142local udp_encap_table = DissectorTable.get("udp.port") 143 144wtap_encap_table:add(wtap.USER15, p_multi) 145wtap_encap_table:add(wtap.USER12, p_multi) 146udp_encap_table:add(7555, p_multi) 147---- 148 149[[wslua_tap_example]] 150 151=== Example: Listener written in Lua 152 153[source,lua] 154---- 155-- This program will register a menu that will open a window with a count of occurrences 156-- of every address in the capture 157 158local function menuable_tap() 159 -- Declare the window we will use 160 local tw = TextWindow.new("Address Counter") 161 162 -- This will contain a hash of counters of appearances of a certain address 163 local ips = {} 164 165 -- this is our tap 166 local tap = Listener.new(); 167 168 local function remove() 169 -- this way we remove the listener that otherwise will remain running indefinitely 170 tap:remove(); 171 end 172 173 -- we tell the window to call the remove() function when closed 174 tw:set_atclose(remove) 175 176 -- this function will be called once for each packet 177 function tap.packet(pinfo,tvb) 178 local src = ips[tostring(pinfo.src)] or 0 179 local dst = ips[tostring(pinfo.dst)] or 0 180 181 ips[tostring(pinfo.src)] = src + 1 182 ips[tostring(pinfo.dst)] = dst + 1 183 end 184 185 -- this function will be called once every few seconds to update our window 186 function tap.draw(t) 187 tw:clear() 188 for ip,num in pairs(ips) do 189 tw:append(ip .. "\t" .. num .. "\n"); 190 end 191 end 192 193 -- this function will be called whenever a reset is needed 194 -- e.g. when reloading the capture file 195 function tap.reset() 196 tw:clear() 197 ips = {} 198 end 199 200 -- Ensure that all existing packets are processed. 201 retap_packets() 202end 203 204-- using this function we register our function 205-- to be called when the user selects the Tools->Test->Packets menu 206register_menu("Test/Packets", menuable_tap, MENU_TOOLS_UNSORTED) 207---- 208 209[[wsluarm_modules]] 210 211== Wireshark’s Lua API Reference Manual 212 213This Part of the User Guide describes the Wireshark specific functions in the embedded Lua. 214 215Classes group certain functionality, the following notational conventions are 216used: 217 218* _Class.function()_ represents a class method (named _function_) on class 219 _Class_, taking no arguments. 220 221* _Class.function(a)_ represents a class method taking one argument. 222 223* _Class.function(...)_ represents a class method taking a variable number of 224 arguments. 225 226* _class:method()_ represents an instance method (named _method_) on an instance 227 of class _Class_, taking no arguments. Note the lowercase notation in the 228 documentation to clarify an instance. 229 230* _class.prop_ represents a property _prop_ on the instance of class _Class_. 231 232Trying to access a non-existing property, function or method currently gives an 233error, but do not rely on it as the behavior may change in the future. 234 235 236include::{build_dir}/wsluarm_src/wslua_dumper.adoc[] 237include::{build_dir}/wsluarm_src/wslua_field.adoc[] 238include::{build_dir}/wsluarm_src/wslua_gui.adoc[] 239include::{build_dir}/wsluarm_src/wslua_listener.adoc[] 240include::{build_dir}/wsluarm_src/wslua_pinfo.adoc[] 241include::{build_dir}/wsluarm_src/wslua_proto.adoc[] 242include::{build_dir}/wsluarm_src/wslua_tree.adoc[] 243include::{build_dir}/wsluarm_src/wslua_tvb.adoc[] 244include::{build_dir}/wsluarm_src/wslua_file.adoc[] 245include::{build_dir}/wsluarm_src/wslua_dir.adoc[] 246include::{build_dir}/wsluarm_src/wslua_wtap.adoc[] 247include::{build_dir}/wsluarm_src/wslua_util.adoc[] 248include::{build_dir}/wsluarm_src/wslua_int64.adoc[] 249include::{build_dir}/wsluarm_src/wslua_struct.adoc[] 250 251[[lua_module_GRegex]] 252 253=== GLib Regular Expressions 254 255Lua has its own native _pattern_ syntax in the string library, but sometimes a 256real regex engine is more useful. Wireshark comes with GLib’s Regex 257implementation, which itself is based on Perl Compatible Regular Expressions 258(PCRE). This engine is exposed into Wireshark’s Lua engine through the 259well-known Lrexlib library, following the same syntax and semantics as the 260Lrexlib PCRE implementation, with a few differences as follows: 261 262* There is no support for using custom locale/chartables 263 264* _dfa_exec()_ doesn't take _ovecsize_ nor _wscount_ arguments 265 266* _dfa_exec()_ returns boolean true for partial match, without subcapture info 267 268* Named subgroups do not return name-keyed entries in the return table (i.e., in 269 match/tfind/exec) 270 271* The _flags()_ function still works, returning all flags, but two new functions 272 _compile_flags()_ and _match_flags()_ return just their respective flags, 273 since GLib has a different and smaller set of such flags, for regex compile 274 vs. match functions 275 276* Using some assertions and POSIX character classes against strings with 277 non-ASCII characters might match high-order characters, because glib always 278 sets PCRE_UCP even if G_REGEX_RAW is set. For example, _[:alpha;]_ matches 279 certain non-ASCII bytes. The following assertions have this issue: _\b_, _\B_, 280 _\s_, _\S_, _\w_, _\W_. The following character classes have this issue: 281 [:alpha:], [:alnum:], [:lower:], [:upper:], [:space:], [:word:], and 282 [:graph:]. 283 284* The compile flag G_REGEX_RAW is always set/used, even if you didn't specify 285 it. This is because GLib runs PCRE in UTF-8 mode by default, whereas Lua 286 strings are not UTF-aware. 287 288 289Since: 1.11.3 290 291This page is based on the full documentation for Lrexlib at 292https://rrthomas.github.io/lrexlib/manual.html[] 293 294The GLib Regular expression syntax (which is essentially PCRE syntax) can be 295found at 296https://developer.gnome.org/glib/2.38/glib-regex-syntax.html[] 297 298[[lua_class_GRegex]] 299 300==== GRegex 301 302GLib Regular Expressions based on PCRE. 303 304Since: 1.11.3 305 306[[lua_class_GRegex_notes]] 307 308===== Notes 309 310All functions that take a regular expression pattern as an argument will 311generate an error if that pattern is found invalid by the regex library. 312 313All functions that take a string-type regex argument accept a compiled regex 314too. In this case, the compile flags argument is ignored (should be either 315supplied as nils or omitted). 316 317The capture flag argument _cf_ may also be supplied as a string, whose 318characters stand for compilation flags. Combinations of the following characters 319(case sensitive) are supported: 320 321* _i_ = G_REGEX_CASELESS - Letters in the pattern match both upper- and 322 lowercase letters. This option can be changed within a pattern by a “(?i)” 323 option setting. 324 325* _m_ = G_REGEX_MULTILINE - By default, GRegex treats the strings as 326 consisting of a single line of characters (even if it actually contains 327 newlines). The “start of line” metacharacter (“^”) matches only at the start 328 of the string, while the “end of line” metacharacter (“$”) matches only at 329 the end of the string, or before a terminating newline (unless 330 G_REGEX_DOLLAR_ENDONLY is set). When G_REGEX_MULTILINE is set, the “start of 331 line” and “end of line” constructs match immediately following or 332 immediately before any newline in the string, respectively, as well as at the 333 very start and end. This can be changed within a pattern by a “(?m)” option 334 setting. 335 336* _s_ = G_REGEX_DOTALL - A dot metacharacter (“.”) in the pattern matches 337 all characters, including newlines. Without it, newlines are excluded. This 338 option can be changed within a pattern by a ("?s") option setting. 339 340* _x_ = G_REGEX_EXTENDED - Whitespace data characters in the pattern are 341 totally ignored except when escaped or inside a character class. Whitespace 342 does not include the VT character (code 11). In addition, characters between 343 an unescaped “$$#$$” outside a character class and the next newline character, 344 inclusive, are also ignored. This can be changed within a pattern by a 345 “(?x)” option setting. 346 347* _U_ = G_REGEX_UNGREEDY - Inverts the “greediness” of the quantifiers so 348 that they are not greedy by default, but become greedy if followed by “?”. 349 It can also be set by a “(?U)” option setting within the pattern. 350 351[[lua_fn_GRegex_new_pattern_]] 352 353===== GRegex.new(pattern) 354 355Compiles regular expression pattern into a regular expression object whose 356internal representation is corresponding to the library used. The returned 357result then can be used by the methods, e.g. match, exec, etc. Regular 358expression objects are automatically garbage collected. 359 360Since: 1.11.3 361 362[discrete] 363===== Arguments 364 365pattern:: A Perl-compatible regular expression pattern string 366 367[discrete] 368===== Returns 369 370The compiled regular expression (a userdata object) 371 372[discrete] 373===== Errors 374 375* A malformed pattern generates a Lua error 376 377[[lua_fn_GRegex_flags__table__]] 378 379===== GRegex.flags([table]) 380 381Returns a table containing the numeric values of the constants defined by the 382regex library, with the keys being the (string) names of the constants. If the 383table argument is supplied then it is used as the output table, otherwise a new 384table is created. The constants contained in the returned table can then be used 385in most functions and methods where compilation flags or execution flags can be 386specified. They can also be used for comparing with return codes of some 387functions and methods for determining the reason of failure. 388 389Since: 1.11.3 390 391[discrete] 392===== Arguments 393 394table (optional):: A table for placing results into 395 396[discrete] 397===== Returns 398 399A table filled with the results. 400 401[[lua_fn_GRegex_compile_flags__table__]] 402 403 404===== GRegex.compile_flags([table]) 405 406Returns a table containing the numeric values of the constants defined by the 407regex library for compile flags, with the keys being the (string) names of the 408constants. If the table argument is supplied then it is used as the output 409table, otherwise a new table is created. 410 411Since: 1.11.3 412 413[discrete] 414===== Arguments 415 416table (optional):: A table for placing results into 417 418[discrete] 419===== Returns 420 421A table filled with the results. 422 423[[lua_fn_GRegex_match_flags__table__]] 424 425===== GRegex.match_flags([table]) 426 427Returns a table containing the numeric values of the constants defined by the 428regex library for match flags, with the keys being the (string) names of the 429constants. If the table argument is supplied then it is used as the output 430table, otherwise a new table is created. 431 432Since: 1.11.3 433 434[discrete] 435===== Arguments 436 437table (optional):: A table for placing results into 438 439[discrete] 440===== Returns 441 442A table filled with the results. 443 444[[lua_fn_GRegex_match_subject__pattern___init____cf____ef__]] 445 446===== GRegex.match(subject, pattern, [init], [cf], [ef]) 447 448Searches for the first match of the regexp pattern in the string subject, 449starting from offset init, subject to flags cf and ef. The pattern is compiled 450each time this is called, unlike the class method _match_ function. 451 452Since: 1.11.3 453 454[discrete] 455===== Arguments 456 457subject:: Subject string to search 458 459pattern:: A Perl-compatible regular expression pattern string or GRegex object 460 461init (optional):: start offset in the subject (can be negative) 462 463cf (optional):: compilation flags (bitwise OR) 464 465ef (optional):: match execution flags (bitwise OR) 466 467[discrete] 468===== Returns 469 470On success, returns all substring matches ("captures"), in the order they appear 471in the pattern. false is returned for sub-patterns that did not participate in 472the match. If the pattern specified no captures then the whole matched substring 473is returned. On failure, returns nil. 474 475[[lua_fn_GRegex_find_subject__pattern___init____cf____ef__]] 476 477===== GRegex.find(subject, pattern, [init], [cf], [ef]) 478 479Searches for the first match of the regexp pattern in the string subject, 480starting from offset init, subject to flags ef. The pattern is compiled each 481time this is called, unlike the class method _find_ function. 482 483Since: 1.11.3 484 485[discrete] 486===== Arguments 487 488subject:: Subject string to search 489 490pattern:: A Perl-compatible regular expression pattern string or GRegex object 491 492init (optional):: start offset in the subject (can be negative) 493 494cf (optional):: compilation flags (bitwise OR) 495 496ef (optional):: match execution flags (bitwise OR) 497 498[discrete] 499===== Returns 500 501On success, returns the start point of the match (a number), the end point of 502the match (a number), and all substring matches ("captures"), in the order they 503appear in the pattern. false is returned for sub-patterns that did not 504participate in the match. On failure, returns nil. 505 506[[lua_fn_GRegex_gmatch_subject__pattern___init____cf____ef__]] 507 508 509===== GRegex.gmatch(subject, pattern, [init], [cf], [ef]) 510 511Returns an iterator for repeated matching of the pattern patt in the string 512subj, subject to flags cf and ef. The function is intended for use in the 513generic for Lua construct. The pattern can be a string or a GRegex object 514previously compiled with GRegex.new(). 515 516Since: 1.11.3 517 518[discrete] 519===== Arguments 520 521subject:: Subject string to search 522 523pattern:: A Perl-compatible regular expression pattern string or GRegex object 524 525init (optional):: start offset in the subject (can be negative) 526 527cf (optional):: compilation flags (bitwise OR) 528 529ef (optional):: match execution flags (bitwise OR) 530 531[discrete] 532===== Returns 533 534The iterator function is called by Lua. On every iteration (that is, on every 535match), it returns all captures in the order they appear in the pattern (or the 536entire match if the pattern specified no captures). The iteration will continue 537till the subject fails to match. 538 539[[lua_fn_GRegex_gsub_subject__pattern___repl____max____cf____ef__]] 540 541===== GRegex.gsub(subject, pattern, [repl], [max], [cf], [ef]) 542 543Searches for all matches of the pattern in the string subject and replaces them 544according to the parameters repl and max. The pattern can be a string or a 545GRegex object previously compiled with GRegex.new(). 546 547Since: 1.11.3 548 549For details see: 550https://rrthomas.github.io/lrexlib/manual.html#gsub[] 551 552[discrete] 553===== Arguments 554 555subject:: Subject string to search 556 557pattern:: A Perl-compatible regular expression pattern string or GRegex object 558 559repl (optional):: Substitution source string, function, table, false or nil 560 561max (optional):: Maximum number of matches to search for, or control function, or nil 562 563cf (optional):: Compilation flags (bitwise OR) 564 565ef (optional):: Match execution flags (bitwise OR) 566 567[discrete] 568===== Returns 569 570On success, returns the subject string with the substitutions made, the number 571of matches found, and the number of substitutions made. 572 573[[lua_fn_GRegex_split_subject__sep___cf____ef__]] 574 575===== GRegex.split(subject, sep, [cf], [ef]) 576 577Splits a subject string subj into parts (sections). The sep parameter is a 578regular expression pattern representing separators between the sections. The 579function is intended for use in the generic for Lua construct. The function 580returns an iterator for repeated matching of the pattern sep in the string subj, 581subject to flags cf and ef. The sep pattern can be a string or a GRegex object 582previously compiled with GRegex.new(). Unlike gmatch, there will always be at 583least one iteration pass, even if there are no matches in the subject. 584 585Since: 1.11.3 586 587[discrete] 588===== Arguments 589 590subject:: Subject string to search 591 592sep:: A Perl-compatible regular expression pattern string or GRegex object 593 594cf (optional):: compilation flags (bitwise OR) 595 596ef (optional):: match execution flags (bitwise OR) 597 598[discrete] 599===== Returns 600 601The iterator function is called by Lua. On every iteration, it returns a subject 602section (can be an empty string), followed by all captures in the order they 603appear in the sep pattern (or the entire match if the sep pattern specified no 604captures). If there is no match (this can occur only in the last iteration), 605then nothing is returned after the subject section. The iteration will continue 606till the end of the subject. 607 608[[lua_fn_GRegex_version__]] 609 610===== GRegex.version() 611 612Returns a returns a string containing the version of the used library. 613 614Since: 1.11.3 615 616[discrete] 617===== Returns 618 619The version string 620 621[[lua_fn_gregex_match_subject___init____ef__]] 622 623===== gregex:match(subject, [init], [ef]) 624 625Searches for the first match of the regexp pattern in the string subject, 626starting from offset init, subject to flags ef. 627 628Since: 1.11.3 629 630[discrete] 631===== Arguments 632 633subject:: Subject string to search 634 635init (optional):: start offset in the subject (can be negative) 636 637ef (optional):: match execution flags (bitwise OR) 638 639[discrete] 640===== Returns 641 642On success, returns all substring matches (“captures”), in the order they appear 643in the pattern. false is returned for sub-patterns that did not participate in 644the match. If the pattern specified no captures then the whole matched substring 645is returned. nil is returned if the pattern did not match. 646 647[[lua_fn_gregex_find_subject___init____ef__]] 648 649===== gregex:find(subject, [init], [ef]) 650 651Searches for the first match of the regexp pattern in the string subject, 652starting from offset init, subject to flags ef. 653 654Since: 1.11.3 655 656[discrete] 657===== Arguments 658 659subject:: Subject string to search 660 661init (optional):: start offset in the subject (can be negative) 662 663ef (optional):: match execution flags (bitwise OR) 664 665[discrete] 666===== Returns 667 668On success, returns the start point of the match (a number), the end point of 669the match (a number), and all substring matches ("captures"), in the order they 670appear in the pattern. false is returned for sub-patterns that did not 671participate in the match. On failure, returns nil. 672 673[[lua_fn_gregex_exec_subject___init____ef__]] 674 675===== gregex:exec(subject, [init], [ef]) 676 677Searches for the first match of the compiled GRegex object in the string 678subject, starting from offset init, subject to the execution match flags ef. 679 680Since: 1.11.3 681 682[discrete] 683===== Arguments 684 685subject:: Subject string to search 686 687init (optional):: start offset in the subject (can be negative) 688 689ef (optional):: match execution flags (bitwise OR) 690 691[discrete] 692===== Returns 693 694On success, returns the start point of the first match (a number), the end point 695of the first match (a number), and the offsets of substring matches (“captures” 696in Lua terminology) are returned as a third result, in a table. This table 697contains false in the positions where the corresponding sub-pattern did not 698participate in the match. On failure, returns nil. Example: If the whole match 699is at offsets 10,20 and substring matches are at offsets 12,14 and 16,19 then 700the function returns the following: 10, 20, { 12,14,16,19 }. 701 702[[lua_fn_gregex_dfa_exec_subject___init____ef__]] 703 704===== gregex:dfa_exec(subject, [init], [ef]) 705 706Matches a compiled regular expression GRegex object against a given subject 707string subj, using a DFA matching algorithm. 708 709Since: 1.11.3 710 711[discrete] 712===== Arguments 713 714subject:: Subject string to search 715 716init (optional):: start offset in the subject (can be negative) 717 718ef (optional):: match execution flags (bitwise OR) 719 720[discrete] 721===== Returns 722 723On success, returns the start point of the matches found (a number), a table 724containing the end points of the matches found, the longer matches first, and 725the number of matches found as the third return value. On failure, returns nil. 726Example: If there are 3 matches found starting at offset 10 and ending at 727offsets 15, 20 and 25 then the function returns the following: 10, { 25,20,15 }, 7283 729 730[[lua_fn_gregex___tostring__]] 731 732===== gregex:__tostring() 733 734Returns a string containing debug information about the GRegex object. 735 736Since: 1.11.3 737 738[discrete] 739===== Returns 740 741The debug string 742