response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Look up a user in the /etc/shadow database using the spwd module. If it is not available, return L{None}. @param username: the username of the user to return the shadow database information for. @type username: L{str} @returns: A L{spwd.struct_spwd}, where field 1 may contain a crypted password, or L{None} when the L{spwd} database is unavailable. @raises KeyError: when no such user exists
def _shadowGetByName(username: str) -> Optional[CryptedPasswordRecord]: """ Look up a user in the /etc/shadow database using the spwd module. If it is not available, return L{None}. @param username: the username of the user to return the shadow database information for. @type username: L{str} @returns: A L{spwd.struct_spwd}, where field 1 may contain a crypted password, or L{None} when the L{spwd} database is unavailable. @raises KeyError: when no such user exists """ if spwd is not None: f = spwd.getspnam else: return None return cast(CryptedPasswordRecord, runAsEffectiveUser(0, 0, f, username))
Reads keys from an authorized keys file. Any non-comment line that cannot be parsed as a key will be ignored, although that particular line will be logged. @param fileobj: something from which to read lines which can be parsed as keys @param parseKey: a callable that takes bytes and returns a L{twisted.conch.ssh.keys.Key}, mainly to be used for testing. The default is L{twisted.conch.ssh.keys.Key.fromString}. @return: an iterable of L{twisted.conch.ssh.keys.Key} @since: 15.0
def readAuthorizedKeyFile( fileobj: IO[bytes], parseKey: Callable[[bytes], keys.Key] = keys.Key.fromString ) -> Iterator[keys.Key]: """ Reads keys from an authorized keys file. Any non-comment line that cannot be parsed as a key will be ignored, although that particular line will be logged. @param fileobj: something from which to read lines which can be parsed as keys @param parseKey: a callable that takes bytes and returns a L{twisted.conch.ssh.keys.Key}, mainly to be used for testing. The default is L{twisted.conch.ssh.keys.Key.fromString}. @return: an iterable of L{twisted.conch.ssh.keys.Key} @since: 15.0 """ for line in fileobj: line = line.strip() if line and not line.startswith(b"#"): # for comments try: yield parseKey(line) except keys.BadKeyError as e: _log.error( "Unable to parse line {line!r} as a key: {error!s}", line=line, error=e, )
Helper function that turns an iterable of filepaths into a generator of keys. If any file cannot be read, a message is logged but it is otherwise ignored. @param filepaths: iterable of L{twisted.python.filepath.FilePath}. @type filepaths: iterable @param parseKey: a callable that takes a string and returns a L{twisted.conch.ssh.keys.Key} @type parseKey: L{callable} @return: generator of L{twisted.conch.ssh.keys.Key} @since: 15.0
def _keysFromFilepaths( filepaths: Iterable[FilePath[Any]], parseKey: Callable[[bytes], keys.Key] ) -> Iterable[keys.Key]: """ Helper function that turns an iterable of filepaths into a generator of keys. If any file cannot be read, a message is logged but it is otherwise ignored. @param filepaths: iterable of L{twisted.python.filepath.FilePath}. @type filepaths: iterable @param parseKey: a callable that takes a string and returns a L{twisted.conch.ssh.keys.Key} @type parseKey: L{callable} @return: generator of L{twisted.conch.ssh.keys.Key} @since: 15.0 """ for fp in filepaths: if fp.exists(): try: with fp.open() as f: yield from readAuthorizedKeyFile(f, parseKey) except OSError as e: _log.error("Unable to read {path!r}: {error!s}", path=fp.path, error=e)
Build an 'ls' line for a file ('file' in its generic sense, it can be of any type).
def lsLine(name, s): """ Build an 'ls' line for a file ('file' in its generic sense, it can be of any type). """ mode = s.st_mode perms = array.array("B", b"-" * 10) ft = stat.S_IFMT(mode) if stat.S_ISDIR(ft): perms[0] = ord("d") elif stat.S_ISCHR(ft): perms[0] = ord("c") elif stat.S_ISBLK(ft): perms[0] = ord("b") elif stat.S_ISREG(ft): perms[0] = ord("-") elif stat.S_ISFIFO(ft): perms[0] = ord("f") elif stat.S_ISLNK(ft): perms[0] = ord("l") elif stat.S_ISSOCK(ft): perms[0] = ord("s") else: perms[0] = ord("!") # User if mode & stat.S_IRUSR: perms[1] = ord("r") if mode & stat.S_IWUSR: perms[2] = ord("w") if mode & stat.S_IXUSR: perms[3] = ord("x") # Group if mode & stat.S_IRGRP: perms[4] = ord("r") if mode & stat.S_IWGRP: perms[5] = ord("w") if mode & stat.S_IXGRP: perms[6] = ord("x") # Other if mode & stat.S_IROTH: perms[7] = ord("r") if mode & stat.S_IWOTH: perms[8] = ord("w") if mode & stat.S_IXOTH: perms[9] = ord("x") # Suid/sgid if mode & stat.S_ISUID: if perms[3] == ord("x"): perms[3] = ord("s") else: perms[3] = ord("S") if mode & stat.S_ISGID: if perms[6] == ord("x"): perms[6] = ord("s") else: perms[6] = ord("S") if isinstance(name, bytes): name = name.decode("utf-8") lsPerms = perms.tobytes() lsPerms = lsPerms.decode("utf-8") lsresult = [ lsPerms, str(s.st_nlink).rjust(5), " ", str(s.st_uid).ljust(9), str(s.st_gid).ljust(9), str(s.st_size).rjust(8), " ", ] # Need to specify the month manually, as strftime depends on locale ttup = localtime(s.st_mtime) sixmonths = 60 * 60 * 24 * 7 * 26 if s.st_mtime + sixmonths < time(): # Last edited more than 6mo ago strtime = strftime("%%s %d %Y ", ttup) else: strtime = strftime("%%s %d %H:%M ", ttup) lsresult.append(strtime % (_MONTH_NAMES[ttup[1]],)) lsresult.append(name) return "".join(lsresult)
Tokenize and colorize the given Python source. Returns a VT102-format colorized version of the last line of C{source}. @param source: Python source code @type source: L{str} or L{bytes} @return: L{bytes} of colorized source
def lastColorizedLine(source): """ Tokenize and colorize the given Python source. Returns a VT102-format colorized version of the last line of C{source}. @param source: Python source code @type source: L{str} or L{bytes} @return: L{bytes} of colorized source """ if not isinstance(source, bytes): source = source.encode("utf-8") w = VT102Writer() p = TokenPrinter(w.write).printtoken s = BytesIO(source) for token in tokenize.tokenize(s.readline): (tokenType, string, start, end, line) = token p(tokenType, string, start, end, line) return bytes(w)
Create a manhole server service. @type options: L{dict} @param options: A mapping describing the configuration of the desired service. Recognized key/value pairs are:: "telnetPort": strports description of the address on which to listen for telnet connections. If None, no telnet service will be started. "sshPort": strports description of the address on which to listen for ssh connections. If None, no ssh service will be started. "namespace": dictionary containing desired initial locals for manhole connections. If None, an empty dictionary will be used. "passwd": Name of a passwd(5)-format username/password file. "sshKeyDir": The folder that the SSH server key will be kept in. "sshKeyName": The filename of the key. "sshKeySize": The size of the key, in bits. Default is 4096. @rtype: L{twisted.application.service.IService} @return: A manhole service.
def makeService(options): """ Create a manhole server service. @type options: L{dict} @param options: A mapping describing the configuration of the desired service. Recognized key/value pairs are:: "telnetPort": strports description of the address on which to listen for telnet connections. If None, no telnet service will be started. "sshPort": strports description of the address on which to listen for ssh connections. If None, no ssh service will be started. "namespace": dictionary containing desired initial locals for manhole connections. If None, an empty dictionary will be used. "passwd": Name of a passwd(5)-format username/password file. "sshKeyDir": The folder that the SSH server key will be kept in. "sshKeyName": The filename of the key. "sshKeySize": The size of the key, in bits. Default is 4096. @rtype: L{twisted.application.service.IService} @return: A manhole service. """ svc = service.MultiService() namespace = options["namespace"] if namespace is None: namespace = {} checker = checkers.FilePasswordDB(options["passwd"]) if options["telnetPort"]: telnetRealm = _StupidRealm( telnet.TelnetBootstrapProtocol, insults.ServerProtocol, manhole.ColoredManhole, namespace, ) telnetPortal = portal.Portal(telnetRealm, [checker]) telnetFactory = protocol.ServerFactory() telnetFactory.protocol = makeTelnetProtocol(telnetPortal) telnetService = strports.service(options["telnetPort"], telnetFactory) telnetService.setServiceParent(svc) if options["sshPort"]: sshRealm = manhole_ssh.TerminalRealm() sshRealm.chainedProtocolFactory = chainedProtocolFactory(namespace) sshPortal = portal.Portal(sshRealm, [checker]) sshFactory = manhole_ssh.ConchFactory(sshPortal) if options["sshKeyDir"] != "<USER DATA DIR>": keyDir = options["sshKeyDir"] else: from twisted.python._appdirs import getDataDirectory keyDir = getDataDirectory() keyLocation = filepath.FilePath(keyDir).child(options["sshKeyName"]) sshKey = keys._getPersistentRSAKey(keyLocation, int(options["sshKeySize"])) sshFactory.publicKeys[b"ssh-rsa"] = sshKey sshFactory.privateKeys[b"ssh-rsa"] = sshKey sshService = strports.service(options["sshPort"], sshFactory) sshService.setServiceParent(svc) return svc
Construct a service for operating a SSH server. @param config: An L{Options} instance specifying server options, including where server keys are stored and what authentication methods to use. @return: A L{twisted.application.service.IService} provider which contains the requested SSH server.
def makeService(config): """ Construct a service for operating a SSH server. @param config: An L{Options} instance specifying server options, including where server keys are stored and what authentication methods to use. @return: A L{twisted.application.service.IService} provider which contains the requested SSH server. """ t = factory.OpenSSHFactory() r = unix.UnixSSHRealm() t.portal = portal.Portal(r, config.get("credCheckers", [])) t.dataRoot = config["data"] t.moduliRoot = config["moduli"] or config["data"] port = config["port"] if config["interface"]: # Add warning here port += ":interface=" + config["interface"] return strports.service(port, t)
Create a byte sequence of length 1. U{RFC 854<https://tools.ietf.org/html/rfc854>} specifies codes in decimal, but Python can only handle L{bytes} literals in octal or hexadecimal. This helper function bridges that gap. @param i: The value of the only byte in the sequence.
def _chr(i: int) -> bytes: """Create a byte sequence of length 1. U{RFC 854<https://tools.ietf.org/html/rfc854>} specifies codes in decimal, but Python can only handle L{bytes} literals in octal or hexadecimal. This helper function bridges that gap. @param i: The value of the only byte in the sequence. """ return bytes((i,))
Verify a host's key. This function is a gross vestige of some bad factoring in the client internals. The actual implementation, and a better signature of this logic is in L{KnownHostsFile.verifyHostKey}. This function is not deprecated yet because the callers have not yet been rehabilitated, but they should eventually be changed to call that method instead. However, this function does perform two functions not implemented by L{KnownHostsFile.verifyHostKey}. It determines the path to the user's known_hosts file based on the options (which should really be the options object's job), and it provides an opener to L{ConsoleUI} which opens '/dev/tty' so that the user will be prompted on the tty of the process even if the input and output of the process has been redirected. This latter part is, somewhat obviously, not portable, but I don't know of a portable equivalent that could be used. @param host: Due to a bug in L{SSHClientTransport.verifyHostKey}, this is always the dotted-quad IP address of the host being connected to. @type host: L{str} @param transport: the client transport which is attempting to connect to the given host. @type transport: L{SSHClientTransport} @param fingerprint: the fingerprint of the given public key, in xx:xx:xx:... format. This is ignored in favor of getting the fingerprint from the key itself. @type fingerprint: L{str} @param pubKey: The public key of the server being connected to. @type pubKey: L{str} @return: a L{Deferred} which fires with C{1} if the key was successfully verified, or fails if the key could not be successfully verified. Failure types may include L{HostKeyChanged}, L{UserRejectedKey}, L{IOError} or L{KeyboardInterrupt}.
def verifyHostKey(transport, host, pubKey, fingerprint): """ Verify a host's key. This function is a gross vestige of some bad factoring in the client internals. The actual implementation, and a better signature of this logic is in L{KnownHostsFile.verifyHostKey}. This function is not deprecated yet because the callers have not yet been rehabilitated, but they should eventually be changed to call that method instead. However, this function does perform two functions not implemented by L{KnownHostsFile.verifyHostKey}. It determines the path to the user's known_hosts file based on the options (which should really be the options object's job), and it provides an opener to L{ConsoleUI} which opens '/dev/tty' so that the user will be prompted on the tty of the process even if the input and output of the process has been redirected. This latter part is, somewhat obviously, not portable, but I don't know of a portable equivalent that could be used. @param host: Due to a bug in L{SSHClientTransport.verifyHostKey}, this is always the dotted-quad IP address of the host being connected to. @type host: L{str} @param transport: the client transport which is attempting to connect to the given host. @type transport: L{SSHClientTransport} @param fingerprint: the fingerprint of the given public key, in xx:xx:xx:... format. This is ignored in favor of getting the fingerprint from the key itself. @type fingerprint: L{str} @param pubKey: The public key of the server being connected to. @type pubKey: L{str} @return: a L{Deferred} which fires with C{1} if the key was successfully verified, or fails if the key could not be successfully verified. Failure types may include L{HostKeyChanged}, L{UserRejectedKey}, L{IOError} or L{KeyboardInterrupt}. """ actualHost = transport.factory.options["host"] actualKey = keys.Key.fromString(pubKey) kh = KnownHostsFile.fromPath( FilePath( transport.factory.options["known-hosts"] or os.path.expanduser(_KNOWN_HOSTS) ) ) ui = ConsoleUI(lambda: _open("/dev/tty", "r+b", buffering=0)) return kh.verifyHostKey(ui, actualHost, host, actualKey)
Checks to see if host is in the known_hosts file for the user. @return: 0 if it isn't, 1 if it is and is the same, 2 if it's changed. @rtype: L{int}
def isInKnownHosts(host, pubKey, options): """ Checks to see if host is in the known_hosts file for the user. @return: 0 if it isn't, 1 if it is and is the same, 2 if it's changed. @rtype: L{int} """ keyType = common.getNS(pubKey)[0] retVal = 0 if not options["known-hosts"] and not os.path.exists(os.path.expanduser("~/.ssh/")): print("Creating ~/.ssh directory...") os.mkdir(os.path.expanduser("~/.ssh")) kh_file = options["known-hosts"] or _KNOWN_HOSTS try: known_hosts = open(os.path.expanduser(kh_file), "rb") except OSError: return 0 with known_hosts: for line in known_hosts.readlines(): split = line.split() if len(split) < 3: continue hosts, hostKeyType, encodedKey = split[:3] if host not in hosts.split(b","): # incorrect host continue if hostKeyType != keyType: # incorrect type of key continue try: decodedKey = decodebytes(encodedKey) except BaseException: continue if decodedKey == pubKey: return 1 else: retVal = 2 return retVal
Look in known_hosts for a key corresponding to C{host}. This can be used to change the order of supported key types in the KEXINIT packet. @type host: L{str} @param host: the host to check in known_hosts @type options: L{twisted.conch.client.options.ConchOptions} @param options: options passed to client @return: L{list} of L{str} representing key types or L{None}.
def getHostKeyAlgorithms(host, options): """ Look in known_hosts for a key corresponding to C{host}. This can be used to change the order of supported key types in the KEXINIT packet. @type host: L{str} @param host: the host to check in known_hosts @type options: L{twisted.conch.client.options.ConchOptions} @param options: options passed to client @return: L{list} of L{str} representing key types or L{None}. """ knownHosts = KnownHostsFile.fromPath( FilePath(options["known-hosts"] or os.path.expanduser(_KNOWN_HOSTS)) ) keyTypes = [] for entry in knownHosts.iterentries(): if entry.matchesHost(host): if entry.keyType not in keyTypes: keyTypes.append(entry.keyType) return keyTypes or None
Encode a binary string as base64 with no trailing newline. @param s: The string to encode. @type s: L{bytes} @return: The base64-encoded string. @rtype: L{bytes}
def _b64encode(s): """ Encode a binary string as base64 with no trailing newline. @param s: The string to encode. @type s: L{bytes} @return: The base64-encoded string. @rtype: L{bytes} """ return b2a_base64(s).strip()
Extract common elements of base64 keys from an entry in a hosts file. @param string: A known hosts file entry (a single line). @type string: L{bytes} @return: a 4-tuple of hostname data (L{bytes}), ssh key type (L{bytes}), key (L{Key}), and comment (L{bytes} or L{None}). The hostname data is simply the beginning of the line up to the first occurrence of whitespace. @rtype: L{tuple}
def _extractCommon(string): """ Extract common elements of base64 keys from an entry in a hosts file. @param string: A known hosts file entry (a single line). @type string: L{bytes} @return: a 4-tuple of hostname data (L{bytes}), ssh key type (L{bytes}), key (L{Key}), and comment (L{bytes} or L{None}). The hostname data is simply the beginning of the line up to the first occurrence of whitespace. @rtype: L{tuple} """ elements = string.split(None, 2) if len(elements) != 3: raise InvalidEntry() hostnames, keyType, keyAndComment = elements splitkey = keyAndComment.split(None, 1) if len(splitkey) == 2: keyString, comment = splitkey comment = comment.rstrip(b"\n") else: keyString = splitkey[0] comment = None key = Key.fromString(a2b_base64(keyString)) return hostnames, keyType, key, comment
Return the SHA-1 HMAC hash of the given key and string. @param key: The HMAC key. @type key: L{bytes} @param string: The string to be hashed. @type string: L{bytes} @return: The keyed hash value. @rtype: L{bytes}
def _hmacedString(key, string): """ Return the SHA-1 HMAC hash of the given key and string. @param key: The HMAC key. @type key: L{bytes} @param string: The string to be hashed. @type string: L{bytes} @return: The keyed hash value. @rtype: L{bytes} """ hash = hmac.HMAC(key, digestmod=sha1) if isinstance(string, str): string = string.encode("utf-8") hash.update(string) return hash.digest()
Assemble formatted text from structured information. Currently handled formatting includes: bold, blink, reverse, underline and color codes. For example:: from twisted.conch.insults.text import attributes as A assembleFormattedText( A.normal[A.bold['Time: '], A.fg.lightRed['Now!']]) Would produce "Time: " in bold formatting, followed by "Now!" with a foreground color of light red and without any additional formatting. @param formatted: Structured text and attributes. @rtype: L{str} @return: String containing VT102 control sequences that mimic those specified by C{formatted}. @see: L{twisted.conch.insults.text._CharacterAttributes} @since: 13.1
def assembleFormattedText(formatted): """ Assemble formatted text from structured information. Currently handled formatting includes: bold, blink, reverse, underline and color codes. For example:: from twisted.conch.insults.text import attributes as A assembleFormattedText( A.normal[A.bold['Time: '], A.fg.lightRed['Now!']]) Would produce "Time: " in bold formatting, followed by "Now!" with a foreground color of light red and without any additional formatting. @param formatted: Structured text and attributes. @rtype: L{str} @return: String containing VT102 control sequences that mimic those specified by C{formatted}. @see: L{twisted.conch.insults.text._CharacterAttributes} @since: 13.1 """ return _textattributes.flatten(formatted, helper._FormattingState(), "toVT102")
Draw a rectangle @type position: L{tuple} @param position: A tuple of the (top, left) coordinates of the rectangle. @type dimension: L{tuple} @param dimension: A tuple of the (width, height) size of the rectangle.
def rectangle(terminal, position, dimension): """ Draw a rectangle @type position: L{tuple} @param position: A tuple of the (top, left) coordinates of the rectangle. @type dimension: L{tuple} @param dimension: A tuple of the (width, height) size of the rectangle. """ (top, left) = position (width, height) = dimension terminal.selectCharacterSet(insults.CS_DRAWING, insults.G0) terminal.cursorPosition(top, left) terminal.write(b"\154") terminal.write(b"\161" * (width - 2)) terminal.write(b"\153") for n in range(height - 2): terminal.cursorPosition(left, top + n + 1) terminal.write(b"\170") terminal.cursorForward(width - 2) terminal.write(b"\170") terminal.cursorPosition(0, top + height - 1) terminal.write(b"\155") terminal.write(b"\161" * (width - 2)) terminal.write(b"\152") terminal.selectCharacterSet(insults.CS_US, insults.G0)
Return a reasonable default private key subtype for a given key type. @type keyType: L{str} @param keyType: A key type, as returned by L{twisted.conch.ssh.keys.Key.type}. @rtype: L{str} @return: A private OpenSSH key subtype (C{'PEM'} or C{'v1'}).
def _defaultPrivateKeySubtype(keyType): """ Return a reasonable default private key subtype for a given key type. @type keyType: L{str} @param keyType: A key type, as returned by L{twisted.conch.ssh.keys.Key.type}. @rtype: L{str} @return: A private OpenSSH key subtype (C{'PEM'} or C{'v1'}). """ if keyType == "Ed25519": # No PEM format is defined for Ed25519 keys. return "v1" else: return "PEM"
If C{options["filename"]} is None, prompt the user to enter a path or attempt to set it to .ssh/id_rsa @param options: command line options @param inputCollector: dependency injection for testing @param keyTypeName: key type or "rsa"
def _getKeyOrDefault( options: Dict[Any, Any], inputCollector: Optional[Callable[[str], str]] = None, keyTypeName: str = "rsa", ) -> str: """ If C{options["filename"]} is None, prompt the user to enter a path or attempt to set it to .ssh/id_rsa @param options: command line options @param inputCollector: dependency injection for testing @param keyTypeName: key type or "rsa" """ if inputCollector is None: inputCollector = input filename = options["filename"] if not filename: filename = os.path.expanduser(f"~/.ssh/id_{keyTypeName}") if platform.system() == "Windows": filename = os.path.expanduser(Rf"%HOMEPATH %\.ssh\id_{keyTypeName}") filename = ( inputCollector("Enter file in which the key is (%s): " % filename) or filename ) return str(filename)
Ask the user where to save the key. This needs to be a separate function so the unit test can patch it.
def _inputSaveFile(prompt: str) -> str: """ Ask the user where to save the key. This needs to be a separate function so the unit test can patch it. """ return input(prompt)
Persist a SSH key on local filesystem. @param key: Key which is persisted on local filesystem. @param options: @param inputCollector: Dependency injection for testing.
def _saveKey( key: keys.Key, options: Dict[Any, Any], inputCollector: Optional[Callable[[str], str]] = None, ) -> None: """ Persist a SSH key on local filesystem. @param key: Key which is persisted on local filesystem. @param options: @param inputCollector: Dependency injection for testing. """ if inputCollector is None: inputCollector = input KeyTypeMapping = {"EC": "ecdsa", "Ed25519": "ed25519", "RSA": "rsa", "DSA": "dsa"} keyTypeName = KeyTypeMapping[key.type()] filename = options["filename"] if not filename: defaultPath = _getKeyOrDefault(options, inputCollector, keyTypeName) newPath = _inputSaveFile( f"Enter file in which to save the key ({defaultPath}): " ) filename = newPath.strip() or defaultPath if os.path.exists(filename): print(f"{filename} already exists.") yn = inputCollector("Overwrite (y/n)? ") if yn[0].lower() != "y": sys.exit() if options.get("no-passphrase"): options["pass"] = b"" elif not options["pass"]: while 1: p1 = getpass.getpass("Enter passphrase (empty for no passphrase): ") p2 = getpass.getpass("Enter same passphrase again: ") if p1 == p2: break print("Passphrases do not match. Try again.") options["pass"] = p1 if options.get("private-key-subtype") is None: options["private-key-subtype"] = _defaultPrivateKeySubtype(key.type()) comment = f"{getpass.getuser()}@{socket.gethostname()}" fp = filepath.FilePath(filename) fp.setContent( key.toString( "openssh", subtype=options["private-key-subtype"], passphrase=options["pass"], ) ) fp.chmod(0o100600) filepath.FilePath(filename + ".pub").setContent( key.public().toString("openssh", comment=comment) ) options = enumrepresentation(options) print(f"Your identification has been saved in {filename}") print(f"Your public key has been saved in {filename}.pub") print(f"The key fingerprint in {options['format']} is:") print(key.fingerprint(options["format"]))
net string
def NS(t): """ net string """ if isinstance(t, str): t = t.encode("utf-8") return struct.pack("!L", len(t)) + t
get net string
def getNS(s, count=1): """ get net string """ ns = [] c = 0 for i in range(count): (l,) = struct.unpack("!L", s[c : c + 4]) ns.append(s[c + 4 : 4 + l + c]) c += 4 + l return tuple(ns) + (s[c:],)
Get multiple precision integer out of the string. A multiple precision integer is stored as a 4-byte length followed by length bytes of the integer. If count is specified, get count integers out of the string. The return value is a tuple of count integers followed by the rest of the data.
def getMP(data, count=1): """ Get multiple precision integer out of the string. A multiple precision integer is stored as a 4-byte length followed by length bytes of the integer. If count is specified, get count integers out of the string. The return value is a tuple of count integers followed by the rest of the data. """ mp = [] c = 0 for i in range(count): (length,) = struct.unpack(">L", data[c : c + 4]) mp.append(int.from_bytes(data[c + 4 : c + 4 + length], "big")) c += 4 + length return tuple(mp) + (data[c:],)
first from second goes through the first list, looking for items in the second, returns the first one
def ffs(c, s): """ first from second goes through the first list, looking for items in the second, returns the first one """ for i in c: if i in s: return i
Pack the data suitable for sending in a CHANNEL_OPEN packet. @type destination: L{tuple} @param destination: A tuple of the (host, port) of the destination host. @type source: L{tuple} @param source: A tuple of the (host, port) of the source host.
def packOpen_direct_tcpip(destination, source): """ Pack the data suitable for sending in a CHANNEL_OPEN packet. @type destination: L{tuple} @param destination: A tuple of the (host, port) of the destination host. @type source: L{tuple} @param source: A tuple of the (host, port) of the source host. """ (connHost, connPort) = destination (origHost, origPort) = source if isinstance(connHost, str): connHost = connHost.encode("utf-8") if isinstance(origHost, str): origHost = origHost.encode("utf-8") conn = common.NS(connHost) + struct.pack(">L", connPort) orig = common.NS(origHost) + struct.pack(">L", origPort) return conn + orig
Unpack the data to a usable format.
def unpackOpen_direct_tcpip(data): """Unpack the data to a usable format.""" connHost, rest = common.getNS(data) if isinstance(connHost, bytes): connHost = connHost.decode("utf-8") connPort = int(struct.unpack(">L", rest[:4])[0]) origHost, rest = common.getNS(rest[4:]) if isinstance(origHost, bytes): origHost = origHost.decode("utf-8") origPort = int(struct.unpack(">L", rest[:4])[0]) return (connHost, connPort), (origHost, origPort)
Pack the data for tcpip forwarding. @param peer: A tuple of the (host, port) . @type peer: L{tuple}
def packGlobal_tcpip_forward(peer): """ Pack the data for tcpip forwarding. @param peer: A tuple of the (host, port) . @type peer: L{tuple} """ (host, port) = peer return common.NS(host) + struct.pack(">L", port)
Normalize a passphrase, which may be Unicode. If the passphrase is Unicode, this follows the requirements of U{NIST 800-63B, section 5.1.1.2<https://pages.nist.gov/800-63-3/sp800-63b.html#memsecretver>} for Unicode characters in memorized secrets: it applies the Normalization Process for Stabilized Strings using NFKC normalization. The passphrase is then encoded using UTF-8. @type passphrase: L{bytes} or L{unicode} or L{None} @param passphrase: The passphrase to normalize. @return: The normalized passphrase, if any. @rtype: L{bytes} or L{None} @raises PassphraseNormalizationError: if the passphrase is Unicode and cannot be normalized using the available Unicode character database.
def _normalizePassphrase(passphrase): """ Normalize a passphrase, which may be Unicode. If the passphrase is Unicode, this follows the requirements of U{NIST 800-63B, section 5.1.1.2<https://pages.nist.gov/800-63-3/sp800-63b.html#memsecretver>} for Unicode characters in memorized secrets: it applies the Normalization Process for Stabilized Strings using NFKC normalization. The passphrase is then encoded using UTF-8. @type passphrase: L{bytes} or L{unicode} or L{None} @param passphrase: The passphrase to normalize. @return: The normalized passphrase, if any. @rtype: L{bytes} or L{None} @raises PassphraseNormalizationError: if the passphrase is Unicode and cannot be normalized using the available Unicode character database. """ if isinstance(passphrase, str): # The Normalization Process for Stabilized Strings requires aborting # with an error if the string contains any unassigned code point. if any(unicodedata.category(c) == "Cn" for c in passphrase): # Perhaps not very helpful, but we don't want to leak any other # information about the passphrase. raise PassphraseNormalizationError() return unicodedata.normalize("NFKC", passphrase).encode("UTF-8") else: return passphrase
This function returns a persistent L{Key}. The key is loaded from a PEM file in C{location}. If it does not exist, a key with the key size of C{keySize} is generated and saved. @param location: Where the key is stored. @type location: L{twisted.python.filepath.FilePath} @param keySize: The size of the key, if it needs to be generated. @type keySize: L{int} @returns: A persistent key. @rtype: L{Key}
def _getPersistentRSAKey(location, keySize=4096): """ This function returns a persistent L{Key}. The key is loaded from a PEM file in C{location}. If it does not exist, a key with the key size of C{keySize} is generated and saved. @param location: Where the key is stored. @type location: L{twisted.python.filepath.FilePath} @param keySize: The size of the key, if it needs to be generated. @type keySize: L{int} @returns: A persistent key. @rtype: L{Key} """ location.parent().makedirs(ignoreExistingDirectory=True) # If it doesn't exist, we want to generate a new key and save it if not location.exists(): privateKey = rsa.generate_private_key( public_exponent=65537, key_size=keySize, backend=default_backend() ) pem = privateKey.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption(), ) location.setContent(pem) # By this point (save any hilarious race conditions) we should have a # working PEM file. Load it! # (Future archaeological readers: I chose not to short circuit above, # because then there's two exit paths to this code!) with location.open("rb") as keyFile: privateKey = serialization.load_pem_private_key( keyFile.read(), password=None, backend=default_backend() ) return Key(privateKey)
Parse the data from a pty-req request into usable data. @returns: a tuple of (terminal type, (rows, cols, xpixel, ypixel), modes)
def parseRequest_pty_req(data): """Parse the data from a pty-req request into usable data. @returns: a tuple of (terminal type, (rows, cols, xpixel, ypixel), modes) """ term, rest = common.getNS(data) cols, rows, xpixel, ypixel = struct.unpack(">4L", rest[:16]) modes, ignored = common.getNS(rest[16:]) winSize = (rows, cols, xpixel, ypixel) modes = [ (ord(modes[i : i + 1]), struct.unpack(">L", modes[i + 1 : i + 5])[0]) for i in range(0, len(modes) - 1, 5) ] return term, winSize, modes
Pack a pty-req request so that it is suitable for sending. NOTE: modes must be packed before being sent here. @type geometry: L{tuple} @param geometry: A tuple of (rows, columns, xpixel, ypixel)
def packRequest_pty_req(term, geometry, modes): """ Pack a pty-req request so that it is suitable for sending. NOTE: modes must be packed before being sent here. @type geometry: L{tuple} @param geometry: A tuple of (rows, columns, xpixel, ypixel) """ (rows, cols, xpixel, ypixel) = geometry termPacked = common.NS(term) winSizePacked = struct.pack(">4L", cols, rows, xpixel, ypixel) modesPacked = common.NS(modes) # depend on the client packing modes return termPacked + winSizePacked + modesPacked
Parse the data from a window-change request into usuable data. @returns: a tuple of (rows, cols, xpixel, ypixel)
def parseRequest_window_change(data): """Parse the data from a window-change request into usuable data. @returns: a tuple of (rows, cols, xpixel, ypixel) """ cols, rows, xpixel, ypixel = struct.unpack(">4L", data) return rows, cols, xpixel, ypixel
Pack a window-change request so that it is suitable for sending. @type geometry: L{tuple} @param geometry: A tuple of (rows, columns, xpixel, ypixel)
def packRequest_window_change(geometry): """ Pack a window-change request so that it is suitable for sending. @type geometry: L{tuple} @param geometry: A tuple of (rows, columns, xpixel, ypixel) """ (rows, cols, xpixel, ypixel) = geometry return struct.pack(">4L", cols, rows, xpixel, ypixel)
Make an SSH multiple-precision integer from big-endian L{bytes}. Used in ECDH key exchange. @type data: L{bytes} @param data: The input data, interpreted as a big-endian octet string. @rtype: L{bytes} @return: The given data encoded as an SSH multiple-precision integer.
def _mpFromBytes(data): """Make an SSH multiple-precision integer from big-endian L{bytes}. Used in ECDH key exchange. @type data: L{bytes} @param data: The input data, interpreted as a big-endian octet string. @rtype: L{bytes} @return: The given data encoded as an SSH multiple-precision integer. """ return MP(int.from_bytes(data, "big"))
Build a list of ciphers that are supported by the backend in use. @return: a list of supported ciphers. @rtype: L{list} of L{str}
def _getSupportedCiphers(): """ Build a list of ciphers that are supported by the backend in use. @return: a list of supported ciphers. @rtype: L{list} of L{str} """ supportedCiphers = [] cs = [ b"aes256-ctr", b"aes256-cbc", b"aes192-ctr", b"aes192-cbc", b"aes128-ctr", b"aes128-cbc", b"cast128-ctr", b"cast128-cbc", b"blowfish-ctr", b"blowfish-cbc", b"3des-ctr", b"3des-cbc", ] for cipher in cs: algorithmClass, keySize, modeClass = SSHCiphers.cipherMap[cipher] try: Cipher( algorithmClass(b" " * keySize), modeClass(b" " * (algorithmClass.block_size // 8)), backend=default_backend(), ).encryptor() except UnsupportedAlgorithm: pass else: supportedCiphers.append(cipher) return supportedCiphers
Get a description of a named key exchange algorithm. @param kexAlgorithm: The key exchange algorithm name. @type kexAlgorithm: L{bytes} @return: A description of the key exchange algorithm named by C{kexAlgorithm}. @rtype: L{_IKexAlgorithm} @raises ConchError: if the key exchange algorithm is not found.
def getKex(kexAlgorithm): """ Get a description of a named key exchange algorithm. @param kexAlgorithm: The key exchange algorithm name. @type kexAlgorithm: L{bytes} @return: A description of the key exchange algorithm named by C{kexAlgorithm}. @rtype: L{_IKexAlgorithm} @raises ConchError: if the key exchange algorithm is not found. """ if kexAlgorithm not in _kexAlgorithms: raise error.ConchError(f"Unsupported key exchange algorithm: {kexAlgorithm}") return _kexAlgorithms[kexAlgorithm]
Returns C{True} if C{kexAlgorithm} is an elliptic curve. @param kexAlgorithm: The key exchange algorithm name. @type kexAlgorithm: C{str} @return: C{True} if C{kexAlgorithm} is an elliptic curve, otherwise C{False}. @rtype: C{bool}
def isEllipticCurve(kexAlgorithm): """ Returns C{True} if C{kexAlgorithm} is an elliptic curve. @param kexAlgorithm: The key exchange algorithm name. @type kexAlgorithm: C{str} @return: C{True} if C{kexAlgorithm} is an elliptic curve, otherwise C{False}. @rtype: C{bool} """ return _IEllipticCurveExchangeKexAlgorithm.providedBy(getKex(kexAlgorithm))
Returns C{True} if C{kexAlgorithm} has a fixed prime / generator group. @param kexAlgorithm: The key exchange algorithm name. @type kexAlgorithm: L{bytes} @return: C{True} if C{kexAlgorithm} has a fixed prime / generator group, otherwise C{False}. @rtype: L{bool}
def isFixedGroup(kexAlgorithm): """ Returns C{True} if C{kexAlgorithm} has a fixed prime / generator group. @param kexAlgorithm: The key exchange algorithm name. @type kexAlgorithm: L{bytes} @return: C{True} if C{kexAlgorithm} has a fixed prime / generator group, otherwise C{False}. @rtype: L{bool} """ return _IFixedGroupKexAlgorithm.providedBy(getKex(kexAlgorithm))
Get the hash algorithm callable to use in key exchange. @param kexAlgorithm: The key exchange algorithm name. @type kexAlgorithm: L{bytes} @return: A callable hash algorithm constructor (e.g. C{hashlib.sha256}). @rtype: C{callable}
def getHashProcessor(kexAlgorithm): """ Get the hash algorithm callable to use in key exchange. @param kexAlgorithm: The key exchange algorithm name. @type kexAlgorithm: L{bytes} @return: A callable hash algorithm constructor (e.g. C{hashlib.sha256}). @rtype: C{callable} """ kex = getKex(kexAlgorithm) return kex.hashProcessor
Get the generator and the prime to use in key exchange. @param kexAlgorithm: The key exchange algorithm name. @type kexAlgorithm: L{bytes} @return: A L{tuple} containing L{int} generator and L{int} prime. @rtype: L{tuple}
def getDHGeneratorAndPrime(kexAlgorithm): """ Get the generator and the prime to use in key exchange. @param kexAlgorithm: The key exchange algorithm name. @type kexAlgorithm: L{bytes} @return: A L{tuple} containing L{int} generator and L{int} prime. @rtype: L{tuple} """ kex = getKex(kexAlgorithm) return kex.generator, kex.prime
Get a list of supported key exchange algorithm names in order of preference. @return: A C{list} of supported key exchange algorithm names. @rtype: C{list} of L{bytes}
def getSupportedKeyExchanges(): """ Get a list of supported key exchange algorithm names in order of preference. @return: A C{list} of supported key exchange algorithm names. @rtype: C{list} of L{bytes} """ from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric import ec from twisted.conch.ssh.keys import _curveTable backend = default_backend() kexAlgorithms = _kexAlgorithms.copy() for keyAlgorithm in list(kexAlgorithms): if keyAlgorithm.startswith(b"ecdh"): keyAlgorithmDsa = keyAlgorithm.replace(b"ecdh", b"ecdsa") supported = backend.elliptic_curve_exchange_algorithm_supported( ec.ECDH(), _curveTable[keyAlgorithmDsa] ) elif keyAlgorithm.startswith(b"curve25519-sha256"): supported = backend.x25519_supported() else: supported = True if not supported: kexAlgorithms.pop(keyAlgorithm) return sorted( kexAlgorithms, key=lambda kexAlgorithm: kexAlgorithms[kexAlgorithm].preference )
Connect a SSHTransport which is already connected to a remote peer to the channel under test. @param service: Service used over the connected transport. @type service: L{SSHService} @param hostAddress: Local address of the connected transport. @type hostAddress: L{interfaces.IAddress} @param peerAddress: Remote address of the connected transport. @type peerAddress: L{interfaces.IAddress}
def connectSSHTransport( service: SSHService, hostAddress: interfaces.IAddress | None = None, peerAddress: interfaces.IAddress | None = None, ) -> None: """ Connect a SSHTransport which is already connected to a remote peer to the channel under test. @param service: Service used over the connected transport. @type service: L{SSHService} @param hostAddress: Local address of the connected transport. @type hostAddress: L{interfaces.IAddress} @param peerAddress: Remote address of the connected transport. @type peerAddress: L{interfaces.IAddress} """ transport = SSHServerTransport() transport.makeConnection( StringTransport(hostAddress=hostAddress, peerAddress=peerAddress) ) transport.setService(service)
Return a callable to patch C{getpass.getpass}. Yields a passphrase each time called. Use case is to provide an old, then new passphrase(s) as if requested interactively. @param passphrases: The list of passphrases returned, one per each call. @return: A callable to patch C{getpass.getpass}.
def makeGetpass(*passphrases: str) -> Callable[[object], str]: """ Return a callable to patch C{getpass.getpass}. Yields a passphrase each time called. Use case is to provide an old, then new passphrase(s) as if requested interactively. @param passphrases: The list of passphrases returned, one per each call. @return: A callable to patch C{getpass.getpass}. """ passphrasesIter = iter(passphrases) def fakeGetpass(_: object) -> str: return next(passphrasesIter) return fakeGetpass
Returns True if the system can bind an IPv6 address.
def _has_ipv6(): """Returns True if the system can bind an IPv6 address.""" sock = None has_ipv6 = False try: sock = socket.socket(socket.AF_INET6) sock.bind(("::1", 0)) has_ipv6 = True except OSError: pass if sock: sock.close() return has_ipv6
Return the byte in 7- or 8-bit code table identified by C{column} and C{row}. "An 8-bit code table consists of 256 positions arranged in 16 columns and 16 rows. The columns and rows are numbered 00 to 15." "A 7-bit code table consists of 128 positions arranged in 8 columns and 16 rows. The columns are numbered 00 to 07 and the rows 00 to 15 (see figure 1)." p.5 of "Standard ECMA-35: Character Code Structure and Extension Techniques", 6th Edition (December 1994).
def _ecmaCodeTableCoordinate(column, row): """ Return the byte in 7- or 8-bit code table identified by C{column} and C{row}. "An 8-bit code table consists of 256 positions arranged in 16 columns and 16 rows. The columns and rows are numbered 00 to 15." "A 7-bit code table consists of 128 positions arranged in 8 columns and 16 rows. The columns are numbered 00 to 07 and the rows 00 to 15 (see figure 1)." p.5 of "Standard ECMA-35: Character Code Structure and Extension Techniques", 6th Edition (December 1994). """ # 8 and 15 both happen to take up 4 bits, so the first number # should be shifted by 4 for both the 7- and 8-bit tables. return bytes(bytearray([(column << 4) | row]))
Return the string used by Python as the name for code objects which are compiled from interactive input or at the top-level of modules.
def determineDefaultFunctionName(): """ Return the string used by Python as the name for code objects which are compiled from interactive input or at the top-level of modules. """ try: 1 // 0 except BaseException: # The last frame is this function. The second to last frame is this # function's caller, which is module-scope, which is what we want, # so -2. return traceback.extract_stack()[-2][2]
Return the MP version of C{(x ** y) % z}.
def _MPpow(x, y, z): """ Return the MP version of C{(x ** y) % z}. """ return common.MP(pow(x, y, z))
Find all objects that implement L{ICheckerFactory}.
def findCheckerFactories(): """ Find all objects that implement L{ICheckerFactory}. """ return getPlugins(ICheckerFactory)
Find the first checker factory that supports the given authType.
def findCheckerFactory(authType): """ Find the first checker factory that supports the given authType. """ for factory in findCheckerFactories(): if factory.authType == authType: return factory raise InvalidAuthType(authType)
Returns an L{twisted.cred.checkers.ICredentialsChecker} based on the contents of a descriptive string. Similar to L{twisted.application.strports}.
def makeChecker(description): """ Returns an L{twisted.cred.checkers.ICredentialsChecker} based on the contents of a descriptive string. Similar to L{twisted.application.strports}. """ if ":" in description: authType, argstring = description.split(":", 1) else: authType = description argstring = "" return findCheckerFactory(authType).generateChecker(argstring)
Compute H(A1) from RFC 2617. @param pszAlg: The name of the algorithm to use to calculate the digest. Currently supported are md5, md5-sess, and sha. @param pszUserName: The username @param pszRealm: The realm @param pszPassword: The password @param pszNonce: The nonce @param pszCNonce: The cnonce @param preHA1: If available this is a str containing a previously calculated H(A1) as a hex string. If this is given then the values for pszUserName, pszRealm, and pszPassword must be L{None} and are ignored.
def calcHA1( pszAlg, pszUserName, pszRealm, pszPassword, pszNonce, pszCNonce, preHA1=None ): """ Compute H(A1) from RFC 2617. @param pszAlg: The name of the algorithm to use to calculate the digest. Currently supported are md5, md5-sess, and sha. @param pszUserName: The username @param pszRealm: The realm @param pszPassword: The password @param pszNonce: The nonce @param pszCNonce: The cnonce @param preHA1: If available this is a str containing a previously calculated H(A1) as a hex string. If this is given then the values for pszUserName, pszRealm, and pszPassword must be L{None} and are ignored. """ if preHA1 and (pszUserName or pszRealm or pszPassword): raise TypeError( "preHA1 is incompatible with the pszUserName, " "pszRealm, and pszPassword arguments" ) if preHA1 is None: # We need to calculate the HA1 from the username:realm:password m = algorithms[pszAlg]() m.update(pszUserName) m.update(b":") m.update(pszRealm) m.update(b":") m.update(pszPassword) HA1 = hexlify(m.digest()) else: # We were given a username:realm:password HA1 = preHA1 if pszAlg == b"md5-sess": m = algorithms[pszAlg]() m.update(HA1) m.update(b":") m.update(pszNonce) m.update(b":") m.update(pszCNonce) HA1 = hexlify(m.digest()) return HA1
Compute H(A2) from RFC 2617. @param algo: The name of the algorithm to use to calculate the digest. Currently supported are md5, md5-sess, and sha. @param pszMethod: The request method. @param pszDigestUri: The request URI. @param pszQop: The Quality-of-Protection value. @param pszHEntity: The hash of the entity body or L{None} if C{pszQop} is not C{'auth-int'}. @return: The hash of the A2 value for the calculation of the response digest.
def calcHA2(algo, pszMethod, pszDigestUri, pszQop, pszHEntity): """ Compute H(A2) from RFC 2617. @param algo: The name of the algorithm to use to calculate the digest. Currently supported are md5, md5-sess, and sha. @param pszMethod: The request method. @param pszDigestUri: The request URI. @param pszQop: The Quality-of-Protection value. @param pszHEntity: The hash of the entity body or L{None} if C{pszQop} is not C{'auth-int'}. @return: The hash of the A2 value for the calculation of the response digest. """ m = algorithms[algo]() m.update(pszMethod) m.update(b":") m.update(pszDigestUri) if pszQop == b"auth-int": m.update(b":") m.update(pszHEntity) return hexlify(m.digest())
Compute the digest for the given parameters. @param HA1: The H(A1) value, as computed by L{calcHA1}. @param HA2: The H(A2) value, as computed by L{calcHA2}. @param pszNonce: The challenge nonce. @param pszNonceCount: The (client) nonce count value for this response. @param pszCNonce: The client nonce. @param pszQop: The Quality-of-Protection value.
def calcResponse(HA1, HA2, algo, pszNonce, pszNonceCount, pszCNonce, pszQop): """ Compute the digest for the given parameters. @param HA1: The H(A1) value, as computed by L{calcHA1}. @param HA2: The H(A2) value, as computed by L{calcHA2}. @param pszNonce: The challenge nonce. @param pszNonceCount: The (client) nonce count value for this response. @param pszCNonce: The client nonce. @param pszQop: The Quality-of-Protection value. """ m = algorithms[algo]() m.update(HA1) m.update(b":") m.update(pszNonce) m.update(b":") if pszNonceCount and pszCNonce: m.update(pszNonceCount) m.update(b":") m.update(pszCNonce) m.update(b":") m.update(pszQop) m.update(b":") m.update(HA2) respHash = hexlify(m.digest()) return respHash
Helper method to produce an auth type that doesn't exist.
def getInvalidAuthType(): """ Helper method to produce an auth type that doesn't exist. """ invalidAuthType = "ThisPluginDoesNotExist" while invalidAuthType in [ factory.authType for factory in strcred.findCheckerFactories() ]: invalidAuthType += "_" return invalidAuthType
Determine whether the given string represents an IP address of the given family; by default, an IPv4 address. @param addr: A string which may or may not be the decimal dotted representation of an IPv4 address. @param family: The address family to test for; one of the C{AF_*} constants from the L{socket} module. (This parameter has only been available since Twisted 17.1.0; previously L{isIPAddress} could only test for IPv4 addresses.) @return: C{True} if C{addr} represents an IPv4 address, C{False} otherwise.
def isIPAddress(addr: str, family: int = AF_INET) -> bool: """ Determine whether the given string represents an IP address of the given family; by default, an IPv4 address. @param addr: A string which may or may not be the decimal dotted representation of an IPv4 address. @param family: The address family to test for; one of the C{AF_*} constants from the L{socket} module. (This parameter has only been available since Twisted 17.1.0; previously L{isIPAddress} could only test for IPv4 addresses.) @return: C{True} if C{addr} represents an IPv4 address, C{False} otherwise. """ if isinstance(addr, bytes): # type: ignore[unreachable] try: # type: ignore[unreachable] addr = addr.decode("ascii") except UnicodeDecodeError: return False if family == AF_INET6: # On some platforms, inet_ntop fails unless the scope ID is valid; this # is a test for whether the given string *is* an IP address, so strip # any potential scope ID before checking. addr = addr.split("%", 1)[0] elif family == AF_INET: # On Windows, where 3.5+ implement inet_pton, "0" is considered a valid # IPv4 address, but we want to ensure we have all 4 segments. if addr.count(".") != 3: return False else: raise ValueError(f"unknown address family {family!r}") try: # This might be a native implementation or the one from # twisted.python.compat. inet_pton(family, addr) except (ValueError, OSError): return False return True
Determine whether the given string represents an IPv6 address. @param addr: A string which may or may not be the hex representation of an IPv6 address. @type addr: C{str} @return: C{True} if C{addr} represents an IPv6 address, C{False} otherwise. @rtype: C{bool}
def isIPv6Address(addr: str) -> bool: """ Determine whether the given string represents an IPv6 address. @param addr: A string which may or may not be the hex representation of an IPv6 address. @type addr: C{str} @return: C{True} if C{addr} represents an IPv6 address, C{False} otherwise. @rtype: C{bool} """ return isIPAddress(addr, AF_INET6)
Install an asyncio-based reactor. @param eventloop: The asyncio eventloop to wrap. If default, the global one is selected.
def install(eventloop=None): """ Install an asyncio-based reactor. @param eventloop: The asyncio eventloop to wrap. If default, the global one is selected. """ reactor = AsyncioSelectorReactor(eventloop) from twisted.internet.main import installReactor installReactor(reactor)
Configure the twisted mainloop to be run inside CFRunLoop. @param runLoop: the run loop to use. @param runner: the function to call in order to actually invoke the main loop. This will default to C{CFRunLoopRun} if not specified. However, this is not an appropriate choice for GUI applications, as you need to run NSApplicationMain (or something like it). For example, to run the Twisted mainloop in a PyObjC application, your C{main.py} should look something like this:: from PyObjCTools import AppHelper from twisted.internet.cfreactor import install install(runner=AppHelper.runEventLoop) # initialize your application reactor.run() @return: The installed reactor. @rtype: C{CFReactor}
def install(runLoop=None, runner=None): """ Configure the twisted mainloop to be run inside CFRunLoop. @param runLoop: the run loop to use. @param runner: the function to call in order to actually invoke the main loop. This will default to C{CFRunLoopRun} if not specified. However, this is not an appropriate choice for GUI applications, as you need to run NSApplicationMain (or something like it). For example, to run the Twisted mainloop in a PyObjC application, your C{main.py} should look something like this:: from PyObjCTools import AppHelper from twisted.internet.cfreactor import install install(runner=AppHelper.runEventLoop) # initialize your application reactor.run() @return: The installed reactor. @rtype: C{CFReactor} """ reactor = CFReactor(runLoop=runLoop, runner=runner) from twisted.internet.main import installReactor installReactor(reactor) return reactor
Return a function to install the reactor most suited for the given platform. @param platform: The platform for which to select a reactor. @type platform: L{twisted.python.runtime.Platform} @return: A zero-argument callable which will install the selected reactor.
def _getInstallFunction(platform): """ Return a function to install the reactor most suited for the given platform. @param platform: The platform for which to select a reactor. @type platform: L{twisted.python.runtime.Platform} @return: A zero-argument callable which will install the selected reactor. """ # Linux: epoll(7) is the default, since it scales well. # # macOS: poll(2) is not exposed by Python because it doesn't support all # file descriptors (in particular, lack of PTY support is a problem) -- # see <http://bugs.python.org/issue5154>. kqueue has the same restrictions # as poll(2) as far PTY support goes. # # Windows: IOCP should eventually be default, but still has some serious # bugs, e.g. <http://twistedmatrix.com/trac/ticket/4667>. # # We therefore choose epoll(7) on Linux, poll(2) on other non-macOS POSIX # platforms, and select(2) everywhere else. try: if platform.isLinux(): try: from twisted.internet.epollreactor import install except ImportError: from twisted.internet.pollreactor import install elif platform.getType() == "posix" and not platform.isMacOSX(): from twisted.internet.pollreactor import install else: from twisted.internet.selectreactor import install except ImportError: from twisted.internet.selectreactor import install return install
Log and return failure. This method can be used as an errback that passes the failure on to the next errback unmodified. Note that if this is the last errback, and the deferred gets garbage collected after being this errback has been called, the clean up code logs it again.
def logError(err: Failure) -> Failure: """ Log and return failure. This method can be used as an errback that passes the failure on to the next errback unmodified. Note that if this is the last errback, and the deferred gets garbage collected after being this errback has been called, the clean up code logs it again. """ log.failure("", err) return err
Return a L{Deferred} that has already had C{.callback(result)} called. This is useful when you're writing synchronous code to an asynchronous interface: i.e., some code is calling you expecting a L{Deferred} result, but you don't actually need to do anything asynchronous. Just return C{defer.succeed(theResult)}. See L{fail} for a version of this function that uses a failing L{Deferred} rather than a successful one. @param result: The result to give to the Deferred's 'callback' method.
def succeed(result: _T) -> "Deferred[_T]": """ Return a L{Deferred} that has already had C{.callback(result)} called. This is useful when you're writing synchronous code to an asynchronous interface: i.e., some code is calling you expecting a L{Deferred} result, but you don't actually need to do anything asynchronous. Just return C{defer.succeed(theResult)}. See L{fail} for a version of this function that uses a failing L{Deferred} rather than a successful one. @param result: The result to give to the Deferred's 'callback' method. """ d: Deferred[_T] = Deferred() d.callback(result) return d
Return a L{Deferred} that has already had C{.errback(result)} called. See L{succeed}'s docstring for rationale. @param result: The same argument that L{Deferred.errback} takes. @raise NoCurrentExceptionError: If C{result} is L{None} but there is no current exception state.
def fail(result: Optional[Union[Failure, BaseException]] = None) -> "Deferred[Any]": """ Return a L{Deferred} that has already had C{.errback(result)} called. See L{succeed}'s docstring for rationale. @param result: The same argument that L{Deferred.errback} takes. @raise NoCurrentExceptionError: If C{result} is L{None} but there is no current exception state. """ d: Deferred[Any] = Deferred() d.errback(result) return d
Create a L{Deferred} from a callable and arguments. Call the given function with the given arguments. Return a L{Deferred} which has been fired with its callback as the result of that invocation or its C{errback} with a L{Failure} for the exception thrown.
def execute( callable: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs ) -> "Deferred[_T]": """ Create a L{Deferred} from a callable and arguments. Call the given function with the given arguments. Return a L{Deferred} which has been fired with its callback as the result of that invocation or its C{errback} with a L{Failure} for the exception thrown. """ try: result = callable(*args, **kwargs) except BaseException: return fail() else: return succeed(result)
Invoke a function that may or may not return a L{Deferred} or coroutine. Call the given function with the given arguments. Then: - If the returned object is a L{Deferred}, return it. - If the returned object is a L{Failure}, wrap it with L{fail} and return it. - If the returned object is a L{types.CoroutineType}, wrap it with L{Deferred.fromCoroutine} and return it. - Otherwise, wrap it in L{succeed} and return it. - If an exception is raised, convert it to a L{Failure}, wrap it in L{fail}, and then return it. @param f: The callable to invoke @param args: The arguments to pass to C{f} @param kwargs: The keyword arguments to pass to C{f} @return: The result of the function call, wrapped in a L{Deferred} if necessary.
def maybeDeferred( f: Callable[_P, Union[Deferred[_T], Coroutine[Deferred[Any], Any, _T], _T]], *args: _P.args, **kwargs: _P.kwargs, ) -> "Deferred[_T]": """ Invoke a function that may or may not return a L{Deferred} or coroutine. Call the given function with the given arguments. Then: - If the returned object is a L{Deferred}, return it. - If the returned object is a L{Failure}, wrap it with L{fail} and return it. - If the returned object is a L{types.CoroutineType}, wrap it with L{Deferred.fromCoroutine} and return it. - Otherwise, wrap it in L{succeed} and return it. - If an exception is raised, convert it to a L{Failure}, wrap it in L{fail}, and then return it. @param f: The callable to invoke @param args: The arguments to pass to C{f} @param kwargs: The keyword arguments to pass to C{f} @return: The result of the function call, wrapped in a L{Deferred} if necessary. """ try: result = f(*args, **kwargs) except BaseException: return fail(Failure(captureVars=Deferred.debug)) if isinstance(result, Deferred): return result elif isinstance(result, Failure): return fail(result) elif type(result) is CoroutineType: # A note on how we identify this case ... # # inspect.iscoroutinefunction(f) should be the simplest and easiest # way to determine if we want to apply coroutine handling. However, # the value may be returned by a regular function that calls a # coroutine function and returns its result. It would be confusing if # cases like this led to different handling of the coroutine (even # though it is a mistake to have a regular function call a coroutine # function to return its result - doing so immediately destroys a # large part of the value of coroutine functions: that they can only # have a coroutine result). # # There are many ways we could inspect ``result`` to determine if it # is a "coroutine" but most of these are mistakes. The goal is only # to determine whether the value came from ``async def`` or not # because these are the only values we're trying to handle with this # case. Such values always have exactly one type: CoroutineType. return Deferred.fromCoroutine(result) else: returned: _T = result # type: ignore return succeed(returned)
Enable or disable L{Deferred} debugging. When debugging is on, the call stacks from creation and invocation are recorded, and added to any L{AlreadyCalledError}s we raise.
def setDebugging(on: bool) -> None: """ Enable or disable L{Deferred} debugging. When debugging is on, the call stacks from creation and invocation are recorded, and added to any L{AlreadyCalledError}s we raise. """ Deferred.debug = bool(on)
Determine whether L{Deferred} debugging is enabled.
def getDebugging() -> bool: """ Determine whether L{Deferred} debugging is enabled. """ return Deferred.debug
A default translation function that translates L{Failure}s that are L{CancelledError}s to L{TimeoutError}s. @param value: Anything @param timeout: The timeout @raise TimeoutError: If C{value} is a L{Failure} that is a L{CancelledError}. @raise Exception: If C{value} is a L{Failure} that is not a L{CancelledError}, it is re-raised. @since: 16.5
def _cancelledToTimedOutError(value: _T, timeout: float) -> _T: """ A default translation function that translates L{Failure}s that are L{CancelledError}s to L{TimeoutError}s. @param value: Anything @param timeout: The timeout @raise TimeoutError: If C{value} is a L{Failure} that is a L{CancelledError}. @raise Exception: If C{value} is a L{Failure} that is not a L{CancelledError}, it is re-raised. @since: 16.5 """ if isinstance(value, Failure): value.trap(CancelledError) raise TimeoutError(timeout, "Deferred") return value
Schedule the execution of a coroutine that awaits/yields from L{Deferred}s, wrapping it in a L{Deferred} that will fire on success/failure of the coroutine. If a Deferred is passed to this function, it will be returned directly (mimicking the L{asyncio.ensure_future} function). See L{Deferred.fromCoroutine} for examples of coroutines. @param coro: The coroutine object to schedule, or a L{Deferred}.
def ensureDeferred( coro: Union[ Coroutine[Deferred[Any], Any, _T], Generator[Deferred[Any], Any, _T], Deferred[_T], ] ) -> Deferred[_T]: """ Schedule the execution of a coroutine that awaits/yields from L{Deferred}s, wrapping it in a L{Deferred} that will fire on success/failure of the coroutine. If a Deferred is passed to this function, it will be returned directly (mimicking the L{asyncio.ensure_future} function). See L{Deferred.fromCoroutine} for examples of coroutines. @param coro: The coroutine object to schedule, or a L{Deferred}. """ if isinstance(coro, Deferred): return coro else: try: return Deferred.fromCoroutine(coro) except NotACoroutineError: # It's not a coroutine. Raise an exception, but say that it's also # not a Deferred so the error makes sense. raise NotACoroutineError(f"{coro!r} is not a coroutine or a Deferred")
Returns, via a L{Deferred}, a list with the results of the given L{Deferred}s - in effect, a "join" of multiple deferred operations. The returned L{Deferred} will fire when I{all} of the provided L{Deferred}s have fired, or when any one of them has failed. This method can be cancelled by calling the C{cancel} method of the L{Deferred}, all the L{Deferred}s in the list will be cancelled. This differs from L{DeferredList} in that you don't need to parse the result for success/failure. @param consumeErrors: (keyword param) a flag, defaulting to False, indicating that failures in any of the given L{Deferred}s should not be propagated to errbacks added to the individual L{Deferred}s after this L{gatherResults} invocation. Any such errors in the individual L{Deferred}s will be converted to a callback result of L{None}. This is useful to prevent spurious 'Unhandled error in Deferred' messages from being logged. This parameter is available since 11.1.0.
def gatherResults( deferredList: Iterable[Deferred[_T]], consumeErrors: bool = False ) -> Deferred[List[_T]]: """ Returns, via a L{Deferred}, a list with the results of the given L{Deferred}s - in effect, a "join" of multiple deferred operations. The returned L{Deferred} will fire when I{all} of the provided L{Deferred}s have fired, or when any one of them has failed. This method can be cancelled by calling the C{cancel} method of the L{Deferred}, all the L{Deferred}s in the list will be cancelled. This differs from L{DeferredList} in that you don't need to parse the result for success/failure. @param consumeErrors: (keyword param) a flag, defaulting to False, indicating that failures in any of the given L{Deferred}s should not be propagated to errbacks added to the individual L{Deferred}s after this L{gatherResults} invocation. Any such errors in the individual L{Deferred}s will be converted to a callback result of L{None}. This is useful to prevent spurious 'Unhandled error in Deferred' messages from being logged. This parameter is available since 11.1.0. """ return DeferredList( deferredList, fireOnOneErrback=True, consumeErrors=consumeErrors ).addCallback(_parseDeferredListResult)
Select the first available result from the sequence of Deferreds and cancel the rest. @return: A cancellable L{Deferred} that fires with the index and output of the element of C{ds} to have a success result first, or that fires with L{FailureGroup} holding a list of their failures if they all fail.
def race(ds: Sequence[Deferred[_T]]) -> Deferred[tuple[int, _T]]: """ Select the first available result from the sequence of Deferreds and cancel the rest. @return: A cancellable L{Deferred} that fires with the index and output of the element of C{ds} to have a success result first, or that fires with L{FailureGroup} holding a list of their failures if they all fail. """ # Keep track of the Deferred for the action which completed first. When # it completes, all of the other Deferreds will get cancelled but this one # shouldn't be. Even though it "completed" it isn't really done - the # caller will still be using it for something. If we cancelled it, # cancellation could propagate down to them. winner: Optional[Deferred[_T]] = None # The cancellation function for the Deferred this function returns. def cancel(result: Deferred[_T]) -> None: # If it is cancelled then we cancel all of the Deferreds for the # individual actions because there is no longer the possibility of # delivering any of their results anywhere. We don't have to fire # `result` because the Deferred will do that for us. for d in to_cancel: d.cancel() # The Deferred that this function will return. It will fire with the # index and output of the action that completes first, or errback if all # of the actions fail. If it is cancelled, all of the actions will be # cancelled. final_result: Deferred[tuple[int, _T]] = Deferred(canceller=cancel) # A callback for an individual action. def succeeded(this_output: _T, this_index: int) -> None: # If it is the first action to succeed then it becomes the "winner", # its index/output become the externally visible result, and the rest # of the action Deferreds get cancelled. If it is not the first # action to succeed (because some action did not support # cancellation), just ignore the result. It is uncommon for this # callback to be entered twice. The only way it can happen is if one # of the input Deferreds has a cancellation function that fires the # Deferred with a success result. nonlocal winner if winner is None: # This is the first success. Act on it. winner = to_cancel[this_index] # Cancel the rest. for d in to_cancel: if d is not winner: d.cancel() # Fire our Deferred final_result.callback((this_index, this_output)) # Keep track of how many actions have failed. If they all fail we need to # deliver failure notification on our externally visible result. failure_state = [] def failed(failure: Failure, this_index: int) -> None: failure_state.append((this_index, failure)) if len(failure_state) == len(to_cancel): # Every operation failed. failure_state.sort() failures = [f for (ignored, f) in failure_state] final_result.errback(FailureGroup(failures)) # Copy the sequence of Deferreds so we know it doesn't get mutated out # from under us. to_cancel = list(ds) for index, d in enumerate(ds): # Propagate the position of this action as well as the argument to f # to the success callback so we can cancel the right Deferreds and # propagate the result outwards. d.addCallbacks(succeeded, failed, callbackArgs=(index,), errbackArgs=(index,)) return final_result
See L{deferredGenerator}.
def _deferGenerator( g: _DeferableGenerator, deferred: Deferred[object] ) -> Deferred[Any]: """ See L{deferredGenerator}. """ result = None # This function is complicated by the need to prevent unbounded recursion # arising from repeatedly yielding immediately ready deferreds. This while # loop and the waiting variable solve that by manually unfolding the # recursion. # defgen is waiting for result? # result # type note: List[Any] because you can't annotate List items by index. # …better fix would be to create a class, but we need to jettison # deferredGenerator anyway. waiting: List[Any] = [True, None] while 1: try: result = next(g) except StopIteration: deferred.callback(result) return deferred except BaseException: deferred.errback() return deferred # Deferred.callback(Deferred) raises an error; we catch this case # early here and give a nicer error message to the user in case # they yield a Deferred. if isinstance(result, Deferred): return fail(TypeError("Yield waitForDeferred(d), not d!")) if isinstance(result, waitForDeferred): # a waitForDeferred was yielded, get the result. # Pass result in so it don't get changed going around the loop # This isn't a problem for waiting, as it's only reused if # gotResult has already been executed. def gotResult( r: object, result: waitForDeferred = cast(waitForDeferred, result) ) -> None: result.result = r if waiting[0]: waiting[0] = False waiting[1] = r else: _deferGenerator(g, deferred) result.d.addBoth(gotResult) if waiting[0]: # Haven't called back yet, set flag so that we get reinvoked # and return from the loop waiting[0] = False return deferred # Reset waiting to initial values for next loop waiting[0] = True waiting[1] = None result = None
L{deferredGenerator} and L{waitForDeferred} help you write L{Deferred}-using code that looks like a regular sequential function. Consider the use of L{inlineCallbacks} instead, which can accomplish the same thing in a more concise manner. There are two important functions involved: L{waitForDeferred}, and L{deferredGenerator}. They are used together, like this:: @deferredGenerator def thingummy(): thing = waitForDeferred(makeSomeRequestResultingInDeferred()) yield thing thing = thing.getResult() print(thing) #the result! hoorj! L{waitForDeferred} returns something that you should immediately yield; when your generator is resumed, calling C{thing.getResult()} will either give you the result of the L{Deferred} if it was a success, or raise an exception if it was a failure. Calling C{getResult} is B{absolutely mandatory}. If you do not call it, I{your program will not work}. L{deferredGenerator} takes one of these waitForDeferred-using generator functions and converts it into a function that returns a L{Deferred}. The result of the L{Deferred} will be the last value that your generator yielded unless the last value is a L{waitForDeferred} instance, in which case the result will be L{None}. If the function raises an unhandled exception, the L{Deferred} will errback instead. Remember that C{return result} won't work; use C{yield result; return} in place of that. Note that not yielding anything from your generator will make the L{Deferred} result in L{None}. Yielding a L{Deferred} from your generator is also an error condition; always yield C{waitForDeferred(d)} instead. The L{Deferred} returned from your deferred generator may also errback if your generator raised an exception. For example:: @deferredGenerator def thingummy(): thing = waitForDeferred(makeSomeRequestResultingInDeferred()) yield thing thing = thing.getResult() if thing == 'I love Twisted': # will become the result of the Deferred yield 'TWISTED IS GREAT!' return else: # will trigger an errback raise Exception('DESTROY ALL LIFE') Put succinctly, these functions connect deferred-using code with this 'fake blocking' style in both directions: L{waitForDeferred} converts from a L{Deferred} to the 'blocking' style, and L{deferredGenerator} converts from the 'blocking' style to a L{Deferred}.
def deferredGenerator( f: Callable[..., _DeferableGenerator] ) -> Callable[..., Deferred[object]]: """ L{deferredGenerator} and L{waitForDeferred} help you write L{Deferred}-using code that looks like a regular sequential function. Consider the use of L{inlineCallbacks} instead, which can accomplish the same thing in a more concise manner. There are two important functions involved: L{waitForDeferred}, and L{deferredGenerator}. They are used together, like this:: @deferredGenerator def thingummy(): thing = waitForDeferred(makeSomeRequestResultingInDeferred()) yield thing thing = thing.getResult() print(thing) #the result! hoorj! L{waitForDeferred} returns something that you should immediately yield; when your generator is resumed, calling C{thing.getResult()} will either give you the result of the L{Deferred} if it was a success, or raise an exception if it was a failure. Calling C{getResult} is B{absolutely mandatory}. If you do not call it, I{your program will not work}. L{deferredGenerator} takes one of these waitForDeferred-using generator functions and converts it into a function that returns a L{Deferred}. The result of the L{Deferred} will be the last value that your generator yielded unless the last value is a L{waitForDeferred} instance, in which case the result will be L{None}. If the function raises an unhandled exception, the L{Deferred} will errback instead. Remember that C{return result} won't work; use C{yield result; return} in place of that. Note that not yielding anything from your generator will make the L{Deferred} result in L{None}. Yielding a L{Deferred} from your generator is also an error condition; always yield C{waitForDeferred(d)} instead. The L{Deferred} returned from your deferred generator may also errback if your generator raised an exception. For example:: @deferredGenerator def thingummy(): thing = waitForDeferred(makeSomeRequestResultingInDeferred()) yield thing thing = thing.getResult() if thing == 'I love Twisted': # will become the result of the Deferred yield 'TWISTED IS GREAT!' return else: # will trigger an errback raise Exception('DESTROY ALL LIFE') Put succinctly, these functions connect deferred-using code with this 'fake blocking' style in both directions: L{waitForDeferred} converts from a L{Deferred} to the 'blocking' style, and L{deferredGenerator} converts from the 'blocking' style to a L{Deferred}. """ @wraps(f) def unwindGenerator(*args: object, **kwargs: object) -> Deferred[object]: return _deferGenerator(f(*args, **kwargs), Deferred()) return unwindGenerator
Return val from a L{inlineCallbacks} generator. Note: this is currently implemented by raising an exception derived from L{BaseException}. You might want to change any 'except:' clauses to an 'except Exception:' clause so as not to catch this exception. Also: while this function currently will work when called from within arbitrary functions called from within the generator, do not rely upon this behavior.
def returnValue(val: object) -> NoReturn: """ Return val from a L{inlineCallbacks} generator. Note: this is currently implemented by raising an exception derived from L{BaseException}. You might want to change any 'except:' clauses to an 'except Exception:' clause so as not to catch this exception. Also: while this function currently will work when called from within arbitrary functions called from within the generator, do not rely upon this behavior. """ raise _DefGen_Return(val)
Helper for L{_inlineCallbacks} to handle a nested L{Deferred} firing. @param r: The result of the L{Deferred} @param waiting: Whether the L{_inlineCallbacks} was waiting, and the result. @param gen: a generator object returned by calling a function or method decorated with C{@}L{inlineCallbacks} @param status: a L{_CancellationStatus} tracking the current status of C{gen} @param context: the contextvars context to run `gen` in
def _gotResultInlineCallbacks( r: object, waiting: List[Any], gen: Union[ Generator[Deferred[Any], Any, _T], Coroutine[Deferred[Any], Any, _T], ], status: _CancellationStatus[_T], context: _Context, ) -> None: """ Helper for L{_inlineCallbacks} to handle a nested L{Deferred} firing. @param r: The result of the L{Deferred} @param waiting: Whether the L{_inlineCallbacks} was waiting, and the result. @param gen: a generator object returned by calling a function or method decorated with C{@}L{inlineCallbacks} @param status: a L{_CancellationStatus} tracking the current status of C{gen} @param context: the contextvars context to run `gen` in """ if waiting[0]: waiting[0] = False waiting[1] = r else: _inlineCallbacks(r, gen, status, context)
Carry out the work of L{inlineCallbacks}. Iterate the generator produced by an C{@}L{inlineCallbacks}-decorated function, C{gen}, C{send()}ing it the results of each value C{yield}ed by that generator, until a L{Deferred} is yielded, at which point a callback is added to that L{Deferred} to call this function again. @param result: The last result seen by this generator. Note that this is never a L{Deferred} - by the time this function is invoked, the L{Deferred} has been called back and this will be a particular result at a point in its callback chain. @param gen: a generator object returned by calling a function or method decorated with C{@}L{inlineCallbacks} @param status: a L{_CancellationStatus} tracking the current status of C{gen} @param context: the contextvars context to run `gen` in
def _inlineCallbacks( result: object, gen: Union[ Generator[Deferred[Any], Any, _T], Coroutine[Deferred[Any], Any, _T], ], status: _CancellationStatus[_T], context: _Context, ) -> None: """ Carry out the work of L{inlineCallbacks}. Iterate the generator produced by an C{@}L{inlineCallbacks}-decorated function, C{gen}, C{send()}ing it the results of each value C{yield}ed by that generator, until a L{Deferred} is yielded, at which point a callback is added to that L{Deferred} to call this function again. @param result: The last result seen by this generator. Note that this is never a L{Deferred} - by the time this function is invoked, the L{Deferred} has been called back and this will be a particular result at a point in its callback chain. @param gen: a generator object returned by calling a function or method decorated with C{@}L{inlineCallbacks} @param status: a L{_CancellationStatus} tracking the current status of C{gen} @param context: the contextvars context to run `gen` in """ # This function is complicated by the need to prevent unbounded recursion # arising from repeatedly yielding immediately ready deferreds. This while # loop and the waiting variable solve that by manually unfolding the # recursion. # waiting for result? # result waiting: List[Any] = [True, None] stopIteration: bool = False callbackValue: Any = None while 1: try: # Send the last result back as the result of the yield expression. isFailure = isinstance(result, Failure) if isFailure: result = context.run( cast(Failure, result).throwExceptionIntoGenerator, gen ) else: result = context.run(gen.send, result) except StopIteration as e: # fell off the end, or "return" statement stopIteration = True callbackValue = getattr(e, "value", None) except _DefGen_Return as e: # returnValue() was called; time to give a result to the original # Deferred. First though, let's try to identify the potentially # confusing situation which results when returnValue() is # accidentally invoked from a different function, one that wasn't # decorated with @inlineCallbacks. # The traceback starts in this frame (the one for # _inlineCallbacks); the next one down should be the application # code. excInfo = exc_info() assert excInfo is not None traceback = excInfo[2] assert traceback is not None appCodeTrace = traceback.tb_next assert appCodeTrace is not None if _oldPypyStack: # PyPy versions through 7.3.13 add an extra frame; 7.3.14 fixed # this discrepancy with CPython. This code can be removed once # we no longer need to support PyPy 7.3.13 or older. appCodeTrace = appCodeTrace.tb_next assert appCodeTrace is not None if isFailure: # If we invoked this generator frame by throwing an exception # into it, then throwExceptionIntoGenerator will consume an # additional stack frame itself, so we need to skip that too. appCodeTrace = appCodeTrace.tb_next assert appCodeTrace is not None # Now that we've identified the frame being exited by the # exception, let's figure out if returnValue was called from it # directly. returnValue itself consumes a stack frame, so the # application code will have a tb_next, but it will *not* have a # second tb_next. assert appCodeTrace.tb_next is not None if appCodeTrace.tb_next.tb_next: # If returnValue was invoked non-local to the frame which it is # exiting, identify the frame that ultimately invoked # returnValue so that we can warn the user, as this behavior is # confusing. ultimateTrace = appCodeTrace assert ultimateTrace is not None assert ultimateTrace.tb_next is not None while ultimateTrace.tb_next.tb_next: ultimateTrace = ultimateTrace.tb_next assert ultimateTrace is not None filename = ultimateTrace.tb_frame.f_code.co_filename lineno = ultimateTrace.tb_lineno assert ultimateTrace.tb_frame is not None assert appCodeTrace.tb_frame is not None warnings.warn_explicit( "returnValue() in %r causing %r to exit: " "returnValue should only be invoked by functions decorated " "with inlineCallbacks" % ( ultimateTrace.tb_frame.f_code.co_name, appCodeTrace.tb_frame.f_code.co_name, ), DeprecationWarning, filename, lineno, ) stopIteration = True callbackValue = e.value except BaseException: status.deferred.errback() return if stopIteration: # Call the callback outside of the exception handler to avoid inappropriate/confusing # "During handling of the above exception, another exception occurred:" if the callback # itself throws an exception. status.deferred.callback(callbackValue) return if isinstance(result, Deferred): # a deferred was yielded, get the result. result.addBoth(_gotResultInlineCallbacks, waiting, gen, status, context) if waiting[0]: # Haven't called back yet, set flag so that we get reinvoked # and return from the loop waiting[0] = False status.waitingOn = result return result = waiting[1] # Reset waiting to initial values for next loop. gotResult uses # waiting, but this isn't a problem because gotResult is only # executed once, and if it hasn't been executed yet, the return # branch above would have been taken. waiting[0] = True waiting[1] = None
Helper for L{_cancellableInlineCallbacks} to add L{_handleCancelInlineCallbacks} as the first errback. @param it: The L{Deferred} to add the errback to. @param status: a L{_CancellationStatus} tracking the current status of C{gen}
def _addCancelCallbackToDeferred( it: Deferred[_T], status: _CancellationStatus[_T] ) -> None: """ Helper for L{_cancellableInlineCallbacks} to add L{_handleCancelInlineCallbacks} as the first errback. @param it: The L{Deferred} to add the errback to. @param status: a L{_CancellationStatus} tracking the current status of C{gen} """ it.callbacks, tmp = [], it.callbacks it = it.addErrback(_handleCancelInlineCallbacks, status) it.callbacks.extend(tmp) it.errback(_InternalInlineCallbacksCancelledError())
Propagate the cancellation of an C{@}L{inlineCallbacks} to the L{Deferred} it is waiting on. @param result: An L{_InternalInlineCallbacksCancelledError} from C{cancel()}. @param status: a L{_CancellationStatus} tracking the current status of C{gen} @return: A new L{Deferred} that the C{@}L{inlineCallbacks} generator can callback or errback through.
def _handleCancelInlineCallbacks( result: Failure, status: _CancellationStatus[_T], / ) -> Deferred[_T]: """ Propagate the cancellation of an C{@}L{inlineCallbacks} to the L{Deferred} it is waiting on. @param result: An L{_InternalInlineCallbacksCancelledError} from C{cancel()}. @param status: a L{_CancellationStatus} tracking the current status of C{gen} @return: A new L{Deferred} that the C{@}L{inlineCallbacks} generator can callback or errback through. """ result.trap(_InternalInlineCallbacksCancelledError) status.deferred = Deferred(lambda d: _addCancelCallbackToDeferred(d, status)) # We would only end up here if the inlineCallback is waiting on # another Deferred. It needs to be cancelled. awaited = status.waitingOn assert awaited is not None awaited.cancel() return status.deferred
Make an C{@}L{inlineCallbacks} cancellable. @param gen: a generator object returned by calling a function or method decorated with C{@}L{inlineCallbacks} @return: L{Deferred} for the C{@}L{inlineCallbacks} that is cancellable.
def _cancellableInlineCallbacks( gen: Union[ Generator[Deferred[Any], object, _T], Coroutine[Deferred[Any], object, _T], ] ) -> Deferred[_T]: """ Make an C{@}L{inlineCallbacks} cancellable. @param gen: a generator object returned by calling a function or method decorated with C{@}L{inlineCallbacks} @return: L{Deferred} for the C{@}L{inlineCallbacks} that is cancellable. """ deferred: Deferred[_T] = Deferred(lambda d: _addCancelCallbackToDeferred(d, status)) status = _CancellationStatus(deferred) _inlineCallbacks(None, gen, status, _copy_context()) return deferred
L{inlineCallbacks} helps you write L{Deferred}-using code that looks like a regular sequential function. For example:: @inlineCallbacks def thingummy(): thing = yield makeSomeRequestResultingInDeferred() print(thing) # the result! hoorj! When you call anything that results in a L{Deferred}, you can simply yield it; your generator will automatically be resumed when the Deferred's result is available. The generator will be sent the result of the L{Deferred} with the 'send' method on generators, or if the result was a failure, 'throw'. Things that are not L{Deferred}s may also be yielded, and your generator will be resumed with the same object sent back. This means C{yield} performs an operation roughly equivalent to L{maybeDeferred}. Your inlineCallbacks-enabled generator will return a L{Deferred} object, which will result in the return value of the generator (or will fail with a failure object if your generator raises an unhandled exception). Note that you can't use C{return result} to return a value; use C{returnValue(result)} instead. Falling off the end of the generator, or simply using C{return} will cause the L{Deferred} to have a result of L{None}. Be aware that L{returnValue} will not accept a L{Deferred} as a parameter. If you believe the thing you'd like to return could be a L{Deferred}, do this:: result = yield result returnValue(result) The L{Deferred} returned from your deferred generator may errback if your generator raised an exception:: @inlineCallbacks def thingummy(): thing = yield makeSomeRequestResultingInDeferred() if thing == 'I love Twisted': # will become the result of the Deferred returnValue('TWISTED IS GREAT!') else: # will trigger an errback raise Exception('DESTROY ALL LIFE') It is possible to use the C{return} statement instead of L{returnValue}:: @inlineCallbacks def loadData(url): response = yield makeRequest(url) return json.loads(response) You can cancel the L{Deferred} returned from your L{inlineCallbacks} generator before it is fired by your generator completing (either by reaching its end, a C{return} statement, or by calling L{returnValue}). A C{CancelledError} will be raised from the C{yield}ed L{Deferred} that has been cancelled if that C{Deferred} does not otherwise suppress it.
def inlineCallbacks( f: Callable[_P, Generator[Deferred[Any], Any, _T]] ) -> Callable[_P, Deferred[_T]]: """ L{inlineCallbacks} helps you write L{Deferred}-using code that looks like a regular sequential function. For example:: @inlineCallbacks def thingummy(): thing = yield makeSomeRequestResultingInDeferred() print(thing) # the result! hoorj! When you call anything that results in a L{Deferred}, you can simply yield it; your generator will automatically be resumed when the Deferred's result is available. The generator will be sent the result of the L{Deferred} with the 'send' method on generators, or if the result was a failure, 'throw'. Things that are not L{Deferred}s may also be yielded, and your generator will be resumed with the same object sent back. This means C{yield} performs an operation roughly equivalent to L{maybeDeferred}. Your inlineCallbacks-enabled generator will return a L{Deferred} object, which will result in the return value of the generator (or will fail with a failure object if your generator raises an unhandled exception). Note that you can't use C{return result} to return a value; use C{returnValue(result)} instead. Falling off the end of the generator, or simply using C{return} will cause the L{Deferred} to have a result of L{None}. Be aware that L{returnValue} will not accept a L{Deferred} as a parameter. If you believe the thing you'd like to return could be a L{Deferred}, do this:: result = yield result returnValue(result) The L{Deferred} returned from your deferred generator may errback if your generator raised an exception:: @inlineCallbacks def thingummy(): thing = yield makeSomeRequestResultingInDeferred() if thing == 'I love Twisted': # will become the result of the Deferred returnValue('TWISTED IS GREAT!') else: # will trigger an errback raise Exception('DESTROY ALL LIFE') It is possible to use the C{return} statement instead of L{returnValue}:: @inlineCallbacks def loadData(url): response = yield makeRequest(url) return json.loads(response) You can cancel the L{Deferred} returned from your L{inlineCallbacks} generator before it is fired by your generator completing (either by reaching its end, a C{return} statement, or by calling L{returnValue}). A C{CancelledError} will be raised from the C{yield}ed L{Deferred} that has been cancelled if that C{Deferred} does not otherwise suppress it. """ @wraps(f) def unwindGenerator(*args: _P.args, **kwargs: _P.kwargs) -> Deferred[_T]: try: gen = f(*args, **kwargs) except _DefGen_Return: raise TypeError( "inlineCallbacks requires %r to produce a generator; instead" "caught returnValue being used in a non-generator" % (f,) ) if not isinstance(gen, GeneratorType): raise TypeError( "inlineCallbacks requires %r to produce a generator; " "instead got %r" % (f, gen) ) return _cancellableInlineCallbacks(gen) return unwindGenerator
Internal parser function for L{_parseServer} to convert the string arguments for a TCP(IPv4) stream endpoint into the structured arguments. @param factory: the protocol factory being parsed, or L{None}. (This was a leftover argument from when this code was in C{strports}, and is now mostly None and unused.) @type factory: L{IProtocolFactory} or L{None} @param port: the integer port number to bind @type port: C{str} @param interface: the interface IP to listen on @param backlog: the length of the listen queue @type backlog: C{str} @return: a 2-tuple of (args, kwargs), describing the parameters to L{IReactorTCP.listenTCP} (or, modulo argument 2, the factory, arguments to L{TCP4ServerEndpoint}.
def _parseTCP(factory, port, interface="", backlog=50): """ Internal parser function for L{_parseServer} to convert the string arguments for a TCP(IPv4) stream endpoint into the structured arguments. @param factory: the protocol factory being parsed, or L{None}. (This was a leftover argument from when this code was in C{strports}, and is now mostly None and unused.) @type factory: L{IProtocolFactory} or L{None} @param port: the integer port number to bind @type port: C{str} @param interface: the interface IP to listen on @param backlog: the length of the listen queue @type backlog: C{str} @return: a 2-tuple of (args, kwargs), describing the parameters to L{IReactorTCP.listenTCP} (or, modulo argument 2, the factory, arguments to L{TCP4ServerEndpoint}. """ return (int(port), factory), {"interface": interface, "backlog": int(backlog)}
Internal parser function for L{_parseServer} to convert the string arguments for a UNIX (AF_UNIX/SOCK_STREAM) stream endpoint into the structured arguments. @param factory: the protocol factory being parsed, or L{None}. (This was a leftover argument from when this code was in C{strports}, and is now mostly None and unused.) @type factory: L{IProtocolFactory} or L{None} @param address: the pathname of the unix socket @type address: C{str} @param backlog: the length of the listen queue @type backlog: C{str} @param lockfile: A string '0' or '1', mapping to True and False respectively. See the C{wantPID} argument to C{listenUNIX} @return: a 2-tuple of (args, kwargs), describing the parameters to L{twisted.internet.interfaces.IReactorUNIX.listenUNIX} (or, modulo argument 2, the factory, arguments to L{UNIXServerEndpoint}.
def _parseUNIX(factory, address, mode="666", backlog=50, lockfile=True): """ Internal parser function for L{_parseServer} to convert the string arguments for a UNIX (AF_UNIX/SOCK_STREAM) stream endpoint into the structured arguments. @param factory: the protocol factory being parsed, or L{None}. (This was a leftover argument from when this code was in C{strports}, and is now mostly None and unused.) @type factory: L{IProtocolFactory} or L{None} @param address: the pathname of the unix socket @type address: C{str} @param backlog: the length of the listen queue @type backlog: C{str} @param lockfile: A string '0' or '1', mapping to True and False respectively. See the C{wantPID} argument to C{listenUNIX} @return: a 2-tuple of (args, kwargs), describing the parameters to L{twisted.internet.interfaces.IReactorUNIX.listenUNIX} (or, modulo argument 2, the factory, arguments to L{UNIXServerEndpoint}. """ return ( (address, factory), {"mode": int(mode, 8), "backlog": int(backlog), "wantPID": bool(int(lockfile))}, )
Internal parser function for L{_parseServer} to convert the string arguments for an SSL (over TCP/IPv4) stream endpoint into the structured arguments. @param factory: the protocol factory being parsed, or L{None}. (This was a leftover argument from when this code was in C{strports}, and is now mostly None and unused.) @type factory: L{IProtocolFactory} or L{None} @param port: the integer port number to bind @type port: C{str} @param interface: the interface IP to listen on @param backlog: the length of the listen queue @type backlog: C{str} @param privateKey: The file name of a PEM format private key file. @type privateKey: C{str} @param certKey: The file name of a PEM format certificate file. @type certKey: C{str} @param sslmethod: The string name of an SSL method, based on the name of a constant in C{OpenSSL.SSL}. @type sslmethod: C{str} @param extraCertChain: The path of a file containing one or more certificates in PEM format that establish the chain from a root CA to the CA that signed your C{certKey}. @type extraCertChain: L{str} @param dhParameters: The file name of a file containing parameters that are required for Diffie-Hellman key exchange. If this is not specified, the forward secret C{DHE} ciphers aren't available for servers. @type dhParameters: L{str} @return: a 2-tuple of (args, kwargs), describing the parameters to L{IReactorSSL.listenSSL} (or, modulo argument 2, the factory, arguments to L{SSL4ServerEndpoint}.
def _parseSSL( factory, port, privateKey="server.pem", certKey=None, sslmethod=None, interface="", backlog=50, extraCertChain=None, dhParameters=None, ): """ Internal parser function for L{_parseServer} to convert the string arguments for an SSL (over TCP/IPv4) stream endpoint into the structured arguments. @param factory: the protocol factory being parsed, or L{None}. (This was a leftover argument from when this code was in C{strports}, and is now mostly None and unused.) @type factory: L{IProtocolFactory} or L{None} @param port: the integer port number to bind @type port: C{str} @param interface: the interface IP to listen on @param backlog: the length of the listen queue @type backlog: C{str} @param privateKey: The file name of a PEM format private key file. @type privateKey: C{str} @param certKey: The file name of a PEM format certificate file. @type certKey: C{str} @param sslmethod: The string name of an SSL method, based on the name of a constant in C{OpenSSL.SSL}. @type sslmethod: C{str} @param extraCertChain: The path of a file containing one or more certificates in PEM format that establish the chain from a root CA to the CA that signed your C{certKey}. @type extraCertChain: L{str} @param dhParameters: The file name of a file containing parameters that are required for Diffie-Hellman key exchange. If this is not specified, the forward secret C{DHE} ciphers aren't available for servers. @type dhParameters: L{str} @return: a 2-tuple of (args, kwargs), describing the parameters to L{IReactorSSL.listenSSL} (or, modulo argument 2, the factory, arguments to L{SSL4ServerEndpoint}. """ from twisted.internet import ssl if certKey is None: certKey = privateKey kw = {} if sslmethod is not None: kw["method"] = getattr(ssl.SSL, sslmethod) certPEM = FilePath(certKey).getContent() keyPEM = FilePath(privateKey).getContent() privateCertificate = ssl.PrivateCertificate.loadPEM(certPEM + b"\n" + keyPEM) if extraCertChain is not None: matches = re.findall( r"(-----BEGIN CERTIFICATE-----\n.+?\n-----END CERTIFICATE-----)", nativeString(FilePath(extraCertChain).getContent()), flags=re.DOTALL, ) chainCertificates = [ ssl.Certificate.loadPEM(chainCertPEM).original for chainCertPEM in matches ] if not chainCertificates: raise ValueError( "Specified chain file '%s' doesn't contain any valid " "certificates in PEM format." % (extraCertChain,) ) else: chainCertificates = None if dhParameters is not None: dhParameters = ssl.DiffieHellmanParameters.fromFile( FilePath(dhParameters), ) cf = ssl.CertificateOptions( privateKey=privateCertificate.privateKey.original, certificate=privateCertificate.original, extraCertChain=chainCertificates, dhParameters=dhParameters, **kw, ) return ((int(port), factory, cf), {"interface": interface, "backlog": int(backlog)})
Tokenize a strports string and yield each token. @param description: a string as described by L{serverFromString} or L{clientFromString}. @type description: L{str} or L{bytes} @return: an iterable of 2-tuples of (C{_OP} or C{_STRING}, string). Tuples starting with C{_OP} will contain a second element of either ':' (i.e. 'next parameter') or '=' (i.e. 'assign parameter value'). For example, the string 'hello:greeting=world' would result in a generator yielding these values:: _STRING, 'hello' _OP, ':' _STRING, 'greet=ing' _OP, '=' _STRING, 'world'
def _tokenize(description): """ Tokenize a strports string and yield each token. @param description: a string as described by L{serverFromString} or L{clientFromString}. @type description: L{str} or L{bytes} @return: an iterable of 2-tuples of (C{_OP} or C{_STRING}, string). Tuples starting with C{_OP} will contain a second element of either ':' (i.e. 'next parameter') or '=' (i.e. 'assign parameter value'). For example, the string 'hello:greeting=world' would result in a generator yielding these values:: _STRING, 'hello' _OP, ':' _STRING, 'greet=ing' _OP, '=' _STRING, 'world' """ empty = _matchingString("", description) colon = _matchingString(":", description) equals = _matchingString("=", description) backslash = _matchingString("\x5c", description) current = empty ops = colon + equals nextOps = {colon: colon + equals, equals: colon} iterdesc = iter(iterbytes(description)) for n in iterdesc: if n in iterbytes(ops): yield _STRING, current yield _OP, n current = empty ops = nextOps[n] elif n == backslash: current += next(iterdesc) else: current += n yield _STRING, current
Convert a description string into a list of positional and keyword parameters, using logic vaguely like what Python does. @param description: a string as described by L{serverFromString} or L{clientFromString}. @return: a 2-tuple of C{(args, kwargs)}, where 'args' is a list of all ':'-separated C{str}s not containing an '=' and 'kwargs' is a map of all C{str}s which do contain an '='. For example, the result of C{_parse('a:b:d=1:c')} would be C{(['a', 'b', 'c'], {'d': '1'})}.
def _parse(description): """ Convert a description string into a list of positional and keyword parameters, using logic vaguely like what Python does. @param description: a string as described by L{serverFromString} or L{clientFromString}. @return: a 2-tuple of C{(args, kwargs)}, where 'args' is a list of all ':'-separated C{str}s not containing an '=' and 'kwargs' is a map of all C{str}s which do contain an '='. For example, the result of C{_parse('a:b:d=1:c')} would be C{(['a', 'b', 'c'], {'d': '1'})}. """ args, kw = [], {} colon = _matchingString(":", description) def add(sofar): if len(sofar) == 1: args.append(sofar[0]) else: kw[nativeString(sofar[0])] = sofar[1] sofar = () for type, value in _tokenize(description): if type is _STRING: sofar += (value,) elif value == colon: add(sofar) sofar = () add(sofar) return args, kw
Parse a strports description into a 2-tuple of arguments and keyword values. @param description: A description in the format explained by L{serverFromString}. @type description: C{str} @param factory: A 'factory' argument; this is left-over from twisted.application.strports, it's not really used. @type factory: L{IProtocolFactory} or L{None} @return: a 3-tuple of (plugin or name, arguments, keyword arguments)
def _parseServer(description, factory): """ Parse a strports description into a 2-tuple of arguments and keyword values. @param description: A description in the format explained by L{serverFromString}. @type description: C{str} @param factory: A 'factory' argument; this is left-over from twisted.application.strports, it's not really used. @type factory: L{IProtocolFactory} or L{None} @return: a 3-tuple of (plugin or name, arguments, keyword arguments) """ args, kw = _parse(description) endpointType = args[0] parser = _serverParsers.get(endpointType) if parser is None: # If the required parser is not found in _server, check if # a plugin exists for the endpointType plugin = _matchPluginToPrefix( getPlugins(IStreamServerEndpointStringParser), endpointType ) return (plugin, args[1:], kw) return (endpointType.upper(),) + parser(factory, *args[1:], **kw)
Match plugin to prefix.
def _matchPluginToPrefix(plugins, endpointType): """ Match plugin to prefix. """ endpointType = endpointType.lower() for plugin in plugins: if _matchingString(plugin.prefix.lower(), endpointType) == endpointType: return plugin raise ValueError(f"Unknown endpoint type: '{endpointType}'")
Construct a stream server endpoint from an endpoint description string. The format for server endpoint descriptions is a simple byte string. It is a prefix naming the type of endpoint, then a colon, then the arguments for that endpoint. For example, you can call it like this to create an endpoint that will listen on TCP port 80:: serverFromString(reactor, "tcp:80") Additional arguments may be specified as keywords, separated with colons. For example, you can specify the interface for a TCP server endpoint to bind to like this:: serverFromString(reactor, "tcp:80:interface=127.0.0.1") SSL server endpoints may be specified with the 'ssl' prefix, and the private key and certificate files may be specified by the C{privateKey} and C{certKey} arguments:: serverFromString( reactor, "ssl:443:privateKey=key.pem:certKey=crt.pem") If a private key file name (C{privateKey}) isn't provided, a "server.pem" file is assumed to exist which contains the private key. If the certificate file name (C{certKey}) isn't provided, the private key file is assumed to contain the certificate as well. You may escape colons in arguments with a backslash, which you will need to use if you want to specify a full pathname argument on Windows:: serverFromString(reactor, "ssl:443:privateKey=C\:/key.pem:certKey=C\:/cert.pem") finally, the 'unix' prefix may be used to specify a filesystem UNIX socket, optionally with a 'mode' argument to specify the mode of the socket file created by C{listen}:: serverFromString(reactor, "unix:/var/run/finger") serverFromString(reactor, "unix:/var/run/finger:mode=660") This function is also extensible; new endpoint types may be registered as L{IStreamServerEndpointStringParser} plugins. See that interface for more information. @param reactor: The server endpoint will be constructed with this reactor. @param description: The strports description to parse. @type description: L{str} @return: A new endpoint which can be used to listen with the parameters given by C{description}. @rtype: L{IStreamServerEndpoint<twisted.internet.interfaces.IStreamServerEndpoint>} @raise ValueError: when the 'description' string cannot be parsed. @since: 10.2
def serverFromString(reactor, description): """ Construct a stream server endpoint from an endpoint description string. The format for server endpoint descriptions is a simple byte string. It is a prefix naming the type of endpoint, then a colon, then the arguments for that endpoint. For example, you can call it like this to create an endpoint that will listen on TCP port 80:: serverFromString(reactor, "tcp:80") Additional arguments may be specified as keywords, separated with colons. For example, you can specify the interface for a TCP server endpoint to bind to like this:: serverFromString(reactor, "tcp:80:interface=127.0.0.1") SSL server endpoints may be specified with the 'ssl' prefix, and the private key and certificate files may be specified by the C{privateKey} and C{certKey} arguments:: serverFromString( reactor, "ssl:443:privateKey=key.pem:certKey=crt.pem") If a private key file name (C{privateKey}) isn't provided, a "server.pem" file is assumed to exist which contains the private key. If the certificate file name (C{certKey}) isn't provided, the private key file is assumed to contain the certificate as well. You may escape colons in arguments with a backslash, which you will need to use if you want to specify a full pathname argument on Windows:: serverFromString(reactor, "ssl:443:privateKey=C\\:/key.pem:certKey=C\\:/cert.pem") finally, the 'unix' prefix may be used to specify a filesystem UNIX socket, optionally with a 'mode' argument to specify the mode of the socket file created by C{listen}:: serverFromString(reactor, "unix:/var/run/finger") serverFromString(reactor, "unix:/var/run/finger:mode=660") This function is also extensible; new endpoint types may be registered as L{IStreamServerEndpointStringParser} plugins. See that interface for more information. @param reactor: The server endpoint will be constructed with this reactor. @param description: The strports description to parse. @type description: L{str} @return: A new endpoint which can be used to listen with the parameters given by C{description}. @rtype: L{IStreamServerEndpoint<twisted.internet.interfaces.IStreamServerEndpoint>} @raise ValueError: when the 'description' string cannot be parsed. @since: 10.2 """ nameOrPlugin, args, kw = _parseServer(description, None) if type(nameOrPlugin) is not str: plugin = nameOrPlugin return plugin.parseStreamServer(reactor, *args, **kw) else: name = nameOrPlugin # Chop out the factory. args = args[:1] + args[2:] return _endpointServerFactories[name](reactor, *args, **kw)
Quote an argument to L{serverFromString} and L{clientFromString}. Since arguments are separated with colons and colons are escaped with backslashes, some care is necessary if, for example, you have a pathname, you may be tempted to interpolate into a string like this:: serverFromString(reactor, "ssl:443:privateKey=%s" % (myPathName,)) This may appear to work, but will have portability issues (Windows pathnames, for example). Usually you should just construct the appropriate endpoint type rather than interpolating strings, which in this case would be L{SSL4ServerEndpoint}. There are some use-cases where you may need to generate such a string, though; for example, a tool to manipulate a configuration file which has strports descriptions in it. To be correct in those cases, do this instead:: serverFromString(reactor, "ssl:443:privateKey=%s" % (quoteStringArgument(myPathName),)) @param argument: The part of the endpoint description string you want to pass through. @type argument: C{str} @return: The quoted argument. @rtype: C{str}
def quoteStringArgument(argument): """ Quote an argument to L{serverFromString} and L{clientFromString}. Since arguments are separated with colons and colons are escaped with backslashes, some care is necessary if, for example, you have a pathname, you may be tempted to interpolate into a string like this:: serverFromString(reactor, "ssl:443:privateKey=%s" % (myPathName,)) This may appear to work, but will have portability issues (Windows pathnames, for example). Usually you should just construct the appropriate endpoint type rather than interpolating strings, which in this case would be L{SSL4ServerEndpoint}. There are some use-cases where you may need to generate such a string, though; for example, a tool to manipulate a configuration file which has strports descriptions in it. To be correct in those cases, do this instead:: serverFromString(reactor, "ssl:443:privateKey=%s" % (quoteStringArgument(myPathName),)) @param argument: The part of the endpoint description string you want to pass through. @type argument: C{str} @return: The quoted argument. @rtype: C{str} """ backslash, colon = "\\:" for c in backslash, colon: argument = argument.replace(c, backslash + c) return argument
Perform any argument value coercion necessary for TCP client parameters. Valid positional arguments to this function are host and port. Valid keyword arguments to this function are all L{IReactorTCP.connectTCP} arguments. @return: The coerced values as a C{dict}.
def _parseClientTCP(*args, **kwargs): """ Perform any argument value coercion necessary for TCP client parameters. Valid positional arguments to this function are host and port. Valid keyword arguments to this function are all L{IReactorTCP.connectTCP} arguments. @return: The coerced values as a C{dict}. """ if len(args) == 2: kwargs["port"] = int(args[1]) kwargs["host"] = args[0] elif len(args) == 1: if "host" in kwargs: kwargs["port"] = int(args[0]) else: kwargs["host"] = args[0] try: kwargs["port"] = int(kwargs["port"]) except KeyError: pass try: kwargs["timeout"] = int(kwargs["timeout"]) except KeyError: pass try: kwargs["bindAddress"] = (kwargs["bindAddress"], 0) except KeyError: pass return kwargs
Load certificate-authority certificate objects in a given directory. @param directoryPath: a L{unicode} or L{bytes} pointing at a directory to load .pem files from, or L{None}. @return: an L{IOpenSSLTrustRoot} provider.
def _loadCAsFromDir(directoryPath): """ Load certificate-authority certificate objects in a given directory. @param directoryPath: a L{unicode} or L{bytes} pointing at a directory to load .pem files from, or L{None}. @return: an L{IOpenSSLTrustRoot} provider. """ caCerts = {} for child in directoryPath.children(): if not child.asTextMode().basename().split(".")[-1].lower() == "pem": continue try: data = child.getContent() except OSError: # Permission denied, corrupt disk, we don't care. continue try: theCert = Certificate.loadPEM(data) except SSLError: # Duplicate certificate, invalid certificate, etc. We don't care. pass else: caCerts[theCert.digest()] = theCert return trustRootFromCertificates(caCerts.values())
Parse a string referring to a directory full of certificate authorities into a trust root. @param pathName: path name @type pathName: L{unicode} or L{bytes} or L{None} @return: L{None} or L{IOpenSSLTrustRoot}
def _parseTrustRootPath(pathName): """ Parse a string referring to a directory full of certificate authorities into a trust root. @param pathName: path name @type pathName: L{unicode} or L{bytes} or L{None} @return: L{None} or L{IOpenSSLTrustRoot} """ if pathName is None: return None return _loadCAsFromDir(FilePath(pathName))
Parse a certificate path and key path, either or both of which might be L{None}, into a certificate object. @param certificatePath: the certificate path @type certificatePath: L{bytes} or L{unicode} or L{None} @param keyPath: the private key path @type keyPath: L{bytes} or L{unicode} or L{None} @return: a L{PrivateCertificate} or L{None}
def _privateCertFromPaths(certificatePath, keyPath): """ Parse a certificate path and key path, either or both of which might be L{None}, into a certificate object. @param certificatePath: the certificate path @type certificatePath: L{bytes} or L{unicode} or L{None} @param keyPath: the private key path @type keyPath: L{bytes} or L{unicode} or L{None} @return: a L{PrivateCertificate} or L{None} """ if certificatePath is None: return None certBytes = FilePath(certificatePath).getContent() if keyPath is None: return PrivateCertificate.loadPEM(certBytes) else: return PrivateCertificate.fromCertificateAndKeyPair( Certificate.loadPEM(certBytes), KeyPair.load(FilePath(keyPath).getContent(), 1), )
Parse common arguments for SSL endpoints, creating an L{CertificateOptions} instance. @param kwargs: A dict of keyword arguments to be parsed, potentially containing keys C{certKey}, C{privateKey}, C{caCertsDir}, and C{hostname}. See L{_parseClientSSL}. @type kwargs: L{dict} @return: The remaining arguments, including a new key C{sslContextFactory}.
def _parseClientSSLOptions(kwargs): """ Parse common arguments for SSL endpoints, creating an L{CertificateOptions} instance. @param kwargs: A dict of keyword arguments to be parsed, potentially containing keys C{certKey}, C{privateKey}, C{caCertsDir}, and C{hostname}. See L{_parseClientSSL}. @type kwargs: L{dict} @return: The remaining arguments, including a new key C{sslContextFactory}. """ hostname = kwargs.pop("hostname", None) clientCertificate = _privateCertFromPaths( kwargs.pop("certKey", None), kwargs.pop("privateKey", None) ) trustRoot = _parseTrustRootPath(kwargs.pop("caCertsDir", None)) if hostname is not None: configuration = optionsForClientTLS( _idnaText(hostname), trustRoot=trustRoot, clientCertificate=clientCertificate, ) else: # _really_ though, you should specify a hostname. if clientCertificate is not None: privateKeyOpenSSL = clientCertificate.privateKey.original certificateOpenSSL = clientCertificate.original else: privateKeyOpenSSL = None certificateOpenSSL = None configuration = CertificateOptions( trustRoot=trustRoot, privateKey=privateKeyOpenSSL, certificate=certificateOpenSSL, ) kwargs["sslContextFactory"] = configuration return kwargs
Perform any argument value coercion necessary for SSL client parameters. Valid keyword arguments to this function are all L{IReactorSSL.connectSSL} arguments except for C{contextFactory}. Instead, C{certKey} (the path name of the certificate file) C{privateKey} (the path name of the private key associated with the certificate) are accepted and used to construct a context factory. Valid positional arguments to this function are host and port. @keyword caCertsDir: The one parameter which is not part of L{IReactorSSL.connectSSL}'s signature, this is a path name used to construct a list of certificate authority certificates. The directory will be scanned for files ending in C{.pem}, all of which will be considered valid certificate authorities for this connection. @type caCertsDir: L{str} @keyword hostname: The hostname to use for validating the server's certificate. @type hostname: L{unicode} @return: The coerced values as a L{dict}.
def _parseClientSSL(*args, **kwargs): """ Perform any argument value coercion necessary for SSL client parameters. Valid keyword arguments to this function are all L{IReactorSSL.connectSSL} arguments except for C{contextFactory}. Instead, C{certKey} (the path name of the certificate file) C{privateKey} (the path name of the private key associated with the certificate) are accepted and used to construct a context factory. Valid positional arguments to this function are host and port. @keyword caCertsDir: The one parameter which is not part of L{IReactorSSL.connectSSL}'s signature, this is a path name used to construct a list of certificate authority certificates. The directory will be scanned for files ending in C{.pem}, all of which will be considered valid certificate authorities for this connection. @type caCertsDir: L{str} @keyword hostname: The hostname to use for validating the server's certificate. @type hostname: L{unicode} @return: The coerced values as a L{dict}. """ kwargs = _parseClientTCP(*args, **kwargs) return _parseClientSSLOptions(kwargs)
Perform any argument value coercion necessary for UNIX client parameters. Valid keyword arguments to this function are all L{IReactorUNIX.connectUNIX} keyword arguments except for C{checkPID}. Instead, C{lockfile} is accepted and has the same meaning. Also C{path} is used instead of C{address}. Valid positional arguments to this function are C{path}. @return: The coerced values as a C{dict}.
def _parseClientUNIX(*args, **kwargs): """ Perform any argument value coercion necessary for UNIX client parameters. Valid keyword arguments to this function are all L{IReactorUNIX.connectUNIX} keyword arguments except for C{checkPID}. Instead, C{lockfile} is accepted and has the same meaning. Also C{path} is used instead of C{address}. Valid positional arguments to this function are C{path}. @return: The coerced values as a C{dict}. """ if len(args) == 1: kwargs["path"] = args[0] try: kwargs["checkPID"] = bool(int(kwargs.pop("lockfile"))) except KeyError: pass try: kwargs["timeout"] = int(kwargs["timeout"]) except KeyError: pass return kwargs
Construct a client endpoint from a description string. Client description strings are much like server description strings, although they take all of their arguments as keywords, aside from host and port. You can create a TCP client endpoint with the 'host' and 'port' arguments, like so:: clientFromString(reactor, "tcp:host=www.example.com:port=80") or, without specifying host and port keywords:: clientFromString(reactor, "tcp:www.example.com:80") Or you can specify only one or the other, as in the following 2 examples:: clientFromString(reactor, "tcp:host=www.example.com:80") clientFromString(reactor, "tcp:www.example.com:port=80") or an SSL client endpoint with those arguments, plus the arguments used by the server SSL, for a client certificate:: clientFromString(reactor, "ssl:web.example.com:443:" "privateKey=foo.pem:certKey=foo.pem") to specify your certificate trust roots, you can identify a directory with PEM files in it with the C{caCertsDir} argument:: clientFromString(reactor, "ssl:host=web.example.com:port=443:" "caCertsDir=/etc/ssl/certs") Both TCP and SSL client endpoint description strings can include a 'bindAddress' keyword argument, whose value should be a local IPv4 address. This fixes the client socket to that IP address:: clientFromString(reactor, "tcp:www.example.com:80:" "bindAddress=192.0.2.100") NB: Fixed client ports are not currently supported in TCP or SSL client endpoints. The client socket will always use an ephemeral port assigned by the operating system You can create a UNIX client endpoint with the 'path' argument and optional 'lockfile' and 'timeout' arguments:: clientFromString( reactor, b"unix:path=/var/foo/bar:lockfile=1:timeout=9") or, with the path as a positional argument with or without optional arguments as in the following 2 examples:: clientFromString(reactor, "unix:/var/foo/bar") clientFromString(reactor, "unix:/var/foo/bar:lockfile=1:timeout=9") This function is also extensible; new endpoint types may be registered as L{IStreamClientEndpointStringParserWithReactor} plugins. See that interface for more information. @param reactor: The client endpoint will be constructed with this reactor. @param description: The strports description to parse. @type description: L{str} @return: A new endpoint which can be used to connect with the parameters given by C{description}. @rtype: L{IStreamClientEndpoint<twisted.internet.interfaces.IStreamClientEndpoint>} @since: 10.2
def clientFromString(reactor, description): """ Construct a client endpoint from a description string. Client description strings are much like server description strings, although they take all of their arguments as keywords, aside from host and port. You can create a TCP client endpoint with the 'host' and 'port' arguments, like so:: clientFromString(reactor, "tcp:host=www.example.com:port=80") or, without specifying host and port keywords:: clientFromString(reactor, "tcp:www.example.com:80") Or you can specify only one or the other, as in the following 2 examples:: clientFromString(reactor, "tcp:host=www.example.com:80") clientFromString(reactor, "tcp:www.example.com:port=80") or an SSL client endpoint with those arguments, plus the arguments used by the server SSL, for a client certificate:: clientFromString(reactor, "ssl:web.example.com:443:" "privateKey=foo.pem:certKey=foo.pem") to specify your certificate trust roots, you can identify a directory with PEM files in it with the C{caCertsDir} argument:: clientFromString(reactor, "ssl:host=web.example.com:port=443:" "caCertsDir=/etc/ssl/certs") Both TCP and SSL client endpoint description strings can include a 'bindAddress' keyword argument, whose value should be a local IPv4 address. This fixes the client socket to that IP address:: clientFromString(reactor, "tcp:www.example.com:80:" "bindAddress=192.0.2.100") NB: Fixed client ports are not currently supported in TCP or SSL client endpoints. The client socket will always use an ephemeral port assigned by the operating system You can create a UNIX client endpoint with the 'path' argument and optional 'lockfile' and 'timeout' arguments:: clientFromString( reactor, b"unix:path=/var/foo/bar:lockfile=1:timeout=9") or, with the path as a positional argument with or without optional arguments as in the following 2 examples:: clientFromString(reactor, "unix:/var/foo/bar") clientFromString(reactor, "unix:/var/foo/bar:lockfile=1:timeout=9") This function is also extensible; new endpoint types may be registered as L{IStreamClientEndpointStringParserWithReactor} plugins. See that interface for more information. @param reactor: The client endpoint will be constructed with this reactor. @param description: The strports description to parse. @type description: L{str} @return: A new endpoint which can be used to connect with the parameters given by C{description}. @rtype: L{IStreamClientEndpoint<twisted.internet.interfaces.IStreamClientEndpoint>} @since: 10.2 """ args, kwargs = _parse(description) aname = args.pop(0) name = aname.upper() if name not in _clientParsers: plugin = _matchPluginToPrefix( getPlugins(IStreamClientEndpointStringParserWithReactor), name ) return plugin.parseStreamClient(reactor, *args, **kwargs) kwargs = _clientParsers[name](*args, **kwargs) return _endpointClientFactories[name](reactor, **kwargs)
Connect a protocol instance to an endpoint. This allows using a client endpoint without having to create a factory. @param endpoint: A client endpoint to connect to. @param protocol: A protocol instance. @return: The result of calling C{connect} on the endpoint, i.e. a L{Deferred} that will fire with the protocol when connected, or an appropriate error. @since: 13.1
def connectProtocol(endpoint, protocol): """ Connect a protocol instance to an endpoint. This allows using a client endpoint without having to create a factory. @param endpoint: A client endpoint to connect to. @param protocol: A protocol instance. @return: The result of calling C{connect} on the endpoint, i.e. a L{Deferred} that will fire with the protocol when connected, or an appropriate error. @since: 13.1 """ class OneShotFactory(Factory): def buildProtocol(self, addr): return protocol return endpoint.connect(OneShotFactory())
Wrap an endpoint which upgrades to TLS as soon as the connection is established. @since: 16.0 @param connectionCreator: The TLS options to use when connecting; see L{twisted.internet.ssl.optionsForClientTLS} for how to construct this. @type connectionCreator: L{twisted.internet.interfaces.IOpenSSLClientConnectionCreator} @param wrappedEndpoint: The endpoint to wrap. @type wrappedEndpoint: An L{IStreamClientEndpoint} provider. @return: an endpoint that provides transport level encryption layered on top of C{wrappedEndpoint} @rtype: L{twisted.internet.interfaces.IStreamClientEndpoint}
def wrapClientTLS(connectionCreator, wrappedEndpoint): """ Wrap an endpoint which upgrades to TLS as soon as the connection is established. @since: 16.0 @param connectionCreator: The TLS options to use when connecting; see L{twisted.internet.ssl.optionsForClientTLS} for how to construct this. @type connectionCreator: L{twisted.internet.interfaces.IOpenSSLClientConnectionCreator} @param wrappedEndpoint: The endpoint to wrap. @type wrappedEndpoint: An L{IStreamClientEndpoint} provider. @return: an endpoint that provides transport level encryption layered on top of C{wrappedEndpoint} @rtype: L{twisted.internet.interfaces.IStreamClientEndpoint} """ if TLSMemoryBIOFactory is None: raise NotImplementedError( "OpenSSL not available. Try `pip install twisted[tls]`." ) return _WrapperEndpoint( wrappedEndpoint, lambda protocolFactory: TLSMemoryBIOFactory( connectionCreator, True, protocolFactory ), )
Internal method to construct an endpoint from string parameters. @param reactor: The reactor passed to L{clientFromString}. @param host: The hostname to connect to. @type host: L{bytes} or L{unicode} @param port: The port to connect to. @type port: L{bytes} or L{unicode} @param timeout: For each individual connection attempt, the number of seconds to wait before assuming the connection has failed. @type timeout: L{bytes} or L{unicode} @param bindAddress: The address to which to bind outgoing connections. @type bindAddress: L{bytes} or L{unicode} @param certificate: a string representing a filesystem path to a PEM-encoded certificate. @type certificate: L{bytes} or L{unicode} @param privateKey: a string representing a filesystem path to a PEM-encoded certificate. @type privateKey: L{bytes} or L{unicode} @param endpoint: an optional string endpoint description of an endpoint to wrap; if this is passed then C{host} is used only for certificate verification. @type endpoint: L{bytes} or L{unicode} @return: a client TLS endpoint @rtype: L{IStreamClientEndpoint}
def _parseClientTLS( reactor, host, port, timeout=b"30", bindAddress=None, certificate=None, privateKey=None, trustRoots=None, endpoint=None, **kwargs, ): """ Internal method to construct an endpoint from string parameters. @param reactor: The reactor passed to L{clientFromString}. @param host: The hostname to connect to. @type host: L{bytes} or L{unicode} @param port: The port to connect to. @type port: L{bytes} or L{unicode} @param timeout: For each individual connection attempt, the number of seconds to wait before assuming the connection has failed. @type timeout: L{bytes} or L{unicode} @param bindAddress: The address to which to bind outgoing connections. @type bindAddress: L{bytes} or L{unicode} @param certificate: a string representing a filesystem path to a PEM-encoded certificate. @type certificate: L{bytes} or L{unicode} @param privateKey: a string representing a filesystem path to a PEM-encoded certificate. @type privateKey: L{bytes} or L{unicode} @param endpoint: an optional string endpoint description of an endpoint to wrap; if this is passed then C{host} is used only for certificate verification. @type endpoint: L{bytes} or L{unicode} @return: a client TLS endpoint @rtype: L{IStreamClientEndpoint} """ if kwargs: raise TypeError("unrecognized keyword arguments present", list(kwargs.keys())) host = host if isinstance(host, str) else host.decode("utf-8") bindAddress = ( bindAddress if isinstance(bindAddress, str) or bindAddress is None else bindAddress.decode("utf-8") ) port = int(port) timeout = int(timeout) return wrapClientTLS( optionsForClientTLS( host, trustRoot=_parseTrustRootPath(trustRoots), clientCertificate=_privateCertFromPaths(certificate, privateKey), ), clientFromString(reactor, endpoint) if endpoint is not None else HostnameEndpoint(reactor, _idnaBytes(host), port, timeout, bindAddress), )
Install the epoll() reactor.
def install(): """ Install the epoll() reactor. """ p = EPollReactor() from twisted.internet.main import installReactor installReactor(p)