github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/p2p/nat/hole_punching.go (about) 1 /* 2 * Copyright (C) 2021 The "MysteriumNetwork/node" Authors. 3 * 4 * This program is free software: you can redistribute it and/or modify 5 * it under the terms of the GNU General Public License as published by 6 * the Free Software Foundation, either version 3 of the License, or 7 * (at your option) any later version. 8 * 9 * This program is distributed in the hope that it will be useful, 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 * GNU General Public License for more details. 13 * 14 * You should have received a copy of the GNU General Public License 15 * along with this program. If not, see <http://www.gnu.org/licenses/>. 16 */ 17 18 package nat 19 20 import ( 21 "context" 22 "net" 23 24 "github.com/rs/zerolog/log" 25 26 "github.com/mysteriumnetwork/node/config" 27 "github.com/mysteriumnetwork/node/core/port" 28 "github.com/mysteriumnetwork/node/eventbus" 29 "github.com/mysteriumnetwork/node/nat/traversal" 30 ) 31 32 // StartPorts starts the process of serving connections for the provided ports. 33 type StartPorts func(ctx context.Context, peerIP string, peerPorts, localPorts []int) ([]*net.UDPConn, error) 34 35 type natHolePunchingPort struct { 36 pool *port.Pool 37 pinger traversal.NATPinger 38 } 39 40 // NewNATHolePunchingPortProvider creates new instance of the NAT hole punching port provider. 41 func NewNATHolePunchingPortProvider() PortProvider { 42 udpPortRange, err := port.ParseRange(config.GetString(config.FlagUDPListenPorts)) 43 if err != nil { 44 log.Warn().Err(err).Msg("Failed to parse UDP listen port range, using default value") 45 46 udpPortRange, err = port.ParseRange("10000:60000") 47 if err != nil { 48 panic(err) // This must never happen. 49 } 50 } 51 52 return &natHolePunchingPort{ 53 pool: port.NewFixedRangePool(udpPortRange), 54 pinger: traversal.NewPinger(traversal.DefaultPingConfig(), eventbus.New()), 55 } 56 } 57 58 func (hp *natHolePunchingPort) PreparePorts() (ports []int, release func(), start StartPorts, err error) { 59 poolPorts, err := hp.pool.AcquireMultiple(pingMaxPorts) 60 if err != nil { 61 return nil, nil, nil, err 62 } 63 64 for _, p := range poolPorts { 65 ports = append(ports, p.Num()) 66 } 67 68 return ports, func() {}, hp.Start, nil 69 } 70 71 func (hp *natHolePunchingPort) Start(ctx context.Context, peerIP string, peerPorts, localPorts []int) ([]*net.UDPConn, error) { 72 return hp.pinger.PingConsumerPeer(context.Background(), "remove this id", peerIP, localPorts, peerPorts, providerInitialTTL, requiredConnCount) 73 }