handlers.go 11.6 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
	proto "github.com/gogo/protobuf/proto"
11
	cid "github.com/ipfs/go-cid"
George Antoniadis's avatar
George Antoniadis committed
12
	ds "github.com/ipfs/go-datastore"
13
	u "github.com/ipfs/go-ipfs-util"
George Antoniadis's avatar
George Antoniadis committed
14
	pb "github.com/libp2p/go-libp2p-kad-dht/pb"
15
	lgbl "github.com/libp2p/go-libp2p-loggables"
16
	inet "github.com/libp2p/go-libp2p-net"
17 18
	peer "github.com/libp2p/go-libp2p-peer"
	pstore "github.com/libp2p/go-libp2p-peerstore"
George Antoniadis's avatar
George Antoniadis committed
19
	recpb "github.com/libp2p/go-libp2p-record/pb"
20
	base32 "github.com/whyrusleeping/base32"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
21 22
)

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

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

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

ForrestWeston's avatar
ForrestWeston committed
48 49 50 51 52 53 54 55
func (dht *IpfsDHT) handleGetValue(ctx context.Context, p peer.ID, pmes *pb.Message) (_ *pb.Message, err error) {
	eip := log.EventBegin(ctx, "handleGetValue", p)
	defer func() {
		if err != nil {
			eip.SetError(err)
		}
		eip.Done()
	}()
Jeromy's avatar
Jeromy committed
56
	log.Debugf("%s handleGetValue for key: %s", dht.self, pmes.GetKey())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
57 58

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

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

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

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

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

	return resp, nil
}

94
func (dht *IpfsDHT) checkLocalDatastore(k []byte) (*recpb.Record, error) {
95
	log.Debugf("%s handleGetValue looking into ds", dht.self)
96
	dskey := convertToDsKey(k)
97 98
	buf, err := dht.datastore.Get(dskey)
	log.Debugf("%s handleGetValue looking into ds GOT %v", dht.self, buf)
99 100 101 102 103 104 105 106 107 108 109 110 111

	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
	log.Debugf("%s handleGetValue success!", dht.self)

George Antoniadis's avatar
George Antoniadis committed
112
	rec := new(recpb.Record)
113
	err = proto.Unmarshal(buf, rec)
114
	if err != nil {
115
		log.Debug("failed to unmarshal DHT record from datastore")
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
		return nil, err
	}

	var recordIsBad bool
	recvtime, err := u.ParseRFC3339(rec.GetTimeReceived())
	if err != nil {
		log.Info("either no receive time set on record, or it was invalid: ", err)
		recordIsBad = true
	}

	if time.Now().Sub(recvtime) > MaxRecordAge {
		log.Debug("old record found, tossing.")
		recordIsBad = true
	}

131
	// NOTE: We do not verify the record here beyond checking these timestamps.
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
	// 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 {
			log.Error("Failed to delete bad record from datastore: ", err)
		}

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

	return rec, nil
}

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
152
// Store a value in this peer local storage
ForrestWeston's avatar
ForrestWeston committed
153 154 155 156 157 158 159 160 161
func (dht *IpfsDHT) handlePutValue(ctx context.Context, p peer.ID, pmes *pb.Message) (_ *pb.Message, err error) {
	eip := log.EventBegin(ctx, "handlePutValue", p)
	defer func() {
		if err != nil {
			eip.SetError(err)
		}
		eip.Done()
	}()

162 163 164 165 166
	rec := pmes.GetRecord()
	if rec == nil {
		log.Infof("Got nil record from: %s", p.Pretty())
		return nil, errors.New("nil record")
	}
167

168
	if !bytes.Equal(pmes.GetKey(), rec.GetKey()) {
169 170 171
		return nil, errors.New("put key doesn't match record key")
	}

172
	cleanRecord(rec)
173

174
	// Make sure the record is valid (not expired, valid signature etc)
175
	if err = dht.Validator.Validate(string(rec.GetKey()), rec.GetValue()); err != nil {
176
		log.Warningf("Bad dht record in PUT from: %s. %s", p.Pretty(), err)
177 178 179
		return nil, err
	}

180 181
	dskey := convertToDsKey(rec.GetKey())

182 183 184 185 186 187 188 189 190 191
	// 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()}
192
		i, err := dht.Validator.Select(string(rec.GetKey()), recs)
193 194 195 196 197 198 199 200 201 202
		if err != nil {
			log.Warningf("Bad dht record in PUT from %s: %s", p.Pretty(), err)
			return nil, err
		}
		if i != 0 {
			log.Infof("DHT record in PUT from %s is older than existing record. Ignoring", p.Pretty())
			return nil, errors.New("old record")
		}
	}

