ipns_unix.go 12.3 KB
Newer Older
1 2 3
package ipns

import (
Jeromy's avatar
Jeromy committed
4
	"fmt"
5 6 7 8 9
	"io/ioutil"
	"os"
	"path/filepath"
	"time"

10 11
	"bytes"

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
12 13 14
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/bazil.org/fuse"
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/bazil.org/fuse/fs"
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/goprotobuf/proto"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
15 16
	logging "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/op/go-logging"

17 18
	"github.com/jbenet/go-ipfs/core"
	ci "github.com/jbenet/go-ipfs/crypto"
19
	imp "github.com/jbenet/go-ipfs/importer"
20 21 22 23 24 25
	mdag "github.com/jbenet/go-ipfs/merkledag"
	u "github.com/jbenet/go-ipfs/util"
)

var log = logging.MustGetLogger("ipns")

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
26
// FileSystem is the readwrite IPNS Fuse Filesystem.
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
type FileSystem struct {
	Ipfs     *core.IpfsNode
	RootNode *Root
}

// NewFileSystem constructs new fs using given core.IpfsNode instance.
func NewIpns(ipfs *core.IpfsNode, ipfspath string) (*FileSystem, error) {
	root, err := CreateRoot(ipfs, []ci.PrivKey{ipfs.Identity.PrivKey}, ipfspath)
	if err != nil {
		return nil, err
	}
	return &FileSystem{Ipfs: ipfs, RootNode: root}, nil
}

func CreateRoot(n *core.IpfsNode, keys []ci.PrivKey, ipfsroot string) (*Root, error) {
	root := new(Root)
	root.LocalDirs = make(map[string]*Node)
	root.Ipfs = n
	abspath, err := filepath.Abs(ipfsroot)
	if err != nil {
		return nil, err
	}
	root.IpfsRoot = abspath

	root.Keys = keys

	if len(keys) == 0 {
		log.Warning("No keys given for ipns root creation")
	} else {
		k := keys[0]
		pub := k.GetPublic()
		hash, err := pub.Hash()
		if err != nil {
			log.Error("Read Root Error: %s", err)
			return nil, err
		}
		root.LocalLink = &Link{u.Key(hash).Pretty()}
	}

66 67 68 69 70 71 72 73 74 75
	for _, k := range keys {
		hash, err := k.GetPublic().Hash()
		if err != nil {
			log.Error("failed to hash public key.")
			continue
		}
		name := u.Key(hash).Pretty()
		nd := new(Node)
		nd.Ipfs = n
		nd.key = k
Jeromy's avatar
Jeromy committed
76
		nd.repub = NewRepublisher(nd, time.Millisecond*10, time.Second)
77 78

		go nd.repub.Run()
79 80 81

		pointsTo, err := n.Namesys.Resolve(name)
		if err != nil {
Jeromy's avatar
Jeromy committed
82 83 84
			log.Warning("Could not resolve value for local ipns entry, providing empty dir")
			nd.Nd = &mdag.Node{Data: mdag.FolderPBData()}
			root.LocalDirs[name] = nd
85 86 87
			continue
		}

88 89 90 91 92
		if !u.IsValidHash(pointsTo) {
			log.Critical("Got back bad data from namesys resolve! [%s]", pointsTo)
			return nil, nil
		}

93 94 95 96 97 98 99 100 101 102
		node, err := n.Resolver.ResolvePath(pointsTo)
		if err != nil {
			log.Warning("Failed to resolve value from ipns entry in ipfs")
			continue
		}

		nd.Nd = node
		root.LocalDirs[name] = nd
	}

103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
	return root, nil
}

// Root constructs the Root of the filesystem, a Root object.
func (f FileSystem) Root() (fs.Node, fuse.Error) {
	return f.RootNode, nil
}

// Root is the root object of the filesystem tree.
type Root struct {
	Ipfs *core.IpfsNode
	Keys []ci.PrivKey

	// Used for symlinking into ipfs
	IpfsRoot  string
	LocalDirs map[string]*Node

	LocalLink *Link
}

// Attr returns file attributes.
func (*Root) Attr() fuse.Attr {
	return fuse.Attr{Mode: os.ModeDir | 0111} // -rw+x
}

// Lookup performs a lookup under this node.
func (s *Root) Lookup(name string, intr fs.Intr) (fs.Node, fuse.Error) {
130
	log.Debug("ipns: Root Lookup: '%s'", name)
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
	switch name {
	case "mach_kernel", ".hidden", "._.":
		// Just quiet some log noise on OS X.
		return nil, fuse.ENOENT
	}

	if name == "local" {
		if s.LocalLink == nil {
			return nil, fuse.ENOENT
		}
		return s.LocalLink, nil
	}

	nd, ok := s.LocalDirs[name]
	if ok {
		return nd, nil
	}

149
	log.Debug("ipns: Falling back to resolution for [%s].", name)
150 151
	resolved, err := s.Ipfs.Namesys.Resolve(name)
	if err != nil {
Jeromy's avatar
Jeromy committed
152
		log.Warning("ipns: namesys resolve error: %s", err)
153 154 155
		return nil, fuse.ENOENT
	}

Jeromy's avatar
Jeromy committed
156
	return &Link{s.IpfsRoot + "/" + resolved}, nil
157 158 159 160
}

