-
Notifications
You must be signed in to change notification settings - Fork 1
/
srsd.go
119 lines (97 loc) · 1.96 KB
/
srsd.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
package main
import (
"bufio"
"net"
"os"
"strings"
)
type srsdListener struct {
config *config
socketPath string
listener net.Listener
}
type srsd interface {
run() error
close() error
}
func newSrsd(config *config, socketPath string, socketAccess os.FileMode) (srsd srsd, err error) {
os.Remove(socketPath)
listener, err := net.Listen("unix", socketPath)
if err != nil {
return
}
err = os.Chmod(socketPath, socketAccess & 0777)
if err != nil {
return
}
srsd = &srsdListener{config, socketPath, listener}
return
}
func (srsd *srsdListener) run() (error) {
for {
connection, err := srsd.listener.Accept()
if err != nil {
return err
}
go handleConnection(srsd, connection)
}
return nil
}
func writeError(writer *bufio.Writer, writeErr error) (err error) {
_, err = writer.WriteString("ERROR: ")
if err != nil {
return
}
_, err = writer.WriteString(writeErr.Error())
if err != nil {
return
}
_, err = writer.WriteString("\n")
if err != nil {
return
}
err = writer.Flush()
return
}
func handleConnection(srsd *srsdListener, connection net.Conn) {
reader := bufio.NewReader(connection)
writer := bufio.NewWriter(connection)
for {
line, err := reader.ReadString('\n')
if err != nil {
break;
}
line = strings.TrimSuffix(line, "\n")
cmd, err := parseCommand(line)
if err != nil {
writeError(writer, err)
break;
}
result, err := cmd.process(srsd.config)
if err != nil {
writeError(writer, err)
} else {
_, err = writer.WriteString(result)
if err != nil {
break;
}
_, err = writer.WriteString("\n")
if err != nil {
break;
}
}
err = writer.Flush()
if err != nil {
break;
}
}
connection.Close()
}
func (srsd *srsdListener) close() (err error) {
err = srsd.listener.Close()
if err != nil {
return
}
err = os.Remove(srsd.socketPath)
return
}