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