You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1640 lines
51 KiB

  1. #include "config.h"
  2. #include "local-store.hh"
  3. #include "globals.hh"
  4. #include "archive.hh"
  5. #include "pathlocks.hh"
  6. #include "worker-protocol.hh"
  7. #include "derivations.hh"
  8. #include "affinity.hh"
  9. #include <iostream>
  10. #include <algorithm>
  11. #include <cstring>
  12. #include <sys/types.h>
  13. #include <sys/stat.h>
  14. #include <sys/time.h>
  15. #include <unistd.h>
  16. #include <utime.h>
  17. #include <fcntl.h>
  18. #include <errno.h>
  19. #include <stdio.h>
  20. #include <time.h>
  21. #include <grp.h>
  22. #if HAVE_UNSHARE && HAVE_STATVFS && HAVE_SYS_MOUNT_H
  23. #include <sched.h>
  24. #include <sys/statvfs.h>
  25. #include <sys/mount.h>
  26. #endif
  27. #if HAVE_LINUX_FS_H
  28. #include <linux/fs.h>
  29. #include <sys/ioctl.h>
  30. #include <errno.h>
  31. #endif
  32. #include <sqlite3.h>
  33. namespace nix {
  34. void checkStoreNotSymlink()
  35. {
  36. if (getEnv("NIX_IGNORE_SYMLINK_STORE") == "1") return;
  37. Path path = settings.nixStore;
  38. struct stat st;
  39. while (path != "/") {
  40. if (lstat(path.c_str(), &st))
  41. throw SysError(format("getting status of `%1%'") % path);
  42. if (S_ISLNK(st.st_mode))
  43. throw Error(format(
  44. "the path `%1%' is a symlink; "
  45. "this is not allowed for the Nix store and its parent directories")
  46. % path);
  47. path = dirOf(path);
  48. }
  49. }
  50. LocalStore::LocalStore(bool reserveSpace)
  51. : didSetSubstituterEnv(false)
  52. {
  53. schemaPath = settings.nixDBPath + "/schema";
  54. if (settings.readOnlyMode) {
  55. openDB(false);
  56. return;
  57. }
  58. /* Create missing state directories if they don't already exist. */
  59. createDirs(settings.nixStore);
  60. makeStoreWritable();
  61. createDirs(linksDir = settings.nixStore + "/.links");
  62. Path profilesDir = settings.nixStateDir + "/profiles";
  63. createDirs(profilesDir);
  64. createDirs(settings.nixStateDir + "/temproots");
  65. createDirs(settings.nixDBPath);
  66. Path gcRootsDir = settings.nixStateDir + "/gcroots";
  67. if (!pathExists(gcRootsDir)) {
  68. createDirs(gcRootsDir);
  69. createSymlink(profilesDir, gcRootsDir + "/profiles");
  70. }
  71. /* Optionally, create directories and set permissions for a
  72. multi-user install. */
  73. if (getuid() == 0 && settings.buildUsersGroup != "") {
  74. Path perUserDir = profilesDir + "/per-user";
  75. createDirs(perUserDir);
  76. if (chmod(perUserDir.c_str(), 01777) == -1)
  77. throw SysError(format("could not set permissions on '%1%' to 1777") % perUserDir);
  78. mode_t perm = 01775;
  79. struct group * gr = getgrnam(settings.buildUsersGroup.c_str());
  80. if (!gr)
  81. throw Error(format("the group `%1%' specified in `build-users-group' does not exist")
  82. % settings.buildUsersGroup);
  83. else {
  84. struct stat st;
  85. if (stat(settings.nixStore.c_str(), &st))
  86. throw SysError(format("getting attributes of path '%1%'") % settings.nixStore);
  87. if (st.st_uid != 0 || st.st_gid != gr->gr_gid || (st.st_mode & ~S_IFMT) != perm) {
  88. if (chown(settings.nixStore.c_str(), 0, gr->gr_gid) == -1)
  89. throw SysError(format("changing ownership of path '%1%'") % settings.nixStore);
  90. if (chmod(settings.nixStore.c_str(), perm) == -1)
  91. throw SysError(format("changing permissions on path '%1%'") % settings.nixStore);
  92. }
  93. }
  94. }
  95. checkStoreNotSymlink();
  96. /* We can't open a SQLite database if the disk is full. Since
  97. this prevents the garbage collector from running when it's most
  98. needed, we reserve some dummy space that we can free just
  99. before doing a garbage collection. */
  100. try {
  101. Path reservedPath = settings.nixDBPath + "/reserved";
  102. if (reserveSpace) {
  103. struct stat st;
  104. if (stat(reservedPath.c_str(), &st) == -1 ||
  105. st.st_size != settings.reservedSize)
  106. {
  107. AutoCloseFD fd = open(reservedPath.c_str(), O_WRONLY | O_CREAT, 0600);
  108. int res = -1;
  109. #if HAVE_POSIX_FALLOCATE
  110. res = posix_fallocate(fd, 0, settings.reservedSize);
  111. #endif
  112. if (res == -1) {
  113. writeFull(fd, string(settings.reservedSize, 'X'));
  114. ftruncate(fd, settings.reservedSize);
  115. }
  116. }
  117. }
  118. else
  119. deletePath(reservedPath);
  120. } catch (SysError & e) { /* don't care about errors */
  121. }
  122. /* Acquire the big fat lock in shared mode to make sure that no
  123. schema upgrade is in progress. */
  124. try {
  125. Path globalLockPath = settings.nixDBPath + "/big-lock";
  126. globalLock = openLockFile(globalLockPath.c_str(), true);
  127. } catch (SysError & e) {
  128. if (e.errNo != EACCES) throw;
  129. settings.readOnlyMode = true;
  130. openDB(false);
  131. return;
  132. }
  133. if (!lockFile(globalLock, ltRead, false)) {
  134. printMsg(lvlError, "waiting for the big Nix store lock...");
  135. lockFile(globalLock, ltRead, true);
  136. }
  137. /* Check the current database schema and if necessary do an
  138. upgrade. */
  139. int curSchema = getSchema();
  140. if (curSchema > nixSchemaVersion)
  141. throw Error(format("current Nix store schema is version %1%, but I only support %2%")
  142. % curSchema % nixSchemaVersion);
  143. else if (curSchema == 0) { /* new store */
  144. curSchema = nixSchemaVersion;
  145. openDB(true);
  146. writeFile(schemaPath, (format("%1%") % nixSchemaVersion).str());
  147. }
  148. else if (curSchema < nixSchemaVersion) {
  149. /* Guix always used version 7 of the schema. */
  150. throw Error(
  151. format("Your store database uses an implausibly old schema, version %1%.")
  152. % curSchema);
  153. }
  154. else openDB(false);
  155. }
  156. LocalStore::~LocalStore()
  157. {
  158. try {
  159. foreach (RunningSubstituters::iterator, i, runningSubstituters) {
  160. if (i->second.disabled) continue;
  161. i->second.to.close();
  162. i->second.from.close();
  163. i->second.error.close();
  164. if (i->second.pid != -1)
  165. i->second.pid.wait(true);
  166. }
  167. } catch (...) {
  168. ignoreException();
  169. }
  170. try {
  171. if (fdTempRoots != -1) {
  172. fdTempRoots.close();
  173. unlink(fnTempRoots.c_str());
  174. }
  175. } catch (...) {
  176. ignoreException();
  177. }
  178. }
  179. int LocalStore::getSchema()
  180. {
  181. int curSchema = 0;
  182. if (pathExists(schemaPath)) {
  183. string s = readFile(schemaPath);
  184. if (!string2Int(s, curSchema))
  185. throw Error(format("`%1%' is corrupt") % schemaPath);
  186. }
  187. return curSchema;
  188. }
  189. void LocalStore::openDB(bool create)
  190. {
  191. if (access(settings.nixDBPath.c_str(), R_OK | W_OK))
  192. throw SysError(format("Nix database directory `%1%' is not writable") % settings.nixDBPath);
  193. /* Open the Nix database. */
  194. string dbPath = settings.nixDBPath + "/db.sqlite";
  195. if (sqlite3_open_v2(dbPath.c_str(), &db.db,
  196. SQLITE_OPEN_READWRITE | (create ? SQLITE_OPEN_CREATE : 0), 0) != SQLITE_OK)
  197. throw Error(format("cannot open Nix database `%1%'") % dbPath);
  198. if (sqlite3_busy_timeout(db, 60 * 60 * 1000) != SQLITE_OK)
  199. throwSQLiteError(db, "setting timeout");
  200. if (sqlite3_exec(db, "pragma foreign_keys = 1;", 0, 0, 0) != SQLITE_OK)
  201. throwSQLiteError(db, "enabling foreign keys");
  202. /* !!! check whether sqlite has been built with foreign key
  203. support */
  204. /* Whether SQLite should fsync(). "Normal" synchronous mode
  205. should be safe enough. If the user asks for it, don't sync at
  206. all. This can cause database corruption if the system
  207. crashes. */
  208. string syncMode = settings.fsyncMetadata ? "normal" : "off";
  209. if (sqlite3_exec(db, ("pragma synchronous = " + syncMode + ";").c_str(), 0, 0, 0) != SQLITE_OK)
  210. throwSQLiteError(db, "setting synchronous mode");
  211. /* Set the SQLite journal mode. WAL mode is fastest, so it's the
  212. default. */
  213. string mode = settings.useSQLiteWAL ? "wal" : "truncate";
  214. string prevMode;
  215. {
  216. SQLiteStmt stmt;
  217. stmt.create(db, "pragma main.journal_mode;");
  218. if (sqlite3_step(stmt) != SQLITE_ROW)
  219. throwSQLiteError(db, "querying journal mode");
  220. prevMode = string((const char *) sqlite3_column_text(stmt, 0));
  221. }
  222. if (prevMode != mode &&
  223. sqlite3_exec(db, ("pragma main.journal_mode = " + mode + ";").c_str(), 0, 0, 0) != SQLITE_OK)
  224. throwSQLiteError(db, "setting journal mode");
  225. /* Increase the auto-checkpoint interval to 40000 pages. This
  226. seems enough to ensure that instantiating the NixOS system
  227. derivation is done in a single fsync(). */
  228. if (mode == "wal" && sqlite3_exec(db, "pragma wal_autocheckpoint = 40000;", 0, 0, 0) != SQLITE_OK)
  229. throwSQLiteError(db, "setting autocheckpoint interval");
  230. /* Initialise the database schema, if necessary. */
  231. if (create) {
  232. const char * schema =
  233. #include "schema.sql.hh"
  234. ;
  235. if (sqlite3_exec(db, (const char *) schema, 0, 0, 0) != SQLITE_OK)
  236. throwSQLiteError(db, "initialising database schema");
  237. }
  238. /* Prepare SQL statements. */
  239. stmtRegisterValidPath.create(db,
  240. "insert into ValidPaths (path, hash, registrationTime, deriver, narSize) values (?, ?, ?, ?, ?);");
  241. stmtUpdatePathInfo.create(db,
  242. "update ValidPaths set narSize = ?, hash = ? where path = ?;");
  243. stmtAddReference.create(db,
  244. "insert or replace into Refs (referrer, reference) values (?, ?);");
  245. stmtQueryPathInfo.create(db,
  246. "select id, hash, registrationTime, deriver, narSize from ValidPaths where path = ?;");
  247. stmtQueryReferences.create(db,
  248. "select path from Refs join ValidPaths on reference = id where referrer = ?;");
  249. stmtQueryReferrers.create(db,
  250. "select path from Refs join ValidPaths on referrer = id where reference = (select id from ValidPaths where path = ?);");
  251. stmtInvalidatePath.create(db,
  252. "delete from ValidPaths where path = ?;");
  253. stmtRegisterFailedPath.create(db,
  254. "insert or ignore into FailedPaths (path, time) values (?, ?);");
  255. stmtHasPathFailed.create(db,
  256. "select time from FailedPaths where path = ?;");
  257. stmtQueryFailedPaths.create(db,
  258. "select path from FailedPaths;");
  259. // If the path is a derivation, then clear its outputs.
  260. stmtClearFailedPath.create(db,
  261. "delete from FailedPaths where ?1 = '*' or path = ?1 "
  262. "or path in (select d.path from DerivationOutputs d join ValidPaths v on d.drv = v.id where v.path = ?1);");
  263. stmtAddDerivationOutput.create(db,
  264. "insert or replace into DerivationOutputs (drv, id, path) values (?, ?, ?);");
  265. stmtQueryValidDerivers.create(db,
  266. "select v.id, v.path from DerivationOutputs d join ValidPaths v on d.drv = v.id where d.path = ?;");
  267. stmtQueryDerivationOutputs.create(db,
  268. "select id, path from DerivationOutputs where drv = ?;");
  269. // Use "path >= ?" with limit 1 rather than "path like '?%'" to
  270. // ensure efficient lookup.
  271. stmtQueryPathFromHashPart.create(db,
  272. "select path from ValidPaths where path >= ? limit 1;");
  273. stmtQueryValidPaths.create(db, "select path from ValidPaths");
  274. }
  275. /* To improve purity, users may want to make the Nix store a read-only
  276. bind mount. So make the Nix store writable for this process. */
  277. void LocalStore::makeStoreWritable()
  278. {
  279. #if HAVE_UNSHARE && HAVE_STATVFS && HAVE_SYS_MOUNT_H && defined(MS_BIND) && defined(MS_REMOUNT)
  280. if (getuid() != 0) return;
  281. /* Check if /nix/store is on a read-only mount. */
  282. struct statvfs stat;
  283. if (statvfs(settings.nixStore.c_str(), &stat) != 0)
  284. throw SysError("getting info about the Nix store mount point");
  285. if (stat.f_flag & ST_RDONLY) {
  286. if (unshare(CLONE_NEWNS) == -1)
  287. throw SysError("setting up a private mount namespace");
  288. if (mount(0, settings.nixStore.c_str(), "none", MS_REMOUNT | MS_BIND, 0) == -1)
  289. throw SysError(format("remounting %1% writable") % settings.nixStore);
  290. }
  291. #endif
  292. }
  293. const time_t mtimeStore = 1; /* 1 second into the epoch */
  294. static void canonicaliseTimestampAndPermissions(const Path & path, const struct stat & st)
  295. {
  296. if (!S_ISLNK(st.st_mode)) {
  297. /* Mask out all type related bits. */
  298. mode_t mode = st.st_mode & ~S_IFMT;
  299. if (mode != 0444 && mode != 0555) {
  300. mode = (st.st_mode & S_IFMT)
  301. | 0444
  302. | (st.st_mode & S_IXUSR ? 0111 : 0);
  303. if (chmod(path.c_str(), mode) == -1)
  304. throw SysError(format("changing mode of `%1%' to %2$o") % path % mode);
  305. }
  306. }
  307. if (st.st_mtime != mtimeStore) {
  308. struct timeval times[2];
  309. times[0].tv_sec = st.st_atime;
  310. times[0].tv_usec = 0;
  311. times[1].tv_sec = mtimeStore;
  312. times[1].tv_usec = 0;
  313. #if HAVE_LUTIMES
  314. if (lutimes(path.c_str(), times) == -1)
  315. if (errno != ENOSYS ||
  316. (!S_ISLNK(st.st_mode) && utimes(path.c_str(), times) == -1))
  317. #else
  318. if (!S_ISLNK(st.st_mode) && utimes(path.c_str(), times) == -1)
  319. #endif
  320. throw SysError(format("changing modification time of `%1%'") % path);
  321. }
  322. }
  323. void canonicaliseTimestampAndPermissions(const Path & path)
  324. {
  325. struct stat st;
  326. if (lstat(path.c_str(), &st))
  327. throw SysError(format("getting attributes of path `%1%'") % path);
  328. canonicaliseTimestampAndPermissions(path, st);
  329. }
  330. static void canonicalisePathMetaData_(const Path & path, uid_t fromUid, InodesSeen & inodesSeen)
  331. {
  332. checkInterrupt();
  333. struct stat st;
  334. if (lstat(path.c_str(), &st))
  335. throw SysError(format("getting attributes of path `%1%'") % path);
  336. /* Really make sure that the path is of a supported type. */
  337. if (!(S_ISREG(st.st_mode) || S_ISDIR(st.st_mode) || S_ISLNK(st.st_mode)))
  338. throw Error(format("file ‘%1%’ has an unsupported type") % path);
  339. /* Fail if the file is not owned by the build user. This prevents
  340. us from messing up the ownership/permissions of files
  341. hard-linked into the output (e.g. "ln /etc/shadow $out/foo").
  342. However, ignore files that we chown'ed ourselves previously to
  343. ensure that we don't fail on hard links within the same build
  344. (i.e. "touch $out/foo; ln $out/foo $out/bar"). */
  345. if (fromUid != (uid_t) -1 && st.st_uid != fromUid) {
  346. assert(!S_ISDIR(st.st_mode));
  347. if (inodesSeen.find(Inode(st.st_dev, st.st_ino)) == inodesSeen.end())
  348. throw BuildError(format("invalid ownership on file `%1%'") % path);
  349. mode_t mode = st.st_mode & ~S_IFMT;
  350. assert(S_ISLNK(st.st_mode) || (st.st_uid == geteuid() && (mode == 0444 || mode == 0555) && st.st_mtime == mtimeStore));
  351. return;
  352. }
  353. inodesSeen.insert(Inode(st.st_dev, st.st_ino));
  354. canonicaliseTimestampAndPermissions(path, st);
  355. /* Change ownership to the current uid. If it's a symlink, use
  356. lchown if available, otherwise don't bother. Wrong ownership
  357. of a symlink doesn't matter, since the owning user can't change
  358. the symlink and can't delete it because the directory is not
  359. writable. The only exception is top-level paths in the Nix
  360. store (since that directory is group-writable for the Nix build
  361. users group); we check for this case below. */
  362. if (st.st_uid != geteuid()) {
  363. #if HAVE_LCHOWN
  364. if (lchown(path.c_str(), geteuid(), getegid()) == -1)
  365. #else
  366. if (!S_ISLNK(st.st_mode) &&
  367. chown(path.c_str(), geteuid(), getegid()) == -1)
  368. #endif
  369. throw SysError(format("changing owner of `%1%' to %2%")
  370. % path % geteuid());
  371. }
  372. if (S_ISDIR(st.st_mode)) {
  373. DirEntries entries = readDirectory(path);
  374. for (auto & i : entries)
  375. canonicalisePathMetaData_(path + "/" + i.name, fromUid, inodesSeen);
  376. }
  377. }
  378. void canonicalisePathMetaData(const Path & path, uid_t fromUid, InodesSeen & inodesSeen)
  379. {
  380. canonicalisePathMetaData_(path, fromUid, inodesSeen);
  381. /* On platforms that don't have lchown(), the top-level path can't
  382. be a symlink, since we can't change its ownership. */
  383. struct stat st;
  384. if (lstat(path.c_str(), &st))
  385. throw SysError(format("getting attributes of path `%1%'") % path);
  386. if (st.st_uid != geteuid()) {
  387. assert(S_ISLNK(st.st_mode));
  388. throw Error(format("wrong ownership of top-level store path `%1%'") % path);
  389. }
  390. }
  391. void canonicalisePathMetaData(const Path & path, uid_t fromUid)
  392. {
  393. InodesSeen inodesSeen;
  394. canonicalisePathMetaData(path, fromUid, inodesSeen);
  395. }
  396. void LocalStore::checkDerivationOutputs(const Path & drvPath, const Derivation & drv)
  397. {
  398. string drvName = storePathToName(drvPath);
  399. assert(isDerivation(drvName));
  400. drvName = string(drvName, 0, drvName.size() - drvExtension.size());
  401. if (isFixedOutputDrv(drv)) {
  402. DerivationOutputs::const_iterator out = drv.outputs.find("out");
  403. if (out == drv.outputs.end())
  404. throw Error(format("derivation `%1%' does not have an output named `out'") % drvPath);
  405. bool recursive; HashType ht; Hash h;
  406. out->second.parseHashInfo(recursive, ht, h);
  407. Path outPath = makeFixedOutputPath(recursive, ht, h, drvName);
  408. StringPairs::const_iterator j = drv.env.find("out");
  409. if (out->second.path != outPath || j == drv.env.end() || j->second != outPath)
  410. throw Error(format("derivation `%1%' has incorrect output `%2%', should be `%3%'")
  411. % drvPath % out->second.path % outPath);
  412. }
  413. else {
  414. Derivation drvCopy(drv);
  415. foreach (DerivationOutputs::iterator, i, drvCopy.outputs) {
  416. i->second.path = "";
  417. drvCopy.env[i->first] = "";
  418. }
  419. Hash h = hashDerivationModulo(*this, drvCopy);
  420. foreach (DerivationOutputs::const_iterator, i, drv.outputs) {
  421. Path outPath = makeOutputPath(i->first, h, drvName);
  422. StringPairs::const_iterator j = drv.env.find(i->first);
  423. if (i->second.path != outPath || j == drv.env.end() || j->second != outPath)
  424. throw Error(format("derivation `%1%' has incorrect output `%2%', should be `%3%'")
  425. % drvPath % i->second.path % outPath);
  426. }
  427. }
  428. }
  429. uint64_t LocalStore::addValidPath(const ValidPathInfo & info, bool checkOutputs)
  430. {
  431. stmtRegisterValidPath.use()
  432. (info.path)
  433. ("sha256:" + printHash(info.hash))
  434. (info.registrationTime == 0 ? time(0) : info.registrationTime)
  435. (info.deriver, info.deriver != "")
  436. (info.narSize, info.narSize != 0)
  437. .exec();
  438. uint64_t id = sqlite3_last_insert_rowid(db);
  439. /* If this is a derivation, then store the derivation outputs in
  440. the database. This is useful for the garbage collector: it can
  441. efficiently query whether a path is an output of some
  442. derivation. */
  443. if (isDerivation(info.path)) {
  444. Derivation drv = readDerivation(info.path);
  445. /* Verify that the output paths in the derivation are correct
  446. (i.e., follow the scheme for computing output paths from
  447. derivations). Note that if this throws an error, then the
  448. DB transaction is rolled back, so the path validity
  449. registration above is undone. */
  450. if (checkOutputs) checkDerivationOutputs(info.path, drv);
  451. for (auto & i : drv.outputs) {
  452. stmtAddDerivationOutput.use()
  453. (id)
  454. (i.first)
  455. (i.second.path)
  456. .exec();
  457. }
  458. }
  459. return id;
  460. }
  461. void LocalStore::addReference(uint64_t referrer, uint64_t reference)
  462. {
  463. stmtAddReference.use()(referrer)(reference).exec();
  464. }
  465. void LocalStore::registerFailedPath(const Path & path)
  466. {
  467. retrySQLite<void>([&]() {
  468. stmtRegisterFailedPath.use()(path)(time(0)).step();
  469. });
  470. }
  471. bool LocalStore::hasPathFailed(const Path & path)
  472. {
  473. return retrySQLite<bool>([&]() {
  474. return stmtHasPathFailed.use()(path).next();
  475. });
  476. }
  477. PathSet LocalStore::queryFailedPaths()
  478. {
  479. return retrySQLite<PathSet>([&]() {
  480. auto useQueryFailedPaths(stmtQueryFailedPaths.use());
  481. PathSet res;
  482. while (useQueryFailedPaths.next())
  483. res.insert(useQueryFailedPaths.getStr(0));
  484. return res;
  485. });
  486. }
  487. void LocalStore::clearFailedPaths(const PathSet & paths)
  488. {
  489. retrySQLite<void>([&]() {
  490. SQLiteTxn txn(db);
  491. for (auto & path : paths)
  492. stmtClearFailedPath.use()(path).exec();
  493. txn.commit();
  494. });
  495. }
  496. Hash parseHashField(const Path & path, const string & s)
  497. {
  498. string::size_type colon = s.find(':');
  499. if (colon == string::npos)
  500. throw Error(format("corrupt hash `%1%' in valid-path entry for `%2%'")
  501. % s % path);
  502. HashType ht = parseHashType(string(s, 0, colon));
  503. if (ht == htUnknown)
  504. throw Error(format("unknown hash type `%1%' in valid-path entry for `%2%'")
  505. % string(s, 0, colon) % path);
  506. return parseHash(ht, string(s, colon + 1));
  507. }
  508. ValidPathInfo LocalStore::queryPathInfo(const Path & path)
  509. {
  510. ValidPathInfo info;
  511. info.path = path;
  512. assertStorePath(path);
  513. return retrySQLite<ValidPathInfo>([&]() {
  514. /* Get the path info. */
  515. auto useQueryPathInfo(stmtQueryPathInfo.use()(path));
  516. if (!useQueryPathInfo.next())
  517. throw Error(format("path `%1%' is not valid") % path);
  518. info.id = useQueryPathInfo.getInt(0);
  519. info.hash = parseHashField(path, useQueryPathInfo.getStr(1));
  520. info.registrationTime = useQueryPathInfo.getInt(2);
  521. auto s = (const char *) sqlite3_column_text(stmtQueryPathInfo, 3);
  522. if (s) info.deriver = s;
  523. /* Note that narSize = NULL yields 0. */
  524. info.narSize = useQueryPathInfo.getInt(4);
  525. /* Get the references. */
  526. auto useQueryReferences(stmtQueryReferences.use()(info.id));
  527. while (useQueryReferences.next())
  528. info.references.insert(useQueryReferences.getStr(0));
  529. return info;
  530. });
  531. }
  532. /* Update path info in the database. Currently only updates the
  533. narSize field. */
  534. void LocalStore::updatePathInfo(const ValidPathInfo & info)
  535. {
  536. stmtUpdatePathInfo.use()
  537. (info.narSize, info.narSize != 0)
  538. ("sha256:" + printHash(info.hash))
  539. (info.path)
  540. .exec();
  541. }
  542. uint64_t LocalStore::queryValidPathId(const Path & path)
  543. {
  544. auto use(stmtQueryPathInfo.use()(path));
  545. if (!use.next())
  546. throw Error(format("path ‘%1%’ is not valid") % path);
  547. return use.getInt(0);
  548. }
  549. bool LocalStore::isValidPath_(const Path & path)
  550. {
  551. return stmtQueryPathInfo.use()(path).next();
  552. }
  553. bool LocalStore::isValidPath(const Path & path)
  554. {
  555. return retrySQLite<bool>([&]() {
  556. return isValidPath_(path);
  557. });
  558. }
  559. PathSet LocalStore::queryValidPaths(const PathSet & paths)
  560. {
  561. return retrySQLite<PathSet>([&]() {
  562. PathSet res;
  563. foreach (PathSet::const_iterator, i, paths)
  564. if (isValidPath_(*i)) res.insert(*i);
  565. return res;
  566. });
  567. }
  568. PathSet LocalStore::queryAllValidPaths()
  569. {
  570. return retrySQLite<PathSet>([&]() {
  571. auto use(stmtQueryValidPaths.use());
  572. PathSet res;
  573. while (use.next()) res.insert(use.getStr(0));
  574. return res;
  575. });
  576. }
  577. void LocalStore::queryReferences(const Path & path,
  578. PathSet & references)
  579. {
  580. ValidPathInfo info = queryPathInfo(path);
  581. references.insert(info.references.begin(), info.references.end());
  582. }
  583. void LocalStore::queryReferrers_(const Path & path, PathSet & referrers)
  584. {
  585. auto useQueryReferrers(stmtQueryReferrers.use()(path));
  586. while (useQueryReferrers.next())
  587. referrers.insert(useQueryReferrers.getStr(0));
  588. }
  589. void LocalStore::queryReferrers(const Path & path, PathSet & referrers)
  590. {
  591. assertStorePath(path);
  592. return retrySQLite<void>([&]() {
  593. queryReferrers_(path, referrers);
  594. });
  595. }
  596. Path LocalStore::queryDeriver(const Path & path)
  597. {
  598. return queryPathInfo(path).deriver;
  599. }
  600. PathSet LocalStore::queryValidDerivers(const Path & path)
  601. {
  602. assertStorePath(path);
  603. return retrySQLite<PathSet>([&]() {
  604. auto useQueryValidDerivers(stmtQueryValidDerivers.use()(path));
  605. PathSet derivers;
  606. while (useQueryValidDerivers.next())
  607. derivers.insert(useQueryValidDerivers.getStr(1));
  608. return derivers;
  609. });
  610. }
  611. PathSet LocalStore::queryDerivationOutputs(const Path & path)
  612. {
  613. return retrySQLite<PathSet>([&]() {
  614. auto useQueryDerivationOutputs(stmtQueryDerivationOutputs.use()(queryValidPathId(path)));
  615. PathSet outputs;
  616. while (useQueryDerivationOutputs.next())
  617. outputs.insert(useQueryDerivationOutputs.getStr(1));
  618. return outputs;
  619. });
  620. }
  621. StringSet LocalStore::queryDerivationOutputNames(const Path & path)
  622. {
  623. return retrySQLite<StringSet>([&]() {
  624. auto useQueryDerivationOutputs(stmtQueryDerivationOutputs.use()(queryValidPathId(path)));
  625. StringSet outputNames;
  626. while (useQueryDerivationOutputs.next())
  627. outputNames.insert(useQueryDerivationOutputs.getStr(0));
  628. return outputNames;
  629. });
  630. }
  631. Path LocalStore::queryPathFromHashPart(const string & hashPart)
  632. {
  633. if (hashPart.size() != 32) throw Error("invalid hash part");
  634. Path prefix = settings.nixStore + "/" + hashPart;
  635. return retrySQLite<Path>([&]() -> Path {
  636. auto useQueryPathFromHashPart(stmtQueryPathFromHashPart.use()(prefix));
  637. if (!useQueryPathFromHashPart.next()) return "";
  638. const char * s = (const char *) sqlite3_column_text(stmtQueryPathFromHashPart, 0);
  639. return s && prefix.compare(0, prefix.size(), s, prefix.size()) == 0 ? s : "";
  640. });
  641. }
  642. void LocalStore::setSubstituterEnv()
  643. {
  644. if (didSetSubstituterEnv) return;
  645. /* Pass configuration options (including those overridden with
  646. --option) to substituters. */
  647. setenv("_NIX_OPTIONS", settings.pack().c_str(), 1);
  648. didSetSubstituterEnv = true;
  649. }
  650. void LocalStore::startSubstituter(const Path & substituter, RunningSubstituter & run)
  651. {
  652. if (run.disabled || run.pid != -1) return;
  653. debug(format("starting substituter program `%1%'") % substituter);
  654. Pipe toPipe, fromPipe, errorPipe;
  655. toPipe.create();
  656. fromPipe.create();
  657. errorPipe.create();
  658. setSubstituterEnv();
  659. run.pid = startProcess([&]() {
  660. if (dup2(toPipe.readSide, STDIN_FILENO) == -1)
  661. throw SysError("dupping stdin");
  662. if (dup2(fromPipe.writeSide, STDOUT_FILENO) == -1)
  663. throw SysError("dupping stdout");
  664. if (dup2(errorPipe.writeSide, STDERR_FILENO) == -1)
  665. throw SysError("dupping stderr");
  666. execl(substituter.c_str(), substituter.c_str(), "--query", NULL);
  667. throw SysError(format("executing `%1%'") % substituter);
  668. });
  669. run.program = baseNameOf(substituter);
  670. run.to = toPipe.writeSide.borrow();
  671. run.from = run.fromBuf.fd = fromPipe.readSide.borrow();
  672. run.error = errorPipe.readSide.borrow();
  673. toPipe.readSide.close();
  674. fromPipe.writeSide.close();
  675. errorPipe.writeSide.close();
  676. /* The substituter may exit right away if it's disabled in any way
  677. (e.g. copy-from-other-stores.pl will exit if no other stores
  678. are configured). */
  679. try {
  680. getLineFromSubstituter(run);
  681. } catch (EndOfFile & e) {
  682. run.to.close();
  683. run.from.close();
  684. run.error.close();
  685. run.disabled = true;
  686. if (run.pid.wait(true) != 0) throw;
  687. }
  688. }
  689. /* Read a line from the substituter's stdout, while also processing
  690. its stderr. */
  691. string LocalStore::getLineFromSubstituter(RunningSubstituter & run)
  692. {
  693. string res, err;
  694. /* We might have stdout data left over from the last time. */
  695. if (run.fromBuf.hasData()) goto haveData;
  696. while (1) {
  697. checkInterrupt();
  698. fd_set fds;
  699. FD_ZERO(&fds);
  700. FD_SET(run.from, &fds);
  701. FD_SET(run.error, &fds);
  702. /* Wait for data to appear on the substituter's stdout or
  703. stderr. */
  704. if (select(run.from > run.error ? run.from + 1 : run.error + 1, &fds, 0, 0, 0) == -1) {
  705. if (errno == EINTR) continue;
  706. throw SysError("waiting for input from the substituter");
  707. }
  708. /* Completely drain stderr before dealing with stdout. */
  709. if (FD_ISSET(run.error, &fds)) {
  710. char buf[4096];
  711. ssize_t n = read(run.error, (unsigned char *) buf, sizeof(buf));
  712. if (n == -1) {
  713. if (errno == EINTR) continue;
  714. throw SysError("reading from substituter's stderr");
  715. }
  716. if (n == 0) throw EndOfFile(format("substituter `%1%' died unexpectedly") % run.program);
  717. err.append(buf, n);
  718. string::size_type p;
  719. while (((p = err.find('\n')) != string::npos)
  720. || ((p = err.find('\r')) != string::npos)) {
  721. string thing(err, 0, p + 1);
  722. writeToStderr(run.program + ": " + thing);
  723. err = string(err, p + 1);
  724. }
  725. }
  726. /* Read from stdout until we get a newline or the buffer is empty. */
  727. else if (run.fromBuf.hasData() || FD_ISSET(run.from, &fds)) {
  728. haveData:
  729. do {
  730. unsigned char c;
  731. run.fromBuf(&c, 1);
  732. if (c == '\n') {
  733. if (!err.empty()) printMsg(lvlError, run.program + ": " + err);
  734. return res;
  735. }
  736. res += c;
  737. } while (run.fromBuf.hasData());
  738. }
  739. }
  740. }
  741. template<class T> T LocalStore::getIntLineFromSubstituter(RunningSubstituter & run)
  742. {
  743. string s = getLineFromSubstituter(run);
  744. T res;
  745. if (!string2Int(s, res)) throw Error("integer expected from stream");
  746. return res;
  747. }
  748. PathSet LocalStore::querySubstitutablePaths(const PathSet & paths)
  749. {
  750. PathSet res;
  751. if (!settings.useSubstitutes) return res;
  752. foreach (Paths::iterator, i, settings.substituters) {
  753. if (res.size() == paths.size()) break;
  754. RunningSubstituter & run(runningSubstituters[*i]);
  755. startSubstituter(*i, run);
  756. if (run.disabled) continue;
  757. string s = "have ";
  758. foreach (PathSet::const_iterator, j, paths)
  759. if (res.find(*j) == res.end()) { s += *j; s += " "; }
  760. writeLine(run.to, s);
  761. while (true) {
  762. /* FIXME: we only read stderr when an error occurs, so
  763. substituters should only write (short) messages to
  764. stderr when they fail. I.e. they shouldn't write debug
  765. output. */
  766. Path path = getLineFromSubstituter(run);
  767. if (path == "") break;
  768. res.insert(path);
  769. }
  770. }
  771. return res;
  772. }
  773. void LocalStore::querySubstitutablePathInfos(const Path & substituter,
  774. PathSet & paths, SubstitutablePathInfos & infos)
  775. {
  776. if (!settings.useSubstitutes) return;
  777. RunningSubstituter & run(runningSubstituters[substituter]);
  778. startSubstituter(substituter, run);
  779. if (run.disabled) return;
  780. string s = "info ";
  781. foreach (PathSet::const_iterator, i, paths)
  782. if (infos.find(*i) == infos.end()) { s += *i; s += " "; }
  783. writeLine(run.to, s);
  784. while (true) {
  785. Path path = getLineFromSubstituter(run);
  786. if (path == "") break;
  787. if (paths.find(path) == paths.end())
  788. throw Error(format("got unexpected path `%1%' from substituter") % path);
  789. paths.erase(path);
  790. SubstitutablePathInfo & info(infos[path]);
  791. info.deriver = getLineFromSubstituter(run);
  792. if (info.deriver != "") assertStorePath(info.deriver);
  793. int nrRefs = getIntLineFromSubstituter<int>(run);
  794. while (nrRefs--) {
  795. Path p = getLineFromSubstituter(run);
  796. assertStorePath(p);
  797. info.references.insert(p);
  798. }
  799. info.downloadSize = getIntLineFromSubstituter<long long>(run);
  800. info.narSize = getIntLineFromSubstituter<long long>(run);
  801. }
  802. }
  803. void LocalStore::querySubstitutablePathInfos(const PathSet & paths,
  804. SubstitutablePathInfos & infos)
  805. {
  806. PathSet todo = paths;
  807. foreach (Paths::iterator, i, settings.substituters) {
  808. if (todo.empty()) break;
  809. querySubstitutablePathInfos(*i, todo, infos);
  810. }
  811. }
  812. Hash LocalStore::queryPathHash(const Path & path)
  813. {
  814. return queryPathInfo(path).hash;
  815. }
  816. void LocalStore::registerValidPath(const ValidPathInfo & info)
  817. {
  818. ValidPathInfos infos;
  819. infos.push_back(info);
  820. registerValidPaths(infos);
  821. }
  822. void LocalStore::registerValidPaths(const ValidPathInfos & infos)
  823. {
  824. /* SQLite will fsync by default, but the new valid paths may not be fsync-ed.
  825. * So some may want to fsync them before registering the validity, at the
  826. * expense of some speed of the path registering operation. */
  827. if (settings.syncBeforeRegistering) sync();
  828. return retrySQLite<void>([&]() {
  829. SQLiteTxn txn(db);
  830. PathSet paths;
  831. foreach (ValidPathInfos::const_iterator, i, infos) {
  832. assert(i->hash.type == htSHA256);
  833. if (isValidPath_(i->path))
  834. updatePathInfo(*i);
  835. else
  836. addValidPath(*i, false);
  837. paths.insert(i->path);
  838. }
  839. for (auto & i : infos) {
  840. auto referrer = queryValidPathId(i.path);
  841. for (auto & j : i.references)
  842. addReference(referrer, queryValidPathId(j));
  843. }
  844. /* Check that the derivation outputs are correct. We can't do
  845. this in addValidPath() above, because the references might
  846. not be valid yet. */
  847. foreach (ValidPathInfos::const_iterator, i, infos)
  848. if (isDerivation(i->path)) {
  849. // FIXME: inefficient; we already loaded the
  850. // derivation in addValidPath().
  851. Derivation drv = readDerivation(i->path);
  852. checkDerivationOutputs(i->path, drv);
  853. }
  854. /* Do a topological sort of the paths. This will throw an
  855. error if a cycle is detected and roll back the
  856. transaction. Cycles can only occur when a derivation
  857. has multiple outputs. */
  858. topoSortPaths(*this, paths);
  859. txn.commit();
  860. });
  861. }
  862. /* Invalidate a path. The caller is responsible for checking that
  863. there are no referrers. */
  864. void LocalStore::invalidatePath(const Path & path)
  865. {
  866. debug(format("invalidating path `%1%'") % path);
  867. drvHashes.erase(path);
  868. stmtInvalidatePath.use()(path).exec();
  869. /* Note that the foreign key constraints on the Refs table take
  870. care of deleting the references entries for `path'. */
  871. }
  872. Path LocalStore::addToStoreFromDump(const string & dump, const string & name,
  873. bool recursive, HashType hashAlgo, bool repair)
  874. {
  875. Hash h = hashString(hashAlgo, dump);
  876. Path dstPath = makeFixedOutputPath(recursive, hashAlgo, h, name);
  877. addTempRoot(dstPath);
  878. if (repair || !isValidPath(dstPath)) {
  879. /* The first check above is an optimisation to prevent
  880. unnecessary lock acquisition. */
  881. PathLocks outputLock(singleton<PathSet, Path>(dstPath));
  882. if (repair || !isValidPath(dstPath)) {
  883. if (pathExists(dstPath)) deletePath(dstPath);
  884. if (recursive) {
  885. StringSource source(dump);
  886. restorePath(dstPath, source);
  887. } else
  888. writeFile(dstPath, dump);
  889. canonicalisePathMetaData(dstPath, -1);
  890. /* Register the SHA-256 hash of the NAR serialisation of
  891. the path in the database. We may just have computed it
  892. above (if called with recursive == true and hashAlgo ==
  893. sha256); otherwise, compute it here. */
  894. HashResult hash;
  895. if (recursive) {
  896. hash.first = hashAlgo == htSHA256 ? h : hashString(htSHA256, dump);
  897. hash.second = dump.size();
  898. } else
  899. hash = hashPath(htSHA256, dstPath);
  900. optimisePath(dstPath); // FIXME: combine with hashPath()
  901. ValidPathInfo info;
  902. info.path = dstPath;
  903. info.hash = hash.first;
  904. info.narSize = hash.second;
  905. registerValidPath(info);
  906. }
  907. outputLock.setDeletion(true);
  908. }
  909. return dstPath;
  910. }
  911. Path LocalStore::addToStore(const string & name, const Path & _srcPath,
  912. bool recursive, HashType hashAlgo, PathFilter & filter, bool repair)
  913. {
  914. Path srcPath(absPath(_srcPath));
  915. debug(format("adding `%1%' to the store") % srcPath);
  916. /* Read the whole path into memory. This is not a very scalable
  917. method for very large paths, but `copyPath' is mainly used for
  918. small files. */
  919. StringSink sink;
  920. if (recursive)
  921. dumpPath(srcPath, sink, filter);
  922. else
  923. sink.s = readFile(srcPath);
  924. return addToStoreFromDump(sink.s, name, recursive, hashAlgo, repair);
  925. }
  926. Path LocalStore::addTextToStore(const string & name, const string & s,
  927. const PathSet & references, bool repair)
  928. {
  929. Path dstPath = computeStorePathForText(name, s, references);
  930. addTempRoot(dstPath);
  931. if (repair || !isValidPath(dstPath)) {
  932. PathLocks outputLock(singleton<PathSet, Path>(dstPath));
  933. if (repair || !isValidPath(dstPath)) {
  934. if (pathExists(dstPath)) deletePath(dstPath);
  935. writeFile(dstPath, s);
  936. canonicalisePathMetaData(dstPath, -1);
  937. HashResult hash = hashPath(htSHA256, dstPath);
  938. optimisePath(dstPath);
  939. ValidPathInfo info;
  940. info.path = dstPath;
  941. info.hash = hash.first;
  942. info.narSize = hash.second;
  943. info.references = references;
  944. registerValidPath(info);
  945. }
  946. outputLock.setDeletion(true);
  947. }
  948. return dstPath;
  949. }
  950. struct HashAndWriteSink : Sink
  951. {
  952. Sink & writeSink;
  953. HashSink hashSink;
  954. HashAndWriteSink(Sink & writeSink) : writeSink(writeSink), hashSink(htSHA256)
  955. {
  956. }
  957. virtual void operator () (const unsigned char * data, size_t len)
  958. {
  959. writeSink(data, len);
  960. hashSink(data, len);
  961. }
  962. Hash currentHash()
  963. {
  964. return hashSink.currentHash().first;
  965. }
  966. };
  967. #define EXPORT_MAGIC 0x4558494e
  968. static void checkSecrecy(const Path & path)
  969. {
  970. struct stat st;
  971. if (stat(path.c_str(), &st))
  972. throw SysError(format("getting status of `%1%'") % path);
  973. if ((st.st_mode & (S_IRWXG | S_IRWXO)) != 0)
  974. throw Error(format("file `%1%' should be secret (inaccessible to everybody else)!") % path);
  975. }
  976. static std::string runAuthenticationProgram(const Strings & args)
  977. {
  978. /* Use the 'authenticate' script from 'LIBEXECDIR/guix' or just
  979. 'LIBEXECDIR', depending on whether we're uninstalled or not. */
  980. const bool installed = getenv("GUIX_UNINSTALLED") == NULL;
  981. const string program = settings.nixLibexecDir
  982. + (installed ? "/guix" : "")
  983. + "/authenticate";
  984. return runProgram(program, false, args);
  985. }
  986. void LocalStore::exportPath(const Path & path, bool sign,
  987. Sink & sink)
  988. {
  989. assertStorePath(path);
  990. printMsg(lvlInfo, format("exporting path `%1%'") % path);
  991. if (!isValidPath(path))
  992. throw Error(format("path `%1%' is not valid") % path);
  993. HashAndWriteSink hashAndWriteSink(sink);
  994. dumpPath(path, hashAndWriteSink);
  995. /* Refuse to export paths that have changed. This prevents
  996. filesystem corruption from spreading to other machines.
  997. Don't complain if the stored hash is zero (unknown). */
  998. Hash hash = hashAndWriteSink.currentHash();
  999. Hash storedHash = queryPathHash(path);
  1000. if (hash != storedHash && storedHash != Hash(storedHash.type))
  1001. throw Error(format("hash of path `%1%' has changed from `%2%' to `%3%'!") % path
  1002. % printHash(storedHash) % printHash(hash));
  1003. writeInt(EXPORT_MAGIC, hashAndWriteSink);
  1004. writeString(path, hashAndWriteSink);
  1005. PathSet references;
  1006. queryReferences(path, references);
  1007. writeStrings(references, hashAndWriteSink);
  1008. Path deriver = queryDeriver(path);
  1009. writeString(deriver, hashAndWriteSink);
  1010. if (sign) {
  1011. Hash hash = hashAndWriteSink.currentHash();
  1012. writeInt(1, hashAndWriteSink);
  1013. Path tmpDir = createTempDir();
  1014. AutoDelete delTmp(tmpDir);
  1015. Path hashFile = tmpDir + "/hash";
  1016. writeFile(hashFile, printHash(hash));
  1017. Path secretKey = settings.nixConfDir + "/signing-key.sec";
  1018. checkSecrecy(secretKey);
  1019. Strings args;
  1020. args.push_back("rsautl");
  1021. args.push_back("-sign");
  1022. args.push_back("-inkey");
  1023. args.push_back(secretKey);
  1024. args.push_back("-in");
  1025. args.push_back(hashFile);
  1026. string signature = runAuthenticationProgram(args);
  1027. writeString(signature, hashAndWriteSink);
  1028. } else
  1029. writeInt(0, hashAndWriteSink);
  1030. }
  1031. struct HashAndReadSource : Source
  1032. {
  1033. Source & readSource;
  1034. HashSink hashSink;
  1035. bool hashing;
  1036. HashAndReadSource(Source & readSource) : readSource(readSource), hashSink(htSHA256)
  1037. {
  1038. hashing = true;
  1039. }
  1040. size_t read(unsigned char * data, size_t len)
  1041. {
  1042. size_t n = readSource.read(data, len);
  1043. if (hashing) hashSink(data, n);
  1044. return n;
  1045. }
  1046. };
  1047. /* Create a temporary directory in the store that won't be
  1048. garbage-collected. */
  1049. Path LocalStore::createTempDirInStore()
  1050. {
  1051. Path tmpDir;
  1052. do {
  1053. /* There is a slight possibility that `tmpDir' gets deleted by
  1054. the GC between createTempDir() and addTempRoot(), so repeat
  1055. until `tmpDir' exists. */
  1056. tmpDir = createTempDir(settings.nixStore);
  1057. addTempRoot(tmpDir);
  1058. } while (!pathExists(tmpDir));
  1059. return tmpDir;
  1060. }
  1061. Path LocalStore::importPath(bool requireSignature, Source & source)
  1062. {
  1063. HashAndReadSource hashAndReadSource(source);
  1064. /* We don't yet know what store path this archive contains (the
  1065. store path follows the archive data proper), and besides, we
  1066. don't know yet whether the signature is valid. */
  1067. Path tmpDir = createTempDirInStore();
  1068. AutoDelete delTmp(tmpDir);
  1069. Path unpacked = tmpDir + "/unpacked";
  1070. restorePath(unpacked, hashAndReadSource);
  1071. unsigned int magic = readInt(hashAndReadSource);
  1072. if (magic != EXPORT_MAGIC)
  1073. throw Error("Nix archive cannot be imported; wrong format");
  1074. Path dstPath = readStorePath(hashAndReadSource);
  1075. PathSet references = readStorePaths<PathSet>(hashAndReadSource);
  1076. Path deriver = readString(hashAndReadSource);
  1077. if (deriver != "") assertStorePath(deriver);
  1078. Hash hash = hashAndReadSource.hashSink.finish().first;
  1079. hashAndReadSource.hashing = false;
  1080. bool haveSignature = readInt(hashAndReadSource) == 1;
  1081. if (requireSignature && !haveSignature)
  1082. throw Error(format("imported archive of `%1%' lacks a signature") % dstPath);
  1083. if (haveSignature) {
  1084. string signature = readString(hashAndReadSource);
  1085. if (requireSignature) {
  1086. Path sigFile = tmpDir + "/sig";
  1087. writeFile(sigFile, signature);
  1088. Strings args;
  1089. args.push_back("rsautl");
  1090. args.push_back("-verify");
  1091. args.push_back("-inkey");
  1092. args.push_back(settings.nixConfDir + "/signing-key.pub");
  1093. args.push_back("-pubin");
  1094. args.push_back("-in");
  1095. args.push_back(sigFile);
  1096. string hash2 = runAuthenticationProgram(args);
  1097. /* Note: runProgram() throws an exception if the signature
  1098. is invalid. */
  1099. if (printHash(hash) != hash2)
  1100. throw Error(
  1101. "signed hash doesn't match actual contents of imported "
  1102. "archive; archive could be corrupt, or someone is trying "
  1103. "to import a Trojan horse");
  1104. }
  1105. }
  1106. /* Do the actual import. */
  1107. /* !!! way too much code duplication with addTextToStore() etc. */
  1108. addTempRoot(dstPath);
  1109. if (!isValidPath(dstPath)) {
  1110. PathLocks outputLock;
  1111. /* Lock the output path. But don't lock if we're being called
  1112. from a build hook (whose parent process already acquired a
  1113. lock on this path). */
  1114. Strings locksHeld = tokenizeString<Strings>(getEnv("NIX_HELD_LOCKS"));
  1115. if (find(locksHeld.begin(), locksHeld.end(), dstPath) == locksHeld.end())
  1116. outputLock.lockPaths(singleton<PathSet, Path>(dstPath));
  1117. if (!isValidPath(dstPath)) {
  1118. if (pathExists(dstPath)) deletePath(dstPath);
  1119. if (rename(unpacked.c_str(), dstPath.c_str()) == -1)
  1120. throw SysError(format("cannot move `%1%' to `%2%'")
  1121. % unpacked % dstPath);
  1122. canonicalisePathMetaData(dstPath, -1);
  1123. /* !!! if we were clever, we could prevent the hashPath()
  1124. here. */
  1125. HashResult hash = hashPath(htSHA256, dstPath);
  1126. optimisePath(dstPath); // FIXME: combine with hashPath()
  1127. ValidPathInfo info;
  1128. info.path = dstPath;
  1129. info.hash = hash.first;
  1130. info.narSize = hash.second;
  1131. info.references = references;
  1132. info.deriver = deriver != "" && isValidPath(deriver) ? deriver : "";
  1133. registerValidPath(info);
  1134. }
  1135. outputLock.setDeletion(true);
  1136. }
  1137. return dstPath;
  1138. }
  1139. Paths LocalStore::importPaths(bool requireSignature, Source & source)
  1140. {
  1141. Paths res;
  1142. while (true) {
  1143. unsigned long long n = readLongLong(source);
  1144. if (n == 0) break;
  1145. if (n != 1) throw Error("input doesn't look like something created by `nix-store --export'");
  1146. res.push_back(importPath(requireSignature, source));
  1147. }
  1148. return res;
  1149. }
  1150. void LocalStore::invalidatePathChecked(const Path & path)
  1151. {
  1152. assertStorePath(path);
  1153. retrySQLite<void>([&]() {
  1154. SQLiteTxn txn(db);
  1155. if (isValidPath_(path)) {
  1156. PathSet referrers; queryReferrers_(path, referrers);
  1157. referrers.erase(path); /* ignore self-references */
  1158. if (!referrers.empty())
  1159. throw PathInUse(format("cannot delete path `%1%' because it is in use by %2%")
  1160. % path % showPaths(referrers));
  1161. invalidatePath(path);
  1162. }
  1163. txn.commit();
  1164. });
  1165. }
  1166. bool LocalStore::verifyStore(bool checkContents, bool repair)
  1167. {
  1168. printMsg(lvlError, format("reading the Nix store..."));
  1169. bool errors = false;
  1170. /* Acquire the global GC lock to prevent a garbage collection. */
  1171. AutoCloseFD fdGCLock = openGCLock(ltWrite);
  1172. PathSet store;
  1173. for (auto & i : readDirectory(settings.nixStore)) store.insert(i.name);
  1174. /* Check whether all valid paths actually exist. */
  1175. printMsg(lvlInfo, "checking path existence...");
  1176. PathSet validPaths2 = queryAllValidPaths(), validPaths, done;
  1177. foreach (PathSet::iterator, i, validPaths2)
  1178. verifyPath(*i, store, done, validPaths, repair, errors);
  1179. /* Release the GC lock so that checking content hashes (which can
  1180. take ages) doesn't block the GC or builds. */
  1181. fdGCLock.close();
  1182. /* Optionally, check the content hashes (slow). */
  1183. if (checkContents) {
  1184. printMsg(lvlInfo, "checking hashes...");
  1185. Hash nullHash(htSHA256);
  1186. foreach (PathSet::iterator, i, validPaths) {
  1187. try {
  1188. ValidPathInfo info = queryPathInfo(*i);
  1189. /* Check the content hash (optionally - slow). */
  1190. printMsg(lvlTalkative, format("checking contents of `%1%'") % *i);
  1191. HashResult current = hashPath(info.hash.type, *i);
  1192. if (info.hash != nullHash && info.hash != current.first) {
  1193. printMsg(lvlError, format("path `%1%' was modified! "
  1194. "expected hash `%2%', got `%3%'")
  1195. % *i % printHash(info.hash) % printHash(current.first));
  1196. if (repair) repairPath(*i); else errors = true;
  1197. } else {
  1198. bool update = false;
  1199. /* Fill in missing hashes. */
  1200. if (info.hash == nullHash) {
  1201. printMsg(lvlError, format("fixing missing hash on `%1%'") % *i);
  1202. info.hash = current.first;
  1203. update = true;
  1204. }
  1205. /* Fill in missing narSize fields (from old stores). */
  1206. if (info.narSize == 0) {
  1207. printMsg(lvlError, format("updating size field on `%1%' to %2%") % *i % current.second);
  1208. info.narSize = current.second;
  1209. update = true;
  1210. }
  1211. if (update) updatePathInfo(info);
  1212. }
  1213. } catch (Error & e) {
  1214. /* It's possible that the path got GC'ed, so ignore
  1215. errors on invalid paths. */
  1216. if (isValidPath(*i))
  1217. printMsg(lvlError, format("error: %1%") % e.msg());
  1218. else
  1219. printMsg(lvlError, format("warning: %1%") % e.msg());
  1220. errors = true;
  1221. }
  1222. }
  1223. }
  1224. return errors;
  1225. }
  1226. void LocalStore::verifyPath(const Path & path, const PathSet & store,
  1227. PathSet & done, PathSet & validPaths, bool repair, bool & errors)
  1228. {
  1229. checkInterrupt();
  1230. if (done.find(path) != done.end()) return;
  1231. done.insert(path);
  1232. if (!isStorePath(path)) {
  1233. printMsg(lvlError, format("path `%1%' is not in the Nix store") % path);
  1234. invalidatePath(path);
  1235. return;
  1236. }
  1237. if (store.find(baseNameOf(path)) == store.end()) {
  1238. /* Check any referrers first. If we can invalidate them
  1239. first, then we can invalidate this path as well. */
  1240. bool canInvalidate = true;
  1241. PathSet referrers; queryReferrers(path, referrers);
  1242. foreach (PathSet::iterator, i, referrers)
  1243. if (*i != path) {
  1244. verifyPath(*i, store, done, validPaths, repair, errors);
  1245. if (validPaths.find(*i) != validPaths.end())
  1246. canInvalidate = false;
  1247. }
  1248. if (canInvalidate) {
  1249. printMsg(lvlError, format("path `%1%' disappeared, removing from database...") % path);
  1250. invalidatePath(path);
  1251. } else {
  1252. printMsg(lvlError, format("path `%1%' disappeared, but it still has valid referrers!") % path);
  1253. if (repair)
  1254. try {
  1255. repairPath(path);
  1256. } catch (Error & e) {
  1257. printMsg(lvlError, format("warning: %1%") % e.msg());
  1258. errors = true;
  1259. }
  1260. else errors = true;
  1261. }
  1262. return;
  1263. }
  1264. validPaths.insert(path);
  1265. }
  1266. bool LocalStore::pathContentsGood(const Path & path)
  1267. {
  1268. std::map<Path, bool>::iterator i = pathContentsGoodCache.find(path);
  1269. if (i != pathContentsGoodCache.end()) return i->second;
  1270. printMsg(lvlInfo, format("checking path `%1%'...") % path);
  1271. ValidPathInfo info = queryPathInfo(path);
  1272. bool res;
  1273. if (!pathExists(path))
  1274. res = false;
  1275. else {
  1276. HashResult current = hashPath(info.hash.type, path);
  1277. Hash nullHash(htSHA256);
  1278. res = info.hash == nullHash || info.hash == current.first;
  1279. }
  1280. pathContentsGoodCache[path] = res;
  1281. if (!res) printMsg(lvlError, format("path `%1%' is corrupted or missing!") % path);
  1282. return res;
  1283. }
  1284. void LocalStore::markContentsGood(const Path & path)
  1285. {
  1286. pathContentsGoodCache[path] = true;
  1287. }
  1288. void LocalStore::vacuumDB()
  1289. {
  1290. if (sqlite3_exec(db, "vacuum;", 0, 0, 0) != SQLITE_OK)
  1291. throwSQLiteError(db, "vacuuming SQLite database");
  1292. }
  1293. }