| 1 |
"""Fork of urllib2. |
| 2 |
|
| 3 |
When reading this, don't assume that all code in here is reachable. Code in |
| 4 |
the rest of mechanize may be used instead. |
| 5 |
|
| 6 |
Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Python |
| 7 |
Software Foundation; All Rights Reserved |
| 8 |
|
| 9 |
Copyright 2002-2009 John J Lee <[email protected]> |
| 10 |
|
| 11 |
This code is free software; you can redistribute it and/or modify it |
| 12 |
under the terms of the BSD or ZPL 2.1 licenses (see the file |
| 13 |
LICENSE included with the distribution). |
| 14 |
|
| 15 |
""" |
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
from __future__ import absolute_import |
| 32 |
|
| 33 |
import base64 |
| 34 |
import bisect |
| 35 |
import copy |
| 36 |
import hashlib |
| 37 |
import logging |
| 38 |
import os |
| 39 |
import platform |
| 40 |
import posixpath |
| 41 |
import re |
| 42 |
import socket |
| 43 |
import sys |
| 44 |
import time |
| 45 |
from collections import OrderedDict |
| 46 |
from functools import partial |
| 47 |
from io import BufferedReader, BytesIO |
| 48 |
|
| 49 |
from . import _rfc3986 |
| 50 |
from ._clientcookie import CookieJar |
| 51 |
from ._headersutil import normalize_header_name |
| 52 |
from ._response import closeable_response |
| 53 |
from .polyglot import (HTTPConnection, HTTPError, HTTPSConnection, URLError, |
| 54 |
as_unicode, create_response_info, ftpwrapper, |
| 55 |
getproxies, is_class, is_mapping, is_py2, is_string, |
| 56 |
iteritems, map, raise_with_traceback, splitattr, |
| 57 |
splitpasswd, splitport, splittype, splituser, |
| 58 |
splitvalue, unquote, unwrap, url2pathname, |
| 59 |
urllib_proxy_bypass, urllib_splithost, urlparse, |
| 60 |
urlsplit, urlunparse) |
| 61 |
|
| 62 |
|
| 63 |
def sha1_digest(data): |
| 64 |
if not isinstance(data, bytes): |
| 65 |
data = data.encode('utf-8') |
| 66 |
return hashlib.sha1(data).hexdigest() |
| 67 |
|
| 68 |
|
| 69 |
def md5_digest(data): |
| 70 |
if not isinstance(data, bytes): |
| 71 |
data = data.encode('utf-8') |
| 72 |
return hashlib.md5(data).hexdigest() |
| 73 |
|
| 74 |
|
| 75 |
if platform.python_implementation() == 'PyPy': |
| 76 |
def create_readline_wrapper(fh): |
| 77 |
fh.recv = fh.read |
| 78 |
if is_py2: |
| 79 |
if not hasattr(fh, '_drop'): |
| 80 |
fh._drop = lambda: None |
| 81 |
fh._reuse = lambda: None |
| 82 |
ans = socket._fileobject(fh, close=True) |
| 83 |
else: |
| 84 |
fh.recv_into = fh.readinto |
| 85 |
fh._decref_socketios = lambda: None |
| 86 |
ans = BufferedReader(socket.SocketIO(fh, 'r')) |
| 87 |
return ans |
| 88 |
else: |
| 89 |
def create_readline_wrapper(fh): |
| 90 |
fh.recv = fh.read |
| 91 |
if is_py2: |
| 92 |
ans = socket._fileobject(fh, close=True) |
| 93 |
else: |
| 94 |
fh.recv_into = fh.readinto |
| 95 |
fh._decref_socketios = lambda: None |
| 96 |
ans = BufferedReader(socket.SocketIO(fh, 'r')) |
| 97 |
return ans |
| 98 |
|
| 99 |
|
| 100 |
splithost = urllib_splithost |
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
__version__ = sys.version[:3] |
| 105 |
|
| 106 |
_opener = None |
| 107 |
|
| 108 |
|
| 109 |
def urlopen(url, data=None): |
| 110 |
global _opener |
| 111 |
if _opener is None: |
| 112 |
_opener = build_opener() |
| 113 |
return _opener._open(url, data) |
| 114 |
|
| 115 |
|
| 116 |
def install_opener(opener): |
| 117 |
global _opener |
| 118 |
_opener = opener |
| 119 |
|
| 120 |
|
| 121 |
|
| 122 |
_cut_port_re = re.compile(r":\d+$") |
| 123 |
|
| 124 |
|
| 125 |
def request_host(request): |
| 126 |
"""Return request-host, as defined by RFC 2965. |
| 127 |
|
| 128 |
Variation from RFC: returned value is lowercased, for convenient |
| 129 |
comparison. |
| 130 |
|
| 131 |
""" |
| 132 |
url = request.get_full_url() |
| 133 |
host = urlparse(url)[1] |
| 134 |
if host == "": |
| 135 |
host = request.get_header("Host", "") |
| 136 |
|
| 137 |
|
| 138 |
host = _cut_port_re.sub("", host, 1) |
| 139 |
return host.lower() |
| 140 |
|
| 141 |
|
| 142 |
PERCENT_RE = re.compile(b"%[a-fA-F0-9]{2}") |
| 143 |
ZONE_ID_CHARS = set(bytearray( |
| 144 |
b"ABCDEFGHIJKLMNOPQRSTUVWXYZ" b"abcdefghijklmnopqrstuvwxyz" b"0123456789._!-" |
| 145 |
)) |
| 146 |
USERINFO_CHARS = ZONE_ID_CHARS | set(bytearray(b"$&'()*+,;=:")) |
| 147 |
PATH_CHARS = USERINFO_CHARS | set(bytearray(b'@/~')) |
| 148 |
QUERY_CHARS = FRAGMENT_CHARS = PATH_CHARS | {ord(b"?")} |
| 149 |
|
| 150 |
|
| 151 |
def fix_invalid_bytes_in_url_component(component, allowed_chars=PATH_CHARS): |
| 152 |
if not component: |
| 153 |
return component |
| 154 |
is_bytes = isinstance(component, bytes) |
| 155 |
if not is_bytes: |
| 156 |
component = component.encode('utf-8', 'surrogatepass') |
| 157 |
percent_encodings = PERCENT_RE.findall(component) |
| 158 |
for enc in percent_encodings: |
| 159 |
if not enc.isupper(): |
| 160 |
component = component.replace(enc, enc.upper()) |
| 161 |
is_percent_encoded = len(percent_encodings) == component.count(b"%") |
| 162 |
encoded_component = bytearray() |
| 163 |
percent = ord('%') |
| 164 |
for byte_ord in bytearray(component): |
| 165 |
if (is_percent_encoded and byte_ord == percent) or (byte_ord < 128 and byte_ord in allowed_chars): |
| 166 |
encoded_component.append(byte_ord) |
| 167 |
continue |
| 168 |
encoded_component.extend(b"%" + (hex(byte_ord)[2:].encode().zfill(2).upper())) |
| 169 |
encoded_component = bytes(encoded_component) |
| 170 |
if not is_bytes: |
| 171 |
encoded_component = encoded_component.decode('utf-8') |
| 172 |
return encoded_component |
| 173 |
|
| 174 |
|
| 175 |
def normalize_url(url): |
| 176 |
parsed = urlparse(url) |
| 177 |
netloc = parsed.netloc |
| 178 |
if not isinstance(netloc, bytes) and netloc: |
| 179 |
def safe_encode(label): |
| 180 |
try: |
| 181 |
return label.encode('idna').decode('ascii') |
| 182 |
except ValueError: |
| 183 |
return label.encode('ascii', 'replace').decode('ascii') |
| 184 |
netloc = u'.'.join(map(safe_encode, netloc.split(u'.'))) |
| 185 |
|
| 186 |
return urlunparse(parsed._replace( |
| 187 |
path=fix_invalid_bytes_in_url_component(parsed.path), netloc=netloc, |
| 188 |
query=fix_invalid_bytes_in_url_component(parsed.query, QUERY_CHARS), |
| 189 |
fragment=fix_invalid_bytes_in_url_component(parsed.fragment, FRAGMENT_CHARS), |
| 190 |
)) |
| 191 |
|
| 192 |
|
| 193 |
class Request: |
| 194 |
|
| 195 |
def __init__(self, url, data=None, headers={}, |
| 196 |
origin_req_host=None, unverifiable=False, method=None): |
| 197 |
|
| 198 |
self.__original = normalize_url(unwrap(url)) |
| 199 |
self.type = None |
| 200 |
self._method = method and str(method) |
| 201 |
|
| 202 |
self.host = None |
| 203 |
self.port = None |
| 204 |
self._tunnel_host = None |
| 205 |
self.data = data |
| 206 |
self.headers = OrderedDict() |
| 207 |
for key, value in iteritems(headers): |
| 208 |
self.add_header(key, value) |
| 209 |
self.unredirected_hdrs = OrderedDict() |
| 210 |
if origin_req_host is None: |
| 211 |
origin_req_host = request_host(self) |
| 212 |
self.origin_req_host = origin_req_host |
| 213 |
self.unverifiable = unverifiable |
| 214 |
try: |
| 215 |
self.get_host() |
| 216 |
except Exception: |
| 217 |
self.host = None |
| 218 |
|
| 219 |
def __getattr__(self, attr): |
| 220 |
|
| 221 |
|
| 222 |
|
| 223 |
|
| 224 |
if attr[:12] == '_Request__r_': |
| 225 |
name = attr[12:] |
| 226 |
if hasattr(Request, 'get_' + name): |
| 227 |
getattr(self, 'get_' + name)() |
| 228 |
return getattr(self, attr) |
| 229 |
raise AttributeError(attr) |
| 230 |
|
| 231 |
def get_method(self): |
| 232 |
' The method used for HTTP requests ' |
| 233 |
if self._method is None: |
| 234 |
return "POST" if self.has_data() else 'GET' |
| 235 |
return self._method |
| 236 |
|
| 237 |
|
| 238 |
|
| 239 |
def set_data(self, data): |
| 240 |
' Set the data (a bytestring) to be sent with this request ' |
| 241 |
self.data = data |
| 242 |
add_data = set_data |
| 243 |
|
| 244 |
def has_data(self): |
| 245 |
' True iff there is some data to be sent with this request ' |
| 246 |
return self.data is not None |
| 247 |
|
| 248 |
def get_data(self): |
| 249 |
' The data to be sent with this request ' |
| 250 |
return self.data |
| 251 |
|
| 252 |
def get_full_url(self): |
| 253 |
return self.__original |
| 254 |
|
| 255 |
@property |
| 256 |
def full_url(self): |
| 257 |
|
| 258 |
|
| 259 |
|
| 260 |
return self.__original |
| 261 |
|
| 262 |
def get_type(self): |
| 263 |
if self.type is None: |
| 264 |
self.type, self.__r_type = splittype(self.__original) |
| 265 |
if self.type is None: |
| 266 |
raise ValueError("unknown url type: %s" % self.__original) |
| 267 |
return self.type |
| 268 |
|
| 269 |
def get_host(self): |
| 270 |
if self.host is None: |
| 271 |
self.host, self.__r_host = splithost(self.__r_type) |
| 272 |
if self.host: |
| 273 |
self.host = unquote(self.host) |
| 274 |
return self.host |
| 275 |
|
| 276 |
def get_selector(self): |
| 277 |
scheme, authority, path, query, fragment = _rfc3986.urlsplit( |
| 278 |
self.__r_host) |
| 279 |
if path == "": |
| 280 |
path = "/" |
| 281 |
fragment = None |
| 282 |
return _rfc3986.urlunsplit([scheme, authority, path, query, fragment]) |
| 283 |
|
| 284 |
def set_proxy(self, host, type): |
| 285 |
orig_host = self.get_host() |
| 286 |
if self.get_type() == 'https' and not self._tunnel_host: |
| 287 |
self._tunnel_host = orig_host |
| 288 |
else: |
| 289 |
self.type = type |
| 290 |
self.__r_host = self.__original |
| 291 |
|
| 292 |
self.host = host |
| 293 |
|
| 294 |
def has_proxy(self): |
| 295 |
"""Private method.""" |
| 296 |
|
| 297 |
return self.__r_host == self.__original |
| 298 |
|
| 299 |
def get_origin_req_host(self): |
| 300 |
return self.origin_req_host |
| 301 |
|
| 302 |
def is_unverifiable(self): |
| 303 |
return self.unverifiable |
| 304 |
|
| 305 |
def add_header(self, key, val=None): |
| 306 |
''' Add the specified header, replacing existing one, if needed. If val |
| 307 |
is None, remove the header. ''' |
| 308 |
|
| 309 |
key = normalize_header_name(key) |
| 310 |
if val is None: |
| 311 |
self.headers.pop(key, None) |
| 312 |
else: |
| 313 |
self.headers[key] = val |
| 314 |
|
| 315 |
def add_unredirected_header(self, key, val): |
| 316 |
''' Same as :meth:`add_header()` except that this header will not |
| 317 |
be sent for redirected requests. ''' |
| 318 |
key = normalize_header_name(key) |
| 319 |
if val is None: |
| 320 |
self.unredirected_hdrs.pop(key, None) |
| 321 |
else: |
| 322 |
self.unredirected_hdrs[key] = val |
| 323 |
|
| 324 |
def has_header(self, header_name): |
| 325 |
''' Check if the specified header is present ''' |
| 326 |
header_name = normalize_header_name(header_name) |
| 327 |
return (header_name in self.headers or |
| 328 |
header_name in self.unredirected_hdrs) |
| 329 |
|
| 330 |
def get_header(self, header_name, default=None): |
| 331 |
''' Get the value of the specified header. If absent, return `default` |
| 332 |
''' |
| 333 |
header_name = normalize_header_name(header_name) |
| 334 |
return self.headers.get( |
| 335 |
header_name, |
| 336 |
self.unredirected_hdrs.get(header_name, default)) |
| 337 |
|
| 338 |
def header_items(self): |
| 339 |
''' Get a copy of all headers for this request as a list of 2-tuples |
| 340 |
''' |
| 341 |
hdrs = self.unredirected_hdrs.copy() |
| 342 |
hdrs.update(self.headers) |
| 343 |
return list(iteritems(hdrs)) |
| 344 |
|
| 345 |
|
| 346 |
class OpenerDirector(object): |
| 347 |
|
| 348 |
def __init__(self): |
| 349 |
client_version = "Python-urllib/%s" % __version__ |
| 350 |
self.addheaders = [('User-agent', client_version)] |
| 351 |
self.finalize_request_headers = None |
| 352 |
|
| 353 |
self.handlers = [] |
| 354 |
self.handle_open = {} |
| 355 |
self.handle_error = {} |
| 356 |
self.process_response = {} |
| 357 |
self.process_request = {} |
| 358 |
|
| 359 |
def add_handler(self, handler): |
| 360 |
if not hasattr(handler, "add_parent"): |
| 361 |
raise TypeError("expected BaseHandler instance, got %r" % |
| 362 |
type(handler)) |
| 363 |
|
| 364 |
added = False |
| 365 |
for meth in dir(handler): |
| 366 |
if meth in ["redirect_request", "do_open", "proxy_open"]: |
| 367 |
|
| 368 |
continue |
| 369 |
|
| 370 |
i = meth.find("_") |
| 371 |
protocol = meth[:i] |
| 372 |
condition = meth[i + 1:] |
| 373 |
|
| 374 |
if condition.startswith("error"): |
| 375 |
j = condition.find("_") + i + 1 |
| 376 |
kind = meth[j + 1:] |
| 377 |
try: |
| 378 |
kind = int(kind) |
| 379 |
except ValueError: |
| 380 |
pass |
| 381 |
lookup = self.handle_error.get(protocol, {}) |
| 382 |
self.handle_error[protocol] = lookup |
| 383 |
elif condition == "open": |
| 384 |
kind = protocol |
| 385 |
lookup = self.handle_open |
| 386 |
elif condition == "response": |
| 387 |
kind = protocol |
| 388 |
lookup = self.process_response |
| 389 |
elif condition == "request": |
| 390 |
kind = protocol |
| 391 |
lookup = self.process_request |
| 392 |
else: |
| 393 |
continue |
| 394 |
|
| 395 |
handlers = lookup.setdefault(kind, []) |
| 396 |
if handlers: |
| 397 |
bisect.insort(handlers, handler) |
| 398 |
else: |
| 399 |
handlers.append(handler) |
| 400 |
added = True |
| 401 |
|
| 402 |
if added: |
| 403 |
|
| 404 |
|
| 405 |
bisect.insort(self.handlers, handler) |
| 406 |
handler.add_parent(self) |
| 407 |
|
| 408 |
def close(self): |
| 409 |
|
| 410 |
pass |
| 411 |
|
| 412 |
def _call_chain(self, chain, kind, meth_name, *args): |
| 413 |
|
| 414 |
|
| 415 |
|
| 416 |
handlers = chain.get(kind, ()) |
| 417 |
for handler in handlers: |
| 418 |
func = getattr(handler, meth_name) |
| 419 |
|
| 420 |
result = func(*args) |
| 421 |
if result is not None: |
| 422 |
return result |
| 423 |
|
| 424 |
def _open(self, req, data=None): |
| 425 |
result = self._call_chain(self.handle_open, 'default', |
| 426 |
'default_open', req) |
| 427 |
if result: |
| 428 |
return result |
| 429 |
|
| 430 |
protocol = req.get_type() |
| 431 |
result = self._call_chain(self.handle_open, protocol, protocol + |
| 432 |
'_open', req) |
| 433 |
if result: |
| 434 |
return result |
| 435 |
|
| 436 |
return self._call_chain(self.handle_open, 'unknown', |
| 437 |
'unknown_open', req) |
| 438 |
|
| 439 |
def error(self, proto, *args): |
| 440 |
if proto in ('http', 'https'): |
| 441 |
|
| 442 |
|
| 443 |
dict = self.handle_error['http'] |
| 444 |
proto = args[2] |
| 445 |
meth_name = 'http_error_%s' % proto |
| 446 |
http_err = 1 |
| 447 |
orig_args = args |
| 448 |
else: |
| 449 |
dict = self.handle_error |
| 450 |
meth_name = proto + '_error' |
| 451 |
http_err = 0 |
| 452 |
args = (dict, proto, meth_name) + args |
| 453 |
result = self._call_chain(*args) |
| 454 |
if result: |
| 455 |
return result |
| 456 |
|
| 457 |
if http_err: |
| 458 |
args = (dict, 'default', 'http_error_default') + orig_args |
| 459 |
return self._call_chain(*args) |
| 460 |
|
| 461 |
|
| 462 |
|
| 463 |
|
| 464 |
|
| 465 |
|
| 466 |
def build_opener(*handlers): |
| 467 |
"""Create an opener object from a list of handlers. |
| 468 |
|
| 469 |
The opener will use several default handlers, including support |
| 470 |
for HTTP, FTP and when applicable, HTTPS. |
| 471 |
|
| 472 |
If any of the handlers passed as arguments are subclasses of the |
| 473 |
default handlers, the default handlers will not be used. |
| 474 |
""" |
| 475 |
opener = OpenerDirector() |
| 476 |
default_classes = [ProxyHandler, UnknownHandler, HTTPHandler, |
| 477 |
HTTPDefaultErrorHandler, HTTPRedirectHandler, |
| 478 |
FTPHandler, FileHandler, HTTPErrorProcessor] |
| 479 |
default_classes.append(HTTPSHandler) |
| 480 |
skip = set() |
| 481 |
for klass in default_classes: |
| 482 |
for check in handlers: |
| 483 |
if is_class(check): |
| 484 |
if issubclass(check, klass): |
| 485 |
skip.add(klass) |
| 486 |
elif isinstance(check, klass): |
| 487 |
skip.add(klass) |
| 488 |
for klass in skip: |
| 489 |
default_classes.remove(klass) |
| 490 |
|
| 491 |
for klass in default_classes: |
| 492 |
opener.add_handler(klass()) |
| 493 |
|
| 494 |
for h in handlers: |
| 495 |
if is_class(h): |
| 496 |
h = h() |
| 497 |
opener.add_handler(h) |
| 498 |
return opener |
| 499 |
|
| 500 |
|
| 501 |
class BaseHandler: |
| 502 |
handler_order = 500 |
| 503 |
|
| 504 |
def add_parent(self, parent): |
| 505 |
self.parent = parent |
| 506 |
|
| 507 |
def close(self): |
| 508 |
|
| 509 |
pass |
| 510 |
|
| 511 |
def __lt__(self, other): |
| 512 |
return self.handler_order < getattr( |
| 513 |
other, 'handler_order', sys.maxsize) |
| 514 |
|
| 515 |
def __copy__(self): |
| 516 |
return self.__class__() |
| 517 |
|
| 518 |
|
| 519 |
class HTTPErrorProcessor(BaseHandler): |
| 520 |
"""Process HTTP error responses. |
| 521 |
|
| 522 |
The purpose of this handler is to to allow other response processors a |
| 523 |
look-in by removing the call to parent.error() from |
| 524 |
AbstractHTTPHandler. |
| 525 |
|
| 526 |
For non-2xx error codes, this just passes the job on to the |
| 527 |
Handler.<proto>_error_<code> methods, via the OpenerDirector.error method. |
| 528 |
Eventually, HTTPDefaultErrorHandler will raise an HTTPError if no other |
| 529 |
handler handles the error. |
| 530 |
|
| 531 |
""" |
| 532 |
handler_order = 1000 |
| 533 |
|
| 534 |
def http_response(self, request, response): |
| 535 |
code, msg, hdrs = response.code, response.msg, response.info() |
| 536 |
|
| 537 |
|
| 538 |
|
| 539 |
if not (200 <= code < 300): |
| 540 |
|
| 541 |
response = self.parent.error( |
| 542 |
'http', request, response, code, msg, hdrs) |
| 543 |
|
| 544 |
return response |
| 545 |
|
| 546 |
https_response = http_response |
| 547 |
|
| 548 |
|
| 549 |
class HTTPDefaultErrorHandler(BaseHandler): |
| 550 |
|
| 551 |
def http_error_default(self, req, fp, code, msg, hdrs): |
| 552 |
|
| 553 |
|
| 554 |
|
| 555 |
|
| 556 |
if isinstance(fp, HTTPError): |
| 557 |
response = fp |
| 558 |
else: |
| 559 |
response = HTTPError( |
| 560 |
req.get_full_url(), code, msg, hdrs, fp) |
| 561 |
assert code == response.code |
| 562 |
assert msg == response.msg |
| 563 |
assert hdrs == response.hdrs |
| 564 |
raise response |
| 565 |
|
| 566 |
|
| 567 |
class HTTPRedirectHandler(BaseHandler): |
| 568 |
|
| 569 |
|
| 570 |
max_repeats = 4 |
| 571 |
|
| 572 |
|
| 573 |
max_redirections = 10 |
| 574 |
|
| 575 |
|
| 576 |
|
| 577 |
|
| 578 |
|
| 579 |
|
| 580 |
|
| 581 |
|
| 582 |
|
| 583 |
|
| 584 |
|
| 585 |
|
| 586 |
|
| 587 |
|
| 588 |
|
| 589 |
|
| 590 |
|
| 591 |
|
| 592 |
def redirect_request(self, req, fp, code, msg, headers, newurl): |
| 593 |
"""Return a Request or None in response to a redirect. |
| 594 |
|
| 595 |
This is called by the http_error_30x methods when a |
| 596 |
redirection response is received. If a redirection should |
| 597 |
take place, return a new Request to allow http_error_30x to |
| 598 |
perform the redirect. Otherwise, raise HTTPError if no-one |
| 599 |
else should try to handle this url. Return None if you can't |
| 600 |
but another Handler might. |
| 601 |
""" |
| 602 |
from ._request import Request |
| 603 |
m = req.get_method() |
| 604 |
if (code in (301, 302, 303, 307, 308, "refresh") and m in ("GET", "HEAD") |
| 605 |
or code in (301, 302, 303, 307, 308, "refresh") and m == "POST"): |
| 606 |
|
| 607 |
|
| 608 |
|
| 609 |
|
| 610 |
|
| 611 |
|
| 612 |
|
| 613 |
new = Request( |
| 614 |
newurl, |
| 615 |
headers=req.headers, |
| 616 |
origin_req_host=req.get_origin_req_host(), |
| 617 |
unverifiable=True, |
| 618 |
visit=False, method=m if code in (307, 308) else None, |
| 619 |
timeout=req.timeout) |
| 620 |
new._origin_req = getattr(req, "_origin_req", req) |
| 621 |
return new |
| 622 |
else: |
| 623 |
raise HTTPError(req.get_full_url(), code, msg, headers, fp) |
| 624 |
|
| 625 |
def http_error_302(self, req, fp, code, msg, headers): |
| 626 |
|
| 627 |
|
| 628 |
if 'location' in headers: |
| 629 |
newurl = headers.getheaders('location')[0] |
| 630 |
elif 'uri' in headers: |
| 631 |
newurl = headers.getheaders('uri')[0] |
| 632 |
else: |
| 633 |
return |
| 634 |
newurl = _rfc3986.clean_url(newurl) |
| 635 |
newurl = _rfc3986.urljoin(req.get_full_url(), newurl) |
| 636 |
|
| 637 |
|
| 638 |
|
| 639 |
|
| 640 |
new = self.redirect_request(req, fp, code, msg, headers, newurl) |
| 641 |
if new is None: |
| 642 |
return |
| 643 |
|
| 644 |
|
| 645 |
|
| 646 |
if hasattr(req, 'redirect_dict'): |
| 647 |
visited = new.redirect_dict = req.redirect_dict |
| 648 |
if (visited.get(newurl, 0) >= self.max_repeats or |
| 649 |
len(visited) >= self.max_redirections): |
| 650 |
raise HTTPError(req.get_full_url(), code, |
| 651 |
self.inf_msg + msg, headers, fp) |
| 652 |
else: |
| 653 |
visited = new.redirect_dict = req.redirect_dict = {} |
| 654 |
visited[newurl] = visited.get(newurl, 0) + 1 |
| 655 |
|
| 656 |
|
| 657 |
|
| 658 |
fp.read() |
| 659 |
fp.close() |
| 660 |
|
| 661 |
return self.parent.open(new) |
| 662 |
|
| 663 |
http_error_301 = http_error_303 = http_error_307 = http_error_302 |
| 664 |
http_error_refresh = http_error_308 = http_error_302 |
| 665 |
|
| 666 |
inf_msg = "The HTTP server returned a redirect error that would " \ |
| 667 |
"lead to an infinite loop.\n" \ |
| 668 |
"The last 30x error message was:\n" |
| 669 |
|
| 670 |
|
| 671 |
def _parse_proxy(proxy): |
| 672 |
"""Return (scheme, user, password, host/port) given a URL or an authority. |
| 673 |
|
| 674 |
If a URL is supplied, it must have an authority (host:port) component. |
| 675 |
According to RFC 3986, having an authority component means the URL must |
| 676 |
have two slashes after the scheme: |
| 677 |
|
| 678 |
>>> _parse_proxy('file:/ftp.example.com/') |
| 679 |
Traceback (most recent call last): |
| 680 |
ValueError: proxy URL with no authority: 'file:/ftp.example.com/' |
| 681 |
|
| 682 |
The first three items of the returned tuple may be None. |
| 683 |
|
| 684 |
Examples of authority parsing: |
| 685 |
|
| 686 |
>>> _parse_proxy('proxy.example.com') |
| 687 |
(None, None, None, 'proxy.example.com') |
| 688 |
>>> _parse_proxy('proxy.example.com:3128') |
| 689 |
(None, None, None, 'proxy.example.com:3128') |
| 690 |
|
| 691 |
The authority component may optionally include userinfo (assumed to be |
| 692 |
username:password): |
| 693 |
|
| 694 |
>>> _parse_proxy('joe:[email protected]') |
| 695 |
(None, 'joe', 'password', 'proxy.example.com') |
| 696 |
>>> _parse_proxy('joe:[email protected]:3128') |
| 697 |
(None, 'joe', 'password', 'proxy.example.com:3128') |
| 698 |
|
| 699 |
Same examples, but with URLs instead: |
| 700 |
|
| 701 |
>>> _parse_proxy('http://proxy.example.com/') |
| 702 |
('http', None, None, 'proxy.example.com') |
| 703 |
>>> _parse_proxy('http://proxy.example.com:3128/') |
| 704 |
('http', None, None, 'proxy.example.com:3128') |
| 705 |
>>> _parse_proxy('http://joe:[email protected]/') |
| 706 |
('http', 'joe', 'password', 'proxy.example.com') |
| 707 |
>>> _parse_proxy('http://joe:[email protected]:3128') |
| 708 |
('http', 'joe', 'password', 'proxy.example.com:3128') |
| 709 |
|
| 710 |
Everything after the authority is ignored: |
| 711 |
|
| 712 |
>>> _parse_proxy('ftp://joe:[email protected]/rubbish:3128') |
| 713 |
('ftp', 'joe', 'password', 'proxy.example.com') |
| 714 |
|
| 715 |
Test for no trailing '/' case: |
| 716 |
|
| 717 |
>>> _parse_proxy('http://joe:[email protected]') |
| 718 |
('http', 'joe', 'password', 'proxy.example.com') |
| 719 |
|
| 720 |
""" |
| 721 |
scheme, r_scheme = splittype(proxy) |
| 722 |
if not r_scheme.startswith("/"): |
| 723 |
|
| 724 |
scheme = None |
| 725 |
authority = proxy |
| 726 |
else: |
| 727 |
|
| 728 |
if not r_scheme.startswith("//"): |
| 729 |
raise ValueError("proxy URL with no authority: %r" % proxy) |
| 730 |
|
| 731 |
|
| 732 |
end = r_scheme.find("/", 2) |
| 733 |
if end == -1: |
| 734 |
end = None |
| 735 |
authority = r_scheme[2:end] |
| 736 |
userinfo, hostport = splituser(authority) |
| 737 |
if userinfo is not None: |
| 738 |
user, password = splitpasswd(userinfo) |
| 739 |
else: |
| 740 |
user = password = None |
| 741 |
return scheme, user, password, hostport |
| 742 |
|
| 743 |
|
| 744 |
class ProxyHandler(BaseHandler): |
| 745 |
|
| 746 |
handler_order = 100 |
| 747 |
|
| 748 |
def __init__(self, proxies=None, proxy_bypass=None): |
| 749 |
if proxies is None: |
| 750 |
proxies = getproxies() |
| 751 |
|
| 752 |
assert is_mapping(proxies), "proxies must be a mapping" |
| 753 |
self.proxies = proxies |
| 754 |
for type, url in iteritems(proxies): |
| 755 |
setattr(self, '%s_open' % type, |
| 756 |
lambda r, proxy=url, type=type, meth=self.proxy_open: |
| 757 |
meth(r, proxy, type)) |
| 758 |
if proxy_bypass is None: |
| 759 |
proxy_bypass = urllib_proxy_bypass |
| 760 |
self._proxy_bypass = proxy_bypass |
| 761 |
|
| 762 |
def proxy_open(self, req, proxy, type): |
| 763 |
orig_type = req.get_type() |
| 764 |
proxy_type, user, password, hostport = _parse_proxy(proxy) |
| 765 |
|
| 766 |
if proxy_type is None: |
| 767 |
proxy_type = orig_type |
| 768 |
|
| 769 |
if req.get_host() and self._proxy_bypass(req.get_host()): |
| 770 |
return None |
| 771 |
|
| 772 |
if user and password: |
| 773 |
user_pass = '%s:%s' % (unquote(user), unquote(password)) |
| 774 |
if not isinstance(user_pass, bytes): |
| 775 |
user_pass = user_pass.encode('utf-8') |
| 776 |
creds = base64.b64encode(user_pass).strip() |
| 777 |
if isinstance(creds, bytes): |
| 778 |
creds = creds.decode('ascii') |
| 779 |
req.add_header('Proxy-authorization', 'Basic ' + creds) |
| 780 |
hostport = unquote(hostport) |
| 781 |
req.set_proxy(hostport, proxy_type) |
| 782 |
if orig_type == proxy_type or orig_type == 'https': |
| 783 |
|
| 784 |
return None |
| 785 |
else: |
| 786 |
|
| 787 |
|
| 788 |
|
| 789 |
|
| 790 |
|
| 791 |
|
| 792 |
return self.parent.open(req) |
| 793 |
|
| 794 |
def __copy__(self): |
| 795 |
return ProxyHandler(self.proxies.copy(), self._proxy_bypass) |
| 796 |
|
| 797 |
|
| 798 |
class HTTPPasswordMgr: |
| 799 |
|
| 800 |
def __init__(self): |
| 801 |
self.passwd = {} |
| 802 |
|
| 803 |
def add_password(self, realm, uri, user, passwd): |
| 804 |
|
| 805 |
if is_string(uri): |
| 806 |
uri = [uri] |
| 807 |
if realm not in self.passwd: |
| 808 |
self.passwd[realm] = {} |
| 809 |
for default_port in True, False: |
| 810 |
reduced_uri = tuple( |
| 811 |
[self.reduce_uri(u, default_port) for u in uri]) |
| 812 |
self.passwd[realm][reduced_uri] = (user, passwd) |
| 813 |
|
| 814 |
def find_user_password(self, realm, authuri): |
| 815 |
domains = self.passwd.get(realm, {}) |
| 816 |
for default_port in True, False: |
| 817 |
reduced_authuri = self.reduce_uri(authuri, default_port) |
| 818 |
for uris, authinfo in iteritems(domains): |
| 819 |
for uri in uris: |
| 820 |
if self.is_suburi(uri, reduced_authuri): |
| 821 |
return authinfo |
| 822 |
return None, None |
| 823 |
|
| 824 |
def reduce_uri(self, uri, default_port=True): |
| 825 |
"""Accept authority or URI and extract only the authority and path.""" |
| 826 |
|
| 827 |
parts = urlsplit(uri) |
| 828 |
if parts[1]: |
| 829 |
|
| 830 |
scheme = parts[0] |
| 831 |
authority = parts[1] |
| 832 |
path = parts[2] or '/' |
| 833 |
else: |
| 834 |
|
| 835 |
scheme = None |
| 836 |
authority = uri |
| 837 |
path = '/' |
| 838 |
host, port = splitport(authority) |
| 839 |
if default_port and port is None and scheme is not None: |
| 840 |
dport = {"http": 80, |
| 841 |
"https": 443, |
| 842 |
}.get(scheme) |
| 843 |
if dport is not None: |
| 844 |
authority = "%s:%d" % (host, dport) |
| 845 |
return authority, path |
| 846 |
|
| 847 |
def is_suburi(self, base, test): |
| 848 |
"""Check if test is below base in a URI tree |
| 849 |
|
| 850 |
Both args must be URIs in reduced form. |
| 851 |
""" |
| 852 |
if base == test: |
| 853 |
return True |
| 854 |
if base[0] != test[0]: |
| 855 |
return False |
| 856 |
common = posixpath.commonprefix((base[1], test[1])) |
| 857 |
if len(common) == len(base[1]): |
| 858 |
return True |
| 859 |
return False |
| 860 |
|
| 861 |
def __copy__(self): |
| 862 |
ans = self.__class__() |
| 863 |
ans.passwd = copy.deepcopy(self.passwd) |
| 864 |
return ans |
| 865 |
|
| 866 |
|
| 867 |
class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr): |
| 868 |
|
| 869 |
def find_user_password(self, realm, authuri): |
| 870 |
user, password = HTTPPasswordMgr.find_user_password(self, realm, |
| 871 |
authuri) |
| 872 |
if user is not None: |
| 873 |
return user, password |
| 874 |
return HTTPPasswordMgr.find_user_password(self, None, authuri) |
| 875 |
|
| 876 |
|
| 877 |
class AbstractBasicAuthHandler: |
| 878 |
|
| 879 |
|
| 880 |
|
| 881 |
|
| 882 |
|
| 883 |
|
| 884 |
rx = re.compile('(?:^|,)' |
| 885 |
'[ \t]*' |
| 886 |
'([^ \t,]+)' |
| 887 |
'[ \t]+' |
| 888 |
|
| 889 |
|
| 890 |
|
| 891 |
'realm=(["\']?)([^"\']*)\\2', |
| 892 |
re.I) |
| 893 |
|
| 894 |
|
| 895 |
|
| 896 |
|
| 897 |
|
| 898 |
def __init__(self, password_mgr=None): |
| 899 |
if password_mgr is None: |
| 900 |
password_mgr = HTTPPasswordMgr() |
| 901 |
self.passwd = password_mgr |
| 902 |
self.add_password = self.passwd.add_password |
| 903 |
|
| 904 |
def http_error_auth_reqed(self, authreq, host, req, headers): |
| 905 |
|
| 906 |
|
| 907 |
|
| 908 |
authreq = headers.get(authreq, None) |
| 909 |
if authreq: |
| 910 |
mo = AbstractBasicAuthHandler.rx.search(authreq) |
| 911 |
if mo: |
| 912 |
scheme, quote, realm = mo.groups() |
| 913 |
if scheme.lower() == 'basic': |
| 914 |
return self.retry_http_basic_auth(host, req, realm) |
| 915 |
|
| 916 |
def retry_http_basic_auth(self, host, req, realm): |
| 917 |
user, pw = self.passwd.find_user_password(realm, host) |
| 918 |
if pw is not None: |
| 919 |
raw = "%s:%s" % (user, pw) |
| 920 |
auth = str('Basic %s' % base64.b64encode( |
| 921 |
raw.encode('utf-8')).strip().decode('ascii')) |
| 922 |
if req.get_header(self.auth_header, None) == auth: |
| 923 |
return None |
| 924 |
newreq = copy.copy(req) |
| 925 |
newreq.add_header(self.auth_header, auth) |
| 926 |
newreq.visit = False |
| 927 |
return self.parent.open(newreq) |
| 928 |
else: |
| 929 |
return None |
| 930 |
|
| 931 |
def __copy__(self): |
| 932 |
return self.__class__(self.passwd.__copy__()) |
| 933 |
|
| 934 |
|
| 935 |
class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler): |
| 936 |
|
| 937 |
auth_header = 'Authorization' |
| 938 |
|
| 939 |
def http_error_401(self, req, fp, code, msg, headers): |
| 940 |
url = req.get_full_url() |
| 941 |
return self.http_error_auth_reqed('www-authenticate', |
| 942 |
url, req, headers) |
| 943 |
|
| 944 |
def __copy__(self): |
| 945 |
return AbstractBasicAuthHandler.__copy__(self) |
| 946 |
|
| 947 |
|
| 948 |
class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler): |
| 949 |
|
| 950 |
auth_header = 'Proxy-authorization' |
| 951 |
|
| 952 |
def http_error_407(self, req, fp, code, msg, headers): |
| 953 |
|
| 954 |
|
| 955 |
|
| 956 |
|
| 957 |
authority = req.get_host() |
| 958 |
return self.http_error_auth_reqed('proxy-authenticate', |
| 959 |
authority, req, headers) |
| 960 |
|
| 961 |
def __copy__(self): |
| 962 |
return AbstractBasicAuthHandler.__copy__(self) |
| 963 |
|
| 964 |
|
| 965 |
randombytes = os.urandom |
| 966 |
|
| 967 |
|
| 968 |
class AbstractDigestAuthHandler: |
| 969 |
|
| 970 |
|
| 971 |
|
| 972 |
|
| 973 |
|
| 974 |
|
| 975 |
|
| 976 |
|
| 977 |
|
| 978 |
|
| 979 |
def __init__(self, passwd=None): |
| 980 |
if passwd is None: |
| 981 |
passwd = HTTPPasswordMgr() |
| 982 |
self.passwd = passwd |
| 983 |
self.add_password = self.passwd.add_password |
| 984 |
self.retried = 0 |
| 985 |
self.nonce_count = 0 |
| 986 |
self.last_nonce = None |
| 987 |
|
| 988 |
def reset_retry_count(self): |
| 989 |
self.retried = 0 |
| 990 |
|
| 991 |
def http_error_auth_reqed(self, auth_header, host, req, headers): |
| 992 |
authreq = headers.get(auth_header, None) |
| 993 |
if self.retried > 5: |
| 994 |
|
| 995 |
|
| 996 |
|
| 997 |
|
| 998 |
|
| 999 |
raise HTTPError(req.get_full_url(), 401, "digest auth failed", |
| 1000 |
headers, None) |
| 1001 |
else: |
| 1002 |
self.retried += 1 |
| 1003 |
if authreq: |
| 1004 |
scheme = authreq.split()[0] |
| 1005 |
if scheme.lower() == 'digest': |
| 1006 |
return self.retry_http_digest_auth(req, authreq) |
| 1007 |
|
| 1008 |
def retry_http_digest_auth(self, req, auth): |
| 1009 |
token, challenge = auth.split(' ', 1) |
| 1010 |
chal = parse_keqv_list(parse_http_list(challenge)) |
| 1011 |
auth = self.get_authorization(req, chal) |
| 1012 |
if auth: |
| 1013 |
auth_val = 'Digest %s' % auth |
| 1014 |
if req.get_header(self.auth_header, None) == auth_val: |
| 1015 |
return None |
| 1016 |
newreq = copy.copy(req) |
| 1017 |
newreq.add_unredirected_header(self.auth_header, auth_val) |
| 1018 |
newreq.visit = False |
| 1019 |
return self.parent.open(newreq) |
| 1020 |
|
| 1021 |
def get_cnonce(self, nonce): |
| 1022 |
|
| 1023 |
|
| 1024 |
|
| 1025 |
|
| 1026 |
|
| 1027 |
dig = sha1_digest("%s:%s:%s:%s" % (self.nonce_count, nonce, |
| 1028 |
time.ctime(), randombytes(8))) |
| 1029 |
return dig[:16] |
| 1030 |
|
| 1031 |
def get_authorization(self, req, chal): |
| 1032 |
try: |
| 1033 |
realm = chal['realm'] |
| 1034 |
nonce = chal['nonce'] |
| 1035 |
qop = chal.get('qop') |
| 1036 |
algorithm = chal.get('algorithm', 'MD5') |
| 1037 |
|
| 1038 |
|
| 1039 |
opaque = chal.get('opaque', None) |
| 1040 |
except KeyError: |
| 1041 |
return None |
| 1042 |
|
| 1043 |
H, KD = self.get_algorithm_impls(algorithm) |
| 1044 |
if H is None: |
| 1045 |
return None |
| 1046 |
|
| 1047 |
user, pw = self.passwd.find_user_password(realm, req.get_full_url()) |
| 1048 |
if user is None: |
| 1049 |
return None |
| 1050 |
|
| 1051 |
|
| 1052 |
if req.has_data(): |
| 1053 |
entdig = self.get_entity_digest(req.get_data(), chal) |
| 1054 |
else: |
| 1055 |
entdig = None |
| 1056 |
|
| 1057 |
A1 = "%s:%s:%s" % (user, realm, pw) |
| 1058 |
A2 = "%s:%s" % (req.get_method(), |
| 1059 |
|
| 1060 |
req.get_selector()) |
| 1061 |
if qop == 'auth': |
| 1062 |
if nonce == self.last_nonce: |
| 1063 |
self.nonce_count += 1 |
| 1064 |
else: |
| 1065 |
self.nonce_count = 1 |
| 1066 |
self.last_nonce = nonce |
| 1067 |
|
| 1068 |
ncvalue = '%08x' % self.nonce_count |
| 1069 |
cnonce = self.get_cnonce(nonce) |
| 1070 |
noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, H(A2)) |
| 1071 |
respdig = KD(H(A1), noncebit) |
| 1072 |
elif qop is None: |
| 1073 |
respdig = KD(H(A1), "%s:%s" % (nonce, H(A2))) |
| 1074 |
else: |
| 1075 |
|
| 1076 |
logger = logging.getLogger("mechanize.auth") |
| 1077 |
logger.info("digest auth auth-int qop is not supported, not " |
| 1078 |
"handling digest authentication") |
| 1079 |
return None |
| 1080 |
|
| 1081 |
|
| 1082 |
|
| 1083 |
base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \ |
| 1084 |
'response="%s"' % (user, realm, nonce, req.get_selector(), |
| 1085 |
respdig) |
| 1086 |
if opaque: |
| 1087 |
base += ', opaque="%s"' % opaque |
| 1088 |
if entdig: |
| 1089 |
base += ', digest="%s"' % entdig |
| 1090 |
base += ', algorithm="%s"' % algorithm |
| 1091 |
if qop: |
| 1092 |
base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce) |
| 1093 |
return base |
| 1094 |
|
| 1095 |
def get_algorithm_impls(self, algorithm): |
| 1096 |
|
| 1097 |
algorithm = algorithm.upper() |
| 1098 |
if algorithm == 'MD5': |
| 1099 |
H = md5_digest |
| 1100 |
elif algorithm == 'SHA': |
| 1101 |
H = sha1_digest |
| 1102 |
|
| 1103 |
KD = lambda s, d: H("%s:%s" % (s, d)) |
| 1104 |
return H, KD |
| 1105 |
|
| 1106 |
def get_entity_digest(self, data, chal): |
| 1107 |
|
| 1108 |
return None |
| 1109 |
|
| 1110 |
def __copy__(self): |
| 1111 |
return self.__class__(self.passwd.__copy__()) |
| 1112 |
|
| 1113 |
|
| 1114 |
class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): |
| 1115 |
"""An authentication protocol defined by RFC 2069 |
| 1116 |
|
| 1117 |
Digest authentication improves on basic authentication because it |
| 1118 |
does not transmit passwords in the clear. |
| 1119 |
""" |
| 1120 |
|
| 1121 |
auth_header = 'Authorization' |
| 1122 |
handler_order = 490 |
| 1123 |
|
| 1124 |
def http_error_401(self, req, fp, code, msg, headers): |
| 1125 |
host = urlparse(req.get_full_url())[1] |
| 1126 |
retry = self.http_error_auth_reqed('www-authenticate', |
| 1127 |
host, req, headers) |
| 1128 |
self.reset_retry_count() |
| 1129 |
return retry |
| 1130 |
|
| 1131 |
def __copy__(self): |
| 1132 |
return AbstractDigestAuthHandler.__copy__(self) |
| 1133 |
|
| 1134 |
|
| 1135 |
class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): |
| 1136 |
|
| 1137 |
auth_header = 'Proxy-Authorization' |
| 1138 |
handler_order = 490 |
| 1139 |
|
| 1140 |
def http_error_407(self, req, fp, code, msg, headers): |
| 1141 |
host = req.get_host() |
| 1142 |
retry = self.http_error_auth_reqed('proxy-authenticate', |
| 1143 |
host, req, headers) |
| 1144 |
self.reset_retry_count() |
| 1145 |
return retry |
| 1146 |
|
| 1147 |
def __copy__(self): |
| 1148 |
return AbstractDigestAuthHandler.__copy__(self) |
| 1149 |
|
| 1150 |
|
| 1151 |
class AbstractHTTPHandler(BaseHandler): |
| 1152 |
|
| 1153 |
def __init__(self, debuglevel=0): |
| 1154 |
self._debuglevel = debuglevel |
| 1155 |
|
| 1156 |
def set_http_debuglevel(self, level): |
| 1157 |
self._debuglevel = level |
| 1158 |
|
| 1159 |
def do_request_(self, request): |
| 1160 |
host = request.get_host() |
| 1161 |
if not host: |
| 1162 |
raise URLError('no host given') |
| 1163 |
|
| 1164 |
if request.has_data(): |
| 1165 |
data = request.get_data() |
| 1166 |
if not request.has_header('Content-type'): |
| 1167 |
request.add_unredirected_header( |
| 1168 |
'Content-type', |
| 1169 |
'application/x-www-form-urlencoded') |
| 1170 |
if not request.has_header('Content-length'): |
| 1171 |
request.add_unredirected_header( |
| 1172 |
'Content-length', '%d' % len(data)) |
| 1173 |
|
| 1174 |
sel_host = host |
| 1175 |
if request.has_proxy(): |
| 1176 |
scheme, sel = splittype(request.get_selector()) |
| 1177 |
sel_host, sel_path = splithost(sel) |
| 1178 |
|
| 1179 |
for name, value in self.parent.addheaders: |
| 1180 |
name = name.capitalize() |
| 1181 |
if not request.has_header(name): |
| 1182 |
request.add_unredirected_header(name, value) |
| 1183 |
if not request.has_header('Host'): |
| 1184 |
request.add_unredirected_header('Host', sel_host) |
| 1185 |
|
| 1186 |
return request |
| 1187 |
|
| 1188 |
def do_open(self, http_class, req): |
| 1189 |
"""Return an addinfourl object for the request, using http_class. |
| 1190 |
|
| 1191 |
http_class must implement the HTTPConnection API from httplib. |
| 1192 |
The addinfourl return value is a file-like object. It also |
| 1193 |
has methods and attributes including: |
| 1194 |
- info(): return a HTTPMessage object for the headers |
| 1195 |
- geturl(): return the original request URL |
| 1196 |
- code: HTTP status code |
| 1197 |
""" |
| 1198 |
host_port = req.get_host() |
| 1199 |
if not host_port: |
| 1200 |
raise URLError('no host given') |
| 1201 |
|
| 1202 |
h = http_class(host_port, timeout=req.timeout) |
| 1203 |
h.set_debuglevel(self._debuglevel) |
| 1204 |
|
| 1205 |
headers = OrderedDict(req.headers) |
| 1206 |
for key, val in iteritems(req.unredirected_hdrs): |
| 1207 |
headers[key] = val |
| 1208 |
|
| 1209 |
|
| 1210 |
|
| 1211 |
|
| 1212 |
|
| 1213 |
|
| 1214 |
headers["Connection"] = "close" |
| 1215 |
|
| 1216 |
|
| 1217 |
if is_py2: |
| 1218 |
headers = OrderedDict( |
| 1219 |
(str(name.title()), str(val)) |
| 1220 |
for name, val in iteritems(headers)) |
| 1221 |
else: |
| 1222 |
headers = OrderedDict( |
| 1223 |
(as_unicode(name, 'iso-8859-1').title(), |
| 1224 |
as_unicode(val, 'iso-8859-1')) |
| 1225 |
for name, val in iteritems(headers)) |
| 1226 |
|
| 1227 |
if req._tunnel_host: |
| 1228 |
set_tunnel = h.set_tunnel if hasattr( |
| 1229 |
h, "set_tunnel") else h._set_tunnel |
| 1230 |
tunnel_headers = {} |
| 1231 |
proxy_auth_hdr = "Proxy-Authorization" |
| 1232 |
if proxy_auth_hdr in headers: |
| 1233 |
tunnel_headers[proxy_auth_hdr] = headers[proxy_auth_hdr] |
| 1234 |
|
| 1235 |
del headers[proxy_auth_hdr] |
| 1236 |
set_tunnel(req._tunnel_host, headers=tunnel_headers) |
| 1237 |
|
| 1238 |
if self.parent.finalize_request_headers is not None: |
| 1239 |
self.parent.finalize_request_headers(req, headers) |
| 1240 |
|
| 1241 |
try: |
| 1242 |
h.request(str(req.get_method()), str(req.get_selector()), req.data, |
| 1243 |
headers) |
| 1244 |
r = h.getresponse() |
| 1245 |
except socket.error as err: |
| 1246 |
raise URLError(err) |
| 1247 |
|
| 1248 |
|
| 1249 |
|
| 1250 |
fp = create_readline_wrapper(r) |
| 1251 |
|
| 1252 |
resp = closeable_response( |
| 1253 |
fp, r.msg, req.get_full_url(), r.status, r.reason, |
| 1254 |
getattr(r, 'version', None)) |
| 1255 |
return resp |
| 1256 |
|
| 1257 |
def __copy__(self): |
| 1258 |
return self.__class__(self._debuglevel) |
| 1259 |
|
| 1260 |
|
| 1261 |
class HTTPHandler(AbstractHTTPHandler): |
| 1262 |
|
| 1263 |
def http_open(self, req): |
| 1264 |
return self.do_open(HTTPConnection, req) |
| 1265 |
|
| 1266 |
http_request = AbstractHTTPHandler.do_request_ |
| 1267 |
|
| 1268 |
|
| 1269 |
class HTTPSHandler(AbstractHTTPHandler): |
| 1270 |
|
| 1271 |
def __init__(self, client_cert_manager=None): |
| 1272 |
AbstractHTTPHandler.__init__(self) |
| 1273 |
self.client_cert_manager = client_cert_manager |
| 1274 |
self.ssl_context = None |
| 1275 |
|
| 1276 |
def https_open(self, req): |
| 1277 |
key_file = cert_file = None |
| 1278 |
if self.client_cert_manager is not None: |
| 1279 |
key_file, cert_file = self.client_cert_manager.find_key_cert( |
| 1280 |
req.get_full_url()) |
| 1281 |
if sys.version_info > (3, 5): |
| 1282 |
import ssl |
| 1283 |
ctx = self.ssl_context or ssl.create_default_context() |
| 1284 |
if cert_file: |
| 1285 |
ctx.load_cert_chain(cert_file, key_file) |
| 1286 |
conn_factory = partial(HTTPSConnection, context=ctx) |
| 1287 |
else: |
| 1288 |
if self.ssl_context is None: |
| 1289 |
conn_factory = partial( |
| 1290 |
HTTPSConnection, key_file=key_file, |
| 1291 |
cert_file=cert_file) |
| 1292 |
else: |
| 1293 |
conn_factory = partial( |
| 1294 |
HTTPSConnection, key_file=key_file, |
| 1295 |
cert_file=cert_file, context=self.ssl_context) |
| 1296 |
return self.do_open(conn_factory, req) |
| 1297 |
|
| 1298 |
https_request = AbstractHTTPHandler.do_request_ |
| 1299 |
|
| 1300 |
def __copy__(self): |
| 1301 |
ans = self.__class__(self.client_cert_manager) |
| 1302 |
ans._debuglevel = self._debuglevel |
| 1303 |
ans.ssl_context = self.ssl_context |
| 1304 |
return ans |
| 1305 |
|
| 1306 |
|
| 1307 |
class HTTPCookieProcessor(BaseHandler): |
| 1308 |
"""Handle HTTP cookies. |
| 1309 |
|
| 1310 |
Public attributes: |
| 1311 |
|
| 1312 |
cookiejar: CookieJar instance |
| 1313 |
|
| 1314 |
""" |
| 1315 |
|
| 1316 |
def __init__(self, cookiejar=None): |
| 1317 |
if cookiejar is None: |
| 1318 |
cookiejar = CookieJar() |
| 1319 |
self.cookiejar = cookiejar |
| 1320 |
|
| 1321 |
def http_request(self, request): |
| 1322 |
self.cookiejar.add_cookie_header(request) |
| 1323 |
return request |
| 1324 |
|
| 1325 |
def http_response(self, request, response): |
| 1326 |
self.cookiejar.extract_cookies(response, request) |
| 1327 |
return response |
| 1328 |
|
| 1329 |
def __copy__(self): |
| 1330 |
return self.__class__(self.cookiejar) |
| 1331 |
|
| 1332 |
https_request = http_request |
| 1333 |
https_response = http_response |
| 1334 |
|
| 1335 |
|
| 1336 |
class UnknownHandler(BaseHandler): |
| 1337 |
|
| 1338 |
def unknown_open(self, req): |
| 1339 |
type = req.get_type() |
| 1340 |
raise URLError('unknown url type: %s' % type) |
| 1341 |
|
| 1342 |
|
| 1343 |
def parse_keqv_list(ln): |
| 1344 |
"""Parse list of key=value strings where keys are not duplicated.""" |
| 1345 |
parsed = {} |
| 1346 |
for elt in ln: |
| 1347 |
k, v = elt.split('=', 1) |
| 1348 |
if v[0:1] == '"' and v[-1:] == '"': |
| 1349 |
v = v[1:-1] |
| 1350 |
parsed[k] = v |
| 1351 |
return parsed |
| 1352 |
|
| 1353 |
|
| 1354 |
def parse_http_list(s): |
| 1355 |
"""Parse lists as described by RFC 2068 Section 2. |
| 1356 |
|
| 1357 |
In particular, parse comma-separated lists where the elements of |
| 1358 |
the list may include quoted-strings. A quoted-string could |
| 1359 |
contain a comma. A non-quoted string could have quotes in the |
| 1360 |
middle. Neither commas nor quotes count if they are escaped. |
| 1361 |
Only double-quotes count, not single-quotes. |
| 1362 |
""" |
| 1363 |
res = [] |
| 1364 |
part = '' |
| 1365 |
|
| 1366 |
escape = quote = False |
| 1367 |
for cur in s: |
| 1368 |
if escape: |
| 1369 |
part += cur |
| 1370 |
escape = False |
| 1371 |
continue |
| 1372 |
if quote: |
| 1373 |
if cur == '\\': |
| 1374 |
escape = True |
| 1375 |
continue |
| 1376 |
elif cur == '"': |
| 1377 |
quote = False |
| 1378 |
part += cur |
| 1379 |
continue |
| 1380 |
|
| 1381 |
if cur == ',': |
| 1382 |
res.append(part) |
| 1383 |
part = '' |
| 1384 |
continue |
| 1385 |
|
| 1386 |
if cur == '"': |
| 1387 |
quote = True |
| 1388 |
|
| 1389 |
part += cur |
| 1390 |
|
| 1391 |
|
| 1392 |
if part: |
| 1393 |
res.append(part) |
| 1394 |
|
| 1395 |
return list(filter(None, (part_.strip() for part_ in res))) |
| 1396 |
|
| 1397 |
|
| 1398 |
class FileHandler(BaseHandler): |
| 1399 |
|
| 1400 |
|
| 1401 |
def file_open(self, req): |
| 1402 |
url = req.get_selector() |
| 1403 |
if url[:2] == '//' and url[2:3] != '/': |
| 1404 |
req.type = 'ftp' |
| 1405 |
return self.parent.open(req) |
| 1406 |
else: |
| 1407 |
return self.open_local_file(req) |
| 1408 |
|
| 1409 |
|
| 1410 |
names = None |
| 1411 |
|
| 1412 |
def get_names(self): |
| 1413 |
if FileHandler.names is None: |
| 1414 |
try: |
| 1415 |
FileHandler.names = (socket.gethostbyname('localhost'), |
| 1416 |
socket.gethostbyname(socket.gethostname()) |
| 1417 |
) |
| 1418 |
except socket.gaierror: |
| 1419 |
FileHandler.names = (socket.gethostbyname('localhost'),) |
| 1420 |
return FileHandler.names |
| 1421 |
|
| 1422 |
|
| 1423 |
def open_local_file(self, req): |
| 1424 |
import email.utils as emailutils |
| 1425 |
import mimetypes |
| 1426 |
host = req.get_host() |
| 1427 |
file = req.get_selector() |
| 1428 |
try: |
| 1429 |
localfile = url2pathname(file) |
| 1430 |
except IOError as err: |
| 1431 |
|
| 1432 |
raise URLError(err) |
| 1433 |
try: |
| 1434 |
stats = os.stat(localfile) |
| 1435 |
size = stats.st_size |
| 1436 |
modified = emailutils.formatdate(stats.st_mtime, usegmt=True) |
| 1437 |
mtype = mimetypes.guess_type(file)[0] |
| 1438 |
headers = create_response_info(BytesIO( |
| 1439 |
('Content-type: %s\nContent-length: %d\nLast-modified: %s\n' % |
| 1440 |
(mtype or 'text/plain', size, modified)).encode( |
| 1441 |
'iso-8859-1'))) |
| 1442 |
if host: |
| 1443 |
host, port = splitport(host) |
| 1444 |
if not host or ( |
| 1445 |
not port and socket.gethostbyname(host) in self.get_names() |
| 1446 |
): |
| 1447 |
fp = open(localfile, 'rb') |
| 1448 |
return closeable_response(fp, headers, 'file:' + file) |
| 1449 |
except OSError as msg: |
| 1450 |
|
| 1451 |
raise URLError(msg) |
| 1452 |
raise URLError('file not on local host') |
| 1453 |
|
| 1454 |
|
| 1455 |
class FTPHandler(BaseHandler): |
| 1456 |
|
| 1457 |
def ftp_open(self, req): |
| 1458 |
import ftplib |
| 1459 |
import mimetypes |
| 1460 |
host = req.get_host() |
| 1461 |
if not host: |
| 1462 |
raise URLError('ftp error: no host given') |
| 1463 |
host, port = splitport(host) |
| 1464 |
if port is None: |
| 1465 |
port = ftplib.FTP_PORT |
| 1466 |
else: |
| 1467 |
port = int(port) |
| 1468 |
|
| 1469 |
|
| 1470 |
user, host = splituser(host) |
| 1471 |
if user: |
| 1472 |
user, passwd = splitpasswd(user) |
| 1473 |
else: |
| 1474 |
passwd = None |
| 1475 |
host = unquote(host) |
| 1476 |
user = unquote(user or '') |
| 1477 |
passwd = unquote(passwd or '') |
| 1478 |
|
| 1479 |
try: |
| 1480 |
host = socket.gethostbyname(host) |
| 1481 |
except socket.error as msg: |
| 1482 |
raise URLError(msg) |
| 1483 |
path, attrs = splitattr(req.get_selector()) |
| 1484 |
dirs = path.split('/') |
| 1485 |
dirs = list(map(unquote, dirs)) |
| 1486 |
dirs, file = dirs[:-1], dirs[-1] |
| 1487 |
if dirs and not dirs[0]: |
| 1488 |
dirs = dirs[1:] |
| 1489 |
try: |
| 1490 |
fw = self.connect_ftp(user, passwd, host, port, dirs, req.timeout) |
| 1491 |
type = file and 'I' or 'D' |
| 1492 |
for attr in attrs: |
| 1493 |
attr, value = splitvalue(attr) |
| 1494 |
if attr.lower() == 'type' and \ |
| 1495 |
value in ('a', 'A', 'i', 'I', 'd', 'D'): |
| 1496 |
type = value.upper() |
| 1497 |
fp, retrlen = fw.retrfile(file, type) |
| 1498 |
headers = "" |
| 1499 |
mtype = mimetypes.guess_type(req.get_full_url())[0] |
| 1500 |
if mtype: |
| 1501 |
headers += "Content-type: %s\n" % mtype |
| 1502 |
if retrlen is not None and retrlen >= 0: |
| 1503 |
headers += "Content-length: %d\n" % retrlen |
| 1504 |
sf = BytesIO(headers.encode('iso-8859-1')) |
| 1505 |
headers = create_response_info(sf) |
| 1506 |
return closeable_response(fp, headers, req.get_full_url()) |
| 1507 |
except ftplib.all_errors as msg: |
| 1508 |
raise_with_traceback(URLError('ftp error: %s' % msg)) |
| 1509 |
|
| 1510 |
def connect_ftp(self, user, passwd, host, port, dirs, timeout): |
| 1511 |
try: |
| 1512 |
fw = ftpwrapper(user, passwd, host, port, dirs, timeout) |
| 1513 |
except TypeError: |
| 1514 |
|
| 1515 |
fw = ftpwrapper(user, passwd, host, port, dirs) |
| 1516 |
|
| 1517 |
return fw |
| 1518 |
|
| 1519 |
|
| 1520 |
class CacheFTPHandler(FTPHandler): |
| 1521 |
|
| 1522 |
|
| 1523 |
|
| 1524 |
def __init__(self): |
| 1525 |
self.cache = {} |
| 1526 |
self.timeout = {} |
| 1527 |
self.soonest = 0 |
| 1528 |
self.delay = 60 |
| 1529 |
self.max_conns = 16 |
| 1530 |
|
| 1531 |
def setTimeout(self, t): |
| 1532 |
self.delay = t |
| 1533 |
|
| 1534 |
def setMaxConns(self, m): |
| 1535 |
self.max_conns = m |
| 1536 |
|
| 1537 |
def connect_ftp(self, user, passwd, host, port, dirs, timeout): |
| 1538 |
key = user, host, port, '/'.join(dirs), timeout |
| 1539 |
if key in self.cache: |
| 1540 |
self.timeout[key] = time.time() + self.delay |
| 1541 |
else: |
| 1542 |
self.cache[key] = ftpwrapper( |
| 1543 |
user, passwd, host, port, dirs, timeout) |
| 1544 |
self.timeout[key] = time.time() + self.delay |
| 1545 |
self.check_cache() |
| 1546 |
return self.cache[key] |
| 1547 |
|
| 1548 |
def check_cache(self): |
| 1549 |
|
| 1550 |
t = time.time() |
| 1551 |
if self.soonest <= t: |
| 1552 |
for k, v in iteritems(self.timeout): |
| 1553 |
if v < t: |
| 1554 |
self.cache[k].close() |
| 1555 |
del self.cache[k] |
| 1556 |
del self.timeout[k] |
| 1557 |
self.soonest = min(self.timeout.values()) |
| 1558 |
|
| 1559 |
|
| 1560 |
if len(self.cache) == self.max_conns: |
| 1561 |
for k, v in iteritems(self.timeout): |
| 1562 |
if v == self.soonest: |
| 1563 |
del self.cache[k] |
| 1564 |
del self.timeout[k] |
| 1565 |
break |
| 1566 |
self.soonest = min(self.timeout.values()) |