]> git.ozlabs.org Git - ccan/blob - tools/tools.c
tools: Fixed unchecked *strrchr in a couple places.
[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         close(p[0]);
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 /* Tallocs *output off ctx; return false if command fails. */
147 bool run_command(const void *ctx, unsigned int *time_ms, char **output,
148                  const char *fmt, ...)
149 {
150         va_list ap;
151         char *cmd;
152         bool ok;
153         unsigned int default_time = default_timeout_ms;
154
155         if (!time_ms)
156                 time_ms = &default_time;
157         else if (*time_ms == 0) {
158                 *output = talloc_strdup(ctx, "\n== TIMED OUT ==\n");
159                 return false;
160         }
161
162         va_start(ap, fmt);
163         cmd = talloc_vasprintf(ctx, fmt, ap);
164         va_end(ap);
165
166         *output = run_with_timeout(ctx, cmd, &ok, time_ms);
167         if (ok)
168                 return true;
169         if (!*output)
170                 err(1, "Problem running child");
171         if (*time_ms == 0)
172                 *output = talloc_asprintf_append(*output,
173                                                  "\n== TIMED OUT ==\n");
174         return false;
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 int unlink_file_destructor(char *filename)
214 {
215         unlink(filename);
216         return 0;
217 }
218
219 char *maybe_temp_file(const void *ctx, const char *extension, bool keep,
220                       const char *srcname)
221 {
222         unsigned baselen;
223         char *f, *suffix = talloc_strdup(ctx, "");
224         struct stat st;
225         unsigned int count = 0;
226
227         srcname = talloc_basename(ctx, srcname);
228         if (strrchr(srcname, '.'))
229                 baselen = strrchr(srcname, '.') - srcname;
230         else
231                 baselen = strlen(srcname);
232
233         do {
234                 f = talloc_asprintf(ctx, "%s/%.*s%s%s",
235                                     temp_dir(ctx),
236                                     baselen, srcname,
237                                     suffix, extension);
238                 talloc_free(suffix);
239                 suffix = talloc_asprintf(ctx, "-%u", ++count);
240         } while (lstat(f, &st) == 0);
241
242         if (tools_verbose)
243                 printf("Creating %sfile %s\n", keep ? "" : "temporary ", f);
244
245         if (!keep)
246                 talloc_set_destructor(f, unlink_file_destructor);
247
248         talloc_free(suffix);
249         return f;
250 }
251
252 bool move_file(const char *oldname, const char *newname)
253 {
254         char *contents;
255         size_t size;
256         int fd;
257         bool ret;
258
259         if (tools_verbose)
260                 printf("Moving file %s to %s: ", oldname, newname);
261
262         /* Simple case: rename works. */
263         if (rename(oldname, newname) == 0) {
264                 if (tools_verbose)
265                         printf("rename worked\n");
266                 return true;
267         }
268
269         /* Try copy and delete: not atomic! */
270         contents = grab_file(NULL, oldname, &size);
271         if (!contents) {
272                 if (tools_verbose)
273                         printf("read failed: %s\n", strerror(errno));
274                 return false;
275         }
276
277         fd = open(newname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
278         if (fd < 0) {
279                 if (tools_verbose)
280                         printf("output open failed: %s\n", strerror(errno));
281                 ret = false;
282                 goto free;
283         }
284
285         ret = write_all(fd, contents, size);
286         if (close(fd) != 0)
287                 ret = false;
288
289         if (ret) {
290                 if (tools_verbose)
291                         printf("copy worked\n");
292                 unlink(oldname);
293         } else {
294                 if (tools_verbose)
295                         printf("write/close failed\n");
296                 unlink(newname);
297         }
298
299 free:
300         talloc_free(contents);
301         return ret;
302 }