blob: 1fe010cc842576ff358d2fa5b110757c3597d5bc [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
Jeremy Hyltonfb35f652007-08-03 20:30:33 +000069import io
Jeremy Hylton6459c8d2001-10-11 17:47:22 +000070import socket
Barry Warsaw820c1202008-06-12 04:06:45 +000071import email.parser
72import email.message
Jeremy Hylton1afc1692008-06-18 20:49:58 +000073from urllib.parse import urlsplit
Thomas Wouters89d996e2007-09-08 17:39:28 +000074import warnings
Guido van Rossum23acc951994-02-21 16:36:04 +000075
Thomas Wouters47b49bf2007-08-30 22:15:33 +000076__all__ = ["HTTPResponse", "HTTPConnection",
Skip Montanaro951a8842001-06-01 16:25:38 +000077 "HTTPException", "NotConnected", "UnknownProtocol",
Jeremy Hylton7c75c992002-06-28 23:38:14 +000078 "UnknownTransferEncoding", "UnimplementedFileMode",
79 "IncompleteRead", "InvalidURL", "ImproperConnectionState",
80 "CannotSendRequest", "CannotSendHeader", "ResponseNotReady",
Georg Brandl6aab16e2006-02-17 19:17:25 +000081 "BadStatusLine", "error", "responses"]
Skip Montanaro2dd42762001-01-23 15:35:05 +000082
Guido van Rossum23acc951994-02-21 16:36:04 +000083HTTP_PORT = 80
Guido van Rossum09c8b6c1999-12-07 21:37:17 +000084HTTPS_PORT = 443
85
Greg Stein5e0fa402000-06-26 08:28:01 +000086_UNKNOWN = 'UNKNOWN'
87
88# connection states
89_CS_IDLE = 'Idle'
90_CS_REQ_STARTED = 'Request-started'
91_CS_REQ_SENT = 'Request-sent'
92
Martin v. Löwis39a31782004-09-18 09:03:49 +000093# status codes
94# informational
95CONTINUE = 100
96SWITCHING_PROTOCOLS = 101
97PROCESSING = 102
98
99# successful
100OK = 200
101CREATED = 201
102ACCEPTED = 202
103NON_AUTHORITATIVE_INFORMATION = 203
104NO_CONTENT = 204
105RESET_CONTENT = 205
106PARTIAL_CONTENT = 206
107MULTI_STATUS = 207
108IM_USED = 226
109
110# redirection
111MULTIPLE_CHOICES = 300
112MOVED_PERMANENTLY = 301
113FOUND = 302
114SEE_OTHER = 303
115NOT_MODIFIED = 304
116USE_PROXY = 305
117TEMPORARY_REDIRECT = 307
118
119# client error
120BAD_REQUEST = 400
121UNAUTHORIZED = 401
122PAYMENT_REQUIRED = 402
123FORBIDDEN = 403
124NOT_FOUND = 404
125METHOD_NOT_ALLOWED = 405
126NOT_ACCEPTABLE = 406
127PROXY_AUTHENTICATION_REQUIRED = 407
128REQUEST_TIMEOUT = 408
129CONFLICT = 409
130GONE = 410
131LENGTH_REQUIRED = 411
132PRECONDITION_FAILED = 412
133REQUEST_ENTITY_TOO_LARGE = 413
134REQUEST_URI_TOO_LONG = 414
135UNSUPPORTED_MEDIA_TYPE = 415
136REQUESTED_RANGE_NOT_SATISFIABLE = 416
137EXPECTATION_FAILED = 417
138UNPROCESSABLE_ENTITY = 422
139LOCKED = 423
140FAILED_DEPENDENCY = 424
141UPGRADE_REQUIRED = 426
142
143# server error
144INTERNAL_SERVER_ERROR = 500
145NOT_IMPLEMENTED = 501
146BAD_GATEWAY = 502
147SERVICE_UNAVAILABLE = 503
148GATEWAY_TIMEOUT = 504
149HTTP_VERSION_NOT_SUPPORTED = 505
150INSUFFICIENT_STORAGE = 507
151NOT_EXTENDED = 510
152
Georg Brandl6aab16e2006-02-17 19:17:25 +0000153# Mapping status codes to official W3C names
154responses = {
155 100: 'Continue',
156 101: 'Switching Protocols',
157
158 200: 'OK',
159 201: 'Created',
160 202: 'Accepted',
161 203: 'Non-Authoritative Information',
162 204: 'No Content',
163 205: 'Reset Content',
164 206: 'Partial Content',
165
166 300: 'Multiple Choices',
167 301: 'Moved Permanently',
168 302: 'Found',
169 303: 'See Other',
170 304: 'Not Modified',
171 305: 'Use Proxy',
172 306: '(Unused)',
173 307: 'Temporary Redirect',
174
175 400: 'Bad Request',
176 401: 'Unauthorized',
177 402: 'Payment Required',
178 403: 'Forbidden',
179 404: 'Not Found',
180 405: 'Method Not Allowed',
181 406: 'Not Acceptable',
182 407: 'Proxy Authentication Required',
183 408: 'Request Timeout',
184 409: 'Conflict',
185 410: 'Gone',
186 411: 'Length Required',
187 412: 'Precondition Failed',
188 413: 'Request Entity Too Large',
189 414: 'Request-URI Too Long',
190 415: 'Unsupported Media Type',
191 416: 'Requested Range Not Satisfiable',
192 417: 'Expectation Failed',
193
194 500: 'Internal Server Error',
195 501: 'Not Implemented',
196 502: 'Bad Gateway',
197 503: 'Service Unavailable',
198 504: 'Gateway Timeout',
199 505: 'HTTP Version Not Supported',
200}
201
Georg Brandl80ba8e82005-09-29 20:16:07 +0000202# maximal amount of data to read at one time in _safe_read
203MAXAMOUNT = 1048576
204
Barry Warsaw820c1202008-06-12 04:06:45 +0000205class HTTPMessage(email.message.Message):
206 def getallmatchingheaders(self, name):
207 """Find all header lines matching a given header name.
Jeremy Hylton6d0a4c72002-07-07 16:51:37 +0000208
Barry Warsaw820c1202008-06-12 04:06:45 +0000209 Look through the list of headers and find all lines matching a given
210 header name (and their continuation lines). A list of the lines is
211 returned, without interpretation. If the header does not occur, an
212 empty list is returned. If the header occurs multiple times, all
213 occurrences are returned. Case is not important in the header name.
Jeremy Hylton6d0a4c72002-07-07 16:51:37 +0000214
Jeremy Hylton6d0a4c72002-07-07 16:51:37 +0000215 """
Barry Warsaw820c1202008-06-12 04:06:45 +0000216 # XXX: copied from rfc822.Message for compatibility
217 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
Barry Warsaw820c1202008-06-12 04:06:45 +0000230def parse_headers(fp):
231 """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')
247
248 return email.parser.Parser(_class=HTTPMessage).parsestr(hstring)
Greg Stein5e0fa402000-06-26 08:28:01 +0000249
Antoine Pitroub353c122009-02-11 00:39:14 +0000250class HTTPResponse(io.RawIOBase):
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000251
252 # strict: If true, raise BadStatusLine if the status line can't be
253 # parsed as a valid HTTP/1.0 or 1.1 status line. By default it is
Skip Montanaro186bec22002-07-25 16:10:38 +0000254 # false because it prevents clients from talking to HTTP/0.9
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000255 # servers. Note that a response with a sufficiently corrupted
256 # status line will look like an HTTP/0.9 response.
257
258 # See RFC 2616 sec 19.6 and RFC 1945 sec 6 for details.
259
Jeremy Hylton811fc142007-08-03 13:30:02 +0000260 # The bytes from the socket object are iso-8859-1 strings.
261 # See RFC 2616 sec 2.2 which notes an exception for MIME-encoded
262 # text following RFC 2047. The basic status line parsing only
263 # accepts iso-8859-1.
264
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000265 def __init__(self, sock, debuglevel=0, strict=0, method=None):
Kristján Valur Jónsson7e11b3f2009-02-02 16:04:04 +0000266 # If the response includes a content-length header, we
Jeremy Hylton39b198d2007-08-04 19:22:00 +0000267 # need to make sure that the client doesn't read more than the
268 # specified number of bytes. If it does, it will block until
269 # the server times out and closes the connection. (The only
Kristján Valur Jónsson7e11b3f2009-02-02 16:04:04 +0000270 # applies to HTTP/1.1 connections.) This will happen if a self.fp.read()
271 # is done (without a size) whether self.fp is buffered or not.
272 # So, no self.fp.read() by clients unless they know what they are doing.
Benjamin Petersonf72d9fb2009-02-08 00:29:20 +0000273 self.fp = sock.makefile("rb")
Jeremy Hylton30f86742000-09-18 22:50:38 +0000274 self.debuglevel = debuglevel
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000275 self.strict = strict
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000276 self._method = method
Greg Stein5e0fa402000-06-26 08:28:01 +0000277
Greg Steindd6eefb2000-07-18 09:09:48 +0000278 self.msg = None
Greg Stein5e0fa402000-06-26 08:28:01 +0000279
Greg Steindd6eefb2000-07-18 09:09:48 +0000280 # from the Status-Line of the response
Tim Peters07e99cb2001-01-14 23:47:14 +0000281 self.version = _UNKNOWN # HTTP-Version
282 self.status = _UNKNOWN # Status-Code
283 self.reason = _UNKNOWN # Reason-Phrase
Greg Stein5e0fa402000-06-26 08:28:01 +0000284
Tim Peters07e99cb2001-01-14 23:47:14 +0000285 self.chunked = _UNKNOWN # is "chunked" being used?
286 self.chunk_left = _UNKNOWN # bytes left to read in current chunk
287 self.length = _UNKNOWN # number of bytes left in response
288 self.will_close = _UNKNOWN # conn will close at end of response
Greg Stein5e0fa402000-06-26 08:28:01 +0000289
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000290 def _read_status(self):
Jeremy Hylton04319c72007-08-04 03:41:19 +0000291 # Initialize with Simple-Response defaults.
Jeremy Hylton811fc142007-08-03 13:30:02 +0000292 line = str(self.fp.readline(), "iso-8859-1")
Jeremy Hylton30f86742000-09-18 22:50:38 +0000293 if self.debuglevel > 0:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000294 print("reply:", repr(line))
Jeremy Hyltonb6769522003-06-29 17:55:05 +0000295 if not line:
296 # Presumably, the server closed the connection before
297 # sending a valid response.
298 raise BadStatusLine(line)
Greg Steindd6eefb2000-07-18 09:09:48 +0000299 try:
Guido van Rossum34735a62000-12-15 15:09:42 +0000300 [version, status, reason] = line.split(None, 2)
Greg Steindd6eefb2000-07-18 09:09:48 +0000301 except ValueError:
302 try:
Guido van Rossum34735a62000-12-15 15:09:42 +0000303 [version, status] = line.split(None, 1)
Greg Steindd6eefb2000-07-18 09:09:48 +0000304 reason = ""
305 except ValueError:
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000306 # empty version will cause next test to fail and status
307 # will be treated as 0.9 response.
308 version = ""
Jeremy Hyltone5d0e842007-08-03 13:45:24 +0000309 if not version.startswith("HTTP/"):
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000310 if self.strict:
311 self.close()
312 raise BadStatusLine(line)
313 else:
Jeremy Hylton04319c72007-08-04 03:41:19 +0000314 # Assume it's a Simple-Response from an 0.9 server.
315 # We have to convert the first line back to raw bytes
316 # because self.fp.readline() needs to return bytes.
Guido van Rossum70d0dda2007-08-29 01:53:26 +0000317 self.fp = LineAndFileWrapper(bytes(line, "ascii"), self.fp)
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000318 return "HTTP/0.9", 200, ""
Greg Stein5e0fa402000-06-26 08:28:01 +0000319
Jeremy Hylton23d40472001-04-13 14:57:08 +0000320 # The status code is a three-digit number
321 try:
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000322 status = int(status)
Jeremy Hylton23d40472001-04-13 14:57:08 +0000323 if status < 100 or status > 999:
324 raise BadStatusLine(line)
325 except ValueError:
326 raise BadStatusLine(line)
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000327 return version, status, reason
Greg Stein5e0fa402000-06-26 08:28:01 +0000328
Jeremy Hylton39c03802002-07-12 14:04:09 +0000329 def begin(self):
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000330 if self.msg is not None:
331 # we've already started reading the response
332 return
333
334 # read until we get a non-100 response
Raymond Hettingerb2e0b922003-02-26 22:45:18 +0000335 while True:
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000336 version, status, reason = self._read_status()
Martin v. Löwis39a31782004-09-18 09:03:49 +0000337 if status != CONTINUE:
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000338 break
339 # skip the header from the 100 response
Raymond Hettingerb2e0b922003-02-26 22:45:18 +0000340 while True:
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000341 skip = self.fp.readline().strip()
342 if not skip:
343 break
344 if self.debuglevel > 0:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000345 print("header:", skip)
Tim Petersc411dba2002-07-16 21:35:23 +0000346
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000347 self.status = status
348 self.reason = reason.strip()
Jeremy Hyltone5d0e842007-08-03 13:45:24 +0000349 if version == "HTTP/1.0":
Greg Steindd6eefb2000-07-18 09:09:48 +0000350 self.version = 10
Jeremy Hyltone5d0e842007-08-03 13:45:24 +0000351 elif version.startswith("HTTP/1."):
Tim Peters07e99cb2001-01-14 23:47:14 +0000352 self.version = 11 # use HTTP/1.1 code for HTTP/1.x where x>=1
Jeremy Hyltone5d0e842007-08-03 13:45:24 +0000353 elif version == "HTTP/0.9":
Jeremy Hylton110941a2000-10-12 19:58:36 +0000354 self.version = 9
Greg Steindd6eefb2000-07-18 09:09:48 +0000355 else:
356 raise UnknownProtocol(version)
Greg Stein5e0fa402000-06-26 08:28:01 +0000357
Jeremy Hylton110941a2000-10-12 19:58:36 +0000358 if self.version == 9:
Georg Brandl0aade9a2005-06-26 22:06:54 +0000359 self.length = None
Jeremy Hylton236156f2008-12-15 03:00:50 +0000360 self.chunked = False
361 self.will_close = True
Barry Warsaw820c1202008-06-12 04:06:45 +0000362 self.msg = email.message_from_string('')
Jeremy Hylton110941a2000-10-12 19:58:36 +0000363 return
364
Barry Warsaw820c1202008-06-12 04:06:45 +0000365 self.msg = parse_headers(self.fp)
366
Jeremy Hylton30f86742000-09-18 22:50:38 +0000367 if self.debuglevel > 0:
Barry Warsaw820c1202008-06-12 04:06:45 +0000368 for hdr in self.msg:
Jeremy Hyltone5d0e842007-08-03 13:45:24 +0000369 print("header:", hdr, end=" ")
Greg Stein5e0fa402000-06-26 08:28:01 +0000370
Greg Steindd6eefb2000-07-18 09:09:48 +0000371 # are we using the chunked-style of transfer encoding?
Barry Warsaw820c1202008-06-12 04:06:45 +0000372 tr_enc = self.msg.get("transfer-encoding")
Jeremy Hyltond229b3a2002-09-03 19:24:24 +0000373 if tr_enc and tr_enc.lower() == "chunked":
Jeremy Hylton236156f2008-12-15 03:00:50 +0000374 self.chunked = True
Greg Steindd6eefb2000-07-18 09:09:48 +0000375 self.chunk_left = None
376 else:
Jeremy Hylton236156f2008-12-15 03:00:50 +0000377 self.chunked = False
Greg Stein5e0fa402000-06-26 08:28:01 +0000378
Greg Steindd6eefb2000-07-18 09:09:48 +0000379 # will the connection close at the end of the response?
Jeremy Hylton22b3a492002-11-13 17:27:43 +0000380 self.will_close = self._check_close()
Greg Stein5e0fa402000-06-26 08:28:01 +0000381
Greg Steindd6eefb2000-07-18 09:09:48 +0000382 # do we have a Content-Length?
383 # NOTE: RFC 2616, S4.4, #3 says we ignore this if tr_enc is "chunked"
Jeremy Hylton0ee5eeb2007-08-04 03:25:17 +0000384 self.length = None
Barry Warsaw820c1202008-06-12 04:06:45 +0000385 length = self.msg.get("content-length")
386
387 # are we using the chunked-style of transfer encoding?
388 tr_enc = self.msg.get("transfer-encoding")
Greg Steindd6eefb2000-07-18 09:09:48 +0000389 if length and not self.chunked:
Jeremy Hylton30a81812000-09-14 20:34:27 +0000390 try:
391 self.length = int(length)
392 except ValueError:
Christian Heimesa612dc02008-02-24 13:08:18 +0000393 self.length = None
394 else:
395 if self.length < 0: # ignore nonsensical negative lengths
396 self.length = None
397 else:
398 self.length = None
Greg Stein5e0fa402000-06-26 08:28:01 +0000399
Greg Steindd6eefb2000-07-18 09:09:48 +0000400 # does the body have a fixed length? (of zero)
Martin v. Löwis39a31782004-09-18 09:03:49 +0000401 if (status == NO_CONTENT or status == NOT_MODIFIED or
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000402 100 <= status < 200 or # 1xx codes
Jeremy Hyltone5d0e842007-08-03 13:45:24 +0000403 self._method == "HEAD"):
Greg Steindd6eefb2000-07-18 09:09:48 +0000404 self.length = 0
Greg Stein5e0fa402000-06-26 08:28:01 +0000405
Greg Steindd6eefb2000-07-18 09:09:48 +0000406 # if the connection remains open, and we aren't using chunked, and
407 # a content-length was not provided, then assume that the connection
408 # WILL close.
Jeremy Hylton0ee5eeb2007-08-04 03:25:17 +0000409 if (not self.will_close and
410 not self.chunked and
411 self.length is None):
Jeremy Hylton236156f2008-12-15 03:00:50 +0000412 self.will_close = True
Greg Stein5e0fa402000-06-26 08:28:01 +0000413
Jeremy Hylton22b3a492002-11-13 17:27:43 +0000414 def _check_close(self):
Barry Warsaw820c1202008-06-12 04:06:45 +0000415 conn = self.msg.get("connection")
Jeremy Hylton22b3a492002-11-13 17:27:43 +0000416 if self.version == 11:
417 # An HTTP/1.1 proxy is assumed to stay open unless
418 # explicitly closed.
Barry Warsaw820c1202008-06-12 04:06:45 +0000419 conn = self.msg.get("connection")
Raymond Hettingerbac788a2004-05-04 09:21:43 +0000420 if conn and "close" in conn.lower():
Jeremy Hylton22b3a492002-11-13 17:27:43 +0000421 return True
422 return False
423
Jeremy Hylton2c178252004-08-07 16:28:14 +0000424 # Some HTTP/1.0 implementations have support for persistent
425 # connections, using rules different than HTTP/1.1.
Jeremy Hylton22b3a492002-11-13 17:27:43 +0000426
Christian Heimes895627f2007-12-08 17:28:33 +0000427 # For older HTTP, Keep-Alive indicates persistent connection.
Barry Warsaw820c1202008-06-12 04:06:45 +0000428 if self.msg.get("keep-alive"):
Jeremy Hylton22b3a492002-11-13 17:27:43 +0000429 return False
Tim Peters77c06fb2002-11-24 02:35:35 +0000430
Jeremy Hylton2c178252004-08-07 16:28:14 +0000431 # At least Akamai returns a "Connection: Keep-Alive" header,
432 # which was supposed to be sent by the client.
433 if conn and "keep-alive" in conn.lower():
434 return False
435
Jeremy Hylton22b3a492002-11-13 17:27:43 +0000436 # Proxy-Connection is a netscape hack.
Barry Warsaw820c1202008-06-12 04:06:45 +0000437 pconn = self.msg.get("proxy-connection")
Raymond Hettingerbac788a2004-05-04 09:21:43 +0000438 if pconn and "keep-alive" in pconn.lower():
Jeremy Hylton22b3a492002-11-13 17:27:43 +0000439 return False
440
441 # otherwise, assume it will close
442 return True
443
Greg Steindd6eefb2000-07-18 09:09:48 +0000444 def close(self):
445 if self.fp:
446 self.fp.close()
447 self.fp = None
Greg Stein5e0fa402000-06-26 08:28:01 +0000448
Jeremy Hyltondf5f6b52007-08-08 17:36:33 +0000449 # These implementations are for the benefit of io.BufferedReader.
450
451 # XXX This class should probably be revised to act more like
452 # the "raw stream" that BufferedReader expects.
453
454 @property
455 def closed(self):
456 return self.isclosed()
457
458 def flush(self):
459 self.fp.flush()
460
461 # End of "raw stream" methods
462
Greg Steindd6eefb2000-07-18 09:09:48 +0000463 def isclosed(self):
464 # NOTE: it is possible that we will not ever call self.close(). This
465 # case occurs when will_close is TRUE, length is None, and we
466 # read up to the last byte, but NOT past it.
467 #
468 # IMPLIES: if will_close is FALSE, then self.close() will ALWAYS be
469 # called, meaning self.isclosed() is meaningful.
470 return self.fp is None
471
472 def read(self, amt=None):
473 if self.fp is None:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000474 return b""
Greg Steindd6eefb2000-07-18 09:09:48 +0000475
476 if self.chunked:
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000477 return self._read_chunked(amt)
Tim Peters230a60c2002-11-09 05:08:07 +0000478
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000479 if amt is None:
Greg Steindd6eefb2000-07-18 09:09:48 +0000480 # unbounded read
Jeremy Hyltondef9d2a2004-11-07 16:13:49 +0000481 if self.length is None:
Greg Steindd6eefb2000-07-18 09:09:48 +0000482 s = self.fp.read()
483 else:
484 s = self._safe_read(self.length)
Jeremy Hyltondef9d2a2004-11-07 16:13:49 +0000485 self.length = 0
Tim Peters07e99cb2001-01-14 23:47:14 +0000486 self.close() # we read everything
Greg Steindd6eefb2000-07-18 09:09:48 +0000487 return s
488
489 if self.length is not None:
490 if amt > self.length:
491 # clip the read to the "end of response"
492 amt = self.length
Greg Steindd6eefb2000-07-18 09:09:48 +0000493
494 # we do not use _safe_read() here because this may be a .will_close
495 # connection, and the user is reading more bytes than will be provided
496 # (for example, reading in 1k chunks)
497 s = self.fp.read(amt)
Jeremy Hyltondef9d2a2004-11-07 16:13:49 +0000498 if self.length is not None:
499 self.length -= len(s)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000500 if not self.length:
501 self.close()
Greg Steindd6eefb2000-07-18 09:09:48 +0000502 return s
503
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000504 def _read_chunked(self, amt):
505 assert self.chunked != _UNKNOWN
506 chunk_left = self.chunk_left
Georg Brandl95ba4692008-01-26 09:45:58 +0000507 value = b""
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000508
509 # XXX This accumulates chunks by repeated string concatenation,
510 # which is not efficient as the number or size of chunks gets big.
Raymond Hettingerb2e0b922003-02-26 22:45:18 +0000511 while True:
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000512 if chunk_left is None:
513 line = self.fp.readline()
Georg Brandl95ba4692008-01-26 09:45:58 +0000514 i = line.find(b";")
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000515 if i >= 0:
516 line = line[:i] # strip chunk-extensions
Christian Heimesa612dc02008-02-24 13:08:18 +0000517 try:
518 chunk_left = int(line, 16)
519 except ValueError:
520 # close the connection as protocol synchronisation is
521 # probably lost
522 self.close()
523 raise IncompleteRead(value)
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000524 if chunk_left == 0:
525 break
526 if amt is None:
527 value += self._safe_read(chunk_left)
528 elif amt < chunk_left:
529 value += self._safe_read(amt)
530 self.chunk_left = chunk_left - amt
531 return value
532 elif amt == chunk_left:
533 value += self._safe_read(amt)
534 self._safe_read(2) # toss the CRLF at the end of the chunk
535 self.chunk_left = None
536 return value
537 else:
538 value += self._safe_read(chunk_left)
539 amt -= chunk_left
540
541 # we read the whole chunk, get another
542 self._safe_read(2) # toss the CRLF at the end of the chunk
543 chunk_left = None
544
545 # read and discard trailer up to the CRLF terminator
546 ### note: we shouldn't have any trailers!
Raymond Hettingerb2e0b922003-02-26 22:45:18 +0000547 while True:
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000548 line = self.fp.readline()
Christian Heimes0bd4e112008-02-12 22:59:25 +0000549 if not line:
550 # a vanishingly small number of sites EOF without
551 # sending the trailer
552 break
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000553 if line == b"\r\n":
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000554 break
555
556 # we read everything; close the "file"
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000557 self.close()
558
559 return value
Tim Peters230a60c2002-11-09 05:08:07 +0000560
Greg Steindd6eefb2000-07-18 09:09:48 +0000561 def _safe_read(self, amt):
562 """Read the number of bytes requested, compensating for partial reads.
563
564 Normally, we have a blocking socket, but a read() can be interrupted
565 by a signal (resulting in a partial read).
566
567 Note that we cannot distinguish between EOF and an interrupt when zero
568 bytes have been read. IncompleteRead() will be raised in this
569 situation.
570
571 This function should be used when <amt> bytes "should" be present for
572 reading. If the bytes are truly not available (due to EOF), then the
573 IncompleteRead exception can be used to detect the problem.
574 """
Georg Brandl80ba8e82005-09-29 20:16:07 +0000575 s = []
Greg Steindd6eefb2000-07-18 09:09:48 +0000576 while amt > 0:
Georg Brandl80ba8e82005-09-29 20:16:07 +0000577 chunk = self.fp.read(min(amt, MAXAMOUNT))
Greg Steindd6eefb2000-07-18 09:09:48 +0000578 if not chunk:
Benjamin Peterson6accb982009-03-02 22:50:25 +0000579 raise IncompleteRead(b''.join(s), amt)
Georg Brandl80ba8e82005-09-29 20:16:07 +0000580 s.append(chunk)
Raymond Hettingerb2e0b922003-02-26 22:45:18 +0000581 amt -= len(chunk)
Guido van Rossuma00f1232007-09-12 19:43:09 +0000582 return b"".join(s)
Greg Steindd6eefb2000-07-18 09:09:48 +0000583
Antoine Pitroub353c122009-02-11 00:39:14 +0000584 def fileno(self):
585 return self.fp.fileno()
586
Greg Steindd6eefb2000-07-18 09:09:48 +0000587 def getheader(self, name, default=None):
588 if self.msg is None:
589 raise ResponseNotReady()
Barry Warsaw820c1202008-06-12 04:06:45 +0000590 return ', '.join(self.msg.get_all(name, default))
Greg Stein5e0fa402000-06-26 08:28:01 +0000591
Martin v. Löwisdeacce22004-08-18 12:46:26 +0000592 def getheaders(self):
593 """Return list of (header, value) tuples."""
594 if self.msg is None:
595 raise ResponseNotReady()
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000596 return list(self.msg.items())
Martin v. Löwisdeacce22004-08-18 12:46:26 +0000597
Antoine Pitroub353c122009-02-11 00:39:14 +0000598 # We override IOBase.__iter__ so that it doesn't check for closed-ness
599
600 def __iter__(self):
601 return self
602
Greg Stein5e0fa402000-06-26 08:28:01 +0000603
604class HTTPConnection:
605
Greg Steindd6eefb2000-07-18 09:09:48 +0000606 _http_vsn = 11
607 _http_vsn_str = 'HTTP/1.1'
Greg Stein5e0fa402000-06-26 08:28:01 +0000608
Greg Steindd6eefb2000-07-18 09:09:48 +0000609 response_class = HTTPResponse
610 default_port = HTTP_PORT
611 auto_open = 1
Jeremy Hylton30f86742000-09-18 22:50:38 +0000612 debuglevel = 0
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000613 strict = 0
Greg Stein5e0fa402000-06-26 08:28:01 +0000614
Georg Brandlf78e02b2008-06-10 17:40:04 +0000615 def __init__(self, host, port=None, strict=None,
616 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000617 self.timeout = timeout
Greg Steindd6eefb2000-07-18 09:09:48 +0000618 self.sock = None
Jeremy Hylton8531b1b2002-07-16 21:21:11 +0000619 self._buffer = []
Greg Steindd6eefb2000-07-18 09:09:48 +0000620 self.__response = None
621 self.__state = _CS_IDLE
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000622 self._method = None
Tim Petersc411dba2002-07-16 21:35:23 +0000623
Greg Steindd6eefb2000-07-18 09:09:48 +0000624 self._set_hostport(host, port)
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000625 if strict is not None:
626 self.strict = strict
Greg Stein5e0fa402000-06-26 08:28:01 +0000627
Greg Steindd6eefb2000-07-18 09:09:48 +0000628 def _set_hostport(self, host, port):
629 if port is None:
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000630 i = host.rfind(':')
Skip Montanarocae14d22004-09-14 17:55:21 +0000631 j = host.rfind(']') # ipv6 addresses have [...]
632 if i > j:
Skip Montanaro9d389972002-03-24 16:53:50 +0000633 try:
634 port = int(host[i+1:])
635 except ValueError:
Jeremy Hyltonfbd79942002-07-02 20:19:08 +0000636 raise InvalidURL("nonnumeric port: '%s'" % host[i+1:])
Greg Steindd6eefb2000-07-18 09:09:48 +0000637 host = host[:i]
638 else:
639 port = self.default_port
Raymond Hettinger4d037912004-10-14 15:23:38 +0000640 if host and host[0] == '[' and host[-1] == ']':
Brett Cannon0a1af4a2004-09-15 23:26:23 +0000641 host = host[1:-1]
Greg Steindd6eefb2000-07-18 09:09:48 +0000642 self.host = host
643 self.port = port
Greg Stein5e0fa402000-06-26 08:28:01 +0000644
Jeremy Hylton30f86742000-09-18 22:50:38 +0000645 def set_debuglevel(self, level):
646 self.debuglevel = level
647
Greg Steindd6eefb2000-07-18 09:09:48 +0000648 def connect(self):
649 """Connect to the host and port specified in __init__."""
Guido van Rossumd8faa362007-04-27 19:54:29 +0000650 self.sock = socket.create_connection((self.host,self.port),
651 self.timeout)
Greg Stein5e0fa402000-06-26 08:28:01 +0000652
Greg Steindd6eefb2000-07-18 09:09:48 +0000653 def close(self):
654 """Close the connection to the HTTP server."""
655 if self.sock:
Tim Peters07e99cb2001-01-14 23:47:14 +0000656 self.sock.close() # close it manually... there may be other refs
Greg Steindd6eefb2000-07-18 09:09:48 +0000657 self.sock = None
658 if self.__response:
659 self.__response.close()
660 self.__response = None
661 self.__state = _CS_IDLE
Greg Stein5e0fa402000-06-26 08:28:01 +0000662
Greg Steindd6eefb2000-07-18 09:09:48 +0000663 def send(self, str):
664 """Send `str' to the server."""
665 if self.sock is None:
666 if self.auto_open:
667 self.connect()
668 else:
669 raise NotConnected()
Greg Stein5e0fa402000-06-26 08:28:01 +0000670
Jeremy Hyltone3252ec2002-07-16 21:41:43 +0000671 # send the data to the server. if we get a broken pipe, then close
Greg Steindd6eefb2000-07-18 09:09:48 +0000672 # the socket. we want to reconnect when somebody tries to send again.
673 #
674 # NOTE: we DO propagate the error, though, because we cannot simply
675 # ignore the error... the caller will know if they can retry.
Jeremy Hylton30f86742000-09-18 22:50:38 +0000676 if self.debuglevel > 0:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000677 print("send:", repr(str))
Greg Steindd6eefb2000-07-18 09:09:48 +0000678 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000679 blocksize=8192
680 if hasattr(str,'read') :
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000681 if self.debuglevel > 0: print("sendIng a read()able")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000682 data=str.read(blocksize)
683 while data:
684 self.sock.sendall(data)
685 data=str.read(blocksize)
686 else:
687 self.sock.sendall(str)
Guido van Rossumb940e112007-01-10 16:19:56 +0000688 except socket.error as v:
Guido van Rossum89df2452007-03-19 22:26:27 +0000689 if v.args[0] == 32: # Broken pipe
Greg Steindd6eefb2000-07-18 09:09:48 +0000690 self.close()
691 raise
Greg Stein5e0fa402000-06-26 08:28:01 +0000692
Jeremy Hylton8531b1b2002-07-16 21:21:11 +0000693 def _output(self, s):
694 """Add a line of output to the current request buffer.
Tim Peters469cdad2002-08-08 20:19:19 +0000695
Jeremy Hyltone3252ec2002-07-16 21:41:43 +0000696 Assumes that the line does *not* end with \\r\\n.
Jeremy Hylton8531b1b2002-07-16 21:21:11 +0000697 """
698 self._buffer.append(s)
699
Benjamin Peterson1742e402008-11-30 22:15:29 +0000700 def _send_output(self, message_body=None):
Jeremy Hylton8531b1b2002-07-16 21:21:11 +0000701 """Send the currently buffered request and clear the buffer.
702
Jeremy Hyltone3252ec2002-07-16 21:41:43 +0000703 Appends an extra \\r\\n to the buffer.
Benjamin Peterson822b21c2009-01-18 00:04:57 +0000704 A message_body may be specified, to be appended to the request.
Jeremy Hylton8531b1b2002-07-16 21:21:11 +0000705 """
Martin v. Löwisdd5a8602007-06-30 09:22:09 +0000706 self._buffer.extend((b"", b""))
707 msg = b"\r\n".join(self._buffer)
Jeremy Hylton8531b1b2002-07-16 21:21:11 +0000708 del self._buffer[:]
Benjamin Peterson1742e402008-11-30 22:15:29 +0000709 # If msg and message_body are sent in a single send() call,
710 # it will avoid performance problems caused by the interaction
711 # between delayed ack and the Nagle algorithim.
Benjamin Peterson822b21c2009-01-18 00:04:57 +0000712 if isinstance(message_body, bytes):
Benjamin Peterson1742e402008-11-30 22:15:29 +0000713 msg += message_body
Benjamin Peterson822b21c2009-01-18 00:04:57 +0000714 message_body = None
Jeremy Hylton8531b1b2002-07-16 21:21:11 +0000715 self.send(msg)
Benjamin Peterson822b21c2009-01-18 00:04:57 +0000716 if message_body is not None:
717 #message_body was not a string (i.e. it is a file) and
718 #we must run the risk of Nagle
719 self.send(message_body)
Jeremy Hylton8531b1b2002-07-16 21:21:11 +0000720
Martin v. Löwisaf7dc8d2003-11-19 19:51:55 +0000721 def putrequest(self, method, url, skip_host=0, skip_accept_encoding=0):
Greg Steindd6eefb2000-07-18 09:09:48 +0000722 """Send a request to the server.
Greg Stein5e0fa402000-06-26 08:28:01 +0000723
Greg Steindd6eefb2000-07-18 09:09:48 +0000724 `method' specifies an HTTP request method, e.g. 'GET'.
725 `url' specifies the object being requested, e.g. '/index.html'.
Martin v. Löwisaf7dc8d2003-11-19 19:51:55 +0000726 `skip_host' if True does not add automatically a 'Host:' header
727 `skip_accept_encoding' if True does not add automatically an
728 'Accept-Encoding:' header
Greg Steindd6eefb2000-07-18 09:09:48 +0000729 """
Greg Stein5e0fa402000-06-26 08:28:01 +0000730
Greg Stein616a58d2003-06-24 06:35:19 +0000731 # if a prior response has been completed, then forget about it.
Greg Steindd6eefb2000-07-18 09:09:48 +0000732 if self.__response and self.__response.isclosed():
733 self.__response = None
Greg Stein5e0fa402000-06-26 08:28:01 +0000734
Tim Peters58eb11c2004-01-18 20:29:55 +0000735
Greg Steindd6eefb2000-07-18 09:09:48 +0000736 # in certain cases, we cannot issue another request on this connection.
737 # this occurs when:
738 # 1) we are in the process of sending a request. (_CS_REQ_STARTED)
739 # 2) a response to a previous request has signalled that it is going
740 # to close the connection upon completion.
741 # 3) the headers for the previous response have not been read, thus
742 # we cannot determine whether point (2) is true. (_CS_REQ_SENT)
743 #
744 # if there is no prior response, then we can request at will.
745 #
746 # if point (2) is true, then we will have passed the socket to the
747 # response (effectively meaning, "there is no prior response"), and
748 # will open a new one when a new request is made.
749 #
750 # Note: if a prior response exists, then we *can* start a new request.
751 # We are not allowed to begin fetching the response to this new
752 # request, however, until that prior response is complete.
753 #
754 if self.__state == _CS_IDLE:
755 self.__state = _CS_REQ_STARTED
756 else:
757 raise CannotSendRequest()
Greg Stein5e0fa402000-06-26 08:28:01 +0000758
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000759 # Save the method we use, we need it later in the response phase
760 self._method = method
Greg Steindd6eefb2000-07-18 09:09:48 +0000761 if not url:
762 url = '/'
Martin v. Löwisdd5a8602007-06-30 09:22:09 +0000763 request = '%s %s %s' % (method, url, self._http_vsn_str)
Greg Stein5e0fa402000-06-26 08:28:01 +0000764
Martin v. Löwisdd5a8602007-06-30 09:22:09 +0000765 # Non-ASCII characters should have been eliminated earlier
766 self._output(request.encode('ascii'))
Greg Stein5e0fa402000-06-26 08:28:01 +0000767
Greg Steindd6eefb2000-07-18 09:09:48 +0000768 if self._http_vsn == 11:
769 # Issue some standard headers for better HTTP/1.1 compliance
Greg Stein5e0fa402000-06-26 08:28:01 +0000770
Jeremy Hylton3921ff62002-03-09 06:07:23 +0000771 if not skip_host:
772 # this header is issued *only* for HTTP/1.1
773 # connections. more specifically, this means it is
774 # only issued when the client uses the new
775 # HTTPConnection() class. backwards-compat clients
776 # will be using HTTP/1.0 and those clients may be
777 # issuing this header themselves. we should NOT issue
778 # it twice; some web servers (such as Apache) barf
779 # when they see two Host: headers
Guido van Rossumf6922aa2001-01-14 21:03:01 +0000780
Jeremy Hylton3921ff62002-03-09 06:07:23 +0000781 # If we need a non-standard port,include it in the
782 # header. If the request is going through a proxy,
783 # but the host of the actual URL, not the host of the
784 # proxy.
Jeremy Hylton8acf1e02002-03-08 19:35:51 +0000785
Jeremy Hylton3921ff62002-03-09 06:07:23 +0000786 netloc = ''
787 if url.startswith('http'):
788 nil, netloc, nil, nil, nil = urlsplit(url)
789
790 if netloc:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000791 try:
792 netloc_enc = netloc.encode("ascii")
793 except UnicodeEncodeError:
794 netloc_enc = netloc.encode("idna")
795 self.putheader('Host', netloc_enc)
Jeremy Hylton3921ff62002-03-09 06:07:23 +0000796 else:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000797 try:
798 host_enc = self.host.encode("ascii")
799 except UnicodeEncodeError:
800 host_enc = self.host.encode("idna")
Georg Brandl86b2fb92008-07-16 03:43:04 +0000801 if self.port == self.default_port:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000802 self.putheader('Host', host_enc)
803 else:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000804 host_enc = host_enc.decode("ascii")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000805 self.putheader('Host', "%s:%s" % (host_enc, self.port))
Greg Stein5e0fa402000-06-26 08:28:01 +0000806
Greg Steindd6eefb2000-07-18 09:09:48 +0000807 # note: we are assuming that clients will not attempt to set these
808 # headers since *this* library must deal with the
809 # consequences. this also means that when the supporting
810 # libraries are updated to recognize other forms, then this
811 # code should be changed (removed or updated).
Greg Stein5e0fa402000-06-26 08:28:01 +0000812
Greg Steindd6eefb2000-07-18 09:09:48 +0000813 # we only want a Content-Encoding of "identity" since we don't
814 # support encodings such as x-gzip or x-deflate.
Martin v. Löwisaf7dc8d2003-11-19 19:51:55 +0000815 if not skip_accept_encoding:
816 self.putheader('Accept-Encoding', 'identity')
Greg Stein5e0fa402000-06-26 08:28:01 +0000817
Greg Steindd6eefb2000-07-18 09:09:48 +0000818 # we can accept "chunked" Transfer-Encodings, but no others
819 # NOTE: no TE header implies *only* "chunked"
820 #self.putheader('TE', 'chunked')
Greg Stein5e0fa402000-06-26 08:28:01 +0000821
Greg Steindd6eefb2000-07-18 09:09:48 +0000822 # if TE is supplied in the header, then it must appear in a
823 # Connection header.
824 #self.putheader('Connection', 'TE')
Greg Stein5e0fa402000-06-26 08:28:01 +0000825
Greg Steindd6eefb2000-07-18 09:09:48 +0000826 else:
827 # For HTTP/1.0, the server will assume "not chunked"
828 pass
Greg Stein5e0fa402000-06-26 08:28:01 +0000829
Benjamin Petersonf608c612008-11-16 18:33:53 +0000830 def putheader(self, header, *values):
Greg Steindd6eefb2000-07-18 09:09:48 +0000831 """Send a request header line to the server.
Greg Stein5e0fa402000-06-26 08:28:01 +0000832
Greg Steindd6eefb2000-07-18 09:09:48 +0000833 For example: h.putheader('Accept', 'text/html')
834 """
835 if self.__state != _CS_REQ_STARTED:
836 raise CannotSendHeader()
Greg Stein5e0fa402000-06-26 08:28:01 +0000837
Guido van Rossum98297ee2007-11-06 21:34:58 +0000838 if hasattr(header, 'encode'):
839 header = header.encode('ascii')
Benjamin Petersonf608c612008-11-16 18:33:53 +0000840 values = list(values)
841 for i, one_value in enumerate(values):
842 if hasattr(one_value, 'encode'):
843 values[i] = one_value.encode('ascii')
844 value = b'\r\n\t'.join(values)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000845 header = header + b': ' + value
846 self._output(header)
Greg Stein5e0fa402000-06-26 08:28:01 +0000847
Benjamin Peterson1742e402008-11-30 22:15:29 +0000848 def endheaders(self, message_body=None):
849 """Indicate that the last header line has been sent to the server.
Greg Stein5e0fa402000-06-26 08:28:01 +0000850
Benjamin Peterson1742e402008-11-30 22:15:29 +0000851 This method sends the request to the server. The optional
852 message_body argument can be used to pass message body
853 associated with the request. The message body will be sent in
854 the same packet as the message headers if possible. The
855 message_body should be a string.
856 """
Greg Steindd6eefb2000-07-18 09:09:48 +0000857 if self.__state == _CS_REQ_STARTED:
858 self.__state = _CS_REQ_SENT
859 else:
860 raise CannotSendHeader()
Benjamin Peterson1742e402008-11-30 22:15:29 +0000861 self._send_output(message_body)
Greg Stein5e0fa402000-06-26 08:28:01 +0000862
Greg Steindd6eefb2000-07-18 09:09:48 +0000863 def request(self, method, url, body=None, headers={}):
864 """Send a complete request to the server."""
Greg Steindd6eefb2000-07-18 09:09:48 +0000865 try:
866 self._send_request(method, url, body, headers)
Guido van Rossumb940e112007-01-10 16:19:56 +0000867 except socket.error as v:
Greg Steindd6eefb2000-07-18 09:09:48 +0000868 # trap 'Broken pipe' if we're allowed to automatically reconnect
Guido van Rossum89df2452007-03-19 22:26:27 +0000869 if v.args[0] != 32 or not self.auto_open:
Greg Steindd6eefb2000-07-18 09:09:48 +0000870 raise
871 # try one more time
872 self._send_request(method, url, body, headers)
Greg Stein5e0fa402000-06-26 08:28:01 +0000873
Benjamin Peterson1742e402008-11-30 22:15:29 +0000874 def _set_content_length(self, body):
875 # Set the content-length based on the body.
876 thelen = None
877 try:
878 thelen = str(len(body))
879 except TypeError as te:
880 # If this is a file-like object, try to
881 # fstat its file descriptor
882 import os
883 try:
884 thelen = str(os.fstat(body.fileno()).st_size)
885 except (AttributeError, OSError):
886 # Don't send a length if this failed
887 if self.debuglevel > 0: print("Cannot stat!!")
888
889 if thelen is not None:
890 self.putheader('Content-Length', thelen)
891
Greg Steindd6eefb2000-07-18 09:09:48 +0000892 def _send_request(self, method, url, body, headers):
Jeremy Hylton2c178252004-08-07 16:28:14 +0000893 # honour explicitly requested Host: and Accept-Encoding headers
894 header_names = dict.fromkeys([k.lower() for k in headers])
895 skips = {}
896 if 'host' in header_names:
897 skips['skip_host'] = 1
898 if 'accept-encoding' in header_names:
899 skips['skip_accept_encoding'] = 1
Greg Stein5e0fa402000-06-26 08:28:01 +0000900
Jeremy Hylton2c178252004-08-07 16:28:14 +0000901 self.putrequest(method, url, **skips)
902
903 if body and ('content-length' not in header_names):
Benjamin Peterson1742e402008-11-30 22:15:29 +0000904 self._set_content_length(body)
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000905 for hdr, value in headers.items():
Greg Steindd6eefb2000-07-18 09:09:48 +0000906 self.putheader(hdr, value)
Jeremy Hyltonef9f48e2009-03-26 22:04:05 +0000907 if isinstance(body, str):
908 body = body.encode('ascii')
909 self.endheaders(body)
Greg Stein5e0fa402000-06-26 08:28:01 +0000910
Greg Steindd6eefb2000-07-18 09:09:48 +0000911 def getresponse(self):
Jeremy Hyltonfb35f652007-08-03 20:30:33 +0000912 """Get the response from the server."""
Greg Stein5e0fa402000-06-26 08:28:01 +0000913
Greg Stein616a58d2003-06-24 06:35:19 +0000914 # if a prior response has been completed, then forget about it.
Greg Steindd6eefb2000-07-18 09:09:48 +0000915 if self.__response and self.__response.isclosed():
916 self.__response = None
Greg Stein5e0fa402000-06-26 08:28:01 +0000917
Greg Steindd6eefb2000-07-18 09:09:48 +0000918 #
919 # if a prior response exists, then it must be completed (otherwise, we
920 # cannot read this response's header to determine the connection-close
921 # behavior)
922 #
923 # note: if a prior response existed, but was connection-close, then the
924 # socket and response were made independent of this HTTPConnection
925 # object since a new request requires that we open a whole new
926 # connection
927 #
928 # this means the prior response had one of two states:
929 # 1) will_close: this connection was reset and the prior socket and
930 # response operate independently
931 # 2) persistent: the response was retained and we await its
932 # isclosed() status to become true.
933 #
934 if self.__state != _CS_REQ_SENT or self.__response:
935 raise ResponseNotReady()
Greg Stein5e0fa402000-06-26 08:28:01 +0000936
Jeremy Hylton30f86742000-09-18 22:50:38 +0000937 if self.debuglevel > 0:
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000938 response = self.response_class(self.sock, self.debuglevel,
Tim Petersc2659cf2003-05-12 20:19:37 +0000939 strict=self.strict,
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000940 method=self._method)
Jeremy Hylton30f86742000-09-18 22:50:38 +0000941 else:
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000942 response = self.response_class(self.sock, strict=self.strict,
943 method=self._method)
Greg Stein5e0fa402000-06-26 08:28:01 +0000944
Jeremy Hylton39c03802002-07-12 14:04:09 +0000945 response.begin()
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000946 assert response.will_close != _UNKNOWN
Greg Steindd6eefb2000-07-18 09:09:48 +0000947 self.__state = _CS_IDLE
Greg Stein5e0fa402000-06-26 08:28:01 +0000948
Greg Steindd6eefb2000-07-18 09:09:48 +0000949 if response.will_close:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000950 # this effectively passes the connection to the response
951 self.close()
Greg Steindd6eefb2000-07-18 09:09:48 +0000952 else:
953 # remember this, so we can tell when it is complete
954 self.__response = response
Greg Stein5e0fa402000-06-26 08:28:01 +0000955
Greg Steindd6eefb2000-07-18 09:09:48 +0000956 return response
Greg Stein5e0fa402000-06-26 08:28:01 +0000957
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000958try:
959 import ssl
960except ImportError:
961 pass
962else:
963 class HTTPSConnection(HTTPConnection):
964 "This class allows communication via SSL."
Jeremy Hylton29d27ac2002-07-09 21:22:36 +0000965
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000966 default_port = HTTPS_PORT
Jeremy Hylton29d27ac2002-07-09 21:22:36 +0000967
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000968 def __init__(self, host, port=None, key_file=None, cert_file=None,
Georg Brandlf78e02b2008-06-10 17:40:04 +0000969 strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000970 HTTPConnection.__init__(self, host, port, strict, timeout)
971 self.key_file = key_file
972 self.cert_file = cert_file
Jeremy Hylton29d27ac2002-07-09 21:22:36 +0000973
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000974 def connect(self):
975 "Connect to a host on a given (SSL) port."
Jeremy Hylton29d27ac2002-07-09 21:22:36 +0000976
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000977 sock = socket.create_connection((self.host, self.port), self.timeout)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000978 self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file)
Jeremy Hylton29d27ac2002-07-09 21:22:36 +0000979
Jeremy Hylton29d27ac2002-07-09 21:22:36 +0000980
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000981 def FakeSocket (sock, sslobj):
Thomas Wouters89d996e2007-09-08 17:39:28 +0000982 warnings.warn("FakeSocket is deprecated, and won't be in 3.x. " +
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000983 "Use the result of ssl.wrap_socket() directly instead.",
Thomas Wouters89d996e2007-09-08 17:39:28 +0000984 DeprecationWarning, stacklevel=2)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000985 return sslobj
Jeremy Hylton29d27ac2002-07-09 21:22:36 +0000986
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000987 __all__.append("HTTPSConnection")
Greg Stein5e0fa402000-06-26 08:28:01 +0000988
Greg Stein5e0fa402000-06-26 08:28:01 +0000989class HTTPException(Exception):
Jeremy Hylton12f4f352002-07-06 18:55:01 +0000990 # Subclasses that define an __init__ must call Exception.__init__
991 # or define self.args. Otherwise, str() will fail.
Greg Steindd6eefb2000-07-18 09:09:48 +0000992 pass
Greg Stein5e0fa402000-06-26 08:28:01 +0000993
994class NotConnected(HTTPException):
Greg Steindd6eefb2000-07-18 09:09:48 +0000995 pass
Greg Stein5e0fa402000-06-26 08:28:01 +0000996
Skip Montanaro9d389972002-03-24 16:53:50 +0000997class InvalidURL(HTTPException):
998 pass
999
Greg Stein5e0fa402000-06-26 08:28:01 +00001000class UnknownProtocol(HTTPException):
Greg Steindd6eefb2000-07-18 09:09:48 +00001001 def __init__(self, version):
Jeremy Hylton12f4f352002-07-06 18:55:01 +00001002 self.args = version,
Greg Steindd6eefb2000-07-18 09:09:48 +00001003 self.version = version
Greg Stein5e0fa402000-06-26 08:28:01 +00001004
1005class UnknownTransferEncoding(HTTPException):
Greg Steindd6eefb2000-07-18 09:09:48 +00001006 pass
Greg Stein5e0fa402000-06-26 08:28:01 +00001007
Greg Stein5e0fa402000-06-26 08:28:01 +00001008class UnimplementedFileMode(HTTPException):
Greg Steindd6eefb2000-07-18 09:09:48 +00001009 pass
Greg Stein5e0fa402000-06-26 08:28:01 +00001010
1011class IncompleteRead(HTTPException):
Benjamin Peterson6accb982009-03-02 22:50:25 +00001012 def __init__(self, partial, expected=None):
Jeremy Hylton12f4f352002-07-06 18:55:01 +00001013 self.args = partial,
Greg Steindd6eefb2000-07-18 09:09:48 +00001014 self.partial = partial
Benjamin Peterson6accb982009-03-02 22:50:25 +00001015 self.expected = expected
1016 def __repr__(self):
1017 if self.expected is not None:
1018 e = ', %i more expected' % self.expected
1019 else:
1020 e = ''
1021 return 'IncompleteRead(%i bytes read%s)' % (len(self.partial), e)
1022 def __str__(self):
1023 return repr(self)
Greg Stein5e0fa402000-06-26 08:28:01 +00001024
1025class ImproperConnectionState(HTTPException):
Greg Steindd6eefb2000-07-18 09:09:48 +00001026 pass
Greg Stein5e0fa402000-06-26 08:28:01 +00001027
1028class CannotSendRequest(ImproperConnectionState):
Greg Steindd6eefb2000-07-18 09:09:48 +00001029 pass
Greg Stein5e0fa402000-06-26 08:28:01 +00001030
1031class CannotSendHeader(ImproperConnectionState):
Greg Steindd6eefb2000-07-18 09:09:48 +00001032 pass
Greg Stein5e0fa402000-06-26 08:28:01 +00001033
1034class ResponseNotReady(ImproperConnectionState):
Greg Steindd6eefb2000-07-18 09:09:48 +00001035 pass
Greg Stein5e0fa402000-06-26 08:28:01 +00001036
1037class BadStatusLine(HTTPException):
Greg Steindd6eefb2000-07-18 09:09:48 +00001038 def __init__(self, line):
Jeremy Hylton12f4f352002-07-06 18:55:01 +00001039 self.args = line,
Greg Steindd6eefb2000-07-18 09:09:48 +00001040 self.line = line
Greg Stein5e0fa402000-06-26 08:28:01 +00001041
1042# for backwards compatibility
1043error = HTTPException
1044
Jeremy Hyltond46aa372002-07-06 18:48:07 +00001045class LineAndFileWrapper:
1046 """A limited file-like object for HTTP/0.9 responses."""
1047
1048 # The status-line parsing code calls readline(), which normally
1049 # get the HTTP status line. For a 0.9 response, however, this is
1050 # actually the first line of the body! Clients need to get a
1051 # readable file object that contains that line.
1052
1053 def __init__(self, line, file):
1054 self._line = line
1055 self._file = file
1056 self._line_consumed = 0
1057 self._line_offset = 0
1058 self._line_left = len(line)
1059
1060 def __getattr__(self, attr):
1061 return getattr(self._file, attr)
1062
1063 def _done(self):
1064 # called when the last byte is read from the line. After the
1065 # call, all read methods are delegated to the underlying file
Skip Montanaro74b9a7a2003-02-25 17:48:15 +00001066 # object.
Jeremy Hyltond46aa372002-07-06 18:48:07 +00001067 self._line_consumed = 1
1068 self.read = self._file.read
1069 self.readline = self._file.readline
1070 self.readlines = self._file.readlines
1071
1072 def read(self, amt=None):
Hye-Shik Chang39aef792004-06-05 13:30:56 +00001073 if self._line_consumed:
1074 return self._file.read(amt)
1075 assert self._line_left
Jeremy Hyltond46aa372002-07-06 18:48:07 +00001076 if amt is None or amt > self._line_left:
1077 s = self._line[self._line_offset:]
1078 self._done()
1079 if amt is None:
1080 return s + self._file.read()
1081 else:
Tim Petersc411dba2002-07-16 21:35:23 +00001082 return s + self._file.read(amt - len(s))
Jeremy Hyltond46aa372002-07-06 18:48:07 +00001083 else:
1084 assert amt <= self._line_left
1085 i = self._line_offset
1086 j = i + amt
1087 s = self._line[i:j]
1088 self._line_offset = j
1089 self._line_left -= amt
1090 if self._line_left == 0:
1091 self._done()
1092 return s
Tim Petersc411dba2002-07-16 21:35:23 +00001093
Jeremy Hyltond46aa372002-07-06 18:48:07 +00001094 def readline(self):
Hye-Shik Chang39aef792004-06-05 13:30:56 +00001095 if self._line_consumed:
1096 return self._file.readline()
1097 assert self._line_left
Jeremy Hyltond46aa372002-07-06 18:48:07 +00001098 s = self._line[self._line_offset:]
1099 self._done()
1100 return s
1101
1102 def readlines(self, size=None):
Hye-Shik Chang39aef792004-06-05 13:30:56 +00001103 if self._line_consumed:
1104 return self._file.readlines(size)
1105 assert self._line_left
Jeremy Hyltond46aa372002-07-06 18:48:07 +00001106 L = [self._line[self._line_offset:]]
1107 self._done()
1108 if size is None:
1109 return L + self._file.readlines()
1110 else:
1111 return L + self._file.readlines(size)