]> Sergey Matveev's repositories - btrtrc.git/blob - portfwd.go
Update anacrolix/log
[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, upnpID string) {
11         externalPort, err := d.AddPortMapping(proto, internalPort, internalPort, upnpID, 0)
12         if err != nil {
13                 cl.logger.WithDefaultLevel(log.Warning).Printf("error adding %s port mapping: %s", proto, err)
14         } else if externalPort != internalPort {
15                 cl.logger.WithDefaultLevel(log.Warning).Printf("external port %d does not match internal port %d in port mapping", externalPort, internalPort)
16         } else {
17                 cl.logger.WithDefaultLevel(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         id := cl.config.UpnpID
33         cl.unlock()
34         for _, d := range ds {
35                 go cl.addPortMapping(d, upnp.TCP, port, id)
36                 go cl.addPortMapping(d, upnp.UDP, port, id)
37         }
38         cl.lock()
39 }