1
0
mirror of https://github.com/gryf/wicd.git synced 2025-12-28 17:32:36 +01:00

Fix some issues by pylint

This commit is contained in:
David Paleino
2012-11-17 01:07:08 +01:00
parent b386b37db7
commit b5a4d70ab8
19 changed files with 729 additions and 448 deletions

View File

@@ -0,0 +1 @@
""" WICD core module. """

View File

@@ -36,14 +36,16 @@ try:
daemon = dbusmanager.get_interface('daemon')
wireless = dbusmanager.get_interface('wireless')
except Exception, e:
print>>sys.stderr, "Exception caught: %s" % str(e)
print>>sys.stderr, 'Could not connect to daemon.'
print >> sys.stderr, "Exception caught: %s" % str(e)
print >> sys.stderr, 'Could not connect to daemon.'
sys.exit(1)
def handler(*args):
""" No-op handler. """
pass
def error_handler(*args):
print>>sys.stderr, 'Async error autoconnecting.'
""" Error handler. """
print >> sys.stderr, 'Async error autoconnecting.'
sys.exit(3)
if __name__ == '__main__':
@@ -54,6 +56,6 @@ if __name__ == '__main__':
daemon.AutoConnect(True, reply_handler=handler,
error_handler=error_handler)
except Exception, e:
print>>sys.stderr, "Exception caught: %s" % str(e)
print>>sys.stderr, 'Error autoconnecting.'
print >> sys.stderr, "Exception caught: %s" % str(e)
print >> sys.stderr, 'Error autoconnecting.'
sys.exit(2)

View File

@@ -30,6 +30,7 @@ import os
import wicd.wpath as wpath
def fail(backend_name, reason):
""" Helper to warn the user about failure in loading backend. """
print "Failed to load backend %s: %s" % (backend_name, reason)
return True
@@ -40,7 +41,7 @@ class BackendManager(object):
""" Initialize the backend manager. """
self.backend_dir = wpath.backends
self.__loaded_backend = None
def _valid_backend_file(self, be_file):
""" Make sure the backend file is valid. """
return (os.path.exists(be_file) and
@@ -115,7 +116,8 @@ class BackendManager(object):
"""
backend = self._load_backend(backend_name)
if not backend : return None
if not backend:
return None
failed = self._validate_backend(backend, backend_name)
if failed:

View File

@@ -0,0 +1 @@
""" Backends module. """

View File

@@ -155,7 +155,7 @@ class Interface(BaseInterface):
return socket.inet_ntoa(raw_ip[20:24])
@neediface(False)
def IsUp(self):
def IsUp(self, ifconfig=None):
""" Determines if the interface is up.
Returns:
@@ -357,7 +357,8 @@ class WirelessInterface(Interface, BaseWirelessInterface):
print "Couldn't open ctrl_interface: %s" % e
return None
else:
print "Couldn't find a wpa_supplicant ctrl_interface for iface %s" % self.iface
print "Couldn't find a wpa_supplicant ctrl_interface for iface %s" \
% self.iface
return None
def ValidateAuthentication(self, auth_time):
@@ -402,7 +403,8 @@ class WirelessInterface(Interface, BaseWirelessInterface):
return False
if self.verbose:
print 'wpa_supplicant ctrl_interface status query is %s' % str(status)
print 'wpa_supplicant ctrl_interface status query is %s' \
% str(status)
try:
[result] = [l for l in status if l.startswith("wpa_state=")]
@@ -456,7 +458,8 @@ class WirelessInterface(Interface, BaseWirelessInterface):
print 'Setting up WEP'
cmd = ''.join(['iwconfig ', self.iface, ' key ',
network.get('key')])
if self.verbose: print cmd
if self.verbose:
print cmd
misc.Run(cmd)
else:
if info[5] == 'SHARED' and info[4] == 'WEP':
@@ -488,7 +491,8 @@ class WirelessInterface(Interface, BaseWirelessInterface):
for cmd in cmd_list:
cmd = 'iwpriv ' + self.iface + ' '
if self.verbose: print cmd
if self.verbose:
print cmd
misc.Run(cmd)
@neediface("")

View File

@@ -35,6 +35,7 @@ from wicd.misc import Noneify, to_unicode
from dbus import Int32
def sanitize_config_file(path):
""" Remove invalid lines from config file. """
conf = open(path)
newconf = ''
for line in conf:
@@ -56,7 +57,7 @@ class ConfigManager(RawConfigParser):
sanitize_config_file(path)
try:
self.read(path)
except ParsingError, e:
except ParsingError:
self.write()
try:
self.read(path)
@@ -121,15 +122,18 @@ class ConfigManager(RawConfigParser):
if default:
if self.debug:
# mask out sensitive information
if option in ['apsk', 'password', 'identity', 'private_key', \
'private_key_passwd', 'key', 'passphrase']:
print ''.join(['found ', option, ' in configuration *****'])
if option in ['apsk', 'password', 'identity', \
'private_key', 'private_key_passwd', \
'key', 'passphrase']:
print ''.join(['found ', option, \
' in configuration *****'])
else:
print ''.join(['found ', option, ' in configuration ',
print ''.join(['found ', option, ' in configuration ',
str(ret)])
else:
if default != "__None__":
print 'did not find %s in configuration, setting default %s' % (option, str(default))
print 'did not find %s in configuration, setting default %s' \
% (option, str(default))
self.set(section, option, str(default), write=True)
ret = default
else:
@@ -196,7 +200,8 @@ class ConfigManager(RawConfigParser):
p = RawConfigParser()
p.readfp(codecs.open(fname, 'r', 'utf-8'))
for section_name in p.sections():
# New files override old, so remove first to avoid DuplicateSectionError.
# New files override old, so remove first to avoid
# DuplicateSectionError.
self.remove_section(section_name)
self.add_section(section_name)
for (name, value) in p.items(section_name):
@@ -206,6 +211,7 @@ class ConfigManager(RawConfigParser):
def _copy_section(self, name):
""" Copy whole section from config file. """
p = ConfigManager("", self.debug, self.mrk_ws)
p.add_section(name)
for (iname, value) in self.items(name):
@@ -215,7 +221,7 @@ class ConfigManager(RawConfigParser):
p.remove_option(name, '_filename_')
return p
def write(self):
def write(self, fp):
""" Writes the loaded config file to disk. """
in_this_file = []
for sname in sorted(self.sections()):

View File

@@ -33,21 +33,27 @@ else:
DBUS_MANAGER = None
def get_dbus_ifaces():
""" Return available DBus interfaces. """
return DBUS_MANAGER.get_dbus_ifaces()
def get_interface(iface):
""" Return specified interface. """
return DBUS_MANAGER.get_interface(iface)
def get_bus():
""" Return the loaded System Bus. """
return DBUS_MANAGER.get_bus()
def set_mainloop():
return DBUS_MANAGER.set_mainloop()
def set_mainloop(loop):
""" Set DBus main loop. """
return DBUS_MANAGER.set_mainloop(loop)
def connect_to_dbus():
""" Connect to DBus. """
return DBUS_MANAGER.connect_to_dbus()
def threads_init():
""" Init GLib threads. """
dbus.mainloop.glib.threads_init()
@@ -59,12 +65,14 @@ class DBusManager(object):
def get_dbus_ifaces(self):
""" Returns a dict of dbus interfaces. """
if not self._dbus_ifaces: connect_to_dbus()
if not self._dbus_ifaces:
connect_to_dbus()
return self._dbus_ifaces
def get_interface(self, iface):
""" Returns a DBus Interface. """
if not self._dbus_ifaces: connect_to_dbus()
if not self._dbus_ifaces:
connect_to_dbus()
return self._dbus_ifaces[iface]
def get_bus(self):
@@ -72,6 +80,7 @@ class DBusManager(object):
return self._bus
def set_mainloop(self, loop):
""" Set DBus main loop. """
dbus.set_default_main_loop(loop)
def connect_to_dbus(self):
@@ -90,4 +99,4 @@ class DBusManager(object):
self._dbus_ifaces = {"daemon" : daemon, "wireless" : wireless,
"wired" : wired}
DBUS_MANAGER = DBusManager()
DBUS_MANAGER = DBusManager()

View File

@@ -26,6 +26,7 @@ import os
import time
class SizeError(IOError):
""" Custom error class. """
pass
class LogFile(file):
@@ -48,7 +49,8 @@ class LogFile(file):
self.written += len(data)
data = data.decode('utf-8').encode('utf-8')
if len(data) <= 0: return
if len(data) <= 0:
return
if self.eol:
super(LogFile, self).write(self.get_time() + ' :: ')
self.eol = False
@@ -79,6 +81,7 @@ class LogFile(file):
str(x[4]).rjust(2, '0'), ':', str(x[5]).rjust(2, '0')])
def rotate(self):
""" Rotate logfile. """
return rotate(self)
def note(self, text):
@@ -108,21 +111,25 @@ class ManagedLog(object):
self._lf.maxsize, self.maxsave)
def write(self, data):
""" Write logfile. """
try:
self._lf.write(data)
except SizeError:
self._lf = rotate(self._lf, self.maxsave)
def note(self, data):
""" Write a note to the logfile. """
try:
self._lf.note(data)
except SizeError:
self._lf = rotate(self._lf, self.maxsave)
def written(self):
""" Return whether the logfile was written. """
return self._lf.written
def rotate(self):
def rotate(self):
""" Rotate logfile. """
self._lf = rotate(self._lf, self.maxsave)
# auto-delegate remaining methods (but you should not read or seek an open
@@ -133,7 +140,9 @@ class ManagedLog(object):
# useful for logged stdout for daemon processes
class ManagedStdio(ManagedLog):
""" Manage stdout/stderr. """
def write(self, data):
""" Write logfile to disk. """
try:
self._lf.write(data)
except SizeError:
@@ -147,6 +156,7 @@ class ManagedStdio(ManagedLog):
def rotate(fileobj, maxsave=9):
""" Rotate fileobj. """
name = fileobj.name
mode = fileobj.mode
maxsize = fileobj.maxsize
@@ -157,6 +167,7 @@ def rotate(fileobj, maxsave=9):
# assumes basename logfile is closed.
def shiftlogs(basename, maxsave):
""" Shift logfiles. """
topname = "%s.%d" % (basename, maxsave)
if os.path.isfile(topname):
os.unlink(topname)
@@ -175,9 +186,11 @@ def shiftlogs(basename, maxsave):
def open(name, maxsize=360000, maxsave=9):
""" Open logfile. """
return ManagedLog(name, maxsize, maxsave)
def writelog(logobj, data):
""" Write logfile. """
try:
logobj.write(data)
except SizeError:

