Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 1 | """HTTP/1.1 client library |
Guido van Rossum | 41999c1 | 1997-12-09 00:12:23 +0000 | [diff] [blame] | 2 | |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 3 | <intro stuff goes here> |
| 4 | <other stuff, too> |
Guido van Rossum | 41999c1 | 1997-12-09 00:12:23 +0000 | [diff] [blame] | 5 | |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 6 | HTTPConnection go through a number of "states", which defines when a client |
| 7 | may legally make another request or fetch the response for a particular |
| 8 | request. This diagram details these state transitions: |
Guido van Rossum | 41999c1 | 1997-12-09 00:12:23 +0000 | [diff] [blame] | 9 | |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 10 | (null) |
| 11 | | |
| 12 | | HTTPConnection() |
| 13 | v |
| 14 | Idle |
| 15 | | |
| 16 | | putrequest() |
| 17 | v |
| 18 | Request-started |
| 19 | | |
| 20 | | ( putheader() )* endheaders() |
| 21 | v |
| 22 | Request-sent |
| 23 | | |
| 24 | | response = getresponse() |
| 25 | v |
| 26 | Unread-response [Response-headers-read] |
| 27 | |\____________________ |
Tim Peters | 5ceadc8 | 2001-01-13 19:16:21 +0000 | [diff] [blame] | 28 | | | |
| 29 | | response.read() | putrequest() |
| 30 | v v |
| 31 | Idle Req-started-unread-response |
| 32 | ______/| |
| 33 | / | |
| 34 | response.read() | | ( putheader() )* endheaders() |
| 35 | v v |
| 36 | Request-started Req-sent-unread-response |
| 37 | | |
| 38 | | response.read() |
| 39 | v |
| 40 | Request-sent |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 41 | |
| 42 | This diagram presents the following rules: |
| 43 | -- a second request may not be started until {response-headers-read} |
| 44 | -- a response [object] cannot be retrieved until {request-sent} |
| 45 | -- there is no differentiation between an unread response body and a |
| 46 | partially read response body |
| 47 | |
| 48 | Note: this enforcement is applied by the HTTPConnection class. The |
| 49 | HTTPResponse class does not enforce this state machine, which |
| 50 | implies sophisticated clients may accelerate the request/response |
| 51 | pipeline. Caution should be taken, though: accelerating the states |
| 52 | beyond the above pattern may imply knowledge of the server's |
| 53 | connection-close behavior for certain requests. For example, it |
| 54 | is impossible to tell whether the server will close the connection |
| 55 | UNTIL the response headers have been read; this means that further |
| 56 | requests cannot be placed into the pipeline until it is known that |
| 57 | the server will NOT be closing the connection. |
| 58 | |
| 59 | Logical State __state __response |
| 60 | ------------- ------- ---------- |
| 61 | Idle _CS_IDLE None |
| 62 | Request-started _CS_REQ_STARTED None |
| 63 | Request-sent _CS_REQ_SENT None |
| 64 | Unread-response _CS_IDLE <response_class> |
| 65 | Req-started-unread-response _CS_REQ_STARTED <response_class> |
| 66 | Req-sent-unread-response _CS_REQ_SENT <response_class> |
Guido van Rossum | 41999c1 | 1997-12-09 00:12:23 +0000 | [diff] [blame] | 67 | """ |
Guido van Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 68 | |
Guido van Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 69 | import socket |
Guido van Rossum | 65ab98c | 1995-08-07 20:13:02 +0000 | [diff] [blame] | 70 | import mimetools |
Guido van Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 71 | |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 72 | try: |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 73 | from cStringIO import StringIO |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 74 | except ImportError: |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 75 | from StringIO import StringIO |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 76 | |
Skip Montanaro | 951a884 | 2001-06-01 16:25:38 +0000 | [diff] [blame] | 77 | __all__ = ["HTTP", "HTTPResponse", "HTTPConnection", "HTTPSConnection", |
| 78 | "HTTPException", "NotConnected", "UnknownProtocol", |
| 79 | "UnknownTransferEncoding", "IllegalKeywordArgument", |
| 80 | "UnimplementedFileMode", "IncompleteRead", |
| 81 | "ImproperConnectionState", "CannotSendRequest", "CannotSendHeader", |
| 82 | "ResponseNotReady", "BadStatusLine", "error"] |
Skip Montanaro | 2dd4276 | 2001-01-23 15:35:05 +0000 | [diff] [blame] | 83 | |
Guido van Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 84 | HTTP_PORT = 80 |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 85 | HTTPS_PORT = 443 |
| 86 | |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 87 | _UNKNOWN = 'UNKNOWN' |
| 88 | |
| 89 | # connection states |
| 90 | _CS_IDLE = 'Idle' |
| 91 | _CS_REQ_STARTED = 'Request-started' |
| 92 | _CS_REQ_SENT = 'Request-sent' |
| 93 | |
| 94 | |
| 95 | class HTTPResponse: |
Jeremy Hylton | 30f8674 | 2000-09-18 22:50:38 +0000 | [diff] [blame] | 96 | def __init__(self, sock, debuglevel=0): |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 97 | self.fp = sock.makefile('rb', 0) |
Jeremy Hylton | 30f8674 | 2000-09-18 22:50:38 +0000 | [diff] [blame] | 98 | self.debuglevel = debuglevel |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 99 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 100 | self.msg = None |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 101 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 102 | # from the Status-Line of the response |
Tim Peters | 07e99cb | 2001-01-14 23:47:14 +0000 | [diff] [blame] | 103 | self.version = _UNKNOWN # HTTP-Version |
| 104 | self.status = _UNKNOWN # Status-Code |
| 105 | self.reason = _UNKNOWN # Reason-Phrase |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 106 | |
Tim Peters | 07e99cb | 2001-01-14 23:47:14 +0000 | [diff] [blame] | 107 | self.chunked = _UNKNOWN # is "chunked" being used? |
| 108 | self.chunk_left = _UNKNOWN # bytes left to read in current chunk |
| 109 | self.length = _UNKNOWN # number of bytes left in response |
| 110 | self.will_close = _UNKNOWN # conn will close at end of response |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 111 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 112 | def begin(self): |
| 113 | if self.msg is not None: |
| 114 | # we've already started reading the response |
| 115 | return |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 116 | |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 117 | line = self.fp.readline() |
Jeremy Hylton | 30f8674 | 2000-09-18 22:50:38 +0000 | [diff] [blame] | 118 | if self.debuglevel > 0: |
| 119 | print "reply:", repr(line) |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 120 | try: |
Guido van Rossum | 34735a6 | 2000-12-15 15:09:42 +0000 | [diff] [blame] | 121 | [version, status, reason] = line.split(None, 2) |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 122 | except ValueError: |
| 123 | try: |
Guido van Rossum | 34735a6 | 2000-12-15 15:09:42 +0000 | [diff] [blame] | 124 | [version, status] = line.split(None, 1) |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 125 | reason = "" |
| 126 | except ValueError: |
Jeremy Hylton | 110941a | 2000-10-12 19:58:36 +0000 | [diff] [blame] | 127 | version = "HTTP/0.9" |
| 128 | status = "200" |
| 129 | reason = "" |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 130 | if version[:5] != 'HTTP/': |
| 131 | self.close() |
| 132 | raise BadStatusLine(line) |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 133 | |
Jeremy Hylton | 23d4047 | 2001-04-13 14:57:08 +0000 | [diff] [blame] | 134 | # The status code is a three-digit number |
| 135 | try: |
| 136 | self.status = status = int(status) |
| 137 | if status < 100 or status > 999: |
| 138 | raise BadStatusLine(line) |
| 139 | except ValueError: |
| 140 | raise BadStatusLine(line) |
Guido van Rossum | 34735a6 | 2000-12-15 15:09:42 +0000 | [diff] [blame] | 141 | self.reason = reason.strip() |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 142 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 143 | if version == 'HTTP/1.0': |
| 144 | self.version = 10 |
Jeremy Hylton | 110941a | 2000-10-12 19:58:36 +0000 | [diff] [blame] | 145 | elif version.startswith('HTTP/1.'): |
Tim Peters | 07e99cb | 2001-01-14 23:47:14 +0000 | [diff] [blame] | 146 | self.version = 11 # use HTTP/1.1 code for HTTP/1.x where x>=1 |
Jeremy Hylton | 110941a | 2000-10-12 19:58:36 +0000 | [diff] [blame] | 147 | elif version == 'HTTP/0.9': |
| 148 | self.version = 9 |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 149 | else: |
| 150 | raise UnknownProtocol(version) |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 151 | |
Jeremy Hylton | 110941a | 2000-10-12 19:58:36 +0000 | [diff] [blame] | 152 | if self.version == 9: |
| 153 | self.msg = mimetools.Message(StringIO()) |
| 154 | return |
| 155 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 156 | self.msg = mimetools.Message(self.fp, 0) |
Jeremy Hylton | 30f8674 | 2000-09-18 22:50:38 +0000 | [diff] [blame] | 157 | if self.debuglevel > 0: |
| 158 | for hdr in self.msg.headers: |
| 159 | print "header:", hdr, |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 160 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 161 | # don't let the msg keep an fp |
| 162 | self.msg.fp = None |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 163 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 164 | # are we using the chunked-style of transfer encoding? |
| 165 | tr_enc = self.msg.getheader('transfer-encoding') |
| 166 | if tr_enc: |
Guido van Rossum | 34735a6 | 2000-12-15 15:09:42 +0000 | [diff] [blame] | 167 | if tr_enc.lower() != 'chunked': |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 168 | raise UnknownTransferEncoding() |
| 169 | self.chunked = 1 |
| 170 | self.chunk_left = None |
| 171 | else: |
| 172 | self.chunked = 0 |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 173 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 174 | # will the connection close at the end of the response? |
| 175 | conn = self.msg.getheader('connection') |
| 176 | if conn: |
Guido van Rossum | 34735a6 | 2000-12-15 15:09:42 +0000 | [diff] [blame] | 177 | conn = conn.lower() |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 178 | # a "Connection: close" will always close the connection. if we |
| 179 | # don't see that and this is not HTTP/1.1, then the connection will |
| 180 | # close unless we see a Keep-Alive header. |
Guido van Rossum | 34735a6 | 2000-12-15 15:09:42 +0000 | [diff] [blame] | 181 | self.will_close = conn.find('close') != -1 or \ |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 182 | ( self.version != 11 and \ |
| 183 | not self.msg.getheader('keep-alive') ) |
| 184 | else: |
| 185 | # for HTTP/1.1, the connection will always remain open |
| 186 | # otherwise, it will remain open IFF we see a Keep-Alive header |
| 187 | self.will_close = self.version != 11 and \ |
| 188 | not self.msg.getheader('keep-alive') |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 189 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 190 | # do we have a Content-Length? |
| 191 | # NOTE: RFC 2616, S4.4, #3 says we ignore this if tr_enc is "chunked" |
| 192 | length = self.msg.getheader('content-length') |
| 193 | if length and not self.chunked: |
Jeremy Hylton | 30a8181 | 2000-09-14 20:34:27 +0000 | [diff] [blame] | 194 | try: |
| 195 | self.length = int(length) |
| 196 | except ValueError: |
| 197 | self.length = None |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 198 | else: |
| 199 | self.length = None |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 200 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 201 | # does the body have a fixed length? (of zero) |
Tim Peters | 07e99cb | 2001-01-14 23:47:14 +0000 | [diff] [blame] | 202 | if (status == 204 or # No Content |
| 203 | status == 304 or # Not Modified |
| 204 | 100 <= status < 200): # 1xx codes |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 205 | self.length = 0 |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 206 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 207 | # if the connection remains open, and we aren't using chunked, and |
| 208 | # a content-length was not provided, then assume that the connection |
| 209 | # WILL close. |
| 210 | if not self.will_close and \ |
| 211 | not self.chunked and \ |
| 212 | self.length is None: |
| 213 | self.will_close = 1 |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 214 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 215 | def close(self): |
| 216 | if self.fp: |
| 217 | self.fp.close() |
| 218 | self.fp = None |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 219 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 220 | def isclosed(self): |
| 221 | # NOTE: it is possible that we will not ever call self.close(). This |
| 222 | # case occurs when will_close is TRUE, length is None, and we |
| 223 | # read up to the last byte, but NOT past it. |
| 224 | # |
| 225 | # IMPLIES: if will_close is FALSE, then self.close() will ALWAYS be |
| 226 | # called, meaning self.isclosed() is meaningful. |
| 227 | return self.fp is None |
| 228 | |
| 229 | def read(self, amt=None): |
| 230 | if self.fp is None: |
| 231 | return '' |
| 232 | |
| 233 | if self.chunked: |
| 234 | chunk_left = self.chunk_left |
| 235 | value = '' |
| 236 | while 1: |
| 237 | if chunk_left is None: |
| 238 | line = self.fp.readline() |
Guido van Rossum | 34735a6 | 2000-12-15 15:09:42 +0000 | [diff] [blame] | 239 | i = line.find(';') |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 240 | if i >= 0: |
Tim Peters | 07e99cb | 2001-01-14 23:47:14 +0000 | [diff] [blame] | 241 | line = line[:i] # strip chunk-extensions |
Guido van Rossum | 34735a6 | 2000-12-15 15:09:42 +0000 | [diff] [blame] | 242 | chunk_left = int(line, 16) |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 243 | if chunk_left == 0: |
| 244 | break |
| 245 | if amt is None: |
| 246 | value = value + self._safe_read(chunk_left) |
| 247 | elif amt < chunk_left: |
| 248 | value = value + self._safe_read(amt) |
| 249 | self.chunk_left = chunk_left - amt |
| 250 | return value |
| 251 | elif amt == chunk_left: |
| 252 | value = value + self._safe_read(amt) |
Tim Peters | 07e99cb | 2001-01-14 23:47:14 +0000 | [diff] [blame] | 253 | self._safe_read(2) # toss the CRLF at the end of the chunk |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 254 | self.chunk_left = None |
| 255 | return value |
| 256 | else: |
| 257 | value = value + self._safe_read(chunk_left) |
| 258 | amt = amt - chunk_left |
| 259 | |
| 260 | # we read the whole chunk, get another |
Tim Peters | 07e99cb | 2001-01-14 23:47:14 +0000 | [diff] [blame] | 261 | self._safe_read(2) # toss the CRLF at the end of the chunk |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 262 | chunk_left = None |
| 263 | |
| 264 | # read and discard trailer up to the CRLF terminator |
| 265 | ### note: we shouldn't have any trailers! |
| 266 | while 1: |
| 267 | line = self.fp.readline() |
| 268 | if line == '\r\n': |
| 269 | break |
| 270 | |
| 271 | # we read everything; close the "file" |
| 272 | self.close() |
| 273 | |
| 274 | return value |
| 275 | |
| 276 | elif amt is None: |
| 277 | # unbounded read |
| 278 | if self.will_close: |
| 279 | s = self.fp.read() |
| 280 | else: |
| 281 | s = self._safe_read(self.length) |
Tim Peters | 07e99cb | 2001-01-14 23:47:14 +0000 | [diff] [blame] | 282 | self.close() # we read everything |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 283 | return s |
| 284 | |
| 285 | if self.length is not None: |
| 286 | if amt > self.length: |
| 287 | # clip the read to the "end of response" |
| 288 | amt = self.length |
| 289 | self.length = self.length - amt |
| 290 | |
| 291 | # we do not use _safe_read() here because this may be a .will_close |
| 292 | # connection, and the user is reading more bytes than will be provided |
| 293 | # (for example, reading in 1k chunks) |
| 294 | s = self.fp.read(amt) |
| 295 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 296 | return s |
| 297 | |
| 298 | def _safe_read(self, amt): |
| 299 | """Read the number of bytes requested, compensating for partial reads. |
| 300 | |
| 301 | Normally, we have a blocking socket, but a read() can be interrupted |
| 302 | by a signal (resulting in a partial read). |
| 303 | |
| 304 | Note that we cannot distinguish between EOF and an interrupt when zero |
| 305 | bytes have been read. IncompleteRead() will be raised in this |
| 306 | situation. |
| 307 | |
| 308 | This function should be used when <amt> bytes "should" be present for |
| 309 | reading. If the bytes are truly not available (due to EOF), then the |
| 310 | IncompleteRead exception can be used to detect the problem. |
| 311 | """ |
| 312 | s = '' |
| 313 | while amt > 0: |
| 314 | chunk = self.fp.read(amt) |
| 315 | if not chunk: |
| 316 | raise IncompleteRead(s) |
| 317 | s = s + chunk |
| 318 | amt = amt - len(chunk) |
| 319 | return s |
| 320 | |
| 321 | def getheader(self, name, default=None): |
| 322 | if self.msg is None: |
| 323 | raise ResponseNotReady() |
| 324 | return self.msg.getheader(name, default) |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 325 | |
| 326 | |
| 327 | class HTTPConnection: |
| 328 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 329 | _http_vsn = 11 |
| 330 | _http_vsn_str = 'HTTP/1.1' |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 331 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 332 | response_class = HTTPResponse |
| 333 | default_port = HTTP_PORT |
| 334 | auto_open = 1 |
Jeremy Hylton | 30f8674 | 2000-09-18 22:50:38 +0000 | [diff] [blame] | 335 | debuglevel = 0 |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 336 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 337 | def __init__(self, host, port=None): |
| 338 | self.sock = None |
| 339 | self.__response = None |
| 340 | self.__state = _CS_IDLE |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 341 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 342 | self._set_hostport(host, port) |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 343 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 344 | def _set_hostport(self, host, port): |
| 345 | if port is None: |
Guido van Rossum | 34735a6 | 2000-12-15 15:09:42 +0000 | [diff] [blame] | 346 | i = host.find(':') |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 347 | if i >= 0: |
Guido van Rossum | fd97a91 | 2001-01-15 14:34:20 +0000 | [diff] [blame] | 348 | port = int(host[i+1:]) |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 349 | host = host[:i] |
| 350 | else: |
| 351 | port = self.default_port |
| 352 | self.host = host |
| 353 | self.port = port |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 354 | |
Jeremy Hylton | 30f8674 | 2000-09-18 22:50:38 +0000 | [diff] [blame] | 355 | def set_debuglevel(self, level): |
| 356 | self.debuglevel = level |
| 357 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 358 | def connect(self): |
| 359 | """Connect to the host and port specified in __init__.""" |
Martin v. Löwis | 2ad2569 | 2001-07-31 08:40:21 +0000 | [diff] [blame^] | 360 | msg = "getaddrinfo returns an empty list" |
Martin v. Löwis | 4eb5940 | 2001-07-26 13:37:33 +0000 | [diff] [blame] | 361 | for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM): |
| 362 | af, socktype, proto, canonname, sa = res |
| 363 | try: |
| 364 | self.sock = socket.socket(af, socktype, proto) |
| 365 | if self.debuglevel > 0: |
| 366 | print "connect: (%s, %s)" % (self.host, self.port) |
| 367 | self.sock.connect(sa) |
| 368 | except socket.error, msg: |
| 369 | if self.debuglevel > 0: |
| 370 | print 'connect fail:', (self.host, self.port) |
| 371 | self.sock.close() |
| 372 | self.sock = None |
| 373 | continue |
| 374 | break |
| 375 | if not self.sock: |
| 376 | raise socket.error, msg |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 377 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 378 | def close(self): |
| 379 | """Close the connection to the HTTP server.""" |
| 380 | if self.sock: |
Tim Peters | 07e99cb | 2001-01-14 23:47:14 +0000 | [diff] [blame] | 381 | self.sock.close() # close it manually... there may be other refs |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 382 | self.sock = None |
| 383 | if self.__response: |
| 384 | self.__response.close() |
| 385 | self.__response = None |
| 386 | self.__state = _CS_IDLE |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 387 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 388 | def send(self, str): |
| 389 | """Send `str' to the server.""" |
| 390 | if self.sock is None: |
| 391 | if self.auto_open: |
| 392 | self.connect() |
| 393 | else: |
| 394 | raise NotConnected() |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 395 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 396 | # send the data to the server. if we get a broken pipe, then close |
| 397 | # the socket. we want to reconnect when somebody tries to send again. |
| 398 | # |
| 399 | # NOTE: we DO propagate the error, though, because we cannot simply |
| 400 | # ignore the error... the caller will know if they can retry. |
Jeremy Hylton | 30f8674 | 2000-09-18 22:50:38 +0000 | [diff] [blame] | 401 | if self.debuglevel > 0: |
| 402 | print "send:", repr(str) |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 403 | try: |
| 404 | self.sock.send(str) |
| 405 | except socket.error, v: |
Tim Peters | 07e99cb | 2001-01-14 23:47:14 +0000 | [diff] [blame] | 406 | if v[0] == 32: # Broken pipe |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 407 | self.close() |
| 408 | raise |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 409 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 410 | def putrequest(self, method, url): |
| 411 | """Send a request to the server. |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 412 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 413 | `method' specifies an HTTP request method, e.g. 'GET'. |
| 414 | `url' specifies the object being requested, e.g. '/index.html'. |
| 415 | """ |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 416 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 417 | # check if a prior response has been completed |
| 418 | if self.__response and self.__response.isclosed(): |
| 419 | self.__response = None |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 420 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 421 | # |
| 422 | # in certain cases, we cannot issue another request on this connection. |
| 423 | # this occurs when: |
| 424 | # 1) we are in the process of sending a request. (_CS_REQ_STARTED) |
| 425 | # 2) a response to a previous request has signalled that it is going |
| 426 | # to close the connection upon completion. |
| 427 | # 3) the headers for the previous response have not been read, thus |
| 428 | # we cannot determine whether point (2) is true. (_CS_REQ_SENT) |
| 429 | # |
| 430 | # if there is no prior response, then we can request at will. |
| 431 | # |
| 432 | # if point (2) is true, then we will have passed the socket to the |
| 433 | # response (effectively meaning, "there is no prior response"), and |
| 434 | # will open a new one when a new request is made. |
| 435 | # |
| 436 | # Note: if a prior response exists, then we *can* start a new request. |
| 437 | # We are not allowed to begin fetching the response to this new |
| 438 | # request, however, until that prior response is complete. |
| 439 | # |
| 440 | if self.__state == _CS_IDLE: |
| 441 | self.__state = _CS_REQ_STARTED |
| 442 | else: |
| 443 | raise CannotSendRequest() |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 444 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 445 | if not url: |
| 446 | url = '/' |
| 447 | str = '%s %s %s\r\n' % (method, url, self._http_vsn_str) |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 448 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 449 | try: |
| 450 | self.send(str) |
| 451 | except socket.error, v: |
| 452 | # trap 'Broken pipe' if we're allowed to automatically reconnect |
| 453 | if v[0] != 32 or not self.auto_open: |
| 454 | raise |
| 455 | # try one more time (the socket was closed; this will reopen) |
| 456 | self.send(str) |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 457 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 458 | if self._http_vsn == 11: |
| 459 | # Issue some standard headers for better HTTP/1.1 compliance |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 460 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 461 | # this header is issued *only* for HTTP/1.1 connections. more |
| 462 | # specifically, this means it is only issued when the client uses |
| 463 | # the new HTTPConnection() class. backwards-compat clients will |
| 464 | # be using HTTP/1.0 and those clients may be issuing this header |
| 465 | # themselves. we should NOT issue it twice; some web servers (such |
| 466 | # as Apache) barf when they see two Host: headers |
Guido van Rossum | f6922aa | 2001-01-14 21:03:01 +0000 | [diff] [blame] | 467 | |
| 468 | # if we need a non-standard port,include it in the header |
| 469 | if self.port == HTTP_PORT: |
| 470 | self.putheader('Host', self.host) |
| 471 | else: |
| 472 | self.putheader('Host', "%s:%s" % (self.host, self.port)) |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 473 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 474 | # note: we are assuming that clients will not attempt to set these |
| 475 | # headers since *this* library must deal with the |
| 476 | # consequences. this also means that when the supporting |
| 477 | # libraries are updated to recognize other forms, then this |
| 478 | # code should be changed (removed or updated). |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 479 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 480 | # we only want a Content-Encoding of "identity" since we don't |
| 481 | # support encodings such as x-gzip or x-deflate. |
| 482 | self.putheader('Accept-Encoding', 'identity') |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 483 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 484 | # we can accept "chunked" Transfer-Encodings, but no others |
| 485 | # NOTE: no TE header implies *only* "chunked" |
| 486 | #self.putheader('TE', 'chunked') |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 487 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 488 | # if TE is supplied in the header, then it must appear in a |
| 489 | # Connection header. |
| 490 | #self.putheader('Connection', 'TE') |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 491 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 492 | else: |
| 493 | # For HTTP/1.0, the server will assume "not chunked" |
| 494 | pass |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 495 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 496 | def putheader(self, header, value): |
| 497 | """Send a request header line to the server. |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 498 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 499 | For example: h.putheader('Accept', 'text/html') |
| 500 | """ |
| 501 | if self.__state != _CS_REQ_STARTED: |
| 502 | raise CannotSendHeader() |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 503 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 504 | str = '%s: %s\r\n' % (header, value) |
| 505 | self.send(str) |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 506 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 507 | def endheaders(self): |
| 508 | """Indicate that the last header line has been sent to the server.""" |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 509 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 510 | if self.__state == _CS_REQ_STARTED: |
| 511 | self.__state = _CS_REQ_SENT |
| 512 | else: |
| 513 | raise CannotSendHeader() |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 514 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 515 | self.send('\r\n') |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 516 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 517 | def request(self, method, url, body=None, headers={}): |
| 518 | """Send a complete request to the server.""" |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 519 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 520 | try: |
| 521 | self._send_request(method, url, body, headers) |
| 522 | except socket.error, v: |
| 523 | # trap 'Broken pipe' if we're allowed to automatically reconnect |
| 524 | if v[0] != 32 or not self.auto_open: |
| 525 | raise |
| 526 | # try one more time |
| 527 | self._send_request(method, url, body, headers) |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 528 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 529 | def _send_request(self, method, url, body, headers): |
| 530 | self.putrequest(method, url) |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 531 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 532 | if body: |
| 533 | self.putheader('Content-Length', str(len(body))) |
| 534 | for hdr, value in headers.items(): |
| 535 | self.putheader(hdr, value) |
| 536 | self.endheaders() |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 537 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 538 | if body: |
| 539 | self.send(body) |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 540 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 541 | def getresponse(self): |
| 542 | "Get the response from the server." |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 543 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 544 | # check if a prior response has been completed |
| 545 | if self.__response and self.__response.isclosed(): |
| 546 | self.__response = None |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 547 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 548 | # |
| 549 | # if a prior response exists, then it must be completed (otherwise, we |
| 550 | # cannot read this response's header to determine the connection-close |
| 551 | # behavior) |
| 552 | # |
| 553 | # note: if a prior response existed, but was connection-close, then the |
| 554 | # socket and response were made independent of this HTTPConnection |
| 555 | # object since a new request requires that we open a whole new |
| 556 | # connection |
| 557 | # |
| 558 | # this means the prior response had one of two states: |
| 559 | # 1) will_close: this connection was reset and the prior socket and |
| 560 | # response operate independently |
| 561 | # 2) persistent: the response was retained and we await its |
| 562 | # isclosed() status to become true. |
| 563 | # |
| 564 | if self.__state != _CS_REQ_SENT or self.__response: |
| 565 | raise ResponseNotReady() |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 566 | |
Jeremy Hylton | 30f8674 | 2000-09-18 22:50:38 +0000 | [diff] [blame] | 567 | if self.debuglevel > 0: |
| 568 | response = self.response_class(self.sock, self.debuglevel) |
| 569 | else: |
| 570 | response = self.response_class(self.sock) |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 571 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 572 | response.begin() |
| 573 | self.__state = _CS_IDLE |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 574 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 575 | if response.will_close: |
| 576 | # this effectively passes the connection to the response |
| 577 | self.close() |
| 578 | else: |
| 579 | # remember this, so we can tell when it is complete |
| 580 | self.__response = response |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 581 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 582 | return response |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 583 | |
| 584 | |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 585 | class FakeSocket: |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 586 | def __init__(self, sock, ssl): |
| 587 | self.__sock = sock |
| 588 | self.__ssl = ssl |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 589 | |
Jeremy Hylton | 4d746fc | 2000-08-23 20:34:17 +0000 | [diff] [blame] | 590 | def makefile(self, mode, bufsize=None): |
| 591 | """Return a readable file-like object with data from socket. |
| 592 | |
| 593 | This method offers only partial support for the makefile |
| 594 | interface of a real socket. It only supports modes 'r' and |
| 595 | 'rb' and the bufsize argument is ignored. |
| 596 | |
Tim Peters | 5ceadc8 | 2001-01-13 19:16:21 +0000 | [diff] [blame] | 597 | The returned object contains *all* of the file data |
Jeremy Hylton | 4d746fc | 2000-08-23 20:34:17 +0000 | [diff] [blame] | 598 | """ |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 599 | if mode != 'r' and mode != 'rb': |
| 600 | raise UnimplementedFileMode() |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 601 | |
Jeremy Hylton | 42dd01a | 2001-02-01 23:35:20 +0000 | [diff] [blame] | 602 | msgbuf = [] |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 603 | while 1: |
| 604 | try: |
Jeremy Hylton | 42dd01a | 2001-02-01 23:35:20 +0000 | [diff] [blame] | 605 | buf = self.__ssl.read() |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 606 | except socket.sslerror, msg: |
| 607 | break |
Jeremy Hylton | 42dd01a | 2001-02-01 23:35:20 +0000 | [diff] [blame] | 608 | if buf == '': |
| 609 | break |
| 610 | msgbuf.append(buf) |
| 611 | return StringIO("".join(msgbuf)) |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 612 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 613 | def send(self, stuff, flags = 0): |
| 614 | return self.__ssl.write(stuff) |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 615 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 616 | def recv(self, len = 1024, flags = 0): |
| 617 | return self.__ssl.read(len) |
Guido van Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 618 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 619 | def __getattr__(self, attr): |
| 620 | return getattr(self.__sock, attr) |
Guido van Rossum | 09c8b6c | 1999-12-07 21:37:17 +0000 | [diff] [blame] | 621 | |
Guido van Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 622 | |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 623 | class HTTPSConnection(HTTPConnection): |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 624 | "This class allows communication via SSL." |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 625 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 626 | default_port = HTTPS_PORT |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 627 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 628 | def __init__(self, host, port=None, **x509): |
| 629 | keys = x509.keys() |
| 630 | try: |
| 631 | keys.remove('key_file') |
| 632 | except ValueError: |
| 633 | pass |
| 634 | try: |
| 635 | keys.remove('cert_file') |
| 636 | except ValueError: |
| 637 | pass |
| 638 | if keys: |
| 639 | raise IllegalKeywordArgument() |
| 640 | HTTPConnection.__init__(self, host, port) |
| 641 | self.key_file = x509.get('key_file') |
| 642 | self.cert_file = x509.get('cert_file') |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 643 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 644 | def connect(self): |
| 645 | "Connect to a host on a given (SSL) port." |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 646 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 647 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 648 | sock.connect((self.host, self.port)) |
Guido van Rossum | 0aee722 | 2000-12-11 20:32:20 +0000 | [diff] [blame] | 649 | realsock = sock |
| 650 | if hasattr(sock, "_sock"): |
| 651 | realsock = sock._sock |
| 652 | ssl = socket.ssl(realsock, self.key_file, self.cert_file) |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 653 | self.sock = FakeSocket(sock, ssl) |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 654 | |
| 655 | |
Jeremy Hylton | 29b8d5a | 2000-08-01 17:33:32 +0000 | [diff] [blame] | 656 | class HTTP: |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 657 | "Compatibility class with httplib.py from 1.5." |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 658 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 659 | _http_vsn = 10 |
| 660 | _http_vsn_str = 'HTTP/1.0' |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 661 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 662 | debuglevel = 0 |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 663 | |
Jeremy Hylton | 29b8d5a | 2000-08-01 17:33:32 +0000 | [diff] [blame] | 664 | _connection_class = HTTPConnection |
| 665 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 666 | def __init__(self, host='', port=None, **x509): |
| 667 | "Provide a default host, since the superclass requires one." |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 668 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 669 | # some joker passed 0 explicitly, meaning default port |
| 670 | if port == 0: |
| 671 | port = None |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 672 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 673 | # Note that we may pass an empty string as the host; this will throw |
| 674 | # an error when we attempt to connect. Presumably, the client code |
| 675 | # will call connect before then, with a proper host. |
Jeremy Hylton | 29b8d5a | 2000-08-01 17:33:32 +0000 | [diff] [blame] | 676 | self._conn = self._connection_class(host, port) |
| 677 | # set up delegation to flesh out interface |
| 678 | self.send = self._conn.send |
| 679 | self.putrequest = self._conn.putrequest |
| 680 | self.endheaders = self._conn.endheaders |
Jeremy Hylton | 4d746fc | 2000-08-23 20:34:17 +0000 | [diff] [blame] | 681 | self._conn._http_vsn = self._http_vsn |
| 682 | self._conn._http_vsn_str = self._http_vsn_str |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 683 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 684 | # we never actually use these for anything, but we keep them here for |
| 685 | # compatibility with post-1.5.2 CVS. |
| 686 | self.key_file = x509.get('key_file') |
| 687 | self.cert_file = x509.get('cert_file') |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 688 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 689 | self.file = None |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 690 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 691 | def connect(self, host=None, port=None): |
| 692 | "Accept arguments to set the host/port, since the superclass doesn't." |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 693 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 694 | if host is not None: |
Jeremy Hylton | 29b8d5a | 2000-08-01 17:33:32 +0000 | [diff] [blame] | 695 | self._conn._set_hostport(host, port) |
| 696 | self._conn.connect() |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 697 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 698 | def set_debuglevel(self, debuglevel): |
Jeremy Hylton | 30f8674 | 2000-09-18 22:50:38 +0000 | [diff] [blame] | 699 | self._conn.set_debuglevel(debuglevel) |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 700 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 701 | def getfile(self): |
| 702 | "Provide a getfile, since the superclass' does not use this concept." |
| 703 | return self.file |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 704 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 705 | def putheader(self, header, *values): |
| 706 | "The superclass allows only one value argument." |
Guido van Rossum | 34735a6 | 2000-12-15 15:09:42 +0000 | [diff] [blame] | 707 | self._conn.putheader(header, '\r\n\t'.join(values)) |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 708 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 709 | def getreply(self): |
| 710 | """Compat definition since superclass does not define it. |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 711 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 712 | Returns a tuple consisting of: |
| 713 | - server status code (e.g. '200' if all goes well) |
| 714 | - server "reason" corresponding to status code |
| 715 | - any RFC822 headers in the response from the server |
| 716 | """ |
| 717 | try: |
Jeremy Hylton | 29b8d5a | 2000-08-01 17:33:32 +0000 | [diff] [blame] | 718 | response = self._conn.getresponse() |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 719 | except BadStatusLine, e: |
| 720 | ### hmm. if getresponse() ever closes the socket on a bad request, |
| 721 | ### then we are going to have problems with self.sock |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 722 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 723 | ### should we keep this behavior? do people use it? |
| 724 | # keep the socket open (as a file), and return it |
Jeremy Hylton | 29b8d5a | 2000-08-01 17:33:32 +0000 | [diff] [blame] | 725 | self.file = self._conn.sock.makefile('rb', 0) |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 726 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 727 | # close our socket -- we want to restart after any protocol error |
| 728 | self.close() |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 729 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 730 | self.headers = None |
| 731 | return -1, e.line, None |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 732 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 733 | self.headers = response.msg |
| 734 | self.file = response.fp |
| 735 | return response.status, response.reason, response.msg |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 736 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 737 | def close(self): |
Jeremy Hylton | 29b8d5a | 2000-08-01 17:33:32 +0000 | [diff] [blame] | 738 | self._conn.close() |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 739 | |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 740 | # note that self.file == response.fp, which gets closed by the |
| 741 | # superclass. just clear the object ref here. |
| 742 | ### hmm. messy. if status==-1, then self.file is owned by us. |
| 743 | ### well... we aren't explicitly closing, but losing this ref will |
| 744 | ### do it |
| 745 | self.file = None |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 746 | |
Jeremy Hylton | 29b8d5a | 2000-08-01 17:33:32 +0000 | [diff] [blame] | 747 | if hasattr(socket, 'ssl'): |
| 748 | class HTTPS(HTTP): |
| 749 | """Compatibility with 1.5 httplib interface |
| 750 | |
| 751 | Python 1.5.2 did not have an HTTPS class, but it defined an |
| 752 | interface for sending http requests that is also useful for |
Tim Peters | 5ceadc8 | 2001-01-13 19:16:21 +0000 | [diff] [blame] | 753 | https. |
Jeremy Hylton | 29b8d5a | 2000-08-01 17:33:32 +0000 | [diff] [blame] | 754 | """ |
| 755 | |
Martin v. Löwis | d7bf974 | 2000-09-21 22:09:47 +0000 | [diff] [blame] | 756 | _connection_class = HTTPSConnection |
Tim Peters | 5ceadc8 | 2001-01-13 19:16:21 +0000 | [diff] [blame] | 757 | |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 758 | |
| 759 | class HTTPException(Exception): |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 760 | pass |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 761 | |
| 762 | class NotConnected(HTTPException): |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 763 | pass |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 764 | |
| 765 | class UnknownProtocol(HTTPException): |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 766 | def __init__(self, version): |
| 767 | self.version = version |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 768 | |
| 769 | class UnknownTransferEncoding(HTTPException): |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 770 | pass |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 771 | |
| 772 | class IllegalKeywordArgument(HTTPException): |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 773 | pass |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 774 | |
| 775 | class UnimplementedFileMode(HTTPException): |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 776 | pass |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 777 | |
| 778 | class IncompleteRead(HTTPException): |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 779 | def __init__(self, partial): |
| 780 | self.partial = partial |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 781 | |
| 782 | class ImproperConnectionState(HTTPException): |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 783 | pass |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 784 | |
| 785 | class CannotSendRequest(ImproperConnectionState): |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 786 | pass |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 787 | |
| 788 | class CannotSendHeader(ImproperConnectionState): |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 789 | pass |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 790 | |
| 791 | class ResponseNotReady(ImproperConnectionState): |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 792 | pass |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 793 | |
| 794 | class BadStatusLine(HTTPException): |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 795 | def __init__(self, line): |
| 796 | self.line = line |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 797 | |
| 798 | # for backwards compatibility |
| 799 | error = HTTPException |
| 800 | |
| 801 | |
| 802 | # |
| 803 | # snarfed from httplib.py for now... |
| 804 | # |
Guido van Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 805 | def test(): |
Guido van Rossum | 41999c1 | 1997-12-09 00:12:23 +0000 | [diff] [blame] | 806 | """Test this module. |
| 807 | |
| 808 | The test consists of retrieving and displaying the Python |
| 809 | home page, along with the error code and error string returned |
| 810 | by the www.python.org server. |
Guido van Rossum | 41999c1 | 1997-12-09 00:12:23 +0000 | [diff] [blame] | 811 | """ |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 812 | |
Guido van Rossum | 41999c1 | 1997-12-09 00:12:23 +0000 | [diff] [blame] | 813 | import sys |
| 814 | import getopt |
| 815 | opts, args = getopt.getopt(sys.argv[1:], 'd') |
| 816 | dl = 0 |
| 817 | for o, a in opts: |
| 818 | if o == '-d': dl = dl + 1 |
| 819 | host = 'www.python.org' |
| 820 | selector = '/' |
| 821 | if args[0:]: host = args[0] |
| 822 | if args[1:]: selector = args[1] |
| 823 | h = HTTP() |
| 824 | h.set_debuglevel(dl) |
| 825 | h.connect(host) |
| 826 | h.putrequest('GET', selector) |
| 827 | h.endheaders() |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 828 | status, reason, headers = h.getreply() |
| 829 | print 'status =', status |
| 830 | print 'reason =', reason |
Guido van Rossum | 41999c1 | 1997-12-09 00:12:23 +0000 | [diff] [blame] | 831 | print |
| 832 | if headers: |
Guido van Rossum | 34735a6 | 2000-12-15 15:09:42 +0000 | [diff] [blame] | 833 | for header in headers.headers: print header.strip() |
Guido van Rossum | 41999c1 | 1997-12-09 00:12:23 +0000 | [diff] [blame] | 834 | print |
| 835 | print h.getfile().read() |
Greg Stein | 5e0fa40 | 2000-06-26 08:28:01 +0000 | [diff] [blame] | 836 | |
| 837 | if hasattr(socket, 'ssl'): |
Jeremy Hylton | 29b8d5a | 2000-08-01 17:33:32 +0000 | [diff] [blame] | 838 | host = 'sourceforge.net' |
Jeremy Hylton | 42dd01a | 2001-02-01 23:35:20 +0000 | [diff] [blame] | 839 | selector = '/projects/python' |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 840 | hs = HTTPS() |
| 841 | hs.connect(host) |
| 842 | hs.putrequest('GET', selector) |
| 843 | hs.endheaders() |
| 844 | status, reason, headers = hs.getreply() |
| 845 | print 'status =', status |
| 846 | print 'reason =', reason |
| 847 | print |
| 848 | if headers: |
Guido van Rossum | 34735a6 | 2000-12-15 15:09:42 +0000 | [diff] [blame] | 849 | for header in headers.headers: print header.strip() |
Greg Stein | dd6eefb | 2000-07-18 09:09:48 +0000 | [diff] [blame] | 850 | print |
| 851 | print hs.getfile().read() |
Guido van Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 852 | |
Guido van Rossum | a0dfc7a | 1995-09-07 19:28:19 +0000 | [diff] [blame] | 853 | |
Guido van Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 854 | if __name__ == '__main__': |
Guido van Rossum | 41999c1 | 1997-12-09 00:12:23 +0000 | [diff] [blame] | 855 | test() |