forked from Luzifer/awsenv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lockagent.go
86 lines (73 loc) · 1.66 KB
/
lockagent.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
package main
import (
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"strings"
"time"
log "github.com/Sirupsen/logrus"
"github.com/gorilla/mux"
"github.com/satori/go.uuid"
)
func runLockagent() {
var token string
deadChan := make(chan error)
r := mux.NewRouter()
r.HandleFunc("/password", func(res http.ResponseWriter, req *http.Request) {
if req.Header.Get("Token") == token {
http.Error(res, os.Getenv("PASSWD"), 200)
}
}).Methods("GET")
r.HandleFunc("/kill", func(res http.ResponseWriter, req *http.Request) {
if req.Header.Get("Token") == token {
deadChan <- fmt.Errorf("Quit")
}
}).Methods("POST")
http.Handle("/", r)
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
log.Errorf("Error listening: %s", err)
}
defer func() {
err := listener.Close()
if err != nil {
log.Errorf("Unable to close listener: %s", err)
}
}()
fmt.Println(listener.Addr().String())
port := strings.Split(listener.Addr().String(), ":")[1]
token, err = writeTokenFile(port)
if err != nil {
os.Exit(1)
}
go func() {
deadChan <- http.Serve(listener, nil)
}()
t := time.NewTicker(10 * time.Second)
for {
select {
case <-deadChan:
err := os.Remove(os.Getenv("DBFILE"))
if err != nil {
log.Errorf("Could not delete token file: %s", err)
}
return
case <-t.C:
token, err = writeTokenFile(port)
if err != nil {
os.Exit(1)
}
}
}
}
func writeTokenFile(port string) (string, error) {
t := uuid.NewV4().String()
err := ioutil.WriteFile(os.Getenv("DBFILE"), []byte(fmt.Sprintf("%s::%s", t, port)), 0600)
if err != nil {
log.Errorf("Unable to save token file: %s", err)
return "", err
}
return t, nil
}