-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathchmod.c
131 lines (121 loc) · 2.27 KB
/
chmod.c
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
/* See LICENSE file for copyright and license details. */
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include "util.h"
static void chmodr(const char *);
static void parsemode(const char *);
static bool rflag = false;
static char oper = '=';
static mode_t mode = 0;
int
main(int argc, char *argv[])
{
char c;
while((c = getopt(argc, argv, "Rrwxs")) != -1)
switch(c) {
case 'R':
rflag = true;
break;
case 'r':
case 'w':
case 'x':
optind--;
goto x;
default:
exit(EXIT_FAILURE);
}
x: if(optind == argc)
eprintf("usage: %s [-r] mode [file...]\n", argv[0]);
parsemode(argv[optind++]);
for(; optind < argc; optind++)
chmodr(argv[optind]);
return EXIT_SUCCESS;
}
void
chmodr(const char *path)
{
struct stat st;
if(stat(path, &st) == -1)
eprintf("stat %s:", path);
switch(oper) {
case '+':
st.st_mode |= mode;
break;
case '-':
st.st_mode &= ~mode;
break;
case '=':
st.st_mode = mode;
break;
}
if(chmod(path, st.st_mode) == -1)
eprintf("chmod %s:", path);
if(rflag)
recurse(path, chmodr);
}
void
parsemode(const char *str)
{
char *end;
const char *p;
int octal;
mode_t mask = 0;
octal = strtol(str, &end, 8);
if(*end == '\0') {
if(octal & 04000) mode |= S_ISUID;
if(octal & 02000) mode |= S_ISGID;
if(octal & 00400) mode |= S_IRUSR;
if(octal & 00200) mode |= S_IWUSR;
if(octal & 00100) mode |= S_IXUSR;
if(octal & 00040) mode |= S_IRGRP;
if(octal & 00020) mode |= S_IWGRP;
if(octal & 00010) mode |= S_IXGRP;
if(octal & 00004) mode |= S_IROTH;
if(octal & 00002) mode |= S_IWOTH;
if(octal & 00001) mode |= S_IXOTH;
return;
}
for(p = str; *p; p++)
switch(*p) {
/* masks */
case 'u':
mask |= S_IRWXU;
break;
case 'g':
mask |= S_IRWXG;
break;
case 'o':
mask |= S_IRWXO;
break;
case 'a':
mask |= S_IRWXU|S_IRWXG|S_IRWXO;
break;
/* opers */
case '+':
case '-':
case '=':
oper = *p;
break;
/* modes */
case 'r':
mode |= S_IRUSR|S_IRGRP|S_IROTH;
break;
case 'w':
mode |= S_IWUSR|S_IWGRP|S_IWOTH;
break;
case 'x':
mode |= S_IXUSR|S_IXGRP|S_IXOTH;
break;
case 's':
mode |= S_ISUID|S_ISGID;
break;
/* error */
default:
eprintf("%s: invalid mode\n", str);
}
if(mask)
mode &= mask;
}