-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupnp_service.go
73 lines (65 loc) · 1.49 KB
/
upnp_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
package discovery
import (
"github.com/miolini/upnp"
"time"
"context"
"github.com/iain17/logger"
)
type UPnPService struct {
mapping *upnp.Upnp
localNode *LocalNode
logger *logger.Logger
context context.Context
}
func (d *UPnPService) String() string {
return "UpNp"
}
func (s *UPnPService) init(ctx context.Context) error {
defer func() {
if s.localNode.wg != nil {
s.localNode.wg.Done()
}
}()
s.mapping = new(upnp.Upnp)
s.logger = logger.New(s.String())
s.context = ctx
return nil
}
func (s *UPnPService) Stop() {
s.mapping.DelPortMapping(s.localNode.port, "TCP")
}
func (s *UPnPService) Serve(ctx context.Context) {
s.localNode.waitTilCoreReady()
defer s.Stop()
if err := s.init(ctx); err != nil {
s.localNode.lastError = err
panic(err)
}
s.localNode.WaitTilReady()
ticker := time.Tick(1 * time.Minute)
for {
select {
case <-s.context.Done():
return
case <-ticker:
err := s.process(s.localNode.port)
if err != nil {
s.logger.Error("error on forwarding process, %v", err)
}
}
}
}
func (s *UPnPService) process(port int) (err error) {
s.logger.Debugf("trying to map port %d...", port)
if err := s.mapping.AddPortMapping(port, port, "TCP"); err == nil {
if s.mapping.GatewayOutsideIP != "" {
s.localNode.ip = s.mapping.GatewayOutsideIP
//Disabled: Seems empty?
//s.localNode.outgoingPort = s.mapping.OutsideMappingPort
}
s.logger.Debug("port mapping passed")
} else {
s.logger.Warningf("port mapping fail, %v", err)
}
return nil
}