Browse Source

Fix more errors and warnings found by code validation

tags/2.3.5RC2
Safihre 7 years ago
parent
commit
5e722b27f3
  1. 8
      SABnzbd.py
  2. 2
      sabnzbd/__init__.py
  3. 9
      sabnzbd/api.py
  4. 6
      sabnzbd/config.py
  5. 5
      sabnzbd/decoder.py
  6. 4
      sabnzbd/dirscanner.py
  7. 2
      sabnzbd/downloader.py
  8. 13
      sabnzbd/interface.py
  9. 3
      sabnzbd/misc.py
  10. 15
      sabnzbd/newsunpack.py
  11. 5
      sabnzbd/newswrapper.py
  12. 2
      sabnzbd/notifier.py
  13. 5
      sabnzbd/nzbqueue.py
  14. 4
      sabnzbd/nzbstuff.py
  15. 1
      sabnzbd/par2file.py
  16. 4
      sabnzbd/postproc.py
  17. 13
      sabnzbd/rss.py
  18. 8
      sabnzbd/skintext.py
  19. 4
      sabnzbd/urlgrabber.py
  20. 2
      sabnzbd/utils/certgen.py
  21. 1
      sabnzbd/utils/checkdir.py
  22. 2
      sabnzbd/utils/getperformance.py
  23. 264
      sabnzbd/utils/happyeyeballs.py
  24. 2
      sabnzbd/utils/pystone.py
  25. 4
      sabnzbd/utils/servertests.py
  26. 5
      sabnzbd/zconfig.py
  27. 1
      tests/conftest.py
  28. 2
      util/apireg.py
  29. 1
      util/mailslot.py

8
SABnzbd.py

@ -502,7 +502,7 @@ def all_localhosts():
def check_resolve(host):
""" Return True if 'host' resolves """
try:
dummy = socket.getaddrinfo(host, None)
socket.getaddrinfo(host, None)
except:
# Does not resolve
return False
@ -598,7 +598,7 @@ def get_webhost(cherryhost, cherryport, https_port):
cherryhost = cherryhost.strip('[]')
else:
try:
info = socket.getaddrinfo(cherryhost, None)
socket.getaddrinfo(cherryhost, None)
except:
cherryhost = cherryhost.strip('[]')
@ -1005,13 +1005,13 @@ def main():
if enable_https and https_port:
try:
cherrypy.process.servers.check_port(cherryhost, https_port, timeout=0.05)
except IOError, error:
except IOError:
Bail_Out(browserhost, cherryport)
except:
Bail_Out(browserhost, cherryport, '49')
try:
cherrypy.process.servers.check_port(cherryhost, cherryport, timeout=0.05)
except IOError, error:
except IOError:
Bail_Out(browserhost, cherryport)
except:
Bail_Out(browserhost, cherryport, '49')

2
sabnzbd/__init__.py

@ -1204,7 +1204,7 @@ def test_cert_checking():
ssl_sock.connect((cfg.selftest_host(), 443))
ssl_sock.close()
return True
except (socket.gaierror, socket.timeout) as e:
except (socket.gaierror, socket.timeout):
# Non-SSL related error.
# We now assume that certificates work instead of forcing
# lower quality just because some (temporary) internet problem

9
sabnzbd/api.py

