-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
188 lines (160 loc) · 4.1 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
package main
import (
"encoding/json"
"fmt"
"log"
"net"
"net/http"
"strings"
"sync"
"time"
)
const lifetime time.Duration = 24 * time.Hour
const httpAddr = ":8180"
var devices struct {
sync.Mutex
d []Device
}
type Device struct {
ExternalAddress string `json:"-"`
InternalAddress string `json:"internaladdress"`
Port int `json:"port,omitempty"` // optional
Name string `json:"name"`
Added time.Time `json:"added"`
}
func main() {
devices.d = make([]Device, 0)
http.HandleFunc("/favicon.ico", func(w http.ResponseWriter, r *http.Request) {})
http.HandleFunc("/api/register", RegisterDevice)
http.HandleFunc("/api/devices", ListDevices)
http.Handle("/", http.FileServer(http.Dir("public")))
go cleanup()
fmt.Println("listen on", httpAddr)
// Note: use TLS
log.Fatal(http.ListenAndServe(httpAddr, nil))
}
func findDevice(ia string, ea string) (int, bool) {
for i, d := range devices.d {
if d.InternalAddress == ia && d.ExternalAddress == ea {
return i, true
}
}
return -1, false
}
func devicesFor(ea string) []Device {
found := []Device{}
for _, d := range devices.d {
if d.ExternalAddress == ea {
found = append(found, d)
}
}
return found
}
func RegisterDevice(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Content-Type") != "application/json" {
http.Error(w, "Please send json", 400)
return
}
if r.Body == nil {
http.Error(w, "Please send a request body", 400)
return
}
var t struct {
Name string `json:"name"`
Address string `json:"address"`
Port int `json:"port"`
}
err := json.NewDecoder(r.Body).Decode(&t)
if err != nil {
http.Error(w, err.Error(), 400)
return
}
t.Address = strings.Trim(t.Address, " ")
if net.ParseIP(t.Address) == nil {
http.Error(w, t.Address+" is not a valid IP address", http.StatusBadRequest)
return
}
// Prevent simple loopback mistake
if t.Address == "127.0.0.1" || t.Address == "::1" {
http.Error(w, `Loopback is not allowed`, http.StatusBadRequest)
return
}
if net.ParseIP(t.Address) == nil {
http.Error(w, `"address" is not a valid IP address`, http.StatusBadRequest)
return
}
// TODO: validate parameter name required and no html/js
ea, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
http.NotFound(w, r)
return
}
// Check if proxy was configured.
if ea == "127.0.0.1" {
xrealip := r.Header.Get("x-real-ip")
if xrealip != "" {
ea = xrealip
} else {
log.Println("127.0.0.1 tried to add an address, this can happen when proxy is not configured correctly.")
http.Error(w, `Host 127.0.0.1 is not allowed to register devices`, http.StatusBadRequest)
http.NotFound(w, r)
return
}
}
devices.Lock()
defer devices.Unlock()
if i, ok := findDevice(t.Address, ea); ok {
devices.d[i].Name = t.Name
devices.d[i].Port = t.Port
devices.d[i].Added = time.Now()
log.Println(time.Now(), "updated", t.Address)
} else {
devices.d = append(devices.d, Device{
ExternalAddress: ea,
InternalAddress: t.Address,
Port: t.Port,
Name: t.Name,
Added: time.Now(),
})
log.Println(time.Now(), "added", t.Address)
}
fmt.Fprintf(w, "Successfully added, visit https://nupnp.com for more.\n")
}
func ListDevices(w http.ResponseWriter, r *http.Request) {
ea, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
http.NotFound(w, r)
return
}
// Check if proxy was configured.
if ea == "127.0.0.1" {
xrealip := r.Header.Get("x-real-ip")
if xrealip != "" {
ea = xrealip
} else {
log.Println("127.0.0.1 tried to access an address, this can happen when proxy is not configured correctly.")
http.NotFound(w, r)
return
}
}
devices.Lock()
defer devices.Unlock()
ds := devicesFor(ea)
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(ds); err != nil {
panic(err)
}
}
func cleanup() {
for {
time.Sleep(time.Second * 5)
devices.Lock()
for i := len(devices.d) - 1; i >= 0; i-- {
d := devices.d[i]
if time.Since(d.Added) > lifetime {
devices.d = append(devices.d[:i], devices.d[i+1:]...)
}
}
devices.Unlock()
}
}