aboutsummaryrefslogtreecommitdiff
#define _XOPEN_SOURCE 600

#include "config.h"

#include <cerrno>
#include <algorithm>
#include <vector>
#include <map>

#include <strings.h> // for strcasecmp

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <fcntl.h>

#include "archive.hh"
#include "util.hh"


namespace nix {

static string archiveVersion1 = "nix-archive-1";

static string caseHackSuffix = "~nix~case~hack~";

PathFilter defaultPathFilter;


static void dumpContents(const Path & path, size_t size,
    Sink & sink)
{
    writeString("contents", sink);
    writeLongLong(size, sink);

    AutoCloseFD fd = open(path.c_str(), O_RDONLY);
    if (fd == -1) throw SysError(format("opening file `%1%'") % path);

    unsigned char buf[65536];
    size_t left = size;

    while (left > 0) {
        size_t n = left > sizeof(buf) ? sizeof(buf) : left;
        readFull(fd, buf, n);
        left -= n;
        sink(buf, n);
    }

    writePadding(size, sink);
}


static void dump(const Path & path, Sink & sink, PathFilter & filter)
{
    struct stat st;
    if (lstat(path.c_str(), &st))
        throw SysError(format("getting attributes of path `%1%'") % path);

    writeString("(", sink);

    if (S_ISREG(st.st_mode)) {
        writeString("type", sink);
        writeString("regular", sink);
        if (st.st_mode & S_IXUSR) {
            writeString("executable", sink);
            writeString("", sink);
        }
        dumpContents(path, (size_t) st.st_size, sink);
    }

    else if (S_ISDIR(st.st_mode)) {
        writeString("type", sink);
        writeString("directory", sink);

        /* If we're on a case-insensitive system like Mac OS X, undo
           the case hack applied by restorePath(). */
        std::map<string, string> unhacked;
        for (auto & i : readDirectory(path))
	    unhacked[i.name] = i.name;

        for (auto & i : unhacked)
            if (filter(path + "/" + i.first)) {
                writeString("entry", sink);
                writeString("(", sink);
                writeString("name", sink);
                writeString(i.first, sink);
                writeString("node", sink);
                dump(path + "/" + i.second, sink, filter);
                writeString(")", sink);
            }
    }

    else if (S_ISLNK(st.st_mode)) {
        writeString("type", sink);
        writeString("symlink", sink);
        writeString("target", sink);
        writeString(readLink(path), sink);
    }

    else throw Error(format("file `%1%' has an unsupported type") % path);

    writeString(")", sink);
}


void dumpPath(const Path & path, Sink & sink, PathFilter & filter)
{
    writeString(archiveVersion1, sink);
    dump(path, sink, filter);
}


static SerialisationError badArchive(string s)
{
    return SerialisationError("bad archive: " + s);
}


#if 0
static void skipGeneric(Source & source)
{
    if (readString(source) == "(") {
        while (readString(source) != ")")
            skipGeneric(source);
    }
}
#endif


static void parseContents(ParseSink & sink, Source & source, const Path & path)
{
    unsigned long long size = readLongLong(source);

    sink.preallocateContents(size);

    unsigned long long left = size;
    unsigned char buf[65536];

    while (left) {
        checkInterrupt();
        unsigned int n = sizeof(buf);
        if ((unsigned long long) n > left) n = left;
        source(buf, n);
        sink.receiveContents(buf, n);
        left -= n;
    }

    readPadding(size, source);
}


struct CaseInsensitiveCompare
{
    bool operator() (const string & a, const string & b) const
    {
        return strcasecmp(a.c_str(), b.c_str()) < 0;
    }
};


static void parse(ParseSink & sink, Source & source, const Path & path)
{
    string s;

    s = readString(source);
    if (s != "(") throw badArchive("expected open tag");

    enum { tpUnknown, tpRegular, tpDirectory, tpSymlink } type = tpUnknown;

    std::map<Path, int, CaseInsensitiveCompare> names;

    while (1) {
        checkInterrupt();

        s = readString(source);

        if (s == ")") {
            break;
        }

        else if (s == "type") {
            if (type != tpUnknown)
                throw badArchive("multiple type fields");
            string t = readString(source);

            if (t == "regular") {
                type = tpRegular;
                sink.createRegularFile(path);
            }

            else if (t == "directory") {
                sink.createDirectory(path);
                type = tpDirectory;
            }

            else if (t == "symlink") {
                type = tpSymlink;
            }

            else throw badArchive("unknown file type " + t);

        }

        else if (s == "contents" && type == tpRegular) {
            parseContents(sink, source, path);
        }

        else if (s == "executable" && type == tpRegular) {
            readString(source);
            sink.isExecutable();
        }

        else if (s == "entry" && type == tpDirectory) {
            string name, prevName;

            s = readString(source);
            if (s != "(") throw badArchive("expected open tag");

            while (1) {
                checkInterrupt();

                s = readString(source);

                if (s == ")") {
                    break;
                } else if (s == "name") {
                    name = readString(source);
                    if (name.empty() || name == "." || name == ".." || name.find('/') != string::npos || name.find((char) 0) != string::npos)
                        throw Error(format("NAR contains invalid file name `%1%'") % name);
                    if (name <= prevName)
                        throw Error("NAR directory is not sorted");
                    prevName = name;
                } else if (s == "node") {
                    if (s.empty()) throw badArchive("entry name missing");
                    parse(sink, source, path + "/" + name);
                } else
                    throw badArchive("unknown field " + s);
            }
        }

        else if (s == "target" && type == tpSymlink) {
            string target = readString(source);
            sink.createSymlink(path, target);
        }

        else
            throw badArchive("unknown field " + s);
    }
}


void parseDump(ParseSink & sink, Source & source)
{
    string version;
    try {
        version = readString(source);
    } catch (SerialisationError & e) {
        /* This generally means the integer at the start couldn't be
           decoded.  Ignore and throw the exception below. */
    }
    if (version != archiveVersion1)
        throw badArchive("input doesn't look like a normalized archive");
    parse(sink, source, "");
}


struct RestoreSink : ParseSink
{
    Path dstPath;
    AutoCloseFD fd;

