aboutsummaryrefslogtreecommitdiff
path: root/nix/libstore/store-api.cc
blob: 0de0b6b2988904b5392fcd70029268f5f8681588 (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
#include "store-api.hh"
#include "globals.hh"
#include "util.hh"

#include <climits>


namespace nix {


GCOptions::GCOptions()
{
    action = gcDeleteDead;
    ignoreLiveness = false;
    maxFreed = ULLONG_MAX;
}


bool isInStore(const Path & path)
{
    return isInDir(path, settings.nixStore);
}


bool isStorePath(const Path & path)
{
    return isInStore(path)
        && path.find('/', settings.nixStore.size() + 1) == Path::npos;
}


void assertStorePath(const Path & path)
{
    if (!isStorePath(path))
        throw Error(format("path `%1%' is not in the store") % path);
}


Path toStorePath(const Path & path)
{
    if (!isInStore(path))
        throw Error(format("path `%1%' is not in the store") % path);
    Path::size_type slash = path.find('/', settings.nixStore.size() + 1);
    if (slash == Path::npos)
        return path;
    else
        return Path(path, 0, slash);
}


string storePathToName(const Path & path)
{
    assertStorePath(path);
    return string(path, settings.nixStore.size() + 34);
}


void checkStoreName(const string & name)
{
    string validChars = "+-._?=";
    /* Disallow names starting with a dot for possible security
       reasons (e.g., "." and ".."). */
    if (string(name, 0, 1) == ".")
        throw Error(format("invalid name: `%1%'") % name);
    foreach (string::const_iterator, i, name)
        if (!((*i >= 'A' && *i <= 'Z') ||
              (*i >= 'a' && *i <= 'z') ||
              (*i >= '0' && *i <= '9') ||
              validChars.find(*i) != string::npos))
        {
            throw Error(format("invalid character `%1%' in name `%2%'")
                % *i % name);
        }
}


/* Store paths have the following form:

   <store>/<h>-<name>

   where

   <store> = the location of the store, usually /gnu/store
   
   <name> = a human readable name for the path, typically obtained
     from the name attribute of the derivation, or the name of the
     source file from which the store path is created.  For derivation
     outputs other than the default "out" output, the string "-<id>"
     is suffixed to <name>.
     
   <h> = base-32 representation of the first 160 bits of a SHA-256
     hash of <s>; the hash part of the store name
     
   <s> = the string "<type>:sha256:<h2>:<store>:<name>";
     note that it includes the location of the store as well as the
     name to make sure that changes to either of those are reflected
     in the hash (e.g. you won't get /nix/store/<h>-name1 and
     /nix/store/<h>-name2 with equal hash parts).
     
   <type> = one of:
     "text:<r1>:<r2>:...<rN>"
       for plain text files written to the store using
       addTextToStore(); <r1> ... <rN> are the references of the
       path.
     "source"
       for paths copied to the store using addToStore() when recursive
       = true and hashAlgo = "sha256"
     "output:<id>"
       for either the outputs created by derivations, OR paths copied
       to the store using addToStore() with recursive != true or
       hashAlgo != "sha256" (in that case "source" is used; it's
       silly, but it's done that way for compatibility).  <id> is the
       name of the output (usually, "out").

   <h2> = base-16 representation of a SHA-256 hash of:
     if <type> = "text:...":
       the string written to the resulting store path
     if <type> = "source":
       the serialisation of the path from which this store path is
       copied, as returned by hashPath()
     if <type> = "output:out":
       for non-fixed derivation outputs:
         the derivation (see hashDerivationModulo() in
         primops.cc)
       for paths copied by addToStore() or produced by fixed-output
       derivations:
         the string "fixed:out:<rec><algo>:<hash>:", where
           <rec> = "r:" for recursive (path) hashes, or "" or flat
             (file) hashes
           <algo> = "md5", "sha1" or "sha256"
           <hash> = base-16 representation of the path or flat hash of
             the contents of the path (or expected contents of the
             path for fixed-output derivations)

   It would have been nicer to handle fixed-output derivations under
   "source", e.g. have something like "source:<rec><algo>", but we're
   stuck with this for now...

   The main reason for this way of computing names is to prevent name
   collisions (for security).  For instance, it shouldn't be feasible
   to come up with a derivation whose output path collides with the
   path for a copied source.  The former would have a <s> starting with
   "output:out:", while the latter would have a <2> starting with
   "source:".
*/


Path makeStorePath(const string & type,
    const Hash & hash, const string & name)
{
    /* e.g., "source:sha256:1abc...:/nix/store:foo.tar.gz" */
    string s = type + ":sha256:" + printHash(hash) + ":"
        + settings.nixStore + ":" + name;

    checkStoreName(name);

    return settings.nixStore + "/"
        + printHash32(compressHash(hashString(htSHA256, s), 20))
        + "-" + name;
}


Path makeOutputPath(const string & id,
    const Hash & hash, const string & name)
{
    return makeStorePath("output:" + id, hash,
        name + (id == "out" ? "" : "-" + id));
}


Path makeFixedOutputPath(bool recursive,
    HashType hashAlgo, Hash hash, string name)
{
    return hashAlgo == htSHA256 && recursive
        ? makeStorePath("source", hash, name)
        : makeStorePath("output:out", hashString(htSHA256,
                "fixed:out:" + (recursive ? (string) "r:" : "") +
                printHashType(hashAlgo) + ":" + printHash(hash) + ":"),
            name);
}


Path computeStorePathForText(const string & name, const string & s,
    const PathSet & references)
{
    Hash hash = hashString(htSHA256, s);
    /* Stuff the references (if any) into the type.  This is a bit
       hacky, but we can't put them in `s' since that would be
       ambiguous. */
    string type = "text";
    foreach (PathSet::const_iterator, i, references) {
        type += ":";
        type += *i;
    }
    return makeStorePath(type, hash, name);
}


/* Return a string accepted by decodeValidPathInfo() that
   registers the specified paths as valid.  Note: it's the
   responsibility of the caller to provide a closure. */
string StoreAPI::makeValidityRegistration(const PathSet & paths,
    bool showDerivers, bool showHash)
{
    string s = "";
    
    foreach (PathSet::iterator, i, paths) {
        s += *i + "\n";

        ValidPathInfo info = queryPathInfo(*i);

        if (showHash) {
            s += printHash(info.hash) + "\n";
            s += (format("%1%\n") % info.narSize).str();
        }

        Path deriver = showDerivers ? info.deriver : "";
        s += deriver + "\n";

        s += (format("%1%\n") % info.references.size()).str();

        foreach (PathSet::iterator, j, info.references)
            s += *j + "\n";
    }

    return s;
}

string showPaths(const PathSet & paths)
{
    string s;
    foreach (PathSet::const_iterator, i, paths) {
        if (s.size() != 0) s += ", ";
        s += "`" + *i + "'";
    }
    return s;
}


void exportPaths(StoreAPI & store, const Paths & paths,
    bool sign, Sink & sink)
{
    foreach (Paths::const_iterator, i, paths) {
        writeInt(1, sink);
        store.exportPath(*i, sign, sink);
    }
    writeInt(0, sink);
}

Path readStorePath(Source & from)
{
    Path path = readString(from);
    assertStorePath(path);
    return path;
}


template<class T> T readStorePaths(Source & from)
{
    T paths = readStrings<T>(from);
    foreach (typename T::iterator, i, paths) assertStorePath(*i);
    return paths;
}

template PathSet readStorePaths(Source & from);

}


#include "local-store.hh"
#include "serialise.hh"


namespace nix {


std::shared_ptr<StoreAPI> store;


std::shared_ptr<StoreAPI> openStore(bool reserveSpace)
{
    return std::shared_ptr<StoreAPI>(new LocalStore(reserveSpace));
}


}
/td> * nix/libutil/util.cc (pathExists) [HAVE_STATX]: New code. 2019-11-27daemon: 'deletePath' uses 'statx' when available.Ludovic Courtès * nix/libutil/util.cc (_deletePath) [HAVE_STATX]: Use 'statx'. 2019-11-27daemon: GC remove-unused-links phase uses 'statx' when available.Ludovic Courtès * config-daemon.ac: Check for 'statx'. * nix/libstore/gc.cc (LocalStore::removeUnusedLinks) [HAVE_STATX]: Use 'statx' instead of 'lstat'. 2019-11-26daemon: boost::format: Fix typo "referred".Vagrant Cascadian * nix/boost/format/exceptions.hpp (too_few_args): Fix typo. (too_many_args): Fix typo. Signed-off-by: Ludovic Courtès <ludo@gnu.org> 2019-11-26guix build, daemon: Rename "--no-build-hook" to "--no-offload".Ludovic Courtès This is a followup to bc69ea2d605810cc32e13ed03d5848b8dc358b61. * guix/scripts/build.scm (show-build-options-help): Rename "--no-build-hook" to "--no-offload". (%standard-build-options): Likewise, and warn when "--no-build-hook" is passed. * nix/nix-daemon/guix-daemon.cc (options): Add "--no-offload" and mark "--no-build-hook" as hidden. * guix/scripts/offload.scm: Adjust comment. * doc/guix.texi (Invoking guix-daemon, Common Build Options): Replace "--no-build-hook" with "--no-offload". * etc/completion/fish/guix.fish, etc/completion/zsh/_guix: Adjust accordingly. 2019-11-22daemon: GC displays how much it has collected.Ludovic Courtès * nix/libstore/gc.cc (LocalStore::deletePathRecursive): Display the percentage reached relative to 'maxFreed', or the total amount of data deleted when 'maxFreed' is ULLONG_MAX. 2019-11-13daemon: Don't include <linux/fs.h>.Ludovic Courtès As of GNU libc 2.29, <sys/mount.h> declares all the constants and functions we need, so there's no use in including <linux/fs.h> anymore. This silences annoying warnings like this one: In file included from nix/libstore/local-store.cc:32:0: /gnu/store/…-linux-libre-headers-4.19.56/include/linux/fs.h:108:0: warning: "MS_RDONLY" redefined #define MS_RDONLY 1 /* Mount read-only */ In file included from nix/libstore/local-store.cc:28:0: /gnu/store/…-glibc-2.29/include/sys/mount.h:36:0: note: this is the location of the previous definition #define MS_RDONLY MS_RDONLY * config-daemon.ac: Remove check for <linux/fs.h>. * nix/libstore/build.cc: Remove conditional inclusion of <linux/fs.h>. * nix/libstore/local-store.cc: Remove "#if HAVE_LINUX_FS_H" and inclusion of <linux/fs.h>. 2019-11-04daemon: Unregister build hook from the worker's children upon build failure.Ludovic Courtès Fixes <https://bugs.gnu.org/38062>. This is a followup to ada9a19a2dca74feafcf24df1152abd685d4142f. * nix/libstore/build.cc (DerivationGoal::killChild): Add conditional call to 'worker.childTerminated' for 'hook->pid'. 2019-10-16daemon: Make 'profiles/per-user' non-world-writable.Ludovic Courtès Fixes <https://bugs.gnu.org/37744>. Reported at <https://www.openwall.com/lists/oss-security/2019/10/09/4>. Based on Nix commit 5a303093dcae1e5ce9212616ef18f2ca51020b0d by Eelco Dolstra <edolstra@gmail.com>. * nix/libstore/local-store.cc (LocalStore::LocalStore): Set 'perUserDir' to #o755 instead of #o1777. (LocalStore::createUser): New function. * nix/libstore/local-store.hh (LocalStore): Add it. * nix/libstore/store-api.hh (StoreAPI): Add it. * nix/nix-daemon/nix-daemon.cc (performOp): In 'wopSetOptions', add condition to handle "user-name" property and honor it. (processConnection): Add 'userId' parameter. Call 'store->createUser' when userId is not -1. * guix/profiles.scm (ensure-profile-directory): Note that this is now handled by the daemon. * guix/store.scm (current-user-name): New procedure. (set-build-options): Add #:user-name parameter and pass it to the daemon. * tests/guix-daemon.sh: Test the creation of 'profiles/per-user' when listening on a TCP socket. * tests/store.scm ("profiles/per-user exists and is not writable") ("profiles/per-user/$USER exists"): New tests. 2019-10-16daemon: Remove traces of 'NIX_ROOT_FINDER'.Ludovic Courtès This is a followup to 2e3e5d21988fc2cafb2a9eaf4b00976ea425629d. * build-aux/test-env.in: Remove mentions of 'NIX_ROOT_FINDER'. * nix/libstore/gc.cc (LocalStore::collectGarbage): Adjust comment accordingly. 2019-09-28daemon: Strictly respect timeouts for 'guix offload'.Ludovic Courtès Until now it was up to 'guix offload' to honor timeouts. Unfortunately it would sometimes fail to do that, for example due to the libssh bug at <https://bugs.libssh.org/T33>. With this change, 'guix offload' is automatically killed by the daemon when one of the timeouts expires. Thus, data transfers performed by 'guix offload' now count as part of the timeouts, rather than just actual build time. * nix/libstore/build.cc (DerivationGoal::tryBuildHook): Pass true as the 'respectTimeouts' argument to 'childStarted'. 2019-09-16daemon: Include 'config.h' in 'nix-daemon.cc'.Timothy Sample * nix/nix-daemon/nix-daemon.cc: Include 'config.h'. 2019-09-08daemon: Remove 'NIX_LIBEXEC_DIR'.Ludovic Courtès * nix/libstore/globals.hh (Settings)[nixLibexecDir]: Remove. * nix/libstore/globals.cc (Settings::processEnvironment): Remove reference to 'nixLibexecDir'. * nix/local.mk (libstore_a_CPPFLAGS): Remove -DNIX_LIBEXEC_DIR flag. * build-aux/pre-inst-env.in: Remove references to 'NIX_LIBEXEC_DIR'. 2019-09-08daemon: Run 'guix substitute' directly and assume a single substituter.Ludovic Courtès The daemon had a mechanism that allows it to handle a list of substituters and try them sequentially; this removes it. * nix/scripts/substitute.in: Remove. * nix/local.mk (nodist_pkglibexec_SCRIPTS): Remove. * config-daemon.ac: Don't output 'nix/scripts/substitute'. * nix/libstore/build.cc (SubstitutionGoal)[subs, sub, hasSubstitute]: Remove. [tryNext]: Make private. (SubstitutionGoal::SubstitutionGoal, SubstitutionGoal::init): Remove now unneeded initializers. (SubstitutionGoal::tryNext): Adjust to assume a single substituter: call 'amDone' upfront when we couldn't find substitutes. (SubstitutionGoal::tryToRun): Adjust to run 'guix substitute' via 'settings.guixProgram'. (SubstitutionGoal::finished): Call 'amDone(ecFailed)' upon failure instead of setting 'state' to 'tryNext'. * nix/libstore/globals.hh (Settings)[substituters]: Remove. * nix/libstore/local-store.cc (LocalStore::~LocalStore): Adjust to handle a single substituter. (LocalStore::startSubstituter): Remove 'path' parameter. Adjust to invoke 'settings.guixProgram'. Don't refer to 'run.program', which no longer exists. (LocalStore::querySubstitutablePaths): Adjust for 'runningSubstituters' being a singleton instead of a list. (LocalStore::querySubstitutablePathInfos): Likewise, and remove 'substituter' parameter. * nix/libstore/local-store.hh (RunningSubstituter)[program]: Remove. (LocalStore)[runningSubstituters]: Remove. [runningSubstituter]: New field. [querySubstitutablePathInfos]: Remove 'substituter' parameter. [startSubstituter]: Remove 'substituter' parameter. * nix/nix-daemon/guix-daemon.cc (main): Remove references to 'settings.substituters'. * nix/nix-daemon/nix-daemon.cc (performOp): Ignore the user's "build-use-substitutes" value when 'settings.useSubstitutes' is false. 2019-09-08daemon: Run 'guix offload' directly.Ludovic Courtès * nix/scripts/offload.in: Remove. * nix/local.mk (nodist_pkglibexec_SCRIPTS) [BUILD_DAEMON_OFFLOAD]: Remove 'scripts/offload'. * config-daemon.ac: Don't output 'nix/scripts/offload'. * build-aux/pre-inst-env.in: Don't set 'NIX_BUILD_HOOK'. * nix/libstore/build.cc (HookInstance::HookInstance): Run 'guix offload'. (DerivationGoal::tryBuildHook): Remove reference to 'NIX_BUILD_HOOK'. * nix/nix-daemon/guix-daemon.cc (main) [HAVE_DAEMON_OFFLOAD_HOOK]: Don't set 'NIX_BUILD_HOOK'. * nix/nix-daemon/nix-daemon.cc (performOp) [!HAVE_DAEMON_OFFLOAD_HOOK]: Leave 'settings.useBuildHook' unchanged. 2019-09-08daemon: Run 'guix perform-download' directly.Ludovic Courtès * nix/scripts/download.in: Remove. * nix/local.mk (nodist_pkglibexec_SCRIPTS): Remove 'scripts/download'. * config-daemon.ac: Don't output 'nix/scripts/download'. * nix/libstore/builtins.cc (builtinDownload): Invoke 'guix perform-download' directly. 2019-09-08daemon: Run 'guix authenticate' directly.Ludovic Courtès * nix/scripts/authenticate.in: Remove. * nix/local.mk (nodist_pkglibexec_SCRIPTS): Remove scripts/authenticate. * config-daemon.ac: Don't output 'nix/scripts/authenticate'. * nix/libstore/local-store.cc (runAuthenticationProgram): Run 'guix authenticate'. 2019-09-08daemon: Invoke 'guix gc --list-busy' instead of 'list-runtime-roots'.Ludovic Courtès * nix/scripts/list-runtime-roots.in: Remove. * guix/store/roots.scm (%proc-directory): New variable. (proc-file-roots, proc-exe-roots, proc-cwd-roots) (proc-fd-roots, proc-maps-roots, proc-environ-roots) (referenced-files, canonicalize-store-item, busy-store-items): New procedures, taken from 'list-runtime-roots.in'. * nix/libstore/globals.hh (Settings)[guixProgram]: New field. * nix/libstore/globals.cc (Settings::processEnvironment): Initialize 'guixProgram'. * nix/libstore/gc.cc (addAdditionalRoots): Drop code related to 'NIX_ROOT_FINDER'. Run "guix gc --list-busy". * nix/local.mk (nodist_pkglibexec_SCRIPTS): Remove 'scripts/list-runtime-roots'. * config-daemon.ac: Don't output nix/scripts/list-runtime-roots. * build-aux/pre-inst-env.in: Don't set 'NIX_ROOT_FINDER'. Set 'GUIX'. * doc/guix.texi (Invoking guix gc): Document '--list-busy'. * guix/scripts/gc.scm (show-help, %options): Add "--list-busy". (guix-gc)[list-busy]: New procedure. Handle the 'list-busy' action. 2019-08-30daemon: Don't reply on 'st_blocks'.Eelco Dolstra Ported by Ludovic Courtès <ludo@gnu.org> from <https://github.com/NixOS/nix/commit/a2c4fcd5e9782dc8d2998773380c7171ee53b813>. * nix/libstore/gc.cc (LocalStore::removeUnusedLinks): Use 'st.st_size' instead of 'st.st_blocks * 512'. * nix/libutil/util.cc (_deletePath): Likewise. 2019-06-13daemon: Replace "illegal" by "invalid" in error messages.Ludovic Courtès * nix/libstore/build.cc (parseReferenceSpecifiers): Replace "illegal" by "invalid". * nix/libstore/globals.cc (Settings::pack): Likewise. * nix/libstore/store-api.cc (checkStoreName): Likewise. 2019-03-13Remove traces of "GuixSD".Ludovic Courtès * gnu/bootloader/extlinux.scm (extlinux-configuration-file): Remove mentions of "GuixSD". * gnu/bootloader/grub.scm (install-grub-efi): Likewise. * gnu/build/vm.scm (make-iso9660-image): Change default #:volume-id to "Guix_image". (initialize-hard-disk): Search for the "Guix_image" label. * gnu/ci.scm (system-test-jobs, tarball-jobs): Remove "GuixSD". * gnu/installer/newt/welcome.scm (run-welcome-page): Likewise. * gnu/packages/audio.scm (supercollider)[description]: Likewise. * gnu/packages/curl.scm (curl): Likewise. * gnu/packages/emacs.scm (emacs): Likewise. * gnu/packages/gnome.scm (network-manager): Likewise. * gnu/packages/julia.scm (julia): Likewise. * gnu/packages/linux.scm (alsa-plugins): Likewise. (powertop, wireless-regdb): Likewise. * gnu/packages/package-management.scm (guix): Likewise. * gnu/packages/polkit.scm (polkit): Likewise. * gnu/packages/tex.scm (texlive-bin): Likewise. * gnu/services/base.scm (file-systems->fstab): Likewise. * gnu/services/cups.scm (%cups-activation): Likewise. * gnu/services/mail.scm (%dovecot-activation): Likewise. * gnu/services/messaging.scm (prosody-configuration)[log]: Likewise. * gnu/system/examples/vm-image.tmpl (vm-image-motd): Likewise. * gnu/system/install.scm (installation-os)[file-systems]: Change root file system label to "Guix_image". * gnu/system/mapped-devices.scm (check-device-initrd-modules): Remove "GuixSD". * gnu/system/vm.scm (system-docker-image): Likewise. (system-disk-image)[root-label]: Change to "Guix_image". * gnu/tests/install.scm (run-install): Remove "GuixSD". * guix/modules.scm (guix-module-name?): Likewise. * nix/libstore/optimise-store.cc: Likewise.