]> Sergey Matveev's repositories - btrtrc.git/blob - portfwd.go
Tidy up UPnP logging
[btrtrc.git] / portfwd.go
1 package torrent
2
3 import (
4         "time"
5
6         "github.com/anacrolix/log"
7         "github.com/anacrolix/upnp"
8 )
9
10 func (cl *Client) addPortMapping(d upnp.Device, proto upnp.Protocol, internalPort int) {
11         externalPort, err := d.AddPortMapping(proto, internalPort, internalPort, "anacrolix/torrent", 0)
12         if err != nil {
13                 cl.logger.WithValues(log.Warning).Printf("error adding %s port mapping: %s", proto, err)
14         } else if externalPort != internalPort {
15                 cl.logger.WithValues(log.Warning).Printf("external port %d does not match internal port %d in port mapping", externalPort, internalPort)
16         } else {
17                 cl.logger.WithValues(log.Info).Printf("forwarded external %s port %d", proto, externalPort)
18         }
19 }
20
21 func (cl *Client) forwardPort() {
22         cl.lock()
23         defer cl.unlock()
24         if cl.config.NoDefaultPortForwarding {
25                 return
26         }
27         cl.unlock()
28         ds := upnp.Discover(0, 2*time.Second, cl.logger.WithValues("upnp-discover"))
29         cl.lock()
30         cl.logger.Printf("discovered %d upnp devices", len(ds))
31         port := cl.incomingPeerPort()
32         cl.unlock()
33         for _, d := range ds {
34                 go cl.addPortMapping(d, upnp.TCP, port)
35                 go cl.addPortMapping(d, upnp.UDP, port)
36         }
37         cl.lock()
38 }