1
0
mirror of https://github.com/gryf/wicd.git synced 2026-02-28 13:25:50 +01:00

Merged r329 of mainline 1.6.

This commit is contained in:
Andrew Psaltis
2009-03-21 22:28:05 -04:00
9 changed files with 198 additions and 125 deletions

View File

@@ -18,14 +18,18 @@
PATH=/usr/sbin:/usr/bin:/sbin:/bin PATH=/usr/sbin:/usr/bin:/sbin:/bin
DESC="Network connection manager" DESC="Network connection manager"
NAME=wicd NAME=wicd
RUNDIR=/var/run/$NAME
DAEMON=%SBIN%$NAME DAEMON=%SBIN%$NAME
DAEMON_ARGS="" DAEMON_ARGS=""
PIDFILE=%PIDFILE% PIDFILE=$RUNDIR/wicd.pid
SCRIPTNAME=%INIT%%INITFILENAME% SCRIPTNAME=%INIT%%INITFILENAME%
# Exit if the package is not installed # Exit if the package is not installed
[ -x "$DAEMON" ] || exit 0 [ -x "$DAEMON" ] || exit 0
# Create RUNDIR if it doesn't exist
[ -d "$RUNDIR" ] || mkdir -p "$RUNDIR"
# Read configuration variable file if it is present # Read configuration variable file if it is present
[ -r /etc/default/$NAME ] && . /etc/default/$NAME [ -r /etc/default/$NAME ] && . /etc/default/$NAME

View File

@@ -8,7 +8,7 @@
# #
# processname: wicd # processname: wicd
# config: # config:
# pidfile: /var/run/wicd.pid # pidfile: %PIDFILE%
# #
# $Id: template.init 9689 2008-03-27 16:15:39Z patrys $ # $Id: template.init 9689 2008-03-27 16:15:39Z patrys $

View File

@@ -441,7 +441,6 @@ try:
piddir = os.path.dirname(wpath.pidfile) piddir = os.path.dirname(wpath.pidfile)
if not piddir.endswith('/'): if not piddir.endswith('/'):
piddir += '/' piddir += '/'
data.append (( piddir, [] ))
if not wpath.no_install_docs: if not wpath.no_install_docs:
data.append((wpath.docdir, ['INSTALL', 'LICENSE', 'AUTHORS', data.append((wpath.docdir, ['INSTALL', 'LICENSE', 'AUTHORS',
'README', 'CHANGES', ])) 'README', 'CHANGES', ]))

View File

