Skip to content

read_bytes(): add extra length check #61

@armijnhemel

Description

@armijnhemel

read_bytes() could benefit from an extra length check. I am using kaitai struct for parsing and there are plenty of false positives for certain file types. I sometimes end up reading a lot of extra data. With an extra check to see if the amount of bytes to be read is smaller than the stream size or file size this would be avoided:

    def read_bytes(self, n):
        if n < 0:
            raise ValueError(
                "requested invalid %d amount of bytes" %
                (n,)
            )
        r = self._io.read(n)
        if len(r) < n:
            raise EOFError(
                "requested %d bytes, but got only %d bytes" %
                (n, len(r))
            )
        return r

for example could be rewritten to something like:

    def read_bytes(self, n):
        if n < 0:
            raise ValueError(
                "requested invalid %d amount of bytes" %
                (n,)
            )
        if n > self.size():
            raise ValueError(
                 "requested to read %d bytes, but only %d available" %
                 (n, self.size()))
        r = self._io.read(n)
        if len(r) < n:
            raise EOFError(
                "requested %d bytes, but got only %d bytes" %
                (n, len(r))
            )
        return r

or something similar.

Right now I am trying to work around this by adding extra boundary checks in the .ksy files that looks at the size of the file, but that's a rather ugly hack.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions