blob: 98ab2dc06fffb11911e2286eae8bbc43cc370087 [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
Mark Dickinson36c80842009-06-02 07:40:15 +000019getprotobyname() -- map a protocol name (e.g. 'tcp') to a number
Fred Drakea6070f02000-08-16 14:14:32 +000020ntohs(), 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:
Jean-Paul Calderonec28d5542010-05-23 15:22:08 +000087 import errno
Fred Drake70d566b2003-04-29 19:50:25 +000088except ImportError:
Jean-Paul Calderonec28d5542010-05-23 15:22:08 +000089 errno = None
90EBADF = getattr(errno, 'EBADF', 9)
91EINTR = getattr(errno, 'EINTR', 4)
Fred Drake70d566b2003-04-29 19:50:25 +000092
Benjamin Peterson2b485732009-04-06 22:11:57 +000093__all__ = ["getfqdn", "create_connection"]
Skip Montanaro0de65802001-02-15 22:15:14 +000094__all__.extend(os._get_exports_list(_socket))
Bill Janssen426ea0a2007-08-29 22:35:05 +000095
Skip Montanaro0de65802001-02-15 22:15:14 +000096
Guido van Rossumc18993f2002-08-08 15:16:20 +000097_realsocket = socket
Fred Drakea6070f02000-08-16 14:14:32 +000098
99# WSA error codes
100if sys.platform.lower().startswith("win"):
101 errorTab = {}
102 errorTab[10004] = "The operation was interrupted."
103 errorTab[10009] = "A bad file handle was passed."
104 errorTab[10013] = "Permission denied."
105 errorTab[10014] = "A fault occurred on the network??" # WSAEFAULT
106 errorTab[10022] = "An invalid operation was attempted."
107 errorTab[10035] = "The socket operation would block"
108 errorTab[10036] = "A blocking operation is already in progress."
109 errorTab[10048] = "The network address is in use."
110 errorTab[10054] = "The connection has been reset."
111 errorTab[10058] = "The network has been shut down."
112 errorTab[10060] = "The operation timed out."
113 errorTab[10061] = "Connection refused."
114 errorTab[10063] = "The name is too long."
115 errorTab[10064] = "The host is down."
116 errorTab[10065] = "The host is unreachable."
Skip Montanaro64de1a42001-03-18 19:53:21 +0000117 __all__.append("errorTab")
Guido van Rossumde7cade2002-08-08 15:25:28 +0000118
Fred Drakea6070f02000-08-16 14:14:32 +0000119
120
121def getfqdn(name=''):
122 """Get fully qualified domain name from name.
123
124 An empty argument is interpreted as meaning the local host.
125
126 First the hostname returned by gethostbyaddr() is checked, then
127 possibly existing aliases. In case no FQDN is available, hostname
Brett Cannon01668a12005-03-11 00:04:17 +0000128 from gethostname() is returned.
Fred Drakea6070f02000-08-16 14:14:32 +0000129 """
130 name = name.strip()
Peter Schneider-Kamp2d2785a2000-08-16 20:30:21 +0000131 if not name or name == '0.0.0.0':
Fred Drakea6070f02000-08-16 14:14:32 +0000132 name = gethostname()
133 try:
134 hostname, aliases, ipaddrs = gethostbyaddr(name)
135 except error:
136 pass
137 else:
138 aliases.insert(0, hostname)
139 for name in aliases:
140 if '.' in name:
141 break
142 else:
143 name = hostname
144 return name
145
146
Guido van Rossume5e50592001-08-18 01:23:20 +0000147_socketmethods = (
148 'bind', 'connect', 'connect_ex', 'fileno', 'listen',
149 'getpeername', 'getsockname', 'getsockopt', 'setsockopt',
Skip Montanaroc6899182003-04-29 19:27:26 +0000150 'sendall', 'setblocking',
Christian Heimesa47b75b2008-01-04 15:48:06 +0000151 'settimeout', 'gettimeout', 'shutdown')
152
153if os.name == "nt":
154 _socketmethods = _socketmethods + ('ioctl',)
Guido van Rossume5e50592001-08-18 01:23:20 +0000155
Martin v. Löwisa94568a2003-05-10 07:36:56 +0000156if sys.platform == "riscos":
157 _socketmethods = _socketmethods + ('sleeptaskw',)
158
Martin v. Löwis7596e832006-07-01 15:33:37 +0000159# All the method names that must be delegated to either the real socket
160# object or the _closedsocket object.
161_delegate_methods = ("recv", "recvfrom", "recv_into", "recvfrom_into",
162 "send", "sendto")
163
Guido van Rossum715f9702002-08-08 18:11:36 +0000164class _closedsocket(object):
165 __slots__ = []
Skip Montanaroc6899182003-04-29 19:27:26 +0000166 def _dummy(*args):
Fred Drake70d566b2003-04-29 19:50:25 +0000167 raise error(EBADF, 'Bad file descriptor')
Martin v. Löwis7596e832006-07-01 15:33:37 +0000168 # All _delegate_methods must also be initialized here.
169 send = recv = recv_into = sendto = recvfrom = recvfrom_into = _dummy
170 __getattr__ = _dummy
Guido van Rossum715f9702002-08-08 18:11:36 +0000171
Martin v. Löwisf25e35b2007-07-27 18:28:22 +0000172# Wrapper around platform socket objects. This implements
173# a platform-independent dup() functionality. The
174# implementation currently relies on reference counting
175# to close the underlying socket object.
Guido van Rossumc18993f2002-08-08 15:16:20 +0000176class _socketobject(object):
Fred Drakea6070f02000-08-16 14:14:32 +0000177
Guido van Rossumc18993f2002-08-08 15:16:20 +0000178 __doc__ = _realsocket.__doc__
179
Martin v. Löwis7596e832006-07-01 15:33:37 +0000180 __slots__ = ["_sock", "__weakref__"] + list(_delegate_methods)
Guido van Rossumc18993f2002-08-08 15:16:20 +0000181
Guido van Rossumc18993f2002-08-08 15:16:20 +0000182 def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, _sock=None):
183 if _sock is None:
Guido van Rossum7c3b6342002-08-08 15:22:12 +0000184 _sock = _realsocket(family, type, proto)
Guido van Rossumc18993f2002-08-08 15:16:20 +0000185 self._sock = _sock
Martin v. Löwis7596e832006-07-01 15:33:37 +0000186 for method in _delegate_methods:
187 setattr(self, method, getattr(_sock, method))
Fred Drakea6070f02000-08-16 14:14:32 +0000188
189 def close(self):
Guido van Rossum715f9702002-08-08 18:11:36 +0000190 self._sock = _closedsocket()
Martin v. Löwis7596e832006-07-01 15:33:37 +0000191 dummy = self._sock._dummy
192 for method in _delegate_methods:
193 setattr(self, method, dummy)
Guido van Rossumc18993f2002-08-08 15:16:20 +0000194 close.__doc__ = _realsocket.close.__doc__
Fred Drakea6070f02000-08-16 14:14:32 +0000195
Fred Drakea6070f02000-08-16 14:14:32 +0000196 def accept(self):
197 sock, addr = self._sock.accept()
Guido van Rossumc18993f2002-08-08 15:16:20 +0000198 return _socketobject(_sock=sock), addr
199 accept.__doc__ = _realsocket.accept.__doc__
Fred Drakea6070f02000-08-16 14:14:32 +0000200
201 def dup(self):
Guido van Rossumc18993f2002-08-08 15:16:20 +0000202 """dup() -> socket object
203
204 Return a new socket object connected to the same system resource."""
205 return _socketobject(_sock=self._sock)
Fred Drakea6070f02000-08-16 14:14:32 +0000206
207 def makefile(self, mode='r', bufsize=-1):
Guido van Rossumc18993f2002-08-08 15:16:20 +0000208 """makefile([mode[, bufsize]]) -> file object
209
210 Return a regular file object corresponding to the socket. The mode
211 and bufsize arguments are as for the built-in open() function."""
Fred Drakea6070f02000-08-16 14:14:32 +0000212 return _fileobject(self._sock, mode, bufsize)
Tim Peters0ae07bd2006-03-22 03:23:21 +0000213
Georg Brandlbb03ac02006-03-21 18:17:25 +0000214 family = property(lambda self: self._sock.family, doc="the socket family")
215 type = property(lambda self: self._sock.type, doc="the socket type")
216 proto = property(lambda self: self._sock.proto, doc="the socket protocol")
Georg Brandlbc45a3f2006-03-17 19:17:34 +0000217
Guido van Rossumc18993f2002-08-08 15:16:20 +0000218 _s = ("def %s(self, *args): return self._sock.%s(*args)\n\n"
219 "%s.__doc__ = _realsocket.%s.__doc__\n")
Guido van Rossume5e50592001-08-18 01:23:20 +0000220 for _m in _socketmethods:
Guido van Rossumc18993f2002-08-08 15:16:20 +0000221 exec _s % (_m, _m, _m, _m)
Tim Petersd7e8a0d2002-08-08 20:07:03 +0000222 del _m, _s
Fred Drakea6070f02000-08-16 14:14:32 +0000223
Skip Montanaro89feabc2003-03-30 04:54:24 +0000224socket = SocketType = _socketobject
Fred Drakea6070f02000-08-16 14:14:32 +0000225
Guido van Rossumc18993f2002-08-08 15:16:20 +0000226class _fileobject(object):
Guido van Rossum443fec32002-08-08 01:02:16 +0000227 """Faux file object attached to a socket object."""
228
229 default_bufsize = 8192
Guido van Rossumc18993f2002-08-08 15:16:20 +0000230 name = "<socket>"
231
232 __slots__ = ["mode", "bufsize", "softspace",
233 # "closed" is a property, see below
Gregory P. Smith1cfc9c02009-08-15 06:40:49 +0000234 "_sock", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf", "_wbuf_len",
Georg Brandldd7b0522007-01-21 10:35:10 +0000235 "_close"]
Fred Drakea6070f02000-08-16 14:14:32 +0000236
Georg Brandldd7b0522007-01-21 10:35:10 +0000237 def __init__(self, sock, mode='rb', bufsize=-1, close=False):
Fred Drakea6070f02000-08-16 14:14:32 +0000238 self._sock = sock
Guido van Rossumc18993f2002-08-08 15:16:20 +0000239 self.mode = mode # Not actually used in this version
Guido van Rossum443fec32002-08-08 01:02:16 +0000240 if bufsize < 0:
241 bufsize = self.default_bufsize
Guido van Rossum7c3b6342002-08-08 15:22:12 +0000242 self.bufsize = bufsize
243 self.softspace = False
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000244 # _rbufsize is the suggested recv buffer size. It is *strictly*
245 # obeyed within readline() for recv calls. If it is larger than
246 # default_bufsize it will be used for recv calls within read().
Guido van Rossum443fec32002-08-08 01:02:16 +0000247 if bufsize == 0:
248 self._rbufsize = 1
249 elif bufsize == 1:
250 self._rbufsize = self.default_bufsize
251 else:
252 self._rbufsize = bufsize
Fred Drakea6070f02000-08-16 14:14:32 +0000253 self._wbufsize = bufsize
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000254 # We use StringIO for the read buffer to avoid holding a list
255 # of variously sized string objects which have been known to
256 # fragment the heap due to how they are malloc()ed and often
257 # realloc()ed down much smaller than their original allocation.
258 self._rbuf = StringIO()
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000259 self._wbuf = [] # A list of strings
Gregory P. Smith1cfc9c02009-08-15 06:40:49 +0000260 self._wbuf_len = 0
Georg Brandldd7b0522007-01-21 10:35:10 +0000261 self._close = close
Fred Drakea6070f02000-08-16 14:14:32 +0000262
Guido van Rossumc18993f2002-08-08 15:16:20 +0000263 def _getclosed(self):
Tim Peters116d83c2004-03-28 02:20:45 +0000264 return self._sock is None
Guido van Rossumc18993f2002-08-08 15:16:20 +0000265 closed = property(_getclosed, doc="True if the file is closed")
266
Fred Drakea6070f02000-08-16 14:14:32 +0000267 def close(self):
268 try:
269 if self._sock:
270 self.flush()
271 finally:
Georg Brandldd7b0522007-01-21 10:35:10 +0000272 if self._close:
273 self._sock.close()
Guido van Rossum67f7a382002-06-06 21:08:16 +0000274 self._sock = None
Fred Drakea6070f02000-08-16 14:14:32 +0000275
276 def __del__(self):
Guido van Rossum65f8ced2003-05-29 14:36:57 +0000277 try:
278 self.close()
279 except:
280 # close() may fail if __init__ didn't complete
281 pass
Fred Drakea6070f02000-08-16 14:14:32 +0000282
283 def flush(self):
284 if self._wbuf:
Jean-Paul Calderonec28d5542010-05-23 15:22:08 +0000285 data = "".join(self._wbuf)
Guido van Rossum443fec32002-08-08 01:02:16 +0000286 self._wbuf = []
Gregory P. Smith1cfc9c02009-08-15 06:40:49 +0000287 self._wbuf_len = 0
Jean-Paul Calderonec28d5542010-05-23 15:22:08 +0000288 buffer_size = max(self._rbufsize, self.default_bufsize)
289 data_size = len(data)
290 write_offset = 0
291 try:
292 while write_offset < data_size:
293 self._sock.sendall(buffer(data, write_offset, buffer_size))
294 write_offset += buffer_size
295 finally:
296 if write_offset < data_size:
297 remainder = data[write_offset:]
298 del data # explicit free
299 self._wbuf.append(remainder)
300 self._wbuf_len = len(remainder)
Fred Drakea6070f02000-08-16 14:14:32 +0000301
Neal Norwitz2b342902002-06-13 22:18:39 +0000302 def fileno(self):
Fred Drakea6070f02000-08-16 14:14:32 +0000303 return self._sock.fileno()
304
305 def write(self, data):
Guido van Rossum443fec32002-08-08 01:02:16 +0000306 data = str(data) # XXX Should really reject non-string non-buffers
307 if not data:
308 return
309 self._wbuf.append(data)
Gregory P. Smith1cfc9c02009-08-15 06:40:49 +0000310 self._wbuf_len += len(data)
Guido van Rossum443fec32002-08-08 01:02:16 +0000311 if (self._wbufsize == 0 or
312 self._wbufsize == 1 and '\n' in data or
Gregory P. Smith1cfc9c02009-08-15 06:40:49 +0000313 self._wbuf_len >= self._wbufsize):
Guido van Rossum67f7a382002-06-06 21:08:16 +0000314 self.flush()
Fred Drakea6070f02000-08-16 14:14:32 +0000315
316 def writelines(self, list):
Guido van Rossum443fec32002-08-08 01:02:16 +0000317 # XXX We could do better here for very long lists
318 # XXX Should really reject non-string non-buffers
Gregory P. Smith1cfc9c02009-08-15 06:40:49 +0000319 lines = filter(None, map(str, list))
320 self._wbuf_len += sum(map(len, lines))
321 self._wbuf.extend(lines)
Guido van Rossum443fec32002-08-08 01:02:16 +0000322 if (self._wbufsize <= 1 or
Gregory P. Smith1cfc9c02009-08-15 06:40:49 +0000323 self._wbuf_len >= self._wbufsize):
Guido van Rossum443fec32002-08-08 01:02:16 +0000324 self.flush()
Fred Drakea6070f02000-08-16 14:14:32 +0000325
Guido van Rossum443fec32002-08-08 01:02:16 +0000326 def _get_wbuf_len(self):
Gregory P. Smith1cfc9c02009-08-15 06:40:49 +0000327 return self._wbuf_len
Fred Drakea6070f02000-08-16 14:14:32 +0000328
Guido van Rossum67f7a382002-06-06 21:08:16 +0000329 def read(self, size=-1):
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000330 # Use max, disallow tiny reads in a loop as they are very inefficient.
Gregory P. Smith24237ea2008-05-05 21:53:45 +0000331 # We never leave read() with any leftover data from a new recv() call
332 # in our internal buffer.
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000333 rbufsize = max(self._rbufsize, self.default_bufsize)
334 # Our use of StringIO rather than lists of string objects returned by
335 # recv() minimizes memory usage and fragmentation that occurs when
336 # rbufsize is large compared to the typical return value of recv().
337 buf = self._rbuf
338 buf.seek(0, 2) # seek end
Guido van Rossum443fec32002-08-08 01:02:16 +0000339 if size < 0:
340 # Read until EOF
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000341 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000342 while True:
Jean-Paul Calderonec28d5542010-05-23 15:22:08 +0000343 try:
344 data = self._sock.recv(rbufsize)
345 except error, e:
346 if e[0] == EINTR:
347 continue
348 raise
Guido van Rossum443fec32002-08-08 01:02:16 +0000349 if not data:
350 break
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000351 buf.write(data)
352 return buf.getvalue()
Guido van Rossum443fec32002-08-08 01:02:16 +0000353 else:
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000354 # Read until size bytes or EOF seen, whichever comes first
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000355 buf_len = buf.tell()
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000356 if buf_len >= size:
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000357 # Already have size bytes in our buffer? Extract and return.
358 buf.seek(0)
359 rv = buf.read(size)
360 self._rbuf = StringIO()
361 self._rbuf.write(buf.read())
362 return rv
363
364 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000365 while True:
366 left = size - buf_len
Gregory P. Smith24237ea2008-05-05 21:53:45 +0000367 # recv() will malloc the amount of memory given as its
368 # parameter even though it often returns much less data
369 # than that. The returned data string is short lived
370 # as we copy it into a StringIO and free it. This avoids
371 # fragmentation issues on many platforms.
Jean-Paul Calderonec28d5542010-05-23 15:22:08 +0000372 try:
373 data = self._sock.recv(left)
374 except error, e:
375 if e[0] == EINTR:
376 continue
377 raise
Guido van Rossum443fec32002-08-08 01:02:16 +0000378 if not data:
379 break
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000380 n = len(data)
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000381 if n == size and not buf_len:
382 # Shortcut. Avoid buffer data copies when:
383 # - We have no data in our buffer.
384 # AND
385 # - Our call to recv returned exactly the
386 # number of bytes we were asked to read.
387 return data
Gregory P. Smith24237ea2008-05-05 21:53:45 +0000388 if n == left:
389 buf.write(data)
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000390 del data # explicit free
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000391 break
Gregory P. Smith24237ea2008-05-05 21:53:45 +0000392 assert n <= left, "recv(%d) returned %d bytes" % (left, n)
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000393 buf.write(data)
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000394 buf_len += n
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000395 del data # explicit free
396 #assert buf_len == buf.tell()
397 return buf.getvalue()
Fred Drakea6070f02000-08-16 14:14:32 +0000398
Guido van Rossum67f7a382002-06-06 21:08:16 +0000399 def readline(self, size=-1):
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000400 buf = self._rbuf
Gregory P. Smith24237ea2008-05-05 21:53:45 +0000401 buf.seek(0, 2) # seek end
402 if buf.tell() > 0:
403 # check if we already have it in our buffer
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000404 buf.seek(0)
405 bline = buf.readline(size)
406 if bline.endswith('\n') or len(bline) == size:
407 self._rbuf = StringIO()
408 self._rbuf.write(buf.read())
409 return bline
410 del bline
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000411 if size < 0:
412 # Read until \n or EOF, whichever comes first
Guido van Rossum48b79692002-08-08 17:34:19 +0000413 if self._rbufsize <= 1:
414 # Speed up unbuffered case
Gregory P. Smith24237ea2008-05-05 21:53:45 +0000415 buf.seek(0)
416 buffers = [buf.read()]
417 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000418 data = None
Guido van Rossum48b79692002-08-08 17:34:19 +0000419 recv = self._sock.recv
Jean-Paul Calderonec28d5542010-05-23 15:22:08 +0000420 while True:
421 try:
422 while data != "\n":
423 data = recv(1)
424 if not data:
425 break
426 buffers.append(data)
427 except error, e:
428 # The try..except to catch EINTR was moved outside the
429 # recv loop to avoid the per byte overhead.
430 if e[0] == EINTR:
431 continue
432 raise
433 break
Guido van Rossum48b79692002-08-08 17:34:19 +0000434 return "".join(buffers)
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000435
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000436 buf.seek(0, 2) # seek end
437 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000438 while True:
Jean-Paul Calderonec28d5542010-05-23 15:22:08 +0000439 try:
440 data = self._sock.recv(self._rbufsize)
441 except error, e:
442 if e[0] == EINTR:
443 continue
444 raise
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000445 if not data:
446 break
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000447 nl = data.find('\n')
448 if nl >= 0:
449 nl += 1
Brett Cannon3f92bc62008-08-08 04:27:28 +0000450 buf.write(data[:nl])
451 self._rbuf.write(data[nl:])
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000452 del data
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000453 break
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000454 buf.write(data)
455 return buf.getvalue()
Guido van Rossum67f7a382002-06-06 21:08:16 +0000456 else:
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000457 # Read until size bytes or \n or EOF seen, whichever comes first
Gregory P. Smith24237ea2008-05-05 21:53:45 +0000458 buf.seek(0, 2) # seek end
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000459 buf_len = buf.tell()
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000460 if buf_len >= size:
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000461 buf.seek(0)
462 rv = buf.read(size)
463 self._rbuf = StringIO()
464 self._rbuf.write(buf.read())
465 return rv
466 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000467 while True:
Jean-Paul Calderonec28d5542010-05-23 15:22:08 +0000468 try:
469 data = self._sock.recv(self._rbufsize)
470 except error, e:
471 if e[0] == EINTR:
472 continue
473 raise
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000474 if not data:
475 break
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000476 left = size - buf_len
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000477 # did we just receive a newline?
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000478 nl = data.find('\n', 0, left)
479 if nl >= 0:
480 nl += 1
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000481 # save the excess data to _rbuf
Brett Cannon3f92bc62008-08-08 04:27:28 +0000482 self._rbuf.write(data[nl:])
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000483 if buf_len:
Brett Cannon3f92bc62008-08-08 04:27:28 +0000484 buf.write(data[:nl])
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000485 break
486 else:
487 # Shortcut. Avoid data copy through buf when returning
488 # a substring of our first recv().
489 return data[:nl]
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000490 n = len(data)
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000491 if n == size and not buf_len:
492 # Shortcut. Avoid data copy through buf when
493 # returning exactly all of our first recv().
494 return data
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000495 if n >= left:
Brett Cannon3f92bc62008-08-08 04:27:28 +0000496 buf.write(data[:left])
497 self._rbuf.write(data[left:])
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000498 break
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000499 buf.write(data)
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000500 buf_len += n
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000501 #assert buf_len == buf.tell()
502 return buf.getvalue()
Guido van Rossum67f7a382002-06-06 21:08:16 +0000503
504 def readlines(self, sizehint=0):
Martin v. Löwis6df27f82000-09-19 11:25:58 +0000505 total = 0
Fred Drakea6070f02000-08-16 14:14:32 +0000506 list = []
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000507 while True:
Fred Drakea6070f02000-08-16 14:14:32 +0000508 line = self.readline()
Neal Norwitz2b342902002-06-13 22:18:39 +0000509 if not line:
510 break
Fred Drakea6070f02000-08-16 14:14:32 +0000511 list.append(line)
Martin v. Löwis6df27f82000-09-19 11:25:58 +0000512 total += len(line)
513 if sizehint and total >= sizehint:
514 break
Fred Drakea6070f02000-08-16 14:14:32 +0000515 return list
Guido van Rossum443fec32002-08-08 01:02:16 +0000516
517 # Iterator protocols
518
519 def __iter__(self):
520 return self
521
522 def next(self):
523 line = self.readline()
524 if not line:
525 raise StopIteration
526 return line
Facundo Batista07c78be2007-03-23 18:54:07 +0000527
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000528_GLOBAL_DEFAULT_TIMEOUT = object()
Facundo Batista07c78be2007-03-23 18:54:07 +0000529
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000530def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT):
531 """Connect to *address* and return the socket object.
Facundo Batista07c78be2007-03-23 18:54:07 +0000532
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000533 Convenience function. Connect to *address* (a 2-tuple ``(host,
534 port)``) and return the socket object. Passing the optional
535 *timeout* parameter will set the timeout on the socket instance
536 before attempting to connect. If no *timeout* is supplied, the
537 global default timeout setting returned by :func:`getdefaulttimeout`
538 is used.
Facundo Batista07c78be2007-03-23 18:54:07 +0000539 """
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000540
Facundo Batista07c78be2007-03-23 18:54:07 +0000541 msg = "getaddrinfo returns an empty list"
542 host, port = address
543 for res in getaddrinfo(host, port, 0, SOCK_STREAM):
544 af, socktype, proto, canonname, sa = res
545 sock = None
546 try:
547 sock = socket(af, socktype, proto)
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000548 if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
Facundo Batista07c78be2007-03-23 18:54:07 +0000549 sock.settimeout(timeout)
550 sock.connect(sa)
551 return sock
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000552
Facundo Batista07c78be2007-03-23 18:54:07 +0000553 except error, msg:
554 if sock is not None:
555 sock.close()
556
557 raise error, msg