@@ -34,7 +34,7 @@ from wicd import misc
from wicd import wnettools from wicd import wnettools
from wicd import wpath from wicd import wpath
from wicd.wnettools import * from wicd.wnettools import *
from wicd.wnettools import wep_pattern, signaldbm_pattern from wicd.wnettools import wep_pattern, signaldbm_pattern, neediface
import iwscan import iwscan
import wpactrl import wpactrl
@@ -79,13 +79,13 @@ SIOCGIFFLAGS = 0x8913
def get_iw_ioctl_result(iface, call): def get_iw_ioctl_result(iface, call):
""" Makes the given ioctl call and returns the results. """ Makes the given ioctl call and returns the results.
Keyword arguments: Keyword arguments:
call -- The ioctl call to make call -- The ioctl call to make
Returns: Returns:
The results of the ioctl call. The results of the ioctl call.
""" """
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
buff = array.array('c', '\0' * 32) buff = array.array('c', '\0' * 32)
@@ -118,12 +118,13 @@ class Interface(wnettools.BaseInterface):
wnettools.BaseInterface.__init__(self, iface, verbose) wnettools.BaseInterface.__init__(self, iface, verbose)
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.Check() self.Check()
def CheckWirelessTools(self): def CheckWirelessTools(self):
""" Check for the existence needed wireless tools """ """ Check for the existence needed wireless tools """
# We don't need any external apps so just return # We don't need any external apps so just return
pass pass
@neediface("")
def GetIP(self, ifconfig=""): def GetIP(self, ifconfig=""):
""" Get the IP address of the interface. """ Get the IP address of the interface.
@@ -138,17 +139,17 @@ class Interface(wnettools.BaseInterface):
return None return None
except OSError: except OSError:
return None return None
return socket.inet_ntoa(raw_ip[20:24]) return socket.inet_ntoa(raw_ip[20:24])
@neediface(False)
def IsUp(self): def IsUp(self):
""" Determines if the interface is up. """ Determines if the interface is up.
Returns: Returns:
True if the interface is up, False otherwise. True if the interface is up, False otherwise.
""" """
if not self.iface: return False
data = (self.iface + '\0' * 16)[:18] data = (self.iface + '\0' * 16)[:18]
try: try:
result = fcntl.ioctl(self.sock.fileno(), SIOCGIFFLAGS, data) result = fcntl.ioctl(self.sock.fileno(), SIOCGIFFLAGS, data)
@@ -156,7 +157,7 @@ class Interface(wnettools.BaseInterface):
if self.verbose: if self.verbose:
print "SIOCGIFFLAGS failed: " + str(e) print "SIOCGIFFLAGS failed: " + str(e)
return False return False
flags, = struct.unpack('H', result[16:18]) flags, = struct.unpack('H', result[16:18])
return bool(flags & 1) return bool(flags & 1)
@@ -174,18 +175,18 @@ class WiredInterface(Interface, wnettools.BaseWiredInterface):
wnettools.BaseWiredInterface.__init__(self, iface, verbose) wnettools.BaseWiredInterface.__init__(self, iface, verbose)
Interface.__init__(self, iface, verbose) Interface.__init__(self, iface, verbose)
@neediface(False)
def GetPluggedIn(self): def GetPluggedIn(self):
""" Get the current physical connection state. """ Get the current physical connection state.
The method will first attempt to use ethtool do determine The method will first attempt to use ethtool do determine
physical connection state. Should ethtool fail to run properly, physical connection state. Should ethtool fail to run properly,
mii-tool will be used instead. mii-tool will be used instead.
Returns: Returns:
True if a link is detected, False otherwise. True if a link is detected, False otherwise.
""" """
if not self.iface: return False
if self.ethtool_cmd and self.link_detect in [misc.ETHTOOL, misc.AUTO]: if self.ethtool_cmd and self.link_detect in [misc.ETHTOOL, misc.AUTO]:
return self._eth_get_plugged_in() return self._eth_get_plugged_in()
elif self.miitool_cmd and self.link_detect in [misc.MIITOOL, misc.AUTO]: elif self.miitool_cmd and self.link_detect in [misc.MIITOOL, misc.AUTO]:
@@ -197,10 +198,10 @@ class WiredInterface(Interface, wnettools.BaseWiredInterface):
def _eth_get_plugged_in(self): def _eth_get_plugged_in(self):
""" Use ethtool to determine the physical connection state. """ Use ethtool to determine the physical connection state.
Returns: Returns:
True if a link is detected, False otherwise. True if a link is detected, False otherwise.
""" """
if not self.IsUp(): if not self.IsUp():
self.Up() self.Up()
@@ -216,19 +217,19 @@ class WiredInterface(Interface, wnettools.BaseWiredInterface):
print 'SIOCETHTOOL failed: ' + str(e) print 'SIOCETHTOOL failed: ' + str(e)
return False return False
return bool(buff.tolist()[1]) return bool(buff.tolist()[1])
def _mii_get_plugged_in(self): def _mii_get_plugged_in(self):
""" Use mii-tool to determine the physical connection state. """ Use mii-tool to determine the physical connection state.
Returns: Returns:
True if a link is detected, False otherwise. True if a link is detected, False otherwise.
""" """
if not self.IsUp(): if not self.IsUp():
self.Up() self.Up()
time.sleep(2.5) time.sleep(2.5)
buff = struct.pack('16shhhh', (self.iface + '\0' * 16)[:16], 0, 1, buff = struct.pack('16shhhh', (self.iface + '\0' * 16)[:16], 0, 1,
0x0004, 0) 0x0004, 0)
try: try:
result = fcntl.ioctl(self.sock.fileno(), SIOCGMIIPHY, buff) result = fcntl.ioctl(self.sock.fileno(), SIOCGMIIPHY, buff)
except IOError, e: except IOError, e:
@@ -253,7 +254,8 @@ class WirelessInterface(Interface, wnettools.BaseWirelessInterface):
wpa_driver) wpa_driver)
Interface.__init__(self, iface, verbose) Interface.__init__(self, iface, verbose)
self.scan_iface = None self.scan_iface = None
@neediface([])
def GetNetworks(self): def GetNetworks(self):
""" Get a list of available wireless networks. """ Get a list of available wireless networks.
@@ -267,14 +269,14 @@ class WirelessInterface(Interface, wnettools.BaseWirelessInterface):
except iwscan.error, e: except iwscan.error, e:
print "GetNetworks caught an exception: %s" % e print "GetNetworks caught an exception: %s" % e
return [] return []
try: try:
results = self.scan_iface.Scan() results = self.scan_iface.Scan()
except iwscan.error, e: except iwscan.error, e:
print "ERROR: %s" print "ERROR: %s"
return [] return []
return filter(None, [self._parse_ap(cell) for cell in results]) return filter(None, [self._parse_ap(cell) for cell in results])
def _parse_ap(self, cell): def _parse_ap(self, cell):
""" Parse a single cell from the python-iwscan list. """ """ Parse a single cell from the python-iwscan list. """
ap = {} ap = {}
@@ -283,22 +285,22 @@ class WirelessInterface(Interface, wnettools.BaseWirelessInterface):
except UnicodeError: except UnicodeError:
print 'Unicode problem with the current network essid, ignoring!!' print 'Unicode problem with the current network essid, ignoring!!'
return None return None
if ap['essid'] in [ "", '<hidden>']: if ap['essid'] in [ "", '<hidden>']:
ap['essid'] = '<hidden>' ap['essid'] = '<hidden>'
ap['hidden'] = True ap['hidden'] = True
else: else:
ap['hidden'] = False ap['hidden'] = False
if cell["channel"]: if cell["channel"]:
ap["channel"] = cell["channel"] ap["channel"] = cell["channel"]
else: else:
ap["channel"] = self._FreqToChannel(cell["frequency"]) ap["channel"] = self._FreqToChannel(cell["frequency"])
ap["bssid"] = cell["bssid"] ap["bssid"] = cell["bssid"]
ap["mode"] = cell["mode"] ap["mode"] = cell["mode"]
ap["bitrates"] = cell["bitrate"] ap["bitrates"] = cell["bitrate"]
if cell["enc"]: if cell["enc"]:
ap["encryption"] = True ap["encryption"] = True
if cell["ie"] and cell["ie"].get('type'): if cell["ie"] and cell["ie"].get('type'):
@@ -310,7 +312,7 @@ class WirelessInterface(Interface, wnettools.BaseWirelessInterface):
ap['encryption_method'] = 'WEP' ap['encryption_method'] = 'WEP'
else: else:
ap["encryption"] = False ap["encryption"] = False
# Link Quality # Link Quality
ap['qual_found'] = True ap['qual_found'] = True
ap['quality'] = self._get_link_quality(cell['stats']) ap['quality'] = self._get_link_quality(cell['stats'])
@@ -324,9 +326,9 @@ class WirelessInterface(Interface, wnettools.BaseWirelessInterface):
ap['strength'] = misc.RunRegex(signaldbm_pattern, cell["stats"]) ap['strength'] = misc.RunRegex(signaldbm_pattern, cell["stats"])
elif self.wpa_driver != RALINK_DRIVER: # This is already set for ralink elif self.wpa_driver != RALINK_DRIVER: # This is already set for ralink
ap['strength'] = -1 ap['strength'] = -1
return ap return ap
def _connect_to_wpa_ctrl_iface(self): def _connect_to_wpa_ctrl_iface(self):
""" Connect to the wpa ctrl interface. """ """ Connect to the wpa ctrl interface. """
ctrl_iface = '/var/run/wpa_supplicant' ctrl_iface = '/var/run/wpa_supplicant'
@@ -340,7 +342,7 @@ class WirelessInterface(Interface, wnettools.BaseWirelessInterface):
else: 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 return None
def ValidateAuthentication(self, auth_time): def ValidateAuthentication(self, auth_time):
""" Validate WPA authentication. """ Validate WPA authentication.
@@ -350,27 +352,27 @@ class WirelessInterface(Interface, wnettools.BaseWirelessInterface):
NOTE: It's possible this could return False, NOTE: It's possible this could return False,
though in reality wpa_supplicant just isn't though in reality wpa_supplicant just isn't
finished yet. finished yet.
Keyword arguments: Keyword arguments:
auth_time -- The time at which authentication began. auth_time -- The time at which authentication began.
Returns: Returns:
True if wpa_supplicant authenticated succesfully, True if wpa_supplicant authenticated succesfully,
False otherwise. False otherwise.
""" """
error= "Unable to find ctrl_interface for wpa_supplicant. " + \ error= "Unable to find ctrl_interface for wpa_supplicant. " + \
"Could not validate authentication." "Could not validate authentication."
# Right now there's no way to do this for ralink drivers # Right now there's no way to do this for ralink drivers
if self.wpa_driver == RALINK_DRIVER: if self.wpa_driver == RALINK_DRIVER:
return True return True
wpa = self._connect_to_wpa_ctrl_iface() wpa = self._connect_to_wpa_ctrl_iface()
if not wpa: if not wpa:
print "Failed to open ctrl interface" print "Failed to open ctrl interface"
return False return False
MAX_TIME = 35 MAX_TIME = 35
MAX_DISCONNECTED_TIME = 3 MAX_DISCONNECTED_TIME = 3
disconnected_time = 0 disconnected_time = 0
@@ -380,15 +382,15 @@ class WirelessInterface(Interface, wnettools.BaseWirelessInterface):
except: except:
print "wpa_supplicant status query failed." print "wpa_supplicant status query failed."
return False return False
if self.verbose: 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: try:
[result] = [l for l in status if l.startswith("wpa_state=")] [result] = [l for l in status if l.startswith("wpa_state=")]
except ValueError: except ValueError:
return False return False
result = result result = result
if result.endswith("COMPLETED"): if result.endswith("COMPLETED"):
return True return True
@@ -404,7 +406,8 @@ class WirelessInterface(Interface, wnettools.BaseWirelessInterface):
print 'wpa_supplicant authentication may have failed.' print 'wpa_supplicant authentication may have failed.'
return False return False
@neediface(False)
def StopWPA(self): def StopWPA(self):
""" Terminates wpa_supplicant using its ctrl interface. """ """ Terminates wpa_supplicant using its ctrl interface. """
wpa = self._connect_to_wpa_ctrl_iface() wpa = self._connect_to_wpa_ctrl_iface()
@@ -433,7 +436,7 @@ class WirelessInterface(Interface, wnettools.BaseWirelessInterface):
info[4] == 'WEP'): info[4] == 'WEP'):
print 'Setting up WEP' print 'Setting up WEP'
cmd = ''.join(['iwconfig ', self.iface, ' key ', cmd = ''.join(['iwconfig ', self.iface, ' key ',
network.get('key')]) network.get('key')])
if self.verbose: print cmd if self.verbose: print cmd
misc.Run(cmd) misc.Run(cmd)
else: else:
@@ -451,7 +454,7 @@ class WirelessInterface(Interface, wnettools.BaseWirelessInterface):
key_name = 'WPAPSK' key_name = 'WPAPSK'
else: else:
print 'Unknown AuthMode, can\'t complete ' + \ print 'Unknown AuthMode, can\'t complete ' + \
'connection process!' 'connection process!'
return return
cmd_list = [] cmd_list = []
@@ -469,9 +472,9 @@ class WirelessInterface(Interface, wnettools.BaseWirelessInterface):
if self.verbose: print cmd if self.verbose: print cmd
misc.Run(cmd) misc.Run(cmd)
@neediface("")
def GetBSSID(self, iwconfig=None): def GetBSSID(self, iwconfig=None):
""" Get the MAC address for the interface. """ """ Get the MAC address for the interface. """
if not self.iface: return ""
data = (self.iface + '\0' * 32)[:32] data = (self.iface + '\0' * 32)[:32]
try: try:
result = fcntl.ioctl(self.sock.fileno(), SIOCGIWAP, data)[16:] result = fcntl.ioctl(self.sock.fileno(), SIOCGIWAP, data)[16:]
@@ -482,9 +485,9 @@ class WirelessInterface(Interface, wnettools.BaseWirelessInterface):
raw_addr = struct.unpack("xxBBBBBB", result[:8]) raw_addr = struct.unpack("xxBBBBBB", result[:8])
return "%02X:%02X:%02X:%02X:%02X:%02X" % raw_addr return "%02X:%02X:%02X:%02X:%02X:%02X" % raw_addr
@neediface("")
def GetCurrentBitrate(self, iwconfig=None): def GetCurrentBitrate(self, iwconfig=None):
""" Get the current bitrate for the interface. """ """ Get the current bitrate for the interface. """
if not self.iface: return ""
data = (self.iface + '\0' * 32)[:32] data = (self.iface + '\0' * 32)[:32]
fmt = "ihbb" fmt = "ihbb"
size = struct.calcsize(fmt) size = struct.calcsize(fmt)
@@ -495,7 +498,7 @@ class WirelessInterface(Interface, wnettools.BaseWirelessInterface):
print "SIOCGIWRATE failed: " + str(e) print "SIOCGIWRATE failed: " + str(e)
return "" return ""
f, e, x, x = struct.unpack(fmt, result[:size]) f, e, x, x = struct.unpack(fmt, result[:size])
return "%s %s" % ((f / 1000000), 'Mb/s') return "%s %s" % ((f / 1000000), 'Mb/s')
#def GetOperationalMode(self, iwconfig=None): #def GetOperationalMode(self, iwconfig=None):
# """ Get the operational mode for the interface. """ # """ Get the operational mode for the interface. """
@@ -507,6 +510,7 @@ class WirelessInterface(Interface, wnettools.BaseWirelessInterface):
# TODO: Implement me # TODO: Implement me
# return '' # return ''
@neediface(-1)
def GetSignalStrength(self, iwconfig=None): def GetSignalStrength(self, iwconfig=None):
""" Get the signal strength of the current network. """ Get the signal strength of the current network.
@@ -514,7 +518,6 @@ class WirelessInterface(Interface, wnettools.BaseWirelessInterface):
The signal strength. The signal strength.
""" """
if not self.iface: return -1
buff = get_iw_ioctl_result(self.iface, SIOCGIWSTATS) buff = get_iw_ioctl_result(self.iface, SIOCGIWSTATS)
strength = ord(buff[2]) strength = ord(buff[2])
max_strength = self._get_max_strength() max_strength = self._get_max_strength()
@@ -524,7 +527,7 @@ class WirelessInterface(Interface, wnettools.BaseWirelessInterface):
return int(strength) return int(strength)
else: else:
return None return None
def _get_max_strength(self): def _get_max_strength(self):
""" Gets the maximum possible strength from the wireless driver. """ """ Gets the maximum possible strength from the wireless driver. """
buff = array.array('c', '\0' * 700) buff = array.array('c', '\0' * 700)
@@ -544,7 +547,8 @@ class WirelessInterface(Interface, wnettools.BaseWirelessInterface):
data = data[0:size] data = data[0:size]
values = struct.unpack(fmt, data) values = struct.unpack(fmt, data)
return values[12] return values[12]
@neediface(-100)
def GetDBMStrength(self, iwconfig=None): def GetDBMStrength(self, iwconfig=None):
""" Get the dBm signal strength of the current network. """ Get the dBm signal strength of the current network.
@@ -552,13 +556,13 @@ class WirelessInterface(Interface, wnettools.BaseWirelessInterface):
The dBm signal strength. The dBm signal strength.
""" """
if not self.iface: return -100
buff = get_iw_ioctl_result(self.iface, SIOCGIWSTATS) buff = get_iw_ioctl_result(self.iface, SIOCGIWSTATS)
if not buff: if not buff:
return None return None
return str((ord(buff[3]) - 256)) return str((ord(buff[3]) - 256))
@neediface("")
def GetCurrentNetwork(self, iwconfig=None): def GetCurrentNetwork(self, iwconfig=None):
""" Get the essid of the current network. """ Get the essid of the current network.
@@ -566,10 +570,8 @@ class WirelessInterface(Interface, wnettools.BaseWirelessInterface):
The current network essid. The current network essid.
""" """
if not self.iface: return ""
buff = get_iw_ioctl_result(self.iface, SIOCGIWESSID) buff = get_iw_ioctl_result(self.iface, SIOCGIWESSID)
if not buff: if not buff:
return None return None
return buff.strip('\x00') return buff.strip('\x00')

