handlers.go 7.1 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3 4 5 6 7
package dht

import (
	"errors"
	"fmt"
	"time"

8 9 10
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
	proto "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/goprotobuf/proto"
	ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
11
	peer "github.com/jbenet/go-ipfs/peer"
12
	pb "github.com/jbenet/go-ipfs/routing/dht/pb"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
13 14 15
	u "github.com/jbenet/go-ipfs/util"
)

Jeromy's avatar
Jeromy committed
16
// The number of closer peers to send on requests.
17 18
var CloserPeerCount = 4

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

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

41
func (dht *IpfsDHT) handleGetValue(ctx context.Context, p peer.ID, pmes *pb.Message) (*pb.Message, error) {
Jeromy's avatar
Jeromy committed
42
	log.Debugf("%s handleGetValue for key: %s", dht.self, pmes.GetKey())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
43 44

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

47
	// first, is there even a key?
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
48 49 50
	key := pmes.GetKey()
	if key == "" {
		return nil, errors.New("handleGetValue but no key was provided")
51
		// TODO: send back an error response? could be bad, but the other node's hanging.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
52 53 54
	}

	// let's first check if we have the value locally.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
55
	log.Debugf("%s handleGetValue looking into ds", dht.self)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
56
	dskey := u.Key(pmes.GetKey()).DsKey()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
57
	iVal, err := dht.datastore.Get(dskey)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
58
	log.Debugf("%s handleGetValue looking into ds GOT %v", dht.self, iVal)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
59 60

	// if we got an unexpected error, bail.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
61
	if err != nil && err != ds.ErrNotFound {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
62 63 64
		return nil, err
	}

65 66 67 68
	// Note: changed the behavior here to return _as much_ info as possible
	// (potentially all of {value, closer peers, provider})

	// if we have the value, send it back
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
69
	if err == nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
70
		log.Debugf("%s handleGetValue success!", dht.self)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
71 72 73 74 75 76

		byts, ok := iVal.([]byte)
		if !ok {
			return nil, fmt.Errorf("datastore had non byte-slice value for %v", dskey)
		}

77 78 79 80 81 82 83 84
		rec := new(pb.Record)
		err := proto.Unmarshal(byts, rec)
		if err != nil {
			log.Error("Failed to unmarshal dht record from datastore")
			return nil, err
		}

		resp.Record = rec
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
85 86 87
	}

	// if we know any providers for the requested value, return those.
88
	provs := dht.providers.GetProviders(ctx, u.Key(pmes.GetKey()))
89
	provinfos := peer.PeerInfos(dht.peerstore, provs)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
90
	if len(provs) > 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
91
		log.Debugf("handleGetValue returning %d provider[s]", len(provs))
92
		resp.ProviderPeers = pb.PeerInfosToPBPeers(dht.network, provinfos)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
93 94 95
	}

	// Find closest peer on given cluster to desired key and reply with that info
96
	closer := dht.betterPeersToQuery(pmes, p, CloserPeerCount)
97
	closerinfos := peer.PeerInfos(dht.peerstore, closer)
98
	if closer != nil {
99 100 101 102 103 104 105
		for _, pi := range closerinfos {
			log.Debugf("handleGetValue returning closer peer: '%s'", pi.ID)
			if len(pi.Addrs) < 1 {
				log.Criticalf(`no addresses on peer being sent!
					[local:%s]
					[sending:%s]
					[remote:%s]`, dht.self, pi.ID, p)
Jeromy's avatar
Jeromy committed
106
			}
107
		}
108 109

		resp.CloserPeers = pb.PeerInfosToPBPeers(dht.network, closerinfos)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
110 111 112 113 114 115
	}

	return resp, nil
}

// Store a value in this peer local storage
116
func (dht *IpfsDHT) handlePutValue(ctx context.Context, p peer.ID, pmes *pb.Message) (*pb.Message, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
117
	dskey := u.Key(pmes.GetKey()).DsKey()
118

119 120
	if err := dht.verifyRecordLocally(pmes.GetRecord()); err != nil {
		log.Errorf("Bad dht record in PUT from: %s. %s", u.Key(pmes.GetRecord().GetAuthor()), err)
121 122 123 124 125 126 127 128 129
		return nil, err
	}

	data, err := proto.Marshal(pmes.GetRecord())
	if err != nil {
		return nil, err
	}

	err = dht.datastore.Put(dskey, data)
Jeromy's avatar
Jeromy committed
130
	log.Debugf("%s handlePutValue %v", dht.self, dskey)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
131
	return pmes, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
132 133
}

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

