Debian Codegraph @

lib-python/3/http/client.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 r"""HTTP/1.1 client library
2
3 <intro stuff goes here>
4 <other stuff, too>
5
6 HTTPConnection goes through a number of "states", which define when a client
7 may legally make another request or fetch the response for a particular
8 request. This diagram details these state transitions:
9
10 (null)
11 |
12 | HTTPConnection()
13 v
14 Idle
15 |
16 | putrequest()
17 v
18 Request-started
19 |
20 | ( putheader() )* endheaders()
21 v
22 Request-sent
23 |\_____________________________
24 | | getresponse() raises
25 | response = getresponse() | ConnectionError
26 v v
27 Unread-response Idle
28 [Response-headers-read]
29 |\____________________
30 | |
31 | response.read() | putrequest()
32 v v
33 Idle Req-started-unread-response
34 ______/|
35 / |
36 response.read() | | ( putheader() )* endheaders()
37 v v
38 Request-started Req-sent-unread-response
39 |
40 | response.read()
41 v
42 Request-sent
43
44 This diagram presents the following rules:
45 -- a second request may not be started until {response-headers-read}
46 -- a response [object] cannot be retrieved until {request-sent}
47 -- there is no differentiation between an unread response body and a
48 partially read response body
49
50 Note: this enforcement is applied by the HTTPConnection class. The
51 HTTPResponse class does not enforce this state machine, which
52 implies sophisticated clients may accelerate the request/response
53 pipeline. Caution should be taken, though: accelerating the states
54 beyond the above pattern may imply knowledge of the server's
55 connection-close behavior for certain requests. For example, it
56 is impossible to tell whether the server will close the connection
57 UNTIL the response headers have been read; this means that further
58 requests cannot be placed into the pipeline until it is known that
59 the server will NOT be closing the connection.
60
61 Logical State __state __response
62 ------------- ------- ----------
63 Idle _CS_IDLE None
64 Request-started _CS_REQ_STARTED None
65 Request-sent _CS_REQ_SENT None
66 Unread-response _CS_IDLE <response_class>
67 Req-started-unread-response _CS_REQ_STARTED <response_class>
68 Req-sent-unread-response _CS_REQ_SENT <response_class>
69 """
70
71 import email.parser
72 import email.message
73 import errno
74 import http
75 import io
76 import re
77 import socket
78 import sys
79 import collections.abc
80 from urllib.parse import urlsplit
81
82 # HTTPMessage, parse_headers(), and the HTTP status code constants are
83 # intentionally omitted for simplicity
84 __all__ = ["HTTPResponse", "HTTPConnection",
85 "HTTPException", "NotConnected", "UnknownProtocol",
86 "UnknownTransferEncoding", "UnimplementedFileMode",
87 "IncompleteRead", "InvalidURL", "ImproperConnectionState",
88 "CannotSendRequest", "CannotSendHeader", "ResponseNotReady",
89 "BadStatusLine", "LineTooLong", "RemoteDisconnected", "error",
90 "responses"]
91
92 HTTP_PORT = 80
93 HTTPS_PORT = 443
94
95 _UNKNOWN = 'UNKNOWN'
96
97 # connection states
98 _CS_IDLE = 'Idle'
99 _CS_REQ_STARTED = 'Request-started'
100 _CS_REQ_SENT = 'Request-sent'
101
102
103 # hack to maintain backwards compatibility
104 globals().update(http.HTTPStatus.__members__)
105
106 # another hack to maintain backwards compatibility
107 # Mapping status codes to official W3C names
108 responses = {v: v.phrase for v in http.HTTPStatus.__members__.values()}
109
110 # maximal line length when calling readline().
111 _MAXLINE = 65536
112 _MAXHEADERS = 100
113
114 # Data larger than this will be read in chunks, to prevent extreme
115 # overallocation.
116 _MIN_READ_BUF_SIZE = 1 << 20
117
118
119 # Header name/value ABNF (http://tools.ietf.org/html/rfc7230#section-3.2)
120 #
121 # VCHAR = %x21-7E
122 # obs-text = %x80-FF
123 # header-field = field-name ":" OWS field-value OWS
124 # field-name = token
125 # field-value = *( field-content / obs-fold )
126 # field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
127 # field-vchar = VCHAR / obs-text
128 #
129 # obs-fold = CRLF 1*( SP / HTAB )
130 # ; obsolete line folding
131 # ; see Section 3.2.4
132
133 # token = 1*tchar
134 #
135 # tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
136 # / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
137 # / DIGIT / ALPHA
138 # ; any VCHAR, except delimiters
139 #
140 # VCHAR defined in http://tools.ietf.org/html/rfc5234#appendix-B.1
141
142 # the patterns for both name and value are more lenient than RFC
143 # definitions to allow for backwards compatibility
144 _is_legal_header_name = re.compile(rb'[^:\s][^:\r\n]*').fullmatch
145 _is_illegal_header_value = re.compile(rb'\n(?![ \t])|\r(?![ \t\n])').search
146
147 # These characters are not allowed within HTTP URL paths.
148 # See https://tools.ietf.org/html/rfc3986#section-3.3 and the
149 # https://tools.ietf.org/html/rfc3986#appendix-A pchar definition.
150 # Prevents CVE-2019-9740. Includes control characters such as \r\n.
151 # We don't restrict chars above \x7f as putrequest() limits us to ASCII.
152 _contains_disallowed_url_pchar_re = re.compile('[\x00-\x20\x7f]')
153 # Arguably only these _should_ allowed:
154 # _is_allowed_url_pchars_re = re.compile(r"^[/!$&'()*+,;=:@%a-zA-Z0-9._~-]+$")
155 # We are more lenient for assumed real world compatibility purposes.
156
157 # These characters are not allowed within HTTP method names
158 # to prevent http header injection.
159 _contains_disallowed_method_pchar_re = re.compile('[\x00-\x1f]')
160
161 # We always set the Content-Length header for these methods because some
162 # servers will otherwise respond with a 411
163 _METHODS_EXPECTING_BODY = {'PATCH', 'POST', 'PUT'}
164
165
166 def _encode(data, name='data'):
167 """Call data.encode("latin-1") but show a better error message."""
168 try:
169 return data.encode("latin-1")
170 except UnicodeEncodeError as err:
171 raise UnicodeEncodeError(
172 err.encoding,
173 err.object,
174 err.start,
175 err.end,
176 "%s (%.20r) is not valid Latin-1. Use %s.encode('utf-8') "
177 "if you want to send it encoded in UTF-8." %
178 (name.title(), data[err.start:err.end], name)) from None
179
180 def _strip_ipv6_iface(enc_name: bytes) -> bytes:
181 """Remove interface scope from IPv6 address."""
182 enc_name, percent, _ = enc_name.partition(b"%")
183 if percent:
184 assert enc_name.startswith(b'['), enc_name
185 enc_name += b']'
186 return enc_name
187
188 class HTTPMessage(email.message.Message):
189 # XXX The only usage of this method is in
190 # http.server.CGIHTTPRequestHandler. Maybe move the code there so
191 # that it doesn't need to be part of the public API. The API has
192 # never been defined so this could cause backwards compatibility
193 # issues.
194
195 def getallmatchingheaders(self, name):
196 """Find all header lines matching a given header name.
197
198 Look through the list of headers and find all lines matching a given
199 header name (and their continuation lines). A list of the lines is
200 returned, without interpretation. If the header does not occur, an
201 empty list is returned. If the header occurs multiple times, all
202 occurrences are returned. Case is not important in the header name.
203
204 """
205 name = name.lower() + ':'
206 n = len(name)
207 lst = []
208 hit = 0
209 for line in self.keys():
210 if line[:n].lower() == name:
211 hit = 1
212 elif not line[:1].isspace():
213 hit = 0
214 if hit:
215 lst.append(line)
216 return lst
217
218 def _read_headers(fp):
219 """Reads potential header lines into a list from a file pointer.
220
221 Length of line is limited by _MAXLINE, and number of
222 headers is limited by _MAXHEADERS.
223 """
224 headers = []
225 while True:
226 line = fp.readline(_MAXLINE + 1)
227 if len(line) > _MAXLINE:
228 raise LineTooLong("header line")
229 headers.append(line)
230 if len(headers) > _MAXHEADERS:
231 raise HTTPException("got more than %d headers" % _MAXHEADERS)
232 if line in (b'\r\n', b'\n', b''):
233 break
234 return headers
235
236 def parse_headers(fp, _class=HTTPMessage):
237 """Parses only RFC2822 headers from a file pointer.
238
239 email Parser wants to see strings rather than bytes.
240 But a TextIOWrapper around self.rfile would buffer too many bytes
241 from the stream, bytes which we later need to read as bytes.
242 So we read the correct bytes here, as bytes, for email Parser
243 to parse.
244
245 """
246 headers = _read_headers(fp)
247 hstring = b''.join(headers).decode('iso-8859-1')
248 return email.parser.Parser(_class=_class).parsestr(hstring)
249
250
251 class HTTPResponse(io.BufferedIOBase):
252
253 # See RFC 2616 sec 19.6 and RFC 1945 sec 6 for details.
254
255 # The bytes from the socket object are iso-8859-1 strings.
256 # See RFC 2616 sec 2.2 which notes an exception for MIME-encoded
257 # text following RFC 2047. The basic status line parsing only
258 # accepts iso-8859-1.
259
260 def __init__(self, sock, debuglevel=0, method=None, url=None):
261 # If the response includes a content-length header, we need to
262 # make sure that the client doesn't read more than the
263 # specified number of bytes. If it does, it will block until
264 # the server times out and closes the connection. This will
265 # happen if a self.fp.read() is done (without a size) whether
266 # self.fp is buffered or not. So, no self.fp.read() by
267 # clients unless they know what they are doing.
268 self.fp = sock.makefile("rb")
269 self.debuglevel = debuglevel
270 self._method = method
271
272 # The HTTPResponse object is returned via urllib. The clients
273 # of http and urllib expect different attributes for the
274 # headers. headers is used here and supports urllib. msg is
275 # provided as a backwards compatibility layer for http
276 # clients.
277
278 self.headers = self.msg = None
279
280 # from the Status-Line of the response
281 self.version = _UNKNOWN # HTTP-Version
282 self.status = _UNKNOWN # Status-Code
283 self.reason = _UNKNOWN # Reason-Phrase
284
285 self.chunked = _UNKNOWN # is "chunked" being used?
286 self.chunk_left = _UNKNOWN # bytes left to read in current chunk
287 self.length = _UNKNOWN # number of bytes left in response
288 self.will_close = _UNKNOWN # conn will close at end of response
289
290 def _read_status(self):
291 line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
292 if len(line) > _MAXLINE:
293 raise LineTooLong("status line")
294 if self.debuglevel > 0:
295 print("reply:", repr(line))
296 if not line:
297 # Presumably, the server closed the connection before
298 # sending a valid response.
299 raise RemoteDisconnected("Remote end closed connection without"
300 " response")
301 try:
302 version, status, reason = line.split(None, 2)
303 except ValueError:
304 try:
305 version, status = line.split(None, 1)
306 reason = ""
307 except ValueError:
308 # empty version will cause next test to fail.
309 version = ""
310 if not version.startswith("HTTP/"):
311 self._close_conn()
312 raise BadStatusLine(line)
313
314 # The status code is a three-digit number
315 try:
316 status = int(status)
317 if status < 100 or status > 999:
318 raise BadStatusLine(line)
319 except ValueError:
320 raise BadStatusLine(line)
321 return version, status, reason
322
323 def begin(self):
324 if self.headers is not None:
325 # we've already started reading the response
326 return
327
328 # read until we get a non-100 response
329 while True:
330 version, status, reason = self._read_status()
331 if status != CONTINUE:
332 break
333 # skip the header from the 100 response
334 skipped_headers = _read_headers(self.fp)
335 if self.debuglevel > 0:
336 print("headers:", skipped_headers)
337 del skipped_headers
338
339 self.code = self.status = status
340 self.reason = reason.strip()
341 if version in ("HTTP/1.0", "HTTP/0.9"):
342 # Some servers might still return "0.9", treat it as 1.0 anyway
343 self.version = 10
344 elif version.startswith("HTTP/1."):
345 self.version = 11 # use HTTP/1.1 code for HTTP/1.x where x>=1
346 else:
347 raise UnknownProtocol(version)
348
349 self.headers = self.msg = parse_headers(self.fp)
350
351 if self.debuglevel > 0:
352 for hdr, val in self.headers.items():
353 print("header:", hdr + ":", val)
354
355 # are we using the chunked-style of transfer encoding?
356 tr_enc = self.headers.get("transfer-encoding")
357 if tr_enc and tr_enc.lower() == "chunked":
358 self.chunked = True
359 self.chunk_left = None
360 else:
361 self.chunked = False
362
363 # will the connection close at the end of the response?
364 self.will_close = self._check_close()
365
366 # do we have a Content-Length?
367 # NOTE: RFC 2616, S4.4, #3 says we ignore this if tr_enc is "chunked"
368 self.length = None
369 length = self.headers.get("content-length")
370 if length and not self.chunked:
371 try:
372 self.length = int(length)
373 except ValueError:
374 self.length = None
375 else:
376 if self.length < 0: # ignore nonsensical negative lengths
377 self.length = None
378 else:
379 self.length = None
380
381 # does the body have a fixed length? (of zero)
382 if (status == NO_CONTENT or status == NOT_MODIFIED or
383 100 <= status < 200 or # 1xx codes
384 self._method == "HEAD"):
385 self.length = 0
386
387 # if the connection remains open, and we aren't using chunked, and
388 # a content-length was not provided, then assume that the connection
389 # WILL close.
390 if (not self.will_close and
391 not self.chunked and
392 self.length is None):
393 self.will_close = True
394
395 def _check_close(self):
396 conn = self.headers.get("connection")
397 if self.version == 11:
398 # An HTTP/1.1 proxy is assumed to stay open unless
399 # explicitly closed.
400 if conn and "close" in conn.lower():
401 return True
402 return False
403
404 # Some HTTP/1.0 implementations have support for persistent
405 # connections, using rules different than HTTP/1.1.
406
407 # For older HTTP, Keep-Alive indicates persistent connection.
408 if self.headers.get("keep-alive"):
409 return False
410
411 # At least Akamai returns a "Connection: Keep-Alive" header,
412 # which was supposed to be sent by the client.
413 if conn and "keep-alive" in conn.lower():
414 return False
415
416 # Proxy-Connection is a netscape hack.
417 pconn = self.headers.get("proxy-connection")
418 if pconn and "keep-alive" in pconn.lower():
419 return False
420
421 # otherwise, assume it will close
422 return True
423
424 def _close_conn(self):
425 fp = self.fp
426 self.fp = None
427 fp.close()
428
429 def close(self):
430 try:
431 super().close() # set "closed" flag
432 finally:
433 if self.fp:
434 self._close_conn()
435
436 # These implementations are for the benefit of io.BufferedReader.
437
438 # XXX This class should probably be revised to act more like
439 # the "raw stream" that BufferedReader expects.
440
441 def flush(self):
442 super().flush()
443 if self.fp:
444 self.fp.flush()
445
446 def readable(self):
447 """Always returns True"""
448 return True
449
450 # End of "raw stream" methods
451
452 def isclosed(self):
453 """True if the connection is closed."""
454 # NOTE: it is possible that we will not ever call self.close(). This
455 # case occurs when will_close is TRUE, length is None, and we
456 # read up to the last byte, but NOT past it.
457 #
458 # IMPLIES: if will_close is FALSE, then self.close() will ALWAYS be
459 # called, meaning self.isclosed() is meaningful.
460 return self.fp is None
461
462 def read(self, amt=None):
463 """Read and return the response body, or up to the next amt bytes."""
464 if self.fp is None:
465 return b""
466
467 if self._method == "HEAD":
468 self._close_conn()
469 return b""
470
471 if self.chunked:
472 return self._read_chunked(amt)
473
474 if amt is not None:
475 if self.length is not None and amt > self.length:
476 # clip the read to the "end of response"
477 amt = self.length
478 s = self.fp.read(amt)
479 if not s and amt:
480 # Ideally, we would raise IncompleteRead if the content-length
481 # wasn't satisfied, but it might break compatibility.
482 self._close_conn()
483 elif self.length is not None:
484 self.length -= len(s)
485 if not self.length:
486 self._close_conn()
487 return s
488 else:
489 # Amount is not given (unbounded read) so we must check self.length
490 if self.length is None:
491 s = self.fp.read()
492 else:
493 try:
494 s = self._safe_read(self.length)
495 except IncompleteRead:
496 self._close_conn()
497 raise
498 self.length = 0
499 self._close_conn() # we read everything
500 return s
501
502 def readinto(self, b):
503 """Read up to len(b) bytes into bytearray b and return the number
504 of bytes read.
505 """
506
507 if self.fp is None:
508 return 0
509
510 if self._method == "HEAD":
511 self._close_conn()
512 return 0
513
514 if self.chunked:
515 return self._readinto_chunked(b)
516
517 if self.length is not None:
518 if len(b) > self.length:
519 # clip the read to the "end of response"
520 b = memoryview(b)[0:self.length]
521
522 # we do not use _safe_read() here because this may be a .will_close
523 # connection, and the user is reading more bytes than will be provided
524 # (for example, reading in 1k chunks)
525 n = self.fp.readinto(b)
526 if not n and b:
527 # Ideally, we would raise IncompleteRead if the content-length
528 # wasn't satisfied, but it might break compatibility.
529 self._close_conn()
530 elif self.length is not None:
531 self.length -= n
532 if not self.length:
533 self._close_conn()
534 return n
535
536 def _read_next_chunk_size(self):
537 # Read the next chunk size from the file
538 line = self.fp.readline(_MAXLINE + 1)
539 if len(line) > _MAXLINE:
540 raise LineTooLong("chunk size")
541 i = line.find(b";")
542 if i >= 0:
543 line = line[:i] # strip chunk-extensions
544 try:
545 return int(line, 16)
546 except ValueError:
547 # close the connection as protocol synchronisation is
548 # probably lost
549 self._close_conn()
550 raise
551
552 def _read_and_discard_trailer(self):
553 # read and discard trailer up to the CRLF terminator
554 ### note: we shouldn't have any trailers!
555 while True:
556 line = self.fp.readline(_MAXLINE + 1)
557 if len(line) > _MAXLINE:
558 raise LineTooLong("trailer line")
559 if not line:
560 # a vanishingly small number of sites EOF without
561 # sending the trailer
562 break
563 if line in (b'\r\n', b'\n', b''):
564 break
565
566 def _get_chunk_left(self):
567 # return self.chunk_left, reading a new chunk if necessary.
568 # chunk_left == 0: at the end of the current chunk, need to close it
569 # chunk_left == None: No current chunk, should read next.
570 # This function returns non-zero or None if the last chunk has
571 # been read.
572 chunk_left = self.chunk_left
573 if not chunk_left: # Can be 0 or None
574 if chunk_left is not None:
575 # We are at the end of chunk, discard chunk end
576 self._safe_read(2) # toss the CRLF at the end of the chunk
577 try:
578 chunk_left = self._read_next_chunk_size()
579 except ValueError:
580 raise IncompleteRead(b'')
581 if chunk_left == 0:
582 # last chunk: 1*("0") [ chunk-extension ] CRLF
583 self._read_and_discard_trailer()
584 # we read everything; close the "file"
585 self._close_conn()
586 chunk_left = None
587 self.chunk_left = chunk_left
588 return chunk_left
589
590 def _read_chunked(self, amt=None):
591 assert self.chunked != _UNKNOWN
592 value = []
593 try:
594 while True:
595 chunk_left = self._get_chunk_left()
596 if chunk_left is None:
597 break
598
599 if amt is not None and amt <= chunk_left:
600 value.append(self._safe_read(amt))
601 self.chunk_left = chunk_left - amt
602 break
603
604 value.append(self._safe_read(chunk_left))
605 if amt is not None:
606 amt -= chunk_left
607 self.chunk_left = 0
608 return b''.join(value)
609 except IncompleteRead as exc:
610 raise IncompleteRead(b''.join(value)) from exc
611
612 def _readinto_chunked(self, b):
613 assert self.chunked != _UNKNOWN
614 total_bytes = 0
615 mvb = memoryview(b)
616 try:
617 while True:
618 chunk_left = self._get_chunk_left()
619 if chunk_left is None:
620 return total_bytes
621
622 if len(mvb) <= chunk_left:
623 n = self._safe_readinto(mvb)
624 self.chunk_left = chunk_left - n
625 return total_bytes + n
626
627 temp_mvb = mvb[:chunk_left]
628 n = self._safe_readinto(temp_mvb)
629 mvb = mvb[n:]
630 total_bytes += n
631 self.chunk_left = 0
632
633 except IncompleteRead:
634 raise IncompleteRead(bytes(b[0:total_bytes]))
635
636 def _safe_read(self, amt):
637 """Read the number of bytes requested.
638
639 This function should be used when <amt> bytes "should" be present for
640 reading. If the bytes are truly not available (due to EOF), then the
641 IncompleteRead exception can be used to detect the problem.
642 """
643 cursize = min(amt, _MIN_READ_BUF_SIZE)
644 data = self.fp.read(cursize)
645 if len(data) >= amt:
646 return data
647 if len(data) < cursize:
648 raise IncompleteRead(data, amt - len(data))
649
650 data = io.BytesIO(data)
651 data.seek(0, 2)
652 while True:
653 # This is a geometric increase in read size (never more than
654 # doubling out the current length of data per loop iteration).
655 delta = min(cursize, amt - cursize)
656 data.write(self.fp.read(delta))
657 if data.tell() >= amt:
658 return data.getvalue()
659 cursize += delta
660 if data.tell() < cursize:
661 raise IncompleteRead(data.getvalue(), amt - data.tell())
662
663 def _safe_readinto(self, b):
664 """Same as _safe_read, but for reading into a buffer."""
665 amt = len(b)
666 n = self.fp.readinto(b)
667 if n < amt:
668 raise IncompleteRead(bytes(b[:n]), amt-n)
669 return n
670
671 def read1(self, n=-1):
672 """Read with at most one underlying system call. If at least one
673 byte is buffered, return that instead.
674 """
675 if self.fp is None or self._method == "HEAD":
676 return b""
677 if self.chunked:
678 return self._read1_chunked(n)
679 if self.length is not None and (n < 0 or n > self.length):
680 n = self.length
681 result = self.fp.read1(n)
682 if not result and n:
683 self._close_conn()
684 elif self.length is not None:
685 self.length -= len(result)
686 if not self.length:
687 self._close_conn()
688 return result
689
690 def peek(self, n=-1):
691 # Having this enables IOBase.readline() to read more than one
692 # byte at a time
693 if self.fp is None or self._method == "HEAD":
694 return b""
695 if self.chunked:
696 return self._peek_chunked(n)
697 return self.fp.peek(n)
698
699 def readline(self, limit=-1):
700 if self.fp is None or self._method == "HEAD":
701 return b""
702 if self.chunked:
703 # Fallback to IOBase readline which uses peek() and read()
704 return super().readline(limit)
705 if self.length is not None and (limit < 0 or limit > self.length):
706 limit = self.length
707 result = self.fp.readline(limit)
708 if not result and limit:
709 self._close_conn()
710 elif self.length is not None:
711 self.length -= len(result)
712 if not self.length:
713 self._close_conn()
714 return result
715
716 def _read1_chunked(self, n):
717 # Strictly speaking, _get_chunk_left() may cause more than one read,
718 # but that is ok, since that is to satisfy the chunked protocol.
719 chunk_left = self._get_chunk_left()
720 if chunk_left is None or n == 0:
721 return b''
722 if not (0 <= n <= chunk_left):
723 n = chunk_left # if n is negative or larger than chunk_left
724 read = self.fp.read1(n)
725 self.chunk_left -= len(read)
726 if not read:
727 raise IncompleteRead(b"")
728 return read
729
730 def _peek_chunked(self, n):
731 # Strictly speaking, _get_chunk_left() may cause more than one read,
732 # but that is ok, since that is to satisfy the chunked protocol.
733 try:
734 chunk_left = self._get_chunk_left()
735 except IncompleteRead:
736 return b'' # peek doesn't worry about protocol
737 if chunk_left is None:
738 return b'' # eof
739 # peek is allowed to return more than requested. Just request the
740 # entire chunk, and truncate what we get.
741 return self.fp.peek(chunk_left)[:chunk_left]
742
743 def fileno(self):
744 return self.fp.fileno()
745
746 def getheader(self, name, default=None):
747 '''Returns the value of the header matching *name*.
748
749 If there are multiple matching headers, the values are
750 combined into a single string separated by commas and spaces.
751
752 If no matching header is found, returns *default* or None if
753 the *default* is not specified.
754
755 If the headers are unknown, raises http.client.ResponseNotReady.
756
757 '''
758 if self.headers is None:
759 raise ResponseNotReady()
760 headers = self.headers.get_all(name) or default
761 if isinstance(headers, str) or not hasattr(headers, '__iter__'):
762 return headers
763 else:
764 return ', '.join(headers)
765
766 def getheaders(self):
767 """Return list of (header, value) tuples."""
768 if self.headers is None:
769 raise ResponseNotReady()
770 return list(self.headers.items())
771
772 # We override IOBase.__iter__ so that it doesn't check for closed-ness
773
774 def __iter__(self):
775 return self
776
777 # For compatibility with old-style urllib responses.
778
779 def info(self):
780 '''Returns an instance of the class mimetools.Message containing
781 meta-information associated with the URL.
782
783 When the method is HTTP, these headers are those returned by
784 the server at the head of the retrieved HTML page (including
785 Content-Length and Content-Type).
786
787 When the method is FTP, a Content-Length header will be
788 present if (as is now usual) the server passed back a file
789 length in response to the FTP retrieval request. A
790 Content-Type header will be present if the MIME type can be
791 guessed.
792
793 When the method is local-file, returned headers will include
794 a Date representing the file's last-modified time, a
795 Content-Length giving file size, and a Content-Type
796 containing a guess at the file's type. See also the
797 description of the mimetools module.
798
799 '''
800 return self.headers
801
802 def geturl(self):
803 '''Return the real URL of the page.
804
805 In some cases, the HTTP server redirects a client to another
806 URL. The urlopen() function handles this transparently, but in
807 some cases the caller needs to know which URL the client was
808 redirected to. The geturl() method can be used to get at this
809 redirected URL.
810
811 '''
812 return self.url
813
814 def getcode(self):
815 '''Return the HTTP status code that was sent with the response,
816 or None if the URL is not an HTTP URL.
817
818 '''
819 return self.status
820
821 class HTTPConnection:
822
823 _http_vsn = 11
824 _http_vsn_str = 'HTTP/1.1'
825
826 response_class = HTTPResponse
827 default_port = HTTP_PORT
828 auto_open = 1
829 debuglevel = 0
830
831 @staticmethod
832 def _is_textIO(stream):
833 """Test whether a file-like object is a text or a binary stream.
834 """
835 return isinstance(stream, io.TextIOBase)
836
837 @staticmethod
838 def _get_content_length(body, method):
839 """Get the content-length based on the body.
840
841 If the body is None, we set Content-Length: 0 for methods that expect
842 a body (RFC 7230, Section 3.3.2). We also set the Content-Length for
843 any method if the body is a str or bytes-like object and not a file.
844 """
845 if body is None:
846 # do an explicit check for not None here to distinguish
847 # between unset and set but empty
848 if method.upper() in _METHODS_EXPECTING_BODY:
849 return 0
850 else:
851 return None
852
853 if hasattr(body, 'read'):
854 # file-like object.
855 return None
856
857 try:
858 # does it implement the buffer protocol (bytes, bytearray, array)?
859 mv = memoryview(body)
860 return mv.nbytes
861 except TypeError:
862 pass
863
864 if isinstance(body, str):
865 return len(body)
866
867 return None
868
869 def __init__(self, host, port=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
870 source_address=None, blocksize=8192):
871 self.timeout = timeout
872 self.source_address = source_address
873 self.blocksize = blocksize
874 self.sock = None
875 self._buffer = []
876 self.__response = None
877 self.__state = _CS_IDLE
878 self._method = None
879 self._tunnel_host = None
880 self._tunnel_port = None
881 self._tunnel_headers = {}
882
883 (self.host, self.port) = self._get_hostport(host, port)
884
885 self._validate_host(self.host)
886
887 # This is stored as an instance variable to allow unit
888 # tests to replace it with a suitable mockup
889 self._create_connection = socket.create_connection
890
891 def set_tunnel(self, host, port=None, headers=None):
892 """Set up host and port for HTTP CONNECT tunnelling.
893
894 In a connection that uses HTTP CONNECT tunneling, the host passed to the
895 constructor is used as a proxy server that relays all communication to
896 the endpoint passed to `set_tunnel`. This done by sending an HTTP
897 CONNECT request to the proxy server when the connection is established.
898
899 This method must be called before the HTTP connection has been
900 established.
901
902 The headers argument should be a mapping of extra HTTP headers to send
903 with the CONNECT request.
904 """
905
906 if self.sock:
907 raise RuntimeError("Can't set up tunnel for established connection")
908
909 self._tunnel_host, self._tunnel_port = self._get_hostport(host, port)
910 if headers:
911 self._tunnel_headers = headers
912 else:
913 self._tunnel_headers.clear()
914
915 def _get_hostport(self, host, port):
916 if port is None:
917 i = host.rfind(':')
918 j = host.rfind(']') # ipv6 addresses have [...]
919 if i > j:
920 try:
921 port = int(host[i+1:])
922 except ValueError:
923 if host[i+1:] == "": # http://foo.com:/ == http://foo.com/
924 port = self.default_port
925 else:
926 raise InvalidURL("nonnumeric port: '%s'" % host[i+1:])
927 host = host[:i]
928 else:
929 port = self.default_port
930 if host and host[0] == '[' and host[-1] == ']':
931 host = host[1:-1]
932
933 return (host, port)
934
935 def set_debuglevel(self, level):
936 self.debuglevel = level
937
938 def _wrap_ipv6(self, ip):
939 if b':' in ip and ip[0] != b'['[0]:
940 return b"[" + ip + b"]"
941 return ip
942
943 def _tunnel(self):
•944 if _contains_disallowed_url_pchar_re.search(self._tunnel_host):
945 raise ValueError('Tunnel host can\'t contain control characters %r'
946 % (self._tunnel_host,))
947 connect = b"CONNECT %s:%d HTTP/1.0\r\n" % (
948 self._wrap_ipv6(self._tunnel_host.encode("ascii")),
949 self._tunnel_port)
950 headers = [connect]
951 for header, value in self._tunnel_headers.items():
•952 header_bytes = header.encode("latin-1")
953 value_bytes = value.encode("latin-1")
954 if not _is_legal_header_name(header_bytes):
955 raise ValueError('Invalid header name %r' % (header_bytes,))
956 if _is_illegal_header_value(value_bytes):
957 raise ValueError('Invalid header value %r' % (value_bytes,))
958 headers.append(b"%s: %s\r\n" % (header_bytes, value_bytes))
959 headers.append(b"\r\n")
960 # Making a single send() call instead of one per line encourages
961 # the host OS to use a more optimal packet size instead of
962 # potentially emitting a series of small packets.
963 self.send(b"".join(headers))
964 del headers
965
966 response = self.response_class(self.sock, method=self._method)
967 try:
968 (version, code, message) = response._read_status()
969
970 if code != http.HTTPStatus.OK:
971 self.close()
972 raise OSError(f"Tunnel connection failed: {code} {message.strip()}")
973 while True:
974 line = response.fp.readline(_MAXLINE + 1)
975 if len(line) > _MAXLINE:
976 raise LineTooLong("header line")
977 if not line:
978 # for sites which EOF without sending a trailer
979 break
980 if line in (b'\r\n', b'\n', b''):
981 break
982
983 if self.debuglevel > 0:
984 print('header:', line.decode())
985 finally:
986 response.close()
987
988 def connect(self):
989 """Connect to the host and port specified in __init__."""
990 sys.audit("http.client.connect", self, self.host, self.port)
991 self.sock = self._create_connection(
992 (self.host,self.port), self.timeout, self.source_address)
993 # Might fail in OSs that don't implement TCP_NODELAY
994 try:
995 self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
996 except OSError as e:
997 if e.errno != errno.ENOPROTOOPT:
998 raise
999
1000 if self._tunnel_host:
1001 self._tunnel()
1002
1003 def close(self):
1004 """Close the connection to the HTTP server."""
1005 self.__state = _CS_IDLE
1006 try:
1007 sock = self.sock
1008 if sock:
1009 self.sock = None
1010 sock.close() # close it manually... there may be other refs
1011 finally:
1012 response = self.__response
1013 if response:
1014 self.__response = None
1015 response.close()
1016
1017 def send(self, data):
1018 """Send `data' to the server.
1019 ``data`` can be a string object, a bytes object, an array object, a
1020 file-like object that supports a .read() method, or an iterable object.
1021 """
1022
1023 if self.sock is None:
1024 if self.auto_open:
1025 self.connect()
1026 else:
1027 raise NotConnected()
1028
1029 if self.debuglevel > 0:
1030 print("send:", repr(data))
1031 if hasattr(data, "read") :
1032 if self.debuglevel > 0:
1033 print("sending a readable")
1034 encode = self._is_textIO(data)
1035 if encode and self.debuglevel > 0:
1036 print("encoding file using iso-8859-1")
1037 while 1:
1038 datablock = data.read(self.blocksize)
1039 if not datablock:
1040 break
1041 if encode:
1042 datablock = datablock.encode("iso-8859-1")
1043 sys.audit("http.client.send", self, datablock)
1044 self.sock.sendall(datablock)
1045 return
1046 sys.audit("http.client.send", self, data)
1047 try:
1048 self.sock.sendall(data)
1049 except TypeError:
1050 if isinstance(data, collections.abc.Iterable):
1051 for d in data:
1052 self.sock.sendall(d)
1053 else:
1054 raise TypeError("data should be a bytes-like object "
1055 "or an iterable, got %r" % type(data))
1056
1057 def _output(self, s):
1058 """Add a line of output to the current request buffer.
1059
1060 Assumes that the line does *not* end with \\r\\n.
1061 """
1062 self._buffer.append(s)
1063
1064 def _read_readable(self, readable):
1065 if self.debuglevel > 0:
1066 print("reading a readable")
1067 encode = self._is_textIO(readable)
1068 if encode and self.debuglevel > 0:
1069 print("encoding file using iso-8859-1")
1070 while True:
1071 datablock = readable.read(self.blocksize)
1072 if not datablock:
1073 break
1074 if encode:
1075 datablock = datablock.encode("iso-8859-1")
1076 yield datablock
1077
1078 def _send_output(self, message_body=None, encode_chunked=False):
1079 """Send the currently buffered request and clear the buffer.
1080
1081 Appends an extra \\r\\n to the buffer.
1082 A message_body may be specified, to be appended to the request.
1083 """
1084 self._buffer.extend((b"", b""))
1085 msg = b"\r\n".join(self._buffer)
1086 del self._buffer[:]
1087 self.send(msg)
1088
1089 if message_body is not None:
1090
1091 # create a consistent interface to message_body
1092 if hasattr(message_body, 'read'):
1093 # Let file-like take precedence over byte-like. This
1094 # is needed to allow the current position of mmap'ed
1095 # files to be taken into account.
1096 chunks = self._read_readable(message_body)
1097 else:
1098 try:
1099 # this is solely to check to see if message_body
1100 # implements the buffer API. it /would/ be easier
1101 # to capture if PyObject_CheckBuffer was exposed
1102 # to Python.
1103 memoryview(message_body)
1104 except TypeError:
1105 try:
1106 chunks = iter(message_body)
1107 except TypeError:
1108 raise TypeError("message_body should be a bytes-like "
1109 "object or an iterable, got %r"
1110 % type(message_body))
1111 else:
1112 # the object implements the buffer interface and
1113 # can be passed directly into socket methods
1114 chunks = (message_body,)
1115
1116 for chunk in chunks:
1117 if not chunk:
1118 if self.debuglevel > 0:
1119 print('Zero length chunk ignored')
1120 continue
1121
1122 if encode_chunked and self._http_vsn == 11:
1123 # chunked encoding
1124 chunk = f'{len(chunk):X}\r\n'.encode('ascii') + chunk \
1125 + b'\r\n'
1126 self.send(chunk)
1127
1128 if encode_chunked and self._http_vsn == 11:
1129 # end chunked transfer
1130 self.send(b'0\r\n\r\n')
1131
1132 def putrequest(self, method, url, skip_host=False,
1133 skip_accept_encoding=False):
1134 """Send a request to the server.
1135
1136 `method' specifies an HTTP request method, e.g. 'GET'.
1137 `url' specifies the object being requested, e.g. '/index.html'.
1138 `skip_host' if True does not add automatically a 'Host:' header
1139 `skip_accept_encoding' if True does not add automatically an
1140 'Accept-Encoding:' header
1141 """
1142
1143 # if a prior response has been completed, then forget about it.
1144 if self.__response and self.__response.isclosed():
1145 self.__response = None
1146
1147
1148 # in certain cases, we cannot issue another request on this connection.
1149 # this occurs when:
1150 # 1) we are in the process of sending a request. (_CS_REQ_STARTED)
1151 # 2) a response to a previous request has signalled that it is going
1152 # to close the connection upon completion.
1153 # 3) the headers for the previous response have not been read, thus
1154 # we cannot determine whether point (2) is true. (_CS_REQ_SENT)
1155 #
1156 # if there is no prior response, then we can request at will.
1157 #
1158 # if point (2) is true, then we will have passed the socket to the
1159 # response (effectively meaning, "there is no prior response"), and
1160 # will open a new one when a new request is made.
1161 #
1162 # Note: if a prior response exists, then we *can* start a new request.
1163 # We are not allowed to begin fetching the response to this new
1164 # request, however, until that prior response is complete.
1165 #
1166 if self.__state == _CS_IDLE:
1167 self.__state = _CS_REQ_STARTED
1168 else:
1169 raise CannotSendRequest(self.__state)
1170
1171 self._validate_method(method)
1172
1173 # Save the method for use later in the response phase
1174 self._method = method
1175
1176 url = url or '/'
1177 self._validate_path(url)
1178
1179 request = '%s %s %s' % (method, url, self._http_vsn_str)
1180
1181 self._output(self._encode_request(request))
1182
1183 if self._http_vsn == 11:
1184 # Issue some standard headers for better HTTP/1.1 compliance
1185
1186 if not skip_host:
1187 # this header is issued *only* for HTTP/1.1
1188 # connections. more specifically, this means it is
1189 # only issued when the client uses the new
1190 # HTTPConnection() class. backwards-compat clients
1191 # will be using HTTP/1.0 and those clients may be
1192 # issuing this header themselves. we should NOT issue
1193 # it twice; some web servers (such as Apache) barf
1194 # when they see two Host: headers
1195
1196 # If we need a non-standard port,include it in the
1197 # header. If the request is going through a proxy,
1198 # but the host of the actual URL, not the host of the
1199 # proxy.
1200
1201 netloc = ''
1202 if url.startswith('http'):
1203 nil, netloc, nil, nil, nil = urlsplit(url)
1204
1205 if netloc:
1206 try:
1207 netloc_enc = netloc.encode("ascii")
1208 except UnicodeEncodeError:
1209 netloc_enc = netloc.encode("idna")
1210 self.putheader('Host', _strip_ipv6_iface(netloc_enc))
1211 else:
1212 if self._tunnel_host:
1213 host = self._tunnel_host
1214 port = self._tunnel_port
1215 else:
1216 host = self.host
1217 port = self.port
1218
1219 try:
1220 host_enc = host.encode("ascii")
1221 except UnicodeEncodeError:
1222 host_enc = host.encode("idna")
1223
1224 # As per RFC 273, IPv6 address should be wrapped with []
1225 # when used as Host header
1226 host_enc = self._wrap_ipv6(host_enc)
1227 if ":" in host:
1228 host_enc = _strip_ipv6_iface(host_enc)
1229
1230 if port == self.default_port:
1231 self.putheader('Host', host_enc)
1232 else:
1233 host_enc = host_enc.decode("ascii")
1234 self.putheader('Host', "%s:%s" % (host_enc, port))
1235
1236 # note: we are assuming that clients will not attempt to set these
1237 # headers since *this* library must deal with the
1238 # consequences. this also means that when the supporting
1239 # libraries are updated to recognize other forms, then this
1240 # code should be changed (removed or updated).
1241
1242 # we only want a Content-Encoding of "identity" since we don't
1243 # support encodings such as x-gzip or x-deflate.
1244 if not skip_accept_encoding:
1245 self.putheader('Accept-Encoding', 'identity')
1246
1247 # we can accept "chunked" Transfer-Encodings, but no others
1248 # NOTE: no TE header implies *only* "chunked"
1249 #self.putheader('TE', 'chunked')
1250
1251 # if TE is supplied in the header, then it must appear in a
1252 # Connection header.
1253 #self.putheader('Connection', 'TE')
1254
1255 else:
1256 # For HTTP/1.0, the server will assume "not chunked"
1257 pass
1258
1259 def _encode_request(self, request):
1260 # ASCII also helps prevent CVE-2019-9740.
1261 return request.encode('ascii')
1262
1263 def _validate_method(self, method):
1264 """Validate a method name for putrequest."""
1265 # prevent http header injection
1266 match = _contains_disallowed_method_pchar_re.search(method)
1267 if match:
1268 raise ValueError(
1269 f"method can't contain control characters. {method!r} "
1270 f"(found at least {match.group()!r})")
1271
1272 def _validate_path(self, url):
1273 """Validate a url for putrequest."""
1274 # Prevent CVE-2019-9740.
1275 match = _contains_disallowed_url_pchar_re.search(url)
1276 if match:
1277 raise InvalidURL(f"URL can't contain control characters. {url!r} "
1278 f"(found at least {match.group()!r})")
1279
1280 def _validate_host(self, host):
1281 """Validate a host so it doesn't contain control characters."""
1282 # Prevent CVE-2019-18348.
1283 match = _contains_disallowed_url_pchar_re.search(host)
1284 if match:
1285 raise InvalidURL(f"URL can't contain control characters. {host!r} "
1286 f"(found at least {match.group()!r})")
1287
1288 def putheader(self, header, *values):
1289 """Send a request header line to the server.
1290
1291 For example: h.putheader('Accept', 'text/html')
1292 """
1293 if self.__state != _CS_REQ_STARTED:
1294 raise CannotSendHeader()
1295
1296 if hasattr(header, 'encode'):
1297 header = header.encode('ascii')
1298
1299 if not _is_legal_header_name(header):
1300 raise ValueError('Invalid header name %r' % (header,))
1301
1302 values = list(values)
1303 for i, one_value in enumerate(values):
1304 if hasattr(one_value, 'encode'):
1305 values[i] = one_value.encode('latin-1')
1306 elif isinstance(one_value, int):
1307 values[i] = str(one_value).encode('ascii')
1308
1309 if _is_illegal_header_value(values[i]):
1310 raise ValueError('Invalid header value %r' % (values[i],))
1311
1312 value = b'\r\n\t'.join(values)
1313 header = header + b': ' + value
1314 self._output(header)
1315
1316 def endheaders(self, message_body=None, *, encode_chunked=False):
1317 """Indicate that the last header line has been sent to the server.
1318
1319 This method sends the request to the server. The optional message_body
1320 argument can be used to pass a message body associated with the
1321 request.
1322 """
1323 if self.__state == _CS_REQ_STARTED:
1324 self.__state = _CS_REQ_SENT
1325 else:
1326 raise CannotSendHeader()
1327 self._send_output(message_body, encode_chunked=encode_chunked)
1328
1329 def request(self, method, url, body=None, headers={}, *,
1330 encode_chunked=False):
1331 """Send a complete request to the server."""
1332 self._send_request(method, url, body, headers, encode_chunked)
1333
1334 def _send_request(self, method, url, body, headers, encode_chunked):
1335 # Honor explicitly requested Host: and Accept-Encoding: headers.
1336 header_names = frozenset(k.lower() for k in headers)
1337 skips = {}
1338 if 'host' in header_names:
1339 skips['skip_host'] = 1
1340 if 'accept-encoding' in header_names:
1341 skips['skip_accept_encoding'] = 1
1342
1343 self.putrequest(method, url, **skips)
1344
1345 # chunked encoding will happen if HTTP/1.1 is used and either
1346 # the caller passes encode_chunked=True or the following
1347 # conditions hold:
1348 # 1. content-length has not been explicitly set
1349 # 2. the body is a file or iterable, but not a str or bytes-like
1350 # 3. Transfer-Encoding has NOT been explicitly set by the caller
1351
1352 if 'content-length' not in header_names:
1353 # only chunk body if not explicitly set for backwards
1354 # compatibility, assuming the client code is already handling the
1355 # chunking
1356 if 'transfer-encoding' not in header_names:
1357 # if content-length cannot be automatically determined, fall
1358 # back to chunked encoding
1359 encode_chunked = False
1360 content_length = self._get_content_length(body, method)
1361 if content_length is None:
1362 if body is not None:
1363 if self.debuglevel > 0:
1364 print('Unable to determine size of %r' % body)
1365 encode_chunked = True
1366 self.putheader('Transfer-Encoding', 'chunked')
1367 else:
1368 self.putheader('Content-Length', str(content_length))
1369 else:
1370 encode_chunked = False
1371
1372 for hdr, value in headers.items():
1373 self.putheader(hdr, value)
1374 if isinstance(body, str):
1375 # RFC 2616 Section 3.7.1 says that text default has a
1376 # default charset of iso-8859-1.
1377 body = _encode(body, 'body')
1378 self.endheaders(body, encode_chunked=encode_chunked)
1379
1380 def getresponse(self):
1381 """Get the response from the server.
1382
1383 If the HTTPConnection is in the correct state, returns an
1384 instance of HTTPResponse or of whatever object is returned by
1385 the response_class variable.
1386
1387 If a request has not been sent or if a previous response has
1388 not be handled, ResponseNotReady is raised. If the HTTP
1389 response indicates that the connection should be closed, then
1390 it will be closed before the response is returned. When the
1391 connection is closed, the underlying socket is closed.
1392 """
1393
1394 # if a prior response has been completed, then forget about it.
1395 if self.__response and self.__response.isclosed():
1396 self.__response = None
1397
1398 # if a prior response exists, then it must be completed (otherwise, we
1399 # cannot read this response's header to determine the connection-close
1400 # behavior)
1401 #
1402 # note: if a prior response existed, but was connection-close, then the
1403 # socket and response were made independent of this HTTPConnection
1404 # object since a new request requires that we open a whole new
1405 # connection
1406 #
1407 # this means the prior response had one of two states:
1408 # 1) will_close: this connection was reset and the prior socket and
1409 # response operate independently
1410 # 2) persistent: the response was retained and we await its
1411 # isclosed() status to become true.
1412 #
1413 if self.__state != _CS_REQ_SENT or self.__response:
1414 raise ResponseNotReady(self.__state)
1415
1416 if self.debuglevel > 0:
1417 response = self.response_class(self.sock, self.debuglevel,
1418 method=self._method)
1419 else:
1420 response = self.response_class(self.sock, method=self._method)
1421
1422 try:
1423 try:
1424 response.begin()
1425 except ConnectionError:
1426 self.close()
1427 raise
1428 assert response.will_close != _UNKNOWN
1429 self.__state = _CS_IDLE
1430
1431 if response.will_close:
1432 # this effectively passes the connection to the response
1433 self.close()
1434 else:
1435 # remember this, so we can tell when it is complete
1436 self.__response = response
1437
1438 return response
1439 except:
1440 response.close()
1441 raise
1442
1443 try:
1444 import ssl
1445 except ImportError:
1446 pass
1447 else:
1448 class HTTPSConnection(HTTPConnection):
1449 "This class allows communication via SSL."
1450
1451 default_port = HTTPS_PORT
1452
1453 # XXX Should key_file and cert_file be deprecated in favour of context?
1454
1455 def __init__(self, host, port=None, key_file=None, cert_file=None,
1456 timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
1457 source_address=None, *, context=None,
1458 check_hostname=None, blocksize=8192):
1459 super(HTTPSConnection, self).__init__(host, port, timeout,
1460 source_address,
1461 blocksize=blocksize)
1462 if (key_file is not None or cert_file is not None or
1463 check_hostname is not None):
1464 import warnings
1465 warnings.warn("key_file, cert_file and check_hostname are "
1466 "deprecated, use a custom context instead.",
1467 DeprecationWarning, 2)
1468 self.key_file = key_file
1469 self.cert_file = cert_file
1470 if context is None:
1471 context = ssl._create_default_https_context()
1472 # send ALPN extension to indicate HTTP/1.1 protocol
1473 if self._http_vsn == 11:
1474 context.set_alpn_protocols(['http/1.1'])
1475 # enable PHA for TLS 1.3 connections if available
1476 if context.post_handshake_auth is not None:
1477 context.post_handshake_auth = True
1478 will_verify = context.verify_mode != ssl.CERT_NONE
1479 if check_hostname is None:
1480 check_hostname = context.check_hostname
1481 if check_hostname and not will_verify:
1482 raise ValueError("check_hostname needs a SSL context with "
1483 "either CERT_OPTIONAL or CERT_REQUIRED")
1484 if key_file or cert_file:
1485 context.load_cert_chain(cert_file, key_file)
1486 # cert and key file means the user wants to authenticate.
1487 # enable TLS 1.3 PHA implicitly even for custom contexts.
1488 if context.post_handshake_auth is not None:
1489 context.post_handshake_auth = True
1490 self._context = context
1491 if check_hostname is not None:
1492 self._context.check_hostname = check_hostname
1493
1494 def connect(self):
1495 "Connect to a host on a given (SSL) port."
1496
1497 super().connect()
1498
1499 if self._tunnel_host:
1500 server_hostname = self._tunnel_host
1501 else:
1502 server_hostname = self.host
1503
1504 self.sock = self._context.wrap_socket(self.sock,
1505 server_hostname=server_hostname)
1506
1507 __all__.append("HTTPSConnection")
1508
1509 class HTTPException(Exception):
1510 # Subclasses that define an __init__ must call Exception.__init__
1511 # or define self.args. Otherwise, str() will fail.
1512 pass
1513
1514 class NotConnected(HTTPException):
1515 pass
1516
1517 class InvalidURL(HTTPException):
1518 pass
1519
1520 class UnknownProtocol(HTTPException):
1521 def __init__(self, version):
1522 self.args = version,
1523 self.version = version
1524
1525 class UnknownTransferEncoding(HTTPException):
1526 pass
1527
1528 class UnimplementedFileMode(HTTPException):
1529 pass
1530
1531 class IncompleteRead(HTTPException):
1532 def __init__(self, partial, expected=None):
1533 self.args = partial,
1534 self.partial = partial
1535 self.expected = expected
1536 def __repr__(self):
1537 if self.expected is not None:
1538 e = ', %i more expected' % self.expected
1539 else:
1540 e = ''
1541 return '%s(%i bytes read%s)' % (self.__class__.__name__,
1542 len(self.partial), e)
1543 __str__ = object.__str__
1544
1545 class ImproperConnectionState(HTTPException):
1546 pass
1547
1548 class CannotSendRequest(ImproperConnectionState):
1549 pass
1550
1551 class CannotSendHeader(ImproperConnectionState):
1552 pass
1553
1554 class ResponseNotReady(ImproperConnectionState):
1555 pass
1556
1557 class BadStatusLine(HTTPException):
1558 def __init__(self, line):
1559 if not line:
1560 line = repr(line)
1561 self.args = line,
1562 self.line = line
1563
1564 class LineTooLong(HTTPException):
1565 def __init__(self, line_type):
1566 HTTPException.__init__(self, "got more than %d bytes when reading %s"
1567 % (_MAXLINE, line_type))
1568
1569 class RemoteDisconnected(ConnectionResetError, BadStatusLine):
1570 def __init__(self, *pos, **kw):
1571 BadStatusLine.__init__(self, "")
1572 ConnectionResetError.__init__(self, *pos, **kw)
1573
1574 # for backwards compatibility
1575 error = HTTPException