// ReadDir reads a particular directory. Disallowed for root.
func (r *Root) ReadDir(intr fs.Intr) ([]fuse.Dirent, fuse.Error) {
Jeromy's avatar
Jeromy committed
161
	log.Debug("Read Root.")
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
	listing := []fuse.Dirent{
		fuse.Dirent{
			Name: "local",
			Type: fuse.DT_Link,
		},
	}
	for _, k := range r.Keys {
		pub := k.GetPublic()
		hash, err := pub.Hash()
		if err != nil {
			log.Error("Read Root Error: %s", err)
			continue
		}
		ent := fuse.Dirent{
			Name: u.Key(hash).Pretty(),
			Type: fuse.DT_Dir,
		}
		listing = append(listing, ent)
	}
	return listing, nil
}

// Node is the core object representing a filesystem tree node.
type Node struct {
Jeromy's avatar
Jeromy committed
186
	root   *Root
187
	nsRoot *Node
Jeromy's avatar
Jeromy committed
188
	parent *Node
189

190 191
	repub *Republisher

Jeromy's avatar
Jeromy committed
192 193 194
	// This nodes name in its parent dir.
	// NOTE: this strategy wont work well if we allow hard links
	// (im all for murdering the thought of hard links)
195
	name string
196 197

	// Private keys held by nodes at the root of a keyspace
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
198 199
	// WARNING(security): the PrivKey interface is currently insecure
	// (holds the raw key). It will be secured later.
200 201
	key ci.PrivKey

202 203 204 205
	Ipfs   *core.IpfsNode
	Nd     *mdag.Node
	fd     *mdag.DagReader
	cached *mdag.PBData
206

207
	// For writing
208 209
	dataBuf *bytes.Buffer
	changed bool
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
}

func (s *Node) loadData() error {
	s.cached = new(mdag.PBData)
	return proto.Unmarshal(s.Nd.Data, s.cached)
}

// Attr returns the attributes of a given node.
func (s *Node) Attr() fuse.Attr {
	if s.cached == nil {
		s.loadData()
	}
	switch s.cached.GetType() {
	case mdag.PBData_Directory:
		return fuse.Attr{Mode: os.ModeDir | 0555}
	case mdag.PBData_File, mdag.PBData_Raw:
		size, _ := s.Nd.Size()
		return fuse.Attr{
228
			Mode:   0666,
229 230 231 232
			Size:   uint64(size),
			Blocks: uint64(len(s.Nd.Links)),
		}
	default:
233
		log.Error("Invalid data type.")
234 235 236 237 238 239
		return fuse.Attr{}
	}
}

// Lookup performs a lookup under this node.
func (s *Node) Lookup(name string, intr fs.Intr) (fs.Node, fuse.Error) {
240
	log.Debug("ipns: node[%s] Lookup '%s'", s.name, name)
241 242 243 244 245 246
	nd, err := s.Ipfs.Resolver.ResolveLinks(s.Nd, []string{name})
	if err != nil {
		// todo: make this error more versatile.
		return nil, fuse.ENOENT
	}

247 248 249 250
	return s.makeChild(name, nd), nil
}

func (n *Node) makeChild(name string, node *mdag.Node) *Node {
251
	child := &Node{
Jeromy's avatar
Jeromy committed
252 253 254 255
		Ipfs:   n.Ipfs,
		Nd:     node,
		name:   name,
		nsRoot: n.nsRoot,
256 257
	}

258 259
	if n.nsRoot == nil {
		child.nsRoot = n
260
	} else {
261
		child.nsRoot = n.nsRoot
262 263
	}

264
	return child
265 266 267 268
}

// ReadDir reads the link structure as directory entries
func (s *Node) ReadDir(intr fs.Intr) ([]fuse.Dirent, fuse.Error) {
Jeromy's avatar
Jeromy committed
269
	log.Debug("Node ReadDir")
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
	entries := make([]fuse.Dirent, len(s.Nd.Links))
	for i, link := range s.Nd.Links {
		n := link.Name
		if len(n) == 0 {
			n = link.Hash.B58String()
		}
		entries[i] = fuse.Dirent{Name: n, Type: fuse.DT_File}
	}

	if len(entries) > 0 {
		return entries, nil
	}
	return nil, fuse.ENOENT
}

