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
95
96
97
98
99
100
101
102
103
104
105
|
#include "system.h"
#include <stdlib.h>
#include <rpm/rpmstring.h>
#include <rpm/rpmlog.h>
#include "lib/rpmchroot.h"
#include "debug.h"
struct rootState_s {
char *rootDir;
int chrootDone;
int cwd;
};
/* Process global chroot state */
static struct rootState_s rootState = {
.rootDir = NULL,
.chrootDone = 0,
.cwd = -1,
};
int rpmChrootSet(const char *rootDir)
{
int rc = 0;
/* Setting same rootDir again is a no-op and not an error */
if (rootDir && rootState.rootDir && rstreq(rootDir, rootState.rootDir))
return 0;
/* Resetting only permitted in neutral state */
if (rootState.chrootDone != 0)
return -1;
rootState.rootDir = _free(rootState.rootDir);
if (rootState.cwd >= 0) {
close(rootState.cwd);
rootState.cwd = -1;
}
if (rootDir != NULL) {
rootState.rootDir = rstrdup(rootDir);
rootState.cwd = open(".", O_RDONLY);
if (rootState.cwd < 0) {
rpmlog(RPMLOG_ERR, _("Unable to open current directory: %m\n"));
rc = -1;
}
}
return rc;
}
int rpmChrootIn(void)
{
int rc = 0;
if (rootState.rootDir == NULL || rstreq(rootState.rootDir, "/"))
return 0;
if (rootState.cwd < 0) {
rpmlog(RPMLOG_ERR, _("%s: chroot directory not set\n"), __func__);
return -1;
}
/* "refcounted" entry to chroot */
if (rootState.chrootDone > 0) {
rootState.chrootDone++;
} else if (rootState.chrootDone == 0) {
if (chdir("/") == 0 && chroot(rootState.rootDir) == 0) {
rootState.chrootDone = 1;
} else {
rpmlog(RPMLOG_ERR, _("Unable to change root directory: %m\n"));
rc = -1;
}
}
return rc;
}
int rpmChrootOut(void)
{
int rc = 0;
if (rootState.rootDir == NULL || rstreq(rootState.rootDir, "/"))
return 0;
if (rootState.cwd < 0) {
rpmlog(RPMLOG_ERR, _("%s: chroot directory not set\n"), __func__);
return -1;
}
/* "refcounted" return from chroot */
if (rootState.chrootDone > 1) {
rootState.chrootDone--;
} else if (rootState.chrootDone == 1) {
if (chroot(".") == 0 && fchdir(rootState.cwd) == 0) {
rootState.chrootDone = 0;
} else {
rpmlog(RPMLOG_ERR, _("Unable to restore root directory: %m\n"));
rc = -1;
}
}
return rc;
}
int rpmChrootDone(void)
{
return (rootState.chrootDone > 0);
}
|