]> git.ozlabs.org Git - ccan/blob - tools/tools.c
1eddf7e934ab9f658cadb9fe4e7a2c34b8312b15
[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         }
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 = 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         ret = grab_fd(ctx, p[0], NULL);
121         /* This shouldn't fail... */
122         if (waitpid(pid, &status, 0) != pid)
123                 err(1, "Failed to wait for child");
124
125         ms = time_to_msec(time_sub(time_now(), start));
126         if (ms > *timeout_ms)
127                 *timeout_ms = 0;
128         else
129                 *timeout_ms -= ms;
130         close(p[0]);
131         if (tools_verbose) {
132                 printf("%s", ret);
133                 printf("Finished: %u ms, %s %u\n", ms,
134                        WIFEXITED(status) ? "exit status" : "killed by signal",
135                        WIFEXITED(status) ? WEXITSTATUS(status)
136                        : WTERMSIG(status));
137         }
138         *ok = (WIFEXITED(status) && WEXITSTATUS(status) == 0);
139         return ret;
140 }
141
142 /* Tallocs *output off ctx; return false if command fails. */
143 bool run_command(const void *ctx, unsigned int *time_ms, char **output,
144                  const char *fmt, ...)
145 {
146         va_list ap;
147         char *cmd;
148         bool ok;
149         unsigned int default_time = default_timeout_ms;
150
151         if (!time_ms)
152                 time_ms = &default_time;
153         else if (*time_ms == 0) {
154                 *output = talloc_strdup(ctx, "\n== TIMED OUT ==\n");
155                 return false;
156         }
157
158         va_start(ap, fmt);
159         cmd = talloc_vasprintf(ctx, fmt, ap);
160         va_end(ap);
161
162         *output = run_with_timeout(ctx, cmd, &ok, time_ms);
163         if (ok)
164                 return true;
165         if (!*output)
166                 err(1, "Problem running child");
167         if (*time_ms == 0)
168                 *output = talloc_asprintf_append(*output,
169                                                  "\n== TIMED OUT ==\n");
170         return false;
171 }
172
173 static int unlink_all(const char *dir)
174 {
175         char cmd[strlen(dir) + sizeof("rm -rf ")];
176         sprintf(cmd, "rm -rf %s", dir);
177         if (tools_verbose)
178                 printf("Running: %s\n", cmd);
179         if (system(cmd) != 0)
180                 warn("Could not remove temporary work in %s", dir);
181         return 0;
182 }
183
184 const char *temp_dir(const void *ctx)
185 {
186         /* For first call, create dir. */
187         while (!tmpdir) {
188                 tmpdir = getenv("TMPDIR");
189                 if (!tmpdir)
190                         tmpdir = "/tmp";
191                 tmpdir = talloc_asprintf(talloc_autofree_context(),
192                                          "%s/ccanlint-%u.%lu",
193                                          tmpdir, getpid(), random());
194                 if (mkdir(tmpdir, 0700) != 0) {
195                         if (errno == EEXIST) {
196                                 talloc_free(tmpdir);
197                                 tmpdir = NULL;
198                                 continue;
199                         }
200                         err(1, "mkdir %s failed", tmpdir);
201                 }
202                 talloc_set_destructor(tmpdir, unlink_all);
203                 if (tools_verbose)
204                         printf("Created temporary directory %s\n", tmpdir);
205         }
206         return tmpdir;
207 }
208
209 int unlink_file_destructor(char *filename)
210 {
211         unlink(filename);
212         return 0;
213 }
214
215 char *temp_file(const void *ctx, const char *extension, const char *srcname)
216 {
217         unsigned baselen;
218         char *f, *suffix = talloc_strdup(ctx, "");
219         struct stat st;
220         unsigned int count = 0;
221
222         srcname = talloc_basename(ctx, srcname);
223         if (strrchr(srcname, '.'))
224                 baselen = strrchr(srcname, '.') - srcname;
225         else
226                 baselen = strlen(srcname);
227
228         do {
229                 f = talloc_asprintf(ctx, "%s/%.*s%s%s",
230                                     temp_dir(ctx),
231                                     baselen, srcname,
232                                     suffix, extension);
233                 talloc_free(suffix);
234                 suffix = talloc_asprintf(ctx, "-%u", ++count);
235         } while (lstat(f, &st) == 0);
236
237         if (tools_verbose)
238                 printf("Creating file %s\n", f);
239
240         talloc_free(suffix);
241         return f;
242 }
243
244 bool move_file(const char *oldname, const char *newname)
245 {
246         char *contents;
247         size_t size;
248         int fd;
249         bool ret;
250
251         if (tools_verbose)
252                 printf("Moving file %s to %s: ", oldname, newname);
253
254         /* Simple case: rename works. */
255         if (rename(oldname, newname) == 0) {
256                 if (tools_verbose)
257                         printf("rename worked\n");
258                 return true;
259         }
260
261         /* Try copy and delete: not atomic! */
262         contents = grab_file(NULL, oldname, &size);
263         if (!contents) {
264                 if (tools_verbose)
265                         printf("read failed: %s\n", strerror(errno));
266                 return false;
267         }
268
269         fd = open(newname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
270         if (fd < 0) {
271                 if (tools_verbose)
272                         printf("output open failed: %s\n", strerror(errno));
273                 ret = false;
274                 goto free;
275         }
276
277         ret = write_all(fd, contents, size);
278         if (close(fd) != 0)
279                 ret = false;
280
281         if (ret) {
282                 if (tools_verbose)
283                         printf("copy worked\n");
284                 unlink(oldname);
285         } else {
286                 if (tools_verbose)
287                         printf("write/close failed\n");
288                 unlink(newname);
289         }
290
291 free:
292         talloc_free(contents);
293         return ret;
294 }