forked from cnf/go-gdm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgdm.go
246 lines (220 loc) · 6.1 KB
/
gdm.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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
package gdm
import "net"
import "fmt"
import "strings"
import "time"
import "strconv"
import "errors"
const GDM_PORT_PLAYER = 32412
const GDM_PORT_SERVER = 32414
const SERVER_WAIT_TIME time.Duration = 2
func GetPlayers() ([]*GDMMessage, error) {
return getter(GDM_PORT_PLAYER)
}
func GetPlayer(name string) (*GDMMessage, error) {
gdms, err := getter(GDM_PORT_PLAYER)
if err != nil {
return nil, err
}
for _, gdm := range gdms {
if (gdm.Props["Name"] == name) || (gdm.Address.IP.String() == name) {
return gdm, nil
}
}
return nil, errors.New(fmt.Sprintf("No player found named `%s`", name))
}
func GetServers() ([]*GDMMessage, error) {
return getter(GDM_PORT_SERVER)
}
func GetServer(name string) (*GDMMessage, error) {
gdms, err := getter(GDM_PORT_SERVER)
if err != nil {
return nil, err
}
for _, gdm := range gdms {
if (gdm.Props["Name"] == name) || (gdm.Address.IP.String() == name) {
return gdm, nil
}
}
return nil, errors.New(fmt.Sprintf("No player found named `%s`", name))
}
func WatchPlayers(freq int) (*GDMWatcher, error) {
gdms, err := watcher(GDM_PORT_PLAYER, freq)
if err != nil {
return nil, err
}
return gdms, nil
}
func WatchPlayer(name string) (*GDMWatcher, error) { return nil, nil }
func WatchServers(freq int) (*GDMWatcher, error) {
gdms, err := watcher(GDM_PORT_SERVER, freq)
if err != nil {
return nil, err
}
return gdms, nil
}
func WatchServer(name string) (*GDMWatcher, error) { return nil, nil }
func WatchForUpdates() {}
type GDMMessage struct {
Address *net.UDPAddr
Added bool
Props map[string]string
}
type GDMWatcher struct {
Watch chan *GDMMessage
closer chan bool
}
type gdmBrowser struct {
mc chan *GDMMessage
ticker *time.Ticker
conn *net.UDPConn
}
func (w *GDMWatcher) Close() {
w.closer <- true
}
func getter(port int) ([]*GDMMessage, error) {
items := make([]*GDMMessage, 0)
browser, err := setupBrowser(10)
if err != nil { return nil, nil }
browser.listen()
browser.browse(port)
timer := time.NewTimer(time.Second * SERVER_WAIT_TIME)
done := false
for !done {
select {
case <-timer.C:
done = true
browser.conn.Close()
case msg := <- browser.mc:
items = append(items, msg)
}
}
return items, nil
}
func watcher(port int, freq int) (*GDMWatcher, error) {
browser, err := setupBrowser(10)
if err != nil {
return nil, err
}
browser.listen()
browser.browse(port)
go func() {
for {
<-browser.ticker.C
browser.browse(port)
}
}()
watcher := &GDMWatcher{Watch: browser.mc, closer: make(chan bool)}
browser.closer(watcher.closer)
return watcher, nil
}
func setupBrowser(i int) (*gdmBrowser, error) {
refresh := (time.Duration(i) * time.Second)
// setup listener to broadcast stuff
udpaddr, err := net.ResolveUDPAddr("udp4", ":0")
if err != nil {
return nil, err
}
conn, lerr := net.ListenUDP("udp4", udpaddr)
if lerr != nil {
return nil, lerr
}
return &gdmBrowser{conn: conn,
mc: make(chan *GDMMessage),
ticker: time.NewTicker(refresh)}, nil
}
func (b *gdmBrowser) listen() {
go func() {
buf := make([]byte, 1024)
for {
mlen, raddr, err := b.conn.ReadFromUDP(buf)
if err != nil {
if nerr, ok := err.(net.Error); !ok || !nerr.Temporary() {
// this connection has become useless
close(b.mc)
return
}
continue
}
msg := string(buf[0:mlen])
if strings.HasPrefix(msg, "HTTP/1.0 200 OK") {
gdmmsg := newGDMMessage(msg, raddr)
b.mc <- gdmmsg
}
}
}()
}
func (b *gdmBrowser) closer(s chan bool) {
go func() {
select {
case <- s:
b.conn.Close()
fmt.Println("channel closed")
return
}
}()
}
func (b *gdmBrowser) browse(port int) {
addrs := getBroadcastAddrs()
ports := strconv.Itoa(port)
for _, a := range addrs {
udpdest, err := net.ResolveUDPAddr("udp4", a+":"+ports)
if err != nil {
continue
}
buf := []byte("M-SEARCH * HTTP/1.1\r\n\r\n")
_, werr := b.conn.WriteToUDP(buf, udpdest);
if werr != nil {
continue
}
}
// browser.waitForReply()
}
func newGDMMessage(data string, addr *net.UDPAddr) (*GDMMessage) {
msglines := strings.Split(data, "\r\n")
gdm := GDMMessage{Address: addr, Added: true, Props: make(map[string]string)}
for _, m := range msglines {
if strings.Contains(m, ":") {
kv := strings.Split(m, ":")
if len(kv) == 2 {
gdm.Props[strings.TrimSpace(kv[0])] = strings.TrimSpace(kv[1])
}
}
}
return &gdm
}
func getBroadcastAddrs() (baddr []string) {
ifaces, _ := net.Interfaces()
for _, iface := range ifaces {
// only send on interfaces that are up and can do broadcast
upandbcast := net.FlagBroadcast | net.FlagUp
if iface.Flags & upandbcast != upandbcast {
continue
}
addrs, _ := iface.Addrs()
if len(addrs) == 0 {
continue
}
for _, addr := range addrs {
var bcast []string
ip, ipn, err := net.ParseCIDR(addr.String())
if err != nil {
continue
}
// we only handle ipv4 addresses for now
ipv4 := ip.To4()
if ipv4 == nil {
continue
}
for i, m := range ipn.Mask {
if m == 0 {
bcast = append(bcast, "255")
} else {
bcast = append(bcast, fmt.Sprintf("%d", ipv4[i]))
}
}
baddr = append(baddr, strings.Join(bcast, "."))
}
}
return baddr
}