Nix Archive (NAR): Python parsing library

Nix Archive (NAR) is the archive format of the Nix package manager. A NAR contains a single file system object: a regular file, a symbolic link, or a directory with everything in it. Besides names, file contents and symlink targets, it only stores which regular files are executable. There are no timestamps and no other permissions.

Unlike TAR or ZIP, the format is canonical: a given file system object always has the same NAR. For example, directory entries are always sorted by name. Nix identifies the contents of each store path by the SHA-256 hash of its NAR, and binary caches serve store paths as NARs, usually compressed. GNU Guix uses the same format.

This Kaitai Struct implementation rejects the same NARs as Nix 2.36.0 with the default settings on Linux, except that it accepts entry names that contain /.

Older versions of Nix may accept more NARs. For example, Nix checks the order of directory entries only since version 2.25.0, and it limits the length of names and symlink targets and the nesting depth only since 2.35.0. Some of these checks were also backported to patch releases of older versions.

File extension

nar

KS implementation details

License: MIT

References

This page hosts a formal specification of Nix Archive (NAR) using Kaitai Struct. This specification can be automatically translated into a variety of programming languages to get a parsing library.

Usage

Runtime library

All Python code generated by Kaitai Struct depends on the Kaitai Struct runtime library for Python. You must add this dependency to your project before you can parse or serialize any data.

The Python runtime library can be installed from PyPI:

python3 -m pip install kaitaistruct

Code

Parse a local file and get structure in memory:

data = NixNar.from_file("path/to/local/file.nar")

Or parse structure from a bytes:

from kaitaistruct import KaitaiStream, BytesIO

raw = b"\x00\x01\x02..."
data = NixNar(KaitaiStream(BytesIO(raw)))

After that, one can get various attributes from the structure by invoking getter methods like:

data.magic # => Magic string, must be `nix-archive-1`.

Python source code to parse Nix Archive (NAR)

nix_nar.py

# This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild
# type: ignore

import kaitaistruct
from kaitaistruct import KaitaiStruct, KaitaiStream, BytesIO


if getattr(kaitaistruct, 'API_VERSION', (0, 9)) < (0, 11):
    raise Exception("Incompatible Kaitai Struct Python API: 0.11 or later is required, but you have %s" % (kaitaistruct.__version__))

