home *** CD-ROM | disk | FTP | other *** search
- # Source Generated with Decompyle++
- # File: in.pyc (Python 2.0)
-
- '''HTTP/1.1 client library
-
- <intro stuff goes here>
- <other stuff, too>
-
- HTTPConnection go through a number of "states", which defines when a client
- may legally make another request or fetch the response for a particular
- request. This diagram details these state transitions:
-
- (null)
- |
- | HTTPConnection()
- v
- Idle
- |
- | putrequest()
- v
- Request-started
- |
- | ( putheader() )* endheaders()
- v
- Request-sent
- |
- | response = getresponse()
- v
- Unread-response [Response-headers-read]
- |\\____________________
- | | response.read() | putrequest()
- v v
- Idle Req-started-unread-response
- _______/|
- / |
- response.read() | | ( putheader() )* endheaders()
- v v
- Request-started Req-sent-unread-response
- |
- | response.read()
- v
- Request-sent
-
- This diagram presents the following rules:
- -- a second request may not be started until {response-headers-read}
- -- a response [object] cannot be retrieved until {request-sent}
- -- there is no differentiation between an unread response body and a
- partially read response body
-
- Note: this enforcement is applied by the HTTPConnection class. The
- HTTPResponse class does not enforce this state machine, which
- implies sophisticated clients may accelerate the request/response
- pipeline. Caution should be taken, though: accelerating the states
- beyond the above pattern may imply knowledge of the server\'s
- connection-close behavior for certain requests. For example, it
- is impossible to tell whether the server will close the connection
- UNTIL the response headers have been read; this means that further
- requests cannot be placed into the pipeline until it is known that
- the server will NOT be closing the connection.
-
- Logical State __state __response
- ------------- ------- ----------
- Idle _CS_IDLE None
- Request-started _CS_REQ_STARTED None
- Request-sent _CS_REQ_SENT None
- Unread-response _CS_IDLE <response_class>
- Req-started-unread-response _CS_REQ_STARTED <response_class>
- Req-sent-unread-response _CS_REQ_SENT <response_class>
- '''
- import socket
- import string
- import mimetools
-
- try:
- from cStringIO import StringIO
- except ImportError:
- from StringIO import StringIO
-
- HTTP_PORT = 80
- HTTPS_PORT = 443
- _UNKNOWN = 'UNKNOWN'
- _CS_IDLE = 'Idle'
- _CS_REQ_STARTED = 'Request-started'
- _CS_REQ_SENT = 'Request-sent'
-
- class HTTPResponse:
-
- def __init__(self, sock, debuglevel = 0):
- self.fp = sock.makefile('rb', 0)
- self.debuglevel = debuglevel
- self.msg = None
- self.version = _UNKNOWN
- self.status = _UNKNOWN
- self.reason = _UNKNOWN
- self.chunked = _UNKNOWN
- self.chunk_left = _UNKNOWN
- self.length = _UNKNOWN
- self.will_close = _UNKNOWN
-
-
- def begin(self):
- if self.msg is not None:
- return None
-
- line = self.fp.readline()
- if self.debuglevel > 0:
- print 'reply:', repr(line)
-
-
- try:
- (version, status, reason) = string.split(line, None, 2)
- except ValueError:
-
- try:
- (version, status) = string.split(line, None, 1)
- reason = ''
- except ValueError:
- version = 'HTTP/0.9'
- status = '200'
- reason = ''
-
-
- if version[:5] != 'HTTP/':
- self.close()
- raise BadStatusLine(line)
-
- self.status = status = int(status)
- self.reason = string.strip(reason)
- if version == 'HTTP/1.0':
- self.version = 10
- elif version.startswith('HTTP/1.'):
- self.version = 11
- elif version == 'HTTP/0.9':
- self.version = 9
- else:
- raise UnknownProtocol(version)
- if self.version == 9:
- self.msg = mimetools.Message(StringIO())
- return None
-
- self.msg = mimetools.Message(self.fp, 0)
- self.msg.fp = None
- tr_enc = self.msg.getheader('transfer-encoding')
- conn = self.msg.getheader('connection')
- if conn:
- conn = string.lower(conn)
- if string.find(conn, 'close') != -1 and self.version != 11:
- pass
- self.will_close = not self.msg.getheader('keep-alive')
- elif self.version != 11:
- pass
- self.will_close = not self.msg.getheader('keep-alive')
- length = self.msg.getheader('content-length')
- if length and not (self.chunked):
-
- try:
- self.length = int(length)
- except ValueError:
- self.length = None
-
- else:
- self.length = None
- if not status == 204 and status == 304:
- if status <= status:
- pass
- elif status < 200:
- self.length = 0
-
- if not (self.will_close) and not (self.chunked) and self.length is None:
- self.will_close = 1
-
-
-
- def close(self):
- if self.fp:
- self.fp.close()
- self.fp = None
-
-
-
- def isclosed(self):
- return self.fp is None
-
-
- def read(self, amt = None):
- if self.fp is None:
- return ''
-
- if self.chunked:
- chunk_left = self.chunk_left
- value = ''
- while 1:
- if chunk_left is None:
- line = self.fp.readline()
- i = string.find(line, ';')
- if i >= 0:
- line = line[:i]
-
- chunk_left = string.atoi(line, 16)
- if chunk_left == 0:
- break
-
-
- if amt is None:
- value = value + self._safe_read(chunk_left)
- elif amt < chunk_left:
- value = value + self._safe_read(amt)
- self.chunk_left = chunk_left - amt
- return value
- elif amt == chunk_left:
- value = value + self._safe_read(amt)
- self._safe_read(2)
- self.chunk_left = None
- return value
- else:
- value = value + self._safe_read(chunk_left)
- amt = amt - chunk_left
- self._safe_read(2)
- chunk_left = None
- while 1:
- line = self.fp.readline()
- if line == '\r\n':
- break
-
- self.close()
- return value
- elif amt is None:
- if self.will_close:
- s = self.fp.read()
- else:
- s = self._safe_read(self.length)
- self.close()
- return s
-
- if self.length is not None:
- if amt > self.length:
- amt = self.length
-
- self.length = self.length - amt
-
- s = self.fp.read(amt)
- return s
-
-
- def _safe_read(self, amt):
- '''Read the number of bytes requested, compensating for partial reads.
-
- Normally, we have a blocking socket, but a read() can be interrupted
- by a signal (resulting in a partial read).
-
- Note that we cannot distinguish between EOF and an interrupt when zero
- bytes have been read. IncompleteRead() will be raised in this
- situation.
-
- This function should be used when <amt> bytes "should" be present for
- reading. If the bytes are truly not available (due to EOF), then the
- IncompleteRead exception can be used to detect the problem.
- '''
- s = ''
- while amt > 0:
- chunk = self.fp.read(amt)
- if not chunk:
- raise IncompleteRead(s)
-
- s = s + chunk
- amt = amt - len(chunk)
- return s
-
-
- def getheader(self, name, default = None):
- if self.msg is None:
- raise ResponseNotReady()
-
- return self.msg.getheader(name, default)
-
-
-
- class HTTPConnection:
- _http_vsn = 11
- _http_vsn_str = 'HTTP/1.1'
- response_class = HTTPResponse
- default_port = HTTP_PORT
- auto_open = 1
- debuglevel = 0
-
- def __init__(self, host, port = None):
- self.sock = None
- self._HTTPConnection__response = None
- self._HTTPConnection__state = _CS_IDLE
- self._set_hostport(host, port)
-
-
- def _set_hostport(self, host, port):
- if port is None:
- i = string.find(host, ':')
- if i >= 0:
- port = int(host[i + 1:])
- host = host[:i]
- else:
- port = self.default_port
-
- self.host = host
- self.port = port
-
-
- def set_debuglevel(self, level):
- self.debuglevel = level
-
-
- def connect(self):
- '''Connect to the host and port specified in __init__.'''
- self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- if self.debuglevel > 0:
- print 'connect: (%s, %s)' % (self.host, self.port)
-
- self.sock.connect((self.host, self.port))
-
-
- def close(self):
- '''Close the connection to the HTTP server.'''
- if self.sock:
- self.sock.close()
- self.sock = None
-
- if self._HTTPConnection__response:
- self._HTTPConnection__response.close()
- self._HTTPConnection__response = None
-
- self._HTTPConnection__state = _CS_IDLE
-
-
- def send(self, str):
- """Send `str' to the server."""
- if self.sock is None:
- if self.auto_open:
- self.connect()
- else:
- raise NotConnected()
-
- if self.debuglevel > 0:
- print 'send:', repr(str)
-
-
- try:
- self.sock.send(str)
- except socket.error:
- v = None
- if v[0] == 32:
- self.close()
-
- raise
-
-
-
- def putrequest(self, method, url):
- """Send a request to the server.
-
- `method' specifies an HTTP request method, e.g. 'GET'.
- `url' specifies the object being requested, e.g. '/index.html'.
- """
- if self._HTTPConnection__response and self._HTTPConnection__response.isclosed():
- self._HTTPConnection__response = None
-
- if self._HTTPConnection__state == _CS_IDLE:
- self._HTTPConnection__state = _CS_REQ_STARTED
- else:
- raise CannotSendRequest()
- if not url:
- url = '/'
-
- str = '%s %s %s\r\n' % (method, url, self._http_vsn_str)
-
- try:
- self.send(str)
- except socket.error:
- v = None
- if v[0] != 32 or not (self.auto_open):
- raise
-
- self.send(str)
-
- if self._http_vsn == 11:
- self.putheader('Host', self.host)
- self.putheader('Accept-Encoding', 'identity')
-
-
-
- def putheader(self, header, value):
- """Send a request header line to the server.
-
- For example: h.putheader('Accept', 'text/html')
- """
- if self._HTTPConnection__state != _CS_REQ_STARTED:
- raise CannotSendHeader()
-
- str = '%s: %s\r\n' % (header, value)
- self.send(str)
-
-
- def endheaders(self):
- '''Indicate that the last header line has been sent to the server.'''
- if self._HTTPConnection__state == _CS_REQ_STARTED:
- self._HTTPConnection__state = _CS_REQ_SENT
- else:
- raise CannotSendHeader()
- self.send('\r\n')
-
-
- def request(self, method, url, body = None, headers = { }):
- '''Send a complete request to the server.'''
-
- try:
- self._send_request(method, url, body, headers)
- except socket.error:
- v = None
- if v[0] != 32 or not (self.auto_open):
- raise
-
- self._send_request(method, url, body, headers)
-
-
-
- def _send_request(self, method, url, body, headers):
- self.putrequest(method, url)
- if body:
- self.putheader('Content-Length', str(len(body)))
-
- for hdr, value in headers.items():
- self.putheader(hdr, value)
-
- self.endheaders()
-
-
- def getresponse(self):
- '''Get the response from the server.'''
- if self._HTTPConnection__response and self._HTTPConnection__response.isclosed():
- self._HTTPConnection__response = None
-
- if self._HTTPConnection__state != _CS_REQ_SENT or self._HTTPConnection__response:
- raise ResponseNotReady()
-
- if self.debuglevel > 0:
- response = self.response_class(self.sock, self.debuglevel)
- else:
- response = self.response_class(self.sock)
- response.begin()
- self._HTTPConnection__state = _CS_IDLE
- if response.will_close:
- self.close()
- else:
- self._HTTPConnection__response = response
- return response
-
-
-
- class FakeSocket:
-
- def __init__(self, sock, ssl):
- self._FakeSocket__sock = sock
- self._FakeSocket__ssl = ssl
-
-
- def makefile(self, mode, bufsize = None):
- """Return a readable file-like object with data from socket.
-
- This method offers only partial support for the makefile
- interface of a real socket. It only supports modes 'r' and
- 'rb' and the bufsize argument is ignored.
-
- The returned object contains *all* of the file data
- """
- if mode != 'r' and mode != 'rb':
- raise UnimplementedFileMode()
-
- msgbuf = ''
- while 1:
-
- try:
- msgbuf = msgbuf + self._FakeSocket__ssl.read()
- except socket.sslerror:
- msg = None
- break
-
- return StringIO(msgbuf)
-
-
- def send(self, stuff, flags = 0):
- return self._FakeSocket__ssl.write(stuff)
-
-
- def recv(self, len = 1024, flags = 0):
- return self._FakeSocket__ssl.read(len)
-
-
- def __getattr__(self, attr):
- return getattr(self._FakeSocket__sock, attr)
-
-
-
- class HTTPSConnection(HTTPConnection):
- '''This class allows communication via SSL.'''
- default_port = HTTPS_PORT
-
- def __init__(self, host, port = None, **x509):
- keys = x509.keys()
-
- try:
- keys.remove('key_file')
- except ValueError:
- pass
-
-
- try:
- keys.remove('cert_file')
- except ValueError:
- pass
-
- if keys:
- raise IllegalKeywordArgument()
-
- HTTPConnection.__init__(self, host, port)
- self.key_file = x509.get('key_file')
- self.cert_file = x509.get('cert_file')
-
-
- def connect(self):
- '''Connect to a host on a given (SSL) port.'''
- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- sock.connect((self.host, self.port))
- ssl = socket.ssl(sock, self.key_file, self.cert_file)
- self.sock = FakeSocket(sock, ssl)
-
-
-
- class HTTP:
- '''Compatibility class with httplib.py from 1.5.'''
- _http_vsn = 10
- _http_vsn_str = 'HTTP/1.0'
- debuglevel = 0
- _connection_class = HTTPConnection
-
- def __init__(self, host = '', port = None, **x509):
- '''Provide a default host, since the superclass requires one.'''
- if port == 0:
- port = None
-
- self._conn = self._connection_class(host, port)
- self.send = self._conn.send
- self.putrequest = self._conn.putrequest
- self.endheaders = self._conn.endheaders
- self._conn._http_vsn = self._http_vsn
- self._conn._http_vsn_str = self._http_vsn_str
- self.key_file = x509.get('key_file')
- self.cert_file = x509.get('cert_file')
- self.file = None
-
-
- def connect(self, host = None, port = None):
- """Accept arguments to set the host/port, since the superclass doesn't."""
- if host is not None:
- self._conn._set_hostport(host, port)
-
- self._conn.connect()
-
-
- def set_debuglevel(self, debuglevel):
- self._conn.set_debuglevel(debuglevel)
-
-
- def getfile(self):
- """Provide a getfile, since the superclass' does not use this concept."""
- return self.file
-
-
- def putheader(self, header, *values):
- '''The superclass allows only one value argument.'''
- self._conn.putheader(header, string.joinfields(values, '\r\n\t'))
-
-
- def getreply(self):
- '''Compat definition since superclass does not define it.
-
- Returns a tuple consisting of:
- - server status code (e.g. \'200\' if all goes well)
- - server "reason" corresponding to status code
- - any RFC822 headers in the response from the server
- '''
-
- try:
- response = self._conn.getresponse()
- except BadStatusLine:
- e = None
- self.file = self._conn.sock.makefile('rb', 0)
- self.close()
- self.headers = None
- return (-1, e.line, None)
-
- self.headers = response.msg
- self.file = response.fp
- return (response.status, response.reason, response.msg)
-
-
- def close(self):
- self._conn.close()
- self.file = None
-
-
- if hasattr(socket, 'ssl'):
-
- class HTTPS(HTTP):
- '''Compatibility with 1.5 httplib interface
-
- Python 1.5.2 did not have an HTTPS class, but it defined an
- interface for sending http requests that is also useful for
- https.
- '''
- _connection_class = HTTPSConnection
-
-
-
- class HTTPException(Exception):
- pass
-
-
- class NotConnected(HTTPException):
- pass
-
-
- class UnknownProtocol(HTTPException):
-
- def __init__(self, version):
- self.version = version
-
-
-
- class UnknownTransferEncoding(HTTPException):
- pass
-
-
- class IllegalKeywordArgument(HTTPException):
- pass
-
-
- class UnimplementedFileMode(HTTPException):
- pass
-
-
- class IncompleteRead(HTTPException):
-
- def __init__(self, partial):
- self.partial = partial
-
-
-
- class ImproperConnectionState(HTTPException):
- pass
-
-
- class CannotSendRequest(ImproperConnectionState):
- pass
-
-
- class CannotSendHeader(ImproperConnectionState):
- pass
-
-
- class ResponseNotReady(ImproperConnectionState):
- pass
-
-
- class BadStatusLine(HTTPException):
-
- def __init__(self, line):
- self.line = line
-
-
- error = HTTPException
-
- def test():
- '''Test this module.
-
- The test consists of retrieving and displaying the Python
- home page, along with the error code and error string returned
- by the www.python.org server.
- '''
- import sys
- import getopt
- (opts, args) = getopt.getopt(sys.argv[1:], 'd')
- dl = 0
- for o, a in opts:
- pass
-
- host = 'www.python.org'
- selector = '/'
- if args[0:]:
- host = args[0]
-
- if args[1:]:
- selector = args[1]
-
- h = HTTP()
- h.set_debuglevel(dl)
- h.connect(host)
- h.putrequest('GET', selector)
- h.endheaders()
- (status, reason, headers) = h.getreply()
- print 'status =', status
- print 'reason =', reason
- print
- if headers:
- for header in headers.headers:
- print string.strip(header)
-
-
- print
- print h.getfile().read()
- if hasattr(socket, 'ssl'):
- host = 'sourceforge.net'
- hs = HTTPS()
- hs.connect(host)
- hs.putrequest('GET', selector)
- hs.endheaders()
- (status, reason, headers) = hs.getreply()
- print 'status =', status
- print 'reason =', reason
- print
- if headers:
- for header in headers.headers:
- print string.strip(header)
-
-
- print
- print hs.getfile().read()
-
-
- if __name__ == '__main__':
- test()
-
-