1+ require " pcap"
2+ require " net"
13require " tostring"
24
35-- Quote a string into lua form (including the non-printable characters from
1719
1820q = quote
1921
22+ -- binary to hex
2023-- binary to hex
2124function h (s )
25+ if s == nil then
26+ return " nil"
27+ end
2228 local function hex (s )
2329 return string.format (" %02x" , string.byte (s ))
2430 end
@@ -40,3 +46,66 @@ function b(s)
4046 return s
4147end
4248
49+ function countdiff (s0 , s1 )
50+ assert (# s0 == # s1 )
51+ local count = 0
52+ for i = 1 ,# s0 do
53+ if string.byte (s0 , i ) ~= string.byte (s1 , i ) then
54+ count = count + 1
55+ end
56+ end
57+ return count
58+ end
59+
60+ function assertmostlyeql (threshold , s0 , s1 )
61+ assert (# s0 == # s1 )
62+ local diff = countdiff (s0 , s1 )
63+ assert (diff <= threshold , diff )
64+ end
65+
66+ function pcapreencode (incap , outcap )
67+ if not outcap then
68+ outcap = " reencoded-" .. incap
69+ end
70+ os.remove (outcap )
71+
72+ local cap = assert (pcap .open_offline (incap ))
73+ local dmp = assert (cap :dump_open (outcap ))
74+ local n = assert (net .init ())
75+ local i = 0
76+ for pkt , time , len in cap .next , cap do
77+ i = i + 1
78+ print (" packet" , i , " wirelen" , len , " timestamp" , time , os.date (" !%c" , time ))
79+ assert (n :clear ())
80+ assert (n :decode_eth (pkt ))
81+ assert (dmp :dump (n :block (), time , len ))
82+ end
83+ -- FIXME assert(i > 0)
84+ dmp :close ()
85+ cap :close ()
86+ n :destroy ()
87+ return outcap
88+ end
89+
90+ function assertpcapsimilar (threshold , file0 , file1 )
91+ local n0 = assert (net .init ())
92+ local n1 = assert (net .init ())
93+ local cap0 = assert (pcap .open_offline (file0 ))
94+ local cap1 = assert (pcap .open_offline (file1 ))
95+ local i = 0
96+ for pkt0 , time0 , len0 in cap0 .next , cap0 do
97+ local pkt1 , time1 , len1 = assert (cap1 :next ())
98+ i = i + 1
99+
100+ print (" packet0" , i , " wirelen" , len0 , " timestamp" , time0 , os.date (" !%c" , time0 ))
101+ print (" packet1" , i , " wirelen" , len1 , " timestamp" , time1 , os.date (" !%c" , time1 ))
102+
103+ assert (len0 == len1 )
104+ assert (time0 == time1 , string.format (" %.7f ~= %.7f" , time0 , time1 ))
105+ assertmostlyeql (threshold , pkt0 , pkt1 )
106+ end
107+ assert (cap1 :next () == nil )
108+ n0 :destroy ()
109+ n1 :destroy ()
110+ end
111+
0 commit comments