-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstun_service.go
78 lines (68 loc) · 1.6 KB
/
stun_service.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 discovery
import (
"context"
"github.com/ccding/go-stun/stun"
"github.com/iain17/logger"
"fmt"
)
type StunService struct {
initialized bool
client *stun.Client
localNode *LocalNode
logger *logger.Logger
context context.Context
}
func (d *StunService) String() string {
return "Stun"
}
func (s *StunService) init(ctx context.Context) (err error) {
if s.initialized {
return nil
}
s.initialized = true
s.logger = logger.New(s.String())
s.context = ctx
s.client = stun.NewClient()
go s.Serve(ctx)
return nil
}
func (s *StunService) Stop() {
}
func (s *StunService) Serve(ctx context.Context) (err error) {
err = s.init(ctx)
if err != nil {
return err
}
s.logger.Info("Running")
nat, host, err := s.client.Discover()
if err != nil {
return err
}
if host != nil {
s.logger.Debugf("processed, family %d, host %q, port %d", host.Family(), host.IP(), host.Port())
s.localNode.ip = host.IP()
s.localNode.port = int(host.Port())
}
switch nat {
case stun.NATError:
return fmt.Errorf("NAT error")
case stun.NATUnknown:
return fmt.Errorf("unexpected response from the STUN server")
case stun.NATBlocked:
return fmt.Errorf("UDP is blocked")
case stun.NATFull:
return fmt.Errorf("full cone NAT")
case stun.NATSymetric:
return fmt.Errorf("symetric NAT")
case stun.NATRestricted:
return fmt.Errorf("restricted NAT")
case stun.NATPortRestricted:
return fmt.Errorf("port restricted NAT")
case stun.NATNone:
return fmt.Errorf("not behind a NAT")
case stun.NATSymetricUDPFirewall:
return fmt.Errorf("symetric UDP firewall")
}
s.logger.Info("NAT open!")
return nil
}