139
func (dht *IpfsDHT) handleFindPeer(ctx context.Context, p peer.ID, pmes *pb.Message) (*pb.Message, error) {
140
	resp := pb.NewMessage(pmes.GetType(), "", pmes.GetClusterLevel())
141
	var closest []peer.ID
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
142 143

	// if looking for self... special case where we send it on CloserPeers.
144 145
	if peer.ID(pmes.GetKey()) == dht.self {
		closest = []peer.ID{dht.self}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
146
	} else {
147
		closest = dht.betterPeersToQuery(pmes, p, CloserPeerCount)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
148 149 150
	}

	if closest == nil {
151
		log.Warningf("handleFindPeer: could not find anything.")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
152 153 154
		return resp, nil
	}

155 156 157 158 159 160
	var withAddresses []peer.PeerInfo
	closestinfos := peer.PeerInfos(dht.peerstore, closest)
	for _, pi := range closestinfos {
		if len(pi.Addrs) > 0 {
			withAddresses = append(withAddresses, pi)
			log.Debugf("handleFindPeer: sending back '%s'", pi.ID)
161
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
162 163
	}

164
	resp.CloserPeers = pb.PeerInfosToPBPeers(dht.network, withAddresses)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
165 166 167
	return resp, nil
}

168
func (dht *IpfsDHT) handleGetProviders(ctx context.Context, p peer.ID, pmes *pb.Message) (*pb.Message, error) {
169
	resp := pb.NewMessage(pmes.GetType(), pmes.GetKey(), pmes.GetClusterLevel())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
170 171

	// check if we have this value, to add ourselves as provider.
Jeromy's avatar
Jeromy committed
172
	log.Debugf("handling GetProviders: '%s'", u.Key(pmes.GetKey()))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
173 174
	dsk := u.Key(pmes.GetKey()).DsKey()
	has, err := dht.datastore.Has(dsk)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
175
	if err != nil && err != ds.ErrNotFound {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
176
		log.Errorf("unexpected datastore error: %v\n", err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
177 178 179 180
		has = false
	}

	// setup providers
181
	providers := dht.providers.GetProviders(ctx, u.Key(pmes.GetKey()))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
182 183 184 185 186
	if has {
		providers = append(providers, dht.self)
	}

	if providers != nil && len(providers) > 0 {
187 188
		infos := peer.PeerInfos(dht.peerstore, providers)
		resp.ProviderPeers = pb.PeerInfosToPBPeers(dht.network, infos)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
189 190 191
	}

	// Also send closer peers.
192
	closer := dht.betterPeersToQuery(pmes, p, CloserPeerCount)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
193
	if closer != nil {
194 195
		infos := peer.PeerInfos(dht.peerstore, providers)
		resp.CloserPeers = pb.PeerInfosToPBPeers(dht.network, infos)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
196 197 198 199 200 201 202
	}

	return resp, nil
}

type providerInfo struct {
	Creation time.Time
203
	Value    peer.ID
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
204 205
}

206
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
207
	key := u.Key(pmes.GetKey())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
208

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
209
	log.Debugf("%s adding %s as a provider for '%s'\n", dht.self, p, peer.ID(key))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
210

211
	// add provider should use the address given in the message
212 213 214 215 216 217 218 219
	pinfos := pb.PBPeersToPeerInfos(pmes.GetProviderPeers())
	for _, pi := range pinfos {
		if pi.ID != p {
			// we should ignore this provider reccord! not from originator.
			// (we chould sign them and check signature later...)
			log.Errorf("handleAddProvider received provider %s from %s. Ignore.", pi.ID, p)
			continue
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
220

221
		if len(pi.Addrs) < 1 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
222
			log.Errorf("%s got no valid addresses for provider %s. Ignore.", dht.self, p)
223 224
			continue
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
225

226 227 228 229
		log.Infof("received provider %s for %s (addrs: %s)", p, key, pi.Addrs)
		for _, maddr := range pi.Addrs {
			// add the received addresses to our peerstore.
			dht.peerstore.AddAddress(p, maddr)
230
		}
231
		dht.providers.AddProvider(key, p)
232 233
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
234
	return pmes, nil // send back same msg as confirmation.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
235
}