    void createDirectory(const Path & path)
    {
        Path p = dstPath + path;
        if (mkdir(p.c_str(), 0777) == -1)
            throw SysError(format("creating directory `%1%'") % p);
    };

    void createRegularFile(const Path & path)
    {
        Path p = dstPath + path;
        fd.close();
        fd = open(p.c_str(), O_CREAT | O_EXCL | O_WRONLY, 0666);
        if (fd == -1) throw SysError(format("creating file `%1%'") % p);
    }

    void isExecutable()
    {
        struct stat st;
        if (fstat(fd, &st) == -1)
            throw SysError("fstat");
        if (fchmod(fd, st.st_mode | (S_IXUSR | S_IXGRP | S_IXOTH)) == -1)
            throw SysError("fchmod");
    }

    void preallocateContents(unsigned long long len)
    {
#if HAVE_POSIX_FALLOCATE
        if (len) {
            errno = posix_fallocate(fd, 0, len);
            /* Note that EINVAL may indicate that the underlying
               filesystem doesn't support preallocation (e.g. on
               OpenSolaris).  Since preallocation is just an
               optimisation, ignore it. */
            if (errno && errno != EINVAL)
                throw SysError(format("preallocating file of %1% bytes") % len);
        }
#endif
    }

    void receiveContents(unsigned char * data, unsigned int len)
    {
        writeFull(fd, data, len);
    }

