Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 1 | # Wrapper module for _socket, providing some additional facilities |
| 2 | # implemented in Python. |
| 3 | |
| 4 | """\ |
| 5 | This module provides socket operations and some related functions. |
| 6 | On Unix, it supports IP (Internet Protocol) and Unix domain sockets. |
Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 7 | On other systems, it only supports IP. Functions specific for a |
Martin v. Löwis | af484d5 | 2000-09-30 11:34:30 +0000 | [diff] [blame] | 8 | socket are available as methods of the socket object. |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 9 | |
| 10 | Functions: |
| 11 | |
| 12 | socket() -- create a new socket object |
Dave Cole | 331708b | 2004-08-09 04:51:41 +0000 | [diff] [blame] | 13 | socketpair() -- create a pair of new socket objects [*] |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 14 | fromfd() -- create a socket object from an open file descriptor [*] |
| 15 | gethostname() -- return the current hostname |
| 16 | gethostbyname() -- map a hostname to its IP number |
| 17 | gethostbyaddr() -- map an IP number or hostname to DNS info |
| 18 | getservbyname() -- map a service name and a protocol name to a port number |
| 19 | getprotobyname() -- mape a protocol name (e.g. 'tcp') to a number |
| 20 | ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order |
| 21 | htons(), htonl() -- convert 16, 32 bit int from host to network byte order |
| 22 | inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format |
| 23 | inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89) |
| 24 | ssl() -- secure socket layer support (only available if configured) |
Guido van Rossum | 9d0c8ce | 2002-07-18 17:08:35 +0000 | [diff] [blame] | 25 | socket.getdefaulttimeout() -- get the default timeout value |
| 26 | socket.setdefaulttimeout() -- set the default timeout value |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 27 | create_connection() -- connects to an address, with an optional timeout |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 28 | |
| 29 | [*] not available on all platforms! |
| 30 | |
| 31 | Special objects: |
| 32 | |
| 33 | SocketType -- type object for socket objects |
| 34 | error -- exception raised for I/O errors |
Guido van Rossum | 47dfa4a | 2003-04-25 05:48:32 +0000 | [diff] [blame] | 35 | has_ipv6 -- boolean value indicating if IPv6 is supported |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 36 | |
| 37 | Integer constants: |
| 38 | |
| 39 | AF_INET, AF_UNIX -- socket domains (first argument to socket() call) |
| 40 | SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument) |
| 41 | |
| 42 | Many other constants may be defined; these may be used in calls to |
| 43 | the setsockopt() and getsockopt() methods. |
| 44 | """ |
| 45 | |
Tim Peters | 18e6778 | 2002-02-17 04:25:24 +0000 | [diff] [blame] | 46 | import _socket |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 47 | from _socket import * |
Tim Peters | 18e6778 | 2002-02-17 04:25:24 +0000 | [diff] [blame] | 48 | |
Guido van Rossum | c18993f | 2002-08-08 15:16:20 +0000 | [diff] [blame] | 49 | _have_ssl = False |
Marc-André Lemburg | a5d2b4c | 2002-02-16 18:23:30 +0000 | [diff] [blame] | 50 | try: |
Guido van Rossum | de7cade | 2002-08-08 15:25:28 +0000 | [diff] [blame] | 51 | import _ssl |
Marc-André Lemburg | a5d2b4c | 2002-02-16 18:23:30 +0000 | [diff] [blame] | 52 | from _ssl import * |
Guido van Rossum | c18993f | 2002-08-08 15:16:20 +0000 | [diff] [blame] | 53 | _have_ssl = True |
Marc-André Lemburg | a5d2b4c | 2002-02-16 18:23:30 +0000 | [diff] [blame] | 54 | except ImportError: |
Guido van Rossum | c18993f | 2002-08-08 15:16:20 +0000 | [diff] [blame] | 55 | pass |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 56 | |
Guido van Rossum | 7d0a826 | 2007-05-21 23:13:11 +0000 | [diff] [blame] | 57 | import os, sys, io |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 58 | |
Fred Drake | 70d566b | 2003-04-29 19:50:25 +0000 | [diff] [blame] | 59 | try: |
| 60 | from errno import EBADF |
| 61 | except ImportError: |
| 62 | EBADF = 9 |
| 63 | |
Skip Montanaro | 0de6580 | 2001-02-15 22:15:14 +0000 | [diff] [blame] | 64 | __all__ = ["getfqdn"] |
Skip Montanaro | 0de6580 | 2001-02-15 22:15:14 +0000 | [diff] [blame] | 65 | __all__.extend(os._get_exports_list(_socket)) |
Guido van Rossum | de7cade | 2002-08-08 15:25:28 +0000 | [diff] [blame] | 66 | if _have_ssl: |
| 67 | __all__.extend(os._get_exports_list(_ssl)) |
Skip Montanaro | 0de6580 | 2001-02-15 22:15:14 +0000 | [diff] [blame] | 68 | |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 69 | # WSA error codes |
| 70 | if 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 Montanaro | 64de1a4 | 2001-03-18 19:53:21 +0000 | [diff] [blame] | 87 | __all__.append("errorTab") |
Guido van Rossum | de7cade | 2002-08-08 15:25:28 +0000 | [diff] [blame] | 88 | |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 89 | |
Guido van Rossum | 93adc5d | 2007-07-17 20:41:19 +0000 | [diff] [blame] | 90 | # True if os.dup() can duplicate socket descriptors. |
| 91 | # (On Windows at least, os.dup only works on files) |
Jeremy Hylton | 5accbdb | 2007-08-03 20:40:09 +0000 | [diff] [blame] | 92 | _can_dup_socket = hasattr(_socket.socket, "dup") |
Guido van Rossum | 93adc5d | 2007-07-17 20:41:19 +0000 | [diff] [blame] | 93 | |
| 94 | if _can_dup_socket: |
Guido van Rossum | 7d0a826 | 2007-05-21 23:13:11 +0000 | [diff] [blame] | 95 | 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 Hylton | 5accbdb | 2007-08-03 20:40:09 +0000 | [diff] [blame] | 99 | class 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 Rossum | 7d0a826 | 2007-05-21 23:13:11 +0000 | [diff] [blame] | 136 | |
| 137 | class socket(_socket.socket): |
| 138 | |
| 139 | """A subclass of _socket.socket adding the makefile() method.""" |
| 140 | |
Jeremy Hylton | 5accbdb | 2007-08-03 20:40:09 +0000 | [diff] [blame] | 141 | __slots__ = ["__weakref__", "_closer"] |
Guido van Rossum | 93adc5d | 2007-07-17 20:41:19 +0000 | [diff] [blame] | 142 | if not _can_dup_socket: |
Guido van Rossum | 7d0a826 | 2007-05-21 23:13:11 +0000 | [diff] [blame] | 143 | __slots__.append("_base") |
| 144 | |
Jeremy Hylton | 5accbdb | 2007-08-03 20:40:09 +0000 | [diff] [blame] | 145 | 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 Rossum | 7d0a826 | 2007-05-21 23:13:11 +0000 | [diff] [blame] | 153 | 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 Rossum | 93adc5d | 2007-07-17 20:41:19 +0000 | [diff] [blame] | 167 | if _can_dup_socket: |
Guido van Rossum | 7d0a826 | 2007-05-21 23:13:11 +0000 | [diff] [blame] | 168 | 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 Rossum | 7d0a826 | 2007-05-21 23:13:11 +0000 | [diff] [blame] | 176 | 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 Hylton | 5accbdb | 2007-08-03 20:40:09 +0000 | [diff] [blame] | 196 | if self._closer is None: |
| 197 | self._closer = SocketCloser(self) |
| 198 | raw = SocketIO(self, rawmode, self._closer) |
Guido van Rossum | 7d0a826 | 2007-05-21 23:13:11 +0000 | [diff] [blame] | 199 | 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 Rossum | 93adc5d | 2007-07-17 20:41:19 +0000 | [diff] [blame] | 222 | text.mode = mode |
Guido van Rossum | 7d0a826 | 2007-05-21 23:13:11 +0000 | [diff] [blame] | 223 | return text |
| 224 | |
Jeremy Hylton | 5accbdb | 2007-08-03 20:40:09 +0000 | [diff] [blame] | 225 | 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 | |
| 245 | class 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 Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 284 | |
| 285 | def 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 Cannon | 01668a1 | 2005-03-11 00:04:17 +0000 | [diff] [blame] | 292 | from gethostname() is returned. |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 293 | """ |
| 294 | name = name.strip() |
Peter Schneider-Kamp | 2d2785a | 2000-08-16 20:30:21 +0000 | [diff] [blame] | 295 | if not name or name == '0.0.0.0': |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 296 | 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 Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 311 | def 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) |