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

attempting to migrate to python 3.x

This commit is contained in:
Guido Serra
2019-08-14 16:18:46 +02:00
parent 681beb13b1
commit 2a52b83583
27 changed files with 740 additions and 165 deletions

View File

@@ -31,7 +31,7 @@ import wicd.wpath as wpath
def fail(backend_name, reason):
""" Helper to warn the user about failure in loading backend. """
print("Failed to load backend %s: %s" % (backend_name, reason))
print(("Failed to load backend %s: %s" % (backend_name, reason)))
return True
@@ -80,7 +80,7 @@ class BackendManager(object):
def _load_backend(self, backend_name):
""" Imports a backend and returns the loaded module. """
print('trying to load backend %s' % backend_name)
print(('trying to load backend %s' % backend_name))
backend_path = os.path.join(self.backend_dir,
'be-' + backend_name + '.py')
if self._valid_backend_file(backend_path):
@@ -124,5 +124,5 @@ class BackendManager(object):
return None
self.__loaded_backend = backend
print('successfully loaded backend %s' % backend_name)
print(('successfully loaded backend %s' % backend_name))
return backend

View File

@@ -167,7 +167,7 @@ class Interface(BaseInterface):
result = fcntl.ioctl(self.sock.fileno(), SIOCGIFFLAGS, data)
except IOError as e:
if self.verbose:
print("SIOCGIFFLAGS failed: " + str(e))
print(("SIOCGIFFLAGS failed: " + str(e)))
return False
flags, = struct.unpack('H', result[16:18])
@@ -226,7 +226,7 @@ class WiredInterface(Interface, BaseWiredInterface):
fcntl.ioctl(self.sock.fileno(), SIOCETHTOOL, data)
except IOError as e:
if self.verbose:
print('SIOCETHTOOL failed: ' + str(e))
print(('SIOCETHTOOL failed: ' + str(e)))
return False
return bool(buff.tolist()[1])
@@ -246,7 +246,7 @@ class WiredInterface(Interface, BaseWiredInterface):
result = fcntl.ioctl(self.sock.fileno(), SIOCGMIIPHY, buff)
except IOError as e:
if self.verbose:
print('SIOCGMIIPHY failed: ' + str(e))
print(('SIOCGMIIPHY failed: ' + str(e)))
return False
reg = struct.unpack('16shhhh', result)[-1]
return bool(reg & 0x0004)
@@ -287,13 +287,13 @@ class WirelessInterface(Interface, BaseWirelessInterface):
try:
self.scan_iface = iwscan.WirelessInterface(self.iface)
except iwscan.error as e:
print("GetNetworks caught an exception: %s" % e)
print(("GetNetworks caught an exception: %s" % e))
return []
try:
results = self.scan_iface.Scan()
except iwscan.error as e:
print("ERROR: %s" % e)
print(("ERROR: %s" % e))
return []
return [_f for _f in [self._parse_ap(cell) for cell in results] if _f]
@@ -357,11 +357,11 @@ class WirelessInterface(Interface, BaseWirelessInterface):
try:
return wpactrl.WPACtrl(socket_loc)
except wpactrl.error as e:
print("Couldn't open ctrl_interface: %s" % e)
print(("Couldn't open ctrl_interface: %s" % e))
return None
else:
print("Couldn't find a wpa_supplicant ctrl_interface for iface %s" \
% self.iface)
print(("Couldn't find a wpa_supplicant ctrl_interface for iface %s" \
% self.iface))
return None
def ValidateAuthentication(self, auth_time):
@@ -406,8 +406,8 @@ class WirelessInterface(Interface, BaseWirelessInterface):
return False
if self.verbose:
print('wpa_supplicant ctrl_interface status query is %s' \
% str(status))
print(('wpa_supplicant ctrl_interface status query is %s' \
% str(status)))
try:
[result] = [l for l in status if l.startswith("wpa_state=")]
@@ -478,8 +478,8 @@ class WirelessInterface(Interface, BaseWirelessInterface):
auth_mode = 'WPA2PSK'
key_name = 'WPAPSK'
else:
print('Unknown AuthMode, can\'t complete ' + \
'connection process!')
print(('Unknown AuthMode, can\'t complete ' + \
'connection process!'))
return
cmd_list = []
@@ -506,7 +506,7 @@ class WirelessInterface(Interface, BaseWirelessInterface):
result = fcntl.ioctl(self.sock.fileno(), SIOCGIWAP, data)[16:]
except IOError as e:
if self.verbose:
print("SIOCGIWAP failed: " + str(e))
print(("SIOCGIWAP failed: " + str(e)))
return ""
raw_addr = struct.unpack("xxBBBBBB", result[:8])
return "%02X:%02X:%02X:%02X:%02X:%02X" % raw_addr
@@ -521,7 +521,7 @@ class WirelessInterface(Interface, BaseWirelessInterface):
result = fcntl.ioctl(self.sock.fileno(), SIOCGIWRATE, data)[16:]
except IOError as e:
if self.verbose:
print("SIOCGIWRATE failed: " + str(e))
print(("SIOCGIWRATE failed: " + str(e)))
return ""
f, e, x, x = struct.unpack(fmt, result[:size])
return "%s %s" % ((f / 1000000), 'Mb/s')
@@ -564,7 +564,7 @@ class WirelessInterface(Interface, BaseWirelessInterface):
result = fcntl.ioctl(self.sock.fileno(), SIOCGIWRANGE, iwfreq)
except IOError as e:
if self.verbose:
print("SIOCGIWRANGE failed: " + str(e))
print(("SIOCGIWRANGE failed: " + str(e)))
return None
# This defines the iwfreq struct, used to get signal strength.
fmt = "iiihb6ii4B4Bi32i2i2i2i2i3h8h2b2bhi8i2b3h2i2ihB17x" + 32 * "ihbb"

