-
Notifications
You must be signed in to change notification settings - Fork 1
/
socket.go
60 lines (54 loc) · 1.12 KB
/
socket.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
package tcpdam
import (
"net"
"os"
"strings"
)
func (dam *Dam) executeCommand(args []string) {
switch args[0] {
case "open":
dam.Open()
case "close":
dam.Close()
case "set-remote":
if len(args) > 1 {
dam.SetRemoteAddr(args[1])
} else {
dam.Logger.Errorf("Missing argument for %s", args[0])
}
default:
dam.Logger.Errorf("Command not found: %s", args[0])
}
}
func (dam *Dam) StartControlSocket(path string) {
dam.Logger.Debugf("Starting control socket at %s", path)
l, err := net.ListenUnix("unix", &net.UnixAddr{Name: path, Net: "unix"})
if err != nil {
panic(err)
}
defer os.Remove(path)
for {
conn, err := l.AcceptUnix()
if err != nil {
panic(err)
}
var buf [1024]byte
n, err := conn.Read(buf[:])
if err != nil {
panic(err)
}
args := strings.Split(strings.TrimSpace(string(buf[:n])), " ")
dam.executeCommand(args)
conn.Close()
}
}
func SendControlCommand(path string, command string) error {
conn, err := net.DialUnix("unix", nil,
&net.UnixAddr{Name: path, Net: "unix"})
if err != nil {
return err
}
defer conn.Close()
_, err = conn.Write([]byte(command))
return err
}