-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
171 lines (146 loc) · 4.43 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
package main
import (
"bytes"
"flag"
"fmt"
"io/ioutil"
"log"
"net"
"strings"
"time"
)
var (
timeout = flag.Duration("timeout", 10*time.Second, "Discovery timeout duration")
userID = flag.String("user-id", "", "Tunnelbroker User ID")
password = flag.String("password", "", "Tunnelbroker password")
tunnelID = flag.String("tunnel-id", "", "Tunnelbroker tunnel ID")
noopMode = flag.Bool("noop", false, "Do not actually update the Tunnelbroker config")
cacheFile = flag.String("cache-file", ".upnp_tunnel_updater.cache", "Cache file that stores the previously updated IP.")
)
func main() {
// Check all necessary flags
flag.Parse()
if !*noopMode && (*userID == "" || *password == "" || *tunnelID == "") {
log.Fatalf("Require user-id, password and tunnel-id to update Tunnelbroker config")
}
conn, err := net.ListenPacket("udp4", ":0")
if err != nil {
log.Fatalf("error creating UDP listener: %s", err.Error())
}
udp := conn.(*net.UDPConn)
log.Printf("listening on UDP %s", udp.LocalAddr())
decodeChan := make(chan []byte)
ssdpChan := make(chan map[string]string)
quitChan := make(chan struct{}, 1)
go msgDecoder(decodeChan, ssdpChan, quitChan)
go UPNPListener(udp, decodeChan)
ssdp, _ := net.ResolveUDPAddr("udp4", "239.255.255.250:1900")
query := ssdpQueryMessage(*timeout)
_, err = udp.WriteToUDP(query.Bytes(), ssdp)
if err != nil {
log.Fatalf("error during UPNP discovery message: %s", err.Error())
}
log.Printf("sent SSDP discovery message (timeout: %s)", *timeout)
// Only wait for the first message or timeout
var msg map[string]string
select {
case msg = <-ssdpChan:
quitChan <- struct{}{}
case <-time.After(*timeout):
log.Fatalf("timed out after %s waiting for discovery response", *timeout)
}
// Find the control point from the discovery response
controlPoint, err := getWANControlPoint(msg)
if err != nil {
fmt.Println(err)
return
}
log.Printf("received control point: %s", controlPoint)
// Hit the control point
wanIP := retrieveWANIP(controlPoint)
if wanIP == "" {
return
}
log.Printf("Current WAN IP is: %s", wanIP)
// Check the cache
if !hasCurrentIPChanged(wanIP, *cacheFile) {
log.Printf("WAN IP has not changed since last run, exiting.")
return
}
// Update the Tunnel config
if *noopMode {
return
}
err = tunnelBrokerUpdate(wanIP)
if err != nil {
log.Printf("%s", err)
}
// Save the new IP address since we successfully updated the tunnel config
log.Printf("Saving new WAN IP to cache file %s", *cacheFile)
saveNewWANIP(wanIP, *cacheFile)
}
func UPNPListener(conn *net.UDPConn, decodeChan chan []byte) {
for {
buf := make([]byte, 512)
n, err := conn.Read(buf)
log.Printf("Read %d bytes from UDP listener\n", n)
if err != nil {
log.Printf("error receiving UDP packet: %s", err.Error())
break
}
decodeChan <- buf
}
}
// Generate a discovery message that restricts the search target to
// only WANIPConnection:1 services.
func ssdpQueryMessage(timeoutDuration time.Duration) *bytes.Buffer {
msg := &bytes.Buffer{}
msg.WriteString("M-SEARCH * HTTP/1.1\r\n")
msg.WriteString("Host: 239.255.255.250:1900\r\n")
msg.WriteString("MAN: \"ssdp:discover\"\r\n")
msg.WriteString(fmt.Sprintf("MX: %d\r\n", int(timeoutDuration.Seconds())))
msg.WriteString("ST: urn:schemas-upnp-org:service:WANIPConnection:1\r\n")
msg.WriteString("\r\n")
return msg
}
func msgDecoder(decodeChan chan []byte, ssdpChan chan map[string]string, quitChan chan struct{}) {
for packet := range decodeChan {
ssdpResponse := make(map[string]string)
// Response lines are separated by CR+LF as in requests
lines := strings.Split(string(packet), "\r\n")
for i := range lines {
// Throw away empty lines
if lines[i] == "" {
continue
}
// Capture status separately
if len(lines[i]) > 4 && lines[i][:4] == "HTTP" {
ssdpResponse["status"] = lines[i]
} else {
// Split header:value from line
fields := strings.SplitN(lines[i], ":", 2)
// Guard against headers with no content
if len(fields) < 2 {
continue
}
ssdpResponse[strings.ToLower(fields[0])] = strings.TrimSpace(fields[1])
}
}
select {
case ssdpChan <- ssdpResponse:
return
case _ = <-quitChan:
return
}
}
}
func hasCurrentIPChanged(wanIP, filename string) bool {
contents, err := ioutil.ReadFile(filename)
if err != nil {
return true
}
return !(string(contents) == wanIP)
}
func saveNewWANIP(wanIP, filename string) {
_ = ioutil.WriteFile(filename, []byte(wanIP), 0600)
}