1 # Copyright (C) 2015 Nippon Telegraph and Telephone Corporation.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
17 Parsing libpcap and reading/writing PCAP file.
18 Reference source: http://wiki.wireshark.org/Development/LibpcapFileFormat
23 +---------------------+
27 +---------------------+
29 +---------------------+
31 +---------------------+
33 +---------------------+
35 +---------------------+
37 +---------------------+
45 class PcapFileHdr(object):
48 typedef struct pcap_hdr_s {
49 guint32 magic_number; /* magic number */
50 guint16 version_major; /* major version number */
51 guint16 version_minor; /* minor version number */
52 gint32 thiszone; /* GMT to local correction */
53 guint32 sigfigs; /* accuracy of timestamps */
54 guint32 snaplen; /* max length of captured packets,
56 guint32 network; /* data link type */
60 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
61 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
63 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
64 | Version Major | Version Minor |
65 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
67 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
69 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
71 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
73 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
76 _FILE_HDR_FMT = '4sHHIIII'
77 _FILE_HDR_FMT_BIG_ENDIAN = '>' + _FILE_HDR_FMT
78 _FILE_HDR_FMT_LITTLE_ENDIAN = '<' + _FILE_HDR_FMT
79 FILE_HDR_SIZE = struct.calcsize(_FILE_HDR_FMT)
81 # Magic Number field is used to detect the file format itself and
83 MAGIC_NUMBER_IDENTICAL = b'\xa1\xb2\xc3\xd4' # Big Endian
84 MAGIC_NUMBER_SWAPPED = b'\xd4\xc3\xb2\xa1' # Little Endian
86 def __init__(self, magic=MAGIC_NUMBER_SWAPPED, version_major=2,
87 version_minor=4, thiszone=0, sigfigs=0, snaplen=0,
90 self.version_major = version_major
91 self.version_minor = version_minor
92 self.thiszone = thiszone
93 self.sigfigs = sigfigs
94 self.snaplen = snaplen
95 self.network = network
100 if magic_buf == cls.MAGIC_NUMBER_IDENTICAL:
102 fmt = cls._FILE_HDR_FMT_BIG_ENDIAN
104 elif magic_buf == cls.MAGIC_NUMBER_SWAPPED:
106 fmt = cls._FILE_HDR_FMT_LITTLE_ENDIAN
109 raise struct.error('Invalid byte ordered pcap file.')
111 return cls(*struct.unpack_from(fmt, buf)), byteorder
114 if sys.byteorder == 'big':
116 fmt = self._FILE_HDR_FMT_BIG_ENDIAN
117 self.magic = self.MAGIC_NUMBER_IDENTICAL
120 fmt = self._FILE_HDR_FMT_LITTLE_ENDIAN
121 self.magic = self.MAGIC_NUMBER_SWAPPED
123 return struct.pack(fmt, self.magic, self.version_major,
124 self.version_minor, self.thiszone,
125 self.sigfigs, self.snaplen, self.network)
128 class PcapPktHdr(object):
130 Record (Packet) Header
131 typedef struct pcaprec_hdr_s {
132 guint32 ts_sec; /* timestamp seconds */
133 guint32 ts_usec; /* timestamp microseconds */
134 guint32 incl_len; /* number of octets of packet
136 guint32 orig_len; /* actual length of packet */
140 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
141 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
142 | Timestamp Seconds |
143 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
144 | Timestamp Microseconds |
145 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
146 | Number of octets of saved in file |
147 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
148 | Actual length of packet |
149 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
150 Record (Packet) Header Format
153 _PKT_HDR_FMT = 'IIII'
154 _PKT_HDR_FMT_BIG_ENDIAN = '>' + _PKT_HDR_FMT
155 _PKT_HDR_FMT_LITTLE_ENDIAN = '<' + _PKT_HDR_FMT
156 PKT_HDR_SIZE = struct.calcsize(_PKT_HDR_FMT)
158 def __init__(self, ts_sec=0, ts_usec=0, incl_len=0, orig_len=0):
160 self.ts_usec = ts_usec
161 self.incl_len = incl_len
162 self.orig_len = orig_len
165 def parser(cls, buf, byteorder='little'):
167 raise IndexError('No data')
169 if byteorder == 'big':
171 fmt = cls._PKT_HDR_FMT_BIG_ENDIAN
174 fmt = cls._PKT_HDR_FMT_LITTLE_ENDIAN
176 (ts_sec, ts_usec, incl_len, orig_len) = struct.unpack_from(fmt, buf)
177 hdr = cls(ts_sec, ts_usec, incl_len, orig_len)
179 return hdr, buf[cls.PKT_HDR_SIZE:cls.PKT_HDR_SIZE + incl_len]
182 if sys.byteorder == 'big':
184 fmt = self._PKT_HDR_FMT_BIG_ENDIAN
187 fmt = self._PKT_HDR_FMT_LITTLE_ENDIAN
189 return struct.pack(fmt, self.ts_sec, self.ts_usec,
190 self.incl_len, self.orig_len)
193 class Reader(object):
197 ================ ===================================
199 ================ ===================================
200 file_obj File object which reading PCAP file
202 ================ ===================================
206 from ryu.lib import pcaplib
207 from ryu.lib.packet import packet
210 # iterate pcaplib.Reader that yields (timestamp, packet_data)
212 for ts, buf in pcaplib.Reader(open('test.pcap', 'rb')):
214 pkt = packet.Packet(buf)
215 print("%d, %f, %s" % (frame_count, ts, pkt))
218 def __init__(self, file_obj):
220 buf = self._fp.read(PcapFileHdr.FILE_HDR_SIZE)
221 # Read only pcap file header
222 self.pcap_header, self._file_byteorder = PcapFileHdr.parser(buf)
223 # Read pcap data with out header
224 self._pcap_body = self._fp.read()
233 pkt_hdr, pkt_data = PcapPktHdr.parser(
234 self._pcap_body[self._next_pos:], self._file_byteorder)
235 self._next_pos += pkt_hdr.incl_len + PcapPktHdr.PKT_HDR_SIZE
238 raise StopIteration()
240 return pkt_hdr.ts_sec + (pkt_hdr.ts_usec / 1e6), pkt_data
242 # for Python 3 compatible
246 class Writer(object):
250 ========== ==================================================
252 ========== ==================================================
253 file_obj File object which writing PCAP file in binary mode
254 snaplen Max length of captured packets (in octets)
255 network Data link type. (e.g. 1 for Ethernet,
256 see `tcpdump.org`_ for details)
257 ========== ==================================================
259 .. _tcpdump.org: http://www.tcpdump.org/linktypes.html
264 from ryu.lib import pcaplib
267 class SimpleSwitch13(app_manager.RyuApp):
268 OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]
270 def __init__(self, *args, **kwargs):
271 super(SimpleSwitch13, self).__init__(*args, **kwargs)
272 self.mac_to_port = {}
274 # Create pcaplib.Writer instance with a file object
276 self.pcap_writer = pcaplib.Writer(open('mypcap.pcap', 'wb'))
280 @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
281 def _packet_in_handler(self, ev):
282 # Dump the packet data into PCAP file
283 self.pcap_writer.write_pkt(ev.msg.data)
288 def __init__(self, file_obj, snaplen=65535, network=1):
290 self.snaplen = snaplen
291 self.network = network
292 self._write_pcap_file_hdr()
294 def _write_pcap_file_hdr(self):
295 pcap_file_hdr = PcapFileHdr(snaplen=self.snaplen,
296 network=self.network)
297 self._f.write(pcap_file_hdr.serialize())
299 def _write_pkt_hdr(self, ts, buf_len):
301 usec = int(round(ts % 1, 6) * 1e6) if sec != 0 else 0
303 pc_pkt_hdr = PcapPktHdr(ts_sec=sec, ts_usec=usec,
304 incl_len=buf_len, orig_len=buf_len)
306 self._f.write(pc_pkt_hdr.serialize())
308 def write_pkt(self, buf, ts=None):
309 ts = time.time() if ts is None else ts
311 # Check the max length of captured packets
313 if buf_len > self.snaplen:
314 buf_len = self.snaplen
315 buf = buf[:self.snaplen]
317 self._write_pkt_hdr(ts, buf_len)