PageRenderTime 52ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/urllib2.py

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

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