class NixNar(KaitaiStruct):
    """Nix Archive (NAR) is the archive format of the [Nix](https://nixos.org/)
    package manager. A NAR contains a single file system object: a regular
    file, a symbolic link, or a directory with everything in it. Besides
    names, file contents and symlink targets, it only stores which regular
    files are executable. There are
    [no timestamps and no other permissions](https://github.com/NixOS/nix/blob/88907193c54fcd5184cf59d14b693188e2875168/doc/manual/source/command-ref/nix-store/dump.md?plain=1#L15-L19).
    
    Unlike TAR or ZIP, the format is
    [canonical](https://github.com/NixOS/nix/blob/88907193c54fcd5184cf59d14b693188e2875168/doc/manual/source/command-ref/nix-store/dump.md?plain=1#L21-L27):
    a given file system object always has the same NAR. For example,
    directory entries are always sorted by name. Nix identifies the contents
    of each store path by the SHA-256 hash of its NAR, and
    [binary caches](https://github.com/NixOS/nix/blob/88907193c54fcd5184cf59d14b693188e2875168/doc/manual/source/protocols/binary-cache/index.md?plain=1#L8-L10)
    serve store paths as NARs, usually compressed.
    [GNU Guix](https://codeberg.org/guix/guix/src/commit/ab6a9f84e783710335a29f6591f570e5e2df143c/guix/serialization.scm#L441-L446)
    uses the same format.
    
    This Kaitai Struct implementation rejects the same NARs as Nix 2.36.0
    with the default settings on Linux, except that it accepts entry names
    that contain `/`.
    
    Older versions of Nix may accept more NARs. For example, Nix checks the
    order of directory entries only since version 2.25.0, and it limits the
    length of names and symlink targets and the nesting depth only since
    2.35.0. Some of these checks were also backported to patch releases of
    older versions.
    
    .. seealso::
       Git tag "2.36.0" - https://github.com/NixOS/nix/blob/88907193c54fcd5184cf59d14b693188e2875168/doc/manual/source/protocols/nix-archive/index.md
    """
    def __init__(self, _io, _parent=None, _root=None):
        super(NixNar, self).__init__(_io)
        self._parent = _parent
        self._root = _root or self
        self._read()

    def _read(self):
        self.magic = NixNar.PaddedStr(self._io, self, self._root)
        _ = self.magic
        if not _.body == u"nix-archive-1":
            raise kaitaistruct.ValidationExprError(self.magic, self._io, u"/seq/0")
        self.root_node = NixNar.Node(0, self._io, self, self._root)


    def _fetch_instances(self):
        pass
        self.magic._fetch_instances()
        self.root_node._fetch_instances()

    class Node(KaitaiStruct):
        """A single file system node (regular file, directory, or symlink)."""
        def __init__(self, depth, _io, _parent=None, _root=None):
            super(NixNar.Node, self).__init__(_io)
            self._parent = _parent
            self._root = _root
            self.depth = depth
            self._read()

        def _read(self):
            self._unnamed0 = self._io.read_bytes(0)
            _ = self._unnamed0
            if not self.depth < 64:
                raise kaitaistruct.ValidationExprError(self._unnamed0, self._io, u"/types/node/seq/0")
            self.open_paren = NixNar.PaddedStr(self._io, self, self._root)
            _ = self.open_paren
            if not _.body == u"(":
                raise kaitaistruct.ValidationExprError(self.open_paren, self._io, u"/types/node/seq/1")
            self.type_key = NixNar.PaddedStr(self._io, self, self._root)
            _ = self.type_key
            if not _.body == u"type":
                raise kaitaistruct.ValidationExprError(self.type_key, self._io, u"/types/node/seq/2")
            self.type_val = NixNar.PaddedStr(self._io, self, self._root)
            _ = self.type_val
            if not  ((_.body == u"regular") or (_.body == u"directory") or (_.body == u"symlink")) :
                raise kaitaistruct.ValidationExprError(self.type_val, self._io, u"/types/node/seq/3")
            _on = self.type_val.body
            if _on == u"directory":
                pass
                self.body = NixNar.TypeDirectory(self._io, self, self._root)
            elif _on == u"regular":
                pass
                self.body = NixNar.TypeRegular(self._io, self, self._root)
            elif _on == u"symlink":
                pass
                self.body = NixNar.TypeSymlink(self._io, self, self._root)
            if self.type_val.body != u"directory":
                pass
                self.close_paren = NixNar.PaddedStr(self._io, self, self._root)
                _ = self.close_paren
                if not _.body == u")":
                    raise kaitaistruct.ValidationExprError(self.close_paren, self._io, u"/types/node/seq/5")



        def _fetch_instances(self):
            pass
            self.open_paren._fetch_instances()
            self.type_key._fetch_instances()
            self.type_val._fetch_instances()
            _on = self.type_val.body
            if _on == u"directory":
                pass
                self.body._fetch_instances()
            elif _on == u"regular":
                pass
                self.body._fetch_instances()
            elif _on == u"symlink":
                pass
                self.body._fetch_instances()
            if self.type_val.body != u"directory":
                pass
                self.close_paren._fetch_instances()



    class PaddedBytes(KaitaiStruct):
        """A byte sequence, prefixed with its length (u8le) and
        padded with null bytes to the next 8-byte boundary.
        
        Used for entry names and symlink targets, which Nix handles as raw
        bytes, without decoding them as text.
        """
        def __init__(self, _io, _parent=None, _root=None):
            super(NixNar.PaddedBytes, self).__init__(_io)
            self._parent = _parent
            self._root = _root
            self._read()

        def _read(self):
            self.len_body = self._io.read_u8le()
            self.body = self._io.read_bytes(self.len_body)
            self.padding = self._io.read_bytes((8 - self.len_body % 8) % 8)
            _ = self.padding
            if not (KaitaiStream.byte_array_max(_) == 0 if len(_) != 0 else True):
                raise kaitaistruct.ValidationExprError(self.padding, self._io, u"/types/padded_bytes/seq/2")


        def _fetch_instances(self):
            pass


    class PaddedStr(KaitaiStruct):
        """A string, prefixed with its length (u8le) and
        padded with null bytes to the next 8-byte boundary.
        
        Used for the tokens of the format, such as `nix-archive-1`, `(` and
        `type`. They are all ASCII.
        """
        def __init__(self, _io, _parent=None, _root=None):
            super(NixNar.PaddedStr, self).__init__(_io)
            self._parent = _parent
            self._root = _root
            self._read()

        def _read(self):
            self.len_body = self._io.read_u8le()
            self.body = (self._io.read_bytes(self.len_body)).decode(u"ASCII")
            self.padding = self._io.read_bytes((8 - self.len_body % 8) % 8)
            _ = self.padding
            if not (KaitaiStream.byte_array_max(_) == 0 if len(_) != 0 else True):
                raise kaitaistruct.ValidationExprError(self.padding, self._io, u"/types/padded_str/seq/2")


        def _fetch_instances(self):
            pass


    class TypeDirectory(KaitaiStruct):
        """A directory node, containing a list of entries. Entries must be
        ordered by their names. Each name must be greater than the previous
        one when compared lexicographically as arrays of unsigned bytes.
        """
        def __init__(self, _io, _parent=None, _root=None):
            super(NixNar.TypeDirectory, self).__init__(_io)
            self._parent = _parent
            self._root = _root
            self._read()

        def _read(self):
            self.entries = []
            i = 0
            while True:
                _ = NixNar.TypeDirectory.DirEntry(self._io, self, self._root)
                self.entries.append(_)
                _ = self.entries[i]
                if not (_.body.name.body > self.entries[i - 1].body.name.body if  ((i != 0) and ((not (_.is_terminator))))  else True):
                    raise kaitaistruct.ValidationExprError(self.entries[i], self._io, u"/types/type_directory/seq/0")
                if _.is_terminator:
                    break
                i += 1


        def _fetch_instances(self):
            pass
            for i in range(len(self.entries)):
                pass
                self.entries[i]._fetch_instances()


        class DirEntry(KaitaiStruct):
            """A single entry within a directory, or the terminator, i.e. the `)`
            token that ends the directory node.
            """
            def __init__(self, _io, _parent=None, _root=None):
                super(NixNar.TypeDirectory.DirEntry, self).__init__(_io)
                self._parent = _parent
                self._root = _root
                self._read()

            def _read(self):
                self.kind = NixNar.PaddedStr(self._io, self, self._root)
                _ = self.kind
                if not  ((_.body == u"entry") or (_.body == u")")) :
                    raise kaitaistruct.ValidationExprError(self.kind, self._io, u"/types/type_directory/types/dir_entry/seq/0")
                if (not (self.is_terminator)):
                    pass
                    self.body = NixNar.TypeDirectory.DirEntryBody(self._io, self, self._root)



            def _fetch_instances(self):
                pass
                self.kind._fetch_instances()
                if (not (self.is_terminator)):
                    pass
                    self.body._fetch_instances()


            @property
            def is_terminator(self):
                if hasattr(self, '_m_is_terminator'):
                    return self._m_is_terminator

                self._m_is_terminator = self.kind.body == u")"
                return getattr(self, '_m_is_terminator', None)


        class DirEntryBody(KaitaiStruct):
            def __init__(self, _io, _parent=None, _root=None):
                super(NixNar.TypeDirectory.DirEntryBody, self).__init__(_io)
                self._parent = _parent
                self._root = _root
                self._read()

            def _read(self):
                self.open_paren = NixNar.PaddedStr(self._io, self, self._root)
                _ = self.open_paren
                if not _.body == u"(":
                    raise kaitaistruct.ValidationExprError(self.open_paren, self._io, u"/types/type_directory/types/dir_entry_body/seq/0")
                self.name_key = NixNar.PaddedStr(self._io, self, self._root)
                _ = self.name_key
                if not _.body == u"name":
                    raise kaitaistruct.ValidationExprError(self.name_key, self._io, u"/types/type_directory/types/dir_entry_body/seq/1")
                self.name = NixNar.PaddedBytes(self._io, self, self._root)
                _ = self.name
                if not  ((len(_.body) != 0) and (len(_.body) <= 255) and (_.body != b"\x2E") and (_.body != b"\x2E\x2E") and (KaitaiStream.byte_array_min(_.body) != 0)) :
                    raise kaitaistruct.ValidationExprError(self.name, self._io, u"/types/type_directory/types/dir_entry_body/seq/2")
                self.node_key = NixNar.PaddedStr(self._io, self, self._root)
                _ = self.node_key
                if not _.body == u"node":
                    raise kaitaistruct.ValidationExprError(self.node_key, self._io, u"/types/type_directory/types/dir_entry_body/seq/3")
                self.node = NixNar.Node(self._parent._parent._parent.depth + 1, self._io, self, self._root)
                self.close_paren = NixNar.PaddedStr(self._io, self, self._root)
                _ = self.close_paren
                if not _.body == u")":
                    raise kaitaistruct.ValidationExprError(self.close_paren, self._io, u"/types/type_directory/types/dir_entry_body/seq/5")


            def _fetch_instances(self):
                pass
                self.open_paren._fetch_instances()
                self.name_key._fetch_instances()
                self.name._fetch_instances()
                self.node_key._fetch_instances()
                self.node._fetch_instances()
                self.close_paren._fetch_instances()



    class TypeRegular(KaitaiStruct):
        """A regular file node."""
        def __init__(self, _io, _parent=None, _root=None):
            super(NixNar.TypeRegular, self).__init__(_io)
            self._parent = _parent
            self._root = _root
            self._read()

        def _read(self):
            self.first_key = NixNar.PaddedStr(self._io, self, self._root)
            _ = self.first_key
            if not  ((_.body == u"executable") or (_.body == u"contents")) :
                raise kaitaistruct.ValidationExprError(self.first_key, self._io, u"/types/type_regular/seq/0")
            if self.is_executable:
                pass
                self.executable_val = NixNar.PaddedStr(self._io, self, self._root)
                _ = self.executable_val
                if not _.body == u"":
                    raise kaitaistruct.ValidationExprError(self.executable_val, self._io, u"/types/type_regular/seq/1")

            if self.is_executable:
                pass
                self.contents_key = NixNar.PaddedStr(self._io, self, self._root)
                _ = self.contents_key
                if not _.body == u"contents":
                    raise kaitaistruct.ValidationExprError(self.contents_key, self._io, u"/types/type_regular/seq/2")

            self.file_data = NixNar.TypeRegular.FileContent(self._io, self, self._root)


        def _fetch_instances(self):
            pass
            self.first_key._fetch_instances()
            if self.is_executable:
                pass
                self.executable_val._fetch_instances()

            if self.is_executable:
                pass
                self.contents_key._fetch_instances()

            self.file_data._fetch_instances()

        class FileContent(KaitaiStruct):
            """The contents of the file, prefixed with their length and padded
            with null bytes to the next 8-byte boundary.
            """
            def __init__(self, _io, _parent=None, _root=None):
                super(NixNar.TypeRegular.FileContent, self).__init__(_io)
                self._parent = _parent
                self._root = _root
                self._read()

            def _read(self):
                self.len_contents = self._io.read_u8le()
                if self.nar_offset < 0:
                    pass
                    self._unnamed1 = self._io.read_bytes(0)

                self.contents = self._io.read_bytes(self.len_contents)
                self.padding = self._io.read_bytes((8 - self.len_contents % 8) % 8)
                _ = self.padding
                if not (KaitaiStream.byte_array_max(_) == 0 if len(_) != 0 else True):
                    raise kaitaistruct.ValidationExprError(self.padding, self._io, u"/types/type_regular/types/file_content/seq/3")


            def _fetch_instances(self):
                pass
                if self.nar_offset < 0:
                    pass


            @property
            def nar_offset(self):
                """Offset of `contents` in the stream. It corresponds to
                [`narOffset`](https://github.com/NixOS/nix/blob/88907193c54fcd5184cf59d14b693188e2875168/src/libutil/include/nix/util/source-accessor.hh#L134-L138)
                in Nix.
                """
                if hasattr(self, '_m_nar_offset'):
                    return self._m_nar_offset

                self._m_nar_offset = self._io.pos()
                return getattr(self, '_m_nar_offset', None)


        @property
        def is_executable(self):
            """True if the file has the `executable` attribute."""
            if hasattr(self, '_m_is_executable'):
                return self._m_is_executable

            self._m_is_executable = self.first_key.body == u"executable"
            return getattr(self, '_m_is_executable', None)


    class TypeSymlink(KaitaiStruct):
        """A symbolic link node."""
        def __init__(self, _io, _parent=None, _root=None):
            super(NixNar.TypeSymlink, self).__init__(_io)
            self._parent = _parent
            self._root = _root
            self._read()

        def _read(self):
            self.target_key = NixNar.PaddedStr(self._io, self, self._root)
            _ = self.target_key
            if not _.body == u"target":
                raise kaitaistruct.ValidationExprError(self.target_key, self._io, u"/types/type_symlink/seq/0")
            self.target_val = NixNar.PaddedBytes(self._io, self, self._root)
            _ = self.target_val
            if not  ((len(_.body) != 0) and (len(_.body) <= 4095) and (KaitaiStream.byte_array_min(_.body) != 0)) :
                raise kaitaistruct.ValidationExprError(self.target_val, self._io, u"/types/type_symlink/seq/1")


        def _fetch_instances(self):
            pass
            self.target_key._fetch_instances()
            self.target_val._fetch_instances()