torrent/portfwd.go

40 lines
1.1 KiB
Go
Raw Normal View History

package torrent
import (
"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"
)
2019-12-16 02:22:24 +00:00
func (cl *Client) addPortMapping(d upnp.Device, proto upnp.Protocol, internalPort int, upnpID string) {
externalPort, err := d.AddPortMapping(proto, internalPort, internalPort, upnpID, 0)
if err != nil {
2019-09-13 01:55:02 +00:00
cl.logger.WithValues(log.Warning).Printf("error adding %s port mapping: %s", proto, err)
} else if externalPort != internalPort {
2019-09-13 01:55:02 +00:00
cl.logger.WithValues(log.Warning).Printf("external port %d does not match internal port %d in port mapping", externalPort, internalPort)
} else {
cl.logger.WithValues(log.Info).Printf("forwarded external %s port %d", proto, externalPort)
}
}
func (cl *Client) forwardPort() {
2018-07-25 03:41:50 +00:00
cl.lock()
defer cl.unlock()
if cl.config.NoDefaultPortForwarding {
return
}
2018-07-25 03:41:50 +00:00
cl.unlock()
2019-09-13 01:55:02 +00:00
ds := upnp.Discover(0, 2*time.Second, cl.logger.WithValues("upnp-discover"))
2018-07-25 03:41:50 +00:00
cl.lock()
2019-08-21 10:44:12 +00:00
cl.logger.Printf("discovered %d upnp devices", len(ds))
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()
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-07-25 03:41:50 +00:00
cl.lock()
}