// ReadAll reads the object data as file data
func (s *Node) ReadAll(intr fs.Intr) ([]byte, fuse.Error) {
	log.Debug("ipns: ReadAll Node")
	r, err := mdag.NewDagReader(s.Nd, s.Ipfs.DAG)
	if err != nil {
		return nil, err
	}
	// this is a terrible function... 'ReadAll'?
	// what if i have a 6TB file? GG RAM.
	return ioutil.ReadAll(r)
}

297
func (n *Node) Write(req *fuse.WriteRequest, resp *fuse.WriteResponse, intr fs.Intr) fuse.Error {
Jeromy's avatar
Jeromy committed
298
	log.Debug("ipns: Node Write [%s]: flags = %s, offset = %d, size = %d", n.name, req.Flags.String(), req.Offset, len(req.Data))
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
	if n.dataBuf == nil {
		n.dataBuf = new(bytes.Buffer)
	}
	if req.Offset == 0 {
		n.dataBuf.Reset()
		n.dataBuf.Write(req.Data)
		n.changed = true
		resp.Size = len(req.Data)
	} else {
		log.Error("Unhandled write to offset!")
	}
	return nil
}

func (n *Node) Flush(req *fuse.FlushRequest, intr fs.Intr) fuse.Error {
	log.Debug("Got flush request!")

	if n.changed {
		//TODO:
		// This operation holds everything in memory,
		// should be changed to stream the block creation/storage
		// but for now, since the buf is all in memory anyways...
Jeromy's avatar
Jeromy committed
321 322 323 324 325

		//NOTE:
		// This should only occur on a file object, if this were to be a
		// folder, bad things would happen.
		newNode, err := imp.NewDagFromReader(n.dataBuf)
326
		if err != nil {
Jeromy's avatar
Jeromy committed
327
			log.Critical("error creating dag from dataBuf: %s", err)
328 329
			return fuse.ENODATA
		}
Jeromy's avatar
Jeromy committed
330 331 332 333 334 335 336 337 338
		if n.parent != nil {
			err := n.parent.update(n.name, newNode)
			if err != nil {
				log.Critical("error in updating ipns dag tree: %s", err)
				// return fuse.ETHISISPRETTYBAD
				return fuse.ENOSYS
			}
		}
		n.Nd = newNode
339

Jeromy's avatar
Jeromy committed
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
		//TEMP
		dr, err := mdag.NewDagReader(n.Nd, n.Ipfs.DAG)
		if err != nil {
			log.Critical("Verification read failed.")
		}
		b, err := ioutil.ReadAll(dr)
		if err != nil {
			log.Critical("Verification read failed.")
		}
		fmt.Println("VERIFICATION READ")
		fmt.Printf("READ %d BYTES\n", len(b))
		fmt.Println(string(b))
		//

		n.wasChanged()
355 356 357
	}
	return nil
}
358

Jeromy's avatar
Jeromy committed
359
func (n *Node) wasChanged() {
360 361 362 363 364 365 366 367
	root := n.nsRoot
	if root == nil {
		root = n
	}

	root.repub.Publish <- struct{}{}
}

Jeromy's avatar
Jeromy committed
368 369
func (n *Node) republishRoot() error {
	log.Debug("Republish root")
370 371 372 373 374 375
	var root *Node
	if n.nsRoot != nil {
		root = n.nsRoot
	} else {
		root = n
	}
376

Jeromy's avatar
Jeromy committed
377 378
	// Add any nodes that may be new to the DAG service
	err := n.Ipfs.DAG.AddRecursive(root.Nd)
379 380 381 382
	if err != nil {
		log.Critical("ipns: Dag Add Error: %s", err)
		return err
	}
383

384
	n.dataBuf = nil
385

386 387 388 389 390 391 392
	ndkey, err := root.Nd.Key()
	if err != nil {
		log.Error("getKey error: %s", err)
		// return fuse.ETHISREALLYSUCKS
		return err
	}
	log.Debug("Publishing changes!")
393

394 395 396 397
	err = n.Ipfs.Publisher.Publish(root.key, ndkey.Pretty())
	if err != nil {
		log.Error("ipns: Publish Failed: %s", err)
		return err
398 399 400 401 402 403 404 405 406
	}
	return nil
}

func (n *Node) Fsync(req *fuse.FsyncRequest, intr fs.Intr) fuse.Error {
	log.Debug("Got fsync request!")
	return nil
}

