Debian Codegraph @

upnp.go

raw symbols SCIP
1 // Package upnp provides a simple and opinionated interface to UPnP-enabled
2 // routers, allowing users to forward ports and discover their external IP
3 // address. Specific quirks:
4 //
5 // - When attempting to discover UPnP-enabled routers on the network, only the
6 // first such router is returned. If you have multiple routers, this may cause
7 // some trouble. But why would you do that?
8 //
9 // - Forwarded ports are always symmetric, e.g. the router's port 9980 will be
10 // mapped to the client's port 9980. This will be unacceptable for some
11 // purposes, but too bad. Symmetric mappings are the desired behavior 99% of
12 // the time, and they save a function argument.
13 //
14 // - TCP and UDP protocols are forwarded together.
15 //
16 // - Ports are forwarded permanently. Some other implementations lease a port
17 // mapping for a set duration, and then renew it periodically. This is nice,
18 // because it means mappings won't stick around after they've served their
19 // purpose. Unfortunately, some routers only support permanent mappings, so this
20 // package has chosen to support the lowest common denominator. To un-forward a
21 // port, you must use the Clear function (or do it manually).
22 //
23 // Once you've discovered your router, you can retrieve its address by calling
24 // its Location method. This address can be supplied to Load to connect to the
25 // router directly, which is much faster than calling Discover.
26 package upnp
27
28 import (
29 "context"
30 "errors"
31 "net"
32 "net/url"
33 "time"
34
35 "github.com/NebulousLabs/fastrand"
36 "github.com/NebulousLabs/go-upnp/goupnp"
37 "github.com/NebulousLabs/go-upnp/goupnp/dcps/internetgateway1"
38 )
39
40 // An IGD provides an interface to the most commonly used functions of an
41 // Internet Gateway Device: discovering the external IP, and forwarding ports.
42 type IGD struct {
43 // This interface is satisfied by the internetgateway1.WANIPConnection1
44 // and internetgateway1.WANPPPConnection1 types.
45 client interface {
46 GetExternalIPAddress() (string, error)
47 AddPortMapping(string, uint16, string, uint16, string, bool, string, uint32) error
48 DeletePortMapping(string, uint16, string) error
49 GetServiceClient() *goupnp.ServiceClient
50 }
51 }
52
53 // ExternalIP returns the router's external IP.
54 func (d *IGD) ExternalIP() (string, error) {
55 return d.client.GetExternalIPAddress()
56 }
57
58 // Forward forwards the specified port, and adds its description to the
59 // router's port mapping table.
60 func (d *IGD) Forward(port uint16, desc string) error {
61 ip, err := d.getInternalIP()
62 if err != nil {
63 return err
64 }
65
66 err = d.client.AddPortMapping("", port, "TCP", port, ip, true, desc, 0)
67 if err != nil {
68 return err
69 }
70 return d.client.AddPortMapping("", port, "UDP", port, ip, true, desc, 0)
71 }
72
73 // Clear un-forwards a port, removing it from the router's port mapping table.
74 func (d *IGD) Clear(port uint16) error {
75 tcpErr := d.client.DeletePortMapping("", port, "TCP")
76 udpErr := d.client.DeletePortMapping("", port, "UDP")
77 // only return an error if both deletions failed
78 if tcpErr != nil && udpErr != nil {
79 return tcpErr
80 }
81 return nil
82 }
83
84 // Location returns the URL of the router, for future lookups (see Load).
85 func (d *IGD) Location() string {
86 return d.client.GetServiceClient().Location.String()
87 }
88
89 // getInternalIP returns the user's local IP.
90 func (d *IGD) getInternalIP() (string, error) {
91 host, _, _ := net.SplitHostPort(d.client.GetServiceClient().RootDevice.URLBase.Host)
92 devIP := net.ParseIP(host)
93 if devIP == nil {
94 return "", errors.New("could not determine router's internal IP")
95 }
96
97 ifaces, err := net.Interfaces()
98 if err != nil {
99 return "", err
100 }
101
102 for _, iface := range ifaces {
103 addrs, err := iface.Addrs()
104 if err != nil {
105 return "", err
106 }
107
108 for _, addr := range addrs {
109 if x, ok := addr.(*net.IPNet); ok && x.Contains(devIP) {
110 return x.IP.String(), nil
111 }
112 }
113 }
114
115 return "", errors.New("could not determine internal IP")
116 }
117
118 // Discover is deprecated; use DiscoverCtx instead.
119 func Discover() (*IGD, error) {
120 return DiscoverCtx(context.Background())
121 }
122
123 // DiscoverCtx scans the local network for routers and returns the first
124 // UPnP-enabled router it encounters. It will try up to 3 times to find a
125 // router, sleeping a random duration between each attempt. This is to
126 // mitigate a race condition with many callers attempting to discover
127 // simultaneously.
128 func DiscoverCtx(ctx context.Context) (*IGD, error) {
129 // TODO: if more than one client is found, only return those on the same
130 // subnet as the user?
131 maxTries := 3
132 sleepTime := time.Millisecond * time.Duration(fastrand.Intn(5000))
133 for try := 0; try < maxTries; try++ {
134 pppclients, _, _ := internetgateway1.NewWANPPPConnection1Clients(ctx)
135 if len(pppclients) > 0 {
136 return &IGD{pppclients[0]}, nil
137 }
138 ipclients, _, _ := internetgateway1.NewWANIPConnection1Clients(ctx)
139 if len(ipclients) > 0 {
140 return &IGD{ipclients[0]}, nil
141 }
142 select {
143 case <-ctx.Done():
144 return nil, context.Canceled
145 case <-time.After(sleepTime):
146 }
147 sleepTime *= 2
148 }
149 return nil, errors.New("no UPnP-enabled gateway found")
150 }
151
152 // Load connects to the router service specified by rawurl. This is much
153 // faster than Discover. Generally, Load should only be called with values
154 // returned by the IGD's Location method.
155 func Load(rawurl string) (*IGD, error) {
156 loc, err := url.Parse(rawurl)
157 if err != nil {
158 return nil, err
159 }
160 pppclients, _ := internetgateway1.NewWANPPPConnection1ClientsByURL(loc)
161 if len(pppclients) > 0 {
162 return &IGD{pppclients[0]}, nil
163 }
164 ipclients, _ := internetgateway1.NewWANIPConnection1ClientsByURL(loc)
165 if len(ipclients) > 0 {
166 return &IGD{ipclients[0]}, nil
167 }
168 return nil, errors.New("no UPnP-enabled gateway found at URL " + rawurl)
169 }