Ignore:
Timestamp:
Mar 19, 2014, 11:11:30 AM (11 years ago)
Author:
dmik
Message:

python: Update vendor to 2.7.6.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • python/vendor/current/Lib/urllib2.py

    r2 r388  
    103103import urlparse
    104104import bisect
     105import warnings
    105106
    106107try:
     
    110111
    111112from urllib import (unwrap, unquote, splittype, splithost, quote,
    112      addinfourl, splitport,
     113     addinfourl, splitport, splittag, toBytes,
    113114     splitattr, ftpwrapper, splituser, splitpasswd, splitvalue)
    114115
     
    167168        return 'HTTP Error %s: %s' % (self.code, self.msg)
    168169
     170    # since URLError specifies a .reason attribute, HTTPError should also
     171    #  provide this attribute. See issue13211 fo discussion.
     172    @property
     173    def reason(self):
     174        return self.msg
     175
     176    def info(self):
     177        return self.hdrs
     178
    169179# copied from cookielib.py
    170180_cut_port_re = re.compile(r":\d+$")
     
    191201        # unwrap('<URL:type://host/path>') --> 'type://host/path'
    192202        self.__original = unwrap(url)
     203        self.__original, self.__fragment = splittag(self.__original)
    193204        self.type = None
    194205        # self.__r_type is what's left after doing the splittype
     
    236247
    237248    def get_full_url(self):
    238         return self.__original
     249        if self.__fragment:
     250            return '%s#%s' % (self.__original, self.__fragment)
     251        else:
     252            return self.__original
    239253
    240254    def get_type(self):
     
    299313        client_version = "Python-urllib/%s" % __version__
    300314        self.addheaders = [('User-agent', client_version)]
     315        # self.handlers is retained only for backward compatibility
     316        self.handlers = []
    301317        # manage the individual handlers
    302         self.handlers = []
    303318        self.handle_open = {}
    304319        self.handle_error = {}
     
    350365
    351366        if added:
    352             # the handlers must work in an specific order, the order
    353             # is specified in a Handler attribute
    354367            bisect.insort(self.handlers, handler)
    355368            handler.add_parent(self)
     
    450463    import types
    451464    def isclass(obj):
    452         return isinstance(obj, types.ClassType) or hasattr(obj, "__bases__")
     465        return isinstance(obj, (types.ClassType, type))
    453466
    454467    opener = OpenerDirector()
     
    579592        newurl = urlparse.urljoin(req.get_full_url(), newurl)
    580593
     594        # For security reasons we do not allow redirects to protocols
     595        # other than HTTP, HTTPS or FTP.
     596        newurl_lower = newurl.lower()
     597        if not (newurl_lower.startswith('http://') or
     598                newurl_lower.startswith('https://') or
     599                newurl_lower.startswith('ftp://')):
     600            raise HTTPError(newurl, code,
     601                            msg + " - Redirection to url '%s' is not allowed" %
     602                            newurl,
     603                            headers, fp)
     604
    581605        # XXX Probably want to forget about the state of the current
    582606        # request, although that might interact poorly with other
     
    809833    # (single quotes are a violation of the RFC, but appear in the wild)
    810834    rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+'
    811                     'realm=(["\'])(.*?)\\2', re.I)
     835                    'realm=(["\']?)([^"\']*)\\2', re.I)
    812836
    813837    # XXX could pre-emptively send auth info already accepted (RFC 2617,
     
    820844        self.passwd = password_mgr
    821845        self.add_password = self.passwd.add_password
     846        self.retried = 0
     847
     848    def reset_retry_count(self):
     849        self.retried = 0
    822850
    823851    def http_error_auth_reqed(self, authreq, host, req, headers):
     
    826854        # XXX could be multiple headers
    827855        authreq = headers.get(authreq, None)
     856
     857        if self.retried > 5:
     858            # retry sending the username:password 5 times before failing.
     859            raise HTTPError(req.get_full_url(), 401, "basic auth failed",
     860                            headers, None)
     861        else:
     862            self.retried += 1
     863
    828864        if authreq:
    829865            mo = AbstractBasicAuthHandler.rx.search(authreq)
    830866            if mo:
    831867                scheme, quote, realm = mo.groups()
     868                if quote not in ['"', "'"]:
     869                    warnings.warn("Basic Auth Realm was unquoted",
     870                                  UserWarning, 2)
    832871                if scheme.lower() == 'basic':
    833                     return self.retry_http_basic_auth(host, req, realm)
     872                    response = self.retry_http_basic_auth(host, req, realm)
     873                    if response and response.code != 401:
     874                        self.retried = 0
     875                    return response
    834876
    835877    def retry_http_basic_auth(self, host, req, realm):
     
    852894    def http_error_401(self, req, fp, code, msg, headers):
    853895        url = req.get_full_url()
    854         return self.http_error_auth_reqed('www-authenticate',
    855                                           url, req, headers)
     896        response = self.http_error_auth_reqed('www-authenticate',
     897                                              url, req, headers)
     898        self.reset_retry_count()
     899        return response
    856900
    857901
     
    866910        # userinfo.
    867911        authority = req.get_host()
    868         return self.http_error_auth_reqed('proxy-authenticate',
     912        response = self.http_error_auth_reqed('proxy-authenticate',
    869913                                          authority, req, headers)
     914        self.reset_retry_count()
     915        return response
    870916
    871917
     
    11081154        h.set_debuglevel(self._debuglevel)
    11091155
    1110         headers = dict(req.headers)
    1111         headers.update(req.unredirected_hdrs)
     1156        headers = dict(req.unredirected_hdrs)
     1157        headers.update(dict((k, v) for k, v in req.headers.items()
     1158                            if k not in headers))
     1159
    11121160        # We want to make an HTTP/1.1 request, but the addinfourl
    11131161        # class isn't prepared to deal with a persistent connection.
     
    11281176                # server.
    11291177                del headers[proxy_auth_hdr]
    1130             h._set_tunnel(req._tunnel_host, headers=tunnel_headers)
     1178            h.set_tunnel(req._tunnel_host, headers=tunnel_headers)
    11311179
    11321180        try:
    11331181            h.request(req.get_method(), req.get_selector(), req.data, headers)
    1134             r = h.getresponse()
    11351182        except socket.error, err: # XXX what error?
     1183            h.close()
    11361184            raise URLError(err)
     1185        else:
     1186            try:
     1187                r = h.getresponse(buffering=True)
     1188            except TypeError: # buffering kw not supported
     1189                r = h.getresponse()
    11371190
    11381191        # Pick apart the HTTPResponse object to get the addinfourl
     
    12471300    return [part.strip() for part in res]
    12481301
     1302def _safe_gethostbyname(host):
     1303    try:
     1304        return socket.gethostbyname(host)
     1305    except socket.gaierror:
     1306        return None
     1307
    12491308class FileHandler(BaseHandler):
    12501309    # Use local file or FTP depending on form of URL
    12511310    def file_open(self, req):
    12521311        url = req.get_selector()
    1253         if url[:2] == '//' and url[2:3] != '/':
     1312        if url[:2] == '//' and url[2:3] != '/' and (req.host and
     1313                req.host != 'localhost'):
    12541314            req.type = 'ftp'
    12551315            return self.parent.open(req)
     
    12741334        import mimetypes
    12751335        host = req.get_host()
    1276         file = req.get_selector()
    1277         localfile = url2pathname(file)
     1336        filename = req.get_selector()
     1337        localfile = url2pathname(filename)
    12781338        try:
    12791339            stats = os.stat(localfile)
    12801340            size = stats.st_size
    12811341            modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
    1282             mtype = mimetypes.guess_type(file)[0]
     1342            mtype = mimetypes.guess_type(filename)[0]
    12831343            headers = mimetools.Message(StringIO(
    12841344                'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' %
     
    12871347                host, port = splitport(host)
    12881348            if not host or \
    1289                 (not port and socket.gethostbyname(host) in self.get_names()):
    1290                 return addinfourl(open(localfile, 'rb'),
    1291                                   headers, 'file:'+file)
     1349                (not port and _safe_gethostbyname(host) in self.get_names()):
     1350                if host:
     1351                    origurl = 'file://' + host + filename
     1352                else:
     1353                    origurl = 'file://' + filename
     1354                return addinfourl(open(localfile, 'rb'), headers, origurl)
    12921355        except OSError, msg:
    12931356            # urllib2 users shouldn't expect OSErrors coming from urlopen()
     
    13151378            passwd = None
    13161379        host = unquote(host)
    1317         user = unquote(user or '')
    1318         passwd = unquote(passwd or '')
     1380        user = user or ''
     1381        passwd = passwd or ''
    13191382
    13201383        try:
     
    13501413
    13511414    def connect_ftp(self, user, passwd, host, port, dirs, timeout):
    1352         fw = ftpwrapper(user, passwd, host, port, dirs, timeout)
     1415        fw = ftpwrapper(user, passwd, host, port, dirs, timeout,
     1416                        persistent=False)
    13531417##        fw.ftp.set_debuglevel(1)
    13541418        return fw
     
    13991463                    break
    14001464            self.soonest = min(self.timeout.values())
     1465
     1466    def clear_cache(self):
     1467        for conn in self.cache.values():
     1468            conn.close()
     1469        self.cache.clear()
     1470        self.timeout.clear()
Note: See TracChangeset for help on using the changeset viewer.