/
publisher.go
103 lines (96 loc) · 2.59 KB
/
publisher.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
package main
import (
"io/ioutil"
"net"
"net/http"
"github.com/Cloud-Foundations/Dominator/lib/html"
"github.com/Cloud-Foundations/golib/pkg/constants"
)
const (
maxResponses = 100
maxSize = 1 << 16
)
func (proxy *acmeProxy) setupPublisher() error {
proxy.ipMap = make(map[string]*responsesType)
html.HandleFunc(constants.AcmeProxyCleanupResponses, proxy.cleanupHandler)
html.HandleFunc(constants.AcmeProxyRecordResponse, proxy.recordHandler)
return nil
}
func (proxy *acmeProxy) getResponse(hostPort, path string) []byte {
host, _, err := net.SplitHostPort(hostPort)
if err != nil {
host = hostPort
}
ips, err := net.LookupHost(host)
if err != nil {
proxy.logger.Println(err)
return nil
}
proxy.rwMutex.RLock()
defer proxy.rwMutex.RUnlock()
for _, ip := range ips {
if responses := proxy.ipMap[ip]; responses != nil {
if data := responses.pathMap[path]; len(data) > 0 {
return data
}
}
}
return nil
}
func (proxy *acmeProxy) cleanupHandler(w http.ResponseWriter,
req *http.Request) {
if req.Method != "POST" {
http.Error(w, "Use POST", http.StatusMethodNotAllowed)
return
}
host, _, err := net.SplitHostPort(req.RemoteAddr)
if err != nil {
http.Error(w, "Cannot split host:port", http.StatusInternalServerError)
proxy.logger.Println(err)
return
}
proxy.rwMutex.Lock()
defer proxy.rwMutex.Unlock()
delete(proxy.ipMap, host)
proxy.logger.Debugf(0, "cleaned up for: %s\n", host)
}
func (proxy *acmeProxy) recordHandler(w http.ResponseWriter,
req *http.Request) {
if req.Method != "POST" {
http.Error(w, "Use POST", http.StatusMethodNotAllowed)
return
}
host, _, err := net.SplitHostPort(req.RemoteAddr)
if err != nil {
http.Error(w, "Cannot split host:port", http.StatusInternalServerError)
proxy.logger.Println(err)
return
}
data, err := ioutil.ReadAll(req.Body)
if err != nil {
http.Error(w, "Cannot read body", http.StatusBadRequest)
proxy.logger.Println(err)
return
}
if len(data) > maxSize {
http.Error(w, "Too much data", http.StatusNotAcceptable)
return
}
proxy.rwMutex.Lock()
defer proxy.rwMutex.Unlock()
responses := proxy.ipMap[host]
if responses == nil {
responses = &responsesType{make(map[string][]byte)}
proxy.ipMap[host] = responses
} else if len(responses.pathMap) >= maxResponses {
http.Error(w, "Too much data", http.StatusTooManyRequests)
return
}
if len(responses.pathMap[req.URL.RawQuery]) > 0 {
http.Error(w, "Duplicate path", http.StatusConflict)
return
}
responses.pathMap[req.URL.RawQuery] = data
w.WriteHeader(http.StatusOK)
proxy.logger.Printf("%s: recorded for path: %s\n", host, req.URL.RawQuery)
}