@ -220,6 +220,8 @@ def _api_queue_pause(output, value, kwargs):
if value:
items = value.split(',')
handled = NzbQueue.do.pause_multiple_nzo(items)
else:
handled = False
return report(output, keyword='', data={'status': bool(handled), 'nzo_ids': handled})
@ -228,6 +230,8 @@ def _api_queue_resume(output, value, kwargs):
if value:
items = value.split(',')
handled = NzbQueue.do.resume_multiple_nzo(items)
else:
handled = False
return report(output, keyword='', data={'status': bool(handled), 'nzo_ids': handled})
@ -462,6 +466,7 @@ def _api_change_opts(name, output, kwargs):
""" API: accepts output, value(=nzo_id), value2(=pp) """
value = kwargs.get('value')
value2 = kwargs.get('value2')
result = 0
if value and value2 and value2.isdigit():
result = NzbQueue.do.change_opts(value, int(value2))
return report(output, keyword='status', data=bool(result > 0))
@ -802,7 +807,6 @@ def _api_browse(name, output, kwargs):
compact = kwargs.get('compact')
if compact and compact == '1':
paths = []
name = platform_encode(kwargs.get('term', ''))
paths = [entry['path'] for entry in folders_at_path(os.path.dirname(name)) if 'path' in entry]
return report(output, keyword='', data=paths)
@ -1685,7 +1689,6 @@ def build_queue_header(search=None, start=0, limit=0, output=None):
header['size'] = format_bytes(bytes)
header['noofslots_total'] = qnfo.q_fullsize
status = ''
if Downloader.do.paused or Downloader.do.postproc:
status = Status.PAUSED
elif bytespersec > 0:
@ -1700,7 +1703,6 @@ def build_queue_header(search=None, start=0, limit=0, output=None):
# new eta format: 16:00 Fri 07 Feb
header['eta'] = datestart.strftime(time_format('%H:%M %a %d %b')).decode(codepage)
except:
datestart = datetime.datetime.now()
header['eta'] = T('unknown')
return (header, qnfo.list, bytespersec, qnfo.q_fullsize, qnfo.bytes_left_previous_page)
@ -1772,7 +1774,6 @@ def build_history(start=None, limit=None, verbose=False, verbose_list=None, sear
if not h_limit:
items, fetched_items, total_items = history_db.fetch_history(h_start, 1, search, failed_only, categories)
items = []
fetched_items = 0
else:
items, fetched_items, total_items = history_db.fetch_history(h_start, h_limit, search, failed_only, categories)

6
sabnzbd/config.py

@ -411,8 +411,8 @@ class ConfigServer(object):
except KeyError:
continue
exec 'self.%s.set(value)' % kw
if not self.displayname():
self.displayname.set(self.__name)
if not self.displayname():
self.displayname.set(self.__name)
return True
def get_dict(self, safe=False):
@ -896,7 +896,7 @@ def get_servers():
return {}
def define_categories(force=False):
def define_categories():
""" Define categories listed in the Setup file
return a list of ConfigCat instances
"""

5
sabnzbd/decoder.py

@ -125,7 +125,7 @@ class Decoder(Thread):
nzf.article_count += 1
found = True
except IOError, e:
except IOError:
logme = T('Decoding %s failed') % art_id
logging.warning(logme)
logging.info("Traceback: ", exc_info=True)
@ -134,7 +134,7 @@ class Decoder(Thread):
sabnzbd.nzbqueue.NzbQueue.do.reset_try_lists(article)
register = False
except MemoryError, e:
except MemoryError:
logme = T('Decoder failure: Out of memory')
logging.warning(logme)
anfo = sabnzbd.articlecache.ArticleCache.do.cache_info()
@ -240,7 +240,6 @@ class Decoder(Thread):
nzf = article.nzf
yenc, data = yCheck(data)
ybegin, ypart, yend = yenc
decoded_data = None
# Deal with non-yencoded posts
if not ybegin:

4
sabnzbd/dirscanner.py

@ -144,7 +144,7 @@ def ProcessArchiveFile(filename, path, pp=None, script=None, cat=None, catdir=No
priority=priority, nzbname=nzbname)
if not nzo.password:
nzo.password = password
except (TypeError, ValueError) as e:
except (TypeError, ValueError):
# Duplicate or empty, ignore
pass
except:
@ -232,7 +232,7 @@ def ProcessSingleFile(filename, path, pp=None, script=None, cat=None, catdir=Non
# Empty, but correct file
return -1, nzo_ids
except:
if data.find("<nzb") >= 0 and data.find("</nzb") < 0:
if data.find("<nzb") >= 0 > data.find("</nzb"):
# Looks like an incomplete file, retry
return -2, nzo_ids
else:

2
sabnzbd/downloader.py

@ -311,7 +311,7 @@ class Downloader(Thread):
'''
if value:
mx = cfg.bandwidth_max.get_int()
if '%' in str(value) or (from_units(value) > 0 and from_units(value) < 101):
if '%' in str(value) or (0 < from_units(value) < 101):
limit = value.strip(' %')
self.bandwidth_perc = from_units(limit)
if mx:

13
sabnzbd/interface.py

@ -161,7 +161,7 @@ def check_hostname():
if not host:
return False
# Remove the port-part (like ':8080'), if it is there, always on the right hand side.
# Remove the port-part (like ':8080'), if it is there, always on the right hand side.
# Not to be confused with IPv6 colons (within square brackets)
host = re.sub(':[0123456789]+$', '', host).lower()
@ -174,7 +174,7 @@ def check_hostname():
return True
# Fine if ends with ".local" or ".local.", aka mDNS name
# See rfc6762 Multicast DNS
# See rfc6762 Multicast DNS
if host.endswith(('.local', '.local.')):
return True
@ -774,7 +774,7 @@ class NzoPage(object):
# /SABnzbd_nzo_xxxxx/files
elif 'files' in args:
info = self.nzo_files(info, pnfo_list, nzo_id)
info = self.nzo_files(info, nzo_id)
# /SABnzbd_nzo_xxxxx/save
elif 'save' in args:
@ -784,7 +784,7 @@ class NzoPage(object):
# /SABnzbd_nzo_xxxxx/
else:
info = self.nzo_details(info, pnfo_list, nzo_id)
info = self.nzo_files(info, pnfo_list, nzo_id)
info = self.nzo_files(info, nzo_id)
template = Template(file=os.path.join(sabnzbd.WEB_DIR, 'nzo.tmpl'),
filter=FILTER, searchList=[info], compilerSettings=DIRECTIVES)
@ -836,7 +836,7 @@ class NzoPage(object):
return info
def nzo_files(self, info, pnfo_list, nzo_id):
def nzo_files(self, info, nzo_id):
active = []
nzo = NzbQueue.do.get_nzo(nzo_id)
if nzo:
@ -2077,7 +2077,7 @@ class ConfigScheduling(object):
if '%' not in value and from_units(value) < 1.0:
value = T('off') # : "Off" value for speedlimit in scheduler
else:
if '%' not in value and int_conv(value) > 1 and int_conv(value) < 101:
if '%' not in value and 1 < int_conv(value) < 101:
value += '%'
value = value.upper()
if action in actions:
@ -2132,7 +2132,6 @@ class ConfigScheduling(object):
@secured_expose(check_session_key=True, check_configlock=True)
def addSchedule(self, **kwargs):
servers = config.get_servers()
categories = list_cats(False)
minute = kwargs.get('minute')
hour = kwargs.get('hour')
days_of_week = ''.join([str(x) for x in kwargs.get('daysofweek', '')])

3
sabnzbd/misc.py

@ -748,7 +748,6 @@ def to_units(val, spaces=0, postfix=''):
Show single decimal for M and higher
"""
dec_limit = 1
decimals = 0
if val < 0:
sign = '-'
else:
@ -1453,7 +1452,7 @@ def create_https_certificates(ssl_cert, ssl_key):
try:
from sabnzbd.utils.certgen import generate_key, generate_local_cert
private_key = generate_key(key_size=2048, output_file=ssl_key)
generate_local_cert(private_key, days_valid=3560, output_file=ssl_cert, LN=u'SABnzbd', ON=u'SABnzbd', CN=u'localhost')
generate_local_cert(private_key, days_valid=3560, output_file=ssl_cert, LN=u'SABnzbd', ON=u'SABnzbd')
logging.info('Self-signed certificates generated successfully')
except:
logging.error(T('Error creating SSL key and certificate'))

15
sabnzbd/newsunpack.py

@ -33,7 +33,7 @@ from sabnzbd.encoding import TRANS, unicoder, platform_encode, deunicode
import sabnzbd.utils.rarfile as rarfile
from sabnzbd.misc import format_time_string, find_on_path, make_script_path, int_conv, \
real_path, globber, globber_full, get_all_passwords, renamer, clip_path, calc_age, \
has_win_device, long_path, remove_file, recursive_listdir, is_rarfile
long_path, remove_file, recursive_listdir, is_rarfile
from sabnzbd.sorting import SeriesSorter
import sabnzbd.cfg as cfg
from sabnzbd.constants import Status
@ -175,7 +175,7 @@ def external_processing(extern_proc, nzo, complete_dir, nicename, status):
proc = p.stdout
if p.stdin:
p.stdin.close()
line = ''
lines = []
while 1:
line = proc.readline()
@ -236,11 +236,10 @@ def unpack_magic(nzo, workdir, workdir_complete, dele, one_folder, joinables, zi
else:
xjoinables, xzips, xrars, xsevens, xts = build_filelists(workdir, workdir_complete, check_both=dele)
rerun = False
force_rerun = False
newfiles = []
error = None
new_joins = new_rars = new_zips = new_ts = None
new_joins = new_ts = None
if cfg.enable_filejoin():
new_joins = [jn for jn in xjoinables if jn not in joinables]
@ -1120,9 +1119,9 @@ def par2_repair(parfile_nzf, nzo, workdir, setname, single):
# Multipar or not?
if sabnzbd.WIN32 and cfg.multipar():
finished, readd, datafiles, used_joinables, used_for_repair = MultiPar_Verify(parfile, parfile_nzf, nzo, setname, joinables, single=single)
finished, readd, datafiles, used_joinables, used_for_repair = MultiPar_Verify(parfile, nzo, setname, joinables, single=single)
else:
finished, readd, datafiles, used_joinables, used_for_repair = PAR_Verify(parfile, parfile_nzf, nzo, setname, joinables, single=single)
finished, readd, datafiles, used_joinables, used_for_repair = PAR_Verify(parfile, nzo, setname, joinables, single=single)
if finished:
result = True
@ -1189,7 +1188,7 @@ _RE_LOADING_PAR2 = re.compile(r'Loading "([^"]+)"\.')
_RE_LOADED_PAR2 = re.compile(r'Loaded (\d+) new packets')
def PAR_Verify(parfile, parfile_nzf, nzo, setname, joinables, single=False):
def PAR_Verify(parfile, nzo, setname, joinables, single=False):
""" Run par2 on par-set """
used_joinables = []
used_for_repair = []
@ -1526,7 +1525,7 @@ def PAR_Verify(parfile, parfile_nzf, nzo, setname, joinables, single=False):
_RE_FILENAME = re.compile(r'"([^"]+)"')
def MultiPar_Verify(parfile, parfile_nzf, nzo, setname, joinables, single=False):
def MultiPar_Verify(parfile, nzo, setname, joinables, single=False):
""" Run par2 on par-set """
parfolder = os.path.split(parfile)[0]
used_joinables = []

5
sabnzbd/newswrapper.py

@ -150,7 +150,7 @@ class NNTP(object):
# Pre-define attributes to save memory
__slots__ = ('host', 'port', 'nw', 'blocking', 'error_msg', 'sock')
def __init__(self, host, port, info, sslenabled, send_group, nw, user=None, password=None, block=False, write_fds=None):
def __init__(self, host, port, info, sslenabled, nw, block=False, write_fds=None):
self.host = host
self.port = port
self.nw = nw
@ -312,8 +312,7 @@ class NewsWrapper(object):
# Construct NNTP object and shorthands
self.nntp = NNTP(self.server.hostip, self.server.port, self.server.info, self.server.ssl,
self.server.send_group, self, self.server.username, self.server.password,
self.blocking, write_fds)
self, self.blocking, write_fds)
self.recv = self.nntp.sock.recv
self.timeout = time.time() + self.server.timeout

2
sabnzbd/notifier.py

@ -462,7 +462,7 @@ def send_pushover(title, msg, gtype, force=False, test=None):
"expire": emergency_expire
}
return do_send_pushover(body)
if prio > -3 and prio < 2:
if -3 < prio < 2:
body = { "token": apikey,
"user": userkey,
"device": device,

5
sabnzbd/nzbqueue.py

@ -69,7 +69,7 @@ class NzbQueue(object):
data = sabnzbd.load_admin(QUEUE_FILE_NAME)
# Process the data and check compatibility
nzo_ids = self.check_compatibility(data)
nzo_ids = self.check_compatibility(repair, data)
# First handle jobs in the queue file
folders = []
@ -104,7 +104,7 @@ class NzbQueue(object):
except:
pass
def check_compatibility(self, data):
def check_compatibility(self, repair, data):
""" Do compatibility checks on the loaded data """
nzo_ids = []
if not data:
@ -204,7 +204,6 @@ class NzbQueue(object):
verified = sabnzbd.load_data(VERIFIED_FILE, path, remove=False) or {'x': False}
return all(verified[x] for x in verified)
nzo_id = None
name = os.path.basename(folder)
path = os.path.join(folder, JOB_ADMIN)
if hasattr(new_nzb, 'filename'):

4
sabnzbd/nzbstuff.py

@ -1022,7 +1022,7 @@ class NzbObject(TryList):
# Sort the sets
for setname in self.extrapars:
self.extrapars[parset].sort(key=lambda x: x.blocks)
self.extrapars[setname].sort(key=lambda x: x.blocks)
# Also re-parse all filenames in case par2 came after first articles
self.verify_all_filenames_and_resort()
@ -2005,7 +2005,7 @@ def scan_password(name):
slash = name.find('/')
# Look for name/password, but make sure that '/' comes before any {{
if slash >= 0 and slash < braces and 'password=' not in name:
if 0 <= slash < braces and 'password=' not in name:
# Is it maybe in 'name / password' notation?
if slash == name.find(' / ') + 1:
# Remove the extra space after name and before password

1
sabnzbd/par2file.py

@ -49,7 +49,6 @@ def analyse_par2(name, filepath=None):
setname is empty when not a par2 file
"""
name = name.strip()
setname = None
vol = block = 0
m = PROBABLY_PAR2_RE.search(name)
if m:

4
sabnzbd/postproc.py

@ -281,7 +281,6 @@ def process_job(nzo):
nzb_list = []
# These need to be initialized in case of a crash
workdir_complete = ''
postproc_time = 0
script_log = ''
script_line = ''
@ -336,15 +335,12 @@ def process_job(nzo):
unpack_error = 1
script = nzo.script
cat = nzo.cat
logging.info('Starting Post-Processing on %s' +
' => Repair:%s, Unpack:%s, Delete:%s, Script:%s, Cat:%s',
filename, flag_repair, flag_unpack, flag_delete, script, nzo.cat)
# Set complete dir to workdir in case we need to abort
workdir_complete = workdir
marker_file = None
# Par processing, if enabled
if all_ok and flag_repair:

13
sabnzbd/rss.py

@ -290,7 +290,7 @@ class RSSQueue(object):
msg = T('Do not have valid authentication for feed %s') % feed
logging.info(msg)
if status >= 500 and status <= 599:
if 500 <= status <= 599:
msg = T('Server side error (server code %s); could not get %s on %s') % (status, feed, uri)
logging.info(msg)
@ -330,12 +330,8 @@ class RSSQueue(object):
if readout:
try:
link, category, size, age, season, episode = _get_link(uri, entry)
link, category, size, age, season, episode = _get_link(entry)
except (AttributeError, IndexError):
link = None
category = u''
size = 0L
age = None
logging.info(T('Incompatible feed') + ' ' + uri)
logging.info("Traceback: ", exc_info=True)
return T('Incompatible feed')
@ -627,14 +623,11 @@ def _HandleLink(jobs, feed, link, title, size, age, season, episode, flag, orgca
else:
jobs[link]['status'] = flag
def _get_link(uri, entry):
def _get_link(entry):
""" Retrieve the post link from this entry
Returns (link, category, size)
"""
link = None
category = ''
size = 0L
uri = uri.lower()
age = datetime.datetime.now()
# Try standard link and enclosures first

8
sabnzbd/skintext.py

@ -47,16 +47,10 @@ SKIN_TEXT = {
'post-Propagating' : TT('Propagation delay'),
'post-Checking' : TT('Checking'), #: PP status
'sch-frequency' : TT('Frequency'), #: #: Config->Scheduler
'sch-action' : TT('Action'), #: #: Config->Scheduler
'sch-arguments' : TT('Arguments'), #: #: Config->Scheduler
'sch-task' : TT('Task'), #: #: Config->Scheduler
'sch-disable_server' : TT('disable server'), #: #: Config->Scheduler
'sch-enable_server' : TT('enable server'), #: #: Config->Scheduler
'sch-resume' : TT('Resume'), #: #: Config->Scheduler
'sch-pause' : TT('Pause'), #: #: Config->Scheduler
'sch-shutdown' : TT('Shutdown'), #: #: Config->Scheduler
'sch-restart' : TT('Restart'), #: #: Config->Scheduler
'sch-speedlimit' : TT('Speedlimit'), #: #: Config->Scheduler
'sch-pause_all' : TT('Pause All'), #: #: Config->Scheduler
'sch-pause_post' : TT('Pause post-processing'), #: #: Config->Scheduler

4
sabnzbd/urlgrabber.py

@ -199,7 +199,7 @@ class URLGrabber(Thread):
retry = True
fetch_request = None
elif retry:
fetch_request, msg, retry, wait, data = _analyse(fetch_request, url, future_nzo)
fetch_request, msg, retry, wait, data = _analyse(fetch_request, future_nzo)
if not fetch_request:
if retry:
@ -351,7 +351,7 @@ def _build_request(url):
return urllib2.urlopen(req)
def _analyse(fetch_request, url, future_nzo):
def _analyse(fetch_request, future_nzo):
""" Analyze response of indexer
returns fetch_request|None, error-message|None, retry, wait-seconds, data
"""

2
sabnzbd/utils/certgen.py

@ -52,7 +52,7 @@ def generate_key(key_size=2048, output_file='key.pem'):
# Ported from cryptography docs/x509/tutorial.rst
def generate_local_cert(private_key, days_valid=3560, output_file='cert.cert', LN=u'SABnzbd', ON=u'SABnzbd', CN=u'localhost'):
def generate_local_cert(private_key, days_valid=3560, output_file='cert.cert', LN=u'SABnzbd', ON=u'SABnzbd'):
# Various details about who we are. For a self-signed certificate the
# subject and issuer are always the same.
subject = issuer = x509.Name([

1
sabnzbd/utils/checkdir.py

@ -70,7 +70,6 @@ def isFAT(dir):
'''
dfcmd = "df " + dir
device = ''
for thisline in os.popen(dfcmd).readlines():
if thisline.find('/')==0:
if debug: print thisline

2
sabnzbd/utils/getperformance.py

@ -61,7 +61,7 @@ def getpystone():
maxpystone = max(maxpystone, int(pystonefloat))
# Stop when pystone() has been running for at least 0.1 second
if duration > 0.1:
break;
break
return maxpystone

264
sabnzbd/utils/happyeyeballs.py

@ -31,119 +31,119 @@ DEBUG = False
# called by each thread
def do_socket_connect(queue, ip, PORT, SSL, ipv4delay):
# connect to the ip, and put the result into the queue
if DEBUG: logging.debug("Input for thread is %s %s %s", ip, PORT, SSL)
try:
# CREATE SOCKET
if ip.find(':') >= 0:
s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
if ip.find('.') >= 0:
time.sleep(ipv4delay) # IPv4 ... so a delay for IPv4 as we prefer IPv6. Note: ipv4delay could be 0
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(3)
if not SSL:
# Connect ...
s.connect((ip, PORT))
# ... and close
s.close()
else:
# WRAP SOCKET
wrappedSocket = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_TLSv1)
# CONNECT
wrappedSocket.connect((ip, PORT))
# CLOSE SOCKET CONNECTION
wrappedSocket.close()
queue.put((ip, True))
if DEBUG: logging.debug("connect to %s OK", ip)
except:
queue.put((ip, False))
if DEBUG: logging.debug("connect to %s not OK", ip)
pass
# connect to the ip, and put the result into the queue
if DEBUG: logging.debug("Input for thread is %s %s %s", ip, PORT, SSL)
try:
# CREATE SOCKET
if ip.find(':') >= 0:
s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
if ip.find('.') >= 0:
time.sleep(ipv4delay) # IPv4 ... so a delay for IPv4 as we prefer IPv6. Note: ipv4delay could be 0
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(3)
if not SSL:
# Connect ...
s.connect((ip, PORT))
# ... and close
s.close()
else:
# WRAP SOCKET
wrappedSocket = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_TLSv1)
# CONNECT
wrappedSocket.connect((ip, PORT))
# CLOSE SOCKET CONNECTION
wrappedSocket.close()
queue.put((ip, True))
if DEBUG: logging.debug("connect to %s OK", ip)
except:
queue.put((ip, False))
if DEBUG: logging.debug("connect to %s not OK", ip)
pass
def happyeyeballs(HOST, **kwargs):
# Happyeyeballs function, with caching of the results
# Fill out the parameters into the variables
try:
PORT = kwargs['port']
except:
PORT = 80
try:
SSL = kwargs['ssl']
except:
SSL = False
try:
preferipv6 = kwargs['preferipv6']
except:
preferipv6 = True # prefer IPv6, so give IPv6 connects a head start by delaying IPv4
# Find out if a cached result is available, and recent enough:
timecurrent = int(time.time()) # current time in seconds since epoch
retentionseconds = 100
hostkey = (HOST, PORT, SSL, preferipv6) # Example key: (u'ssl.astraweb.com', 563, True, True)
try:
happyeyeballs.happylist[hostkey] # just to check: does it exist?
# No exception, so entry exists, so let's check the time:
timecached = happyeyeballs.happylist[hostkey][1]
if timecurrent - timecached <= retentionseconds:
if DEBUG: logging.debug("existing cached result recent enough")
return happyeyeballs.happylist[hostkey][0]
else:
if DEBUG: logging.debug("existing cached result too old. Find a new one")
# Continue a few lines down
except:
# Exception, so entry not there, so we have to fill it out
if DEBUG: logging.debug("Host not yet in the cache. Find entry")
pass
# we only arrive here if the entry has to be determined. So let's do that:
# We have to determine the (new) best IP address
start = time.clock()
if DEBUG: logging.debug("\n\n%s %s %s %s", HOST, PORT, SSL, preferipv6)
ipv4delay = 0
try:
# Check if there is an AAAA / IPv6 result for this host:
info = socket.getaddrinfo(HOST, PORT, socket.AF_INET6, socket.SOCK_STREAM, socket.IPPROTO_IP, socket.AI_CANONNAME)
if DEBUG: logging.debug("IPv6 address found for %s", HOST)
if preferipv6:
ipv4delay=0.1 # preferipv6, AND at least one IPv6 found, so give IPv4 (!) a delay so that IPv6 has a head start and is preferred
except:
if DEBUG: logging.debug("No IPv6 address found for %s", HOST)
myqueue = Queue.Queue() # queue used for threads giving back the results
try:
# Happyeyeballs function, with caching of the results
# Fill out the parameters into the variables
try:
PORT = kwargs['port']
except:
PORT = 80
try:
SSL = kwargs['ssl']
except:
SSL = False
try:
preferipv6 = kwargs['preferipv6']
except:
preferipv6 = True # prefer IPv6, so give IPv6 connects a head start by delaying IPv4
# Find out if a cached result is available, and recent enough:
timecurrent = int(time.time()) # current time in seconds since epoch
retentionseconds = 100
hostkey = (HOST, PORT, SSL, preferipv6) # Example key: (u'ssl.astraweb.com', 563, True, True)
try:
happyeyeballs.happylist[hostkey] # just to check: does it exist?
# No exception, so entry exists, so let's check the time:
timecached = happyeyeballs.happylist[hostkey][1]
if timecurrent - timecached <= retentionseconds:
if DEBUG: logging.debug("existing cached result recent enough")
return happyeyeballs.happylist[hostkey][0]
else:
if DEBUG: logging.debug("existing cached result too old. Find a new one")
# Continue a few lines down
except:
# Exception, so entry not there, so we have to fill it out
if DEBUG: logging.debug("Host not yet in the cache. Find entry")
pass
# we only arrive here if the entry has to be determined. So let's do that:
# We have to determine the (new) best IP address
start = time.clock()
if DEBUG: logging.debug("\n\n%s %s %s %s", HOST, PORT, SSL, preferipv6)
ipv4delay = 0
try:
# Check if there is an AAAA / IPv6 result for this host:
socket.getaddrinfo(HOST, PORT, socket.AF_INET6, socket.SOCK_STREAM, socket.IPPROTO_IP, socket.AI_CANONNAME)
if DEBUG: logging.debug("IPv6 address found for %s", HOST)
if preferipv6:
ipv4delay=0.1 # preferipv6, AND at least one IPv6 found, so give IPv4 (!) a delay so that IPv6 has a head start and is preferred
except:
if DEBUG: logging.debug("No IPv6 address found for %s", HOST)
myqueue = Queue.Queue() # queue used for threads giving back the results
try:
# Get all IP (IPv4 and IPv6) addresses:
allinfo = socket.getaddrinfo(HOST, PORT, 0, 0, socket.IPPROTO_TCP)
for info in allinfo:
address = info[4][0]
thisthread = threading.Thread(target=do_socket_connect, args=(myqueue, address, PORT, SSL, ipv4delay))
thisthread.daemon = True
thisthread.start()
result = None # default return value, used if none of threads says True/"OK", so no connect on any IP address
# start reading from the Queue for message from the threads:
for i in range(len(allinfo)):
s = myqueue.get() # get a response
if s[1] == True:
result = s[0]
break # the first True/"OK" is enough, so break out of for loop
except:
if DEBUG: logging.debug("something went wrong in the try block")
result = None
logging.info("Quickest IP address for %s (port %s, ssl %s, preferipv6 %s) is %s", HOST, PORT, SSL, preferipv6, result)
delay = int(1000 * (time.clock() - start))
logging.debug("Happy Eyeballs lookup and port connect took %s ms", delay)
# We're done. Store and return the result
if result:
happyeyeballs.happylist[hostkey] = ( result, timecurrent )
if DEBUG: logging.debug("Determined new result for %s with result %s", (hostkey, happyeyeballs.happylist[hostkey]) )
return result
allinfo = socket.getaddrinfo(HOST, PORT, 0, 0, socket.IPPROTO_TCP)
for info in allinfo:
address = info[4][0]
thisthread = threading.Thread(target=do_socket_connect, args=(myqueue, address, PORT, SSL, ipv4delay))
thisthread.daemon = True
thisthread.start()
result = None # default return value, used if none of threads says True/"OK", so no connect on any IP address
# start reading from the Queue for message from the threads:
for i in range(len(allinfo)):
s = myqueue.get() # get a response
if s[1] == True:
result = s[0]
break # the first True/"OK" is enough, so break out of for loop
except:
if DEBUG: logging.debug("something went wrong in the try block")
result = None
logging.info("Quickest IP address for %s (port %s, ssl %s, preferipv6 %s) is %s", HOST, PORT, SSL, preferipv6, result)
delay = int(1000 * (time.clock() - start))
logging.debug("Happy Eyeballs lookup and port connect took %s ms", delay)
# We're done. Store and return the result
if result:
happyeyeballs.happylist[hostkey] = ( result, timecurrent )
if DEBUG: logging.debug("Determined new result for %s with result %s", (hostkey, happyeyeballs.happylist[hostkey]) )
return result
happyeyeballs.happylist = {} # The cached results. This static variable must be after the def happyeyeballs()
@ -152,27 +152,27 @@ happyeyeballs.happylist = {} # The cached results. This static variable must
if __name__ == '__main__':
logger = logging.getLogger('')
logger.setLevel(logging.INFO)
if DEBUG: logger.setLevel(logging.DEBUG)
# plain HTTP/HTTPS sites:
print happyeyeballs('www.google.com')
print happyeyeballs('www.google.com', port=443, ssl=True)
print happyeyeballs('www.nu.nl')
# newsservers:
print happyeyeballs('newszilla6.xs4all.nl', port=119)
print happyeyeballs('newszilla.xs4all.nl', port=119)
print happyeyeballs('block.cheapnews.eu', port=119)
print happyeyeballs('block.cheapnews.eu', port=443, ssl=True)
print happyeyeballs('sslreader.eweka.nl', port=563, ssl=True)
print happyeyeballs('news.thundernews.com', port=119)
print happyeyeballs('news.thundernews.com', port=119, preferipv6=False)
print happyeyeballs('secure.eu.thundernews.com', port=563, ssl=True)
# Strange cases
print happyeyeballs('does.not.resolve', port=443, ssl=True)
print happyeyeballs('www.google.com', port=119)
print happyeyeballs('216.58.211.164')
logger = logging.getLogger('')
logger.setLevel(logging.INFO)
if DEBUG: logger.setLevel(logging.DEBUG)
# plain HTTP/HTTPS sites:
print happyeyeballs('www.google.com')
print happyeyeballs('www.google.com', port=443, ssl=True)
print happyeyeballs('www.nu.nl')
# newsservers:
print happyeyeballs('newszilla6.xs4all.nl', port=119)
print happyeyeballs('newszilla.xs4all.nl', port=119)
print happyeyeballs('block.cheapnews.eu', port=119)
print happyeyeballs('block.cheapnews.eu', port=443, ssl=True)
print happyeyeballs('sslreader.eweka.nl', port=563, ssl=True)
print happyeyeballs('news.thundernews.com', port=119)
print happyeyeballs('news.thundernews.com', port=119, preferipv6=False)
print happyeyeballs('secure.eu.thundernews.com', port=563, ssl=True)
# Strange cases
print happyeyeballs('does.not.resolve', port=443, ssl=True)
print happyeyeballs('www.google.com', port=119)
print happyeyeballs('216.58.211.164')

