示例#1
0
  def _ReadFileHeader(self, file_object):
    """Reads the file header.

    Args:
      file_object: the file-like object to read from.

    Raises:
      FileFormatError: if file format related errors are detected.
    """
    file_object.seek(0, os.SEEK_SET)
    file_header = self._FILE_HEADER_STRUCT.parse_stream(file_object)
    self._compressed_data_offset = file_object.get_offset()

    if file_header.signature != self._FILE_SIGNATURE:
      raise errors.FileFormatError(
          u'Unsuppored file signature: 0x{0:04x}.'.format(
              file_header.signature))

    if file_header.compression_method != self._COMPRESSION_METHOD_DEFLATE:
      raise errors.FileFormatError(
          u'Unsuppored compression method: {0:d}.'.format(
              file_header.compression_method))

    self.modification_time = file_header.modification_time
    self.operating_system = file_header.operating_system

    if file_header.flags & self._FLAG_FEXTRA:
      extra_field_data_size = construct.ULInt16(
          u'extra_field_data_size').parse_stream(file_object)
      file_object.seek(extra_field_data_size, os.SEEK_CUR)
      self._compressed_data_offset += 2 + extra_field_data_size

    if file_header.flags & self._FLAG_FNAME:
      # Since encoding is set construct will convert the C string to Unicode.
      # Note that construct 2 does not support the encoding to be a Unicode
      # string.
      self.original_filename = construct.CString(
          u'original_filename', encoding='iso-8859-1').parse_stream(
              file_object)
      self._compressed_data_offset = file_object.get_offset()

    if file_header.flags & self._FLAG_FCOMMENT:
      # Since encoding is set construct will convert the C string to Unicode.
      # Note that construct 2 does not support the encoding to be a Unicode
      # string.
      self.comment = construct.CString(
          u'comment', encoding='iso-8859-1').parse_stream(file_object)
      self._compressed_data_offset = file_object.get_offset()

    if file_header.flags & self._FLAG_FHCRC:
      self._compressed_data_offset += 2

    self._compressed_data_size = (
        file_object.get_size() - (self._compressed_data_offset + 8))
示例#2
0
    def _ReadAndParseHeader(self, file_object):
        """Reads the member header and sets relevant member values.

    Args:
      file_object (FileIO): file-like object to read from.

    Raises:
      FileFormatError: if file format related errors are detected.
    """
        member_header = self._MEMBER_HEADER_STRUCT.parse_stream(file_object)

        if member_header.signature != self._GZIP_SIGNATURE:
            raise errors.FileFormatError(
                'Unsupported file signature: 0x{0:04x}.'.format(
                    member_header.signature))

        if member_header.compression_method != self._COMPRESSION_METHOD_DEFLATE:
            raise errors.FileFormatError(
                'Unsupported compression method: {0:d}.'.format(
                    member_header.compression_method))

        self.modification_time = member_header.modification_time
        self.operating_system = member_header.operating_system

        if member_header.flags & self._FLAG_FEXTRA:
            extra_field_data_size = construct.ULInt16(
                'extra_field_data_size').parse_stream(file_object)
            file_object.seek(extra_field_data_size, os.SEEK_CUR)

        if member_header.flags & self._FLAG_FNAME:
            # Since encoding is set construct will convert the C string to Unicode.
            # Note that construct 2 does not support the encoding to be a Unicode
            # string.
            self.original_filename = construct.CString(
                'original_filename',
                encoding=b'iso-8859-1').parse_stream(file_object)

        if member_header.flags & self._FLAG_FCOMMENT:
            # Since encoding is set construct will convert the C string to Unicode.
            # Note that construct 2 does not support the encoding to be a Unicode
            # string.
            self.comment = construct.CString(
                'comment', encoding=b'iso-8859-1').parse_stream(file_object)

        if member_header.flags & self._FLAG_FHCRC:
            file_object.read(2)
示例#3
0
def decode_itempos(itempos):
    """
    Decodes a single itempos and returns extracted information
    """
    itempos_io = StringIO.StringIO(itempos)
    itempos_struct = construct.Struct("itempos",
                                      construct.ULInt16("itempos_size"),
                                      construct.Padding(2),
                                      construct.ULInt32("filesize"),
                                      construct.Bytes("dos_date", 2),
                                      construct.Bytes("dos_time", 2),
                                      construct.ULInt16("file_attr"),
                                      construct.CString("filename")
                                      )
    parse_res = itempos_struct.parse_stream(itempos_io)
    if itempos_io.pos % 2 == 1:
        itempos_io.read(1)
    ext_struct = construct.Struct("ext",
                                  construct.ULInt16("ext_size"),
                                  construct.ULInt16("ext_version")
                                  )
    parse_ext = ext_struct.parse_stream(itempos_io)
    if parse_ext["ext_version"] >= 0x3:
        itempos2_struct = construct.Struct("itempos2",
                                           construct.Padding(2),  # 0004
                                           construct.Padding(2),  # BEEF
                                           construct.Bytes("creation_dos_date", 2),
                                           construct.Bytes("creation_dos_time", 2),
                                           construct.Bytes("access_dos_date", 2),
                                           construct.Bytes("access_dos_time", 2),
                                           construct.Padding(4)
                                           )
        parse_res2 = itempos2_struct.parse_stream(itempos_io)
    unicode_filename = ""
    if parse_ext["ext_version"] >= 0x7:
        itempos3_struct = construct.Struct("itempos3",
                                           construct.ULInt64("file_ref"),
                                           construct.Padding(8),
                                           construct.Padding(2),
                                           construct.Padding(4)
                                           )
        parse_res3 = itempos3_struct.parse_stream(itempos_io)
        unicode_filename = itempos_io.read().decode("utf16")
        if not unicode_filename.endswith("\0"):
            unicode_filename = unicode_filename[:-2]  # ditch last unused 2 bytes and \0 char
    elif parse_ext["ext_version"] >= 0x3:
        unicode_filename = itempos_io.read().decode("utf16")
        if not unicode_filename.endswith("\0"):
            unicode_filename = unicode_filename[:-2]  # ditch last unused 2 bytes and \0 char

    timestamp_modified = dosdate(parse_res["dos_date"], parse_res["dos_time"]).strftime("%d/%m/%Y %H:%M:%S")
    timestamp_created = dosdate(parse_res2["creation_dos_date"], parse_res2["creation_dos_time"]).strftime(
        "%d/%m/%Y %H:%M:%S")
    timestamp_access = dosdate(parse_res2["access_dos_date"], parse_res2["access_dos_time"]).strftime(
        "%d/%m/%Y %H:%M:%S")

    return [unicode(parse_res["itempos_size"]), unicode(parse_res["filesize"]), timestamp_modified,
            parse_res["filename"], timestamp_created, timestamp_access, unicode_filename]