203
	// record the time we receive every record
204
	rec.TimeReceived = u.FormatRFC3339(time.Now())
205 206

	data, err := proto.Marshal(rec)
207 208 209 210 211
	if err != nil {
		return nil, err
	}

	err = dht.datastore.Put(dskey, data)
Jeromy's avatar
Jeromy committed
212
	log.Debugf("%s handlePutValue %v", dht.self, dskey)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
213
	return pmes, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
214 215
}

Steven Allen's avatar
Steven Allen committed
216 217
// 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)
218
func (dht *IpfsDHT) getRecordFromDatastore(dskey ds.Key) (*recpb.Record, error) {
219
	buf, err := dht.datastore.Get(dskey)
220 221 222 223
	if err == ds.ErrNotFound {
		return nil, nil
	}
	if err != nil {
224
		log.Errorf("Got error retrieving record with key %s from datastore: %s", dskey, err)
225 226 227
		return nil, err
	}
	rec := new(recpb.Record)
228
	err = proto.Unmarshal(buf, rec)
229 230
	if err != nil {
		// Bad data in datastore, log it but don't return an error, we'll just overwrite it
231
		log.Errorf("Bad record data stored in datastore with key %s: could not unmarshal record", dskey)
232 233 234
		return nil, nil
	}

235
	err = dht.Validator.Validate(string(rec.GetKey()), rec.GetValue())
236 237 238 239 240 241 242 243 244 245
	if err != nil {
		// Invalid record in datastore, probably expired but don't return an error,
		// we'll just overwrite it
		log.Debugf("Local record verify failed: %s (discarded)", err)
		return nil, nil
	}

	return rec, nil
}

