Make proxy detection more robust on windows and OS X. calibre now queries OS X Network Settigns if no environment variables are set. Also handle proxies with a trailing slash correctly.

This commit is contained in:
Kovid Goyal 2010-05-07 22:30:13 -06:00
parent 8c80d91ae9
commit 6b79a732b1

View File

@ -4,6 +4,7 @@ __copyright__ = '2008, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import sys, os, re, logging, time, mimetypes, \
__builtin__, warnings, multiprocessing
from urllib import getproxies
__builtin__.__dict__['dynamic_property'] = lambda(func): func(None)
from htmlentitydefs import name2codepoint
from math import floor
@ -199,46 +200,29 @@ def extract(path, dir):
extractor(path, dir)
def get_proxies(debug=True):
proxies = {}
for q in ('http', 'ftp'):
proxy = os.environ.get(q+'_proxy', None)
if not proxy: continue
if proxy.startswith(q+'://'):
proxy = proxy[7:]
proxies[q] = proxy
if iswindows:
try:
winreg = __import__('_winreg')
settings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
'Software\\Microsoft\\Windows'
'\\CurrentVersion\\Internet Settings')
proxy = winreg.QueryValueEx(settings, "ProxyEnable")[0]
if proxy:
server = str(winreg.QueryValueEx(settings, 'ProxyServer')[0])
if ';' in server:
for p in server.split(';'):
protocol, address = p.split('=')
proxies[protocol] = address
proxies = getproxies()
for key, proxy in list(proxies.items()):
if not proxy:
del proxies[key]
continue
if proxy.startswith(key+'://'):
proxy = proxy[len(key)+3:]
if proxy.endswith('/'):
proxy = proxy[:-1]
if len(proxy) > 4:
proxies[key] = proxy
else:
proxies['http'] = server
proxies['ftp'] = server
settings.Close()
except Exception, e:
prints('Unable to detect proxy settings: %s' % str(e))
for x in list(proxies):
if len(proxies[x]) < 5:
prints('Removing invalid', x, 'proxy:', proxies[x])
del proxies[x]
prints('Removing invalid', key, 'proxy:', proxy)
del proxies[key]
if proxies and debug:
prints('Using proxies:', proxies)
return proxies
def get_parsed_proxy(typ='http', debug=True):
proxies = get_proxies(debug)
if typ not in proxies:
return
proxy = proxies.get(typ, None)
if proxy:
pattern = re.compile((
'(?:ptype://)?' \
'(?:(?P<user>\w+):(?P<pass>.*)@)?' \
@ -246,7 +230,7 @@ def get_parsed_proxy(typ='http', debug=True):
'(?::(?P<port>\d+))?').replace('ptype', typ)
)
match = pattern.match(proxies['typ'])
match = pattern.match(proxies[typ])
if match:
try:
ans = {
@ -260,9 +244,9 @@ def get_parsed_proxy(typ='http', debug=True):
except:
if debug:
traceback.print_exc()
return
else:
if debug:
prints('Using http proxy', ans)
prints('Using http proxy', str(ans))
return ans