util.hh 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. #pragma once
  2. #include "types.hh"
  3. #include <sys/types.h>
  4. #include <sys/stat.h>
  5. #include <dirent.h>
  6. #include <unistd.h>
  7. #include <signal.h>
  8. #include <functional>
  9. #include <cstdio>
  10. namespace nix {
  11. #define foreach(it_type, it, collection) \
  12. for (it_type it = (collection).begin(); it != (collection).end(); ++it)
  13. #define foreach_reverse(it_type, it, collection) \
  14. for (it_type it = (collection).rbegin(); it != (collection).rend(); ++it)
  15. /* Return an environment variable. */
  16. string getEnv(const string & key, const string & def = "");
  17. /* Return an absolutized path, resolving paths relative to the
  18. specified directory, or the current directory otherwise. The path
  19. is also canonicalised. */
  20. Path absPath(Path path, Path dir = "");
  21. /* Canonicalise a path by removing all `.' or `..' components and
  22. double or trailing slashes. Optionally resolves all symlink
  23. components such that each component of the resulting path is *not*
  24. a symbolic link. */
  25. Path canonPath(const Path & path, bool resolveSymlinks = false);
  26. /* Return the directory part of the given canonical path, i.e.,
  27. everything before the final `/'. If the path is the root or an
  28. immediate child thereof (e.g., `/foo'), this means an empty string
  29. is returned. */
  30. Path dirOf(const Path & path);
  31. /* Return the base name of the given canonical path, i.e., everything
  32. following the final `/'. */
  33. string baseNameOf(const Path & path);
  34. /* Check whether a given path is a descendant of the given
  35. directory. */
  36. bool isInDir(const Path & path, const Path & dir);
  37. /* Get status of `path'. */
  38. struct stat lstat(const Path & path);
  39. /* Return true iff the given path exists. */
  40. bool pathExists(const Path & path);
  41. /* Read the contents (target) of a symbolic link. The result is not
  42. in any way canonicalised. */
  43. Path readLink(const Path & path);
  44. bool isLink(const Path & path);
  45. /* Read the contents of a directory. The entries `.' and `..' are
  46. removed. */
  47. struct DirEntry
  48. {
  49. string name;
  50. ino_t ino;
  51. unsigned char type; // one of DT_*
  52. DirEntry(const string & name, ino_t ino, unsigned char type)
  53. : name(name), ino(ino), type(type) { }
  54. };
  55. typedef vector<DirEntry> DirEntries;
  56. DirEntries readDirectory(const Path & path);
  57. unsigned char getFileType(const Path & path);
  58. /* Read the contents of a file into a string. */
  59. string readFile(int fd);
  60. string readFile(const Path & path, bool drain = false);
  61. /* Write a string to a file. */
  62. void writeFile(const Path & path, const string & s);
  63. /* Read a line from a file descriptor. */
  64. string readLine(int fd);
  65. /* Write a line to a file descriptor. */
  66. void writeLine(int fd, string s);
  67. /* Delete a path; i.e., in the case of a directory, it is deleted
  68. recursively. Don't use this at home, kids. The second variant
  69. returns the number of bytes and blocks freed, and 'linkThreshold' denotes
  70. the number of links under which a file is accounted for in 'bytesFreed'. */
  71. void deletePath(const Path & path);
  72. void deletePath(const Path & path, unsigned long long & bytesFreed,
  73. size_t linkThreshold = 1);
  74. /* Create a temporary directory. */
  75. Path createTempDir(const Path & tmpRoot = "", const Path & prefix = "nix",
  76. bool includePid = true, bool useGlobalCounter = true, mode_t mode = 0755);
  77. /* Create a directory and all its parents, if necessary. Returns the
  78. list of created directories, in order of creation. */
  79. Paths createDirs(const Path & path);
  80. /* Create a symlink. */
  81. void createSymlink(const Path & target, const Path & link);
  82. template<class T, class A>
  83. T singleton(const A & a)
  84. {
  85. T t;
  86. t.insert(a);
  87. return t;
  88. }
  89. /* Messages. */
  90. typedef enum {
  91. ltPretty, /* nice, nested output */
  92. ltEscapes, /* nesting indicated using escape codes (for log2xml) */
  93. ltFlat /* no nesting */
  94. } LogType;
  95. extern LogType logType;
  96. extern Verbosity verbosity; /* suppress msgs > this */
  97. class Nest
  98. {
  99. private:
  100. bool nest;
  101. public:
  102. Nest();
  103. ~Nest();
  104. void open(Verbosity level, const FormatOrString & fs);
  105. void close();
  106. };
  107. void printMsg_(Verbosity level, const FormatOrString & fs);
  108. #define startNest(varName, level, f) \
  109. Nest varName; \
  110. if (level <= verbosity) { \
  111. varName.open(level, (f)); \
  112. }
  113. #define printMsg(level, f) \
  114. do { \
  115. if (level <= nix::verbosity) { \
  116. nix::printMsg_(level, (f)); \
  117. } \
  118. } while (0)
  119. #define debug(f) printMsg(lvlDebug, f)
  120. void warnOnce(bool & haveWarned, const FormatOrString & fs);
  121. void writeToStderr(const string & s);
  122. extern void (*_writeToStderr) (const unsigned char * buf, size_t count);
  123. /* Wrappers arount read()/write() that read/write exactly the
  124. requested number of bytes. */
  125. void readFull(int fd, unsigned char * buf, size_t count);
  126. void writeFull(int fd, const unsigned char * buf, size_t count);
  127. void writeFull(int fd, const string & s);
  128. MakeError(EndOfFile, Error)
  129. /* Read a file descriptor until EOF occurs. */
  130. string drainFD(int fd);
  131. /* Automatic cleanup of resources. */
  132. template <class T>
  133. struct AutoDeleteArray
  134. {
  135. T * p;
  136. AutoDeleteArray(T * p) : p(p) { }
  137. ~AutoDeleteArray()
  138. {
  139. delete [] p;
  140. }
  141. };
  142. class AutoDelete
  143. {
  144. Path path;
  145. bool del;
  146. bool recursive;
  147. public:
  148. AutoDelete(const Path & p, bool recursive = true);
  149. ~AutoDelete();
  150. void cancel();
  151. };
  152. class AutoCloseFD
  153. {
  154. int fd;
  155. public:
  156. AutoCloseFD();
  157. AutoCloseFD(int fd);
  158. AutoCloseFD(const AutoCloseFD & fd);
  159. ~AutoCloseFD();
  160. void operator =(int fd);
  161. operator int() const;
  162. void close();
  163. bool isOpen();
  164. int borrow();
  165. };
  166. class Pipe
  167. {
  168. public:
  169. AutoCloseFD readSide, writeSide;
  170. void create();
  171. };
  172. class AutoCloseDir
  173. {
  174. DIR * dir;
  175. public:
  176. AutoCloseDir();
  177. AutoCloseDir(DIR * dir);
  178. ~AutoCloseDir();
  179. void operator =(DIR * dir);
  180. operator DIR *();
  181. void close();
  182. };
  183. class Pid
  184. {
  185. pid_t pid;
  186. bool separatePG;
  187. int killSignal;
  188. public:
  189. Pid();
  190. Pid(pid_t pid);
  191. ~Pid();
  192. void operator =(pid_t pid);
  193. operator pid_t();
  194. void kill(bool quiet = false);
  195. int wait(bool block);
  196. void setSeparatePG(bool separatePG);
  197. void setKillSignal(int signal);
  198. };
  199. /* An "agent" is a helper program that runs in the background and that we talk
  200. to over pipes, such as the "guix offload" program. */
  201. struct Agent
  202. {
  203. /* Pipes for talking to the agent. */
  204. Pipe toAgent;
  205. /* Pipe for the agent's standard output/error. */
  206. Pipe fromAgent;
  207. /* Pipe for build standard output/error--e.g., for build processes started
  208. by "guix offload". */
  209. Pipe builderOut;
  210. /* The process ID of the agent. */
  211. Pid pid;
  212. /* The command and arguments passed to the agent. */
  213. Agent(const string &command, const Strings &args);
  214. ~Agent();
  215. };
  216. /* Kill all processes running under the specified uid by sending them
  217. a SIGKILL. */
  218. void killUser(uid_t uid);
  219. /* Fork a process that runs the given function, and return the child
  220. pid to the caller. */
  221. pid_t startProcess(std::function<void()> fun, bool dieWithParent = true,
  222. const string & errorPrefix = "error: ", bool runExitHandlers = false);
  223. /* Run a program and return its stdout in a string (i.e., like the
  224. shell backtick operator). */
  225. string runProgram(Path program, bool searchPath = false,
  226. const Strings & args = Strings());
  227. MakeError(ExecError, Error)
  228. /* Convert a list of strings to a null-terminated vector of char
  229. *'s. The result must not be accessed beyond the lifetime of the
  230. list of strings. */
  231. std::vector<char *> stringsToCharPtrs(const Strings & ss);
  232. /* Close all file descriptors except stdin, stdout, stderr, and those
  233. listed in the given set. Good practice in child processes. */
  234. void closeMostFDs(const set<int> & exceptions);
  235. /* Set the close-on-exec flag for the given file descriptor. */
  236. void closeOnExec(int fd);
  237. /* Common initialisation performed in child processes. */
  238. void commonChildInit(Pipe & logPipe);
  239. /* User interruption. */
  240. extern volatile sig_atomic_t _isInterrupted;
  241. void _interrupted();
  242. void inline checkInterrupt()
  243. {
  244. if (_isInterrupted) _interrupted();
  245. }
  246. MakeError(Interrupted, BaseError)
  247. /* String tokenizer. */
  248. template<class C> C tokenizeString(const string & s, const string & separators = " \t\n\r");
  249. /* Concatenate the given strings with a separator between the
  250. elements. */
  251. string concatStringsSep(const string & sep, const Strings & ss);
  252. string concatStringsSep(const string & sep, const StringSet & ss);
  253. /* Remove trailing whitespace from a string. */
  254. string chomp(const string & s);
  255. /* Convert the exit status of a child as returned by wait() into an
  256. error string. */
  257. string statusToString(int status);
  258. bool statusOk(int status);
  259. /* Parse a string into an integer. */
  260. template<class N> bool string2Int(const string & s, N & n)
  261. {
  262. std::istringstream str(s);
  263. str >> n;
  264. return str && str.get() == EOF;
  265. }
  266. /* Return true iff `s' ends in `suffix'. */
  267. bool hasSuffix(const string & s, const string & suffix);
  268. /* Read string `s' from stream `str'. */
  269. void expect(std::istream & str, const string & s);
  270. MakeError(FormatError, Error)
  271. /* Read a C-style string from stream `str'. */
  272. string parseString(std::istream & str);
  273. /* Utility function used to parse legacy ATerms. */
  274. bool endOfList(std::istream & str);
  275. /* Exception handling in destructors: print an error message, then
  276. ignore the exception. */
  277. void ignoreException();
  278. }