]> git.ozlabs.org Git - ccan/blob - tools/tools.c
ccanlint: remove redundant num_lines in struct ccan_file.
[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 <sys/stat.h>
10 #include <sys/types.h>
11 #include <sys/time.h>
12 #include <sys/wait.h>
13 #include <fcntl.h>
14 #include <string.h>
15 #include <unistd.h>
16 #include <stdarg.h>
17 #include <errno.h>
18 #include <unistd.h>
19 #include <assert.h>
20 #include <signal.h>
21 #include "tools.h"
22
23 static const char *tmpdir = NULL;
24 bool tools_verbose = false;
25
26 /* Ten minutes. */
27 const unsigned int default_timeout_ms = 10 * 60 * 1000;
28
29 static void killme(int sig)
30 {
31         kill(-getpid(), SIGKILL);
32 }
33
34 char *run_with_timeout(const void *ctx, const char *cmd,
35                        bool *ok, unsigned *timeout_ms)
36 {
37         pid_t pid;
38         int p[2];
39         struct rbuf in;
40         int status, ms;
41         struct timespec start;
42
43         *ok = false;
44         if (pipe(p) != 0)
45                 return tal_fmt(ctx, "Failed to create pipe: %s",
46                                strerror(errno));
47
48         if (tools_verbose)
49                 printf("Running: %s\n", cmd);
50
51         /* Always flush buffers before fork! */
52         fflush(stdout);
53         start = time_now();
54         pid = fork();
55         if (pid == -1) {
56                 close_noerr(p[0]);
57                 close_noerr(p[1]);
58                 return tal_fmt(ctx, "Failed to fork: %s", strerror(errno));
59         }
60
61         if (pid == 0) {
62                 struct itimerval itim;
63
64                 if (dup2(p[1], STDOUT_FILENO) != STDOUT_FILENO
65                     || dup2(p[1], STDERR_FILENO) != STDERR_FILENO
66                     || close(p[0]) != 0
67                     || close(STDIN_FILENO) != 0
68                     || open("/dev/null", O_RDONLY) != STDIN_FILENO)
69                         exit(128);
70
71                 signal(SIGALRM, killme);
72                 itim.it_interval.tv_sec = itim.it_interval.tv_usec = 0;
73                 itim.it_value = timespec_to_timeval(time_from_msec(*timeout_ms));
74                 setitimer(ITIMER_REAL, &itim, NULL);
75
76                 status = system(cmd);
77                 if (WIFEXITED(status))
78                         exit(WEXITSTATUS(status));
79                 /* Here's a hint... */
80                 exit(128 + WTERMSIG(status));
81         }
82
83         close(p[1]);
84         rbuf_init(&in, p[0], tal_arr(ctx, char, 4096), 4096);
85         if (!rbuf_read_str(&in, 0, do_tal_realloc) && errno)
86                 in.buf = tal_free(in.buf);
87
88         /* This shouldn't fail... */
89         if (waitpid(pid, &status, 0) != pid)
90                 err(1, "Failed to wait for child");
91
92         ms = time_to_msec(time_sub(time_now(), start));
93         if (ms > *timeout_ms)
94                 *timeout_ms = 0;
95         else
96                 *timeout_ms -= ms;
97         close(p[0]);
98         if (tools_verbose) {
99                 printf("%s", in.buf);
100                 printf("Finished: %u ms, %s %u\n", ms,
101                        WIFEXITED(status) ? "exit status" : "killed by signal",
102                        WIFEXITED(status) ? WEXITSTATUS(status)
103                        : WTERMSIG(status));
104         }
105         *ok = (WIFEXITED(status) && WEXITSTATUS(status) == 0);
106         return in.buf;
107 }
108
109 /* Tals *output off ctx; return false if command fails. */
110 bool run_command(const void *ctx, unsigned int *time_ms, char **output,
111                  const char *fmt, ...)
112 {
113         va_list ap;
114         char *cmd;
115         bool ok;
116         unsigned int default_time = default_timeout_ms;
117
118         if (!time_ms)
119                 time_ms = &default_time;
120         else if (*time_ms == 0) {
121                 *output = tal_strdup(ctx, "\n== TIMED OUT ==\n");
122                 return false;
123         }
124
125         va_start(ap, fmt);
126         cmd = tal_vfmt(ctx, fmt, ap);
127         va_end(ap);
128
129         *output = run_with_timeout(ctx, cmd, &ok, time_ms);
130         if (ok)
131                 return true;
132         if (!*output)
133                 err(1, "Problem running child");
134         if (*time_ms == 0)
135                 *output = tal_strcat(ctx, take(*output), "\n== TIMED OUT ==\n");
136         return false;
137 }
138
139 static void unlink_all(const char *dir)
140 {
141         char cmd[strlen(dir) + sizeof("rm -rf ")];
142         sprintf(cmd, "rm -rf %s", dir);
143         if (tools_verbose)
144                 printf("Running: %s\n", cmd);
145         if (system(cmd) != 0)
146                 warn("Could not remove temporary work in %s", dir);
147 }
148
149 static pid_t *afree;
150 static void free_autofree(void)
151 {
152         if (*afree == getpid())
153                 tal_free(afree);
154 }
155
156 tal_t *autofree(void)
157 {
158         if (!afree) {
159                 afree = tal(NULL, pid_t);
160                 *afree = getpid();
161                 atexit(free_autofree);
162         }
163         return afree;
164 }
165
166 const char *temp_dir(void)
167 {
168         /* For first call, create dir. */
169         while (!tmpdir) {
170                 tmpdir = getenv("TMPDIR");
171                 if (!tmpdir)
172                         tmpdir = "/tmp";
173                 tmpdir = tal_fmt(autofree(), "%s/ccanlint-%u.%lu",
174                                  tmpdir, getpid(), random());
175                 if (mkdir(tmpdir, 0700) != 0) {
176                         if (errno == EEXIST) {
177                                 tal_free(tmpdir);
178                                 tmpdir = NULL;
179                                 continue;
180                         }
181                         err(1, "mkdir %s failed", tmpdir);
182                 }
183                 tal_add_destructor(tmpdir, unlink_all);
184                 if (tools_verbose)
185                         printf("Created temporary directory %s\n", tmpdir);
186         }
187         return tmpdir;
188 }
189
190 void keep_temp_dir(void)
191 {
192         tal_del_destructor(temp_dir(), unlink_all);
193 }
194
195 char *temp_file(const void *ctx, const char *extension, const char *srcname)
196 {
197         char *f, *base, *suffix;
198         struct stat st;
199         unsigned int count = 0;
200
201         base = path_join(ctx, temp_dir(), take(path_basename(ctx, srcname)));
202         /* Trim extension. */
203         base[path_ext_off(base)] = '\0';
204         suffix = tal_strdup(ctx, extension);
205
206         do {
207                 f = tal_strcat(ctx, base, suffix);
208                 suffix = tal_fmt(base, "-%u%s", ++count, extension);
209         } while (lstat(f, &st) == 0);
210
211         if (tools_verbose)
212                 printf("Creating file %s\n", f);
213
214         tal_free(base);
215         return f;
216 }
217
218 bool move_file(const char *oldname, const char *newname)
219 {
220         char *contents;
221         size_t size;
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 = tal_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
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, size);
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 }
275
276 void *tal_grab_file(const void *ctx, const char *filename, size_t *size)
277 {
278         struct rbuf rbuf;
279         char *buf = tal_arr(ctx, char, 0);
280
281         if (!rbuf_open(&rbuf, filename, buf, 0))
282                 return tal_free(buf);
283
284         if (!rbuf_fill_all(&rbuf, do_tal_realloc) && errno)
285                 rbuf.buf = tal_free(rbuf.buf);
286         else {
287                 rbuf.buf[rbuf.len] = '\0';
288                 if (size)
289                         *size = rbuf.len;
290         }
291         close(rbuf.fd);
292
293         return rbuf.buf;
294 }