-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathhost.go
407 lines (353 loc) · 11.9 KB
/
host.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
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
400
401
402
403
404
405
406
407
package main
import (
"context"
"fmt"
"sort"
"strconv"
"sync"
"time"
"github.com/libp2p/go-libp2p"
"github.com/libp2p/go-libp2p-core/crypto"
"github.com/libp2p/go-libp2p-core/host"
"github.com/libp2p/go-libp2p-core/network"
"github.com/libp2p/go-libp2p-core/peer"
kaddht "github.com/libp2p/go-libp2p-kad-dht"
"github.com/libp2p/go-libp2p/p2p/protocol/holepunch"
"github.com/multiformats/go-multiaddr"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/dennis-tra/punchr/pkg/pb"
"github.com/dennis-tra/punchr/pkg/util"
)
var (
CommunicationTimeout = 15 * time.Second
RetryCount = 3
)
// Host holds information of the honeypot libp2p host.
type Host struct {
host.Host
holePunchEventsPeers sync.Map
streamOpenPeers sync.Map
}
func InitHost(ctx context.Context, privKey crypto.PrivKey) (*Host, error) {
log.Info("Starting libp2p host...")
h := &Host{
holePunchEventsPeers: sync.Map{},
streamOpenPeers: sync.Map{},
}
// Configure new libp2p host
libp2pHost, err := libp2p.New(
libp2p.Identity(privKey),
libp2p.UserAgent("punchr/go-client/0.1.0"),
libp2p.ListenAddrStrings("/ip4/0.0.0.0/tcp/0"),
libp2p.ListenAddrStrings("/ip4/0.0.0.0/udp/0/quic"),
libp2p.ListenAddrStrings("/ip6/::/tcp/0"),
libp2p.ListenAddrStrings("/ip6/::/udp/0/quic"),
libp2p.EnableHolePunching(holepunch.WithTracer(h)),
)
if err != nil {
return nil, errors.Wrap(err, "new libp2p host")
}
h.Host = libp2pHost
libp2pHost.Network().Notify(h)
return h, nil
}
func (h *Host) logEntry(remoteID peer.ID) *log.Entry {
return log.WithFields(log.Fields{
"remoteID": util.FmtPeerID(remoteID),
"hostID": util.FmtPeerID(h.ID()),
})
}
// Bootstrap connects this host to bootstrap peers.
func (h *Host) Bootstrap(ctx context.Context) error {
for _, bp := range kaddht.GetDefaultBootstrapPeerAddrInfos() {
log.WithField("remoteID", util.FmtPeerID(bp.ID)).Info("Connecting to bootstrap peer...")
if err := h.Connect(ctx, bp); err != nil {
return errors.Wrap(err, "connecting to bootstrap peer")
}
}
return nil
}
// WaitForPublicAddr blocks execution until the host has identified its public address.
// As we currently don't have an event like this, just check our observed addresses
// regularly (exponential backoff starting at 250 ms, capped at 5s).
// TODO: There should be an event here that fires when identify discovers a new address
func (h *Host) WaitForPublicAddr(ctx context.Context) error {
logEntry := log.WithField("hostID", util.FmtPeerID(h.ID()))
logEntry.Infoln("Waiting for public address...")
timeout := time.NewTimer(CommunicationTimeout)
duration := 250 * time.Millisecond
const maxDuration = 5 * time.Second
t := time.NewTimer(duration)
defer t.Stop()
for {
if util.ContainsPublicAddr(h.Host.Addrs()) {
logEntry.Debug("Found >= 1 public addresses!")
return nil
}
select {
case <-ctx.Done():
return ctx.Err()
case <-t.C:
duration *= 2
if duration > maxDuration {
duration = maxDuration
}
t.Reset(duration)
case <-timeout.C:
return fmt.Errorf("timeout wait for public addrs")
}
}
}
// GetAgentVersion pulls the agent version from the peer store. Returns nil if no information is available.
func (h *Host) GetAgentVersion(pid peer.ID) *string {
if value, err := h.Peerstore().Get(pid, "AgentVersion"); err == nil {
av := value.(string)
return &av
} else {
return nil
}
}
// GetProtocols pulls the supported protocols of a peer from the peer store. Returns nil if no information is available.
func (h *Host) GetProtocols(pid peer.ID) []string {
protocols, err := h.Peerstore().GetProtocols(pid)
if err != nil {
log.WithError(err).Warnln("Could not get protocols from peerstore")
return nil
}
sort.Strings(protocols)
return protocols
}
func (h *Host) Close() error {
h.Host.Network().StopNotify(h)
return h.Host.Close()
}
func (h *Host) HolePunch(ctx context.Context, addrInfo peer.AddrInfo) *HolePunchState {
// we received a new peer to hole punch -> log its information
h.logAddrInfo(addrInfo)
// sanity operation -> clean up all resources before and after
h.prunePeer(addrInfo.ID)
defer h.prunePeer(addrInfo.ID)
// register for tracer events for this particular peer
evtChan := h.RegisterPeerToTrace(addrInfo.ID)
defer h.UnregisterPeerToTrace(addrInfo.ID)
// initialize a new hole punch state
hpState := NewHolePunchState(h.ID(), addrInfo.ID, addrInfo.Addrs)
defer func() { hpState.EndedAt = time.Now() }()
// Track open connections after the hole punch
defer func() {
for _, conn := range h.Network().ConnsToPeer(addrInfo.ID) {
hpState.OpenMaddrs = append(hpState.OpenMaddrs, conn.RemoteMultiaddr())
}
hpState.HasDirectConns = h.hasDirectConnToPeer(addrInfo.ID)
}()
// connect to the remote peer via relay
hpState.ConnectStartedAt = time.Now()
if err := h.Connect(ctx, addrInfo); err != nil {
h.logEntry(addrInfo.ID).WithError(err).Warnln("Error connecting to remote peer")
hpState.ConnectEndedAt = time.Now()
hpState.Error = err.Error()
hpState.Outcome = pb.HolePunchOutcome_HOLE_PUNCH_OUTCOME_NO_CONNECTION
return hpState
}
hpState.ConnectEndedAt = time.Now()
h.logEntry(addrInfo.ID).Infoln("Connected!")
// we were able to connect to the remote peer.
for i := 0; i < RetryCount; i++ {
// wait for the DCUtR stream to be opened
select {
case <-h.WaitForDCUtRStream(addrInfo.ID):
// pass
case <-time.After(CommunicationTimeout):
// Stream was not opened in time by the remote.
hpState.Outcome = pb.HolePunchOutcome_HOLE_PUNCH_OUTCOME_NO_STREAM
hpState.Error = "/libp2p/dcutr stream was not opened after " + CommunicationTimeout.String()
return hpState
case <-ctx.Done():
hpState.Outcome = pb.HolePunchOutcome_HOLE_PUNCH_OUTCOME_CANCELLED
hpState.Error = ctx.Err().Error()
return hpState
}
// stream was opened! Now, wait for the first hole punch event.
hpa := hpState.TrackHolePunch(ctx, addrInfo.ID, evtChan)
hpState.HolePunchAttempts = append(hpState.HolePunchAttempts, &hpa)
switch hpa.Outcome {
case pb.HolePunchAttemptOutcome_HOLE_PUNCH_ATTEMPT_OUTCOME_PROTOCOL_ERROR:
hpState.Outcome = pb.HolePunchOutcome_HOLE_PUNCH_OUTCOME_FAILED
hpState.Error = hpa.Error
return hpState
case pb.HolePunchAttemptOutcome_HOLE_PUNCH_ATTEMPT_OUTCOME_DIRECT_DIAL:
hpState.Outcome = pb.HolePunchOutcome_HOLE_PUNCH_OUTCOME_SUCCESS
return hpState
case pb.HolePunchAttemptOutcome_HOLE_PUNCH_ATTEMPT_OUTCOME_UNKNOWN:
hpState.Outcome = pb.HolePunchOutcome_HOLE_PUNCH_OUTCOME_UNKNOWN
hpState.Error = "unknown hole punch attempt outcome"
return hpState
case pb.HolePunchAttemptOutcome_HOLE_PUNCH_ATTEMPT_OUTCOME_CANCELLED:
hpState.Outcome = pb.HolePunchOutcome_HOLE_PUNCH_OUTCOME_CANCELLED
hpState.Error = hpa.Error
return hpState
case pb.HolePunchAttemptOutcome_HOLE_PUNCH_ATTEMPT_OUTCOME_TIMEOUT:
hpState.Outcome = pb.HolePunchOutcome_HOLE_PUNCH_OUTCOME_FAILED
hpState.Error = hpa.Error
return hpState
case pb.HolePunchAttemptOutcome_HOLE_PUNCH_ATTEMPT_OUTCOME_SUCCESS:
hpState.Outcome = pb.HolePunchOutcome_HOLE_PUNCH_OUTCOME_SUCCESS
return hpState
}
}
hpState.Outcome = pb.HolePunchOutcome_HOLE_PUNCH_OUTCOME_FAILED
hpState.Error = fmt.Sprintf("none of the %d attempts succeeded", RetryCount)
return hpState
}
func (hps HolePunchState) TrackHolePunch(ctx context.Context, remoteID peer.ID, evtChan <-chan *holepunch.Event) HolePunchAttempt {
hps.logEntry(remoteID).Infoln("Waiting for hole punch events...")
hpa := &HolePunchAttempt{
HostID: hps.HostID,
RemoteID: remoteID,
OpenedAt: time.Now(),
}
for {
select {
case evt := <-evtChan:
switch event := evt.Evt.(type) {
case *holepunch.StartHolePunchEvt:
hpa.handleStartHolePunchEvt(evt, event)
case *holepunch.EndHolePunchEvt:
hpa.handleEndHolePunchEvt(evt, event)
return *hpa
case *holepunch.HolePunchAttemptEvt:
hpa.handleHolePunchAttemptEvt(event)
case *holepunch.ProtocolErrorEvt:
hpa.handleProtocolErrorEvt(evt, event)
return *hpa
case *holepunch.DirectDialEvt:
hpa.handleDirectDialEvt(evt, event)
if event.Success {
return *hpa
}
default:
panic(fmt.Sprintf("unexpected event %T", evt.Evt))
}
case <-time.After(CommunicationTimeout):
hpa.handleHolePunchTimeout()
return *hpa
case <-ctx.Done():
hpa.handleHolePunchCancelled(ctx.Err())
return *hpa
}
}
}
func (h *Host) WaitForDCUtRStream(pid peer.ID) <-chan struct{} {
evtChan := make(chan struct{})
h.streamOpenPeers.Store(pid, evtChan)
// Exit early if the DCUtR stream is already open
for _, conn := range h.Network().ConnsToPeer(pid) {
for _, stream := range conn.GetStreams() {
if stream.Protocol() == holepunch.Protocol {
// If not found, it was already closed by the open stream handler
if _, found := h.streamOpenPeers.LoadAndDelete(pid); !found {
return evtChan
}
close(evtChan)
return evtChan
}
}
}
h.logEntry(pid).Infoln("Waiting for /libp2p/dcutr stream...")
return evtChan
}
func (h *Host) RegisterPeerToTrace(pid peer.ID) <-chan *holepunch.Event {
evtChan := make(chan *holepunch.Event, 3) // Start, attempt, end -> so that we get the events in this order!
h.holePunchEventsPeers.Store(pid, evtChan)
return evtChan
}
func (h *Host) UnregisterPeerToTrace(pid peer.ID) {
val, found := h.holePunchEventsPeers.LoadAndDelete(pid)
if !found {
return
}
evtChan := val.(chan *holepunch.Event)
// Drain channel
for {
select {
case evt := <-evtChan:
h.logEntry(pid).WithField("evtType", evt.Type).Infoln("Draining event channel")
default:
close(evtChan)
return
}
}
}
// logAddrInfo logs address information about the given peer
func (h *Host) logAddrInfo(addrInfo peer.AddrInfo) {
h.logEntry(addrInfo.ID).WithField("openConns", len(h.Network().ConnsToPeer(addrInfo.ID))).Infoln("Connecting to remote peer...")
for i, maddr := range addrInfo.Addrs {
log.Infoln(" ["+strconv.Itoa(i)+"]", maddr.String())
}
}
// hasDirectConnToPeer returns true if the libp2p host has a direct (non-relay) connection to the given peer.
func (h *Host) hasDirectConnToPeer(pid peer.ID) bool {
for _, conn := range h.Network().ConnsToPeer(pid) {
if !util.IsRelayedMaddr(conn.RemoteMultiaddr()) {
return true
}
}
return false
}
// prunePeer closes all connections to the given peer and removes all information about it from the peer store.
func (h *Host) prunePeer(pid peer.ID) {
if err := h.Network().ClosePeer(pid); err != nil {
h.logEntry(pid).WithError(err).Warnln("Error closing connection")
}
h.Peerstore().RemovePeer(pid)
h.Peerstore().ClearAddrs(pid)
}
// Trace is called during the hole punching process
func (h *Host) Trace(evt *holepunch.Event) {
val, found := h.holePunchEventsPeers.Load(evt.Remote)
if !found {
h.logEntry(evt.Remote).Infoln("Tracer event for untracked peer")
return
}
val.(chan *holepunch.Event) <- evt
}
func (h *Host) Listen(network.Network, multiaddr.Multiaddr) {}
func (h *Host) ListenClose(network.Network, multiaddr.Multiaddr) {}
func (h *Host) Connected(network.Network, network.Conn) {}
func (h *Host) Disconnected(network.Network, network.Conn) {}
func (h *Host) ClosedStream(_ network.Network, stream network.Stream) {
if stream.Protocol() != holepunch.Protocol {
return
}
h.logEntry(stream.Conn().RemotePeer()).Debugln("/libp2p/dcutr stream closed!")
}
func (h *Host) OpenedStream(_ network.Network, stream network.Stream) {
// The following is a hack. `stream` does not have the `Protocol` field set yet. So we just check
// every 5 ms for a total of 15 s.
go func() {
timeout := time.After(CommunicationTimeout)
timer := time.NewTimer(0)
for {
select {
case <-timeout:
return
case <-timer.C:
}
if stream.Protocol() == "" {
timer.Reset(5 * time.Millisecond)
continue
}
if stream.Protocol() != holepunch.Protocol {
return
}
break
}
val, found := h.streamOpenPeers.LoadAndDelete(stream.Conn().RemotePeer())
if !found {
return
}
h.logEntry(stream.Conn().RemotePeer()).Debugln("/libp2p/dcutr stream opened!")
close(val.(chan struct{}))
}()
}