diff --git a/daemon.py b/daemon.py index 79945f4..6460a85 100644 --- a/daemon.py +++ b/daemon.py @@ -1,4 +1,5 @@ #!/usr/bin/env python +# -*- coding: utf-8 -*- """ wicd - wireless connection daemon implementation. This module implements the wicd daemon that provides network @@ -6,7 +7,7 @@ connection management, for both wireless and wired networks. The daemon must be run as root to control the networks, however the user interface components should be run as a normal user. -class LogWriter() -- Class to redirect stdout and stderr to a log file. +class LogWriter() -- Class to redirect stdout and stderr to a log file. class ConnectionWizard() -- DBUS interface to manage the network. def usage() -- Print usage information. def daemonize() -- Daemonize the current process with a double fork. @@ -50,6 +51,16 @@ import misc if __name__ == '__main__': wpath.chdir(__file__) + +if sys.platform == 'linux2': + # Set process name. Only works on Linux >= 2.1.57. + try: + import dl + libc = dl.open('/lib/libc.so.6') + libc.call('prctl', 15, 'wicd-daemon\0', 0, 0, 0) # 15 is PR_SET_NAME + except: + pass + logging_enabled = True @@ -83,6 +94,7 @@ class LogWriter: """ global logging_enabled + data = data.encode('utf-8') if len(data) <= 0: return if logging_enabled: if self.eol: @@ -121,7 +133,6 @@ class ConnectionWizard(dbus.service.Object): auto_connect=True): 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 = wpath.etc + 'manager-settings.conf' self.wireless_conf = wpath.etc + 'wireless-settings.conf' self.wired_conf = wpath.etc + 'wired-settings.conf' @@ -130,20 +141,21 @@ class ConnectionWizard(dbus.service.Object): self.wired = networking.Wired() self.forced_disconnect = False self.need_profile_chooser = False + self.current_interface = None + self.vpn_session = None - #load the config file - it should have most of the stuff we need to run... + # Load the config file 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) + # 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 = '' - #make a variable that will hold the wired network profile + # Make a variable that will hold the wired network profile self.WiredNetwork = {} - #scan since we just got started + # Scan since we just got started if auto_connect: print "autoconnecting...",str(self.GetWirelessInterface()[5:]) print self.AutoConnect(True) @@ -155,7 +167,7 @@ class ConnectionWizard(dbus.service.Object): @dbus.service.method('org.wicd.daemon') def Hello(self): - '''returns the version number''' + ''' Returns the version number ''' #returns a version number. #this number is major-minor-micro #major is only incremented if minor @@ -165,14 +177,14 @@ class ConnectionWizard(dbus.service.Object): #micro is for everything else. #and micro may be anything >= 0 #this number is effective starting wicd v1.2.0 - version = '1.3.3' + version = '1.4.0' 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''' + ''' 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 @@ -184,7 +196,7 @@ class ConnectionWizard(dbus.service.Object): @dbus.service.method('org.wicd.daemon') def SetWirelessInterface(self,interface): - '''sets the wireless interface the daemon will use''' + ''' Sets the wireless interface the daemon will use ''' print "setting wireless interface" , str(interface) self.wifi.wireless_interface = interface self.wired.wireless_interface = interface @@ -197,7 +209,7 @@ class ConnectionWizard(dbus.service.Object): @dbus.service.method('org.wicd.daemon') def SetWPADriver(self,driver): - '''sets the wpa driver the wpa_supplicant will use''' + ''' Sets the wpa driver the wpa_supplicant will use ''' print "setting wpa driver" , str(driver) self.wifi.wpa_driver = driver config = ConfigParser.ConfigParser() @@ -209,6 +221,7 @@ class ConnectionWizard(dbus.service.Object): @dbus.service.method('org.wicd.daemon') def SetUseGlobalDNS(self,use): + ''' Sets a boolean which determines if global DNS is enabled ''' print 'setting use global dns to',use use = bool(use) print 'setting use global dns to boolean',use @@ -223,7 +236,7 @@ class ConnectionWizard(dbus.service.Object): @dbus.service.method('org.wicd.daemon') def SetGlobalDNS(self,dns1=None,dns2=None,dns3=None): - '''sets the global dns addresses''' + ''' Sets the global dns addresses ''' print "setting global dns" config = ConfigParser.ConfigParser() config.read(self.app_conf) @@ -247,35 +260,36 @@ class ConnectionWizard(dbus.service.Object): @dbus.service.method('org.wicd.daemon') def GetUseGlobalDNS(self): + ''' Returns a boolean that determines if global dns is enabled ''' return bool(self.use_global_dns) @dbus.service.method('org.wicd.daemon') def GetWPADriver(self): - '''returns the wpa driver the daemon is using''' + ''' 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''' + ''' 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''' + ''' 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''' + 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",int(debug)) + config.set("Settings","debug_mode",debug) configfile = open(self.app_conf,"w") config.write(configfile) self.debug_mode = debug @@ -283,13 +297,13 @@ class ConnectionWizard(dbus.service.Object): @dbus.service.method('org.wicd.daemon') def GetDebugMode(self): - '''returns whether debugging is enabled''' + ''' Returns whether debugging is enabled ''' return int(self.debug_mode) #end function GetDebugMode @dbus.service.method('org.wicd.daemon') def GetSignalDisplayType(self): - ''' returns the signal display type + ''' Returns the signal display type Returns either 0 or 1. 0 for signal strength as a percentage @@ -304,7 +318,7 @@ class ConnectionWizard(dbus.service.Object): ''' Sets the signal display type and writes it the wicd config file ''' config = ConfigParser.ConfigParser() config.read(self.app_conf) - config.set("Settings","signal_display_type",int(value)) + config.set("Settings","signal_display_type",value) configfile = open(self.app_conf,"w") config.write(configfile) self.signal_display_type = value @@ -319,8 +333,7 @@ class ConnectionWizard(dbus.service.Object): return (signal + "%") # End function FormatSignalForPrinting - - @dbus.service.method('org.wicd.daemon') + @dbus.service. method('org.wicd.daemon') def AutoConnect(self,fresh): '''first tries to autoconnect to a wired network, if that fails it tries a wireless connection''' if fresh: @@ -328,31 +341,13 @@ class ConnectionWizard(dbus.service.Object): #self.AutoConnectScan() # Also scans for hidden networks if self.CheckPluggedIn() == True: if self.GetWiredAutoConnectMethod() == 2: - #self.SetNeedWiredProfileChooser(True) self.LaunchChooser() - elif self.GetWiredAutoConnectMethod() == 3: - lastUsedNetwork = self.GetLastUsedWiredNetwork() - if lastUsedNetwork != None: - self.ReadWiredNetworkProfile(lastUsedNetwork) - self.wired.profilename = lastUsedNetwork - self.ConnectWired() - time.sleep(1) - print "Attempting to autoconnect with last used wired interface..." - while self.CheckIfWiredConnecting(): #Leaving this for wired since you're probably not going to have DHCP problems - time.sleep(1) - print "...done autoconnecting with last used wired connection." - else: - print "there is no last used wired connection, wired autoconnect failed" else: defaultNetwork = self.GetDefaultWiredNetwork() if defaultNetwork != None: self.ReadWiredNetworkProfile(defaultNetwork) self.ConnectWired() - time.sleep(1) print "Attempting to autoconnect with wired interface..." - while self.CheckIfWiredConnecting(): #Leaving this for wired since you're probably not going to have DHCP problems - time.sleep(1) - print "...done autoconnecting." else: print "couldn't find a default wired connection, wired autoconnect failed" else: @@ -365,40 +360,11 @@ class ConnectionWizard(dbus.service.Object): if bool(self.LastScan[x].get('automatic')): print 'trying to automatically connect to...',str(self.LastScan[x]["essid"]) self.ConnectWireless(x) - time.sleep(5) + time.sleep(1) return - #Changed this because the while loop would cause dbus errors if - #there was trouble connecting or connecting took a long time - #print "autoconnecting... hold" - #while self.CheckIfWirelessConnecting(): - #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(3) - #if self.GetWirelessIP() != None: - # print "autoconnecting... done" - # return - #else: - # print 'autoconnect was taking too long, aborted.' - # self.SetForcedDisconnect(True) - # return print "unable to autoconnect, you'll have to manually connect" else: - print 'autoconnect failed because wireless interface == None' + print 'autoconnect failed because wireless interface returned None' #end function AutoConnect @dbus.service.method('org.wicd.daemon') @@ -418,6 +384,14 @@ class ConnectionWizard(dbus.service.Object): else: return True #end function CheckIfConnecting + + @dbus.service.method('org.wicd.daemon') + def GetCurrentInterface(self): + return self.current_interface + + @dbus.service.method('org.wicd.daemon') + def SetCurrentInterface(self, iface): + self.current_interface = iface @dbus.service.method('org.wicd.daemon') def SetNeedWiredProfileChooser(self,val): @@ -432,21 +406,7 @@ class ConnectionWizard(dbus.service.Object): @dbus.service.signal(dbus_interface='org.wicd.daemon', signature='') def LaunchChooser(self): print 'calling wired profile chooser' - - @dbus.service.signal(dbus_interface='org.wicd.daemon',signature='') - def CloseGui(self, killed): - ''' Sends a dbus signal announcing the GUI is closing ''' - print 'sending close signal' - @dbus.service.method('org.wicd.daemon') - def close_gui(self): - ''' Calls the CloseGui method - - intermediary method to send a signal announcing gui.py is being - closed. It's needed because a method can't be both a - service.method and service.signal - - ''' - self.CloseGui(True) + daemon.SetNeedWiredProfileChooser(True) ########## WIRELESS FUNCTIONS ################################# @@ -461,15 +421,14 @@ class ConnectionWizard(dbus.service.Object): 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... + scan = self.wifi.Scan(str(self.hidden_essid)) self.LastScan = scan print 'scanning done' print 'found',str(len(scan)),'networks:', for i, network in enumerate(scan): self.ReadWirelessNetworkProfile(i) - print - - # This is unfinished so not on dbus yet + + # This is unfinished so not on dbus yet def AutoConnectScan(self): ''' Scan for networks and for known hidden networks @@ -572,6 +531,10 @@ class ConnectionWizard(dbus.service.Object): '''retrieves wireless property from the network specified''' value = self.LastScan[networkid].get(property) print 'returned wireless network',networkid,'property',property,'of value',value + try: + value = value.encode('utf-8') + except: + pass return value #end function GetWirelessProperty @@ -595,7 +558,10 @@ class ConnectionWizard(dbus.service.Object): @dbus.service.method('org.wicd.daemon.wireless') def GetCurrentSignalStrength(self): '''returns the current signal strength''' - strength = int(self.wifi.GetSignalStrength()) + try: + strength = int(self.wifi.GetSignalStrength()) + except: + strength = 0 print 'returning current signal strength',strength return strength #end function GetCurrentSignalStrength @@ -630,9 +596,9 @@ class ConnectionWizard(dbus.service.Object): @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 + # 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') @@ -649,16 +615,22 @@ class ConnectionWizard(dbus.service.Object): @dbus.service.method('org.wicd.daemon.wireless') def SetForcedDisconnect(self,value): - '''sets whether wireless has been disconnected by user since last connection''' + ''' + + Set to True when a user manually disconnects or cancels a connection. + It gets set to False as soon as the connection process is manually + started. + + ''' 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''' + ''' Returns True if wireless interface is connecting, otherwise False''' if not self.wifi.connecting_thread == None: - #if connecting_thread exists, then check for it's - #status, if it doesn't, we aren't connecting + # If connecting_thread exists, then check for it's + # status, if it doesn't, we aren't connecting. status = self.wifi.connecting_thread.is_connecting print 'wireless connecting',status return status @@ -819,7 +791,7 @@ class ConnectionWizard(dbus.service.Object): @dbus.service.method('org.wicd.daemon.wired') def CheckPluggedIn(self): - if not self.wired.wired_interface == None: + if not self.wired.wired_interface == None and self.wired.wired_interface != "None": return self.__printReturn('returning plugged in',self.wired.CheckPluggedIn()) else: return self.__printReturn("returning plugged in",None) @@ -828,7 +800,6 @@ class ConnectionWizard(dbus.service.Object): @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.disconnect_script = self.GetWiredProperty("disconnectscript") @@ -907,8 +878,6 @@ class ConnectionWizard(dbus.service.Object): config.set(profile,"default", False) self.SaveWiredNetworkProfile(profile) #end function UnsetWiredDefault - - @dbus.service.method('org.wicd.daemon.config') def GetDefaultWiredNetwork(self): @@ -1006,7 +975,7 @@ class ConnectionWizard(dbus.service.Object): #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.set(self.LastScan[id]["bssid"], x, self.LastScan[id][x]) config.write(open(self.wireless_conf,"w")) #end function SaveWirelessNetworkProfile @@ -1029,16 +998,16 @@ class ConnectionWizard(dbus.service.Object): 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")) + 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]["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 - if config.has_option(self.LastScan[id]["bssid"],"disconnectscript"): + if config.has_option(self.LastScan[id]["bssid"], "disconnectscript"): self.LastScan[id]["disconnectscript"] = misc.Noneify(config.get(self.LastScan[id]["bssid"], "disconnectscript")) else: @@ -1047,10 +1016,10 @@ class ConnectionWizard(dbus.service.Object): #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")) + 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)) + self.LastScan[id][x] = misc.Noneify(config.get(self.LastScan[id]["bssid"], x)) return "100: Loaded Profile" else: self.LastScan[id]["has_profile"] = False @@ -1080,7 +1049,7 @@ class ConnectionWizard(dbus.service.Object): config = ConfigParser.ConfigParser() config.read(self.app_conf) if config.has_section("Settings"): - if config.has_option("Settings","wireless_interface"): + if config.has_option("Settings", "wireless_interface"): print "found wireless interface in configuration...", self.SetWirelessInterface(config.get("Settings", "wireless_interface")) @@ -1088,10 +1057,10 @@ class ConnectionWizard(dbus.service.Object): print "found wired interface in configuration...", self.SetWiredInterface(config.get("Settings", "wired_interface")) - if config.has_option("Settings","wpa_driver"): + 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.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: @@ -1103,32 +1072,32 @@ class ConnectionWizard(dbus.service.Object): self.SetUseGlobalDNS(int(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"): + 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') + if config.has_option("Settings", "global_dns_3"): + dns3 = config.get('Settings', 'global_dns_3') self.SetGlobalDNS(dns1,dns2,dns3) else: self.SetUseGlobalDNS(False) - self.SetGlobalDNS(False,False,False) - if config.has_option("Settings","auto_reconnect"): + self.SetGlobalDNS(False, False, False) + if config.has_option("Settings", "auto_reconnect"): self.auto_reconnect = config.get("Settings", "auto_reconnect") else: - config.set("Settings","auto_reconnect","0") + config.set("Settings", "auto_reconnect", "0") self.auto_reconnect = False - if config.has_option("Settings","debug_mode"): - self.debug_mode = config.get("Settings","debug_mode") + if config.has_option("Settings", "debug_mode"): + self.debug_mode = config.get("Settings", "debug_mode") else: self.debug_mode = 0 - config.set("Settings","debug_mode","0") - if config.has_option("Settings","wired_connect_mode"): + config.set("Settings", "debug_mode", "0") + if config.has_option("Settings", "wired_connect_mode"): self.SetWiredAutoConnectMethod(config.get("Settings", "wired_connect_mode")) else: - config.set("Settings","wired_connect_mode","1") + config.set("Settings", "wired_connect_mode", "1") self.SetWiredAutoConnectMethod(config.get("Settings", "wired_connect_mode")) if config.has_option("Settings", "signal_display_type"): @@ -1138,19 +1107,19 @@ class ConnectionWizard(dbus.service.Object): self.SetSignalDisplayType(0) else: print "configuration file exists, no settings found, adding defaults..." - configfile = open(self.app_conf,"w") + 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","0") - config.set("Settings","auto_reconnect","0") - config.set("Settings","debug_mode","0") - config.set("Settings","wired_connect_mode","1") - config.set("Settings","use_global_dns","False") - config.set("Settings","dns1","None") - config.set("Settings","dns2","None") - config.set("Settings","dns3","None") + 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","0") + config.set("Settings", "auto_reconnect","0") + config.set("Settings", "debug_mode","0") + config.set("Settings", "wired_connect_mode","1") + config.set("Settings", "use_global_dns","False") + config.set("Settings", "dns1","None") + config.set("Settings", "dns2","None") + config.set("Settings", "dns3","None") config.set("Settings", "signal_display_type", "0") self.SetUseGlobalDNS(False) self.SetGlobalDNS(config.get('Settings', 'dns1'), @@ -1176,24 +1145,24 @@ class ConnectionWizard(dbus.service.Object): 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","0") - config.set("Settings","auto_reconnect","0") - config.set("Settings","debug_mode","0") - config.set("Settings","wired_connect_mode","1") + config.set("Settings", "wireless_interface", "wlan0") + config.set("Settings", "wired_interface", "eth0") + config.set("Settings", "always_show_wired_interface", "0") + config.set("Settings", "auto_reconnect", "0") + config.set("Settings", "debug_mode", "0") + config.set("Settings", "wired_connect_mode", "1") config.set("Settings", "signal_display_type", "0") - config.set("Settings","dns1","None") - config.set("Settings","dns2","None") - config.set("Settings","dns3","None") + config.set("Settings", "dns1", "None") + config.set("Settings", "dns2", "None") + config.set("Settings", "dns3", "None") iface = self.DetectWirelessInterface() if iface is not None: - config.set("Settings","wireless_interface",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")) + 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", @@ -1206,7 +1175,7 @@ class ConnectionWizard(dbus.service.Object): self.SetWiredAutoConnectMethod(1) self.SetSignalDisplayType(0) self.SetUseGlobalDNS(False) - self.SetGlobalDNS(None,None,None) + self.SetGlobalDNS(None, None, None) #end If if os.path.isfile( self.wireless_conf ): @@ -1216,7 +1185,7 @@ class ConnectionWizard(dbus.service.Object): 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() + open( self.wireless_conf, "w" ).close() #end If if os.path.isfile( self.wired_conf ): @@ -1226,14 +1195,14 @@ class ConnectionWizard(dbus.service.Object): 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() + 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) + 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..." diff --git a/gui.py b/gui.py index bfa4369..efe98b1 100644 --- a/gui.py +++ b/gui.py @@ -2,6 +2,7 @@ import os import sys import wpath +import signal if __name__ == '__main__': wpath.chdir(__file__) try: @@ -38,6 +39,7 @@ except: 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') +vpn_session = dbus.Interface(proxy_obj, 'org.wicd.daemon.vpn') config = dbus.Interface(proxy_obj, 'org.wicd.daemon.config') #Translation stuff @@ -179,12 +181,12 @@ class LinkButton(gtk.EventBox): 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_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 @@ -229,7 +231,7 @@ class LabelEntry(gtk.HBox): # When the box has focus, show the characters if self.auto_hide_text and widget: self.entry.set_visibility(True) - + def set_sensitive(self,value): self.entry.set_sensitive(value) self.label.set_sensitive(value) @@ -253,7 +255,7 @@ class GreyLabel(gtk.Label): 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" + return "None" else: return str(text) @@ -286,7 +288,7 @@ def checkboxTextboxToggle(checkbox,textboxes): ######################################## ##### NETWORK LIST CLASSES -######################################## +######################################## class PrettyNetworkEntry(gtk.HBox): @@ -313,7 +315,7 @@ class PrettyWiredNetworkEntry(PrettyNetworkEntry): self.image.set_alignment(.5,0) self.image.set_size_request(60,-1) - self.image.set_from_icon_name("network-wired",6) + self.image.set_from_icon_name("network-wired",6) self.image.show() self.pack_start(self.image,fill=False,expand=False) self.show() @@ -328,7 +330,7 @@ class PrettyWirelessNetworkEntry(PrettyNetworkEntry): 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.image.set_from_icon_name("network-wired",6) self.pack_start(self.image,fill=False,expand=False) self.setSignalStrength(wireless.GetWirelessProperty(networkID,'quality'), wireless.GetWirelessProperty(networkID,'strength')) @@ -339,7 +341,7 @@ class PrettyWirelessNetworkEntry(PrettyNetworkEntry): wireless.GetWirelessProperty(networkID,'encryption_method')) #show everything self.show_all() - + def setSignalStrength(self,strength, dbm_strength): if strength is not None: strength = int(strength) @@ -374,7 +376,7 @@ class PrettyWirelessNetworkEntry(PrettyNetworkEntry): else: self.image.set_from_file(wpath.images + 'signal-25.png') self.expander.setSignalStrength(strength, dbm_strength) - + def setMACAddress(self,address): self.expander.setMACAddress(address) @@ -445,7 +447,7 @@ class NetworkEntry(gtk.Expander): 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 @@ -456,7 +458,7 @@ class NetworkEntry(gtk.Expander): 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') + 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 @@ -510,7 +512,7 @@ class NetworkEntry(gtk.Expander): 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, don't use local dns @@ -629,7 +631,7 @@ class WiredNetworkEntry(NetworkEntry): 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...' @@ -646,7 +648,7 @@ class WiredNetworkEntry(NetworkEntry): 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"))) @@ -654,11 +656,11 @@ class WiredNetworkEntry(NetworkEntry): 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.txtDisconnectScript.set_text(noneToBlankString(wired.GetWiredProperty("disconnectscript"))) - + self.checkboxDefaultProfile.set_active(stringToBoolean(wired.GetWiredProperty("default"))) self.resetStaticCheckboxes() @@ -801,7 +803,7 @@ class WirelessNetworkEntry(NetworkEntry): ending = "%" disp_strength = str(strength) self.lblStrength.set_label(disp_strength + ending) - + def setMACAddress(self,address): self.lblMAC.set_label(str(address)) @@ -819,102 +821,106 @@ class WirelessNetworkEntry(NetworkEntry): def setChannel(self,channel): self.lblChannel.set_label(language['channel'] + ' ' + str(channel)) - + def setMode(self,mode): self.lblMode.set_label(str(mode)) -class appGui: - +class WiredProfileChooser: def __init__(self): - print "starting gui.py..." - # Two possibilities here, one is that the normal GUI should be opened, - # the other is that wired auto-connect is set to prompt the user to - # select a profile. It's kind of hacked together, but it'll do. - if daemon.GetNeedWiredProfileChooser() == True: - daemon.SetNeedWiredProfileChooser(False) - # Profile chooser init block. - # Import and init WiredNetworkEntry to steal some of the - # functions and widgets it uses. - wiredNetEntry = WiredNetworkEntry() - wiredNetEntry.__init__() - - dialog = gtk.Dialog(title = language['wired_network_found'], - flags = gtk.DIALOG_MODAL, - buttons = (gtk.STOCK_CONNECT, 1, - gtk.STOCK_CANCEL, 2)) - dialog.set_has_separator(False) - dialog.set_size_request(400,150) - instructLabel = gtk.Label(language['choose_wired_profile'] + ':\n') - stoppopcheckbox = gtk.CheckButton(language['stop_showing_chooser']) + # Import and init WiredNetworkEntry to steal some of the + # functions and widgets it uses. + wiredNetEntry = WiredNetworkEntry() + wiredNetEntry.__init__() - wiredNetEntry.isFullGUI = False - instructLabel.set_alignment(0,0) - stoppopcheckbox.set_active(False) - - # Remove widgets that were added to the normal - # WiredNetworkEntry so that they can be added to - # the pop-up wizard. - wiredNetEntry.vboxTop.remove(wiredNetEntry.hboxTemp) - wiredNetEntry.vboxTop.remove(wiredNetEntry.profileHelp) - - dialog.vbox.pack_start(instructLabel,fill=False,expand=False) - dialog.vbox.pack_start(wiredNetEntry.profileHelp,fill=False,expand=False) - dialog.vbox.pack_start(wiredNetEntry.hboxTemp,fill=False,expand=False) - dialog.vbox.pack_start(stoppopcheckbox,fill=False,expand=False) - dialog.show_all() - - wiredNetEntry.profileHelp.hide() - if wiredNetEntry.profileList != None: - wiredNetEntry.comboProfileNames.set_active(0) - print "wired profiles found" - else: - print "no wired profiles found" - wiredNetEntry.profileHelp.show() - - response = dialog.run() - if response == 1: - print 'reading profile ', wiredNetEntry.comboProfileNames.get_active_text() - config.ReadWiredNetworkProfile(wiredNetEntry.comboProfileNames.get_active_text()) - wired.ConnectWired() - dialog.destroy() - sys.exit(0) - else: - if stoppopcheckbox.get_active() == True: - # Stops the pop-up from reappearing if cancelled - wired.use_default_profile = 1 - dialog.destroy() - sys.exit(0) + dialog = gtk.Dialog(title = language['wired_network_found'], + flags = gtk.DIALOG_MODAL, + buttons = (gtk.STOCK_CONNECT, 1, + gtk.STOCK_CANCEL, 2)) + dialog.set_has_separator(False) + dialog.set_size_request(400,150) + instructLabel = gtk.Label(language['choose_wired_profile'] + ':\n') + stoppopcheckbox = gtk.CheckButton(language['stop_showing_chooser']) + + wiredNetEntry.isFullGUI = False + instructLabel.set_alignment(0,0) + stoppopcheckbox.set_active(False) + + # Remove widgets that were added to the normal + # WiredNetworkEntry so that they can be added to + # the pop-up wizard. + wiredNetEntry.vboxTop.remove(wiredNetEntry.hboxTemp) + wiredNetEntry.vboxTop.remove(wiredNetEntry.profileHelp) + + dialog.vbox.pack_start(instructLabel,fill=False,expand=False) + dialog.vbox.pack_start(wiredNetEntry.profileHelp,fill=False,expand=False) + dialog.vbox.pack_start(wiredNetEntry.hboxTemp,fill=False,expand=False) + dialog.vbox.pack_start(stoppopcheckbox,fill=False,expand=False) + dialog.show_all() + + wiredNetEntry.profileHelp.hide() + if wiredNetEntry.profileList != None: + wiredNetEntry.comboProfileNames.set_active(0) + print "wired profiles found" else: - #normal init block - gladefile = "data/wicd.glade" - self.windowname = "gtkbench" - self.wTree = gtk.glade.XML(gladefile) + print "no wired profiles found" + wiredNetEntry.profileHelp.show() - 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) + response = dialog.run() + if response == 1: + print 'reading profile ', wiredNetEntry.comboProfileNames.get_active_text() + config.ReadWiredNetworkProfile(wiredNetEntry.comboProfileNames.get_active_text()) + wired.ConnectWired() + dialog.destroy() + else: + if stoppopcheckbox.get_active() == True: + # Stops the pop-up from reappearing if cancelled + wired.use_default_profile = 1 + dialog.destroy() +class appGui: + def __init__(self): + gladefile = "data/wicd.glade" + self.windowname = "gtkbench" + self.wTree = gtk.glade.XML(gladefile) - #set some strings in the GUI - they may be translated + dic = { "on_vpn_connection" : self.on_vpn_connection, + "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) - 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['_network']) - self.wTree.get_widget("progressbar").set_text(language['connecting']) + # Set some strings in the GUI - they may be translated - 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.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['_network']) + self.wTree.get_widget("progressbar").set_text(language['connecting']) + self.window = self.wTree.get_widget("window1") - self.statusID = None + 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) - gobject.timeout_add(300,self.update_statusbar) - gobject.timeout_add(100,self.pulse_progress_bar) + self.statusID = None + + self.vpn_connection_pipe = None + self.is_visible = True + + self.window.connect('delete_event', self.exit) + + gobject.timeout_add(600, 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' + print "Starting the Ad-Hoc Network Creation Process..." dialog = gtk.Dialog(title = language['create_adhoc_network'], flags = gtk.DIALOG_MODAL, buttons=(gtk.STOCK_OK, 1, gtk.STOCK_CANCEL, 2)) @@ -928,10 +934,10 @@ class appGui: 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) + 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 @@ -956,7 +962,7 @@ class appGui: self.useEncryptionCheckbox.get_active(), False) #useICSCheckbox.get_active()) dialog.destroy() - + def toggleEncryptionCheck(self,widget=None): self.keyEntry.set_sensitive(self.useEncryptionCheckbox.get_active()) @@ -971,9 +977,10 @@ class appGui: 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 = 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(465,-1) wiredcheckbox = gtk.CheckButton(language['wired_always_on']) @@ -1001,7 +1008,8 @@ class appGui: wpadriverlabel.set_size_request(75,-1) wpadrivercombo = gtk.combo_box_new_text() wpadrivercombo.set_size_request(50,-1) - wpadrivers = [ "hostap","hermes","madwifi","atmel","wext","ndiswrapper","broadcom","ipw","ralink legacy" ] + wpadrivers = ["hostap","hermes","madwifi","atmel","wext","ndiswrapper", + "broadcom","ipw","ralink legacy"] i = 0 found = False for x in wpadrivers: @@ -1011,19 +1019,18 @@ class appGui: 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 + # 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 + # 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.label.set_size_request(260,-1) + entryWirelessInterface.label.set_size_request(260,-1) entryWiredInterface.label.set_size_request(260,-1) entryWiredAutoMethod = gtk.Label('Wired Autoconnect Setting:') @@ -1034,7 +1041,7 @@ class appGui: 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() @@ -1085,10 +1092,8 @@ class appGui: daemon.SetWPADriver(wpadrivers[wpadrivercombo.get_active()]) wired.SetAlwaysShowWiredInterface(wiredcheckbox.get_active()) wireless.SetAutoReconnect(reconnectcheckbox.get_active()) - daemon.SetDebugMode(debugmodecheckbox.get_active()) daemon.SetSignalDisplayType(displaytypecheckbox.get_active()) - if showlistradiobutton.get_active(): wired.SetWiredAutoConnectMethod(2) elif lastusedradiobutton.get_active(): @@ -1102,8 +1107,8 @@ class appGui: def connect_hidden(self,widget): # Should display a dialog asking - #for the ssid of a hidden network - #and displaying connect/cancel buttons + # 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']) @@ -1115,7 +1120,7 @@ class appGui: if button == 1: answer = dialog.textbox.get_text() dialog.destroy() - self.refresh_networks(None,True,answer) + self.refresh_networks(None, True, answer) else: dialog.destroy() @@ -1129,7 +1134,10 @@ class appGui: wireless.SetForcedDisconnect(True) def pulse_progress_bar(self): - self.wTree.get_widget("progressbar").pulse() + try: + self.wTree.get_widget("progressbar").pulse() + except: + pass return True def update_statusbar(self): @@ -1139,8 +1147,8 @@ class appGui: 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() + wiredConnecting = wired.CheckIfWiredConnecting() + wirelessConnecting = wireless.CheckIfWirelessConnecting() if wirelessConnecting == True or wiredConnecting == True: self.network_list.set_sensitive(False) self.status_area.show_all() @@ -1165,7 +1173,7 @@ class appGui: if strength is not None and dbm_strength is not None: network = str(network) if daemon.GetSignalDisplayType() == 0: - strength = str(strength) + strength = str(strength) else: strength = str(dbm_strength) ip = str(wireless_ip) @@ -1190,7 +1198,7 @@ class appGui: 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: @@ -1228,12 +1236,12 @@ class appGui: label = gtk.Label(language['no_wireless_networks_found']) self.network_list.pack_start(label) label.show() - - def connect(self,widget,event,type,networkid,networkentry): + + 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())) + 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())) @@ -1302,23 +1310,24 @@ class appGui: wired.SetWiredProperty("dns2",'') wired.SetWiredProperty("dns3",'') - #Script Info + # Script Info before_script = networkentry.expander.txtBeforeScript.get_text() after_script = networkentry.expander.txtAfterScript.get_text() disconnect_script = networkentry.expander.txtDisconnectScript.get_text() wired.SetWiredBeforeScript(before_script) wired.SetWiredAfterScript(after_script) wired.SetWiredDisconnectScript(disconnect_script) - + config.SaveWiredNetworkProfile(networkentry.expander.comboProfileNames.get_active_text()) wired.ConnectWired() - def exit(self,widget,event=None): - # Call close_gui so the daemon can send a signal to alert - # the tray that the gui has closed (prevents zombies) - daemon.close_gui() - sys.exit(0) - -#start the app -app = appGui() -gtk.main() + def exit(self, widget=None, event=None): + self.window.hide() + self.is_visible = False + while gtk.events_pending(): + gtk.main_iteration() + return True + + def show_win(self): + self.window.show_all() + self.is_visible = True diff --git a/misc.py b/misc.py index 292b364..1074c29 100644 --- a/misc.py +++ b/misc.py @@ -1,7 +1,7 @@ ''' Misc - miscellaneous functions for wicd ''' -#pretty much useless to anyone else... -#but if it is useful, feel free to use under the terms of the GPL +# Pretty much useless to anyone else... +# But if it is useful, feel free to use under the terms of the GPL # # This is released under the # GNU General Public License @@ -13,15 +13,21 @@ import os import wpath +import locale +import gettext +import time +import sys + if __name__ == '__main__': wpath.chdir(__file__) -def Run(cmd,include_std_error=False): + +def Run(cmd, include_std_error = False): ''' Run a command ''' if not include_std_error: f = os.popen( cmd , "r") return f.read() else: - input,out_err = os.popen4( cmd, 'r') + input, out_err = os.popen4( cmd, 'r') return out_err.read() def IsValidIP(ip): @@ -40,13 +46,17 @@ def PromptToStartDaemon(): print 'You need to start the daemon before using the gui or tray. Use \ the command \'sudo /etc/init.d/wicd start\'.' -def RunRegex(regex,string): +def RunRegex(regex, string): ''' runs a regex search on a string ''' m = regex.search(string) if m: return m.groups()[0] else: return None + +def log(text): + log = self.LogWriter() + log.write(text + "\n") def WriteLine(my_file, text): ''' write a line to a file ''' @@ -117,43 +127,43 @@ def ParseEncryption(network): # Loop through the lines in the template, selecting ones to use for x in template: x = x.strip("\n") - if y>4: - #blah blah replace stuff + if y > 4: + # blah blah replace stuff x = x.replace("$_SCAN","0") for t in network: # Don't bother if z's value is None cause it will cause errors if Noneify(network[t]) != None: - x = x.replace("$_" + str(t).upper(),str(network[t])) + x = x.replace("$_" + str(t).upper(), str(network[t])) z = z + "\n" + x - y+=1 + y += 1 # Write the data to the files - #then chmod them so they can't be read by evil little munchkins + # then chmod them so they can't be read by evil little munchkins fileness = open(wpath.networks + network["bssid"].replace(":", "").lower(), "w") - os.chmod(wpath.networks + network["bssid"].replace(":","").lower(),0600) - os.chown(wpath.networks + network["bssid"].replace(":","").lower(), 0, 0) + os.chmod(wpath.networks + network["bssid"].replace(":", "").lower(), 0600) + os.chown(wpath.networks + network["bssid"].replace(":", "").lower(), 0, 0) # We could do this above, but we'd like to permod (permission mod) # them before we write, so that it can't be read. fileness.write(z) fileness.close() def LoadEncryptionMethods(): - ''' Load encryption methods from configuration files + ''' Load encryption methods from configuration files - Loads all the encryption methods from the template files - in /encryption/templates into a data structure. To be - loaded, the template must be listed in the "active" file. + Loads all the encryption methods from the template files + in /encryption/templates into a data structure. To be + loaded, the template must be listed in the "active" file. - ''' - encryptionTypes = {} - types = open("encryption/templates/active","r") - enctypes = types.readlines() - for x in enctypes: + ''' + encryptionTypes = {} + types = open("encryption/templates/active","r") + enctypes = types.readlines() + for x in enctypes: # Skip some lines, we don't care who the author is/was, etc # we don't care about version either. - x = x.strip("\n") - current = open("encryption/templates/" + x,"r") - line = current.readlines() + x = x.strip("\n") + current = open("encryption/templates/" + x,"r") + line = current.readlines() # Get the length so we know where in the array to add data typeID = len(encryptionTypes) encryptionTypes[typeID] = {} @@ -165,19 +175,19 @@ def LoadEncryptionMethods(): requiredFields = requiredFields.split(" ") index = -1 for current in requiredFields: - # The pretty names will start with an * so we can - #seperate them with that + # The pretty names will start with an * so we can + # seperate them with that if current[0] == "*": # Make underscores spaces - #and remove the * + # and remove the * encryptionTypes[typeID][2][index][0] = current.replace("_", - " ").lstrip("*") + " ").lstrip("*") else: - # Add to the list of things that are required + # Add to the list of things that are required index = len(encryptionTypes[typeID][2]) encryptionTypes[typeID][2][index] = {} encryptionTypes[typeID][2][index][1] = current - return encryptionTypes + return encryptionTypes def noneToString(text): ''' Convert None, "None", or "" to string type "None" @@ -189,3 +199,78 @@ def noneToString(text): return "None" else: return str(text) + +def get_gettext(): + local_path = os.path.realpath(os.path.dirname(sys.argv[0])) + '/translations' + langs = [] + lc, encoding = locale.getdefaultlocale() + if (lc): + langs = [lc] + osLanguage = os.environ.get('LANGUAGE', None) + if (osLanguage): + langs += osLanguage.split(":") + langs += ["en_US"] + lang = gettext.translation('wicd', local_path, languages=langs, + fallback = True) + _ = lang.gettext + return _ + +class LogWriter(): + """ A class to provide timestamped logging. """ + def __init__(self): + self.file = open(wpath.log + 'wicd.log','a') + self.eol = True + self.logging_enabled = True + + + def __del__(self): + self.file.close() + + + def write(self, data): + """ Writes the data to the log with a timestamp. + + This function handles writing of data to a log file. In order to + handle output redirection, we need to be careful with how we + handle the addition of timestamps. In any set of data that is + written, we replace the newlines with a timestamp + new line, + except for newlines that are the final character in data. + + When a newline is the last character in data, we set a flag to + indicate that the next write should have a timestamp prepended + as well, which ensures that the timestamps match the time at + which the data is written, rather than the previous write. + + Keyword arguments: + data -- The string to write to the log. + + """ + #global logging_enabled + data = data.encode('utf-8') + if len(data) <= 0: return + if self.logging_enabled: + if self.eol: + self.file.write(self.get_time() + ' :: ') + self.eol = False + + if data[-1] == '\n': + self.eol = True + data = data[:-1] + + self.file.write( + data.replace('\n', '\n' + self.get_time() + ' :: ')) + if self.eol: self.file.write('\n') + self.file.flush() + + + def get_time(self): + """ Return a string with the current time nicely formatted. + + The format of the returned string is yyyy/mm/dd HH:MM:SS + + """ + x = time.localtime() + return ''.join([ + 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')]) \ No newline at end of file diff --git a/networking.py b/networking.py index 86134b0..e40e689 100644 --- a/networking.py +++ b/networking.py @@ -47,6 +47,7 @@ import thread import misc import wnettools import wpath +import os if __name__ == '__main__': wpath.chdir(__file__) @@ -81,7 +82,6 @@ class ConnectThread(threading.Thread): should_die = False lock = thread.allocate_lock() - def __init__(self, network, wireless, wired, before_script, after_script, disconnect_script, gdns1, gdns2, gdns3): @@ -290,7 +290,8 @@ class Wireless(Controller): 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 -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 ') @@ -298,7 +299,9 @@ class Wireless(Controller): misc.Run('iptables -P FORWARD DROP') misc.Run('iptables -A fw-interfaces -i ' + self.wireless_interface + ' -j ACCEPT') net_ip = '.'.join(ip_parts[0:3]) + '.0' - misc.Run('iptables -t nat -A POSTROUTING -s ' + net_ip + '/255.255.255.0 -o ' + self.wired_interface + ' -j MASQUERADE') + misc.Run('iptables -t nat -A POSTROUTING -s ' + net_ip + \ + '/255.255.255.0 -o ' + self.wired_interface + \ + ' -j MASQUERADE') misc.Run('echo 1 > /proc/sys/net/ipv4/ip_forward') # Enable routing @@ -323,8 +326,6 @@ class Wireless(Controller): wiface.SetAddress('0.0.0.0') wiface.Down() - - class WirelessConnectThread(ConnectThread): """ A thread class to perform the connection to a wireless network. @@ -459,8 +460,7 @@ class WirelessConnectThread(ConnectThread): wiface.StartDHCP() if ((self.network.get('dns1') or self.network.get('dns2') or - self.network.get('dns3')) and - self.network.get('use_static_dns')): + self.network.get('dns3')) and self.network.get('use_static_dns')): self.SetStatus('setting_static_dns') if self.network.get('use_global_dns'): wnettools.SetDNS(misc.Noneify(self.global_dns_1), @@ -469,11 +469,11 @@ class WirelessConnectThread(ConnectThread): else: wnettools.SetDNS(self.network.get('dns1'), self.network.get('dns2'), self.network.get('dns3')) - - #save as last used profile + + # Save as last used profile print 'Saving last used profile' config.UnsetLastUsedDefault() # Makes sure there is only one last used profile at a time - self.network.SetWiredProperty("lastused",True) + self.network.SetWiredProperty("lastused", True) config.SaveWiredNetworkProfile(self.profilename) #execute post-connection script if necessary @@ -596,7 +596,7 @@ class WiredConnectThread(ConnectThread): # Execute pre-connection script if necessary if self.before_script != '' and self.before_script != None: - print 'executing pre-connectiong script' + print 'executing pre-connection script' misc.ExecuteScript(self.before_script) # Put it down @@ -645,8 +645,7 @@ class WiredConnectThread(ConnectThread): liface.StartDHCP() if ((self.network.get('dns1') or self.network.get('dns2') or - self.network.get('dns3')) and - self.network.get('use_static_dns')): + self.network.get('dns3')) and self.network.get('use_static_dns')): self.SetStatus('setting_static_dns') if self.network.get('use_global_dns'): wnettools.SetDNS(misc.Noneify(self.global_dns_1), diff --git a/wicd.py b/wicd.py new file mode 100755 index 0000000..70b94f7 --- /dev/null +++ b/wicd.py @@ -0,0 +1,501 @@ +#!/usr/bin/env python + +""" wicd - wireless connection daemon frontend implementation + +This module implements a usermode frontend for wicd. It updates connection +information, provides an (optional) tray icon, and allows for launching of +the wicd GUI and Wired Profile Chooser. + +class TrayIcon() -- Parent class of TrayIconGUI and IconConnectionInfo. + class TrayConnectionInfo() -- Child class of TrayIcon which provides + and updates connection status. + class TrayIconGUI() -- Child class of TrayIcon which implements the tray. + icon itself. Parent class of EdgyTrayIconGUI and DapperTrayIconGUI. + class EdgyTrayIconGUI() -- Implements the tray icon using a gtk.StatusIcon. + class DapperTrayIconGUI() -- Implements the tray icon using egg.trayicon. +def usage() -- Prints usage information. +def main() -- Runs the wicd frontend main loop. + +""" + +# +# Copyright (C) 2007 Adam Blackburn +# Copyright (C) 2007 Dan O'Reilly +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License Version 2 as +# published by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# + +import os +import sys +import gtk +import gobject +import dbus +import dbus.service +import locale +import gettext +import signal +import getopt + +# Import egg.trayicon if we're using an older gtk version +if not (gtk.gtk_version[0] >= 2 and gtk.gtk_version[1] >= 10): + import egg.trayicon + USE_EGG = True +else: + USE_EGG = False + +if getattr(dbus, 'version', (0, 0, 0)) >= (0, 41, 0): + import dbus.glib + +# Wicd specific imports +import wpath +import misc +import gui + +if sys.platform == 'linux2': + # Set process name. Only works on Linux >= 2.1.57. + try: + import dl + libc = dl.open('/lib/libc.so.6') + libc.call('prctl', 15, 'wicd\0', 0, 0, 0) # 15 is PR_SET_NAME + except: + pass + +if __name__ == '__main__': + wpath.chdir(__file__) + +log = misc.LogWriter() +bus = dbus.SystemBus() + +# Connect to the daemon +try: + log.write('Attempting to connect daemon...') + proxy_obj = bus.get_object('org.wicd.daemon', '/org/wicd/daemon') + log.write('Success.') +except: + log.write('Daemon not running...') + misc.PromptToStartDaemon() + +daemon = dbus.Interface(proxy_obj, 'org.wicd.daemon') +wireless = dbus.Interface(proxy_obj, 'org.wicd.daemon.wireless') +wired = dbus.Interface(proxy_obj, 'org.wicd.daemon.wired') +config = dbus.Interface(proxy_obj, 'org.wicd.daemon.config') + +_ = misc.get_gettext() +language = {} +language['connected_to_wireless'] = _('Connected to $A at $B (IP: $C)') +language['connected_to_wired'] = _('Connected to wired network (IP: $A)') +language['not_connected'] = _('Not connected') +language['connecting'] = _('Connecting...') + +class TrayIcon(): + def __init__(self, use_tray): + if USE_EGG: + self.tr = self.DapperIconGUI(use_tray) + else: + self.tr = self.EdgyTrayIconGUI(use_tray) + self.icon_info = self.TrayConnectionInfo(self.tr) + + class TrayConnectionInfo(): + ''' class for updating the tray icon status ''' + def __init__(self, tr): + ''' initialize variables needed for the icon status methods ''' + self.last_strength = -2 + self.still_wired = False + self.network = '' + self.tried_reconnect = False + self.connection_lost_counter = 0 + self.tr = tr + + def wired_profile_chooser(self): + ''' Launched the wired profile chooser ''' + daemon.SetNeedWiredProfileChooser(False) + chooser = gui.WiredProfileChooser() + + def check_for_wired_connection(self, wired_ip): + ''' Checks for an active wired connection + + Checks for and updates the tray icon for an active wired connection + Returns True if wired connection is active, false if inactive. + + ''' + if wired_ip is not None and wired.CheckPluggedIn(): + # Only set image/tooltip if it hasn't been set already + # and the wire is actually plugged in. + if not self.still_wired: + daemon.SetCurrentInterface(daemon.GetWiredInterface()) + self.tr.set_from_file("images/wired.png") + self.tr.set_tooltip(language['connected_to_wired'].replace('$A', + wired_ip)) + self.still_wired = True + return True + return False + + def check_for_wireless_connection(self, wireless_ip): + ''' Checks for an active wireless connection + + Checks for and updates the tray icon for an active wireless connection + Returns True if wireless connection is active, False otherwise. + + ''' + if wireless.GetWirelessIP() is None: + return False + + # Reset this, just in case + self.tried_reconnect = False + + # Try getting signal strength, default to 0 if something goes wrong. + try: + if daemon.GetSignalDisplayType() == 0: + wireless_signal = int(wireless.GetCurrentSignalStrength()) + else: + wireless_signal = int(wireless.GetCurrentDBMStrength()) + except: + wireless_signal = 0 + + if wireless_signal == 0: + # If we have no signal, increment connection loss counter. + # If we haven't gotten any signal 4 runs in a row (12 seconds), + # try to reconnect. + self.connection_lost_counter += 1 + print self.connection_lost_counter + if self.connection_lost_counter > 4: + self.connection_lost_counter = 0 + self.auto_reconnect() + return False + + # Only update if the signal strength has changed because doing I/O + # calls is expensive, and the icon flickers + if (wireless_signal != self.last_strength or + self.network != wireless.GetCurrentNetwork()): + self.last_strength = wireless_signal + # Set the string to '' so that when it is put in "high-signal" + + # lock + ".png", there will be nothing + lock = '' + + # cur_net_id needs to be checked because a negative value + # will break the tray when passed to GetWirelessProperty. + cur_net_id = wireless.GetCurrentNetworkID() + + if cur_net_id > -1 and \ + wireless.GetWirelessProperty(cur_net_id, "encryption"): + # Set the string to '-lock' so that it will display the + # lock picture + lock = '-lock' + # Update the tooltip and icon picture + self.network = str(wireless.GetCurrentNetwork()) + daemon.SetCurrentInterface(daemon.GetWirelessInterface()) + str_signal = daemon.FormatSignalForPrinting(str(wireless_signal)) + self.tr.set_tooltip(language['connected_to_wireless'] + .replace('$A', self.network) + .replace('$B', str_signal) + .replace('$C', str(wireless_ip))) + self.set_signal_image(wireless_signal, lock) + return True + + def update_tray_icon(self): + ''' Updates the tray icon and current connection status ''' + + # Disable logging if debugging isn't on to prevent log spam + if not daemon.GetDebugMode(): + config.DisableLogging() + + # First check for an active wired network, then for an + # active wireless network. If neither is found, change + # icon to reflect that and run auto_reconnect() + wired_ip = wired.GetWiredIP() + wired_found = self.check_for_wired_connection(wired_ip) + if not wired_found: + self.still_wired = False # We're not wired any more + wireless_ip = wireless.GetWirelessIP() + wireless_found = self.check_for_wireless_connection(wireless_ip) + if not wireless_found: # No connection at all + self.tr.set_from_file("images/no-signal.png") + if daemon.CheckIfConnecting(): + self.tr.set_tooltip(language['connecting']) + else: + self.tr.set_tooltip(language['not_connected']) + daemon.SetCurrentInterface('') + self.auto_reconnect() + + if not daemon.GetDebugMode(): + config.EnableLogging() + + return True + + def set_signal_image(self, wireless_signal, lock): + ''' Sets the tray icon picture for an active wireless connection ''' + if wireless_signal == 0: + # We handle a signal of 0 the same regardless of dBm or % + # signal strength. Set the image based on connection loss + # counter, and then return so the counter isn't reset. + if self.connection_lost_counter < 4: + self.tr.set_from_file(wpath.images + "bad-signal" + lock + ".png") + else: + self.tr.set_from_file(wpath.images + "no-signal.png") + return + elif daemon.GetSignalDisplayType() == 0: + if wireless_signal > 75: + self.tr.set_from_file(wpath.images + "high-signal" + lock + ".png") + elif wireless_signal > 50: + self.tr.set_from_file(wpath.images + "good-signal" + lock + ".png") + elif wireless_signal > 25: + self.tr.set_from_file(wpath.images + "low-signal" + lock + ".png") + elif wireless_signal > 0: + self.tr.set_from_file(wpath.images + "bad-signal" + lock + ".png") + else: + if wireless_signal >= -60: + self.tr.set_from_file(wpath.images + "high-signal" + lock + ".png") + elif wireless_signal >= -70: + self.tr.set_from_file(wpath.images + "good-signal" + lock + ".png") + elif wireless_signal >= -80: + self.tr.set_from_file(wpath.images + "low-signal" + lock + ".png") + else: + self.tr.set_from_file(wpath.images + "bad-signal" + lock + ".png") + # Since we have a signal, we should reset + # the connection loss counter. + self.connection_lost_counter = 0 + + def auto_reconnect(self): + ''' Automatically reconnects to a network if needed + + If automatic reconnection is turned on, this method will + attempt to first reconnect to the last used wireless network, and + should that fail will simply run AutoConnect() + + ''' + if wireless.GetAutoReconnect() and not daemon.CheckIfConnecting() and \ + not wireless.GetForcedDisconnect(): + print 'Starting automatic reconnect process' + # First try connecting through ethernet + if wired.CheckPluggedIn(): + print "Wired connection available, trying to connect..." + daemon.AutoConnect(False) + return + + # Next try the last wireless network we were connected to + cur_net_id = wireless.GetCurrentNetworkID() + if cur_net_id > -1: # Needs to be a valid network + if not self.tried_reconnect: + print 'Trying to reconnect to last used wireless network' + wireless.ConnectWireless(cur_net_id) + self.tried_reconnect = True + elif wireless.CheckIfWirelessConnecting() == False: + print "Couldn't reconnect to last used network, \ + scanning for an autoconnect network..." + daemon.AutoConnect(True) + else: + daemon.AutoConnect(True) + + class TrayIconGUI(): + def __init__(self): + menu = ''' + + + + + + + + + + + ''' + actions = [ + ('Menu', None, 'Menu'), + ('Connect', gtk.STOCK_CONNECT, '_Connect...', None, + 'Connect to network', self.on_preferences), + ('About', gtk.STOCK_ABOUT, '_About...', None, + 'About wicd-tray-icon', self.on_about), + ('Quit',gtk.STOCK_QUIT,'_Quit',None,'Quit wicd-tray-icon', + self.on_quit), + ] + actg = gtk.ActionGroup('Actions') + actg.add_actions(actions) + self.manager = gtk.UIManager() + self.manager.insert_action_group(actg, 0) + self.manager.add_ui_from_string(menu) + self.menu = self.manager.get_widget('/Menubar/Menu/About').props.parent + self.gui_win = None + + def on_activate(self, data=None): + ''' Opens the wicd GUI ''' + self.toggle_wicd_gui() + + def on_quit(self, widget=None): + ''' Closes the tray icon ''' + sys.exit(0) + + def on_preferences(self, data=None): + ''' Opens the wicd GUI ''' + self.toggle_wicd_gui() + + def on_about(self, data = None): + ''' Opens the About Dialog ''' + dialog = gtk.AboutDialog() + dialog.set_name('wicd tray icon') + dialog.set_version('0.4') + dialog.set_comments('an icon that shows your network connectivity') + dialog.set_website('http://wicd.sourceforge.net') + dialog.run() + dialog.destroy() + + def set_from_file(self, path = None): + ''' Sets a new tray icon picture ''' + if not self.use_tray: return + if path != self.current_icon_path: + self.current_icon_path = path + gtk.StatusIcon.set_from_file(self, path) + + def toggle_wicd_gui(self): + ''' Toggles the wicd GUI ''' + if self.gui_win == None: + self.gui_win = gui.appGui() + elif self.gui_win.is_active == False: + self.gui_win.show_win() + else: + self.gui_win.exit() + return True + + + class DapperTrayIconGUI(TrayIconGUI): + def __init__(self, use_tray=True): + ''' initializes the tray icon ''' + TrayIcon.TrayIconGUI.__init__() + self.use_tray = use_tray + if not use_tray: + self.toggle_wicd_gui() + return + + self.tooltip = gtk.Tooltips() + self.eb = gtk.EventBox() + self.tray = egg.trayicon.TrayIcon("WicdTrayIcon") + self.pic = gtk.Image() + self.tooltip.set_tip(self.eb, "Initializing wicd...") + self.pic.set_from_file("images/no-signal.png") + + self.eb.connect('button_press_event', tray_display.tray_clicked) + self.eb.add(pic) + self.tray.add(eb) + self.tray.show_all() + + def tray_clicked(self, widget, event): + ''' Handles tray mouse click events ''' + if event.button == 1: + self.open_wicd_gui() + if event.button == 3: + self.menu.popup(None, None, None, event.button, event.time) + + def set_from_file(str): + ''' Calls set_from_file on the gtk.Image for the tray icon ''' + if not self.use_tray: return + self.pic.set_from_file(str) + + def set_tooltip(str): + ''' + Sets the tooltip for the gtk.ToolTips associated with this + tray icon. + ''' + if not self.use_tray: return + self.tooltip.set_tip(self.eb, str) + + class EdgyTrayIconGUI(gtk.StatusIcon, TrayIconGUI): + ''' Class for creating the wicd tray icon ''' + def __init__(self, use_tray=True): + TrayIcon.TrayIconGUI.__init__(self) + self.use_tray = use_tray + if not use_tray: + self.toggle_wicd_gui() + return + + gtk.StatusIcon.__init__(self) + + self.current_icon_path = '' + wireless.SetForcedDisconnect(False) + self.set_visible(True) + self.connect('activate', self.on_activate) + self.connect('popup-menu', self.on_popup_menu) + self.set_from_file("images/no-signal.png") + self.set_tooltip("Initializing wicd...") + + def on_popup_menu(self, status, button, time): + ''' Opens the right click menu for the tray icon ''' + self.menu.popup(None, None, None, button, time) + + def set_from_file(self, path = None): + ''' Sets a new tray icon picture ''' + if not self.use_tray: return + if path != self.current_icon_path: + self.current_icon_path = path + gtk.StatusIcon.set_from_file(self, path) + + +def usage(): + print """ +wicd 1.40 +wireless (and wired) connection daemon front-end. + +Arguments: +\t-n\t--no-tray\tRun wicd without the tray icon. +\t-h\t--help\t\tPrint this help. +""" + +def main(argv): + """ The main frontend program. + + Keyword arguments: + argv -- The arguments passed to the script. + + """ + use_tray = True + + try: + opts, args = getopt.getopt(sys.argv[1:], 'nh', + ['help', 'no-tray']) + except getopt.GetoptError: + # Print help information and exit + usage() + sys.exit(2) + + for o, a in opts: + if o in ('-h', '--help'): + usage() + sys.exit() + if o in ('-n', '--no-tray'): + use_tray = False + + # Redirect stderr and stdout for logging purposes + sys.stderr = log + sys.stdout = log + + # Set up the tray icon GUI and backend + tray_icon = TrayIcon(use_tray) + + # Check to see if wired profile chooser was called before icon + # was launched (typically happens on startup or daemon restart) + if daemon.GetNeedWiredProfileChooser(): + daemon.SetNeedWiredProfileChooser(False) + tray_icon.icon_info.wired_profile_chooser() + + # Add dbus signal listener for wired_profile_chooser + bus.add_signal_receiver(tray_icon.icon_info.wired_profile_chooser, + 'LaunchChooser', 'org.wicd.daemon') + + # Run update_tray_icon every 3000ms (3 seconds) + gobject.timeout_add(3000, tray_icon.icon_info.update_tray_icon) + + # Enter the main loop + mainloop = gobject.MainLoop() + mainloop.run() + +if __name__ == '__main__': + main(sys.argv) \ No newline at end of file diff --git a/wnettools.py b/wnettools.py index 6763d06..1c10be5 100644 --- a/wnettools.py +++ b/wnettools.py @@ -260,9 +260,9 @@ class WirelessInterface(Interface): results = misc.Run(cmd) # Split the networks apart, using Cell as our split point - # this way we can look at only one network at a time + # this way we can look at only one network at a time. networks = results.split( ' Cell ' ) - + # Get available network info from iwpriv get_site_survey # if we're using a ralink card (needed to get encryption info) if self.wpa_driver == 'ralink legacy': @@ -294,7 +294,7 @@ class WirelessInterface(Interface): The channel number, or None if not found. """ - if freq == '2.412 GHz': return 1 + if freq == '2.412 GHz': return 1 elif freq == '2.417 GHz': return 2 elif freq == '2.422 GHz': return 3 elif freq == '2.427 GHz': return 4 @@ -314,11 +314,11 @@ class WirelessInterface(Interface): def _GetRalinkInfo(self): """ Get a network info list used for ralink drivers - + Calls iwpriv get_site_survey, which on some ralink cards will return encryption and signal strength info for wireless networks in the area. - + """ iwpriv = misc.Run('iwpriv ' + self.iface + ' get_site_survey') lines = iwpriv.splitlines() @@ -334,7 +334,7 @@ class WirelessInterface(Interface): for ralink cards. Returns: - + A dictionary containing the cell networks properties. """ @@ -399,21 +399,21 @@ class WirelessInterface(Interface): ap['strength'] = -1 return ap - + def _ParseRalinkAccessPoint(self, ap, ralink_info, cell): """ Parse encryption and signal strength info for ralink cards - + Keyword arguments: ap -- array containing info about the current access point ralink_info -- string containing available network info cell -- string containing cell information - + Returns: Updated array containing info about the current access point - + """ lines = ralink_info - for x in lines: # Iterate through all networks found + for x in lines: # Iterate through all networks found info = x.split() # Make sure we read in a valid entry if len(info) < 5 or info == None or info == '': @@ -532,7 +532,7 @@ class WirelessInterface(Interface): if len(info) < 5: break if info[2] == network.get('essid'): - if info[5] == 'WEP' or (info[5] == 'OPEN' and info[4] == 'WEP'): # Needs to be tested + if info[5] == 'WEP' or (info[5] == 'OPEN' and info[4] == 'WEP'): print 'Setting up WEP' cmd = 'iwconfig ' + self.iface + ' key ' + network.get('key') if self.verbose: print cmd @@ -610,5 +610,7 @@ class WirelessInterface(Interface): cmd = 'iwconfig ' + self.iface if self.verbose: print cmd output = misc.Run(cmd) - return misc.RunRegex(re.compile('.*ESSID:"(.*?)"',re.DOTALL | re.I | re.M | re.S), output) - + network = misc.RunRegex(re.compile('.*ESSID:"(.*?)"',re.DOTALL | re.I | re.M | re.S), output) + if network is not None: + network = network.encode('utf-8') + return network