home *** CD-ROM | disk | FTP | other *** search
/ Chip 2011 November / CHIP_2011_11.iso / Programy / Narzedzia / Calibre / calibre-0.8.18.msi / file_262 / urllib.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2011-09-09  |  40.3 KB  |  1,551 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.7)
  3.  
  4. import string
  5. import socket
  6. import os
  7. import time
  8. import sys
  9. from urlparse import urljoin as basejoin
  10. __all__ = [
  11.     'urlopen',
  12.     'URLopener',
  13.     'FancyURLopener',
  14.     'urlretrieve',
  15.     'urlcleanup',
  16.     'quote',
  17.     'quote_plus',
  18.     'unquote',
  19.     'unquote_plus',
  20.     'urlencode',
  21.     'url2pathname',
  22.     'pathname2url',
  23.     'splittag',
  24.     'localhost',
  25.     'thishost',
  26.     'ftperrors',
  27.     'basejoin',
  28.     'unwrap',
  29.     'splittype',
  30.     'splithost',
  31.     'splituser',
  32.     'splitpasswd',
  33.     'splitport',
  34.     'splitnport',
  35.     'splitquery',
  36.     'splitattr',
  37.     'splitvalue',
  38.     'getproxies']
  39. __version__ = '1.17'
  40. MAXFTPCACHE = 10
  41. if os.name == 'nt':
  42.     from nturl2path import url2pathname, pathname2url
  43. elif os.name == 'riscos':
  44.     from rourl2path import url2pathname, pathname2url
  45. else:
  46.     
  47.     def url2pathname(pathname):
  48.         return unquote(pathname)
  49.  
  50.     
  51.     def pathname2url(pathname):
  52.         return quote(pathname)
  53.  
  54. _urlopener = None
  55.  
  56. def urlopen(url, data = None, proxies = None):
  57.     global _urlopener
  58.     warnpy3k = warnpy3k
  59.     import warnings
  60.     warnpy3k('urllib.urlopen() has been removed in Python 3.0 in favor of urllib2.urlopen()', stacklevel = 2)
  61.     if proxies is not None:
  62.         opener = FancyURLopener(proxies = proxies)
  63.     elif not _urlopener:
  64.         opener = FancyURLopener()
  65.         _urlopener = opener
  66.     else:
  67.         opener = _urlopener
  68.     if data is None:
  69.         return opener.open(url)
  70.     return None.open(url, data)
  71.  
  72.  
  73. def urlretrieve(url, filename = None, reporthook = None, data = None):
  74.     global _urlopener
  75.     if not _urlopener:
  76.         _urlopener = FancyURLopener()
  77.     return _urlopener.retrieve(url, filename, reporthook, data)
  78.  
  79.  
  80. def urlcleanup():
  81.     if _urlopener:
  82.         _urlopener.cleanup()
  83.     _safe_quoters.clear()
  84.     ftpcache.clear()
  85.  
  86.  
  87. try:
  88.     import ssl
  89. except:
  90.     _have_ssl = False
  91.  
  92. _have_ssl = True
  93.  
  94. class ContentTooShortError(IOError):
  95.     
  96.     def __init__(self, message, content):
  97.         IOError.__init__(self, message)
  98.         self.content = content
  99.  
  100.  
  101. ftpcache = { }
  102.  
  103. class URLopener:
  104.     __tempfiles = None
  105.     version = 'Python-urllib/%s' % __version__
  106.     
  107.     def __init__(self, proxies = None, **x509):
  108.         if proxies is None:
  109.             proxies = getproxies()
  110.         self.proxies = proxies
  111.         self.key_file = x509.get('key_file')
  112.         self.cert_file = x509.get('cert_file')
  113.         self.addheaders = [
  114.             ('User-Agent', self.version)]
  115.         self._URLopener__tempfiles = []
  116.         self._URLopener__unlink = os.unlink
  117.         self.tempcache = None
  118.         self.ftpcache = ftpcache
  119.  
  120.     
  121.     def __del__(self):
  122.         self.close()
  123.  
  124.     
  125.     def close(self):
  126.         self.cleanup()
  127.  
  128.     
  129.     def cleanup(self):
  130.         if self._URLopener__tempfiles:
  131.             for file in self._URLopener__tempfiles:
  132.                 
  133.                 try:
  134.                     self._URLopener__unlink(file)
  135.                 continue
  136.                 except OSError:
  137.                     continue
  138.                 
  139.  
  140.             
  141.             del self._URLopener__tempfiles[:]
  142.         if self.tempcache:
  143.             self.tempcache.clear()
  144.  
  145.     
  146.     def addheader(self, *args):
  147.         self.addheaders.append(args)
  148.  
  149.     
  150.     def open(self, fullurl, data = None):
  151.         fullurl = unwrap(toBytes(fullurl))
  152.         fullurl = quote(fullurl, safe = "%/:=&?~#+!$,;'@()*[]|")
  153.         if self.tempcache and fullurl in self.tempcache:
  154.             (filename, headers) = self.tempcache[fullurl]
  155.             fp = open(filename, 'rb')
  156.             return addinfourl(fp, headers, fullurl)
  157.         (urltype, url) = None(fullurl)
  158.         if not urltype:
  159.             urltype = 'file'
  160.         if urltype in self.proxies:
  161.             proxy = self.proxies[urltype]
  162.             (urltype, proxyhost) = splittype(proxy)
  163.             (host, selector) = splithost(proxyhost)
  164.             url = (host, fullurl)
  165.         else:
  166.             proxy = None
  167.         name = 'open_' + urltype
  168.         self.type = urltype
  169.         name = name.replace('-', '_')
  170.         if not hasattr(self, name):
  171.             if proxy:
  172.                 return self.open_unknown_proxy(proxy, fullurl, data)
  173.             return None.open_unknown(fullurl, data)
  174.         
  175.         try:
  176.             if data is None:
  177.                 return getattr(self, name)(url)
  178.             return None(self, name)(url, data)
  179.         except socket.error:
  180.             msg = None
  181.             raise IOError, ('socket error', msg), sys.exc_info()[2]
  182.  
  183.  
  184.     
  185.     def open_unknown(self, fullurl, data = None):
  186.         (type, url) = splittype(fullurl)
  187.         raise IOError, ('url error', 'unknown url type', type)
  188.  
  189.     
  190.     def open_unknown_proxy(self, proxy, fullurl, data = None):
  191.         (type, url) = splittype(fullurl)
  192.         raise IOError, ('url error', 'invalid proxy for %s' % type, proxy)
  193.  
  194.     
  195.     def retrieve(self, url, filename = None, reporthook = None, data = None):
  196.         url = unwrap(toBytes(url))
  197.         if self.tempcache and url in self.tempcache:
  198.             return self.tempcache[url]
  199.         (type, url1) = None(url)
  200.         if filename is None:
  201.             if not type or type == 'file':
  202.                 
  203.                 try:
  204.                     fp = self.open_local_file(url1)
  205.                     hdrs = fp.info()
  206.                     fp.close()
  207.                     return (url2pathname(splithost(url1)[1]), hdrs)
  208.                 except IOError:
  209.                     pass
  210.                 
  211.  
  212.         fp = self.open(url, data)
  213.         
  214.         try:
  215.             headers = fp.info()
  216.             if filename:
  217.                 tfp = open(filename, 'wb')
  218.             else:
  219.                 import tempfile
  220.                 (garbage, path) = splittype(url)
  221.                 if not path:
  222.                     pass
  223.                 (garbage, path) = splithost('')
  224.                 if not path:
  225.                     pass
  226.                 (path, garbage) = splitquery('')
  227.                 if not path:
  228.                     pass
  229.                 (path, garbage) = splitattr('')
  230.                 suffix = os.path.splitext(path)[1]
  231.                 (fd, filename) = tempfile.mkstemp(suffix)
  232.                 self._URLopener__tempfiles.append(filename)
  233.                 tfp = os.fdopen(fd, 'wb')
  234.             
  235.             try:
  236.                 result = (filename, headers)
  237.                 if self.tempcache is not None:
  238.                     self.tempcache[url] = result
  239.                 bs = 8192
  240.                 size = -1
  241.                 read = 0
  242.                 blocknum = 0
  243.                 if reporthook:
  244.                     if 'content-length' in headers:
  245.                         size = int(headers['Content-Length'])
  246.                     reporthook(blocknum, bs, size)
  247.                 while None:
  248.                     block = fp.read(bs)
  249.                     if block == '':
  250.                         break
  251.                     read += len(block)
  252.                     blocknum += 1
  253.                     if reporthook:
  254.                         reporthook(blocknum, bs, size)
  255.                         continue
  256.                     tfp.close()
  257.                 fp.close()
  258.                 if size >= 0 and read < size:
  259.                     raise ContentTooShortError('retrieval incomplete: got only %i out of %i bytes' % (read, size), result)
  260.                 return result
  261.  
  262.  
  263.  
  264.     
  265.     def open_http(self, url, data = None):
  266.         import httplib
  267.         user_passwd = None
  268.         proxy_passwd = None
  269.         if isinstance(url, str):
  270.             (host, selector) = splithost(url)
  271.             if host:
  272.                 (user_passwd, host) = splituser(host)
  273.                 host = unquote(host)
  274.             realhost = host
  275.         else:
  276.             (host, selector) = url
  277.             (proxy_passwd, host) = splituser(host)
  278.             (urltype, rest) = splittype(selector)
  279.             url = rest
  280.             user_passwd = None
  281.             if urltype.lower() != 'http':
  282.                 realhost = None
  283.             else:
  284.                 (realhost, rest) = splithost(rest)
  285.                 if realhost:
  286.                     (user_passwd, realhost) = splituser(realhost)
  287.                 if user_passwd:
  288.                     selector = '%s://%s%s' % (urltype, realhost, rest)
  289.                 if proxy_bypass(realhost):
  290.                     host = realhost
  291.         if not host:
  292.             raise IOError, ('http error', 'no host given')
  293.         if proxy_passwd:
  294.             import base64
  295.             proxy_auth = base64.b64encode(proxy_passwd).strip()
  296.         else:
  297.             proxy_auth = None
  298.         if user_passwd:
  299.             import base64
  300.             auth = base64.b64encode(user_passwd).strip()
  301.         else:
  302.             auth = None
  303.         h = httplib.HTTP(host)
  304.         if data is not None:
  305.             h.putrequest('POST', selector)
  306.             h.putheader('Content-Type', 'application/x-www-form-urlencoded')
  307.             h.putheader('Content-Length', '%d' % len(data))
  308.         else:
  309.             h.putrequest('GET', selector)
  310.         if proxy_auth:
  311.             h.putheader('Proxy-Authorization', 'Basic %s' % proxy_auth)
  312.         if auth:
  313.             h.putheader('Authorization', 'Basic %s' % auth)
  314.         if realhost:
  315.             h.putheader('Host', realhost)
  316.         for args in self.addheaders:
  317.             h.putheader(*args)
  318.         
  319.         h.endheaders(data)
  320.         (errcode, errmsg, headers) = h.getreply()
  321.         fp = h.getfile()
  322.         if errcode == -1:
  323.             if fp:
  324.                 fp.close()
  325.             raise IOError, ('http protocol error', 0, 'got a bad status line', None)
  326.         if errcode <= errcode:
  327.             pass
  328.         elif errcode < 300:
  329.             return addinfourl(fp, headers, 'http:' + url, errcode)
  330.         if data is None:
  331.             return self.http_error(url, fp, errcode, errmsg, headers)
  332.         return None.http_error(url, fp, errcode, errmsg, headers, data)
  333.  
  334.     
  335.     def http_error(self, url, fp, errcode, errmsg, headers, data = None):
  336.         name = 'http_error_%d' % errcode
  337.         if hasattr(self, name):
  338.             method = getattr(self, name)
  339.             if data is None:
  340.                 result = method(url, fp, errcode, errmsg, headers)
  341.             else:
  342.                 result = method(url, fp, errcode, errmsg, headers, data)
  343.             if result:
  344.                 return result
  345.         return self.http_error_default(url, fp, errcode, errmsg, headers)
  346.  
  347.     
  348.     def http_error_default(self, url, fp, errcode, errmsg, headers):
  349.         void = fp.read()
  350.         fp.close()
  351.         raise IOError, ('http error', errcode, errmsg, headers)
  352.  
  353.     if _have_ssl:
  354.         
  355.         def open_https(self, url, data = None):
  356.             import httplib
  357.             user_passwd = None
  358.             proxy_passwd = None
  359.             if isinstance(url, str):
  360.                 (host, selector) = splithost(url)
  361.                 if host:
  362.                     (user_passwd, host) = splituser(host)
  363.                     host = unquote(host)
  364.                 realhost = host
  365.             else:
  366.                 (host, selector) = url
  367.                 (proxy_passwd, host) = splituser(host)
  368.                 (urltype, rest) = splittype(selector)
  369.                 url = rest
  370.                 user_passwd = None
  371.                 if urltype.lower() != 'https':
  372.                     realhost = None
  373.                 else:
  374.                     (realhost, rest) = splithost(rest)
  375.                     if realhost:
  376.                         (user_passwd, realhost) = splituser(realhost)
  377.                     if user_passwd:
  378.                         selector = '%s://%s%s' % (urltype, realhost, rest)
  379.             if not host:
  380.                 raise IOError, ('https error', 'no host given')
  381.             if proxy_passwd:
  382.                 import base64
  383.                 proxy_auth = base64.b64encode(proxy_passwd).strip()
  384.             else:
  385.                 proxy_auth = None
  386.             if user_passwd:
  387.                 import base64
  388.                 auth = base64.b64encode(user_passwd).strip()
  389.             else:
  390.                 auth = None
  391.             h = httplib.HTTPS(host, 0, key_file = self.key_file, cert_file = self.cert_file)
  392.             if data is not None:
  393.                 h.putrequest('POST', selector)
  394.                 h.putheader('Content-Type', 'application/x-www-form-urlencoded')
  395.                 h.putheader('Content-Length', '%d' % len(data))
  396.             else:
  397.                 h.putrequest('GET', selector)
  398.             if proxy_auth:
  399.                 h.putheader('Proxy-Authorization', 'Basic %s' % proxy_auth)
  400.             if auth:
  401.                 h.putheader('Authorization', 'Basic %s' % auth)
  402.             if realhost:
  403.                 h.putheader('Host', realhost)
  404.             for args in self.addheaders:
  405.                 h.putheader(*args)
  406.             
  407.             h.endheaders(data)
  408.             (errcode, errmsg, headers) = h.getreply()
  409.             fp = h.getfile()
  410.             if errcode == -1:
  411.                 if fp:
  412.                     fp.close()
  413.                 raise IOError, ('http protocol error', 0, 'got a bad status line', None)
  414.             if errcode <= errcode:
  415.                 pass
  416.             elif errcode < 300:
  417.                 return addinfourl(fp, headers, 'https:' + url, errcode)
  418.             if data is None:
  419.                 return self.http_error(url, fp, errcode, errmsg, headers)
  420.             return None.http_error(url, fp, errcode, errmsg, headers, data)
  421.  
  422.     
  423.     def open_file(self, url):
  424.         if not isinstance(url, str):
  425.             raise IOError, ('file error', 'proxy support for file protocol currently not implemented')
  426.         if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
  427.             return self.open_ftp(url)
  428.         return None.open_local_file(url)
  429.  
  430.     
  431.     def open_local_file(self, url):
  432.         import mimetypes
  433.         import mimetools
  434.         import email.utils as email
  435.         
  436.         try:
  437.             StringIO = StringIO
  438.             import cStringIO
  439.         except ImportError:
  440.             StringIO = StringIO
  441.             import StringIO
  442.  
  443.         (host, file) = splithost(url)
  444.         localname = url2pathname(file)
  445.         
  446.         try:
  447.             stats = os.stat(localname)
  448.         except OSError:
  449.             e = None
  450.             raise IOError(e.errno, e.strerror, e.filename)
  451.  
  452.         size = stats.st_size
  453.         modified = email.utils.formatdate(stats.st_mtime, usegmt = True)
  454.         mtype = mimetypes.guess_type(url)[0]
  455.         if not mtype:
  456.             pass
  457.         headers = mimetools.Message(StringIO('Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' % ('text/plain', size, modified)))
  458.         if not host:
  459.             urlfile = file
  460.             if file[:1] == '/':
  461.                 urlfile = 'file://' + file
  462.             return addinfourl(open(localname, 'rb'), headers, urlfile)
  463.         (host, port) = None(host)
  464.         if not port and socket.gethostbyname(host) in (localhost(), thishost()):
  465.             urlfile = file
  466.             if file[:1] == '/':
  467.                 urlfile = 'file://' + file
  468.             return addinfourl(open(localname, 'rb'), headers, urlfile)
  469.         raise None, ('local file error', 'not on local host')
  470.  
  471.     
  472.     def open_ftp(self, url):
  473.         if not isinstance(url, str):
  474.             raise IOError, ('ftp error', 'proxy support for ftp protocol currently not implemented')
  475.         import mimetypes
  476.         import mimetools
  477.         
  478.         try:
  479.             StringIO = StringIO
  480.             import cStringIO
  481.         except ImportError:
  482.             StringIO = StringIO
  483.             import StringIO
  484.  
  485.         (host, path) = splithost(url)
  486.         if not host:
  487.             raise IOError, ('ftp error', 'no host given')
  488.         (host, port) = splitport(host)
  489.         (user, host) = splituser(host)
  490.         if user:
  491.             (user, passwd) = splitpasswd(user)
  492.         else:
  493.             passwd = None
  494.         host = unquote(host)
  495.         if not user:
  496.             pass
  497.         user = ''
  498.         if not passwd:
  499.             pass
  500.         passwd = ''
  501.         host = socket.gethostbyname(host)
  502.         if not port:
  503.             import ftplib
  504.             port = ftplib.FTP_PORT
  505.         else:
  506.             port = int(port)
  507.         (path, attrs) = splitattr(path)
  508.         path = unquote(path)
  509.         dirs = path.split('/')
  510.         dirs = dirs[:-1]
  511.         file = dirs[-1]
  512.         if dirs and not dirs[0]:
  513.             dirs = dirs[1:]
  514.         if dirs and not dirs[0]:
  515.             dirs[0] = '/'
  516.         key = (user, host, port, '/'.join(dirs))
  517.         if len(self.ftpcache) > MAXFTPCACHE:
  518.             for k in self.ftpcache.keys():
  519.                 if k != key:
  520.                     v = self.ftpcache[k]
  521.                     del self.ftpcache[k]
  522.                     v.close()
  523.                     continue
  524.         
  525.         try:
  526.             if key not in self.ftpcache:
  527.                 self.ftpcache[key] = ftpwrapper(user, passwd, host, port, dirs)
  528.             if not file:
  529.                 type = 'D'
  530.             else:
  531.                 type = 'I'
  532.             for attr in attrs:
  533.                 (attr, value) = splitvalue(attr)
  534.                 if attr.lower() == 'type' and value in ('a', 'A', 'i', 'I', 'd', 'D'):
  535.                     type = value.upper()
  536.                     continue
  537.             (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
  538.             mtype = mimetypes.guess_type('ftp:' + url)[0]
  539.             headers = ''
  540.             if mtype:
  541.                 headers += 'Content-Type: %s\n' % mtype
  542.             if retrlen is not None and retrlen >= 0:
  543.                 headers += 'Content-Length: %d\n' % retrlen
  544.             headers = mimetools.Message(StringIO(headers))
  545.             return addinfourl(fp, headers, 'ftp:' + url)
  546.         except ftperrors():
  547.             msg = None
  548.             raise IOError, ('ftp error', msg), sys.exc_info()[2]
  549.  
  550.  
  551.     
  552.     def open_data(self, url, data = None):
  553.         if not isinstance(url, str):
  554.             raise IOError, ('data error', 'proxy support for data protocol currently not implemented')
  555.         import mimetools
  556.         
  557.         try:
  558.             StringIO = StringIO
  559.             import cStringIO
  560.         except ImportError:
  561.             StringIO = StringIO
  562.             import StringIO
  563.  
  564.         
  565.         try:
  566.             (type, data) = url.split(',', 1)
  567.         except ValueError:
  568.             raise IOError, ('data error', 'bad data URL')
  569.  
  570.         if not type:
  571.             type = 'text/plain;charset=US-ASCII'
  572.         semi = type.rfind(';')
  573.         if semi >= 0 and '=' not in type[semi:]:
  574.             encoding = type[semi + 1:]
  575.             type = type[:semi]
  576.         else:
  577.             encoding = ''
  578.         msg = []
  579.         msg.append('Date: %s' % time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(time.time())))
  580.         msg.append('Content-type: %s' % type)
  581.         if encoding == 'base64':
  582.             import base64
  583.             data = base64.decodestring(data)
  584.         else:
  585.             data = unquote(data)
  586.         msg.append('Content-Length: %d' % len(data))
  587.         msg.append('')
  588.         msg.append(data)
  589.         msg = '\n'.join(msg)
  590.         f = StringIO(msg)
  591.         headers = mimetools.Message(f, 0)
  592.         return addinfourl(f, headers, url)
  593.  
  594.  
  595.  
  596. class FancyURLopener(URLopener):
  597.     
  598.     def __init__(self, *args, **kwargs):
  599.         URLopener.__init__(self, *args, **kwargs)
  600.         self.auth_cache = { }
  601.         self.tries = 0
  602.         self.maxtries = 10
  603.  
  604.     
  605.     def http_error_default(self, url, fp, errcode, errmsg, headers):
  606.         return addinfourl(fp, headers, 'http:' + url, errcode)
  607.  
  608.     
  609.     def http_error_302(self, url, fp, errcode, errmsg, headers, data = None):
  610.         self.tries += 1
  611.         if self.maxtries and self.tries >= self.maxtries:
  612.             self.tries = 0
  613.             return meth(url, fp, 500, 'Internal Server Error: Redirect Recursion', headers)
  614.         result = self.redirect_internal(url, fp, errcode, errmsg, headers, data)
  615.         self.tries = 0
  616.         return result
  617.  
  618.     
  619.     def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
  620.         if 'location' in headers:
  621.             newurl = headers['location']
  622.         elif 'uri' in headers:
  623.             newurl = headers['uri']
  624.         else:
  625.             return None
  626.         void = None.read()
  627.         fp.close()
  628.         newurl = basejoin(self.type + ':' + url, newurl)
  629.         return self.open(newurl)
  630.  
  631.     
  632.     def http_error_301(self, url, fp, errcode, errmsg, headers, data = None):
  633.         return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  634.  
  635.     
  636.     def http_error_303(self, url, fp, errcode, errmsg, headers, data = None):
  637.         return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  638.  
  639.     
  640.     def http_error_307(self, url, fp, errcode, errmsg, headers, data = None):
  641.         if data is None:
  642.             return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  643.         return None.http_error_default(url, fp, errcode, errmsg, headers)
  644.  
  645.     
  646.     def http_error_401(self, url, fp, errcode, errmsg, headers, data = None):
  647.         if 'www-authenticate' not in headers:
  648.             URLopener.http_error_default(self, url, fp, errcode, errmsg, headers)
  649.         stuff = headers['www-authenticate']
  650.         import re
  651.         match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
  652.         if not match:
  653.             URLopener.http_error_default(self, url, fp, errcode, errmsg, headers)
  654.         (scheme, realm) = match.groups()
  655.         if scheme.lower() != 'basic':
  656.             URLopener.http_error_default(self, url, fp, errcode, errmsg, headers)
  657.         name = 'retry_' + self.type + '_basic_auth'
  658.         if data is None:
  659.             return getattr(self, name)(url, realm)
  660.         return None(self, name)(url, realm, data)
  661.  
  662.     
  663.     def http_error_407(self, url, fp, errcode, errmsg, headers, data = None):
  664.         if 'proxy-authenticate' not in headers:
  665.             URLopener.http_error_default(self, url, fp, errcode, errmsg, headers)
  666.         stuff = headers['proxy-authenticate']
  667.         import re
  668.         match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
  669.         if not match:
  670.             URLopener.http_error_default(self, url, fp, errcode, errmsg, headers)
  671.         (scheme, realm) = match.groups()
  672.         if scheme.lower() != 'basic':
  673.             URLopener.http_error_default(self, url, fp, errcode, errmsg, headers)
  674.         name = 'retry_proxy_' + self.type + '_basic_auth'
  675.         if data is None:
  676.             return getattr(self, name)(url, realm)
  677.         return None(self, name)(url, realm, data)
  678.  
  679.     
  680.     def retry_proxy_http_basic_auth(self, url, realm, data = None):
  681.         (host, selector) = splithost(url)
  682.         newurl = 'http://' + host + selector
  683.         proxy = self.proxies['http']
  684.         (urltype, proxyhost) = splittype(proxy)
  685.         (proxyhost, proxyselector) = splithost(proxyhost)
  686.         i = proxyhost.find('@') + 1
  687.         proxyhost = proxyhost[i:]
  688.         (user, passwd) = self.get_user_passwd(proxyhost, realm, i)
  689.         if not user or passwd:
  690.             return None
  691.         proxyhost = None(user, safe = '') + ':' + quote(passwd, safe = '') + '@' + proxyhost
  692.         self.proxies['http'] = 'http://' + proxyhost + proxyselector
  693.         if data is None:
  694.             return self.open(newurl)
  695.         return None.open(newurl, data)
  696.  
  697.     
  698.     def retry_proxy_https_basic_auth(self, url, realm, data = None):
  699.         (host, selector) = splithost(url)
  700.         newurl = 'https://' + host + selector
  701.         proxy = self.proxies['https']
  702.         (urltype, proxyhost) = splittype(proxy)
  703.         (proxyhost, proxyselector) = splithost(proxyhost)
  704.         i = proxyhost.find('@') + 1
  705.         proxyhost = proxyhost[i:]
  706.         (user, passwd) = self.get_user_passwd(proxyhost, realm, i)
  707.         if not user or passwd:
  708.             return None
  709.         proxyhost = None(user, safe = '') + ':' + quote(passwd, safe = '') + '@' + proxyhost
  710.         self.proxies['https'] = 'https://' + proxyhost + proxyselector
  711.         if data is None:
  712.             return self.open(newurl)
  713.         return None.open(newurl, data)
  714.  
  715.     
  716.     def retry_http_basic_auth(self, url, realm, data = None):
  717.         (host, selector) = splithost(url)
  718.         i = host.find('@') + 1
  719.         host = host[i:]
  720.         (user, passwd) = self.get_user_passwd(host, realm, i)
  721.         if not user or passwd:
  722.             return None
  723.         host = None(user, safe = '') + ':' + quote(passwd, safe = '') + '@' + host
  724.         newurl = 'http://' + host + selector
  725.         if data is None:
  726.             return self.open(newurl)
  727.         return None.open(newurl, data)
  728.  
  729.     
  730.     def retry_https_basic_auth(self, url, realm, data = None):
  731.         (host, selector) = splithost(url)
  732.         i = host.find('@') + 1
  733.         host = host[i:]
  734.         (user, passwd) = self.get_user_passwd(host, realm, i)
  735.         if not user or passwd:
  736.             return None
  737.         host = None(user, safe = '') + ':' + quote(passwd, safe = '') + '@' + host
  738.         newurl = 'https://' + host + selector
  739.         if data is None:
  740.             return self.open(newurl)
  741.         return None.open(newurl, data)
  742.  
  743.     
  744.     def get_user_passwd(self, host, realm, clear_cache = 0):
  745.         key = realm + '@' + host.lower()
  746.         if key in self.auth_cache:
  747.             if clear_cache:
  748.                 del self.auth_cache[key]
  749.             else:
  750.                 return self.auth_cache[key]
  751.         (user, passwd) = self.prompt_user_passwd(host, realm)
  752.         if user or passwd:
  753.             self.auth_cache[key] = (user, passwd)
  754.         return (user, passwd)
  755.  
  756.     
  757.     def prompt_user_passwd(self, host, realm):
  758.         import getpass
  759.         
  760.         try:
  761.             user = raw_input('Enter username for %s at %s: ' % (realm, host))
  762.             passwd = getpass.getpass('Enter password for %s in %s at %s: ' % (user, realm, host))
  763.             return (user, passwd)
  764.         except KeyboardInterrupt:
  765.             print 
  766.             return (None, None)
  767.  
  768.  
  769.  
  770. _localhost = None
  771.  
  772. def localhost():
  773.     global _localhost
  774.     if _localhost is None:
  775.         _localhost = socket.gethostbyname('localhost')
  776.     return _localhost
  777.  
  778. _thishost = None
  779.  
  780. def thishost():
  781.     global _thishost
  782.     if _thishost is None:
  783.         _thishost = socket.gethostbyname(socket.gethostname())
  784.     return _thishost
  785.  
  786. _ftperrors = None
  787.  
  788. def ftperrors():
  789.     global _ftperrors
  790.     if _ftperrors is None:
  791.         import ftplib
  792.         _ftperrors = ftplib.all_errors
  793.     return _ftperrors
  794.  
  795. _noheaders = None
  796.  
  797. def noheaders():
  798.     global _noheaders
  799.     if _noheaders is None:
  800.         import mimetools
  801.         
  802.         try:
  803.             StringIO = StringIO
  804.             import cStringIO
  805.         except ImportError:
  806.             StringIO = StringIO
  807.             import StringIO
  808.  
  809.         _noheaders = mimetools.Message(StringIO(), 0)
  810.         _noheaders.fp.close()
  811.     return _noheaders
  812.  
  813.  
  814. class ftpwrapper:
  815.     
  816.     def __init__(self, user, passwd, host, port, dirs, timeout = socket._GLOBAL_DEFAULT_TIMEOUT):
  817.         self.user = user
  818.         self.passwd = passwd
  819.         self.host = host
  820.         self.port = port
  821.         self.dirs = dirs
  822.         self.timeout = timeout
  823.         self.init()
  824.  
  825.     
  826.     def init(self):
  827.         import ftplib
  828.         self.busy = 0
  829.         self.ftp = ftplib.FTP()
  830.         self.ftp.connect(self.host, self.port, self.timeout)
  831.         self.ftp.login(self.user, self.passwd)
  832.         for dir in self.dirs:
  833.             self.ftp.cwd(dir)
  834.         
  835.  
  836.     
  837.     def retrfile(self, file, type):
  838.         import ftplib
  839.         self.endtransfer()
  840.         if type in ('d', 'D'):
  841.             cmd = 'TYPE A'
  842.             isdir = 1
  843.         else:
  844.             cmd = 'TYPE ' + type
  845.             isdir = 0
  846.         
  847.         try:
  848.             self.ftp.voidcmd(cmd)
  849.         except ftplib.all_errors:
  850.             self.init()
  851.             self.ftp.voidcmd(cmd)
  852.  
  853.         conn = None
  854.         if file and not isdir:
  855.             
  856.             try:
  857.                 cmd = 'RETR ' + file
  858.                 conn = self.ftp.ntransfercmd(cmd)
  859.             except ftplib.error_perm:
  860.                 reason = None
  861.                 if str(reason)[:3] != '550':
  862.                     raise IOError, ('ftp error', reason), sys.exc_info()[2]
  863.             
  864.  
  865.         if not conn:
  866.             self.ftp.voidcmd('TYPE A')
  867.             if file:
  868.                 pwd = self.ftp.pwd()
  869.                 
  870.                 try:
  871.                     self.ftp.cwd(file)
  872.                 except ftplib.error_perm:
  873.                     reason = None
  874.                     raise IOError, ('ftp error', reason), sys.exc_info()[2]
  875.                 finally:
  876.                     self.ftp.cwd(pwd)
  877.  
  878.                 cmd = 'LIST ' + file
  879.             else:
  880.                 cmd = 'LIST'
  881.             conn = self.ftp.ntransfercmd(cmd)
  882.         self.busy = 1
  883.         return (addclosehook(conn[0].makefile('rb'), self.endtransfer), conn[1])
  884.  
  885.     
  886.     def endtransfer(self):
  887.         if not self.busy:
  888.             return None
  889.         self.busy = None
  890.         
  891.         try:
  892.             self.ftp.voidresp()
  893.         except ftperrors():
  894.             pass
  895.  
  896.  
  897.     
  898.     def close(self):
  899.         self.endtransfer()
  900.         
  901.         try:
  902.             self.ftp.close()
  903.         except ftperrors():
  904.             pass
  905.  
  906.  
  907.  
  908.  
  909. class addbase:
  910.     
  911.     def __init__(self, fp):
  912.         self.fp = fp
  913.         self.read = self.fp.read
  914.         self.readline = self.fp.readline
  915.         if hasattr(self.fp, 'readlines'):
  916.             self.readlines = self.fp.readlines
  917.         if hasattr(self.fp, 'fileno'):
  918.             self.fileno = self.fp.fileno
  919.         else:
  920.             
  921.             self.fileno = lambda : pass
  922.         if hasattr(self.fp, '__iter__'):
  923.             self.__iter__ = self.fp.__iter__
  924.             if hasattr(self.fp, 'next'):
  925.                 self.next = self.fp.next
  926.             
  927.  
  928.     
  929.     def __repr__(self):
  930.         return '<%s at %r whose fp = %r>' % (self.__class__.__name__, id(self), self.fp)
  931.  
  932.     
  933.     def close(self):
  934.         self.read = None
  935.         self.readline = None
  936.         self.readlines = None
  937.         self.fileno = None
  938.         if self.fp:
  939.             self.fp.close()
  940.         self.fp = None
  941.  
  942.  
  943.  
  944. class addclosehook(addbase):
  945.     
  946.     def __init__(self, fp, closehook, *hookargs):
  947.         addbase.__init__(self, fp)
  948.         self.closehook = closehook
  949.         self.hookargs = hookargs
  950.  
  951.     
  952.     def close(self):
  953.         addbase.close(self)
  954.         if self.closehook:
  955.             self.closehook(*self.hookargs)
  956.             self.closehook = None
  957.             self.hookargs = None
  958.  
  959.  
  960.  
  961. class addinfo(addbase):
  962.     
  963.     def __init__(self, fp, headers):
  964.         addbase.__init__(self, fp)
  965.         self.headers = headers
  966.  
  967.     
  968.     def info(self):
  969.         return self.headers
  970.  
  971.  
  972.  
  973. class addinfourl(addbase):
  974.     
  975.     def __init__(self, fp, headers, url, code = None):
  976.         addbase.__init__(self, fp)
  977.         self.headers = headers
  978.         self.url = url
  979.         self.code = code
  980.  
  981.     
  982.     def info(self):
  983.         return self.headers
  984.  
  985.     
  986.     def getcode(self):
  987.         return self.code
  988.  
  989.     
  990.     def geturl(self):
  991.         return self.url
  992.  
  993.  
  994.  
  995. try:
  996.     unicode
  997. except NameError:
  998.     
  999.     def _is_unicode(x):
  1000.         return 0
  1001.  
  1002.  
  1003.  
  1004. def _is_unicode(x):
  1005.     return isinstance(x, unicode)
  1006.  
  1007.  
  1008. def toBytes(url):
  1009.     if _is_unicode(url):
  1010.         
  1011.         try:
  1012.             url = url.encode('ASCII')
  1013.         except UnicodeError:
  1014.             raise UnicodeError('URL ' + repr(url) + ' contains non-ASCII characters')
  1015.         
  1016.  
  1017.     return url
  1018.  
  1019.  
  1020. def unwrap(url):
  1021.     url = url.strip()
  1022.     if url[:1] == '<' and url[-1:] == '>':
  1023.         url = url[1:-1].strip()
  1024.     if url[:4] == 'URL:':
  1025.         url = url[4:].strip()
  1026.     return url
  1027.  
  1028. _typeprog = None
  1029.  
  1030. def splittype(url):
  1031.     global _typeprog
  1032.     if _typeprog is None:
  1033.         import re
  1034.         _typeprog = re.compile('^([^/:]+):')
  1035.     match = _typeprog.match(url)
  1036.     if match:
  1037.         scheme = match.group(1)
  1038.         return (scheme.lower(), url[len(scheme) + 1:])
  1039.     return (None, url)
  1040.  
  1041. _hostprog = None
  1042.  
  1043. def splithost(url):
  1044.     global _hostprog
  1045.     if _hostprog is None:
  1046.         import re
  1047.         _hostprog = re.compile('^//([^/?]*)(.*)$')
  1048.     match = _hostprog.match(url)
  1049.     if match:
  1050.         host_port = match.group(1)
  1051.         path = match.group(2)
  1052.         if path and not path.startswith('/'):
  1053.             path = '/' + path
  1054.         return (host_port, path)
  1055.     return (None, url)
  1056.  
  1057. _userprog = None
  1058.  
  1059. def splituser(host):
  1060.     global _userprog
  1061.     if _userprog is None:
  1062.         import re
  1063.         _userprog = re.compile('^(.*)@(.*)$')
  1064.     match = _userprog.match(host)
  1065.     if match:
  1066.         return match.group(1, 2)
  1067.     return (None, host)
  1068.  
  1069. _passwdprog = None
  1070.  
  1071. def splitpasswd(user):
  1072.     global _passwdprog
  1073.     if _passwdprog is None:
  1074.         import re
  1075.         _passwdprog = re.compile('^([^:]*):(.*)$', re.S)
  1076.     match = _passwdprog.match(user)
  1077.     if match:
  1078.         return match.group(1, 2)
  1079.     return (None, None)
  1080.  
  1081. _portprog = None
  1082.  
  1083. def splitport(host):
  1084.     global _portprog
  1085.     if _portprog is None:
  1086.         import re
  1087.         _portprog = re.compile('^(.*):([0-9]+)$')
  1088.     match = _portprog.match(host)
  1089.     if match:
  1090.         return match.group(1, 2)
  1091.     return (None, None)
  1092.  
  1093. _nportprog = None
  1094.  
  1095. def splitnport(host, defport = -1):
  1096.     global _nportprog
  1097.     if _nportprog is None:
  1098.         import re
  1099.         _nportprog = re.compile('^(.*):(.*)$')
  1100.     match = _nportprog.match(host)
  1101.     if match:
  1102.         (host, port) = match.group(1, 2)
  1103.         
  1104.         try:
  1105.             if not port:
  1106.                 raise ValueError, 'no digits'
  1107.             nport = int(port)
  1108.         except ValueError:
  1109.             nport = None
  1110.  
  1111.         return (host, nport)
  1112.     return (None, defport)
  1113.  
  1114. _queryprog = None
  1115.  
  1116. def splitquery(url):
  1117.     global _queryprog
  1118.     if _queryprog is None:
  1119.         import re
  1120.         _queryprog = re.compile('^(.*)\\?([^?]*)$')
  1121.     match = _queryprog.match(url)
  1122.     if match:
  1123.         return match.group(1, 2)
  1124.     return (None, None)
  1125.  
  1126. _tagprog = None
  1127.  
  1128. def splittag(url):
  1129.     global _tagprog
  1130.     if _tagprog is None:
  1131.         import re
  1132.         _tagprog = re.compile('^(.*)#([^#]*)$')
  1133.     match = _tagprog.match(url)
  1134.     if match:
  1135.         return match.group(1, 2)
  1136.     return (None, None)
  1137.  
  1138.  
  1139. def splitattr(url):
  1140.     words = url.split(';')
  1141.     return (words[0], words[1:])
  1142.  
  1143. _valueprog = None
  1144.  
  1145. def splitvalue(attr):
  1146.     global _valueprog
  1147.     if _valueprog is None:
  1148.         import re
  1149.         _valueprog = re.compile('^([^=]*)=(.*)$')
  1150.     match = _valueprog.match(attr)
  1151.     if match:
  1152.         return match.group(1, 2)
  1153.     return (None, None)
  1154.  
  1155. _hexdig = '0123456789ABCDEFabcdef'
  1156. _hextochr = dict((lambda .0: pass)(_hexdig))
  1157.  
  1158. def unquote(s):
  1159.     res = s.split('%')
  1160.     if len(res) == 1:
  1161.         return s
  1162.     s = None[0]
  1163.     for item in res[1:]:
  1164.         
  1165.         try:
  1166.             s += _hextochr[item[:2]] + item[2:]
  1167.         continue
  1168.         except KeyError:
  1169.             s += '%' + item
  1170.             continue
  1171.             except UnicodeDecodeError:
  1172.                 s += unichr(int(item[:2], 16)) + item[2:]
  1173.                 continue
  1174.             
  1175.         return s
  1176.  
  1177.  
  1178.  
  1179. def unquote_plus(s):
  1180.     s = s.replace('+', ' ')
  1181.     return unquote(s)
  1182.  
  1183. always_safe = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.-'
  1184. _safe_map = { }
  1185. for i, c in zip(xrange(256), str(bytearray(xrange(256)))):
  1186.     _safe_map[c] = c if i < 128 and c in always_safe else '%{:02X}'.format(i)
  1187.  
  1188. _safe_quoters = { }
  1189.  
  1190. def quote(s, safe = '/'):
  1191.     if not s:
  1192.         if s is None:
  1193.             raise TypeError('None object cannot be quoted')
  1194.         return s
  1195.     cachekey = (None, always_safe)
  1196.     
  1197.     try:
  1198.         (quoter, safe) = _safe_quoters[cachekey]
  1199.     except KeyError:
  1200.         safe_map = _safe_map.copy()
  1201.         safe_map.update([ (c, c) for c in safe ])
  1202.         quoter = safe_map.__getitem__
  1203.         safe = always_safe + safe
  1204.         _safe_quoters[cachekey] = (quoter, safe)
  1205.  
  1206.     if not s.rstrip(safe):
  1207.         return s
  1208.     return None.join(map(quoter, s))
  1209.  
  1210.  
  1211. def quote_plus(s, safe = ''):
  1212.     if ' ' in s:
  1213.         s = quote(s, safe + ' ')
  1214.         return s.replace(' ', '+')
  1215.     return None(s, safe)
  1216.  
  1217.  
  1218. def urlencode(query, doseq = 0):
  1219.     if hasattr(query, 'items'):
  1220.         query = query.items()
  1221.     else:
  1222.         
  1223.         try:
  1224.             if len(query) and not isinstance(query[0], tuple):
  1225.                 raise TypeError
  1226.         except TypeError:
  1227.             (ty, va, tb) = sys.exc_info()
  1228.             raise TypeError, 'not a valid non-string sequence or mapping object', tb
  1229.  
  1230.     l = []
  1231.     if not doseq:
  1232.         for k, v in query:
  1233.             k = quote_plus(str(k))
  1234.             v = quote_plus(str(v))
  1235.             l.append(k + '=' + v)
  1236.         
  1237.     else:
  1238.         for k, v in query:
  1239.             k = quote_plus(str(k))
  1240.             if isinstance(v, str):
  1241.                 v = quote_plus(v)
  1242.                 l.append(k + '=' + v)
  1243.                 continue
  1244.             if _is_unicode(v):
  1245.                 v = quote_plus(v.encode('ASCII', 'replace'))
  1246.                 l.append(k + '=' + v)
  1247.                 continue
  1248.             
  1249.             try:
  1250.                 len(v)
  1251.             except TypeError:
  1252.                 v = quote_plus(str(v))
  1253.                 l.append(k + '=' + v)
  1254.                 continue
  1255.  
  1256.             for elt in v:
  1257.                 l.append(k + '=' + quote_plus(str(elt)))
  1258.             
  1259.         
  1260.     return '&'.join(l)
  1261.  
  1262.  
  1263. def getproxies_environment():
  1264.     proxies = { }
  1265.     for name, value in os.environ.items():
  1266.         name = name.lower()
  1267.         if value and name[-6:] == '_proxy':
  1268.             proxies[name[:-6]] = value
  1269.             continue
  1270.     return proxies
  1271.  
  1272.  
  1273. def proxy_bypass_environment(host):
  1274.     if not os.environ.get('no_proxy', ''):
  1275.         pass
  1276.     no_proxy = os.environ.get('NO_PROXY', '')
  1277.     if no_proxy == '*':
  1278.         return 1
  1279.     (hostonly, port) = None(host)
  1280.     for name in no_proxy.split(','):
  1281.         if not name or hostonly.endswith(name):
  1282.             if host.endswith(name):
  1283.                 return 1
  1284.     return 0
  1285.  
  1286. if sys.platform == 'darwin':
  1287.     from _scproxy import _get_proxy_settings, _get_proxies
  1288.     
  1289.     def proxy_bypass_macosx_sysconf(host):
  1290.         import re
  1291.         import socket
  1292.         fnmatch = fnmatch
  1293.         import fnmatch
  1294.         (hostonly, port) = splitport(host)
  1295.         
  1296.         def ip2num(ipAddr):
  1297.             parts = ipAddr.split('.')
  1298.             parts = map(int, parts)
  1299.             if len(parts) != 4:
  1300.                 parts = parts + [
  1301.                     0,
  1302.                     0,
  1303.                     0,
  1304.                     0][:4]
  1305.             return parts[0] << 24 | parts[1] << 16 | parts[2] << 8 | parts[3]
  1306.  
  1307.         proxy_settings = _get_proxy_settings()
  1308.         if '.' not in host and proxy_settings['exclude_simple']:
  1309.             return True
  1310.         hostIP = None
  1311.         for value in proxy_settings.get('exceptions', ()):
  1312.             if not value:
  1313.                 continue
  1314.             m = re.match('(\\d+(?:\\.\\d+)*)(/\\d+)?', value)
  1315.             if m is not None:
  1316.                 if hostIP is None:
  1317.                     
  1318.                     try:
  1319.                         hostIP = socket.gethostbyname(hostonly)
  1320.                         hostIP = ip2num(hostIP)
  1321.                     except socket.error:
  1322.                         continue
  1323.                     
  1324.  
  1325.                 base = ip2num(m.group(1))
  1326.                 mask = m.group(2)
  1327.                 if mask is None:
  1328.                     mask = 8 * (m.group(1).count('.') + 1)
  1329.                 else:
  1330.                     mask = int(mask[1:])
  1331.                     mask = 32 - mask
  1332.                 if hostIP >> mask == base >> mask:
  1333.                     return True
  1334.             if fnmatch(host, value):
  1335.                 return True
  1336.         
  1337.         return False
  1338.  
  1339.     
  1340.     def getproxies_macosx_sysconf():
  1341.         return _get_proxies()
  1342.  
  1343.     
  1344.     def proxy_bypass(host):
  1345.         if getproxies_environment():
  1346.             return proxy_bypass_environment(host)
  1347.         return None(host)
  1348.  
  1349.     
  1350.     def getproxies():
  1351.         if not getproxies_environment():
  1352.             pass
  1353.         return getproxies_macosx_sysconf()
  1354.  
  1355. elif os.name == 'nt':
  1356.     
  1357.     def getproxies_registry():
  1358.         proxies = { }
  1359.         
  1360.         try:
  1361.             import _winreg
  1362.         except ImportError:
  1363.             return proxies
  1364.  
  1365.         
  1366.         try:
  1367.             internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings')
  1368.             proxyEnable = _winreg.QueryValueEx(internetSettings, 'ProxyEnable')[0]
  1369.             if proxyEnable:
  1370.                 proxyServer = str(_winreg.QueryValueEx(internetSettings, 'ProxyServer')[0])
  1371.                 if '=' in proxyServer:
  1372.                     for p in proxyServer.split(';'):
  1373.                         (protocol, address) = p.split('=', 1)
  1374.                         import re
  1375.                         if not re.match('^([^/:]+)://', address):
  1376.                             address = '%s://%s' % (protocol, address)
  1377.                         proxies[protocol] = address
  1378.                     
  1379.                 elif proxyServer[:5] == 'http:':
  1380.                     proxies['http'] = proxyServer
  1381.                 else:
  1382.                     proxies['http'] = 'http://%s' % proxyServer
  1383.                     proxies['https'] = 'https://%s' % proxyServer
  1384.                     proxies['ftp'] = 'ftp://%s' % proxyServer
  1385.             internetSettings.Close()
  1386.         except (WindowsError, ValueError, TypeError):
  1387.             pass
  1388.  
  1389.         return proxies
  1390.  
  1391.     
  1392.     def getproxies():
  1393.         if not getproxies_environment():
  1394.             pass
  1395.         return getproxies_registry()
  1396.  
  1397.     
  1398.     def proxy_bypass_registry(host):
  1399.         
  1400.         try:
  1401.             import _winreg
  1402.             import re
  1403.         except ImportError:
  1404.             return 0
  1405.  
  1406.         
  1407.         try:
  1408.             internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings')
  1409.             proxyEnable = _winreg.QueryValueEx(internetSettings, 'ProxyEnable')[0]
  1410.             proxyOverride = str(_winreg.QueryValueEx(internetSettings, 'ProxyOverride')[0])
  1411.         except WindowsError:
  1412.             return 0
  1413.  
  1414.         if not proxyEnable or not proxyOverride:
  1415.             return 0
  1416.         (rawHost, port) = None(host)
  1417.         host = [
  1418.             rawHost]
  1419.         
  1420.         try:
  1421.             addr = socket.gethostbyname(rawHost)
  1422.             if addr != rawHost:
  1423.                 host.append(addr)
  1424.         except socket.error:
  1425.             pass
  1426.  
  1427.         
  1428.         try:
  1429.             fqdn = socket.getfqdn(rawHost)
  1430.             if fqdn != rawHost:
  1431.                 host.append(fqdn)
  1432.         except socket.error:
  1433.             pass
  1434.  
  1435.         proxyOverride = proxyOverride.split(';')
  1436.         for test in proxyOverride:
  1437.             if test == '<local>' and '.' not in rawHost:
  1438.                 return 1
  1439.             test = test.replace('.', '\\.')
  1440.             test = test.replace('*', '.*')
  1441.             test = test.replace('?', '.')
  1442.             for val in host:
  1443.                 if re.match(test, val, re.I):
  1444.                     return 1
  1445.             
  1446.         
  1447.         return 0
  1448.  
  1449.     
  1450.     def proxy_bypass(host):
  1451.         if getproxies_environment():
  1452.             return proxy_bypass_environment(host)
  1453.         return None(host)
  1454.  
  1455. else:
  1456.     getproxies = getproxies_environment
  1457.     proxy_bypass = proxy_bypass_environment
  1458.  
  1459. def test1():
  1460.     s = ''
  1461.     for i in range(256):
  1462.         s = s + chr(i)
  1463.     
  1464.     s = s * 4
  1465.     t0 = time.time()
  1466.     qs = quote(s)
  1467.     uqs = unquote(qs)
  1468.     t1 = time.time()
  1469.     if uqs != s:
  1470.         print 'Wrong!'
  1471.     print repr(s)
  1472.     print repr(qs)
  1473.     print repr(uqs)
  1474.     print round(t1 - t0, 3), 'sec'
  1475.  
  1476.  
  1477. def reporthook(blocknum, blocksize, totalsize):
  1478.     print 'Block number: %d, Block size: %d, Total size: %d' % (blocknum, blocksize, totalsize)
  1479.  
  1480.  
  1481. def test(args = []):
  1482.     if not args:
  1483.         args = [
  1484.             '/etc/passwd',
  1485.             'file:/etc/passwd',
  1486.             'file://localhost/etc/passwd',
  1487.             'ftp://ftp.gnu.org/pub/README',
  1488.             'http://www.python.org/index.html']
  1489.         if hasattr(URLopener, 'open_https'):
  1490.             args.append('https://synergy.as.cmu.edu/~geek/')
  1491.         
  1492.     
  1493.     try:
  1494.         for url in args:
  1495.             print '----------', url, '----------'
  1496.             (fn, h) = urlretrieve(url, None, reporthook)
  1497.             print fn
  1498.             if h:
  1499.                 print '======'
  1500.                 for k in h.keys():
  1501.                     print k + ':', h[k]
  1502.                 
  1503.                 print '======'
  1504.             with open(fn, 'rb') as fp:
  1505.                 data = fp.read()
  1506.             if '\r' in data:
  1507.                 table = string.maketrans('', '')
  1508.                 data = data.translate(table, '\r')
  1509.             print data
  1510.             (fn, h) = (None, None)
  1511.         
  1512.         print '-' * 40
  1513.     finally:
  1514.         urlcleanup()
  1515.  
  1516.  
  1517.  
  1518. def main():
  1519.     import getopt
  1520.     import sys
  1521.     
  1522.     try:
  1523.         (opts, args) = getopt.getopt(sys.argv[1:], 'th')
  1524.     except getopt.error:
  1525.         msg = None
  1526.         print msg
  1527.         print 'Use -h for help'
  1528.         return None
  1529.  
  1530.     t = 0
  1531.     for o, a in opts:
  1532.         if o == '-t':
  1533.             t = t + 1
  1534.         if o == '-h':
  1535.             print 'Usage: python urllib.py [-t] [url ...]'
  1536.             print '-t runs self-test;', 'otherwise, contents of urls are printed'
  1537.             return None
  1538.     
  1539.     if t:
  1540.         if t > 1:
  1541.             test1()
  1542.         test(args)
  1543.     elif not args:
  1544.         print 'Use -h for help'
  1545.     for url in args:
  1546.         print urlopen(url).read(),
  1547.     
  1548.  
  1549. if __name__ == '__main__':
  1550.     main()
  1551.