local-store.cc 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634
  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 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 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 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("store database directory `%1%' is not writable") % settings.nixDBPath);
  193. /* Open the store 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 store 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 store a read-only
  276. bind mount. So make the 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 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
  360. store (since that directory is group-writable for the 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. return runProgram(settings.nixLibexecDir + "/authenticate",
  979. false, args);
  980. }
  981. void LocalStore::exportPath(const Path & path, bool sign,
  982. Sink & sink)
  983. {
  984. assertStorePath(path);
  985. printMsg(lvlInfo, format("exporting path `%1%'") % path);
  986. if (!isValidPath(path))
  987. throw Error(format("path `%1%' is not valid") % path);
  988. HashAndWriteSink hashAndWriteSink(sink);
  989. dumpPath(path, hashAndWriteSink);
  990. /* Refuse to export paths that have changed. This prevents
  991. filesystem corruption from spreading to other machines.
  992. Don't complain if the stored hash is zero (unknown). */
  993. Hash hash = hashAndWriteSink.currentHash();
  994. Hash storedHash = queryPathHash(path);
  995. if (hash != storedHash && storedHash != Hash(storedHash.type))
  996. throw Error(format("hash of path `%1%' has changed from `%2%' to `%3%'!") % path
  997. % printHash(storedHash) % printHash(hash));
  998. writeInt(EXPORT_MAGIC, hashAndWriteSink);
  999. writeString(path, hashAndWriteSink);
  1000. PathSet references;
  1001. queryReferences(path, references);
  1002. writeStrings(references, hashAndWriteSink);
  1003. Path deriver = queryDeriver(path);
  1004. writeString(deriver, hashAndWriteSink);
  1005. if (sign) {
  1006. Hash hash = hashAndWriteSink.currentHash();
  1007. writeInt(1, hashAndWriteSink);
  1008. Path tmpDir = createTempDir();
  1009. AutoDelete delTmp(tmpDir);
  1010. Path hashFile = tmpDir + "/hash";
  1011. writeFile(hashFile, printHash(hash));
  1012. Path secretKey = settings.nixConfDir + "/signing-key.sec";
  1013. checkSecrecy(secretKey);
  1014. Strings args;
  1015. args.push_back("rsautl");
  1016. args.push_back("-sign");
  1017. args.push_back("-inkey");
  1018. args.push_back(secretKey);
  1019. args.push_back("-in");
  1020. args.push_back(hashFile);
  1021. string signature = runAuthenticationProgram(args);
  1022. writeString(signature, hashAndWriteSink);
  1023. } else
  1024. writeInt(0, hashAndWriteSink);
  1025. }
  1026. struct HashAndReadSource : Source
  1027. {
  1028. Source & readSource;
  1029. HashSink hashSink;
  1030. bool hashing;
  1031. HashAndReadSource(Source & readSource) : readSource(readSource), hashSink(htSHA256)
  1032. {
  1033. hashing = true;
  1034. }
  1035. size_t read(unsigned char * data, size_t len)
  1036. {
  1037. size_t n = readSource.read(data, len);
  1038. if (hashing) hashSink(data, n);
  1039. return n;
  1040. }
  1041. };
  1042. /* Create a temporary directory in the store that won't be
  1043. garbage-collected. */
  1044. Path LocalStore::createTempDirInStore()
  1045. {
  1046. Path tmpDir;
  1047. do {
  1048. /* There is a slight possibility that `tmpDir' gets deleted by
  1049. the GC between createTempDir() and addTempRoot(), so repeat
  1050. until `tmpDir' exists. */
  1051. tmpDir = createTempDir(settings.nixStore);
  1052. addTempRoot(tmpDir);
  1053. } while (!pathExists(tmpDir));
  1054. return tmpDir;
  1055. }
  1056. Path LocalStore::importPath(bool requireSignature, Source & source)
  1057. {
  1058. HashAndReadSource hashAndReadSource(source);
  1059. /* We don't yet know what store path this archive contains (the
  1060. store path follows the archive data proper), and besides, we
  1061. don't know yet whether the signature is valid. */
  1062. Path tmpDir = createTempDirInStore();
  1063. AutoDelete delTmp(tmpDir);
  1064. Path unpacked = tmpDir + "/unpacked";
  1065. restorePath(unpacked, hashAndReadSource);
  1066. unsigned int magic = readInt(hashAndReadSource);
  1067. if (magic != EXPORT_MAGIC)
  1068. throw Error("normalized archive cannot be imported; wrong format");
  1069. Path dstPath = readStorePath(hashAndReadSource);
  1070. PathSet references = readStorePaths<PathSet>(hashAndReadSource);
  1071. Path deriver = readString(hashAndReadSource);
  1072. if (deriver != "") assertStorePath(deriver);
  1073. Hash hash = hashAndReadSource.hashSink.finish().first;
  1074. hashAndReadSource.hashing = false;
  1075. bool haveSignature = readInt(hashAndReadSource) == 1;
  1076. if (requireSignature && !haveSignature)
  1077. throw Error(format("imported archive of `%1%' lacks a signature") % dstPath);
  1078. if (haveSignature) {
  1079. string signature = readString(hashAndReadSource);
  1080. if (requireSignature) {
  1081. Path sigFile = tmpDir + "/sig";
  1082. writeFile(sigFile, signature);
  1083. Strings args;
  1084. args.push_back("rsautl");
  1085. args.push_back("-verify");
  1086. args.push_back("-inkey");
  1087. args.push_back(settings.nixConfDir + "/signing-key.pub");
  1088. args.push_back("-pubin");
  1089. args.push_back("-in");
  1090. args.push_back(sigFile);
  1091. string hash2 = runAuthenticationProgram(args);
  1092. /* Note: runProgram() throws an exception if the signature
  1093. is invalid. */
  1094. if (printHash(hash) != hash2)
  1095. throw Error(
  1096. "signed hash doesn't match actual contents of imported "
  1097. "archive; archive could be corrupt, or someone is trying "
  1098. "to import a Trojan horse");
  1099. }
  1100. }
  1101. /* Do the actual import. */
  1102. /* !!! way too much code duplication with addTextToStore() etc. */
  1103. addTempRoot(dstPath);
  1104. if (!isValidPath(dstPath)) {
  1105. PathLocks outputLock;
  1106. /* Lock the output path. But don't lock if we're being called
  1107. from a build hook (whose parent process already acquired a
  1108. lock on this path). */
  1109. Strings locksHeld = tokenizeString<Strings>(getEnv("NIX_HELD_LOCKS"));
  1110. if (find(locksHeld.begin(), locksHeld.end(), dstPath) == locksHeld.end())
  1111. outputLock.lockPaths(singleton<PathSet, Path>(dstPath));
  1112. if (!isValidPath(dstPath)) {
  1113. if (pathExists(dstPath)) deletePath(dstPath);
  1114. if (rename(unpacked.c_str(), dstPath.c_str()) == -1)
  1115. throw SysError(format("cannot move `%1%' to `%2%'")
  1116. % unpacked % dstPath);
  1117. canonicalisePathMetaData(dstPath, -1);
  1118. /* !!! if we were clever, we could prevent the hashPath()
  1119. here. */
  1120. HashResult hash = hashPath(htSHA256, dstPath);
  1121. optimisePath(dstPath); // FIXME: combine with hashPath()
  1122. ValidPathInfo info;
  1123. info.path = dstPath;
  1124. info.hash = hash.first;
  1125. info.narSize = hash.second;
  1126. info.references = references;
  1127. info.deriver = deriver != "" && isValidPath(deriver) ? deriver : "";
  1128. registerValidPath(info);
  1129. }
  1130. outputLock.setDeletion(true);
  1131. }
  1132. return dstPath;
  1133. }
  1134. Paths LocalStore::importPaths(bool requireSignature, Source & source)
  1135. {
  1136. Paths res;
  1137. while (true) {
  1138. unsigned long long n = readLongLong(source);
  1139. if (n == 0) break;
  1140. if (n != 1) throw Error("input doesn't look like something created by `nix-store --export'");
  1141. res.push_back(importPath(requireSignature, source));
  1142. }
  1143. return res;
  1144. }
  1145. void LocalStore::invalidatePathChecked(const Path & path)
  1146. {
  1147. assertStorePath(path);
  1148. retrySQLite<void>([&]() {
  1149. SQLiteTxn txn(db);
  1150. if (isValidPath_(path)) {
  1151. PathSet referrers; queryReferrers_(path, referrers);
  1152. referrers.erase(path); /* ignore self-references */
  1153. if (!referrers.empty())
  1154. throw PathInUse(format("cannot delete path `%1%' because it is in use by %2%")
  1155. % path % showPaths(referrers));
  1156. invalidatePath(path);
  1157. }
  1158. txn.commit();
  1159. });
  1160. }
  1161. bool LocalStore::verifyStore(bool checkContents, bool repair)
  1162. {
  1163. printMsg(lvlError, format("reading the store..."));
  1164. bool errors = false;
  1165. /* Acquire the global GC lock to prevent a garbage collection. */
  1166. AutoCloseFD fdGCLock = openGCLock(ltWrite);
  1167. PathSet store;
  1168. for (auto & i : readDirectory(settings.nixStore)) store.insert(i.name);
  1169. /* Check whether all valid paths actually exist. */
  1170. printMsg(lvlInfo, "checking path existence...");
  1171. PathSet validPaths2 = queryAllValidPaths(), validPaths, done;
  1172. foreach (PathSet::iterator, i, validPaths2)
  1173. verifyPath(*i, store, done, validPaths, repair, errors);
  1174. /* Release the GC lock so that checking content hashes (which can
  1175. take ages) doesn't block the GC or builds. */
  1176. fdGCLock.close();
  1177. /* Optionally, check the content hashes (slow). */
  1178. if (checkContents) {
  1179. printMsg(lvlInfo, "checking hashes...");
  1180. Hash nullHash(htSHA256);
  1181. foreach (PathSet::iterator, i, validPaths) {
  1182. try {
  1183. ValidPathInfo info = queryPathInfo(*i);
  1184. /* Check the content hash (optionally - slow). */
  1185. printMsg(lvlTalkative, format("checking contents of `%1%'") % *i);
  1186. HashResult current = hashPath(info.hash.type, *i);
  1187. if (info.hash != nullHash && info.hash != current.first) {
  1188. printMsg(lvlError, format("path `%1%' was modified! "
  1189. "expected hash `%2%', got `%3%'")
  1190. % *i % printHash(info.hash) % printHash(current.first));
  1191. if (repair) repairPath(*i); else errors = true;
  1192. } else {
  1193. bool update = false;
  1194. /* Fill in missing hashes. */
  1195. if (info.hash == nullHash) {
  1196. printMsg(lvlError, format("fixing missing hash on `%1%'") % *i);
  1197. info.hash = current.first;
  1198. update = true;
  1199. }
  1200. /* Fill in missing narSize fields (from old stores). */
  1201. if (info.narSize == 0) {
  1202. printMsg(lvlError, format("updating size field on `%1%' to %2%") % *i % current.second);
  1203. info.narSize = current.second;
  1204. update = true;
  1205. }
  1206. if (update) updatePathInfo(info);
  1207. }
  1208. } catch (Error & e) {
  1209. /* It's possible that the path got GC'ed, so ignore
  1210. errors on invalid paths. */
  1211. if (isValidPath(*i))
  1212. printMsg(lvlError, format("error: %1%") % e.msg());
  1213. else
  1214. printMsg(lvlError, format("warning: %1%") % e.msg());
  1215. errors = true;
  1216. }
  1217. }
  1218. }
  1219. return errors;
  1220. }
  1221. void LocalStore::verifyPath(const Path & path, const PathSet & store,
  1222. PathSet & done, PathSet & validPaths, bool repair, bool & errors)
  1223. {
  1224. checkInterrupt();
  1225. if (done.find(path) != done.end()) return;
  1226. done.insert(path);
  1227. if (!isStorePath(path)) {
  1228. printMsg(lvlError, format("path `%1%' is not in the store") % path);
  1229. invalidatePath(path);
  1230. return;
  1231. }
  1232. if (store.find(baseNameOf(path)) == store.end()) {
  1233. /* Check any referrers first. If we can invalidate them
  1234. first, then we can invalidate this path as well. */
  1235. bool canInvalidate = true;
  1236. PathSet referrers; queryReferrers(path, referrers);
  1237. foreach (PathSet::iterator, i, referrers)
  1238. if (*i != path) {
  1239. verifyPath(*i, store, done, validPaths, repair, errors);
  1240. if (validPaths.find(*i) != validPaths.end())
  1241. canInvalidate = false;
  1242. }
  1243. if (canInvalidate) {
  1244. printMsg(lvlError, format("path `%1%' disappeared, removing from database...") % path);
  1245. invalidatePath(path);
  1246. } else {
  1247. printMsg(lvlError, format("path `%1%' disappeared, but it still has valid referrers!") % path);
  1248. if (repair)
  1249. try {
  1250. repairPath(path);
  1251. } catch (Error & e) {
  1252. printMsg(lvlError, format("warning: %1%") % e.msg());
  1253. errors = true;
  1254. }
  1255. else errors = true;
  1256. }
  1257. return;
  1258. }
  1259. validPaths.insert(path);
  1260. }
  1261. bool LocalStore::pathContentsGood(const Path & path)
  1262. {
  1263. std::map<Path, bool>::iterator i = pathContentsGoodCache.find(path);
  1264. if (i != pathContentsGoodCache.end()) return i->second;
  1265. printMsg(lvlInfo, format("checking path `%1%'...") % path);
  1266. ValidPathInfo info = queryPathInfo(path);
  1267. bool res;
  1268. if (!pathExists(path))
  1269. res = false;
  1270. else {
  1271. HashResult current = hashPath(info.hash.type, path);
  1272. Hash nullHash(htSHA256);
  1273. res = info.hash == nullHash || info.hash == current.first;
  1274. }
  1275. pathContentsGoodCache[path] = res;
  1276. if (!res) printMsg(lvlError, format("path `%1%' is corrupted or missing!") % path);
  1277. return res;
  1278. }
  1279. void LocalStore::markContentsGood(const Path & path)
  1280. {
  1281. pathContentsGoodCache[path] = true;
  1282. }
  1283. void LocalStore::vacuumDB()
  1284. {
  1285. if (sqlite3_exec(db, "vacuum;", 0, 0, 0) != SQLITE_OK)
  1286. throwSQLiteError(db, "vacuuming SQLite database");
  1287. }
  1288. }