1 /*
2 * Copyright (c) 2017 Colin Watson <cjwatson@debian.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
16
17 /* Roughly equivalent to "mktemp -d -t TEMPLATE", but portable. */
18
19 #include "includes.h"
20
21 #include <limits.h>
22 #include <stdarg.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <unistd.h>
26
27 #include "log.h"
28
29 static void
usage(void)30 usage(void)
31 {
32 fprintf(stderr, "mkdtemp template\n");
33 exit(1);
34 }
35
36 int
main(int argc,char ** argv)37 main(int argc, char **argv)
38 {
39 const char *base;
40 const char *tmpdir;
41 char template[PATH_MAX];
42 int r;
43 char *dir;
44
45 if (argc != 2)
46 usage();
47 base = argv[1];
48
49 if ((tmpdir = getenv("TMPDIR")) == NULL)
50 tmpdir = "/tmp";
51 r = snprintf(template, sizeof(template), "%s/%s", tmpdir, base);
52 if (r < 0 || (size_t)r >= sizeof(template))
53 fatal("template string too long");
54 dir = mkdtemp(template);
55 if (dir == NULL) {
56 perror("mkdtemp");
57 exit(1);
58 }
59 puts(dir);
60 return 0;
61 }
62