request.py 99 KB

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