-
Notifications
You must be signed in to change notification settings - Fork 0
/
tftp.go
62 lines (56 loc) · 1.4 KB
/
tftp.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
package main
import (
"errors"
"io"
"log"
"os"
"os/exec"
"github.com/NiceLabs/hook-driven-server/utils"
"github.com/pin/tftp/v3"
)
type TFTPConfigure struct {
Workdir string `json:"workdir"`
ReadHook string `json:"hook_read"`
WriteHook string `json:"hook_write"`
}
func (t *TFTPConfigure) NewServer() *tftp.Server {
return tftp.NewServer(t.onRead, t.onWrite)
}
func (t *TFTPConfigure) onRead(filename string, reader io.ReaderFrom) (err error) {
log.Printf("Read %q\n", filename)
if t.ReadHook == "" {
return errors.New("tftp-worker: read operation not permitted")
}
cmd := exec.Command(t.ReadHook, filename)
cmd.Dir = t.Workdir
utils.AddEnv(cmd, map[string]string{
"TFTP_ACTION": "READ",
"TFTP_READ_FILE": filename,
})
cmd.Stderr = os.Stderr
go func() {
if stdout, err := cmd.StdoutPipe(); err == nil {
_, _ = reader.ReadFrom(stdout)
}
}()
return cmd.Run()
}
func (t *TFTPConfigure) onWrite(filename string, writer io.WriterTo) (err error) {
log.Printf("Write %q\n", filename)
if t.WriteHook == "" {
return errors.New("tftp-worker: write operation not permitted")
}
cmd := exec.Command(t.WriteHook, filename)
cmd.Dir = t.Workdir
utils.AddEnv(cmd, map[string]string{
"TFTP_ACTION": "WRITE",
"TFTP_WRITE_FILE": filename,
})
cmd.Stderr = os.Stderr
go func() {
if stdin, err := cmd.StdinPipe(); err == nil {
_, _ = writer.WriteTo(stdin)
}
}()
return cmd.Run()
}