util.cc 25 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120
  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. struct stat st;
  140. res = lstat(path.c_str(), &st);
  141. if (!res) return true;
  142. if (errno != ENOENT && errno != ENOTDIR)
  143. throw SysError(format("getting status of %1%") % path);
  144. return false;
  145. }
  146. Path readLink(const Path & path)
  147. {
  148. checkInterrupt();
  149. struct stat st = lstat(path);
  150. if (!S_ISLNK(st.st_mode))
  151. throw Error(format("`%1%' is not a symlink") % path);
  152. char buf[st.st_size];
  153. ssize_t rlsize = readlink(path.c_str(), buf, st.st_size);
  154. if (rlsize == -1)
  155. throw SysError(format("reading symbolic link '%1%'") % path);
  156. else if (rlsize > st.st_size)
  157. throw Error(format("symbolic link ‘%1%’ size overflow %2% > %3%")
  158. % path % rlsize % st.st_size);
  159. return string(buf, st.st_size);
  160. }
  161. bool isLink(const Path & path)
  162. {
  163. struct stat st = lstat(path);
  164. return S_ISLNK(st.st_mode);
  165. }
  166. DirEntries readDirectory(const Path & path)
  167. {
  168. DirEntries entries;
  169. entries.reserve(64);
  170. AutoCloseDir dir = opendir(path.c_str());
  171. if (!dir) throw SysError(format("opening directory `%1%'") % path);
  172. struct dirent * dirent;
  173. while (errno = 0, dirent = readdir(dir)) { /* sic */
  174. checkInterrupt();
  175. string name = dirent->d_name;
  176. if (name == "." || name == "..") continue;
  177. entries.emplace_back(name, dirent->d_ino, dirent->d_type);
  178. }
  179. if (errno) throw SysError(format("reading directory `%1%'") % path);
  180. return entries;
  181. }
  182. unsigned char getFileType(const Path & path)
  183. {
  184. struct stat st = lstat(path);
  185. if (S_ISDIR(st.st_mode)) return DT_DIR;
  186. if (S_ISLNK(st.st_mode)) return DT_LNK;
  187. if (S_ISREG(st.st_mode)) return DT_REG;
  188. return DT_UNKNOWN;
  189. }
  190. string readFile(int fd)
  191. {
  192. struct stat st;
  193. if (fstat(fd, &st) == -1)
  194. throw SysError("statting file");
  195. unsigned char * buf = new unsigned char[st.st_size];
  196. AutoDeleteArray<unsigned char> d(buf);
  197. readFull(fd, buf, st.st_size);
  198. return string((char *) buf, st.st_size);
  199. }
  200. string readFile(const Path & path, bool drain)
  201. {
  202. AutoCloseFD fd = open(path.c_str(), O_RDONLY);
  203. if (fd == -1)
  204. throw SysError(format("opening file `%1%'") % path);
  205. return drain ? drainFD(fd) : readFile(fd);
  206. }
  207. void writeFile(const Path & path, const string & s)
  208. {
  209. AutoCloseFD fd = open(path.c_str(), O_WRONLY | O_TRUNC | O_CREAT, 0666);
  210. if (fd == -1)
  211. throw SysError(format("opening file '%1%'") % path);
  212. writeFull(fd, s);
  213. }
  214. string readLine(int fd)
  215. {
  216. string s;
  217. while (1) {
  218. checkInterrupt();
  219. char ch;
  220. ssize_t rd = read(fd, &ch, 1);
  221. if (rd == -1) {
  222. if (errno != EINTR)
  223. throw SysError("reading a line");
  224. } else if (rd == 0)
  225. throw EndOfFile("unexpected EOF reading a line");
  226. else {
  227. if (ch == '\n') return s;
  228. s += ch;
  229. }
  230. }
  231. }
  232. void writeLine(int fd, string s)
  233. {
  234. s += '\n';
  235. writeFull(fd, s);
  236. }
  237. static void _deletePath(const Path & path, unsigned long long & bytesFreed)
  238. {
  239. checkInterrupt();
  240. printMsg(lvlVomit, format("%1%") % path);
  241. struct stat st = lstat(path);
  242. if (!S_ISDIR(st.st_mode) && st.st_nlink == 1)
  243. bytesFreed += st.st_blocks * 512;
  244. if (S_ISDIR(st.st_mode)) {
  245. /* Make the directory writable. */
  246. if (!(st.st_mode & S_IWUSR)) {
  247. if (chmod(path.c_str(), st.st_mode | S_IWUSR) == -1)
  248. throw SysError(format("making `%1%' writable") % path);
  249. }
  250. for (auto & i : readDirectory(path))
  251. _deletePath(path + "/" + i.name, bytesFreed);
  252. }
  253. if (remove(path.c_str()) == -1)
  254. throw SysError(format("cannot unlink `%1%'") % path);
  255. }
  256. void deletePath(const Path & path)
  257. {
  258. unsigned long long dummy;
  259. deletePath(path, dummy);
  260. }
  261. void deletePath(const Path & path, unsigned long long & bytesFreed)
  262. {
  263. startNest(nest, lvlDebug,
  264. format("recursively deleting path `%1%'") % path);
  265. bytesFreed = 0;
  266. _deletePath(path, bytesFreed);
  267. }
  268. static Path tempName(Path tmpRoot, const Path & prefix, bool includePid,
  269. int & counter)
  270. {
  271. tmpRoot = canonPath(tmpRoot.empty() ? getEnv("TMPDIR", "/tmp") : tmpRoot, true);
  272. if (includePid)
  273. return (format("%1%/%2%-%3%-%4%") % tmpRoot % prefix % getpid() % counter++).str();
  274. else
  275. return (format("%1%/%2%-%3%") % tmpRoot % prefix % counter++).str();
  276. }
  277. Path createTempDir(const Path & tmpRoot, const Path & prefix,
  278. bool includePid, bool useGlobalCounter, mode_t mode)
  279. {
  280. static int globalCounter = 0;
  281. int localCounter = 0;
  282. int & counter(useGlobalCounter ? globalCounter : localCounter);
  283. while (1) {
  284. checkInterrupt();
  285. Path tmpDir = tempName(tmpRoot, prefix, includePid, counter);
  286. if (mkdir(tmpDir.c_str(), mode) == 0) {
  287. /* Explicitly set the group of the directory. This is to
  288. work around around problems caused by BSD's group
  289. ownership semantics (directories inherit the group of
  290. the parent). For instance, the group of /tmp on
  291. FreeBSD is "wheel", so all directories created in /tmp
  292. will be owned by "wheel"; but if the user is not in
  293. "wheel", then "tar" will fail to unpack archives that
  294. have the setgid bit set on directories. */
  295. if (chown(tmpDir.c_str(), (uid_t) -1, getegid()) != 0)
  296. throw SysError(format("setting group of directory `%1%'") % tmpDir);
  297. return tmpDir;
  298. }
  299. if (errno != EEXIST)
  300. throw SysError(format("creating directory `%1%'") % tmpDir);
  301. }
  302. }
  303. Paths createDirs(const Path & path)
  304. {
  305. Paths created;
  306. if (path == "/") return created;
  307. struct stat st;
  308. if (lstat(path.c_str(), &st) == -1) {
  309. created = createDirs(dirOf(path));
  310. if (mkdir(path.c_str(), 0777) == -1 && errno != EEXIST)
  311. throw SysError(format("creating directory `%1%'") % path);
  312. st = lstat(path);
  313. created.push_back(path);
  314. }
  315. if (S_ISLNK(st.st_mode) && stat(path.c_str(), &st) == -1)
  316. throw SysError(format("statting symlink `%1%'") % path);
  317. if (!S_ISDIR(st.st_mode)) throw Error(format("`%1%' is not a directory") % path);
  318. return created;
  319. }
  320. void createSymlink(const Path & target, const Path & link)
  321. {
  322. if (symlink(target.c_str(), link.c_str()))
  323. throw SysError(format("creating symlink from `%1%' to `%2%'") % link % target);
  324. }
  325. LogType logType = ltPretty;
  326. Verbosity verbosity = lvlInfo;
  327. static int nestingLevel = 0;
  328. Nest::Nest()
  329. {
  330. nest = false;
  331. }
  332. Nest::~Nest()
  333. {
  334. close();
  335. }
  336. static string escVerbosity(Verbosity level)
  337. {
  338. return std::to_string((int) level);
  339. }
  340. void Nest::open(Verbosity level, const FormatOrString & fs)
  341. {
  342. if (level <= verbosity) {
  343. if (logType == ltEscapes)
  344. std::cerr << "\033[" << escVerbosity(level) << "p"
  345. << fs.s << "\n";
  346. else
  347. printMsg_(level, fs);
  348. nest = true;
  349. nestingLevel++;
  350. }
  351. }
  352. void Nest::close()
  353. {
  354. if (nest) {
  355. nestingLevel--;
  356. if (logType == ltEscapes)
  357. std::cerr << "\033[q";
  358. nest = false;
  359. }
  360. }
  361. void printMsg_(Verbosity level, const FormatOrString & fs)
  362. {
  363. checkInterrupt();
  364. if (level > verbosity) return;
  365. string prefix;
  366. if (logType == ltPretty)
  367. for (int i = 0; i < nestingLevel; i++)
  368. prefix += "| ";
  369. else if (logType == ltEscapes && level != lvlInfo)
  370. prefix = "\033[" + escVerbosity(level) + "s";
  371. string s = (format("%1%%2%\n") % prefix % fs.s).str();
  372. writeToStderr(s);
  373. }
  374. void warnOnce(bool & haveWarned, const FormatOrString & fs)
  375. {
  376. if (!haveWarned) {
  377. printMsg(lvlError, format("warning: %1%") % fs.s);
  378. haveWarned = true;
  379. }
  380. }
  381. void writeToStderr(const string & s)
  382. {
  383. try {
  384. if (_writeToStderr)
  385. _writeToStderr((const unsigned char *) s.data(), s.size());
  386. else
  387. writeFull(STDERR_FILENO, s);
  388. } catch (SysError & e) {
  389. /* Ignore failing writes to stderr if we're in an exception
  390. handler, otherwise throw an exception. We need to ignore
  391. write errors in exception handlers to ensure that cleanup
  392. code runs to completion if the other side of stderr has
  393. been closed unexpectedly. */
  394. if (!std::uncaught_exception()) throw;
  395. }
  396. }
  397. void (*_writeToStderr) (const unsigned char * buf, size_t count) = 0;
  398. void readFull(int fd, unsigned char * buf, size_t count)
  399. {
  400. while (count) {
  401. checkInterrupt();
  402. ssize_t res = read(fd, (char *) buf, count);
  403. if (res == -1) {
  404. if (errno == EINTR) continue;
  405. throw SysError("reading from file");
  406. }
  407. if (res == 0) throw EndOfFile("unexpected end-of-file");
  408. count -= res;
  409. buf += res;
  410. }
  411. }
  412. void writeFull(int fd, const unsigned char * buf, size_t count)
  413. {
  414. while (count) {
  415. checkInterrupt();
  416. ssize_t res = write(fd, (char *) buf, count);
  417. if (res == -1) {
  418. if (errno == EINTR) continue;
  419. throw SysError("writing to file");
  420. }
  421. count -= res;
  422. buf += res;
  423. }
  424. }
  425. void writeFull(int fd, const string & s)
  426. {
  427. writeFull(fd, (const unsigned char *) s.data(), s.size());
  428. }
  429. string drainFD(int fd)
  430. {
  431. string result;
  432. unsigned char buffer[4096];
  433. while (1) {
  434. checkInterrupt();
  435. ssize_t rd = read(fd, buffer, sizeof buffer);
  436. if (rd == -1) {
  437. if (errno != EINTR)
  438. throw SysError("reading from file");
  439. }
  440. else if (rd == 0) break;
  441. else result.append((char *) buffer, rd);
  442. }
  443. return result;
  444. }
  445. //////////////////////////////////////////////////////////////////////
  446. AutoDelete::AutoDelete(const string & p, bool recursive) : path(p)
  447. {
  448. del = true;
  449. this->recursive = recursive;
  450. }
  451. AutoDelete::~AutoDelete()
  452. {
  453. try {
  454. if (del) {
  455. if (recursive)
  456. deletePath(path);
  457. else {
  458. if (remove(path.c_str()) == -1)
  459. throw SysError(format("cannot unlink `%1%'") % path);
  460. }
  461. }
  462. } catch (...) {
  463. ignoreException();
  464. }
  465. }
  466. void AutoDelete::cancel()
  467. {
  468. del = false;
  469. }
  470. //////////////////////////////////////////////////////////////////////
  471. AutoCloseFD::AutoCloseFD()
  472. {
  473. fd = -1;
  474. }
  475. AutoCloseFD::AutoCloseFD(int fd)
  476. {
  477. this->fd = fd;
  478. }
  479. AutoCloseFD::AutoCloseFD(const AutoCloseFD & fd)
  480. {
  481. /* Copying an AutoCloseFD isn't allowed (who should get to close
  482. it?). But as an edge case, allow copying of closed
  483. AutoCloseFDs. This is necessary due to tiresome reasons
  484. involving copy constructor use on default object values in STL
  485. containers (like when you do `map[value]' where value isn't in
  486. the map yet). */
  487. this->fd = fd.fd;
  488. if (this->fd != -1) abort();
  489. }
  490. AutoCloseFD::~AutoCloseFD()
  491. {
  492. try {
  493. close();
  494. } catch (...) {
  495. ignoreException();
  496. }
  497. }
  498. void AutoCloseFD::operator =(int fd)
  499. {
  500. if (this->fd != fd) close();
  501. this->fd = fd;
  502. }
  503. AutoCloseFD::operator int() const
  504. {
  505. return fd;
  506. }
  507. void AutoCloseFD::close()
  508. {
  509. if (fd != -1) {
  510. if (::close(fd) == -1)
  511. /* This should never happen. */
  512. throw SysError(format("closing file descriptor %1%") % fd);
  513. fd = -1;
  514. }
  515. }
  516. bool AutoCloseFD::isOpen()
  517. {
  518. return fd != -1;
  519. }
  520. /* Pass responsibility for closing this fd to the caller. */
  521. int AutoCloseFD::borrow()
  522. {
  523. int oldFD = fd;
  524. fd = -1;
  525. return oldFD;
  526. }
  527. void Pipe::create()
  528. {
  529. int fds[2];
  530. if (pipe(fds) != 0) throw SysError("creating pipe");
  531. readSide = fds[0];
  532. writeSide = fds[1];
  533. closeOnExec(readSide);
  534. closeOnExec(writeSide);
  535. }
  536. //////////////////////////////////////////////////////////////////////
  537. AutoCloseDir::AutoCloseDir()
  538. {
  539. dir = 0;
  540. }
  541. AutoCloseDir::AutoCloseDir(DIR * dir)
  542. {
  543. this->dir = dir;
  544. }
  545. AutoCloseDir::~AutoCloseDir()
  546. {
  547. close();
  548. }
  549. void AutoCloseDir::operator =(DIR * dir)
  550. {
  551. this->dir = dir;
  552. }
  553. AutoCloseDir::operator DIR *()
  554. {
  555. return dir;
  556. }
  557. void AutoCloseDir::close()
  558. {
  559. if (dir) {
  560. closedir(dir);
  561. dir = 0;
  562. }
  563. }
  564. //////////////////////////////////////////////////////////////////////
  565. Pid::Pid()
  566. : pid(-1), separatePG(false), killSignal(SIGKILL)
  567. {
  568. }
  569. Pid::Pid(pid_t pid)
  570. : pid(pid), separatePG(false), killSignal(SIGKILL)
  571. {
  572. }
  573. Pid::~Pid()
  574. {
  575. kill();
  576. }
  577. void Pid::operator =(pid_t pid)
  578. {
  579. if (this->pid != pid) kill();
  580. this->pid = pid;
  581. killSignal = SIGKILL; // reset signal to default
  582. }
  583. Pid::operator pid_t()
  584. {
  585. return pid;
  586. }
  587. void Pid::kill(bool quiet)
  588. {
  589. if (pid == -1 || pid == 0) return;
  590. if (!quiet)
  591. printMsg(lvlError, format("killing process %1%") % pid);
  592. /* Send the requested signal to the child. If it has its own
  593. process group, send the signal to every process in the child
  594. process group (which hopefully includes *all* its children). */
  595. if (::kill(separatePG ? -pid : pid, killSignal) != 0)
  596. printMsg(lvlError, (SysError(format("killing process %1%") % pid).msg()));
  597. /* Wait until the child dies, disregarding the exit status. */
  598. int status;
  599. while (waitpid(pid, &status, 0) == -1) {
  600. checkInterrupt();
  601. if (errno != EINTR) {
  602. printMsg(lvlError,
  603. (SysError(format("waiting for process %1%") % pid).msg()));
  604. break;
  605. }
  606. }
  607. pid = -1;
  608. }
  609. int Pid::wait(bool block)
  610. {
  611. assert(pid != -1);
  612. while (1) {
  613. int status;
  614. int res = waitpid(pid, &status, block ? 0 : WNOHANG);
  615. if (res == pid) {
  616. pid = -1;
  617. return status;
  618. }
  619. if (res == 0 && !block) return -1;
  620. if (errno != EINTR)
  621. throw SysError("cannot get child exit status");
  622. checkInterrupt();
  623. }
  624. }
  625. void Pid::setSeparatePG(bool separatePG)
  626. {
  627. this->separatePG = separatePG;
  628. }
  629. void Pid::setKillSignal(int signal)
  630. {
  631. this->killSignal = signal;
  632. }
  633. void killUser(uid_t uid)
  634. {
  635. debug(format("killing all processes running under uid `%1%'") % uid);
  636. assert(uid != 0); /* just to be safe... */
  637. /* The system call kill(-1, sig) sends the signal `sig' to all
  638. users to which the current process can send signals. So we
  639. fork a process, switch to uid, and send a mass kill. */
  640. Pid pid = startProcess([&]() {
  641. if (setuid(uid) == -1)
  642. throw SysError("setting uid");
  643. while (true) {
  644. #ifdef __APPLE__
  645. /* OSX's kill syscall takes a third parameter that, among
  646. other things, determines if kill(-1, signo) affects the
  647. calling process. In the OSX libc, it's set to true,
  648. which means "follow POSIX", which we don't want here
  649. */
  650. if (syscall(SYS_kill, -1, SIGKILL, false) == 0) break;
  651. #else
  652. if (kill(-1, SIGKILL) == 0) break;
  653. #endif
  654. if (errno == ESRCH) break; /* no more processes */
  655. if (errno != EINTR)
  656. throw SysError(format("cannot kill processes for uid `%1%'") % uid);
  657. }
  658. _exit(0);
  659. });
  660. int status = pid.wait(true);
  661. if (status != 0)
  662. throw Error(format("cannot kill processes for uid `%1%': %2%") % uid % statusToString(status));
  663. /* !!! We should really do some check to make sure that there are
  664. no processes left running under `uid', but there is no portable
  665. way to do so (I think). The most reliable way may be `ps -eo
  666. uid | grep -q $uid'. */
  667. }
  668. //////////////////////////////////////////////////////////////////////
  669. pid_t startProcess(std::function<void()> fun,
  670. bool dieWithParent, const string & errorPrefix, bool runExitHandlers)
  671. {
  672. pid_t pid = fork();
  673. if (pid == -1) throw SysError("unable to fork");
  674. if (pid == 0) {
  675. _writeToStderr = 0;
  676. try {
  677. #if __linux__
  678. if (dieWithParent && prctl(PR_SET_PDEATHSIG, SIGKILL) == -1)
  679. throw SysError("setting death signal");
  680. #endif
  681. restoreAffinity();
  682. fun();
  683. } catch (std::exception & e) {
  684. try {
  685. std::cerr << errorPrefix << e.what() << "\n";
  686. } catch (...) { }
  687. } catch (...) { }
  688. if (runExitHandlers)
  689. exit(1);
  690. else
  691. _exit(1);
  692. }
  693. return pid;
  694. }
  695. std::vector<char *> stringsToCharPtrs(const Strings & ss)
  696. {
  697. std::vector<char *> res;
  698. for (auto & s : ss) res.push_back((char *) s.c_str());
  699. res.push_back(0);
  700. return res;
  701. }
  702. string runProgram(Path program, bool searchPath, const Strings & args)
  703. {
  704. checkInterrupt();
  705. /* Create a pipe. */
  706. Pipe pipe;
  707. pipe.create();
  708. /* Fork. */
  709. Pid pid = startProcess([&]() {
  710. if (dup2(pipe.writeSide, STDOUT_FILENO) == -1)
  711. throw SysError("dupping stdout");
  712. Strings args_(args);
  713. args_.push_front(program);
  714. if (searchPath)
  715. execvp(program.c_str(), stringsToCharPtrs(args_).data());
  716. else
  717. execv(program.c_str(), stringsToCharPtrs(args_).data());
  718. throw SysError(format("executing `%1%'") % program);
  719. });
  720. pipe.writeSide.close();
  721. string result = drainFD(pipe.readSide);
  722. /* Wait for the child to finish. */
  723. int status = pid.wait(true);
  724. if (!statusOk(status))
  725. throw ExecError(format("program `%1%' %2%")
  726. % program % statusToString(status));
  727. return result;
  728. }
  729. void closeMostFDs(const set<int> & exceptions)
  730. {
  731. int maxFD = 0;
  732. maxFD = sysconf(_SC_OPEN_MAX);
  733. for (int fd = 0; fd < maxFD; ++fd)
  734. if (fd != STDIN_FILENO && fd != STDOUT_FILENO && fd != STDERR_FILENO
  735. && exceptions.find(fd) == exceptions.end())
  736. close(fd); /* ignore result */
  737. }
  738. void closeOnExec(int fd)
  739. {
  740. int prev;
  741. if ((prev = fcntl(fd, F_GETFD, 0)) == -1 ||
  742. fcntl(fd, F_SETFD, prev | FD_CLOEXEC) == -1)
  743. throw SysError("setting close-on-exec flag");
  744. }
  745. //////////////////////////////////////////////////////////////////////
  746. volatile sig_atomic_t _isInterrupted = 0;
  747. void _interrupted()
  748. {
  749. /* Block user interrupts while an exception is being handled.
  750. Throwing an exception while another exception is being handled
  751. kills the program! */
  752. if (!std::uncaught_exception()) {
  753. _isInterrupted = 0;
  754. throw Interrupted("interrupted by the user");
  755. }
  756. }
  757. //////////////////////////////////////////////////////////////////////
  758. template<class C> C tokenizeString(const string & s, const string & separators)
  759. {
  760. C result;
  761. string::size_type pos = s.find_first_not_of(separators, 0);
  762. while (pos != string::npos) {
  763. string::size_type end = s.find_first_of(separators, pos + 1);
  764. if (end == string::npos) end = s.size();
  765. string token(s, pos, end - pos);
  766. result.insert(result.end(), token);
  767. pos = s.find_first_not_of(separators, end);
  768. }
  769. return result;
  770. }
  771. template Strings tokenizeString(const string & s, const string & separators);
  772. template StringSet tokenizeString(const string & s, const string & separators);
  773. template vector<string> tokenizeString(const string & s, const string & separators);
  774. string concatStringsSep(const string & sep, const Strings & ss)
  775. {
  776. string s;
  777. foreach (Strings::const_iterator, i, ss) {
  778. if (s.size() != 0) s += sep;
  779. s += *i;
  780. }
  781. return s;
  782. }
  783. string concatStringsSep(const string & sep, const StringSet & ss)
  784. {
  785. string s;
  786. foreach (StringSet::const_iterator, i, ss) {
  787. if (s.size() != 0) s += sep;
  788. s += *i;
  789. }
  790. return s;
  791. }
  792. string chomp(const string & s)
  793. {
  794. size_t i = s.find_last_not_of(" \n\r\t");
  795. return i == string::npos ? "" : string(s, 0, i + 1);
  796. }
  797. string statusToString(int status)
  798. {
  799. if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
  800. if (WIFEXITED(status))
  801. return (format("failed with exit code %1%") % WEXITSTATUS(status)).str();
  802. else if (WIFSIGNALED(status)) {
  803. int sig = WTERMSIG(status);
  804. #if HAVE_STRSIGNAL
  805. const char * description = strsignal(sig);
  806. return (format("failed due to signal %1% (%2%)") % sig % description).str();
  807. #else
  808. return (format("failed due to signal %1%") % sig).str();
  809. #endif
  810. }
  811. else
  812. return "died abnormally";
  813. } else return "succeeded";
  814. }
  815. bool statusOk(int status)
  816. {
  817. return WIFEXITED(status) && WEXITSTATUS(status) == 0;
  818. }
  819. bool hasSuffix(const string & s, const string & suffix)
  820. {
  821. return s.size() >= suffix.size() && string(s, s.size() - suffix.size()) == suffix;
  822. }
  823. void expect(std::istream & str, const string & s)
  824. {
  825. char s2[s.size()];
  826. str.read(s2, s.size());
  827. if (string(s2, s.size()) != s)
  828. throw FormatError(format("expected string `%1%'") % s);
  829. }
  830. string parseString(std::istream & str)
  831. {
  832. string res;
  833. expect(str, "\"");
  834. int c;
  835. while ((c = str.get()) != '"')
  836. if (c == '\\') {
  837. c = str.get();
  838. if (c == 'n') res += '\n';
  839. else if (c == 'r') res += '\r';
  840. else if (c == 't') res += '\t';
  841. else res += c;
  842. }
  843. else res += c;
  844. return res;
  845. }
  846. bool endOfList(std::istream & str)
  847. {
  848. if (str.peek() == ',') {
  849. str.get();
  850. return false;
  851. }
  852. if (str.peek() == ']') {
  853. str.get();
  854. return true;
  855. }
  856. return false;
  857. }
  858. void ignoreException()
  859. {
  860. try {
  861. throw;
  862. } catch (std::exception & e) {
  863. printMsg(lvlError, format("error (ignored): %1%") % e.what());
  864. }
  865. }
  866. }