class ASN1_BIT_STRING(ASN1_Object[str]):
    """
     ASN1_BIT_STRING values are bit strings like "011101".
     A zero-bit padded readable string is provided nonetheless,
     which is stored in val_readable
    """
    tag = ASN1_Class_UNIVERSAL.BIT_STRING

    def __init__(self, val, readable=False):
        # type: (AnyStr, bool) -> None
        if not readable:
            self.val = cast(str, val)  # type: ignore
        else:
            self.val_readable = cast(bytes, val)  # type: ignore

    def __setattr__(self, name, value):
        # type: (str, Any) -> None
        if name == "val_readable":
            if isinstance(value, (str, bytes)):
                val = "".join(binrepr(orb(x)).zfill(8) for x in value)
            else:
                warning("Invalid val: should be bytes")
                val = "<invalid val_readable>"
            object.__setattr__(self, "val", val)
            object.__setattr__(self, name, bytes_encode(value))
            object.__setattr__(self, "unused_bits", 0)
        elif name == "val":
            value = plain_str(value)
            if isinstance(value, str):
                if any(c for c in value if c not in ["0", "1"]):
                    warning("Invalid operation: 'val' is not a valid bit string.")  # noqa: E501
                    return
                else:
                    if len(value) % 8 == 0:
                        unused_bits = 0
                    else:
                        unused_bits = 8 - (len(value) % 8)
                    padded_value = value + ("0" * unused_bits)
                    bytes_arr = zip(*[iter(padded_value)] * 8)
                    val_readable = b"".join(chb(int("".join(x), 2)) for x in bytes_arr)  # noqa: E501
            else:
                warning("Invalid val: should be str")
                val_readable = b"<invalid val>"
                unused_bits = 0
            object.__setattr__(self, "val_readable", val_readable)
            object.__setattr__(self, name, value)
            object.__setattr__(self, "unused_bits", unused_bits)
        elif name == "unused_bits":
            warning("Invalid operation: unused_bits rewriting "
                    "is not supported.")
        else:
            object.__setattr__(self, name, value)

    def __repr__(self):
        # type: () -> str
        s = self.val_readable
        if len(s) > 16:
            s = s[:10] + b"..." + s[-10:]
        v = self.val
        if len(v) > 20:
            v = v[:10] + "..." + v[-10:]
        return "<%s[%s]=%r (%d unused bit%s)>" % (
            self.__dict__.get("name", self.__class__.__name__),
            v,
            s,
            self.unused_bits,  # type: ignore
            "s" if self.unused_bits > 1 else ""  # type: ignore
        ) class ASN1_BOOLEAN(ASN1_INTEGER):
    tag = ASN1_Class_UNIVERSAL.BOOLEAN
    # BER: 0 means False, anything else means True

    def __repr__(self):
        # type: () -> str
        return '%s %s' % (not (self.val == 0), ASN1_Object.__repr__(self)) class ASN1_Class:
    pass class ASN1_Class_UNIVERSAL(ASN1_Class):
    name = "UNIVERSAL"
    # Those casts are made so that MyPy understands what the
    # metaclass does in the background.
    ERROR = cast(ASN1Tag, -3)
    RAW = cast(ASN1Tag, -2)
    NONE = cast(ASN1Tag, -1)
    ANY = cast(ASN1Tag, 0)
    BOOLEAN = cast(ASN1Tag, 1)
    INTEGER = cast(ASN1Tag, 2)
    BIT_STRING = cast(ASN1Tag, 3)
    STRING = cast(ASN1Tag, 4)
    NULL = cast(ASN1Tag, 5)
    OID = cast(ASN1Tag, 6)
    OBJECT_DESCRIPTOR = cast(ASN1Tag, 7)
    EXTERNAL = cast(ASN1Tag, 8)
    REAL = cast(ASN1Tag, 9)
    ENUMERATED = cast(ASN1Tag, 10)
    EMBEDDED_PDF = cast(ASN1Tag, 11)
    UTF8_STRING = cast(ASN1Tag, 12)
    RELATIVE_OID = cast(ASN1Tag, 13)
    SEQUENCE = cast(ASN1Tag, 16 | 0x20)     # constructed encoding
    SET = cast(ASN1Tag, 17 | 0x20)          # constructed encoding
    NUMERIC_STRING = cast(ASN1Tag, 18)
    PRINTABLE_STRING = cast(ASN1Tag, 19)
    T61_STRING = cast(ASN1Tag, 20)          # aka TELETEX_STRING
    VIDEOTEX_STRING = cast(ASN1Tag, 21)
    IA5_STRING = cast(ASN1Tag, 22)
    UTC_TIME = cast(ASN1Tag, 23)
    GENERALIZED_TIME = cast(ASN1Tag, 24)
    GRAPHIC_STRING = cast(ASN1Tag, 25)
    ISO646_STRING = cast(ASN1Tag, 26)       # aka VISIBLE_STRING
    GENERAL_STRING = cast(ASN1Tag, 27)
    UNIVERSAL_STRING = cast(ASN1Tag, 28)
    CHAR_STRING = cast(ASN1Tag, 29)
    BMP_STRING = cast(ASN1Tag, 30)
    IPADDRESS = cast(ASN1Tag, 0 | 0x40)     # application-specific encoding
    COUNTER32 = cast(ASN1Tag, 1 | 0x40)     # application-specific encoding
    GAUGE32 = cast(ASN1Tag, 2 | 0x40)       # application-specific encoding
    TIME_TICKS = cast(ASN1Tag, 3 | 0x40)    # application-specific encoding class ASN1_Error(Scapy_Exception):
    pass class ASN1_INTEGER(ASN1_Object[int]):
    tag = ASN1_Class_UNIVERSAL.INTEGER

    def __repr__(self):
        # type: () -> str
        h = hex(self.val)
        if h[-1] == "L":
            h = h[:-1]
        # cut at 22 because with leading '0x', x509 serials should be < 23
        if len(h) > 22:
            h = h[:12] + "..." + h[-10:]
        r = repr(self.val)
        if len(r) > 20:
            r = r[:10] + "..." + r[-10:]
        return h + " <%s[%s]>" % (self.__dict__.get("name", self.__class__.__name__), r)  # noqa: E501 class ASN1_NULL(ASN1_Object[None]):
    tag = ASN1_Class_UNIVERSAL.NULL

    def __repr__(self):
        # type: () -> str
        return ASN1_Object.__repr__(self) class ASN1_OID(ASN1_Object[str]):
    tag = ASN1_Class_UNIVERSAL.OID

    def __init__(self, val):
        # type: (str) -> None
        val = plain_str(val)
        val = conf.mib._oid(val)
        ASN1_Object.__init__(self, val)
        self.oidname = conf.mib._oidname(val)

    def __repr__(self):
        # type: () -> str
        return "<%s[%r]>" % (self.__dict__.get("name", self.__class__.__name__), self.oidname)  # noqa: E501 class ASN1_Object(Generic[_K]):
    tag = ASN1_Class_UNIVERSAL.ANY

    def __init__(self, val):
        # type: (_K) -> None
        self.val = val

    def enc(self, codec):
        # type: (Any) -> bytes
        return self.tag.get_codec(codec).enc(self.val)

    def __repr__(self):
        # type: () -> str
        return "<%s[%r]>" % (self.__dict__.get("name", self.__class__.__name__), self.val)  # noqa: E501

    def __str__(self):
        # type: () -> str
        return plain_str(self.enc(conf.ASN1_default_codec))

    def __bytes__(self):
        # type: () -> bytes
        return self.enc(conf.ASN1_default_codec)

    def strshow(self, lvl=0):
        # type: (int) -> str
        return ("  " * lvl) + repr(self) + "\n"

    def show(self, lvl=0):
        # type: (int) -> None
        print(self.strshow(lvl))

    def __eq__(self, other):
        # type: (Any) -> bool
        return bool(self.val == other)

    def __lt__(self, other):
        # type: (Any) -> bool
        return bool(self.val < other)

    def __le__(self, other):
        # type: (Any) -> bool
        return bool(self.val <= other)

    def __gt__(self, other):
        # type: (Any) -> bool
        return bool(self.val > other)

    def __ge__(self, other):
        # type: (Any) -> bool
        return bool(self.val >= other)

    def __ne__(self, other):
        # type: (Any) -> bool
        return bool(self.val != other)

    def command(self):
        # type: () -> str
        return "%s(%s)" % (self.__class__.__name__, repr(self.val)) class ASN1_STRING(ASN1_Object[str]):
    tag = ASN1_Class_UNIVERSAL.STRING class BER_Decoding_Error(ASN1_Decoding_Error):
    def __init__(self,
                 msg,  # type: str
                 decoded=None,  # type: Optional[Any]
                 remaining=b""  # type: bytes
                 ):
        # type: (...) -> None
        Exception.__init__(self, msg)
        self.remaining = remaining
        self.decoded = decoded

    def __str__(self):
        # type: () -> str
        s = Exception.__str__(self)
        if isinstance(self.decoded, ASN1_Object):
            s += "\n### Already decoded ###\n%s" % self.decoded.strshow()
        else:
            s += "\n### Already decoded ###\n%r" % self.decoded
        s += "\n### Remaining ###\n%r" % self.remaining
        return s def BER_id_dec(s):
    # type: (bytes) -> Tuple[int, bytes]
    # This returns the tag ALONG WITH THE PADDED CLASS+CONSTRUCTIVE INFO.
    # Let's recall that bits 8-7 from the first byte of the tag encode
    # the class information, while bit 6 means primitive or constructive.
    #
    # For instance, with low-tag-number b'\x81', class would be 0b10
    # ('context-specific') and tag 0x01, but we return 0x81 as a whole.
    # For b'\xff\x22', class would be 0b11 ('private'), constructed, then
    # padding, then tag 0x22, but we return (0xff>>5)*128^1 + 0x22*128^0.
    # Why the 5-bit-shifting? Because it provides an unequivocal encoding
    # on base 128 (note that 0xff would equal 1*128^1 + 127*128^0...),
    # as we know that bits 5 to 1 are fixed to 1 anyway.
    #
    # As long as there is no class differentiation, we have to keep this info
    # encoded in scapy's tag in order to reuse it for packet building.
    # Note that tags thus may have to be hard-coded with their extended
    # information, e.g. a SEQUENCE from asn1.py has a direct tag 0x20|16.
    x = orb(s[0])
    if x & 0x1f != 0x1f:
        # low-tag-number
        return x, s[1:]
    else:
        # high-tag-number
        return BER_num_dec(s[1:], cls_id=x >> 5) def BER_tagging_dec(s,  # type: bytes
                    hidden_tag=None,  # type: Optional[Any]
                    implicit_tag=None,  # type: Optional[int]
                    explicit_tag=None,  # type: Optional[int]
                    safe=False,  # type: Optional[bool]
                    ):
    # type: (...) -> Tuple[Optional[int], bytes]
    # We output the 'real_tag' if it is different from the (im|ex)plicit_tag.
    real_tag = None
    if len(s) > 0:
        err_msg = (
            "BER_tagging_dec: observed tag 0x%.02x does not "
            "match expected tag 0x%.02x"
        )
        if implicit_tag is not None:
            ber_id, s = BER_id_dec(s)
            if ber_id != implicit_tag:
                if not safe and ber_id & 0x1f != implicit_tag & 0x1f:
                    raise BER_Decoding_Error(err_msg % (ber_id, implicit_tag),
                                             remaining=s)
                else:
                    real_tag = ber_id
            s = chb(hash(hidden_tag)) + s
        elif explicit_tag is not None:
            ber_id, s = BER_id_dec(s)
            if ber_id != explicit_tag:
                if not safe:
                    raise BER_Decoding_Error(err_msg % (ber_id, explicit_tag),
                                             remaining=s)
                else:
                    real_tag = ber_id
            l, s = BER_len_dec(s)
    return real_tag, s def BER_tagging_enc(s, implicit_tag=None, explicit_tag=None):
    # type: (bytes, Optional[int], Optional[int]) -> bytes
    if len(s) > 0:
        if implicit_tag is not None:
            s = BER_id_enc(implicit_tag) + s[1:]
        elif explicit_tag is not None:
            s = BER_id_enc(explicit_tag) + BER_len_enc(len(s)) + s
    return s class GeneralizedTime(_AutoTime[str]):
    def __init__(self, diff=0):
        # type: (int) -> None
        super(GeneralizedTime, self).__init__(diff=diff)

    def _fix(self):
        # type: () -> str
        return time.strftime("%Y%m%d%H%M%SZ",
                             time.gmtime(time.time() + self.diff)) class RandChoice(RandField[Any]):
    def __init__(self, *args):
        # type: (*Any) -> None
        if not args:
            raise TypeError("RandChoice needs at least one choice")
        self._choice = list(args)

    def _command_args(self):
        # type: () -> str
        return ", ".join(self._choice)

    def _fix(self):
        # type: () -> Any
        return random.choice(self._choice) class RandInt(RandNum):
    def __init__(self):
        # type: () -> None
        RandNum.__init__(self, 0, 2**32 - 1) class RandNum(_RandNumeral[int]):
    """Instances evaluate to random integers in selected range"""
    min = 0
    max = 0

    def __init__(self, min, max):
        # type: (int, int) -> None
        self.min = min
        self.max = max

    def _command_args(self):
        # type: () -> str
        if self.__class__.__name__ == 'RandNum':
            return "min=%r, max=%r" % (self.min, self.max)
        return super(RandNum, self)._command_args()

    def _fix(self):
        # type: () -> int
        return random.randrange(self.min, self.max + 1)

    def __lshift__(self, other):
        # type: (int) -> int
        return self._fix() << other

    def __rshift__(self, other):
        # type: (int) -> int
        return self._fix() >> other

    def __and__(self, other):
        # type: (int) -> int
        return self._fix() & other

    def __rand__(self, other):
        # type: (int) -> int
        return other & self._fix()

    def __or__(self, other):
        # type: (int) -> int
        return self._fix() | other

    def __ror__(self, other):
        # type: (int) -> int
        return other | self._fix() class RandOID(_RandString[str]):
    def __init__(self, fmt=None, depth=RandNumExpo(0.1), idnum=RandNumExpo(0.01)):  # noqa: E501
        # type: (Optional[str], RandNumExpo, RandNumExpo) -> None
        super(RandOID, self).__init__()
        self.ori_fmt = fmt
        self.fmt = None  # type: Optional[List[Union[str, Tuple[int, ...]]]]
        if fmt is not None:
            self.fmt = [
                tuple(map(int, x.split("-"))) if "-" in x else x
                for x in fmt.split(".")
            ]
        self.depth = depth
        self.idnum = idnum

    def _command_args(self):
        # type: () -> str
        ret = []
        if self.fmt:
            ret.append("fmt=%r" % self.ori_fmt)

        if not isinstance(self.depth, VolatileValue):
            ret.append("depth=%r" % self.depth)
        elif not isinstance(self.depth, RandNumExpo) or \
                self.depth.lambd != 0.1 or self.depth.base != 0:
            ret.append("depth=%s" % self.depth.command())

        if not isinstance(self.idnum, VolatileValue):
            ret.append("idnum=%r" % self.idnum)
        elif not isinstance(self.idnum, RandNumExpo) or \
                self.idnum.lambd != 0.01 or self.idnum.base != 0:
            ret.append("idnum=%s" % self.idnum.command())

        return ", ".join(ret)

    def __repr__(self):
        # type: () -> str
        if self.ori_fmt is None:
            return "<%s>" % self.__class__.__name__
        else:
            return "<%s [%s]>" % (self.__class__.__name__, self.ori_fmt)

    def _fix(self):
        # type: () -> str
        if self.fmt is None:
            return ".".join(str(self.idnum) for _ in range(1 + self.depth))
        else:
            oid = []
            for i in self.fmt:
                if i == "*":
                    oid.append(str(self.idnum))
                elif i == "**":
                    oid += [str(self.idnum) for i in range(1 + self.depth)]
                elif isinstance(i, tuple):
                    oid.append(str(random.randrange(*i)))
                else:
                    oid.append(i)
            return ".".join(oid) class RandString(_RandString[bytes]):
    _DEFAULT_CHARS = (string.ascii_uppercase + string.ascii_lowercase +
                      string.digits).encode("utf-8")

    def __init__(self, size=None, chars=_DEFAULT_CHARS):
        # type: (Optional[Union[int, RandNum]], bytes) -> None
        if size is None:
            size = RandNumExpo(0.01)
        self.size = size
        self.chars = chars

    def _command_args(self):
        # type: () -> str
        ret = ""
        if isinstance(self.size, VolatileValue):
            if self.size.lambd != 0.01 or self.size.base != 0:
                ret += "size=%r" % self.size.command()
        else:
            ret += "size=%r" % self.size

        if self.chars != self._DEFAULT_CHARS:
            ret += ", chars=%r" % self.chars
        return ret

    def _fix(self):
        # type: () -> bytes
        s = b""
        for _ in range(int(self.size)):
            rdm_chr = random.choice(self.chars)
            s += rdm_chr if isinstance(rdm_chr, str) else chb(rdm_chr)
        return s class RandField(VolatileValue[_T], Generic[_T]):
    pass def raw(x):
    # type: (Union[Packet]) -> bytes
    """
    Builds a packet and returns its bytes representation.
    This function is and will always be cross-version compatible
    """
    if hasattr(x, "__bytes__"):
        return x.__bytes__()
    return bytes(x) class BasePacket(Gen['scapy.packet.Packet']):
    __slots__ = []  # type: List[str] _T = TypeVar("_T", Dict[str, Any], Optional[Dict[str, Any]])
        YTXTI = len(t)
        YTXT = float(YTXTI)
        YDUMP = YTXT
        XSTART = 1
        XDSTART = 10
        XMUL = 0.55
        YMUL = 0.4