407 408
func (n *Node) Mkdir(req *fuse.MkdirRequest, intr fs.Intr) (fs.Node, fuse.Error) {
	log.Debug("Got mkdir request!")
Jeromy's avatar
Jeromy committed
409
	dagnd := &mdag.Node{Data: mdag.FolderPBData()}
Jeromy's avatar
Jeromy committed
410 411
	nnode := n.Nd.Copy()
	nnode.AddNodeLink(req.Name, dagnd)
412 413 414 415

	child := &Node{
		Ipfs: n.Ipfs,
		Nd:   dagnd,
Jeromy's avatar
Jeromy committed
416
		name: req.Name,
417 418 419 420 421 422 423 424
	}

	if n.nsRoot == nil {
		child.nsRoot = n
	} else {
		child.nsRoot = n.nsRoot
	}

Jeromy's avatar
Jeromy committed
425 426 427 428 429 430 431 432 433 434 435
	if n.parent != nil {
		err := n.parent.update(n.name, nnode)
		if err != nil {
			log.Critical("Error updating node: %s", err)
			// Can we panic, please?
			return nil, fuse.ENODATA
		}
	}
	n.Nd = nnode

	n.wasChanged()
436

437 438 439 440 441 442 443
	return child, nil
}

func (n *Node) Mknod(req *fuse.MknodRequest, intr fs.Intr) (fs.Node, fuse.Error) {
	log.Debug("Got mknod request!")
	return nil, nil
}
444

445
func (n *Node) Open(req *fuse.OpenRequest, resp *fuse.OpenResponse, intr fs.Intr) (fs.Handle, fuse.Error) {
Jeromy's avatar
Jeromy committed
446
	//log.Debug("[%s] Received open request! flags = %s", n.name, req.Flags.String())
447
	//TODO: check open flags and truncate if necessary
448 449 450 451
	return n, nil
}

func (n *Node) Create(req *fuse.CreateRequest, resp *fuse.CreateResponse, intr fs.Intr) (fs.Node, fs.Handle, fuse.Error) {
452
	log.Debug("Got create request: %s", req.Name)
Jeromy's avatar
Jeromy committed
453 454 455

	// New 'empty' file
	nd := &mdag.Node{Data: mdag.FilePBData(nil)}
456 457
	child := n.makeChild(req.Name, nd)

Jeromy's avatar
Jeromy committed
458 459 460
	nnode := n.Nd.Copy()

	err := nnode.AddNodeLink(req.Name, nd)
461 462 463 464
	if err != nil {
		log.Error("Error adding child to node: %s", err)
		return nil, nil, fuse.ENOENT
	}
Jeromy's avatar
Jeromy committed
465 466 467 468 469 470 471 472 473 474 475
	if n.parent != nil {
		err := n.parent.update(n.name, nnode)
		if err != nil {
			log.Critical("Error updating node: %s", err)
			// Can we panic, please?
			return nil, nil, fuse.ENODATA
		}
	}
	n.Nd = nnode
	n.wasChanged()

476
	return child, child, nil
477 478 479
}

func (n *Node) Remove(req *fuse.RemoveRequest, intr fs.Intr) fuse.Error {
480
	log.Debug("[%s] Got Remove request: %s", n.name, req.Name)
Jeromy's avatar
Jeromy committed
481 482
	nnode := n.Nd.Copy()
	err := nnode.RemoveNodeLink(req.Name)
483 484 485 486
	if err != nil {
		log.Error("Remove: No such file.")
		return fuse.ENOENT
	}
Jeromy's avatar
Jeromy committed
487 488 489 490 491 492 493 494 495 496 497

	if n.parent != nil {
		err := n.parent.update(n.name, nnode)
		if err != nil {
			log.Critical("Error updating node: %s", err)
			// Can we panic, please?
			return fuse.ENODATA
		}
	}
	n.Nd = nnode
	n.wasChanged()
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
	return nil
}

func (n *Node) Rename(req *fuse.RenameRequest, newDir fs.Node, intr fs.Intr) fuse.Error {
	log.Debug("Got Rename request '%s' -> '%s'", req.OldName, req.NewName)
	var mdn *mdag.Node
	for _, l := range n.Nd.Links {
		if l.Name == req.OldName {
			mdn = l.Node
		}
	}
	if mdn == nil {
		log.Critical("nil Link found on rename!")
		return fuse.ENOENT
	}
	n.Nd.RemoveNodeLink(req.OldName)

	switch newDir := newDir.(type) {
	case *Node:
		err := newDir.Nd.AddNodeLink(req.NewName, mdn)
		if err != nil {
			log.Error("Error adding node to new dir on rename: %s", err)
			return fuse.ENOENT
		}
	default:
		log.Critical("Unknown node type for rename target dir!")
		return fuse.ENOENT
	}
	return nil
527
}
Jeromy's avatar
Jeromy committed
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545

func (n *Node) update(name string, newnode *mdag.Node) error {
	nnode := n.Nd.Copy()
	err := nnode.RemoveNodeLink(name)
	if err != nil {
		return err
	}
	nnode.AddNodeLink(name, newnode)

	if n.parent != nil {
		err := n.parent.update(n.name, newnode)
		if err != nil {
			return err
		}
	}
	n.Nd = nnode
	return nil
}