blob: b37914441d255673e19ca0d7e856b589c5f7c1e6 [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
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 *
Chris Withersb5248252009-04-11 11:22:19 +000048from functools import partial
Antoine Pitroudaa524a2009-10-14 18:27:32 +000049from types import MethodType
Tim Peters18e67782002-02-17 04:25:24 +000050
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000051try:
Guido van Rossumde7cade2002-08-08 15:25:28 +000052 import _ssl
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000053except ImportError:
Bill Janssen426ea0a2007-08-29 22:35:05 +000054 # no SSL support
Guido van Rossumc18993f2002-08-08 15:16:20 +000055 pass
Bill Janssen426ea0a2007-08-29 22:35:05 +000056else:
57 def ssl(sock, keyfile=None, certfile=None):
58 # we do an internal import here because the ssl
59 # module imports the socket module
60 import ssl as _realssl
Bill Janssen98d19da2007-09-10 21:51:02 +000061 warnings.warn("socket.ssl() is deprecated. Use ssl.wrap_socket() instead.",
Bill Janssen426ea0a2007-08-29 22:35:05 +000062 DeprecationWarning, stacklevel=2)
63 return _realssl.sslwrap_simple(sock, keyfile, certfile)
Fred Drakea6070f02000-08-16 14:14:32 +000064
Bill Janssen426ea0a2007-08-29 22:35:05 +000065 # we need to import the same constants we used to...
Bill Janssen98d19da2007-09-10 21:51:02 +000066 from _ssl import SSLError as sslerror
Bill Janssen426ea0a2007-08-29 22:35:05 +000067 from _ssl import \
Bill Janssen426ea0a2007-08-29 22:35:05 +000068 RAND_add, \
69 RAND_egd, \
70 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
80
81import os, sys, warnings
Fred Drakea6070f02000-08-16 14:14:32 +000082
Fred Drake70d566b2003-04-29 19:50:25 +000083try:
Gregory P. Smithf8cc6402008-05-02 07:26:52 +000084 from cStringIO import StringIO
85except ImportError:
86 from StringIO import StringIO
87
88try:
Gregory P. Smithc4ad0342009-08-13 18:54:50 +000089 import errno
Fred Drake70d566b2003-04-29 19:50:25 +000090except ImportError:
Gregory P. Smithc4ad0342009-08-13 18:54:50 +000091 errno = None
92EBADF = getattr(errno, 'EBADF', 9)
93EINTR = getattr(errno, 'EINTR', 4)
Fred Drake70d566b2003-04-29 19:50:25 +000094
Benjamin Petersona27e6e32009-04-06 21:53:33 +000095__all__ = ["getfqdn", "create_connection"]
Skip Montanaro0de65802001-02-15 22:15:14 +000096__all__.extend(os._get_exports_list(_socket))
Bill Janssen426ea0a2007-08-29 22:35:05 +000097
Skip Montanaro0de65802001-02-15 22:15:14 +000098
Guido van Rossumc18993f2002-08-08 15:16:20 +000099_realsocket = socket
Fred Drakea6070f02000-08-16 14:14:32 +0000100
101# WSA error codes
102if sys.platform.lower().startswith("win"):
103 errorTab = {}
104 errorTab[10004] = "The operation was interrupted."
105 errorTab[10009] = "A bad file handle was passed."
106 errorTab[10013] = "Permission denied."
107 errorTab[10014] = "A fault occurred on the network??" # WSAEFAULT
108 errorTab[10022] = "An invalid operation was attempted."
109 errorTab[10035] = "The socket operation would block"
110 errorTab[10036] = "A blocking operation is already in progress."
111 errorTab[10048] = "The network address is in use."
112 errorTab[10054] = "The connection has been reset."
113 errorTab[10058] = "The network has been shut down."
114 errorTab[10060] = "The operation timed out."
115 errorTab[10061] = "Connection refused."
116 errorTab[10063] = "The name is too long."
117 errorTab[10064] = "The host is down."
118 errorTab[10065] = "The host is unreachable."
Skip Montanaro64de1a42001-03-18 19:53:21 +0000119 __all__.append("errorTab")
Guido van Rossumde7cade2002-08-08 15:25:28 +0000120
Fred Drakea6070f02000-08-16 14:14:32 +0000121
122
123def getfqdn(name=''):
124 """Get fully qualified domain name from name.
125
126 An empty argument is interpreted as meaning the local host.
127
128 First the hostname returned by gethostbyaddr() is checked, then
129 possibly existing aliases. In case no FQDN is available, hostname
Brett Cannon01668a12005-03-11 00:04:17 +0000130 from gethostname() is returned.
Fred Drakea6070f02000-08-16 14:14:32 +0000131 """
132 name = name.strip()
Peter Schneider-Kamp2d2785a2000-08-16 20:30:21 +0000133 if not name or name == '0.0.0.0':
Fred Drakea6070f02000-08-16 14:14:32 +0000134 name = gethostname()
135 try:
136 hostname, aliases, ipaddrs = gethostbyaddr(name)
137 except error:
138 pass
139 else:
140 aliases.insert(0, hostname)
141 for name in aliases:
142 if '.' in name:
143 break
144 else:
145 name = hostname
146 return name
147
148
Guido van Rossume5e50592001-08-18 01:23:20 +0000149_socketmethods = (
150 'bind', 'connect', 'connect_ex', 'fileno', 'listen',
151 'getpeername', 'getsockname', 'getsockopt', 'setsockopt',
Skip Montanaroc6899182003-04-29 19:27:26 +0000152 'sendall', 'setblocking',
Christian Heimesa47b75b2008-01-04 15:48:06 +0000153 'settimeout', 'gettimeout', 'shutdown')
154
155if os.name == "nt":
156 _socketmethods = _socketmethods + ('ioctl',)
Guido van Rossume5e50592001-08-18 01:23:20 +0000157
Martin v. Löwisa94568a2003-05-10 07:36:56 +0000158if sys.platform == "riscos":
159 _socketmethods = _socketmethods + ('sleeptaskw',)
160
Martin v. Löwis7596e832006-07-01 15:33:37 +0000161# All the method names that must be delegated to either the real socket
162# object or the _closedsocket object.
163_delegate_methods = ("recv", "recvfrom", "recv_into", "recvfrom_into",
164 "send", "sendto")
165
Guido van Rossum715f9702002-08-08 18:11:36 +0000166class _closedsocket(object):
167 __slots__ = []
Skip Montanaroc6899182003-04-29 19:27:26 +0000168 def _dummy(*args):
Fred Drake70d566b2003-04-29 19:50:25 +0000169 raise error(EBADF, 'Bad file descriptor')
Martin v. Löwis7596e832006-07-01 15:33:37 +0000170 # All _delegate_methods must also be initialized here.
171 send = recv = recv_into = sendto = recvfrom = recvfrom_into = _dummy
172 __getattr__ = _dummy
Guido van Rossum715f9702002-08-08 18:11:36 +0000173
Martin v. Löwisf25e35b2007-07-27 18:28:22 +0000174# Wrapper around platform socket objects. This implements
175# a platform-independent dup() functionality. The
176# implementation currently relies on reference counting
177# to close the underlying socket object.
Guido van Rossumc18993f2002-08-08 15:16:20 +0000178class _socketobject(object):
Fred Drakea6070f02000-08-16 14:14:32 +0000179
Guido van Rossumc18993f2002-08-08 15:16:20 +0000180 __doc__ = _realsocket.__doc__
181
Martin v. Löwis7596e832006-07-01 15:33:37 +0000182 __slots__ = ["_sock", "__weakref__"] + list(_delegate_methods)
Guido van Rossumc18993f2002-08-08 15:16:20 +0000183
Guido van Rossumc18993f2002-08-08 15:16:20 +0000184 def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, _sock=None):
185 if _sock is None:
Guido van Rossum7c3b6342002-08-08 15:22:12 +0000186 _sock = _realsocket(family, type, proto)
Guido van Rossumc18993f2002-08-08 15:16:20 +0000187 self._sock = _sock
Martin v. Löwis7596e832006-07-01 15:33:37 +0000188 for method in _delegate_methods:
189 setattr(self, method, getattr(_sock, method))
Fred Drakea6070f02000-08-16 14:14:32 +0000190
191 def close(self):
Guido van Rossum715f9702002-08-08 18:11:36 +0000192 self._sock = _closedsocket()
Martin v. Löwis7596e832006-07-01 15:33:37 +0000193 dummy = self._sock._dummy
194 for method in _delegate_methods:
195 setattr(self, method, dummy)
Guido van Rossumc18993f2002-08-08 15:16:20 +0000196 close.__doc__ = _realsocket.close.__doc__
Fred Drakea6070f02000-08-16 14:14:32 +0000197
Fred Drakea6070f02000-08-16 14:14:32 +0000198 def accept(self):
199 sock, addr = self._sock.accept()
Guido van Rossumc18993f2002-08-08 15:16:20 +0000200 return _socketobject(_sock=sock), addr
201 accept.__doc__ = _realsocket.accept.__doc__
Fred Drakea6070f02000-08-16 14:14:32 +0000202
203 def dup(self):
Guido van Rossumc18993f2002-08-08 15:16:20 +0000204 """dup() -> socket object
205
206 Return a new socket object connected to the same system resource."""
207 return _socketobject(_sock=self._sock)
Fred Drakea6070f02000-08-16 14:14:32 +0000208
209 def makefile(self, mode='r', bufsize=-1):
Guido van Rossumc18993f2002-08-08 15:16:20 +0000210 """makefile([mode[, bufsize]]) -> file object
211
212 Return a regular file object corresponding to the socket. The mode
213 and bufsize arguments are as for the built-in open() function."""
Fred Drakea6070f02000-08-16 14:14:32 +0000214 return _fileobject(self._sock, mode, bufsize)
Tim Peters0ae07bd2006-03-22 03:23:21 +0000215
Georg Brandlbb03ac02006-03-21 18:17:25 +0000216 family = property(lambda self: self._sock.family, doc="the socket family")
217 type = property(lambda self: self._sock.type, doc="the socket type")
218 proto = property(lambda self: self._sock.proto, doc="the socket protocol")
Georg Brandlbc45a3f2006-03-17 19:17:34 +0000219
Chris Withersb5248252009-04-11 11:22:19 +0000220def meth(name,self,*args):
221 return getattr(self._sock,name)(*args)
222
223for _m in _socketmethods:
224 p = partial(meth,_m)
225 p.__name__ = _m
226 p.__doc__ = getattr(_realsocket,_m).__doc__
Antoine Pitroudaa524a2009-10-14 18:27:32 +0000227 m = MethodType(p,None,_socketobject)
Chris Withersb5248252009-04-11 11:22:19 +0000228 setattr(_socketobject,_m,m)
Fred Drakea6070f02000-08-16 14:14:32 +0000229
Skip Montanaro89feabc2003-03-30 04:54:24 +0000230socket = SocketType = _socketobject
Fred Drakea6070f02000-08-16 14:14:32 +0000231
Guido van Rossumc18993f2002-08-08 15:16:20 +0000232class _fileobject(object):
Guido van Rossum443fec32002-08-08 01:02:16 +0000233 """Faux file object attached to a socket object."""
234
235 default_bufsize = 8192
Guido van Rossumc18993f2002-08-08 15:16:20 +0000236 name = "<socket>"
237
238 __slots__ = ["mode", "bufsize", "softspace",
239 # "closed" is a property, see below
Kristján Valur Jónsson36c39282009-06-02 13:14:08 +0000240 "_sock", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf", "_wbuf_len",
Georg Brandldd7b0522007-01-21 10:35:10 +0000241 "_close"]
Fred Drakea6070f02000-08-16 14:14:32 +0000242
Georg Brandldd7b0522007-01-21 10:35:10 +0000243 def __init__(self, sock, mode='rb', bufsize=-1, close=False):
Fred Drakea6070f02000-08-16 14:14:32 +0000244 self._sock = sock
Guido van Rossumc18993f2002-08-08 15:16:20 +0000245 self.mode = mode # Not actually used in this version
Guido van Rossum443fec32002-08-08 01:02:16 +0000246 if bufsize < 0:
247 bufsize = self.default_bufsize
Guido van Rossum7c3b6342002-08-08 15:22:12 +0000248 self.bufsize = bufsize
249 self.softspace = False
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000250 # _rbufsize is the suggested recv buffer size. It is *strictly*
251 # obeyed within readline() for recv calls. If it is larger than
252 # default_bufsize it will be used for recv calls within read().
Guido van Rossum443fec32002-08-08 01:02:16 +0000253 if bufsize == 0:
254 self._rbufsize = 1
255 elif bufsize == 1:
256 self._rbufsize = self.default_bufsize
257 else:
258 self._rbufsize = bufsize
Fred Drakea6070f02000-08-16 14:14:32 +0000259 self._wbufsize = bufsize
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000260 # We use StringIO for the read buffer to avoid holding a list
261 # of variously sized string objects which have been known to
262 # fragment the heap due to how they are malloc()ed and often
263 # realloc()ed down much smaller than their original allocation.
264 self._rbuf = StringIO()
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000265 self._wbuf = [] # A list of strings
Kristján Valur Jónsson36c39282009-06-02 13:14:08 +0000266 self._wbuf_len = 0
Georg Brandldd7b0522007-01-21 10:35:10 +0000267 self._close = close
Fred Drakea6070f02000-08-16 14:14:32 +0000268
Guido van Rossumc18993f2002-08-08 15:16:20 +0000269 def _getclosed(self):
Tim Peters116d83c2004-03-28 02:20:45 +0000270 return self._sock is None
Guido van Rossumc18993f2002-08-08 15:16:20 +0000271 closed = property(_getclosed, doc="True if the file is closed")
272
Fred Drakea6070f02000-08-16 14:14:32 +0000273 def close(self):
274 try:
275 if self._sock:
276 self.flush()
277 finally:
Georg Brandldd7b0522007-01-21 10:35:10 +0000278 if self._close:
279 self._sock.close()
Guido van Rossum67f7a382002-06-06 21:08:16 +0000280 self._sock = None
Fred Drakea6070f02000-08-16 14:14:32 +0000281
282 def __del__(self):
Guido van Rossum65f8ced2003-05-29 14:36:57 +0000283 try:
284 self.close()
285 except:
286 # close() may fail if __init__ didn't complete
287 pass
Fred Drakea6070f02000-08-16 14:14:32 +0000288
289 def flush(self):
290 if self._wbuf:
Gregory P. Smithc4ad0342009-08-13 18:54:50 +0000291 data = "".join(self._wbuf)
Guido van Rossum443fec32002-08-08 01:02:16 +0000292 self._wbuf = []
Kristján Valur Jónsson36c39282009-06-02 13:14:08 +0000293 self._wbuf_len = 0
Gregory P. Smithc4ad0342009-08-13 18:54:50 +0000294 buffer_size = max(self._rbufsize, self.default_bufsize)
295 data_size = len(data)
296 write_offset = 0
Antoine Pitroudaa524a2009-10-14 18:27:32 +0000297 view = memoryview(data)
Gregory P. Smithc4ad0342009-08-13 18:54:50 +0000298 try:
299 while write_offset < data_size:
Antoine Pitroudaa524a2009-10-14 18:27:32 +0000300 self._sock.sendall(view[write_offset:write_offset+buffer_size])
Gregory P. Smithc4ad0342009-08-13 18:54:50 +0000301 write_offset += buffer_size
302 finally:
303 if write_offset < data_size:
304 remainder = data[write_offset:]
Antoine Pitroudaa524a2009-10-14 18:27:32 +0000305 del view, data # explicit free
Gregory P. Smithc4ad0342009-08-13 18:54:50 +0000306 self._wbuf.append(remainder)
307 self._wbuf_len = len(remainder)
Fred Drakea6070f02000-08-16 14:14:32 +0000308
Neal Norwitz2b342902002-06-13 22:18:39 +0000309 def fileno(self):
Fred Drakea6070f02000-08-16 14:14:32 +0000310 return self._sock.fileno()
311
312 def write(self, data):
Guido van Rossum443fec32002-08-08 01:02:16 +0000313 data = str(data) # XXX Should really reject non-string non-buffers
314 if not data:
315 return
316 self._wbuf.append(data)
Kristján Valur Jónsson36c39282009-06-02 13:14:08 +0000317 self._wbuf_len += len(data)
Guido van Rossum443fec32002-08-08 01:02:16 +0000318 if (self._wbufsize == 0 or
319 self._wbufsize == 1 and '\n' in data or
Kristján Valur Jónsson36c39282009-06-02 13:14:08 +0000320 self._wbuf_len >= self._wbufsize):
Guido van Rossum67f7a382002-06-06 21:08:16 +0000321 self.flush()
Fred Drakea6070f02000-08-16 14:14:32 +0000322
323 def writelines(self, list):
Guido van Rossum443fec32002-08-08 01:02:16 +0000324 # XXX We could do better here for very long lists
325 # XXX Should really reject non-string non-buffers
Kristján Valur Jónsson36c39282009-06-02 13:14:08 +0000326 lines = filter(None, map(str, list))
327 self._wbuf_len += sum(map(len, lines))
328 self._wbuf.extend(lines)
Guido van Rossum443fec32002-08-08 01:02:16 +0000329 if (self._wbufsize <= 1 or
Kristján Valur Jónsson36c39282009-06-02 13:14:08 +0000330 self._wbuf_len >= self._wbufsize):
Guido van Rossum443fec32002-08-08 01:02:16 +0000331 self.flush()
Fred Drakea6070f02000-08-16 14:14:32 +0000332
Guido van Rossum67f7a382002-06-06 21:08:16 +0000333 def read(self, size=-1):
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000334 # Use max, disallow tiny reads in a loop as they are very inefficient.
Gregory P. Smith24237ea2008-05-05 21:53:45 +0000335 # We never leave read() with any leftover data from a new recv() call
336 # in our internal buffer.
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000337 rbufsize = max(self._rbufsize, self.default_bufsize)
338 # Our use of StringIO rather than lists of string objects returned by
339 # recv() minimizes memory usage and fragmentation that occurs when
340 # rbufsize is large compared to the typical return value of recv().
341 buf = self._rbuf
342 buf.seek(0, 2) # seek end
Guido van Rossum443fec32002-08-08 01:02:16 +0000343 if size < 0:
344 # Read until EOF
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000345 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000346 while True:
Gregory P. Smithc4ad0342009-08-13 18:54:50 +0000347 try:
348 data = self._sock.recv(rbufsize)
349 except error, e:
Antoine Pitroudaa524a2009-10-14 18:27:32 +0000350 if e.args[0] == EINTR:
Gregory P. Smithc4ad0342009-08-13 18:54:50 +0000351 continue
352 raise
Guido van Rossum443fec32002-08-08 01:02:16 +0000353 if not data:
354 break
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000355 buf.write(data)
356 return buf.getvalue()
Guido van Rossum443fec32002-08-08 01:02:16 +0000357 else:
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000358 # Read until size bytes or EOF seen, whichever comes first
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000359 buf_len = buf.tell()
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000360 if buf_len >= size:
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000361 # Already have size bytes in our buffer? Extract and return.
362 buf.seek(0)
363 rv = buf.read(size)
364 self._rbuf = StringIO()
365 self._rbuf.write(buf.read())
366 return rv
367
368 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000369 while True:
370 left = size - buf_len
Gregory P. Smith24237ea2008-05-05 21:53:45 +0000371 # recv() will malloc the amount of memory given as its
372 # parameter even though it often returns much less data
373 # than that. The returned data string is short lived
374 # as we copy it into a StringIO and free it. This avoids
375 # fragmentation issues on many platforms.
Gregory P. Smithc4ad0342009-08-13 18:54:50 +0000376 try:
377 data = self._sock.recv(left)
378 except error, e:
Antoine Pitroudaa524a2009-10-14 18:27:32 +0000379 if e.args[0] == EINTR:
Gregory P. Smithc4ad0342009-08-13 18:54:50 +0000380 continue
381 raise
Guido van Rossum443fec32002-08-08 01:02:16 +0000382 if not data:
383 break
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000384 n = len(data)
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000385 if n == size and not buf_len:
386 # Shortcut. Avoid buffer data copies when:
387 # - We have no data in our buffer.
388 # AND
389 # - Our call to recv returned exactly the
390 # number of bytes we were asked to read.
391 return data
Gregory P. Smith24237ea2008-05-05 21:53:45 +0000392 if n == left:
393 buf.write(data)
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000394 del data # explicit free
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000395 break
Gregory P. Smith24237ea2008-05-05 21:53:45 +0000396 assert n <= left, "recv(%d) returned %d bytes" % (left, n)
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000397 buf.write(data)
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000398 buf_len += n
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000399 del data # explicit free
400 #assert buf_len == buf.tell()
401 return buf.getvalue()
Fred Drakea6070f02000-08-16 14:14:32 +0000402
Guido van Rossum67f7a382002-06-06 21:08:16 +0000403 def readline(self, size=-1):
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000404 buf = self._rbuf
Gregory P. Smith24237ea2008-05-05 21:53:45 +0000405 buf.seek(0, 2) # seek end
406 if buf.tell() > 0:
407 # check if we already have it in our buffer
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000408 buf.seek(0)
409 bline = buf.readline(size)
410 if bline.endswith('\n') or len(bline) == size:
411 self._rbuf = StringIO()
412 self._rbuf.write(buf.read())
413 return bline
414 del bline
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000415 if size < 0:
416 # Read until \n or EOF, whichever comes first
Guido van Rossum48b79692002-08-08 17:34:19 +0000417 if self._rbufsize <= 1:
418 # Speed up unbuffered case
Gregory P. Smith24237ea2008-05-05 21:53:45 +0000419 buf.seek(0)
420 buffers = [buf.read()]
421 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000422 data = None
Guido van Rossum48b79692002-08-08 17:34:19 +0000423 recv = self._sock.recv
Gregory P. Smithc4ad0342009-08-13 18:54:50 +0000424 while True:
425 try:
426 while data != "\n":
427 data = recv(1)
428 if not data:
429 break
430 buffers.append(data)
431 except error, e:
432 # The try..except to catch EINTR was moved outside the
433 # recv loop to avoid the per byte overhead.
Antoine Pitroudaa524a2009-10-14 18:27:32 +0000434 if e.args[0] == EINTR:
Gregory P. Smithc4ad0342009-08-13 18:54:50 +0000435 continue
436 raise
437 break
Guido van Rossum48b79692002-08-08 17:34:19 +0000438 return "".join(buffers)
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000439
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000440 buf.seek(0, 2) # seek end
441 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000442 while True:
Gregory P. Smithc4ad0342009-08-13 18:54:50 +0000443 try:
444 data = self._sock.recv(self._rbufsize)
445 except error, e:
Antoine Pitroudaa524a2009-10-14 18:27:32 +0000446 if e.args[0] == EINTR:
Gregory P. Smithc4ad0342009-08-13 18:54:50 +0000447 continue
448 raise
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000449 if not data:
450 break
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000451 nl = data.find('\n')
452 if nl >= 0:
453 nl += 1
Brett Cannon3f92bc62008-08-08 04:27:28 +0000454 buf.write(data[:nl])
455 self._rbuf.write(data[nl:])
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000456 del data
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000457 break
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000458 buf.write(data)
459 return buf.getvalue()
Guido van Rossum67f7a382002-06-06 21:08:16 +0000460 else:
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000461 # Read until size bytes or \n or EOF seen, whichever comes first
Gregory P. Smith24237ea2008-05-05 21:53:45 +0000462 buf.seek(0, 2) # seek end
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000463 buf_len = buf.tell()
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000464 if buf_len >= size:
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000465 buf.seek(0)
466 rv = buf.read(size)
467 self._rbuf = StringIO()
468 self._rbuf.write(buf.read())
469 return rv
470 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000471 while True:
Gregory P. Smithc4ad0342009-08-13 18:54:50 +0000472 try:
473 data = self._sock.recv(self._rbufsize)
474 except error, e:
Antoine Pitroudaa524a2009-10-14 18:27:32 +0000475 if e.args[0] == EINTR:
Gregory P. Smithc4ad0342009-08-13 18:54:50 +0000476 continue
477 raise
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000478 if not data:
479 break
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000480 left = size - buf_len
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000481 # did we just receive a newline?
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000482 nl = data.find('\n', 0, left)
483 if nl >= 0:
484 nl += 1
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000485 # save the excess data to _rbuf
Brett Cannon3f92bc62008-08-08 04:27:28 +0000486 self._rbuf.write(data[nl:])
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000487 if buf_len:
Brett Cannon3f92bc62008-08-08 04:27:28 +0000488 buf.write(data[:nl])
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000489 break
490 else:
491 # Shortcut. Avoid data copy through buf when returning
492 # a substring of our first recv().
493 return data[:nl]
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000494 n = len(data)
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000495 if n == size and not buf_len:
496 # Shortcut. Avoid data copy through buf when
497 # returning exactly all of our first recv().
498 return data
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000499 if n >= left:
Brett Cannon3f92bc62008-08-08 04:27:28 +0000500 buf.write(data[:left])
501 self._rbuf.write(data[left:])
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000502 break
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000503 buf.write(data)
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000504 buf_len += n
Gregory P. Smithf8cc6402008-05-02 07:26:52 +0000505 #assert buf_len == buf.tell()
506 return buf.getvalue()
Guido van Rossum67f7a382002-06-06 21:08:16 +0000507
508 def readlines(self, sizehint=0):
Martin v. Löwis6df27f82000-09-19 11:25:58 +0000509 total = 0
Fred Drakea6070f02000-08-16 14:14:32 +0000510 list = []
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000511 while True:
Fred Drakea6070f02000-08-16 14:14:32 +0000512 line = self.readline()
Neal Norwitz2b342902002-06-13 22:18:39 +0000513 if not line:
514 break
Fred Drakea6070f02000-08-16 14:14:32 +0000515 list.append(line)
Martin v. Löwis6df27f82000-09-19 11:25:58 +0000516 total += len(line)
517 if sizehint and total >= sizehint:
518 break
Fred Drakea6070f02000-08-16 14:14:32 +0000519 return list
Guido van Rossum443fec32002-08-08 01:02:16 +0000520
521 # Iterator protocols
522
523 def __iter__(self):
524 return self
525
526 def next(self):
527 line = self.readline()
528 if not line:
529 raise StopIteration
530 return line
Facundo Batista07c78be2007-03-23 18:54:07 +0000531
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000532_GLOBAL_DEFAULT_TIMEOUT = object()
Facundo Batista07c78be2007-03-23 18:54:07 +0000533
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000534def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT):
535 """Connect to *address* and return the socket object.
Facundo Batista07c78be2007-03-23 18:54:07 +0000536
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000537 Convenience function. Connect to *address* (a 2-tuple ``(host,
538 port)``) and return the socket object. Passing the optional
539 *timeout* parameter will set the timeout on the socket instance
540 before attempting to connect. If no *timeout* is supplied, the
541 global default timeout setting returned by :func:`getdefaulttimeout`
542 is used.
Facundo Batista07c78be2007-03-23 18:54:07 +0000543 """
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000544
Facundo Batista07c78be2007-03-23 18:54:07 +0000545 msg = "getaddrinfo returns an empty list"
546 host, port = address
547 for res in getaddrinfo(host, port, 0, SOCK_STREAM):
548 af, socktype, proto, canonname, sa = res
549 sock = None
550 try:
551 sock = socket(af, socktype, proto)
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000552 if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
Facundo Batista07c78be2007-03-23 18:54:07 +0000553 sock.settimeout(timeout)
554 sock.connect(sa)
555 return sock
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000556
Facundo Batista07c78be2007-03-23 18:54:07 +0000557 except error, msg:
558 if sock is not None:
559 sock.close()
560
561 raise error, msg