class Packet(six.with_metaclass(Packet_metaclass,  # type: ignore
             BasePacket, _CanvasDumpExtended)):
class NoPayload(Packet):
class Raw(Packet):
class Padding(Raw):
    def from_hexcap(cls):
    def upper_bonds(self):
    def lower_bonds(self):
    def __init__(self,
                 _pkt=b"",  # type: bytes
                 post_transform=None,  # type: Any
                 _internal=0,  # type: int
                 _underlayer=None,  # type: Optional[Packet]
                 **fields  # type: Any
                 ):
    def __reduce__(self):
    def __setstate__(self, state):
    def __deepcopy__(self,
                     memo,  # type: Any
                     ):
    def init_fields(self):
    def do_init_fields(self,
                       flist,  # type: Sequence[AnyField]
                       ):
    def do_init_cached_fields(self):
    def prepare_cached_fields(self, flist):
    def dissection_done(self, pkt):
    def post_dissection(self, pkt):
    def get_field(self, fld):
    def add_payload(self, payload):
    def remove_payload(self):
    def add_underlayer(self, underlayer):
    def remove_underlayer(self, other):
    def copy(self):
    def _resolve_alias(self, attr):
    def getfieldval(self, attr):
    def getfield_and_val(self, attr):
    def __getattr__(self, attr):
    def setfieldval(self, attr, val):
    def __setattr__(self, attr, val):
    def delfieldval(self, attr):
    def __delattr__(self, attr):
    def _superdir(self):
    def __dir__(self):
    def __repr__(self):
        def __str__(self):
        def __str__(self):
    def __bytes__(self):
    def __div__(self, other):
    def __rdiv__(self, other):
    def __mul__(self, other):
    def __rmul__(self, other):
    def __nonzero__(self):
    def __len__(self):
    def copy_field_value(self, fieldname, value):
    def copy_fields_dict(self, fields):
    def clear_cache(self):
    def self_build(self):
    def do_build_payload(self):
    def do_build(self):
    def build_padding(self):
    def build(self):
    def post_build(self, pkt, pay):
    def build_done(self, p):
    def do_build_ps(self):
    def build_ps(self, internal=0):
    def canvas_dump(self, layer_shift=0, rebuild=1):
        def hexstr(x):
        def make_dump_txt(x, y, txt):
        def make_box(o):
        def make_frame(lst):
        def make_dump(s,   # type: bytes
                      shift=0,  # type: int
                      y=0.,  # type: float
                      col=None,  # type: pyx.color.color
                      bkcol=None,  # type: pyx.color.color
                      large=16  # type: int
                      ):
    def extract_padding(self, s):
    def post_dissect(self, s):
    def pre_dissect(self, s):
    def do_dissect(self, s):
    def do_dissect_payload(self, s):
    def dissect(self, s):
    def guess_payload_class(self, payload):
    def default_payload_class(self, payload):
    def hide_defaults(self):
    def clone_with(self, payload=None, **kargs):
    def __iter__(self):
        def loop(todo, done, self=self):
    def iterpayloads(self):
    def __gt__(self, other):
    def __lt__(self, other):
    def __eq__(self, other):
    def __ne__(self, other):
    def hashret(self):
    def answers(self, other):
    def layers(self):
    def haslayer(self, cls, _subclass=None):
    def getlayer(self,
                 cls,  # type: Union[int, Type[Packet], str]
                 nb=1,  # type: int
                 _track=None,  # type: Optional[List[int]]
                 _subclass=None,  # type: Optional[bool]
                 **flt  # type: Any
                 ):
    def firstlayer(self):
    def __getitem__(self, cls):
    def __delitem__(self, cls):
    def __setitem__(self, cls, val):
    def __contains__(self, cls):
    def route(self):
    def fragment(self, *args, **kargs):
    def display(self, *args, **kargs):  # Deprecated. Use show()
    def _show_or_dump(self,
                      dump=False,  # type: bool
                      indent=3,  # type: int
                      lvl="",  # type: str
                      label_lvl="",  # type: str
                      first_call=True  # type: bool
                      ):
    def show(self, dump=False, indent=3, lvl="", label_lvl=""):
    def show2(self, dump=False, indent=3, lvl="", label_lvl=""):
    def sprintf(self, fmt, relax=1):
    def mysummary(self):
    def _do_summary(self):
    def summary(self, intern=0):
    def lastlayer(self, layer=None):
    def decode_payload_as(self, cls):
    def command(self):
    def __new__(cls, *args, **kargs):
    def __init__(self, *args, **kargs):
    def dissection_done(self, pkt):
    def add_payload(self, payload):
    def remove_payload(self):
    def add_underlayer(self, underlayer):
    def remove_underlayer(self, other):
    def copy(self):
    def clear_cache(self):
    def __repr__(self):
    def __str__(self):
    def __bytes__(self):
    def __nonzero__(self):
    def do_build(self):
    def build(self):
    def build_padding(self):
    def build_done(self, p):
    def build_ps(self, internal=0):
    def getfieldval(self, attr):
    def getfield_and_val(self, attr):
    def setfieldval(self, attr, val):
    def delfieldval(self, attr):
    def hide_defaults(self):
    def __iter__(self):
    def __eq__(self, other):
    def hashret(self):
    def answers(self, other):
    def haslayer(self, cls, _subclass=None):
    def getlayer(self,
                 cls,  # type: Union[int, Type[Packet], str]
                 nb=1,  # type: int
                 _track=None,  # type: Optional[List[int]]
                 _subclass=None,  # type: Optional[bool]
                 **flt  # type: Any
                 ):
    def fragment(self, *args, **kargs):
    def show(self, dump=False, indent=3, lvl="", label_lvl=""):
    def sprintf(self, fmt, relax=1):
    def _do_summary(self):
    def layers(self):
    def lastlayer(self, layer=None):
    def command(self):
    def route(self):
    def __init__(self, _pkt=b"", *args, **kwargs):
    def answers(self, other):
    def mysummary(self):
    def self_build(self, field_pos_list=None):
    def build_padding(self):
