diff options
35 files changed, 864 insertions, 263 deletions
diff --git a/doc/manual/command-ref/conf-file.xml b/doc/manual/command-ref/conf-file.xml index 6b90083f0873..fb4d8cefc4d2 100644 --- a/doc/manual/command-ref/conf-file.xml +++ b/doc/manual/command-ref/conf-file.xml @@ -563,7 +563,8 @@ password <replaceable>my-password</replaceable> <para>If set to <literal>true</literal>, the Nix evaluator will not allow access to any files outside of the Nix search path (as set via the <envar>NIX_PATH</envar> environment variable or the - <option>-I</option> option). The default is + <option>-I</option> option), or to URIs outside of + <option>allowed-uri</option>. The default is <literal>false</literal>.</para> </listitem> @@ -571,6 +572,21 @@ password <replaceable>my-password</replaceable> </varlistentry> + <varlistentry xml:id="conf-allowed-uris"><term><literal>allowed-uris</literal></term> + + <listitem> + + <para>A list of URI prefixes to which access is allowed in + restricted evaluation mode. For example, when set to + <literal>https://github.com/NixOS</literal>, builtin functions + such as <function>fetchGit</function> are allowed to access + <literal>https://github.com/NixOS/patchelf.git</literal>.</para> + + </listitem> + + </varlistentry> + + <varlistentry xml:id="conf-pre-build-hook"><term><literal>pre-build-hook</literal></term> <listitem> diff --git a/doc/manual/expressions/builtins.xml b/doc/manual/expressions/builtins.xml index 615314880aba..5e88b88561fc 100644 --- a/doc/manual/expressions/builtins.xml +++ b/doc/manual/expressions/builtins.xml @@ -264,13 +264,13 @@ stdenv.mkDerivation { … } Note that when obtaining the hash with <varname>nix-prefetch-url </varname> the option <varname>--unpack</varname> is required. - </para> - - <para>This function can also verify the contents against a hash. - In that case, the function takes a set instead of a URL. The set + </para> + + <para>This function can also verify the contents against a hash. + In that case, the function takes a set instead of a URL. The set requires the attribute <varname>url</varname> and the attribute <varname>sha256</varname>, e.g. - + <programlisting> with import (fetchTarball { url = https://github.com/NixOS/nixpkgs-channels/archive/nixos-14.12.tar.gz; @@ -279,7 +279,7 @@ with import (fetchTarball { stdenv.mkDerivation { … } </programlisting> - + </para> <para>This function is not available if <link @@ -600,6 +600,16 @@ x: x + 456</programlisting> </varlistentry> + <varlistentry><term><function>builtins.isFloat</function> + <replaceable>e</replaceable></term> + + <listitem><para>Return <literal>true</literal> if + <replaceable>e</replaceable> evaluates to a float, and + <literal>false</literal> otherwise.</para></listitem> + + </varlistentry> + + <varlistentry><term><function>builtins.isBool</function> <replaceable>e</replaceable></term> @@ -1245,8 +1255,9 @@ stdenv.mkDerivation (rec { <replaceable>e</replaceable>, namely <literal>"int"</literal>, <literal>"bool"</literal>, <literal>"string"</literal>, <literal>"path"</literal>, <literal>"null"</literal>, - <literal>"set"</literal>, <literal>"list"</literal> or - <literal>"lambda"</literal>.</para></listitem> + <literal>"set"</literal>, <literal>"list"</literal>, + <literal>"lambda"</literal> or + <literal>"float"</literal>.</para></listitem> </varlistentry> diff --git a/doc/manual/expressions/language-constructs.xml b/doc/manual/expressions/language-constructs.xml index fe69dba837a1..2f0027d479cd 100644 --- a/doc/manual/expressions/language-constructs.xml +++ b/doc/manual/expressions/language-constructs.xml @@ -333,7 +333,20 @@ with (import ./definitions.nix); ...</programlisting> makes all attributes defined in the file <filename>definitions.nix</filename> available as if they were defined -locally in a <literal>rec</literal>-expression.</para> +locally in a <literal>let</literal>-expression.</para> + +<para>The bindings introduced by <literal>with</literal> do not shadow bindings +introduced by other means, e.g. + +<programlisting> +let a = 3; in with { a = 1; }; let a = 4; in with { a = 2; }; ...</programlisting> + +establishes the same scope as + +<programlisting> +let a = 1; in let a = 2; in let a = 3; in let a = 4; in ...</programlisting> + +</para> </simplesect> diff --git a/doc/manual/expressions/language-operators.xml b/doc/manual/expressions/language-operators.xml index a3323ced4c50..f1f75093461b 100644 --- a/doc/manual/expressions/language-operators.xml +++ b/doc/manual/expressions/language-operators.xml @@ -41,6 +41,11 @@ weakest binding).</para> argument <replaceable>e2</replaceable>.</entry> </row> <row> + <entry><literal>-</literal> <replaceable>e</replaceable></entry> + <entry>none</entry> + <entry>Arithmetic negation.</entry> + </row> + <row> <entry><replaceable>e</replaceable> <literal>?</literal> <replaceable>attrpath</replaceable></entry> <entry>none</entry> @@ -55,13 +60,24 @@ weakest binding).</para> <entry>List concatenation.</entry> </row> <row> - <entry><replaceable>e1</replaceable> <literal>+</literal> <replaceable>e2</replaceable></entry> + <entry> + <replaceable>e1</replaceable> <literal>*</literal> <replaceable>e2</replaceable>, + <replaceable>e1</replaceable> <literal>/</literal> <replaceable>e2</replaceable> + </entry> <entry>left</entry> - <entry>String or path concatenation.</entry> + <entry>Arithmetic multiplication and division.</entry> </row> <row> - <entry><literal>!</literal> <replaceable>e</replaceable></entry> + <entry> + <replaceable>e1</replaceable> <literal>+</literal> <replaceable>e2</replaceable>, + <replaceable>e1</replaceable> <literal>-</literal> <replaceable>e2</replaceable> + </entry> <entry>left</entry> + <entry>Arithmetic addition and subtraction. String or path concatenation (only by <literal>+</literal>).</entry> + </row> + <row> + <entry><literal>!</literal> <replaceable>e</replaceable></entry> + <entry>none</entry> <entry>Boolean negation.</entry> </row> <row> @@ -75,16 +91,22 @@ weakest binding).</para> attributes).</entry> </row> <row> - <entry><replaceable>e1</replaceable> <literal>==</literal> - <replaceable>e2</replaceable></entry> + <entry> + <replaceable>e1</replaceable> <literal><</literal> <replaceable>e2</replaceable>, + <replaceable>e1</replaceable> <literal>></literal> <replaceable>e2</replaceable>, + <replaceable>e1</replaceable> <literal><=</literal> <replaceable>e2</replaceable>, + <replaceable>e1</replaceable> <literal>>=</literal> <replaceable>e2</replaceable> + </entry> <entry>none</entry> - <entry>Equality.</entry> + <entry>Arithmetic comparison.</entry> </row> <row> - <entry><replaceable>e1</replaceable> <literal>!=</literal> - <replaceable>e2</replaceable></entry> + <entry> + <replaceable>e1</replaceable> <literal>==</literal> <replaceable>e2</replaceable>, + <replaceable>e1</replaceable> <literal>!=</literal> <replaceable>e2</replaceable> + </entry> <entry>none</entry> - <entry>Inequality.</entry> + <entry>Equality and inequality.</entry> </row> <row> <entry><replaceable>e1</replaceable> <literal>&&</literal> diff --git a/doc/manual/expressions/language-values.xml b/doc/manual/expressions/language-values.xml index 67da688a4fc5..bb2090c881fd 100644 --- a/doc/manual/expressions/language-values.xml +++ b/doc/manual/expressions/language-values.xml @@ -98,13 +98,17 @@ configureFlags = " <para>Since <literal>${</literal> and <literal>''</literal> have special meaning in indented strings, you need a way to quote them. - <literal>${</literal> can be escaped by prefixing it with + <literal>$</literal> can be escaped by prefixing it with <literal>''</literal> (that is, two single quotes), i.e., - <literal>''${</literal>. <literal>''</literal> can be escaped by + <literal>''$</literal>. <literal>''</literal> can be escaped by prefixing it with <literal>'</literal>, i.e., - <literal>'''</literal>. Finally, linefeed, carriage-return and - tab characters can be written as <literal>''\n</literal>, - <literal>''\r</literal>, <literal>''\t</literal>.</para> + <literal>'''</literal>. <literal>$</literal> removes any special meaning + from the following <literal>$</literal>. Linefeed, carriage-return and tab + characters can be written as <literal>''\n</literal>, + <literal>''\r</literal>, <literal>''\t</literal>, and <literal>''\</literal> + escapes any other character. + + </para> <para>Indented strings are primarily useful in that they allow multi-line string literals to follow the indentation of the diff --git a/doc/manual/release-notes/rl-1.12.xml b/doc/manual/release-notes/rl-1.12.xml index adfbaa157f22..29943e3e6e97 100644 --- a/doc/manual/release-notes/rl-1.12.xml +++ b/doc/manual/release-notes/rl-1.12.xml @@ -184,18 +184,11 @@ </listitem> <listitem> - <para><function>builtins.fetchgit</function>. + <para><function>builtins.fetchGit</function>. (38539b943a060d9cdfc24d6e5d997c0885b8aa2f)</para> </listitem> <listitem> - <para>Git repositories can now be specified in the Nix search - path, - e.g. <literal>nixpkgs=git://github.com/NixOS/nixpkgs</literal>. - (d8bf0d4859e28ddd23401fbe89f4e528aa09ddb3)</para> - </listitem> - - <listitem> <para><literal><nix/fetchurl.nix></literal> now uses the content-addressable tarball cache at <uri>http://tarballs.nixos.org/</uri>, just like @@ -223,8 +216,7 @@ <para><function>builtins.fetchurl</function> and <function>builtins.fetchTarball</function> now support <varname>sha256</varname> and <varname>name</varname> - attributes. Using these functions is now allowed in restricted - mode if a hash is supplied.</para> + attributes.</para> </listitem> <listitem> @@ -419,6 +411,14 @@ configureFlags = "--prefix=${placeholder "out"} --includedir=${placeholder "dev" through the MELPA package repository.</para> </listitem> + <listitem> + <para>In restricted evaluation mode + (<option>--restrict-eval</option>), builtin functions that + download from the network (such as <function>fetchGit</function>) + are permitted to fetch underneath the list of URI prefixes + specified in the option <option>allowed-uris</option>.</para> + </listitem> + </itemizedlist> <para>This release has contributions from TBD.</para> diff --git a/release.nix b/release.nix index a98199258842..aa4d63777ebe 100644 --- a/release.nix +++ b/release.nix @@ -77,6 +77,9 @@ let bzip2 xz brotli openssl pkgconfig sqlite boehmgc + # Tests + git + mercurial ] ++ lib.optional stdenv.isLinux libseccomp ++ lib.optional (stdenv.isLinux || stdenv.isDarwin) libsodium diff --git a/shell.nix b/shell.nix index 2b4d0dd201e7..f47952582fce 100644 --- a/shell.nix +++ b/shell.nix @@ -23,6 +23,10 @@ with import ./release-common.nix { inherit pkgs; }; # For nix-perl perl perlPackages.DBDSQLite + + # Tests + git + mercurial ] ++ lib.optional stdenv.isLinux libseccomp; diff --git a/src/libexpr/common-eval-args.hh b/src/libexpr/common-eval-args.hh index 09fa406b2cdc..be7fda783783 100644 --- a/src/libexpr/common-eval-args.hh +++ b/src/libexpr/common-eval-args.hh @@ -6,7 +6,7 @@ namespace nix { class Store; class EvalState; -struct Bindings; +class Bindings; struct MixEvalArgs : virtual Args { diff --git a/src/libexpr/eval.cc b/src/libexpr/eval.cc index 78f6b0010523..63de2d60a147 100644 --- a/src/libexpr/eval.cc +++ b/src/libexpr/eval.cc @@ -149,7 +149,7 @@ string showType(const Value & v) switch (v.type) { case tInt: return "an integer"; case tBool: return "a boolean"; - case tString: return "a string"; + case tString: return v.string.context ? "a string with context" : "a string"; case tPath: return "a path"; case tNull: return "null"; case tAttrs: return "a set"; @@ -355,6 +355,26 @@ Path EvalState::checkSourcePath(const Path & path_) } +void EvalState::checkURI(const std::string & uri) +{ + if (!restricted) return; + + /* 'uri' should be equal to a prefix, or in a subdirectory of a + prefix. Thus, the prefix https://github.co does not permit + access to https://github.com. Note: this allows 'http://' and + 'https://' as prefixes for any http/https URI. */ + for (auto & prefix : settings.allowedUris.get()) + if (uri == prefix || + (uri.size() > prefix.size() + && prefix.size() > 0 + && hasPrefix(uri, prefix) + && (prefix[prefix.size() - 1] == '/' || uri[prefix.size()] == '/'))) + return; + + throw RestrictedPathError("access to URI '%s' is forbidden in restricted mode", uri); +} + + void EvalState::addConstant(const string & name, Value & v) { Value * v2 = allocValue(); diff --git a/src/libexpr/eval.hh b/src/libexpr/eval.hh index 04a36b14cefa..f0ab1435bff3 100644 --- a/src/libexpr/eval.hh +++ b/src/libexpr/eval.hh @@ -110,6 +110,8 @@ public: Path checkSourcePath(const Path & path); + void checkURI(const std::string & uri); + /* Parse a Nix expression from the specified file. */ Expr * parseExprFromFile(const Path & path); Expr * parseExprFromFile(const Path & path, StaticEnv & staticEnv); diff --git a/src/libexpr/lexer.l b/src/libexpr/lexer.l index 28a0a6a87896..828356bbf447 100644 --- a/src/libexpr/lexer.l +++ b/src/libexpr/lexer.l @@ -90,7 +90,7 @@ FLOAT (([1-9][0-9]*\.[0-9]*)|(0?\.[0-9]+))([Ee][+-]?[0-9]+)? PATH [a-zA-Z0-9\.\_\-\+]*(\/[a-zA-Z0-9\.\_\-\+]+)+\/? HPATH \~(\/[a-zA-Z0-9\.\_\-\+]+)+\/? SPATH \<[a-zA-Z0-9\.\_\-\+]+(\/[a-zA-Z0-9\.\_\-\+]+)*\> -URI [a-zA-Z][a-zA-Z0-9\+\-\.]*\:[a-zA-Z0-9\%\/\?\:\@\&\=\+\$\,\-\_\.\!\~\*\']+ +URI [a-zA-Z][a-zA-Z0-9\+\-\.]*\:\/\/[a-zA-Z0-9\%\/\?\:\@\&\=\+\$\,\-\_\.\!\~\*\']+|channel\:[a-zA-Z0-9\%\/\?\:\@\&\=\+\$\,\-\_\.\!\~\*\']+ %% diff --git a/src/libexpr/parser.y b/src/libexpr/parser.y index 669312bb7cff..ef11dd609217 100644 --- a/src/libexpr/parser.y +++ b/src/libexpr/parser.y @@ -523,7 +523,6 @@ formal #include "eval.hh" #include "download.hh" #include "store-api.hh" -#include "primops/fetchgit.hh" namespace nix { @@ -665,11 +664,7 @@ std::pair<bool, std::string> EvalState::resolveSearchPathElem(const SearchPathEl if (isUri(elem.second)) { try { - if (hasPrefix(elem.second, "git://") || hasSuffix(elem.second, ".git")) - // FIXME: support specifying revision/branch - res = { true, exportGit(store, elem.second, "master") }; - else - res = { true, getDownloader()->downloadCached(store, elem.second, true) }; + res = { true, getDownloader()->downloadCached(store, elem.second, true) }; } catch (DownloadError & e) { printError(format("warning: Nix search path entry '%1%' cannot be downloaded, ignoring") % elem.second); res = { false, "" }; diff --git a/src/libexpr/primops.cc b/src/libexpr/primops.cc index 6a50c99345e4..e3b5dfb420b4 100644 --- a/src/libexpr/primops.cc +++ b/src/libexpr/primops.cc @@ -1009,22 +1009,21 @@ static void prim_toFile(EvalState & state, const Pos & pos, Value * * args, Valu } -struct FilterFromExpr : PathFilter +static void prim_filterSource(EvalState & state, const Pos & pos, Value * * args, Value & v) { - EvalState & state; - Value & filter; - Pos pos; + PathSet context; + Path path = state.coerceToPath(pos, *args[1], context); + if (!context.empty()) + throw EvalError(format("string '%1%' cannot refer to other paths, at %2%") % path % pos); - FilterFromExpr(EvalState & state, Value & filter, const Pos & pos) - : state(state), filter(filter), pos(pos) - { - } + state.forceValue(*args[0]); + if (args[0]->type != tLambda) + throw TypeError(format("first argument in call to 'filterSource' is not a function but %1%, at %2%") % showType(*args[0]) % pos); - bool operator () (const Path & path) - { - struct stat st; - if (lstat(path.c_str(), &st)) - throw SysError(format("getting attributes of path '%1%'") % path); + path = state.checkSourcePath(path); + + PathFilter filter = [&](const Path & path) { + auto st = lstat(path); /* Call the filter function. The first argument is the path, the second is a string indicating the type of the file. */ @@ -1032,7 +1031,7 @@ struct FilterFromExpr : PathFilter mkString(arg1, path); Value fun2; - state.callFunction(filter, arg1, fun2, noPos); + state.callFunction(*args[0], arg1, fun2, noPos); Value arg2; mkString(arg2, @@ -1045,24 +1044,7 @@ struct FilterFromExpr : PathFilter state.callFunction(fun2, arg2, res, noPos); return state.forceBool(res, pos); - } -}; - - -static void prim_filterSource(EvalState & state, const Pos & pos, Value * * args, Value & v) -{ - PathSet context; - Path path = state.coerceToPath(pos, *args[1], context); - if (!context.empty()) - throw EvalError(format("string '%1%' cannot refer to other paths, at %2%") % path % pos); - - state.forceValue(*args[0]); - if (args[0]->type != tLambda) - throw TypeError(format("first argument in call to 'filterSource' is not a function but %1%, at %2%") % showType(*args[0]) % pos); - - FilterFromExpr filter(state, *args[0], pos); - - path = state.checkSourcePath(path); + }; Path dstPath = settings.readOnlyMode ? state.store->computeStorePathForPath(path, true, htSHA256, filter).first @@ -1907,11 +1889,11 @@ static void prim_compareVersions(EvalState & state, const Pos & pos, Value * * a void fetch(EvalState & state, const Pos & pos, Value * * args, Value & v, - const string & who, bool unpack) + const string & who, bool unpack, const std::string & defaultName) { string url; Hash expectedHash; - string name; + string name = defaultName; state.forceValue(*args[0]); @@ -1937,8 +1919,7 @@ void fetch(EvalState & state, const Pos & pos, Value * * args, Value & v, } else url = state.forceStringNoCtx(*args[0], pos); - if (state.restricted && !expectedHash) - throw Error(format("'%1%' is not allowed in restricted mode") % who); + state.checkURI(url); Path res = getDownloader()->downloadCached(state.store, url, unpack, name, expectedHash); mkString(v, res, PathSet({res})); @@ -1947,13 +1928,13 @@ void fetch(EvalState & state, const Pos & pos, Value * * args, Value & v, static void prim_fetchurl(EvalState & state, const Pos & pos, Value * * args, Value & v) { - fetch(state, pos, args, v, "fetchurl", false); + fetch(state, pos, args, v, "fetchurl", false, ""); } static void prim_fetchTarball(EvalState & state, const Pos & pos, Value * * args, Value & v) { - fetch(state, pos, args, v, "fetchTarball", true); + fetch(state, pos, args, v, "fetchTarball", true, "source"); } diff --git a/src/libexpr/primops/fetchGit.cc b/src/libexpr/primops/fetchGit.cc new file mode 100644 index 000000000000..bca68ed72091 --- /dev/null +++ b/src/libexpr/primops/fetchGit.cc @@ -0,0 +1,223 @@ +#include "primops.hh" +#include "eval-inline.hh" +#include "download.hh" +#include "store-api.hh" +#include "pathlocks.hh" + +#include <sys/time.h> + +#include <regex> + +#include <nlohmann/json.hpp> + +using namespace std::string_literals; + +namespace nix { + +struct GitInfo +{ + Path storePath; + std::string rev; + std::string shortRev; + uint64_t revCount = 0; +}; + +GitInfo exportGit(ref<Store> store, const std::string & uri, + std::experimental::optional<std::string> ref, const std::string & rev, + const std::string & name) +{ + if (!ref && rev == "" && hasPrefix(uri, "/") && pathExists(uri + "/.git")) { + + bool clean = true; + + try { + runProgram("git", true, { "-C", uri, "diff-index", "--quiet", "HEAD", "--" }); + } catch (ExecError e) { + if (!WIFEXITED(e.status) || WEXITSTATUS(e.status) != 1) throw; + clean = false; + } + + if (!clean) { + + /* This is an unclean working tree. So copy all tracked + files. */ + + GitInfo gitInfo; + gitInfo.rev = "0000000000000000000000000000000000000000"; + gitInfo.shortRev = std::string(gitInfo.rev, 0, 7); + + auto files = tokenizeString<std::set<std::string>>( + runProgram("git", true, { "-C", uri, "ls-files", "-z" }), "\0"s); + + PathFilter filter = [&](const Path & p) -> bool { + assert(hasPrefix(p, uri)); + std::string file(p, uri.size() + 1); + + auto st = lstat(p); + + if (S_ISDIR(st.st_mode)) { + auto i = files.lower_bound(file); + return i != files.end() && hasPrefix(*i, file); + } + + return files.count(file); + }; + + gitInfo.storePath = store->addToStore("source", uri, true, htSHA256, filter); + + return gitInfo; + } + } + + if (!ref) ref = "master"s; + + if (rev != "") { + std::regex revRegex("^[0-9a-fA-F]{40}$"); + if (!std::regex_match(rev, revRegex)) + throw Error("invalid Git revision '%s'", rev); + } + + Path cacheDir = getCacheDir() + "/nix/git"; + + if (!pathExists(cacheDir)) { + createDirs(cacheDir); + runProgram("git", true, { "init", "--bare", cacheDir }); + } + + std::string localRef = hashString(htSHA256, fmt("%s-%s", uri, *ref)).to_string(Base32, false); + + Path localRefFile = cacheDir + "/refs/heads/" + localRef; + + /* If the local ref is older than ‘tarball-ttl’ seconds, do a git + fetch to update the local ref to the remote ref. */ + time_t now = time(0); + struct stat st; + if (stat(localRefFile.c_str(), &st) != 0 || + st.st_mtime <= now - settings.tarballTtl) + { + if (rev == "" || + chomp(runProgram( + RunOptions("git", { "-C", cacheDir, "cat-file", "-t", rev }) + .killStderr(true)).second) != "commit") + { + Activity act(*logger, lvlTalkative, actUnknown, fmt("fetching Git repository '%s'", uri)); + + // FIXME: git stderr messes up our progress indicator, so + // we're using --quiet for now. Should process its stderr. + runProgram("git", true, { "-C", cacheDir, "fetch", "--quiet", "--force", "--", uri, *ref + ":" + localRef }); + + struct timeval times[2]; + times[0].tv_sec = now; + times[0].tv_usec = 0; + times[1].tv_sec = now; + times[1].tv_usec = 0; + + utimes(localRefFile.c_str(), times); + } + } + + // FIXME: check whether rev is an ancestor of ref. + GitInfo gitInfo; + gitInfo.rev = rev != "" ? rev : chomp(readFile(localRefFile)); + gitInfo.shortRev = std::string(gitInfo.rev, 0, 7); + + printTalkative("using revision %s of repo '%s'", uri, gitInfo.rev); + + std::string storeLinkName = hashString(htSHA512, name + std::string("\0"s) + gitInfo.rev).to_string(Base32, false); + Path storeLink = cacheDir + "/" + storeLinkName + ".link"; + PathLocks storeLinkLock({storeLink}, fmt("waiting for lock on '%1%'...", storeLink)); // FIXME: broken + + try { + auto json = nlohmann::json::parse(readFile(storeLink)); + + assert(json["name"] == name && json["rev"] == gitInfo.rev); + + gitInfo.storePath = json["storePath"]; + + if (store->isValidPath(gitInfo.storePath)) { + gitInfo.revCount = json["revCount"]; + return gitInfo; + } + + } catch (SysError & e) { + if (e.errNo != ENOENT) throw; + } + + // FIXME: should pipe this, or find some better way to extract a + // revision. + auto tar = runProgram("git", true, { "-C", cacheDir, "archive", gitInfo.rev }); + + Path tmpDir = createTempDir(); + AutoDelete delTmpDir(tmpDir, true); + + runProgram("tar", true, { "x", "-C", tmpDir }, tar); + + gitInfo.storePath = store->addToStore(name, tmpDir); + + gitInfo.revCount = std::stoull(runProgram("git", true, { "-C", cacheDir, "rev-list", "--count", gitInfo.rev })); + + nlohmann::json json; + json["storePath"] = gitInfo.storePath; + json["uri"] = uri; + json["name"] = name; + json["rev"] = gitInfo.rev; + json["revCount"] = gitInfo.revCount; + + writeFile(storeLink, json.dump()); + + return gitInfo; +} + +static void prim_fetchGit(EvalState & state, const Pos & pos, Value * * args, Value & v) +{ + std::string url; + std::experimental::optional<std::string> ref; + std::string rev; + std::string name = "source"; + PathSet context; + + state.forceValue(*args[0]); + + if (args[0]->type == tAttrs) { + + state.forceAttrs(*args[0], pos); + + for (auto & attr : *args[0]->attrs) { + string n(attr.name); + if (n == "url") + url = state.coerceToString(*attr.pos, *attr.value, context, false, false); + else if (n == "ref") + ref = state.forceStringNoCtx(*attr.value, *attr.pos); + else if (n == "rev") + rev = state.forceStringNoCtx(*attr.value, *attr.pos); + else if (n == "name") + name = state.forceStringNoCtx(*attr.value, *attr.pos); + else + throw EvalError("unsupported argument '%s' to 'fetchGit', at %s", attr.name, *attr.pos); + } + + if (url.empty()) + throw EvalError(format("'url' argument required, at %1%") % pos); + + } else + url = state.coerceToString(pos, *args[0], context, false, false); + + if (!isUri(url)) url = absPath(url); + + // FIXME: git externals probably can be used to bypass the URI + // whitelist. Ah well. + state.checkURI(url); + + auto gitInfo = exportGit(state.store, url, ref, rev, name); + + state.mkAttrs(v, 8); + mkString(*state.allocAttr(v, state.sOutPath), gitInfo.storePath, PathSet({gitInfo.storePath})); + mkString(*state.allocAttr(v, state.symbols.create("rev")), gitInfo.rev); + mkString(*state.allocAttr(v, state.symbols.create("shortRev")), gitInfo.shortRev); + mkInt(*state.allocAttr(v, state.symbols.create("revCount")), gitInfo.revCount); + v.attrs->sort(); +} + +static RegisterPrimOp r("fetchGit", 1, prim_fetchGit); + +} diff --git a/src/libexpr/primops/fetchMercurial.cc b/src/libexpr/primops/fetchMercurial.cc new file mode 100644 index 000000000000..7def7103bf3d --- /dev/null +++ b/src/libexpr/primops/fetchMercurial.cc @@ -0,0 +1,202 @@ +#include "primops.hh" +#include "eval-inline.hh" +#include "download.hh" +#include "store-api.hh" +#include "pathlocks.hh" + +#include <sys/time.h> + +#include <regex> + +#include <nlohmann/json.hpp> + +using namespace std::string_literals; + +namespace nix { + +struct HgInfo +{ + Path storePath; + std::string branch; + std::string rev; + uint64_t revCount = 0; +}; + +std::regex commitHashRegex("^[0-9a-fA-F]{40}$"); + +HgInfo exportMercurial(ref<Store> store, const std::string & uri, + std::string rev, const std::string & name) +{ + if (rev == "" && hasPrefix(uri, "/") && pathExists(uri + "/.hg")) { + + bool clean = runProgram("hg", true, { "status", "-R", uri, "--modified", "--added", "--removed" }) == ""; + + if (!clean) { + + /* This is an unclean working tree. So copy all tracked + files. */ + + printTalkative("copying unclean Mercurial working tree '%s'", uri); + + HgInfo hgInfo; + hgInfo.rev = "0000000000000000000000000000000000000000"; + hgInfo.branch = chomp(runProgram("hg", true, { "branch", "-R", uri })); + + auto files = tokenizeString<std::set<std::string>>( + runProgram("hg", true, { "status", "-R", uri, "--clean", "--modified", "--added", "--no-status", "--print0" }), "\0"s); + + PathFilter filter = [&](const Path & p) -> bool { + assert(hasPrefix(p, uri)); + std::string file(p, uri.size() + 1); + + auto st = lstat(p); + + if (S_ISDIR(st.st_mode)) { + auto i = files.lower_bound(file); + return i != files.end() && hasPrefix(*i, file); + } + + return files.count(file); + }; + + hgInfo.storePath = store->addToStore("source", uri, true, htSHA256, filter); + + return hgInfo; + } + } + + if (rev == "") rev = "default"; + + Path cacheDir = fmt("%s/nix/hg/%s", getCacheDir(), hashString(htSHA256, uri).to_string(Base32, false)); + + Path stampFile = fmt("%s/.hg/%s.stamp", cacheDir, hashString(htSHA512, rev).to_string(Base32, false)); + + /* If we haven't pulled this repo less than ‘tarball-ttl’ seconds, + do so now. */ + time_t now = time(0); + struct stat st; + if (stat(stampFile.c_str(), &st) != 0 || + st.st_mtime <= now - settings.tarballTtl) + { + /* Except that if this is a commit hash that we already have, + we don't have to pull again. */ + if (!(std::regex_match(rev, commitHashRegex) + && pathExists(cacheDir) + && runProgram( + RunOptions("hg", { "log", "-R", cacheDir, "-r", rev, "--template", "1" }) + .killStderr(true)).second == "1")) + { + Activity act(*logger, lvlTalkative, actUnknown, fmt("fetching Mercurial repository '%s'", uri)); + + if (pathExists(cacheDir)) { + runProgram("hg", true, { "pull", "-R", cacheDir, "--", uri }); + } else { + createDirs(dirOf(cacheDir)); + runProgram("hg", true, { "clone", "--noupdate", "--", uri, cacheDir }); + } + } + + writeFile(stampFile, ""); + } + + auto tokens = tokenizeString<std::vector<std::string>>( + runProgram("hg", true, { "log", "-R", cacheDir, "-r", rev, "--template", "{node} {rev} {branch}" })); + assert(tokens.size() == 3); + + HgInfo hgInfo; + hgInfo.rev = tokens[0]; + hgInfo.revCount = std::stoull(tokens[1]); + hgInfo.branch = tokens[2]; + + std::string storeLinkName = hashString(htSHA512, name + std::string("\0"s) + hgInfo.rev).to_string(Base32, false); + Path storeLink = fmt("%s/.hg/%s.link", cacheDir, storeLinkName); + + try { + auto json = nlohmann::json::parse(readFile(storeLink)); + + assert(json["name"] == name && json["rev"] == hgInfo.rev); + + hgInfo.storePath = json["storePath"]; + + if (store->isValidPath(hgInfo.storePath)) { + printTalkative("using cached Mercurial store path '%s'", hgInfo.storePath); + return hgInfo; + } + + } catch (SysError & e) { + if (e.errNo != ENOENT) throw; + } + + Path tmpDir = createTempDir(); + AutoDelete delTmpDir(tmpDir, true); + + runProgram("hg", true, { "archive", "-R", cacheDir, "-r", rev, tmpDir }); + + deletePath(tmpDir + "/.hg_archival.txt"); + + hgInfo.storePath = store->addToStore(name, tmpDir); + + nlohmann::json json; + json["storePath"] = hgInfo.storePath; + json["uri"] = uri; + json["name"] = name; + json["branch"] = hgInfo.branch; + json["rev"] = hgInfo.rev; + json["revCount"] = hgInfo.revCount; + + writeFile(storeLink, json.dump()); + + return hgInfo; +} + +static void prim_fetchMercurial(EvalState & state, const Pos & pos, Value * * args, Value & v) +{ + std::string url; + std::string rev; + std::string name = "source"; + PathSet context; + + state.forceValue(*args[0]); + + if (args[0]->type == tAttrs) { + + state.forceAttrs(*args[0], pos); + + for (auto & attr : *args[0]->attrs) { + string n(attr.name); + if (n == "url") + url = state.coerceToString(*attr.pos, *attr.value, context, false, false); + else if (n == "rev") + rev = state.forceStringNoCtx(*attr.value, *attr.pos); + else if (n == "name") + name = state.forceStringNoCtx(*attr.value, *attr.pos); + else + throw EvalError("unsupported argument '%s' to 'fetchMercurial', at %s", attr.name, *attr.pos); + } + + if (url.empty()) + throw EvalError(format("'url' argument required, at %1%") % pos); + + } else + url = state.coerceToString(pos, *args[0], context, false, false); + + if (!isUri(url)) url = absPath(url); + + // FIXME: git externals probably can be used to bypass the URI + // whitelist. Ah well. + state.checkURI(url); + + auto hgInfo = exportMercurial(state.store, url, rev, name); + + state.mkAttrs(v, 8); + mkString(*state.allocAttr(v, state.sOutPath), hgInfo.storePath, PathSet({hgInfo.storePath})); + mkString(*state.allocAttr(v, state.symbols.create("branch")), hgInfo.branch); + mkString(*state.allocAttr(v, state.symbols.create("rev")), hgInfo.rev); + mkString(*state.allocAttr(v, state.symbols.create("shortRev")), std::string(hgInfo.rev, 0, 12)); + mkInt(*state.allocAttr(v, state.symbols.create("revCount")), hgInfo.revCount); + v.attrs->sort(); +} + +static RegisterPrimOp r("fetchMercurial", 1, prim_fetchMercurial); + +} diff --git a/src/libexpr/primops/fetchgit.cc b/src/libexpr/primops/fetchgit.cc deleted file mode 100644 index 9db4adbc9da2..000000000000 --- a/src/libexpr/primops/fetchgit.cc +++ /dev/null @@ -1,129 +0,0 @@ -#include "primops.hh" -#include "eval-inline.hh" -#include "download.hh" -#include "store-api.hh" -#include "pathlocks.hh" - -#include <sys/time.h> - -#include <regex> - -namespace nix { - -Path exportGit(ref<Store> store, const std::string & uri, - const std::string & ref, const std::string & rev) -{ - if (rev != "") { - std::regex revRegex("^[0-9a-fA-F]{40}$"); - if (!std::regex_match(rev, revRegex)) - throw Error("invalid Git revision '%s'", rev); - } - - Path cacheDir = getCacheDir() + "/nix/git"; - - if (!pathExists(cacheDir)) { - createDirs(cacheDir); - runProgram("git", true, { "init", "--bare", cacheDir }); - } - - //Activity act(*logger, lvlInfo, format("fetching Git repository '%s'") % uri); - - std::string localRef = hashString(htSHA256, fmt("%s-%s", uri, ref)).to_string(Base32, false); - - Path localRefFile = cacheDir + "/refs/heads/" + localRef; - - /* If the local ref is older than ‘tarball-ttl’ seconds, do a git - fetch to update the local ref to the remote ref. */ - time_t now = time(0); - struct stat st; - if (stat(localRefFile.c_str(), &st) != 0 || - st.st_mtime < now - settings.tarballTtl) - { - runProgram("git", true, { "-C", cacheDir, "fetch", "--force", "--", uri, ref + ":" + localRef }); - - struct timeval times[2]; - times[0].tv_sec = now; - times[0].tv_usec = 0; - times[1].tv_sec = now; - times[1].tv_usec = 0; - - utimes(localRefFile.c_str(), times); - } - - // FIXME: check whether rev is an ancestor of ref. - std::string commitHash = - rev != "" ? rev : chomp(readFile(localRefFile)); - - printTalkative("using revision %s of repo '%s'", uri, commitHash); - - Path storeLink = cacheDir + "/" + commitHash + ".link"; - PathLocks storeLinkLock({storeLink}, fmt("waiting for lock on '%1%'...", storeLink)); - - if (pathExists(storeLink)) { - auto storePath = readLink(storeLink); - store->addTempRoot(storePath); - if (store->isValidPath(storePath)) { - return storePath; - } - } - - // FIXME: should pipe this, or find some better way to extract a - // revision. - auto tar = runProgram("git", true, { "-C", cacheDir, "archive", commitHash }); - - Path tmpDir = createTempDir(); - AutoDelete delTmpDir(tmpDir, true); - - runProgram("tar", true, { "x", "-C", tmpDir }, tar); - - auto storePath = store->addToStore("git-export", tmpDir); - - replaceSymlink(storePath, storeLink); - - return storePath; -} - -static void prim_fetchgit(EvalState & state, const Pos & pos, Value * * args, Value & v) -{ - // FIXME: cut&paste from fetch(). - if (state.restricted) throw Error("'fetchgit' is not allowed in restricted mode"); - - std::string url; - std::string ref = "master"; - std::string rev; - - state.forceValue(*args[0]); - - if (args[0]->type == tAttrs) { - - state.forceAttrs(*args[0], pos); - - for (auto & attr : *args[0]->attrs) { - string name(attr.name); - if (name == "url") { - PathSet context; - url = state.coerceToString(*attr.pos, *attr.value, context, false, false); - if (hasPrefix(url, "/")) url = "file://" + url; - } - else if (name == "ref") - ref = state.forceStringNoCtx(*attr.value, *attr.pos); - else if (name == "rev") - rev = state.forceStringNoCtx(*attr.value, *attr.pos); - else - throw EvalError("unsupported argument '%s' to 'fetchgit', at %s", attr.name, *attr.pos); - } - - if (url.empty()) - throw EvalError(format("'url' argument required, at %1%") % pos); - - } else - url = state.forceStringNoCtx(*args[0], pos); - - Path storePath = exportGit(state.store, url, ref, rev); - - mkString(v, storePath, PathSet({storePath})); -} - -static RegisterPrimOp r("__fetchgit", 1, prim_fetchgit); - -} diff --git a/src/libexpr/primops/fetchgit.hh b/src/libexpr/primops/fetchgit.hh deleted file mode 100644 index ff228f3b3c6a..000000000000 --- a/src/libexpr/primops/fetchgit.hh +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include <string> - -#include "ref.hh" - -namespace nix { - -class Store; - -Path exportGit(ref<Store> store, const std::string & uri, - const std::string & ref, const std::string & rev = ""); - -} diff --git a/src/libstore/build.cc b/src/libstore/build.cc index 9f8edc826a04..061682377257 100644 --- a/src/libstore/build.cc +++ b/src/libstore/build.cc @@ -2833,10 +2833,10 @@ void DerivationGoal::runChild() sandboxProfile += "(deny default (with no-log))\n"; } - sandboxProfile += "(import \"sandbox-defaults.sb\")"; + sandboxProfile += "(import \"sandbox-defaults.sb\")\n"; if (fixedOutput) - sandboxProfile += "(import \"sandbox-network.sb\")"; + sandboxProfile += "(import \"sandbox-network.sb\")\n"; /* Our rwx outputs */ sandboxProfile += "(allow file-read* file-write* process-exec\n"; @@ -2879,7 +2879,7 @@ void DerivationGoal::runChild() sandboxProfile += additionalSandboxProfile; } else - sandboxProfile += "(import \"sandbox-minimal.sb\")"; + sandboxProfile += "(import \"sandbox-minimal.sb\")\n"; debug("Generated sandbox profile:"); debug(sandboxProfile); @@ -2888,6 +2888,8 @@ void DerivationGoal::runChild() writeFile(sandboxFile, sandboxProfile); + bool allowLocalNetworking = get(drv->env, "__darwinAllowLocalNetworking") == "1"; + /* The tmpDir in scope points at the temporary build directory for our derivation. Some packages try different mechanisms to find temporary directories, so we want to open up a broader place for them to dump their files, if needed. */ Path globalTmpDir = canonPath(getEnv("TMPDIR", "/tmp"), true); @@ -2903,6 +2905,10 @@ void DerivationGoal::runChild() args.push_back("_GLOBAL_TMP_DIR=" + globalTmpDir); args.push_back("-D"); args.push_back("IMPORT_DIR=" + settings.nixDataDir + "/nix/sandbox/"); + if (allowLocalNetworking) { + args.push_back("-D"); + args.push_back(string("_ALLOW_LOCAL_NETWORKING=1")); + } args.push_back(drv->builder); } #endif diff --git a/src/libstore/download.cc b/src/libstore/download.cc index 608b8fd399b4..70f9b1f5eacb 100644 --- a/src/libstore/download.cc +++ b/src/libstore/download.cc @@ -23,6 +23,8 @@ #include <cmath> #include <random> +using namespace std::string_literals; + namespace nix { double getTime() @@ -604,7 +606,7 @@ Path Downloader::downloadCached(ref<Store> store, const string & url_, bool unpa Path cacheDir = getCacheDir() + "/nix/tarballs"; createDirs(cacheDir); - string urlHash = hashString(htSHA256, url).to_string(Base32, false); + string urlHash = hashString(htSHA256, name + std::string("\0"s) + url).to_string(Base32, false); Path dataFile = cacheDir + "/" + urlHash + ".info"; Path fileLink = cacheDir + "/" + urlHash + "-file"; @@ -705,7 +707,7 @@ bool isUri(const string & s) size_t pos = s.find("://"); if (pos == string::npos) return false; string scheme(s, 0, pos); - return scheme == "http" || scheme == "https" || scheme == "file" || scheme == "channel" || scheme == "git" || scheme == "s3"; + return scheme == "http" || scheme == "https" || scheme == "file" || scheme == "channel" || scheme == "git" || scheme == "s3" || scheme == "ssh"; } diff --git a/src/libstore/globals.hh b/src/libstore/globals.hh index 880527322794..a4aa842d70fd 100644 --- a/src/libstore/globals.hh +++ b/src/libstore/globals.hh @@ -225,7 +225,7 @@ public: Setting<bool> restrictEval{this, false, "restrict-eval", "Whether to restrict file system access to paths in $NIX_PATH, " - "and to disallow fetching files from the network."}; + "and network access to the URI prefixes listed in 'allowed-uris'."}; Setting<size_t> buildRepeat{this, 0, "repeat", "The number of times to repeat a build in order to verify determinism.", @@ -271,7 +271,7 @@ public: "Number of parallel HTTP connections.", {"binary-caches-parallel-connections"}}; - Setting<bool> enableHttp2{this, true, "enable-http2", + Setting<bool> enableHttp2{this, true, "http2", "Whether to enable HTTP/2 support."}; Setting<unsigned int> tarballTtl{this, 60 * 60, "tarball-ttl", @@ -353,6 +353,8 @@ public: Setting<uint64_t> maxFree{this, std::numeric_limits<uint64_t>::max(), "max-free", "Stop deleting garbage when free disk space is above the specified amount."}; + Setting<Strings> allowedUris{this, {}, "allowed-uris", + "Prefixes of URIs that builtin functions such as fetchurl and fetchGit are allowed to fetch."}; }; diff --git a/src/libstore/s3-binary-cache-store.cc b/src/libstore/s3-binary-cache-store.cc index 5fc7371a5198..6a0f19238add 100644 --- a/src/libstore/s3-binary-cache-store.cc +++ b/src/libstore/s3-binary-cache-store.cc @@ -241,8 +241,8 @@ struct S3BinaryCacheStoreImpl : public S3BinaryCacheStore auto & error = res.GetError(); if (error.GetErrorType() == Aws::S3::S3Errors::RESOURCE_NOT_FOUND || error.GetErrorType() == Aws::S3::S3Errors::NO_SUCH_KEY - || (error.GetErrorType() == Aws::S3::S3Errors::UNKNOWN // FIXME - && error.GetMessage().find("404") != std::string::npos)) + // If bucket listing is disabled, 404s turn into 403s + || error.GetErrorType() == Aws::S3::S3Errors::ACCESS_DENIED) return false; throw Error(format("AWS error fetching '%s': %s") % path % error.GetMessage()); } diff --git a/src/libstore/sandbox-defaults.sb b/src/libstore/sandbox-defaults.sb index d63c8f813c9e..c8436d9866c5 100644 --- a/src/libstore/sandbox-defaults.sb +++ b/src/libstore/sandbox-defaults.sb @@ -21,6 +21,9 @@ ; Allow sending signals within the sandbox. (allow signal (target same-sandbox)) +; Allow getpwuid. +(allow mach-lookup (global-name "com.apple.system.opendirectoryd.libinfo")) + ; Access to /tmp. (allow file* process-exec (literal "/tmp") (subpath TMPDIR)) @@ -30,6 +33,29 @@ ; Without this line clang cannot write to /dev/null, breaking some configure tests. (allow file-read-metadata (literal "/dev")) +; Many packages like to do local networking in their test suites, but let's only +; allow it if the package explicitly asks for it. +(if (param "_ALLOW_LOCAL_NETWORKING") + (begin + (allow network* (local ip) (local tcp) (local udp)) + + ; Allow access to /etc/resolv.conf (which is a symlink to + ; /private/var/run/resolv.conf). + ; TODO: deduplicate with sandbox-network.sb + (allow file-read-metadata + (literal "/var") + (literal "/etc") + (literal "/etc/resolv.conf") + (literal "/private/etc/resolv.conf")) + + (allow file-read* + (literal "/private/var/run/resolv.conf")) + + ; Allow DNS lookups. This is even needed for localhost, which lots of tests rely on + (allow file-read-metadata (literal "/etc/hosts")) + (allow file-read* (literal "/private/etc/hosts")) + (allow network-outbound (remote unix-socket (path-literal "/private/var/run/mDNSResponder"))))) + ; Standard devices. (allow file* (literal "/dev/null") @@ -54,5 +80,4 @@ (allow file-read-metadata (literal "/etc") (literal "/var") - (literal "/private/var/tmp") - ) + (literal "/private/var/tmp")) diff --git a/src/libutil/archive.cc b/src/libutil/archive.cc index ea1deb924e67..f71229d8fdd6 100644 --- a/src/libutil/archive.cc +++ b/src/libutil/archive.cc @@ -29,7 +29,7 @@ const std::string narVersionMagic1 = "nix-archive-1"; static string caseHackSuffix = "~nix~case~hack~"; -PathFilter defaultPathFilter; +PathFilter defaultPathFilter = [](const Path &) { return true; }; static void dumpContents(const Path & path, size_t size, diff --git a/src/libutil/archive.hh b/src/libutil/archive.hh index 607ebf8b28f9..8a15e849c7b8 100644 --- a/src/libutil/archive.hh +++ b/src/libutil/archive.hh @@ -44,13 +44,6 @@ namespace nix { `+' denotes string concatenation. */ -struct PathFilter -{ - virtual ~PathFilter() { } - virtual bool operator () (const Path & path) { return true; } -}; - -extern PathFilter defaultPathFilter; void dumpPath(const Path & path, Sink & sink, PathFilter & filter = defaultPathFilter); diff --git a/src/libutil/hash.hh b/src/libutil/hash.hh index d83049b02368..fd7a61df8e46 100644 --- a/src/libutil/hash.hh +++ b/src/libutil/hash.hh @@ -93,8 +93,6 @@ Hash hashFile(HashType ht, const Path & path); /* Compute the hash of the given path. The hash is defined as (essentially) hashString(ht, dumpPath(path)). */ -struct PathFilter; -extern PathFilter defaultPathFilter; typedef std::pair<Hash, unsigned long long> HashResult; HashResult hashPath(HashType ht, const Path & path, PathFilter & filter = defaultPathFilter); diff --git a/src/libutil/util.cc b/src/libutil/util.cc index 9346d5dc4cf8..f56153cd4a8a 100644 --- a/src/libutil/util.cc +++ b/src/libutil/util.cc @@ -896,31 +896,45 @@ std::vector<char *> stringsToCharPtrs(const Strings & ss) string runProgram(Path program, bool searchPath, const Strings & args, const std::experimental::optional<std::string> & input) { + RunOptions opts(program, args); + opts.searchPath = searchPath; + opts.input = input; + + auto res = runProgram(opts); + + if (!statusOk(res.first)) + throw ExecError(res.first, fmt("program '%1%' %2%", program, statusToString(res.first))); + + return res.second; +} + +std::pair<int, std::string> runProgram(const RunOptions & options) +{ checkInterrupt(); /* Create a pipe. */ Pipe out, in; out.create(); - if (input) in.create(); + if (options.input) in.create(); /* Fork. */ Pid pid = startProcess([&]() { if (dup2(out.writeSide.get(), STDOUT_FILENO) == -1) throw SysError("dupping stdout"); - if (input && dup2(in.readSide.get(), STDIN_FILENO) == -1) + if (options.input && dup2(in.readSide.get(), STDIN_FILENO) == -1) throw SysError("dupping stdin"); - Strings args_(args); - args_.push_front(program); + Strings args_(options.args); + args_.push_front(options.program); restoreSignals(); - if (searchPath) - execvp(program.c_str(), stringsToCharPtrs(args_).data()); + if (options.searchPath) + execvp(options.program.c_str(), stringsToCharPtrs(args_).data()); else - execv(program.c_str(), stringsToCharPtrs(args_).data()); + execv(options.program.c_str(), stringsToCharPtrs(args_).data()); - throw SysError(format("executing '%1%'") % program); + throw SysError("executing '%1%'", options.program); }); out.writeSide = -1; @@ -935,11 +949,11 @@ string runProgram(Path program, bool searchPath, const Strings & args, }); - if (input) { + if (options.input) { in.readSide = -1; writerThread = std::thread([&]() { try { - writeFull(in.writeSide.get(), *input); + writeFull(in.writeSide.get(), *options.input); promise.set_value(); } catch (...) { promise.set_exception(std::current_exception()); @@ -952,14 +966,11 @@ string runProgram(Path program, bool searchPath, const Strings & args, /* Wait for the child to finish. */ int status = pid.wait(); - if (!statusOk(status)) - throw ExecError(status, format("program '%1%' %2%") - % program % statusToString(status)); /* Wait for the writer thread to finish. */ - if (input) promise.get_future().get(); + if (options.input) promise.get_future().get(); - return result; + return {status, result}; } diff --git a/src/libutil/util.hh b/src/libutil/util.hh index fccf5d854800..a3494e09b09b 100644 --- a/src/libutil/util.hh +++ b/src/libutil/util.hh @@ -245,6 +245,23 @@ string runProgram(Path program, bool searchPath = false, const Strings & args = Strings(), const std::experimental::optional<std::string> & input = {}); +struct RunOptions +{ + Path program; + bool searchPath = true; + Strings args; + std::experimental::optional<std::string> input; + bool _killStderr = false; + + RunOptions(const Path & program, const Strings & args) + : program(program), args(args) { }; + + RunOptions & killStderr(bool v) { _killStderr = true; return *this; } +}; + +std::pair<int, std::string> runProgram(const RunOptions & options); + + class ExecError : public Error { public: @@ -481,4 +498,10 @@ struct MaintainCount std::pair<unsigned short, unsigned short> getWindowSize(); +/* Used in various places. */ +typedef std::function<bool(const Path & path)> PathFilter; + +extern PathFilter defaultPathFilter; + + } diff --git a/src/nix-build/nix-build.cc b/src/nix-build/nix-build.cc index 8e56e5a46b19..21b0a18dd887 100755 --- a/src/nix-build/nix-build.cc +++ b/src/nix-build/nix-build.cc @@ -167,6 +167,9 @@ void mainWrapped(int argc, char * * argv) buildMode = bmRepair; } + else if (*arg == "--hash") + buildMode = bmHash; + else if (*arg == "--run-env") // obsolete runEnv = true; diff --git a/tests/fetchGit.sh b/tests/fetchGit.sh new file mode 100644 index 000000000000..a967380cd5b2 --- /dev/null +++ b/tests/fetchGit.sh @@ -0,0 +1,86 @@ +source common.sh + +if [[ -z $(type -p git) ]]; then + echo "Git not installed; skipping Git tests" + exit 0 +fi + +clearStore + +repo=$TEST_ROOT/git + +rm -rf $repo ${repo}-tmp $TEST_HOME/.cache/nix/git + +git init $repo +git -C $repo config user.email "foobar@example.com" +git -C $repo config user.name "Foobar" + +echo utrecht > $repo/hello +git -C $repo add hello +git -C $repo commit -m 'Bla1' +rev1=$(git -C $repo rev-parse HEAD) + +echo world > $repo/hello +git -C $repo commit -m 'Bla2' -a +rev2=$(git -C $repo rev-parse HEAD) + +# Fetch the default branch. +path=$(nix eval --raw "(builtins.fetchGit file://$repo).outPath") +[[ $(cat $path/hello) = world ]] + +# Fetch using an explicit revision hash. +path2=$(nix eval --raw "(builtins.fetchGit { url = file://$repo; rev = \"$rev2\"; }).outPath") +[[ $path = $path2 ]] + +# Fetch again. This should be cached. +mv $repo ${repo}-tmp +path2=$(nix eval --raw "(builtins.fetchGit file://$repo).outPath") +[[ $path = $path2 ]] + +[[ $(nix eval "(builtins.fetchGit file://$repo).revCount") = 2 ]] +[[ $(nix eval --raw "(builtins.fetchGit file://$repo).rev") = $rev2 ]] + +# But with TTL 0, it should fail. +(! nix eval --tarball-ttl 0 "(builtins.fetchGit file://$repo)" -vvvvv) + +# Fetching with a explicit hash should succeed. +path2=$(nix eval --tarball-ttl 0 --raw "(builtins.fetchGit { url = file://$repo; rev = \"$rev2\"; }).outPath") +[[ $path = $path2 ]] + +path2=$(nix eval --tarball-ttl 0 --raw "(builtins.fetchGit { url = file://$repo; rev = \"$rev1\"; }).outPath") +[[ $(cat $path2/hello) = utrecht ]] + +mv ${repo}-tmp $repo + +# Using a clean working tree should produce the same result. +path2=$(nix eval --raw "(builtins.fetchGit $repo).outPath") +[[ $path = $path2 ]] + +# Using an unclean tree should yield the tracked but uncommitted changes. +mkdir $repo/dir1 $repo/dir2 +echo foo > $repo/dir1/foo +echo bar > $repo/bar +echo bar > $repo/dir2/bar +git -C $repo add dir1/foo +git -C $repo rm hello + +path2=$(nix eval --raw "(builtins.fetchGit $repo).outPath") +[ ! -e $path2/hello ] +[ ! -e $path2/bar ] +[ ! -e $path2/dir2/bar ] +[[ $(cat $path2/dir1/foo) = foo ]] + +[[ $(nix eval --raw "(builtins.fetchGit $repo).rev") = 0000000000000000000000000000000000000000 ]] + +# ... unless we're using an explicit ref or rev. +path3=$(nix eval --raw "(builtins.fetchGit { url = $repo; ref = \"master\"; }).outPath") +[[ $path = $path3 ]] + +path3=$(nix eval --raw "(builtins.fetchGit { url = $repo; rev = \"$rev2\"; }).outPath") +[[ $path = $path3 ]] + +# Committing should not affect the store path. +git -C $repo commit -m 'Bla3' -a + +path4=$(nix eval --tarball-ttl 0 --raw "(builtins.fetchGit file://$repo).outPath") +[[ $path2 = $path4 ]] diff --git a/tests/fetchMercurial.sh b/tests/fetchMercurial.sh new file mode 100644 index 000000000000..0c9f4bdbbc87 --- /dev/null +++ b/tests/fetchMercurial.sh @@ -0,0 +1,84 @@ +source common.sh + +if [[ -z $(type -p hg) ]]; then + echo "Mercurial not installed; skipping Mercurial tests" + exit 0 +fi + +clearStore + +repo=$TEST_ROOT/hg + +rm -rf $repo ${repo}-tmp $TEST_HOME/.cache/nix/hg + +hg init $repo +echo '[ui]' >> $repo/.hg/hgrc +echo 'username = Foobar <foobar@example.org>' >> $repo/.hg/hgrc + +echo utrecht > $repo/hello +hg add --cwd $repo hello +hg commit --cwd $repo -m 'Bla1' +rev1=$(hg log --cwd $repo -r tip --template '{node}') + +echo world > $repo/hello +hg commit --cwd $repo -m 'Bla2' +rev2=$(hg log --cwd $repo -r tip --template '{node}') + +# Fetch the default branch. +path=$(nix eval --raw "(builtins.fetchMercurial file://$repo).outPath") +[[ $(cat $path/hello) = world ]] + +# Fetch using an explicit revision hash. +path2=$(nix eval --raw "(builtins.fetchMercurial { url = file://$repo; rev = \"$rev2\"; }).outPath") +[[ $path = $path2 ]] + +# Fetch again. This should be cached. +mv $repo ${repo}-tmp +path2=$(nix eval --raw "(builtins.fetchMercurial file://$repo).outPath") +[[ $path = $path2 ]] + +[[ $(nix eval --raw "(builtins.fetchMercurial file://$repo).branch") = default ]] +[[ $(nix eval "(builtins.fetchMercurial file://$repo).revCount") = 1 ]] +[[ $(nix eval --raw "(builtins.fetchMercurial file://$repo).rev") = $rev2 ]] + +# But with TTL 0, it should fail. +(! nix eval --tarball-ttl 0 "(builtins.fetchMercurial file://$repo)") + +# Fetching with a explicit hash should succeed. +path2=$(nix eval --tarball-ttl 0 --raw "(builtins.fetchMercurial { url = file://$repo; rev = \"$rev2\"; }).outPath") +[[ $path = $path2 ]] + +path2=$(nix eval --tarball-ttl 0 --raw "(builtins.fetchMercurial { url = file://$repo; rev = \"$rev1\"; }).outPath") +[[ $(cat $path2/hello) = utrecht ]] + +mv ${repo}-tmp $repo + +# Using a clean working tree should produce the same result. +path2=$(nix eval --raw "(builtins.fetchMercurial $repo).outPath") +[[ $path = $path2 ]] + +# Using an unclean tree should yield the tracked but uncommitted changes. +mkdir $repo/dir1 $repo/dir2 +echo foo > $repo/dir1/foo +echo bar > $repo/bar +echo bar > $repo/dir2/bar +hg add --cwd $repo dir1/foo +hg rm --cwd $repo hello + +path2=$(nix eval --raw "(builtins.fetchMercurial $repo).outPath") +[ ! -e $path2/hello ] +[ ! -e $path2/bar ] +[ ! -e $path2/dir2/bar ] +[[ $(cat $path2/dir1/foo) = foo ]] + +[[ $(nix eval --raw "(builtins.fetchMercurial $repo).rev") = 0000000000000000000000000000000000000000 ]] + +# ... unless we're using an explicit rev. +path3=$(nix eval --raw "(builtins.fetchMercurial { url = $repo; rev = \"default\"; }).outPath") +[[ $path = $path3 ]] + +# Committing should not affect the store path. +hg commit --cwd $repo -m 'Bla3' + +path4=$(nix eval --tarball-ttl 0 --raw "(builtins.fetchMercurial file://$repo).outPath") +[[ $path2 = $path4 ]] diff --git a/tests/lang/lib.nix b/tests/lang/lib.nix index 028a538314b7..1c63b2f31d67 100644 --- a/tests/lang/lib.nix +++ b/tests/lang/lib.nix @@ -49,7 +49,7 @@ rec { if comp (head list2) (head list1) then [(head list2)] ++ mergeLists comp list1 (tail list2) else [(head list1)] ++ mergeLists comp (tail list1) list2; - id = x: x; + id = x:x; # sic const = x: y: x; diff --git a/tests/lang/parse-okay-url.nix b/tests/lang/parse-okay-url.nix index fce3b13ee64b..fb74d66f0923 100644 --- a/tests/lang/parse-okay-url.nix +++ b/tests/lang/parse-okay-url.nix @@ -1,7 +1,8 @@ -[ x:x +[ https://svn.cs.uu.nl:12443/repos/trace/trunk http://www2.mplayerhq.hu/MPlayer/releases/fonts/font-arial-iso-8859-1.tar.bz2 http://losser.st-lab.cs.uu.nl/~armijn/.nix/gcc-3.3.4-static-nix.tar.gz http://fpdownload.macromedia.com/get/shockwave/flash/english/linux/7.0r25/install_flash_player_7_linux.tar.gz ftp://ftp.gtk.org/pub/gtk/v1.2/gtk+-1.2.10.tar.gz + channel:nixos-17.09 ] diff --git a/tests/local.mk b/tests/local.mk index 6160b04c2598..67b378839a22 100644 --- a/tests/local.mk +++ b/tests/local.mk @@ -15,7 +15,9 @@ nix_tests = \ linux-sandbox.sh \ build-remote.sh \ nar-index.sh \ - structured-attrs.sh + structured-attrs.sh \ + fetchGit.sh \ + fetchMercurial.sh # parallel.sh install-tests += $(foreach x, $(nix_tests), tests/$(x)) diff --git a/tests/restricted.sh b/tests/restricted.sh index 19096a9f8dd2..a297847cc8e3 100644 --- a/tests/restricted.sh +++ b/tests/restricted.sh @@ -16,3 +16,15 @@ nix-instantiate --option restrict-eval true --eval -E 'builtins.readDir ../src/b (! nix-instantiate --option restrict-eval true --eval -E 'let __nixPath = [ { prefix = "foo"; path = ./.; } ]; in <foo>') nix-instantiate --option restrict-eval true --eval -E 'let __nixPath = [ { prefix = "foo"; path = ./.; } ]; in <foo>' -I src=. +p=$(nix eval --raw "(builtins.fetchurl file://$(pwd)/restricted.sh)" --restrict-eval --allowed-uris "file://$(pwd)") +cmp $p restricted.sh + +(! nix eval --raw "(builtins.fetchurl file://$(pwd)/restricted.sh)" --restrict-eval) + +(! nix eval --raw "(builtins.fetchurl file://$(pwd)/restricted.sh)" --restrict-eval --allowed-uris "file://$(pwd)/restricted.sh/") + +nix eval --raw "(builtins.fetchurl file://$(pwd)/restricted.sh)" --restrict-eval --allowed-uris "file://$(pwd)/restricted.sh" + +(! nix eval --raw "(builtins.fetchurl https://github.com/NixOS/patchelf/archive/master.tar.gz)" --restrict-eval) +(! nix eval --raw "(builtins.fetchTarball https://github.com/NixOS/patchelf/archive/master.tar.gz)" --restrict-eval) +(! nix eval --raw "(fetchGit git://github.com/NixOS/patchelf.git)" --restrict-eval) |