forked from sherpya/ris-linux
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinfparser.py
More file actions
executable file
·331 lines (272 loc) · 10.6 KB
/
infparser.py
File metadata and controls
executable file
·331 lines (272 loc) · 10.6 KB
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
#!/usr/bin/env python3
# -*- Mode: Python; tab-width: 4 -*-
#
# Inf Driver parser
#
# Copyright (C) 2005-2007 Gianluigi Tiesi <sherpya@netfarm.it>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTIBILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
# ======================================================================
from codecs import utf_16_le_decode, BOM_LE, BOM_BE
from sys import argv, exit as sys_exit
from os.path import isfile
from glob import glob
from pickle import dump
from traceback import format_exc
__version__ = '1.0'
class_guids = ['{4d36e972-e325-11ce-bfc1-08002be10318}']
classes = ['net']
exclude = ['layout.inf', 'drvindex.inf', 'netclass.inf']
debug = 0
dumpdev = 0
bustype = { 'USB' : 1,
'PCI' : 5,
'PCMCIA': 8,
'ISAPNP': 14
}
def csv2list(value):
values = value.strip().split(',')
for i in range(len(values)):
values[i] = values[i].strip()
return values
def str_lookup(dc, c_key):
for key, value in dc.items():
if key.lower() == c_key.lower():
if value:
return value.pop()
return 'NoDesc'
def item_lookup(dc, c_key):
for key, value in dc.items():
if key.lower() == c_key.lower():
return value
return None
def fuzzy_lookup(strlist, pattern, ends=None):
for s in strlist:
if ends is not None and not s.endswith('services'): continue
if s.startswith(pattern): return s
return None
def unquote(text):
return ''.join(text.split('"'))
def skip_inf(line):
## Check if driver is requested
if line.find('=') == -1: return False
key, value = line.split('=', 1)
key = key.strip().lower()
value = value.strip().lower()
if key == 'class' and value not in classes: return True
if key == 'classguid' and value not in class_guids: return True
return False
def parse_line(sections, secname, lineno, line):
equal = line.find('=')
comma = line.find(',')
if equal + comma != -2:
if equal == -1:
equal = comma+1
if comma == -1:
comma = equal+1
if debug > 2: print(f'[{lineno}] [{secname}] equal = {equal} - comma = {comma}')
if len(line) + equal + comma == -1:
if debug: print(f'[{lineno}] [{secname}] Invalid line')
return True
### Values
if equal < comma:
if not isinstance(sections[secname], dict):
sections[secname] = {}
section = sections[secname]
key, value = line.split('=', 1)
key = key.strip()
### SkipList
if key == '0':return True
if key in section:
values = csv2list(value)
### SkipList
if (len(values) < 2) or (value.find('VEN_') == -1) or (value.find('DEV_') == -1):
return True
oldkey = key
key = key + '_dev_' + values[1]
if debug > 1:
print(f'[{lineno}] [{secname}] Duplicate key {oldkey} will be renamed to {key}')
if secname == 'manufacturer':
mlist = value.strip().split(',')
mf = mlist[0].strip().lower()
if len(mlist) > 1:
ml = []
for m in mlist[1:]:
ml.append('.'.join([mf, m.strip().lower()]))
mlist = [mf] + ml
else:
mlist = [mf]
if debug > 0: print('Preprocessing Manifacturers:', ', '.join(mlist))
section[key] = mlist
if debug > 0: print(f'Manifacturer {key}={section[key]}')
return True
section[key] = csv2list(value)
if debug > 1: print(f'[K] [{lineno}] [{secname}] {key}={section[key]}')
return True
values = csv2list(line)
if debug > 1: print(f'[V] [{lineno}] [{secname}] Values = {",".join(values)}')
sections[secname] = values
return True
def parse_inf(filename):
lineno = 0
name = ''
sections = {}
section = None
data = open(filename, 'rb').read()
## Cheap Unicode to ascii
if data[:2] == BOM_LE or data[:2] == BOM_BE:
data = utf_16_le_decode(data)[0]
data = data.encode('ascii', 'ignore')
data = data.decode('ascii', 'ignore')
## De-inf fixer ;)
data = 'Copy'.join(data.split(';Cpy'))
data = '\n'.join(data.split('\r\n'))
data = ''.join(data.split('\\\n'))
for line in data.split('\n'):
lineno = lineno + 1
line = line.strip()
line = line.split(';', 1)[0]
line = line.strip()
if len(line) < 1: continue # empty lines
if line[0] == ';': continue # comment
## We only need network drivers
if name == 'version' and skip_inf(line):
if debug > 0: print(f'Skipped {filename} not a network inf')
return None
## Section start
if line.startswith('[') and line.endswith(']'):
name = line[1:-1].lower()
sections[name] = {}
section = sections[name]
else:
if section is None: continue
if not parse_line(sections, name, lineno, line):
break
return sections
def scan_inf(filename):
if debug > 0: print('Parsing ', filename)
inf = parse_inf(filename)
if inf is None: return {}
devices = {}
if inf and 'manufacturer' in inf:
devlist = sum(inf['manufacturer'].values(), [])
if debug > 0: print('Devlist:', ', '.join(devlist))
for devmap in devlist:
devmap_k = unquote(devmap.lower())
if devmap_k not in inf:
if debug > 0: print(f'Warning: missing [{devmap}] driver section in {filename}, ignored')
continue
devmap = devmap_k
for dev in inf[devmap]:
if dev.find('%') == -1: continue # bad infs
device = dev.split('%')[1]
desc = unquote(str_lookup(inf['strings'], device))
sec = inf[devmap][dev][0]
hid = inf[devmap][dev][1]
sec = sec.lower()
hid = hid.upper()
if sec in inf:
mainsec = sec
else:
mainsec = fuzzy_lookup(inf.keys(), sec)
if mainsec is None: continue
if mainsec.endswith('.services') and mainsec in inf:
serv_sec = mainsec
elif mainsec + '.services' in inf:
serv_sec = mainsec + '.services'
else:
serv_sec = fuzzy_lookup(inf.keys(), mainsec.split('.')[0], '.services')
if serv_sec is None:
if debug > 0: print(f'Service section for {mainsec} not found, skipping...')
continue
if hid in devices: continue # Multiple sections define same devices
if dumpdev: print('Desc:', desc)
if dumpdev: print('hid:', hid)
tmp = item_lookup(inf[serv_sec], 'addservice')
if tmp is None:
if debug > 0: print(f'Warning: addservice not found {serv_sec}')
continue
service = tmp[0]
sec_service = tmp[2]
driver = None
if (type(inf[mainsec]) == type({})
and 'copyfiles' in inf[mainsec]):
sec_files = inf[mainsec]['copyfiles'][0].lower()
if type(inf[sec_files]) == type([]):
driver = inf[sec_files][0]
if driver is None:
if sec_service.lower() not in inf:
print(f'Warning missing ServiceBinary for {sec_service}')
#print(f'Please report including this file: {filename}\n')
continue
driver = inf[sec_service.lower()]['ServiceBinary'][0].split('\\').pop()
if dumpdev: print('Driver', driver)
try:
char = eval(inf[mainsec]['Characteristics'][0])
except:
char = 132
if dumpdev: print('Characteristics', char)
try:
btype = int(inf[mainsec]['BusType'][0])
except:
try:
btype = bustype[hid.split('\\')[0]]
except:
btype = 0
if dumpdev: print('BusType', btype)
if dumpdev: print('Service', service)
if dumpdev: print('-'*78)
devices[hid] = { 'desc' : desc,
'char' : str(char),
'btype': str(btype),
'drv' : driver,
'svc' : service,
'inf' : filename.split('/').pop() }
return devices
if __name__ == '__main__':
if len(argv) != 2:
print(f'Usage {argv[0]}: directory_with_infs or inf file')
sys_exit(-1)
if isfile(argv[1]):
filelist = [ argv[1] ]
else:
filelist = glob(argv[1] + '/*.inf')
devlist = {}
for inffile in filelist:
if inffile.split('/').pop() not in exclude:
try:
devlist.update(scan_inf(inffile))
except:
print('--')
print('Error parsing', inffile)
#print('Please report sending the inf file and this message:')
print('---- CUT HERE ----')
print(f'{argv[0]} Version {__version__}\n')
print(format_exc())
print('---- CUT HERE ----')
print(f'Compiled {len(devlist)} drivers')
fd = open('devlist.cache', 'wb')
dump(devlist, fd)
fd.close()
print('generated devlist.cache')
fd = open('nics.txt', 'w')
drvhash = {}
for nic, desc in devlist.items():
entry = nic.split('&')
if len(entry) < 2: continue # just to be sure
if not entry[0].startswith('PCI'): continue # skip usb
vid = entry[0].split('VEN_').pop().lower()
pid = entry[1].split('DEV_').pop().lower()
key = (vid, pid)
line = f'{vid:4} {pid:4} {desc["drv"]} {desc["svc"]}\n'
drvhash[key] = line
fd.writelines(sorted(drvhash.values()))
fd.close()
print('generated nics.txt')