def bind_bottom_up(lower,  # type: Type[Packet]
                   upper,  # type: Type[Packet]
                   __fval=None,  # type: Optional[Any]
                   **fval  # type: Any
                   ):
def bind_top_down(lower,  # type: Type[Packet]
                  upper,  # type: Type[Packet]
                  __fval=None,  # type: Optional[Any]
                  **fval  # type: Any
                  ):
def bind_layers(lower,  # type: Type[Packet]
                upper,  # type: Type[Packet]
                __fval=None,  # type: Optional[Dict[str, int]]
                **fval  # type: Any
                ):
def split_bottom_up(lower,  # type: Type[Packet]
                    upper,  # type: Type[Packet]
                    __fval=None,  # type: Optional[Any]
                    **fval  # type: Any
                    ):
    def do_filter(params, cls):
def split_top_down(lower,  # type: Type[Packet]
                   upper,  # type: Type[Packet]
                   __fval=None,  # type: Optional[Any]
                   **fval  # type: Any
                   ):
def split_layers(lower,  # type: Type[Packet]
                 upper,  # type: Type[Packet]
                 __fval=None,  # type: Optional[Any]
                 **fval  # type: Any
                 ):
def explore(layer=None):
def _pkt_ls(obj,  # type: Union[Packet, Type[Packet]]
            verbose=False,  # type: bool
            ):
