blob: 8dbe8a07e41ef89c827d47b7ed9c896aee59a0d2 [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
Andrew M. Kuchlingca2e7902006-07-30 00:27:34 +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
Guido van Rossum65ab98c1995-08-07 20:13:02 +000070import mimetools
Jeremy Hylton6459c8d2001-10-11 17:47:22 +000071import socket
Jeremy Hylton8acf1e02002-03-08 19:35:51 +000072from urlparse import urlsplit
Bill Janssenc4592642007-08-31 19:02:23 +000073import warnings
Guido van Rossum23acc951994-02-21 16:36:04 +000074
Guido van Rossum09c8b6c1999-12-07 21:37:17 +000075try:
Greg Steindd6eefb2000-07-18 09:09:48 +000076 from cStringIO import StringIO
Greg Stein5e0fa402000-06-26 08:28:01 +000077except ImportError:
Greg Steindd6eefb2000-07-18 09:09:48 +000078 from StringIO import StringIO
Guido van Rossum09c8b6c1999-12-07 21:37:17 +000079
Thomas Woutersa6900e82007-08-30 21:54:39 +000080__all__ = ["HTTP", "HTTPResponse", "HTTPConnection",
Skip Montanaro951a8842001-06-01 16:25:38 +000081 "HTTPException", "NotConnected", "UnknownProtocol",
Jeremy Hylton7c75c992002-06-28 23:38:14 +000082 "UnknownTransferEncoding", "UnimplementedFileMode",
83 "IncompleteRead", "InvalidURL", "ImproperConnectionState",
84 "CannotSendRequest", "CannotSendHeader", "ResponseNotReady",
Georg Brandl6aab16e2006-02-17 19:17:25 +000085 "BadStatusLine", "error", "responses"]
Skip Montanaro2dd42762001-01-23 15:35:05 +000086
Guido van Rossum23acc951994-02-21 16:36:04 +000087HTTP_PORT = 80
Guido van Rossum09c8b6c1999-12-07 21:37:17 +000088HTTPS_PORT = 443
89
Greg Stein5e0fa402000-06-26 08:28:01 +000090_UNKNOWN = 'UNKNOWN'
91
92# connection states
93_CS_IDLE = 'Idle'
94_CS_REQ_STARTED = 'Request-started'
95_CS_REQ_SENT = 'Request-sent'
96
Martin v. Löwis39a31782004-09-18 09:03:49 +000097# status codes
98# informational
99CONTINUE = 100
100SWITCHING_PROTOCOLS = 101
101PROCESSING = 102
102
103# successful
104OK = 200
105CREATED = 201
106ACCEPTED = 202
107NON_AUTHORITATIVE_INFORMATION = 203
108NO_CONTENT = 204
109RESET_CONTENT = 205
110PARTIAL_CONTENT = 206
111MULTI_STATUS = 207
112IM_USED = 226
113
114# redirection
115MULTIPLE_CHOICES = 300
116MOVED_PERMANENTLY = 301
117FOUND = 302
118SEE_OTHER = 303
119NOT_MODIFIED = 304
120USE_PROXY = 305
121TEMPORARY_REDIRECT = 307
122
123# client error
124BAD_REQUEST = 400
125UNAUTHORIZED = 401
126PAYMENT_REQUIRED = 402
127FORBIDDEN = 403
128NOT_FOUND = 404
129METHOD_NOT_ALLOWED = 405
130NOT_ACCEPTABLE = 406
131PROXY_AUTHENTICATION_REQUIRED = 407
132REQUEST_TIMEOUT = 408
133CONFLICT = 409
134GONE = 410
135LENGTH_REQUIRED = 411
136PRECONDITION_FAILED = 412
137REQUEST_ENTITY_TOO_LARGE = 413
138REQUEST_URI_TOO_LONG = 414
139UNSUPPORTED_MEDIA_TYPE = 415
140REQUESTED_RANGE_NOT_SATISFIABLE = 416
141EXPECTATION_FAILED = 417
142UNPROCESSABLE_ENTITY = 422
143LOCKED = 423
144FAILED_DEPENDENCY = 424
145UPGRADE_REQUIRED = 426
146
147# server error
148INTERNAL_SERVER_ERROR = 500
149NOT_IMPLEMENTED = 501
150BAD_GATEWAY = 502
151SERVICE_UNAVAILABLE = 503
152GATEWAY_TIMEOUT = 504
153HTTP_VERSION_NOT_SUPPORTED = 505
154INSUFFICIENT_STORAGE = 507
155NOT_EXTENDED = 510
156
Georg Brandl6aab16e2006-02-17 19:17:25 +0000157# Mapping status codes to official W3C names
158responses = {
159 100: 'Continue',
160 101: 'Switching Protocols',
161
162 200: 'OK',
163 201: 'Created',
164 202: 'Accepted',
165 203: 'Non-Authoritative Information',
166 204: 'No Content',
167 205: 'Reset Content',
168 206: 'Partial Content',
169
170 300: 'Multiple Choices',
171 301: 'Moved Permanently',
172 302: 'Found',
173 303: 'See Other',
174 304: 'Not Modified',
175 305: 'Use Proxy',
176 306: '(Unused)',
177 307: 'Temporary Redirect',
178
179 400: 'Bad Request',
180 401: 'Unauthorized',
181 402: 'Payment Required',
182 403: 'Forbidden',
183 404: 'Not Found',
184 405: 'Method Not Allowed',
185 406: 'Not Acceptable',
186 407: 'Proxy Authentication Required',
187 408: 'Request Timeout',
188 409: 'Conflict',
189 410: 'Gone',
190 411: 'Length Required',
191 412: 'Precondition Failed',
192 413: 'Request Entity Too Large',
193 414: 'Request-URI Too Long',
194 415: 'Unsupported Media Type',
195 416: 'Requested Range Not Satisfiable',
196 417: 'Expectation Failed',
197
198 500: 'Internal Server Error',
199 501: 'Not Implemented',
200 502: 'Bad Gateway',
201 503: 'Service Unavailable',
202 504: 'Gateway Timeout',
203 505: 'HTTP Version Not Supported',
204}
205
Georg Brandl80ba8e82005-09-29 20:16:07 +0000206# maximal amount of data to read at one time in _safe_read
207MAXAMOUNT = 1048576
208
Jeremy Hylton6d0a4c72002-07-07 16:51:37 +0000209class HTTPMessage(mimetools.Message):
210
211 def addheader(self, key, value):
212 """Add header for field key handling repeats."""
213 prev = self.dict.get(key)
214 if prev is None:
215 self.dict[key] = value
216 else:
217 combined = ", ".join((prev, value))
218 self.dict[key] = combined
219
220 def addcontinue(self, key, more):
221 """Add more field data from a continuation line."""
222 prev = self.dict[key]
223 self.dict[key] = prev + "\n " + more
224
225 def readheaders(self):
226 """Read header lines.
227
228 Read header lines up to the entirely blank line that terminates them.
229 The (normally blank) line that ends the headers is skipped, but not
230 included in the returned list. If a non-header line ends the headers,
231 (which is an error), an attempt is made to backspace over it; it is
232 never included in the returned list.
233
234 The variable self.status is set to the empty string if all went well,
235 otherwise it is an error message. The variable self.headers is a
236 completely uninterpreted list of lines contained in the header (so
237 printing them will reproduce the header exactly as it appears in the
238 file).
239
240 If multiple header fields with the same name occur, they are combined
241 according to the rules in RFC 2616 sec 4.2:
242
243 Appending each subsequent field-value to the first, each separated
244 by a comma. The order in which header fields with the same field-name
245 are received is significant to the interpretation of the combined
246 field value.
247 """
248 # XXX The implementation overrides the readheaders() method of
249 # rfc822.Message. The base class design isn't amenable to
250 # customized behavior here so the method here is a copy of the
251 # base class code with a few small changes.
252
253 self.dict = {}
254 self.unixfrom = ''
Raymond Hettingerb2e0b922003-02-26 22:45:18 +0000255 self.headers = hlist = []
Jeremy Hylton6d0a4c72002-07-07 16:51:37 +0000256 self.status = ''
257 headerseen = ""
258 firstline = 1
259 startofline = unread = tell = None
260 if hasattr(self.fp, 'unread'):
261 unread = self.fp.unread
262 elif self.seekable:
263 tell = self.fp.tell
Raymond Hettingerb2e0b922003-02-26 22:45:18 +0000264 while True:
Jeremy Hylton6d0a4c72002-07-07 16:51:37 +0000265 if tell:
266 try:
267 startofline = tell()
268 except IOError:
269 startofline = tell = None
270 self.seekable = 0
271 line = self.fp.readline()
272 if not line:
273 self.status = 'EOF in headers'
274 break
275 # Skip unix From name time lines
276 if firstline and line.startswith('From '):
277 self.unixfrom = self.unixfrom + line
278 continue
279 firstline = 0
280 if headerseen and line[0] in ' \t':
281 # XXX Not sure if continuation lines are handled properly
282 # for http and/or for repeating headers
283 # It's a continuation line.
Raymond Hettingerb2e0b922003-02-26 22:45:18 +0000284 hlist.append(line)
Jeremy Hylton6d0a4c72002-07-07 16:51:37 +0000285 self.addcontinue(headerseen, line.strip())
286 continue
287 elif self.iscomment(line):
288 # It's a comment. Ignore it.
289 continue
290 elif self.islast(line):
291 # Note! No pushback here! The delimiter line gets eaten.
292 break
293 headerseen = self.isheader(line)
294 if headerseen:
295 # It's a legal header line, save it.
Raymond Hettingerb2e0b922003-02-26 22:45:18 +0000296 hlist.append(line)
Jeremy Hylton6d0a4c72002-07-07 16:51:37 +0000297 self.addheader(headerseen, line[len(headerseen)+1:].strip())
298 continue
299 else:
300 # It's not a header line; throw it back and stop here.
301 if not self.dict:
302 self.status = 'No headers'
303 else:
304 self.status = 'Non-header line where header expected'
305 # Try to undo the read.
306 if unread:
307 unread(line)
308 elif tell:
309 self.fp.seek(startofline)
310 else:
311 self.status = self.status + '; bad seek'
312 break
Greg Stein5e0fa402000-06-26 08:28:01 +0000313
314class HTTPResponse:
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000315
316 # strict: If true, raise BadStatusLine if the status line can't be
317 # parsed as a valid HTTP/1.0 or 1.1 status line. By default it is
Skip Montanaro186bec22002-07-25 16:10:38 +0000318 # false because it prevents clients from talking to HTTP/0.9
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000319 # servers. Note that a response with a sufficiently corrupted
320 # status line will look like an HTTP/0.9 response.
321
322 # See RFC 2616 sec 19.6 and RFC 1945 sec 6 for details.
323
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000324 def __init__(self, sock, debuglevel=0, strict=0, method=None):
Greg Steindd6eefb2000-07-18 09:09:48 +0000325 self.fp = sock.makefile('rb', 0)
Jeremy Hylton30f86742000-09-18 22:50:38 +0000326 self.debuglevel = debuglevel
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000327 self.strict = strict
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000328 self._method = method
Greg Stein5e0fa402000-06-26 08:28:01 +0000329
Greg Steindd6eefb2000-07-18 09:09:48 +0000330 self.msg = None
Greg Stein5e0fa402000-06-26 08:28:01 +0000331
Greg Steindd6eefb2000-07-18 09:09:48 +0000332 # from the Status-Line of the response
Tim Peters07e99cb2001-01-14 23:47:14 +0000333 self.version = _UNKNOWN # HTTP-Version
334 self.status = _UNKNOWN # Status-Code
335 self.reason = _UNKNOWN # Reason-Phrase
Greg Stein5e0fa402000-06-26 08:28:01 +0000336
Tim Peters07e99cb2001-01-14 23:47:14 +0000337 self.chunked = _UNKNOWN # is "chunked" being used?
338 self.chunk_left = _UNKNOWN # bytes left to read in current chunk
339 self.length = _UNKNOWN # number of bytes left in response
340 self.will_close = _UNKNOWN # conn will close at end of response
Greg Stein5e0fa402000-06-26 08:28:01 +0000341
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000342 def _read_status(self):
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000343 # Initialize with Simple-Response defaults
Greg Stein5e0fa402000-06-26 08:28:01 +0000344 line = self.fp.readline()
Jeremy Hylton30f86742000-09-18 22:50:38 +0000345 if self.debuglevel > 0:
346 print "reply:", repr(line)
Jeremy Hyltonb6769522003-06-29 17:55:05 +0000347 if not line:
348 # Presumably, the server closed the connection before
349 # sending a valid response.
350 raise BadStatusLine(line)
Greg Steindd6eefb2000-07-18 09:09:48 +0000351 try:
Guido van Rossum34735a62000-12-15 15:09:42 +0000352 [version, status, reason] = line.split(None, 2)
Greg Steindd6eefb2000-07-18 09:09:48 +0000353 except ValueError:
354 try:
Guido van Rossum34735a62000-12-15 15:09:42 +0000355 [version, status] = line.split(None, 1)
Greg Steindd6eefb2000-07-18 09:09:48 +0000356 reason = ""
357 except ValueError:
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000358 # empty version will cause next test to fail and status
359 # will be treated as 0.9 response.
360 version = ""
361 if not version.startswith('HTTP/'):
362 if self.strict:
363 self.close()
364 raise BadStatusLine(line)
365 else:
366 # assume it's a Simple-Response from an 0.9 server
367 self.fp = LineAndFileWrapper(line, self.fp)
368 return "HTTP/0.9", 200, ""
Greg Stein5e0fa402000-06-26 08:28:01 +0000369
Jeremy Hylton23d40472001-04-13 14:57:08 +0000370 # The status code is a three-digit number
371 try:
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000372 status = int(status)
Jeremy Hylton23d40472001-04-13 14:57:08 +0000373 if status < 100 or status > 999:
374 raise BadStatusLine(line)
375 except ValueError:
376 raise BadStatusLine(line)
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000377 return version, status, reason
Greg Stein5e0fa402000-06-26 08:28:01 +0000378
Jeremy Hylton39c03802002-07-12 14:04:09 +0000379 def begin(self):
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000380 if self.msg is not None:
381 # we've already started reading the response
382 return
383
384 # read until we get a non-100 response
Raymond Hettingerb2e0b922003-02-26 22:45:18 +0000385 while True:
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000386 version, status, reason = self._read_status()
Martin v. Löwis39a31782004-09-18 09:03:49 +0000387 if status != CONTINUE:
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000388 break
389 # skip the header from the 100 response
Raymond Hettingerb2e0b922003-02-26 22:45:18 +0000390 while True:
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000391 skip = self.fp.readline().strip()
392 if not skip:
393 break
394 if self.debuglevel > 0:
395 print "header:", skip
Tim Petersc411dba2002-07-16 21:35:23 +0000396
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000397 self.status = status
398 self.reason = reason.strip()
Greg Steindd6eefb2000-07-18 09:09:48 +0000399 if version == 'HTTP/1.0':
400 self.version = 10
Jeremy Hylton110941a2000-10-12 19:58:36 +0000401 elif version.startswith('HTTP/1.'):
Tim Peters07e99cb2001-01-14 23:47:14 +0000402 self.version = 11 # use HTTP/1.1 code for HTTP/1.x where x>=1
Jeremy Hylton110941a2000-10-12 19:58:36 +0000403 elif version == 'HTTP/0.9':
404 self.version = 9
Greg Steindd6eefb2000-07-18 09:09:48 +0000405 else:
406 raise UnknownProtocol(version)
Greg Stein5e0fa402000-06-26 08:28:01 +0000407
Jeremy Hylton110941a2000-10-12 19:58:36 +0000408 if self.version == 9:
Georg Brandl0aade9a2005-06-26 22:06:54 +0000409 self.length = None
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000410 self.chunked = 0
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000411 self.will_close = 1
Jeremy Hylton6d0a4c72002-07-07 16:51:37 +0000412 self.msg = HTTPMessage(StringIO())
Jeremy Hylton110941a2000-10-12 19:58:36 +0000413 return
414
Jeremy Hylton6d0a4c72002-07-07 16:51:37 +0000415 self.msg = HTTPMessage(self.fp, 0)
Jeremy Hylton30f86742000-09-18 22:50:38 +0000416 if self.debuglevel > 0:
417 for hdr in self.msg.headers:
418 print "header:", hdr,
Greg Stein5e0fa402000-06-26 08:28:01 +0000419
Greg Steindd6eefb2000-07-18 09:09:48 +0000420 # don't let the msg keep an fp
421 self.msg.fp = None
Greg Stein5e0fa402000-06-26 08:28:01 +0000422
Greg Steindd6eefb2000-07-18 09:09:48 +0000423 # are we using the chunked-style of transfer encoding?
424 tr_enc = self.msg.getheader('transfer-encoding')
Jeremy Hyltond229b3a2002-09-03 19:24:24 +0000425 if tr_enc and tr_enc.lower() == "chunked":
Greg Steindd6eefb2000-07-18 09:09:48 +0000426 self.chunked = 1
427 self.chunk_left = None
428 else:
429 self.chunked = 0
Greg Stein5e0fa402000-06-26 08:28:01 +0000430
Greg Steindd6eefb2000-07-18 09:09:48 +0000431 # will the connection close at the end of the response?
Jeremy Hylton22b3a492002-11-13 17:27:43 +0000432 self.will_close = self._check_close()
Greg Stein5e0fa402000-06-26 08:28:01 +0000433
Greg Steindd6eefb2000-07-18 09:09:48 +0000434 # do we have a Content-Length?
435 # NOTE: RFC 2616, S4.4, #3 says we ignore this if tr_enc is "chunked"
436 length = self.msg.getheader('content-length')
437 if length and not self.chunked:
Jeremy Hylton30a81812000-09-14 20:34:27 +0000438 try:
439 self.length = int(length)
440 except ValueError:
441 self.length = None
Greg Steindd6eefb2000-07-18 09:09:48 +0000442 else:
443 self.length = None
Greg Stein5e0fa402000-06-26 08:28:01 +0000444
Greg Steindd6eefb2000-07-18 09:09:48 +0000445 # does the body have a fixed length? (of zero)
Martin v. Löwis39a31782004-09-18 09:03:49 +0000446 if (status == NO_CONTENT or status == NOT_MODIFIED or
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000447 100 <= status < 200 or # 1xx codes
448 self._method == 'HEAD'):
Greg Steindd6eefb2000-07-18 09:09:48 +0000449 self.length = 0
Greg Stein5e0fa402000-06-26 08:28:01 +0000450
Greg Steindd6eefb2000-07-18 09:09:48 +0000451 # if the connection remains open, and we aren't using chunked, and
452 # a content-length was not provided, then assume that the connection
453 # WILL close.
454 if not self.will_close and \
455 not self.chunked and \
456 self.length is None:
457 self.will_close = 1
Greg Stein5e0fa402000-06-26 08:28:01 +0000458
Jeremy Hylton22b3a492002-11-13 17:27:43 +0000459 def _check_close(self):
Jeremy Hylton2c178252004-08-07 16:28:14 +0000460 conn = self.msg.getheader('connection')
Jeremy Hylton22b3a492002-11-13 17:27:43 +0000461 if self.version == 11:
462 # An HTTP/1.1 proxy is assumed to stay open unless
463 # explicitly closed.
464 conn = self.msg.getheader('connection')
Raymond Hettingerbac788a2004-05-04 09:21:43 +0000465 if conn and "close" in conn.lower():
Jeremy Hylton22b3a492002-11-13 17:27:43 +0000466 return True
467 return False
468
Jeremy Hylton2c178252004-08-07 16:28:14 +0000469 # Some HTTP/1.0 implementations have support for persistent
470 # connections, using rules different than HTTP/1.1.
Jeremy Hylton22b3a492002-11-13 17:27:43 +0000471
472 # For older HTTP, Keep-Alive indiciates persistent connection.
473 if self.msg.getheader('keep-alive'):
474 return False
Tim Peters77c06fb2002-11-24 02:35:35 +0000475
Jeremy Hylton2c178252004-08-07 16:28:14 +0000476 # At least Akamai returns a "Connection: Keep-Alive" header,
477 # which was supposed to be sent by the client.
478 if conn and "keep-alive" in conn.lower():
479 return False
480
Jeremy Hylton22b3a492002-11-13 17:27:43 +0000481 # Proxy-Connection is a netscape hack.
482 pconn = self.msg.getheader('proxy-connection')
Raymond Hettingerbac788a2004-05-04 09:21:43 +0000483 if pconn and "keep-alive" in pconn.lower():
Jeremy Hylton22b3a492002-11-13 17:27:43 +0000484 return False
485
486 # otherwise, assume it will close
487 return True
488
Greg Steindd6eefb2000-07-18 09:09:48 +0000489 def close(self):
490 if self.fp:
491 self.fp.close()
492 self.fp = None
Greg Stein5e0fa402000-06-26 08:28:01 +0000493
Greg Steindd6eefb2000-07-18 09:09:48 +0000494 def isclosed(self):
495 # NOTE: it is possible that we will not ever call self.close(). This
496 # case occurs when will_close is TRUE, length is None, and we
497 # read up to the last byte, but NOT past it.
498 #
499 # IMPLIES: if will_close is FALSE, then self.close() will ALWAYS be
500 # called, meaning self.isclosed() is meaningful.
501 return self.fp is None
502
Jeremy Hylton2c178252004-08-07 16:28:14 +0000503 # XXX It would be nice to have readline and __iter__ for this, too.
504
Greg Steindd6eefb2000-07-18 09:09:48 +0000505 def read(self, amt=None):
506 if self.fp is None:
507 return ''
508
509 if self.chunked:
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000510 return self._read_chunked(amt)
Tim Peters230a60c2002-11-09 05:08:07 +0000511
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000512 if amt is None:
Greg Steindd6eefb2000-07-18 09:09:48 +0000513 # unbounded read
Jeremy Hyltondef9d2a2004-11-07 16:13:49 +0000514 if self.length is None:
Greg Steindd6eefb2000-07-18 09:09:48 +0000515 s = self.fp.read()
516 else:
517 s = self._safe_read(self.length)
Jeremy Hyltondef9d2a2004-11-07 16:13:49 +0000518 self.length = 0
Tim Peters07e99cb2001-01-14 23:47:14 +0000519 self.close() # we read everything
Greg Steindd6eefb2000-07-18 09:09:48 +0000520 return s
521
522 if self.length is not None:
523 if amt > self.length:
524 # clip the read to the "end of response"
525 amt = self.length
Greg Steindd6eefb2000-07-18 09:09:48 +0000526
527 # we do not use _safe_read() here because this may be a .will_close
528 # connection, and the user is reading more bytes than will be provided
529 # (for example, reading in 1k chunks)
530 s = self.fp.read(amt)
Jeremy Hyltondef9d2a2004-11-07 16:13:49 +0000531 if self.length is not None:
532 self.length -= len(s)
Greg Steindd6eefb2000-07-18 09:09:48 +0000533
Greg Steindd6eefb2000-07-18 09:09:48 +0000534 return s
535
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000536 def _read_chunked(self, amt):
537 assert self.chunked != _UNKNOWN
538 chunk_left = self.chunk_left
539 value = ''
540
541 # XXX This accumulates chunks by repeated string concatenation,
542 # which is not efficient as the number or size of chunks gets big.
Raymond Hettingerb2e0b922003-02-26 22:45:18 +0000543 while True:
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000544 if chunk_left is None:
545 line = self.fp.readline()
546 i = line.find(';')
547 if i >= 0:
548 line = line[:i] # strip chunk-extensions
549 chunk_left = int(line, 16)
550 if chunk_left == 0:
551 break
552 if amt is None:
553 value += self._safe_read(chunk_left)
554 elif amt < chunk_left:
555 value += self._safe_read(amt)
556 self.chunk_left = chunk_left - amt
557 return value
558 elif amt == chunk_left:
559 value += self._safe_read(amt)
560 self._safe_read(2) # toss the CRLF at the end of the chunk
561 self.chunk_left = None
562 return value
563 else:
564 value += self._safe_read(chunk_left)
565 amt -= chunk_left
566
567 # we read the whole chunk, get another
568 self._safe_read(2) # toss the CRLF at the end of the chunk
569 chunk_left = None
570
571 # read and discard trailer up to the CRLF terminator
572 ### note: we shouldn't have any trailers!
Raymond Hettingerb2e0b922003-02-26 22:45:18 +0000573 while True:
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000574 line = self.fp.readline()
575 if line == '\r\n':
576 break
577
578 # we read everything; close the "file"
Jeremy Hyltond4c472c2002-09-03 20:49:06 +0000579 self.close()
580
581 return value
Tim Peters230a60c2002-11-09 05:08:07 +0000582
Greg Steindd6eefb2000-07-18 09:09:48 +0000583 def _safe_read(self, amt):
584 """Read the number of bytes requested, compensating for partial reads.
585
586 Normally, we have a blocking socket, but a read() can be interrupted
587 by a signal (resulting in a partial read).
588
589 Note that we cannot distinguish between EOF and an interrupt when zero
590 bytes have been read. IncompleteRead() will be raised in this
591 situation.
592
593 This function should be used when <amt> bytes "should" be present for
594 reading. If the bytes are truly not available (due to EOF), then the
595 IncompleteRead exception can be used to detect the problem.
596 """
Georg Brandl80ba8e82005-09-29 20:16:07 +0000597 s = []
Greg Steindd6eefb2000-07-18 09:09:48 +0000598 while amt > 0:
Georg Brandl80ba8e82005-09-29 20:16:07 +0000599 chunk = self.fp.read(min(amt, MAXAMOUNT))
Greg Steindd6eefb2000-07-18 09:09:48 +0000600 if not chunk:
601 raise IncompleteRead(s)
Georg Brandl80ba8e82005-09-29 20:16:07 +0000602 s.append(chunk)
Raymond Hettingerb2e0b922003-02-26 22:45:18 +0000603 amt -= len(chunk)
Georg Brandl80ba8e82005-09-29 20:16:07 +0000604 return ''.join(s)
Greg Steindd6eefb2000-07-18 09:09:48 +0000605
606 def getheader(self, name, default=None):
607 if self.msg is None:
608 raise ResponseNotReady()
609 return self.msg.getheader(name, default)
Greg Stein5e0fa402000-06-26 08:28:01 +0000610
Martin v. Löwisdeacce22004-08-18 12:46:26 +0000611 def getheaders(self):
612 """Return list of (header, value) tuples."""
613 if self.msg is None:
614 raise ResponseNotReady()
615 return self.msg.items()
616
Greg Stein5e0fa402000-06-26 08:28:01 +0000617
618class HTTPConnection:
619
Greg Steindd6eefb2000-07-18 09:09:48 +0000620 _http_vsn = 11
621 _http_vsn_str = 'HTTP/1.1'
Greg Stein5e0fa402000-06-26 08:28:01 +0000622
Greg Steindd6eefb2000-07-18 09:09:48 +0000623 response_class = HTTPResponse
624 default_port = HTTP_PORT
625 auto_open = 1
Jeremy Hylton30f86742000-09-18 22:50:38 +0000626 debuglevel = 0
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000627 strict = 0
Greg Stein5e0fa402000-06-26 08:28:01 +0000628
Facundo Batista07c78be2007-03-23 18:54:07 +0000629 def __init__(self, host, port=None, strict=None, timeout=None):
630 self.timeout = timeout
Greg Steindd6eefb2000-07-18 09:09:48 +0000631 self.sock = None
Jeremy Hylton8531b1b2002-07-16 21:21:11 +0000632 self._buffer = []
Greg Steindd6eefb2000-07-18 09:09:48 +0000633 self.__response = None
634 self.__state = _CS_IDLE
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000635 self._method = None
Tim Petersc411dba2002-07-16 21:35:23 +0000636
Greg Steindd6eefb2000-07-18 09:09:48 +0000637 self._set_hostport(host, port)
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000638 if strict is not None:
639 self.strict = strict
Greg Stein5e0fa402000-06-26 08:28:01 +0000640
Greg Steindd6eefb2000-07-18 09:09:48 +0000641 def _set_hostport(self, host, port):
642 if port is None:
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000643 i = host.rfind(':')
Skip Montanarocae14d22004-09-14 17:55:21 +0000644 j = host.rfind(']') # ipv6 addresses have [...]
645 if i > j:
Skip Montanaro9d389972002-03-24 16:53:50 +0000646 try:
647 port = int(host[i+1:])
648 except ValueError:
Jeremy Hyltonfbd79942002-07-02 20:19:08 +0000649 raise InvalidURL("nonnumeric port: '%s'" % host[i+1:])
Greg Steindd6eefb2000-07-18 09:09:48 +0000650 host = host[:i]
651 else:
652 port = self.default_port
Raymond Hettinger4d037912004-10-14 15:23:38 +0000653 if host and host[0] == '[' and host[-1] == ']':
Brett Cannon0a1af4a2004-09-15 23:26:23 +0000654 host = host[1:-1]
Greg Steindd6eefb2000-07-18 09:09:48 +0000655 self.host = host
656 self.port = port
Greg Stein5e0fa402000-06-26 08:28:01 +0000657
Jeremy Hylton30f86742000-09-18 22:50:38 +0000658 def set_debuglevel(self, level):
659 self.debuglevel = level
660
Greg Steindd6eefb2000-07-18 09:09:48 +0000661 def connect(self):
662 """Connect to the host and port specified in __init__."""
Georg Brandlf03facf2007-03-26 20:28:28 +0000663 self.sock = socket.create_connection((self.host,self.port),
664 self.timeout)
Greg Stein5e0fa402000-06-26 08:28:01 +0000665
Greg Steindd6eefb2000-07-18 09:09:48 +0000666 def close(self):
667 """Close the connection to the HTTP server."""
668 if self.sock:
Tim Peters07e99cb2001-01-14 23:47:14 +0000669 self.sock.close() # close it manually... there may be other refs
Greg Steindd6eefb2000-07-18 09:09:48 +0000670 self.sock = None
671 if self.__response:
672 self.__response.close()
673 self.__response = None
674 self.__state = _CS_IDLE
Greg Stein5e0fa402000-06-26 08:28:01 +0000675
Greg Steindd6eefb2000-07-18 09:09:48 +0000676 def send(self, str):
677 """Send `str' to the server."""
678 if self.sock is None:
679 if self.auto_open:
680 self.connect()
681 else:
682 raise NotConnected()
Greg Stein5e0fa402000-06-26 08:28:01 +0000683
Jeremy Hyltone3252ec2002-07-16 21:41:43 +0000684 # send the data to the server. if we get a broken pipe, then close
Greg Steindd6eefb2000-07-18 09:09:48 +0000685 # the socket. we want to reconnect when somebody tries to send again.
686 #
687 # NOTE: we DO propagate the error, though, because we cannot simply
688 # ignore the error... the caller will know if they can retry.
Jeremy Hylton30f86742000-09-18 22:50:38 +0000689 if self.debuglevel > 0:
690 print "send:", repr(str)
Greg Steindd6eefb2000-07-18 09:09:48 +0000691 try:
Martin v. Löwis040a9272006-11-12 10:32:47 +0000692 blocksize=8192
693 if hasattr(str,'read') :
694 if self.debuglevel > 0: print "sendIng a read()able"
695 data=str.read(blocksize)
696 while data:
697 self.sock.sendall(data)
698 data=str.read(blocksize)
699 else:
700 self.sock.sendall(str)
Greg Steindd6eefb2000-07-18 09:09:48 +0000701 except socket.error, v:
Tim Peters07e99cb2001-01-14 23:47:14 +0000702 if v[0] == 32: # Broken pipe
Greg Steindd6eefb2000-07-18 09:09:48 +0000703 self.close()
704 raise
Greg Stein5e0fa402000-06-26 08:28:01 +0000705
Jeremy Hylton8531b1b2002-07-16 21:21:11 +0000706 def _output(self, s):
707 """Add a line of output to the current request buffer.
Tim Peters469cdad2002-08-08 20:19:19 +0000708
Jeremy Hyltone3252ec2002-07-16 21:41:43 +0000709 Assumes that the line does *not* end with \\r\\n.
Jeremy Hylton8531b1b2002-07-16 21:21:11 +0000710 """
711 self._buffer.append(s)
712
713 def _send_output(self):
714 """Send the currently buffered request and clear the buffer.
715
Jeremy Hyltone3252ec2002-07-16 21:41:43 +0000716 Appends an extra \\r\\n to the buffer.
Jeremy Hylton8531b1b2002-07-16 21:21:11 +0000717 """
718 self._buffer.extend(("", ""))
719 msg = "\r\n".join(self._buffer)
720 del self._buffer[:]
721 self.send(msg)
722
Martin v. Löwisaf7dc8d2003-11-19 19:51:55 +0000723 def putrequest(self, method, url, skip_host=0, skip_accept_encoding=0):
Greg Steindd6eefb2000-07-18 09:09:48 +0000724 """Send a request to the server.
Greg Stein5e0fa402000-06-26 08:28:01 +0000725
Greg Steindd6eefb2000-07-18 09:09:48 +0000726 `method' specifies an HTTP request method, e.g. 'GET'.
727 `url' specifies the object being requested, e.g. '/index.html'.
Martin v. Löwisaf7dc8d2003-11-19 19:51:55 +0000728 `skip_host' if True does not add automatically a 'Host:' header
729 `skip_accept_encoding' if True does not add automatically an
730 'Accept-Encoding:' header
Greg Steindd6eefb2000-07-18 09:09:48 +0000731 """
Greg Stein5e0fa402000-06-26 08:28:01 +0000732
Greg Stein616a58d2003-06-24 06:35:19 +0000733 # if a prior response has been completed, then forget about it.
Greg Steindd6eefb2000-07-18 09:09:48 +0000734 if self.__response and self.__response.isclosed():
735 self.__response = None
Greg Stein5e0fa402000-06-26 08:28:01 +0000736
Tim Peters58eb11c2004-01-18 20:29:55 +0000737
Greg Steindd6eefb2000-07-18 09:09:48 +0000738 # in certain cases, we cannot issue another request on this connection.
739 # this occurs when:
740 # 1) we are in the process of sending a request. (_CS_REQ_STARTED)
741 # 2) a response to a previous request has signalled that it is going
742 # to close the connection upon completion.
743 # 3) the headers for the previous response have not been read, thus
744 # we cannot determine whether point (2) is true. (_CS_REQ_SENT)
745 #
746 # if there is no prior response, then we can request at will.
747 #
748 # if point (2) is true, then we will have passed the socket to the
749 # response (effectively meaning, "there is no prior response"), and
750 # will open a new one when a new request is made.
751 #
752 # Note: if a prior response exists, then we *can* start a new request.
753 # We are not allowed to begin fetching the response to this new
754 # request, however, until that prior response is complete.
755 #
756 if self.__state == _CS_IDLE:
757 self.__state = _CS_REQ_STARTED
758 else:
759 raise CannotSendRequest()
Greg Stein5e0fa402000-06-26 08:28:01 +0000760
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000761 # Save the method we use, we need it later in the response phase
762 self._method = method
Greg Steindd6eefb2000-07-18 09:09:48 +0000763 if not url:
764 url = '/'
Jeremy Hylton8531b1b2002-07-16 21:21:11 +0000765 str = '%s %s %s' % (method, url, self._http_vsn_str)
Greg Stein5e0fa402000-06-26 08:28:01 +0000766
Jeremy Hylton8531b1b2002-07-16 21:21:11 +0000767 self._output(str)
Greg Stein5e0fa402000-06-26 08:28:01 +0000768
Greg Steindd6eefb2000-07-18 09:09:48 +0000769 if self._http_vsn == 11:
770 # Issue some standard headers for better HTTP/1.1 compliance
Greg Stein5e0fa402000-06-26 08:28:01 +0000771
Jeremy Hylton3921ff62002-03-09 06:07:23 +0000772 if not skip_host:
773 # this header is issued *only* for HTTP/1.1
774 # connections. more specifically, this means it is
775 # only issued when the client uses the new
776 # HTTPConnection() class. backwards-compat clients
777 # will be using HTTP/1.0 and those clients may be
778 # issuing this header themselves. we should NOT issue
779 # it twice; some web servers (such as Apache) barf
780 # when they see two Host: headers
Guido van Rossumf6922aa2001-01-14 21:03:01 +0000781
Jeremy Hylton3921ff62002-03-09 06:07:23 +0000782 # If we need a non-standard port,include it in the
783 # header. If the request is going through a proxy,
784 # but the host of the actual URL, not the host of the
785 # proxy.
Jeremy Hylton8acf1e02002-03-08 19:35:51 +0000786
Jeremy Hylton3921ff62002-03-09 06:07:23 +0000787 netloc = ''
788 if url.startswith('http'):
789 nil, netloc, nil, nil, nil = urlsplit(url)
790
791 if netloc:
Georg Brandla2ac2ef2006-05-03 18:03:22 +0000792 try:
793 netloc_enc = netloc.encode("ascii")
794 except UnicodeEncodeError:
795 netloc_enc = netloc.encode("idna")
796 self.putheader('Host', netloc_enc)
Jeremy Hylton3921ff62002-03-09 06:07:23 +0000797 else:
Georg Brandla2ac2ef2006-05-03 18:03:22 +0000798 try:
799 host_enc = self.host.encode("ascii")
800 except UnicodeEncodeError:
801 host_enc = self.host.encode("idna")
802 if self.port == HTTP_PORT:
803 self.putheader('Host', host_enc)
804 else:
805 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
Greg Steindd6eefb2000-07-18 09:09:48 +0000830 def putheader(self, header, value):
831 """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
Jeremy Hylton8531b1b2002-07-16 21:21:11 +0000838 str = '%s: %s' % (header, value)
839 self._output(str)
Greg Stein5e0fa402000-06-26 08:28:01 +0000840
Greg Steindd6eefb2000-07-18 09:09:48 +0000841 def endheaders(self):
842 """Indicate that the last header line has been sent to the server."""
Greg Stein5e0fa402000-06-26 08:28:01 +0000843
Greg Steindd6eefb2000-07-18 09:09:48 +0000844 if self.__state == _CS_REQ_STARTED:
845 self.__state = _CS_REQ_SENT
846 else:
847 raise CannotSendHeader()
Greg Stein5e0fa402000-06-26 08:28:01 +0000848
Jeremy Hylton8531b1b2002-07-16 21:21:11 +0000849 self._send_output()
Greg Stein5e0fa402000-06-26 08:28:01 +0000850
Greg Steindd6eefb2000-07-18 09:09:48 +0000851 def request(self, method, url, body=None, headers={}):
852 """Send a complete request to the server."""
Greg Stein5e0fa402000-06-26 08:28:01 +0000853
Greg Steindd6eefb2000-07-18 09:09:48 +0000854 try:
855 self._send_request(method, url, body, headers)
856 except socket.error, v:
857 # trap 'Broken pipe' if we're allowed to automatically reconnect
858 if v[0] != 32 or not self.auto_open:
859 raise
860 # try one more time
861 self._send_request(method, url, body, headers)
Greg Stein5e0fa402000-06-26 08:28:01 +0000862
Greg Steindd6eefb2000-07-18 09:09:48 +0000863 def _send_request(self, method, url, body, headers):
Jeremy Hylton2c178252004-08-07 16:28:14 +0000864 # honour explicitly requested Host: and Accept-Encoding headers
865 header_names = dict.fromkeys([k.lower() for k in headers])
866 skips = {}
867 if 'host' in header_names:
868 skips['skip_host'] = 1
869 if 'accept-encoding' in header_names:
870 skips['skip_accept_encoding'] = 1
Greg Stein5e0fa402000-06-26 08:28:01 +0000871
Jeremy Hylton2c178252004-08-07 16:28:14 +0000872 self.putrequest(method, url, **skips)
873
874 if body and ('content-length' not in header_names):
Martin v. Löwis040a9272006-11-12 10:32:47 +0000875 thelen=None
876 try:
877 thelen=str(len(body))
878 except TypeError, te:
879 # If this is a file-like object, try to
880 # fstat its file descriptor
881 import os
882 try:
883 thelen = str(os.fstat(body.fileno()).st_size)
884 except (AttributeError, OSError):
885 # Don't send a length if this failed
886 if self.debuglevel > 0: print "Cannot stat!!"
Tim Petersf733abb2007-01-30 03:03:46 +0000887
Martin v. Löwis040a9272006-11-12 10:32:47 +0000888 if thelen is not None:
889 self.putheader('Content-Length',thelen)
Raymond Hettingerb2e0b922003-02-26 22:45:18 +0000890 for hdr, value in headers.iteritems():
Greg Steindd6eefb2000-07-18 09:09:48 +0000891 self.putheader(hdr, value)
892 self.endheaders()
Greg Stein5e0fa402000-06-26 08:28:01 +0000893
Greg Steindd6eefb2000-07-18 09:09:48 +0000894 if body:
895 self.send(body)
Greg Stein5e0fa402000-06-26 08:28:01 +0000896
Greg Steindd6eefb2000-07-18 09:09:48 +0000897 def getresponse(self):
898 "Get the response from the server."
Greg Stein5e0fa402000-06-26 08:28:01 +0000899
Greg Stein616a58d2003-06-24 06:35:19 +0000900 # if a prior response has been completed, then forget about it.
Greg Steindd6eefb2000-07-18 09:09:48 +0000901 if self.__response and self.__response.isclosed():
902 self.__response = None
Greg Stein5e0fa402000-06-26 08:28:01 +0000903
Greg Steindd6eefb2000-07-18 09:09:48 +0000904 #
905 # if a prior response exists, then it must be completed (otherwise, we
906 # cannot read this response's header to determine the connection-close
907 # behavior)
908 #
909 # note: if a prior response existed, but was connection-close, then the
910 # socket and response were made independent of this HTTPConnection
911 # object since a new request requires that we open a whole new
912 # connection
913 #
914 # this means the prior response had one of two states:
915 # 1) will_close: this connection was reset and the prior socket and
916 # response operate independently
917 # 2) persistent: the response was retained and we await its
918 # isclosed() status to become true.
919 #
920 if self.__state != _CS_REQ_SENT or self.__response:
921 raise ResponseNotReady()
Greg Stein5e0fa402000-06-26 08:28:01 +0000922
Jeremy Hylton30f86742000-09-18 22:50:38 +0000923 if self.debuglevel > 0:
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000924 response = self.response_class(self.sock, self.debuglevel,
Tim Petersc2659cf2003-05-12 20:19:37 +0000925 strict=self.strict,
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000926 method=self._method)
Jeremy Hylton30f86742000-09-18 22:50:38 +0000927 else:
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000928 response = self.response_class(self.sock, strict=self.strict,
929 method=self._method)
Greg Stein5e0fa402000-06-26 08:28:01 +0000930
Jeremy Hylton39c03802002-07-12 14:04:09 +0000931 response.begin()
Jeremy Hyltonbe4fcf12002-06-28 22:38:01 +0000932 assert response.will_close != _UNKNOWN
Greg Steindd6eefb2000-07-18 09:09:48 +0000933 self.__state = _CS_IDLE
Greg Stein5e0fa402000-06-26 08:28:01 +0000934
Greg Steindd6eefb2000-07-18 09:09:48 +0000935 if response.will_close:
Martin v. Löwis0af33882007-03-23 13:27:15 +0000936 # this effectively passes the connection to the response
937 self.close()
Greg Steindd6eefb2000-07-18 09:09:48 +0000938 else:
939 # remember this, so we can tell when it is complete
940 self.__response = response
Greg Stein5e0fa402000-06-26 08:28:01 +0000941
Greg Steindd6eefb2000-07-18 09:09:48 +0000942 return response
Greg Stein5e0fa402000-06-26 08:28:01 +0000943
Greg Stein5e0fa402000-06-26 08:28:01 +0000944
Jeremy Hylton29b8d5a2000-08-01 17:33:32 +0000945class HTTP:
Greg Steindd6eefb2000-07-18 09:09:48 +0000946 "Compatibility class with httplib.py from 1.5."
Greg Stein5e0fa402000-06-26 08:28:01 +0000947
Greg Steindd6eefb2000-07-18 09:09:48 +0000948 _http_vsn = 10
949 _http_vsn_str = 'HTTP/1.0'
Greg Stein5e0fa402000-06-26 08:28:01 +0000950
Greg Steindd6eefb2000-07-18 09:09:48 +0000951 debuglevel = 0
Greg Stein5e0fa402000-06-26 08:28:01 +0000952
Jeremy Hylton29b8d5a2000-08-01 17:33:32 +0000953 _connection_class = HTTPConnection
954
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000955 def __init__(self, host='', port=None, strict=None):
Greg Steindd6eefb2000-07-18 09:09:48 +0000956 "Provide a default host, since the superclass requires one."
Greg Stein5e0fa402000-06-26 08:28:01 +0000957
Greg Steindd6eefb2000-07-18 09:09:48 +0000958 # some joker passed 0 explicitly, meaning default port
959 if port == 0:
960 port = None
Greg Stein5e0fa402000-06-26 08:28:01 +0000961
Greg Steindd6eefb2000-07-18 09:09:48 +0000962 # Note that we may pass an empty string as the host; this will throw
963 # an error when we attempt to connect. Presumably, the client code
964 # will call connect before then, with a proper host.
Jeremy Hyltond46aa372002-07-06 18:48:07 +0000965 self._setup(self._connection_class(host, port, strict))
Greg Stein5e0fa402000-06-26 08:28:01 +0000966
Greg Stein81937a42001-08-18 09:20:23 +0000967 def _setup(self, conn):
968 self._conn = conn
969
970 # set up delegation to flesh out interface
971 self.send = conn.send
972 self.putrequest = conn.putrequest
973 self.endheaders = conn.endheaders
974 self.set_debuglevel = conn.set_debuglevel
975
976 conn._http_vsn = self._http_vsn
977 conn._http_vsn_str = self._http_vsn_str
Greg Stein5e0fa402000-06-26 08:28:01 +0000978
Greg Steindd6eefb2000-07-18 09:09:48 +0000979 self.file = None
Greg Stein5e0fa402000-06-26 08:28:01 +0000980
Greg Steindd6eefb2000-07-18 09:09:48 +0000981 def connect(self, host=None, port=None):
982 "Accept arguments to set the host/port, since the superclass doesn't."
Greg Stein5e0fa402000-06-26 08:28:01 +0000983
Greg Steindd6eefb2000-07-18 09:09:48 +0000984 if host is not None:
Jeremy Hylton29b8d5a2000-08-01 17:33:32 +0000985 self._conn._set_hostport(host, port)
986 self._conn.connect()
Greg Stein5e0fa402000-06-26 08:28:01 +0000987
Greg Steindd6eefb2000-07-18 09:09:48 +0000988 def getfile(self):
989 "Provide a getfile, since the superclass' does not use this concept."
990 return self.file
Greg Stein5e0fa402000-06-26 08:28:01 +0000991
Greg Steindd6eefb2000-07-18 09:09:48 +0000992 def putheader(self, header, *values):
993 "The superclass allows only one value argument."
Guido van Rossum34735a62000-12-15 15:09:42 +0000994 self._conn.putheader(header, '\r\n\t'.join(values))
Greg Stein5e0fa402000-06-26 08:28:01 +0000995
Greg Steindd6eefb2000-07-18 09:09:48 +0000996 def getreply(self):
997 """Compat definition since superclass does not define it.
Greg Stein5e0fa402000-06-26 08:28:01 +0000998
Greg Steindd6eefb2000-07-18 09:09:48 +0000999 Returns a tuple consisting of:
1000 - server status code (e.g. '200' if all goes well)
1001 - server "reason" corresponding to status code
1002 - any RFC822 headers in the response from the server
1003 """
1004 try:
Jeremy Hylton29b8d5a2000-08-01 17:33:32 +00001005 response = self._conn.getresponse()
Greg Steindd6eefb2000-07-18 09:09:48 +00001006 except BadStatusLine, e:
1007 ### hmm. if getresponse() ever closes the socket on a bad request,
1008 ### then we are going to have problems with self.sock
Greg Stein5e0fa402000-06-26 08:28:01 +00001009
Greg Steindd6eefb2000-07-18 09:09:48 +00001010 ### should we keep this behavior? do people use it?
1011 # keep the socket open (as a file), and return it
Jeremy Hylton29b8d5a2000-08-01 17:33:32 +00001012 self.file = self._conn.sock.makefile('rb', 0)
Greg Stein5e0fa402000-06-26 08:28:01 +00001013
Greg Steindd6eefb2000-07-18 09:09:48 +00001014 # close our socket -- we want to restart after any protocol error
1015 self.close()
Greg Stein5e0fa402000-06-26 08:28:01 +00001016
Greg Steindd6eefb2000-07-18 09:09:48 +00001017 self.headers = None
1018 return -1, e.line, None
Greg Stein5e0fa402000-06-26 08:28:01 +00001019
Greg Steindd6eefb2000-07-18 09:09:48 +00001020 self.headers = response.msg
1021 self.file = response.fp
1022 return response.status, response.reason, response.msg
Greg Stein5e0fa402000-06-26 08:28:01 +00001023
Greg Steindd6eefb2000-07-18 09:09:48 +00001024 def close(self):
Jeremy Hylton29b8d5a2000-08-01 17:33:32 +00001025 self._conn.close()
Greg Stein5e0fa402000-06-26 08:28:01 +00001026
Greg Steindd6eefb2000-07-18 09:09:48 +00001027 # note that self.file == response.fp, which gets closed by the
1028 # superclass. just clear the object ref here.
1029 ### hmm. messy. if status==-1, then self.file is owned by us.
1030 ### well... we aren't explicitly closing, but losing this ref will
1031 ### do it
1032 self.file = None
Greg Stein5e0fa402000-06-26 08:28:01 +00001033
Bill Janssen426ea0a2007-08-29 22:35:05 +00001034try:
1035 import ssl
1036except ImportError:
1037 pass
1038else:
1039 class HTTPSConnection(HTTPConnection):
1040 "This class allows communication via SSL."
1041
1042 default_port = HTTPS_PORT
1043
1044 def __init__(self, host, port=None, key_file=None, cert_file=None,
1045 strict=None, timeout=None):
1046 HTTPConnection.__init__(self, host, port, strict, timeout)
1047 self.key_file = key_file
1048 self.cert_file = cert_file
1049
1050 def connect(self):
1051 "Connect to a host on a given (SSL) port."
1052
1053 sock = socket.create_connection((self.host, self.port), self.timeout)
Bill Janssen98d19da2007-09-10 21:51:02 +00001054 self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file)
Bill Janssen426ea0a2007-08-29 22:35:05 +00001055
Thomas Woutersa6900e82007-08-30 21:54:39 +00001056 __all__.append("HTTPSConnection")
Bill Janssen426ea0a2007-08-29 22:35:05 +00001057
Jeremy Hylton29b8d5a2000-08-01 17:33:32 +00001058 class HTTPS(HTTP):
1059 """Compatibility with 1.5 httplib interface
1060
1061 Python 1.5.2 did not have an HTTPS class, but it defined an
1062 interface for sending http requests that is also useful for
Tim Peters5ceadc82001-01-13 19:16:21 +00001063 https.
Jeremy Hylton29b8d5a2000-08-01 17:33:32 +00001064 """
1065
Martin v. Löwisd7bf9742000-09-21 22:09:47 +00001066 _connection_class = HTTPSConnection
Tim Peters5ceadc82001-01-13 19:16:21 +00001067
Jeremy Hyltond46aa372002-07-06 18:48:07 +00001068 def __init__(self, host='', port=None, key_file=None, cert_file=None,
1069 strict=None):
Greg Stein81937a42001-08-18 09:20:23 +00001070 # provide a default host, pass the X509 cert info
1071
1072 # urf. compensate for bad input.
1073 if port == 0:
1074 port = None
Jeremy Hyltond46aa372002-07-06 18:48:07 +00001075 self._setup(self._connection_class(host, port, key_file,
1076 cert_file, strict))
Greg Stein81937a42001-08-18 09:20:23 +00001077
1078 # we never actually use these for anything, but we keep them
1079 # here for compatibility with post-1.5.2 CVS.
Jeremy Hyltond46aa372002-07-06 18:48:07 +00001080 self.key_file = key_file
1081 self.cert_file = cert_file
Greg Stein81937a42001-08-18 09:20:23 +00001082
Greg Stein5e0fa402000-06-26 08:28:01 +00001083
Bill Janssen426ea0a2007-08-29 22:35:05 +00001084 def FakeSocket (sock, sslobj):
Bill Janssenc4592642007-08-31 19:02:23 +00001085 warnings.warn("FakeSocket is deprecated, and won't be in 3.x. " +
Bill Janssen98d19da2007-09-10 21:51:02 +00001086 "Use the result of ssl.wrap_socket() directly instead.",
Bill Janssenc4592642007-08-31 19:02:23 +00001087 DeprecationWarning, stacklevel=2)
Bill Janssen426ea0a2007-08-29 22:35:05 +00001088 return sslobj
1089
1090
Greg Stein5e0fa402000-06-26 08:28:01 +00001091class HTTPException(Exception):
Jeremy Hylton12f4f352002-07-06 18:55:01 +00001092 # Subclasses that define an __init__ must call Exception.__init__
1093 # or define self.args. Otherwise, str() will fail.
Greg Steindd6eefb2000-07-18 09:09:48 +00001094 pass
Greg Stein5e0fa402000-06-26 08:28:01 +00001095
1096class NotConnected(HTTPException):
Greg Steindd6eefb2000-07-18 09:09:48 +00001097 pass
Greg Stein5e0fa402000-06-26 08:28:01 +00001098
Skip Montanaro9d389972002-03-24 16:53:50 +00001099class InvalidURL(HTTPException):
1100 pass
1101
Greg Stein5e0fa402000-06-26 08:28:01 +00001102class UnknownProtocol(HTTPException):
Greg Steindd6eefb2000-07-18 09:09:48 +00001103 def __init__(self, version):
Jeremy Hylton12f4f352002-07-06 18:55:01 +00001104 self.args = version,
Greg Steindd6eefb2000-07-18 09:09:48 +00001105 self.version = version
Greg Stein5e0fa402000-06-26 08:28:01 +00001106
1107class UnknownTransferEncoding(HTTPException):
Greg Steindd6eefb2000-07-18 09:09:48 +00001108 pass
Greg Stein5e0fa402000-06-26 08:28:01 +00001109
Greg Stein5e0fa402000-06-26 08:28:01 +00001110class UnimplementedFileMode(HTTPException):
Greg Steindd6eefb2000-07-18 09:09:48 +00001111 pass
Greg Stein5e0fa402000-06-26 08:28:01 +00001112
1113class IncompleteRead(HTTPException):
Greg Steindd6eefb2000-07-18 09:09:48 +00001114 def __init__(self, partial):
Jeremy Hylton12f4f352002-07-06 18:55:01 +00001115 self.args = partial,
Greg Steindd6eefb2000-07-18 09:09:48 +00001116 self.partial = partial
Greg Stein5e0fa402000-06-26 08:28:01 +00001117
1118class ImproperConnectionState(HTTPException):
Greg Steindd6eefb2000-07-18 09:09:48 +00001119 pass
Greg Stein5e0fa402000-06-26 08:28:01 +00001120
1121class CannotSendRequest(ImproperConnectionState):
Greg Steindd6eefb2000-07-18 09:09:48 +00001122 pass
Greg Stein5e0fa402000-06-26 08:28:01 +00001123
1124class CannotSendHeader(ImproperConnectionState):
Greg Steindd6eefb2000-07-18 09:09:48 +00001125 pass
Greg Stein5e0fa402000-06-26 08:28:01 +00001126
1127class ResponseNotReady(ImproperConnectionState):
Greg Steindd6eefb2000-07-18 09:09:48 +00001128 pass
Greg Stein5e0fa402000-06-26 08:28:01 +00001129
1130class BadStatusLine(HTTPException):
Greg Steindd6eefb2000-07-18 09:09:48 +00001131 def __init__(self, line):
Jeremy Hylton12f4f352002-07-06 18:55:01 +00001132 self.args = line,
Greg Steindd6eefb2000-07-18 09:09:48 +00001133 self.line = line
Greg Stein5e0fa402000-06-26 08:28:01 +00001134
1135# for backwards compatibility
1136error = HTTPException
1137
Jeremy Hyltond46aa372002-07-06 18:48:07 +00001138class LineAndFileWrapper:
1139 """A limited file-like object for HTTP/0.9 responses."""
1140
1141 # The status-line parsing code calls readline(), which normally
1142 # get the HTTP status line. For a 0.9 response, however, this is
1143 # actually the first line of the body! Clients need to get a
1144 # readable file object that contains that line.
1145
1146 def __init__(self, line, file):
1147 self._line = line
1148 self._file = file
1149 self._line_consumed = 0
1150 self._line_offset = 0
1151 self._line_left = len(line)
1152
1153 def __getattr__(self, attr):
1154 return getattr(self._file, attr)
1155
1156 def _done(self):
1157 # called when the last byte is read from the line. After the
1158 # call, all read methods are delegated to the underlying file
Skip Montanaro74b9a7a2003-02-25 17:48:15 +00001159 # object.
Jeremy Hyltond46aa372002-07-06 18:48:07 +00001160 self._line_consumed = 1
1161 self.read = self._file.read
1162 self.readline = self._file.readline
1163 self.readlines = self._file.readlines
1164
1165 def read(self, amt=None):
Hye-Shik Chang39aef792004-06-05 13:30:56 +00001166 if self._line_consumed:
1167 return self._file.read(amt)
1168 assert self._line_left
Jeremy Hyltond46aa372002-07-06 18:48:07 +00001169 if amt is None or amt > self._line_left:
1170 s = self._line[self._line_offset:]
1171 self._done()
1172 if amt is None:
1173 return s + self._file.read()
1174 else:
Tim Petersc411dba2002-07-16 21:35:23 +00001175 return s + self._file.read(amt - len(s))
Jeremy Hyltond46aa372002-07-06 18:48:07 +00001176 else:
1177 assert amt <= self._line_left
1178 i = self._line_offset
1179 j = i + amt
1180 s = self._line[i:j]
1181 self._line_offset = j
1182 self._line_left -= amt
1183 if self._line_left == 0:
1184 self._done()
1185 return s
Tim Petersc411dba2002-07-16 21:35:23 +00001186
Jeremy Hyltond46aa372002-07-06 18:48:07 +00001187 def readline(self):
Hye-Shik Chang39aef792004-06-05 13:30:56 +00001188 if self._line_consumed:
1189 return self._file.readline()
1190 assert self._line_left
Jeremy Hyltond46aa372002-07-06 18:48:07 +00001191 s = self._line[self._line_offset:]
1192 self._done()
1193 return s
1194
1195 def readlines(self, size=None):
Hye-Shik Chang39aef792004-06-05 13:30:56 +00001196 if self._line_consumed:
1197 return self._file.readlines(size)
1198 assert self._line_left
Jeremy Hyltond46aa372002-07-06 18:48:07 +00001199 L = [self._line[self._line_offset:]]
1200 self._done()
1201 if size is None:
1202 return L + self._file.readlines()
1203 else:
1204 return L + self._file.readlines(size)
Greg Stein5e0fa402000-06-26 08:28:01 +00001205
Guido van Rossum23acc951994-02-21 16:36:04 +00001206def test():
Guido van Rossum41999c11997-12-09 00:12:23 +00001207 """Test this module.
1208
Jeremy Hylton29d27ac2002-07-09 21:22:36 +00001209 A hodge podge of tests collected here, because they have too many
1210 external dependencies for the regular test suite.
Guido van Rossum41999c11997-12-09 00:12:23 +00001211 """
Greg Stein5e0fa402000-06-26 08:28:01 +00001212
Guido van Rossum41999c11997-12-09 00:12:23 +00001213 import sys
1214 import getopt
1215 opts, args = getopt.getopt(sys.argv[1:], 'd')
1216 dl = 0
1217 for o, a in opts:
1218 if o == '-d': dl = dl + 1
1219 host = 'www.python.org'
1220 selector = '/'
1221 if args[0:]: host = args[0]
1222 if args[1:]: selector = args[1]
1223 h = HTTP()
1224 h.set_debuglevel(dl)
1225 h.connect(host)
1226 h.putrequest('GET', selector)
1227 h.endheaders()
Greg Stein5e0fa402000-06-26 08:28:01 +00001228 status, reason, headers = h.getreply()
1229 print 'status =', status
1230 print 'reason =', reason
Jeremy Hylton29d27ac2002-07-09 21:22:36 +00001231 print "read", len(h.getfile().read())
Guido van Rossum41999c11997-12-09 00:12:23 +00001232 print
1233 if headers:
Guido van Rossum34735a62000-12-15 15:09:42 +00001234 for header in headers.headers: print header.strip()
Guido van Rossum41999c11997-12-09 00:12:23 +00001235 print
Greg Stein5e0fa402000-06-26 08:28:01 +00001236
Jeremy Hylton8acf1e02002-03-08 19:35:51 +00001237 # minimal test that code to extract host from url works
1238 class HTTP11(HTTP):
1239 _http_vsn = 11
1240 _http_vsn_str = 'HTTP/1.1'
1241
1242 h = HTTP11('www.python.org')
1243 h.putrequest('GET', 'http://www.python.org/~jeremy/')
1244 h.endheaders()
1245 h.getreply()
1246 h.close()
1247
Bill Janssen426ea0a2007-08-29 22:35:05 +00001248 try:
1249 import ssl
1250 except ImportError:
1251 pass
1252 else:
Tim Petersc411dba2002-07-16 21:35:23 +00001253
Jeremy Hylton29d27ac2002-07-09 21:22:36 +00001254 for host, selector in (('sourceforge.net', '/projects/python'),
Jeremy Hylton29d27ac2002-07-09 21:22:36 +00001255 ):
1256 print "https://%s%s" % (host, selector)
1257 hs = HTTPS()
Jeremy Hylton8531b1b2002-07-16 21:21:11 +00001258 hs.set_debuglevel(dl)
Jeremy Hylton29d27ac2002-07-09 21:22:36 +00001259 hs.connect(host)
1260 hs.putrequest('GET', selector)
1261 hs.endheaders()
1262 status, reason, headers = hs.getreply()
1263 print 'status =', status
1264 print 'reason =', reason
1265 print "read", len(hs.getfile().read())
1266 print
1267 if headers:
1268 for header in headers.headers: print header.strip()
1269 print
Guido van Rossum23acc951994-02-21 16:36:04 +00001270
Guido van Rossum23acc951994-02-21 16:36:04 +00001271if __name__ == '__main__':
Guido van Rossum41999c11997-12-09 00:12:23 +00001272 test()