+/melee-stream

git clone https://git.julia.blue/+/melee-stream

Julia Ryanwireshark slippi dissector2f3b2ca

main
33.4 KiB785 linesraw
1--
2-- slippi.lua - Wireshark dissector for Slippi console mirroring traffic
3--
4-- Slippi ("Project Slippi") mirroring lets a Slippi Nintendont console (Wii)
5-- stream live game data to a desktop client (Slippi Launcher / Dolphin /
6-- slippi-js / libmelee). The client opens a TCP connection to the console
7-- (default port 51441; legacy 666; relay instances 53741+) and sends a
8-- handshake; the console then streams length-prefixed UBJSON messages, each
9-- wrapping either connection metadata or a chunk of the .slp event byte stream.
10--
11-- Wire format (per message, "normal" mode):
12--
13--     +----------------+---------------------------------------------+
14--     | u32be length N | N bytes of UBJSON                          |
15--     +----------------+---------------------------------------------+
16--
17--   The UBJSON object is:  { "type": <u8>, "payload": { ... } }
18--
19--     type 1 HANDSHAKE  payload: nick, nintendontVersion, clientToken[4],
20--                                pos[8]           (console -> client)
21--                       payload: cursor[8], clientToken[4], isRealtime
22--                                                 (client -> console handshake)
23--     type 2 REPLAY     payload: pos[8], nextPos[8], forcePos(bool),
24--                                data[]  <- concatenated raw .slp events
25--     type 3 KEEPALIVE  payload: (empty)
26--     type 4 MENU       payload: data[]  <- menu snapshot event bytes
27--
28-- "legacy" mode (old Nintendont / relay): no length prefix, the TCP stream is
29-- just the raw concatenated .slp event byte stream. Detected heuristically.
30--
31-- The .slp event stream is a sequence of events, each: <u8 command><payload>.
32-- The payload length per command is announced once per game by the Event
33-- Payloads (0x35) event. When we join mid-game we won't have seen it, so a
34-- built-in default table (current Slippi replay spec, verified against live
35-- console traffic) is used until a real 0x35 is observed on that TCP stream.
36--
37-- References:
38--   https://github.com/project-slippi/slippi-wiki  (SPEC.md, SPECTATOR_PROTOCOL.md)
39--   https://github.com/project-slippi/slippi-js     src/node/console/*
40--   https://github.com/altf4/libmelee               melee/slippstream.py
41--
42-- Install: drop this file in your Wireshark "Personal Lua Plugins" directory
43--   (Help > About Wireshark > Folders), or run:
44--     tshark -X lua_script:slippi.lua -d tcp.port==51441,slippi ...
45--
46
47local p_slippi = Proto("slippi", "Slippi Console Mirroring")
48
49----------------------------------------------------------------------
50-- Constants / lookup tables
51----------------------------------------------------------------------
52
53local COMM_TYPE = {
54    [1] = "HANDSHAKE",
55    [2] = "REPLAY",
56    [3] = "KEEPALIVE",
57    [4] = "MENU",
58}
59
60local SLP_CMD = {
61    [0x10] = "Message Splitter",
62    [0x35] = "Event Payloads",
63    [0x36] = "Game Start",
64    [0x37] = "Pre-Frame Update",
65    [0x38] = "Post-Frame Update",
66    [0x39] = "Game End",
67    [0x3A] = "Frame Start",
68    [0x3B] = "Item Update",
69    [0x3C] = "Frame Bookend",
70    [0x3D] = "Gecko List",
71}
72
73-- short tags for the Info column summary
74local SLP_CMD_SHORT = {
75    [0x10] = "SPLIT",
76    [0x35] = "PAYLOADS",
77    [0x36] = "START",
78    [0x37] = "PRE",
79    [0x38] = "POST",
80    [0x39] = "END",
81    [0x3A] = "FS",
82    [0x3B] = "ITEM",
83    [0x3C] = "BE",
84    [0x3D] = "GECKO",
85}
86
87-- Default payload sizes (bytes AFTER the command byte). Used only until a real
88-- Event Payloads (0x35) event is seen on the stream. Values match the current
89-- Slippi replay spec and were verified byte-for-byte against a live Slippi
90-- Nintendont console (Frame Start = 12, Pre = 0x42, Post = 0x54, Bookend = 8).
91local SLP_DEFAULT_SIZE = {
92    [0x10] = 516,   -- Message Splitter: 512 data + 2 size + 1 idx + 1 cmd(of split)
93    [0x36] = 760,   -- Game Start (>= 3.14.0); real size comes from 0x35 anyway
94    [0x37] = 0x42,  -- Pre-Frame Update  (66)
95    [0x38] = 0x54,  -- Post-Frame Update (84)
96    [0x39] = 6,     -- Game End (method + LRAS initiator + 4 placements)
97    [0x3A] = 12,    -- Frame Start (frame + seed + scene frame counter)
98    [0x3B] = 44,    -- Item Update
99    [0x3C] = 8,     -- Frame Bookend (frame + latest finalized frame)
100    -- 0x3D Gecko List is variable-length; deliberately absent so it is only
101    -- ever split using a real 0x35 table (it always follows Game Start, which
102    -- always carries the 0x35 event).
103}
104
105local STAGE = {
106    [2]="Fountain of Dreams", [3]="Pokemon Stadium", [4]="Princess Peach's Castle",
107    [5]="Kongo Jungle", [6]="Brinstar", [7]="Corneria", [8]="Yoshi's Story",
108    [9]="Onett", [10]="Mute City", [11]="Rainbow Cruise", [12]="Jungle Japes",
109    [13]="Great Bay", [14]="Hyrule Temple", [15]="Brinstar Depths",
110    [16]="Yoshi's Island", [17]="Green Greens", [18]="Fourside",
111    [19]="Mushroom Kingdom I", [20]="Mushroom Kingdom II", [22]="Venom",
112    [23]="Poke Floats", [24]="Big Blue", [25]="Icicle Mountain", [26]="Icetop",
113    [27]="Flat Zone", [28]="Dream Land N64", [29]="Yoshi's Island N64",
114    [30]="Kongo Jungle N64", [31]="Battlefield", [32]="Final Destination",
115}
116
117local CHAR_EXT = {
118    [0]="Captain Falcon", [1]="Donkey Kong", [2]="Fox", [3]="Mr. Game & Watch",
119    [4]="Kirby", [5]="Bowser", [6]="Link", [7]="Luigi", [8]="Mario", [9]="Marth",
120    [10]="Mewtwo", [11]="Ness", [12]="Peach", [13]="Pikachu", [14]="Ice Climbers",
121    [15]="Jigglypuff", [16]="Samus", [17]="Yoshi", [18]="Zelda", [19]="Sheik",
122    [20]="Falco", [21]="Young Link", [22]="Dr. Mario", [23]="Roy", [24]="Pichu",
123    [25]="Ganondorf", [26]="Master Hand", [27]="Wireframe (M)", [28]="Wireframe (F)",
124    [29]="Giga Bowser", [30]="Crazy Hand", [31]="Sandbag", [32]="Popo",
125}
126
127local PLAYER_TYPE = { [0]="Human", [1]="CPU", [2]="Demo", [3]="Empty" }
128
129local GAME_END_METHOD = {
130    [0]="Unresolved", [1]="TIME!", [2]="GAME!", [3]="Resolved",
131    [7]="No Contest (LRAS)",
132}
133
134----------------------------------------------------------------------
135-- Protocol fields
136----------------------------------------------------------------------
137
138local f = p_slippi.fields
139
140f.msg_len   = ProtoField.uint32("slippi.msg_len", "Message Length", base.DEC)
141f.msg_type  = ProtoField.uint8 ("slippi.type", "Message Type", base.DEC, COMM_TYPE)
142f.direction = ProtoField.string("slippi.direction", "Direction")
143f.legacy    = ProtoField.bool  ("slippi.legacy", "Legacy raw stream (no length prefix)")
144
145-- UBJSON generic rendering
146f.ub_key    = ProtoField.string("slippi.ubjson.key", "Key")
147f.ub_num    = ProtoField.int64 ("slippi.ubjson.num", "Number")
148f.ub_str    = ProtoField.string("slippi.ubjson.str", "String")
149f.ub_bool   = ProtoField.bool  ("slippi.ubjson.bool", "Bool")
150f.ub_bytes  = ProtoField.bytes ("slippi.ubjson.bytes", "Bytes")
151
152-- Named payload fields (handshake / replay)
153f.nick        = ProtoField.string("slippi.nick", "Console Nickname")
154f.version     = ProtoField.string("slippi.nintendont_version", "Nintendont Version")
155f.client_tok  = ProtoField.bytes ("slippi.client_token", "Client Token")
156f.pos         = ProtoField.bytes ("slippi.pos", "Cursor / Position")
157f.next_pos    = ProtoField.bytes ("slippi.next_pos", "Next Position")
158f.force_pos   = ProtoField.bool  ("slippi.force_pos", "Force Position (overflow)")
159f.cursor_req  = ProtoField.bytes ("slippi.cursor", "Requested Cursor")
160f.is_realtime = ProtoField.bool  ("slippi.is_realtime", "Is Realtime")
161f.data_len    = ProtoField.uint32("slippi.data_len", "SLP Data Length", base.DEC)
162
163-- SLP event stream
164f.slp        = ProtoField.bytes ("slippi.slp", "SLP Event Stream")
165f.slp_event  = ProtoField.bytes ("slippi.slp.event", "SLP Event")
166f.slp_cmd    = ProtoField.uint8 ("slippi.slp.command", "Command", base.HEX, SLP_CMD)
167f.slp_size   = ProtoField.uint16("slippi.slp.payload_size", "Payload Size", base.DEC)
168f.slp_raw    = ProtoField.bytes ("slippi.slp.raw", "Undissected bytes")
169
170f.slp_frame      = ProtoField.int32 ("slippi.slp.frame", "Frame", base.DEC)
171f.slp_final_frame= ProtoField.int32 ("slippi.slp.latest_finalized_frame", "Latest Finalized Frame", base.DEC)
172f.slp_scene_fc   = ProtoField.uint32("slippi.slp.scene_frame_counter", "Scene Frame Counter", base.DEC)
173f.slp_seed       = ProtoField.uint32("slippi.slp.rng_seed", "RNG Seed", base.HEX)
174f.slp_pidx       = ProtoField.uint8 ("slippi.slp.player_index", "Player Index", base.DEC)
175f.slp_follower   = ProtoField.uint8 ("slippi.slp.is_follower", "Is Follower", base.DEC)
176f.slp_action     = ProtoField.uint16("slippi.slp.action_state", "Action State ID", base.DEC)
177f.slp_intchar    = ProtoField.uint8 ("slippi.slp.internal_char", "Internal Character ID", base.DEC)
178f.slp_posx       = ProtoField.float ("slippi.slp.pos_x", "Position X")
179f.slp_posy       = ProtoField.float ("slippi.slp.pos_y", "Position Y")
180f.slp_facing     = ProtoField.float ("slippi.slp.facing", "Facing")
181f.slp_percent    = ProtoField.float ("slippi.slp.percent", "Percent")
182f.slp_shield     = ProtoField.float ("slippi.slp.shield", "Shield Size")
183f.slp_stocks     = ProtoField.uint8 ("slippi.slp.stocks", "Stocks Remaining", base.DEC)
184
185f.slp_version    = ProtoField.string("slippi.slp.replay_version", "Replay Format Version")
186f.slp_stage      = ProtoField.uint16("slippi.slp.stage", "Stage ID", base.DEC, STAGE)
187f.slp_ext_char   = ProtoField.uint8 ("slippi.slp.external_char", "External Character ID", base.DEC, CHAR_EXT)
188f.slp_ptype      = ProtoField.uint8 ("slippi.slp.player_type", "Player Type", base.DEC, PLAYER_TYPE)
189f.slp_disp_name  = ProtoField.string("slippi.slp.display_name", "Display Name")
190f.slp_conn_code  = ProtoField.string("slippi.slp.connect_code", "Connect Code")
191
192f.slp_end_method = ProtoField.uint8("slippi.slp.game_end_method", "Game End Method", base.DEC, GAME_END_METHOD)
193f.slp_lras       = ProtoField.int8 ("slippi.slp.lras_initiator", "LRAS Initiator", base.DEC)
194
195f.slp_item_type  = ProtoField.uint16("slippi.slp.item_type", "Item Type ID", base.DEC)
196f.slp_item_id    = ProtoField.uint32("slippi.slp.item_spawn_id", "Item Spawn ID", base.DEC)
197
198f.slp_placement  = ProtoField.int8 ("slippi.slp.placement", "Placement", base.DEC)
199f.slp_split_cmd  = ProtoField.uint8("slippi.slp.split_command", "Wrapped Command", base.HEX, SLP_CMD)
200f.slp_split_size = ProtoField.uint16("slippi.slp.split_size", "Chunk Data Size", base.DEC)
201f.slp_split_last = ProtoField.bool ("slippi.slp.split_last", "Last Chunk")
202
203----------------------------------------------------------------------
204-- Per-TCP-stream state: learned Event Payloads (0x35) size tables
205----------------------------------------------------------------------
206
207local tcp_stream_f = Field.new("tcp.stream")
208local learned_sizes = {}   -- [stream_id] = { [cmd] = payload_size }
209local legacy_stream = {}    -- [stream_id] = true  (no length prefix)
210
211local function stream_id()
212    local s = tcp_stream_f()
213    if s == nil then return -1 end
214    return tonumber(s.value) or -1
215end
216
217local function size_for(sid, cmd)
218    local t = learned_sizes[sid]
219    if t and t[cmd] ~= nil then return t[cmd], true end
220    return SLP_DEFAULT_SIZE[cmd], false
221end
222
223----------------------------------------------------------------------
224-- UBJSON reader
225----------------------------------------------------------------------
226
227-- Read an integer whose type marker is at `off`. Returns value, total_size.
228-- Handles i U I l L. Returns nil if the marker is not an int marker.
229local function ub_read_int(tvb, off)
230    local m = tvb(off, 1):uint()
231    if m == 0x69 then return tvb(off+1,1):int(),  2      -- 'i' int8
232    elseif m == 0x55 then return tvb(off+1,1):uint(), 2  -- 'U' uint8
233    elseif m == 0x49 then return tvb(off+1,2):int(),  3  -- 'I' int16
234    elseif m == 0x6C then return tvb(off+1,4):int(),  5  -- 'l' int32
235    elseif m == 0x4C then return tvb(off+1,8):int64(), 9 -- 'L' int64
236    end
237    return nil
238end
239
240-- forward decls
241local ub_parse_value, ub_parse_array, ub_parse_array_bytes, ub_array_byte_span
242
243-- Parse an object (marker '{' already consumed at caller). `off` points at the
244-- first member key marker (or '}'). Returns next_offset.
245-- `on_member(key, value_marker, value_off, tree)` is called per member and may
246-- return true to indicate it fully handled (dissected) that member's value.
247local function ub_parse_object(tvb, off, tree, on_member)
248    while true do
249        local m = tvb(off, 1):uint()
250        if m == 0x7D then          -- '}'
251            return off + 1
252        end
253        -- object key: bare int-length + bytes (no 'S' marker)
254        local klen, ksz = ub_read_int(tvb, off)
255        if klen == nil then
256            tree:add_expert_info(PI_MALFORMED, PI_ERROR, "bad UBJSON key marker")
257            return off + 1
258        end
259        klen = tonumber(klen)
260        local key = tvb(off + ksz, klen):string()
261        local koff = off
262        off = off + ksz + klen
263
264        local vmarker = tvb(off, 1):uint()
265        local handled = false
266        if on_member then
267            handled = on_member(key, vmarker, off, tree, koff, ksz + klen)
268        end
269        if handled then
270            off = handled                     -- callback returns next offset
271        else
272            local kt = tree:add(f.ub_key, tvb(koff, ksz + klen), key)
273            off = ub_parse_value(tvb, off, kt)
274        end
275    end
276end
277
278-- Parse a value whose marker is at `off`. Returns next_offset.
279ub_parse_value = function(tvb, off, tree)
280    local m = tvb(off, 1):uint()
281
282    if m == 0x5A then tree:append_text(" = null"); return off + 1        -- 'Z'
283    elseif m == 0x4E then return off + 1                                  -- 'N' no-op
284    elseif m == 0x54 then tree:add(f.ub_bool, tvb(off,1), true); return off + 1   -- 'T'
285    elseif m == 0x46 then tree:add(f.ub_bool, tvb(off,1), false); return off + 1  -- 'F'
286    elseif m == 0x69 or m == 0x55 or m == 0x49 or m == 0x6C or m == 0x4C then
287        local v, sz = ub_read_int(tvb, off)
288        tree:add(f.ub_num, tvb(off, sz), tonumber(v) or 0)
289        return off + sz
290    elseif m == 0x64 then                                                -- 'd' float32
291        tree:add(f.ub_num, tvb(off+1, 4), 0):set_text(string.format("float32: %g", tvb(off+1,4):float()))
292        return off + 5
293    elseif m == 0x44 then                                                -- 'D' float64
294        tree:add(f.ub_num, tvb(off+1, 8), 0):set_text(string.format("float64: %g", tvb(off+1,8):float()))
295        return off + 9
296    elseif m == 0x43 then                                                -- 'C' char
297        tree:add(f.ub_str, tvb(off+1, 1))
298        return off + 2
299    elseif m == 0x53 or m == 0x48 then                                   -- 'S' string / 'H' high-prec
300        local slen, ssz = ub_read_int(tvb, off + 1)
301        slen = tonumber(slen)
302        tree:add(f.ub_str, tvb(off + 1 + ssz, slen))
303        return off + 1 + ssz + slen
304    elseif m == 0x5B then                                                -- '[' array
305        return ub_parse_array(tvb, off + 1, tree)
306    elseif m == 0x7B then                                                -- '{' object
307        return ub_parse_object(tvb, off + 1, tree, nil)
308    end
309
310    tree:add_expert_info(PI_UNDECODED, PI_WARN,
311        string.format("unknown UBJSON marker 0x%02X", m))
312    return off + 1
313end
314
315-- Parse an array body (marker '[' already consumed). Handles the optimized
316-- form  [ $ <type> # <count-int> <packed values> . Returns next_offset.
317ub_parse_array = function(tvb, off, tree)
318    if tvb(off, 1):uint() == 0x24 then         -- '$' typed
319        local etype = tvb(off + 1, 1):uint()
320        -- next must be '#'
321        local count, csz = ub_read_int(tvb, off + 3)   -- off+2 is '#'
322        count = tonumber(count) or 0
323        local body = off + 3 + csz
324        if etype == 0x55 or etype == 0x69 then         -- byte array
325            if count > 0 then
326                tree:add(f.ub_bytes, tvb(body, count))
327            else
328                tree:append_text(" = <empty>")
329            end
330            return body + count
331        end
332        -- other typed arrays: element size lookup
333        local esz = ({ [0x49]=2, [0x6C]=4, [0x4C]=8, [0x64]=4, [0x44]=8 })[etype] or 1
334        tree:add(f.ub_bytes, tvb(body, count * esz)):append_text(
335            string.format(" (%d x type 0x%02X)", count, etype))
336        return body + count * esz
337    end
338
339    -- unoptimized: values until ']'
340    while tvb(off, 1):uint() ~= 0x5D do
341        off = ub_parse_value(tvb, off, tree)
342    end
343    return off + 1
344end
345
346----------------------------------------------------------------------
347-- SLP event stream dissection
348----------------------------------------------------------------------
349
350local function add_replay_version(tree, tvb, off)
351    local s = string.format("%d.%d.%d.%d",
352        tvb(off,1):uint(), tvb(off+1,1):uint(), tvb(off+2,1):uint(), tvb(off+3,1):uint())
353    tree:add(f.slp_version, tvb(off, 4), s)
354    return s
355end
356
357-- Dissect a single SLP event's payload. `off` points at the command byte.
358local function dissect_slp_event(tvb, off, cmd, evlen, tree)
359    local plen = evlen - 1
360    local function has(n) return plen >= n end
361
362    if cmd == 0x35 then
363        -- Event Payloads: byte 1 = size (3n+1); then n entries of {u8 cmd, u16 size}
364        local n = math.floor((tvb(off+1,1):uint() - 1) / 3)
365        for i = 0, n - 1 do
366            local e = off + 2 + i * 3
367            local ec = tvb(e, 1):uint()
368            local es = tvb(e + 1, 2):uint()
369            tree:add(f.slp_cmd, tvb(e, 1), ec)
370            tree:add(f.slp_size, tvb(e + 1, 2), es):append_text(
371                SLP_CMD[ec] and (" (" .. SLP_CMD[ec] .. ")") or "")
372        end
373
374    elseif cmd == 0x36 then
375        local v = add_replay_version(tree, tvb, off + 1)
376        if has(0x14) then tree:add(f.slp_stage, tvb(off + 0x13, 2)) end
377        for p = 0, 3 do
378            local cbase = off + 0x65 + 0x24 * p
379            if has(0x66 + 0x24 * p) then
380                local pt = tree:add(p_slippi, tvb(cbase, 2), "Player " .. p)
381                pt:add(f.slp_ext_char, tvb(cbase, 1))
382                pt:add(f.slp_ptype, tvb(cbase + 1, 1))
383            end
384        end
385        -- Display names (3.9.0+): 0x1A5 + 31*p, connect codes: 0x221 + 10*p
386        for p = 0, 3 do
387            local no = off + 1 + 0x1A5 + 31 * p
388            if has(0x1A5 + 31 * p + 31) then
389                tree:add(f.slp_disp_name, tvb(no, 31))
390            end
391            local co = off + 1 + 0x221 + 10 * p
392            if has(0x221 + 10 * p + 10) then
393                tree:add(f.slp_conn_code, tvb(co, 10))
394            end
395        end
396
397    elseif cmd == 0x37 then           -- Pre-Frame Update
398        tree:add(f.slp_frame,  tvb(off + 1, 4))
399        tree:add(f.slp_pidx,   tvb(off + 5, 1))
400        tree:add(f.slp_follower,tvb(off + 6, 1))
401        tree:add(f.slp_seed,   tvb(off + 7, 4))
402        if has(13) then tree:add(f.slp_action, tvb(off + 11, 2)) end
403        if has(17) then tree:add(f.slp_posx,   tvb(off + 13, 4)) end
404        if has(21) then tree:add(f.slp_posy,   tvb(off + 17, 4)) end
405        if has(25) then tree:add(f.slp_facing, tvb(off + 21, 4)) end
406        if has(64) then tree:add(f.slp_percent,tvb(off + 60, 4)) end
407
408    elseif cmd == 0x38 then           -- Post-Frame Update
409        tree:add(f.slp_frame,   tvb(off + 1, 4))
410        tree:add(f.slp_pidx,    tvb(off + 5, 1))
411        tree:add(f.slp_follower,tvb(off + 6, 1))
412        tree:add(f.slp_intchar, tvb(off + 7, 1))
413        tree:add(f.slp_action,  tvb(off + 8, 2))
414        if has(14) then tree:add(f.slp_posx,   tvb(off + 10, 4)) end
415        if has(18) then tree:add(f.slp_posy,   tvb(off + 14, 4)) end
416        if has(22) then tree:add(f.slp_facing, tvb(off + 18, 4)) end
417        if has(26) then tree:add(f.slp_percent,tvb(off + 22, 4)) end
418        if has(30) then tree:add(f.slp_shield, tvb(off + 26, 4)) end
419        if has(34) then tree:add(f.slp_stocks, tvb(off + 33, 1)) end
420
421    elseif cmd == 0x10 then           -- Message Splitter
422        -- payload: data[512] | u16 chunk size | u8 wrapped command | u8 last
423        if has(516) then
424            tree:add(f.slp_split_size, tvb(off + 513, 2))
425            tree:add(f.slp_split_cmd,  tvb(off + 515, 1))
426            tree:add(f.slp_split_last, tvb(off + 516, 1))
427        end
428
429    elseif cmd == 0x39 then           -- Game End
430        tree:add(f.slp_end_method, tvb(off + 1, 1))
431        if has(2) then tree:add(f.slp_lras, tvb(off + 2, 1)) end
432        if has(6) then
433            for p = 0, 3 do
434                tree:add(f.slp_placement, tvb(off + 3 + p, 1)):append_text(" (player " .. p .. ")")
435            end
436        end
437
438    elseif cmd == 0x3A then           -- Frame Start
439        tree:add(f.slp_frame, tvb(off + 1, 4))
440        tree:add(f.slp_seed,  tvb(off + 5, 4))
441        if has(12) then tree:add(f.slp_scene_fc, tvb(off + 9, 4)) end
442
443    elseif cmd == 0x3B then           -- Item Update
444        tree:add(f.slp_frame,     tvb(off + 1, 4))
445        tree:add(f.slp_item_type, tvb(off + 5, 2))
446        if has(37) then tree:add(f.slp_item_id, tvb(off + 33, 4)) end
447
448    elseif cmd == 0x3C then           -- Frame Bookend
449        tree:add(f.slp_frame,       tvb(off + 1, 4))
450        tree:add(f.slp_final_frame, tvb(off + 5, 4))
451    end
452end
453
454-- Walk a concatenated SLP event byte range [off, off+len). Learns the 0x35
455-- size table into learned_sizes[sid]. Returns an array of short tags and the
456-- min/max frame numbers seen (or nil).
457local function dissect_slp_stream(tvb, off, len, tree, sid, pinfo)
458    local st = tree:add(f.slp, tvb(off, len))
459    local pos, endp = off, off + len
460    local tags, fmin, fmax = {}, nil, nil
461
462    while pos < endp do
463        local cmd = tvb(pos, 1):uint()
464        local psize, learned
465
466        if cmd == 0x35 then
467            local total = tvb(pos + 1, 1):uint()   -- 3n+1
468            psize = total
469            -- learn the table before we render, so later events in this same
470            -- blob use the right sizes
471            local n = math.floor((total - 1) / 3)
472            learned_sizes[sid] = learned_sizes[sid] or {}
473            for i = 0, n - 1 do
474                local e = pos + 2 + i * 3
475                learned_sizes[sid][tvb(e, 1):uint()] = tvb(e + 1, 2):uint()
476            end
477        else
478            psize, learned = size_for(sid, cmd)
479        end
480
481        if psize == nil then
482            st:add(f.slp_raw, tvb(pos, endp - pos)):append_text(
483                string.format(" (unknown command 0x%02X, stopped)", cmd))
484            st:add_expert_info(PI_UNDECODED, PI_NOTE,
485                string.format("unknown SLP command 0x%02X; no size table yet", cmd))
486            break
487        end
488
489        local evlen = 1 + psize
490        if pos + evlen > endp then
491            st:add(f.slp_raw, tvb(pos, endp - pos)):append_text(
492                string.format(" (truncated %s event, want %d have %d)",
493                    SLP_CMD[cmd] or "?", evlen, endp - pos))
494            break
495        end
496
497        local ev = st:add(f.slp_event, tvb(pos, evlen))
498        ev:set_text(string.format("%s (0x%02X) - %d bytes%s",
499            SLP_CMD[cmd] or "Unknown", cmd, evlen,
500            (not learned and cmd ~= 0x35) and " [default size]" or ""))
501        ev:add(f.slp_cmd, tvb(pos, 1))
502        dissect_slp_event(tvb, pos, cmd, evlen, ev)
503
504        tags[#tags + 1] = SLP_CMD_SHORT[cmd] or string.format("%02X", cmd)
505        if cmd == 0x37 or cmd == 0x38 or cmd == 0x3A or cmd == 0x3C or cmd == 0x3B then
506            local fr = tvb(pos + 1, 4):int()
507            if fmin == nil or fr < fmin then fmin = fr end
508            if fmax == nil or fr > fmax then fmax = fr end
509        end
510        pos = pos + evlen
511    end
512
513    return tags, fmin, fmax
514end
515
516----------------------------------------------------------------------
517-- One length-prefixed message
518----------------------------------------------------------------------
519
520-- The message body is dissected by one function that has `tvb` captured in
521-- scope, so the per-member callbacks below can read string/array values.
522
523local function dissect_message(tvb, pinfo, root, off, total, to_console)
524    local sid = stream_id()
525    local mt = root:add(p_slippi, tvb(off, total))
526
527    mt:add(f.msg_len, tvb(off, 4))
528    local body = off + 4
529    local blen = total - 4
530
531    mt:add(f.direction, tvb(off, 1),
532        to_console and "client -> console" or "console -> client"):set_generated(true)
533
534    if tvb(body, 1):uint() ~= 0x7B then
535        mt:add(f.slp_raw, tvb(body, blen)):append_text(" (not a UBJSON object)")
536        return "?"
537    end
538
539    -- We know the shape: { "type": U<n>, "payload": {...} }. Parse it with the
540    -- generic object walker but intercept the members we care about.
541    local msg_type_val = nil
542    local summary = {}
543    local on_payload_member
544
545    local function on_top(key, vm, voff, tree)
546        if key == "type" and (vm == 0x55 or vm == 0x69) then
547            local v, sz = ub_read_int(tvb, voff)
548            msg_type_val = tonumber(v)
549            tree:add(f.msg_type, tvb(voff, sz), msg_type_val)
550            return voff + sz
551        elseif key == "payload" and vm == 0x7B then
552            local pt = tree:add(p_slippi, tvb(voff, 1), "Payload")
553            local noff = ub_parse_object(tvb, voff + 1, pt, on_payload_member(pt))
554            pt:set_len(noff - voff)
555            return noff
556        end
557        return false   -- generic
558    end
559
560    -- payload member handler (needs tvb + summary + sid in scope)
561    on_payload_member = function(pt)
562        return function(key, vm, voff, tree, koff, kfull)
563            local kt = tree:add(f.ub_key, tvb(koff, kfull), key)
564
565            if key == "nick" and vm == 0x53 then
566                local slen, ssz = ub_read_int(tvb, voff + 1)
567                slen = tonumber(slen)
568                kt:add(f.nick, tvb(voff + 1 + ssz, slen))
569                summary[#summary+1] = 'nick="' .. tvb(voff + 1 + ssz, slen):string() .. '"'
570                return voff + 1 + ssz + slen
571
572            elseif key == "nintendontVersion" and vm == 0x53 then
573                local slen, ssz = ub_read_int(tvb, voff + 1)
574                slen = tonumber(slen)
575                kt:add(f.version, tvb(voff + 1 + ssz, slen))
576                summary[#summary+1] = "v" .. tvb(voff + 1 + ssz, slen):string()
577                return voff + 1 + ssz + slen
578
579            elseif (key == "clientToken") and vm == 0x5B then
580                local noff = ub_parse_array_bytes(tvb, voff + 1, kt, f.client_tok)
581                return noff
582
583            elseif key == "pos" and vm == 0x5B then
584                local noff = ub_parse_array_bytes(tvb, voff + 1, kt, f.pos)
585                return noff
586
587            elseif key == "cursor" and vm == 0x5B then
588                return ub_parse_array_bytes(tvb, voff + 1, kt, f.cursor_req)
589
590            elseif key == "nextPos" and vm == 0x5B then
591                return ub_parse_array_bytes(tvb, voff + 1, kt, f.next_pos)
592
593            elseif key == "forcePos" and (vm == 0x54 or vm == 0x46) then
594                kt:add(f.force_pos, tvb(voff, 1), vm == 0x54)
595                if vm == 0x54 then summary[#summary+1] = "forcePos" end
596                return voff + 1
597
598            elseif key == "isRealtime" and (vm == 0x54 or vm == 0x46) then
599                kt:add(f.is_realtime, tvb(voff, 1), vm == 0x54)
600                summary[#summary+1] = "realtime=" .. tostring(vm == 0x54)
601                return voff + 1
602
603            elseif key == "data" and vm == 0x5B then
604                -- [ $ U # <int count> <bytes>
605                local dstart, dlen, noff = ub_array_byte_span(tvb, voff + 1)
606                kt:add(f.data_len, tvb(voff, dstart - voff), dlen):set_generated(true)
607                if dlen > 0 then
608                    local tags, fmin, fmax = dissect_slp_stream(tvb, dstart, dlen, kt, sid, pinfo)
609                    if #tags > 0 then
610                        if fmin ~= nil then
611                            summary[#summary+1] = (fmin == fmax) and ("frame " .. fmin)
612                                or string.format("frames %d..%d", fmin, fmax)
613                        end
614                        summary[#summary+1] = "[" .. table.concat(tags, " ") .. "]"
615                    end
616                end
617                return noff
618            end
619
620            return false   -- generic rendering
621        end
622    end
623
624    local noff = ub_parse_object(tvb, body + 1, mt, on_top)
625    mt:set_len(math.max(total, noff - off))
626
627    local tname = COMM_TYPE[msg_type_val] or ("type " .. tostring(msg_type_val))
628    mt:append_text(": " .. tname)
629    return tname, summary
630end
631
632-- Helpers that need to be visible to the closures above -------------
633
634-- Parse  [ $ U # <int> <bytes>  starting at `off` (just after '['), add the
635-- bytes as `field` under `tree`. Returns next offset.
636ub_parse_array_bytes = function(tvb, off, tree, field)
637    local dstart, dlen, noff = ub_array_byte_span(tvb, off)
638    if dstart == nil then
639        -- not the optimized byte form; fall back to generic
640        return ub_parse_array(tvb, off, tree)
641    end
642    if dlen > 0 then tree:add(field, tvb(dstart, dlen)) end
643    return noff
644end
645
646-- For  $ U # <int> <bytes>  at `off` (just after '['): return
647-- data_start, data_len, next_offset  (or nil if not that shape).
648ub_array_byte_span = function(tvb, off)
649    if tvb(off, 1):uint() ~= 0x24 then return nil end       -- '$'
650    local etype = tvb(off + 1, 1):uint()
651    if tvb(off + 2, 1):uint() ~= 0x23 then return nil end    -- '#'
652    local count, csz = ub_read_int(tvb, off + 3)
653    count = tonumber(count) or 0
654    local esz = (etype == 0x55 or etype == 0x69) and 1
655        or ({ [0x49]=2, [0x6C]=4, [0x4C]=8, [0x64]=4, [0x44]=8 })[etype] or 1
656    local body = off + 3 + csz
657    return body, count * esz, body + count * esz
658end
659
660----------------------------------------------------------------------
661-- Legacy raw stream (no length prefix): whole TCP payload is .slp events
662----------------------------------------------------------------------
663
664local function dissect_legacy(tvb, pinfo, root)
665    local sid = stream_id()
666    local mt = root:add(p_slippi, tvb(), "Slippi legacy raw SLP stream")
667    mt:add(f.legacy, tvb(0,1), true):set_generated(true)
668    local tags, fmin, fmax = dissect_slp_stream(tvb, 0, tvb:len(), mt, sid, pinfo)
669    local parts = { "SLP" }
670    if fmin ~= nil then
671        parts[#parts+1] = (fmin == fmax) and ("frame " .. fmin)
672            or string.format("frames %d..%d", fmin, fmax)
673    end
674    if #tags > 0 then parts[#parts+1] = "[" .. table.concat(tags, " ") .. "]" end
675    pinfo.cols.info:set(table.concat(parts, "  "))
676end
677
678----------------------------------------------------------------------
679-- Framing / desegmentation
680----------------------------------------------------------------------
681
682local SANE_MAX = 8 * 1024 * 1024
683
684local function looks_like_prefixed(tvb, off)
685    if tvb:len() - off < 6 then return nil end        -- need len + '{' + 'i'
686    local n = tvb(off, 4):uint()
687    if n < 2 or n > SANE_MAX then return false end
688    -- UBJSON object starting with an "i"-length key ("type")
689    return tvb(off + 4, 1):uint() == 0x7B and tvb(off + 5, 1):uint() == 0x69
690end
691
692function p_slippi.dissector(tvb, pinfo, tree)
693    local n = tvb:len()
694    if n == 0 then return 0 end
695
696    pinfo.cols.protocol = "Slippi"
697    local sid = stream_id()
698    local to_console = (pinfo.dst_port == 51441 or pinfo.dst_port == 666
699        or (pinfo.dst_port >= 53741 and pinfo.dst_port <= 53750))
700
701    -- Legacy stream? decide once per TCP stream, from the first bytes we see.
702    if legacy_stream[sid] then
703        dissect_legacy(tvb, pinfo, tree)
704        return n
705    end
706    local lp = looks_like_prefixed(tvb, 0)
707    if lp == nil then
708        -- not enough bytes to tell; ask for more
709        pinfo.desegment_offset = 0
710        pinfo.desegment_len = DESEGMENT_ONE_MORE_SEGMENT
711        return n
712    end
713    if lp == false then
714        -- Heuristic: a raw SLP stream typically begins with Event Payloads
715        -- (0x35) or, mid-join, some known command byte. Treat as legacy.
716        if not to_console and SLP_CMD[tvb(0,1):uint()] ~= nil then
717            legacy_stream[sid] = true
718            dissect_legacy(tvb, pinfo, tree)
719            return n
720        end
721        -- otherwise: not our traffic
722        return 0
723    end
724
725    local off = 0
726    local summaries = {}
727    local last_type = nil
728
729    while off < n do
730        if n - off < 4 then
731            pinfo.desegment_offset = off
732            pinfo.desegment_len = DESEGMENT_ONE_MORE_SEGMENT
733            return n
734        end
735        local msglen = tvb(off, 4):uint()
736        local total = 4 + msglen
737        if msglen < 2 or msglen > SANE_MAX then
738            -- framing lost; bail rather than loop
739            tree:add(p_slippi, tvb(off, n - off), "Slippi (unframed / desync)")
740            return n
741        end
742        if n - off < total then
743            pinfo.desegment_offset = off
744            pinfo.desegment_len = total - (n - off)
745            return n
746        end
747
748        local tname, summary = dissect_message(tvb, pinfo, tree, off, total, to_console)
749        last_type = tname
750        if summary and #summary > 0 then
751            summaries[#summaries + 1] = table.concat(summary, " ")
752        end
753        off = off + total
754    end
755
756    local info = (to_console and "-> " or "") .. tostring(last_type)
757    if #summaries > 0 then info = info .. "  " .. table.concat(summaries, " | ") end
758    pinfo.cols.info:set(info)
759    return n
760end
761
762----------------------------------------------------------------------
763-- Registration
764----------------------------------------------------------------------
765
766local tcp_port = DissectorTable.get("tcp.port")
767tcp_port:add(51441, p_slippi)   -- default Wii direct
768tcp_port:add(666,   p_slippi)   -- legacy Nintendont
769for p = 53741, 53744 do tcp_port:add(p, p_slippi) end   -- relay instances
770
771-- Heuristic: catch Slippi on any TCP port (e.g. custom relay).
772local function heur(tvb, pinfo, tree)
773    if tvb:len() < 13 then return false end
774    local n = tvb(0, 4):uint()
775    if n < 8 or n > SANE_MAX then return false end
776    -- { i 04 "type" U ...
777    if tvb(4, 1):uint() ~= 0x7B then return false end
778    if tvb(5, 1):uint() ~= 0x69 then return false end
779    if tvb(6, 1):uint() ~= 0x04 then return false end
780    if tvb(7, 4):string() ~= "type" then return false end
781    pinfo.conversation = p_slippi
782    p_slippi.dissector(tvb, pinfo, tree)
783    return true
784end
785p_slippi:register_heuristic("tcp", heur)