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