blob: 05ddf12be6c32cd4a8b2f106d45fb2ed7e39cce2 [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 Hylton6459c8d2001-10-11 17:47:22 +000069import errno
Jeremy Hyltonfb35f652007-08-03 20:30:33 +000070import io
Guido van Rossum65ab98c1995-08-07 20:13:02 +000071import mimetools
Jeremy Hylton6459c8d2001-10-11 17:47:22 +000072import socket
Jeremy Hylton8acf1e02002-03-08 19:35:51 +000073from urlparse 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
Jeremy Hylton6d0a4c72002-07-07 16:51:37 +0000205class HTTPMessage(mimetools.Message):
206
207 def addheader(self, key, value):
208 """Add header for field key handling repeats."""
209 prev = self.dict.get(key)
210 if prev is None:
211 self.dict[key] = value
212 else:
213 combined = ", ".join((prev, value))
214 self.dict[key] = combined
215
216 def addcontinue(self, key, more):
217 """Add more field data from a continuation line."""
218 prev = self.dict[key]
219 self.dict[key] = prev + "\n " + more
220
221 def readheaders(self):
222 """Read header lines.
223
224 Read header lines up to the entirely blank line that terminates them.
225 The (normally blank) line that ends the headers is skipped, but not
226 included in the returned list. If a non-header line ends the headers,
227 (which is an error), an attempt is made to backspace over it; it is
228 never included in the returned list.
229
230 The variable self.status is set to the empty string if all went well,
231 otherwise it is an error message. The variable self.headers is a
232 completely uninterpreted list of lines contained in the header (so
233 printing them will reproduce the header exactly as it appears in the
234 file).
235
236 If multiple header fields with the same name occur, they are combined
237 according to the rules in RFC 2616 sec 4.2:
238
239 Appending each subsequent field-value to the first, each separated
240 by a comma. The order in which header fields with the same field-name
241 are received is significant to the interpretation of the combined
242 field value.
243 """
244 # XXX The implementation overrides the readheaders() method of
245 # rfc822.Message. The base class design isn't amenable to
246 # customized behavior here so the method here is a copy of the
247 # base class code with a few small changes.
248
249 self.dict = {}
250 self.unixfrom = ''
Raymond Hettingerb2e0b922003-02-26 22:45:18 +0000251 self.headers = hlist = []
Jeremy Hylton6d0a4c72002-07-07 16:51:37 +0000252 self.status = ''
253 headerseen = ""
254 firstline = 1
255 startofline = unread = tell = None
256 if hasattr(self.fp, 'unread'):
257 unread = self.fp.unread
258 elif self.seekable:
259 tell = self.fp.tell
Raymond Hettingerb2e0b922003-02-26 22:45:18 +0000260 while True:
Jeremy Hylton6d0a4c72002-07-07 16:51:37 +0000261 if tell:
262 try:
263 startofline = tell()
264 except IOError:
265 startofline = tell = None
266 self.seekable = 0
Jeremy Hylton811fc142007-08-03 13:30:02 +0000267 line = str(self.fp.readline(), "iso-8859-1")
Jeremy Hylton6d0a4c72002-07-07 16:51:37 +0000268 if not line:
269 self.status = 'EOF in headers'
270 break
271 # Skip unix From name time lines
272 if firstline and line.startswith('From '):
273 self.unixfrom = self.unixfrom + line
274 continue
275 firstline = 0
276 if headerseen and line[0] in ' \t':
277 # XXX Not sure if continuation lines are handled properly
278 # for http and/or for repeating headers
279 # It's a continuation line.
Raymond Hettingerb2e0b922003-02-26 22:45:18 +0000280 hlist.append(line)
Jeremy Hylton6d0a4c72002-07-07 16:51:37 +0000281 self.addcontinue(headerseen, line.strip())
282 continue
283 elif self.iscomment(line):
284 # It's a comment. Ignore it.
285 continue
286 elif self.islast(line):
287 # Note! No pushback here! The delimiter line gets eaten.
288 break
289 headerseen = self.isheader(line)
290 if headerseen:
291 # It's a legal header line, save it.
Raymond Hettingerb2e0b922003-02-26 22:45:18 +0000292 hlist.append(line)
Jeremy Hylton6d0a4c72002-07-07 16:51:37 +0000293 self.addheader(headerseen, line[len(headerseen)+1:].strip())
294 continue
295 else:
296 # It's not a header line; throw it back and stop here.
297 if not self.dict:
298 self.status = 'No headers'
299 else:
300 self.status = 'Non-header line where header expected'
301 # Try to undo the read.
302 if unread:
303 unread(line)
304 elif tell:
305 self.fp.seek(startofline)
306 else:
307 self.status = self.status + '; bad seek'
308 break
Greg Stein5e0fa402000-06-26 08:28:01 +0000309
Jeremy Hylton97043c32007-08-04 02:34:24 +0000310class HTTPResponse:
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000311
312 # strict: If true, raise BadStatusLine if the status line can't be
313 # parsed as a valid HTTP/1.0 or 1.1 status line. By default it is
Skip Montanaro186bec22002-07-25 16:10:38 +0000314 # false because it prevents clients from talking to HTTP/0.9
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000315 # servers. Note that a response with a sufficiently corrupted
316 # status line will look like an HTTP/0.9 response.
317
318 # See RFC 2616 sec 19.6 and RFC 1945 sec 6 for details.
319
Jeremy Hylton811fc142007-08-03 13:30:02 +0000320 # The bytes from the socket object are iso-8859-1 strings.
321 # See RFC 2616 sec 2.2 which notes an exception for MIME-encoded
322 # text following RFC 2047. The basic status line parsing only
323 # accepts iso-8859-1.
324
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000325 def __init__(self, sock, debuglevel=0, strict=0, method=None):
Jeremy Hylton39b198d2007-08-04 19:22:00 +0000326 # XXX If the response includes a content-length header, we
327 # need to make sure that the client doesn't read more than the
328 # specified number of bytes. If it does, it will block until
329 # the server times out and closes the connection. (The only
330 # applies to HTTP/1.1 connections.) Since some clients access
331 # self.fp directly rather than calling read(), this is a little
332 # tricky.
Jeremy Hyltone5d0e842007-08-03 13:45:24 +0000333 self.fp = sock.makefile("rb", 0)
Jeremy Hylton30f86742000-09-18 22:50:38 +0000334 self.debuglevel = debuglevel
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000335 self.strict = strict
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000336 self._method = method
Greg Stein5e0fa402000-06-26 08:28:01 +0000337
Greg Steindd6eefb2000-07-18 09:09:48 +0000338 self.msg = None
Greg Stein5e0fa402000-06-26 08:28:01 +0000339
Greg Steindd6eefb2000-07-18 09:09:48 +0000340 # from the Status-Line of the response
Tim Peters07e99cb2001-01-14 23:47:14 +0000341 self.version = _UNKNOWN # HTTP-Version
342 self.status = _UNKNOWN # Status-Code
343 self.reason = _UNKNOWN # Reason-Phrase
Greg Stein5e0fa402000-06-26 08:28:01 +0000344
Tim Peters07e99cb2001-01-14 23:47:14 +0000345 self.chunked = _UNKNOWN # is "chunked" being used?
346 self.chunk_left = _UNKNOWN # bytes left to read in current chunk
347 self.length = _UNKNOWN # number of bytes left in response
348 self.will_close = _UNKNOWN # conn will close at end of response
Greg Stein5e0fa402000-06-26 08:28:01 +0000349
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000350 def _read_status(self):
Jeremy Hylton04319c72007-08-04 03:41:19 +0000351 # Initialize with Simple-Response defaults.
Jeremy Hylton811fc142007-08-03 13:30:02 +0000352 line = str(self.fp.readline(), "iso-8859-1")
Jeremy Hylton30f86742000-09-18 22:50:38 +0000353 if self.debuglevel > 0:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000354 print("reply:", repr(line))
Jeremy Hyltonb6769522003-06-29 17:55:05 +0000355 if not line:
356 # Presumably, the server closed the connection before
357 # sending a valid response.
358 raise BadStatusLine(line)
Greg Steindd6eefb2000-07-18 09:09:48 +0000359 try:
Guido van Rossum34735a62000-12-15 15:09:42 +0000360 [version, status, reason] = line.split(None, 2)
Greg Steindd6eefb2000-07-18 09:09:48 +0000361 except ValueError:
362 try:
Guido van Rossum34735a62000-12-15 15:09:42 +0000363 [version, status] = line.split(None, 1)
Greg Steindd6eefb2000-07-18 09:09:48 +0000364 reason = ""
365 except ValueError:
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000366 # empty version will cause next test to fail and status
367 # will be treated as 0.9 response.
368 version = ""
Jeremy Hyltone5d0e842007-08-03 13:45:24 +0000369 if not version.startswith("HTTP/"):
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000370 if self.strict:
371 self.close()
372 raise BadStatusLine(line)
373 else:
Jeremy Hylton04319c72007-08-04 03:41:19 +0000374 # Assume it's a Simple-Response from an 0.9 server.
375 # We have to convert the first line back to raw bytes
376 # because self.fp.readline() needs to return bytes.
Guido van Rossum70d0dda2007-08-29 01:53:26 +0000377 self.fp = LineAndFileWrapper(bytes(line, "ascii"), self.fp)
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000378 return "HTTP/0.9", 200, ""
Greg Stein5e0fa402000-06-26 08:28:01 +0000379
Jeremy Hylton23d40472001-04-13 14:57:08 +0000380 # The status code is a three-digit number
381 try:
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000382 status = int(status)
Jeremy Hylton23d40472001-04-13 14:57:08 +0000383 if status < 100 or status > 999:
384 raise BadStatusLine(line)
385 except ValueError:
386 raise BadStatusLine(line)
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000387 return version, status, reason
Greg Stein5e0fa402000-06-26 08:28:01 +0000388
Jeremy Hylton39c03802002-07-12 14:04:09 +0000389 def begin(self):
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000390 if self.msg is not None:
391 # we've already started reading the response
392 return
393
394 # read until we get a non-100 response
Raymond Hettingerb2e0b922003-02-26 22:45:18 +0000395 while True:
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000396 version, status, reason = self._read_status()
Martin v. Löwis39a31782004-09-18 09:03:49 +0000397 if status != CONTINUE:
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000398 break
399 # skip the header from the 100 response
Raymond Hettingerb2e0b922003-02-26 22:45:18 +0000400 while True:
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000401 skip = self.fp.readline().strip()
402 if not skip:
403 break
404 if self.debuglevel > 0:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000405 print("header:", skip)
Tim Petersc411dba2002-07-16 21:35:23 +0000406
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000407 self.status = status
408 self.reason = reason.strip()
Jeremy Hyltone5d0e842007-08-03 13:45:24 +0000409 if version == "HTTP/1.0":
Greg Steindd6eefb2000-07-18 09:09:48 +0000410 self.version = 10
Jeremy Hyltone5d0e842007-08-03 13:45:24 +0000411 elif version.startswith("HTTP/1."):
Tim Peters07e99cb2001-01-14 23:47:14 +0000412 self.version = 11 # use HTTP/1.1 code for HTTP/1.x where x>=1
Jeremy Hyltone5d0e842007-08-03 13:45:24 +0000413 elif version == "HTTP/0.9":
Jeremy Hylton110941a2000-10-12 19:58:36 +0000414 self.version = 9
Greg Steindd6eefb2000-07-18 09:09:48 +0000415 else:
416 raise UnknownProtocol(version)
Greg Stein5e0fa402000-06-26 08:28:01 +0000417
Jeremy Hylton110941a2000-10-12 19:58:36 +0000418 if self.version == 9:
Georg Brandl0aade9a2005-06-26 22:06:54 +0000419 self.length = None
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000420 self.chunked = 0
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000421 self.will_close = 1
Jeremy Hylton4e7855d2007-08-04 03:34:03 +0000422 self.msg = HTTPMessage(io.BytesIO())
Jeremy Hylton110941a2000-10-12 19:58:36 +0000423 return
424
Jeremy Hylton6d0a4c72002-07-07 16:51:37 +0000425 self.msg = HTTPMessage(self.fp, 0)
Jeremy Hylton30f86742000-09-18 22:50:38 +0000426 if self.debuglevel > 0:
427 for hdr in self.msg.headers:
Jeremy Hyltone5d0e842007-08-03 13:45:24 +0000428 print("header:", hdr, end=" ")
Greg Stein5e0fa402000-06-26 08:28:01 +0000429
Greg Steindd6eefb2000-07-18 09:09:48 +0000430 # don't let the msg keep an fp
431 self.msg.fp = None
Greg Stein5e0fa402000-06-26 08:28:01 +0000432
Greg Steindd6eefb2000-07-18 09:09:48 +0000433 # are we using the chunked-style of transfer encoding?
Jeremy Hyltone5d0e842007-08-03 13:45:24 +0000434 tr_enc = self.msg.getheader("transfer-encoding")
Jeremy Hyltond229b3a2002-09-03 19:24:24 +0000435 if tr_enc and tr_enc.lower() == "chunked":
Greg Steindd6eefb2000-07-18 09:09:48 +0000436 self.chunked = 1
437 self.chunk_left = None
438 else:
439 self.chunked = 0
Greg Stein5e0fa402000-06-26 08:28:01 +0000440
Greg Steindd6eefb2000-07-18 09:09:48 +0000441 # will the connection close at the end of the response?
Jeremy Hylton22b3a492002-11-13 17:27:43 +0000442 self.will_close = self._check_close()
Greg Stein5e0fa402000-06-26 08:28:01 +0000443
Greg Steindd6eefb2000-07-18 09:09:48 +0000444 # do we have a Content-Length?
445 # NOTE: RFC 2616, S4.4, #3 says we ignore this if tr_enc is "chunked"
Jeremy Hylton0ee5eeb2007-08-04 03:25:17 +0000446 self.length = None
Jeremy Hyltone5d0e842007-08-03 13:45:24 +0000447 length = self.msg.getheader("content-length")
Greg Steindd6eefb2000-07-18 09:09:48 +0000448 if length and not self.chunked:
Jeremy Hylton30a81812000-09-14 20:34:27 +0000449 try:
450 self.length = int(length)
451 except ValueError:
Jeremy Hylton0ee5eeb2007-08-04 03:25:17 +0000452 pass
Greg Stein5e0fa402000-06-26 08:28:01 +0000453
Greg Steindd6eefb2000-07-18 09:09:48 +0000454 # does the body have a fixed length? (of zero)
Martin v. Löwis39a31782004-09-18 09:03:49 +0000455 if (status == NO_CONTENT or status == NOT_MODIFIED or
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000456 100 <= status < 200 or # 1xx codes
Jeremy Hyltone5d0e842007-08-03 13:45:24 +0000457 self._method == "HEAD"):
Greg Steindd6eefb2000-07-18 09:09:48 +0000458 self.length = 0
Greg Stein5e0fa402000-06-26 08:28:01 +0000459
Greg Steindd6eefb2000-07-18 09:09:48 +0000460 # if the connection remains open, and we aren't using chunked, and
461 # a content-length was not provided, then assume that the connection
462 # WILL close.
Jeremy Hylton0ee5eeb2007-08-04 03:25:17 +0000463 if (not self.will_close and
464 not self.chunked and
465 self.length is None):
Greg Steindd6eefb2000-07-18 09:09:48 +0000466 self.will_close = 1
Greg Stein5e0fa402000-06-26 08:28:01 +0000467
Jeremy Hylton22b3a492002-11-13 17:27:43 +0000468 def _check_close(self):
Jeremy Hyltone5d0e842007-08-03 13:45:24 +0000469 conn = self.msg.getheader("connection")
Jeremy Hylton22b3a492002-11-13 17:27:43 +0000470 if self.version == 11:
471 # An HTTP/1.1 proxy is assumed to stay open unless
472 # explicitly closed.
Jeremy Hyltone5d0e842007-08-03 13:45:24 +0000473 conn = self.msg.getheader("connection")
Raymond Hettingerbac788a2004-05-04 09:21:43 +0000474 if conn and "close" in conn.lower():
Jeremy Hylton22b3a492002-11-13 17:27:43 +0000475 return True
476 return False
477
Jeremy Hylton2c178252004-08-07 16:28:14 +0000478 # Some HTTP/1.0 implementations have support for persistent
479 # connections, using rules different than HTTP/1.1.
Jeremy Hylton22b3a492002-11-13 17:27:43 +0000480
481 # For older HTTP, Keep-Alive indiciates persistent connection.
Jeremy Hyltone5d0e842007-08-03 13:45:24 +0000482 if self.msg.getheader("keep-alive"):
Jeremy Hylton22b3a492002-11-13 17:27:43 +0000483 return False
Tim Peters77c06fb2002-11-24 02:35:35 +0000484
Jeremy Hylton2c178252004-08-07 16:28:14 +0000485 # At least Akamai returns a "Connection: Keep-Alive" header,
486 # which was supposed to be sent by the client.
487 if conn and "keep-alive" in conn.lower():
488 return False
489
Jeremy Hylton22b3a492002-11-13 17:27:43 +0000490 # Proxy-Connection is a netscape hack.
Jeremy Hyltone5d0e842007-08-03 13:45:24 +0000491 pconn = self.msg.getheader("proxy-connection")
Raymond Hettingerbac788a2004-05-04 09:21:43 +0000492 if pconn and "keep-alive" in pconn.lower():
Jeremy Hylton22b3a492002-11-13 17:27:43 +0000493 return False
494
495 # otherwise, assume it will close
496 return True
497
Greg Steindd6eefb2000-07-18 09:09:48 +0000498 def close(self):
499 if self.fp:
500 self.fp.close()
501 self.fp = None
Greg Stein5e0fa402000-06-26 08:28:01 +0000502
Jeremy Hyltondf5f6b52007-08-08 17:36:33 +0000503 # These implementations are for the benefit of io.BufferedReader.
504
505 # XXX This class should probably be revised to act more like
506 # the "raw stream" that BufferedReader expects.
507
508 @property
509 def closed(self):
510 return self.isclosed()
511
512 def flush(self):
513 self.fp.flush()
514
515 # End of "raw stream" methods
516
Greg Steindd6eefb2000-07-18 09:09:48 +0000517 def isclosed(self):
518 # NOTE: it is possible that we will not ever call self.close(). This
519 # case occurs when will_close is TRUE, length is None, and we
520 # read up to the last byte, but NOT past it.
521 #
522 # IMPLIES: if will_close is FALSE, then self.close() will ALWAYS be
523 # called, meaning self.isclosed() is meaningful.
524 return self.fp is None
525
Jeremy Hylton2c178252004-08-07 16:28:14 +0000526 # XXX It would be nice to have readline and __iter__ for this, too.
527
Greg Steindd6eefb2000-07-18 09:09:48 +0000528 def read(self, amt=None):
529 if self.fp is None:
Jeremy Hyltone5d0e842007-08-03 13:45:24 +0000530 return ""
Greg Steindd6eefb2000-07-18 09:09:48 +0000531
532 if self.chunked:
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000533 return self._read_chunked(amt)
Tim Peters230a60c2002-11-09 05:08:07 +0000534
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000535 if amt is None:
Greg Steindd6eefb2000-07-18 09:09:48 +0000536 # unbounded read
Jeremy Hyltondef9d2a2004-11-07 16:13:49 +0000537 if self.length is None:
Greg Steindd6eefb2000-07-18 09:09:48 +0000538 s = self.fp.read()
539 else:
540 s = self._safe_read(self.length)
Jeremy Hyltondef9d2a2004-11-07 16:13:49 +0000541 self.length = 0
Tim Peters07e99cb2001-01-14 23:47:14 +0000542 self.close() # we read everything
Greg Steindd6eefb2000-07-18 09:09:48 +0000543 return s
544
545 if self.length is not None:
546 if amt > self.length:
547 # clip the read to the "end of response"
548 amt = self.length
Greg Steindd6eefb2000-07-18 09:09:48 +0000549
550 # we do not use _safe_read() here because this may be a .will_close
551 # connection, and the user is reading more bytes than will be provided
552 # (for example, reading in 1k chunks)
553 s = self.fp.read(amt)
Jeremy Hyltondef9d2a2004-11-07 16:13:49 +0000554 if self.length is not None:
555 self.length -= len(s)
Greg Steindd6eefb2000-07-18 09:09:48 +0000556
Greg Steindd6eefb2000-07-18 09:09:48 +0000557 return s
558
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000559 def _read_chunked(self, amt):
560 assert self.chunked != _UNKNOWN
561 chunk_left = self.chunk_left
Jeremy Hyltone5d0e842007-08-03 13:45:24 +0000562 value = ""
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000563
564 # XXX This accumulates chunks by repeated string concatenation,
565 # which is not efficient as the number or size of chunks gets big.
Raymond Hettingerb2e0b922003-02-26 22:45:18 +0000566 while True:
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000567 if chunk_left is None:
568 line = self.fp.readline()
Jeremy Hyltone5d0e842007-08-03 13:45:24 +0000569 i = line.find(";")
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000570 if i >= 0:
571 line = line[:i] # strip chunk-extensions
572 chunk_left = int(line, 16)
573 if chunk_left == 0:
574 break
575 if amt is None:
576 value += self._safe_read(chunk_left)
577 elif amt < chunk_left:
578 value += self._safe_read(amt)
579 self.chunk_left = chunk_left - amt
580 return value
581 elif amt == chunk_left:
582 value += self._safe_read(amt)
583 self._safe_read(2) # toss the CRLF at the end of the chunk
584 self.chunk_left = None
585 return value
586 else:
587 value += self._safe_read(chunk_left)
588 amt -= chunk_left
589
590 # we read the whole chunk, get another
591 self._safe_read(2) # toss the CRLF at the end of the chunk
592 chunk_left = None
593
594 # read and discard trailer up to the CRLF terminator
595 ### note: we shouldn't have any trailers!
Raymond Hettingerb2e0b922003-02-26 22:45:18 +0000596 while True:
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000597 line = self.fp.readline()
Jeremy Hyltone5d0e842007-08-03 13:45:24 +0000598 if line == "\r\n":
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000599 break
600
601 # we read everything; close the "file"
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000602 self.close()
603
604 return value
Tim Peters230a60c2002-11-09 05:08:07 +0000605
Greg Steindd6eefb2000-07-18 09:09:48 +0000606 def _safe_read(self, amt):
607 """Read the number of bytes requested, compensating for partial reads.
608
609 Normally, we have a blocking socket, but a read() can be interrupted
610 by a signal (resulting in a partial read).
611
612 Note that we cannot distinguish between EOF and an interrupt when zero
613 bytes have been read. IncompleteRead() will be raised in this
614 situation.
615
616 This function should be used when <amt> bytes "should" be present for
617 reading. If the bytes are truly not available (due to EOF), then the
618 IncompleteRead exception can be used to detect the problem.
619 """
Georg Brandl80ba8e82005-09-29 20:16:07 +0000620 s = []
Greg Steindd6eefb2000-07-18 09:09:48 +0000621 while amt > 0:
Georg Brandl80ba8e82005-09-29 20:16:07 +0000622 chunk = self.fp.read(min(amt, MAXAMOUNT))
Greg Steindd6eefb2000-07-18 09:09:48 +0000623 if not chunk:
624 raise IncompleteRead(s)
Georg Brandl80ba8e82005-09-29 20:16:07 +0000625 s.append(chunk)
Raymond Hettingerb2e0b922003-02-26 22:45:18 +0000626 amt -= len(chunk)
Guido van Rossuma00f1232007-09-12 19:43:09 +0000627 return b"".join(s)
Greg Steindd6eefb2000-07-18 09:09:48 +0000628
629 def getheader(self, name, default=None):
630 if self.msg is None:
631 raise ResponseNotReady()
632 return self.msg.getheader(name, default)
Greg Stein5e0fa402000-06-26 08:28:01 +0000633
Martin v. Löwisdeacce22004-08-18 12:46:26 +0000634 def getheaders(self):
635 """Return list of (header, value) tuples."""
636 if self.msg is None:
637 raise ResponseNotReady()
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000638 return list(self.msg.items())
Martin v. Löwisdeacce22004-08-18 12:46:26 +0000639
Greg Stein5e0fa402000-06-26 08:28:01 +0000640
641class HTTPConnection:
642
Greg Steindd6eefb2000-07-18 09:09:48 +0000643 _http_vsn = 11
644 _http_vsn_str = 'HTTP/1.1'
Greg Stein5e0fa402000-06-26 08:28:01 +0000645
Greg Steindd6eefb2000-07-18 09:09:48 +0000646 response_class = HTTPResponse
647 default_port = HTTP_PORT
648 auto_open = 1
Jeremy Hylton30f86742000-09-18 22:50:38 +0000649 debuglevel = 0
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000650 strict = 0
Greg Stein5e0fa402000-06-26 08:28:01 +0000651
Guido van Rossumd8faa362007-04-27 19:54:29 +0000652 def __init__(self, host, port=None, strict=None, timeout=None):
653 self.timeout = timeout
Greg Steindd6eefb2000-07-18 09:09:48 +0000654 self.sock = None
Jeremy Hylton8531b1b2002-07-16 21:21:11 +0000655 self._buffer = []
Greg Steindd6eefb2000-07-18 09:09:48 +0000656 self.__response = None
657 self.__state = _CS_IDLE
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000658 self._method = None
Tim Petersc411dba2002-07-16 21:35:23 +0000659
Greg Steindd6eefb2000-07-18 09:09:48 +0000660 self._set_hostport(host, port)
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000661 if strict is not None:
662 self.strict = strict
Greg Stein5e0fa402000-06-26 08:28:01 +0000663
Greg Steindd6eefb2000-07-18 09:09:48 +0000664 def _set_hostport(self, host, port):
665 if port is None:
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000666 i = host.rfind(':')
Skip Montanarocae14d22004-09-14 17:55:21 +0000667 j = host.rfind(']') # ipv6 addresses have [...]
668 if i > j:
Skip Montanaro9d389972002-03-24 16:53:50 +0000669 try:
670 port = int(host[i+1:])
671 except ValueError:
Jeremy Hyltonfbd79942002-07-02 20:19:08 +0000672 raise InvalidURL("nonnumeric port: '%s'" % host[i+1:])
Greg Steindd6eefb2000-07-18 09:09:48 +0000673 host = host[:i]
674 else:
675 port = self.default_port
Raymond Hettinger4d037912004-10-14 15:23:38 +0000676 if host and host[0] == '[' and host[-1] == ']':
Brett Cannon0a1af4a2004-09-15 23:26:23 +0000677 host = host[1:-1]
Greg Steindd6eefb2000-07-18 09:09:48 +0000678 self.host = host
679 self.port = port
Greg Stein5e0fa402000-06-26 08:28:01 +0000680
Jeremy Hylton30f86742000-09-18 22:50:38 +0000681 def set_debuglevel(self, level):
682 self.debuglevel = level
683
Greg Steindd6eefb2000-07-18 09:09:48 +0000684 def connect(self):
685 """Connect to the host and port specified in __init__."""
Guido van Rossumd8faa362007-04-27 19:54:29 +0000686 self.sock = socket.create_connection((self.host,self.port),
687 self.timeout)
Greg Stein5e0fa402000-06-26 08:28:01 +0000688
Greg Steindd6eefb2000-07-18 09:09:48 +0000689 def close(self):
690 """Close the connection to the HTTP server."""
691 if self.sock:
Tim Peters07e99cb2001-01-14 23:47:14 +0000692 self.sock.close() # close it manually... there may be other refs
Greg Steindd6eefb2000-07-18 09:09:48 +0000693 self.sock = None
694 if self.__response:
695 self.__response.close()
696 self.__response = None
697 self.__state = _CS_IDLE
Greg Stein5e0fa402000-06-26 08:28:01 +0000698
Greg Steindd6eefb2000-07-18 09:09:48 +0000699 def send(self, str):
700 """Send `str' to the server."""
701 if self.sock is None:
702 if self.auto_open:
703 self.connect()
704 else:
705 raise NotConnected()
Greg Stein5e0fa402000-06-26 08:28:01 +0000706
Jeremy Hyltone3252ec2002-07-16 21:41:43 +0000707 # send the data to the server. if we get a broken pipe, then close
Greg Steindd6eefb2000-07-18 09:09:48 +0000708 # the socket. we want to reconnect when somebody tries to send again.
709 #
710 # NOTE: we DO propagate the error, though, because we cannot simply
711 # ignore the error... the caller will know if they can retry.
Jeremy Hylton30f86742000-09-18 22:50:38 +0000712 if self.debuglevel > 0:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000713 print("send:", repr(str))
Greg Steindd6eefb2000-07-18 09:09:48 +0000714 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000715 blocksize=8192
716 if hasattr(str,'read') :
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000717 if self.debuglevel > 0: print("sendIng a read()able")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000718 data=str.read(blocksize)
719 while data:
720 self.sock.sendall(data)
721 data=str.read(blocksize)
722 else:
723 self.sock.sendall(str)
Guido van Rossumb940e112007-01-10 16:19:56 +0000724 except socket.error as v:
Guido van Rossum89df2452007-03-19 22:26:27 +0000725 if v.args[0] == 32: # Broken pipe
Greg Steindd6eefb2000-07-18 09:09:48 +0000726 self.close()
727 raise
Greg Stein5e0fa402000-06-26 08:28:01 +0000728
Jeremy Hylton8531b1b2002-07-16 21:21:11 +0000729 def _output(self, s):
730 """Add a line of output to the current request buffer.
Tim Peters469cdad2002-08-08 20:19:19 +0000731
Jeremy Hyltone3252ec2002-07-16 21:41:43 +0000732 Assumes that the line does *not* end with \\r\\n.
Jeremy Hylton8531b1b2002-07-16 21:21:11 +0000733 """
734 self._buffer.append(s)
735
736 def _send_output(self):
737 """Send the currently buffered request and clear the buffer.
738
Jeremy Hyltone3252ec2002-07-16 21:41:43 +0000739 Appends an extra \\r\\n to the buffer.
Jeremy Hylton8531b1b2002-07-16 21:21:11 +0000740 """
Martin v. Löwisdd5a8602007-06-30 09:22:09 +0000741 self._buffer.extend((b"", b""))
742 msg = b"\r\n".join(self._buffer)
Jeremy Hylton8531b1b2002-07-16 21:21:11 +0000743 del self._buffer[:]
744 self.send(msg)
745
Martin v. Löwisaf7dc8d2003-11-19 19:51:55 +0000746 def putrequest(self, method, url, skip_host=0, skip_accept_encoding=0):
Greg Steindd6eefb2000-07-18 09:09:48 +0000747 """Send a request to the server.
Greg Stein5e0fa402000-06-26 08:28:01 +0000748
Greg Steindd6eefb2000-07-18 09:09:48 +0000749 `method' specifies an HTTP request method, e.g. 'GET'.
750 `url' specifies the object being requested, e.g. '/index.html'.
Martin v. Löwisaf7dc8d2003-11-19 19:51:55 +0000751 `skip_host' if True does not add automatically a 'Host:' header
752 `skip_accept_encoding' if True does not add automatically an
753 'Accept-Encoding:' header
Greg Steindd6eefb2000-07-18 09:09:48 +0000754 """
Greg Stein5e0fa402000-06-26 08:28:01 +0000755
Greg Stein616a58d2003-06-24 06:35:19 +0000756 # if a prior response has been completed, then forget about it.
Greg Steindd6eefb2000-07-18 09:09:48 +0000757 if self.__response and self.__response.isclosed():
758 self.__response = None
Greg Stein5e0fa402000-06-26 08:28:01 +0000759
Tim Peters58eb11c2004-01-18 20:29:55 +0000760
Greg Steindd6eefb2000-07-18 09:09:48 +0000761 # in certain cases, we cannot issue another request on this connection.
762 # this occurs when:
763 # 1) we are in the process of sending a request. (_CS_REQ_STARTED)
764 # 2) a response to a previous request has signalled that it is going
765 # to close the connection upon completion.
766 # 3) the headers for the previous response have not been read, thus
767 # we cannot determine whether point (2) is true. (_CS_REQ_SENT)
768 #
769 # if there is no prior response, then we can request at will.
770 #
771 # if point (2) is true, then we will have passed the socket to the
772 # response (effectively meaning, "there is no prior response"), and
773 # will open a new one when a new request is made.
774 #
775 # Note: if a prior response exists, then we *can* start a new request.
776 # We are not allowed to begin fetching the response to this new
777 # request, however, until that prior response is complete.
778 #
779 if self.__state == _CS_IDLE:
780 self.__state = _CS_REQ_STARTED
781 else:
782 raise CannotSendRequest()
Greg Stein5e0fa402000-06-26 08:28:01 +0000783
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000784 # Save the method we use, we need it later in the response phase
785 self._method = method
Greg Steindd6eefb2000-07-18 09:09:48 +0000786 if not url:
787 url = '/'
Martin v. Löwisdd5a8602007-06-30 09:22:09 +0000788 request = '%s %s %s' % (method, url, self._http_vsn_str)
Greg Stein5e0fa402000-06-26 08:28:01 +0000789
Martin v. Löwisdd5a8602007-06-30 09:22:09 +0000790 # Non-ASCII characters should have been eliminated earlier
791 self._output(request.encode('ascii'))
Greg Stein5e0fa402000-06-26 08:28:01 +0000792
Greg Steindd6eefb2000-07-18 09:09:48 +0000793 if self._http_vsn == 11:
794 # Issue some standard headers for better HTTP/1.1 compliance
Greg Stein5e0fa402000-06-26 08:28:01 +0000795
Jeremy Hylton3921ff62002-03-09 06:07:23 +0000796 if not skip_host:
797 # this header is issued *only* for HTTP/1.1
798 # connections. more specifically, this means it is
799 # only issued when the client uses the new
800 # HTTPConnection() class. backwards-compat clients
801 # will be using HTTP/1.0 and those clients may be
802 # issuing this header themselves. we should NOT issue
803 # it twice; some web servers (such as Apache) barf
804 # when they see two Host: headers
Guido van Rossumf6922aa2001-01-14 21:03:01 +0000805
Jeremy Hylton3921ff62002-03-09 06:07:23 +0000806 # If we need a non-standard port,include it in the
807 # header. If the request is going through a proxy,
808 # but the host of the actual URL, not the host of the
809 # proxy.
Jeremy Hylton8acf1e02002-03-08 19:35:51 +0000810
Jeremy Hylton3921ff62002-03-09 06:07:23 +0000811 netloc = ''
812 if url.startswith('http'):
813 nil, netloc, nil, nil, nil = urlsplit(url)
814
815 if netloc:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000816 try:
817 netloc_enc = netloc.encode("ascii")
818 except UnicodeEncodeError:
819 netloc_enc = netloc.encode("idna")
820 self.putheader('Host', netloc_enc)
Jeremy Hylton3921ff62002-03-09 06:07:23 +0000821 else:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000822 try:
823 host_enc = self.host.encode("ascii")
824 except UnicodeEncodeError:
825 host_enc = self.host.encode("idna")
826 if self.port == HTTP_PORT:
827 self.putheader('Host', host_enc)
828 else:
829 self.putheader('Host', "%s:%s" % (host_enc, self.port))
Greg Stein5e0fa402000-06-26 08:28:01 +0000830
Greg Steindd6eefb2000-07-18 09:09:48 +0000831 # note: we are assuming that clients will not attempt to set these
832 # headers since *this* library must deal with the
833 # consequences. this also means that when the supporting
834 # libraries are updated to recognize other forms, then this
835 # code should be changed (removed or updated).
Greg Stein5e0fa402000-06-26 08:28:01 +0000836
Greg Steindd6eefb2000-07-18 09:09:48 +0000837 # we only want a Content-Encoding of "identity" since we don't
838 # support encodings such as x-gzip or x-deflate.
Martin v. Löwisaf7dc8d2003-11-19 19:51:55 +0000839 if not skip_accept_encoding:
840 self.putheader('Accept-Encoding', 'identity')
Greg Stein5e0fa402000-06-26 08:28:01 +0000841
Greg Steindd6eefb2000-07-18 09:09:48 +0000842 # we can accept "chunked" Transfer-Encodings, but no others
843 # NOTE: no TE header implies *only* "chunked"
844 #self.putheader('TE', 'chunked')
Greg Stein5e0fa402000-06-26 08:28:01 +0000845
Greg Steindd6eefb2000-07-18 09:09:48 +0000846 # if TE is supplied in the header, then it must appear in a
847 # Connection header.
848 #self.putheader('Connection', 'TE')
Greg Stein5e0fa402000-06-26 08:28:01 +0000849
Greg Steindd6eefb2000-07-18 09:09:48 +0000850 else:
851 # For HTTP/1.0, the server will assume "not chunked"
852 pass
Greg Stein5e0fa402000-06-26 08:28:01 +0000853
Greg Steindd6eefb2000-07-18 09:09:48 +0000854 def putheader(self, header, value):
855 """Send a request header line to the server.
Greg Stein5e0fa402000-06-26 08:28:01 +0000856
Greg Steindd6eefb2000-07-18 09:09:48 +0000857 For example: h.putheader('Accept', 'text/html')
858 """
859 if self.__state != _CS_REQ_STARTED:
860 raise CannotSendHeader()
Greg Stein5e0fa402000-06-26 08:28:01 +0000861
Martin v. Löwisdd5a8602007-06-30 09:22:09 +0000862 header = '%s: %s' % (header, value)
863 self._output(header.encode('ascii'))
Greg Stein5e0fa402000-06-26 08:28:01 +0000864
Greg Steindd6eefb2000-07-18 09:09:48 +0000865 def endheaders(self):
866 """Indicate that the last header line has been sent to the server."""
Greg Stein5e0fa402000-06-26 08:28:01 +0000867
Greg Steindd6eefb2000-07-18 09:09:48 +0000868 if self.__state == _CS_REQ_STARTED:
869 self.__state = _CS_REQ_SENT
870 else:
871 raise CannotSendHeader()
Greg Stein5e0fa402000-06-26 08:28:01 +0000872
Jeremy Hylton8531b1b2002-07-16 21:21:11 +0000873 self._send_output()
Greg Stein5e0fa402000-06-26 08:28:01 +0000874
Greg Steindd6eefb2000-07-18 09:09:48 +0000875 def request(self, method, url, body=None, headers={}):
876 """Send a complete request to the server."""
Greg Steindd6eefb2000-07-18 09:09:48 +0000877 try:
878 self._send_request(method, url, body, headers)
Guido van Rossumb940e112007-01-10 16:19:56 +0000879 except socket.error as v:
Greg Steindd6eefb2000-07-18 09:09:48 +0000880 # trap 'Broken pipe' if we're allowed to automatically reconnect
Guido van Rossum89df2452007-03-19 22:26:27 +0000881 if v.args[0] != 32 or not self.auto_open:
Greg Steindd6eefb2000-07-18 09:09:48 +0000882 raise
883 # try one more time
884 self._send_request(method, url, body, headers)
Greg Stein5e0fa402000-06-26 08:28:01 +0000885
Greg Steindd6eefb2000-07-18 09:09:48 +0000886 def _send_request(self, method, url, body, headers):
Jeremy Hylton2c178252004-08-07 16:28:14 +0000887 # honour explicitly requested Host: and Accept-Encoding headers
888 header_names = dict.fromkeys([k.lower() for k in headers])
889 skips = {}
890 if 'host' in header_names:
891 skips['skip_host'] = 1
892 if 'accept-encoding' in header_names:
893 skips['skip_accept_encoding'] = 1
Greg Stein5e0fa402000-06-26 08:28:01 +0000894
Jeremy Hylton2c178252004-08-07 16:28:14 +0000895 self.putrequest(method, url, **skips)
896
897 if body and ('content-length' not in header_names):
Jeremy Hylton4b878bd2007-08-10 18:49:01 +0000898 thelen = None
Thomas Wouters89f507f2006-12-13 04:49:30 +0000899 try:
Jeremy Hylton4b878bd2007-08-10 18:49:01 +0000900 thelen = str(len(body))
Guido van Rossumb940e112007-01-10 16:19:56 +0000901 except TypeError as te:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000902 # If this is a file-like object, try to
903 # fstat its file descriptor
904 import os
905 try:
906 thelen = str(os.fstat(body.fileno()).st_size)
907 except (AttributeError, OSError):
908 # Don't send a length if this failed
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000909 if self.debuglevel > 0: print("Cannot stat!!")
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000910
Thomas Wouters89f507f2006-12-13 04:49:30 +0000911 if thelen is not None:
912 self.putheader('Content-Length',thelen)
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000913 for hdr, value in headers.items():
Greg Steindd6eefb2000-07-18 09:09:48 +0000914 self.putheader(hdr, value)
915 self.endheaders()
Greg Stein5e0fa402000-06-26 08:28:01 +0000916
Greg Steindd6eefb2000-07-18 09:09:48 +0000917 if body:
Martin v. Löwisdd5a8602007-06-30 09:22:09 +0000918 if isinstance(body, str): body = body.encode('ascii')
Greg Steindd6eefb2000-07-18 09:09:48 +0000919 self.send(body)
Greg Stein5e0fa402000-06-26 08:28:01 +0000920
Greg Steindd6eefb2000-07-18 09:09:48 +0000921 def getresponse(self):
Jeremy Hyltonfb35f652007-08-03 20:30:33 +0000922 """Get the response from the server."""
Greg Stein5e0fa402000-06-26 08:28:01 +0000923
Greg Stein616a58d2003-06-24 06:35:19 +0000924 # if a prior response has been completed, then forget about it.
Greg Steindd6eefb2000-07-18 09:09:48 +0000925 if self.__response and self.__response.isclosed():
926 self.__response = None
Greg Stein5e0fa402000-06-26 08:28:01 +0000927
Greg Steindd6eefb2000-07-18 09:09:48 +0000928 #
929 # if a prior response exists, then it must be completed (otherwise, we
930 # cannot read this response's header to determine the connection-close
931 # behavior)
932 #
933 # note: if a prior response existed, but was connection-close, then the
934 # socket and response were made independent of this HTTPConnection
935 # object since a new request requires that we open a whole new
936 # connection
937 #
938 # this means the prior response had one of two states:
939 # 1) will_close: this connection was reset and the prior socket and
940 # response operate independently
941 # 2) persistent: the response was retained and we await its
942 # isclosed() status to become true.
943 #
944 if self.__state != _CS_REQ_SENT or self.__response:
945 raise ResponseNotReady()
Greg Stein5e0fa402000-06-26 08:28:01 +0000946
Jeremy Hylton30f86742000-09-18 22:50:38 +0000947 if self.debuglevel > 0:
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000948 response = self.response_class(self.sock, self.debuglevel,
Tim Petersc2659cf2003-05-12 20:19:37 +0000949 strict=self.strict,
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000950 method=self._method)
Jeremy Hylton30f86742000-09-18 22:50:38 +0000951 else:
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000952 response = self.response_class(self.sock, strict=self.strict,
953 method=self._method)
Greg Stein5e0fa402000-06-26 08:28:01 +0000954
Jeremy Hylton39c03802002-07-12 14:04:09 +0000955 response.begin()
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000956 assert response.will_close != _UNKNOWN
Greg Steindd6eefb2000-07-18 09:09:48 +0000957 self.__state = _CS_IDLE
Greg Stein5e0fa402000-06-26 08:28:01 +0000958
Greg Steindd6eefb2000-07-18 09:09:48 +0000959 if response.will_close:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000960 # this effectively passes the connection to the response
961 self.close()
Greg Steindd6eefb2000-07-18 09:09:48 +0000962 else:
963 # remember this, so we can tell when it is complete
964 self.__response = response
Greg Stein5e0fa402000-06-26 08:28:01 +0000965
Greg Steindd6eefb2000-07-18 09:09:48 +0000966 return response
Greg Stein5e0fa402000-06-26 08:28:01 +0000967
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000968try:
969 import ssl
970except ImportError:
971 pass
972else:
973 class HTTPSConnection(HTTPConnection):
974 "This class allows communication via SSL."
Jeremy Hylton29d27ac2002-07-09 21:22:36 +0000975
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000976 default_port = HTTPS_PORT
Jeremy Hylton29d27ac2002-07-09 21:22:36 +0000977
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000978 def __init__(self, host, port=None, key_file=None, cert_file=None,
979 strict=None, timeout=None):
980 HTTPConnection.__init__(self, host, port, strict, timeout)
981 self.key_file = key_file
982 self.cert_file = cert_file
Jeremy Hylton29d27ac2002-07-09 21:22:36 +0000983
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000984 def connect(self):
985 "Connect to a host on a given (SSL) port."
Jeremy Hylton29d27ac2002-07-09 21:22:36 +0000986
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000987 sock = socket.create_connection((self.host, self.port), self.timeout)
988 self.sock = ssl.sslsocket(sock, self.key_file, self.cert_file)
Jeremy Hylton29d27ac2002-07-09 21:22:36 +0000989
Jeremy Hylton29d27ac2002-07-09 21:22:36 +0000990
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000991 def FakeSocket (sock, sslobj):
Thomas Wouters89d996e2007-09-08 17:39:28 +0000992 warnings.warn("FakeSocket is deprecated, and won't be in 3.x. " +
993 "Use the result of ssl.sslsocket directly instead.",
994 DeprecationWarning, stacklevel=2)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000995 return sslobj
Jeremy Hylton29d27ac2002-07-09 21:22:36 +0000996
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000997 __all__.append("HTTPSConnection")
Greg Stein5e0fa402000-06-26 08:28:01 +0000998
Greg Stein5e0fa402000-06-26 08:28:01 +0000999class HTTPException(Exception):
Jeremy Hylton12f4f352002-07-06 18:55:01 +00001000 # Subclasses that define an __init__ must call Exception.__init__
1001 # or define self.args. Otherwise, str() will fail.
Greg Steindd6eefb2000-07-18 09:09:48 +00001002 pass
Greg Stein5e0fa402000-06-26 08:28:01 +00001003
1004class NotConnected(HTTPException):
Greg Steindd6eefb2000-07-18 09:09:48 +00001005 pass
Greg Stein5e0fa402000-06-26 08:28:01 +00001006
Skip Montanaro9d389972002-03-24 16:53:50 +00001007class InvalidURL(HTTPException):
1008 pass
1009
Greg Stein5e0fa402000-06-26 08:28:01 +00001010class UnknownProtocol(HTTPException):
Greg Steindd6eefb2000-07-18 09:09:48 +00001011 def __init__(self, version):
Jeremy Hylton12f4f352002-07-06 18:55:01 +00001012 self.args = version,
Greg Steindd6eefb2000-07-18 09:09:48 +00001013 self.version = version
Greg Stein5e0fa402000-06-26 08:28:01 +00001014
1015class UnknownTransferEncoding(HTTPException):
Greg Steindd6eefb2000-07-18 09:09:48 +00001016 pass
Greg Stein5e0fa402000-06-26 08:28:01 +00001017
Greg Stein5e0fa402000-06-26 08:28:01 +00001018class UnimplementedFileMode(HTTPException):
Greg Steindd6eefb2000-07-18 09:09:48 +00001019 pass
Greg Stein5e0fa402000-06-26 08:28:01 +00001020
1021class IncompleteRead(HTTPException):
Greg Steindd6eefb2000-07-18 09:09:48 +00001022 def __init__(self, partial):
Jeremy Hylton12f4f352002-07-06 18:55:01 +00001023 self.args = partial,
Greg Steindd6eefb2000-07-18 09:09:48 +00001024 self.partial = partial
Greg Stein5e0fa402000-06-26 08:28:01 +00001025
1026class ImproperConnectionState(HTTPException):
Greg Steindd6eefb2000-07-18 09:09:48 +00001027 pass
Greg Stein5e0fa402000-06-26 08:28:01 +00001028
1029class CannotSendRequest(ImproperConnectionState):
Greg Steindd6eefb2000-07-18 09:09:48 +00001030 pass
Greg Stein5e0fa402000-06-26 08:28:01 +00001031
1032class CannotSendHeader(ImproperConnectionState):
Greg Steindd6eefb2000-07-18 09:09:48 +00001033 pass
Greg Stein5e0fa402000-06-26 08:28:01 +00001034
1035class ResponseNotReady(ImproperConnectionState):
Greg Steindd6eefb2000-07-18 09:09:48 +00001036 pass
Greg Stein5e0fa402000-06-26 08:28:01 +00001037
1038class BadStatusLine(HTTPException):
Greg Steindd6eefb2000-07-18 09:09:48 +00001039 def __init__(self, line):
Jeremy Hylton12f4f352002-07-06 18:55:01 +00001040 self.args = line,
Greg Steindd6eefb2000-07-18 09:09:48 +00001041 self.line = line
Greg Stein5e0fa402000-06-26 08:28:01 +00001042
1043# for backwards compatibility
1044error = HTTPException
1045
Jeremy Hyltond46aa372002-07-06 18:48:07 +00001046class LineAndFileWrapper:
1047 """A limited file-like object for HTTP/0.9 responses."""
1048
1049 # The status-line parsing code calls readline(), which normally
1050 # get the HTTP status line. For a 0.9 response, however, this is
1051 # actually the first line of the body! Clients need to get a
1052 # readable file object that contains that line.
1053
1054 def __init__(self, line, file):
1055 self._line = line
1056 self._file = file
1057 self._line_consumed = 0
1058 self._line_offset = 0
1059 self._line_left = len(line)
1060
1061 def __getattr__(self, attr):
1062 return getattr(self._file, attr)
1063
1064 def _done(self):
1065 # called when the last byte is read from the line. After the
1066 # call, all read methods are delegated to the underlying file
Skip Montanaro74b9a7a2003-02-25 17:48:15 +00001067 # object.
Jeremy Hyltond46aa372002-07-06 18:48:07 +00001068 self._line_consumed = 1
1069 self.read = self._file.read
1070 self.readline = self._file.readline
1071 self.readlines = self._file.readlines
1072
1073 def read(self, amt=None):
Hye-Shik Chang39aef792004-06-05 13:30:56 +00001074 if self._line_consumed:
1075 return self._file.read(amt)
1076 assert self._line_left
Jeremy Hyltond46aa372002-07-06 18:48:07 +00001077 if amt is None or amt > self._line_left:
1078 s = self._line[self._line_offset:]
1079 self._done()
1080 if amt is None:
1081 return s + self._file.read()
1082 else:
Tim Petersc411dba2002-07-16 21:35:23 +00001083 return s + self._file.read(amt - len(s))
Jeremy Hyltond46aa372002-07-06 18:48:07 +00001084 else:
1085 assert amt <= self._line_left
1086 i = self._line_offset
1087 j = i + amt
1088 s = self._line[i:j]
1089 self._line_offset = j
1090 self._line_left -= amt
1091 if self._line_left == 0:
1092 self._done()
1093 return s
Tim Petersc411dba2002-07-16 21:35:23 +00001094
Jeremy Hyltond46aa372002-07-06 18:48:07 +00001095 def readline(self):
Hye-Shik Chang39aef792004-06-05 13:30:56 +00001096 if self._line_consumed:
1097 return self._file.readline()
1098 assert self._line_left
Jeremy Hyltond46aa372002-07-06 18:48:07 +00001099 s = self._line[self._line_offset:]
1100 self._done()
1101 return s
1102
1103 def readlines(self, size=None):
Hye-Shik Chang39aef792004-06-05 13:30:56 +00001104 if self._line_consumed:
1105 return self._file.readlines(size)
1106 assert self._line_left
Jeremy Hyltond46aa372002-07-06 18:48:07 +00001107 L = [self._line[self._line_offset:]]
1108 self._done()
1109 if size is None:
1110 return L + self._file.readlines()
1111 else:
1112 return L + self._file.readlines(size)