backing up
[vsorcdistro/.git] / ryu / build / lib.linux-armv7l-2.7 / ryu / lib / pcaplib.py
1 # Copyright (C) 2015 Nippon Telegraph and Telephone Corporation.
2 #
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
6 #
7 #    http://www.apache.org/licenses/LICENSE-2.0
8 #
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
12 # implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16 """
17 Parsing libpcap and reading/writing PCAP file.
18 Reference source: http://wiki.wireshark.org/Development/LibpcapFileFormat
19
20
21                   Libpcap File Format
22
23                 +---------------------+
24                 |                     |
25                 |     Global Header   |
26                 |                     |
27                 +---------------------+
28                 |     Packet Header   |
29                 +---------------------+
30                 |     Packet Data     |
31                 +---------------------+
32                 |     Packet Header   |
33                 +---------------------+
34                 |     Packet Data     |
35                 +---------------------+
36                 |          ...        |
37                 +---------------------+
38 """
39
40 import struct
41 import sys
42 import time
43
44
45 class PcapFileHdr(object):
46     """
47     Global Header
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,
55                                            in octets */
56                 guint32 network;        /* data link type */
57     } pcap_hdr_t;
58
59     0                   1                   2                   3
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     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
62     |                          Magic Number                         |
63     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
64     |        Version Major          |        Version Minor          |
65     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
66     |                            Thiszone                           |
67     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
68     |                            Sigfigs                            |
69     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
70     |                            Snaplen                            |
71     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
72     |                            Network                            |
73     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
74                                 File Format
75     """
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)
80
81     # Magic Number field is used to detect the file format itself and
82     # the byte ordering.
83     MAGIC_NUMBER_IDENTICAL = b'\xa1\xb2\xc3\xd4'  # Big Endian
84     MAGIC_NUMBER_SWAPPED = b'\xd4\xc3\xb2\xa1'    # Little Endian
85
86     def __init__(self, magic=MAGIC_NUMBER_SWAPPED, version_major=2,
87                  version_minor=4, thiszone=0, sigfigs=0, snaplen=0,
88                  network=0):
89         self.magic = magic
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
96
97     @classmethod
98     def parser(cls, buf):
99         magic_buf = buf[:4]
100         if magic_buf == cls.MAGIC_NUMBER_IDENTICAL:
101             # Big Endian
102             fmt = cls._FILE_HDR_FMT_BIG_ENDIAN
103             byteorder = 'big'
104         elif magic_buf == cls.MAGIC_NUMBER_SWAPPED:
105             # Little Endian
106             fmt = cls._FILE_HDR_FMT_LITTLE_ENDIAN
107             byteorder = 'little'
108         else:
109             raise struct.error('Invalid byte ordered pcap file.')
110
111         return cls(*struct.unpack_from(fmt, buf)), byteorder
112
113     def serialize(self):
114         if sys.byteorder == 'big':
115             # Big Endian
116             fmt = self._FILE_HDR_FMT_BIG_ENDIAN
117             self.magic = self.MAGIC_NUMBER_IDENTICAL
118         else:
119             # Little Endian
120             fmt = self._FILE_HDR_FMT_LITTLE_ENDIAN
121             self.magic = self.MAGIC_NUMBER_SWAPPED
122
123         return struct.pack(fmt, self.magic, self.version_major,
124                            self.version_minor, self.thiszone,
125                            self.sigfigs, self.snaplen, self.network)
126
127
128 class PcapPktHdr(object):
129     """
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
135                                      saved in file */
136             guint32 orig_len;     /* actual length of packet */
137     } pcaprec_hdr_t;
138
139     0                   1                   2                   3
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
151     """
152
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)
157
158     def __init__(self, ts_sec=0, ts_usec=0, incl_len=0, orig_len=0):
159         self.ts_sec = ts_sec
160         self.ts_usec = ts_usec
161         self.incl_len = incl_len
162         self.orig_len = orig_len
163
164     @classmethod
165     def parser(cls, buf, byteorder='little'):
166         if not buf:
167             raise IndexError('No data')
168
169         if byteorder == 'big':
170             # Big Endian
171             fmt = cls._PKT_HDR_FMT_BIG_ENDIAN
172         else:
173             # Little Endian
174             fmt = cls._PKT_HDR_FMT_LITTLE_ENDIAN
175
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)
178
179         return hdr, buf[cls.PKT_HDR_SIZE:cls.PKT_HDR_SIZE + incl_len]
180
181     def serialize(self):
182         if sys.byteorder == 'big':
183             # Big Endian
184             fmt = self._PKT_HDR_FMT_BIG_ENDIAN
185         else:
186             # Little Endian
187             fmt = self._PKT_HDR_FMT_LITTLE_ENDIAN
188
189         return struct.pack(fmt, self.ts_sec, self.ts_usec,
190                            self.incl_len, self.orig_len)
191
192
193 class Reader(object):
194     """
195     PCAP file reader
196
197     ================ ===================================
198     Argument         Description
199     ================ ===================================
200     file_obj         File object which reading PCAP file
201                      in binary mode
202     ================ ===================================
203
204     Example of usage::
205
206         from ryu.lib import pcaplib
207         from ryu.lib.packet import packet
208
209         frame_count = 0
210         # iterate pcaplib.Reader that yields (timestamp, packet_data)
211         # in the PCAP file
212         for ts, buf in pcaplib.Reader(open('test.pcap', 'rb')):
213             frame_count += 1
214             pkt = packet.Packet(buf)
215             print("%d, %f, %s" % (frame_count, ts, pkt))
216     """
217
218     def __init__(self, file_obj):
219         self._fp = 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()
225         self._fp.close()
226         self._next_pos = 0
227
228     def __iter__(self):
229         return self
230
231     def next(self):
232         try:
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
236
237         except IndexError:
238             raise StopIteration()
239
240         return pkt_hdr.ts_sec + (pkt_hdr.ts_usec / 1e6), pkt_data
241
242     # for Python 3 compatible
243     __next__ = next
244
245
246 class Writer(object):
247     """
248     PCAP file writer
249
250     ========== ==================================================
251     Argument   Description
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     ========== ==================================================
258
259     .. _tcpdump.org: http://www.tcpdump.org/linktypes.html
260
261     Example of usage::
262
263         ...
264         from ryu.lib import pcaplib
265
266
267         class SimpleSwitch13(app_manager.RyuApp):
268             OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]
269
270             def __init__(self, *args, **kwargs):
271                 super(SimpleSwitch13, self).__init__(*args, **kwargs)
272                 self.mac_to_port = {}
273
274                 # Create pcaplib.Writer instance with a file object
275                 # for the PCAP file
276                 self.pcap_writer = pcaplib.Writer(open('mypcap.pcap', 'wb'))
277
278             ...
279
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)
284
285                 ...
286     """
287
288     def __init__(self, file_obj, snaplen=65535, network=1):
289         self._f = file_obj
290         self.snaplen = snaplen
291         self.network = network
292         self._write_pcap_file_hdr()
293
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())
298
299     def _write_pkt_hdr(self, ts, buf_len):
300         sec = int(ts)
301         usec = int(round(ts % 1, 6) * 1e6) if sec != 0 else 0
302
303         pc_pkt_hdr = PcapPktHdr(ts_sec=sec, ts_usec=usec,
304                                 incl_len=buf_len, orig_len=buf_len)
305
306         self._f.write(pc_pkt_hdr.serialize())
307
308     def write_pkt(self, buf, ts=None):
309         ts = time.time() if ts is None else ts
310
311         # Check the max length of captured packets
312         buf_len = len(buf)
313         if buf_len > self.snaplen:
314             buf_len = self.snaplen
315             buf = buf[:self.snaplen]
316
317         self._write_pkt_hdr(ts, buf_len)
318
319         self._f.write(buf)
320
321     def __del__(self):
322         self._f.close()