1
0
mirror of https://github.com/gryf/wicd.git synced 2025-12-19 04:20:22 +01:00

Style changes for python files

This commit is contained in:
2020-08-01 11:25:13 +02:00
parent c401f2963b
commit 40a7a8ac5d
32 changed files with 2775 additions and 2614 deletions

View File

@@ -17,9 +17,11 @@
# MA 02110-1301, USA. # MA 02110-1301, USA.
import optparse import optparse
import sys
import dbus import dbus
import dbus.service import dbus.service
import sys
from wicd import misc from wicd import misc
from wicd.translations import _ from wicd.translations import _
@@ -52,13 +54,13 @@ try:
'org.wicd.daemon.config' 'org.wicd.daemon.config'
) )
except dbus.DBusException: except dbus.DBusException:
print(('Error: Could not connect to the daemon. ' + \ print('Error: Could not connect to the daemon. Please make sure it is '
'Please make sure it is running.')) 'running.')
sys.exit(3) sys.exit(3)
if not daemon: if not daemon:
print(('Error connecting to wicd via D-Bus. ' + \ print('Error connecting to wicd via D-Bus. Please make sure the wicd '
'Please make sure the wicd service is running.')) 'service is running.')
sys.exit(3) sys.exit(3)
parser = optparse.OptionParser() parser = optparse.OptionParser()
@@ -71,7 +73,8 @@ parser.add_option('--name', '-m')
parser.add_option('--scan', '-S', default=False, action='store_true') parser.add_option('--scan', '-S', default=False, action='store_true')
parser.add_option('--save', '-w', default=False, action='store_true') parser.add_option('--save', '-w', default=False, action='store_true')
parser.add_option('--list-networks', '-l', default=False, action='store_true') parser.add_option('--list-networks', '-l', default=False, action='store_true')
parser.add_option('--network-details', '-d', default=False, action='store_true') parser.add_option('--network-details', '-d', default=False,
action='store_true')
parser.add_option('--disconnect', '-x', default=False, action='store_true') parser.add_option('--disconnect', '-x', default=False, action='store_true')
parser.add_option('--connect', '-c', default=False, action='store_true') parser.add_option('--connect', '-c', default=False, action='store_true')
parser.add_option('--list-encryption-types', '-e', default=False, parser.add_option('--list-encryption-types', '-e', default=False,
@@ -88,8 +91,8 @@ options, arguments = parser.parse_args()
op_performed = False op_performed = False
if not (options.wireless or options.wired) and not options.status: if not (options.wireless or options.wired) and not options.status:
print(("Please use --wireless or --wired to specify " + \ print("Please use --wireless or --wired to specify the type of "
"the type of connection to operate on.")) "connection to operate on.")
if options.status: if options.status:
status, info = daemon.GetConnectionStatus() status, info = daemon.GetConnectionStatus()
@@ -109,46 +112,47 @@ if options.status:
print((_('Connection type') + ': ' + conn_type)) print((_('Connection type') + ': ' + conn_type))
if status == misc.WIRELESS: if status == misc.WIRELESS:
strength = daemon.FormatSignalForPrinting(info[2]) strength = daemon.FormatSignalForPrinting(info[2])
print((_('Connected to $A at $B (IP: $C)') \ print(_('Connected to $A at $B (IP: $C)')
.replace('$A', info[1]) \ .replace('$A', info[1])
.replace('$B', strength) \ .replace('$B', strength)
.replace('$C', info[0]))) .replace('$C', info[0]))
print((_('Network ID: $A') \ print(_('Network ID: $A').replace('$A', info[3]))
.replace('$A', info[3])))
else: else:
print((_('Connected to wired network (IP: $A)') \ print(_('Connected to wired network (IP: $A)')
.replace('$A', info[0]))) .replace('$A', info[0]))
else: else:
if status == misc.CONNECTING: if status == misc.CONNECTING:
if info[0] == 'wired': if info[0] == 'wired':
print((_('Connecting to wired network.'))) print(_('Connecting to wired network.'))
elif info[0] == 'wireless': elif info[0] == 'wireless':
print((_('Connecting to wireless network "$A".') \ print(_('Connecting to wireless network "$A".')
.replace('$A', info[1]))) .replace('$A', info[1]))
op_performed = True op_performed = True
# functions
def is_valid_wireless_network_id(network_id): def is_valid_wireless_network_id(network_id):
""" Check if it's a valid wireless network. '""" """Check if it's a valid wireless network."""
if not (network_id >= 0 \ if not (network_id >= 0 and
and network_id < wireless.GetNumberOfNetworks()): network_id < wireless.GetNumberOfNetworks()):
print('Invalid wireless network identifier.') print('Invalid wireless network identifier.')
sys.exit(1) sys.exit(1)
def is_valid_wired_network_id(network_id): def is_valid_wired_network_id(network_id):
""" Check if it's a valid wired network. '""" """Check if it's a valid wired network. """
num = len(wired.GetWiredProfileList()) num = len(wired.GetWiredProfileList())
if not (network_id < num and \ if not (network_id < num and network_id >= 0):
network_id >= 0):
print('Invalid wired network identifier.') print('Invalid wired network identifier.')
sys.exit(4) sys.exit(4)
def is_valid_wired_network_profile(profile_name): def is_valid_wired_network_profile(profile_name):
""" Check if it's a valid wired network profile. '""" """Check if it's a valid wired network profile. """
if not profile_name in wired.GetWiredProfileList(): if profile_name not in wired.GetWiredProfileList():
print('Profile of that name does not exist.') print('Profile of that name does not exist.')
sys.exit(5) sys.exit(5)
if options.scan and options.wireless: if options.scan and options.wireless:
# synchronized scan # synchronized scan
wireless.Scan(True) wireless.Scan(True)
@@ -163,10 +167,11 @@ if options.list_networks:
if options.wireless: if options.wireless:
print('#\tBSSID\t\t\tChannel\tESSID') print('#\tBSSID\t\t\tChannel\tESSID')
for network_id in range(0, wireless.GetNumberOfNetworks()): for network_id in range(0, wireless.GetNumberOfNetworks()):
print(('%s\t%s\t%s\t%s' % (network_id, print('%s\t%s\t%s\t%s' %
(network_id,
wireless.GetWirelessProperty(network_id, 'bssid'), wireless.GetWirelessProperty(network_id, 'bssid'),
wireless.GetWirelessProperty(network_id, 'channel'), wireless.GetWirelessProperty(network_id, 'channel'),
wireless.GetWirelessProperty(network_id, 'essid')))) wireless.GetWirelessProperty(network_id, 'essid')))
elif options.wired: elif options.wired:
print('#\tProfile name') print('#\tProfile name')
i = 0 i = 0
@@ -186,22 +191,22 @@ if options.network_details:
# we're connected to a network, print IP # we're connected to a network, print IP
print(("IP: %s" % wireless.GetWirelessIP(0))) print(("IP: %s" % wireless.GetWirelessIP(0)))
print(("Essid: %s" % wireless.GetWirelessProperty(network_id, "essid"))) print("Essid: %s" % wireless.GetWirelessProperty(network_id, "essid"))
print(("Bssid: %s" % wireless.GetWirelessProperty(network_id, "bssid"))) print("Bssid: %s" % wireless.GetWirelessProperty(network_id, "bssid"))
if wireless.GetWirelessProperty(network_id, "encryption"): if wireless.GetWirelessProperty(network_id, "encryption"):
print("Encryption: On") print("Encryption: On")
print(("Encryption Method: %s" % \ print("Encryption Method: %s" %
wireless.GetWirelessProperty(network_id, "encryption_method"))) wireless.GetWirelessProperty(network_id,
"encryption_method"))
else: else:
print("Encryption: Off") print("Encryption: Off")
print(("Quality: %s" % \ print("Quality: %s" %
wireless.GetWirelessProperty(network_id, "quality"))) wireless.GetWirelessProperty(network_id, "quality"))
print(("Mode: %s" % \ print("Mode: %s" % wireless.GetWirelessProperty(network_id, "mode"))
wireless.GetWirelessProperty(network_id, "mode"))) print("Channel: %s" %
print(("Channel: %s" % \ wireless.GetWirelessProperty(network_id, "channel"))
wireless.GetWirelessProperty(network_id, "channel"))) print("Bit Rates: %s" %
print(("Bit Rates: %s" % \ wireless.GetWirelessProperty(network_id, "bitrates"))
wireless.GetWirelessProperty(network_id, "bitrates")))
op_performed = True op_performed = True
# network properties # network properties
@@ -216,11 +221,11 @@ if options.network_property:
network_id = wireless.GetCurrentNetworkID(0) network_id = wireless.GetCurrentNetworkID(0)
is_valid_wireless_network_id(network_id) is_valid_wireless_network_id(network_id)
if not options.set_to: if not options.set_to:
print((wireless.GetWirelessProperty(network_id, print(wireless.GetWirelessProperty(network_id,
options.network_property))) options.network_property))
else: else:
wireless.SetWirelessProperty(network_id, \ wireless.SetWirelessProperty(network_id, options.network_property,
options.network_property, options.set_to) options.set_to)
elif options.wired: elif options.wired:
if not options.set_to: if not options.set_to:
print((wired.GetWiredProperty(options.network_property))) print((wired.GetWiredProperty(options.network_property)))
@@ -232,13 +237,13 @@ if options.disconnect:
daemon.Disconnect() daemon.Disconnect()
if options.wireless: if options.wireless:
if wireless.GetCurrentNetworkID(0) > -1: if wireless.GetCurrentNetworkID(0) > -1:
print(("Disconnecting from %s on %s" % \ print("Disconnecting from %s on %s" %
(wireless.GetCurrentNetwork(0), (wireless.GetCurrentNetwork(0),
wireless.DetectWirelessInterface()))) wireless.DetectWirelessInterface()))
elif options.wired: elif options.wired:
if wired.CheckPluggedIn(): if wired.CheckPluggedIn():
print(("Disconnecting from wired connection on %s" % \ print("Disconnecting from wired connection on %s" %
wired.DetectWiredInterface())) wired.DetectWiredInterface())
op_performed = True op_performed = True
if options.connect: if options.connect:
@@ -247,16 +252,16 @@ if options.connect:
is_valid_wireless_network_id(options.network) is_valid_wireless_network_id(options.network)
name = wireless.GetWirelessProperty(options.network, 'essid') name = wireless.GetWirelessProperty(options.network, 'essid')
encryption = wireless.GetWirelessProperty(options.network, 'enctype') encryption = wireless.GetWirelessProperty(options.network, 'enctype')
print(("Connecting to %s with %s on %s" % (name, encryption, print("Connecting to %s with %s on %s" %
wireless.DetectWirelessInterface()))) (name, encryption, wireless.DetectWirelessInterface()))
wireless.ConnectWireless(options.network) wireless.ConnectWireless(options.network)
check = wireless.CheckIfWirelessConnecting check = wireless.CheckIfWirelessConnecting
status = wireless.CheckWirelessConnectingStatus status = wireless.CheckWirelessConnectingStatus
message = wireless.CheckWirelessConnectingMessage message = wireless.CheckWirelessConnectingMessage
elif options.wired: elif options.wired:
print(("Connecting to wired connection on %s" % \ print("Connecting to wired connection on %s" %
wired.DetectWiredInterface())) wired.DetectWiredInterface())
wired.ConnectWired() wired.ConnectWired()
check = wired.CheckIfWiredConnecting check = wired.CheckIfWiredConnecting
@@ -273,8 +278,8 @@ if options.connect:
while check(): while check():
next_ = status() next_ = status()
if next_ != last: if next_ != last:
# avoid a race condition where status is updated to "done" after # avoid a race condition where status is updated to "done"
# the loop check # after the loop check
if next_ == "done": if next_ == "done":
break break
print((message())) print((message()))
@@ -284,6 +289,7 @@ if options.connect:
exit_status = 6 exit_status = 6
op_performed = True op_performed = True
def str_properties(prop): def str_properties(prop):
"""Pretty print optional and required properties.""" """Pretty print optional and required properties."""
if len(prop) == 0: if len(prop) == 0:
@@ -292,6 +298,7 @@ def str_properties(prop):
tmp = [(x[0], x[1].replace('_', ' ')) for x in type['required']] tmp = [(x[0], x[1].replace('_', ' ')) for x in type['required']]
return ', '.join("%s (%s)" % (x, y) for x, y in tmp) return ', '.join("%s (%s)" % (x, y) for x, y in tmp)
if options.wireless and options.list_encryption_types: if options.wireless and options.list_encryption_types:
et = misc.LoadEncryptionMethods() et = misc.LoadEncryptionMethods()
# print 'Installed encryption templates:' # print 'Installed encryption templates:'
@@ -318,4 +325,3 @@ if not op_performed:
print("No operations performed.") print("No operations performed.")
sys.exit(exit_status) sys.exit(exit_status)

View File

@@ -23,16 +23,17 @@ Also recycles a lot of configscript.py, too. :-)
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA. # MA 02110-1301, USA.
import sys
import os
import urwid
import urwid.curses_display
from wicd.translations import _ from wicd.translations import _
from configscript import write_scripts, get_script_info from configscript import write_scripts, get_script_info
from configscript import none_to_blank, blank_to_none from configscript import none_to_blank, blank_to_none
import urwid
import urwid.curses_display
import sys
import os
ui = None ui = None
frame = None frame = None
pre_entry = None pre_entry = None
@@ -49,13 +50,11 @@ def main(argv):
sys.exit(1) sys.exit(1)
ui = urwid.curses_display.Screen() ui = urwid.curses_display.Screen()
ui.register_palette([ ui.register_palette([('body', 'default', 'default'),
('body', 'default', 'default'),
('focus', 'dark magenta', 'light gray'), ('focus', 'dark magenta', 'light gray'),
('editcp', 'default', 'default', 'standout'), ('editcp', 'default', 'default', 'standout'),
('editbx', 'light gray', 'dark blue'), ('editbx', 'light gray', 'dark blue'),
('editfc', 'white', 'dark blue', 'bold'), ('editfc', 'white', 'dark blue', 'bold')])
])
network = argv[1] network = argv[1]
network_type = argv[2] network_type = argv[2]
@@ -70,28 +69,28 @@ def main(argv):
global pre_entry, post_entry, pre_disconnect_entry, post_disconnect_entry global pre_entry, post_entry, pre_disconnect_entry, post_disconnect_entry
pre_entry = urwid.AttrWrap(urwid.Edit(pre_entry_t, pre_entry = urwid.AttrWrap(urwid.Edit(pre_entry_t,
none_to_blank(script_info.get('pre_entry'))), none_to_blank(script_info.
get('pre_entry'))),
'editbx', 'editfc') 'editbx', 'editfc')
post_entry = urwid.AttrWrap(urwid.Edit(post_entry_t, post_entry = urwid.AttrWrap(urwid.Edit(post_entry_t,
none_to_blank(script_info.get('post_entry'))), none_to_blank(script_info.
get('post_entry'))),
'editbx', 'editfc') 'editbx', 'editfc')
pre_disconnect_entry = urwid.AttrWrap(urwid.Edit(pre_disconnect_entry_t, pre_disconnect_entry = urwid.AttrWrap(
urwid.Edit(pre_disconnect_entry_t,
none_to_blank(script_info.get('pre_disconnect_entry'))), none_to_blank(script_info.get('pre_disconnect_entry'))),
'editbx', 'editfc') 'editbx', 'editfc')
post_disconnect_entry = urwid.AttrWrap(urwid.Edit(post_disconnect_entry_t, post_disconnect_entry = urwid.AttrWrap(
urwid.Edit(post_disconnect_entry_t,
none_to_blank(script_info.get('post_disconnect_entry'))), none_to_blank(script_info.get('post_disconnect_entry'))),
'editbx', 'editfc') 'editbx', 'editfc')
# The buttons # The buttons
ok_button = urwid.AttrWrap( ok_button = urwid.AttrWrap(urwid.Button(_('OK'), ok_callback), 'body',
urwid.Button(_('OK'), ok_callback), 'focus')
'body', 'focus' cancel_button = urwid.AttrWrap(urwid.Button(_('Cancel'), cancel_callback),
) 'body', 'focus')
cancel_button = urwid.AttrWrap(
urwid.Button(_('Cancel'), cancel_callback),
'body', 'focus'
)
button_cols = urwid.Columns([ok_button, cancel_button], dividechars=1) button_cols = urwid.Columns([ok_button, cancel_button], dividechars=1)
@@ -101,20 +100,20 @@ def main(argv):
('fixed', 2, urwid.Filler(pre_disconnect_entry)), ('fixed', 2, urwid.Filler(pre_disconnect_entry)),
('fixed', 2, urwid.Filler(post_disconnect_entry)), ('fixed', 2, urwid.Filler(post_disconnect_entry)),
# blank, blank, blank, blank, blank, # blank, blank, blank, blank, blank,
urwid.Filler(button_cols, 'bottom') urwid.Filler(button_cols, 'bottom')])
])
frame = urwid.Frame(lbox) frame = urwid.Frame(lbox)
result = ui.run_wrapper(run) result = ui.run_wrapper(run)
if result: if result:
script_info["pre_entry"] = blank_to_none(pre_entry.get_edit_text()) script_info["pre_entry"] = blank_to_none(pre_entry.get_edit_text())
script_info["post_entry"] = blank_to_none(post_entry.get_edit_text()) script_info["post_entry"] = blank_to_none(post_entry.get_edit_text())
script_info["pre_disconnect_entry"] = \ script_info["pre_disconnect_entry"] = blank_to_none(
blank_to_none(pre_disconnect_entry.get_edit_text()) pre_disconnect_entry.get_edit_text())
script_info["post_disconnect_entry"] = \ script_info["post_disconnect_entry"] = blank_to_none(
blank_to_none(post_disconnect_entry.get_edit_text()) post_disconnect_entry.get_edit_text())
write_scripts(network, network_type, script_info) write_scripts(network, network_type, script_info)
OK_PRESSED = False OK_PRESSED = False
CANCEL_PRESSED = False CANCEL_PRESSED = False
@@ -159,6 +158,7 @@ def run():
if OK_PRESSED or 'meta enter' in keys: if OK_PRESSED or 'meta enter' in keys:
return True return True
if __name__ == '__main__': if __name__ == '__main__':
if os.getuid() != 0: if os.getuid() != 0:
print("Root privileges are required to configure scripts. Exiting.") print("Root privileges are required to configure scripts. Exiting.")

View File

@@ -163,7 +163,7 @@ class MaskingEdit(urwid.Edit):
mask_mode="always", mask_char='*'): mask_mode="always", mask_char='*'):
self.mask_mode = mask_mode self.mask_mode = mask_mode
if len(mask_char) > 1: if len(mask_char) > 1:
raise MaskingEditException('Masks of more than one character are' + raise MaskingEditException('Masks of more than one character are '
'not supported!') 'not supported!')
self.mask_char = mask_char self.mask_char = mask_char
# pylint: disable-msg=E1101 # pylint: disable-msg=E1101
@@ -195,8 +195,8 @@ class MaskingEdit(urwid.Edit):
if self.mask_mode == "off" or (self.mask_mode == 'no_focus' and focus): if self.mask_mode == "off" or (self.mask_mode == 'no_focus' and focus):
# pylint: disable-msg=E1101 # pylint: disable-msg=E1101
canv = self.__super.render((maxcol, ), focus) canv = self.__super.render((maxcol, ), focus)
# The cache messes this thing up, because I am totally changing what # The cache messes this thing up, because I am totally changing
# is displayed. # what is displayed.
self._invalidate() self._invalidate()
return canv return canv
@@ -226,7 +226,8 @@ class TabColumns(urwid.WidgetWrap):
# FIXME Make the bottom_part optional # FIXME Make the bottom_part optional
# pylint: disable-msg=W0231 # pylint: disable-msg=W0231
def __init__(self, tab_str, tab_wid, title, bottom_part=None, def __init__(self, tab_str, tab_wid, title, bottom_part=None,
attr=('body', 'focus'), attrsel='tab active', attrtitle='header'): attr=('body', 'focus'), attrsel='tab active',
attrtitle='header'):
# self.bottom_part = bottom_part # self.bottom_part = bottom_part
# title_wid = urwid.Text((attrtitle, title), align='right') # title_wid = urwid.Text((attrtitle, title), align='right')
column_list = [] column_list = []
@@ -247,11 +248,11 @@ class TabColumns(urwid.WidgetWrap):
def gen_pile(self, lbox, firstrun=False): def gen_pile(self, lbox, firstrun=False):
"""Make the pile in the middle.""" """Make the pile in the middle."""
self.pile = urwid.Pile([ self.pile = urwid.Pile([('fixed', 1,
('fixed', 1, urwid.Filler(self.columns, 'top')), urwid.Filler(self.columns, 'top')),
urwid.Filler(lbox, 'top', height=('relative', 99)), urwid.Filler(lbox, 'top',
#('fixed', 1, urwid.Filler(self.bottom_part, 'bottom')) height=('relative', 99))])
]) # ('fixed', 1, urwid.Filler(self.bottom_part, 'bottom'))])
if not firstrun: if not firstrun:
self.frame.set_body(self.pile) self.frame.set_body(self.pile)
self._w = self.frame self._w = self.frame
@@ -314,11 +315,11 @@ class ComboBox(urwid.WidgetWrap):
class ComboSpace(urwid.WidgetWrap): class ComboSpace(urwid.WidgetWrap):
"""The actual menu-like space that comes down from the ComboBox""" """The actual menu-like space that comes down from the ComboBox"""
# pylint: disable-msg=W0231 # pylint: disable-msg=W0231
def __init__(self, l, body, ui, show_first, pos=(0, 0), def __init__(self, data, body, ui, show_first, pos=(0, 0),
attr=('body', 'focus')): attr=('body', 'focus')):
""" """
body : parent widget body : parent widget
l : stuff to include in the combobox data : stuff to include in the combobox
ui : the screen ui : the screen
show_first: index of the element in the list to pick first show_first: index of the element in the list to pick first
pos : a tuple of (row,col) where to put the list pos : a tuple of (row,col) where to put the list
@@ -326,18 +327,19 @@ class ComboBox(urwid.WidgetWrap):
""" """
# Calculate width and height of the menu widget: # Calculate width and height of the menu widget:
height = len(l) height = len(data)
width = 0 width = 0
for entry in l: for entry in data:
if len(entry) > width: if len(entry) > width:
width = len(entry) width = len(entry)
content = [urwid.AttrWrap(SelText(w), attr[0], attr[1]) content = [urwid.AttrWrap(SelText(w), attr[0], attr[1])
for w in l] for w in data]
self._listbox = urwid.ListBox(content) self._listbox = urwid.ListBox(content)
self._listbox.set_focus(show_first) self._listbox.set_focus(show_first)
overlay = urwid.Overlay(self._listbox, body, ('fixed left', pos[0]), overlay = urwid.Overlay(self._listbox, body,
width + 2, ('fixed top', pos[1]), height) ('fixed left', pos[0]), width + 2,
('fixed top', pos[1]), height)
# pylint: disable-msg=E1101 # pylint: disable-msg=E1101
self.__super.__init__(overlay) self.__super.__init__(overlay)
@@ -369,13 +371,13 @@ class ComboBox(urwid.WidgetWrap):
# def get_size(self): # def get_size(self):
# pylint: disable-msg=W0231 # pylint: disable-msg=W0231
def __init__(self, label='', l=None, attrs=('body', 'editnfc'), def __init__(self, label='', data=None, attrs=('body', 'editnfc'),
focus_attr='focus', use_enter=True, focus=0, callback=None, focus_attr='focus', use_enter=True, focus=0, callback=None,
user_args=None): user_args=None):
""" """
label : bit of text that preceeds the combobox. If it is "", then label : bit of text that preceeds the combobox. If it is "", then
ignore it ignore it
l : stuff to include in the combobox data : stuff to include in the combobox
body : parent widget body : parent widget
ui : the screen ui : the screen
row : where this object is to be found onscreen row : where this object is to be found onscreen
@@ -388,9 +390,9 @@ class ComboBox(urwid.WidgetWrap):
self.label = urwid.Text(label) self.label = urwid.Text(label)
self.attrs = attrs self.attrs = attrs
self.focus_attr = focus_attr self.focus_attr = focus_attr
if l is None: if data is None:
l = [] data = []
self.list = l self.list = data
s, trash = self.label.get_text() s, trash = self.label.get_text()
@@ -424,9 +426,9 @@ class ComboBox(urwid.WidgetWrap):
self.ui = None self.ui = None
self.row = None self.row = None
def set_list(self, l): def set_list(self, data):
"""Populate widget list.""" """Populate widget list."""
self.list = l self.list = data
def set_focus(self, index): def set_focus(self, index):
"""Set widget focus.""" """Set widget focus."""
@@ -508,7 +510,7 @@ class ComboBox(urwid.WidgetWrap):
if urwid.VERSION < (1, 1, 0): if urwid.VERSION < (1, 1, 0):
return None, self.focus return None, self.focus
else: else:
return None, self._w.focus_position # pylint: disable-msg=E1103 return None, self._w.focus_position
def get_sensitive(self): def get_sensitive(self):
"""Return widget sensitivity.""" """Return widget sensitivity."""
@@ -554,16 +556,16 @@ class Dialog2(urwid.WidgetWrap):
# buttons: tuple of name,exitcode # buttons: tuple of name,exitcode
def add_buttons(self, buttons): def add_buttons(self, buttons):
"""Add buttons.""" """Add buttons."""
l = [] data = []
maxlen = 0 maxlen = 0
for name, exitcode in buttons: for name, exitcode in buttons:
b = urwid.Button(name, self.button_press) b = urwid.Button(name, self.button_press)
b.exitcode = exitcode b.exitcode = exitcode
b = urwid.AttrWrap(b, 'body', 'focus') b = urwid.AttrWrap(b, 'body', 'focus')
l.append(b) data.append(b)
maxlen = max(len(name), maxlen) maxlen = max(len(name), maxlen)
maxlen += 4 # because of '< ... >' maxlen += 4 # because of '< ... >'
self.buttons = urwid.GridFlow(l, maxlen, 3, 1, 'center') self.buttons = urwid.GridFlow(data, maxlen, 3, 1, 'center')
self.frame.footer = urwid.Pile([ self.frame.footer = urwid.Pile([
urwid.Divider(), urwid.Divider(),
self.buttons self.buttons
@@ -622,8 +624,8 @@ class TextDialog(Dialog2):
"""Simple dialog with text and "OK" button.""" """Simple dialog with text and "OK" button."""
def __init__(self, text, height, width, header=None, align='left', def __init__(self, text, height, width, header=None, align='left',
buttons=(_('OK'), 1)): buttons=(_('OK'), 1)):
l = [urwid.Text(text)] data = [urwid.Text(text)]
body = urwid.ListBox(l) body = urwid.ListBox(data)
body = urwid.AttrWrap(body, 'body') body = urwid.AttrWrap(body, 'body')
Dialog2.__init__(self, header, height + 2, width + 2, body) Dialog2.__init__(self, header, height + 2, width + 2, body)
@@ -681,7 +683,8 @@ class ClickCols(urwid.WidgetWrap):
def mouse_event(self, size, event, button, x, y, focus): def mouse_event(self, size, event, button, x, y, focus):
"""Handle mouse events.""" """Handle mouse events."""
if event == "mouse press": if event == "mouse press":
# The keypress dealie in wicd-curses.py expects a list of keystrokes # The keypress dealie in wicd-curses.py expects a list of
# keystrokes
self.callback([self.args]) self.callback([self.args])
@@ -692,7 +695,8 @@ class OptCols(urwid.WidgetWrap):
# handler = function passed the key of the "button" pressed # handler = function passed the key of the "button" pressed
# mentions of 'left' and right will be converted to <- and -> respectively # mentions of 'left' and right will be converted to <- and -> respectively
# pylint: disable-msg=W0231 # pylint: disable-msg=W0231
def __init__(self, tuples, handler, attrs=('body', 'infobar'), debug=False): def __init__(self, tuples, handler, attrs=('body', 'infobar'),
debug=False):
# Find the longest string. Keys for this bar should be no greater than # Find the longest string. Keys for this bar should be no greater than
# 2 characters long (e.g., -> for left) # 2 characters long (e.g., -> for left)
# maxlen = 6 # maxlen = 6

View File

@@ -20,6 +20,7 @@
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA. # MA 02110-1301, USA.
import os
import urwid import urwid
from curses_misc import DynWrap, MaskingEdit, ComboBox, error from curses_misc import DynWrap, MaskingEdit, ComboBox, error
@@ -27,7 +28,6 @@ import wicd.misc as misc
from wicd.misc import noneToString, stringToNone, noneToBlankString, to_bool from wicd.misc import noneToString, stringToNone, noneToBlankString, to_bool
from wicd.translations import language, _ from wicd.translations import language, _
import os
daemon = None daemon = None
wired = None wired = None
@@ -47,10 +47,10 @@ class AdvancedSettingsDialog(urwid.WidgetWrap):
""" """
Settings dialog. Settings dialog.
Both the wired and the wireless settings preferences dialogs use some of the Both the wired and the wireless settings preferences dialogs use some of
same fields. the same fields.
This will be used to produce the individual network settings dialogs way far This will be used to produce the individual network settings dialogs way
below. far below.
""" """
# pylint: disable-msg=W0231 # pylint: disable-msg=W0231
def __init__(self): def __init__(self):
@@ -84,28 +84,20 @@ class AdvancedSettingsDialog(urwid.WidgetWrap):
cancel_t = _('Cancel') cancel_t = _('Cancel')
ok_t = _('OK') ok_t = _('OK')
self.static_ip_cb = urwid.CheckBox(static_ip_t, self.static_ip_cb = urwid.CheckBox(
on_state_change=self.static_ip_toggle) static_ip_t, on_state_change=self.static_ip_toggle)
self.ip_edit = DynWrap(urwid.Edit(ip_t), False) self.ip_edit = DynWrap(urwid.Edit(ip_t), False)
self.netmask_edit = DynWrap(urwid.Edit(netmask_t), False) self.netmask_edit = DynWrap(urwid.Edit(netmask_t), False)
self.gateway_edit = DynWrap(urwid.Edit(gateway_t), False) self.gateway_edit = DynWrap(urwid.Edit(gateway_t), False)
self.static_dns_cb = DynWrap( self.static_dns_cb = DynWrap(
urwid.CheckBox(use_static_dns_t, on_state_change=self.dns_toggle), urwid.CheckBox(use_static_dns_t, on_state_change=self.dns_toggle),
True, True, ('body', 'editnfc'), None)
('body', 'editnfc'),
None
)
self.global_dns_cb = DynWrap( self.global_dns_cb = DynWrap(
urwid.CheckBox(use_global_dns_t, on_state_change=self.dns_toggle), urwid.CheckBox(use_global_dns_t, on_state_change=self.dns_toggle),
False, False, ('body', 'editnfc'), None)
('body', 'editnfc'), self.checkb_cols = urwid.Columns([self.static_dns_cb,
None self.global_dns_cb])
)
self.checkb_cols = urwid.Columns([
self.static_dns_cb,
self.global_dns_cb
])
self.dns_dom_edit = DynWrap(urwid.Edit(dns_dom_t), False) self.dns_dom_edit = DynWrap(urwid.Edit(dns_dom_t), False)
self.search_dom_edit = DynWrap(urwid.Edit(search_dom_t), False) self.search_dom_edit = DynWrap(urwid.Edit(search_dom_t), False)
self.dns1 = DynWrap(urwid.Edit(dns1_t), False) self.dns1 = DynWrap(urwid.Edit(dns1_t), False)
@@ -113,10 +105,8 @@ class AdvancedSettingsDialog(urwid.WidgetWrap):
self.dns3 = DynWrap(urwid.Edit(dns3_t), False) self.dns3 = DynWrap(urwid.Edit(dns3_t), False)
self.use_dhcp_h = urwid.CheckBox( self.use_dhcp_h = urwid.CheckBox(
use_dhcp_h_t, use_dhcp_h_t, False,
False, on_state_change=self.use_dhcp_h_toggle)
on_state_change=self.use_dhcp_h_toggle
)
self.dhcp_h = DynWrap(urwid.Edit(dhcp_h_t), False) self.dhcp_h = DynWrap(urwid.Edit(dhcp_h_t), False)
_blank = urwid.Text('') _blank = urwid.Text('')
@@ -174,8 +164,8 @@ class AdvancedSettingsDialog(urwid.WidgetWrap):
self.global_dns_cb.set_sensitive(new_state) self.global_dns_cb.set_sensitive(new_state)
# use_global_dns_cb is DynWrapped # use_global_dns_cb is DynWrapped
if checkb == self.global_dns_cb.get_w(): if checkb == self.global_dns_cb.get_w():
for w in [self.dns_dom_edit, self.search_dom_edit, for w in [self.dns_dom_edit, self.search_dom_edit, self.dns1,
self.dns1, self.dns2, self.dns3 ]: self.dns2, self.dns3]:
w.set_sensitive(not new_state) w.set_sensitive(not new_state)
def set_net_prop(self, option, value): def set_net_prop(self, option, value):
@@ -219,12 +209,13 @@ class AdvancedSettingsDialog(urwid.WidgetWrap):
self.set_net_prop('dns_domain', self.set_net_prop('dns_domain',
noneToString(self.dns_dom_edit.get_edit_text())) noneToString(self.dns_dom_edit.get_edit_text()))
self.set_net_prop("search_domain", self.set_net_prop("search_domain",
noneToString(self.search_dom_edit.get_edit_text())) noneToString(self.search_dom_edit
.get_edit_text()))
self.set_net_prop("dns1", noneToString(self.dns1.get_edit_text())) self.set_net_prop("dns1", noneToString(self.dns1.get_edit_text()))
self.set_net_prop("dns2", noneToString(self.dns2.get_edit_text())) self.set_net_prop("dns2", noneToString(self.dns2.get_edit_text()))
self.set_net_prop("dns3", noneToString(self.dns3.get_edit_text())) self.set_net_prop("dns3", noneToString(self.dns3.get_edit_text()))
elif self.static_dns_cb.get_state() and \ elif (self.static_dns_cb.get_state() and
self.global_dns_cb.get_state(): self.global_dns_cb.get_state()):
self.set_net_prop('use_static_dns', True) self.set_net_prop('use_static_dns', True)
self.set_net_prop('use_global_dns', True) self.set_net_prop('use_global_dns', True)
else: else:
@@ -288,18 +279,18 @@ class AdvancedSettingsDialog(urwid.WidgetWrap):
wired.GetWiredProperty(field[0]))) wired.GetWiredProperty(field[0])))
else: else:
edit.set_edit_text(noneToBlankString( edit.set_edit_text(noneToBlankString(
wireless.GetWirelessProperty(self.networkid, field[0]))) wireless.GetWirelessProperty(self.networkid,
field[0])))
# FIXME: This causes the entire pile to light up upon use. # FIXME: This causes the entire pile to light up upon use.
# Make this into a listbox? # Make this into a listbox?
self.pile_encrypt = DynWrap( self.pile_encrypt = DynWrap(urwid.Pile(theList),
urwid.Pile(theList), attrs=('editbx', 'editnfc'))
attrs=('editbx', 'editnfc')
)
self.pile_encrypt.set_sensitive(self.encryption_chkbox.get_state()) self.pile_encrypt.set_sensitive(self.encryption_chkbox.get_state())
self._w.body.body.insert(self._w.body.body.__len__(), self.pile_encrypt) self._w.body.body.insert(self._w.body.body.__len__(),
self.pile_encrypt)
# self._w.body.body.append(self.pile_encrypt) # self._w.body.body.append(self.pile_encrypt)
def encryption_toggle(self, chkbox, new_state, user_data=None): def encryption_toggle(self, chkbox, new_state, user_data=None):
@@ -315,8 +306,7 @@ class WiredSettingsDialog(AdvancedSettingsDialog):
self.wired = True self.wired = True
self.set_default = urwid.CheckBox( self.set_default = urwid.CheckBox(
_('Use as default profile (overwrites any previous default)') _('Use as default profile (overwrites any previous default)'))
)
# self.cur_default = # self.cur_default =
# Add widgets to listbox # Add widgets to listbox
self._w.body.body.append(self.set_default) self._w.body.body.append(self.set_default)
@@ -375,13 +365,13 @@ class WiredSettingsDialog(AdvancedSettingsDialog):
self.set_default.set_state(to_bool(wired.GetWiredProperty("default"))) self.set_default.set_state(to_bool(wired.GetWiredProperty("default")))
# Throw the encryption stuff into a list # Throw the encryption stuff into a list
l = [] combo_items = []
activeID = -1 # Set the menu to this item when we are done activeID = -1 # Set the menu to this item when we are done
for x, enc_type in enumerate(self.encrypt_types): for x, enc_type in enumerate(self.encrypt_types):
l.append(enc_type['name']) combo_items.append(enc_type['name'])
if enc_type['type'] == wired.GetWiredProperty("enctype"): if enc_type['type'] == wired.GetWiredProperty("enctype"):
activeID = x activeID = x
self.encryption_combo.set_list(l) self.encryption_combo.set_list(combo_items)
self.encryption_combo.set_focus(activeID) self.encryption_combo.set_focus(activeID)
if wired.GetWiredProperty("encryption_enabled"): if wired.GetWiredProperty("encryption_enabled"):
@@ -502,17 +492,21 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
self.encrypt_types = misc.LoadEncryptionMethods() self.encrypt_types = misc.LoadEncryptionMethods()
self.set_values() self.set_values()
title = _('Configuring preferences for wireless network "$A" ($B)'). \ title = (_('Configuring preferences for wireless network "$A" ($B)')
replace('$A', wireless.GetWirelessProperty(networkID, 'essid')). \ .replace('$A', wireless.GetWirelessProperty(networkID,
replace('$B', wireless.GetWirelessProperty(networkID, 'bssid')) 'essid'))
.replace('$B', wireless.GetWirelessProperty(networkID,
'bssid')))
self._w.header = urwid.Text(('header', title), align='right') self._w.header = urwid.Text(('header', title), align='right')
def set_values(self): def set_values(self):
"""Set the various network settings to the right values.""" """Set the various network settings to the right values."""
networkID = self.networkid networkID = self.networkid
self.ip_edit.set_edit_text(self.format_entry(networkID, "ip")) self.ip_edit.set_edit_text(self.format_entry(networkID, "ip"))
self.netmask_edit.set_edit_text(self.format_entry(networkID, "netmask")) self.netmask_edit.set_edit_text(self.format_entry(networkID,
self.gateway_edit.set_edit_text(self.format_entry(networkID, "gateway")) "netmask"))
self.gateway_edit.set_edit_text(self.format_entry(networkID,
"gateway"))
self.global_dns_cb.set_state( self.global_dns_cb.set_state(
bool(wireless.GetWirelessProperty(networkID, 'use_global_dns'))) bool(wireless.GetWirelessProperty(networkID, 'use_global_dns')))
@@ -552,21 +546,18 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
bool(wireless.GetWirelessProperty(networkID, 'encryption')), bool(wireless.GetWirelessProperty(networkID, 'encryption')),
do_callback=False) do_callback=False)
self.global_settings_chkbox.set_state( self.global_settings_chkbox.set_state(
bool(wireless.GetWirelessProperty( bool(wireless.GetWirelessProperty(networkID,
networkID, 'use_settings_globally')))
'use_settings_globally')
)
)
# Throw the encryption stuff into a list # Throw the encryption stuff into a list
l = [] combo_items = []
activeID = -1 # Set the menu to this item when we are done activeID = -1 # Set the menu to this item when we are done
for x, enc_type in enumerate(self.encrypt_types): for x, enc_type in enumerate(self.encrypt_types):
l.append(enc_type['name']) combo_items.append(enc_type['name'])
if enc_type['type'] == \ if enc_type['type'] == wireless.GetWirelessProperty(networkID,
wireless.GetWirelessProperty(networkID, "enctype"): "enctype"):
activeID = x activeID = x
self.encryption_combo.set_list(l) self.encryption_combo.set_list(combo_items)
self.encryption_combo.set_focus(activeID) self.encryption_combo.set_focus(activeID)
if activeID != -1: if activeID != -1:
@@ -592,7 +583,8 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
def format_entry(self, networkid, label): def format_entry(self, networkid, label):
"""Helper method for fetching/formatting wireless properties.""" """Helper method for fetching/formatting wireless properties."""
return noneToBlankString(wireless.GetWirelessProperty(networkid, label)) return noneToBlankString(wireless.GetWirelessProperty(networkid,
label))
# Ripped from netentry.py # Ripped from netentry.py
def save_settings(self): def save_settings(self):
@@ -607,29 +599,21 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
) )
# Make sure all required fields are filled in. # Make sure all required fields are filled in.
for entry_info in list(encrypt_info.values()): for entry_info in list(encrypt_info.values()):
if entry_info[0].get_edit_text() == "" \ if (entry_info[0].get_edit_text() == "" and
and entry_info[1] == 'required': entry_info[1] == 'required'):
error( error(self.ui, self.parent, "%s (%s)" %
self.ui, (_('Required encryption information is missing.'),
self.parent, entry_info[0].get_caption()[0:-2]))
"%s (%s)" % (
_('Required encryption information is missing.'),
entry_info[0].get_caption()[0:-2]
)
)
return False return False
for entry_key, entry_info in list(encrypt_info.items()): for entry_key, entry_info in list(encrypt_info.items()):
self.set_net_prop(entry_key, noneToString(entry_info[0]. self.set_net_prop(entry_key, noneToString(entry_info[0].
get_edit_text())) get_edit_text()))
elif not self.encryption_chkbox.get_state() and \ elif (not self.encryption_chkbox.get_state() and
wireless.GetWirelessProperty(self.networkid, "encryption"): wireless.GetWirelessProperty(self.networkid, "encryption")):
# Encrypt checkbox is off, but the network needs it. # Encrypt checkbox is off, but the network needs it.
error( error(self.ui, self.parent,
self.ui, _('This network requires encryption to be enabled.'))
self.parent,
_('This network requires encryption to be enabled.')
)
return False return False
else: else:
self.set_net_prop("enctype", "None") self.set_net_prop("enctype", "None")

