nat.go 4.93 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3
package nat

import (
Steven Allen's avatar
Steven Allen committed
4
	"context"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
5 6 7 8 9
	"errors"
	"fmt"
	"sync"
	"time"

Jeromy's avatar
Jeromy committed
10 11 12
	logging "github.com/ipfs/go-log"
	goprocess "github.com/jbenet/goprocess"
	periodic "github.com/jbenet/goprocess/periodic"
Steven Allen's avatar
Steven Allen committed
13
	nat "github.com/libp2p/go-nat"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
)

var (
	// ErrNoMapping signals no mapping exists for an address
	ErrNoMapping = errors.New("mapping not established")
)

var log = logging.Logger("nat")

// MappingDuration is a default port mapping duration.
// Port mappings are renewed every (MappingDuration / 3)
const MappingDuration = time.Second * 60

// CacheTime is the time a mapping will cache an external address for
const CacheTime = time.Second * 15

// DiscoverNAT looks for a NAT device in the network and
// returns an object that can manage port mappings.
Steven Allen's avatar
Steven Allen committed
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
func DiscoverNAT(ctx context.Context) (*NAT, error) {
	var (
		natInstance nat.NAT
		err         error
	)

	done := make(chan struct{})
	go func() {
		defer close(done)
		// This will abort in 10 seconds anyways.
		natInstance, err = nat.DiscoverGateway()
	}()

	select {
	case <-done:
	case <-ctx.Done():
		return nil, ctx.Err()
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
51
	if err != nil {
Steven Allen's avatar
Steven Allen committed
52
		return nil, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
53
	}
Steven Allen's avatar
Steven Allen committed
54 55 56

	// Log the device addr.
	addr, err := natInstance.GetDeviceAddress()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
57 58 59 60 61
	if err != nil {
		log.Debug("DiscoverGateway address error:", err)
	} else {
		log.Debug("DiscoverGateway address:", addr)
	}
Steven Allen's avatar
Steven Allen committed
62 63

	return newNAT(natInstance), nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
64 65 66 67 68 69 70
}

// NAT is an object that manages address port mappings in
// NATs (Network Address Translators). It is a long-running
// service that will periodically renew port mappings,
// and keep an up-to-date list of all the external addresses.
type NAT struct {
Jakub Sztandera's avatar
Jakub Sztandera committed
71 72
	natmu sync.Mutex
	nat   nat.NAT
Steven Allen's avatar
Steven Allen committed
73
	proc  goprocess.Process
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123

	mappingmu sync.RWMutex // guards mappings
	mappings  map[*mapping]struct{}
}

func newNAT(realNAT nat.NAT) *NAT {
	return &NAT{
		nat:      realNAT,
		proc:     goprocess.WithParent(goprocess.Background()),
		mappings: make(map[*mapping]struct{}),
	}
}

// Close shuts down all port mappings. NAT can no longer be used.
func (nat *NAT) Close() error {
	return nat.proc.Close()
}

// Process returns the nat's life-cycle manager, for making it listen
// to close signals.
func (nat *NAT) Process() goprocess.Process {
	return nat.proc
}

// Mappings returns a slice of all NAT mappings
func (nat *NAT) Mappings() []Mapping {
	nat.mappingmu.Lock()
	maps2 := make([]Mapping, 0, len(nat.mappings))
	for m := range nat.mappings {
		maps2 = append(maps2, m)
	}
	nat.mappingmu.Unlock()
	return maps2
}

func (nat *NAT) addMapping(m *mapping) {
	// make mapping automatically close when nat is closed.
	nat.proc.AddChild(m.proc)

	nat.mappingmu.Lock()
	nat.mappings[m] = struct{}{}
	nat.mappingmu.Unlock()
}

func (nat *NAT) rmMapping(m *mapping) {
	nat.mappingmu.Lock()
	delete(nat.mappings, m)
	nat.mappingmu.Unlock()
}

Arber Avdullahu's avatar
Arber Avdullahu committed
124
// NewMapping attempts to construct a mapping on protocol and internal port
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
125 126 127 128 129 130 131
// It will also periodically renew the mapping until the returned Mapping
// -- or its parent NAT -- is Closed.
//
// May not succeed, and mappings may change over time;
// NAT devices may not respect our port requests, and even lie.
// Clients should not store the mapped results, but rather always
// poll our object for the latest mappings.
Steven Allen's avatar
Steven Allen committed
132
func (nat *NAT) NewMapping(protocol string, port int) (Mapping, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
133 134 135 136
	if nat == nil {
		return nil, fmt.Errorf("no nat available")
	}

Steven Allen's avatar
Steven Allen committed
137 138
	switch protocol {
	case "tcp", "udp":
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
139
	default:
Steven Allen's avatar
Steven Allen committed
140
		return nil, fmt.Errorf("invalid protocol: %s", protocol)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
141 142 143
	}

	m := &mapping{
Steven Allen's avatar
Steven Allen committed
144
		intport: port,
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
145
		nat:     nat,
Steven Allen's avatar
Steven Allen committed
146
		proto:   protocol,
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
147
	}
Steven Allen's avatar
Steven Allen committed
148

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
149 150
	m.proc = goprocess.WithTeardown(func() error {
		nat.rmMapping(m)
Steven Allen's avatar
Steven Allen committed
151 152 153
		nat.natmu.Lock()
		defer nat.natmu.Unlock()
		nat.nat.DeletePortMapping(m.Protocol(), m.InternalPort())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
154 155
		return nil
	})
Steven Allen's avatar
Steven Allen committed
156

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
157 158 159 160 161 162 163 164 165 166 167 168 169 170
	nat.addMapping(m)

	m.proc.AddChild(periodic.Every(MappingDuration/3, func(worker goprocess.Process) {
		nat.establishMapping(m)
	}))

	// do it once synchronously, so first mapping is done right away, and before exiting,
	// allowing users -- in the optimistic case -- to use results right after.
	nat.establishMapping(m)
	return m, nil
}

func (nat *NAT) establishMapping(m *mapping) {
	oldport := m.ExternalPort()
171

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
172
	log.Debugf("Attempting port map: %s/%d", m.Protocol(), m.InternalPort())
173
	comment := "libp2p"
174

Jakub Sztandera's avatar
Jakub Sztandera committed
175
	nat.natmu.Lock()
176
	newport, err := nat.nat.AddPortMapping(m.Protocol(), m.InternalPort(), comment, MappingDuration)
177 178
	if err != nil {
		// Some hardware does not support mappings with timeout, so try that
179
		newport, err = nat.nat.AddPortMapping(m.Protocol(), m.InternalPort(), comment, 0)
180
	}
181
	nat.natmu.Unlock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
182

Steven Allen's avatar
Steven Allen committed
183
	if err != nil || newport == 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
184 185
		m.setExternalPort(0) // clear mapping
		// TODO: log.Event
Arber Avdullahu's avatar
Arber Avdullahu committed
186
		log.Warnf("failed to establish port mapping: %s", err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
187 188 189 190 191 192
		// we do not close if the mapping failed,
		// because it may work again next time.
		return
	}

	m.setExternalPort(newport)
Steven Allen's avatar
Steven Allen committed
193
	log.Debugf("NAT Mapping: %d --> %d (%s)", m.ExternalPort(), m.InternalPort(), m.Protocol())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
194 195 196 197
	if oldport != 0 && newport != oldport {
		log.Debugf("failed to renew same port mapping: ch %d -> %d", oldport, newport)
	}
}