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