示例#4
0
def CString(terminator=b"\x00", encoding=None):
    r"""
    This is an alternative of implementation of construct.CString() that fixes the issues with
    working with utf-16 or utf-32 encoded strings (github.com/construct/construct/issues/388)

    >>> CString().parse(b'hello\x00')
    'hello'
    >>> CString(encoding='utf-16').parse(b'\xff\xfeh\x00e\x00l\x00l\x00o\x00\x00\x00')  # FFFE is BOM for utf-16-le
    u'hello'
    >>> CString(encoding='utf-16').parse(b'h\x00e\x00l\x00l\x00o\x00\x00\x00')
    u'hello'
    >>> CString(encoding='utf-16').build(u'hello')
    '\xff\xfeh\x00e\x00l\x00l\x00o\x00\x00\x00'
    >>> CString(encoding='utf-32').build(u'hello')
    '\xff\xfe\x00\x00h\x00\x00\x00e\x00\x00\x00l\x00\x00\x00l\x00\x00\x00o\x00\x00\x00\x00\x00\x00\x00'

    Make sure to specify 'le' or 'be' in the encoding if you don't want BOM markers when building.
    >>> CString(encoding='utf-32-le').build(u'hello')
    'h\x00\x00\x00e\x00\x00\x00l\x00\x00\x00l\x00\x00\x00o\x00\x00\x00\x00\x00\x00\x00'
    >>> CString(encoding='utf-32-be').build(u'hello')
    '\x00\x00\x00h\x00\x00\x00e\x00\x00\x00l\x00\x00\x00l\x00\x00\x00o\x00\x00\x00\x00'
    """
    # Revert to original if not utf-16 or utf-32.
    if not encoding or not ('16' in encoding or '32' in encoding):
        return construct.CString(terminators=terminator, encoding=encoding)

    size = 4 if '32' in encoding else 2
    if len(terminator) == 1:
        terminator = terminator * size
    assert len(terminator) == size

    return construct.StringEncoded(
        construct.ExprAdapter(
            RepeatUntil(lambda obj, lst, ctx: obj == terminator, Bytes(size)),
            encoder=lambda obj, ctx: list(
                map(b''.join, chunk(py3compat.iteratebytes(obj), size))
            ) + [terminator],
            decoder=lambda obj, ctx: b''.join(obj[:-1])), encoding)
示例#5
0
def CString(encoding='utf-8'):
    r"""
    Adds default encoding option to CString().

    >>> CString().parse(b'hello\x00')
    u'hello'
    >>> CString().parse(b'hello\x00\xff\xff')
    u'hello'
    >>> CString(encoding='utf-16').parse(b'\xff\xfeh\x00e\x00l\x00l\x00o\x00\x00\x00')  # FFFE is BOM for utf-16-le
    u'hello'
    >>> CString(encoding='utf-16').parse(b'h\x00e\x00l\x00l\x00o\x00\x00\x00')
    u'hello'
    >>> CString(encoding='utf-16').build(u'hello')
    '\xff\xfeh\x00e\x00l\x00l\x00o\x00\x00\x00'
    >>> CString(encoding='utf-32').build(u'hello')
    '\xff\xfe\x00\x00h\x00\x00\x00e\x00\x00\x00l\x00\x00\x00l\x00\x00\x00o\x00\x00\x00\x00\x00\x00\x00'

    Make sure to specify 'le' or 'be' in the encoding if you don't want BOM markers when building.
    >>> CString(encoding='utf-32-le').build(u'hello')
    'h\x00\x00\x00e\x00\x00\x00l\x00\x00\x00l\x00\x00\x00o\x00\x00\x00\x00\x00\x00\x00'
    >>> CString(encoding='utf-32-be').build(u'hello')
    '\x00\x00\x00h\x00\x00\x00e\x00\x00\x00l\x00\x00\x00l\x00\x00\x00o\x00\x00\x00\x00'
    """
    return construct.CString(encoding)
示例#6
0
文件: recycler.py 项目: iwm911/plaso
class WinRecycleInfo2Parser(parser.BaseParser):
    """Parses the Windows INFO2 recycle bin file."""

    NAME = 'recycle_bin_info2'

    # Define a list of all structs used.
    INT32_LE = construct.ULInt32('my_int')

    FILE_HEADER_STRUCT = construct.Struct('file_header', construct.Padding(8),
                                          construct.ULInt32('record_size'))

    # Struct based on (-both unicode and legacy string):
    # https://code.google.com/p/rifiuti2/source/browse/trunk/src/rifiuti.h
    RECORD_STRUCT = construct.Struct('record', construct.ULInt32('index'),
                                     construct.ULInt32('drive'),
                                     construct.ULInt64('filetime'),
                                     construct.ULInt32('filesize'))

    STRING_STRUCT = construct.CString('legacy_filename')

    # Define a list of needed variables.
    UNICODE_FILENAME_OFFSET = 0x11C
    RECORD_INDEX_OFFSET = 0x108

    def Parse(self, file_entry):
        """Extract entries from Windows Recycler INFO2 file.

    Args:
      file_entry: A file entry object.

    Yields:
      An event object.
    """
        file_object = file_entry.GetFileObject()
        try:
            magic_header = self.INT32_LE.parse_stream(file_object)
        except (construct.FieldError, IOError) as exception:
            raise errors.UnableToParseFile(
                u'Unable to parse INFO2 file with error: {0:s}'.format(
                    exception))

        if magic_header is not 5:
            raise errors.UnableToParseFile(
                u'Not an INFO2 file, wrong magic header.')

        # Since this header value is really generic it is hard not to use filename
        # as an indicator too.
        # TODO: Rethink this and potentially make a better test.
        base_filename = utils.GetBaseName(file_entry.name)
        if not base_filename.startswith('INFO2'):
            raise errors.UnableToParseFile(
                u'Not an INFO2 file, filename isn\'t INFO2.')

        file_header = self.FILE_HEADER_STRUCT.parse_stream(file_object)

        # Limit recrodsize to 65536 to be on the safe side.
        record_size = file_header['record_size']
        if record_size > 65536:
            logging.error(
                (u'Record size is too large for INFO2 [{}], reducing size to '
                 '65.535').format(record_size))
            record_size = 65535

        # If recordsize is 0x320 then we have UTF/unicode names as well.
        read_unicode_names = False
        if record_size is 0x320:
            read_unicode_names = True

        data = file_object.read(record_size)
        while data:
            if len(data) != record_size:
                break
            filename_ascii = self.STRING_STRUCT.parse(data[4:])
            record_information = self.RECORD_STRUCT.parse(
                data[self.RECORD_INDEX_OFFSET:])
            if read_unicode_names:
                filename_utf = binary.ReadUtf16(
                    data[self.UNICODE_FILENAME_OFFSET:])
            else:
                filename_utf = u''

            yield WinRecycleEvent(filename_ascii, filename_utf,
                                  record_information, record_size)

            data = file_object.read(record_size)

        file_object.close()
