home *** CD-ROM | disk | FTP | other *** search
/ Freelog 116 / FreelogNo116-JuilletSeptembre2013.iso / GestionFichiers / metamorphose / metamorphose2_0.8.2_setup.exe / metamorphose2.exe / urllib.pyo (.txt) < prev    next >
Python Compiled Bytecode  |  2011-01-12  |  42KB  |  1,677 lines

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