-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
289 lines (259 loc) · 6.05 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
package main
import (
"bytes"
"flag"
"fmt"
"html/template"
"io"
"log"
"net/http"
"os"
"os/exec"
"path"
"path/filepath"
"runtime"
"strings"
"github.com/go-chi/chi"
)
type vpnState int
func (s vpnState) String() string {
switch s {
case Disconnected:
return "Disconnected"
case Connecting:
return "Connecting"
case Active:
return "Active"
}
return "Unknown"
}
func (s vpnState) Refresh() bool {
switch s {
case Disconnected:
return false
case Connecting:
return true
case Active:
return false
}
return false
}
const (
Disconnected vpnState = iota
Connecting
Active
Done
)
var status vpnState
type vpnServer struct {
Name string
Config string
}
type htmlPage struct {
Refresh bool
State string
Servers []vpnServer
}
type process struct {
cmd *exec.Cmd
messages chan string
state chan<- vpnState
done chan<- error
quit chan error
}
func NewProcess(state chan<- vpnState, done chan<- error) *process {
p := process{}
p.state = state
p.done = done
p.quit = make(chan error, 1)
return &p
}
func (p *process) Start(config string) error {
p.cmd = exec.Command("openvpn", "--config", config)
stdout, err := p.cmd.StdoutPipe()
if err != nil {
return err
}
p.messages = make(chan string, 10)
// Spawn a go routine consuming messages
go func(m <-chan string, s chan<- vpnState, q <-chan error) {
for {
select {
case message := <-m:
if strings.Contains(message, "Initialization Sequence Completed") {
s <- Active
}
case <-q:
return
}
}
}(p.messages, p.state, p.quit)
// Spawn a go routine parsing cmd output and sending it to a channel
go func(rc io.ReadCloser, m chan<- string, q <-chan error) {
var message []byte
for {
select {
case <-q:
return
default:
b := make([]byte, 80)
n, err := rc.Read(b)
if err != nil {
if strings.Contains(err.Error(), os.ErrClosed.Error()) {
return
}
log.Println("error reading cmd output:", err)
}
parts := bytes.Split(b[:n], []byte{10})
splits := len(parts)
for i, part := range parts {
message = append(message, part...)
if i != splits-1 {
m <- string(message)
message = message[:0]
}
}
}
}
}(stdout, p.messages, p.quit)
// Start the cmd
err = p.cmd.Start()
if err != nil {
close(p.messages)
close(p.quit)
return err
}
p.state <- Connecting
// Spawn a process waiting for the command the finnish
go func() {
p.done <- p.cmd.Wait()
}()
return nil
}
func (p *process) Stop() error {
p.quit <- nil
close(p.messages)
return p.cmd.Process.Kill()
}
func serverConfigs(confDir string) ([]vpnServer, error) {
tmpFiles, err := filepath.Glob(confDir + "/*.ovpn")
if err != nil {
return nil, err
}
servers := make([]vpnServer, len(tmpFiles))
for i, tmpFile := range tmpFiles {
servers[i] = vpnServer{Name: strings.TrimSuffix(path.Base(tmpFile), ".ovpn"), Config: tmpFile}
}
return servers, nil
}
func main() {
var host string
var port int
var configDir string
var dataDir string
flag.StringVar(&host, "host", "0.0.0.0", "Host to bind to")
flag.IntVar(&port, "port", 8080, "Port to bind to")
flag.StringVar(&configDir, "config-dir", "/etc/openvpn", "Directoy with configurations")
flag.StringVar(&dataDir, "data-dir", "/usr/share/gopenvpn", "Directory for templates")
flag.Parse()
// read template or panic
indexFile := filepath.Join(dataDir, "index.html")
tmpl := template.Must(template.ParseFiles(indexFile))
state := make(chan vpnState, 1)
done := make(chan error, 1)
// Spawn a go routine updating internal state
go func(s <-chan vpnState, d <-chan error) {
for {
select {
case vpnState := <-s:
status = vpnState
case <-d:
status = Disconnected
}
}
}(state, done)
var p *process
r := chi.NewRouter()
r.Get("/state", func(w http.ResponseWriter, r *http.Request) {
log.Println(r.URL.String())
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte(fmt.Sprintf("VPN: %s\n", status.String())))
w.Write([]byte(fmt.Sprintf("Number of goroutines: %d\n", runtime.NumGoroutine())))
w.Write([]byte(fmt.Sprintf("Process: %v\n", p)))
})
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
log.Println(r.URL.String())
var servers []vpnServer
if status == Disconnected {
s, err := serverConfigs(configDir)
if err != nil {
log.Println("unable to get server configs:", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("internal server error"))
return
}
servers = s
}
data := htmlPage{Refresh: status.Refresh(), State: status.String(), Servers: servers}
tmpl.Execute(w, data)
})
r.Get("/start", func(w http.ResponseWriter, r *http.Request) {
log.Println(r.URL.String())
if status == Disconnected {
configs, ok := r.URL.Query()["config"]
if !ok || len(configs[0]) < 1 {
log.Println("url param 'config' is missing")
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("bad request"))
return
}
config := configs[0]
proc := NewProcess(state, done)
err := proc.Start(config)
if err != nil {
log.Println("unable to start process:", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
p = proc
}
http.Redirect(w, r, "/", 307)
})
r.Get("/stop", func(w http.ResponseWriter, r *http.Request) {
log.Println(r.URL.String())
if status != Disconnected {
if p == nil {
w.WriteHeader(http.StatusBadRequest)
return
}
err := p.Stop()
if err != nil {
log.Println("unable to stop process:", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
p = nil
status = Disconnected
}
http.Redirect(w, r, "/", 307)
})
r.Get("/reset", func(w http.ResponseWriter, r *http.Request) {
log.Println(r.URL.String())
if p != nil {
p.Stop()
p = nil
}
status = Disconnected
http.Redirect(w, r, "/", 307)
})
// Fire up HTTP handler
srv := &http.Server{Addr: fmt.Sprintf("%s:%d", host, port), Handler: r}
log.Printf("Listening for requests on %s:%d", host, port)
err := srv.ListenAndServe()
if err != nil {
if err == http.ErrServerClosed {
return
}
log.Fatal(err)
}
}