Nix Archive (NAR): Ruby 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 Ruby code generated by Kaitai Struct depends on the Kaitai Struct runtime library for Ruby. You must add this dependency to your project before you can parse or serialize any data.

The Ruby runtime library can be installed from RubyGems:

gem install kaitai-struct

Code

Parse a local file and get structure in memory:

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

Or parse structure from a string of bytes:

bytes = "\x00\x01\x02..."
data = NixNar.new(Kaitai::Struct::Stream.new(bytes))

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

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

Ruby source code to parse Nix Archive (NAR)

nix_nar.rb

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

require 'kaitai/struct/struct'

unless Gem::Version.new(Kaitai::Struct::VERSION) >= Gem::Version.new('0.11')
  raise "Incompatible Kaitai Struct Ruby API: 0.11 or later is required, but you have #{Kaitai::Struct::VERSION}"
end


##
# 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.
# @see https://github.com/NixOS/nix/blob/88907193c54fcd5184cf59d14b693188e2875168/doc/manual/source/protocols/nix-archive/index.md Git tag "2.36.0"
class NixNar < Kaitai::Struct::Struct
  def initialize(_io, _parent = nil, _root = nil)
    super(_io, _parent, _root || self)
    _read
  end

  def _read
    @magic = PaddedStr.new(@_io, self, @_root)
    _ = @magic
    raise Kaitai::Struct::ValidationExprError.new(@magic, @_io, "/seq/0") if not _.body == "nix-archive-1"
    @root_node = Node.new(@_io, self, @_root, 0)
    self
  end

  ##
  # A single file system node (regular file, directory, or symlink).
  class Node < Kaitai::Struct::Struct
    def initialize(_io, _parent = nil, _root = nil, depth)
      super(_io, _parent, _root)
      @depth = depth
      _read
    end

    def _read
      @_unnamed0 = @_io.read_bytes(0)
      _ = @_unnamed0
      raise Kaitai::Struct::ValidationExprError.new(@_unnamed0, @_io, "/types/node/seq/0") if not depth < 64
      @open_paren = PaddedStr.new(@_io, self, @_root)
      _ = @open_paren
      raise Kaitai::Struct::ValidationExprError.new(@open_paren, @_io, "/types/node/seq/1") if not _.body == "("
      @type_key = PaddedStr.new(@_io, self, @_root)
      _ = @type_key
      raise Kaitai::Struct::ValidationExprError.new(@type_key, @_io, "/types/node/seq/2") if not _.body == "type"
      @type_val = PaddedStr.new(@_io, self, @_root)
      _ = @type_val
      raise Kaitai::Struct::ValidationExprError.new(@type_val, @_io, "/types/node/seq/3") if not  ((_.body == "regular") || (_.body == "directory") || (_.body == "symlink")) 
      case type_val.body
      when "directory"
        @body = TypeDirectory.new(@_io, self, @_root)
      when "regular"
        @body = TypeRegular.new(@_io, self, @_root)
      when "symlink"
        @body = TypeSymlink.new(@_io, self, @_root)
      end
      if type_val.body != "directory"
        @close_paren = PaddedStr.new(@_io, self, @_root)
        _ = @close_paren
        raise Kaitai::Struct::ValidationExprError.new(@close_paren, @_io, "/types/node/seq/5") if not _.body == ")"
      end
      self
    end
    attr_reader :_unnamed0

    ##
    # Must be `(`, a token starting the node definition.
    attr_reader :open_paren

    ##
    # Must be `type`.
    attr_reader :type_key

    ##
    # Type of the node (`regular`, `directory`, or `symlink`).
    attr_reader :type_val
    attr_reader :body

    ##
    # Must be `)`, a token ending the node definition. A directory node
    # has no `close_paren`: its `)` is read as the terminator at the end
    # of `body.entries`.
    attr_reader :close_paren

    ##
    # Nesting depth of the node. The root node has depth 0.
    attr_reader :depth
  end

  ##
  # 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.
  class PaddedBytes < Kaitai::Struct::Struct
    def initialize(_io, _parent = nil, _root = nil)
      super(_io, _parent, _root)
      _read
    end

    def _read
      @len_body = @_io.read_u8le
      @body = @_io.read_bytes(len_body)
      @padding = @_io.read_bytes((8 - len_body % 8) % 8)
      _ = @padding
      raise Kaitai::Struct::ValidationExprError.new(@padding, @_io, "/types/padded_bytes/seq/2") if not (_.size != 0 ? _.bytes.max == 0 : true)
      self
    end
    attr_reader :len_body
    attr_reader :body
    attr_reader :padding
  end

  ##
  # 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.
  class PaddedStr < Kaitai::Struct::Struct
    def initialize(_io, _parent = nil, _root = nil)
      super(_io, _parent, _root)
      _read
    end

    def _read
      @len_body = @_io.read_u8le
      @body = (@_io.read_bytes(len_body)).force_encoding("ASCII").encode('UTF-8')
      @padding = @_io.read_bytes((8 - len_body % 8) % 8)
      _ = @padding
      raise Kaitai::Struct::ValidationExprError.new(@padding, @_io, "/types/padded_str/seq/2") if not (_.size != 0 ? _.bytes.max == 0 : true)
      self
    end
    attr_reader :len_body
    attr_reader :body
    attr_reader :padding
  end

  ##
  # 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.
  class TypeDirectory < Kaitai::Struct::Struct
    def initialize(_io, _parent = nil, _root = nil)
      super(_io, _parent, _root)
      _read
    end

    def _read
      @entries = []
      i = 0
      begin
        _ = DirEntry.new(@_io, self, @_root)
        @entries << _
        _ = @entries[i]
        raise Kaitai::Struct::ValidationExprError.new(@entries[i], @_io, "/types/type_directory/seq/0") if not ( ((i != 0) && (!(_.is_terminator)))  ? _.body.name.body > entries[i - 1].body.name.body : true)
        i += 1
      end until _.is_terminator
      self
    end

    ##
    # A single entry within a directory, or the terminator, i.e. the `)`
    # token that ends the directory node.
    class DirEntry < Kaitai::Struct::Struct
      def initialize(_io, _parent = nil, _root = nil)
        super(_io, _parent, _root)
        _read
      end

      def _read
        @kind = PaddedStr.new(@_io, self, @_root)
        _ = @kind
        raise Kaitai::Struct::ValidationExprError.new(@kind, @_io, "/types/type_directory/types/dir_entry/seq/0") if not  ((_.body == "entry") || (_.body == ")")) 
        if !(is_terminator)
          @body = DirEntryBody.new(@_io, self, @_root)
        end
        self
      end
      def is_terminator
        return @is_terminator unless @is_terminator.nil?
        @is_terminator = kind.body == ")"
        @is_terminator
      end

      ##
      # Must be `entry` (for a child node) or `)` (for the terminator).
      attr_reader :kind

      ##
      # The entry itself. The terminator has no `body`.
      attr_reader :body
    end
    class DirEntryBody < Kaitai::Struct::Struct
      def initialize(_io, _parent = nil, _root = nil)
        super(_io, _parent, _root)
        _read
      end

      def _read
        @open_paren = PaddedStr.new(@_io, self, @_root)
        _ = @open_paren
        raise Kaitai::Struct::ValidationExprError.new(@open_paren, @_io, "/types/type_directory/types/dir_entry_body/seq/0") if not _.body == "("
        @name_key = PaddedStr.new(@_io, self, @_root)
        _ = @name_key
        raise Kaitai::Struct::ValidationExprError.new(@name_key, @_io, "/types/type_directory/types/dir_entry_body/seq/1") if not _.body == "name"
        @name = PaddedBytes.new(@_io, self, @_root)
        _ = @name
        raise Kaitai::Struct::ValidationExprError.new(@name, @_io, "/types/type_directory/types/dir_entry_body/seq/2") if not  ((_.body.size != 0) && (_.body.size <= 255) && (_.body != [46].pack('C*')) && (_.body != [46, 46].pack('C*')) && (_.body.bytes.min != 0)) 
        @node_key = PaddedStr.new(@_io, self, @_root)
        _ = @node_key
        raise Kaitai::Struct::ValidationExprError.new(@node_key, @_io, "/types/type_directory/types/dir_entry_body/seq/3") if not _.body == "node"
        @node = Node.new(@_io, self, @_root, _parent._parent._parent.depth + 1)
        @close_paren = PaddedStr.new(@_io, self, @_root)
        _ = @close_paren
        raise Kaitai::Struct::ValidationExprError.new(@close_paren, @_io, "/types/type_directory/types/dir_entry_body/seq/5") if not _.body == ")"
        self
      end
      attr_reader :open_paren
      attr_reader :name_key

      ##
      # Name of the entry, as raw bytes. Nix 2.36.0
      # [doesn't decode names as text](https://github.com/NixOS/nix/blob/88907193c54fcd5184cf59d14b693188e2875168/src/libutil/archive.cc#L245-L248)
      # either, and real NARs contain names that aren't valid UTF-8.
      # 
      # The name must be 1 to 255 bytes long, must not be `.` or `..`, and
      # must not contain a null byte. Nix also rejects names that contain
      # `/`, but this Kaitai Struct implementation doesn't check that: as
      # of KS 0.11, expressions can't search a byte array for a given
      # byte. A null byte can be detected anyway: 0 is the smallest
      # possible byte value, so a name contains a null byte exactly if its
      # smallest byte is 0.
      attr_reader :name
      attr_reader :node_key

      ##
      # The child node.
      attr_reader :node
      attr_reader :close_paren
    end
    attr_reader :entries
  end

  ##
  # A regular file node.
  class TypeRegular < Kaitai::Struct::Struct
    def initialize(_io, _parent = nil, _root = nil)
      super(_io, _parent, _root)
      _read
    end

    def _read
      @first_key = PaddedStr.new(@_io, self, @_root)
      _ = @first_key
      raise Kaitai::Struct::ValidationExprError.new(@first_key, @_io, "/types/type_regular/seq/0") if not  ((_.body == "executable") || (_.body == "contents")) 
      if is_executable
        @executable_val = PaddedStr.new(@_io, self, @_root)
        _ = @executable_val
        raise Kaitai::Struct::ValidationExprError.new(@executable_val, @_io, "/types/type_regular/seq/1") if not _.body == ""
      end
      if is_executable
        @contents_key = PaddedStr.new(@_io, self, @_root)
        _ = @contents_key
        raise Kaitai::Struct::ValidationExprError.new(@contents_key, @_io, "/types/type_regular/seq/2") if not _.body == "contents"
      end
      @file_data = FileContent.new(@_io, self, @_root)
      self
    end

    ##
    # The contents of the file, prefixed with their length and padded
    # with null bytes to the next 8-byte boundary.
    class FileContent < Kaitai::Struct::Struct
      def initialize(_io, _parent = nil, _root = nil)
        super(_io, _parent, _root)
        _read
      end

      def _read
        @len_contents = @_io.read_u8le
        if nar_offset < 0
          @_unnamed1 = @_io.read_bytes(0)
        end
        @contents = @_io.read_bytes(len_contents)
        @padding = @_io.read_bytes((8 - len_contents % 8) % 8)
        _ = @padding
        raise Kaitai::Struct::ValidationExprError.new(@padding, @_io, "/types/type_regular/types/file_content/seq/3") if not (_.size != 0 ? _.bytes.max == 0 : true)
        self
      end

      ##
      # 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.
      def nar_offset
        return @nar_offset unless @nar_offset.nil?
        @nar_offset = _io.pos
        @nar_offset
      end
      attr_reader :len_contents
      attr_reader :_unnamed1

      ##
      # This Kaitai Struct implementation keeps the contents of every
      # file in memory, so parsing a NAR needs at least as much memory
      # as all its files together.
      attr_reader :contents
      attr_reader :padding
    end

    ##
    # True if the file has the `executable` attribute.
    def is_executable
      return @is_executable unless @is_executable.nil?
      @is_executable = first_key.body == "executable"
      @is_executable
    end

    ##
    # Either `executable` or `contents`.
    attr_reader :first_key

    ##
    # Must be empty.
    attr_reader :executable_val
    attr_reader :contents_key
    attr_reader :file_data
  end

  ##
  # A symbolic link node.
  class TypeSymlink < Kaitai::Struct::Struct
    def initialize(_io, _parent = nil, _root = nil)
      super(_io, _parent, _root)
      _read
    end

    def _read
      @target_key = PaddedStr.new(@_io, self, @_root)
      _ = @target_key
      raise Kaitai::Struct::ValidationExprError.new(@target_key, @_io, "/types/type_symlink/seq/0") if not _.body == "target"
      @target_val = PaddedBytes.new(@_io, self, @_root)
      _ = @target_val
      raise Kaitai::Struct::ValidationExprError.new(@target_val, @_io, "/types/type_symlink/seq/1") if not  ((_.body.size != 0) && (_.body.size <= 4095) && (_.body.bytes.min != 0)) 
      self
    end

    ##
    # Must be `target`.
    attr_reader :target_key

    ##
    # The destination path of the symlink, as raw bytes. Nix 2.36.0
    # [doesn't decode targets as text](https://github.com/NixOS/nix/blob/88907193c54fcd5184cf59d14b693188e2875168/src/libutil/archive.cc#L280-L282)
    # either.
    # 
    # The target must be 1 to 4095 bytes long and must not contain a null
    # byte.
    attr_reader :target_val
  end

  ##
  # Magic string, must be `nix-archive-1`.
  attr_reader :magic

  ##
  # The root of the archive, which is always a single node.
  attr_reader :root_node
end