246
func (dht *IpfsDHT) handlePing(_ context.Context, p peer.ID, pmes *pb.Message) (*pb.Message, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
247
	log.Debugf("%s Responding to ping from %s!\n", dht.self, p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
248
	return pmes, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
249 250
}

251
func (dht *IpfsDHT) handleFindPeer(ctx context.Context, p peer.ID, pmes *pb.Message) (*pb.Message, error) {
Jeromy's avatar
Jeromy committed
252
	defer log.EventBegin(ctx, "handleFindPeer", p).Done()
253
	resp := pb.NewMessage(pmes.GetType(), nil, pmes.GetClusterLevel())
254
	var closest []peer.ID
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
255 256

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

		// 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) {
			case inet.Connected, inet.CanConnect:
				closest = append(closest, targetPid)
			}
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
279 280 281
	}

	if closest == nil {
282
		log.Infof("%s handleFindPeer %s: could not find anything.", dht.self, p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
283 284 285
		return resp, nil
	}

Jeromy's avatar
Jeromy committed
286
	closestinfos := pstore.PeerInfos(dht.peerstore, closest)
Steven Allen's avatar
Steven Allen committed
287 288
	// possibly an over-allocation but this array is temporary anyways.
	withAddresses := make([]pstore.PeerInfo, 0, len(closestinfos))
289 290 291 292
	for _, pi := range closestinfos {
		if len(pi.Addrs) > 0 {
			withAddresses = append(withAddresses, pi)
			log.Debugf("handleFindPeer: sending back '%s'", pi.ID)
293
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
294 295
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
296
	resp.CloserPeers = pb.PeerInfosToPBPeers(dht.host.Network(), withAddresses)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
297 298 299
	return resp, nil
}

300
func (dht *IpfsDHT) handleGetProviders(ctx context.Context, p peer.ID, pmes *pb.Message) (*pb.Message, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
301 302
	lm := make(lgbl.DeferredMap)
	lm["peer"] = func() interface{} { return p.Pretty() }
ForrestWeston's avatar
ForrestWeston committed
303 304
	eip := log.EventBegin(ctx, "handleGetProviders", lm)
	defer eip.Done()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
305

306
	resp := pb.NewMessage(pmes.GetType(), pmes.GetKey(), pmes.GetClusterLevel())
307 308
	c, err := cid.Cast([]byte(pmes.GetKey()))
	if err != nil {
ForrestWeston's avatar
ForrestWeston committed
309
		eip.SetError(err)
310 311 312 313
		return nil, err
	}

	lm["key"] = func() interface{} { return c.String() }
314 315

	// debug logging niceness.
316
	reqDesc := fmt.Sprintf("%s handleGetProviders(%s, %s): ", dht.self, p, c)
317 318
	log.Debugf("%s begin", reqDesc)
	defer log.Debugf("%s end", reqDesc)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
319 320

	// check if we have this value, to add ourselves as provider.
321
	has, err := dht.datastore.Has(convertToDsKey(c.Bytes()))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
322
	if err != nil && err != ds.ErrNotFound {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
323
		log.Debugf("unexpected datastore error: %v\n", err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
324 325 326 327
		has = false
	}

	// setup providers
328
	providers := dht.providers.GetProviders(ctx, c)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
329 330
	if has {
		providers = append(providers, dht.self)
331
		log.Debugf("%s have the value. added self as provider", reqDesc)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
332 333 334
	}

	if providers != nil && len(providers) > 0 {
Jeromy's avatar
Jeromy committed
335
		infos := pstore.PeerInfos(dht.peerstore, providers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
336
		resp.ProviderPeers = pb.PeerInfosToPBPeers(dht.host.Network(), infos)
337
		log.Debugf("%s have %d providers: %s", reqDesc, len(providers), infos)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
338 339 340
	}

	// Also send closer peers.
341
	closer := dht.betterPeersToQuery(pmes, p, CloserPeerCount)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
342
	if closer != nil {
Jeromy's avatar
Jeromy committed
343
		infos := pstore.PeerInfos(dht.peerstore, closer)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
344
		resp.CloserPeers = pb.PeerInfosToPBPeers(dht.host.Network(), infos)
345
		log.Debugf("%s have %d closer peers: %s", reqDesc, len(closer), infos)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
346 347 348 349 350
	}

	return resp, nil
}

351
func (dht *IpfsDHT) handleAddProvider(ctx context.Context, p peer.ID, pmes *pb.Message) (*pb.Message, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
352 353
	lm := make(lgbl.DeferredMap)
	lm["peer"] = func() interface{} { return p.Pretty() }
ForrestWeston's avatar
ForrestWeston committed
354 355
	eip := log.EventBegin(ctx, "handleAddProvider", lm)
	defer eip.Done()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
356

357 358
	c, err := cid.Cast([]byte(pmes.GetKey()))
	if err != nil {
ForrestWeston's avatar
ForrestWeston committed
359
		eip.SetError(err)
360 361 362 363
		return nil, err
	}

	lm["key"] = func() interface{} { return c.String() }
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
364

365
	log.Debugf("%s adding %s as a provider for '%s'\n", dht.self, p, c)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
366

367
	// add provider should use the address given in the message
368 369 370
	pinfos := pb.PBPeersToPeerInfos(pmes.GetProviderPeers())
	for _, pi := range pinfos {
		if pi.ID != p {
371 372
			// we should ignore this provider record! not from originator.
			// (we should sign them and check signature later...)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
373
			log.Debugf("handleAddProvider received provider %s from %s. Ignore.", pi.ID, p)
374 375
			continue
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
376

377
		if len(pi.Addrs) < 1 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
378
			log.Debugf("%s got no valid addresses for provider %s. Ignore.", dht.self, p)
379 380
			continue
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
381

382
		log.Infof("received provider %s for %s (addrs: %s)", p, c, pi.Addrs)
383
		if pi.ID != dht.self { // don't add own addrs.
384
			// add the received addresses to our peerstore.
Jeromy's avatar
Jeromy committed
385
			dht.peerstore.AddAddrs(pi.ID, pi.Addrs, pstore.ProviderAddrTTL)
386
		}
387
		dht.providers.AddProvider(ctx, c, p)
388 389
	}

Jeromy's avatar
Jeromy committed
390
	return nil, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
391
}
392

393 394
func convertToDsKey(s []byte) ds.Key {
	return ds.NewKey(base32.RawStdEncoding.EncodeToString(s))
395
}