def ls(obj=None,  # type: Optional[Union[str, Packet, Type[Packet]]]
       case_sensitive=False,  # type: bool
       verbose=False  # type: bool
       ):
def rfc(cls, ret=False, legend=True):
def fuzz(p,  # type: Packet
         _inplace=0,  # type: int
         ):     FAKE_TYPING = False
    FAKE_TYPING = True
    TYPE_CHECKING = False
    IO = _FakeType("IO")  # type: ignore
        AF_INET = socket.AF_INET
        AF_INET6 = socket.AF_INET6
class _Generic_metaclass(type):
    class _FT(object):
    class Sized(object):  # type: ignore
    class Generic(object):  # type: ignore
        class _NT(cls):
    class AddressFamily:
        def __getitem__(self, typ):
def _FakeType(name, cls=object):
        def __init__(self, name):
        def __getitem__(self, item):  # type: ignore
        def __call__(self, *args, **kargs):
        def __repr__(self):
    def cast(_type, obj):  # type: ignore
    def _unpickleNamedTuple(name, len_params, *args):
    def NamedTuple(name, params):
            def __reduce__(self):
def lambda_tuple_converter(func):
    def chb(x):
    def raw(x):
    def raw(x):
    def bytes_encode(x):
        def plain_str(x):
        def plain_str(x):
    def chb(x):
    def orb(x):
