nat.go 5.19 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 124 125 126 127 128 129 130 131 132 133

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

	Notifier
}

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()
}

// NewMapping attemps to construct a mapping on protocol and internal port
// 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
134
func (nat *NAT) NewMapping(protocol string, port int) (Mapping, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
135 136 137 138
	if nat == nil {
		return nil, fmt.Errorf("no nat available")
	}

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

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
159 160 161 162 163 164 165 166 167 168 169 170 171 172
	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()
173

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

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

Steven Allen's avatar
Steven Allen committed
185
	if err != nil || newport == 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
186 187
		m.setExternalPort(0) // clear mapping
		// TODO: log.Event
188
		log.Warningf("failed to establish port mapping: %s", err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
189 190 191 192 193 194 195 196 197 198
		nat.Notifier.notifyAll(func(n Notifiee) {
			n.MappingFailed(nat, m, oldport, err)
		})

		// 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
199
	log.Debugf("NAT Mapping: %s --> %s (%s)", m.ExternalPort(), m.InternalPort(), m.Protocol())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
200 201 202 203 204 205 206 207 208 209 210
	if oldport != 0 && newport != oldport {
		log.Debugf("failed to renew same port mapping: ch %d -> %d", oldport, newport)
		nat.Notifier.notifyAll(func(n Notifiee) {
			n.MappingChanged(nat, m, oldport, newport)
		})
	}

	nat.Notifier.notifyAll(func(n Notifiee) {
		n.MappingSuccess(nat, m)
	})
}