View File

@@ -69,7 +69,8 @@ class WicdError(Exception):
__LANG = None __LANG = None
def Run(cmd, include_stderr=False, return_pipe=False, return_obj=False): def Run(cmd, include_stderr=False, return_pipe=False,
return_obj=False, return_retcode=True):
""" Run a command. """ Run a command.
Runs the given command, returning either the output Runs the given command, returning either the output
@@ -81,8 +82,10 @@ def Run(cmd, include_stderr=False, return_pipe=False, return_obj=False):
be included in the pipe to the cmd. be included in the pipe to the cmd.
return_pipe - Boolean specifying if a pipe to the return_pipe - Boolean specifying if a pipe to the
command should be returned. If it is command should be returned. If it is
false, all that will be returned is False, all that will be returned is
one output string from the command. one output string from the command.
return_obj - If True, Run will return the Popen object
for the command that was run.
""" """
global __LANG global __LANG
@@ -135,9 +138,15 @@ def LaunchAndWait(cmd):
""" Launches the given program with the given arguments, then blocks. """ Launches the given program with the given arguments, then blocks.
cmd : A list contained the program name and its arguments. cmd : A list contained the program name and its arguments.
returns: The exit code of the process.
""" """
call(cmd, shell=False) if not isinstance(cmd, list):
cmd = to_unicode(str(cmd))
cmd = cmd.split()
p = Popen(cmd, shell=False, stdout=PIPE, stderr=STDOUT, stdin=None)
return p.wait()
def IsValidIP(ip): def IsValidIP(ip):
""" Make sure an entered IP is valid. """ """ Make sure an entered IP is valid. """

