1 /* tempfile.c: handle temporary directory creation (formerly also temporary
2 * files but this is no longer used).
3 *
4 * Copyright (C) 2001, 2003, 2007, 2009, 2011 Colin Watson.
5 *
6 * This file is part of man-db.
7 *
8 * man-db is free software; you can redistribute it and/or modify it
9 * under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * man-db is distributed in the hope that it will be useful, but
14 * WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with man-db; if not, write to the Free Software Foundation,
20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23 #ifdef HAVE_CONFIG_H
24 # include "config.h"
25 #endif /* HAVE_CONFIG_H */
26
27 #include <assert.h>
28 #include <stdbool.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <unistd.h>
32
33 #include "attribute.h"
34 #include "xvasprintf.h"
35
36 #include "manconfig.h"
37
38 #include "tempfile.h"
39
40 static bool ATTRIBUTE_PURE running_setid (void)
41 {
42 #ifdef HAVE_GETUID
43 return getuid () != geteuid () || getgid () != getegid ();
44 #else /* !HAVE_GETUID */
45 return false;
46 #endif /* HAVE_GETUID */
47 }
48
49 static const char *path_search (void)
50 {
51 const char *dir = NULL;
52
53 if (running_setid ()) {
54 dir = getenv ("TMPDIR");
55 if (!dir || !CAN_ACCESS (dir, W_OK))
56 dir = NULL;
57 if (!dir) {
58 dir = getenv ("TMP");
59 if (!dir || !CAN_ACCESS (dir, W_OK))
60 dir = NULL;
61 }
62 }
63 #ifdef P_tmpdir
64 if (!dir) {
65 dir = P_tmpdir;
66 if (!dir || !CAN_ACCESS (dir, W_OK))
67 dir = NULL;
68 }
69 #endif
70 if (!dir) {
71 dir = "/tmp";
72 if (!CAN_ACCESS (dir, W_OK))
73 dir = NULL;
74 }
75
76 return dir;
77 }
78
79 /* Get a sane temporary directory, looking in $TMPDIR, P_tmpdir, and finally
80 * /tmp.
81 */
82 char *create_tempdir (const char *template)
83 {
84 const char *dir = path_search ();
85 char *created_dirname;
86
87 if (!dir)
88 return NULL;
89 created_dirname = xasprintf ("%s/%sXXXXXX", dir, template);
90 assert (created_dirname);
91 if (!mkdtemp (created_dirname))
92 return NULL;
93 return created_dirname;
94 }