request.py 95 KB

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