2 #include "local-store.hh"
5 #include "pathlocks.hh"
6 #include "worker-protocol.hh"
7 #include "derivations.hh"
14 #include <sys/types.h>
25 #if HAVE_UNSHARE && HAVE_STATVFS && HAVE_SYS_MOUNT_H
27 #include <sys/statvfs.h>
28 #include <sys/mount.h>
33 #include <sys/ioctl.h>
43 MakeError(SQLiteError
, Error
);
44 MakeError(SQLiteBusy
, SQLiteError
);
47 static void throwSQLiteError(sqlite3
* db
, const format
& f
)
48 __attribute__ ((noreturn
));
50 static void throwSQLiteError(sqlite3
* db
, const format
& f
)
52 int err
= sqlite3_errcode(db
);
53 if (err
== SQLITE_BUSY
|| err
== SQLITE_PROTOCOL
) {
54 if (err
== SQLITE_PROTOCOL
)
55 printMsg(lvlError
, "warning: SQLite database is busy (SQLITE_PROTOCOL)");
57 static bool warned
= false;
59 printMsg(lvlError
, "warning: SQLite database is busy");
63 /* Sleep for a while since retrying the transaction right away
64 is likely to fail again. */
68 t
.tv_nsec
= (random() % 100) * 1000 * 1000; /* <= 0.1s */
73 throw SQLiteBusy(format("%1%: %2%") % f
.str() % sqlite3_errmsg(db
));
76 throw SQLiteError(format("%1%: %2%") % f
.str() % sqlite3_errmsg(db
));
80 /* Convenience macros for retrying a SQLite transaction. */
81 #define retry_sqlite while (1) { try {
82 #define end_retry_sqlite break; } catch (SQLiteBusy & e) { } }
88 if (db
&& sqlite3_close(db
) != SQLITE_OK
)
89 throwSQLiteError(db
, "closing database");
96 void SQLiteStmt::create(sqlite3
* db
, const string
& s
)
100 if (sqlite3_prepare_v2(db
, s
.c_str(), -1, &stmt
, 0) != SQLITE_OK
)
101 throwSQLiteError(db
, "creating statement");
106 void SQLiteStmt::reset()
109 /* Note: sqlite3_reset() returns the error code for the most
110 recent call to sqlite3_step(). So ignore it. */
116 SQLiteStmt::~SQLiteStmt()
119 if (stmt
&& sqlite3_finalize(stmt
) != SQLITE_OK
)
120 throwSQLiteError(db
, "finalizing statement");
127 void SQLiteStmt::bind(const string
& value
)
129 if (sqlite3_bind_text(stmt
, curArg
++, value
.c_str(), -1, SQLITE_TRANSIENT
) != SQLITE_OK
)
130 throwSQLiteError(db
, "binding argument");
134 void SQLiteStmt::bind(int value
)
136 if (sqlite3_bind_int(stmt
, curArg
++, value
) != SQLITE_OK
)
137 throwSQLiteError(db
, "binding argument");
141 void SQLiteStmt::bind64(long long value
)
143 if (sqlite3_bind_int64(stmt
, curArg
++, value
) != SQLITE_OK
)
144 throwSQLiteError(db
, "binding argument");
148 void SQLiteStmt::bind()
150 if (sqlite3_bind_null(stmt
, curArg
++) != SQLITE_OK
)
151 throwSQLiteError(db
, "binding argument");
155 /* Helper class to ensure that prepared statements are reset when
156 leaving the scope that uses them. Unfinished prepared statements
157 prevent transactions from being aborted, and can cause locks to be
158 kept when they should be released. */
162 SQLiteStmtUse(SQLiteStmt
& stmt
) : stmt(stmt
)
182 SQLiteTxn(sqlite3
* db
) : active(false) {
184 if (sqlite3_exec(db
, "begin;", 0, 0, 0) != SQLITE_OK
)
185 throwSQLiteError(db
, "starting transaction");
191 if (sqlite3_exec(db
, "commit;", 0, 0, 0) != SQLITE_OK
)
192 throwSQLiteError(db
, "committing transaction");
199 if (active
&& sqlite3_exec(db
, "rollback;", 0, 0, 0) != SQLITE_OK
)
200 throwSQLiteError(db
, "aborting transaction");
208 void checkStoreNotSymlink()
210 if (getEnv("NIX_IGNORE_SYMLINK_STORE") == "1") return;
211 Path path
= settings
.nixStore
;
213 while (path
!= "/") {
214 if (lstat(path
.c_str(), &st
))
215 throw SysError(format("getting status of `%1%'") % path
);
216 if (S_ISLNK(st
.st_mode
))
218 "the path `%1%' is a symlink; "
219 "this is not allowed for the Nix store and its parent directories")
226 LocalStore::LocalStore(bool reserveSpace
)
227 : didSetSubstituterEnv(false)
229 schemaPath
= settings
.nixDBPath
+ "/schema";
231 if (settings
.readOnlyMode
) {
236 /* Create missing state directories if they don't already exist. */
237 createDirs(settings
.nixStore
);
239 createDirs(linksDir
= settings
.nixStore
+ "/.links");
240 Path profilesDir
= settings
.nixStateDir
+ "/profiles";
241 createDirs(profilesDir
);
242 createDirs(settings
.nixStateDir
+ "/temproots");
243 createDirs(settings
.nixDBPath
);
244 Path gcRootsDir
= settings
.nixStateDir
+ "/gcroots";
245 if (!pathExists(gcRootsDir
)) {
246 createDirs(gcRootsDir
);
247 createSymlink(profilesDir
, gcRootsDir
+ "/profiles");
250 /* Optionally, create directories and set permissions for a
251 multi-user install. */
252 if (getuid() == 0 && settings
.buildUsersGroup
!= "") {
254 Path perUserDir
= profilesDir
+ "/per-user";
255 createDirs(perUserDir
);
256 if (chmod(perUserDir
.c_str(), 01777) == -1)
257 throw SysError(format("could not set permissions on '%1%' to 1777") % perUserDir
);
261 struct group
* gr
= getgrnam(settings
.buildUsersGroup
.c_str());
263 throw Error(format("the group `%1%' specified in `build-users-group' does not exist")
264 % settings
.buildUsersGroup
);
267 if (stat(settings
.nixStore
.c_str(), &st
))
268 throw SysError(format("getting attributes of path '%1%'") % settings
.nixStore
);
270 if (st
.st_uid
!= 0 || st
.st_gid
!= gr
->gr_gid
|| (st
.st_mode
& ~S_IFMT
) != perm
) {
271 if (chown(settings
.nixStore
.c_str(), 0, gr
->gr_gid
) == -1)
272 throw SysError(format("changing ownership of path '%1%'") % settings
.nixStore
);
273 if (chmod(settings
.nixStore
.c_str(), perm
) == -1)
274 throw SysError(format("changing permissions on path '%1%'") % settings
.nixStore
);
279 checkStoreNotSymlink();
281 /* We can't open a SQLite database if the disk is full. Since
282 this prevents the garbage collector from running when it's most
283 needed, we reserve some dummy space that we can free just
284 before doing a garbage collection. */
286 Path reservedPath
= settings
.nixDBPath
+ "/reserved";
289 if (stat(reservedPath
.c_str(), &st
) == -1 ||
290 st
.st_size
!= settings
.reservedSize
)
292 AutoCloseFD fd
= open(reservedPath
.c_str(), O_WRONLY
| O_CREAT
, 0600);
294 #if HAVE_POSIX_FALLOCATE
295 res
= posix_fallocate(fd
, 0, settings
.reservedSize
);
298 writeFull(fd
, string(settings
.reservedSize
, 'X'));
299 ftruncate(fd
, settings
.reservedSize
);
304 deletePath(reservedPath
);
305 } catch (SysError
& e
) { /* don't care about errors */
308 /* Acquire the big fat lock in shared mode to make sure that no
309 schema upgrade is in progress. */
311 Path globalLockPath
= settings
.nixDBPath
+ "/big-lock";
312 globalLock
= openLockFile(globalLockPath
.c_str(), true);
313 } catch (SysError
& e
) {
314 if (e
.errNo
!= EACCES
) throw;
315 settings
.readOnlyMode
= true;
320 if (!lockFile(globalLock
, ltRead
, false)) {
321 printMsg(lvlError
, "waiting for the big Nix store lock...");
322 lockFile(globalLock
, ltRead
, true);
325 /* Check the current database schema and if necessary do an
327 int curSchema
= getSchema();
328 if (curSchema
> nixSchemaVersion
)
329 throw Error(format("current Nix store schema is version %1%, but I only support %2%")
330 % curSchema
% nixSchemaVersion
);
332 else if (curSchema
== 0) { /* new store */
333 curSchema
= nixSchemaVersion
;
335 writeFile(schemaPath
, (format("%1%") % nixSchemaVersion
).str());
338 else if (curSchema
< nixSchemaVersion
) {
341 "Your Nix store has a database in Berkeley DB format,\n"
342 "which is no longer supported. To convert to the new format,\n"
343 "please upgrade Nix to version 0.12 first.");
345 if (!lockFile(globalLock
, ltWrite
, false)) {
346 printMsg(lvlError
, "waiting for exclusive access to the Nix store...");
347 lockFile(globalLock
, ltWrite
, true);
350 /* Get the schema version again, because another process may
351 have performed the upgrade already. */
352 curSchema
= getSchema();
354 if (curSchema
< 6) upgradeStore6();
355 else if (curSchema
< 7) { upgradeStore7(); openDB(true); }
357 writeFile(schemaPath
, (format("%1%") % nixSchemaVersion
).str());
359 lockFile(globalLock
, ltRead
, true);
366 LocalStore::~LocalStore()
369 foreach (RunningSubstituters::iterator
, i
, runningSubstituters
) {
370 if (i
->second
.disabled
) continue;
371 i
->second
.to
.close();
372 i
->second
.from
.close();
373 i
->second
.error
.close();
374 if (i
->second
.pid
!= -1)
375 i
->second
.pid
.wait(true);
382 if (fdTempRoots
!= -1) {
384 unlink(fnTempRoots
.c_str());
392 int LocalStore::getSchema()
395 if (pathExists(schemaPath
)) {
396 string s
= readFile(schemaPath
);
397 if (!string2Int(s
, curSchema
))
398 throw Error(format("`%1%' is corrupt") % schemaPath
);
404 void LocalStore::openDB(bool create
)
406 if (access(settings
.nixDBPath
.c_str(), R_OK
| W_OK
))
407 throw SysError(format("Nix database directory `%1%' is not writable") % settings
.nixDBPath
);
409 /* Open the Nix database. */
410 string dbPath
= settings
.nixDBPath
+ "/db.sqlite";
411 if (sqlite3_open_v2(dbPath
.c_str(), &db
.db
,
412 SQLITE_OPEN_READWRITE
| (create
? SQLITE_OPEN_CREATE
: 0), 0) != SQLITE_OK
)
413 throw Error(format("cannot open Nix database `%1%'") % dbPath
);
415 if (sqlite3_busy_timeout(db
, 60 * 60 * 1000) != SQLITE_OK
)
416 throwSQLiteError(db
, "setting timeout");
418 if (sqlite3_exec(db
, "pragma foreign_keys = 1;", 0, 0, 0) != SQLITE_OK
)
419 throwSQLiteError(db
, "enabling foreign keys");
421 /* !!! check whether sqlite has been built with foreign key
424 /* Whether SQLite should fsync(). "Normal" synchronous mode
425 should be safe enough. If the user asks for it, don't sync at
426 all. This can cause database corruption if the system
428 string syncMode
= settings
.fsyncMetadata
? "normal" : "off";
429 if (sqlite3_exec(db
, ("pragma synchronous = " + syncMode
+ ";").c_str(), 0, 0, 0) != SQLITE_OK
)
430 throwSQLiteError(db
, "setting synchronous mode");
432 /* Set the SQLite journal mode. WAL mode is fastest, so it's the
434 string mode
= settings
.useSQLiteWAL
? "wal" : "truncate";
438 stmt
.create(db
, "pragma main.journal_mode;");
439 if (sqlite3_step(stmt
) != SQLITE_ROW
)
440 throwSQLiteError(db
, "querying journal mode");
441 prevMode
= string((const char *) sqlite3_column_text(stmt
, 0));
443 if (prevMode
!= mode
&&
444 sqlite3_exec(db
, ("pragma main.journal_mode = " + mode
+ ";").c_str(), 0, 0, 0) != SQLITE_OK
)
445 throwSQLiteError(db
, "setting journal mode");
447 /* Increase the auto-checkpoint interval to 40000 pages. This
448 seems enough to ensure that instantiating the NixOS system
449 derivation is done in a single fsync(). */
450 if (mode
== "wal" && sqlite3_exec(db
, "pragma wal_autocheckpoint = 40000;", 0, 0, 0) != SQLITE_OK
)
451 throwSQLiteError(db
, "setting autocheckpoint interval");
453 /* Initialise the database schema, if necessary. */
455 const char * schema
=
456 #include "schema.sql.hh"
458 if (sqlite3_exec(db
, (const char *) schema
, 0, 0, 0) != SQLITE_OK
)
459 throwSQLiteError(db
, "initialising database schema");
462 /* Prepare SQL statements. */
463 stmtRegisterValidPath
.create(db
,
464 "insert into ValidPaths (path, hash, registrationTime, deriver, narSize) values (?, ?, ?, ?, ?);");
465 stmtUpdatePathInfo
.create(db
,
466 "update ValidPaths set narSize = ?, hash = ? where path = ?;");
467 stmtAddReference
.create(db
,
468 "insert or replace into Refs (referrer, reference) values (?, ?);");
469 stmtQueryPathInfo
.create(db
,
470 "select id, hash, registrationTime, deriver, narSize from ValidPaths where path = ?;");
471 stmtQueryReferences
.create(db
,
472 "select path from Refs join ValidPaths on reference = id where referrer = ?;");
473 stmtQueryReferrers
.create(db
,
474 "select path from Refs join ValidPaths on referrer = id where reference = (select id from ValidPaths where path = ?);");
475 stmtInvalidatePath
.create(db
,
476 "delete from ValidPaths where path = ?;");
477 stmtRegisterFailedPath
.create(db
,
478 "insert or ignore into FailedPaths (path, time) values (?, ?);");
479 stmtHasPathFailed
.create(db
,
480 "select time from FailedPaths where path = ?;");
481 stmtQueryFailedPaths
.create(db
,
482 "select path from FailedPaths;");
483 // If the path is a derivation, then clear its outputs.
484 stmtClearFailedPath
.create(db
,
485 "delete from FailedPaths where ?1 = '*' or path = ?1 "
486 "or path in (select d.path from DerivationOutputs d join ValidPaths v on d.drv = v.id where v.path = ?1);");
487 stmtAddDerivationOutput
.create(db
,
488 "insert or replace into DerivationOutputs (drv, id, path) values (?, ?, ?);");
489 stmtQueryValidDerivers
.create(db
,
490 "select v.id, v.path from DerivationOutputs d join ValidPaths v on d.drv = v.id where d.path = ?;");
491 stmtQueryDerivationOutputs
.create(db
,
492 "select id, path from DerivationOutputs where drv = ?;");
493 // Use "path >= ?" with limit 1 rather than "path like '?%'" to
494 // ensure efficient lookup.
495 stmtQueryPathFromHashPart
.create(db
,
496 "select path from ValidPaths where path >= ? limit 1;");
500 /* To improve purity, users may want to make the Nix store a read-only
501 bind mount. So make the Nix store writable for this process. */
502 void LocalStore::makeStoreWritable()
504 #if HAVE_UNSHARE && HAVE_STATVFS && HAVE_SYS_MOUNT_H && defined(MS_BIND) && defined(MS_REMOUNT)
505 if (getuid() != 0) return;
506 /* Check if /nix/store is on a read-only mount. */
508 if (statvfs(settings
.nixStore
.c_str(), &stat
) != 0)
509 throw SysError("getting info about the Nix store mount point");
511 if (stat
.f_flag
& ST_RDONLY
) {
512 if (unshare(CLONE_NEWNS
) == -1)
513 throw SysError("setting up a private mount namespace");
515 if (mount(0, settings
.nixStore
.c_str(), "none", MS_REMOUNT
| MS_BIND
, 0) == -1)
516 throw SysError(format("remounting %1% writable") % settings
.nixStore
);
522 const time_t mtimeStore
= 1; /* 1 second into the epoch */
525 static void canonicaliseTimestampAndPermissions(const Path
& path
, const struct stat
& st
)
527 if (!S_ISLNK(st
.st_mode
)) {
529 /* Mask out all type related bits. */
530 mode_t mode
= st
.st_mode
& ~S_IFMT
;
532 if (mode
!= 0444 && mode
!= 0555) {
533 mode
= (st
.st_mode
& S_IFMT
)
535 | (st
.st_mode
& S_IXUSR
? 0111 : 0);
536 if (chmod(path
.c_str(), mode
) == -1)
537 throw SysError(format("changing mode of `%1%' to %2$o") % path
% mode
);
542 if (st
.st_mtime
!= mtimeStore
) {
543 struct timeval times
[2];
544 times
[0].tv_sec
= st
.st_atime
;
545 times
[0].tv_usec
= 0;
546 times
[1].tv_sec
= mtimeStore
;
547 times
[1].tv_usec
= 0;
549 if (lutimes(path
.c_str(), times
) == -1)
550 if (errno
!= ENOSYS
||
551 (!S_ISLNK(st
.st_mode
) && utimes(path
.c_str(), times
) == -1))
553 if (!S_ISLNK(st
.st_mode
) && utimes(path
.c_str(), times
) == -1)
555 throw SysError(format("changing modification time of `%1%'") % path
);
560 void canonicaliseTimestampAndPermissions(const Path
& path
)
563 if (lstat(path
.c_str(), &st
))
564 throw SysError(format("getting attributes of path `%1%'") % path
);
565 canonicaliseTimestampAndPermissions(path
, st
);
569 static void canonicalisePathMetaData_(const Path
& path
, uid_t fromUid
, InodesSeen
& inodesSeen
)
574 if (lstat(path
.c_str(), &st
))
575 throw SysError(format("getting attributes of path `%1%'") % path
);
577 /* Really make sure that the path is of a supported type. */
578 if (!(S_ISREG(st
.st_mode
) || S_ISDIR(st
.st_mode
) || S_ISLNK(st
.st_mode
)))
579 throw Error(format("file ‘%1%’ has an unsupported type") % path
);
581 /* Fail if the file is not owned by the build user. This prevents
582 us from messing up the ownership/permissions of files
583 hard-linked into the output (e.g. "ln /etc/shadow $out/foo").
584 However, ignore files that we chown'ed ourselves previously to
585 ensure that we don't fail on hard links within the same build
586 (i.e. "touch $out/foo; ln $out/foo $out/bar"). */
587 if (fromUid
!= (uid_t
) -1 && st
.st_uid
!= fromUid
) {
588 assert(!S_ISDIR(st
.st_mode
));
589 if (inodesSeen
.find(Inode(st
.st_dev
, st
.st_ino
)) == inodesSeen
.end())
590 throw BuildError(format("invalid ownership on file `%1%'") % path
);
591 mode_t mode
= st
.st_mode
& ~S_IFMT
;
592 assert(S_ISLNK(st
.st_mode
) || (st
.st_uid
== geteuid() && (mode
== 0444 || mode
== 0555) && st
.st_mtime
== mtimeStore
));
596 inodesSeen
.insert(Inode(st
.st_dev
, st
.st_ino
));
598 canonicaliseTimestampAndPermissions(path
, st
);
600 /* Change ownership to the current uid. If it's a symlink, use
601 lchown if available, otherwise don't bother. Wrong ownership
602 of a symlink doesn't matter, since the owning user can't change
603 the symlink and can't delete it because the directory is not
604 writable. The only exception is top-level paths in the Nix
605 store (since that directory is group-writable for the Nix build
606 users group); we check for this case below. */
607 if (st
.st_uid
!= geteuid()) {
609 if (lchown(path
.c_str(), geteuid(), (gid_t
) -1) == -1)
611 if (!S_ISLNK(st
.st_mode
) &&
612 chown(path
.c_str(), geteuid(), (gid_t
) -1) == -1)
614 throw SysError(format("changing owner of `%1%' to %2%")
618 if (S_ISDIR(st
.st_mode
)) {
619 DirEntries entries
= readDirectory(path
);
620 for (auto & i
: entries
)
621 canonicalisePathMetaData_(path
+ "/" + i
.name
, fromUid
, inodesSeen
);
626 void canonicalisePathMetaData(const Path
& path
, uid_t fromUid
, InodesSeen
& inodesSeen
)
628 canonicalisePathMetaData_(path
, fromUid
, inodesSeen
);
630 /* On platforms that don't have lchown(), the top-level path can't
631 be a symlink, since we can't change its ownership. */
633 if (lstat(path
.c_str(), &st
))
634 throw SysError(format("getting attributes of path `%1%'") % path
);
636 if (st
.st_uid
!= geteuid()) {
637 assert(S_ISLNK(st
.st_mode
));
638 throw Error(format("wrong ownership of top-level store path `%1%'") % path
);
643 void canonicalisePathMetaData(const Path
& path
, uid_t fromUid
)
645 InodesSeen inodesSeen
;
646 canonicalisePathMetaData(path
, fromUid
, inodesSeen
);
650 void LocalStore::checkDerivationOutputs(const Path
& drvPath
, const Derivation
& drv
)
652 string drvName
= storePathToName(drvPath
);
653 assert(isDerivation(drvName
));
654 drvName
= string(drvName
, 0, drvName
.size() - drvExtension
.size());
656 if (isFixedOutputDrv(drv
)) {
657 DerivationOutputs::const_iterator out
= drv
.outputs
.find("out");
658 if (out
== drv
.outputs
.end())
659 throw Error(format("derivation `%1%' does not have an output named `out'") % drvPath
);
661 bool recursive
; HashType ht
; Hash h
;
662 out
->second
.parseHashInfo(recursive
, ht
, h
);
663 Path outPath
= makeFixedOutputPath(recursive
, ht
, h
, drvName
);
665 StringPairs::const_iterator j
= drv
.env
.find("out");
666 if (out
->second
.path
!= outPath
|| j
== drv
.env
.end() || j
->second
!= outPath
)
667 throw Error(format("derivation `%1%' has incorrect output `%2%', should be `%3%'")
668 % drvPath
% out
->second
.path
% outPath
);
672 Derivation
drvCopy(drv
);
673 foreach (DerivationOutputs::iterator
, i
, drvCopy
.outputs
) {
675 drvCopy
.env
[i
->first
] = "";
678 Hash h
= hashDerivationModulo(*this, drvCopy
);
680 foreach (DerivationOutputs::const_iterator
, i
, drv
.outputs
) {
681 Path outPath
= makeOutputPath(i
->first
, h
, drvName
);
682 StringPairs::const_iterator j
= drv
.env
.find(i
->first
);
683 if (i
->second
.path
!= outPath
|| j
== drv
.env
.end() || j
->second
!= outPath
)
684 throw Error(format("derivation `%1%' has incorrect output `%2%', should be `%3%'")
685 % drvPath
% i
->second
.path
% outPath
);
691 unsigned long long LocalStore::addValidPath(const ValidPathInfo
& info
, bool checkOutputs
)
693 SQLiteStmtUse
use(stmtRegisterValidPath
);
694 stmtRegisterValidPath
.bind(info
.path
);
695 stmtRegisterValidPath
.bind("sha256:" + printHash(info
.hash
));
696 stmtRegisterValidPath
.bind(info
.registrationTime
== 0 ? time(0) : info
.registrationTime
);
697 if (info
.deriver
!= "")
698 stmtRegisterValidPath
.bind(info
.deriver
);
700 stmtRegisterValidPath
.bind(); // null
701 if (info
.narSize
!= 0)
702 stmtRegisterValidPath
.bind64(info
.narSize
);
704 stmtRegisterValidPath
.bind(); // null
705 if (sqlite3_step(stmtRegisterValidPath
) != SQLITE_DONE
)
706 throwSQLiteError(db
, format("registering valid path `%1%' in database") % info
.path
);
707 unsigned long long id
= sqlite3_last_insert_rowid(db
);
709 /* If this is a derivation, then store the derivation outputs in
710 the database. This is useful for the garbage collector: it can
711 efficiently query whether a path is an output of some
713 if (isDerivation(info
.path
)) {
714 Derivation drv
= readDerivation(info
.path
);
716 /* Verify that the output paths in the derivation are correct
717 (i.e., follow the scheme for computing output paths from
718 derivations). Note that if this throws an error, then the
719 DB transaction is rolled back, so the path validity
720 registration above is undone. */
721 if (checkOutputs
) checkDerivationOutputs(info
.path
, drv
);
723 foreach (DerivationOutputs::iterator
, i
, drv
.outputs
) {
724 SQLiteStmtUse
use(stmtAddDerivationOutput
);
725 stmtAddDerivationOutput
.bind(id
);
726 stmtAddDerivationOutput
.bind(i
->first
);
727 stmtAddDerivationOutput
.bind(i
->second
.path
);
728 if (sqlite3_step(stmtAddDerivationOutput
) != SQLITE_DONE
)
729 throwSQLiteError(db
, format("adding derivation output for `%1%' in database") % info
.path
);
737 void LocalStore::addReference(unsigned long long referrer
, unsigned long long reference
)
739 SQLiteStmtUse
use(stmtAddReference
);
740 stmtAddReference
.bind(referrer
);
741 stmtAddReference
.bind(reference
);
742 if (sqlite3_step(stmtAddReference
) != SQLITE_DONE
)
743 throwSQLiteError(db
, "adding reference to database");
747 void LocalStore::registerFailedPath(const Path
& path
)
750 SQLiteStmtUse
use(stmtRegisterFailedPath
);
751 stmtRegisterFailedPath
.bind(path
);
752 stmtRegisterFailedPath
.bind(time(0));
753 if (sqlite3_step(stmtRegisterFailedPath
) != SQLITE_DONE
)
754 throwSQLiteError(db
, format("registering failed path `%1%'") % path
);
759 bool LocalStore::hasPathFailed(const Path
& path
)
762 SQLiteStmtUse
use(stmtHasPathFailed
);
763 stmtHasPathFailed
.bind(path
);
764 int res
= sqlite3_step(stmtHasPathFailed
);
765 if (res
!= SQLITE_DONE
&& res
!= SQLITE_ROW
)
766 throwSQLiteError(db
, "querying whether path failed");
767 return res
== SQLITE_ROW
;
772 PathSet
LocalStore::queryFailedPaths()
775 SQLiteStmtUse
use(stmtQueryFailedPaths
);
779 while ((r
= sqlite3_step(stmtQueryFailedPaths
)) == SQLITE_ROW
) {
780 const char * s
= (const char *) sqlite3_column_text(stmtQueryFailedPaths
, 0);
785 if (r
!= SQLITE_DONE
)
786 throwSQLiteError(db
, "error querying failed paths");
793 void LocalStore::clearFailedPaths(const PathSet
& paths
)
798 foreach (PathSet::const_iterator
, i
, paths
) {
799 SQLiteStmtUse
use(stmtClearFailedPath
);
800 stmtClearFailedPath
.bind(*i
);
801 if (sqlite3_step(stmtClearFailedPath
) != SQLITE_DONE
)
802 throwSQLiteError(db
, format("clearing failed path `%1%' in database") % *i
);
810 Hash
parseHashField(const Path
& path
, const string
& s
)
812 string::size_type colon
= s
.find(':');
813 if (colon
== string::npos
)
814 throw Error(format("corrupt hash `%1%' in valid-path entry for `%2%'")
816 HashType ht
= parseHashType(string(s
, 0, colon
));
818 throw Error(format("unknown hash type `%1%' in valid-path entry for `%2%'")
819 % string(s
, 0, colon
) % path
);
820 return parseHash(ht
, string(s
, colon
+ 1));
824 ValidPathInfo
LocalStore::queryPathInfo(const Path
& path
)
829 assertStorePath(path
);
833 /* Get the path info. */
834 SQLiteStmtUse
use1(stmtQueryPathInfo
);
836 stmtQueryPathInfo
.bind(path
);
838 int r
= sqlite3_step(stmtQueryPathInfo
);
839 if (r
== SQLITE_DONE
) throw Error(format("path `%1%' is not valid") % path
);
840 if (r
!= SQLITE_ROW
) throwSQLiteError(db
, "querying path in database");
842 info
.id
= sqlite3_column_int(stmtQueryPathInfo
, 0);
844 const char * s
= (const char *) sqlite3_column_text(stmtQueryPathInfo
, 1);
846 info
.hash
= parseHashField(path
, s
);
848 info
.registrationTime
= sqlite3_column_int(stmtQueryPathInfo
, 2);
850 s
= (const char *) sqlite3_column_text(stmtQueryPathInfo
, 3);
851 if (s
) info
.deriver
= s
;
853 /* Note that narSize = NULL yields 0. */
854 info
.narSize
= sqlite3_column_int64(stmtQueryPathInfo
, 4);
856 /* Get the references. */
857 SQLiteStmtUse
use2(stmtQueryReferences
);
859 stmtQueryReferences
.bind(info
.id
);
861 while ((r
= sqlite3_step(stmtQueryReferences
)) == SQLITE_ROW
) {
862 s
= (const char *) sqlite3_column_text(stmtQueryReferences
, 0);
864 info
.references
.insert(s
);
867 if (r
!= SQLITE_DONE
)
868 throwSQLiteError(db
, format("error getting references of `%1%'") % path
);
875 /* Update path info in the database. Currently only updates the
877 void LocalStore::updatePathInfo(const ValidPathInfo
& info
)
879 SQLiteStmtUse
use(stmtUpdatePathInfo
);
880 if (info
.narSize
!= 0)
881 stmtUpdatePathInfo
.bind64(info
.narSize
);
883 stmtUpdatePathInfo
.bind(); // null
884 stmtUpdatePathInfo
.bind("sha256:" + printHash(info
.hash
));
885 stmtUpdatePathInfo
.bind(info
.path
);
886 if (sqlite3_step(stmtUpdatePathInfo
) != SQLITE_DONE
)
887 throwSQLiteError(db
, format("updating info of path `%1%' in database") % info
.path
);
891 unsigned long long LocalStore::queryValidPathId(const Path
& path
)
893 SQLiteStmtUse
use(stmtQueryPathInfo
);
894 stmtQueryPathInfo
.bind(path
);
895 int res
= sqlite3_step(stmtQueryPathInfo
);
896 if (res
== SQLITE_ROW
) return sqlite3_column_int(stmtQueryPathInfo
, 0);
897 if (res
== SQLITE_DONE
) throw Error(format("path `%1%' is not valid") % path
);
898 throwSQLiteError(db
, "querying path in database");
902 bool LocalStore::isValidPath_(const Path
& path
)
904 SQLiteStmtUse
use(stmtQueryPathInfo
);
905 stmtQueryPathInfo
.bind(path
);
906 int res
= sqlite3_step(stmtQueryPathInfo
);
907 if (res
!= SQLITE_DONE
&& res
!= SQLITE_ROW
)
908 throwSQLiteError(db
, "querying path in database");
909 return res
== SQLITE_ROW
;
913 bool LocalStore::isValidPath(const Path
& path
)
916 return isValidPath_(path
);
921 PathSet
LocalStore::queryValidPaths(const PathSet
& paths
)
925 foreach (PathSet::const_iterator
, i
, paths
)
926 if (isValidPath_(*i
)) res
.insert(*i
);
932 PathSet
LocalStore::queryAllValidPaths()
936 stmt
.create(db
, "select path from ValidPaths");
940 while ((r
= sqlite3_step(stmt
)) == SQLITE_ROW
) {
941 const char * s
= (const char *) sqlite3_column_text(stmt
, 0);
946 if (r
!= SQLITE_DONE
)
947 throwSQLiteError(db
, "error getting valid paths");
954 void LocalStore::queryReferences(const Path
& path
,
955 PathSet
& references
)
957 ValidPathInfo info
= queryPathInfo(path
);
958 references
.insert(info
.references
.begin(), info
.references
.end());
962 void LocalStore::queryReferrers_(const Path
& path
, PathSet
& referrers
)
964 SQLiteStmtUse
use(stmtQueryReferrers
);
966 stmtQueryReferrers
.bind(path
);
969 while ((r
= sqlite3_step(stmtQueryReferrers
)) == SQLITE_ROW
) {
970 const char * s
= (const char *) sqlite3_column_text(stmtQueryReferrers
, 0);
975 if (r
!= SQLITE_DONE
)
976 throwSQLiteError(db
, format("error getting references of `%1%'") % path
);
980 void LocalStore::queryReferrers(const Path
& path
, PathSet
& referrers
)
982 assertStorePath(path
);
984 queryReferrers_(path
, referrers
);
989 Path
LocalStore::queryDeriver(const Path
& path
)
991 return queryPathInfo(path
).deriver
;
995 PathSet
LocalStore::queryValidDerivers(const Path
& path
)
997 assertStorePath(path
);
1000 SQLiteStmtUse
use(stmtQueryValidDerivers
);
1001 stmtQueryValidDerivers
.bind(path
);
1005 while ((r
= sqlite3_step(stmtQueryValidDerivers
)) == SQLITE_ROW
) {
1006 const char * s
= (const char *) sqlite3_column_text(stmtQueryValidDerivers
, 1);
1011 if (r
!= SQLITE_DONE
)
1012 throwSQLiteError(db
, format("error getting valid derivers of `%1%'") % path
);
1019 PathSet
LocalStore::queryDerivationOutputs(const Path
& path
)
1022 SQLiteStmtUse
use(stmtQueryDerivationOutputs
);
1023 stmtQueryDerivationOutputs
.bind(queryValidPathId(path
));
1027 while ((r
= sqlite3_step(stmtQueryDerivationOutputs
)) == SQLITE_ROW
) {
1028 const char * s
= (const char *) sqlite3_column_text(stmtQueryDerivationOutputs
, 1);
1033 if (r
!= SQLITE_DONE
)
1034 throwSQLiteError(db
, format("error getting outputs of `%1%'") % path
);
1041 StringSet
LocalStore::queryDerivationOutputNames(const Path
& path
)
1044 SQLiteStmtUse
use(stmtQueryDerivationOutputs
);
1045 stmtQueryDerivationOutputs
.bind(queryValidPathId(path
));
1047 StringSet outputNames
;
1049 while ((r
= sqlite3_step(stmtQueryDerivationOutputs
)) == SQLITE_ROW
) {
1050 const char * s
= (const char *) sqlite3_column_text(stmtQueryDerivationOutputs
, 0);
1052 outputNames
.insert(s
);
1055 if (r
!= SQLITE_DONE
)
1056 throwSQLiteError(db
, format("error getting output names of `%1%'") % path
);
1063 Path
LocalStore::queryPathFromHashPart(const string
& hashPart
)
1065 if (hashPart
.size() != 32) throw Error("invalid hash part");
1067 Path prefix
= settings
.nixStore
+ "/" + hashPart
;
1070 SQLiteStmtUse
use(stmtQueryPathFromHashPart
);
1071 stmtQueryPathFromHashPart
.bind(prefix
);
1073 int res
= sqlite3_step(stmtQueryPathFromHashPart
);
1074 if (res
== SQLITE_DONE
) return "";
1075 if (res
!= SQLITE_ROW
) throwSQLiteError(db
, "finding path in database");
1077 const char * s
= (const char *) sqlite3_column_text(stmtQueryPathFromHashPart
, 0);
1078 return s
&& prefix
.compare(0, prefix
.size(), s
, prefix
.size()) == 0 ? s
: "";
1083 void LocalStore::setSubstituterEnv()
1085 if (didSetSubstituterEnv
) return;
1087 /* Pass configuration options (including those overridden with
1088 --option) to substituters. */
1089 setenv("_NIX_OPTIONS", settings
.pack().c_str(), 1);
1091 didSetSubstituterEnv
= true;
1095 void LocalStore::startSubstituter(const Path
& substituter
, RunningSubstituter
& run
)
1097 if (run
.disabled
|| run
.pid
!= -1) return;
1099 debug(format("starting substituter program `%1%'") % substituter
);
1101 Pipe toPipe
, fromPipe
, errorPipe
;
1107 setSubstituterEnv();
1109 run
.pid
= startProcess([&]() {
1110 if (dup2(toPipe
.readSide
, STDIN_FILENO
) == -1)
1111 throw SysError("dupping stdin");
1112 if (dup2(fromPipe
.writeSide
, STDOUT_FILENO
) == -1)
1113 throw SysError("dupping stdout");
1114 if (dup2(errorPipe
.writeSide
, STDERR_FILENO
) == -1)
1115 throw SysError("dupping stderr");
1116 execl(substituter
.c_str(), substituter
.c_str(), "--query", NULL
);
1117 throw SysError(format("executing `%1%'") % substituter
);
1120 run
.program
= baseNameOf(substituter
);
1121 run
.to
= toPipe
.writeSide
.borrow();
1122 run
.from
= run
.fromBuf
.fd
= fromPipe
.readSide
.borrow();
1123 run
.error
= errorPipe
.readSide
.borrow();
1125 toPipe
.readSide
.close();
1126 fromPipe
.writeSide
.close();
1127 errorPipe
.writeSide
.close();
1129 /* The substituter may exit right away if it's disabled in any way
1130 (e.g. copy-from-other-stores.pl will exit if no other stores
1133 getLineFromSubstituter(run
);
1134 } catch (EndOfFile
& e
) {
1138 run
.disabled
= true;
1139 if (run
.pid
.wait(true) != 0) throw;
1144 /* Read a line from the substituter's stdout, while also processing
1146 string
LocalStore::getLineFromSubstituter(RunningSubstituter
& run
)
1150 /* We might have stdout data left over from the last time. */
1151 if (run
.fromBuf
.hasData()) goto haveData
;
1158 FD_SET(run
.from
, &fds
);
1159 FD_SET(run
.error
, &fds
);
1161 /* Wait for data to appear on the substituter's stdout or
1163 if (select(run
.from
> run
.error
? run
.from
+ 1 : run
.error
+ 1, &fds
, 0, 0, 0) == -1) {
1164 if (errno
== EINTR
) continue;
1165 throw SysError("waiting for input from the substituter");
1168 /* Completely drain stderr before dealing with stdout. */
1169 if (FD_ISSET(run
.error
, &fds
)) {
1171 ssize_t n
= read(run
.error
, (unsigned char *) buf
, sizeof(buf
));
1173 if (errno
== EINTR
) continue;
1174 throw SysError("reading from substituter's stderr");
1176 if (n
== 0) throw EndOfFile(format("substituter `%1%' died unexpectedly") % run
.program
);
1178 string::size_type p
;
1179 while (((p
= err
.find('\n')) != string::npos
)
1180 || ((p
= err
.find('\r')) != string::npos
)) {
1181 string
thing(err
, 0, p
+ 1);
1182 writeToStderr(run
.program
+ ": " + thing
);
1183 err
= string(err
, p
+ 1);
1187 /* Read from stdout until we get a newline or the buffer is empty. */
1188 else if (run
.fromBuf
.hasData() || FD_ISSET(run
.from
, &fds
)) {
1194 if (!err
.empty()) printMsg(lvlError
, run
.program
+ ": " + err
);
1198 } while (run
.fromBuf
.hasData());
1204 template<class T
> T
LocalStore::getIntLineFromSubstituter(RunningSubstituter
& run
)
1206 string s
= getLineFromSubstituter(run
);
1208 if (!string2Int(s
, res
)) throw Error("integer expected from stream");
1213 PathSet
LocalStore::querySubstitutablePaths(const PathSet
& paths
)
1216 foreach (Paths::iterator
, i
, settings
.substituters
) {
1217 if (res
.size() == paths
.size()) break;
1218 RunningSubstituter
& run(runningSubstituters
[*i
]);
1219 startSubstituter(*i
, run
);
1220 if (run
.disabled
) continue;
1222 foreach (PathSet::const_iterator
, j
, paths
)
1223 if (res
.find(*j
) == res
.end()) { s
+= *j
; s
+= " "; }
1224 writeLine(run
.to
, s
);
1226 /* FIXME: we only read stderr when an error occurs, so
1227 substituters should only write (short) messages to
1228 stderr when they fail. I.e. they shouldn't write debug
1230 Path path
= getLineFromSubstituter(run
);
1231 if (path
== "") break;
1239 void LocalStore::querySubstitutablePathInfos(const Path
& substituter
,
1240 PathSet
& paths
, SubstitutablePathInfos
& infos
)
1242 RunningSubstituter
& run(runningSubstituters
[substituter
]);
1243 startSubstituter(substituter
, run
);
1244 if (run
.disabled
) return;
1247 foreach (PathSet::const_iterator
, i
, paths
)
1248 if (infos
.find(*i
) == infos
.end()) { s
+= *i
; s
+= " "; }
1249 writeLine(run
.to
, s
);
1252 Path path
= getLineFromSubstituter(run
);
1253 if (path
== "") break;
1254 if (paths
.find(path
) == paths
.end())
1255 throw Error(format("got unexpected path `%1%' from substituter") % path
);
1257 SubstitutablePathInfo
& info(infos
[path
]);
1258 info
.deriver
= getLineFromSubstituter(run
);
1259 if (info
.deriver
!= "") assertStorePath(info
.deriver
);
1260 int nrRefs
= getIntLineFromSubstituter
<int>(run
);
1262 Path p
= getLineFromSubstituter(run
);
1264 info
.references
.insert(p
);
1266 info
.downloadSize
= getIntLineFromSubstituter
<long long>(run
);
1267 info
.narSize
= getIntLineFromSubstituter
<long long>(run
);
1272 void LocalStore::querySubstitutablePathInfos(const PathSet
& paths
,
1273 SubstitutablePathInfos
& infos
)
1275 PathSet todo
= paths
;
1276 foreach (Paths::iterator
, i
, settings
.substituters
) {
1277 if (todo
.empty()) break;
1278 querySubstitutablePathInfos(*i
, todo
, infos
);
1283 Hash
LocalStore::queryPathHash(const Path
& path
)
1285 return queryPathInfo(path
).hash
;
1289 void LocalStore::registerValidPath(const ValidPathInfo
& info
)
1291 ValidPathInfos infos
;
1292 infos
.push_back(info
);
1293 registerValidPaths(infos
);
1297 void LocalStore::registerValidPaths(const ValidPathInfos
& infos
)
1299 /* SQLite will fsync by default, but the new valid paths may not be fsync-ed.
1300 * So some may want to fsync them before registering the validity, at the
1301 * expense of some speed of the path registering operation. */
1302 if (settings
.syncBeforeRegistering
) sync();
1308 foreach (ValidPathInfos::const_iterator
, i
, infos
) {
1309 assert(i
->hash
.type
== htSHA256
);
1310 if (isValidPath_(i
->path
))
1313 addValidPath(*i
, false);
1314 paths
.insert(i
->path
);
1317 foreach (ValidPathInfos::const_iterator
, i
, infos
) {
1318 unsigned long long referrer
= queryValidPathId(i
->path
);
1319 foreach (PathSet::iterator
, j
, i
->references
)
1320 addReference(referrer
, queryValidPathId(*j
));
1323 /* Check that the derivation outputs are correct. We can't do
1324 this in addValidPath() above, because the references might
1325 not be valid yet. */
1326 foreach (ValidPathInfos::const_iterator
, i
, infos
)
1327 if (isDerivation(i
->path
)) {
1328 // FIXME: inefficient; we already loaded the
1329 // derivation in addValidPath().
1330 Derivation drv
= readDerivation(i
->path
);
1331 checkDerivationOutputs(i
->path
, drv
);
1334 /* Do a topological sort of the paths. This will throw an
1335 error if a cycle is detected and roll back the
1336 transaction. Cycles can only occur when a derivation
1337 has multiple outputs. */
1338 topoSortPaths(*this, paths
);
1345 /* Invalidate a path. The caller is responsible for checking that
1346 there are no referrers. */
1347 void LocalStore::invalidatePath(const Path
& path
)
1349 debug(format("invalidating path `%1%'") % path
);
1351 drvHashes
.erase(path
);
1353 SQLiteStmtUse
use(stmtInvalidatePath
);
1355 stmtInvalidatePath
.bind(path
);
1357 if (sqlite3_step(stmtInvalidatePath
) != SQLITE_DONE
)
1358 throwSQLiteError(db
, format("invalidating path `%1%' in database") % path
);
1360 /* Note that the foreign key constraints on the Refs table take
1361 care of deleting the references entries for `path'. */
1365 Path
LocalStore::addToStoreFromDump(const string
& dump
, const string
& name
,
1366 bool recursive
, HashType hashAlgo
, bool repair
)
1368 Hash h
= hashString(hashAlgo
, dump
);
1370 Path dstPath
= makeFixedOutputPath(recursive
, hashAlgo
, h
, name
);
1372 addTempRoot(dstPath
);
1374 if (repair
|| !isValidPath(dstPath
)) {
1376 /* The first check above is an optimisation to prevent
1377 unnecessary lock acquisition. */
1379 PathLocks
outputLock(singleton
<PathSet
, Path
>(dstPath
));
1381 if (repair
|| !isValidPath(dstPath
)) {
1383 if (pathExists(dstPath
)) deletePath(dstPath
);
1386 StringSource
source(dump
);
1387 restorePath(dstPath
, source
);
1389 writeFile(dstPath
, dump
);
1391 canonicalisePathMetaData(dstPath
, -1);
1393 /* Register the SHA-256 hash of the NAR serialisation of
1394 the path in the database. We may just have computed it
1395 above (if called with recursive == true and hashAlgo ==
1396 sha256); otherwise, compute it here. */
1399 hash
.first
= hashAlgo
== htSHA256
? h
: hashString(htSHA256
, dump
);
1400 hash
.second
= dump
.size();
1402 hash
= hashPath(htSHA256
, dstPath
);
1404 optimisePath(dstPath
); // FIXME: combine with hashPath()
1407 info
.path
= dstPath
;
1408 info
.hash
= hash
.first
;
1409 info
.narSize
= hash
.second
;
1410 registerValidPath(info
);
1413 outputLock
.setDeletion(true);
1420 Path
LocalStore::addToStore(const string
& name
, const Path
& _srcPath
,
1421 bool recursive
, HashType hashAlgo
, PathFilter
& filter
, bool repair
)
1423 Path
srcPath(absPath(_srcPath
));
1424 debug(format("adding `%1%' to the store") % srcPath
);
1426 /* Read the whole path into memory. This is not a very scalable
1427 method for very large paths, but `copyPath' is mainly used for
1431 dumpPath(srcPath
, sink
, filter
);
1433 sink
.s
= readFile(srcPath
);
1435 return addToStoreFromDump(sink
.s
, name
, recursive
, hashAlgo
, repair
);
1439 Path
LocalStore::addTextToStore(const string
& name
, const string
& s
,
1440 const PathSet
& references
, bool repair
)
1442 Path dstPath
= computeStorePathForText(name
, s
, references
);
1444 addTempRoot(dstPath
);
1446 if (repair
|| !isValidPath(dstPath
)) {
1448 PathLocks
outputLock(singleton
<PathSet
, Path
>(dstPath
));
1450 if (repair
|| !isValidPath(dstPath
)) {
1452 if (pathExists(dstPath
)) deletePath(dstPath
);
1454 writeFile(dstPath
, s
);
1456 canonicalisePathMetaData(dstPath
, -1);
1458 HashResult hash
= hashPath(htSHA256
, dstPath
);
1460 optimisePath(dstPath
);
1463 info
.path
= dstPath
;
1464 info
.hash
= hash
.first
;
1465 info
.narSize
= hash
.second
;
1466 info
.references
= references
;
1467 registerValidPath(info
);
1470 outputLock
.setDeletion(true);
1477 struct HashAndWriteSink
: Sink
1481 HashAndWriteSink(Sink
& writeSink
) : writeSink(writeSink
), hashSink(htSHA256
)
1484 virtual void operator () (const unsigned char * data
, size_t len
)
1486 writeSink(data
, len
);
1487 hashSink(data
, len
);
1491 return hashSink
.currentHash().first
;
1496 #define EXPORT_MAGIC 0x4558494e
1499 static void checkSecrecy(const Path
& path
)
1502 if (stat(path
.c_str(), &st
))
1503 throw SysError(format("getting status of `%1%'") % path
);
1504 if ((st
.st_mode
& (S_IRWXG
| S_IRWXO
)) != 0)
1505 throw Error(format("file `%1%' should be secret (inaccessible to everybody else)!") % path
);
1509 void LocalStore::exportPath(const Path
& path
, bool sign
,
1512 assertStorePath(path
);
1514 printMsg(lvlInfo
, format("exporting path `%1%'") % path
);
1516 if (!isValidPath(path
))
1517 throw Error(format("path `%1%' is not valid") % path
);
1519 HashAndWriteSink
hashAndWriteSink(sink
);
1521 dumpPath(path
, hashAndWriteSink
);
1523 /* Refuse to export paths that have changed. This prevents
1524 filesystem corruption from spreading to other machines.
1525 Don't complain if the stored hash is zero (unknown). */
1526 Hash hash
= hashAndWriteSink
.currentHash();
1527 Hash storedHash
= queryPathHash(path
);
1528 if (hash
!= storedHash
&& storedHash
!= Hash(storedHash
.type
))
1529 throw Error(format("hash of path `%1%' has changed from `%2%' to `%3%'!") % path
1530 % printHash(storedHash
) % printHash(hash
));
1532 writeInt(EXPORT_MAGIC
, hashAndWriteSink
);
1534 writeString(path
, hashAndWriteSink
);
1537 queryReferences(path
, references
);
1538 writeStrings(references
, hashAndWriteSink
);
1540 Path deriver
= queryDeriver(path
);
1541 writeString(deriver
, hashAndWriteSink
);
1544 Hash hash
= hashAndWriteSink
.currentHash();
1546 writeInt(1, hashAndWriteSink
);
1548 Path tmpDir
= createTempDir();
1549 AutoDelete
delTmp(tmpDir
);
1550 Path hashFile
= tmpDir
+ "/hash";
1551 writeFile(hashFile
, printHash(hash
));
1553 Path secretKey
= settings
.nixConfDir
+ "/signing-key.sec";
1554 checkSecrecy(secretKey
);
1557 args
.push_back("rsautl");
1558 args
.push_back("-sign");
1559 args
.push_back("-inkey");
1560 args
.push_back(secretKey
);
1561 args
.push_back("-in");
1562 args
.push_back(hashFile
);
1563 string signature
= runProgram(OPENSSL_PATH
, true, args
);
1565 writeString(signature
, hashAndWriteSink
);
1568 writeInt(0, hashAndWriteSink
);
1572 struct HashAndReadSource
: Source
1574 Source
& readSource
;
1577 HashAndReadSource(Source
& readSource
) : readSource(readSource
), hashSink(htSHA256
)
1581 size_t read(unsigned char * data
, size_t len
)
1583 size_t n
= readSource
.read(data
, len
);
1584 if (hashing
) hashSink(data
, n
);
1590 /* Create a temporary directory in the store that won't be
1591 garbage-collected. */
1592 Path
LocalStore::createTempDirInStore()
1596 /* There is a slight possibility that `tmpDir' gets deleted by
1597 the GC between createTempDir() and addTempRoot(), so repeat
1598 until `tmpDir' exists. */
1599 tmpDir
= createTempDir(settings
.nixStore
);
1600 addTempRoot(tmpDir
);
1601 } while (!pathExists(tmpDir
));
1606 Path
LocalStore::importPath(bool requireSignature
, Source
& source
)
1608 HashAndReadSource
hashAndReadSource(source
);
1610 /* We don't yet know what store path this archive contains (the
1611 store path follows the archive data proper), and besides, we
1612 don't know yet whether the signature is valid. */
1613 Path tmpDir
= createTempDirInStore();
1614 AutoDelete
delTmp(tmpDir
);
1615 Path unpacked
= tmpDir
+ "/unpacked";
1617 restorePath(unpacked
, hashAndReadSource
);
1619 unsigned int magic
= readInt(hashAndReadSource
);
1620 if (magic
!= EXPORT_MAGIC
)
1621 throw Error("Nix archive cannot be imported; wrong format");
1623 Path dstPath
= readStorePath(hashAndReadSource
);
1625 PathSet references
= readStorePaths
<PathSet
>(hashAndReadSource
);
1627 Path deriver
= readString(hashAndReadSource
);
1628 if (deriver
!= "") assertStorePath(deriver
);
1630 Hash hash
= hashAndReadSource
.hashSink
.finish().first
;
1631 hashAndReadSource
.hashing
= false;
1633 bool haveSignature
= readInt(hashAndReadSource
) == 1;
1635 if (requireSignature
&& !haveSignature
)
1636 throw Error(format("imported archive of `%1%' lacks a signature") % dstPath
);
1638 if (haveSignature
) {
1639 string signature
= readString(hashAndReadSource
);
1641 if (requireSignature
) {
1642 Path sigFile
= tmpDir
+ "/sig";
1643 writeFile(sigFile
, signature
);
1646 args
.push_back("rsautl");
1647 args
.push_back("-verify");
1648 args
.push_back("-inkey");
1649 args
.push_back(settings
.nixConfDir
+ "/signing-key.pub");
1650 args
.push_back("-pubin");
1651 args
.push_back("-in");
1652 args
.push_back(sigFile
);
1653 string hash2
= runProgram(OPENSSL_PATH
, true, args
);
1655 /* Note: runProgram() throws an exception if the signature
1658 if (printHash(hash
) != hash2
)
1660 "signed hash doesn't match actual contents of imported "
1661 "archive; archive could be corrupt, or someone is trying "
1662 "to import a Trojan horse");
1666 /* Do the actual import. */
1668 /* !!! way too much code duplication with addTextToStore() etc. */
1669 addTempRoot(dstPath
);
1671 if (!isValidPath(dstPath
)) {
1673 PathLocks outputLock
;
1675 /* Lock the output path. But don't lock if we're being called
1676 from a build hook (whose parent process already acquired a
1677 lock on this path). */
1678 Strings locksHeld
= tokenizeString
<Strings
>(getEnv("NIX_HELD_LOCKS"));
1679 if (find(locksHeld
.begin(), locksHeld
.end(), dstPath
) == locksHeld
.end())
1680 outputLock
.lockPaths(singleton
<PathSet
, Path
>(dstPath
));
1682 if (!isValidPath(dstPath
)) {
1684 if (pathExists(dstPath
)) deletePath(dstPath
);
1686 if (rename(unpacked
.c_str(), dstPath
.c_str()) == -1)
1687 throw SysError(format("cannot move `%1%' to `%2%'")
1688 % unpacked
% dstPath
);
1690 canonicalisePathMetaData(dstPath
, -1);
1692 /* !!! if we were clever, we could prevent the hashPath()
1694 HashResult hash
= hashPath(htSHA256
, dstPath
);
1696 optimisePath(dstPath
); // FIXME: combine with hashPath()
1699 info
.path
= dstPath
;
1700 info
.hash
= hash
.first
;
1701 info
.narSize
= hash
.second
;
1702 info
.references
= references
;
1703 info
.deriver
= deriver
!= "" && isValidPath(deriver
) ? deriver
: "";
1704 registerValidPath(info
);
1707 outputLock
.setDeletion(true);
1714 Paths
LocalStore::importPaths(bool requireSignature
, Source
& source
)
1718 unsigned long long n
= readLongLong(source
);
1720 if (n
!= 1) throw Error("input doesn't look like something created by `nix-store --export'");
1721 res
.push_back(importPath(requireSignature
, source
));
1727 void LocalStore::invalidatePathChecked(const Path
& path
)
1729 assertStorePath(path
);
1734 if (isValidPath_(path
)) {
1735 PathSet referrers
; queryReferrers_(path
, referrers
);
1736 referrers
.erase(path
); /* ignore self-references */
1737 if (!referrers
.empty())
1738 throw PathInUse(format("cannot delete path `%1%' because it is in use by %2%")
1739 % path
% showPaths(referrers
));
1740 invalidatePath(path
);
1748 bool LocalStore::verifyStore(bool checkContents
, bool repair
)
1750 printMsg(lvlError
, format("reading the Nix store..."));
1752 bool errors
= false;
1754 /* Acquire the global GC lock to prevent a garbage collection. */
1755 AutoCloseFD fdGCLock
= openGCLock(ltWrite
);
1758 for (auto & i
: readDirectory(settings
.nixStore
)) store
.insert(i
.name
);
1760 /* Check whether all valid paths actually exist. */
1761 printMsg(lvlInfo
, "checking path existence...");
1763 PathSet validPaths2
= queryAllValidPaths(), validPaths
, done
;
1765 foreach (PathSet::iterator
, i
, validPaths2
)
1766 verifyPath(*i
, store
, done
, validPaths
, repair
, errors
);
1768 /* Release the GC lock so that checking content hashes (which can
1769 take ages) doesn't block the GC or builds. */
1772 /* Optionally, check the content hashes (slow). */
1773 if (checkContents
) {
1774 printMsg(lvlInfo
, "checking hashes...");
1776 Hash
nullHash(htSHA256
);
1778 foreach (PathSet::iterator
, i
, validPaths
) {
1780 ValidPathInfo info
= queryPathInfo(*i
);
1782 /* Check the content hash (optionally - slow). */
1783 printMsg(lvlTalkative
, format("checking contents of `%1%'") % *i
);
1784 HashResult current
= hashPath(info
.hash
.type
, *i
);
1786 if (info
.hash
!= nullHash
&& info
.hash
!= current
.first
) {
1787 printMsg(lvlError
, format("path `%1%' was modified! "
1788 "expected hash `%2%', got `%3%'")
1789 % *i
% printHash(info
.hash
) % printHash(current
.first
));
1790 if (repair
) repairPath(*i
); else errors
= true;
1793 bool update
= false;
1795 /* Fill in missing hashes. */
1796 if (info
.hash
== nullHash
) {
1797 printMsg(lvlError
, format("fixing missing hash on `%1%'") % *i
);
1798 info
.hash
= current
.first
;
1802 /* Fill in missing narSize fields (from old stores). */
1803 if (info
.narSize
== 0) {
1804 printMsg(lvlError
, format("updating size field on `%1%' to %2%") % *i
% current
.second
);
1805 info
.narSize
= current
.second
;
1809 if (update
) updatePathInfo(info
);
1813 } catch (Error
& e
) {
1814 /* It's possible that the path got GC'ed, so ignore
1815 errors on invalid paths. */
1816 if (isValidPath(*i
))
1817 printMsg(lvlError
, format("error: %1%") % e
.msg());
1819 printMsg(lvlError
, format("warning: %1%") % e
.msg());
1829 void LocalStore::verifyPath(const Path
& path
, const PathSet
& store
,
1830 PathSet
& done
, PathSet
& validPaths
, bool repair
, bool & errors
)
1834 if (done
.find(path
) != done
.end()) return;
1837 if (!isStorePath(path
)) {
1838 printMsg(lvlError
, format("path `%1%' is not in the Nix store") % path
);
1839 invalidatePath(path
);
1843 if (store
.find(baseNameOf(path
)) == store
.end()) {
1844 /* Check any referrers first. If we can invalidate them
1845 first, then we can invalidate this path as well. */
1846 bool canInvalidate
= true;
1847 PathSet referrers
; queryReferrers(path
, referrers
);
1848 foreach (PathSet::iterator
, i
, referrers
)
1850 verifyPath(*i
, store
, done
, validPaths
, repair
, errors
);
1851 if (validPaths
.find(*i
) != validPaths
.end())
1852 canInvalidate
= false;
1855 if (canInvalidate
) {
1856 printMsg(lvlError
, format("path `%1%' disappeared, removing from database...") % path
);
1857 invalidatePath(path
);
1859 printMsg(lvlError
, format("path `%1%' disappeared, but it still has valid referrers!") % path
);
1863 } catch (Error
& e
) {
1864 printMsg(lvlError
, format("warning: %1%") % e
.msg());
1873 validPaths
.insert(path
);
1877 bool LocalStore::pathContentsGood(const Path
& path
)
1879 std::map
<Path
, bool>::iterator i
= pathContentsGoodCache
.find(path
);
1880 if (i
!= pathContentsGoodCache
.end()) return i
->second
;
1881 printMsg(lvlInfo
, format("checking path `%1%'...") % path
);
1882 ValidPathInfo info
= queryPathInfo(path
);
1884 if (!pathExists(path
))
1887 HashResult current
= hashPath(info
.hash
.type
, path
);
1888 Hash
nullHash(htSHA256
);
1889 res
= info
.hash
== nullHash
|| info
.hash
== current
.first
;
1891 pathContentsGoodCache
[path
] = res
;
1892 if (!res
) printMsg(lvlError
, format("path `%1%' is corrupted or missing!") % path
);
1897 void LocalStore::markContentsGood(const Path
& path
)
1899 pathContentsGoodCache
[path
] = true;
1903 /* Functions for upgrading from the pre-SQLite database. */
1905 PathSet
LocalStore::queryValidPathsOld()
1908 for (auto & i
: readDirectory(settings
.nixDBPath
+ "/info"))
1909 if (i
.name
.at(0) != '.') paths
.insert(settings
.nixStore
+ "/" + i
.name
);
1914 ValidPathInfo
LocalStore::queryPathInfoOld(const Path
& path
)
1919 /* Read the info file. */
1920 string baseName
= baseNameOf(path
);
1921 Path infoFile
= (format("%1%/info/%2%") % settings
.nixDBPath
% baseName
).str();
1922 if (!pathExists(infoFile
))
1923 throw Error(format("path `%1%' is not valid") % path
);
1924 string info
= readFile(infoFile
);
1927 Strings lines
= tokenizeString
<Strings
>(info
, "\n");
1929 foreach (Strings::iterator
, i
, lines
) {
1930 string::size_type p
= i
->find(':');
1931 if (p
== string::npos
)
1932 throw Error(format("corrupt line in `%1%': %2%") % infoFile
% *i
);
1933 string
name(*i
, 0, p
);
1934 string
value(*i
, p
+ 2);
1935 if (name
== "References") {
1936 Strings refs
= tokenizeString
<Strings
>(value
, " ");
1937 res
.references
= PathSet(refs
.begin(), refs
.end());
1938 } else if (name
== "Deriver") {
1939 res
.deriver
= value
;
1940 } else if (name
== "Hash") {
1941 res
.hash
= parseHashField(path
, value
);
1942 } else if (name
== "Registered-At") {
1944 string2Int(value
, n
);
1945 res
.registrationTime
= n
;
1953 /* Upgrade from schema 5 (Nix 0.12) to schema 6 (Nix >= 0.15). */
1954 void LocalStore::upgradeStore6()
1956 printMsg(lvlError
, "upgrading Nix store to new schema (this may take a while)...");
1960 PathSet validPaths
= queryValidPathsOld();
1964 foreach (PathSet::iterator
, i
, validPaths
) {
1965 addValidPath(queryPathInfoOld(*i
), false);
1971 foreach (PathSet::iterator
, i
, validPaths
) {
1972 ValidPathInfo info
= queryPathInfoOld(*i
);
1973 unsigned long long referrer
= queryValidPathId(*i
);
1974 foreach (PathSet::iterator
, j
, info
.references
)
1975 addReference(referrer
, queryValidPathId(*j
));
1985 #if defined(FS_IOC_SETFLAGS) && defined(FS_IOC_GETFLAGS) && defined(FS_IMMUTABLE_FL)
1987 static void makeMutable(const Path
& path
)
1991 struct stat st
= lstat(path
);
1993 if (!S_ISDIR(st
.st_mode
) && !S_ISREG(st
.st_mode
)) return;
1995 if (S_ISDIR(st
.st_mode
)) {
1996 for (auto & i
: readDirectory(path
))
1997 makeMutable(path
+ "/" + i
.name
);
2000 /* The O_NOFOLLOW is important to prevent us from changing the
2001 mutable bit on the target of a symlink (which would be a
2003 AutoCloseFD fd
= open(path
.c_str(), O_RDONLY
| O_NOFOLLOW
);
2005 if (errno
== ELOOP
) return; // it's a symlink
2006 throw SysError(format("opening file `%1%'") % path
);
2009 unsigned int flags
= 0, old
;
2011 /* Silently ignore errors getting/setting the immutable flag so
2012 that we work correctly on filesystems that don't support it. */
2013 if (ioctl(fd
, FS_IOC_GETFLAGS
, &flags
)) return;
2015 flags
&= ~FS_IMMUTABLE_FL
;
2016 if (old
== flags
) return;
2017 if (ioctl(fd
, FS_IOC_SETFLAGS
, &flags
)) return;
2020 /* Upgrade from schema 6 (Nix 0.15) to schema 7 (Nix >= 1.3). */
2021 void LocalStore::upgradeStore7()
2023 if (getuid() != 0) return;
2024 printMsg(lvlError
, "removing immutable bits from the Nix store (this may take a while)...");
2025 makeMutable(settings
.nixStore
);
2030 void LocalStore::upgradeStore7()
2037 void LocalStore::vacuumDB()
2039 if (sqlite3_exec(db
, "vacuum;", 0, 0, 0) != SQLITE_OK
)
2040 throwSQLiteError(db
, "vacuuming SQLite database");