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