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