response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Parse a content-range header into (start, end, realLength). realLength might be None if real length is not known ('*').
def parseContentRange(header): """ Parse a content-range header into (start, end, realLength). realLength might be None if real length is not known ('*'). """ kind, other = header.strip().split() if kind.lower() != "bytes": raise ValueError("a range of type %r is not supported") startend, realLength = other.split("/") start, end = map(int, startend.split("-")) if realLength == "*": realLength = None else: realLength = int(realLength) return (start, end, realLength)
Get a writeable file-like object to which request content can be written.
def _getContentFile(length): """ Get a writeable file-like object to which request content can be written. """ if length is not None and length < 100000: return BytesIO() return tempfile.TemporaryFile()
Return a string like python repr, but always escaped as if surrounding quotes were double quotes. @param s: The string to escape. @type s: L{bytes} or L{str} @return: An escaped string. @rtype: L{str}
def _escape(s): """ Return a string like python repr, but always escaped as if surrounding quotes were double quotes. @param s: The string to escape. @type s: L{bytes} or L{str} @return: An escaped string. @rtype: L{str} """ if not isinstance(s, bytes): s = s.encode("ascii") r = repr(s) if not isinstance(r, str): r = r.decode("ascii") if r.startswith("b"): r = r[1:] if r.startswith("'"): return r[1:-1].replace('"', '\\"').replace("\\'", "'") return r[1:-1]
@return: A combined log formatted log line for the given request. @see: L{IAccessLogFormatter}
def combinedLogFormatter(timestamp, request): """ @return: A combined log formatted log line for the given request. @see: L{IAccessLogFormatter} """ clientAddr = request.getClientAddress() if isinstance( clientAddr, (address.IPv4Address, address.IPv6Address, _XForwardedForAddress) ): ip = clientAddr.host else: ip = b"-" referrer = _escape(request.getHeader(b"referer") or b"-") agent = _escape(request.getHeader(b"user-agent") or b"-") line = ( '"%(ip)s" - - %(timestamp)s "%(method)s %(uri)s %(protocol)s" ' '%(code)d %(length)s "%(referrer)s" "%(agent)s"' % dict( ip=_escape(ip), timestamp=timestamp, method=_escape(request.method), uri=_escape(request.uri), protocol=_escape(request.clientproto), code=request.code, length=request.sentLength or "-", referrer=referrer, agent=agent, ) ) return line
@return: A combined log formatted log line for the given request but use the value of the I{X-Forwarded-For} header as the value for the client IP address. @see: L{IAccessLogFormatter}
def proxiedLogFormatter(timestamp, request): """ @return: A combined log formatted log line for the given request but use the value of the I{X-Forwarded-For} header as the value for the client IP address. @see: L{IAccessLogFormatter} """ return combinedLogFormatter(timestamp, _XForwardedForRequest(request))
Returns an appropriately initialized _GenericHTTPChannelProtocol.
def _genericHTTPChannelProtocolFactory(self): """ Returns an appropriately initialized _GenericHTTPChannelProtocol. """ return _GenericHTTPChannelProtocol(HTTPChannel())
Replace linear whitespace (C{\n}, C{\r\n}, C{\r}) in a header key or value with a single space. @param headerComponent: The header key or value to sanitize. @return: The sanitized header key or value.
def _sanitizeLinearWhitespace(headerComponent: bytes) -> bytes: r""" Replace linear whitespace (C{\n}, C{\r\n}, C{\r}) in a header key or value with a single space. @param headerComponent: The header key or value to sanitize. @return: The sanitized header key or value. """ return b" ".join(headerComponent.splitlines())
Return a list of all child elements of C{iNode} with a name matching C{name}. Note that this implementation does not conform to the DOM Level 1 Core specification because it may return C{iNode}. @param iNode: An element at which to begin searching. If C{iNode} has a name matching C{name}, it will be included in the result. @param name: A C{str} giving the name of the elements to return. @return: A C{list} of direct or indirect child elements of C{iNode} with the name C{name}. This may include C{iNode}.
def getElementsByTagName(iNode, name): """ Return a list of all child elements of C{iNode} with a name matching C{name}. Note that this implementation does not conform to the DOM Level 1 Core specification because it may return C{iNode}. @param iNode: An element at which to begin searching. If C{iNode} has a name matching C{name}, it will be included in the result. @param name: A C{str} giving the name of the elements to return. @return: A C{list} of direct or indirect child elements of C{iNode} with the name C{name}. This may include C{iNode}. """ matches = [] matches_append = matches.append # faster lookup. don't do this at home slice = [iNode] while len(slice) > 0: c = slice.pop(0) if c.nodeName == name: matches_append(c) slice[:0] = c.childNodes return matches
Perform the exact opposite of 'escape'.
def unescape(text, chars=REV_HTML_ESCAPE_CHARS): """ Perform the exact opposite of 'escape'. """ for s, h in chars: text = text.replace(h, s) return text
Escape a few XML special chars with XML entities.
def escape(text, chars=HTML_ESCAPE_CHARS): """ Escape a few XML special chars with XML entities. """ for s, h in chars: text = text.replace(s, h) return text
Parse HTML or XML readable.
def parse(readable, *args, **kwargs): """ Parse HTML or XML readable. """ if not hasattr(readable, "read"): readable = open(readable, "rb") mdp = MicroDOMParser(*args, **kwargs) mdp.filename = getattr(readable, "name", "<xmlfile />") mdp.makeConnection(None) if hasattr(readable, "getvalue"): mdp.dataReceived(readable.getvalue()) else: r = readable.read(1024) while r: mdp.dataReceived(r) r = readable.read(1024) mdp.connectionLost(None) if not mdp.documents: raise ParseError(mdp.filename, 0, 0, "No top-level Nodes in document") if mdp.beExtremelyLenient: if len(mdp.documents) == 1: d = mdp.documents[0] if not isinstance(d, Element): el = Element("html") el.appendChild(d) d = el else: d = Element("html") for child in mdp.documents: d.appendChild(child) else: d = mdp.documents[0] doc = Document(d) doc.doctype = mdp._mddoctype return doc
Parse an XML readable object.
def parseXML(readable): """ Parse an XML readable object. """ return parse(readable, caseInsensitive=0, preserveCase=1)
Parse an XML readable object.
def parseXMLString(st): """ Parse an XML readable object. """ return parseString(st, caseInsensitive=0, preserveCase=1)
Build a resource that responds to all requests with a particular HTTP status code and an HTML body containing some descriptive text. This is useful for rendering simple error pages. The resource dynamically handles all paths below it. Use L{IResource.putChild()} to override a specific path. @param code: An integer HTTP status code which will be used for the response. @param brief: A short string which will be included in the response body as the page title. @param detail: A longer string which will be included in the response body. @returns: An L{IResource}
def errorPage(code: int, brief: str, detail: str) -> _ErrorPage: """ Build a resource that responds to all requests with a particular HTTP status code and an HTML body containing some descriptive text. This is useful for rendering simple error pages. The resource dynamically handles all paths below it. Use L{IResource.putChild()} to override a specific path. @param code: An integer HTTP status code which will be used for the response. @param brief: A short string which will be included in the response body as the page title. @param detail: A longer string which will be included in the response body. @returns: An L{IResource} """ return _ErrorPage(code, brief, detail)
Generate an L{IResource} with a 404 Not Found status code. @see: L{twisted.web.pages.errorPage} @param brief: A short string displayed as the page title. @param brief: A longer string displayed in the page body. @returns: An L{IResource}
def notFound( brief: str = "No Such Resource", message: str = "Sorry. No luck finding that resource.", ) -> IResource: """ Generate an L{IResource} with a 404 Not Found status code. @see: L{twisted.web.pages.errorPage} @param brief: A short string displayed as the page title. @param brief: A longer string displayed in the page body. @returns: An L{IResource} """ return _ErrorPage(http.NOT_FOUND, brief, message)
Generate an L{IResource} with a 403 Forbidden status code. @see: L{twisted.web.pages.errorPage} @param brief: A short string displayed as the page title. @param brief: A longer string displayed in the page body. @returns: An L{IResource}
def forbidden( brief: str = "Forbidden Resource", message: str = "Sorry, resource is forbidden." ) -> IResource: """ Generate an L{IResource} with a 403 Forbidden status code. @see: L{twisted.web.pages.errorPage} @param brief: A short string displayed as the page title. @param brief: A longer string displayed in the page body. @returns: An L{IResource} """ return _ErrorPage(http.FORBIDDEN, brief, message)
Traverse resource tree to find who will handle the request.
def getChildForRequest(resource, request): """ Traverse resource tree to find who will handle the request. """ while request.postpath and not resource.isLeaf: pathElement = request.postpath.pop(0) request.prepath.append(pathElement) resource = resource.getChildWithDefault(pathElement, request) return resource
Compute the allowed methods on a C{Resource} based on defined render_FOO methods. Used when raising C{UnsupportedMethod} but C{Resource} does not define C{allowedMethods} attribute.
def _computeAllowedMethods(resource): """ Compute the allowed methods on a C{Resource} based on defined render_FOO methods. Used when raising C{UnsupportedMethod} but C{Resource} does not define C{allowedMethods} attribute. """ allowedMethods = [] for name in prefixedMethodNames(resource.__class__, "render_"): # Potentially there should be an API for encode('ascii') in this # situation - an API for taking a Python native string (bytes on Python # 2, text on Python 3) and returning a socket-compatible string type. allowedMethods.append(name.encode("ascii")) return allowedMethods
I am not a very good aliaser. But I'm the best I can be. If I'm aliasing to a Resource that generates links, and it uses any parts of request.prepath to do so, the links will not be relative to the aliased path, but rather to the aliased-to path. That I can't alias static.File directory listings that nicely. However, I can still be useful, as many resources will play nice.
def alias(aliasPath, sourcePath): """ I am not a very good aliaser. But I'm the best I can be. If I'm aliasing to a Resource that generates links, and it uses any parts of request.prepath to do so, the links will not be relative to the aliased path, but rather to the aliased-to path. That I can't alias static.File directory listings that nicely. However, I can still be useful, as many resources will play nice. """ sourcePath = sourcePath.split("/") aliasPath = aliasPath.split("/") def rewriter(request): if request.postpath[: len(aliasPath)] == aliasPath: after = request.postpath[len(aliasPath) :] request.postpath = sourcePath + after request.path = "/" + "/".join(request.prepath + request.postpath) return rewriter
I am a normal py file which must define a 'resource' global, which should be an instance of (a subclass of) web.resource.Resource; it will be renderred.
def ResourceScript(path, registry): """ I am a normal py file which must define a 'resource' global, which should be an instance of (a subclass of) web.resource.Resource; it will be renderred. """ cs = CacheScanner(path, registry) glob = { "__file__": _coerceToFilesystemEncoding("", path), "resource": noRsrc, "registry": registry, "cache": cs.cache, "recache": cs.recache, } try: execfile(path, glob, glob) except AlreadyCached as ac: return ac.args[0] rsrc = glob["resource"] if cs.doCache and rsrc is not noRsrc: registry.cachePath(path, rsrc) return rsrc
Add a trailing slash to C{request}'s URI. Deprecated, do not use.
def addSlash(request): """ Add a trailing slash to C{request}'s URI. Deprecated, do not use. """ return _addSlash(request)
Add a trailing slash to C{request}'s URI. @param request: The incoming request to add the ending slash to. @type request: An object conforming to L{twisted.web.iweb.IRequest} @return: A URI with a trailing slash, with query and fragment preserved. @rtype: L{bytes}
def _addSlash(request): """ Add a trailing slash to C{request}'s URI. @param request: The incoming request to add the ending slash to. @type request: An object conforming to L{twisted.web.iweb.IRequest} @return: A URI with a trailing slash, with query and fragment preserved. @rtype: L{bytes} """ url = URL.fromText(request.uri.decode("ascii")) # Add an empty path segment at the end, so that it adds a trailing slash url = url.replace(path=list(url.path) + [""]) return url.asText().encode("ascii")
Produces a mapping of extensions (with leading dot) to MIME types. It does this by calling the C{init} function of the L{mimetypes} module. This will have the side effect of modifying the global MIME types cache in that module. Multiple file locations containing mime-types can be passed as a list. The files will be sourced in that order, overriding mime-types from the files sourced beforehand, but only if a new entry explicitly overrides the current entry. @param mimetype_locations: Optional. List of paths to C{mime.types} style files that should be used. @type mimetype_locations: iterable of paths or L{None} @param init: The init function to call. Defaults to the global C{init} function of the C{mimetypes} module. For internal use (testing) only. @type init: callable
def loadMimeTypes(mimetype_locations=None, init=mimetypes.init): """ Produces a mapping of extensions (with leading dot) to MIME types. It does this by calling the C{init} function of the L{mimetypes} module. This will have the side effect of modifying the global MIME types cache in that module. Multiple file locations containing mime-types can be passed as a list. The files will be sourced in that order, overriding mime-types from the files sourced beforehand, but only if a new entry explicitly overrides the current entry. @param mimetype_locations: Optional. List of paths to C{mime.types} style files that should be used. @type mimetype_locations: iterable of paths or L{None} @param init: The init function to call. Defaults to the global C{init} function of the C{mimetypes} module. For internal use (testing) only. @type init: callable """ init(mimetype_locations) mimetypes.types_map.update( { ".conf": "text/plain", ".diff": "text/plain", ".flac": "audio/x-flac", ".java": "text/plain", ".oz": "text/x-oz", ".swf": "application/x-shockwave-flash", ".wml": "text/vnd.wap.wml", ".xul": "application/vnd.mozilla.xul+xml", ".patch": "text/plain", } ) return mimetypes.types_map
Format the given file size in bytes to human readable format.
def formatFileSize(size): """ Format the given file size in bytes to human readable format. """ if size < 1024: return "%iB" % size elif size < (1024**2): return "%iK" % (size / 1024) elif size < (1024**3): return "%iM" % (size / (1024**2)) else: return "%iG" % (size / (1024**3))
Do nothing.
def nop(*args, **kw): "Do nothing."
Create and return a factory which will respond to I{distrib} requests against the given site. @type site: L{twisted.web.server.Site} @rtype: L{twisted.internet.protocol.Factory}
def makePersonalServerFactory(site): """ Create and return a factory which will respond to I{distrib} requests against the given site. @type site: L{twisted.web.server.Site} @rtype: L{twisted.internet.protocol.Factory} """ return pb.PBServerFactory(distrib.ResourcePublisher(site))
Decorator to cause the request to be passed as the first argument to the method. If an I{xmlrpc_} method is wrapped with C{withRequest}, the request object is passed as the first argument to that method. For example:: @withRequest def xmlrpc_echo(self, request, s): return s @since: 10.2
def withRequest(f): """ Decorator to cause the request to be passed as the first argument to the method. If an I{xmlrpc_} method is wrapped with C{withRequest}, the request object is passed as the first argument to that method. For example:: @withRequest def xmlrpc_echo(self, request, s): return s @since: 10.2 """ f.withRequest = True return f
Add Introspection support to an XMLRPC server. @param xmlrpc: the XMLRPC server to add Introspection support to. @type xmlrpc: L{XMLRPC}
def addIntrospection(xmlrpc): """ Add Introspection support to an XMLRPC server. @param xmlrpc: the XMLRPC server to add Introspection support to. @type xmlrpc: L{XMLRPC} """ xmlrpc.putSubHandler("system", XMLRPCIntrospection(xmlrpc))
Decorate with L{renderer} to use methods as template render directives. For example:: class Foo(Element): @renderer def twiddle(self, request, tag): return tag('Hello, world.') <div xmlns:t="http://twistedmatrix.com/ns/twisted.web.template/0.1"> <span t:render="twiddle" /> </div> Will result in this final output:: <div> <span>Hello, world.</span> </div>
def renderer() -> None: """ Decorate with L{renderer} to use methods as template render directives. For example:: class Foo(Element): @renderer def twiddle(self, request, tag): return tag('Hello, world.') <div xmlns:t="http://twistedmatrix.com/ns/twisted.web.template/0.1"> <span t:render="twiddle" /> </div> Will result in this final output:: <div> <span>Hello, world.</span> </div> """
Escape some character or UTF-8 byte data for inclusion in an HTML or XML document, by replacing metacharacters (C{&<>}) with their entity equivalents (C{&amp;&lt;&gt;}). This is used as an input to L{_flattenElement}'s C{dataEscaper} parameter. @param data: The string to escape. @return: The quoted form of C{data}. If C{data} is L{str}, return a utf-8 encoded string.
def escapeForContent(data: Union[bytes, str]) -> bytes: """ Escape some character or UTF-8 byte data for inclusion in an HTML or XML document, by replacing metacharacters (C{&<>}) with their entity equivalents (C{&amp;&lt;&gt;}). This is used as an input to L{_flattenElement}'s C{dataEscaper} parameter. @param data: The string to escape. @return: The quoted form of C{data}. If C{data} is L{str}, return a utf-8 encoded string. """ if isinstance(data, str): data = data.encode("utf-8") data = data.replace(b"&", b"&amp;").replace(b"<", b"&lt;").replace(b">", b"&gt;") return data
Escape some character or UTF-8 byte data for inclusion in the top level of an attribute. L{attributeEscapingDoneOutside} actually passes the data through unchanged, because L{writeWithAttributeEscaping} handles the quoting of the text within attributes outside the generator returned by L{_flattenElement}; this is used as the C{dataEscaper} argument to that L{_flattenElement} call so that that generator does not redundantly escape its text output. @param data: The string to escape. @return: The string, unchanged, except for encoding.
def attributeEscapingDoneOutside(data: Union[bytes, str]) -> bytes: """ Escape some character or UTF-8 byte data for inclusion in the top level of an attribute. L{attributeEscapingDoneOutside} actually passes the data through unchanged, because L{writeWithAttributeEscaping} handles the quoting of the text within attributes outside the generator returned by L{_flattenElement}; this is used as the C{dataEscaper} argument to that L{_flattenElement} call so that that generator does not redundantly escape its text output. @param data: The string to escape. @return: The string, unchanged, except for encoding. """ if isinstance(data, str): return data.encode("utf-8") return data
Decorate a C{write} callable so that all output written is properly quoted for inclusion within an XML attribute value. If a L{Tag <twisted.web.template.Tag>} C{x} is flattened within the context of the contents of another L{Tag <twisted.web.template.Tag>} C{y}, the metacharacters (C{<>&"}) delimiting C{x} should be passed through unchanged, but the textual content of C{x} should still be quoted, as usual. For example: C{<y><x>&amp;</x></y>}. That is the default behavior of L{_flattenElement} when L{escapeForContent} is passed as the C{dataEscaper}. However, when a L{Tag <twisted.web.template.Tag>} C{x} is flattened within the context of an I{attribute} of another L{Tag <twisted.web.template.Tag>} C{y}, then the metacharacters delimiting C{x} should be quoted so that it can be parsed from the attribute's value. In the DOM itself, this is not a valid thing to do, but given that renderers and slots may be freely moved around in a L{twisted.web.template} template, it is a condition which may arise in a document and must be handled in a way which produces valid output. So, for example, you should be able to get C{<y attr="&lt;x /&gt;" />}. This should also be true for other XML/HTML meta-constructs such as comments and CDATA, so if you were to serialize a L{comment <twisted.web.template.Comment>} in an attribute you should get C{<y attr="&lt;-- comment --&gt;" />}. Therefore in order to capture these meta-characters, flattening is done with C{write} callable that is wrapped with L{writeWithAttributeEscaping}. The final case, and hopefully the much more common one as compared to serializing L{Tag <twisted.web.template.Tag>} and arbitrary L{IRenderable} objects within an attribute, is to serialize a simple string, and those should be passed through for L{writeWithAttributeEscaping} to quote without applying a second, redundant level of quoting. @param write: A callable which will be invoked with the escaped L{bytes}. @return: A callable that writes data with escaping.
def writeWithAttributeEscaping( write: Callable[[bytes], object] ) -> Callable[[bytes], None]: """ Decorate a C{write} callable so that all output written is properly quoted for inclusion within an XML attribute value. If a L{Tag <twisted.web.template.Tag>} C{x} is flattened within the context of the contents of another L{Tag <twisted.web.template.Tag>} C{y}, the metacharacters (C{<>&"}) delimiting C{x} should be passed through unchanged, but the textual content of C{x} should still be quoted, as usual. For example: C{<y><x>&amp;</x></y>}. That is the default behavior of L{_flattenElement} when L{escapeForContent} is passed as the C{dataEscaper}. However, when a L{Tag <twisted.web.template.Tag>} C{x} is flattened within the context of an I{attribute} of another L{Tag <twisted.web.template.Tag>} C{y}, then the metacharacters delimiting C{x} should be quoted so that it can be parsed from the attribute's value. In the DOM itself, this is not a valid thing to do, but given that renderers and slots may be freely moved around in a L{twisted.web.template} template, it is a condition which may arise in a document and must be handled in a way which produces valid output. So, for example, you should be able to get C{<y attr="&lt;x /&gt;" />}. This should also be true for other XML/HTML meta-constructs such as comments and CDATA, so if you were to serialize a L{comment <twisted.web.template.Comment>} in an attribute you should get C{<y attr="&lt;-- comment --&gt;" />}. Therefore in order to capture these meta-characters, flattening is done with C{write} callable that is wrapped with L{writeWithAttributeEscaping}. The final case, and hopefully the much more common one as compared to serializing L{Tag <twisted.web.template.Tag>} and arbitrary L{IRenderable} objects within an attribute, is to serialize a simple string, and those should be passed through for L{writeWithAttributeEscaping} to quote without applying a second, redundant level of quoting. @param write: A callable which will be invoked with the escaped L{bytes}. @return: A callable that writes data with escaping. """ def _write(data: bytes) -> None: write(escapeForContent(data).replace(b'"', b"&quot;")) return _write
Escape CDATA for inclusion in a document. @param data: The string to escape. @return: The quoted form of C{data}. If C{data} is unicode, return a utf-8 encoded string.
def escapedCDATA(data: Union[bytes, str]) -> bytes: """ Escape CDATA for inclusion in a document. @param data: The string to escape. @return: The quoted form of C{data}. If C{data} is unicode, return a utf-8 encoded string. """ if isinstance(data, str): data = data.encode("utf-8") return data.replace(b"]]>", b"]]]]><![CDATA[>")
Within comments the sequence C{-->} can be mistaken as the end of the comment. To ensure consistent parsing and valid output the sequence is replaced with C{--&gt;}. Furthermore, whitespace is added when a comment ends in a dash. This is done to break the connection of the ending C{-} with the closing C{-->}. @param data: The string to escape. @return: The quoted form of C{data}. If C{data} is unicode, return a utf-8 encoded string.
def escapedComment(data: Union[bytes, str]) -> bytes: """ Within comments the sequence C{-->} can be mistaken as the end of the comment. To ensure consistent parsing and valid output the sequence is replaced with C{--&gt;}. Furthermore, whitespace is added when a comment ends in a dash. This is done to break the connection of the ending C{-} with the closing C{-->}. @param data: The string to escape. @return: The quoted form of C{data}. If C{data} is unicode, return a utf-8 encoded string. """ if isinstance(data, str): data = data.encode("utf-8") data = data.replace(b"-->", b"--&gt;") if data and data[-1:] == b"-": data += b" " return data
Find the value of the named slot in the given stack of slot data.
def _getSlotValue( name: str, slotData: Sequence[Optional[Mapping[str, Flattenable]]], default: Optional[Flattenable] = None, ) -> Flattenable: """ Find the value of the named slot in the given stack of slot data. """ for slotFrame in reversed(slotData): if slotFrame is not None and name in slotFrame: return slotFrame[name] else: if default is not None: return default raise UnfilledSlot(name)
Create a new L{Deferred} based on C{d} that will fire and fail with C{d}'s result or error, but will not modify C{d}'s callback type.
def _fork(d: Deferred[T]) -> Deferred[T]: """ Create a new L{Deferred} based on C{d} that will fire and fail with C{d}'s result or error, but will not modify C{d}'s callback type. """ d2: Deferred[T] = Deferred(lambda _: d.cancel()) def callback(result: T) -> T: d2.callback(result) return result def errback(failure: Failure) -> Failure: d2.errback(failure) return failure d.addCallbacks(callback, errback) return d2
Make C{root} slightly more flat by yielding all its immediate contents as strings, deferreds or generators that are recursive calls to itself. @param request: A request object which will be passed to L{IRenderable.render}. @param root: An object to be made flatter. This may be of type C{unicode}, L{str}, L{slot}, L{Tag <twisted.web.template.Tag>}, L{tuple}, L{list}, L{types.GeneratorType}, L{Deferred}, or an object that implements L{IRenderable}. @param write: A callable which will be invoked with each L{bytes} produced by flattening C{root}. @param slotData: A L{list} of L{dict} mapping L{str} slot names to data with which those slots will be replaced. @param renderFactory: If not L{None}, an object that provides L{IRenderable}. @param dataEscaper: A 1-argument callable which takes L{bytes} or L{unicode} and returns L{bytes}, quoted as appropriate for the rendering context. This is really only one of two values: L{attributeEscapingDoneOutside} or L{escapeForContent}, depending on whether the rendering context is within an attribute or not. See the explanation in L{writeWithAttributeEscaping}. @return: An iterator that eventually writes L{bytes} to C{write}. It can yield other iterators or L{Deferred}s; if it yields another iterator, the caller will iterate it; if it yields a L{Deferred}, the result of that L{Deferred} will be another generator, in which case it is iterated. See L{_flattenTree} for the trampoline that consumes said values.
def _flattenElement( request: Optional[IRequest], root: Flattenable, write: Callable[[bytes], object], slotData: List[Optional[Mapping[str, Flattenable]]], renderFactory: Optional[IRenderable], dataEscaper: Callable[[Union[bytes, str]], bytes], # This is annotated as Generator[T, None, None] instead of Iterator[T] # because mypy does not consider an Iterator to be an instance of # GeneratorType. ) -> Generator[Union[Generator[Any, Any, Any], Deferred[Flattenable]], None, None]: """ Make C{root} slightly more flat by yielding all its immediate contents as strings, deferreds or generators that are recursive calls to itself. @param request: A request object which will be passed to L{IRenderable.render}. @param root: An object to be made flatter. This may be of type C{unicode}, L{str}, L{slot}, L{Tag <twisted.web.template.Tag>}, L{tuple}, L{list}, L{types.GeneratorType}, L{Deferred}, or an object that implements L{IRenderable}. @param write: A callable which will be invoked with each L{bytes} produced by flattening C{root}. @param slotData: A L{list} of L{dict} mapping L{str} slot names to data with which those slots will be replaced. @param renderFactory: If not L{None}, an object that provides L{IRenderable}. @param dataEscaper: A 1-argument callable which takes L{bytes} or L{unicode} and returns L{bytes}, quoted as appropriate for the rendering context. This is really only one of two values: L{attributeEscapingDoneOutside} or L{escapeForContent}, depending on whether the rendering context is within an attribute or not. See the explanation in L{writeWithAttributeEscaping}. @return: An iterator that eventually writes L{bytes} to C{write}. It can yield other iterators or L{Deferred}s; if it yields another iterator, the caller will iterate it; if it yields a L{Deferred}, the result of that L{Deferred} will be another generator, in which case it is iterated. See L{_flattenTree} for the trampoline that consumes said values. """ def keepGoing( newRoot: Flattenable, dataEscaper: Callable[[Union[bytes, str]], bytes] = dataEscaper, renderFactory: Optional[IRenderable] = renderFactory, write: Callable[[bytes], object] = write, ) -> Generator[Union[Flattenable, Deferred[Flattenable]], None, None]: return _flattenElement( request, newRoot, write, slotData, renderFactory, dataEscaper ) def keepGoingAsync(result: Deferred[Flattenable]) -> Deferred[Flattenable]: return result.addCallback(keepGoing) if isinstance(root, (bytes, str)): write(dataEscaper(root)) elif isinstance(root, slot): slotValue = _getSlotValue(root.name, slotData, root.default) yield keepGoing(slotValue) elif isinstance(root, CDATA): write(b"<![CDATA[") write(escapedCDATA(root.data)) write(b"]]>") elif isinstance(root, Comment): write(b"<!--") write(escapedComment(root.data)) write(b"-->") elif isinstance(root, Tag): slotData.append(root.slotData) rendererName = root.render if rendererName is not None: if renderFactory is None: raise ValueError( f'Tag wants to be rendered by method "{rendererName}" ' f"but is not contained in any IRenderable" ) rootClone = root.clone(False) rootClone.render = None renderMethod = renderFactory.lookupRenderMethod(rendererName) result = renderMethod(request, rootClone) yield keepGoing(result) slotData.pop() return if not root.tagName: yield keepGoing(root.children) return write(b"<") if isinstance(root.tagName, str): tagName = root.tagName.encode("ascii") else: tagName = root.tagName write(tagName) for k, v in root.attributes.items(): if isinstance(k, str): k = k.encode("ascii") write(b" " + k + b'="') # Serialize the contents of the attribute, wrapping the results of # that serialization so that _everything_ is quoted. yield keepGoing( v, attributeEscapingDoneOutside, write=writeWithAttributeEscaping(write) ) write(b'"') if root.children or nativeString(tagName) not in voidElements: write(b">") # Regardless of whether we're in an attribute or not, switch back # to the escapeForContent dataEscaper. The contents of a tag must # be quoted no matter what; in the top-level document, just so # they're valid, and if they're within an attribute, they have to # be quoted so that after applying the *un*-quoting required to re- # parse the tag within the attribute, all the quoting is still # correct. yield keepGoing(root.children, escapeForContent) write(b"</" + tagName + b">") else: write(b" />") elif isinstance(root, (tuple, list, GeneratorType)): for element in root: yield keepGoing(element) elif isinstance(root, CharRef): escaped = "&#%d;" % (root.ordinal,) write(escaped.encode("ascii")) elif isinstance(root, Deferred): yield keepGoingAsync(_fork(root)) elif iscoroutine(root): yield keepGoingAsync( Deferred.fromCoroutine( cast(Coroutine[Deferred[Flattenable], object, Flattenable], root) ) ) elif IRenderable.providedBy(root): result = root.render(request) yield keepGoing(result, renderFactory=root) else: raise UnsupportedType(root)
Incrementally write out a string representation of C{root} using C{write}. In order to create a string representation, C{root} will be decomposed into simpler objects which will themselves be decomposed and so on until strings or objects which can easily be converted to strings are encountered. @param request: A request object which will be passed to the C{render} method of any L{IRenderable} provider which is encountered. @param root: An object to be made flatter. This may be of type L{str}, L{bytes}, L{slot}, L{Tag <twisted.web.template.Tag>}, L{tuple}, L{list}, L{types.GeneratorType}, L{Deferred}, or something that provides L{IRenderable}. @param write: A callable which will be invoked with each L{bytes} produced by flattening C{root}. @return: A L{Deferred} which will be called back with C{None} when C{root} has been completely flattened into C{write} or which will be errbacked if an unexpected exception occurs.
def flatten( request: Optional[IRequest], root: Flattenable, write: Callable[[bytes], object] ) -> Deferred[None]: """ Incrementally write out a string representation of C{root} using C{write}. In order to create a string representation, C{root} will be decomposed into simpler objects which will themselves be decomposed and so on until strings or objects which can easily be converted to strings are encountered. @param request: A request object which will be passed to the C{render} method of any L{IRenderable} provider which is encountered. @param root: An object to be made flatter. This may be of type L{str}, L{bytes}, L{slot}, L{Tag <twisted.web.template.Tag>}, L{tuple}, L{list}, L{types.GeneratorType}, L{Deferred}, or something that provides L{IRenderable}. @param write: A callable which will be invoked with each L{bytes} produced by flattening C{root}. @return: A L{Deferred} which will be called back with C{None} when C{root} has been completely flattened into C{write} or which will be errbacked if an unexpected exception occurs. """ return ensureDeferred(_flattenTree(request, root, write))
Collate a string representation of C{root} into a single string. This is basically gluing L{flatten} to an L{io.BytesIO} and returning the results. See L{flatten} for the exact meanings of C{request} and C{root}. @return: A L{Deferred} which will be called back with a single UTF-8 encoded string as its result when C{root} has been completely flattened or which will be errbacked if an unexpected exception occurs.
def flattenString(request: Optional[IRequest], root: Flattenable) -> Deferred[bytes]: """ Collate a string representation of C{root} into a single string. This is basically gluing L{flatten} to an L{io.BytesIO} and returning the results. See L{flatten} for the exact meanings of C{request} and C{root}. @return: A L{Deferred} which will be called back with a single UTF-8 encoded string as its result when C{root} has been completely flattened or which will be errbacked if an unexpected exception occurs. """ io = BytesIO() d = flatten(request, root, io.write) d.addCallback(lambda _: io.getvalue()) return cast(Deferred[bytes], d)
Add a header tuple to a request header object. @param request: The request to add the header tuple to. @type request: L{twisted.web.http.Request} @param header: The header tuple to add to the request. @type header: A L{tuple} with two elements, the header name and header value, both as L{bytes}. @return: If the header being added was the C{Content-Length} header. @rtype: L{bool}
def _addHeaderToRequest(request, header): """ Add a header tuple to a request header object. @param request: The request to add the header tuple to. @type request: L{twisted.web.http.Request} @param header: The header tuple to add to the request. @type header: A L{tuple} with two elements, the header name and header value, both as L{bytes}. @return: If the header being added was the C{Content-Length} header. @rtype: L{bool} """ requestHeaders = request.requestHeaders name, value = header values = requestHeaders.getRawHeaders(name) if values is not None: values.append(value) else: requestHeaders.setRawHeaders(name, [value]) if name == b"content-length": request.gotLength(int(value)) return True return False
Call C{function}. If it raises an exception, log it with a minimal description of the source. @return: L{None}
def _callAppFunction(function): """ Call C{function}. If it raises an exception, log it with a minimal description of the source. @return: L{None} """ try: function() except BaseException: _moduleLog.failure( "Unexpected exception from {name}", name=fullyQualifiedName(function) )
An HTTP method is an HTTP token, which consists of any visible ASCII character that is not a delimiter (i.e. one of C{"(),/:;<=>?@[\]{}}.) @param method: the method to check @type method: L{bytes} @return: the method if it is valid @rtype: L{bytes} @raise ValueError: if the method is not valid @see: U{https://tools.ietf.org/html/rfc7230#section-3.1.1}, U{https://tools.ietf.org/html/rfc7230#section-3.2.6}, U{https://tools.ietf.org/html/rfc5234#appendix-B.1}
def _ensureValidMethod(method): """ An HTTP method is an HTTP token, which consists of any visible ASCII character that is not a delimiter (i.e. one of C{"(),/:;<=>?@[\\]{}}.) @param method: the method to check @type method: L{bytes} @return: the method if it is valid @rtype: L{bytes} @raise ValueError: if the method is not valid @see: U{https://tools.ietf.org/html/rfc7230#section-3.1.1}, U{https://tools.ietf.org/html/rfc7230#section-3.2.6}, U{https://tools.ietf.org/html/rfc5234#appendix-B.1} """ if _VALID_METHOD.match(method): return method raise ValueError(f"Invalid method {method!r}")
A valid URI cannot contain control characters (i.e., characters between 0-32, inclusive and 127) or non-ASCII characters (i.e., characters with values between 128-255, inclusive). @param uri: the URI to check @type uri: L{bytes} @return: the URI if it is valid @rtype: L{bytes} @raise ValueError: if the URI is not valid @see: U{https://tools.ietf.org/html/rfc3986#section-3.3}, U{https://tools.ietf.org/html/rfc3986#appendix-A}, U{https://tools.ietf.org/html/rfc5234#appendix-B.1}
def _ensureValidURI(uri): """ A valid URI cannot contain control characters (i.e., characters between 0-32, inclusive and 127) or non-ASCII characters (i.e., characters with values between 128-255, inclusive). @param uri: the URI to check @type uri: L{bytes} @return: the URI if it is valid @rtype: L{bytes} @raise ValueError: if the URI is not valid @see: U{https://tools.ietf.org/html/rfc3986#section-3.3}, U{https://tools.ietf.org/html/rfc3986#appendix-A}, U{https://tools.ietf.org/html/rfc5234#appendix-B.1} """ if _VALID_URI.match(uri): return uri raise ValueError(f"Invalid URI {uri!r}")
Given a I{dispatch} name and a function, return a function which can be used as a method and which, when called, will call another method defined on the instance and return the result. The other method which is called is determined by the value of the C{_state} attribute of the instance. @param name: A string which is used to construct the name of the subsidiary method to invoke. The subsidiary method is named like C{'_%s_%s' % (name, _state)}. @param template: A function object which is used to give the returned function a docstring. @return: The dispatcher function.
def makeStatefulDispatcher(name, template): """ Given a I{dispatch} name and a function, return a function which can be used as a method and which, when called, will call another method defined on the instance and return the result. The other method which is called is determined by the value of the C{_state} attribute of the instance. @param name: A string which is used to construct the name of the subsidiary method to invoke. The subsidiary method is named like C{'_%s_%s' % (name, _state)}. @param template: A function object which is used to give the returned function a docstring. @return: The dispatcher function. """ def dispatcher(self, *args, **kwargs): func = getattr(self, "_" + name + "_" + self._state, None) if func is None: raise RuntimeError(f"{self!r} has no {name} method in state {self._state}") return func(*args, **kwargs) dispatcher.__doc__ = template.__doc__ return dispatcher
Wraps <pre> tags around some text and HTML-escape it. This is here since once twisted.web.html was deprecated it was hard to migrate the html.PRE from current code to twisted.web.template. For new code consider using twisted.web.template. @return: Escaped text wrapped in <pre> tags. @rtype: C{str}
def _PRE(text): """ Wraps <pre> tags around some text and HTML-escape it. This is here since once twisted.web.html was deprecated it was hard to migrate the html.PRE from current code to twisted.web.template. For new code consider using twisted.web.template. @return: Escaped text wrapped in <pre> tags. @rtype: C{str} """ return f"<pre>{escape(text)}</pre>"
Generate a redirect to the given location. @param URL: A L{bytes} giving the location to which to redirect. @param request: The request object to use to generate the redirect. @type request: L{IRequest<twisted.web.iweb.IRequest>} provider @raise TypeError: If the type of C{URL} a L{str} instead of L{bytes}. @return: A L{bytes} containing HTML which tries to convince the client agent to visit the new location even if it doesn't respect the I{FOUND} response code. This is intended to be returned from a render method, eg:: def render_GET(self, request): return redirectTo(b"http://example.com/", request)
def redirectTo(URL: bytes, request: IRequest) -> bytes: """ Generate a redirect to the given location. @param URL: A L{bytes} giving the location to which to redirect. @param request: The request object to use to generate the redirect. @type request: L{IRequest<twisted.web.iweb.IRequest>} provider @raise TypeError: If the type of C{URL} a L{str} instead of L{bytes}. @return: A L{bytes} containing HTML which tries to convince the client agent to visit the new location even if it doesn't respect the I{FOUND} response code. This is intended to be returned from a render method, eg:: def render_GET(self, request): return redirectTo(b"http://example.com/", request) """ if not isinstance(URL, bytes): raise TypeError("URL must be bytes") request.setHeader(b"Content-Type", b"text/html; charset=utf-8") request.redirect(URL) # FIXME: The URL should be HTML-escaped. # https://twistedmatrix.com/trac/ticket/9839 content = b""" <html> <head> <meta http-equiv=\"refresh\" content=\"0;URL=%(url)s\"> </head> <body bgcolor=\"#FFFFFF\" text=\"#000000\"> <a href=\"%(url)s\">click here</a> </body> </html> """ % { b"url": URL } return content
Perform a SAX parse of an XML document with the _ToStan class. @param fl: The XML document to be parsed. @return: a C{list} of Stan objects.
def _flatsaxParse(fl: Union[IO[AnyStr], str]) -> List["Flattenable"]: """ Perform a SAX parse of an XML document with the _ToStan class. @param fl: The XML document to be parsed. @return: a C{list} of Stan objects. """ parser = make_parser() parser.setFeature(handler.feature_validation, 0) parser.setFeature(handler.feature_namespaces, 1) parser.setFeature(handler.feature_external_ges, 0) parser.setFeature(handler.feature_external_pes, 0) s = _ToStan(getattr(fl, "name", None)) parser.setContentHandler(s) parser.setEntityResolver(s) parser.setProperty(handler.property_lexical_handler, s) parser.parse(fl) return s.document
Construct an HTML representation of the given failure. Consider using L{FailureElement} instead. @type myFailure: L{Failure<twisted.python.failure.Failure>} @rtype: L{bytes} @return: A string containing the HTML representation of the given failure.
def formatFailure(myFailure): """ Construct an HTML representation of the given failure. Consider using L{FailureElement} instead. @type myFailure: L{Failure<twisted.python.failure.Failure>} @rtype: L{bytes} @return: A string containing the HTML representation of the given failure. """ result = [] flattenString(None, FailureElement(myFailure)).addBoth(result.append) if isinstance(result[0], bytes): # Ensure the result string is all ASCII, for compatibility with the # default encoding expected by browsers. return result[0].decode("utf-8").encode("ascii", "xmlcharrefreplace") result[0].raiseException()
Render an element or other L{IRenderable}. @param request: The L{IRequest} being rendered to. @param element: An L{IRenderable} which will be rendered. @param doctype: A L{bytes} which will be written as the first line of the request, or L{None} to disable writing of a doctype. The argument should not include a trailing newline and will default to the HTML5 doctype C{'<!DOCTYPE html>'}. @returns: NOT_DONE_YET @since: 12.1
def renderElement( request: IRequest, element: IRenderable, doctype: Optional[bytes] = b"<!DOCTYPE html>", _failElement: Optional[Callable[[Failure], "Element"]] = None, ) -> object: """ Render an element or other L{IRenderable}. @param request: The L{IRequest} being rendered to. @param element: An L{IRenderable} which will be rendered. @param doctype: A L{bytes} which will be written as the first line of the request, or L{None} to disable writing of a doctype. The argument should not include a trailing newline and will default to the HTML5 doctype C{'<!DOCTYPE html>'}. @returns: NOT_DONE_YET @since: 12.1 """ if doctype is not None: request.write(doctype) request.write(b"\n") if _failElement is None: _failElement = FailureElement d = flatten(request, element, request.write) def eb(failure: Failure) -> Optional[Deferred[None]]: _moduleLog.failure( "An error occurred while rendering the response.", failure=failure ) site = getattr(request, "site", None) if site is not None and site.displayTracebacks: assert _failElement is not None return flatten(request, _failElement(failure), request.write) else: request.write( b'<div style="font-size:800%;' b"background-color:#FFF;" b"color:#F00" b'">An error occurred while rendering the response.</div>' ) return None def finish(result: object, *, request: IRequest = request) -> object: request.finish() return result d.addErrback(eb) d.addBoth(finish) return NOT_DONE_YET
Discard the body of a HTTP response. @param response: The response. @return: The response.
def discardBody(response): """ Discard the body of a HTTP response. @param response: The response. @return: The response. """ return client.readBody(response).addCallback(lambda _: response)
Return a callable that proxies instances of C{clsToWrap} via L{_IDeprecatedHTTPChannelToRequestInterface}. @param clsToWrap: The class whose instances will be proxied. @type cls: L{_IDeprecatedHTTPChannelToRequestInterface} implementer. @return: A factory that returns L{_IDeprecatedHTTPChannelToRequestInterface} proxies. @rtype: L{callable} whose interface matches C{clsToWrap}'s constructor.
def _makeRequestProxyFactory(clsToWrap): """ Return a callable that proxies instances of C{clsToWrap} via L{_IDeprecatedHTTPChannelToRequestInterface}. @param clsToWrap: The class whose instances will be proxied. @type cls: L{_IDeprecatedHTTPChannelToRequestInterface} implementer. @return: A factory that returns L{_IDeprecatedHTTPChannelToRequestInterface} proxies. @rtype: L{callable} whose interface matches C{clsToWrap}'s constructor. """ def _makeRequestProxy(*args, **kwargs): instance = clsToWrap(*args, **kwargs) return _IDeprecatedHTTPChannelToRequestInterfaceProxy(instance) # For INonQueuedRequestFactory directlyProvides(_makeRequestProxy, providedBy(clsToWrap)) return _makeRequestProxy
Parametrizes the L{TimeoutMixin} so that it works with whatever reactor is being used by the test. @param protocol: A L{_GenericHTTPChannel} or something implementing a similar interface. @type protocol: L{_GenericHTTPChannel} @param reactor: An L{IReactorTime} implementation. @type reactor: L{IReactorTime} @return: The C{channel}, with its C{callLater} method patched.
def parametrizeTimeoutMixin(protocol, reactor): """ Parametrizes the L{TimeoutMixin} so that it works with whatever reactor is being used by the test. @param protocol: A L{_GenericHTTPChannel} or something implementing a similar interface. @type protocol: L{_GenericHTTPChannel} @param reactor: An L{IReactorTime} implementation. @type reactor: L{IReactorTime} @return: The C{channel}, with its C{callLater} method patched. """ # This is a terrible violation of the abstraction later of # _genericHTTPChannelProtocol, but we need to do it because # policies.TimeoutMixin doesn't accept a reactor on the object. # See https://twistedmatrix.com/trac/ticket/8488 protocol._channel.callLater = reactor.callLater return protocol
Make a request with the given request headers for the persistence tests.
def _prequest(**headers): """ Make a request with the given request headers for the persistence tests. """ request = http.Request(DummyChannel(), False) for headerName, v in headers.items(): request.requestHeaders.setRawHeaders(networkString(headerName), v) return request
Create a new dict containing only a subset of the items of an existing dict. @param keys: An iterable of the keys which will be added (with values from C{d}) to the result. @param d: The existing L{dict} from which to copy items. @return: The new L{dict} with keys given by C{keys} and values given by the corresponding values in C{d}. @rtype: L{dict}
def sub(keys, d): """ Create a new dict containing only a subset of the items of an existing dict. @param keys: An iterable of the keys which will be added (with values from C{d}) to the result. @param d: The existing L{dict} from which to copy items. @return: The new L{dict} with keys given by C{keys} and values given by the corresponding values in C{d}. @rtype: L{dict} """ return {k: d[k] for k in keys}
Provides a sequence of HTTP/2 frames that encode a single HTTP request. This should be used when you want to control the serialization yourself, e.g. because you want to interleave other frames with these. If that's not necessary, prefer L{buildRequestBytes}. @param headers: The HTTP/2 headers to send. @type headers: L{list} of L{tuple} of L{bytes} @param data: The HTTP data to send. Each list entry will be sent in its own frame. @type data: L{list} of L{bytes} @param frameFactory: The L{FrameFactory} that will be used to construct the frames. @type frameFactory: L{FrameFactory} @param streamID: The ID of the stream on which to send the request. @type streamID: L{int}
def buildRequestFrames(headers, data, frameFactory=None, streamID=1): """ Provides a sequence of HTTP/2 frames that encode a single HTTP request. This should be used when you want to control the serialization yourself, e.g. because you want to interleave other frames with these. If that's not necessary, prefer L{buildRequestBytes}. @param headers: The HTTP/2 headers to send. @type headers: L{list} of L{tuple} of L{bytes} @param data: The HTTP data to send. Each list entry will be sent in its own frame. @type data: L{list} of L{bytes} @param frameFactory: The L{FrameFactory} that will be used to construct the frames. @type frameFactory: L{FrameFactory} @param streamID: The ID of the stream on which to send the request. @type streamID: L{int} """ if frameFactory is None: frameFactory = FrameFactory() frames = [] frames.append(frameFactory.buildHeadersFrame(headers=headers, streamID=streamID)) frames.extend( frameFactory.buildDataFrame(chunk, streamID=streamID) for chunk in data ) frames[-1].flags.add("END_STREAM") return frames
Provides the byte sequence for a collection of HTTP/2 frames representing the provided request. @param headers: The HTTP/2 headers to send. @type headers: L{list} of L{tuple} of L{bytes} @param data: The HTTP data to send. Each list entry will be sent in its own frame. @type data: L{list} of L{bytes} @param frameFactory: The L{FrameFactory} that will be used to construct the frames. @type frameFactory: L{FrameFactory} @param streamID: The ID of the stream on which to send the request. @type streamID: L{int}
def buildRequestBytes(headers, data, frameFactory=None, streamID=1): """ Provides the byte sequence for a collection of HTTP/2 frames representing the provided request. @param headers: The HTTP/2 headers to send. @type headers: L{list} of L{tuple} of L{bytes} @param data: The HTTP data to send. Each list entry will be sent in its own frame. @type data: L{list} of L{bytes} @param frameFactory: The L{FrameFactory} that will be used to construct the frames. @type frameFactory: L{FrameFactory} @param streamID: The ID of the stream on which to send the request. @type streamID: L{int} """ frames = buildRequestFrames(headers, data, frameFactory, streamID) return b"".join(f.serialize() for f in frames)
Given a sequence of bytes, decodes them into frames. Note that this method should almost always be called only once, before making some assertions. This is because decoding HTTP/2 frames is extremely stateful, and this function doesn't preserve any of that state between calls. @param data: The serialized HTTP/2 frames. @type data: L{bytes} @returns: A list of HTTP/2 frames. @rtype: L{list} of L{hyperframe.frame.Frame} subclasses.
def framesFromBytes(data): """ Given a sequence of bytes, decodes them into frames. Note that this method should almost always be called only once, before making some assertions. This is because decoding HTTP/2 frames is extremely stateful, and this function doesn't preserve any of that state between calls. @param data: The serialized HTTP/2 frames. @type data: L{bytes} @returns: A list of HTTP/2 frames. @rtype: L{list} of L{hyperframe.frame.Frame} subclasses. """ buffer = FrameBuffer() buffer.receiveData(data) return list(buffer)
Assert that the components are sanitized to the expected value as both a header name and value, across all of L{Header}'s setters and getters. @param testCase: A test case. @param components: A sequence of values that contain linear whitespace to use as header names and values; see C{textLinearWhitespaceComponents} and C{bytesLinearWhitespaceComponents} @param expected: The expected sanitized form of the component for both headers names and their values.
def assertSanitized( testCase: TestCase, components: Sequence[bytes] | Sequence[str], expected: bytes ) -> None: """ Assert that the components are sanitized to the expected value as both a header name and value, across all of L{Header}'s setters and getters. @param testCase: A test case. @param components: A sequence of values that contain linear whitespace to use as header names and values; see C{textLinearWhitespaceComponents} and C{bytesLinearWhitespaceComponents} @param expected: The expected sanitized form of the component for both headers names and their values. """ for component in components: headers = [] headers.append(Headers({component: [component]})) # type: ignore[type-var] added = Headers() added.addRawHeader(component, component) headers.append(added) setHeader = Headers() setHeader.setRawHeaders(component, [component]) headers.append(setHeader) for header in headers: testCase.assertEqual( list(header.getAllRawHeaders()), [(expected, [expected])] ) testCase.assertEqual(header.getRawHeaders(expected), [expected])
Assert that the given L{Deferred} fails with the exception given by C{mainType} and that the exceptions wrapped by the instance of C{mainType} it fails with match the list of exception types given by C{reasonTypes}. This is a helper for testing failures of exceptions which subclass L{_newclient._WrapperException}. @param self: A L{TestCase} instance which will be used to make the assertions. @param deferred: The L{Deferred} which is expected to fail with C{mainType}. @param mainType: A L{_newclient._WrapperException} subclass which will be trapped on C{deferred}. @param reasonTypes: A sequence of exception types which will be trapped on the resulting C{mainType} exception instance's C{reasons} sequence. @return: A L{Deferred} which fires with the C{mainType} instance C{deferred} fails with, or which fails somehow.
def assertWrapperExceptionTypes(self, deferred, mainType, reasonTypes): """ Assert that the given L{Deferred} fails with the exception given by C{mainType} and that the exceptions wrapped by the instance of C{mainType} it fails with match the list of exception types given by C{reasonTypes}. This is a helper for testing failures of exceptions which subclass L{_newclient._WrapperException}. @param self: A L{TestCase} instance which will be used to make the assertions. @param deferred: The L{Deferred} which is expected to fail with C{mainType}. @param mainType: A L{_newclient._WrapperException} subclass which will be trapped on C{deferred}. @param reasonTypes: A sequence of exception types which will be trapped on the resulting C{mainType} exception instance's C{reasons} sequence. @return: A L{Deferred} which fires with the C{mainType} instance C{deferred} fails with, or which fails somehow. """ def cbFailed(err): for reason, type in zip(err.reasons, reasonTypes): reason.trap(type) self.assertEqual( len(err.reasons), len(reasonTypes), f"len({err.reasons}) != len({reasonTypes})", ) return err d = self.assertFailure(deferred, mainType) d.addCallback(cbFailed) return d
A simple helper to invoke L{assertWrapperExceptionTypes} with a C{mainType} of L{ResponseFailed}.
def assertResponseFailed(self, deferred, reasonTypes): """ A simple helper to invoke L{assertWrapperExceptionTypes} with a C{mainType} of L{ResponseFailed}. """ return assertWrapperExceptionTypes(self, deferred, ResponseFailed, reasonTypes)
A simple helper to invoke L{assertWrapperExceptionTypes} with a C{mainType} of L{RequestGenerationFailed}.
def assertRequestGenerationFailed(self, deferred, reasonTypes): """ A simple helper to invoke L{assertWrapperExceptionTypes} with a C{mainType} of L{RequestGenerationFailed}. """ return assertWrapperExceptionTypes( self, deferred, RequestGenerationFailed, reasonTypes )
A simple helper to invoke L{assertWrapperExceptionTypes} with a C{mainType} of L{RequestTransmissionFailed}.
def assertRequestTransmissionFailed(self, deferred, reasonTypes): """ A simple helper to invoke L{assertWrapperExceptionTypes} with a C{mainType} of L{RequestTransmissionFailed}. """ return assertWrapperExceptionTypes( self, deferred, RequestTransmissionFailed, reasonTypes )
Helper function for creating a Response which uses the given transport. All of the other parameters to L{Response.__init__} are filled with arbitrary values. Only use this method if you don't care about any of them.
def justTransportResponse(transport): """ Helper function for creating a Response which uses the given transport. All of the other parameters to L{Response.__init__} are filled with arbitrary values. Only use this method if you don't care about any of them. """ return Response((b"HTTP", 1, 1), 200, b"OK", _boringHeaders, transport)
Render a response using the given resource. @param resource: The resource to use to handle the request. @returns: The request that the resource handled,
def _render(resource: IResource) -> DummyRequest: """ Render a response using the given resource. @param resource: The resource to use to handle the request. @returns: The request that the resource handled, """ request = DummyRequest([b""]) # The cast is necessary because DummyRequest isn't annotated # as an IRequest, and this can't be trivially done. See # https://github.com/twisted/twisted/issues/11719 resource.render(cast(IRequest, request)) return request
Produce a new tag for testing.
def proto(*a: Flattenable, **kw: Flattenable) -> Tag: """ Produce a new tag for testing. """ return Tag("hello")(*a, **kw)
Assert that C{fileObj} is a temporary file on the filesystem. @param case: A C{TestCase} instance to use to make the assertion. @raise: C{case.failureException} if C{fileObj} is not a temporary file on the filesystem.
def assertIsFilesystemTemporary(case, fileObj): """ Assert that C{fileObj} is a temporary file on the filesystem. @param case: A C{TestCase} instance to use to make the assertion. @raise: C{case.failureException} if C{fileObj} is not a temporary file on the filesystem. """ # The tempfile API used to create content returns an instance of a # different type depending on what platform we're running on. The point # here is to verify that the request body is in a file that's on the # filesystem. Having a fileno method that returns an int is a somewhat # close approximation of this. -exarkun case.assertIsInstance(fileObj.fileno(), int)
Breaks a message from an IRC server into its prefix, command, and arguments. @param s: The message to break. @type s: L{bytes} @return: A tuple of (prefix, command, args). @rtype: L{tuple}
def parsemsg(s): """ Breaks a message from an IRC server into its prefix, command, and arguments. @param s: The message to break. @type s: L{bytes} @return: A tuple of (prefix, command, args). @rtype: L{tuple} """ prefix = "" trailing = [] if not s: raise IRCBadMessage("Empty line.") if s[0:1] == ":": prefix, s = s[1:].split(" ", 1) if s.find(" :") != -1: s, trailing = s.split(" :", 1) args = s.split() args.append(trailing) else: args = s.split() command = args.pop(0) return prefix, command, args
Split a string into multiple lines. Whitespace near C{str[length]} will be preferred as a breaking point. C{"\n"} will also be used as a breaking point. @param str: The string to split. @type str: C{str} @param length: The maximum length which will be allowed for any string in the result. @type length: C{int} @return: C{list} of C{str}
def split(str, length=80): """ Split a string into multiple lines. Whitespace near C{str[length]} will be preferred as a breaking point. C{"\\n"} will also be used as a breaking point. @param str: The string to split. @type str: C{str} @param length: The maximum length which will be allowed for any string in the result. @type length: C{int} @return: C{list} of C{str} """ return [chunk for line in str.split("\n") for chunk in textwrap.wrap(line, length)]
Convert a value to an integer if possible. @rtype: C{int} or type of L{default} @return: An integer when C{value} can be converted to an integer, otherwise return C{default}
def _intOrDefault(value, default=None): """ Convert a value to an integer if possible. @rtype: C{int} or type of L{default} @return: An integer when C{value} can be converted to an integer, otherwise return C{default} """ if value: try: return int(value) except (TypeError, ValueError): pass return default
Parse an IRC mode string. The mode string is parsed into two lists of mode changes (added and removed), with each mode change represented as C{(mode, param)} where mode is the mode character, and param is the parameter passed for that mode, or L{None} if no parameter is required. @type modes: C{str} @param modes: Modes string to parse. @type params: C{list} @param params: Parameters specified along with L{modes}. @type paramModes: C{(str, str)} @param paramModes: A pair of strings (C{(add, remove)}) that indicate which modes take parameters when added or removed. @returns: Two lists of mode changes, one for modes added and the other for modes removed respectively, mode changes in each list are represented as C{(mode, param)}.
def parseModes(modes, params, paramModes=("", "")): """ Parse an IRC mode string. The mode string is parsed into two lists of mode changes (added and removed), with each mode change represented as C{(mode, param)} where mode is the mode character, and param is the parameter passed for that mode, or L{None} if no parameter is required. @type modes: C{str} @param modes: Modes string to parse. @type params: C{list} @param params: Parameters specified along with L{modes}. @type paramModes: C{(str, str)} @param paramModes: A pair of strings (C{(add, remove)}) that indicate which modes take parameters when added or removed. @returns: Two lists of mode changes, one for modes added and the other for modes removed respectively, mode changes in each list are represented as C{(mode, param)}. """ if len(modes) == 0: raise IRCBadModes("Empty mode string") if modes[0] not in "+-": raise IRCBadModes(f"Malformed modes string: {modes!r}") changes = ([], []) direction = None count = -1 for ch in modes: if ch in "+-": if count == 0: raise IRCBadModes(f"Empty mode sequence: {modes!r}") direction = "+-".index(ch) count = 0 else: param = None if ch in paramModes[direction]: try: param = params.pop(0) except IndexError: raise IRCBadModes(f"Not enough parameters: {ch!r}") changes[direction].append((ch, param)) count += 1 if len(params) > 0: raise IRCBadModes(f"Too many parameters: {modes!r} {params!r}") if count == 0: raise IRCBadModes(f"Empty mode sequence: {modes!r}") return changes
I'll try my damndest to determine the size of this file object. @param file: The file object to determine the size of. @type file: L{io.IOBase} @rtype: L{int} or L{None} @return: The size of the file object as an integer if it can be determined, otherwise return L{None}.
def fileSize(file): """ I'll try my damndest to determine the size of this file object. @param file: The file object to determine the size of. @type file: L{io.IOBase} @rtype: L{int} or L{None} @return: The size of the file object as an integer if it can be determined, otherwise return L{None}. """ size = None if hasattr(file, "fileno"): fileno = file.fileno() try: stat_ = os.fstat(fileno) size = stat_[stat.ST_SIZE] except BaseException: pass else: return size if hasattr(file, "name") and path.exists(file.name): try: size = path.getsize(file.name) except BaseException: pass else: return size if hasattr(file, "seek") and hasattr(file, "tell"): try: try: file.seek(0, 2) size = file.tell() finally: file.seek(0, 0) except BaseException: pass else: return size return size
Given the data chunk from a DCC query, return a descriptive string. @param data: The data from a DCC query. @type data: L{bytes} @rtype: L{bytes} @return: A descriptive string.
def dccDescribe(data): """ Given the data chunk from a DCC query, return a descriptive string. @param data: The data from a DCC query. @type data: L{bytes} @rtype: L{bytes} @return: A descriptive string. """ orig_data = data data = data.split() if len(data) < 4: return orig_data (dcctype, arg, address, port) = data[:4] if "." in address: pass else: try: address = int(address) except ValueError: pass else: address = ( (address >> 24) & 0xFF, (address >> 16) & 0xFF, (address >> 8) & 0xFF, address & 0xFF, ) address = ".".join(map(str, address)) if dcctype == "SEND": filename = arg size_txt = "" if len(data) >= 5: try: size = int(data[4]) size_txt = " of size %d bytes" % (size,) except ValueError: pass dcc_text = "SEND for file '{}'{} at host {}, port {}".format( filename, size_txt, address, port, ) elif dcctype == "CHAT": dcc_text = f"CHAT for host {address}, port {port}" else: dcc_text = orig_data return dcc_text
Apply a function of two arguments cumulatively to the items of a sequence, from right to left, so as to reduce the sequence to a single value. @type f: C{callable} taking 2 arguments @param z: Initial value. @param xs: Sequence to reduce. @return: Single value resulting from reducing C{xs}.
def _foldr(f, z, xs): """ Apply a function of two arguments cumulatively to the items of a sequence, from right to left, so as to reduce the sequence to a single value. @type f: C{callable} taking 2 arguments @param z: Initial value. @param xs: Sequence to reduce. @return: Single value resulting from reducing C{xs}. """ return reduce(lambda x, y: f(y, x), reversed(xs), z)
Parse text containing IRC formatting codes into structured information. Color codes are mapped from 0 to 15 and wrap around if greater than 15. @type text: C{str} @param text: Formatted text to parse. @return: Structured text and attributes. @since: 13.1
def parseFormattedText(text): """ Parse text containing IRC formatting codes into structured information. Color codes are mapped from 0 to 15 and wrap around if greater than 15. @type text: C{str} @param text: Formatted text to parse. @return: Structured text and attributes. @since: 13.1 """ state = _FormattingParser() for ch in text: state.process(ch) return state.complete()
Assemble formatted text from structured information. Currently handled formatting includes: bold, reverse, underline, mIRC color codes and the ability to remove all current formatting. It is worth noting that assembled text will always begin with the control code to disable other attributes for the sake of correctness. For example:: from twisted.words.protocols.irc 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. Available attributes are: - bold - reverseVideo - underline Available colors are: 0. white 1. black 2. blue 3. green 4. light red 5. red 6. magenta 7. orange 8. yellow 9. light green 10. cyan 11. light cyan 12. light blue 13. light magenta 14. gray 15. light gray @see: U{http://www.mirc.co.uk/help/color.txt} @param formatted: Structured text and attributes. @rtype: C{str} @return: String containing mIRC control sequences that mimic those specified by I{formatted}. @since: 13.1
def assembleFormattedText(formatted): """ Assemble formatted text from structured information. Currently handled formatting includes: bold, reverse, underline, mIRC color codes and the ability to remove all current formatting. It is worth noting that assembled text will always begin with the control code to disable other attributes for the sake of correctness. For example:: from twisted.words.protocols.irc 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. Available attributes are: - bold - reverseVideo - underline Available colors are: 0. white 1. black 2. blue 3. green 4. light red 5. red 6. magenta 7. orange 8. yellow 9. light green 10. cyan 11. light cyan 12. light blue 13. light magenta 14. gray 15. light gray @see: U{http://www.mirc.co.uk/help/color.txt} @param formatted: Structured text and attributes. @rtype: C{str} @return: String containing mIRC control sequences that mimic those specified by I{formatted}. @since: 13.1 """ return _textattributes.flatten(formatted, _FormattingState(), "toMIRCControlCodes")
Remove all formatting codes from C{text}, leaving only the text. @type text: C{str} @param text: Formatted text to parse. @rtype: C{str} @return: Plain text without any control sequences. @since: 13.1
def stripFormatting(text): """ Remove all formatting codes from C{text}, leaving only the text. @type text: C{str} @param text: Formatted text to parse. @rtype: C{str} @return: Plain text without any control sequences. @since: 13.1 """ formatted = parseFormattedText(text) return _textattributes.flatten(formatted, _textattributes.DefaultFormattingState())
Extract CTCP data from a string. @return: A C{dict} containing two keys: - C{'extended'}: A list of CTCP (tag, data) tuples. - C{'normal'}: A list of strings which were not inside a CTCP delimiter.
def ctcpExtract(message): """ Extract CTCP data from a string. @return: A C{dict} containing two keys: - C{'extended'}: A list of CTCP (tag, data) tuples. - C{'normal'}: A list of strings which were not inside a CTCP delimiter. """ extended_messages = [] normal_messages = [] retval = {"extended": extended_messages, "normal": normal_messages} messages = message.split(X_DELIM) odd = 0 # X1 extended data X2 nomal data X3 extended data X4 normal... while messages: if odd: extended_messages.append(messages.pop(0)) else: normal_messages.append(messages.pop(0)) odd = not odd extended_messages[:] = list(filter(None, extended_messages)) normal_messages[:] = list(filter(None, normal_messages)) extended_messages[:] = list(map(ctcpDequote, extended_messages)) for i in range(len(extended_messages)): m = extended_messages[i].split(SPC, 1) tag = m[0] if len(m) > 1: data = m[1] else: data = None extended_messages[i] = (tag, data) return retval
@type messages: a list of extended messages. An extended message is a (tag, data) tuple, where 'data' may be L{None}, a string, or a list of strings to be joined with whitespace. @returns: String
def ctcpStringify(messages): """ @type messages: a list of extended messages. An extended message is a (tag, data) tuple, where 'data' may be L{None}, a string, or a list of strings to be joined with whitespace. @returns: String """ coded_messages = [] for tag, data in messages: if data: if not isinstance(data, str): try: # data as list-of-strings data = " ".join(map(str, data)) except TypeError: # No? Then use it's %s representation. pass m = f"{tag} {data}" else: m = str(tag) m = ctcpQuote(m) m = f"{X_DELIM}{m}{X_DELIM}" coded_messages.append(m) line = "".join(coded_messages) return line
Client factory for XMPP 1.0 (only). This returns a L{xmlstream.XmlStreamFactory} with an L{XMPPAuthenticator} object to perform the stream initialization steps (such as authentication). @see: The notes at L{XMPPAuthenticator} describe how the C{jid} and C{password} parameters are to be used. @param jid: Jabber ID to connect with. @type jid: L{jid.JID} @param password: password to authenticate with. @type password: L{unicode} @param configurationForTLS: An object which creates appropriately configured TLS connections. This is passed to C{startTLS} on the transport and is preferably created using L{twisted.internet.ssl.optionsForClientTLS}. If L{None}, the default is to verify the server certificate against the trust roots as provided by the platform. See L{twisted.internet._sslverify.platformTrust}. @type configurationForTLS: L{IOpenSSLClientConnectionCreator} or L{None} @return: XML stream factory. @rtype: L{xmlstream.XmlStreamFactory}
def XMPPClientFactory(jid, password, configurationForTLS=None): """ Client factory for XMPP 1.0 (only). This returns a L{xmlstream.XmlStreamFactory} with an L{XMPPAuthenticator} object to perform the stream initialization steps (such as authentication). @see: The notes at L{XMPPAuthenticator} describe how the C{jid} and C{password} parameters are to be used. @param jid: Jabber ID to connect with. @type jid: L{jid.JID} @param password: password to authenticate with. @type password: L{unicode} @param configurationForTLS: An object which creates appropriately configured TLS connections. This is passed to C{startTLS} on the transport and is preferably created using L{twisted.internet.ssl.optionsForClientTLS}. If L{None}, the default is to verify the server certificate against the trust roots as provided by the platform. See L{twisted.internet._sslverify.platformTrust}. @type configurationForTLS: L{IOpenSSLClientConnectionCreator} or L{None} @return: XML stream factory. @rtype: L{xmlstream.XmlStreamFactory} """ a = XMPPAuthenticator(jid, password, configurationForTLS=configurationForTLS) return xmlstream.XmlStreamFactory(a)
XML stream factory for external server-side components. @param componentid: JID of the component. @type componentid: L{unicode} @param password: password used to authenticate to the server. @type password: C{str}
def componentFactory(componentid, password): """ XML stream factory for external server-side components. @param componentid: JID of the component. @type componentid: L{unicode} @param password: password used to authenticate to the server. @type password: C{str} """ a = ConnectComponentAuthenticator(componentid, password) return xmlstream.XmlStreamFactory(a)
Constructs a pre-built L{ServiceManager}, using the specified strport string.
def buildServiceManager(jid, password, strport): """ Constructs a pre-built L{ServiceManager}, using the specified strport string. """ svc = ServiceManager(jid, password) client_svc = jstrports.client(strport, svc.getFactory()) client_svc.setServiceParent(svc) return svc
Parses an error element. @param error: The error element to be parsed @type error: L{domish.Element} @param errorNamespace: The namespace of the elements that hold the error condition and text. @type errorNamespace: C{str} @return: Dictionary with extracted error information. If present, keys C{condition}, C{text}, C{textLang} have a string value, and C{appCondition} has an L{domish.Element} value. @rtype: C{dict}
def _parseError(error, errorNamespace): """ Parses an error element. @param error: The error element to be parsed @type error: L{domish.Element} @param errorNamespace: The namespace of the elements that hold the error condition and text. @type errorNamespace: C{str} @return: Dictionary with extracted error information. If present, keys C{condition}, C{text}, C{textLang} have a string value, and C{appCondition} has an L{domish.Element} value. @rtype: C{dict} """ condition = None text = None textLang = None appCondition = None for element in error.elements(): if element.uri == errorNamespace: if element.name == "text": text = str(element) textLang = element.getAttribute((NS_XML, "lang")) else: condition = element.name else: appCondition = element return { "condition": condition, "text": text, "textLang": textLang, "appCondition": appCondition, }
Build an exception object from a stream error. @param element: the stream error @type element: L{domish.Element} @return: the generated exception object @rtype: L{StreamError}
def exceptionFromStreamError(element): """ Build an exception object from a stream error. @param element: the stream error @type element: L{domish.Element} @return: the generated exception object @rtype: L{StreamError} """ error = _parseError(element, NS_XMPP_STREAMS) exception = StreamError( error["condition"], error["text"], error["textLang"], error["appCondition"] ) return exception
Build an exception object from an error stanza. @param stanza: the error stanza @type stanza: L{domish.Element} @return: the generated exception object @rtype: L{StanzaError}
def exceptionFromStanza(stanza): """ Build an exception object from an error stanza. @param stanza: the error stanza @type stanza: L{domish.Element} @return: the generated exception object @rtype: L{StanzaError} """ children = [] condition = text = textLang = appCondition = type = code = None for element in stanza.elements(): if element.name == "error" and element.uri == stanza.uri: code = element.getAttribute("code") type = element.getAttribute("type") error = _parseError(element, NS_XMPP_STANZAS) condition = error["condition"] text = error["text"] textLang = error["textLang"] appCondition = error["appCondition"] if not condition and code: condition, type = CODES_TO_CONDITIONS[code] text = str(stanza.error) else: children.append(element) if condition is None: # TODO: raise exception instead? return StanzaError(None) exception = StanzaError(condition, type, text, textLang, appCondition) exception.children = children exception.stanza = stanza return exception
Parse given JID string into its respective parts and apply stringprep. @param jidstring: string representation of a JID. @type jidstring: L{str} @return: tuple of (user, host, resource), each of type L{str} as the parsed and stringprep'd parts of the given JID. If the given string did not have a user or resource part, the respective field in the tuple will hold L{None}. @rtype: L{tuple}
def parse(jidstring: str) -> Tuple[Union[str, None], str, Union[str, None]]: """ Parse given JID string into its respective parts and apply stringprep. @param jidstring: string representation of a JID. @type jidstring: L{str} @return: tuple of (user, host, resource), each of type L{str} as the parsed and stringprep'd parts of the given JID. If the given string did not have a user or resource part, the respective field in the tuple will hold L{None}. @rtype: L{tuple} """ user = None host = None resource = None # Search for delimiters user_sep = jidstring.find("@") res_sep = jidstring.find("/") if user_sep == -1: if res_sep == -1: # host host = jidstring else: # host/resource host = jidstring[0:res_sep] resource = jidstring[res_sep + 1 :] or None else: if res_sep == -1: # user@host user = jidstring[0:user_sep] or None host = jidstring[user_sep + 1 :] else: if user_sep < res_sep: # user@host/resource user = jidstring[0:user_sep] or None host = jidstring[user_sep + 1 : user_sep + (res_sep - user_sep)] resource = jidstring[res_sep + 1 :] or None else: # host/resource (with an @ in resource) host = jidstring[0:res_sep] resource = jidstring[res_sep + 1 :] or None return prep(user, host, resource)
Perform stringprep on all JID fragments. @param user: The user part of the JID. @type user: L{str} @param host: The host part of the JID. @type host: L{str} @param resource: The resource part of the JID. @type resource: L{str} @return: The given parts with stringprep applied. @rtype: L{tuple}
def prep( user: Union[str, None], host: str, resource: Union[str, None] ) -> Tuple[Union[str, None], str, Union[str, None]]: """ Perform stringprep on all JID fragments. @param user: The user part of the JID. @type user: L{str} @param host: The host part of the JID. @type host: L{str} @param resource: The resource part of the JID. @type resource: L{str} @return: The given parts with stringprep applied. @rtype: L{tuple} """ if user: try: user = nodeprep.prepare(str(user)) except UnicodeError: raise InvalidFormat("Invalid character in username") else: user = None if not host: raise InvalidFormat("Server address required.") else: try: host = nameprep.prepare(str(host)) except UnicodeError: raise InvalidFormat("Invalid character in hostname") if resource: try: resource = resourceprep.prepare(str(resource)) except UnicodeError: raise InvalidFormat("Invalid character in resource") else: resource = None return (user, host, resource)
Return interned JID. @rtype: L{JID}
def internJID(jidstring): """ Return interned JID. @rtype: L{JID} """ if jidstring in __internJIDs: return __internJIDs[jidstring] else: j = JID(jidstring) __internJIDs[jidstring] = j return j
For the moment, parse TCP or SSL connections the same
def _parseTCPSSL(factory, domain, port): """For the moment, parse TCP or SSL connections the same""" return (domain, int(port), factory), {}
Parse the SASL feature to extract the available mechanism names.
def get_mechanisms(xs): """ Parse the SASL feature to extract the available mechanism names. """ mechanisms = [] for element in xs.features[(NS_XMPP_SASL, "mechanisms")].elements(): if element.name == "mechanism": mechanisms.append(str(element)) return mechanisms
Decode base64 encoded string. This helper performs regular decoding of a base64 encoded string, but also rejects any characters that are not in the base64 alphabet and padding occurring elsewhere from the last or last two characters, as specified in section 14.9 of RFC 3920. This safeguards against various attack vectors among which the creation of a covert channel that "leaks" information.
def fromBase64(s): """ Decode base64 encoded string. This helper performs regular decoding of a base64 encoded string, but also rejects any characters that are not in the base64 alphabet and padding occurring elsewhere from the last or last two characters, as specified in section 14.9 of RFC 3920. This safeguards against various attack vectors among which the creation of a covert channel that "leaks" information. """ if base64Pattern.match(s) is None: raise SASLIncorrectEncodingError() try: return b64decode(s) except Exception as e: raise SASLIncorrectEncodingError(str(e))
Create a SHA1-digest string of a session identifier and password. @param sid: The stream session identifier. @type sid: C{unicode}. @param password: The password to be hashed. @type password: C{unicode}.
def hashPassword(sid, password): """ Create a SHA1-digest string of a session identifier and password. @param sid: The stream session identifier. @type sid: C{unicode}. @param password: The password to be hashed. @type password: C{unicode}. """ if not isinstance(sid, str): raise TypeError("The session identifier must be a unicode object") if not isinstance(password, str): raise TypeError("The password must be a unicode object") input = f"{sid}{password}" return sha1(input.encode("utf-8")).hexdigest()
Enhances an XmlStream for iq response tracking. This makes an L{XmlStream} object provide L{IIQResponseTracker}. When a response is an error iq stanza, the deferred has its errback invoked with a failure that holds a L{StanzaError<error.StanzaError>} that is easier to examine.
def upgradeWithIQResponseTracker(xs): """ Enhances an XmlStream for iq response tracking. This makes an L{XmlStream} object provide L{IIQResponseTracker}. When a response is an error iq stanza, the deferred has its errback invoked with a failure that holds a L{StanzaError<error.StanzaError>} that is easier to examine. """ def callback(iq): """ Handle iq response by firing associated deferred. """ if getattr(iq, "handled", False): return try: d = xs.iqDeferreds[iq["id"]] except KeyError: pass else: del xs.iqDeferreds[iq["id"]] iq.handled = True if iq["type"] == "error": d.errback(error.exceptionFromStanza(iq)) else: d.callback(iq) def disconnected(_): """ Make sure deferreds do not linger on after disconnect. This errbacks all deferreds of iq's for which no response has been received with a L{ConnectionLost} failure. Otherwise, the deferreds will never be fired. """ iqDeferreds = xs.iqDeferreds xs.iqDeferreds = {} for d in iqDeferreds.values(): d.errback(ConnectionLost()) xs.iqDeferreds = {} xs.iqDefaultTimeout = getattr(xs, "iqDefaultTimeout", None) xs.addObserver(xmlstream.STREAM_END_EVENT, disconnected) xs.addObserver('/iq[@type="result"]', callback) xs.addObserver('/iq[@type="error"]', callback) directlyProvides(xs, ijabber.IIQResponseTracker)
Create a response stanza from another stanza. This takes the addressing and id attributes from a stanza to create a (new, empty) response stanza. The addressing attributes are swapped and the id copied. Optionally, the stanza type of the response can be specified. @param stanza: the original stanza @type stanza: L{domish.Element} @param stanzaType: optional response stanza type @type stanzaType: C{str} @return: the response stanza. @rtype: L{domish.Element}
def toResponse(stanza, stanzaType=None): """ Create a response stanza from another stanza. This takes the addressing and id attributes from a stanza to create a (new, empty) response stanza. The addressing attributes are swapped and the id copied. Optionally, the stanza type of the response can be specified. @param stanza: the original stanza @type stanza: L{domish.Element} @param stanzaType: optional response stanza type @type stanzaType: C{str} @return: the response stanza. @rtype: L{domish.Element} """ toAddr = stanza.getAttribute("from") fromAddr = stanza.getAttribute("to") stanzaID = stanza.getAttribute("id") response = domish.Element((None, stanza.name)) if toAddr: response["to"] = toAddr if fromAddr: response["from"] = fromAddr if stanzaID: response["id"] = stanzaID if stanzaType: response["type"] = stanzaType return response
Internal method for splitting a prefixed Element name into its respective parts
def _splitPrefix(name): """Internal method for splitting a prefixed Element name into its respective parts""" ntok = name.split(":", 1) if len(ntok) == 2: return ntok else: return (None, ntok[0])
Escape text to proper XML form, per section 2.3 in the XML specification. @type text: C{str} @param text: Text to escape @type isattrib: C{bool} @param isattrib: Triggers escaping of characters necessary for use as attribute values
def escapeToXml(text, isattrib=0): """Escape text to proper XML form, per section 2.3 in the XML specification. @type text: C{str} @param text: Text to escape @type isattrib: C{bool} @param isattrib: Triggers escaping of characters necessary for use as attribute values """ text = text.replace("&", "&amp;") text = text.replace("<", "&lt;") text = text.replace(">", "&gt;") if isattrib == 1: text = text.replace("'", "&apos;") text = text.replace('"', "&quot;") return text
Filters items in a list by class
def generateOnlyInterface(list, int): """Filters items in a list by class""" for n in list: if int.providedBy(n): yield n
Filters Element items in a list with matching name and URI.
def generateElementsQNamed(list, name, uri): """Filters Element items in a list with matching name and URI.""" for n in list: if IElement.providedBy(n) and n.name == name and n.uri == uri: yield n
Filters Element items in a list with matching name, regardless of URI.
def generateElementsNamed(list, name): """Filters Element items in a list with matching name, regardless of URI.""" for n in list: if IElement.providedBy(n) and n.name == name: yield n
Preferred method to construct an ElementStream Uses Expat-based stream if available, and falls back to Sux if necessary.
def elementStream(): """Preferred method to construct an ElementStream Uses Expat-based stream if available, and falls back to Sux if necessary. """ try: es = ExpatElementStream() return es except ImportError: if SuxElementStream is None: raise Exception("No parsers available :(") es = SuxElementStream() return es
Internal method which selects the function object
def Function(fname): """ Internal method which selects the function object """ klassname = "_%s_Function" % fname c = globals()[klassname]() return c