View File

@@ -38,7 +38,7 @@ misc.RenameProcess("wicd-monitor")
if __name__ == '__main__': if __name__ == '__main__':
wpath.chdir(__file__) wpath.chdir(__file__)
dbusmanager.connect_to_dbus() dbusmanager.connect_to_dbus()
dbus_dict = dbusmanager.get_dbus_ifaces() dbus_dict = dbusmanager.get_dbus_ifaces()
daemon = dbus_dict["daemon"] daemon = dbus_dict["daemon"]
@@ -61,7 +61,7 @@ def diewithdbus(func):
mainloop.quit() mainloop.quit()
self.__lost_dbus_count += 1 self.__lost_dbus_count += 1
return True return True
wrapper.__name__ = func.__name__ wrapper.__name__ = func.__name__
wrapper.__dict__ = func.__dict__ wrapper.__dict__ = func.__dict__
wrapper.__doc__ = func.__doc__ wrapper.__doc__ = func.__doc__
@@ -86,7 +86,7 @@ class ConnectionStatus(object):
self.iwconfig = "" self.iwconfig = ""
self.trigger_reconnect = False self.trigger_reconnect = False
self.__lost_dbus_count = 0 self.__lost_dbus_count = 0
bus = dbusmanager.get_bus() bus = dbusmanager.get_bus()
bus.add_signal_receiver(self._force_update_connection_status, bus.add_signal_receiver(self._force_update_connection_status,
"UpdateState", "org.wicd.daemon") "UpdateState", "org.wicd.daemon")
@@ -99,7 +99,7 @@ class ConnectionStatus(object):
in, and the user has chosen to switch to a wired connection in, and the user has chosen to switch to a wired connection
whenever its available, even if already connected to a whenever its available, even if already connected to a
wireless network. wireless network.
2) A wired connection is currently active. 2) A wired connection is currently active.
""" """
@@ -107,7 +107,7 @@ class ConnectionStatus(object):
if not wired_ip and daemon.GetPreferWiredNetwork(): if not wired_ip and daemon.GetPreferWiredNetwork():
if not daemon.GetForcedDisconnect() and wired.CheckPluggedIn(): if not daemon.GetForcedDisconnect() and wired.CheckPluggedIn():
self.trigger_reconnect = True self.trigger_reconnect = True
elif wired_ip and wired.CheckPluggedIn(): elif wired_ip and wired.CheckPluggedIn():
# Only change the interface if it's not already set for wired # Only change the interface if it's not already set for wired
if not self.still_wired: if not self.still_wired:
@@ -128,7 +128,7 @@ class ConnectionStatus(object):
Checks for an active wireless connection. Also notes Checks for an active wireless connection. Also notes
if the signal strength is 0, and if it remains there if the signal strength is 0, and if it remains there
for too long, triggers a wireless disconnect. for too long, triggers a wireless disconnect.
Returns True if wireless connection is active, and Returns True if wireless connection is active, and
False otherwise. False otherwise.
@@ -144,7 +144,7 @@ class ConnectionStatus(object):
self.iwconfig = '' self.iwconfig = ''
# Reset this, just in case. # Reset this, just in case.
self.tried_reconnect = False self.tried_reconnect = False
wifi_signal = self._get_printable_sig_strength() wifi_signal = self._get_printable_sig_strength()
if wifi_signal == 0: if wifi_signal == 0:
# If we have no signal, increment connection loss counter. # If we have no signal, increment connection loss counter.
@@ -165,17 +165,17 @@ class ConnectionStatus(object):
self.last_network = self.network self.last_network = self.network
self.signal_changed = True self.signal_changed = True
daemon.SetCurrentInterface(daemon.GetWirelessInterface()) daemon.SetCurrentInterface(daemon.GetWirelessInterface())
return True return True
@diewithdbus @diewithdbus
def update_connection_status(self): def update_connection_status(self):
""" Updates the tray icon and current connection status. """ Updates the tray icon and current connection status.
Determines the current connection state and sends a dbus signal Determines the current connection state and sends a dbus signal
announcing when the status changes. Also starts the automatic announcing when the status changes. Also starts the automatic
reconnection process if necessary. reconnection process if necessary.
""" """
wired_ip = None wired_ip = None
wifi_ip = None wifi_ip = None
@@ -183,24 +183,21 @@ class ConnectionStatus(object):
if daemon.GetSuspend(): if daemon.GetSuspend():
print "Suspended." print "Suspended."
state = misc.SUSPENDED state = misc.SUSPENDED
self.update_state(state) return self.update_state(state)
return True
# Determine what our current state is. # Determine what our current state is.
# Are we currently connecting? # Are we currently connecting?
if daemon.CheckIfConnecting(): if daemon.CheckIfConnecting():
state = misc.CONNECTING state = misc.CONNECTING
self.update_state(state) return self.update_state(state)
return True
daemon.SendConnectResultsIfAvail() daemon.SendConnectResultsIfAvail()
# Check for wired. # Check for wired.
wired_ip = wired.GetWiredIP("") wired_ip = wired.GetWiredIP("")
wired_found = self.check_for_wired_connection(wired_ip) wired_found = self.check_for_wired_connection(wired_ip)
if wired_found: if wired_found:
self.update_state(misc.WIRED, wired_ip=wired_ip) return self.update_state(misc.WIRED, wired_ip=wired_ip)
return True
# Check for wireless # Check for wireless
wifi_ip = wireless.GetWirelessIP("") wifi_ip = wireless.GetWirelessIP("")
@@ -213,35 +210,32 @@ class ConnectionStatus(object):
# connection is active. So we kill the wireless connection # connection is active. So we kill the wireless connection
# so the autoconnect logic will connect to the wired network. # so the autoconnect logic will connect to the wired network.
self.trigger_reconnect = False self.trigger_reconnect = False
# Don't trigger it if the gui is open, because autoconnect # Don't trigger it if the gui is open, because autoconnect
# is disabled while it's open. # is disabled while it's open.
if not daemon.GetGUIOpen(): if not daemon.GetGUIOpen():
print 'Killing wireless connection to switch to wired...' print 'Killing wireless connection to switch to wired...'
wireless.DisconnectWireless() wireless.DisconnectWireless()
daemon.AutoConnect(False, reply_handler=lambda:None, daemon.AutoConnect(False, reply_handler=lambda *a:None,
error_handler=lambda:None) error_handler=lambda *a:None)
self.update_state(misc.NOT_CONNECTED) return self.update_state(misc.NOT_CONNECTED)
return True return self.update_state(misc.WIRELESS, wifi_ip=wifi_ip)
self.update_state(misc.WIRELESS, wifi_ip=wifi_ip)
return True
state = misc.NOT_CONNECTED state = misc.NOT_CONNECTED
if self.last_state == misc.WIRELESS: if self.last_state == misc.WIRELESS:
from_wireless = True from_wireless = True
else: else:
from_wireless = False from_wireless = False
self.auto_reconnect(from_wireless) self.auto_reconnect(from_wireless)
self.update_state(state) return self.update_state(state)
return True
def _force_update_connection_status(self): def _force_update_connection_status(self):
""" Run a connection status update on demand. """ Run a connection status update on demand.
Removes the scheduled update_connection_status() Removes the scheduled update_connection_status()
call, explicitly calls the function, and reschedules call, explicitly calls the function, and reschedules
it. it.
""" """
global update_callback global update_callback
gobject.source_remove(update_callback) gobject.source_remove(update_callback)
@@ -272,6 +266,7 @@ class ConnectionStatus(object):
else: else:
print 'ERROR: Invalid state!' print 'ERROR: Invalid state!'
return True return True
daemon.SetConnectionStatus(state, info) daemon.SetConnectionStatus(state, info)
# Send a D-Bus signal announcing status has changed if necessary. # Send a D-Bus signal announcing status has changed if necessary.
@@ -280,7 +275,7 @@ class ConnectionStatus(object):
daemon.EmitStatusChanged(state, info) daemon.EmitStatusChanged(state, info)
self.last_state = state self.last_state = state
return True return True
def _get_printable_sig_strength(self): def _get_printable_sig_strength(self):
""" Get the correct signal strength format. """ """ Get the correct signal strength format. """
try: try:
@@ -290,7 +285,7 @@ class ConnectionStatus(object):
wifi_signal = int(wireless.GetCurrentDBMStrength(self.iwconfig)) wifi_signal = int(wireless.GetCurrentDBMStrength(self.iwconfig))
except TypeError: except TypeError:
wifi_signal = 0 wifi_signal = 0
return wifi_signal return wifi_signal
def auto_reconnect(self, from_wireless=None): def auto_reconnect(self, from_wireless=None):
@@ -303,37 +298,37 @@ class ConnectionStatus(object):
""" """
if self.reconnecting: if self.reconnecting:
return return
# Some checks to keep reconnect retries from going crazy. # Some checks to keep reconnect retries from going crazy.
if (self.reconnect_tries > 3 and if (self.reconnect_tries > 3 and
(time.time() - self.last_reconnect_time) < 200): (time.time() - self.last_reconnect_time) < 200):
print "Throttling autoreconnect" print "Throttling autoreconnect"
return return
self.reconnecting = True self.reconnecting = True
daemon.SetCurrentInterface('') daemon.SetCurrentInterface('')
if daemon.ShouldAutoReconnect(): if daemon.ShouldAutoReconnect():
print 'Starting automatic reconnect process' print 'Starting automatic reconnect process'
self.last_reconnect_time = time.time() self.last_reconnect_time = time.time()
self.reconnect_tries += 1 self.reconnect_tries += 1
# If we just lost a wireless connection, try to connect to that # If we just lost a wireless connection, try to connect to that
# network again. Otherwise just call Autoconnect. # network again. Otherwise just call Autoconnect.
cur_net_id = wireless.GetCurrentNetworkID(self.iwconfig) cur_net_id = wireless.GetCurrentNetworkID(self.iwconfig)
if from_wireless and cur_net_id > -1: if from_wireless and cur_net_id > -1:
print 'Trying to reconnect to last used wireless ' + \ print 'Trying to reconnect to last used wireless ' + \
'network' 'network'
wireless.ConnectWireless(cur_net_id) wireless.ConnectWireless(cur_net_id)
else: else:
daemon.AutoConnect(True, reply_handler=reply_handle, daemon.AutoConnect(True, reply_handler=reply_handle,
error_handler=err_handle) error_handler=err_handle)
self.reconnecting = False self.reconnecting = False
def reply_handle(): def reply_handle():
""" Just a dummy function needed for asynchronous dbus calls. """ """ Just a dummy function needed for asynchronous dbus calls. """
pass pass
def err_handle(error): def err_handle(error):
""" Just a dummy function needed for asynchronous dbus calls. """ """ Just a dummy function needed for asynchronous dbus calls. """
pass pass
@@ -343,16 +338,16 @@ def add_poll_callback():
update_callback = misc.timeout_add(to_time, update_callback = misc.timeout_add(to_time,
monitor.update_connection_status) monitor.update_connection_status)
def main(): def main():
""" Starts the connection monitor. """ Starts the connection monitor.
Starts a ConnectionStatus instance, sets the status to update Starts a ConnectionStatus instance, sets the status to update
an amount of time determined by the active backend. an amount of time determined by the active backend.
""" """
global monitor, to_time, mainloop global monitor, to_time, mainloop
monitor = ConnectionStatus() monitor = ConnectionStatus()
to_time = daemon.GetBackendUpdateInterval() to_time = daemon.GetBackendUpdateInterval()
add_poll_callback() add_poll_callback()