View File

@@ -55,7 +55,8 @@ class PrefsDialog(urwid.WidgetWrap):
header0_t = _('General Settings') header0_t = _('General Settings')
header1_t = _('External Programs') header1_t = _('External Programs')
header2_t = _('Advanced Settings') header2_t = _('Advanced Settings')
self.header0 = urwid.AttrWrap(SelText(header0_t), 'tab active', 'focus') self.header0 = urwid.AttrWrap(SelText(header0_t), 'tab active',
'focus')
self.header1 = urwid.AttrWrap(SelText(header1_t), 'body', 'focus') self.header1 = urwid.AttrWrap(SelText(header1_t), 'body', 'focus')
self.header2 = urwid.AttrWrap(SelText(header2_t), 'body', 'focus') self.header2 = urwid.AttrWrap(SelText(header2_t), 'body', 'focus')
title = ('Preferences') title = ('Preferences')
@@ -63,9 +64,7 @@ class PrefsDialog(urwid.WidgetWrap):
# Blank line # Blank line
_blank = urwid.Text('') _blank = urwid.Text('')
#### # Text in the widgets
#### Text in the widgets
####
# General Settings # General Settings
net_cat_t = ('header', ('Network Interfaces')) net_cat_t = ('header', ('Network Interfaces'))
@@ -90,7 +89,7 @@ class PrefsDialog(urwid.WidgetWrap):
auto_reconn_cat_t = ('header', _('Automatic Reconnection')) auto_reconn_cat_t = ('header', _('Automatic Reconnection'))
auto_reconn_t = _('Automatically reconnect on connection loss') auto_reconn_t = _('Automatically reconnect on connection loss')
#### External Programs # External Programs
automatic_t = _('Automatic (recommended)') automatic_t = _('Automatic (recommended)')
dhcp_header_t = ('header', _('DHCP Client')) dhcp_header_t = ('header', _('DHCP Client'))
@@ -108,12 +107,12 @@ class PrefsDialog(urwid.WidgetWrap):
flush1_t = 'ip' flush1_t = 'ip'
flush2_t = 'route' flush2_t = 'route'
#### Advanced Settings # Advanced Settings
wpa_cat_t = ('header', _('WPA Supplicant')) wpa_cat_t = ('header', _('WPA Supplicant'))
wpa_t = ('editcp', 'Driver:') wpa_t = ('editcp', 'Driver:')
wpa_list = [] wpa_list = []
wpa_warn_t = ('important', wpa_warn_t = ('important', _('You should almost always use wext as '
_('You should almost always use wext as the WPA supplicant driver')) 'the WPA supplicant driver'))
backend_cat_t = ('header', _('Backend')) backend_cat_t = ('header', _('Backend'))
backend_t = _('Backend') + ':' backend_t = _('Backend') + ':'
@@ -124,12 +123,10 @@ class PrefsDialog(urwid.WidgetWrap):
wless_cat_t = ('header', _('Wireless Interface')) wless_cat_t = ('header', _('Wireless Interface'))
use_dbm_t = _('Use dBm to measure signal strength') use_dbm_t = _('Use dBm to measure signal strength')
verify_ap_t = \ verify_ap_t = _('Ping static gateways after connecting to verify '
_('Ping static gateways after connecting to verify association') 'association')
#### # UI Widgets
#### UI Widgets
####
# General Settings # General Settings
self.net_cat = urwid.Text(net_cat_t) self.net_cat = urwid.Text(net_cat_t)
@@ -142,10 +139,9 @@ class PrefsDialog(urwid.WidgetWrap):
# Default the global DNS settings to off. They will be reenabled later # Default the global DNS settings to off. They will be reenabled later
# if so required. # if so required.
global_dns_state = False global_dns_state = False
self.global_dns_checkb = urwid.CheckBox(global_dns_t, self.global_dns_checkb = urwid.CheckBox(global_dns_t, global_dns_state,
global_dns_state, on_state_change=self.
on_state_change=self.global_dns_trigger global_dns_trigger)
)
self.search_dom = DynWrap(urwid.Edit(search_dom_t), global_dns_state) self.search_dom = DynWrap(urwid.Edit(search_dom_t), global_dns_state)
self.dns_dom = DynWrap(urwid.Edit(dns_dom_t), global_dns_state) self.dns_dom = DynWrap(urwid.Edit(dns_dom_t), global_dns_state)
self.dns1 = DynWrap(urwid.Edit(dns1_t), global_dns_state) self.dns1 = DynWrap(urwid.Edit(dns1_t), global_dns_state)
@@ -156,9 +152,12 @@ class PrefsDialog(urwid.WidgetWrap):
self.wired_auto_l = [] self.wired_auto_l = []
self.wired_auto_cat = urwid.Text(wired_auto_cat_t) self.wired_auto_cat = urwid.Text(wired_auto_cat_t)
self.wired_auto_1 = urwid.RadioButton(self.wired_auto_l, wired_auto_1_t) self.wired_auto_1 = urwid.RadioButton(self.wired_auto_l,
self.wired_auto_2 = urwid.RadioButton(self.wired_auto_l, wired_auto_2_t) wired_auto_1_t)
self.wired_auto_3 = urwid.RadioButton(self.wired_auto_l, wired_auto_3_t) self.wired_auto_2 = urwid.RadioButton(self.wired_auto_l,
wired_auto_2_t)
self.wired_auto_3 = urwid.RadioButton(self.wired_auto_l,
wired_auto_2_t)
self.auto_reconn_cat = urwid.Text(auto_reconn_cat_t) self.auto_reconn_cat = urwid.Text(auto_reconn_cat_t)
self.auto_reconn_checkb = urwid.CheckBox(auto_reconn_t) self.auto_reconn_checkb = urwid.CheckBox(auto_reconn_t)
@@ -180,7 +179,8 @@ class PrefsDialog(urwid.WidgetWrap):
self.auto_reconn_checkb self.auto_reconn_checkb
]) ])
#### External Programs tab # External Programs tab
automatic_t = _('Automatic (recommended)') automatic_t = _('Automatic (recommended)')
self.dhcp_header = urwid.Text(dhcp_header_t) self.dhcp_header = urwid.Text(dhcp_header_t)
@@ -223,7 +223,8 @@ class PrefsDialog(urwid.WidgetWrap):
self.flush0, self.flush1, self.flush2 self.flush0, self.flush1, self.flush2
]) ])
#### Advanced settings # Advanced settings
self.wpa_cat = urwid.Text(wpa_cat_t) self.wpa_cat = urwid.Text(wpa_cat_t)
self.wpa_cbox = ComboBox(wpa_t) self.wpa_cbox = ComboBox(wpa_t)
self.wpa_warn = urwid.Text(wpa_warn_t) self.wpa_warn = urwid.Text(wpa_warn_t)
@@ -257,6 +258,7 @@ class PrefsDialog(urwid.WidgetWrap):
self.header1: externalLB, self.header1: externalLB,
self.header2: advancedLB self.header2: advancedLB
} }
# self.load_settings() # self.load_settings()
self.tabs = TabColumns(headerList, lbList, _('Preferences')) self.tabs = TabColumns(headerList, lbList, _('Preferences'))
@@ -265,7 +267,7 @@ class PrefsDialog(urwid.WidgetWrap):
def load_settings(self): def load_settings(self):
"""Load settings to be used in the dialog.""" """Load settings to be used in the dialog."""
### General Settings # General Settings
# ComboBox does not like dbus.Strings as text markups. My fault. :/ # ComboBox does not like dbus.Strings as text markups. My fault. :/
wless_iface = str(daemon.GetWirelessInterface()) wless_iface = str(daemon.GetWirelessInterface())
wired_iface = str(daemon.GetWiredInterface()) wired_iface = str(daemon.GetWiredInterface())
@@ -280,7 +282,8 @@ class PrefsDialog(urwid.WidgetWrap):
theDNS = daemon.GetGlobalDNSAddresses() theDNS = daemon.GetGlobalDNSAddresses()
i = 0 i = 0
for w in self.dns1, self.dns2, self.dns3, self.dns_dom, self.search_dom: for w in (self.dns1, self.dns2, self.dns3, self.dns_dom,
self.search_dom):
w.set_edit_text(misc.noneToBlankString(theDNS[i])) w.set_edit_text(misc.noneToBlankString(theDNS[i]))
i += 1 i += 1
@@ -293,7 +296,7 @@ class PrefsDialog(urwid.WidgetWrap):
for app in apps[1:]: for app in apps[1:]:
app.set_sensitive(daemon.GetAppAvailable(app.get_label())) app.set_sensitive(daemon.GetAppAvailable(app.get_label()))
### External Programs # External Programs
find_avail(self.dhcp_l) find_avail(self.dhcp_l)
dhcp_method = daemon.GetDHCPClient() dhcp_method = daemon.GetDHCPClient()
self.dhcp_l[dhcp_method].set_state(True) self.dhcp_l[dhcp_method].set_state(True)
@@ -306,7 +309,7 @@ class PrefsDialog(urwid.WidgetWrap):
flush_method = daemon.GetFlushTool() flush_method = daemon.GetFlushTool()
self.flush_l[flush_method].set_state(True) self.flush_l[flush_method].set_state(True)
### Advanced settings # Advanced settings
# wpa_supplicant janx # wpa_supplicant janx
self.wpadrivers = wireless.GetWpaSupplicantDrivers() self.wpadrivers = wireless.GetWpaSupplicantDrivers()
self.wpadrivers.append("ralink_legacy") self.wpadrivers.append("ralink_legacy")
@@ -405,7 +408,8 @@ class PrefsDialog(urwid.WidgetWrap):
def global_dns_trigger(self, check_box, new_state, user_data=None): def global_dns_trigger(self, check_box, new_state, user_data=None):
"""DNS CheckBox callback.""" """DNS CheckBox callback."""
for w in self.dns1, self.dns2, self.dns3, self.dns_dom, self.search_dom: for w in (self.dns1, self.dns2, self.dns3, self.dns_dom,
self.search_dom):
w.set_sensitive(new_state) w.set_sensitive(new_state)
def ready_widgets(self, ui, body): def ready_widgets(self, ui, body):

View File

@@ -35,29 +35,20 @@ at least get a network connection. Or those who don't like using X and/or GTK.
# Filter out a confusing urwid warning in python 2.6. # Filter out a confusing urwid warning in python 2.6.
# This is valid as of urwid version 0.9.8.4 # This is valid as of urwid version 0.9.8.4
from optparse import OptionParser
import signal
import sys
import warnings import warnings
warnings.filterwarnings(
"ignore",
"The popen2 module is deprecated. Use the subprocess module."
)
# UI stuff
import urwid
# DBus communication stuff import urwid
from dbus import DBusException from dbus import DBusException
# It took me a while to figure out that I have to use this. # It took me a while to figure out that I have to use this.
from gi.repository import GLib as gobject from gi.repository import GLib as gobject
# Other important wicd-related stuff
from wicd import wpath from wicd import wpath
from wicd import misc from wicd import misc
from wicd import dbusmanager from wicd import dbusmanager
from wicd.translations import _
# Internal Python stuff
import sys
# SIGQUIT signal handling
import signal
# Curses UIs for other stuff # Curses UIs for other stuff
from curses_misc import ComboBox, Dialog2, NSelListBox, SelText, OptCols from curses_misc import ComboBox, Dialog2, NSelListBox, SelText, OptCols
@@ -67,8 +58,6 @@ from prefs_curses import PrefsDialog
import netentry_curses import netentry_curses
from netentry_curses import WirelessSettingsDialog, WiredSettingsDialog from netentry_curses import WirelessSettingsDialog, WiredSettingsDialog
from optparse import OptionParser
# Stuff about getting the script configurer running # Stuff about getting the script configurer running
# from grp import getgrgid # from grp import getgrgid
# from os import getgroups, system # from os import getgroups, system
@@ -80,15 +69,16 @@ CURSES_REV = wpath.curses_revision
# Fix strings in wicd-curses # Fix strings in wicd-curses
# from wicd.translations import language # from wicd.translations import language
from wicd.translations import _
warnings.filterwarnings(
"ignore",
"The popen2 module is deprecated. Use the subprocess module."
)
ui = None ui = None
loop = None loop = None
bus = daemon = wireless = wired = None bus = daemon = wireless = wired = None
########################################
##### SUPPORT CLASSES
########################################
# Yay for decorators! # Yay for decorators!
def wrap_exceptions(func): def wrap_exceptions(func):
"""Decorator to wrap exceptions.""" """Decorator to wrap exceptions."""
@@ -104,12 +94,12 @@ def wrap_exceptions(func):
except DBusException: except DBusException:
loop.quit() loop.quit()
ui.stop() ui.stop()
print("\n" + _('DBus failure! ' print("\n" + _('DBus failure! This is most likely caused by the '
'This is most likely caused by the wicd daemon ' 'wicd daemon stopping while wicd-curses is '
'stopping while wicd-curses is running. ' 'running. Please restart the daemon, and then '
'Please restart the daemon, and then restart wicd-curses.'), file=sys.stderr) 'restart wicd-curses.'), file=sys.stderr)
raise raise
except: except Exception:
# Quit the loop # Quit the loop
# if 'loop' in locals(): # if 'loop' in locals():
loop.quit() loop.quit()
@@ -133,19 +123,14 @@ def wrap_exceptions(func):
return wrapper return wrapper
########################################
##### SUPPORT FUNCTIONS
########################################
# Look familiar? These two functions are clones of functions found in wicd's # Look familiar? These two functions are clones of functions found in wicd's
# gui.py file, except that now set_status is a function passed to them. # gui.py file, except that now set_status is a function passed to them.
@wrap_exceptions @wrap_exceptions
def check_for_wired(wired_ip, set_status): def check_for_wired(wired_ip, set_status):
"""Determine if wired is active, and if yes, set the status.""" """Determine if wired is active, and if yes, set the status."""
if wired_ip and wired.CheckPluggedIn(): if wired_ip and wired.CheckPluggedIn():
set_status( set_status(_('Connected to wired network (IP: $A)')
_('Connected to wired network (IP: $A)').replace('$A',wired_ip) .replace('$A', wired_ip))
)
return True return True
else: else:
return False return False
@@ -171,10 +156,10 @@ def check_for_wireless(iwconfig, wireless_ip, set_status):
return False return False
strength = misc.to_unicode(daemon.FormatSignalForPrinting(strength)) strength = misc.to_unicode(daemon.FormatSignalForPrinting(strength))
ip = misc.to_unicode(wireless_ip) ip = misc.to_unicode(wireless_ip)
set_status(_('Connected to $A at $B (IP: $C)').replace set_status(_('Connected to $A at $B (IP: $C)')
('$A', network).replace .replace('$A', network)
('$B', strength).replace .replace('$B', strength)
('$C', ip)) .replace('$C', ip))
return True return True
@@ -188,10 +173,10 @@ def gen_network_list():
wlessL = [] wlessL = []
# This one makes a list of NetLabels # This one makes a list of NetLabels
for network_id in range(0, wireless.GetNumberOfNetworks()): for network_id in range(0, wireless.GetNumberOfNetworks()):
is_active = \ is_active = (wireless.GetCurrentSignalStrength("") != 0 and
wireless.GetCurrentSignalStrength("") != 0 and \ wireless.GetCurrentNetworkID(wireless.GetIwconfig()) ==
wireless.GetCurrentNetworkID(wireless.GetIwconfig()) == network_id \ network_id and
and wireless.GetWirelessIP('') is not None wireless.GetWirelessIP('') is not None)
label = NetLabel(network_id, is_active) label = NetLabel(network_id, is_active)
wlessL.append(label) wlessL.append(label)
@@ -203,20 +188,24 @@ def about_dialog(body):
# This looks A LOT better when it is actually displayed. I promise :-). # This looks A LOT better when it is actually displayed. I promise :-).
# The ASCII Art "Wicd" was made from the "smslant" font on one of those # The ASCII Art "Wicd" was made from the "smslant" font on one of those
# online ASCII big text generators. # online ASCII big text generators.
theText = [ theText = [('green', " /// \\\\\\"),
('green', " /// \\\\\\"), " _ ___ __\n", " _ ___ __\n",
('green', " /// \\\\\\"), " | | /| / (_)______/ /\n", ('green', " /// \\\\\\"),
('green', " /// \\\\\\"), " | |/ |/ / / __/ _ / \n", " | | /| / (_)______/ /\n",
('green', "/|| // \\\\ ||\\"), " |__/|__/_/\__/\_,_/ \n", ('green', " /// \\\\\\"),
" | |/ |/ / / __/ _ / \n",
('green', "/|| // \\\\ ||\\"),
" |__/|__/_/\__/\_,_/ \n",
('green', "||| ||"), "(|^|)", ('green', "|| |||"), ('green', "||| ||"), "(|^|)", ('green', "|| |||"),
" ($VERSION) \n".replace("$VERSION", daemon.Hello()), " ($VERSION) \n".replace("$VERSION",
daemon.Hello()),
('green', "\\|| \\\\"), " |+| ", ('green', "// ||/ \n"), ('green', "\\|| \\\\"), " |+| ", ('green', "// ||/ \n"),
('green', " \\\\\\"), " |+| ", ('green', "///"), ('green', " \\\\\\"), " |+| ", ('green', "///"),
" http://launchpad.net/wicd\n", " http://launchpad.net/wicd\n",
('green', " \\\\\\"), " |+| ", ('green', "///"), " ", ('green', " \\\\\\"), " |+| ", ('green', "///"), " ",
_('Brought to you by:'), "\n", _('Brought to you by:'), "\n",
('green', " \\\\\\"), " |+| ", ('green', "///"), " * Tom Van Braeckel\n", ('green', " \\\\\\"), " |+| ",
('green', "///"), " * Tom Van Braeckel\n",
" __|+|__ * Adam Blackburn\n", " __|+|__ * Adam Blackburn\n",
" ___|+|___ * Dan O'Reilly\n", " ___|+|___ * Dan O'Reilly\n",
" ____|+|____ * Andrew Psaltis\n", " ____|+|____ * Andrew Psaltis\n",
@@ -234,32 +223,41 @@ def help_dialog(body):
' using wicd ', str(daemon.Hello()), '\n' ' using wicd ', str(daemon.Hello()), '\n'
]) ])
textH = urwid.Text([ textH = urwid.Text([_('For more detailed help, consult the wicd-curses(8) '
_('For more detailed help, consult the wicd-curses(8) man page.') + "\n", 'man page.') + "\n", ('bold', '->'), ' and ',
('bold', '->'), ' and ', ('bold', '<-'), ('bold', '<-'), " are the right and left arrows "
" are the right and left arrows respectively.\n" "respectively.\n"])
])
text1 = urwid.Text([ text1 = urwid.Text([('bold', ' H h ?'),
('bold', ' H h ?'), ": " + _('Display this help dialog') + "\n", ": " + _('Display this help dialog') + "\n",
('bold', 'enter C'), ": " + _('Connect to selected network') + "\n", ('bold', 'enter C'),
('bold', ' D'), ": " + _('Disconnect from all networks') + "\n", ": " + _('Connect to selected network') + "\n",
('bold', ' ESC'), ": " + _('Stop a connection in progress') + "\n", ('bold', ' D'),
('bold', ' F5 R'), ": " + _('Refresh network list') + "\n", ": " + _('Disconnect from all networks') + "\n",
('bold', ' P'), ": " + _('Preferences dialog') + "\n", ('bold', ' ESC'),
]) ": " + _('Stop a connection in progress') + "\n",
text2 = urwid.Text([ ('bold', ' F5 R'),
('bold', ' I'), ": " + _('Scan for hidden networks') + "\n", ": " + _('Refresh network list') + "\n",
('bold', ' S'), ": " + _('Select scripts') + "\n", ('bold', ' P'),
('bold', ' O'), ": " + _('Set up Ad-hoc network') + "\n", ": " + _('Preferences dialog') + "\n"])
('bold', ' X'), ": " + _('Remove settings for saved networks') + "\n", text2 = urwid.Text([('bold', ' I'),
('bold', ' ->'), ": " + _('Configure selected network') + "\n", ": " + _('Scan for hidden networks') + "\n",
('bold', ' A'), ": " + _("Display 'about' dialog") + "\n", ('bold', ' S'),
('bold', ' F8 q Q'), ": " + _('Quit wicd-curses') + "\n", ": " + _('Select scripts') + "\n",
]) ('bold', ' O'),
": " + _('Set up Ad-hoc network') + "\n",
('bold', ' X'),
": " + _('Remove settings for saved networks') + "\n",
('bold', ' ->'),
": " + _('Configure selected network') + "\n",
('bold', ' A'),
": " + _("Display 'about' dialog") + "\n",
('bold', ' F8 q Q'),
": " + _('Quit wicd-curses') + "\n"])
textF = urwid.Text(_('Press any key to return.')) textF = urwid.Text(_('Press any key to return.'))
#textJ = urwid.Text(('important', 'Nobody expects the Spanish Inquisition!')) # textJ = urwid.Text(('important',
# 'Nobody expects the Spanish Inquisition!'))
blank = urwid.Text('') blank = urwid.Text('')
@@ -301,22 +299,25 @@ def run_configscript(parent, netname, nettype):
profname = nettype profname = nettype
else: else:
profname = wireless.GetWirelessProperty(int(netname), 'bssid') profname = wireless.GetWirelessProperty(int(netname), 'bssid')
theText = [ theText = [_('To avoid various complications, wicd-curses does not '
_('To avoid various complications, wicd-curses does not support directly ' 'support directly editing the scripts. However, you can '
'editing the scripts. However, you can edit them manually. First, (as root), ' 'edit them manually. First, (as root), open the "$A" config '
'open the "$A" config file, and look for the section labeled by the $B in ' 'file, and look for the section labeled by the $B in '
'question. In this case, this is:'). 'question. In this case, this is:')
replace('$A', configfile).replace('$B', header), .replace('$A', configfile)
.replace('$B', header),
"\n\n[" + profname + "]\n\n", "\n\n[" + profname + "]\n\n",
_('You can also configure the wireless networks by looking for the "[<ESSID>]" ' _('You can also configure the wireless networks by looking '
'field in the config file.'), 'for the "[<ESSID>]" field in the config file.'),
_('Once there, you can adjust (or add) the "beforescript", "afterscript", ' _('Once there, you can adjust (or add) the "beforescript", '
'"predisconnectscript" and "postdisconnectscript" variables as needed, to ' '"afterscript", "predisconnectscript" and '
'change the preconnect, postconnect, predisconnect and postdisconnect scripts ' '"postdisconnectscript" variables as needed, to change the '
'respectively. Note that you will be specifying the full path to the scripts ' 'preconnect, postconnect, predisconnect and postdisconnect '
'- not the actual script contents. You will need to add/edit the script ' 'scripts respectively. Note that you will be specifying '
'contents separately. Refer to the wicd manual page for more information.') 'the full path to the scripts - not the actual script '
] 'contents. You will need to add/edit the script contents '
'separately. Refer to the wicd manual page for more '
'information.')]
dialog = TextDialog(theText, 20, 80) dialog = TextDialog(theText, 20, 80)
dialog.run(ui, parent) dialog.run(ui, parent)
# This code works with many distributions, but not all of them. So, to # This code works with many distributions, but not all of them. So, to
@@ -363,14 +364,12 @@ def gen_list_header():
return 'C %s %*s %9s %17s %6s %s' % \ return 'C %s %*s %9s %17s %6s %s' % \
('STR ', essidgap, 'ESSID', 'ENCRYPT', 'BSSID', 'MODE', 'CHNL') ('STR ', essidgap, 'ESSID', 'ENCRYPT', 'BSSID', 'MODE', 'CHNL')
""" Some people use CTRL-\ to quit the application (SIGQUIT) """
def handle_sigquit(signal_number, stack_frame): def handle_sigquit(signal_number, stack_frame):
"""Some people use CTRL-\ to quit the application (SIGQUIT)"""
loop.quit() loop.quit()
ui.stop() ui.stop()
########################################
##### URWID SUPPORT CLASSES
########################################
class NetLabel(urwid.WidgetWrap): class NetLabel(urwid.WidgetWrap):
"""Wireless network label.""" """Wireless network label."""
@@ -434,22 +433,22 @@ class WiredComboBox(ComboBox):
list : the list of wired network profiles. The rest is self-explanitory. list : the list of wired network profiles. The rest is self-explanitory.
""" """
# pylint: disable-msg=W0231 # pylint: disable-msg=W0231
def __init__(self, l): def __init__(self, wired_list):
self.ADD_PROFILE = '---' + _('Add a new profile') + '---' self.ADD_PROFILE = '---' + _('Add a new profile') + '---'
# pylint: disable-msg=E1101 # pylint: disable-msg=E1101
self.__super.__init__(use_enter=False) self.__super.__init__(use_enter=False)
self.theList = [] self.theList = []
self.set_list(l) self.set_list(wired_list)
def set_list(self, l): def set_list(self, wired_list):
"""Set contents of the combobox.""" """Set contents of the combobox."""
self.theList = l self.theList = wired_list
i = 0 i = 0
wiredL = [] wiredL = []
is_active = \ is_active = \
wireless.GetWirelessIP('') is None and \ wireless.GetWirelessIP('') is None and \
wired.GetWiredIP('') is not None wired.GetWiredIP('') is not None
for profile in l: for profile in wired_list:
theString = '%4s %25s' % (i, profile) theString = '%4s %25s' % (i, profile)
# Tag if no wireless IP present, and wired one is # Tag if no wireless IP present, and wired one is
if is_active: if is_active:
@@ -474,10 +473,8 @@ class WiredComboBox(ComboBox):
key = ComboBox.keypress(self, size, key) key = ComboBox.keypress(self, size, key)
if key == ' ': if key == ' ':
if self.get_focus()[1] == len(self.list) - 1: if self.get_focus()[1] == len(self.list) - 1:
dialog = InputDialog( dialog = InputDialog(('header', _('Add a new wired profile')),
('header', _('Add a new wired profile')), 7, 30)
7, 30
)
exitcode, name = dialog.run(ui, self.parent) exitcode, name = dialog.run(ui, self.parent)
if exitcode == 0: if exitcode == 0:
name = name.strip() name = name.strip()
@@ -494,12 +491,9 @@ class WiredComboBox(ComboBox):
wired.ReadWiredNetworkProfile(self.get_selected_profile()) wired.ReadWiredNetworkProfile(self.get_selected_profile())
if key == 'delete': if key == 'delete':
if len(self.theList) == 1: if len(self.theList) == 1:
error( error(self.ui, self.parent,
self.ui, _('wicd-curses does not support deleting the last '
self.parent, 'wired profile. Try renaming it ("F2")'))
_('wicd-curses does not support deleting the last wired '
'profile. Try renaming it ("F2")')
)
return key return key
wired.DeleteWiredNetworkProfile(self.get_selected_profile()) wired.DeleteWiredNetworkProfile(self.get_selected_profile())
# Return to the top of the list if something is deleted. # Return to the top of the list if something is deleted.
@@ -551,8 +545,8 @@ class AdHocDialog(Dialog2):
self.key_edit = DynEdit(key_t, sensitive=False) self.key_edit = DynEdit(key_t, sensitive=False)
self.use_ics_chkb = urwid.CheckBox(use_ics_t) self.use_ics_chkb = urwid.CheckBox(use_ics_t)
self.use_encrypt_chkb = urwid.CheckBox(use_encrypt_t, self.use_encrypt_chkb = urwid.CheckBox(
on_state_change=self.encrypt_callback) use_encrypt_t, on_state_change=self.encrypt_callback)
blank = urwid.Text('') blank = urwid.Text('')
@@ -561,9 +555,9 @@ class AdHocDialog(Dialog2):
self.ip_edit.set_edit_text("169.254.12.10") self.ip_edit.set_edit_text("169.254.12.10")
self.channel_edit.set_edit_text("3") self.channel_edit.set_edit_text("3")
l = [self.essid_edit, self.ip_edit, self.channel_edit, blank, lb = [self.essid_edit, self.ip_edit, self.channel_edit, blank,
self.use_ics_chkb, self.use_encrypt_chkb, self.key_edit] self.use_ics_chkb, self.use_encrypt_chkb, self.key_edit]
body = urwid.ListBox(l) body = urwid.ListBox(lb)
header = ('header', _('Create an Ad-Hoc Network')) header = ('header', _('Create an Ad-Hoc Network'))
Dialog2.__init__(self, header, 15, 50, body) Dialog2.__init__(self, header, 15, 50, body)
@@ -608,7 +602,7 @@ class ForgetDialog(Dialog2):
'listbar' 'listbar'
) )
title = urwid.Text(_('Please select the networks to forget')) title = urwid.Text(_('Please select the networks to forget'))
l = [title, header] lb = [title, header]
for entry in wireless.GetSavedWirelessNetworks(): for entry in wireless.GetSavedWirelessNetworks():
label = '%20s %20s' label = '%20s %20s'
if entry[1] != 'None': if entry[1] != 'None':
@@ -623,8 +617,8 @@ class ForgetDialog(Dialog2):
on_state_change=self.update_to_remove, on_state_change=self.update_to_remove,
user_data=data user_data=data
) )
l.append(cb) lb.append(cb)
body = urwid.ListBox(l) body = urwid.ListBox(lb)
header = ('header', _('List of saved networks')) header = ('header', _('List of saved networks'))
Dialog2.__init__(self, header, 15, 50, body) Dialog2.__init__(self, header, 15, 50, body)
@@ -657,9 +651,6 @@ class ForgetDialog(Dialog2):
return exitcode, self.to_remove return exitcode, self.to_remove
########################################
##### APPLICATION INTERFACE CLASS
########################################
# The Whole Shebang # The Whole Shebang
class appGUI(): class appGUI():
"""The UI itself, all glory belongs to it!""" """The UI itself, all glory belongs to it!"""
@@ -686,7 +677,8 @@ class appGUI():
self.WIRED_IDX = 1 self.WIRED_IDX = 1
self.WLESS_IDX = 3 self.WLESS_IDX = 3
header = urwid.AttrWrap(urwid.Text(self.TITLE, align='right'), 'header') header = urwid.AttrWrap(urwid.Text(self.TITLE, align='right'),
'header')
self.wiredH = urwid.Filler(urwid.Text(_('Wired Networks'))) self.wiredH = urwid.Filler(urwid.Text(_('Wired Networks')))
self.list_header = urwid.AttrWrap( self.list_header = urwid.AttrWrap(
urwid.Text(gen_list_header()), 'listbar' urwid.Text(gen_list_header()), 'listbar'
@@ -713,8 +705,7 @@ class appGUI():
self.update_netlist(force_check=True, firstrun=True) self.update_netlist(force_check=True, firstrun=True)
# Keymappings proposed by nanotube in #wicd # Keymappings proposed by nanotube in #wicd
keys = [ keys = [('H', _('Help'), None),
('H', _('Help'), None),
('right', _('Config'), None), ('right', _('Config'), None),
# (' ', ' ', None), # (' ', ' ', None),
('K', _('RfKill'), None), ('K', _('RfKill'), None),
@@ -724,8 +715,7 @@ class appGUI():
('P', _('Prefs'), None), ('P', _('Prefs'), None),
('I', _('Hidden'), None), ('I', _('Hidden'), None),
('A', _('About'), None), ('A', _('About'), None),
('Q', _('Quit'), loop.quit) ('Q', _('Quit'), loop.quit)]
]
self.primaryCols = OptCols(keys, self.handle_keys) self.primaryCols = OptCols(keys, self.handle_keys)
self.status_label = urwid.AttrWrap(urwid.Text(''), 'important') self.status_label = urwid.AttrWrap(urwid.Text(''), 'important')
@@ -745,7 +735,8 @@ class appGUI():
self.prev_state = False self.prev_state = False
self.connecting = False self.connecting = False
self.screen_locked = False self.screen_locked = False
self.do_diag_lock = False # Whether the screen is locked beneath a dialog # Whether the screen is locked beneath a dialog
self.do_diag_lock = False
self.diag_type = 'none' # The type of dialog that is up self.diag_type = 'none' # The type of dialog that is up
self.scanning = False self.scanning = False
@@ -762,16 +753,12 @@ class appGUI():
def init_other_optcols(self): def init_other_optcols(self):
"""Init "tabbed" preferences dialog.""" """Init "tabbed" preferences dialog."""
self.prefCols = OptCols([ self.prefCols = OptCols([('S', _('Save')),
('S', _('Save')),
('page up', _('Tab Left'), ), ('page up', _('Tab Left'), ),
('page down', _('Tab Right')), ('page down', _('Tab Right')),
('esc', _('Cancel')) ('esc', _('Cancel'))], self.handle_keys)
], self.handle_keys) self.confCols = OptCols([('S', _('Save')),
self.confCols = OptCols([ ('esc', _('Cancel'))], self.handle_keys)
('S', _('Save')),
('esc', _('Cancel'))
], self.handle_keys)
def lock_screen(self): def lock_screen(self):
"""Lock the screen.""" """Lock the screen."""
@@ -872,8 +859,10 @@ class appGUI():
get_body().set_focus(self.focusloc[1]) get_body().set_focus(self.focusloc[1])
else: else:
if self.wlessLB != self.no_wlan: if self.wlessLB != self.no_wlan:
# Set the focus to the last selected item, but never past the length of the list # Set the focus to the last selected item, but never
self.thePile.get_focus().set_focus(min(self.focusloc[1], len(wlessL) - 1)) # past the length of the list
self.thePile.get_focus().set_focus(
min(self .focusloc[1], len(wlessL) - 1))
else: else:
self.thePile.set_focus(self.wiredCB) self.thePile.set_focus(self.wiredCB)
else: else:
@@ -886,8 +875,10 @@ class appGUI():
if self.focusloc[1] is None: if self.focusloc[1] is None:
self.focusloc[1] = 0 self.focusloc[1] = 0
if self.wlessLB != self.no_wlan: if self.wlessLB != self.no_wlan:
# Set the focus to the last selected item, but never past the length of the list # Set the focus to the last selected item, but never past
self.wlessLB.set_focus(min(self.focusloc[1], len(wlessL) - 1)) # the length of the list
self.wlessLB.set_focus(min(self.focusloc[1],
len(wlessL) - 1))
self.prev_state = state self.prev_state = state
if not firstrun: if not firstrun:
@@ -896,9 +887,7 @@ class appGUI():
if wired.GetDefaultWiredNetwork() is not None: if wired.GetDefaultWiredNetwork() is not None:
self.wiredCB.get_body().set_focus( self.wiredCB.get_body().set_focus(
wired.GetWiredProfileList().index( wired.GetWiredProfileList().index(
wired.GetDefaultWiredNetwork() wired.GetDefaultWiredNetwork()))
)
)
@wrap_exceptions @wrap_exceptions
def update_status(self): def update_status(self):
@@ -941,8 +930,8 @@ class appGUI():
stat = wireless.CheckWirelessConnectingMessage() stat = wireless.CheckWirelessConnectingMessage()
return self.set_status("%s: %s" % (essid, stat), True) return self.set_status("%s: %s" % (essid, stat), True)
if wired_connecting: if wired_connecting:
return self.set_status(_('Wired Network') + return self.set_status(_('Wired Network') + ': ' +
': ' + wired.CheckWiredConnectingMessage(), True) wired.CheckWiredConnectingMessage(), True)
else: else:
self.conn_status = False self.conn_status = False
return False return False
@@ -1065,7 +1054,8 @@ class appGUI():
) )
self.pref.load_settings() self.pref.load_settings()
self.pref.ready_widgets(ui, self.frame) self.pref.ready_widgets(ui, self.frame)
self.frame.set_footer(urwid.Pile([self.prefCols, self.footer2])) self.frame.set_footer(urwid.Pile([self.prefCols,
self.footer2]))
self.diag = self.pref self.diag = self.pref
self.diag_type = 'pref' self.diag_type = 'pref'
self.frame.set_body(self.diag) self.frame.set_body(self.diag)
@@ -1108,9 +1098,10 @@ class appGUI():
text = _('Are you sure you want to discard settings for ' text = _('Are you sure you want to discard settings for '
'the selected networks?') 'the selected networks?')
text += '\n\n' + '\n'.join(data['essid']) text += '\n\n' + '\n'.join(data['essid'])
confirm, trash = TextDialog(text, 20, 50, confirm, trash = TextDialog(
buttons=[(_('OK'), 1), (_('Cancel'), -1)], text, 20, 50,
).run(ui, self.frame) buttons=[(_('OK'), 1),
(_('Cancel'), -1)],).run(ui, self.frame)
if confirm == 1: if confirm == 1:
for x in data['bssid']: for x in data['bssid']:
wireless.DeleteWirelessNetwork(x) wireless.DeleteWirelessNetwork(x)
@@ -1132,7 +1123,8 @@ class appGUI():
break break
# F10 has been changed to S to avoid using function keys, # F10 has been changed to S to avoid using function keys,
# which are often caught by the terminal emulator. # which are often caught by the terminal emulator.
# But F10 still works, because it doesn't hurt and some users might be used to it. # But F10 still works, because it doesn't hurt and some users
# might be used to it.
if k == 'f10' or k == 'S' or k == 's': if k == 'f10' or k == 'S' or k == 's':
self.diag.save_settings() self.diag.save_settings()
self.restore_primary() self.restore_primary()
@@ -1175,9 +1167,6 @@ class appGUI():
self.update_status() self.update_status()
########################################
##### INITIALIZATION FUNCTIONS
########################################
def main(): def main():
"""Main function.""" """Main function."""
global ui, dlogger global ui, dlogger
@@ -1216,7 +1205,8 @@ def main():
('red', 'dark red', 'default'), ('red', 'dark red', 'default'),
('bold', 'white', 'black', 'bold') ('bold', 'white', 'black', 'bold')
]) ])
# Handle SIGQUIT correctly (otherwise urwid leaves the terminal in a bad state) # Handle SIGQUIT correctly (otherwise urwid leaves the terminal in a bad
# state)
signal.signal(signal.SIGQUIT, handle_sigquit) signal.signal(signal.SIGQUIT, handle_sigquit)
# This is a wrapper around a function that calls another a function that # This is a wrapper around a function that calls another a function that
# is a wrapper around a infinite loop. Fun. # is a wrapper around a infinite loop. Fun.
@@ -1259,7 +1249,8 @@ def setup_dbus(force=True):
try: try:
dbusmanager.connect_to_dbus() dbusmanager.connect_to_dbus()
except DBusException: except DBusException:
print(_("Can't connect to the daemon, trying to start it automatically..."), file=sys.stderr) print(_("Can't connect to the daemon, trying to start it "
"automatically..."), file=sys.stderr)
try: try:
bus = dbusmanager.get_bus() bus = dbusmanager.get_bus()
@@ -1268,33 +1259,31 @@ def setup_dbus(force=True):
wireless = dbus_ifaces['wireless'] wireless = dbus_ifaces['wireless']
wired = dbus_ifaces['wired'] wired = dbus_ifaces['wired']
except DBusException: except DBusException:
print(_("Can't automatically start the daemon, this error is fatal..."), file=sys.stderr) print(_("Can't automatically start the daemon, this error is "
"fatal..."), file=sys.stderr)
if not daemon: if not daemon:
print('Error connecting to wicd via D-Bus. ' \ print('Error connecting to wicd via D-Bus.\nPlease make sure the '
'Please make sure the wicd service is running.') 'wicd service is running.')
sys.exit(3) sys.exit(3)
netentry_curses.dbus_init(dbus_ifaces) netentry_curses.dbus_init(dbus_ifaces)
return True return True
setup_dbus() setup_dbus()
########################################
##### MAIN ENTRY POINT
########################################
if __name__ == '__main__': if __name__ == '__main__':
try: try:
parser = OptionParser( parser = OptionParser(version="wicd-curses-%s (using wicd %s)" %
version="wicd-curses-%s (using wicd %s)" %
(CURSES_REV, daemon.Hello()), (CURSES_REV, daemon.Hello()),
prog="wicd-curses" prog="wicd-curses")
)
except Exception as e: except Exception as e:
if "DBus.Error.AccessDenied" in e.get_dbus_name(): if "DBus.Error.AccessDenied" in e.get_dbus_name():
print(_('ERROR: wicd-curses was denied access to the wicd daemon: ' print(_('ERROR: wicd-curses was denied access to the wicd daemon: '
'please check that your user is in the "$A" group.'). \ 'please check that your user is in the "$A" group.')
replace('$A', '\033[1;34m' + wpath.wicd_group + '\033[0m')) .replace('$A', '\033[1;34m' + wpath.wicd_group + '\033[0m'))
sys.exit(1) sys.exit(1)
else: else:
raise raise

