urllib2.py 51 KB

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