| 1 |
r"""HTTP/1.1 client library |
| 2 |
|
| 3 |
<intro stuff goes here> |
| 4 |
<other stuff, too> |
| 5 |
|
| 6 |
HTTPConnection goes through a number of "states", which define when a client |
| 7 |
may legally make another request or fetch the response for a particular |
| 8 |
request. This diagram details these state transitions: |
| 9 |
|
| 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 |
|\____________________ |
| 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 |
| 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> |
| 67 |
""" |
| 68 |
|
| 69 |
from array import array |
| 70 |
import os |
| 71 |
import re |
| 72 |
import socket |
| 73 |
from sys import py3kwarning |
| 74 |
from urlparse import urlsplit |
| 75 |
import warnings |
| 76 |
with warnings.catch_warnings(): |
| 77 |
if py3kwarning: |
| 78 |
warnings.filterwarnings("ignore", ".*mimetools has been removed", |
| 79 |
DeprecationWarning) |
| 80 |
import mimetools |
| 81 |
|
| 82 |
try: |
| 83 |
from cStringIO import StringIO |
| 84 |
except ImportError: |
| 85 |
from StringIO import StringIO |
| 86 |
|
| 87 |
__all__ = ["HTTP", "HTTPResponse", "HTTPConnection", |
| 88 |
"HTTPException", "NotConnected", "UnknownProtocol", |
| 89 |
"UnknownTransferEncoding", "UnimplementedFileMode", |
| 90 |
"IncompleteRead", "InvalidURL", "ImproperConnectionState", |
| 91 |
"CannotSendRequest", "CannotSendHeader", "ResponseNotReady", |
| 92 |
"BadStatusLine", "error", "responses"] |
| 93 |
|
| 94 |
HTTP_PORT = 80 |
| 95 |
HTTPS_PORT = 443 |
| 96 |
|
| 97 |
_UNKNOWN = 'UNKNOWN' |
| 98 |
|
| 99 |
|
| 100 |
_CS_IDLE = 'Idle' |
| 101 |
_CS_REQ_STARTED = 'Request-started' |
| 102 |
_CS_REQ_SENT = 'Request-sent' |
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
CONTINUE = 100 |
| 107 |
SWITCHING_PROTOCOLS = 101 |
| 108 |
PROCESSING = 102 |
| 109 |
|
| 110 |
|
| 111 |
OK = 200 |
| 112 |
CREATED = 201 |
| 113 |
ACCEPTED = 202 |
| 114 |
NON_AUTHORITATIVE_INFORMATION = 203 |
| 115 |
NO_CONTENT = 204 |
| 116 |
RESET_CONTENT = 205 |
| 117 |
PARTIAL_CONTENT = 206 |
| 118 |
MULTI_STATUS = 207 |
| 119 |
IM_USED = 226 |
| 120 |
|
| 121 |
|
| 122 |
MULTIPLE_CHOICES = 300 |
| 123 |
MOVED_PERMANENTLY = 301 |
| 124 |
FOUND = 302 |
| 125 |
SEE_OTHER = 303 |
| 126 |
NOT_MODIFIED = 304 |
| 127 |
USE_PROXY = 305 |
| 128 |
TEMPORARY_REDIRECT = 307 |
| 129 |
|
| 130 |
|
| 131 |
BAD_REQUEST = 400 |
| 132 |
UNAUTHORIZED = 401 |
| 133 |
PAYMENT_REQUIRED = 402 |
| 134 |
FORBIDDEN = 403 |
| 135 |
NOT_FOUND = 404 |
| 136 |
METHOD_NOT_ALLOWED = 405 |
| 137 |
NOT_ACCEPTABLE = 406 |
| 138 |
PROXY_AUTHENTICATION_REQUIRED = 407 |
| 139 |
REQUEST_TIMEOUT = 408 |
| 140 |
CONFLICT = 409 |
| 141 |
GONE = 410 |
| 142 |
LENGTH_REQUIRED = 411 |
| 143 |
PRECONDITION_FAILED = 412 |
| 144 |
REQUEST_ENTITY_TOO_LARGE = 413 |
| 145 |
REQUEST_URI_TOO_LONG = 414 |
| 146 |
UNSUPPORTED_MEDIA_TYPE = 415 |
| 147 |
REQUESTED_RANGE_NOT_SATISFIABLE = 416 |
| 148 |
EXPECTATION_FAILED = 417 |
| 149 |
UNPROCESSABLE_ENTITY = 422 |
| 150 |
LOCKED = 423 |
| 151 |
FAILED_DEPENDENCY = 424 |
| 152 |
UPGRADE_REQUIRED = 426 |
| 153 |
|
| 154 |
|
| 155 |
INTERNAL_SERVER_ERROR = 500 |
| 156 |
NOT_IMPLEMENTED = 501 |
| 157 |
BAD_GATEWAY = 502 |
| 158 |
SERVICE_UNAVAILABLE = 503 |
| 159 |
GATEWAY_TIMEOUT = 504 |
| 160 |
HTTP_VERSION_NOT_SUPPORTED = 505 |
| 161 |
INSUFFICIENT_STORAGE = 507 |
| 162 |
NOT_EXTENDED = 510 |
| 163 |
|
| 164 |
|
| 165 |
responses = { |
| 166 |
100: 'Continue', |
| 167 |
101: 'Switching Protocols', |
| 168 |
|
| 169 |
200: 'OK', |
| 170 |
201: 'Created', |
| 171 |
202: 'Accepted', |
| 172 |
203: 'Non-Authoritative Information', |
| 173 |
204: 'No Content', |
| 174 |
205: 'Reset Content', |
| 175 |
206: 'Partial Content', |
| 176 |
|
| 177 |
300: 'Multiple Choices', |
| 178 |
301: 'Moved Permanently', |
| 179 |
302: 'Found', |
| 180 |
303: 'See Other', |
| 181 |
304: 'Not Modified', |
| 182 |
305: 'Use Proxy', |
| 183 |
306: '(Unused)', |
| 184 |
307: 'Temporary Redirect', |
| 185 |
|
| 186 |
400: 'Bad Request', |
| 187 |
401: 'Unauthorized', |
| 188 |
402: 'Payment Required', |
| 189 |
403: 'Forbidden', |
| 190 |
404: 'Not Found', |
| 191 |
405: 'Method Not Allowed', |
| 192 |
406: 'Not Acceptable', |
| 193 |
407: 'Proxy Authentication Required', |
| 194 |
408: 'Request Timeout', |
| 195 |
409: 'Conflict', |
| 196 |
410: 'Gone', |
| 197 |
411: 'Length Required', |
| 198 |
412: 'Precondition Failed', |
| 199 |
413: 'Request Entity Too Large', |
| 200 |
414: 'Request-URI Too Long', |
| 201 |
415: 'Unsupported Media Type', |
| 202 |
416: 'Requested Range Not Satisfiable', |
| 203 |
417: 'Expectation Failed', |
| 204 |
|
| 205 |
500: 'Internal Server Error', |
| 206 |
501: 'Not Implemented', |
| 207 |
502: 'Bad Gateway', |
| 208 |
503: 'Service Unavailable', |
| 209 |
504: 'Gateway Timeout', |
| 210 |
505: 'HTTP Version Not Supported', |
| 211 |
} |
| 212 |
|
| 213 |
|
| 214 |
MAXAMOUNT = 1048576 |
| 215 |
|
| 216 |
|
| 217 |
_MAXLINE = 65536 |
| 218 |
|
| 219 |
|
| 220 |
_MAXHEADERS = 100 |
| 221 |
|
| 222 |
|
| 223 |
|
| 224 |
|
| 225 |
|
| 226 |
|
| 227 |
|
| 228 |
|
| 229 |
|
| 230 |
|
| 231 |
|
| 232 |
|
| 233 |
|
| 234 |
|
| 235 |
|
| 236 |
|
| 237 |
|
| 238 |
|
| 239 |
|
| 240 |
|
| 241 |
|
| 242 |
|
| 243 |
|
| 244 |
|
| 245 |
|
| 246 |
|
| 247 |
_is_legal_header_name = re.compile(r'\A[^:\s][^:\r\n]*\Z').match |
| 248 |
_is_illegal_header_value = re.compile(r'\n(?![ \t])|\r(?![ \t\n])').search |
| 249 |
|
| 250 |
|
| 251 |
|
| 252 |
|
| 253 |
|
| 254 |
|
| 255 |
_contains_disallowed_url_pchar_re = re.compile('[\x00-\x20\x7f-\xff]') |
| 256 |
|
| 257 |
|
| 258 |
|
| 259 |
|
| 260 |
|
| 261 |
|
| 262 |
_METHODS_EXPECTING_BODY = {'PATCH', 'POST', 'PUT'} |
| 263 |
|
| 264 |
|
| 265 |
class HTTPMessage(mimetools.Message): |
| 266 |
|
| 267 |
def addheader(self, key, value): |
| 268 |
"""Add header for field key handling repeats.""" |
| 269 |
prev = self.dict.get(key) |
| 270 |
if prev is None: |
| 271 |
self.dict[key] = value |
| 272 |
else: |
| 273 |
combined = ", ".join((prev, value)) |
| 274 |
self.dict[key] = combined |
| 275 |
|
| 276 |
def addcontinue(self, key, more): |
| 277 |
"""Add more field data from a continuation line.""" |
| 278 |
prev = self.dict[key] |
| 279 |
self.dict[key] = prev + "\n " + more |
| 280 |
|
| 281 |
def readheaders(self): |
| 282 |
"""Read header lines. |
| 283 |
|
| 284 |
Read header lines up to the entirely blank line that terminates them. |
| 285 |
The (normally blank) line that ends the headers is skipped, but not |
| 286 |
included in the returned list. If an invalid line is found in the |
| 287 |
header section, it is skipped, and further lines are processed. |
| 288 |
|
| 289 |
The variable self.status is set to the empty string if all went well, |
| 290 |
otherwise it is an error message. The variable self.headers is a |
| 291 |
completely uninterpreted list of lines contained in the header (so |
| 292 |
printing them will reproduce the header exactly as it appears in the |
| 293 |
file). |
| 294 |
|
| 295 |
If multiple header fields with the same name occur, they are combined |
| 296 |
according to the rules in RFC 2616 sec 4.2: |
| 297 |
|
| 298 |
Appending each subsequent field-value to the first, each separated |
| 299 |
by a comma. The order in which header fields with the same field-name |
| 300 |
are received is significant to the interpretation of the combined |
| 301 |
field value. |
| 302 |
""" |
| 303 |
|
| 304 |
|
| 305 |
|
| 306 |
|
| 307 |
|
| 308 |
self.dict = {} |
| 309 |
self.unixfrom = '' |
| 310 |
self.headers = hlist = [] |
| 311 |
self.status = '' |
| 312 |
headerseen = "" |
| 313 |
firstline = 1 |
| 314 |
tell = None |
| 315 |
if not hasattr(self.fp, 'unread') and self.seekable: |
| 316 |
tell = self.fp.tell |
| 317 |
while True: |
| 318 |
if len(hlist) > _MAXHEADERS: |
| 319 |
raise HTTPException("got more than %d headers" % _MAXHEADERS) |
| 320 |
if tell: |
| 321 |
try: |
| 322 |
tell() |
| 323 |
except IOError: |
| 324 |
tell = None |
| 325 |
self.seekable = 0 |
| 326 |
line = self.fp.readline(_MAXLINE + 1) |
| 327 |
if len(line) > _MAXLINE: |
| 328 |
raise LineTooLong("header line") |
| 329 |
if not line: |
| 330 |
self.status = 'EOF in headers' |
| 331 |
break |
| 332 |
|
| 333 |
if firstline and line.startswith('From '): |
| 334 |
self.unixfrom = self.unixfrom + line |
| 335 |
continue |
| 336 |
firstline = 0 |
| 337 |
if headerseen and line[0] in ' \t': |
| 338 |
|
| 339 |
|
| 340 |
|
| 341 |
hlist.append(line) |
| 342 |
self.addcontinue(headerseen, line.strip()) |
| 343 |
continue |
| 344 |
elif self.iscomment(line): |
| 345 |
|
| 346 |
continue |
| 347 |
elif self.islast(line): |
| 348 |
|
| 349 |
break |
| 350 |
headerseen = self.isheader(line) |
| 351 |
if headerseen: |
| 352 |
|
| 353 |
hlist.append(line) |
| 354 |
self.addheader(headerseen, line[len(headerseen)+1:].strip()) |
| 355 |
elif headerseen is not None: |
| 356 |
|
| 357 |
|
| 358 |
|
| 359 |
pass |
| 360 |
else: |
| 361 |
|
| 362 |
self.status = 'Non-header line where header expected' |
| 363 |
|
| 364 |
class HTTPResponse: |
| 365 |
|
| 366 |
|
| 367 |
|
| 368 |
|
| 369 |
|
| 370 |
|
| 371 |
|
| 372 |
|
| 373 |
|
| 374 |
def __init__(self, sock, debuglevel=0, strict=0, method=None, buffering=False): |
| 375 |
if buffering: |
| 376 |
|
| 377 |
|
| 378 |
self.fp = sock.makefile('rb') |
| 379 |
else: |
| 380 |
|
| 381 |
|
| 382 |
|
| 383 |
|
| 384 |
|
| 385 |
self.fp = sock.makefile('rb', 0) |
| 386 |
self.debuglevel = debuglevel |
| 387 |
self.strict = strict |
| 388 |
self._method = method |
| 389 |
|
| 390 |
self.msg = None |
| 391 |
|
| 392 |
|
| 393 |
self.version = _UNKNOWN |
| 394 |
self.status = _UNKNOWN |
| 395 |
self.reason = _UNKNOWN |
| 396 |
|
| 397 |
self.chunked = _UNKNOWN |
| 398 |
self.chunk_left = _UNKNOWN |
| 399 |
self.length = _UNKNOWN |
| 400 |
self.will_close = _UNKNOWN |
| 401 |
|
| 402 |
def _read_status(self): |
| 403 |
|
| 404 |
line = self.fp.readline(_MAXLINE + 1) |
| 405 |
if len(line) > _MAXLINE: |
| 406 |
raise LineTooLong("header line") |
| 407 |
if self.debuglevel > 0: |
| 408 |
print "reply:", repr(line) |
| 409 |
if not line: |
| 410 |
|
| 411 |
|
| 412 |
raise BadStatusLine("No status line received - the server has closed the connection") |
| 413 |
try: |
| 414 |
[version, status, reason] = line.split(None, 2) |
| 415 |
except ValueError: |
| 416 |
try: |
| 417 |
[version, status] = line.split(None, 1) |
| 418 |
reason = "" |
| 419 |
except ValueError: |
| 420 |
|
| 421 |
|
| 422 |
version = "" |
| 423 |
if not version.startswith('HTTP/'): |
| 424 |
if self.strict: |
| 425 |
self.close() |
| 426 |
raise BadStatusLine(line) |
| 427 |
else: |
| 428 |
|
| 429 |
self.fp = LineAndFileWrapper(line, self.fp) |
| 430 |
return "HTTP/0.9", 200, "" |
| 431 |
|
| 432 |
|
| 433 |
try: |
| 434 |
status = int(status) |
| 435 |
if status < 100 or status > 999: |
| 436 |
raise BadStatusLine(line) |
| 437 |
except ValueError: |
| 438 |
raise BadStatusLine(line) |
| 439 |
return version, status, reason |
| 440 |
|
| 441 |
def begin(self): |
| 442 |
if self.msg is not None: |
| 443 |
|
| 444 |
return |
| 445 |
|
| 446 |
|
| 447 |
while True: |
| 448 |
version, status, reason = self._read_status() |
| 449 |
if status != CONTINUE: |
| 450 |
break |
| 451 |
|
| 452 |
while True: |
| 453 |
skip = self.fp.readline(_MAXLINE + 1) |
| 454 |
if len(skip) > _MAXLINE: |
| 455 |
raise LineTooLong("header line") |
| 456 |
skip = skip.strip() |
| 457 |
if not skip: |
| 458 |
break |
| 459 |
if self.debuglevel > 0: |
| 460 |
print "header:", skip |
| 461 |
|
| 462 |
self.status = status |
| 463 |
self.reason = reason.strip() |
| 464 |
if version == 'HTTP/1.0': |
| 465 |
self.version = 10 |
| 466 |
elif version.startswith('HTTP/1.'): |
| 467 |
self.version = 11 |
| 468 |
elif version == 'HTTP/0.9': |
| 469 |
self.version = 9 |
| 470 |
else: |
| 471 |
raise UnknownProtocol(version) |
| 472 |
|
| 473 |
if self.version == 9: |
| 474 |
self.length = None |
| 475 |
self.chunked = 0 |
| 476 |
self.will_close = 1 |
| 477 |
self.msg = HTTPMessage(StringIO()) |
| 478 |
return |
| 479 |
|
| 480 |
self.msg = HTTPMessage(self.fp, 0) |
| 481 |
if self.debuglevel > 0: |
| 482 |
for hdr in self.msg.headers: |
| 483 |
print "header:", hdr, |
| 484 |
|
| 485 |
|
| 486 |
self.msg.fp = None |
| 487 |
|
| 488 |
|
| 489 |
tr_enc = self.msg.getheader('transfer-encoding') |
| 490 |
if tr_enc and tr_enc.lower() == "chunked": |
| 491 |
self.chunked = 1 |
| 492 |
self.chunk_left = None |
| 493 |
else: |
| 494 |
self.chunked = 0 |
| 495 |
|
| 496 |
|
| 497 |
self.will_close = self._check_close() |
| 498 |
|
| 499 |
|
| 500 |
|
| 501 |
length = self.msg.getheader('content-length') |
| 502 |
if length and not self.chunked: |
| 503 |
try: |
| 504 |
self.length = int(length) |
| 505 |
except ValueError: |
| 506 |
self.length = None |
| 507 |
else: |
| 508 |
if self.length < 0: |
| 509 |
self.length = None |
| 510 |
else: |
| 511 |
self.length = None |
| 512 |
|
| 513 |
|
| 514 |
if (status == NO_CONTENT or status == NOT_MODIFIED or |
| 515 |
100 <= status < 200 or |
| 516 |
self._method == 'HEAD'): |
| 517 |
self.length = 0 |
| 518 |
|
| 519 |
|
| 520 |
|
| 521 |
|
| 522 |
if not self.will_close and \ |
| 523 |
not self.chunked and \ |
| 524 |
self.length is None: |
| 525 |
self.will_close = 1 |
| 526 |
|
| 527 |
def _check_close(self): |
| 528 |
conn = self.msg.getheader('connection') |
| 529 |
if self.version == 11: |
| 530 |
|
| 531 |
|
| 532 |
conn = self.msg.getheader('connection') |
| 533 |
if conn and "close" in conn.lower(): |
| 534 |
return True |
| 535 |
return False |
| 536 |
|
| 537 |
|
| 538 |
|
| 539 |
|
| 540 |
|
| 541 |
if self.msg.getheader('keep-alive'): |
| 542 |
return False |
| 543 |
|
| 544 |
|
| 545 |
|
| 546 |
if conn and "keep-alive" in conn.lower(): |
| 547 |
return False |
| 548 |
|
| 549 |
|
| 550 |
pconn = self.msg.getheader('proxy-connection') |
| 551 |
if pconn and "keep-alive" in pconn.lower(): |
| 552 |
return False |
| 553 |
|
| 554 |
|
| 555 |
return True |
| 556 |
|
| 557 |
def close(self): |
| 558 |
fp = self.fp |
| 559 |
if fp: |
| 560 |
self.fp = None |
| 561 |
fp.close() |
| 562 |
|
| 563 |
def isclosed(self): |
| 564 |
|
| 565 |
|
| 566 |
|
| 567 |
|
| 568 |
|
| 569 |
|
| 570 |
return self.fp is None |
| 571 |
|
| 572 |
|
| 573 |
|
| 574 |
def read(self, amt=None): |
| 575 |
if self.fp is None: |
| 576 |
return '' |
| 577 |
|
| 578 |
if self._method == 'HEAD': |
| 579 |
self.close() |
| 580 |
return '' |
| 581 |
|
| 582 |
if self.chunked: |
| 583 |
return self._read_chunked(amt) |
| 584 |
|
| 585 |
if amt is None: |
| 586 |
|
| 587 |
if self.length is None: |
| 588 |
s = self.fp.read() |
| 589 |
else: |
| 590 |
try: |
| 591 |
s = self._safe_read(self.length) |
| 592 |
except IncompleteRead: |
| 593 |
self.close() |
| 594 |
raise |
| 595 |
self.length = 0 |
| 596 |
self.close() |
| 597 |
return s |
| 598 |
|
| 599 |
if self.length is not None: |
| 600 |
if amt > self.length: |
| 601 |
|
| 602 |
amt = self.length |
| 603 |
|
| 604 |
|
| 605 |
|
| 606 |
|
| 607 |
s = self.fp.read(amt) |
| 608 |
if not s and amt: |
| 609 |
|
| 610 |
|
| 611 |
self.close() |
| 612 |
if self.length is not None: |
| 613 |
self.length -= len(s) |
| 614 |
if not self.length: |
| 615 |
self.close() |
| 616 |
|
| 617 |
return s |
| 618 |
|
| 619 |
def _read_chunked(self, amt): |
| 620 |
assert self.chunked != _UNKNOWN |
| 621 |
chunk_left = self.chunk_left |
| 622 |
value = [] |
| 623 |
while True: |
| 624 |
if chunk_left is None: |
| 625 |
line = self.fp.readline(_MAXLINE + 1) |
| 626 |
if len(line) > _MAXLINE: |
| 627 |
raise LineTooLong("chunk size") |
| 628 |
i = line.find(';') |
| 629 |
if i >= 0: |
| 630 |
line = line[:i] |
| 631 |
try: |
| 632 |
chunk_left = int(line, 16) |
| 633 |
except ValueError: |
| 634 |
|
| 635 |
|
| 636 |
self.close() |
| 637 |
raise IncompleteRead(''.join(value)) |
| 638 |
if chunk_left == 0: |
| 639 |
break |
| 640 |
if amt is None: |
| 641 |
value.append(self._safe_read(chunk_left)) |
| 642 |
elif amt < chunk_left: |
| 643 |
value.append(self._safe_read(amt)) |
| 644 |
self.chunk_left = chunk_left - amt |
| 645 |
return ''.join(value) |
| 646 |
elif amt == chunk_left: |
| 647 |
value.append(self._safe_read(amt)) |
| 648 |
self._safe_read(2) |
| 649 |
self.chunk_left = None |
| 650 |
return ''.join(value) |
| 651 |
else: |
| 652 |
value.append(self._safe_read(chunk_left)) |
| 653 |
amt -= chunk_left |
| 654 |
|
| 655 |
|
| 656 |
self._safe_read(2) |
| 657 |
chunk_left = None |
| 658 |
|
| 659 |
|
| 660 |
|
| 661 |
while True: |
| 662 |
line = self.fp.readline(_MAXLINE + 1) |
| 663 |
if len(line) > _MAXLINE: |
| 664 |
raise LineTooLong("trailer line") |
| 665 |
if not line: |
| 666 |
|
| 667 |
|
| 668 |
break |
| 669 |
if line == '\r\n': |
| 670 |
break |
| 671 |
|
| 672 |
|
| 673 |
self.close() |
| 674 |
|
| 675 |
return ''.join(value) |
| 676 |
|
| 677 |
def _safe_read(self, amt): |
| 678 |
"""Read the number of bytes requested, compensating for partial reads. |
| 679 |
|
| 680 |
Normally, we have a blocking socket, but a read() can be interrupted |
| 681 |
by a signal (resulting in a partial read). |
| 682 |
|
| 683 |
Note that we cannot distinguish between EOF and an interrupt when zero |
| 684 |
bytes have been read. IncompleteRead() will be raised in this |
| 685 |
situation. |
| 686 |
|
| 687 |
This function should be used when <amt> bytes "should" be present for |
| 688 |
reading. If the bytes are truly not available (due to EOF), then the |
| 689 |
IncompleteRead exception can be used to detect the problem. |
| 690 |
""" |
| 691 |
|
| 692 |
|
| 693 |
|
| 694 |
|
| 695 |
|
| 696 |
s = [] |
| 697 |
while amt > 0: |
| 698 |
chunk = self.fp.read(min(amt, MAXAMOUNT)) |
| 699 |
if not chunk: |
| 700 |
raise IncompleteRead(''.join(s), amt) |
| 701 |
s.append(chunk) |
| 702 |
amt -= len(chunk) |
| 703 |
return ''.join(s) |
| 704 |
|
| 705 |
def fileno(self): |
| 706 |
return self.fp.fileno() |
| 707 |
|
| 708 |
def getheader(self, name, default=None): |
| 709 |
if self.msg is None: |
| 710 |
raise ResponseNotReady() |
| 711 |
return self.msg.getheader(name, default) |
| 712 |
|
| 713 |
def getheaders(self): |
| 714 |
"""Return list of (header, value) tuples.""" |
| 715 |
if self.msg is None: |
| 716 |
raise ResponseNotReady() |
| 717 |
return self.msg.items() |
| 718 |
|
| 719 |
|
| 720 |
class HTTPConnection: |
| 721 |
|
| 722 |
_http_vsn = 11 |
| 723 |
_http_vsn_str = 'HTTP/1.1' |
| 724 |
|
| 725 |
response_class = HTTPResponse |
| 726 |
default_port = HTTP_PORT |
| 727 |
auto_open = 1 |
| 728 |
debuglevel = 0 |
| 729 |
strict = 0 |
| 730 |
|
| 731 |
def __init__(self, host, port=None, strict=None, |
| 732 |
timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None): |
| 733 |
self.timeout = timeout |
| 734 |
self.source_address = source_address |
| 735 |
self.sock = None |
| 736 |
self._buffer = [] |
| 737 |
self.__response = None |
| 738 |
self.__state = _CS_IDLE |
| 739 |
self._method = None |
| 740 |
self._tunnel_host = None |
| 741 |
self._tunnel_port = None |
| 742 |
self._tunnel_headers = {} |
| 743 |
if strict is not None: |
| 744 |
self.strict = strict |
| 745 |
|
| 746 |
(self.host, self.port) = self._get_hostport(host, port) |
| 747 |
|
| 748 |
self._validate_host(self.host) |
| 749 |
|
| 750 |
|
| 751 |
|
| 752 |
self._create_connection = socket.create_connection |
| 753 |
|
| 754 |
def set_tunnel(self, host, port=None, headers=None): |
| 755 |
""" Set up host and port for HTTP CONNECT tunnelling. |
| 756 |
|
| 757 |
In a connection that uses HTTP Connect tunneling, the host passed to the |
| 758 |
constructor is used as proxy server that relays all communication to the |
| 759 |
endpoint passed to set_tunnel. This is done by sending a HTTP CONNECT |
| 760 |
request to the proxy server when the connection is established. |
| 761 |
|
| 762 |
This method must be called before the HTTP connection has been |
| 763 |
established. |
| 764 |
|
| 765 |
The headers argument should be a mapping of extra HTTP headers |
| 766 |
to send with the CONNECT request. |
| 767 |
""" |
| 768 |
|
| 769 |
if self.sock: |
| 770 |
raise RuntimeError("Can't setup tunnel for established connection.") |
| 771 |
|
| 772 |
self._tunnel_host, self._tunnel_port = self._get_hostport(host, port) |
| 773 |
if headers: |
| 774 |
self._tunnel_headers = headers |
| 775 |
else: |
| 776 |
self._tunnel_headers.clear() |
| 777 |
|
| 778 |
def _get_hostport(self, host, port): |
| 779 |
if port is None: |
| 780 |
i = host.rfind(':') |
| 781 |
j = host.rfind(']') |
| 782 |
if i > j: |
| 783 |
try: |
| 784 |
port = int(host[i+1:]) |
| 785 |
except ValueError: |
| 786 |
if host[i+1:] == "": |
| 787 |
port = self.default_port |
| 788 |
else: |
| 789 |
raise InvalidURL("nonnumeric port: '%s'" % host[i+1:]) |
| 790 |
host = host[:i] |
| 791 |
else: |
| 792 |
port = self.default_port |
| 793 |
if host and host[0] == '[' and host[-1] == ']': |
| 794 |
host = host[1:-1] |
| 795 |
return (host, port) |
| 796 |
|
| 797 |
def set_debuglevel(self, level): |
| 798 |
self.debuglevel = level |
| 799 |
|
| 800 |
def _tunnel(self): |
| 801 |
self.send("CONNECT %s:%d HTTP/1.0\r\n" % (self._tunnel_host, |
| 802 |
self._tunnel_port)) |
| 803 |
for header, value in self._tunnel_headers.iteritems(): |
| 804 |
self.send("%s: %s\r\n" % (header, value)) |
| 805 |
self.send("\r\n") |
| 806 |
response = self.response_class(self.sock, strict = self.strict, |
| 807 |
method = self._method) |
| 808 |
(version, code, message) = response._read_status() |
| 809 |
|
| 810 |
if version == "HTTP/0.9": |
| 811 |
|
| 812 |
|
| 813 |
self.close() |
| 814 |
raise socket.error("Invalid response from tunnel request") |
| 815 |
if code != 200: |
| 816 |
self.close() |
| 817 |
raise socket.error("Tunnel connection failed: %d %s" % (code, |
| 818 |
message.strip())) |
| 819 |
while True: |
| 820 |
line = response.fp.readline(_MAXLINE + 1) |
| 821 |
if len(line) > _MAXLINE: |
| 822 |
raise LineTooLong("header line") |
| 823 |
if not line: |
| 824 |
|
| 825 |
break |
| 826 |
if line == '\r\n': |
| 827 |
break |
| 828 |
|
| 829 |
|
| 830 |
def connect(self): |
| 831 |
"""Connect to the host and port specified in __init__.""" |
| 832 |
self.sock = self._create_connection((self.host,self.port), |
| 833 |
self.timeout, self.source_address) |
| 834 |
|
| 835 |
if self._tunnel_host: |
| 836 |
self._tunnel() |
| 837 |
|
| 838 |
def close(self): |
| 839 |
"""Close the connection to the HTTP server.""" |
| 840 |
self.__state = _CS_IDLE |
| 841 |
try: |
| 842 |
sock = self.sock |
| 843 |
if sock: |
| 844 |
self.sock = None |
| 845 |
sock.close() |
| 846 |
finally: |
| 847 |
response = self.__response |
| 848 |
if response: |
| 849 |
self.__response = None |
| 850 |
response.close() |
| 851 |
|
| 852 |
def send(self, data): |
| 853 |
"""Send `data' to the server.""" |
| 854 |
if self.sock is None: |
| 855 |
if self.auto_open: |
| 856 |
self.connect() |
| 857 |
else: |
| 858 |
raise NotConnected() |
| 859 |
|
| 860 |
if self.debuglevel > 0: |
| 861 |
print "send:", repr(data) |
| 862 |
blocksize = 8192 |
| 863 |
if hasattr(data,'read') and not isinstance(data, array): |
| 864 |
if self.debuglevel > 0: print "sendIng a read()able" |
| 865 |
datablock = data.read(blocksize) |
| 866 |
while datablock: |
| 867 |
self.sock.sendall(datablock) |
| 868 |
datablock = data.read(blocksize) |
| 869 |
else: |
| 870 |
self.sock.sendall(data) |
| 871 |
|
| 872 |
def _output(self, s): |
| 873 |
"""Add a line of output to the current request buffer. |
| 874 |
|
| 875 |
Assumes that the line does *not* end with \\r\\n. |
| 876 |
""" |
| 877 |
self._buffer.append(s) |
| 878 |
|
| 879 |
def _send_output(self, message_body=None): |
| 880 |
"""Send the currently buffered request and clear the buffer. |
| 881 |
|
| 882 |
Appends an extra \\r\\n to the buffer. |
| 883 |
A message_body may be specified, to be appended to the request. |
| 884 |
""" |
| 885 |
self._buffer.extend(("", "")) |
| 886 |
msg = "\r\n".join(self._buffer) |
| 887 |
del self._buffer[:] |
| 888 |
|
| 889 |
|
| 890 |
|
| 891 |
if isinstance(message_body, str): |
| 892 |
msg += message_body |
| 893 |
message_body = None |
| 894 |
self.send(msg) |
| 895 |
if message_body is not None: |
| 896 |
|
| 897 |
|
| 898 |
self.send(message_body) |
| 899 |
|
| 900 |
def putrequest(self, method, url, skip_host=0, skip_accept_encoding=0): |
| 901 |
"""Send a request to the server. |
| 902 |
|
| 903 |
`method' specifies an HTTP request method, e.g. 'GET'. |
| 904 |
`url' specifies the object being requested, e.g. '/index.html'. |
| 905 |
`skip_host' if True does not add automatically a 'Host:' header |
| 906 |
`skip_accept_encoding' if True does not add automatically an |
| 907 |
'Accept-Encoding:' header |
| 908 |
""" |
| 909 |
|
| 910 |
|
| 911 |
if self.__response and self.__response.isclosed(): |
| 912 |
self.__response = None |
| 913 |
|
| 914 |
|
| 915 |
|
| 916 |
|
| 917 |
|
| 918 |
|
| 919 |
|
| 920 |
|
| 921 |
|
| 922 |
|
| 923 |
|
| 924 |
|
| 925 |
|
| 926 |
|
| 927 |
|
| 928 |
|
| 929 |
|
| 930 |
|
| 931 |
|
| 932 |
|
| 933 |
if self.__state == _CS_IDLE: |
| 934 |
self.__state = _CS_REQ_STARTED |
| 935 |
else: |
| 936 |
raise CannotSendRequest() |
| 937 |
|
| 938 |
|
| 939 |
self._method = method |
| 940 |
|
| 941 |
url = url or '/' |
| 942 |
self._validate_path(url) |
| 943 |
|
| 944 |
request = '%s %s %s' % (method, url, self._http_vsn_str) |
| 945 |
|
| 946 |
self._output(self._encode_request(request)) |
| 947 |
|
| 948 |
if self._http_vsn == 11: |
| 949 |
|
| 950 |
|
| 951 |
if not skip_host: |
| 952 |
|
| 953 |
|
| 954 |
|
| 955 |
|
| 956 |
|
| 957 |
|
| 958 |
|
| 959 |
|
| 960 |
|
| 961 |
|
| 962 |
|
| 963 |
|
| 964 |
|
| 965 |
|
| 966 |
netloc = '' |
| 967 |
if url.startswith('http'): |
| 968 |
nil, netloc, nil, nil, nil = urlsplit(url) |
| 969 |
|
| 970 |
if netloc: |
| 971 |
try: |
| 972 |
netloc_enc = netloc.encode("ascii") |
| 973 |
except UnicodeEncodeError: |
| 974 |
netloc_enc = netloc.encode("idna") |
| 975 |
self.putheader('Host', netloc_enc) |
| 976 |
else: |
| 977 |
if self._tunnel_host: |
| 978 |
host = self._tunnel_host |
| 979 |
port = self._tunnel_port |
| 980 |
else: |
| 981 |
host = self.host |
| 982 |
port = self.port |
| 983 |
|
| 984 |
try: |
| 985 |
host_enc = host.encode("ascii") |
| 986 |
except UnicodeEncodeError: |
| 987 |
host_enc = host.encode("idna") |
| 988 |
|
| 989 |
if host_enc.find(':') >= 0: |
| 990 |
host_enc = "[" + host_enc + "]" |
| 991 |
if port == self.default_port: |
| 992 |
self.putheader('Host', host_enc) |
| 993 |
else: |
| 994 |
self.putheader('Host', "%s:%s" % (host_enc, port)) |
| 995 |
|
| 996 |
|
| 997 |
|
| 998 |
|
| 999 |
|
| 1000 |
|
| 1001 |
|
| 1002 |
|
| 1003 |
|
| 1004 |
if not skip_accept_encoding: |
| 1005 |
self.putheader('Accept-Encoding', 'identity') |
| 1006 |
|
| 1007 |
|
| 1008 |
|
| 1009 |
|
| 1010 |
|
| 1011 |
|
| 1012 |
|
| 1013 |
|
| 1014 |
|
| 1015 |
else: |
| 1016 |
|
| 1017 |
pass |
| 1018 |
|
| 1019 |
def _encode_request(self, request): |
| 1020 |
|
| 1021 |
return request |
| 1022 |
|
| 1023 |
def _validate_path(self, url): |
| 1024 |
"""Validate a url for putrequest.""" |
| 1025 |
|
| 1026 |
match = _contains_disallowed_url_pchar_re.search(url) |
| 1027 |
if match: |
| 1028 |
msg = ( |
| 1029 |
"URL can't contain control characters. {url!r} " |
| 1030 |
"(found at least {matched!r})" |
| 1031 |
).format(matched=match.group(), url=url) |
| 1032 |
raise InvalidURL(msg) |
| 1033 |
|
| 1034 |
def _validate_host(self, host): |
| 1035 |
"""Validate a host so it doesn't contain control characters.""" |
| 1036 |
|
| 1037 |
match = _contains_disallowed_url_pchar_re.search(host) |
| 1038 |
if match: |
| 1039 |
msg = ( |
| 1040 |
"URL can't contain control characters. {host!r} " |
| 1041 |
"(found at least {matched!r})" |
| 1042 |
).format(matched=match.group(), host=host) |
| 1043 |
raise InvalidURL(msg) |
| 1044 |
|
| 1045 |
def putheader(self, header, *values): |
| 1046 |
"""Send a request header line to the server. |
| 1047 |
|
| 1048 |
For example: h.putheader('Accept', 'text/html') |
| 1049 |
""" |
| 1050 |
if self.__state != _CS_REQ_STARTED: |
| 1051 |
raise CannotSendHeader() |
| 1052 |
|
| 1053 |
header = '%s' % header |
| 1054 |
if not _is_legal_header_name(header): |
| 1055 |
raise ValueError('Invalid header name %r' % (header,)) |
| 1056 |
|
| 1057 |
values = [str(v) for v in values] |
| 1058 |
for one_value in values: |
| 1059 |
if _is_illegal_header_value(one_value): |
| 1060 |
raise ValueError('Invalid header value %r' % (one_value,)) |
| 1061 |
|
| 1062 |
hdr = '%s: %s' % (header, '\r\n\t'.join(values)) |
| 1063 |
self._output(hdr) |
| 1064 |
|
| 1065 |
def endheaders(self, message_body=None): |
| 1066 |
"""Indicate that the last header line has been sent to the server. |
| 1067 |
|
| 1068 |
This method sends the request to the server. The optional |
| 1069 |
message_body argument can be used to pass a message body |
| 1070 |
associated with the request. The message body will be sent in |
| 1071 |
the same packet as the message headers if it is string, otherwise it is |
| 1072 |
sent as a separate packet. |
| 1073 |
""" |
| 1074 |
if self.__state == _CS_REQ_STARTED: |
| 1075 |
self.__state = _CS_REQ_SENT |
| 1076 |
else: |
| 1077 |
raise CannotSendHeader() |
| 1078 |
self._send_output(message_body) |
| 1079 |
|
| 1080 |
def request(self, method, url, body=None, headers={}): |
| 1081 |
"""Send a complete request to the server.""" |
| 1082 |
self._send_request(method, url, body, headers) |
| 1083 |
|
| 1084 |
def _set_content_length(self, body, method): |
| 1085 |
|
| 1086 |
|
| 1087 |
|
| 1088 |
|
| 1089 |
thelen = None |
| 1090 |
if body is None and method.upper() in _METHODS_EXPECTING_BODY: |
| 1091 |
thelen = '0' |
| 1092 |
elif body is not None: |
| 1093 |
try: |
| 1094 |
thelen = str(len(body)) |
| 1095 |
except (TypeError, AttributeError): |
| 1096 |
|
| 1097 |
|
| 1098 |
try: |
| 1099 |
thelen = str(os.fstat(body.fileno()).st_size) |
| 1100 |
except (AttributeError, OSError): |
| 1101 |
|
| 1102 |
if self.debuglevel > 0: print "Cannot stat!!" |
| 1103 |
|
| 1104 |
if thelen is not None: |
| 1105 |
self.putheader('Content-Length', thelen) |
| 1106 |
|
| 1107 |
def _send_request(self, method, url, body, headers): |
| 1108 |
|
| 1109 |
header_names = dict.fromkeys([k.lower() for k in headers]) |
| 1110 |
skips = {} |
| 1111 |
if 'host' in header_names: |
| 1112 |
skips['skip_host'] = 1 |
| 1113 |
if 'accept-encoding' in header_names: |
| 1114 |
skips['skip_accept_encoding'] = 1 |
| 1115 |
|
| 1116 |
self.putrequest(method, url, **skips) |
| 1117 |
|
| 1118 |
if 'content-length' not in header_names: |
| 1119 |
self._set_content_length(body, method) |
| 1120 |
for hdr, value in headers.iteritems(): |
| 1121 |
self.putheader(hdr, value) |
| 1122 |
self.endheaders(body) |
| 1123 |
|
| 1124 |
def getresponse(self, buffering=False): |
| 1125 |
"Get the response from the server." |
| 1126 |
|
| 1127 |
|
| 1128 |
if self.__response and self.__response.isclosed(): |
| 1129 |
self.__response = None |
| 1130 |
|
| 1131 |
|
| 1132 |
|
| 1133 |
|
| 1134 |
|
| 1135 |
|
| 1136 |
|
| 1137 |
|
| 1138 |
|
| 1139 |
|
| 1140 |
|
| 1141 |
|
| 1142 |
|
| 1143 |
|
| 1144 |
|
| 1145 |
|
| 1146 |
|
| 1147 |
if self.__state != _CS_REQ_SENT or self.__response: |
| 1148 |
raise ResponseNotReady() |
| 1149 |
|
| 1150 |
args = (self.sock,) |
| 1151 |
kwds = {"strict":self.strict, "method":self._method} |
| 1152 |
if self.debuglevel > 0: |
| 1153 |
args += (self.debuglevel,) |
| 1154 |
if buffering: |
| 1155 |
|
| 1156 |
|
| 1157 |
kwds["buffering"] = True; |
| 1158 |
response = self.response_class(*args, **kwds) |
| 1159 |
|
| 1160 |
try: |
| 1161 |
response.begin() |
| 1162 |
assert response.will_close != _UNKNOWN |
| 1163 |
self.__state = _CS_IDLE |
| 1164 |
|
| 1165 |
if response.will_close: |
| 1166 |
|
| 1167 |
self.close() |
| 1168 |
else: |
| 1169 |
|
| 1170 |
self.__response = response |
| 1171 |
|
| 1172 |
return response |
| 1173 |
except: |
| 1174 |
response.close() |
| 1175 |
raise |
| 1176 |
|
| 1177 |
|
| 1178 |
class HTTP: |
| 1179 |
"Compatibility class with httplib.py from 1.5." |
| 1180 |
|
| 1181 |
_http_vsn = 10 |
| 1182 |
_http_vsn_str = 'HTTP/1.0' |
| 1183 |
|
| 1184 |
debuglevel = 0 |
| 1185 |
|
| 1186 |
_connection_class = HTTPConnection |
| 1187 |
|
| 1188 |
def __init__(self, host='', port=None, strict=None): |
| 1189 |
"Provide a default host, since the superclass requires one." |
| 1190 |
|
| 1191 |
|
| 1192 |
if port == 0: |
| 1193 |
port = None |
| 1194 |
|
| 1195 |
|
| 1196 |
|
| 1197 |
|
| 1198 |
self._setup(self._connection_class(host, port, strict)) |
| 1199 |
|
| 1200 |
def _setup(self, conn): |
| 1201 |
self._conn = conn |
| 1202 |
|
| 1203 |
|
| 1204 |
self.send = conn.send |
| 1205 |
self.putrequest = conn.putrequest |
| 1206 |
self.putheader = conn.putheader |
| 1207 |
self.endheaders = conn.endheaders |
| 1208 |
self.set_debuglevel = conn.set_debuglevel |
| 1209 |
|
| 1210 |
conn._http_vsn = self._http_vsn |
| 1211 |
conn._http_vsn_str = self._http_vsn_str |
| 1212 |
|
| 1213 |
self.file = None |
| 1214 |
|
| 1215 |
def connect(self, host=None, port=None): |
| 1216 |
"Accept arguments to set the host/port, since the superclass doesn't." |
| 1217 |
|
| 1218 |
if host is not None: |
| 1219 |
(self._conn.host, self._conn.port) = self._conn._get_hostport(host, port) |
| 1220 |
self._conn.connect() |
| 1221 |
|
| 1222 |
def getfile(self): |
| 1223 |
"Provide a getfile, since the superclass' does not use this concept." |
| 1224 |
return self.file |
| 1225 |
|
| 1226 |
def getreply(self, buffering=False): |
| 1227 |
"""Compat definition since superclass does not define it. |
| 1228 |
|
| 1229 |
Returns a tuple consisting of: |
| 1230 |
- server status code (e.g. '200' if all goes well) |
| 1231 |
- server "reason" corresponding to status code |
| 1232 |
- any RFC822 headers in the response from the server |
| 1233 |
""" |
| 1234 |
try: |
| 1235 |
if not buffering: |
| 1236 |
response = self._conn.getresponse() |
| 1237 |
else: |
| 1238 |
|
| 1239 |
|
| 1240 |
response = self._conn.getresponse(buffering) |
| 1241 |
except BadStatusLine, e: |
| 1242 |
|
| 1243 |
|
| 1244 |
|
| 1245 |
|
| 1246 |
|
| 1247 |
self.file = self._conn.sock.makefile('rb', 0) |
| 1248 |
|
| 1249 |
|
| 1250 |
self.close() |
| 1251 |
|
| 1252 |
self.headers = None |
| 1253 |
return -1, e.line, None |
| 1254 |
|
| 1255 |
self.headers = response.msg |
| 1256 |
self.file = response.fp |
| 1257 |
return response.status, response.reason, response.msg |
| 1258 |
|
| 1259 |
def close(self): |
| 1260 |
self._conn.close() |
| 1261 |
|
| 1262 |
|
| 1263 |
|
| 1264 |
|
| 1265 |
|
| 1266 |
|
| 1267 |
self.file = None |
| 1268 |
|
| 1269 |
try: |
| 1270 |
import ssl |
| 1271 |
except ImportError: |
| 1272 |
pass |
| 1273 |
else: |
| 1274 |
class HTTPSConnection(HTTPConnection): |
| 1275 |
"This class allows communication via SSL." |
| 1276 |
|
| 1277 |
default_port = HTTPS_PORT |
| 1278 |
|
| 1279 |
def __init__(self, host, port=None, key_file=None, cert_file=None, |
| 1280 |
strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, |
| 1281 |
source_address=None, context=None): |
| 1282 |
HTTPConnection.__init__(self, host, port, strict, timeout, |
| 1283 |
source_address) |
| 1284 |
self.key_file = key_file |
| 1285 |
self.cert_file = cert_file |
| 1286 |
if context is None: |
| 1287 |
context = ssl._create_default_https_context() |
| 1288 |
if key_file or cert_file: |
| 1289 |
context.load_cert_chain(cert_file, key_file) |
| 1290 |
self._context = context |
| 1291 |
|
| 1292 |
def connect(self): |
| 1293 |
"Connect to a host on a given (SSL) port." |
| 1294 |
|
| 1295 |
HTTPConnection.connect(self) |
| 1296 |
|
| 1297 |
if self._tunnel_host: |
| 1298 |
server_hostname = self._tunnel_host |
| 1299 |
else: |
| 1300 |
server_hostname = self.host |
| 1301 |
|
| 1302 |
self.sock = self._context.wrap_socket(self.sock, |
| 1303 |
server_hostname=server_hostname) |
| 1304 |
|
| 1305 |
__all__.append("HTTPSConnection") |
| 1306 |
|
| 1307 |
class HTTPS(HTTP): |
| 1308 |
"""Compatibility with 1.5 httplib interface |
| 1309 |
|
| 1310 |
Python 1.5.2 did not have an HTTPS class, but it defined an |
| 1311 |
interface for sending http requests that is also useful for |
| 1312 |
https. |
| 1313 |
""" |
| 1314 |
|
| 1315 |
_connection_class = HTTPSConnection |
| 1316 |
|
| 1317 |
def __init__(self, host='', port=None, key_file=None, cert_file=None, |
| 1318 |
strict=None, context=None): |
| 1319 |
|
| 1320 |
|
| 1321 |
|
| 1322 |
if port == 0: |
| 1323 |
port = None |
| 1324 |
self._setup(self._connection_class(host, port, key_file, |
| 1325 |
cert_file, strict, |
| 1326 |
context=context)) |
| 1327 |
|
| 1328 |
|
| 1329 |
|
| 1330 |
self.key_file = key_file |
| 1331 |
self.cert_file = cert_file |
| 1332 |
|
| 1333 |
|
| 1334 |
def FakeSocket (sock, sslobj): |
| 1335 |
warnings.warn("FakeSocket is deprecated, and won't be in 3.x. " + |
| 1336 |
"Use the result of ssl.wrap_socket() directly instead.", |
| 1337 |
DeprecationWarning, stacklevel=2) |
| 1338 |
return sslobj |
| 1339 |
|
| 1340 |
|
| 1341 |
class HTTPException(Exception): |
| 1342 |
|
| 1343 |
|
| 1344 |
pass |
| 1345 |
|
| 1346 |
class NotConnected(HTTPException): |
| 1347 |
pass |
| 1348 |
|
| 1349 |
class InvalidURL(HTTPException): |
| 1350 |
pass |
| 1351 |
|
| 1352 |
class UnknownProtocol(HTTPException): |
| 1353 |
def __init__(self, version): |
| 1354 |
self.args = version, |
| 1355 |
self.version = version |
| 1356 |
|
| 1357 |
class UnknownTransferEncoding(HTTPException): |
| 1358 |
pass |
| 1359 |
|
| 1360 |
class UnimplementedFileMode(HTTPException): |
| 1361 |
pass |
| 1362 |
|
| 1363 |
class IncompleteRead(HTTPException): |
| 1364 |
def __init__(self, partial, expected=None): |
| 1365 |
self.args = partial, |
| 1366 |
self.partial = partial |
| 1367 |
self.expected = expected |
| 1368 |
def __repr__(self): |
| 1369 |
if self.expected is not None: |
| 1370 |
e = ', %i more expected' % self.expected |
| 1371 |
else: |
| 1372 |
e = '' |
| 1373 |
return 'IncompleteRead(%i bytes read%s)' % (len(self.partial), e) |
| 1374 |
def __str__(self): |
| 1375 |
return repr(self) |
| 1376 |
|
| 1377 |
class ImproperConnectionState(HTTPException): |
| 1378 |
pass |
| 1379 |
|
| 1380 |
class CannotSendRequest(ImproperConnectionState): |
| 1381 |
pass |
| 1382 |
|
| 1383 |
class CannotSendHeader(ImproperConnectionState): |
| 1384 |
pass |
| 1385 |
|
| 1386 |
class ResponseNotReady(ImproperConnectionState): |
| 1387 |
pass |
| 1388 |
|
| 1389 |
class BadStatusLine(HTTPException): |
| 1390 |
def __init__(self, line): |
| 1391 |
if not line: |
| 1392 |
line = repr(line) |
| 1393 |
self.args = line, |
| 1394 |
self.line = line |
| 1395 |
|
| 1396 |
class LineTooLong(HTTPException): |
| 1397 |
def __init__(self, line_type): |
| 1398 |
HTTPException.__init__(self, "got more than %d bytes when reading %s" |
| 1399 |
% (_MAXLINE, line_type)) |
| 1400 |
|
| 1401 |
|
| 1402 |
error = HTTPException |
| 1403 |
|
| 1404 |
class LineAndFileWrapper: |
| 1405 |
"""A limited file-like object for HTTP/0.9 responses.""" |
| 1406 |
|
| 1407 |
|
| 1408 |
|
| 1409 |
|
| 1410 |
|
| 1411 |
|
| 1412 |
def __init__(self, line, file): |
| 1413 |
self._line = line |
| 1414 |
self._file = file |
| 1415 |
self._line_consumed = 0 |
| 1416 |
self._line_offset = 0 |
| 1417 |
self._line_left = len(line) |
| 1418 |
|
| 1419 |
def __getattr__(self, attr): |
| 1420 |
return getattr(self._file, attr) |
| 1421 |
|
| 1422 |
def _done(self): |
| 1423 |
|
| 1424 |
|
| 1425 |
|
| 1426 |
self._line_consumed = 1 |
| 1427 |
self.read = self._file.read |
| 1428 |
self.readline = self._file.readline |
| 1429 |
self.readlines = self._file.readlines |
| 1430 |
|
| 1431 |
def read(self, amt=None): |
| 1432 |
if self._line_consumed: |
| 1433 |
return self._file.read(amt) |
| 1434 |
assert self._line_left |
| 1435 |
if amt is None or amt > self._line_left: |
| 1436 |
s = self._line[self._line_offset:] |
| 1437 |
self._done() |
| 1438 |
if amt is None: |
| 1439 |
return s + self._file.read() |
| 1440 |
else: |
| 1441 |
return s + self._file.read(amt - len(s)) |
| 1442 |
else: |
| 1443 |
assert amt <= self._line_left |
| 1444 |
i = self._line_offset |
| 1445 |
j = i + amt |
| 1446 |
s = self._line[i:j] |
| 1447 |
self._line_offset = j |
| 1448 |
self._line_left -= amt |
| 1449 |
if self._line_left == 0: |
| 1450 |
self._done() |
| 1451 |
return s |
| 1452 |
|
| 1453 |
def readline(self): |
| 1454 |
if self._line_consumed: |
| 1455 |
return self._file.readline() |
| 1456 |
assert self._line_left |
| 1457 |
s = self._line[self._line_offset:] |
| 1458 |
self._done() |
| 1459 |
return s |
| 1460 |
|
| 1461 |
def readlines(self, size=None): |
| 1462 |
if self._line_consumed: |
| 1463 |
return self._file.readlines(size) |
| 1464 |
assert self._line_left |
| 1465 |
L = [self._line[self._line_offset:]] |
| 1466 |
self._done() |
| 1467 |
if size is None: |
| 1468 |
return L + self._file.readlines() |
| 1469 |
else: |
| 1470 |
return L + self._file.readlines(size) |