blob: 6547f859ee6484c2b7c808ca095484cb70eba38a [file] [log] [blame]
Greg Stein5e0fa402000-06-26 08:28:01 +00001"""HTTP/1.1 client library
Guido van Rossum41999c11997-12-09 00:12:23 +00002
Greg Stein5e0fa402000-06-26 08:28:01 +00003<intro stuff goes here>
4<other stuff, too>
Guido van Rossum41999c11997-12-09 00:12:23 +00005
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006HTTPConnection goes through a number of "states", which define when a client
Greg Stein5e0fa402000-06-26 08:28:01 +00007may legally make another request or fetch the response for a particular
8request. This diagram details these state transitions:
Guido van Rossum41999c11997-12-09 00:12:23 +00009
Greg Stein5e0fa402000-06-26 08:28:01 +000010 (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 |\____________________
Tim Peters5ceadc82001-01-13 19:16:21 +000028 | |
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
Greg Stein5e0fa402000-06-26 08:28:01 +000041
42This 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
48Note: 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
59Logical State __state __response
60------------- ------- ----------
61Idle _CS_IDLE None
62Request-started _CS_REQ_STARTED None
63Request-sent _CS_REQ_SENT None
64Unread-response _CS_IDLE <response_class>
65Req-started-unread-response _CS_REQ_STARTED <response_class>
66Req-sent-unread-response _CS_REQ_SENT <response_class>
Guido van Rossum41999c11997-12-09 00:12:23 +000067"""
Guido van Rossum23acc951994-02-21 16:36:04 +000068
Barry Warsaw820c1202008-06-12 04:06:45 +000069import email.parser
70import email.message
Jeremy Hylton636950f2009-03-28 04:34:21 +000071import io
72import os
73import socket
Jeremy Hylton1afc1692008-06-18 20:49:58 +000074from urllib.parse import urlsplit
Thomas Wouters89d996e2007-09-08 17:39:28 +000075import warnings
Guido van Rossum23acc951994-02-21 16:36:04 +000076
Thomas Wouters47b49bf2007-08-30 22:15:33 +000077__all__ = ["HTTPResponse", "HTTPConnection",
Skip Montanaro951a8842001-06-01 16:25:38 +000078 "HTTPException", "NotConnected", "UnknownProtocol",
Jeremy Hylton7c75c992002-06-28 23:38:14 +000079 "UnknownTransferEncoding", "UnimplementedFileMode",
80 "IncompleteRead", "InvalidURL", "ImproperConnectionState",
81 "CannotSendRequest", "CannotSendHeader", "ResponseNotReady",
Georg Brandl6aab16e2006-02-17 19:17:25 +000082 "BadStatusLine", "error", "responses"]
Skip Montanaro2dd42762001-01-23 15:35:05 +000083
Guido van Rossum23acc951994-02-21 16:36:04 +000084HTTP_PORT = 80
Guido van Rossum09c8b6c1999-12-07 21:37:17 +000085HTTPS_PORT = 443
86
Greg Stein5e0fa402000-06-26 08:28:01 +000087_UNKNOWN = 'UNKNOWN'
88
89# connection states
90_CS_IDLE = 'Idle'
91_CS_REQ_STARTED = 'Request-started'
92_CS_REQ_SENT = 'Request-sent'
93
Martin v. Löwis39a31782004-09-18 09:03:49 +000094# status codes
95# informational
96CONTINUE = 100
97SWITCHING_PROTOCOLS = 101
98PROCESSING = 102
99
100# successful
101OK = 200
102CREATED = 201
103ACCEPTED = 202
104NON_AUTHORITATIVE_INFORMATION = 203
105NO_CONTENT = 204
106RESET_CONTENT = 205
107PARTIAL_CONTENT = 206
108MULTI_STATUS = 207
109IM_USED = 226
110
111# redirection
112MULTIPLE_CHOICES = 300
113MOVED_PERMANENTLY = 301
114FOUND = 302
115SEE_OTHER = 303
116NOT_MODIFIED = 304
117USE_PROXY = 305
118TEMPORARY_REDIRECT = 307
119
120# client error
121BAD_REQUEST = 400
122UNAUTHORIZED = 401
123PAYMENT_REQUIRED = 402
124FORBIDDEN = 403
125NOT_FOUND = 404
126METHOD_NOT_ALLOWED = 405
127NOT_ACCEPTABLE = 406
128PROXY_AUTHENTICATION_REQUIRED = 407
129REQUEST_TIMEOUT = 408
130CONFLICT = 409
131GONE = 410
132LENGTH_REQUIRED = 411
133PRECONDITION_FAILED = 412
134REQUEST_ENTITY_TOO_LARGE = 413
135REQUEST_URI_TOO_LONG = 414
136UNSUPPORTED_MEDIA_TYPE = 415
137REQUESTED_RANGE_NOT_SATISFIABLE = 416
138EXPECTATION_FAILED = 417
139UNPROCESSABLE_ENTITY = 422
140LOCKED = 423
141FAILED_DEPENDENCY = 424
142UPGRADE_REQUIRED = 426
143
144# server error
145INTERNAL_SERVER_ERROR = 500
146NOT_IMPLEMENTED = 501
147BAD_GATEWAY = 502
148SERVICE_UNAVAILABLE = 503
149GATEWAY_TIMEOUT = 504
150HTTP_VERSION_NOT_SUPPORTED = 505
151INSUFFICIENT_STORAGE = 507
152NOT_EXTENDED = 510
153
Georg Brandl6aab16e2006-02-17 19:17:25 +0000154# Mapping status codes to official W3C names
155responses = {
156 100: 'Continue',
157 101: 'Switching Protocols',
158
159 200: 'OK',
160 201: 'Created',
161 202: 'Accepted',
162 203: 'Non-Authoritative Information',
163 204: 'No Content',
164 205: 'Reset Content',
165 206: 'Partial Content',
166
167 300: 'Multiple Choices',
168 301: 'Moved Permanently',
169 302: 'Found',
170 303: 'See Other',
171 304: 'Not Modified',
172 305: 'Use Proxy',
173 306: '(Unused)',
174 307: 'Temporary Redirect',
175
176 400: 'Bad Request',
177 401: 'Unauthorized',
178 402: 'Payment Required',
179 403: 'Forbidden',
180 404: 'Not Found',
181 405: 'Method Not Allowed',
182 406: 'Not Acceptable',
183 407: 'Proxy Authentication Required',
184 408: 'Request Timeout',
185 409: 'Conflict',
186 410: 'Gone',
187 411: 'Length Required',
188 412: 'Precondition Failed',
189 413: 'Request Entity Too Large',
190 414: 'Request-URI Too Long',
191 415: 'Unsupported Media Type',
192 416: 'Requested Range Not Satisfiable',
193 417: 'Expectation Failed',
194
195 500: 'Internal Server Error',
196 501: 'Not Implemented',
197 502: 'Bad Gateway',
198 503: 'Service Unavailable',
199 504: 'Gateway Timeout',
200 505: 'HTTP Version Not Supported',
201}
202
Georg Brandl80ba8e82005-09-29 20:16:07 +0000203# maximal amount of data to read at one time in _safe_read
204MAXAMOUNT = 1048576
205
Barry Warsaw820c1202008-06-12 04:06:45 +0000206class HTTPMessage(email.message.Message):
207 def getallmatchingheaders(self, name):
208 """Find all header lines matching a given header name.
Jeremy Hylton6d0a4c72002-07-07 16:51:37 +0000209
Barry Warsaw820c1202008-06-12 04:06:45 +0000210 Look through the list of headers and find all lines matching a given
211 header name (and their continuation lines). A list of the lines is
212 returned, without interpretation. If the header does not occur, an
213 empty list is returned. If the header occurs multiple times, all
214 occurrences are returned. Case is not important in the header name.
Jeremy Hylton6d0a4c72002-07-07 16:51:37 +0000215
Jeremy Hylton6d0a4c72002-07-07 16:51:37 +0000216 """
Barry Warsaw820c1202008-06-12 04:06:45 +0000217 name = name.lower() + ':'
218 n = len(name)
219 lst = []
220 hit = 0
221 for line in self.keys():
222 if line[:n].lower() == name:
223 hit = 1
224 elif not line[:1].isspace():
225 hit = 0
226 if hit:
227 lst.append(line)
228 return lst
Jeremy Hylton6d0a4c72002-07-07 16:51:37 +0000229
Jeremy Hylton98eb6c22009-03-27 18:31:36 +0000230def parse_headers(fp, _class=HTTPMessage):
Barry Warsaw820c1202008-06-12 04:06:45 +0000231 """Parses only RFC2822 headers from a file pointer.
232
233 email Parser wants to see strings rather than bytes.
234 But a TextIOWrapper around self.rfile would buffer too many bytes
235 from the stream, bytes which we later need to read as bytes.
236 So we read the correct bytes here, as bytes, for email Parser
237 to parse.
238
239 """
Barry Warsaw820c1202008-06-12 04:06:45 +0000240 headers = []
241 while True:
242 line = fp.readline()
243 headers.append(line)
244 if line in (b'\r\n', b'\n', b''):
245 break
246 hstring = b''.join(headers).decode('iso-8859-1')
Jeremy Hylton98eb6c22009-03-27 18:31:36 +0000247 return email.parser.Parser(_class=_class).parsestr(hstring)
Greg Stein5e0fa402000-06-26 08:28:01 +0000248
Antoine Pitroub353c122009-02-11 00:39:14 +0000249class HTTPResponse(io.RawIOBase):
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000250
251 # strict: If true, raise BadStatusLine if the status line can't be
252 # parsed as a valid HTTP/1.0 or 1.1 status line. By default it is
Skip Montanaro186bec22002-07-25 16:10:38 +0000253 # false because it prevents clients from talking to HTTP/0.9
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000254 # servers. Note that a response with a sufficiently corrupted
255 # status line will look like an HTTP/0.9 response.
256
257 # See RFC 2616 sec 19.6 and RFC 1945 sec 6 for details.
258
Jeremy Hylton811fc142007-08-03 13:30:02 +0000259 # The bytes from the socket object are iso-8859-1 strings.
260 # See RFC 2616 sec 2.2 which notes an exception for MIME-encoded
261 # text following RFC 2047. The basic status line parsing only
262 # accepts iso-8859-1.
263
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000264 def __init__(self, sock, debuglevel=0, strict=0, method=None):
Kristján Valur Jónsson7e11b3f2009-02-02 16:04:04 +0000265 # If the response includes a content-length header, we
Jeremy Hylton39b198d2007-08-04 19:22:00 +0000266 # need to make sure that the client doesn't read more than the
267 # specified number of bytes. If it does, it will block until
268 # the server times out and closes the connection. (The only
Kristján Valur Jónsson7e11b3f2009-02-02 16:04:04 +0000269 # applies to HTTP/1.1 connections.) This will happen if a self.fp.read()
270 # is done (without a size) whether self.fp is buffered or not.
271 # So, no self.fp.read() by clients unless they know what they are doing.
Benjamin Petersonf72d9fb2009-02-08 00:29:20 +0000272 self.fp = sock.makefile("rb")
Jeremy Hylton30f86742000-09-18 22:50:38 +0000273 self.debuglevel = debuglevel
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000274 self.strict = strict
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000275 self._method = method
Greg Stein5e0fa402000-06-26 08:28:01 +0000276
Greg Steindd6eefb2000-07-18 09:09:48 +0000277 self.msg = None
Greg Stein5e0fa402000-06-26 08:28:01 +0000278
Greg Steindd6eefb2000-07-18 09:09:48 +0000279 # from the Status-Line of the response
Tim Peters07e99cb2001-01-14 23:47:14 +0000280 self.version = _UNKNOWN # HTTP-Version
281 self.status = _UNKNOWN # Status-Code
282 self.reason = _UNKNOWN # Reason-Phrase
Greg Stein5e0fa402000-06-26 08:28:01 +0000283
Tim Peters07e99cb2001-01-14 23:47:14 +0000284 self.chunked = _UNKNOWN # is "chunked" being used?
285 self.chunk_left = _UNKNOWN # bytes left to read in current chunk
286 self.length = _UNKNOWN # number of bytes left in response
287 self.will_close = _UNKNOWN # conn will close at end of response
Greg Stein5e0fa402000-06-26 08:28:01 +0000288
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000289 def _read_status(self):
Jeremy Hylton04319c72007-08-04 03:41:19 +0000290 # Initialize with Simple-Response defaults.
Jeremy Hylton811fc142007-08-03 13:30:02 +0000291 line = str(self.fp.readline(), "iso-8859-1")
Jeremy Hylton30f86742000-09-18 22:50:38 +0000292 if self.debuglevel > 0:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000293 print("reply:", repr(line))
Jeremy Hyltonb6769522003-06-29 17:55:05 +0000294 if not line:
295 # Presumably, the server closed the connection before
296 # sending a valid response.
297 raise BadStatusLine(line)
Greg Steindd6eefb2000-07-18 09:09:48 +0000298 try:
Guido van Rossum34735a62000-12-15 15:09:42 +0000299 [version, status, reason] = line.split(None, 2)
Greg Steindd6eefb2000-07-18 09:09:48 +0000300 except ValueError:
301 try:
Guido van Rossum34735a62000-12-15 15:09:42 +0000302 [version, status] = line.split(None, 1)
Greg Steindd6eefb2000-07-18 09:09:48 +0000303 reason = ""
304 except ValueError:
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000305 # empty version will cause next test to fail and status
306 # will be treated as 0.9 response.
307 version = ""
Jeremy Hyltone5d0e842007-08-03 13:45:24 +0000308 if not version.startswith("HTTP/"):
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000309 if self.strict:
310 self.close()
311 raise BadStatusLine(line)
312 else:
Jeremy Hylton04319c72007-08-04 03:41:19 +0000313 # Assume it's a Simple-Response from an 0.9 server.
314 # We have to convert the first line back to raw bytes
315 # because self.fp.readline() needs to return bytes.
Guido van Rossum70d0dda2007-08-29 01:53:26 +0000316 self.fp = LineAndFileWrapper(bytes(line, "ascii"), self.fp)
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000317 return "HTTP/0.9", 200, ""
Greg Stein5e0fa402000-06-26 08:28:01 +0000318
Jeremy Hylton23d40472001-04-13 14:57:08 +0000319 # The status code is a three-digit number
320 try:
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000321 status = int(status)
Jeremy Hylton23d40472001-04-13 14:57:08 +0000322 if status < 100 or status > 999:
323 raise BadStatusLine(line)
324 except ValueError:
325 raise BadStatusLine(line)
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000326 return version, status, reason
Greg Stein5e0fa402000-06-26 08:28:01 +0000327
Jeremy Hylton39c03802002-07-12 14:04:09 +0000328 def begin(self):
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000329 if self.msg is not None:
330 # we've already started reading the response
331 return
332
333 # read until we get a non-100 response
Raymond Hettingerb2e0b922003-02-26 22:45:18 +0000334 while True:
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000335 version, status, reason = self._read_status()
Martin v. Löwis39a31782004-09-18 09:03:49 +0000336 if status != CONTINUE:
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000337 break
338 # skip the header from the 100 response
Raymond Hettingerb2e0b922003-02-26 22:45:18 +0000339 while True:
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000340 skip = self.fp.readline().strip()
341 if not skip:
342 break
343 if self.debuglevel > 0:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000344 print("header:", skip)
Tim Petersc411dba2002-07-16 21:35:23 +0000345
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000346 self.status = status
347 self.reason = reason.strip()
Jeremy Hyltone5d0e842007-08-03 13:45:24 +0000348 if version == "HTTP/1.0":
Greg Steindd6eefb2000-07-18 09:09:48 +0000349 self.version = 10
Jeremy Hyltone5d0e842007-08-03 13:45:24 +0000350 elif version.startswith("HTTP/1."):
Tim Peters07e99cb2001-01-14 23:47:14 +0000351 self.version = 11 # use HTTP/1.1 code for HTTP/1.x where x>=1
Jeremy Hyltone5d0e842007-08-03 13:45:24 +0000352 elif version == "HTTP/0.9":
Jeremy Hylton110941a2000-10-12 19:58:36 +0000353 self.version = 9
Greg Steindd6eefb2000-07-18 09:09:48 +0000354 else:
355 raise UnknownProtocol(version)
Greg Stein5e0fa402000-06-26 08:28:01 +0000356
Jeremy Hylton110941a2000-10-12 19:58:36 +0000357 if self.version == 9:
Georg Brandl0aade9a2005-06-26 22:06:54 +0000358 self.length = None
Jeremy Hylton236156f2008-12-15 03:00:50 +0000359 self.chunked = False
360 self.will_close = True
Barry Warsaw820c1202008-06-12 04:06:45 +0000361 self.msg = email.message_from_string('')
Jeremy Hylton110941a2000-10-12 19:58:36 +0000362 return
363
Barry Warsaw820c1202008-06-12 04:06:45 +0000364 self.msg = parse_headers(self.fp)
365
Jeremy Hylton30f86742000-09-18 22:50:38 +0000366 if self.debuglevel > 0:
Barry Warsaw820c1202008-06-12 04:06:45 +0000367 for hdr in self.msg:
Jeremy Hyltone5d0e842007-08-03 13:45:24 +0000368 print("header:", hdr, end=" ")
Greg Stein5e0fa402000-06-26 08:28:01 +0000369
Greg Steindd6eefb2000-07-18 09:09:48 +0000370 # are we using the chunked-style of transfer encoding?
Barry Warsaw820c1202008-06-12 04:06:45 +0000371 tr_enc = self.msg.get("transfer-encoding")
Jeremy Hyltond229b3a2002-09-03 19:24:24 +0000372 if tr_enc and tr_enc.lower() == "chunked":
Jeremy Hylton236156f2008-12-15 03:00:50 +0000373 self.chunked = True
Greg Steindd6eefb2000-07-18 09:09:48 +0000374 self.chunk_left = None
375 else:
Jeremy Hylton236156f2008-12-15 03:00:50 +0000376 self.chunked = False
Greg Stein5e0fa402000-06-26 08:28:01 +0000377
Greg Steindd6eefb2000-07-18 09:09:48 +0000378 # will the connection close at the end of the response?
Jeremy Hylton22b3a492002-11-13 17:27:43 +0000379 self.will_close = self._check_close()
Greg Stein5e0fa402000-06-26 08:28:01 +0000380
Greg Steindd6eefb2000-07-18 09:09:48 +0000381 # do we have a Content-Length?
382 # NOTE: RFC 2616, S4.4, #3 says we ignore this if tr_enc is "chunked"
Jeremy Hylton0ee5eeb2007-08-04 03:25:17 +0000383 self.length = None
Barry Warsaw820c1202008-06-12 04:06:45 +0000384 length = self.msg.get("content-length")
385
386 # are we using the chunked-style of transfer encoding?
387 tr_enc = self.msg.get("transfer-encoding")
Greg Steindd6eefb2000-07-18 09:09:48 +0000388 if length and not self.chunked:
Jeremy Hylton30a81812000-09-14 20:34:27 +0000389 try:
390 self.length = int(length)
391 except ValueError:
Christian Heimesa612dc02008-02-24 13:08:18 +0000392 self.length = None
393 else:
394 if self.length < 0: # ignore nonsensical negative lengths
395 self.length = None
396 else:
397 self.length = None
Greg Stein5e0fa402000-06-26 08:28:01 +0000398
Greg Steindd6eefb2000-07-18 09:09:48 +0000399 # does the body have a fixed length? (of zero)
Martin v. Löwis39a31782004-09-18 09:03:49 +0000400 if (status == NO_CONTENT or status == NOT_MODIFIED or
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000401 100 <= status < 200 or # 1xx codes
Jeremy Hyltone5d0e842007-08-03 13:45:24 +0000402 self._method == "HEAD"):
Greg Steindd6eefb2000-07-18 09:09:48 +0000403 self.length = 0
Greg Stein5e0fa402000-06-26 08:28:01 +0000404
Greg Steindd6eefb2000-07-18 09:09:48 +0000405 # if the connection remains open, and we aren't using chunked, and
406 # a content-length was not provided, then assume that the connection
407 # WILL close.
Jeremy Hylton0ee5eeb2007-08-04 03:25:17 +0000408 if (not self.will_close and
409 not self.chunked and
410 self.length is None):
Jeremy Hylton236156f2008-12-15 03:00:50 +0000411 self.will_close = True
Greg Stein5e0fa402000-06-26 08:28:01 +0000412
Jeremy Hylton22b3a492002-11-13 17:27:43 +0000413 def _check_close(self):
Barry Warsaw820c1202008-06-12 04:06:45 +0000414 conn = self.msg.get("connection")
Jeremy Hylton22b3a492002-11-13 17:27:43 +0000415 if self.version == 11:
416 # An HTTP/1.1 proxy is assumed to stay open unless
417 # explicitly closed.
Barry Warsaw820c1202008-06-12 04:06:45 +0000418 conn = self.msg.get("connection")
Raymond Hettingerbac788a2004-05-04 09:21:43 +0000419 if conn and "close" in conn.lower():
Jeremy Hylton22b3a492002-11-13 17:27:43 +0000420 return True
421 return False
422
Jeremy Hylton2c178252004-08-07 16:28:14 +0000423 # Some HTTP/1.0 implementations have support for persistent
424 # connections, using rules different than HTTP/1.1.
Jeremy Hylton22b3a492002-11-13 17:27:43 +0000425
Christian Heimes895627f2007-12-08 17:28:33 +0000426 # For older HTTP, Keep-Alive indicates persistent connection.
Barry Warsaw820c1202008-06-12 04:06:45 +0000427 if self.msg.get("keep-alive"):
Jeremy Hylton22b3a492002-11-13 17:27:43 +0000428 return False
Tim Peters77c06fb2002-11-24 02:35:35 +0000429
Jeremy Hylton2c178252004-08-07 16:28:14 +0000430 # At least Akamai returns a "Connection: Keep-Alive" header,
431 # which was supposed to be sent by the client.
432 if conn and "keep-alive" in conn.lower():
433 return False
434
Jeremy Hylton22b3a492002-11-13 17:27:43 +0000435 # Proxy-Connection is a netscape hack.
Barry Warsaw820c1202008-06-12 04:06:45 +0000436 pconn = self.msg.get("proxy-connection")
Raymond Hettingerbac788a2004-05-04 09:21:43 +0000437 if pconn and "keep-alive" in pconn.lower():
Jeremy Hylton22b3a492002-11-13 17:27:43 +0000438 return False
439
440 # otherwise, assume it will close
441 return True
442
Greg Steindd6eefb2000-07-18 09:09:48 +0000443 def close(self):
444 if self.fp:
445 self.fp.close()
446 self.fp = None
Greg Stein5e0fa402000-06-26 08:28:01 +0000447
Jeremy Hyltondf5f6b52007-08-08 17:36:33 +0000448 # These implementations are for the benefit of io.BufferedReader.
449
450 # XXX This class should probably be revised to act more like
451 # the "raw stream" that BufferedReader expects.
452
453 @property
454 def closed(self):
455 return self.isclosed()
456
457 def flush(self):
458 self.fp.flush()
459
460 # End of "raw stream" methods
461
Greg Steindd6eefb2000-07-18 09:09:48 +0000462 def isclosed(self):
463 # NOTE: it is possible that we will not ever call self.close(). This
464 # case occurs when will_close is TRUE, length is None, and we
465 # read up to the last byte, but NOT past it.
466 #
467 # IMPLIES: if will_close is FALSE, then self.close() will ALWAYS be
468 # called, meaning self.isclosed() is meaningful.
469 return self.fp is None
470
471 def read(self, amt=None):
472 if self.fp is None:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000473 return b""
Greg Steindd6eefb2000-07-18 09:09:48 +0000474
475 if self.chunked:
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000476 return self._read_chunked(amt)
Tim Peters230a60c2002-11-09 05:08:07 +0000477
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000478 if amt is None:
Greg Steindd6eefb2000-07-18 09:09:48 +0000479 # unbounded read
Jeremy Hyltondef9d2a2004-11-07 16:13:49 +0000480 if self.length is None:
Greg Steindd6eefb2000-07-18 09:09:48 +0000481 s = self.fp.read()
482 else:
483 s = self._safe_read(self.length)
Jeremy Hyltondef9d2a2004-11-07 16:13:49 +0000484 self.length = 0
Tim Peters07e99cb2001-01-14 23:47:14 +0000485 self.close() # we read everything
Greg Steindd6eefb2000-07-18 09:09:48 +0000486 return s
487
488 if self.length is not None:
489 if amt > self.length:
490 # clip the read to the "end of response"
491 amt = self.length
Greg Steindd6eefb2000-07-18 09:09:48 +0000492
493 # we do not use _safe_read() here because this may be a .will_close
494 # connection, and the user is reading more bytes than will be provided
495 # (for example, reading in 1k chunks)
496 s = self.fp.read(amt)
Jeremy Hyltondef9d2a2004-11-07 16:13:49 +0000497 if self.length is not None:
498 self.length -= len(s)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000499 if not self.length:
500 self.close()
Greg Steindd6eefb2000-07-18 09:09:48 +0000501 return s
502
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000503 def _read_chunked(self, amt):
504 assert self.chunked != _UNKNOWN
505 chunk_left = self.chunk_left
Georg Brandl95ba4692008-01-26 09:45:58 +0000506 value = b""
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000507
508 # XXX This accumulates chunks by repeated string concatenation,
509 # which is not efficient as the number or size of chunks gets big.
Raymond Hettingerb2e0b922003-02-26 22:45:18 +0000510 while True:
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000511 if chunk_left is None:
512 line = self.fp.readline()
Georg Brandl95ba4692008-01-26 09:45:58 +0000513 i = line.find(b";")
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000514 if i >= 0:
515 line = line[:i] # strip chunk-extensions
Christian Heimesa612dc02008-02-24 13:08:18 +0000516 try:
517 chunk_left = int(line, 16)
518 except ValueError:
519 # close the connection as protocol synchronisation is
520 # probably lost
521 self.close()
522 raise IncompleteRead(value)
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000523 if chunk_left == 0:
524 break
525 if amt is None:
526 value += self._safe_read(chunk_left)
527 elif amt < chunk_left:
528 value += self._safe_read(amt)
529 self.chunk_left = chunk_left - amt
530 return value
531 elif amt == chunk_left:
532 value += self._safe_read(amt)
533 self._safe_read(2) # toss the CRLF at the end of the chunk
534 self.chunk_left = None
535 return value
536 else:
537 value += self._safe_read(chunk_left)
538 amt -= chunk_left
539
540 # we read the whole chunk, get another
541 self._safe_read(2) # toss the CRLF at the end of the chunk
542 chunk_left = None
543
544 # read and discard trailer up to the CRLF terminator
545 ### note: we shouldn't have any trailers!
Raymond Hettingerb2e0b922003-02-26 22:45:18 +0000546 while True:
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000547 line = self.fp.readline()
Christian Heimes0bd4e112008-02-12 22:59:25 +0000548 if not line:
549 # a vanishingly small number of sites EOF without
550 # sending the trailer
551 break
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000552 if line == b"\r\n":
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000553 break
554
555 # we read everything; close the "file"
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000556 self.close()
557
558 return value
Tim Peters230a60c2002-11-09 05:08:07 +0000559
Greg Steindd6eefb2000-07-18 09:09:48 +0000560 def _safe_read(self, amt):
561 """Read the number of bytes requested, compensating for partial reads.
562
563 Normally, we have a blocking socket, but a read() can be interrupted
564 by a signal (resulting in a partial read).
565
566 Note that we cannot distinguish between EOF and an interrupt when zero
567 bytes have been read. IncompleteRead() will be raised in this
568 situation.
569
570 This function should be used when <amt> bytes "should" be present for
571 reading. If the bytes are truly not available (due to EOF), then the
572 IncompleteRead exception can be used to detect the problem.
573 """
Georg Brandl80ba8e82005-09-29 20:16:07 +0000574 s = []
Greg Steindd6eefb2000-07-18 09:09:48 +0000575 while amt > 0:
Georg Brandl80ba8e82005-09-29 20:16:07 +0000576 chunk = self.fp.read(min(amt, MAXAMOUNT))
Greg Steindd6eefb2000-07-18 09:09:48 +0000577 if not chunk:
Benjamin Peterson6accb982009-03-02 22:50:25 +0000578 raise IncompleteRead(b''.join(s), amt)
Georg Brandl80ba8e82005-09-29 20:16:07 +0000579 s.append(chunk)
Raymond Hettingerb2e0b922003-02-26 22:45:18 +0000580 amt -= len(chunk)
Guido van Rossuma00f1232007-09-12 19:43:09 +0000581 return b"".join(s)
Greg Steindd6eefb2000-07-18 09:09:48 +0000582
Antoine Pitroub353c122009-02-11 00:39:14 +0000583 def fileno(self):
584 return self.fp.fileno()
585
Greg Steindd6eefb2000-07-18 09:09:48 +0000586 def getheader(self, name, default=None):
587 if self.msg is None:
588 raise ResponseNotReady()
Barry Warsaw820c1202008-06-12 04:06:45 +0000589 return ', '.join(self.msg.get_all(name, default))
Greg Stein5e0fa402000-06-26 08:28:01 +0000590
Martin v. Löwisdeacce22004-08-18 12:46:26 +0000591 def getheaders(self):
592 """Return list of (header, value) tuples."""
593 if self.msg is None:
594 raise ResponseNotReady()
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000595 return list(self.msg.items())
Martin v. Löwisdeacce22004-08-18 12:46:26 +0000596
Antoine Pitroub353c122009-02-11 00:39:14 +0000597 # We override IOBase.__iter__ so that it doesn't check for closed-ness
598
599 def __iter__(self):
600 return self
601
Greg Stein5e0fa402000-06-26 08:28:01 +0000602
603class HTTPConnection:
604
Greg Steindd6eefb2000-07-18 09:09:48 +0000605 _http_vsn = 11
606 _http_vsn_str = 'HTTP/1.1'
Greg Stein5e0fa402000-06-26 08:28:01 +0000607
Greg Steindd6eefb2000-07-18 09:09:48 +0000608 response_class = HTTPResponse
609 default_port = HTTP_PORT
610 auto_open = 1
Jeremy Hylton30f86742000-09-18 22:50:38 +0000611 debuglevel = 0
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000612 strict = 0
Greg Stein5e0fa402000-06-26 08:28:01 +0000613
Georg Brandlf78e02b2008-06-10 17:40:04 +0000614 def __init__(self, host, port=None, strict=None,
615 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000616 self.timeout = timeout
Greg Steindd6eefb2000-07-18 09:09:48 +0000617 self.sock = None
Jeremy Hylton8531b1b2002-07-16 21:21:11 +0000618 self._buffer = []
Greg Steindd6eefb2000-07-18 09:09:48 +0000619 self.__response = None
620 self.__state = _CS_IDLE
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000621 self._method = None
Tim Petersc411dba2002-07-16 21:35:23 +0000622
Greg Steindd6eefb2000-07-18 09:09:48 +0000623 self._set_hostport(host, port)
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000624 if strict is not None:
625 self.strict = strict
Greg Stein5e0fa402000-06-26 08:28:01 +0000626
Greg Steindd6eefb2000-07-18 09:09:48 +0000627 def _set_hostport(self, host, port):
628 if port is None:
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000629 i = host.rfind(':')
Skip Montanarocae14d22004-09-14 17:55:21 +0000630 j = host.rfind(']') # ipv6 addresses have [...]
631 if i > j:
Skip Montanaro9d389972002-03-24 16:53:50 +0000632 try:
633 port = int(host[i+1:])
634 except ValueError:
Jeremy Hyltonfbd79942002-07-02 20:19:08 +0000635 raise InvalidURL("nonnumeric port: '%s'" % host[i+1:])
Greg Steindd6eefb2000-07-18 09:09:48 +0000636 host = host[:i]
637 else:
638 port = self.default_port
Raymond Hettinger4d037912004-10-14 15:23:38 +0000639 if host and host[0] == '[' and host[-1] == ']':
Brett Cannon0a1af4a2004-09-15 23:26:23 +0000640 host = host[1:-1]
Greg Steindd6eefb2000-07-18 09:09:48 +0000641 self.host = host
642 self.port = port
Greg Stein5e0fa402000-06-26 08:28:01 +0000643
Jeremy Hylton30f86742000-09-18 22:50:38 +0000644 def set_debuglevel(self, level):
645 self.debuglevel = level
646
Greg Steindd6eefb2000-07-18 09:09:48 +0000647 def connect(self):
648 """Connect to the host and port specified in __init__."""
Guido van Rossumd8faa362007-04-27 19:54:29 +0000649 self.sock = socket.create_connection((self.host,self.port),
650 self.timeout)
Greg Stein5e0fa402000-06-26 08:28:01 +0000651
Greg Steindd6eefb2000-07-18 09:09:48 +0000652 def close(self):
653 """Close the connection to the HTTP server."""
654 if self.sock:
Tim Peters07e99cb2001-01-14 23:47:14 +0000655 self.sock.close() # close it manually... there may be other refs
Greg Steindd6eefb2000-07-18 09:09:48 +0000656 self.sock = None
657 if self.__response:
658 self.__response.close()
659 self.__response = None
660 self.__state = _CS_IDLE
Greg Stein5e0fa402000-06-26 08:28:01 +0000661
Greg Steindd6eefb2000-07-18 09:09:48 +0000662 def send(self, str):
663 """Send `str' to the server."""
664 if self.sock is None:
665 if self.auto_open:
666 self.connect()
667 else:
668 raise NotConnected()
Greg Stein5e0fa402000-06-26 08:28:01 +0000669
Jeremy Hyltone3252ec2002-07-16 21:41:43 +0000670 # send the data to the server. if we get a broken pipe, then close
Greg Steindd6eefb2000-07-18 09:09:48 +0000671 # the socket. we want to reconnect when somebody tries to send again.
672 #
673 # NOTE: we DO propagate the error, though, because we cannot simply
674 # ignore the error... the caller will know if they can retry.
Jeremy Hylton30f86742000-09-18 22:50:38 +0000675 if self.debuglevel > 0:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000676 print("send:", repr(str))
Jeremy Hylton636950f2009-03-28 04:34:21 +0000677 blocksize = 8192
678 if hasattr(str, "read") :
679 if self.debuglevel > 0:
680 print("sendIng a read()able")
681 encode = False
682 if "b" not in str.mode:
683 encode = True
Jeremy Hylton236654b2009-03-27 20:24:34 +0000684 if self.debuglevel > 0:
Jeremy Hylton636950f2009-03-28 04:34:21 +0000685 print("encoding file using iso-8859-1")
686 while 1:
687 data = str.read(blocksize)
688 if not data:
689 break
690 if encode:
691 data = data.encode("iso-8859-1")
692 self.sock.sendall(data)
693 else:
694 self.sock.sendall(str)
Greg Stein5e0fa402000-06-26 08:28:01 +0000695
Jeremy Hylton8531b1b2002-07-16 21:21:11 +0000696 def _output(self, s):
697 """Add a line of output to the current request buffer.
Tim Peters469cdad2002-08-08 20:19:19 +0000698
Jeremy Hyltone3252ec2002-07-16 21:41:43 +0000699 Assumes that the line does *not* end with \\r\\n.
Jeremy Hylton8531b1b2002-07-16 21:21:11 +0000700 """
701 self._buffer.append(s)
702
Benjamin Peterson1742e402008-11-30 22:15:29 +0000703 def _send_output(self, message_body=None):
Jeremy Hylton8531b1b2002-07-16 21:21:11 +0000704 """Send the currently buffered request and clear the buffer.
705
Jeremy Hyltone3252ec2002-07-16 21:41:43 +0000706 Appends an extra \\r\\n to the buffer.
Benjamin Peterson822b21c2009-01-18 00:04:57 +0000707 A message_body may be specified, to be appended to the request.
Jeremy Hylton8531b1b2002-07-16 21:21:11 +0000708 """
Martin v. Löwisdd5a8602007-06-30 09:22:09 +0000709 self._buffer.extend((b"", b""))
710 msg = b"\r\n".join(self._buffer)
Jeremy Hylton8531b1b2002-07-16 21:21:11 +0000711 del self._buffer[:]
Benjamin Peterson1742e402008-11-30 22:15:29 +0000712 # If msg and message_body are sent in a single send() call,
713 # it will avoid performance problems caused by the interaction
714 # between delayed ack and the Nagle algorithim.
Benjamin Peterson822b21c2009-01-18 00:04:57 +0000715 if isinstance(message_body, bytes):
Benjamin Peterson1742e402008-11-30 22:15:29 +0000716 msg += message_body
Benjamin Peterson822b21c2009-01-18 00:04:57 +0000717 message_body = None
Jeremy Hylton8531b1b2002-07-16 21:21:11 +0000718 self.send(msg)
Benjamin Peterson822b21c2009-01-18 00:04:57 +0000719 if message_body is not None:
Jeremy Hylton236654b2009-03-27 20:24:34 +0000720 # message_body was not a string (i.e. it is a file), and
721 # we must run the risk of Nagle.
Benjamin Peterson822b21c2009-01-18 00:04:57 +0000722 self.send(message_body)
Jeremy Hylton8531b1b2002-07-16 21:21:11 +0000723
Martin v. Löwisaf7dc8d2003-11-19 19:51:55 +0000724 def putrequest(self, method, url, skip_host=0, skip_accept_encoding=0):
Greg Steindd6eefb2000-07-18 09:09:48 +0000725 """Send a request to the server.
Greg Stein5e0fa402000-06-26 08:28:01 +0000726
Greg Steindd6eefb2000-07-18 09:09:48 +0000727 `method' specifies an HTTP request method, e.g. 'GET'.
728 `url' specifies the object being requested, e.g. '/index.html'.
Martin v. Löwisaf7dc8d2003-11-19 19:51:55 +0000729 `skip_host' if True does not add automatically a 'Host:' header
730 `skip_accept_encoding' if True does not add automatically an
731 'Accept-Encoding:' header
Greg Steindd6eefb2000-07-18 09:09:48 +0000732 """
Greg Stein5e0fa402000-06-26 08:28:01 +0000733
Greg Stein616a58d2003-06-24 06:35:19 +0000734 # if a prior response has been completed, then forget about it.
Greg Steindd6eefb2000-07-18 09:09:48 +0000735 if self.__response and self.__response.isclosed():
736 self.__response = None
Greg Stein5e0fa402000-06-26 08:28:01 +0000737
Tim Peters58eb11c2004-01-18 20:29:55 +0000738
Greg Steindd6eefb2000-07-18 09:09:48 +0000739 # in certain cases, we cannot issue another request on this connection.
740 # this occurs when:
741 # 1) we are in the process of sending a request. (_CS_REQ_STARTED)
742 # 2) a response to a previous request has signalled that it is going
743 # to close the connection upon completion.
744 # 3) the headers for the previous response have not been read, thus
745 # we cannot determine whether point (2) is true. (_CS_REQ_SENT)
746 #
747 # if there is no prior response, then we can request at will.
748 #
749 # if point (2) is true, then we will have passed the socket to the
750 # response (effectively meaning, "there is no prior response"), and
751 # will open a new one when a new request is made.
752 #
753 # Note: if a prior response exists, then we *can* start a new request.
754 # We are not allowed to begin fetching the response to this new
755 # request, however, until that prior response is complete.
756 #
757 if self.__state == _CS_IDLE:
758 self.__state = _CS_REQ_STARTED
759 else:
760 raise CannotSendRequest()
Greg Stein5e0fa402000-06-26 08:28:01 +0000761
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000762 # Save the method we use, we need it later in the response phase
763 self._method = method
Greg Steindd6eefb2000-07-18 09:09:48 +0000764 if not url:
765 url = '/'
Martin v. Löwisdd5a8602007-06-30 09:22:09 +0000766 request = '%s %s %s' % (method, url, self._http_vsn_str)
Greg Stein5e0fa402000-06-26 08:28:01 +0000767
Martin v. Löwisdd5a8602007-06-30 09:22:09 +0000768 # Non-ASCII characters should have been eliminated earlier
769 self._output(request.encode('ascii'))
Greg Stein5e0fa402000-06-26 08:28:01 +0000770
Greg Steindd6eefb2000-07-18 09:09:48 +0000771 if self._http_vsn == 11:
772 # Issue some standard headers for better HTTP/1.1 compliance
Greg Stein5e0fa402000-06-26 08:28:01 +0000773
Jeremy Hylton3921ff62002-03-09 06:07:23 +0000774 if not skip_host:
775 # this header is issued *only* for HTTP/1.1
776 # connections. more specifically, this means it is
777 # only issued when the client uses the new
778 # HTTPConnection() class. backwards-compat clients
779 # will be using HTTP/1.0 and those clients may be
780 # issuing this header themselves. we should NOT issue
781 # it twice; some web servers (such as Apache) barf
782 # when they see two Host: headers
Guido van Rossumf6922aa2001-01-14 21:03:01 +0000783
Jeremy Hylton3921ff62002-03-09 06:07:23 +0000784 # If we need a non-standard port,include it in the
785 # header. If the request is going through a proxy,
786 # but the host of the actual URL, not the host of the
787 # proxy.
Jeremy Hylton8acf1e02002-03-08 19:35:51 +0000788
Jeremy Hylton3921ff62002-03-09 06:07:23 +0000789 netloc = ''
790 if url.startswith('http'):
791 nil, netloc, nil, nil, nil = urlsplit(url)
792
793 if netloc:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000794 try:
795 netloc_enc = netloc.encode("ascii")
796 except UnicodeEncodeError:
797 netloc_enc = netloc.encode("idna")
798 self.putheader('Host', netloc_enc)
Jeremy Hylton3921ff62002-03-09 06:07:23 +0000799 else:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000800 try:
801 host_enc = self.host.encode("ascii")
802 except UnicodeEncodeError:
803 host_enc = self.host.encode("idna")
Georg Brandl86b2fb92008-07-16 03:43:04 +0000804 if self.port == self.default_port:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000805 self.putheader('Host', host_enc)
806 else:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000807 host_enc = host_enc.decode("ascii")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000808 self.putheader('Host', "%s:%s" % (host_enc, self.port))
Greg Stein5e0fa402000-06-26 08:28:01 +0000809
Greg Steindd6eefb2000-07-18 09:09:48 +0000810 # note: we are assuming that clients will not attempt to set these
811 # headers since *this* library must deal with the
812 # consequences. this also means that when the supporting
813 # libraries are updated to recognize other forms, then this
814 # code should be changed (removed or updated).
Greg Stein5e0fa402000-06-26 08:28:01 +0000815
Greg Steindd6eefb2000-07-18 09:09:48 +0000816 # we only want a Content-Encoding of "identity" since we don't
817 # support encodings such as x-gzip or x-deflate.
Martin v. Löwisaf7dc8d2003-11-19 19:51:55 +0000818 if not skip_accept_encoding:
819 self.putheader('Accept-Encoding', 'identity')
Greg Stein5e0fa402000-06-26 08:28:01 +0000820
Greg Steindd6eefb2000-07-18 09:09:48 +0000821 # we can accept "chunked" Transfer-Encodings, but no others
822 # NOTE: no TE header implies *only* "chunked"
823 #self.putheader('TE', 'chunked')
Greg Stein5e0fa402000-06-26 08:28:01 +0000824
Greg Steindd6eefb2000-07-18 09:09:48 +0000825 # if TE is supplied in the header, then it must appear in a
826 # Connection header.
827 #self.putheader('Connection', 'TE')
Greg Stein5e0fa402000-06-26 08:28:01 +0000828
Greg Steindd6eefb2000-07-18 09:09:48 +0000829 else:
830 # For HTTP/1.0, the server will assume "not chunked"
831 pass
Greg Stein5e0fa402000-06-26 08:28:01 +0000832
Benjamin Petersonf608c612008-11-16 18:33:53 +0000833 def putheader(self, header, *values):
Greg Steindd6eefb2000-07-18 09:09:48 +0000834 """Send a request header line to the server.
Greg Stein5e0fa402000-06-26 08:28:01 +0000835
Greg Steindd6eefb2000-07-18 09:09:48 +0000836 For example: h.putheader('Accept', 'text/html')
837 """
838 if self.__state != _CS_REQ_STARTED:
839 raise CannotSendHeader()
Greg Stein5e0fa402000-06-26 08:28:01 +0000840
Guido van Rossum98297ee2007-11-06 21:34:58 +0000841 if hasattr(header, 'encode'):
842 header = header.encode('ascii')
Benjamin Petersonf608c612008-11-16 18:33:53 +0000843 values = list(values)
844 for i, one_value in enumerate(values):
845 if hasattr(one_value, 'encode'):
846 values[i] = one_value.encode('ascii')
847 value = b'\r\n\t'.join(values)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000848 header = header + b': ' + value
849 self._output(header)
Greg Stein5e0fa402000-06-26 08:28:01 +0000850
Benjamin Peterson1742e402008-11-30 22:15:29 +0000851 def endheaders(self, message_body=None):
852 """Indicate that the last header line has been sent to the server.
Greg Stein5e0fa402000-06-26 08:28:01 +0000853
Benjamin Peterson1742e402008-11-30 22:15:29 +0000854 This method sends the request to the server. The optional
855 message_body argument can be used to pass message body
856 associated with the request. The message body will be sent in
857 the same packet as the message headers if possible. The
858 message_body should be a string.
859 """
Greg Steindd6eefb2000-07-18 09:09:48 +0000860 if self.__state == _CS_REQ_STARTED:
861 self.__state = _CS_REQ_SENT
862 else:
863 raise CannotSendHeader()
Benjamin Peterson1742e402008-11-30 22:15:29 +0000864 self._send_output(message_body)
Greg Stein5e0fa402000-06-26 08:28:01 +0000865
Greg Steindd6eefb2000-07-18 09:09:48 +0000866 def request(self, method, url, body=None, headers={}):
867 """Send a complete request to the server."""
Jeremy Hylton636950f2009-03-28 04:34:21 +0000868 self._send_request(method, url, body, headers)
Greg Stein5e0fa402000-06-26 08:28:01 +0000869
Benjamin Peterson1742e402008-11-30 22:15:29 +0000870 def _set_content_length(self, body):
871 # Set the content-length based on the body.
872 thelen = None
873 try:
874 thelen = str(len(body))
875 except TypeError as te:
876 # If this is a file-like object, try to
877 # fstat its file descriptor
Benjamin Peterson1742e402008-11-30 22:15:29 +0000878 try:
879 thelen = str(os.fstat(body.fileno()).st_size)
880 except (AttributeError, OSError):
881 # Don't send a length if this failed
882 if self.debuglevel > 0: print("Cannot stat!!")
883
884 if thelen is not None:
885 self.putheader('Content-Length', thelen)
886
Greg Steindd6eefb2000-07-18 09:09:48 +0000887 def _send_request(self, method, url, body, headers):
Jeremy Hylton636950f2009-03-28 04:34:21 +0000888 # Honor explicitly requested Host: and Accept-Encoding: headers.
Jeremy Hylton2c178252004-08-07 16:28:14 +0000889 header_names = dict.fromkeys([k.lower() for k in headers])
890 skips = {}
891 if 'host' in header_names:
892 skips['skip_host'] = 1
893 if 'accept-encoding' in header_names:
894 skips['skip_accept_encoding'] = 1
Greg Stein5e0fa402000-06-26 08:28:01 +0000895
Jeremy Hylton2c178252004-08-07 16:28:14 +0000896 self.putrequest(method, url, **skips)
897
898 if body and ('content-length' not in header_names):
Benjamin Peterson1742e402008-11-30 22:15:29 +0000899 self._set_content_length(body)
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000900 for hdr, value in headers.items():
Greg Steindd6eefb2000-07-18 09:09:48 +0000901 self.putheader(hdr, value)
Jeremy Hyltonef9f48e2009-03-26 22:04:05 +0000902 if isinstance(body, str):
Jeremy Hylton236654b2009-03-27 20:24:34 +0000903 # RFC 2616 Section 3.7.1 says that text default has a
904 # default charset of iso-8859-1.
905 body = body.encode('iso-8859-1')
Jeremy Hyltonef9f48e2009-03-26 22:04:05 +0000906 self.endheaders(body)
Greg Stein5e0fa402000-06-26 08:28:01 +0000907
Greg Steindd6eefb2000-07-18 09:09:48 +0000908 def getresponse(self):
Jeremy Hyltonfb35f652007-08-03 20:30:33 +0000909 """Get the response from the server."""
Greg Stein5e0fa402000-06-26 08:28:01 +0000910
Greg Stein616a58d2003-06-24 06:35:19 +0000911 # if a prior response has been completed, then forget about it.
Greg Steindd6eefb2000-07-18 09:09:48 +0000912 if self.__response and self.__response.isclosed():
913 self.__response = None
Greg Stein5e0fa402000-06-26 08:28:01 +0000914
Greg Steindd6eefb2000-07-18 09:09:48 +0000915 #
916 # if a prior response exists, then it must be completed (otherwise, we
917 # cannot read this response's header to determine the connection-close
918 # behavior)
919 #
920 # note: if a prior response existed, but was connection-close, then the
921 # socket and response were made independent of this HTTPConnection
922 # object since a new request requires that we open a whole new
923 # connection
924 #
925 # this means the prior response had one of two states:
926 # 1) will_close: this connection was reset and the prior socket and
927 # response operate independently
928 # 2) persistent: the response was retained and we await its
929 # isclosed() status to become true.
930 #
931 if self.__state != _CS_REQ_SENT or self.__response:
932 raise ResponseNotReady()
Greg Stein5e0fa402000-06-26 08:28:01 +0000933
Jeremy Hylton30f86742000-09-18 22:50:38 +0000934 if self.debuglevel > 0:
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000935 response = self.response_class(self.sock, self.debuglevel,
Tim Petersc2659cf2003-05-12 20:19:37 +0000936 strict=self.strict,
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000937 method=self._method)
Jeremy Hylton30f86742000-09-18 22:50:38 +0000938 else:
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000939 response = self.response_class(self.sock, strict=self.strict,
940 method=self._method)
Greg Stein5e0fa402000-06-26 08:28:01 +0000941
Jeremy Hylton39c03802002-07-12 14:04:09 +0000942 response.begin()
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000943 assert response.will_close != _UNKNOWN
Greg Steindd6eefb2000-07-18 09:09:48 +0000944 self.__state = _CS_IDLE
Greg Stein5e0fa402000-06-26 08:28:01 +0000945
Greg Steindd6eefb2000-07-18 09:09:48 +0000946 if response.will_close:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000947 # this effectively passes the connection to the response
948 self.close()
Greg Steindd6eefb2000-07-18 09:09:48 +0000949 else:
950 # remember this, so we can tell when it is complete
951 self.__response = response
Greg Stein5e0fa402000-06-26 08:28:01 +0000952
Greg Steindd6eefb2000-07-18 09:09:48 +0000953 return response
Greg Stein5e0fa402000-06-26 08:28:01 +0000954
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000955try:
956 import ssl
957except ImportError:
958 pass
959else:
960 class HTTPSConnection(HTTPConnection):
961 "This class allows communication via SSL."
Jeremy Hylton29d27ac2002-07-09 21:22:36 +0000962
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000963 default_port = HTTPS_PORT
Jeremy Hylton29d27ac2002-07-09 21:22:36 +0000964
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000965 def __init__(self, host, port=None, key_file=None, cert_file=None,
Georg Brandlf78e02b2008-06-10 17:40:04 +0000966 strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000967 HTTPConnection.__init__(self, host, port, strict, timeout)
968 self.key_file = key_file
969 self.cert_file = cert_file
Jeremy Hylton29d27ac2002-07-09 21:22:36 +0000970
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000971 def connect(self):
972 "Connect to a host on a given (SSL) port."
Jeremy Hylton29d27ac2002-07-09 21:22:36 +0000973
Jeremy Hylton636950f2009-03-28 04:34:21 +0000974 sock = socket.create_connection((self.host, self.port),
975 self.timeout)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000976 self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file)
Jeremy Hylton29d27ac2002-07-09 21:22:36 +0000977
Jeremy Hylton29d27ac2002-07-09 21:22:36 +0000978
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000979 def FakeSocket (sock, sslobj):
Thomas Wouters89d996e2007-09-08 17:39:28 +0000980 warnings.warn("FakeSocket is deprecated, and won't be in 3.x. " +
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000981 "Use the result of ssl.wrap_socket() directly instead.",
Thomas Wouters89d996e2007-09-08 17:39:28 +0000982 DeprecationWarning, stacklevel=2)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000983 return sslobj
Jeremy Hylton29d27ac2002-07-09 21:22:36 +0000984
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000985 __all__.append("HTTPSConnection")
Greg Stein5e0fa402000-06-26 08:28:01 +0000986
Greg Stein5e0fa402000-06-26 08:28:01 +0000987class HTTPException(Exception):
Jeremy Hylton12f4f352002-07-06 18:55:01 +0000988 # Subclasses that define an __init__ must call Exception.__init__
989 # or define self.args. Otherwise, str() will fail.
Greg Steindd6eefb2000-07-18 09:09:48 +0000990 pass
Greg Stein5e0fa402000-06-26 08:28:01 +0000991
992class NotConnected(HTTPException):
Greg Steindd6eefb2000-07-18 09:09:48 +0000993 pass
Greg Stein5e0fa402000-06-26 08:28:01 +0000994
Skip Montanaro9d389972002-03-24 16:53:50 +0000995class InvalidURL(HTTPException):
996 pass
997
Greg Stein5e0fa402000-06-26 08:28:01 +0000998class UnknownProtocol(HTTPException):
Greg Steindd6eefb2000-07-18 09:09:48 +0000999 def __init__(self, version):
Jeremy Hylton12f4f352002-07-06 18:55:01 +00001000 self.args = version,
Greg Steindd6eefb2000-07-18 09:09:48 +00001001 self.version = version
Greg Stein5e0fa402000-06-26 08:28:01 +00001002
1003class UnknownTransferEncoding(HTTPException):
Greg Steindd6eefb2000-07-18 09:09:48 +00001004 pass
Greg Stein5e0fa402000-06-26 08:28:01 +00001005
Greg Stein5e0fa402000-06-26 08:28:01 +00001006class UnimplementedFileMode(HTTPException):
Greg Steindd6eefb2000-07-18 09:09:48 +00001007 pass
Greg Stein5e0fa402000-06-26 08:28:01 +00001008
1009class IncompleteRead(HTTPException):
Benjamin Peterson6accb982009-03-02 22:50:25 +00001010 def __init__(self, partial, expected=None):
Jeremy Hylton12f4f352002-07-06 18:55:01 +00001011 self.args = partial,
Greg Steindd6eefb2000-07-18 09:09:48 +00001012 self.partial = partial
Benjamin Peterson6accb982009-03-02 22:50:25 +00001013 self.expected = expected
1014 def __repr__(self):
1015 if self.expected is not None:
1016 e = ', %i more expected' % self.expected
1017 else:
1018 e = ''
1019 return 'IncompleteRead(%i bytes read%s)' % (len(self.partial), e)
1020 def __str__(self):
1021 return repr(self)
Greg Stein5e0fa402000-06-26 08:28:01 +00001022
1023class ImproperConnectionState(HTTPException):
Greg Steindd6eefb2000-07-18 09:09:48 +00001024 pass
Greg Stein5e0fa402000-06-26 08:28:01 +00001025
1026class CannotSendRequest(ImproperConnectionState):
Greg Steindd6eefb2000-07-18 09:09:48 +00001027 pass
Greg Stein5e0fa402000-06-26 08:28:01 +00001028
1029class CannotSendHeader(ImproperConnectionState):
Greg Steindd6eefb2000-07-18 09:09:48 +00001030 pass
Greg Stein5e0fa402000-06-26 08:28:01 +00001031
1032class ResponseNotReady(ImproperConnectionState):
Greg Steindd6eefb2000-07-18 09:09:48 +00001033 pass
Greg Stein5e0fa402000-06-26 08:28:01 +00001034
1035class BadStatusLine(HTTPException):
Greg Steindd6eefb2000-07-18 09:09:48 +00001036 def __init__(self, line):
Jeremy Hylton12f4f352002-07-06 18:55:01 +00001037 self.args = line,
Greg Steindd6eefb2000-07-18 09:09:48 +00001038 self.line = line
Greg Stein5e0fa402000-06-26 08:28:01 +00001039
1040# for backwards compatibility
1041error = HTTPException
1042
Jeremy Hyltond46aa372002-07-06 18:48:07 +00001043class LineAndFileWrapper:
1044 """A limited file-like object for HTTP/0.9 responses."""
1045
1046 # The status-line parsing code calls readline(), which normally
1047 # get the HTTP status line. For a 0.9 response, however, this is
1048 # actually the first line of the body! Clients need to get a
1049 # readable file object that contains that line.
1050
1051 def __init__(self, line, file):
1052 self._line = line
1053 self._file = file
1054 self._line_consumed = 0
1055 self._line_offset = 0
1056 self._line_left = len(line)
1057
1058 def __getattr__(self, attr):
1059 return getattr(self._file, attr)
1060
1061 def _done(self):
1062 # called when the last byte is read from the line. After the
1063 # call, all read methods are delegated to the underlying file
Skip Montanaro74b9a7a2003-02-25 17:48:15 +00001064 # object.
Jeremy Hyltond46aa372002-07-06 18:48:07 +00001065 self._line_consumed = 1
1066 self.read = self._file.read
1067 self.readline = self._file.readline
1068 self.readlines = self._file.readlines
1069
1070 def read(self, amt=None):
Hye-Shik Chang39aef792004-06-05 13:30:56 +00001071 if self._line_consumed:
1072 return self._file.read(amt)
1073 assert self._line_left
Jeremy Hyltond46aa372002-07-06 18:48:07 +00001074 if amt is None or amt > self._line_left:
1075 s = self._line[self._line_offset:]
1076 self._done()
1077 if amt is None:
1078 return s + self._file.read()
1079 else:
Tim Petersc411dba2002-07-16 21:35:23 +00001080 return s + self._file.read(amt - len(s))
Jeremy Hyltond46aa372002-07-06 18:48:07 +00001081 else:
1082 assert amt <= self._line_left
1083 i = self._line_offset
1084 j = i + amt
1085 s = self._line[i:j]
1086 self._line_offset = j
1087 self._line_left -= amt
1088 if self._line_left == 0:
1089 self._done()
1090 return s
Tim Petersc411dba2002-07-16 21:35:23 +00001091
Jeremy Hyltond46aa372002-07-06 18:48:07 +00001092 def readline(self):
Hye-Shik Chang39aef792004-06-05 13:30:56 +00001093 if self._line_consumed:
1094 return self._file.readline()
1095 assert self._line_left
Jeremy Hyltond46aa372002-07-06 18:48:07 +00001096 s = self._line[self._line_offset:]
1097 self._done()
1098 return s
1099
1100 def readlines(self, size=None):
Hye-Shik Chang39aef792004-06-05 13:30:56 +00001101 if self._line_consumed:
1102 return self._file.readlines(size)
1103 assert self._line_left
Jeremy Hyltond46aa372002-07-06 18:48:07 +00001104 L = [self._line[self._line_offset:]]
1105 self._done()
1106 if size is None:
1107 return L + self._file.readlines()
1108 else:
1109 return L + self._file.readlines(size)