fix traceback handling

fix struc and sha1 usage (use bytes instead of string)
This commit is contained in:
Yann Leboulanger 2013-01-05 00:03:36 +01:00
parent 89540b0c2e
commit e03b3c35b6
24 changed files with 107 additions and 101 deletions

View File

@ -508,7 +508,7 @@ if dbus_support.supported:
def prefs_store(self):
try:
gajim.interface.save_config()
except Exception as e:
except Exception:
return DBUS_BOOLEAN(False)
return DBUS_BOOLEAN(True)

View File

@ -218,7 +218,7 @@ class TimeResultReceivedEvent(nec.NetworkIncomingEvent, HelperEvent):
try:
t = datetime.datetime.strptime(utc_time, '%Y-%m-%dT%H:%M:%SZ')
except ValueError as e:
except ValueError:
try:
t = datetime.datetime.strptime(utc_time,
'%Y-%m-%dT%H:%M:%S.%fZ')

View File

@ -36,7 +36,7 @@ try:
import common.gajim
except ImportError as e:
if __name__ != "__main__":
raise ImportError(e)
raise ImportError(str(e))
class XMPPEntity(object):
"""

View File

@ -79,7 +79,7 @@ class GlobalEventsDispatcher(object):
if event_name in self.handlers:
try:
self.handlers[event_name].remove((priority, handler))
except ValueError as error:
except ValueError:
log.warn('''Function (%s) with priority "%s" never registered
as handler of event "%s". Couldn\'t remove. Error: %s'''
%(handler, priority, event_name, error))
@ -94,7 +94,7 @@ class GlobalEventsDispatcher(object):
return True
except NodeProcessed:
node_processed = True
except Exception as e:
except Exception:
log.error('Error while running an even handler: %s' % \
handler)
traceback.print_exc()

View File

@ -915,7 +915,8 @@ def get_auth_sha(sid, initiator, target):
"""
Return sha of sid + initiator + target used for proxy auth
"""
return hashlib.sha1("%s%s%s" % (sid, initiator, target)).hexdigest()
return hashlib.sha1(("%s%s%s" % (sid, initiator, target)).encode('utf-8')).\
hexdigest()
def remove_invalid_xml_chars(string):
if string:
@ -1545,9 +1546,9 @@ def _get_img_proxy(attrs, proxy):
alt = attrs.get('alt', '')
if alt:
alt += '\n'
if ex[0] == pycurl.E_FILESIZE_EXCEEDED:
if ex.errno == pycurl.E_FILESIZE_EXCEEDED:
alt += _('Image is too big')
elif ex[0] == pycurl.E_OPERATION_TIMEOUTED:
elif ex.errno == pycurl.E_OPERATION_TIMEOUTED:
alt += _('Timeout loading image')
else:
alt += _('Error loading image')

View File

@ -68,7 +68,7 @@ try:
rootwindow = libX11.XDefaultRootWindow(dpy_p)
xss_available = True
except OSError as e:
except OSError:
# Logging?
xss_available = False

View File

@ -95,8 +95,8 @@ class JingleFileTransfer(JingleContent):
if gajim.contacts.is_gc_contact(session.connection.name,
session.peerjid):
roomjid = session.peerjid.split('/')[0]
dstaddr = hashlib.sha1('%s%s%s' % (self.file_props['sid'],
session.ourjid, roomjid)).hexdigest()
dstaddr = hashlib.sha1(('%s%s%s' % (self.file_props['sid'],
session.ourjid, roomjid)).encode('utf-8')).hexdigest()
self.file_props.dstaddr = dstaddr
self.state = STATE_NOT_STARTED
self.states = {STATE_INITIALIZED : StateInitialized(self),

View File

@ -105,13 +105,13 @@ class JingleRTPContent(JingleContent):
try:
bin = gst.parse_bin_from_description(pipeline, True)
return bin
except GError as error_str:
except GError as e:
gajim.nec.push_incoming_event(InformationEvent(None,
conn=self.session.connection, level='error',
pri_txt=_('%s configuration error') % text.capitalize(),
sec_txt=_("Couldn't setup %s. Check your configuration.\n\n"
"Pipeline was:\n%s\n\nError was:\n%s") % (text, pipeline,
error_str)))
str(e))))
raise JingleContentSetupException
def add_remote_candidates(self, candidates):

View File

@ -256,7 +256,7 @@ class Logger:
self.cur.execute('INSERT INTO jids (jid, type) VALUES (?, ?)', (jid,
typ))
self.con.commit()
except sqlite.IntegrityError as e:
except sqlite.IntegrityError:
# Jid already in DB, maybe added by another instance. re-read DB
self.get_jids_already_in_db()
return self.get_jid_id(jid, typestr)
@ -580,7 +580,7 @@ class Logger:
"""
try:
self.get_jid_id(jid)
except exceptions.PysqliteOperationalError as e:
except exceptions.PysqliteOperationalError:
# Error trying to create a new jid_id. This means there is no log
return []
where_sql, jid_tuple = self._build_contact_where(account, jid)
@ -624,7 +624,7 @@ class Logger:
"""
try:
self.get_jid_id(jid)
except exceptions.PysqliteOperationalError as e:
except exceptions.PysqliteOperationalError:
# Error trying to create a new jid_id. This means there is no log
return []
where_sql, jid_tuple = self._build_contact_where(account, jid)
@ -653,7 +653,7 @@ class Logger:
"""
try:
self.get_jid_id(jid)
except exceptions.PysqliteOperationalError as e:
except exceptions.PysqliteOperationalError:
# Error trying to create a new jid_id. This means there is no log
return []
@ -694,7 +694,7 @@ class Logger:
"""
try:
self.get_jid_id(jid)
except exceptions.PysqliteOperationalError as e:
except exceptions.PysqliteOperationalError:
# Error trying to create a new jid_id. This means there is no log
return []
days_with_logs = []
@ -736,7 +736,7 @@ class Logger:
else:
try:
jid_id = self.get_jid_id(jid, 'ROOM')
except exceptions.PysqliteOperationalError as e:
except exceptions.PysqliteOperationalError:
# Error trying to create a new jid_id. This means there is no log
return None
where_sql = 'jid_id = ?'
@ -762,7 +762,7 @@ class Logger:
"""
try:
jid_id = self.get_jid_id(jid, 'ROOM')
except exceptions.PysqliteOperationalError as e:
except exceptions.PysqliteOperationalError:
# Error trying to create a new jid_id. This means there is no log
return None
where_sql = 'jid_id = %s' % jid_id
@ -802,7 +802,7 @@ class Logger:
for user in family:
try:
jid_id = self.get_jid_id(user['jid'])
except exceptions.PysqliteOperationalError as e:
except exceptions.PysqliteOperationalError:
continue
where_sql += 'jid_id = ?'
jid_tuple += (jid_id,)

