handlers.go 11.9 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3
package dht

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

10 11 12 13 14
	"github.com/libp2p/go-libp2p-core/network"
	"github.com/libp2p/go-libp2p-core/peer"
	"github.com/libp2p/go-libp2p-core/peerstore"
	pstore "github.com/libp2p/go-libp2p-peerstore"

15
	proto "github.com/gogo/protobuf/proto"
16
	cid "github.com/ipfs/go-cid"
George Antoniadis's avatar
George Antoniadis committed
17
	ds "github.com/ipfs/go-datastore"
18
	u "github.com/ipfs/go-ipfs-util"
19
	pb "github.com/libp2p/go-libp2p-kad-dht/pb"
George Antoniadis's avatar
George Antoniadis committed
20
	recpb "github.com/libp2p/go-libp2p-record/pb"
21
	base32 "github.com/whyrusleeping/base32"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
22 23
)

Jeromy's avatar
Jeromy committed
24
// The number of closer peers to send on requests.
Jeromy's avatar
Jeromy committed
25
var CloserPeerCount = KValue
26

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
27
// dhthandler specifies the signature of functions that handle DHT messages.
28
type dhtHandler func(context.Context, peer.ID, *pb.Message) (*pb.Message, error)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
29

30
func (dht *IpfsDHT) handlerForMsgType(t pb.Message_MessageType) dhtHandler {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
31
	switch t {
32
	case pb.Message_GET_VALUE:
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
33
		return dht.handleGetValue
34
	case pb.Message_PUT_VALUE:
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
35
		return dht.handlePutValue
36
	case pb.Message_FIND_NODE:
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
37
		return dht.handleFindPeer
38
	case pb.Message_ADD_PROVIDER:
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
39
		return dht.handleAddProvider
40
	case pb.Message_GET_PROVIDERS:
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
41
		return dht.handleGetProviders
42
	case pb.Message_PING:
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
43 44 45 46 47 48
		return dht.handlePing
	default:
		return nil
	}
}

ForrestWeston's avatar
ForrestWeston committed
49
func (dht *IpfsDHT) handleGetValue(ctx context.Context, p peer.ID, pmes *pb.Message) (_ *pb.Message, err error) {
Matt Joiner's avatar
Matt Joiner committed
50 51 52 53
	ctx = logger.Start(ctx, "handleGetValue")
	logger.SetTag(ctx, "peer", p)
	defer func() { logger.FinishWithErr(ctx, err) }()
	logger.Debugf("%s handleGetValue for key: %s", dht.self, pmes.GetKey())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
54 55

	// setup response
56
	resp := pb.NewMessage(pmes.GetType(), pmes.GetKey(), pmes.GetClusterLevel())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
57

58
	// first, is there even a key?
59
	k := pmes.GetKey()
60
	if len(k) == 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
61
		return nil, errors.New("handleGetValue but no key was provided")
62
		// TODO: send back an error response? could be bad, but the other node's hanging.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
63 64
	}

65 66
	rec, err := dht.checkLocalDatastore(k)
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
67 68
		return nil, err
	}
69
	resp.Record = rec
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
70 71

	// Find closest peer on given cluster to desired key and reply with that info
72
	closer := dht.betterPeersToQuery(pmes, p, CloserPeerCount)
Jeromy's avatar
Jeromy committed
73
	if len(closer) > 0 {
74
		// TODO: pstore.PeerInfos should move to core (=> peerstore.AddrInfos).
Jeromy's avatar
Jeromy committed
75
		closerinfos := pstore.PeerInfos(dht.peerstore, closer)
76
		for _, pi := range closerinfos {
Matt Joiner's avatar
Matt Joiner committed
77
			logger.Debugf("handleGetValue returning closer peer: '%s'", pi.ID)
78
			if len(pi.Addrs) < 1 {
Matt Joiner's avatar
Matt Joiner committed
79
				logger.Warningf(`no addresses on peer being sent!
80 81 82
					[local:%s]
					[sending:%s]
					[remote:%s]`, dht.self, pi.ID, p)
Jeromy's avatar
Jeromy committed
83
			}
84
		}
85

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
86
		resp.CloserPeers = pb.PeerInfosToPBPeers(dht.host.Network(), closerinfos)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
87 88 89 90 91
	}

	return resp, nil
}

