~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
#!/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 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

__version__ = '0.0.1'

import os
import platform
import commands
import sys
import time
import re
from ConfigParser import ConfigParser
from optparse import OptionParser
sys.path.append(os.getcwd())
import database

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'"
	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" 
	sys.exit(1)

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

def get_and_print_card_info():
	## The function's name is self explanatory, but aniway this is thanks to mintwifi.py
	os.system("lspci | grep \"Network controller\" > /tmp/detected_wireless_devices")
	devices_file = open("/tmp/detected_wireless_devices")
	for device_item in devices_file.readlines():
		deviceArray = device_item.split()
		device = ' '.join(deviceArray[3:])
		pci_id_line = commands.getoutput("lspci -n | grep " + deviceArray[0]) 
		pci_id_array = pci_id_line.split()
		pci_id = ' '.join(pci_id_array[2:])
	print "  -- " + device 
	print "      ==> PCI ID = " + pci_id
	

def check_for_internet(URL,card):
	##Checks if the user has an internet connection available
	print "[*] Looking if an Internet connection is available, this may take a few seconds."
	test = commands.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)
		
		elif choice == "O" or choice == "o":
			manualmode(URL,card)
			installdriver(card)
			create_auto_ndis_folder()

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

def searchcard(L,D):
	##Looks if card is in the list of supported cards
	card = -1	
	for item in L:
		if item in D:
			card = item
			return card
	return card

def any(iterable):
	for element in iterable:
		if element:
			return True
	return False
	 
def remove_old_drivers():
        ##Removes existing wireless drivers
	print "[*] removing old drivers:"
        baddrivers = yourcard['blacklist']
        if baddrivers in commands.getoutput("lsmod| awk '{print $1}'"):
                print "   removing %s" % (baddrivers, )
                os.system("rmmod %s" % (baddrivers, ))
        else:
                print "   drivers not loaded, nothing to remove"

def blacklist_drivers():
        ##Blacklists existing wireless drivers
	print "[*] blacklisting:"
        baddrivers = yourcard['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 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 to place the drivers
	try:
		os.makedirs("%s/%s" % (opts.tmp_dir, card, ))
		print 'Tmpdir created'
		os.chmod(opts.tmp_dir,0777) 
		os.chdir("%s/%s" % (opts.tmp_dir, card, ))
	except:
		if os.path.exists("%s/%s" % (opts.tmp_dir, card, )):
			print 'Tmpdir exists and ok, continuing'
			os.chdir("%s/%s" % (opts.tmp_dir, card, ))
		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(FILE):
	##Determines the right decompression program to be used to decompress the downloaded driver
	decompression = "manual"
	
	if ".exe" in FILE or ".zip" in FILE:
		decompression = "unzip "
		
	elif ".tar" in FILE:
		decompression = "tar -vvf "
	
	elif ".tar.gz" in FILE:
		decompression = "tar -xvvzf "
	
	elif ".tar.bz2" in FILE:
		decompression = "tar -xvvjf "
	
	elif ".cab" in FILE:
		decompression = "cabextract "
	
	elif ".rar" in FILE:
		decompression = "unrar "
	
	if decompression != "manual":	
		#Checks if the system has the necessary decompression program
		test = commands.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 fetchnextract(URL,card):
	## determine decompression method
	decompression = "manual"	
	decompression = find_decompression(URL)
	
	if ( decompression != "manual"):
	
		print '[*] Downloading driver now from "%s"' % (URL, )
		if ( opts.quiet ):
			os.system("wget %s -qO %s/%s/driver" % (URL, opts.tmp_dir, card))
		else:
			os.system("wget %s -O %s/%s/driver" % (URL, opts.tmp_dir, card))
		print "   Download sucsessfull"
		print "[*] Extracting driver"
		if ( opts.debug ):
			print "[DEBUG] Decompression method: %s" % (decompression, )
		
		os.system("%s %s/%s/driver" % (decompression, opts.tmp_dir, card))
		
	else:
		manualmode(URL,card)

def manualmode(URL,card):
	##Comes into play if the user doesn't have an internet connection or if the driver need to be fetched manually
	yourcard = database.D[card]
	driver = yourcard['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, )
	while not any(driver in line for line in os.listdir('%s/%s/' % (opts.tmp_dir, card, ))):
	#while ((commands.getoutput("ls %s/%s/|grep %s" % (opts.tmp_dir, card, driver, ))) == ""):
		try:
			dummy = raw_input("When you have succesfully dowloaded the driver and extracted it press <Enter>: ")
			
		except: ## executed when CTRL + C is pressed
			print ' '
			print ' '
			print 'Canceled!'
			print ' '
			sys.exit(1)
	print '  Driver file found! Continuing installation.'

def installdriver(card):
	##Installs the driver with NDISwrapper
	driver = yourcard['driver']
	Inf = commands.getoutput("find %s/%s/ -name %s" % (opts.tmp_dir, card, driver, ))
	if ( opts.debug ):
		print "[DEBUG] Driver found at %s" % (Inf, )
	os.system("%s -i %s" % (opts.ndiswrapper_bin, Inf, ))
	os.system("%s -l" % (opts.ndiswrapper_bin, ))
	os.system("%s -ma" % (opts.ndiswrapper_bin, ))
	os.system("modprobe -r ndiswrapper")
	os.system("modprobe ndiswrapper")		
	os.system("echo ndiswrapper >> /etc/modules")
	
	print "Installation finished, please reboot your computer."
	sys.exit(0)


##Gets the id of all the pci devices
outtext = commands.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 = commands.getoutput("lsusb")
##Stores the usb ids in a list
USB = re.findall(".{4}:.{4}",outtext2)

pcicard = -1
usbcard = -1
pcicard = searchcard(PCI,database.D)
usbcard = searchcard(USB,database.D)

##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:
	card = pcicard

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

elif pcicard != -1 and usbcard != -1:
	
		choice = 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 = input("Setup (w)ificard or setup your (u)sbcard?: ") 
		if choice == 'w' or chice == 'W':
			card = pcicard
		else:
			card = usbcard
		
elif pcicard == -1 and usbcard == -1:
	
		print "Sorry, card not yet supported by Auto-NDISwrapper but most likely there are other solutions"
		print "Save this output as it will help other people give you support"
		get_and_print_card_info()
		sys.exit(1)

print "[*] Card Supported"
yourcard = database.D[card]
print "[*] Will attempt to fetch and install driver for this card"
get_and_print_card_info()
URL = yourcard['url']
print "[*] Will attempt to fetch driver from: %s" % (URL, )
driver = yourcard['driver']
print "[*] Will attempt to install driver: %s" % (driver, )
print " "

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 ' '
		print ' '
		print 'Canceled!'		
		print ' '
		sys.exit(1)
	print " "

print "[*] Beginning installation:"
print " "

driver_license()
create_auto_ndis_folder()

os.chdir("%s/%s" % (opts.tmp_dir, card, ))

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

OS = os.uname()
Distribution = platform.dist()
ndis_version = commands.getoutput("ndiswrapper -v")

log.write("OS and date = ")
for item in OS:
	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, ))
log.write("URL = %s \n" % (URL, ))
log.write("DRIVER = %s \n" % (driver, ))

log.close()

check_for_internet(URL,card)
fetchnextract(URL,card)
installdriver(card)