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