def bytes_hex(x):
def hex_bytes(x):
    def int_bytes(x, size):
    def bytes_int(x):
    def int_bytes(x, size):
    def bytes_int(x):
def base64_bytes(x):
def bytes_base64(x):
    def gzip_decompress(x):
    def gzip_compress(x):
from scapy.asn1.asn1 import (
    ASN1_BIT_STRING,
    ASN1_BOOLEAN,
    ASN1_Class,
    ASN1_Class_UNIVERSAL,
    ASN1_Error,
    ASN1_INTEGER,
    ASN1_NULL,
    ASN1_OID,
    ASN1_Object,
    ASN1_STRING,
)
from scapy.asn1.ber import (
    BER_Decoding_Error,
    BER_id_dec,
    BER_tagging_dec,
    BER_tagging_enc,
)
from scapy.volatile import (
    GeneralizedTime,
    RandChoice,
    RandInt,
    RandNum,
    RandOID,
    RandString,
    RandField,
)
from scapy.compat import raw
from scapy.base_classes import BasePacket
from scapy import packet
from functools import reduce
from scapy.compat import (
    Any,
    AnyStr,
    Callable,
    Dict,
    Generic,
    List,
    Optional,
    Tuple,
    Type,
    TypeVar,
    Union,
    cast,
    TYPE_CHECKING,
)
    from scapy.asn1packet import ASN1_Packet