92
func (dht *IpfsDHT) checkLocalDatastore(k []byte) (*recpb.Record, error) {
Matt Joiner's avatar
Matt Joiner committed
93
	logger.Debugf("%s handleGetValue looking into ds", dht.self)
94
	dskey := convertToDsKey(k)
95
	buf, err := dht.datastore.Get(dskey)
Matt Joiner's avatar
Matt Joiner committed
96
	logger.Debugf("%s handleGetValue looking into ds GOT %v", dht.self, buf)
97 98 99 100 101 102 103 104 105 106 107

	if err == ds.ErrNotFound {
		return nil, nil
	}

	// if we got an unexpected error, bail.
	if err != nil {
		return nil, err
	}

	// if we have the value, send it back
Matt Joiner's avatar
Matt Joiner committed
108
	logger.Debugf("%s handleGetValue success!", dht.self)
109

George Antoniadis's avatar
George Antoniadis committed
110
	rec := new(recpb.Record)
111
	err = proto.Unmarshal(buf, rec)
112
	if err != nil {
Matt Joiner's avatar
Matt Joiner committed
113
		logger.Debug("failed to unmarshal DHT record from datastore")
114 115 116 117 118 119
		return nil, err
	}

	var recordIsBad bool
	recvtime, err := u.ParseRFC3339(rec.GetTimeReceived())
	if err != nil {
Matt Joiner's avatar
Matt Joiner committed
120
		logger.Info("either no receive time set on record, or it was invalid: ", err)
121 122 123
		recordIsBad = true
	}

124
	if time.Since(recvtime) > MaxRecordAge {
Matt Joiner's avatar
Matt Joiner committed
125
		logger.Debug("old record found, tossing.")
126 127 128
		recordIsBad = true
	}

129
	// NOTE: We do not verify the record here beyond checking these timestamps.
130 131 132 133 134 135
	// we put the burden of checking the records on the requester as checking a record
	// may be computationally expensive

	if recordIsBad {
		err := dht.datastore.Delete(dskey)
		if err != nil {
Matt Joiner's avatar
Matt Joiner committed
136
			logger.Error("Failed to delete bad record from datastore: ", err)
137 138 139 140 141 142 143 144
		}

		return nil, nil // can treat this as not having the record at all
	}

	return rec, nil
}