View File

@@ -62,7 +62,7 @@ class ConfigManager(RawConfigParser):
try:
self.read(path)
except ParsingError as p:
print("Could not start wicd: %s" % p.message)
print(("Could not start wicd: %s" % p.message))
sys.exit(1)
def __repr__(self):
@@ -125,15 +125,15 @@ class ConfigManager(RawConfigParser):
if option in ['apsk', 'password', 'identity', \
'private_key', 'private_key_passwd', \
'key', 'passphrase']:
print(''.join(['found ', option, \
' in configuration *****']))
print((''.join(['found ', option, \
' in configuration *****'])))
else:
print(''.join(['found ', option, ' in configuration ',
str(ret)]))
print((''.join(['found ', option, ' in configuration ',
str(ret)])))
else: # Use the default, unless no default was provided
if default != "__None__":
print('did not find %s in configuration, setting default %s' \
% (option, str(default)))
print(('did not find %s in configuration, setting default %s' \
% (option, str(default))))
self.set(section, option, str(default), write=True)
ret = default
else:

View File

@@ -38,7 +38,7 @@ import socket
from wicd.translations import _
# wicd imports
import wpath
from . import wpath
# Connection state constants
NOT_CONNECTED = 0
@@ -155,7 +155,7 @@ def Run(cmd, include_stderr=False, return_pipe=False,
f = Popen(cmd, shell=False, stdout=PIPE, stdin=std_in, stderr=err,
close_fds=fds, cwd='/', env=tmpenv)
except OSError as e:
print("Running command %s failed: %s" % (str(cmd), str(e)))
print(("Running command %s failed: %s" % (str(cmd), str(e))))
return ""
if return_obj:
@@ -252,10 +252,10 @@ def ExecuteScript(script, verbose=False, extra_parameters=()):
# escape script name
script = quote(script)
if verbose:
print("Executing %s with params %s" % (script, params))
print(("Executing %s with params %s" % (script, params)))
ret = call('%s %s > /dev/null 2>&1' % (script, params), shell=True)
if verbose:
print("%s returned %s" % (script, ret))
print(("%s returned %s" % (script, ret)))
def ReadFile(filename):
""" read in a file and return it's contents as a string """
@@ -322,7 +322,7 @@ def ParseEncryption(network):
if rep_val:
line = line.replace("$_%s" % cur_val, str(rep_val))
else:
print("Ignoring template line: '%s'" % line)
print(("Ignoring template line: '%s'" % line))
else:
print("Weird parsing error occurred")
config_file = ''.join([config_file, line])
@@ -391,7 +391,7 @@ def _parse_enc_template(enctype):
try:
f = open(os.path.join(wpath.encryption, enctype), "r")
except IOError:
print("Failed to open template file %s" % enctype)
print(("Failed to open template file %s" % enctype))
return None
cur_type = {}
@@ -408,7 +408,7 @@ def _parse_enc_template(enctype):
cur_type["required"] = __parse_field_ent(parse_ent(line, "require"))
if not cur_type["required"]:
# 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
elif line.startswith("optional"):
cur_type["optional"] = __parse_field_ent(parse_ent(line,
@@ -416,7 +416,7 @@ def _parse_enc_template(enctype):
field_type="optional")
if not cur_type["optional"]:
# 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
elif line.startswith("protected"):
cur_type["protected"] = __parse_field_ent(
@@ -425,17 +425,17 @@ def _parse_enc_template(enctype):
)
if not cur_type["protected"]:
# 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
elif line.startswith("----"):
# We're done.
break
f.close()
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
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
else:
return cur_type

View File

@@ -56,7 +56,7 @@ def diewithdbus(func):
self.__lost_dbus_count = 0
return ret
except DBusException as e:
print("Caught exception %s" % str(e))
print(("Caught exception %s" % str(e)))
if not hasattr(self, "__lost_dbus_count"):
self.__lost_dbus_count = 0
if self.__lost_dbus_count > 3:
@@ -188,7 +188,7 @@ class ConnectionStatus(object):
# If we haven't gotten any signal 4 runs in a row (12 seconds),
# try to reconnect.
self.connection_lost_counter += 1
print(self.connection_lost_counter)
print((self.connection_lost_counter))
if self.connection_lost_counter >= 4 and daemon.GetAutoReconnect():
wireless.DisconnectWireless()
self.connection_lost_counter = 0
@@ -364,8 +364,8 @@ class ConnectionStatus(object):
# before we reconnect
print('Disconnecting from network')
wireless.DisconnectWireless()
print('Trying to reconnect to last used wireless ' + \
'network')
print(('Trying to reconnect to last used wireless ' + \
'network'))
wireless.ConnectWireless(cur_net_id)
else:
daemon.AutoConnect(True, reply_handler=reply_handle,

View File

@@ -51,7 +51,7 @@ from signal import SIGTERM
# wicd imports
from . import misc
import wpath
from . import wpath
from .backend import BackendManager
from .translations import _
@@ -125,7 +125,7 @@ def expand_script_macros(script, msg, bssid, essid):
macro = match.group(1).lower()
if macro in macro_dict:
return macro_dict[macro]
print('Warning: found illegal macro %s in %s script' % (macro, msg))
print(('Warning: found illegal macro %s in %s script' % (macro, msg)))
return match.group()
macro_dict = { 'script' : msg,
@@ -133,7 +133,7 @@ def expand_script_macros(script, msg, bssid, essid):
'essid' : essid }
regex = re.compile(r'%\{([a-zA-Z0-9]+)\}')
expanded = regex.sub(repl, script)
print("Expanded '%s' to '%s'" % (script, expanded))
print(("Expanded '%s' to '%s'" % (script, expanded)))
return expanded
@@ -430,7 +430,7 @@ class ConnectThread(threading.Thread):
"""
if script:
print('Executing %s script' % (msg))
print(('Executing %s script' % (msg)))
misc.ExecuteScript(expand_script_macros(script, msg, bssid, essid),
self.debug)
@@ -446,7 +446,7 @@ class ConnectThread(threading.Thread):
""" Set the broadcast address for the given interface. """
if not self.network.get('broadcast') == None:
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'])
@abortable
@@ -458,10 +458,10 @@ class ConnectThread(threading.Thread):
"""
if self.network.get('ip'):
self.SetStatus('setting_static_ip')
print('Setting static IP : ' + self.network['ip'])
print(('Setting static IP : ' + self.network['ip']))
iface.SetAddress(self.network['ip'], self.network['netmask'])
if self.network.get('gateway'):
print('Setting default gateway : ' + self.network['gateway'])
print(('Setting default gateway : ' + self.network['gateway']))
iface.SetDefaultRoute(self.network['gateway'])
else:
# Run dhcp...
@@ -472,7 +472,7 @@ class ConnectThread(threading.Thread):
self.network['dhcphostname'] = os.uname()[1]
if self.network['usedhcphostname']:
hname = self.network['dhcphostname']
print("Running DHCP with hostname", hname)
print(("Running DHCP with hostname", hname))
else:
hname = None
print("Running DHCP with NO hostname")
@@ -657,7 +657,7 @@ class Wireless(Controller):
# Note: this does not always work, sometimes we have to pass it with "iwlist wlan0 scan essid -- XXXXX"
essid = misc.Noneify(essid)
if essid is not None:
print('Setting hidden essid ' + essid)
print(('Setting hidden essid ' + essid))
wiface.SetEssid(essid)
# sleep for a bit; scanning to fast will result in nothing
time.sleep(1)
@@ -843,7 +843,7 @@ class Wireless(Controller):
action = 'block'
for t in types:
cmd = ['rfkill', action, t]
print("rfkill: %sing %s" % (action, t))
print(("rfkill: %sing %s" % (action, t)))
misc.Run(cmd)
return True
except Exception as e:
@@ -982,7 +982,7 @@ class WirelessConnectThread(ConnectThread):
if self.network.get('enctype'):
self.SetStatus('validating_authentication')
if not wiface.ValidateAuthentication(time.time()):
print("connect result is %s" % self.connect_result)
print(("connect result is %s" % self.connect_result))
if not self.connect_result or self.connect_result == 'failed':
self.abort_connection('bad_pass')
@@ -1004,7 +1004,7 @@ class WirelessConnectThread(ConnectThread):
self.SetStatus('done')
print('Connecting thread exiting.')
if self.debug:
print("IP Address is: " + str(wiface.GetIP()))
print(("IP Address is: " + str(wiface.GetIP())))
self.connect_result = "success"
self.is_connecting = False
@@ -1021,7 +1021,7 @@ class WirelessConnectThread(ConnectThread):
self.SetStatus('verifying_association')
print("Verifying AP association...")
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'])
if retcode == 0:
print("Successfully associated.")
@@ -1051,7 +1051,7 @@ class WirelessConnectThread(ConnectThread):
# Check to see if we need to generate a PSK (only for non-ralink
# cards).
if self.debug:
print("enctype is %s" % self.network.get('enctype'))
print(("enctype is %s" % self.network.get('enctype')))
if self.network.get('key') and \
'wpa' in str(self.network.get('enctype')):
self.SetStatus('generating_psk')
@@ -1060,9 +1060,9 @@ class WirelessConnectThread(ConnectThread):
if not self.network.get('psk'):
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 ' + \
'developers!')
'developers!'))
# Generate the wpa_supplicant file...
if self.network.get('enctype'):
self.SetStatus('generating_wpa_config')
@@ -1249,7 +1249,7 @@ class WiredConnectThread(ConnectThread):
self.SetStatus('done')
print('Connecting thread exiting.')
if self.debug:
print("IP Address is: " + str(liface.GetIP()))
print(("IP Address is: " + str(liface.GetIP())))
self.connect_result = "success"
self.is_connecting = False

View File

@@ -21,7 +21,7 @@
#
import locale
import os
import wpath
from . import wpath
import gettext
@@ -45,7 +45,7 @@ def get_gettext():
'LC_ALL', 'LANG',
'LANGUAGE'))
except ValueError as e:
print(str(e))
print((str(e)))
print("Default locale unavailable, falling back to en_US")
if (lc):
langs += [lc]

View File

@@ -35,7 +35,6 @@ import os
import re
import random
import time
from string import maketrans, translate
import dbus
import socket, fcntl
import shutil
@@ -81,19 +80,18 @@ NONE_DRIVER = 'none'
blacklist_strict = '!"#$%&\'()*+,./:;<=>?@[\\]^`{|}~ '
blacklist_norm = ";`$!*|><&\\"
blank_trans = maketrans("", "")
def _sanitize_string(string):
""" Sanitize string. """
if string:
return translate(str(string), blank_trans, blacklist_norm)
return str(string).translate(blacklist_norm)
else:
return string
def _sanitize_string_strict(string):
""" Sanitize string in a stricter way. """
if string:
return translate(str(string), blank_trans, blacklist_strict)
return str(string).translate(blacklist_strict)
else:
return string