local-store.cc 50 KB

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