]> git.ozlabs.org Git - ccan/blob - tools/tools.c
junkcode: new addition.
[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 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 *temp_file(const void *ctx, const char *extension)
214 {
215         char *f = talloc_asprintf(ctx, "%s/%u%s",
216                                   temp_dir(ctx), count++, extension);
217         if (tools_verbose)
218                 printf("Created temporary file %s\n", f);
219         return f;
220 }
221
222 char *maybe_temp_file(const void *ctx, const char *extension, bool keep,
223                       const char *srcname)
224 {
225         size_t baselen;
226         char *f;
227
228         if (!keep)
229                 return temp_file(ctx, extension);
230
231         baselen = strrchr(srcname, '.') - srcname;
232         f = talloc_asprintf(ctx, "%.*s%s", baselen, srcname, extension);
233         if (tools_verbose)
234                 printf("Creating file %s\n", f);
235         return f;
236 }
237
238 bool move_file(const char *oldname, const char *newname)
239 {
240         char *contents;
241         size_t size;
242         int fd;
243         bool ret;
244
245         if (tools_verbose)
246                 printf("Moving file %s to %s: ", oldname, newname);
247
248         /* Simple case: rename works. */
249         if (rename(oldname, newname) == 0) {
250                 if (tools_verbose)
251                         printf("rename worked\n");
252                 return true;
253         }
254
255         /* Try copy and delete: not atomic! */
256         contents = grab_file(NULL, oldname, &size);
257         if (!contents) {
258                 if (tools_verbose)
259                         printf("read failed: %s\n", strerror(errno));
260                 return false;
261         }
262
263         fd = open(newname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
264         if (fd < 0) {
265                 if (tools_verbose)
266                         printf("output open failed: %s\n", strerror(errno));
267                 ret = false;
268                 goto free;
269         }
270
271         ret = write_all(fd, contents, size);
272         if (close(fd) != 0)
273                 ret = false;
274
275         if (ret) {
276                 if (tools_verbose)
277                         printf("copy worked\n");
278                 unlink(oldname);
279         } else {
280                 if (tools_verbose)
281                         printf("write/close failed\n");
282                 unlink(newname);
283         }
284
285 free:
286         talloc_free(contents);
287         return ret;
288 }