View File

@@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""configscript -- Configure the scripts for a particular network. """configscript -- Configure the scripts for a particular network.
Script for configuring the scripts for a network passed in as a Script for configuring the scripts for a network passed in as a
@@ -8,7 +7,6 @@ editing scripts requires root access, and the GUI/Tray are typically
run as the current user. run as the current user.
""" """
# #
# Copyright (C) 2007-2009 Adam Blackburn # Copyright (C) 2007-2009 Adam Blackburn
# Copyright (C) 2007-2009 Dan O'Reilly # Copyright (C) 2007-2009 Dan O'Reilly
@@ -57,6 +55,7 @@ def none_to_blank(text):
else: else:
return str(text) return str(text)
def blank_to_none(text): def blank_to_none(text):
"""Convert an empty or null string to 'None'.""" """Convert an empty or null string to 'None'."""
if text in ("", None): if text in ("", None):
@@ -64,30 +63,30 @@ def blank_to_none(text):
else: else:
return str(text) return str(text)
def get_script_info(network, network_type): def get_script_info(network, network_type):
""" Read script info from disk and load it into the configuration dialog """ """
Read script info from disk and load it into the configuration dialog
"""
info = {} info = {}
if network_type == "wired": if network_type == "wired":
con = ConfigManager(wired_conf) con = ConfigManager(wired_conf)
if con.has_section(network): section = network
info["pre_entry"] = con.get(network, "beforescript", None)
info["post_entry"] = con.get(network, "afterscript", None)
info["pre_disconnect_entry"] = con.get(network,
"predisconnectscript", None)
info["post_disconnect_entry"] = con.get(network,
"postdisconnectscript", None)
else: else:
bssid = wireless.GetWirelessProperty(int(network), "bssid") bssid = wireless.GetWirelessProperty(int(network), "bssid")
con = ConfigManager(wireless_conf) con = ConfigManager(wireless_conf)
if con.has_section(bssid): section = bssid
info["pre_entry"] = con.get(bssid, "beforescript", None)
info["post_entry"] = con.get(bssid, "afterscript", None) if con.has_section(section):
info["pre_disconnect_entry"] = con.get(bssid, info["pre_entry"] = con.get(section, "beforescript", None)
info["post_entry"] = con.get(section, "afterscript", None)
info["pre_disconnect_entry"] = con.get(section,
"predisconnectscript", None) "predisconnectscript", None)
info["post_disconnect_entry"] = con.get(bssid, info["post_disconnect_entry"] = con.get(section,
"postdisconnectscript", None) "postdisconnectscript", None)
return info return info
def write_scripts(network, network_type, script_info): def write_scripts(network, network_type, script_info):
"""Writes script info to disk and loads it into the daemon.""" """Writes script info to disk and loads it into the daemon."""
if network_type == "wired": if network_type == "wired":

View File

@@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""gui -- The main wicd GUI module. """gui -- The main wicd GUI module.
Module containing the code for the main wicd GUI. Module containing the code for the main wicd GUI.
@@ -26,6 +25,7 @@ Module containing the code for the main wicd GUI.
import os import os
import sys import sys
import time import time
from gi.repository import GLib as gobject from gi.repository import GLib as gobject
import gtk import gtk
from itertools import chain from itertools import chain
@@ -65,11 +65,8 @@ def setup_dbus(force=True):
try: try:
dbusmanager.connect_to_dbus() dbusmanager.connect_to_dbus()
except DBusException: except DBusException:
error( error(None, _("Could not connect to wicd's D-Bus interface. "
None, "Check the wicd log for error messages."))
_("Could not connect to wicd's D-Bus interface. "
"Check the wicd log for error messages.")
)
return False return False
else: else:
return False return False
@@ -92,12 +89,8 @@ def handle_no_dbus(from_tray=False):
if from_tray: if from_tray:
return False return False
print("Wicd daemon is shutting down!") print("Wicd daemon is shutting down!")
error( error(None, _('The wicd daemon has shut down. The UI will not function '
None, 'properly until it is restarted.'), block=False)
_('The wicd daemon has shut down. The UI will not function '
'properly until it is restarted.'),
block=False
)
return False return False
@@ -166,6 +159,7 @@ def get_wireless_prop(net_id, prop):
"""Get wireless property.""" """Get wireless property."""
return wireless.GetWirelessProperty(net_id, prop) return wireless.GetWirelessProperty(net_id, prop)
class appGui(object): class appGui(object):
"""The main wicd GUI class.""" """The main wicd GUI class."""
def __init__(self, standalone=False, tray=None): def __init__(self, standalone=False, tray=None):
@@ -336,8 +330,8 @@ class appGui(object):
"WEP", "WEP",
self.key_entry.entry.get_text(), self.key_entry.entry.get_text(),
self.chkbox_use_encryption.get_active(), self.chkbox_use_encryption.get_active(),
False # chkbox_use_ics.get_active()) False) # chkbox_use_ics.get_active())
)
dialog.destroy() dialog.destroy()
def forget_network(self, widget=None): def forget_network(self, widget=None):
@@ -359,7 +353,8 @@ class appGui(object):
if entry[1] != 'None': if entry[1] != 'None':
networks.append(entry) networks.append(entry)
else: else:
networks.append((entry[0], _('Global settings for this ESSID'))) networks.append((entry[0],
_('Global settings for this ESSID')))
tree = gtk.TreeView(model=networks) tree = gtk.TreeView(model=networks)
tree.get_selection().set_mode(gtk.SELECTION_MULTIPLE) tree.get_selection().set_mode(gtk.SELECTION_MULTIPLE)
@@ -395,9 +390,8 @@ class appGui(object):
flags=gtk.DIALOG_MODAL, flags=gtk.DIALOG_MODAL,
type=gtk.MESSAGE_INFO, type=gtk.MESSAGE_INFO,
buttons=gtk.BUTTONS_YES_NO, buttons=gtk.BUTTONS_YES_NO,
message_format=_('Are you sure you want to discard' + message_format=_('Are you sure you want to discard '
' settings for the selected networks?') 'settings for the selected networks?'))
)
confirm.format_secondary_text('\n'.join(to_remove['essid'])) confirm.format_secondary_text('\n'.join(to_remove['essid']))
response = confirm.run() response = confirm.run()
if response == gtk.RESPONSE_YES: if response == gtk.RESPONSE_YES:
@@ -486,8 +480,7 @@ class appGui(object):
def cancel_connect(self, widget): def cancel_connect(self, widget):
"""Alerts the daemon to cancel the connection process.""" """Alerts the daemon to cancel the connection process."""
#should cancel a connection if there # should cancel a connection if there is one in progress
#is one in progress
cancel_button = self.wTree.get_object("cancel_button") cancel_button = self.wTree.get_object("cancel_button")
cancel_button.set_sensitive(False) cancel_button.set_sensitive(False)
daemon.CancelConnect() daemon.CancelConnect()
@@ -502,7 +495,7 @@ class appGui(object):
return True return True
try: try:
gobject.idle_add(self.wTree.get_object("progressbar").pulse) gobject.idle_add(self.wTree.get_object("progressbar").pulse)
except: except Exception:
pass pass
return True return True
@@ -595,8 +588,8 @@ class appGui(object):
stat = wireless.CheckWirelessConnectingMessage() stat = wireless.CheckWirelessConnectingMessage()
gobject.idle_add(self.set_status, "%s: %s" % (info[1], stat)) gobject.idle_add(self.set_status, "%s: %s" % (info[1], stat))
elif info[0] == "wired": elif info[0] == "wired":
gobject.idle_add(self.set_status, _('Wired Network') + ': ' gobject.idle_add(self.set_status, _('Wired Network') + ': ' +
+ wired.CheckWiredConnectingMessage()) wired.CheckWiredConnectingMessage())
return True return True
def update_connect_buttons(self, state=None, x=None, force_check=False): def update_connect_buttons(self, state=None, x=None, force_check=False):
@@ -797,7 +790,8 @@ class appGui(object):
dialog.set_values() dialog.set_values()
dialog.show_all() dialog.show_all()
while True: while True:
if self.run_settings_dialog(dialog, ttype, networkid, networkentry): if self.run_settings_dialog(dialog, ttype, networkid,
networkentry):
break break
dialog.hide() dialog.hide()
@@ -824,20 +818,15 @@ class appGui(object):
for entry_info in list(encryption_info.values()): for entry_info in list(encryption_info.values()):
if entry_info[0].entry.get_text() == "" and \ if entry_info[0].entry.get_text() == "" and \
entry_info[1] == 'required': entry_info[1] == 'required':
error( error(self.window, "%s (%s)" %
self.window,
"%s (%s)" %
(_('Required encryption information is missing.'), (_('Required encryption information is missing.'),
entry_info[0].label.get_label()) entry_info[0].label.get_label()))
)
return False return False
# Make sure the checkbox is checked when it should be # Make sure the checkbox is checked when it should be
elif not entry.chkbox_encryption.get_active() and \ elif (not entry.chkbox_encryption.get_active() and
wireless.GetWirelessProperty(networkid, "encryption"): wireless.GetWirelessProperty(networkid, "encryption")):
error( error(self.window, _('This network requires encryption to be '
self.window, 'enabled.'))
_('This network requires encryption to be enabled.')
)
return False return False
return True return True

View File

@@ -23,9 +23,9 @@ contained within them.
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
import os
import gtk import gtk
import os
import wicd.misc as misc import wicd.misc as misc
import wicd.wpath as wpath import wicd.wpath as wpath
@@ -239,14 +239,14 @@ class AdvancedSettingsDialog(gtk.Dialog):
self.chkbox_global_dns.set_sensitive(self.chkbox_static_dns. self.chkbox_global_dns.set_sensitive(self.chkbox_static_dns.
get_active()) get_active())
l = [self.txt_dns_1, self.txt_dns_2, self.txt_dns_3, self.txt_domain, search_list = [self.txt_dns_1, self.txt_dns_2, self.txt_dns_3,
self.txt_search_dom] self.txt_domain, self.txt_search_dom]
if self.chkbox_static_dns.get_active(): if self.chkbox_static_dns.get_active():
# If global dns is on, don't use local dns # If global dns is on, don't use local dns
for w in l: for w in search_list:
w.set_sensitive(not self.chkbox_global_dns.get_active()) w.set_sensitive(not self.chkbox_global_dns.get_active())
else: else:
for w in l: for w in search_list:
w.set_sensitive(False) w.set_sensitive(False)
self.chkbox_global_dns.set_active(False) self.chkbox_global_dns.set_active(False)
@@ -270,7 +270,9 @@ class AdvancedSettingsDialog(gtk.Dialog):
w.set_sensitive(not self.chkbox_global_dns.get_active()) w.set_sensitive(not self.chkbox_global_dns.get_active())
def toggle_encryption(self, widget=None): def toggle_encryption(self, widget=None):
""" Toggle the encryption combobox based on the encryption checkbox. """ """
Toggle the encryption combobox based on the encryption checkbox.
"""
active = self.chkbox_encryption.get_active() active = self.chkbox_encryption.get_active()
self.vbox_encrypt_info.set_sensitive(active) self.vbox_encrypt_info.set_sensitive(active)
self.combo_encryption.set_sensitive(active) self.combo_encryption.set_sensitive(active)
@@ -305,8 +307,8 @@ class AdvancedSettingsDialog(gtk.Dialog):
self.set_net_prop("dns1", noneToString(self.txt_dns_1.get_text())) self.set_net_prop("dns1", noneToString(self.txt_dns_1.get_text()))
self.set_net_prop("dns2", noneToString(self.txt_dns_2.get_text())) self.set_net_prop("dns2", noneToString(self.txt_dns_2.get_text()))
self.set_net_prop("dns3", noneToString(self.txt_dns_3.get_text())) self.set_net_prop("dns3", noneToString(self.txt_dns_3.get_text()))
elif self.chkbox_static_dns.get_active() and \ elif (self.chkbox_static_dns.get_active() and
self.chkbox_global_dns.get_active(): self.chkbox_global_dns.get_active()):
self.set_net_prop('use_static_dns', True) self.set_net_prop('use_static_dns', True)
self.set_net_prop('use_global_dns', True) self.set_net_prop('use_global_dns', True)
else: else:
@@ -319,8 +321,8 @@ class AdvancedSettingsDialog(gtk.Dialog):
self.set_net_prop("dns3", '') self.set_net_prop("dns3", '')
self.set_net_prop('usedhcphostname', self.set_net_prop('usedhcphostname',
self.chkbox_use_dhcp_hostname.get_active()) self.chkbox_use_dhcp_hostname.get_active())
self.set_net_prop( self.set_net_prop("dhcphostname", noneToString(self.txt_dhcp_hostname.
"dhcphostname",noneToString(self.txt_dhcp_hostname.get_text())) get_text()))
def change_encrypt_method(self, widget=None): def change_encrypt_method(self, widget=None):
"""Load all the entries for a given encryption method.""" """Load all the entries for a given encryption method."""
@@ -358,8 +360,10 @@ class AdvancedSettingsDialog(gtk.Dialog):
box.entry.set_text(noneToBlankString( box.entry.set_text(noneToBlankString(
wired.GetWiredProperty(field[0]))) wired.GetWiredProperty(field[0])))
else: else:
box.entry.set_text(noneToBlankString( box.entry.set_text(
wireless.GetWirelessProperty(self.networkID, field[0]))) noneToBlankString(wireless.
GetWirelessProperty(self.networkID,
field[0])))
self.vbox_encrypt_info.show_all() self.vbox_encrypt_info.show_all()
@@ -373,8 +377,9 @@ class WiredSettingsDialog(AdvancedSettingsDialog):
# change_encrypt_method()) # change_encrypt_method())
self.wired = True self.wired = True
## This section is largely copied from WirelessSettingsDialog, but with # This section is largely copied from WirelessSettingsDialog, but with
## some changes # some changes
#
# Set up encryption stuff # Set up encryption stuff
self.combo_encryption = gtk.combo_box_new_text() self.combo_encryption = gtk.combo_box_new_text()
self.chkbox_encryption = gtk.CheckButton(_('Use Encryption')) self.chkbox_encryption = gtk.CheckButton(_('Use Encryption'))
@@ -418,12 +423,11 @@ class WiredSettingsDialog(AdvancedSettingsDialog):
prog_num=daemon.GetSudoApp() prog_num=daemon.GetSudoApp()
) )
if not cmdbase: if not cmdbase:
error(None, error(None, _("Could not find a graphical sudo program. "
_('Could not find a graphical sudo program. ' "The script editor could not be launched. "
'The script editor could not be launched. ' "You'll have to edit scripts directly your "
"You'll have to edit scripts directly your configuration " "configuration "
"file.") "file."))
)
return return
cmdbase.extend(cmdend) cmdbase.extend(cmdend)
misc.LaunchAndWait(cmdbase) misc.LaunchAndWait(cmdbase)
@@ -555,8 +559,8 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
activeID = -1 # Set the menu to this item when we are done activeID = -1 # Set the menu to this item when we are done
for x, enc_type in enumerate(self.encrypt_types): for x, enc_type in enumerate(self.encrypt_types):
self.combo_encryption.append_text(enc_type['name']) self.combo_encryption.append_text(enc_type['name'])
if enc_type['type'] == \ if enc_type['type'] == wireless.GetWirelessProperty(networkID,
wireless.GetWirelessProperty(networkID, "enctype"): "enctype"):
activeID = x activeID = x
self.combo_encryption.set_active(activeID) self.combo_encryption.set_active(activeID)
if activeID != -1: if activeID != -1:
@@ -596,13 +600,10 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
prog_num=daemon.GetSudoApp() prog_num=daemon.GetSudoApp()
) )
if not cmdbase: if not cmdbase:
error( error(None, _("Could not find a graphical sudo program. The "
None, "script editor could not be launched. You'll "
_('Could not find a graphical sudo program. ' "have to edit scripts directly your "
'The script editor could not be launched. ' "configuration file."))
"You'll have to edit scripts directly your "
"configuration file.")
)
return return
cmdbase.extend(cmdend) cmdbase.extend(cmdend)
misc.LaunchAndWait(cmdbase) misc.LaunchAndWait(cmdbase)
@@ -636,15 +637,12 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
self.chkbox_encryption.set_active( self.chkbox_encryption.set_active(
bool(wireless.GetWirelessProperty(networkID, 'encryption'))) bool(wireless.GetWirelessProperty(networkID, 'encryption')))
self.chkbox_global_settings.set_active( self.chkbox_global_settings.set_active(
bool( bool(wireless.GetWirelessProperty(networkID,
wireless.GetWirelessProperty(networkID, 'use_settings_globally') 'use_settings_globally')))
)
)
self.chkbox_use_dhcp_hostname.set_active( self.chkbox_use_dhcp_hostname.set_active(
bool(wireless.GetWirelessProperty(networkID, 'usedhcphostname'))) bool(wireless.GetWirelessProperty(networkID, 'usedhcphostname')))
dhcphname = wireless.GetWirelessProperty(networkID, "dhcphostname") dhcphname = wireless.GetWirelessProperty(networkID, "dhcphostname")
if dhcphname is None: if dhcphname is None:
dhcphname = os.uname()[1] dhcphname = os.uname()[1]
@@ -704,8 +702,8 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
for entry_key, entry_info in list(encrypt_info.items()): for entry_key, entry_info in list(encrypt_info.items()):
self.set_net_prop(entry_key, self.set_net_prop(entry_key,
noneToString(entry_info[0].entry.get_text())) noneToString(entry_info[0].entry.get_text()))
elif not self.chkbox_encryption.get_active() and \ elif (not self.chkbox_encryption.get_active() and
wireless.GetWirelessProperty(networkid, "encryption"): wireless.GetWirelessProperty(networkid, "encryption")):
# Encrypt checkbox is off, but the network needs it. # Encrypt checkbox is off, but the network needs it.
error(self, _('This network requires encryption to be enabled.')) error(self, _('This network requires encryption to be enabled.'))
return False return False
@@ -736,7 +734,8 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
def format_entry(self, networkid, label): def format_entry(self, networkid, label):
"""Helper method for fetching/formatting wireless properties.""" """Helper method for fetching/formatting wireless properties."""
return noneToBlankString(wireless.GetWirelessProperty(networkid, label)) return noneToBlankString(wireless.GetWirelessProperty(networkid,
label))
class NetworkEntry(gtk.HBox): class NetworkEntry(gtk.HBox):
@@ -819,13 +818,15 @@ class WiredNetworkEntry(NetworkEntry):
self.button_add = gtk.Button(stock=gtk.STOCK_ADD) self.button_add = gtk.Button(stock=gtk.STOCK_ADD)
self.button_delete = gtk.Button(stock=gtk.STOCK_DELETE) self.button_delete = gtk.Button(stock=gtk.STOCK_DELETE)
self.profile_help = gtk.Label( self.profile_help = gtk.Label(_('To connect to a wired network, you '
_('To connect to a wired network, you must create a network ' 'must create a network profile. To '
'profile. To create a network profile, type a name that describes ' 'create a network profile, type a '
'this network, and press Add.') 'name that describes this network, '
) 'and press Add.'))
self.chkbox_default_profile = gtk.CheckButton( self.chkbox_default_profile = gtk.CheckButton(_('Use as default '
_('Use as default profile (overwrites any previous default)')) 'profile (overwrites '
'any previous '
'default)'))
self.combo_profile_names = gtk.combo_box_new_text() self.combo_profile_names = gtk.combo_box_new_text()
# Format the profile help label. # Format the profile help label.
@@ -1176,7 +1177,8 @@ class WirelessNetworkEntry(NetworkEntry):
def format_entry(self, networkid, label): def format_entry(self, networkid, label):
"""Helper method for fetching/formatting wireless properties.""" """Helper method for fetching/formatting wireless properties."""
return noneToBlankString(wireless.GetWirelessProperty(networkid, label)) return noneToBlankString(wireless.GetWirelessProperty(networkid,
label))
class WirelessInformationDialog(gtk.Dialog): class WirelessInformationDialog(gtk.Dialog):
@@ -1305,4 +1307,5 @@ class WirelessInformationDialog(gtk.Dialog):
def format_entry(self, networkid, label): def format_entry(self, networkid, label):
"""Helper method for fetching/formatting wireless properties.""" """Helper method for fetching/formatting wireless properties."""
return noneToBlankString(wireless.GetWirelessProperty(networkid, label)) return noneToBlankString(wireless.GetWirelessProperty(networkid,
label))

