response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
On FreeBSD, kill the embedded interface indices in link-local scoped addresses. @param family: The address family of the packed address - one of the I{socket.AF_*} constants. @param packed: The packed representation of the address (ie, the bytes of a I{in_addr} field). @type packed: L{bytes} @return: The packed address with any FreeBSD-specific extra bits cleared. @rtype: L{bytes} @see: U{https://twistedmatrix.com/trac/ticket/6843} @see: U{http://www.freebsd.org/doc/en/books/developers-handbook/ipv6.html#ipv6-scope-index} @note: Indications are that the need for this will be gone in FreeBSD >=10.
def _maybeCleanupScopeIndex(family, packed): """ On FreeBSD, kill the embedded interface indices in link-local scoped addresses. @param family: The address family of the packed address - one of the I{socket.AF_*} constants. @param packed: The packed representation of the address (ie, the bytes of a I{in_addr} field). @type packed: L{bytes} @return: The packed address with any FreeBSD-specific extra bits cleared. @rtype: L{bytes} @see: U{https://twistedmatrix.com/trac/ticket/6843} @see: U{http://www.freebsd.org/doc/en/books/developers-handbook/ipv6.html#ipv6-scope-index} @note: Indications are that the need for this will be gone in FreeBSD >=10. """ if sys.platform.startswith("freebsd") and packed[:2] == b"\xfe\x80": return packed[:2] + b"\x00\x00" + packed[4:] return packed
Call C{getifaddrs(3)} and return a list of tuples of interface name, address family, and human-readable address representing its results.
def _interfaces(): """ Call C{getifaddrs(3)} and return a list of tuples of interface name, address family, and human-readable address representing its results. """ ifaddrs = ifaddrs_p() if getifaddrs(pointer(ifaddrs)) < 0: raise OSError() results = [] try: while ifaddrs: if ifaddrs[0].ifa_addr: family = ifaddrs[0].ifa_addr[0].sin_family if family == AF_INET: addr = cast(ifaddrs[0].ifa_addr, POINTER(sockaddr_in)) elif family == AF_INET6: addr = cast(ifaddrs[0].ifa_addr, POINTER(sockaddr_in6)) else: addr = None if addr: packed = bytes(addr[0].sin_addr.in_addr[:]) packed = _maybeCleanupScopeIndex(family, packed) results.append( (ifaddrs[0].ifa_name, family, inet_ntop(family, packed)) ) ifaddrs = ifaddrs[0].ifa_next finally: freeifaddrs(ifaddrs) return results
Return a list of strings in colon-hex format representing all the link local IPv6 addresses available on the system, as reported by I{getifaddrs(3)}.
def posixGetLinkLocalIPv6Addresses(): """ Return a list of strings in colon-hex format representing all the link local IPv6 addresses available on the system, as reported by I{getifaddrs(3)}. """ retList = [] for interface, family, address in _interfaces(): interface = nativeString(interface) address = nativeString(address) if family == socket.AF_INET6 and address.startswith("fe80:"): retList.append(f"{address}%{interface}") return retList
Return a list of strings in colon-hex format representing all the link local IPv6 addresses available on the system, as reported by I{WSAIoctl}/C{SIO_ADDRESS_LIST_QUERY}.
def win32GetLinkLocalIPv6Addresses(): """ Return a list of strings in colon-hex format representing all the link local IPv6 addresses available on the system, as reported by I{WSAIoctl}/C{SIO_ADDRESS_LIST_QUERY}. """ s = socket(AF_INET6, SOCK_STREAM) size = 4096 retBytes = c_int() for i in range(2): buf = create_string_buffer(size) ret = WSAIoctl( s.fileno(), SIO_ADDRESS_LIST_QUERY, 0, 0, buf, size, byref(retBytes), 0, 0 ) # WSAIoctl might fail with WSAEFAULT, which means there was not enough # space in the buffer we gave it. There's no way to check the errno # until Python 2.6, so we don't even try. :/ Maybe if retBytes is still # 0 another error happened, though. if ret and retBytes.value: size = retBytes.value else: break # If it failed, then we'll just have to give up. Still no way to see why. if ret: raise RuntimeError("WSAIoctl failure") addrList = cast(buf, POINTER(make_SAL(0))) addrCount = addrList[0].iAddressCount addrList = cast(buf, POINTER(make_SAL(addrCount))) addressStringBufLength = 1024 addressStringBuf = create_unicode_buffer(addressStringBufLength) retList = [] for i in range(addrList[0].iAddressCount): retBytes.value = addressStringBufLength address = addrList[0].Address[i] ret = WSAAddressToString( address.lpSockaddr, address.iSockaddrLength, 0, addressStringBuf, byref(retBytes), ) if ret: raise RuntimeError("WSAAddressToString failure") retList.append(wstring_at(addressStringBuf)) return [addr for addr in retList if "%" in addr]
Create a L{FileLogObserver} that emits text to a specified (writable) file-like object. @param outFile: A file-like object. Ideally one should be passed which accepts text data. Otherwise, UTF-8 L{bytes} will be used. @param timeFormat: The format to use when adding timestamp prefixes to logged events. If L{None}, or for events with no C{"log_timestamp"} key, the default timestamp prefix of C{"-"} is used. @return: A file log observer.
def textFileLogObserver( outFile: IO[Any], timeFormat: Optional[str] = timeFormatRFC3339 ) -> FileLogObserver: """ Create a L{FileLogObserver} that emits text to a specified (writable) file-like object. @param outFile: A file-like object. Ideally one should be passed which accepts text data. Otherwise, UTF-8 L{bytes} will be used. @param timeFormat: The format to use when adding timestamp prefixes to logged events. If L{None}, or for events with no C{"log_timestamp"} key, the default timestamp prefix of C{"-"} is used. @return: A file log observer. """ def formatEvent(event: LogEvent) -> Optional[str]: return formatEventAsClassicLogText( event, formatTime=lambda e: formatTime(e, timeFormat) ) return FileLogObserver(outFile, formatEvent)
Determine whether an event should be logged, based on the result of C{predicates}. By default, the result is C{True}; so if there are no predicates, everything will be logged. If any predicate returns C{yes}, then we will immediately return C{True}. If any predicate returns C{no}, then we will immediately return C{False}. As predicates return C{maybe}, we keep calling the next predicate until we run out, at which point we return C{True}. @param predicates: The predicates to use. @param event: An event @return: True if the message should be forwarded on, C{False} if not.
def shouldLogEvent(predicates: Iterable[ILogFilterPredicate], event: LogEvent) -> bool: """ Determine whether an event should be logged, based on the result of C{predicates}. By default, the result is C{True}; so if there are no predicates, everything will be logged. If any predicate returns C{yes}, then we will immediately return C{True}. If any predicate returns C{no}, then we will immediately return C{False}. As predicates return C{maybe}, we keep calling the next predicate until we run out, at which point we return C{True}. @param predicates: The predicates to use. @param event: An event @return: True if the message should be forwarded on, C{False} if not. """ for predicate in predicates: result = predicate(event) if result == PredicateResult.yes: return True if result == PredicateResult.no: return False if result == PredicateResult.maybe: continue raise TypeError(f"Invalid predicate result: {result!r}") return True
Flatten the given event by pre-associating format fields with specific objects and callable results in a L{dict} put into the C{"log_flattened"} key in the event. @param event: A logging event.
def flattenEvent(event: LogEvent) -> None: """ Flatten the given event by pre-associating format fields with specific objects and callable results in a L{dict} put into the C{"log_flattened"} key in the event. @param event: A logging event. """ if event.get("log_format", None) is None: return if "log_flattened" in event: fields = event["log_flattened"] else: fields = {} keyFlattener = KeyFlattener() for literalText, fieldName, formatSpec, conversion in aFormatter.parse( event["log_format"] ): if fieldName is None: continue if conversion != "r": conversion = "s" flattenedKey = keyFlattener.flatKey(fieldName, formatSpec, conversion) structuredKey = keyFlattener.flatKey(fieldName, formatSpec, "") if flattenedKey in fields: # We've already seen and handled this key continue if fieldName.endswith("()"): fieldName = fieldName[:-2] callit = True else: callit = False field = aFormatter.get_field(fieldName, (), event) fieldValue = field[0] if conversion == "r": conversionFunction = repr else: # Above: if conversion is not "r", it's "s" conversionFunction = str if callit: fieldValue = fieldValue() flattenedValue = conversionFunction(fieldValue) fields[flattenedKey] = flattenedValue fields[structuredKey] = fieldValue if fields: event["log_flattened"] = fields
Extract a given format field from the given event. @param field: A string describing a format field or log key. This is the text that would normally fall between a pair of curly braces in a format string: for example, C{"key[2].attribute"}. If a conversion is specified (the thing after the C{"!"} character in a format field) then the result will always be str. @param event: A log event. @return: A value extracted from the field. @raise KeyError: if the field is not found in the given event.
def extractField(field: str, event: LogEvent) -> Any: """ Extract a given format field from the given event. @param field: A string describing a format field or log key. This is the text that would normally fall between a pair of curly braces in a format string: for example, C{"key[2].attribute"}. If a conversion is specified (the thing after the C{"!"} character in a format field) then the result will always be str. @param event: A log event. @return: A value extracted from the field. @raise KeyError: if the field is not found in the given event. """ keyFlattener = KeyFlattener() [[literalText, fieldName, formatSpec, conversion]] = aFormatter.parse( "{" + field + "}" ) assert fieldName is not None key = keyFlattener.flatKey(fieldName, formatSpec, conversion) if "log_flattened" not in event: flattenEvent(event) return event["log_flattened"][key]
Format an event which has been flattened with L{flattenEvent}. @param event: A logging event. @return: A formatted string.
def flatFormat(event: LogEvent) -> str: """ Format an event which has been flattened with L{flattenEvent}. @param event: A logging event. @return: A formatted string. """ fieldValues = event["log_flattened"] keyFlattener = KeyFlattener() s = [] for literalText, fieldName, formatSpec, conversion in aFormatter.parse( event["log_format"] ): s.append(literalText) if fieldName is not None: key = keyFlattener.flatKey(fieldName, formatSpec, conversion or "s") s.append(str(fieldValues[key])) return "".join(s)
Formats an event as text, using the format in C{event["log_format"]}. This implementation should never raise an exception; if the formatting cannot be done, the returned string will describe the event generically so that a useful message is emitted regardless. @param event: A logging event. @return: A formatted string.
def formatEvent(event: LogEvent) -> str: """ Formats an event as text, using the format in C{event["log_format"]}. This implementation should never raise an exception; if the formatting cannot be done, the returned string will describe the event generically so that a useful message is emitted regardless. @param event: A logging event. @return: A formatted string. """ return eventAsText( event, includeTraceback=False, includeTimestamp=False, includeSystem=False, )
Formats an event as text that describes the event generically and a formatting error. @param event: A logging event. @param error: The formatting error. @return: A formatted string.
def formatUnformattableEvent(event: LogEvent, error: BaseException) -> str: """ Formats an event as text that describes the event generically and a formatting error. @param event: A logging event. @param error: The formatting error. @return: A formatted string. """ try: return "Unable to format event {event!r}: {error}".format( event=event, error=error ) except BaseException: # Yikes, something really nasty happened. # # Try to recover as much formattable data as possible; hopefully at # least the namespace is sane, which will help you find the offending # logger. failure = Failure() text = ", ".join( " = ".join((safe_repr(key), safe_repr(value))) for key, value in event.items() ) return ( "MESSAGE LOST: unformattable object logged: {error}\n" "Recoverable data: {text}\n" "Exception during formatting:\n{failure}".format( error=safe_repr(error), failure=failure, text=text ) )
Format a timestamp as text. Example:: >>> from time import time >>> from twisted.logger import formatTime >>> >>> t = time() >>> formatTime(t) u'2013-10-22T14:19:11-0700' >>> formatTime(t, timeFormat="%Y/%W") # Year and week number u'2013/42' >>> @param when: A timestamp. @param timeFormat: A time format. @param default: Text to return if C{when} or C{timeFormat} is L{None}. @return: A formatted time.
def formatTime( when: Optional[float], timeFormat: Optional[str] = timeFormatRFC3339, default: str = "-", ) -> str: """ Format a timestamp as text. Example:: >>> from time import time >>> from twisted.logger import formatTime >>> >>> t = time() >>> formatTime(t) u'2013-10-22T14:19:11-0700' >>> formatTime(t, timeFormat="%Y/%W") # Year and week number u'2013/42' >>> @param when: A timestamp. @param timeFormat: A time format. @param default: Text to return if C{when} or C{timeFormat} is L{None}. @return: A formatted time. """ if timeFormat is None or when is None: return default else: tz = FixedOffsetTimeZone.fromLocalTimeStamp(when) datetime = DateTime.fromtimestamp(when, tz) return str(datetime.strftime(timeFormat))
Format an event as a line of human-readable text for, e.g. traditional log file output. The output format is C{"{timeStamp} [{system}] {event}\n"}, where: - C{timeStamp} is computed by calling the given C{formatTime} callable on the event's C{"log_time"} value - C{system} is the event's C{"log_system"} value, if set, otherwise, the C{"log_namespace"} and C{"log_level"}, joined by a C{"#"}. Each defaults to C{"-"} is not set. - C{event} is the event, as formatted by L{formatEvent}. Example:: >>> from time import time >>> from twisted.logger import formatEventAsClassicLogText >>> from twisted.logger import LogLevel >>> >>> formatEventAsClassicLogText(dict()) # No format, returns None >>> formatEventAsClassicLogText(dict(log_format="Hello!")) u'- [-#-] Hello!\n' >>> formatEventAsClassicLogText(dict( ... log_format="Hello!", ... log_time=time(), ... log_namespace="my_namespace", ... log_level=LogLevel.info, ... )) u'2013-10-22T17:30:02-0700 [my_namespace#info] Hello!\n' >>> formatEventAsClassicLogText(dict( ... log_format="Hello!", ... log_time=time(), ... log_system="my_system", ... )) u'2013-11-11T17:22:06-0800 [my_system] Hello!\n' >>> @param event: an event. @param formatTime: A time formatter @return: A formatted event, or L{None} if no output is appropriate.
def formatEventAsClassicLogText( event: LogEvent, formatTime: Callable[[Optional[float]], str] = formatTime ) -> Optional[str]: """ Format an event as a line of human-readable text for, e.g. traditional log file output. The output format is C{"{timeStamp} [{system}] {event}\\n"}, where: - C{timeStamp} is computed by calling the given C{formatTime} callable on the event's C{"log_time"} value - C{system} is the event's C{"log_system"} value, if set, otherwise, the C{"log_namespace"} and C{"log_level"}, joined by a C{"#"}. Each defaults to C{"-"} is not set. - C{event} is the event, as formatted by L{formatEvent}. Example:: >>> from time import time >>> from twisted.logger import formatEventAsClassicLogText >>> from twisted.logger import LogLevel >>> >>> formatEventAsClassicLogText(dict()) # No format, returns None >>> formatEventAsClassicLogText(dict(log_format="Hello!")) u'- [-#-] Hello!\\n' >>> formatEventAsClassicLogText(dict( ... log_format="Hello!", ... log_time=time(), ... log_namespace="my_namespace", ... log_level=LogLevel.info, ... )) u'2013-10-22T17:30:02-0700 [my_namespace#info] Hello!\\n' >>> formatEventAsClassicLogText(dict( ... log_format="Hello!", ... log_time=time(), ... log_system="my_system", ... )) u'2013-11-11T17:22:06-0800 [my_system] Hello!\\n' >>> @param event: an event. @param formatTime: A time formatter @return: A formatted event, or L{None} if no output is appropriate. """ eventText = eventAsText(event, formatTime=formatTime) if not eventText: return None eventText = eventText.replace("\n", "\n\t") return eventText + "\n"
Check to see if C{key} ends with parentheses ("C{()}"); if not, wrap up the result of C{get} in a L{PotentialCallWrapper}. Otherwise, call the result of C{get} first, before wrapping it up. @param key: The last dotted segment of a formatting key, as parsed by L{Formatter.vformat}, which may end in C{()}. @param getter: A function which takes a string and returns some other object, to be formatted and stringified for a log. @return: A L{PotentialCallWrapper} that will wrap up the result to allow for subsequent usages of parens to defer execution to log-format time.
def keycall(key: str, getter: Callable[[str], Any]) -> PotentialCallWrapper: """ Check to see if C{key} ends with parentheses ("C{()}"); if not, wrap up the result of C{get} in a L{PotentialCallWrapper}. Otherwise, call the result of C{get} first, before wrapping it up. @param key: The last dotted segment of a formatting key, as parsed by L{Formatter.vformat}, which may end in C{()}. @param getter: A function which takes a string and returns some other object, to be formatted and stringified for a log. @return: A L{PotentialCallWrapper} that will wrap up the result to allow for subsequent usages of parens to defer execution to log-format time. """ callit = key.endswith("()") realKey = key[:-2] if callit else key value = getter(realKey) if callit: value = value() return PotentialCallWrapper(value)
Format a string like L{str.format}, but: - taking only a name mapping; no positional arguments - with the additional syntax that an empty set of parentheses correspond to a formatting item that should be called, and its result C{str}'d, rather than calling C{str} on the element directly as normal. For example:: >>> formatWithCall("{string}, {function()}.", ... dict(string="just a string", ... function=lambda: "a function")) 'just a string, a function.' @param formatString: A PEP-3101 format string. @param mapping: A L{dict}-like object to format. @return: The string with formatted values interpolated.
def formatWithCall(formatString: str, mapping: Mapping[str, Any]) -> str: """ Format a string like L{str.format}, but: - taking only a name mapping; no positional arguments - with the additional syntax that an empty set of parentheses correspond to a formatting item that should be called, and its result C{str}'d, rather than calling C{str} on the element directly as normal. For example:: >>> formatWithCall("{string}, {function()}.", ... dict(string="just a string", ... function=lambda: "a function")) 'just a string, a function.' @param formatString: A PEP-3101 format string. @param mapping: A L{dict}-like object to format. @return: The string with formatted values interpolated. """ return str(aFormatter.vformat(formatString, (), CallMapping(mapping)))
Formats an event as a string, using the format in C{event["log_format"]}. This implementation should never raise an exception; if the formatting cannot be done, the returned string will describe the event generically so that a useful message is emitted regardless. @param event: A logging event. @return: A formatted string.
def _formatEvent(event: LogEvent) -> str: """ Formats an event as a string, using the format in C{event["log_format"]}. This implementation should never raise an exception; if the formatting cannot be done, the returned string will describe the event generically so that a useful message is emitted regardless. @param event: A logging event. @return: A formatted string. """ try: if "log_flattened" in event: return flatFormat(event) format = cast(Optional[Union[str, bytes]], event.get("log_format", None)) if format is None: return "" # Make sure format is text. if isinstance(format, str): pass elif isinstance(format, bytes): format = format.decode("utf-8") else: raise TypeError(f"Log format must be str, not {format!r}") return formatWithCall(format, event) except BaseException as e: return formatUnformattableEvent(event, e)
Format a failure traceback, assuming UTF-8 and using a replacement strategy for errors. Every effort is made to provide a usable traceback, but should not that not be possible, a message and the captured exception are logged. @param failure: The failure to retrieve a traceback from. @return: The formatted traceback.
def _formatTraceback(failure: Failure) -> str: """ Format a failure traceback, assuming UTF-8 and using a replacement strategy for errors. Every effort is made to provide a usable traceback, but should not that not be possible, a message and the captured exception are logged. @param failure: The failure to retrieve a traceback from. @return: The formatted traceback. """ try: traceback = failure.getTraceback() except BaseException as e: traceback = "(UNABLE TO OBTAIN TRACEBACK FROM EVENT):" + str(e) return traceback
Format the system specified in the event in the "log_system" key if set, otherwise the C{"log_namespace"} and C{"log_level"}, joined by a C{"#"}. Each defaults to C{"-"} is not set. If formatting fails completely, "UNFORMATTABLE" is returned. @param event: The event containing the system specification. @return: A formatted string representing the "log_system" key.
def _formatSystem(event: LogEvent) -> str: """ Format the system specified in the event in the "log_system" key if set, otherwise the C{"log_namespace"} and C{"log_level"}, joined by a C{"#"}. Each defaults to C{"-"} is not set. If formatting fails completely, "UNFORMATTABLE" is returned. @param event: The event containing the system specification. @return: A formatted string representing the "log_system" key. """ system = cast(Optional[str], event.get("log_system", None)) if system is None: level = cast(Optional[NamedConstant], event.get("log_level", None)) if level is None: levelName = "-" else: levelName = level.name system = "{namespace}#{level}".format( namespace=cast(str, event.get("log_namespace", "-")), level=levelName, ) else: try: system = str(system) except Exception: system = "UNFORMATTABLE" return system
Format an event as text. Optionally, attach timestamp, traceback, and system information. The full output format is: C{"{timeStamp} [{system}] {event}\n{traceback}\n"} where: - C{timeStamp} is the event's C{"log_time"} value formatted with the provided C{formatTime} callable. - C{system} is the event's C{"log_system"} value, if set, otherwise, the C{"log_namespace"} and C{"log_level"}, joined by a C{"#"}. Each defaults to C{"-"} is not set. - C{event} is the event, as formatted by L{formatEvent}. - C{traceback} is the traceback if the event contains a C{"log_failure"} key. In the event the original traceback cannot be formatted, a message indicating the failure will be substituted. If the event cannot be formatted, and no traceback exists, an empty string is returned, even if includeSystem or includeTimestamp are true. @param event: A logging event. @param includeTraceback: If true and a C{"log_failure"} key exists, append a traceback. @param includeTimestamp: If true include a formatted timestamp before the event. @param includeSystem: If true, include the event's C{"log_system"} value. @param formatTime: A time formatter @return: A formatted string with specified options. @since: Twisted 18.9.0
def eventAsText( event: LogEvent, includeTraceback: bool = True, includeTimestamp: bool = True, includeSystem: bool = True, formatTime: Callable[[float], str] = formatTime, ) -> str: r""" Format an event as text. Optionally, attach timestamp, traceback, and system information. The full output format is: C{"{timeStamp} [{system}] {event}\n{traceback}\n"} where: - C{timeStamp} is the event's C{"log_time"} value formatted with the provided C{formatTime} callable. - C{system} is the event's C{"log_system"} value, if set, otherwise, the C{"log_namespace"} and C{"log_level"}, joined by a C{"#"}. Each defaults to C{"-"} is not set. - C{event} is the event, as formatted by L{formatEvent}. - C{traceback} is the traceback if the event contains a C{"log_failure"} key. In the event the original traceback cannot be formatted, a message indicating the failure will be substituted. If the event cannot be formatted, and no traceback exists, an empty string is returned, even if includeSystem or includeTimestamp are true. @param event: A logging event. @param includeTraceback: If true and a C{"log_failure"} key exists, append a traceback. @param includeTimestamp: If true include a formatted timestamp before the event. @param includeSystem: If true, include the event's C{"log_system"} value. @param formatTime: A time formatter @return: A formatted string with specified options. @since: Twisted 18.9.0 """ eventText = _formatEvent(event) if includeTraceback and "log_failure" in event: f = event["log_failure"] traceback = _formatTraceback(f) eventText = "\n".join((eventText, traceback)) if not eventText: return eventText timeStamp = "" if includeTimestamp: timeStamp = "".join([formatTime(cast(float, event.get("log_time", None))), " "]) system = "" if includeSystem: system = "".join(["[", _formatSystem(event), "]", " "]) return "{timeStamp}{system}{eventText}".format( timeStamp=timeStamp, system=system, eventText=eventText, )
Convert a failure to a JSON-serializable data structure. @param failure: A failure to serialize. @return: a mapping of strings to ... stuff, mostly reminiscent of L{Failure.__getstate__}
def failureAsJSON(failure: Failure) -> JSONDict: """ Convert a failure to a JSON-serializable data structure. @param failure: A failure to serialize. @return: a mapping of strings to ... stuff, mostly reminiscent of L{Failure.__getstate__} """ return dict( failure.__getstate__(), type=dict( __module__=failure.type.__module__, __name__=failure.type.__name__, ), )
Load a L{Failure} from a dictionary deserialized from JSON. @param failureDict: a JSON-deserialized object like one previously returned by L{failureAsJSON}. @return: L{Failure}
def failureFromJSON(failureDict: JSONDict) -> Failure: """ Load a L{Failure} from a dictionary deserialized from JSON. @param failureDict: a JSON-deserialized object like one previously returned by L{failureAsJSON}. @return: L{Failure} """ f = Failure.__new__(Failure) typeInfo = failureDict["type"] failureDict["type"] = type(typeInfo["__name__"], (), typeInfo) f.__setstate__(failureDict) return f
Dictionary-to-object-translation hook for certain value types used within the logging system. @see: the C{object_hook} parameter to L{json.load} @param aDict: A dictionary loaded from a JSON object. @return: C{aDict} itself, or the object represented by C{aDict}
def objectLoadHook(aDict: JSONDict) -> object: """ Dictionary-to-object-translation hook for certain value types used within the logging system. @see: the C{object_hook} parameter to L{json.load} @param aDict: A dictionary loaded from a JSON object. @return: C{aDict} itself, or the object represented by C{aDict} """ if "__class_uuid__" in aDict: return uuidToLoader[UUID(aDict["__class_uuid__"])](aDict) return aDict
Object-to-serializable hook for certain value types used within the logging system. @see: the C{default} parameter to L{json.dump} @param pythonObject: Any object. @return: If the object is one of the special types the logging system supports, a specially-formatted dictionary; otherwise, a marker dictionary indicating that it could not be serialized.
def objectSaveHook(pythonObject: object) -> JSONDict: """ Object-to-serializable hook for certain value types used within the logging system. @see: the C{default} parameter to L{json.dump} @param pythonObject: Any object. @return: If the object is one of the special types the logging system supports, a specially-formatted dictionary; otherwise, a marker dictionary indicating that it could not be serialized. """ for predicate, uuid, saver, loader in classInfo: if predicate(pythonObject): result = saver(pythonObject) result["__class_uuid__"] = str(uuid) return result return {"unpersistable": True}
Encode an event as JSON, flattening it if necessary to preserve as much structure as possible. Not all structure from the log event will be preserved when it is serialized. @param event: A log event dictionary. @return: A string of the serialized JSON; note that this will contain no newline characters, and may thus safely be stored in a line-delimited file.
def eventAsJSON(event: LogEvent) -> str: """ Encode an event as JSON, flattening it if necessary to preserve as much structure as possible. Not all structure from the log event will be preserved when it is serialized. @param event: A log event dictionary. @return: A string of the serialized JSON; note that this will contain no newline characters, and may thus safely be stored in a line-delimited file. """ def default(unencodable: object) -> Union[JSONDict, str]: """ Serialize an object not otherwise serializable by L{dumps}. @param unencodable: An unencodable object. @return: C{unencodable}, serialized """ if isinstance(unencodable, bytes): return unencodable.decode("charmap") return objectSaveHook(unencodable) flattenEvent(event) return dumps(event, default=default, skipkeys=True)
Decode a log event from JSON. @param eventText: The output of a previous call to L{eventAsJSON} @return: A reconstructed version of the log event.
def eventFromJSON(eventText: str) -> JSONDict: """ Decode a log event from JSON. @param eventText: The output of a previous call to L{eventAsJSON} @return: A reconstructed version of the log event. """ return cast(JSONDict, loads(eventText, object_hook=objectLoadHook))
Create a L{FileLogObserver} that emits JSON-serialized events to a specified (writable) file-like object. Events are written in the following form:: RS + JSON + NL C{JSON} is the serialized event, which is JSON text. C{NL} is a newline (C{"\n"}). C{RS} is a record separator. By default, this is a single RS character (C{"\x1e"}), which makes the default output conform to the IETF draft document "draft-ietf-json-text-sequence-13". @param outFile: A file-like object. Ideally one should be passed which accepts L{str} data. Otherwise, UTF-8 L{bytes} will be used. @param recordSeparator: The record separator to use. @return: A file log observer.
def jsonFileLogObserver( outFile: IO[Any], recordSeparator: str = "\x1e" ) -> FileLogObserver: """ Create a L{FileLogObserver} that emits JSON-serialized events to a specified (writable) file-like object. Events are written in the following form:: RS + JSON + NL C{JSON} is the serialized event, which is JSON text. C{NL} is a newline (C{"\\n"}). C{RS} is a record separator. By default, this is a single RS character (C{"\\x1e"}), which makes the default output conform to the IETF draft document "draft-ietf-json-text-sequence-13". @param outFile: A file-like object. Ideally one should be passed which accepts L{str} data. Otherwise, UTF-8 L{bytes} will be used. @param recordSeparator: The record separator to use. @return: A file log observer. """ return FileLogObserver( outFile, lambda event: f"{recordSeparator}{eventAsJSON(event)}\n" )
Load events from a file previously saved with L{jsonFileLogObserver}. Event records that are truncated or otherwise unreadable are ignored. @param inFile: A (readable) file-like object. Data read from C{inFile} should be L{str} or UTF-8 L{bytes}. @param recordSeparator: The expected record separator. If L{None}, attempt to automatically detect the record separator from one of C{"\x1e"} or C{""}. @param bufferSize: The size of the read buffer used while reading from C{inFile}. @return: Log events as read from C{inFile}.
def eventsFromJSONLogFile( inFile: IO[Any], recordSeparator: Optional[str] = None, bufferSize: int = 4096, ) -> Iterable[LogEvent]: """ Load events from a file previously saved with L{jsonFileLogObserver}. Event records that are truncated or otherwise unreadable are ignored. @param inFile: A (readable) file-like object. Data read from C{inFile} should be L{str} or UTF-8 L{bytes}. @param recordSeparator: The expected record separator. If L{None}, attempt to automatically detect the record separator from one of C{"\\x1e"} or C{""}. @param bufferSize: The size of the read buffer used while reading from C{inFile}. @return: Log events as read from C{inFile}. """ def asBytes(s: AnyStr) -> bytes: if isinstance(s, bytes): return s else: return s.encode("utf-8") def eventFromBytearray(record: bytearray) -> Optional[LogEvent]: try: text = bytes(record).decode("utf-8") except UnicodeDecodeError: log.error( "Unable to decode UTF-8 for JSON record: {record!r}", record=bytes(record), ) return None try: return eventFromJSON(text) except ValueError: log.error("Unable to read JSON record: {record!r}", record=bytes(record)) return None if recordSeparator is None: first = asBytes(inFile.read(1)) if first == b"\x1e": # This looks json-text-sequence compliant. recordSeparatorBytes = first else: # Default to simpler newline-separated stream, which does not use # a record separator. recordSeparatorBytes = b"" else: recordSeparatorBytes = asBytes(recordSeparator) first = b"" if recordSeparatorBytes == b"": recordSeparatorBytes = b"\n" # Split on newlines below eventFromRecord = eventFromBytearray else: def eventFromRecord(record: bytearray) -> Optional[LogEvent]: if record[-1] == ord("\n"): return eventFromBytearray(record) else: log.error( "Unable to read truncated JSON record: {record!r}", record=bytes(record), ) return None buffer = bytearray(first) while True: newData = inFile.read(bufferSize) if not newData: if len(buffer) > 0: event = eventFromRecord(buffer) if event is not None: yield event break buffer += asBytes(newData) records = buffer.split(recordSeparatorBytes) for record in records[:-1]: if len(record) > 0: event = eventFromRecord(record) if event is not None: yield event buffer = records[-1]
Publish an old-style (L{twisted.python.log}) event to a new-style (L{twisted.logger}) observer. @note: It's possible that a new-style event was sent to a L{LegacyLogObserverWrapper}, and may now be getting sent back to a new-style observer. In this case, it's already a new-style event, adapted to also look like an old-style event, and we don't need to tweak it again to be a new-style event, hence this checks for already-defined new-style keys. @param observer: A new-style observer to handle this event. @param eventDict: An L{old-style <twisted.python.log>}, log event. @param textFromEventDict: callable that can format an old-style event as a string. Passed here rather than imported to avoid circular dependency.
def publishToNewObserver( observer: ILogObserver, eventDict: Dict[str, Any], textFromEventDict: Callable[[Dict[str, Any]], Optional[str]], ) -> None: """ Publish an old-style (L{twisted.python.log}) event to a new-style (L{twisted.logger}) observer. @note: It's possible that a new-style event was sent to a L{LegacyLogObserverWrapper}, and may now be getting sent back to a new-style observer. In this case, it's already a new-style event, adapted to also look like an old-style event, and we don't need to tweak it again to be a new-style event, hence this checks for already-defined new-style keys. @param observer: A new-style observer to handle this event. @param eventDict: An L{old-style <twisted.python.log>}, log event. @param textFromEventDict: callable that can format an old-style event as a string. Passed here rather than imported to avoid circular dependency. """ if "log_time" not in eventDict: eventDict["log_time"] = eventDict["time"] if "log_format" not in eventDict: text = textFromEventDict(eventDict) if text is not None: eventDict["log_text"] = text eventDict["log_format"] = "{log_text}" if "log_level" not in eventDict: if "logLevel" in eventDict: try: level = fromStdlibLogLevelMapping[eventDict["logLevel"]] except KeyError: level = None elif "isError" in eventDict: if eventDict["isError"]: level = LogLevel.critical else: level = LogLevel.info else: level = LogLevel.info if level is not None: eventDict["log_level"] = level if "log_namespace" not in eventDict: eventDict["log_namespace"] = "log_legacy" if "log_system" not in eventDict and "system" in eventDict: eventDict["log_system"] = eventDict["system"] observer(eventDict)
I{ILogObserver} that does nothing with the events it sees.
def bitbucketLogObserver(event: LogEvent) -> None: """ I{ILogObserver} that does nothing with the events it sees. """
Reverse the above mapping, adding both the numerical keys used above and the corresponding string keys also used by python logging. @return: the reversed mapping
def _reverseLogLevelMapping() -> Mapping[int, NamedConstant]: """ Reverse the above mapping, adding both the numerical keys used above and the corresponding string keys also used by python logging. @return: the reversed mapping """ mapping = {} for logLevel, pyLogLevel in toStdlibLogLevelMapping.items(): mapping[pyLogLevel] = logLevel mapping[stdlibLogging.getLevelName(pyLogLevel)] = logLevel return mapping
Format a trace (that is, the contents of the C{log_trace} key of a log event) as a visual indication of the message's propagation through various observers. @param trace: the contents of the C{log_trace} key from an event. @return: A multi-line string with indentation and arrows indicating the flow of the message through various observers.
def formatTrace(trace: LogTrace) -> str: """ Format a trace (that is, the contents of the C{log_trace} key of a log event) as a visual indication of the message's propagation through various observers. @param trace: the contents of the C{log_trace} key from an event. @return: A multi-line string with indentation and arrows indicating the flow of the message through various observers. """ def formatWithName(obj: object) -> str: if hasattr(obj, "name"): return f"{obj} ({obj.name})" else: return f"{obj}" result = [] lineage: List[Logger] = [] for parent, child in trace: if not lineage or lineage[-1] is not parent: if parent in lineage: while lineage[-1] is not parent: lineage.pop() else: if not lineage: result.append(f"{formatWithName(parent)}\n") lineage.append(parent) result.append(" " * len(lineage)) result.append(f"-> {formatWithName(child)}\n") return "".join(result)
Compare two sequences of log events, examining only the the keys which are present in both. @param test: a test case doing the comparison @param actualEvents: A list of log events that were emitted by a logger. @param expectedEvents: A list of log events that were expected by a test.
def compareEvents( test: unittest.TestCase, actualEvents: List[LogEvent], expectedEvents: List[LogEvent], ) -> None: """ Compare two sequences of log events, examining only the the keys which are present in both. @param test: a test case doing the comparison @param actualEvents: A list of log events that were emitted by a logger. @param expectedEvents: A list of log events that were expected by a test. """ if len(actualEvents) != len(expectedEvents): test.assertEqual(actualEvents, expectedEvents) allMergedKeys = set() for event in expectedEvents: allMergedKeys |= set(event.keys()) def simplify(event: LogEvent) -> LogEvent: copy = event.copy() for key in event.keys(): if key not in allMergedKeys: copy.pop(key) return copy simplifiedActual = [simplify(event) for event in actualEvents] test.assertEqual(simplifiedActual, expectedEvents)
Assert a few things about the result of L{eventAsJSON}, then return it. @param testCase: The L{TestCase} with which to perform the assertions. @param savedJSON: The result of L{eventAsJSON}. @return: C{savedJSON} @raise AssertionError: If any of the preconditions fail.
def savedJSONInvariants(testCase: TestCase, savedJSON: str) -> str: """ Assert a few things about the result of L{eventAsJSON}, then return it. @param testCase: The L{TestCase} with which to perform the assertions. @param savedJSON: The result of L{eventAsJSON}. @return: C{savedJSON} @raise AssertionError: If any of the preconditions fail. """ testCase.assertIsInstance(savedJSON, str) testCase.assertEqual(savedJSON.count("\n"), 0) return savedJSON
Retrive the file name and line number immediately after where this function is called. @return: the file name and line number
def nextLine() -> Tuple[Optional[str], int]: """ Retrive the file name and line number immediately after where this function is called. @return: the file name and line number """ caller = currentframe(1) return ( getsourcefile(sys.modules[caller.f_globals["__name__"]]), caller.f_lineno + 1, )
Construct a 2-tuple of C{(StreamHandler, BytesIO)} for testing interaction with the 'logging' module. @return: handler and io object
def handlerAndBytesIO() -> tuple[StreamHandler[TextIOWrapper], BytesIO]: """ Construct a 2-tuple of C{(StreamHandler, BytesIO)} for testing interaction with the 'logging' module. @return: handler and io object """ output = BytesIO() template = py_logging.BASIC_FORMAT stream = TextIOWrapper(output, encoding="utf-8", newline="\n") formatter = Formatter(template) handler = StreamHandler(stream) handler.setFormatter(formatter) return handler, output
Parse a line from an aliases file. @type result: L{dict} mapping L{bytes} to L{list} of L{bytes} @param result: A dictionary mapping username to aliases to which the results of parsing the line are added. @type line: L{bytes} @param line: A line from an aliases file. @type filename: L{bytes} @param filename: The full or relative path to the aliases file. @type lineNo: L{int} @param lineNo: The position of the line within the aliases file.
def handle(result, line, filename, lineNo): """ Parse a line from an aliases file. @type result: L{dict} mapping L{bytes} to L{list} of L{bytes} @param result: A dictionary mapping username to aliases to which the results of parsing the line are added. @type line: L{bytes} @param line: A line from an aliases file. @type filename: L{bytes} @param filename: The full or relative path to the aliases file. @type lineNo: L{int} @param lineNo: The position of the line within the aliases file. """ parts = [p.strip() for p in line.split(":", 1)] if len(parts) != 2: fmt = "Invalid format on line %d of alias file %s." arg = (lineNo, filename) log.err(fmt % arg) else: user, alias = parts result.setdefault(user.strip(), []).extend(map(str.strip, alias.split(",")))
Load a file containing email aliases. Lines in the file should be formatted like so:: username: alias1, alias2, ..., aliasN Aliases beginning with a C{|} will be treated as programs, will be run, and the message will be written to their stdin. Aliases beginning with a C{:} will be treated as a file containing additional aliases for the username. Aliases beginning with a C{/} will be treated as the full pathname to a file to which the message will be appended. Aliases without a host part will be assumed to be addresses on localhost. If a username is specified multiple times, the aliases for each are joined together as if they had all been on one line. Lines beginning with a space or a tab are continuations of the previous line. Lines beginning with a C{#} are comments. @type domains: L{dict} mapping L{bytes} to L{IDomain} provider @param domains: A mapping of domain name to domain object. @type filename: L{bytes} or L{None} @param filename: The full or relative path to a file from which to load aliases. If omitted, the C{fp} parameter must be specified. @type fp: file-like object or L{None} @param fp: The file from which to load aliases. If specified, the C{filename} parameter is ignored. @rtype: L{dict} mapping L{bytes} to L{AliasGroup} @return: A mapping from username to group of aliases.
def loadAliasFile(domains, filename=None, fp=None): """ Load a file containing email aliases. Lines in the file should be formatted like so:: username: alias1, alias2, ..., aliasN Aliases beginning with a C{|} will be treated as programs, will be run, and the message will be written to their stdin. Aliases beginning with a C{:} will be treated as a file containing additional aliases for the username. Aliases beginning with a C{/} will be treated as the full pathname to a file to which the message will be appended. Aliases without a host part will be assumed to be addresses on localhost. If a username is specified multiple times, the aliases for each are joined together as if they had all been on one line. Lines beginning with a space or a tab are continuations of the previous line. Lines beginning with a C{#} are comments. @type domains: L{dict} mapping L{bytes} to L{IDomain} provider @param domains: A mapping of domain name to domain object. @type filename: L{bytes} or L{None} @param filename: The full or relative path to a file from which to load aliases. If omitted, the C{fp} parameter must be specified. @type fp: file-like object or L{None} @param fp: The file from which to load aliases. If specified, the C{filename} parameter is ignored. @rtype: L{dict} mapping L{bytes} to L{AliasGroup} @return: A mapping from username to group of aliases. """ result = {} close = False if fp is None: fp = open(filename) close = True else: filename = getattr(fp, "name", "<unknown>") i = 0 prev = "" try: for line in fp: i += 1 line = line.rstrip() if line.lstrip().startswith("#"): continue elif line.startswith(" ") or line.startswith("\t"): prev = prev + line else: if prev: handle(result, prev, filename, i) prev = line finally: if close: fp.close() if prev: handle(result, prev, filename, i) for u, a in result.items(): result[u] = AliasGroup(a, domains, u) return result
Generate a bounce message for an undeliverable email message. @type message: a file-like object @param message: The undeliverable message. @type failedFrom: L{bytes} or L{unicode} @param failedFrom: The originator of the undeliverable message. @type failedTo: L{bytes} or L{unicode} @param failedTo: The destination of the undeliverable message. @type transcript: L{bytes} or L{unicode} @param transcript: An error message to include in the bounce message. @type encoding: L{str} or L{unicode} @param encoding: Encoding to use, default: utf-8 @rtype: 3-L{tuple} of (E{1}) L{bytes}, (E{2}) L{bytes}, (E{3}) L{bytes} @return: The originator, the destination and the contents of the bounce message. The destination of the bounce message is the originator of the undeliverable message.
def generateBounce(message, failedFrom, failedTo, transcript="", encoding="utf-8"): """ Generate a bounce message for an undeliverable email message. @type message: a file-like object @param message: The undeliverable message. @type failedFrom: L{bytes} or L{unicode} @param failedFrom: The originator of the undeliverable message. @type failedTo: L{bytes} or L{unicode} @param failedTo: The destination of the undeliverable message. @type transcript: L{bytes} or L{unicode} @param transcript: An error message to include in the bounce message. @type encoding: L{str} or L{unicode} @param encoding: Encoding to use, default: utf-8 @rtype: 3-L{tuple} of (E{1}) L{bytes}, (E{2}) L{bytes}, (E{3}) L{bytes} @return: The originator, the destination and the contents of the bounce message. The destination of the bounce message is the originator of the undeliverable message. """ if isinstance(failedFrom, bytes): failedFrom = failedFrom.decode(encoding) if isinstance(failedTo, bytes): failedTo = failedTo.decode(encoding) if not transcript: transcript = """\ I'm sorry, the following address has permanent errors: {failedTo}. I've given up, and I will not retry the message again. """.format( failedTo=failedTo ) failedAddress = email.utils.parseaddr(failedTo)[1] data = { "boundary": "{}_{}_{}".format(time.time(), os.getpid(), "XXXXX"), "ctime": time.ctime(time.time()), "failedAddress": failedAddress, "failedDomain": failedAddress.split("@", 1)[1], "failedFrom": failedFrom, "failedTo": failedTo, "messageID": smtp.messageid(uniq="bounce"), "message": message, "transcript": transcript, } fp = StringIO() fp.write(BOUNCE_FORMAT.format(**data)) orig = message.tell() message.seek(0, SEEK_END) sz = message.tell() message.seek(orig, SEEK_SET) if sz > 10000: while 1: line = message.readline() if isinstance(line, bytes): line = line.decode(encoding) if len(line) <= 0: break fp.write(line) else: messageContent = message.read() if isinstance(messageContent, bytes): messageContent = messageContent.decode(encoding) fp.write(messageContent) return b"", failedFrom.encode(encoding), fp.getvalue().encode(encoding)
Swap C{this} with C{that} if C{this} is C{ifIs}. @param this: The object that may be replaced. @param that: The object that may replace C{this}. @param ifIs: An object whose identity will be compared to C{this}.
def _swap(this, that, ifIs): """ Swap C{this} with C{that} if C{this} is C{ifIs}. @param this: The object that may be replaced. @param that: The object that may replace C{this}. @param ifIs: An object whose identity will be compared to C{this}. """ return that if this is ifIs else this
Swap each element in each pair in C{of} with C{that} it is C{ifIs}. @param of: A list of 2-L{tuple}s, whose members may be the object C{that} @type of: L{list} of 2-L{tuple}s @param ifIs: An object whose identity will be compared to members of each pair in C{of} @return: A L{list} of 2-L{tuple}s with all occurences of C{ifIs} replaced with C{that}
def _swapAllPairs(of, that, ifIs): """ Swap each element in each pair in C{of} with C{that} it is C{ifIs}. @param of: A list of 2-L{tuple}s, whose members may be the object C{that} @type of: L{list} of 2-L{tuple}s @param ifIs: An object whose identity will be compared to members of each pair in C{of} @return: A L{list} of 2-L{tuple}s with all occurences of C{ifIs} replaced with C{that} """ return [ (_swap(first, that, ifIs), _swap(second, that, ifIs)) for first, second in of ]
Parse a message set search key into a C{MessageSet}. @type s: L{bytes} @param s: A string description of an id list, for example "1:3, 4:*" @type lastMessageId: L{int} @param lastMessageId: The last message sequence id or UID, depending on whether we are parsing the list in UID or sequence id context. The caller should pass in the correct value. @rtype: C{MessageSet} @return: A C{MessageSet} that contains the ids defined in the list
def parseIdList(s, lastMessageId=None): """ Parse a message set search key into a C{MessageSet}. @type s: L{bytes} @param s: A string description of an id list, for example "1:3, 4:*" @type lastMessageId: L{int} @param lastMessageId: The last message sequence id or UID, depending on whether we are parsing the list in UID or sequence id context. The caller should pass in the correct value. @rtype: C{MessageSet} @return: A C{MessageSet} that contains the ids defined in the list """ res = MessageSet() parts = s.split(b",") for p in parts: if b":" in p: low, high = p.split(b":", 1) try: if low == b"*": low = None else: low = int(low) if high == b"*": high = None else: high = int(high) if low is high is None: # *:* does not make sense raise IllegalIdentifierError(p) # non-positive values are illegal according to RFC 3501 if (low is not None and low <= 0) or (high is not None and high <= 0): raise IllegalIdentifierError(p) # star means "highest value of an id in the mailbox" high = high or lastMessageId low = low or lastMessageId res.add(low, high) except ValueError: raise IllegalIdentifierError(p) else: try: if p == b"*": p = None else: p = int(p) if p is not None and p <= 0: raise IllegalIdentifierError(p) except ValueError: raise IllegalIdentifierError(p) else: res.extend(p or lastMessageId) return res
Create a query string Among the accepted keywords are:: all : If set to a true value, search all messages in the current mailbox answered : If set to a true value, search messages flagged with \Answered bcc : A substring to search the BCC header field for before : Search messages with an internal date before this value. The given date should be a string in the format of 'DD-Mon-YYYY'. For example, '03-Mar-2003'. body : A substring to search the body of the messages for cc : A substring to search the CC header field for deleted : If set to a true value, search messages flagged with \Deleted draft : If set to a true value, search messages flagged with \Draft flagged : If set to a true value, search messages flagged with \Flagged from : A substring to search the From header field for header : A two-tuple of a header name and substring to search for in that header keyword : Search for messages with the given keyword set larger : Search for messages larger than this number of octets messages : Search only the given message sequence set. new : If set to a true value, search messages flagged with \Recent but not \Seen old : If set to a true value, search messages not flagged with \Recent on : Search messages with an internal date which is on this date. The given date should be a string in the format of 'DD-Mon-YYYY'. For example, '03-Mar-2003'. recent : If set to a true value, search for messages flagged with \Recent seen : If set to a true value, search for messages flagged with \Seen sentbefore : Search for messages with an RFC822 'Date' header before this date. The given date should be a string in the format of 'DD-Mon-YYYY'. For example, '03-Mar-2003'. senton : Search for messages with an RFC822 'Date' header which is on this date The given date should be a string in the format of 'DD-Mon-YYYY'. For example, '03-Mar-2003'. sentsince : Search for messages with an RFC822 'Date' header which is after this date. The given date should be a string in the format of 'DD-Mon-YYYY'. For example, '03-Mar-2003'. since : Search for messages with an internal date that is after this date.. The given date should be a string in the format of 'DD-Mon-YYYY'. For example, '03-Mar-2003'. smaller : Search for messages smaller than this number of octets subject : A substring to search the 'subject' header for text : A substring to search the entire message for to : A substring to search the 'to' header for uid : Search only the messages in the given message set unanswered : If set to a true value, search for messages not flagged with \Answered undeleted : If set to a true value, search for messages not flagged with \Deleted undraft : If set to a true value, search for messages not flagged with \Draft unflagged : If set to a true value, search for messages not flagged with \Flagged unkeyword : Search for messages without the given keyword set unseen : If set to a true value, search for messages not flagged with \Seen @type sorted: C{bool} @param sorted: If true, the output will be sorted, alphabetically. The standard does not require it, but it makes testing this function easier. The default is zero, and this should be acceptable for any application. @rtype: L{str} @return: The formatted query string
def Query(sorted=0, **kwarg): """ Create a query string Among the accepted keywords are:: all : If set to a true value, search all messages in the current mailbox answered : If set to a true value, search messages flagged with \\Answered bcc : A substring to search the BCC header field for before : Search messages with an internal date before this value. The given date should be a string in the format of 'DD-Mon-YYYY'. For example, '03-Mar-2003'. body : A substring to search the body of the messages for cc : A substring to search the CC header field for deleted : If set to a true value, search messages flagged with \\Deleted draft : If set to a true value, search messages flagged with \\Draft flagged : If set to a true value, search messages flagged with \\Flagged from : A substring to search the From header field for header : A two-tuple of a header name and substring to search for in that header keyword : Search for messages with the given keyword set larger : Search for messages larger than this number of octets messages : Search only the given message sequence set. new : If set to a true value, search messages flagged with \\Recent but not \\Seen old : If set to a true value, search messages not flagged with \\Recent on : Search messages with an internal date which is on this date. The given date should be a string in the format of 'DD-Mon-YYYY'. For example, '03-Mar-2003'. recent : If set to a true value, search for messages flagged with \\Recent seen : If set to a true value, search for messages flagged with \\Seen sentbefore : Search for messages with an RFC822 'Date' header before this date. The given date should be a string in the format of 'DD-Mon-YYYY'. For example, '03-Mar-2003'. senton : Search for messages with an RFC822 'Date' header which is on this date The given date should be a string in the format of 'DD-Mon-YYYY'. For example, '03-Mar-2003'. sentsince : Search for messages with an RFC822 'Date' header which is after this date. The given date should be a string in the format of 'DD-Mon-YYYY'. For example, '03-Mar-2003'. since : Search for messages with an internal date that is after this date.. The given date should be a string in the format of 'DD-Mon-YYYY'. For example, '03-Mar-2003'. smaller : Search for messages smaller than this number of octets subject : A substring to search the 'subject' header for text : A substring to search the entire message for to : A substring to search the 'to' header for uid : Search only the messages in the given message set unanswered : If set to a true value, search for messages not flagged with \\Answered undeleted : If set to a true value, search for messages not flagged with \\Deleted undraft : If set to a true value, search for messages not flagged with \\Draft unflagged : If set to a true value, search for messages not flagged with \\Flagged unkeyword : Search for messages without the given keyword set unseen : If set to a true value, search for messages not flagged with \\Seen @type sorted: C{bool} @param sorted: If true, the output will be sorted, alphabetically. The standard does not require it, but it makes testing this function easier. The default is zero, and this should be acceptable for any application. @rtype: L{str} @return: The formatted query string """ cmd = [] keys = kwarg.keys() if sorted: keys = _sorted(keys) for k in keys: v = kwarg[k] k = k.upper() if k in _SIMPLE_BOOL and v: cmd.append(k) elif k == "HEADER": cmd.extend([k, str(v[0]), str(v[1])]) elif k == "KEYWORD" or k == "UNKEYWORD": # Discard anything that does not fit into an "atom". Perhaps turn # the case where this actually removes bytes from the value into a # warning and then an error, eventually. See #6277. v = _nonAtomRE.sub("", v) cmd.extend([k, v]) elif k not in _NO_QUOTES: if isinstance(v, MessageSet): fmt = '"%s"' elif isinstance(v, str): fmt = '"%s"' else: fmt = '"%d"' cmd.extend([k, fmt % (v,)]) elif isinstance(v, int): cmd.extend([k, "%d" % (v,)]) else: cmd.extend([k, f"{v}"]) if len(cmd) > 1: return "(" + " ".join(cmd) + ")" else: return " ".join(cmd)
The disjunction of two or more queries
def Or(*args): """ The disjunction of two or more queries """ if len(args) < 2: raise IllegalQueryError(args) elif len(args) == 2: return "(OR %s %s)" % args else: return f"(OR {args[0]} {Or(*args[1:])})"
The negation of a query
def Not(query): """The negation of a query""" return f"(NOT {query})"
Split a string into whitespace delimited tokens Tokens that would otherwise be separated but are surrounded by " remain as a single token. Any token that is not quoted and is equal to "NIL" is tokenized as L{None}. @type s: L{bytes} @param s: The string to be split @rtype: L{list} of L{bytes} @return: A list of the resulting tokens @raise MismatchedQuoting: Raised if an odd number of quotes are present
def splitQuoted(s): """ Split a string into whitespace delimited tokens Tokens that would otherwise be separated but are surrounded by \" remain as a single token. Any token that is not quoted and is equal to \"NIL\" is tokenized as L{None}. @type s: L{bytes} @param s: The string to be split @rtype: L{list} of L{bytes} @return: A list of the resulting tokens @raise MismatchedQuoting: Raised if an odd number of quotes are present """ s = s.strip() result = [] word = [] inQuote = inWord = False qu = _matchingString('"', s) esc = _matchingString("\x5c", s) empty = _matchingString("", s) nil = _matchingString("NIL", s) for i, c in enumerate(iterbytes(s)): if c == qu: if i and s[i - 1 : i] == esc: word.pop() word.append(qu) elif not inQuote: inQuote = True else: inQuote = False result.append(empty.join(word)) word = [] elif ( not inWord and not inQuote and c not in (qu + (string.whitespace.encode("ascii"))) ): inWord = True word.append(c) elif inWord and not inQuote and c in string.whitespace.encode("ascii"): w = empty.join(word) if w == nil: result.append(None) else: result.append(w) word = [] inWord = False elif inWord or inQuote: word.append(c) if inQuote: raise MismatchedQuoting(s) if inWord: w = empty.join(word) if w == nil: result.append(None) else: result.append(w) return result
Turns a list of length-one strings and lists into a list of longer strings and lists. For example, ['a', 'b', ['c', 'd']] is returned as ['ab', ['cd']] @type results: L{list} of L{bytes} and L{list} @param results: The list to be collapsed @rtype: L{list} of L{bytes} and L{list} @return: A new list which is the collapsed form of C{results}
def collapseStrings(results): """ Turns a list of length-one strings and lists into a list of longer strings and lists. For example, ['a', 'b', ['c', 'd']] is returned as ['ab', ['cd']] @type results: L{list} of L{bytes} and L{list} @param results: The list to be collapsed @rtype: L{list} of L{bytes} and L{list} @return: A new list which is the collapsed form of C{results} """ copy = [] begun = None pred = lambda e: isinstance(e, tuple) tran = { 0: lambda e: splitQuoted(b"".join(e)), 1: lambda e: [b"".join([i[0] for i in e])], } for i, c in enumerate(results): if isinstance(c, list): if begun is not None: copy.extend(splitOn(results[begun:i], pred, tran)) begun = None copy.append(collapseStrings(c)) elif begun is None: begun = i if begun is not None: copy.extend(splitOn(results[begun:], pred, tran)) return copy
Parse an s-exp-like string into a more useful data structure. @type s: L{bytes} @param s: The s-exp-like string to parse @rtype: L{list} of L{bytes} and L{list} @return: A list containing the tokens present in the input. @raise MismatchedNesting: Raised if the number or placement of opening or closing parenthesis is invalid.
def parseNestedParens(s, handleLiteral=1): """ Parse an s-exp-like string into a more useful data structure. @type s: L{bytes} @param s: The s-exp-like string to parse @rtype: L{list} of L{bytes} and L{list} @return: A list containing the tokens present in the input. @raise MismatchedNesting: Raised if the number or placement of opening or closing parenthesis is invalid. """ s = s.strip() inQuote = 0 contentStack = [[]] try: i = 0 L = len(s) while i < L: c = s[i : i + 1] if inQuote: if c == b"\\": contentStack[-1].append(s[i : i + 2]) i += 2 continue elif c == b'"': inQuote = not inQuote contentStack[-1].append(c) i += 1 else: if c == b'"': contentStack[-1].append(c) inQuote = not inQuote i += 1 elif handleLiteral and c == b"{": end = s.find(b"}", i) if end == -1: raise ValueError("Malformed literal") literalSize = int(s[i + 1 : end]) contentStack[-1].append((s[end + 3 : end + 3 + literalSize],)) i = end + 3 + literalSize elif c == b"(" or c == b"[": contentStack.append([]) i += 1 elif c == b")" or c == b"]": contentStack[-2].append(contentStack.pop()) i += 1 else: contentStack[-1].append(c) i += 1 except IndexError: raise MismatchedNesting(s) if len(contentStack) != 1: raise MismatchedNesting(s) return collapseStrings(contentStack[0])
Turn a nested list structure into an s-exp-like string. Strings in C{items} will be sent as literals if they contain CR or LF, otherwise they will be quoted. References to None in C{items} will be translated to the atom NIL. Objects with a 'read' attribute will have it called on them with no arguments and the returned string will be inserted into the output as a literal. Integers will be converted to strings and inserted into the output unquoted. Instances of C{DontQuoteMe} will be converted to strings and inserted into the output unquoted. This function used to be much nicer, and only quote things that really needed to be quoted (and C{DontQuoteMe} did not exist), however, many broken IMAP4 clients were unable to deal with this level of sophistication, forcing the current behavior to be adopted for practical reasons. @type items: Any iterable @rtype: L{str}
def collapseNestedLists(items): """ Turn a nested list structure into an s-exp-like string. Strings in C{items} will be sent as literals if they contain CR or LF, otherwise they will be quoted. References to None in C{items} will be translated to the atom NIL. Objects with a 'read' attribute will have it called on them with no arguments and the returned string will be inserted into the output as a literal. Integers will be converted to strings and inserted into the output unquoted. Instances of C{DontQuoteMe} will be converted to strings and inserted into the output unquoted. This function used to be much nicer, and only quote things that really needed to be quoted (and C{DontQuoteMe} did not exist), however, many broken IMAP4 clients were unable to deal with this level of sophistication, forcing the current behavior to be adopted for practical reasons. @type items: Any iterable @rtype: L{str} """ pieces = [] for i in items: if isinstance(i, str): # anything besides ASCII will have to wait for an RFC 5738 # implementation. See # https://twistedmatrix.com/trac/ticket/9258 i = i.encode("ascii") if i is None: pieces.extend([b" ", b"NIL"]) elif isinstance(i, int): pieces.extend([b" ", networkString(str(i))]) elif isinstance(i, DontQuoteMe): pieces.extend([b" ", i.value]) elif isinstance(i, bytes): # XXX warning if _needsLiteral(i): pieces.extend([b" ", b"{%d}" % (len(i),), IMAP4Server.delimiter, i]) else: pieces.extend([b" ", _quote(i)]) elif hasattr(i, "read"): d = i.read() pieces.extend([b" ", b"{%d}" % (len(d),), IMAP4Server.delimiter, d]) else: pieces.extend([b" ", b"(" + collapseNestedLists(i) + b")"]) return b"".join(pieces[1:])
Return a two-tuple of the main and subtype of the given message.
def _getContentType(msg): """ Return a two-tuple of the main and subtype of the given message. """ attrs = None mm = msg.getHeaders(False, "content-type").get("content-type", "") mm = "".join(mm.splitlines()) if mm: mimetype = mm.split(";") type = mimetype[0].split("/", 1) if len(type) == 1: major = type[0] minor = None else: # length must be 2, because of split('/', 1) major, minor = type attrs = dict(x.strip().lower().split("=", 1) for x in mimetype[1:]) else: major = minor = None return major, minor, attrs
Construct an appropriate type of message structure object for the given message object. @param message: A L{IMessagePart} provider @return: A L{_MessageStructure} instance of the most specific type available for the given message, determined by inspecting the MIME type of the message.
def _getMessageStructure(message): """ Construct an appropriate type of message structure object for the given message object. @param message: A L{IMessagePart} provider @return: A L{_MessageStructure} instance of the most specific type available for the given message, determined by inspecting the MIME type of the message. """ main, subtype, attrs = _getContentType(message) if main is not None: main = main.lower() if subtype is not None: subtype = subtype.lower() if main == "multipart": return _MultipartMessageStructure(message, subtype, attrs) elif (main, subtype) == ("message", "rfc822"): return _RFC822MessageStructure(message, main, subtype, attrs) elif main == "text": return _TextMessageStructure(message, main, subtype, attrs) else: return _SinglepartMessageStructure(message, main, subtype, attrs)
RFC 3501, 7.4.2, BODYSTRUCTURE:: A parenthesized list that describes the [MIME-IMB] body structure of a message. This is computed by the server by parsing the [MIME-IMB] header fields, defaulting various fields as necessary. For example, a simple text message of 48 lines and 2279 octets can have a body structure of: ("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 2279 48) This is represented as:: ["TEXT", "PLAIN", ["CHARSET", "US-ASCII"], None, None, "7BIT", 2279, 48] These basic fields are documented in the RFC as: 1. body type A string giving the content media type name as defined in [MIME-IMB]. 2. body subtype A string giving the content subtype name as defined in [MIME-IMB]. 3. body parameter parenthesized list A parenthesized list of attribute/value pairs [e.g., ("foo" "bar" "baz" "rag") where "bar" is the value of "foo" and "rag" is the value of "baz"] as defined in [MIME-IMB]. 4. body id A string giving the content id as defined in [MIME-IMB]. 5. body description A string giving the content description as defined in [MIME-IMB]. 6. body encoding A string giving the content transfer encoding as defined in [MIME-IMB]. 7. body size A number giving the size of the body in octets. Note that this size is the size in its transfer encoding and not the resulting size after any decoding. Put another way, the body structure is a list of seven elements. The semantics of the elements of this list are: 1. Byte string giving the major MIME type 2. Byte string giving the minor MIME type 3. A list giving the Content-Type parameters of the message 4. A byte string giving the content identifier for the message part, or None if it has no content identifier. 5. A byte string giving the content description for the message part, or None if it has no content description. 6. A byte string giving the Content-Encoding of the message body 7. An integer giving the number of octets in the message body The RFC goes on:: Multiple parts are indicated by parenthesis nesting. Instead of a body type as the first element of the parenthesized list, there is a sequence of one or more nested body structures. The second element of the parenthesized list is the multipart subtype (mixed, digest, parallel, alternative, etc.). For example, a two part message consisting of a text and a BASE64-encoded text attachment can have a body structure of: (("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 1152 23)("TEXT" "PLAIN" ("CHARSET" "US-ASCII" "NAME" "cc.diff") "<[email protected]>" "Compiler diff" "BASE64" 4554 73) "MIXED") This is represented as:: [["TEXT", "PLAIN", ["CHARSET", "US-ASCII"], None, None, "7BIT", 1152, 23], ["TEXT", "PLAIN", ["CHARSET", "US-ASCII", "NAME", "cc.diff"], "<[email protected]>", "Compiler diff", "BASE64", 4554, 73], "MIXED"] In other words, a list of N + 1 elements, where N is the number of parts in the message. The first N elements are structures as defined by the previous section. The last element is the minor MIME subtype of the multipart message. Additionally, the RFC describes extension data:: Extension data follows the multipart subtype. Extension data is never returned with the BODY fetch, but can be returned with a BODYSTRUCTURE fetch. Extension data, if present, MUST be in the defined order. The C{extended} flag controls whether extension data might be returned with the normal data.
def getBodyStructure(msg, extended=False): """ RFC 3501, 7.4.2, BODYSTRUCTURE:: A parenthesized list that describes the [MIME-IMB] body structure of a message. This is computed by the server by parsing the [MIME-IMB] header fields, defaulting various fields as necessary. For example, a simple text message of 48 lines and 2279 octets can have a body structure of: ("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 2279 48) This is represented as:: ["TEXT", "PLAIN", ["CHARSET", "US-ASCII"], None, None, "7BIT", 2279, 48] These basic fields are documented in the RFC as: 1. body type A string giving the content media type name as defined in [MIME-IMB]. 2. body subtype A string giving the content subtype name as defined in [MIME-IMB]. 3. body parameter parenthesized list A parenthesized list of attribute/value pairs [e.g., ("foo" "bar" "baz" "rag") where "bar" is the value of "foo" and "rag" is the value of "baz"] as defined in [MIME-IMB]. 4. body id A string giving the content id as defined in [MIME-IMB]. 5. body description A string giving the content description as defined in [MIME-IMB]. 6. body encoding A string giving the content transfer encoding as defined in [MIME-IMB]. 7. body size A number giving the size of the body in octets. Note that this size is the size in its transfer encoding and not the resulting size after any decoding. Put another way, the body structure is a list of seven elements. The semantics of the elements of this list are: 1. Byte string giving the major MIME type 2. Byte string giving the minor MIME type 3. A list giving the Content-Type parameters of the message 4. A byte string giving the content identifier for the message part, or None if it has no content identifier. 5. A byte string giving the content description for the message part, or None if it has no content description. 6. A byte string giving the Content-Encoding of the message body 7. An integer giving the number of octets in the message body The RFC goes on:: Multiple parts are indicated by parenthesis nesting. Instead of a body type as the first element of the parenthesized list, there is a sequence of one or more nested body structures. The second element of the parenthesized list is the multipart subtype (mixed, digest, parallel, alternative, etc.). For example, a two part message consisting of a text and a BASE64-encoded text attachment can have a body structure of: (("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 1152 23)("TEXT" "PLAIN" ("CHARSET" "US-ASCII" "NAME" "cc.diff") "<[email protected]>" "Compiler diff" "BASE64" 4554 73) "MIXED") This is represented as:: [["TEXT", "PLAIN", ["CHARSET", "US-ASCII"], None, None, "7BIT", 1152, 23], ["TEXT", "PLAIN", ["CHARSET", "US-ASCII", "NAME", "cc.diff"], "<[email protected]>", "Compiler diff", "BASE64", 4554, 73], "MIXED"] In other words, a list of N + 1 elements, where N is the number of parts in the message. The first N elements are structures as defined by the previous section. The last element is the minor MIME subtype of the multipart message. Additionally, the RFC describes extension data:: Extension data follows the multipart subtype. Extension data is never returned with the BODY fetch, but can be returned with a BODYSTRUCTURE fetch. Extension data, if present, MUST be in the defined order. The C{extended} flag controls whether extension data might be returned with the normal data. """ return _getMessageStructure(msg).encode(extended)
Consume an interator at most a single iteration per reactor iteration. If the iterator produces a Deferred, the next iteration will not occur until the Deferred fires, otherwise the next iteration will be taken in the next reactor iteration. @rtype: C{Deferred} @return: A deferred which fires (with None) when the iterator is exhausted or whose errback is called if there is an exception.
def iterateInReactor(i): """ Consume an interator at most a single iteration per reactor iteration. If the iterator produces a Deferred, the next iteration will not occur until the Deferred fires, otherwise the next iteration will be taken in the next reactor iteration. @rtype: C{Deferred} @return: A deferred which fires (with None) when the iterator is exhausted or whose errback is called if there is an exception. """ from twisted.internet import reactor d = defer.Deferred() def go(last): try: r = next(i) except StopIteration: d.callback(last) except BaseException: d.errback() else: if isinstance(r, defer.Deferred): r.addCallback(go) else: reactor.callLater(0, go, r) go(None) return d
Encode the given C{unicode} string using the IMAP4 specific variation of UTF-7. @type s: C{unicode} @param s: The text to encode. @param errors: Policy for handling encoding errors. Currently ignored. @return: L{tuple} of a L{str} giving the encoded bytes and an L{int} giving the number of code units consumed from the input.
def encoder(s, errors=None): """ Encode the given C{unicode} string using the IMAP4 specific variation of UTF-7. @type s: C{unicode} @param s: The text to encode. @param errors: Policy for handling encoding errors. Currently ignored. @return: L{tuple} of a L{str} giving the encoded bytes and an L{int} giving the number of code units consumed from the input. """ r = bytearray() _in = [] valid_chars = set(map(chr, range(0x20, 0x7F))) - {"&"} for c in s: if c in valid_chars: if _in: r += b"&" + modified_base64("".join(_in)) + b"-" del _in[:] r.append(ord(c)) elif c == "&": if _in: r += b"&" + modified_base64("".join(_in)) + b"-" del _in[:] r += b"&-" else: _in.append(c) if _in: r.extend(b"&" + modified_base64("".join(_in)) + b"-") return (bytes(r), len(s))
Decode the given L{str} using the IMAP4 specific variation of UTF-7. @type s: L{str} @param s: The bytes to decode. @param errors: Policy for handling decoding errors. Currently ignored. @return: a L{tuple} of a C{unicode} string giving the text which was decoded and an L{int} giving the number of bytes consumed from the input.
def decoder(s, errors=None): """ Decode the given L{str} using the IMAP4 specific variation of UTF-7. @type s: L{str} @param s: The bytes to decode. @param errors: Policy for handling decoding errors. Currently ignored. @return: a L{tuple} of a C{unicode} string giving the text which was decoded and an L{int} giving the number of bytes consumed from the input. """ r = [] decode = [] s = memory_cast(memoryview(s), "c") for c in s: if c == b"&" and not decode: decode.append(b"&") elif c == b"-" and decode: if len(decode) == 1: r.append("&") else: r.append(modified_unbase64(b"".join(decode[1:]))) decode = [] elif decode: decode.append(c) else: r.append(c.decode()) if decode: r.append(modified_unbase64(b"".join(decode[1:]))) return ("".join(r), len(s))
Create a maildir user directory if it doesn't already exist. @type dir: L{bytes} @param dir: The path name for a user directory.
def initializeMaildir(dir): """ Create a maildir user directory if it doesn't already exist. @type dir: L{bytes} @param dir: The path name for a user directory. """ dir = os.fsdecode(dir) if not os.path.isdir(dir): os.mkdir(dir, 0o700) for subdir in ["new", "cur", "tmp", ".Trash"]: os.mkdir(os.path.join(dir, subdir), 0o700) for subdir in ["new", "cur", "tmp"]: os.mkdir(os.path.join(dir, ".Trash", subdir), 0o700) # touch open(os.path.join(dir, ".Trash", "maildirfolder"), "w").close()
Direct the output of an iterator to the transport of a protocol and arrange for iteration to take place. @type proto: L{POP3} @param proto: A POP3 server protocol. @type gen: iterator which yields L{bytes} @param gen: An iterator over strings. @rtype: L{Deferred <defer.Deferred>} @return: A deferred which fires when the iterator finishes.
def iterateLineGenerator(proto, gen): """ Direct the output of an iterator to the transport of a protocol and arrange for iteration to take place. @type proto: L{POP3} @param proto: A POP3 server protocol. @type gen: iterator which yields L{bytes} @param gen: An iterator over strings. @rtype: L{Deferred <defer.Deferred>} @return: A deferred which fires when the iterator finishes. """ coll = _IteratorBuffer(proto.transport.writeSequence, gen) return proto.schedule(coll)
Format an object as a positive response. @type response: stringifyable L{object} @param response: An object with a string representation. @rtype: L{bytes} @return: A positive POP3 response string.
def successResponse(response): """ Format an object as a positive response. @type response: stringifyable L{object} @param response: An object with a string representation. @rtype: L{bytes} @return: A positive POP3 response string. """ if not isinstance(response, bytes): response = str(response).encode("utf-8") return b"+OK " + response + b"\r\n"
Format a list of message sizes into a STAT response. This generator function is intended to be used with L{Cooperator <twisted.internet.task.Cooperator>}. @type msgs: L{list} of L{int} @param msgs: A list of message sizes. @rtype: L{None} or L{bytes} @return: Yields none until a result is available, then a string that is suitable for use in a STAT response. The string consists of the number of messages and the total size of the messages in octets.
def formatStatResponse(msgs): """ Format a list of message sizes into a STAT response. This generator function is intended to be used with L{Cooperator <twisted.internet.task.Cooperator>}. @type msgs: L{list} of L{int} @param msgs: A list of message sizes. @rtype: L{None} or L{bytes} @return: Yields none until a result is available, then a string that is suitable for use in a STAT response. The string consists of the number of messages and the total size of the messages in octets. """ i = 0 bytes = 0 for size in msgs: i += 1 bytes += size yield None yield successResponse(b"%d %d" % (i, bytes))
Format a list of message sizes for use in a LIST response. @type msgs: L{list} of L{int} @param msgs: A list of message sizes. @rtype: L{bytes} @return: Yields a series of strings that are suitable for use as scan listings in a LIST response. Each string consists of a message number and its size in octets.
def formatListLines(msgs): """ Format a list of message sizes for use in a LIST response. @type msgs: L{list} of L{int} @param msgs: A list of message sizes. @rtype: L{bytes} @return: Yields a series of strings that are suitable for use as scan listings in a LIST response. Each string consists of a message number and its size in octets. """ i = 0 for size in msgs: i += 1 yield b"%d %d\r\n" % (i, size)
Format a list of message sizes into a complete LIST response. This generator function is intended to be used with L{Cooperator <twisted.internet.task.Cooperator>}. @type msgs: L{list} of L{int} @param msgs: A list of message sizes. @rtype: L{bytes} @return: Yields a series of strings which make up a complete LIST response.
def formatListResponse(msgs): """ Format a list of message sizes into a complete LIST response. This generator function is intended to be used with L{Cooperator <twisted.internet.task.Cooperator>}. @type msgs: L{list} of L{int} @param msgs: A list of message sizes. @rtype: L{bytes} @return: Yields a series of strings which make up a complete LIST response. """ yield successResponse(b"%d" % (len(msgs),)) yield from formatListLines(msgs) yield b".\r\n"
Format a list of message sizes for use in a UIDL response. @param msgs: See L{formatUIDListResponse} @param getUidl: See L{formatUIDListResponse} @rtype: L{bytes} @return: Yields a series of strings that are suitable for use as unique-id listings in a UIDL response. Each string consists of a message number and its unique id.
def formatUIDListLines(msgs, getUidl): """ Format a list of message sizes for use in a UIDL response. @param msgs: See L{formatUIDListResponse} @param getUidl: See L{formatUIDListResponse} @rtype: L{bytes} @return: Yields a series of strings that are suitable for use as unique-id listings in a UIDL response. Each string consists of a message number and its unique id. """ for i, m in enumerate(msgs): if m is not None: uid = getUidl(i) if not isinstance(uid, bytes): uid = str(uid).encode("utf-8") yield b"%d %b\r\n" % (i + 1, uid)
Format a list of message sizes into a complete UIDL response. This generator function is intended to be used with L{Cooperator <twisted.internet.task.Cooperator>}. @type msgs: L{list} of L{int} @param msgs: A list of message sizes. @type getUidl: one-argument callable returning bytes @param getUidl: A callable which takes a message index number and returns the UID of the corresponding message in the mailbox. @rtype: L{bytes} @return: Yields a series of strings which make up a complete UIDL response.
def formatUIDListResponse(msgs, getUidl): """ Format a list of message sizes into a complete UIDL response. This generator function is intended to be used with L{Cooperator <twisted.internet.task.Cooperator>}. @type msgs: L{list} of L{int} @param msgs: A list of message sizes. @type getUidl: one-argument callable returning bytes @param getUidl: A callable which takes a message index number and returns the UID of the corresponding message in the mailbox. @rtype: L{bytes} @return: Yields a series of strings which make up a complete UIDL response. """ yield successResponse("") yield from formatUIDListLines(msgs, getUidl) yield b".\r\n"
Prompt a relaying manager to check state. @type manager: L{SmartHostSMTPRelayingManager} @param manager: A relaying manager.
def _checkState(manager): """ Prompt a relaying manager to check state. @type manager: L{SmartHostSMTPRelayingManager} @param manager: A relaying manager. """ manager.checkState()
Set up a periodic call to prompt a relaying manager to check state. @type manager: L{SmartHostSMTPRelayingManager} @param manager: A relaying manager. @type delay: L{float} @param delay: The number of seconds between calls. @rtype: L{TimerService <internet.TimerService>} @return: A service which periodically reminds a relaying manager to check state.
def RelayStateHelper(manager, delay): """ Set up a periodic call to prompt a relaying manager to check state. @type manager: L{SmartHostSMTPRelayingManager} @param manager: A relaying manager. @type delay: L{float} @param delay: The number of seconds between calls. @rtype: L{TimerService <internet.TimerService>} @return: A service which periodically reminds a relaying manager to check state. """ return internet.TimerService(delay, _checkState, manager)
Format an RFC-2822 compliant date string. @param timeinfo: (optional) A sequence as returned by C{time.localtime()} or C{time.gmtime()}. Default is now. @param local: (optional) Indicates if the supplied time is local or universal time, or if no time is given, whether now should be local or universal time. Default is local, as suggested (SHOULD) by rfc-2822. @returns: A L{bytes} representing the time and date in RFC-2822 format.
def rfc822date(timeinfo=None, local=1): """ Format an RFC-2822 compliant date string. @param timeinfo: (optional) A sequence as returned by C{time.localtime()} or C{time.gmtime()}. Default is now. @param local: (optional) Indicates if the supplied time is local or universal time, or if no time is given, whether now should be local or universal time. Default is local, as suggested (SHOULD) by rfc-2822. @returns: A L{bytes} representing the time and date in RFC-2822 format. """ if not timeinfo: if local: timeinfo = time.localtime() else: timeinfo = time.gmtime() if local: if timeinfo[8]: # DST tz = -time.altzone else: tz = -time.timezone (tzhr, tzmin) = divmod(abs(tz), 3600) if tz: tzhr *= int(abs(tz) // tz) (tzmin, tzsec) = divmod(tzmin, 60) else: (tzhr, tzmin) = (0, 0) return networkString( "%s, %02d %s %04d %02d:%02d:%02d %+03d%02d" % ( ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][timeinfo[6]], timeinfo[2], [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ][timeinfo[1] - 1], timeinfo[0], timeinfo[3], timeinfo[4], timeinfo[5], tzhr, tzmin, ) )
Return a globally unique random string in RFC 2822 Message-ID format <[email protected]> Optional uniq string will be added to strengthen uniqueness if given.
def messageid(uniq=None, N=lambda: next(_gen)): """ Return a globally unique random string in RFC 2822 Message-ID format <[email protected]> Optional uniq string will be added to strengthen uniqueness if given. """ datetime = time.strftime("%Y%m%d%H%M%S", time.gmtime()) pid = os.getpid() rand = random.randrange(2**31 - 1) if uniq is None: uniq = "" else: uniq = "." + uniq return "<{}.{}.{}{}.{}@{}>".format( datetime, pid, rand, uniq, N(), DNSNAME.decode() ).encode()
Turn an email address, possibly with realname part etc, into a form suitable for and SMTP envelope.
def quoteaddr(addr): """ Turn an email address, possibly with realname part etc, into a form suitable for and SMTP envelope. """ if isinstance(addr, Address): return b"<" + bytes(addr) + b">" if isinstance(addr, bytes): addr = addr.decode("ascii") res = parseaddr(addr) if res == (None, None): # It didn't parse, use it as-is return b"<" + bytes(addr) + b">" else: return b"<" + res[1].encode("ascii") + b">"
Send an email. This interface is intended to be a replacement for L{smtplib.SMTP.sendmail} and related methods. To maintain backwards compatibility, it will fall back to plain SMTP, if ESMTP support is not available. If ESMTP support is available, it will attempt to provide encryption via STARTTLS and authentication if a secret is provided. @param smtphost: The host the message should be sent to. @type smtphost: L{bytes} @param from_addr: The (envelope) address sending this mail. @type from_addr: L{bytes} @param to_addrs: A list of addresses to send this mail to. A string will be treated as a list of one address. @type to_addrs: L{list} of L{bytes} or L{bytes} @param msg: The message, including headers, either as a file or a string. File-like objects need to support read() and close(). Lines must be delimited by '\n'. If you pass something that doesn't look like a file, we try to convert it to a string (so you should be able to pass an L{email.message} directly, but doing the conversion with L{email.generator} manually will give you more control over the process). @param senderDomainName: Name by which to identify. If None, try to pick something sane (but this depends on external configuration and may not succeed). @type senderDomainName: L{bytes} @param port: Remote port to which to connect. @type port: L{int} @param username: The username to use, if wanting to authenticate. @type username: L{bytes} or L{unicode} @param password: The secret to use, if wanting to authenticate. If you do not specify this, SMTP authentication will not occur. @type password: L{bytes} or L{unicode} @param requireTransportSecurity: Whether or not STARTTLS is required. @type requireTransportSecurity: L{bool} @param requireAuthentication: Whether or not authentication is required. @type requireAuthentication: L{bool} @param reactor: The L{reactor} used to make the TCP connection. @rtype: L{Deferred} @returns: A cancellable L{Deferred}, its callback will be called if a message is sent to ANY address, the errback if no message is sent. When the C{cancel} method is called, it will stop retrying and disconnect the connection immediately. The callback will be called with a tuple (numOk, addresses) where numOk is the number of successful recipient addresses and addresses is a list of tuples (address, code, resp) giving the response to the RCPT command for each address.
def sendmail( smtphost, from_addr, to_addrs, msg, senderDomainName=None, port=25, reactor=reactor, username=None, password=None, requireAuthentication=False, requireTransportSecurity=False, ): """ Send an email. This interface is intended to be a replacement for L{smtplib.SMTP.sendmail} and related methods. To maintain backwards compatibility, it will fall back to plain SMTP, if ESMTP support is not available. If ESMTP support is available, it will attempt to provide encryption via STARTTLS and authentication if a secret is provided. @param smtphost: The host the message should be sent to. @type smtphost: L{bytes} @param from_addr: The (envelope) address sending this mail. @type from_addr: L{bytes} @param to_addrs: A list of addresses to send this mail to. A string will be treated as a list of one address. @type to_addrs: L{list} of L{bytes} or L{bytes} @param msg: The message, including headers, either as a file or a string. File-like objects need to support read() and close(). Lines must be delimited by '\\n'. If you pass something that doesn't look like a file, we try to convert it to a string (so you should be able to pass an L{email.message} directly, but doing the conversion with L{email.generator} manually will give you more control over the process). @param senderDomainName: Name by which to identify. If None, try to pick something sane (but this depends on external configuration and may not succeed). @type senderDomainName: L{bytes} @param port: Remote port to which to connect. @type port: L{int} @param username: The username to use, if wanting to authenticate. @type username: L{bytes} or L{unicode} @param password: The secret to use, if wanting to authenticate. If you do not specify this, SMTP authentication will not occur. @type password: L{bytes} or L{unicode} @param requireTransportSecurity: Whether or not STARTTLS is required. @type requireTransportSecurity: L{bool} @param requireAuthentication: Whether or not authentication is required. @type requireAuthentication: L{bool} @param reactor: The L{reactor} used to make the TCP connection. @rtype: L{Deferred} @returns: A cancellable L{Deferred}, its callback will be called if a message is sent to ANY address, the errback if no message is sent. When the C{cancel} method is called, it will stop retrying and disconnect the connection immediately. The callback will be called with a tuple (numOk, addresses) where numOk is the number of successful recipient addresses and addresses is a list of tuples (address, code, resp) giving the response to the RCPT command for each address. """ if not hasattr(msg, "read"): # It's not a file msg = BytesIO(bytes(msg)) def cancel(d): """ Cancel the L{twisted.mail.smtp.sendmail} call, tell the factory not to retry and disconnect the connection. @param d: The L{defer.Deferred} to be cancelled. """ factory.sendFinished = True if factory.currentProtocol: factory.currentProtocol.transport.abortConnection() else: # Connection hasn't been made yet connector.disconnect() d = defer.Deferred(cancel) if isinstance(username, str): username = username.encode("utf-8") if isinstance(password, str): password = password.encode("utf-8") tlsHostname = smtphost if not isinstance(tlsHostname, str): tlsHostname = _idnaText(tlsHostname) factory = ESMTPSenderFactory( username, password, from_addr, to_addrs, msg, d, heloFallback=True, requireAuthentication=requireAuthentication, requireTransportSecurity=requireTransportSecurity, hostname=tlsHostname, ) if senderDomainName is not None: factory.domain = networkString(senderDomainName) connector = reactor.connectTCP(smtphost, port, factory) return d
Decode the xtext-encoded string C{s}. @param s: String to decode. @param errors: codec error handling scheme. @return: The decoded string.
def xtext_decode(s, errors=None): """ Decode the xtext-encoded string C{s}. @param s: String to decode. @param errors: codec error handling scheme. @return: The decoded string. """ r = [] i = 0 while i < len(s): if s[i : i + 1] == b"+": try: r.append(chr(int(bytes(s[i + 1 : i + 3]), 16))) except ValueError: r.append(ord(s[i : i + 3])) i += 3 else: r.append(bytes(s[i : i + 1]).decode("ascii")) i += 1 return ("".join(r), len(s))
Configure a service for operating a mail server. The returned service may include POP3 servers, SMTP servers, or both, depending on the configuration passed in. If there are multiple servers, they will share all of their non-network state (i.e. the same user accounts are available on all of them). @type config: L{Options <usage.Options>} @param config: Configuration options specifying which servers to include in the returned service and where they should keep mail data. @rtype: L{IService <twisted.application.service.IService>} provider @return: A service which contains the requested mail servers.
def makeService(config): """ Configure a service for operating a mail server. The returned service may include POP3 servers, SMTP servers, or both, depending on the configuration passed in. If there are multiple servers, they will share all of their non-network state (i.e. the same user accounts are available on all of them). @type config: L{Options <usage.Options>} @param config: Configuration options specifying which servers to include in the returned service and where they should keep mail data. @rtype: L{IService <twisted.application.service.IService>} provider @return: A service which contains the requested mail servers. """ if config["esmtp"]: rmType = relaymanager.SmartHostESMTPRelayingManager smtpFactory = config.service.getESMTPFactory else: rmType = relaymanager.SmartHostSMTPRelayingManager smtpFactory = config.service.getSMTPFactory if config["relay"]: dir = config["relay"] if not os.path.isdir(dir): os.mkdir(dir) config.service.setQueue(relaymanager.Queue(dir)) default = relay.DomainQueuer(config.service) manager = rmType(config.service.queue) if config["esmtp"]: manager.fArgs += (None, None) manager.fArgs += (config["hostname"],) helper = relaymanager.RelayStateHelper(manager, 1) helper.setServiceParent(config.service) config.service.domains.setDefaultDomain(default) if config["pop3"]: f = config.service.getPOP3Factory() for endpoint in config["pop3"]: svc = internet.StreamServerEndpointService(endpoint, f) svc.setServiceParent(config.service) if config["smtp"]: f = smtpFactory() if config["hostname"]: f.domain = config["hostname"] f.fArgs = (f.domain,) if config["esmtp"]: f.fArgs = (None, None) + f.fArgs for endpoint in config["smtp"]: svc = internet.StreamServerEndpointService(endpoint, f) svc.setServiceParent(config.service) return config.service
Parse the response to a STAT command. @type line: L{bytes} @param line: The response from the server to a STAT command minus the status indicator. @rtype: 2-L{tuple} of (0) L{int}, (1) L{int} @return: The number of messages in the mailbox and the size of the mailbox.
def _statXform(line): """ Parse the response to a STAT command. @type line: L{bytes} @param line: The response from the server to a STAT command minus the status indicator. @rtype: 2-L{tuple} of (0) L{int}, (1) L{int} @return: The number of messages in the mailbox and the size of the mailbox. """ numMsgs, totalSize = line.split(None, 1) return int(numMsgs), int(totalSize)
Parse a line of the response to a LIST command. The line from the LIST response consists of a 1-based message number followed by a size. @type line: L{bytes} @param line: A non-initial line from the multi-line response to a LIST command. @rtype: 2-L{tuple} of (0) L{int}, (1) L{int} @return: The 0-based index of the message and the size of the message.
def _listXform(line): """ Parse a line of the response to a LIST command. The line from the LIST response consists of a 1-based message number followed by a size. @type line: L{bytes} @param line: A non-initial line from the multi-line response to a LIST command. @rtype: 2-L{tuple} of (0) L{int}, (1) L{int} @return: The 0-based index of the message and the size of the message. """ index, size = line.split(None, 1) return int(index) - 1, int(size)
Parse a line of the response to a UIDL command. The line from the UIDL response consists of a 1-based message number followed by a unique id. @type line: L{bytes} @param line: A non-initial line from the multi-line response to a UIDL command. @rtype: 2-L{tuple} of (0) L{int}, (1) L{bytes} @return: The 0-based index of the message and the unique identifier for the message.
def _uidXform(line): """ Parse a line of the response to a UIDL command. The line from the UIDL response consists of a 1-based message number followed by a unique id. @type line: L{bytes} @param line: A non-initial line from the multi-line response to a UIDL command. @rtype: 2-L{tuple} of (0) L{int}, (1) L{bytes} @return: The 0-based index of the message and the unique identifier for the message. """ index, uid = line.split(None, 1) return int(index) - 1, uid
Parse the first line of a multi-line server response. @type line: L{bytes} @param line: The first line of a multi-line server response. @rtype: 2-tuple of (0) L{bytes}, (1) L{bytes} @return: The status indicator and the rest of the server response.
def _codeStatusSplit(line): """ Parse the first line of a multi-line server response. @type line: L{bytes} @param line: The first line of a multi-line server response. @rtype: 2-tuple of (0) L{bytes}, (1) L{bytes} @return: The status indicator and the rest of the server response. """ parts = line.split(b" ", 1) if len(parts) == 1: return parts[0], b"" return parts
Remove a byte-stuffed termination character at the beginning of a line if present. When the termination character (C{'.'}) appears at the beginning of a line, the server byte-stuffs it by adding another termination character to avoid confusion with the terminating sequence (C{'.\r\n'}). @type line: L{bytes} @param line: A received line. @rtype: L{bytes} @return: The line without the byte-stuffed termination character at the beginning if it was present. Otherwise, the line unchanged.
def _dotUnquoter(line): """ Remove a byte-stuffed termination character at the beginning of a line if present. When the termination character (C{'.'}) appears at the beginning of a line, the server byte-stuffs it by adding another termination character to avoid confusion with the terminating sequence (C{'.\\r\\n'}). @type line: L{bytes} @param line: A received line. @rtype: L{bytes} @return: The line without the byte-stuffed termination character at the beginning if it was present. Otherwise, the line unchanged. """ if line.startswith(b".."): return line[1:] return line
Assert that the given capability is included in all of the capability sets. @param testcase: A L{unittest.TestCase} to use to make assertions. @param s: The capability for which to check. @type s: L{bytes} @param caps: The capability sets in which to check. @type caps: L{tuple} of iterable
def contained(testcase, s, *caps): """ Assert that the given capability is included in all of the capability sets. @param testcase: A L{unittest.TestCase} to use to make assertions. @param s: The capability for which to check. @type s: L{bytes} @param caps: The capability sets in which to check. @type caps: L{tuple} of iterable """ for c in caps: testcase.assertIn(s, c)
Return a monotonically increasing (across program runs) integer. State is stored in the given file. If it does not exist, it is created with rw-/---/--- permissions. This manipulates process-global state by calling C{os.umask()}, so it isn't thread-safe. @param filename: Path to a file that is used to store the state across program runs. @type filename: L{str} @return: a monotonically increasing number @rtype: L{str}
def getSerial(filename="/tmp/twisted-names.serial"): """ Return a monotonically increasing (across program runs) integer. State is stored in the given file. If it does not exist, it is created with rw-/---/--- permissions. This manipulates process-global state by calling C{os.umask()}, so it isn't thread-safe. @param filename: Path to a file that is used to store the state across program runs. @type filename: L{str} @return: a monotonically increasing number @rtype: L{str} """ serial = time.strftime("%Y%m%d") o = os.umask(0o177) try: if not os.path.exists(filename): with open(filename, "w") as f: f.write(serial + " 0") finally: os.umask(o) with open(filename) as serialFile: lastSerial, zoneID = serialFile.readline().split() zoneID = (lastSerial == serial) and (int(zoneID) + 1) or 0 with open(filename, "w") as serialFile: serialFile.write("%s %d" % (serial, zoneID)) serial = serial + ("%02d" % (zoneID,)) return serial
Create and return a Resolver. @type servers: C{list} of C{(str, int)} or L{None} @param servers: If not L{None}, interpreted as a list of domain name servers to attempt to use. Each server is a tuple of address in C{str} dotted-quad form and C{int} port number. @type resolvconf: C{str} or L{None} @param resolvconf: If not L{None}, on posix systems will be interpreted as an alternate resolv.conf to use. Will do nothing on windows systems. If L{None}, /etc/resolv.conf will be used. @type hosts: C{str} or L{None} @param hosts: If not L{None}, an alternate hosts file to use. If L{None} on posix systems, /etc/hosts will be used. On windows, C:\windows\hosts will be used. @rtype: C{IResolver}
def createResolver(servers=None, resolvconf=None, hosts=None): r""" Create and return a Resolver. @type servers: C{list} of C{(str, int)} or L{None} @param servers: If not L{None}, interpreted as a list of domain name servers to attempt to use. Each server is a tuple of address in C{str} dotted-quad form and C{int} port number. @type resolvconf: C{str} or L{None} @param resolvconf: If not L{None}, on posix systems will be interpreted as an alternate resolv.conf to use. Will do nothing on windows systems. If L{None}, /etc/resolv.conf will be used. @type hosts: C{str} or L{None} @param hosts: If not L{None}, an alternate hosts file to use. If L{None} on posix systems, /etc/hosts will be used. On windows, C:\windows\hosts will be used. @rtype: C{IResolver} """ if platform.getType() == "posix": if resolvconf is None: resolvconf = b"/etc/resolv.conf" if hosts is None: hosts = b"/etc/hosts" theResolver = Resolver(resolvconf, servers) hostResolver = hostsModule.Resolver(hosts) else: if hosts is None: hosts = r"c:\windows\hosts" from twisted.internet import reactor bootstrap = _ThreadedResolverImpl(reactor) hostResolver = hostsModule.Resolver(hosts) theResolver = root.bootstrap(bootstrap, resolverFactory=Resolver) L = [hostResolver, cache.CacheResolver(), theResolver] return resolve.ResolverChain(L)
Get a Resolver instance. Create twisted.names.client.theResolver if it is L{None}, and then return that value. @rtype: C{IResolver}
def getResolver(): """ Get a Resolver instance. Create twisted.names.client.theResolver if it is L{None}, and then return that value. @rtype: C{IResolver} """ global theResolver if theResolver is None: try: theResolver = createResolver() except ValueError: theResolver = createResolver(servers=[("127.0.0.1", 53)]) return theResolver
Resolve a name to a valid ipv4 or ipv6 address. Will errback with C{DNSQueryTimeoutError} on a timeout, C{DomainError} or C{AuthoritativeDomainError} (or subclasses) on other errors. @type name: C{str} @param name: DNS name to resolve. @type timeout: Sequence of C{int} @param timeout: Number of seconds after which to reissue the query. When the last timeout expires, the query is considered failed. @type effort: C{int} @param effort: How many times CNAME and NS records to follow while resolving this name. @rtype: C{Deferred}
def getHostByName(name, timeout=None, effort=10): """ Resolve a name to a valid ipv4 or ipv6 address. Will errback with C{DNSQueryTimeoutError} on a timeout, C{DomainError} or C{AuthoritativeDomainError} (or subclasses) on other errors. @type name: C{str} @param name: DNS name to resolve. @type timeout: Sequence of C{int} @param timeout: Number of seconds after which to reissue the query. When the last timeout expires, the query is considered failed. @type effort: C{int} @param effort: How many times CNAME and NS records to follow while resolving this name. @rtype: C{Deferred} """ return getResolver().getHostByName(name, timeout, effort)
Resolve a name to an IP address, following I{CNAME} records and I{NS} referrals recursively. This is an implementation detail of L{ResolverBase.getHostByName}. @param resolver: The resolver to use for the next query (unless handling an I{NS} referral). @type resolver: L{IResolver} @param name: The name being looked up. @type name: L{dns.Name} @param answers: All of the records returned by the previous query (answers, authority, and additional concatenated). @type answers: L{list} of L{dns.RRHeader} @param level: Remaining recursion budget. This is decremented at each recursion. The query returns L{None} when it reaches 0. @type level: L{int} @returns: The first IPv4 or IPv6 address (as a dotted quad or colon quibbles), or L{None} when no result is found. @rtype: native L{str} or L{None}
def extractRecord(resolver, name, answers, level=10): """ Resolve a name to an IP address, following I{CNAME} records and I{NS} referrals recursively. This is an implementation detail of L{ResolverBase.getHostByName}. @param resolver: The resolver to use for the next query (unless handling an I{NS} referral). @type resolver: L{IResolver} @param name: The name being looked up. @type name: L{dns.Name} @param answers: All of the records returned by the previous query (answers, authority, and additional concatenated). @type answers: L{list} of L{dns.RRHeader} @param level: Remaining recursion budget. This is decremented at each recursion. The query returns L{None} when it reaches 0. @type level: L{int} @returns: The first IPv4 or IPv6 address (as a dotted quad or colon quibbles), or L{None} when no result is found. @rtype: native L{str} or L{None} """ if not level: return None # FIXME: twisted.python.compat monkeypatches this if missing, so this # condition is always true. https://twistedmatrix.com/trac/ticket/9753 if hasattr(socket, "inet_ntop"): for r in answers: if r.name == name and r.type == dns.A6: return socket.inet_ntop(socket.AF_INET6, r.payload.address) for r in answers: if r.name == name and r.type == dns.AAAA: return socket.inet_ntop(socket.AF_INET6, r.payload.address) for r in answers: if r.name == name and r.type == dns.A: return socket.inet_ntop(socket.AF_INET, r.payload.address) for r in answers: if r.name == name and r.type == dns.CNAME: result = extractRecord(resolver, r.payload.name, answers, level - 1) if not result: return resolver.getHostByName(r.payload.name.name, effort=level - 1) return result # No answers, but maybe there's a hint at who we should be asking about # this for r in answers: if r.type != dns.NS: continue from twisted.names import client nsResolver = client.Resolver( servers=[ (r.payload.name.name.decode("ascii"), dns.PORT), ] ) def queryAgain(records): (ans, auth, add) = records return extractRecord(nsResolver, name, ans + auth + add, level - 1) return nsResolver.lookupAddress(name.name).addCallback(queryAgain)
Construct a bytes object representing a single byte with the given ordinal value. @type ordinal: L{int} @rtype: L{bytes}
def _ord2bytes(ordinal): """ Construct a bytes object representing a single byte with the given ordinal value. @type ordinal: L{int} @rtype: L{bytes} """ return bytes([ordinal])
Represent a mostly textful bytes object in a way suitable for presentation to an end user. @param bytes: The bytes to represent. @rtype: L{str}
def _nicebytes(bytes): """ Represent a mostly textful bytes object in a way suitable for presentation to an end user. @param bytes: The bytes to represent. @rtype: L{str} """ return repr(bytes)[1:]
Represent a list of mostly textful bytes objects in a way suitable for presentation to an end user. @param list: The list of bytes to represent. @rtype: L{str}
def _nicebyteslist(list): """ Represent a list of mostly textful bytes objects in a way suitable for presentation to an end user. @param list: The list of bytes to represent. @rtype: L{str} """ return "[{}]".format(", ".join([_nicebytes(b) for b in list]))
Wrapper around L{twisted.python.randbytes.RandomFactory.secureRandom} to return 2 random bytes. @rtype: L{bytes}
def randomSource(): """ Wrapper around L{twisted.python.randbytes.RandomFactory.secureRandom} to return 2 random bytes. @rtype: L{bytes} """ return struct.unpack("H", randbytes.secureRandom(2, fallback=True))[0]
Split a domain name into its constituent labels. @type name: L{bytes} @param name: A fully qualified domain name (with or without a trailing dot). @return: A L{list} of labels ending with an empty label representing the DNS root zone. @rtype: L{list} of L{bytes}
def _nameToLabels(name): """ Split a domain name into its constituent labels. @type name: L{bytes} @param name: A fully qualified domain name (with or without a trailing dot). @return: A L{list} of labels ending with an empty label representing the DNS root zone. @rtype: L{list} of L{bytes} """ if name in (b"", b"."): return [b""] labels = name.split(b".") if labels[-1] != b"": labels.append(b"") return labels
Coerce a domain name string to bytes. L{twisted.names} represents domain names as L{bytes}, but many interfaces accept L{bytes} or a text string (L{unicode} on Python 2, L{str} on Python 3). This function coerces text strings using IDNA encoding --- see L{encodings.idna}. Note that DNS is I{case insensitive} but I{case preserving}. This function doesn't normalize case, so you'll still need to do that whenever comparing the strings it returns. @param domain: A domain name. If passed as a text string it will be C{idna} encoded. @type domain: L{bytes} or L{str} @returns: L{bytes} suitable for network transmission. @rtype: L{bytes} @since: Twisted 20.3.0
def domainString(domain: str | bytes) -> bytes: """ Coerce a domain name string to bytes. L{twisted.names} represents domain names as L{bytes}, but many interfaces accept L{bytes} or a text string (L{unicode} on Python 2, L{str} on Python 3). This function coerces text strings using IDNA encoding --- see L{encodings.idna}. Note that DNS is I{case insensitive} but I{case preserving}. This function doesn't normalize case, so you'll still need to do that whenever comparing the strings it returns. @param domain: A domain name. If passed as a text string it will be C{idna} encoded. @type domain: L{bytes} or L{str} @returns: L{bytes} suitable for network transmission. @rtype: L{bytes} @since: Twisted 20.3.0 """ if isinstance(domain, str): domain = domain.encode("idna") if not isinstance(domain, bytes): raise TypeError( "Expected {} or {} but found {!r} of type {}".format( bytes.__name__, str.__name__, domain, type(domain) ) ) return domain
Test whether C{descendantName} is equal to or is a I{subdomain} of C{ancestorName}. The names are compared case-insensitively. The names are treated as byte strings containing one or more DNS labels separated by B{.}. C{descendantName} is considered equal if its sequence of labels exactly matches the labels of C{ancestorName}. C{descendantName} is considered a I{subdomain} if its sequence of labels ends with the labels of C{ancestorName}. @type descendantName: L{bytes} @param descendantName: The DNS subdomain name. @type ancestorName: L{bytes} @param ancestorName: The DNS parent or ancestor domain name. @return: C{True} if C{descendantName} is equal to or if it is a subdomain of C{ancestorName}. Otherwise returns C{False}.
def _isSubdomainOf(descendantName, ancestorName): """ Test whether C{descendantName} is equal to or is a I{subdomain} of C{ancestorName}. The names are compared case-insensitively. The names are treated as byte strings containing one or more DNS labels separated by B{.}. C{descendantName} is considered equal if its sequence of labels exactly matches the labels of C{ancestorName}. C{descendantName} is considered a I{subdomain} if its sequence of labels ends with the labels of C{ancestorName}. @type descendantName: L{bytes} @param descendantName: The DNS subdomain name. @type ancestorName: L{bytes} @param ancestorName: The DNS parent or ancestor domain name. @return: C{True} if C{descendantName} is equal to or if it is a subdomain of C{ancestorName}. Otherwise returns C{False}. """ descendantLabels = _nameToLabels(descendantName.lower()) ancestorLabels = _nameToLabels(ancestorName.lower()) return descendantLabels[-len(ancestorLabels) :] == ancestorLabels
mypy doesn't like type-punning str | bytes | int | None into a str so we have this helper function.
def _str2time(s: str) -> int: """ mypy doesn't like type-punning str | bytes | int | None into a str so we have this helper function. """ suffixes = ( ("S", 1), ("M", 60), ("H", 60 * 60), ("D", 60 * 60 * 24), ("W", 60 * 60 * 24 * 7), ("Y", 60 * 60 * 24 * 365), ) s = s.upper().strip() for suff, mult in suffixes: if s.endswith(suff): return int(float(s[:-1]) * mult) try: return int(s) except ValueError: raise ValueError("Invalid time interval specifier: " + s)
Parse a string description of an interval into an integer number of seconds. @param s: An interval definition constructed as an interval duration followed by an interval unit. An interval duration is a base ten representation of an integer. An interval unit is one of the following letters: S (seconds), M (minutes), H (hours), D (days), W (weeks), or Y (years). For example: C{"3S"} indicates an interval of three seconds; C{"5D"} indicates an interval of five days. Alternatively, C{s} may be any non-string and it will be returned unmodified. @type s: text string (L{bytes} or L{str}) for parsing; anything else for passthrough. @return: an L{int} giving the interval represented by the string C{s}, or whatever C{s} is if it is not a string.
def str2time(s: Union[str, bytes, int, None]) -> Union[int, None]: """ Parse a string description of an interval into an integer number of seconds. @param s: An interval definition constructed as an interval duration followed by an interval unit. An interval duration is a base ten representation of an integer. An interval unit is one of the following letters: S (seconds), M (minutes), H (hours), D (days), W (weeks), or Y (years). For example: C{"3S"} indicates an interval of three seconds; C{"5D"} indicates an interval of five days. Alternatively, C{s} may be any non-string and it will be returned unmodified. @type s: text string (L{bytes} or L{str}) for parsing; anything else for passthrough. @return: an L{int} giving the interval represented by the string C{s}, or whatever C{s} is if it is not a string. """ if isinstance(s, bytes): return _str2time(s.decode("ascii")) if isinstance(s, str): return _str2time(s) return s
Generate a L{Message} like instance suitable for use as the response to C{message}. The C{queries}, C{id} attributes will be copied from C{message} and the C{answer} flag will be set to L{True}. @param responseConstructor: A response message constructor with an initializer signature matching L{dns.Message.__init__}. @type responseConstructor: C{callable} @param message: A request message. @type message: L{Message} @param kwargs: Keyword arguments which will be passed to the initialiser of the response message. @type kwargs: L{dict} @return: A L{Message} like response instance. @rtype: C{responseConstructor}
def _responseFromMessage(responseConstructor, message, **kwargs): """ Generate a L{Message} like instance suitable for use as the response to C{message}. The C{queries}, C{id} attributes will be copied from C{message} and the C{answer} flag will be set to L{True}. @param responseConstructor: A response message constructor with an initializer signature matching L{dns.Message.__init__}. @type responseConstructor: C{callable} @param message: A request message. @type message: L{Message} @param kwargs: Keyword arguments which will be passed to the initialiser of the response message. @type kwargs: L{dict} @return: A L{Message} like response instance. @rtype: C{responseConstructor} """ response = responseConstructor(id=message.id, answer=True, **kwargs) response.queries = message.queries[:] return response
Inspect the function signature of C{obj}'s constructor, and get a list of which arguments should be displayed. This is a helper function for C{_compactRepr}. @param obj: The instance whose repr is being generated. @param alwaysShow: A L{list} of field names which should always be shown. @param fieldNames: A L{list} of field attribute names which should be shown if they have non-default values. @return: A L{list} of displayable arguments.
def _getDisplayableArguments(obj, alwaysShow, fieldNames): """ Inspect the function signature of C{obj}'s constructor, and get a list of which arguments should be displayed. This is a helper function for C{_compactRepr}. @param obj: The instance whose repr is being generated. @param alwaysShow: A L{list} of field names which should always be shown. @param fieldNames: A L{list} of field attribute names which should be shown if they have non-default values. @return: A L{list} of displayable arguments. """ displayableArgs = [] # Get the argument names and values from the constructor. signature = inspect.signature(obj.__class__.__init__) for name in fieldNames: defaultValue = signature.parameters[name].default fieldValue = getattr(obj, name, defaultValue) if (name in alwaysShow) or (fieldValue != defaultValue): displayableArgs.append(f" {name}={fieldValue!r}") return displayableArgs
Return a L{str} representation of C{obj} which only shows fields with non-default values, flags which are True and sections which have been explicitly set. @param obj: The instance whose repr is being generated. @param alwaysShow: A L{list} of field names which should always be shown. @param flagNames: A L{list} of flag attribute names which should be shown if they are L{True}. @param fieldNames: A L{list} of field attribute names which should be shown if they have non-default values. @param sectionNames: A L{list} of section attribute names which should be shown if they have been assigned a value. @return: A L{str} representation of C{obj}.
def _compactRepr( obj: object, alwaysShow: Sequence[str] | None = None, flagNames: Sequence[str] | None = None, fieldNames: Sequence[str] | None = None, sectionNames: Sequence[str] | None = None, ) -> str: """ Return a L{str} representation of C{obj} which only shows fields with non-default values, flags which are True and sections which have been explicitly set. @param obj: The instance whose repr is being generated. @param alwaysShow: A L{list} of field names which should always be shown. @param flagNames: A L{list} of flag attribute names which should be shown if they are L{True}. @param fieldNames: A L{list} of field attribute names which should be shown if they have non-default values. @param sectionNames: A L{list} of section attribute names which should be shown if they have been assigned a value. @return: A L{str} representation of C{obj}. """ if alwaysShow is None: alwaysShow = [] if flagNames is None: flagNames = [] if fieldNames is None: fieldNames = [] if sectionNames is None: sectionNames = [] setFlags = [] for name in flagNames: if name in alwaysShow or getattr(obj, name, False) == True: setFlags.append(name) displayableArgs = _getDisplayableArguments(obj, alwaysShow, fieldNames) out = ["<", obj.__class__.__name__] + displayableArgs if setFlags: out.append(" flags={}".format(",".join(setFlags))) for name in sectionNames: section = getattr(obj, name, []) if section: out.append(f" {name}={section!r}") out.append(">") return "".join(out)
Search the given file, which is in hosts(5) standard format, for addresses associated with a given name. @param hostsFile: The name of the hosts(5)-format file to search. @type hostsFile: L{FilePath} @param name: The name to search for. @type name: C{bytes} @return: L{None} if the name is not found in the file, otherwise a C{str} giving the address in the file associated with the name.
def searchFileForAll(hostsFile, name): """ Search the given file, which is in hosts(5) standard format, for addresses associated with a given name. @param hostsFile: The name of the hosts(5)-format file to search. @type hostsFile: L{FilePath} @param name: The name to search for. @type name: C{bytes} @return: L{None} if the name is not found in the file, otherwise a C{str} giving the address in the file associated with the name. """ results = [] try: lines = hostsFile.getContent().splitlines() except BaseException: return results name = name.lower() for line in lines: idx = line.find(b"#") if idx != -1: line = line[:idx] if not line: continue parts = line.split() if name.lower() in [s.lower() for s in parts[1:]]: try: maybeIP = nativeString(parts[0]) except ValueError: # Not ASCII. continue if isIPAddress(maybeIP) or isIPv6Address(maybeIP): results.append(maybeIP) return results
Grep given file, which is in hosts(5) standard format, for an address entry with a given name. @param file: The name of the hosts(5)-format file to search. @type file: C{str} or C{bytes} @param name: The name to search for. @type name: C{bytes} @return: L{None} if the name is not found in the file, otherwise a C{str} giving the first address in the file associated with the name.
def searchFileFor(file, name): """ Grep given file, which is in hosts(5) standard format, for an address entry with a given name. @param file: The name of the hosts(5)-format file to search. @type file: C{str} or C{bytes} @param name: The name to search for. @type name: C{bytes} @return: L{None} if the name is not found in the file, otherwise a C{str} giving the first address in the file associated with the name. """ addresses = searchFileForAll(FilePath(file), name) if addresses: return addresses[0] return None
Lookup the root nameserver addresses using the given resolver Return a Resolver which will eventually become a C{root.Resolver} instance that has references to all the root servers that we were able to look up. @param resolver: The resolver instance which will be used to lookup the root nameserver addresses. @type resolver: L{twisted.internet.interfaces.IResolverSimple} @param resolverFactory: An optional callable which returns a resolver instance. It will passed as the C{resolverFactory} argument to L{Resolver.__init__}. @type resolverFactory: callable @return: A L{DeferredResolver} which will be dynamically replaced with L{Resolver} when the root nameservers have been looked up.
def bootstrap(resolver, resolverFactory=None): """ Lookup the root nameserver addresses using the given resolver Return a Resolver which will eventually become a C{root.Resolver} instance that has references to all the root servers that we were able to look up. @param resolver: The resolver instance which will be used to lookup the root nameserver addresses. @type resolver: L{twisted.internet.interfaces.IResolverSimple} @param resolverFactory: An optional callable which returns a resolver instance. It will passed as the C{resolverFactory} argument to L{Resolver.__init__}. @type resolverFactory: callable @return: A L{DeferredResolver} which will be dynamically replaced with L{Resolver} when the root nameservers have been looked up. """ domains = [chr(ord("a") + i) for i in range(13)] L = [resolver.getHostByName("%s.root-servers.net" % d) for d in domains] d = defer.DeferredList(L, consumeErrors=True) def buildResolver(res): return Resolver( hints=[e[1] for e in res if e[0]], resolverFactory=resolverFactory ) d.addCallback(buildResolver) return DeferredResolver(d)
Build DNS resolver instances in an order which leaves recursive resolving as a last resort. @type config: L{Options} instance @param config: Parsed command-line configuration @return: Two-item tuple of a list of cache resovers and a list of client resolvers
def _buildResolvers(config): """ Build DNS resolver instances in an order which leaves recursive resolving as a last resort. @type config: L{Options} instance @param config: Parsed command-line configuration @return: Two-item tuple of a list of cache resovers and a list of client resolvers """ from twisted.names import cache, client, hosts ca, cl = [], [] if config["cache"]: ca.append(cache.CacheResolver(verbose=config["verbose"])) if config["hosts-file"]: cl.append(hosts.Resolver(file=config["hosts-file"])) if config["recursive"]: cl.append(client.createResolver(resolvconf=config["resolv-conf"])) return ca, cl
Assert that C{descendant} *is* a subdomain of C{ancestor}. @type testCase: L{unittest.SynchronousTestCase} @param testCase: The test case on which to run the assertions. @type descendant: C{str} @param descendant: The subdomain name to test. @type ancestor: C{str} @param ancestor: The superdomain name to test.
def assertIsSubdomainOf(testCase, descendant, ancestor): """ Assert that C{descendant} *is* a subdomain of C{ancestor}. @type testCase: L{unittest.SynchronousTestCase} @param testCase: The test case on which to run the assertions. @type descendant: C{str} @param descendant: The subdomain name to test. @type ancestor: C{str} @param ancestor: The superdomain name to test. """ testCase.assertTrue( dns._isSubdomainOf(descendant, ancestor), f"{descendant!r} is not a subdomain of {ancestor!r}", )
Assert that C{descendant} *is not* a subdomain of C{ancestor}. @type testCase: L{unittest.SynchronousTestCase} @param testCase: The test case on which to run the assertions. @type descendant: C{str} @param descendant: The subdomain name to test. @type ancestor: C{str} @param ancestor: The superdomain name to test.
def assertIsNotSubdomainOf(testCase, descendant, ancestor): """ Assert that C{descendant} *is not* a subdomain of C{ancestor}. @type testCase: L{unittest.SynchronousTestCase} @param testCase: The test case on which to run the assertions. @type descendant: C{str} @param descendant: The subdomain name to test. @type ancestor: C{str} @param ancestor: The superdomain name to test. """ testCase.assertFalse( dns._isSubdomainOf(descendant, ancestor), f"{descendant!r} is a subdomain of {ancestor!r}", )
Verify that an attribute has the expected default value and that a corresponding argument passed to a constructor is assigned to that attribute. @param testCase: The L{TestCase} whose assert methods will be called. @type testCase: L{unittest.TestCase} @param cls: The constructor under test. @type cls: L{type} @param argName: The name of the constructor argument under test. @type argName: L{str} @param defaultVal: The expected default value of C{attrName} / C{argName} @type defaultVal: L{object} @param altVal: A value which is different from the default. Used to test that supplied constructor arguments are actually assigned to the correct attribute. @type altVal: L{object} @param attrName: The name of the attribute under test if different from C{argName}. Defaults to C{argName} @type attrName: L{str}
def verifyConstructorArgument( testCase, cls, argName, defaultVal, altVal, attrName=None ): """ Verify that an attribute has the expected default value and that a corresponding argument passed to a constructor is assigned to that attribute. @param testCase: The L{TestCase} whose assert methods will be called. @type testCase: L{unittest.TestCase} @param cls: The constructor under test. @type cls: L{type} @param argName: The name of the constructor argument under test. @type argName: L{str} @param defaultVal: The expected default value of C{attrName} / C{argName} @type defaultVal: L{object} @param altVal: A value which is different from the default. Used to test that supplied constructor arguments are actually assigned to the correct attribute. @type altVal: L{object} @param attrName: The name of the attribute under test if different from C{argName}. Defaults to C{argName} @type attrName: L{str} """ if attrName is None: attrName = argName actual = {} expected = {"defaultVal": defaultVal, "altVal": altVal} o = cls() actual["defaultVal"] = getattr(o, attrName) o = cls(**{argName: altVal}) actual["altVal"] = getattr(o, attrName) testCase.assertEqual(expected, actual)