~nilsschlupp/auto-ndiswrapper/rewrite

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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
#!/usr/bin/env python

#Auto-NDISwrapper by Nils Schulupp, Gabriel J. Perez and Richard Kaufman
#
#This program automatically looks at what Wi-Fi card you have, it disables any wireless driver currently installed, fetches #the correct Windows driver from the Internet and installs it with NDISwrapper.

#Copyright (C) 2007, 2008 Gabriel J. Perez <gabrieljoel@gmail.com>, Nils Schulupp <nils.schlupp@gmail.com> and Richard Kaufman <richardbkaufman@gmail.com>
#
#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 of the License, 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
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

"""Auto-NDISwrapper -- Linux Wi-Fi as easy as it can get"""

__version__ = '0.0.1'

import os, platform, sys, re, subprocess
from database import data
from ConfigParser import ConfigParser
from optparse import OptionParser
sys.path.append(os.getcwd())

print 'Auto-NDISwrapper %s' % (__version__, )

##Parse options
parser = OptionParser(version='version: '+__version__)
parser.add_option('--ndiswrapper-bin', default='/usr/sbin/ndiswrapper', help='default: %default', metavar='FILE')
parser.add_option('-t', '--tmp-dir', default='/tmp/auto-ndis', help='default: %default', metavar='DIR')
parser.add_option('-a', '--ask', action='store_true', default=False, help='ask for confirmation')
parser.add_option('-q', '--quiet', action='store_true', default=False, help='reduce some output')
parser.add_option('--nocheck', action='store_true', default=False, help='doesnt check for ndiswrapper binary (debug only)')
parser.add_option('-d', '--debug', action='store_true', default=False, help='turn on debugging output')
opts, args = parser.parse_args()

##If the user isn't root the program will quit
if os.geteuid() != 0:
  	print '[ERROR] You must be root to run this script.'
	print 'Try, "su then python auto-ndis.py" or "sudo python auto-ndis.py"'
	sys.exit(1)

##If the user doesn't have ndiswrapper installed the program will quit
if not os.path.exists(opts.ndiswrapper_bin) and not opts.nocheck:
	print '[ERROR] NDISwrapper not found!!!'
	print 'Please look for "ndiswrapper" in your distribution\'s package manager and install it or go to www.ndiswrapper.com and download the latest sources' 
	sys.exit(1)

##Print the debug options enabled
if (opts.debug):
	print '[DEBUG] Options:'
	print opts
	print '[DEBUG] Arguments:'
	print args
	print

def getoutput(*cmd):
	"""
	Like commands.getoutput, but uses subprocess.
	"""

	myproc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
	value  =  myproc.stdout.read()
	return value

def get_output_retcode(*cmd):
	
	myproc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
	value  =  myproc.stdout.read()
	retcode = myproc.wait()
	return value, retcode

def get_print_card_info():
	"""
	Prints the pci id and other information about the pci wireless cards.
	"""
	output = getoutput('lspci')
	
	

	print '  -- ' + device 
	print '      ==> PCI ID = ' + pci_id
	

def check_for_internet(url, card_id):
	"""
	Pings google to see if the user has an internet conecction available.
	"""
	
	print '[*] Looking if an Internet connection is available, this may take a few seconds.'
	test = getoutput('ping', '-c', '1', 'google.com')
	if 'unknown host' in test:
		print '[ERROR] An Internet connection was not found'
		choice = raw_input('(C)ontinue, (R)etry, (O)ffline mode or (E)xit: ')
		
		if choice == 'C' or choice == 'c':
			return 0
		
		elif choice == 'R' or choice == 'r':
			return check_for_internet(url,card_id)
		
		elif choice == 'O' or choice == 'o':
			manualmode(url,card_id)
			installdriver(card_id)

		elif choice == 'E' or choice == 'e':
			sys.exit(1)
		
		else:
			return check_for_internet(url,card_id)
	
	else:
		print '[*] Internet connection found, continuing installation'
		return 0

def searchcard(devices_list, database):
	"""
	Looks if one of the ids in the devices list given as argument matches an entry in the database given as argument. 
	"""
		
	for item in devices_list:
		if item in database:
			return item
	return -1
	 
def remove_old_drivers():
        """
	Removes existing wireless drivers.
	"""

	print '[*] Removing Old Drivers:'
        baddrivers = yourcard_dic['blacklist']
        if baddrivers in getoutput('lsmod| awk "{print $1}"'):
                print '   removing %s' % (baddrivers, )
                subprocess.call(['rmmod', baddrivers])
        else:
                print '   drivers not loaded, nothing to remove'

