]> git.ozlabs.org Git - ccan/blob - tools/tools.c
ccanlint: clean up reduced feature handling.
[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 <ccan/time/time.h>
7 #include <sys/stat.h>
8 #include <sys/types.h>
9 #include <sys/time.h>
10 #include <sys/wait.h>
11 #include <fcntl.h>
12 #include <string.h>
13 #include <unistd.h>
14 #include <stdarg.h>
15 #include <errno.h>
16 #include <err.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         char *ret;
75         int status, ms;
76         struct timeval 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                 return NULL;
96         }
97
98         if (pid == 0) {
99                 struct itimerval itim;
100
101                 if (dup2(p[1], STDOUT_FILENO) != STDOUT_FILENO
102                     || dup2(p[1], STDERR_FILENO) != STDERR_FILENO
103                     || close(p[0]) != 0
104                     || close(STDIN_FILENO) != 0
105                     || open("/dev/null", O_RDONLY) != STDIN_FILENO)
106                         exit(128);
107
108                 signal(SIGALRM, killme);
109                 itim.it_interval.tv_sec = itim.it_interval.tv_usec = 0;
110                 itim.it_value = time_from_msec(*timeout_ms);
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         ms = time_to_msec(time_sub(time_now(), start));
127         if (ms > *timeout_ms)
128                 *timeout_ms = 0;
129         else
130                 *timeout_ms -= ms;
131         close(p[0]);
132         if (tools_verbose) {
133                 printf("%s", ret);
134                 printf("Finished: %u ms, %s %u\n", ms,
135                        WIFEXITED(status) ? "exit status" : "killed by signal",
136                        WIFEXITED(status) ? WEXITSTATUS(status)
137                        : WTERMSIG(status));
138         }
139         *ok = (WIFEXITED(status) && WEXITSTATUS(status) == 0);
140         return ret;
141 }
142
143 /* Tallocs *output off ctx; return false if command fails. */
144 bool run_command(const void *ctx, unsigned int *time_ms, char **output,
145                  const char *fmt, ...)
146 {
147         va_list ap;
148         char *cmd;
149         bool ok;
150         unsigned int default_time = default_timeout_ms;
151
152         if (!time_ms)
153                 time_ms = &default_time;
154         else if (*time_ms == 0) {
155                 *output = talloc_strdup(ctx, "\n== TIMED OUT ==\n");
156                 return false;
157         }
158
159         va_start(ap, fmt);
160         cmd = talloc_vasprintf(ctx, fmt, ap);
161         va_end(ap);
162
163         *output = run_with_timeout(ctx, cmd, &ok, time_ms);
164         if (ok)
165                 return true;
166         if (!*output)
167                 err(1, "Problem running child");
168         if (*time_ms == 0)
169                 *output = talloc_asprintf_append(*output,
170                                                  "\n== TIMED OUT ==\n");
171         return false;
172 }
173
174 static int unlink_all(const char *dir)
175 {
176         char cmd[strlen(dir) + sizeof("rm -rf ")];
177         sprintf(cmd, "rm -rf %s", dir);
178         if (tools_verbose)
179                 printf("Running: %s\n", cmd);
180         if (system(cmd) != 0)
181                 warn("Could not remove temporary work in %s", dir);
182         return 0;
183 }
184
185 const char *temp_dir(const void *ctx)
186 {
187         /* For first call, create dir. */
188         while (!tmpdir) {
189                 tmpdir = getenv("TMPDIR");
190                 if (!tmpdir)
191                         tmpdir = "/tmp";
192                 tmpdir = talloc_asprintf(talloc_autofree_context(),
193                                          "%s/ccanlint-%u.%lu",
194                                          tmpdir, getpid(), random());
195                 if (mkdir(tmpdir, 0700) != 0) {
196                         if (errno == EEXIST) {
197                                 talloc_free(tmpdir);
198                                 tmpdir = NULL;
199                                 continue;
200                         }
201                         err(1, "mkdir %s failed", tmpdir);
202                 }
203                 talloc_set_destructor(tmpdir, unlink_all);
204                 if (tools_verbose)
205                         printf("Created temporary directory %s\n", tmpdir);
206         }
207         return tmpdir;
208 }
209
210 int unlink_file_destructor(char *filename)
211 {
212         unlink(filename);
213         return 0;
214 }
215
216 char *maybe_temp_file(const void *ctx, const char *extension, bool keep,
217                       const char *srcname)
218 {
219         unsigned baselen;
220         char *f, *suffix = talloc_strdup(ctx, "");
221         struct stat st;
222         unsigned int count = 0;
223
224         srcname = talloc_basename(ctx, srcname);
225         if (strrchr(srcname, '.'))
226                 baselen = strrchr(srcname, '.') - srcname;
227         else
228                 baselen = strlen(srcname);
229
230         do {
231                 f = talloc_asprintf(ctx, "%s/%.*s%s%s",
232                                     temp_dir(ctx),
233                                     baselen, srcname,
234                                     suffix, extension);
235                 talloc_free(suffix);
236                 suffix = talloc_asprintf(ctx, "-%u", ++count);
237         } while (lstat(f, &st) == 0);
238
239         if (tools_verbose)
240                 printf("Creating %sfile %s\n", keep ? "" : "temporary ", f);
241
242         if (!keep)
243                 talloc_set_destructor(f, unlink_file_destructor);
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 = 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 }