request.py 99 KB

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