View File

@@ -84,7 +84,8 @@ _sudo_dict = {
_status_dict = {
'aborted': _('Connection Cancelled'),
'association_failed': _('Connection failed: Could not contact the wireless access point.'),
'association_failed': _('Connection failed: Could not contact the ' + \
'wireless access point.'),
'bad_pass': _('Connection Failed: Bad password'),
'configuring_interface': _('Configuring wireless interface...'),
'dhcp_failed': _('Connection Failed: Unable to Get IP Address'),
@@ -107,6 +108,7 @@ _status_dict = {
}
class WicdError(Exception):
""" Custom Exception type. """
pass
@@ -179,7 +181,8 @@ def LaunchAndWait(cmd):
def IsValidIP(ip):
""" Make sure an entered IP is valid. """
if not ip: return False
if not ip:
return False
if not IsValidIPv4(ip):
if not IsValidIPv6(ip):
@@ -218,9 +221,9 @@ def PromptToStartDaemon():
os.spawnvpe(os.P_WAIT, sudo_prog, sudo_args, os.environ)
return True
def RunRegex(regex, string):
def RunRegex(regex, s):
""" runs a regex search on a string """
m = regex.search(string)
m = regex.search(s)
if m:
return m.groups()[0]
else:
@@ -271,12 +274,13 @@ def to_bool(var):
var = bool(var)
return var
def Noneify(variable, to_bool=True):
def Noneify(variable, convert_to_bool=True):
""" Convert string types to either None or booleans"""
#set string Nones to real Nones
if variable in ("None", "", None):
return None
if to_bool:
if convert_to_bool:
# FIXME: should instead use above to_bool()?
if variable in ("False", "0"):
return False
if variable in ("True", "1"):
@@ -415,8 +419,10 @@ def _parse_enc_template(enctype):
print "Invalid 'optional' line found in template %s" % enctype
continue
elif line.startswith("protected"):
cur_type["protected"] = __parse_field_ent(parse_ent(line, "protected"),
field_type="protected")
cur_type["protected"] = __parse_field_ent(
parse_ent(line, "protected"),
field_type="protected"
)
if not cur_type["protected"]:
# An error occured parsing the protected line.
print "Invalid 'protected' line found in template %s" % enctype
@@ -530,7 +536,8 @@ def detect_desktop_environment():
def get_sudo_cmd(msg, prog_num=0):
""" Returns a graphical sudo command for generic use. """
sudo_prog = choose_sudo_prog(prog_num)
if not sudo_prog: return None
if not sudo_prog:
return None
if re.search("(ktsuss|gksu|gksudo)$", sudo_prog):
msg_flag = "-m"
else:
@@ -590,6 +597,8 @@ def stringToNone(text):
return str(text)
def checkboxTextboxToggle(checkbox, textboxes):
""" Manage {de,}activation of textboxes depending on checkboxes. """
# FIXME: should be moved to UI-specific files?
for textbox in textboxes:
textbox.set_sensitive(checkbox.get_active())
@@ -613,7 +622,8 @@ def timeout_add(time, func, milli=False):
if hasattr(gobject, "timeout_add_seconds") and not milli:
return gobject.timeout_add_seconds(time, func)
else:
if not milli: time = time * 1000
if not milli:
time = time * 1000
return gobject.timeout_add(time, func)
def izip_longest(*args, **kwds):

View File

@@ -47,6 +47,9 @@ wireless = dbus_dict["wireless"]
mainloop = None
def diewithdbus(func):
"""
Decorator catching DBus exceptions, making wicd quit.
"""
def wrapper(self, *__args, **__kargs):
try:
ret = func(self, *__args, **__kargs)
@@ -86,6 +89,7 @@ class ConnectionStatus(object):
self.trigger_reconnect = False
self.__lost_dbus_count = 0
self._to_time = daemon.GetBackendUpdateInterval()
self.update_callback = None
self.add_poll_callback()
bus = dbusmanager.get_bus()
@@ -275,14 +279,14 @@ class ConnectionStatus(object):
info = ["wired"]
else:
info = ["wireless",
misc.noneToBlankString(wireless.GetCurrentNetwork(iwconfig))]
misc.noneToBlankString(wireless.GetCurrentNetwork(iwconfig))]
elif state == misc.WIRELESS:
self.reconnect_tries = 0
info = [str(wifi_ip),
misc.noneToBlankString(wireless.GetCurrentNetwork(iwconfig)),
str(self._get_printable_sig_strength()),
str(wireless.GetCurrentNetworkID(iwconfig)),
misc.noneToBlankString(wireless.GetCurrentBitrate(iwconfig))]
misc.noneToBlankString(wireless.GetCurrentNetwork(iwconfig)),
str(self._get_printable_sig_strength()),
str(wireless.GetCurrentNetworkID(iwconfig)),
misc.noneToBlankString(wireless.GetCurrentBitrate(iwconfig))]
elif state == misc.WIRED:
self.reconnect_tries = 0
info = [str(wired_ip)]
@@ -310,16 +314,18 @@ class ConnectionStatus(object):
""" Get the correct signal strength format. """
try:
if daemon.GetSignalDisplayType() == 0:
wifi_signal = int(wireless.GetCurrentSignalStrength(self.iwconfig))
signal = wireless.GetCurrentSignalStrength(self.iwconfig)
wifi_signal = int(signal)
else:
signal = wireless.GetCurrentDBMStrength(self.iwconfig)
if always_positive:
# because dBm is negative, add 99 to the signal. This way, if
# the signal drops below -99, wifi_signal will == 0, and
# because dBm is negative, add 99 to the signal. This way,
# if the signal drops below -99, wifi_signal will == 0, and
# an automatic reconnect will be triggered
# this is only used in check_for_wireless_connection
wifi_signal = 99 + int(wireless.GetCurrentDBMStrength(self.iwconfig))
wifi_signal = 99 + int(signal)
else:
wifi_signal = int(wireless.GetCurrentDBMStrength(self.iwconfig))
wifi_signal = int(signal)
except TypeError:
wifi_signal = 0

View File