示例#7
0
    def _ParseRecord(self, page_data, record_offset):
        """Reads a record from the page data.

    Args:
      page_data (bytes): page data.
      record_offset (int): record offset.
    """
        try:
            record_header_struct = self._RECORD_HEADER.parse(
                page_data[record_offset:])
        except construct.FieldError as exception:
            raise IOError(
                u'Unable to parse record header with error: {0:s}'.format(
                    exception))

        record_data_size = record_offset + record_header_struct.size

        if self._debug:
            print(u'Record data:')
            print(hexdump.Hexdump(page_data[record_offset:record_data_size]))

        if self._debug:
            print(u'Size\t\t\t\t\t\t\t\t: {0:d}'.format(
                record_header_struct.size))
            print(u'Unknown1\t\t\t\t\t\t\t: 0x{0:08x}'.format(
                record_header_struct.unknown1))
            print(u'Flags\t\t\t\t\t\t\t\t: 0x{0:08x}'.format(
                record_header_struct.flags))
            print(u'Unknown2\t\t\t\t\t\t\t: 0x{0:08x}'.format(
                record_header_struct.unknown2))
            print(u'URL offset\t\t\t\t\t\t\t: {0:d}'.format(
                record_header_struct.url_offset))
            print(u'name offset\t\t\t\t\t\t\t: {0:d}'.format(
                record_header_struct.name_offset))
            print(u'path offset\t\t\t\t\t\t\t: {0:d}'.format(
                record_header_struct.path_offset))
            print(u'value offset\t\t\t\t\t\t\t: {0:d}'.format(
                record_header_struct.value_offset))
            print(u'Unknown3\t\t\t\t\t\t\t: 0x{0:08x}'.format(
                record_header_struct.unknown3))

            date_time = (datetime.datetime(2001, 1, 1) + datetime.timedelta(
                seconds=int(record_header_struct.expiration_time)))
            print(u'expiration time\t\t\t\t\t\t\t: {0!s} ({1:f})'.format(
                date_time, record_header_struct.expiration_time))

            date_time = (datetime.datetime(2001, 1, 1) + datetime.timedelta(
                seconds=int(record_header_struct.creation_time)))
            print(u'creation time\t\t\t\t\t\t\t: {0!s} ({1:f})'.format(
                date_time, record_header_struct.creation_time))

            print(u'')

            if record_header_struct.url_offset:
                data_offset = record_offset + record_header_struct.url_offset
                string = construct.CString(u'string').parse(
                    page_data[data_offset:record_data_size])
            else:
                sting = u''

            print(u'URL\t\t\t\t\t\t\t\t: {0:s}'.format(string))

            if record_header_struct.name_offset:
                data_offset = record_offset + record_header_struct.name_offset
                string = construct.CString(u'string').parse(
                    page_data[data_offset:record_data_size])
            else:
                sting = u''

            print(u'Name\t\t\t\t\t\t\t\t: {0:s}'.format(string))

            if record_header_struct.path_offset:
                data_offset = record_offset + record_header_struct.path_offset
                string = construct.CString(u'string').parse(
                    page_data[data_offset:record_data_size])
            else:
                sting = u''

            print(u'Path\t\t\t\t\t\t\t\t: {0:s}'.format(string))

            if record_header_struct.value_offset:
                data_offset = record_offset + record_header_struct.value_offset
                string = construct.CString(u'string').parse(
                    page_data[data_offset:record_data_size])
            else:
                sting = u''

            print(u'Value\t\t\t\t\t\t\t\t: {0:s}'.format(string))

            print(u'')
示例#8
0
# See the License for the specific language governing permissions and
# limitations under the License.
"""Cups Reading Control Files."""

# IMPORTANT: DIRTY PARSE...

# MSc Project in Royal Holloway, University of London.
__author__ = 'Joaquin Moreno Garijo ([email protected])'

import datetime
import construct
import sys

header = construct.Padding(11)
attr_id = construct.UBInt8('type')
attr_text = construct.CString('text')
attr_time = construct.Struct('time', construct.UBInt32('timestamp'),
                             construct.UBInt16('other'))


class ControlFile(object):
    def __init__(self):
        self.crt_time = 0
        self.proc_time = 0
        self.comp_time = 0
        self.data = []


def printValue(name, value):
    # print u'{}: {}'.format(name, value)
    if type(name) != str and type(name) != unicode:
示例#9
0
文件: recycler.py 项目: juju4/plaso
class WinRecyclerInfo2Parser(interface.FileObjectParser):
    """Parses the Windows Recycler INFO2 file."""

    NAME = u'recycle_bin_info2'
    DESCRIPTION = u'Parser for Windows Recycler INFO2 files.'

    _FILE_HEADER_STRUCT = construct.Struct(u'file_header',
                                           construct.ULInt32(u'unknown1'),
                                           construct.ULInt32(u'unknown2'),
                                           construct.ULInt32(u'unknown3'),
                                           construct.ULInt32(u'record_size'),
                                           construct.ULInt32(u'unknown4'))

    _RECYCLER_RECORD_STRUCT = construct.Struct(
        u'recycler_record', construct.ULInt32(u'index'),
        construct.ULInt32(u'drive_number'),
        construct.ULInt64(u'deletion_time'), construct.ULInt32(u'file_size'))

    _ASCII_STRING = construct.CString(u'string')

    _RECORD_INDEX_OFFSET = 0x104
    _UNICODE_FILENAME_OFFSET = 0x118

    def _ParseRecord(self, parser_mediator, file_object, record_offset,
                     record_size):
        """Parses an INFO-2 record.

    Args:
      parser_mediator (ParserMediator): mediates interactions between parsers
          and other components, such as storage and dfvfs.
      file_object (dfvfs.FileIO): file-like object.
      record_offset (int): record offset.
      record_size (int): record size.
    """
        record_data = file_object.read(record_size)

        try:
            ascii_filename = self._ASCII_STRING.parse(record_data)

        except (IOError, construct.FieldError) as exception:
            parser_mediator.ProduceExtractionError((
                u'unable to parse recycler ASCII filename at offset: 0x{0:08x} '
                u'with error: {1:s}').format(record_offset, exception))

        try:
            recycler_record_struct = self._RECYCLER_RECORD_STRUCT.parse(
                record_data[self._RECORD_INDEX_OFFSET:])
        except (IOError, construct.FieldError) as exception:
            parser_mediator.ProduceExtractionError(
                (u'unable to parse recycler index record at offset: 0x{0:08x} '
                 u'with error: {1:s}').format(
                     record_offset + self._RECORD_INDEX_OFFSET, exception))

        unicode_filename = None
        if record_size == 800:
            unicode_filename = binary.ReadUTF16(
                record_data[self._UNICODE_FILENAME_OFFSET:])

        ascii_filename = None
        if ascii_filename and parser_mediator.codepage:
            try:
                ascii_filename = ascii_filename.decode(
                    parser_mediator.codepage)
            except UnicodeDecodeError:
                ascii_filename = ascii_filename.decode(
                    parser_mediator.codepage, errors=u'replace')

        elif ascii_filename:
            ascii_filename = repr(ascii_filename)

        if recycler_record_struct.deletion_time == 0:
            date_time = dfdatetime_semantic_time.SemanticTime(u'Not set')
        else:
            date_time = dfdatetime_filetime.Filetime(
                timestamp=recycler_record_struct.deletion_time)

        event_data = WinRecycleBinEventData()
        event_data.drive_number = recycler_record_struct.drive_number
        event_data.original_filename = unicode_filename or ascii_filename
        event_data.file_size = recycler_record_struct.file_size
        event_data.offset = record_offset
        event_data.record_index = recycler_record_struct.index
        event_data.short_filename = ascii_filename

        event = time_events.DateTimeValuesEvent(
            date_time, eventdata.EventTimestamp.DELETED_TIME)
        parser_mediator.ProduceEventWithEventData(event, event_data)

    def ParseFileObject(self, parser_mediator, file_object, **kwargs):
        """Parses a Windows Recycler INFO2 file-like object.

    Args:
      parser_mediator (ParserMediator): mediates interactions between parsers
          and other components, such as storage and dfvfs.
      file_object (dfvfs.FileIO): file-like object.
    """
        # Since this header value is really generic it is hard not to use filename
        # as an indicator too.

        # TODO: Rethink this and potentially make a better test.
        filename = parser_mediator.GetFilename()
        if not filename.startswith(u'INFO2'):
            return

        try:
            file_header_struct = self._FILE_HEADER_STRUCT.parse_stream(
                file_object)
        except (construct.FieldError, IOError) as exception:
            parser_mediator.ProduceExtractionError(
                u'unable to parse file header with error: {0:s}'.format(
                    exception))
            return

        if file_header_struct.unknown1 != 5:
            parser_mediator.ProduceExtractionError(
                u'unsupport format signature.')
            return

        record_size = file_header_struct.record_size
        if record_size not in (280, 800):
            parser_mediator.ProduceExtractionError(
                u'unsupported record size: {0:d}'.format(record_size))
            return

        record_offset = self._FILE_HEADER_STRUCT.sizeof()
        file_size = file_object.get_size()

        while record_offset < file_size:
            self._ParseRecord(parser_mediator, file_object, record_offset,
                              record_size)

            record_offset += record_size
