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