View File

@@ -425,7 +425,30 @@ class ConnectThread(threading.Thread):
if self.connect_result != "aborted": if self.connect_result != "aborted":
self.abort_connection(dhcp_status) self.abort_connection(dhcp_status)
return return
@abortable
def verify_association(self, iface):
""" Verify that our association the AP is valid.
Try to ping the gateway we have set to see if we're
really associated with it. This is only done if
we're using a static IP.
"""
if self.network.get('gateway'):
self.SetStatus('verifying_association')
print "Verifying AP association"
retcode = self.iface.VerifyAPAssociation(self.network['gateway'])
#TODO this should be in wnettools.py
if retcode:
print "Connection Failed: Failed to ping the access point!"
# Clean up before aborting.
iface.SetAddress('0.0.0.0')
iface.FlushRoutes()
if hasattr(iface, "StopWPA"):
iface.StopWPA()
self.abort_connection("association_failed")
@abortable @abortable
def set_dns_addresses(self, iface): def set_dns_addresses(self, iface):
""" Set the DNS address(es). """ Set the DNS address(es).
@@ -838,6 +861,7 @@ class WirelessConnectThread(ConnectThread):
self.set_broadcast_address(wiface) self.set_broadcast_address(wiface)
self.set_ip_address(wiface) self.set_ip_address(wiface)
self.set_dns_addresses(wiface) self.set_dns_addresses(wiface)
self.verify_association(wiface)
# Run post-connection script. # Run post-connection script.
self.run_global_scripts_if_needed(wpath.postconnectscripts) self.run_global_scripts_if_needed(wpath.postconnectscripts)

