-
Notifications
You must be signed in to change notification settings - Fork 26
/
main.go
78 lines (65 loc) · 1.57 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
package main
import (
"fmt"
"log"
"net"
"github.com/wilfreddenton/crypto"
"github.com/wilfreddenton/udp-hole-punching/shared"
"github.com/wilfreddenton/udp-hole-punching/udp_server"
)
var (
pubKey [32]byte
priKey [32]byte
)
func route(peers shared.Peers, conns shared.Conns, conn shared.Conn, m *shared.Message) (*shared.Message, error) {
switch m.Type {
case "greeting":
return greetingHandler(conn, m)
case "register":
return registerHandler(peers, conn, m)
case "establish":
return establishHandler(peers, conns, m)
default:
return notFoundHandler(m)
}
}
func createMessageCallback(peers shared.Peers) func(cs shared.Conns, c shared.Conn, m *shared.Message) {
return func(cs shared.Conns, c shared.Conn, m *shared.Message) {
// log request
log.Printf("Request from client at %s over %s with type %s", c.GetAddr(), c.Protocol(), m.Type)
// route request to a handler
res, err := route(peers, cs, c, m)
// respond with error if there was one
if err != nil {
c.Send(&shared.Message{
Type: m.Type,
Error: err.Error(),
})
return
}
// respond
err = c.Send(res)
if err != nil {
log.Print(err)
}
}
}
func main() {
fmt.Println("UDP Hole Punching Rendezvous Server v0.0.1")
var err error
priKey, pubKey, err = crypto.GenKeyPair()
if err != nil {
log.Fatal(err)
}
udpAddr, err := net.ResolveUDPAddr("udp", "0.0.0.0:9001")
if err != nil {
log.Fatal(err)
}
udpS, err := udp_server.New(udpAddr)
if err != nil {
log.Fatal(err)
}
udpPeers := make(shared.Peers)
udpS.OnMessage(createMessageCallback(udpPeers))
udpS.Listen()
}