-
Notifications
You must be signed in to change notification settings - Fork 0
/
permissions.go
145 lines (133 loc) · 2.26 KB
/
permissions.go
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package main
// https://tylercipriani.com/blog/2020/01/12/unix-permissions-for-dummies/
import (
"fmt"
"strconv"
)
// I think you can write this function more elegant by utilizig bit operations
func parseUnixPermissions(octal string) (string, error) {
var special int
if len(octal) > 4 || len(octal) < 3 {
return "", fmt.Errorf("invalid format")
}
if len(octal) == 4 {
special, _ = strconv.Atoi(string(octal[0]))
octal = octal[1:]
}
other, err := strconv.ParseInt(string(octal[2]), 10, 0)
if err != nil {
return "", err
}
group, err := strconv.ParseInt(string(octal[1]), 10, 0)
if err != nil {
return "", err
}
user, err := strconv.ParseInt(string(octal[0]), 10, 0)
if err != nil {
return "", err
}
if user > 7 || user < 0 {
return "", fmt.Errorf("invalid format")
}
if group > 7 || group < 0 {
return "", fmt.Errorf("invalid format")
}
if other > 7 || other < 0 {
return "", fmt.Errorf("invalid format")
}
octalToStr := map[int64]string{
0: "---",
1: "--x",
2: "-w-",
3: "-wx",
4: "r--",
5: "r-x",
6: "rw-",
7: "rwx",
}
u := octalToStr[user]
g := octalToStr[group]
o := octalToStr[other]
// sticky
if special == 1 {
if o[2] == 'x' {
o = o[:2] + "t"
} else {
o = o[:2] + "T"
}
}
// setgid
if special == 2 {
if g[2] == 'x' {
g = g[:2] + "s"
} else {
g = g[:2] + "S"
}
}
// sticky+setgid
if special == 3 {
if g[2] == 'x' {
g = g[:2] + "s"
} else {
g = g[:2] + "S"
}
if o[2] == 'x' {
o = o[:2] + "t"
} else {
o = o[:2] + "T"
}
}
// setuid
if special == 4 {
if u[2] == 'x' {
u = u[:2] + "s"
} else {
u = u[:2] + "S"
}
}
// setuid+sticky
if special == 5 {
if u[2] == 'x' {
u = u[:2] + "s"
} else {
u = u[:2] + "S"
}
if o[2] == 'x' {
o = o[:2] + "t"
} else {
o = o[:2] + "T"
}
}
// setuid+setgid
if special == 6 {
if u[2] == 'x' {
u = u[:2] + "s"
} else {
u = u[:2] + "S"
}
if g[2] == 'x' {
g = g[:2] + "s"
} else {
g = g[:2] + "S"
}
}
// sticky+setuid+setgid
if special == 7 {
if u[2] == 'x' {
u = u[:2] + "s"
} else {
u = u[:2] + "S"
}
if g[2] == 'x' {
g = g[:2] + "s"
} else {
g = g[:2] + "S"
}
if o[2] == 'x' {
o = o[:2] + "t"
} else {
o = o[:2] + "T"
}
}
return u + g + o, nil
}