blob: 614af290d1078233513ebce19bd5e537d52390f1 [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 Dickinsond57b5542009-06-02 07:39:26 +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
Gregory P. Smith79a3eb12010-01-03 01:29:44 +000027create_connection() -- connects to an address, with an optional timeout and
28 optional source address.
Fred Drakea6070f02000-08-16 14:14:32 +000029
30 [*] not available on all platforms!
31
32Special objects:
33
34SocketType -- type object for socket objects
35error -- exception raised for I/O errors
Guido van Rossum47dfa4a2003-04-25 05:48:32 +000036has_ipv6 -- boolean value indicating if IPv6 is supported
Fred Drakea6070f02000-08-16 14:14:32 +000037
38Integer constants:
39
40AF_INET, AF_UNIX -- socket domains (first argument to socket() call)
41SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument)
42
43Many other constants may be defined; these may be used in calls to
44the setsockopt() and getsockopt() methods.
45"""
46
Tim Peters18e67782002-02-17 04:25:24 +000047import _socket
Fred Drakea6070f02000-08-16 14:14:32 +000048from _socket import *
Chris Withersb5248252009-04-11 11:22:19 +000049from functools import partial
Antoine Pitroudaa524a2009-10-14 18:27:32 +000050from types import MethodType
Tim Peters18e67782002-02-17 04:25:24 +000051
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000052try:
Guido van Rossumde7cade2002-08-08 15:25:28 +000053 import _ssl
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000054except ImportError:
Bill Janssen426ea0a2007-08-29 22:35:05 +000055 # no SSL support
Guido van Rossumc18993f2002-08-08 15:16:20 +000056 pass
Bill Janssen426ea0a2007-08-29 22:35:05 +000057else:
58 def ssl(sock, keyfile=None, certfile=None):
59 # we do an internal import here because the ssl
60 # module imports the socket module
61 import ssl as _realssl
Bill Janssen98d19da2007-09-10 21:51:02 +000062 warnings.warn("socket.ssl() is deprecated. Use ssl.wrap_socket() instead.",
Bill Janssen426ea0a2007-08-29 22:35:05 +000063 DeprecationWarning, stacklevel=2)
64 return _realssl.sslwrap_simple(sock, keyfile, certfile)
Fred Drakea6070f02000-08-16 14:14:32 +000065
Bill Janssen426ea0a2007-08-29 22:35:05 +000066 # we need to import the same constants we used to...
Bill Janssen98d19da2007-09-10 21:51:02 +000067 from _ssl import SSLError as sslerror
Bill Janssen426ea0a2007-08-29 22:35:05 +000068 from _ssl import \
Bill Janssen426ea0a2007-08-29 22:35:05 +000069 RAND_add, \
Bill Janssen426ea0a2007-08-29 22:35:05 +000070 RAND_status, \
71 SSL_ERROR_ZERO_RETURN, \
72 SSL_ERROR_WANT_READ, \
73 SSL_ERROR_WANT_WRITE, \
74 SSL_ERROR_WANT_X509_LOOKUP, \
75 SSL_ERROR_SYSCALL, \
76 SSL_ERROR_SSL, \
77 SSL_ERROR_WANT_CONNECT, \
78 SSL_ERROR_EOF, \
79 SSL_ERROR_INVALID_ERROR_CODE
Victor Stinner7c906672015-01-06 13:53:37 +010080 try:
81 from _ssl import RAND_egd
82 except ImportError:
83 # LibreSSL does not provide RAND_egd
84 pass
Bill Janssen426ea0a2007-08-29 22:35:05 +000085
86import os, sys, warnings
Fred Drakea6070f02000-08-16 14:14:32 +000087
Fred Drake70d566b2003-04-29 19:50:25 +000088try:
Gregory P. Smithf8cc6402008-05-02 07:26:52 +000089 from cStringIO import StringIO
90except ImportError:
91 from StringIO import StringIO
92
93try:
Gregory P. Smithc4ad0342009-08-13 18:54:50 +000094 import errno
Fred Drake70d566b2003-04-29 19:50:25 +000095except ImportError:
Gregory P. Smithc4ad0342009-08-13 18:54:50 +000096 errno = None
97EBADF = getattr(errno, 'EBADF', 9)
98EINTR = getattr(errno, 'EINTR', 4)
Fred Drake70d566b2003-04-29 19:50:25 +000099
Benjamin Petersona27e6e32009-04-06 21:53:33 +0000100__all__ = ["getfqdn", "create_connection"]
Skip Montanaro0de65802001-02-15 22:15:14 +0000101__all__.extend(os._get_exports_list(_socket))
Bill Janssen426ea0a2007-08-29 22:35:05 +0000102
Skip Montanaro0de65802001-02-15 22:15:14 +0000103
Guido van Rossumc18993f2002-08-08 15:16:20 +0000104_realsocket = socket
Fred Drakea6070f02000-08-16 14:14:32 +0000105
106# WSA error codes
107if sys.platform.lower().startswith("win"):
108 errorTab = {}
109 errorTab[10004] = "The operation was interrupted."
110 errorTab[10009] = "A bad file handle was passed."
111 errorTab[10013] = "Permission denied."
112 errorTab[10014] = "A fault occurred on the network??" # WSAEFAULT
113 errorTab[10022] = "An invalid operation was attempted."
114 errorTab[10035] = "The socket operation would block"
115 errorTab[10036] = "A blocking operation is already in progress."
116 errorTab[10048] = "The network address is in use."
117 errorTab[10054] = "The connection has been reset."
118 errorTab[10058] = "The network has been shut down."
119 errorTab[10060] = "The operation timed out."
120 errorTab[10061] = "Connection refused."
121 errorTab[10063] = "The name is too long."
122 errorTab[10064] = "The host is down."
123 errorTab[10065] = "The host is unreachable."
Skip Montanaro64de1a42001-03-18 19:53:21 +0000124 __all__.append("errorTab")
Guido van Rossumde7cade2002-08-08 15:25:28 +0000125
Fred Drakea6070f02000-08-16 14:14:32 +0000126
127
128def getfqdn(name=''):
129 """Get fully qualified domain name from name.
130
131 An empty argument is interpreted as meaning the local host.
132
133 First the hostname returned by gethostbyaddr() is checked, then
134 possibly existing aliases. In case no FQDN is available, hostname
Brett Cannon01668a12005-03-11 00:04:17 +0000135 from gethostname() is returned.
Fred Drakea6070f02000-08-16 14:14:32 +0000136 """
137 name = name.strip()
Peter Schneider-Kamp2d2785a2000-08-16 20:30:21 +0000138 if not name or name == '0.0.0.0':
Fred Drakea6070f02000-08-16 14:14:32 +0000139 name = gethostname()
140 try:
141 hostname, aliases, ipaddrs = gethostbyaddr(name)
142 except error:
143 pass
144 else:
145 aliases.insert(0, hostname)
146 for name in aliases:
147 if '.' in name:
148 break
149 else:
150 name = hostname
151 return name
152
153
Guido van Rossume5e50592001-08-18 01:23:20 +0000154_socketmethods = (
155 'bind', 'connect', 'connect_ex', 'fileno', 'listen',
156 'getpeername', 'getsockname', 'getsockopt', 'setsockopt',
Skip Montanaroc6899182003-04-29 19:27:26 +0000157 'sendall', 'setblocking',
Christian Heimesa47b75b2008-01-04 15:48:06 +0000158 'settimeout', 'gettimeout', 'shutdown')
159
160if os.name == "nt":
161 _socketmethods = _socketmethods + ('ioctl',)
Guido van Rossume5e50592001-08-18 01:23:20 +0000162
Martin v. Löwisa94568a2003-05-10 07:36:56 +0000163if sys.platform == "riscos":
164 _socketmethods = _socketmethods + ('sleeptaskw',)
165
Martin v. Löwis7596e832006-07-01 15:33:37 +0000166# All the method names that must be delegated to either the real socket
167# object or the _closedsocket object.
168_delegate_methods = ("recv", "recvfrom", "recv_into", "recvfrom_into",
169 "send", "sendto")
170
Guido van Rossum715f9702002-08-08 18:11:36 +0000171class _closedsocket(object):
172 __slots__ = []
Skip Montanaroc6899182003-04-29 19:27:26 +0000173 def _dummy(*args):
Fred Drake70d566b2003-04-29 19:50:25 +0000174 raise error(EBADF, 'Bad file descriptor')
Martin v. Löwis7596e832006-07-01 15:33:37 +0000175 # All _delegate_methods must also be initialized here.
176 send = recv = recv_into = sendto = recvfrom = recvfrom_into = _dummy
177 __getattr__ = _dummy
Guido van Rossum715f9702002-08-08 18:11:36 +0000178
Martin v. Löwisf25e35b2007-07-27 18:28:22 +0000179# Wrapper around platform socket objects. This implements
180# a platform-independent dup() functionality. The
181# implementation currently relies on reference counting
182# to close the underlying socket object.
Guido van Rossumc18993f2002-08-08 15:16:20 +0000183class _socketobject(object):
Fred Drakea6070f02000-08-16 14:14:32 +0000184
Guido van Rossumc18993f2002-08-08 15:16:20 +0000185 __doc__ = _realsocket.__doc__
186
Martin v. Löwis7596e832006-07-01 15:33:37 +0000187 __slots__ = ["_sock", "__weakref__"] + list(_delegate_methods)
Guido van Rossumc18993f2002-08-08 15:16:20 +0000188
Guido van Rossumc18993f2002-08-08 15:16:20 +0000189 def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, _sock=None):
190 if _sock is None:
Guido van Rossum7c3b6342002-08-08 15:22:12 +0000191 _sock = _realsocket(family, type, proto)
Guido van Rossumc18993f2002-08-08 15:16:20 +0000192 self._sock = _sock
Martin v. Löwis7596e832006-07-01 15:33:37 +0000193 for method in _delegate_methods:
194 setattr(self, method, getattr(_sock, method))
Fred Drakea6070f02000-08-16 14:14:32 +0000195
Daniel Stutzbach66c981b2010-08-31 20:29:39 +0000196 def close(self, _closedsocket=_closedsocket,
197 _delegate_methods=_delegate_methods, setattr=setattr):
198 # This function should not reference any globals. See issue #808164.
Guido van Rossum715f9702002-08-08 18:11:36 +0000199 self._sock = _closedsocket()
Martin v. Löwis7596e832006-07-01 15:33:37 +0000200 dummy = self._sock._dummy
201 for method in _delegate_methods:
202 setattr(self, method, dummy)
Guido van Rossumc18993f2002-08-08 15:16:20 +0000203 close.__doc__ = _realsocket.close.__doc__
Fred Drakea6070f02000-08-16 14:14:32 +0000204
Fred Drakea6070f02000-08-16 14:14:32 +0000205 def accept(self):
206 sock, addr = self._sock.accept()
Guido van Rossumc18993f2002-08-08 15:16:20 +0000207 return _socketobject(_sock=sock), addr
208 accept.__doc__ = _realsocket.accept.__doc__
Fred Drakea6070f02000-08-16 14:14:32 +0000209
210 def dup(self):
Guido van Rossumc18993f2002-08-08 15:16:20 +0000211 """dup() -> socket object
212
213 Return a new socket object connected to the same system resource."""
214 return _socketobject(_sock=self._sock)
Fred Drakea6070f02000-08-16 14:14:32 +0000215
216 def makefile(self, mode='r', bufsize=-1):
Guido van Rossumc18993f2002-08-08 15:16:20 +0000217 """makefile([mode[, bufsize]]) -> file object
218
219 Return a regular file object corresponding to the socket. The mode
220 and bufsize arguments are as for the built-in open() function."""
Fred Drakea6070f02000-08-16 14:14:32 +0000221 return _fileobject(self._sock, mode, bufsize)
Tim Peters0ae07bd2006-03-22 03:23:21 +0000222
Georg Brandlbb03ac02006-03-21 18:17:25 +0000223 family = property(lambda self: self._sock.family, doc="the socket family")
224 type = property(lambda self: self._sock.type, doc="the socket type")
225 proto = property(lambda self: self._sock.proto, doc="the socket protocol")
Georg Brandlbc45a3f2006-03-17 19:17:34 +0000226
Chris Withersb5248252009-04-11 11:22:19 +0000227def meth(name,self,*args):
228 return getattr(self._sock,name)(*args)
229
230for _m in _socketmethods:
231 p = partial(meth,_m)
232 p.__name__ = _m
233 p.__doc__ = getattr(_realsocket,_m).__doc__
Antoine Pitroudaa524a2009-10-14 18:27:32 +0000234 m = MethodType(p,None,_socketobject)
Chris Withersb5248252009-04-11 11:22:19 +0000235 setattr(_socketobject,_m,m)
Fred Drakea6070f02000-08-16 14:14:32 +0000236
Skip Montanaro89feabc2003-03-30 04:54:24 +0000237socket = SocketType = _socketobject
Fred Drakea6070f02000-08-16 14:14:32 +0000238
Guido van Rossumc18993f2002-08-08 15:16:20 +0000239class _fileobject(object):
Guido van Rossum443fec32002-08-08 01:02:16 +0000240 """Faux file object attached to a socket object."""
241
242 default_bufsize = 8192
Guido van Rossumc18993f2002-08-08 15:16:20 +0000243 name = "<socket>"
244
245 __slots__ = ["mode", "bufsize", "softspace",
246 # "closed" is a property, see below
Kristján Valur Jónsson36c39282009-06-02 13:14:08 +0000247 "_sock", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf", "_wbuf_len",
Georg Brandldd7b0522007-01-21 10:35:10 +0000248 "_close"]
Fred Drakea6070f02000-08-16 14:14:32 +0000249
Georg Brandldd7b0522007-01-21 10:35:10 +0000250 def __init__(self, sock, mode='rb', bufsize=-1, close=False):
Fred Drakea6070f02000-08-16 14:14:32 +0000251 self._sock = sock
Guido van Rossumc18993f2002-08-08 15:16:20 +0000252 self.mode = mode # Not actually used in this version
Guido van Rossum443fec32002-08-08 01:02:16 +0000253 if bufsize < 0:
254 bufsize = self.default_bufsize
Guido van Rossum7c3b6342002-08-08 15:22:12 +0000255 self.bufsize = bufsize
256 self.softspace = False
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000257 # _rbufsize is the suggested recv buffer size. It is *strictly*
258 # obeyed within readline() for recv calls. If it is larger than
259 # default_bufsize it will be used for recv calls within read().
Guido van Rossum443fec32002-08-08 01:02:16 +0000260 if bufsize == 0:
261 self._rbufsize = 1
262 elif bufsize == 1:
263 self._rbufsize = self.default_bufsize
264 else:
265 self._rbufsize = bufsize
Fred Drakea6070f02000-08-16 14:14:32 +0000266 self._wbufsize = bufsize
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000267 # We use StringIO for the read buffer to avoid holding a list
268 # of variously sized string objects which have been known to
269 # fragment the heap due to how they are malloc()ed and often
270 # realloc()ed down much smaller than their original allocation.
271 self._rbuf = StringIO()
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000272 self._wbuf = [] # A list of strings
Kristján Valur Jónsson36c39282009-06-02 13:14:08 +0000273 self._wbuf_len = 0
Georg Brandldd7b0522007-01-21 10:35:10 +0000274 self._close = close
Fred Drakea6070f02000-08-16 14:14:32 +0000275
Guido van Rossumc18993f2002-08-08 15:16:20 +0000276 def _getclosed(self):
Tim Peters116d83c2004-03-28 02:20:45 +0000277 return self._sock is None
Guido van Rossumc18993f2002-08-08 15:16:20 +0000278 closed = property(_getclosed, doc="True if the file is closed")
279
Fred Drakea6070f02000-08-16 14:14:32 +0000280 def close(self):
281 try:
282 if self._sock:
283 self.flush()
284 finally:
Georg Brandldd7b0522007-01-21 10:35:10 +0000285 if self._close:
286 self._sock.close()
Guido van Rossum67f7a382002-06-06 21:08:16 +0000287 self._sock = None
Fred Drakea6070f02000-08-16 14:14:32 +0000288
289 def __del__(self):
Guido van Rossum65f8ced2003-05-29 14:36:57 +0000290 try:
291 self.close()
292 except:
293 # close() may fail if __init__ didn't complete
294 pass
Fred Drakea6070f02000-08-16 14:14:32 +0000295
296 def flush(self):
297 if self._wbuf:
Gregory P. Smithc4ad0342009-08-13 18:54:50 +0000298 data = "".join(self._wbuf)
Guido van Rossum443fec32002-08-08 01:02:16 +0000299 self._wbuf = []
Kristján Valur Jónsson36c39282009-06-02 13:14:08 +0000300 self._wbuf_len = 0
Gregory P. Smithc4ad0342009-08-13 18:54:50 +0000301 buffer_size = max(self._rbufsize, self.default_bufsize)
302 data_size = len(data)
303 write_offset = 0
Antoine Pitroudaa524a2009-10-14 18:27:32 +0000304 view = memoryview(data)
Gregory P. Smithc4ad0342009-08-13 18:54:50 +0000305 try:
306 while write_offset < data_size:
Antoine Pitroudaa524a2009-10-14 18:27:32 +0000307 self._sock.sendall(view[write_offset:write_offset+buffer_size])
Gregory P. Smithc4ad0342009-08-13 18:54:50 +0000308 write_offset += buffer_size
309 finally:
310 if write_offset < data_size:
311 remainder = data[write_offset:]
Antoine Pitroudaa524a2009-10-14 18:27:32 +0000312 del view, data # explicit free
Gregory P. Smithc4ad0342009-08-13 18:54:50 +0000313 self._wbuf.append(remainder)
314 self._wbuf_len = len(remainder)
Fred Drakea6070f02000-08-16 14:14:32 +0000315
Neal Norwitz2b342902002-06-13 22:18:39 +0000316 def fileno(self):
Fred Drakea6070f02000-08-16 14:14:32 +0000317 return self._sock.fileno()
318
319 def write(self, data):
Guido van Rossum443fec32002-08-08 01:02:16 +0000320 data = str(data) # XXX Should really reject non-string non-buffers
321 if not data:
322 return
323 self._wbuf.append(data)
Kristján Valur Jónsson36c39282009-06-02 13:14:08 +0000324 self._wbuf_len += len(data)
Guido van Rossum443fec32002-08-08 01:02:16 +0000325 if (self._wbufsize == 0 or
Kristján Valur Jónsson2380fee2012-12-25 13:04:50 +0000326 (self._wbufsize == 1 and '\n' in data) or
327 (self._wbufsize > 1 and self._wbuf_len >= self._wbufsize)):
Guido van Rossum67f7a382002-06-06 21:08:16 +0000328 self.flush()
Fred Drakea6070f02000-08-16 14:14:32 +0000329
330 def writelines(self, list):
Guido van Rossum443fec32002-08-08 01:02:16 +0000331 # XXX We could do better here for very long lists
332 # XXX Should really reject non-string non-buffers
Kristján Valur Jónsson36c39282009-06-02 13:14:08 +0000333 lines = filter(None, map(str, list))
334 self._wbuf_len += sum(map(len, lines))
335 self._wbuf.extend(lines)
Guido van Rossum443fec32002-08-08 01:02:16 +0000336 if (self._wbufsize <= 1 or
Kristján Valur Jónsson36c39282009-06-02 13:14:08 +0000337 self._wbuf_len >= self._wbufsize):
Guido van Rossum443fec32002-08-08 01:02:16 +0000338 self.flush()
Fred Drakea6070f02000-08-16 14:14:32 +0000339
Guido van Rossum67f7a382002-06-06 21:08:16 +0000340 def read(self, size=-1):
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000341 # Use max, disallow tiny reads in a loop as they are very inefficient.
Gregory P. Smith24237ea2008-05-05 21:53:45 +0000342 # We never leave read() with any leftover data from a new recv() call
343 # in our internal buffer.
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000344 rbufsize = max(self._rbufsize, self.default_bufsize)
345 # Our use of StringIO rather than lists of string objects returned by
346 # recv() minimizes memory usage and fragmentation that occurs when
347 # rbufsize is large compared to the typical return value of recv().
348 buf = self._rbuf
349 buf.seek(0, 2) # seek end
Guido van Rossum443fec32002-08-08 01:02:16 +0000350 if size < 0:
351 # Read until EOF
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000352 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000353 while True:
Gregory P. Smithc4ad0342009-08-13 18:54:50 +0000354 try:
355 data = self._sock.recv(rbufsize)
356 except error, e:
Antoine Pitroudaa524a2009-10-14 18:27:32 +0000357 if e.args[0] == EINTR:
Gregory P. Smithc4ad0342009-08-13 18:54:50 +0000358 continue
359 raise
Guido van Rossum443fec32002-08-08 01:02:16 +0000360 if not data:
361 break
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000362 buf.write(data)
363 return buf.getvalue()
Guido van Rossum443fec32002-08-08 01:02:16 +0000364 else:
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000365 # Read until size bytes or EOF seen, whichever comes first
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000366 buf_len = buf.tell()
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000367 if buf_len >= size:
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000368 # Already have size bytes in our buffer? Extract and return.
369 buf.seek(0)
370 rv = buf.read(size)
371 self._rbuf = StringIO()
372 self._rbuf.write(buf.read())
373 return rv
374
375 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000376 while True:
377 left = size - buf_len
Gregory P. Smith24237ea2008-05-05 21:53:45 +0000378 # recv() will malloc the amount of memory given as its
379 # parameter even though it often returns much less data
380 # than that. The returned data string is short lived
381 # as we copy it into a StringIO and free it. This avoids
382 # fragmentation issues on many platforms.
Gregory P. Smithc4ad0342009-08-13 18:54:50 +0000383 try:
384 data = self._sock.recv(left)
385 except error, e:
Antoine Pitroudaa524a2009-10-14 18:27:32 +0000386 if e.args[0] == EINTR:
Gregory P. Smithc4ad0342009-08-13 18:54:50 +0000387 continue
388 raise
Guido van Rossum443fec32002-08-08 01:02:16 +0000389 if not data:
390 break
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000391 n = len(data)
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000392 if n == size and not buf_len:
393 # Shortcut. Avoid buffer data copies when:
394 # - We have no data in our buffer.
395 # AND
396 # - Our call to recv returned exactly the
397 # number of bytes we were asked to read.
398 return data
Gregory P. Smith24237ea2008-05-05 21:53:45 +0000399 if n == left:
400 buf.write(data)
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000401 del data # explicit free
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000402 break
Gregory P. Smith24237ea2008-05-05 21:53:45 +0000403 assert n <= left, "recv(%d) returned %d bytes" % (left, n)
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000404 buf.write(data)
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000405 buf_len += n
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000406 del data # explicit free
407 #assert buf_len == buf.tell()
408 return buf.getvalue()
Fred Drakea6070f02000-08-16 14:14:32 +0000409
Guido van Rossum67f7a382002-06-06 21:08:16 +0000410 def readline(self, size=-1):
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000411 buf = self._rbuf
Gregory P. Smith24237ea2008-05-05 21:53:45 +0000412 buf.seek(0, 2) # seek end
413 if buf.tell() > 0:
414 # check if we already have it in our buffer
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000415 buf.seek(0)
416 bline = buf.readline(size)
417 if bline.endswith('\n') or len(bline) == size:
418 self._rbuf = StringIO()
419 self._rbuf.write(buf.read())
420 return bline
421 del bline
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000422 if size < 0:
423 # Read until \n or EOF, whichever comes first
Guido van Rossum48b79692002-08-08 17:34:19 +0000424 if self._rbufsize <= 1:
425 # Speed up unbuffered case
Gregory P. Smith24237ea2008-05-05 21:53:45 +0000426 buf.seek(0)
427 buffers = [buf.read()]
428 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000429 data = None
Guido van Rossum48b79692002-08-08 17:34:19 +0000430 recv = self._sock.recv
Gregory P. Smithc4ad0342009-08-13 18:54:50 +0000431 while True:
432 try:
433 while data != "\n":
434 data = recv(1)
435 if not data:
436 break
437 buffers.append(data)
438 except error, e:
439 # The try..except to catch EINTR was moved outside the
440 # recv loop to avoid the per byte overhead.
Antoine Pitroudaa524a2009-10-14 18:27:32 +0000441 if e.args[0] == EINTR:
Gregory P. Smithc4ad0342009-08-13 18:54:50 +0000442 continue
443 raise
444 break
Guido van Rossum48b79692002-08-08 17:34:19 +0000445 return "".join(buffers)
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000446
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000447 buf.seek(0, 2) # seek end
448 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000449 while True:
Gregory P. Smithc4ad0342009-08-13 18:54:50 +0000450 try:
451 data = self._sock.recv(self._rbufsize)
452 except error, e:
Antoine Pitroudaa524a2009-10-14 18:27:32 +0000453 if e.args[0] == EINTR:
Gregory P. Smithc4ad0342009-08-13 18:54:50 +0000454 continue
455 raise
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000456 if not data:
457 break
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000458 nl = data.find('\n')
459 if nl >= 0:
460 nl += 1
Brett Cannon3f92bc62008-08-08 04:27:28 +0000461 buf.write(data[:nl])
462 self._rbuf.write(data[nl:])
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000463 del data
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000464 break
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000465 buf.write(data)
466 return buf.getvalue()
Guido van Rossum67f7a382002-06-06 21:08:16 +0000467 else:
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000468 # Read until size bytes or \n or EOF seen, whichever comes first
Gregory P. Smith24237ea2008-05-05 21:53:45 +0000469 buf.seek(0, 2) # seek end
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000470 buf_len = buf.tell()
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000471 if buf_len >= size:
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000472 buf.seek(0)
473 rv = buf.read(size)
474 self._rbuf = StringIO()
475 self._rbuf.write(buf.read())
476 return rv
477 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000478 while True:
Gregory P. Smithc4ad0342009-08-13 18:54:50 +0000479 try:
480 data = self._sock.recv(self._rbufsize)
481 except error, e:
Antoine Pitroudaa524a2009-10-14 18:27:32 +0000482 if e.args[0] == EINTR:
Gregory P. Smithc4ad0342009-08-13 18:54:50 +0000483 continue
484 raise
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000485 if not data:
486 break
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000487 left = size - buf_len
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000488 # did we just receive a newline?
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000489 nl = data.find('\n', 0, left)
490 if nl >= 0:
491 nl += 1
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000492 # save the excess data to _rbuf
Brett Cannon3f92bc62008-08-08 04:27:28 +0000493 self._rbuf.write(data[nl:])
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000494 if buf_len:
Brett Cannon3f92bc62008-08-08 04:27:28 +0000495 buf.write(data[:nl])
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000496 break
497 else:
498 # Shortcut. Avoid data copy through buf when returning
499 # a substring of our first recv().
500 return data[:nl]
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000501 n = len(data)
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000502 if n == size and not buf_len:
503 # Shortcut. Avoid data copy through buf when
504 # returning exactly all of our first recv().
505 return data
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000506 if n >= left:
Brett Cannon3f92bc62008-08-08 04:27:28 +0000507 buf.write(data[:left])
508 self._rbuf.write(data[left:])
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000509 break
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000510 buf.write(data)
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000511 buf_len += n
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000512 #assert buf_len == buf.tell()
513 return buf.getvalue()
Guido van Rossum67f7a382002-06-06 21:08:16 +0000514
515 def readlines(self, sizehint=0):
Martin v. Löwis6df27f82000-09-19 11:25:58 +0000516 total = 0
Fred Drakea6070f02000-08-16 14:14:32 +0000517 list = []
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000518 while True:
Fred Drakea6070f02000-08-16 14:14:32 +0000519 line = self.readline()
Neal Norwitz2b342902002-06-13 22:18:39 +0000520 if not line:
521 break
Fred Drakea6070f02000-08-16 14:14:32 +0000522 list.append(line)
Martin v. Löwis6df27f82000-09-19 11:25:58 +0000523 total += len(line)
524 if sizehint and total >= sizehint:
525 break
Fred Drakea6070f02000-08-16 14:14:32 +0000526 return list
Guido van Rossum443fec32002-08-08 01:02:16 +0000527
528 # Iterator protocols
529
530 def __iter__(self):
531 return self
532
533 def next(self):
534 line = self.readline()
535 if not line:
536 raise StopIteration
537 return line
Facundo Batista07c78be2007-03-23 18:54:07 +0000538
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000539_GLOBAL_DEFAULT_TIMEOUT = object()
Facundo Batista07c78be2007-03-23 18:54:07 +0000540
Gregory P. Smith79a3eb12010-01-03 01:29:44 +0000541def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT,
542 source_address=None):
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000543 """Connect to *address* and return the socket object.
Facundo Batista07c78be2007-03-23 18:54:07 +0000544
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000545 Convenience function. Connect to *address* (a 2-tuple ``(host,
546 port)``) and return the socket object. Passing the optional
547 *timeout* parameter will set the timeout on the socket instance
548 before attempting to connect. If no *timeout* is supplied, the
549 global default timeout setting returned by :func:`getdefaulttimeout`
Gregory P. Smith79a3eb12010-01-03 01:29:44 +0000550 is used. If *source_address* is set it must be a tuple of (host, port)
551 for the socket to bind as a source address before making the connection.
552 An host of '' or port 0 tells the OS to use the default.
Facundo Batista07c78be2007-03-23 18:54:07 +0000553 """
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000554
Facundo Batista07c78be2007-03-23 18:54:07 +0000555 host, port = address
Antoine Pitrouc818ed42010-09-07 21:40:25 +0000556 err = None
Facundo Batista07c78be2007-03-23 18:54:07 +0000557 for res in getaddrinfo(host, port, 0, SOCK_STREAM):
558 af, socktype, proto, canonname, sa = res
559 sock = None
560 try:
561 sock = socket(af, socktype, proto)
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000562 if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
Facundo Batista07c78be2007-03-23 18:54:07 +0000563 sock.settimeout(timeout)
Gregory P. Smith79a3eb12010-01-03 01:29:44 +0000564 if source_address:
565 sock.bind(source_address)
Facundo Batista07c78be2007-03-23 18:54:07 +0000566 sock.connect(sa)
567 return sock
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000568
Antoine Pitrouc818ed42010-09-07 21:40:25 +0000569 except error as _:
570 err = _
Facundo Batista07c78be2007-03-23 18:54:07 +0000571 if sock is not None:
572 sock.close()
573
Antoine Pitrouc818ed42010-09-07 21:40:25 +0000574 if err is not None:
575 raise err
576 else:
577 raise error("getaddrinfo returns an empty list")