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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
11 12 13
	"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
14 15
	logging "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/op/go-logging"

16 17
	"github.com/jbenet/go-ipfs/core"
	ci "github.com/jbenet/go-ipfs/crypto"
18
	imp "github.com/jbenet/go-ipfs/importer"
19 20 21 22 23 24
	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
25
// FileSystem is the readwrite IPNS Fuse Filesystem.
26 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
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()}
	}

65 66 67 68 69 70 71 72 73 74
	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
75
		nd.repub = NewRepublisher(nd, time.Millisecond*10, time.Second)
76 77

		go nd.repub.Run()
78 79 80

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

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

92 93 94 95 96 97 98 99 100 101
		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
	}

102 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
	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) {
129
	log.Debug("ipns: Root Lookup: '%s'", name)
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
	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
	}

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

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

// ReadDir reads a particular directory. Disallowed for root.
func (r *Root) ReadDir(intr fs.Intr) ([]fuse.Dirent, fuse.Error) {
Jeromy's avatar
Jeromy committed
160
	log.Debug("Read Root.")
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
	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
185
	root   *Root
186
	nsRoot *Node
Jeromy's avatar
Jeromy committed
187
	parent *Node
188

189 190
	repub *Republisher

Jeromy's avatar
Jeromy committed
191 192 193
	// 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)
194
	name string
195 196

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

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

206
	// For writing
Jeromy's avatar
Jeromy committed
207
	writerBuf WriteAtBuf
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
}

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{
226
			Mode:   0666,
227 228 229 230
			Size:   uint64(size),
			Blocks: uint64(len(s.Nd.Links)),
		}
	default:
231
		log.Error("Invalid data type.")
232 233 234 235 236 237
		return fuse.Attr{}
	}
}

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

245 246 247 248
	return s.makeChild(name, nd), nil
}

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

256 257
	if n.nsRoot == nil {
		child.nsRoot = n
258
	} else {
259
		child.nsRoot = n.nsRoot
260 261
	}

262
	return child
263 264 265 266
}

// ReadDir reads the link structure as directory entries
func (s *Node) ReadDir(intr fs.Intr) ([]fuse.Dirent, fuse.Error) {
Jeromy's avatar
Jeromy committed
267
	log.Debug("Node ReadDir")
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
	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.
Jeromy's avatar
Jeromy committed
292 293 294 295 296 297 298 299 300
	b, err := ioutil.ReadAll(r)
	if err != nil {
		log.Error("[%s] Readall error: %s", s.name, err)
		return nil, err
	}
	if len(b) > 4 {
		log.Debug("ReadAll trailing bytes: %v", b[len(b)-4:])
	}
	return b, nil
301 302
}

303
func (n *Node) Write(req *fuse.WriteRequest, resp *fuse.WriteResponse, intr fs.Intr) fuse.Error {
Jeromy's avatar
Jeromy committed
304
	log.Debug("ipns: Node Write [%s]: flags = %s, offset = %d, size = %d", n.name, req.Flags.String(), req.Offset, len(req.Data))
Jeromy's avatar
Jeromy committed
305 306
	if n.writerBuf == nil {
		n.writerBuf = NewWriterAtFromBytes(nil)
307
	}
Jeromy's avatar
Jeromy committed
308 309 310
	_, err := n.writerBuf.WriteAt(req.Data, req.Offset)
	if err != nil {
		return err
311 312 313 314 315
	}
	return nil
}

func (n *Node) Flush(req *fuse.FlushRequest, intr fs.Intr) fuse.Error {
Jeromy's avatar
Jeromy committed
316
	log.Debug("Got flush request [%s]!", n.name)
317

Jeromy's avatar
Jeromy committed
318
	if n.writerBuf != nil {
319 320 321 322
		//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
323 324 325 326

		//NOTE:
		// This should only occur on a file object, if this were to be a
		// folder, bad things would happen.
Jeromy's avatar
Jeromy committed
327 328
		buf := bytes.NewReader(n.writerBuf.Bytes())
		newNode, err := imp.NewDagFromReader(buf)
329
		if err != nil {
Jeromy's avatar
Jeromy committed
330
			log.Critical("error creating dag from writerBuf: %s", err)
331 332
			return fuse.ENODATA
		}
Jeromy's avatar
Jeromy committed
333 334 335 336 337 338 339 340 341
		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
342

Jeromy's avatar
Jeromy committed
343 344 345 346 347 348 349 350 351 352 353 354 355 356
		//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))
		//

Jeromy's avatar
Jeromy committed
357
		n.writerBuf = nil
Jeromy's avatar
Jeromy committed
358

Jeromy's avatar
Jeromy committed
359
		n.wasChanged()
360 361 362
	}
	return nil
}
363

Jeromy's avatar
Jeromy committed
364
func (n *Node) wasChanged() {
365 366 367 368 369 370 371 372
	root := n.nsRoot
	if root == nil {
		root = n
	}

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

Jeromy's avatar
Jeromy committed
373 374
func (n *Node) republishRoot() error {
	log.Debug("Republish root")
375 376 377 378 379 380
	var root *Node
	if n.nsRoot != nil {
		root = n.nsRoot
	} else {
		root = n
	}
381

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

Jeromy's avatar
Jeromy committed
389
	n.writerBuf = nil
390

391 392 393 394 395 396 397
	ndkey, err := root.Nd.Key()
	if err != nil {
		log.Error("getKey error: %s", err)
		// return fuse.ETHISREALLYSUCKS
		return err
	}
	log.Debug("Publishing changes!")
398

399 400 401 402
	err = n.Ipfs.Publisher.Publish(root.key, ndkey.Pretty())
	if err != nil {
		log.Error("ipns: Publish Failed: %s", err)
		return err
403 404 405 406 407 408 409 410 411
	}
	return nil
}

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

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

	child := &Node{
		Ipfs: n.Ipfs,
		Nd:   dagnd,
Jeromy's avatar
Jeromy committed
421
		name: req.Name,
422 423 424 425 426 427 428 429
	}

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

Jeromy's avatar
Jeromy committed
430 431 432 433 434 435 436 437 438 439 440
	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()
441

442 443 444 445 446 447 448
	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
}
449

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

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

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

Jeromy's avatar
Jeromy committed
463 464 465
	nnode := n.Nd.Copy()

	err := nnode.AddNodeLink(req.Name, nd)
466 467 468 469
	if err != nil {
		log.Error("Error adding child to node: %s", err)
		return nil, nil, fuse.ENOENT
	}
Jeromy's avatar
Jeromy committed
470 471 472 473 474 475 476 477 478 479 480
	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()

481
	return child, child, nil
482 483 484
}

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

	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()
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
	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
532
}
Jeromy's avatar
Jeromy committed
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550

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
}