natmgr.go 6.94 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1
2
3
package basichost

import (
4
	"context"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
5
6
	"sync"

Jeromy's avatar
Jeromy committed
7
	goprocess "github.com/jbenet/goprocess"
8
	inat "github.com/libp2p/go-libp2p-nat"
Jeromy's avatar
Jeromy committed
9
	inet "github.com/libp2p/go-libp2p-net"
10
	lgbl "github.com/libp2p/go-libp2p-loggables"
Jeromy's avatar
Jeromy committed
11
	ma "github.com/multiformats/go-multiaddr"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
12
13
)

14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// A simple interface to manage NAT devices. 
type NATManager interface {

	// Get the NAT device managed by the NAT manager.
	NAT() *inat.NAT

	// Receive a notification when the NAT device is ready for use.
	Ready() <-chan struct{}

	// Close all resources associated with a NAT manager.
	Close() error

}

// Create a NAT manager.
func NewNATManager(net inet.Network) NATManager {
	return newNatManager(net)
}

// natManager takes care of adding + removing port mappings to the nat.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
34
// Initialized with the host if it has a NATPortMap option enabled.
35
36
// natManager receives signals from the network, and check on nat mappings:
//  * natManager listens to the network and adds or closes port mappings
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
37
//    as the network signals Listen() or ListenClose().
38
39
//  * closing the natManager closes the nat and its mappings.
type natManager struct {
40
	net   inet.Network
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
41
42
43
44
	natmu sync.RWMutex // guards nat (ready could obviate this mutex, but safety first.)
	nat   *inat.NAT

	ready chan struct{}     // closed once the nat is ready to process port mappings
45
	proc  goprocess.Process // natManager has a process + children. can be closed.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
46
47
}

48
49
func newNatManager(net inet.Network) *natManager {
	nmgr := &natManager{
50
		net:   net,
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
51
52
53
54
55
		ready: make(chan struct{}),
	}

	nmgr.proc = goprocess.WithTeardown(func() error {
		// on closing, unregister from network notifications.
56
		net.StopNotify((*nmgrNetNotifiee)(nmgr))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
57
58
59
60
61
62
63
64
		return nil
	})

	// discover the nat.
	nmgr.discoverNAT()
	return nmgr
}

65
// Close closes the natManager, closing the underlying nat
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
66
// and unregistering from network events.
67
func (nmgr *natManager) Close() error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
68
69
70
71
72
	return nmgr.proc.Close()
}

// Ready returns a channel which will be closed when the NAT has been found
// and is ready to be used, or the search process is done.
73
func (nmgr *natManager) Ready() <-chan struct{} {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
74
75
76
	return nmgr.ready
}

