routing.go 5.15 KB
Newer Older
1 2 3 4
package namesys

import (
	"fmt"
5
	"strings"
6
	"time"
7

8
	"context"
Jakub Sztandera's avatar
Jakub Sztandera committed
9
	lru "gx/ipfs/QmVYxfoJQiZijTgPNHCHgHELvQpbsJNTg6Crmc3dQkj3yy/golang-lru"
10
	mh "gx/ipfs/QmYDds3421prZgqKbLpEK7T9Aa2eVdQ7o3YarX1LVLdP2J/go-multihash"
Jeromy's avatar
Jeromy committed
11
	proto "gx/ipfs/QmZ4Qi3GaRbjcx28Sme5eMH7RQjGkt8wHxt2a65oLaeFEV/gogo-protobuf/proto"
12

13
	pb "github.com/ipfs/go-ipfs/namesys/pb"
14
	path "github.com/ipfs/go-ipfs/path"
15
	routing "gx/ipfs/QmUrCwTDvJgmBbJVHu1HGEyqDaod3dR6sEkZkpxZk4u47c/go-libp2p-routing"
16
	key "gx/ipfs/QmYEoKZXHoAToWfhGF3vryhMn3WWhE1o2MasQ8uzY5iDi9/go-key"
Jeromy's avatar
Jeromy committed
17

Jeromy's avatar
Jeromy committed
18
	logging "gx/ipfs/QmSpJByNKFX1sCsHBEp3R73FL4NF6FnQTEGyNAXHm2GS52/go-log"
19
	u "gx/ipfs/Qmb912gdngC1UWwTkhuW8knyRbcWeu5kqkxBpveLmW8bSr/go-ipfs-util"
20
	cid "gx/ipfs/QmcEcrBAMrwMyhSjXt4yfyPpzgSuV8HLHavnfmiKCSRqZU/go-cid"
21
	ci "gx/ipfs/QmfWDLQjGjVe4fr5CoztYW2DYYjRysMJrFe1RCsXLPTf46/go-libp2p-crypto"
22 23
)

Jeromy's avatar
Jeromy committed
24
var log = logging.Logger("namesys")
25

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
26 27
// routingResolver implements NSResolver for the main IPFS SFS-like naming
type routingResolver struct {
28
	routing routing.ValueStore
29 30

	cache *lru.Cache
Jeromy's avatar
Jeromy committed
31 32
}

33 34 35 36 37 38 39 40
func (r *routingResolver) cacheGet(name string) (path.Path, bool) {
	if r.cache == nil {
		return "", false
	}

	ientry, ok := r.cache.Get(name)
	if !ok {
		return "", false
41 42
	}

43 44 45 46 47 48 49 50 51 52 53 54 55
	entry, ok := ientry.(cacheEntry)
	if !ok {
		// should never happen, purely for sanity
		log.Panicf("unexpected type %T in cache for %q.", ientry, name)
	}

	if time.Now().Before(entry.eol) {
		return entry.val, true
	}

	r.cache.Remove(name)

	return "", false
56 57
}

58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
func (r *routingResolver) cacheSet(name string, val path.Path, rec *pb.IpnsEntry) {
	if r.cache == nil {
		return
	}

	// if completely unspecified, just use one minute
	ttl := DefaultResolverCacheTTL
	if rec.Ttl != nil {
		recttl := time.Duration(rec.GetTtl())
		if recttl >= 0 {
			ttl = recttl
		}
	}

	cacheTil := time.Now().Add(ttl)
	eol, ok := checkEOL(rec)
	if ok && eol.Before(cacheTil) {
		cacheTil = eol
	}

	r.cache.Add(name, cacheEntry{
		val: val,
		eol: cacheTil,
	})
}

type cacheEntry struct {
	val path.Path
	eol time.Time
}

// NewRoutingResolver constructs a name resolver using the IPFS Routing system
// to implement SFS-like naming on top.
// cachesize is the limit of the number of entries in the lru cache. Setting it
// to '0' will disable caching.
93
func NewRoutingResolver(route routing.ValueStore, cachesize int) *routingResolver {
94 95 96 97
	if route == nil {
		panic("attempt to create resolver with nil routing system")
	}

98 99 100 101 102 103 104 105 106
	var cache *lru.Cache
	if cachesize > 0 {
		cache, _ = lru.New(cachesize)
	}

	return &routingResolver{
		routing: route,
		cache:   cache,
	}
Jeromy's avatar
Jeromy committed
107 108
}

