request.py 98 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741
  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. common = posixpath.commonprefix((base[1], test[1]))
  745. if len(common) == len(base[1]):
  746. return True
  747. return False
  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('(?:.*,)*[ \t]*([^ \t]+)[ \t]+'
  785. 'realm=(["\']?)([^"\']*)\\2', re.I)
  786. # XXX could pre-emptively send auth info already accepted (RFC 2617,
  787. # end of section 2, and section 1.2 immediately after "credentials"
  788. # production).
  789. def __init__(self, password_mgr=None):
  790. if password_mgr is None:
  791. password_mgr = HTTPPasswordMgr()
  792. self.passwd = password_mgr
  793. self.add_password = self.passwd.add_password
  794. def http_error_auth_reqed(self, authreq, host, req, headers):
  795. # host may be an authority (without userinfo) or a URL with an
  796. # authority
  797. # XXX could be multiple headers
  798. authreq = headers.get(authreq, None)
  799. if authreq:
  800. scheme = authreq.split()[0]
  801. if scheme.lower() != 'basic':
  802. raise ValueError("AbstractBasicAuthHandler does not"
  803. " support the following scheme: '%s'" %
  804. scheme)
  805. else:
  806. mo = AbstractBasicAuthHandler.rx.search(authreq)
  807. if mo:
  808. scheme, quote, realm = mo.groups()
  809. if quote not in ['"',"'"]:
  810. warnings.warn("Basic Auth Realm was unquoted",
  811. UserWarning, 2)
  812. if scheme.lower() == 'basic':
  813. return self.retry_http_basic_auth(host, req, realm)
  814. def retry_http_basic_auth(self, host, req, realm):
  815. user, pw = self.passwd.find_user_password(realm, host)
  816. if pw is not None:
  817. raw = "%s:%s" % (user, pw)
  818. auth = "Basic " + base64.b64encode(raw.encode()).decode("ascii")
  819. if req.get_header(self.auth_header, None) == auth:
  820. return None
  821. req.add_unredirected_header(self.auth_header, auth)
  822. return self.parent.open(req, timeout=req.timeout)
  823. else:
  824. return None
  825. def http_request(self, req):
  826. if (not hasattr(self.passwd, 'is_authenticated') or
  827. not self.passwd.is_authenticated(req.full_url)):
  828. return req
  829. if not req.has_header('Authorization'):
  830. user, passwd = self.passwd.find_user_password(None, req.full_url)
  831. credentials = '{0}:{1}'.format(user, passwd).encode()
  832. auth_str = base64.standard_b64encode(credentials).decode()
  833. req.add_unredirected_header('Authorization',
  834. 'Basic {}'.format(auth_str.strip()))
  835. return req
  836. def http_response(self, req, response):
  837. if hasattr(self.passwd, 'is_authenticated'):
  838. if 200 <= response.code < 300:
  839. self.passwd.update_authenticated(req.full_url, True)
  840. else:
  841. self.passwd.update_authenticated(req.full_url, False)
  842. return response
  843. https_request = http_request
  844. https_response = http_response
  845. class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
  846. auth_header = 'Authorization'
  847. def http_error_401(self, req, fp, code, msg, headers):
  848. url = req.full_url
  849. response = self.http_error_auth_reqed('www-authenticate',
  850. url, req, headers)
  851. return response
  852. class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
  853. auth_header = 'Proxy-authorization'
  854. def http_error_407(self, req, fp, code, msg, headers):
  855. # http_error_auth_reqed requires that there is no userinfo component in
  856. # authority. Assume there isn't one, since urllib.request does not (and
  857. # should not, RFC 3986 s. 3.2.1) support requests for URLs containing
  858. # userinfo.
  859. authority = req.host
  860. response = self.http_error_auth_reqed('proxy-authenticate',
  861. authority, req, headers)
  862. return response
  863. # Return n random bytes.
  864. _randombytes = os.urandom
  865. class AbstractDigestAuthHandler:
  866. # Digest authentication is specified in RFC 2617.
  867. # XXX The client does not inspect the Authentication-Info header
  868. # in a successful response.
  869. # XXX It should be possible to test this implementation against
  870. # a mock server that just generates a static set of challenges.
  871. # XXX qop="auth-int" supports is shaky
  872. def __init__(self, passwd=None):
  873. if passwd is None:
  874. passwd = HTTPPasswordMgr()
  875. self.passwd = passwd
  876. self.add_password = self.passwd.add_password
  877. self.retried = 0
  878. self.nonce_count = 0
  879. self.last_nonce = None
  880. def reset_retry_count(self):
  881. self.retried = 0
  882. def http_error_auth_reqed(self, auth_header, host, req, headers):
  883. authreq = headers.get(auth_header, None)
  884. if self.retried > 5:
  885. # Don't fail endlessly - if we failed once, we'll probably
  886. # fail a second time. Hm. Unless the Password Manager is
  887. # prompting for the information. Crap. This isn't great
  888. # but it's better than the current 'repeat until recursion
  889. # depth exceeded' approach <wink>
  890. raise HTTPError(req.full_url, 401, "digest auth failed",
  891. headers, None)
  892. else:
  893. self.retried += 1
  894. if authreq:
  895. scheme = authreq.split()[0]
  896. if scheme.lower() == 'digest':
  897. return self.retry_http_digest_auth(req, authreq)
  898. elif scheme.lower() != 'basic':
  899. raise ValueError("AbstractDigestAuthHandler does not support"
  900. " the following scheme: '%s'" % scheme)
  901. def retry_http_digest_auth(self, req, auth):
  902. token, challenge = auth.split(' ', 1)
  903. chal = parse_keqv_list(filter(None, parse_http_list(challenge)))
  904. auth = self.get_authorization(req, chal)
  905. if auth:
  906. auth_val = 'Digest %s' % auth
  907. if req.headers.get(self.auth_header, None) == auth_val:
  908. return None
  909. req.add_unredirected_header(self.auth_header, auth_val)
  910. resp = self.parent.open(req, timeout=req.timeout)
  911. return resp
  912. def get_cnonce(self, nonce):
  913. # The cnonce-value is an opaque
  914. # quoted string value provided by the client and used by both client
  915. # and server to avoid chosen plaintext attacks, to provide mutual
  916. # authentication, and to provide some message integrity protection.
  917. # This isn't a fabulous effort, but it's probably Good Enough.
  918. s = "%s:%s:%s:" % (self.nonce_count, nonce, time.ctime())
  919. b = s.encode("ascii") + _randombytes(8)
  920. dig = hashlib.sha1(b).hexdigest()
  921. return dig[:16]
  922. def get_authorization(self, req, chal):
  923. try:
  924. realm = chal['realm']
  925. nonce = chal['nonce']
  926. qop = chal.get('qop')
  927. algorithm = chal.get('algorithm', 'MD5')
  928. # mod_digest doesn't send an opaque, even though it isn't
  929. # supposed to be optional
  930. opaque = chal.get('opaque', None)
  931. except KeyError:
  932. return None
  933. H, KD = self.get_algorithm_impls(algorithm)
  934. if H is None:
  935. return None
  936. user, pw = self.passwd.find_user_password(realm, req.full_url)
  937. if user is None:
  938. return None
  939. # XXX not implemented yet
  940. if req.data is not None:
  941. entdig = self.get_entity_digest(req.data, chal)
  942. else:
  943. entdig = None
  944. A1 = "%s:%s:%s" % (user, realm, pw)
  945. A2 = "%s:%s" % (req.get_method(),
  946. # XXX selector: what about proxies and full urls
  947. req.selector)
  948. # NOTE: As per RFC 2617, when server sends "auth,auth-int", the client could use either `auth`
  949. # or `auth-int` to the response back. we use `auth` to send the response back.
  950. if qop is None:
  951. respdig = KD(H(A1), "%s:%s" % (nonce, H(A2)))
  952. elif 'auth' in qop.split(','):
  953. if nonce == self.last_nonce:
  954. self.nonce_count += 1
  955. else:
  956. self.nonce_count = 1
  957. self.last_nonce = nonce
  958. ncvalue = '%08x' % self.nonce_count
  959. cnonce = self.get_cnonce(nonce)
  960. noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, 'auth', H(A2))
  961. respdig = KD(H(A1), noncebit)
  962. else:
  963. # XXX handle auth-int.
  964. raise URLError("qop '%s' is not supported." % qop)
  965. # XXX should the partial digests be encoded too?
  966. base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \
  967. 'response="%s"' % (user, realm, nonce, req.selector,
  968. respdig)
  969. if opaque:
  970. base += ', opaque="%s"' % opaque
  971. if entdig:
  972. base += ', digest="%s"' % entdig
  973. base += ', algorithm="%s"' % algorithm
  974. if qop:
  975. base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)
  976. return base
  977. def get_algorithm_impls(self, algorithm):
  978. # lambdas assume digest modules are imported at the top level
  979. if algorithm == 'MD5':
  980. H = lambda x: hashlib.md5(x.encode("ascii")).hexdigest()
  981. elif algorithm == 'SHA':
  982. H = lambda x: hashlib.sha1(x.encode("ascii")).hexdigest()
  983. # XXX MD5-sess
  984. else:
  985. raise ValueError("Unsupported digest authentication "
  986. "algorithm %r" % algorithm)
  987. KD = lambda s, d: H("%s:%s" % (s, d))
  988. return H, KD
  989. def get_entity_digest(self, data, chal):
  990. # XXX not implemented yet
  991. return None
  992. class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
  993. """An authentication protocol defined by RFC 2069
  994. Digest authentication improves on basic authentication because it
  995. does not transmit passwords in the clear.
  996. """
  997. auth_header = 'Authorization'
  998. handler_order = 490 # before Basic auth
  999. def http_error_401(self, req, fp, code, msg, headers):
  1000. host = urlparse(req.full_url)[1]
  1001. retry = self.http_error_auth_reqed('www-authenticate',
  1002. host, req, headers)
  1003. self.reset_retry_count()
  1004. return retry
  1005. class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
  1006. auth_header = 'Proxy-Authorization'
  1007. handler_order = 490 # before Basic auth
  1008. def http_error_407(self, req, fp, code, msg, headers):
  1009. host = req.host
  1010. retry = self.http_error_auth_reqed('proxy-authenticate',
  1011. host, req, headers)
  1012. self.reset_retry_count()
  1013. return retry
  1014. class AbstractHTTPHandler(BaseHandler):
  1015. def __init__(self, debuglevel=0):
  1016. self._debuglevel = debuglevel
  1017. def set_http_debuglevel(self, level):
  1018. self._debuglevel = level
  1019. def _get_content_length(self, request):
  1020. return http.client.HTTPConnection._get_content_length(
  1021. request.data,
  1022. request.get_method())
  1023. def do_request_(self, request):
  1024. host = request.host
  1025. if not host:
  1026. raise URLError('no host given')
  1027. if request.data is not None: # POST
  1028. data = request.data
  1029. if isinstance(data, str):
  1030. msg = "POST data should be bytes, an iterable of bytes, " \
  1031. "or a file object. It cannot be of type str."
  1032. raise TypeError(msg)
  1033. if not request.has_header('Content-type'):
  1034. request.add_unredirected_header(
  1035. 'Content-type',
  1036. 'application/x-www-form-urlencoded')
  1037. if (not request.has_header('Content-length')
  1038. and not request.has_header('Transfer-encoding')):
  1039. content_length = self._get_content_length(request)
  1040. if content_length is not None:
  1041. request.add_unredirected_header(
  1042. 'Content-length', str(content_length))
  1043. else:
  1044. request.add_unredirected_header(
  1045. 'Transfer-encoding', 'chunked')
  1046. sel_host = host
  1047. if request.has_proxy():
  1048. scheme, sel = splittype(request.selector)
  1049. sel_host, sel_path = splithost(sel)
  1050. if not request.has_header('Host'):
  1051. request.add_unredirected_header('Host', sel_host)
  1052. for name, value in self.parent.addheaders:
  1053. name = name.capitalize()
  1054. if not request.has_header(name):
  1055. request.add_unredirected_header(name, value)
  1056. return request
  1057. def do_open(self, http_class, req, **http_conn_args):
  1058. """Return an HTTPResponse object for the request, using http_class.
  1059. http_class must implement the HTTPConnection API from http.client.
  1060. """
  1061. host = req.host
  1062. if not host:
  1063. raise URLError('no host given')
  1064. # will parse host:port
  1065. h = http_class(host, timeout=req.timeout, **http_conn_args)
  1066. h.set_debuglevel(self._debuglevel)
  1067. headers = dict(req.unredirected_hdrs)
  1068. headers.update({k: v for k, v in req.headers.items()
  1069. if k not in headers})
  1070. # TODO(jhylton): Should this be redesigned to handle
  1071. # persistent connections?
  1072. # We want to make an HTTP/1.1 request, but the addinfourl
  1073. # class isn't prepared to deal with a persistent connection.
  1074. # It will try to read all remaining data from the socket,
  1075. # which will block while the server waits for the next request.
  1076. # So make sure the connection gets closed after the (only)
  1077. # request.
  1078. headers["Connection"] = "close"
  1079. headers = {name.title(): val for name, val in headers.items()}
  1080. if req._tunnel_host:
  1081. tunnel_headers = {}
  1082. proxy_auth_hdr = "Proxy-Authorization"
  1083. if proxy_auth_hdr in headers:
  1084. tunnel_headers[proxy_auth_hdr] = headers[proxy_auth_hdr]
  1085. # Proxy-Authorization should not be sent to origin
  1086. # server.
  1087. del headers[proxy_auth_hdr]
  1088. h.set_tunnel(req._tunnel_host, headers=tunnel_headers)
  1089. try:
  1090. try:
  1091. h.request(req.get_method(), req.selector, req.data, headers,
  1092. encode_chunked=req.has_header('Transfer-encoding'))
  1093. except OSError as err: # timeout error
  1094. raise URLError(err)
  1095. r = h.getresponse()
  1096. except:
  1097. h.close()
  1098. raise
  1099. # If the server does not send us a 'Connection: close' header,
  1100. # HTTPConnection assumes the socket should be left open. Manually
  1101. # mark the socket to be closed when this response object goes away.
  1102. if h.sock:
  1103. h.sock.close()
  1104. h.sock = None
  1105. r.url = req.get_full_url()
  1106. # This line replaces the .msg attribute of the HTTPResponse
  1107. # with .headers, because urllib clients expect the response to
  1108. # have the reason in .msg. It would be good to mark this
  1109. # attribute is deprecated and get then to use info() or
  1110. # .headers.
  1111. r.msg = r.reason
  1112. return r
  1113. class HTTPHandler(AbstractHTTPHandler):
  1114. def http_open(self, req):
  1115. return self.do_open(http.client.HTTPConnection, req)
  1116. http_request = AbstractHTTPHandler.do_request_
  1117. if hasattr(http.client, 'HTTPSConnection'):
  1118. class HTTPSHandler(AbstractHTTPHandler):
  1119. def __init__(self, debuglevel=0, context=None, check_hostname=None):
  1120. AbstractHTTPHandler.__init__(self, debuglevel)
  1121. self._context = context
  1122. self._check_hostname = check_hostname
  1123. def https_open(self, req):
  1124. return self.do_open(http.client.HTTPSConnection, req,
  1125. context=self._context, check_hostname=self._check_hostname)
  1126. https_request = AbstractHTTPHandler.do_request_
  1127. __all__.append('HTTPSHandler')
  1128. class HTTPCookieProcessor(BaseHandler):
  1129. def __init__(self, cookiejar=None):
  1130. import http.cookiejar
  1131. if cookiejar is None:
  1132. cookiejar = http.cookiejar.CookieJar()
  1133. self.cookiejar = cookiejar
  1134. def http_request(self, request):
  1135. self.cookiejar.add_cookie_header(request)
  1136. return request
  1137. def http_response(self, request, response):
  1138. self.cookiejar.extract_cookies(response, request)
  1139. return response
  1140. https_request = http_request
  1141. https_response = http_response
  1142. class UnknownHandler(BaseHandler):
  1143. def unknown_open(self, req):
  1144. type = req.type
  1145. raise URLError('unknown url type: %s' % type)
  1146. def parse_keqv_list(l):
  1147. """Parse list of key=value strings where keys are not duplicated."""
  1148. parsed = {}
  1149. for elt in l:
  1150. k, v = elt.split('=', 1)
  1151. if v[0] == '"' and v[-1] == '"':
  1152. v = v[1:-1]
  1153. parsed[k] = v
  1154. return parsed
  1155. def parse_http_list(s):
  1156. """Parse lists as described by RFC 2068 Section 2.
  1157. In particular, parse comma-separated lists where the elements of
  1158. the list may include quoted-strings. A quoted-string could
  1159. contain a comma. A non-quoted string could have quotes in the
  1160. middle. Neither commas nor quotes count if they are escaped.
  1161. Only double-quotes count, not single-quotes.
  1162. """
  1163. res = []
  1164. part = ''
  1165. escape = quote = False
  1166. for cur in s:
  1167. if escape:
  1168. part += cur
  1169. escape = False
  1170. continue
  1171. if quote:
  1172. if cur == '\\':
  1173. escape = True
  1174. continue
  1175. elif cur == '"':
  1176. quote = False
  1177. part += cur
  1178. continue
  1179. if cur == ',':
  1180. res.append(part)
  1181. part = ''
  1182. continue
  1183. if cur == '"':
  1184. quote = True
  1185. part += cur
  1186. # append last part
  1187. if part:
  1188. res.append(part)
  1189. return [part.strip() for part in res]
  1190. class FileHandler(BaseHandler):
  1191. # Use local file or FTP depending on form of URL
  1192. def file_open(self, req):
  1193. url = req.selector
  1194. if url[:2] == '//' and url[2:3] != '/' and (req.host and
  1195. req.host != 'localhost'):
  1196. if not req.host in self.get_names():
  1197. raise URLError("file:// scheme is supported only on localhost")
  1198. else:
  1199. return self.open_local_file(req)
  1200. # names for the localhost
  1201. names = None
  1202. def get_names(self):
  1203. if FileHandler.names is None:
  1204. try:
  1205. FileHandler.names = tuple(
  1206. socket.gethostbyname_ex('localhost')[2] +
  1207. socket.gethostbyname_ex(socket.gethostname())[2])
  1208. except socket.gaierror:
  1209. FileHandler.names = (socket.gethostbyname('localhost'),)
  1210. return FileHandler.names
  1211. # not entirely sure what the rules are here
  1212. def open_local_file(self, req):
  1213. import email.utils
  1214. import mimetypes
  1215. host = req.host
  1216. filename = req.selector
  1217. localfile = url2pathname(filename)
  1218. try:
  1219. stats = os.stat(localfile)
  1220. size = stats.st_size
  1221. modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
  1222. mtype = mimetypes.guess_type(filename)[0]
  1223. headers = email.message_from_string(
  1224. 'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' %
  1225. (mtype or 'text/plain', size, modified))
  1226. if host:
  1227. host, port = splitport(host)
  1228. if not host or \
  1229. (not port and _safe_gethostbyname(host) in self.get_names()):
  1230. if host:
  1231. origurl = 'file://' + host + filename
  1232. else:
  1233. origurl = 'file://' + filename
  1234. return addinfourl(open(localfile, 'rb'), headers, origurl)
  1235. except OSError as exp:
  1236. raise URLError(exp)
  1237. raise URLError('file not on local host')
  1238. def _safe_gethostbyname(host):
  1239. try:
  1240. return socket.gethostbyname(host)
  1241. except socket.gaierror:
  1242. return None
  1243. class FTPHandler(BaseHandler):
  1244. def ftp_open(self, req):
  1245. import ftplib
  1246. import mimetypes
  1247. host = req.host
  1248. if not host:
  1249. raise URLError('ftp error: no host given')
  1250. host, port = splitport(host)
  1251. if port is None:
  1252. port = ftplib.FTP_PORT
  1253. else:
  1254. port = int(port)
  1255. # username/password handling
  1256. user, host = splituser(host)
  1257. if user:
  1258. user, passwd = splitpasswd(user)
  1259. else:
  1260. passwd = None
  1261. host = unquote(host)
  1262. user = user or ''
  1263. passwd = passwd or ''
  1264. try:
  1265. host = socket.gethostbyname(host)
  1266. except OSError as msg:
  1267. raise URLError(msg)
  1268. path, attrs = splitattr(req.selector)
  1269. dirs = path.split('/')
  1270. dirs = list(map(unquote, dirs))
  1271. dirs, file = dirs[:-1], dirs[-1]
  1272. if dirs and not dirs[0]:
  1273. dirs = dirs[1:]
  1274. try:
  1275. fw = self.connect_ftp(user, passwd, host, port, dirs, req.timeout)
  1276. type = file and 'I' or 'D'
  1277. for attr in attrs:
  1278. attr, value = splitvalue(attr)
  1279. if attr.lower() == 'type' and \
  1280. value in ('a', 'A', 'i', 'I', 'd', 'D'):
  1281. type = value.upper()
  1282. fp, retrlen = fw.retrfile(file, type)
  1283. headers = ""
  1284. mtype = mimetypes.guess_type(req.full_url)[0]
  1285. if mtype:
  1286. headers += "Content-type: %s\n" % mtype
  1287. if retrlen is not None and retrlen >= 0:
  1288. headers += "Content-length: %d\n" % retrlen
  1289. headers = email.message_from_string(headers)
  1290. return addinfourl(fp, headers, req.full_url)
  1291. except ftplib.all_errors as exp:
  1292. exc = URLError('ftp error: %r' % exp)
  1293. raise exc.with_traceback(sys.exc_info()[2])
  1294. def connect_ftp(self, user, passwd, host, port, dirs, timeout):
  1295. return ftpwrapper(user, passwd, host, port, dirs, timeout,
  1296. persistent=False)
  1297. class CacheFTPHandler(FTPHandler):
  1298. # XXX would be nice to have pluggable cache strategies
  1299. # XXX this stuff is definitely not thread safe
  1300. def __init__(self):
  1301. self.cache = {}
  1302. self.timeout = {}
  1303. self.soonest = 0
  1304. self.delay = 60
  1305. self.max_conns = 16
  1306. def setTimeout(self, t):
  1307. self.delay = t
  1308. def setMaxConns(self, m):
  1309. self.max_conns = m
  1310. def connect_ftp(self, user, passwd, host, port, dirs, timeout):
  1311. key = user, host, port, '/'.join(dirs), timeout
  1312. if key in self.cache:
  1313. self.timeout[key] = time.time() + self.delay
  1314. else:
  1315. self.cache[key] = ftpwrapper(user, passwd, host, port,
  1316. dirs, timeout)
  1317. self.timeout[key] = time.time() + self.delay
  1318. self.check_cache()
  1319. return self.cache[key]
  1320. def check_cache(self):
  1321. # first check for old ones
  1322. t = time.time()
  1323. if self.soonest <= t:
  1324. for k, v in list(self.timeout.items()):
  1325. if v < t:
  1326. self.cache[k].close()
  1327. del self.cache[k]
  1328. del self.timeout[k]
  1329. self.soonest = min(list(self.timeout.values()))
  1330. # then check the size
  1331. if len(self.cache) == self.max_conns:
  1332. for k, v in list(self.timeout.items()):
  1333. if v == self.soonest:
  1334. del self.cache[k]
  1335. del self.timeout[k]
  1336. break
  1337. self.soonest = min(list(self.timeout.values()))
  1338. def clear_cache(self):
  1339. for conn in self.cache.values():
  1340. conn.close()
  1341. self.cache.clear()
  1342. self.timeout.clear()
  1343. class DataHandler(BaseHandler):
  1344. def data_open(self, req):
  1345. # data URLs as specified in RFC 2397.
  1346. #
  1347. # ignores POSTed data
  1348. #
  1349. # syntax:
  1350. # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
  1351. # mediatype := [ type "/" subtype ] *( ";" parameter )
  1352. # data := *urlchar
  1353. # parameter := attribute "=" value
  1354. url = req.full_url
  1355. scheme, data = url.split(":",1)
  1356. mediatype, data = data.split(",",1)
  1357. # even base64 encoded data URLs might be quoted so unquote in any case:
  1358. data = unquote_to_bytes(data)
  1359. if mediatype.endswith(";base64"):
  1360. data = base64.decodebytes(data)
  1361. mediatype = mediatype[:-7]
  1362. if not mediatype:
  1363. mediatype = "text/plain;charset=US-ASCII"
  1364. headers = email.message_from_string("Content-type: %s\nContent-length: %d\n" %
  1365. (mediatype, len(data)))
  1366. return addinfourl(io.BytesIO(data), headers, url)
  1367. # Code move from the old urllib module
  1368. MAXFTPCACHE = 10 # Trim the ftp cache beyond this size
  1369. # Helper for non-unix systems
  1370. if os.name == 'nt':
  1371. from nturl2path import url2pathname, pathname2url
  1372. else:
  1373. def url2pathname(pathname):
  1374. """OS-specific conversion from a relative URL of the 'file' scheme
  1375. to a file system path; not recommended for general use."""
  1376. return unquote(pathname)
  1377. def pathname2url(pathname):
  1378. """OS-specific conversion from a file system path to a relative URL
  1379. of the 'file' scheme; not recommended for general use."""
  1380. return quote(pathname)
  1381. ftpcache = {}
  1382. class URLopener:
  1383. """Class to open URLs.
  1384. This is a class rather than just a subroutine because we may need
  1385. more than one set of global protocol-specific options.
  1386. Note -- this is a base class for those who don't want the
  1387. automatic handling of errors type 302 (relocated) and 401
  1388. (authorization needed)."""
  1389. __tempfiles = None
  1390. version = "Python-urllib/%s" % __version__
  1391. # Constructor
  1392. def __init__(self, proxies=None, **x509):
  1393. msg = "%(class)s style of invoking requests is deprecated. " \
  1394. "Use newer urlopen functions/methods" % {'class': self.__class__.__name__}
  1395. warnings.warn(msg, DeprecationWarning, stacklevel=3)
  1396. if proxies is None:
  1397. proxies = getproxies()
  1398. assert hasattr(proxies, 'keys'), "proxies must be a mapping"
  1399. self.proxies = proxies
  1400. self.key_file = x509.get('key_file')
  1401. self.cert_file = x509.get('cert_file')
  1402. self.addheaders = [('User-Agent', self.version), ('Accept', '*/*')]
  1403. self.__tempfiles = []
  1404. self.__unlink = os.unlink # See cleanup()
  1405. self.tempcache = None
  1406. # Undocumented feature: if you assign {} to tempcache,
  1407. # it is used to cache files retrieved with
  1408. # self.retrieve(). This is not enabled by default
  1409. # since it does not work for changing documents (and I
  1410. # haven't got the logic to check expiration headers
  1411. # yet).
  1412. self.ftpcache = ftpcache
  1413. # Undocumented feature: you can use a different
  1414. # ftp cache by assigning to the .ftpcache member;
  1415. # in case you want logically independent URL openers
  1416. # XXX This is not threadsafe. Bah.
  1417. def __del__(self):
  1418. self.close()
  1419. def close(self):
  1420. self.cleanup()
  1421. def cleanup(self):
  1422. # This code sometimes runs when the rest of this module
  1423. # has already been deleted, so it can't use any globals
  1424. # or import anything.
  1425. if self.__tempfiles:
  1426. for file in self.__tempfiles:
  1427. try:
  1428. self.__unlink(file)
  1429. except OSError:
  1430. pass
  1431. del self.__tempfiles[:]
  1432. if self.tempcache:
  1433. self.tempcache.clear()
  1434. def addheader(self, *args):
  1435. """Add a header to be used by the HTTP interface only
  1436. e.g. u.addheader('Accept', 'sound/basic')"""
  1437. self.addheaders.append(args)
  1438. # External interface
  1439. def open(self, fullurl, data=None):
  1440. """Use URLopener().open(file) instead of open(file, 'r')."""
  1441. fullurl = unwrap(to_bytes(fullurl))
  1442. fullurl = quote(fullurl, safe="%/:=&?~#+!$,;'@()*[]|")
  1443. if self.tempcache and fullurl in self.tempcache:
  1444. filename, headers = self.tempcache[fullurl]
  1445. fp = open(filename, 'rb')
  1446. return addinfourl(fp, headers, fullurl)
  1447. urltype, url = splittype(fullurl)
  1448. if not urltype:
  1449. urltype = 'file'
  1450. if urltype in self.proxies:
  1451. proxy = self.proxies[urltype]
  1452. urltype, proxyhost = splittype(proxy)
  1453. host, selector = splithost(proxyhost)
  1454. url = (host, fullurl) # Signal special case to open_*()
  1455. else:
  1456. proxy = None
  1457. name = 'open_' + urltype
  1458. self.type = urltype
  1459. name = name.replace('-', '_')
  1460. if not hasattr(self, name) or name == 'open_local_file':
  1461. if proxy:
  1462. return self.open_unknown_proxy(proxy, fullurl, data)
  1463. else:
  1464. return self.open_unknown(fullurl, data)
  1465. try:
  1466. if data is None:
  1467. return getattr(self, name)(url)
  1468. else:
  1469. return getattr(self, name)(url, data)
  1470. except (HTTPError, URLError):
  1471. raise
  1472. except OSError as msg:
  1473. raise OSError('socket error', msg).with_traceback(sys.exc_info()[2])
  1474. def open_unknown(self, fullurl, data=None):
  1475. """Overridable interface to open unknown URL type."""
  1476. type, url = splittype(fullurl)
  1477. raise OSError('url error', 'unknown url type', type)
  1478. def open_unknown_proxy(self, proxy, fullurl, data=None):
  1479. """Overridable interface to open unknown URL type."""
  1480. type, url = splittype(fullurl)
  1481. raise OSError('url error', 'invalid proxy for %s' % type, proxy)
  1482. # External interface
  1483. def retrieve(self, url, filename=None, reporthook=None, data=None):
  1484. """retrieve(url) returns (filename, headers) for a local object
  1485. or (tempfilename, headers) for a remote object."""
  1486. url = unwrap(to_bytes(url))
  1487. if self.tempcache and url in self.tempcache:
  1488. return self.tempcache[url]
  1489. type, url1 = splittype(url)
  1490. if filename is None and (not type or type == 'file'):
  1491. try:
  1492. fp = self.open_local_file(url1)
  1493. hdrs = fp.info()
  1494. fp.close()
  1495. return url2pathname(splithost(url1)[1]), hdrs
  1496. except OSError as msg:
  1497. pass
  1498. fp = self.open(url, data)
  1499. try:
  1500. headers = fp.info()
  1501. if filename:
  1502. tfp = open(filename, 'wb')
  1503. else:
  1504. garbage, path = splittype(url)
  1505. garbage, path = splithost(path or "")
  1506. path, garbage = splitquery(path or "")
  1507. path, garbage = splitattr(path or "")
  1508. suffix = os.path.splitext(path)[1]
  1509. (fd, filename) = tempfile.mkstemp(suffix)
  1510. self.__tempfiles.append(filename)
  1511. tfp = os.fdopen(fd, 'wb')
  1512. try:
  1513. result = filename, headers
  1514. if self.tempcache is not None:
  1515. self.tempcache[url] = result
  1516. bs = 1024*8
  1517. size = -1
  1518. read = 0
  1519. blocknum = 0
  1520. if "content-length" in headers:
  1521. size = int(headers["Content-Length"])
  1522. if reporthook:
  1523. reporthook(blocknum, bs, size)
  1524. while 1:
  1525. block = fp.read(bs)
  1526. if not block:
  1527. break
  1528. read += len(block)
  1529. tfp.write(block)
  1530. blocknum += 1
  1531. if reporthook:
  1532. reporthook(blocknum, bs, size)
  1533. finally:
  1534. tfp.close()
  1535. finally:
  1536. fp.close()
  1537. # raise exception if actual size does not match content-length header
  1538. if size >= 0 and read < size:
  1539. raise ContentTooShortError(
  1540. "retrieval incomplete: got only %i out of %i bytes"
  1541. % (read, size), result)
  1542. return result
  1543. # Each method named open_<type> knows how to open that type of URL
  1544. def _open_generic_http(self, connection_factory, url, data):
  1545. """Make an HTTP connection using connection_class.
  1546. This is an internal method that should be called from
  1547. open_http() or open_https().
  1548. Arguments:
  1549. - connection_factory should take a host name and return an
  1550. HTTPConnection instance.
  1551. - url is the url to retrieval or a host, relative-path pair.
  1552. - data is payload for a POST request or None.
  1553. """
  1554. user_passwd = None
  1555. proxy_passwd= None
  1556. if isinstance(url, str):
  1557. host, selector = splithost(url)
  1558. if host:
  1559. user_passwd, host = splituser(host)
  1560. host = unquote(host)
  1561. realhost = host
  1562. else:
  1563. host, selector = url
  1564. # check whether the proxy contains authorization information
  1565. proxy_passwd, host = splituser(host)
  1566. # now we proceed with the url we want to obtain
  1567. urltype, rest = splittype(selector)
  1568. url = rest
  1569. user_passwd = None
  1570. if urltype.lower() != 'http':
  1571. realhost = None
  1572. else:
  1573. realhost, rest = splithost(rest)
  1574. if realhost:
  1575. user_passwd, realhost = splituser(realhost)
  1576. if user_passwd:
  1577. selector = "%s://%s%s" % (urltype, realhost, rest)
  1578. if proxy_bypass(realhost):
  1579. host = realhost
  1580. if not host: raise OSError('http error', 'no host given')
  1581. if proxy_passwd:
  1582. proxy_passwd = unquote(proxy_passwd)
  1583. proxy_auth = base64.b64encode(proxy_passwd.encode()).decode('ascii')
  1584. else:
  1585. proxy_auth = None
  1586. if user_passwd:
  1587. user_passwd = unquote(user_passwd)
  1588. auth = base64.b64encode(user_passwd.encode()).decode('ascii')
  1589. else:
  1590. auth = None
  1591. http_conn = connection_factory(host)
  1592. headers = {}
  1593. if proxy_auth:
  1594. headers["Proxy-Authorization"] = "Basic %s" % proxy_auth
  1595. if auth:
  1596. headers["Authorization"] = "Basic %s" % auth
  1597. if realhost:
  1598. headers["Host"] = realhost
  1599. # Add Connection:close as we don't support persistent connections yet.
  1600. # This helps in closing the socket and avoiding ResourceWarning
  1601. headers["Connection"] = "close"
  1602. for header, value in self.addheaders:
  1603. headers[header] = value
  1604. if data is not None:
  1605. headers["Content-Type"] = "application/x-www-form-urlencoded"
  1606. http_conn.request("POST", selector, data, headers)
  1607. else:
  1608. http_conn.request("GET", selector, headers=headers)
  1609. try:
  1610. response = http_conn.getresponse()
  1611. except http.client.BadStatusLine:
  1612. # something went wrong with the HTTP status line
  1613. raise URLError("http protocol error: bad status line")
  1614. # According to RFC 2616, "2xx" code indicates that the client's
  1615. # request was successfully received, understood, and accepted.
  1616. if 200 <= response.status < 300:
  1617. return addinfourl(response, response.msg, "http:" + url,
  1618. response.status)
  1619. else:
  1620. return self.http_error(
  1621. url, response.fp,
  1622. response.status, response.reason, response.msg, data)
  1623. def open_http(self, url, data=None):
  1624. """Use HTTP protocol."""
  1625. return self._open_generic_http(http.client.HTTPConnection, url, data)
  1626. def http_error(self, url, fp, errcode, errmsg, headers, data=None):
  1627. """Handle http errors.
  1628. Derived class can override this, or provide specific handlers
  1629. named http_error_DDD where DDD is the 3-digit error code."""
  1630. # First check if there's a specific handler for this error
  1631. name = 'http_error_%d' % errcode
  1632. if hasattr(self, name):
  1633. method = getattr(self, name)
  1634. if data is None:
  1635. result = method(url, fp, errcode, errmsg, headers)
  1636. else:
  1637. result = method(url, fp, errcode, errmsg, headers, data)
  1638. if result: return result
  1639. return self.http_error_default(url, fp, errcode, errmsg, headers)
  1640. def http_error_default(self, url, fp, errcode, errmsg, headers):
  1641. """Default error handler: close the connection and raise OSError."""
  1642. fp.close()
  1643. raise HTTPError(url, errcode, errmsg, headers, None)
  1644. if _have_ssl:
  1645. def _https_connection(self, host):
  1646. return http.client.HTTPSConnection(host,
  1647. key_file=self.key_file,
  1648. cert_file=self.cert_file)
  1649. def open_https(self, url, data=None):
  1650. """Use HTTPS protocol."""
  1651. return self._open_generic_http(self._https_connection, url, data)
  1652. def open_file(self, url):
  1653. """Use local file or FTP depending on form of URL."""
  1654. if not isinstance(url, str):
  1655. raise URLError('file error: proxy support for file protocol currently not implemented')
  1656. if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
  1657. raise ValueError("file:// scheme is supported only on localhost")
  1658. else:
  1659. return self.open_local_file(url)
  1660. def open_local_file(self, url):
  1661. """Use local file."""
  1662. import email.utils
  1663. import mimetypes
  1664. host, file = splithost(url)
  1665. localname = url2pathname(file)
  1666. try:
  1667. stats = os.stat(localname)
  1668. except OSError as e:
  1669. raise URLError(e.strerror, e.filename)
  1670. size = stats.st_size
  1671. modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
  1672. mtype = mimetypes.guess_type(url)[0]
  1673. headers = email.message_from_string(
  1674. 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
  1675. (mtype or 'text/plain', size, modified))
  1676. if not host:
  1677. urlfile = file
  1678. if file[:1] == '/':
  1679. urlfile = 'file://' + file
  1680. return addinfourl(open(localname, 'rb'), headers, urlfile)
  1681. host, port = splitport(host)
  1682. if (not port
  1683. and socket.gethostbyname(host) in ((localhost(),) + thishost())):
  1684. urlfile = file
  1685. if file[:1] == '/':
  1686. urlfile = 'file://' + file
  1687. elif file[:2] == './':
  1688. raise ValueError("local file url may start with / or file:. Unknown url of type: %s" % url)
  1689. return addinfourl(open(localname, 'rb'), headers, urlfile)
  1690. raise URLError('local file error: not on local host')
  1691. def open_ftp(self, url):
  1692. """Use FTP protocol."""
  1693. if not isinstance(url, str):
  1694. raise URLError('ftp error: proxy support for ftp protocol currently not implemented')
  1695. import mimetypes
  1696. host, path = splithost(url)
  1697. if not host: raise URLError('ftp error: no host given')
  1698. host, port = splitport(host)
  1699. user, host = splituser(host)
  1700. if user: user, passwd = splitpasswd(user)
  1701. else: passwd = None
  1702. host = unquote(host)
  1703. user = unquote(user or '')
  1704. passwd = unquote(passwd or '')
  1705. host = socket.gethostbyname(host)
  1706. if not port:
  1707. import ftplib
  1708. port = ftplib.FTP_PORT
  1709. else:
  1710. port = int(port)
  1711. path, attrs = splitattr(path)
  1712. path = unquote(path)
  1713. dirs = path.split('/')
  1714. dirs, file = dirs[:-1], dirs[-1]
  1715. if dirs and not dirs[0]: dirs = dirs[1:]
  1716. if dirs and not dirs[0]: dirs[0] = '/'
  1717. key = user, host, port, '/'.join(dirs)
  1718. # XXX thread unsafe!
  1719. if len(self.ftpcache) > MAXFTPCACHE:
  1720. # Prune the cache, rather arbitrarily
  1721. for k in list(self.ftpcache):
  1722. if k != key:
  1723. v = self.ftpcache[k]
  1724. del self.ftpcache[k]
  1725. v.close()
  1726. try:
  1727. if key not in self.ftpcache:
  1728. self.ftpcache[key] = \
  1729. ftpwrapper(user, passwd, host, port, dirs)
  1730. if not file: type = 'D'
  1731. else: type = 'I'
  1732. for attr in attrs:
  1733. attr, value = splitvalue(attr)
  1734. if attr.lower() == 'type' and \
  1735. value in ('a', 'A', 'i', 'I', 'd', 'D'):
  1736. type = value.upper()
  1737. (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
  1738. mtype = mimetypes.guess_type("ftp:" + url)[0]
  1739. headers = ""
  1740. if mtype:
  1741. headers += "Content-Type: %s\n" % mtype
  1742. if retrlen is not None and retrlen >= 0:
  1743. headers += "Content-Length: %d\n" % retrlen
  1744. headers = email.message_from_string(headers)
  1745. return addinfourl(fp, headers, "ftp:" + url)
  1746. except ftperrors() as exp:
  1747. raise URLError('ftp error %r' % exp).with_traceback(sys.exc_info()[2])
  1748. def open_data(self, url, data=None):
  1749. """Use "data" URL."""
  1750. if not isinstance(url, str):
  1751. raise URLError('data error: proxy support for data protocol currently not implemented')
  1752. # ignore POSTed data
  1753. #
  1754. # syntax of data URLs:
  1755. # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
  1756. # mediatype := [ type "/" subtype ] *( ";" parameter )
  1757. # data := *urlchar
  1758. # parameter := attribute "=" value
  1759. try:
  1760. [type, data] = url.split(',', 1)
  1761. except ValueError:
  1762. raise OSError('data error', 'bad data URL')
  1763. if not type:
  1764. type = 'text/plain;charset=US-ASCII'
  1765. semi = type.rfind(';')
  1766. if semi >= 0 and '=' not in type[semi:]:
  1767. encoding = type[semi+1:]
  1768. type = type[:semi]
  1769. else:
  1770. encoding = ''
  1771. msg = []
  1772. msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT',
  1773. time.gmtime(time.time())))
  1774. msg.append('Content-type: %s' % type)
  1775. if encoding == 'base64':
  1776. # XXX is this encoding/decoding ok?
  1777. data = base64.decodebytes(data.encode('ascii')).decode('latin-1')
  1778. else:
  1779. data = unquote(data)
  1780. msg.append('Content-Length: %d' % len(data))
  1781. msg.append('')
  1782. msg.append(data)
  1783. msg = '\n'.join(msg)
  1784. headers = email.message_from_string(msg)
  1785. f = io.StringIO(msg)
  1786. #f.fileno = None # needed for addinfourl
  1787. return addinfourl(f, headers, url)
  1788. class FancyURLopener(URLopener):
  1789. """Derived class with handlers for errors we can handle (perhaps)."""
  1790. def __init__(self, *args, **kwargs):
  1791. URLopener.__init__(self, *args, **kwargs)
  1792. self.auth_cache = {}
  1793. self.tries = 0
  1794. self.maxtries = 10
  1795. def http_error_default(self, url, fp, errcode, errmsg, headers):
  1796. """Default error handling -- don't raise an exception."""
  1797. return addinfourl(fp, headers, "http:" + url, errcode)
  1798. def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
  1799. """Error 302 -- relocated (temporarily)."""
  1800. self.tries += 1
  1801. try:
  1802. if self.maxtries and self.tries >= self.maxtries:
  1803. if hasattr(self, "http_error_500"):
  1804. meth = self.http_error_500
  1805. else:
  1806. meth = self.http_error_default
  1807. return meth(url, fp, 500,
  1808. "Internal Server Error: Redirect Recursion",
  1809. headers)
  1810. result = self.redirect_internal(url, fp, errcode, errmsg,
  1811. headers, data)
  1812. return result
  1813. finally:
  1814. self.tries = 0
  1815. def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
  1816. if 'location' in headers:
  1817. newurl = headers['location']
  1818. elif 'uri' in headers:
  1819. newurl = headers['uri']
  1820. else:
  1821. return
  1822. fp.close()
  1823. # In case the server sent a relative URL, join with original:
  1824. newurl = urljoin(self.type + ":" + url, newurl)
  1825. urlparts = urlparse(newurl)
  1826. # For security reasons, we don't allow redirection to anything other
  1827. # than http, https and ftp.
  1828. # We are using newer HTTPError with older redirect_internal method
  1829. # This older method will get deprecated in 3.3
  1830. if urlparts.scheme not in ('http', 'https', 'ftp', ''):
  1831. raise HTTPError(newurl, errcode,
  1832. errmsg +
  1833. " Redirection to url '%s' is not allowed." % newurl,
  1834. headers, fp)
  1835. return self.open(newurl)
  1836. def http_error_301(self, url, fp, errcode, errmsg, headers, data=None):
  1837. """Error 301 -- also relocated (permanently)."""
  1838. return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  1839. def http_error_303(self, url, fp, errcode, errmsg, headers, data=None):
  1840. """Error 303 -- also relocated (essentially identical to 302)."""
  1841. return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  1842. def http_error_307(self, url, fp, errcode, errmsg, headers, data=None):
  1843. """Error 307 -- relocated, but turn POST into error."""
  1844. if data is None:
  1845. return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  1846. else:
  1847. return self.http_error_default(url, fp, errcode, errmsg, headers)
  1848. def http_error_401(self, url, fp, errcode, errmsg, headers, data=None,
  1849. retry=False):
  1850. """Error 401 -- authentication required.
  1851. This function supports Basic authentication only."""
  1852. if 'www-authenticate' not in headers:
  1853. URLopener.http_error_default(self, url, fp,
  1854. errcode, errmsg, headers)
  1855. stuff = headers['www-authenticate']
  1856. match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
  1857. if not match:
  1858. URLopener.http_error_default(self, url, fp,
  1859. errcode, errmsg, headers)
  1860. scheme, realm = match.groups()
  1861. if scheme.lower() != 'basic':
  1862. URLopener.http_error_default(self, url, fp,
  1863. errcode, errmsg, headers)
  1864. if not retry:
  1865. URLopener.http_error_default(self, url, fp, errcode, errmsg,
  1866. headers)
  1867. name = 'retry_' + self.type + '_basic_auth'
  1868. if data is None:
  1869. return getattr(self,name)(url, realm)
  1870. else:
  1871. return getattr(self,name)(url, realm, data)
  1872. def http_error_407(self, url, fp, errcode, errmsg, headers, data=None,
  1873. retry=False):
  1874. """Error 407 -- proxy authentication required.
  1875. This function supports Basic authentication only."""
  1876. if 'proxy-authenticate' not in headers:
  1877. URLopener.http_error_default(self, url, fp,
  1878. errcode, errmsg, headers)
  1879. stuff = headers['proxy-authenticate']
  1880. match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
  1881. if not match:
  1882. URLopener.http_error_default(self, url, fp,
  1883. errcode, errmsg, headers)
  1884. scheme, realm = match.groups()
  1885. if scheme.lower() != 'basic':
  1886. URLopener.http_error_default(self, url, fp,
  1887. errcode, errmsg, headers)
  1888. if not retry:
  1889. URLopener.http_error_default(self, url, fp, errcode, errmsg,
  1890. headers)
  1891. name = 'retry_proxy_' + self.type + '_basic_auth'
  1892. if data is None:
  1893. return getattr(self,name)(url, realm)
  1894. else:
  1895. return getattr(self,name)(url, realm, data)
  1896. def retry_proxy_http_basic_auth(self, url, realm, data=None):
  1897. host, selector = splithost(url)
  1898. newurl = 'http://' + host + selector
  1899. proxy = self.proxies['http']
  1900. urltype, proxyhost = splittype(proxy)
  1901. proxyhost, proxyselector = splithost(proxyhost)
  1902. i = proxyhost.find('@') + 1
  1903. proxyhost = proxyhost[i:]
  1904. user, passwd = self.get_user_passwd(proxyhost, realm, i)
  1905. if not (user or passwd): return None
  1906. proxyhost = "%s:%s@%s" % (quote(user, safe=''),
  1907. quote(passwd, safe=''), proxyhost)
  1908. self.proxies['http'] = 'http://' + proxyhost + proxyselector
  1909. if data is None:
  1910. return self.open(newurl)
  1911. else:
  1912. return self.open(newurl, data)
  1913. def retry_proxy_https_basic_auth(self, url, realm, data=None):
  1914. host, selector = splithost(url)
  1915. newurl = 'https://' + host + selector
  1916. proxy = self.proxies['https']
  1917. urltype, proxyhost = splittype(proxy)
  1918. proxyhost, proxyselector = splithost(proxyhost)
  1919. i = proxyhost.find('@') + 1
  1920. proxyhost = proxyhost[i:]
  1921. user, passwd = self.get_user_passwd(proxyhost, realm, i)
  1922. if not (user or passwd): return None
  1923. proxyhost = "%s:%s@%s" % (quote(user, safe=''),
  1924. quote(passwd, safe=''), proxyhost)
  1925. self.proxies['https'] = 'https://' + proxyhost + proxyselector
  1926. if data is None:
  1927. return self.open(newurl)
  1928. else:
  1929. return self.open(newurl, data)
  1930. def retry_http_basic_auth(self, url, realm, data=None):
  1931. host, selector = splithost(url)
  1932. i = host.find('@') + 1
  1933. host = host[i:]
  1934. user, passwd = self.get_user_passwd(host, realm, i)
  1935. if not (user or passwd): return None
  1936. host = "%s:%s@%s" % (quote(user, safe=''),
  1937. quote(passwd, safe=''), host)
  1938. newurl = 'http://' + host + selector
  1939. if data is None:
  1940. return self.open(newurl)
  1941. else:
  1942. return self.open(newurl, data)
  1943. def retry_https_basic_auth(self, url, realm, data=None):
  1944. host, selector = splithost(url)
  1945. i = host.find('@') + 1
  1946. host = host[i:]
  1947. user, passwd = self.get_user_passwd(host, realm, i)
  1948. if not (user or passwd): return None
  1949. host = "%s:%s@%s" % (quote(user, safe=''),
  1950. quote(passwd, safe=''), host)
  1951. newurl = 'https://' + host + selector
  1952. if data is None:
  1953. return self.open(newurl)
  1954. else:
  1955. return self.open(newurl, data)
  1956. def get_user_passwd(self, host, realm, clear_cache=0):
  1957. key = realm + '@' + host.lower()
  1958. if key in self.auth_cache:
  1959. if clear_cache:
  1960. del self.auth_cache[key]
  1961. else:
  1962. return self.auth_cache[key]
  1963. user, passwd = self.prompt_user_passwd(host, realm)
  1964. if user or passwd: self.auth_cache[key] = (user, passwd)
  1965. return user, passwd
  1966. def prompt_user_passwd(self, host, realm):
  1967. """Override this in a GUI environment!"""
  1968. import getpass
  1969. try:
  1970. user = input("Enter username for %s at %s: " % (realm, host))
  1971. passwd = getpass.getpass("Enter password for %s in %s at %s: " %
  1972. (user, realm, host))
  1973. return user, passwd
  1974. except KeyboardInterrupt:
  1975. print()
  1976. return None, None
  1977. # Utility functions
  1978. _localhost = None
  1979. def localhost():
  1980. """Return the IP address of the magic hostname 'localhost'."""
  1981. global _localhost
  1982. if _localhost is None:
  1983. _localhost = socket.gethostbyname('localhost')
  1984. return _localhost
  1985. _thishost = None
  1986. def thishost():
  1987. """Return the IP addresses of the current host."""
  1988. global _thishost
  1989. if _thishost is None:
  1990. try:
  1991. _thishost = tuple(socket.gethostbyname_ex(socket.gethostname())[2])
  1992. except socket.gaierror:
  1993. _thishost = tuple(socket.gethostbyname_ex('localhost')[2])
  1994. return _thishost
  1995. _ftperrors = None
  1996. def ftperrors():
  1997. """Return the set of errors raised by the FTP class."""
  1998. global _ftperrors
  1999. if _ftperrors is None:
  2000. import ftplib
  2001. _ftperrors = ftplib.all_errors
  2002. return _ftperrors
  2003. _noheaders = None
  2004. def noheaders():
  2005. """Return an empty email Message object."""
  2006. global _noheaders
  2007. if _noheaders is None:
  2008. _noheaders = email.message_from_string("")
  2009. return _noheaders
  2010. # Utility classes
  2011. class ftpwrapper:
  2012. """Class used by open_ftp() for cache of open FTP connections."""
  2013. def __init__(self, user, passwd, host, port, dirs, timeout=None,
  2014. persistent=True):
  2015. self.user = user
  2016. self.passwd = passwd
  2017. self.host = host
  2018. self.port = port
  2019. self.dirs = dirs
  2020. self.timeout = timeout
  2021. self.refcount = 0
  2022. self.keepalive = persistent
  2023. try:
  2024. self.init()
  2025. except:
  2026. self.close()
  2027. raise
  2028. def init(self):
  2029. import ftplib
  2030. self.busy = 0
  2031. self.ftp = ftplib.FTP()
  2032. self.ftp.connect(self.host, self.port, self.timeout)
  2033. self.ftp.login(self.user, self.passwd)
  2034. _target = '/'.join(self.dirs)
  2035. self.ftp.cwd(_target)
  2036. def retrfile(self, file, type):
  2037. import ftplib
  2038. self.endtransfer()
  2039. if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
  2040. else: cmd = 'TYPE ' + type; isdir = 0
  2041. try:
  2042. self.ftp.voidcmd(cmd)
  2043. except ftplib.all_errors:
  2044. self.init()
  2045. self.ftp.voidcmd(cmd)
  2046. conn = None
  2047. if file and not isdir:
  2048. # Try to retrieve as a file
  2049. try:
  2050. cmd = 'RETR ' + file
  2051. conn, retrlen = self.ftp.ntransfercmd(cmd)
  2052. except ftplib.error_perm as reason:
  2053. if str(reason)[:3] != '550':
  2054. raise URLError('ftp error: %r' % reason).with_traceback(
  2055. sys.exc_info()[2])
  2056. if not conn:
  2057. # Set transfer mode to ASCII!
  2058. self.ftp.voidcmd('TYPE A')
  2059. # Try a directory listing. Verify that directory exists.
  2060. if file:
  2061. pwd = self.ftp.pwd()
  2062. try:
  2063. try:
  2064. self.ftp.cwd(file)
  2065. except ftplib.error_perm as reason:
  2066. raise URLError('ftp error: %r' % reason) from reason
  2067. finally:
  2068. self.ftp.cwd(pwd)
  2069. cmd = 'LIST ' + file
  2070. else:
  2071. cmd = 'LIST'
  2072. conn, retrlen = self.ftp.ntransfercmd(cmd)
  2073. self.busy = 1
  2074. ftpobj = addclosehook(conn.makefile('rb'), self.file_close)
  2075. self.refcount += 1
  2076. conn.close()
  2077. # Pass back both a suitably decorated object and a retrieval length
  2078. return (ftpobj, retrlen)
  2079. def endtransfer(self):
  2080. self.busy = 0
  2081. def close(self):
  2082. self.keepalive = False
  2083. if self.refcount <= 0:
  2084. self.real_close()
  2085. def file_close(self):
  2086. self.endtransfer()
  2087. self.refcount -= 1
  2088. if self.refcount <= 0 and not self.keepalive:
  2089. self.real_close()
  2090. def real_close(self):
  2091. self.endtransfer()
  2092. try:
  2093. self.ftp.close()
  2094. except ftperrors():
  2095. pass
  2096. # Proxy handling
  2097. def getproxies_environment():
  2098. """Return a dictionary of scheme -> proxy server URL mappings.
  2099. Scan the environment for variables named <scheme>_proxy;
  2100. this seems to be the standard convention. If you need a
  2101. different way, you can pass a proxies dictionary to the
  2102. [Fancy]URLopener constructor.
  2103. """
  2104. proxies = {}
  2105. # in order to prefer lowercase variables, process environment in
  2106. # two passes: first matches any, second pass matches lowercase only
  2107. for name, value in os.environ.items():
  2108. name = name.lower()
  2109. if value and name[-6:] == '_proxy':
  2110. proxies[name[:-6]] = value
  2111. # CVE-2016-1000110 - If we are running as CGI script, forget HTTP_PROXY
  2112. # (non-all-lowercase) as it may be set from the web server by a "Proxy:"
  2113. # header from the client
  2114. # If "proxy" is lowercase, it will still be used thanks to the next block
  2115. if 'REQUEST_METHOD' in os.environ:
  2116. proxies.pop('http', None)
  2117. for name, value in os.environ.items():
  2118. if name[-6:] == '_proxy':
  2119. name = name.lower()
  2120. if value:
  2121. proxies[name[:-6]] = value
  2122. else:
  2123. proxies.pop(name[:-6], None)
  2124. return proxies
  2125. def proxy_bypass_environment(host, proxies=None):
  2126. """Test if proxies should not be used for a particular host.
  2127. Checks the proxy dict for the value of no_proxy, which should
  2128. be a list of comma separated DNS suffixes, or '*' for all hosts.
  2129. """
  2130. if proxies is None:
  2131. proxies = getproxies_environment()
  2132. # don't bypass, if no_proxy isn't specified
  2133. try:
  2134. no_proxy = proxies['no']
  2135. except KeyError:
  2136. return False
  2137. # '*' is special case for always bypass
  2138. if no_proxy == '*':
  2139. return True
  2140. host = host.lower()
  2141. # strip port off host
  2142. hostonly, port = splitport(host)
  2143. # check if the host ends with any of the DNS suffixes
  2144. for name in no_proxy.split(','):
  2145. name = name.strip()
  2146. if name:
  2147. name = name.lstrip('.') # ignore leading dots
  2148. name = name.lower()
  2149. if hostonly == name or host == name:
  2150. return True
  2151. name = '.' + name
  2152. if hostonly.endswith(name) or host.endswith(name):
  2153. return True
  2154. # otherwise, don't bypass
  2155. return False
  2156. # This code tests an OSX specific data structure but is testable on all
  2157. # platforms
  2158. def _proxy_bypass_macosx_sysconf(host, proxy_settings):
  2159. """
  2160. Return True iff this host shouldn't be accessed using a proxy
  2161. This function uses the MacOSX framework SystemConfiguration
  2162. to fetch the proxy information.
  2163. proxy_settings come from _scproxy._get_proxy_settings or get mocked ie:
  2164. { 'exclude_simple': bool,
  2165. 'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.1', '10.0/16']
  2166. }
  2167. """
  2168. from fnmatch import fnmatch
  2169. hostonly, port = splitport(host)
  2170. def ip2num(ipAddr):
  2171. parts = ipAddr.split('.')
  2172. parts = list(map(int, parts))
  2173. if len(parts) != 4:
  2174. parts = (parts + [0, 0, 0, 0])[:4]
  2175. return (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]
  2176. # Check for simple host names:
  2177. if '.' not in host:
  2178. if proxy_settings['exclude_simple']:
  2179. return True
  2180. hostIP = None
  2181. for value in proxy_settings.get('exceptions', ()):
  2182. # Items in the list are strings like these: *.local, 169.254/16
  2183. if not value: continue
  2184. m = re.match(r"(\d+(?:\.\d+)*)(/\d+)?", value)
  2185. if m is not None:
  2186. if hostIP is None:
  2187. try:
  2188. hostIP = socket.gethostbyname(hostonly)
  2189. hostIP = ip2num(hostIP)
  2190. except OSError:
  2191. continue
  2192. base = ip2num(m.group(1))
  2193. mask = m.group(2)
  2194. if mask is None:
  2195. mask = 8 * (m.group(1).count('.') + 1)
  2196. else:
  2197. mask = int(mask[1:])
  2198. mask = 32 - mask
  2199. if (hostIP >> mask) == (base >> mask):
  2200. return True
  2201. elif fnmatch(host, value):
  2202. return True
  2203. return False
  2204. if sys.platform == 'darwin':
  2205. from _scproxy import _get_proxy_settings, _get_proxies
  2206. def proxy_bypass_macosx_sysconf(host):
  2207. proxy_settings = _get_proxy_settings()
  2208. return _proxy_bypass_macosx_sysconf(host, proxy_settings)
  2209. def getproxies_macosx_sysconf():
  2210. """Return a dictionary of scheme -> proxy server URL mappings.
  2211. This function uses the MacOSX framework SystemConfiguration
  2212. to fetch the proxy information.
  2213. """
  2214. return _get_proxies()
  2215. def proxy_bypass(host):
  2216. """Return True, if host should be bypassed.
  2217. Checks proxy settings gathered from the environment, if specified,
  2218. or from the MacOSX framework SystemConfiguration.
  2219. """
  2220. proxies = getproxies_environment()
  2221. if proxies:
  2222. return proxy_bypass_environment(host, proxies)
  2223. else:
  2224. return proxy_bypass_macosx_sysconf(host)
  2225. def getproxies():
  2226. return getproxies_environment() or getproxies_macosx_sysconf()
  2227. elif os.name == 'nt':
  2228. def getproxies_registry():
  2229. """Return a dictionary of scheme -> proxy server URL mappings.
  2230. Win32 uses the registry to store proxies.
  2231. """
  2232. proxies = {}
  2233. try:
  2234. import winreg
  2235. except ImportError:
  2236. # Std module, so should be around - but you never know!
  2237. return proxies
  2238. try:
  2239. internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
  2240. r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
  2241. proxyEnable = winreg.QueryValueEx(internetSettings,
  2242. 'ProxyEnable')[0]
  2243. if proxyEnable:
  2244. # Returned as Unicode but problems if not converted to ASCII
  2245. proxyServer = str(winreg.QueryValueEx(internetSettings,
  2246. 'ProxyServer')[0])
  2247. if '=' in proxyServer:
  2248. # Per-protocol settings
  2249. for p in proxyServer.split(';'):
  2250. protocol, address = p.split('=', 1)
  2251. # See if address has a type:// prefix
  2252. if not re.match('(?:[^/:]+)://', address):
  2253. address = '%s://%s' % (protocol, address)
  2254. proxies[protocol] = address
  2255. else:
  2256. # Use one setting for all protocols
  2257. if proxyServer[:5] == 'http:':
  2258. proxies['http'] = proxyServer
  2259. else:
  2260. proxies['http'] = 'http://%s' % proxyServer
  2261. proxies['https'] = 'https://%s' % proxyServer
  2262. proxies['ftp'] = 'ftp://%s' % proxyServer
  2263. internetSettings.Close()
  2264. except (OSError, ValueError, TypeError):
  2265. # Either registry key not found etc, or the value in an
  2266. # unexpected format.
  2267. # proxies already set up to be empty so nothing to do
  2268. pass
  2269. return proxies
  2270. def getproxies():
  2271. """Return a dictionary of scheme -> proxy server URL mappings.
  2272. Returns settings gathered from the environment, if specified,
  2273. or the registry.
  2274. """
  2275. return getproxies_environment() or getproxies_registry()
  2276. def proxy_bypass_registry(host):
  2277. try:
  2278. import winreg
  2279. except ImportError:
  2280. # Std modules, so should be around - but you never know!
  2281. return 0
  2282. try:
  2283. internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
  2284. r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
  2285. proxyEnable = winreg.QueryValueEx(internetSettings,
  2286. 'ProxyEnable')[0]
  2287. proxyOverride = str(winreg.QueryValueEx(internetSettings,
  2288. 'ProxyOverride')[0])
  2289. # ^^^^ Returned as Unicode but problems if not converted to ASCII
  2290. except OSError:
  2291. return 0
  2292. if not proxyEnable or not proxyOverride:
  2293. return 0
  2294. # try to make a host list from name and IP address.
  2295. rawHost, port = splitport(host)
  2296. host = [rawHost]
  2297. try:
  2298. addr = socket.gethostbyname(rawHost)
  2299. if addr != rawHost:
  2300. host.append(addr)
  2301. except OSError:
  2302. pass
  2303. try:
  2304. fqdn = socket.getfqdn(rawHost)
  2305. if fqdn != rawHost:
  2306. host.append(fqdn)
  2307. except OSError:
  2308. pass
  2309. # make a check value list from the registry entry: replace the
  2310. # '<local>' string by the localhost entry and the corresponding
  2311. # canonical entry.
  2312. proxyOverride = proxyOverride.split(';')
  2313. # now check if we match one of the registry values.
  2314. for test in proxyOverride:
  2315. if test == '<local>':
  2316. if '.' not in rawHost:
  2317. return 1
  2318. test = test.replace(".", r"\.") # mask dots
  2319. test = test.replace("*", r".*") # change glob sequence
  2320. test = test.replace("?", r".") # change glob char
  2321. for val in host:
  2322. if re.match(test, val, re.I):
  2323. return 1
  2324. return 0
  2325. def proxy_bypass(host):
  2326. """Return True, if host should be bypassed.
  2327. Checks proxy settings gathered from the environment, if specified,
  2328. or the registry.
  2329. """
  2330. proxies = getproxies_environment()
  2331. if proxies:
  2332. return proxy_bypass_environment(host, proxies)
  2333. else:
  2334. return proxy_bypass_registry(host)
  2335. else:
  2336. # By default use environment variables
  2337. getproxies = getproxies_environment
  2338. proxy_bypass = proxy_bypass_environment