diff --git a/daemon.py b/daemon.py index b66e4be..14158bb 100644 --- a/daemon.py +++ b/daemon.py @@ -1,14 +1,20 @@ #!/usr/bin/python + +############ +## USES 4 SPACES FOR INDENT +## NO TABS +############ + #change to the directory that the file lives in import os,sys if __name__ == '__main__': - os.chdir(os.path.dirname(os.path.normpath(os.path.join(os.getcwd(),sys.argv[0])))) + os.chdir(os.path.dirname(os.path.normpath(os.path.join(os.getcwd(),sys.argv[0])))) #import the dbus stuff import gobject import dbus import dbus.service if getattr(dbus, 'version', (0,0,0)) >= (0,41,0): - import dbus.glib + import dbus.glib #import the networking library import networking #import random other libraries @@ -17,970 +23,969 @@ import ConfigParser, time import misc ############################### -# GENERAL NOTES +# GENERAL NOTES # -# wicd Daemon -# Version 1.0.0 -# Suppliments wicd -# Written December/January 2006 +# wicd Daemon +# Version 1.0.0 +# Suppliments wicd +# Written December/January 2006 # -# Uses libraries also written by me -# for this program -# called networking.py and misc.py -# Will not function without them. +# Uses libraries also written by me +# for this program +# called networking.py and misc.py +# Will not function without them. # -# CODE NOTES +# CODE NOTES # -# If a function has the "pass" statement in it -# this is usually because it is not complete. +# If a function has the "pass" statement in it +# this is usually because it is not complete. # -# Runs on behalf of the wicd GUI -# to perform actions that require root. -# The GUI should be running as the current user +# Runs on behalf of the wicd GUI +# to perform actions that require root. +# The GUI should be running as the current user # -# This is released under the -# GNU General Public License -# The terms can be found at -# http://www.gnu.org/copyleft/gpl.html +# This is released under the +# GNU General Public License # -# Copyright (C) 2007 Adam Blackburn +# The terms can be found at +# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html +# +# Copyright (C) 2007 Adam Blackburn ############################### logging_enabled = True class FlushWriter: - def __init__(self): - print os.getcwd() - self.file = open('data/wicd.log','w') - self.file.write(self.__getPrettyTime() + ' :: ') + def __init__(self): + print os.getcwd() + self.file = open('data/wicd.log','w') + self.file.write(self.__getPrettyTime() + ' :: ') - def write(self,data): - '''prepends a timestamp, writes the data, and then flushes the buffer''' - global logging_enabled + def write(self,data): + '''prepends a timestamp, writes the data, and then flushes the buffer''' + global logging_enabled - if logging_enabled: + if logging_enabled: - #it appears that only one character at a time is written, but I don't trust it - #so if it isn't always one letter, make it so - #this code should never run - if len(data) > 1: - for letter in data: - self.write(letter) - return + #it appears that only one character at a time is written, but I don't trust it + #so if it isn't always one letter, make it so + #this code should never run + if len(data) > 1: + for letter in data: + self.write(letter) + return - if data == '\n': - self.file.write('\n' + self.__getPrettyTime() + ' :: ') - else: - self.file.write(str(data)) + if data == '\n': + self.file.write('\n' + self.__getPrettyTime() + ' :: ') + else: + self.file.write(str(data)) - self.file.flush() + self.file.flush() - def __getPrettyTime(self): - '''generate a string with the time, and space numbers with 0s''' - x = time.localtime() - #year/month/day hours:minutes:seconds - pretty_time = str(x[0]).rjust(4,'0') + '/' + str(x[1]).rjust(2,'0') + '/'+str(x[2]).rjust(2,'0') + ' '+str(x[3]).rjust(2,'0') + ':' + str(x[4]).rjust(2,'0') + ':' + str(x[5]).rjust(2,'0') - #probably don't need to pad the year, but it makes it consistent - return pretty_time + def __getPrettyTime(self): + '''generate a string with the time, and space numbers with 0s''' + x = time.localtime() + #year/month/day hours:minutes:seconds + pretty_time = str(x[0]).rjust(4,'0') + '/' + str(x[1]).rjust(2,'0') + '/'+str(x[2]).rjust(2,'0') + ' '+str(x[3]).rjust(2,'0') + ':' + str(x[4]).rjust(2,'0') + ':' + str(x[5]).rjust(2,'0') + #probably don't need to pad the year, but it makes it consistent + return pretty_time - - def flush(self): - '''flushes the buffer''' - self.file.flush() + + def flush(self): + '''flushes the buffer''' + self.file.flush() class ConnectionWizard(dbus.service.Object): - ########## VARIABLES AND STUFF - ################################# - - def __init__(self, bus_name, object_path='/org/wicd/daemon'): - dbus.service.Object.__init__(self, bus_name, object_path) - - #set variables needed to run - these probably won't be changed too often - self.app_conf = "data/manager-settings.conf" - self.wireless_conf = "data/wireless-settings.conf" - self.wired_conf = "data/wired-settings.conf" - self.hidden_essid = None - self.wifi = networking.Wireless() - self.wired = networking.Wired() - self.forced_disconnect = False - - #load the config file - it should have most of the stuff we need to run... - self.ReadConfig() - - #set some other stuff needed to run - these probably will be changed often - - #this will speed up the scanning process - if a client doesn't need a fresh scan, just - #feed them the old one. a fresh scan can be done by calling FreshScan(self,interface) - self.LastScan = None - - #make a variable that will hold the wired network profile - self.WiredNetwork = {} - - #scan since we just got started - - DoAutoConnect = True - - if len(sys.argv) > 1: - if sys.argv[1] == "--do-not-scan": - print "--do-not-scan detected, not autoconnecting..." - DoAutoConnect = False - - if DoAutoConnect: - print "autoconnecting...",str(self.GetWirelessInterface()[5:]) - print self.AutoConnect(True) - - #log file! all std:out is redirected to this log file, so we'll flush it from time to time - #see POI:500 for details (use the search feature to search for POI:500 in this file) - - ########## DAEMON FUNCTIONS - ################################# - - @dbus.service.method('org.wicd.daemon') - def Hello(self): - '''returns the version number''' - #returns a version number. - #this number is major-minor-micro - #major is only incremented if minor - #reaches > 9 - #minor is incremented if changes - #that break core stucture are implemented - #micro is for everything else. - #and micro may be anything >= 0 - #this number is effective starting wicd v1.2.0 - version = '1.3.2' - print 'returned version number',version - return version - #end function Hello - - @dbus.service.method('org.wicd.daemon') - def SetWiredInterface(self,interface): - '''sets the wired interface for the daemon to use''' - print "setting wired interface" , str(interface) - self.wired.wired_interface = interface - self.wifi.wired_interface = interface - config = ConfigParser.ConfigParser() - config.read(self.app_conf) - config.set("Settings","wired_interface",interface) - config.write(open(self.app_conf,"w")) - #end function SetWiredInterface - - @dbus.service.method('org.wicd.daemon') - def SetWirelessInterface(self,interface): - '''sets the wireless interface the daemon will use''' - print "setting wireless interface" , str(interface) - self.wifi.wireless_interface = interface - self.wired.wireless_interface = interface - config = ConfigParser.ConfigParser() - config.read(self.app_conf) - config.set("Settings","wireless_interface",interface) - configfile = open(self.app_conf,"w") - config.write(configfile) - #end function SetWirelessInterface - - @dbus.service.method('org.wicd.daemon') - def SetWPADriver(self,driver): - '''sets the wpa driver the wpa_supplicant will use''' - print "setting wpa driver" , str(driver) - self.wifi.wpa_driver = driver - config = ConfigParser.ConfigParser() - config.read(self.app_conf) - config.set("Settings","wpa_driver",driver) - configfile = open(self.app_conf,"w") - config.write(configfile) - #end function SetWPADriver - - @dbus.service.method('org.wicd.daemon') - def SetUseGlobalDNS(self,use): - config = ConfigParser.ConfigParser() - config.read(self.app_conf) - config.set("Settings","use_global_dns",str(use)) - self.use_global_dns = use - self.wifi.use_global_dns = use - self.wired.use_global_dns = use - configfile = open(self.app_conf,"w") - config.write(configfile) - - @dbus.service.method('org.wicd.daemon') - def SetGlobalDNS(self,dns1=None,dns2=None,dns3=None): - '''sets the global dns addresses''' - print "setting global dns" - config = ConfigParser.ConfigParser() - config.read(self.app_conf) - if dns1: - config.set("Settings","global_dns_1",misc.noneToString(dns1)) - self.dns1 = dns1 - self.wifi.global_dns_1 = dns1 - self.wired.global_dns_1 = dns1 - if dns2: - config.set("Settings","global_dns_2",misc.noneToString(dns2)) - self.dns2 = dns2 - self.wifi.global_dns_2 = dns2 - self.wired.global_dns_2 = dns2 - if dns3: - config.set("Settings","global_dns_3",misc.noneToString(dns3)) - self.dns3 = dns3 - self.wifi.global_dns_3 = dns3 - self.wired.global_dns_3 = dns3 - configfile = open(self.app_conf,"w") - config.write(configfile) - #end function SetWirelessInterface - - - @dbus.service.method('org.wicd.daemon') - def GetUseGlobalDNS(self): - return bool(self.use_global_dns) - - @dbus.service.method('org.wicd.daemon') - def GetWPADriver(self): - '''returns the wpa driver the daemon is using''' - print 'returned wpa driver' - return str(self.wifi.wpa_driver) - #end function GetWPADriver - - @dbus.service.method('org.wicd.daemon') - def GetWiredInterface(self): - '''returns the wired interface''' - print 'returning wired interface' - return str(self.wired.wired_interface) - #end function GetWiredInterface - - @dbus.service.method('org.wicd.daemon') - def GetWirelessInterface(self): - '''returns the wireless interface the daemon is using''' - print 'returning wireless interface to client' - return str(self.wifi.wireless_interface) - #end function GetWirelessInterface - - @dbus.service.method('org.wicd.daemon') - def SetDebugMode(self,debug): - '''sets if debugging mode is on or off''' - config = ConfigParser.ConfigParser() - config.read(self.app_conf) - config.set("Settings","debug_mode",debug) - configfile = open(self.app_conf,"w") - config.write(configfile) - self.debug_mode = debug - - @dbus.service.method('org.wicd.daemon') - def GetDebugMode(self): - '''returns whether debugging is enabled''' - return bool(int(self.debug_mode)) - - @dbus.service.method('org.wicd.daemon') - def GetGlobalDNSAddresses(self): - '''returns the global dns addresses''' - print 'returning global dns addresses to client' - return (self.dns1,self.dns2,self.dns3) - #end function GetWirelessInterface - - ########## WIRELESS FUNCTIONS - ################################# - - @dbus.service.method('org.wicd.daemon.wireless') - def SetHiddenNetworkESSID(self,essid): - '''sets the ESSID of a hidden network for use with ConnectionWizard.Scan''' - print 'setting hidden essid: ' + str(essid) - self.hidden_essid = str(misc.Noneify(essid)) - - @dbus.service.method('org.wicd.daemon.wireless') - def Scan(self): - '''scans for wireless networks, optionally using a (hidden) essid set with SetHiddenNetworkESSID''' - print 'scanning start' - scan = self.wifi.Scan(str(self.hidden_essid)) #_should_ already be a string but you never know... - self.LastScan = scan - print 'scanning done' - print 'found',str(len(scan)),'networks:', - for i in scan: - print i, - self.ReadWirelessNetworkProfile(i) - print - #end function FreshScan - - @dbus.service.method('org.wicd.daemon.wireless') - def DisconnectWireless(self): - '''disconnects all wireless networks''' - self.SetForcedDisconnect(True) - self.wifi.Disconnect() - #end function DisconnectWireless - - @dbus.service.method('org.wicd.daemon.wireless') - def SetWirelessBeforeScript(self,script): - self.wifi.before_script = script - #end function SetWirelessBeforeScript - - @dbus.service.method('org.wicd.daemon.wireless') - def SetWirelessAfterScript(self,script): - self.wifi.after_script = script - #end function SetWirelessAfterScript - - @dbus.service.method('org.wicd.daemon.wireless') - def GetNumberOfNetworks(self): - '''returns number of networks''' - print 'returned number of networks...',len(self.LastScan) - return len(self.LastScan) - #end function GetNumberOfNetworks - - @dbus.service.method('org.wicd.daemon.wireless') - def CreateAdHocNetwork(self,essid,channel,ip,enctype,key,encused,ics): - '''creates an ad-hoc network using user inputted settings''' - print 'attempting to create ad-hoc network...' - self.wifi.CreateAdHocNetwork(essid,channel,ip,enctype,key,encused,ics) - #end function CreateAdHocNetwork - - @dbus.service.method('org.wicd.daemon.wireless') - def GetAutoReconnect(self): - '''returns if wicd should automatically try to reconnect is connection is lost''' - do = bool(int(self.auto_reconnect)) - return self.__printReturn('returning automatically reconnect when connection drops',do) - #end function GetAutoReconnect - - @dbus.service.method('org.wicd.daemon.wireless') - def SetAutoReconnect(self,value): - '''sets if wicd should try to reconnect with connection drops''' - print 'setting automatically reconnect when connection drops' - config = ConfigParser.ConfigParser() - config.read(self.app_conf) - config.set("Settings","auto_reconnect",int(value)) - config.write(open(self.app_conf,"w")) - self.auto_reconnect = value - #end function SetAutoReconnect - - @dbus.service.method('org.wicd.daemon.wireless') - def AutoConnect(self,fresh): - '''first tries to autoconnect to a wireled network, if that fails it tries a wireless connection''' - if fresh and self.CheckPluggedIn() == True: - defaultNetwork = self.GetDefaultWiredNetwork() - if defaultNetwork != None: - self.ReadWiredNetworkProfile(defaultNetwork) - self.ConnectWired() - time.sleep(1) - print "Attempting to autoconnect with wired interface..." - while self.CheckIfWiredConnecting(): # Keeps us from going into an infinite connecting loop - time.sleep(1) - print "...done autoconnecting." - else: - print "couldn't find a default wired connection, wired autoconnect failed" - else: - print "no wired connection present, wired autoconnect failed" - print 'attempting to autoconnect to wireless network' - if fresh: - self.Scan() - if self.GetWirelessInterface() != None: - for x in self.LastScan: - if bool(self.LastScan[x]["has_profile"]): - print str(self.LastScan[x]["essid"]) + ' has profile' - if bool(self.LastScan[x].get('automatic')): - print 'automatically connecting to...',str(self.LastScan[x]["essid"]) - self.ConnectWireless(x) - time.sleep(3) - while self.CheckIfWirelessConnecting(): - print "autoconnecting... hold" - #not sure why I need to get IPs, but - #it solves the autoconnect problem - #i think it has something to do with - #making IO calls while threads are working...? - #if anyone knows why...email me at compwiz18@gmail.com - #only some people need these statements for autoconnect - #to function properly - self.GetWirelessIP() - ### - # removed line below for 1.3.0 - if there is trouble with - # connecting at boot, - # add back to file -- adam - ### - # as far as I can tell, it seems fine - what does everyone else - # think? -- adam - ### - #self.GetWiredIP() - time.sleep(2) - print "autoconnecting... done" - return - print "unable to autoconnect, you'll have to manually connect" - else: - print 'autoconnect failed because wireless interface == None' - #end function AutoConnect - - @dbus.service.method('org.wicd.daemon.wireless') - def GetWirelessProperty(self,networkid,property): - '''retrieves wireless property from the network specified''' - value = self.LastScan[networkid].get(property) - print 'returned wireless network',networkid,'property',property,'of value',value - return value - #end function GetWirelessProperty - - @dbus.service.method('org.wicd.daemon.wireless') - def SetWirelessProperty(self,networkid,property,value): - '''sets property to value in network specified''' - #simple - set the value of the item in our current data - #to the value the client asked for - print 'setting wireless network',networkid,'property',property,'to value',value - self.LastScan[networkid][property] = misc.Noneify(value) - #end function SetProperty - - @dbus.service.method('org.wicd.daemon.wireless') - def DetectWirelessInterface(self): - '''returns an automatically detected wireless interface''' - iface = self.wifi.DetectWirelessInterface() - print 'automatically detected wireless interface',iface - return str(iface) - #end function DetectWirelessInterface - - @dbus.service.method('org.wicd.daemon.wireless') - def GetCurrentSignalStrength(self): - '''returns the current signal strength''' - strength = int(self.wifi.GetSignalStrength()) - print 'returning current signal strength',strength - return strength - #end function GetCurrentSignalStrength - - @dbus.service.method('org.wicd.daemon.wireless') - def GetCurrentNetwork(self): - '''returns the current network''' - current_network = str(self.wifi.GetCurrentNetwork()) - print current_network - return current_network - #end function GetCurrentNetwork - - @dbus.service.method('org.wicd.daemon.wireless') - def GetCurrentNetworkID(self): - '''returns the id of the current network, or -1 if network is not found''' - currentESSID = self.GetCurrentNetwork() - for x in self.LastScan: - if self.LastScan[x]['essid'] == currentESSID: - print 'current network found, id is ',x - return x - print 'returning -1, current network not found' - return -1 - #end function GetCurrentNetwork - - @dbus.service.method('org.wicd.daemon.wireless') - def ConnectWireless(self,id): - '''connects the the wireless network specified by id''' - #will returned instantly, that way we don't hold up dbus - #CheckIfWirelessConnecting can be used to test if the connection - #is done - self.SetForcedDisconnect(False) - self.wifi.before_script = self.GetWirelessProperty(id,'beforescript') - self.wifi.after_script = self.GetWirelessProperty(id,'afterscript') - print 'connecting to wireless network',self.LastScan[id]['essid'] - return self.wifi.Connect(self.LastScan[id]) - #end function Connect - - @dbus.service.method('org.wicd.daemon.wireless') - def GetForcedDisconnect(self): - '''returns whether wireless was dropped by user, or for some other reason''' - return self.forced_disconnect - #end function GetForcedDisconnect - - @dbus.service.method('org.wicd.daemon.wireless') - def SetForcedDisconnect(self,value): - '''sets whether wireless has been disconnected by user since last connection''' - self.forced_disconnect = value - #end function SetForcedDisconnect - - @dbus.service.method('org.wicd.daemon.wireless') - def CheckIfWirelessConnecting(self): - '''returns True if wireless interface is connecting, otherwise False''' - if not self.wifi.ConnectingThread == None: - #if ConnectingThread exists, then check for it's - #status, if it doesn't, we aren't connecting - status = self.wifi.ConnectingThread.IsConnecting - print 'wireless connecting',status - return status - else: - print 'wireless connecting',False - return False - #end function CheckIfWirelessConnecting - - @dbus.service.method('org.wicd.daemon.wireless') - def GetWirelessIP(self): - '''returns the IP that the wireless interface has''' - ip = self.wifi.GetIP() - print 'returning wireless ip',ip - return ip - #end function GetWirelessIP - - @dbus.service.method('org.wicd.daemon.wireless') - def CheckWirelessConnectingMessage(self): - '''returns the wireless interface's status message''' - if not self.wifi.ConnectingThread == None: - stat = self.wifi.ConnectingThread.GetStatus() - print 'wireless connect status',stat - return stat - else: - print 'wireless connect status',False - return False - #end function CheckWirelessConnectingMessage - - @dbus.service.method('org.wicd.daemon.wireless') - def CancelConnect(self): - '''cancels the wireless connection attempt''' - print 'canceling connection attempt' - if not self.wifi.ConnectingThread == None: - self.wifi.ConnectingThread.ShouldDie = True - misc.Run("killall dhclient dhclient3 wpa_supplicant") - #end function CancelConnect - - ########## WIRED FUNCTIONS - ################################# - - @dbus.service.method('org.wicd.daemon.wired') - def GetWiredIP(self): - '''returns the wired interface\'s ip address''' - ip = self.wired.GetIP() - print 'returning wired ip',ip - return ip - #end function GetWiredIP - - @dbus.service.method('org.wicd.daemon.wired') - def CheckIfWiredConnecting(self): - '''returns True if wired interface is connecting, otherwise False''' - if not self.wired.ConnectingThread == None: - #if ConnectingThread exists, then check for it's - #status, if it doesn't exist, we aren't connecting - status = self.wired.ConnectingThread.IsConnecting - print 'wired connecting',status - return status - else: - print 'wired connecting',False - return False - #end function CheckIfWiredConnecting - - @dbus.service.method('org.wicd.daemon.wired') - def SetWiredBeforeScript(self,script): - '''sets pre-connection script to run for a wired connection''' - self.wired.before_script = script - #end function SetWiredBeforeScript - - @dbus.service.method('org.wicd.daemon.wired') - def SetWiredAfterScript(self,script): - '''sets post-connection script to run for a wired connection''' - self.wired.after_script = script - #end function SetWiredAfterScript - - @dbus.service.method('org.wicd.daemon.wired') - def CheckWiredConnectingMessage(self): - '''returns the wired interface\'s status message''' - if not self.wired.ConnectingThread == None: - status = self.wired.ConnectingThread.GetStatus() - print 'wired connect status',status - return status - else: - print 'wired connect status',False - return False - #end function CheckWiredConnectingMessage - - @dbus.service.method('org.wicd.daemon.wired') - def SetWiredProperty(self,property,value): - if self.WiredNetwork: - self.WiredNetwork[property] = misc.Noneify(value) - print 'set',property,'to',misc.Noneify(value) - return True - else: - print 'WiredNetwork does not exist' - return False - #end function SetWiredProperty - - @dbus.service.method('org.wicd.daemon.wired') - def GetWiredProperty(self,property): - if self.WiredNetwork: - value = self.WiredNetwork.get(property) - print 'returned',property,'with value of',value,'to client...' - return value - else: - print 'WiredNetwork does not exist' - return False - #end function GetWiredProperty - - @dbus.service.method('org.wicd.daemon.wired') - def SetAlwaysShowWiredInterface(self,value): - print 'setting always show wired interface' - config = ConfigParser.ConfigParser() - config.read(self.app_conf) - config.set("Settings","always_show_wired_interface",int(value)) - config.write(open(self.app_conf,"w")) - self.always_show_wired_interface = value - #end function SetAlwaysShowWiredInterface - - @dbus.service.method('org.wicd.daemon.wired') - def GetAlwaysShowWiredInterface(self): - do = bool(int(self.always_show_wired_interface)) - return self.__printReturn('returning always show wired interface',do) - #end function GetAlwaysShowWiredInterface - - @dbus.service.method('org.wicd.daemon.wired') - def CheckPluggedIn(self): - if not self.wired.wired_interface == None: - return self.__printReturn('returning plugged in',self.wired.CheckPluggedIn()) - else: - return self.__printReturn("returning plugged in",None) - #end function CheckPluggedIn - - @dbus.service.method('org.wicd.daemon.wired') - def ConnectWired(self): - '''connects to a wired network''' - #simple enough. - self.wired.before_script = self.GetWiredProperty("beforescript") - self.wired.after_script = self.GetWiredProperty("afterscript") - self.wired.Connect(self.WiredNetwork) - - ########## LOG FILE STUFF - ################################# - - @dbus.service.method('org.wicd.daemon.config') - def DisableLogging(self): - global logging_enabled - logging_enabled = False - - @dbus.service.method('org.wicd.daemon.config') - def EnableLogging(self): - global logging_enabled - logging_enabled = True - - ########## CONFIGURATION FILE FUNCTIONS - ################################# - - @dbus.service.method('org.wicd.daemon.config') - def CreateWiredNetworkProfile(self,profilename): - #should include: profilename,ip,netmask,gateway,dns1,dns2,dns3 - print "creating profile for " + str(profilename) - config = ConfigParser.ConfigParser() - config.read(self.wired_conf) - if config.has_section(profilename): - return False - config.add_section(profilename) - config.set(profilename,"ip",None) - config.set(profilename,"broadcast",None) - config.set(profilename,"netmask",None) - config.set(profilename,"gateway",None) - config.set(profilename,"dns1",None) - config.set(profilename,"dns2",None) - config.set(profilename,"dns3",None) - config.set(profilename,"beforescript",None) - config.set(profilename,"afterscript",None) - config.set(profilename,"default",False) - config.write( open(self.wired_conf,"w")) - return True - #end function CreateWiredNetworkProfile - - @dbus.service.method('org.wicd.daemon.config') - def UnsetWiredDefault(self): - '''Unsets the default option in the current default wired profile''' - config = ConfigParser.ConfigParser() - config.read(self.wired_conf) - profileList = config.sections() - print "profileList = ",profileList - for profile in profileList: - print "profile = ", profile - if config.get(profile,"default") == "True": - print "removing existing default" - config.set(profile,"default", False) - self.SaveWiredNetworkProfile(profile) - #end function UnsetWiredDefault - - @dbus.service.method('org.wicd.daemon.config') - def GetDefaultWiredNetwork(self): - config = ConfigParser.ConfigParser() - config.read(self.wired_conf) - profileList = config.sections() - for profile in profileList: - if config.get(profile,"default") == "True": - return profile - return None - - @dbus.service.method('org.wicd.daemon.config') - def DeleteWiredNetworkProfile(self,profilename): - print "deleting profile for " + str(profilename) - config = ConfigParser.ConfigParser() - config.read(self.wired_conf) - if config.has_section(profilename): - config.remove_section(profilename) - else: - return "500: Profile does not exist" - config.write( open(self.wired_conf,"w")) - return "100: Profile Deleted" - #end function DeleteWiredNetworkProfile - - @dbus.service.method('org.wicd.daemon.config') - def SaveWiredNetworkProfile(self,profilename): - #should include: profilename,ip,netmask,gateway,dns1,dns2 - print "setting profile for " + str(profilename) - config = ConfigParser.ConfigParser() - config.read(self.wired_conf) - if config.has_section(profilename): - config.remove_section(profilename) - config.add_section(profilename) - for x in self.WiredNetwork: - config.set(profilename,x,self.WiredNetwork[x]) - config.write( open(self.wired_conf,"w")) - return "100: Profile Written" - #end function SaveWiredNetworkProfile - - @dbus.service.method('org.wicd.daemon.config') - def ReadWiredNetworkProfile(self,profilename): - profile = {} - config = ConfigParser.ConfigParser() - config.read(self.wired_conf) - if config.has_section(profilename) == True: - for x in config.options(profilename): - profile[x] = misc.Noneify(config.get(profilename,x)) - self.WiredNetwork = profile - return "100: Loaded Profile" - else: - self.WiredNetwork = None - return "500: Profile Not Found" - #end function ReadWiredNetworkProfile - - @dbus.service.method('org.wicd.daemon.config') - def GetWiredProfileList(self): - config = ConfigParser.ConfigParser() - config.read(self.wired_conf) - print config.sections() - if config.sections(): - return config.sections() - else: - return None - #end function GetWiredProfileList - - @dbus.service.method('org.wicd.daemon.config') - def SaveWirelessNetworkProfile(self,id): - print "setting network profile" - config = ConfigParser.ConfigParser() - config.read(self.wireless_conf) - if config.has_section(self.LastScan[id]["bssid"]): - config.remove_section(self.LastScan[id]["bssid"]) - config.add_section(self.LastScan[id]["bssid"]) - #add the essid so that people reading the config can figure - #out which network is which. it will not be read - for x in self.LastScan[id]: - config.set(self.LastScan[id]["bssid"],x,self.LastScan[id][x]) - config.write(open(self.wireless_conf,"w")) - #end function SaveWirelessNetworkProfile - - @dbus.service.method('org.wicd.daemon.config') - def SaveWirelessNetworkProperty(self,id,option): - print "setting network option " + str(option) + " to " + str(self.LastScan[id][option]) - config = ConfigParser.ConfigParser() - config.read(self.wireless_conf) - if config.has_section(self.LastScan[id]["bssid"]): - config.set(self.LastScan[id]["bssid"],option,str(self.LastScan[id][option])) - config.write(open(self.wireless_conf,"w")) - #end function SaveWirelessNetworkProperty - - @dbus.service.method('org.wicd.daemon.config') - def ReadWirelessNetworkProfile(self,id): - config = ConfigParser.ConfigParser() - config.read(self.wireless_conf) - print self.LastScan[id]["bssid"] - if config.has_section(self.LastScan[id]["bssid"]): - self.LastScan[id]["has_profile"] = True - - if config.has_option(self.LastScan[id]["bssid"],"beforescript"): - self.LastScan[id]["beforescript"]= misc.Noneify(config.get(self.LastScan[id]["bssid"],"beforescript")) - else: - self.LastScan[id]["beforescript"]= None - if config.has_option(self.LastScan[id]["bssid"],"afterscript"): - self.LastScan[id]["afterscript"]=misc.Noneify(config.get(self.LastScan[id]["bssid"],"afterscript")) - else: - self.LastScan[id]["afterscript"] = None - #read the essid because we be needing to name those hidden - #wireless networks now - but only read it if it is hidden - if self.LastScan[id]["hidden"] == True: - self.LastScan[id]["essid"] = misc.Noneify(config.get(self.LastScan[id]["bssid"],"essid")) - - for x in config.options(self.LastScan[id]["bssid"]): - if self.LastScan[id].has_key(x) == False: - self.LastScan[id][x] = misc.Noneify(config.get(self.LastScan[id]["bssid"],x)) - return "100: Loaded Profile" - else: - self.LastScan[id]["has_profile"] = False - return "500: Profile Not Found" - #end function ReadWirelessNetworkProfile - - ############################################# - ########## INTERNAL FUNCTIONS ############### - ############################################# - # so don't touch the stuff below # - # it read/writes the configuration files # - # and shouldn't need to be changed # - # unless you add a new property... # - # then be SURE YOU CHANGE IT # - ############################################# - - def __printReturn(self,text,value): - '''prints the specified text followed by the specified value, then returns value''' - print text,value - return value - #end function __printReturn - - def ReadConfig(self): - if os.path.isfile( self.app_conf ): - config = ConfigParser.ConfigParser() - config.read(self.app_conf) - if config.has_section("Settings"): - if config.has_option("Settings","wireless_interface"): - print "found wireless interface in configuration...", - self.SetWirelessInterface(config.get("Settings","wireless_interface")) - if config.has_option("Settings","wired_interface"): - print "found wired interface in configuration...", - self.SetWiredInterface(config.get("Settings","wired_interface")) - if config.has_option("Settings","wpa_driver"): - print "found wpa driver in configuration...", - self.SetWPADriver(config.get("Settings","wpa_driver")) - if config.has_option("Settings","always_show_wired_interface"): - self.always_show_wired_interface = config.get("Settings","always_show_wired_interface") - else: - config.set("Settings","always_show_wired_interface","False") - self.always_show_wired_interface = False - if config.has_option("Settings","use_global_dns"): - self.SetUseGlobalDNS(config.get("Settings","use_global_dns")) - dns1, dns2, dns3 = ('None','None','None') #so we can access them later - if config.has_option("Settings","global_dns_1"): - dns1 = config.get('Settings','global_dns_1') - if config.has_option("Settings","global_dns_2"): - dns2 = config.get('Settings','global_dns_2') - if config.has_option("Settings","global_dns_3"): - dns3 = config.get('Settings','global_dns_3') - self.SetGlobalDNS(dns1,dns2,dns3) - else: - self.SetUseGlobalDNS(False) - if config.has_option("Settings","auto_reconnect"): - self.auto_reconnect = config.get("Settings","auto_reconnect") - else: - config.set("Settings","auto_reconnect","False") - self.auto_reconnect = False - if config.has_option("Settings","debug_mode"): - self.debug_mode = config.get("Settings","debug_mode") - else: - self.debug_mode = False - config.set("Settings","debug_mode","False") - if config.has_option('Settings','dns1') and config.has_option('Settings','dns2') and config.has_option('Settings','dns3'): - self.SetGlobalDNS(config.get('Settings','dns1'),config.get('Settings','dns2'),config.get('Settings','dns3')) - else: - self.SetGlobalDNS("None","None","None") - else: - print "configuration file exists, no settings found, adding defaults..." - configfile = open(self.app_conf,"w") - config.add_section("Settings") - config.set("Settings","wireless_interface","wlan0") - config.set("Settings","wired_interface","eth0") - config.set("Settings","wpa_driver","wext") - config.set("Settings","always_show_wired_interface","False") - config.set("Settings","auto_reconnect","False") - config.set("Settings","debug_mode","False") - config.set("Settings","use_global_dns","False") - config.set("Settings","dns1","None") - config.set("Settings","dns2","None") - config.set("Settings","dns3","None") - self.SetGlobalDNS(config.get('Settings','dns1'),config.get('Settings','dns2'),config.get('Settings','dns3')) - self.SetWirelessInterface(config.get("Settings","wireless_interface")) - self.SetWiredInterface(config.get("Settings","wired_interface")) - self.SetWPADriver(config.get("Settings","wpa_driver")) - self.SetAlwaysShowWiredInterface(False) - self.SetAutoReconnect(True) - self.SetDebugMode(False) - config.write(configfile) - - else: - #write some defaults maybe? - print "configuration file not found, creating, adding defaults..." - config = ConfigParser.ConfigParser() - config.read(self.app_conf) - config.add_section("Settings") - config.set("Settings","wireless_interface","wlan0") - config.set("Settings","wired_interface","eth0") - config.set("Settings","always_show_wired_interface","False") - config.set("Settings","auto_reconnect","False") - config.set("Settings","debug_mode","False") - config.set("Settings","dns1","None") - config.set("Settings","dns2","None") - config.set("Settings","dns3","None") - iface = self.DetectWirelessInterface() - if iface: - config.set("Settings","wireless_interface",iface) - else: - print "couldn't detect a wireless interface, using wlan0..." - config.set("Settings","wireless_interface","wlan0") - config.set("Settings","wpa_driver","wext") - config.write(open(self.app_conf,"w")) - self.SetWirelessInterface(config.get("Settings","wireless_interface")) - self.SetWiredInterface(config.get("Settings","wired_interface")) - self.SetWPADriver(config.get("Settings","wpa_driver")) - self.SetAlwaysShowWiredInterface(False) - self.SetAutoReconnect(True) - self.SetDebugMode(False) - self.SetGlobalDNS(None,None,None) - #end If - - if os.path.isfile( self.wireless_conf ): - print "wireless configuration file found..." - #don't do anything since it is there - pass - else: - #we don't need to put anything in it, so just make it - print "wireless configuration file not found, creating..." - open( self.wireless_conf,"w" ).close() - #end If - - if os.path.isfile( self.wired_conf ): - print "wired configuration file found..." - #don't do anything since it is there - pass - else: - print "wired confguration file not found, creating..." - #we don't need to put anything in it, so just make it - open( self.wired_conf,"w" ).close() - #end If - - #hide the files, so the keys aren't exposed - print "chmoding configuration files 0600..." - os.chmod(self.app_conf,0600) - os.chmod(self.wireless_conf,0600) - os.chmod(self.wired_conf,0600) - - #make root own them - print "chowning configuration files root:root..." - os.chown(self.app_conf, 0, 0) - os.chown(self.wireless_conf, 0, 0) - os.chown(self.wired_conf, 0, 0) - - print "autodetected wireless interface...",self.DetectWirelessInterface() - print "using wireless interface...",self.GetWirelessInterface()[5:] - #end function ReadConfig + ########## VARIABLES AND STUFF + ################################# + + def __init__(self, bus_name, object_path='/org/wicd/daemon'): + dbus.service.Object.__init__(self, bus_name, object_path) + + #set variables needed to run - these probably won't be changed too often + self.app_conf = "data/manager-settings.conf" + self.wireless_conf = "data/wireless-settings.conf" + self.wired_conf = "data/wired-settings.conf" + self.hidden_essid = None + self.wifi = networking.Wireless() + self.wired = networking.Wired() + self.forced_disconnect = False + + #load the config file - it should have most of the stuff we need to run... + self.ReadConfig() + + #set some other stuff needed to run - these probably will be changed often + + #this will speed up the scanning process - if a client doesn't need a fresh scan, just + #feed them the old one. a fresh scan can be done by calling FreshScan(self,interface) + self.LastScan = None + + #make a variable that will hold the wired network profile + self.WiredNetwork = {} + + #scan since we just got started + + DoAutoConnect = True + + if len(sys.argv) > 1: + if sys.argv[1] == "--do-not-scan": + print "--do-not-scan detected, not autoconnecting..." + DoAutoConnect = False + + if DoAutoConnect: + print "autoconnecting...",str(self.GetWirelessInterface()[5:]) + print self.AutoConnect(True) + + #log file! all std:out is redirected to this log file, so we'll flush it from time to time + #see POI:500 for details (use the search feature to search for POI:500 in this file) + + ########## DAEMON FUNCTIONS + ################################# + + @dbus.service.method('org.wicd.daemon') + def Hello(self): + '''returns the version number''' + #returns a version number. + #this number is major-minor-micro + #major is only incremented if minor + #reaches > 9 + #minor is incremented if changes + #that break core stucture are implemented + #micro is for everything else. + #and micro may be anything >= 0 + #this number is effective starting wicd v1.2.0 + version = '1.3.2' + print 'returned version number',version + return version + #end function Hello + + @dbus.service.method('org.wicd.daemon') + def SetWiredInterface(self,interface): + '''sets the wired interface for the daemon to use''' + print "setting wired interface" , str(interface) + self.wired.wired_interface = interface + self.wifi.wired_interface = interface + config = ConfigParser.ConfigParser() + config.read(self.app_conf) + config.set("Settings","wired_interface",interface) + config.write(open(self.app_conf,"w")) + #end function SetWiredInterface + + @dbus.service.method('org.wicd.daemon') + def SetWirelessInterface(self,interface): + '''sets the wireless interface the daemon will use''' + print "setting wireless interface" , str(interface) + self.wifi.wireless_interface = interface + self.wired.wireless_interface = interface + config = ConfigParser.ConfigParser() + config.read(self.app_conf) + config.set("Settings","wireless_interface",interface) + configfile = open(self.app_conf,"w") + config.write(configfile) + #end function SetWirelessInterface + + @dbus.service.method('org.wicd.daemon') + def SetWPADriver(self,driver): + '''sets the wpa driver the wpa_supplicant will use''' + print "setting wpa driver" , str(driver) + self.wifi.wpa_driver = driver + config = ConfigParser.ConfigParser() + config.read(self.app_conf) + config.set("Settings","wpa_driver",driver) + configfile = open(self.app_conf,"w") + config.write(configfile) + #end function SetWPADriver + + @dbus.service.method('org.wicd.daemon') + def SetUseGlobalDNS(self,use): + config = ConfigParser.ConfigParser() + config.read(self.app_conf) + config.set("Settings","use_global_dns",str(use)) + self.use_global_dns = use + self.wifi.use_global_dns = use + self.wired.use_global_dns = use + configfile = open(self.app_conf,"w") + config.write(configfile) + + @dbus.service.method('org.wicd.daemon') + def SetGlobalDNS(self,dns1=None,dns2=None,dns3=None): + '''sets the global dns addresses''' + print "setting global dns" + config = ConfigParser.ConfigParser() + config.read(self.app_conf) + if dns1: + config.set("Settings","global_dns_1",misc.noneToString(dns1)) + self.dns1 = dns1 + self.wifi.global_dns_1 = dns1 + self.wired.global_dns_1 = dns1 + if dns2: + config.set("Settings","global_dns_2",misc.noneToString(dns2)) + self.dns2 = dns2 + self.wifi.global_dns_2 = dns2 + self.wired.global_dns_2 = dns2 + if dns3: + config.set("Settings","global_dns_3",misc.noneToString(dns3)) + self.dns3 = dns3 + self.wifi.global_dns_3 = dns3 + self.wired.global_dns_3 = dns3 + print 'global dns servers are',dns1,dns2,dns3 + configfile = open(self.app_conf,"w") + config.write(configfile) + #end function SetWirelessInterface + + + @dbus.service.method('org.wicd.daemon') + def GetUseGlobalDNS(self): + return bool(self.use_global_dns) + + @dbus.service.method('org.wicd.daemon') + def GetWPADriver(self): + '''returns the wpa driver the daemon is using''' + print 'returned wpa driver' + return str(self.wifi.wpa_driver) + #end function GetWPADriver + + @dbus.service.method('org.wicd.daemon') + def GetWiredInterface(self): + '''returns the wired interface''' + print 'returning wired interface' + return str(self.wired.wired_interface) + #end function GetWiredInterface + + @dbus.service.method('org.wicd.daemon') + def GetWirelessInterface(self): + '''returns the wireless interface the daemon is using''' + print 'returning wireless interface to client' + return str(self.wifi.wireless_interface) + #end function GetWirelessInterface + + @dbus.service.method('org.wicd.daemon') + def SetDebugMode(self,debug): + '''sets if debugging mode is on or off''' + config = ConfigParser.ConfigParser() + config.read(self.app_conf) + config.set("Settings","debug_mode",debug) + configfile = open(self.app_conf,"w") + config.write(configfile) + self.debug_mode = debug + + @dbus.service.method('org.wicd.daemon') + def GetDebugMode(self): + '''returns whether debugging is enabled''' + return bool(int(self.debug_mode)) + + @dbus.service.method('org.wicd.daemon') + def GetGlobalDNSAddresses(self): + '''returns the global dns addresses''' + print 'returning global dns addresses to client' + return (self.dns1,self.dns2,self.dns3) + #end function GetWirelessInterface + + ########## WIRELESS FUNCTIONS + ################################# + + @dbus.service.method('org.wicd.daemon.wireless') + def SetHiddenNetworkESSID(self,essid): + '''sets the ESSID of a hidden network for use with ConnectionWizard.Scan''' + print 'setting hidden essid: ' + str(essid) + self.hidden_essid = str(misc.Noneify(essid)) + + @dbus.service.method('org.wicd.daemon.wireless') + def Scan(self): + '''scans for wireless networks, optionally using a (hidden) essid set with SetHiddenNetworkESSID''' + print 'scanning start' + scan = self.wifi.Scan(str(self.hidden_essid)) #_should_ already be a string but you never know... + self.LastScan = scan + print 'scanning done' + print 'found',str(len(scan)),'networks:', + for i in scan: + print i, + self.ReadWirelessNetworkProfile(i) + print + #end function FreshScan + + @dbus.service.method('org.wicd.daemon.wireless') + def DisconnectWireless(self): + '''disconnects all wireless networks''' + self.SetForcedDisconnect(True) + self.wifi.Disconnect() + #end function DisconnectWireless + + @dbus.service.method('org.wicd.daemon.wireless') + def SetWirelessBeforeScript(self,script): + self.wifi.before_script = script + #end function SetWirelessBeforeScript + + @dbus.service.method('org.wicd.daemon.wireless') + def SetWirelessAfterScript(self,script): + self.wifi.after_script = script + #end function SetWirelessAfterScript + + @dbus.service.method('org.wicd.daemon.wireless') + def GetNumberOfNetworks(self): + '''returns number of networks''' + print 'returned number of networks...',len(self.LastScan) + return len(self.LastScan) + #end function GetNumberOfNetworks + + @dbus.service.method('org.wicd.daemon.wireless') + def CreateAdHocNetwork(self,essid,channel,ip,enctype,key,encused,ics): + '''creates an ad-hoc network using user inputted settings''' + print 'attempting to create ad-hoc network...' + self.wifi.CreateAdHocNetwork(essid,channel,ip,enctype,key,encused,ics) + #end function CreateAdHocNetwork + + @dbus.service.method('org.wicd.daemon.wireless') + def GetAutoReconnect(self): + '''returns if wicd should automatically try to reconnect is connection is lost''' + do = bool(int(self.auto_reconnect)) + return self.__printReturn('returning automatically reconnect when connection drops',do) + #end function GetAutoReconnect + + @dbus.service.method('org.wicd.daemon.wireless') + def SetAutoReconnect(self,value): + '''sets if wicd should try to reconnect with connection drops''' + print 'setting automatically reconnect when connection drops' + config = ConfigParser.ConfigParser() + config.read(self.app_conf) + config.set("Settings","auto_reconnect",int(value)) + config.write(open(self.app_conf,"w")) + self.auto_reconnect = value + #end function SetAutoReconnect + + @dbus.service.method('org.wicd.daemon.wireless') + def AutoConnect(self,fresh): + '''first tries to autoconnect to a wireled network, if that fails it tries a wireless connection''' + if fresh and self.CheckPluggedIn() == True: + defaultNetwork = self.GetDefaultWiredNetwork() + if defaultNetwork != None: + self.ReadWiredNetworkProfile(defaultNetwork) + self.ConnectWired() + time.sleep(1) + print "Attempting to autoconnect with wired interface..." + while self.CheckIfWiredConnecting(): # Keeps us from going into an infinite connecting loop + time.sleep(1) + print "...done autoconnecting." + else: + print "couldn't find a default wired connection, wired autoconnect failed" + else: + print "no wired connection present, wired autoconnect failed" + print 'attempting to autoconnect to wireless network' + if fresh: + self.Scan() + if self.GetWirelessInterface() != None: + for x in self.LastScan: + if bool(self.LastScan[x]["has_profile"]): + print str(self.LastScan[x]["essid"]) + ' has profile' + if bool(self.LastScan[x].get('automatic')): + print 'automatically connecting to...',str(self.LastScan[x]["essid"]) + self.ConnectWireless(x) + time.sleep(3) + while self.CheckIfWirelessConnecting(): + print "autoconnecting... hold" + #not sure why I need to get IPs, but + #it solves the autoconnect problem + #i think it has something to do with + #making IO calls while threads are working...? + #if anyone knows why...email me at compwiz18@gmail.com + #only some people need these statements for autoconnect + #to function properly + self.GetWirelessIP() + ### + # removed line below for 1.3.0 - if there is trouble with + # connecting at boot, + # add back to file -- adam + ### + # as far as I can tell, it seems fine - what does everyone else + # think? -- adam + ### + #self.GetWiredIP() + time.sleep(2) + print "autoconnecting... done" + return + print "unable to autoconnect, you'll have to manually connect" + else: + print 'autoconnect failed because wireless interface == None' + #end function AutoConnect + + @dbus.service.method('org.wicd.daemon.wireless') + def GetWirelessProperty(self,networkid,property): + '''retrieves wireless property from the network specified''' + value = self.LastScan[networkid].get(property) + print 'returned wireless network',networkid,'property',property,'of value',value + return value + #end function GetWirelessProperty + + @dbus.service.method('org.wicd.daemon.wireless') + def SetWirelessProperty(self,networkid,property,value): + '''sets property to value in network specified''' + #simple - set the value of the item in our current data + #to the value the client asked for + print 'setting wireless network',networkid,'property',property,'to value',value + self.LastScan[networkid][property] = misc.Noneify(value) + #end function SetProperty + + @dbus.service.method('org.wicd.daemon.wireless') + def DetectWirelessInterface(self): + '''returns an automatically detected wireless interface''' + iface = self.wifi.DetectWirelessInterface() + print 'automatically detected wireless interface',iface + return str(iface) + #end function DetectWirelessInterface + + @dbus.service.method('org.wicd.daemon.wireless') + def GetCurrentSignalStrength(self): + '''returns the current signal strength''' + strength = int(self.wifi.GetSignalStrength()) + print 'returning current signal strength',strength + return strength + #end function GetCurrentSignalStrength + + @dbus.service.method('org.wicd.daemon.wireless') + def GetCurrentNetwork(self): + '''returns the current network''' + current_network = str(self.wifi.GetCurrentNetwork()) + print current_network + return current_network + #end function GetCurrentNetwork + + @dbus.service.method('org.wicd.daemon.wireless') + def GetCurrentNetworkID(self): + '''returns the id of the current network, or -1 if network is not found''' + currentESSID = self.GetCurrentNetwork() + for x in self.LastScan: + if self.LastScan[x]['essid'] == currentESSID: + print 'current network found, id is ',x + return x + print 'returning -1, current network not found' + return -1 + #end function GetCurrentNetwork + + @dbus.service.method('org.wicd.daemon.wireless') + def ConnectWireless(self,id): + '''connects the the wireless network specified by id''' + #will returned instantly, that way we don't hold up dbus + #CheckIfWirelessConnecting can be used to test if the connection + #is done + self.SetForcedDisconnect(False) + self.wifi.before_script = self.GetWirelessProperty(id,'beforescript') + self.wifi.after_script = self.GetWirelessProperty(id,'afterscript') + print 'connecting to wireless network',self.LastScan[id]['essid'] + return self.wifi.Connect(self.LastScan[id]) + #end function Connect + + @dbus.service.method('org.wicd.daemon.wireless') + def GetForcedDisconnect(self): + '''returns whether wireless was dropped by user, or for some other reason''' + return self.forced_disconnect + #end function GetForcedDisconnect + + @dbus.service.method('org.wicd.daemon.wireless') + def SetForcedDisconnect(self,value): + '''sets whether wireless has been disconnected by user since last connection''' + self.forced_disconnect = value + #end function SetForcedDisconnect + + @dbus.service.method('org.wicd.daemon.wireless') + def CheckIfWirelessConnecting(self): + '''returns True if wireless interface is connecting, otherwise False''' + if not self.wifi.ConnectingThread == None: + #if ConnectingThread exists, then check for it's + #status, if it doesn't, we aren't connecting + status = self.wifi.ConnectingThread.IsConnecting + print 'wireless connecting',status + return status + else: + print 'wireless connecting',False + return False + #end function CheckIfWirelessConnecting + + @dbus.service.method('org.wicd.daemon.wireless') + def GetWirelessIP(self): + '''returns the IP that the wireless interface has''' + ip = self.wifi.GetIP() + print 'returning wireless ip',ip + return ip + #end function GetWirelessIP + + @dbus.service.method('org.wicd.daemon.wireless') + def CheckWirelessConnectingMessage(self): + '''returns the wireless interface's status message''' + if not self.wifi.ConnectingThread == None: + stat = self.wifi.ConnectingThread.GetStatus() + print 'wireless connect status',stat + return stat + else: + print 'wireless connect status',False + return False + #end function CheckWirelessConnectingMessage + + @dbus.service.method('org.wicd.daemon.wireless') + def CancelConnect(self): + '''cancels the wireless connection attempt''' + print 'canceling connection attempt' + if not self.wifi.ConnectingThread == None: + self.wifi.ConnectingThread.ShouldDie = True + misc.Run("killall dhclient dhclient3 wpa_supplicant") + #end function CancelConnect + + ########## WIRED FUNCTIONS + ################################# + + @dbus.service.method('org.wicd.daemon.wired') + def GetWiredIP(self): + '''returns the wired interface\'s ip address''' + ip = self.wired.GetIP() + print 'returning wired ip',ip + return ip + #end function GetWiredIP + + @dbus.service.method('org.wicd.daemon.wired') + def CheckIfWiredConnecting(self): + '''returns True if wired interface is connecting, otherwise False''' + if not self.wired.ConnectingThread == None: + #if ConnectingThread exists, then check for it's + #status, if it doesn't exist, we aren't connecting + status = self.wired.ConnectingThread.IsConnecting + print 'wired connecting',status + return status + else: + print 'wired connecting',False + return False + #end function CheckIfWiredConnecting + + @dbus.service.method('org.wicd.daemon.wired') + def SetWiredBeforeScript(self,script): + '''sets pre-connection script to run for a wired connection''' + self.wired.before_script = script + #end function SetWiredBeforeScript + + @dbus.service.method('org.wicd.daemon.wired') + def SetWiredAfterScript(self,script): + '''sets post-connection script to run for a wired connection''' + self.wired.after_script = script + #end function SetWiredAfterScript + + @dbus.service.method('org.wicd.daemon.wired') + def CheckWiredConnectingMessage(self): + '''returns the wired interface\'s status message''' + if not self.wired.ConnectingThread == None: + status = self.wired.ConnectingThread.GetStatus() + print 'wired connect status',status + return status + else: + print 'wired connect status',False + return False + #end function CheckWiredConnectingMessage + + @dbus.service.method('org.wicd.daemon.wired') + def SetWiredProperty(self,property,value): + if self.WiredNetwork: + self.WiredNetwork[property] = misc.Noneify(value) + print 'set',property,'to',misc.Noneify(value) + return True + else: + print 'WiredNetwork does not exist' + return False + #end function SetWiredProperty + + @dbus.service.method('org.wicd.daemon.wired') + def GetWiredProperty(self,property): + if self.WiredNetwork: + value = self.WiredNetwork.get(property) + print 'returned',property,'with value of',value,'to client...' + return value + else: + print 'WiredNetwork does not exist' + return False + #end function GetWiredProperty + + @dbus.service.method('org.wicd.daemon.wired') + def SetAlwaysShowWiredInterface(self,value): + print 'setting always show wired interface' + config = ConfigParser.ConfigParser() + config.read(self.app_conf) + config.set("Settings","always_show_wired_interface",int(value)) + config.write(open(self.app_conf,"w")) + self.always_show_wired_interface = value + #end function SetAlwaysShowWiredInterface + + @dbus.service.method('org.wicd.daemon.wired') + def GetAlwaysShowWiredInterface(self): + do = bool(int(self.always_show_wired_interface)) + return self.__printReturn('returning always show wired interface',do) + #end function GetAlwaysShowWiredInterface + + @dbus.service.method('org.wicd.daemon.wired') + def CheckPluggedIn(self): + if not self.wired.wired_interface == None: + return self.__printReturn('returning plugged in',self.wired.CheckPluggedIn()) + else: + return self.__printReturn("returning plugged in",None) + #end function CheckPluggedIn + + @dbus.service.method('org.wicd.daemon.wired') + def ConnectWired(self): + '''connects to a wired network''' + #simple enough. + self.wired.before_script = self.GetWiredProperty("beforescript") + self.wired.after_script = self.GetWiredProperty("afterscript") + self.wired.Connect(self.WiredNetwork) + + ########## LOG FILE STUFF + ################################# + + @dbus.service.method('org.wicd.daemon.config') + def DisableLogging(self): + global logging_enabled + logging_enabled = False + + @dbus.service.method('org.wicd.daemon.config') + def EnableLogging(self): + global logging_enabled + logging_enabled = True + + ########## CONFIGURATION FILE FUNCTIONS + ################################# + + @dbus.service.method('org.wicd.daemon.config') + def CreateWiredNetworkProfile(self,profilename): + #should include: profilename,ip,netmask,gateway,dns1,dns2,dns3 + print "creating profile for " + str(profilename) + config = ConfigParser.ConfigParser() + config.read(self.wired_conf) + if config.has_section(profilename): + return False + config.add_section(profilename) + config.set(profilename,"ip",None) + config.set(profilename,"broadcast",None) + config.set(profilename,"netmask",None) + config.set(profilename,"gateway",None) + config.set(profilename,"dns1",None) + config.set(profilename,"dns2",None) + config.set(profilename,"dns3",None) + config.set(profilename,"beforescript",None) + config.set(profilename,"afterscript",None) + config.set(profilename,"default",False) + config.write( open(self.wired_conf,"w")) + return True + #end function CreateWiredNetworkProfile + + @dbus.service.method('org.wicd.daemon.config') + def UnsetWiredDefault(self): + '''Unsets the default option in the current default wired profile''' + config = ConfigParser.ConfigParser() + config.read(self.wired_conf) + profileList = config.sections() + print "profileList = ",profileList + for profile in profileList: + print "profile = ", profile + if config.get(profile,"default") == "True": + print "removing existing default" + config.set(profile,"default", False) + self.SaveWiredNetworkProfile(profile) + #end function UnsetWiredDefault + + @dbus.service.method('org.wicd.daemon.config') + def GetDefaultWiredNetwork(self): + config = ConfigParser.ConfigParser() + config.read(self.wired_conf) + profileList = config.sections() + for profile in profileList: + if config.get(profile,"default") == "True": + return profile + return None + + @dbus.service.method('org.wicd.daemon.config') + def DeleteWiredNetworkProfile(self,profilename): + print "deleting profile for " + str(profilename) + config = ConfigParser.ConfigParser() + config.read(self.wired_conf) + if config.has_section(profilename): + config.remove_section(profilename) + else: + return "500: Profile does not exist" + config.write( open(self.wired_conf,"w")) + return "100: Profile Deleted" + #end function DeleteWiredNetworkProfile + + @dbus.service.method('org.wicd.daemon.config') + def SaveWiredNetworkProfile(self,profilename): + #should include: profilename,ip,netmask,gateway,dns1,dns2 + print "setting profile for " + str(profilename) + config = ConfigParser.ConfigParser() + config.read(self.wired_conf) + if config.has_section(profilename): + config.remove_section(profilename) + config.add_section(profilename) + for x in self.WiredNetwork: + config.set(profilename,x,self.WiredNetwork[x]) + config.write( open(self.wired_conf,"w")) + return "100: Profile Written" + #end function SaveWiredNetworkProfile + + @dbus.service.method('org.wicd.daemon.config') + def ReadWiredNetworkProfile(self,profilename): + profile = {} + config = ConfigParser.ConfigParser() + config.read(self.wired_conf) + if config.has_section(profilename) == True: + for x in config.options(profilename): + profile[x] = misc.Noneify(config.get(profilename,x)) + self.WiredNetwork = profile + return "100: Loaded Profile" + else: + self.WiredNetwork = None + return "500: Profile Not Found" + #end function ReadWiredNetworkProfile + + @dbus.service.method('org.wicd.daemon.config') + def GetWiredProfileList(self): + config = ConfigParser.ConfigParser() + config.read(self.wired_conf) + print config.sections() + if config.sections(): + return config.sections() + else: + return None + #end function GetWiredProfileList + + @dbus.service.method('org.wicd.daemon.config') + def SaveWirelessNetworkProfile(self,id): + print "setting network profile" + config = ConfigParser.ConfigParser() + config.read(self.wireless_conf) + if config.has_section(self.LastScan[id]["bssid"]): + config.remove_section(self.LastScan[id]["bssid"]) + config.add_section(self.LastScan[id]["bssid"]) + #add the essid so that people reading the config can figure + #out which network is which. it will not be read + for x in self.LastScan[id]: + config.set(self.LastScan[id]["bssid"],x,self.LastScan[id][x]) + config.write(open(self.wireless_conf,"w")) + #end function SaveWirelessNetworkProfile + + @dbus.service.method('org.wicd.daemon.config') + def SaveWirelessNetworkProperty(self,id,option): + print "setting network option " + str(option) + " to " + str(self.LastScan[id][option]) + config = ConfigParser.ConfigParser() + config.read(self.wireless_conf) + if config.has_section(self.LastScan[id]["bssid"]): + config.set(self.LastScan[id]["bssid"],option,str(self.LastScan[id][option])) + config.write(open(self.wireless_conf,"w")) + #end function SaveWirelessNetworkProperty + + @dbus.service.method('org.wicd.daemon.config') + def ReadWirelessNetworkProfile(self,id): + config = ConfigParser.ConfigParser() + config.read(self.wireless_conf) + print self.LastScan[id]["bssid"] + if config.has_section(self.LastScan[id]["bssid"]): + self.LastScan[id]["has_profile"] = True + if config.has_option(self.LastScan[id]["bssid"],"beforescript"): + self.LastScan[id]["beforescript"]=misc.Noneify(config.get(self.LastScan[id]["bssid"],"beforescript")) + else: + self.LastScan[id]["beforescript"]= None + if config.has_option(self.LastScan[id]["bssid"],"afterscript"): + self.LastScan[id]["afterscript"]=misc.Noneify(config.get(self.LastScan[id]["bssid"],"afterscript")) + else: + self.LastScan[id]["afterscript"] = None + #read the essid because we be needing to name those hidden + #wireless networks now - but only read it if it is hidden + if self.LastScan[id]["hidden"] == True: + self.LastScan[id]["essid"] = misc.Noneify(config.get(self.LastScan[id]["bssid"],"essid")) + for x in config.options(self.LastScan[id]["bssid"]): + if self.LastScan[id].has_key(x) == False: + self.LastScan[id][x] = misc.Noneify(config.get(self.LastScan[id]["bssid"],x)) + return "100: Loaded Profile" + else: + self.LastScan[id]["has_profile"] = False + self.LastScan[id]['use_static_dns'] = bool(int(self.GetUseGlobalDNS())) + self.LastScan[id]['use_global_dns'] = bool(int(self.GetUseGlobalDNS())) + return "500: Profile Not Found" + #end function ReadWirelessNetworkProfile + + ############################################# + ########## INTERNAL FUNCTIONS ############### + ############################################# + # so don't touch the stuff below # + # it read/writes the configuration files # + # and shouldn't need to be changed # + # unless you add a new property... # + # then be SURE YOU CHANGE IT # + ############################################# + + def __printReturn(self,text,value): + '''prints the specified text followed by the specified value, then returns value''' + print text,value + return value + #end function __printReturn + + def ReadConfig(self): + if os.path.isfile( self.app_conf ): + config = ConfigParser.ConfigParser() + config.read(self.app_conf) + if config.has_section("Settings"): + if config.has_option("Settings","wireless_interface"): + print "found wireless interface in configuration...", + self.SetWirelessInterface(config.get("Settings","wireless_interface")) + if config.has_option("Settings","wired_interface"): + print "found wired interface in configuration...", + self.SetWiredInterface(config.get("Settings","wired_interface")) + if config.has_option("Settings","wpa_driver"): + print "found wpa driver in configuration...", + self.SetWPADriver(config.get("Settings","wpa_driver")) + if config.has_option("Settings","always_show_wired_interface"): + self.always_show_wired_interface = config.get("Settings","always_show_wired_interface") + else: + config.set("Settings","always_show_wired_interface","False") + self.always_show_wired_interface = False + if config.has_option("Settings","use_global_dns"): + self.SetUseGlobalDNS(config.get("Settings","use_global_dns")) + dns1, dns2, dns3 = ('None','None','None') #so we can access them later + if config.has_option("Settings","global_dns_1"): + dns1 = config.get('Settings','global_dns_1') + if config.has_option("Settings","global_dns_2"): + dns2 = config.get('Settings','global_dns_2') + if config.has_option("Settings","global_dns_3"): + dns3 = config.get('Settings','global_dns_3') + self.SetGlobalDNS(dns1,dns2,dns3) + else: + self.SetUseGlobalDNS(False) + if config.has_option("Settings","auto_reconnect"): + self.auto_reconnect = config.get("Settings","auto_reconnect") + else: + config.set("Settings","auto_reconnect","False") + self.auto_reconnect = False + if config.has_option("Settings","debug_mode"): + self.debug_mode = config.get("Settings","debug_mode") + else: + self.debug_mode = False + config.set("Settings","debug_mode","False") + else: + print "configuration file exists, no settings found, adding defaults..." + configfile = open(self.app_conf,"w") + config.add_section("Settings") + config.set("Settings","wireless_interface","wlan0") + config.set("Settings","wired_interface","eth0") + config.set("Settings","wpa_driver","wext") + config.set("Settings","always_show_wired_interface","False") + config.set("Settings","auto_reconnect","False") + config.set("Settings","debug_mode","False") + config.set("Settings","use_global_dns","False") + config.set("Settings","dns1","None") + config.set("Settings","dns2","None") + config.set("Settings","dns3","None") + self.SetGlobalDNS(config.get('Settings','dns1'),config.get('Settings','dns2'),config.get('Settings','dns3')) + self.SetWirelessInterface(config.get("Settings","wireless_interface")) + self.SetWiredInterface(config.get("Settings","wired_interface")) + self.SetWPADriver(config.get("Settings","wpa_driver")) + self.SetAlwaysShowWiredInterface(False) + self.SetAutoReconnect(True) + self.SetDebugMode(False) + config.write(configfile) + + else: + #write some defaults maybe? + print "configuration file not found, creating, adding defaults..." + config = ConfigParser.ConfigParser() + config.read(self.app_conf) + config.add_section("Settings") + config.set("Settings","wireless_interface","wlan0") + config.set("Settings","wired_interface","eth0") + config.set("Settings","always_show_wired_interface","False") + config.set("Settings","auto_reconnect","False") + config.set("Settings","debug_mode","False") + config.set("Settings","dns1","None") + config.set("Settings","dns2","None") + config.set("Settings","dns3","None") + iface = self.DetectWirelessInterface() + if iface: + config.set("Settings","wireless_interface",iface) + else: + print "couldn't detect a wireless interface, using wlan0..." + config.set("Settings","wireless_interface","wlan0") + config.set("Settings","wpa_driver","wext") + config.write(open(self.app_conf,"w")) + self.SetWirelessInterface(config.get("Settings","wireless_interface")) + self.SetWiredInterface(config.get("Settings","wired_interface")) + self.SetWPADriver(config.get("Settings","wpa_driver")) + self.SetAlwaysShowWiredInterface(False) + self.SetAutoReconnect(True) + self.SetDebugMode(False) + self.SetGlobalDNS(None,None,None) + #end If + + if os.path.isfile( self.wireless_conf ): + print "wireless configuration file found..." + #don't do anything since it is there + pass + else: + #we don't need to put anything in it, so just make it + print "wireless configuration file not found, creating..." + open( self.wireless_conf,"w" ).close() + #end If + + if os.path.isfile( self.wired_conf ): + print "wired configuration file found..." + #don't do anything since it is there + pass + else: + print "wired confguration file not found, creating..." + #we don't need to put anything in it, so just make it + open( self.wired_conf,"w" ).close() + #end If + + #hide the files, so the keys aren't exposed + print "chmoding configuration files 0600..." + os.chmod(self.app_conf,0600) + os.chmod(self.wireless_conf,0600) + os.chmod(self.wired_conf,0600) + + #make root own them + print "chowning configuration files root:root..." + os.chown(self.app_conf, 0, 0) + os.chown(self.wireless_conf, 0, 0) + os.chown(self.wired_conf, 0, 0) + + print "autodetected wireless interface...",self.DetectWirelessInterface() + print "using wireless interface...",self.GetWirelessInterface()[5:] + #end function ReadConfig ## fork from the parent terminal +## borrowed from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012 -if True: #for easy disabling - try: - pid = os.fork() - if pid > 0: - # exit first parent - sys.exit(0) +if False: #True: #for easy disabling + try: + pid = os.fork() + if pid > 0: + # exit first parent + sys.exit(0) - except OSError, e: - print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror) - sys.exit(1) + except OSError, e: + print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror) + sys.exit(1) - # decouple from parent environment - os.setsid() - os.umask(0) + # decouple from parent environment + os.setsid() + os.umask(0) - # do second fork - try: - pid = os.fork() - if pid > 0: - print "wicd daemon: pid " + str(pid) - sys.exit(0) - except OSError, e: - print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror) - sys.exit(1) + # do second fork + try: + pid = os.fork() + if pid > 0: + print "wicd daemon: pid " + str(pid) + sys.exit(0) + except OSError, e: + print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror) + sys.exit(1) #kill output #POI:500 stdout redirection output = FlushWriter() -sys.stdout = output #open("data/wicd.log","w") -sys.stderr = output +#sys.stdout = output #open("data/wicd.log","w") +#sys.stderr = output print "---------------------------" print "wicd initalizing..." diff --git a/gui.py b/gui.py index 62fbc00..01aec22 100644 --- a/gui.py +++ b/gui.py @@ -1,38 +1,38 @@ #!/usr/bin/python import os,sys if __name__ == '__main__': - os.chdir(os.path.dirname(os.path.normpath(os.path.join(os.getcwd(),sys.argv[0])))) + os.chdir(os.path.dirname(os.path.normpath(os.path.join(os.getcwd(),sys.argv[0])))) try: - import pygtk - pygtk.require("2.0") + import pygtk + pygtk.require("2.0") except: - pass + pass try: - import gtk, gtk.glade + import gtk, gtk.glade except: - print 'Missing GTK and gtk.glade. Aborting.' - sys.exit(1) + print 'Missing GTK and gtk.glade. Aborting.' + sys.exit(1) import time, os, misc, gettext, locale, gobject, dbus, dbus.service if getattr(dbus, 'version', (0,0,0)) >= (0,41,0): - import dbus.glib + import dbus.glib #declare the connections to the daemon, so that they may be accessed #in any class bus = dbus.SystemBus() try: - print 'attempting to connect daemon...' - proxy_obj = bus.get_object('org.wicd.daemon', '/org/wicd/daemon') - print 'success' + print 'attempting to connect daemon...' + proxy_obj = bus.get_object('org.wicd.daemon', '/org/wicd/daemon') + print 'success' except: - print 'daemon not running, running gksudo ./daemon.py...' - misc.PromptToStartDaemon() - time.sleep(1) - try: - proxy_obj = bus.get_object('org.wicd.daemon', '/org/wicd/daemon') - except: - print 'daemon still not running, aborting.' + print 'daemon not running, running gksudo ./daemon.py...' + misc.PromptToStartDaemon() + time.sleep(1) + 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') wireless = dbus.Interface(proxy_obj, 'org.wicd.daemon.wireless') wired = dbus.Interface(proxy_obj, 'org.wicd.daemon.wired') @@ -50,15 +50,15 @@ langs = list() #Check the default locale lc, encoding = locale.getdefaultlocale() if (lc): - #If we have a default, it's the first in the list - langs = [lc] + #If we have a default, it's the first in the list + langs = [lc] # Now lets get all of the supported languages on the system osLanguage = os.environ.get('LANGUAGE', None) if (osLanguage): - #langage comes back something like en_CA:en_US:en_GB:en - #on linuxy systems, on Win32 it's nothing, so we need to - #split it up into a list - langs += osLanguage.split(":") + #langage comes back something like en_CA:en_US:en_GB:en + #on linuxy systems, on Win32 it's nothing, so we need to + #split it up into a list + langs += osLanguage.split(":") #Now add on to the back of the list the translations that we #know that we have, our defaults @@ -163,111 +163,111 @@ language['done'] = _('Done connecting...') ######################################## class LinkButton(gtk.EventBox): - label = None - def __init__(self): - gtk.EventBox.__init__(self) - self.connect("realize",self.__setHandCursor) #set the hand cursor when the box is initalized - label = gtk.Label() - label.set_markup(" " + language['connect'] + "") - label.set_alignment(0,.5) - label.show() - self.add(label) - self.show_all() - - def __setHandCursor(self,widget): - #we need this to set the cursor to a hand for the link labels - #I'm not entirely sure what it does :P - hand = gtk.gdk.Cursor(gtk.gdk.HAND1) - widget.window.set_cursor(hand) + label = None + def __init__(self): + gtk.EventBox.__init__(self) + self.connect("realize",self.__setHandCursor) #set the hand cursor when the box is initalized + label = gtk.Label() + label.set_markup(" " + language['connect'] + "") + label.set_alignment(0,.5) + label.show() + self.add(label) + self.show_all() + + def __setHandCursor(self,widget): + #we need this to set the cursor to a hand for the link labels + #I'm not entirely sure what it does :P + hand = gtk.gdk.Cursor(gtk.gdk.HAND1) + widget.window.set_cursor(hand) class SmallLabel(gtk.Label): - def __init__(self,text=''): - gtk.Label.__init__(self,text) - self.set_size_request(50,-1) + def __init__(self,text=''): + gtk.Label.__init__(self,text) + self.set_size_request(50,-1) class LabelEntry(gtk.HBox): - '''a label on the left with a textbox on the right''' - def __init__(self,text): - gtk.HBox.__init__(self) - self.entry = gtk.Entry() - self.entry.set_size_request(200,-1) - self.label = SmallLabel() - self.label.set_text(text) - self.label.set_size_request(170,-1) - self.pack_start(self.label,fill=False,expand=False) - self.pack_start(self.entry,fill=False,expand=False) - self.label.show() - self.entry.show() - self.entry.connect('focus-out-event',self.hide_characters) - self.entry.connect('focus-in-event',self.show_characters) - self.auto_hide_text = False - self.show() + '''a label on the left with a textbox on the right''' + def __init__(self,text): + gtk.HBox.__init__(self) + self.entry = gtk.Entry() + self.entry.set_size_request(200,-1) + self.label = SmallLabel() + self.label.set_text(text) + self.label.set_size_request(170,-1) + self.pack_start(self.label,fill=False,expand=False) + self.pack_start(self.entry,fill=False,expand=False) + self.label.show() + self.entry.show() + self.entry.connect('focus-out-event',self.hide_characters) + self.entry.connect('focus-in-event',self.show_characters) + self.auto_hide_text = False + self.show() - def set_text(self,text): - #for compatibility... - self.entry.set_text(text) + def set_text(self,text): + #for compatibility... + self.entry.set_text(text) - def get_text(self): - return self.entry.get_text() + def get_text(self): + return self.entry.get_text() - def set_auto_hidden(self,value): - self.entry.set_visibility(False) - self.auto_hide_text = value + def set_auto_hidden(self,value): + self.entry.set_visibility(False) + self.auto_hide_text = value - def show_characters(self,widget=None,event=None): - #when the box has focus, show the characters - if self.auto_hide_text and widget: - self.entry.set_visibility(True) + def show_characters(self,widget=None,event=None): + #when the box has focus, show the characters + if self.auto_hide_text and widget: + self.entry.set_visibility(True) - def hide_characters(self,widget=None,event=None): - #when the box looses focus, hide them - if self.auto_hide_text and widget: - self.entry.set_visibility(False) + def hide_characters(self,widget=None,event=None): + #when the box looses focus, hide them + if self.auto_hide_text and widget: + self.entry.set_visibility(False) class GreyLabel(gtk.Label): - def __init__(self): - gtk.Label.__init__(self) - def set_label(self,text): - self.set_markup("" + text + "") - self.set_alignment(0,0) + def __init__(self): + gtk.Label.__init__(self) + def set_label(self,text): + self.set_markup("" + text + "") + self.set_alignment(0,0) ######################################## ##### OTHER RANDOM FUNCTIONS ######################################## def noneToString(text): - '''used for putting text in a text box - if the value to put in is 'None' the box will be blank''' - if text == None or text == "None" or text == "": - return "None" - else: - return str(text) + '''used for putting text in a text box - if the value to put in is 'None' the box will be blank''' + if text == None or text == "None" or text == "": + return "None" + else: + return str(text) def noneToBlankString(text): - '''if text is None, 'None', or '' then return '', otherwise return str(text)''' - if text == None or text == "None" or text == "": - return "" - else: - return str(text) + '''if text is None, 'None', or '' then return '', otherwise return str(text)''' + if text == None or text == "None" or text == "": + return "" + else: + return str(text) def stringToNone(text): - '''performs opposite function of noneToString''' - if text == "" or text == "None" or text == None: - return None - else: - return str(text) + '''performs opposite function of noneToString''' + if text == "" or text == "None" or text == None: + return None + else: + return str(text) def stringToBoolean(text): - '''turns a "True" to True or a "False" to False otherwise returns the text''' - if text == "True": - return True - if text == "False": - return False - return text + '''turns a "True" to True or a "False" to False otherwise returns the text''' + if text == "True": + return True + if text == "False": + return False + return text def checkboxTextboxToggle(checkbox,textboxes): - #really bad practice, but checkbox == self - for textbox in textboxes: - textbox.set_sensitive(checkbox.get_active()) + #really bad practice, but checkbox == self + for textbox in textboxes: + textbox.set_sensitive(checkbox.get_active()) ######################################## ##### NETWORK LIST CLASSES @@ -275,850 +275,858 @@ def checkboxTextboxToggle(checkbox,textboxes): class PrettyNetworkEntry(gtk.HBox): - '''adds an image and a connect button to a NetworkEntry''' - def __init__(self,expander): - gtk.HBox.__init__(self) - #add the stuff to the hbox (self) - self.expander = expander - self.expander.show() - self.expander.higherLevel = self #do this so that the expander can access the stuff inside me - self.tempVBox = gtk.VBox(False,1) - self.tempVBox.show() - self.connectButton = LinkButton() - self.connectButton.show() - self.tempVBox.pack_start(self.expander,fill=False,expand=False) - self.tempVBox.pack_start(self.connectButton,fill=False,expand=False) - self.pack_end(self.tempVBox) + '''adds an image and a connect button to a NetworkEntry''' + def __init__(self,expander): + gtk.HBox.__init__(self) + #add the stuff to the hbox (self) + self.expander = expander + self.expander.show() + self.expander.higherLevel = self #do this so that the expander can access the stuff inside me + self.tempVBox = gtk.VBox(False,1) + self.tempVBox.show() + self.connectButton = LinkButton() + self.connectButton.show() + self.tempVBox.pack_start(self.expander,fill=False,expand=False) + self.tempVBox.pack_start(self.connectButton,fill=False,expand=False) + self.pack_end(self.tempVBox) class PrettyWiredNetworkEntry(PrettyNetworkEntry): - def __init__(self): - PrettyNetworkEntry.__init__(self,WiredNetworkEntry()) - #center the picture and pad it a bit - self.image = gtk.Image() - self.image.set_alignment(.5,0) + def __init__(self): + PrettyNetworkEntry.__init__(self,WiredNetworkEntry()) + #center the picture and pad it a bit + self.image = gtk.Image() + self.image.set_alignment(.5,0) - self.image.set_size_request(60,-1) - self.image.set_from_icon_name("network-wired",6) - self.image.show() - self.pack_start(self.image,fill=False,expand=False) - self.show() - self.expander.checkEnable() - self.expander.show() + self.image.set_size_request(60,-1) + self.image.set_from_icon_name("network-wired",6) + self.image.show() + self.pack_start(self.image,fill=False,expand=False) + self.show() + self.expander.checkEnable() + self.expander.show() class PrettyWirelessNetworkEntry(PrettyNetworkEntry): - def __init__(self,networkID): - PrettyNetworkEntry.__init__(self,WirelessNetworkEntry(networkID)) - self.image = gtk.Image() - self.image.set_padding(0,0) - self.image.set_alignment(.5,0) - self.image.set_size_request(60,-1) - self.image.set_from_icon_name("network-wired",6) - self.pack_start(self.image,fill=False,expand=False) - self.setSignalStrength(wireless.GetWirelessProperty(networkID,'quality')) - self.setMACAddress(wireless.GetWirelessProperty(networkID,'bssid')) - self.setMode(wireless.GetWirelessProperty(networkID,'mode')) - self.setChannel(wireless.GetWirelessProperty(networkID,'channel')) - self.setEncryption(wireless.GetWirelessProperty(networkID,'encryption'),wireless.GetWirelessProperty(networkID,'encryption_method')) - #show everything - self.show_all() - - def setSignalStrength(self,strength): - strength = int(strength) - if strength > 75: - self.image.set_from_file("images/signal-100.png") - elif strength > 50: - self.image.set_from_file("images/signal-75.png") - elif strength > 25: - self.image.set_from_file("images/signal-50.png") - else: - self.image.set_from_file("images/signal-25.png") - self.expander.setSignalStrength(strength) - - def setMACAddress(self,address): - self.expander.setMACAddress(address) + def __init__(self,networkID): + PrettyNetworkEntry.__init__(self,WirelessNetworkEntry(networkID)) + self.image = gtk.Image() + self.image.set_padding(0,0) + self.image.set_alignment(.5,0) + self.image.set_size_request(60,-1) + self.image.set_from_icon_name("network-wired",6) + self.pack_start(self.image,fill=False,expand=False) + self.setSignalStrength(wireless.GetWirelessProperty(networkID,'quality')) + self.setMACAddress(wireless.GetWirelessProperty(networkID,'bssid')) + self.setMode(wireless.GetWirelessProperty(networkID,'mode')) + self.setChannel(wireless.GetWirelessProperty(networkID,'channel')) + self.setEncryption(wireless.GetWirelessProperty(networkID,'encryption'),wireless.GetWirelessProperty(networkID,'encryption_method')) + #show everything + self.show_all() + + def setSignalStrength(self,strength): + strength = int(strength) + if strength > 75: + self.image.set_from_file("images/signal-100.png") + elif strength > 50: + self.image.set_from_file("images/signal-75.png") + elif strength > 25: + self.image.set_from_file("images/signal-50.png") + else: + self.image.set_from_file("images/signal-25.png") + self.expander.setSignalStrength(strength) + + def setMACAddress(self,address): + self.expander.setMACAddress(address) - def setEncryption(self,on,type): - self.expander.setEncryption(on,type) + def setEncryption(self,on,type): + self.expander.setEncryption(on,type) - def setChannel(self,channel): - self.expander.setChannel(channel) + def setChannel(self,channel): + self.expander.setChannel(channel) - def setMode(self,mode): - self.expander.setMode(mode) + def setMode(self,mode): + self.expander.setMode(mode) class NetworkEntry(gtk.Expander): - '''the basis for the entries in the network list''' - def __init__(self): - #make stuff exist, this is pretty long and boring - gtk.Expander.__init__(self) - self.txtIP = LabelEntry(language['ip']) - self.txtIP.entry.connect('focus-out-event',self.setDefaults) - self.txtNetmask = LabelEntry(language['netmask']) - self.txtGateway = LabelEntry(language['gateway']) - self.txtDNS1 = LabelEntry(language['dns'] + ' ' + language['1']) - self.txtDNS2 = LabelEntry(language['dns'] + ' ' + language['2']) - self.txtDNS3 = LabelEntry(language['dns'] + ' ' + language['3']) - #dns_addresses = daemon.GetGlobalDNSAddresses() - #self.txtDNS1.set_text(dns_addresses[0]) - #self.txtDNS2.set_text(dns_addresses[1]) - #self.txtDNS3.set_text(dns_addresses[2]) - self.txtBeforeScript = LabelEntry(language['before_script']) - self.txtAfterScript = LabelEntry(language['after_script']) - self.txtBeforeScript.label.set_size_request(200,-1) - self.txtAfterScript.label.set_size_request(200,-1) - self.checkboxStaticIP = gtk.CheckButton(language['use_static_ip']) - self.checkboxStaticDNS = gtk.CheckButton(language['use_static_dns']) - self.checkboxGlobalDNS = gtk.CheckButton(language['use_global_dns']) - self.expanderAdvanced = gtk.Expander(language['advanced_settings']) - self.expanderScripts = gtk.Expander(language['script_settings']) - self.vboxTop = gtk.VBox(False,0) - self.vboxAdvanced = gtk.VBox(False,0) - self.vboxScripts = gtk.VBox(False,0) - self.hboxDNS = gtk.HBox(False,0) - self.hboxDNS.pack_start(self.checkboxStaticDNS) - self.hboxDNS.pack_start(self.checkboxGlobalDNS) - self.vboxAdvanced.pack_start(self.checkboxStaticIP,fill=False,expand=False) - self.vboxAdvanced.pack_start(self.txtIP,fill=False,expand=False) - self.vboxAdvanced.pack_start(self.txtNetmask,fill=False,expand=False) - self.vboxAdvanced.pack_start(self.txtGateway,fill=False,expand=False) - self.vboxAdvanced.pack_start(self.hboxDNS,fill=False,expand=False) - self.vboxAdvanced.pack_start(self.txtDNS1,fill=False,expand=False) - self.vboxAdvanced.pack_start(self.txtDNS2,fill=False,expand=False) - self.vboxAdvanced.pack_start(self.txtDNS3,fill=False,expand=False) - self.vboxScripts.pack_start(self.txtBeforeScript,fill=False,expand=False) - self.vboxScripts.pack_start(self.txtAfterScript,fill=False,expand=False) - self.vboxTop.pack_end(self.expanderScripts,fill=False,expand=False) - self.vboxTop.pack_end(self.expanderAdvanced,fill=False,expand=False) - self.expanderAdvanced.add(self.vboxAdvanced) - self.expanderScripts.add(self.vboxScripts) - #connect the events to the actions - self.checkboxStaticIP.connect("toggled",self.toggleIPCheckbox) - self.checkboxStaticDNS.connect("toggled",self.toggleDNSCheckbox) - self.checkboxGlobalDNS.connect("toggled",self.toggleGlobalDNSCheckbox) - self.add(self.vboxTop) - #start with all disabled, then they will be enabled later - self.checkboxStaticIP.set_active(False) - self.checkboxStaticDNS.set_active(False) - - def setDefaults(self,widget=None,event=None): - #after the user types in the IP address, - #help them out a little - ipAddress = self.txtIP.get_text() #for easy typing :) - netmask = self.txtNetmask - gateway = self.txtGateway - ip_parts = misc.IsValidIP(ipAddress) - if ip_parts: - if stringToNone(gateway.get_text()) == None: #make sure the gateway box is blank - #fill it in with a .1 at the end - gateway.set_text('.'.join(ip_parts[0:3]) + '.1') + '''the basis for the entries in the network list''' + def __init__(self): + #make stuff exist, this is pretty long and boring + gtk.Expander.__init__(self) + self.txtIP = LabelEntry(language['ip']) + self.txtIP.entry.connect('focus-out-event',self.setDefaults) + self.txtNetmask = LabelEntry(language['netmask']) + self.txtGateway = LabelEntry(language['gateway']) + self.txtDNS1 = LabelEntry(language['dns'] + ' ' + language['1']) + self.txtDNS2 = LabelEntry(language['dns'] + ' ' + language['2']) + self.txtDNS3 = LabelEntry(language['dns'] + ' ' + language['3']) + #dns_addresses = daemon.GetGlobalDNSAddresses() + #self.txtDNS1.set_text(dns_addresses[0]) + #self.txtDNS2.set_text(dns_addresses[1]) + #self.txtDNS3.set_text(dns_addresses[2]) + self.txtBeforeScript = LabelEntry(language['before_script']) + self.txtAfterScript = LabelEntry(language['after_script']) + self.txtBeforeScript.label.set_size_request(200,-1) + self.txtAfterScript.label.set_size_request(200,-1) + self.checkboxStaticIP = gtk.CheckButton(language['use_static_ip']) + self.checkboxStaticDNS = gtk.CheckButton(language['use_static_dns']) + self.checkboxGlobalDNS = gtk.CheckButton(language['use_global_dns']) + self.expanderAdvanced = gtk.Expander(language['advanced_settings']) + self.expanderScripts = gtk.Expander(language['script_settings']) + self.vboxTop = gtk.VBox(False,0) + self.vboxAdvanced = gtk.VBox(False,0) + self.vboxScripts = gtk.VBox(False,0) + self.hboxDNS = gtk.HBox(False,0) + self.hboxDNS.pack_start(self.checkboxStaticDNS) + self.hboxDNS.pack_start(self.checkboxGlobalDNS) + self.vboxAdvanced.pack_start(self.checkboxStaticIP,fill=False,expand=False) + self.vboxAdvanced.pack_start(self.txtIP,fill=False,expand=False) + self.vboxAdvanced.pack_start(self.txtNetmask,fill=False,expand=False) + self.vboxAdvanced.pack_start(self.txtGateway,fill=False,expand=False) + self.vboxAdvanced.pack_start(self.hboxDNS,fill=False,expand=False) + self.vboxAdvanced.pack_start(self.txtDNS1,fill=False,expand=False) + self.vboxAdvanced.pack_start(self.txtDNS2,fill=False,expand=False) + self.vboxAdvanced.pack_start(self.txtDNS3,fill=False,expand=False) + self.vboxScripts.pack_start(self.txtBeforeScript,fill=False,expand=False) + self.vboxScripts.pack_start(self.txtAfterScript,fill=False,expand=False) + self.vboxTop.pack_end(self.expanderScripts,fill=False,expand=False) + self.vboxTop.pack_end(self.expanderAdvanced,fill=False,expand=False) + self.expanderAdvanced.add(self.vboxAdvanced) + self.expanderScripts.add(self.vboxScripts) + #connect the events to the actions + self.checkboxStaticIP.connect("toggled",self.toggleIPCheckbox) + self.checkboxStaticDNS.connect("toggled",self.toggleDNSCheckbox) + self.checkboxGlobalDNS.connect("toggled",self.toggleGlobalDNSCheckbox) + self.add(self.vboxTop) + #start with all disabled, then they will be enabled later + self.checkboxStaticIP.set_active(False) + self.checkboxStaticDNS.set_active(False) + print 'using global dns:',daemon.GetUseGlobalDNS() + #self.checkboxGlobalDNS.set_active(bool(int(daemon.GetUseGlobalDNS()))) + + def setDefaults(self,widget=None,event=None): + #after the user types in the IP address, + #help them out a little + ipAddress = self.txtIP.get_text() #for easy typing :) + netmask = self.txtNetmask + gateway = self.txtGateway + ip_parts = misc.IsValidIP(ipAddress) + if ip_parts: + if stringToNone(gateway.get_text()) == None: #make sure the gateway box is blank + #fill it in with a .1 at the end + gateway.set_text('.'.join(ip_parts[0:3]) + '.1') - if stringToNone(netmask.get_text()) == None: #make sure the netmask is blank - netmask.set_text('255.255.255.0') #fill in the most common one + if stringToNone(netmask.get_text()) == None: #make sure the netmask is blank + netmask.set_text('255.255.255.0') #fill in the most common one - def resetStaticCheckboxes(self): - #enable the right stuff - if not stringToNone(self.txtIP.get_text()) == None: - self.checkboxStaticIP.set_active(True) - self.checkboxStaticDNS.set_active(True) - self.checkboxStaticDNS.set_sensitive(False) - print 'enabling ip' - else: - self.checkboxStaticIP.set_active(False) - self.checkboxStaticDNS.set_active(False) - self.checkboxStaticDNS.set_sensitive(True) - print 'disabling ip' + def resetStaticCheckboxes(self): + #enable the right stuff + if not stringToNone(self.txtIP.get_text()) == None: + self.checkboxStaticIP.set_active(True) + self.checkboxStaticDNS.set_active(True) + self.checkboxStaticDNS.set_sensitive(False) + print 'enabling ip' + else: + self.checkboxStaticIP.set_active(False) + self.checkboxStaticDNS.set_active(False) + self.checkboxStaticDNS.set_sensitive(True) + print 'disabling ip' - if not stringToNone(self.txtDNS1.get_text()) == None: - self.checkboxStaticDNS.set_active(True) - print 'enabling dns' - else: - self.checkboxStaticDNS.set_active(False) - print 'disabling dns' + if not stringToNone(self.txtDNS1.get_text()) == None: + self.checkboxStaticDNS.set_active(True) + print 'enabling dns' + else: + self.checkboxStaticDNS.set_active(False) + print 'disabling dns' - #blankify stuff! - #this will properly disable - #unused boxes - self.toggleIPCheckbox() - self.toggleDNSCheckbox() + #blankify stuff! + #this will properly disable + #unused boxes + self.toggleIPCheckbox() + self.toggleDNSCheckbox() + self.toggleGlobalDNSCheckbox() - def toggleIPCheckbox(self,widget=None): - #should disable the static IP text boxes - #and also enable the DNS checkbox when - #disabled and disable when enabled + def toggleIPCheckbox(self,widget=None): + #should disable the static IP text boxes + #and also enable the DNS checkbox when + #disabled and disable when enabled - if self.checkboxStaticIP.get_active(): - self.checkboxStaticDNS.set_active(True) - self.checkboxStaticDNS.set_sensitive(False) - else: - self.checkboxStaticDNS.set_sensitive(True) + if self.checkboxStaticIP.get_active(): + self.checkboxStaticDNS.set_active(True) + self.checkboxStaticDNS.set_sensitive(False) + else: + self.checkboxStaticDNS.set_sensitive(True) - self.txtIP.set_sensitive(self.checkboxStaticIP.get_active()) - self.txtNetmask.set_sensitive(self.checkboxStaticIP.get_active()) - self.txtGateway.set_sensitive(self.checkboxStaticIP.get_active()) + self.txtIP.set_sensitive(self.checkboxStaticIP.get_active()) + self.txtNetmask.set_sensitive(self.checkboxStaticIP.get_active()) + self.txtGateway.set_sensitive(self.checkboxStaticIP.get_active()) - def toggleDNSCheckbox(self,widget=None): - #should disable the static DNS boxes - if self.checkboxStaticIP.get_active() == True: - self.checkboxStaticDNS.set_active(self.checkboxStaticIP.get_active()) - self.checkboxStaticDNS.set_sensitive(False) - - self.checkboxGlobalDNS.set_sensitive(self.checkboxStaticDNS.get_active()) - if self.checkboxStaticDNS.get_active(): - self.txtDNS1.set_sensitive(not self.checkboxGlobalDNS.get_active()) #if global dns is on, use local dns - self.txtDNS2.set_sensitive(not self.checkboxGlobalDNS.get_active()) - self.txtDNS3.set_sensitive(not self.checkboxGlobalDNS.get_active()) - else: - self.txtDNS1.set_sensitive(False) - self.txtDNS2.set_sensitive(False) - self.txtDNS3.set_sensitive(False) - - def toggleGlobalDNSCheckbox(self,widget=None): - self.txtDNS1.set_sensitive(not self.checkboxGlobalDNS.get_active()) - self.txtDNS2.set_sensitive(not self.checkboxGlobalDNS.get_active()) - self.txtDNS3.set_sensitive(not self.checkboxGlobalDNS.get_active()) + def toggleDNSCheckbox(self,widget=None): + print 'dns checkbox toggled',self.checkboxStaticDNS.get_active() + #should disable the static DNS boxes + if self.checkboxStaticIP.get_active() == True: + self.checkboxStaticDNS.set_active(self.checkboxStaticIP.get_active()) + self.checkboxStaticDNS.set_sensitive(False) + + self.checkboxGlobalDNS.set_sensitive(self.checkboxStaticDNS.get_active()) + if self.checkboxStaticDNS.get_active() == True: + self.txtDNS1.set_sensitive(not self.checkboxGlobalDNS.get_active()) #if global dns is on, use local dns + self.txtDNS2.set_sensitive(not self.checkboxGlobalDNS.get_active()) + self.txtDNS3.set_sensitive(not self.checkboxGlobalDNS.get_active()) + else: + self.txtDNS1.set_sensitive(False) + self.txtDNS2.set_sensitive(False) + self.txtDNS3.set_sensitive(False) + + def toggleGlobalDNSCheckbox(self,widget=None): + self.checkboxStaticDNS.set_active(True) + self.txtDNS1.set_sensitive(not self.checkboxGlobalDNS.get_active()) + self.txtDNS2.set_sensitive(not self.checkboxGlobalDNS.get_active()) + self.txtDNS3.set_sensitive(not self.checkboxGlobalDNS.get_active()) class WiredNetworkEntry(NetworkEntry): - #creates the wired network expander - def __init__(self): - NetworkEntry.__init__(self) - self.set_label(language['wired_network']) - self.resetStaticCheckboxes() - self.comboProfileNames = gtk.combo_box_entry_new_text() + #creates the wired network expander + def __init__(self): + NetworkEntry.__init__(self) + self.set_label(language['wired_network']) + self.resetStaticCheckboxes() + self.comboProfileNames = gtk.combo_box_entry_new_text() - profileList = config.GetWiredProfileList() - if profileList: #make sure there is something in it... - for x in config.GetWiredProfileList(): #add all the names to the combobox - self.comboProfileNames.append_text(x) - hboxTemp = gtk.HBox(False,0) - hboxDef = gtk.HBox(False,0) - buttonOK = gtk.Button(stock=gtk.STOCK_ADD) - self.buttonDelete = gtk.Button(stock=gtk.STOCK_DELETE) - self.profileHelp = gtk.Label(language['wired_network_instructions']) - self.checkboxDefaultProfile = gtk.CheckButton(language['default_wired']) + profileList = config.GetWiredProfileList() + if profileList: #make sure there is something in it... + for x in config.GetWiredProfileList(): #add all the names to the combobox + self.comboProfileNames.append_text(x) + hboxTemp = gtk.HBox(False,0) + hboxDef = gtk.HBox(False,0) + buttonOK = gtk.Button(stock=gtk.STOCK_ADD) + self.buttonDelete = gtk.Button(stock=gtk.STOCK_DELETE) + self.profileHelp = gtk.Label(language['wired_network_instructions']) + self.checkboxDefaultProfile = gtk.CheckButton(language['default_wired']) - self.profileHelp.set_width_chars(5) #the default is a tad too long - self.profileHelp.set_padding(10,10) - self.profileHelp.set_justify(gtk.JUSTIFY_LEFT) - self.profileHelp.set_line_wrap(True) + self.profileHelp.set_width_chars(5) #the default is a tad too long + self.profileHelp.set_padding(10,10) + self.profileHelp.set_justify(gtk.JUSTIFY_LEFT) + self.profileHelp.set_line_wrap(True) - self.vboxTop.pack_start(self.profileHelp,fill=False,expand=False) - hboxTemp.pack_start(self.comboProfileNames,fill=True,expand=True) - hboxTemp.pack_start(buttonOK,fill=False,expand=False) - hboxTemp.pack_start(self.buttonDelete,fill=False,expand=False) - hboxDef.pack_start(self.checkboxDefaultProfile,fill=False,expand=False) + self.vboxTop.pack_start(self.profileHelp,fill=False,expand=False) + hboxTemp.pack_start(self.comboProfileNames,fill=True,expand=True) + hboxTemp.pack_start(buttonOK,fill=False,expand=False) + hboxTemp.pack_start(self.buttonDelete,fill=False,expand=False) + hboxDef.pack_start(self.checkboxDefaultProfile,fill=False,expand=False) - buttonOK.connect("clicked",self.addProfile) #hook up our buttons - self.buttonDelete.connect("clicked",self.removeProfile) - self.comboProfileNames.connect("changed",self.changeProfile) - self.vboxTop.pack_start(hboxTemp) - self.vboxTop.pack_start(hboxDef) + buttonOK.connect("clicked",self.addProfile) #hook up our buttons + self.buttonDelete.connect("clicked",self.removeProfile) + self.comboProfileNames.connect("changed",self.changeProfile) + self.vboxTop.pack_start(hboxTemp) + self.vboxTop.pack_start(hboxDef) - if stringToBoolean(wired.GetWiredProperty("default")) == True: - self.checkboxDefaultProfile.set_active(True) - else: - self.checkboxDefaultProfile.set_active(False) - self.checkboxDefaultProfile.connect("toggled",self.toggleDefaultProfile) + if stringToBoolean(wired.GetWiredProperty("default")) == True: + self.checkboxDefaultProfile.set_active(True) + else: + self.checkboxDefaultProfile.set_active(False) + self.checkboxDefaultProfile.connect("toggled",self.toggleDefaultProfile) - self.show_all() - self.profileHelp.hide() - if profileList != None: - self.comboProfileNames.set_active(0) - print "wired profiles found" - self.set_expanded(False) - else: - print "no wired profiles found" - if not wired.GetAlwaysShowWiredInterface(): - self.set_expanded(True) - self.profileHelp.show() + self.show_all() + self.profileHelp.hide() + if profileList != None: + self.comboProfileNames.set_active(0) + print "wired profiles found" + self.set_expanded(False) + else: + print "no wired profiles found" + if not wired.GetAlwaysShowWiredInterface(): + self.set_expanded(True) + self.profileHelp.show() - def checkEnable(self): - profileList = config.GetWiredProfileList() - if profileList == None: - self.buttonDelete.set_sensitive(False) - self.higherLevel.connectButton.set_sensitive(False) - self.vboxAdvanced.set_sensitive(False) + def checkEnable(self): + profileList = config.GetWiredProfileList() + if profileList == None: + self.buttonDelete.set_sensitive(False) + self.higherLevel.connectButton.set_sensitive(False) + self.vboxAdvanced.set_sensitive(False) - def addProfile(self,widget): - print "adding profile" - profileName = self.comboProfileNames.get_active_text() - profileList = config.GetWiredProfileList() - if profileList: - if profileName in profileList: - return False - if profileName != "": - self.profileHelp.hide() - config.CreateWiredNetworkProfile(profileName) - self.comboProfileNames.prepend_text(profileName) - self.comboProfileNames.set_active(0) - self.buttonDelete.set_sensitive(True) - self.vboxAdvanced.set_sensitive(True) - self.higherLevel.connectButton.set_sensitive(True) + def addProfile(self,widget): + print "adding profile" + profileName = self.comboProfileNames.get_active_text() + profileList = config.GetWiredProfileList() + if profileList: + if profileName in profileList: + return False + if profileName != "": + self.profileHelp.hide() + config.CreateWiredNetworkProfile(profileName) + self.comboProfileNames.prepend_text(profileName) + self.comboProfileNames.set_active(0) + self.buttonDelete.set_sensitive(True) + self.vboxAdvanced.set_sensitive(True) + self.higherLevel.connectButton.set_sensitive(True) - def removeProfile(self,widget): - print "removing profile" - config.DeleteWiredNetworkProfile(self.comboProfileNames.get_active_text()) - self.comboProfileNames.remove_text(self.comboProfileNames.get_active()) - self.comboProfileNames.set_active(0) - if config.GetWiredProfileList() == None: - self.profileHelp.show() - entry = self.comboProfileNames.child - entry.set_text("") - self.buttonDelete.set_sensitive(False) - self.vboxAdvanced.set_sensitive(False) - self.higherLevel.connectButton.set_sensitive(False) - else: - self.profileHelp.hide() - - def toggleDefaultProfile(self,widget): - if self.checkboxDefaultProfile.get_active() == True: - print 'unsetting previous default profile...' - config.UnsetWiredDefault() # Makes sure there is only one default profile at a time - wired.SetWiredProperty("default",self.checkboxDefaultProfile.get_active()) - config.SaveWiredNetworkProfile(self.comboProfileNames.get_active_text()) + def removeProfile(self,widget): + print "removing profile" + config.DeleteWiredNetworkProfile(self.comboProfileNames.get_active_text()) + self.comboProfileNames.remove_text(self.comboProfileNames.get_active()) + self.comboProfileNames.set_active(0) + if config.GetWiredProfileList() == None: + self.profileHelp.show() + entry = self.comboProfileNames.child + entry.set_text("") + self.buttonDelete.set_sensitive(False) + self.vboxAdvanced.set_sensitive(False) + self.higherLevel.connectButton.set_sensitive(False) + else: + self.profileHelp.hide() + + def toggleDefaultProfile(self,widget): + if self.checkboxDefaultProfile.get_active() == True: + print 'unsetting previous default profile...' + config.UnsetWiredDefault() # Makes sure there is only one default profile at a time + wired.SetWiredProperty("default",self.checkboxDefaultProfile.get_active()) + config.SaveWiredNetworkProfile(self.comboProfileNames.get_active_text()) - def changeProfile(self,widget): - if self.comboProfileNames.get_active() > -1: #this way the name doesn't change - # #everytime someone types something in - print "changing profile..." - profileName = self.comboProfileNames.get_active_text() - print profileName - config.ReadWiredNetworkProfile(profileName) - - self.txtIP.set_text(noneToBlankString(wired.GetWiredProperty("ip"))) - self.txtNetmask.set_text(noneToBlankString(wired.GetWiredProperty("netmask"))) - self.txtGateway.set_text(noneToBlankString(wired.GetWiredProperty("gateway"))) + def changeProfile(self,widget): + if self.comboProfileNames.get_active() > -1: #this way the name doesn't change + # #everytime someone types something in + print "changing profile..." + profileName = self.comboProfileNames.get_active_text() + print profileName + config.ReadWiredNetworkProfile(profileName) + + self.txtIP.set_text(noneToBlankString(wired.GetWiredProperty("ip"))) + self.txtNetmask.set_text(noneToBlankString(wired.GetWiredProperty("netmask"))) + self.txtGateway.set_text(noneToBlankString(wired.GetWiredProperty("gateway"))) - self.txtDNS1.set_text(noneToBlankString(wired.GetWiredProperty("dns1"))) - self.txtDNS2.set_text(noneToBlankString(wired.GetWiredProperty("dns2"))) - self.txtDNS3.set_text(noneToBlankString(wired.GetWiredProperty("dns3"))) - - self.txtBeforeScript.set_text(noneToBlankString(wired.GetWiredProperty("beforescript"))) - self.txtAfterScript.set_text(noneToBlankString(wired.GetWiredProperty("afterscript"))) - - self.checkboxDefaultProfile.set_active(stringToBoolean(wired.GetWiredProperty("default"))) + self.txtDNS1.set_text(noneToBlankString(wired.GetWiredProperty("dns1"))) + self.txtDNS2.set_text(noneToBlankString(wired.GetWiredProperty("dns2"))) + self.txtDNS3.set_text(noneToBlankString(wired.GetWiredProperty("dns3"))) + + self.txtBeforeScript.set_text(noneToBlankString(wired.GetWiredProperty("beforescript"))) + self.txtAfterScript.set_text(noneToBlankString(wired.GetWiredProperty("afterscript"))) + + self.checkboxDefaultProfile.set_active(stringToBoolean(wired.GetWiredProperty("default"))) - self.resetStaticCheckboxes() + self.resetStaticCheckboxes() class WirelessNetworkEntry(NetworkEntry): - #this class is respsponsible for creating the expander - #in each wirelessnetwork entry - def __init__(self,networkID): - self.networkID = networkID - #create the data labels - NetworkEntry.__init__(self) - print "ESSID : " + wireless.GetWirelessProperty(networkID,"essid") - self.set_label(wireless.GetWirelessProperty(networkID,"essid")) - self.essid = wireless.GetWirelessProperty(networkID,"essid") - print "making a new network entry..." + #this class is respsponsible for creating the expander + #in each wirelessnetwork entry + def __init__(self,networkID): + self.networkID = networkID + #create the data labels + NetworkEntry.__init__(self) + print "ESSID : " + wireless.GetWirelessProperty(networkID,"essid") + self.set_label(wireless.GetWirelessProperty(networkID,"essid")) + self.essid = wireless.GetWirelessProperty(networkID,"essid") + print "making a new network entry..." - #make the vbox to hold the encryption stuff - self.vboxEncryptionInformation = gtk.VBox(False,0) - #make the combo box - self.comboEncryption = gtk.combo_box_new_text() - self.checkboxEncryption = gtk.CheckButton(language['use_encryption']) - self.lblStrength = GreyLabel() - self.lblEncryption = GreyLabel() - self.lblMAC = GreyLabel() - self.lblChannel = GreyLabel() - self.lblMode = GreyLabel() - self.hboxStatus = gtk.HBox(False,5) - self.checkboxAutoConnect = gtk.CheckButton(language['automatic_connect']) - self.checkboxAutoConnect.connect("toggled",self.updateAutoConnect) #so that the autoconnect box is - #toggled + #make the vbox to hold the encryption stuff + self.vboxEncryptionInformation = gtk.VBox(False,0) + #make the combo box + self.comboEncryption = gtk.combo_box_new_text() + self.checkboxEncryption = gtk.CheckButton(language['use_encryption']) + self.lblStrength = GreyLabel() + self.lblEncryption = GreyLabel() + self.lblMAC = GreyLabel() + self.lblChannel = GreyLabel() + self.lblMode = GreyLabel() + self.hboxStatus = gtk.HBox(False,5) + self.checkboxAutoConnect = gtk.CheckButton(language['automatic_connect']) + self.checkboxAutoConnect.connect("toggled",self.updateAutoConnect) #so that the autoconnect box is + #toggled - self.hboxStatus.pack_start(self.lblStrength,fill=False,expand=True) - self.hboxStatus.pack_start(self.lblEncryption,fill=False,expand=True) - self.hboxStatus.pack_start(self.lblMAC,fill=False,expand=True) - self.hboxStatus.pack_start(self.lblMode,fill=False,expand=True) - self.hboxStatus.pack_start(self.lblChannel,fill=False,expand=True) + self.hboxStatus.pack_start(self.lblStrength,fill=False,expand=True) + self.hboxStatus.pack_start(self.lblEncryption,fill=False,expand=True) + self.hboxStatus.pack_start(self.lblMAC,fill=False,expand=True) + self.hboxStatus.pack_start(self.lblMode,fill=False,expand=True) + self.hboxStatus.pack_start(self.lblChannel,fill=False,expand=True) - self.vboxTop.pack_start(self.checkboxAutoConnect,fill=False,expand=False) - self.vboxTop.pack_start(self.hboxStatus,fill=True,expand=False) + self.vboxTop.pack_start(self.checkboxAutoConnect,fill=False,expand=False) + self.vboxTop.pack_start(self.hboxStatus,fill=True,expand=False) - self.vboxAdvanced.pack_start(self.checkboxEncryption,fill=False,expand=False) + self.vboxAdvanced.pack_start(self.checkboxEncryption,fill=False,expand=False) - self.txtIP.set_text(noneToBlankString(wireless.GetWirelessProperty(networkID,"ip"))) - self.txtNetmask.set_text(noneToBlankString(wireless.GetWirelessProperty(networkID,"netmask"))) - self.txtGateway.set_text(noneToBlankString(wireless.GetWirelessProperty(networkID,"gateway"))) + self.txtIP.set_text(noneToBlankString(wireless.GetWirelessProperty(networkID,"ip"))) + self.txtNetmask.set_text(noneToBlankString(wireless.GetWirelessProperty(networkID,"netmask"))) + self.txtGateway.set_text(noneToBlankString(wireless.GetWirelessProperty(networkID,"gateway"))) - if wireless.GetWirelessProperty(networkID,"dns1") != None: - self.txtDNS1.set_text(noneToBlankString(wireless.GetWirelessProperty(networkID,"dns1"))) + if wireless.GetWirelessProperty(networkID,'use_global_dns'): + self.checkboxGlobalDNS.set_active(True) - if wireless.GetWirelessProperty(networkID,'dns2') != None: - self.txtDNS2.set_text(noneToBlankString(wireless.GetWirelessProperty(networkID,"dns2"))) + if wireless.GetWirelessProperty(networkID,"dns1") != None: + self.txtDNS1.set_text(noneToBlankString(wireless.GetWirelessProperty(networkID,"dns1"))) - if wireless.GetWirelessProperty(networkID,'dns3') != None: - self.txtDNS3.set_text(noneToBlankString(wireless.GetWirelessProperty(networkID,"dns3"))) + if wireless.GetWirelessProperty(networkID,'dns2') != None: + self.txtDNS2.set_text(noneToBlankString(wireless.GetWirelessProperty(networkID,"dns2"))) - self.txtBeforeScript.set_text(noneToBlankString(wireless.GetWirelessProperty(networkID,"beforescript"))) - self.txtAfterScript.set_text(noneToBlankString(wireless.GetWirelessProperty(networkID,"afterscript"))) + if wireless.GetWirelessProperty(networkID,'dns3') != None: + self.txtDNS3.set_text(noneToBlankString(wireless.GetWirelessProperty(networkID,"dns3"))) - self.resetStaticCheckboxes() - encryptionTypes = misc.LoadEncryptionMethods() + self.txtBeforeScript.set_text(noneToBlankString(wireless.GetWirelessProperty(networkID,"beforescript"))) + self.txtAfterScript.set_text(noneToBlankString(wireless.GetWirelessProperty(networkID,"afterscript"))) - self.checkboxEncryption.set_active(False) - self.comboEncryption.set_sensitive(False) + self.resetStaticCheckboxes() + encryptionTypes = misc.LoadEncryptionMethods() - if stringToBoolean(wireless.GetWirelessProperty(networkID,"automatic")) == True: - self.checkboxAutoConnect.set_active(True) - else: - self.checkboxAutoConnect.set_active(False) - #set it up right, with disabled stuff - self.toggleEncryption() + self.checkboxEncryption.set_active(False) + self.comboEncryption.set_sensitive(False) - #add the names to the menu - activeID = -1 #set the menu to this item when we are done - for x in encryptionTypes: - self.comboEncryption.append_text(encryptionTypes[x][0]) - if encryptionTypes[x][1] == wireless.GetWirelessProperty(networkID,"enctype"): - activeID = x + if stringToBoolean(wireless.GetWirelessProperty(networkID,"automatic")) == True: + self.checkboxAutoConnect.set_active(True) + else: + self.checkboxAutoConnect.set_active(False) + #set it up right, with disabled stuff + self.toggleEncryption() - self.comboEncryption.set_active(activeID) - if activeID != -1: - self.checkboxEncryption.set_active(True) - self.comboEncryption.set_sensitive(True) - self.vboxEncryptionInformation.set_sensitive(True) - else: - self.comboEncryption.set_active(0) + #add the names to the menu + activeID = -1 #set the menu to this item when we are done + for x in encryptionTypes: + self.comboEncryption.append_text(encryptionTypes[x][0]) + if encryptionTypes[x][1] == wireless.GetWirelessProperty(networkID,"enctype"): + activeID = x - self.vboxAdvanced.pack_start(self.comboEncryption) - self.vboxAdvanced.pack_start(self.vboxEncryptionInformation) - self.changeEncryptionMethod() - self.checkboxEncryption.connect("toggled",self.toggleEncryption) - self.comboEncryption.connect("changed",self.changeEncryptionMethod) - self.show_all() + self.comboEncryption.set_active(activeID) + if activeID != -1: + self.checkboxEncryption.set_active(True) + self.comboEncryption.set_sensitive(True) + self.vboxEncryptionInformation.set_sensitive(True) + else: + self.comboEncryption.set_active(0) - def updateAutoConnect(self,widget): - wireless.SetWirelessProperty(self.networkID,"automatic",self.checkboxAutoConnect.get_active()) - config.SaveWirelessNetworkProperty(self.networkID,"automatic") + self.vboxAdvanced.pack_start(self.comboEncryption) + self.vboxAdvanced.pack_start(self.vboxEncryptionInformation) + self.changeEncryptionMethod() + self.checkboxEncryption.connect("toggled",self.toggleEncryption) + self.comboEncryption.connect("changed",self.changeEncryptionMethod) + self.show_all() - def toggleEncryption(self,widget=None): - active = self.checkboxEncryption.get_active() - self.vboxEncryptionInformation.set_sensitive(active) - self.comboEncryption.set_sensitive(active) + def updateAutoConnect(self,widget): + wireless.SetWirelessProperty(self.networkID,"automatic",self.checkboxAutoConnect.get_active()) + config.SaveWirelessNetworkProperty(self.networkID,"automatic") - def changeEncryptionMethod(self,widget=None): - for z in self.vboxEncryptionInformation: - z.destroy() #remove stuff in there already - ID = self.comboEncryption.get_active() - methods = misc.LoadEncryptionMethods() - self.encryptionInfo = {} - if ID == -1: - #in case nothing is selected - self.comboEncryption.set_active(0) - ID == 0 - for x in methods[ID][2]: - print x - box = None - if language.has_key(methods[ID][2][x][0]): - box = LabelEntry(language[methods[ID][2][x][0].lower().replace(' ','_')]) - else: - box = LabelEntry(methods[ID][2][x][0].replace('_',' ')) - box.set_auto_hidden(True) - self.vboxEncryptionInformation.pack_start(box) - #add the data to any array, so that the information - #can be easily accessed by giving the name of the wanted - #data - self.encryptionInfo[methods[ID][2][x][1]] = box.entry + def toggleEncryption(self,widget=None): + active = self.checkboxEncryption.get_active() + self.vboxEncryptionInformation.set_sensitive(active) + self.comboEncryption.set_sensitive(active) - box.entry.set_text(noneToBlankString(wireless.GetWirelessProperty(self.networkID,methods[ID][2][x][1]))) - self.vboxEncryptionInformation.show_all() + def changeEncryptionMethod(self,widget=None): + for z in self.vboxEncryptionInformation: + z.destroy() #remove stuff in there already + ID = self.comboEncryption.get_active() + methods = misc.LoadEncryptionMethods() + self.encryptionInfo = {} + if ID == -1: + #in case nothing is selected + self.comboEncryption.set_active(0) + ID == 0 + for x in methods[ID][2]: + print x + box = None + if language.has_key(methods[ID][2][x][0]): + box = LabelEntry(language[methods[ID][2][x][0].lower().replace(' ','_')]) + else: + box = LabelEntry(methods[ID][2][x][0].replace('_',' ')) + box.set_auto_hidden(True) + self.vboxEncryptionInformation.pack_start(box) + #add the data to any array, so that the information + #can be easily accessed by giving the name of the wanted + #data + self.encryptionInfo[methods[ID][2][x][1]] = box.entry - def setSignalStrength(self,strength): - self.lblStrength.set_label(str(strength) + "%") - - def setMACAddress(self,address): - self.lblMAC.set_label(str(address)) + box.entry.set_text(noneToBlankString(wireless.GetWirelessProperty(self.networkID,methods[ID][2][x][1]))) + self.vboxEncryptionInformation.show_all() - def setEncryption(self,on,type): - if on and type: - self.lblEncryption.set_label(language['secured'] + " " + str(type)) - self.set_use_markup(True) - self.set_label(self.essid + ' ' + str(type) + '') - if on and not type: - self.lblEncryption.set_label(language['secured']) - self.set_label(self.essid + ' Secured') - if not on: - self.lblEncryption.set_label(language['unsecured']) + def setSignalStrength(self,strength): + self.lblStrength.set_label(str(strength) + "%") + + def setMACAddress(self,address): + self.lblMAC.set_label(str(address)) - def setChannel(self,channel): - self.lblChannel.set_label(language['channel'] + ' ' + str(channel)) - - def setMode(self,mode): - self.lblMode.set_label(str(mode)) + def setEncryption(self,on,type): + if on and type: + self.lblEncryption.set_label(language['secured'] + " " + str(type)) + self.set_use_markup(True) + self.set_label(self.essid + ' ' + str(type) + '') + if on and not type: + self.lblEncryption.set_label(language['secured']) + self.set_label(self.essid + ' Secured') + if not on: + self.lblEncryption.set_label(language['unsecured']) + + def setChannel(self,channel): + self.lblChannel.set_label(language['channel'] + ' ' + str(channel)) + + def setMode(self,mode): + self.lblMode.set_label(str(mode)) class appGui: - def __init__(self): - print "starting..." - gladefile = "data/wicd.glade" - self.windowname = "gtkbench" - self.wTree = gtk.glade.XML(gladefile) + def __init__(self): + print "starting..." + gladefile = "data/wicd.glade" + self.windowname = "gtkbench" + self.wTree = gtk.glade.XML(gladefile) - dic = { "refresh_clicked" : self.refresh_networks, "quit_clicked" : self.exit, 'disconnect_clicked' : self.disconnect_wireless, "main_exit" : self.exit, "cancel_clicked" : self.cancel_connect, "connect_clicked" : self.connect_hidden, "preferences_clicked" : self.settings_dialog, "about_clicked" : self.about_dialog, 'create_adhoc_network_button_button' : self.create_adhoc_network} - self.wTree.signal_autoconnect(dic) + dic = { "refresh_clicked" : self.refresh_networks, "quit_clicked" : self.exit, 'disconnect_clicked' : self.disconnect_wireless, "main_exit" : self.exit, "cancel_clicked" : self.cancel_connect, "connect_clicked" : self.connect_hidden, "preferences_clicked" : self.settings_dialog, "about_clicked" : self.about_dialog, 'create_adhoc_network_button_button' : self.create_adhoc_network} + self.wTree.signal_autoconnect(dic) - #set some strings in the GUI - they may be translated + #set some strings in the GUI - they may be translated - self.wTree.get_widget("label_instructions").set_label(language['select_a_network']) - #I don't know how to translate a menu entry - #more specifically, I don't know how to set a menu entry's text - #self.wTree.get_widget("connect_button").modify_text(language['hidden_network']) - self.wTree.get_widget("progressbar").set_text(language['connecting']) + self.wTree.get_widget("label_instructions").set_label(language['select_a_network']) + #I don't know how to translate a menu entry + #more specifically, I don't know how to set a menu entry's text + #self.wTree.get_widget("connect_button").modify_text(language['hidden_network']) + self.wTree.get_widget("progressbar").set_text(language['connecting']) - self.network_list = self.wTree.get_widget("network_list_vbox") - self.status_area = self.wTree.get_widget("connecting_hbox") - self.status_bar = self.wTree.get_widget("statusbar") - self.refresh_networks(fresh=False) + self.network_list = self.wTree.get_widget("network_list_vbox") + self.status_area = self.wTree.get_widget("connecting_hbox") + self.status_bar = self.wTree.get_widget("statusbar") + self.refresh_networks(fresh=False) - self.statusID = None + self.statusID = None - gobject.timeout_add(300,self.update_statusbar) - gobject.timeout_add(100,self.pulse_progress_bar) + gobject.timeout_add(300,self.update_statusbar) + gobject.timeout_add(100,self.pulse_progress_bar) - def create_adhoc_network(self,widget=None): - '''shows a dialog that creates a new adhoc network''' - #create a new adhoc network here. - print 'create adhoc network' - dialog = gtk.Dialog(title=language['create_adhoc_network'], flags = gtk.DIALOG_MODAL, buttons=(gtk.STOCK_OK,1,gtk.STOCK_CANCEL,2)) - dialog.set_has_separator(False) - dialog.set_size_request(400,-1) - self.useEncryptionCheckbox = gtk.CheckButton(language['use_wep_encryption']) - self.useEncryptionCheckbox.set_active(False) - ipEntry = LabelEntry(language['ip'] + ':') - essidEntry = LabelEntry(language['essid'] + ':') - channelEntry = LabelEntry(language['channel'] + ':') - self.keyEntry = LabelEntry(language['key'] + ':') - self.keyEntry.set_auto_hidden(True) - self.keyEntry.set_sensitive(False) - - useICSCheckbox = gtk.CheckButton(language['use_ics']) + def create_adhoc_network(self,widget=None): + '''shows a dialog that creates a new adhoc network''' + #create a new adhoc network here. + print 'create adhoc network' + dialog = gtk.Dialog(title=language['create_adhoc_network'], flags = gtk.DIALOG_MODAL, buttons=(gtk.STOCK_OK,1,gtk.STOCK_CANCEL,2)) + dialog.set_has_separator(False) + dialog.set_size_request(400,-1) + self.useEncryptionCheckbox = gtk.CheckButton(language['use_wep_encryption']) + self.useEncryptionCheckbox.set_active(False) + ipEntry = LabelEntry(language['ip'] + ':') + essidEntry = LabelEntry(language['essid'] + ':') + channelEntry = LabelEntry(language['channel'] + ':') + self.keyEntry = LabelEntry(language['key'] + ':') + self.keyEntry.set_auto_hidden(True) + self.keyEntry.set_sensitive(False) + + useICSCheckbox = gtk.CheckButton(language['use_ics']) - self.useEncryptionCheckbox.connect("toggled",self.toggleEncryptionCheck) - channelEntry.entry.set_text('3') - essidEntry.entry.set_text('My_Adhoc_Network') - ipEntry.entry.set_text('169.254.12.10') #Just a random IP + self.useEncryptionCheckbox.connect("toggled",self.toggleEncryptionCheck) + channelEntry.entry.set_text('3') + essidEntry.entry.set_text('My_Adhoc_Network') + ipEntry.entry.set_text('169.254.12.10') #Just a random IP - vboxA = gtk.VBox(False,0) - vboxA.pack_start(self.useEncryptionCheckbox,fill=False,expand=False) - vboxA.pack_start(self.keyEntry,fill=False,expand=False) - vboxA.show() - dialog.vbox.pack_start(essidEntry) - dialog.vbox.pack_start(ipEntry) - dialog.vbox.pack_start(channelEntry) - dialog.vbox.pack_start(useICSCheckbox) - dialog.vbox.pack_start(vboxA) - dialog.vbox.set_spacing(5) - dialog.show_all() - response = dialog.run() - if response == 1: - wireless.CreateAdHocNetwork(essidEntry.entry.get_text(),channelEntry.entry.get_text(),ipEntry.entry.get_text(),"WEP",self.keyEntry.entry.get_text(),self.useEncryptionCheckbox.get_active(),False) #useICSCheckbox.get_active()) - dialog.destroy() + vboxA = gtk.VBox(False,0) + vboxA.pack_start(self.useEncryptionCheckbox,fill=False,expand=False) + vboxA.pack_start(self.keyEntry,fill=False,expand=False) + vboxA.show() + dialog.vbox.pack_start(essidEntry) + dialog.vbox.pack_start(ipEntry) + dialog.vbox.pack_start(channelEntry) + dialog.vbox.pack_start(useICSCheckbox) + dialog.vbox.pack_start(vboxA) + dialog.vbox.set_spacing(5) + dialog.show_all() + response = dialog.run() + if response == 1: + wireless.CreateAdHocNetwork(essidEntry.entry.get_text(),channelEntry.entry.get_text(),ipEntry.entry.get_text(),"WEP",self.keyEntry.entry.get_text(),self.useEncryptionCheckbox.get_active(),False) #useICSCheckbox.get_active()) + dialog.destroy() - def toggleEncryptionCheck(self,widget=None): - self.keyEntry.set_sensitive(self.useEncryptionCheckbox.get_active()) + def toggleEncryptionCheck(self,widget=None): + self.keyEntry.set_sensitive(self.useEncryptionCheckbox.get_active()) - def disconnect_wireless(self,widget=None): - wireless.DisconnectWireless() + def disconnect_wireless(self,widget=None): + wireless.DisconnectWireless() - def about_dialog(self,widget,event=None): - dialog = gtk.AboutDialog() - dialog.set_name("Wicd") - dialog.set_version(daemon.Hello()) - dialog.set_authors([ "Adam Blackburn" ]) - dialog.set_website("http://wicd.sourceforge.net") - dialog.run() - dialog.destroy() - - def settings_dialog(self,widget,event=None): - dialog = gtk.Dialog(title=language['preferences'], flags=gtk.DIALOG_MODAL, buttons=(gtk.STOCK_OK,1,gtk.STOCK_CANCEL,2)) - dialog.set_has_separator(False) - dialog.set_size_request(375,-1) - wiredcheckbox = gtk.CheckButton(language['wired_always_on']) - wiredcheckbox.set_active(wired.GetAlwaysShowWiredInterface()) - reconnectcheckbox = gtk.CheckButton(language['auto_reconnect']) - reconnectcheckbox.set_active(wireless.GetAutoReconnect()) - debugmodecheckbox = gtk.CheckButton(language['use_debug_mode']) - debugmodecheckbox.set_active(daemon.GetDebugMode()) - wpadriverlabel = SmallLabel(language['wpa_supplicant_driver'] + ':') - wpadrivercombo = gtk.combo_box_new_text() - wpadrivercombo.set_size_request(50,-1) - wpadrivers = [ "hostap","hermes","madwifi","atmel","wext","ndiswrapper","broadcom","ipw","ralink legacy" ] - i = 0 - found = False - for x in wpadrivers: - if x == daemon.GetWPADriver() and found == False: - found = True - else: - if found == False: - i+=1 - wpadrivercombo.append_text(x) - #set active here. - #if we set active an item to active, then add more items - #it loses the activeness - wpadrivercombo.set_active(i) - #select wext as the default driver, because - #it works for most cards - wpabox = gtk.HBox(False,1) - wpabox.pack_start(wpadriverlabel) - wpabox.pack_start(wpadrivercombo) + def about_dialog(self,widget,event=None): + dialog = gtk.AboutDialog() + dialog.set_name("Wicd") + dialog.set_version(daemon.Hello()) + dialog.set_authors([ "Adam Blackburn" ]) + dialog.set_website("http://wicd.sourceforge.net") + dialog.run() + dialog.destroy() + + def settings_dialog(self,widget,event=None): + dialog = gtk.Dialog(title=language['preferences'], flags=gtk.DIALOG_MODAL, buttons=(gtk.STOCK_OK,1,gtk.STOCK_CANCEL,2)) + dialog.set_has_separator(False) + dialog.set_size_request(375,-1) + wiredcheckbox = gtk.CheckButton(language['wired_always_on']) + wiredcheckbox.set_active(wired.GetAlwaysShowWiredInterface()) + reconnectcheckbox = gtk.CheckButton(language['auto_reconnect']) + reconnectcheckbox.set_active(wireless.GetAutoReconnect()) + debugmodecheckbox = gtk.CheckButton(language['use_debug_mode']) + debugmodecheckbox.set_active(daemon.GetDebugMode()) + wpadriverlabel = SmallLabel(language['wpa_supplicant_driver'] + ':') + wpadrivercombo = gtk.combo_box_new_text() + wpadrivercombo.set_size_request(50,-1) + wpadrivers = [ "hostap","hermes","madwifi","atmel","wext","ndiswrapper","broadcom","ipw","ralink legacy" ] + i = 0 + found = False + for x in wpadrivers: + if x == daemon.GetWPADriver() and found == False: + found = True + else: + if found == False: + i+=1 + wpadrivercombo.append_text(x) + #set active here. + #if we set active an item to active, then add more items + #it loses the activeness + wpadrivercombo.set_active(i) + #select wext as the default driver, because + #it works for most cards + wpabox = gtk.HBox(False,1) + wpabox.pack_start(wpadriverlabel) + wpabox.pack_start(wpadrivercombo) - entryWirelessInterface = LabelEntry(language['wireless_interface'] + ':') - entryWiredInterface = LabelEntry(language['wired_interface'] + ':') + entryWirelessInterface = LabelEntry(language['wireless_interface'] + ':') + entryWiredInterface = LabelEntry(language['wired_interface'] + ':') - entryWirelessInterface.entry.set_text(daemon.GetWirelessInterface()) - entryWiredInterface.entry.set_text(daemon.GetWiredInterface()) + entryWirelessInterface.entry.set_text(daemon.GetWirelessInterface()) + entryWiredInterface.entry.set_text(daemon.GetWiredInterface()) - useGlobalDNSCheckbox = gtk.CheckButton(language['use_global_dns']) - dns1Entry = LabelEntry(language['dns'] + ' ' + language['1']) - dns2Entry = LabelEntry(language['dns'] + ' ' + language['2']) - dns3Entry = LabelEntry(language['dns'] + ' ' + language['3']) - - useGlobalDNSCheckbox.connect("toggled",checkboxTextboxToggle,(dns1Entry, dns2Entry, dns3Entry)) + useGlobalDNSCheckbox = gtk.CheckButton(language['use_global_dns']) + dns1Entry = LabelEntry(language['dns'] + ' ' + language['1']) + dns2Entry = LabelEntry(language['dns'] + ' ' + language['2']) + dns3Entry = LabelEntry(language['dns'] + ' ' + language['3']) + + useGlobalDNSCheckbox.connect("toggled",checkboxTextboxToggle,(dns1Entry, dns2Entry, dns3Entry)) - dns_addresses = daemon.GetGlobalDNSAddresses() + dns_addresses = daemon.GetGlobalDNSAddresses() - useGlobalDNSCheckbox.set_active(daemon.GetUseGlobalDNS()) - dns1Entry.set_text(dns_addresses[0]) - dns2Entry.set_text(dns_addresses[1]) - dns3Entry.set_text(dns_addresses[2]) + useGlobalDNSCheckbox.set_active(daemon.GetUseGlobalDNS()) + dns1Entry.set_text(noneToBlankString(dns_addresses[0])) + dns2Entry.set_text(noneToBlankString(dns_addresses[1])) + dns3Entry.set_text(noneToBlankString(dns_addresses[2])) - dialog.vbox.pack_start(wpabox) - dialog.vbox.pack_start(entryWirelessInterface) - dialog.vbox.pack_start(entryWiredInterface) + dialog.vbox.pack_start(wpabox) + dialog.vbox.pack_start(entryWirelessInterface) + dialog.vbox.pack_start(entryWiredInterface) - dialog.vbox.pack_start(useGlobalDNSCheckbox) - dialog.vbox.pack_start(dns1Entry) - dialog.vbox.pack_start(dns2Entry) - dialog.vbox.pack_start(dns3Entry) + dialog.vbox.pack_start(useGlobalDNSCheckbox) + dialog.vbox.pack_start(dns1Entry) + dialog.vbox.pack_start(dns2Entry) + dialog.vbox.pack_start(dns3Entry) - dialog.vbox.pack_start(wiredcheckbox) - dialog.vbox.pack_start(reconnectcheckbox) - dialog.vbox.pack_start(debugmodecheckbox) - dialog.vbox.set_spacing(5) - dialog.show_all() - response = dialog.run() - if response == 1: - daemon.SetUseGlobalDNS(useGlobalDNSCheckbox.get_active()) - daemon.SetGlobalDNS(dns1Entry.get_text(),dns2Entry.get_text(),dns3Entry.get_text()) - daemon.SetWirelessInterface(entryWirelessInterface.entry.get_text()) - daemon.SetWiredInterface(entryWiredInterface.entry.get_text()) - print "setting: " + wpadrivers[wpadrivercombo.get_active()] - daemon.SetWPADriver(wpadrivers[wpadrivercombo.get_active()]) - wired.SetAlwaysShowWiredInterface(wiredcheckbox.get_active()) - wireless.SetAutoReconnect(reconnectcheckbox.get_active()) - daemon.SetDebugMode(debugmodecheckbox.get_active()) - dialog.destroy() - else: - dialog.destroy() + dialog.vbox.pack_start(wiredcheckbox) + dialog.vbox.pack_start(reconnectcheckbox) + dialog.vbox.pack_start(debugmodecheckbox) + dialog.vbox.set_spacing(5) + dialog.show_all() + response = dialog.run() + if response == 1: + daemon.SetUseGlobalDNS(useGlobalDNSCheckbox.get_active()) + daemon.SetGlobalDNS(dns1Entry.get_text(),dns2Entry.get_text(),dns3Entry.get_text()) + daemon.SetWirelessInterface(entryWirelessInterface.entry.get_text()) + daemon.SetWiredInterface(entryWiredInterface.entry.get_text()) + print "setting: " + wpadrivers[wpadrivercombo.get_active()] + daemon.SetWPADriver(wpadrivers[wpadrivercombo.get_active()]) + wired.SetAlwaysShowWiredInterface(wiredcheckbox.get_active()) + wireless.SetAutoReconnect(reconnectcheckbox.get_active()) + daemon.SetDebugMode(debugmodecheckbox.get_active()) + dialog.destroy() + else: + dialog.destroy() - def connect_hidden(self,widget): - #should display a dialog asking - #for the ssid of a hidden network - #and displaying connect/cancel buttons - dialog = gtk.Dialog(title=language['hidden_network'], flags=gtk.DIALOG_MODAL, buttons=(gtk.STOCK_CONNECT,1,gtk.STOCK_CANCEL,2)) - dialog.set_has_separator(False) - dialog.lbl = gtk.Label(language['hidden_network_essid']) - dialog.textbox = gtk.Entry() - dialog.vbox.pack_start(dialog.lbl) - dialog.vbox.pack_start(dialog.textbox) - dialog.show_all() - button = dialog.run() - if button == 1: - answer = dialog.textbox.get_text() - dialog.destroy() - self.refresh_networks(None,True,answer) - else: - dialog.destroy() + def connect_hidden(self,widget): + #should display a dialog asking + #for the ssid of a hidden network + #and displaying connect/cancel buttons + dialog = gtk.Dialog(title=language['hidden_network'], flags=gtk.DIALOG_MODAL, buttons=(gtk.STOCK_CONNECT,1,gtk.STOCK_CANCEL,2)) + dialog.set_has_separator(False) + dialog.lbl = gtk.Label(language['hidden_network_essid']) + dialog.textbox = gtk.Entry() + dialog.vbox.pack_start(dialog.lbl) + dialog.vbox.pack_start(dialog.textbox) + dialog.show_all() + button = dialog.run() + if button == 1: + answer = dialog.textbox.get_text() + dialog.destroy() + self.refresh_networks(None,True,answer) + else: + dialog.destroy() - def cancel_connect(self,widget): - #should cancel a connection if there - #is one in progress - cancelButton = self.wTree.get_widget("cancel_button") - cancelButton.set_sensitive(False) - wireless.CancelConnect() - wireless.SetForcedDisconnect(True) #Prevents automatic reconnecting if that option is enabled + def cancel_connect(self,widget): + #should cancel a connection if there + #is one in progress + cancelButton = self.wTree.get_widget("cancel_button") + cancelButton.set_sensitive(False) + wireless.CancelConnect() + wireless.SetForcedDisconnect(True) #Prevents automatic reconnecting if that option is enabled - def pulse_progress_bar(self): - self.wTree.get_widget("progressbar").pulse() - return True + def pulse_progress_bar(self): + self.wTree.get_widget("progressbar").pulse() + return True - def update_statusbar(self): - #should update the status bar - #every couple hundred milliseconds - if not daemon.GetDebugMode(): - config.DisableLogging() #stop log file spam - wireless_ip = wireless.GetWirelessIP() #do this so that it doesn't lock up. don't know how or why this works - #but it does so we leave it alone :) - wiredConnecting = wired.CheckIfWiredConnecting() - wirelessConnecting = wireless.CheckIfWirelessConnecting() - if wirelessConnecting == True or wiredConnecting == True: - self.network_list.set_sensitive(False) - self.status_area.show_all() - if self.statusID: - self.status_bar.remove(1,self.statusID) - if wirelessConnecting: - self.statusID = self.status_bar.push(1,language[str(wireless.CheckWirelessConnectingMessage())]) - if wiredConnecting: - self.statusID = self.status_bar.push(1,language[str(wired.CheckWiredConnectingMessage())]) - else: - self.network_list.set_sensitive(True) - self.status_area.hide_all() - if self.statusID: - self.status_bar.remove(1,self.statusID) - #use the chain approach to save calls to external programs - #external programs are quite CPU intensive - if wireless_ip: - network = wireless.GetCurrentNetwork() - if network: - strength = wireless.GetCurrentSignalStrength() - if strength != None: #do this because if strength is 0, if strength: doesn't work - network = str(network) - strength = str(strength) - ip = str(wireless_ip) - self.statusID=self.status_bar.push(1,language['connected_to_wireless'].replace('$A',network).replace('$B',strength).replace('$C',wireless_ip)) - if not daemon.GetDebugMode(): - config.EnableLogging() - return True - wired_ip = wired.GetWiredIP() - if wired_ip: - if wired.GetAlwaysShowWiredInterface() or wired.CheckPluggedIn(): - self.statusID = self.status_bar.push(1,language['connected_to_wired'].replace('$A',wired_ip)) - if not daemon.GetDebugMode(): - config.EnableLogging() - return True - self.statusID = self.status_bar.push(1,language['not_connected']) - if not daemon.GetDebugMode(): - config.EnableLogging() - return True + def update_statusbar(self): + #should update the status bar + #every couple hundred milliseconds + if not daemon.GetDebugMode(): + config.DisableLogging() #stop log file spam + wireless_ip = wireless.GetWirelessIP() #do this so that it doesn't lock up. don't know how or why this works + #but it does so we leave it alone :) + wiredConnecting = wired.CheckIfWiredConnecting() + wirelessConnecting = wireless.CheckIfWirelessConnecting() + if wirelessConnecting == True or wiredConnecting == True: + self.network_list.set_sensitive(False) + self.status_area.show_all() + if self.statusID: + self.status_bar.remove(1,self.statusID) + if wirelessConnecting: + self.statusID = self.status_bar.push(1,language[str(wireless.CheckWirelessConnectingMessage())]) + if wiredConnecting: + self.statusID = self.status_bar.push(1,language[str(wired.CheckWiredConnectingMessage())]) + else: + self.network_list.set_sensitive(True) + self.status_area.hide_all() + if self.statusID: + self.status_bar.remove(1,self.statusID) + #use the chain approach to save calls to external programs + #external programs are quite CPU intensive + if wireless_ip: + network = wireless.GetCurrentNetwork() + if network: + strength = wireless.GetCurrentSignalStrength() + if strength != None: #do this because if strength is 0, if strength: doesn't work + network = str(network) + strength = str(strength) + ip = str(wireless_ip) + self.statusID=self.status_bar.push(1,language['connected_to_wireless'].replace('$A',network).replace('$B',strength).replace('$C',wireless_ip)) + if not daemon.GetDebugMode(): + config.EnableLogging() + return True + wired_ip = wired.GetWiredIP() + if wired_ip: + if wired.GetAlwaysShowWiredInterface() or wired.CheckPluggedIn(): + self.statusID = self.status_bar.push(1,language['connected_to_wired'].replace('$A',wired_ip)) + if not daemon.GetDebugMode(): + config.EnableLogging() + return True + self.statusID = self.status_bar.push(1,language['not_connected']) + if not daemon.GetDebugMode(): + config.EnableLogging() + return True - def refresh_networks(self,widget=None,fresh=True,hidden=None): - print "refreshing..." - - printLine = False #so that we don't print the first line... - #remove stuff already in there. - for z in self.network_list: - z.destroy() + def refresh_networks(self,widget=None,fresh=True,hidden=None): + print "refreshing..." + + printLine = False #so that we don't print the first line... + #remove stuff already in there. + for z in self.network_list: + z.destroy() - if wired.CheckPluggedIn() or wired.GetAlwaysShowWiredInterface(): - printLine = True #so that a horizontal line is printed if there are wireless networks - wiredNetwork = PrettyWiredNetworkEntry() - self.network_list.pack_start(wiredNetwork,fill=False,expand=False) - wiredNetwork.connectButton.connect("button-press-event",self.connect,"wired",0,wiredNetwork) - #scan! - if fresh: - #even if it is None, it can still be passed - wireless.SetHiddenNetworkESSID(noneToString(hidden)) - wireless.Scan() + if wired.CheckPluggedIn() or wired.GetAlwaysShowWiredInterface(): + printLine = True #so that a horizontal line is printed if there are wireless networks + wiredNetwork = PrettyWiredNetworkEntry() + self.network_list.pack_start(wiredNetwork,fill=False,expand=False) + wiredNetwork.connectButton.connect("button-press-event",self.connect,"wired",0,wiredNetwork) + #scan! + if fresh: + #even if it is None, it can still be passed + wireless.SetHiddenNetworkESSID(noneToString(hidden)) + wireless.Scan() - print wireless.GetNumberOfNetworks() + print wireless.GetNumberOfNetworks() - instructLabel = self.wTree.get_widget("label_instructions") - if wireless.GetNumberOfNetworks() > 0: - instructLabel.show() - for x in range(0,wireless.GetNumberOfNetworks()): - if printLine: - sep = gtk.HSeparator() - self.network_list.pack_start(sep,padding=10,expand=False,fill=False) - sep.show() - else: - printLine = True - tempNetwork = PrettyWirelessNetworkEntry(x) - tempNetwork.show_all() - self.network_list.pack_start(tempNetwork,expand=False,fill=False) - tempNetwork.connectButton.connect("button-press-event",self.connect,"wireless",x,tempNetwork) - else: - instructLabel.hide() - label = gtk.Label(language['no_wireless_networks_found']) - self.network_list.pack_start(label) - label.show() - - def connect(self,widget,event,type,networkid,networkentry): - cancelButton = self.wTree.get_widget("cancel_button") - cancelButton.set_sensitive(True) - if type == "wireless": - wireless.SetWirelessProperty(networkid,"automatic",noneToString(networkentry.expander.checkboxAutoConnect.get_active())) - if networkentry.expander.checkboxStaticIP.get_active() == True: - wireless.SetWirelessProperty(networkid,"ip",noneToString(networkentry.expander.txtIP.get_text())) - wireless.SetWirelessProperty(networkid,"netmask",noneToString(networkentry.expander.txtNetmask.get_text())) - wireless.SetWirelessProperty(networkid,"gateway",noneToString(networkentry.expander.txtGateway.get_text())) - else: - #blank the values - wireless.SetWirelessProperty(networkid,"ip",'') - wireless.SetWirelessProperty(networkid,"netmask",'') - wireless.SetWirelessProperty(networkid,"gateway",'') + instructLabel = self.wTree.get_widget("label_instructions") + if wireless.GetNumberOfNetworks() > 0: + instructLabel.show() + for x in range(0,wireless.GetNumberOfNetworks()): + if printLine: + sep = gtk.HSeparator() + self.network_list.pack_start(sep,padding=10,expand=False,fill=False) + sep.show() + else: + printLine = True + tempNetwork = PrettyWirelessNetworkEntry(x) + tempNetwork.show_all() + self.network_list.pack_start(tempNetwork,expand=False,fill=False) + tempNetwork.connectButton.connect("button-press-event",self.connect,"wireless",x,tempNetwork) + else: + instructLabel.hide() + label = gtk.Label(language['no_wireless_networks_found']) + self.network_list.pack_start(label) + label.show() + + def connect(self,widget,event,type,networkid,networkentry): + cancelButton = self.wTree.get_widget("cancel_button") + cancelButton.set_sensitive(True) + if type == "wireless": + wireless.SetWirelessProperty(networkid,"automatic",noneToString(networkentry.expander.checkboxAutoConnect.get_active())) + if networkentry.expander.checkboxStaticIP.get_active() == True: + wireless.SetWirelessProperty(networkid,"ip",noneToString(networkentry.expander.txtIP.get_text())) + wireless.SetWirelessProperty(networkid,"netmask",noneToString(networkentry.expander.txtNetmask.get_text())) + wireless.SetWirelessProperty(networkid,"gateway",noneToString(networkentry.expander.txtGateway.get_text())) + else: + #blank the values + wireless.SetWirelessProperty(networkid,"ip",'') + wireless.SetWirelessProperty(networkid,"netmask",'') + wireless.SetWirelessProperty(networkid,"gateway",'') - if networkentry.expander.checkboxStaticDNS.get_active() == True and networkentry.expander.checkboxGlobalDNS.get_active() == False: - wireless.SetWirelessProperty(networkid,'global_dns',False) - wireless.SetWirelessProperty(networkid,'static_dns',True) - wireless.SetWirelessProperty(networkid,'dns1',noneToString(networkentry.expander.txtDNS1.get_text())) - wireless.SetWirelessProperty(networkid,'dns2',noneToString(networkentry.expander.txtDNS2.get_text())) - wireless.SetWirelessProperty(networkid,'dns3',noneToString(networkentry.expander.txtDNS3.get_text())) - elif networkentry.expander.checkboxStaticDNS.get_active() == True and networkentry.expander.checkboxGlobalDNS.get_active() == True: - wireless.SetWirelessProperty(networkid,'static_dns',True) - wireless.SetWirelessProperty(networkid,'global_dns',True) - else: - wireless.SetWirelessProperty(networkid,'static_dns',False) #disable static dns + if networkentry.expander.checkboxStaticDNS.get_active() == True and networkentry.expander.checkboxGlobalDNS.get_active() == False: + wireless.SetWirelessProperty(networkid,'use_static_dns',True) + wireless.SetWirelessProperty(networkid,'use_global_dns',False) + wireless.SetWirelessProperty(networkid,'dns1',noneToString(networkentry.expander.txtDNS1.get_text())) + wireless.SetWirelessProperty(networkid,'dns2',noneToString(networkentry.expander.txtDNS2.get_text())) + wireless.SetWirelessProperty(networkid,'dns3',noneToString(networkentry.expander.txtDNS3.get_text())) + elif networkentry.expander.checkboxStaticDNS.get_active() == True and networkentry.expander.checkboxGlobalDNS.get_active() == True: + wireless.SetWirelessProperty(networkid,'use_static_dns',True) + wireless.SetWirelessProperty(networkid,'use_global_dns',True) + else: + wireless.SetWirelessProperty(networkid,'use_static_dns',False) #disable static dns - if networkentry.expander.checkboxEncryption.get_active() == True: - print "setting encryption info..." - encryptionInfo = networkentry.expander.encryptionInfo - #set the encryption type. without the encryption type, nothing is gonna happen - wireless.SetWirelessProperty(networkid,"enctype",misc.LoadEncryptionMethods()[networkentry.expander.comboEncryption.get_active()][1]) - for x in encryptionInfo: - wireless.SetWirelessProperty(networkid,x,noneToString(encryptionInfo[x].get_text())) - else: - print "no encryption specified..." - wireless.SetWirelessProperty(networkid,"enctype",noneToString(None)) + if networkentry.expander.checkboxEncryption.get_active() == True: + print "setting encryption info..." + encryptionInfo = networkentry.expander.encryptionInfo + #set the encryption type. without the encryption type, nothing is gonna happen + wireless.SetWirelessProperty(networkid,"enctype",misc.LoadEncryptionMethods()[networkentry.expander.comboEncryption.get_active()][1]) + for x in encryptionInfo: + wireless.SetWirelessProperty(networkid,x,noneToString(encryptionInfo[x].get_text())) + else: + print "no encryption specified..." + wireless.SetWirelessProperty(networkid,"enctype",noneToString(None)) - # Script info - before_script = networkentry.expander.txtBeforeScript.get_text() - after_script = networkentry.expander.txtAfterScript.get_text() - wireless.SetWirelessProperty(networkid,"beforescript",noneToString(before_script)) - wireless.SetWirelessProperty(networkid,"afterscript",noneToString(after_script)) - wireless.SetWirelessBeforeScript(before_script) - wireless.SetWirelessAfterScript(after_script) + # Script info + before_script = networkentry.expander.txtBeforeScript.get_text() + after_script = networkentry.expander.txtAfterScript.get_text() + wireless.SetWirelessProperty(networkid,"beforescript",noneToString(before_script)) + wireless.SetWirelessProperty(networkid,"afterscript",noneToString(after_script)) + wireless.SetWirelessBeforeScript(before_script) + wireless.SetWirelessAfterScript(after_script) - # if it exists. maybe kept as a value in the network entry? Not sure... - print "connecting to wireless network..." - config.SaveWirelessNetworkProfile(networkid) - wireless.ConnectWireless(networkid) + # if it exists. maybe kept as a value in the network entry? Not sure... + print "connecting to wireless network..." + config.SaveWirelessNetworkProfile(networkid) + wireless.ConnectWireless(networkid) - if type == "wired": - print "wired" - if networkentry.expander.checkboxStaticIP.get_active() == True: - wired.SetWiredProperty("ip",noneToString(networkentry.expander.txtIP.get_text())) - wired.SetWiredProperty("netmask",noneToString(networkentry.expander.txtNetmask.get_text())) - wired.SetWiredProperty("gateway",noneToString(networkentry.expander.txtGateway.get_text())) - else: - wired.SetWiredProperty("ip",'') - wired.SetWiredProperty("netmask",'') - wired.SetWiredProperty("gateway",'') + if type == "wired": + print "wired" + if networkentry.expander.checkboxStaticIP.get_active() == True: + wired.SetWiredProperty("ip",noneToString(networkentry.expander.txtIP.get_text())) + wired.SetWiredProperty("netmask",noneToString(networkentry.expander.txtNetmask.get_text())) + wired.SetWiredProperty("gateway",noneToString(networkentry.expander.txtGateway.get_text())) + else: + wired.SetWiredProperty("ip",'') + wired.SetWiredProperty("netmask",'') + wired.SetWiredProperty("gateway",'') - if networkentry.expander.checkboxStaticDNS.get_active() == True: - wired.SetWiredProperty("dns1",noneToString(networkentry.expander.txtDNS1.get_text())) - wired.SetWiredProperty("dns2",noneToString(networkentry.expander.txtDNS2.get_text())) - wired.SetWiredProperty("dns3",noneToString(networkentry.expander.txtDNS3.get_text())) - else: - wired.SetWiredProperty("dns1",'') - wired.SetWiredProperty("dns2",'') - wired.SetWiredProperty("dns3",'') + if networkentry.expander.checkboxStaticDNS.get_active() == True: + wired.SetWiredProperty("dns1",noneToString(networkentry.expander.txtDNS1.get_text())) + wired.SetWiredProperty("dns2",noneToString(networkentry.expander.txtDNS2.get_text())) + wired.SetWiredProperty("dns3",noneToString(networkentry.expander.txtDNS3.get_text())) + else: + wired.SetWiredProperty("dns1",'') + wired.SetWiredProperty("dns2",'') + wired.SetWiredProperty("dns3",'') - #Script Info - before_script = networkentry.expander.txtBeforeScript.get_text() - after_script = networkentry.expander.txtAfterScript.get_text() - wired.SetWiredProperty("beforescript",noneToString(before_script)) - wired.SetWiredProperty("afterscript",noneToString(after_script)) - wired.SetWiredBeforeScript(before_script) - wired.SetWiredAfterScript(after_script) - - config.SaveWiredNetworkProfile(networkentry.expander.comboProfileNames.get_active_text()) - wired.ConnectWired() + #Script Info + before_script = networkentry.expander.txtBeforeScript.get_text() + after_script = networkentry.expander.txtAfterScript.get_text() + wired.SetWiredProperty("beforescript",noneToString(before_script)) + wired.SetWiredProperty("afterscript",noneToString(after_script)) + wired.SetWiredBeforeScript(before_script) + wired.SetWiredAfterScript(after_script) + + config.SaveWiredNetworkProfile(networkentry.expander.comboProfileNames.get_active_text()) + wired.ConnectWired() - def exit(self,widget,event=None): - sys.exit(0) + def exit(self,widget,event=None): + sys.exit(0) #start the app app = appGui() diff --git a/networking.py b/networking.py index e1c024a..903640c 100644 --- a/networking.py +++ b/networking.py @@ -8,7 +8,7 @@ import os,sys if __name__ == '__main__': - os.chdir(os.path.dirname(os.path.normpath(os.path.join(os.getcwd(),sys.argv[0])))) + os.chdir(os.path.dirname(os.path.normpath(os.path.join(os.getcwd(),sys.argv[0])))) #import the library of random functions that we need here #this is also written by me, for this purpose @@ -22,668 +22,665 @@ import re,sys,threading,thread class Wireless: - wireless_interface = None - wired_interface = None - wpa_driver = None - ConnectingThread = None - before_script = None - after_script = None - - #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 - - ##### - ## 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) - mode_pattern = re.compile('.*Mode:(.*?)\n',re.DOTALL | re.I | re.M | re.S) - - wep_pattern = re.compile('.*Encryption key:(.*?)\n',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 - 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 - print "setting hidden 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 - 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 - networks = scandata.split( ' Cell ' ) - - #declare - i=0 - #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 - - #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 - 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 - - 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 - CurrentNetwork["essid"] = "Hidden" - else: - CurrentNetwork["hidden"] = False - - CurrentNetwork["channel"] = misc.RunRegex(channel_pattern,cell) - 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 - if misc.RunRegex(wep_pattern,cell) == "on": - if self.wpa_driver != 'ralink legacy': - CurrentNetwork["encryption"] = True - #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(wpa2_pattern,cell) == "WPA2": - CurrentNetwork["encryption_method"] = "WPA2" - - else: #support for ralink legacy drivers, may not work w/ hidden networks - 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 == '': - break; - if info[2] == CurrentNetwork["essid"]: - if info[5] == 'WEP' or info[5] == 'OPEN': # Needs to be tested - CurrentNetwork["encryption_method"] = 'WEP' - elif info[5] == 'WPA-PSK': - CurrentNetwork["encrytion_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 link strength here - else: - CurrentNetwork["encryption"] = False - #end If - - if self.wpa_driver != 'ralink legacy': - #since stength 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) - else: - CurrentNetwork["quality"] = -1 - - #add this network to the list of networks - aps[ i ] = CurrentNetwork - #now increment the counter - i+=1 - #end For - - #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 - x = int(i) - #set y to the next number - y = int(i+1) - - #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 - - 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 - temp=aps[y] - aps[y]=aps[x] - aps[x]=temp - #end If - #end If - #end For - - if (sorted == False): - going = False - #end If - #end While - - #return the list of sorted access points - return aps - - #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.ConnectingThread.start() - return True - - class ConnectThread(threading.Thread): - IsConnecting = None - ConnectingMessage = None - ShouldDie = False - lock = thread.allocate_lock() - - def __init__(self,network,wireless,wired,wpa_driver,before_script,after_script): - threading.Thread.__init__(self) - self.network = network - self.wireless_interface = wireless - self.wired_interface = wired - self.wpa_driver = wpa_driver - self.IsConnecting = False - self.before_script = before_script - self.after_script = after_script - - self.lock.acquire() - self.ConnectingMessage = 'interface_down' - 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() - 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. - - self.IsConnecting = True - network = self.network - self.lock.acquire() - self.ConnectingMessage = 'executing_before_script' - self.lock.release() - - before_script = self.before_script - print 'before script is ', before_script - if before_script != '' and before_script != None: - print 'Executing pre-connection script' - misc.Run(before_script) - - #put it down - print "interface down..." - self.lock.acquire() - self.ConnectingMessage = 'interface_down' - 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 - print "Setting false ip..." - self.lock.acquire() - self.ConnectingMessage = 'resetting_ip_address' - 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() - - 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: - self.lock.acquire() - self.ConnectingMessage = 'generating_psk' - 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: - self.lock.acquire() - self.ConnectingMessage = 'generating_wpa_config' - self.lock.release() - - print "generating wpa_supplicant configuration file..." - misc.ParseEncryption(network) - print "wpa_supplicant -B -i " + self.wireless_interface + " -c \"encryption/configurations/" + network["bssid"].replace(":","").lower() + "\" -D " + self.wpa_driver - misc.Run("wpa_supplicant -B -i " + self.wireless_interface + " -c \"encryption/configurations/" + network["bssid"].replace(":","").lower() + "\" -D " + self.wpa_driver) - - print "flushing the routing table..." - self.lock.acquire() - self.ConnectingMessage = 'flushing_routing_table' - 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() - - #bring it up - print "interface up..." - self.lock.acquire() - self.ConnectingMessage = 'interface_up' - self.lock.release() - - print misc.Run("ifconfig " + self.wireless_interface + " up") - - if network["mode"].lower() == "master": - misc.Run("iwconfig " + self.wireless_interface + " mode managed") - else: - 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"] - - if self.wpa_driver == "ralink legacy": #Adds support for ralink cards that can't use wpasupplicant - if network.get('key') != None: - self.lock.acquire() - self.ConnectingMessage = 'setting_encryption_info' - self.lock.release() - - print 'setting up ralink encryption' - 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 - break; - if info[2] == network.get("essid"): - if info[5] == 'WEP' or info[5] == 'OPEN': # Needs to be tested - print 'setting up WEP' - misc.Run("iwconfig " + self.wireless_interface + " key " + network.get('key')) - 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]) - 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]) - else: - print 'Unknown AuthMode, can\'t complete connection process!!!' - print "done setting encryption info" - - if not network.get('broadcast') == None: - self.lock.acquire() - self.ConnectingMessage = 'setting_broadcast_address' - self.lock.release() - - print "setting the broadcast address..." + network["broadcast"] - misc.Run("ifconfig " + self.wireless_interface + " broadcast " + network["broadcast"]) - - - if not network.get("dns1") == None: - self.lock.acquire() - self.ConnectingMessage = 'setting_static_dns' - 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"] - misc.WriteLine(resolv,"nameserver " + network["dns2"]) - if not network.get("dns3") == None: - print "setting the third dns server..." - misc.WriteLine(resolv,"nameserver " + network["dns3"]) - if network.get('static_dns') == True and network.get('global_dns') == False: - if not network.get("dns1") == None: - self.lock.acquire() - self.ConnectingMessage = 'setting_static_dns' - 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"] - misc.WriteLine(resolv,"nameserver " + network["dns2"]) - if not network.get("dns3") == None: - print "setting the third dns server..." - misc.WriteLine(resolv,"nameserver " + network["dns3"]) - else: - if not self.global_dns_1 == None: - self.lock.acquire() - self.ConnectingMessage = 'setting_static_dns' - 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 self.global_dns_2 == None: - print "setting the second dns server...", self.global_dns_2 - misc.WriteLine(resolv,"nameserver " + self.global_dns_2) - if not self.global_dns_3 == None: - print "setting the third dns server..." - misc.WriteLine(resolv,"nameserver " + self.global_dns_3) - - if not network.get('ip') == None: - self.lock.acquire() - self.ConnectingMessage = 'setting_static_ip' - self.lock.release() - - print "setting static ips..." - 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() - - print "running dhcp..." - if not self.ShouldDie: - misc.Run("dhclient " + self.wireless_interface) - - self.lock.acquire() - self.ConnectingMessage = 'done' - self.lock.release() - - print "done" - self.IsConnecting = False - - after_script = self.after_script - if after_script != '' and after_script != None: - print 'executing post connection script' - misc.Run(after_script) - #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) - return misc.RunRegex(strength_pattern,output) - #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) - return misc.RunRegex(essid_pattern,output) - #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) - return misc.RunRegex(ip_pattern,output) - #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... - 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 - 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') - - ip_parts = misc.IsValidIP(ip) - - if ics and ip_parts: - #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 -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 -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 - - 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")) - - def Disconnect(self): - misc.Run('ifconfig ' + self.wired_interface + ' 0.0.0.0') - misc.Run('ifconfig ' + self.wired_interface + ' down') - misc.Run('ifconfig ' + self.wireless_interface + ' 0.0.0.0') - misc.Run('ifconfig ' + self.wireless_interface + ' down') + wireless_interface = None + wired_interface = None + wpa_driver = None + ConnectingThread = None + before_script = None + after_script = None + + #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 + + ##### + ## 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) + mode_pattern = re.compile('.*Mode:(.*?)\n',re.DOTALL | re.I | re.M | re.S) + + wep_pattern = re.compile('.*Encryption key:(.*?)\n',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 + 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 + print "setting hidden 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 + 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 + networks = scandata.split( ' Cell ' ) + + #declare + i=0 + #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 + + #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 + 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 + + 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 + CurrentNetwork["essid"] = "Hidden" + else: + CurrentNetwork["hidden"] = False + + CurrentNetwork["channel"] = misc.RunRegex(channel_pattern,cell) + 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 + if misc.RunRegex(wep_pattern,cell) == "on": + if self.wpa_driver != 'ralink legacy': + CurrentNetwork["encryption"] = True + #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(wpa2_pattern,cell) == "WPA2": + CurrentNetwork["encryption_method"] = "WPA2" + + else: #support for ralink legacy drivers, may not work w/ hidden networks + 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 == '': + break; + if info[2] == CurrentNetwork["essid"]: + if info[5] == 'WEP' or info[5] == 'OPEN': # Needs to be tested + CurrentNetwork["encryption_method"] = 'WEP' + elif info[5] == 'WPA-PSK': + CurrentNetwork["encrytion_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 link strength here + else: + CurrentNetwork["encryption"] = False + #end If + + if self.wpa_driver != 'ralink legacy': + #since stength 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) + else: + CurrentNetwork["quality"] = -1 + + #add this network to the list of networks + aps[ i ] = CurrentNetwork + #now increment the counter + i+=1 + #end For + + #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 + x = int(i) + #set y to the next number + y = int(i+1) + + #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 + + 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 + temp=aps[y] + aps[y]=aps[x] + aps[x]=temp + #end If + #end If + #end For + + if (sorted == False): + going = False + #end If + #end While + + #return the list of sorted access points + return aps + + #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.global_dns_1,self.global_dns_2,self.global_dns_3) + self.ConnectingThread.start() + return True + + class ConnectThread(threading.Thread): + IsConnecting = None + ConnectingMessage = None + ShouldDie = False + lock = thread.allocate_lock() + + def __init__(self,network,wireless,wired,wpa_driver,before_script,after_script,gdns1,gdns2,gdns3): + threading.Thread.__init__(self) + self.network = network + self.wireless_interface = wireless + self.wired_interface = wired + self.wpa_driver = wpa_driver + self.IsConnecting = False + self.before_script = before_script + self.after_script = after_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() + #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() + 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. + + self.IsConnecting = True + network = self.network + self.lock.acquire() + self.ConnectingMessage = 'executing_before_script' + self.lock.release() + + before_script = self.before_script + print 'before script is ', before_script + if before_script != '' and before_script != None: + print 'Executing pre-connection script' + misc.Run(before_script) + + #put it down + print "interface down..." + self.lock.acquire() + self.ConnectingMessage = 'interface_down' + 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 + print "Setting false ip..." + self.lock.acquire() + self.ConnectingMessage = 'resetting_ip_address' + 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() + + 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: + self.lock.acquire() + self.ConnectingMessage = 'generating_psk' + 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: + self.lock.acquire() + self.ConnectingMessage = 'generating_wpa_config' + self.lock.release() + + print "generating wpa_supplicant configuration file..." + misc.ParseEncryption(network) + print "wpa_supplicant -B -i " + self.wireless_interface + " -c \"encryption/configurations/" + network["bssid"].replace(":","").lower() + "\" -D " + self.wpa_driver + misc.Run("wpa_supplicant -B -i " + self.wireless_interface + " -c \"encryption/configurations/" + network["bssid"].replace(":","").lower() + "\" -D " + self.wpa_driver) + + print "flushing the routing table..." + self.lock.acquire() + self.ConnectingMessage = 'flushing_routing_table' + 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() + + #bring it up + print "interface up..." + self.lock.acquire() + self.ConnectingMessage = 'interface_up' + self.lock.release() + + print misc.Run("ifconfig " + self.wireless_interface + " up") + + if network["mode"].lower() == "master": + misc.Run("iwconfig " + self.wireless_interface + " mode managed") + else: + 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"] + + if self.wpa_driver == "ralink legacy": #Adds support for ralink cards that can't use wpasupplicant + if network.get('key') != None: + self.lock.acquire() + self.ConnectingMessage = 'setting_encryption_info' + self.lock.release() + + print 'setting up ralink encryption' + 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 + break; + if info[2] == network.get("essid"): + if info[5] == 'WEP' or info[5] == 'OPEN': # Needs to be tested + print 'setting up WEP' + misc.Run("iwconfig " + self.wireless_interface + " key " + network.get('key')) + 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]) + 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]) + else: + print 'Unknown AuthMode, can\'t complete connection process!!!' + print "done setting encryption info" + + if not network.get('broadcast') == None: + self.lock.acquire() + self.ConnectingMessage = 'setting_broadcast_address' + self.lock.release() + + print "setting the broadcast address..." + network["broadcast"] + misc.Run("ifconfig " + self.wireless_interface + " broadcast " + network["broadcast"]) + + if not network.get('ip') == None: + self.lock.acquire() + self.ConnectingMessage = 'setting_static_ip' + self.lock.release() + + print "setting static ips..." + 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() + + print "running dhcp..." + if not self.ShouldDie: + misc.Run("dhclient " + self.wireless_interface) + + #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: + self.lock.acquire() + self.ConnectingMessage = 'setting_static_dns' + 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"] + misc.WriteLine(resolv,"nameserver " + network["dns2"]) + if not network.get("dns3") == 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: + self.lock.acquire() + self.ConnectingMessage = 'setting_static_dns' + 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 + misc.WriteLine(resolv,"nameserver " + self.global_dns_2) + if not misc.Noneify(self.global_dns_3) == 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() + + print "done" + self.IsConnecting = False + + after_script = self.after_script + if after_script != '' and after_script != None: + print 'executing post connection script' + misc.Run(after_script) + #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) + return misc.RunRegex(strength_pattern,output) + #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) + return misc.RunRegex(essid_pattern,output) + #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) + return misc.RunRegex(ip_pattern,output) + #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... + 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 + 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') + + ip_parts = misc.IsValidIP(ip) + + if ics and ip_parts: + #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 -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 -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 + + 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")) + + def Disconnect(self): + misc.Run('ifconfig ' + self.wired_interface + ' 0.0.0.0') + misc.Run('ifconfig ' + self.wired_interface + ' down') + misc.Run('ifconfig ' + self.wireless_interface + ' 0.0.0.0') + misc.Run('ifconfig ' + self.wireless_interface + ' down') #end class Wireless class Wired: - wireless_interface = None - wired_interface = None - ConnectingThread = None - before_script = None - after_script = None + wireless_interface = None + wired_interface = None + ConnectingThread = None + before_script = None + after_script = None - def GetIP(self): - output = misc.Run("ifconfig " + self.wired_interface) - ip_pattern = re.compile(r'inet [Aa]d?dr[^.]*:([^.]*\.[^.]*\.[^.]*\.[0-9]*)',re.S) - return misc.RunRegex(ip_pattern,output) + def GetIP(self): + output = misc.Run("ifconfig " + self.wired_interface) + ip_pattern = re.compile(r'inet [Aa]d?dr[^.]*:([^.]*\.[^.]*\.[^.]*\.[0-9]*)',re.S) + return misc.RunRegex(ip_pattern,output) - 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: - 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: - return True - else: - return False - #end function CheckPluggedIn + 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: + 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: + return True + else: + return False + #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.ConnectingThread.start() - return True - #end function Connect + 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.ConnectingThread.start() + return True + #end function Connect - class ConnectThread(threading.Thread): - #wired interface connect thread - lock = thread.allocate_lock() - ConnectingMessage = None - ShouldDie = False + class ConnectThread(threading.Thread): + #wired interface connect thread + lock = thread.allocate_lock() + ConnectingMessage = None + ShouldDie = False - def __init__(self,network,wireless,wired,before_script,after_script): - threading.Thread.__init__(self) - self.network = network - self.wireless_interface = wireless - self.wired_interface = wired - self.IsConnecting = False - self.before_script = before_script - self.after_script = after_script - self.lock.acquire() - self.ConnectingMessage = 'interface_down' - self.lock.release() - #end function __init__ + def __init__(self,network,wireless,wired,before_script,after_script): + threading.Thread.__init__(self) + self.network = network + self.wireless_interface = wireless + self.wired_interface = wired + self.IsConnecting = False + self.before_script = before_script + self.after_script = after_script + self.lock.acquire() + self.ConnectingMessage = 'interface_down' + self.lock.release() + #end function __init__ - def GetStatus(self): - self.lock.acquire() - print " ...lock acquired..." - message = self.ConnectingMessage - self.lock.release() - print " ...lock released..." - return message + def GetStatus(self): + self.lock.acquire() + print " ...lock acquired..." + message = self.ConnectingMessage + 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 + def run(self): + #we don't touch the wifi interface + #but we do remove all wifi entries from the + #routing table - before_script = self.before_script - print 'before script is ', before_script - if before_script != '' and before_script != None: - print 'Executing pre-connection script' - misc.Run(before_script) + before_script = self.before_script + print 'before script is ', before_script + if before_script != '' and before_script != None: + print 'Executing pre-connection script' + misc.Run(before_script) - self.IsConnecting = True - network = self.network + self.IsConnecting = True + network = self.network - #put it down - self.lock.acquire() - self.ConnectingMessage = 'interface_down' - self.lock.release() - print "interface down...", self.wired_interface - misc.Run("ifconfig " + self.wired_interface + " down") + #put it down + self.lock.acquire() + self.ConnectingMessage = 'interface_down' + 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 - self.lock.acquire() - self.ConnectingMessage = 'resetting_ip_address' - 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") + #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() + 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 - self.lock.acquire() - self.ConnectingMessage = 'interface_up' - self.lock.release() - print "interface up...", self.wired_interface - misc.Run("ifconfig " + self.wired_interface + " up") + #bring it up + self.lock.acquire() + self.ConnectingMessage = 'interface_up' + 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() - misc.Run("killall dhclient dhclient3 wpa_supplicant") + print "killing wpa_supplicant, dhclient, dhclient3" + self.lock.acquire() + self.ConnectingMessage = 'removing_old_connection' + 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() - misc.Run("ip route flush dev " + self.wireless_interface) - misc.Run("ip route flush dev " + self.wired_interface) + print "flushing the routing table..." + self.lock.acquire() + self.ConnectingMessage = 'flushing_routing_table' + 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: - self.lock.acquire() - self.ConnectingMessage = 'setting_broadcast_address' - self.lock.release() - print "setting the broadcast address..." + network["broadcast"] - misc.Run("ifconfig " + self.wired_interface + " broadcast " + network["broadcast"]) + if not network.get("broadcast") == None: + self.lock.acquire() + self.ConnectingMessage = 'setting_broadcast_address' + self.lock.release() + print "setting the broadcast address..." + network["broadcast"] + misc.Run("ifconfig " + self.wired_interface + " broadcast " + network["broadcast"]) - if not network.get("dns1") == None: - self.lock.acquire() - self.ConnectingMessage = 'setting_static_dns' - 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"] - misc.WriteLine(resolv,"nameserver " + network["dns2"]) - if not network.get("dns3") == None: - print "setting the third dns server..." - misc.WriteLine(resolv,"nameserver " + network["dns3"]) + if not network.get("dns1") == None: + self.lock.acquire() + self.ConnectingMessage = 'setting_static_dns' + 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"] + misc.WriteLine(resolv,"nameserver " + network["dns2"]) + if not network.get("dns3") == None: + print "setting the third dns server..." + misc.WriteLine(resolv,"nameserver " + network["dns3"]) - if not network.get("ip") == None: - self.lock.acquire() - self.ConnectingMessage = 'setting_static_ip' - 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"]) - 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() - print "running dhcp..." - if not self.ShouldDie: - misc.Run("dhclient " + self.wired_interface) + if not network.get("ip") == None: + self.lock.acquire() + self.ConnectingMessage = 'setting_static_ip' + 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"]) + 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() + print "running dhcp..." + if not self.ShouldDie: + misc.Run("dhclient " + self.wired_interface) - self.lock.acquire() - self.ConnectingMessage = 'done' - self.lock.release() - self.IsConnecting = False + self.lock.acquire() + self.ConnectingMessage = 'done' + self.lock.release() + self.IsConnecting = False - after_script = self.after_script - if after_script != '' and after_script != None: - print 'executing post connection script' - misc.Run(after_script) - #end function run + after_script = self.after_script + if after_script != '' and after_script != None: + print 'executing post connection script' + misc.Run(after_script) + #end function run