util.hh 9.4 KB

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