1
0

urllib2.py 44 KB

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