request.py 99 KB

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