109
// Resolve implements Resolver.
110
func (r *routingResolver) Resolve(ctx context.Context, name string) (path.Path, error) {
111 112 113 114 115 116 117 118 119 120 121
	return r.ResolveN(ctx, name, DefaultDepthLimit)
}

// ResolveN implements Resolver.
func (r *routingResolver) ResolveN(ctx context.Context, name string, depth int) (path.Path, error) {
	return resolve(ctx, r, name, depth, "/ipns/")
}

// resolveOnce implements resolver. Uses the IPFS routing system to
// resolve SFS-like names.
func (r *routingResolver) resolveOnce(ctx context.Context, name string) (path.Path, error) {
122
	log.Debugf("RoutingResolve: '%s'", name)
123 124 125 126 127
	cached, ok := r.cacheGet(name)
	if ok {
		return cached, nil
	}

128
	name = strings.TrimPrefix(name, "/ipns/")
129 130
	hash, err := mh.FromB58String(name)
	if err != nil {
Jeromy's avatar
Jeromy committed
131
		// name should be a multihash. if it isn't, error out here.
132
		log.Warningf("RoutingResolve: bad input hash: [%s]\n", name)
133 134 135 136 137
		return "", err
	}

	// use the routing system to get the name.
	// /ipns/<name>
Jeromy's avatar
Jeromy committed
138
	h := []byte("/ipns/" + string(hash))
139

Jeromy's avatar
Jeromy committed
140 141
	var entry *pb.IpnsEntry
	var pubkey ci.PubKey
142

Jeromy's avatar
Jeromy committed
143 144
	resp := make(chan error, 2)
	go func() {
145
		ipnsKey := string(h)
Jeromy's avatar
Jeromy committed
146 147 148 149
		val, err := r.routing.GetValue(ctx, ipnsKey)
		if err != nil {
			log.Warning("RoutingResolve get failed.")
			resp <- err
Jeromy's avatar
Jeromy committed
150
			return
Jeromy's avatar
Jeromy committed
151
		}
152

Jeromy's avatar
Jeromy committed
153 154 155 156
		entry = new(pb.IpnsEntry)
		err = proto.Unmarshal(val, entry)
		if err != nil {
			resp <- err
Jeromy's avatar
Jeromy committed
157
			return
Jeromy's avatar
Jeromy committed
158
		}
Jeromy's avatar
Jeromy committed
159

Jeromy's avatar
Jeromy committed
160 161 162 163 164 165 166 167
		resp <- nil
	}()

	go func() {
		// name should be a public key retrievable from ipfs
		pubk, err := routing.GetPublicKey(r.routing, ctx, hash)
		if err != nil {
			resp <- err
Jeromy's avatar
Jeromy committed
168
			return
Jeromy's avatar
Jeromy committed
169
		}
Jeromy's avatar
Jeromy committed
170

Jeromy's avatar
Jeromy committed
171 172 173 174 175 176 177 178 179
		pubkey = pubk
		resp <- nil
	}()

	for i := 0; i < 2; i++ {
		err = <-resp
		if err != nil {
			return "", err
		}
180
	}
181 182

	hsh, _ := pubkey.Hash()
183
	log.Debugf("pk hash = %s", key.Key(hsh))
184 185

	// check sig with pk
186 187
	if ok, err := pubkey.Verify(ipnsEntryDataForSig(entry), entry.GetSignature()); err != nil || !ok {
		return "", fmt.Errorf("Invalid value. Not signed by PrivateKey corresponding to %v", pubkey)
188 189 190
	}

	// ok sig checks out. this is a valid name.
191 192 193 194 195

	// check for old style record:
	valh, err := mh.Cast(entry.GetValue())
	if err != nil {
		// Not a multihash, probably a new record
196 197 198 199 200 201 202
		p, err := path.ParsePath(string(entry.GetValue()))
		if err != nil {
			return "", err
		}

		r.cacheSet(name, p, entry)
		return p, nil
203 204 205
	} else {
		// Its an old style multihash record
		log.Warning("Detected old style multihash record")
Jeromy's avatar
Jeromy committed
206
		p := path.FromCid(cid.NewCidV0(valh))
207 208 209 210 211 212 213 214 215 216 217 218
		r.cacheSet(name, p, entry)
		return p, nil
	}
}

func checkEOL(e *pb.IpnsEntry) (time.Time, bool) {
	if e.GetValidityType() == pb.IpnsEntry_EOL {
		eol, err := u.ParseRFC3339(string(e.GetValidity()))
		if err != nil {
			return time.Time{}, false
		}
		return eol, true
219
	}
220
	return time.Time{}, false
221
}