OLD | NEW |
(Empty) | |
| 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. |
| 7 On other systems, it only supports IP. Functions specific for a |
| 8 socket are available as methods of the socket object. |
| 9 |
| 10 Functions: |
| 11 |
| 12 socket() -- create a new socket object |
| 13 socketpair() -- create a pair of new socket objects [*] |
| 14 fromfd() -- create a socket object from an open file descriptor [*] |
| 15 fromshare() -- create a socket object from data received from socket.share() [*] |
| 16 gethostname() -- return the current hostname |
| 17 gethostbyname() -- map a hostname to its IP number |
| 18 gethostbyaddr() -- map an IP number or hostname to DNS info |
| 19 getservbyname() -- map a service name and a protocol name to a port number |
| 20 getprotobyname() -- map a protocol name (e.g. 'tcp') to a number |
| 21 ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order |
| 22 htons(), htonl() -- convert 16, 32 bit int from host to network byte order |
| 23 inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format |
| 24 inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89) |
| 25 socket.getdefaulttimeout() -- get the default timeout value |
| 26 socket.setdefaulttimeout() -- set the default timeout value |
| 27 create_connection() -- connects to an address, with an optional timeout and |
| 28 optional source address. |
| 29 |
| 30 [*] not available on all platforms! |
| 31 |
| 32 Special objects: |
| 33 |
| 34 SocketType -- type object for socket objects |
| 35 error -- exception raised for I/O errors |
| 36 has_ipv6 -- boolean value indicating if IPv6 is supported |
| 37 |
| 38 Integer constants: |
| 39 |
| 40 AF_INET, AF_UNIX -- socket domains (first argument to socket() call) |
| 41 SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument) |
| 42 |
| 43 Many other constants may be defined; these may be used in calls to |
| 44 the setsockopt() and getsockopt() methods. |
| 45 """ |
| 46 |
| 47 from __future__ import unicode_literals |
| 48 from __future__ import print_function |
| 49 from __future__ import division |
| 50 from __future__ import absolute_import |
| 51 from future.builtins import super |
| 52 |
| 53 import _socket |
| 54 from _socket import * |
| 55 |
| 56 import os, sys, io |
| 57 |
| 58 try: |
| 59 import errno |
| 60 except ImportError: |
| 61 errno = None |
| 62 EBADF = getattr(errno, 'EBADF', 9) |
| 63 EAGAIN = getattr(errno, 'EAGAIN', 11) |
| 64 EWOULDBLOCK = getattr(errno, 'EWOULDBLOCK', 11) |
| 65 |
| 66 __all__ = ["getfqdn", "create_connection"] |
| 67 __all__.extend(os._get_exports_list(_socket)) |
| 68 |
| 69 |
| 70 _realsocket = socket |
| 71 |
| 72 # WSA error codes |
| 73 if sys.platform.lower().startswith("win"): |
| 74 errorTab = {} |
| 75 errorTab[10004] = "The operation was interrupted." |
| 76 errorTab[10009] = "A bad file handle was passed." |
| 77 errorTab[10013] = "Permission denied." |
| 78 errorTab[10014] = "A fault occurred on the network??" # WSAEFAULT |
| 79 errorTab[10022] = "An invalid operation was attempted." |
| 80 errorTab[10035] = "The socket operation would block" |
| 81 errorTab[10036] = "A blocking operation is already in progress." |
| 82 errorTab[10048] = "The network address is in use." |
| 83 errorTab[10054] = "The connection has been reset." |
| 84 errorTab[10058] = "The network has been shut down." |
| 85 errorTab[10060] = "The operation timed out." |
| 86 errorTab[10061] = "Connection refused." |
| 87 errorTab[10063] = "The name is too long." |
| 88 errorTab[10064] = "The host is down." |
| 89 errorTab[10065] = "The host is unreachable." |
| 90 __all__.append("errorTab") |
| 91 |
| 92 |
| 93 class socket(_socket.socket): |
| 94 |
| 95 """A subclass of _socket.socket adding the makefile() method.""" |
| 96 |
| 97 __slots__ = ["__weakref__", "_io_refs", "_closed"] |
| 98 |
| 99 def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None): |
| 100 if fileno is None: |
| 101 _socket.socket.__init__(self, family, type, proto) |
| 102 else: |
| 103 _socket.socket.__init__(self, family, type, proto, fileno) |
| 104 self._io_refs = 0 |
| 105 self._closed = False |
| 106 |
| 107 def __enter__(self): |
| 108 return self |
| 109 |
| 110 def __exit__(self, *args): |
| 111 if not self._closed: |
| 112 self.close() |
| 113 |
| 114 def __repr__(self): |
| 115 """Wrap __repr__() to reveal the real class name.""" |
| 116 s = _socket.socket.__repr__(self) |
| 117 if s.startswith("<socket object"): |
| 118 s = "<%s.%s%s%s" % (self.__class__.__module__, |
| 119 self.__class__.__name__, |
| 120 getattr(self, '_closed', False) and " [closed] "
or "", |
| 121 s[7:]) |
| 122 return s |
| 123 |
| 124 def __getstate__(self): |
| 125 raise TypeError("Cannot serialize socket object") |
| 126 |
| 127 def dup(self): |
| 128 """dup() -> socket object |
| 129 |
| 130 Return a new socket object connected to the same system resource. |
| 131 """ |
| 132 fd = dup(self.fileno()) |
| 133 sock = self.__class__(self.family, self.type, self.proto, fileno=fd) |
| 134 sock.settimeout(self.gettimeout()) |
| 135 return sock |
| 136 |
| 137 def accept(self): |
| 138 """accept() -> (socket object, address info) |
| 139 |
| 140 Wait for an incoming connection. Return a new socket |
| 141 representing the connection, and the address of the client. |
| 142 For IP sockets, the address info is a pair (hostaddr, port). |
| 143 """ |
| 144 fd, addr = self._accept() |
| 145 sock = socket(self.family, self.type, self.proto, fileno=fd) |
| 146 # Issue #7995: if no default timeout is set and the listening |
| 147 # socket had a (non-zero) timeout, force the new socket in blocking |
| 148 # mode to override platform-specific socket flags inheritance. |
| 149 if getdefaulttimeout() is None and self.gettimeout(): |
| 150 sock.setblocking(True) |
| 151 return sock, addr |
| 152 |
| 153 def makefile(self, mode="r", buffering=None, **_3to2kwargs): |
| 154 """makefile(...) -> an I/O stream connected to the socket |
| 155 |
| 156 The arguments are as for io.open() after the filename, |
| 157 except the only mode characters supported are 'r', 'w' and 'b'. |
| 158 The semantics are similar too. (XXX refactor to share code?) |
| 159 """ |
| 160 if 'newline' in _3to2kwargs: newline = _3to2kwargs['newline']; del _3to2
kwargs['newline'] |
| 161 else: newline = None |
| 162 if 'errors' in _3to2kwargs: errors = _3to2kwargs['errors']; del _3to2kwa
rgs['errors'] |
| 163 else: errors = None |
| 164 if 'encoding' in _3to2kwargs: encoding = _3to2kwargs['encoding']; del _3
to2kwargs['encoding'] |
| 165 else: encoding = None |
| 166 for c in mode: |
| 167 if c not in ("r", "w", "b"): |
| 168 raise ValueError("invalid mode %r (only r, w, b allowed)") |
| 169 writing = "w" in mode |
| 170 reading = "r" in mode or not writing |
| 171 assert reading or writing |
| 172 binary = "b" in mode |
| 173 rawmode = "" |
| 174 if reading: |
| 175 rawmode += "r" |
| 176 if writing: |
| 177 rawmode += "w" |
| 178 raw = SocketIO(self, rawmode) |
| 179 self._io_refs += 1 |
| 180 if buffering is None: |
| 181 buffering = -1 |
| 182 if buffering < 0: |
| 183 buffering = io.DEFAULT_BUFFER_SIZE |
| 184 if buffering == 0: |
| 185 if not binary: |
| 186 raise ValueError("unbuffered streams must be binary") |
| 187 return raw |
| 188 if reading and writing: |
| 189 buffer = io.BufferedRWPair(raw, raw, buffering) |
| 190 elif reading: |
| 191 buffer = io.BufferedReader(raw, buffering) |
| 192 else: |
| 193 assert writing |
| 194 buffer = io.BufferedWriter(raw, buffering) |
| 195 if binary: |
| 196 return buffer |
| 197 text = io.TextIOWrapper(buffer, encoding, errors, newline) |
| 198 text.mode = mode |
| 199 return text |
| 200 |
| 201 def _decref_socketios(self): |
| 202 if self._io_refs > 0: |
| 203 self._io_refs -= 1 |
| 204 if self._closed: |
| 205 self.close() |
| 206 |
| 207 def _real_close(self, _ss=_socket.socket): |
| 208 # This function should not reference any globals. See issue #808164. |
| 209 _ss.close(self) |
| 210 |
| 211 def close(self): |
| 212 # This function should not reference any globals. See issue #808164. |
| 213 self._closed = True |
| 214 if self._io_refs <= 0: |
| 215 self._real_close() |
| 216 |
| 217 def detach(self): |
| 218 """detach() -> file descriptor |
| 219 |
| 220 Close the socket object without closing the underlying file descriptor. |
| 221 The object cannot be used after this call, but the file descriptor |
| 222 can be reused for other purposes. The file descriptor is returned. |
| 223 """ |
| 224 self._closed = True |
| 225 return super().detach() |
| 226 |
| 227 def fromfd(fd, family, type, proto=0): |
| 228 """ fromfd(fd, family, type[, proto]) -> socket object |
| 229 |
| 230 Create a socket object from a duplicate of the given file |
| 231 descriptor. The remaining arguments are the same as for socket(). |
| 232 """ |
| 233 nfd = dup(fd) |
| 234 return socket(family, type, proto, nfd) |
| 235 |
| 236 if hasattr(_socket.socket, "share"): |
| 237 def fromshare(info): |
| 238 """ fromshare(info) -> socket object |
| 239 |
| 240 Create a socket object from a the bytes object returned by |
| 241 socket.share(pid). |
| 242 """ |
| 243 return socket(0, 0, 0, info) |
| 244 |
| 245 if hasattr(_socket, "socketpair"): |
| 246 |
| 247 def socketpair(family=None, type=SOCK_STREAM, proto=0): |
| 248 """socketpair([family[, type[, proto]]]) -> (socket object, socket objec
t) |
| 249 |
| 250 Create a pair of socket objects from the sockets returned by the platfor
m |
| 251 socketpair() function. |
| 252 The arguments are the same as for socket() except the default family is |
| 253 AF_UNIX if defined on the platform; otherwise, the default is AF_INET. |
| 254 """ |
| 255 if family is None: |
| 256 try: |
| 257 family = AF_UNIX |
| 258 except NameError: |
| 259 family = AF_INET |
| 260 a, b = _socket.socketpair(family, type, proto) |
| 261 a = socket(family, type, proto, a.detach()) |
| 262 b = socket(family, type, proto, b.detach()) |
| 263 return a, b |
| 264 |
| 265 |
| 266 _blocking_errnos = set([EAGAIN, EWOULDBLOCK]) |
| 267 |
| 268 class 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 # One might wonder why not let FileIO do the job instead. There are two |
| 277 # main reasons why FileIO is not adapted: |
| 278 # - it wouldn't work under Windows (where you can't used read() and |
| 279 # write() on a socket handle) |
| 280 # - it wouldn't work with socket timeouts (FileIO would ignore the |
| 281 # timeout and consider the socket non-blocking) |
| 282 |
| 283 # XXX More docs |
| 284 |
| 285 def __init__(self, sock, mode): |
| 286 if mode not in ("r", "w", "rw", "rb", "wb", "rwb"): |
| 287 raise ValueError("invalid mode: %r" % mode) |
| 288 io.RawIOBase.__init__(self) |
| 289 self._sock = sock |
| 290 if "b" not in mode: |
| 291 mode += "b" |
| 292 self._mode = mode |
| 293 self._reading = "r" in mode |
| 294 self._writing = "w" in mode |
| 295 self._timeout_occurred = False |
| 296 |
| 297 def readinto(self, b): |
| 298 """Read up to len(b) bytes into the writable buffer *b* and return |
| 299 the number of bytes read. If the socket is non-blocking and no bytes |
| 300 are available, None is returned. |
| 301 |
| 302 If *b* is non-empty, a 0 return value indicates that the connection |
| 303 was shutdown at the other end. |
| 304 """ |
| 305 self._checkClosed() |
| 306 self._checkReadable() |
| 307 if self._timeout_occurred: |
| 308 raise IOError("cannot read from timed out object") |
| 309 while True: |
| 310 try: |
| 311 return self._sock.recv_into(b) |
| 312 except timeout: |
| 313 self._timeout_occurred = True |
| 314 raise |
| 315 # except InterruptedError: |
| 316 # continue |
| 317 except error as e: |
| 318 if e.args[0] in _blocking_errnos: |
| 319 return None |
| 320 raise |
| 321 |
| 322 def write(self, b): |
| 323 """Write the given bytes or bytearray object *b* to the socket |
| 324 and return the number of bytes written. This can be less than |
| 325 len(b) if not all data could be written. If the socket is |
| 326 non-blocking and no bytes could be written None is returned. |
| 327 """ |
| 328 self._checkClosed() |
| 329 self._checkWritable() |
| 330 try: |
| 331 return self._sock.send(b) |
| 332 except error as e: |
| 333 # XXX what about EINTR? |
| 334 if e.args[0] in _blocking_errnos: |
| 335 return None |
| 336 raise |
| 337 |
| 338 def readable(self): |
| 339 """True if the SocketIO is open for reading. |
| 340 """ |
| 341 if self.closed: |
| 342 raise ValueError("I/O operation on closed socket.") |
| 343 return self._reading |
| 344 |
| 345 def writable(self): |
| 346 """True if the SocketIO is open for writing. |
| 347 """ |
| 348 if self.closed: |
| 349 raise ValueError("I/O operation on closed socket.") |
| 350 return self._writing |
| 351 |
| 352 def seekable(self): |
| 353 """True if the SocketIO is open for seeking. |
| 354 """ |
| 355 if self.closed: |
| 356 raise ValueError("I/O operation on closed socket.") |
| 357 return super().seekable() |
| 358 |
| 359 def fileno(self): |
| 360 """Return the file descriptor of the underlying socket. |
| 361 """ |
| 362 self._checkClosed() |
| 363 return self._sock.fileno() |
| 364 |
| 365 @property |
| 366 def name(self): |
| 367 if not self.closed: |
| 368 return self.fileno() |
| 369 else: |
| 370 return -1 |
| 371 |
| 372 @property |
| 373 def mode(self): |
| 374 return self._mode |
| 375 |
| 376 def close(self): |
| 377 """Close the SocketIO object. This doesn't close the underlying |
| 378 socket, except if all references to it have disappeared. |
| 379 """ |
| 380 if self.closed: |
| 381 return |
| 382 io.RawIOBase.close(self) |
| 383 self._sock._decref_socketios() |
| 384 self._sock = None |
| 385 |
| 386 |
| 387 def getfqdn(name=''): |
| 388 """Get fully qualified domain name from name. |
| 389 |
| 390 An empty argument is interpreted as meaning the local host. |
| 391 |
| 392 First the hostname returned by gethostbyaddr() is checked, then |
| 393 possibly existing aliases. In case no FQDN is available, hostname |
| 394 from gethostname() is returned. |
| 395 """ |
| 396 name = name.strip() |
| 397 if not name or name == '0.0.0.0': |
| 398 name = gethostname() |
| 399 try: |
| 400 hostname, aliases, ipaddrs = gethostbyaddr(name) |
| 401 except error: |
| 402 pass |
| 403 else: |
| 404 aliases.insert(0, hostname) |
| 405 for name in aliases: |
| 406 if '.' in name: |
| 407 break |
| 408 else: |
| 409 name = hostname |
| 410 return name |
| 411 |
| 412 |
| 413 # Re-use the same sentinel as in the Python stdlib socket module: |
| 414 from socket import _GLOBAL_DEFAULT_TIMEOUT |
| 415 # Was: _GLOBAL_DEFAULT_TIMEOUT = object() |
| 416 |
| 417 |
| 418 def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, |
| 419 source_address=None): |
| 420 """Connect to *address* and return the socket object. |
| 421 |
| 422 Convenience function. Connect to *address* (a 2-tuple ``(host, |
| 423 port)``) and return the socket object. Passing the optional |
| 424 *timeout* parameter will set the timeout on the socket instance |
| 425 before attempting to connect. If no *timeout* is supplied, the |
| 426 global default timeout setting returned by :func:`getdefaulttimeout` |
| 427 is used. If *source_address* is set it must be a tuple of (host, port) |
| 428 for the socket to bind as a source address before making the connection. |
| 429 An host of '' or port 0 tells the OS to use the default. |
| 430 """ |
| 431 |
| 432 host, port = address |
| 433 err = None |
| 434 for res in getaddrinfo(host, port, 0, SOCK_STREAM): |
| 435 af, socktype, proto, canonname, sa = res |
| 436 sock = None |
| 437 try: |
| 438 sock = socket(af, socktype, proto) |
| 439 if timeout is not _GLOBAL_DEFAULT_TIMEOUT: |
| 440 sock.settimeout(timeout) |
| 441 if source_address: |
| 442 sock.bind(source_address) |
| 443 sock.connect(sa) |
| 444 return sock |
| 445 |
| 446 except error as _: |
| 447 err = _ |
| 448 if sock is not None: |
| 449 sock.close() |
| 450 |
| 451 if err is not None: |
| 452 raise err |
| 453 else: |
| 454 raise error("getaddrinfo returns an empty list") |
OLD | NEW |