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