diff --git a/daemon.py b/daemon.py index c5200af..da523cd 100644 --- a/daemon.py +++ b/daemon.py @@ -1029,7 +1029,6 @@ class ConnectionWizard(dbus.service.Object): self.SetWPADriver(config.get("Settings","wpa_driver")) self.SetAlwaysShowWiredInterface(0) self.SetAutoReconnect(1) - self.SetHideDupeAPs(0) self.SetDebugMode(0) self.SetWiredAutoConnectMethod(1) self.SetUseGlobalDNS(False) diff --git a/dapper.py b/dapper.py index 3c07d78..c4aa296 100644 --- a/dapper.py +++ b/dapper.py @@ -14,9 +14,9 @@ import gobject, dbus, dbus.service if getattr(dbus, 'version', (0,0,0)) >= (0,41,0): import dbus.glib ############# -#declare the connections to our daemon. -#without them nothing useful will happen -#the daemon should be running as root +# Declare the connections to our daemon. +# Without them nothing useful will happen. +# The daemon should be running as root. bus = dbus.SystemBus() try: print 'attempting to connect daemon...' @@ -61,87 +61,109 @@ pic = gtk.Image() def set_signal_image(): global LastStrength - global stillWired #keeps us from resetting the wired info over and over - global network #declared as global so it is initialized once before it gets used in the if statement below - + global stillWired # Keeps us from resetting the wired info over and over + global network # Declared as global so it gets initialized before first use + + # Disable logging if debugging isn't on to prevent log spam if not daemon.GetDebugMode(): config.DisableLogging() - #Check if wired profile chooser should be launched + # Check if wired profile chooser should be launched if daemon.GetNeedWiredProfileChooser() == True: wired_profile_chooser() daemon.SetNeedWiredProfileChooser(False) - - #Are we using a wired connection? + + # Check for active wired connection wired_ip = wired.GetWiredIP() - if wired.CheckPluggedIn() == True and wired_ip: - if stillWired == False: - pic.set_from_file("images/wired.png") - tooltip.set_tip(eb,language['connected_to_wired'].replace('$A',wired_ip)) - stillWired = True - lock = '' - #Check for wireless or no connection + if wired.CheckPluggedIn() == True and wired_ip != None: + # Only set image/tooltip if it hasn't been set already + if stillWired == False: + pic.set_from_file("images/wired.png") + tooltip.set_tip(eb,language['connected_to_wired'].replace('$A', + wired_ip)) + stillWired = True + lock = '' else: - if stillWired == True: #wire must have gotten unplugged + # Check to see if we were using a wired connection that has now become + # unplugged or disabled. + if stillWired == True: pic.set_from_file("images/no-signal.png") - tooltip.set_tip(eb,language['not_connected']) + tooltip.set_tip(eb,language['not_connected']) stillWired = False - + wireless_ip = wireless.GetWirelessIP() - #If ip returns as None, we are probably returning from hibernation and need to force signal to 0 to avoid crashing + # If ip returns as None, we are probably returning from hibernation + # and need to force signal to 0 to avoid crashing. if wireless_ip != None: - signal = int(wireless.GetCurrentSignalStrength()) + wireless_signal = int(wireless.GetCurrentSignalStrength()) else: - signal = 0 - - #only update if the signal strength has changed because doing I/O calls is expensive, - #and the icon flickers - if (signal != LastStrength or network != wireless.GetCurrentNetwork()) and wireless_ip != None: - LastStrength = signal - lock = '' #set the string to '' so that when it is put in "high-signal" + lock + ".png", there will be nothing - curNetID = wireless.GetCurrentNetworkID() #the network ID needs to be checked because a negative value here will break the tray - if signal > 0 and curNetID > -1 and wireless.GetWirelessProperty(curNetID,"encryption"): - lock = '-lock' #set the string to '-lock' so that it will display the lock picture + wireless_signal = 0 + + # Only update if the signal strength has changed because doing I/O + # calls is expensive, and the icon flickers + if (wireless_signal != LastStrength or + network != wireless.GetCurrentNetwork() or wireless_signal == 0) \ + and wireless_ip != None: + LastStrength = wireless_signal + # Set the string to '' so that when it is put in "high-signal" + + # lock + ".png", there will be nothing + lock = '' + # curNetID needs to be checked because a negative value + # will break the tray when passed to GetWirelessProperty. + curNetID = wireless.GetCurrentNetworkID() + if wireless_signal > 0 and curNetID > -1 and \ + wireless.GetWirelessProperty(curNetID,"encryption"): + # Set the string to '-lock' so that it will display the + # lock picture + lock = '-lock' network = str(wireless.GetCurrentNetwork()) - tooltip.set_tip(eb,language['connected_to_wireless'].replace('$A',network).replace('$B',str(signal)).replace('$C',str(wireless_ip))) - if signal > 75: + tooltip.set_tip(eb,language['connected_to_wireless'].replace + ('$A',network).replace('$B',str(wireless_signal)). + replace('$C',str(wireless_ip))) + if wireless_signal > 75: pic.set_from_file("images/high-signal" + lock + ".png") - elif signal > 50: + elif wireless_signal > 50: pic.set_from_file("images/good-signal" + lock + ".png") - elif signal > 25: + elif wireless_signal > 25: pic.set_from_file("images/low-signal" + lock + ".png") - elif signal > 0: + elif wireless_signal > 0: pic.set_from_file("images/bad-signal" + lock + ".png") - elif signal == 0: + elif wireless_signal == 0: pic.set_from_file("images/no-signal.png") autoreconnect() - elif wireless_ip == None and wired_ip == None: + elif wireless_ip is None and wired_ip is None: pic.set_from_file("images/no-signal") tooltip.set_tip(eb,language['not_connected']) auto_reconnect() - + if not daemon.GetDebugMode(): config.EnableLogging() return True def auto_reconnect(): - #Auto-reconnect code - not sure how well this works. I know that without the ForcedDisconnect check it reconnects you when - #a disconnect is forced. People who have disconnection problems need to test it to determine if it actually works. - #First it will attempt to reconnect to the last known wireless network, and if that fails it should run a scan and try to - #connect to any network set to autoconnect. - if wireless.GetAutoReconnect() == True and daemon.CheckIfConnecting() == False and wireless.GetForcedDisconnect() == False: + # Auto-reconnect code - not sure how well this works. I know that + # without the ForcedDisconnect check it reconnects you when a + # disconnect is forced. People who have disconnection problems need + # to test it to determine if it actually works. + # + # First it will attempt to reconnect to the last known wireless network + # and if that fails it should run a scan and try to connect to a wired + # network or any wireless network set to autoconnect. + global triedReconnect + + if wireless.GetAutoReconnect() == True and \ + daemon.CheckIfConnecting() == False: curNetID = wireless.GetCurrentNetworkID() - print 'Trying to autoreconnect' - if curNetID > -1: - wireless.ConnectWireless(wireless.GetCurrentNetworkID()) - while wireless.CheckIfWirelessConnecting() == True: - time.sleep(1) - if wireless.GetCurrentSignalStrength() != 0: - print "Successfully autoreconnected." - else: - print "Couldn't reconnect to last used network, scanning for an autoconnect network..." - print wireless.AutoConnect(True) + if curNetID > -1: # Needs to be a valid network to try to connect to + if triedReconnect == False: + print 'Trying to autoreconnect to last used network' + wireless.ConnectWireless(curNetID) + triedReconnect = True + elif wireless.CheckIfWirelessConnecting() == False: + print "Couldn't reconnect to last used network,\ + scanning for an autoconnect network..." + daemon.AutoConnect(True) else: daemon.AutoConnect(True) @@ -174,12 +196,14 @@ def on_about(data): dialog.set_comments('an icon that shows your network connectivity') dialog.set_website('http://wicd.sourceforge.net') dialog.run() - dialog.destroy() + dialog.destroy() LastStrength = -2 stillWired = False network = '' lastWinId = 0 +triedReconnect = False + menu = ''' @@ -194,10 +218,12 @@ menu = ''' ''' actions = [ ('Menu', None, 'Menu'), - ('Connect', gtk.STOCK_CONNECT, '_Connect...', None, 'Connect to network', on_preferences), - ('About', gtk.STOCK_ABOUT, '_About...', None, 'About wicd-tray-icon', on_about), + ('Connect', gtk.STOCK_CONNECT, '_Connect...', None, + 'Connect to network', on_preferences), + ('About', gtk.STOCK_ABOUT, '_About...', None, + 'About wicd-tray-icon', on_about), ('Quit',gtk.STOCK_QUIT,'_Quit',None,'Quit wicd-tray-icon', on_quit), - + ] ag = gtk.ActionGroup('Actions') ag.add_actions(actions) diff --git a/edgy.py b/edgy.py index 81e4035..391b44f 100755 --- a/edgy.py +++ b/edgy.py @@ -24,10 +24,10 @@ if getattr(dbus, 'version', (0,0,0)) >= (0,41,0): import dbus.glib ############# -#declare the connections to our daemon. -#without them nothing useful will happen -#the daemon should be running as root -#some connections aren't used so they are commented +# Declare the connections to our daemon. +# Without them nothing useful will happen. +# The daemon should be running as root. +# Some connections aren't used so they are commented. bus = dbus.SystemBus() try: print 'attempting to connect daemon...' @@ -37,12 +37,8 @@ except: print 'daemon not running...' import misc misc.PromptToStartDaemon() - time.sleep(5) - try: - proxy_obj = bus.get_object('org.wicd.daemon', '/org/wicd/daemon') - except: - print 'daemon still not running, aborting.' -daemon = dbus.Interface(proxy_obj, 'org.wicd.daemon') # Had to uncomment it + sys.exit(0) +daemon = dbus.Interface(proxy_obj, 'org.wicd.daemon') wireless = dbus.Interface(proxy_obj, 'org.wicd.daemon.wireless') wired = dbus.Interface(proxy_obj, 'org.wicd.daemon.wired') config = dbus.Interface(proxy_obj, 'org.wicd.daemon.config') @@ -82,66 +78,82 @@ def open_wicd_gui(): def wired_profile_chooser(): print 'profile chooser is running' os.spawnlpe(os.P_WAIT, './gui.py', os.environ) - + def set_signal_image(): global LastStrength - global stillWired #keeps us from resetting the wired info over and over - global network #declared as global so it gets initialized before initial use + global stillWired # Keeps us from resetting the wired info over and over + global network # Declared as global so it gets initialized before first use - #Disable logging if debugging isn't on to prevent log spam + # Disable logging if debugging isn't on to prevent log spam if not daemon.GetDebugMode(): config.DisableLogging() - - #Check if wired profile chooser should be launched + + # Check if wired profile chooser should be launched if daemon.GetNeedWiredProfileChooser() == True: wired_profile_chooser() daemon.SetNeedWiredProfileChooser(False) - - #Check for active wired connection + + # Check for active wired connection wired_ip = wired.GetWiredIP() if wired.CheckPluggedIn() == True and wired_ip != None: - if stillWired == False: # Only set image/tooltip if it hasn't been set already + # Only set image/tooltip if it hasn't been set already + if stillWired == False: tr.set_from_file("images/wired.png") - tr.set_tooltip(language['connected_to_wired'].replace('$A',wired_ip)) + tr.set_tooltip(language['connected_to_wired'].replace('$A', + wired_ip)) stillWired = True lock = '' - #Check if using wireless/not-connected else: - if stillWired == True: #this only occurs when we were previously using wired but it became unplugged + # Check to see if we were using a wired connection that has now become + # unplugged or disabled. + if stillWired == True: tr.set_from_file("images/no-signal.png") tr.set_tooltip(language['not_connected']) stillWired = False - + wireless_ip = wireless.GetWirelessIP() - #If ip returns as None, we are probably returning from hibernation and need to force signal to 0 to avoid crashing + # If ip returns as None, we are probably returning from hibernation + # and need to force signal to 0 to avoid crashing. if wireless_ip != None: - signal = int(wireless.GetCurrentSignalStrength()) + wireless_signal = int(wireless.GetCurrentSignalStrength()) else: - signal = 0 - - #only update if the signal strength has changed because doing I/O calls is expensive, - #and the icon flickers - if (signal != LastStrength or network != wireless.GetCurrentNetwork() or signal == 0) and wireless_ip != None: - LastStrength = signal - lock = '' #set the string to '' so that when it is put in "high-signal" + lock + ".png", there will be nothing - curNetID = wireless.GetCurrentNetworkID() #this needs to be checked because a negative value will break the tray - if signal > 0 and curNetID > -1 and wireless.GetWirelessProperty(curNetID,"encryption"): - lock = '-lock' #set the string to '-lock' so that it will display the lock picture - network = str(wireless.GetCurrentNetwork()) - tr.set_tooltip(language['connected_to_wireless'].replace('$A',network).replace('$B',str(signal)).replace('$C',str(wireless_ip))) - if signal > 75: + wireless_signal = 0 + + # Only update if the signal strength has changed because doing I/O + # calls is expensive, and the icon flickers + if (wireless_signal != LastStrength or + network != wireless.GetCurrentNetwork() or wireless_signal == 0) \ + and wireless_ip != None: + LastStrength = wireless_signal + # Set the string to '' so that when it is put in "high-signal" + + # lock + ".png", there will be nothing + lock = '' + # curNetID needs to be checked because a negative value + # will break the tray when passed to GetWirelessProperty. + curNetID = wireless.GetCurrentNetworkID() + if wireless_signal > 0 and curNetID > -1 and \ + wireless.GetWirelessProperty(curNetID,"encryption"): + # Set the string to '-lock' so that it will display the + # lock picture + lock = '-lock' + network = str(wireless.GetCurrentNetwork()) + tr.set_tooltip(language['connected_to_wireless'].replace + ('$A',network).replace + ('$B',str(wireless_signal)).replace + ('$C',str(wireless_ip))) + if wireless_signal > 75: tr.set_from_file("images/high-signal" + lock + ".png") - elif signal > 50: + elif wireless_signal > 50: tr.set_from_file("images/good-signal" + lock + ".png") - elif signal > 25: + elif wireless_signal > 25: tr.set_from_file("images/low-signal" + lock + ".png") - elif signal > 0: + elif wireless_signal > 0: tr.set_from_file("images/bad-signal" + lock + ".png") - elif signal == 0: + elif wireless_signal == 0: tr.set_from_file("images/no-signal.png") auto_reconnect() - - elif wireless_ip == None and wired_ip == None: + + elif wireless_ip is None and wired_ip is None: tr.set_from_file("images/no-signal.png") tr.set_tooltip(language['not_connected']) auto_reconnect() @@ -152,24 +164,31 @@ def set_signal_image(): return True def auto_reconnect(): - #Auto-reconnect code - not sure how well this works. I know that without the ForcedDisconnect check it reconnects you when - #a disconnect is forced. People who have disconnection problems need to test it to determine if it actually works. - #First it will attempt to reconnect to the last known wireless network, and if that fails it should run a scan and try to - #connect to a wired network or any wireless network set to autoconnect. + # Auto-reconnect code - not sure how well this works. I know that + # without the ForcedDisconnect check it reconnects you when a + # disconnect is forced. People who have disconnection problems need + # to test it to determine if it actually works. + # + # First it will attempt to reconnect to the last known wireless network + # and if that fails it should run a scan and try to connect to a wired + # network or any wireless network set to autoconnect. global triedReconnect - if wireless.GetAutoReconnect() == True and daemon.CheckIfConnecting() == False and wireless.GetForcedDisconnect() == False: + + if wireless.GetAutoReconnect() == True and \ + daemon.CheckIfConnecting() == False: curNetID = wireless.GetCurrentNetworkID() - print 'Trying to autoreconnect to last used network' - if curNetID > -1: #needs to be a valid network to try to connect to + if curNetID > -1: # Needs to be a valid network to try to connect to if triedReconnect == False: + print 'Trying to autoreconnect to last used network' wireless.ConnectWireless(curNetID) triedReconnect = True - elif triedReconnect == True and wireless.CheckIfWirelessConnecting() == False: - print "Couldn't reconnect to last used network, scanning for an autoconnect network..." + elif wireless.CheckIfWirelessConnecting() == False: + print "Couldn't reconnect to last used network,\ + scanning for an autoconnect network..." daemon.AutoConnect(True) - else: + else: daemon.AutoConnect(True) - + class TrackerStatusIcon(gtk.StatusIcon): def __init__(self): gtk.StatusIcon.__init__(self) @@ -187,10 +206,12 @@ class TrackerStatusIcon(gtk.StatusIcon): ''' actions = [ ('Menu', None, 'Menu'), - ('Connect', gtk.STOCK_CONNECT, '_Connect...', None, 'Connect to network', self.on_preferences), - ('About', gtk.STOCK_ABOUT, '_About...', None, 'About wicd-tray-icon', self.on_about), - ('Quit',gtk.STOCK_QUIT,'_Quit',None,'Quit wicd-tray-icon', self.on_quit), - + ('Connect', gtk.STOCK_CONNECT, '_Connect...', None, + 'Connect to network', self.on_preferences), + ('About', gtk.STOCK_ABOUT, '_About...', None, + 'About wicd-tray-icon', self.on_about), + ('Quit',gtk.STOCK_QUIT,'_Quit',None,'Quit wicd-tray-icon', + self.on_quit), ] ag = gtk.ActionGroup('Actions') ag.add_actions(actions) @@ -205,7 +226,7 @@ class TrackerStatusIcon(gtk.StatusIcon): self.connect('popup-menu', self.on_popup_menu) self.set_from_file("images/no-signal.png") self.set_tooltip("Initializing wicd...") - + wireless.SetForcedDisconnect(False) def on_activate(self, data): @@ -223,7 +244,7 @@ class TrackerStatusIcon(gtk.StatusIcon): def on_about(self, data): dialog = gtk.AboutDialog() dialog.set_name('wicd tray icon') - dialog.set_version('0.2') #Might be time to move the version number up? + dialog.set_version('0.2') # Might be time to move the version number up? dialog.set_comments('an icon that shows your network connectivity') dialog.set_website('http://wicd.sourceforge.net') dialog.run() diff --git a/networking.py b/networking.py index 86d9417..674c7f1 100644 --- a/networking.py +++ b/networking.py @@ -12,15 +12,15 @@ import wpath if __name__ == '__main__': wpath.chdir(__file__) -#import the library of random functions that we need here -#this is also written by me, for this purpose +# Import the library of random functions that we need here +# this is also written by me, for this purpose import misc -#import some other random libraries that we're gonna need -import re,sys,threading,thread +# Import some other random libraries that we're gonna need. +import re,threading,thread -#much thanks to wieman01 for help and support with various types of encyption -#also thanks to foxy123, yopnono, and the many others who reported bugs helped -#and helped keep this project moving +# Much thanks to wieman01 for help and support with various types of encyption +# also thanks to foxy123, yopnono, and the many others who reported bugs helped +# and helped keep this project moving. class Wireless: @@ -31,95 +31,107 @@ class Wireless: before_script = None after_script = None disconnect_script = None - - #Create a function to scan for wireless networks + # Create a function to scan for wireless networks def Scan(self,essid=None): - #we ask for an essid, because then we can see hidden networks + # We ask for an essid, because then we can see hidden networks ##### ## DECLARE THE REGEX PATTERNS ##### - #init the regex patterns that will be used to search the output of iwlist scan for info - #these are well tested, should work on most cards - essid_pattern = re.compile('.*ESSID:"(.*?)"\n',re.DOTALL | re.I | re.M | re.S) - ap_mac_pattern = re.compile('.*Address: (.*?)\n',re.DOTALL | re.I | re.M | re.S) - channel_pattern = re.compile('.*Channel:? ?(\d\d?)',re.DOTALL | re.I | re.M | re.S) - strength_pattern = re.compile('.*Quality:?=? ?(\d\d*)',re.DOTALL | re.I | re.M | re.S) - altstrength_pattern = re.compile('.*Signal level:?=? ?(\d\d*)',re.DOTALL | re.I | re.M | re.S) - mode_pattern = re.compile('.*Mode:(.*?)\n',re.DOTALL | re.I | re.M | re.S) - freq_pattern = re.compile('.*Frequency:(.*?)\n',re.DOTALL | re.I | re.M | re.S) + # Init the regex patterns that will be used to search the output of + # iwlist scan for info. + # These are well tested, should work on most cards. + essid_pattern = re.compile('.*ESSID:"(.*?)"\n',re.DOTALL | re.I | re.M | + re.S) + ap_mac_pattern = re.compile('.*Address: (.*?)\n',re.DOTALL | re.I | + re.M | re.S) + channel_pattern = re.compile('.*Channel:? ?(\d\d?)',re.DOTALL | re.I | + re.M | re.S) + strength_pattern = re.compile('.*Quality:?=? ?(\d\d*)',re.DOTALL | + re.I | re.M | re.S) + altstrength_pattern = re.compile('.*Signal level:?=? ?(\d\d*)', + re.DOTALL | re.I | re.M | re.S) + mode_pattern = re.compile('.*Mode:(.*?)\n',re.DOTALL | re.I | re.M | + re.S) + freq_pattern = re.compile('.*Frequency:(.*?)\n',re.DOTALL | re.I | + re.M | re.S) - wep_pattern = re.compile('.*Encryption key:(.*?)\n',re.DOTALL | re.I | re.M | re.S) - altwpa_pattern = re.compile('(wpa_ie)',re.DOTALL | re.I | re.M | re.S) - wpa1_pattern = re.compile('(WPA Version 1)',re.DOTALL | re.I | re.M | re.S) - wpa2_pattern = re.compile('(WPA2)',re.DOTALL | re.I | re.M | re.S) + wep_pattern = re.compile('.*Encryption key:(.*?)\n',re.DOTALL | re.I | + re.M | re.S) + altwpa_pattern = re.compile('(wpa_ie)',re.DOTALL | re.I | re.M | re.S) + wpa1_pattern = re.compile('(WPA Version 1)',re.DOTALL | re.I | re.M | + re.S) + wpa2_pattern = re.compile('(WPA2)',re.DOTALL | re.I | re.M | re.S) ##### ## PREPARE THE INTERFACE ##### - #prepare the interface for scanning - #note that this must be run as root, otherwise we're gonna have trouble + # Prepare the interface for scanning. + # Note that this must be run as root, otherwise we're gonna have trouble misc.Run('ifconfig ' + self.wireless_interface + ' up') essid = misc.Noneify(essid) - if not essid == None: - #if there is a hidden essid, we need to tell the computer what it is - #then when it is scanned it will be recognized + if not essid is None: + # If there is a hidden essid, we need to tell the computer what it + # is. Then when it is scanned it will be recognized. print "setting hidden essid..." + essid - misc.Run('iwconfig ' + self.wireless_interface + ' essid "' + essid + '"') + misc.Run('iwconfig ' + self.wireless_interface + ' essid "' + + essid + '"') ##### ## RUN THE SCAN ##### - #run iwlist scan and get the avaliable networks - #save them to scan_data - all in one big string + # Run iwlist scan and get the avaliable networks and + # save them to scan_data - all in one big string scandata = misc.Run('iwlist ' + self.wireless_interface + ' scan') ##### ## PROCESS THE DATA ##### - #split the networks apart, using Cell as our split point - #this way we can look at only one network at a time + # Split the networks apart, using Cell as our split point + # this way we can look at only one network at a time networks = scandata.split( ' Cell ' ) - #declare + # Declare i=0 - #make an array for the aps + # Make an array for the aps aps = {} for cell in networks: - #search to see if there is an essid in this section - #if there isn't, that means that it is useless - #so we don't use it then + # Search to see if there is an essid in this section + # if there isn't, that means that it is useless + # so we don't use it then. - #set essid to the value, this is just a temp variable + # Set essid to the value, this is just a temp variable if cell.count("ESSID:") > 0: - #since an essid was found, - #we will extract the rest of the info - #make a dictionary for the data + # Since an essid was found + # we will extract the rest of the info + # make a dictionary for the data CurrentNetwork = {} - #use the RunRegex function to neaten up our code - #all it does for us is run the regex on the string - #and return the result - #but it makes this code look pretty + # Use the RunRegex function to neaten up our code + # all it does for us is run the regex on the string + # and return the result, + # but it makes this code look pretty. CurrentNetwork["essid"] = misc.RunRegex(essid_pattern,cell) if CurrentNetwork["essid"] == "": CurrentNetwork["hidden"] = True - #change the name so it doesn't screw stuff up - #because it looks like HTML - GTK no like + # Change the name so it doesn't screw stuff up + # because it looks like HTML - GTK no like CurrentNetwork["essid"] = "Hidden" else: CurrentNetwork["hidden"] = False CurrentNetwork["channel"] = misc.RunRegex(channel_pattern,cell) - if CurrentNetwork["channel"] == None: #some cards don't show the channel number + # Some cards don't show the channel number, so we try + # assigning the number based on the frequency returned. + if CurrentNetwork["channel"] is None: freq = misc.RunRegex(freq_pattern,cell) if freq == '2.412 GHz': CurrentNetwork["channel"] = 1 @@ -146,119 +158,139 @@ class Wireless: elif freq == '2.467 GHz': CurrentNetwork["channel"] = 12 elif freq == '2.472 GHz': - CurrentNetwork["channel"] = 13 + CurrentNetwork["channel"] = 13 elif freq == '2.484 GHz': CurrentNetwork["channel"] = 14 - else: - print 'Couldn\'t determine channel number for current network' + else: # Must be a really crappy driver. :( + print 'Couldn\'t determine channel number for \ + current network' CurrentNetwork["bssid"] = misc.RunRegex(ap_mac_pattern,cell) print " ##### " + CurrentNetwork["bssid"] CurrentNetwork["mode"] = misc.RunRegex(mode_pattern,cell) - - #since encryption needs a True or False - #we have to do a simple if then to set it + + # Since encryption needs a True or False, + # we have to do a simple if then to set it if misc.RunRegex(wep_pattern,cell) == "on": - if self.wpa_driver != 'ralink legacy': + if self.wpa_driver != 'ralink legacy': CurrentNetwork["encryption"] = True - #set this, because if it is something else this will be overwritten + # Set this, because if it is something else this will + # be overwritten. CurrentNetwork["encryption_method"] = "WEP" if misc.RunRegex(wpa1_pattern,cell) == "WPA Version 1": CurrentNetwork["encryption_method"] = "WPA" - + if misc.RunRegex(altwpa_pattern,cell) == "wpa_ie": CurrentNetwork["encryption_method"] = "WPA" if misc.RunRegex(wpa2_pattern,cell) == "WPA2": CurrentNetwork["encryption_method"] = "WPA2" - else: #support for ralink legacy drivers (maybe only serialmonkey enhanced), may not work w/ hidden networks - iwpriv = misc.Run("iwpriv " + self.wireless_interface + " get_site_survey") + # Support for ralink legacy drivers (maybe only + # serialmonkey enhanced), may not work w/ hidden networks. + else: + iwpriv = misc.Run("iwpriv " + self.wireless_interface + + " get_site_survey") lines = iwpriv.splitlines() lines = lines[2:] - for x in lines: #iterate through all networks found + for x in lines: info = x.split() - if len(info) < 5 or info == None or info == '': #make sure we read in a valid entry + # Make sure we read in a valid entry + if len(info) < 5 or info is None or info == '': break; + # We've found the network we want to connect to if info[2] == CurrentNetwork["essid"]: CurrentNetwork["encryption"] = True - if info[5] == 'WEP' or ((info[5] == 'OPEN' or info[5] == 'SHARED') and info[4] == 'WEP'): # Needs to be tested + if info[5] == 'WEP' or ((info[5] == 'OPEN' or + info[5] == 'SHARED') and info[4] == 'WEP'): CurrentNetwork["encryption_method"] = 'WEP' elif info[5] == 'WPA-PSK': CurrentNetwork["encryption_method"] = 'WPA' elif info[5] == 'WPA2-PSK': CurrentNetwork["encryption_method"] = 'WPA2' else: - print 'Unknown AuthMode, can\'t assign encryption_method!!' - CurrentNetwork["encryption_method"] = 'Unknown' - - CurrentNetwork["quality"] = info[1][1:] #set signal strength here (not link quality! dBm vs %) + print 'Unknown AuthMode, can\'t assign \ + encryption_method!!' + CurrentNetwork["encryption_method"] = \ + 'Unknown' + # Set signal strength here + # (not link quality! dBm vs %) + CurrentNetwork["quality"] = info[1][1:] else: CurrentNetwork["encryption"] = False - #end If + # End If if self.wpa_driver != 'ralink legacy': - #since strength needs a -1 if the quality isn't found - #we need a simple if then to set it + # Since strength needs a -1 if the quality isn't found + # we need a simple if then to set it if misc.RunRegex(strength_pattern,cell): - CurrentNetwork["quality"] = misc.RunRegex(strength_pattern,cell) - elif misc.RunRegex(altstrength_pattern,cell): #alternate way of labeling link quality used by some drivers - CurrentNetwork["quality"] = misc.RunRegex(altstrength_pattern,cell) + CurrentNetwork["quality"] = misc.RunRegex( + strength_pattern,cell) + # Alternate way of labeling link quality + elif misc.RunRegex(altstrength_pattern,cell): + CurrentNetwork["quality"] = misc.RunRegex( + altstrength_pattern, + cell) else: CurrentNetwork["quality"] = -1 - #add this network to the list of networks + # Add this network to the list of networks aps[ i ] = CurrentNetwork - #now increment the counter + # Now increment the counter i+=1 - #end For + # End For - #run a bubble sort - #to list networks by signal strength + # Run a bubble sort to list networks by signal strength going = True while going: sorted = False for i in aps: - #set x to the current number + # Set x to the current number x = int(i) - #set y to the next number + # Set y to the next number y = int(i+1) - #only run this if we actually have another element after the current one + # Only run this if we actually have another element after + # the current one. if (len(aps) > i+1): - #move around depending on qualities - #we want the lower qualities at the bottom of the list - #so we check to see if the quality below the current one - #is higher the current one - #if it is, we swap them + # Move around depending on qualities. + # We want the lower qualities at the bottom of the list, + # so we check to see if the quality below the current one + # is higher the current one. If it is, we swap them. - if (int(aps[int(y)]["quality"]) > int(aps[int(x)]["quality"])): - #set sorted to true so we don't exit + if (int(aps[int(y)]["quality"]) > + int(aps[int(x)]["quality"])): + # Set sorted to true so we don't exit sorted=True - #do the move + # Do the move temp=aps[y] aps[y]=aps[x] aps[x]=temp - #end If - #end If - #end For + # End If + # End If + # End For if (sorted == False): going = False - #end If - #end While + # End If + # End While #return the list of sorted access points return aps - #end Function Scan + # End Function Scan def Connect(self,network): #call the thread, so we don't hang up the entire works - self.ConnectingThread = self.ConnectThread(network,self.wireless_interface,self.wired_interface,self.wpa_driver,self.before_script,self.after_script,self.disconnect_script,self.global_dns_1,self.global_dns_2,self.global_dns_3) + self.ConnectingThread = self.ConnectThread(network, + self.wireless_interface, self.wired_interface, + self.wpa_driver, self.before_script, + self.after_script, self.disconnect_script, + self.global_dns_1, self.global_dns_2, + self.global_dns_3) self.ConnectingThread.start() return True @@ -268,7 +300,8 @@ class Wireless: ShouldDie = False lock = thread.allocate_lock() - def __init__(self,network,wireless,wired,wpa_driver,before_script,after_script,disconnect_script,gdns1,gdns2,gdns3): + def __init__(self, network, wireless, wired, wpa_driver, before_script, + after_script, disconnect_script, gdns1, gdns2, gdns3): threading.Thread.__init__(self) self.network = network self.wireless_interface = wireless @@ -278,315 +311,406 @@ class Wireless: self.before_script = before_script self.after_script = after_script self.disconnect_script = disconnect_script - + self.global_dns_1 = gdns1 self.global_dns_2 = gdns2 self.global_dns_3 = gdns3 self.lock.acquire() - self.ConnectingMessage = 'interface_down' - self.lock.release() + try: + self.ConnectingMessage = 'interface_down' + finally: + self.lock.release() #lock = thread.allocate_lock() def GetStatus(self): print "status request" print "acqlock",self.lock.acquire() - print " ...lock acquired..." - message = self.ConnectingMessage - #return "bob" #self.ConnectingMessage - self.lock.release() + try: + print " ...lock acquired..." + message = self.ConnectingMessage + finally: + self.lock.release() print " ...lock released..." return message def run(self): - #note that we don't put the wired interface down - #but we do flush all wired entries from the routing table - #so it shouldn't be used at all. + # Note that we don't put the wired interface down, + # but we do flush all wired entries from the routing table + # so it shouldn't be used at all. self.IsConnecting = True network = self.network - #execute pre-connection script if necessary + # Execute pre-connection script if necessary. if self.before_script != '' and self.before_script != None: print 'Executing pre-connection script' print misc.Run('./run-script.py ' + self.before_script) - #put it down + # Put it down print "interface down..." self.lock.acquire() - self.ConnectingMessage = 'interface_down' - self.lock.release() + try: + self.ConnectingMessage = 'interface_down' + finally: + self.lock.release() misc.Run("ifconfig " + self.wireless_interface + " down") - #set a false ip so that when we set the real one, the correct - #routing entry is created + # Set a false ip so that when we set the real one, the correct + # routing entry is created. print "Setting false ip..." self.lock.acquire() - self.ConnectingMessage = 'resetting_ip_address' - self.lock.release() + try: + self.ConnectingMessage = 'resetting_ip_address' + finally: + self.lock.release() misc.Run("ifconfig " + self.wired_interface + " 0.0.0.0") misc.Run("ifconfig " + self.wireless_interface + " 0.0.0.0") print "killing wpa_supplicant, dhclient, dhclient3" self.lock.acquire() - self.ConnectingMessage = 'removing_old_connection' - self.lock.release() + try: + self.ConnectingMessage = 'removing_old_connection' + finally: + self.lock.release() misc.Run("killall dhclient dhclient3 wpa_supplicant") - #check to see if we need to generate a PSK - if self.wpa_driver != "ralink legacy": # Enhanced Ralink legacy drivers are handled later - if not network.get('key')== None: + # Check to see if we need to generate a PSK + if self.wpa_driver != "ralink legacy": + if not network.get('key') is None: self.lock.acquire() - self.ConnectingMessage = 'generating_psk' - self.lock.release() + try: + self.ConnectingMessage = 'generating_psk' + finally: + self.lock.release() print "generating psk..." - key_pattern = re.compile('network={.*?\spsk=(.*?)\n}.*',re.DOTALL | re.I | re.M | re.S) - network["psk"] = misc.RunRegex(key_pattern,misc.Run('wpa_passphrase "' + network["essid"] + '" "' + network["key"] + '"')) - #generate the wpa_supplicant file... - if not network.get('enctype') == None: + key_pattern = re.compile('network={.*?\spsk=(.*?)\n}.*', + re.DOTALL | re.I | re.M | re.S) + network["psk"] = misc.RunRegex(key_pattern, + misc.Run('wpa_passphrase "' + + network["essid"] + '" "' + + network["key"] + '"')) + # Generate the wpa_supplicant file... + if not network.get('enctype') is None: self.lock.acquire() - self.ConnectingMessage = 'generating_wpa_config' - self.lock.release() + try: + self.ConnectingMessage = 'generating_wpa_config' + finally: + self.lock.release() print "generating wpa_supplicant configuration file..." misc.ParseEncryption(network) - print 'wpa_supplicant -B -i ' + self.wireless_interface + ' -c "' + wpath.networks + network["bssid"].replace(":","").lower() + '" -D ' + self.wpa_driver - misc.Run('wpa_supplicant -B -i ' + self.wireless_interface + ' -c "' + wpath.networks + network["bssid"].replace(":","").lower() + '" -D ' + self.wpa_driver) + wpa_string = ("wpa_supplicant -B -i " + + self.wireless_interface + + " -c " + wpath.networks + "\"" + + network["bssid"].replace(":","").lower() + + "\" -D " + self.wpa_driver) + print wpa_string + misc.Run(wpa_string) print "flushing the routing table..." self.lock.acquire() - self.ConnectingMessage = 'flushing_routing_table' - self.lock.release() + try: + self.ConnectingMessage = 'flushing_routing_table' + finally: + self.lock.release() misc.Run("ip route flush dev " + self.wireless_interface) misc.Run("ip route flush dev " + self.wired_interface) print "configuring the wireless interface..." self.lock.acquire() - self.ConnectingMessage = 'configuring_interface' - self.lock.release() + try: + self.ConnectingMessage = 'configuring_interface' + finally: + self.lock.release() - #bring it up + # Bring it up print "interface up..." self.lock.acquire() - self.ConnectingMessage = 'interface_up' - self.lock.release() + try: + self.ConnectingMessage = 'interface_up' + finally: + self.lock.release() print misc.Run("ifconfig " + self.wireless_interface + " up") if network["mode"].lower() == "master": - misc.Run("iwconfig " + self.wireless_interface + " mode managed") + misc.Run("iwconfig " + self.wireless_interface + + " mode managed") else: - misc.Run("iwconfig " + self.wireless_interface + " mode " + network["mode"]) + misc.Run("iwconfig " + self.wireless_interface + " mode " + + network["mode"]) - misc.Run("iwconfig " + self.wireless_interface + " essid \"" + network["essid"] + "\" channel " + str(network["channel"]) + " ap " + network["bssid"]) + misc.Run("iwconfig " + self.wireless_interface + " essid \"" + + network["essid"] + "\" channel " + str(network["channel"]) + + " ap " + network["bssid"]) - if self.wpa_driver == "ralink legacy": #Adds support for ralink cards that can't use wpasupplicant + # Adds support for ralink cards that can't use wpasupplicant + if self.wpa_driver == "ralink legacy": if network.get('key') != None: self.lock.acquire() - self.ConnectingMessage = 'setting_encryption_info' - self.lock.release() + try: + self.ConnectingMessage = 'setting_encryption_info' + finally: + self.lock.release() print 'setting up ralink encryption' - iwpriv = misc.Run("iwpriv " + self.wireless_interface + " get_site_survey") + iwpriv = misc.Run("iwpriv " + self.wireless_interface + + " get_site_survey") lines = iwpriv.splitlines() lines = lines[2:] for x in lines: info = x.split() - if len(info) < 5 or info == None or info == '': #probably overkill, but the last 2 won't get run anyways + if len(info) < 5 or info is None or info == '': break; if info[2] == network.get("essid"): - if info[5] == 'WEP' or (info[5] == 'OPEN' and info[4] == 'WEP'): # Needs to be tested + if info[5] == 'WEP' or (info[5] == 'OPEN' + and info[4] == 'WEP'): print 'setting up WEP' - misc.Run("iwconfig " + self.wireless_interface + " key " + network.get('key')) + misc.Run("iwconfig " + self.wireless_interface + + " key " + network.get('key')) elif info[5] == 'SHARED' and info[4] == 'WEP': print 'setting up WEP' - misc.Run("iwpriv " + self.wireless_interface + " set NetworkType=" + info[6]) - misc.Run("iwpriv " + self.wireless_interface + " set AuthMode=SHARED") - misc.Run("iwpriv " + self.wireless_interface + " set EncrypType=" + info[4]) - misc.Run("iwpriv " + self.wireless_interface + " set Key1=" + network.get('key')) - misc.Run("iwpriv " + self.wireless_interface + " set DefaultKeyID=1") - misc.Run("iwpriv " + self.wireless_interface + " set SSID=" + info[2]) + misc.Run("iwpriv " + self.wireless_interface + + " set NetworkType=" + info[6]) + misc.Run("iwpriv " + self.wireless_interface + + " set AuthMode=SHARED") + misc.Run("iwpriv " + self.wireless_interface + + " set EncrypType=" + info[4]) + misc.Run("iwpriv " + self.wireless_interface + + " set Key1=" + network.get('key')) + misc.Run("iwpriv " + self.wireless_interface + + " set DefaultKeyID=1") + misc.Run("iwpriv " + self.wireless_interface + + " set SSID=" + info[2]) elif info[5] == 'WPA-PSK': print 'setting up WPA-PSK' - misc.Run("iwpriv " + self.wireless_interface + " set NetworkType=" + info[6]) - misc.Run("iwpriv " + self.wireless_interface + " set AuthMode=WPAPSK") - misc.Run("iwpriv " + self.wireless_interface + " set EncrypType=" + info[4]) - misc.Run("iwpriv " + self.wireless_interface + " set SSID=" + info[2]) - misc.Run("iwpriv " + self.wireless_interface + " set WPAPSK=" + network.get('key')) - misc.Run("iwpriv " + self.wireless_interface + " set SSID=" + info[2]) + misc.Run("iwpriv " + self.wireless_interface + + " set NetworkType=" + info[6]) + misc.Run("iwpriv " + self.wireless_interface + + " set AuthMode=WPAPSK") + misc.Run("iwpriv " + self.wireless_interface + + " set EncrypType=" + info[4]) + misc.Run("iwpriv " + self.wireless_interface + + " set SSID=" + info[2]) + misc.Run("iwpriv " + self.wireless_interface + + " set WPAPSK=" + network.get('key')) + misc.Run("iwpriv " + self.wireless_interface + + " set SSID=" + info[2]) elif info[5] == 'WPA2-PSK': print 'setting up WPA2-PSK' - misc.Run("iwpriv " + self.wireless_interface + " set NetworkType=" + info[6]) - misc.Run("iwpriv " + self.wireless_interface + " set AuthMode=WPA2PSK") - misc.Run("iwpriv " + self.wireless_interface + " set EncrypType=" + info[4]) - misc.Run("iwpriv " + self.wireless_interface + " set SSID=" + info[2]) - misc.Run("iwpriv " + self.wireless_interface + " set WPAPSK=" + network.get('key')) - misc.Run("iwpriv " + self.wireless_interface + " set SSID=" + info[2]) + misc.Run("iwpriv " + self.wireless_interface + + " set NetworkType=" + info[6]) + misc.Run("iwpriv " + self.wireless_interface + + " set AuthMode=WPA2PSK") + misc.Run("iwpriv " + self.wireless_interface + + " set EncrypType=" + info[4]) + misc.Run("iwpriv " + self.wireless_interface + + " set SSID=" + info[2]) + misc.Run("iwpriv " + self.wireless_interface + + " set WPAPSK=" + network.get('key')) + misc.Run("iwpriv " + self.wireless_interface + + " set SSID=" + info[2]) else: - print 'Unknown AuthMode, can\'t complete connection process!!!' + print 'Unknown AuthMode, can\'t complete \ + connection process!!!' print "done setting encryption info" - if not network.get('broadcast') == None: + if not network.get('broadcast') is None: self.lock.acquire() - self.ConnectingMessage = 'setting_broadcast_address' - self.lock.release() + try: + self.ConnectingMessage = 'setting_broadcast_address' + finally: + self.lock.release() + print "setting the broadcast address..." + network["broadcast"] - misc.Run("ifconfig " + self.wireless_interface + " broadcast " + network["broadcast"]) + misc.Run("ifconfig " + self.wireless_interface + " broadcast " + + network["broadcast"]) - if not network.get("dns1") == None: + if not network.get("dns1") is None: self.lock.acquire() - self.ConnectingMessage = 'setting_static_dns' - self.lock.release() + try: + self.ConnectingMessage = 'setting_static_dns' + finally: + self.lock.release() print "setting the first dns server...", network["dns1"] resolv = open("/etc/resolv.conf","w") misc.WriteLine(resolv,"nameserver " + network["dns1"]) - if not network.get("dns2") == None: + if not network.get("dns2") is None: print "setting the second dns server...", network["dns2"] misc.WriteLine(resolv,"nameserver " + network["dns2"]) - if not network.get("dns3") == None: + if not network.get("dns3") is None: print "setting the third dns server..." misc.WriteLine(resolv,"nameserver " + network["dns3"]) - if not network.get('ip') == None: + if not network.get('ip') is None: self.lock.acquire() - self.ConnectingMessage = 'setting_static_ip' - self.lock.release() + try: + self.ConnectingMessage = 'setting_static_ip' + finally: + self.lock.release() print "setting static ips..." - misc.Run("ifconfig " + self.wireless_interface + " " + network["ip"] ) - misc.Run("ifconfig " + self.wireless_interface + " netmask " + network["netmask"] ) + misc.Run("ifconfig " + self.wireless_interface + " " + + network["ip"] ) + misc.Run("ifconfig " + self.wireless_interface + " netmask " + + network["netmask"] ) print "adding default gateway..." + network["gateway"] misc.Run("route add default gw " + network["gateway"]) else: #run dhcp... self.lock.acquire() - self.ConnectingMessage = 'running_dhcp' - self.lock.release() + try: + self.ConnectingMessage = 'running_dhcp' + finally: + self.lock.release() print "running dhcp..." if not self.ShouldDie: misc.Run("dhclient " + self.wireless_interface) - #code repetition --- bad. - #however, I think this is the best way + # Code repetition --- bad. + # However, I think this is the best way. - if network.get('use_static_dns') == True and network.get('use_global_dns') == False: - #just using normal dns - if not network.get("dns1") == None: + if (network.get('use_static_dns') == True and + network.get('use_global_dns') == False): + # Just using normal dns + if not network.get("dns1") is None: self.lock.acquire() - self.ConnectingMessage = 'setting_static_dns' - self.lock.release() + try: + self.ConnectingMessage = 'setting_static_dns' + finally: + self.lock.release() print "setting the first dns server...", network["dns1"] resolv = open("/etc/resolv.conf","w") misc.WriteLine(resolv,"nameserver " + network["dns1"]) - if not network.get("dns2") == None: - print "setting the second dns server...", network["dns2"] + if not network.get("dns2") is None: + print "setting the second dns server...",network["dns2"] misc.WriteLine(resolv,"nameserver " + network["dns2"]) - if not network.get("dns3") == None: + if not network.get("dns3") is None: print "setting the third dns server..." misc.WriteLine(resolv,"nameserver " + network["dns3"]) resolv.close() - - if network.get('use_static_dns') == True and network.get('use_global_dns') == True: - #using static dns - if not self.global_dns_1 == None: + + if (network.get('use_static_dns') == True and + network.get('use_global_dns') == True): + # Using static dns + if not self.global_dns_1 is None: self.lock.acquire() - self.ConnectingMessage = 'setting_static_dns' - self.lock.release() + try: + self.ConnectingMessage = 'setting_static_dns' + finally: + self.lock.release() print "setting the first dns server...", self.global_dns_1 resolv = open("/etc/resolv.conf","w") misc.WriteLine(resolv,"nameserver " + self.global_dns_1) - if not misc.Noneify(self.global_dns_2) == None: - print "setting the second dns server...", self.global_dns_2 + if not misc.Noneify(self.global_dns_2) is None: + print "setting the second dns server...",\ + self.global_dns_2 misc.WriteLine(resolv,"nameserver " + self.global_dns_2) - if not misc.Noneify(self.global_dns_3) == None: + if not misc.Noneify(self.global_dns_3) is None: print "setting the third dns server..." misc.WriteLine(resolv,"nameserver " + self.global_dns_3) resolv.close() self.lock.acquire() - self.ConnectingMessage = 'done' - self.lock.release() + try: + self.ConnectingMessage = 'done' + finally: + self.lock.release() print "done" self.IsConnecting = False - #execute post-connection script if necessary + # Execute post-connection script if necessary. if self.after_script != '' and self.after_script != None: print 'executing post connection script' print misc.Run('./run-script.py ' + self.after_script) - #end function Connect - #end class Connect + # End function Connect + # End class Connect def GetSignalStrength(self): output = misc.Run("iwconfig " + self.wireless_interface) - strength_pattern = re.compile('.*Quality:?=? ?(\d+)',re.DOTALL | re.I | re.M | re.S) - altstrength_pattern = re.compile('.*Signal level:?=? ?(\d\d*)',re.DOTALL | re.I | re.M | re.S) + strength_pattern = re.compile('.*Quality:?=? ?(\d+)',re.DOTALL | re.I + | re.M | re.S) + altstrength_pattern = re.compile('.*Signal level:?=? ?(\d\d*)',re.DOTALL + | re.I | re.M | re.S) strength = misc.RunRegex(strength_pattern,output) - if strength == None: + if strength is None: strength = misc.RunRegex(altstrength_pattern,output) return strength - #end function GetSignalStrength + # End function GetSignalStrength def GetCurrentNetwork(self): output = misc.Run("iwconfig " + self.wireless_interface) - essid_pattern = re.compile('.*ESSID:"(.*?)"',re.DOTALL | re.I | re.M | re.S) + essid_pattern = re.compile('.*ESSID:"(.*?)"',re.DOTALL | re.I | re.M + | re.S) return misc.RunRegex(essid_pattern,output) - #end function GetCurrentNetwork + # End function GetCurrentNetwork def GetIP(self): output = misc.Run("ifconfig " + self.wireless_interface) - ip_pattern = re.compile(r'inet [Aa]d?dr[^.]*:([^.]*\.[^.]*\.[^.]*\.[0-9]*)',re.S) + ip_pattern = re.compile(r'inet [Aa]d?dr[^.]*:([^.]*\.[^.]*\.[^.]*\.[0-9]*)',re.S) return misc.RunRegex(ip_pattern,output) - #end function GetIP + # End function GetIP def CreateAdHocNetwork(self,essid,channel,ip,enctype,key,encused,ics): - misc.Run("killall dhclient dhclient3 wpa_supplicant") #remove wpa_supplicant, as it can cause the connection to revert to - #previous networks... + # Remove wpa_supplicant, as it can cause the connection to revert to + # previous networks... + misc.Run("killall dhclient dhclient3 wpa_supplicant") misc.Run('ifconfig ' + self.wireless_interface + ' down') misc.Run('iwconfig ' + self.wireless_interface + ' mode ad-hoc') misc.Run('iwconfig ' + self.wireless_interface + ' channel ' + channel) misc.Run('iwconfig ' + self.wireless_interface + ' essid ' + essid) - #Right now it just assumes you're using WEP + # Right now it just assumes you're using WEP if encused == True: misc.Run('iwconfig ' + self.wireless_interface + ' key ' + key) misc.Run('ifconfig ' + self.wireless_interface + ' up') misc.Run('ifconfig ' + self.wireless_interface + ' inet ' + ip) - #also just assume that the netmask is 255.255.255.0, it simplifies ICS - misc.Run('ifconfig ' + self.wireless_interface + ' netmask 255.255.255.0') + # Also just assume that the netmask is 255.255.255.0, it simplifies ICS. + misc.Run('ifconfig ' + self.wireless_interface + + ' netmask 255.255.255.0') ip_parts = misc.IsValidIP(ip) if ics and ip_parts: - #set up internet connection sharing here - #flush the forward tables + # Set up internet connection sharing here + # flush the forward tables misc.Run('iptables -F FORWARD') misc.Run('iptables -N fw-interfaces') misc.Run('iptables -N fw-open') misc.Run('iptables -F fw-interfaces') misc.Run('iptables -F fw-open') - misc.Run('iptables -A FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu') - misc.Run('iptables -A FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT') + misc.Run('iptables -A FORWARD -p tcp --tcp-flags SYN,RST SYN \ + -j TCPMSS --clamp-mss-to-pmtu') + misc.Run('iptables -A FORWARD -m state --state RELATED,ESTABLISHED \ + -j ACCEPT') misc.Run('iptables -A FORWARD -j fw-interfaces ') misc.Run('iptables -A FORWARD -j fw-open ') - misc.Run('iptables -A FORWARD -j REJECT --reject-with icmp-host-unreachable') + misc.Run('iptables -A FORWARD -j REJECT --reject-with \ + icmp-host-unreachable') misc.Run('iptables -P FORWARD DROP') - misc.Run('iptables -A fw-interfaces -i ' + self.wireless_interface + ' -j ACCEPT') - basic_ip = '.'.join(ip_parts[0:3]) + '.0' #not sure that basic_ip is a good name - misc.Run('iptables -t nat -A POSTROUTING -s ' + basic_ip + '/255.255.255.0 -o ' + self.wired_interface + ' -j MASQUERADE') - misc.Run('echo 1 > /proc/sys/net/ipv4/ip_forward') #enable routing - #end function CreateAdHocNetwork + misc.Run('iptables -A fw-interfaces -i ' + self.wireless_interface + + ' -j ACCEPT') + basic_ip = '.'.join(ip_parts[0:3]) + '.0' # Not sure that basic_ip is a good name + misc.Run('iptables -t nat -A POSTROUTING -s ' + basic_ip + + '/255.255.255.0 -o ' + self.wired_interface + + ' -j MASQUERADE') + misc.Run('echo 1 > /proc/sys/net/ipv4/ip_forward') # Enable routing + # End function CreateAdHocNetwork def DetectWirelessInterface(self): - return misc.RunRegex(re.compile('(\w*)\s*\w*\s*[a-zA-Z0-9.-_]*\s*(?=ESSID)',re.DOTALL | re.I | re.M | re.S),misc.Run("iwconfig")) + return misc.RunRegex(re.compile('(\w*)\s*\w*\s*[a-zA-Z0-9.-_]*\s*(?=ESSID)', + re.DOTALL | re.I | re.M | re.S), + misc.Run("iwconfig")) def Disconnect(self): if self.disconnect_script != None: @@ -596,7 +720,7 @@ class Wireless: misc.Run('ifconfig ' + self.wireless_interface + ' down') -#end class Wireless +# End class Wireless class Wired: @@ -614,30 +738,38 @@ class Wired: def CheckPluggedIn(self): mii_tool_data = misc.Run( 'mii-tool ' + self.wired_interface,True) - if not misc.RunRegex(re.compile('(Invalid argument)',re.DOTALL | re.I | re.M | re.S),mii_tool_data) == None: + if not misc.RunRegex(re.compile('(Invalid argument)',re.DOTALL | re.I | + re.M | re.S),mii_tool_data) is None: print 'wired interface appears down, putting up for mii-tool check' misc.Run( 'ifconfig ' + self.wired_interface + ' up' ) mii_tool_data = misc.Run( 'mii-tool ' + self.wired_interface) - if not misc.RunRegex(re.compile('(link ok)',re.DOTALL | re.I | re.M | re.S),mii_tool_data) == None: + if not misc.RunRegex(re.compile('(link ok)',re.DOTALL | re.I | re.M | + re.S),mii_tool_data) is None: return True else: return False - #end function CheckPluggedIn + # End function CheckPluggedIn def Connect(self,network): - #call the thread, so we don't hang up the entire works - self.ConnectingThread = self.ConnectThread(network,self.wireless_interface,self.wired_interface,self.before_script,self.after_script,self.disconnect_script) + # Call the thread, so we don't hang up the entire works + self.ConnectingThread = self.ConnectThread(network, + self.wireless_interface, + self.wired_interface, + self.before_script, + self.after_script, + self.disconnect_script) self.ConnectingThread.start() return True - #end function Connect + # End function Connect class ConnectThread(threading.Thread): - #wired interface connect thread + # Wired interface connect thread lock = thread.allocate_lock() ConnectingMessage = None ShouldDie = False - def __init__(self,network,wireless,wired,before_script,after_script,disconnect_script): + def __init__(self,network,wireless,wired,before_script,after_script, + disconnect_script): threading.Thread.__init__(self) self.network = network self.wireless_interface = wireless @@ -647,113 +779,140 @@ class Wired: self.after_script = after_script self.disconnect_script = disconnect_script self.lock.acquire() - self.ConnectingMessage = 'interface_down' - self.lock.release() - #end function __init__ + try: + self.ConnectingMessage = 'interface_down' + finally: + self.lock.release() + # End function __init__ def GetStatus(self): self.lock.acquire() - print " ...lock acquired..." - message = self.ConnectingMessage - self.lock.release() + try: + print " ...lock acquired..." + message = self.ConnectingMessage + finally: + self.lock.release() print " ...lock released..." return message def run(self): - #we don't touch the wifi interface - #but we do remove all wifi entries from the - #routing table + # We don't touch the wifi interface + # but we do remove all wifi entries from the + # routing table. self.IsConnecting = True network = self.network - + if self.before_script != '' and self.before_script != None: print 'executing pre-connection script' misc.Run('./run-script.py ' + self.before_script) - #put it down + # Put it down self.lock.acquire() - self.ConnectingMessage = 'interface_down' - self.lock.release() + try: + self.ConnectingMessage = 'interface_down' + finally: + self.lock.release() print "interface down...", self.wired_interface misc.Run("ifconfig " + self.wired_interface + " down") - #set a false ip so that when we set the real one, the correct - #routing entry is created + # Set a false ip so that when we set the real one, the correct + # routing entry is created self.lock.acquire() - self.ConnectingMessage = 'resetting_ip_address' - self.lock.release() + try: + self.ConnectingMessage = 'resetting_ip_address' + finally: + self.lock.release() print "setting false ip... 0.0.0.0 on", self.wired_interface misc.Run("ifconfig " + self.wired_interface + " 0.0.0.0") misc.Run("ifconfig " + self.wireless_interface + " 0.0.0.0") - #bring it up + # Bring it up self.lock.acquire() - self.ConnectingMessage = 'interface_up' - self.lock.release() + try: + self.ConnectingMessage = 'interface_up' + finally: + self.lock.release() print "interface up...", self.wired_interface misc.Run("ifconfig " + self.wired_interface + " up") print "killing wpa_supplicant, dhclient, dhclient3" self.lock.acquire() - self.ConnectingMessage = 'removing_old_connection' - self.lock.release() + try: + self.ConnectingMessage = 'removing_old_connection' + finally: + self.lock.release() misc.Run("killall dhclient dhclient3 wpa_supplicant") print "flushing the routing table..." self.lock.acquire() - self.ConnectingMessage = 'flushing_routing_table' - self.lock.release() + try: + self.ConnectingMessage = 'flushing_routing_table' + finally: + self.lock.release() misc.Run("ip route flush dev " + self.wireless_interface) misc.Run("ip route flush dev " + self.wired_interface) - if not network.get("broadcast") == None: + if not network.get("broadcast") is None: self.lock.acquire() - self.ConnectingMessage = 'setting_broadcast_address' - self.lock.release() + try: + self.ConnectingMessage = 'setting_broadcast_address' + finally: + self.lock.release() print "setting the broadcast address..." + network["broadcast"] - misc.Run("ifconfig " + self.wired_interface + " broadcast " + network["broadcast"]) + misc.Run("ifconfig " + self.wired_interface + " broadcast " + + network["broadcast"]) - if not network.get("dns1") == None: + if not network.get("dns1") is None: self.lock.acquire() - self.ConnectingMessage = 'setting_static_dns' - self.lock.release() + try: + self.ConnectingMessage = 'setting_static_dns' + finally: + self.lock.release() print "setting the first dns server...", network["dns1"] resolv = open("/etc/resolv.conf","w") misc.WriteLine(resolv,"nameserver " + network["dns1"]) - if not network.get("dns2") == None: + if not network.get("dns2") is None: print "setting the second dns server...", network["dns2"] misc.WriteLine(resolv,"nameserver " + network["dns2"]) - if not network.get("dns3") == None: + if not network.get("dns3") is None: print "setting the third dns server..." misc.WriteLine(resolv,"nameserver " + network["dns3"]) - if not network.get("ip") == None: + if not network.get("ip") is None: self.lock.acquire() - self.ConnectingMessage = 'setting_static_ip' - self.lock.release() + try: + self.ConnectingMessage = 'setting_static_ip' + finally: + self.lock.release() print "setting static ips...", network["ip"] - misc.Run("ifconfig " + self.wired_interface + " " + network["ip"]) - misc.Run("ifconfig " + self.wired_interface + " netmask " + network["netmask"]) + misc.Run("ifconfig " + self.wired_interface + " " + + network["ip"]) + misc.Run("ifconfig " + self.wired_interface + " netmask " + + network["netmask"]) print "adding default gateway..." + network["gateway"] misc.Run("route add default gw " + network["gateway"]) else: - #run dhcp... + # Run dhcp... self.lock.acquire() - self.ConnectingMessage = 'running_dhcp' - self.lock.release() + try: + self.ConnectingMessage = 'running_dhcp' + finally: + self.lock.release() print "running dhcp..." if not self.ShouldDie: misc.Run("dhclient " + self.wired_interface) self.lock.acquire() - self.ConnectingMessage = 'done' - self.lock.release() + try: + self.ConnectingMessage = 'done' + finally: + self.lock.release() self.IsConnecting = False if self.after_script != '' and self.after_script != None: print 'executing post connection script' misc.Run('./run-script.py ' + self.after_script) - #end function run + # End function run def Disconnect(self): print 'wired disconnect running'