request.py 100 KB

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