Reformat offlineimap/imapserver.py

Add some spaces, remove lines,... now format is better (lintian).
This commit is contained in:
Rodolfo García Peñas (kix) 2020-08-29 20:19:23 +02:00
parent 20a9837e26
commit b6a686e56f

View File

@ -34,9 +34,9 @@ import offlineimap.accounts
from offlineimap import imaplibutil, imaputil, threadutil, OfflineImapError
from offlineimap.ui import getglobalui
try:
import gssapi
have_gss = True
except ImportError:
have_gss = False
@ -62,7 +62,7 @@ class IMAPServer(object):
self.preauth_tunnel = repos.getpreauthtunnel()
self.transport_tunnel = repos.gettransporttunnel()
if self.preauth_tunnel and self.transport_tunnel:
raise OfflineImapError('%s: '% repos +
raise OfflineImapError('%s: ' % repos +
'you must enable precisely one '
'type of tunnel (preauth or transport), '
'not both', OfflineImapError.ERROR.REPO)
@ -164,7 +164,7 @@ class IMAPServer(object):
self.ui.warn("PySocks not installed, ignoring proxy option.")
except (AttributeError, ValueError) as e:
self.ui.warn("Bad proxy option %s for account %s: %s "
"Ignoring %s option."%
"Ignoring %s option." %
(proxy, self.repos.account.name, e, proxysection))
return dfltsocket
@ -185,11 +185,11 @@ class IMAPServer(object):
def __md5handler(self, response):
challenge = response.strip()
self.ui.debug('imap', '__md5handler: got challenge %s'% challenge)
self.ui.debug('imap', '__md5handler: got challenge %s' % challenge)
passwd = self.__getpassword()
retval = self.username + ' ' + hmac.new(passwd, challenge).hexdigest()
self.ui.debug('imap', '__md5handler: returning %s'% retval)
self.ui.debug('imap', '__md5handler: returning %s' % retval)
return retval
def __loginauth(self, imapobj):
@ -216,7 +216,7 @@ class IMAPServer(object):
retval = NULL.join((authz, authc, passwd))
logsafe_retval = NULL.join((authz, authc, '(passwd hidden for log)'))
self.ui.debug('imap', '__plainhandler: returning %s'% logsafe_retval)
self.ui.debug('imap', '__plainhandler: returning %s' % logsafe_retval)
return retval
def __xoauth2handler(self, response):
@ -229,7 +229,7 @@ class IMAPServer(object):
if self.oauth2_access_token is None:
if self.oauth2_request_url is None:
raise OfflineImapError("No remote oauth2_request_url for "
"repository '%s' specified."%
"repository '%s' specified." %
self, OfflineImapError.ERROR.REPO)
# Generate new access token.
@ -239,9 +239,9 @@ class IMAPServer(object):
params['refresh_token'] = self.oauth2_refresh_token
params['grant_type'] = 'refresh_token'
self.ui.debug('imap', 'xoauth2handler: url "%s"'%
self.ui.debug('imap', 'xoauth2handler: url "%s"' %
self.oauth2_request_url)
self.ui.debug('imap', 'xoauth2handler: params "%s"'% params)
self.ui.debug('imap', 'xoauth2handler: params "%s"' % params)
original_socket = socket.socket
socket.socket = self.authproxied_socket
@ -250,30 +250,30 @@ class IMAPServer(object):
self.oauth2_request_url, urllib.parse.urlencode(params)).read()
except Exception as e:
try:
msg = "%s (configuration is: %s)"% (e, str(params))
msg = "%s (configuration is: %s)" % (e, str(params))
except Exception as eparams:
msg = "%s [cannot display configuration: %s]"% (e, eparams)
msg = "%s [cannot display configuration: %s]" % (e, eparams)
six.reraise(type(e), type(e)(msg), exc_info()[2])
finally:
socket.socket = original_socket
resp = json.loads(response)
self.ui.debug('imap', 'xoauth2handler: response "%s"'% resp)
self.ui.debug('imap', 'xoauth2handler: response "%s"' % resp)
if 'error' in resp:
raise OfflineImapError("xoauth2handler got: %s"% resp,
raise OfflineImapError("xoauth2handler got: %s" % resp,
OfflineImapError.ERROR.REPO)
self.oauth2_access_token = resp['access_token']
if 'expires_in' in resp:
self.oauth2_access_token_expires_at = now + datetime.timedelta(
seconds=resp['expires_in']/2
seconds=resp['expires_in'] / 2
)
self.ui.debug('imap', 'xoauth2handler: access_token "%s expires %s"'% (
self.ui.debug('imap', 'xoauth2handler: access_token "%s expires %s"' % (
self.oauth2_access_token, self.oauth2_access_token_expires_at))
auth_string = 'user=%s\1auth=Bearer %s\1\1'% (
auth_string = 'user=%s\1auth=Bearer %s\1\1' % (
self.username, self.oauth2_access_token)
#auth_string = base64.b64encode(auth_string)
self.ui.debug('imap', 'xoauth2handler: returning "%s"'% auth_string)
# auth_string = base64.b64encode(auth_string)
self.ui.debug('imap', 'xoauth2handler: returning "%s"' % auth_string)
return auth_string
# Perform the next step handling a GSSAPI connection.
@ -330,25 +330,25 @@ class IMAPServer(object):
imapobj.starttls()
except imapobj.error as e:
raise OfflineImapError("Failed to start "
"TLS connection: %s"% str(e),
"TLS connection: %s" % str(e),
OfflineImapError.ERROR.REPO, None, exc_info()[2])
## All __authn_* procedures are helpers that do authentication.
## They are class methods that take one parameter, IMAP object.
##
## Each function should return True if authentication was
## successful and False if authentication wasn't even tried
## for some reason (but not when IMAP has no such authentication
## capability, calling code checks that).
##
## Functions can also raise exceptions; two types are special
## and will be handled by the calling code:
##
## - imapobj.error means that there was some error that
## comes from imaplib2;
##
## - OfflineImapError means that function detected some
## problem by itself.
# All __authn_* procedures are helpers that do authentication.
# They are class methods that take one parameter, IMAP object.
#
# Each function should return True if authentication was
# successful and False if authentication wasn't even tried
# for some reason (but not when IMAP has no such authentication
# capability, calling code checks that).
#
# Functions can also raise exceptions; two types are special
# and will be handled by the calling code:
#
# - imapobj.error means that there was some error that
# comes from imaplib2;
#
# - OfflineImapError means that function detected some
# problem by itself.
def __authn_gssapi(self, imapobj):
if not have_gss:
@ -444,25 +444,25 @@ class IMAPServer(object):
tried_to_authn = True
self.ui.debug('imap', 'Attempting '
'%s authentication'% m)
'%s authentication' % m)
try:
if func(imapobj):
return
except (imapobj.error, OfflineImapError) as e:
self.ui.warn('%s authentication failed: %s'% (m, e))
self.ui.warn('%s authentication failed: %s' % (m, e))
exc_stack.append((m, e))
if len(exc_stack):
msg = "\n\t".join([": ".join((x[0], str(x[1]))) for x in exc_stack])
raise OfflineImapError("All authentication types "
"failed:\n\t%s"% msg, OfflineImapError.ERROR.REPO)
"failed:\n\t%s" % msg, OfflineImapError.ERROR.REPO)
if not tried_to_authn:
methods = ", ".join([x[5:] for x in
[x for x in imapobj.capabilities if x[0:5] == "AUTH="]])
raise OfflineImapError("Repository %s: no supported "
"authentication mechanisms found; configured %s, "
"server advertises %s"% (self.repos,
"server advertises %s" % (self.repos,
", ".join(self.authmechs), methods),
OfflineImapError.ERROR.REPO)
@ -474,7 +474,7 @@ class IMAPServer(object):
errstr = "CA Cert verifying failed: "
if not cert:
return ('%s no certificate received'% errstr)
return ('%s no certificate received' % errstr)
dnsname = hostname.lower()
certnames = []
@ -482,7 +482,7 @@ class IMAPServer(object):
notafter = cert.get('notAfter')
if notafter:
if time.time() >= cert_time_to_seconds(notafter):
return '%s certificate expired %s'% (errstr, notafter)
return '%s certificate expired %s' % (errstr, notafter)
# First read commonName
for s in cert.get('subject', []):
@ -490,7 +490,7 @@ class IMAPServer(object):
if key == 'commonName':
certnames.append(value.lower())
if len(certnames) == 0:
return ('%s no commonName found in certificate'% errstr)
return ('%s no commonName found in certificate' % errstr)
# Then read subjectAltName
for key, value in cert.get('subjectAltName', []):
@ -503,7 +503,7 @@ class IMAPServer(object):
'.' in dnsname and certname == '*.' + dnsname.split('.', 1)[1]):
return None
return ('%s no matching domain name found in certificate'% errstr)
return ('%s no matching domain name found in certificate' % errstr)
def acquireconnection(self):
"""Fetches a connection from the pool, making sure to create a new one
@ -524,11 +524,11 @@ class IMAPServer(object):
tryobj = self.availableconnections[i]
if self.lastowner[tryobj] == curThread.ident:
imapobj = tryobj
del(self.availableconnections[i])
del (self.availableconnections[i])
break
if not imapobj:
imapobj = self.availableconnections[0]
del(self.availableconnections[0])
del (self.availableconnections[0])
self.assignedconnections.append(imapobj)
self.lastowner[imapobj] = curThread.ident
self.connectionlock.release()
@ -554,7 +554,7 @@ class IMAPServer(object):
elif self.usessl:
self.ui.connecting(
self.repos.getname(), self.hostname, self.port)
self.ui.debug('imap', "%s: level '%s', version '%s'"%
self.ui.debug('imap', "%s: level '%s', version '%s'" %
(self.repos.getname(), self.tlslevel, self.sslversion))
imapobj = imaplibutil.WrappedIMAP4_SSL(
host=self.hostname,
@ -608,7 +608,7 @@ class IMAPServer(object):
# No Folders were returned. This occurs, e.g. if the
# 'reference' prefix does not exist on the mail
# server. Raise exception.
err = "Server '%s' returned no folders in '%s'"% \
err = "Server '%s' returned no folders in '%s'" % \
(self.repos.getname(), self.reference)
self.ui.warn(err)
raise Exception(err)
@ -630,11 +630,11 @@ class IMAPServer(object):
severity = OfflineImapError.ERROR.REPO
if type(e) == gaierror:
#DNS related errors. Abort Repo sync
#TODO: special error msg for e.errno == 2 "Name or service not known"?
reason = "Could not resolve name '%s' for repository "\
"'%s'. Make sure you have configured the ser"\
"ver name correctly and that you are online."%\
# DNS related errors. Abort Repo sync
# TODO: special error msg for e.errno == 2 "Name or service not known"?
reason = "Could not resolve name '%s' for repository " \
"'%s'. Make sure you have configured the ser" \
"ver name correctly and that you are online." % \
(self.hostname, self.repos)
six.reraise(OfflineImapError,
OfflineImapError(reason, severity),
@ -644,13 +644,13 @@ class IMAPServer(object):
# SSL unknown protocol error
# happens e.g. when connecting via SSL to a non-SSL service
if self.port != 993:
reason = "Could not connect via SSL to host '%s' and non-s"\
"tandard ssl port %d configured. Make sure you connect"\
" to the correct port. Got: %s"% (
reason = "Could not connect via SSL to host '%s' and non-s" \
"tandard ssl port %d configured. Make sure you connect" \
" to the correct port. Got: %s" % (
self.hostname, self.port, e)
else:
reason = "Unknown SSL protocol connecting to host '%s' for "\
"repository '%s'. OpenSSL responded:\n%s"\
reason = "Unknown SSL protocol connecting to host '%s' for " \
"repository '%s'. OpenSSL responded:\n%s" \
% (self.hostname, self.repos, e)
six.reraise(OfflineImapError,
OfflineImapError(reason, severity),
@ -659,10 +659,10 @@ class IMAPServer(object):
elif isinstance(e, socket.error) and e.args[0] == errno.ECONNREFUSED:
# "Connection refused", can be a non-existing port, or an unauthorized
# webproxy (open WLAN?)
reason = "Connection to host '%s:%d' for repository '%s' was "\
"refused. Make sure you have the right host and port "\
"configured and that you are actually able to access the "\
"network."% (self.hostname, self.port, self.repos)
reason = "Connection to host '%s:%d' for repository '%s' was " \
"refused. Make sure you have the right host and port " \
"configured and that you are actually able to access the " \
"network." % (self.hostname, self.port, self.repos)
six.reraise(OfflineImapError,
OfflineImapError(reason, severity),
exc_info()[2])
@ -672,8 +672,7 @@ class IMAPServer(object):
six.reraise(OfflineImapError,
OfflineImapError(
"Could not connect to remote server '%s' "
"for repository '%s'. Remote does not answer."%
(self.hostname, self.repos),
"for repository '%s'. Remote does not answer." % (self.hostname, self.repos),
OfflineImapError.ERROR.REPO),
exc_info()[2])
else:
@ -728,7 +727,7 @@ class IMAPServer(object):
threads = []
for i in range(numconnections):
self.ui.debug('imap', 'keepalive: processing connection %d of %d'%
self.ui.debug('imap', 'keepalive: processing connection %d of %d' %
(i, numconnections))
if len(self.idlefolders) > i:
# IDLE thread
@ -751,7 +750,6 @@ class IMAPServer(object):
self.ui.debug('imap', 'keepalive: event is set; exiting')
return
def releaseconnection(self, connection, drop_conn=False):
"""Releases a connection, returning it to the pool.
@ -808,7 +806,7 @@ class IdleThread(object):
try:
imapobj.noop()
except imapobj.abort:
self.ui.warn('Attempting NOOP on dropped connection %s'%
self.ui.warn('Attempting NOOP on dropped connection %s' %
imapobj.identifier)
self.parent.releaseconnection(imapobj, True)
imapobj = None
@ -832,7 +830,7 @@ class IdleThread(object):
account.callhook(hook)
ui = getglobalui()
ui.unregisterthread(currentThread()) #syncfolder registered the thread
ui.unregisterthread(currentThread()) # syncfolder registered the thread
def __idle(self):
"""Invoke IDLE mode until timeout or self.stop() is invoked."""
@ -858,13 +856,12 @@ class IdleThread(object):
# End IDLE mode with noop, imapobj can point to a dropped conn.
imapobj.noop()
except imapobj.abort:
self.ui.warn('Attempting NOOP on dropped connection %s'%
self.ui.warn('Attempting NOOP on dropped connection %s' %
imapobj.identifier)
self.parent.releaseconnection(imapobj, True)
else:
self.parent.releaseconnection(imapobj)
while not self.stop_sig.isSet():
self.needsync = False
@ -890,8 +887,8 @@ class IdleThread(object):
imapobj.idle(callback=callback)
else:
self.ui.warn("IMAP IDLE not supported on server '%s'."
"Sleep until next refresh cycle."% imapobj.identifier)
noop(imapobj) #XXX: why?
"Sleep until next refresh cycle." % imapobj.identifier)
noop(imapobj) # XXX: why?
self.stop_sig.wait() # self.stop() or IDLE callback are invoked.
noop(imapobj)