View File

@@ -23,10 +23,14 @@ handles recieving/sendings the settings from/to the daemon.
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
import os
import gtk import gtk
from gi.repository import GObject as gobject from gi.repository import GObject as gobject
import os try:
import pynotify
except ImportError:
pynotify = None
from wicd import misc from wicd import misc
from wicd import wpath from wicd import wpath
@@ -208,9 +212,7 @@ class PreferencesDialog(object):
)) ))
# if pynotify isn't installed disable the option # if pynotify isn't installed disable the option
try: if not pynotify:
import pynotify
except ImportError:
self.notificationscheckbox.set_active(False) self.notificationscheckbox.set_active(False)
self.notificationscheckbox.set_sensitive(False) self.notificationscheckbox.set_sensitive(False)
@@ -354,12 +356,18 @@ class PreferencesDialog(object):
return widget return widget
# External Programs tab # External Programs tab
# self.wTree.get_object("gen_settings_label").set_label(_('General Settings')) # self.wTree.get_object("gen_settings_label").set_label(_('General '
# self.wTree.get_object("ext_prog_label").set_label(_('External Programs')) # 'Settings'))
# self.wTree.get_object("dhcp_client_label").set_label(_('DHCP Client')) # self.wTree.get_object("ext_prog_label").set_label(_('External '
# self.wTree.get_object("wired_detect_label").set_label(_('Wired Link Detection')) # 'Programs'))
# self.wTree.get_object("route_flush_label").set_label(_('Route Table Flushing')) # self.wTree.get_object("dhcp_client_label").set_label(_('DHCP '
# self.wTree.get_object("pref_backend_label").set_label(_('Backend') + ":") # 'Client'))
# self.wTree.get_object("wired_detect_label").set_label(_('Wired Link '
# 'Detection'))
# self.wTree.get_object("route_flush_label").set_label(_('Route Table '
# 'Flushing'))
# self.wTree.get_object("pref_backend_label").set_label(_('Backend') +
# ":")
# entryWiredAutoMethod = self.wTree.get_object("pref_wired_auto_label") # entryWiredAutoMethod = self.wTree.get_object("pref_wired_auto_label")
# entryWiredAutoMethod.set_label('Wired Autoconnect Setting:') # entryWiredAutoMethod.set_label('Wired Autoconnect Setting:')
@@ -374,7 +382,8 @@ class PreferencesDialog(object):
# self.set_label("pref_search_dom_label", "%s:" % _('Search domain')) # self.set_label("pref_search_dom_label", "%s:" % _('Search domain'))
# self.set_label("pref_wifi_label", "%s:" % _('Wireless Interface')) # self.set_label("pref_wifi_label", "%s:" % _('Wireless Interface'))
# self.set_label("pref_wired_label", "%s:" % _('Wired Interface')) # self.set_label("pref_wired_label", "%s:" % _('Wired Interface'))
# self.set_label("pref_driver_label", "%s:" % _('WPA Supplicant Driver')) # self.set_label("pref_driver_label", "%s:" % _('WPA Supplicant '
# 'Driver'))
self.dialog = self.wTree.get_object("pref_dialog") self.dialog = self.wTree.get_object("pref_dialog")
self.dialog.set_title(_('Preferences')) self.dialog.set_title(_('Preferences'))
@@ -384,46 +393,36 @@ class PreferencesDialog(object):
width = 450 width = 450
self.dialog.resize(width, int(gtk.gdk.screen_height() / 2)) self.dialog.resize(width, int(gtk.gdk.screen_height() / 2))
self.wiredcheckbox = setup_label( self.wiredcheckbox = setup_label("pref_always_check",
"pref_always_check", _('''Always show wired interface'''))
_('''Always show wired interface''')
)
self.preferwiredcheckbox = setup_label("pref_prefer_wired_check", self.preferwiredcheckbox = setup_label("pref_prefer_wired_check",
"prefer_wired") "prefer_wired")
self.reconnectcheckbox = setup_label("pref_auto_check", self.reconnectcheckbox = setup_label("pref_auto_check",
_('Automatically reconnect on connection loss')) _('Automatically reconnect on '
'connection loss'))
self.showneverconnectcheckbox = setup_label( self.showneverconnectcheckbox = setup_label(
"pref_show_never_connect_check", "pref_show_never_connect_check", _('Show never connect networks'))
_('Show never connect networks')
)
self.debugmodecheckbox = setup_label("pref_debug_check", self.debugmodecheckbox = setup_label("pref_debug_check",
_('Enable debug mode')) _('Enable debug mode'))
self.displaytypecheckbox = setup_label( self.displaytypecheckbox = setup_label(
"pref_dbm_check", "pref_dbm_check", _('Use dBm to measure signal strength'))
_('Use dBm to measure signal strength')
)
self.verifyapcheckbox = setup_label( self.verifyapcheckbox = setup_label(
"pref_verify_ap_check", "pref_verify_ap_check",
_('Ping static gateways after connecting to verify association') _('Ping static gateways after connecting to verify association'))
)
self.usedefaultradiobutton = setup_label( self.usedefaultradiobutton = setup_label(
"pref_use_def_radio", "pref_use_def_radio",
_('Use default profile on wired autoconnect') _('Use default profile on wired autoconnect'))
)
self.showlistradiobutton = setup_label( self.showlistradiobutton = setup_label(
"pref_prompt_radio", "pref_prompt_radio",
_('Prompt for profile on wired autoconnect') _('Prompt for profile on wired autoconnect'))
)
self.lastusedradiobutton = setup_label( self.lastusedradiobutton = setup_label(
"pref_use_last_radio", "pref_use_last_radio",
_('Use last used profile on wired autoconnect') _('Use last used profile on wired autoconnect'))
)
self.notificationscheckbox = setup_label( self.notificationscheckbox = setup_label(
"pref_use_libnotify", "pref_use_libnotify",
_('Display notifications about connection status') _('Display notifications about connection status'))
)
# DHCP Clients # DHCP Clients
self.dhcpautoradio = setup_label( self.dhcpautoradio = setup_label(
@@ -434,8 +433,8 @@ class PreferencesDialog(object):
self.udhcpcradio = self.wTree.get_object("udhcpc_radio") self.udhcpcradio = self.wTree.get_object("udhcpc_radio")
# Wired Link Detection Apps # Wired Link Detection Apps
self.linkautoradio = setup_label( self.linkautoradio = setup_label("link_auto_radio",
"link_auto_radio", _('Automatic (recommended)')) _('Automatic (recommended)'))
self.linkautoradio = setup_label("link_auto_radio") self.linkautoradio = setup_label("link_auto_radio")
self.ethtoolradio = setup_label("ethtool_radio") self.ethtoolradio = setup_label("ethtool_radio")
self.miitoolradio = setup_label("miitool_radio") self.miitoolradio = setup_label("miitool_radio")
@@ -447,8 +446,8 @@ class PreferencesDialog(object):
self.routeflushradio = setup_label("route_flush_radio") self.routeflushradio = setup_label("route_flush_radio")
# Graphical Sudo Apps # Graphical Sudo Apps
self.sudoautoradio = setup_label( self.sudoautoradio = setup_label("sudo_auto_radio",
"sudo_auto_radio", _('Automatic (recommended)')) _('Automatic (recommended)'))
self.gksudoradio = setup_label("gksudo_radio") self.gksudoradio = setup_label("gksudo_radio")
self.kdesuradio = setup_label("kdesu_radio") self.kdesuradio = setup_label("kdesu_radio")
self.ktsussradio = setup_label("ktsuss_radio") self.ktsussradio = setup_label("ktsuss_radio")
@@ -489,5 +488,4 @@ class PreferencesDialog(object):
def be_combo_changed(self, combo): def be_combo_changed(self, combo):
"""Update the description label for the given backend.""" """Update the description label for the given backend."""
self.backendcombo.set_tooltip_text( self.backendcombo.set_tooltip_text(
self.be_descriptions[self.backends[combo.get_active()]] self.be_descriptions[self.backends[combo.get_active()]])
)

View File

@@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""wicd - wireless connection daemon frontend implementation """wicd - wireless connection daemon frontend implementation
This module implements a usermode frontend for wicd. It updates connection This module implements a usermode frontend for wicd. It updates connection
@@ -11,7 +10,8 @@ class TrayIcon() -- Parent class of TrayIconGUI and IconConnectionInfo.
and updates connection status. and updates connection status.
class TrayIconGUI() -- Child class of TrayIcon which implements the tray. class TrayIconGUI() -- Child class of TrayIcon which implements the tray.
icon itself. Parent class of StatusTrayIconGUI and EggTrayIconGUI. icon itself. Parent class of StatusTrayIconGUI and EggTrayIconGUI.
class IndicatorTrayIconGUI() -- Implements the tray icon using appindicator.Indicator. class IndicatorTrayIconGUI() -- Implements the tray icon using
appindicator.Indicator.
class StatusTrayIconGUI() -- Implements the tray icon using a class StatusTrayIconGUI() -- Implements the tray icon using a
gtk.StatusIcon. gtk.StatusIcon.
class EggTrayIconGUI() -- Implements the tray icon using egg.trayicon. class EggTrayIconGUI() -- Implements the tray icon using egg.trayicon.
@@ -37,31 +37,27 @@ class TrayIcon() -- Parent class of TrayIconGUI and IconConnectionInfo.
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
import sys import atexit
import gtk
from gi.repository import GLib as gobject
import getopt import getopt
import os import os
import pango import sys
import atexit
from dbus import DBusException from dbus import DBusException
import gtk
from gi.repository import GLib as gobject
import pango
import pygtk import pygtk
pygtk.require('2.0')
USE_APP_INDICATOR = True
try: try:
import appindicator import appindicator
except ImportError: except ImportError:
USE_APP_INDICATOR = False appindicator = None
HAS_NOTIFY = True
try: try:
import pynotify import pynotify
if not pynotify.init("Wicd"):
HAS_NOTIFY = False
except ImportError: except ImportError:
HAS_NOTIFY = False pynotify = None
# Wicd specific imports # Wicd specific imports
from wicd import wpath from wicd import wpath
@@ -72,6 +68,12 @@ from guiutil import error, can_use_notify
from wicd.translations import _ from wicd.translations import _
pygtk.require('2.0')
if pynotify and not pynotify.init("Wicd"):
pynotify = None
ICON_AVAIL = True ICON_AVAIL = True
USE_EGG = False USE_EGG = False
# Import egg.trayicon if we're using an older gtk version # Import egg.trayicon if we're using an older gtk version
@@ -80,8 +82,8 @@ if not hasattr(gtk, "StatusIcon"):
import egg.trayicon import egg.trayicon
USE_EGG = True USE_EGG = True
except ImportError: except ImportError:
print(('Unable to load tray icon: Missing both egg.trayicon and ' + \ print('Unable to load tray icon: Missing both egg.trayicon and '
'gtk.StatusIcon modules.')) 'gtk.StatusIcon modules.')
ICON_AVAIL = False ICON_AVAIL = False
misc.RenameProcess("wicd-client") misc.RenameProcess("wicd-client")
@@ -104,14 +106,11 @@ def catchdbus(func):
except DBusException as e: except DBusException as e:
if e.get_dbus_name() is not None and \ if e.get_dbus_name() is not None and \
"DBus.Error.AccessDenied" in e.get_dbus_name(): "DBus.Error.AccessDenied" in e.get_dbus_name():
error( error(None,
None,
_('Unable to contact the Wicd daemon due to an access ' _('Unable to contact the Wicd daemon due to an access '
'denied error from DBus. Please check that your user is ' 'denied error from DBus. Please check that your user '
'in the $A group.'). 'is in the $A group.').replace("$A", "<b>%s</b>" %
replace("$A", "<b>" + wpath.wicd_group + "</b>") wpath.wicd_group))
)
#raise
raise DBusException(e) raise DBusException(e)
else: else:
print(("warning: ignoring exception %s" % e)) print(("warning: ignoring exception %s" % e))
@@ -152,7 +151,7 @@ class TrayIcon(object):
self.max_snd_gain = 10000 self.max_snd_gain = 10000
self.max_rcv_gain = 10000 self.max_rcv_gain = 10000
if USE_APP_INDICATOR: if appindicator:
self.tr = self.IndicatorTrayIconGUI(self) self.tr = self.IndicatorTrayIconGUI(self)
elif USE_EGG: elif USE_EGG:
self.tr = self.EggTrayIconGUI(self) self.tr = self.EggTrayIconGUI(self)
@@ -333,8 +332,7 @@ class TrayIcon(object):
wired = True wired = True
else: else:
cur_network = info[1] cur_network = info[1]
status_string = _('Connecting') + " to " + \ status_string = _('Connecting') + " to " + cur_network + "..."
cur_network + "..."
self.update_tooltip() self.update_tooltip()
# self.tr.set_tooltip(status_string) # self.tr.set_tooltip(status_string)
self.tr.set_from_name('no-signal') self.tr.set_from_name('no-signal')
@@ -538,7 +536,7 @@ class TrayIcon(object):
self.current_icon_name = None self.current_icon_name = None
self._is_scanning = False self._is_scanning = False
net_menuitem = self.manager.get_widget("/Menubar/Menu/Connect/") net_menuitem = self.manager.get_widget("/Menubar/Menu/Connect/")
if not USE_APP_INDICATOR: if not appindicator:
net_menuitem.connect("activate", self.on_net_menu_activate) net_menuitem.connect("activate", self.on_net_menu_activate)
self.parent = parent self.parent = parent
@@ -625,7 +623,7 @@ class TrayIcon(object):
window.destroy() window.destroy()
self.cont = 'Stop' self.cont = 'Stop'
def update_conn_info_win(self, l): def update_conn_info_win(self, *args):
"""Updates the information in the connection summary window""" """Updates the information in the connection summary window"""
if (self.cont == "Stop"): if (self.cont == "Stop"):
return False return False
@@ -635,19 +633,12 @@ class TrayIcon(object):
# Choose info for the data # Choose info for the data
if state == misc.WIRED: if state == misc.WIRED:
text = (_('''$A text = (_("$A\n$B KB/s\n$C KB/s")
$B KB/s
$C KB/s''')
.replace('$A', str(info[0])) # IP .replace('$A', str(info[0])) # IP
.replace('$B', str(rx)) # RX .replace('$B', str(rx)) # RX
.replace('$C', str(tx))) # TX .replace('$C', str(tx))) # TX
elif state == misc.WIRELESS: elif state == misc.WIRELESS:
text = (_('''$A text = (_("$A\n$B\n$C\n$D\n$E KB/s\n$F KB/s")
$B
$C
$D
$E KB/s
$F KB/s''')
.replace('$A', str(info[1])) # SSID .replace('$A', str(info[1])) # SSID
.replace('$B', str(info[4])) # Speed .replace('$B', str(info[4])) # Speed
.replace('$C', str(info[0])) # IP .replace('$C', str(info[0])) # IP
@@ -661,18 +652,10 @@ $F KB/s''')
# Choose info for the labels # Choose info for the labels
self.list[0].set_text('\n' + text) self.list[0].set_text('\n' + text)
if state == misc.WIRED: if state == misc.WIRED:
self.list[1].set_text(_('''Wired self.list[1].set_text(_("Wired\nIP:\nRX:\nTX:"))
IP:
RX:
TX:'''))
elif state == misc.WIRELESS: elif state == misc.WIRELESS:
self.list[1].set_text(_('''Wireless self.list[1].set_text(_("Wireless\nSSID:\nSpeed:\nIP:\n"
SSID: "Strength:\nRX:\nTX:"))
Speed:
IP:
Strength:
RX:
TX:'''))
elif state == misc.CONNECTING: elif state == misc.CONNECTING:
self.list[1].set_text(_('Connecting')) self.list[1].set_text(_('Connecting'))
elif state in (misc.SUSPENDED, misc.NOT_CONNECTED): elif state in (misc.SUSPENDED, misc.NOT_CONNECTED):
@@ -812,8 +795,8 @@ TX:'''))
is_active = True is_active = True
else: else:
is_active = False is_active = False
self._add_item_to_menu(submenu, "Wired Network", "__wired__", 0, self._add_item_to_menu(submenu, "Wired Network", "__wired__",
is_connecting, is_active) 0, is_connecting, is_active)
sep = gtk.SeparatorMenuItem() sep = gtk.SeparatorMenuItem()
submenu.append(sep) submenu.append(sep)
sep.show() sep.show()
@@ -821,8 +804,8 @@ TX:'''))
if num_networks > 0: if num_networks > 0:
skip_never_connect = not daemon.GetShowNeverConnect() skip_never_connect = not daemon.GetShowNeverConnect()
for x in range(0, num_networks): for x in range(0, num_networks):
if skip_never_connect and \ if (skip_never_connect and
misc.to_bool(get_prop(x,"never")): misc.to_bool(get_prop(x, "never"))):
continue continue
essid = get_prop(x, "essid") essid = get_prop(x, "essid")
if status == misc.WIRELESS and info[1] == essid: if status == misc.WIRELESS and info[1] == essid:
@@ -968,7 +951,7 @@ TX:'''))
""" """
self.set_visible(val) self.set_visible(val)
if USE_APP_INDICATOR: if appindicator:
class IndicatorTrayIconGUI(gtk.StatusIcon, TrayIconGUI): class IndicatorTrayIconGUI(gtk.StatusIcon, TrayIconGUI):
"""Class for creating the wicd AppIndicator. """Class for creating the wicd AppIndicator.
This is required on recent versions of Unity (>=13.04). This is required on recent versions of Unity (>=13.04).
@@ -978,8 +961,10 @@ TX:'''))
""" """
def __init__(self, parent): def __init__(self, parent):
TrayIcon.TrayIconGUI.__init__(self, parent) TrayIcon.TrayIconGUI.__init__(self, parent)
self.ind = appindicator.Indicator( self.ind = appindicator.Indicator("wicd", "wicd-gtk",
"wicd", "wicd-gtk", appindicator.CATEGORY_SYSTEM_SERVICES, wpath.images) appindicator.
CATEGORY_SYSTEM_SERVICES,
wpath.images)
self.current_icon_name = '' self.current_icon_name = ''
# Rescaning when hovering over the net_menu doesn't work. # Rescaning when hovering over the net_menu doesn't work.
@@ -1008,7 +993,9 @@ TX:'''))
self.ind.set_menu(self.menu) self.ind.set_menu(self.menu)
def on_rescan(self, *data): def on_rescan(self, *data):
""" Triggers a network rescan that updates the 'Connect' menu when the 'Rescan' menu item is selected. """ """Triggers a network rescan that updates the 'Connect' menu
when the 'Rescan' menu item is selected.
"""
self.init_network_menu() self.init_network_menu()
wireless.Scan(False) wireless.Scan(False)
@@ -1031,7 +1018,8 @@ TX:'''))
hides the tray icon. hides the tray icon.
""" """
self.ind.set_status(val and appindicator.STATUS_ACTIVE or appindicator.STATUS_PASSIVE) self.ind.set_status(val and appindicator.STATUS_ACTIVE or
appindicator.STATUS_PASSIVE)
def set_tooltip(self, str): def set_tooltip(self, str):
"""Set the tooltip for this tray icon. """Set the tooltip for this tray icon.
@@ -1046,7 +1034,7 @@ TX:'''))
def usage(): def usage():
"""Print usage information.""" """Print usage information."""
print((""" print("""
wicd %s wicd %s
wireless (and wired) connection daemon front-end. wireless (and wired) connection daemon front-end.
@@ -1056,7 +1044,7 @@ Arguments:
\t-h\t--help\t\tPrint this help information. \t-h\t--help\t\tPrint this help information.
\t-a\t--no-animate\tRun the tray without network traffic tray animations. \t-a\t--no-animate\tRun the tray without network traffic tray animations.
\t-o\t--only-notifications\tDon't display anything except notifications. \t-o\t--only-notifications\tDon't display anything except notifications.
""" % wpath.version)) """ % wpath.version)
def setup_dbus(force=True): def setup_dbus(force=True):
@@ -1067,16 +1055,14 @@ def setup_dbus(force=True):
dbusmanager.connect_to_dbus() dbusmanager.connect_to_dbus()
except DBusException: except DBusException:
if force: if force:
print(("Can't connect to the daemon, trying to start it " + \ print("Can't connect to the daemon, trying to start it "
"automatically...")) "automatically...")
misc.PromptToStartDaemon() misc.PromptToStartDaemon()
try: try:
dbusmanager.connect_to_dbus() dbusmanager.connect_to_dbus()
except DBusException: except DBusException:
error(None, error(None, _("Could not connect to wicd's D-Bus interface. "
_("Could not connect to wicd's D-Bus interface. Check " "Check the wicd log for error messages."))
"the wicd log for error messages.")
)
return False return False
else: else:
return False return False
@@ -1108,13 +1094,10 @@ def handle_no_dbus():
DBUS_AVAIL = False DBUS_AVAIL = False
gui.handle_no_dbus(from_tray=True) gui.handle_no_dbus(from_tray=True)
print("Wicd daemon is shutting down!") print("Wicd daemon is shutting down!")
lost_dbus_id = misc.timeout_add(5, err_msg = _('The wicd daemon has shut down. The UI will not function '
lambda: error(None, 'properly until it is restarted.')
_('The wicd daemon has shut down. The UI will not function ' lost_dbus_id = misc.timeout_add(5, lambda: error(None, err_msg,
'properly until it is restarted.'), block=False))
block=False
)
)
return False return False

View File

@@ -3,7 +3,6 @@
chdir() -- Change directory to the location of the current file. chdir() -- Change directory to the location of the current file.
""" """
import os import os
# The path containing the wpath.py file. # The path containing the wpath.py file.
@@ -90,6 +89,7 @@ no_install_cli = %NO_INSTALL_CLI%
no_install_gnome_shell_extensions = %NO_INSTALL_GNOME_SHELL_EXTENSIONS% no_install_gnome_shell_extensions = %NO_INSTALL_GNOME_SHELL_EXTENSIONS%
no_use_notifications = %NO_USE_NOTIFICATIONS% no_use_notifications = %NO_USE_NOTIFICATIONS%
def chdir(f): def chdir(f):
"""Change directory to the location of the specified file. """Change directory to the location of the specified file.

251
setup.py
View File

@@ -16,16 +16,15 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from glob import glob
import os
import re
import shutil
import subprocess
from distutils.core import setup, Command from distutils.core import setup, Command
from distutils.command.build import build as _build from distutils.command.build import build as _build
from distutils.command.install import install as _install from distutils.command.install import install as _install
import os
import re
import sys
import shutil
import subprocess
from glob import glob
# Be sure to keep this updated! # Be sure to keep this updated!
# VERSIONNUMBER # VERSIONNUMBER
@@ -46,8 +45,9 @@ os.chdir(os.path.abspath(os.path.split(__file__)[0]))
try: try:
if os.path.exists('.bzr') and os.system('bzr > /dev/null 2>&1') == 0: if os.path.exists('.bzr') and os.system('bzr > /dev/null 2>&1') == 0:
try: try:
os.system('bzr version-info --python > vcsinfo.py && 2to3-2.7 -w vcsinfo.py') os.system('bzr version-info --python > vcsinfo.py && 2to3-2.7 '
except: '-w vcsinfo.py')
except Exception:
pass pass
import vcsinfo import vcsinfo
REVISION_NUM = vcsinfo.version_info['revno'] REVISION_NUM = vcsinfo.version_info['revno']
@@ -55,6 +55,7 @@ except Exception as e:
print('failed to find revision number:') print('failed to find revision number:')
print(e) print(e)
class build(_build): class build(_build):
sub_commands = _build.sub_commands + [('compile_translations', None)] sub_commands = _build.sub_commands + [('compile_translations', None)]
@@ -67,6 +68,7 @@ class build(_build):
# raise Exception, 'Please run "./setup.py configure" first.' # raise Exception, 'Please run "./setup.py configure" first.'
_build.run(self) _build.run(self)
class configure(Command): class configure(Command):
description = "configure the paths that Wicd will be installed to" description = "configure the paths that Wicd will be installed to"
@@ -87,20 +89,30 @@ class configure(Command):
('curses=', None, 'set the curses UI directory'), ('curses=', None, 'set the curses UI directory'),
('gtk=', None, 'set the GTK UI directory'), ('gtk=', None, 'set the GTK UI directory'),
('cli=', None, 'set the CLI directory'), ('cli=', None, 'set the CLI directory'),
('gnome-shell-extensions=', None, 'set the Gnome Shell Extensions directory'), ('gnome-shell-extensions=', None, 'set the Gnome Shell Extensions '
'directory'),
('networks=', None, 'set the encryption configuration directory'), ('networks=', None, 'set the encryption configuration directory'),
('log=', None, 'set the log directory'), ('log=', None, 'set the log directory'),
('resume=', None, 'set the directory the resume from suspend script is stored in'), ('resume=', None, 'set the directory the resume from suspend script '
('suspend=', None, 'set the directory the suspend script is stored in'), 'is stored in'),
('pmutils=', None, 'set the directory the pm-utils hooks are stored in'), ('suspend=', None, 'set the directory the suspend script is stored '
'in'),
('pmutils=', None, 'set the directory the pm-utils hooks are stored '
'in'),
('dbus=', None, 'set the directory the dbus config file is stored in'), ('dbus=', None, 'set the directory the dbus config file is stored in'),
('dbus-service=', None, 'set the directory where the dbus services config files are stored in'), ('dbus-service=', None, 'set the directory where the dbus services '
('systemd=', None, 'set the directory where the systemd system services config files are stored in'), 'config files are stored in'),
('logrotate=', None, 'set the directory where the logrotate configuration files are stored in'), ('systemd=', None, 'set the directory where the systemd system '
'services config files are stored in'),
('logrotate=', None, 'set the directory where the logrotate '
'configuration files are stored in'),
('desktop=', None, 'set the directory the .desktop file is stored in'), ('desktop=', None, 'set the directory the .desktop file is stored in'),
('icons=', None, "set the base directory for the .desktop file's icons"), ('icons=', None, "set the base directory for the .desktop file's "
('translations=', None, 'set the directory translations are stored in'), "icons"),
('autostart=', None, 'set the directory that will be autostarted on desktop login'), ('translations=', None, 'set the directory translations are stored '
'in'),
('autostart=', None, 'set the directory that will be autostarted on '
'desktop login'),
('varlib=', None, 'set the path for wicd\'s variable state data'), ('varlib=', None, 'set the path for wicd\'s variable state data'),
('init=', None, 'set the directory for the init file'), ('init=', None, 'set the directory for the init file'),
('docdir=', None, 'set the directory for the documentation'), ('docdir=', None, 'set the directory for the documentation'),
@@ -116,7 +128,8 @@ class configure(Command):
('initfile=', None, 'set the init file to use'), ('initfile=', None, 'set the init file to use'),
('initfilename=', None, "set the name of the init file (don't use)"), ('initfilename=', None, "set the name of the init file (don't use)"),
('wicdgroup=', None, "set the name of the group used for wicd"), ('wicdgroup=', None, "set the name of the group used for wicd"),
('distro=', None, 'set the distribution for which wicd will be installed'), ('distro=', None, 'set the distribution for which wicd will be '
'installed'),
('loggroup=', None, 'the group the log file belongs to'), ('loggroup=', None, 'the group the log file belongs to'),
('logperms=', None, 'the log file permissions'), ('logperms=', None, 'the log file permissions'),
@@ -124,17 +137,21 @@ class configure(Command):
('no-install-init', None, "do not install the init file"), ('no-install-init', None, "do not install the init file"),
('no-install-man', None, 'do not install the man files'), ('no-install-man', None, 'do not install the man files'),
('no-install-i18n', None, 'do not install translation files'), ('no-install-i18n', None, 'do not install translation files'),
('no-install-i18n-man', None, 'do not install the translated man files'), ('no-install-i18n-man', None, 'do not install the translated man '
'files'),
('no-install-kde', None, 'do not install the kde autostart file'), ('no-install-kde', None, 'do not install the kde autostart file'),
('no-install-acpi', None, 'do not install the suspend.d and resume.d acpi scripts'), ('no-install-acpi', None, 'do not install the suspend.d and resume.d '
'acpi scripts'),
('no-install-pmutils', None, 'do not install the pm-utils hooks'), ('no-install-pmutils', None, 'do not install the pm-utils hooks'),
('no-install-docs', None, 'do not install the auxiliary documentation'), ('no-install-docs', None, 'do not install the auxiliary '
'documentation'),
('no-install-ncurses', None, 'do not install the ncurses client'), ('no-install-ncurses', None, 'do not install the ncurses client'),
('no-install-cli', None, 'do not install the command line executable'), ('no-install-cli', None, 'do not install the command line executable'),
('no-install-gtk', None, 'do not install the gtk client'), ('no-install-gtk', None, 'do not install the gtk client'),
('no-install-gnome-shell-extensions', None, 'do not install the Gnome Shell extension'), ('no-install-gnome-shell-extensions', None, 'do not install the Gnome '
('no-use-notifications', None, 'do not ever allow the use of libnotify notifications') 'Shell extension'),
] ('no-use-notifications', None, 'do not ever allow the use of '
'libnotify notifications')]
def initialize_options(self): def initialize_options(self):
self.lib = '/usr/lib/wicd/' self.lib = '/usr/lib/wicd/'
@@ -202,9 +219,9 @@ class configure(Command):
self.ddistro = 'debian' self.ddistro = 'debian'
elif os.path.exists('/etc/arch-release'): elif os.path.exists('/etc/arch-release'):
self.ddistro = 'arch' self.ddistro = 'arch'
elif os.path.exists('/etc/slackware-version') or \ elif (os.path.exists('/etc/slackware-version') or
os.path.exists('/etc/slamd64-version') or \ os.path.exists('/etc/slamd64-version') or
os.path.exists('/etc/bluewhite64-version'): os.path.exists('/etc/bluewhite64-version')):
self.ddistro = 'slackware' self.ddistro = 'slackware'
elif os.path.exists('/etc/pld-release'): elif os.path.exists('/etc/pld-release'):
self.ddistro = 'pld' self.ddistro = 'pld'
@@ -216,10 +233,11 @@ class configure(Command):
self.ddistro = 'FAIL' self.ddistro = 'FAIL'
# self.no_install_init = True # self.no_install_init = True
# self.distro_detect_failed = True # self.distro_detect_failed = True
print('WARNING: Unable to detect the distribution in use. ' + \ print('WARNING: Unable to detect the distribution in use.\n'
'If you have specified --distro or --init and --initfile, configure will continue. ' + \ 'If you have specified --distro or --init and --initfile, '
'Please report this warning, along with the name of your ' + \ 'configure will continue.\nPlease report this warning, '
'distribution, to the wicd developers.') 'along with the name of your distribution, to the wicd '
'developers.')
# Try to get the pm-utils sleep hooks directory from pkg-config and # Try to get the pm-utils sleep hooks directory from pkg-config and
# the kde prefix from kde-config # the kde prefix from kde-config
@@ -228,10 +246,12 @@ class configure(Command):
# If we don't get anything from *-config, or it didn't run properly, # If we don't get anything from *-config, or it didn't run properly,
# or the path is not a proper absolute path, raise an error # or the path is not a proper absolute path, raise an error
try: try:
pmtemp = subprocess.Popen(["pkg-config", "--variable=pm_sleephooks", pmtemp = subprocess.Popen(["pkg-config",
"--variable=pm_sleephooks",
"pm-utils"], stdout=subprocess.PIPE) "pm-utils"], stdout=subprocess.PIPE)
returncode = pmtemp.wait() # let it finish, and get the exit code returncode = pmtemp.wait() # let it finish, and get the exit code
pmutils_candidate = str(pmtemp.stdout.readline().strip()) # read stdout # read stdout
pmutils_candidate = str(pmtemp.stdout.readline().strip())
if len(pmutils_candidate) == 0 or returncode != 0 or \ if len(pmutils_candidate) == 0 or returncode != 0 or \
not os.path.isabs(pmutils_candidate): not os.path.isabs(pmutils_candidate):
raise ValueError raise ValueError
@@ -241,20 +261,27 @@ class configure(Command):
pass # use our default pass # use our default
try: try:
kdetemp = subprocess.Popen(["kde-config","--prefix"], stdout=subprocess.PIPE) kdetemp = subprocess.Popen(["kde-config", "--prefix"],
returncode = kdetemp.wait() # let it finish, and get the exit code stdout=subprocess.PIPE)
kdedir_candidate = str(kdetemp.stdout.readline().strip()) # read stdout # let it finish, and get the exit code
if len(kdedir_candidate) == 0 or returncode != 0 or \ returncode = kdetemp.wait()
not os.path.isabs(kdedir_candidate): # read stdout
kdedir_candidate = str(kdetemp.stdout.readline().strip())
if (len(kdedir_candidate) == 0 or
returncode != 0 or
not os.path.isabs(kdedir_candidate)):
raise ValueError raise ValueError
else: else:
self.kdedir = kdedir_candidate + '/share/autostart' self.kdedir = kdedir_candidate + '/share/autostart'
except (OSError, ValueError, FileNotFoundError): except (OSError, ValueError, FileNotFoundError):
# If kde-config isn't present, we'll check for kde-4.x # If kde-config isn't present, we'll check for kde-4.x
try: try:
kde4temp = subprocess.Popen(["kde4-config","--prefix"], stdout=subprocess.PIPE) kde4temp = subprocess.Popen(["kde4-config", "--prefix"],
returncode = kde4temp.wait() # let it finish, and get the exit code stdout=subprocess.PIPE)
kde4dir_candidate = str(kde4temp.stdout.readline().strip()) # read stdout # let it finish, and get the exit code
returncode = kde4temp.wait()
# read stdout
kde4dir_candidate = str(kde4temp.stdout.readline().strip())
if len(kde4dir_candidate) == 0 or returncode != 0 or \ if len(kde4dir_candidate) == 0 or returncode != 0 or \
not os.path.isabs(kde4dir_candidate): not os.path.isabs(kde4dir_candidate):
raise ValueError raise ValueError
@@ -313,7 +340,8 @@ class configure(Command):
self.initfile = 'init/lunar/wicd' self.initfile = 'init/lunar/wicd'
else: else:
if self.distro == 'auto': if self.distro == 'auto':
print("NOTICE: Automatic distro detection found: " + self.ddistro + ", retrying with that...") print("NOTICE: Automatic distro detection found: %s, retrying "
"with that..." % self.ddistro)
self.distro = self.ddistro self.distro = self.ddistro
self.distro_check() self.distro_check()
else: else:
@@ -321,13 +349,13 @@ class configure(Command):
self.no_install_init = True self.no_install_init = True
self.distro_detect_failed = True self.distro_detect_failed = True
def finalize_options(self): def finalize_options(self):
self.distro_check() self.distro_check()
if self.distro_detect_failed and not self.no_install_init and \ if self.distro_detect_failed and not self.no_install_init and \
'FAIL' in [self.init, self.initfile]: 'FAIL' in [self.init, self.initfile]:
print('ERROR: Failed to detect distro. Configure cannot continue. ' + \ print('ERROR: Failed to detect distro. Configure cannot '
'Please specify --init and --initfile to continue with configuration.') 'continue.\nPlease specify --init and --initfile to '
'continue with configuration.')
# loop through the argument definitions in user_options # loop through the argument definitions in user_options
for argument in self.user_options: for argument in self.user_options:
@@ -354,7 +382,8 @@ class configure(Command):
cur_arg = argument[0][:-1] cur_arg = argument[0][:-1]
cur_arg_value = getattr(self, cur_arg.replace('-', '_')) cur_arg_value = getattr(self, cur_arg.replace('-', '_'))
print("%s is %s" % (cur_arg, cur_arg_value)) print("%s is %s" % (cur_arg, cur_arg_value))
values.append((cur_arg, getattr(self, cur_arg.replace('-','_')))) values.append((cur_arg, getattr(self, cur_arg.replace('-',
'_'))))
else: else:
cur_arg = argument[0] cur_arg = argument[0]
cur_arg_value = getattr(self, cur_arg.replace('-', '_')) cur_arg_value = getattr(self, cur_arg.replace('-', '_'))
@@ -376,8 +405,9 @@ class configure(Command):
item_out = open(final_name, 'w') item_out = open(final_name, 'w')
for line in item_in.readlines(): for line in item_in.readlines():
for item, value in values: for item, value in values:
line = line.replace('%' + str(item.upper().replace('-','_')) + \ line = line.replace('%' + str(item.upper())
'%', str(value)) .replace('-', '_') + '%',
str(value))
# other things to replace that aren't arguments # other things to replace that aren't arguments
line = line.replace('%VERSION%', str(VERSION_NUM)) line = line.replace('%VERSION%', str(VERSION_NUM))
@@ -420,6 +450,7 @@ class clear_generated(Command):
shutil.rmtree('translations/') shutil.rmtree('translations/')
os.makedirs('translations/') os.makedirs('translations/')
class install(_install): class install(_install):
def run(self): def run(self):
try: try:
@@ -428,7 +459,7 @@ class install(_install):
self.run_command('build') self.run_command('build')
import wpath import wpath
print("Using init file",(wpath.init, wpath.initfile)) print("Using init file", wpath.init, wpath.initfile)
data.extend([ data.extend([
(wpath.dbus, ['other/wicd.conf']), (wpath.dbus, ['other/wicd.conf']),
(wpath.dbus_service, ['other/org.wicd.daemon.service']), (wpath.dbus_service, ['other/org.wicd.daemon.service']),
@@ -437,12 +468,14 @@ class install(_install):
(wpath.log, [empty_file]), (wpath.log, [empty_file]),
(wpath.etc, ['other/dhclient.conf.template.default']), (wpath.etc, ['other/dhclient.conf.template.default']),
(wpath.encryption, [('encryption/templates/' + b) for b in (wpath.encryption, [('encryption/templates/' + b) for b in
os.listdir('encryption/templates') if not b.startswith('.')]), os.listdir('encryption/templates')
if not b.startswith('.')]),
(wpath.networks, [empty_file]), (wpath.networks, [empty_file]),
(wpath.sbin, ['scripts/wicd']), (wpath.sbin, ['scripts/wicd']),
(wpath.daemon, ['wicd/monitor.py', 'wicd/wicd-daemon.py', (wpath.daemon, ['wicd/monitor.py', 'wicd/wicd-daemon.py',
'wicd/suspend.py', 'wicd/autoconnect.py']), 'wicd/suspend.py', 'wicd/autoconnect.py']),
(wpath.backends, ['wicd/backends/be-external.py', 'wicd/backends/be-ioctl.py']), (wpath.backends, ['wicd/backends/be-external.py',
'wicd/backends/be-ioctl.py']),
(wpath.scripts, [empty_file]), (wpath.scripts, [empty_file]),
(wpath.predisconnectscripts, [empty_file]), (wpath.predisconnectscripts, [empty_file]),
(wpath.postdisconnectscripts, [empty_file]), (wpath.postdisconnectscripts, [empty_file]),
@@ -469,17 +502,18 @@ class install(_install):
for size in os.listdir('icons'): for size in os.listdir('icons'):
for category in os.listdir(os.path.join('icons', size)): for category in os.listdir(os.path.join('icons', size)):
imgdir = os.path.join('icons', size, category) imgdir = os.path.join('icons', size, category)
data.append( data.append((os.path.join(wpath.icons, size, category),
(os.path.join(wpath.icons, size, category), [(os.path.join(imgdir, f))
[(os.path.join(imgdir, f)) for f in os.listdir(imgdir) if not f.startswith('.')]) for f in os.listdir(imgdir)
) if not f.startswith('.')]))
for size in os.listdir('images'): for size in os.listdir('images'):
for category in os.listdir(os.path.join('images', size)): for category in os.listdir(os.path.join('images', size)):
imgdir = os.path.join('images', size, category) imgdir = os.path.join('images', size, category)
data.append( data.append((os.path.join(wpath.images, 'hicolor', size,
(os.path.join(wpath.images, 'hicolor', size, category), category),
[(os.path.join(imgdir, f)) for f in os.listdir(imgdir) if not f.startswith('.')]) [(os.path.join(imgdir, f))
) for f in os.listdir(imgdir)
if not f.startswith('.')]))
data.append((wpath.pixmaps, ['other/wicd-gtk.xpm'])) data.append((wpath.pixmaps, ['other/wicd-gtk.xpm']))
if not wpath.no_install_gnome_shell_extensions: if not wpath.no_install_gnome_shell_extensions:
data.append( data.append(
@@ -496,7 +530,8 @@ class install(_install):
if not wpath.no_install_man: if not wpath.no_install_man:
data.append((wpath.mandir + 'man8/', ['man/wicd-curses.8'])) data.append((wpath.mandir + 'man8/', ['man/wicd-curses.8']))
if not wpath.no_install_man and not wpath.no_install_i18n_man: if not wpath.no_install_man and not wpath.no_install_i18n_man:
data.append(( wpath.mandir + 'nl/man8/', ['man/nl/wicd-curses.8'])) data.append((wpath.mandir + 'nl/man8/',
['man/nl/wicd-curses.8']))
if not wpath.no_install_docs: if not wpath.no_install_docs:
data.append((wpath.docdir, ['curses/README.curses'])) data.append((wpath.docdir, ['curses/README.curses']))
if not wpath.no_install_cli: if not wpath.no_install_cli:
@@ -520,17 +555,24 @@ class install(_install):
data.append((wpath.init, [wpath.initfile])) data.append((wpath.init, [wpath.initfile]))
if not wpath.no_install_man: if not wpath.no_install_man:
data.append((wpath.mandir + 'man8/', ['man/wicd.8'])) data.append((wpath.mandir + 'man8/', ['man/wicd.8']))
data.append((wpath.mandir + 'man5/', ['man/wicd-manager-settings.conf.5'])) data.append((wpath.mandir + 'man5/',
data.append((wpath.mandir + 'man5/', ['man/wicd-wired-settings.conf.5'])) ['man/wicd-manager-settings.conf.5']))
data.append((wpath.mandir + 'man5/', ['man/wicd-wireless-settings.conf.5'])) data.append((wpath.mandir + 'man5/',
['man/wicd-wired-settings.conf.5']))
data.append((wpath.mandir + 'man5/',
['man/wicd-wireless-settings.conf.5']))
data.append((wpath.mandir + 'man1/', ['man/wicd-client.1'])) data.append((wpath.mandir + 'man1/', ['man/wicd-client.1']))
if not wpath.no_install_man and not wpath.no_install_i18n_man: if not wpath.no_install_man and not wpath.no_install_i18n_man:
# Dutch translations of the man # Dutch translations of the man
data.append((wpath.mandir + 'nl/man8/', ['man/nl/wicd.8'])) data.append((wpath.mandir + 'nl/man8/', ['man/nl/wicd.8']))
data.append((wpath.mandir + 'nl/man5/', ['man/nl/wicd-manager-settings.conf.5'])) data.append((wpath.mandir + 'nl/man5/',
data.append((wpath.mandir + 'nl/man5/', ['man/nl/wicd-wired-settings.conf.5'])) ['man/nl/wicd-manager-settings.conf.5']))
data.append((wpath.mandir + 'nl/man5/', ['man/nl/wicd-wireless-settings.conf.5'])) data.append((wpath.mandir + 'nl/man5/',
data.append((wpath.mandir + 'nl/man1/', ['man/nl/wicd-client.1'])) ['man/nl/wicd-wired-settings.conf.5']))
data.append((wpath.mandir + 'nl/man5/',
['man/nl/wicd-wireless-settings.conf.5']))
data.append((wpath.mandir + 'nl/man1/',
['man/nl/wicd-client.1']))
if not wpath.no_install_acpi: if not wpath.no_install_acpi:
data.append((wpath.resume, ['other/80-wicd-connect.sh'])) data.append((wpath.resume, ['other/80-wicd-connect.sh']))
data.append((wpath.suspend, ['other/50-wicd-suspend.sh'])) data.append((wpath.suspend, ['other/50-wicd-suspend.sh']))
@@ -543,11 +585,13 @@ class install(_install):
language = language.replace('translations/', '') language = language.replace('translations/', '')
print(language, end=' ') print(language, end=' ')
data.append((wpath.translations + language + '/LC_MESSAGES/', data.append((wpath.translations + language + '/LC_MESSAGES/',
['translations/' + language + '/LC_MESSAGES/wicd.mo'])) ['translations/' + language +
'/LC_MESSAGES/wicd.mo']))
print() print()
_install.run(self) _install.run(self)
class test(Command): class test(Command):
description = "run Wicd's unit tests" description = "run Wicd's unit tests"
@@ -565,6 +609,7 @@ class test(Command):
print('running tests') print('running tests')
tests.run_tests() tests.run_tests()
class update_message_catalog(Command): class update_message_catalog(Command):
description = "update wicd.pot with new strings" description = "update wicd.pot with new strings"
@@ -580,6 +625,7 @@ class update_message_catalog(Command):
os.system('pybabel extract . -o po/wicd.pot --sort-output') os.system('pybabel extract . -o po/wicd.pot --sort-output')
os.system('xgettext -L glade data/wicd.ui -j -o po/wicd.pot') os.system('xgettext -L glade data/wicd.ui -j -o po/wicd.pot')
class update_translations(Command): class update_translations(Command):
description = "update po-files with new strings from wicd.pot" description = "update po-files with new strings from wicd.pot"
@@ -594,7 +640,9 @@ class update_translations(Command):
def run(self): def run(self):
for pofile in glob('po/*.po'): for pofile in glob('po/*.po'):
lang = pofile.replace('po/', '').replace('.po', '') lang = pofile.replace('po/', '').replace('.po', '')
os.system('pybabel update -N -o %s -i po/wicd.pot -D wicd -l %s' % (pofile, lang)) os.system('pybabel update -N -o %s -i po/wicd.pot -D wicd -l %s' %
(pofile, lang))
class compile_translations(Command): class compile_translations(Command):
description = 'compile po-files to binary mo' description = 'compile po-files to binary mo'
@@ -628,36 +676,44 @@ class compile_translations(Command):
lang = pofile.replace('po/', '').replace('.po', '') lang = pofile.replace('po/', '').replace('.po', '')
compile_po = False compile_po = False
try: try:
msgfmt = subprocess.Popen(['msgfmt', '--statistics', pofile, msgfmt = subprocess.Popen(['msgfmt', '--statistics',
'-o', '/dev/null'], stderr=subprocess.PIPE) pofile, '-o', '/dev/null'],
returncode = msgfmt.wait() # let it finish, and get the exit code stderr=subprocess.PIPE)
# let it finish, and get the exit code
returncode = msgfmt.wait()
output = msgfmt.stderr.readline().strip().decode('utf-8') output = msgfmt.stderr.readline().strip().decode('utf-8')
if len(output) == 0 or returncode != 0: if len(output) == 0 or returncode != 0:
print(len(output), returncode) print(len(output), returncode)
raise ValueError raise ValueError
else: else:
m = re.match('(\d+) translated messages(?:, (\d+) fuzzy translation)?(?:, (\d+) untranslated messages)?.', output) m = re.match(r'(\d+) translated messages(?:, (\d+) '
r'fuzzy translation)?(?:, (\d+) '
r'untranslated messages)?.', output)
if m: if m:
done, fuzzy, missing = m.groups() done, fuzzy, missing = m.groups()
fuzzy = int(fuzzy) if fuzzy else 0 fuzzy = int(fuzzy) if fuzzy else 0
missing = int(missing) if missing else 0 missing = int(missing) if missing else 0
completeness = float(done)/(int(done) + missing + fuzzy) completeness = float(done)/(int(done) + missing +
fuzzy)
if completeness >= self.threshold: if completeness >= self.threshold:
compile_po = True compile_po = True
else: else:
print('Disabled %s (%s%% < %s%%).' % \ print('Disabled %s (%s%% < %s%%).' %
(lang, completeness*100, self.threshold*100)) (lang, completeness*100,
self.threshold*100))
continue continue
except (OSError, ValueError): except (OSError, ValueError):
print('ARGH') print('ARGH')
if compile_po: if compile_po:
os.makedirs('translations/' + lang + '/LC_MESSAGES/') os.makedirs('translations/' + lang + '/LC_MESSAGES/')
os.system('pybabel compile -D wicd -i %s -l %s -d translations/' % (pofile, lang)) os.system('pybabel compile -D wicd -i %s -l %s -d '
'translations/' % (pofile, lang))
os.environ['LANG'] = oldlang os.environ['LANG'] = oldlang
class uninstall(Command): class uninstall(Command):
description = "remove Wicd using uninstall.sh and install.log" description = "remove Wicd using uninstall.sh and install.log"
@@ -672,14 +728,12 @@ class uninstall(Command):
def run(self): def run(self):
os.system("./uninstall.sh") os.system("./uninstall.sh")
py_modules = ['wicd.networking','wicd.misc','wicd.wnettools',
'wicd.wpath','wicd.dbusmanager',
'wicd.logfile','wicd.backend','wicd.configmanager',
'wicd.translations']
setup( py_modules = ['wicd.networking', 'wicd.misc', 'wicd.wnettools', 'wicd.wpath',
cmdclass = { 'wicd.dbusmanager', 'wicd.logfile', 'wicd.backend',
'build' : build, 'wicd.configmanager', 'wicd.translations']
setup(cmdclass={'build': build,
'configure': configure, 'configure': configure,
'install': install, 'install': install,
'uninstall': uninstall, 'uninstall': uninstall,
@@ -687,23 +741,22 @@ setup(
'clear_generated': clear_generated, 'clear_generated': clear_generated,
'update_message_catalog': update_message_catalog, 'update_message_catalog': update_message_catalog,
'update_translations': update_translations, 'update_translations': update_translations,
'compile_translations' : compile_translations, 'compile_translations': compile_translations},
},
name="wicd", name="wicd",
version=VERSION_NUM, version=VERSION_NUM,
description="A wireless and wired network manager", description="A wireless and wired network manager",
long_description = """A complete network connection manager long_description="A complete network connection manager Wicd supports "
Wicd supports wired and wireless networks, and capable of "wired and wireless networks, and capable of creating and tracking "
creating and tracking profiles for both. It has a "profiles for both. It has a template-based wireless encryption system, "
template-based wireless encryption system, which allows the user "which allows the user to easily add encryption methods used. It ships "
to easily add encryption methods used. It ships with some common "with some common encryption types, such as WPA and WEP. Wicd will "
encryption types, such as WPA and WEP. Wicd will automatically "automatically connect at startup to any preferred network within "
connect at startup to any preferred network within range. "range.",
""", author="Tom Van Braeckel, Adam Blackburn, Dan O'Reilly, Andrew Psaltis, "
author = "Tom Van Braeckel, Adam Blackburn, Dan O'Reilly, Andrew Psaltis, David Paleino", "David Paleino",
author_email = "tomvanbraeckel@gmail.com, compwiz18@gmail.com, oreilldf@gmail.com, ampsaltis@gmail.com, d.paleino@gmail.com", author_email="tomvanbraeckel@gmail.com, compwiz18@gmail.com, "
"oreilldf@gmail.com, ampsaltis@gmail.com, d.paleino@gmail.com",
url="https://launchpad.net/wicd", url="https://launchpad.net/wicd",
license="http://www.gnu.org/licenses/old-licenses/gpl-2.0.html", license="http://www.gnu.org/licenses/old-licenses/gpl-2.0.html",
py_modules=py_modules, py_modules=py_modules,
data_files = data, data_files=data)
)

View File

@@ -4,6 +4,7 @@
import unittest import unittest
from wicd import misc from wicd import misc
class TestMisc(unittest.TestCase): class TestMisc(unittest.TestCase):
def test_misc_run(self): def test_misc_run(self):
output = misc.Run(['echo', 'hi']).strip() output = misc.Run(['echo', 'hi']).strip()
@@ -25,10 +26,12 @@ class TestMisc(unittest.TestCase):
self.assertTrue(misc.IsValidIP('::1')) self.assertTrue(misc.IsValidIP('::1'))
def test_valid_ip_6(self): def test_valid_ip_6(self):
self.assertTrue(misc.IsValidIP('FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF')) self.assertTrue(misc.
IsValidIP('FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF'))
def test_valid_ip_7(self): def test_valid_ip_7(self):
self.assertTrue(misc.IsValidIP('2001:0db8:85a3:0000:0000:8a2e:0370:7334')) self.assertTrue(misc.
IsValidIP('2001:0db8:85a3:0000:0000:8a2e:0370:7334'))
def test_invalid_ip_1(self): def test_invalid_ip_1(self):
self.assertFalse(misc.IsValidIP('-10.0.-1.-1')) self.assertFalse(misc.IsValidIP('-10.0.-1.-1'))
@@ -46,10 +49,12 @@ class TestMisc(unittest.TestCase):
self.assertFalse(misc.IsValidIP('1:')) self.assertFalse(misc.IsValidIP('1:'))
def test_invalid_ip_6(self): def test_invalid_ip_6(self):
self.assertFalse(misc.IsValidIP('ZZZZ:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF')) self.assertFalse(misc.
IsValidIP('ZZZZ:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF'))
def test_invalid_ip_7(self): def test_invalid_ip_7(self):
self.assertFalse(misc.IsValidIP('2001:0db8:85Z3:0000:0000:8a2e:0370:7334')) self.assertFalse(misc.
IsValidIP('2001:0db8:85Z3:0000:0000:8a2e:0370:7334'))
def test_run_valid_regex(self): def test_run_valid_regex(self):
import re import re
@@ -72,7 +77,7 @@ class TestMisc(unittest.TestCase):
def test_to_boolean_true(self): def test_to_boolean_true(self):
self.assertTrue(misc.to_bool('True')) self.assertTrue(misc.to_bool('True'))
def test_to_boolean_true(self): def test_to_boolean_true_int(self):
self.assertTrue(misc.to_bool('1')) self.assertTrue(misc.to_bool('1'))
def test_noneify_1(self): def test_noneify_1(self):
@@ -137,7 +142,8 @@ class TestMisc(unittest.TestCase):
self.assertEqual(misc.to_unicode('abcdef'), 'abcdef') self.assertEqual(misc.to_unicode('abcdef'), 'abcdef')
def test_to_unicode_4(self): def test_to_unicode_4(self):
self.assertEqual(type(misc.to_unicode('abcdef'.encode('latin-1'))), bytes) self.assertEqual(type(misc.to_unicode('abcdef'.encode('latin-1'))),
bytes)
def test_to_unicode_5(self): def test_to_unicode_5(self):
self.assertEqual(misc.to_unicode("berkåk"), "berkåk") self.assertEqual(misc.to_unicode("berkåk"), "berkåk")
@@ -163,6 +169,7 @@ class TestMisc(unittest.TestCase):
def test_string_to_none_4(self): def test_string_to_none_4(self):
self.assertEqual(misc.stringToNone('abcdef'), 'abcdef') self.assertEqual(misc.stringToNone('abcdef'), 'abcdef')
def suite(): def suite():
suite = unittest.TestSuite() suite = unittest.TestSuite()
tests = [] tests = []
@@ -171,5 +178,6 @@ def suite():
suite.addTest(TestMisc(test)) suite.addTest(TestMisc(test))
return suite return suite
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()

View File

@@ -2,6 +2,7 @@ import unittest
from unittest import mock from unittest import mock
from wicd import wnettools from wicd import wnettools
class TestWnettools(unittest.TestCase): class TestWnettools(unittest.TestCase):
def setUp(self): def setUp(self):
self.interface = wnettools.BaseInterface('eth0') self.interface = wnettools.BaseInterface('eth0')
@@ -41,7 +42,8 @@ class TestWnettools(unittest.TestCase):
self.assertFalse(self.interface.verbose) self.assertFalse(self.interface.verbose)
def test_interface_name_sanitation(self): def test_interface_name_sanitation(self):
interface = wnettools.BaseInterface('blahblah; uptime > /tmp/blah | cat') interface = wnettools.BaseInterface('blahblah; uptime > /tmp/blah | '
'cat')
self.assertEqual(interface.iface, 'blahblahuptimetmpblahcat') self.assertEqual(interface.iface, 'blahblahuptimetmpblahcat')
def test_freq_translation_low(self): def test_freq_translation_low(self):
@@ -57,16 +59,21 @@ class TestWnettools(unittest.TestCase):
def test_generate_psk(self): def test_generate_psk(self):
interface = wnettools.BaseWirelessInterface('wlan0') interface = wnettools.BaseWirelessInterface('wlan0')
if 'wlan0' in wnettools.GetWirelessInterfaces(): if 'wlan0' in wnettools.GetWirelessInterfaces():
psk = interface.GeneratePSK({'essid' : 'Network 1', 'key' : 'arandompassphrase'}) psk = interface.GeneratePSK({'essid': 'Network 1',
self.assertEqual(psk, 'd70463014514f4b4ebb8e3aebbdec13f4437ac3a9af084b3433f3710e658a7be') 'key': 'arandompassphrase'})
self.assertEqual(psk, 'd70463014514f4b4ebb8e3aebbdec13f4437ac3a9a'
'f084b3433f3710e658a7be')
def suite(): def suite():
suite = unittest.TestSuite() suite = unittest.TestSuite()
tests = [] tests = []
[ tests.append(test) for test in dir(TestWnettools) if test.startswith('test') ] [tests.append(test) for test in dir(TestWnettools)
if test.startswith('test')]
for test in tests: for test in tests:
suite.addTest(TestWnettools(test)) suite.addTest(TestWnettools(test))
return suite return suite
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()

View File

@@ -18,19 +18,18 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
import sys
from wicd import dbusmanager import time
import dbus import dbus
import time
import sys
if getattr(dbus, 'version', (0, 0, 0)) < (0, 80, 0): if getattr(dbus, 'version', (0, 0, 0)) < (0, 80, 0):
import dbus.glib import dbus.glib
else: else:
from dbus.mainloop.glib import DBusGMainLoop from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True) DBusGMainLoop(set_as_default=True)
from wicd import dbusmanager
try: try:
dbusmanager.connect_to_dbus() dbusmanager.connect_to_dbus()
daemon = dbusmanager.get_interface('daemon') daemon = dbusmanager.get_interface('daemon')
@@ -40,14 +39,18 @@ except Exception as e:
print('Could not connect to daemon.', file=sys.stderr) print('Could not connect to daemon.', file=sys.stderr)
sys.exit(1) sys.exit(1)
def handler(*args): def handler(*args):
"""No-op handler.""" """No-op handler."""
pass pass
def error_handler(*args): def error_handler(*args):
"""Error handler.""" """Error handler."""
print('Async error autoconnecting.', file=sys.stderr) print('Async error autoconnecting.', file=sys.stderr)
sys.exit(3) sys.exit(3)
if __name__ == '__main__': if __name__ == '__main__':
try: try:
time.sleep(2) time.sleep(2)

View File

@@ -29,6 +29,7 @@ import os
import wicd.wpath as wpath import wicd.wpath as wpath
def fail(backend_name, reason): def fail(backend_name, reason):
"""Helper to warn the user about failure in loading backend.""" """Helper to warn the user about failure in loading backend."""
print(("Failed to load backend %s: %s" % (backend_name, reason))) print(("Failed to load backend %s: %s" % (backend_name, reason)))

View File

@@ -29,9 +29,15 @@ class WirelessInterface() -- Control a wireless network interface.
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from wicd.wnettools import GetDefaultGateway, GetWiredInterfaces, \ from wicd.wnettools import BaseInterface
GetWirelessInterfaces, IsValidWpaSuppDriver, BaseWirelessInterface, \ from wicd.wnettools import BaseWiredInterface
BaseWiredInterface, BaseInterface, GetWpaSupplicantDrivers from wicd.wnettools import BaseWirelessInterface
from wicd.wnettools import GetDefaultGateway
from wicd.wnettools import GetWiredInterfaces
from wicd.wnettools import GetWirelessInterfaces
from wicd.wnettools import GetWpaSupplicantDrivers
from wicd.wnettools import IsValidWpaSuppDriver
NAME = "external" NAME = "external"
UPDATE_INTERVAL = 5 UPDATE_INTERVAL = 5

View File

@@ -30,18 +30,33 @@ class WirelessInterface() -- Control a wireless network interface.
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
import array
import fcntl
import os
import socket
import struct
import time
from wicd import misc from wicd import misc
from wicd import wpath from wicd import wpath
from wicd.wnettools import GetDefaultGateway, GetWiredInterfaces, \ from wicd.wnettools import BaseInterface
GetWirelessInterfaces, IsValidWpaSuppDriver, BaseWirelessInterface, \ from wicd.wnettools import BaseWiredInterface
BaseWiredInterface, BaseInterface, GetWpaSupplicantDrivers, wep_pattern, \ from wicd.wnettools import BaseWirelessInterface
signaldbm_pattern, neediface from wicd.wnettools import GetDefaultGateway
from wicd.wnettools import GetWiredInterfaces
from wicd.wnettools import GetWirelessInterfaces
from wicd.wnettools import GetWpaSupplicantDrivers
from wicd.wnettools import IsValidWpaSuppDriver
from wicd.wnettools import neediface
from wicd.wnettools import signaldbm_pattern
from wicd.wnettools import wep_pattern
try: try:
import iwscan import iwscan
IWSCAN_AVAIL = True IWSCAN_AVAIL = True
except ImportError: except ImportError:
print("WARNING: python-iwscan not found, falling back to using iwlist scan.") print("WARNING: python-iwscan not found, falling back to using iwlist "
"scan.")
IWSCAN_AVAIL = False IWSCAN_AVAIL = False
try: try:
import wpactrl import wpactrl
@@ -50,14 +65,6 @@ except ImportError:
print("WARNING: python-wpactrl not found, falling back to using wpa_cli.") print("WARNING: python-wpactrl not found, falling back to using wpa_cli.")
WPACTRL_AVAIL = False WPACTRL_AVAIL = False
import re
import os
import time
import socket
import fcntl
import struct
import array
NAME = "ioctl" NAME = "ioctl"
UPDATE_INTERVAL = 4 UPDATE_INTERVAL = 4
@@ -112,6 +119,7 @@ def get_iw_ioctl_result(iface, call):
return None return None
return buff.tostring() return buff.tostring()
def NeedsExternalCalls(*args, **kargs): def NeedsExternalCalls(*args, **kargs):
"""Return False, since this backend doesn't use any external apps.""" """Return False, since this backend doesn't use any external apps."""
return False return False
@@ -201,7 +209,8 @@ class WiredInterface(Interface, BaseWiredInterface):
""" """
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]:
return self._mii_get_plugged_in() return self._mii_get_plugged_in()
else: else:
print(('Error: No way of checking for a wired connection. Make' + print(('Error: No way of checking for a wired connection. Make' +
@@ -262,8 +271,7 @@ class WirelessInterface(Interface, BaseWirelessInterface):
verbose -- print all commands verbose -- print all commands
""" """
BaseWirelessInterface.__init__(self, iface, verbose, BaseWirelessInterface.__init__(self, iface, verbose, wpa_driver)
wpa_driver)
Interface.__init__(self, iface, verbose) Interface.__init__(self, iface, verbose)
self.scan_iface = None self.scan_iface = None
self.CheckWirelessTools() self.CheckWirelessTools()
@@ -344,7 +352,8 @@ class WirelessInterface(Interface, BaseWirelessInterface):
# quality displayed or it isn't found) # quality displayed or it isn't found)
if misc.RunRegex(signaldbm_pattern, cell["stats"]): if misc.RunRegex(signaldbm_pattern, cell["stats"]):
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 # This is already set for ralink
elif self.wpa_driver != RALINK_DRIVER:
ap['strength'] = -1 ap['strength'] = -1
return ap return ap
@@ -360,8 +369,8 @@ class WirelessInterface(Interface, BaseWirelessInterface):
print(("Couldn't open ctrl_interface: %s" % e)) print(("Couldn't open ctrl_interface: %s" % e))
return None return None
else: else:
print(("Couldn't find a wpa_supplicant ctrl_interface for iface %s" \ print(f"Couldn't find a wpa_supplicant ctrl_interface for iface "
% self.iface)) f"{self.iface}")
return None return None
def ValidateAuthentication(self, auth_time): def ValidateAuthentication(self, auth_time):
@@ -384,7 +393,8 @@ class WirelessInterface(Interface, BaseWirelessInterface):
""" """
if not WPACTRL_AVAIL: if not WPACTRL_AVAIL:
# If we don't have python-wpactrl, use the slow version. # If we don't have python-wpactrl, use the slow version.
return BaseWirelessInterface.ValidateAuthentication(self, auth_time) return BaseWirelessInterface.ValidateAuthentication(self,
auth_time)
# 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:
@@ -401,16 +411,16 @@ class WirelessInterface(Interface, BaseWirelessInterface):
while (time.time() - auth_time) < MAX_TIME: while (time.time() - auth_time) < MAX_TIME:
try: try:
status = wpa.request("STATUS").split("\n") status = wpa.request("STATUS").split("\n")
except: except Exception:
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' \ print(f'wpa_supplicant ctrl_interface status query is '
% str(status))) f'{status}')
try: try:
[result] = [l for l in status if l.startswith("wpa_state=")] [result] = [s for s in status if s.startswith("wpa_state=")]
except ValueError: except ValueError:
return False return False
@@ -449,14 +459,16 @@ class WirelessInterface(Interface, BaseWirelessInterface):
network -- dictionary containing network info network -- dictionary containing network info
""" """
if network.get('key') != None: if network.get('key') is None:
return
lines = self._GetRalinkInfo() lines = self._GetRalinkInfo()
for x in lines: for x in lines:
info = x.split() info = x.split()
if len(info) < 5: if len(info) < 5:
break break
if info[2] == network.get('essid'): if info[2] == network.get('essid'):
if info[5] == 'WEP' or (info[5] == 'OPEN' and \ if info[5] == 'WEP' or (info[5] == 'OPEN' and
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 ',
@@ -478,8 +490,8 @@ class WirelessInterface(Interface, BaseWirelessInterface):
auth_mode = 'WPA2PSK' auth_mode = 'WPA2PSK'
key_name = 'WPAPSK' key_name = 'WPAPSK'
else: else:
print(('Unknown AuthMode, can\'t complete ' + \ print("Unknown AuthMode, can\'t complete connection "
'connection process!')) "process!")
return return
cmd_list = [] cmd_list = []

View File

@@ -25,14 +25,15 @@ reusable for other purposes as well.
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
import sys, os
from configparser import RawConfigParser, ParsingError
import codecs import codecs
import configparser
import os
import sys
from dbus import Int32
from wicd.misc import Noneify, to_unicode from wicd.misc import Noneify, to_unicode
from dbus import Int32
def sanitize_config_file(path): def sanitize_config_file(path):
"""Remove invalid lines from config file.""" """Remove invalid lines from config file."""
@@ -46,10 +47,11 @@ def sanitize_config_file(path):
conf.write(newconf) conf.write(newconf)
conf.close() conf.close()
class ConfigManager(RawConfigParser):
class ConfigManager(configparser.RawConfigParser):
"""A class that can be used to manage a given configuration file.""" """A class that can be used to manage a given configuration file."""
def __init__(self, path, debug=False, mark_whitespace="`'`"): def __init__(self, path, debug=False, mark_whitespace="`'`"):
RawConfigParser.__init__(self) configparser.RawConfigParser.__init__(self)
self.config_file = path self.config_file = path
self.debug = debug self.debug = debug
self.mrk_ws = mark_whitespace self.mrk_ws = mark_whitespace
@@ -57,11 +59,11 @@ class ConfigManager(RawConfigParser):
sanitize_config_file(path) sanitize_config_file(path)
try: try:
self.read(path) self.read(path)
except ParsingError: except configparser.ParsingError:
self.write() self.write()
try: try:
self.read(path) self.read(path)
except ParsingError as p: except configparser.ParsingError as p:
print(("Could not start wicd: %s" % p.message)) print(("Could not start wicd: %s" % p.message))
sys.exit(1) sys.exit(1)
@@ -91,7 +93,7 @@ class ConfigManager(RawConfigParser):
if value.startswith(' ') or value.endswith(' '): if value.startswith(' ') or value.endswith(' '):
value = "%(ws)s%(value)s%(ws)s" % {"value": value, value = "%(ws)s%(value)s%(ws)s" % {"value": value,
"ws": self.mrk_ws} "ws": self.mrk_ws}
RawConfigParser.set(self, section, str(option), value) configparser.RawConfigParser.set(self, section, str(option), value)
if write: if write:
self.write() self.write()
@@ -114,7 +116,7 @@ class ConfigManager(RawConfigParser):
return None return None
if self.has_option(section, option): if self.has_option(section, option):
ret = RawConfigParser.get(self, section, option) ret = configparser.RawConfigParser.get(self, section, option)
if (isinstance(ret, str) and ret.startswith(self.mrk_ws) if (isinstance(ret, str) and ret.startswith(self.mrk_ws)
and ret.endswith(self.mrk_ws)): and ret.endswith(self.mrk_ws)):
ret = ret[3:-3] ret = ret[3:-3]
@@ -122,18 +124,16 @@ class ConfigManager(RawConfigParser):
if default: if default:
if self.debug: if self.debug:
# mask out sensitive information # mask out sensitive information
if option in ['apsk', 'password', 'identity', \ if option in ['apsk', 'password', 'identity',
'private_key', 'private_key_passwd', \ 'private_key', 'private_key_passwd',
'key', 'passphrase']: 'key', 'passphrase']:
print((''.join(['found ', option, \ print(f'found {option} in configuration *****')
' in configuration *****'])))
else: else:
print((''.join(['found ', option, ' in configuration ', print(f'found {option} in configuration {ret}')
str(ret)])))
else: # Use the default, unless no default was provided else: # Use the default, unless no default was provided
if default != "__None__": if default != "__None__":
print(('did not find %s in configuration, setting default %s' \ print(f'did not find {option} in configuration, setting '
% (option, str(default)))) f'default {default}')
self.set(section, option, str(default), write=True) self.set(section, option, str(default), write=True)
ret = default ret = default
else: else:
@@ -163,7 +163,7 @@ class ConfigManager(RawConfigParser):
if not section: if not section:
self.remove_section(section) self.remove_section(section)
configfile = open(self.config_file, 'w') configfile = open(self.config_file, 'w')
RawConfigParser.write(self, configfile) configparser.RawConfigParser.write(self, configfile)
configfile.close() configfile.close()
def remove_section(self, section): def remove_section(self, section):
@@ -174,7 +174,7 @@ class ConfigManager(RawConfigParser):
""" """
if self.has_section(section): if self.has_section(section):
RawConfigParser.remove_section(self, section) configparser.RawConfigParser.remove_section(self, section)
def reload(self): def reload(self):
"""Re-reads the config file, in case it was edited out-of-band.""" """Re-reads the config file, in case it was edited out-of-band."""
@@ -187,7 +187,8 @@ class ConfigManager(RawConfigParser):
entries in these files override entries in the main file. entries in these files override entries in the main file.
""" """
if os.path.exists(path): if os.path.exists(path):
RawConfigParser.readfp(self, codecs.open(path, 'r', 'utf-8')) configparser.RawConfigParser.readfp(self, codecs.open(path, 'r',
'utf-8'))
path_d = path + ".d" path_d = path + ".d"
files = [] files = []
@@ -197,7 +198,7 @@ class ConfigManager(RawConfigParser):
files.sort() files.sort()
for fname in files: for fname in files:
p = RawConfigParser() p = configparser.RawConfigParser()
p.readfp(codecs.open(fname, 'r', 'utf-8')) p.readfp(codecs.open(fname, 'r', 'utf-8'))
for section_name in p.sections(): for section_name in p.sections():
# New files override old, so remove first to avoid # New files override old, so remove first to avoid
@@ -209,7 +210,6 @@ class ConfigManager(RawConfigParser):
# Store the filename this section was read from. # Store the filename this section was read from.
self.set(section_name, '_filename_', fname) self.set(section_name, '_filename_', fname)
def _copy_section(self, name): def _copy_section(self, name):
"""Copy whole section from config file.""" """Copy whole section from config file."""
p = ConfigManager("", self.debug, self.mrk_ws) p = ConfigManager("", self.debug, self.mrk_ws)
@@ -243,4 +243,3 @@ class ConfigManager(RawConfigParser):
p.set(sname, iname, value) p.set(sname, iname, value)
p.remove_option(sname, '_filename_') p.remove_option(sname, '_filename_')
p._write_one() p._write_one()

View File

@@ -1,5 +1,3 @@
#!/usr/bin/env python3
"""The wicd DBus Manager. """The wicd DBus Manager.
A module for managing wicd's dbus interfaces. A module for managing wicd's dbus interfaces.
@@ -32,26 +30,32 @@ else:
DBUS_MANAGER = None DBUS_MANAGER = None
def get_dbus_ifaces(): def get_dbus_ifaces():
"""Return available DBus interfaces.""" """Return available DBus interfaces."""
return DBUS_MANAGER.get_dbus_ifaces() return DBUS_MANAGER.get_dbus_ifaces()
def get_interface(iface): def get_interface(iface):
"""Return specified interface.""" """Return specified interface."""
return DBUS_MANAGER.get_interface(iface) return DBUS_MANAGER.get_interface(iface)
def get_bus(): def get_bus():
"""Return the loaded System Bus.""" """Return the loaded System Bus."""
return DBUS_MANAGER.get_bus() return DBUS_MANAGER.get_bus()
def set_mainloop(loop): def set_mainloop(loop):
"""Set DBus main loop.""" """Set DBus main loop."""
return DBUS_MANAGER.set_mainloop(loop) return DBUS_MANAGER.set_mainloop(loop)
def connect_to_dbus(): def connect_to_dbus():
"""Connect to DBus.""" """Connect to DBus."""
return DBUS_MANAGER.connect_to_dbus() return DBUS_MANAGER.connect_to_dbus()
def threads_init(): def threads_init():
"""Init GLib threads.""" """Init GLib threads."""
dbus.mainloop.glib.threads_init() dbus.mainloop.glib.threads_init()
@@ -99,4 +103,5 @@ class DBusManager(object):
self._dbus_ifaces = {"daemon": daemon, "wireless": wireless, self._dbus_ifaces = {"daemon": daemon, "wireless": wireless,
"wired": wired} "wired": wired}
DBUS_MANAGER = DBusManager() DBUS_MANAGER = DBusManager()

View File

@@ -1,5 +1,12 @@
#!/usr/bin/env python3 """
Managing logfile rotation. A ManagedLog object is a file-like object that
rotates itself when a maximum size is reached.
TODO(gryf): how about using standard logging module and let the log rotating
to system tools like logrotate?
"""
# #
# Copyright (C) 1999-2006 Keith Dart <keith@kdart.com> # Copyright (C) 1999-2006 Keith Dart <keith@kdart.com>
# Copyright (C) 2008-2009 Dan O'Reilly <oreilldf@gmail.com> # Copyright (C) 2008-2009 Dan O'Reilly <oreilldf@gmail.com>
@@ -14,22 +21,17 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details. # Lesser General Public License for more details.
"""
Managing logfile rotation. A ManagedLog object is a file-like object that
rotates itself when a maximum size is reached.
"""
import sys
import os
import time
import io import io
import os
import sys
import time
class SizeError(IOError): class SizeError(IOError):
"""Custom error class.""" """Custom error class."""
pass pass
class LogFile(io.FileIO): class LogFile(io.FileIO):
"""LogFile(name, [mode="w"], [maxsize=360000]) """LogFile(name, [mode="w"], [maxsize=360000])
@@ -49,19 +51,22 @@ class LogFile(io.FileIO):
def write(self, data): def write(self, data):
self.written += len(data) self.written += len(data)
# TODO(gryf): revisit need for encode/decode madness
data = data.encode('utf-8') data = data.encode('utf-8')
if len(data) <= 0: if len(data) <= 0:
return return
if self.eol: if self.eol:
super(LogFile, self).write(self.get_time().encode("utf-8") + b' :: ') super(LogFile, self).write(self.get_time().encode("utf-8") +
b' :: ')
self.eol = False self.eol = False
if data[-1] == '\n': if data[-1] == '\n':
self.eol = True self.eol = True
data = data[:-1] data = data[:-1]
super(LogFile, self).write(data.replace( super(LogFile, self).write(data.replace(b'\n', b'\n' + self.get_time()
b'\n', b'\n' + self.get_time().encode("utf-8") + b' :: ')) .encode("utf-8") + b' :: '))
if self.eol: if self.eol:
super(LogFile, self).write('\n') super(LogFile, self).write('\n')
@@ -190,6 +195,7 @@ def open(name, maxsize=360000, maxsave=9):
"""Open logfile.""" """Open logfile."""
return ManagedLog(name, maxsize, maxsave) return ManagedLog(name, maxsize, maxsave)
def writelog(logobj, data): def writelog(logobj, data):
"""Write logfile.""" """Write logfile."""
try: try:

View File

@@ -22,23 +22,24 @@ throughout wicd.
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
import os
import locale
import sys
import re
import string
from gi.repository import GLib as gobject
from threading import Thread
from subprocess import Popen, STDOUT, PIPE, call
from subprocess import getoutput
from itertools import repeat, chain from itertools import repeat, chain
import locale
import os
import re
from pipes import quote from pipes import quote
import socket import socket
import string
from subprocess import Popen, STDOUT, PIPE, call
from subprocess import getoutput
import sys
from threading import Thread
from gi.repository import GLib as gobject
from wicd.translations import _ from wicd.translations import _
# wicd imports # wicd imports
from . import wpath from wicd import wpath
# Connection state constants # Connection state constants
NOT_CONNECTED = 0 NOT_CONNECTED = 0
@@ -46,13 +47,11 @@ CONNECTING = 1
WIRELESS = 2 WIRELESS = 2
WIRED = 3 WIRED = 3
SUSPENDED = 4 SUSPENDED = 4
_const_status_dict = { _const_status_dict = {NOT_CONNECTED: _('Not connected'),
NOT_CONNECTED: _('Not connected'),
CONNECTING: _('Connection in progress'), CONNECTING: _('Connection in progress'),
WIRELESS: _('Connected to a wireless network'), WIRELESS: _('Connected to a wireless network'),
WIRED: _('Connected to a wired network'), WIRED: _('Connected to a wired network'),
SUSPENDED: _('Connection suspended'), SUSPENDED: _('Connection suspended')}
}
# Automatic app selection constant # Automatic app selection constant
AUTO = 0 AUTO = 0
@@ -75,16 +74,14 @@ ROUTE = 2
GKSUDO = 1 GKSUDO = 1
KDESU = 2 KDESU = 2
KTSUSS = 3 KTSUSS = 3
_sudo_dict = { _sudo_dict = {AUTO: "",
AUTO : "",
GKSUDO: "gksudo", GKSUDO: "gksudo",
KDESU: "kdesu", KDESU: "kdesu",
KTSUSS: "ktsuss", KTSUSS: "ktsuss"}
}
_status_dict = { _status_dict = {
'aborted': _('Connection Cancelled'), 'aborted': _('Connection Cancelled'),
'association_failed': _('Connection failed: Could not contact the ' + \ 'association_failed': _('Connection failed: Could not contact the '
'wireless access point.'), 'wireless access point.'),
'bad_pass': _('Connection Failed: Bad password'), 'bad_pass': _('Connection Failed: Bad password'),
'configuring_interface': _('Configuring wireless interface...'), 'configuring_interface': _('Configuring wireless interface...'),
@@ -107,6 +104,7 @@ _status_dict = {
'verifying_association': _('Verifying access point association...'), 'verifying_association': _('Verifying access point association...'),
} }
class WicdError(Exception): class WicdError(Exception):
"""Custom Exception type.""" """Custom Exception type."""
pass pass
@@ -165,6 +163,7 @@ def Run(cmd, include_stderr=False, return_pipe=False,
else: else:
return f.communicate()[0].decode() return f.communicate()[0].decode()
def LaunchAndWait(cmd): def LaunchAndWait(cmd):
"""Launches the given program with the given arguments, then blocks. """Launches the given program with the given arguments, then blocks.
@@ -179,6 +178,7 @@ def LaunchAndWait(cmd):
p = Popen(cmd, shell=False, stdout=PIPE, stderr=STDOUT, stdin=None) p = Popen(cmd, shell=False, stdout=PIPE, stderr=STDOUT, stdin=None)
return p.wait() return p.wait()
def IsValidIP(ip): def IsValidIP(ip):
"""Make sure an entered IP is valid.""" """Make sure an entered IP is valid."""
if not ip: if not ip:
@@ -189,6 +189,7 @@ def IsValidIP(ip):
return False return False
return True return True
def IsValidIPv4(ip): def IsValidIPv4(ip):
''' Make sure an entered IP is a valid IPv4. ''' ''' Make sure an entered IP is a valid IPv4. '''
try: try:
@@ -197,6 +198,7 @@ def IsValidIPv4(ip):
return False return False
return True return True
def IsValidIPv6(ip): def IsValidIPv6(ip):
''' Make sure an entered IP is a valid IPv6. ''' ''' Make sure an entered IP is a valid IPv6. '''
try: try:
@@ -205,6 +207,7 @@ def IsValidIPv6(ip):
return False return False
return True return True
def PromptToStartDaemon(): def PromptToStartDaemon():
"""Prompt the user to start the daemon""" """Prompt the user to start the daemon"""
daemonloc = wpath.sbin + 'wicd' daemonloc = wpath.sbin + 'wicd'
@@ -221,6 +224,7 @@ def PromptToStartDaemon():
os.spawnvpe(os.P_WAIT, sudo_prog, sudo_args, os.environ) os.spawnvpe(os.P_WAIT, sudo_prog, sudo_args, os.environ)
return True return True
def RunRegex(regex, s): def RunRegex(regex, s):
"""runs a regex search on a string""" """runs a regex search on a string"""
m = regex.search(s) m = regex.search(s)
@@ -229,10 +233,12 @@ def RunRegex(regex, s):
else: else:
return None return None
def WriteLine(my_file, text): def WriteLine(my_file, text):
"""write a line to a file""" """write a line to a file"""
my_file.write(text + "\n") my_file.write(text + "\n")
def ExecuteScripts(scripts_dir, verbose=False, extra_parameters=()): def ExecuteScripts(scripts_dir, verbose=False, extra_parameters=()):
"""Execute every executable file in a given directory.""" """Execute every executable file in a given directory."""
if not os.path.exists(scripts_dir): if not os.path.exists(scripts_dir):
@@ -245,6 +251,7 @@ def ExecuteScripts(scripts_dir, verbose=False, extra_parameters=()):
ExecuteScript(os.path.abspath(obj), verbose=verbose, ExecuteScript(os.path.abspath(obj), verbose=verbose,
extra_parameters=extra_parameters) extra_parameters=extra_parameters)
def ExecuteScript(script, verbose=False, extra_parameters=()): def ExecuteScript(script, verbose=False, extra_parameters=()):
"""Execute a command and send its output to the bit bucket.""" """Execute a command and send its output to the bit bucket."""
extra_parameters = [quote(s) for s in extra_parameters] extra_parameters = [quote(s) for s in extra_parameters]
@@ -257,6 +264,7 @@ def ExecuteScript(script, verbose=False, extra_parameters=()):
if verbose: if verbose:
print(("%s returned %s" % (script, ret))) print(("%s returned %s" % (script, ret)))
def ReadFile(filename): def ReadFile(filename):
"""read in a file and return it's contents as a string""" """read in a file and return it's contents as a string"""
if not os.path.exists(filename): if not os.path.exists(filename):
@@ -266,6 +274,7 @@ def ReadFile(filename):
my_file.close() my_file.close()
return str(data) return str(data)
def to_bool(var): def to_bool(var):
"""Convert a string to type bool, but make "False"/"0" become False.""" """Convert a string to type bool, but make "False"/"0" become False."""
if var in ("False", "0"): if var in ("False", "0"):
@@ -274,6 +283,7 @@ def to_bool(var):
var = bool(var) var = bool(var)
return var return var
def Noneify(variable, convert_to_bool=True): def Noneify(variable, convert_to_bool=True):
"""Convert string types to either None or booleans""" """Convert string types to either None or booleans"""
# set string Nones to real Nones # set string Nones to real Nones
@@ -287,6 +297,7 @@ def Noneify(variable, convert_to_bool=True):
return True return True
return variable return variable
def ParseEncryption(network): def ParseEncryption(network):
"""Parse through an encryption template file """Parse through an encryption template file
@@ -310,7 +321,7 @@ def ParseEncryption(network):
# This is the last line, so we just write it. # This is the last line, so we just write it.
config_file = ''.join([config_file, line]) config_file = ''.join([config_file, line])
elif "$_" in line: elif "$_" in line:
for cur_val in re.findall('\$_([A-Z0-9_]+)', line): for cur_val in re.findall(r'\$_([A-Z0-9_]+)', line):
if cur_val: if cur_val:
rep_val = network.get(cur_val.lower()) rep_val = network.get(cur_val.lower())
if not rep_val: if not rep_val:
@@ -344,6 +355,7 @@ def ParseEncryption(network):
f.write(config_file) f.write(config_file)
f.close() f.close()
def LoadEncryptionMethods(wired=False): def LoadEncryptionMethods(wired=False):
"""Load encryption methods from configuration files """Load encryption methods from configuration files
@@ -370,6 +382,7 @@ def LoadEncryptionMethods(wired = False):
encryptionTypes.append(parsed_template) encryptionTypes.append(parsed_template)
return encryptionTypes return encryptionTypes
def __parse_field_ent(fields, field_type='require'): def __parse_field_ent(fields, field_type='require'):
fields = fields.split(" ") fields = fields.split(" ")
ret = [] ret = []
@@ -383,6 +396,7 @@ def __parse_field_ent(fields, field_type='require'):
ret.append([val, disp_val[1:]]) ret.append([val, disp_val[1:]])
return ret return ret
def _parse_enc_template(enctype): def _parse_enc_template(enctype):
"""Parse an encryption template.""" """Parse an encryption template."""
def parse_ent(line, key): def parse_ent(line, key):
@@ -405,10 +419,12 @@ def _parse_enc_template(enctype):
if line.startswith("name") and not cur_type["name"]: if line.startswith("name") and not cur_type["name"]:
cur_type["name"] = parse_ent(line, "name") cur_type["name"] = parse_ent(line, "name")
elif line.startswith("require"): elif line.startswith("require"):
cur_type["required"] = __parse_field_ent(parse_ent(line, "require")) cur_type["required"] = __parse_field_ent(parse_ent(line,
"require"))
if not cur_type["required"]: if not cur_type["required"]:
# An error occured parsing the require line. # An error occured parsing the require line.
print(("Invalid 'required' line found in template %s" % enctype)) print("Invalid 'required' line found in template %s" %
enctype)
continue continue
elif line.startswith("optional"): elif line.startswith("optional"):
cur_type["optional"] = __parse_field_ent(parse_ent(line, cur_type["optional"] = __parse_field_ent(parse_ent(line,
@@ -416,30 +432,32 @@ def _parse_enc_template(enctype):
field_type="optional") field_type="optional")
if not cur_type["optional"]: if not cur_type["optional"]:
# An error occured parsing the optional line. # An error occured parsing the optional line.
print(("Invalid 'optional' line found in template %s" % enctype)) print("Invalid 'optional' line found in template %s" %
enctype)
continue continue
elif line.startswith("protected"): elif line.startswith("protected"):
cur_type["protected"] = __parse_field_ent( cur_type["protected"] = __parse_field_ent(parse_ent(line,
parse_ent(line, "protected"), "protected"),
field_type="protected" field_type="protected")
)
if not cur_type["protected"]: if not cur_type["protected"]:
# An error occured parsing the protected line. # An error occured parsing the protected line.
print(("Invalid 'protected' line found in template %s" % enctype)) print("Invalid 'protected' line found in template %s" %
enctype)
continue continue
elif line.startswith("----"): elif line.startswith("----"):
# We're done. # We're done.
break break
f.close() f.close()
if not cur_type["required"]: if not cur_type["required"]:
print(("Failed to find a 'require' line in template %s" % enctype)) print("Failed to find a 'require' line in template %s" % enctype)
return None return None
if not cur_type["name"]: if not cur_type["name"]:
print(("Failed to find a 'name' line in template %s" % enctype)) print("Failed to find a 'name' line in template %s" % enctype)
return None return None
else: else:
return cur_type return cur_type
def noneToString(text): def noneToString(text):
"""Convert None, "None", or "" to string type "None" """Convert None, "None", or "" to string type "None"
@@ -452,6 +470,7 @@ def noneToString(text):
else: else:
return to_unicode(text) return to_unicode(text)
def sanitize_config(s): def sanitize_config(s):
"""Sanitize property names to be used in config-files.""" """Sanitize property names to be used in config-files."""
allowed = string.ascii_letters + '_' + string.digits allowed = string.ascii_letters + '_' + string.digits
@@ -461,6 +480,7 @@ def sanitize_config(s):
# make it simple. # make it simple.
return s.encode('ascii', 'replace').translate(None, table) return s.encode('ascii', 'replace').translate(None, table)
def sanitize_escaped(s): def sanitize_escaped(s):
"""Sanitize double-escaped unicode strings.""" """Sanitize double-escaped unicode strings."""
lastpos = -1 lastpos = -1
@@ -473,6 +493,7 @@ def sanitize_escaped(s):
s = s.replace('\\x'+c, chr(int(c, 16))) s = s.replace('\\x'+c, chr(int(c, 16)))
return s return s
def to_unicode(x): def to_unicode(x):
"""Attempts to convert a string to utf-8.""" """Attempts to convert a string to utf-8."""
# If this is a unicode string, encode it and return # If this is a unicode string, encode it and return
@@ -498,6 +519,7 @@ def to_unicode(x):
return ret return ret
def RenameProcess(new_name): def RenameProcess(new_name):
"""Renames the process calling the function to the given name.""" """Renames the process calling the function to the given name."""
if 'linux' not in sys.platform: if 'linux' not in sys.platform:
@@ -509,10 +531,11 @@ def RenameProcess(new_name):
libc = ctypes.CDLL(find_library('c')) libc = ctypes.CDLL(find_library('c'))
libc.prctl(15, new_name, 0, 0, 0) libc.prctl(15, new_name, 0, 0, 0)
return True return True
except: except Exception:
print("rename failed") print("rename failed")
return False return False
def detect_desktop_environment(): def detect_desktop_environment():
"""Try to determine which desktop environment is in use. """Try to determine which desktop environment is in use.
@@ -534,6 +557,7 @@ def detect_desktop_environment():
pass pass
return desktop_environment return desktop_environment
def get_sudo_cmd(msg, prog_num=0): def get_sudo_cmd(msg, prog_num=0):
"""Returns a graphical sudo command for generic use.""" """Returns a graphical sudo command for generic use."""
sudo_prog = choose_sudo_prog(prog_num) sudo_prog = choose_sudo_prog(prog_num)
@@ -545,6 +569,7 @@ def get_sudo_cmd(msg, prog_num=0):
msg_flag = "--caption" msg_flag = "--caption"
return [sudo_prog, msg_flag, msg] return [sudo_prog, msg_flag, msg]
def choose_sudo_prog(prog_num=0): def choose_sudo_prog(prog_num=0):
"""Try to intelligently decide which graphical sudo program to use.""" """Try to intelligently decide which graphical sudo program to use."""
if prog_num: if prog_num:
@@ -566,6 +591,7 @@ def choose_sudo_prog(prog_num=0):
return path return path
return "" return ""
def find_path(cmd): def find_path(cmd):
"""Try to find a full path for a given file name. """Try to find a full path for a given file name.
@@ -583,6 +609,7 @@ def find_path(cmd):
return os.path.join(path, cmd) return os.path.join(path, cmd)
return None return None
def noneToBlankString(text): def noneToBlankString(text):
"""Converts NoneType or "None" to a blank string.""" """Converts NoneType or "None" to a blank string."""
if text in (None, "None"): if text in (None, "None"):
@@ -590,6 +617,7 @@ def noneToBlankString(text):
else: else:
return str(text) return str(text)
def stringToNone(text): def stringToNone(text):
"""Performs opposite function of noneToString.""" """Performs opposite function of noneToString."""
if text in ("", None, "None"): if text in ("", None, "None"):
@@ -597,12 +625,14 @@ def stringToNone(text):
else: else:
return str(text) return str(text)
def checkboxTextboxToggle(checkbox, textboxes): def checkboxTextboxToggle(checkbox, textboxes):
"""Manage {de,}activation of textboxes depending on checkboxes.""" """Manage {de,}activation of textboxes depending on checkboxes."""
# FIXME: should be moved to UI-specific files? # FIXME: should be moved to UI-specific files?
for textbox in textboxes: for textbox in textboxes:
textbox.set_sensitive(checkbox.get_active()) textbox.set_sensitive(checkbox.get_active())
def threaded(f): def threaded(f):
"""A decorator that will make any function run in a new thread.""" """A decorator that will make any function run in a new thread."""
@@ -618,6 +648,7 @@ def threaded(f):
return wrapper return wrapper
def timeout_add(time, func, milli=False): def timeout_add(time, func, milli=False):
"""Convience function for running a function on a timer.""" """Convience function for running a function on a timer."""
if hasattr(gobject, "timeout_add_seconds") and not milli: if hasattr(gobject, "timeout_add_seconds") and not milli:
@@ -627,6 +658,7 @@ def timeout_add(time, func, milli=False):
time = time * 1000 time = time * 1000
return gobject.timeout_add(time, func) return gobject.timeout_add(time, func)
def izip_longest(*args, **kwds): def izip_longest(*args, **kwds):
"""Implement the itertools.izip_longest method. """Implement the itertools.izip_longest method.
@@ -635,8 +667,10 @@ def izip_longest(*args, **kwds):
""" """
# izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D- # izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
fillvalue = kwds.get('fillvalue') fillvalue = kwds.get('fillvalue')
def sentinel(counter=([fillvalue]*(len(args)-1)).pop): def sentinel(counter=([fillvalue]*(len(args)-1)).pop):
yield counter() # yields the fillvalue, or raises IndexError yield counter() # yields the fillvalue, or raises IndexError
fillers = repeat(fillvalue) fillers = repeat(fillvalue)
iters = [chain(it, sentinel(), fillers) for it in args] iters = [chain(it, sentinel(), fillers) for it in args]
try: try:
@@ -645,6 +679,7 @@ def izip_longest(*args, **kwds):
except IndexError: except IndexError:
pass pass
def grouper(n, iterable, fillvalue=None): def grouper(n, iterable, fillvalue=None):
"""Iterate over several elements at once """Iterate over several elements at once

View File

@@ -24,9 +24,9 @@ when appropriate.
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from gi.repository import GLib as gobject
import time import time
from gi.repository import GLib as gobject
from dbus import DBusException from dbus import DBusException
from wicd import wpath from wicd import wpath
@@ -46,6 +46,7 @@ wireless = dbus_dict["wireless"]
mainloop = None mainloop = None
def diewithdbus(func): def diewithdbus(func):
""" """
Decorator catching DBus exceptions, making wicd quit. Decorator catching DBus exceptions, making wicd quit.
@@ -69,6 +70,7 @@ def diewithdbus(func):
wrapper.__doc__ = func.__doc__ wrapper.__doc__ = func.__doc__
return wrapper return wrapper
class ConnectionStatus(object): class ConnectionStatus(object):
"""Class for monitoring the computer's connection status.""" """Class for monitoring the computer's connection status."""
def __init__(self): def __init__(self):
@@ -278,15 +280,18 @@ class ConnectionStatus(object):
if wired.CheckIfWiredConnecting(): if wired.CheckIfWiredConnecting():
info = ["wired"] info = ["wired"]
else: else:
info = ["wireless", info = ["wireless", misc.
misc.noneToBlankString(wireless.GetCurrentNetwork(iwconfig))] noneToBlankString(wireless.
GetCurrentNetwork(iwconfig))]
elif state == misc.WIRELESS: elif state == misc.WIRELESS:
self.reconnect_tries = 0 self.reconnect_tries = 0
info = [str(wifi_ip), info = [str(wifi_ip),
misc.noneToBlankString(wireless.GetCurrentNetwork(iwconfig)), misc.noneToBlankString(wireless.
GetCurrentNetwork(iwconfig)),
str(self._get_printable_sig_strength()), str(self._get_printable_sig_strength()),
str(wireless.GetCurrentNetworkID(iwconfig)), str(wireless.GetCurrentNetworkID(iwconfig)),
misc.noneToBlankString(wireless.GetCurrentBitrate(iwconfig))] misc.noneToBlankString(wireless.
GetCurrentBitrate(iwconfig))]
elif state == misc.WIRED: elif state == misc.WIRED:
self.reconnect_tries = 0 self.reconnect_tries = 0
info = [str(wired_ip)] info = [str(wired_ip)]
@@ -301,8 +306,8 @@ class ConnectionStatus(object):
self.signal_changed)): self.signal_changed)):
daemon.EmitStatusChanged(state, info) daemon.EmitStatusChanged(state, info)
if (state != self.last_state) and (state == misc.NOT_CONNECTED) and \ if (state != self.last_state and state == misc.NOT_CONNECTED and
(not daemon.GetForcedDisconnect()): not daemon.GetForcedDisconnect()):
daemon.Disconnect() daemon.Disconnect()
# Disconnect() sets forced disconnect = True # Disconnect() sets forced disconnect = True
# so we'll revert that # so we'll revert that
@@ -364,22 +369,24 @@ class ConnectionStatus(object):
# before we reconnect # before we reconnect
print('Disconnecting from network') print('Disconnecting from network')
wireless.DisconnectWireless() wireless.DisconnectWireless()
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
def main(): def main():
"""Starts the connection monitor. """Starts the connection monitor.

View File

@@ -1,6 +1,3 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""networking - Provides wrappers for common network operations """networking - Provides wrappers for common network operations
This module provides wrappers of the common network tasks as well as This module provides wrappers of the common network tasks as well as
@@ -51,10 +48,9 @@ from signal import SIGTERM
from functools import cmp_to_key from functools import cmp_to_key
# wicd imports # wicd imports
from . import misc from wicd import misc
from . import wpath from wicd import wpath
from .backend import BackendManager from wicd.backend import BackendManager
from .translations import _
if __name__ == '__main__': if __name__ == '__main__':
wpath.chdir(__file__) wpath.chdir(__file__)
@@ -62,6 +58,7 @@ if __name__ == '__main__':
BACKEND = None BACKEND = None
BACKEND_MGR = BackendManager() BACKEND_MGR = BackendManager()
def abortable(func): def abortable(func):
"""Mark a method in a ConnectionThread as abortable. """Mark a method in a ConnectionThread as abortable.
@@ -79,6 +76,7 @@ def abortable(func):
wrapper.__module = func.__module__ wrapper.__module = func.__module__
return wrapper return wrapper
def get_backend_list(): def get_backend_list():
"""Returns a list of available backends.""" """Returns a list of available backends."""
if BACKEND_MGR: if BACKEND_MGR:
@@ -86,6 +84,7 @@ def get_backend_list():
else: else:
return [""] return [""]
def get_backend_update_interval(): def get_backend_update_interval():
"""Returns the suggested connection status update interval.""" """Returns the suggested connection status update interval."""
if BACKEND_MGR: if BACKEND_MGR:
@@ -93,6 +92,7 @@ def get_backend_update_interval():
else: else:
return 5 # Seconds, this should never happen though. return 5 # Seconds, this should never happen though.
def get_current_backend(): def get_current_backend():
"""Returns the current backend instance.""" """Returns the current backend instance."""
if BACKEND_MGR: if BACKEND_MGR:
@@ -100,10 +100,12 @@ def get_current_backend():
else: else:
return None return None
def get_backend_description(backend_name): def get_backend_description(backend_name):
"""Returns the description of the currently loaded backend.""" """Returns the description of the currently loaded backend."""
return BACKEND_MGR.get_backend_description(backend_name) return BACKEND_MGR.get_backend_description(backend_name)
def get_backend_description_dict(): def get_backend_description_dict():
"""Returns a dict of all available backend descriptions.""" """Returns a dict of all available backend descriptions."""
d = {} d = {}
@@ -112,6 +114,7 @@ def get_backend_description_dict():
d[be] = get_backend_description(be) d[be] = get_backend_description(be)
return d return d
def expand_script_macros(script, msg, bssid, essid): def expand_script_macros(script, msg, bssid, essid):
"""Expands any supported macros in a script. """Expands any supported macros in a script.
@@ -162,6 +165,7 @@ class Controller(object):
def get_debug(self): def get_debug(self):
"""Getter for debug property.""" """Getter for debug property."""
return self._debug return self._debug
def set_debug(self, value): def set_debug(self, value):
"""Setter for debug property.""" """Setter for debug property."""
self._debug = value self._debug = value
@@ -174,6 +178,7 @@ class Controller(object):
self._dhcp_client = value self._dhcp_client = value
if self.iface: if self.iface:
self.iface.DHCP_CLIENT = value self.iface.DHCP_CLIENT = value
def get_dhcp_client(self): def get_dhcp_client(self):
"""Getter for dhcp_client property.""" """Getter for dhcp_client property."""
return self._dhcp_client return self._dhcp_client
@@ -184,6 +189,7 @@ class Controller(object):
self._flush_tool = value self._flush_tool = value
if self.iface: if self.iface:
self.iface.flush_tool = value self.iface.flush_tool = value
def get_flush_tool(self): def get_flush_tool(self):
"""Getter for flush_tool property.""" """Getter for flush_tool property."""
return self._flush_tool return self._flush_tool
@@ -239,7 +245,8 @@ class Controller(object):
extra_parameters=(nettype, name, mac)) extra_parameters=(nettype, name, mac))
if self.post_disconnect_script: if self.post_disconnect_script:
print('Running post-disconnect script') print('Running post-disconnect script')
misc.ExecuteScript(expand_script_macros(self.post_disconnect_script, misc.ExecuteScript(expand_script_macros(self.
post_disconnect_script,
'post-disconnection', 'post-disconnection',
mac, name), mac, name),
self.debug) self.debug)
@@ -364,6 +371,7 @@ class ConnectThread(threading.Thread):
self._should_die = val self._should_die = val
finally: finally:
self.lock.release() self.lock.release()
def get_should_die(self): def get_should_die(self):
"""Getter for should_die property.""" """Getter for should_die property."""
return self._should_die return self._should_die
@@ -416,8 +424,8 @@ class ConnectThread(threading.Thread):
iface.Down() iface.Down()
@abortable @abortable
def run_global_scripts_if_needed(self, script_dir, extra_parameters=()): def run_scripts(self, script_dir, extra_parameters=()):
""" Run global scripts if needed. '""" """Execute all script in provided script_dir."""
misc.ExecuteScripts(script_dir, verbose=self.debug, misc.ExecuteScripts(script_dir, verbose=self.debug,
extra_parameters=extra_parameters) extra_parameters=extra_parameters)
@@ -445,9 +453,10 @@ class ConnectThread(threading.Thread):
@abortable @abortable
def set_broadcast_address(self, iface): def set_broadcast_address(self, iface):
"""Set the broadcast address for the given interface.""" """Set the broadcast address for the given interface."""
if not self.network.get('broadcast') == None: if self.network.get('broadcast') is not None:
self.SetStatus('setting_broadcast_address') self.SetStatus('setting_broadcast_address')
print(('Setting the broadcast address...' + self.network['broadcast'])) print('Setting the broadcast address...' +
self.network['broadcast'])
iface.SetAddress(broadcast=self.network['broadcast']) iface.SetAddress(broadcast=self.network['broadcast'])
@abortable @abortable
@@ -467,9 +476,9 @@ class ConnectThread(threading.Thread):
else: else:
# Run dhcp... # Run dhcp...
self.SetStatus('running_dhcp') self.SetStatus('running_dhcp')
if self.network.get('usedhcphostname') == None: if self.network.get('usedhcphostname') is None:
self.network['usedhcphostname'] = False self.network['usedhcphostname'] = False
if self.network.get('dhcphostname') == None: if self.network.get('dhcphostname') is None:
self.network['dhcphostname'] = os.uname()[1] self.network['dhcphostname'] = os.uname()[1]
if self.network['usedhcphostname']: if self.network['usedhcphostname']:
hname = self.network['dhcphostname'] hname = self.network['dhcphostname']
@@ -478,9 +487,14 @@ class ConnectThread(threading.Thread):
hname = None hname = None
print("Running DHCP with NO hostname") print("Running DHCP with NO hostname")
# Check if a global DNS is configured. If it is, then let the DHCP know *not* to update resolv.conf # Check if a global DNS is configured. If it is, then let the DHCP
# know *not* to update resolv.conf
staticdns = False staticdns = False
if self.network.get('use_global_dns') or (self.network.get('use_static_dns') and (self.network.get('dns1') or self.network.get('dns2') or self.network.get('dns3'))): if (self.network.get('use_global_dns') or
(self.network.get('use_static_dns') and
(self.network.get('dns1') or
self.network.get('dns2') or
self.network.get('dns3')))):
staticdns = True staticdns = True
dhcp_status = iface.StartDHCP(hname, staticdns) dhcp_status = iface.StartDHCP(hname, staticdns)
@@ -514,8 +528,9 @@ class ConnectThread(threading.Thread):
misc.Noneify(self.global_dns_3), misc.Noneify(self.global_dns_3),
misc.Noneify(self.global_dns_dom), misc.Noneify(self.global_dns_dom),
misc.Noneify(self.global_search_dom)) misc.Noneify(self.global_search_dom))
elif self.network.get('use_static_dns') and (self.network.get('dns1') or elif (self.network.get('use_static_dns') and
self.network.get('dns2') or self.network.get('dns3')): (self.network.get('dns1') or self.network.get('dns2')
or self.network.get('dns3'))):
self.SetStatus('setting_static_dns') self.SetStatus('setting_static_dns')
iface.SetDNS(self.network.get('dns1'), iface.SetDNS(self.network.get('dns1'),
self.network.get('dns2'), self.network.get('dns2'),
@@ -592,6 +607,7 @@ class Wireless(Controller):
self._wireless_interface = value self._wireless_interface = value
if self.wiface: if self.wiface:
self.wiface.SetInterface(value) self.wiface.SetInterface(value)
def get_wireless_iface(self): def get_wireless_iface(self):
"""Getter for wireless_interface property.""" """Getter for wireless_interface property."""
return self._wireless_interface return self._wireless_interface
@@ -602,6 +618,7 @@ class Wireless(Controller):
self._wpa_driver = value self._wpa_driver = value
if self.wiface: if self.wiface:
self.SetWPADriver(value) self.SetWPADriver(value)
def get_wpa_driver(self): def get_wpa_driver(self):
"""Getter for wpa_driver property.""" """Getter for wpa_driver property."""
return self._wpa_driver return self._wpa_driver
@@ -610,6 +627,7 @@ class Wireless(Controller):
def set_iface(self, value): def set_iface(self, value):
"""Setter for iface property.""" """Setter for iface property."""
self.wiface = value self.wiface = value
def get_iface(self): def get_iface(self):
"""Getter for iface property.""" """Getter for iface property."""
return self.wiface return self.wiface
@@ -626,7 +644,8 @@ class Wireless(Controller):
backend = self._backend backend = self._backend
if backend: if backend:
self.wiface = backend.WirelessInterface(self.wireless_interface, self.wiface = backend.WirelessInterface(self.wireless_interface,
self.debug, self.wpa_driver) self.debug,
self.wpa_driver)
def Scan(self, essid=None): def Scan(self, essid=None):
"""Scan for available wireless networks. """Scan for available wireless networks.
@@ -644,8 +663,9 @@ class Wireless(Controller):
key = 'quality' key = 'quality'
else: else:
key = 'strength' key = 'strength'
return ((x[key] > y[key]) - (x[key] < y[key])) # cmp(x[key], y[key])
return ((x[key] > y[key]) -
(x[key] < y[key])) # cmp(x[key], y[key])
if not self.wiface: if not self.wiface:
return [] return []
@@ -656,7 +676,8 @@ class Wireless(Controller):
# If there is a hidden essid then set it now, so that when it is # If there is a hidden essid then set it now, so that when it is
# scanned it will be recognized. # scanned it will be recognized.
# Note: this does not always work, sometimes we have to pass it with "iwlist wlan0 scan essid -- XXXXX" # Note: this does not always work, sometimes we have to pass it with
# "iwlist wlan0 scan essid -- XXXXX"
essid = misc.Noneify(essid) essid = misc.Noneify(essid)
if essid is not None: if essid is not None:
print(('Setting hidden essid ' + essid)) print(('Setting hidden essid ' + essid))
@@ -679,13 +700,13 @@ class Wireless(Controller):
if not self.wiface: if not self.wiface:
return False return False
self.connecting_thread = WirelessConnectThread(network, self.connecting_thread = WirelessConnectThread(
self.wireless_interface, self.wpa_driver, self.before_script, network, self.wireless_interface, self.wpa_driver,
self.after_script, self.pre_disconnect_script, self.before_script, self.after_script, self.pre_disconnect_script,
self.post_disconnect_script, self.global_dns_1, self.post_disconnect_script, self.global_dns_1, self.global_dns_2,
self.global_dns_2, self.global_dns_3, self.global_dns_dom, self.global_dns_3, self.global_dns_dom, self.global_search_dom,
self.global_search_dom, self.wiface, self.should_verify_ap, self.wiface, self.should_verify_ap, self.bitrate,
self.bitrate, self.allow_lower_bitrates, debug) self.allow_lower_bitrates, debug)
self.connecting_thread.setDaemon(True) self.connecting_thread.setDaemon(True)
self.connecting_thread.start() self.connecting_thread.start()
return True return True
@@ -780,8 +801,7 @@ class Wireless(Controller):
"""Stop wpa_supplicant.""" """Stop wpa_supplicant."""
return self.wiface.StopWPA() return self.wiface.StopWPA()
def CreateAdHocNetwork(self, essid, channel, ip, enctype, key, def CreateAdHocNetwork(self, essid, channel, ip, enctype, key, enc_used):
enc_used):
"""Create an ad-hoc wireless network. """Create an ad-hoc wireless network.
Keyword arguments: Keyword arguments:
@@ -860,7 +880,8 @@ class Wireless(Controller):
""" """
cmd = 'rfkill list' cmd = 'rfkill list'
rfkill_out = misc.Run(cmd) rfkill_out = misc.Run(cmd)
soft_blocks = [x for x in rfkill_out.split('\t') if x.startswith('Soft')] soft_blocks = [x for x in rfkill_out.split('\t')
if x.startswith('Soft')]
for line in [x.strip() for x in soft_blocks]: for line in [x.strip() for x in soft_blocks]:
if line.endswith('yes'): if line.endswith('yes'):
return True return True
@@ -944,15 +965,12 @@ class WirelessConnectThread(ConnectThread):
self.is_connecting = True self.is_connecting = True
# Run pre-connection script. # Run pre-connection script.
self.run_global_scripts_if_needed(wpath.preconnectscripts, self.run_scripts(wpath.preconnectscripts,
extra_parameters=('wireless', extra_parameters=('wireless', self.network['essid'],
self.network['essid'], self.network['bssid']))
self.network['bssid'])
)
self.run_script_if_needed(self.before_script, 'pre-connection', self.run_script_if_needed(self.before_script, 'pre-connection',
self.network['bssid'], self.network['essid']) self.network['bssid'], self.network['essid'])
# Take down interface and clean up previous connections. # Take down interface and clean up previous connections.
self.put_iface_down(wiface) self.put_iface_down(wiface)
self.release_dhcp_clients(wiface) self.release_dhcp_clients(wiface)
@@ -995,11 +1013,9 @@ class WirelessConnectThread(ConnectThread):
self.verify_association(wiface) self.verify_association(wiface)
# Run post-connection script. # Run post-connection script.
self.run_global_scripts_if_needed(wpath.postconnectscripts, self.run_scripts(wpath.postconnectscripts,
extra_parameters=('wireless', extra_parameters=('wireless', self.network['essid'],
self.network['essid'], self.network['bssid']))
self.network['bssid'])
)
self.run_script_if_needed(self.after_script, 'post-connection', self.run_script_if_needed(self.after_script, 'post-connection',
self.network['bssid'], self.network['essid']) self.network['bssid'], self.network['essid'])
@@ -1024,7 +1040,8 @@ class WirelessConnectThread(ConnectThread):
print("Verifying AP association...") print("Verifying AP association...")
for tries in range(1, 11): for tries in range(1, 11):
print(("Attempt %d of 10..." % tries)) print(("Attempt %d of 10..." % tries))
retcode = self.iface.VerifyAPAssociation(self.network['gateway']) retcode = self.iface.VerifyAPAssociation(self.
network['gateway'])
if retcode == 0: if retcode == 0:
print("Successfully associated.") print("Successfully associated.")
break break
@@ -1062,9 +1079,9 @@ class WirelessConnectThread(ConnectThread):
if not self.network.get('psk'): if not self.network.get('psk'):
self.network['psk'] = self.network['key'] self.network['psk'] = self.network['key']
print(('WARNING: PSK generation failed! Falling back to ' + \ print('WARNING: PSK generation failed! Falling back to '
'wireless key.\nPlease report this error to the wicd ' + \ 'wireless key.\nPlease report this error to the wicd '
'developers!')) 'developers!')
# Generate the wpa_supplicant file... # Generate the wpa_supplicant file...
if self.network.get('enctype'): if self.network.get('enctype'):
self.SetStatus('generating_wpa_config') self.SetStatus('generating_wpa_config')
@@ -1083,34 +1100,39 @@ class Wired(Controller):
self._wired_interface = None self._wired_interface = None
self.liface = None self.liface = None
def set_link_detect(self, value): @property
def link_detect(self):
"""Getter for link_detect property."""
return self._link_detect
@link_detect.setter
def link_detect(self, value):
"""Setter for link_detect property.""" """Setter for link_detect property."""
self._link_detect = value self._link_detect = value
if self.liface: if self.liface:
self.liface.link_detect = value self.liface.link_detect = value
def get_link_detect(self):
""" Getter for link_detect property. """
return self._link_detect
link_detect = property(get_link_detect, set_link_detect)
@property
def wired_iface(self):
"""Getter for wired_interface property."""
return self._wired_interface
def set_wired_iface(self, value): @wired_iface.setter
def wired_iface(self, value):
"""Setter for wired_interface property.""" """Setter for wired_interface property."""
self._wired_interface = value self._wired_interface = value
if self.liface: if self.liface:
self.liface.SetInterface(value) self.liface.SetInterface(value)
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): @property
""" Setter for iface property. """ def iface(self):
self.liface = value
def get_iface(self):
"""Getter for iface property.""" """Getter for iface property."""
return self.liface return self.liface
iface = property(get_iface, set_iface)
@iface.setter
def iface(self, value):
"""Setter for iface property."""
self.liface = value
def LoadBackend(self, backend): def LoadBackend(self, backend):
"""Load the backend up.""" """Load the backend up."""
@@ -1137,12 +1159,12 @@ class Wired(Controller):
""" """
if not self.liface: if not self.liface:
return False return False
self.connecting_thread = WiredConnectThread(network, self.connecting_thread = WiredConnectThread(
self.wired_interface, self.before_script, self.after_script, network, self.wired_interface, self.before_script,
self.pre_disconnect_script, self.post_disconnect_script, self.after_script, self.pre_disconnect_script,
self.global_dns_1, self.global_dns_2, self.global_dns_3, self.post_disconnect_script, self.global_dns_1, self.global_dns_2,
self.global_dns_dom, self.global_search_dom, self.liface, self.global_dns_3, self.global_dns_dom, self.global_search_dom,
debug) self.liface, debug)
self.connecting_thread.setDaemon(True) self.connecting_thread.setDaemon(True)
self.connecting_thread.start() self.connecting_thread.start()
return self.connecting_thread return self.connecting_thread
@@ -1213,12 +1235,11 @@ class WiredConnectThread(ConnectThread):
self.is_connecting = True self.is_connecting = True
# Run pre-connection script. # Run pre-connection script.
self.run_global_scripts_if_needed(wpath.preconnectscripts, self.run_scripts(wpath.preconnectscripts,
extra_parameters=('wired', 'wired', extra_parameters=('wired', 'wired',
self.network['profilename']) self.network['profilename']))
) self.run_script_if_needed(self.before_script, 'pre-connection',
self.run_script_if_needed(self.before_script, 'pre-connection', 'wired', 'wired', 'wired')
'wired')
# Take down interface and clean up previous connections. # Take down interface and clean up previous connections.
self.put_iface_down(liface) self.put_iface_down(liface)
@@ -1241,12 +1262,11 @@ class WiredConnectThread(ConnectThread):
self.set_dns_addresses(liface) self.set_dns_addresses(liface)
# Run post-connection script. # Run post-connection script.
self.run_global_scripts_if_needed(wpath.postconnectscripts, self.run_scripts(wpath.postconnectscripts,
extra_parameters=('wired', 'wired', extra_parameters=('wired', 'wired',
self.network['profilename']) self.network['profilename']))
) self.run_script_if_needed(self.after_script, 'post-connection',
self.run_script_if_needed(self.after_script, 'post-connection', 'wired', 'wired', 'wired')
'wired')
self.SetStatus('done') self.SetStatus('done')
print('Connecting thread exiting.') print('Connecting thread exiting.')

View File

@@ -23,10 +23,10 @@ Used for when a laptop enters hibernation/suspension.
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
import sys
import dbus import dbus
import dbus.service import dbus.service
import sys
try: try:
bus = dbus.SystemBus() bus = dbus.SystemBus()

View File

@@ -21,7 +21,7 @@
# #
import locale import locale
import os import os
from . import wpath from wicd import wpath
import gettext import gettext
@@ -54,7 +54,7 @@ def get_gettext():
fallback=True) fallback=True)
return lang.gettext return lang.gettext
_ = get_gettext() _ = get_gettext() # noqa
# language[] should contain only strings in encryption templates, which # language[] should contain only strings in encryption templates, which
@@ -66,10 +66,12 @@ language = {}
# FIXME: these were present in wicd 1.7.0, can't find where they are. # 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 # Leaving here for future reference, they should be removed whenever
# possible. # possible.
#language['cannot_start_daemon'] = _('Unable to connect to wicd daemon ' + \ # language['cannot_start_daemon'] = _('Unable to connect to wicd daemon '
# 'DBus interface. This typically means there was a problem starting ' + \ # 'DBus interface. This typically means '
# 'the daemon. Check the wicd log for more information.') # 'there was a problem starting the '
#language['backend_alert'] = _('Changes to your backend won't occur until ' + \ # 'daemon. Check the wicd log for more '
# 'information.')
# language['backend_alert'] = _('Changes to your backend won't occur until '
# 'the daemon is restarted.') # 'the daemon is restarted.')
# language['about_help'] = _('Stop a network connection in progress') # language['about_help'] = _('Stop a network connection in progress')
# language['connect'] = _('Connect') # language['connect'] = _('Connect')