    void createSymlink(const Path & path, const string & target)
    {
        Path p = dstPath + path;
        nix::createSymlink(target, p);
    }
};


void restorePath(const Path & path, Source & source)
{
    RestoreSink sink;
    sink.dstPath = path;
    parseDump(sink, source);
}


}
2018-10-22Merge branch 'master' into core-updatesMarius Bakke 2018-10-22gnu: Add GN....* gnu/packages/build-tools.scm (gn): New public variable. Marius Bakke 2018-09-09gnu: meson: Update to 0.47.2....* gnu/packages/build-tools.scm (meson): Update to 0.47.2. Marius Bakke 2018-08-13Merge branch 'staging' into core-updatesRicardo Wurmus 2018-08-10gnu: meson: Update to 0.47.1....* gnu/packages/build-tools.scm (meson): Update to 0.47.1. * gnu/packages/patches/meson-for-build-rpath.patch: Adjust. Ricardo Wurmus 2018-08-10Merge branch 'master' into stagingMarius Bakke 2018-08-10gnu: bear: Update to 2.3.12....* gnu/packages/build-tools.scm (bear): Update to 2.3.12. Tobias Geerinckx-Rice 2018-08-10gnu: bear: Don't use unstable tarball....* gnu/packages/build-tools.scm (bear)[source]: Use GIT-FETCH and GIT-FILE-NAME. Tobias Geerinckx-Rice 2018-07-28gnu: meson: Update to 0.47.1....* gnu/packages/build-tools.scm (meson): Update to 0.47.1. * gnu/packages/patches/meson-for-build-rpath.patch: Adjust to file rename and indendation change. Marius Bakke 2018-06-11Merge branch 'master' into stagingMarius Bakke 2018-06-11gnu: meson: Update to 0.46.1....* gnu/packages/build-tools.scm (meson): Update to 0.46.1. Marius Bakke 2018-05-31gnu: bear: Fix python path....* gnu/packages/build-tools.scm (bear) [inputs]: Add python-wrapper. Signed-off-by: Ludovic Courtès <ludo@gnu.org> Fis Trivial 2018-04-30gnu: meson: Update to 0.46.0....* gnu/packages/build-tools.scm (meson): Update to 0.46.0. * gnu/packages/patches/meson-for-build-rpath.patch: Adapt. Marius Bakke 2018-04-25Merge branch 'master' into stagingMarius Bakke 2018-04-21gnu: Add osc.... * gnu/packages/build-tools.scm (osc): New variable. Tomáš Čech 2018-04-16Merge branch 'master' into stagingMarius Bakke 2018-04-08gnu: Add bear....* gnu/packages/build-tools.scm (bear): New public variable. Signed-off-by: Ludovic Courtès <ludo@gnu.org> Fis Trivial 2018-03-22gnu: meson: Update to 0.45.1....* gnu/packages/build-tools.scm (meson): Update to 0.45.1. Marius Bakke 2018-03-18Merge branch 'master' into stagingMarius Bakke 2018-03-17gnu: Fix common unquote typos....It's easy to mistype ‘("foo" foo)’ as ‘("foo", foo)’ (which also works). Fix such typos for the proper edification of our young. * gnu/packages/android.scm: Move unquotes to their operands. * gnu/packages/bootloaders.scm: Likewise. * gnu/packages/build-tools.scm: Likewise. * gnu/packages/chemistry.scm: Likewise. * gnu/packages/compression.scm: Likewise. * gnu/packages/connman.scm: Likewise. * gnu/packages/django.scm: Likewise. * gnu/packages/emulators.scm: Likewise. * gnu/packages/engineering.scm: Likewise. * gnu/packages/file-systems.scm: Likewise. * gnu/packages/freedesktop.scm: Likewise. * gnu/packages/games.scm: Likewise. * gnu/packages/gimp.scm: Likewise. * gnu/packages/gl.scm: Likewise. * gnu/packages/gnome.scm: Likewise. * gnu/packages/graphics.scm: Likewise. * gnu/packages/haskell.scm: Likewise. * gnu/packages/irc.scm: Likewise. * gnu/packages/julia.scm: Likewise. * gnu/packages/kde-frameworks.scm: Likewise. * gnu/packages/linux.scm: Likewise. * gnu/packages/lua.scm: Likewise. * gnu/packages/mail.scm: Likewise. * gnu/packages/make-bootstrap.scm: Likewise. * gnu/packages/messaging.scm: Likewise. * gnu/packages/music.scm: Likewise. * gnu/packages/networking.scm: Likewise. * gnu/packages/ocaml.scm: Likewise. * gnu/packages/perl.scm: Likewise. * gnu/packages/python.scm: Likewise. * gnu/packages/python-web.scm: Likewise. * gnu/packages/qt.scm: Likewise. * gnu/packages/ratpoison.scm: Likewise. * gnu/packages/sdl.scm: Likewise. * gnu/packages/sml.scm: Likewise. * gnu/packages/terminals.scm: Likewise. * gnu/packages/text-editors.scm: Likewise. * gnu/packages/video.scm: Likewise. * gnu/packages/virtualization.scm: Likewise. * gnu/packages/vulkan.scm: Likewise. * gnu/packages/wget.scm: Likewise. * gnu/packages/wine.scm: Likewise. * gnu/packages/wm.scm: Likewise. * gnu/packages/xdisorg.scm: Likewise. * gnu/packages/xml.scm: Likewise. * gnu/packages/xorg.scm: Likewise. Tobias Geerinckx-Rice 2018-03-12gnu: meson: Update to 0.45.0....* gnu/packages/build-tools.scm (meson): Update to 0.45.0. [arguments]: Explicitly disable tests (they were skipped before). Marius Bakke 2018-03-12gnu: meson-for-build: Update to 0.44.0....* gnu/packages/build-tools.scm (meson-for-build)[version]: Remove field. [source]: Inherit from MESON. Marius Bakke 2018-03-12gnu: meson: Don't wrap the meson executable....* gnu/packages/build-tools.scm (meson)[arguments]: Delete WRAP-PHASE. Marius Bakke 2018-03-07gnu: meson: Mark up description....* gnu/packages/build-tools.scm (meson)[description]: Use @dfn. Tobias Geerinckx-Rice 2017-12-12gnu: meson: Update to 0.44.0....* gnu/packages/build-tools.scm (meson): Update to 0.44.0 Tobias Geerinckx-Rice 2017-10-13gnu: meson: Update to 0.43.0....* gnu/packages/build-tools.scm (meson): Update to 0.43.0. Ricardo Wurmus