import scapy.modules.six as six
        return lst, remain

    def build(self, pkt):
        # type: (ASN1_Packet) -> bytes
        val = getattr(pkt, self.name)
        if isinstance(val, ASN1_Object) and \
                val.tag == ASN1_Class_UNIVERSAL.RAW:
            s = cast(Union[List[ASN1_Packet], bytes], val)
        elif val is None:
            s = b""
        else:
            s = b"".join(raw(i) for i in val)
        return self.i2m(pkt, s)

    def randval(self):
        # type: () -> ASN1_Packet
        return packet.fuzz(self.cls())

    def __repr__(self):
        # type: () -> str
        return "<%s %s>" % (self.__class__.__name__, self.name)


class ASN1F_SET_OF(ASN1F_SEQUENCE_OF):
    ASN1_tag = ASN1_Class_UNIVERSAL.SET


class ASN1F_IPADDRESS(ASN1F_STRING):
    ASN1_tag = ASN1_Class_UNIVERSAL.IPADDRESS


class ASN1F_TIME_TICKS(ASN1F_INTEGER):
    ASN1_tag = ASN1_Class_UNIVERSAL.TIME_TICKS


#############################
#    Complex ASN1 Fields    #
#############################

class ASN1F_optional(ASN1F_element):
    def __init__(self, field):
        # type: (ASN1F_field[Any, Any]) -> None
        field.flexible_tag = False
        self._field = field

    def __getattr__(self, attr):
        # type: (str) -> Optional[Any]
        return getattr(self._field, attr)

    def m2i(self, pkt, s):
        # type: (ASN1_Packet, bytes) -> Tuple[Any, bytes]
        try:
            return self._field.m2i(pkt, s)
        except (ASN1_Error, ASN1F_badsequence, BER_Decoding_Error):
            # ASN1_Error may be raised by ASN1F_CHOICE
            return None, s

    def dissect(self, pkt, s):
        # type: (ASN1_Packet, bytes) -> bytes
        try:
            return self._field.dissect(pkt, s)
        except (ASN1_Error, ASN1F_badsequence, BER_Decoding_Error):
            self._field.set_val(pkt, None)
            return s

    def build(self, pkt):
        # type: (ASN1_Packet) -> bytes
        if self._field.is_empty(pkt):
            return b""
        return self._field.build(pkt)

    def any2i(self, pkt, x):
        # type: (ASN1_Packet, Any) -> Any
        return self._field.any2i(pkt, x)

    def i2repr(self, pkt, x):
        # type: (ASN1_Packet, Any) -> str
        return self._field.i2repr(pkt, x)


