handlers.go 11.5 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
	inet "github.com/libp2p/go-libp2p-net"
16 17
	peer "github.com/libp2p/go-libp2p-peer"
	pstore "github.com/libp2p/go-libp2p-peerstore"
George Antoniadis's avatar
George Antoniadis committed
18
	recpb "github.com/libp2p/go-libp2p-record/pb"
19
	base32 "github.com/whyrusleeping/base32"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
20 21
)

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

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

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

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

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

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

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

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

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

	return resp, nil
}

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

	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
107
	rec := new(recpb.Record)
108
	err = proto.Unmarshal(buf, rec)
109
	if err != nil {
110
		log.Debug("failed to unmarshal DHT record from datastore")
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
		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
	}

126
	// NOTE: We do not verify the record here beyond checking these timestamps.
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
	// 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
}

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

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

153 154 155 156 157
	rec := pmes.GetRecord()
	if rec == nil {
		log.Infof("Got nil record from: %s", p.Pretty())
		return nil, errors.New("nil record")
	}
158

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

163
	cleanRecord(rec)
164

165
	// Make sure the record is valid (not expired, valid signature etc)
166
	if err = dht.Validator.Validate(string(rec.GetKey()), rec.GetValue()); err != nil {
167
		log.Warningf("Bad dht record in PUT from: %s. %s", p.Pretty(), err)
168 169 170
		return nil, err
	}

171 172
	dskey := convertToDsKey(rec.GetKey())

173 174 175 176 177 178 179 180 181 182
	// 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()}
183
		i, err := dht.Validator.Select(string(rec.GetKey()), recs)
184 185 186 187 188 189 190 191 192 193
		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")
		}
	}

194
	// record the time we receive every record
195
	rec.TimeReceived = u.FormatRFC3339(time.Now())
196 197

	data, err := proto.Marshal(rec)
198 199 200 201 202
	if err != nil {
		return nil, err
	}

	err = dht.datastore.Put(dskey, data)
Jeromy's avatar
Jeromy committed
203
	log.Debugf("%s handlePutValue %v", dht.self, dskey)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
204
	return pmes, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
205 206
}

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

226
	err = dht.Validator.Validate(string(rec.GetKey()), rec.GetValue())
227 228 229 230 231 232 233 234 235 236
	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
}

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

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

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

		// 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
272 273 274
	}

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

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

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

293
func (dht *IpfsDHT) handleGetProviders(ctx context.Context, p peer.ID, pmes *pb.Message) (_ *pb.Message, _err error) {
294
	ctx = log.Start(ctx, "handleGetProviders")
295 296
	defer func() { log.FinishWithErr(ctx, _err) }()
	log.SetTag(ctx, "peer", p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
297

298
	resp := pb.NewMessage(pmes.GetType(), pmes.GetKey(), pmes.GetClusterLevel())
299 300 301 302
	c, err := cid.Cast([]byte(pmes.GetKey()))
	if err != nil {
		return nil, err
	}
303
	log.SetTag(ctx, "key", c)
304 305

	// debug logging niceness.
306
	reqDesc := fmt.Sprintf("%s handleGetProviders(%s, %s): ", dht.self, p, c)
307 308
	log.Debugf("%s begin", reqDesc)
	defer log.Debugf("%s end", reqDesc)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
309 310

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

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

	if providers != nil && len(providers) > 0 {
Jeromy's avatar
Jeromy committed
325
		infos := pstore.PeerInfos(dht.peerstore, providers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
326
		resp.ProviderPeers = pb.PeerInfosToPBPeers(dht.host.Network(), infos)
327
		log.Debugf("%s have %d providers: %s", reqDesc, len(providers), infos)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
328 329 330
	}

	// Also send closer peers.
331
	closer := dht.betterPeersToQuery(pmes, p, CloserPeerCount)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
332
	if closer != nil {
Jeromy's avatar
Jeromy committed
333
		infos := pstore.PeerInfos(dht.peerstore, closer)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
334
		resp.CloserPeers = pb.PeerInfosToPBPeers(dht.host.Network(), infos)
335
		log.Debugf("%s have %d closer peers: %s", reqDesc, len(closer), infos)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
336 337 338 339 340
	}

	return resp, nil
}

341
func (dht *IpfsDHT) handleAddProvider(ctx context.Context, p peer.ID, pmes *pb.Message) (_ *pb.Message, _err error) {
342
	ctx = log.Start(ctx, "handleAddProvider")
343 344
	defer func() { log.FinishWithErr(ctx, _err) }()
	log.SetTag(ctx, "peer", p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
345

346 347 348 349
	c, err := cid.Cast([]byte(pmes.GetKey()))
	if err != nil {
		return nil, err
	}
350
	log.SetTag(ctx, "key", c)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
351

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

354
	// add provider should use the address given in the message
355 356 357
	pinfos := pb.PBPeersToPeerInfos(pmes.GetProviderPeers())
	for _, pi := range pinfos {
		if pi.ID != p {
358 359
			// 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
360
			log.Debugf("handleAddProvider received provider %s from %s. Ignore.", pi.ID, p)
361 362
			continue
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
363

364
		if len(pi.Addrs) < 1 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
365
			log.Debugf("%s got no valid addresses for provider %s. Ignore.", dht.self, p)
366 367
			continue
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
368

369
		log.Infof("received provider %s for %s (addrs: %s)", p, c, pi.Addrs)
370
		if pi.ID != dht.self { // don't add own addrs.
371
			// add the received addresses to our peerstore.
Jeromy's avatar
Jeromy committed
372
			dht.peerstore.AddAddrs(pi.ID, pi.Addrs, pstore.ProviderAddrTTL)
373
		}
374
		dht.providers.AddProvider(ctx, c, p)
375 376
	}

Jeromy's avatar
Jeromy committed
377
	return nil, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
378
}
379

380 381
func convertToDsKey(s []byte) ds.Key {
	return ds.NewKey(base32.RawStdEncoding.EncodeToString(s))
382
}