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

import (
4
	"errors"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
5
6
7
	"fmt"
	"strconv"
	"strings"
8
	"sync"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
9
10
	"time"

11
12
13
14
15
16
17
18
	ma "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
	manet "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr-net"

	nat "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/fd/go-nat"
	goprocess "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/goprocess"
	periodic "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/goprocess/periodic"
	eventlog "github.com/ipfs/go-ipfs/thirdparty/eventlog"
	notifier "github.com/ipfs/go-ipfs/thirdparty/notifier"
19
20
21
22
23
)

var (
	// ErrNoMapping signals no mapping exists for an address
	ErrNoMapping = errors.New("mapping not established")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
24
25
26
27
)

var log = eventlog.Logger("nat")

28
29
// MappingDuration is a default port mapping duration.
// Port mappings are renewed every (MappingDuration / 3)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
30
31
const MappingDuration = time.Second * 60

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

35
// DiscoverNAT looks for a NAT device in the network and
36
// returns an object that can manage port mappings.
37
func DiscoverNAT() *NAT {
38
	log.Error("DISCOVER NAT")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
39
40
41
	nat, err := nat.DiscoverGateway()
	if err != nil {
		log.Debug("DiscoverGateway error:", err)
42
		log.Error("DISCOVER GATEWAY ERROR: ", err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
43
44
45
46
47
48
49
50
		return nil
	}
	addr, err := nat.GetDeviceAddress()
	if err != nil {
		log.Debug("DiscoverGateway address error:", err)
	} else {
		log.Debug("DiscoverGateway address:", addr)
	}
51
	log.Error("NEW NAT!")
52
53
54
55
56
57
58
59
60
61
62
63
	return newNAT(nat)
}

// 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 {
	nat  nat.NAT
	proc goprocess.Process // manages nat mappings lifecycle

	mappingmu sync.RWMutex // guards mappings
64
	mappings  map[*mapping]struct{}
65
66
67
68
69
70

	Notifier
}

func newNAT(realNAT nat.NAT) *NAT {
	return &NAT{
71
72
73
		nat:      realNAT,
		proc:     goprocess.WithParent(goprocess.Background()),
		mappings: make(map[*mapping]struct{}),
74
75
76
77
78
79
80
81
	}
}

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

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

88
// Notifier is an object that assists NAT in notifying listeners.
89
// It is implemented using github.com/ipfs/go-ipfs/thirdparty/notifier
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
type Notifier struct {
	n notifier.Notifier
}

func (n *Notifier) notifyAll(notify func(n Notifiee)) {
	n.n.NotifyAll(func(n notifier.Notifiee) {
		notify(n.(Notifiee))
	})
}

// Notify signs up notifiee to listen to NAT events.
func (n *Notifier) Notify(notifiee Notifiee) {
	n.n.Notify(n)
}

// StopNotify stops signaling events to notifiee.
func (n *Notifier) StopNotify(notifiee Notifiee) {
	n.n.StopNotify(notifiee)
}

// Notifiee is an interface objects must implement to listen to NAT events.
type Notifiee interface {

	// Called every time a successful mapping happens
	// Warning: the port mapping may have changed. If that is the
	// case, both MappingSuccess and MappingChanged are called.
	MappingSuccess(nat *NAT, m Mapping)

	// Called when mapping a port succeeds, but the mapping is
	// with a different port than an earlier success.
	MappingChanged(nat *NAT, m Mapping, oldport int, newport int)

	// Called when a port mapping fails. NAT will continue attempting after
	// the next period. To stop trying, use: mapping.Close(). After this failure,
	// mapping.ExternalPort() will be zero, and nat.ExternalAddrs() will not
	// return the address for this mapping. With luck, the next attempt will
	// succeed, without the client needing to do anything.
	MappingFailed(nat *NAT, m Mapping, oldport int, err error)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
128
129
}

130
// Mapping represents a port mapping in a NAT.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
131
type Mapping interface {
132
133
134
135
136
	// NAT returns the NAT object this Mapping belongs to.
	NAT() *NAT

	// Protocol returns the protocol of this port mapping. This is either
	// "tcp" or "udp" as no other protocols are likely to be NAT-supported.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
137
	Protocol() string
138
139
140

	// InternalPort returns the internal device port. Mapping will continue to
	// try to map InternalPort() to an external facing port.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
141
	InternalPort() int
142
143
144

	// ExternalPort returns the external facing port. If the mapping is not
	// established, port will be 0
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
145
	ExternalPort() int
146
147
148
149
150
151
152

	// InternalAddr returns the internal address.
	InternalAddr() ma.Multiaddr

	// ExternalAddr returns the external facing address. If the mapping is not
	// established, addr will be nil, and and ErrNoMapping will be returned.
	ExternalAddr() (addr ma.Multiaddr, err error)
153
154
155

	// Close closes the port mapping
	Close() error
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
156
157
}

