summaryrefslogtreecommitdiffstats
path: root/lib/tempfile.c
blob: 5d8847c6aa85a358acbfc36448600a9c193222ef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/* tempfile.c: handle temporary directory creation (formerly also temporary
 * files but this is no longer used).
 *
 * Copyright (C) 2001, 2003, 2007, 2009, 2011 Colin Watson.
 *
 * This file is part of man-db.
 *
 * man-db is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * man-db is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with man-db; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#ifdef HAVE_CONFIG_H
#  include "config.h"
#endif /* HAVE_CONFIG_H */

#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "attribute.h"
#include "xvasprintf.h"

#include "manconfig.h"

#include "tempfile.h"

static bool ATTRIBUTE_PURE running_setid (void)
{
#ifdef HAVE_GETUID
	return getuid () != geteuid () || getgid () != getegid ();
#else /* !HAVE_GETUID */
	return false;
#endif /* HAVE_GETUID */
}

static const char *path_search (void)
{
	const char *dir = NULL;

	if (running_setid ()) {
		dir = getenv ("TMPDIR");
		if (!dir || !CAN_ACCESS (dir, W_OK))
			dir = NULL;
		if (!dir) {
			dir = getenv ("TMP");
			if (!dir || !CAN_ACCESS (dir, W_OK))
				dir = NULL;
		}
	}
#ifdef P_tmpdir
	if (!dir) {
		dir = P_tmpdir;
		if (!dir || !CAN_ACCESS (dir, W_OK))
			dir = NULL;
	}
#endif
	if (!dir) {
		dir = "/tmp";
		if (!CAN_ACCESS (dir, W_OK))
			dir = NULL;
	}

	return dir;
}

/* Get a sane temporary directory, looking in $TMPDIR, P_tmpdir, and finally
 * /tmp.
 */
char *create_tempdir (const char *template)
{
	const char *dir = path_search ();
	char *created_dirname;

	if (!dir)
		return NULL;
	created_dirname = xasprintf ("%s/%sXXXXXX", dir, template);
	assert (created_dirname);
	if (!mkdtemp (created_dirname))
		return NULL;
	return created_dirname;
}