_CHOICE_T = Union['ASN1_Packet', Type[ASN1F_field], 'ASN1F_PACKET']


class ASN1F_CHOICE(ASN1F_field[_CHOICE_T, ASN1_Object[Any]]):
    """
    Multiple types are allowed: ASN1_Packet, ASN1F_field and ASN1F_PACKET(),
    See layers/x509.py for examples.
    Other ASN1F_field instances than ASN1F_PACKET instances must not be used.
    """
    holds_packets = 1
    ASN1_tag = ASN1_Class_UNIVERSAL.ANY

    def __init__(self, name, default, *args, **kwargs):
        # type: (str, Any, *_CHOICE_T, **Any) -> None
        if "implicit_tag" in kwargs:
            err_msg = "ASN1F_CHOICE has been called with an implicit_tag"
            raise ASN1_Error(err_msg)
        self.implicit_tag = None
        for kwarg in ["context", "explicit_tag"]:
            setattr(self, kwarg, kwargs.get(kwarg))
        super(ASN1F_CHOICE, self).__init__(
            name, None, context=self.context,
            explicit_tag=self.explicit_tag
        )
        self.default = default
        self.current_choice = None
        self.choices = {}  # type: Dict[int, _CHOICE_T]
        self.pktchoices = {}
        for p in args:
            if hasattr(p, "ASN1_root"):
                p = cast('ASN1_Packet', p)
                # should be ASN1_Packet
                if hasattr(p.ASN1_root, "choices"):
                    root = cast(ASN1F_CHOICE, p.ASN1_root)
                    for k, v in six.iteritems(root.choices):
                        # ASN1F_CHOICE recursion
                        self.choices[k] = v
                else:
                    self.choices[p.ASN1_root.network_tag] = p
            elif hasattr(p, "ASN1_tag"):

                p = cast(Union[ASN1F_PACKET, Type[ASN1F_field[Any, Any]]], p)