local-store.cc 55 KB

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