10a8c90248264a8b26970b4473770bcc3df8515fJosh Gao# Wrapper module for _socket, providing some additional facilities
20a8c90248264a8b26970b4473770bcc3df8515fJosh Gao# implemented in Python.
30a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
40a8c90248264a8b26970b4473770bcc3df8515fJosh Gao"""\
50a8c90248264a8b26970b4473770bcc3df8515fJosh GaoThis module provides socket operations and some related functions.
60a8c90248264a8b26970b4473770bcc3df8515fJosh GaoOn Unix, it supports IP (Internet Protocol) and Unix domain sockets.
70a8c90248264a8b26970b4473770bcc3df8515fJosh GaoOn other systems, it only supports IP. Functions specific for a
80a8c90248264a8b26970b4473770bcc3df8515fJosh Gaosocket are available as methods of the socket object.
90a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
100a8c90248264a8b26970b4473770bcc3df8515fJosh GaoFunctions:
110a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
120a8c90248264a8b26970b4473770bcc3df8515fJosh Gaosocket() -- create a new socket object
130a8c90248264a8b26970b4473770bcc3df8515fJosh Gaosocketpair() -- create a pair of new socket objects [*]
140a8c90248264a8b26970b4473770bcc3df8515fJosh Gaofromfd() -- create a socket object from an open file descriptor [*]
150a8c90248264a8b26970b4473770bcc3df8515fJosh Gaogethostname() -- return the current hostname
160a8c90248264a8b26970b4473770bcc3df8515fJosh Gaogethostbyname() -- map a hostname to its IP number
170a8c90248264a8b26970b4473770bcc3df8515fJosh Gaogethostbyaddr() -- map an IP number or hostname to DNS info
180a8c90248264a8b26970b4473770bcc3df8515fJosh Gaogetservbyname() -- map a service name and a protocol name to a port number
190a8c90248264a8b26970b4473770bcc3df8515fJosh Gaogetprotobyname() -- map a protocol name (e.g. 'tcp') to a number
200a8c90248264a8b26970b4473770bcc3df8515fJosh Gaontohs(), ntohl() -- convert 16, 32 bit int from network to host byte order
210a8c90248264a8b26970b4473770bcc3df8515fJosh Gaohtons(), htonl() -- convert 16, 32 bit int from host to network byte order
220a8c90248264a8b26970b4473770bcc3df8515fJosh Gaoinet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format
230a8c90248264a8b26970b4473770bcc3df8515fJosh Gaoinet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89)
240a8c90248264a8b26970b4473770bcc3df8515fJosh Gaossl() -- secure socket layer support (only available if configured)
250a8c90248264a8b26970b4473770bcc3df8515fJosh Gaosocket.getdefaulttimeout() -- get the default timeout value
260a8c90248264a8b26970b4473770bcc3df8515fJosh Gaosocket.setdefaulttimeout() -- set the default timeout value
270a8c90248264a8b26970b4473770bcc3df8515fJosh Gaocreate_connection() -- connects to an address, with an optional timeout and
280a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                       optional source address.
290a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
300a8c90248264a8b26970b4473770bcc3df8515fJosh Gao [*] not available on all platforms!
310a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
320a8c90248264a8b26970b4473770bcc3df8515fJosh GaoSpecial objects:
330a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
340a8c90248264a8b26970b4473770bcc3df8515fJosh GaoSocketType -- type object for socket objects
350a8c90248264a8b26970b4473770bcc3df8515fJosh Gaoerror -- exception raised for I/O errors
360a8c90248264a8b26970b4473770bcc3df8515fJosh Gaohas_ipv6 -- boolean value indicating if IPv6 is supported
370a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
380a8c90248264a8b26970b4473770bcc3df8515fJosh GaoInteger constants:
390a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
400a8c90248264a8b26970b4473770bcc3df8515fJosh GaoAF_INET, AF_UNIX -- socket domains (first argument to socket() call)
410a8c90248264a8b26970b4473770bcc3df8515fJosh GaoSOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument)
420a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
430a8c90248264a8b26970b4473770bcc3df8515fJosh GaoMany other constants may be defined; these may be used in calls to
440a8c90248264a8b26970b4473770bcc3df8515fJosh Gaothe setsockopt() and getsockopt() methods.
450a8c90248264a8b26970b4473770bcc3df8515fJosh Gao"""
460a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
470a8c90248264a8b26970b4473770bcc3df8515fJosh Gaoimport _socket
480a8c90248264a8b26970b4473770bcc3df8515fJosh Gaofrom _socket import *
490a8c90248264a8b26970b4473770bcc3df8515fJosh Gaofrom functools import partial
500a8c90248264a8b26970b4473770bcc3df8515fJosh Gaofrom types import MethodType
510a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
520a8c90248264a8b26970b4473770bcc3df8515fJosh Gaotry:
530a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    import _ssl
540a8c90248264a8b26970b4473770bcc3df8515fJosh Gaoexcept ImportError:
550a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    # no SSL support
560a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    pass
570a8c90248264a8b26970b4473770bcc3df8515fJosh Gaoelse:
580a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    def ssl(sock, keyfile=None, certfile=None):
590a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        # we do an internal import here because the ssl
600a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        # module imports the socket module
610a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        import ssl as _realssl
620a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        warnings.warn("socket.ssl() is deprecated.  Use ssl.wrap_socket() instead.",
630a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                      DeprecationWarning, stacklevel=2)
640a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        return _realssl.sslwrap_simple(sock, keyfile, certfile)
650a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
660a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    # we need to import the same constants we used to...
670a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    from _ssl import SSLError as sslerror
680a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    from _ssl import \
690a8c90248264a8b26970b4473770bcc3df8515fJosh Gao         RAND_add, \
700a8c90248264a8b26970b4473770bcc3df8515fJosh Gao         RAND_egd, \
710a8c90248264a8b26970b4473770bcc3df8515fJosh Gao         RAND_status, \
720a8c90248264a8b26970b4473770bcc3df8515fJosh Gao         SSL_ERROR_ZERO_RETURN, \
730a8c90248264a8b26970b4473770bcc3df8515fJosh Gao         SSL_ERROR_WANT_READ, \
740a8c90248264a8b26970b4473770bcc3df8515fJosh Gao         SSL_ERROR_WANT_WRITE, \
750a8c90248264a8b26970b4473770bcc3df8515fJosh Gao         SSL_ERROR_WANT_X509_LOOKUP, \
760a8c90248264a8b26970b4473770bcc3df8515fJosh Gao         SSL_ERROR_SYSCALL, \
770a8c90248264a8b26970b4473770bcc3df8515fJosh Gao         SSL_ERROR_SSL, \
780a8c90248264a8b26970b4473770bcc3df8515fJosh Gao         SSL_ERROR_WANT_CONNECT, \
790a8c90248264a8b26970b4473770bcc3df8515fJosh Gao         SSL_ERROR_EOF, \
800a8c90248264a8b26970b4473770bcc3df8515fJosh Gao         SSL_ERROR_INVALID_ERROR_CODE
810a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
820a8c90248264a8b26970b4473770bcc3df8515fJosh Gaoimport os, sys, warnings
830a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
840a8c90248264a8b26970b4473770bcc3df8515fJosh Gaotry:
850a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    from cStringIO import StringIO
860a8c90248264a8b26970b4473770bcc3df8515fJosh Gaoexcept ImportError:
870a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    from StringIO import StringIO
880a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
890a8c90248264a8b26970b4473770bcc3df8515fJosh Gaotry:
900a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    import errno
910a8c90248264a8b26970b4473770bcc3df8515fJosh Gaoexcept ImportError:
920a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    errno = None
930a8c90248264a8b26970b4473770bcc3df8515fJosh GaoEBADF = getattr(errno, 'EBADF', 9)
940a8c90248264a8b26970b4473770bcc3df8515fJosh GaoEINTR = getattr(errno, 'EINTR', 4)
950a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
960a8c90248264a8b26970b4473770bcc3df8515fJosh Gao__all__ = ["getfqdn", "create_connection"]
970a8c90248264a8b26970b4473770bcc3df8515fJosh Gao__all__.extend(os._get_exports_list(_socket))
980a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
990a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
1000a8c90248264a8b26970b4473770bcc3df8515fJosh Gao_realsocket = socket
1010a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
1020a8c90248264a8b26970b4473770bcc3df8515fJosh Gao# WSA error codes
1030a8c90248264a8b26970b4473770bcc3df8515fJosh Gaoif sys.platform.lower().startswith("win"):
1040a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    errorTab = {}
1050a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    errorTab[10004] = "The operation was interrupted."
1060a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    errorTab[10009] = "A bad file handle was passed."
1070a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    errorTab[10013] = "Permission denied."
1080a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    errorTab[10014] = "A fault occurred on the network??" # WSAEFAULT
1090a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    errorTab[10022] = "An invalid operation was attempted."
1100a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    errorTab[10035] = "The socket operation would block"
1110a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    errorTab[10036] = "A blocking operation is already in progress."
1120a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    errorTab[10048] = "The network address is in use."
1130a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    errorTab[10054] = "The connection has been reset."
1140a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    errorTab[10058] = "The network has been shut down."
1150a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    errorTab[10060] = "The operation timed out."
1160a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    errorTab[10061] = "Connection refused."
1170a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    errorTab[10063] = "The name is too long."
1180a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    errorTab[10064] = "The host is down."
1190a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    errorTab[10065] = "The host is unreachable."
1200a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    __all__.append("errorTab")
1210a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
1220a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
1230a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
1240a8c90248264a8b26970b4473770bcc3df8515fJosh Gaodef getfqdn(name=''):
1250a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    """Get fully qualified domain name from name.
1260a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
1270a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    An empty argument is interpreted as meaning the local host.
1280a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
1290a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    First the hostname returned by gethostbyaddr() is checked, then
1300a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    possibly existing aliases. In case no FQDN is available, hostname
1310a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    from gethostname() is returned.
1320a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    """
1330a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    name = name.strip()
1340a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    if not name or name == '0.0.0.0':
1350a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        name = gethostname()
1360a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    try:
1370a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        hostname, aliases, ipaddrs = gethostbyaddr(name)
1380a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    except error:
1390a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        pass
1400a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    else:
1410a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        aliases.insert(0, hostname)
1420a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        for name in aliases:
1430a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            if '.' in name:
1440a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                break
1450a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        else:
1460a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            name = hostname
1470a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    return name
1480a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
1490a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
1500a8c90248264a8b26970b4473770bcc3df8515fJosh Gao_socketmethods = (
1510a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    'bind', 'connect', 'connect_ex', 'fileno', 'listen',
1520a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    'getpeername', 'getsockname', 'getsockopt', 'setsockopt',
1530a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    'sendall', 'setblocking',
1540a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    'settimeout', 'gettimeout', 'shutdown')
1550a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
1560a8c90248264a8b26970b4473770bcc3df8515fJosh Gaoif os.name == "nt":
1570a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    _socketmethods = _socketmethods + ('ioctl',)
1580a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
1590a8c90248264a8b26970b4473770bcc3df8515fJosh Gaoif sys.platform == "riscos":
1600a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    _socketmethods = _socketmethods + ('sleeptaskw',)
1610a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
1620a8c90248264a8b26970b4473770bcc3df8515fJosh Gao# All the method names that must be delegated to either the real socket
1630a8c90248264a8b26970b4473770bcc3df8515fJosh Gao# object or the _closedsocket object.
1640a8c90248264a8b26970b4473770bcc3df8515fJosh Gao_delegate_methods = ("recv", "recvfrom", "recv_into", "recvfrom_into",
1650a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                     "send", "sendto")
1660a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
1670a8c90248264a8b26970b4473770bcc3df8515fJosh Gaoclass _closedsocket(object):
1680a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    __slots__ = []
1690a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    def _dummy(*args):
1700a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        raise error(EBADF, 'Bad file descriptor')
1710a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    # All _delegate_methods must also be initialized here.
1720a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    send = recv = recv_into = sendto = recvfrom = recvfrom_into = _dummy
1730a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    __getattr__ = _dummy
1740a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
1750a8c90248264a8b26970b4473770bcc3df8515fJosh Gao# Wrapper around platform socket objects. This implements
1760a8c90248264a8b26970b4473770bcc3df8515fJosh Gao# a platform-independent dup() functionality. The
1770a8c90248264a8b26970b4473770bcc3df8515fJosh Gao# implementation currently relies on reference counting
1780a8c90248264a8b26970b4473770bcc3df8515fJosh Gao# to close the underlying socket object.
1790a8c90248264a8b26970b4473770bcc3df8515fJosh Gaoclass _socketobject(object):
1800a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
1810a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    __doc__ = _realsocket.__doc__
1820a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
1830a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    __slots__ = ["_sock", "__weakref__"] + list(_delegate_methods)
1840a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
1850a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, _sock=None):
1860a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        if _sock is None:
1870a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            _sock = _realsocket(family, type, proto)
1880a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        self._sock = _sock
1890a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        for method in _delegate_methods:
1900a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            setattr(self, method, getattr(_sock, method))
1910a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
1920a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    def close(self, _closedsocket=_closedsocket,
1930a8c90248264a8b26970b4473770bcc3df8515fJosh Gao              _delegate_methods=_delegate_methods, setattr=setattr):
1940a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        # This function should not reference any globals. See issue #808164.
1950a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        self._sock = _closedsocket()
1960a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        dummy = self._sock._dummy
1970a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        for method in _delegate_methods:
1980a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            setattr(self, method, dummy)
1990a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    close.__doc__ = _realsocket.close.__doc__
2000a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
2010a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    def accept(self):
2020a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        sock, addr = self._sock.accept()
2030a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        return _socketobject(_sock=sock), addr
2040a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    accept.__doc__ = _realsocket.accept.__doc__
2050a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
2060a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    def dup(self):
2070a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        """dup() -> socket object
2080a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
2090a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        Return a new socket object connected to the same system resource."""
2100a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        return _socketobject(_sock=self._sock)
2110a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
2120a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    def makefile(self, mode='r', bufsize=-1):
2130a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        """makefile([mode[, bufsize]]) -> file object
2140a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
2150a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        Return a regular file object corresponding to the socket.  The mode
2160a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        and bufsize arguments are as for the built-in open() function."""
2170a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        return _fileobject(self._sock, mode, bufsize)
2180a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
2190a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    family = property(lambda self: self._sock.family, doc="the socket family")
2200a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    type = property(lambda self: self._sock.type, doc="the socket type")
2210a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    proto = property(lambda self: self._sock.proto, doc="the socket protocol")
2220a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
2230a8c90248264a8b26970b4473770bcc3df8515fJosh Gaodef meth(name,self,*args):
2240a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    return getattr(self._sock,name)(*args)
2250a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
2260a8c90248264a8b26970b4473770bcc3df8515fJosh Gaofor _m in _socketmethods:
2270a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    p = partial(meth,_m)
2280a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    p.__name__ = _m
2290a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    p.__doc__ = getattr(_realsocket,_m).__doc__
2300a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    m = MethodType(p,None,_socketobject)
2310a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    setattr(_socketobject,_m,m)
2320a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
2330a8c90248264a8b26970b4473770bcc3df8515fJosh Gaosocket = SocketType = _socketobject
2340a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
2350a8c90248264a8b26970b4473770bcc3df8515fJosh Gaoclass _fileobject(object):
2360a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    """Faux file object attached to a socket object."""
2370a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
2380a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    default_bufsize = 8192
2390a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    name = "<socket>"
2400a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
2410a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    __slots__ = ["mode", "bufsize", "softspace",
2420a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                 # "closed" is a property, see below
2430a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                 "_sock", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf", "_wbuf_len",
2440a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                 "_close"]
2450a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
2460a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    def __init__(self, sock, mode='rb', bufsize=-1, close=False):
2470a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        self._sock = sock
2480a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        self.mode = mode # Not actually used in this version
2490a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        if bufsize < 0:
2500a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            bufsize = self.default_bufsize
2510a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        self.bufsize = bufsize
2520a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        self.softspace = False
2530a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        # _rbufsize is the suggested recv buffer size.  It is *strictly*
2540a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        # obeyed within readline() for recv calls.  If it is larger than
2550a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        # default_bufsize it will be used for recv calls within read().
2560a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        if bufsize == 0:
2570a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            self._rbufsize = 1
2580a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        elif bufsize == 1:
2590a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            self._rbufsize = self.default_bufsize
2600a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        else:
2610a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            self._rbufsize = bufsize
2620a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        self._wbufsize = bufsize
2630a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        # We use StringIO for the read buffer to avoid holding a list
2640a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        # of variously sized string objects which have been known to
2650a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        # fragment the heap due to how they are malloc()ed and often
2660a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        # realloc()ed down much smaller than their original allocation.
2670a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        self._rbuf = StringIO()
2680a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        self._wbuf = [] # A list of strings
2690a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        self._wbuf_len = 0
2700a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        self._close = close
2710a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
2720a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    def _getclosed(self):
2730a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        return self._sock is None
2740a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    closed = property(_getclosed, doc="True if the file is closed")
2750a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
2760a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    def close(self):
2770a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        try:
2780a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            if self._sock:
2790a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                self.flush()
2800a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        finally:
2810a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            if self._close:
2820a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                self._sock.close()
2830a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            self._sock = None
2840a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
2850a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    def __del__(self):
2860a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        try:
2870a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            self.close()
2880a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        except:
2890a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            # close() may fail if __init__ didn't complete
2900a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            pass
2910a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
2920a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    def flush(self):
2930a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        if self._wbuf:
2940a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            data = "".join(self._wbuf)
2950a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            self._wbuf = []
2960a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            self._wbuf_len = 0
2970a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            buffer_size = max(self._rbufsize, self.default_bufsize)
2980a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            data_size = len(data)
2990a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            write_offset = 0
3000a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            view = memoryview(data)
3010a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            try:
3020a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                while write_offset < data_size:
3030a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    self._sock.sendall(view[write_offset:write_offset+buffer_size])
3040a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    write_offset += buffer_size
3050a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            finally:
3060a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                if write_offset < data_size:
3070a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    remainder = data[write_offset:]
3080a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    del view, data  # explicit free
3090a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    self._wbuf.append(remainder)
3100a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    self._wbuf_len = len(remainder)
3110a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
3120a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    def fileno(self):
3130a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        return self._sock.fileno()
3140a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
3150a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    def write(self, data):
3160a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        data = str(data) # XXX Should really reject non-string non-buffers
3170a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        if not data:
3180a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            return
3190a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        self._wbuf.append(data)
3200a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        self._wbuf_len += len(data)
3210a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        if (self._wbufsize == 0 or
3220a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            (self._wbufsize == 1 and '\n' in data) or
3230a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            (self._wbufsize > 1 and self._wbuf_len >= self._wbufsize)):
3240a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            self.flush()
3250a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
3260a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    def writelines(self, list):
3270a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        # XXX We could do better here for very long lists
3280a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        # XXX Should really reject non-string non-buffers
3290a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        lines = filter(None, map(str, list))
3300a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        self._wbuf_len += sum(map(len, lines))
3310a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        self._wbuf.extend(lines)
3320a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        if (self._wbufsize <= 1 or
3330a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            self._wbuf_len >= self._wbufsize):
3340a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            self.flush()
3350a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
3360a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    def read(self, size=-1):
3370a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        # Use max, disallow tiny reads in a loop as they are very inefficient.
3380a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        # We never leave read() with any leftover data from a new recv() call
3390a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        # in our internal buffer.
3400a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        rbufsize = max(self._rbufsize, self.default_bufsize)
3410a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        # Our use of StringIO rather than lists of string objects returned by
3420a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        # recv() minimizes memory usage and fragmentation that occurs when
3430a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        # rbufsize is large compared to the typical return value of recv().
3440a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        buf = self._rbuf
3450a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        buf.seek(0, 2)  # seek end
3460a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        if size < 0:
3470a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            # Read until EOF
3480a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            self._rbuf = StringIO()  # reset _rbuf.  we consume it via buf.
3490a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            while True:
3500a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                try:
3510a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    data = self._sock.recv(rbufsize)
3520a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                except error, e:
3530a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    if e.args[0] == EINTR:
3540a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                        continue
3550a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    raise
3560a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                if not data:
3570a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    break
3580a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                buf.write(data)
3590a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            return buf.getvalue()
3600a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        else:
3610a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            # Read until size bytes or EOF seen, whichever comes first
3620a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            buf_len = buf.tell()
3630a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            if buf_len >= size:
3640a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                # Already have size bytes in our buffer?  Extract and return.
3650a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                buf.seek(0)
3660a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                rv = buf.read(size)
3670a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                self._rbuf = StringIO()
3680a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                self._rbuf.write(buf.read())
3690a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                return rv
3700a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
3710a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            self._rbuf = StringIO()  # reset _rbuf.  we consume it via buf.
3720a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            while True:
3730a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                left = size - buf_len
3740a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                # recv() will malloc the amount of memory given as its
3750a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                # parameter even though it often returns much less data
3760a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                # than that.  The returned data string is short lived
3770a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                # as we copy it into a StringIO and free it.  This avoids
3780a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                # fragmentation issues on many platforms.
3790a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                try:
3800a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    data = self._sock.recv(left)
3810a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                except error, e:
3820a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    if e.args[0] == EINTR:
3830a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                        continue
3840a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    raise
3850a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                if not data:
3860a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    break
3870a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                n = len(data)
3880a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                if n == size and not buf_len:
3890a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    # Shortcut.  Avoid buffer data copies when:
3900a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    # - We have no data in our buffer.
3910a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    # AND
3920a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    # - Our call to recv returned exactly the
3930a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    #   number of bytes we were asked to read.
3940a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    return data
3950a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                if n == left:
3960a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    buf.write(data)
3970a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    del data  # explicit free
3980a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    break
3990a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                assert n <= left, "recv(%d) returned %d bytes" % (left, n)
4000a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                buf.write(data)
4010a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                buf_len += n
4020a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                del data  # explicit free
4030a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                #assert buf_len == buf.tell()
4040a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            return buf.getvalue()
4050a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
4060a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    def readline(self, size=-1):
4070a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        buf = self._rbuf
4080a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        buf.seek(0, 2)  # seek end
4090a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        if buf.tell() > 0:
4100a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            # check if we already have it in our buffer
4110a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            buf.seek(0)
4120a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            bline = buf.readline(size)
4130a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            if bline.endswith('\n') or len(bline) == size:
4140a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                self._rbuf = StringIO()
4150a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                self._rbuf.write(buf.read())
4160a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                return bline
4170a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            del bline
4180a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        if size < 0:
4190a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            # Read until \n or EOF, whichever comes first
4200a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            if self._rbufsize <= 1:
4210a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                # Speed up unbuffered case
4220a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                buf.seek(0)
4230a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                buffers = [buf.read()]
4240a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                self._rbuf = StringIO()  # reset _rbuf.  we consume it via buf.
4250a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                data = None
4260a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                recv = self._sock.recv
4270a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                while True:
4280a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    try:
4290a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                        while data != "\n":
4300a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                            data = recv(1)
4310a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                            if not data:
4320a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                                break
4330a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                            buffers.append(data)
4340a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    except error, e:
4350a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                        # The try..except to catch EINTR was moved outside the
4360a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                        # recv loop to avoid the per byte overhead.
4370a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                        if e.args[0] == EINTR:
4380a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                            continue
4390a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                        raise
4400a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    break
4410a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                return "".join(buffers)
4420a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
4430a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            buf.seek(0, 2)  # seek end
4440a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            self._rbuf = StringIO()  # reset _rbuf.  we consume it via buf.
4450a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            while True:
4460a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                try:
4470a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    data = self._sock.recv(self._rbufsize)
4480a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                except error, e:
4490a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    if e.args[0] == EINTR:
4500a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                        continue
4510a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    raise
4520a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                if not data:
4530a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    break
4540a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                nl = data.find('\n')
4550a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                if nl >= 0:
4560a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    nl += 1
4570a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    buf.write(data[:nl])
4580a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    self._rbuf.write(data[nl:])
4590a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    del data
4600a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    break
4610a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                buf.write(data)
4620a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            return buf.getvalue()
4630a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        else:
4640a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            # Read until size bytes or \n or EOF seen, whichever comes first
4650a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            buf.seek(0, 2)  # seek end
4660a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            buf_len = buf.tell()
4670a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            if buf_len >= size:
4680a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                buf.seek(0)
4690a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                rv = buf.read(size)
4700a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                self._rbuf = StringIO()
4710a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                self._rbuf.write(buf.read())
4720a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                return rv
4730a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            self._rbuf = StringIO()  # reset _rbuf.  we consume it via buf.
4740a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            while True:
4750a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                try:
4760a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    data = self._sock.recv(self._rbufsize)
4770a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                except error, e:
4780a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    if e.args[0] == EINTR:
4790a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                        continue
4800a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    raise
4810a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                if not data:
4820a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    break
4830a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                left = size - buf_len
4840a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                # did we just receive a newline?
4850a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                nl = data.find('\n', 0, left)
4860a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                if nl >= 0:
4870a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    nl += 1
4880a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    # save the excess data to _rbuf
4890a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    self._rbuf.write(data[nl:])
4900a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    if buf_len:
4910a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                        buf.write(data[:nl])
4920a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                        break
4930a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    else:
4940a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                        # Shortcut.  Avoid data copy through buf when returning
4950a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                        # a substring of our first recv().
4960a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                        return data[:nl]
4970a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                n = len(data)
4980a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                if n == size and not buf_len:
4990a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    # Shortcut.  Avoid data copy through buf when
5000a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    # returning exactly all of our first recv().
5010a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    return data
5020a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                if n >= left:
5030a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    buf.write(data[:left])
5040a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    self._rbuf.write(data[left:])
5050a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                    break
5060a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                buf.write(data)
5070a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                buf_len += n
5080a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                #assert buf_len == buf.tell()
5090a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            return buf.getvalue()
5100a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
5110a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    def readlines(self, sizehint=0):
5120a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        total = 0
5130a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        list = []
5140a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        while True:
5150a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            line = self.readline()
5160a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            if not line:
5170a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                break
5180a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            list.append(line)
5190a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            total += len(line)
5200a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            if sizehint and total >= sizehint:
5210a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                break
5220a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        return list
5230a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
5240a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    # Iterator protocols
5250a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
5260a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    def __iter__(self):
5270a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        return self
5280a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
5290a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    def next(self):
5300a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        line = self.readline()
5310a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        if not line:
5320a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            raise StopIteration
5330a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        return line
5340a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
5350a8c90248264a8b26970b4473770bcc3df8515fJosh Gao_GLOBAL_DEFAULT_TIMEOUT = object()
5360a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
5370a8c90248264a8b26970b4473770bcc3df8515fJosh Gaodef create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT,
5380a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                      source_address=None):
5390a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    """Connect to *address* and return the socket object.
5400a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
5410a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    Convenience function.  Connect to *address* (a 2-tuple ``(host,
5420a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    port)``) and return the socket object.  Passing the optional
5430a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    *timeout* parameter will set the timeout on the socket instance
5440a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    before attempting to connect.  If no *timeout* is supplied, the
5450a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    global default timeout setting returned by :func:`getdefaulttimeout`
5460a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    is used.  If *source_address* is set it must be a tuple of (host, port)
5470a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    for the socket to bind as a source address before making the connection.
5480a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    An host of '' or port 0 tells the OS to use the default.
5490a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    """
5500a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
5510a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    host, port = address
5520a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    err = None
5530a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
5540a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        af, socktype, proto, canonname, sa = res
5550a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        sock = None
5560a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        try:
5570a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            sock = socket(af, socktype, proto)
5580a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
5590a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                sock.settimeout(timeout)
5600a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            if source_address:
5610a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                sock.bind(source_address)
5620a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            sock.connect(sa)
5630a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            return sock
5640a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
5650a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        except error as _:
5660a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            err = _
5670a8c90248264a8b26970b4473770bcc3df8515fJosh Gao            if sock is not None:
5680a8c90248264a8b26970b4473770bcc3df8515fJosh Gao                sock.close()
5690a8c90248264a8b26970b4473770bcc3df8515fJosh Gao
5700a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    if err is not None:
5710a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        raise err
5720a8c90248264a8b26970b4473770bcc3df8515fJosh Gao    else:
5730a8c90248264a8b26970b4473770bcc3df8515fJosh Gao        raise error("getaddrinfo returns an empty list")
574