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