FedP2P/portfwd.go

40 lines
1.1 KiB
Go
Raw Normal View History

package torrent
import (
"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"
)
2019-12-16 10:22:24 +08: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 {
2020-04-16 15:20:58 +08:00
cl.logger.WithDefaultLevel(log.Warning).Printf("error adding %s port mapping: %s", proto, err)
} else if externalPort != internalPort {
2020-04-16 15:20:58 +08:00
cl.logger.WithDefaultLevel(log.Warning).Printf("external port %d does not match internal port %d in port mapping", externalPort, internalPort)
2019-09-13 09:55:02 +08:00
} else {
2020-04-16 15:20:58 +08:00
cl.logger.WithDefaultLevel(log.Info).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()
if cl.config.NoDefaultPortForwarding {
return
}
2018-07-25 11:41:50 +08:00
cl.unlock()
2019-09-13 09:55:02 +08:00
ds := upnp.Discover(0, 2*time.Second, cl.logger.WithValues("upnp-discover"))
2018-07-25 11:41:50 +08:00
cl.lock()
2019-08-21 18:44:12 +08:00
cl.logger.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()
}