-
Notifications
You must be signed in to change notification settings - Fork 0
/
stun.go
64 lines (52 loc) · 1.05 KB
/
stun.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
package stun
import (
"net"
)
const (
headerSize = 20
magicCookie uint32 = 0x2112A442
magicCookiePort uint16 = 0x2112
nonceSecurityFeaturesPrefix = "obMatJos2"
)
type Type uint16
const (
TypeBindingRequest Type = 0x0001
TypeBindingSuccess Type = 0x0101
)
type TxID [12]byte
type Message struct {
typ Type
txID TxID
}
func (m *Message) Type() Type { return m.typ }
func (m *Message) TxID() (txID TxID) { copy(txID[:], m.txID[:]); return }
func (m *Message) Reset() {
m.typ = 0
for i := range m.txID[:] {
m.txID[i] = 0
}
}
func Serve(pc net.PacketConn, password string) {
buf := make([]byte, 4*1024)
var p Parser
var m Message
for {
n, addr, err := pc.ReadFrom(buf)
if err != nil {
continue
}
if err := p.Parse(&m, buf[:n:n]); err != nil {
continue
}
switch m.Type() {
case TypeBindingRequest:
b := New(TypeBindingSuccess, m.TxID())
b.SetXorMappingAddress(addr.(*net.UDPAddr))
if raw, err := b.Build(); err == nil {
if _, err := pc.WriteTo(raw, addr); err != nil {
// @TODO?
}
}
}
}
}