Debian Codegraph @

cpython27/Lib/httplib.py

raw symbols SCIP
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 | response = getresponse()
25 v
26 Unread-response [Response-headers-read]
27 |\____________________
28 | |
29 | response.read() | putrequest()
30 v v
31 Idle Req-started-unread-response
32 ______/|
33 / |
34 response.read() | | ( putheader() )* endheaders()
35 v v
36 Request-started Req-sent-unread-response
37 |
38 | response.read()
39 v
40 Request-sent
41
42 This diagram presents the following rules:
43 -- a second request may not be started until {response-headers-read}
44 -- a response [object] cannot be retrieved until {request-sent}
45 -- there is no differentiation between an unread response body and a
46 partially read response body
47
48 Note: this enforcement is applied by the HTTPConnection class. The
49 HTTPResponse class does not enforce this state machine, which
50 implies sophisticated clients may accelerate the request/response
51 pipeline. Caution should be taken, though: accelerating the states
52 beyond the above pattern may imply knowledge of the server's
53 connection-close behavior for certain requests. For example, it
54 is impossible to tell whether the server will close the connection
55 UNTIL the response headers have been read; this means that further
56 requests cannot be placed into the pipeline until it is known that
57 the server will NOT be closing the connection.
58
59 Logical State __state __response
60 ------------- ------- ----------
61 Idle _CS_IDLE None
62 Request-started _CS_REQ_STARTED None
63 Request-sent _CS_REQ_SENT None
64 Unread-response _CS_IDLE <response_class>
65 Req-started-unread-response _CS_REQ_STARTED <response_class>
66 Req-sent-unread-response _CS_REQ_SENT <response_class>
67 """
68
69 from array import array
70 import os
71 import re
72 import socket
73 from sys import py3kwarning
74 from urlparse import urlsplit
75 import warnings
76 with warnings.catch_warnings():
77 if py3kwarning:
78 warnings.filterwarnings("ignore", ".*mimetools has been removed",
79 DeprecationWarning)
80 import mimetools
81
82 try:
83 from cStringIO import StringIO
84 except ImportError:
85 from StringIO import StringIO
86
87 __all__ = ["HTTP", "HTTPResponse", "HTTPConnection",
88 "HTTPException", "NotConnected", "UnknownProtocol",
89 "UnknownTransferEncoding", "UnimplementedFileMode",
90 "IncompleteRead", "InvalidURL", "ImproperConnectionState",
91 "CannotSendRequest", "CannotSendHeader", "ResponseNotReady",
92 "BadStatusLine", "error", "responses"]
93
94 HTTP_PORT = 80
95 HTTPS_PORT = 443
96
97 _UNKNOWN = 'UNKNOWN'
98
99 # connection states
100 _CS_IDLE = 'Idle'
101 _CS_REQ_STARTED = 'Request-started'
102 _CS_REQ_SENT = 'Request-sent'
103
104 # status codes
105 # informational
106 CONTINUE = 100
107 SWITCHING_PROTOCOLS = 101
108 PROCESSING = 102
109
110 # successful
111 OK = 200
112 CREATED = 201
113 ACCEPTED = 202
114 NON_AUTHORITATIVE_INFORMATION = 203
115 NO_CONTENT = 204
116 RESET_CONTENT = 205
117 PARTIAL_CONTENT = 206
118 MULTI_STATUS = 207
119 IM_USED = 226
120
121 # redirection
122 MULTIPLE_CHOICES = 300
123 MOVED_PERMANENTLY = 301
124 FOUND = 302
125 SEE_OTHER = 303
126 NOT_MODIFIED = 304
127 USE_PROXY = 305
128 TEMPORARY_REDIRECT = 307
129
130 # client error
131 BAD_REQUEST = 400
132 UNAUTHORIZED = 401
133 PAYMENT_REQUIRED = 402
134 FORBIDDEN = 403
135 NOT_FOUND = 404
136 METHOD_NOT_ALLOWED = 405
137 NOT_ACCEPTABLE = 406
138 PROXY_AUTHENTICATION_REQUIRED = 407
139 REQUEST_TIMEOUT = 408
140 CONFLICT = 409
141 GONE = 410
142 LENGTH_REQUIRED = 411
143 PRECONDITION_FAILED = 412
144 REQUEST_ENTITY_TOO_LARGE = 413
145 REQUEST_URI_TOO_LONG = 414
146 UNSUPPORTED_MEDIA_TYPE = 415
147 REQUESTED_RANGE_NOT_SATISFIABLE = 416
148 EXPECTATION_FAILED = 417
149 UNPROCESSABLE_ENTITY = 422
150 LOCKED = 423
151 FAILED_DEPENDENCY = 424
152 UPGRADE_REQUIRED = 426
153
154 # server error
155 INTERNAL_SERVER_ERROR = 500
156 NOT_IMPLEMENTED = 501
157 BAD_GATEWAY = 502
158 SERVICE_UNAVAILABLE = 503
159 GATEWAY_TIMEOUT = 504
160 HTTP_VERSION_NOT_SUPPORTED = 505
161 INSUFFICIENT_STORAGE = 507
162 NOT_EXTENDED = 510
163
164 # Mapping status codes to official W3C names
165 responses = {
166 100: 'Continue',
167 101: 'Switching Protocols',
168
169 200: 'OK',
170 201: 'Created',
171 202: 'Accepted',
172 203: 'Non-Authoritative Information',
173 204: 'No Content',
174 205: 'Reset Content',
175 206: 'Partial Content',
176
177 300: 'Multiple Choices',
178 301: 'Moved Permanently',
179 302: 'Found',
180 303: 'See Other',
181 304: 'Not Modified',
182 305: 'Use Proxy',
183 306: '(Unused)',
184 307: 'Temporary Redirect',
185
186 400: 'Bad Request',
187 401: 'Unauthorized',
188 402: 'Payment Required',
189 403: 'Forbidden',
190 404: 'Not Found',
191 405: 'Method Not Allowed',
192 406: 'Not Acceptable',
193 407: 'Proxy Authentication Required',
194 408: 'Request Timeout',
195 409: 'Conflict',
196 410: 'Gone',
197 411: 'Length Required',
198 412: 'Precondition Failed',
199 413: 'Request Entity Too Large',
200 414: 'Request-URI Too Long',
201 415: 'Unsupported Media Type',
202 416: 'Requested Range Not Satisfiable',
203 417: 'Expectation Failed',
204
205 500: 'Internal Server Error',
206 501: 'Not Implemented',
207 502: 'Bad Gateway',
208 503: 'Service Unavailable',
209 504: 'Gateway Timeout',
210 505: 'HTTP Version Not Supported',
211 }
212
213 # maximal amount of data to read at one time in _safe_read
214 MAXAMOUNT = 1048576
215
216 # maximal line length when calling readline().
217 _MAXLINE = 65536
218
219 # maximum amount of headers accepted
220 _MAXHEADERS = 100
221
222 # Header name/value ABNF (http://tools.ietf.org/html/rfc7230#section-3.2)
223 #
224 # VCHAR = %x21-7E
225 # obs-text = %x80-FF
226 # header-field = field-name ":" OWS field-value OWS
227 # field-name = token
228 # field-value = *( field-content / obs-fold )
229 # field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
230 # field-vchar = VCHAR / obs-text
231 #
232 # obs-fold = CRLF 1*( SP / HTAB )
233 # ; obsolete line folding
234 # ; see Section 3.2.4
235
236 # token = 1*tchar
237 #
238 # tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
239 # / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
240 # / DIGIT / ALPHA
241 # ; any VCHAR, except delimiters
242 #
243 # VCHAR defined in http://tools.ietf.org/html/rfc5234#appendix-B.1
244
245 # the patterns for both name and value are more lenient than RFC
246 # definitions to allow for backwards compatibility
247 _is_legal_header_name = re.compile(r'\A[^:\s][^:\r\n]*\Z').match
248 _is_illegal_header_value = re.compile(r'\n(?![ \t])|\r(?![ \t\n])').search
249
250 # These characters are not allowed within HTTP URL paths.
251 # See https://tools.ietf.org/html/rfc3986#section-3.3 and the
252 # https://tools.ietf.org/html/rfc3986#appendix-A pchar definition.
253 # Prevents CVE-2019-9740. Includes control characters such as \r\n.
254 # Restrict non-ASCII characters above \x7f (0x80-0xff).
255 _contains_disallowed_url_pchar_re = re.compile('[\x00-\x20\x7f-\xff]')
256 # Arguably only these _should_ allowed:
257 # _is_allowed_url_pchars_re = re.compile(r"^[/!$&'()*+,;=:@%a-zA-Z0-9._~-]+$")
258 # We are more lenient for assumed real world compatibility purposes.
259
260 # We always set the Content-Length header for these methods because some
261 # servers will otherwise respond with a 411
262 _METHODS_EXPECTING_BODY = {'PATCH', 'POST', 'PUT'}
263
264
265 class HTTPMessage(mimetools.Message):
266
267 def addheader(self, key, value):
268 """Add header for field key handling repeats."""
269 prev = self.dict.get(key)
270 if prev is None:
271 self.dict[key] = value
272 else:
273 combined = ", ".join((prev, value))
274 self.dict[key] = combined
275
276 def addcontinue(self, key, more):
277 """Add more field data from a continuation line."""
278 prev = self.dict[key]
279 self.dict[key] = prev + "\n " + more
280
281 def readheaders(self):
282 """Read header lines.
283
284 Read header lines up to the entirely blank line that terminates them.
285 The (normally blank) line that ends the headers is skipped, but not
286 included in the returned list. If an invalid line is found in the
287 header section, it is skipped, and further lines are processed.
288
289 The variable self.status is set to the empty string if all went well,
290 otherwise it is an error message. The variable self.headers is a
291 completely uninterpreted list of lines contained in the header (so
292 printing them will reproduce the header exactly as it appears in the
293 file).
294
295 If multiple header fields with the same name occur, they are combined
296 according to the rules in RFC 2616 sec 4.2:
297
298 Appending each subsequent field-value to the first, each separated
299 by a comma. The order in which header fields with the same field-name
300 are received is significant to the interpretation of the combined
301 field value.
302 """
303 # XXX The implementation overrides the readheaders() method of
304 # rfc822.Message. The base class design isn't amenable to
305 # customized behavior here so the method here is a copy of the
306 # base class code with a few small changes.
307
308 self.dict = {}
309 self.unixfrom = ''
310 self.headers = hlist = []
311 self.status = ''
312 headerseen = ""
313 firstline = 1
314 tell = None
315 if not hasattr(self.fp, 'unread') and self.seekable:
316 tell = self.fp.tell
317 while True:
318 if len(hlist) > _MAXHEADERS:
319 raise HTTPException("got more than %d headers" % _MAXHEADERS)
320 if tell:
321 try:
322 tell()
323 except IOError:
324 tell = None
325 self.seekable = 0
326 line = self.fp.readline(_MAXLINE + 1)
327 if len(line) > _MAXLINE:
328 raise LineTooLong("header line")
329 if not line:
330 self.status = 'EOF in headers'
331 break
332 # Skip unix From name time lines
333 if firstline and line.startswith('From '):
334 self.unixfrom = self.unixfrom + line
335 continue
336 firstline = 0
337 if headerseen and line[0] in ' \t':
338 # XXX Not sure if continuation lines are handled properly
339 # for http and/or for repeating headers
340 # It's a continuation line.
341 hlist.append(line)
342 self.addcontinue(headerseen, line.strip())
343 continue
344 elif self.iscomment(line):
345 # It's a comment. Ignore it.
346 continue
347 elif self.islast(line):
348 # Note! No pushback here! The delimiter line gets eaten.
349 break
350 headerseen = self.isheader(line)
351 if headerseen:
352 # It's a legal header line, save it.
353 hlist.append(line)
354 self.addheader(headerseen, line[len(headerseen)+1:].strip())
355 elif headerseen is not None:
356 # An empty header name. These aren't allowed in HTTP, but it's
357 # probably a benign mistake. Don't add the header, just keep
358 # going.
359 pass
360 else:
361 # It's not a header line; skip it and try the next line.
362 self.status = 'Non-header line where header expected'
363
364 class HTTPResponse:
365
366 # strict: If true, raise BadStatusLine if the status line can't be
367 # parsed as a valid HTTP/1.0 or 1.1 status line. By default it is
368 # false because it prevents clients from talking to HTTP/0.9
369 # servers. Note that a response with a sufficiently corrupted
370 # status line will look like an HTTP/0.9 response.
371
372 # See RFC 2616 sec 19.6 and RFC 1945 sec 6 for details.
373
374 def __init__(self, sock, debuglevel=0, strict=0, method=None, buffering=False):
375 if buffering:
376 # The caller won't be using any sock.recv() calls, so buffering
377 # is fine and recommended for performance.
378 self.fp = sock.makefile('rb')
379 else:
380 # The buffer size is specified as zero, because the headers of
381 # the response are read with readline(). If the reads were
382 # buffered the readline() calls could consume some of the
383 # response, which make be read via a recv() on the underlying
384 # socket.
385 self.fp = sock.makefile('rb', 0)
386 self.debuglevel = debuglevel
387 self.strict = strict
388 self._method = method
389
390 self.msg = None
391
392 # from the Status-Line of the response
393 self.version = _UNKNOWN # HTTP-Version
394 self.status = _UNKNOWN # Status-Code
395 self.reason = _UNKNOWN # Reason-Phrase
396
397 self.chunked = _UNKNOWN # is "chunked" being used?
398 self.chunk_left = _UNKNOWN # bytes left to read in current chunk
399 self.length = _UNKNOWN # number of bytes left in response
400 self.will_close = _UNKNOWN # conn will close at end of response
401
402 def _read_status(self):
403 # Initialize with Simple-Response defaults
404 line = self.fp.readline(_MAXLINE + 1)
405 if len(line) > _MAXLINE:
406 raise LineTooLong("header line")
407 if self.debuglevel > 0:
408 print "reply:", repr(line)
409 if not line:
410 # Presumably, the server closed the connection before
411 # sending a valid response.
412 raise BadStatusLine("No status line received - the server has closed the connection")
413 try:
414 [version, status, reason] = line.split(None, 2)
415 except ValueError:
416 try:
417 [version, status] = line.split(None, 1)
418 reason = ""
419 except ValueError:
420 # empty version will cause next test to fail and status
421 # will be treated as 0.9 response.
422 version = ""
423 if not version.startswith('HTTP/'):
424 if self.strict:
425 self.close()
426 raise BadStatusLine(line)
427 else:
428 # assume it's a Simple-Response from an 0.9 server
429 self.fp = LineAndFileWrapper(line, self.fp)
430 return "HTTP/0.9", 200, ""
431
432 # The status code is a three-digit number
433 try:
434 status = int(status)
435 if status < 100 or status > 999:
436 raise BadStatusLine(line)
437 except ValueError:
438 raise BadStatusLine(line)
439 return version, status, reason
440
441 def begin(self):
442 if self.msg is not None:
443 # we've already started reading the response
444 return
445
446 # read until we get a non-100 response
447 while True:
448 version, status, reason = self._read_status()
449 if status != CONTINUE:
450 break
451 # skip the header from the 100 response
452 while True:
453 skip = self.fp.readline(_MAXLINE + 1)
454 if len(skip) > _MAXLINE:
455 raise LineTooLong("header line")
456 skip = skip.strip()
457 if not skip:
458 break
459 if self.debuglevel > 0:
460 print "header:", skip
461
462 self.status = status
463 self.reason = reason.strip()
464 if version == 'HTTP/1.0':
465 self.version = 10
466 elif version.startswith('HTTP/1.'):
467 self.version = 11 # use HTTP/1.1 code for HTTP/1.x where x>=1
468 elif version == 'HTTP/0.9':
469 self.version = 9
470 else:
471 raise UnknownProtocol(version)
472
473 if self.version == 9:
474 self.length = None
475 self.chunked = 0
476 self.will_close = 1
477 self.msg = HTTPMessage(StringIO())
478 return
479
480 self.msg = HTTPMessage(self.fp, 0)
481 if self.debuglevel > 0:
482 for hdr in self.msg.headers:
483 print "header:", hdr,
484
485 # don't let the msg keep an fp
486 self.msg.fp = None
487
488 # are we using the chunked-style of transfer encoding?
489 tr_enc = self.msg.getheader('transfer-encoding')
490 if tr_enc and tr_enc.lower() == "chunked":
491 self.chunked = 1
492 self.chunk_left = None
493 else:
494 self.chunked = 0
495
496 # will the connection close at the end of the response?
497 self.will_close = self._check_close()
498
499 # do we have a Content-Length?
500 # NOTE: RFC 2616, S4.4, #3 says we ignore this if tr_enc is "chunked"
501 length = self.msg.getheader('content-length')
502 if length and not self.chunked:
503 try:
504 self.length = int(length)
505 except ValueError:
506 self.length = None
507 else:
508 if self.length < 0: # ignore nonsensical negative lengths
509 self.length = None
510 else:
511 self.length = None
512
513 # does the body have a fixed length? (of zero)
514 if (status == NO_CONTENT or status == NOT_MODIFIED or
515 100 <= status < 200 or # 1xx codes
516 self._method == 'HEAD'):
517 self.length = 0
518
519 # if the connection remains open, and we aren't using chunked, and
520 # a content-length was not provided, then assume that the connection
521 # WILL close.
522 if not self.will_close and \
523 not self.chunked and \
524 self.length is None:
525 self.will_close = 1
526
527 def _check_close(self):
528 conn = self.msg.getheader('connection')
529 if self.version == 11:
530 # An HTTP/1.1 proxy is assumed to stay open unless
531 # explicitly closed.
532 conn = self.msg.getheader('connection')
533 if conn and "close" in conn.lower():
534 return True
535 return False
536
537 # Some HTTP/1.0 implementations have support for persistent
538 # connections, using rules different than HTTP/1.1.
539
540 # For older HTTP, Keep-Alive indicates persistent connection.
541 if self.msg.getheader('keep-alive'):
542 return False
543
544 # At least Akamai returns a "Connection: Keep-Alive" header,
545 # which was supposed to be sent by the client.
546 if conn and "keep-alive" in conn.lower():
547 return False
548
549 # Proxy-Connection is a netscape hack.
550 pconn = self.msg.getheader('proxy-connection')
551 if pconn and "keep-alive" in pconn.lower():
552 return False
553
554 # otherwise, assume it will close
555 return True
556
557 def close(self):
558 fp = self.fp
559 if fp:
560 self.fp = None
561 fp.close()
562
563 def isclosed(self):
564 # NOTE: it is possible that we will not ever call self.close(). This
565 # case occurs when will_close is TRUE, length is None, and we
566 # read up to the last byte, but NOT past it.
567 #
568 # IMPLIES: if will_close is FALSE, then self.close() will ALWAYS be
569 # called, meaning self.isclosed() is meaningful.
570 return self.fp is None
571
572 # XXX It would be nice to have readline and __iter__ for this, too.
573
574 def read(self, amt=None):
575 if self.fp is None:
576 return ''
577
578 if self._method == 'HEAD':
579 self.close()
580 return ''
581
582 if self.chunked:
583 return self._read_chunked(amt)
584
585 if amt is None:
586 # unbounded read
587 if self.length is None:
588 s = self.fp.read()
589 else:
590 try:
591 s = self._safe_read(self.length)
592 except IncompleteRead:
593 self.close()
594 raise
595 self.length = 0
596 self.close() # we read everything
597 return s
598
599 if self.length is not None:
600 if amt > self.length:
601 # clip the read to the "end of response"
602 amt = self.length
603
604 # we do not use _safe_read() here because this may be a .will_close
605 # connection, and the user is reading more bytes than will be provided
606 # (for example, reading in 1k chunks)
607 s = self.fp.read(amt)
608 if not s and amt:
609 # Ideally, we would raise IncompleteRead if the content-length
610 # wasn't satisfied, but it might break compatibility.
611 self.close()
612 if self.length is not None:
613 self.length -= len(s)
614 if not self.length:
615 self.close()
616
617 return s
618
619 def _read_chunked(self, amt):
620 assert self.chunked != _UNKNOWN
621 chunk_left = self.chunk_left
622 value = []
623 while True:
624 if chunk_left is None:
625 line = self.fp.readline(_MAXLINE + 1)
626 if len(line) > _MAXLINE:
627 raise LineTooLong("chunk size")
628 i = line.find(';')
629 if i >= 0:
630 line = line[:i] # strip chunk-extensions
631 try:
632 chunk_left = int(line, 16)
633 except ValueError:
634 # close the connection as protocol synchronisation is
635 # probably lost
636 self.close()
637 raise IncompleteRead(''.join(value))
638 if chunk_left == 0:
639 break
640 if amt is None:
641 value.append(self._safe_read(chunk_left))
642 elif amt < chunk_left:
643 value.append(self._safe_read(amt))
644 self.chunk_left = chunk_left - amt
645 return ''.join(value)
646 elif amt == chunk_left:
647 value.append(self._safe_read(amt))
648 self._safe_read(2) # toss the CRLF at the end of the chunk
649 self.chunk_left = None
650 return ''.join(value)
651 else:
652 value.append(self._safe_read(chunk_left))
653 amt -= chunk_left
654
655 # we read the whole chunk, get another
656 self._safe_read(2) # toss the CRLF at the end of the chunk
657 chunk_left = None
658
659 # read and discard trailer up to the CRLF terminator
660 ### note: we shouldn't have any trailers!
661 while True:
662 line = self.fp.readline(_MAXLINE + 1)
663 if len(line) > _MAXLINE:
664 raise LineTooLong("trailer line")
665 if not line:
666 # a vanishingly small number of sites EOF without
667 # sending the trailer
668 break
669 if line == '\r\n':
670 break
671
672 # we read everything; close the "file"
673 self.close()
674
675 return ''.join(value)
676
677 def _safe_read(self, amt):
678 """Read the number of bytes requested, compensating for partial reads.
679
680 Normally, we have a blocking socket, but a read() can be interrupted
681 by a signal (resulting in a partial read).
682
683 Note that we cannot distinguish between EOF and an interrupt when zero
684 bytes have been read. IncompleteRead() will be raised in this
685 situation.
686
687 This function should be used when <amt> bytes "should" be present for
688 reading. If the bytes are truly not available (due to EOF), then the
689 IncompleteRead exception can be used to detect the problem.
690 """
691 # NOTE(gps): As of svn r74426 socket._fileobject.read(x) will never
692 # return less than x bytes unless EOF is encountered. It now handles
693 # signal interruptions (socket.error EINTR) internally. This code
694 # never caught that exception anyways. It seems largely pointless.
695 # self.fp.read(amt) will work fine.
696 s = []
697 while amt > 0:
698 chunk = self.fp.read(min(amt, MAXAMOUNT))
699 if not chunk:
700 raise IncompleteRead(''.join(s), amt)
701 s.append(chunk)
702 amt -= len(chunk)
703 return ''.join(s)
704
705 def fileno(self):
706 return self.fp.fileno()
707
708 def getheader(self, name, default=None):
709 if self.msg is None:
710 raise ResponseNotReady()
711 return self.msg.getheader(name, default)
712
713 def getheaders(self):
714 """Return list of (header, value) tuples."""
715 if self.msg is None:
716 raise ResponseNotReady()
717 return self.msg.items()
718
719
720 class HTTPConnection:
721
722 _http_vsn = 11
723 _http_vsn_str = 'HTTP/1.1'
724
725 response_class = HTTPResponse
726 default_port = HTTP_PORT
727 auto_open = 1
728 debuglevel = 0
729 strict = 0
730
731 def __init__(self, host, port=None, strict=None,
732 timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None):
733 self.timeout = timeout
734 self.source_address = source_address
735 self.sock = None
736 self._buffer = []
737 self.__response = None
738 self.__state = _CS_IDLE
739 self._method = None
740 self._tunnel_host = None
741 self._tunnel_port = None
742 self._tunnel_headers = {}
743 if strict is not None:
744 self.strict = strict
745
746 (self.host, self.port) = self._get_hostport(host, port)
747
748 self._validate_host(self.host)
749
750 # This is stored as an instance variable to allow unittests
751 # to replace with a suitable mock
752 self._create_connection = socket.create_connection
753
754 def set_tunnel(self, host, port=None, headers=None):
755 """ Set up host and port for HTTP CONNECT tunnelling.
756
757 In a connection that uses HTTP Connect tunneling, the host passed to the
758 constructor is used as proxy server that relays all communication to the
759 endpoint passed to set_tunnel. This is done by sending a HTTP CONNECT
760 request to the proxy server when the connection is established.
761
762 This method must be called before the HTTP connection has been
763 established.
764
765 The headers argument should be a mapping of extra HTTP headers
766 to send with the CONNECT request.
767 """
768 # Verify if this is required.
769 if self.sock:
770 raise RuntimeError("Can't setup tunnel for established connection.")
771
772 self._tunnel_host, self._tunnel_port = self._get_hostport(host, port)
773 if headers:
774 self._tunnel_headers = headers
775 else:
776 self._tunnel_headers.clear()
777
778 def _get_hostport(self, host, port):
779 if port is None:
780 i = host.rfind(':')
781 j = host.rfind(']') # ipv6 addresses have [...]
782 if i > j:
783 try:
784 port = int(host[i+1:])
785 except ValueError:
786 if host[i+1:] == "": # http://foo.com:/ == http://foo.com/
787 port = self.default_port
788 else:
789 raise InvalidURL("nonnumeric port: '%s'" % host[i+1:])
790 host = host[:i]
791 else:
792 port = self.default_port
793 if host and host[0] == '[' and host[-1] == ']':
794 host = host[1:-1]
795 return (host, port)
796
797 def set_debuglevel(self, level):
798 self.debuglevel = level
799
800 def _tunnel(self):
801 self.send("CONNECT %s:%d HTTP/1.0\r\n" % (self._tunnel_host,
802 self._tunnel_port))
803 for header, value in self._tunnel_headers.iteritems():
804 self.send("%s: %s\r\n" % (header, value))
805 self.send("\r\n")
806 response = self.response_class(self.sock, strict = self.strict,
807 method = self._method)
808 (version, code, message) = response._read_status()
809
810 if version == "HTTP/0.9":
811 # HTTP/0.9 doesn't support the CONNECT verb, so if httplib has
812 # concluded HTTP/0.9 is being used something has gone wrong.
813 self.close()
814 raise socket.error("Invalid response from tunnel request")
815 if code != 200:
816 self.close()
817 raise socket.error("Tunnel connection failed: %d %s" % (code,
818 message.strip()))
819 while True:
820 line = response.fp.readline(_MAXLINE + 1)
821 if len(line) > _MAXLINE:
822 raise LineTooLong("header line")
823 if not line:
824 # for sites which EOF without sending trailer
825 break
826 if line == '\r\n':
827 break
828
829
830 def connect(self):
831 """Connect to the host and port specified in __init__."""
832 self.sock = self._create_connection((self.host,self.port),
833 self.timeout, self.source_address)
834
835 if self._tunnel_host:
836 self._tunnel()
837
838 def close(self):
839 """Close the connection to the HTTP server."""
840 self.__state = _CS_IDLE
841 try:
842 sock = self.sock
843 if sock:
844 self.sock = None
845 sock.close() # close it manually... there may be other refs
846 finally:
847 response = self.__response
848 if response:
849 self.__response = None
850 response.close()
851
852 def send(self, data):
853 """Send `data' to the server."""
854 if self.sock is None:
855 if self.auto_open:
856 self.connect()
857 else:
858 raise NotConnected()
859
860 if self.debuglevel > 0:
861 print "send:", repr(data)
862 blocksize = 8192
863 if hasattr(data,'read') and not isinstance(data, array):
864 if self.debuglevel > 0: print "sendIng a read()able"
865 datablock = data.read(blocksize)
866 while datablock:
867 self.sock.sendall(datablock)
868 datablock = data.read(blocksize)
869 else:
870 self.sock.sendall(data)
871
872 def _output(self, s):
873 """Add a line of output to the current request buffer.
874
875 Assumes that the line does *not* end with \\r\\n.
876 """
877 self._buffer.append(s)
878
879 def _send_output(self, message_body=None):
880 """Send the currently buffered request and clear the buffer.
881
882 Appends an extra \\r\\n to the buffer.
883 A message_body may be specified, to be appended to the request.
884 """
885 self._buffer.extend(("", ""))
886 msg = "\r\n".join(self._buffer)
887 del self._buffer[:]
888 # If msg and message_body are sent in a single send() call,
889 # it will avoid performance problems caused by the interaction
890 # between delayed ack and the Nagle algorithm.
891 if isinstance(message_body, str):
892 msg += message_body
893 message_body = None
894 self.send(msg)
895 if message_body is not None:
896 #message_body was not a string (i.e. it is a file) and
897 #we must run the risk of Nagle
898 self.send(message_body)
899
900 def putrequest(self, method, url, skip_host=0, skip_accept_encoding=0):
901 """Send a request to the server.
902
903 `method' specifies an HTTP request method, e.g. 'GET'.
904 `url' specifies the object being requested, e.g. '/index.html'.
905 `skip_host' if True does not add automatically a 'Host:' header
906 `skip_accept_encoding' if True does not add automatically an
907 'Accept-Encoding:' header
908 """
909
910 # if a prior response has been completed, then forget about it.
911 if self.__response and self.__response.isclosed():
912 self.__response = None
913
914
915 # in certain cases, we cannot issue another request on this connection.
916 # this occurs when:
917 # 1) we are in the process of sending a request. (_CS_REQ_STARTED)
918 # 2) a response to a previous request has signalled that it is going
919 # to close the connection upon completion.
920 # 3) the headers for the previous response have not been read, thus
921 # we cannot determine whether point (2) is true. (_CS_REQ_SENT)
922 #
923 # if there is no prior response, then we can request at will.
924 #
925 # if point (2) is true, then we will have passed the socket to the
926 # response (effectively meaning, "there is no prior response"), and
927 # will open a new one when a new request is made.
928 #
929 # Note: if a prior response exists, then we *can* start a new request.
930 # We are not allowed to begin fetching the response to this new
931 # request, however, until that prior response is complete.
932 #
933 if self.__state == _CS_IDLE:
934 self.__state = _CS_REQ_STARTED
935 else:
936 raise CannotSendRequest()
937
938 # Save the method for use later in the response phase
939 self._method = method
940
941 url = url or '/'
942 self._validate_path(url)
943
944 request = '%s %s %s' % (method, url, self._http_vsn_str)
945
946 self._output(self._encode_request(request))
947
948 if self._http_vsn == 11:
949 # Issue some standard headers for better HTTP/1.1 compliance
950
951 if not skip_host:
952 # this header is issued *only* for HTTP/1.1
953 # connections. more specifically, this means it is
954 # only issued when the client uses the new
955 # HTTPConnection() class. backwards-compat clients
956 # will be using HTTP/1.0 and those clients may be
957 # issuing this header themselves. we should NOT issue
958 # it twice; some web servers (such as Apache) barf
959 # when they see two Host: headers
960
961 # If we need a non-standard port,include it in the
962 # header. If the request is going through a proxy,
963 # but the host of the actual URL, not the host of the
964 # proxy.
965
966 netloc = ''
967 if url.startswith('http'):
968 nil, netloc, nil, nil, nil = urlsplit(url)
969
970 if netloc:
971 try:
972 netloc_enc = netloc.encode("ascii")
973 except UnicodeEncodeError:
974 netloc_enc = netloc.encode("idna")
975 self.putheader('Host', netloc_enc)
976 else:
977 if self._tunnel_host:
978 host = self._tunnel_host
979 port = self._tunnel_port
980 else:
981 host = self.host
982 port = self.port
983
984 try:
985 host_enc = host.encode("ascii")
986 except UnicodeEncodeError:
987 host_enc = host.encode("idna")
988 # Wrap the IPv6 Host Header with [] (RFC 2732)
989 if host_enc.find(':') >= 0:
990 host_enc = "[" + host_enc + "]"
991 if port == self.default_port:
992 self.putheader('Host', host_enc)
993 else:
994 self.putheader('Host', "%s:%s" % (host_enc, port))
995
996 # note: we are assuming that clients will not attempt to set these
997 # headers since *this* library must deal with the
998 # consequences. this also means that when the supporting
999 # libraries are updated to recognize other forms, then this
1000 # code should be changed (removed or updated).
1001
1002 # we only want a Content-Encoding of "identity" since we don't
1003 # support encodings such as x-gzip or x-deflate.
1004 if not skip_accept_encoding:
1005 self.putheader('Accept-Encoding', 'identity')
1006
1007 # we can accept "chunked" Transfer-Encodings, but no others
1008 # NOTE: no TE header implies *only* "chunked"
1009 #self.putheader('TE', 'chunked')
1010
1011 # if TE is supplied in the header, then it must appear in a
1012 # Connection header.
1013 #self.putheader('Connection', 'TE')
1014
1015 else:
1016 # For HTTP/1.0, the server will assume "not chunked"
1017 pass
1018
1019 def _encode_request(self, request):
1020 # On Python 2, request is already encoded (default)
1021 return request
1022
1023 def _validate_path(self, url):
1024 """Validate a url for putrequest."""
1025 # Prevent CVE-2019-9740.
1026 match = _contains_disallowed_url_pchar_re.search(url)
1027 if match:
1028 msg = (
1029 "URL can't contain control characters. {url!r} "
1030 "(found at least {matched!r})"
1031 ).format(matched=match.group(), url=url)
1032 raise InvalidURL(msg)
1033
1034 def _validate_host(self, host):
1035 """Validate a host so it doesn't contain control characters."""
1036 # Prevent CVE-2019-18348.
1037 match = _contains_disallowed_url_pchar_re.search(host)
1038 if match:
1039 msg = (
1040 "URL can't contain control characters. {host!r} "
1041 "(found at least {matched!r})"
1042 ).format(matched=match.group(), host=host)
1043 raise InvalidURL(msg)
1044
1045 def putheader(self, header, *values):
1046 """Send a request header line to the server.
1047
1048 For example: h.putheader('Accept', 'text/html')
1049 """
1050 if self.__state != _CS_REQ_STARTED:
1051 raise CannotSendHeader()
1052
1053 header = '%s' % header
1054 if not _is_legal_header_name(header):
1055 raise ValueError('Invalid header name %r' % (header,))
1056
1057 values = [str(v) for v in values]
1058 for one_value in values:
1059 if _is_illegal_header_value(one_value):
1060 raise ValueError('Invalid header value %r' % (one_value,))
1061
1062 hdr = '%s: %s' % (header, '\r\n\t'.join(values))
1063 self._output(hdr)
1064
1065 def endheaders(self, message_body=None):
1066 """Indicate that the last header line has been sent to the server.
1067
1068 This method sends the request to the server. The optional
1069 message_body argument can be used to pass a message body
1070 associated with the request. The message body will be sent in
1071 the same packet as the message headers if it is string, otherwise it is
1072 sent as a separate packet.
1073 """
1074 if self.__state == _CS_REQ_STARTED:
1075 self.__state = _CS_REQ_SENT
1076 else:
1077 raise CannotSendHeader()
1078 self._send_output(message_body)
1079
1080 def request(self, method, url, body=None, headers={}):
1081 """Send a complete request to the server."""
1082 self._send_request(method, url, body, headers)
1083
1084 def _set_content_length(self, body, method):
1085 # Set the content-length based on the body. If the body is "empty", we
1086 # set Content-Length: 0 for methods that expect a body (RFC 7230,
1087 # Section 3.3.2). If the body is set for other methods, we set the
1088 # header provided we can figure out what the length is.
1089 thelen = None
1090 if body is None and method.upper() in _METHODS_EXPECTING_BODY:
1091 thelen = '0'
1092 elif body is not None:
1093 try:
1094 thelen = str(len(body))
1095 except (TypeError, AttributeError):
1096 # If this is a file-like object, try to
1097 # fstat its file descriptor
1098 try:
1099 thelen = str(os.fstat(body.fileno()).st_size)
1100 except (AttributeError, OSError):
1101 # Don't send a length if this failed
1102 if self.debuglevel > 0: print "Cannot stat!!"
1103
1104 if thelen is not None:
1105 self.putheader('Content-Length', thelen)
1106
1107 def _send_request(self, method, url, body, headers):
1108 # Honor explicitly requested Host: and Accept-Encoding: headers.
1109 header_names = dict.fromkeys([k.lower() for k in headers])
1110 skips = {}
1111 if 'host' in header_names:
1112 skips['skip_host'] = 1
1113 if 'accept-encoding' in header_names:
1114 skips['skip_accept_encoding'] = 1
1115
1116 self.putrequest(method, url, **skips)
1117
1118 if 'content-length' not in header_names:
1119 self._set_content_length(body, method)
1120 for hdr, value in headers.iteritems():
1121 self.putheader(hdr, value)
1122 self.endheaders(body)
1123
1124 def getresponse(self, buffering=False):
1125 "Get the response from the server."
1126
1127 # if a prior response has been completed, then forget about it.
1128 if self.__response and self.__response.isclosed():
1129 self.__response = None
1130
1131 #
1132 # if a prior response exists, then it must be completed (otherwise, we
1133 # cannot read this response's header to determine the connection-close
1134 # behavior)
1135 #
1136 # note: if a prior response existed, but was connection-close, then the
1137 # socket and response were made independent of this HTTPConnection
1138 # object since a new request requires that we open a whole new
1139 # connection
1140 #
1141 # this means the prior response had one of two states:
1142 # 1) will_close: this connection was reset and the prior socket and
1143 # response operate independently
1144 # 2) persistent: the response was retained and we await its
1145 # isclosed() status to become true.
1146 #
1147 if self.__state != _CS_REQ_SENT or self.__response:
1148 raise ResponseNotReady()
1149
1150 args = (self.sock,)
1151 kwds = {"strict":self.strict, "method":self._method}
1152 if self.debuglevel > 0:
1153 args += (self.debuglevel,)
1154 if buffering:
1155 #only add this keyword if non-default, for compatibility with
1156 #other response_classes.
1157 kwds["buffering"] = True;
1158 response = self.response_class(*args, **kwds)
1159
1160 try:
1161 response.begin()
1162 assert response.will_close != _UNKNOWN
1163 self.__state = _CS_IDLE
1164
1165 if response.will_close:
1166 # this effectively passes the connection to the response
1167 self.close()
1168 else:
1169 # remember this, so we can tell when it is complete
1170 self.__response = response
1171
1172 return response
1173 except:
1174 response.close()
1175 raise
1176
1177
1178 class HTTP:
1179 "Compatibility class with httplib.py from 1.5."
1180
1181 _http_vsn = 10
1182 _http_vsn_str = 'HTTP/1.0'
1183
1184 debuglevel = 0
1185
1186 _connection_class = HTTPConnection
1187
1188 def __init__(self, host='', port=None, strict=None):
1189 "Provide a default host, since the superclass requires one."
1190
1191 # some joker passed 0 explicitly, meaning default port
1192 if port == 0:
1193 port = None
1194
1195 # Note that we may pass an empty string as the host; this will raise
1196 # an error when we attempt to connect. Presumably, the client code
1197 # will call connect before then, with a proper host.
1198 self._setup(self._connection_class(host, port, strict))
1199
1200 def _setup(self, conn):
1201 self._conn = conn
1202
1203 # set up delegation to flesh out interface
1204 self.send = conn.send
1205 self.putrequest = conn.putrequest
1206 self.putheader = conn.putheader
1207 self.endheaders = conn.endheaders
1208 self.set_debuglevel = conn.set_debuglevel
1209
1210 conn._http_vsn = self._http_vsn
1211 conn._http_vsn_str = self._http_vsn_str
1212
1213 self.file = None
1214
1215 def connect(self, host=None, port=None):
1216 "Accept arguments to set the host/port, since the superclass doesn't."
1217
1218 if host is not None:
1219 (self._conn.host, self._conn.port) = self._conn._get_hostport(host, port)
1220 self._conn.connect()
1221
1222 def getfile(self):
1223 "Provide a getfile, since the superclass' does not use this concept."
1224 return self.file
1225
1226 def getreply(self, buffering=False):
1227 """Compat definition since superclass does not define it.
1228
1229 Returns a tuple consisting of:
1230 - server status code (e.g. '200' if all goes well)
1231 - server "reason" corresponding to status code
1232 - any RFC822 headers in the response from the server
1233 """
1234 try:
1235 if not buffering:
1236 response = self._conn.getresponse()
1237 else:
1238 #only add this keyword if non-default for compatibility
1239 #with other connection classes
1240 response = self._conn.getresponse(buffering)
1241 except BadStatusLine, e:
1242 ### hmm. if getresponse() ever closes the socket on a bad request,
1243 ### then we are going to have problems with self.sock
1244
1245 ### should we keep this behavior? do people use it?
1246 # keep the socket open (as a file), and return it
1247 self.file = self._conn.sock.makefile('rb', 0)
1248
1249 # close our socket -- we want to restart after any protocol error
1250 self.close()
1251
1252 self.headers = None
1253 return -1, e.line, None
1254
1255 self.headers = response.msg
1256 self.file = response.fp
1257 return response.status, response.reason, response.msg
1258
1259 def close(self):
1260 self._conn.close()
1261
1262 # note that self.file == response.fp, which gets closed by the
1263 # superclass. just clear the object ref here.
1264 ### hmm. messy. if status==-1, then self.file is owned by us.
1265 ### well... we aren't explicitly closing, but losing this ref will
1266 ### do it
1267 self.file = None
1268
1269 try:
1270 import ssl
1271 except ImportError:
1272 pass
1273 else:
1274 class HTTPSConnection(HTTPConnection):
1275 "This class allows communication via SSL."
1276
1277 default_port = HTTPS_PORT
1278
1279 def __init__(self, host, port=None, key_file=None, cert_file=None,
1280 strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
1281 source_address=None, context=None):
1282 HTTPConnection.__init__(self, host, port, strict, timeout,
1283 source_address)
1284 self.key_file = key_file
1285 self.cert_file = cert_file
1286 if context is None:
1287 context = ssl._create_default_https_context()
1288 if key_file or cert_file:
1289 context.load_cert_chain(cert_file, key_file)
1290 self._context = context
1291
1292 def connect(self):
1293 "Connect to a host on a given (SSL) port."
1294
1295 HTTPConnection.connect(self)
1296
1297 if self._tunnel_host:
1298 server_hostname = self._tunnel_host
1299 else:
1300 server_hostname = self.host
1301
1302 self.sock = self._context.wrap_socket(self.sock,
1303 server_hostname=server_hostname)
1304
1305 __all__.append("HTTPSConnection")
1306
1307 class HTTPS(HTTP):
1308 """Compatibility with 1.5 httplib interface
1309
1310 Python 1.5.2 did not have an HTTPS class, but it defined an
1311 interface for sending http requests that is also useful for
1312 https.
1313 """
1314
1315 _connection_class = HTTPSConnection
1316
1317 def __init__(self, host='', port=None, key_file=None, cert_file=None,
1318 strict=None, context=None):
1319 # provide a default host, pass the X509 cert info
1320
1321 # urf. compensate for bad input.
1322 if port == 0:
1323 port = None
1324 self._setup(self._connection_class(host, port, key_file,
1325 cert_file, strict,
1326 context=context))
1327
1328 # we never actually use these for anything, but we keep them
1329 # here for compatibility with post-1.5.2 CVS.
1330 self.key_file = key_file
1331 self.cert_file = cert_file
1332
1333
1334 def FakeSocket (sock, sslobj):
1335 warnings.warn("FakeSocket is deprecated, and won't be in 3.x. " +
1336 "Use the result of ssl.wrap_socket() directly instead.",
1337 DeprecationWarning, stacklevel=2)
1338 return sslobj
1339
1340
1341 class HTTPException(Exception):
1342 # Subclasses that define an __init__ must call Exception.__init__
1343 # or define self.args. Otherwise, str() will fail.
1344 pass
1345
1346 class NotConnected(HTTPException):
1347 pass
1348
1349 class InvalidURL(HTTPException):
1350 pass
1351
1352 class UnknownProtocol(HTTPException):
1353 def __init__(self, version):
1354 self.args = version,
1355 self.version = version
1356
1357 class UnknownTransferEncoding(HTTPException):
1358 pass
1359
1360 class UnimplementedFileMode(HTTPException):
1361 pass
1362
1363 class IncompleteRead(HTTPException):
1364 def __init__(self, partial, expected=None):
1365 self.args = partial,
1366 self.partial = partial
1367 self.expected = expected
1368 def __repr__(self):
1369 if self.expected is not None:
1370 e = ', %i more expected' % self.expected
1371 else:
1372 e = ''
1373 return 'IncompleteRead(%i bytes read%s)' % (len(self.partial), e)
1374 def __str__(self):
1375 return repr(self)
1376
1377 class ImproperConnectionState(HTTPException):
1378 pass
1379
1380 class CannotSendRequest(ImproperConnectionState):
1381 pass
1382
1383 class CannotSendHeader(ImproperConnectionState):
1384 pass
1385
1386 class ResponseNotReady(ImproperConnectionState):
1387 pass
1388
1389 class BadStatusLine(HTTPException):
1390 def __init__(self, line):
1391 if not line:
1392 line = repr(line)
1393 self.args = line,
1394 self.line = line
1395
1396 class LineTooLong(HTTPException):
1397 def __init__(self, line_type):
1398 HTTPException.__init__(self, "got more than %d bytes when reading %s"
1399 % (_MAXLINE, line_type))
1400
1401 # for backwards compatibility
1402 error = HTTPException
1403
1404 class LineAndFileWrapper:
1405 """A limited file-like object for HTTP/0.9 responses."""
1406
1407 # The status-line parsing code calls readline(), which normally
1408 # get the HTTP status line. For a 0.9 response, however, this is
1409 # actually the first line of the body! Clients need to get a
1410 # readable file object that contains that line.
1411
1412 def __init__(self, line, file):
1413 self._line = line
1414 self._file = file
1415 self._line_consumed = 0
1416 self._line_offset = 0
1417 self._line_left = len(line)
1418
1419 def __getattr__(self, attr):
1420 return getattr(self._file, attr)
1421
1422 def _done(self):
1423 # called when the last byte is read from the line. After the
1424 # call, all read methods are delegated to the underlying file
1425 # object.
1426 self._line_consumed = 1
1427 self.read = self._file.read
1428 self.readline = self._file.readline
1429 self.readlines = self._file.readlines
1430
1431 def read(self, amt=None):
1432 if self._line_consumed:
1433 return self._file.read(amt)
1434 assert self._line_left
1435 if amt is None or amt > self._line_left:
1436 s = self._line[self._line_offset:]
1437 self._done()
1438 if amt is None:
1439 return s + self._file.read()
1440 else:
1441 return s + self._file.read(amt - len(s))
1442 else:
1443 assert amt <= self._line_left
1444 i = self._line_offset
1445 j = i + amt
1446 s = self._line[i:j]
1447 self._line_offset = j
1448 self._line_left -= amt
1449 if self._line_left == 0:
1450 self._done()
1451 return s
1452
1453 def readline(self):
1454 if self._line_consumed:
1455 return self._file.readline()
1456 assert self._line_left
1457 s = self._line[self._line_offset:]
1458 self._done()
1459 return s
1460
1461 def readlines(self, size=None):
1462 if self._line_consumed:
1463 return self._file.readlines(size)
1464 assert self._line_left
1465 L = [self._line[self._line_offset:]]
1466 self._done()
1467 if size is None:
1468 return L + self._file.readlines()
1469 else:
1470 return L + self._file.readlines(size)