@@ -158,25 +158,34 @@ class Controller(object):
self.driver = None
self.iface = None
def get_debug(self): return self._debug
def get_debug(self):
""" Getter for debug property. """
return self._debug
def set_debug(self, value):
""" Setter for debug property. """
self._debug = value
if self.iface:
self.iface.SetDebugMode(value)
debug = property(get_debug, set_debug)
def set_dhcp_client(self, value):
""" Setter for dhcp_client property. """
self._dhcp_client = value
if self.iface:
self.iface.DHCP_CLIENT = value
def get_dhcp_client(self): return self._dhcp_client
def get_dhcp_client(self):
""" Getter for dhcp_client property. """
return self._dhcp_client
dhcp_client = property(get_dhcp_client, set_dhcp_client)
def set_flush_tool(self, value):
""" Setter for flush_tool property. """
self._flush_tool = value
if self.iface:
self.iface.flush_tool = value
def get_flush_tool(self): return self._flush_tool
def get_flush_tool(self):
""" Getter for flush_tool property. """
return self._flush_tool
flush_tool = property(get_flush_tool, set_flush_tool)
def LoadBackend(self, backend_name):
@@ -336,7 +345,10 @@ class ConnectThread(threading.Thread):
self.debug = debug
self.SetStatus('interface_down')
def _connect(self):
raise NotImplementedError
def run(self):
self.connect_result = "failed"
try:
@@ -345,12 +357,15 @@ class ConnectThread(threading.Thread):
self.is_connecting = False
def set_should_die(self, val):
""" Setter for should_die property. """
self.lock.acquire()
try:
self._should_die = val
finally:
self.lock.release()
def get_should_die(self): return self._should_die
def get_should_die(self):
""" Getter for should_die property. """
return self._should_die
should_die = property(get_should_die, set_should_die)
def SetStatus(self, status):
@@ -401,6 +416,7 @@ class ConnectThread(threading.Thread):
@abortable
def run_global_scripts_if_needed(self, script_dir, extra_parameters=()):
""" Run global scripts if needed. '"""
misc.ExecuteScripts(script_dir, verbose=self.debug,
extra_parameters=extra_parameters)
@@ -458,7 +474,7 @@ class ConnectThread(threading.Thread):
hname = os.uname()[1]
else:
hname = self.network['dhcphostname']
print "Running DHCP with hostname",hname
print "Running DHCP with hostname", hname
dhcp_status = iface.StartDHCP(hname)
if dhcp_status in ['no_dhcp_offers', 'dhcp_failed']:
if self.connect_result != "aborted":
@@ -564,22 +580,30 @@ class Wireless(Controller):
self.should_verify_ap = True
def set_wireless_iface(self, value):
""" Setter for wireless_interface property. """
self._wireless_interface = value
if self.wiface:
self.wiface.SetInterface(value)
def get_wireless_iface(self): return self._wireless_interface
def get_wireless_iface(self):
""" Getter for wireless_interface property. """
return self._wireless_interface
wireless_interface = property(get_wireless_iface, set_wireless_iface)
def set_wpa_driver(self, value):
""" Setter for wpa_driver property. """
self._wpa_driver = value
if self.wiface:
self.SetWPADriver(value)
def get_wpa_driver(self): return self._wpa_driver
def get_wpa_driver(self):
""" Getter for wpa_driver property. """
return self._wpa_driver
wpa_driver = property(get_wpa_driver, set_wpa_driver)
def set_iface(self, value):
""" Setter for iface property. """
self.wiface = value
def get_iface(self):
""" Getter for iface property. """
return self.wiface
iface = property(get_iface, set_iface)
@@ -591,8 +615,9 @@ class Wireless(Controller):
"""
Controller.LoadBackend(self, backend)
if self._backend:
self.wiface = self._backend.WirelessInterface(self.wireless_interface,
backend = self._backend
if backend:
self.wiface = backend.WirelessInterface(self.wireless_interface,
self.debug, self.wpa_driver)
def Scan(self, essid=None):
@@ -606,13 +631,15 @@ class Wireless(Controller):
"""
def comp(x, y):
""" Custom sorting function. """
if 'quality' in x:
key = 'quality'
else:
key = 'strength'
return cmp(x[key], y[key])
if not self.wiface: return []
if not self.wiface:
return []
wiface = self.wiface
# Prepare the interface for scanning
@@ -639,7 +666,8 @@ class Wireless(Controller):
network -- network to connect to
"""
if not self.wiface: return False
if not self.wiface:
return False
self.connecting_thread = WirelessConnectThread(network,
self.wireless_interface, self.wpa_driver, self.before_script,
@@ -739,6 +767,7 @@ class Wireless(Controller):
return BACKEND.GetWpaSupplicantDrivers()
def StopWPA(self):
""" Stop wpa_supplicant. """
return self.wiface.StopWPA()
def CreateAdHocNetwork(self, essid, channel, ip, enctype, key,
@@ -821,7 +850,8 @@ class Wireless(Controller):
"""
cmd = 'rfkill list'
rfkill_out = misc.Run(cmd)
soft_blocks = filter(lambda x: x.startswith('Soft'), rfkill_out.split('\t'))
soft_blocks = filter(lambda x: x.startswith('Soft'),
rfkill_out.split('\t'))
for line in map(lambda x: x.strip(), soft_blocks):
if line.endswith('yes'):
return True
@@ -1015,7 +1045,8 @@ class WirelessConnectThread(ConnectThread):
# cards).
if self.debug:
print "enctype is %s" % self.network.get('enctype')
if self.network.get('key') and 'wpa' in str(self.network.get('enctype')):
if self.network.get('key') and \
'wpa' in str(self.network.get('enctype')):
self.SetStatus('generating_psk')
print 'Generating psk...'
self.network['psk'] = wiface.GeneratePSK(self.network)
@@ -1044,23 +1075,31 @@ class Wired(Controller):
self.liface = None
def set_link_detect(self, value):
""" Setter for link_detect property. """
self._link_detect = value
if self.liface:
self.liface.link_detect = value
def get_link_detect(self): return self._link_detect
def get_link_detect(self):
""" Getter for link_detect property. """
return self._link_detect
link_detect = property(get_link_detect, set_link_detect)
def set_wired_iface(self, value):
""" Setter for wired_interface property. """
self._wired_interface = value
if self.liface:
self.liface.SetInterface(value)
def get_wired_iface(self): return self._wired_interface
def get_wired_iface(self):
""" Getter for wired_interface property. """
return self._wired_interface
wired_interface = property(get_wired_iface, set_wired_iface)
def set_iface(self, value):
""" Setter for iface property. """
self.liface = value
def get_iface(self):
""" Getter for iface property. """
return self.liface
iface = property(get_iface, set_iface)
@@ -1087,7 +1126,8 @@ class Wired(Controller):
network -- network to connect to
"""
if not self.liface: return False
if not self.liface:
return False
self.connecting_thread = WiredConnectThread(network,
self.wired_interface, self.before_script, self.after_script,
self.pre_disconnect_script, self.post_disconnect_script,
@@ -1103,6 +1143,7 @@ class Wired(Controller):
self.StopWPA()
def StopWPA(self):
""" Stop wpa_supplicant. """
self.liface.StopWPA()
def DetectWiredInterface(self):
@@ -1165,9 +1206,9 @@ class WiredConnectThread(ConnectThread):
# Run pre-connection script.
self.run_global_scripts_if_needed(wpath.preconnectscripts,
extra_parameters=('wired', 'wired',
self.network['profilename'])
self.network['profilename'])
)
self.run_script_if_needed(self.before_script, 'pre-connection', 'wired',
self.run_script_if_needed(self.before_script, 'pre-connection', 'wired',
'wired')
# Take down interface and clean up previous connections.
@@ -1195,7 +1236,7 @@ class WiredConnectThread(ConnectThread):
extra_parameters=('wired', 'wired',
self.network['profilename'])
)
self.run_script_if_needed(self.after_script, 'post-connection', 'wired',
self.run_script_if_needed(self.after_script, 'post-connection', 'wired',
'wired')
self.SetStatus('done')

View File

@@ -33,10 +33,9 @@ try:
proxy_obj = bus.get_object('org.wicd.daemon', '/org/wicd/daemon')
daemon = dbus.Interface(proxy_obj, 'org.wicd.daemon')
except Exception, e:
print>>sys.stderr, "Exception caught: %s" % str(e)
print>>sys.stderr, 'Could not connect to daemon.'
print >> sys.stderr, "Exception caught: %s" % str(e)
print >> sys.stderr, 'Could not connect to daemon.'
sys.exit(1)
if __name__ == '__main__':
@@ -45,7 +44,6 @@ if __name__ == '__main__':
daemon.SetForcedDisconnect(False)
daemon.SetSuspend(True)
except Exception, e:
print>>sys.stderr, "Exception caught: %s" % str(e)
print>>sys.stderr, 'Error setting suspend.'
print >> sys.stderr, "Exception caught: %s" % str(e)
print >> sys.stderr, 'Error setting suspend.'
sys.exit(2)

View File

@@ -52,8 +52,7 @@ def get_gettext():
langs += ["en_US"]
lang = gettext.translation('wicd', local_path, languages=langs,
fallback=True)
_ = lang.ugettext
return _
return lang.ugettext
_ = get_gettext()
@@ -67,13 +66,17 @@ language = {}
# FIXME: these were present in wicd 1.7.0, can't find where they are.
# Leaving here for future reference, they should be removed whenever
# possible.
#language['cannot_start_daemon'] = _('''Unable to connect to wicd daemon DBus interface. This typically means there was a problem starting the daemon. Check the wicd log for more information.''')
#language['backend_alert'] = _('''Changes to your backend won't occur until the daemon is restarted.''')
#language['about_help'] = _('''Stop a network connection in progress''')
#language['connect'] = _('''Connect''')
#language['cannot_start_daemon'] = _('Unable to connect to wicd daemon ' + \
# 'DBus interface. This typically means there was a problem starting ' + \
# 'the daemon. Check the wicd log for more information.')
#language['backend_alert'] = _('Changes to your backend won't occur until ' + \
# 'the daemon is restarted.')
#language['about_help'] = _('Stop a network connection in progress')
#language['connect'] = _('Connect')
# from templates, dict populated with:
# grep -R "*" encryption/templates/ | tr " " "\n" | grep "^*" | sed -e "s/*//"| sort -u | tr [A-Z] [a-z]
# grep -R "*" encryption/templates/ | tr " " "\n" | grep "^*" | \
# sed -e "s/*//" | sort -u | tr [A-Z] [a-z]
language['authentication'] = _('Authentication')
language['domain'] = _('Domain')
language['identity'] = _('Identity')

View File

@@ -71,7 +71,7 @@ wireless_conf = os.path.join(wpath.etc, "wireless-settings.conf")
wired_conf = os.path.join(wpath.etc, "wired-settings.conf")
dhclient_conf = os.path.join(wpath.etc, "dhclient.conf.template")
class WicdDaemon(dbus.service.Object):
class WicdDaemon(dbus.service.Object, object):
""" The main wicd daemon class.
This class mostly contains exported DBus methods that are not
@@ -107,6 +107,17 @@ class WicdDaemon(dbus.service.Object):
self.link_detect_tool = 0
self.flush_tool = 0
self.sudo_app = 0
self.use_global_dns = False
self.always_show_wired_interface = True
self.wired_connect_mode = 1
self.wired_bus.connect_mode = 1
self.dns_dom = None
self.signal_display_type = 0
self.dns1 = None
self.dns2 = None
self.dns3 = None
self.search_dom = None
self.auto_reconnect = True
# 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
@@ -126,8 +137,10 @@ class WicdDaemon(dbus.service.Object):
self.wireless_bus.Scan()
def get_debug_mode(self):
""" Getter for debug_mode property. """
return self._debug_mode
def set_debug_mode(self, mode):
""" Setter for debug_mode property. """
self._debug_mode = mode
self.config.debug = mode
debug_mode = property(get_debug_mode, set_debug_mode)
@@ -192,11 +205,13 @@ class WicdDaemon(dbus.service.Object):
self.dns3 = dns3
self.wifi.global_dns_3 = dns3
self.wired.global_dns_3 = dns3
self.config.set("Settings", "global_dns_dom", misc.noneToString(dns_dom))
self.config.set("Settings", "global_dns_dom",
misc.noneToString(dns_dom))
self.dns_dom = dns_dom
self.wifi.dns_dom = dns_dom
self.wired.dns_dom = dns_dom
self.config.set("Settings", "global_search_dom", misc.noneToString(search_dom))
self.config.set("Settings", "global_search_dom",
misc.noneToString(search_dom))
self.search_dom = search_dom
self.wifi.global_search_dom = search_dom
self.wired.global_search_dom = search_dom
@@ -211,7 +226,8 @@ class WicdDaemon(dbus.service.Object):
print "setting backend to %s" % backend
backends = networking.BACKEND_MGR.get_available_backends()
if backend not in backends:
print "backend %s not available, trying to fallback to another" % backend
print "backend %s not available, trying to fallback to another" \
% backend
try:
backend = backends[0]
except IndexError:
@@ -310,18 +326,18 @@ class WicdDaemon(dbus.service.Object):
self.wired.Disconnect()
@dbus.service.method('org.wicd.daemon')
def FormatSignalForPrinting(self, signal):
def FormatSignalForPrinting(self, sign):
""" Returns the suffix to display after the signal strength number. """
if self.GetSignalDisplayType() == 1:
return '%s dBm' % signal
return '%s dBm' % sign
else:
try:
if int(signal) == 101:
if int(sign) == 101:
return '??%'
else:
return '%s%%' % signal
return '%s%%' % sign
except ValueError:
return '%s%%' % signal
return '%s%%' % sign
@dbus.service.method('org.wicd.daemon')
def SetSuspend(self, val):
@@ -463,7 +479,8 @@ class WicdDaemon(dbus.service.Object):
started.
"""
if self.debug_mode and value: print "Forced disconnect on"
if self.debug_mode and value:
print "Forced disconnect on"
self.forced_disconnect = bool(value)
@dbus.service.method('org.wicd.daemon')
@@ -578,7 +595,8 @@ class WicdDaemon(dbus.service.Object):
@dbus.service.method('org.wicd.daemon')
def SetShowNeverConnect(self, value):
""" Sets the how_never_connect state. """
self.config.set("Settings", "show_never_connect", bool(value), write=True)
self.config.set("Settings", "show_never_connect", bool(value),
write=True)
self.show_never_connect = bool(value)
@dbus.service.method('org.wicd.daemon')
@@ -746,7 +764,7 @@ class WicdDaemon(dbus.service.Object):
try:
gobject.timeout_add_seconds(3, self._monitor_wired_autoconnect,
fresh)
except:
except AttributeError:
gobject.timeout_add(3000, self._monitor_wired_autoconnect, fresh)
return True
@@ -772,28 +790,36 @@ class WicdDaemon(dbus.service.Object):
@dbus.service.method("org.wicd.daemon")
def ConnectResultsAvailable(self):
if ((self.wired.connecting_thread and self.wired.connecting_thread.connect_result) or
(self.wifi.connecting_thread and self.wifi.connecting_thread.connect_result)):
""" Return whether connection results are available. """
wired_thread = self.wired.connecting_thread
wifi_thread = self.wifi.connecting_thread
if ((wired_thread and wired_thread.connect_result) or
(wifi_thread and wifi_thread.connect_result)):
return True
else:
return False
@dbus.service.method("org.wicd.daemon")
def SendConnectResultsIfAvail(self):
""" Send connection results if they're available. '"""
if self.ConnectResultsAvailable():
self.SendConnectResult()
@dbus.service.method("org.wicd.daemon")
def SendConnectResult(self):
if self.wired.connecting_thread and self.wired.connecting_thread.connect_result:
self.ConnectResultsSent(self.wired.connecting_thread.connect_result)
self.wired.connecting_thread.connect_result = ""
elif self.wifi.connecting_thread and self.wifi.connecting_thread.connect_result:
self.ConnectResultsSent(self.wifi.connecting_thread.connect_result)
self.wifi.connecting_thread.connect_result = ""
""" Send connection result. """
wired_thread = self.wired.connecting_thread
wifi_thread = self.wifi.connecting_thread
if wired_thread and wired_thread.connect_result:
self.ConnectResultsSent(wired_thread.connect_result)
wired_thread.connect_result = ""
elif wifi_thread and wifi_thread.connect_result:
self.ConnectResultsSent(wifi_thread.connect_result)
wifi_thread.connect_result = ""
@dbus.service.signal(dbus_interface="org.wicd.daemon",signature='s')
def ConnectResultsSent(self, result):
""" Signal emit when connection results are sent. """
print "Sending connection attempt result %s" % result
@dbus.service.method("org.wicd.daemon")
@@ -853,25 +879,29 @@ class WicdDaemon(dbus.service.Object):
# Load network interfaces.
iface = self.wireless_bus.DetectWirelessInterface()
if not iface: iface = 'wlan0'
if not iface:
iface = 'wlan0'
self.SetWirelessInterface(app_conf.get("Settings", "wireless_interface",
default=iface))
iface = self.wired_bus.DetectWiredInterface()
if not iface: iface = 'eth0'
if not iface:
iface = 'eth0'
self.SetWiredInterface(app_conf.get("Settings", "wired_interface",
default=iface))
self.SetWPADriver(app_conf.get("Settings", "wpa_driver", default="wext"))
self.SetWPADriver(app_conf.get("Settings", "wpa_driver",
default="wext"))
self.SetAlwaysShowWiredInterface(app_conf.get("Settings",
"always_show_wired_interface",
default=False))
"always_show_wired_interface",
default=False))
self.SetUseGlobalDNS(app_conf.get("Settings", "use_global_dns",
default=False))
dns1 = app_conf.get("Settings", "global_dns_1", default='None')
dns2 = app_conf.get("Settings", "global_dns_2", default='None')
dns3 = app_conf.get("Settings", "global_dns_3", default='None')
dns_dom = app_conf.get("Settings", "global_dns_dom", default='None')
search_dom = app_conf.get("Settings", "global_search_dom", default='None')
search_dom = app_conf.get("Settings", "global_search_dom",
default='None')
self.SetGlobalDNS(dns1, dns2, dns3, dns_dom, search_dom)
self.SetAutoReconnect(app_conf.get("Settings", "auto_reconnect",
default=True))
@@ -933,7 +963,7 @@ class WicdDaemon(dbus.service.Object):
###### Wireless Daemon #######
##############################
class WirelessDaemon(dbus.service.Object):
class WirelessDaemon(dbus.service.Object, object):
""" DBus interface for wireless connection operations. """
def __init__(self, bus_name, daemon, wifi=None, debug=False):
""" Intitialize the wireless DBus interface. """
@@ -948,8 +978,10 @@ class WirelessDaemon(dbus.service.Object):
self.config = ConfigManager(wireless_conf, debug=debug)
def get_debug_mode(self):
""" Getter for the debug_mode property. """
return self._debug_mode
def set_debug_mode(self, mode):
""" Setter for the debug_mode property. """
self._debug_mode = mode
self.config.debug = mode
debug_mode = property(get_debug_mode, set_debug_mode)
@@ -1068,10 +1100,10 @@ class WirelessDaemon(dbus.service.Object):
return self.wifi.GetRfKillStatus()
@dbus.service.method('org.wicd.daemon.wireless')
def GetWirelessProperty(self, networkid, property):
def GetWirelessProperty(self, networkid, prop):
""" Retrieves wireless property from the network specified """
try:
value = self.LastScan[networkid].get(property)
value = self.LastScan[networkid].get(prop)
except IndexError:
return ""
value = misc.to_unicode(value)
@@ -1088,7 +1120,8 @@ class WirelessDaemon(dbus.service.Object):
return False
# whitelist some props that need different handling
if prop in ('key_index', ):
self.LastScan[netid][prop] = misc.to_unicode(misc.Noneify(value, False))
self.LastScan[netid][prop] = \
misc.to_unicode(misc.Noneify(value, False))
else:
self.LastScan[netid][prop] = misc.to_unicode(misc.Noneify(value))
@@ -1161,27 +1194,28 @@ class WirelessDaemon(dbus.service.Object):
return result
@dbus.service.method('org.wicd.daemon.wireless')
def ConnectWireless(self, id):
def ConnectWireless(self, nid):
""" Connects the the wireless network specified by i"""
self.SaveWirelessNetworkProfile(id)
self.SaveWirelessNetworkProfile(nid)
# Will returned instantly, that way we don't hold up dbus.
# CheckIfWirelessConnecting can be used to test if the connection
# is done.
self.wifi.before_script = self.GetWirelessProperty(id, 'beforescript')
self.wifi.after_script = self.GetWirelessProperty(id, 'afterscript')
self.wifi.pre_disconnect_script = self.GetWirelessProperty(id,
'predisconnectscript')
self.wifi.post_disconnect_script = self.GetWirelessProperty(id,
'postdisconnectscript')
self.wifi.bitrate = self.GetWirelessProperty(id, 'bitrate')
self.wifi.allow_lower_bitrates = self.GetWirelessProperty(id,
'allow_lower_bitrates')
print 'Connecting to wireless network ' + str(self.LastScan[id]['essid'])
self.wifi.before_script = self.GetWirelessProperty(nid, 'beforescript')
self.wifi.after_script = self.GetWirelessProperty(nid, 'afterscript')
self.wifi.pre_disconnect_script = self.GetWirelessProperty(nid,
'predisconnectscript')
self.wifi.post_disconnect_script = self.GetWirelessProperty(nid,
'postdisconnectscript')
self.wifi.bitrate = self.GetWirelessProperty(nid, 'bitrate')
self.wifi.allow_lower_bitrates = self.GetWirelessProperty(nid,
'allow_lower_bitrates')
print 'Connecting to wireless network ' + \
str(self.LastScan[nid]['essid'])
# disconnect to make sure that scripts are run
self.wifi.Disconnect()
self.daemon.wired_bus.wired.Disconnect()
self.daemon.SetForcedDisconnect(False)
conthread = self.wifi.Connect(self.LastScan[id], debug=self.debug_mode)
self.wifi.Connect(self.LastScan[nid], debug=self.debug_mode)
self.daemon.UpdateState()
@dbus.service.method('org.wicd.daemon.wireless')
@@ -1217,9 +1251,9 @@ class WirelessDaemon(dbus.service.Object):
return False
@dbus.service.method('org.wicd.daemon.wireless')
def ReadWirelessNetworkProfile(self, id):
def ReadWirelessNetworkProfile(self, nid):
""" Reads in wireless profile as the active network """
cur_network = self.LastScan[id]
cur_network = self.LastScan[nid]
essid_key = "essid:%s" % cur_network["essid"]
bssid_key = cur_network["bssid"]
@@ -1247,13 +1281,13 @@ class WirelessDaemon(dbus.service.Object):
cur_network['essid'] = stored_essid
@dbus.service.method('org.wicd.daemon.wireless')
def SaveWirelessNetworkProfile(self, id):
def SaveWirelessNetworkProfile(self, nid):
""" Writes a wireless profile to disk. """
def write_script_ent(prof, script):
if not self.config.has_option(prof, script):
self.config.set(prof, script, None)
cur_network = self.LastScan[id]
cur_network = self.LastScan[nid]
bssid_key = cur_network["bssid"]
essid_key = "essid:%s" % cur_network["essid"]
@@ -1287,7 +1321,7 @@ class WirelessDaemon(dbus.service.Object):
self.config.write()
@dbus.service.method('org.wicd.daemon.wireless')
def SaveWirelessNetworkProperty(self, id, option):
def SaveWirelessNetworkProperty(self, nid, option):
""" Writes a particular wireless property to disk. """
option = misc.sanitize_config(option)
if option.endswith("script"):
@@ -1295,7 +1329,7 @@ class WirelessDaemon(dbus.service.Object):
'the daemon.'
return
config = self.config
cur_network = self.LastScan[id]
cur_network = self.LastScan[nid]
essid_key = "essid:" + cur_network["essid"]
config.set(cur_network["bssid"], option, str(cur_network[option]))
@@ -1347,12 +1381,14 @@ class WirelessDaemon(dbus.service.Object):
self.config.remove_section(section)
self.config.write()
@dbus.service.signal(dbus_interface='org.wicd.daemon.wireless', signature='')
@dbus.service.signal(dbus_interface='org.wicd.daemon.wireless', \
signature='')
def SendStartScanSignal(self):
""" Emits a signal announcing a scan has started. """
self._scanning = True
@dbus.service.signal(dbus_interface='org.wicd.daemon.wireless', signature='')
@dbus.service.signal(dbus_interface='org.wicd.daemon.wireless', \
signature='')
def SendEndScanSignal(self):
""" Emits a signal announcing a scan has finished. """
self._scanning = False
@@ -1372,11 +1408,10 @@ class WirelessDaemon(dbus.service.Object):
if self.debug_mode:
print network["essid"] + ' has profile'
if bool(network.get('automatic')):
try:
if network.get('never'):
print network["essid"],'marked never connect'
continue
except:
if network.get('never'):
print network["essid"],'marked never connect'
continue
else:
print network["essid"],'has no never connect value'
print 'trying to automatically connect to...' + \
network["essid"]
@@ -1389,7 +1424,7 @@ class WirelessDaemon(dbus.service.Object):
###### Wired Daemon #######
###########################
class WiredDaemon(dbus.service.Object):
class WiredDaemon(dbus.service.Object, object):
""" DBus interface for wired connection operations. """
def __init__(self, bus_name, daemon, wired=None, debug=False):
""" Intitialize the wireless DBus interface. """
@@ -1403,8 +1438,10 @@ class WiredDaemon(dbus.service.Object):
self.config = ConfigManager(wired_conf, debug=debug)
def get_debug_mode(self):
""" Getter for debug_mode property. """
return self._debug_mode
def set_debug_mode(self, mode):
""" Setter for debug_mode property. """
self._debug_mode = mode
self.config.debug = mode
debug_mode = property(get_debug_mode, set_debug_mode)
@@ -1465,10 +1502,10 @@ class WiredDaemon(dbus.service.Object):
return False
@dbus.service.method('org.wicd.daemon.wired')
def GetWiredProperty(self, property):
def GetWiredProperty(self, prop):
""" Returns the requested wired property. """
if self.WiredNetwork:
value = self.WiredNetwork.get(property)
value = self.WiredNetwork.get(prop)
return value
else:
print 'GetWiredProperty: WiredNetwork does not exist'
@@ -1516,8 +1553,10 @@ class WiredDaemon(dbus.service.Object):
""" Connects to a wired network. """
self.wired.before_script = self.GetWiredProperty("beforescript")
self.wired.after_script = self.GetWiredProperty("afterscript")
self.wired.pre_disconnect_script = self.GetWiredProperty("predisconnectscript")
self.wired.post_disconnect_script = self.GetWiredProperty("postdisconnectscript")
self.wired.pre_disconnect_script = \
self.GetWiredProperty("predisconnectscript")
self.wired.post_disconnect_script = \
self.GetWiredProperty("postdisconnectscript")
self.daemon.wireless_bus.wifi.Disconnect()
# make sure disconnect scripts are run
self.wired.Disconnect()
@@ -1537,13 +1576,13 @@ class WiredDaemon(dbus.service.Object):
if self.config.has_section(profilename):
return False
for option in ["ip", "broadcast", "netmask", "gateway", "search_domain",
for option in ["ip", "broadcast", "netmask", "gateway", "search_domain",
"dns_domain", "dns1", "dns2", "dns3", "beforescript",
"afterscript", "predisconnectscript",
"postdisconnectscript", "encryption_enabled"]:
self.config.set(profilename, option, None)
self.config.set(profilename, "default", default)
self.config.set(profilename,"dhcphostname",os.uname()[1])
self.config.set(profilename, "dhcphostname", os.uname()[1])
self.config.write()
return True
@@ -1628,7 +1667,8 @@ class WiredDaemon(dbus.service.Object):
profile[x] = misc.Noneify(self.config.get(profilename, x))
profile['use_global_dns'] = bool(profile.get('use_global_dns'))
profile['use_static_dns'] = bool(profile.get('use_static_dns'))
profile['encryption_enabled'] = bool(profile.get('encryption_enabled'))
profile['encryption_enabled'] = \
bool(profile.get('encryption_enabled'))
profile['profilename'] = profilename
self.WiredNetwork = profile
self._cur_wired_prof_name = profilename
@@ -1657,6 +1697,7 @@ class WiredDaemon(dbus.service.Object):
return wnettools.GetWiredInterfaces()
def usage():
""" Print help screen. """
print """
wicd %s
wireless (and wired) connection daemon.
@@ -1765,8 +1806,8 @@ def main(argv):
try:
opts, args = getopt.getopt(sys.argv[1:], 'fenoahk',
['help', 'no-daemon', 'no-poll', 'no-stderr', 'no-stdout',
'no-autoconnect', 'kill'])
['help', 'no-daemon', 'no-poll', 'no-stderr',
'no-stdout', 'no-autoconnect', 'kill'])
except getopt.GetoptError:
# Print help information and exit
usage()
@@ -1788,12 +1829,12 @@ def main(argv):
if o in ('-n', '--no-poll'):
no_poll = True
if o in ('-k', '--kill'):
kill = True
kill = True
if kill:
try:
f = open(wpath.pidfile)
except:
except IOError:
#print >> sys.stderr, "No wicd instance active, aborting."
sys.exit(1)
@@ -1817,7 +1858,7 @@ def main(argv):
dbus_ifaces['daemon'].Disconnect()
pid = int(f.readline())
f.close()
os.kill(pid,signal.SIGTERM)
os.kill(pid, signal.SIGTERM)
# quit, this should be the only option specified
sys.exit(0)
@@ -1830,7 +1871,8 @@ def main(argv):
if not os.path.exists(wpath.networks):
os.makedirs(wpath.networks)
if do_daemonize: daemonize()
if do_daemonize:
daemonize()
if redirect_stderr or redirect_stdout:
logpath = os.path.join(wpath.log, 'wicd.log')
@@ -1840,8 +1882,8 @@ def main(argv):
output = ManagedStdio(logpath)
if os.path.exists(logpath):
try:
os.chmod(logpath, int(wpath.log_perms,8))
except:
os.chmod(logpath, int(wpath.log_perms, 8))
except OSError:
print 'unable to chmod log file to %s' % wpath.log_perms
try:
@@ -1849,11 +1891,13 @@ def main(argv):
import grp
group = grp.getgrnam(wpath.log_group)
os.chown(logpath, 0, group[2])
except:
except OSError:
print 'unable to chown log file to %s' % group[2]
if redirect_stdout: sys.stdout = output
if redirect_stderr: sys.stderr = output
if redirect_stdout:
sys.stdout = output
if redirect_stderr:
sys.stderr = output
print '---------------------------'
print 'wicd initializing...'

