-
Notifications
You must be signed in to change notification settings - Fork 2
/
plumber.go
379 lines (344 loc) · 8.32 KB
/
plumber.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
package main
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"log"
"os"
"os/exec"
"os/signal"
"regexp"
"strconv"
"strings"
"syscall"
"time"
)
const (
AFFECT = iota
BLANK
COMMENT
ERROR
PATTERN
)
type Msg struct {
Data string
Dst string
Src string
Type string
Wdir string
}
type Pattern struct {
Obj string
Verb string
Arg string
}
type Rule struct {
Patterns []Pattern
Vars Variables
Value bool
}
type Variables map[string]string
const DefaultShell = "/bin/sh"
const DefaultShellOpts = "-c"
var LogFile = flag.String("l", "/mnt/plumb/log", "log file")
var PlumbFile = flag.String("p", "/mnt/plumb/send", "plumb file")
var RulesFile = flag.String("r", "/mnt/plumb/rules", "rules file")
var DebugMode = flag.Bool("d", false, "debug mode")
func main() {
var jsonMsg bytes.Buffer
flag.Parse()
// Select the log file.
if *DebugMode {
*LogFile = "/dev/stdout"
}
logFd, err := os.OpenFile(*LogFile, os.O_WRONLY | os.O_APPEND, os.ModeAppend)
if err != nil {
fmt.Printf("Plumber: Can't start: couldn't open the log file: %s\n", *LogFile)
}
defer logFd.Close()
log.SetOutput(logFd)
log.Println("Plumber started")
// Handle sigs
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGHUP, syscall.SIGKILL)
go HandleSignals(sigs)
sendFd, err := os.OpenFile(*PlumbFile, os.O_RDONLY, os.ModeNamedPipe)
if err != nil {
log.Println(err)
}
defer sendFd.Close()
// Listening loop.
for {
_, err := io.Copy(&jsonMsg, sendFd)
if err != nil {
log.Println(err)
continue
}
if jsonMsg.Len() > 0 {
go ProcessMsg(jsonMsg.Bytes())
jsonMsg.Reset()
}
time.Sleep(50 * time.Millisecond)
}
}
func AffectVar(line string, rule *Rule) error {
var name string
var value string
for i := 0; i < len(line); i++ {
if line[i] == '=' {
name = line[:i]
value = line[i + 1:]
if name == "" {
return errors.New("Missing name is variable declaration")
}
break
}
if !IsAlphaNum(line[i]) {
return errors.New("Invalid character '" + string(line[i]) +
"' in variable declaration: " + line)
}
}
value, err := Expand([]byte(value), &rule.Vars)
if err != nil {
return err
}
(*rule).Vars[name] = value
return nil
}
func CookPattern(line string, pattern *Pattern) error {
var tokNb int
var isTok bool
for i := 0; i < len(line); i++ {
if line[i] != ' ' && line[i] != '\t' || tokNb == 2 && isTok {
switch tokNb {
case 0:
(*pattern).Obj += string(line[i])
case 1:
(*pattern).Verb += string(line[i])
case 2:
(*pattern).Arg += string(line[i])
}
isTok = true
} else if isTok && tokNb < 2 {
tokNb++
isTok = false
}
}
if (*pattern).Arg == "" || (*pattern).Verb == "" || (*pattern).Obj == "" {
return errors.New("Inconsistent pattern: " + line)
}
return nil
}
func EvalPattern(rule *Rule, i int) (bool, error) {
var patternValue bool
var err error
pattern := (*rule).Patterns[i]
pattern.Arg, err = Expand([]byte(pattern.Arg), &rule.Vars)
if err != nil {
return false, err
}
if pattern.Obj == "arg" || pattern.Obj == "data" || pattern.Obj == "dst" ||
pattern.Obj == "src" || pattern.Obj == "type" || pattern.Obj == "wdir" {
switch pattern.Verb {
case "is":
patternValue = (pattern.Arg == (*rule).Vars[pattern.Obj])
case "isn't":
patternValue = (pattern.Arg != (*rule).Vars[pattern.Obj])
case "set":
(*rule).Vars[pattern.Obj] = pattern.Arg
patternValue = true
case "matches":
re := regexp.MustCompile(pattern.Arg)
patternValue = re.MatchString((*rule).Vars[pattern.Obj])
if patternValue {
submatch := re.FindStringSubmatch((*rule).Vars[pattern.Obj])
// set $0 $1 ... $n
for i := 0; i < len(submatch); i++ {
(*rule).Vars[strconv.Itoa(i)] = submatch[i]
}
}
case "isfile": fallthrough
case "isdir":
// If pattern.Arg isn't an absolute path,
// concatenate it with the working directory.
if len(pattern.Arg) > 0 && pattern.Arg[0] != '/' {
pattern.Arg = (*rule).Vars["wdir"] + "/" + pattern.Arg
}
stat, err := os.Stat(pattern.Arg)
if err != nil {
break
}
mode := stat.Mode()
if pattern.Verb == "isfile" && mode.IsRegular() {
patternValue = true
(*rule).Vars["file"] = pattern.Arg
}
if pattern.Verb == "isdir" && mode.IsDir() {
patternValue = true
(*rule).Vars["dir"] = pattern.Arg
}
default:
err = errors.New("Inconsistent verb with object '" +
pattern.Obj + "': " + pattern.Verb)
}
} else if pattern.Obj == "plumb" {
switch pattern.Verb {
case "start":
PlumbStart(pattern.Arg, &rule.Vars)
patternValue = true
case "to":
// If pattern.Arg isn't an absolute path,
// concatenate it with the working directory.
if len(pattern.Arg) > 0 && pattern.Arg[0] != '/' {
pattern.Arg = (*rule).Vars["wdir"] + "/" + pattern.Arg
}
PlumbTo((*rule).Vars["arg"], pattern.Arg)
patternValue = true
default:
err = errors.New("Inconsistent verb with object '" +
pattern.Obj + "': " + pattern.Verb)
}
} else {
err = errors.New("Unknow object: " + pattern.Obj)
patternValue = false
}
return patternValue, err
}
func EvalRule(rule *Rule) {
(*rule).Value = true
for i := 0; i < len((*rule).Patterns) && (*rule).Value; i++ {
patternValue, err := EvalPattern(rule, i)
if err != nil {
log.Println(err)
}
(*rule).Value = (*rule).Value && patternValue
}
}
func HandleSignals(sigs chan os.Signal) {
for s := range(sigs) {
switch s {
case syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP, syscall.SIGQUIT:
log.Printf("Exit on signal: %d\n", s)
os.Exit(1)
}
}
}
func LineType(line string) int {
if line == "\n" || line == "" {
return BLANK
} else if line[0] == '#' {
return COMMENT
}
for i := 0; i < len(line); i++ {
if line[i] == ' ' || line[i] == '\t' {
return PATTERN
} else if line[i] == '=' {
return AFFECT
}
}
return ERROR
}
func PlumbStart(command string, vars *Variables) {
// Use the shell, and shell options defined in rules,
// if they aren't defined, use the default ones.
shell, shellExists := (*vars)["SHELL"]
shellOpts, shellOptsExists := (*vars)["SHELL_OPTS"]
if !shellExists || !shellOptsExists {
shell = DefaultShell
shellOpts = DefaultShellOpts
}
cmd := exec.Command(shell, shellOpts, command)
err := cmd.Start()
if err != nil {
log.Println(err)
} else {
log.Printf("Plumb start %s\n", command)
}
}
func PlumbTo(text string, fileName string) {
fd, err := os.OpenFile(fileName, os.O_CREATE | os.O_APPEND | os.O_WRONLY, 0777)
if err != nil {
log.Println(err)
} else {
defer fd.Close()
fd.WriteString(text + "\n")
log.Printf("Plumb to %s :\n%s\n", fileName, text)
}
}
func ProcessMsg(jsonMsg []byte) {
var msg Msg
var rule Rule
var ruleTemplate Rule
var ruleErr bool
var capturing bool
// Unpack the json encoded message
err := json.Unmarshal(jsonMsg, &msg)
if err != nil {
log.Println(err)
return
}
// Create a rule template with message variables.
ruleTemplate.Vars = Variables {
"data": msg.Data, "dst": msg.Dst, "src": msg.Src,
"type": msg.Type, "wdir": msg.Wdir, "dir": "", "file": "",
}
rulesFd, err := os.Open(*RulesFile)
if err != nil {
log.Println(err)
return
}
defer rulesFd.Close()
scanner := bufio.NewScanner(rulesFd)
for scanner.Scan() {
err := scanner.Err()
if err != nil {
log.Println(err)
}
line := strings.Trim(scanner.Text(), " \t")
switch LineType(line) {
case AFFECT:
// Add the variable to the rule template
err := AffectVar(line, &ruleTemplate)
if err != nil {
log.Println(err)
}
ruleErr = true
case BLANK:
if capturing && !ruleErr && len(rule.Patterns) > 0 {
EvalRule(&rule)
if rule.Value {
return
}
capturing = false
}
ruleErr = false
case COMMENT: // Skip the line
case PATTERN:
// New rule encountered: initialize a new rule from the template
if !capturing {
rule = ruleTemplate
}
if ruleErr {
break
}
var pattern Pattern
err := CookPattern(line, &pattern)
if err != nil {
ruleErr = true
log.Println(err)
break
}
rule.Patterns = append(rule.Patterns, pattern)
capturing = true
case ERROR:
ruleErr = true
}
}
// no valid rule in the whole rules file: print log message.
// If a rule value was true, the function return (cf case BLANK).
log.Println("Can't find valid rule for the message")
}