77
func (nmgr *natManager) discoverNAT() {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
78
79
80
81
82
83
84
85
86
87
88
89
90

	nmgr.proc.Go(func(worker goprocess.Process) {
		// inat.DiscoverNAT blocks until the nat is found or a timeout
		// is reached. we unfortunately cannot specify timeouts-- the
		// library we're using just blocks.
		//
		// Note: on early shutdown, there may be a case where we're trying
		// to close before DiscoverNAT() returns. Since we cant cancel it
		// (library) we can choose to (1) drop the result and return early,
		// or (2) wait until it times out to exit. For now we choose (2),
		// to avoid leaking resources in a non-obvious way. the only case
		// this affects is when the daemon is being started up and _immediately_
		// asked to close. other services are also starting up, so ok to wait.
Jeromy's avatar
Jeromy committed
91
92
93
94
95
96
		discoverdone := make(chan struct{})
		var nat *inat.NAT
		go func() {
			defer close(discoverdone)
			nat = inat.DiscoverNAT()
		}()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
97
98
99
100
101
102

		// by this point -- after finding the NAT -- we may have already
		// be closing. if so, just exit.
		select {
		case <-worker.Closing():
			return
Jeromy's avatar
Jeromy committed
103
104
105
106
		case <-discoverdone:
			if nat == nil { // no nat, or failed to get it.
				return
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
107
108
109
110
111
112
113
114
115
116
117
118
119
120
		}

		// wire up the nat to close when nmgr closes.
		// nmgr.proc is our parent, and waiting for us.
		nmgr.proc.AddChild(nat.Process())

		// set the nat.
		nmgr.natmu.Lock()
		nmgr.nat = nat
		nmgr.natmu.Unlock()

		// signal that we're ready to process nat mappings:
		close(nmgr.ready)

121
		// sign natManager up for network notifications
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
122
123
		// we need to sign up here to avoid missing some notifs
		// before the NAT has been found.
124
		nmgr.net.Notify((*nmgrNetNotifiee)(nmgr))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
125
126
127
128
129

		// if any interfaces were brought up while we were setting up
		// the nat, now is the time to setup port mappings for them.
		// we release ready, then grab them to avoid losing any. adding
		// a port mapping is idempotent, so its ok to add the same twice.
130
		addrs := nmgr.net.ListenAddresses()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
131
132
133
134
135
136
137
		for _, addr := range addrs {
			// we do it async because it's slow and we may want to close beforehand
			go addPortMapping(nmgr, addr)
		}
	})
}

138
// NAT returns the natManager's nat object. this may be nil, if
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
139
140
// (a) the search process is still ongoing, or (b) the search process
// found no nat. Clients must check whether the return value is nil.
141
func (nmgr *natManager) NAT() *inat.NAT {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
142
143
144
145
146
	nmgr.natmu.Lock()
	defer nmgr.natmu.Unlock()
	return nmgr.nat
}

147
func addPortMapping(nmgr *natManager, intaddr ma.Multiaddr) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
148
149
	nat := nmgr.NAT()
	if nat == nil {
150
		panic("natManager addPortMapping called without a nat.")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
	}

	// first, check if the port mapping already exists.
	for _, mapping := range nat.Mappings() {
		if mapping.InternalAddr().Equal(intaddr) {
			return // it exists! return.
		}
	}

	ctx := context.TODO()
	lm := make(lgbl.DeferredMap)
	lm["internalAddr"] = func() interface{} { return intaddr.String() }

	defer log.EventBegin(ctx, "natMgrAddPortMappingWait", lm).Done()

	select {
	case <-nmgr.proc.Closing():
		lm["outcome"] = "cancelled"
		return // no use.
	case <-nmgr.ready: // wait until it's ready.
	}

	// actually start the port map (sub-event because waiting may take a while)
	defer log.EventBegin(ctx, "natMgrAddPortMapping", lm).Done()

	// get the nat
	m, err := nat.NewMapping(intaddr)
	if err != nil {
		lm["outcome"] = "failure"
		lm["error"] = err
		return
	}

	extaddr, err := m.ExternalAddr()
	if err != nil {
		lm["outcome"] = "failure"
		lm["error"] = err
		return
	}

	lm["outcome"] = "success"
	lm["externalAddr"] = func() interface{} { return extaddr.String() }
	log.Infof("established nat port mapping: %s <--> %s", intaddr, extaddr)
}

196
func rmPortMapping(nmgr *natManager, intaddr ma.Multiaddr) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
197
198
	nat := nmgr.NAT()
	if nat == nil {
199
		panic("natManager rmPortMapping called without a nat.")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
200
201
202
203
204
205
206
207
208
209
210
211
212
213
	}

	// list the port mappings (it may be gone on it's own, so we need to
	// check this list, and not store it ourselves behind the scenes)

	// close mappings for this internal address.
	for _, mapping := range nat.Mappings() {
		if mapping.InternalAddr().Equal(intaddr) {
			mapping.Close()
		}
	}
}

// nmgrNetNotifiee implements the network notification listening part
214
// of the natManager. this is merely listening to Listen() and ListenClose()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
215
// events.
216
type nmgrNetNotifiee natManager
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
217

218
219
func (nn *nmgrNetNotifiee) natManager() *natManager {
	return (*natManager)(nn)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
}

func (nn *nmgrNetNotifiee) Listen(n inet.Network, addr ma.Multiaddr) {
	if nn.natManager().NAT() == nil {
		return // not ready or doesnt exist.
	}

	addPortMapping(nn.natManager(), addr)
}

func (nn *nmgrNetNotifiee) ListenClose(n inet.Network, addr ma.Multiaddr) {
	if nn.natManager().NAT() == nil {
		return // not ready or doesnt exist.
	}

	rmPortMapping(nn.natManager(), addr)
}

func (nn *nmgrNetNotifiee) Connected(inet.Network, inet.Conn)      {}
func (nn *nmgrNetNotifiee) Disconnected(inet.Network, inet.Conn)   {}
func (nn *nmgrNetNotifiee) OpenedStream(inet.Network, inet.Stream) {}
func (nn *nmgrNetNotifiee) ClosedStream(inet.Network, inet.Stream) {}