示例#10
0
_COMMAND_SUCCESS = construct.Const(b"\x03\x06")

_VERSION_REQUEST = construct.Const(b"\x03\x0d\x01")

_VERSION_RESPONSE = construct.Struct(
    _COMMAND_SUCCESS,
    "version" / construct.PascalString(construct.Byte, encoding="ascii"),
    # NULL-termination is not included in string length.
    construct.Const(b"\x00"),
)

_SERIAL_NUMBER_REQUEST = construct.Const(b"\x03\x0b\x01\x02")

_SERIAL_NUMBER_RESPONSE = construct.Struct(
    _COMMAND_SUCCESS,
    "serial_number" / construct.CString(encoding="ascii"),
)

_READ_RTC_REQUEST = construct.Const(b"\x03\x20\x02")

_READ_RTC_RESPONSE = construct.Struct(
    _COMMAND_SUCCESS,
    "timestamp" / lifescan_binary_protocol.VERIO_TIMESTAMP,  # type: ignore
)

_WRITE_RTC_REQUEST = construct.Struct(
    construct.Const(b"\x03\x20\x01"),
    "timestamp" / lifescan_binary_protocol.VERIO_TIMESTAMP,  # type: ignore
)

_GLUCOSE_UNIT_REQUEST = construct.Const(b"\x03\x09\x02\x02")
示例#11
0
# This device uses SCSI blocks as registers.
_REGISTER_SIZE = 512

_PACKET = construct.Padded(
    _REGISTER_SIZE, lifescan_binary_protocol.LifeScanPacket(0x03, False))

_QUERY_REQUEST = construct.Struct(
    construct.Const(b'\xe6\x02'),
    'selector' /
    construct.Enum(construct.Byte, serial=0x00, model=0x01, software=0x02),
)

_QUERY_RESPONSE = construct.Struct(
    lifescan_binary_protocol.COMMAND_SUCCESS,
    'value' / construct.CString(encoding='utf-16-le'),
)

_READ_PARAMETER_REQUEST = construct.Struct(
    'selector' / construct.Enum(construct.Byte, unit=0x04), )

_READ_UNIT_RESPONSE = construct.Struct(
    lifescan_binary_protocol.COMMAND_SUCCESS,
    'unit' / lifescan_binary_protocol.GLUCOSE_UNIT,
    construct.Padding(3),
)

_READ_RTC_REQUEST = construct.Const(b'\x20\x02')