View File

@@ -71,6 +71,7 @@ wireless_conf = os.path.join(wpath.etc, "wireless-settings.conf")
wired_conf = os.path.join(wpath.etc, "wired-settings.conf") wired_conf = os.path.join(wpath.etc, "wired-settings.conf")
dhclient_conf = os.path.join(wpath.etc, "dhclient.conf.template") dhclient_conf = os.path.join(wpath.etc, "dhclient.conf.template")
class WicdDaemon(dbus.service.Object, object): class WicdDaemon(dbus.service.Object, object):
"""The main wicd daemon class. """The main wicd daemon class.
@@ -140,6 +141,7 @@ class WicdDaemon(dbus.service.Object, object):
def get_debug_mode(self): def get_debug_mode(self):
"""Getter for debug_mode property.""" """Getter for debug_mode property."""
return self._debug_mode return self._debug_mode
def set_debug_mode(self, mode): def set_debug_mode(self, mode):
"""Setter for debug_mode property.""" """Setter for debug_mode property."""
self._debug_mode = mode self._debug_mode = mode
@@ -162,7 +164,8 @@ class WicdDaemon(dbus.service.Object, object):
def SetWiredInterface(self, interface): def SetWiredInterface(self, interface):
"""Sets the wired interface for the daemon to use.""" """Sets the wired interface for the daemon to use."""
print("setting wired interface %s" % (str(interface))) print("setting wired interface %s" % (str(interface)))
# Set it to a blank string, otherwise a network card named "None" will be searched # Set it to a blank string, otherwise a network card named "None" will
# be searched
self.wired.wired_interface = noneToBlankString(interface) self.wired.wired_interface = noneToBlankString(interface)
self.config.set("Settings", "wired_interface", interface, write=True) self.config.set("Settings", "wired_interface", interface, write=True)
@@ -170,9 +173,11 @@ class WicdDaemon(dbus.service.Object, object):
def SetWirelessInterface(self, interface): def SetWirelessInterface(self, interface):
"""Sets the wireless interface the daemon will use.""" """Sets the wireless interface the daemon will use."""
print("setting wireless interface %s" % (str(interface))) print("setting wireless interface %s" % (str(interface)))
# Set it to a blank string, otherwise a network card named "None" will be searched # Set it to a blank string, otherwise a network card named "None" will
# be searched
self.wifi.wireless_interface = noneToBlankString(interface) self.wifi.wireless_interface = noneToBlankString(interface)
self.config.set("Settings", "wireless_interface", interface, write=True) self.config.set("Settings", "wireless_interface", interface,
write=True)
@dbus.service.method('org.wicd.daemon') @dbus.service.method('org.wicd.daemon')
def SetWPADriver(self, driver): def SetWPADriver(self, driver):
@@ -192,8 +197,8 @@ class WicdDaemon(dbus.service.Object, object):
self.wired.use_global_dns = use self.wired.use_global_dns = use
@dbus.service.method('org.wicd.daemon') @dbus.service.method('org.wicd.daemon')
def SetGlobalDNS(self, dns1=None, dns2=None, dns3=None, def SetGlobalDNS(self, dns1=None, dns2=None, dns3=None, dns_dom=None,
dns_dom =None, search_dom=None): search_dom=None):
"""Sets the global dns addresses.""" """Sets the global dns addresses."""
print("setting global dns") print("setting global dns")
self.config.set("Settings", "global_dns_1", misc.noneToString(dns1)) self.config.set("Settings", "global_dns_1", misc.noneToString(dns1))
@@ -229,8 +234,8 @@ class WicdDaemon(dbus.service.Object, object):
print("setting backend to %s" % backend) print("setting backend to %s" % backend)
backends = networking.BACKEND_MGR.get_available_backends() backends = networking.BACKEND_MGR.get_available_backends()
if backend not in backends: if backend not in backends:
print("backend %s not available, trying to fallback to another" \ print(f"backend {backend} not available, trying to fallback to "
% backend) f"another")
try: try:
backend = backends[0] backend = backends[0]
except IndexError: except IndexError:
@@ -392,7 +397,7 @@ class WicdDaemon(dbus.service.Object, object):
and wait for the user to initiate reconnection. and wait for the user to initiate reconnection.
""" """
print('setting automatically reconnect when connection drops %s' % value) print(f'setting automatically reconnect when connection drops {value}')
self.config.set("Settings", "auto_reconnect", misc.to_bool(value), self.config.set("Settings", "auto_reconnect", misc.to_bool(value),
write=True) write=True)
self.auto_reconnect = misc.to_bool(value) self.auto_reconnect = misc.to_bool(value)
@@ -648,7 +653,8 @@ class WicdDaemon(dbus.service.Object, object):
@dbus.service.method("org.wicd.daemon") @dbus.service.method("org.wicd.daemon")
def GetAppAvailable(self, app): def GetAppAvailable(self, app):
"""Determine if a given application is available.""" """Determine if a given application is available."""
return bool(self.wifi.AppAvailable(app) or self.wired.AppAvailable(app)) return bool(self.wifi.AppAvailable(app) or
self.wired.AppAvailable(app))
@dbus.service.method('org.wicd.daemon') @dbus.service.method('org.wicd.daemon')
def GetDHCPClient(self): def GetDHCPClient(self):
@@ -740,8 +746,8 @@ class WicdDaemon(dbus.service.Object, object):
elif self.GetWiredAutoConnectMethod() == 1: elif self.GetWiredAutoConnectMethod() == 1:
network = wiredb.GetDefaultWiredNetwork() network = wiredb.GetDefaultWiredNetwork()
if not network: if not network:
print("Couldn't find a default wired connection," + \ print("Couldn't find a default wired connection, wired "
" wired autoconnect failed.") "autoconnect failed.")
self.wireless_bus._wireless_autoconnect(fresh) self.wireless_bus._wireless_autoconnect(fresh)
return return
@@ -749,7 +755,7 @@ class WicdDaemon(dbus.service.Object, object):
else: else:
network = wiredb.GetLastUsedWiredNetwork() network = wiredb.GetLastUsedWiredNetwork()
if not network: if not network:
print("no previous wired profile available, wired " + \ print("no previous wired profile available, wired "
"autoconnect failed.") "autoconnect failed.")
self.wireless_bus._wireless_autoconnect(fresh) self.wireless_bus._wireless_autoconnect(fresh)
return return
@@ -791,8 +797,8 @@ class WicdDaemon(dbus.service.Object, object):
"""Return whether connection results are available.""" """Return whether connection results are available."""
wired_thread = self.wired.connecting_thread wired_thread = self.wired.connecting_thread
wifi_thread = self.wifi.connecting_thread wifi_thread = self.wifi.connecting_thread
if ((wired_thread and wired_thread.connect_result) or if (wired_thread and wired_thread.connect_result or
(wifi_thread and wifi_thread.connect_result)): wifi_thread and wifi_thread.connect_result):
return True return True
else: else:
return False return False
@@ -881,7 +887,8 @@ class WicdDaemon(dbus.service.Object, object):
iface = self.wireless_bus.DetectWirelessInterface() iface = self.wireless_bus.DetectWirelessInterface()
if not iface: if not iface:
iface = 'wlan0' iface = 'wlan0'
self.SetWirelessInterface(app_conf.get("Settings", "wireless_interface", self.SetWirelessInterface(app_conf.get("Settings",
"wireless_interface",
default=iface)) default=iface))
iface = self.wired_bus.DetectWiredInterface() iface = self.wired_bus.DetectWiredInterface()
if not iface: if not iface:
@@ -891,7 +898,8 @@ class WicdDaemon(dbus.service.Object, object):
self.SetWPADriver(app_conf.get("Settings", "wpa_driver", self.SetWPADriver(app_conf.get("Settings", "wpa_driver",
default="wext")) default="wext"))
self.SetAlwaysShowWiredInterface(app_conf.get("Settings", self.SetAlwaysShowWiredInterface(app_conf.
get("Settings",
"always_show_wired_interface", "always_show_wired_interface",
default=False)) default=False))
self.SetUseGlobalDNS(app_conf.get("Settings", "use_global_dns", self.SetUseGlobalDNS(app_conf.get("Settings", "use_global_dns",
@@ -905,7 +913,8 @@ class WicdDaemon(dbus.service.Object, object):
self.SetGlobalDNS(dns1, dns2, dns3, dns_dom, search_dom) self.SetGlobalDNS(dns1, dns2, dns3, dns_dom, search_dom)
self.SetAutoReconnect(app_conf.get("Settings", "auto_reconnect", self.SetAutoReconnect(app_conf.get("Settings", "auto_reconnect",
default=True)) default=True))
self.SetDebugMode(app_conf.get("Settings", "debug_mode", default=False)) self.SetDebugMode(app_conf.get("Settings", "debug_mode",
default=False))
self.SetWiredAutoConnectMethod(app_conf.get("Settings", self.SetWiredAutoConnectMethod(app_conf.get("Settings",
"wired_connect_mode", "wired_connect_mode",
default=1)) default=1))
@@ -959,9 +968,6 @@ class WicdDaemon(dbus.service.Object, object):
print("Using wireless interface..." + self.GetWirelessInterface()) print("Using wireless interface..." + self.GetWirelessInterface())
print("Using wired interface..." + self.GetWiredInterface()) print("Using wired interface..." + self.GetWiredInterface())
##############################
###### Wireless Daemon #######
##############################
class WirelessDaemon(dbus.service.Object, object): class WirelessDaemon(dbus.service.Object, object):
"""DBus interface for wireless connection operations.""" """DBus interface for wireless connection operations."""
@@ -980,6 +986,7 @@ class WirelessDaemon(dbus.service.Object, object):
def get_debug_mode(self): def get_debug_mode(self):
"""Getter for the debug_mode property.""" """Getter for the debug_mode property."""
return self._debug_mode return self._debug_mode
def set_debug_mode(self, mode): def set_debug_mode(self, mode):
"""Setter for the debug_mode property.""" """Setter for the debug_mode property."""
self._debug_mode = mode self._debug_mode = mode
@@ -1115,8 +1122,8 @@ class WirelessDaemon(dbus.service.Object, object):
# We don't write script settings here. # We don't write script settings here.
prop = misc.sanitize_config(prop) prop = misc.sanitize_config(prop)
if prop.endswith('script'): if prop.endswith('script'):
print('Setting script properties through the daemon' \ print('Setting script properties through the daemon is not '
+ ' is not permitted.') 'permitted.')
return False return False
# whitelist some props that need different handling # whitelist some props that need different handling
if prop in ('key_index', ): if prop in ('key_index', ):
@@ -1160,7 +1167,7 @@ class WirelessDaemon(dbus.service.Object, object):
"""Returns the current dbm signal strength.""" """Returns the current dbm signal strength."""
try: try:
dbm_strength = int(self.wifi.GetDBMStrength(iwconfig)) dbm_strength = int(self.wifi.GetDBMStrength(iwconfig))
except: except Exception:
dbm_strength = 0 dbm_strength = 0
return dbm_strength return dbm_strength
@@ -1178,7 +1185,8 @@ class WirelessDaemon(dbus.service.Object, object):
if self.LastScan[x]['essid'] == currentESSID: if self.LastScan[x]['essid'] == currentESSID:
return x return x
if self.debug_mode: if self.debug_mode:
print('GetCurrentNetworkID: Returning -1, current network not found') print('GetCurrentNetworkID: Returning -1, current network not '
'found')
return -1 return -1
@dbus.service.method('org.wicd.daemon.wireless') @dbus.service.method('org.wicd.daemon.wireless')
@@ -1202,15 +1210,14 @@ class WirelessDaemon(dbus.service.Object, object):
# is done. # is done.
self.wifi.before_script = self.GetWirelessProperty(nid, 'beforescript') self.wifi.before_script = self.GetWirelessProperty(nid, 'beforescript')
self.wifi.after_script = self.GetWirelessProperty(nid, 'afterscript') self.wifi.after_script = self.GetWirelessProperty(nid, 'afterscript')
self.wifi.pre_disconnect_script = self.GetWirelessProperty(nid, self.wifi.pre_disconnect_script = (
'predisconnectscript') self.GetWirelessProperty(nid, 'predisconnectscript'))
self.wifi.post_disconnect_script = self.GetWirelessProperty(nid, self.wifi.post_disconnect_script = (
'postdisconnectscript') self.GetWirelessProperty(nid, 'postdisconnectscript'))
self.wifi.bitrate = self.GetWirelessProperty(nid, 'bitrate') self.wifi.bitrate = self.GetWirelessProperty(nid, 'bitrate')
self.wifi.allow_lower_bitrates = self.GetWirelessProperty(nid, self.wifi.allow_lower_bitrates = (
'allow_lower_bitrates') self.GetWirelessProperty(nid, 'allow_lower_bitrates'))
print('Connecting to wireless network ' + \ print(f"Connecting to wireless network {self.LastScan[nid]['essid']}")
str(self.LastScan[nid]['essid']))
# disconnect to make sure that scripts are run # disconnect to make sure that scripts are run
self.wifi.Disconnect() self.wifi.Disconnect()
self.daemon.wired_bus.wired.Disconnect() self.daemon.wired_bus.wired.Disconnect()
@@ -1220,7 +1227,9 @@ class WirelessDaemon(dbus.service.Object, object):
@dbus.service.method('org.wicd.daemon.wireless') @dbus.service.method('org.wicd.daemon.wireless')
def CheckIfWirelessConnecting(self): def CheckIfWirelessConnecting(self):
"""Returns True if wireless interface is connecting, otherwise False.""" """
Returns True if wireless interface is connecting, otherwise False.
"""
if self.wifi.connecting_thread: if self.wifi.connecting_thread:
return self.wifi.connecting_thread.is_connecting return self.wifi.connecting_thread.is_connecting
else: else:
@@ -1325,8 +1334,8 @@ class WirelessDaemon(dbus.service.Object, object):
"""Writes a particular wireless property to disk.""" """Writes a particular wireless property to disk."""
option = misc.sanitize_config(option) option = misc.sanitize_config(option)
if option.endswith("script"): if option.endswith("script"):
print('You cannot save script information to disk through ' + \ print('You cannot save script information to disk through the '
'the daemon.') 'daemon.')
return return
config = self.config config = self.config
cur_network = self.LastScan[nid] cur_network = self.LastScan[nid]
@@ -1376,18 +1385,18 @@ class WirelessDaemon(dbus.service.Object, object):
def DeleteWirelessNetwork(self, section): def DeleteWirelessNetwork(self, section):
"""Deletes a wireless network section.""" """Deletes a wireless network section."""
section = misc.to_unicode(section) section = misc.to_unicode(section)
print("Deleting wireless settings for %s (%s)" % \ print("Deleting wireless settings for %s (%s)" %
(self.config.get(section, 'essid'), str(section))) (self.config.get(section, 'essid'), str(section)))
self.config.remove_section(section) self.config.remove_section(section)
self.config.write() self.config.write()
@dbus.service.signal(dbus_interface='org.wicd.daemon.wireless', \ @dbus.service.signal(dbus_interface='org.wicd.daemon.wireless',
signature='') signature='')
def SendStartScanSignal(self): def SendStartScanSignal(self):
"""Emits a signal announcing a scan has started.""" """Emits a signal announcing a scan has started."""
self._scanning = True self._scanning = True
@dbus.service.signal(dbus_interface='org.wicd.daemon.wireless', \ @dbus.service.signal(dbus_interface='org.wicd.daemon.wireless',
signature='') signature='')
def SendEndScanSignal(self): def SendEndScanSignal(self):
"""Emits a signal announcing a scan has finished.""" """Emits a signal announcing a scan has finished."""
@@ -1395,10 +1404,11 @@ class WirelessDaemon(dbus.service.Object, object):
def _wireless_autoconnect(self, fresh=True): def _wireless_autoconnect(self, fresh=True):
"""Attempts to autoconnect to a wireless network.""" """Attempts to autoconnect to a wireless network."""
print("No wired connection present, attempting to autoconnect " + \ print("No wired connection present, attempting to autoconnect to "
"to wireless network") "wireless network")
if self.wifi.wireless_interface is None: if self.wifi.wireless_interface is None:
print('Autoconnect failed because wireless interface returned None') print('Autoconnect failed because wireless interface returned '
'None')
return return
if fresh: if fresh:
self.Scan(sync=True) self.Scan(sync=True)
@@ -1409,20 +1419,17 @@ class WirelessDaemon(dbus.service.Object, object):
print(network["essid"] + ' has profile') print(network["essid"] + ' has profile')
if bool(network.get('automatic')): if bool(network.get('automatic')):
if network.get('never'): if network.get('never'):
print(network["essid"],'marked never connect') print(f'{network["essid"]} marked never connect')
continue continue
else: else:
print(network["essid"],'has no never connect value') print(f'{network["essid"]} has no never connect value')
print('trying to automatically connect to...' + \ print(f'trying to automatically connect to... '
network["essid"]) f'{network["essid"]}')
self.ConnectWireless(x) self.ConnectWireless(x)
time.sleep(1) time.sleep(1)
return return
print("Unable to autoconnect, you'll have to manually connect") print("Unable to autoconnect, you'll have to manually connect")
###########################
###### Wired Daemon #######
###########################
class WiredDaemon(dbus.service.Object, object): class WiredDaemon(dbus.service.Object, object):
"""DBus interface for wired connection operations.""" """DBus interface for wired connection operations."""
@@ -1440,6 +1447,7 @@ class WiredDaemon(dbus.service.Object, object):
def get_debug_mode(self): def get_debug_mode(self):
"""Getter for debug_mode property.""" """Getter for debug_mode property."""
return self._debug_mode return self._debug_mode
def set_debug_mode(self, mode): def set_debug_mode(self, mode):
"""Setter for debug_mode property.""" """Setter for debug_mode property."""
self._debug_mode = mode self._debug_mode = mode
@@ -1492,8 +1500,8 @@ class WiredDaemon(dbus.service.Object, object):
if self.WiredNetwork: if self.WiredNetwork:
prop = misc.sanitize_config(prop) prop = misc.sanitize_config(prop)
if prop.endswith('script'): if prop.endswith('script'):
print('Setting script properties through the daemon' \ print('Setting script properties through the daemon is not '
+ ' is not permitted.') 'permitted.')
return False return False
self.WiredNetwork[prop] = misc.to_unicode(misc.Noneify(value)) self.WiredNetwork[prop] = misc.to_unicode(misc.Noneify(value))
return True return True
@@ -1562,7 +1570,8 @@ class WiredDaemon(dbus.service.Object, object):
self.wired.Disconnect() self.wired.Disconnect()
self.daemon.SetForcedDisconnect(False) self.daemon.SetForcedDisconnect(False)
self.UnsetWiredLastUsed() self.UnsetWiredLastUsed()
self.config.set(self._cur_wired_prof_name, "lastused", True, write=True) self.config.set(self._cur_wired_prof_name, "lastused", True,
write=True)
self.wired.Connect(self.WiredNetwork, debug=self.debug_mode) self.wired.Connect(self.WiredNetwork, debug=self.debug_mode)
self.daemon.UpdateState() self.daemon.UpdateState()
@@ -1576,9 +1585,9 @@ class WiredDaemon(dbus.service.Object, object):
if self.config.has_section(profilename): if self.config.has_section(profilename):
return False return False
for option in ["ip", "broadcast", "netmask", "gateway", "search_domain", for option in ["ip", "broadcast", "netmask", "gateway",
"dns_domain", "dns1", "dns2", "dns3", "beforescript", "search_domain", "dns_domain", "dns1", "dns2", "dns3",
"afterscript", "predisconnectscript", "beforescript", "afterscript", "predisconnectscript",
"postdisconnectscript", "encryption_enabled"]: "postdisconnectscript", "encryption_enabled"]:
self.config.set(profilename, option, None) self.config.set(profilename, option, None)
self.config.set(profilename, "default", default) self.config.set(profilename, "default", default)
@@ -1696,6 +1705,7 @@ class WiredDaemon(dbus.service.Object, object):
''' Returns a list of wireless interfaces on the system. ''' ''' Returns a list of wireless interfaces on the system. '''
return wnettools.GetWiredInterfaces() return wnettools.GetWiredInterfaces()
def usage(): def usage():
"""Print help screen.""" """Print help screen."""
print(""" print("""
@@ -1712,6 +1722,7 @@ Arguments:
\t-h\t--help\t\tPrint this help. \t-h\t--help\t\tPrint this help.
""" % (wpath.version + ' (bzr-r%s)' % wpath.revision)) """ % (wpath.version + ' (bzr-r%s)' % wpath.revision))
def daemonize(): def daemonize():
"""Disconnect from the controlling terminal. """Disconnect from the controlling terminal.
@@ -1730,7 +1741,8 @@ def daemonize():
if pid > 0: if pid > 0:
sys.exit(0) sys.exit(0)
except OSError as e: except OSError as e:
print("Fork #1 failed: %d (%s)" % (e.errno, e.strerror), file=sys.stderr) print("Fork #1 failed: %d (%s)" % (e.errno, e.strerror),
file=sys.stderr)
sys.exit(1) sys.exit(1)
# Decouple from parent environment to stop us from being a zombie. # Decouple from parent environment to stop us from being a zombie.
@@ -1752,7 +1764,8 @@ def daemonize():
os.umask(0) os.umask(0)
os.chdir('/') os.chdir('/')
except OSError as e: except OSError as e:
print("Fork #2 failed: %d (%s)" % (e.errno, e.strerror), file=sys.stderr) print("Fork #2 failed: %d (%s)" % (e.errno, e.strerror),
file=sys.stderr)
sys.exit(1) sys.exit(1)
sys.stdin.close() sys.stdin.close()
@@ -1787,9 +1800,12 @@ def main(argv):
# back up resolv.conf before we do anything else # back up resolv.conf before we do anything else
try: try:
backup_location = wpath.varlib + 'resolv.conf.orig' backup_location = wpath.varlib + 'resolv.conf.orig'
# Don't back up if the backup already exists, either as a regular file or a symlink # Don't back up if the backup already exists, either as a regular file
# The backup file should have been cleaned up by wicd, so perhaps it didn't exit cleanly... # or a symlink
if not os.path.exists(backup_location) and not os.path.islink(backup_location): # The backup file should have been cleaned up by wicd, so perhaps it
# didn't exit cleanly...
if (not os.path.exists(backup_location) and
not os.path.islink(backup_location)):
if os.path.islink('/etc/resolv.conf'): if os.path.islink('/etc/resolv.conf'):
dest = os.readlink('/etc/resolv.conf') dest = os.readlink('/etc/resolv.conf')
os.symlink(dest, backup_location) os.symlink(dest, backup_location)
@@ -1808,9 +1824,9 @@ def main(argv):
try: try:
opts, args = getopt.getopt(sys.argv[1:], 'fenoahkc', opts, args = getopt.getopt(sys.argv[1:], 'fenoahkc',
['help', 'no-daemon', 'no-poll', 'no-stderr', ['help', 'no-daemon', 'no-poll',
'no-stdout', 'no-autoconnect', 'kill', 'no-stderr', 'no-stdout', 'no-autoconnect',
'keep-connection']) 'kill', 'keep-connection'])
except getopt.GetoptError: except getopt.GetoptError:
# Print help information and exit # Print help information and exit
usage() usage()
@@ -1930,6 +1946,7 @@ def main(argv):
pass pass
daemon.DaemonClosing() daemon.DaemonClosing()
def on_exit(child_pid): def on_exit(child_pid):
"""Called when a SIGTERM is caught, kills monitor.py before exiting.""" """Called when a SIGTERM is caught, kills monitor.py before exiting."""
if child_pid: if child_pid:
@@ -1947,8 +1964,8 @@ def on_exit(child_pid):
if __name__ == '__main__': if __name__ == '__main__':
if os.getuid() != 0: if os.getuid() != 0:
print(("Root privileges are required for the daemon to run properly." + print("Root privileges are required for the daemon to run properly. "
" Exiting.")) "Exiting.")
sys.exit(1) sys.exit(1)
# No more needed since PyGObject 3.11, c.f. # No more needed since PyGObject 3.11, c.f.
# https://wiki.gnome.org/PyGObject/Threading # https://wiki.gnome.org/PyGObject/Threading

View File

@@ -31,29 +31,30 @@ class BaseWirelessInterface() -- Control a wireless network interface.
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
import os
import re
import random
import time
import dbus import dbus
import socket, fcntl import fcntl
import functools
import os
import random
import re
import shutil import shutil
from functools import cmp_to_key import socket
import time
from . import wpath from wicd import wpath
from . import misc from wicd import misc
from .misc import find_path from wicd.misc import find_path
# Regular expressions. # Regular expressions.
_re_mode = (re.I | re.M | re.S) _re_mode = (re.I | re.M | re.S)
essid_pattern = re.compile('.*ESSID:"?(.*?)".*\n', _re_mode) essid_pattern = re.compile('.*ESSID:"?(.*?)".*\n', _re_mode)
ap_mac_pattern = re.compile('.*Address: (.*?)\n', _re_mode) ap_mac_pattern = re.compile('.*Address: (.*?)\n', _re_mode)
channel_pattern = re.compile('.*Channel:?=? ?(\d+)', _re_mode) channel_pattern = re.compile(r'.*Channel:?=? ?(\d+)', _re_mode)
strength_pattern = re.compile('.*Quality:?=? ?(\d+)\s*/?\s*(\d*)', _re_mode) strength_pattern = re.compile(r'.*Quality:?=? ?(\d+)\s*/?\s*(\d*)', _re_mode)
altstrength_pattern = re.compile('.*Signal level:?=? ?(\d+)\s*/?\s*(\d*)', altstrength_pattern = re.compile(r'.*Signal level:?=? ?(\d+)\s*/?\s*(\d*)',
_re_mode) _re_mode)
signaldbm_pattern = re.compile('.*Signal level:?=? ?(-\d\d*)', _re_mode) signaldbm_pattern = re.compile(r'.*Signal level:?=? ?(-\d\d*)', _re_mode)
bitrates_pattern = re.compile('([\d\.]+)\s+\S+/s', _re_mode) bitrates_pattern = re.compile(r'([\d\.]+)\s+\S+/s', _re_mode)
mode_pattern = re.compile('.*Mode:([A-Za-z-]*?)\n', _re_mode) mode_pattern = re.compile('.*Mode:([A-Za-z-]*?)\n', _re_mode)
freq_pattern = re.compile('.*Frequency:(.*?)\n', _re_mode) freq_pattern = re.compile('.*Frequency:(.*?)\n', _re_mode)
wep_pattern = re.compile('.*Encryption key:(.*?)\n', _re_mode) wep_pattern = re.compile('.*Encryption key:(.*?)\n', _re_mode)
@@ -66,11 +67,11 @@ ip_up = re.compile(r'flags=[0.9]*<([^>]*)>', re.S)
ip_pattern = re.compile(r'inet [Aa]d?dr[^.]*:([^.]*\.[^.]*\.[^.]*\.[0-9]*)', ip_pattern = re.compile(r'inet [Aa]d?dr[^.]*:([^.]*\.[^.]*\.[^.]*\.[0-9]*)',
re.S) re.S)
ip_pattern1 = re.compile(r'inet ([^.]*\.[^.]*\.[^.]*\.[0-9]*)', re.S) ip_pattern1 = re.compile(r'inet ([^.]*\.[^.]*\.[^.]*\.[0-9]*)', re.S)
bssid_pattern = re.compile('.*[(Access Point)|(Cell)]: ' + \ bssid_pattern = re.compile('.*[(Access Point)|(Cell)]: '
'(([0-9A-Z]{2}:){5}[0-9A-Z]{2})', _re_mode) '(([0-9A-Z]{2}:){5}[0-9A-Z]{2})', _re_mode)
bitrate_pattern = re.compile('.*Bit Rate[=:](.*?/s)', _re_mode) bitrate_pattern = re.compile('.*Bit Rate[=:](.*?/s)', _re_mode)
opmode_pattern = re.compile('.*Mode:(.*?) ', _re_mode) opmode_pattern = re.compile('.*Mode:(.*?) ', _re_mode)
authmethods_pattern = re.compile('.*Authentication capabilities ' + \ authmethods_pattern = re.compile('.*Authentication capabilities '
':\n(.*?)Current', _re_mode) ':\n(.*?)Current', _re_mode)
# Regular expressions for wpa_cli output # Regular expressions for wpa_cli output
@@ -85,6 +86,9 @@ blacklist_norm = list(";`$!*|><&\\")
blacklist_strict_t = str.maketrans(dict.fromkeys(blacklist_strict, None)) blacklist_strict_t = str.maketrans(dict.fromkeys(blacklist_strict, None))
blacklist_norm_t = str.maketrans(dict.fromkeys(blacklist_norm, None)) blacklist_norm_t = str.maketrans(dict.fromkeys(blacklist_norm, None))
_cache = {}
def _sanitize_string(string): def _sanitize_string(string):
"""Sanitize string.""" """Sanitize string."""
if string: if string:
@@ -92,6 +96,7 @@ def _sanitize_string(string):
else: else:
return string return string
def _sanitize_string_strict(string): def _sanitize_string_strict(string):
"""Sanitize string in a stricter way.""" """Sanitize string in a stricter way."""
if string: if string:
@@ -99,7 +104,7 @@ def _sanitize_string_strict(string):
else: else:
return string return string
_cache = {}
def timedcache(duration=5): def timedcache(duration=5):
"""A caching decorator for use with wnettools methods. """A caching decorator for use with wnettools methods.
@@ -124,6 +129,7 @@ def timedcache(duration=5):
return _timedcache return _timedcache
def GetDefaultGateway(): def GetDefaultGateway():
"""Attempts to determine the default gateway by parsing route -n.""" """Attempts to determine the default gateway by parsing route -n."""
route_info = misc.Run("route -n") route_info = misc.Run("route -n")
@@ -142,6 +148,7 @@ def GetDefaultGateway():
print('couldn\'t retrieve default gateway from route -n') print('couldn\'t retrieve default gateway from route -n')
return gateway return gateway
def isWireless(devname): def isWireless(devname):
""" """
Classic-style wifi device classification using linux/wireless.h Classic-style wifi device classification using linux/wireless.h
@@ -167,6 +174,7 @@ def isWireless(devname):
sk.close() sk.close()
return we is not None return we is not None
def GetWirelessInterfaces(): def GetWirelessInterfaces():
"""Get available wireless interfaces. """Get available wireless interfaces.
@@ -177,21 +185,25 @@ def GetWirelessInterfaces():
""" """
dev_dir = '/sys/class/net/' dev_dir = '/sys/class/net/'
ifnames = [iface for iface in os.listdir(dev_dir) if isWireless(str(iface))] ifnames = [iface for iface in os.listdir(dev_dir)
if isWireless(str(iface))]
return ifnames return ifnames
def GetWiredInterfaces(): def GetWiredInterfaces():
"""Returns a list of wired interfaces on the system.""" """Returns a list of wired interfaces on the system."""
basedir = '/sys/class/net/' basedir = '/sys/class/net/'
return [iface for iface in os.listdir(basedir) return [iface for iface in os.listdir(basedir)
if os.path.isdir(basedir + iface) and not 'wireless' if os.path.isdir(basedir + iface) and
in os.listdir(basedir + iface) and 'wireless' not in os.listdir(basedir + iface) and
open(basedir + iface + "/type").readlines()[0].strip() == "1"] open(basedir + iface + "/type").readlines()[0].strip() == "1"]
def NeedsExternalCalls(): def NeedsExternalCalls():
"""Returns True if the backend needs to use an external program.""" """Returns True if the backend needs to use an external program."""
raise NotImplementedError raise NotImplementedError
def GetWpaSupplicantDrivers(): def GetWpaSupplicantDrivers():
"""Returns a list of all valid wpa_supplicant drivers.""" """Returns a list of all valid wpa_supplicant drivers."""
output = misc.Run(["wpa_supplicant", "-h"]) output = misc.Run(["wpa_supplicant", "-h"])
@@ -200,17 +212,20 @@ def GetWpaSupplicantDrivers():
except KeyError: except KeyError:
print("Warning: Couldn't get list of valid wpa_supplicant drivers") print("Warning: Couldn't get list of valid wpa_supplicant drivers")
return [""] return [""]
patt = re.compile("(\S+)\s+=.*") patt = re.compile(r"(\S+)\s+=.*")
drivers = patt.findall(output) or [""] drivers = patt.findall(output) or [""]
# We cannot use the "wired" driver for wireless interfaces. # We cannot use the "wired" driver for wireless interfaces.
if 'wired' in drivers: if 'wired' in drivers:
drivers.remove('wired') drivers.remove('wired')
return drivers return drivers
def IsValidWpaSuppDriver(driver): def IsValidWpaSuppDriver(driver):
"""Returns True if given string is a valid wpa_supplicant driver.""" """Returns True if given string is a valid wpa_supplicant driver."""
output = misc.Run(["wpa_supplicant", "-D%s" % driver, "-iolan19", output = misc.Run(["wpa_supplicant", "-D%s" % driver, "-iolan19",
"-c/etc/abcd%sdefzz.zconfz" % random.randint(1, 1000)]) "-c/etc/abcd%sdefzz.zconfz" % random.randint(1, 1000)])
return not "Unsupported driver" in output return "Unsupported driver" not in output
def neediface(default_response): def neediface(default_response):
"""A decorator for only running a method if self.iface is defined. """A decorator for only running a method if self.iface is defined.
@@ -297,7 +312,6 @@ class BaseInterface(object):
print("WARNING: No path found for %s" % program) print("WARNING: No path found for %s" % program)
return path return path
def _get_dhcp_command(self, flavor=None, hostname=None, staticdns=False): def _get_dhcp_command(self, flavor=None, hostname=None, staticdns=False):
"""Returns the correct DHCP client command. """Returns the correct DHCP client command.
@@ -328,36 +342,34 @@ class BaseInterface(object):
return (client, cmd) return (client, cmd)
# probably /var/lib/wicd/dhclient.conf with defaults # probably /var/lib/wicd/dhclient.conf with defaults
dhclient_conf_path = os.path.join( dhclient_conf_path = os.path.join(wpath.varlib, 'dhclient.conf')
wpath.varlib,
'dhclient.conf'
)
client_dict = { client_dict = {
"dhclient": "dhclient":
{'connect' : r"%(cmd)s -cf %(dhclientconf)s %(extra)s %(iface)s", {'connect': r"%(cmd)s -cf %(dhclientconf)s "
'connect_with_hostname' : r"%(cmd)s -cf %(dhclientconf)s %(extra)s %(iface)s", r"%(extra)s %(iface)s",
'connect_with_hostname': r"%(cmd)s -cf %(dhclientconf)s "
r"%(extra)s %(iface)s",
'release': r"%(cmd)s -r %(iface)s", 'release': r"%(cmd)s -r %(iface)s",
'id' : misc.DHCLIENT, 'id': misc.DHCLIENT},
},
"pump": "pump":
{'connect': r"%(cmd)s -i %(iface)s %(extra)s", {'connect': r"%(cmd)s -i %(iface)s %(extra)s",
'connect_with_hostname' : r"%(cmd)s -i %(iface)s -h %(hostname)s %(extra)s", 'connect_with_hostname': r"%(cmd)s -i %(iface)s -h "
r"%(hostname)s %(extra)s",
'release': r"%(cmd)s -r -i %(iface)s", 'release': r"%(cmd)s -r -i %(iface)s",
'id' : misc.PUMP, 'id': misc.PUMP},
},
"dhcpcd": "dhcpcd":
{'connect': r"%(cmd)s --noipv4ll %(extra)s %(iface)s", {'connect': r"%(cmd)s --noipv4ll %(extra)s %(iface)s",
'connect_with_hostname' : r"%(cmd)s -h %(hostname)s --noipv4ll %(extra)s %(iface)s ", 'connect_with_hostname': r"%(cmd)s -h %(hostname)s "
r"--noipv4ll %(extra)s %(iface)s ",
'release': r"%(cmd)s -k %(iface)s", 'release': r"%(cmd)s -k %(iface)s",
'id' : misc.DHCPCD, 'id': misc.DHCPCD},
},
"udhcpc": "udhcpc":
{'connect': r"%(cmd)s -n -i %(iface)s %(extra)s", {'connect': r"%(cmd)s -n -i %(iface)s %(extra)s",
'connect_with_hostname' : r"%(cmd)s -n -i %(iface)s -H %(hostname)s %(extra)s", 'connect_with_hostname': r"%(cmd)s -n -i %(iface)s -H "
r"%(hostname)s %(extra)s",
'release': r"killall -SIGUSR2 %(cmd)s", 'release': r"killall -SIGUSR2 %(cmd)s",
'id' : misc.UDHCPC, 'id': misc.UDHCPC},
},
} }
(client_name, cmd) = get_client_name(self.DHCP_CLIENT) (client_name, cmd) = get_client_name(self.DHCP_CLIENT)
@@ -366,21 +378,24 @@ class BaseInterface(object):
if client_name == "dhclient" and flavor: if client_name == "dhclient" and flavor:
if hostname: if hostname:
print('attempting to set hostname with dhclient') print('attempting to set hostname with dhclient')
print('using dhcpcd or another supported client may work better') print('using dhcpcd or another supported client may work '
'better')
dhclient_template = \ dhclient_template = open(os.path.
open(os.path.join(wpath.etc, 'dhclient.conf.template'), 'r') join(wpath.etc,
'dhclient.conf.template'), 'r')
output_conf = open(dhclient_conf_path, 'w') output_conf = open(dhclient_conf_path, 'w')
for line in dhclient_template.readlines(): for line in dhclient_template.readlines():
line = line.replace('# <WICDHOSTNAME>', 'send host-name "%s";' \ line = line.replace('# <WICDHOSTNAME>', 'send host-name '
% hostname) '"%s";' % hostname)
output_conf.write(line) output_conf.write(line)
output_conf.close() output_conf.close()
dhclient_template.close() dhclient_template.close()
else: else:
shutil.copy(os.path.join(wpath.etc, 'dhclient.conf.template'), \ shutil.copy(os.path.join(wpath.etc,
'dhclient.conf.template'),
dhclient_conf_path) dhclient_conf_path)
os.chmod(dhclient_conf_path, 0o644) os.chmod(dhclient_conf_path, 0o644)
@@ -398,21 +413,21 @@ class BaseInterface(object):
extra_args = "--nohook resolv.conf" extra_args = "--nohook resolv.conf"
if hostname: if hostname:
return client_dict[client_name]['connect_with_hostname'] % \ return (client_dict[client_name]['connect_with_hostname'] %
{"cmd": cmd, {"cmd": cmd,
"iface": self.iface, "iface": self.iface,
"hostname": hostname, "hostname": hostname,
'extra': extra_args, 'extra': extra_args,
'dhclientconf' : dhclient_conf_path } 'dhclientconf': dhclient_conf_path})
else: else:
return client_dict[client_name]['connect'] % \ return (client_dict[client_name]['connect'] %
{"cmd": cmd, {"cmd": cmd,
"iface": self.iface, "iface": self.iface,
'extra': extra_args, 'extra': extra_args,
'dhclientconf' : dhclient_conf_path } 'dhclientconf': dhclient_conf_path})
elif flavor == "release": elif flavor == "release":
return client_dict[client_name]['release'] % \ return client_dict[client_name]['release'] % {"cmd": cmd,
{"cmd": cmd, "iface": self.iface} "iface": self.iface}
else: else:
return client_dict[client_name]['id'] return client_dict[client_name]['id']
@@ -450,7 +465,7 @@ class BaseInterface(object):
""" """
self.dhclient_cmd = self._find_program_path("dhclient") self.dhclient_cmd = self._find_program_path("dhclient")
if self.dhclient_cmd != None: if self.dhclient_cmd is not None:
output = misc.Run(self.dhclient_cmd + " --version", output = misc.Run(self.dhclient_cmd + " --version",
include_stderr=True) include_stderr=True)
if '4.' in output: if '4.' in output:
@@ -685,8 +700,7 @@ class BaseInterface(object):
client_dict = {misc.DHCLIENT: self._parse_dhclient, client_dict = {misc.DHCLIENT: self._parse_dhclient,
misc.DHCPCD: self._parse_dhcpcd, misc.DHCPCD: self._parse_dhcpcd,
misc.PUMP: self._parse_pump, misc.PUMP: self._parse_pump,
misc.UDHCPC : self._parse_udhcpc, misc.UDHCPC: self._parse_udhcpc}
}
DHCP_CLIENT = self._get_dhcp_command() DHCP_CLIENT = self._get_dhcp_command()
if DHCP_CLIENT in client_dict: if DHCP_CLIENT in client_dict:
@@ -762,7 +776,8 @@ class BaseInterface(object):
print('Setting DNS : ' + dns) print('Setting DNS : ' + dns)
valid_dns_list.append("nameserver %s\n" % dns) valid_dns_list.append("nameserver %s\n" % dns)
else: else:
print('DNS IP %s is not a valid IP address, skipping' % dns) print('DNS IP %s is not a valid IP address, skipping' %
dns)
if valid_dns_list: if valid_dns_list:
resolv_params += ''.join(valid_dns_list) resolv_params += ''.join(valid_dns_list)
@@ -862,8 +877,8 @@ class BaseInterface(object):
try: try:
flags = open(flags_file, "r").read().strip() flags = open(flags_file, "r").read().strip()
except IOError: except IOError:
print("Could not open %s, using ifconfig to determine status" \ print("Could not open %s, using ifconfig to determine status" %
% flags_file) flags_file)
return self._slow_is_up(ifconfig) return self._slow_is_up(ifconfig)
return bool(int(flags, 16) & 1) return bool(int(flags, 16) & 1)
@@ -875,7 +890,6 @@ class BaseInterface(object):
print(cmd) print(cmd)
misc.Run(cmd) misc.Run(cmd)
def _slow_is_up(self, ifconfig=None): def _slow_is_up(self, ifconfig=None):
"""Determine if an interface is up using ifconfig.""" """Determine if an interface is up using ifconfig."""
if not ifconfig: if not ifconfig:
@@ -944,12 +958,13 @@ class BaseWiredInterface(BaseInterface):
elif link == 0: elif link == 0:
return False return False
except (IOError, ValueError, TypeError): except (IOError, ValueError, TypeError):
print('Error checking link using /sys/class/net/%s/carrier' \ print('Error checking link using /sys/class/net/%s/carrier' %
% self.iface) self.iface)
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]:
return self._mii_get_plugged_in() return self._mii_get_plugged_in()
else: else:
print(('Error: No way of checking for a wired connection. Make ' + print(('Error: No way of checking for a wired connection. Make ' +
@@ -971,10 +986,8 @@ class BaseWiredInterface(BaseInterface):
if self.verbose: if self.verbose:
print(cmd) print(cmd)
tool_data = misc.Run(cmd, include_stderr=True) tool_data = misc.Run(cmd, include_stderr=True)
if misc.RunRegex( if misc.RunRegex(re.compile('(Link detected: yes)',
re.compile('(Link detected: yes)', re.I | re.M | re.S), re.I | re.M | re.S), tool_data):
tool_data
):
return True return True
else: else:
return False return False
@@ -1015,6 +1028,7 @@ class BaseWiredInterface(BaseInterface):
print(cmd) print(cmd)
misc.Run(cmd) misc.Run(cmd)
class BaseWirelessInterface(BaseInterface): class BaseWirelessInterface(BaseInterface):
"""Control a wireless network interface.""" """Control a wireless network interface."""
def __init__(self, iface, verbose=False, wpa_driver='wext'): def __init__(self, iface, verbose=False, wpa_driver='wext'):
@@ -1095,7 +1109,8 @@ class BaseWirelessInterface(BaseInterface):
try: try:
ret = freq_dict[freq] ret = freq_dict[freq]
except KeyError: except KeyError:
print("Couldn't determine channel number for frequency:", str(freq)) print("Couldn't determine channel number for frequency:",
str(freq))
return ret return ret
@@ -1277,7 +1292,7 @@ class BaseWirelessInterface(BaseInterface):
wpa_pass_path = misc.find_path('wpa_passphrase') wpa_pass_path = misc.find_path('wpa_passphrase')
if not wpa_pass_path: if not wpa_pass_path:
return None return None
key_pattern = re.compile('network={.*?\spsk=(.*?)\n}.*', key_pattern = re.compile(r'network={.*?\spsk=(.*?)\n}.*',
re.I | re.M | re.S) re.I | re.M | re.S)
cmd = [wpa_pass_path, str(network['essid']), str(network['key'])] cmd = [wpa_pass_path, str(network['essid']), str(network['key'])]
if self.verbose: if self.verbose:
@@ -1318,11 +1333,11 @@ class BaseWirelessInterface(BaseInterface):
network -- dictionary containing network info network -- dictionary containing network info
""" """
if network.get('key') != None: if network.get('key') is not None:
try: try:
info = self._GetRalinkInfo()[network.get('bssid')] info = self._GetRalinkInfo()[network.get('bssid')]
except KeyError: except KeyError:
print("Could not find current network in iwpriv " + \ print("Could not find current network in iwpriv "
"get_site_survey results. Cannot authenticate.") "get_site_survey results. Cannot authenticate.")
return return
@@ -1360,8 +1375,10 @@ class BaseWirelessInterface(BaseInterface):
cmd = 'iwlist ' + self.iface + ' scan' cmd = 'iwlist ' + self.iface + ' scan'
# If there is a hidden essid then it was set earlier, with iwconfig wlan0 essid, # If there is a hidden essid then it was set earlier, with
# but on some drivers (iwlwifi, in my case) we have to pass it to iwlist scan. # iwconfig wlan0 essid,
# but on some drivers (iwlwifi, in my case) we have to pass it to
# iwlist scan.
essid = misc.Noneify(essid) essid = misc.Noneify(essid)
if essid is not None: if essid is not None:
print('Passing hidden essid to iwlist scan: ' + essid) print('Passing hidden essid to iwlist scan: ' + essid)
@@ -1436,7 +1453,7 @@ class BaseWirelessInterface(BaseInterface):
# Channel - For cards that don't have a channel number, # Channel - For cards that don't have a channel number,
# convert the frequency. # convert the frequency.
ap['channel'] = misc.RunRegex(channel_pattern, cell) ap['channel'] = misc.RunRegex(channel_pattern, cell)
if ap['channel'] == None: if ap['channel'] is None:
freq = misc.RunRegex(freq_pattern, cell) freq = misc.RunRegex(freq_pattern, cell)
ap['channel'] = self._FreqToChannel(freq) ap['channel'] = self._FreqToChannel(freq)
@@ -1445,7 +1462,10 @@ class BaseWirelessInterface(BaseInterface):
m = re.findall(bitrates_pattern, bitrates) m = re.findall(bitrates_pattern, bitrates)
if m: if m:
# numeric sort # numeric sort
ap['bitrates'] = sorted(m, key=cmp_to_key(lambda x, y: int(float(x) - float(y)))) ap['bitrates'] = sorted(m,
key=functools.
cmp_to_key(lambda x, y:
int(float(x) - float(y))))
else: else:
ap['bitrates'] = None ap['bitrates'] = None
@@ -1487,7 +1507,8 @@ class BaseWirelessInterface(BaseInterface):
# quality displayed or it isn't found) # quality displayed or it isn't found)
if misc.RunRegex(signaldbm_pattern, cell): if misc.RunRegex(signaldbm_pattern, cell):
ap['strength'] = misc.RunRegex(signaldbm_pattern, cell) ap['strength'] = misc.RunRegex(signaldbm_pattern, cell)
elif self.wpa_driver != RALINK_DRIVER: # This is already set for ralink # This is already set for ralink
elif self.wpa_driver != RALINK_DRIVER:
ap['strength'] = -1 ap['strength'] = -1
return ap return ap
@@ -1544,7 +1565,6 @@ class BaseWirelessInterface(BaseInterface):
print('wpa_supplicant authentication may have failed.') print('wpa_supplicant authentication may have failed.')
return False return False
def _ForceSupplicantScan(self): def _ForceSupplicantScan(self):
"""Force wpa_supplicant to rescan available networks. """Force wpa_supplicant to rescan available networks.
@@ -1634,7 +1654,8 @@ class BaseWirelessInterface(BaseInterface):
if strength in ['', None]: if strength in ['', None]:
try: try:
[(strength, max_strength)] = altstrength_pattern.findall(output) [(strength,
max_strength)] = altstrength_pattern.findall(output)
except ValueError: except ValueError:
# if the pattern was unable to match anything # if the pattern was unable to match anything
# we'll return 101, which will allow us to stay # we'll return 101, which will allow us to stay