2
sabnzbd/utils/pystone.py

@ -236,7 +236,7 @@ def Func2(StrParI1, StrParI2):
if Func1(StrParI1[IntLoc], StrParI2[IntLoc+1]) == Ident1:
CharLoc = 'A'
IntLoc = IntLoc + 1
if CharLoc >= 'W' and CharLoc <= 'Z':
if 'W' <= CharLoc <= 'Z':
IntLoc = 7
if CharLoc == 'X':
return TRUE

4
sabnzbd/utils/servertests.py

@ -90,7 +90,7 @@ def test_nntp_server(host, port, server=None, username=None, password=None, ssl=
nw.recv_chunk(block=True)
nw.finish_connect(nw.status_code)
except socket.timeout, e:
except socket.timeout:
if port != 119 and not ssl:
return False, T('Timed out: Try enabling SSL or connecting on a different port.')
else:
@ -103,7 +103,7 @@ def test_nntp_server(host, port, server=None, username=None, password=None, ssl=
return False, unicode(e)
except TypeError, e:
except TypeError:
return False, T('Invalid server address.')
except IndexError:

5
sabnzbd/zconfig.py

@ -79,11 +79,6 @@ def set_bonjour(host=None, port=None):
return
name = hostname()
if '.local' in name:
suffix = ''
else:
suffix = '.local'
logging.debug('Try to publish in Bonjour as "%s" (%s:%s)', name, host, port)
try:
refObject = pybonjour.DNSServiceRegister(

1
tests/conftest.py

@ -21,7 +21,6 @@ tests.conftest - Wrappers to start SABnzbd for testing
import os
import itertools
import urllib2
import pytest
import shutil
import time

2
util/apireg.py

@ -69,7 +69,7 @@ def set_connection_info(url, user=True):
try:
hive = _winreg.ConnectRegistry(None, section)
try:
key = _winreg.CreateKey(hive, keypath)
_winreg.CreateKey(hive, keypath)
except:
pass
key = _winreg.OpenKey(hive, keypath)

1
util/mailslot.py

@ -19,7 +19,6 @@
sabnzbd.mailslot - Mailslot communication
"""
import os
from win32file import GENERIC_WRITE, FILE_SHARE_READ, \
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL
from ctypes import c_uint, c_buffer, byref, sizeof, windll

Loading…
Cancel
Save