145 146
// Cleans the record (to avoid storing arbitrary data).
func cleanRecord(rec *recpb.Record) {
147
	rec.TimeReceived = ""
148 149
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
150
// Store a value in this peer local storage
ForrestWeston's avatar
ForrestWeston committed
151
func (dht *IpfsDHT) handlePutValue(ctx context.Context, p peer.ID, pmes *pb.Message) (_ *pb.Message, err error) {
Matt Joiner's avatar
Matt Joiner committed
152 153 154
	ctx = logger.Start(ctx, "handlePutValue")
	logger.SetTag(ctx, "peer", p)
	defer func() { logger.FinishWithErr(ctx, err) }()
ForrestWeston's avatar
ForrestWeston committed
155

156 157
	rec := pmes.GetRecord()
	if rec == nil {
Matt Joiner's avatar
Matt Joiner committed
158
		logger.Infof("Got nil record from: %s", p.Pretty())
159 160
		return nil, errors.New("nil record")
	}
161

162
	if !bytes.Equal(pmes.GetKey(), rec.GetKey()) {
163 164 165
		return nil, errors.New("put key doesn't match record key")
	}

166
	cleanRecord(rec)
167

168
	// Make sure the record is valid (not expired, valid signature etc)
169
	if err = dht.Validator.Validate(string(rec.GetKey()), rec.GetValue()); err != nil {
Matt Joiner's avatar
Matt Joiner committed
170
		logger.Warningf("Bad dht record in PUT from: %s. %s", p.Pretty(), err)
171 172 173
		return nil, err
	}

174 175
	dskey := convertToDsKey(rec.GetKey())

176 177 178 179 180 181 182 183 184 185
	// Make sure the new record is "better" than the record we have locally.
	// This prevents a record with for example a lower sequence number from
	// overwriting a record with a higher sequence number.
	existing, err := dht.getRecordFromDatastore(dskey)
	if err != nil {
		return nil, err
	}

	if existing != nil {
		recs := [][]byte{rec.GetValue(), existing.GetValue()}
186
		i, err := dht.Validator.Select(string(rec.GetKey()), recs)
187
		if err != nil {
Matt Joiner's avatar
Matt Joiner committed
188
			logger.Warningf("Bad dht record in PUT from %s: %s", p.Pretty(), err)
189 190 191
			return nil, err
		}
		if i != 0 {
Matt Joiner's avatar
Matt Joiner committed
192
			logger.Infof("DHT record in PUT from %s is older than existing record. Ignoring", p.Pretty())
193 194 195 196
			return nil, errors.New("old record")
		}
	}

197
	// record the time we receive every record
198
	rec.TimeReceived = u.FormatRFC3339(time.Now())
199 200

	data, err := proto.Marshal(rec)
201 202 203 204 205
	if err != nil {
		return nil, err
	}

	err = dht.datastore.Put(dskey, data)
Matt Joiner's avatar
Matt Joiner committed
206
	logger.Debugf("%s handlePutValue %v", dht.self, dskey)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
207
	return pmes, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
208 209
}

Steven Allen's avatar
Steven Allen committed
210 211
// returns nil, nil when either nothing is found or the value found doesn't properly validate.
// returns nil, some_error when there's a *datastore* error (i.e., something goes very wrong)
212
func (dht *IpfsDHT) getRecordFromDatastore(dskey ds.Key) (*recpb.Record, error) {
213
	buf, err := dht.datastore.Get(dskey)
214 215 216 217
	if err == ds.ErrNotFound {
		return nil, nil
	}
	if err != nil {
Matt Joiner's avatar
Matt Joiner committed
218
		logger.Errorf("Got error retrieving record with key %s from datastore: %s", dskey, err)
219 220 221
		return nil, err
	}
	rec := new(recpb.Record)
222
	err = proto.Unmarshal(buf, rec)
223 224
	if err != nil {
		// Bad data in datastore, log it but don't return an error, we'll just overwrite it
Matt Joiner's avatar
Matt Joiner committed
225
		logger.Errorf("Bad record data stored in datastore with key %s: could not unmarshal record", dskey)
226 227 228
		return nil, nil
	}

229
	err = dht.Validator.Validate(string(rec.GetKey()), rec.GetValue())
230 231 232
	if err != nil {
		// Invalid record in datastore, probably expired but don't return an error,
		// we'll just overwrite it
Matt Joiner's avatar
Matt Joiner committed
233
		logger.Debugf("Local record verify failed: %s (discarded)", err)
234 235 236 237 238 239
		return nil, nil
	}

	return rec, nil
}

240
func (dht *IpfsDHT) handlePing(_ context.Context, p peer.ID, pmes *pb.Message) (*pb.Message, error) {
Matt Joiner's avatar
Matt Joiner committed
241
	logger.Debugf("%s Responding to ping from %s!\n", dht.self, p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
242
	return pmes, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
243 244
}

245
func (dht *IpfsDHT) handleFindPeer(ctx context.Context, p peer.ID, pmes *pb.Message) (_ *pb.Message, _err error) {
Matt Joiner's avatar
Matt Joiner committed
246 247 248
	ctx = logger.Start(ctx, "handleFindPeer")
	defer func() { logger.FinishWithErr(ctx, _err) }()
	logger.SetTag(ctx, "peer", p)
249
	resp := pb.NewMessage(pmes.GetType(), nil, pmes.GetClusterLevel())
250
	var closest []peer.ID
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
251 252

	// if looking for self... special case where we send it on CloserPeers.
253 254
	targetPid := peer.ID(pmes.GetKey())
	if targetPid == dht.self {
255
		closest = []peer.ID{dht.self}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
256
	} else {
257
		closest = dht.betterPeersToQuery(pmes, p, CloserPeerCount)
258 259 260 261 262 263 264 265 266 267 268 269 270

		// Never tell a peer about itself.
		if targetPid != p {
			// If we're connected to the target peer, report their
			// peer info. This makes FindPeer work even if the
			// target peer isn't in our routing table.
			//
			// Alternatively, we could just check our peerstore.
			// However, we don't want to return out of date
			// information. We can change this in the future when we
			// add a progressive, asynchronous `SearchPeer` function
			// and improve peer routing in the host.
			switch dht.host.Network().Connectedness(targetPid) {
271
			case network.Connected, network.CanConnect:
272 273 274
				closest = append(closest, targetPid)
			}
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
275 276 277
	}

	if closest == nil {
Matt Joiner's avatar
Matt Joiner committed
278
		logger.Infof("%s handleFindPeer %s: could not find anything.", dht.self, p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
279 280 281
		return resp, nil
	}

282
	// TODO: pstore.PeerInfos should move to core (=> peerstore.AddrInfos).
Jeromy's avatar
Jeromy committed
283
	closestinfos := pstore.PeerInfos(dht.peerstore, closest)
Steven Allen's avatar
Steven Allen committed
284
	// possibly an over-allocation but this array is temporary anyways.
285
	withAddresses := make([]peer.AddrInfo, 0, len(closestinfos))
286 287 288
	for _, pi := range closestinfos {
		if len(pi.Addrs) > 0 {
			withAddresses = append(withAddresses, pi)
289
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
290 291
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
292
	resp.CloserPeers = pb.PeerInfosToPBPeers(dht.host.Network(), withAddresses)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
293 294 295
	return resp, nil
}

296
func (dht *IpfsDHT) handleGetProviders(ctx context.Context, p peer.ID, pmes *pb.Message) (_ *pb.Message, _err error) {
Matt Joiner's avatar
Matt Joiner committed
297 298 299
	ctx = logger.Start(ctx, "handleGetProviders")
	defer func() { logger.FinishWithErr(ctx, _err) }()
	logger.SetTag(ctx, "peer", p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
300

301
	resp := pb.NewMessage(pmes.GetType(), pmes.GetKey(), pmes.GetClusterLevel())
302 303 304 305
	c, err := cid.Cast([]byte(pmes.GetKey()))
	if err != nil {
		return nil, err
	}
Matt Joiner's avatar
Matt Joiner committed
306
	logger.SetTag(ctx, "key", c)
307 308

	// debug logging niceness.
309
	reqDesc := fmt.Sprintf("%s handleGetProviders(%s, %s): ", dht.self, p, c)
Matt Joiner's avatar
Matt Joiner committed
310 311
	logger.Debugf("%s begin", reqDesc)
	defer logger.Debugf("%s end", reqDesc)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
312 313

	// check if we have this value, to add ourselves as provider.
314
	has, err := dht.datastore.Has(convertToDsKey(c.Bytes()))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
315
	if err != nil && err != ds.ErrNotFound {
Matt Joiner's avatar
Matt Joiner committed
316
		logger.Debugf("unexpected datastore error: %v\n", err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
317 318 319 320
		has = false
	}

	// setup providers
321
	providers := dht.providers.GetProviders(ctx, c)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
322 323
	if has {
		providers = append(providers, dht.self)
Matt Joiner's avatar
Matt Joiner committed
324
		logger.Debugf("%s have the value. added self as provider", reqDesc)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
325 326
	}

327
	if len(providers) > 0 {
328
		// TODO: pstore.PeerInfos should move to core (=> peerstore.AddrInfos).
Jeromy's avatar
Jeromy committed
329
		infos := pstore.PeerInfos(dht.peerstore, providers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
330
		resp.ProviderPeers = pb.PeerInfosToPBPeers(dht.host.Network(), infos)
Matt Joiner's avatar
Matt Joiner committed
331
		logger.Debugf("%s have %d providers: %s", reqDesc, len(providers), infos)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
332 333 334
	}

	// Also send closer peers.
335
	closer := dht.betterPeersToQuery(pmes, p, CloserPeerCount)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
336
	if closer != nil {
337
		// TODO: pstore.PeerInfos should move to core (=> peerstore.AddrInfos).
Jeromy's avatar
Jeromy committed
338
		infos := pstore.PeerInfos(dht.peerstore, closer)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
339
		resp.CloserPeers = pb.PeerInfosToPBPeers(dht.host.Network(), infos)
Matt Joiner's avatar
Matt Joiner committed
340
		logger.Debugf("%s have %d closer peers: %s", reqDesc, len(closer), infos)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
341 342 343 344 345
	}

	return resp, nil
}

346
func (dht *IpfsDHT) handleAddProvider(ctx context.Context, p peer.ID, pmes *pb.Message) (_ *pb.Message, _err error) {
Matt Joiner's avatar
Matt Joiner committed
347 348 349
	ctx = logger.Start(ctx, "handleAddProvider")
	defer func() { logger.FinishWithErr(ctx, _err) }()
	logger.SetTag(ctx, "peer", p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
350

351 352 353 354
	c, err := cid.Cast([]byte(pmes.GetKey()))
	if err != nil {
		return nil, err
	}
Matt Joiner's avatar
Matt Joiner committed
355
	logger.SetTag(ctx, "key", c)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
356

Matt Joiner's avatar
Matt Joiner committed
357
	logger.Debugf("%s adding %s as a provider for '%s'\n", dht.self, p, c)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
358

359
	// add provider should use the address given in the message
360 361 362
	pinfos := pb.PBPeersToPeerInfos(pmes.GetProviderPeers())
	for _, pi := range pinfos {
		if pi.ID != p {
363 364
			// we should ignore this provider record! not from originator.
			// (we should sign them and check signature later...)
Matt Joiner's avatar
Matt Joiner committed
365
			logger.Debugf("handleAddProvider received provider %s from %s. Ignore.", pi.ID, p)
366 367
			continue
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
368

369
		if len(pi.Addrs) < 1 {
Matt Joiner's avatar
Matt Joiner committed
370
			logger.Debugf("%s got no valid addresses for provider %s. Ignore.", dht.self, p)
371 372
			continue
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
373

Matt Joiner's avatar
Matt Joiner committed
374
		logger.Debugf("received provider %s for %s (addrs: %s)", p, c, pi.Addrs)
375
		if pi.ID != dht.self { // don't add own addrs.
376
			// add the received addresses to our peerstore.
377
			dht.peerstore.AddAddrs(pi.ID, pi.Addrs, peerstore.ProviderAddrTTL)
378
		}
379
		dht.providers.AddProvider(ctx, c, p)
380 381
	}

Jeromy's avatar
Jeromy committed
382
	return nil, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
383
}
384

385 386
func convertToDsKey(s []byte) ds.Key {
	return ds.NewKey(base32.RawStdEncoding.EncodeToString(s))
387
}