blob: 1b3920adf9087f73ce763812b56ba920d4eea2b2 [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
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000050try:
Guido van Rossumde7cade2002-08-08 15:25:28 +000051 import _ssl
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000052 from _ssl import *
Guido van Rossumc18993f2002-08-08 15:16:20 +000053 _have_ssl = True
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000054except ImportError:
Guido van Rossumc18993f2002-08-08 15:16:20 +000055 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))
Skip Montanaro0de65802001-02-15 22:15:14 +000068
Fred Drakea6070f02000-08-16 14:14:32 +000069# WSA error codes
70if sys.platform.lower().startswith("win"):
71 errorTab = {}
72 errorTab[10004] = "The operation was interrupted."
73 errorTab[10009] = "A bad file handle was passed."
74 errorTab[10013] = "Permission denied."
75 errorTab[10014] = "A fault occurred on the network??" # WSAEFAULT
76 errorTab[10022] = "An invalid operation was attempted."
77 errorTab[10035] = "The socket operation would block"
78 errorTab[10036] = "A blocking operation is already in progress."
79 errorTab[10048] = "The network address is in use."
80 errorTab[10054] = "The connection has been reset."
81 errorTab[10058] = "The network has been shut down."
82 errorTab[10060] = "The operation timed out."
83 errorTab[10061] = "Connection refused."
84 errorTab[10063] = "The name is too long."
85 errorTab[10064] = "The host is down."
86 errorTab[10065] = "The host is unreachable."
Skip Montanaro64de1a42001-03-18 19:53:21 +000087 __all__.append("errorTab")
Guido van Rossumde7cade2002-08-08 15:25:28 +000088
Fred Drakea6070f02000-08-16 14:14:32 +000089
Guido van Rossum93adc5d2007-07-17 20:41:19 +000090# True if os.dup() can duplicate socket descriptors.
91# (On Windows at least, os.dup only works on files)
Jeremy Hylton5accbdb2007-08-03 20:40:09 +000092_can_dup_socket = hasattr(_socket.socket, "dup")
Guido van Rossum93adc5d2007-07-17 20:41:19 +000093
94if _can_dup_socket:
Guido van Rossum7d0a8262007-05-21 23:13:11 +000095 def fromfd(fd, family=AF_INET, type=SOCK_STREAM, proto=0):
96 nfd = os.dup(fd)
97 return socket(family, type, proto, fileno=nfd)
98
Jeremy Hylton5accbdb2007-08-03 20:40:09 +000099class SocketCloser:
100
101 """Helper to manage socket close() logic for makefile().
102
103 The OS socket should not be closed until the socket and all
104 of its makefile-children are closed. If the refcount is zero
105 when socket.close() is called, this is easy: Just close the
106 socket. If the refcount is non-zero when socket.close() is
107 called, then the real close should not occur until the last
108 makefile-child is closed.
109 """
110
111 def __init__(self, sock):
112 self._sock = sock
113 self._makefile_refs = 0
114 # Test whether the socket is open.
115 try:
116 sock.fileno()
117 self._socket_open = True
118 except error:
119 self._socket_open = False
120
121 def socket_close(self):
122 self._socket_open = False
123 self.close()
124
125 def makefile_open(self):
126 self._makefile_refs += 1
127
128 def makefile_close(self):
129 self._makefile_refs -= 1
130 self.close()
131
132 def close(self):
133 if not (self._socket_open or self._makefile_refs):
134 self._sock._real_close()
135
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000136
137class socket(_socket.socket):
138
139 """A subclass of _socket.socket adding the makefile() method."""
140
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000141 __slots__ = ["__weakref__", "_closer"]
Guido van Rossum93adc5d2007-07-17 20:41:19 +0000142 if not _can_dup_socket:
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000143 __slots__.append("_base")
144
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000145 def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None):
146 if fileno is None:
147 _socket.socket.__init__(self, family, type, proto)
148 else:
149 _socket.socket.__init__(self, family, type, proto, fileno)
150 # Defer creating a SocketCloser until makefile() is actually called.
151 self._closer = None
152
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000153 def __repr__(self):
154 """Wrap __repr__() to reveal the real class name."""
155 s = _socket.socket.__repr__(self)
156 if s.startswith("<socket object"):
157 s = "<%s.%s%s" % (self.__class__.__module__,
158 self.__class__.__name__,
159 s[7:])
160 return s
161
162 def accept(self):
163 """Wrap accept() to give the connection the right type."""
164 conn, addr = _socket.socket.accept(self)
165 fd = conn.fileno()
166 nfd = fd
Guido van Rossum93adc5d2007-07-17 20:41:19 +0000167 if _can_dup_socket:
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000168 nfd = os.dup(fd)
169 wrapper = socket(self.family, self.type, self.proto, fileno=nfd)
170 if fd == nfd:
171 wrapper._base = conn # Keep the base alive
172 else:
173 conn.close()
174 return wrapper, addr
175
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000176 def makefile(self, mode="r", buffering=None, *,
177 encoding=None, newline=None):
178 """Return an I/O stream connected to the socket.
179
180 The arguments are as for io.open() after the filename,
181 except the only mode characters supported are 'r', 'w' and 'b'.
182 The semantics are similar too. (XXX refactor to share code?)
183 """
184 for c in mode:
185 if c not in {"r", "w", "b"}:
186 raise ValueError("invalid mode %r (only r, w, b allowed)")
187 writing = "w" in mode
188 reading = "r" in mode or not writing
189 assert reading or writing
190 binary = "b" in mode
191 rawmode = ""
192 if reading:
193 rawmode += "r"
194 if writing:
195 rawmode += "w"
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000196 if self._closer is None:
197 self._closer = SocketCloser(self)
198 raw = SocketIO(self, rawmode, self._closer)
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000199 if buffering is None:
200 buffering = -1
201 if buffering < 0:
202 buffering = io.DEFAULT_BUFFER_SIZE
203 if buffering == 0:
204 if not binary:
205 raise ValueError("unbuffered streams must be binary")
206 raw.name = self.fileno()
207 raw.mode = mode
208 return raw
209 if reading and writing:
210 buffer = io.BufferedRWPair(raw, raw, buffering)
211 elif reading:
212 buffer = io.BufferedReader(raw, buffering)
213 else:
214 assert writing
215 buffer = io.BufferedWriter(raw, buffering)
216 if binary:
217 buffer.name = self.fileno()
218 buffer.mode = mode
219 return buffer
220 text = io.TextIOWrapper(buffer, encoding, newline)
221 text.name = self.fileno()
Guido van Rossum93adc5d2007-07-17 20:41:19 +0000222 text.mode = mode
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000223 return text
224
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000225 def close(self):
226 if self._closer is None:
227 self._real_close()
228 else:
229 self._closer.socket_close()
230
231 # _real_close calls close on the _socket.socket base class.
232
233 if not _can_dup_socket:
234 def _real_close(self):
235 _socket.socket.close(self)
236 base = getattr(self, "_base", None)
237 if base is not None:
238 self._base = None
239 base.close()
240 else:
241 def _real_close(self):
242 _socket.socket.close(self)
243
244
245class SocketIO(io.RawIOBase):
246
247 """Raw I/O implementation for stream sockets.
248
249 This class supports the makefile() method on sockets. It provides
250 the raw I/O interface on top of a socket object.
251 """
252
253 # XXX More docs
254
255 def __init__(self, sock, mode, closer):
256 assert mode in ("r", "w", "rw")
257 io.RawIOBase.__init__(self)
258 self._sock = sock
259 self._mode = mode
260 self._closer = closer
261 closer.makefile_open()
262
263 def readinto(self, b):
264 return self._sock.recv_into(b)
265
266 def write(self, b):
267 return self._sock.send(b)
268
269 def readable(self):
270 return "r" in self._mode
271
272 def writable(self):
273 return "w" in self._mode
274
275 def fileno(self):
276 return self._sock.fileno()
277
278 def close(self):
279 if self.closed:
280 return
281 self._closer.makefile_close()
282 io.RawIOBase.close(self)
283
Fred Drakea6070f02000-08-16 14:14:32 +0000284
285def getfqdn(name=''):
286 """Get fully qualified domain name from name.
287
288 An empty argument is interpreted as meaning the local host.
289
290 First the hostname returned by gethostbyaddr() is checked, then
291 possibly existing aliases. In case no FQDN is available, hostname
Brett Cannon01668a12005-03-11 00:04:17 +0000292 from gethostname() is returned.
Fred Drakea6070f02000-08-16 14:14:32 +0000293 """
294 name = name.strip()
Peter Schneider-Kamp2d2785a2000-08-16 20:30:21 +0000295 if not name or name == '0.0.0.0':
Fred Drakea6070f02000-08-16 14:14:32 +0000296 name = gethostname()
297 try:
298 hostname, aliases, ipaddrs = gethostbyaddr(name)
299 except error:
300 pass
301 else:
302 aliases.insert(0, hostname)
303 for name in aliases:
304 if '.' in name:
305 break
306 else:
307 name = hostname
308 return name
309
310
Guido van Rossumd8faa362007-04-27 19:54:29 +0000311def create_connection(address, timeout=None):
312 """Connect to address (host, port) with an optional timeout.
313
314 Provides access to socketobject timeout for higher-level
315 protocols. Passing a timeout will set the timeout on the
316 socket instance (if not present, or passed as None, the
317 default global timeout setting will be used).
318 """
319
320 msg = "getaddrinfo returns an empty list"
321 host, port = address
322 for res in getaddrinfo(host, port, 0, SOCK_STREAM):
323 af, socktype, proto, canonname, sa = res
324 sock = None
325 try:
326 sock = socket(af, socktype, proto)
327 if timeout is not None:
328 sock.settimeout(timeout)
329 sock.connect(sa)
330 return sock
331
332 except error as err:
333 msg = err
334 if sock is not None:
335 sock.close()
336
337 raise error(msg)