handlers.go 6.59 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.Peer, *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.Peer, pmes *pb.Message) (*pb.Message, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
42
	log.Debugf("%s handleGetValue for key: %s\n", 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 48 49 50 51 52 53

	// first, is the key even a key?
	key := pmes.GetKey()
	if key == "" {
		return nil, errors.New("handleGetValue but no key was provided")
	}

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

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

64 65 66 67
	// 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
68
	if err == nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
69
		log.Debugf("%s handleGetValue success!", dht.self)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
70 71 72 73 74 75

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

76 77 78 79 80 81 82 83
		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
84 85 86
	}

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

	// Find closest peer on given cluster to desired key and reply with that info
94
	closer := dht.betterPeersToQuery(pmes, CloserPeerCount)
95
	if closer != nil {
96
		for _, p := range closer {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
97
			log.Debugf("handleGetValue returning closer peer: '%s'", p)
Jeromy's avatar
Jeromy committed
98
			if len(p.Addresses()) < 1 {
Juan Batiz-Benet's avatar
notes  
Juan Batiz-Benet committed
99
				log.Critical("no addresses on peer being sent!")
Jeromy's avatar
Jeromy committed
100
			}
101
		}
102
		resp.CloserPeers = pb.PeersToPBPeers(dht.dialer, closer)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
103 104 105 106 107 108
	}

	return resp, nil
}

// Store a value in this peer local storage
109
func (dht *IpfsDHT) handlePutValue(ctx context.Context, p peer.Peer, pmes *pb.Message) (*pb.Message, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
110 111
	dht.dslock.Lock()
	defer dht.dslock.Unlock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
112
	dskey := u.Key(pmes.GetKey()).DsKey()
113 114 115

	err := dht.verifyRecord(pmes.GetRecord())
	if err != nil {
Jeromy's avatar
Jeromy committed
116
		fmt.Println(u.Key(pmes.GetRecord().GetAuthor()))
117 118 119 120 121 122 123 124 125 126 127
		log.Error("Bad dht record in put request")
		return nil, err
	}

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

	err = dht.datastore.Put(dskey, data)
	log.Debugf("%s handlePutValue %v\n", dht.self, dskey)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
128
	return pmes, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
129 130
}

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

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

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

	if closest == nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
148
		log.Errorf("handleFindPeer: could not find anything.")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
149 150 151
		return resp, nil
	}

152
	var withAddresses []peer.Peer
153
	for _, p := range closest {
154
		if len(p.Addresses()) > 0 {
155 156
			withAddresses = append(withAddresses, p)
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
157 158
	}

159
	for _, p := range withAddresses {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
160
		log.Debugf("handleFindPeer: sending back '%s'", p)
161
	}
162

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

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

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

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

	// if we've got providers, send thos those.
	if providers != nil && len(providers) > 0 {
187
		resp.ProviderPeers = pb.PeersToPBPeers(dht.dialer, providers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
188 189 190
	}

	// Also send closer peers.
191
	closer := dht.betterPeersToQuery(pmes, CloserPeerCount)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
192
	if closer != nil {
193
		resp.CloserPeers = pb.PeersToPBPeers(dht.dialer, closer)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
194 195 196 197 198 199 200
	}

	return resp, nil
}

type providerInfo struct {
	Creation time.Time
201
	Value    peer.Peer
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
202 203
}

204
func (dht *IpfsDHT) handleAddProvider(ctx context.Context, p peer.Peer, pmes *pb.Message) (*pb.Message, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
205
	key := u.Key(pmes.GetKey())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
206

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
207
	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
208

209
	// add provider should use the address given in the message
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
210 211
	for _, pb := range pmes.GetProviderPeers() {
		pid := peer.ID(pb.GetId())
212
		if pid.Equal(p.ID()) {
213

214
			maddrs, err := pb.Addresses()
215
			if err != nil {
216
				log.Errorf("provider %s error with addresses %s", p, pb.Addrs)
217 218
				continue
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
219

220 221 222 223
			log.Infof("received provider %s %s for %s", p, maddrs, key)
			for _, maddr := range maddrs {
				p.AddAddress(maddr)
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
224 225 226
			dht.providers.AddProvider(key, p)

		} else {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
227
			log.Errorf("handleAddProvider received provider %s from %s", pid, p)
228 229 230
		}
	}

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