util.cc 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235
  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, const std::map<string, string> &env)
  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. for (auto pair: env) {
  931. setenv(pair.first.c_str(), pair.second.c_str(), 1);
  932. }
  933. if (chdir("/") == -1) throw SysError("changing into `/");
  934. /* Dup the communication pipes. */
  935. if (dup2(toAgent.readSide, STDIN_FILENO) == -1)
  936. throw SysError("dupping to-hook read side");
  937. /* Use fd 4 for the builder's stdout/stderr. */
  938. if (dup2(builderOut.writeSide, 4) == -1)
  939. throw SysError("dupping builder's stdout/stderr");
  940. Strings allArgs;
  941. allArgs.push_back(command);
  942. allArgs.insert(allArgs.end(), args.begin(), args.end()); // append
  943. execv(command.c_str(), stringsToCharPtrs(allArgs).data());
  944. throw SysError(format("executing `%1%'") % command);
  945. });
  946. pid.setSeparatePG(true);
  947. fromAgent.writeSide.close();
  948. toAgent.readSide.close();
  949. }
  950. Agent::~Agent()
  951. {
  952. try {
  953. toAgent.writeSide.close();
  954. pid.kill(true);
  955. } catch (...) {
  956. ignoreException();
  957. }
  958. }
  959. }