/
main.go
107 lines (96 loc) · 2.23 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
package main
import (
"os"
"os/exec"
"log"
"html/template"
"net/http"
"github.com/davidbanham/required_env"
"fmt"
"strings"
)
func main() {
required_env.Ensure(map[string]string{"ROUTER": "", "PORT": "3000", "COUNTRIES": "US,AU"})
countries := strings.Split(os.Getenv("COUNTRIES"), ",")
allowed_countries := map[string]bool{"": true}
for _, key := range countries {
allowed_countries[key] = true
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
target := r.FormValue("country")
if !allowed_countries[target] {
w.WriteHeader(403)
w.Write([]byte("That country is not permitted!"))
return
}
if target != "" {
fmt.Println(target)
err := fly(target, w)
if err != nil {
w.Write([]byte(err.Error()))
return
}
}
t, err := template.New("foo").Parse(`
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Jetlag</title>
</head>
<body>
{{if .LastAction}}
<h4>Just flew to {{ .LastAction }}</h4>
{{end}}
{{range .Countries}}
<div>
<form action="/" method="POST">
<input type="hidden" name="country" value="{{ . }}"></input>
<button type="submit">{{ . }}</button>
</form>
</div>
{{end}}
</body>
</html>
`)
if err != nil {
w.Write([]byte(err.Error()))
return
}
data := struct {
Countries []string
LastAction string
}{
Countries: countries,
LastAction: target,
}
err = t.Execute(w, data)
if err != nil {
w.Write([]byte(err.Error()))
return
}
})
log.Fatal(http.ListenAndServe(":"+os.Getenv("PORT"), nil))
}
func fly(target string, w http.ResponseWriter) error {
router := os.Getenv("ROUTER")
scriptName := target + "-vpn.sh"
cmd := exec.Command("ssh", router, "killall openvpn")
cmd.Stdout = w
cmd.Stderr = w
err := cmd.Run()
if err != nil {
if e := err.Error(); e != "exit status 1" {
return err
}
}
cmd2 := exec.Command("ssh", router, "/root/"+scriptName)
cmd2.Stdout = w
cmd2.Stderr = w
err = cmd2.Run()
if err != nil {
return err
}
return nil
}