3131import gflags
3232import re
3333import struct
34+ import tempfile
35+ import os
36+ from scapy .all import RawPcapWriter , RawPcapReader
3437from usbrevue import Packet
3538
3639
@@ -56,7 +59,6 @@ def __init__(self, module_file, routine_file, cmdline_exps):
5659 self .routine_file = routine_file
5760 self .cmdline_exps = cmdline_exps
5861
59-
6062 def run (self ):
6163 """If a user-supplied module file is present, simply run that
6264 module. Otherwise, Pass each packet from the packet stream
@@ -102,12 +104,13 @@ def packet_generator(self, input_stream='-'):
102104 self .pcap = pcapy .open_offline (input_stream )
103105
104106 # create the Dumper object now that we have a Reader
105- self .out = self .pcap .dump_open ('-' )
107+ if not sys .stdout .isatty ():
108+ self .out = self .pcap .dump_open ('-' )
106109
107110 while True :
108111 (hdr , pack ) = self .pcap .next ()
109112 if hdr is None :
110- return # EOF
113+ return # EOF
111114 # keep track of the most recent yielding packet, for diffing
112115 self .orig_packet = Packet (hdr , pack )
113116 yield Packet (hdr , pack )
@@ -135,8 +138,28 @@ def commit_packet(self, packet):
135138 sys .stderr .write ('Attempted to dump packets without first reading them -- make sure to call packet_generator()' )
136139 sys .exit (1 )
137140 else :
141+ # make a temp file, use scapy's RawPcapWriter to write the
142+ # current packet to that file, then read that same packet
143+ # in using a new instance of pcapy.open_offline, then
144+ # write out to stdout the packet that we just read back
145+ # in, then finally delete the temp file
146+ #
147+ # we have to do it this way in case the size of the packet
148+ # changed, in which case the packet's pcap header needs to
149+ # be regenerated. RawPcapWriter does this for us
150+ #
151+ # on reflection, it would be pretty straightforward to
152+ # copy RawPcapWriter's code for generating the pcap
153+ # header(s) and do it ourselves, without the messy temp
154+ # file stuff. this code should be re-worked to do that.
155+ temp = tempfile .mkstemp ()
156+ rpw = RawPcapWriter (temp [1 ], linktype = 220 , sync = True )
157+ rpw .write (packet .repack ())
158+ mypcap = pcapy .open_offline (temp [1 ])
159+ (myhdr , mypack ) = mypcap .next ()
138160 if not sys .stdout .isatty ():
139- self .out .dump (packet .hdr , packet .datapack )
161+ self .out .dump (myhdr , mypack )
162+ os .remove (temp [1 ])
140163
141164
142165 def apply_routine_file (self , packet ):
0 commit comments