blob: fb96637d74e7eaa9643cf65d1fd540b9b725612e [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
Guido van Rossumc18993f2002-08-08 15:16:20 +000049_have_ssl = False
Guido van Rossum245b42e2007-08-29 03:59:57 +000050## try:
51## import _ssl
52## from _ssl import *
53## _have_ssl = True
54## except ImportError:
55## pass
Fred Drakea6070f02000-08-16 14:14:32 +000056
Guido van Rossum7d0a8262007-05-21 23:13:11 +000057import os, sys, io
Fred Drakea6070f02000-08-16 14:14:32 +000058
Fred Drake70d566b2003-04-29 19:50:25 +000059try:
60 from errno import EBADF
61except ImportError:
62 EBADF = 9
63
Skip Montanaro0de65802001-02-15 22:15:14 +000064__all__ = ["getfqdn"]
Skip Montanaro0de65802001-02-15 22:15:14 +000065__all__.extend(os._get_exports_list(_socket))
Guido van Rossumde7cade2002-08-08 15:25:28 +000066if _have_ssl:
67 __all__.extend(os._get_exports_list(_ssl))
Thomas Woutersed03b412007-08-28 21:37:11 +000068 def ssl(sock, keyfile=None, certfile=None):
69 import ssl as realssl
70 return realssl.sslwrap_simple(sock, keyfile, certfile)
71 __all__.append("ssl")
Skip Montanaro0de65802001-02-15 22:15:14 +000072
Fred Drakea6070f02000-08-16 14:14:32 +000073# WSA error codes
74if sys.platform.lower().startswith("win"):
75 errorTab = {}
76 errorTab[10004] = "The operation was interrupted."
77 errorTab[10009] = "A bad file handle was passed."
78 errorTab[10013] = "Permission denied."
79 errorTab[10014] = "A fault occurred on the network??" # WSAEFAULT
80 errorTab[10022] = "An invalid operation was attempted."
81 errorTab[10035] = "The socket operation would block"
82 errorTab[10036] = "A blocking operation is already in progress."
83 errorTab[10048] = "The network address is in use."
84 errorTab[10054] = "The connection has been reset."
85 errorTab[10058] = "The network has been shut down."
86 errorTab[10060] = "The operation timed out."
87 errorTab[10061] = "Connection refused."
88 errorTab[10063] = "The name is too long."
89 errorTab[10064] = "The host is down."
90 errorTab[10065] = "The host is unreachable."
Skip Montanaro64de1a42001-03-18 19:53:21 +000091 __all__.append("errorTab")
Guido van Rossumde7cade2002-08-08 15:25:28 +000092
Fred Drakea6070f02000-08-16 14:14:32 +000093
Guido van Rossum93adc5d2007-07-17 20:41:19 +000094# True if os.dup() can duplicate socket descriptors.
95# (On Windows at least, os.dup only works on files)
Jeremy Hylton5accbdb2007-08-03 20:40:09 +000096_can_dup_socket = hasattr(_socket.socket, "dup")
Guido van Rossum93adc5d2007-07-17 20:41:19 +000097
98if _can_dup_socket:
Guido van Rossum7d0a8262007-05-21 23:13:11 +000099 def fromfd(fd, family=AF_INET, type=SOCK_STREAM, proto=0):
100 nfd = os.dup(fd)
101 return socket(family, type, proto, fileno=nfd)
102
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000103class SocketCloser:
104
105 """Helper to manage socket close() logic for makefile().
106
107 The OS socket should not be closed until the socket and all
108 of its makefile-children are closed. If the refcount is zero
109 when socket.close() is called, this is easy: Just close the
110 socket. If the refcount is non-zero when socket.close() is
111 called, then the real close should not occur until the last
112 makefile-child is closed.
113 """
114
115 def __init__(self, sock):
116 self._sock = sock
117 self._makefile_refs = 0
118 # Test whether the socket is open.
119 try:
120 sock.fileno()
121 self._socket_open = True
122 except error:
123 self._socket_open = False
124
125 def socket_close(self):
126 self._socket_open = False
127 self.close()
128
129 def makefile_open(self):
130 self._makefile_refs += 1
131
132 def makefile_close(self):
133 self._makefile_refs -= 1
134 self.close()
135
136 def close(self):
137 if not (self._socket_open or self._makefile_refs):
138 self._sock._real_close()
139
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000140
141class socket(_socket.socket):
142
143 """A subclass of _socket.socket adding the makefile() method."""
144
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000145 __slots__ = ["__weakref__", "_closer"]
Guido van Rossum93adc5d2007-07-17 20:41:19 +0000146 if not _can_dup_socket:
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000147 __slots__.append("_base")
148
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000149 def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None):
150 if fileno is None:
151 _socket.socket.__init__(self, family, type, proto)
152 else:
153 _socket.socket.__init__(self, family, type, proto, fileno)
154 # Defer creating a SocketCloser until makefile() is actually called.
155 self._closer = None
156
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000157 def __repr__(self):
158 """Wrap __repr__() to reveal the real class name."""
159 s = _socket.socket.__repr__(self)
160 if s.startswith("<socket object"):
161 s = "<%s.%s%s" % (self.__class__.__module__,
162 self.__class__.__name__,
163 s[7:])
164 return s
165
166 def accept(self):
167 """Wrap accept() to give the connection the right type."""
168 conn, addr = _socket.socket.accept(self)
169 fd = conn.fileno()
170 nfd = fd
Guido van Rossum93adc5d2007-07-17 20:41:19 +0000171 if _can_dup_socket:
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000172 nfd = os.dup(fd)
173 wrapper = socket(self.family, self.type, self.proto, fileno=nfd)
174 if fd == nfd:
175 wrapper._base = conn # Keep the base alive
176 else:
177 conn.close()
178 return wrapper, addr
179
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000180 def makefile(self, mode="r", buffering=None, *,
181 encoding=None, newline=None):
182 """Return an I/O stream connected to the socket.
183
184 The arguments are as for io.open() after the filename,
185 except the only mode characters supported are 'r', 'w' and 'b'.
186 The semantics are similar too. (XXX refactor to share code?)
187 """
188 for c in mode:
189 if c not in {"r", "w", "b"}:
190 raise ValueError("invalid mode %r (only r, w, b allowed)")
191 writing = "w" in mode
192 reading = "r" in mode or not writing
193 assert reading or writing
194 binary = "b" in mode
195 rawmode = ""
196 if reading:
197 rawmode += "r"
198 if writing:
199 rawmode += "w"
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000200 if self._closer is None:
201 self._closer = SocketCloser(self)
202 raw = SocketIO(self, rawmode, self._closer)
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000203 if buffering is None:
204 buffering = -1
205 if buffering < 0:
206 buffering = io.DEFAULT_BUFFER_SIZE
207 if buffering == 0:
208 if not binary:
209 raise ValueError("unbuffered streams must be binary")
210 raw.name = self.fileno()
211 raw.mode = mode
212 return raw
213 if reading and writing:
214 buffer = io.BufferedRWPair(raw, raw, buffering)
215 elif reading:
216 buffer = io.BufferedReader(raw, buffering)
217 else:
218 assert writing
219 buffer = io.BufferedWriter(raw, buffering)
220 if binary:
221 buffer.name = self.fileno()
222 buffer.mode = mode
223 return buffer
224 text = io.TextIOWrapper(buffer, encoding, newline)
225 text.name = self.fileno()
Guido van Rossum93adc5d2007-07-17 20:41:19 +0000226 text.mode = mode
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000227 return text
228
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000229 def close(self):
230 if self._closer is None:
231 self._real_close()
232 else:
233 self._closer.socket_close()
234
235 # _real_close calls close on the _socket.socket base class.
236
237 if not _can_dup_socket:
238 def _real_close(self):
239 _socket.socket.close(self)
240 base = getattr(self, "_base", None)
241 if base is not None:
242 self._base = None
243 base.close()
244 else:
245 def _real_close(self):
246 _socket.socket.close(self)
247
248
249class SocketIO(io.RawIOBase):
250
251 """Raw I/O implementation for stream sockets.
252
253 This class supports the makefile() method on sockets. It provides
254 the raw I/O interface on top of a socket object.
255 """
256
257 # XXX More docs
258
259 def __init__(self, sock, mode, closer):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000260 if mode not in ("r", "w", "rw"):
261 raise ValueError("invalid mode: %r" % mode)
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000262 io.RawIOBase.__init__(self)
263 self._sock = sock
264 self._mode = mode
265 self._closer = closer
Guido van Rossum5abbf752007-08-27 17:39:33 +0000266 self._reading = "r" in mode
267 self._writing = "w" in mode
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000268 closer.makefile_open()
269
270 def readinto(self, b):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000271 self._checkClosed()
272 self._checkReadable()
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000273 return self._sock.recv_into(b)
274
275 def write(self, b):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000276 self._checkClosed()
277 self._checkWritable()
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000278 return self._sock.send(b)
279
280 def readable(self):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000281 return self._reading and not self.closed
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000282
283 def writable(self):
Guido van Rossum5abbf752007-08-27 17:39:33 +0000284 return self._writing and not self.closed
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000285
286 def fileno(self):
287 return self._sock.fileno()
288
289 def close(self):
290 if self.closed:
291 return
292 self._closer.makefile_close()
293 io.RawIOBase.close(self)
294
Fred Drakea6070f02000-08-16 14:14:32 +0000295
296def getfqdn(name=''):
297 """Get fully qualified domain name from name.
298
299 An empty argument is interpreted as meaning the local host.
300
301 First the hostname returned by gethostbyaddr() is checked, then
302 possibly existing aliases. In case no FQDN is available, hostname
Brett Cannon01668a12005-03-11 00:04:17 +0000303 from gethostname() is returned.
Fred Drakea6070f02000-08-16 14:14:32 +0000304 """
305 name = name.strip()
Peter Schneider-Kamp2d2785a2000-08-16 20:30:21 +0000306 if not name or name == '0.0.0.0':
Fred Drakea6070f02000-08-16 14:14:32 +0000307 name = gethostname()
308 try:
309 hostname, aliases, ipaddrs = gethostbyaddr(name)
310 except error:
311 pass
312 else:
313 aliases.insert(0, hostname)
314 for name in aliases:
315 if '.' in name:
316 break
317 else:
318 name = hostname
319 return name
320
321
Guido van Rossumd8faa362007-04-27 19:54:29 +0000322def create_connection(address, timeout=None):
323 """Connect to address (host, port) with an optional timeout.
324
325 Provides access to socketobject timeout for higher-level
326 protocols. Passing a timeout will set the timeout on the
327 socket instance (if not present, or passed as None, the
328 default global timeout setting will be used).
329 """
330
331 msg = "getaddrinfo returns an empty list"
332 host, port = address
333 for res in getaddrinfo(host, port, 0, SOCK_STREAM):
334 af, socktype, proto, canonname, sa = res
335 sock = None
336 try:
337 sock = socket(af, socktype, proto)
338 if timeout is not None:
339 sock.settimeout(timeout)
340 sock.connect(sa)
341 return sock
342
343 except error as err:
344 msg = err
345 if sock is not None:
346 sock.close()
347
348 raise error(msg)