tools.c 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. #include <ccan/talloc/talloc.h>
  2. #include <ccan/grab_file/grab_file.h>
  3. #include <ccan/noerr/noerr.h>
  4. #include <ccan/read_write_all/read_write_all.h>
  5. #include <ccan/noerr/noerr.h>
  6. #include <sys/stat.h>
  7. #include <sys/types.h>
  8. #include <sys/time.h>
  9. #include <sys/wait.h>
  10. #include <fcntl.h>
  11. #include <string.h>
  12. #include <unistd.h>
  13. #include <stdarg.h>
  14. #include <errno.h>
  15. #include <err.h>
  16. #include <unistd.h>
  17. #include <assert.h>
  18. #include "tools.h"
  19. static const char *tmpdir = NULL;
  20. bool tools_verbose = false;
  21. /* Ten minutes. */
  22. const unsigned int default_timeout_ms = 10 * 60 * 1000;
  23. char *talloc_basename(const void *ctx, const char *dir)
  24. {
  25. char *p = strrchr(dir, '/');
  26. if (!p)
  27. return talloc_strdup(ctx, dir);
  28. return talloc_strdup(ctx, p+1);
  29. }
  30. char *talloc_dirname(const void *ctx, const char *dir)
  31. {
  32. char *p = strrchr(dir, '/');
  33. if (!p)
  34. return talloc_strdup(ctx, ".");
  35. return talloc_strndup(ctx, dir, p - dir);
  36. }
  37. char *talloc_getcwd(const void *ctx)
  38. {
  39. unsigned int len;
  40. char *cwd;
  41. /* *This* is why people hate C. */
  42. len = 32;
  43. cwd = talloc_array(ctx, char, len);
  44. while (!getcwd(cwd, len)) {
  45. if (errno != ERANGE) {
  46. talloc_free(cwd);
  47. return NULL;
  48. }
  49. cwd = talloc_realloc(ctx, cwd, char, len *= 2);
  50. }
  51. return cwd;
  52. }
  53. static void killme(int sig)
  54. {
  55. kill(-getpid(), SIGKILL);
  56. }
  57. char *run_with_timeout(const void *ctx, const char *cmd,
  58. bool *ok, unsigned *timeout_ms)
  59. {
  60. pid_t pid;
  61. int p[2];
  62. char *ret;
  63. int status, ms;
  64. struct timeval start, end;
  65. *ok = false;
  66. if (pipe(p) != 0)
  67. return talloc_asprintf(ctx, "Failed to create pipe: %s",
  68. strerror(errno));
  69. if (tools_verbose)
  70. printf("Running: %s\n", cmd);
  71. /* Always flush buffers before fork! */
  72. fflush(stdout);
  73. gettimeofday(&start, NULL);
  74. pid = fork();
  75. if (pid == -1) {
  76. close_noerr(p[0]);
  77. close_noerr(p[1]);
  78. return talloc_asprintf(ctx, "Failed to fork: %s",
  79. strerror(errno));
  80. return NULL;
  81. }
  82. if (pid == 0) {
  83. struct itimerval itim;
  84. if (dup2(p[1], STDOUT_FILENO) != STDOUT_FILENO
  85. || dup2(p[1], STDERR_FILENO) != STDERR_FILENO
  86. || close(p[0]) != 0
  87. || close(STDIN_FILENO) != 0
  88. || open("/dev/null", O_RDONLY) != STDIN_FILENO)
  89. exit(128);
  90. signal(SIGALRM, killme);
  91. itim.it_interval.tv_sec = itim.it_interval.tv_usec = 0;
  92. itim.it_value.tv_sec = *timeout_ms / 1000;
  93. itim.it_value.tv_usec = (*timeout_ms % 1000) * 1000;
  94. setitimer(ITIMER_REAL, &itim, NULL);
  95. status = system(cmd);
  96. if (WIFEXITED(status))
  97. exit(WEXITSTATUS(status));
  98. /* Here's a hint... */
  99. exit(128 + WTERMSIG(status));
  100. }
  101. close(p[1]);
  102. ret = grab_fd(ctx, p[0], NULL);
  103. /* This shouldn't fail... */
  104. if (waitpid(pid, &status, 0) != pid)
  105. err(1, "Failed to wait for child");
  106. gettimeofday(&end, NULL);
  107. if (end.tv_usec < start.tv_usec) {
  108. end.tv_usec += 1000000;
  109. end.tv_sec--;
  110. }
  111. ms = (end.tv_sec - start.tv_sec) * 1000
  112. + (end.tv_usec - start.tv_usec) / 1000;
  113. if (ms > *timeout_ms)
  114. *timeout_ms = 0;
  115. else
  116. *timeout_ms -= ms;
  117. close(p[0]);
  118. if (tools_verbose) {
  119. printf("%s", ret);
  120. printf("Finished: %u ms, %s %u\n", ms,
  121. WIFEXITED(status) ? "exit status" : "killed by signal",
  122. WIFEXITED(status) ? WEXITSTATUS(status)
  123. : WTERMSIG(status));
  124. }
  125. *ok = (WIFEXITED(status) && WEXITSTATUS(status) == 0);
  126. return ret;
  127. }
  128. /* Tallocs *output off ctx; return false if command fails. */
  129. bool run_command(const void *ctx, unsigned int *time_ms, char **output,
  130. const char *fmt, ...)
  131. {
  132. va_list ap;
  133. char *cmd;
  134. bool ok;
  135. unsigned int default_time = default_timeout_ms;
  136. if (!time_ms)
  137. time_ms = &default_time;
  138. else if (*time_ms == 0) {
  139. *output = talloc_strdup(ctx, "\n== TIMED OUT ==\n");
  140. return false;
  141. }
  142. va_start(ap, fmt);
  143. cmd = talloc_vasprintf(ctx, fmt, ap);
  144. va_end(ap);
  145. *output = run_with_timeout(ctx, cmd, &ok, time_ms);
  146. if (ok)
  147. return true;
  148. if (!*output)
  149. err(1, "Problem running child");
  150. if (*time_ms == 0)
  151. *output = talloc_asprintf_append(*output,
  152. "\n== TIMED OUT ==\n");
  153. return false;
  154. }
  155. static int unlink_all(const char *dir)
  156. {
  157. char cmd[strlen(dir) + sizeof("rm -rf ")];
  158. sprintf(cmd, "rm -rf %s", dir);
  159. if (tools_verbose)
  160. printf("Running: %s\n", cmd);
  161. if (system(cmd) != 0)
  162. warn("Could not remove temporary work in %s", dir);
  163. return 0;
  164. }
  165. const char *temp_dir(const void *ctx)
  166. {
  167. /* For first call, create dir. */
  168. while (!tmpdir) {
  169. tmpdir = getenv("TMPDIR");
  170. if (!tmpdir)
  171. tmpdir = "/tmp";
  172. tmpdir = talloc_asprintf(talloc_autofree_context(),
  173. "%s/ccanlint-%u.%lu",
  174. tmpdir, getpid(), random());
  175. if (mkdir(tmpdir, 0700) != 0) {
  176. if (errno == EEXIST) {
  177. talloc_free(tmpdir);
  178. tmpdir = NULL;
  179. continue;
  180. }
  181. err(1, "mkdir %s failed", tmpdir);
  182. }
  183. talloc_set_destructor(tmpdir, unlink_all);
  184. if (tools_verbose)
  185. printf("Created temporary directory %s\n", tmpdir);
  186. }
  187. return tmpdir;
  188. }
  189. int unlink_file_destructor(char *filename)
  190. {
  191. unlink(filename);
  192. return 0;
  193. }
  194. char *maybe_temp_file(const void *ctx, const char *extension, bool keep,
  195. const char *srcname)
  196. {
  197. unsigned baselen;
  198. char *f, *suffix = talloc_strdup(ctx, "");
  199. struct stat st;
  200. unsigned int count = 0;
  201. srcname = talloc_basename(ctx, srcname);
  202. if (strrchr(srcname, '.'))
  203. baselen = strrchr(srcname, '.') - srcname;
  204. else
  205. baselen = strlen(srcname);
  206. do {
  207. f = talloc_asprintf(ctx, "%s/%.*s%s%s",
  208. temp_dir(ctx),
  209. baselen, srcname,
  210. suffix, extension);
  211. talloc_free(suffix);
  212. suffix = talloc_asprintf(ctx, "-%u", ++count);
  213. } while (lstat(f, &st) == 0);
  214. if (tools_verbose)
  215. printf("Creating %sfile %s\n", keep ? "" : "temporary ", f);
  216. if (!keep)
  217. talloc_set_destructor(f, unlink_file_destructor);
  218. talloc_free(suffix);
  219. return f;
  220. }
  221. bool move_file(const char *oldname, const char *newname)
  222. {
  223. char *contents;
  224. size_t size;
  225. int fd;
  226. bool ret;
  227. if (tools_verbose)
  228. printf("Moving file %s to %s: ", oldname, newname);
  229. /* Simple case: rename works. */
  230. if (rename(oldname, newname) == 0) {
  231. if (tools_verbose)
  232. printf("rename worked\n");
  233. return true;
  234. }
  235. /* Try copy and delete: not atomic! */
  236. contents = grab_file(NULL, oldname, &size);
  237. if (!contents) {
  238. if (tools_verbose)
  239. printf("read failed: %s\n", strerror(errno));
  240. return false;
  241. }
  242. fd = open(newname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
  243. if (fd < 0) {
  244. if (tools_verbose)
  245. printf("output open failed: %s\n", strerror(errno));
  246. ret = false;
  247. goto free;
  248. }
  249. ret = write_all(fd, contents, size);
  250. if (close(fd) != 0)
  251. ret = false;
  252. if (ret) {
  253. if (tools_verbose)
  254. printf("copy worked\n");
  255. unlink(oldname);
  256. } else {
  257. if (tools_verbose)
  258. printf("write/close failed\n");
  259. unlink(newname);
  260. }
  261. free:
  262. talloc_free(contents);
  263. return ret;
  264. }