1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
|
#!/usr/bin/env python
#-----------------------------------------------------------------------------
# Copyright (c) 2008 by David P. D. Moss. All rights reserved.
#
# Released under the BSD license. See the LICENSE file for details.
#-----------------------------------------------------------------------------
#
# DISCLAIMER
#
# netaddr is not sponsored nor endorsed by the IEEE.
#
# Use of data from the IEEE (Institute of Electrical and Electronics
# Engineers) is subject to copyright. See the following URL for
# details :-
#
# - http://www.ieee.org/web/publications/rights/legal.html
#
# IEEE data files included with netaddr are not modified in any way but are
# parsed and made available to end users through an API. There is no
# guarantee that referenced files are not out of date.
#
# See README file and source code for URLs to latest copies of the relevant
# files.
#
#-----------------------------------------------------------------------------
"""
Provides access to public OUI and IAB registration data published by the IEEE.
More details can be found at the following URLs :-
- IEEE Home Page - http://www.ieee.org/
- Registration Authority Home Page - http://standards.ieee.org/regauth/
"""
import os.path as _path
import csv as _csv
from netaddr.compat import _bytes_type, _open_binary
from netaddr.core import Subscriber, Publisher
#: OUI index lookup dictionary.
OUI_INDEX = {}
#: IAB index lookup dictionary.
IAB_INDEX = {}
class FileIndexer(Subscriber):
"""
A concrete Subscriber that receives OUI record offset information that is
written to an index data file as a set of comma separated records.
"""
def __init__(self, index_file):
"""
Constructor.
:param index_file: a file-like object or name of index file where
index records will be written.
"""
if hasattr(index_file, 'readline') and hasattr(index_file, 'tell'):
self.fh = index_file
else:
self.fh = open(index_file, 'w')
self.writer = _csv.writer(self.fh, lineterminator="\n")
def update(self, data):
"""
Receives and writes index data to a CSV data file.
:param data: record containing offset record information.
"""
self.writer.writerow(data)
class OUIIndexParser(Publisher):
"""
A concrete Publisher that parses OUI (Organisationally Unique Identifier)
records from IEEE text-based registration files
It notifies registered Subscribers as each record is encountered, passing
on the record's position relative to the start of the file (offset) and
the size of the record (in bytes).
The file processed by this parser is available online from this URL :-
- http://standards.ieee.org/regauth/oui/oui.txt
This is a sample of the record structure expected::
00-CA-FE (hex) ACME CORPORATION
00CAFE (base 16) ACME CORPORATION
1 MAIN STREET
SPRINGFIELD
UNITED STATES
"""
def __init__(self, ieee_file):
"""
Constructor.
:param ieee_file: a file-like object or name of file containing OUI
records. When using a file-like object always open it in binary
mode otherwise offsets will probably misbehave.
"""
super(OUIIndexParser, self).__init__()
if hasattr(ieee_file, 'readline') and hasattr(ieee_file, 'tell'):
self.fh = ieee_file
else:
self.fh = open(ieee_file, 'rb')
def parse(self):
"""
Starts the parsing process which detects records and notifies
registered subscribers as it finds each OUI record.
"""
skip_header = True
record = None
size = 0
marker = _bytes_type('(hex)')
hyphen = _bytes_type('-')
empty_string = _bytes_type('')
while True:
line = self.fh.readline()
if not line:
break # EOF, we're done
if skip_header and marker in line:
skip_header = False
if skip_header:
# ignoring header section
continue
if marker in line:
# record start
if record is not None:
# a complete record.
record.append(size)
self.notify(record)
size = len(line)
offset = (self.fh.tell() - len(line))
oui = line.split()[0]
index = int(oui.replace(hyphen, empty_string), 16)
record = [index, offset]
else:
# within record
size += len(line)
# process final record on loop exit
record.append(size)
self.notify(record)
class IABIndexParser(Publisher):
"""
A concrete Publisher that parses IAB (Individual Address Block) records
from IEEE text-based registration files
It notifies registered Subscribers as each record is encountered, passing
on the record's position relative to the start of the file (offset) and
the size of the record (in bytes).
The file processed by this parser is available online from this URL :-
- http://standards.ieee.org/regauth/oui/iab.txt
This is a sample of the record structure expected::
00-50-C2 (hex) ACME CORPORATION
ABC000-ABCFFF (base 16) ACME CORPORATION
1 MAIN STREET
SPRINGFIELD
UNITED STATES
"""
def __init__(self, ieee_file):
"""
Constructor.
:param ieee_file: a file-like object or name of file containing IAB
records. When using a file-like object always open it in binary
mode otherwise offsets will probably misbehave.
"""
super(IABIndexParser, self).__init__()
if hasattr(ieee_file, 'readline') and hasattr(ieee_file, 'tell'):
self.fh = ieee_file
else:
self.fh = open(ieee_file, 'rb')
def parse(self):
"""
Starts the parsing process which detects records and notifies
registered subscribers as it finds each IAB record.
"""
skip_header = True
record = None
size = 0
hex_marker = _bytes_type('(hex)')
base16_marker = _bytes_type('(base 16)')
hyphen = _bytes_type('-')
empty_string = _bytes_type('')
while True:
line = self.fh.readline()
if not line:
break # EOF, we're done
if skip_header and hex_marker in line:
skip_header = False
if skip_header:
# ignoring header section
continue
if hex_marker in line:
# record start
if record is not None:
record.append(size)
self.notify(record)
offset = (self.fh.tell() - len(line))
iab_prefix = line.split()[0]
index = iab_prefix
record = [index, offset]
size = len(line)
elif base16_marker in line:
# within record
size += len(line)
prefix = record[0].replace(hyphen, empty_string)
suffix = line.split()[0]
suffix = suffix.split(hyphen)[0]
record[0] = (int(prefix + suffix, 16)) >> 12
else:
# within record
size += len(line)
# process final record on loop exit
record.append(size)
self.notify(record)
def create_index_from_registry(registry_fh, index_path, parser):
"""Generate an index files from the IEEE registry file."""
oui_parser = parser(registry_fh)
oui_parser.attach(FileIndexer(index_path))
oui_parser.parse()
def create_indices():
"""Create indices for OUI and IAB file based lookups"""
create_index_from_registry(
_path.join(_path.dirname(__file__), 'oui.txt'),
_path.join(_path.dirname(__file__), 'oui.idx'),
OUIIndexParser,
)
create_index_from_registry(
_path.join(_path.dirname(__file__), 'iab.txt'),
_path.join(_path.dirname(__file__), 'iab.idx'),
IABIndexParser,
)
def load_index(index, fp):
"""Load index from file into index data structure."""
try:
for row in _csv.reader([x.decode('UTF-8') for x in fp]):
(key, offset, size) = [int(_) for _ in row]
index.setdefault(key, [])
index[key].append((offset, size))
finally:
fp.close()
def load_indices():
"""Load OUI and IAB lookup indices into memory"""
load_index(OUI_INDEX, _open_binary(__package__, 'oui.idx'))
load_index(IAB_INDEX, _open_binary(__package__, 'iab.idx'))
if __name__ == '__main__':
# Generate indices when module is executed as a script.
create_indices()
else:
# On module load read indices in memory to enable lookups.
load_indices()
|