request.py 94 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647
  1. """
  2. Ported using Python-Future from the Python 3.3 standard library.
  3. An extensible library for opening URLs using a variety of protocols
  4. The simplest way to use this module is to call the urlopen function,
  5. which accepts a string containing a URL or a Request object (described
  6. below). It opens the URL and returns the results as file-like
  7. object; the returned object has some extra methods described below.
  8. The OpenerDirector manages a collection of Handler objects that do
  9. all the actual work. Each Handler implements a particular protocol or
  10. option. The OpenerDirector is a composite object that invokes the
  11. Handlers needed to open the requested URL. For example, the
  12. HTTPHandler performs HTTP GET and POST requests and deals with
  13. non-error returns. The HTTPRedirectHandler automatically deals with
  14. HTTP 301, 302, 303 and 307 redirect errors, and the HTTPDigestAuthHandler
  15. deals with digest authentication.
  16. urlopen(url, data=None) -- Basic usage is the same as original
  17. urllib. pass the url and optionally data to post to an HTTP URL, and
  18. get a file-like object back. One difference is that you can also pass
  19. a Request instance instead of URL. Raises a URLError (subclass of
  20. IOError); for HTTP errors, raises an HTTPError, which can also be
  21. treated as a valid response.
  22. build_opener -- Function that creates a new OpenerDirector instance.
  23. Will install the default handlers. Accepts one or more Handlers as
  24. arguments, either instances or Handler classes that it will
  25. instantiate. If one of the argument is a subclass of the default
  26. handler, the argument will be installed instead of the default.
  27. install_opener -- Installs a new opener as the default opener.
  28. objects of interest:
  29. OpenerDirector -- Sets up the User Agent as the Python-urllib client and manages
  30. the Handler classes, while dealing with requests and responses.
  31. Request -- An object that encapsulates the state of a request. The
  32. state can be as simple as the URL. It can also include extra HTTP
  33. headers, e.g. a User-Agent.
  34. BaseHandler --
  35. internals:
  36. BaseHandler and parent
  37. _call_chain conventions
  38. Example usage:
  39. import urllib.request
  40. # set up authentication info
  41. authinfo = urllib.request.HTTPBasicAuthHandler()
  42. authinfo.add_password(realm='PDQ Application',
  43. uri='https://mahler:8092/site-updates.py',
  44. user='klem',
  45. passwd='geheim$parole')
  46. proxy_support = urllib.request.ProxyHandler({"http" : "http://ahad-haam:3128"})
  47. # build a new opener that adds authentication and caching FTP handlers
  48. opener = urllib.request.build_opener(proxy_support, authinfo,
  49. urllib.request.CacheFTPHandler)
  50. # install it
  51. urllib.request.install_opener(opener)
  52. f = urllib.request.urlopen('http://www.python.org/')
  53. """
  54. # XXX issues:
  55. # If an authentication error handler that tries to perform
  56. # authentication for some reason but fails, how should the error be
  57. # signalled? The client needs to know the HTTP error code. But if
  58. # the handler knows that the problem was, e.g., that it didn't know
  59. # that hash algo that requested in the challenge, it would be good to
  60. # pass that information along to the client, too.
  61. # ftp errors aren't handled cleanly
  62. # check digest against correct (i.e. non-apache) implementation
  63. # Possible extensions:
  64. # complex proxies XXX not sure what exactly was meant by this
  65. # abstract factory for opener
  66. from __future__ import absolute_import, division, print_function, unicode_literals
  67. from future.builtins import bytes, dict, filter, input, int, map, open, str
  68. from future.utils import PY2, PY3, raise_with_traceback
  69. import base64
  70. import bisect
  71. import hashlib
  72. import array
  73. from future.backports import email
  74. from future.backports.http import client as http_client
  75. from .error import URLError, HTTPError, ContentTooShortError
  76. from .parse import (
  77. urlparse, urlsplit, urljoin, unwrap, quote, unquote,
  78. splittype, splithost, splitport, splituser, splitpasswd,
  79. splitattr, splitquery, splitvalue, splittag, to_bytes, urlunparse)
  80. from .response import addinfourl, addclosehook
  81. import io
  82. import os
  83. import posixpath
  84. import re
  85. import socket
  86. import sys
  87. import time
  88. import tempfile
  89. import contextlib
  90. import warnings
  91. from future.utils import PY2
  92. if PY2:
  93. from collections import Iterable
  94. else:
  95. from collections.abc import Iterable
  96. # check for SSL
  97. try:
  98. import ssl
  99. # Not available in the SSL module in Py2:
  100. from ssl import SSLContext
  101. except ImportError:
  102. _have_ssl = False
  103. else:
  104. _have_ssl = True
  105. __all__ = [
  106. # Classes
  107. 'Request', 'OpenerDirector', 'BaseHandler', 'HTTPDefaultErrorHandler',
  108. 'HTTPRedirectHandler', 'HTTPCookieProcessor', 'ProxyHandler',
  109. 'HTTPPasswordMgr', 'HTTPPasswordMgrWithDefaultRealm',
  110. 'AbstractBasicAuthHandler', 'HTTPBasicAuthHandler', 'ProxyBasicAuthHandler',
  111. 'AbstractDigestAuthHandler', 'HTTPDigestAuthHandler', 'ProxyDigestAuthHandler',
  112. 'HTTPHandler', 'FileHandler', 'FTPHandler', 'CacheFTPHandler',
  113. 'UnknownHandler', 'HTTPErrorProcessor',
  114. # Functions
  115. 'urlopen', 'install_opener', 'build_opener',
  116. 'pathname2url', 'url2pathname', 'getproxies',
  117. # Legacy interface
  118. 'urlretrieve', 'urlcleanup', 'URLopener', 'FancyURLopener',
  119. ]
  120. # used in User-Agent header sent
  121. __version__ = sys.version[:3]
  122. _opener = None
  123. def urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, **_3to2kwargs):
  124. if 'cadefault' in _3to2kwargs: cadefault = _3to2kwargs['cadefault']; del _3to2kwargs['cadefault']
  125. else: cadefault = False
  126. if 'capath' in _3to2kwargs: capath = _3to2kwargs['capath']; del _3to2kwargs['capath']
  127. else: capath = None
  128. if 'cafile' in _3to2kwargs: cafile = _3to2kwargs['cafile']; del _3to2kwargs['cafile']
  129. else: cafile = None
  130. global _opener
  131. if cafile or capath or cadefault:
  132. if not _have_ssl:
  133. raise ValueError('SSL support not available')
  134. context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
  135. context.options |= ssl.OP_NO_SSLv2
  136. context.verify_mode = ssl.CERT_REQUIRED
  137. if cafile or capath:
  138. context.load_verify_locations(cafile, capath)
  139. else:
  140. context.set_default_verify_paths()
  141. https_handler = HTTPSHandler(context=context, check_hostname=True)
  142. opener = build_opener(https_handler)
  143. elif _opener is None:
  144. _opener = opener = build_opener()
  145. else:
  146. opener = _opener
  147. return opener.open(url, data, timeout)
  148. def install_opener(opener):
  149. global _opener
  150. _opener = opener
  151. _url_tempfiles = []
  152. def urlretrieve(url, filename=None, reporthook=None, data=None):
  153. """
  154. Retrieve a URL into a temporary location on disk.
  155. Requires a URL argument. If a filename is passed, it is used as
  156. the temporary file location. The reporthook argument should be
  157. a callable that accepts a block number, a read size, and the
  158. total file size of the URL target. The data argument should be
  159. valid URL encoded data.
  160. If a filename is passed and the URL points to a local resource,
  161. the result is a copy from local file to new file.
  162. Returns a tuple containing the path to the newly created
  163. data file as well as the resulting HTTPMessage object.
  164. """
  165. url_type, path = splittype(url)
  166. with contextlib.closing(urlopen(url, data)) as fp:
  167. headers = fp.info()
  168. # Just return the local path and the "headers" for file://
  169. # URLs. No sense in performing a copy unless requested.
  170. if url_type == "file" and not filename:
  171. return os.path.normpath(path), headers
  172. # Handle temporary file setup.
  173. if filename:
  174. tfp = open(filename, 'wb')
  175. else:
  176. tfp = tempfile.NamedTemporaryFile(delete=False)
  177. filename = tfp.name
  178. _url_tempfiles.append(filename)
  179. with tfp:
  180. result = filename, headers
  181. bs = 1024*8
  182. size = -1
  183. read = 0
  184. blocknum = 0
  185. if "content-length" in headers:
  186. size = int(headers["Content-Length"])
  187. if reporthook:
  188. reporthook(blocknum, bs, size)
  189. while True:
  190. block = fp.read(bs)
  191. if not block:
  192. break
  193. read += len(block)
  194. tfp.write(block)
  195. blocknum += 1
  196. if reporthook:
  197. reporthook(blocknum, bs, size)
  198. if size >= 0 and read < size:
  199. raise ContentTooShortError(
  200. "retrieval incomplete: got only %i out of %i bytes"
  201. % (read, size), result)
  202. return result
  203. def urlcleanup():
  204. for temp_file in _url_tempfiles:
  205. try:
  206. os.unlink(temp_file)
  207. except EnvironmentError:
  208. pass
  209. del _url_tempfiles[:]
  210. global _opener
  211. if _opener:
  212. _opener = None
  213. if PY3:
  214. _cut_port_re = re.compile(r":\d+$", re.ASCII)
  215. else:
  216. _cut_port_re = re.compile(r":\d+$")
  217. def request_host(request):
  218. """Return request-host, as defined by RFC 2965.
  219. Variation from RFC: returned value is lowercased, for convenient
  220. comparison.
  221. """
  222. url = request.full_url
  223. host = urlparse(url)[1]
  224. if host == "":
  225. host = request.get_header("Host", "")
  226. # remove port, if present
  227. host = _cut_port_re.sub("", host, 1)
  228. return host.lower()
  229. class Request(object):
  230. def __init__(self, url, data=None, headers={},
  231. origin_req_host=None, unverifiable=False,
  232. method=None):
  233. # unwrap('<URL:type://host/path>') --> 'type://host/path'
  234. self.full_url = unwrap(url)
  235. self.full_url, self.fragment = splittag(self.full_url)
  236. self.data = data
  237. self.headers = {}
  238. self._tunnel_host = None
  239. for key, value in headers.items():
  240. self.add_header(key, value)
  241. self.unredirected_hdrs = {}
  242. if origin_req_host is None:
  243. origin_req_host = request_host(self)
  244. self.origin_req_host = origin_req_host
  245. self.unverifiable = unverifiable
  246. self.method = method
  247. self._parse()
  248. def _parse(self):
  249. self.type, rest = splittype(self.full_url)
  250. if self.type is None:
  251. raise ValueError("unknown url type: %r" % self.full_url)
  252. self.host, self.selector = splithost(rest)
  253. if self.host:
  254. self.host = unquote(self.host)
  255. def get_method(self):
  256. """Return a string indicating the HTTP request method."""
  257. if self.method is not None:
  258. return self.method
  259. elif self.data is not None:
  260. return "POST"
  261. else:
  262. return "GET"
  263. def get_full_url(self):
  264. if self.fragment:
  265. return '%s#%s' % (self.full_url, self.fragment)
  266. else:
  267. return self.full_url
  268. # Begin deprecated methods
  269. def add_data(self, data):
  270. msg = "Request.add_data method is deprecated."
  271. warnings.warn(msg, DeprecationWarning, stacklevel=1)
  272. self.data = data
  273. def has_data(self):
  274. msg = "Request.has_data method is deprecated."
  275. warnings.warn(msg, DeprecationWarning, stacklevel=1)
  276. return self.data is not None
  277. def get_data(self):
  278. msg = "Request.get_data method is deprecated."
  279. warnings.warn(msg, DeprecationWarning, stacklevel=1)
  280. return self.data
  281. def get_type(self):
  282. msg = "Request.get_type method is deprecated."
  283. warnings.warn(msg, DeprecationWarning, stacklevel=1)
  284. return self.type
  285. def get_host(self):
  286. msg = "Request.get_host method is deprecated."
  287. warnings.warn(msg, DeprecationWarning, stacklevel=1)
  288. return self.host
  289. def get_selector(self):
  290. msg = "Request.get_selector method is deprecated."
  291. warnings.warn(msg, DeprecationWarning, stacklevel=1)
  292. return self.selector
  293. def is_unverifiable(self):
  294. msg = "Request.is_unverifiable method is deprecated."
  295. warnings.warn(msg, DeprecationWarning, stacklevel=1)
  296. return self.unverifiable
  297. def get_origin_req_host(self):
  298. msg = "Request.get_origin_req_host method is deprecated."
  299. warnings.warn(msg, DeprecationWarning, stacklevel=1)
  300. return self.origin_req_host
  301. # End deprecated methods
  302. def set_proxy(self, host, type):
  303. if self.type == 'https' and not self._tunnel_host:
  304. self._tunnel_host = self.host
  305. else:
  306. self.type= type
  307. self.selector = self.full_url
  308. self.host = host
  309. def has_proxy(self):
  310. return self.selector == self.full_url
  311. def add_header(self, key, val):
  312. # useful for something like authentication
  313. self.headers[key.capitalize()] = val
  314. def add_unredirected_header(self, key, val):
  315. # will not be added to a redirected request
  316. self.unredirected_hdrs[key.capitalize()] = val
  317. def has_header(self, header_name):
  318. return (header_name in self.headers or
  319. header_name in self.unredirected_hdrs)
  320. def get_header(self, header_name, default=None):
  321. return self.headers.get(
  322. header_name,
  323. self.unredirected_hdrs.get(header_name, default))
  324. def header_items(self):
  325. hdrs = self.unredirected_hdrs.copy()
  326. hdrs.update(self.headers)
  327. return list(hdrs.items())
  328. class OpenerDirector(object):
  329. def __init__(self):
  330. client_version = "Python-urllib/%s" % __version__
  331. self.addheaders = [('User-agent', client_version)]
  332. # self.handlers is retained only for backward compatibility
  333. self.handlers = []
  334. # manage the individual handlers
  335. self.handle_open = {}
  336. self.handle_error = {}
  337. self.process_response = {}
  338. self.process_request = {}
  339. def add_handler(self, handler):
  340. if not hasattr(handler, "add_parent"):
  341. raise TypeError("expected BaseHandler instance, got %r" %
  342. type(handler))
  343. added = False
  344. for meth in dir(handler):
  345. if meth in ["redirect_request", "do_open", "proxy_open"]:
  346. # oops, coincidental match
  347. continue
  348. i = meth.find("_")
  349. protocol = meth[:i]
  350. condition = meth[i+1:]
  351. if condition.startswith("error"):
  352. j = condition.find("_") + i + 1
  353. kind = meth[j+1:]
  354. try:
  355. kind = int(kind)
  356. except ValueError:
  357. pass
  358. lookup = self.handle_error.get(protocol, {})
  359. self.handle_error[protocol] = lookup
  360. elif condition == "open":
  361. kind = protocol
  362. lookup = self.handle_open
  363. elif condition == "response":
  364. kind = protocol
  365. lookup = self.process_response
  366. elif condition == "request":
  367. kind = protocol
  368. lookup = self.process_request
  369. else:
  370. continue
  371. handlers = lookup.setdefault(kind, [])
  372. if handlers:
  373. bisect.insort(handlers, handler)
  374. else:
  375. handlers.append(handler)
  376. added = True
  377. if added:
  378. bisect.insort(self.handlers, handler)
  379. handler.add_parent(self)
  380. def close(self):
  381. # Only exists for backwards compatibility.
  382. pass
  383. def _call_chain(self, chain, kind, meth_name, *args):
  384. # Handlers raise an exception if no one else should try to handle
  385. # the request, or return None if they can't but another handler
  386. # could. Otherwise, they return the response.
  387. handlers = chain.get(kind, ())
  388. for handler in handlers:
  389. func = getattr(handler, meth_name)
  390. result = func(*args)
  391. if result is not None:
  392. return result
  393. def open(self, fullurl, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
  394. """
  395. Accept a URL or a Request object
  396. Python-Future: if the URL is passed as a byte-string, decode it first.
  397. """
  398. if isinstance(fullurl, bytes):
  399. fullurl = fullurl.decode()
  400. if isinstance(fullurl, str):
  401. req = Request(fullurl, data)
  402. else:
  403. req = fullurl
  404. if data is not None:
  405. req.data = data
  406. req.timeout = timeout
  407. protocol = req.type
  408. # pre-process request
  409. meth_name = protocol+"_request"
  410. for processor in self.process_request.get(protocol, []):
  411. meth = getattr(processor, meth_name)
  412. req = meth(req)
  413. response = self._open(req, data)
  414. # post-process response
  415. meth_name = protocol+"_response"
  416. for processor in self.process_response.get(protocol, []):
  417. meth = getattr(processor, meth_name)
  418. response = meth(req, response)
  419. return response
  420. def _open(self, req, data=None):
  421. result = self._call_chain(self.handle_open, 'default',
  422. 'default_open', req)
  423. if result:
  424. return result
  425. protocol = req.type
  426. result = self._call_chain(self.handle_open, protocol, protocol +
  427. '_open', req)
  428. if result:
  429. return result
  430. return self._call_chain(self.handle_open, 'unknown',
  431. 'unknown_open', req)
  432. def error(self, proto, *args):
  433. if proto in ('http', 'https'):
  434. # XXX http[s] protocols are special-cased
  435. dict = self.handle_error['http'] # https is not different than http
  436. proto = args[2] # YUCK!
  437. meth_name = 'http_error_%s' % proto
  438. http_err = 1
  439. orig_args = args
  440. else:
  441. dict = self.handle_error
  442. meth_name = proto + '_error'
  443. http_err = 0
  444. args = (dict, proto, meth_name) + args
  445. result = self._call_chain(*args)
  446. if result:
  447. return result
  448. if http_err:
  449. args = (dict, 'default', 'http_error_default') + orig_args
  450. return self._call_chain(*args)
  451. # XXX probably also want an abstract factory that knows when it makes
  452. # sense to skip a superclass in favor of a subclass and when it might
  453. # make sense to include both
  454. def build_opener(*handlers):
  455. """Create an opener object from a list of handlers.
  456. The opener will use several default handlers, including support
  457. for HTTP, FTP and when applicable HTTPS.
  458. If any of the handlers passed as arguments are subclasses of the
  459. default handlers, the default handlers will not be used.
  460. """
  461. def isclass(obj):
  462. return isinstance(obj, type) or hasattr(obj, "__bases__")
  463. opener = OpenerDirector()
  464. default_classes = [ProxyHandler, UnknownHandler, HTTPHandler,
  465. HTTPDefaultErrorHandler, HTTPRedirectHandler,
  466. FTPHandler, FileHandler, HTTPErrorProcessor]
  467. if hasattr(http_client, "HTTPSConnection"):
  468. default_classes.append(HTTPSHandler)
  469. skip = set()
  470. for klass in default_classes:
  471. for check in handlers:
  472. if isclass(check):
  473. if issubclass(check, klass):
  474. skip.add(klass)
  475. elif isinstance(check, klass):
  476. skip.add(klass)
  477. for klass in skip:
  478. default_classes.remove(klass)
  479. for klass in default_classes:
  480. opener.add_handler(klass())
  481. for h in handlers:
  482. if isclass(h):
  483. h = h()
  484. opener.add_handler(h)
  485. return opener
  486. class BaseHandler(object):
  487. handler_order = 500
  488. def add_parent(self, parent):
  489. self.parent = parent
  490. def close(self):
  491. # Only exists for backwards compatibility
  492. pass
  493. def __lt__(self, other):
  494. if not hasattr(other, "handler_order"):
  495. # Try to preserve the old behavior of having custom classes
  496. # inserted after default ones (works only for custom user
  497. # classes which are not aware of handler_order).
  498. return True
  499. return self.handler_order < other.handler_order
  500. class HTTPErrorProcessor(BaseHandler):
  501. """Process HTTP error responses."""
  502. handler_order = 1000 # after all other processing
  503. def http_response(self, request, response):
  504. code, msg, hdrs = response.code, response.msg, response.info()
  505. # According to RFC 2616, "2xx" code indicates that the client's
  506. # request was successfully received, understood, and accepted.
  507. if not (200 <= code < 300):
  508. response = self.parent.error(
  509. 'http', request, response, code, msg, hdrs)
  510. return response
  511. https_response = http_response
  512. class HTTPDefaultErrorHandler(BaseHandler):
  513. def http_error_default(self, req, fp, code, msg, hdrs):
  514. raise HTTPError(req.full_url, code, msg, hdrs, fp)
  515. class HTTPRedirectHandler(BaseHandler):
  516. # maximum number of redirections to any single URL
  517. # this is needed because of the state that cookies introduce
  518. max_repeats = 4
  519. # maximum total number of redirections (regardless of URL) before
  520. # assuming we're in a loop
  521. max_redirections = 10
  522. def redirect_request(self, req, fp, code, msg, headers, newurl):
  523. """Return a Request or None in response to a redirect.
  524. This is called by the http_error_30x methods when a
  525. redirection response is received. If a redirection should
  526. take place, return a new Request to allow http_error_30x to
  527. perform the redirect. Otherwise, raise HTTPError if no-one
  528. else should try to handle this url. Return None if you can't
  529. but another Handler might.
  530. """
  531. m = req.get_method()
  532. if (not (code in (301, 302, 303, 307) and m in ("GET", "HEAD")
  533. or code in (301, 302, 303) and m == "POST")):
  534. raise HTTPError(req.full_url, code, msg, headers, fp)
  535. # Strictly (according to RFC 2616), 301 or 302 in response to
  536. # a POST MUST NOT cause a redirection without confirmation
  537. # from the user (of urllib.request, in this case). In practice,
  538. # essentially all clients do redirect in this case, so we do
  539. # the same.
  540. # be conciliant with URIs containing a space
  541. newurl = newurl.replace(' ', '%20')
  542. CONTENT_HEADERS = ("content-length", "content-type")
  543. newheaders = dict((k, v) for k, v in req.headers.items()
  544. if k.lower() not in CONTENT_HEADERS)
  545. return Request(newurl,
  546. headers=newheaders,
  547. origin_req_host=req.origin_req_host,
  548. unverifiable=True)
  549. # Implementation note: To avoid the server sending us into an
  550. # infinite loop, the request object needs to track what URLs we
  551. # have already seen. Do this by adding a handler-specific
  552. # attribute to the Request object.
  553. def http_error_302(self, req, fp, code, msg, headers):
  554. # Some servers (incorrectly) return multiple Location headers
  555. # (so probably same goes for URI). Use first header.
  556. if "location" in headers:
  557. newurl = headers["location"]
  558. elif "uri" in headers:
  559. newurl = headers["uri"]
  560. else:
  561. return
  562. # fix a possible malformed URL
  563. urlparts = urlparse(newurl)
  564. # For security reasons we don't allow redirection to anything other
  565. # than http, https or ftp.
  566. if urlparts.scheme not in ('http', 'https', 'ftp', ''):
  567. raise HTTPError(
  568. newurl, code,
  569. "%s - Redirection to url '%s' is not allowed" % (msg, newurl),
  570. headers, fp)
  571. if not urlparts.path:
  572. urlparts = list(urlparts)
  573. urlparts[2] = "/"
  574. newurl = urlunparse(urlparts)
  575. newurl = urljoin(req.full_url, newurl)
  576. # XXX Probably want to forget about the state of the current
  577. # request, although that might interact poorly with other
  578. # handlers that also use handler-specific request attributes
  579. new = self.redirect_request(req, fp, code, msg, headers, newurl)
  580. if new is None:
  581. return
  582. # loop detection
  583. # .redirect_dict has a key url if url was previously visited.
  584. if hasattr(req, 'redirect_dict'):
  585. visited = new.redirect_dict = req.redirect_dict
  586. if (visited.get(newurl, 0) >= self.max_repeats or
  587. len(visited) >= self.max_redirections):
  588. raise HTTPError(req.full_url, code,
  589. self.inf_msg + msg, headers, fp)
  590. else:
  591. visited = new.redirect_dict = req.redirect_dict = {}
  592. visited[newurl] = visited.get(newurl, 0) + 1
  593. # Don't close the fp until we are sure that we won't use it
  594. # with HTTPError.
  595. fp.read()
  596. fp.close()
  597. return self.parent.open(new, timeout=req.timeout)
  598. http_error_301 = http_error_303 = http_error_307 = http_error_302
  599. inf_msg = "The HTTP server returned a redirect error that would " \
  600. "lead to an infinite loop.\n" \
  601. "The last 30x error message was:\n"
  602. def _parse_proxy(proxy):
  603. """Return (scheme, user, password, host/port) given a URL or an authority.
  604. If a URL is supplied, it must have an authority (host:port) component.
  605. According to RFC 3986, having an authority component means the URL must
  606. have two slashes after the scheme:
  607. >>> _parse_proxy('file:/ftp.example.com/')
  608. Traceback (most recent call last):
  609. ValueError: proxy URL with no authority: 'file:/ftp.example.com/'
  610. The first three items of the returned tuple may be None.
  611. Examples of authority parsing:
  612. >>> _parse_proxy('proxy.example.com')
  613. (None, None, None, 'proxy.example.com')
  614. >>> _parse_proxy('proxy.example.com:3128')
  615. (None, None, None, 'proxy.example.com:3128')
  616. The authority component may optionally include userinfo (assumed to be
  617. username:password):
  618. >>> _parse_proxy('joe:password@proxy.example.com')
  619. (None, 'joe', 'password', 'proxy.example.com')
  620. >>> _parse_proxy('joe:password@proxy.example.com:3128')
  621. (None, 'joe', 'password', 'proxy.example.com:3128')
  622. Same examples, but with URLs instead:
  623. >>> _parse_proxy('http://proxy.example.com/')
  624. ('http', None, None, 'proxy.example.com')
  625. >>> _parse_proxy('http://proxy.example.com:3128/')
  626. ('http', None, None, 'proxy.example.com:3128')
  627. >>> _parse_proxy('http://joe:password@proxy.example.com/')
  628. ('http', 'joe', 'password', 'proxy.example.com')
  629. >>> _parse_proxy('http://joe:password@proxy.example.com:3128')
  630. ('http', 'joe', 'password', 'proxy.example.com:3128')
  631. Everything after the authority is ignored:
  632. >>> _parse_proxy('ftp://joe:password@proxy.example.com/rubbish:3128')
  633. ('ftp', 'joe', 'password', 'proxy.example.com')
  634. Test for no trailing '/' case:
  635. >>> _parse_proxy('http://joe:password@proxy.example.com')
  636. ('http', 'joe', 'password', 'proxy.example.com')
  637. """
  638. scheme, r_scheme = splittype(proxy)
  639. if not r_scheme.startswith("/"):
  640. # authority
  641. scheme = None
  642. authority = proxy
  643. else:
  644. # URL
  645. if not r_scheme.startswith("//"):
  646. raise ValueError("proxy URL with no authority: %r" % proxy)
  647. # We have an authority, so for RFC 3986-compliant URLs (by ss 3.
  648. # and 3.3.), path is empty or starts with '/'
  649. end = r_scheme.find("/", 2)
  650. if end == -1:
  651. end = None
  652. authority = r_scheme[2:end]
  653. userinfo, hostport = splituser(authority)
  654. if userinfo is not None:
  655. user, password = splitpasswd(userinfo)
  656. else:
  657. user = password = None
  658. return scheme, user, password, hostport
  659. class ProxyHandler(BaseHandler):
  660. # Proxies must be in front
  661. handler_order = 100
  662. def __init__(self, proxies=None):
  663. if proxies is None:
  664. proxies = getproxies()
  665. assert hasattr(proxies, 'keys'), "proxies must be a mapping"
  666. self.proxies = proxies
  667. for type, url in proxies.items():
  668. setattr(self, '%s_open' % type,
  669. lambda r, proxy=url, type=type, meth=self.proxy_open:
  670. meth(r, proxy, type))
  671. def proxy_open(self, req, proxy, type):
  672. orig_type = req.type
  673. proxy_type, user, password, hostport = _parse_proxy(proxy)
  674. if proxy_type is None:
  675. proxy_type = orig_type
  676. if req.host and proxy_bypass(req.host):
  677. return None
  678. if user and password:
  679. user_pass = '%s:%s' % (unquote(user),
  680. unquote(password))
  681. creds = base64.b64encode(user_pass.encode()).decode("ascii")
  682. req.add_header('Proxy-authorization', 'Basic ' + creds)
  683. hostport = unquote(hostport)
  684. req.set_proxy(hostport, proxy_type)
  685. if orig_type == proxy_type or orig_type == 'https':
  686. # let other handlers take care of it
  687. return None
  688. else:
  689. # need to start over, because the other handlers don't
  690. # grok the proxy's URL type
  691. # e.g. if we have a constructor arg proxies like so:
  692. # {'http': 'ftp://proxy.example.com'}, we may end up turning
  693. # a request for http://acme.example.com/a into one for
  694. # ftp://proxy.example.com/a
  695. return self.parent.open(req, timeout=req.timeout)
  696. class HTTPPasswordMgr(object):
  697. def __init__(self):
  698. self.passwd = {}
  699. def add_password(self, realm, uri, user, passwd):
  700. # uri could be a single URI or a sequence
  701. if isinstance(uri, str):
  702. uri = [uri]
  703. if realm not in self.passwd:
  704. self.passwd[realm] = {}
  705. for default_port in True, False:
  706. reduced_uri = tuple(
  707. [self.reduce_uri(u, default_port) for u in uri])
  708. self.passwd[realm][reduced_uri] = (user, passwd)
  709. def find_user_password(self, realm, authuri):
  710. domains = self.passwd.get(realm, {})
  711. for default_port in True, False:
  712. reduced_authuri = self.reduce_uri(authuri, default_port)
  713. for uris, authinfo in domains.items():
  714. for uri in uris:
  715. if self.is_suburi(uri, reduced_authuri):
  716. return authinfo
  717. return None, None
  718. def reduce_uri(self, uri, default_port=True):
  719. """Accept authority or URI and extract only the authority and path."""
  720. # note HTTP URLs do not have a userinfo component
  721. parts = urlsplit(uri)
  722. if parts[1]:
  723. # URI
  724. scheme = parts[0]
  725. authority = parts[1]
  726. path = parts[2] or '/'
  727. else:
  728. # host or host:port
  729. scheme = None
  730. authority = uri
  731. path = '/'
  732. host, port = splitport(authority)
  733. if default_port and port is None and scheme is not None:
  734. dport = {"http": 80,
  735. "https": 443,
  736. }.get(scheme)
  737. if dport is not None:
  738. authority = "%s:%d" % (host, dport)
  739. return authority, path
  740. def is_suburi(self, base, test):
  741. """Check if test is below base in a URI tree
  742. Both args must be URIs in reduced form.
  743. """
  744. if base == test:
  745. return True
  746. if base[0] != test[0]:
  747. return False
  748. common = posixpath.commonprefix((base[1], test[1]))
  749. if len(common) == len(base[1]):
  750. return True
  751. return False
  752. class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr):
  753. def find_user_password(self, realm, authuri):
  754. user, password = HTTPPasswordMgr.find_user_password(self, realm,
  755. authuri)
  756. if user is not None:
  757. return user, password
  758. return HTTPPasswordMgr.find_user_password(self, None, authuri)
  759. class AbstractBasicAuthHandler(object):
  760. # XXX this allows for multiple auth-schemes, but will stupidly pick
  761. # the last one with a realm specified.
  762. # allow for double- and single-quoted realm values
  763. # (single quotes are a violation of the RFC, but appear in the wild)
  764. rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+'
  765. 'realm=(["\']?)([^"\']*)\\2', re.I)
  766. # XXX could pre-emptively send auth info already accepted (RFC 2617,
  767. # end of section 2, and section 1.2 immediately after "credentials"
  768. # production).
  769. def __init__(self, password_mgr=None):
  770. if password_mgr is None:
  771. password_mgr = HTTPPasswordMgr()
  772. self.passwd = password_mgr
  773. self.add_password = self.passwd.add_password
  774. self.retried = 0
  775. def reset_retry_count(self):
  776. self.retried = 0
  777. def http_error_auth_reqed(self, authreq, host, req, headers):
  778. # host may be an authority (without userinfo) or a URL with an
  779. # authority
  780. # XXX could be multiple headers
  781. authreq = headers.get(authreq, None)
  782. if self.retried > 5:
  783. # retry sending the username:password 5 times before failing.
  784. raise HTTPError(req.get_full_url(), 401, "basic auth failed",
  785. headers, None)
  786. else:
  787. self.retried += 1
  788. if authreq:
  789. scheme = authreq.split()[0]
  790. if scheme.lower() != 'basic':
  791. raise ValueError("AbstractBasicAuthHandler does not"
  792. " support the following scheme: '%s'" %
  793. scheme)
  794. else:
  795. mo = AbstractBasicAuthHandler.rx.search(authreq)
  796. if mo:
  797. scheme, quote, realm = mo.groups()
  798. if quote not in ['"',"'"]:
  799. warnings.warn("Basic Auth Realm was unquoted",
  800. UserWarning, 2)
  801. if scheme.lower() == 'basic':
  802. response = self.retry_http_basic_auth(host, req, realm)
  803. if response and response.code != 401:
  804. self.retried = 0
  805. return response
  806. def retry_http_basic_auth(self, host, req, realm):
  807. user, pw = self.passwd.find_user_password(realm, host)
  808. if pw is not None:
  809. raw = "%s:%s" % (user, pw)
  810. auth = "Basic " + base64.b64encode(raw.encode()).decode("ascii")
  811. if req.headers.get(self.auth_header, None) == auth:
  812. return None
  813. req.add_unredirected_header(self.auth_header, auth)
  814. return self.parent.open(req, timeout=req.timeout)
  815. else:
  816. return None
  817. class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
  818. auth_header = 'Authorization'
  819. def http_error_401(self, req, fp, code, msg, headers):
  820. url = req.full_url
  821. response = self.http_error_auth_reqed('www-authenticate',
  822. url, req, headers)
  823. self.reset_retry_count()
  824. return response
  825. class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
  826. auth_header = 'Proxy-authorization'
  827. def http_error_407(self, req, fp, code, msg, headers):
  828. # http_error_auth_reqed requires that there is no userinfo component in
  829. # authority. Assume there isn't one, since urllib.request does not (and
  830. # should not, RFC 3986 s. 3.2.1) support requests for URLs containing
  831. # userinfo.
  832. authority = req.host
  833. response = self.http_error_auth_reqed('proxy-authenticate',
  834. authority, req, headers)
  835. self.reset_retry_count()
  836. return response
  837. # Return n random bytes.
  838. _randombytes = os.urandom
  839. class AbstractDigestAuthHandler(object):
  840. # Digest authentication is specified in RFC 2617.
  841. # XXX The client does not inspect the Authentication-Info header
  842. # in a successful response.
  843. # XXX It should be possible to test this implementation against
  844. # a mock server that just generates a static set of challenges.
  845. # XXX qop="auth-int" supports is shaky
  846. def __init__(self, passwd=None):
  847. if passwd is None:
  848. passwd = HTTPPasswordMgr()
  849. self.passwd = passwd
  850. self.add_password = self.passwd.add_password
  851. self.retried = 0
  852. self.nonce_count = 0
  853. self.last_nonce = None
  854. def reset_retry_count(self):
  855. self.retried = 0
  856. def http_error_auth_reqed(self, auth_header, host, req, headers):
  857. authreq = headers.get(auth_header, None)
  858. if self.retried > 5:
  859. # Don't fail endlessly - if we failed once, we'll probably
  860. # fail a second time. Hm. Unless the Password Manager is
  861. # prompting for the information. Crap. This isn't great
  862. # but it's better than the current 'repeat until recursion
  863. # depth exceeded' approach <wink>
  864. raise HTTPError(req.full_url, 401, "digest auth failed",
  865. headers, None)
  866. else:
  867. self.retried += 1
  868. if authreq:
  869. scheme = authreq.split()[0]
  870. if scheme.lower() == 'digest':
  871. return self.retry_http_digest_auth(req, authreq)
  872. elif scheme.lower() != 'basic':
  873. raise ValueError("AbstractDigestAuthHandler does not support"
  874. " the following scheme: '%s'" % scheme)
  875. def retry_http_digest_auth(self, req, auth):
  876. token, challenge = auth.split(' ', 1)
  877. chal = parse_keqv_list(filter(None, parse_http_list(challenge)))
  878. auth = self.get_authorization(req, chal)
  879. if auth:
  880. auth_val = 'Digest %s' % auth
  881. if req.headers.get(self.auth_header, None) == auth_val:
  882. return None
  883. req.add_unredirected_header(self.auth_header, auth_val)
  884. resp = self.parent.open(req, timeout=req.timeout)
  885. return resp
  886. def get_cnonce(self, nonce):
  887. # The cnonce-value is an opaque
  888. # quoted string value provided by the client and used by both client
  889. # and server to avoid chosen plaintext attacks, to provide mutual
  890. # authentication, and to provide some message integrity protection.
  891. # This isn't a fabulous effort, but it's probably Good Enough.
  892. s = "%s:%s:%s:" % (self.nonce_count, nonce, time.ctime())
  893. b = s.encode("ascii") + _randombytes(8)
  894. dig = hashlib.sha1(b).hexdigest()
  895. return dig[:16]
  896. def get_authorization(self, req, chal):
  897. try:
  898. realm = chal['realm']
  899. nonce = chal['nonce']
  900. qop = chal.get('qop')
  901. algorithm = chal.get('algorithm', 'MD5')
  902. # mod_digest doesn't send an opaque, even though it isn't
  903. # supposed to be optional
  904. opaque = chal.get('opaque', None)
  905. except KeyError:
  906. return None
  907. H, KD = self.get_algorithm_impls(algorithm)
  908. if H is None:
  909. return None
  910. user, pw = self.passwd.find_user_password(realm, req.full_url)
  911. if user is None:
  912. return None
  913. # XXX not implemented yet
  914. if req.data is not None:
  915. entdig = self.get_entity_digest(req.data, chal)
  916. else:
  917. entdig = None
  918. A1 = "%s:%s:%s" % (user, realm, pw)
  919. A2 = "%s:%s" % (req.get_method(),
  920. # XXX selector: what about proxies and full urls
  921. req.selector)
  922. if qop == 'auth':
  923. if nonce == self.last_nonce:
  924. self.nonce_count += 1
  925. else:
  926. self.nonce_count = 1
  927. self.last_nonce = nonce
  928. ncvalue = '%08x' % self.nonce_count
  929. cnonce = self.get_cnonce(nonce)
  930. noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, H(A2))
  931. respdig = KD(H(A1), noncebit)
  932. elif qop is None:
  933. respdig = KD(H(A1), "%s:%s" % (nonce, H(A2)))
  934. else:
  935. # XXX handle auth-int.
  936. raise URLError("qop '%s' is not supported." % qop)
  937. # XXX should the partial digests be encoded too?
  938. base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \
  939. 'response="%s"' % (user, realm, nonce, req.selector,
  940. respdig)
  941. if opaque:
  942. base += ', opaque="%s"' % opaque
  943. if entdig:
  944. base += ', digest="%s"' % entdig
  945. base += ', algorithm="%s"' % algorithm
  946. if qop:
  947. base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)
  948. return base
  949. def get_algorithm_impls(self, algorithm):
  950. # lambdas assume digest modules are imported at the top level
  951. if algorithm == 'MD5':
  952. H = lambda x: hashlib.md5(x.encode("ascii")).hexdigest()
  953. elif algorithm == 'SHA':
  954. H = lambda x: hashlib.sha1(x.encode("ascii")).hexdigest()
  955. # XXX MD5-sess
  956. KD = lambda s, d: H("%s:%s" % (s, d))
  957. return H, KD
  958. def get_entity_digest(self, data, chal):
  959. # XXX not implemented yet
  960. return None
  961. class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
  962. """An authentication protocol defined by RFC 2069
  963. Digest authentication improves on basic authentication because it
  964. does not transmit passwords in the clear.
  965. """
  966. auth_header = 'Authorization'
  967. handler_order = 490 # before Basic auth
  968. def http_error_401(self, req, fp, code, msg, headers):
  969. host = urlparse(req.full_url)[1]
  970. retry = self.http_error_auth_reqed('www-authenticate',
  971. host, req, headers)
  972. self.reset_retry_count()
  973. return retry
  974. class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
  975. auth_header = 'Proxy-Authorization'
  976. handler_order = 490 # before Basic auth
  977. def http_error_407(self, req, fp, code, msg, headers):
  978. host = req.host
  979. retry = self.http_error_auth_reqed('proxy-authenticate',
  980. host, req, headers)
  981. self.reset_retry_count()
  982. return retry
  983. class AbstractHTTPHandler(BaseHandler):
  984. def __init__(self, debuglevel=0):
  985. self._debuglevel = debuglevel
  986. def set_http_debuglevel(self, level):
  987. self._debuglevel = level
  988. def do_request_(self, request):
  989. host = request.host
  990. if not host:
  991. raise URLError('no host given')
  992. if request.data is not None: # POST
  993. data = request.data
  994. if isinstance(data, str):
  995. msg = "POST data should be bytes or an iterable of bytes. " \
  996. "It cannot be of type str."
  997. raise TypeError(msg)
  998. if not request.has_header('Content-type'):
  999. request.add_unredirected_header(
  1000. 'Content-type',
  1001. 'application/x-www-form-urlencoded')
  1002. if not request.has_header('Content-length'):
  1003. size = None
  1004. try:
  1005. ### For Python-Future:
  1006. if PY2 and isinstance(data, array.array):
  1007. # memoryviews of arrays aren't supported
  1008. # in Py2.7. (e.g. memoryview(array.array('I',
  1009. # [1, 2, 3, 4])) raises a TypeError.)
  1010. # So we calculate the size manually instead:
  1011. size = len(data) * data.itemsize
  1012. ###
  1013. else:
  1014. mv = memoryview(data)
  1015. size = len(mv) * mv.itemsize
  1016. except TypeError:
  1017. if isinstance(data, Iterable):
  1018. raise ValueError("Content-Length should be specified "
  1019. "for iterable data of type %r %r" % (type(data),
  1020. data))
  1021. else:
  1022. request.add_unredirected_header(
  1023. 'Content-length', '%d' % size)
  1024. sel_host = host
  1025. if request.has_proxy():
  1026. scheme, sel = splittype(request.selector)
  1027. sel_host, sel_path = splithost(sel)
  1028. if not request.has_header('Host'):
  1029. request.add_unredirected_header('Host', sel_host)
  1030. for name, value in self.parent.addheaders:
  1031. name = name.capitalize()
  1032. if not request.has_header(name):
  1033. request.add_unredirected_header(name, value)
  1034. return request
  1035. def do_open(self, http_class, req, **http_conn_args):
  1036. """Return an HTTPResponse object for the request, using http_class.
  1037. http_class must implement the HTTPConnection API from http.client.
  1038. """
  1039. host = req.host
  1040. if not host:
  1041. raise URLError('no host given')
  1042. # will parse host:port
  1043. h = http_class(host, timeout=req.timeout, **http_conn_args)
  1044. headers = dict(req.unredirected_hdrs)
  1045. headers.update(dict((k, v) for k, v in req.headers.items()
  1046. if k not in headers))
  1047. # TODO(jhylton): Should this be redesigned to handle
  1048. # persistent connections?
  1049. # We want to make an HTTP/1.1 request, but the addinfourl
  1050. # class isn't prepared to deal with a persistent connection.
  1051. # It will try to read all remaining data from the socket,
  1052. # which will block while the server waits for the next request.
  1053. # So make sure the connection gets closed after the (only)
  1054. # request.
  1055. headers["Connection"] = "close"
  1056. headers = dict((name.title(), val) for name, val in headers.items())
  1057. if req._tunnel_host:
  1058. tunnel_headers = {}
  1059. proxy_auth_hdr = "Proxy-Authorization"
  1060. if proxy_auth_hdr in headers:
  1061. tunnel_headers[proxy_auth_hdr] = headers[proxy_auth_hdr]
  1062. # Proxy-Authorization should not be sent to origin
  1063. # server.
  1064. del headers[proxy_auth_hdr]
  1065. h.set_tunnel(req._tunnel_host, headers=tunnel_headers)
  1066. try:
  1067. h.request(req.get_method(), req.selector, req.data, headers)
  1068. except socket.error as err: # timeout error
  1069. h.close()
  1070. raise URLError(err)
  1071. else:
  1072. r = h.getresponse()
  1073. # If the server does not send us a 'Connection: close' header,
  1074. # HTTPConnection assumes the socket should be left open. Manually
  1075. # mark the socket to be closed when this response object goes away.
  1076. if h.sock:
  1077. h.sock.close()
  1078. h.sock = None
  1079. r.url = req.get_full_url()
  1080. # This line replaces the .msg attribute of the HTTPResponse
  1081. # with .headers, because urllib clients expect the response to
  1082. # have the reason in .msg. It would be good to mark this
  1083. # attribute is deprecated and get then to use info() or
  1084. # .headers.
  1085. r.msg = r.reason
  1086. return r
  1087. class HTTPHandler(AbstractHTTPHandler):
  1088. def http_open(self, req):
  1089. return self.do_open(http_client.HTTPConnection, req)
  1090. http_request = AbstractHTTPHandler.do_request_
  1091. if hasattr(http_client, 'HTTPSConnection'):
  1092. class HTTPSHandler(AbstractHTTPHandler):
  1093. def __init__(self, debuglevel=0, context=None, check_hostname=None):
  1094. AbstractHTTPHandler.__init__(self, debuglevel)
  1095. self._context = context
  1096. self._check_hostname = check_hostname
  1097. def https_open(self, req):
  1098. return self.do_open(http_client.HTTPSConnection, req,
  1099. context=self._context, check_hostname=self._check_hostname)
  1100. https_request = AbstractHTTPHandler.do_request_
  1101. __all__.append('HTTPSHandler')
  1102. class HTTPCookieProcessor(BaseHandler):
  1103. def __init__(self, cookiejar=None):
  1104. import future.backports.http.cookiejar as http_cookiejar
  1105. if cookiejar is None:
  1106. cookiejar = http_cookiejar.CookieJar()
  1107. self.cookiejar = cookiejar
  1108. def http_request(self, request):
  1109. self.cookiejar.add_cookie_header(request)
  1110. return request
  1111. def http_response(self, request, response):
  1112. self.cookiejar.extract_cookies(response, request)
  1113. return response
  1114. https_request = http_request
  1115. https_response = http_response
  1116. class UnknownHandler(BaseHandler):
  1117. def unknown_open(self, req):
  1118. type = req.type
  1119. raise URLError('unknown url type: %s' % type)
  1120. def parse_keqv_list(l):
  1121. """Parse list of key=value strings where keys are not duplicated."""
  1122. parsed = {}
  1123. for elt in l:
  1124. k, v = elt.split('=', 1)
  1125. if v[0] == '"' and v[-1] == '"':
  1126. v = v[1:-1]
  1127. parsed[k] = v
  1128. return parsed
  1129. def parse_http_list(s):
  1130. """Parse lists as described by RFC 2068 Section 2.
  1131. In particular, parse comma-separated lists where the elements of
  1132. the list may include quoted-strings. A quoted-string could
  1133. contain a comma. A non-quoted string could have quotes in the
  1134. middle. Neither commas nor quotes count if they are escaped.
  1135. Only double-quotes count, not single-quotes.
  1136. """
  1137. res = []
  1138. part = ''
  1139. escape = quote = False
  1140. for cur in s:
  1141. if escape:
  1142. part += cur
  1143. escape = False
  1144. continue
  1145. if quote:
  1146. if cur == '\\':
  1147. escape = True
  1148. continue
  1149. elif cur == '"':
  1150. quote = False
  1151. part += cur
  1152. continue
  1153. if cur == ',':
  1154. res.append(part)
  1155. part = ''
  1156. continue
  1157. if cur == '"':
  1158. quote = True
  1159. part += cur
  1160. # append last part
  1161. if part:
  1162. res.append(part)
  1163. return [part.strip() for part in res]
  1164. class FileHandler(BaseHandler):
  1165. # Use local file or FTP depending on form of URL
  1166. def file_open(self, req):
  1167. url = req.selector
  1168. if url[:2] == '//' and url[2:3] != '/' and (req.host and
  1169. req.host != 'localhost'):
  1170. if not req.host is self.get_names():
  1171. raise URLError("file:// scheme is supported only on localhost")
  1172. else:
  1173. return self.open_local_file(req)
  1174. # names for the localhost
  1175. names = None
  1176. def get_names(self):
  1177. if FileHandler.names is None:
  1178. try:
  1179. FileHandler.names = tuple(
  1180. socket.gethostbyname_ex('localhost')[2] +
  1181. socket.gethostbyname_ex(socket.gethostname())[2])
  1182. except socket.gaierror:
  1183. FileHandler.names = (socket.gethostbyname('localhost'),)
  1184. return FileHandler.names
  1185. # not entirely sure what the rules are here
  1186. def open_local_file(self, req):
  1187. import future.backports.email.utils as email_utils
  1188. import mimetypes
  1189. host = req.host
  1190. filename = req.selector
  1191. localfile = url2pathname(filename)
  1192. try:
  1193. stats = os.stat(localfile)
  1194. size = stats.st_size
  1195. modified = email_utils.formatdate(stats.st_mtime, usegmt=True)
  1196. mtype = mimetypes.guess_type(filename)[0]
  1197. headers = email.message_from_string(
  1198. 'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' %
  1199. (mtype or 'text/plain', size, modified))
  1200. if host:
  1201. host, port = splitport(host)
  1202. if not host or \
  1203. (not port and _safe_gethostbyname(host) in self.get_names()):
  1204. if host:
  1205. origurl = 'file://' + host + filename
  1206. else:
  1207. origurl = 'file://' + filename
  1208. return addinfourl(open(localfile, 'rb'), headers, origurl)
  1209. except OSError as exp:
  1210. # users shouldn't expect OSErrors coming from urlopen()
  1211. raise URLError(exp)
  1212. raise URLError('file not on local host')
  1213. def _safe_gethostbyname(host):
  1214. try:
  1215. return socket.gethostbyname(host)
  1216. except socket.gaierror:
  1217. return None
  1218. class FTPHandler(BaseHandler):
  1219. def ftp_open(self, req):
  1220. import ftplib
  1221. import mimetypes
  1222. host = req.host
  1223. if not host:
  1224. raise URLError('ftp error: no host given')
  1225. host, port = splitport(host)
  1226. if port is None:
  1227. port = ftplib.FTP_PORT
  1228. else:
  1229. port = int(port)
  1230. # username/password handling
  1231. user, host = splituser(host)
  1232. if user:
  1233. user, passwd = splitpasswd(user)
  1234. else:
  1235. passwd = None
  1236. host = unquote(host)
  1237. user = user or ''
  1238. passwd = passwd or ''
  1239. try:
  1240. host = socket.gethostbyname(host)
  1241. except socket.error as msg:
  1242. raise URLError(msg)
  1243. path, attrs = splitattr(req.selector)
  1244. dirs = path.split('/')
  1245. dirs = list(map(unquote, dirs))
  1246. dirs, file = dirs[:-1], dirs[-1]
  1247. if dirs and not dirs[0]:
  1248. dirs = dirs[1:]
  1249. try:
  1250. fw = self.connect_ftp(user, passwd, host, port, dirs, req.timeout)
  1251. type = file and 'I' or 'D'
  1252. for attr in attrs:
  1253. attr, value = splitvalue(attr)
  1254. if attr.lower() == 'type' and \
  1255. value in ('a', 'A', 'i', 'I', 'd', 'D'):
  1256. type = value.upper()
  1257. fp, retrlen = fw.retrfile(file, type)
  1258. headers = ""
  1259. mtype = mimetypes.guess_type(req.full_url)[0]
  1260. if mtype:
  1261. headers += "Content-type: %s\n" % mtype
  1262. if retrlen is not None and retrlen >= 0:
  1263. headers += "Content-length: %d\n" % retrlen
  1264. headers = email.message_from_string(headers)
  1265. return addinfourl(fp, headers, req.full_url)
  1266. except ftplib.all_errors as exp:
  1267. exc = URLError('ftp error: %r' % exp)
  1268. raise_with_traceback(exc)
  1269. def connect_ftp(self, user, passwd, host, port, dirs, timeout):
  1270. return ftpwrapper(user, passwd, host, port, dirs, timeout,
  1271. persistent=False)
  1272. class CacheFTPHandler(FTPHandler):
  1273. # XXX would be nice to have pluggable cache strategies
  1274. # XXX this stuff is definitely not thread safe
  1275. def __init__(self):
  1276. self.cache = {}
  1277. self.timeout = {}
  1278. self.soonest = 0
  1279. self.delay = 60
  1280. self.max_conns = 16
  1281. def setTimeout(self, t):
  1282. self.delay = t
  1283. def setMaxConns(self, m):
  1284. self.max_conns = m
  1285. def connect_ftp(self, user, passwd, host, port, dirs, timeout):
  1286. key = user, host, port, '/'.join(dirs), timeout
  1287. if key in self.cache:
  1288. self.timeout[key] = time.time() + self.delay
  1289. else:
  1290. self.cache[key] = ftpwrapper(user, passwd, host, port,
  1291. dirs, timeout)
  1292. self.timeout[key] = time.time() + self.delay
  1293. self.check_cache()
  1294. return self.cache[key]
  1295. def check_cache(self):
  1296. # first check for old ones
  1297. t = time.time()
  1298. if self.soonest <= t:
  1299. for k, v in list(self.timeout.items()):
  1300. if v < t:
  1301. self.cache[k].close()
  1302. del self.cache[k]
  1303. del self.timeout[k]
  1304. self.soonest = min(list(self.timeout.values()))
  1305. # then check the size
  1306. if len(self.cache) == self.max_conns:
  1307. for k, v in list(self.timeout.items()):
  1308. if v == self.soonest:
  1309. del self.cache[k]
  1310. del self.timeout[k]
  1311. break
  1312. self.soonest = min(list(self.timeout.values()))
  1313. def clear_cache(self):
  1314. for conn in self.cache.values():
  1315. conn.close()
  1316. self.cache.clear()
  1317. self.timeout.clear()
  1318. # Code move from the old urllib module
  1319. MAXFTPCACHE = 10 # Trim the ftp cache beyond this size
  1320. # Helper for non-unix systems
  1321. if os.name == 'nt':
  1322. from nturl2path import url2pathname, pathname2url
  1323. else:
  1324. def url2pathname(pathname):
  1325. """OS-specific conversion from a relative URL of the 'file' scheme
  1326. to a file system path; not recommended for general use."""
  1327. return unquote(pathname)
  1328. def pathname2url(pathname):
  1329. """OS-specific conversion from a file system path to a relative URL
  1330. of the 'file' scheme; not recommended for general use."""
  1331. return quote(pathname)
  1332. # This really consists of two pieces:
  1333. # (1) a class which handles opening of all sorts of URLs
  1334. # (plus assorted utilities etc.)
  1335. # (2) a set of functions for parsing URLs
  1336. # XXX Should these be separated out into different modules?
  1337. ftpcache = {}
  1338. class URLopener(object):
  1339. """Class to open URLs.
  1340. This is a class rather than just a subroutine because we may need
  1341. more than one set of global protocol-specific options.
  1342. Note -- this is a base class for those who don't want the
  1343. automatic handling of errors type 302 (relocated) and 401
  1344. (authorization needed)."""
  1345. __tempfiles = None
  1346. version = "Python-urllib/%s" % __version__
  1347. # Constructor
  1348. def __init__(self, proxies=None, **x509):
  1349. msg = "%(class)s style of invoking requests is deprecated. " \
  1350. "Use newer urlopen functions/methods" % {'class': self.__class__.__name__}
  1351. warnings.warn(msg, DeprecationWarning, stacklevel=3)
  1352. if proxies is None:
  1353. proxies = getproxies()
  1354. assert hasattr(proxies, 'keys'), "proxies must be a mapping"
  1355. self.proxies = proxies
  1356. self.key_file = x509.get('key_file')
  1357. self.cert_file = x509.get('cert_file')
  1358. self.addheaders = [('User-Agent', self.version)]
  1359. self.__tempfiles = []
  1360. self.__unlink = os.unlink # See cleanup()
  1361. self.tempcache = None
  1362. # Undocumented feature: if you assign {} to tempcache,
  1363. # it is used to cache files retrieved with
  1364. # self.retrieve(). This is not enabled by default
  1365. # since it does not work for changing documents (and I
  1366. # haven't got the logic to check expiration headers
  1367. # yet).
  1368. self.ftpcache = ftpcache
  1369. # Undocumented feature: you can use a different
  1370. # ftp cache by assigning to the .ftpcache member;
  1371. # in case you want logically independent URL openers
  1372. # XXX This is not threadsafe. Bah.
  1373. def __del__(self):
  1374. self.close()
  1375. def close(self):
  1376. self.cleanup()
  1377. def cleanup(self):
  1378. # This code sometimes runs when the rest of this module
  1379. # has already been deleted, so it can't use any globals
  1380. # or import anything.
  1381. if self.__tempfiles:
  1382. for file in self.__tempfiles:
  1383. try:
  1384. self.__unlink(file)
  1385. except OSError:
  1386. pass
  1387. del self.__tempfiles[:]
  1388. if self.tempcache:
  1389. self.tempcache.clear()
  1390. def addheader(self, *args):
  1391. """Add a header to be used by the HTTP interface only
  1392. e.g. u.addheader('Accept', 'sound/basic')"""
  1393. self.addheaders.append(args)
  1394. # External interface
  1395. def open(self, fullurl, data=None):
  1396. """Use URLopener().open(file) instead of open(file, 'r')."""
  1397. fullurl = unwrap(to_bytes(fullurl))
  1398. fullurl = quote(fullurl, safe="%/:=&?~#+!$,;'@()*[]|")
  1399. if self.tempcache and fullurl in self.tempcache:
  1400. filename, headers = self.tempcache[fullurl]
  1401. fp = open(filename, 'rb')
  1402. return addinfourl(fp, headers, fullurl)
  1403. urltype, url = splittype(fullurl)
  1404. if not urltype:
  1405. urltype = 'file'
  1406. if urltype in self.proxies:
  1407. proxy = self.proxies[urltype]
  1408. urltype, proxyhost = splittype(proxy)
  1409. host, selector = splithost(proxyhost)
  1410. url = (host, fullurl) # Signal special case to open_*()
  1411. else:
  1412. proxy = None
  1413. name = 'open_' + urltype
  1414. self.type = urltype
  1415. name = name.replace('-', '_')
  1416. if not hasattr(self, name):
  1417. if proxy:
  1418. return self.open_unknown_proxy(proxy, fullurl, data)
  1419. else:
  1420. return self.open_unknown(fullurl, data)
  1421. try:
  1422. if data is None:
  1423. return getattr(self, name)(url)
  1424. else:
  1425. return getattr(self, name)(url, data)
  1426. except HTTPError:
  1427. raise
  1428. except socket.error as msg:
  1429. raise_with_traceback(IOError('socket error', msg))
  1430. def open_unknown(self, fullurl, data=None):
  1431. """Overridable interface to open unknown URL type."""
  1432. type, url = splittype(fullurl)
  1433. raise IOError('url error', 'unknown url type', type)
  1434. def open_unknown_proxy(self, proxy, fullurl, data=None):
  1435. """Overridable interface to open unknown URL type."""
  1436. type, url = splittype(fullurl)
  1437. raise IOError('url error', 'invalid proxy for %s' % type, proxy)
  1438. # External interface
  1439. def retrieve(self, url, filename=None, reporthook=None, data=None):
  1440. """retrieve(url) returns (filename, headers) for a local object
  1441. or (tempfilename, headers) for a remote object."""
  1442. url = unwrap(to_bytes(url))
  1443. if self.tempcache and url in self.tempcache:
  1444. return self.tempcache[url]
  1445. type, url1 = splittype(url)
  1446. if filename is None and (not type or type == 'file'):
  1447. try:
  1448. fp = self.open_local_file(url1)
  1449. hdrs = fp.info()
  1450. fp.close()
  1451. return url2pathname(splithost(url1)[1]), hdrs
  1452. except IOError as msg:
  1453. pass
  1454. fp = self.open(url, data)
  1455. try:
  1456. headers = fp.info()
  1457. if filename:
  1458. tfp = open(filename, 'wb')
  1459. else:
  1460. import tempfile
  1461. garbage, path = splittype(url)
  1462. garbage, path = splithost(path or "")
  1463. path, garbage = splitquery(path or "")
  1464. path, garbage = splitattr(path or "")
  1465. suffix = os.path.splitext(path)[1]
  1466. (fd, filename) = tempfile.mkstemp(suffix)
  1467. self.__tempfiles.append(filename)
  1468. tfp = os.fdopen(fd, 'wb')
  1469. try:
  1470. result = filename, headers
  1471. if self.tempcache is not None:
  1472. self.tempcache[url] = result
  1473. bs = 1024*8
  1474. size = -1
  1475. read = 0
  1476. blocknum = 0
  1477. if "content-length" in headers:
  1478. size = int(headers["Content-Length"])
  1479. if reporthook:
  1480. reporthook(blocknum, bs, size)
  1481. while 1:
  1482. block = fp.read(bs)
  1483. if not block:
  1484. break
  1485. read += len(block)
  1486. tfp.write(block)
  1487. blocknum += 1
  1488. if reporthook:
  1489. reporthook(blocknum, bs, size)
  1490. finally:
  1491. tfp.close()
  1492. finally:
  1493. fp.close()
  1494. # raise exception if actual size does not match content-length header
  1495. if size >= 0 and read < size:
  1496. raise ContentTooShortError(
  1497. "retrieval incomplete: got only %i out of %i bytes"
  1498. % (read, size), result)
  1499. return result
  1500. # Each method named open_<type> knows how to open that type of URL
  1501. def _open_generic_http(self, connection_factory, url, data):
  1502. """Make an HTTP connection using connection_class.
  1503. This is an internal method that should be called from
  1504. open_http() or open_https().
  1505. Arguments:
  1506. - connection_factory should take a host name and return an
  1507. HTTPConnection instance.
  1508. - url is the url to retrieval or a host, relative-path pair.
  1509. - data is payload for a POST request or None.
  1510. """
  1511. user_passwd = None
  1512. proxy_passwd= None
  1513. if isinstance(url, str):
  1514. host, selector = splithost(url)
  1515. if host:
  1516. user_passwd, host = splituser(host)
  1517. host = unquote(host)
  1518. realhost = host
  1519. else:
  1520. host, selector = url
  1521. # check whether the proxy contains authorization information
  1522. proxy_passwd, host = splituser(host)
  1523. # now we proceed with the url we want to obtain
  1524. urltype, rest = splittype(selector)
  1525. url = rest
  1526. user_passwd = None
  1527. if urltype.lower() != 'http':
  1528. realhost = None
  1529. else:
  1530. realhost, rest = splithost(rest)
  1531. if realhost:
  1532. user_passwd, realhost = splituser(realhost)
  1533. if user_passwd:
  1534. selector = "%s://%s%s" % (urltype, realhost, rest)
  1535. if proxy_bypass(realhost):
  1536. host = realhost
  1537. if not host: raise IOError('http error', 'no host given')
  1538. if proxy_passwd:
  1539. proxy_passwd = unquote(proxy_passwd)
  1540. proxy_auth = base64.b64encode(proxy_passwd.encode()).decode('ascii')
  1541. else:
  1542. proxy_auth = None
  1543. if user_passwd:
  1544. user_passwd = unquote(user_passwd)
  1545. auth = base64.b64encode(user_passwd.encode()).decode('ascii')
  1546. else:
  1547. auth = None
  1548. http_conn = connection_factory(host)
  1549. headers = {}
  1550. if proxy_auth:
  1551. headers["Proxy-Authorization"] = "Basic %s" % proxy_auth
  1552. if auth:
  1553. headers["Authorization"] = "Basic %s" % auth
  1554. if realhost:
  1555. headers["Host"] = realhost
  1556. # Add Connection:close as we don't support persistent connections yet.
  1557. # This helps in closing the socket and avoiding ResourceWarning
  1558. headers["Connection"] = "close"
  1559. for header, value in self.addheaders:
  1560. headers[header] = value
  1561. if data is not None:
  1562. headers["Content-Type"] = "application/x-www-form-urlencoded"
  1563. http_conn.request("POST", selector, data, headers)
  1564. else:
  1565. http_conn.request("GET", selector, headers=headers)
  1566. try:
  1567. response = http_conn.getresponse()
  1568. except http_client.BadStatusLine:
  1569. # something went wrong with the HTTP status line
  1570. raise URLError("http protocol error: bad status line")
  1571. # According to RFC 2616, "2xx" code indicates that the client's
  1572. # request was successfully received, understood, and accepted.
  1573. if 200 <= response.status < 300:
  1574. return addinfourl(response, response.msg, "http:" + url,
  1575. response.status)
  1576. else:
  1577. return self.http_error(
  1578. url, response.fp,
  1579. response.status, response.reason, response.msg, data)
  1580. def open_http(self, url, data=None):
  1581. """Use HTTP protocol."""
  1582. return self._open_generic_http(http_client.HTTPConnection, url, data)
  1583. def http_error(self, url, fp, errcode, errmsg, headers, data=None):
  1584. """Handle http errors.
  1585. Derived class can override this, or provide specific handlers
  1586. named http_error_DDD where DDD is the 3-digit error code."""
  1587. # First check if there's a specific handler for this error
  1588. name = 'http_error_%d' % errcode
  1589. if hasattr(self, name):
  1590. method = getattr(self, name)
  1591. if data is None:
  1592. result = method(url, fp, errcode, errmsg, headers)
  1593. else:
  1594. result = method(url, fp, errcode, errmsg, headers, data)
  1595. if result: return result
  1596. return self.http_error_default(url, fp, errcode, errmsg, headers)
  1597. def http_error_default(self, url, fp, errcode, errmsg, headers):
  1598. """Default error handler: close the connection and raise IOError."""
  1599. fp.close()
  1600. raise HTTPError(url, errcode, errmsg, headers, None)
  1601. if _have_ssl:
  1602. def _https_connection(self, host):
  1603. return http_client.HTTPSConnection(host,
  1604. key_file=self.key_file,
  1605. cert_file=self.cert_file)
  1606. def open_https(self, url, data=None):
  1607. """Use HTTPS protocol."""
  1608. return self._open_generic_http(self._https_connection, url, data)
  1609. def open_file(self, url):
  1610. """Use local file or FTP depending on form of URL."""
  1611. if not isinstance(url, str):
  1612. raise URLError('file error: proxy support for file protocol currently not implemented')
  1613. if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
  1614. raise ValueError("file:// scheme is supported only on localhost")
  1615. else:
  1616. return self.open_local_file(url)
  1617. def open_local_file(self, url):
  1618. """Use local file."""
  1619. import future.backports.email.utils as email_utils
  1620. import mimetypes
  1621. host, file = splithost(url)
  1622. localname = url2pathname(file)
  1623. try:
  1624. stats = os.stat(localname)
  1625. except OSError as e:
  1626. raise URLError(e.strerror, e.filename)
  1627. size = stats.st_size
  1628. modified = email_utils.formatdate(stats.st_mtime, usegmt=True)
  1629. mtype = mimetypes.guess_type(url)[0]
  1630. headers = email.message_from_string(
  1631. 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
  1632. (mtype or 'text/plain', size, modified))
  1633. if not host:
  1634. urlfile = file
  1635. if file[:1] == '/':
  1636. urlfile = 'file://' + file
  1637. return addinfourl(open(localname, 'rb'), headers, urlfile)
  1638. host, port = splitport(host)
  1639. if (not port
  1640. and socket.gethostbyname(host) in ((localhost(),) + thishost())):
  1641. urlfile = file
  1642. if file[:1] == '/':
  1643. urlfile = 'file://' + file
  1644. elif file[:2] == './':
  1645. raise ValueError("local file url may start with / or file:. Unknown url of type: %s" % url)
  1646. return addinfourl(open(localname, 'rb'), headers, urlfile)
  1647. raise URLError('local file error: not on local host')
  1648. def open_ftp(self, url):
  1649. """Use FTP protocol."""
  1650. if not isinstance(url, str):
  1651. raise URLError('ftp error: proxy support for ftp protocol currently not implemented')
  1652. import mimetypes
  1653. host, path = splithost(url)
  1654. if not host: raise URLError('ftp error: no host given')
  1655. host, port = splitport(host)
  1656. user, host = splituser(host)
  1657. if user: user, passwd = splitpasswd(user)
  1658. else: passwd = None
  1659. host = unquote(host)
  1660. user = unquote(user or '')
  1661. passwd = unquote(passwd or '')
  1662. host = socket.gethostbyname(host)
  1663. if not port:
  1664. import ftplib
  1665. port = ftplib.FTP_PORT
  1666. else:
  1667. port = int(port)
  1668. path, attrs = splitattr(path)
  1669. path = unquote(path)
  1670. dirs = path.split('/')
  1671. dirs, file = dirs[:-1], dirs[-1]
  1672. if dirs and not dirs[0]: dirs = dirs[1:]
  1673. if dirs and not dirs[0]: dirs[0] = '/'
  1674. key = user, host, port, '/'.join(dirs)
  1675. # XXX thread unsafe!
  1676. if len(self.ftpcache) > MAXFTPCACHE:
  1677. # Prune the cache, rather arbitrarily
  1678. for k in self.ftpcache.keys():
  1679. if k != key:
  1680. v = self.ftpcache[k]
  1681. del self.ftpcache[k]
  1682. v.close()
  1683. try:
  1684. if key not in self.ftpcache:
  1685. self.ftpcache[key] = \
  1686. ftpwrapper(user, passwd, host, port, dirs)
  1687. if not file: type = 'D'
  1688. else: type = 'I'
  1689. for attr in attrs:
  1690. attr, value = splitvalue(attr)
  1691. if attr.lower() == 'type' and \
  1692. value in ('a', 'A', 'i', 'I', 'd', 'D'):
  1693. type = value.upper()
  1694. (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
  1695. mtype = mimetypes.guess_type("ftp:" + url)[0]
  1696. headers = ""
  1697. if mtype:
  1698. headers += "Content-Type: %s\n" % mtype
  1699. if retrlen is not None and retrlen >= 0:
  1700. headers += "Content-Length: %d\n" % retrlen
  1701. headers = email.message_from_string(headers)
  1702. return addinfourl(fp, headers, "ftp:" + url)
  1703. except ftperrors() as exp:
  1704. raise_with_traceback(URLError('ftp error %r' % exp))
  1705. def open_data(self, url, data=None):
  1706. """Use "data" URL."""
  1707. if not isinstance(url, str):
  1708. raise URLError('data error: proxy support for data protocol currently not implemented')
  1709. # ignore POSTed data
  1710. #
  1711. # syntax of data URLs:
  1712. # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
  1713. # mediatype := [ type "/" subtype ] *( ";" parameter )
  1714. # data := *urlchar
  1715. # parameter := attribute "=" value
  1716. try:
  1717. [type, data] = url.split(',', 1)
  1718. except ValueError:
  1719. raise IOError('data error', 'bad data URL')
  1720. if not type:
  1721. type = 'text/plain;charset=US-ASCII'
  1722. semi = type.rfind(';')
  1723. if semi >= 0 and '=' not in type[semi:]:
  1724. encoding = type[semi+1:]
  1725. type = type[:semi]
  1726. else:
  1727. encoding = ''
  1728. msg = []
  1729. msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT',
  1730. time.gmtime(time.time())))
  1731. msg.append('Content-type: %s' % type)
  1732. if encoding == 'base64':
  1733. # XXX is this encoding/decoding ok?
  1734. data = base64.decodebytes(data.encode('ascii')).decode('latin-1')
  1735. else:
  1736. data = unquote(data)
  1737. msg.append('Content-Length: %d' % len(data))
  1738. msg.append('')
  1739. msg.append(data)
  1740. msg = '\n'.join(msg)
  1741. headers = email.message_from_string(msg)
  1742. f = io.StringIO(msg)
  1743. #f.fileno = None # needed for addinfourl
  1744. return addinfourl(f, headers, url)
  1745. class FancyURLopener(URLopener):
  1746. """Derived class with handlers for errors we can handle (perhaps)."""
  1747. def __init__(self, *args, **kwargs):
  1748. URLopener.__init__(self, *args, **kwargs)
  1749. self.auth_cache = {}
  1750. self.tries = 0
  1751. self.maxtries = 10
  1752. def http_error_default(self, url, fp, errcode, errmsg, headers):
  1753. """Default error handling -- don't raise an exception."""
  1754. return addinfourl(fp, headers, "http:" + url, errcode)
  1755. def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
  1756. """Error 302 -- relocated (temporarily)."""
  1757. self.tries += 1
  1758. if self.maxtries and self.tries >= self.maxtries:
  1759. if hasattr(self, "http_error_500"):
  1760. meth = self.http_error_500
  1761. else:
  1762. meth = self.http_error_default
  1763. self.tries = 0
  1764. return meth(url, fp, 500,
  1765. "Internal Server Error: Redirect Recursion", headers)
  1766. result = self.redirect_internal(url, fp, errcode, errmsg, headers,
  1767. data)
  1768. self.tries = 0
  1769. return result
  1770. def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
  1771. if 'location' in headers:
  1772. newurl = headers['location']
  1773. elif 'uri' in headers:
  1774. newurl = headers['uri']
  1775. else:
  1776. return
  1777. fp.close()
  1778. # In case the server sent a relative URL, join with original:
  1779. newurl = urljoin(self.type + ":" + url, newurl)
  1780. urlparts = urlparse(newurl)
  1781. # For security reasons, we don't allow redirection to anything other
  1782. # than http, https and ftp.
  1783. # We are using newer HTTPError with older redirect_internal method
  1784. # This older method will get deprecated in 3.3
  1785. if urlparts.scheme not in ('http', 'https', 'ftp', ''):
  1786. raise HTTPError(newurl, errcode,
  1787. errmsg +
  1788. " Redirection to url '%s' is not allowed." % newurl,
  1789. headers, fp)
  1790. return self.open(newurl)
  1791. def http_error_301(self, url, fp, errcode, errmsg, headers, data=None):
  1792. """Error 301 -- also relocated (permanently)."""
  1793. return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  1794. def http_error_303(self, url, fp, errcode, errmsg, headers, data=None):
  1795. """Error 303 -- also relocated (essentially identical to 302)."""
  1796. return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  1797. def http_error_307(self, url, fp, errcode, errmsg, headers, data=None):
  1798. """Error 307 -- relocated, but turn POST into error."""
  1799. if data is None:
  1800. return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  1801. else:
  1802. return self.http_error_default(url, fp, errcode, errmsg, headers)
  1803. def http_error_401(self, url, fp, errcode, errmsg, headers, data=None,
  1804. retry=False):
  1805. """Error 401 -- authentication required.
  1806. This function supports Basic authentication only."""
  1807. if 'www-authenticate' not in headers:
  1808. URLopener.http_error_default(self, url, fp,
  1809. errcode, errmsg, headers)
  1810. stuff = headers['www-authenticate']
  1811. match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
  1812. if not match:
  1813. URLopener.http_error_default(self, url, fp,
  1814. errcode, errmsg, headers)
  1815. scheme, realm = match.groups()
  1816. if scheme.lower() != 'basic':
  1817. URLopener.http_error_default(self, url, fp,
  1818. errcode, errmsg, headers)
  1819. if not retry:
  1820. URLopener.http_error_default(self, url, fp, errcode, errmsg,
  1821. headers)
  1822. name = 'retry_' + self.type + '_basic_auth'
  1823. if data is None:
  1824. return getattr(self,name)(url, realm)
  1825. else:
  1826. return getattr(self,name)(url, realm, data)
  1827. def http_error_407(self, url, fp, errcode, errmsg, headers, data=None,
  1828. retry=False):
  1829. """Error 407 -- proxy authentication required.
  1830. This function supports Basic authentication only."""
  1831. if 'proxy-authenticate' not in headers:
  1832. URLopener.http_error_default(self, url, fp,
  1833. errcode, errmsg, headers)
  1834. stuff = headers['proxy-authenticate']
  1835. match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
  1836. if not match:
  1837. URLopener.http_error_default(self, url, fp,
  1838. errcode, errmsg, headers)
  1839. scheme, realm = match.groups()
  1840. if scheme.lower() != 'basic':
  1841. URLopener.http_error_default(self, url, fp,
  1842. errcode, errmsg, headers)
  1843. if not retry:
  1844. URLopener.http_error_default(self, url, fp, errcode, errmsg,
  1845. headers)
  1846. name = 'retry_proxy_' + self.type + '_basic_auth'
  1847. if data is None:
  1848. return getattr(self,name)(url, realm)
  1849. else:
  1850. return getattr(self,name)(url, realm, data)
  1851. def retry_proxy_http_basic_auth(self, url, realm, data=None):
  1852. host, selector = splithost(url)
  1853. newurl = 'http://' + host + selector
  1854. proxy = self.proxies['http']
  1855. urltype, proxyhost = splittype(proxy)
  1856. proxyhost, proxyselector = splithost(proxyhost)
  1857. i = proxyhost.find('@') + 1
  1858. proxyhost = proxyhost[i:]
  1859. user, passwd = self.get_user_passwd(proxyhost, realm, i)
  1860. if not (user or passwd): return None
  1861. proxyhost = "%s:%s@%s" % (quote(user, safe=''),
  1862. quote(passwd, safe=''), proxyhost)
  1863. self.proxies['http'] = 'http://' + proxyhost + proxyselector
  1864. if data is None:
  1865. return self.open(newurl)
  1866. else:
  1867. return self.open(newurl, data)
  1868. def retry_proxy_https_basic_auth(self, url, realm, data=None):
  1869. host, selector = splithost(url)
  1870. newurl = 'https://' + host + selector
  1871. proxy = self.proxies['https']
  1872. urltype, proxyhost = splittype(proxy)
  1873. proxyhost, proxyselector = splithost(proxyhost)
  1874. i = proxyhost.find('@') + 1
  1875. proxyhost = proxyhost[i:]
  1876. user, passwd = self.get_user_passwd(proxyhost, realm, i)
  1877. if not (user or passwd): return None
  1878. proxyhost = "%s:%s@%s" % (quote(user, safe=''),
  1879. quote(passwd, safe=''), proxyhost)
  1880. self.proxies['https'] = 'https://' + proxyhost + proxyselector
  1881. if data is None:
  1882. return self.open(newurl)
  1883. else:
  1884. return self.open(newurl, data)
  1885. def retry_http_basic_auth(self, url, realm, data=None):
  1886. host, selector = splithost(url)
  1887. i = host.find('@') + 1
  1888. host = host[i:]
  1889. user, passwd = self.get_user_passwd(host, realm, i)
  1890. if not (user or passwd): return None
  1891. host = "%s:%s@%s" % (quote(user, safe=''),
  1892. quote(passwd, safe=''), host)
  1893. newurl = 'http://' + host + selector
  1894. if data is None:
  1895. return self.open(newurl)
  1896. else:
  1897. return self.open(newurl, data)
  1898. def retry_https_basic_auth(self, url, realm, data=None):
  1899. host, selector = splithost(url)
  1900. i = host.find('@') + 1
  1901. host = host[i:]
  1902. user, passwd = self.get_user_passwd(host, realm, i)
  1903. if not (user or passwd): return None
  1904. host = "%s:%s@%s" % (quote(user, safe=''),
  1905. quote(passwd, safe=''), host)
  1906. newurl = 'https://' + host + selector
  1907. if data is None:
  1908. return self.open(newurl)
  1909. else:
  1910. return self.open(newurl, data)
  1911. def get_user_passwd(self, host, realm, clear_cache=0):
  1912. key = realm + '@' + host.lower()
  1913. if key in self.auth_cache:
  1914. if clear_cache:
  1915. del self.auth_cache[key]
  1916. else:
  1917. return self.auth_cache[key]
  1918. user, passwd = self.prompt_user_passwd(host, realm)
  1919. if user or passwd: self.auth_cache[key] = (user, passwd)
  1920. return user, passwd
  1921. def prompt_user_passwd(self, host, realm):
  1922. """Override this in a GUI environment!"""
  1923. import getpass
  1924. try:
  1925. user = input("Enter username for %s at %s: " % (realm, host))
  1926. passwd = getpass.getpass("Enter password for %s in %s at %s: " %
  1927. (user, realm, host))
  1928. return user, passwd
  1929. except KeyboardInterrupt:
  1930. print()
  1931. return None, None
  1932. # Utility functions
  1933. _localhost = None
  1934. def localhost():
  1935. """Return the IP address of the magic hostname 'localhost'."""
  1936. global _localhost
  1937. if _localhost is None:
  1938. _localhost = socket.gethostbyname('localhost')
  1939. return _localhost
  1940. _thishost = None
  1941. def thishost():
  1942. """Return the IP addresses of the current host."""
  1943. global _thishost
  1944. if _thishost is None:
  1945. try:
  1946. _thishost = tuple(socket.gethostbyname_ex(socket.gethostname())[2])
  1947. except socket.gaierror:
  1948. _thishost = tuple(socket.gethostbyname_ex('localhost')[2])
  1949. return _thishost
  1950. _ftperrors = None
  1951. def ftperrors():
  1952. """Return the set of errors raised by the FTP class."""
  1953. global _ftperrors
  1954. if _ftperrors is None:
  1955. import ftplib
  1956. _ftperrors = ftplib.all_errors
  1957. return _ftperrors
  1958. _noheaders = None
  1959. def noheaders():
  1960. """Return an empty email Message object."""
  1961. global _noheaders
  1962. if _noheaders is None:
  1963. _noheaders = email.message_from_string("")
  1964. return _noheaders
  1965. # Utility classes
  1966. class ftpwrapper(object):
  1967. """Class used by open_ftp() for cache of open FTP connections."""
  1968. def __init__(self, user, passwd, host, port, dirs, timeout=None,
  1969. persistent=True):
  1970. self.user = user
  1971. self.passwd = passwd
  1972. self.host = host
  1973. self.port = port
  1974. self.dirs = dirs
  1975. self.timeout = timeout
  1976. self.refcount = 0
  1977. self.keepalive = persistent
  1978. self.init()
  1979. def init(self):
  1980. import ftplib
  1981. self.busy = 0
  1982. self.ftp = ftplib.FTP()
  1983. self.ftp.connect(self.host, self.port, self.timeout)
  1984. self.ftp.login(self.user, self.passwd)
  1985. _target = '/'.join(self.dirs)
  1986. self.ftp.cwd(_target)
  1987. def retrfile(self, file, type):
  1988. import ftplib
  1989. self.endtransfer()
  1990. if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
  1991. else: cmd = 'TYPE ' + type; isdir = 0
  1992. try:
  1993. self.ftp.voidcmd(cmd)
  1994. except ftplib.all_errors:
  1995. self.init()
  1996. self.ftp.voidcmd(cmd)
  1997. conn = None
  1998. if file and not isdir:
  1999. # Try to retrieve as a file
  2000. try:
  2001. cmd = 'RETR ' + file
  2002. conn, retrlen = self.ftp.ntransfercmd(cmd)
  2003. except ftplib.error_perm as reason:
  2004. if str(reason)[:3] != '550':
  2005. raise_with_traceback(URLError('ftp error: %r' % reason))
  2006. if not conn:
  2007. # Set transfer mode to ASCII!
  2008. self.ftp.voidcmd('TYPE A')
  2009. # Try a directory listing. Verify that directory exists.
  2010. if file:
  2011. pwd = self.ftp.pwd()
  2012. try:
  2013. try:
  2014. self.ftp.cwd(file)
  2015. except ftplib.error_perm as reason:
  2016. ### Was:
  2017. # raise URLError('ftp error: %r' % reason) from reason
  2018. exc = URLError('ftp error: %r' % reason)
  2019. exc.__cause__ = reason
  2020. raise exc
  2021. finally:
  2022. self.ftp.cwd(pwd)
  2023. cmd = 'LIST ' + file
  2024. else:
  2025. cmd = 'LIST'
  2026. conn, retrlen = self.ftp.ntransfercmd(cmd)
  2027. self.busy = 1
  2028. ftpobj = addclosehook(conn.makefile('rb'), self.file_close)
  2029. self.refcount += 1
  2030. conn.close()
  2031. # Pass back both a suitably decorated object and a retrieval length
  2032. return (ftpobj, retrlen)
  2033. def endtransfer(self):
  2034. self.busy = 0
  2035. def close(self):
  2036. self.keepalive = False
  2037. if self.refcount <= 0:
  2038. self.real_close()
  2039. def file_close(self):
  2040. self.endtransfer()
  2041. self.refcount -= 1
  2042. if self.refcount <= 0 and not self.keepalive:
  2043. self.real_close()
  2044. def real_close(self):
  2045. self.endtransfer()
  2046. try:
  2047. self.ftp.close()
  2048. except ftperrors():
  2049. pass
  2050. # Proxy handling
  2051. def getproxies_environment():
  2052. """Return a dictionary of scheme -> proxy server URL mappings.
  2053. Scan the environment for variables named <scheme>_proxy;
  2054. this seems to be the standard convention. If you need a
  2055. different way, you can pass a proxies dictionary to the
  2056. [Fancy]URLopener constructor.
  2057. """
  2058. proxies = {}
  2059. for name, value in os.environ.items():
  2060. name = name.lower()
  2061. if value and name[-6:] == '_proxy':
  2062. proxies[name[:-6]] = value
  2063. return proxies
  2064. def proxy_bypass_environment(host):
  2065. """Test if proxies should not be used for a particular host.
  2066. Checks the environment for a variable named no_proxy, which should
  2067. be a list of DNS suffixes separated by commas, or '*' for all hosts.
  2068. """
  2069. no_proxy = os.environ.get('no_proxy', '') or os.environ.get('NO_PROXY', '')
  2070. # '*' is special case for always bypass
  2071. if no_proxy == '*':
  2072. return 1
  2073. # strip port off host
  2074. hostonly, port = splitport(host)
  2075. # check if the host ends with any of the DNS suffixes
  2076. no_proxy_list = [proxy.strip() for proxy in no_proxy.split(',')]
  2077. for name in no_proxy_list:
  2078. if name and (hostonly.endswith(name) or host.endswith(name)):
  2079. return 1
  2080. # otherwise, don't bypass
  2081. return 0
  2082. # This code tests an OSX specific data structure but is testable on all
  2083. # platforms
  2084. def _proxy_bypass_macosx_sysconf(host, proxy_settings):
  2085. """
  2086. Return True iff this host shouldn't be accessed using a proxy
  2087. This function uses the MacOSX framework SystemConfiguration
  2088. to fetch the proxy information.
  2089. proxy_settings come from _scproxy._get_proxy_settings or get mocked ie:
  2090. { 'exclude_simple': bool,
  2091. 'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.1', '10.0/16']
  2092. }
  2093. """
  2094. from fnmatch import fnmatch
  2095. hostonly, port = splitport(host)
  2096. def ip2num(ipAddr):
  2097. parts = ipAddr.split('.')
  2098. parts = list(map(int, parts))
  2099. if len(parts) != 4:
  2100. parts = (parts + [0, 0, 0, 0])[:4]
  2101. return (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]
  2102. # Check for simple host names:
  2103. if '.' not in host:
  2104. if proxy_settings['exclude_simple']:
  2105. return True
  2106. hostIP = None
  2107. for value in proxy_settings.get('exceptions', ()):
  2108. # Items in the list are strings like these: *.local, 169.254/16
  2109. if not value: continue
  2110. m = re.match(r"(\d+(?:\.\d+)*)(/\d+)?", value)
  2111. if m is not None:
  2112. if hostIP is None:
  2113. try:
  2114. hostIP = socket.gethostbyname(hostonly)
  2115. hostIP = ip2num(hostIP)
  2116. except socket.error:
  2117. continue
  2118. base = ip2num(m.group(1))
  2119. mask = m.group(2)
  2120. if mask is None:
  2121. mask = 8 * (m.group(1).count('.') + 1)
  2122. else:
  2123. mask = int(mask[1:])
  2124. mask = 32 - mask
  2125. if (hostIP >> mask) == (base >> mask):
  2126. return True
  2127. elif fnmatch(host, value):
  2128. return True
  2129. return False
  2130. if sys.platform == 'darwin':
  2131. from _scproxy import _get_proxy_settings, _get_proxies
  2132. def proxy_bypass_macosx_sysconf(host):
  2133. proxy_settings = _get_proxy_settings()
  2134. return _proxy_bypass_macosx_sysconf(host, proxy_settings)
  2135. def getproxies_macosx_sysconf():
  2136. """Return a dictionary of scheme -> proxy server URL mappings.
  2137. This function uses the MacOSX framework SystemConfiguration
  2138. to fetch the proxy information.
  2139. """
  2140. return _get_proxies()
  2141. def proxy_bypass(host):
  2142. if getproxies_environment():
  2143. return proxy_bypass_environment(host)
  2144. else:
  2145. return proxy_bypass_macosx_sysconf(host)
  2146. def getproxies():
  2147. return getproxies_environment() or getproxies_macosx_sysconf()
  2148. elif os.name == 'nt':
  2149. def getproxies_registry():
  2150. """Return a dictionary of scheme -> proxy server URL mappings.
  2151. Win32 uses the registry to store proxies.
  2152. """
  2153. proxies = {}
  2154. try:
  2155. import winreg
  2156. except ImportError:
  2157. # Std module, so should be around - but you never know!
  2158. return proxies
  2159. try:
  2160. internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
  2161. r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
  2162. proxyEnable = winreg.QueryValueEx(internetSettings,
  2163. 'ProxyEnable')[0]
  2164. if proxyEnable:
  2165. # Returned as Unicode but problems if not converted to ASCII
  2166. proxyServer = str(winreg.QueryValueEx(internetSettings,
  2167. 'ProxyServer')[0])
  2168. if '=' in proxyServer:
  2169. # Per-protocol settings
  2170. for p in proxyServer.split(';'):
  2171. protocol, address = p.split('=', 1)
  2172. # See if address has a type:// prefix
  2173. if not re.match('^([^/:]+)://', address):
  2174. address = '%s://%s' % (protocol, address)
  2175. proxies[protocol] = address
  2176. else:
  2177. # Use one setting for all protocols
  2178. if proxyServer[:5] == 'http:':
  2179. proxies['http'] = proxyServer
  2180. else:
  2181. proxies['http'] = 'http://%s' % proxyServer
  2182. proxies['https'] = 'https://%s' % proxyServer
  2183. proxies['ftp'] = 'ftp://%s' % proxyServer
  2184. internetSettings.Close()
  2185. except (WindowsError, ValueError, TypeError):
  2186. # Either registry key not found etc, or the value in an
  2187. # unexpected format.
  2188. # proxies already set up to be empty so nothing to do
  2189. pass
  2190. return proxies
  2191. def getproxies():
  2192. """Return a dictionary of scheme -> proxy server URL mappings.
  2193. Returns settings gathered from the environment, if specified,
  2194. or the registry.
  2195. """
  2196. return getproxies_environment() or getproxies_registry()
  2197. def proxy_bypass_registry(host):
  2198. try:
  2199. import winreg
  2200. except ImportError:
  2201. # Std modules, so should be around - but you never know!
  2202. return 0
  2203. try:
  2204. internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
  2205. r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
  2206. proxyEnable = winreg.QueryValueEx(internetSettings,
  2207. 'ProxyEnable')[0]
  2208. proxyOverride = str(winreg.QueryValueEx(internetSettings,
  2209. 'ProxyOverride')[0])
  2210. # ^^^^ Returned as Unicode but problems if not converted to ASCII
  2211. except WindowsError:
  2212. return 0
  2213. if not proxyEnable or not proxyOverride:
  2214. return 0
  2215. # try to make a host list from name and IP address.
  2216. rawHost, port = splitport(host)
  2217. host = [rawHost]
  2218. try:
  2219. addr = socket.gethostbyname(rawHost)
  2220. if addr != rawHost:
  2221. host.append(addr)
  2222. except socket.error:
  2223. pass
  2224. try:
  2225. fqdn = socket.getfqdn(rawHost)
  2226. if fqdn != rawHost:
  2227. host.append(fqdn)
  2228. except socket.error:
  2229. pass
  2230. # make a check value list from the registry entry: replace the
  2231. # '<local>' string by the localhost entry and the corresponding
  2232. # canonical entry.
  2233. proxyOverride = proxyOverride.split(';')
  2234. # now check if we match one of the registry values.
  2235. for test in proxyOverride:
  2236. if test == '<local>':
  2237. if '.' not in rawHost:
  2238. return 1
  2239. test = test.replace(".", r"\.") # mask dots
  2240. test = test.replace("*", r".*") # change glob sequence
  2241. test = test.replace("?", r".") # change glob char
  2242. for val in host:
  2243. if re.match(test, val, re.I):
  2244. return 1
  2245. return 0
  2246. def proxy_bypass(host):
  2247. """Return a dictionary of scheme -> proxy server URL mappings.
  2248. Returns settings gathered from the environment, if specified,
  2249. or the registry.
  2250. """
  2251. if getproxies_environment():
  2252. return proxy_bypass_environment(host)
  2253. else:
  2254. return proxy_bypass_registry(host)
  2255. else:
  2256. # By default use environment variables
  2257. getproxies = getproxies_environment
  2258. proxy_bypass = proxy_bypass_environment