Debian Codegraph @

lib-python/3/http/client.py

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
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 connect = b"CONNECT %s:%d HTTP/1.0\r\n" % (
945 self._wrap_ipv6(self._tunnel_host.encode("ascii")),
946 self._tunnel_port)
947 headers = [connect]
948 for header, value in self._tunnel_headers.items():
949 headers.append(f"{header}: {value}\r\n".encode("latin-1"))
950 headers.append(b"\r\n")
951 # Making a single send() call instead of one per line encourages
952 # the host OS to use a more optimal packet size instead of
953 # potentially emitting a series of small packets.
954 self.send(b"".join(headers))
955 del headers
956
957 response = self.response_class(self.sock, method=self._method)
958 try:
959 (version, code, message) = response._read_status()
960
961 if code != http.HTTPStatus.OK:
962 self.close()
963 raise OSError(f"Tunnel connection failed: {code} {message.strip()}")
964 while True:
965 line = response.fp.readline(_MAXLINE + 1)
966 if len(line) > _MAXLINE:
967 raise LineTooLong("header line")
968 if not line:
969 # for sites which EOF without sending a trailer
970 break
971 if line in (b'\r\n', b'\n', b''):
972 break
973
974 if self.debuglevel > 0:
975 print('header:', line.decode())
976 finally:
977 response.close()
978
979 def connect(self):
980 """Connect to the host and port specified in __init__."""
981 sys.audit("http.client.connect", self, self.host, self.port)
982 self.sock = self._create_connection(
983 (self.host,self.port), self.timeout, self.source_address)
984 # Might fail in OSs that don't implement TCP_NODELAY
985 try:
986 self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
987 except OSError as e:
988 if e.errno != errno.ENOPROTOOPT:
989 raise
990
991 if self._tunnel_host:
992 self._tunnel()
993
994 def close(self):
995 """Close the connection to the HTTP server."""
996 self.__state = _CS_IDLE
997 try:
998 sock = self.sock
999 if sock:
1000 self.sock = None
1001 sock.close() # close it manually... there may be other refs
1002 finally:
1003 response = self.__response
1004 if response:
1005 self.__response = None
1006 response.close()
1007
1008 def send(self, data):
1009 """Send `data' to the server.
1010 ``data`` can be a string object, a bytes object, an array object, a
1011 file-like object that supports a .read() method, or an iterable object.
1012 """
1013
1014 if self.sock is None:
1015 if self.auto_open:
1016 self.connect()
1017 else:
1018 raise NotConnected()
1019
1020 if self.debuglevel > 0:
1021 print("send:", repr(data))
1022 if hasattr(data, "read") :
1023 if self.debuglevel > 0:
1024 print("sending a readable")
1025 encode = self._is_textIO(data)
1026 if encode and self.debuglevel > 0:
1027 print("encoding file using iso-8859-1")
1028 while 1:
1029 datablock = data.read(self.blocksize)
1030 if not datablock:
1031 break
1032 if encode:
1033 datablock = datablock.encode("iso-8859-1")
1034 sys.audit("http.client.send", self, datablock)
1035 self.sock.sendall(datablock)
1036 return
1037 sys.audit("http.client.send", self, data)
1038 try:
1039 self.sock.sendall(data)
1040 except TypeError:
1041 if isinstance(data, collections.abc.Iterable):
1042 for d in data:
1043 self.sock.sendall(d)
1044 else:
1045 raise TypeError("data should be a bytes-like object "
1046 "or an iterable, got %r" % type(data))
1047
1048 def _output(self, s):
1049 """Add a line of output to the current request buffer.
1050
1051 Assumes that the line does *not* end with \\r\\n.
1052 """
1053 self._buffer.append(s)
1054
1055 def _read_readable(self, readable):
1056 if self.debuglevel > 0:
1057 print("reading a readable")
1058 encode = self._is_textIO(readable)
1059 if encode and self.debuglevel > 0:
1060 print("encoding file using iso-8859-1")
1061 while True:
1062 datablock = readable.read(self.blocksize)
1063 if not datablock:
1064 break
1065 if encode:
1066 datablock = datablock.encode("iso-8859-1")
1067 yield datablock
1068
1069 def _send_output(self, message_body=None, encode_chunked=False):
1070 """Send the currently buffered request and clear the buffer.
1071
1072 Appends an extra \\r\\n to the buffer.
1073 A message_body may be specified, to be appended to the request.
1074 """
1075 self._buffer.extend((b"", b""))
1076 msg = b"\r\n".join(self._buffer)
1077 del self._buffer[:]
1078 self.send(msg)
1079
1080 if message_body is not None:
1081
1082 # create a consistent interface to message_body
1083 if hasattr(message_body, 'read'):
1084 # Let file-like take precedence over byte-like. This
1085 # is needed to allow the current position of mmap'ed
1086 # files to be taken into account.
1087 chunks = self._read_readable(message_body)
1088 else:
1089 try:
1090 # this is solely to check to see if message_body
1091 # implements the buffer API. it /would/ be easier
1092 # to capture if PyObject_CheckBuffer was exposed
1093 # to Python.
1094 memoryview(message_body)
1095 except TypeError:
1096 try:
1097 chunks = iter(message_body)
1098 except TypeError:
1099 raise TypeError("message_body should be a bytes-like "
1100 "object or an iterable, got %r"
1101 % type(message_body))
1102 else:
1103 # the object implements the buffer interface and
1104 # can be passed directly into socket methods
1105 chunks = (message_body,)
1106
1107 for chunk in chunks:
1108 if not chunk:
1109 if self.debuglevel > 0:
1110 print('Zero length chunk ignored')
1111 continue
1112
1113 if encode_chunked and self._http_vsn == 11:
1114 # chunked encoding
1115 chunk = f'{len(chunk):X}\r\n'.encode('ascii') + chunk \
1116 + b'\r\n'
1117 self.send(chunk)
1118
1119 if encode_chunked and self._http_vsn == 11:
1120 # end chunked transfer
1121 self.send(b'0\r\n\r\n')
1122
1123 def putrequest(self, method, url, skip_host=False,
1124 skip_accept_encoding=False):
1125 """Send a request to the server.
1126
1127 `method' specifies an HTTP request method, e.g. 'GET'.
1128 `url' specifies the object being requested, e.g. '/index.html'.
1129 `skip_host' if True does not add automatically a 'Host:' header
1130 `skip_accept_encoding' if True does not add automatically an
1131 'Accept-Encoding:' header
1132 """
1133
1134 # if a prior response has been completed, then forget about it.
1135 if self.__response and self.__response.isclosed():
1136 self.__response = None
1137
1138
1139 # in certain cases, we cannot issue another request on this connection.
1140 # this occurs when:
1141 # 1) we are in the process of sending a request. (_CS_REQ_STARTED)
1142 # 2) a response to a previous request has signalled that it is going
1143 # to close the connection upon completion.
1144 # 3) the headers for the previous response have not been read, thus
1145 # we cannot determine whether point (2) is true. (_CS_REQ_SENT)
1146 #
1147 # if there is no prior response, then we can request at will.
1148 #
1149 # if point (2) is true, then we will have passed the socket to the
1150 # response (effectively meaning, "there is no prior response"), and
1151 # will open a new one when a new request is made.
1152 #
1153 # Note: if a prior response exists, then we *can* start a new request.
1154 # We are not allowed to begin fetching the response to this new
1155 # request, however, until that prior response is complete.
1156 #
1157 if self.__state == _CS_IDLE:
1158 self.__state = _CS_REQ_STARTED
1159 else:
1160 raise CannotSendRequest(self.__state)
1161
1162 self._validate_method(method)
1163
1164 # Save the method for use later in the response phase
1165 self._method = method
1166
1167 url = url or '/'
1168 self._validate_path(url)
1169
1170 request = '%s %s %s' % (method, url, self._http_vsn_str)
1171
1172 self._output(self._encode_request(request))
1173
1174 if self._http_vsn == 11:
1175 # Issue some standard headers for better HTTP/1.1 compliance
1176
1177 if not skip_host:
1178 # this header is issued *only* for HTTP/1.1
1179 # connections. more specifically, this means it is
1180 # only issued when the client uses the new
1181 # HTTPConnection() class. backwards-compat clients
1182 # will be using HTTP/1.0 and those clients may be
1183 # issuing this header themselves. we should NOT issue
1184 # it twice; some web servers (such as Apache) barf
1185 # when they see two Host: headers
1186
1187 # If we need a non-standard port,include it in the
1188 # header. If the request is going through a proxy,
1189 # but the host of the actual URL, not the host of the
1190 # proxy.
1191
1192 netloc = ''
1193 if url.startswith('http'):
1194 nil, netloc, nil, nil, nil = urlsplit(url)
1195
1196 if netloc:
1197 try:
1198 netloc_enc = netloc.encode("ascii")
1199 except UnicodeEncodeError:
1200 netloc_enc = netloc.encode("idna")
1201 self.putheader('Host', _strip_ipv6_iface(netloc_enc))
1202 else:
1203 if self._tunnel_host:
1204 host = self._tunnel_host
1205 port = self._tunnel_port
1206 else:
1207 host = self.host
1208 port = self.port
1209
1210 try:
1211 host_enc = host.encode("ascii")
1212 except UnicodeEncodeError:
1213 host_enc = host.encode("idna")
1214
1215 # As per RFC 273, IPv6 address should be wrapped with []
1216 # when used as Host header
1217 host_enc = self._wrap_ipv6(host_enc)
1218 if ":" in host:
1219 host_enc = _strip_ipv6_iface(host_enc)
1220
1221 if port == self.default_port:
1222 self.putheader('Host', host_enc)
1223 else:
1224 host_enc = host_enc.decode("ascii")
1225 self.putheader('Host', "%s:%s" % (host_enc, port))
1226
1227 # note: we are assuming that clients will not attempt to set these
1228 # headers since *this* library must deal with the
1229 # consequences. this also means that when the supporting
1230 # libraries are updated to recognize other forms, then this
1231 # code should be changed (removed or updated).
1232
1233 # we only want a Content-Encoding of "identity" since we don't
1234 # support encodings such as x-gzip or x-deflate.
1235 if not skip_accept_encoding:
1236 self.putheader('Accept-Encoding', 'identity')
1237
1238 # we can accept "chunked" Transfer-Encodings, but no others
1239 # NOTE: no TE header implies *only* "chunked"
1240 #self.putheader('TE', 'chunked')
1241
1242 # if TE is supplied in the header, then it must appear in a
1243 # Connection header.
1244 #self.putheader('Connection', 'TE')
1245
1246 else:
1247 # For HTTP/1.0, the server will assume "not chunked"
1248 pass
1249
1250 def _encode_request(self, request):
1251 # ASCII also helps prevent CVE-2019-9740.
1252 return request.encode('ascii')
1253
1254 def _validate_method(self, method):
1255 """Validate a method name for putrequest."""
1256 # prevent http header injection
1257 match = _contains_disallowed_method_pchar_re.search(method)
1258 if match:
1259 raise ValueError(
1260 f"method can't contain control characters. {method!r} "
1261 f"(found at least {match.group()!r})")
1262
1263 def _validate_path(self, url):
1264 """Validate a url for putrequest."""
1265 # Prevent CVE-2019-9740.
1266 match = _contains_disallowed_url_pchar_re.search(url)
1267 if match:
1268 raise InvalidURL(f"URL can't contain control characters. {url!r} "
1269 f"(found at least {match.group()!r})")
1270
1271 def _validate_host(self, host):
1272 """Validate a host so it doesn't contain control characters."""
1273 # Prevent CVE-2019-18348.
1274 match = _contains_disallowed_url_pchar_re.search(host)
1275 if match:
1276 raise InvalidURL(f"URL can't contain control characters. {host!r} "
1277 f"(found at least {match.group()!r})")
1278
1279 def putheader(self, header, *values):
1280 """Send a request header line to the server.
1281
1282 For example: h.putheader('Accept', 'text/html')
1283 """
1284 if self.__state != _CS_REQ_STARTED:
1285 raise CannotSendHeader()
1286
1287 if hasattr(header, 'encode'):
1288 header = header.encode('ascii')
1289
1290 if not _is_legal_header_name(header):
1291 raise ValueError('Invalid header name %r' % (header,))
1292
1293 values = list(values)
1294 for i, one_value in enumerate(values):
1295 if hasattr(one_value, 'encode'):
1296 values[i] = one_value.encode('latin-1')
1297 elif isinstance(one_value, int):
1298 values[i] = str(one_value).encode('ascii')
1299
1300 if _is_illegal_header_value(values[i]):
1301 raise ValueError('Invalid header value %r' % (values[i],))
1302
1303 value = b'\r\n\t'.join(values)
1304 header = header + b': ' + value
1305 self._output(header)
1306
1307 def endheaders(self, message_body=None, *, encode_chunked=False):
1308 """Indicate that the last header line has been sent to the server.
1309
1310 This method sends the request to the server. The optional message_body
1311 argument can be used to pass a message body associated with the
1312 request.
1313 """
1314 if self.__state == _CS_REQ_STARTED:
1315 self.__state = _CS_REQ_SENT
1316 else:
1317 raise CannotSendHeader()
1318 self._send_output(message_body, encode_chunked=encode_chunked)
1319
1320 def request(self, method, url, body=None, headers={}, *,
1321 encode_chunked=False):
1322 """Send a complete request to the server."""
1323 self._send_request(method, url, body, headers, encode_chunked)
1324
1325 def _send_request(self, method, url, body, headers, encode_chunked):
1326 # Honor explicitly requested Host: and Accept-Encoding: headers.
1327 header_names = frozenset(k.lower() for k in headers)
1328 skips = {}
1329 if 'host' in header_names:
1330 skips['skip_host'] = 1
1331 if 'accept-encoding' in header_names:
1332 skips['skip_accept_encoding'] = 1
1333
1334 self.putrequest(method, url, **skips)
1335
1336 # chunked encoding will happen if HTTP/1.1 is used and either
1337 # the caller passes encode_chunked=True or the following
1338 # conditions hold:
1339 # 1. content-length has not been explicitly set
1340 # 2. the body is a file or iterable, but not a str or bytes-like
1341 # 3. Transfer-Encoding has NOT been explicitly set by the caller
1342
1343 if 'content-length' not in header_names:
1344 # only chunk body if not explicitly set for backwards
1345 # compatibility, assuming the client code is already handling the
1346 # chunking
1347 if 'transfer-encoding' not in header_names:
1348 # if content-length cannot be automatically determined, fall
1349 # back to chunked encoding
1350 encode_chunked = False
1351 content_length = self._get_content_length(body, method)
1352 if content_length is None:
1353 if body is not None:
1354 if self.debuglevel > 0:
1355 print('Unable to determine size of %r' % body)
1356 encode_chunked = True
1357 self.putheader('Transfer-Encoding', 'chunked')
1358 else:
1359 self.putheader('Content-Length', str(content_length))
1360 else:
1361 encode_chunked = False
1362
1363 for hdr, value in headers.items():
1364 self.putheader(hdr, value)
1365 if isinstance(body, str):
1366 # RFC 2616 Section 3.7.1 says that text default has a
1367 # default charset of iso-8859-1.
1368 body = _encode(body, 'body')
1369 self.endheaders(body, encode_chunked=encode_chunked)
1370
1371 def getresponse(self):
1372 """Get the response from the server.
1373
1374 If the HTTPConnection is in the correct state, returns an
1375 instance of HTTPResponse or of whatever object is returned by
1376 the response_class variable.
1377
1378 If a request has not been sent or if a previous response has
1379 not be handled, ResponseNotReady is raised. If the HTTP
1380 response indicates that the connection should be closed, then
1381 it will be closed before the response is returned. When the
1382 connection is closed, the underlying socket is closed.
1383 """
1384
1385 # if a prior response has been completed, then forget about it.
1386 if self.__response and self.__response.isclosed():
1387 self.__response = None
1388
1389 # if a prior response exists, then it must be completed (otherwise, we
1390 # cannot read this response's header to determine the connection-close
1391 # behavior)
1392 #
1393 # note: if a prior response existed, but was connection-close, then the
1394 # socket and response were made independent of this HTTPConnection
1395 # object since a new request requires that we open a whole new
1396 # connection
1397 #
1398 # this means the prior response had one of two states:
1399 # 1) will_close: this connection was reset and the prior socket and
1400 # response operate independently
1401 # 2) persistent: the response was retained and we await its
1402 # isclosed() status to become true.
1403 #
1404 if self.__state != _CS_REQ_SENT or self.__response:
1405 raise ResponseNotReady(self.__state)
1406
1407 if self.debuglevel > 0:
1408 response = self.response_class(self.sock, self.debuglevel,
1409 method=self._method)
1410 else:
1411 response = self.response_class(self.sock, method=self._method)
1412
1413 try:
1414 try:
1415 response.begin()
1416 except ConnectionError:
1417 self.close()
1418 raise
1419 assert response.will_close != _UNKNOWN
1420 self.__state = _CS_IDLE
1421
1422 if response.will_close:
1423 # this effectively passes the connection to the response
1424 self.close()
1425 else:
1426 # remember this, so we can tell when it is complete
1427 self.__response = response
1428
1429 return response
1430 except:
1431 response.close()
1432 raise
1433
1434 try:
1435 import ssl
1436 except ImportError:
1437 pass
1438 else:
1439 class HTTPSConnection(HTTPConnection):
1440 "This class allows communication via SSL."
1441
1442 default_port = HTTPS_PORT
1443
1444 # XXX Should key_file and cert_file be deprecated in favour of context?
1445
1446 def __init__(self, host, port=None, key_file=None, cert_file=None,
1447 timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
1448 source_address=None, *, context=None,
1449 check_hostname=None, blocksize=8192):
1450 super(HTTPSConnection, self).__init__(host, port, timeout,
1451 source_address,
1452 blocksize=blocksize)
1453 if (key_file is not None or cert_file is not None or
1454 check_hostname is not None):
1455 import warnings
1456 warnings.warn("key_file, cert_file and check_hostname are "
1457 "deprecated, use a custom context instead.",
1458 DeprecationWarning, 2)
1459 self.key_file = key_file
1460 self.cert_file = cert_file
1461 if context is None:
1462 context = ssl._create_default_https_context()
1463 # send ALPN extension to indicate HTTP/1.1 protocol
1464 if self._http_vsn == 11:
1465 context.set_alpn_protocols(['http/1.1'])
1466 # enable PHA for TLS 1.3 connections if available
1467 if context.post_handshake_auth is not None:
1468 context.post_handshake_auth = True
1469 will_verify = context.verify_mode != ssl.CERT_NONE
1470 if check_hostname is None:
1471 check_hostname = context.check_hostname
1472 if check_hostname and not will_verify:
1473 raise ValueError("check_hostname needs a SSL context with "
1474 "either CERT_OPTIONAL or CERT_REQUIRED")
1475 if key_file or cert_file:
1476 context.load_cert_chain(cert_file, key_file)
1477 # cert and key file means the user wants to authenticate.
1478 # enable TLS 1.3 PHA implicitly even for custom contexts.
1479 if context.post_handshake_auth is not None:
1480 context.post_handshake_auth = True
1481 self._context = context
1482 if check_hostname is not None:
1483 self._context.check_hostname = check_hostname
1484
1485 def connect(self):
1486 "Connect to a host on a given (SSL) port."
1487
1488 super().connect()
1489
1490 if self._tunnel_host:
1491 server_hostname = self._tunnel_host
1492 else:
1493 server_hostname = self.host
1494
1495 self.sock = self._context.wrap_socket(self.sock,
1496 server_hostname=server_hostname)
1497
1498 __all__.append("HTTPSConnection")
1499
1500 class HTTPException(Exception):
1501 # Subclasses that define an __init__ must call Exception.__init__
1502 # or define self.args. Otherwise, str() will fail.
1503 pass
1504
1505 class NotConnected(HTTPException):
1506 pass
1507
1508 class InvalidURL(HTTPException):
1509 pass
1510
1511 class UnknownProtocol(HTTPException):
1512 def __init__(self, version):
1513 self.args = version,
1514 self.version = version
1515
1516 class UnknownTransferEncoding(HTTPException):
1517 pass
1518
1519 class UnimplementedFileMode(HTTPException):
1520 pass
1521
1522 class IncompleteRead(HTTPException):
1523 def __init__(self, partial, expected=None):
1524 self.args = partial,
1525 self.partial = partial
1526 self.expected = expected
1527 def __repr__(self):
1528 if self.expected is not None:
1529 e = ', %i more expected' % self.expected
1530 else:
1531 e = ''
1532 return '%s(%i bytes read%s)' % (self.__class__.__name__,
1533 len(self.partial), e)
1534 __str__ = object.__str__
1535
1536 class ImproperConnectionState(HTTPException):
1537 pass
1538
1539 class CannotSendRequest(ImproperConnectionState):
1540 pass
1541
1542 class CannotSendHeader(ImproperConnectionState):
1543 pass
1544
1545 class ResponseNotReady(ImproperConnectionState):
1546 pass
1547
1548 class BadStatusLine(HTTPException):
1549 def __init__(self, line):
1550 if not line:
1551 line = repr(line)
1552 self.args = line,
1553 self.line = line
1554
1555 class LineTooLong(HTTPException):
1556 def __init__(self, line_type):
1557 HTTPException.__init__(self, "got more than %d bytes when reading %s"
1558 % (_MAXLINE, line_type))
1559
1560 class RemoteDisconnected(ConnectionResetError, BadStatusLine):
1561 def __init__(self, *pos, **kw):
1562 BadStatusLine.__init__(self, "")
1563 ConnectionResetError.__init__(self, *pos, **kw)
1564
1565 # for backwards compatibility
1566 error = HTTPException