blob: 0da08ae4481a43004025a0d7e7d173928035c9b9 [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
Guido van Rossumd8faa362007-04-27 19:54:29 +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
Thomas Wouters47b49bf2007-08-30 22:15:33 +000049try:
50 import _ssl
51 import ssl as _realssl
52except ImportError:
53 # no SSL support
54 pass
55else:
56 def ssl(sock, keyfile=None, certfile=None):
57 # we do an internal import here because the ssl
58 # module imports the socket module
59 warnings.warn("socket.ssl() is deprecated. Use ssl.sslsocket() instead.",
60 DeprecationWarning, stacklevel=2)
61 return _realssl.sslwrap_simple(sock, keyfile, certfile)
62
63 # we need to import the same constants we used to...
64 from _ssl import \
65 sslerror, \
66 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
Fred Drakea6070f02000-08-16 14:14:32 +000078
Guido van Rossum7d0a8262007-05-21 23:13:11 +000079import os, sys, io
Fred Drakea6070f02000-08-16 14:14:32 +000080
Fred Drake70d566b2003-04-29 19:50:25 +000081try:
82 from errno import EBADF
83except ImportError:
84 EBADF = 9
85
Skip Montanaro0de65802001-02-15 22:15:14 +000086__all__ = ["getfqdn"]
Skip Montanaro0de65802001-02-15 22:15:14 +000087__all__.extend(os._get_exports_list(_socket))
Thomas Wouters47b49bf2007-08-30 22:15:33 +000088
89
90_realsocket = socket
Skip Montanaro0de65802001-02-15 22:15:14 +000091
Fred Drakea6070f02000-08-16 14:14:32 +000092# WSA error codes
93if sys.platform.lower().startswith("win"):
94 errorTab = {}
95 errorTab[10004] = "The operation was interrupted."
96 errorTab[10009] = "A bad file handle was passed."
97 errorTab[10013] = "Permission denied."
98 errorTab[10014] = "A fault occurred on the network??" # WSAEFAULT
99 errorTab[10022] = "An invalid operation was attempted."
100 errorTab[10035] = "The socket operation would block"
101 errorTab[10036] = "A blocking operation is already in progress."
102 errorTab[10048] = "The network address is in use."
103 errorTab[10054] = "The connection has been reset."
104 errorTab[10058] = "The network has been shut down."
105 errorTab[10060] = "The operation timed out."
106 errorTab[10061] = "Connection refused."
107 errorTab[10063] = "The name is too long."
108 errorTab[10064] = "The host is down."
109 errorTab[10065] = "The host is unreachable."
Skip Montanaro64de1a42001-03-18 19:53:21 +0000110 __all__.append("errorTab")
Guido van Rossumde7cade2002-08-08 15:25:28 +0000111
Fred Drakea6070f02000-08-16 14:14:32 +0000112
Guido van Rossum93adc5d2007-07-17 20:41:19 +0000113# True if os.dup() can duplicate socket descriptors.
114# (On Windows at least, os.dup only works on files)
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000115_can_dup_socket = hasattr(_socket.socket, "dup")
Guido van Rossum93adc5d2007-07-17 20:41:19 +0000116
117if _can_dup_socket:
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000118 def fromfd(fd, family=AF_INET, type=SOCK_STREAM, proto=0):
119 nfd = os.dup(fd)
120 return socket(family, type, proto, fileno=nfd)
121
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000122class SocketCloser:
123
124 """Helper to manage socket close() logic for makefile().
125
126 The OS socket should not be closed until the socket and all
127 of its makefile-children are closed. If the refcount is zero
128 when socket.close() is called, this is easy: Just close the
129 socket. If the refcount is non-zero when socket.close() is
130 called, then the real close should not occur until the last
131 makefile-child is closed.
132 """
133
134 def __init__(self, sock):
135 self._sock = sock
136 self._makefile_refs = 0
137 # Test whether the socket is open.
138 try:
139 sock.fileno()
140 self._socket_open = True
141 except error:
142 self._socket_open = False
143
144 def socket_close(self):
145 self._socket_open = False
146 self.close()
147
148 def makefile_open(self):
149 self._makefile_refs += 1
150
151 def makefile_close(self):
152 self._makefile_refs -= 1
153 self.close()
154
155 def close(self):
156 if not (self._socket_open or self._makefile_refs):
157 self._sock._real_close()
158
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000159
160class socket(_socket.socket):
161
162 """A subclass of _socket.socket adding the makefile() method."""
163
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000164 __slots__ = ["__weakref__", "_closer"]
Guido van Rossum93adc5d2007-07-17 20:41:19 +0000165 if not _can_dup_socket:
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000166 __slots__.append("_base")
167
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000168 def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None):
169 if fileno is None:
170 _socket.socket.__init__(self, family, type, proto)
171 else:
172 _socket.socket.__init__(self, family, type, proto, fileno)
173 # Defer creating a SocketCloser until makefile() is actually called.
174 self._closer = None
175
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000176 def __repr__(self):
177 """Wrap __repr__() to reveal the real class name."""
178 s = _socket.socket.__repr__(self)
179 if s.startswith("<socket object"):
180 s = "<%s.%s%s" % (self.__class__.__module__,
181 self.__class__.__name__,
182 s[7:])
183 return s
184
185 def accept(self):
186 """Wrap accept() to give the connection the right type."""
187 conn, addr = _socket.socket.accept(self)
188 fd = conn.fileno()
189 nfd = fd
Guido van Rossum93adc5d2007-07-17 20:41:19 +0000190 if _can_dup_socket:
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000191 nfd = os.dup(fd)
192 wrapper = socket(self.family, self.type, self.proto, fileno=nfd)
193 if fd == nfd:
194 wrapper._base = conn # Keep the base alive
195 else:
196 conn.close()
197 return wrapper, addr
198
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000199 def makefile(self, mode="r", buffering=None, *,
200 encoding=None, newline=None):
201 """Return an I/O stream connected to the socket.
202
203 The arguments are as for io.open() after the filename,
204 except the only mode characters supported are 'r', 'w' and 'b'.
205 The semantics are similar too. (XXX refactor to share code?)
206 """
207 for c in mode:
208 if c not in {"r", "w", "b"}:
209 raise ValueError("invalid mode %r (only r, w, b allowed)")
210 writing = "w" in mode
211 reading = "r" in mode or not writing
212 assert reading or writing
213 binary = "b" in mode
214 rawmode = ""
215 if reading:
216 rawmode += "r"
217 if writing:
218 rawmode += "w"
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000219 if self._closer is None:
220 self._closer = SocketCloser(self)
221 raw = SocketIO(self, rawmode, self._closer)
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000222 if buffering is None:
223 buffering = -1
224 if buffering < 0:
225 buffering = io.DEFAULT_BUFFER_SIZE
226 if buffering == 0:
227 if not binary:
228 raise ValueError("unbuffered streams must be binary")
229 raw.name = self.fileno()
230 raw.mode = mode
231 return raw
232 if reading and writing:
233 buffer = io.BufferedRWPair(raw, raw, buffering)
234 elif reading:
235 buffer = io.BufferedReader(raw, buffering)
236 else:
237 assert writing
238 buffer = io.BufferedWriter(raw, buffering)
239 if binary:
240 buffer.name = self.fileno()
241 buffer.mode = mode
242 return buffer
243 text = io.TextIOWrapper(buffer, encoding, newline)
244 text.name = self.fileno()
Guido van Rossum93adc5d2007-07-17 20:41:19 +0000245 text.mode = mode
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000246 return text
247
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000248 def close(self):
249 if self._closer is None:
250 self._real_close()
251 else:
252 self._closer.socket_close()
253
254 # _real_close calls close on the _socket.socket base class.
255
256 if not _can_dup_socket:
257 def _real_close(self):
258 _socket.socket.close(self)
259 base = getattr(self, "_base", None)
260 if base is not None:
261 self._base = None
262 base.close()
263 else:
264 def _real_close(self):
265 _socket.socket.close(self)
266
267
268class SocketIO(io.RawIOBase):
269
270 """Raw I/O implementation for stream sockets.
271
272 This class supports the makefile() method on sockets. It provides
273 the raw I/O interface on top of a socket object.
274 """
275
276 # XXX More docs
277
278 def __init__(self, sock, mode, closer):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000279 if mode not in ("r", "w", "rw"):
280 raise ValueError("invalid mode: %r" % mode)
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000281 io.RawIOBase.__init__(self)
282 self._sock = sock
283 self._mode = mode
284 self._closer = closer
Guido van Rossum5abbf752007-08-27 17:39:33 +0000285 self._reading = "r" in mode
286 self._writing = "w" in mode
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000287 closer.makefile_open()
288
289 def readinto(self, b):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000290 self._checkClosed()
291 self._checkReadable()
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000292 return self._sock.recv_into(b)
293
294 def write(self, b):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000295 self._checkClosed()
296 self._checkWritable()
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000297 return self._sock.send(b)
298
299 def readable(self):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000300 return self._reading and not self.closed
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000301
302 def writable(self):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000303 return self._writing and not self.closed
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000304
305 def fileno(self):
306 return self._sock.fileno()
307
308 def close(self):
309 if self.closed:
310 return
311 self._closer.makefile_close()
312 io.RawIOBase.close(self)
313
Fred Drakea6070f02000-08-16 14:14:32 +0000314
315def getfqdn(name=''):
316 """Get fully qualified domain name from name.
317
318 An empty argument is interpreted as meaning the local host.
319
320 First the hostname returned by gethostbyaddr() is checked, then
321 possibly existing aliases. In case no FQDN is available, hostname
Brett Cannon01668a12005-03-11 00:04:17 +0000322 from gethostname() is returned.
Fred Drakea6070f02000-08-16 14:14:32 +0000323 """
324 name = name.strip()
Peter Schneider-Kamp2d2785a2000-08-16 20:30:21 +0000325 if not name or name == '0.0.0.0':
Fred Drakea6070f02000-08-16 14:14:32 +0000326 name = gethostname()
327 try:
328 hostname, aliases, ipaddrs = gethostbyaddr(name)
329 except error:
330 pass
331 else:
332 aliases.insert(0, hostname)
333 for name in aliases:
334 if '.' in name:
335 break
336 else:
337 name = hostname
338 return name
339
340
Guido van Rossumd8faa362007-04-27 19:54:29 +0000341def create_connection(address, timeout=None):
342 """Connect to address (host, port) with an optional timeout.
343
344 Provides access to socketobject timeout for higher-level
345 protocols. Passing a timeout will set the timeout on the
346 socket instance (if not present, or passed as None, the
347 default global timeout setting will be used).
348 """
349
350 msg = "getaddrinfo returns an empty list"
351 host, port = address
352 for res in getaddrinfo(host, port, 0, SOCK_STREAM):
353 af, socktype, proto, canonname, sa = res
354 sock = None
355 try:
356 sock = socket(af, socktype, proto)
357 if timeout is not None:
358 sock.settimeout(timeout)
359 sock.connect(sa)
360 return sock
361
362 except error as err:
363 msg = err
364 if sock is not None:
365 sock.close()
366
367 raise error(msg)