ConfigurationSetWithOptionalDhcpEnabledWithStaticDns = Struct( Embedded(ConfigurationSetWithoutOptionalAutoDhcpEnabled), "dns_ip_address" / IpAddressAdapter(Bytes(4)), ) ConfigurationSetWithOptionalDhcpDisabled = Struct( Embedded(ConfigurationSetWithOptionalDhcpEnabledWithStaticDns), "ip_address" / IpAddressAdapter(Bytes(4)), "gateway_ip_address" / IpAddressAdapter(Bytes(4)), "netmask" / Int8ul, ) ConfigurationSet = Select( ConfigurationSetWithOptionalDhcpDisabled, ConfigurationSetWithOptionalDhcpEnabledWithStaticDns, ConfigurationSetWithoutOptionalAutoDhcpEnabled, ) ConfigurationStatus = Struct( "chip_revision_id" / Int8ul, Embedded(ConfigurationSetWithOptionalDhcpDisabled), "flags" / EnumAdapter(Int8ul, DhcpFlag), "status_code" / EnumAdapter(Int8ul, StatusCode), ) # GATEWAY PACKETS MSG PacketsStatus = Struct( "total_eth_rx_errors" / Int16ul, "total_eth_tx_errors" / Int16ul, "bandwidth" / Int16ul,
Select, Rebuild, Terminated, this ) from .compat import Const # RFC 4251 section 5 SshBytes = Prefixed(Int32ub, GreedyBytes) SshString = PascalString(Int32ub, 'utf8') SshMPInt = Select( Const(0, Int32ub), # zero stored as zero bytes of data FocusedSeq( 'num', 'len' / Rebuild(Int32ub, lambda ctx: int(ctx.num.bit_length() // 8 + 1)), 'num' / BytesInteger(this.len, signed=True), ), ) # RFC 4253 section 6.6 SshRSAKeyBlob = Struct( 'algo' / Const('ssh-rsa', SshString), 'e' / SshMPInt, 'n' / SshMPInt, Terminated ) # I-D.ietf-curdle-ssh-ed25519, section 4 SshEd25519KeyBlob = Struct(
def __init__(self, **subconskw): subcons = list( NameAdapter(k / v.compile()) for k, v in subconskw.items()) super().__init__(Select(*subcons)) self._subcon = Select(**subconskw)
"id" / Const(value=1, subcon=Int32ub), "channel" / CString(encoding='ascii'), "productversion" / CString(encoding='ascii'), "padding" / Bytes( this.size - len_(this.channel) - len_(this.productversion) - # 8 bytes for size/id fields, and an # extra 2 bytes for the null terminator after # channel and productversion 8 - 2, ), ) extras_header = "extras_header" / Struct( "offset" / Tell, "count" / Int32ub, "sections" / Array(this.count, Select(productinfo_entry, extra_entry)), "offset_end" / Tell, ) index_entry = "index_entry" / Struct( "offset" / Int32ub, "size" / Int32ub, "flags" / Int32ub, "name" / CString(encoding='ascii'), ) index_header = "index_header" / Struct( "entries" / Prefixed(Int32ub, GreedyRange(index_entry)), )
CTL_TEMPERATURE_DEFAULT_SET_UNACKNOWLEDGED = 0x826A CTL_TEMPERATURE_RANGE_SET = 0x826B CTL_TEMPERATURE_RANGE_SET_UNACKNOWLEDGED = 0x826C LightCTLGet = Struct() LightCTLDefault = Struct("ctl_lightness" / Int16ul, "ctl_temperature" / Int16ul, "ctl_delta_uv" / Int16ul) LightCTLSetMinimal = Struct(Embedded(LightCTLDefault), "tid" / Int8ul) LightCTLSetOptional = Struct(Embedded(LightCTLSetMinimal), Embedded(OptionalSetParameters)) LightCTLSet = Select(LightCTLSetOptional, LightCTLSetMinimal) LightCTLStatusMinimal = Struct( "present_ctl_lightness" / Int16ul, "present_ctl_temperature" / Int16ul, ) LightCTLStatusOptional = Struct( Embedded(LightCTLStatusMinimal), "target_ctl_lightness" / Int16ul, "target_ctl_temperature" / Int16ul, "remaining_time" / TransitionTimeAdapter(TransitionTime, allow_unknown=True)) LightCTLStatus = Select(LightCTLStatusOptional, LightCTLStatusMinimal) LightCTLTemperatureStatusMinimal = Struct( "present_ctl_temperature" / Int16ul,
SENSOR_SETTINGS_GET = 0x8235 SENSOR_SETTINGS_STATUS = 0x58 SENSOR_SETTING_GET = 0x8236 SENSOR_SETTING_SET = 0x59 SENSOR_SETTING_SET_UNACKNOWLEDGED = 0x5A SENSOR_SETTING_STATUS = 0x5B SensorGetMinimal = Struct() SensorGetOptional = Struct( "property_id" / Int16ul ) SensorGet = Select( SensorGetOptional, SensorGetMinimal ) SensorSettingsGet = Struct( "sensor_property_id" / Int16ul ) SensorSettingGet = Struct( Embedded(SensorSettingsGet), "sensor_setting_property_id" / Int16ul ) SensorSettingSet = Struct( Embedded(SensorSettingGet), "sensor_setting_raw" / PropertyValue, )
DecodingResult = Struct("type" / Const(2, Int8ul), "status" / Int32ul) RectResult = Struct("type" / Const(3, Int8ul), "status" / Int32ul) """ This struct encompass all calista stream """ Bitmap = Struct("type" / Const(4, Int8ul), "index" / Int32ul, "length" / Int32ul, "data" / Bytes(lambda this: this.length), "info" / RdpBitmapinfo, "have_point" / Int8ul, "point" / If(lambda this: this.have_point != 0, Int64ul)) CacdecDump = Struct( "magic" / Const(b"CacDec01"), "objects" / RepeatUntil( lambda x, lst, ctx: len(x._io.getbuffer()) == x._io.tell(), Select(SurfaceContext, SurfaceResult, DecodingResult, RectResult, Bitmap))) def write_bmp(file_path, width, height, data): """ Write a BMP file a output :param file_path: path of file :param width: with of image :param height: height of image :param data: raw image data """ with open(file_path, "wb") as f: f.write(b"BM" + pack("<L", len(data) + 0x36) + b"\x00\x00\x00\x00\x32\x00\x00\x00\x28\x00\x00\x00" + pack("<L", width) + pack("<L", height) +
LightLightnessDefault = Struct( "lightness" / Int16ul ) LightLightnessStatusMinimal = Struct( "present_lightness" / Int16ul ) LightLightnessStatusOptional = Struct( Embedded(LightLightnessStatusMinimal), "target_lightness" / Int16ul, "remaining_time" / TransitionTimeAdapter(TransitionTime, allow_unknown=True) ) LightLightnessStatus = Select( LightLightnessStatusOptional, LightLightnessStatusMinimal ) LightLightnessRange = Struct( "range_min" / Int16ul, "range_max" / Int16ul, ) LightLightnessRangeStatus = Struct( "status" / StatusCodeAdapter, Embedded(LightLightnessRange) ) LightLightnessSetMinimal = Struct( "lightness" / Int16ul, "tid" / Int8ul
from construct import Select from .onoff import GenericOnOffMessage from .level import GenericLevelMessage from .light.ctl import LightCTLMessage, LightCTLSetupMessage from .light.lightness import LightLightnessMessage, LightLightnessSetupMessage GenericMessage = Select(GenericOnOffMessage, GenericLevelMessage, LightCTLMessage, LightCTLSetupMessage, LightLightnessMessage, LightLightnessSetupMessage)
NodeIdentityAdapter = EnumAdapter(Int8ul, NodeIdentity) FriendAdapter = EnumAdapter(Int8ul, Friend) TTL = RangeValidator(Int8ul, max_value=0x7F) # fmt: off SIGModelId = Struct("model_id" / Int16ul, ) VendorModelId = Struct( "vendor_id" / Int16ul, "model_id" / Int16ul, ) ModelId = Select(VendorModelId, SIGModelId) # fmt: on class AddressType(enum.Enum): UNASSIGNED = 0 UNICAST = 1 GROUP = 2 VIRTUAL = 3 RFU = 4 ALL_PROXIES = 5 ALL_FRIENDS = 6 ALL_RELAYS = 7 ALL_NODES = 8
SENSOR_CADENCE_GET = 0x8234 SENSOR_CADENCE_SET = 0x55 SENSOR_CADENCE_SET_UNACKNOWLEDGED = 0x56 SENSOR_CADENCE_STATUS = 0x57 SENSOR_SETTINGS_GET = 0x8235 SENSOR_SETTINGS_STATUS = 0x58 SENSOR_SETTING_GET = 0x8236 SENSOR_SETTING_SET = 0x59 SENSOR_SETTING_SET_UNACKNOWLEDGED = 0x5A SENSOR_SETTING_STATUS = 0x5B def __repr__(self): return str(self.value) SensorPropertyId = Select(EnumAdapter(Int16ul, PropertyID), Int16ul) # fmt: off SensorGetMinimal = Struct() SensorGetOptional = Struct("property_id" / SensorPropertyId, ) SensorGet = Select(SensorGetOptional, SensorGetMinimal) SensorSettingsGet = Struct("sensor_property_id" / SensorPropertyId, ) SensorSettingGet = Struct( Embedded(SensorSettingsGet), "sensor_setting_property_id" / SensorPropertyId, )
TransactionStartPDU = Struct( *EmbeddedBitStruct( "_", "last_segment_number" / BitsInteger(6), "type" / Const(GenericProvisioningPDUType.START, BitsInteger(2)), ), "total_length" / Int16ub, "frame_check" / Int8ub, "data" / GreedyBytes) TransactionContinuationPDU = Struct( *EmbeddedBitStruct( "_", "segment_index" / BitsInteger(6), "type" / Const(GenericProvisioningPDUType.CONTINUATION, BitsInteger(2)), ), "data" / GreedyBytes) TransactionPDUSegment = Select(TransactionStartPDU, TransactionContinuationPDU, ProvisioningBearerControl) ProvisioningMessage = Struct("link_id" / Bytes(4), "transaction_id" / Int8ub, "data" / GreedyBytes) # fmt: on class ProvisioningEncryption: @staticmethod def data_encrypt(secret, inputs, data): """inputs = confirmation_salt + provisioner_random + device_random""" provisioning_salt = s1(inputs) provisioning_key = k1(secret, provisioning_salt, b"prsk") provisioning_nonce = k1(secret, provisioning_salt, b"prsn")[-13:] return aes_ccm_encrypt(provisioning_key,
NOTE: This is a hack. Do not use unless you absolutely have to. """ bit_struct = BitStruct(*args) if reversed: bit_struct = Reversed(bit_struct) bit_struct.__construct_doc__ = Embedded(Struct(*args)) return (name / Rebuild(bit_struct, dict), ) + \ tuple(i.name / Computed(this[name][i.name]) for i in args if i.name is not None) Opcode = Select( ExprValidator(Int8ub, (obj_ != 0x7F) and (obj_ >> 7 == 0)), ExprValidator(Int16ub, (obj_ >> 14 == 2)), ExprValidator(Int24ub, (obj_ >> 22 == 3)), ) class DefaultCountValidator(Adapter): def __init__(self, subcon, rounding=None, resolution=1.0): super().__init__(subcon) self.rounding = rounding self.resolution = resolution def _decode(self, obj, content, path): if obj == (256**self.subcon.length) - 1: return None else: return round(
def iter_con(self, mst_stream, yield_control_record=False): # noqa: C """Generator of records as parsed construct.Container objects. Parameters ---------- mst_stream : file-like A seekable open stream of bytes in its initial position, where the MST binary contents should be read from. yield_control_record : bool Control if the first generated construct.Container object should be the control record, or if it should skip it to generate just the records. """ ending_struct = self.create_ending_struct() control_record_struct = self.create_control_record_struct() control_record = control_record_struct.parse_stream(mst_stream) record_struct = self.create_record_struct(control_record) leader_len = 18 + 4 * (self.format == "ffi") + 2 * (not self.packed) rec_or_end_struct = Select(record_struct, ending_struct) last_tell = 0 def record_ibp_gen(): nonlocal last_tell ibps = [] while True: try: record = rec_or_end_struct.parse_stream(mst_stream) except SelectError: if self.ibp == "check": raise elif self.ibp == "store": ibps.append(mst_stream.read(control_record.modulus)) continue if ibps: yield {"ibp": b2a_hex(b"".join(ibps))} ibps.clear() if record is None: # No more records break last_tell = mst_stream.tell() yield record if yield_control_record: prev = control_record else: prev = None for record in record_ibp_gen(): if record and "ibp" in record: prev.update(record) yield prev prev = None else: if prev: yield prev prev = record if prev: yield prev next_addr = last_tell + never_split_pad_size(last_tell, leader_len) next_block = 1 + (next_addr >> 9) next_offset = 1 + (next_addr & 0x1ff) if control_record.next_block != next_block: raise CheckError("Invalid next_block") if control_record.next_offset != next_offset: raise CheckError("Invalid next_offset")
SENSOR_CADENCE_STATUS = 0x57 SENSOR_SETTINGS_GET = 0x8235 SENSOR_SETTINGS_STATUS = 0x58 SENSOR_SETTING_GET = 0x8236 SENSOR_SETTING_SET = 0x59 SENSOR_SETTING_SET_UNACKNOWLEDGED = 0x5A SENSOR_SETTING_STATUS = 0x5B def __repr__(self): return str(self.value) # fmt: off SensorPropertyId = FieldAdapter( Select( EnumAdapter(Int16ul, PropertyID), Int16ul), Int16ul ) SensorGetMinimal = Struct() SensorGetOptional = Struct( "property_id" / SensorPropertyId, ) SensorGet = NamedSelect( optional=SensorGetOptional, minimal=SensorGetMinimal )
from construct import ( Select, Struct, GreedyBytes, ) from .util import Opcode from .health import HealthMessage from .config import ConfigMessage from .generic import GenericMessage from .scene import SceneMessage from .sensor import SensorMessage, SensorSetupMessage Message = Struct( "opcode" / Opcode, "params" / GreedyBytes, ) AccessMessage = Select( "HealthMessage" / HealthMessage, "ConfigMessage" / ConfigMessage, "GenericMessage" / GenericMessage, "SceneMessage" / SceneMessage, "SensorMessage" / SensorMessage, "SensorSetupMessage" / SensorSetupMessage, "Message" / Message, )
'channelCode' / Int32sl, 'expectsReply' / Int32ul, ) dtx_message_payload_header_struct = Struct( 'flags' / Int32ul, 'auxiliaryLength' / Int32ul, 'totalLength' / Int64ul, ) message_aux_t_struct = Struct( 'magic' / Default(Int64ul, 0x1f0), 'aux' / Prefixed( Int64ul, GreedyRange( Struct( '_empty_dictionary' / Select(Const(0xa, Int32ul), Int32ul), 'type' / Int32ul, 'value' / Switch(this.type, { 2: BplitAdapter(Prefixed(Int32ul, GreedyBytes)), 3: Int32ul, 4: Int64ul }, default=GreedyBytes), )))) class MessageAux: def __init__(self): self.values = []
SENSOR_SETTING_SET_UNACKNOWLEDGED = 0x5A SENSOR_SETTING_STATUS = 0x5B def __repr__(self): return str(self.value) # fmt: off SensorGetMinimal = Struct() SensorGetOptional = Struct( "property_id" / Int16ul ) SensorGet = Select( SensorGetOptional, SensorGetMinimal ) SensorSettingsGet = Struct( "sensor_property_id" / Int16ul ) SensorSettingGet = Struct( Embedded(SensorSettingsGet), "sensor_setting_property_id" / Int16ul ) SensorSettingSet = Struct( Embedded(SensorSettingGet), "sensor_setting_raw" / PropertyValue, )
LEVEL_SET_UNACKNOWLEDGED = 0x8207 LEVEL_STATUS = 0x8208 DELTA_SET = 0x8209 DELTA_SET_UNACKNOWLEDGED = 0x820A MOVE_SET = 0x820B MOVE_SET_UNACKNOWLEDGED = 0x820C GenericLevelGet = Struct() GenericLevelSetMinimal = Struct("level" / Int16ul, "tid" / Int8ul) GenericLevelSetOptional = Struct(Embedded(GenericLevelSetMinimal), Embedded(OptionalSetParameters)) GenericLevelSet = Select(GenericLevelSetOptional, GenericLevelSetMinimal) GenericDeltaSetMinimal = Struct("delta_level" / Int32ul, "tid" / Int8ul) GenericDeltaSetOptional = Struct(Embedded(GenericDeltaSetMinimal), Embedded(OptionalSetParameters)) GenericDeltaSet = Select(GenericDeltaSetOptional, GenericDeltaSetMinimal) GenericMoveSetMinimal = Struct("delta_level" / Int16ul, "tid" / Int8ul) GenericMoveSetOptional = Struct(Embedded(GenericMoveSetMinimal), Embedded(OptionalSetParameters)) GenericMoveSet = Select(GenericMoveSetOptional, GenericMoveSetMinimal)
"payload" / Bytes(lambda this: this.header.wnode.saved_offset - WmiBufferHeader.sizeof()), "padding" / Bytes(lambda this: this.header.wnode.buffer_size - this.header. wnode.saved_offset)) # An ETL file is structured by ETL chunks until the end EtlLogFile = GreedyRange(EtlChunk) # This is a common way to select any type of chunks # We add name selecting as computed to handle typing during parsing Chunk = Aligned( 8, Select( Struct("type" / Computed("PerfInfoTraceRecord"), "value" / PerfInfoTraceRecord), Struct("type" / Computed("EventRecord"), "value" / EventRecord), Struct("type" / Computed("TraceRecord"), "value" / TraceRecord), Struct("type" / Computed("SystemTraceRecord"), "value" / SystemTraceRecord), Struct("type" / Computed("WinTraceRecord"), "value" / WinTraceRecord))) ChunkParser = RepeatUntil( lambda x, lst, ctx: len(x._io.getbuffer()) == x._io.tell(), Chunk) class IEtlFileObserver(metaclass=ABCMeta): """ This is etl file observer Parse sequentially an etl file and commit event when found a particular event """ @abstractmethod def on_event_record(self, event: Event):
ONOFF_STATUS = 0x8204 # fmt: on GenericOnOffGet = Struct() GenericOnOffSetMinimal = Struct("onoff" / Int8ul, "tid" / Int8ul) GenericOnOffSetOptional = Struct( "onoff" / Int8ul, "tid" / Int8ul, "transition_time" / TransitionTimeAdapter(TransitionTime, allow_unknown=False), "delay" / Delay(Int8ul), ) GenericOnOffSet = Select(GenericOnOffSetOptional, GenericOnOffSetMinimal) GenericOnOffStatusMinimal = Struct("present_onoff" / Int8ul) GenericOnOffStatusOptional = Struct( "present_onoff" / Int8ul, "target_onoff" / Int8ul, "remaining_time" / TransitionTimeAdapter(TransitionTime, allow_unknown=True), ) GenericOnOffStatus = Select(GenericOnOffStatusOptional, GenericOnOffStatusMinimal) GenericOnOffMessage = Struct( "opcode" / Opcode(GenericOnOffOpcode), "params"
SceneGet = Struct() SceneRecallMinimal = Struct( "scene_number" / ExprValidator(Int16ul, obj_ > 0), "tid" / Int8ul, ) SceneRecallWithTransition = Struct( "scene_number" / ExprValidator(Int16ul, obj_ > 0), "tid" / Int8ul, "transition_time" / TransitionTimeAdapter(TransitionTime, allow_unknown=False), "delay" / Delay(Int8ul), ) SceneRecall = Select( SceneRecallWithTransition, SceneRecallMinimal ) SceneStatusMinimal = Struct( "status_code" / EnumAdapter(Int8ul, SceneStatusCode), "current_scene" / Int16ul ) SceneStatusWithTargetScene = Struct( "status_code" / EnumAdapter(Int8ul, SceneStatusCode), "current_scene" / Int16ul, "target_scene" / Int16ul, "remaining_time" / TransitionTimeAdapter(TransitionTime, allow_unknown=False), ) SceneStatus = Select(
ConfigurationSetWithOptionalDhcpEnabledWithStaticDns = Struct( Embedded(ConfigurationSetWithoutOptionalAutoDhcpEnabled), "dns_ip_address" / IpAddressAdapter(Bytes(4)), ) ConfigurationSetWithOptionalDhcpDisabled = Struct( Embedded(ConfigurationSetWithOptionalDhcpEnabledWithStaticDns), "ip_address" / IpAddressAdapter(Bytes(4)), "gateway_ip_address" / IpAddressAdapter(Bytes(4)), "netmask" / Int8ul, ) ConfigurationSet = Select( static=ConfigurationSetWithOptionalDhcpDisabled, dns=ConfigurationSetWithOptionalDhcpEnabledWithStaticDns, minimal=ConfigurationSetWithoutOptionalAutoDhcpEnabled, ) ConfigurationStatus = Struct( "chip_revision_id" / Int8ul, Embedded(ConfigurationSetWithOptionalDhcpDisabled), "flags" / EnumAdapter(Int8ul, DhcpFlag), "status_code" / EnumAdapter(Int8ul, StatusCode), ) ConnectionState = BitStruct( "conn_state" / EnumAdapter(BitsInteger(3), ConnState), "link_status" / EnumAdapter(BitsInteger(1), LinkStatus), "last_error" / EnumAdapter(BitsInteger(4), LastError))
ret += [dict(first=obj.pop(0), second=obj.pop(0))] if obj: ret += [dict(last=obj.pop())] return ret # fmt: off KeyIndices = KeyIndicesAdapter( GreedyRange( Select( Reversed( BitStruct( "first" / BitsInteger(12), "second" / BitsInteger(12), )), Reversed(BitStruct( Padding(4), "last" / BitsInteger(12), ))))) KeyIndices.__construct_doc__ = GreedyRange(BitsInteger(12)) # fmt: on class PublishPeriodStepResolution(enum.IntEnum): RESOLUTION_100_MS = 0x0 RESOLUTION_1_S = 0x1 RESOLUTION_10_S = 0x2 RESOLUTION_10_MIN = 0x3 @property
"version" / GreedyString("utf8") ) IvIndex = Struct( "ivindex" / Int32ul ) GarbageCollectorCounter = Struct( "counter" / Int16ul ) ArapSize = Select( Struct( "capacity" / Int16ul, "size" / Int16ul ), Struct( "capacity" / Int8ul, "size" / Int8ul ) ) ArapContentGet = Struct( "page" / Int8ul ) ArapContent = Struct( "current_page" / Int8ul, "last_page" / Int8ul, "nodes" / DictAdapter( GreedyRange( ByteSwapped(
from functools import partial from binascii import hexlify from construct import Struct, Byte, Bytes, Const, String, CString, \ Switch, Pointer, Anchor, Sequence, GreedyRange, Computed, this, \ RawCopy, Checksum, Probe, Container, Array, Range, Select from PyCRC.CRCCCITT import CRCCCITT TIME_FORMAT = '%Y-%m-%d;%H:%M' crc16 = lambda val: '{:04x}'.format(CRCCCITT().calculate(val)).upper() TabTerminated = CString(terminators=b'\x09', encoding='cp1250') PosnetParameter = Struct( 'name' / Select(Const('@'), Const('?'), String(length=2)), 'value' / TabTerminated) PosnetFrame = Struct( Const(b'\x02'), 'summed' / RawCopy( Struct('instruction' / TabTerminated, 'parameters' / GreedyRange(PosnetParameter))), Const('#'), 'crc' / Checksum(Bytes(4), crc16, 'summed'), Const('\x03'), 'instruction' / Computed(this.summed.value.instruction), 'parameters' / Computed(this.summed.value.parameters)) def build_frame(instruction, *params): ''' Helper for building Posnet protocol frames out of instructions and params passed as (name, value) tuples. Can't use **kwargs: Posnet protocol