2018-01-25 10:14:20 +08:00
|
|
|
package torrent
|
|
|
|
|
|
|
|
import (
|
2021-05-04 10:39:52 +08:00
|
|
|
"fmt"
|
2018-01-25 10:14:20 +08:00
|
|
|
"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"
|
2018-01-25 10:14:20 +08:00
|
|
|
)
|
|
|
|
|
2021-05-04 10:39:52 +08:00
|
|
|
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) {
|
2021-05-04 10:39:52 +08:00
|
|
|
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)
|
2018-01-25 10:14:20 +08:00
|
|
|
if err != nil {
|
2021-05-04 10:39:52 +08:00
|
|
|
logger.WithDefaultLevel(log.Warning).Printf("error: %v", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
level := log.Info
|
|
|
|
if externalPort != internalPort {
|
|
|
|
level = log.Warning
|
2018-01-25 10:14:20 +08:00
|
|
|
}
|
2021-05-04 10:39:52 +08:00
|
|
|
logger.WithDefaultLevel(level).Printf("success: external port %v", externalPort)
|
2018-01-25 10:14:20 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (cl *Client) forwardPort() {
|
2018-07-25 11:41:50 +08:00
|
|
|
cl.lock()
|
|
|
|
defer cl.unlock()
|
2018-01-25 10:14:20 +08:00
|
|
|
if cl.config.NoDefaultPortForwarding {
|
|
|
|
return
|
|
|
|
}
|
2018-07-25 11:41:50 +08:00
|
|
|
cl.unlock()
|
2021-05-04 10:39:52 +08:00
|
|
|
ds := upnp.Discover(0, 2*time.Second, cl.logger.WithValues(UpnpDiscoverLogTag))
|
2018-07-25 11:41:50 +08:00
|
|
|
cl.lock()
|
2021-05-04 10:39:52 +08:00
|
|
|
cl.logger.WithDefaultLevel(log.Debug).Printf("discovered %d upnp devices", len(ds))
|
2018-01-25 10:14:20 +08:00
|
|
|
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()
|
2018-01-25 10:14:20 +08:00
|
|
|
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-01-25 10:14:20 +08:00
|
|
|
}
|
2018-07-25 11:41:50 +08:00
|
|
|
cl.lock()
|
2018-01-25 10:14:20 +08:00
|
|
|
}
|