blob: 24ef3af3ff43785ebf34aefbca2e007f7aba279d [file] [log] [blame]
Fred Drakea6070f02000-08-16 14:14:32 +00001# Wrapper module for _socket, providing some additional facilities
2# implemented in Python.
3
4"""\
5This module provides socket operations and some related functions.
6On Unix, it supports IP (Internet Protocol) and Unix domain sockets.
Tim Peters495ad3c2001-01-15 01:36:40 +00007On other systems, it only supports IP. Functions specific for a
Martin v. Löwisaf484d52000-09-30 11:34:30 +00008socket are available as methods of the socket object.
Fred Drakea6070f02000-08-16 14:14:32 +00009
10Functions:
11
12socket() -- create a new socket object
Dave Cole331708b2004-08-09 04:51:41 +000013socketpair() -- create a pair of new socket objects [*]
Fred Drakea6070f02000-08-16 14:14:32 +000014fromfd() -- create a socket object from an open file descriptor [*]
15gethostname() -- return the current hostname
16gethostbyname() -- map a hostname to its IP number
17gethostbyaddr() -- map an IP number or hostname to DNS info
18getservbyname() -- map a service name and a protocol name to a port number
19getprotobyname() -- mape a protocol name (e.g. 'tcp') to a number
20ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order
21htons(), htonl() -- convert 16, 32 bit int from host to network byte order
22inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format
23inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89)
24ssl() -- secure socket layer support (only available if configured)
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +000025socket.getdefaulttimeout() -- get the default timeout value
26socket.setdefaulttimeout() -- set the default timeout value
Neal Norwitz0d4c06e2007-04-25 06:30:05 +000027create_connection() -- connects to an address, with an optional timeout
Fred Drakea6070f02000-08-16 14:14:32 +000028
29 [*] not available on all platforms!
30
31Special objects:
32
33SocketType -- type object for socket objects
34error -- exception raised for I/O errors
Guido van Rossum47dfa4a2003-04-25 05:48:32 +000035has_ipv6 -- boolean value indicating if IPv6 is supported
Fred Drakea6070f02000-08-16 14:14:32 +000036
37Integer constants:
38
39AF_INET, AF_UNIX -- socket domains (first argument to socket() call)
40SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument)
41
42Many other constants may be defined; these may be used in calls to
43the setsockopt() and getsockopt() methods.
44"""
45
Tim Peters18e67782002-02-17 04:25:24 +000046import _socket
Fred Drakea6070f02000-08-16 14:14:32 +000047from _socket import *
Tim Peters18e67782002-02-17 04:25:24 +000048
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000049try:
Guido van Rossumde7cade2002-08-08 15:25:28 +000050 import _ssl
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000051except ImportError:
Bill Janssen426ea0a2007-08-29 22:35:05 +000052 # no SSL support
Guido van Rossumc18993f2002-08-08 15:16:20 +000053 pass
Bill Janssen426ea0a2007-08-29 22:35:05 +000054else:
55 def ssl(sock, keyfile=None, certfile=None):
56 # we do an internal import here because the ssl
57 # module imports the socket module
58 import ssl as _realssl
Bill Janssen98d19da2007-09-10 21:51:02 +000059 warnings.warn("socket.ssl() is deprecated. Use ssl.wrap_socket() instead.",
Bill Janssen426ea0a2007-08-29 22:35:05 +000060 DeprecationWarning, stacklevel=2)
61 return _realssl.sslwrap_simple(sock, keyfile, certfile)
Fred Drakea6070f02000-08-16 14:14:32 +000062
Bill Janssen426ea0a2007-08-29 22:35:05 +000063 # we need to import the same constants we used to...
Bill Janssen98d19da2007-09-10 21:51:02 +000064 from _ssl import SSLError as sslerror
Bill Janssen426ea0a2007-08-29 22:35:05 +000065 from _ssl import \
Bill Janssen426ea0a2007-08-29 22:35:05 +000066 RAND_add, \
67 RAND_egd, \
68 RAND_status, \
69 SSL_ERROR_ZERO_RETURN, \
70 SSL_ERROR_WANT_READ, \
71 SSL_ERROR_WANT_WRITE, \
72 SSL_ERROR_WANT_X509_LOOKUP, \
73 SSL_ERROR_SYSCALL, \
74 SSL_ERROR_SSL, \
75 SSL_ERROR_WANT_CONNECT, \
76 SSL_ERROR_EOF, \
77 SSL_ERROR_INVALID_ERROR_CODE
78
79import os, sys, warnings
Fred Drakea6070f02000-08-16 14:14:32 +000080
Fred Drake70d566b2003-04-29 19:50:25 +000081try:
Gregory P. Smithf8cc6402008-05-02 07:26:52 +000082 from cStringIO import StringIO
83except ImportError:
84 from StringIO import StringIO
85
86try:
Fred Drake70d566b2003-04-29 19:50:25 +000087 from errno import EBADF
88except ImportError:
89 EBADF = 9
90
Skip Montanaro0de65802001-02-15 22:15:14 +000091__all__ = ["getfqdn"]
Skip Montanaro0de65802001-02-15 22:15:14 +000092__all__.extend(os._get_exports_list(_socket))
Bill Janssen426ea0a2007-08-29 22:35:05 +000093
Skip Montanaro0de65802001-02-15 22:15:14 +000094
Guido van Rossumc18993f2002-08-08 15:16:20 +000095_realsocket = socket
Fred Drakea6070f02000-08-16 14:14:32 +000096
97# WSA error codes
98if sys.platform.lower().startswith("win"):
99 errorTab = {}
100 errorTab[10004] = "The operation was interrupted."
101 errorTab[10009] = "A bad file handle was passed."
102 errorTab[10013] = "Permission denied."
103 errorTab[10014] = "A fault occurred on the network??" # WSAEFAULT
104 errorTab[10022] = "An invalid operation was attempted."
105 errorTab[10035] = "The socket operation would block"
106 errorTab[10036] = "A blocking operation is already in progress."
107 errorTab[10048] = "The network address is in use."
108 errorTab[10054] = "The connection has been reset."
109 errorTab[10058] = "The network has been shut down."
110 errorTab[10060] = "The operation timed out."
111 errorTab[10061] = "Connection refused."
112 errorTab[10063] = "The name is too long."
113 errorTab[10064] = "The host is down."
114 errorTab[10065] = "The host is unreachable."
Skip Montanaro64de1a42001-03-18 19:53:21 +0000115 __all__.append("errorTab")
Guido van Rossumde7cade2002-08-08 15:25:28 +0000116
Fred Drakea6070f02000-08-16 14:14:32 +0000117
118
119def getfqdn(name=''):
120 """Get fully qualified domain name from name.
121
122 An empty argument is interpreted as meaning the local host.
123
124 First the hostname returned by gethostbyaddr() is checked, then
125 possibly existing aliases. In case no FQDN is available, hostname
Brett Cannon01668a12005-03-11 00:04:17 +0000126 from gethostname() is returned.
Fred Drakea6070f02000-08-16 14:14:32 +0000127 """
128 name = name.strip()
Peter Schneider-Kamp2d2785a2000-08-16 20:30:21 +0000129 if not name or name == '0.0.0.0':
Fred Drakea6070f02000-08-16 14:14:32 +0000130 name = gethostname()
131 try:
132 hostname, aliases, ipaddrs = gethostbyaddr(name)
133 except error:
134 pass
135 else:
136 aliases.insert(0, hostname)
137 for name in aliases:
138 if '.' in name:
139 break
140 else:
141 name = hostname
142 return name
143
144
Guido van Rossume5e50592001-08-18 01:23:20 +0000145_socketmethods = (
146 'bind', 'connect', 'connect_ex', 'fileno', 'listen',
147 'getpeername', 'getsockname', 'getsockopt', 'setsockopt',
Skip Montanaroc6899182003-04-29 19:27:26 +0000148 'sendall', 'setblocking',
Christian Heimesa47b75b2008-01-04 15:48:06 +0000149 'settimeout', 'gettimeout', 'shutdown')
150
151if os.name == "nt":
152 _socketmethods = _socketmethods + ('ioctl',)
Guido van Rossume5e50592001-08-18 01:23:20 +0000153
Martin v. Löwisa94568a2003-05-10 07:36:56 +0000154if sys.platform == "riscos":
155 _socketmethods = _socketmethods + ('sleeptaskw',)
156
Martin v. Löwis7596e832006-07-01 15:33:37 +0000157# All the method names that must be delegated to either the real socket
158# object or the _closedsocket object.
159_delegate_methods = ("recv", "recvfrom", "recv_into", "recvfrom_into",
160 "send", "sendto")
161
Guido van Rossum715f9702002-08-08 18:11:36 +0000162class _closedsocket(object):
163 __slots__ = []
Skip Montanaroc6899182003-04-29 19:27:26 +0000164 def _dummy(*args):
Fred Drake70d566b2003-04-29 19:50:25 +0000165 raise error(EBADF, 'Bad file descriptor')
Martin v. Löwis7596e832006-07-01 15:33:37 +0000166 # All _delegate_methods must also be initialized here.
167 send = recv = recv_into = sendto = recvfrom = recvfrom_into = _dummy
168 __getattr__ = _dummy
Guido van Rossum715f9702002-08-08 18:11:36 +0000169
Martin v. Löwisf25e35b2007-07-27 18:28:22 +0000170# Wrapper around platform socket objects. This implements
171# a platform-independent dup() functionality. The
172# implementation currently relies on reference counting
173# to close the underlying socket object.
Guido van Rossumc18993f2002-08-08 15:16:20 +0000174class _socketobject(object):
Fred Drakea6070f02000-08-16 14:14:32 +0000175
Guido van Rossumc18993f2002-08-08 15:16:20 +0000176 __doc__ = _realsocket.__doc__
177
Martin v. Löwis7596e832006-07-01 15:33:37 +0000178 __slots__ = ["_sock", "__weakref__"] + list(_delegate_methods)
Guido van Rossumc18993f2002-08-08 15:16:20 +0000179
Guido van Rossumc18993f2002-08-08 15:16:20 +0000180 def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, _sock=None):
181 if _sock is None:
Guido van Rossum7c3b6342002-08-08 15:22:12 +0000182 _sock = _realsocket(family, type, proto)
Guido van Rossumc18993f2002-08-08 15:16:20 +0000183 self._sock = _sock
Martin v. Löwis7596e832006-07-01 15:33:37 +0000184 for method in _delegate_methods:
185 setattr(self, method, getattr(_sock, method))
Fred Drakea6070f02000-08-16 14:14:32 +0000186
187 def close(self):
Guido van Rossum715f9702002-08-08 18:11:36 +0000188 self._sock = _closedsocket()
Martin v. Löwis7596e832006-07-01 15:33:37 +0000189 dummy = self._sock._dummy
190 for method in _delegate_methods:
191 setattr(self, method, dummy)
Guido van Rossumc18993f2002-08-08 15:16:20 +0000192 close.__doc__ = _realsocket.close.__doc__
Fred Drakea6070f02000-08-16 14:14:32 +0000193
Fred Drakea6070f02000-08-16 14:14:32 +0000194 def accept(self):
195 sock, addr = self._sock.accept()
Guido van Rossumc18993f2002-08-08 15:16:20 +0000196 return _socketobject(_sock=sock), addr
197 accept.__doc__ = _realsocket.accept.__doc__
Fred Drakea6070f02000-08-16 14:14:32 +0000198
199 def dup(self):
Guido van Rossumc18993f2002-08-08 15:16:20 +0000200 """dup() -> socket object
201
202 Return a new socket object connected to the same system resource."""
203 return _socketobject(_sock=self._sock)
Fred Drakea6070f02000-08-16 14:14:32 +0000204
205 def makefile(self, mode='r', bufsize=-1):
Guido van Rossumc18993f2002-08-08 15:16:20 +0000206 """makefile([mode[, bufsize]]) -> file object
207
208 Return a regular file object corresponding to the socket. The mode
209 and bufsize arguments are as for the built-in open() function."""
Fred Drakea6070f02000-08-16 14:14:32 +0000210 return _fileobject(self._sock, mode, bufsize)
Tim Peters0ae07bd2006-03-22 03:23:21 +0000211
Georg Brandlbb03ac02006-03-21 18:17:25 +0000212 family = property(lambda self: self._sock.family, doc="the socket family")
213 type = property(lambda self: self._sock.type, doc="the socket type")
214 proto = property(lambda self: self._sock.proto, doc="the socket protocol")
Georg Brandlbc45a3f2006-03-17 19:17:34 +0000215
Guido van Rossumc18993f2002-08-08 15:16:20 +0000216 _s = ("def %s(self, *args): return self._sock.%s(*args)\n\n"
217 "%s.__doc__ = _realsocket.%s.__doc__\n")
Guido van Rossume5e50592001-08-18 01:23:20 +0000218 for _m in _socketmethods:
Guido van Rossumc18993f2002-08-08 15:16:20 +0000219 exec _s % (_m, _m, _m, _m)
Tim Petersd7e8a0d2002-08-08 20:07:03 +0000220 del _m, _s
Fred Drakea6070f02000-08-16 14:14:32 +0000221
Skip Montanaro89feabc2003-03-30 04:54:24 +0000222socket = SocketType = _socketobject
Fred Drakea6070f02000-08-16 14:14:32 +0000223
Guido van Rossumc18993f2002-08-08 15:16:20 +0000224class _fileobject(object):
Guido van Rossum443fec32002-08-08 01:02:16 +0000225 """Faux file object attached to a socket object."""
226
227 default_bufsize = 8192
Guido van Rossumc18993f2002-08-08 15:16:20 +0000228 name = "<socket>"
229
230 __slots__ = ["mode", "bufsize", "softspace",
231 # "closed" is a property, see below
Georg Brandldd7b0522007-01-21 10:35:10 +0000232 "_sock", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf",
233 "_close"]
Fred Drakea6070f02000-08-16 14:14:32 +0000234
Georg Brandldd7b0522007-01-21 10:35:10 +0000235 def __init__(self, sock, mode='rb', bufsize=-1, close=False):
Fred Drakea6070f02000-08-16 14:14:32 +0000236 self._sock = sock
Guido van Rossumc18993f2002-08-08 15:16:20 +0000237 self.mode = mode # Not actually used in this version
Guido van Rossum443fec32002-08-08 01:02:16 +0000238 if bufsize < 0:
239 bufsize = self.default_bufsize
Guido van Rossum7c3b6342002-08-08 15:22:12 +0000240 self.bufsize = bufsize
241 self.softspace = False
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000242 # _rbufsize is the suggested recv buffer size. It is *strictly*
243 # obeyed within readline() for recv calls. If it is larger than
244 # default_bufsize it will be used for recv calls within read().
Guido van Rossum443fec32002-08-08 01:02:16 +0000245 if bufsize == 0:
246 self._rbufsize = 1
247 elif bufsize == 1:
248 self._rbufsize = self.default_bufsize
249 else:
250 self._rbufsize = bufsize
Fred Drakea6070f02000-08-16 14:14:32 +0000251 self._wbufsize = bufsize
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000252 # We use StringIO for the read buffer to avoid holding a list
253 # of variously sized string objects which have been known to
254 # fragment the heap due to how they are malloc()ed and often
255 # realloc()ed down much smaller than their original allocation.
256 self._rbuf = StringIO()
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000257 self._wbuf = [] # A list of strings
Georg Brandldd7b0522007-01-21 10:35:10 +0000258 self._close = close
Fred Drakea6070f02000-08-16 14:14:32 +0000259
Guido van Rossumc18993f2002-08-08 15:16:20 +0000260 def _getclosed(self):
Tim Peters116d83c2004-03-28 02:20:45 +0000261 return self._sock is None
Guido van Rossumc18993f2002-08-08 15:16:20 +0000262 closed = property(_getclosed, doc="True if the file is closed")
263
Fred Drakea6070f02000-08-16 14:14:32 +0000264 def close(self):
265 try:
266 if self._sock:
267 self.flush()
268 finally:
Georg Brandldd7b0522007-01-21 10:35:10 +0000269 if self._close:
270 self._sock.close()
Guido van Rossum67f7a382002-06-06 21:08:16 +0000271 self._sock = None
Fred Drakea6070f02000-08-16 14:14:32 +0000272
273 def __del__(self):
Guido van Rossum65f8ced2003-05-29 14:36:57 +0000274 try:
275 self.close()
276 except:
277 # close() may fail if __init__ didn't complete
278 pass
Fred Drakea6070f02000-08-16 14:14:32 +0000279
280 def flush(self):
281 if self._wbuf:
Guido van Rossum443fec32002-08-08 01:02:16 +0000282 buffer = "".join(self._wbuf)
283 self._wbuf = []
Guido van Rossum67f7a382002-06-06 21:08:16 +0000284 self._sock.sendall(buffer)
Fred Drakea6070f02000-08-16 14:14:32 +0000285
Neal Norwitz2b342902002-06-13 22:18:39 +0000286 def fileno(self):
Fred Drakea6070f02000-08-16 14:14:32 +0000287 return self._sock.fileno()
288
289 def write(self, data):
Guido van Rossum443fec32002-08-08 01:02:16 +0000290 data = str(data) # XXX Should really reject non-string non-buffers
291 if not data:
292 return
293 self._wbuf.append(data)
294 if (self._wbufsize == 0 or
295 self._wbufsize == 1 and '\n' in data or
296 self._get_wbuf_len() >= self._wbufsize):
Guido van Rossum67f7a382002-06-06 21:08:16 +0000297 self.flush()
Fred Drakea6070f02000-08-16 14:14:32 +0000298
299 def writelines(self, list):
Guido van Rossum443fec32002-08-08 01:02:16 +0000300 # XXX We could do better here for very long lists
301 # XXX Should really reject non-string non-buffers
302 self._wbuf.extend(filter(None, map(str, list)))
303 if (self._wbufsize <= 1 or
304 self._get_wbuf_len() >= self._wbufsize):
305 self.flush()
Fred Drakea6070f02000-08-16 14:14:32 +0000306
Guido van Rossum443fec32002-08-08 01:02:16 +0000307 def _get_wbuf_len(self):
Guido van Rossum67f7a382002-06-06 21:08:16 +0000308 buf_len = 0
Guido van Rossum443fec32002-08-08 01:02:16 +0000309 for x in self._wbuf:
310 buf_len += len(x)
Guido van Rossum67f7a382002-06-06 21:08:16 +0000311 return buf_len
Fred Drakea6070f02000-08-16 14:14:32 +0000312
Guido van Rossum67f7a382002-06-06 21:08:16 +0000313 def read(self, size=-1):
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000314 # Use max, disallow tiny reads in a loop as they are very inefficient.
Gregory P. Smith24237ea2008-05-05 21:53:45 +0000315 # We never leave read() with any leftover data from a new recv() call
316 # in our internal buffer.
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000317 rbufsize = max(self._rbufsize, self.default_bufsize)
318 # Our use of StringIO rather than lists of string objects returned by
319 # recv() minimizes memory usage and fragmentation that occurs when
320 # rbufsize is large compared to the typical return value of recv().
321 buf = self._rbuf
322 buf.seek(0, 2) # seek end
Guido van Rossum443fec32002-08-08 01:02:16 +0000323 if size < 0:
324 # Read until EOF
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000325 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000326 while True:
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000327 data = self._sock.recv(rbufsize)
Guido van Rossum443fec32002-08-08 01:02:16 +0000328 if not data:
329 break
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000330 buf.write(data)
331 return buf.getvalue()
Guido van Rossum443fec32002-08-08 01:02:16 +0000332 else:
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000333 # Read until size bytes or EOF seen, whichever comes first
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000334 buf_len = buf.tell()
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000335 if buf_len >= size:
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000336 # Already have size bytes in our buffer? Extract and return.
337 buf.seek(0)
338 rv = buf.read(size)
339 self._rbuf = StringIO()
340 self._rbuf.write(buf.read())
341 return rv
342
343 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000344 while True:
345 left = size - buf_len
Gregory P. Smith24237ea2008-05-05 21:53:45 +0000346 # recv() will malloc the amount of memory given as its
347 # parameter even though it often returns much less data
348 # than that. The returned data string is short lived
349 # as we copy it into a StringIO and free it. This avoids
350 # fragmentation issues on many platforms.
351 data = self._sock.recv(left)
Guido van Rossum443fec32002-08-08 01:02:16 +0000352 if not data:
353 break
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000354 n = len(data)
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000355 if n == size and not buf_len:
356 # Shortcut. Avoid buffer data copies when:
357 # - We have no data in our buffer.
358 # AND
359 # - Our call to recv returned exactly the
360 # number of bytes we were asked to read.
361 return data
Gregory P. Smith24237ea2008-05-05 21:53:45 +0000362 if n == left:
363 buf.write(data)
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000364 del data # explicit free
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000365 break
Gregory P. Smith24237ea2008-05-05 21:53:45 +0000366 assert n <= left, "recv(%d) returned %d bytes" % (left, n)
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000367 buf.write(data)
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000368 buf_len += n
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000369 del data # explicit free
370 #assert buf_len == buf.tell()
371 return buf.getvalue()
Fred Drakea6070f02000-08-16 14:14:32 +0000372
Guido van Rossum67f7a382002-06-06 21:08:16 +0000373 def readline(self, size=-1):
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000374 buf = self._rbuf
Gregory P. Smith24237ea2008-05-05 21:53:45 +0000375 buf.seek(0, 2) # seek end
376 if buf.tell() > 0:
377 # check if we already have it in our buffer
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000378 buf.seek(0)
379 bline = buf.readline(size)
380 if bline.endswith('\n') or len(bline) == size:
381 self._rbuf = StringIO()
382 self._rbuf.write(buf.read())
383 return bline
384 del bline
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000385 if size < 0:
386 # Read until \n or EOF, whichever comes first
Guido van Rossum48b79692002-08-08 17:34:19 +0000387 if self._rbufsize <= 1:
388 # Speed up unbuffered case
Gregory P. Smith24237ea2008-05-05 21:53:45 +0000389 buf.seek(0)
390 buffers = [buf.read()]
391 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000392 data = None
Guido van Rossum48b79692002-08-08 17:34:19 +0000393 recv = self._sock.recv
394 while data != "\n":
395 data = recv(1)
396 if not data:
397 break
398 buffers.append(data)
399 return "".join(buffers)
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000400
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000401 buf.seek(0, 2) # seek end
402 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000403 while True:
404 data = self._sock.recv(self._rbufsize)
405 if not data:
406 break
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000407 nl = data.find('\n')
408 if nl >= 0:
409 nl += 1
Brett Cannon3f92bc62008-08-08 04:27:28 +0000410 buf.write(data[:nl])
411 self._rbuf.write(data[nl:])
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000412 del data
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000413 break
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000414 buf.write(data)
415 return buf.getvalue()
Guido van Rossum67f7a382002-06-06 21:08:16 +0000416 else:
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000417 # Read until size bytes or \n or EOF seen, whichever comes first
Gregory P. Smith24237ea2008-05-05 21:53:45 +0000418 buf.seek(0, 2) # seek end
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000419 buf_len = buf.tell()
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000420 if buf_len >= size:
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000421 buf.seek(0)
422 rv = buf.read(size)
423 self._rbuf = StringIO()
424 self._rbuf.write(buf.read())
425 return rv
426 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000427 while True:
428 data = self._sock.recv(self._rbufsize)
429 if not data:
430 break
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000431 left = size - buf_len
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000432 # did we just receive a newline?
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000433 nl = data.find('\n', 0, left)
434 if nl >= 0:
435 nl += 1
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000436 # save the excess data to _rbuf
Brett Cannon3f92bc62008-08-08 04:27:28 +0000437 self._rbuf.write(data[nl:])
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000438 if buf_len:
Brett Cannon3f92bc62008-08-08 04:27:28 +0000439 buf.write(data[:nl])
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000440 break
441 else:
442 # Shortcut. Avoid data copy through buf when returning
443 # a substring of our first recv().
444 return data[:nl]
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000445 n = len(data)
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000446 if n == size and not buf_len:
447 # Shortcut. Avoid data copy through buf when
448 # returning exactly all of our first recv().
449 return data
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000450 if n >= left:
Brett Cannon3f92bc62008-08-08 04:27:28 +0000451 buf.write(data[:left])
452 self._rbuf.write(data[left:])
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000453 break
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000454 buf.write(data)
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000455 buf_len += n
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000456 #assert buf_len == buf.tell()
457 return buf.getvalue()
Guido van Rossum67f7a382002-06-06 21:08:16 +0000458
459 def readlines(self, sizehint=0):
Martin v. Löwis6df27f82000-09-19 11:25:58 +0000460 total = 0
Fred Drakea6070f02000-08-16 14:14:32 +0000461 list = []
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000462 while True:
Fred Drakea6070f02000-08-16 14:14:32 +0000463 line = self.readline()
Neal Norwitz2b342902002-06-13 22:18:39 +0000464 if not line:
465 break
Fred Drakea6070f02000-08-16 14:14:32 +0000466 list.append(line)
Martin v. Löwis6df27f82000-09-19 11:25:58 +0000467 total += len(line)
468 if sizehint and total >= sizehint:
469 break
Fred Drakea6070f02000-08-16 14:14:32 +0000470 return list
Guido van Rossum443fec32002-08-08 01:02:16 +0000471
472 # Iterator protocols
473
474 def __iter__(self):
475 return self
476
477 def next(self):
478 line = self.readline()
479 if not line:
480 raise StopIteration
481 return line
Facundo Batista07c78be2007-03-23 18:54:07 +0000482
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000483_GLOBAL_DEFAULT_TIMEOUT = object()
Facundo Batista07c78be2007-03-23 18:54:07 +0000484
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000485def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT):
486 """Connect to *address* and return the socket object.
Facundo Batista07c78be2007-03-23 18:54:07 +0000487
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000488 Convenience function. Connect to *address* (a 2-tuple ``(host,
489 port)``) and return the socket object. Passing the optional
490 *timeout* parameter will set the timeout on the socket instance
491 before attempting to connect. If no *timeout* is supplied, the
492 global default timeout setting returned by :func:`getdefaulttimeout`
493 is used.
Facundo Batista07c78be2007-03-23 18:54:07 +0000494 """
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000495
Facundo Batista07c78be2007-03-23 18:54:07 +0000496 msg = "getaddrinfo returns an empty list"
497 host, port = address
498 for res in getaddrinfo(host, port, 0, SOCK_STREAM):
499 af, socktype, proto, canonname, sa = res
500 sock = None
501 try:
502 sock = socket(af, socktype, proto)
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000503 if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
Facundo Batista07c78be2007-03-23 18:54:07 +0000504 sock.settimeout(timeout)
505 sock.connect(sa)
506 return sock
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000507
Facundo Batista07c78be2007-03-23 18:54:07 +0000508 except error, msg:
509 if sock is not None:
510 sock.close()
511
512 raise error, msg