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