View File

@ -644,7 +644,7 @@ class OptionsParser:
'''
)
con.commit()
except sqlite.OperationalError as e:
except sqlite.OperationalError:
pass
con.close()
gajim.config.set('version', '0.11.4.4')

View File

@ -310,7 +310,7 @@ class HostTester(Socks5, IdleObject):
# read auth response
if buff is None or len(buff) != 2:
return None
version, method = struct.unpack('!BB', buff[:2])
version, method = struct.unpack('!BB', buff[:2].encode('utf-8'))
if version != 0x05 or method == 0xff:
self.pollend()
return
@ -334,7 +334,7 @@ class HostTester(Socks5, IdleObject):
self._send = self._sock.send
self._recv = self._sock.recv
except Exception as ee:
errnum = ee[0]
errnum = ee.errno
# 56 is for freebsd
if errnum in (errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK):
# still trying to connect
@ -431,7 +431,7 @@ class ReceiverTester(Socks5, IdleObject):
# read auth response
if buff is None or len(buff) != 2:
return None
version, method = struct.unpack('!BB', buff[:2])
version, method = struct.unpack('!BB', buff[:2].encode('utf-8'))
if version != 0x05 or method == 0xff:
self.pollend()
return
@ -443,7 +443,7 @@ class ReceiverTester(Socks5, IdleObject):
# read connect response
if buff is None or len(buff) < 2:
return None
version, reply = struct.unpack('!BB', buff[:2])
version, reply = struct.unpack('!BB', buff[:2].encode('utf-8'))
if version != 0x05 or reply != 0x00:
self.pollend()
return

View File

@ -464,7 +464,7 @@ class Socks5:
self._server = ai[4]
break
except socket.error as e:
if not isinstance(e, basestring) and e[0] == EINPROGRESS:
if e.errno == EINPROGRESS:
break
# for all other errors, we try other addresses
continue
@ -482,7 +482,7 @@ class Socks5:
self._send=self._sock.send
self._recv=self._sock.recv
except Exception as ee:
errnum = ee[0]
errnum = ee.errno
self.connect_timeout += 1
if errnum == 111 or self.connect_timeout > 1000:
self.queue._connection_refused(self.streamhost, self.file_props,
@ -581,7 +581,7 @@ class Socks5:
"""
received = ''
try:
add = self._recv(64)
add = self._recv(64).decode('utf-8')
except (OpenSSL.SSL.WantReadError, OpenSSL.SSL.WantWriteError,
OpenSSL.SSL.WantX509LookupError) as e:
log.info('SSL rehandshake request : ' + repr(e))
@ -603,7 +603,7 @@ class Socks5:
OpenSSL.SSL.WantX509LookupError) as e:
log.info('SSL rehandshake request :' + repr(e))
raise e
except Exception as e:
except Exception:
self.disconnect()
return len(raw_data)
@ -614,7 +614,7 @@ class Socks5:
else:
try:
self.open_file_for_reading()
except IOError as e:
except IOError:
self.state = 8 # end connection
self.disconnect()
self.file_props.error = -7 # unable to read from file
@ -629,7 +629,7 @@ class Socks5:
log.info('SSL rehandshake request :' + repr(e))
raise e
except Exception as e:
if e.args[0] not in (EINTR, ENOBUFS, EWOULDBLOCK):
if e.errno not in (EINTR, ENOBUFS, EWOULDBLOCK):
# peer stopped reading
self.state = 8 # end connection
self.disconnect()
@ -671,7 +671,7 @@ class Socks5:
if self.remaining_buff != '':
try:
fd = self.get_fd()
except IOError as e:
except IOError:
self.disconnect(False)
self.file_props.error = -6 # file system error
return 0
@ -692,12 +692,12 @@ class Socks5:
else:
try:
fd = self.get_fd()
except IOError as e:
except IOError:
self.disconnect(False)
self.file_props.error = -6 # file system error
return 0
try:
buff = self._recv(MAX_BUFF_LEN)
buff = self._recv(MAX_BUFF_LEN).decode('utf-8')
except (OpenSSL.SSL.WantReadError, OpenSSL.SSL.WantWriteError,
OpenSSL.SSL.WantX509LookupError) as e:
log.info('SSL rehandshake request :' + repr(e))
@ -718,7 +718,7 @@ class Socks5:
return 0
try:
fd.write(buff)
except IOError as e:
except IOError:
self.rem_fd(fd)
self.disconnect()
self.file_props.error = -6 # file system error
@ -780,9 +780,9 @@ class Socks5:
"""
auth_mechanisms = []
try:
num_auth = struct.unpack('!xB', buff[:2])[0]
num_auth = struct.unpack('!xB', buff[:2].encode('utf-8'))[0]
for i in list(range(num_auth)):
mechanism, = struct.unpack('!B', buff[1 + i])
mechanism, = struct.unpack('!B', buff[1 + i].encode('utf-8'))
auth_mechanisms.append(mechanism)
except Exception:
return None
@ -799,8 +799,8 @@ class Socks5:
Connect request by domain name
"""
buff = struct.pack('!BBBBB%dsBB' % len(self.host),
0x05, 0x01, 0x00, 0x03, len(self.host), self.host, self.port >> 8,
self.port & 0xff)
0x05, 0x01, 0x00, 0x03, len(self.host), self.host.encode('utf-8'),
self.port >> 8, self.port & 0xff)
return buff
def _get_request_buff(self, msg, command = 0x01):
@ -809,27 +809,30 @@ class Socks5:
0096)
"""
buff = struct.pack('!BBBBB%dsBB' % len(msg),
0x05, command, 0x00, 0x03, len(msg), msg, 0, 0)
0x05, command, 0x00, 0x03, len(msg), msg.encode('utf-8'), 0, 0)
return buff
def _parse_request_buff(self, buff):
try: # don't trust on what comes from the outside
req_type, host_type, = struct.unpack('!xBxB', buff[:4])
req_type, host_type, = struct.unpack('!xBxB', buff[:4].encode(
'utf-8'))
if host_type == 0x01:
host_arr = struct.unpack('!iiii', buff[4:8])
host_arr = struct.unpack('!iiii', buff[4:8].encode('utf-8'))
host, = '.'.join(str(s) for s in host_arr)
host_len = len(host)
elif host_type == 0x03:
host_len, = struct.unpack('!B', buff[4])
host, = struct.unpack('!%ds' % host_len, buff[5:5 + host_len])
host_len, = struct.unpack('!B', buff[4].encode('utf-8'))
host, = struct.unpack('!%ds' % host_len, buff[5:5 + host_len].\
encode('utf-8'))
portlen = len(buff[host_len + 5:])
if portlen == 1:
port, = struct.unpack('!B', buff[host_len + 5])
port, = struct.unpack('!B', buff[host_len + 5].encode('utf-8'))
elif portlen == 2:
port, = struct.unpack('!H', buff[host_len + 5:])
port, = struct.unpack('!H', buff[host_len + 5:].encode('utf-8'))
# file data, comes with auth message (Gaim bug)
else:
port, = struct.unpack('!H', buff[host_len + 5: host_len + 7])
port, = struct.unpack('!H', buff[host_len + 5: host_len + 7].\
encode('utf-8'))
self.remaining_buff = buff[host_len + 7:]
except Exception:
return (None, None, None)
@ -840,13 +843,13 @@ class Socks5:
Connect response: version, auth method
"""
try:
buff = self._recv()
buff = self._recv().decode('utf-8')
except (SSL.WantReadError, SSL.WantWriteError,
SSL.WantX509LookupError) as e:
log.info("SSL rehandshake request : " + repr(e))
raise e
try:
version, method = struct.unpack('!BB', buff)
version, method = struct.unpack('!BB', buff.encode('utf-8'))
except Exception:
version, method = None, None
if version != 0x05 or method == 0xff:
@ -864,8 +867,8 @@ class Socks5:
"""
Get sha of sid + Initiator jid + Target jid
"""
return hashlib.sha1('%s%s%s' % (self.sid, self.initiator,
self.target)).hexdigest()
return hashlib.sha1(('%s%s%s' % (self.sid, self.initiator,
self.target)).encode('utf-8')).hexdigest()
class Socks5Sender(IdleObject):
@ -1151,7 +1154,7 @@ class Socks5Client(Socks5):
if self.state == 2: # read auth response
if buff is None or len(buff) != 2:
return None
version, method = struct.unpack('!BB', buff[:2])
version, method = struct.unpack('!BB', buff[:2].encode('utf-8'))
if version != 0x05 or method == 0xff:
self.disconnect()
elif self.state == 4: # get approve of our request
@ -1160,18 +1163,23 @@ class Socks5Client(Socks5):
sub_buff = buff[:4]
if len(sub_buff) < 4:
return None
version, address_type = struct.unpack('!BxxB', buff[:4])
version, address_type = struct.unpack('!BxxB', buff[:4].encode(
'utf-8'))
addrlen = 0
if address_type == 0x03:
addrlen = ord(buff[4])
address = struct.unpack('!%ds' % addrlen, buff[5:addrlen + 5])
address = struct.unpack('!%ds' % addrlen, buff[5:addrlen + 5].\
encode('utf-8'))
portlen = len(buff[addrlen + 5:])
if portlen == 1:
port, = struct.unpack('!B', buff[addrlen + 5])
port, = struct.unpack('!B', buff[addrlen + 5].encode(
'utf-8'))
elif portlen == 2:
port, = struct.unpack('!H', buff[addrlen + 5:])
port, = struct.unpack('!H', buff[addrlen + 5:].encode(
'utf-8'))
else: # Gaim bug :)
port, = struct.unpack('!H', buff[addrlen + 5:addrlen + 7])
port, = struct.unpack('!H', buff[addrlen + 5:addrlen + 7].\
encode('utf-8'))
self.remaining_buff = buff[addrlen + 7:]
self.state = 5 # for senders: init file_props and send '\n'
if self.queue.on_success:
@ -1347,7 +1355,7 @@ class Socks5Listener(IdleObject):
self._serv = OpenSSL.SSL.Connection(
jingle_xtls.get_context('server'), self._serv)
except socket.error as e:
if e.args[0] == EAFNOSUPPORT:
if e.errno == EAFNOSUPPORT:
self.ai = None
continue
raise

View File

@ -357,8 +357,8 @@ class P2PConnection(IdleObject, PlugIn):
self.ais = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
socket.SOCK_STREAM)
except socket.gaierror as e:
log.info('Lookup failure for %s: %s[%s]', host, e[1],
repr(e[0]), exc_info=True)
log.info('Lookup failure for %s: %s', host, str(e),
exc_info=True)
else:
self.connect_to_next_ip()
@ -449,7 +449,8 @@ class P2PConnection(IdleObject, PlugIn):
self._sock.connect(self._server)
self._sock.setblocking(False)
except Exception as ee:
(errnum, errstr) = ee
errnum = ee.errno
errstr = ee.strerror
errors = (errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK)
if 'WSAEINVAL' in errno.__dict__:
errors += (errno.WSAEINVAL,)
@ -489,8 +490,7 @@ class P2PConnection(IdleObject, PlugIn):
# get as many bites, as possible, but not more than RECV_BUFSIZE
received = self._sock.recv(MAX_BUFF_LEN)
except Exception as e:
if len(e.args) > 0 and isinstance(e.args[0], int):
errnum = e[0]
errnum = e.errno
# "received" will be empty anyhow
if errnum == socket.SSL_ERROR_WANT_READ:
pass
@ -560,7 +560,7 @@ class P2PConnection(IdleObject, PlugIn):
self._on_send()
except socket.error as e:
if e[0] == socket.SSL_ERROR_WANT_WRITE:
if e.errno == socket.SSL_ERROR_WANT_WRITE:
return True
if self.state < 0:
self.disconnect()

View File

@ -22,7 +22,7 @@ log = logging.getLogger('gajim.c.z.zeroconf_avahi')
try:
import dbus.exceptions
except ImportError as e:
except ImportError:
pass
from common.zeroconf.zeroconf import C_BARE_NAME, C_INTERFACE, C_PROTOCOL, C_DOMAIN

View File

@ -24,7 +24,7 @@ from common.zeroconf.zeroconf import C_BARE_NAME, C_DOMAIN
try:
import pybonjour
except ImportError as e:
except ImportError:
pass
@ -283,7 +283,7 @@ class Zeroconf:
try:
self.browse_sdRef = pybonjour.DNSServiceBrowse(regtype=self.stype, domain=domain, callBack=self.browse_callback)
except pybonjour.BonjourError as e:
self.error_CB("Error while browsing: %s" % e)
self.error_CB("Error while browsing: %s" % str(e))
def browse_loop(self):
ready = select.select([self.browse_sdRef], [], [], 0)

View File

@ -3385,7 +3385,7 @@ class ManageBookmarksWindow:
nick = self.nick_entry.get_text()
try:
nick = helpers.parse_resource(nick)
except helpers.InvalidFormat as e:
except helpers.InvalidFormat:
dialogs.ErrorDialog(_('Invalid nickname'),
_('Character not allowed'))
self.nick_entry.set_text(model[iter_][6])
@ -3424,7 +3424,7 @@ class ManageBookmarksWindow:
self.server_entry.get_text().strip()
try:
room_jid = helpers.parse_resource(room_jid)
except helpers.InvalidFormat as e:
except helpers.InvalidFormat:
dialogs.ErrorDialog(_('Invalid room'),
_('Character not allowed'))
self.room_entry.set_text(model[iter_][2].split('@')[0])

View File

@ -2755,7 +2755,7 @@ class NewChatDialog(InputDialog):
try:
jid = helpers.parse_jid(jid)
except helpers.InvalidFormat as e:
ErrorDialog(_('Invalid JID'), e[0])
ErrorDialog(_('Invalid JID'), str(e))
return
except:
ErrorDialog(_('Invalid JID'), _('Unable to parse "%s".') % jid)

View File

@ -132,7 +132,7 @@ def parseOpts():
longargs += ' sm-client-id= sm-client-state-file= sm-disable'
opts = getopt.getopt(sys.argv[1:], shortargs, longargs.split())[0]
except getopt.error as msg1:
print(msg1)
print(str(msg1))
print('for help use --help')
sys.exit(2)
for o, a in opts:

View File

@ -349,10 +349,10 @@ def parse_server_xml(path_to_file):
return handler.servers
# handle exception if unable to open file
except IOError as message:
print(_('Error reading file:') + message, file=sys.stderr)
print(_('Error reading file:') + str(message), file=sys.stderr)
# handle exception parsing file
except xml.sax.SAXParseException as message:
print(_('Error parsing file:') + message, file=sys.stderr)
print(_('Error parsing file:') + str(message), file=sys.stderr)
def set_unset_urgency_hint(window, unread_messages_no):
"""

View File

@ -766,7 +766,7 @@ class HtmlHandler(xml.sax.handler.ContentHandler):
#self._insert_text('\u2550'*40)
self._jump_line()
except Exception as e:
log.debug(str('Error in hr'+e))
log.debug('Error in hr' + str(e))
elif name in LIST_ELEMS:
self.list_counters.pop()
elif name == 'li':

View File

@ -427,9 +427,9 @@ class PluginManager(object):
try:
module = __import__(module_name)
except ValueError as value_error:
log.debug(value_error)
log.debug(str(value_error))
except ImportError as import_error:
log.debug(import_error)
log.debug(str(import_error))
elif os.path.isdir(file_path) and scan_dirs:
module_name = elem_name
@ -440,9 +440,9 @@ class PluginManager(object):
try:
module = __import__(module_name)
except ValueError as value_error:
log.debug(value_error)
log.debug(str(value_error))
except ImportError as import_error:
log.debug(import_error)
log.debug(str(import_error))
if module is None:
@ -477,21 +477,21 @@ class PluginManager(object):
plugins_found.append(module_attr)
except TypeError as type_error:
except TypeError:
# set plugin localization
try:
module_attr._ = _
except AttributeError as type_error:
except AttributeError:
pass
except configparser.NoOptionError as type_error:
except configparser.NoOptionError:
# all fields are required
log.debug('%s : %s' % (module_attr_name,
'wrong manifest file. all fields are required!'))
except configparser.NoSectionError as type_error:
except configparser.NoSectionError:
# info section are required
log.debug('%s : %s' % (module_attr_name,
'wrong manifest file. info section are required!'))
except configparser.MissingSectionHeaderError as type_error:
except configparser.MissingSectionHeaderError:
# info section are required
log.debug('%s : %s' % (module_attr_name,
'wrong manifest file. section are required!'))
@ -504,10 +504,10 @@ class PluginManager(object):
'''
try:
zip_file = zipfile.ZipFile(zip_filename)
except zipfile.BadZipfile as e:
except zipfile.BadZipfile:
# it is not zip file
raise PluginsystemError(_('Archive corrupted'))
except IOError as e:
except IOError:
raise PluginsystemError(_('Archive empty'))
if zip_file.testzip():

View File

@ -36,6 +36,6 @@ if os.name != 'nt':
try:
t = gettext.translation(APP, plugins_locale_dir)
_ = t.gettext
except IOError as msg:
except IOError:
from common import i18n
_ = gettext.gettext

View File

@ -743,7 +743,7 @@ class SignalObject(dbus.service.Object):
def prefs_store(self):
try:
gajim.interface.save_config()
except Exception as e:
except Exception:
return DBUS_BOOLEAN(False)
return DBUS_BOOLEAN(True)

View File

@ -25,14 +25,11 @@ class fake_sock(Mock):
self.incoming = []
self.incoming.append(self.sockobj._get_auth_response())
self.incoming.append(
self.sockobj._get_request_buff(sha1, 0x00)
)
self.incoming.append(self.sockobj._get_request_buff(sha1, 0x00))
self.outgoing = []
self.outgoing.append(self.sockobj._get_auth_buff())
self.outgoing.append(self.sockobj._get_request_buff(
sha1
))
self.outgoing.append(self.sockobj._get_request_buff(sha1))
def switch_stream(self):
# Roles are reversed, client will be expecting server stream
# and server will be expecting client stream