158
// keeps republishing
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
159
type mapping struct {
160
161
162
	sync.Mutex // guards all fields

	nat     *NAT
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
163
164
165
	proto   string
	intport int
	extport int
166
	intaddr ma.Multiaddr
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
167
	proc    goprocess.Process
168
169
170

	cached    ma.Multiaddr
	cacheTime time.Time
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
171
172
}

173
174
175
func (m *mapping) NAT() *NAT {
	m.Lock()
	defer m.Unlock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
176
177
	return m.nat
}
178

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
179
func (m *mapping) Protocol() string {
180
181
	m.Lock()
	defer m.Unlock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
182
183
	return m.proto
}
184

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
185
func (m *mapping) InternalPort() int {
186
187
	m.Lock()
	defer m.Unlock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
188
189
	return m.intport
}
190

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
191
func (m *mapping) ExternalPort() int {
192
193
	m.Lock()
	defer m.Unlock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
194
195
196
	return m.extport
}

197
198
199
200
201
202
203
204
205
206
207
208
209
func (m *mapping) setExternalPort(p int) {
	m.Lock()
	defer m.Unlock()
	m.extport = p
}

func (m *mapping) InternalAddr() ma.Multiaddr {
	m.Lock()
	defer m.Unlock()
	return m.intaddr
}

