2018-01-25 10:14:20 +08:00
|
|
|
package torrent
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
flog "github.com/anacrolix/log"
|
2018-06-19 20:49:20 +08:00
|
|
|
"github.com/elgatito/upnp"
|
2018-01-25 10:14:20 +08:00
|
|
|
)
|
|
|
|
|
2018-06-19 20:49:20 +08:00
|
|
|
func addPortMapping(d upnp.Device, proto upnp.Protocol, internalPort int, debug bool) {
|
2018-01-25 10:14:20 +08:00
|
|
|
externalPort, err := d.AddPortMapping(proto, internalPort, internalPort, "anacrolix/torrent", 0)
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("error adding %s port mapping: %s", proto, err)
|
|
|
|
} else if externalPort != internalPort {
|
|
|
|
log.Printf("external port %d does not match internal port %d in port mapping", externalPort, internalPort)
|
|
|
|
} else if debug {
|
|
|
|
log.Printf("forwarded external %s port %d", proto, externalPort)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
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()
|
2018-01-25 10:14:20 +08:00
|
|
|
ds := upnp.Discover(0, 2*time.Second)
|
2018-07-25 11:41:50 +08:00
|
|
|
cl.lock()
|
2018-01-29 15:19:53 +08:00
|
|
|
flog.Default.Handle(flog.Fmsg("discovered %d upnp devices", len(ds)))
|
2018-01-25 10:14:20 +08:00
|
|
|
port := cl.incomingPeerPort()
|
2018-07-25 11:41:50 +08:00
|
|
|
cl.unlock()
|
2018-01-25 10:14:20 +08:00
|
|
|
for _, d := range ds {
|
2018-06-19 20:49:20 +08:00
|
|
|
go addPortMapping(d, upnp.TCP, port, cl.config.Debug)
|
|
|
|
go addPortMapping(d, upnp.UDP, port, cl.config.Debug)
|
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
|
|
|
}
|