util.cc 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231
  1. #include "config.h"
  2. #include "util.hh"
  3. #include "affinity.hh"
  4. #include <iostream>
  5. #include <cerrno>
  6. #include <cstdio>
  7. #include <cstdlib>
  8. #include <sstream>
  9. #include <cstring>
  10. #include <sys/wait.h>
  11. #include <unistd.h>
  12. #include <fcntl.h>
  13. #include <limits.h>
  14. #ifdef __APPLE__
  15. #include <sys/syscall.h>
  16. #endif
  17. #ifdef __linux__
  18. #include <sys/prctl.h>
  19. #endif
  20. extern char * * environ;
  21. namespace nix {
  22. BaseError::BaseError(const FormatOrString & fs, unsigned int status)
  23. : status(status)
  24. {
  25. err = fs.s;
  26. }
  27. BaseError & BaseError::addPrefix(const FormatOrString & fs)
  28. {
  29. prefix_ = fs.s + prefix_;
  30. return *this;
  31. }
  32. SysError::SysError(const FormatOrString & fs)
  33. : Error(format("%1%: %2%") % fs.s % strerror(errno))
  34. , errNo(errno)
  35. {
  36. }
  37. string getEnv(const string & key, const string & def)
  38. {
  39. char * value = getenv(key.c_str());
  40. return value ? string(value) : def;
  41. }
  42. Path absPath(Path path, Path dir)
  43. {
  44. if (path[0] != '/') {
  45. if (dir == "") {
  46. #ifdef __GNU__
  47. /* GNU (aka. GNU/Hurd) doesn't have any limitation on path
  48. lengths and doesn't define `PATH_MAX'. */
  49. char *buf = getcwd(NULL, 0);
  50. if (buf == NULL)
  51. #else
  52. char buf[PATH_MAX];
  53. if (!getcwd(buf, sizeof(buf)))
  54. #endif
  55. throw SysError("cannot get cwd");
  56. dir = buf;
  57. #ifdef __GNU__
  58. free(buf);
  59. #endif
  60. }
  61. path = dir + "/" + path;
  62. }
  63. return canonPath(path);
  64. }
  65. Path canonPath(const Path & path, bool resolveSymlinks)
  66. {
  67. string s;
  68. if (path[0] != '/')
  69. throw Error(format("not an absolute path: `%1%'") % path);
  70. string::const_iterator i = path.begin(), end = path.end();
  71. string temp;
  72. /* Count the number of times we follow a symlink and stop at some
  73. arbitrary (but high) limit to prevent infinite loops. */
  74. unsigned int followCount = 0, maxFollow = 1024;
  75. while (1) {
  76. /* Skip slashes. */
  77. while (i != end && *i == '/') i++;
  78. if (i == end) break;
  79. /* Ignore `.'. */
  80. if (*i == '.' && (i + 1 == end || i[1] == '/'))
  81. i++;
  82. /* If `..', delete the last component. */
  83. else if (*i == '.' && i + 1 < end && i[1] == '.' &&
  84. (i + 2 == end || i[2] == '/'))
  85. {
  86. if (!s.empty()) s.erase(s.rfind('/'));
  87. i += 2;
  88. }
  89. /* Normal component; copy it. */
  90. else {
  91. s += '/';
  92. while (i != end && *i != '/') s += *i++;
  93. /* If s points to a symlink, resolve it and restart (since
  94. the symlink target might contain new symlinks). */
  95. if (resolveSymlinks && isLink(s)) {
  96. if (++followCount >= maxFollow)
  97. throw Error(format("infinite symlink recursion in path `%1%'") % path);
  98. temp = absPath(readLink(s), dirOf(s))
  99. + string(i, end);
  100. i = temp.begin(); /* restart */
  101. end = temp.end();
  102. s = "";
  103. }
  104. }
  105. }
  106. return s.empty() ? "/" : s;
  107. }
  108. Path dirOf(const Path & path)
  109. {
  110. Path::size_type pos = path.rfind('/');
  111. if (pos == string::npos)
  112. throw Error(format("invalid file name `%1%'") % path);
  113. return pos == 0 ? "/" : Path(path, 0, pos);
  114. }
  115. string baseNameOf(const Path & path)
  116. {
  117. Path::size_type pos = path.rfind('/');
  118. if (pos == string::npos)
  119. throw Error(format("invalid file name `%1%'") % path);
  120. return string(path, pos + 1);
  121. }
  122. bool isInDir(const Path & path, const Path & dir)
  123. {
  124. return path[0] == '/'
  125. && string(path, 0, dir.size()) == dir
  126. && path.size() >= dir.size() + 2
  127. && path[dir.size()] == '/';
  128. }
  129. struct stat lstat(const Path & path)
  130. {
  131. struct stat st;
  132. if (lstat(path.c_str(), &st))
  133. throw SysError(format("getting status of `%1%'") % path);
  134. return st;
  135. }
  136. bool pathExists(const Path & path)
  137. {
  138. int res;
  139. #ifdef HAVE_STATX
  140. struct statx st;
  141. res = statx(AT_FDCWD, path.c_str(), AT_SYMLINK_NOFOLLOW, 0, &st);
  142. #else
  143. struct stat st;
  144. res = lstat(path.c_str(), &st);
  145. #endif
  146. if (!res) return true;
  147. if (errno != ENOENT && errno != ENOTDIR)
  148. throw SysError(format("getting status of %1%") % path);
  149. return false;
  150. }
  151. Path readLink(const Path & path)
  152. {
  153. checkInterrupt();
  154. struct stat st = lstat(path);
  155. if (!S_ISLNK(st.st_mode))
  156. throw Error(format("`%1%' is not a symlink") % path);
  157. char buf[st.st_size];
  158. ssize_t rlsize = readlink(path.c_str(), buf, st.st_size);
  159. if (rlsize == -1)
  160. throw SysError(format("reading symbolic link '%1%'") % path);
  161. else if (rlsize > st.st_size)
  162. throw Error(format("symbolic link ‘%1%’ size overflow %2% > %3%")
  163. % path % rlsize % st.st_size);
  164. return string(buf, st.st_size);
  165. }
  166. bool isLink(const Path & path)
  167. {
  168. struct stat st = lstat(path);
  169. return S_ISLNK(st.st_mode);
  170. }
  171. DirEntries readDirectory(const Path & path)
  172. {
  173. DirEntries entries;
  174. entries.reserve(64);
  175. AutoCloseDir dir = opendir(path.c_str());
  176. if (!dir) throw SysError(format("opening directory `%1%'") % path);
  177. struct dirent * dirent;
  178. while (errno = 0, dirent = readdir(dir)) { /* sic */
  179. checkInterrupt();
  180. string name = dirent->d_name;
  181. if (name == "." || name == "..") continue;
  182. entries.emplace_back(name, dirent->d_ino, dirent->d_type);
  183. }
  184. if (errno) throw SysError(format("reading directory `%1%'") % path);
  185. return entries;
  186. }
  187. unsigned char getFileType(const Path & path)
  188. {
  189. struct stat st = lstat(path);
  190. if (S_ISDIR(st.st_mode)) return DT_DIR;
  191. if (S_ISLNK(st.st_mode)) return DT_LNK;
  192. if (S_ISREG(st.st_mode)) return DT_REG;
  193. return DT_UNKNOWN;
  194. }
  195. string readFile(int fd)
  196. {
  197. struct stat st;
  198. if (fstat(fd, &st) == -1)
  199. throw SysError("statting file");
  200. unsigned char * buf = new unsigned char[st.st_size];
  201. AutoDeleteArray<unsigned char> d(buf);
  202. readFull(fd, buf, st.st_size);
  203. return string((char *) buf, st.st_size);
  204. }
  205. string readFile(const Path & path, bool drain)
  206. {
  207. AutoCloseFD fd = open(path.c_str(), O_RDONLY);
  208. if (fd == -1)
  209. throw SysError(format("opening file `%1%'") % path);
  210. return drain ? drainFD(fd) : readFile(fd);
  211. }
  212. void writeFile(const Path & path, const string & s)
  213. {
  214. AutoCloseFD fd = open(path.c_str(), O_WRONLY | O_TRUNC | O_CREAT, 0666);
  215. if (fd == -1)
  216. throw SysError(format("opening file '%1%'") % path);
  217. writeFull(fd, s);
  218. }
  219. string readLine(int fd)
  220. {
  221. string s;
  222. while (1) {
  223. checkInterrupt();
  224. char ch;
  225. ssize_t rd = read(fd, &ch, 1);
  226. if (rd == -1) {
  227. if (errno != EINTR)
  228. throw SysError("reading a line");
  229. } else if (rd == 0)
  230. throw EndOfFile("unexpected EOF reading a line");
  231. else {
  232. if (ch == '\n') return s;
  233. s += ch;
  234. }
  235. }
  236. }
  237. void writeLine(int fd, string s)
  238. {
  239. s += '\n';
  240. writeFull(fd, s);
  241. }
  242. static void _deletePath(const Path & path, unsigned long long & bytesFreed, size_t linkThreshold)
  243. {
  244. checkInterrupt();
  245. printMsg(lvlVomit, format("%1%") % path);
  246. #ifdef HAVE_STATX
  247. # define st_mode stx_mode
  248. # define st_size stx_size
  249. # define st_nlink stx_nlink
  250. struct statx st;
  251. if (statx(AT_FDCWD, path.c_str(),
  252. AT_SYMLINK_NOFOLLOW,
  253. STATX_SIZE | STATX_NLINK | STATX_MODE, &st) == -1)
  254. throw SysError(format("getting status of `%1%'") % path);
  255. #else
  256. struct stat st = lstat(path);
  257. #endif
  258. if (!S_ISDIR(st.st_mode) && st.st_nlink <= linkThreshold)
  259. bytesFreed += st.st_size;
  260. if (S_ISDIR(st.st_mode)) {
  261. /* Make the directory writable. */
  262. if (!(st.st_mode & S_IWUSR)) {
  263. if (chmod(path.c_str(), st.st_mode | S_IWUSR) == -1)
  264. throw SysError(format("making `%1%' writable") % path);
  265. }
  266. for (auto & i : readDirectory(path))
  267. _deletePath(path + "/" + i.name, bytesFreed, linkThreshold);
  268. }
  269. #undef st_mode
  270. #undef st_size
  271. #undef st_nlink
  272. if (remove(path.c_str()) == -1)
  273. throw SysError(format("cannot unlink `%1%'") % path);
  274. }
  275. void deletePath(const Path & path)
  276. {
  277. unsigned long long dummy;
  278. deletePath(path, dummy);
  279. }
  280. void deletePath(const Path & path, unsigned long long & bytesFreed, size_t linkThreshold)
  281. {
  282. startNest(nest, lvlDebug,
  283. format("recursively deleting path `%1%'") % path);
  284. bytesFreed = 0;
  285. _deletePath(path, bytesFreed, linkThreshold);
  286. }
  287. static Path tempName(Path tmpRoot, const Path & prefix, bool includePid,
  288. int & counter)
  289. {
  290. tmpRoot = canonPath(tmpRoot.empty() ? getEnv("TMPDIR", "/tmp") : tmpRoot, true);
  291. if (includePid)
  292. return (format("%1%/%2%-%3%-%4%") % tmpRoot % prefix % getpid() % counter++).str();
  293. else
  294. return (format("%1%/%2%-%3%") % tmpRoot % prefix % counter++).str();
  295. }
  296. Path createTempDir(const Path & tmpRoot, const Path & prefix,
  297. bool includePid, bool useGlobalCounter, mode_t mode)
  298. {
  299. static int globalCounter = 0;
  300. int localCounter = 0;
  301. int & counter(useGlobalCounter ? globalCounter : localCounter);
  302. while (1) {
  303. checkInterrupt();
  304. Path tmpDir = tempName(tmpRoot, prefix, includePid, counter);
  305. if (mkdir(tmpDir.c_str(), mode) == 0) {
  306. /* Explicitly set the group of the directory. This is to
  307. work around around problems caused by BSD's group
  308. ownership semantics (directories inherit the group of
  309. the parent). For instance, the group of /tmp on
  310. FreeBSD is "wheel", so all directories created in /tmp
  311. will be owned by "wheel"; but if the user is not in
  312. "wheel", then "tar" will fail to unpack archives that
  313. have the setgid bit set on directories. */
  314. if (chown(tmpDir.c_str(), (uid_t) -1, getegid()) != 0)
  315. throw SysError(format("setting group of directory `%1%'") % tmpDir);
  316. return tmpDir;
  317. }
  318. if (errno != EEXIST)
  319. throw SysError(format("creating directory `%1%'") % tmpDir);
  320. }
  321. }
  322. Paths createDirs(const Path & path)
  323. {
  324. Paths created;
  325. if (path == "/") return created;
  326. struct stat st;
  327. if (lstat(path.c_str(), &st) == -1) {
  328. created = createDirs(dirOf(path));
  329. if (mkdir(path.c_str(), 0777) == -1 && errno != EEXIST)
  330. throw SysError(format("creating directory `%1%'") % path);
  331. st = lstat(path);
  332. created.push_back(path);
  333. }
  334. if (S_ISLNK(st.st_mode) && stat(path.c_str(), &st) == -1)
  335. throw SysError(format("statting symlink `%1%'") % path);
  336. if (!S_ISDIR(st.st_mode)) throw Error(format("`%1%' is not a directory") % path);
  337. return created;
  338. }
  339. void createSymlink(const Path & target, const Path & link)
  340. {
  341. if (symlink(target.c_str(), link.c_str()))
  342. throw SysError(format("creating symlink from `%1%' to `%2%'") % link % target);
  343. }
  344. LogType logType = ltPretty;
  345. Verbosity verbosity = lvlInfo;
  346. static int nestingLevel = 0;
  347. Nest::Nest()
  348. {
  349. nest = false;
  350. }
  351. Nest::~Nest()
  352. {
  353. close();
  354. }
  355. static string escVerbosity(Verbosity level)
  356. {
  357. return std::to_string((int) level);
  358. }
  359. void Nest::open(Verbosity level, const FormatOrString & fs)
  360. {
  361. if (level <= verbosity) {
  362. if (logType == ltEscapes)
  363. std::cerr << "\033[" << escVerbosity(level) << "p"
  364. << fs.s << "\n";
  365. else
  366. printMsg_(level, fs);
  367. nest = true;
  368. nestingLevel++;
  369. }
  370. }
  371. void Nest::close()
  372. {
  373. if (nest) {
  374. nestingLevel--;
  375. if (logType == ltEscapes)
  376. std::cerr << "\033[q";
  377. nest = false;
  378. }
  379. }
  380. void printMsg_(Verbosity level, const FormatOrString & fs)
  381. {
  382. checkInterrupt();
  383. if (level > verbosity) return;
  384. string prefix;
  385. if (logType == ltPretty)
  386. for (int i = 0; i < nestingLevel; i++)
  387. prefix += "| ";
  388. else if (logType == ltEscapes && level != lvlInfo)
  389. prefix = "\033[" + escVerbosity(level) + "s";
  390. string s = (format("%1%%2%\n") % prefix % fs.s).str();
  391. writeToStderr(s);
  392. }
  393. void warnOnce(bool & haveWarned, const FormatOrString & fs)
  394. {
  395. if (!haveWarned) {
  396. printMsg(lvlError, format("warning: %1%") % fs.s);
  397. haveWarned = true;
  398. }
  399. }
  400. void writeToStderr(const string & s)
  401. {
  402. try {
  403. if (_writeToStderr)
  404. _writeToStderr((const unsigned char *) s.data(), s.size());
  405. else
  406. writeFull(STDERR_FILENO, s);
  407. } catch (SysError & e) {
  408. /* Ignore failing writes to stderr if we're in an exception
  409. handler, otherwise throw an exception. We need to ignore
  410. write errors in exception handlers to ensure that cleanup
  411. code runs to completion if the other side of stderr has
  412. been closed unexpectedly. */
  413. if (!std::uncaught_exception()) throw;
  414. }
  415. }
  416. void (*_writeToStderr) (const unsigned char * buf, size_t count) = 0;
  417. void readFull(int fd, unsigned char * buf, size_t count)
  418. {
  419. while (count) {
  420. checkInterrupt();
  421. ssize_t res = read(fd, (char *) buf, count);
  422. if (res == -1) {
  423. if (errno == EINTR) continue;
  424. throw SysError("reading from file");
  425. }
  426. if (res == 0) throw EndOfFile("unexpected end-of-file");
  427. count -= res;
  428. buf += res;
  429. }
  430. }
  431. void writeFull(int fd, const unsigned char * buf, size_t count)
  432. {
  433. while (count) {
  434. checkInterrupt();
  435. ssize_t res = write(fd, (char *) buf, count);
  436. if (res == -1) {
  437. if (errno == EINTR) continue;
  438. throw SysError("writing to file");
  439. }
  440. count -= res;
  441. buf += res;
  442. }
  443. }
  444. void writeFull(int fd, const string & s)
  445. {
  446. writeFull(fd, (const unsigned char *) s.data(), s.size());
  447. }
  448. string drainFD(int fd)
  449. {
  450. string result;
  451. unsigned char buffer[4096];
  452. while (1) {
  453. checkInterrupt();
  454. ssize_t rd = read(fd, buffer, sizeof buffer);
  455. if (rd == -1) {
  456. if (errno != EINTR)
  457. throw SysError("reading from file");
  458. }
  459. else if (rd == 0) break;
  460. else result.append((char *) buffer, rd);
  461. }
  462. return result;
  463. }
  464. //////////////////////////////////////////////////////////////////////
  465. AutoDelete::AutoDelete(const string & p, bool recursive) : path(p)
  466. {
  467. del = true;
  468. this->recursive = recursive;
  469. }
  470. AutoDelete::~AutoDelete()
  471. {
  472. try {
  473. if (del) {
  474. if (recursive)
  475. deletePath(path);
  476. else {
  477. if (remove(path.c_str()) == -1)
  478. throw SysError(format("cannot unlink `%1%'") % path);
  479. }
  480. }
  481. } catch (...) {
  482. ignoreException();
  483. }
  484. }
  485. void AutoDelete::cancel()
  486. {
  487. del = false;
  488. }
  489. //////////////////////////////////////////////////////////////////////
  490. AutoCloseFD::AutoCloseFD()
  491. {
  492. fd = -1;
  493. }
  494. AutoCloseFD::AutoCloseFD(int fd)
  495. {
  496. this->fd = fd;
  497. }
  498. AutoCloseFD::AutoCloseFD(const AutoCloseFD & fd)
  499. {
  500. /* Copying an AutoCloseFD isn't allowed (who should get to close
  501. it?). But as an edge case, allow copying of closed
  502. AutoCloseFDs. This is necessary due to tiresome reasons
  503. involving copy constructor use on default object values in STL
  504. containers (like when you do `map[value]' where value isn't in
  505. the map yet). */
  506. this->fd = fd.fd;
  507. if (this->fd != -1) abort();
  508. }
  509. AutoCloseFD::~AutoCloseFD()
  510. {
  511. try {
  512. close();
  513. } catch (...) {
  514. ignoreException();
  515. }
  516. }
  517. void AutoCloseFD::operator =(int fd)
  518. {
  519. if (this->fd != fd) close();
  520. this->fd = fd;
  521. }
  522. AutoCloseFD::operator int() const
  523. {
  524. return fd;
  525. }
  526. void AutoCloseFD::close()
  527. {
  528. if (fd != -1) {
  529. if (::close(fd) == -1)
  530. /* This should never happen. */
  531. throw SysError(format("closing file descriptor %1%") % fd);
  532. fd = -1;
  533. }
  534. }
  535. bool AutoCloseFD::isOpen()
  536. {
  537. return fd != -1;
  538. }
  539. /* Pass responsibility for closing this fd to the caller. */
  540. int AutoCloseFD::borrow()
  541. {
  542. int oldFD = fd;
  543. fd = -1;
  544. return oldFD;
  545. }
  546. void Pipe::create()
  547. {
  548. int fds[2];
  549. if (pipe(fds) != 0) throw SysError("creating pipe");
  550. readSide = fds[0];
  551. writeSide = fds[1];
  552. closeOnExec(readSide);
  553. closeOnExec(writeSide);
  554. }
  555. //////////////////////////////////////////////////////////////////////
  556. AutoCloseDir::AutoCloseDir()
  557. {
  558. dir = 0;
  559. }
  560. AutoCloseDir::AutoCloseDir(DIR * dir)
  561. {
  562. this->dir = dir;
  563. }
  564. AutoCloseDir::~AutoCloseDir()
  565. {
  566. close();
  567. }
  568. void AutoCloseDir::operator =(DIR * dir)
  569. {
  570. this->dir = dir;
  571. }
  572. AutoCloseDir::operator DIR *()
  573. {
  574. return dir;
  575. }
  576. void AutoCloseDir::close()
  577. {
  578. if (dir) {
  579. closedir(dir);
  580. dir = 0;
  581. }
  582. }
  583. //////////////////////////////////////////////////////////////////////
  584. Pid::Pid()
  585. : pid(-1), separatePG(false), killSignal(SIGKILL)
  586. {
  587. }
  588. Pid::Pid(pid_t pid)
  589. : pid(pid), separatePG(false), killSignal(SIGKILL)
  590. {
  591. }
  592. Pid::~Pid()
  593. {
  594. kill();
  595. }
  596. void Pid::operator =(pid_t pid)
  597. {
  598. if (this->pid != pid) kill();
  599. this->pid = pid;
  600. killSignal = SIGKILL; // reset signal to default
  601. }
  602. Pid::operator pid_t()
  603. {
  604. return pid;
  605. }
  606. void Pid::kill(bool quiet)
  607. {
  608. if (pid == -1 || pid == 0) return;
  609. if (!quiet)
  610. printMsg(lvlError, format("killing process %1%") % pid);
  611. /* Send the requested signal to the child. If it has its own
  612. process group, send the signal to every process in the child
  613. process group (which hopefully includes *all* its children). */
  614. if (::kill(separatePG ? -pid : pid, killSignal) != 0)
  615. printMsg(lvlError, (SysError(format("killing process %1%") % pid).msg()));
  616. /* Wait until the child dies, disregarding the exit status. */
  617. int status;
  618. while (waitpid(pid, &status, 0) == -1) {
  619. checkInterrupt();
  620. if (errno != EINTR) {
  621. printMsg(lvlError,
  622. (SysError(format("waiting for process %1%") % pid).msg()));
  623. break;
  624. }
  625. }
  626. pid = -1;
  627. }
  628. int Pid::wait(bool block)
  629. {
  630. assert(pid != -1);
  631. while (1) {
  632. int status;
  633. int res = waitpid(pid, &status, block ? 0 : WNOHANG);
  634. if (res == pid) {
  635. pid = -1;
  636. return status;
  637. }
  638. if (res == 0 && !block) return -1;
  639. if (errno != EINTR)
  640. throw SysError("cannot get child exit status");
  641. checkInterrupt();
  642. }
  643. }
  644. void Pid::setSeparatePG(bool separatePG)
  645. {
  646. this->separatePG = separatePG;
  647. }
  648. void Pid::setKillSignal(int signal)
  649. {
  650. this->killSignal = signal;
  651. }
  652. void killUser(uid_t uid)
  653. {
  654. debug(format("killing all processes running under uid `%1%'") % uid);
  655. assert(uid != 0); /* just to be safe... */
  656. /* The system call kill(-1, sig) sends the signal `sig' to all
  657. users to which the current process can send signals. So we
  658. fork a process, switch to uid, and send a mass kill. */
  659. Pid pid = startProcess([&]() {
  660. if (setuid(uid) == -1)
  661. throw SysError("setting uid");
  662. while (true) {
  663. #ifdef __APPLE__
  664. /* OSX's kill syscall takes a third parameter that, among
  665. other things, determines if kill(-1, signo) affects the
  666. calling process. In the OSX libc, it's set to true,
  667. which means "follow POSIX", which we don't want here
  668. */
  669. if (syscall(SYS_kill, -1, SIGKILL, false) == 0) break;
  670. #elif __GNU__
  671. /* Killing all a user's processes using PID=-1 does currently
  672. not work on the Hurd. */
  673. if (kill(getpid(), SIGKILL) == 0) break;
  674. #else
  675. if (kill(-1, SIGKILL) == 0) break;
  676. #endif
  677. if (errno == ESRCH) break; /* no more processes */
  678. if (errno != EINTR)
  679. throw SysError(format("cannot kill processes for uid `%1%'") % uid);
  680. }
  681. _exit(0);
  682. });
  683. int status = pid.wait(true);
  684. #if __GNU__
  685. /* When the child killed itself, status = SIGKILL. */
  686. if (status == SIGKILL) return;
  687. #endif
  688. if (status != 0)
  689. throw Error(format("cannot kill processes for uid `%1%': %2%") % uid % statusToString(status));
  690. /* !!! We should really do some check to make sure that there are
  691. no processes left running under `uid', but there is no portable
  692. way to do so (I think). The most reliable way may be `ps -eo
  693. uid | grep -q $uid'. */
  694. }
  695. //////////////////////////////////////////////////////////////////////
  696. pid_t startProcess(std::function<void()> fun,
  697. bool dieWithParent, const string & errorPrefix, bool runExitHandlers)
  698. {
  699. pid_t pid = fork();
  700. if (pid == -1) throw SysError("unable to fork");
  701. if (pid == 0) {
  702. _writeToStderr = 0;
  703. try {
  704. #if __linux__
  705. if (dieWithParent && prctl(PR_SET_PDEATHSIG, SIGKILL) == -1)
  706. throw SysError("setting death signal");
  707. #endif
  708. restoreAffinity();
  709. fun();
  710. } catch (std::exception & e) {
  711. try {
  712. std::cerr << errorPrefix << e.what() << "\n";
  713. } catch (...) { }
  714. } catch (...) { }
  715. if (runExitHandlers)
  716. exit(1);
  717. else
  718. _exit(1);
  719. }
  720. return pid;
  721. }
  722. std::vector<char *> stringsToCharPtrs(const Strings & ss)
  723. {
  724. std::vector<char *> res;
  725. for (auto & s : ss) res.push_back((char *) s.c_str());
  726. res.push_back(0);
  727. return res;
  728. }
  729. string runProgram(Path program, bool searchPath, const Strings & args)
  730. {
  731. checkInterrupt();
  732. /* Create a pipe. */
  733. Pipe pipe;
  734. pipe.create();
  735. /* Fork. */
  736. Pid pid = startProcess([&]() {
  737. if (dup2(pipe.writeSide, STDOUT_FILENO) == -1)
  738. throw SysError("dupping stdout");
  739. Strings args_(args);
  740. args_.push_front(program);
  741. if (searchPath)
  742. execvp(program.c_str(), stringsToCharPtrs(args_).data());
  743. else
  744. execv(program.c_str(), stringsToCharPtrs(args_).data());
  745. throw SysError(format("executing `%1%'") % program);
  746. });
  747. pipe.writeSide.close();
  748. string result = drainFD(pipe.readSide);
  749. /* Wait for the child to finish. */
  750. int status = pid.wait(true);
  751. if (!statusOk(status))
  752. throw ExecError(format("program `%1%' %2%")
  753. % program % statusToString(status));
  754. return result;
  755. }
  756. void closeMostFDs(const set<int> & exceptions)
  757. {
  758. int maxFD = 0;
  759. maxFD = sysconf(_SC_OPEN_MAX);
  760. for (int fd = 0; fd < maxFD; ++fd)
  761. if (fd != STDIN_FILENO && fd != STDOUT_FILENO && fd != STDERR_FILENO
  762. && exceptions.find(fd) == exceptions.end())
  763. close(fd); /* ignore result */
  764. }
  765. void closeOnExec(int fd)
  766. {
  767. int prev;
  768. if ((prev = fcntl(fd, F_GETFD, 0)) == -1 ||
  769. fcntl(fd, F_SETFD, prev | FD_CLOEXEC) == -1)
  770. throw SysError("setting close-on-exec flag");
  771. }
  772. //////////////////////////////////////////////////////////////////////
  773. volatile sig_atomic_t _isInterrupted = 0;
  774. void _interrupted()
  775. {
  776. /* Block user interrupts while an exception is being handled.
  777. Throwing an exception while another exception is being handled
  778. kills the program! */
  779. if (!std::uncaught_exception()) {
  780. _isInterrupted = 0;
  781. throw Interrupted("interrupted by the user");
  782. }
  783. }
  784. //////////////////////////////////////////////////////////////////////
  785. template<class C> C tokenizeString(const string & s, const string & separators)
  786. {
  787. C result;
  788. string::size_type pos = s.find_first_not_of(separators, 0);
  789. while (pos != string::npos) {
  790. string::size_type end = s.find_first_of(separators, pos + 1);
  791. if (end == string::npos) end = s.size();
  792. string token(s, pos, end - pos);
  793. result.insert(result.end(), token);
  794. pos = s.find_first_not_of(separators, end);
  795. }
  796. return result;
  797. }
  798. template Strings tokenizeString(const string & s, const string & separators);
  799. template StringSet tokenizeString(const string & s, const string & separators);
  800. template vector<string> tokenizeString(const string & s, const string & separators);
  801. string concatStringsSep(const string & sep, const Strings & ss)
  802. {
  803. string s;
  804. foreach (Strings::const_iterator, i, ss) {
  805. if (s.size() != 0) s += sep;
  806. s += *i;
  807. }
  808. return s;
  809. }
  810. string concatStringsSep(const string & sep, const StringSet & ss)
  811. {
  812. string s;
  813. foreach (StringSet::const_iterator, i, ss) {
  814. if (s.size() != 0) s += sep;
  815. s += *i;
  816. }
  817. return s;
  818. }
  819. string chomp(const string & s)
  820. {
  821. size_t i = s.find_last_not_of(" \n\r\t");
  822. return i == string::npos ? "" : string(s, 0, i + 1);
  823. }
  824. string statusToString(int status)
  825. {
  826. if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
  827. if (WIFEXITED(status))
  828. return (format("failed with exit code %1%") % WEXITSTATUS(status)).str();
  829. else if (WIFSIGNALED(status)) {
  830. int sig = WTERMSIG(status);
  831. #if HAVE_STRSIGNAL
  832. const char * description = strsignal(sig);
  833. return (format("failed due to signal %1% (%2%)") % sig % description).str();
  834. #else
  835. return (format("failed due to signal %1%") % sig).str();
  836. #endif
  837. }
  838. else
  839. return "died abnormally";
  840. } else return "succeeded";
  841. }
  842. bool statusOk(int status)
  843. {
  844. return WIFEXITED(status) && WEXITSTATUS(status) == 0;
  845. }
  846. bool hasSuffix(const string & s, const string & suffix)
  847. {
  848. return s.size() >= suffix.size() && string(s, s.size() - suffix.size()) == suffix;
  849. }
  850. void expect(std::istream & str, const string & s)
  851. {
  852. char s2[s.size()];
  853. str.read(s2, s.size());
  854. if (string(s2, s.size()) != s)
  855. throw FormatError(format("expected string `%1%'") % s);
  856. }
  857. string parseString(std::istream & str)
  858. {
  859. string res;
  860. expect(str, "\"");
  861. int c;
  862. while ((c = str.get()) != '"')
  863. if (c == '\\') {
  864. c = str.get();
  865. if (c == 'n') res += '\n';
  866. else if (c == 'r') res += '\r';
  867. else if (c == 't') res += '\t';
  868. else res += c;
  869. }
  870. else res += c;
  871. return res;
  872. }
  873. bool endOfList(std::istream & str)
  874. {
  875. if (str.peek() == ',') {
  876. str.get();
  877. return false;
  878. }
  879. if (str.peek() == ']') {
  880. str.get();
  881. return true;
  882. }
  883. return false;
  884. }
  885. void ignoreException()
  886. {
  887. try {
  888. throw;
  889. } catch (std::exception & e) {
  890. printMsg(lvlError, format("error (ignored): %1%") % e.what());
  891. }
  892. }
  893. static const string pathNullDevice = "/dev/null";
  894. /* Common initialisation performed in child processes. */
  895. void commonChildInit(Pipe & logPipe)
  896. {
  897. /* Put the child in a separate session (and thus a separate
  898. process group) so that it has no controlling terminal (meaning
  899. that e.g. ssh cannot open /dev/tty) and it doesn't receive
  900. terminal signals. */
  901. if (setsid() == -1)
  902. throw SysError(format("creating a new session"));
  903. /* Dup the write side of the logger pipe into stderr. */
  904. if (dup2(logPipe.writeSide, STDERR_FILENO) == -1)
  905. throw SysError("cannot pipe standard error into log file");
  906. /* Dup stderr to stdout. */
  907. if (dup2(STDERR_FILENO, STDOUT_FILENO) == -1)
  908. throw SysError("cannot dup stderr into stdout");
  909. /* Reroute stdin to /dev/null. */
  910. int fdDevNull = open(pathNullDevice.c_str(), O_RDWR);
  911. if (fdDevNull == -1)
  912. throw SysError(format("cannot open `%1%'") % pathNullDevice);
  913. if (dup2(fdDevNull, STDIN_FILENO) == -1)
  914. throw SysError("cannot dup null device into stdin");
  915. close(fdDevNull);
  916. }
  917. //////////////////////////////////////////////////////////////////////
  918. Agent::Agent(const string &command, const Strings &args)
  919. {
  920. debug(format("starting agent '%1%'") % command);
  921. /* Create a pipe to get the output of the child. */
  922. fromAgent.create();
  923. /* Create the communication pipes. */
  924. toAgent.create();
  925. /* Create a pipe to get the output of the builder. */
  926. builderOut.create();
  927. /* Fork the hook. */
  928. pid = startProcess([&]() {
  929. commonChildInit(fromAgent);
  930. if (chdir("/") == -1) throw SysError("changing into `/");
  931. /* Dup the communication pipes. */
  932. if (dup2(toAgent.readSide, STDIN_FILENO) == -1)
  933. throw SysError("dupping to-hook read side");
  934. /* Use fd 4 for the builder's stdout/stderr. */
  935. if (dup2(builderOut.writeSide, 4) == -1)
  936. throw SysError("dupping builder's stdout/stderr");
  937. Strings allArgs;
  938. allArgs.push_back(command);
  939. allArgs.insert(allArgs.end(), args.begin(), args.end()); // append
  940. execv(command.c_str(), stringsToCharPtrs(allArgs).data());
  941. throw SysError(format("executing `%1%'") % command);
  942. });
  943. pid.setSeparatePG(true);
  944. fromAgent.writeSide.close();
  945. toAgent.readSide.close();
  946. }
  947. Agent::~Agent()
  948. {
  949. try {
  950. toAgent.writeSide.close();
  951. pid.kill(true);
  952. } catch (...) {
  953. ignoreException();
  954. }
  955. }
  956. }