-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
424 lines (373 loc) · 7.81 KB
/
main.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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
type rule struct {
deny bool
pathTokens []string
current int
perms string
}
func newRule(rs string) rule {
r := rule{}
i := 0
tokens := strings.Split(rs, " ")
if len(tokens) == 3 {
if tokens[i] == "deny" {
r.deny = true
}
i++
}
r.pathTokens = strings.Split(tokens[i], "/")
if r.pathTokens[0] == "" {
r.pathTokens = r.pathTokens[1:]
}
r.perms = tokens[i+1]
return r
}
func (r *rule) next() (string, bool) {
if r.current == len(r.pathTokens) {
return "", true
}
n := r.pathTokens[r.current]
r.current++
return n, r.current == len(r.pathTokens)
}
type leaf struct {
part string
children map[string]*leaf
}
func newLeaf(p string) *leaf {
return &leaf{
part: p,
children: make(map[string]*leaf),
}
}
func (l *leaf) addToken(p string) *leaf {
nl := l.children[p]
if nl == nil {
nl = newLeaf(p)
l.children[p] = nl
}
return nl
}
func (l *leaf) addRule(r rule) {
p, last := r.next()
if strings.HasPrefix(p, "{") {
pt := strings.Trim(p, "{}")
pts := strings.Split(pt, ",")
for _, t := range pts {
nl := l.addToken(t)
if !last {
cl := r.current
nl.addRule(r)
r.current = cl
}
}
} else {
nl := l.addToken(p)
if !last {
nl.addRule(r)
}
}
}
func (l *leaf) dump(ctx string) {
nctx := fmt.Sprintf("%s/%s", ctx, l.part)
if len(l.children) == 0 {
fmt.Println(nctx)
return
}
for _, c := range l.children {
c.dump(nctx)
}
}
func (l *leaf) format(ctx, perms string) []string {
var lines []string
nctx := fmt.Sprintf("%s/%s", ctx, l.part)
if len(l.children) == 0 {
lines = append(lines, fmt.Sprintf(" %s %s", nctx, perms))
}
for _, c := range l.children {
lines = append(lines, c.format(nctx, perms)...)
}
return lines
}
type aaOptimizer struct {
trees map[string]*leaf
}
func newAaOptimizer() *aaOptimizer {
return &aaOptimizer{
trees: make(map[string]*leaf),
}
}
func (aa *aaOptimizer) addRule(rs string) {
r := newRule(rs)
if r.deny {
// ignore deny for now
return
}
p, _ := r.next()
l := aa.trees[r.perms]
if l == nil {
l = newLeaf(p)
aa.trees[r.perms] = l
}
l.addRule(r)
}
func (aa *aaOptimizer) combineLeafs(dst, src *leaf) {
for _, s := range src.children {
d := dst.children[s.part]
if d != nil {
aa.combineLeafs(d, s)
} else {
dst.children[s.part] = s
}
}
}
// Combine things like:
// /sys/devices/*/xxx r,
// /sys/devices/**/xxx r,
func (aa *aaOptimizer) optimizeTreePass0(l *leaf) {
// /tmp/* => Files directly in /tmp.
// /tmp/*/ => Directories directly in /tmp.
// /tmp/** => Files and directories anywhere underneath /tmp.
// /tmp/**/ => Directories anywhere underneath /tmp.
var swc *leaf
var dwc *leaf
for _, c := range l.children {
if c.part == "*" {
swc = c
} else if c.part == "**" {
dwc = c
}
}
if swc != nil && dwc != nil {
if len(dwc.children) == 0 {
// combine /* and /*/ with /**, /** covers anything
// when they have identical perms and overrules that
delete(l.children, "*")
} else if len(dwc.children) > 0 && len(swc.children) > 0 {
// combine /*/ with /**/
aa.combineLeafs(dwc, swc)
delete(l.children, "*")
}
}
for _, c := range l.children {
aa.optimizeTreePass0(c)
}
}
func (aa *aaOptimizer) optimizePass0() {
for _, l := range aa.trees {
aa.optimizeTreePass0(l)
}
}
func (aa *aaOptimizer) optimizeTreePass1(l *leaf) bool {
if len(l.children) == 0 {
return true
}
// if we do have children, then they must not have it, or they
// must be identical
var parts []string
children := make(map[string]*leaf)
for _, c := range l.children {
if c.part != "" && aa.optimizeTreePass1(c) {
parts = append(parts, c.part)
} else {
children[c.part] = c
}
}
if len(parts) < 2 {
return false
}
// If one the children is a * or **. then ignore all else
for _, pc := range parts {
if pc == "*" || pc == "**" {
parts = []string{pc}
break
}
}
// ok none of our children have children, consolidate
// them
var p string
if len(parts) == 1 {
p = parts[0]
} else {
p = fmt.Sprintf("{%s}", strings.Join(parts, ","))
}
l.children = children
l.children[p] = newLeaf(p)
return false
}
// Combine things like:
// /sys/devices/**/uevent r,
// /sys/devices/**/read_ahead_kb r,
func (aa *aaOptimizer) optimizePass1() {
for _, l := range aa.trees {
aa.optimizeTreePass1(l)
}
}
func (aa *aaOptimizer) identicalChildren(l, r *leaf) bool {
if len(l.children) != len(r.children) {
return false
}
for _, cl := range l.children {
rl := r.children[cl.part]
if rl == nil {
return false
}
if !aa.identicalChildren(cl, rl) {
return false
}
}
return true
}
func (aa *aaOptimizer) containsUnbracketedComma(p string) bool {
var sawBracket bool
for _, r := range p {
if r == '{' {
sawBracket = true
} else if r == ',' && !sawBracket {
return true
}
}
return false
}
func (aa *aaOptimizer) optimizeTreePass2(l *leaf) {
if len(l.children) > 1 {
for _, cl := range l.children {
for _, rl := range l.children {
if rl == cl {
continue
}
if aa.identicalChildren(cl, rl) {
p := fmt.Sprintf("%s,%s", strings.Trim(cl.part, "{}"), strings.Trim(rl.part, "{}"))
delete(l.children, cl.part)
delete(l.children, rl.part)
cl.part = p
l.children[p] = cl
}
}
}
}
// fixup namings
for _, c := range l.children {
if aa.containsUnbracketedComma(c.part) {
if !strings.HasPrefix(c.part, "{") {
p := fmt.Sprintf("{%s}", c.part)
delete(l.children, c.part)
c.part = p
l.children[p] = c
}
}
}
for _, c := range l.children {
aa.optimizeTreePass2(c)
}
}
func (aa *aaOptimizer) optimizePass2() {
for _, l := range aa.trees {
aa.optimizeTreePass2(l)
}
}
func (aa *aaOptimizer) dump() {
for _, t := range aa.trees {
t.dump("")
}
}
func (aa *aaOptimizer) format() []string {
var lines []string
for p, t := range aa.trees {
lines = append(lines, t.format("", p)...)
}
return lines
}
func readLines(path string) ([]string, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
return lines, scanner.Err()
}
func writeLines(lines []string, path string) error {
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close()
w := bufio.NewWriter(file)
for _, line := range lines {
fmt.Fprintln(w, line)
}
return w.Flush()
}
func insert(a []string, index int, s string) []string {
if len(a) == index {
return append(a, s)
}
a = append(a[:index+1], a[index:]...)
a[index] = s
return a
}
func main() {
if len(os.Args) < 3 {
fmt.Println("usage: aaoptimizer [input] [output]")
os.Exit(-1)
}
input := os.Args[1]
output := os.Args[2]
lines, err := readLines(input)
if err != nil {
fmt.Printf("aaoptimizer: %v", err)
return
}
aa := newAaOptimizer()
pathsToOptimize := []string{"/sys/devices"}
// simple stupid replacement from the last encounter
insertAt := -1
var filteredLines []string
for i, l := range lines {
tl := strings.Trim(l, " ")
if !strings.HasPrefix(tl, pathsToOptimize[0]) {
filteredLines = append(filteredLines, l)
continue
}
if insertAt == -1 {
insertAt = i
}
aa.addRule(tl)
}
//fmt.Printf("original:\n")
//aa.dump()
fmt.Println("executing pass 0")
aa.optimizePass0()
//aa.dump()
// must be last passes
fmt.Println("executing pass 1")
aa.optimizePass1()
//aa.dump()
fmt.Println("executing pass 2")
aa.optimizePass2()
//aa.dump()
// insert a small header
insert(filteredLines, insertAt, "\n # generated by aa-optimizer app")
insertAt++
// insert into filteredLines
rls := aa.format()
for _, r := range rls {
filteredLines = insert(filteredLines, insertAt, r)
insertAt++
}
err = writeLines(filteredLines, output)
if err != nil {
fmt.Printf("aaoptimizer: %v", err)
}
}