~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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
#!/usr/bin/env python

#Auto-NDISwrapper by Nils Schlupp, Gabriel J. Perez and Richard Kaufman
#
#				Main Module
#
#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 Schlupp <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.1.1'

import os, platform, sys, re, subprocess, webbrowser, commands
import logging

class NullHandler(logging.Handler):
	'''Define an empty logger'''
	def emit(self, record):
		pass


class UIDError(Exception):
	'''Raised when not run as root'''

class BinaryNotFound(Exception):
	'''Raised when ndiswrapper binary not found'''

class AUTO_NDIS(object):
	'''Primary auto-ndiswrapper class'''
	
	def __init__(self):
		#sys.path.append(os.getcwd())
		self.logger = logging.getLogger("AUTO-NDIS MAIN")

		
	def perform_initial_checks(self):
		'''Check for root privileges and ndiswrapper binary'''
		self.logger.info('perform_initial_checks')
		##If the user isn't root the program will quit
		if os.geteuid() != 0:
			raise UIDError
		
		##If the user doesn't have ndiswrapper installed the program will quit
		if not os.path.exists(opts.ndiswrapper_bin) and not opts.nocheck:
			raise BinaryNotFound
		
		self.logger.info('Done perform_initial_checks')


	def getoutput(*cmd):
		"""Like commands.getoutput, but uses subprocess. It also returns the return code of the process."""
	
		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, retcode = getoutput('lspci')
		lines = output.split('\n')
	
		for line in lines:
			if 'Network controller' in line:
				card_data = line
				break
	
		if card_data:
			card_info = card_data[28:len(card_data)]
			print card_info
		else:
			print 'No Network Devices Found!'
	
	def check_for_internet():
		"""Pings google to see if the user has an internet conecction available."""
	
		print '\n[*] Looking if an Internet connection is available, this may take a few seconds'
	
		test, retcode = 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':
				pass
	
			elif choice == 'R' or choice == 'r':
				return check_for_internet()
	
			elif choice == 'O' or choice == 'o':
				manualmode()
				installdriver()
				installation_report()
				sys.exit(1)
	
			elif choice == 'E' or choice == 'e':
				sys.exit(1)
	
			else:
				return check_for_internet()
	
		else:
			print '[*] Internet connection found, continuing installation'
	
	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
				break
		return 'empty'
	
	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':
			pass
	
		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 '\nTmpdir exists and ok, continuing'
				os.chdir('%s/%s' % (opts.tmp_dir, card_id, ))
			else:
				print '[ERROR] can\'t create tmpdir'
				print '   Either specify an alternative or ensure that /tmp is writable and not full'
				sys.exit(1)
	
	def find_decompression():
		"""
		Determines the right decompression program to be used with the downloaded driver.
		"""
	
		decompression = 'manual'
	
		if '.exe' in url or '.zip' in url:
			decompression = 'unzip'
	
		elif '.tar' in url:
			decompression = 'tar -vvf'
	
		elif '.tar.gz' in url:
			decompression = 'tar -xvvzf'
	
		elif '.tar.bz2' in url:
			decompression = 'tar -xvvjf'
	
		elif '.cab' in url:
			decompression = 'cabextract'
	
		elif '.rar' in url:
			decompression = 'unrar'
	
		if decompression != 'manual':
			#Checks if the system has the necessary decompression program
			test = commands.getoutput(decompression)
			if '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():
		"""
		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, '-o ', opts.tmp_dir + '/' + card_id + '/' + 'wget.log'])
		else:
			retcode = subprocess.call(['wget', url, '-O ', opts.tmp_dir + '/' + card_id + '/' + driver, '-o ', opts.tmp_dir + '/' + card_id + '/' + 'wget.log'])
	
	
		if retcode != 0:
			print '[ERROR] Download unsuccessfull, please check your Internet conecction and wget.log in your tmpdir for errors.'
			if (opts.debug):
				print '[DEBUG] wget returned code: %s' % (retcode, )
			sys.exit(1)
	
	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 retcode != 0:
			print '[WARNING] Decompression may have failed'
	
			if (opts.debug):
				print '[DEBUG] Decompression method returned code: %s' % (retcode, )
	
			choice = raw_input('(C)ontinue, (R)etry, (S)pecify different decompression method or (E)xit: ')
	
			if choice == 'C' or choice == 'c':
				pass
	
			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():
		"""
		Comes into play if the user doesn't have an internet connection or if the driver need to be fetched manually.
		"""
	
		print '\nThe 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, )
		webbrowser.open_new(url)
	
		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 '\nDriver file found! Continuing installation.'
	
	def installdriver():
		"""
		Installs the driver with NDISwrapper.
		"""
	
		if driver == '.inf':
			inf_files, retcode = getoutput('find', opts.tmp_dir + '/' + card_id, '-type', 'f', '-name', '*.inf')
			inf_files = inf_files.split('\n')
			inf_file = inf_files[0]
			print '\nA driver has not been specified yet for this card, will attempt procedure with the first found driver in %s/%s: %s' % (opts.tmp_dir, card_id, inf_file)
	
		else:
			inf_file, retcode = getoutput('find', opts.tmp_dir + '/' + card_id, '-type', 'f', '-name', driver)
	
		create_log_file(inf_file)
	
		if ( opts.debug ):
			print '[DEBUG] Driver found at %s' % (inf_file, )
	
		#Attempt to install driver
		output, retcode = getoutput('ndiswrapper', '-i', inf_file)
	
		#Attempt to detect errors
		if 'already' in output:
			print '\nDriver is already installed'
			pass
	
		elif retcode != 0:
			print '[ERROR] Driver installation failed'
			if (opts.debug):
				print '[DEBUG] NDISwrapper returned code: %s' % (retcode, )
			pass
	
		else:
			##Assume driver installed successfully and then set up and reload the module
			subprocess.call(['ndiswrapper',  '-ma'])
			subprocess.call(['modprobe', '-r', 'ndiswrapper'])
			subprocess.call(['modprobe', 'ndiswrapper'])
			print 'Installation finished'
			pass
	
	def create_log_file(driver):
		"""
		Creates a simple log file with some useful info.
		"""
	
		log = open('autondis-log.txt', 'w')
	
		os_info = os.uname()
		distribution = platform.dist()
		ndis_version, retcode = 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 wireless card's id number and revision number.
		"""
	
		##Gets the id of all the pci devices
		outtext, retcode = 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, retcode = 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 != 'empty' and usbcard == 'empty':
			return pcicard
	
		elif pcicard == 'empty' and usbcard != 'empty':
			return usbcard
	
		elif pcicard != 'empty' and usbcard != 'empty':
			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 == 'empty' and usbcard == 'empty':
			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)
	
	def installation_report():
		"""
		Prompts the user to report the installation if it was succesful.
		"""
	
		output, retcode = getoutput('ndiswrapper', '-l')
		print '\n' + 'NDISwrapper output: ' + '\n' + output
	
		print 'Is your wireless connection working now with NDISwrapper thanks to this script?'
		choice = raw_input('(Y)es and I would like to help this project by reporting my installation manually trough www.easylinuxwifi.org, (N)o it did not work for me: ')
	
		if choice == 'Y' or choice == 'y':
			print '\nPlease when you have time visit www.easylinuxwifi.org and report your installation. All the information needed for the report is available in your computer in %s/%s/autondis-log.txt\nThank You!' % (opts.tmp_dir, card_id )
			sys.exit(1)
	
		elif choice == 'N' or choice == 'n':
			print '\nWe are sorry that the procedure failed, but don\'t get discouraged! Please visit easylinuxwifi.org for help or any other community support website. Remember, the community is here to help. You may also want to try with other .inf files if more than one was included in the dowloaded driver. You may do this by entering manual mode with -m flag. and removing all .inf files from %s/%s/ except the one you want to try to install. Also if possible report any broken urls as bugs in our bug tracker.' % (opts.tmp_dir, card_id)
			sys.exit(1)
	
		else:
			return installation_report()

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