View File

@@ -49,7 +49,8 @@ essid_pattern = re.compile('.*ESSID:"?(.*?)".*\n', _re_mode)
ap_mac_pattern = re.compile('.*Address: (.*?)\n', _re_mode)
channel_pattern = re.compile('.*Channel:?=? ?(\d+)', _re_mode)
strength_pattern = re.compile('.*Quality:?=? ?(\d+)\s*/?\s*(\d*)', _re_mode)
altstrength_pattern = re.compile('.*Signal level:?=? ?(\d+)\s*/?\s*(\d*)', _re_mode)
altstrength_pattern = re.compile('.*Signal level:?=? ?(\d+)\s*/?\s*(\d*)',
_re_mode)
signaldbm_pattern = re.compile('.*Signal level:?=? ?(-\d\d*)', _re_mode)
bitrates_pattern = re.compile('([\d\.]+)\s+\S+/s', _re_mode)
mode_pattern = re.compile('.*Mode:([A-Za-z-]*?)\n', _re_mode)
@@ -61,12 +62,15 @@ wpa2_pattern = re.compile('(WPA2)', _re_mode)
#iwconfig-only regular expressions.
ip_up = re.compile(r'flags=[0.9]*<([^>]*)>', re.S)
ip_pattern = re.compile(r'inet [Aa]d?dr[^.]*:([^.]*\.[^.]*\.[^.]*\.[0-9]*)', re.S)
ip_pattern = re.compile(r'inet [Aa]d?dr[^.]*:([^.]*\.[^.]*\.[^.]*\.[0-9]*)',
re.S)
ip_pattern1 = re.compile(r'inet ([^.]*\.[^.]*\.[^.]*\.[0-9]*)', re.S)
bssid_pattern = re.compile('.*[(Access Point)|(Cell)]: (([0-9A-Z]{2}:){5}[0-9A-Z]{2})', _re_mode)
bssid_pattern = re.compile('.*[(Access Point)|(Cell)]: ' + \
'(([0-9A-Z]{2}:){5}[0-9A-Z]{2})', _re_mode)
bitrate_pattern = re.compile('.*Bit Rate[=:](.*?/s)', _re_mode)
opmode_pattern = re.compile('.*Mode:(.*?) ', _re_mode)
authmethods_pattern = re.compile('.*Authentication capabilities :\n(.*?)Current', _re_mode)
authmethods_pattern = re.compile('.*Authentication capabilities ' + \
':\n(.*?)Current', _re_mode)
# Regular expressions for wpa_cli output
auth_pattern = re.compile('.*wpa_state=(.*?)\n', _re_mode)
@@ -79,12 +83,14 @@ blacklist_norm = ";`$!*|><&\\"
blank_trans = maketrans("", "")
def _sanitize_string(string):
""" Sanitize string. """
if string:
return translate(str(string), blank_trans, blacklist_norm)
else:
return string
def _sanitize_string_strict(string):
""" Sanitize string in a stricter way. """
if string:
return translate(str(string), blank_trans, blacklist_strict)
else:
@@ -140,7 +146,8 @@ def isWireless(devname):
in the future, if wireless.h is fully replaced.
"""
we = None
for t in [socket.AF_INET, socket.AF_INET6, socket.AF_IPX, socket.AF_AX25, socket.AF_APPLETALK]:
for t in [socket.AF_INET, socket.AF_INET6, socket.AF_IPX, socket.AF_AX25,
socket.AF_APPLETALK]:
sk = socket.socket(t, socket.SOCK_DGRAM)
if sk is None:
continue
@@ -149,7 +156,7 @@ def isWireless(devname):
#define SIOCGIWNAME 0x8b01 in linux/wireless.h
# "used to verify the presence of wireless extensions"
we = fcntl.ioctl(skfd, 0x8b01, devname)
except:
except IOError:
pass
sk.close()
return we is not None
@@ -184,7 +191,7 @@ def GetWpaSupplicantDrivers():
output = misc.Run(["wpa_supplicant", "-h"])
try:
output = output.split("drivers:")[1].split("options:")[0].strip()
except:
except KeyError:
print "Warning: Couldn't get list of valid wpa_supplicant drivers"
return [""]
patt = re.compile("(\S+)\s+=.*")
@@ -236,7 +243,24 @@ class BaseInterface(object):
self.flush_tool = None
self.link_detect = None
self.dhcp_object = None
self.ethtool_cmd = None
self.miitool_cmd = None
self.ip_cmd = None
self.route_cmd = None
self.wpa_cli_cmd = None
self.resolvconf_cmd = None
self.dhclient_cmd = None
self.dhclient_needs_verbose = False
self.udhcpc_cmd = None
self.dhcpcd_cmd = None
self.pump_cmd = None
self.kdesu_cmd = None
self.gksudo_cmd = None
self.ktsuss_cmd = None
def SetDebugMode(self, value):
""" If True, verbose output is enabled. """
self.verbose = value
@@ -363,7 +387,8 @@ class BaseInterface(object):
"hostname" : hostname,
'dhclientconf' : dhclient_conf_path }
elif flavor == "release":
return client_dict[client_name]['release'] % {"cmd":cmd, "iface":self.iface}
return client_dict[client_name]['release'] % \
{"cmd": cmd, "iface": self.iface}
else:
return client_dict[client_name]['id']
@@ -429,6 +454,7 @@ class BaseInterface(object):
self.route_cmd = self._find_program_path("route")
def CheckSudoApplications(self):
""" Check for available root-gaining 'sudo' applications. """
self.gksudo_cmd = self._find_program_path("gksudo")
self.kdesu_cmd = self._find_program_path("kdesu")
self.ktsuss_cmd = self._find_program_path("ktsuss")
@@ -442,7 +468,8 @@ class BaseInterface(object):
"""
cmd = 'ifconfig ' + self.iface + ' up'
if self.verbose: print cmd
if self.verbose:
print cmd
misc.Run(cmd)
return True
@@ -455,7 +482,8 @@ class BaseInterface(object):
"""
cmd = 'ifconfig ' + self.iface + ' down'
if self.verbose: print cmd
if self.verbose:
print cmd
misc.Run(cmd)
return True
@@ -464,7 +492,8 @@ class BaseInterface(object):
def GetIfconfig(self):
""" Runs ifconfig and returns the output. """
cmd = "ifconfig %s" % self.iface
if self.verbose: print cmd
if self.verbose:
print cmd
return misc.Run(cmd)
@neediface("")
@@ -491,7 +520,8 @@ class BaseInterface(object):
cmd = ''.join([cmd, 'netmask ', netmask, ' '])
if broadcast:
cmd = ''.join([cmd, 'broadcast ', broadcast, ' '])
if self.verbose: print cmd
if self.verbose:
print cmd
misc.Run(cmd)
def _parse_dhclient(self, pipe):
@@ -624,7 +654,8 @@ class BaseInterface(object):
"""
cmd = self._get_dhcp_command('connect', hostname)
if self.verbose: print cmd
if self.verbose:
print cmd
self.dhcp_object = misc.Run(cmd, include_stderr=True, return_obj=True)
pipe = self.dhcp_object.stdout
client_dict = { misc.DHCLIENT : self._parse_dhclient,
@@ -646,7 +677,8 @@ class BaseInterface(object):
def ReleaseDHCP(self):
""" Release the DHCP lease for this interface. """
cmd = self._get_dhcp_command("release")
if self.verbose: print cmd
if self.verbose:
print cmd
misc.Run(cmd)
@neediface(False)
@@ -659,7 +691,8 @@ class BaseInterface(object):
else:
print "No route manipulation command available!"
return
if self.verbose: print cmd
if self.verbose:
print cmd
misc.Run(cmd)
@neediface(False)
@@ -671,7 +704,8 @@ class BaseInterface(object):
"""
if self.resolvconf_cmd:
cmd = [self.resolvconf_cmd, '-d', self.iface + '.wicd']
if self.verbose: print cmd
if self.verbose:
print cmd
p = misc.Run(cmd, include_stderr=True, return_obj=True)
p.communicate()
@@ -711,7 +745,8 @@ class BaseInterface(object):
if self.resolvconf_cmd:
cmd = [self.resolvconf_cmd, '-a', self.iface + '.wicd']
if self.verbose: print cmd
if self.verbose:
print cmd
p = misc.Run(cmd, include_stderr=True, return_obj=True)
p.communicate(input=resolv_params)
else:
@@ -730,7 +765,8 @@ class BaseInterface(object):
print "No flush command available!"
cmds = []
for cmd in cmds:
if self.verbose: print cmd
if self.verbose:
print cmd
misc.Run(cmd)
@neediface(False)
@@ -745,7 +781,8 @@ class BaseInterface(object):
print 'WARNING: Invalid gateway found. Aborting!'
return False
cmd = 'route add default gw %s dev %s' % (gw, self.iface)
if self.verbose: print cmd
if self.verbose:
print cmd
misc.Run(cmd)
@neediface("")
@@ -763,7 +800,8 @@ class BaseInterface(object):
# check multiple ifconfig output styles
for pat in [ip_pattern, ip_pattern1]:
m = misc.RunRegex(pat, output)
if m: return m
if m:
return m
return None
@neediface(False)
@@ -784,7 +822,8 @@ class BaseInterface(object):
# timeout, while the above will wait (-w) 3 seconds at
# most.
cmd = "ping -q -c 1 %s" % gateway
if self.verbose: print cmd
if self.verbose:
print cmd
return misc.LaunchAndWait(cmd)
@neediface(False)
@@ -799,7 +838,8 @@ class BaseInterface(object):
try:
flags = open(flags_file, "r").read().strip()
except IOError:
print "Could not open %s, using ifconfig to determine status" % flags_file
print "Could not open %s, using ifconfig to determine status" \
% flags_file
return self._slow_is_up(ifconfig)
return bool(int(flags, 16) & 1)
@@ -807,7 +847,8 @@ class BaseInterface(object):
def StopWPA(self):
""" Terminates wpa using wpa_cli"""
cmd = 'wpa_cli -i %s terminate' % self.iface
if self.verbose: print cmd
if self.verbose:
print cmd
misc.Run(cmd)
@@ -866,7 +907,8 @@ class BaseWiredInterface(BaseInterface):
while True:
tries += 1
time.sleep(2)
if self.IsUp() or tries > MAX_TRIES: break
if self.IsUp() or tries > MAX_TRIES:
break
if os.path.exists(carrier_path):
carrier = open(carrier_path, 'r')
@@ -878,7 +920,8 @@ class BaseWiredInterface(BaseInterface):
elif link == 0:
return False
except (IOError, ValueError, TypeError):
print 'Error checking link using /sys/class/net/%s/carrier' % self.iface
print 'Error checking link using /sys/class/net/%s/carrier' \
% self.iface
if self.ethtool_cmd and self.link_detect in [misc.ETHTOOL, misc.AUTO]:
return self._eth_get_plugged_in()
@@ -901,10 +944,13 @@ class BaseWiredInterface(BaseInterface):
print 'Wired Interface is down, putting it up'
self.Up()
time.sleep(6)
if self.verbose: print cmd
if self.verbose:
print cmd
tool_data = misc.Run(cmd, include_stderr=True)
if misc.RunRegex(re.compile('(Link detected: yes)', re.I | re.M | re.S),
tool_data):
if misc.RunRegex(
re.compile('(Link detected: yes)', re.I | re.M | re.S),
tool_data
):
return True
else:
return False
@@ -917,14 +963,16 @@ class BaseWiredInterface(BaseInterface):
"""
cmd = "%s %s" % (self.miitool_cmd, self.iface)
if self.verbose: print cmd
if self.verbose:
print cmd
tool_data = misc.Run(cmd, include_stderr=True)
if misc.RunRegex(re.compile('(Invalid argument)', re.I | re.M | re.S),
tool_data) is not None:
print 'Wired Interface is down, putting it up'
self.Up()
time.sleep(4)
if self.verbose: print cmd
if self.verbose:
print cmd
tool_data = misc.Run(cmd, include_stderr=True)
if misc.RunRegex(re.compile('(link ok)', re.I | re.M | re.S),
@@ -934,11 +982,13 @@ class BaseWiredInterface(BaseInterface):
return False
def Authenticate(self, network):
""" Authenticate with wpa_supplicant. """
misc.ParseEncryption(network)
cmd = ['wpa_supplicant', '-B', '-i', self.iface, '-c',
os.path.join(wpath.networks, 'wired'),
'-Dwired']
if self.verbose: print cmd
if self.verbose:
print cmd
misc.Run(cmd)
class BaseWirelessInterface(BaseInterface):
@@ -968,7 +1018,8 @@ class BaseWirelessInterface(BaseInterface):
"""
cmd = ['iwconfig', self.iface, 'essid', '--', str(essid)]
if self.verbose: print str(cmd)
if self.verbose:
print str(cmd)
misc.Run(cmd)
@neediface(False)
@@ -994,7 +1045,8 @@ class BaseWirelessInterface(BaseInterface):
def GetIwconfig(self):
""" Returns the output of iwconfig for this interface. """
cmd = "iwconfig " + self.iface
if self.verbose: print cmd
if self.verbose:
print cmd
return misc.Run(cmd)
def _FreqToChannel(self, freq):
@@ -1019,7 +1071,7 @@ class BaseWirelessInterface(BaseInterface):
try:
ret = freq_dict[freq]
except KeyError:
print "Couldn't determine channel number for frequency: " + str(freq)
print "Couldn't determine channel number for frequency:", str(freq)
return ret
@@ -1040,7 +1092,7 @@ class BaseWirelessInterface(BaseInterface):
for x in lines:
ap = {}
info = x.split(" ")
info = filter(None, [x.strip() for x in info])
info = [x.strip() for x in info if x.strip()]
if len(info) < 5:
continue
if re.match(patt, info[2].upper()):
@@ -1066,7 +1118,7 @@ class BaseWirelessInterface(BaseInterface):
ap['enctype'] = info[4 + offset]
elif info[5 + offset] == 'WPA2-PSK':
ap['encryption_method'] = 'WPA2'
ap['authmode'] ="WPA2PSK"
ap['authmode'] = "WPA2PSK"
ap['keyname'] = "WPA2PSK"
ap['enctype'] = info[4 + offset]
elif info[4 + offset] == "NONE":
@@ -1075,7 +1127,8 @@ class BaseWirelessInterface(BaseInterface):
print "Unknown AuthMode, can't assign encryption_method!"
ap['encryption_method'] = 'Unknown'
aps[bssid] = ap
if self.verbose: print str(aps)
if self.verbose:
print str(aps)
return aps
def _ParseRalinkAccessPoint(self, ap, ralink_info, cell):
@@ -1090,7 +1143,6 @@ class BaseWirelessInterface(BaseInterface):
Updated array containing info about the current access point
"""
wep_pattern = re.compile('.*Encryption key:(.*?)\n', re.I | re.M | re.S)
if ralink_info.has_key(ap['bssid']):
info = ralink_info[ap['bssid']]
for key in info.keys():
@@ -1115,7 +1167,8 @@ class BaseWirelessInterface(BaseInterface):
if mode.lower() == 'master':
mode = 'managed'
cmd = 'iwconfig %s mode %s' % (self.iface, mode)
if self.verbose: print cmd
if self.verbose:
print cmd
misc.Run(cmd)
@neediface(False)
@@ -1131,7 +1184,8 @@ class BaseWirelessInterface(BaseInterface):
return False
cmd = 'iwconfig %s channel %s' % (self.iface, str(channel))
if self.verbose: print cmd
if self.verbose:
print cmd
misc.Run(cmd)
@neediface(False)
@@ -1143,7 +1197,8 @@ class BaseWirelessInterface(BaseInterface):
"""
cmd = 'iwconfig %s key %s' % (self.iface, key)
if self.verbose: print cmd
if self.verbose:
print cmd
misc.Run(cmd)
@neediface(False)
@@ -1176,11 +1231,13 @@ class BaseWirelessInterface(BaseInterface):
base = "iwconfig %s" % self.iface
if channel and str(channel).isdigit():
cmd = "%s channel %s" % (base, str(channel))
if self.verbose: print cmd
if self.verbose:
print cmd
misc.Run(cmd)
if bssid:
cmd = "%s ap %s" % (base, bssid)
if self.verbose: print cmd
if self.verbose:
print cmd
misc.Run(cmd)
def GeneratePSK(self, network):
@@ -1191,11 +1248,13 @@ class BaseWirelessInterface(BaseInterface):
"""
wpa_pass_path = misc.find_path('wpa_passphrase')
if not wpa_pass_path: return None
if not wpa_pass_path:
return None
key_pattern = re.compile('network={.*?\spsk=(.*?)\n}.*',
re.I | re.M | re.S)
cmd = [wpa_pass_path, str(network['essid']), str(network['key'])]
if self.verbose: print cmd
if self.verbose:
print cmd
return misc.RunRegex(key_pattern, misc.Run(cmd))
@neediface(False)
@@ -1218,7 +1277,8 @@ class BaseWirelessInterface(BaseInterface):
os.path.join(wpath.networks,
network['bssid'].replace(':', '').lower()),
driver]
if self.verbose: print cmd
if self.verbose:
print cmd
misc.Run(cmd)
def _AuthenticateRalinkLegacy(self, network):
@@ -1243,7 +1303,8 @@ class BaseWirelessInterface(BaseInterface):
print 'Setting up WEP'
cmd = ''.join(['iwconfig ', self.iface, ' key ',
network.get('key')])
if self.verbose: print cmd
if self.verbose:
print cmd
misc.Run(cmd)
else:
cmd_list = []
@@ -1251,13 +1312,14 @@ class BaseWirelessInterface(BaseInterface):
cmd_list.append('AuthMode=' + info['authmode'])
cmd_list.append('EncrypType=' + info['enctype'])
cmd_list.append('SSID="%s"' % network['essid'])
cmd_list.append('%s="%s"' % (network['keyname'], network['key']))
cmd_list.append('%(keyname)s="%(key)s"' % network)
if info['nettype'] == 'SHARED' and info['enctype'] == 'WEP':
cmd_list.append('DefaultKeyID=1')
for cmd in cmd_list:
cmd = ['iwpriv', self.iface, 'set', cmd]
if self.verbose: print ' '.join(cmd)
if self.verbose:
print ' '.join(cmd)
misc.Run(cmd)
@neediface([])
@@ -1269,7 +1331,8 @@ class BaseWirelessInterface(BaseInterface):
"""
cmd = 'iwlist ' + self.iface + ' scan'
if self.verbose: print cmd
if self.verbose:
print cmd
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.
@@ -1501,7 +1564,8 @@ class BaseWirelessInterface(BaseInterface):
""" Get the available authentication methods for the interface. """
if not iwlistauth:
cmd = 'iwlist ' + self.iface + ' auth'
if self.verbose: print cmd
if self.verbose:
print cmd
output = misc.Run(cmd)
else:
output = iwlistauth
@@ -1515,13 +1579,14 @@ class BaseWirelessInterface(BaseInterface):
""" Get the available bitrates the wifi card can use. """
cmd = 'iwlist ' + self.iface + ' rate'
if self.verbose: print cmd
if self.verbose:
print cmd
rates = misc.Run(cmd)
# process the output
rates = rates.split('\n')
rates = filter(None, map(lambda x: x.strip().split(' ')[0], rates))
rates = filter(lambda x: x[0].isdigit(), rates)
rates = [x.strip().split(' ')[0] for x in rates]
rates = [x for x in rates if x[0].isdigit()]
return dbus.Array(rates, signature='v')
def _get_link_quality(self, output):