Exemple #1
0
 class ConstDefaultTest(DataclassMixin):
     const_bytes: bytes = csfield(cs.Const(b"BMP"))
     const_int: int = csfield(cs.Const(5, cs.Int8ub))
     default_int: int = csfield(cs.Default(cs.Int8ub, 28))
     default_lambda: bytes = csfield(
         cs.Default(cs.Bytes(cs.this.const_int),
                    lambda ctx: bytes(ctx.const_int)))
Exemple #2
0
 class Image(DataclassMixin):
     width: int = csfield(cs.Int8ub)
     height: int = csfield(cs.Int8ub)
     pixels: t.Optional[bytes] = csfield(
         cs.Default(
             cs.Bytes(cs.this.width * cs.this.height),
             lambda ctx: bytes(ctx.width * ctx.height),
         ))
 class Image(cst.TContainerBase):
     width: int = cst.TStructField(cs.Int8ub)
     height: int = cst.TStructField(cs.Int8ub)
     pixels: cst.Opt[bytes] = cst.TStructField(
         cs.Default(
             cs.Bytes(cs.this.width * cs.this.height),
             lambda ctx: bytes(ctx.width * ctx.height),
         ))
Exemple #4
0
    def __rtruediv__(self, field_name):
        field_type = self._get_type_for_name(field_name)

        if self.default is not None:
            field_type = construct.Default(field_type, self.default)

        # Build our subconstruct. Construct makes this look super weird,
        # but this is actually "we have a field with <field_name> of type <field_type>".
        # In long form, we'll call it "description".
        return (field_name / field_type) * self.description
Exemple #5
0
    def __rtruediv__(self, field_name):
        # If we have a length, use it to figure out the type.
        # Otherwise, extract the type from the prefix. (Using a length
        # is useful for e.g. USB3 bitfields; which can span several bytes.)
        if self.length is not None:
            field_type = self.LENGTH_TYPES[self.length]
        else:
            field_type = self._get_type_for_name(field_name)

        if self.default is not None:
            field_type = construct.Default(field_type, self.default)

        # Build our subconstruct. Construct makes this look super weird,
        # but this is actually "we have a field with <field_name> of type <field_type>".
        # In long form, we'll call it "description".
        return (field_name / field_type) * self.description
Exemple #6
0
    # "start" / Pointer(8, Bytes(1)),
    # For debug purposes this could potentially contain argument names.
    # Or have a separate 'debug' entry for details only needed for debugging
    # or reverse-engineering.
)

instruction_definition = construct.Struct(
    "opcode" / construct.Enum(construct.Byte, Opcode),
    "operand_a" / construct.Int8ub,
    "operand_b" / construct.Int8ub,
    "reserved" / construct.Const(0xFF, construct.Int8ub),
)

binary = construct.Struct(
    "signature" / construct.Const(b"DC"),
    "features" / construct.Default(construct.Int16ub, 0),
    "version" / construct.Default(construct.Byte, FILE_FORMAT_VERSION),
    "reserved" / construct.Const(0xCD, construct.Int8ub),
    "symbol_count" / construct.Int8ub,
    "symbols" / construct.Array(construct.this.symbol_count, symbol_entry),
    "instruction_count" / construct.Int16ub,
    "instructions" /
    construct.Array(construct.this.instruction_count, instruction_definition),
)


def binary_to_textual(source, writer: io.TextIOBase):
    """Convert a file in binary format to textual format."""
    parsed = binary.parse(source)
    writer.write(f'// Digital Circuit File - version {parsed.version}\n')
    if parsed.features:
Exemple #7
0
                                        C.len_(this.data) - offs),
                     "data" / C.Bytes(this.size + offs)), lambda obj:
            {"data": type.build(obj.content, **{
                **obj._params,
                **obj
            })}), "content" / C.RestreamData(this._data.data, type))


# Class definition handling

ClassMemberDefinition = Struct(
    "name" / DataPointer(Int64ul, CString("utf8"), "names"),
    "type" / Byte,
    "unkn" / Byte,
    "size" / Byte,
    "_unknData" / C.Default(Byte[69], [0 for _ in range(69)]),
)

ClassDefinition = DataPointer(
    Int64ul,
    Struct("hash" / Int64ul,
           "members" / C.PrefixedArray(Int64ul, ClassMemberDefinition)),
    "definitionData")