func (m *mapping) ExternalAddr() (ma.Multiaddr, error) {
210
211
212
213
	if time.Now().Sub(m.cacheTime) < CacheTime {
		return m.cached, nil
	}

214
215
216
217
218
	if m.ExternalPort() == 0 { // dont even try right now.
		return nil, ErrNoMapping
	}

	ip, err := m.nat.nat.GetExternalAddress()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
219
220
221
222
	if err != nil {
		return nil, err
	}

223
224
225
226
	ipmaddr, err := manet.FromIP(ip)
	if err != nil {
		return nil, fmt.Errorf("error parsing ip")
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
227

228
229
230
231
232
233
234
235
236
237
238
239
	// call m.ExternalPort again, as mapping may have changed under our feet. (tocttou)
	extport := m.ExternalPort()
	if extport == 0 {
		return nil, ErrNoMapping
	}

	tcp, err := ma.NewMultiaddr(fmt.Sprintf("/%s/%d", m.Protocol(), extport))
	if err != nil {
		return nil, err
	}

	maddr2 := ipmaddr.Encapsulate(tcp)
240
241
242

	m.cached = maddr2
	m.cacheTime = time.Now()
243
	return maddr2, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
244
245
246
247
248
249
}

func (m *mapping) Close() error {
	return m.proc.Close()
}

250
251
252
// Mappings returns a slice of all NAT mappings
func (nat *NAT) Mappings() []Mapping {
	nat.mappingmu.Lock()
253
254
255
	maps2 := make([]Mapping, 0, len(nat.mappings))
	for m := range nat.mappings {
		maps2 = append(maps2, m)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
256
	}
257
258
259
	nat.mappingmu.Unlock()
	return maps2
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
260

261
262
263
func (nat *NAT) addMapping(m *mapping) {
	// make mapping automatically close when nat is closed.
	nat.proc.AddChild(m.proc)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
264

265
	nat.mappingmu.Lock()
266
267
268
269
270
271
272
	nat.mappings[m] = struct{}{}
	nat.mappingmu.Unlock()
}

func (nat *NAT) rmMapping(m *mapping) {
	nat.mappingmu.Lock()
	delete(nat.mappings, m)
273
274
275
276
277
278
279
280
281
282
283
284
	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.
func (nat *NAT) NewMapping(maddr ma.Multiaddr) (Mapping, error) {
285
	log.Error("NEW MAPPING!")
286
287
	if nat == nil {
		return nil, fmt.Errorf("no nat available")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
	}

	network, addr, err := manet.DialArgs(maddr)
	if err != nil {
		return nil, fmt.Errorf("DialArgs failed on addr:", maddr.String())
	}

	switch network {
	case "tcp", "tcp4", "tcp6":
		network = "tcp"
	case "udp", "udp4", "udp6":
		network = "udp"
	default:
		return nil, fmt.Errorf("transport not supported by NAT: %s", network)
	}

304
305
	intports := strings.Split(addr, ":")[1]
	intport, err := strconv.Atoi(intports)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
306
307
308
309
	if err != nil {
		return nil, err
	}

310
311
312
313
314
315
	m := &mapping{
		nat:     nat,
		proto:   network,
		intport: intport,
		intaddr: maddr,
	}
316
317
318
	m.proc = goprocess.WithTeardown(func() error {
		nat.rmMapping(m)
		return nil
319
320
	})
	nat.addMapping(m)
321
322
323
324
325

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

326
327
328
329
330
331
332
	// 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) {
333
	log.Error("establishMapping!")
334
335
336
337
338
339
340
	oldport := m.ExternalPort()
	log.Debugf("Attempting port map: %s/%d", m.Protocol(), m.InternalPort())
	newport, err := nat.nat.AddPortMapping(m.Protocol(), m.InternalPort(), "http", MappingDuration)

	failure := func() {
		m.setExternalPort(0) // clear mapping
		// TODO: log.Event
341
		log.Debugf("failed to establish port mapping: %s", err)
342
343
344
345
346
347
348
349
350
351
352
		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.
	}

	if err != nil || newport == 0 {
		failure()
		return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
353
354
	}

355
356
	m.setExternalPort(newport)
	ext, err := m.ExternalAddr()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
357
	if err != nil {
358
359
360
		log.Debugf("NAT Mapping addr error: %s %s", m.InternalAddr(), err)
		failure()
		return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
361
362
	}

363
364
	log.Debugf("NAT Mapping: %s --> %s", m.InternalAddr(), ext)
	if oldport != 0 && newport != oldport {
365
		log.Debugf("failed to renew same port mapping: ch %d -> %d", oldport, newport)
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
		nat.Notifier.notifyAll(func(n Notifiee) {
			n.MappingChanged(nat, m, oldport, newport)
		})
	}

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

// PortMapAddrs attempts to open (and continue to keep open)
// port mappings for given addrs. This function blocks until
// all  addresses have been tried. This allows clients to
// retrieve results immediately after:
//
//   nat.PortMapAddrs(addrs)
//   mapped := nat.ExternalAddrs()
//
// Some 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.
func (nat *NAT) PortMapAddrs(addrs []ma.Multiaddr) {
	// spin off addr mappings independently.
	var wg sync.WaitGroup
	for _, addr := range addrs {
		// do all of them concurrently
		wg.Add(1)
		go func() {
			defer wg.Done()
			nat.NewMapping(addr)
		}()
	}
	wg.Wait()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
400
401
}

402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
// MappedAddrs returns address mappings NAT believes have been
// successfully established. Unsuccessful mappings are nil. This is:
//
// 		map[internalAddr]externalAddr
//
// This set of mappings _may not_ be correct, as NAT devices are finicky.
// Consider this with _best effort_ semantics.
func (nat *NAT) MappedAddrs() map[ma.Multiaddr]ma.Multiaddr {

	mappings := nat.Mappings()
	addrmap := make(map[ma.Multiaddr]ma.Multiaddr, len(mappings))

	for _, m := range mappings {
		i := m.InternalAddr()
		e, err := m.ExternalAddr()
		if err != nil {
			addrmap[i] = nil
		} else {
			addrmap[i] = e
		}
	}
	return addrmap
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
425

426
427
428
429
430
431
432
433
// ExternalAddrs returns a list of addresses that NAT believes have
// been successfully established. Unsuccessful mappings are omitted,
// so nat.ExternalAddrs() may return less addresses than nat.InternalAddrs().
// To see which addresses are mapped, use nat.MappedAddrs().
//
// This set of mappings _may not_ be correct, as NAT devices are finicky.
// Consider this with _best effort_ semantics.
func (nat *NAT) ExternalAddrs() []ma.Multiaddr {
434
	log.Error("EXTERNAL ADDRS")
435
436
437
438
439
440
	mappings := nat.Mappings()
	addrs := make([]ma.Multiaddr, 0, len(mappings))
	for _, m := range mappings {
		a, err := m.ExternalAddr()
		if err != nil {
			continue // this mapping not currently successful.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
441
		}
442
		addrs = append(addrs, a)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
443
	}
444
	return addrs
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
445
}