def blacklist_drivers():
        """
	Blacklists existing wireless drivers.
	"""

	print '[*] Blacklisting:'
        baddrivers = yourcard_dic['blacklist']
        if any(baddrivers in line.split('#')[0] for line in open('/etc/modprobe.d/blacklist')):
                print '   driver already blacklisted, skipping'
        else:
                print '   writing to /etc/modprobe.d/blacklist'
                blacklist = open('/etc/modprobe.d/blacklist', 'a')
                blacklist.write('\n#%s' % (baddrivers, ))
                blacklist.close()

def print_driver_license():
	"""
	Checks if the user agrees with the driver's EULA.
	"""
	
	print 'Do you agree with this proprietary driver\'s End User License Agreement? You can find it in the website of your card\'s manufacturer.'
	choice = raw_input('(Y)es or (N)o, if you don\'t agree the program will quit: ')
	
	if choice == 'y' or choice == 'Y':
		return 0
	elif choice == 'n' or choice == 'N':
		sys.exit(1)
	else:
		return driver_license()

def create_auto_ndis_folder():
	"""
	Creates a folder in which place the downloaded drivers.
	"""

	try:
		os.makedirs('%s/%s' % (opts.tmp_dir, card_id, ))
		print 'Tmpdir created'
		os.chmod(opts.tmp_dir,0777) 
		os.chdir('%s/%s' % (opts.tmp_dir, card_id, ))
	except:
		if os.path.exists('%s/%s' % (opts.tmp_dir, card_id, )):
			print 'Tmpdir exists and ok, continuing'
			os.chdir('%s/%s' % (opts.tmp_dir, card_id, ))
		else:
			print '[ERROR] cant create tmpdir'
			print '   Either specify an alternative or ensure that /tmp is writable and not full'
			sys.exit(1)

def find_decompression(driver_url):
	"""
	Determines the right decompression program to be used with the downloaded driver.
	"""

	decompression = 'manual'
	
	if '.exe' in driver_url or '.zip' in driver_url:
		decompression = 'unzip'
		
	elif '.tar' in driver_url:
		decompression = 'tar -vvf'
	
	elif '.tar.gz' in driver_url:
		decompression = 'tar -xvvzf'
	
	elif '.tar.bz2' in driver_url:
		decompression = 'tar -xvvjf'
	
	elif '.cab' in driver_url:
		decompression = 'cabextract'
	
	elif '.rar' in driver_url:
		decompression = 'unrar'
	
	if decompression != 'manual':	
		#Checks if the system has the necessary decompression program
		test = getoutput(decompression)
		if 'command not found' in test:
			print '[ERROR] The program to extract %s files is not installed in your system' % (decompression, )
			print 'Install a program on your system to extract %s files and then rerun the script' % (decompression, )
			sys.exit(1)
	return decompression
	
def fetch(url, card_id):
	"""
	Downloads the apropiate driver.
	"""

	print '[*] Downloading driver now from "%s"' % (url, )
	if (opts.quiet):
		retcode = subprocess.call(['wget', url, '-qO', opts.tmp_dir/card_id/driver])
		if retcode != 0:
			print '[ERROR] Download unsuccessfull, please check your Internet conecction'
			sys.exit(1)
		else:
			retcode = subprocess.call(['wget', url, '-O', opts.tmp_dir/card_id/driver])
			if retcode != 0:
				print '[ERROR] Download unsuccessfull, please check your Internet conecction'
				sys.exit(1)
		print '   Download successfull'
		
def extract(decompression):
	"""
	Extracts the dowloaded driver.
	"""

	print '[*] Extracting driver'
	
	if (opts.debug):
		print '[DEBUG] Decompression method: %s' % (decompression, )
		
	retcode = subprocess.call([decompression, opts.tmp_dir/card_id/driver])
	
	if recode != 0:
		print '[ERROR] Decompression failed'
		choice = raw_input('(C)ontinue, (R)etry, (S)pecify different decompression method or (E)xit: ')
			
		if choice == 'C' or choice == 'c':
			return 0
			
		elif choice == 'R' or choice == 'r':
			return extract(decompression)
		
		elif choice == 'S' or choice == 's':
			divided_url = url.split('.')
			file_type = divided_url[len(divided_url)-1]
			decompression = raw_input('Enter command to decompress %s files: ' % (file_type, ))
			return extract(decompression)		

		elif choice == 'E' or choice == 'e':
			sys.exit(1)
		
		else:
			return extract(decompression)

