nix-daemon.cc 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  1. #include "shared.hh"
  2. #include "local-store.hh"
  3. #include "util.hh"
  4. #include "serialise.hh"
  5. #include "worker-protocol.hh"
  6. #include "archive.hh"
  7. #include "affinity.hh"
  8. #include "globals.hh"
  9. #include "builtins.hh"
  10. #include <algorithm>
  11. #include <cstring>
  12. #include <unistd.h>
  13. #include <signal.h>
  14. #include <sys/types.h>
  15. #include <sys/wait.h>
  16. #include <sys/stat.h>
  17. #include <sys/socket.h>
  18. #include <sys/un.h>
  19. #include <arpa/inet.h>
  20. #include <netinet/in.h>
  21. #include <netinet/tcp.h>
  22. #include <fcntl.h>
  23. #include <errno.h>
  24. #include <pwd.h>
  25. #include <grp.h>
  26. using namespace nix;
  27. /* On platforms that have O_ASYNC, we can detect when a client
  28. disconnects and immediately kill any ongoing builds. On platforms
  29. that lack it, we only notice the disconnection the next time we try
  30. to write to the client. So if you have a builder that never
  31. generates output on stdout/stderr, the daemon will never notice
  32. that the client has disconnected until the builder terminates.
  33. GNU/Hurd does have O_ASYNC, but its Unix-domain socket translator
  34. (pflocal) does not implement F_SETOWN. See
  35. <http://lists.gnu.org/archive/html/bug-guix/2013-07/msg00021.html> for
  36. details.*/
  37. #if defined O_ASYNC && !defined __GNU__
  38. #define HAVE_HUP_NOTIFICATION
  39. #ifndef SIGPOLL
  40. #define SIGPOLL SIGIO
  41. #endif
  42. #endif
  43. static FdSource from(STDIN_FILENO);
  44. static FdSink to(STDOUT_FILENO);
  45. bool canSendStderr;
  46. /* This variable is used to keep track of whether a connection
  47. comes from a host other than the host running guix-daemon. */
  48. static bool isRemoteConnection;
  49. /* This function is called anytime we want to write something to
  50. stderr. If we're in a state where the protocol allows it (i.e.,
  51. when canSendStderr), send the message to the client over the
  52. socket. */
  53. static void tunnelStderr(const unsigned char * buf, size_t count)
  54. {
  55. if (canSendStderr) {
  56. try {
  57. writeInt(STDERR_NEXT, to);
  58. writeString(buf, count, to);
  59. to.flush();
  60. } catch (...) {
  61. /* Write failed; that means that the other side is
  62. gone. */
  63. canSendStderr = false;
  64. throw;
  65. }
  66. } else
  67. writeFull(STDERR_FILENO, buf, count);
  68. }
  69. /* Return true if the remote side has closed its end of the
  70. connection, false otherwise. Should not be called on any socket on
  71. which we expect input! */
  72. static bool isFarSideClosed(int socket)
  73. {
  74. struct timeval timeout;
  75. timeout.tv_sec = timeout.tv_usec = 0;
  76. fd_set fds;
  77. FD_ZERO(&fds);
  78. FD_SET(socket, &fds);
  79. while (select(socket + 1, &fds, 0, 0, &timeout) == -1)
  80. if (errno != EINTR) throw SysError("select()");
  81. if (!FD_ISSET(socket, &fds)) return false;
  82. /* Destructive read to determine whether the select() marked the
  83. socket as readable because there is actual input or because
  84. we've reached EOF (i.e., a read of size 0 is available). */
  85. char c;
  86. int rd;
  87. if ((rd = read(socket, &c, 1)) > 0)
  88. throw Error("EOF expected (protocol error?)");
  89. else if (rd == -1 && errno != ECONNRESET)
  90. throw SysError("expected connection reset or EOF");
  91. return true;
  92. }
  93. /* A SIGPOLL signal is received when data is available on the client
  94. communication socket, or when the client has closed its side of the
  95. socket. This handler is enabled at precisely those moments in the
  96. protocol when we're doing work and the client is supposed to be
  97. quiet. Thus, if we get a SIGPOLL signal, it means that the client
  98. has quit. So we should quit as well.
  99. Too bad most operating systems don't support the POLL_HUP value for
  100. si_code in siginfo_t. That would make most of the SIGPOLL
  101. complexity unnecessary, i.e., we could just enable SIGPOLL all the
  102. time and wouldn't have to worry about races. */
  103. static void sigPollHandler(int sigNo)
  104. {
  105. using namespace std;
  106. try {
  107. /* Check that the far side actually closed. We're still
  108. getting spurious signals every once in a while. I.e.,
  109. there is no input available, but we get a signal with
  110. POLL_IN set. Maybe it's delayed or something. */
  111. if (isFarSideClosed(from.fd)) {
  112. if (!blockInt) {
  113. _isInterrupted = 1;
  114. blockInt = 1;
  115. canSendStderr = false;
  116. const char * s = "SIGPOLL\n";
  117. write(STDERR_FILENO, s, strlen(s));
  118. }
  119. } else {
  120. const char * s = "spurious SIGPOLL\n";
  121. write(STDERR_FILENO, s, strlen(s));
  122. }
  123. }
  124. catch (Error & e) {
  125. /* Shouldn't happen. */
  126. string s = "impossible: " + e.msg() + '\n';
  127. write(STDERR_FILENO, s.data(), s.size());
  128. throw;
  129. }
  130. }
  131. static void setSigPollAction(bool enable)
  132. {
  133. #ifdef HAVE_HUP_NOTIFICATION
  134. struct sigaction act, oact;
  135. act.sa_handler = enable ? sigPollHandler : SIG_IGN;
  136. sigfillset(&act.sa_mask);
  137. act.sa_flags = 0;
  138. if (sigaction(SIGPOLL, &act, &oact))
  139. throw SysError("setting handler for SIGPOLL");
  140. #endif
  141. }
  142. /* startWork() means that we're starting an operation for which we
  143. want to send out stderr to the client. */
  144. static void startWork()
  145. {
  146. canSendStderr = true;
  147. /* Handle client death asynchronously. */
  148. setSigPollAction(true);
  149. /* Of course, there is a race condition here: the socket could
  150. have closed between when we last read from / wrote to it, and
  151. between the time we set the handler for SIGPOLL. In that case
  152. we won't get the signal. So do a non-blocking select() to find
  153. out if any input is available on the socket. If there is, it
  154. has to be the 0-byte read that indicates that the socket has
  155. closed. */
  156. if (isFarSideClosed(from.fd)) {
  157. _isInterrupted = 1;
  158. checkInterrupt();
  159. }
  160. }
  161. /* stopWork() means that we're done; stop sending stderr to the
  162. client. */
  163. static void stopWork(bool success = true, const string & msg = "", unsigned int status = 0)
  164. {
  165. /* Stop handling async client death; we're going to a state where
  166. we're either sending or receiving from the client, so we'll be
  167. notified of client death anyway. */
  168. setSigPollAction(false);
  169. canSendStderr = false;
  170. if (success)
  171. writeInt(STDERR_LAST, to);
  172. else {
  173. writeInt(STDERR_ERROR, to);
  174. writeString(msg, to);
  175. if (status != 0) writeInt(status, to);
  176. }
  177. }
  178. struct TunnelSink : BufferedSink
  179. {
  180. Sink & to;
  181. TunnelSink(Sink & to) : BufferedSink(64 * 1024), to(to) { }
  182. virtual void write(const unsigned char * data, size_t len)
  183. {
  184. writeInt(STDERR_WRITE, to);
  185. writeString(data, len, to);
  186. }
  187. };
  188. struct TunnelSource : BufferedSource
  189. {
  190. Source & from;
  191. TunnelSource(Source & from) : from(from) { }
  192. size_t readUnbuffered(unsigned char * data, size_t len)
  193. {
  194. /* Careful: we're going to receive data from the client now,
  195. so we have to disable the SIGPOLL handler. */
  196. setSigPollAction(false);
  197. canSendStderr = false;
  198. writeInt(STDERR_READ, to);
  199. writeInt(len, to);
  200. to.flush();
  201. size_t n = readString(data, len, from);
  202. startWork();
  203. if (n == 0) throw EndOfFile("unexpected end-of-file");
  204. return n;
  205. }
  206. };
  207. /* If the NAR archive contains a single file at top-level, then save
  208. the contents of the file to `s'. Otherwise barf. */
  209. struct RetrieveRegularNARSink : ParseSink
  210. {
  211. bool regular;
  212. string s;
  213. RetrieveRegularNARSink() : regular(true) { }
  214. void createDirectory(const Path & path)
  215. {
  216. regular = false;
  217. }
  218. void receiveContents(unsigned char * data, unsigned int len)
  219. {
  220. s.append((const char *) data, len);
  221. }
  222. void createSymlink(const Path & path, const string & target)
  223. {
  224. regular = false;
  225. }
  226. };
  227. /* Adapter class of a Source that saves all data read to `s'. */
  228. struct SavingSourceAdapter : Source
  229. {
  230. Source & orig;
  231. string s;
  232. SavingSourceAdapter(Source & orig) : orig(orig) { }
  233. size_t read(unsigned char * data, size_t len)
  234. {
  235. size_t n = orig.read(data, len);
  236. s.append((const char *) data, n);
  237. return n;
  238. }
  239. };
  240. static void performOp(bool trusted, unsigned int clientVersion,
  241. Source & from, Sink & to, unsigned int op)
  242. {
  243. switch (op) {
  244. case wopIsValidPath: {
  245. /* 'readStorePath' could raise an error leading to the connection
  246. being closed. To be able to recover from an invalid path error,
  247. call 'startWork' early, and do 'assertStorePath' afterwards so
  248. that the 'Error' exception handler doesn't close the
  249. connection. */
  250. Path path = readString(from);
  251. startWork();
  252. assertStorePath(path);
  253. bool result = store->isValidPath(path);
  254. stopWork();
  255. writeInt(result, to);
  256. break;
  257. }
  258. case wopQueryValidPaths: {
  259. PathSet paths = readStorePaths<PathSet>(from);
  260. startWork();
  261. PathSet res = store->queryValidPaths(paths);
  262. stopWork();
  263. writeStrings(res, to);
  264. break;
  265. }
  266. case wopHasSubstitutes: {
  267. Path path = readStorePath(from);
  268. startWork();
  269. PathSet res = store->querySubstitutablePaths(singleton<PathSet>(path));
  270. stopWork();
  271. writeInt(res.find(path) != res.end(), to);
  272. break;
  273. }
  274. case wopQuerySubstitutablePaths: {
  275. PathSet paths = readStorePaths<PathSet>(from);
  276. startWork();
  277. PathSet res = store->querySubstitutablePaths(paths);
  278. stopWork();
  279. writeStrings(res, to);
  280. break;
  281. }
  282. case wopQueryPathHash: {
  283. Path path = readStorePath(from);
  284. startWork();
  285. Hash hash = store->queryPathHash(path);
  286. stopWork();
  287. writeString(printHash(hash), to);
  288. break;
  289. }
  290. case wopQueryReferences:
  291. case wopQueryReferrers:
  292. case wopQueryValidDerivers:
  293. case wopQueryDerivationOutputs: {
  294. Path path = readStorePath(from);
  295. startWork();
  296. PathSet paths;
  297. if (op == wopQueryReferences)
  298. store->queryReferences(path, paths);
  299. else if (op == wopQueryReferrers)
  300. store->queryReferrers(path, paths);
  301. else if (op == wopQueryValidDerivers)
  302. paths = store->queryValidDerivers(path);
  303. else paths = store->queryDerivationOutputs(path);
  304. stopWork();
  305. writeStrings(paths, to);
  306. break;
  307. }
  308. case wopQueryDerivationOutputNames: {
  309. Path path = readStorePath(from);
  310. startWork();
  311. StringSet names;
  312. names = store->queryDerivationOutputNames(path);
  313. stopWork();
  314. writeStrings(names, to);
  315. break;
  316. }
  317. case wopQueryDeriver: {
  318. Path path = readStorePath(from);
  319. startWork();
  320. Path deriver = store->queryDeriver(path);
  321. stopWork();
  322. writeString(deriver, to);
  323. break;
  324. }
  325. case wopQueryPathFromHashPart: {
  326. string hashPart = readString(from);
  327. startWork();
  328. Path path = store->queryPathFromHashPart(hashPart);
  329. stopWork();
  330. writeString(path, to);
  331. break;
  332. }
  333. case wopAddToStore: {
  334. string baseName = readString(from);
  335. bool fixed = readInt(from) == 1; /* obsolete */
  336. bool recursive = readInt(from) == 1;
  337. string s = readString(from);
  338. /* Compatibility hack. */
  339. if (!fixed) {
  340. s = "sha256";
  341. recursive = true;
  342. }
  343. HashType hashAlgo = parseHashType(s);
  344. SavingSourceAdapter savedNAR(from);
  345. RetrieveRegularNARSink savedRegular;
  346. if (recursive) {
  347. /* Get the entire NAR dump from the client and save it to
  348. a string so that we can pass it to
  349. addToStoreFromDump(). */
  350. ParseSink sink; /* null sink; just parse the NAR */
  351. parseDump(sink, savedNAR);
  352. } else
  353. parseDump(savedRegular, from);
  354. startWork();
  355. if (!savedRegular.regular) throw Error("regular file expected");
  356. Path path = dynamic_cast<LocalStore *>(store.get())
  357. ->addToStoreFromDump(recursive ? savedNAR.s : savedRegular.s, baseName, recursive, hashAlgo);
  358. stopWork();
  359. writeString(path, to);
  360. break;
  361. }
  362. case wopAddTextToStore: {
  363. string suffix = readString(from);
  364. string s = readString(from);
  365. PathSet refs = readStorePaths<PathSet>(from);
  366. startWork();
  367. Path path = store->addTextToStore(suffix, s, refs);
  368. stopWork();
  369. writeString(path, to);
  370. break;
  371. }
  372. case wopExportPath: {
  373. Path path = readStorePath(from);
  374. bool sign = readInt(from) == 1;
  375. startWork();
  376. TunnelSink sink(to);
  377. try {
  378. store->exportPath(path, sign, sink);
  379. }
  380. catch (Error &e) {
  381. /* Flush SINK beforehand or its destructor will rightfully trigger
  382. an assertion failure. */
  383. sink.flush();
  384. throw e;
  385. }
  386. sink.flush();
  387. stopWork();
  388. writeInt(1, to);
  389. break;
  390. }
  391. case wopImportPaths: {
  392. startWork();
  393. TunnelSource source(from);
  394. /* Unlike Nix, always require a signature, even for "trusted"
  395. users. */
  396. Paths paths = store->importPaths(true, source);
  397. stopWork();
  398. writeStrings(paths, to);
  399. break;
  400. }
  401. case wopBuildPaths: {
  402. PathSet drvs = readStorePaths<PathSet>(from);
  403. BuildMode mode = bmNormal;
  404. if (GET_PROTOCOL_MINOR(clientVersion) >= 15) {
  405. mode = (BuildMode)readInt(from);
  406. /* Repairing is not atomic, so disallowed for "untrusted"
  407. clients. */
  408. if (mode == bmRepair && !trusted)
  409. throw Error("repairing is a privileged operation");
  410. }
  411. startWork();
  412. store->buildPaths(drvs, mode);
  413. stopWork();
  414. writeInt(1, to);
  415. break;
  416. }
  417. case wopEnsurePath: {
  418. Path path = readStorePath(from);
  419. startWork();
  420. store->ensurePath(path);
  421. stopWork();
  422. writeInt(1, to);
  423. break;
  424. }
  425. case wopAddTempRoot: {
  426. Path path = readStorePath(from);
  427. startWork();
  428. store->addTempRoot(path);
  429. stopWork();
  430. writeInt(1, to);
  431. break;
  432. }
  433. case wopAddIndirectRoot: {
  434. Path path = absPath(readString(from));
  435. startWork();
  436. store->addIndirectRoot(path);
  437. stopWork();
  438. writeInt(1, to);
  439. break;
  440. }
  441. case wopSyncWithGC: {
  442. startWork();
  443. store->syncWithGC();
  444. stopWork();
  445. writeInt(1, to);
  446. break;
  447. }
  448. case wopFindRoots: {
  449. startWork();
  450. Roots roots = store->findRoots();
  451. stopWork();
  452. writeInt(roots.size(), to);
  453. for (Roots::iterator i = roots.begin(); i != roots.end(); ++i) {
  454. writeString(i->first, to);
  455. writeString(i->second, to);
  456. }
  457. break;
  458. }
  459. case wopCollectGarbage: {
  460. if (isRemoteConnection) {
  461. throw Error("Garbage collection is disabled for remote hosts.");
  462. break;
  463. }
  464. GCOptions options;
  465. options.action = (GCOptions::GCAction) readInt(from);
  466. options.pathsToDelete = readStorePaths<PathSet>(from);
  467. options.ignoreLiveness = readInt(from);
  468. options.maxFreed = readLongLong(from);
  469. readInt(from); // obsolete field
  470. if (GET_PROTOCOL_MINOR(clientVersion) >= 5) {
  471. /* removed options */
  472. readInt(from);
  473. readInt(from);
  474. }
  475. GCResults results;
  476. startWork();
  477. if (options.ignoreLiveness)
  478. throw Error("you are not allowed to ignore liveness");
  479. store->collectGarbage(options, results);
  480. stopWork();
  481. writeStrings(results.paths, to);
  482. writeLongLong(results.bytesFreed, to);
  483. writeLongLong(0, to); // obsolete
  484. break;
  485. }
  486. case wopSetOptions: {
  487. settings.keepFailed = readInt(from) != 0;
  488. if (isRemoteConnection)
  489. /* When the client is remote, don't keep the failed build tree as
  490. it is presumably inaccessible to the client and could fill up
  491. our disk. */
  492. settings.keepFailed = 0;
  493. settings.keepGoing = readInt(from) != 0;
  494. settings.set("build-fallback", readInt(from) ? "true" : "false");
  495. verbosity = (Verbosity) readInt(from);
  496. if (GET_PROTOCOL_MINOR(clientVersion) < 0x61) {
  497. settings.set("build-max-jobs", std::to_string(readInt(from)));
  498. settings.set("build-max-silent-time", std::to_string(readInt(from)));
  499. }
  500. if (GET_PROTOCOL_MINOR(clientVersion) >= 2)
  501. settings.useBuildHook = readInt(from) != 0;
  502. if (GET_PROTOCOL_MINOR(clientVersion) >= 4) {
  503. settings.buildVerbosity = (Verbosity) readInt(from);
  504. logType = (LogType) readInt(from);
  505. settings.printBuildTrace = readInt(from) != 0;
  506. }
  507. if (GET_PROTOCOL_MINOR(clientVersion) >= 6
  508. && GET_PROTOCOL_MINOR(clientVersion) < 0x61)
  509. settings.set("build-cores", std::to_string(readInt(from)));
  510. if (GET_PROTOCOL_MINOR(clientVersion) >= 10)
  511. settings.set("build-use-substitutes", readInt(from) ? "true" : "false");
  512. if (GET_PROTOCOL_MINOR(clientVersion) >= 12) {
  513. unsigned int n = readInt(from);
  514. for (unsigned int i = 0; i < n; i++) {
  515. string name = readString(from);
  516. string value = readString(from);
  517. if (name == "build-timeout" || name == "build-max-silent-time"
  518. || name == "build-max-jobs" || name == "build-cores"
  519. || name == "build-repeat"
  520. || name == "multiplexed-build-output")
  521. settings.set(name, value);
  522. else
  523. settings.set(trusted ? name : "untrusted-" + name, value);
  524. }
  525. }
  526. settings.update();
  527. startWork();
  528. stopWork();
  529. break;
  530. }
  531. case wopQuerySubstitutablePathInfo: {
  532. Path path = absPath(readString(from));
  533. startWork();
  534. SubstitutablePathInfos infos;
  535. store->querySubstitutablePathInfos(singleton<PathSet>(path), infos);
  536. stopWork();
  537. SubstitutablePathInfos::iterator i = infos.find(path);
  538. if (i == infos.end())
  539. writeInt(0, to);
  540. else {
  541. writeInt(1, to);
  542. writeString(i->second.deriver, to);
  543. writeStrings(i->second.references, to);
  544. writeLongLong(i->second.downloadSize, to);
  545. if (GET_PROTOCOL_MINOR(clientVersion) >= 7)
  546. writeLongLong(i->second.narSize, to);
  547. }
  548. break;
  549. }
  550. case wopQuerySubstitutablePathInfos: {
  551. PathSet paths = readStorePaths<PathSet>(from);
  552. startWork();
  553. SubstitutablePathInfos infos;
  554. store->querySubstitutablePathInfos(paths, infos);
  555. stopWork();
  556. writeInt(infos.size(), to);
  557. foreach (SubstitutablePathInfos::iterator, i, infos) {
  558. writeString(i->first, to);
  559. writeString(i->second.deriver, to);
  560. writeStrings(i->second.references, to);
  561. writeLongLong(i->second.downloadSize, to);
  562. writeLongLong(i->second.narSize, to);
  563. }
  564. break;
  565. }
  566. case wopQueryAllValidPaths: {
  567. startWork();
  568. PathSet paths = store->queryAllValidPaths();
  569. stopWork();
  570. writeStrings(paths, to);
  571. break;
  572. }
  573. case wopQueryFailedPaths: {
  574. startWork();
  575. PathSet paths = store->queryFailedPaths();
  576. stopWork();
  577. writeStrings(paths, to);
  578. break;
  579. }
  580. case wopClearFailedPaths: {
  581. PathSet paths = readStrings<PathSet>(from);
  582. startWork();
  583. store->clearFailedPaths(paths);
  584. stopWork();
  585. writeInt(1, to);
  586. break;
  587. }
  588. case wopQueryPathInfo: {
  589. Path path = readStorePath(from);
  590. startWork();
  591. ValidPathInfo info = store->queryPathInfo(path);
  592. stopWork();
  593. writeString(info.deriver, to);
  594. writeString(printHash(info.hash), to);
  595. writeStrings(info.references, to);
  596. writeInt(info.registrationTime, to);
  597. writeLongLong(info.narSize, to);
  598. break;
  599. }
  600. case wopOptimiseStore:
  601. startWork();
  602. store->optimiseStore();
  603. stopWork();
  604. writeInt(1, to);
  605. break;
  606. case wopVerifyStore: {
  607. bool checkContents = readInt(from) != 0;
  608. bool repair = readInt(from) != 0;
  609. startWork();
  610. if (repair && !trusted)
  611. throw Error("you are not privileged to repair paths");
  612. bool errors = store->verifyStore(checkContents, repair);
  613. stopWork();
  614. writeInt(errors, to);
  615. break;
  616. }
  617. case wopBuiltinBuilders: {
  618. startWork();
  619. auto names = builtinBuilderNames();
  620. stopWork();
  621. writeStrings(names, to);
  622. break;
  623. }
  624. default:
  625. throw Error(format("invalid operation %1%") % op);
  626. }
  627. }
  628. static void processConnection(bool trusted)
  629. {
  630. canSendStderr = false;
  631. _writeToStderr = tunnelStderr;
  632. #ifdef HAVE_HUP_NOTIFICATION
  633. /* Allow us to receive SIGPOLL for events on the client socket. */
  634. setSigPollAction(false);
  635. if (fcntl(from.fd, F_SETOWN, getpid()) == -1)
  636. throw SysError("F_SETOWN");
  637. if (fcntl(from.fd, F_SETFL, fcntl(from.fd, F_GETFL, 0) | O_ASYNC) == -1)
  638. throw SysError("F_SETFL");
  639. #endif
  640. /* Exchange the greeting. */
  641. unsigned int magic = readInt(from);
  642. if (magic != WORKER_MAGIC_1) throw Error("protocol mismatch");
  643. writeInt(WORKER_MAGIC_2, to);
  644. writeInt(PROTOCOL_VERSION, to);
  645. to.flush();
  646. unsigned int clientVersion = readInt(from);
  647. if (GET_PROTOCOL_MINOR(clientVersion) >= 14 && readInt(from))
  648. setAffinityTo(readInt(from));
  649. bool reserveSpace = true;
  650. if (GET_PROTOCOL_MINOR(clientVersion) >= 11)
  651. reserveSpace = readInt(from) != 0;
  652. /* Send startup error messages to the client. */
  653. startWork();
  654. try {
  655. /* If we can't accept clientVersion, then throw an error
  656. *here* (not above). */
  657. #if 0
  658. /* Prevent users from doing something very dangerous. */
  659. if (geteuid() == 0 &&
  660. querySetting("build-users-group", "") == "")
  661. throw Error("if you run `nix-daemon' as root, then you MUST set `build-users-group'!");
  662. #endif
  663. /* Open the store. */
  664. store = std::shared_ptr<StoreAPI>(new LocalStore(reserveSpace));
  665. stopWork();
  666. to.flush();
  667. } catch (Error & e) {
  668. stopWork(false, e.msg(), GET_PROTOCOL_MINOR(clientVersion) >= 8 ? 1 : 0);
  669. to.flush();
  670. return;
  671. }
  672. /* Process client requests. */
  673. unsigned int opCount = 0;
  674. while (true) {
  675. WorkerOp op;
  676. try {
  677. op = (WorkerOp) readInt(from);
  678. } catch (EndOfFile & e) {
  679. break;
  680. }
  681. opCount++;
  682. try {
  683. performOp(trusted, clientVersion, from, to, op);
  684. } catch (Error & e) {
  685. /* If we're not in a state where we can send replies, then
  686. something went wrong processing the input of the
  687. client. This can happen especially if I/O errors occur
  688. during addTextToStore() / importPath(). If that
  689. happens, just send the error message and exit. */
  690. bool errorAllowed = canSendStderr;
  691. stopWork(false, e.msg(), GET_PROTOCOL_MINOR(clientVersion) >= 8 ? e.status : 0);
  692. if (!errorAllowed) throw;
  693. } catch (std::bad_alloc & e) {
  694. stopWork(false, "build daemon out of memory", GET_PROTOCOL_MINOR(clientVersion) >= 8 ? 1 : 0);
  695. throw;
  696. }
  697. to.flush();
  698. assert(!canSendStderr);
  699. };
  700. canSendStderr = false;
  701. _isInterrupted = false;
  702. printMsg(lvlDebug, format("%1% operations") % opCount);
  703. }
  704. static void sigChldHandler(int sigNo)
  705. {
  706. /* Reap all dead children. */
  707. while (waitpid(-1, 0, WNOHANG) > 0) ;
  708. }
  709. static void setSigChldAction(bool autoReap)
  710. {
  711. struct sigaction act, oact;
  712. act.sa_handler = autoReap ? sigChldHandler : SIG_DFL;
  713. sigfillset(&act.sa_mask);
  714. act.sa_flags = 0;
  715. if (sigaction(SIGCHLD, &act, &oact))
  716. throw SysError("setting SIGCHLD handler");
  717. }
  718. /* Accept a connection on FDSOCKET and fork a server process to process the
  719. new connection. */
  720. static void acceptConnection(int fdSocket)
  721. {
  722. uid_t clientUid = (uid_t) -1;
  723. gid_t clientGid = (gid_t) -1;
  724. try {
  725. /* Important: the server process *cannot* open the SQLite
  726. database, because it doesn't like forks very much. */
  727. assert(!store);
  728. /* Accept a connection. */
  729. struct sockaddr_storage remoteAddr;
  730. socklen_t remoteAddrLen = sizeof(remoteAddr);
  731. try_again:
  732. AutoCloseFD remote = accept(fdSocket,
  733. (struct sockaddr *) &remoteAddr, &remoteAddrLen);
  734. checkInterrupt();
  735. if (remote == -1) {
  736. if (errno == EINTR)
  737. goto try_again;
  738. else
  739. throw SysError("accepting connection");
  740. }
  741. closeOnExec(remote);
  742. {
  743. int enabled = 1;
  744. /* If we're on a TCP connection, disable Nagle's algorithm so that
  745. data is sent as soon as possible. */
  746. (void) setsockopt(remote, SOL_TCP, TCP_NODELAY,
  747. &enabled, sizeof enabled);
  748. #if defined(TCP_QUICKACK)
  749. /* Enable TCP quick-ack if applicable; this might help a little. */
  750. (void) setsockopt(remote, SOL_TCP, TCP_QUICKACK,
  751. &enabled, sizeof enabled);
  752. #endif
  753. }
  754. pid_t clientPid = -1;
  755. bool trusted = false;
  756. /* Get the identity of the caller, if possible. */
  757. if (remoteAddr.ss_family == AF_UNIX) {
  758. #if defined(SO_PEERCRED)
  759. ucred cred;
  760. socklen_t credLen = sizeof(cred);
  761. if (getsockopt(remote, SOL_SOCKET, SO_PEERCRED,
  762. &cred, &credLen) == -1)
  763. throw SysError("getting peer credentials");
  764. clientPid = cred.pid;
  765. clientUid = cred.uid;
  766. clientGid = cred.gid;
  767. trusted = clientUid == 0;
  768. struct passwd * pw = getpwuid(cred.uid);
  769. string user = pw ? pw->pw_name : std::to_string(cred.uid);
  770. printMsg(lvlInfo,
  771. format((string) "accepted connection from pid %1%, user %2%")
  772. % clientPid % user);
  773. #endif
  774. } else {
  775. char address_str[128];
  776. const char *result;
  777. if (remoteAddr.ss_family == AF_INET) {
  778. struct sockaddr_in *addr = (struct sockaddr_in *) &remoteAddr;
  779. result = inet_ntop(AF_INET, &addr->sin_addr,
  780. address_str, sizeof address_str);
  781. } else if (remoteAddr.ss_family == AF_INET6) {
  782. struct sockaddr_in6 *addr = (struct sockaddr_in6 *) &remoteAddr;
  783. result = inet_ntop(AF_INET6, &addr->sin6_addr,
  784. address_str, sizeof address_str);
  785. } else {
  786. result = NULL;
  787. }
  788. if (result != NULL) {
  789. printMsg(lvlInfo,
  790. format("accepted connection from %1%")
  791. % address_str);
  792. }
  793. }
  794. /* Fork a child to handle the connection. */
  795. startProcess([&]() {
  796. close(fdSocket);
  797. /* Background the daemon. */
  798. if (setsid() == -1)
  799. throw SysError(format("creating a new session"));
  800. /* Restore normal handling of SIGCHLD. */
  801. setSigChldAction(false);
  802. /* For debugging, stuff the pid into argv[1]. */
  803. if (clientPid != -1 && argvSaved[1]) {
  804. string processName = std::to_string(clientPid);
  805. strncpy(argvSaved[1], processName.c_str(), strlen(argvSaved[1]));
  806. }
  807. /* Store the client's user and group for this connection. This
  808. has to be done in the forked process since it is per
  809. connection. Setting these to -1 means: do not change. */
  810. settings.clientUid = clientUid;
  811. settings.clientGid = clientGid;
  812. isRemoteConnection = (remoteAddr.ss_family != AF_UNIX);
  813. /* Handle the connection. */
  814. from.fd = remote;
  815. to.fd = remote;
  816. processConnection(trusted);
  817. exit(0);
  818. }, false, "unexpected build daemon error: ", true);
  819. } catch (Interrupted & e) {
  820. throw;
  821. } catch (Error & e) {
  822. printMsg(lvlError, format("error processing connection: %1%") % e.msg());
  823. }
  824. }
  825. static void daemonLoop(const std::vector<int>& sockets)
  826. {
  827. if (chdir("/") == -1)
  828. throw SysError("cannot change current directory");
  829. /* Get rid of children automatically; don't let them become
  830. zombies. */
  831. setSigChldAction(true);
  832. /* Mark sockets as close-on-exec. */
  833. for(int fd: sockets) {
  834. closeOnExec(fd);
  835. }
  836. /* Prepare the FD set corresponding to SOCKETS. */
  837. auto initializeFDSet = [&](fd_set *set) {
  838. FD_ZERO(set);
  839. for (int fd: sockets) {
  840. FD_SET(fd, set);
  841. }
  842. };
  843. /* Loop accepting connections. */
  844. while (1) {
  845. fd_set readfds;
  846. initializeFDSet(&readfds);
  847. int count =
  848. select(*std::max_element(sockets.begin(), sockets.end()) + 1,
  849. &readfds, NULL, NULL,
  850. NULL);
  851. if (count < 0) {
  852. int err = errno;
  853. if (err == EINTR)
  854. continue;
  855. throw SysError(format("select error: %1%") % strerror(err));
  856. }
  857. for (unsigned int i = 0; i < sockets.size(); i++) {
  858. if (FD_ISSET(sockets[i], &readfds)) {
  859. acceptConnection(sockets[i]);
  860. }
  861. }
  862. }
  863. }
  864. void run(const std::vector<int>& sockets)
  865. {
  866. daemonLoop(sockets);
  867. }
  868. void printHelp()
  869. {
  870. showManPage("nix-daemon");
  871. }
  872. string programId = "nix-daemon";