FedP2P/portfwd.go

46 lines
1.2 KiB
Go
Raw Permalink Normal View History

package torrent
import (
"fmt"
"time"
2019-08-21 18:44:12 +08:00
"github.com/anacrolix/log"
2019-08-22 11:59:04 +08:00
"github.com/anacrolix/upnp"
)
const UpnpDiscoverLogTag = "upnp-discover"
2019-12-16 10:22:24 +08:00
func (cl *Client) addPortMapping(d upnp.Device, proto upnp.Protocol, internalPort int, upnpID string) {
logger := cl.logger.WithContextText(fmt.Sprintf("UPnP device at %v: mapping internal %v port %v", d.GetLocalIPAddress(), proto, internalPort))
2019-12-16 10:22:24 +08:00
externalPort, err := d.AddPortMapping(proto, internalPort, internalPort, upnpID, 0)
if err != nil {
logger.WithDefaultLevel(log.Warning).Printf("error: %v", err)
return
}
level := log.Info
if externalPort != internalPort {
level = log.Warning
}
logger.WithDefaultLevel(level).Printf("success: external port %v", externalPort)
}
func (cl *Client) forwardPort() {
2018-07-25 11:41:50 +08:00
cl.lock()
defer cl.unlock()
if cl.config.NoDefaultPortForwarding {
return
}
2018-07-25 11:41:50 +08:00
cl.unlock()
ds := upnp.Discover(0, 2*time.Second, cl.logger.WithValues(UpnpDiscoverLogTag))
2018-07-25 11:41:50 +08:00
cl.lock()
cl.logger.WithDefaultLevel(log.Debug).Printf("discovered %d upnp devices", len(ds))
port := cl.incomingPeerPort()
2019-12-16 10:22:24 +08:00
id := cl.config.UpnpID
2018-07-25 11:41:50 +08:00
cl.unlock()
for _, d := range ds {
2019-12-16 10:22:24 +08:00
go cl.addPortMapping(d, upnp.TCP, port, id)
go cl.addPortMapping(d, upnp.UDP, port, id)
}
2018-07-25 11:41:50 +08:00
cl.lock()
}