def manualmode(url, card_id):
	"""
	Comes into play if the user doesn't have an internet connection or if the driver need to be fetched manually.
	"""
	yourcard_dic = data[card_id]
	driver = yourcard_dic['driver']
	print 'The driver needs to be fetched manually from: %s' % (url, )
	print 'Please place the "%s" file, along with the .sys files into:' % (driver, )
	print '"%s/%s"' % (opts.tmp_dir, card_id, )
	while not any(driver in line for line in os.listdir('%s/%s/' % (opts.tmp_dir, card_id, ))):
		
		try:
			dummy = raw_input('When you have succesfully dowloaded the driver and extracted it press <Enter>: ')
			
		except: 
			##Executed when CTRL + C is pressed.
			print '\n\nCanceled!\n'
			sys.exit(1)
	print '  Driver file found! Continuing installation.'

def installdriver(card_id):
	"""
	Installs the driver with NDISwrapper.
	"""

	driver = yourcard_dic['driver']
	inf_file = getoutput('find', opts.tmp_dir/card_id, '-name', driver)
	if ( opts.debug ):
		print '[DEBUG] Driver found at %s' % (inf, )

	#Attempt to install driver.
	output, retcode = get_output_retcode('ndiswrapper', '-i', inf_file)

	#Attempt to detect errors.
	if "already" in output:
		print 'Driver is already installed!'
		sys.exit(1)
	
	elif retcode != 0:
		print '[ERROR] Driver installation failed'
		sys.exit(1)
			
	else:
		##Assume driver installed successfully. Set up and reload module.
		subprocess.call(['ndiswrapper',  '-ma'])
		subprocess.call(['modprobe', '-r', 'ndiswrapper'])
		subprocess.call(['modprobe', 'ndiswrapper'])
		print 'Installation finished'
		sys.exit(1)

def create_log_file():
	"""
	Creates a simple log file with some useful info.
	"""

	log = open('auto-ndis-log.txt', 'w')

	os_info = os.uname()
	distribution = platform.dist()
	ndis_version = getoutput('ndiswrapper', '-v')

	log.write('OS and date = ')
	for item in os_info:
		log.write(item)

	log.write('\nDistribution = ')
	for item in distribution:
		log.write(item)

	log.write('\nNDISwrapper info = ')
	for item in ndis_version:
		log.write(item)

	log.write('\nID = %s \n' % (card_id, ))
	log.write('URL = %s \n' % (url, ))
	log.write('DRIVER = %s \n' % (driver, ))

	log.close()

def get_card_id():
	##Gets the id of all the pci devices
	outtext = getoutput('lspci', '-n')

	##Stores the pci ids with the revision number in a list
	pci = re.findall('.{4}:.{4}\ \(rev .{2}\)',outtext)

	##Gets the id of all the usb devices
	outtext2 = getoutput('lsusb')
	##Stores the usb ids in a list
	usb = re.findall('.{4}:.{4}',outtext2)

	pcicard = searchcard(pci, data)
	usbcard = searchcard(usb, data)

	##Checks if the user has a pci card or a usb card, if he has both the program will ask card he wants to setup
	##If he has neither the program will exit and tell him what pci card he has if he has one
	if pcicard != -1 and usbcard == -1:
		return pcicard

	elif pcicard == -1 and usbcard != -1:
		return usbcard

	elif pcicard != -1 and usbcard != -1:
		choice = raw_input('Setup (w)ificard or setup your (u)sbcard?: ') 
		
		while choice != 'W' and choice != 'w' and choice != 'U' and choice != 'u':
			print 'Please try again'
			choice = raw_input('Setup (w)ificard or setup your (u)sbcard?: ') 
		if choice == 'W' or choice == 'w':
			return pcicard
		elif choice == 'U' or choice == 'u':
			return usbcard
		else:
			return get_card_id()
		
	elif pcicard == -1 and usbcard == -1:
		print 'Sorry, card not yet supported by Auto-NDISwrapper'
		print 'Save this output as it will help other people give you support'
		get_print_card_info()
		sys.exit(1)

card_id = get_card_id()
yourcard_dic = data[card_id]
url = yourcard_dic['url']
driver = yourcard_dic['driver']
decompression = find_decompression(url)

print '[*] Card Supported'
print '[*] Will attempt to fetch and install driver for the card with id: %s' % (card_id, )
print '[*] Will attempt to fetch driver from: %s' % (url, )
print '[*] Will attempt to install driver: %s' % (driver, )

if (opts.ask):
	print '   Do you want to continue?'
	try:
		dummy = raw_input('   Please hit <Enter> to continue, or use Ctrl+C to cancel: ')
	except:
		print '\n\nCanceled!\n'		
		sys.exit(1)
	print

print '[*] Beginning Setup Procedure:\n'
print_driver_license()
create_auto_ndis_folder()
create_log_file()

if decompression != 'manual':
	check_for_internet(url, card_id)
	fetch(url, card_id)
	extract(decompression)
	installdriver(card_id)
else:
	manualmode(url,card_id)
	installdriver(card_id)