ClassDefinitionList = C.FocusedSeq(
    "definitions", "_count" / C.Rebuild(Int32ul, C.len_(this.definitions)),
    "definitions" / C.Prefixed(
        Int32ul,
        C.Aligned(
            8,
            C.FocusedSeq(
    'version' / construct.PascalString(construct.Byte, encoding='ascii'),
)

_SERIAL_NUMBER_REQUEST = construct.Const(
    b'\x05\x0B\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00')

_SERIAL_NUMBER_RESPONSE = construct.Struct(
    _COMMAND_SUCCESS,
    'serial_number' / construct.GreedyString(encoding='ascii'),
)

_DATETIME_REQUEST = construct.Struct(
    construct.Const(b'\x05\x20'),  # 0x20 is the datetime
    'request_type' / construct.Enum(construct.Byte, write=0x01, read=0x02),
    'timestamp' / construct.Default(
        construct_extras.Timestamp(construct.Int32ul),  # type: ignore
        datetime.datetime(1970, 1, 1, 0, 0)),
)

_DATETIME_RESPONSE = construct.Struct(
    _COMMAND_SUCCESS,
    'timestamp' /
    construct_extras.Timestamp(construct.Int32ul),  # type: ignore
)

_GLUCOSE_UNIT_REQUEST = construct.Const(b'\x05\x09\x02\x09\x00\x00\x00\x00')

_GLUCOSE_UNIT_RESPONSE = construct.Struct(
    _COMMAND_SUCCESS,
    'unit' / lifescan_binary_protocol.GLUCOSE_UNIT,
    construct.Padding(3),
import construct

try:
    import anyio
except ImportError:
    ASYNC_AVAILABLE = False
else:
    ASYNC_AVAILABLE = True

PACKET_PARSER = construct.GreedyRange(
    construct.Prefixed(
        construct.Int32sl,
        construct.Struct("id" / construct.Int32sl, "type" / construct.Int32sl,
                         "body" / construct.CString("utf8"),
                         construct.Default(construct.CString("utf8"), ""))))


class RCONBaseError(Exception):
    """Exception base for all exceptions in this library"""


class ClientBusy(RCONBaseError):
    """Client is already busy with another call"""


class InvalidPassword(RCONBaseError):
    """RCON password is incorrect"""


class InvalidResponse(RCONBaseError):
Exemple #10
0
                   KHz200=0,
                   KHz50=1,
                   KHz83=2,
                   KHz455=3,
                   KHz800=4,
                   Khz38=5,
                   KHz28=6,
                   Khz130Khz210=7,
                   Khz90Khz150=8,
                   KHz40Khz60=9,
                   KHz25KHz45=10)

sl2_frame = c.Struct(
    # 0
    frame_offset=c.Int32ul,
    last_frame_offset_primary=c.Default(c.Int32ul, 0),
    last_frame_offset_secondary=c.Default(c.Int32ul, 0),
    last_frame_offset_down_scan=c.Default(c.Int32ul, 0),
    last_frame_offset_left=c.Default(c.Int32ul, 0),
    last_frame_offset_right=c.Default(c.Int32ul, 0),
    last_frame_offset_composite=c.Default(c.Int32ul, 0),
    # 28
    frame_size=c.Int16ul,
    previous_frame_size=c.Int16ul,
    channel_type=ChannelType,
    packet_size=c.Int16ul,
    # 36
    frame_index=c.Int32ul,
    upper_limit_feet=c.Float32l,
    lower_limit_feet=c.Float32l,
    # 48
"""Support module for the LifeScan binary protocol.

A number of LifeScan devices use a semi-compatible binary protocol to talk host
and device, which is (vastly) compatible.

This module implements an interface to send and receive these messages.
"""

import construct

from glucometerutils import common
from glucometerutils.support import construct_extras, lifescan

_LINK_CONTROL = construct.BitStruct(
    construct.Padding(3),
    "more" / construct.Default(construct.Flag, False),
    "disconnect" / construct.Default(construct.Flag, False),
    "acknowledge" / construct.Default(construct.Flag, False),
    "expect_receive" / construct.Default(construct.Flag, False),
    "sequence_number" / construct.Default(construct.Flag, False),
)


def LifeScanPacket(include_link_control: bool, ) -> construct.Struct:  # pylint: disable=invalid-name
    if include_link_control:
        link_control_construct = _LINK_CONTROL
    else:
        link_control_construct = construct.Const(b"\x00")

    return construct.Struct(
        "data" / construct.RawCopy(
Exemple #12
0
"""

__author__ = 'Diego Elio Pettenò'
__email__ = '*****@*****.**'
__copyright__ = 'Copyright © 2014-2018, Diego Elio Pettenò'
__license__ = 'MIT'

import construct

from glucometerutils import common
from glucometerutils.support import construct_extras
from glucometerutils.support import lifescan

_LINK_CONTROL = construct.BitStruct(
    construct.Padding(3),
    'more' / construct.Default(construct.Flag, False),
    'disconnect' / construct.Default(construct.Flag, False),
    'acknowledge' / construct.Default(construct.Flag, False),
    'expect_receive' / construct.Default(construct.Flag, False),
    'sequence_number' / construct.Default(construct.Flag, False),
)


def LifeScanPacket(command_prefix, include_link_control):
    if include_link_control:
        link_control_construct = _LINK_CONTROL
    else:
        link_control_construct = construct.Const(b'\x00')

    command_prefix_construct = construct.Const(command_prefix, construct.Byte)
def profile_base(is_v1, recipe_name_encoding="GBK"):
    """Build a Construct for IHCooker recipes based on version and name encoding."""
    return c.Struct(
        c.Const(3, c.Int8un),
        "device_version" / c.Default(c.Enum(c.Int8ub, **DEVICE_ID), 1 if is_v1 else 2),
        "menu_location"
        / c.Default(c.ExprValidator(c.Int8ub, lambda o, _: 0 <= o < 10), 9),
        "recipe_name"
        / c.Default(
            c.ExprAdapter(
                c.StringEncoded(  # PaddedString wrapper does not support GBK encoding.
                    c.FixedSized(
                        RECIPE_NAME_MAX_LEN_V1 if is_v1 else RECIPE_NAME_MAX_LEN_V2,
                        c.NullStripped(c.GreedyBytes),
                    ),
                    recipe_name_encoding,
                ),
                lambda x, _: x.replace("\n", " "),
                lambda x, _: x.replace(" ", "\n"),
            ),
            "Unnamed",
        ),
        c.Padding(1) if is_v1 else c.Padding(2),
        "recipe_id" / c.Default(c.Int32ub, lambda _: random.randint(0, 2 ** 32 - 1)),
        "menu_settings"
        / c.Default(
            c.BitStruct(  # byte 37
                "save_recipe" / c.Default(c.Flag, 0),
                "confirm_start" / c.Default(c.Flag, 0),
                "menu_unknown3" / c.Default(c.Flag, 0),
                "menu_unknown4" / c.Default(c.Flag, 0),
                "menu_unknown5" / c.Default(c.Flag, 0),
                "menu_unknown6" / c.Default(c.Flag, 0),
                "menu_unknown7" / c.Default(c.Flag, 0),
                "menu_unknown8" / c.Default(c.Flag, 0),
            ),
            {},
        ),
        "duration_hours"
        / c.Rebuild(
            c.Int8ub, lambda ctx: ctx.get("duration_minutes", 0) // 60
        ),  # byte 38
        "duration_minutes"
        / c.Default(
            c.ExprAdapter(
                c.Int8ub, lambda obj, ctx: obj + ctx.duration_hours * 60, c.obj_ % 60
            ),
            60,
        ),  # byte 39
        "duration_max_hours"
        / c.Rebuild(
            c.Int8ub, lambda ctx: ctx.get("duration_max_minutes", 0) // 60
        ),  # byte 40
        "duration_max_minutes"
        / c.Default(
            c.ExprAdapter(
                c.Int8ub,
                lambda obj, ctx: obj + ctx.duration_max_hours * 60,
                c.obj_ % 60,
            ),
            0,
        ),  # byte 41
        "duration_min_hours"
        / c.Rebuild(
            c.Int8ub, lambda ctx: ctx.get("duration_min_minutes", 0) // 60
        ),  # byte 42
        "duration_min_minutes"
        / c.Default(
            c.ExprAdapter(
                c.Int8ub,
                lambda obj, ctx: obj + ctx.duration_min_hours * 60,
                c.obj_ % 60,
            ),
            0,
        ),  # byte 43
        c.Padding(2),  # byte 44, 45
        "unknown_46" / c.Default(c.Byte, 1),  # byte 46, should be set to 1
        c.Padding(7) if is_v1 else c.Padding(1),
        "stages"
        / c.Default(
            ArrayDefault(
                15,
                c.Struct(  # byte 48-168
                    "mode" / c.Default(c.Enum(c.Byte, StageMode), StageMode.FireMode),
                    "hours"
                    / c.Rebuild(
                        c.Int8ub, lambda ctx: (ctx.get("minutes", 0) // 60) + 128
                    ),
                    "minutes"
                    / c.Default(
                        c.ExprAdapter(
                            c.Int8ub,
                            decoder=lambda obj, ctx: obj + (ctx.hours - 128) * 60,
                            encoder=c.obj_ % 60,
                        ),
                        DEFAULT_PHASE_MINUTES,
                    ),
                    "temp_threshold" / c.Default(c.Int8ub, DEFAULT_THRESHOLD_CELCIUS),
                    "temp_target" / c.Default(c.Int8ub, DEFAULT_TEMP_TARGET_CELCIUS),
                    "power" / c.Default(c.Int8ub, DEFAULT_FIRE_LEVEL),
                    "fire_off" / c.Default(c.Int8ub, DEFAULT_FIRE_ON_OFF),
                    "fire_on" / c.Default(c.Int8ub, DEFAULT_FIRE_ON_OFF),
                ),
                default=dict(
                    mode=StageMode.FireMode,
                    minutes=DEFAULT_PHASE_MINUTES,
                    temp_threshold=DEFAULT_THRESHOLD_CELCIUS,
                    temp_target=DEFAULT_TEMP_TARGET_CELCIUS,
                    power=DEFAULT_FIRE_LEVEL,
                    fire_off=DEFAULT_FIRE_ON_OFF,
                    fire_on=DEFAULT_FIRE_ON_OFF,
                ),
            ),
            [],
        ),
        c.Padding(16) if is_v1 else c.Padding(6),  # byte 169-174
        "unknown175" / c.Default(c.Int8ub, 0),
        "unknown176" / c.Default(c.Int8ub, 0),
        "unknown177" / c.Default(c.Int8ub, 0),
        "crc"  # byte 178-179
        / RebuildStream(
            c.Bytes(2), crc16
        ),  # Default profiles have invalid crc, c.Checksum() raises undesired error when parsed.
    )
    'version' / construct.PascalString(construct.Byte, encoding='ascii'),
)

_SERIAL_NUMBER_REQUEST = construct.Const(
    b'\x05\x0B\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00')

_SERIAL_NUMBER_RESPONSE = construct.Struct(
    _COMMAND_SUCCESS,
    'serial_number' / construct.GreedyString(encoding='ascii'),
)

_DATETIME_REQUEST = construct.Struct(
    construct.Const(b'\x05\x20'),  # 0x20 is the datetime
    'request_type' / construct.Enum(construct.Byte, write=0x01, read=0x02),
    'timestamp' /
    construct.Default(construct_extras.Timestamp(construct.Int32ul),
                      datetime.datetime(1970, 1, 1, 0, 0)),
)

_DATETIME_RESPONSE = construct.Struct(
    _COMMAND_SUCCESS,
    'timestamp' / construct_extras.Timestamp(construct.Int32ul),
)

_GLUCOSE_UNIT_REQUEST = construct.Const(b'\x05\x09\x02\x09\x00\x00\x00\x00')

_GLUCOSE_UNIT_RESPONSE = construct.Struct(
    _COMMAND_SUCCESS,
    'unit' / lifescan_binary_protocol.GLUCOSE_UNIT,
    construct.Padding(3),
)
Exemple #15
0
    "bAlternateSetting" / DescriptorField("Alternate setting", default=0),
    "bNumEndpoints" / DescriptorField("Endpoints included"),
    "bInterfaceClass" / DescriptorField("Class", default=0xff),
    "bInterfaceSubclass" / DescriptorField("Subclass", default=0xff),
    "bInterfaceProtocol" / DescriptorField("Protocol", default=0xff),
    "iInterface" / DescriptorField("String index", default=0),
)

EndpointDescriptor = DescriptorFormat(

    # [USB2.0: 9.6; USB Audio Device Class Definition 1.0: 4.6.1.1, 4.6.2.1]
    # Interfaces of the Audio 1.0 class extend their subordinate endpoint descriptors with
    # 2 additional bytes (extending it from 7 to 9 bytes). Thankfully, this is the only extension that
    # changes the length of a standard descriptor type, but we do have to handle this case in Construct.
    "bLength" /
    construct.Default(construct.OneOf(construct.Int8ul, [7, 9]), 7),
    "bDescriptorType" / DescriptorNumber(StandardDescriptorNumbers.ENDPOINT),
    "bEndpointAddress" / DescriptorField("Endpoint Address"),
    "bmAttributes" / DescriptorField("Attributes", default=2),
    "wMaxPacketSize" / DescriptorField("Maximum Packet Size", default=64),
    "bInterval" / DescriptorField("Polling interval", default=255),

    # 2 bytes that are only present on endpoint descriptors for Audio 1.0 class interfaces.
    ("bRefresh" / construct.Optional(construct.Int8ul)) * "Refresh Rate",
    ("bSynchAddress" / construct.Optional(construct.Int8ul)) *
    "Synch Endpoint Address",
)

DeviceQualifierDescriptor = DescriptorFormat(
    "bLength" / construct.Const(9, construct.Int8ul), "bDescriptorType" /
    DescriptorNumber(StandardDescriptorNumbers.DEVICE_QUALIFIER),
func_sig_t = con.Struct(
    "version" / Const(1, IdaVarInt32),  # protocol version (con.Default: 1)
    "signature" / VarBuff  # signature buffer
)

# a.k.a func_info_t
func_metadata = con.Struct(
    "func_name" / CString("utf8"),  # function name
    "func_size" / IdaVarInt32,  # function size in bytes
    "serialized_data" / VarBuff  # metadata
)

# extended func_metadata
func_info_t = con.Struct(
    "metadata" / func_metadata,  #
    "popularity" / con.Default(IdaVarInt32, 0),  # unknown
)

func_md_t = con.Struct("metadata" / func_metadata, "signature" / func_sig_t)

# same as func_md_t with extra (unknown) field
func_md2_t = con.Struct(
    "metadata" / func_metadata,
    "signature" / func_sig_t,
    "field_0x58" / Hex(Const(0, IdaVarInt32)),
)

#######################################
#
# Lumina message types
#
"""Support module for the LifeScan binary protocol.

A number of LifeScan devices use a semi-compatible binary protocol to talk host
and device, which is (vastly) compatible.

This module implements an interface to send and receive these messages.
"""

import construct

from glucometerutils import common
from glucometerutils.support import construct_extras, lifescan

_LINK_CONTROL = construct.BitStruct(
    padding=construct.Padding(3),
    more=construct.Default(construct.Flag, False),
    disconnect=construct.Default(construct.Flag, False),
    acknowledge=construct.Default(construct.Flag, False),
    expect_receive=construct.Default(construct.Flag, False),
    sequence_number=construct.Default(construct.Flag, False),
)


def LifeScanPacket(
    include_link_control: bool,
) -> construct.Struct:  # pylint: disable=invalid-name
    if include_link_control:
        link_control_construct = _LINK_CONTROL
    else:
        link_control_construct = construct.Const(b"\x00")
    """
    return bytes(~b & 0xFF for b in data)[::-1]


# fmt: off
Toif = c.Struct(
    "magic" / c.Const(b"TOI"),
    "format" / c.Enum(c.Byte, full_color=b"f", grayscale=b"g"),
    "width" / c.Int16ul,
    "height" / c.Int16ul,
    "data" / c.Prefixed(c.Int32ul, c.GreedyBytes),
)

VendorTrust = c.Transformed(
    c.BitStruct(
        "reserved" / c.Default(c.BitsInteger(9), 0),
        "show_vendor_string" / c.Flag,
        "require_user_click" / c.Flag,
        "red_background" / c.Flag,
        "delay" / c.BitsInteger(4),
    ), _transform_vendor_trust, 2, _transform_vendor_trust, 2)

VendorHeader = c.Struct(
    "_start_offset" / c.Tell,
    "magic" / c.Const(b"TRZV"),
    "_header_len" / c.Padding(4),
    "expiry" / c.Int32ul,
    "version" / c.Struct(
        "major" / c.Int8ul,
        "minor" / c.Int8ul,
    ),
Exemple #19
0
import construct
from enum import Enum
from trio_socks.socks5.constructs import PackEnum, IPv4Address, IPv6Address


class AuthMethod(Enum):
    no_auth = 0x0
    gssap = 0x1
    username_password = 0x2


auth_methods = AuthMethod

ClientGreeting = construct.Struct(
    'version' / construct.Default(construct.Const(5, construct.Byte), 5),
    'auth_methods' /
    construct.PrefixedArray(construct.Byte, PackEnum(AuthMethod)))

ServerChoice = construct.Struct(
    'version' / construct.Default(construct.Const(5, construct.Byte), 5),
    'auth_choice' / PackEnum(AuthMethod))

ClientAuthRequest = construct.Struct(
    'version' / construct.Default(construct.Byte, 1),
    'username' / construct.PascalString(construct.Byte, 'utf-8'),
    'password' / construct.PascalString(construct.Byte, 'utf-8'),
)

ServerAuthResponse = construct.Struct(
    'version' / construct.Default(construct.Byte, 1),
    'status' / construct.Flag,