#print '\n[*] Card Supported'
#try:
	#print '[*] Card detected as a %s' % (yourcard_dic['name'], )
#try:
	#print '[*] Card ciptset detected as a %s' % (yourcard_dic['chipset'], )
#try:
	#print '[*] Aditional comments were provided:\n"%s"' % (yourcard_dic['other']
#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()

#if decompression != 'manual' and not (opts.manual):
	#check_for_internet()
	#fetch()
	#extract(decompression)
	#installdriver()
	#installation_report()
#else:
	#manualmode()
	#installdriver()
	#installation_report()



def parse_args():
	'''Parse comand line options'''
	parser = OptionParser(version='version: '+auto_ndis.__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='doesn\'t check for ndiswrapper binary (debug only)')
	parser.add_option('-d', '--debug', action='store_true', default=False, help='turn on debugging output')
	parser.add_option('-m', '--manual', action='store_true', default=False, help='proceed with manual procedure')
	parser.add_option('-r', '--repo', default='auto', help='sets source of card information. use either remote, local or auto. defaults to %default')
	parser.add_option('-c', '--clear', action='store_true', default=False, help='clears tmp-dir before running again')
	return parser.parse_args()

def make_dirs():
	if opts.clear and os.path.isdir(opts.tmp_dir):
		for root, dirs, files in os.walk(opts.tmp_dir, topdown=False):
			for name in files:
				os.remove(os.path.join(root, name))
			for name in dirs:
				os.rmdir(os.path.join(root, name))
	if not os.path.isdir(opts.tmp_dir):
		os.mkdir(opts.tmp_dir)