View File

@@ -153,6 +153,8 @@ language['dhcp_failed'] = _('Connection Failed: Unable to Get IP Address')
language['no_dhcp_offers'] = _('Connection Failed: No DHCP offers received.') language['no_dhcp_offers'] = _('Connection Failed: No DHCP offers received.')
language['aborted'] = _('Connection Cancelled') language['aborted'] = _('Connection Cancelled')
language['bad_pass'] = _('Connection Failed: Could not authenticate (bad password?)') language['bad_pass'] = _('Connection Failed: Could not authenticate (bad password?)')
language['verifying_association'] = _("Verifying access point association...")
language['association_failed'] = _("Connection Failed: Could not contact the wireless access point.")
language['done'] = _('Done connecting...') language['done'] = _('Done connecting...')
language['scanning'] = _('Scanning') language['scanning'] = _('Scanning')
language['scanning_stand_by'] = _('Scanning networks... stand by...') language['scanning_stand_by'] = _('Scanning networks... stand by...')

View File

@@ -143,6 +143,25 @@ def IsValidWpaSuppDriver(driver):
return False return False
else: else:
return True return True
def neediface(default_response):
""" A decorator for only running a method if self.iface is defined.
This decorator is wrapped around Interface methods, and will
return a provided default_response value if self.iface is not
defined.
"""
def wrapper(func):
def newfunc(self, *args, **kwargs):
if not self.iface:
return default_response
return func(self, *args, **kwargs)
newfunc.__dict__ = func.__dict__
newfunc.__doc__ = func.__doc__
newfunc.__module__ = func.__module__
return newfunc
return wrapper
class BaseInterface(object): class BaseInterface(object):
@@ -304,6 +323,7 @@ class BaseInterface(object):
self.kdesu_cmd = self._find_program_path("kdesu") self.kdesu_cmd = self._find_program_path("kdesu")
self.ktsuss_cmd = self._find_program_path("ktsuss") self.ktsuss_cmd = self._find_program_path("ktsuss")
@neediface(False)
def Up(self): def Up(self):
""" Bring the network interface up. """ Bring the network interface up.
@@ -311,12 +331,12 @@ class BaseInterface(object):
True True
""" """
if not self.iface: return False
cmd = 'ifconfig ' + self.iface + ' up' cmd = 'ifconfig ' + self.iface + ' up'
if self.verbose: print cmd if self.verbose: print cmd
misc.Run(cmd) misc.Run(cmd)
return True return True
@neediface(False)
def Down(self): def Down(self):
""" Take down the network interface. """ Take down the network interface.
@@ -324,12 +344,12 @@ class BaseInterface(object):
True True
""" """
if not self.iface: return False
cmd = 'ifconfig ' + self.iface + ' down' cmd = 'ifconfig ' + self.iface + ' down'
if self.verbose: print cmd if self.verbose: print cmd
misc.Run(cmd) misc.Run(cmd)
return True return True
@neediface("")
def SetAddress(self, ip=None, netmask=None, broadcast=None): def SetAddress(self, ip=None, netmask=None, broadcast=None):
""" Set the IP addresses of an interface. """ Set the IP addresses of an interface.
@@ -339,9 +359,6 @@ class BaseInterface(object):
broadcast -- broadcast address in dotted quad form broadcast -- broadcast address in dotted quad form
""" """
if not self.iface:
return
for val in [ip, netmask, broadcast]: for val in [ip, netmask, broadcast]:
if not val: if not val:
continue continue
@@ -452,6 +469,7 @@ class BaseInterface(object):
print 'DHCP connection failed' print 'DHCP connection failed'
return 'dhcp_failed' return 'dhcp_failed'
@neediface
def StartDHCP(self): def StartDHCP(self):
""" Start the DHCP client to obtain an IP address. """ Start the DHCP client to obtain an IP address.
@@ -460,8 +478,6 @@ class BaseInterface(object):
_check_dhcp_result for the possible values. _check_dhcp_result for the possible values.
""" """
if not self.iface: return False
cmd = self._get_dhcp_command('connect') cmd = self._get_dhcp_command('connect')
if self.verbose: print cmd if self.verbose: print cmd
self.dhcp_object = misc.Run(cmd, include_stderr=True, return_obj=True) self.dhcp_object = misc.Run(cmd, include_stderr=True, return_obj=True)
@@ -477,16 +493,16 @@ class BaseInterface(object):
else: else:
print 'ERROR no dhclient found!' print 'ERROR no dhclient found!'
@neediface
def ReleaseDHCP(self): def ReleaseDHCP(self):
""" Release the DHCP lease for this interface. """ """ Release the DHCP lease for this interface. """
if not self.iface: return False
cmd = self._get_dhcp_command("release") cmd = self._get_dhcp_command("release")
if self.verbose: print cmd if self.verbose: print cmd
misc.Run(cmd) misc.Run(cmd)
@neediface
def DelDefaultRoute(self): def DelDefaultRoute(self):
""" Delete only the default route for a device. """ """ Delete only the default route for a device. """
if not self.iface: return False
if self.ip_cmd and self.flush_tool in [misc.AUTO, misc.IP]: if self.ip_cmd and self.flush_tool in [misc.AUTO, misc.IP]:
cmd = '%s route del default dev %s' % (self.ip_cmd, self.iface) cmd = '%s route del default dev %s' % (self.ip_cmd, self.iface)
elif self.route_cmd and self.flush_tool in [misc.AUTO, misc.ROUTE]: elif self.route_cmd and self.flush_tool in [misc.AUTO, misc.ROUTE]:
@@ -497,6 +513,7 @@ class BaseInterface(object):
if self.verbose: print cmd if self.verbose: print cmd
misc.Run(cmd) misc.Run(cmd)
@neediface
def SetDNS(self, dns1=None, dns2=None, dns3=None, def SetDNS(self, dns1=None, dns2=None, dns3=None,
dns_dom=None, search_dom=None): dns_dom=None, search_dom=None):
""" Set the DNS of the system to the specified DNS servers. """ Set the DNS of the system to the specified DNS servers.
@@ -511,7 +528,6 @@ class BaseInterface(object):
search_dom -- DNS search domain search_dom -- DNS search domain
""" """
if not self.iface: return False
resolv_params = "" resolv_params = ""
if dns_dom: if dns_dom:
resolv_params += 'domain %s\n' % dns_dom resolv_params += 'domain %s\n' % dns_dom
@@ -541,9 +557,9 @@ class BaseInterface(object):
resolv.write(resolv_params + "\n") resolv.write(resolv_params + "\n")
resolv.close() resolv.close()
@neediface
def FlushRoutes(self): def FlushRoutes(self):
""" Flush network routes for this device. """ """ Flush network routes for this device. """
if not self.iface: return False
if self.ip_cmd and self.flush_tool in [misc.AUTO, misc.IP]: if self.ip_cmd and self.flush_tool in [misc.AUTO, misc.IP]:
cmds = ['%s route flush dev %s' % (self.ip_cmd, self.iface)] cmds = ['%s route flush dev %s' % (self.ip_cmd, self.iface)]
elif self.route_cmd and self.flush_tool in [misc.AUTO, misc.ROUTE]: elif self.route_cmd and self.flush_tool in [misc.AUTO, misc.ROUTE]:
@@ -555,6 +571,7 @@ class BaseInterface(object):
if self.verbose: print cmd if self.verbose: print cmd
misc.Run(cmd) misc.Run(cmd)
@neediface
def SetDefaultRoute(self, gw): def SetDefaultRoute(self, gw):
""" Add a default route with the specified gateway. """ Add a default route with the specified gateway.
@@ -562,7 +579,6 @@ class BaseInterface(object):
gw -- gateway of the default route in dotted quad form gw -- gateway of the default route in dotted quad form
""" """
if not self.iface: return
if not misc.IsValidIP(gw): if not misc.IsValidIP(gw):
print 'WARNING: Invalid gateway found. Aborting!' print 'WARNING: Invalid gateway found. Aborting!'
return False return False
@@ -570,6 +586,7 @@ class BaseInterface(object):
if self.verbose: print cmd if self.verbose: print cmd
misc.Run(cmd) misc.Run(cmd)
@neediface("")
def GetIP(self, ifconfig=""): def GetIP(self, ifconfig=""):
""" Get the IP address of the interface. """ Get the IP address of the interface.
@@ -585,6 +602,19 @@ class BaseInterface(object):
output = ifconfig output = ifconfig
return misc.RunRegex(ip_pattern, output) return misc.RunRegex(ip_pattern, output)
@neediface(False)
def VerifyAPAssociation(self, gateway):
""" Verify assocation with an access point.
Verifies that an access point can be contacted by
trying to ping it.
"""
cmd = "ping -q -w 3 -c 1 %s" % gateway
if self.verbose: print cmd
return misc.LaunchAndWait(cmd)
@neediface(False)
def IsUp(self, ifconfig=None): def IsUp(self, ifconfig=None):
""" Determines if the interface is up. """ Determines if the interface is up.
@@ -592,7 +622,6 @@ class BaseInterface(object):
True if the interface is up, False otherwise. True if the interface is up, False otherwise.
""" """
if not self.iface: return False
flags_file = '/sys/class/net/%s/flags' % self.iface flags_file = '/sys/class/net/%s/flags' % self.iface
try: try:
flags = open(flags_file, "r").read().strip() flags = open(flags_file, "r").read().strip()
@@ -631,6 +660,7 @@ class BaseWiredInterface(BaseInterface):
""" """
BaseInterface.__init__(self, iface, verbose) BaseInterface.__init__(self, iface, verbose)
@neediface(False)
def GetPluggedIn(self): def GetPluggedIn(self):
""" Get the current physical connection state. """ Get the current physical connection state.
@@ -642,8 +672,6 @@ class BaseWiredInterface(BaseInterface):
True if a link is detected, False otherwise. True if a link is detected, False otherwise.
""" """
if not self.iface:
return False
# check for link using /sys/class/net/iface/carrier # check for link using /sys/class/net/iface/carrier
# is usually more accurate # is usually more accurate
sys_device = '/sys/class/net/%s/' % self.iface sys_device = '/sys/class/net/%s/' % self.iface
@@ -741,6 +769,7 @@ class BaseWirelessInterface(BaseInterface):
""" Sets the wpa_driver. """ """ Sets the wpa_driver. """
self.wpa_driver = _sanitize_string(driver) self.wpa_driver = _sanitize_string(driver)
@neediface(False)
def SetEssid(self, essid): def SetEssid(self, essid):
""" Set the essid of the wireless interface. """ Set the essid of the wireless interface.
@@ -752,6 +781,7 @@ class BaseWirelessInterface(BaseInterface):
if self.verbose: print str(cmd) if self.verbose: print str(cmd)
misc.Run(cmd) misc.Run(cmd)
@neediface(False)
def GetKillSwitchStatus(self): def GetKillSwitchStatus(self):
""" Determines if the wireless killswitch is enabled. """ Determines if the wireless killswitch is enabled.
@@ -759,7 +789,6 @@ class BaseWirelessInterface(BaseInterface):
True if the killswitch is enabled, False otherwise. True if the killswitch is enabled, False otherwise.
""" """
if not self.iface: return False
output = self.GetIwconfig() output = self.GetIwconfig()
killswitch_pattern = re.compile('.*radio off', re.I | re.M | re.S) killswitch_pattern = re.compile('.*radio off', re.I | re.M | re.S)
@@ -770,9 +799,9 @@ class BaseWirelessInterface(BaseInterface):
return radiostatus return radiostatus
@neediface(False)
def GetIwconfig(self): def GetIwconfig(self):
""" Returns the output of iwconfig for this interface. """ """ Returns the output of iwconfig for this interface. """
if not self.iface: return ""
cmd = "iwconfig " + self.iface cmd = "iwconfig " + self.iface
if self.verbose: print cmd if self.verbose: print cmd
return misc.Run(cmd) return misc.Run(cmd)
@@ -881,6 +910,7 @@ class BaseWirelessInterface(BaseInterface):
ap['encryption'] = False ap['encryption'] = False
return ap return ap
@neediface(False)
def SetMode(self, mode): def SetMode(self, mode):
""" Set the mode of the wireless interface. """ Set the mode of the wireless interface.
@@ -888,7 +918,6 @@ class BaseWirelessInterface(BaseInterface):
mode -- mode to set the interface to mode -- mode to set the interface to
""" """
if not self.iface: return False
mode = _sanitize_string_strict(mode) mode = _sanitize_string_strict(mode)
if mode.lower() == 'master': if mode.lower() == 'master':
mode = 'managed' mode = 'managed'
@@ -896,6 +925,7 @@ class BaseWirelessInterface(BaseInterface):
if self.verbose: print cmd if self.verbose: print cmd
misc.Run(cmd) misc.Run(cmd)
@neediface(False)
def SetChannel(self, channel): def SetChannel(self, channel):
""" Set the channel of the wireless interface. """ Set the channel of the wireless interface.
@@ -903,7 +933,6 @@ class BaseWirelessInterface(BaseInterface):
channel -- channel to set the interface to channel -- channel to set the interface to
""" """
if not self.iface: return False
if not channel.isdigit(): if not channel.isdigit():
print 'WARNING: Invalid channel found. Aborting!' print 'WARNING: Invalid channel found. Aborting!'
return False return False
@@ -912,6 +941,7 @@ class BaseWirelessInterface(BaseInterface):
if self.verbose: print cmd if self.verbose: print cmd
misc.Run(cmd) misc.Run(cmd)
@neediface(False)
def SetKey(self, key): def SetKey(self, key):
""" Set the encryption key of the wireless interface. """ Set the encryption key of the wireless interface.
@@ -919,11 +949,11 @@ class BaseWirelessInterface(BaseInterface):
key -- encryption key to set key -- encryption key to set
""" """
if not self.iface: return False
cmd = 'iwconfig %s key %s' % (self.iface, key) cmd = 'iwconfig %s key %s' % (self.iface, key)
if self.verbose: print cmd if self.verbose: print cmd
misc.Run(cmd) misc.Run(cmd)
@neediface(False)
def Associate(self, essid, channel=None, bssid=None): def Associate(self, essid, channel=None, bssid=None):
""" Associate with the specified wireless network. """ Associate with the specified wireless network.
@@ -933,7 +963,6 @@ class BaseWirelessInterface(BaseInterface):
bssid -- bssid of the network bssid -- bssid of the network
""" """
if not self.iface: return False
cmd = ['iwconfig', self.iface, 'essid', essid] cmd = ['iwconfig', self.iface, 'essid', essid]
if channel and str(channel).isdigit(): if channel and str(channel).isdigit():
cmd.extend(['channel', str(channel)]) cmd.extend(['channel', str(channel)])
@@ -957,6 +986,7 @@ class BaseWirelessInterface(BaseInterface):
if self.verbose: print cmd if self.verbose: print cmd
return misc.RunRegex(key_pattern, misc.Run(cmd)) return misc.RunRegex(key_pattern, misc.Run(cmd))
@neediface(False)
def Authenticate(self, network): def Authenticate(self, network):
""" Authenticate with the specified wireless network. """ Authenticate with the specified wireless network.
@@ -1014,6 +1044,7 @@ class BaseWirelessInterface(BaseInterface):
if self.verbose: print ' '.join(cmd) if self.verbose: print ' '.join(cmd)
misc.Run(cmd) misc.Run(cmd)
@neediface([])
def GetNetworks(self): def GetNetworks(self):
""" Get a list of available wireless networks. """ Get a list of available wireless networks.
@@ -1191,12 +1222,14 @@ class BaseWirelessInterface(BaseInterface):
cmd = 'wpa_cli -i' + self.iface + ' scan' cmd = 'wpa_cli -i' + self.iface + ' scan'
misc.Run(cmd) misc.Run(cmd)
@neediface(False)
def StopWPA(self): def StopWPA(self):
""" Terminates wpa using wpa_cli""" """ Terminates wpa using wpa_cli"""
cmd = 'wpa_cli -i %s terminate' % self.iface cmd = 'wpa_cli -i %s terminate' % self.iface
if self.verbose: print cmd if self.verbose: print cmd
misc.Run(cmd) misc.Run(cmd)
@neediface("")
def GetBSSID(self, iwconfig=None): def GetBSSID(self, iwconfig=None):
""" Get the MAC address for the interface. """ """ Get the MAC address for the interface. """
if not iwconfig: if not iwconfig:
@@ -1209,6 +1242,7 @@ class BaseWirelessInterface(BaseInterface):
bssid = misc.RunRegex(bssid_pattern, output) bssid = misc.RunRegex(bssid_pattern, output)
return bssid return bssid
@neediface("")
def GetCurrentBitrate(self, iwconfig=None): def GetCurrentBitrate(self, iwconfig=None):
""" Get the current bitrate for the interface. """ """ Get the current bitrate for the interface. """
if not iwconfig: if not iwconfig:
@@ -1221,6 +1255,7 @@ class BaseWirelessInterface(BaseInterface):
bitrate = misc.RunRegex(bitrate_pattern, output) bitrate = misc.RunRegex(bitrate_pattern, output)
return bitrate return bitrate
@neediface("")
def GetOperationalMode(self, iwconfig=None): def GetOperationalMode(self, iwconfig=None):
""" Get the operational mode for the interface. """ """ Get the operational mode for the interface. """
if not iwconfig: if not iwconfig:
@@ -1235,6 +1270,7 @@ class BaseWirelessInterface(BaseInterface):
opmode = opmode.strip() opmode = opmode.strip()
return opmode return opmode
@neediface("")
def GetAvailableAuthMethods(self, iwlistauth=None): def GetAvailableAuthMethods(self, iwlistauth=None):
""" Get the available authentication methods for the interface. """ """ Get the available authentication methods for the interface. """
if not iwlistauth: if not iwlistauth:
@@ -1264,6 +1300,7 @@ class BaseWirelessInterface(BaseInterface):
else: else:
return None return None
@neediface(-1)
def GetSignalStrength(self, iwconfig=None): def GetSignalStrength(self, iwconfig=None):
""" Get the signal strength of the current network. """ Get the signal strength of the current network.
@@ -1279,6 +1316,7 @@ class BaseWirelessInterface(BaseInterface):
output = iwconfig output = iwconfig
return self._get_link_quality(output) return self._get_link_quality(output)
@neediface(-100)
def GetDBMStrength(self, iwconfig=None): def GetDBMStrength(self, iwconfig=None):
""" Get the dBm signal strength of the current network. """ Get the dBm signal strength of the current network.
@@ -1297,6 +1335,7 @@ class BaseWirelessInterface(BaseInterface):
dbm_strength = misc.RunRegex(signaldbm_pattern, output) dbm_strength = misc.RunRegex(signaldbm_pattern, output)
return dbm_strength return dbm_strength
@neediface("")
def GetCurrentNetwork(self, iwconfig=None): def GetCurrentNetwork(self, iwconfig=None):
""" Get the essid of the current network. """ Get the essid of the current network.
@@ -1315,4 +1354,3 @@ class BaseWirelessInterface(BaseInterface):
if network: if network:
network = misc.to_unicode(network) network = misc.to_unicode(network)
return network return network