_READ_RTC_RESPONSE = construct.Struct(
    lifescan_binary_protocol.COMMAND_SUCCESS,
示例#12
0
    pass


# fmt: off
PsbtKeyValue = c.Struct(
    "key" / c.Prefixed(
        CompactUint,
        c.Struct(
            "type" / CompactUint,
            "data" / Optional(c.GreedyBytes),
        )),
    "value" / c.Prefixed(CompactUint, c.GreedyBytes),
)

PsbtProprietaryKey = c.Struct(
    "prefix" / c.CString("utf-8"),
    "subtype" / CompactUint,
    "data" / Optional(c.GreedyBytes),
)

PsbtSequence = c.FocusedSeq(
    "content",
    "content" / c.GreedyRange(PsbtKeyValue),
    c.Const(b"\0"),
)

PsbtEnvelope = c.FocusedSeq(
    "sequences",
    "magic" / c.Const(b"psbt\xff"),
    "sequences" / c.GreedyRange(PsbtSequence),
    c.Terminated,
示例#13
0
class FseventsdParser(interface.FileObjectParser):
  """Parser for fseventsd files.

  This parser supports both version 1 and version 2 fseventsd files.
  Refer to http://nicoleibrahim.com/apple-fsevents-forensics/ for details.
  """

  NAME = 'fsevents'

  DESCRIPTION = 'Parser for fseventsd files.'

  # The version 1 format was used in Mac OS X 10.5 (Leopard) through macOS 10.12
  # (Sierra).
  _DLS_V1_SIGNATURE = b'1SLD'
  _DLS_RECORD_V1 = construct.Struct(
      'dls_record_v1',
      construct.CString('path'),
      construct.ULInt64('event_identifier'),
      construct.UBInt32('flags'))

  # The version 2 format was introduced in MacOS High Sierra (10.13).
  _DLS_V2_SIGNATURE = b'2SLD'
  _DLS_RECORD_V2 = construct.Struct(
      'dls_record_v2',
      construct.CString('path'),
      construct.ULInt64('event_identifier'),
      construct.UBInt32('flags'),
      construct.ULInt64('node_identifier'))

  _DLS_SIGNATURES = [_DLS_V1_SIGNATURE, _DLS_V2_SIGNATURE]

  _DLS_PAGE_HEADER = construct.Struct(
      'dls_header',
      construct.OneOf(construct.Bytes('signature', 4), _DLS_SIGNATURES),
      construct.Padding(4),
      construct.ULInt32('page_size'))

  @classmethod
  def GetFormatSpecification(cls):
    """Retrieves the format specification.

    Returns:
      FormatSpecification: format specification.
    """
    format_specification = specification.FormatSpecification(cls.NAME)
    format_specification.AddNewSignature(cls._DLS_V1_SIGNATURE, offset=0)
    format_specification.AddNewSignature(cls._DLS_V2_SIGNATURE, offset=0)
    return format_specification

  def _ParseDLSPageHeader(self, file_object):
    """Parses a DLS page header from a file-like object.

    Args:
      file_object (file): file-like object to read the header from.

    Returns:
      construct.Container: parsed record structure.

    Raises:
      UnableToParseFile: when the header cannot be parsed.
    """
    try:
      return self._DLS_PAGE_HEADER.parse_stream(file_object)
    except construct.ConstructError:
      raise errors.UnableToParseFile('Unable to parse DLS header from file')

  def _BuildEventData(self, record):
    """Builds an FseventsdData object from a parsed structure.

    Args:
      record (construct.Container): parsed record structure.

    Returns:
      FseventsdEventData: event data attribute container.
    """
    event_data = FseventsdEventData()
    event_data.path = record.path
    event_data.flags = record.flags
    event_data.event_identifier = record.event_identifier
    # Node identifier is only set in DLS V2 records.
    event_data.node_identifier = getattr(record, 'node_identifier', None)

    return event_data

  def _GetParentModificationTime(self, gzip_file_entry):
    """Retrieves the modification time of the file entry's parent file.

    Note that this retrieves the time from the file entry of the parent of the
    gzip file entry's path spec, which is different from trying to retrieve it
    from the gzip file entry's parent file entry.

    It would be preferable to retrieve the modification time from the metadata
    in the gzip file itself, but it appears to not be set when the file is
    written by fseventsd.

    Args:
      gzip_file_entry (dfvfs.FileEntry): file entry of the gzip file containing
          the fseventsd data.

    Returns:
      dfdatetime.DateTimeValues: parent modification time, or None if not
          available.
    """
    parent_path_spec = gzip_file_entry.path_spec.parent
    parent_file_entry = path_spec_resolver.Resolver.OpenFileEntry(
        parent_path_spec)
    time_values = parent_file_entry.modification_time
    return time_values

  def ParseFileObject(self, parser_mediator, file_object, **kwargs):
    """Parses an fseventsd file.

    Args:
      parser_mediator (ParserMediator): parser mediator.
      file_object (dfvfs.FileIO): a file-like object.

    Raises:
      UnableToParseFile: when the header cannot be parsed.
    """
    page_header = self._ParseDLSPageHeader(file_object)
    current_page_end = page_header.page_size
    file_entry = parser_mediator.GetFileEntry()
    date_time = self._GetParentModificationTime(file_entry)
    # TODO: Change this to use a more representative time definition (time span)
    # when https://github.com/log2timeline/dfdatetime/issues/65 is resolved.
    if date_time:
      timestamp_description = definitions.TIME_DESCRIPTION_RECORDED
    else:
      date_time = dfdatetime_semantic_time.SemanticTime('Not set')
      timestamp_description = definitions.TIME_DESCRIPTION_NOT_A_TIME
    event = time_events.DateTimeValuesEvent(date_time, timestamp_description)

    while file_object.get_offset() < file_object.get_size():
      if file_object.get_offset() >= current_page_end:
        page_header = self._ParseDLSPageHeader(file_object)
        current_page_end += page_header.page_size
        continue
      if page_header.signature == self._DLS_V1_SIGNATURE:
        record = self._DLS_RECORD_V1.parse_stream(file_object)
      else:
        record = self._DLS_RECORD_V2.parse_stream(file_object)

      event_data = self._BuildEventData(record)
      parser_mediator.ProduceEventWithEventData(event, event_data)
示例#14
0
 def getStringFromHeap(index):
     stringHeap = streams.getStream('#Strings')
     stringHeap.seek(index)
     return construct.CString('Name').parse_stream(stringHeap)
示例#15
0
    #construct.String('pVersion', lambda ctx: ctx.iVersionString)
)

StorageHeader = construct.Struct('StorageHeader',
    construct.ULInt8('fFlags'),
    construct.Padding(1, strict = True),
    construct.ULInt16('iStreams')
)

MAXSTREAMNAME = 32

StorageStream = construct.Struct('StorageStream',
    # offset from StorageSignature.lSignature
    construct.ULInt32('iOffset'),
    construct.ULInt32('iSize'),
    construct.CString('rcName')
)

MetadataTableHeader = construct.Struct('MetadataTableHeader',
    construct.ULInt32('Reserved'),
    construct.ULInt8('MajorVersion'),
    construct.ULInt8('MinorVersion'),
    construct.FlagsEnum(construct.ULInt8('HeapSizeFlags'),
        StringHeapLarge = 0x01, # 4 byte uint indexes used for string heap offsets
        GUIDHeapLarge   = 0x02, # 4 byte uint indexes used for GUID heap offsets
        BlobHeapLarge   = 0x04, # 4 byte uint indexes used for Blob heap offsets
        EnCDeltas       = 0x20, # Indicates only EnC Deltas are present
        DeletedMarks    = 0x80, # Indicates metadata might contain items marked deleted
    ),
    construct.ULInt8('RowId'),
    construct.ULInt64('ValidTables'),
示例#16
0
    cst.Flag('background_on'),
    cst.Flag('non_english'),
    cst.Flag('autocenter'),
    cst.Flag('bold_joins_78'),
    cst.Flag('bold_joins_56'),
    cst.Flag('bold_joins_34'),
    cst.Flag('bold_joins_12'),
)

CMD_SEQ = cst.Struct(
    '_cmd', cst.Magic('\x1c'),
    cst.Enum(cst.Byte('cmd'), FLASH=70, ENLARGE=69, DEFAULT=68))

PAGE = cst.Struct('page', PAGE_IDX, cst.Embed(TEMPO), cst.Embed(PAGE_FUNC),
                  cst.Embed(PAGE_CFG), cst.Embed(CMD_SEQ),
                  cst.CString('body', terminators='\x04'))

DATETIME_BODY = cst.Struct(
    'datetime_page',
    cst.Const(PAGE_IDX, '000'),
)
# values as ascii numbers 0x30-0x39

MESSAGE = cst.Struct('msg', HEADER, SER_STATUS, PAGE)


class Protocol:
    @staticmethod
    def datetime_page():
        pass
示例#17
0
_PACKET = construct.Padded(_REGISTER_SIZE,
                           lifescan_binary_protocol.LifeScanPacket(False))

_COMMAND_SUCCESS = construct.Const(b"\x03\x06")

_QUERY_REQUEST = construct.Struct(
    const=construct.Const(b"\x03\xe6\x02"),
    selector=construct.Enum(construct.Byte,
                            serial=0x00,
                            model=0x01,
                            software=0x02),
)

_QUERY_RESPONSE = construct.Struct(
    const=construct.Const(b"\x03\x06"),
    value=construct.CString(encoding="utf-16-le"),
)

_READ_PARAMETER_REQUEST = construct.Struct(
    const=construct.Const(b"\x03"),
    selector=construct.Enum(construct.Byte, unit=0x04),
)

_READ_UNIT_RESPONSE = construct.Struct(
    success=_COMMAND_SUCCESS,
    unit=lifescan_binary_protocol.GLUCOSE_UNIT,
    padding=construct.Padding(3),
)

_READ_RTC_REQUEST = construct.Const(b"\x03\x20\x02")
示例#18
0
 def __init__(self, websocket, mode):
     self._websocket = websocket
     self._mode = mode
     self._inbound_packet = construct.Struct(
         "type" / construct.Enum(
             construct.Int8ul,
             setup=0,
             killed=1,
             kill=2,
             remove=3,
             sync=4,
             club_collision=5,
             wall_collision=6,
             set_leaderboard=7,
             set_target_dim=8
         ),
         "payload" / construct.Switch(
             construct.this.type, {
                 "setup": construct.Struct(
                     "server_version" / construct.CString(encoding="utf8"),
                     construct.Check(lambda ctx: ctx.server_version == CLIENT_VERSION),
                     "syncer_value" / construct.Int32ul,
                     "game_mode" / construct.Mapping(
                         construct.Int8ul, {
                             0: Mode.ffa,
                             1: Mode.tdm
                         },
                         dict() # This packet is only received
                     ),
                     "setup_value" / construct.Int32ul
                 ),
                 "killed": construct.Pass,
                 "kill": construct.Struct("stamp" / construct.Int32ul),
                 "remove": construct.Struct(
                     "enqueue_param" / construct.Int32ul, # TODO: Figure out purpose
                     "player_id" / construct.Int32ul
                 ),
                 "sync": construct.Struct(
                     "timestamp" / construct.Int32ul,
                     "remove_count" / construct.Int32ul,
                     "removal_array" / construct.Array(
                         construct.this.remove_count,
                         construct.Int32ul
                     ),
                     "sync_count" / construct.Int32ul,
                     "sync_array" / construct.Array(
                         construct.this.sync_count,
                         construct.Struct(
                             "player_id" / construct.Int32ul,
                             "player_state" / physical_state,
                             "mace_state" / physical_state,
                             "mace_radius" / construct.Float32l
                         )
                     )
                 ),
                 "club_collision": construct.Struct(
                     "enqueue_param" / construct.Int32ul, # TODO: Figure out purpose
                     "p" / vector2d, # TODO: Figure out purpose
                     "i" / construct.Float32l, # TODO: Figure out purpose
                     "first_id" / construct.Int32ul,
                     "first_state" / physical_state,
                     "second_id" / construct.Int32ul,
                     "second_state" / physical_state
                 ),
                 "wall_collision": construct.Struct(
                     "enqueue_param" / construct.Int32ul, # TODO: Figure out purpose
                     "p" / vector2d, # TODO: Figure out purpose
                     "i" / construct.Float32l, # TODO: Figure out purpose
                     "player_id" / construct.Int32ul,
                     "player_state" / physical_state,
                     "mace_radius" / construct.Float32l
                 ),
                 "set_leaderboard": construct.Struct(
                     "player_count" / construct.Int32ul,
                     "total" / construct.Int32ul, # TODO: Figure out purpose,
                     construct.IfThenElse(
                         lambda ctx: self._mode == Mode.ffa,
                         construct.Struct( # FFA
                             "count" / construct.Int8ul,
                             "first_entry_id" / construct.Int32ul,
                             "leaderboard" / construct.Array(
                                 construct.this.count,
                                 construct.Struct(
                                     "name" / construct.CString(encoding="utf8"),
                                     "score" / construct.Int32ul,
                                     )
                                 ),
                             "king_name" / construct.CString(encoding="utf8"),
                             "king_score" / construct.Int32ul,
                             "place" / construct.Int32ul,
                             "score" / construct.Int32ul
                         ),
                         construct.Array(
                             3,
                             construct.Struct(
                                 "id" / construct.Int8ul,
                                 "score" / construct.Int32ul,
                                 "count" / construct.Int32ul
                             )
                         )
                     )
                 ),
                 "set_target_dim": construct.Struct("target_dim" / vector2d)
             }
         )
     )
     self._outbound_packet = construct.Struct(
         "type" / construct.Enum(
             construct.Int8ul,
             play=0,
             direction=1,
             move_up=2,
             move_down=3,
             move_left=4,
             move_right=5,
             stop_move_up=6,
             stop_move_down=7,
             stop_move_left=8,
             stop_move_right=9
         ),
         "payload" / construct.Switch(
             construct.this.type, {
                 "play": construct.Pass
                         # TODO: Implement the rest of the packets
             }
         )
     )
示例#19
0
import socket

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"""

示例#20
0
"""
Created on Sat Nov 21 19:23:09 2020

@author: AsteriskAmpersand
"""

import construct as C
import copy
from pathlib import Path

mipOffsets = C.Struct(
    "mipOffset" / C.Int64sl[C.this._.mipCount],
    )

texHeader = C.Struct(
    "texString" / C.CString("utf8"),
    "version" / C.Int64sl,
    "datablock" / C.Int32sl,
    "format" / C.Int32sl,
    "mipCount" / C.Int32sl,
    "width" / C.Int32sl,
    "height" / C.Int32sl,
    "imageCount" / C.Int32sl,
    "typeData" / C.Int32sl,
    "one1" / C.Int32sl,
    "null0" / C.Int32sl[3],
    "neg0" / C.Int32sl,
    "null1" / C.Int32sl[2],
    "special" / C.Int32sl,
    "null2" / C.Int32sl[4],
    "neg1" / C.Int32sl[8],
示例#21
0
    "SEVEN" / C.Const(7, C.Int16ul),
    "ONE_1" / C.Const(1, C.Int16ul),
)

swizzleNull = C.Struct(
    "swizzleHeightDepth" / C.Int8ul,
    "swizzleHeight" / C.Computed(C.this.swizzleHeightDepth & 0xF),
    "swizzleDepth" / C.Computed(C.this.swizzleHeightDepth & 0xF0 >> 4),
    "swizzleWidth" / C.Int8ul,
    "NULL1" / C.Int16ul,
    "SEVEN" / C.Const(0, C.Int16ul),
    "ONE_1" / C.Const(0, C.Int16ul),
)

_TEXHeader = C.Struct(
    "magic" / C.CString("utf-8"),
    "version" / C.Int32ul,
    "width" / C.Int16ul,
    "height" / C.Int16ul,
    "depth" / C.Int16ul,
    "counts" / C.Int16ul,
    "imageCount" /
    C.Computed(lambda this: this.counts & 0x3FF if this.version in
               swizzableFormats else this.counts >> 8),  #C.Int8ul,#12
    "mipCount" /
    C.Computed(lambda this:
               (this.counts >> 12 if this.version in swizzableFormats else this
                .counts & 0xFF)),  #C.Int8ul,#4
    "format" / C.Int32ul,
    "swizzleControl" / C.Int32sl,  #C.Const(1,C.Int32ul),
    "cubemapMarker" / C.Int32ul,
示例#22
0
                construct.ULInt32("unk_dword_01"),
                construct.ULInt32("unk_dword_02"),
                construct.ULInt32("version"),
                construct.ULInt32("subversion"),
                construct.ULInt32("revision")
                )

safeEntry = construct.Struct("safeEntry",
                construct.ULInt32("unk_dword_00"),
                construct.ULInt32("unk_dword_01"),
                construct.ULInt32("unk_dword_02"),
                construct.ULInt32("SizeFile"),
                construct.ULInt32("Offset"),
                construct.ULInt32("unk_dword_03"),
                construct.ULInt32("unk_dword_04"),
                construct.CString("Name", terminators='\x00')
                )

def hexdump(src, length=16):
    FILTER = ''.join([(len(repr(chr(x))) == 3) and chr(x) or '.' for x in range(256)])
    lines = []
    for c in xrange(0, len(src), length):
        chars = src[c:c+length]
        hex = ' '.join(["%02x" % ord(x) for x in chars])
        printable = ''.join(["%s" % ((ord(x) <= 127 and FILTER[ord(x)]) or '.') for x in chars])
        lines.append("%04x  %-*s  %s\n" % (c, length*3, hex, printable))
    return ''.join(lines).rstrip('\n')

SIG = "BoG_ *90.0&!!  Yy>"
FILENAME = "comm2.exe"
示例#23
0
class WinRecyclerInfo2Parser(interface.FileObjectParser):
    """Parses the Windows Recycler INFO2 file."""

    NAME = u'recycle_bin_info2'
    DESCRIPTION = u'Parser for Windows Recycler INFO2 files.'

    # Define a list of all structs used.
    INT32_LE = construct.ULInt32(u'my_int')

    FILE_HEADER_STRUCT = construct.Struct(u'file_header', construct.Padding(8),
                                          construct.ULInt32(u'record_size'))

    # Struct based on (-both Unicode and byte strings):
    # https://code.google.com/p/rifiuti2/source/browse/trunk/src/rifiuti.h
    RECORD_STRUCT = construct.Struct(u'record', construct.ULInt32(u'index'),
                                     construct.ULInt32(u'drive'),
                                     construct.ULInt64(u'filetime'),
                                     construct.ULInt32(u'filesize'))

    STRING_STRUCT = construct.CString(u'legacy_filename')

    # Define a list of needed variables.
    UNICODE_FILENAME_OFFSET = 0x11C
    RECORD_INDEX_OFFSET = 0x108

    def ParseFileObject(self, parser_mediator, file_object, **kwargs):
        """Parses a Windows Recycler INFO2 file-like object.

    Args:
      parser_mediator: A parser mediator object (instance of ParserMediator).
      file_object: A file-like object.

    Raises:
      UnableToParseFile: when the file cannot be parsed.
    """
        try:
            magic_header = self.INT32_LE.parse_stream(file_object)
        except (construct.FieldError, IOError) as exception:
            raise errors.UnableToParseFile(
                u'Unable to parse INFO2 file with error: {0:s}'.format(
                    exception))

        if magic_header != 5:
            raise errors.UnableToParseFile(
                u'Not an INFO2 file, wrong magic header.')

        # Since this header value is really generic it is hard not to use filename
        # as an indicator too.
        # TODO: Rethink this and potentially make a better test.
        filename = parser_mediator.GetFilename()
        if not filename.startswith(u'INFO2'):
            raise errors.UnableToParseFile(
                u'Not an INFO2 file, filename isn\'t INFO2.')

        file_header = self.FILE_HEADER_STRUCT.parse_stream(file_object)

        # Limit record size to 65536 to be on the safe side.
        record_size = file_header[u'record_size']
        if record_size > 65536:
            parser_mediator.ProduceParseError(
                (u'Record size: {0:d} is too large for INFO2. Defaulting to: '
                 u'65535').format(record_size))
            record_size = 65535

        # If recordsize is 0x320 then we have Unicode names as well.
        read_unicode_names = False
        if record_size == 0x320:
            read_unicode_names = True

        data = file_object.read(record_size)
        while data:
            if len(data) != record_size:
                break
            filename_string = self.STRING_STRUCT.parse(data[4:])
            record_information = self.RECORD_STRUCT.parse(
                data[self.RECORD_INDEX_OFFSET:])
            if read_unicode_names:
                filename_utf = binary.ReadUTF16(
                    data[self.UNICODE_FILENAME_OFFSET:])
            else:
                filename_utf = u''

            filetime = record_information.get(u'filetime', 0)
            # TODO: handle missing timestamp.
            event_object = WinRecycleEvent(filetime,
                                           filename_string,
                                           filename_utf,
                                           record_information,
                                           record_size,
                                           encoding=parser_mediator.codepage)
            parser_mediator.ProduceEvent(event_object)

            data = file_object.read(record_size)
示例#24
0
        'Hardcoded Value 2' / HexString(construct.Int32ul),
        'Hardcoded Value 3' / HexString(construct.Int32ul),
        construct.Padding(0x17),
        'Compromised Host IP' / IP4Address,  # Use IP adapter
        # 'Unknown IP Addresses' / construct.Switch(
        #     this['Hardcoded Value 1'],
        #     {
        #         '0x1f4' : EMBED_SPEC
        #     },
        # ),
        'Unknown IP Addresses' / address_struct[4],
        # 'Unknown IP Addresses' / IP4Address[4],
        construct.Padding(8),
        'Unknown Indicator' / construct.String(0xF),
        construct.Padding(2),
        'Number of CPUs' / construct.Int32ul,
        'CPU Mhz' / construct.Int32ul,
        'Total Memory (MB)' / construct.Int32ul,
        'Compromised System Kernel' / construct.CString(),
        'Possible Trojan Version' / construct.CString())

    data = (
        b'\x01\x00\x00\x00}\x00\x00\x00\x00\xf4\x01\x00\x002\x00\x00\x00\xe8'
        b'\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01'
        b'\x01\x00\x00\x00\x00\x01\x00\x00\x00\xc0\xa8\x01\r\xc0\xa8\x01\r\xc0'
        b'\xa8\x01\r\xc0\xa8\x01\r\xc0\xa8\x01\r\xff\xff\x01\x00\x00\x00\x00\x00'
        b'-== Love AV ==-:\x00\x01\x00\x00\x00d\n\x00\x00\xc4\x07\x00\x00'
        b'Linux 3.13.0-93-generic\x001:G2.40\x00')

    print(html_hex(PACKET, data, depth=2))
示例#25
0
    cst.Flag('bold_joins_12'),
)

CMD_SEQ = cst.Sequence(
    '_cmd', cst.Magic('\x1c'),
    cst.Enum(cst.Byte('cmd'),
             FLASH='F',
             ENLARGE='E',
             RED='R',
             GREEN='G',
             YELLOW='Y',
             MULTICOLOUR='M',
             DEFAULT='D'))

PAGE = cst.Struct('page', PAGE_IDX, cst.Embed(TEMPO), cst.Embed(PAGE_FUNC),
                  cst.Embed(PAGE_CFG), cst.CString('body', terminators='\x04'))

DATETIME_BODY = cst.Struct(
    'datetime_page',
    cst.Const(PAGE_IDX, '000'),
)
# values as ascii numbers 0x30-0x39

# hours_m
# hours_l
# mins_m
# mins_l
# secs_m
# secs_l
# date_m
# date_l
示例#26
0
 c.If(lambda ctx: ctx["version"] >= 3,
     c.Struct("ext_date",
         OpenTTD_NewDate("current"),
         OpenTTD_NewDate("start"),
     )
 ),
 c.If(lambda ctx: ctx["version"] >= 2,
     c.Struct("ext_limits",
         c.ULInt8("companies_max"),
         c.ULInt8("companies_current"),
         c.ULInt8("spectators_max")
     )
 ),
 c.If(lambda ctx: ctx["version"] >= 1,
     c.Struct("basic", 
         c.CString("name"),
         c.CString("revision"),
         c.Enum(c.ULInt8("language"),
             any=0,
             en=1,
             de=2,
             fr=3,
         ),
         c.ULInt8("password"),
         c.ULInt8("clients_max"),
         c.ULInt8("clients_current"),
         c.ULInt8("spectators_current"),
         c.If(lambda ctx: ctx["_"]["version"] < 3, c.Struct("old_date",
             OpenTTD_OldDate("current"),
             OpenTTD_OldDate("start"),
         )),
示例#27
0
InitCmd = c.Struct(
    "FIELD_ID" / c.Const(ControlPacketField.build("PKT_INIT")),
    "INIT" / c.FlagsEnum(
        c.Byte,
        echo_canceller=0x4,
        decoder_init=0x2,
        encoder_init=0x1,
    ))

ProdIdCmd = c.Struct("FIELD_ID" /
                     c.Const(ControlPacketField.build("PKT_PRODID")))

ProdIdResp = c.Struct(
    "FIELD_ID" / c.Const(ControlPacketField.build("PKT_PRODID")),
    "PRODID" / c.CString("utf8"))

VersionCmd = c.Struct("FIELD_ID" /
                      c.Const(ControlPacketField.build("PKT_VERSTRING")))

VersionResp = c.Struct(
    "FIELD_ID" / c.Const(ControlPacketField.build("PKT_VERSTRING")),
    "VERSTRING" / c.CString("utf8"))

RateTCmd = c.Struct(
    "FIELD_ID" / c.Const(ControlPacketField.build("PKT_RATET")),
    "RATE_IDX" / c.Byte)

RateTResp = c.Struct(
    "FIELD_ID" / c.Const(ControlPacketField.build("PKT_RATET")),
    "RESULT" / c.Byte)
示例#28
0
    "frameIndex" /
    C.Pointer(C.this.frameIndexOffset,
              C.Int32sl[C.this.frameIndexCount]),  #32-Padded to next
    "mapIndices" /
    C.IfThenElse(C.this.frameCount != 0,
                 C.Pointer(C.this.dataOffset, C.Int32sl[4]), C.Int32sl[0]),
)


def defaultMapIndices(l):
    return l + [0] * (4 - len(l))


StringHead = C.Struct("blank" / C.Int64sl, "stringOffset" / C.Int64sl,
                      "type" / C.Int32sl)
StringBody = C.Struct("string" / C.CString("utf-8"), )
StringData = C.Struct(
    "blank" / C.Int64sl, "stringOffset" / C.Int64sl, "type" / C.Int32sl,
    "string" / C.Pointer(C.this.stringOffset, C.CString("utf-8")),
    "padding" / C.Optional(C.Const(0, C.Int32sl)))

UVSFile = C.Struct(
    "Header" / Header, "Groups" /
    C.Pointer(C.this.Header.groupOffset, Group[C.this.Header.groupCount]),
    "Strings" / C.Pointer(C.this.Header.stringOffset,
                          StringData[C.this.Header.stringCount]))


def pad(size, offset):
    cursor = offset
    return (-cursor) % size + offset
示例#29
0
_COMMAND_SUCCESS = construct.Const(b'\x03\x06')

_VERSION_REQUEST = construct.Const(b'\x03\x0d\x01')

_VERSION_RESPONSE = construct.Struct(
    _COMMAND_SUCCESS,
    'version' / construct.PascalString(construct.Byte, encoding='ascii'),
    # NULL-termination is not included in string length.
    construct.Const(b'\x00'),
)

_SERIAL_NUMBER_REQUEST = construct.Const(b'\x03\x0b\x01\x02')

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

_READ_RTC_REQUEST = construct.Const(b'\x03\x20\x02')

_READ_RTC_RESPONSE = construct.Struct(
    _COMMAND_SUCCESS,
    'timestamp' / lifescan_binary_protocol.VERIO_TIMESTAMP,
)

_WRITE_RTC_REQUEST = construct.Struct(
    construct.Const(b'\x03\x20\x01'),
    'timestamp' / lifescan_binary_protocol.VERIO_TIMESTAMP,
)

_GLUCOSE_UNIT_REQUEST = construct.Const(b'\x03\x09\x02\x02')
示例#30
0
def createdir(dirname):
    try:
        os.stat(dirname)
    except:
        os.mkdir(dirname)


#
# DAS filename & description
#

das_string_entry = construct.Struct(
    "sizeof" / construct.
    Int16ul,  # + 0x00        (sizeof (index) + len(name) + len(desc) + 2)
    "index" / construct.Int16ul,  # + 0x02
    "name" / construct.CString(),  # + 0x04
    "desc" / construct.CString(),  # + 0xXX
)

das_strings = construct.Struct(
    "nb_unk_00" / construct.Int16ul,  # + 0x00
    "nb_unk_01" / construct.Int16ul,  # + 0x02
    "entries_00" /
    construct.Array(lambda ctx: ctx.nb_unk_00, das_string_entry),  # + 0x04
    "entries_01" /
    construct.Array(lambda ctx: ctx.nb_unk_01, das_string_entry))

# cseg01:0004122F 80 7A 06 20                             cmp     byte ptr [edx+6], 20h ; ' '
# cseg01:00041233 74 D8                                   jz      short loc_4120D
# cseg01:00041235 80 7A 06 24                             cmp     byte ptr [edx+6], 24h ; '$'
# cseg01:00041239 74 D2                                   jz      short loc_4120D