PageRenderTime 54ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/urllib2.py

https://bitbucket.org/yrttyr/pypy
Python | 1463 lines | 1349 code | 18 blank | 96 comment | 9 complexity | 5ce2498203e4cd6a39f3cf39c2e9feee MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. """An extensible library for opening URLs using a variety of protocols
  2. The simplest way to use this module is to call the urlopen function,
  3. which accepts a string containing a URL or a Request object (described
  4. below). It opens the URL and returns the results as file-like
  5. object; the returned object has some extra methods described below.
  6. The OpenerDirector manages a collection of Handler objects that do
  7. all the actual work. Each Handler implements a particular protocol or
  8. option. The OpenerDirector is a composite object that invokes the
  9. Handlers needed to open the requested URL. For example, the
  10. HTTPHandler performs HTTP GET and POST requests and deals with
  11. non-error returns. The HTTPRedirectHandler automatically deals with
  12. HTTP 301, 302, 303 and 307 redirect errors, and the HTTPDigestAuthHandler
  13. deals with digest authentication.
  14. urlopen(url, data=None) -- Basic usage is the same as original
  15. urllib. pass the url and optionally data to post to an HTTP URL, and
  16. get a file-like object back. One difference is that you can also pass
  17. a Request instance instead of URL. Raises a URLError (subclass of
  18. IOError); for HTTP errors, raises an HTTPError, which can also be
  19. treated as a valid response.
  20. build_opener -- Function that creates a new OpenerDirector instance.
  21. Will install the default handlers. Accepts one or more Handlers as
  22. arguments, either instances or Handler classes that it will
  23. instantiate. If one of the argument is a subclass of the default
  24. handler, the argument will be installed instead of the default.
  25. install_opener -- Installs a new opener as the default opener.
  26. objects of interest:
  27. OpenerDirector -- Sets up the User Agent as the Python-urllib client and manages
  28. the Handler classes, while dealing with requests and responses.
  29. Request -- An object that encapsulates the state of a request. The
  30. state can be as simple as the URL. It can also include extra HTTP
  31. headers, e.g. a User-Agent.
  32. BaseHandler --
  33. exceptions:
  34. URLError -- A subclass of IOError, individual protocols have their own
  35. specific subclass.
  36. HTTPError -- Also a valid HTTP response, so you can treat an HTTP error
  37. as an exceptional event or valid response.
  38. internals:
  39. BaseHandler and parent
  40. _call_chain conventions
  41. Example usage:
  42. import urllib2
  43. # set up authentication info
  44. authinfo = urllib2.HTTPBasicAuthHandler()
  45. authinfo.add_password(realm='PDQ Application',
  46. uri='https://mahler:8092/site-updates.py',
  47. user='klem',
  48. passwd='geheim$parole')
  49. proxy_support = urllib2.ProxyHandler({"http" : "http://ahad-haam:3128"})
  50. # build a new opener that adds authentication and caching FTP handlers
  51. opener = urllib2.build_opener(proxy_support, authinfo, urllib2.CacheFTPHandler)
  52. # install it
  53. urllib2.install_opener(opener)
  54. f = urllib2.urlopen('http://www.python.org/')
  55. """
  56. # XXX issues:
  57. # If an authentication error handler that tries to perform
  58. # authentication for some reason but fails, how should the error be
  59. # signalled? The client needs to know the HTTP error code. But if
  60. # the handler knows that the problem was, e.g., that it didn't know
  61. # that hash algo that requested in the challenge, it would be good to
  62. # pass that information along to the client, too.
  63. # ftp errors aren't handled cleanly
  64. # check digest against correct (i.e. non-apache) implementation
  65. # Possible extensions:
  66. # complex proxies XXX not sure what exactly was meant by this
  67. # abstract factory for opener
  68. import base64
  69. import hashlib
  70. import httplib
  71. import mimetools
  72. import os
  73. import posixpath
  74. import random
  75. import re
  76. import socket
  77. import sys
  78. import time
  79. import urlparse
  80. import bisect
  81. try:
  82. from cStringIO import StringIO
  83. except ImportError:
  84. from StringIO import StringIO
  85. from urllib import (unwrap, unquote, splittype, splithost, quote,
  86. addinfourl, splitport, splittag,
  87. splitattr, ftpwrapper, splituser, splitpasswd, splitvalue)
  88. # support for FileHandler, proxies via environment variables
  89. from urllib import localhost, url2pathname, getproxies, proxy_bypass
  90. # used in User-Agent header sent
  91. __version__ = sys.version[:3]
  92. _opener = None
  93. def urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
  94. global _opener
  95. if _opener is None:
  96. _opener = build_opener()
  97. return _opener.open(url, data, timeout)
  98. def install_opener(opener):
  99. global _opener
  100. _opener = opener
  101. # do these error classes make sense?
  102. # make sure all of the IOError stuff is overridden. we just want to be
  103. # subtypes.
  104. class URLError(IOError):
  105. # URLError is a sub-type of IOError, but it doesn't share any of
  106. # the implementation. need to override __init__ and __str__.
  107. # It sets self.args for compatibility with other EnvironmentError
  108. # subclasses, but args doesn't have the typical format with errno in
  109. # slot 0 and strerror in slot 1. This may be better than nothing.
  110. def __init__(self, reason):
  111. self.args = reason,
  112. self.reason = reason
  113. def __str__(self):
  114. return '<urlopen error %s>' % self.reason
  115. class HTTPError(URLError, addinfourl):
  116. """Raised when HTTP error occurs, but also acts like non-error return"""
  117. __super_init = addinfourl.__init__
  118. def __init__(self, url, code, msg, hdrs, fp):
  119. self.code = code
  120. self.msg = msg
  121. self.hdrs = hdrs
  122. self.fp = fp
  123. self.filename = url
  124. # The addinfourl classes depend on fp being a valid file
  125. # object. In some cases, the HTTPError may not have a valid
  126. # file object. If this happens, the simplest workaround is to
  127. # not initialize the base classes.
  128. if fp is not None:
  129. self.__super_init(fp, hdrs, url, code)
  130. def __str__(self):
  131. return 'HTTP Error %s: %s' % (self.code, self.msg)
  132. # since URLError specifies a .reason attribute, HTTPError should also
  133. # provide this attribute. See issue13211 fo discussion.
  134. @property
  135. def reason(self):
  136. return self.msg
  137. # copied from cookielib.py
  138. _cut_port_re = re.compile(r":\d+$")
  139. def request_host(request):
  140. """Return request-host, as defined by RFC 2965.
  141. Variation from RFC: returned value is lowercased, for convenient
  142. comparison.
  143. """
  144. url = request.get_full_url()
  145. host = urlparse.urlparse(url)[1]
  146. if host == "":
  147. host = request.get_header("Host", "")
  148. # remove port, if present
  149. host = _cut_port_re.sub("", host, 1)
  150. return host.lower()
  151. class Request:
  152. def __init__(self, url, data=None, headers={},
  153. origin_req_host=None, unverifiable=False):
  154. # unwrap('<URL:type://host/path>') --> 'type://host/path'
  155. self.__original = unwrap(url)
  156. self.__original, self.__fragment = splittag(self.__original)
  157. self.type = None
  158. # self.__r_type is what's left after doing the splittype
  159. self.host = None
  160. self.port = None
  161. self._tunnel_host = None
  162. self.data = data
  163. self.headers = {}
  164. for key, value in headers.items():
  165. self.add_header(key, value)
  166. self.unredirected_hdrs = {}
  167. if origin_req_host is None:
  168. origin_req_host = request_host(self)
  169. self.origin_req_host = origin_req_host
  170. self.unverifiable = unverifiable
  171. def __getattr__(self, attr):
  172. # XXX this is a fallback mechanism to guard against these
  173. # methods getting called in a non-standard order. this may be
  174. # too complicated and/or unnecessary.
  175. # XXX should the __r_XXX attributes be public?
  176. if attr[:12] == '_Request__r_':
  177. name = attr[12:]
  178. if hasattr(Request, 'get_' + name):
  179. getattr(self, 'get_' + name)()
  180. return getattr(self, attr)
  181. raise AttributeError, attr
  182. def get_method(self):
  183. if self.has_data():
  184. return "POST"
  185. else:
  186. return "GET"
  187. # XXX these helper methods are lame
  188. def add_data(self, data):
  189. self.data = data
  190. def has_data(self):
  191. return self.data is not None
  192. def get_data(self):
  193. return self.data
  194. def get_full_url(self):
  195. if self.__fragment:
  196. return '%s#%s' % (self.__original, self.__fragment)
  197. else:
  198. return self.__original
  199. def get_type(self):
  200. if self.type is None:
  201. self.type, self.__r_type = splittype(self.__original)
  202. if self.type is None:
  203. raise ValueError, "unknown url type: %s" % self.__original
  204. return self.type
  205. def get_host(self):
  206. if self.host is None:
  207. self.host, self.__r_host = splithost(self.__r_type)
  208. if self.host:
  209. self.host = unquote(self.host)
  210. return self.host
  211. def get_selector(self):
  212. return self.__r_host
  213. def set_proxy(self, host, type):
  214. if self.type == 'https' and not self._tunnel_host:
  215. self._tunnel_host = self.host
  216. else:
  217. self.type = type
  218. self.__r_host = self.__original
  219. self.host = host
  220. def has_proxy(self):
  221. return self.__r_host == self.__original
  222. def get_origin_req_host(self):
  223. return self.origin_req_host
  224. def is_unverifiable(self):
  225. return self.unverifiable
  226. def add_header(self, key, val):
  227. # useful for something like authentication
  228. self.headers[key.capitalize()] = val
  229. def add_unredirected_header(self, key, val):
  230. # will not be added to a redirected request
  231. self.unredirected_hdrs[key.capitalize()] = val
  232. def has_header(self, header_name):
  233. return (header_name in self.headers or
  234. header_name in self.unredirected_hdrs)
  235. def get_header(self, header_name, default=None):
  236. return self.headers.get(
  237. header_name,
  238. self.unredirected_hdrs.get(header_name, default))
  239. def header_items(self):
  240. hdrs = self.unredirected_hdrs.copy()
  241. hdrs.update(self.headers)
  242. return hdrs.items()
  243. class OpenerDirector:
  244. def __init__(self):
  245. client_version = "Python-urllib/%s" % __version__
  246. self.addheaders = [('User-agent', client_version)]
  247. # self.handlers is retained only for backward compatibility
  248. self.handlers = []
  249. # manage the individual handlers
  250. self.handle_open = {}
  251. self.handle_error = {}
  252. self.process_response = {}
  253. self.process_request = {}
  254. def add_handler(self, handler):
  255. if not hasattr(handler, "add_parent"):
  256. raise TypeError("expected BaseHandler instance, got %r" %
  257. type(handler))
  258. added = False
  259. for meth in dir(handler):
  260. if meth in ["redirect_request", "do_open", "proxy_open"]:
  261. # oops, coincidental match
  262. continue
  263. i = meth.find("_")
  264. protocol = meth[:i]
  265. condition = meth[i+1:]
  266. if condition.startswith("error"):
  267. j = condition.find("_") + i + 1
  268. kind = meth[j+1:]
  269. try:
  270. kind = int(kind)
  271. except ValueError:
  272. pass
  273. lookup = self.handle_error.get(protocol, {})
  274. self.handle_error[protocol] = lookup
  275. elif condition == "open":
  276. kind = protocol
  277. lookup = self.handle_open
  278. elif condition == "response":
  279. kind = protocol
  280. lookup = self.process_response
  281. elif condition == "request":
  282. kind = protocol
  283. lookup = self.process_request
  284. else:
  285. continue
  286. handlers = lookup.setdefault(kind, [])
  287. if handlers:
  288. bisect.insort(handlers, handler)
  289. else:
  290. handlers.append(handler)
  291. added = True
  292. if added:
  293. bisect.insort(self.handlers, handler)
  294. handler.add_parent(self)
  295. def close(self):
  296. # Only exists for backwards compatibility.
  297. pass
  298. def _call_chain(self, chain, kind, meth_name, *args):
  299. # Handlers raise an exception if no one else should try to handle
  300. # the request, or return None if they can't but another handler
  301. # could. Otherwise, they return the response.
  302. handlers = chain.get(kind, ())
  303. for handler in handlers:
  304. func = getattr(handler, meth_name)
  305. result = func(*args)
  306. if result is not None:
  307. return result
  308. def open(self, fullurl, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
  309. # accept a URL or a Request object
  310. if isinstance(fullurl, basestring):
  311. req = Request(fullurl, data)
  312. else:
  313. req = fullurl
  314. if data is not None:
  315. req.add_data(data)
  316. req.timeout = timeout
  317. protocol = req.get_type()
  318. # pre-process request
  319. meth_name = protocol+"_request"
  320. for processor in self.process_request.get(protocol, []):
  321. meth = getattr(processor, meth_name)
  322. req = meth(req)
  323. response = self._open(req, data)
  324. # post-process response
  325. meth_name = protocol+"_response"
  326. for processor in self.process_response.get(protocol, []):
  327. meth = getattr(processor, meth_name)
  328. response = meth(req, response)
  329. return response
  330. def _open(self, req, data=None):
  331. result = self._call_chain(self.handle_open, 'default',
  332. 'default_open', req)
  333. if result:
  334. return result
  335. protocol = req.get_type()
  336. result = self._call_chain(self.handle_open, protocol, protocol +
  337. '_open', req)
  338. if result:
  339. return result
  340. return self._call_chain(self.handle_open, 'unknown',
  341. 'unknown_open', req)
  342. def error(self, proto, *args):
  343. if proto in ('http', 'https'):
  344. # XXX http[s] protocols are special-cased
  345. dict = self.handle_error['http'] # https is not different than http
  346. proto = args[2] # YUCK!
  347. meth_name = 'http_error_%s' % proto
  348. http_err = 1
  349. orig_args = args
  350. else:
  351. dict = self.handle_error
  352. meth_name = proto + '_error'
  353. http_err = 0
  354. args = (dict, proto, meth_name) + args
  355. result = self._call_chain(*args)
  356. if result:
  357. return result
  358. if http_err:
  359. args = (dict, 'default', 'http_error_default') + orig_args
  360. return self._call_chain(*args)
  361. # XXX probably also want an abstract factory that knows when it makes
  362. # sense to skip a superclass in favor of a subclass and when it might
  363. # make sense to include both
  364. def build_opener(*handlers):
  365. """Create an opener object from a list of handlers.
  366. The opener will use several default handlers, including support
  367. for HTTP, FTP and when applicable, HTTPS.
  368. If any of the handlers passed as arguments are subclasses of the
  369. default handlers, the default handlers will not be used.
  370. """
  371. import types
  372. def isclass(obj):
  373. return isinstance(obj, (types.ClassType, type))
  374. opener = OpenerDirector()
  375. default_classes = [ProxyHandler, UnknownHandler, HTTPHandler,
  376. HTTPDefaultErrorHandler, HTTPRedirectHandler,
  377. FTPHandler, FileHandler, HTTPErrorProcessor]
  378. if hasattr(httplib, 'HTTPS'):
  379. default_classes.append(HTTPSHandler)
  380. skip = set()
  381. for klass in default_classes:
  382. for check in handlers:
  383. if isclass(check):
  384. if issubclass(check, klass):
  385. skip.add(klass)
  386. elif isinstance(check, klass):
  387. skip.add(klass)
  388. for klass in skip:
  389. default_classes.remove(klass)
  390. for klass in default_classes:
  391. opener.add_handler(klass())
  392. for h in handlers:
  393. if isclass(h):
  394. h = h()
  395. opener.add_handler(h)
  396. return opener
  397. class BaseHandler:
  398. handler_order = 500
  399. def add_parent(self, parent):
  400. self.parent = parent
  401. def close(self):
  402. # Only exists for backwards compatibility
  403. pass
  404. def __lt__(self, other):
  405. if not hasattr(other, "handler_order"):
  406. # Try to preserve the old behavior of having custom classes
  407. # inserted after default ones (works only for custom user
  408. # classes which are not aware of handler_order).
  409. return True
  410. return self.handler_order < other.handler_order
  411. class HTTPErrorProcessor(BaseHandler):
  412. """Process HTTP error responses."""
  413. handler_order = 1000 # after all other processing
  414. def http_response(self, request, response):
  415. code, msg, hdrs = response.code, response.msg, response.info()
  416. # According to RFC 2616, "2xx" code indicates that the client's
  417. # request was successfully received, understood, and accepted.
  418. if not (200 <= code < 300):
  419. response = self.parent.error(
  420. 'http', request, response, code, msg, hdrs)
  421. return response
  422. https_response = http_response
  423. class HTTPDefaultErrorHandler(BaseHandler):
  424. def http_error_default(self, req, fp, code, msg, hdrs):
  425. raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
  426. class HTTPRedirectHandler(BaseHandler):
  427. # maximum number of redirections to any single URL
  428. # this is needed because of the state that cookies introduce
  429. max_repeats = 4
  430. # maximum total number of redirections (regardless of URL) before
  431. # assuming we're in a loop
  432. max_redirections = 10
  433. def redirect_request(self, req, fp, code, msg, headers, newurl):
  434. """Return a Request or None in response to a redirect.
  435. This is called by the http_error_30x methods when a
  436. redirection response is received. If a redirection should
  437. take place, return a new Request to allow http_error_30x to
  438. perform the redirect. Otherwise, raise HTTPError if no-one
  439. else should try to handle this url. Return None if you can't
  440. but another Handler might.
  441. """
  442. m = req.get_method()
  443. if (code in (301, 302, 303, 307) and m in ("GET", "HEAD")
  444. or code in (301, 302, 303) and m == "POST"):
  445. # Strictly (according to RFC 2616), 301 or 302 in response
  446. # to a POST MUST NOT cause a redirection without confirmation
  447. # from the user (of urllib2, in this case). In practice,
  448. # essentially all clients do redirect in this case, so we
  449. # do the same.
  450. # be conciliant with URIs containing a space
  451. newurl = newurl.replace(' ', '%20')
  452. newheaders = dict((k,v) for k,v in req.headers.items()
  453. if k.lower() not in ("content-length", "content-type")
  454. )
  455. return Request(newurl,
  456. headers=newheaders,
  457. origin_req_host=req.get_origin_req_host(),
  458. unverifiable=True)
  459. else:
  460. raise HTTPError(req.get_full_url(), code, msg, headers, fp)
  461. # Implementation note: To avoid the server sending us into an
  462. # infinite loop, the request object needs to track what URLs we
  463. # have already seen. Do this by adding a handler-specific
  464. # attribute to the Request object.
  465. def http_error_302(self, req, fp, code, msg, headers):
  466. # Some servers (incorrectly) return multiple Location headers
  467. # (so probably same goes for URI). Use first header.
  468. if 'location' in headers:
  469. newurl = headers.getheaders('location')[0]
  470. elif 'uri' in headers:
  471. newurl = headers.getheaders('uri')[0]
  472. else:
  473. return
  474. # fix a possible malformed URL
  475. urlparts = urlparse.urlparse(newurl)
  476. if not urlparts.path:
  477. urlparts = list(urlparts)
  478. urlparts[2] = "/"
  479. newurl = urlparse.urlunparse(urlparts)
  480. newurl = urlparse.urljoin(req.get_full_url(), newurl)
  481. # For security reasons we do not allow redirects to protocols
  482. # other than HTTP, HTTPS or FTP.
  483. newurl_lower = newurl.lower()
  484. if not (newurl_lower.startswith('http://') or
  485. newurl_lower.startswith('https://') or
  486. newurl_lower.startswith('ftp://')):
  487. raise HTTPError(newurl, code,
  488. msg + " - Redirection to url '%s' is not allowed" %
  489. newurl,
  490. headers, fp)
  491. # XXX Probably want to forget about the state of the current
  492. # request, although that might interact poorly with other
  493. # handlers that also use handler-specific request attributes
  494. new = self.redirect_request(req, fp, code, msg, headers, newurl)
  495. if new is None:
  496. return
  497. # loop detection
  498. # .redirect_dict has a key url if url was previously visited.
  499. if hasattr(req, 'redirect_dict'):
  500. visited = new.redirect_dict = req.redirect_dict
  501. if (visited.get(newurl, 0) >= self.max_repeats or
  502. len(visited) >= self.max_redirections):
  503. raise HTTPError(req.get_full_url(), code,
  504. self.inf_msg + msg, headers, fp)
  505. else:
  506. visited = new.redirect_dict = req.redirect_dict = {}
  507. visited[newurl] = visited.get(newurl, 0) + 1
  508. # Don't close the fp until we are sure that we won't use it
  509. # with HTTPError.
  510. fp.read()
  511. fp.close()
  512. return self.parent.open(new, timeout=req.timeout)
  513. http_error_301 = http_error_303 = http_error_307 = http_error_302
  514. inf_msg = "The HTTP server returned a redirect error that would " \
  515. "lead to an infinite loop.\n" \
  516. "The last 30x error message was:\n"
  517. def _parse_proxy(proxy):
  518. """Return (scheme, user, password, host/port) given a URL or an authority.
  519. If a URL is supplied, it must have an authority (host:port) component.
  520. According to RFC 3986, having an authority component means the URL must
  521. have two slashes after the scheme:
  522. >>> _parse_proxy('file:/ftp.example.com/')
  523. Traceback (most recent call last):
  524. ValueError: proxy URL with no authority: 'file:/ftp.example.com/'
  525. The first three items of the returned tuple may be None.
  526. Examples of authority parsing:
  527. >>> _parse_proxy('proxy.example.com')
  528. (None, None, None, 'proxy.example.com')
  529. >>> _parse_proxy('proxy.example.com:3128')
  530. (None, None, None, 'proxy.example.com:3128')
  531. The authority component may optionally include userinfo (assumed to be
  532. username:password):
  533. >>> _parse_proxy('joe:password@proxy.example.com')
  534. (None, 'joe', 'password', 'proxy.example.com')
  535. >>> _parse_proxy('joe:password@proxy.example.com:3128')
  536. (None, 'joe', 'password', 'proxy.example.com:3128')
  537. Same examples, but with URLs instead:
  538. >>> _parse_proxy('http://proxy.example.com/')
  539. ('http', None, None, 'proxy.example.com')
  540. >>> _parse_proxy('http://proxy.example.com:3128/')
  541. ('http', None, None, 'proxy.example.com:3128')
  542. >>> _parse_proxy('http://joe:password@proxy.example.com/')
  543. ('http', 'joe', 'password', 'proxy.example.com')
  544. >>> _parse_proxy('http://joe:password@proxy.example.com:3128')
  545. ('http', 'joe', 'password', 'proxy.example.com:3128')
  546. Everything after the authority is ignored:
  547. >>> _parse_proxy('ftp://joe:password@proxy.example.com/rubbish:3128')
  548. ('ftp', 'joe', 'password', 'proxy.example.com')
  549. Test for no trailing '/' case:
  550. >>> _parse_proxy('http://joe:password@proxy.example.com')
  551. ('http', 'joe', 'password', 'proxy.example.com')
  552. """
  553. scheme, r_scheme = splittype(proxy)
  554. if not r_scheme.startswith("/"):
  555. # authority
  556. scheme = None
  557. authority = proxy
  558. else:
  559. # URL
  560. if not r_scheme.startswith("//"):
  561. raise ValueError("proxy URL with no authority: %r" % proxy)
  562. # We have an authority, so for RFC 3986-compliant URLs (by ss 3.
  563. # and 3.3.), path is empty or starts with '/'
  564. end = r_scheme.find("/", 2)
  565. if end == -1:
  566. end = None
  567. authority = r_scheme[2:end]
  568. userinfo, hostport = splituser(authority)
  569. if userinfo is not None:
  570. user, password = splitpasswd(userinfo)
  571. else:
  572. user = password = None
  573. return scheme, user, password, hostport
  574. class ProxyHandler(BaseHandler):
  575. # Proxies must be in front
  576. handler_order = 100
  577. def __init__(self, proxies=None):
  578. if proxies is None:
  579. proxies = getproxies()
  580. assert hasattr(proxies, 'has_key'), "proxies must be a mapping"
  581. self.proxies = proxies
  582. for type, url in proxies.items():
  583. setattr(self, '%s_open' % type,
  584. lambda r, proxy=url, type=type, meth=self.proxy_open: \
  585. meth(r, proxy, type))
  586. def proxy_open(self, req, proxy, type):
  587. orig_type = req.get_type()
  588. proxy_type, user, password, hostport = _parse_proxy(proxy)
  589. if proxy_type is None:
  590. proxy_type = orig_type
  591. if req.host and proxy_bypass(req.host):
  592. return None
  593. if user and password:
  594. user_pass = '%s:%s' % (unquote(user), unquote(password))
  595. creds = base64.b64encode(user_pass).strip()
  596. req.add_header('Proxy-authorization', 'Basic ' + creds)
  597. hostport = unquote(hostport)
  598. req.set_proxy(hostport, proxy_type)
  599. if orig_type == proxy_type or orig_type == 'https':
  600. # let other handlers take care of it
  601. return None
  602. else:
  603. # need to start over, because the other handlers don't
  604. # grok the proxy's URL type
  605. # e.g. if we have a constructor arg proxies like so:
  606. # {'http': 'ftp://proxy.example.com'}, we may end up turning
  607. # a request for http://acme.example.com/a into one for
  608. # ftp://proxy.example.com/a
  609. return self.parent.open(req, timeout=req.timeout)
  610. class HTTPPasswordMgr:
  611. def __init__(self):
  612. self.passwd = {}
  613. def add_password(self, realm, uri, user, passwd):
  614. # uri could be a single URI or a sequence
  615. if isinstance(uri, basestring):
  616. uri = [uri]
  617. if not realm in self.passwd:
  618. self.passwd[realm] = {}
  619. for default_port in True, False:
  620. reduced_uri = tuple(
  621. [self.reduce_uri(u, default_port) for u in uri])
  622. self.passwd[realm][reduced_uri] = (user, passwd)
  623. def find_user_password(self, realm, authuri):
  624. domains = self.passwd.get(realm, {})
  625. for default_port in True, False:
  626. reduced_authuri = self.reduce_uri(authuri, default_port)
  627. for uris, authinfo in domains.iteritems():
  628. for uri in uris:
  629. if self.is_suburi(uri, reduced_authuri):
  630. return authinfo
  631. return None, None
  632. def reduce_uri(self, uri, default_port=True):
  633. """Accept authority or URI and extract only the authority and path."""
  634. # note HTTP URLs do not have a userinfo component
  635. parts = urlparse.urlsplit(uri)
  636. if parts[1]:
  637. # URI
  638. scheme = parts[0]
  639. authority = parts[1]
  640. path = parts[2] or '/'
  641. else:
  642. # host or host:port
  643. scheme = None
  644. authority = uri
  645. path = '/'
  646. host, port = splitport(authority)
  647. if default_port and port is None and scheme is not None:
  648. dport = {"http": 80,
  649. "https": 443,
  650. }.get(scheme)
  651. if dport is not None:
  652. authority = "%s:%d" % (host, dport)
  653. return authority, path
  654. def is_suburi(self, base, test):
  655. """Check if test is below base in a URI tree
  656. Both args must be URIs in reduced form.
  657. """
  658. if base == test:
  659. return True
  660. if base[0] != test[0]:
  661. return False
  662. common = posixpath.commonprefix((base[1], test[1]))
  663. if len(common) == len(base[1]):
  664. return True
  665. return False
  666. class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr):
  667. def find_user_password(self, realm, authuri):
  668. user, password = HTTPPasswordMgr.find_user_password(self, realm,
  669. authuri)
  670. if user is not None:
  671. return user, password
  672. return HTTPPasswordMgr.find_user_password(self, None, authuri)
  673. class AbstractBasicAuthHandler:
  674. # XXX this allows for multiple auth-schemes, but will stupidly pick
  675. # the last one with a realm specified.
  676. # allow for double- and single-quoted realm values
  677. # (single quotes are a violation of the RFC, but appear in the wild)
  678. rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+'
  679. 'realm=(["\'])(.*?)\\2', re.I)
  680. # XXX could pre-emptively send auth info already accepted (RFC 2617,
  681. # end of section 2, and section 1.2 immediately after "credentials"
  682. # production).
  683. def __init__(self, password_mgr=None):
  684. if password_mgr is None:
  685. password_mgr = HTTPPasswordMgr()
  686. self.passwd = password_mgr
  687. self.add_password = self.passwd.add_password
  688. self.retried = 0
  689. def reset_retry_count(self):
  690. self.retried = 0
  691. def http_error_auth_reqed(self, authreq, host, req, headers):
  692. # host may be an authority (without userinfo) or a URL with an
  693. # authority
  694. # XXX could be multiple headers
  695. authreq = headers.get(authreq, None)
  696. if self.retried > 5:
  697. # retry sending the username:password 5 times before failing.
  698. raise HTTPError(req.get_full_url(), 401, "basic auth failed",
  699. headers, None)
  700. else:
  701. self.retried += 1
  702. if authreq:
  703. mo = AbstractBasicAuthHandler.rx.search(authreq)
  704. if mo:
  705. scheme, quote, realm = mo.groups()
  706. if scheme.lower() == 'basic':
  707. response = self.retry_http_basic_auth(host, req, realm)
  708. if response and response.code != 401:
  709. self.retried = 0
  710. return response
  711. def retry_http_basic_auth(self, host, req, realm):
  712. user, pw = self.passwd.find_user_password(realm, host)
  713. if pw is not None:
  714. raw = "%s:%s" % (user, pw)
  715. auth = 'Basic %s' % base64.b64encode(raw).strip()
  716. if req.headers.get(self.auth_header, None) == auth:
  717. return None
  718. req.add_unredirected_header(self.auth_header, auth)
  719. return self.parent.open(req, timeout=req.timeout)
  720. else:
  721. return None
  722. class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
  723. auth_header = 'Authorization'
  724. def http_error_401(self, req, fp, code, msg, headers):
  725. url = req.get_full_url()
  726. response = self.http_error_auth_reqed('www-authenticate',
  727. url, req, headers)
  728. self.reset_retry_count()
  729. return response
  730. class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
  731. auth_header = 'Proxy-authorization'
  732. def http_error_407(self, req, fp, code, msg, headers):
  733. # http_error_auth_reqed requires that there is no userinfo component in
  734. # authority. Assume there isn't one, since urllib2 does not (and
  735. # should not, RFC 3986 s. 3.2.1) support requests for URLs containing
  736. # userinfo.
  737. authority = req.get_host()
  738. response = self.http_error_auth_reqed('proxy-authenticate',
  739. authority, req, headers)
  740. self.reset_retry_count()
  741. return response
  742. def randombytes(n):
  743. """Return n random bytes."""
  744. # Use /dev/urandom if it is available. Fall back to random module
  745. # if not. It might be worthwhile to extend this function to use
  746. # other platform-specific mechanisms for getting random bytes.
  747. if os.path.exists("/dev/urandom"):
  748. f = open("/dev/urandom")
  749. s = f.read(n)
  750. f.close()
  751. return s
  752. else:
  753. L = [chr(random.randrange(0, 256)) for i in range(n)]
  754. return "".join(L)
  755. class AbstractDigestAuthHandler:
  756. # Digest authentication is specified in RFC 2617.
  757. # XXX The client does not inspect the Authentication-Info header
  758. # in a successful response.
  759. # XXX It should be possible to test this implementation against
  760. # a mock server that just generates a static set of challenges.
  761. # XXX qop="auth-int" supports is shaky
  762. def __init__(self, passwd=None):
  763. if passwd is None:
  764. passwd = HTTPPasswordMgr()
  765. self.passwd = passwd
  766. self.add_password = self.passwd.add_password
  767. self.retried = 0
  768. self.nonce_count = 0
  769. self.last_nonce = None
  770. def reset_retry_count(self):
  771. self.retried = 0
  772. def http_error_auth_reqed(self, auth_header, host, req, headers):
  773. authreq = headers.get(auth_header, None)
  774. if self.retried > 5:
  775. # Don't fail endlessly - if we failed once, we'll probably
  776. # fail a second time. Hm. Unless the Password Manager is
  777. # prompting for the information. Crap. This isn't great
  778. # but it's better than the current 'repeat until recursion
  779. # depth exceeded' approach <wink>
  780. raise HTTPError(req.get_full_url(), 401, "digest auth failed",
  781. headers, None)
  782. else:
  783. self.retried += 1
  784. if authreq:
  785. scheme = authreq.split()[0]
  786. if scheme.lower() == 'digest':
  787. return self.retry_http_digest_auth(req, authreq)
  788. def retry_http_digest_auth(self, req, auth):
  789. token, challenge = auth.split(' ', 1)
  790. chal = parse_keqv_list(parse_http_list(challenge))
  791. auth = self.get_authorization(req, chal)
  792. if auth:
  793. auth_val = 'Digest %s' % auth
  794. if req.headers.get(self.auth_header, None) == auth_val:
  795. return None
  796. req.add_unredirected_header(self.auth_header, auth_val)
  797. resp = self.parent.open(req, timeout=req.timeout)
  798. return resp
  799. def get_cnonce(self, nonce):
  800. # The cnonce-value is an opaque
  801. # quoted string value provided by the client and used by both client
  802. # and server to avoid chosen plaintext attacks, to provide mutual
  803. # authentication, and to provide some message integrity protection.
  804. # This isn't a fabulous effort, but it's probably Good Enough.
  805. dig = hashlib.sha1("%s:%s:%s:%s" % (self.nonce_count, nonce, time.ctime(),
  806. randombytes(8))).hexdigest()
  807. return dig[:16]
  808. def get_authorization(self, req, chal):
  809. try:
  810. realm = chal['realm']
  811. nonce = chal['nonce']
  812. qop = chal.get('qop')
  813. algorithm = chal.get('algorithm', 'MD5')
  814. # mod_digest doesn't send an opaque, even though it isn't
  815. # supposed to be optional
  816. opaque = chal.get('opaque', None)
  817. except KeyError:
  818. return None
  819. H, KD = self.get_algorithm_impls(algorithm)
  820. if H is None:
  821. return None
  822. user, pw = self.passwd.find_user_password(realm, req.get_full_url())
  823. if user is None:
  824. return None
  825. # XXX not implemented yet
  826. if req.has_data():
  827. entdig = self.get_entity_digest(req.get_data(), chal)
  828. else:
  829. entdig = None
  830. A1 = "%s:%s:%s" % (user, realm, pw)
  831. A2 = "%s:%s" % (req.get_method(),
  832. # XXX selector: what about proxies and full urls
  833. req.get_selector())
  834. if qop == 'auth':
  835. if nonce == self.last_nonce:
  836. self.nonce_count += 1
  837. else:
  838. self.nonce_count = 1
  839. self.last_nonce = nonce
  840. ncvalue = '%08x' % self.nonce_count
  841. cnonce = self.get_cnonce(nonce)
  842. noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, H(A2))
  843. respdig = KD(H(A1), noncebit)
  844. elif qop is None:
  845. respdig = KD(H(A1), "%s:%s" % (nonce, H(A2)))
  846. else:
  847. # XXX handle auth-int.
  848. raise URLError("qop '%s' is not supported." % qop)
  849. # XXX should the partial digests be encoded too?
  850. base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \
  851. 'response="%s"' % (user, realm, nonce, req.get_selector(),
  852. respdig)
  853. if opaque:
  854. base += ', opaque="%s"' % opaque
  855. if entdig:
  856. base += ', digest="%s"' % entdig
  857. base += ', algorithm="%s"' % algorithm
  858. if qop:
  859. base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)
  860. return base
  861. def get_algorithm_impls(self, algorithm):
  862. # algorithm should be case-insensitive according to RFC2617
  863. algorithm = algorithm.upper()
  864. # lambdas assume digest modules are imported at the top level
  865. if algorithm == 'MD5':
  866. H = lambda x: hashlib.md5(x).hexdigest()
  867. elif algorithm == 'SHA':
  868. H = lambda x: hashlib.sha1(x).hexdigest()
  869. # XXX MD5-sess
  870. KD = lambda s, d: H("%s:%s" % (s, d))
  871. return H, KD
  872. def get_entity_digest(self, data, chal):
  873. # XXX not implemented yet
  874. return None
  875. class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
  876. """An authentication protocol defined by RFC 2069
  877. Digest authentication improves on basic authentication because it
  878. does not transmit passwords in the clear.
  879. """
  880. auth_header = 'Authorization'
  881. handler_order = 490 # before Basic auth
  882. def http_error_401(self, req, fp, code, msg, headers):
  883. host = urlparse.urlparse(req.get_full_url())[1]
  884. retry = self.http_error_auth_reqed('www-authenticate',
  885. host, req, headers)
  886. self.reset_retry_count()
  887. return retry
  888. class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
  889. auth_header = 'Proxy-Authorization'
  890. handler_order = 490 # before Basic auth
  891. def http_error_407(self, req, fp, code, msg, headers):
  892. host = req.get_host()
  893. retry = self.http_error_auth_reqed('proxy-authenticate',
  894. host, req, headers)
  895. self.reset_retry_count()
  896. return retry
  897. class AbstractHTTPHandler(BaseHandler):
  898. def __init__(self, debuglevel=0):
  899. self._debuglevel = debuglevel
  900. def set_http_debuglevel(self, level):
  901. self._debuglevel = level
  902. def do_request_(self, request):
  903. host = request.get_host()
  904. if not host:
  905. raise URLError('no host given')
  906. if request.has_data(): # POST
  907. data = request.get_data()
  908. if not request.has_header('Content-type'):
  909. request.add_unredirected_header(
  910. 'Content-type',
  911. 'application/x-www-form-urlencoded')
  912. if not request.has_header('Content-length'):
  913. request.add_unredirected_header(
  914. 'Content-length', '%d' % len(data))
  915. sel_host = host
  916. if request.has_proxy():
  917. scheme, sel = splittype(request.get_selector())
  918. sel_host, sel_path = splithost(sel)
  919. if not request.has_header('Host'):
  920. request.add_unredirected_header('Host', sel_host)
  921. for name, value in self.parent.addheaders:
  922. name = name.capitalize()
  923. if not request.has_header(name):
  924. request.add_unredirected_header(name, value)
  925. return request
  926. def do_open(self, http_class, req):
  927. """Return an addinfourl object for the request, using http_class.
  928. http_class must implement the HTTPConnection API from httplib.
  929. The addinfourl return value is a file-like object. It also
  930. has methods and attributes including:
  931. - info(): return a mimetools.Message object for the headers
  932. - geturl(): return the original request URL
  933. - code: HTTP status code
  934. """
  935. host = req.get_host()
  936. if not host:
  937. raise URLError('no host given')
  938. h = http_class(host, timeout=req.timeout) # will parse host:port
  939. h.set_debuglevel(self._debuglevel)
  940. headers = dict(req.unredirected_hdrs)
  941. headers.update(dict((k, v) for k, v in req.headers.items()
  942. if k not in headers))
  943. # We want to make an HTTP/1.1 request, but the addinfourl
  944. # class isn't prepared to deal with a persistent connection.
  945. # It will try to read all remaining data from the socket,
  946. # which will block while the server waits for the next request.
  947. # So make sure the connection gets closed after the (only)
  948. # request.
  949. headers["Connection"] = "close"
  950. headers = dict(
  951. (name.title(), val) for name, val in headers.items())
  952. if req._tunnel_host:
  953. tunnel_headers = {}
  954. proxy_auth_hdr = "Proxy-Authorization"
  955. if proxy_auth_hdr in headers:
  956. tunnel_headers[proxy_auth_hdr] = headers[proxy_auth_hdr]
  957. # Proxy-Authorization should not be sent to origin
  958. # server.
  959. del headers[proxy_auth_hdr]
  960. h.set_tunnel(req._tunnel_host, headers=tunnel_headers)
  961. try:
  962. h.request(req.get_method(), req.get_selector(), req.data, headers)
  963. except socket.error, err: # XXX what error?
  964. h.close()
  965. raise URLError(err)
  966. else:
  967. try:
  968. r = h.getresponse(buffering=True)
  969. except TypeError: # buffering kw not supported
  970. r = h.getresponse()
  971. # Pick apart the HTTPResponse object to get the addinfourl
  972. # object initialized properly.
  973. # Wrap the HTTPResponse object in socket's file object adapter
  974. # for Windows. That adapter calls recv(), so delegate recv()
  975. # to read(). This weird wrapping allows the returned object to
  976. # have readline() and readlines() methods.
  977. # XXX It might be better to extract the read buffering code
  978. # out of socket._fileobject() and into a base class.
  979. r.recv = r.read
  980. fp = socket._fileobject(r, close=True)
  981. resp = addinfourl(fp, r.msg, req.get_full_url())
  982. resp.code = r.status
  983. resp.msg = r.reason
  984. return resp
  985. class HTTPHandler(AbstractHTTPHandler):
  986. def http_open(self, req):
  987. return self.do_open(httplib.HTTPConnection, req)
  988. http_request = AbstractHTTPHandler.do_request_
  989. if hasattr(httplib, 'HTTPS'):
  990. class HTTPSHandler(AbstractHTTPHandler):
  991. def https_open(self, req):
  992. return self.do_open(httplib.HTTPSConnection, req)
  993. https_request = AbstractHTTPHandler.do_request_
  994. class HTTPCookieProcessor(BaseHandler):
  995. def __init__(self, cookiejar=None):
  996. import cookielib
  997. if cookiejar is None:
  998. cookiejar = cookielib.CookieJar()
  999. self.cookiejar = cookiejar
  1000. def http_request(self, request):
  1001. self.cookiejar.add_cookie_header(request)
  1002. return request
  1003. def http_response(self, request, response):
  1004. self.cookiejar.extract_cookies(response, request)
  1005. return response
  1006. https_request = http_request
  1007. https_response = http_response
  1008. class UnknownHandler(BaseHandler):
  1009. def unknown_open(self, req):
  1010. type = req.get_type()
  1011. raise URLError('unknown url type: %s' % type)
  1012. def parse_keqv_list(l):
  1013. """Parse list of key=value strings where keys are not duplicated."""
  1014. parsed = {}
  1015. for elt in l:
  1016. k, v = elt.split('=', 1)
  1017. if v[0] == '"' and v[-1] == '"':
  1018. v = v[1:-1]
  1019. parsed[k] = v
  1020. return parsed
  1021. def parse_http_list(s):
  1022. """Parse lists as described by RFC 2068 Section 2.
  1023. In particular, parse comma-separated lists where the elements of
  1024. the list may include quoted-strings. A quoted-string could
  1025. contain a comma. A non-quoted string could have quotes in the
  1026. middle. Neither commas nor quotes count if they are escaped.
  1027. Only double-quotes count, not single-quotes.
  1028. """
  1029. res = []
  1030. part = ''
  1031. escape = quote = False
  1032. for cur in s:
  1033. if escape:
  1034. part += cur
  1035. escape = False
  1036. continue
  1037. if quote:
  1038. if cur == '\\':
  1039. escape = True
  1040. continue
  1041. elif cur == '"':
  1042. quote = False
  1043. part += cur
  1044. continue
  1045. if cur == ',':
  1046. res.append(part)
  1047. part = ''
  1048. continue
  1049. if cur == '"':
  1050. quote = True
  1051. part += cur
  1052. # append last part
  1053. if part:
  1054. res.append(part)
  1055. return [part.strip() for part in res]
  1056. def _safe_gethostbyname(host):
  1057. try:
  1058. return socket.gethostbyname(host)
  1059. except socket.gaierror:
  1060. return None
  1061. class FileHandler(BaseHandler):
  1062. # Use local file or FTP depending on form of URL
  1063. def file_open(self, req):
  1064. url = req.get_selector()
  1065. if url[:2] == '//' and url[2:3] != '/' and (req.host and
  1066. req.host != 'localhost'):
  1067. req.type = 'ftp'
  1068. return self.parent.open(req)
  1069. else:
  1070. return self.open_local_file(req)
  1071. # names for the localhost
  1072. names = None
  1073. def get_names(self):
  1074. if FileHandler.names is None:
  1075. try:
  1076. FileHandler.names = tuple(
  1077. socket.gethostbyname_ex('localhost')[2] +
  1078. socket.gethostbyname_ex(socket.gethostname())[2])
  1079. except socket.gaierror:
  1080. FileHandler.names = (socket.gethostbyname('localhost'),)
  1081. return FileHandler.names
  1082. # not entirely sure what the rules are here
  1083. def open_local_file(self, req):
  1084. import email.utils
  1085. import mimetypes
  1086. host = req.get_host()
  1087. filename = req.get_selector()
  1088. localfile = url2pathname(filename)
  1089. try:
  1090. stats = os.stat(localfile)
  1091. size = stats.st_size
  1092. modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
  1093. mtype = mimetypes.guess_type(filename)[0]
  1094. headers = mimetools.Message(StringIO(
  1095. 'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' %
  1096. (mtype or 'text/plain', size, modified)))
  1097. if host:
  1098. host, port = splitport(host)
  1099. if not host or \
  1100. (not port and _safe_gethostbyname(host) in self.get_names()):
  1101. if host:
  1102. origurl = 'file://' + host + filename
  1103. else:
  1104. origurl = 'file://' + filename
  1105. return addinfourl(open(localfile, 'rb'), headers, origurl)
  1106. except OSError, msg:
  1107. # urllib2 users shouldn't expect OSErrors coming from urlopen()
  1108. raise URLError(msg)
  1109. raise URLError('file not on local host')
  1110. class FTPHandler(BaseHandler):
  1111. def ftp_open(self, req):
  1112. import ftplib
  1113. import mimetypes
  1114. host = req.get_host()
  1115. if not host:
  1116. raise URLError('ftp error: no host given')
  1117. host, port = splitport(host)
  1118. if port is None:
  1119. port = ftplib.FTP_PORT
  1120. else:
  1121. port = int(port)
  1122. # username/password handling
  1123. user, host = splituser(host)
  1124. if user:
  1125. user, passwd = splitpasswd(user)
  1126. else:
  1127. passwd = None
  1128. host = unquote(host)
  1129. user = user or ''
  1130. passwd = passwd or ''
  1131. try:
  1132. host = socket.gethostbyname(host)
  1133. except socket.error, msg:
  1134. raise URLError(msg)
  1135. path, attrs = splitattr(req.get_selector())
  1136. dirs = path.split('/')
  1137. dirs = map(unquote, dirs)
  1138. dirs, file = dirs[:-1], dirs[-1]
  1139. if dirs and not dirs[0]:
  1140. dirs = dirs[1:]
  1141. try:
  1142. fw = self.connect_ftp(user, passwd, host, port, dirs, req.timeout)
  1143. type = file and 'I' or 'D'
  1144. for attr in attrs:
  1145. attr, value = splitvalue(attr)
  1146. if attr.lower() == 'type' and \
  1147. value in ('a', 'A', 'i', 'I', 'd', 'D'):
  1148. type = value.upper()
  1149. fp, retrlen = fw.retrfile(file, type)
  1150. headers = ""
  1151. mtype = mimetypes.guess_type(req.get_full_url())[0]
  1152. if mtype:
  1153. headers += "Content-type: %s\n" % mtype
  1154. if retrlen is not None and retrlen >= 0:
  1155. headers += "Content-length: %d\n" % retrlen
  1156. sf = StringIO(headers)
  1157. headers = mimetools.Message(sf)
  1158. return addinfourl(fp, headers, req.get_full_url())
  1159. except ftplib.all_errors, msg:
  1160. raise URLError, ('ftp error: %s' % msg), sys.exc_info()[2]
  1161. def connect_ftp(self, user, passwd, host, port, dirs, timeout):
  1162. fw = ftpwrapper(user, passwd, host, port, dirs, timeout,
  1163. persistent=False)
  1164. ## fw.ftp.set_debuglevel(1)
  1165. return fw
  1166. class CacheFTPHandler(FTPHandler):
  1167. # XXX would be nice to have pluggable cache strategies
  1168. # XXX thi

Large files files are truncated, but you can click here to view the full file