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