Nix Archive (NAR): Lua 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.

Lua source code to parse Nix Archive (NAR)

nix_nar.lua

-- This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild
--
-- This file is compatible with Lua 5.3

local class = require("class")
require("kaitaistruct")
local utils = require("utils")
local str_decode = require("string_decode")

-- 
-- 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 also: Git tag "2.36.0" (https://github.com/NixOS/nix/blob/88907193c54fcd5184cf59d14b693188e2875168/doc/manual/source/protocols/nix-archive/index.md)
NixNar = class.class(KaitaiStruct)

function NixNar:_init(io, parent, root)
  KaitaiStruct._init(self, io)
  self._parent = parent
  self._root = root or self
  self:_read()
end

function NixNar:_read()
  self.magic = NixNar.PaddedStr(self._io, self, self._root)
  local _ = self.magic
  if not(_.body == "nix-archive-1") then
    error("ValidationExprError")
  end
  self.root_node = NixNar.Node(0, self._io, self, self._root)
end

-- 
-- Magic string, must be `nix-archive-1`.
-- 
-- The root of the archive, which is always a single node.

-- 
-- A single file system node (regular file, directory, or symlink).
NixNar.Node = class.class(KaitaiStruct)

function NixNar.Node:_init(depth, io, parent, root)
  KaitaiStruct._init(self, io)
  self._parent = parent
  self._root = root
  self.depth = depth
  self:_read()
end

function NixNar.Node:_read()
  self._unnamed0 = self._io:read_bytes(0)
  local _ = self._unnamed0
  if not(self.depth < 64) then
    error("ValidationExprError")
  end
  self.open_paren = NixNar.PaddedStr(self._io, self, self._root)
  local _ = self.open_paren
  if not(_.body == "(") then
    error("ValidationExprError")
  end
  self.type_key = NixNar.PaddedStr(self._io, self, self._root)
  local _ = self.type_key
  if not(_.body == "type") then
    error("ValidationExprError")
  end
  self.type_val = NixNar.PaddedStr(self._io, self, self._root)
  local _ = self.type_val
  if not( ((_.body == "regular") or (_.body == "directory") or (_.body == "symlink")) ) then
    error("ValidationExprError")
  end
  local _on = self.type_val.body
  if _on == "directory" then
    self.body = NixNar.TypeDirectory(self._io, self, self._root)
  elseif _on == "regular" then
    self.body = NixNar.TypeRegular(self._io, self, self._root)
  elseif _on == "symlink" then
    self.body = NixNar.TypeSymlink(self._io, self, self._root)
  end
  if self.type_val.body ~= "directory" then
    self.close_paren = NixNar.PaddedStr(self._io, self, self._root)
    local _ = self.close_paren
    if not(_.body == ")") then
      error("ValidationExprError")
    end
  end
end

-- 
-- Must be `(`, a token starting the node definition.
-- 
-- Must be `type`.
-- 
-- Type of the node (`regular`, `directory`, or `symlink`).
-- 
-- 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`.
-- 
-- Nesting depth of the node. The root node has depth 0.

-- 
-- 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.
NixNar.PaddedBytes = class.class(KaitaiStruct)

function NixNar.PaddedBytes:_init(io, parent, root)
  KaitaiStruct._init(self, io)
  self._parent = parent
  self._root = root
  self:_read()
end

function NixNar.PaddedBytes:_read()
  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)
  local _ = self.padding
  if not(utils.box_unwrap((#_ ~= 0) and utils.box_wrap(utils.byte_array_max(_) == 0) or (true))) then
    error("ValidationExprError")
  end
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.
NixNar.PaddedStr = class.class(KaitaiStruct)

function NixNar.PaddedStr:_init(io, parent, root)
  KaitaiStruct._init(self, io)
  self._parent = parent
  self._root = root
  self:_read()
end

function NixNar.PaddedStr:_read()
  self.len_body = self._io:read_u8le()
  self.body = str_decode.decode(self._io:read_bytes(self.len_body), "ASCII")
  self.padding = self._io:read_bytes((8 - self.len_body % 8) % 8)
  local _ = self.padding
  if not(utils.box_unwrap((#_ ~= 0) and utils.box_wrap(utils.byte_array_max(_) == 0) or (true))) then
    error("ValidationExprError")
  end
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.
NixNar.TypeDirectory = class.class(KaitaiStruct)

function NixNar.TypeDirectory:_init(io, parent, root)
  KaitaiStruct._init(self, io)
  self._parent = parent
  self._root = root
  self:_read()
end

function NixNar.TypeDirectory:_read()
  self.entries = {}
  local i = 0
  while true do
    local _ = NixNar.TypeDirectory.DirEntry(self._io, self, self._root)
    self.entries[i + 1] = _
    local _ = self.entries[i + 1]
    if not(utils.box_unwrap(( ((i ~= 0) and (not(_.is_terminator))) ) and utils.box_wrap(_.body.name.body > self.entries[(i - 1) + 1].body.name.body) or (true))) then
      error("ValidationExprError")
    end
    if _.is_terminator then
      break
    end
    i = i + 1
  end
end


-- 
-- A single entry within a directory, or the terminator, i.e. the `)`
-- token that ends the directory node.
NixNar.TypeDirectory.DirEntry = class.class(KaitaiStruct)

function NixNar.TypeDirectory.DirEntry:_init(io, parent, root)
  KaitaiStruct._init(self, io)
  self._parent = parent
  self._root = root
  self:_read()
end

function NixNar.TypeDirectory.DirEntry:_read()
  self.kind = NixNar.PaddedStr(self._io, self, self._root)
  local _ = self.kind
  if not( ((_.body == "entry") or (_.body == ")")) ) then
    error("ValidationExprError")
  end
  if not(self.is_terminator) then
    self.body = NixNar.TypeDirectory.DirEntryBody(self._io, self, self._root)
  end
end

NixNar.TypeDirectory.DirEntry.property.is_terminator = {}
function NixNar.TypeDirectory.DirEntry.property.is_terminator:get()
  if self._m_is_terminator ~= nil then
    return self._m_is_terminator
  end

  self._m_is_terminator = self.kind.body == ")"
  return self._m_is_terminator
end

-- 
-- Must be `entry` (for a child node) or `)` (for the terminator).
-- 
-- The entry itself. The terminator has no `body`.

NixNar.TypeDirectory.DirEntryBody = class.class(KaitaiStruct)

function NixNar.TypeDirectory.DirEntryBody:_init(io, parent, root)
  KaitaiStruct._init(self, io)
  self._parent = parent
  self._root = root
  self:_read()
end

function NixNar.TypeDirectory.DirEntryBody:_read()
  self.open_paren = NixNar.PaddedStr(self._io, self, self._root)
  local _ = self.open_paren
  if not(_.body == "(") then
    error("ValidationExprError")
  end
  self.name_key = NixNar.PaddedStr(self._io, self, self._root)
  local _ = self.name_key
  if not(_.body == "name") then
    error("ValidationExprError")
  end
  self.name = NixNar.PaddedBytes(self._io, self, self._root)
  local _ = self.name
  if not( ((#_.body ~= 0) and (#_.body <= 255) and (_.body ~= "\046") and (_.body ~= "\046\046") and (utils.byte_array_min(_.body) ~= 0)) ) then
    error("ValidationExprError")
  end
  self.node_key = NixNar.PaddedStr(self._io, self, self._root)
  local _ = self.node_key
  if not(_.body == "node") then
    error("ValidationExprError")
  end
  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)
  local _ = self.close_paren
  if not(_.body == ")") then
    error("ValidationExprError")
  end
end

-- 
-- 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.
-- 
-- The child node.

-- 
-- A regular file node.
NixNar.TypeRegular = class.class(KaitaiStruct)

function NixNar.TypeRegular:_init(io, parent, root)
  KaitaiStruct._init(self, io)
  self._parent = parent
  self._root = root
  self:_read()
end

function NixNar.TypeRegular:_read()
  self.first_key = NixNar.PaddedStr(self._io, self, self._root)
  local _ = self.first_key
  if not( ((_.body == "executable") or (_.body == "contents")) ) then
    error("ValidationExprError")
  end
  if self.is_executable then
    self.executable_val = NixNar.PaddedStr(self._io, self, self._root)
    local _ = self.executable_val
    if not(_.body == "") then
      error("ValidationExprError")
    end
  end
  if self.is_executable then
    self.contents_key = NixNar.PaddedStr(self._io, self, self._root)
    local _ = self.contents_key
    if not(_.body == "contents") then
      error("ValidationExprError")
    end
  end
  self.file_data = NixNar.TypeRegular.FileContent(self._io, self, self._root)
end

-- 
-- True if the file has the `executable` attribute.
NixNar.TypeRegular.property.is_executable = {}
function NixNar.TypeRegular.property.is_executable:get()
  if self._m_is_executable ~= nil then
    return self._m_is_executable
  end

  self._m_is_executable = self.first_key.body == "executable"
  return self._m_is_executable
end

-- 
-- Either `executable` or `contents`.
-- 
-- Must be empty.

-- 
-- The contents of the file, prefixed with their length and padded
-- with null bytes to the next 8-byte boundary.
NixNar.TypeRegular.FileContent = class.class(KaitaiStruct)

function NixNar.TypeRegular.FileContent:_init(io, parent, root)
  KaitaiStruct._init(self, io)
  self._parent = parent
  self._root = root
  self:_read()
end

function NixNar.TypeRegular.FileContent:_read()
  self.len_contents = self._io:read_u8le()
  if self.nar_offset < 0 then
    self._unnamed1 = self._io:read_bytes(0)
  end
  self.contents = self._io:read_bytes(self.len_contents)
  self.padding = self._io:read_bytes((8 - self.len_contents % 8) % 8)
  local _ = self.padding
  if not(utils.box_unwrap((#_ ~= 0) and utils.box_wrap(utils.byte_array_max(_) == 0) or (true))) then
    error("ValidationExprError")
  end
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.
NixNar.TypeRegular.FileContent.property.nar_offset = {}
function NixNar.TypeRegular.FileContent.property.nar_offset:get()
  if self._m_nar_offset ~= nil then
    return self._m_nar_offset
  end

  self._m_nar_offset = self._io:pos()
  return self._m_nar_offset
end

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

-- 
-- A symbolic link node.
NixNar.TypeSymlink = class.class(KaitaiStruct)

function NixNar.TypeSymlink:_init(io, parent, root)
  KaitaiStruct._init(self, io)
  self._parent = parent
  self._root = root
  self:_read()
end

function NixNar.TypeSymlink:_read()
  self.target_key = NixNar.PaddedStr(self._io, self, self._root)
  local _ = self.target_key
  if not(_.body == "target") then
    error("ValidationExprError")
  end
  self.target_val = NixNar.PaddedBytes(self._io, self, self._root)
  local _ = self.target_val
  if not( ((#_.body ~= 0) and (#_.body <= 4095) and (utils.byte_array_min(_.body) ~= 0)) ) then
    error("ValidationExprError")
  end
end

-- 
-- Must be `target`.
-- 
-- 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.