def initialise_logging():
	'''Create a logging facility'''
	
	__logname__ = '%s/log' % (opts.tmp_dir,)
	logger = logging.getLogger("AUTO-NDIS CLI")
	logger.setLevel(logging.DEBUG)
	# create file handler which logs even debug messages
	fh = logging.FileHandler(__logname__)
	fh.setLevel(logging.DEBUG)
	# create console handler with a higher log level
	ch = logging.StreamHandler()
	if opts.debug:
		ch.setLevel(logging.DEBUG)
	else:
		ch.setLevel(logging.ERROR)
	# create formatter and add it to the handlers
	formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
	fh.setFormatter(formatter)
	ch.setFormatter(formatter)
	# add the handlers to the logger
	logger.addHandler(fh)
	logger.addHandler(ch)
	return logger



def main():
	print 'Welcome to auto-ndiswrapper %s' % (auto_ndis.__version__, )
	print 'Please remember to always try to use the latest version of ndiswrapper with this script'
	#parse options
	opts, args = parse_args()
	#create directories
	make_dirs()
	#set up logging
	logger = initialise_logging()
	#initialise main modules
	main = auto_ndis.AUTO_NDIS()
	#print the debug options enabled
	logger.debug('options: %s' % (opts,))
	logger.debug('arguments: %s' % (args,))
	#check for root and binary
	try:
		print 'hi'
		main.perform_initial_checks()
		print 'done'
	except UIDError:
		logger.error('you must be root to run this script')
		logger.error('try, "su then python auto-ndis.py" or "sudo python auto-ndis.py"')
	except BinaryNotFound:
		logger.error('ndiswrapper not found!!!')
		logger.error('please look for "ndiswrapper" in your distribution\'s package manager and install it or go to www.ndiswrapper.com and download the latest sources')
	finally:
		logger.error('Error occured, exiting')
		return 1
	
	
	return 0
	

if __name__ == '__main__':
	sys.exit(main())