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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
10 11 12
	"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
13

14 15
	"github.com/jbenet/go-ipfs/core"
	ci "github.com/jbenet/go-ipfs/crypto"
16
	imp "github.com/jbenet/go-ipfs/importer"
17
	ft "github.com/jbenet/go-ipfs/importer/format"
18 19 20 21
	mdag "github.com/jbenet/go-ipfs/merkledag"
	u "github.com/jbenet/go-ipfs/util"
)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
22
var log = u.Logger("ipns")
23

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
24
// FileSystem is the readwrite IPNS Fuse Filesystem.
25 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
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()}
	}

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

		go nd.repub.Run()
77 78 79

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

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

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

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

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

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

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

188 189
	repub *Republisher

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

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

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

205
	// For writing
Jeromy's avatar
Jeromy committed
206
	writerBuf WriteAtBuf
207 208 209
}

func (s *Node) loadData() error {
210
	s.cached = new(ft.PBData)
211 212 213 214 215 216 217 218 219
	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() {
220
	case ft.PBData_Directory:
221
		return fuse.Attr{Mode: os.ModeDir | 0555}
222 223
	case ft.PBData_File, ft.PBData_Raw:
		size, err := ft.DataSize(s.Nd.Data)
Jeromy's avatar
Jeromy committed
224 225 226 227
		if err != nil {
			log.Error("Error getting size of file: %s", err)
			size = 0
		}
228
		return fuse.Attr{
229
			Mode:   0666,
Jeromy's avatar
Jeromy committed
230
			Size:   size,
231 232 233
			Blocks: uint64(len(s.Nd.Links)),
		}
	default:
234
		log.Error("Invalid data type.")
235 236 237 238 239 240
		return fuse.Attr{}
	}
}

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

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

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

260 261
	if n.nsRoot == nil {
		child.nsRoot = n
262
	} else {
263
		child.nsRoot = n.nsRoot
264 265
	}

266
	return child
267 268 269 270
}

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

304
func (n *Node) Write(req *fuse.WriteRequest, resp *fuse.WriteResponse, intr fs.Intr) fuse.Error {
Jeromy's avatar
Jeromy committed
305
	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
306 307
	if n.writerBuf == nil {
		n.writerBuf = NewWriterAtFromBytes(nil)
308
	}
Jeromy's avatar
Jeromy committed
309 310 311
	_, err := n.writerBuf.WriteAt(req.Data, req.Offset)
	if err != nil {
		return err
312
	}
313
	resp.Size = len(req.Data)
314 315 316 317
	return nil
}

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

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

		//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
329 330
		buf := bytes.NewReader(n.writerBuf.Bytes())
		newNode, err := imp.NewDagFromReader(buf)
331
		if err != nil {
Jeromy's avatar
Jeromy committed
332
			log.Critical("error creating dag from writerBuf: %s", err)
Jeromy's avatar
Jeromy committed
333
			return err
334
		}
Jeromy's avatar
Jeromy committed
335
		if n.parent != nil {
Jeromy's avatar
Jeromy committed
336
			log.Debug("updating self in parent!")
Jeromy's avatar
Jeromy committed
337 338 339 340
			err := n.parent.update(n.name, newNode)
			if err != nil {
				log.Critical("error in updating ipns dag tree: %s", err)
				// return fuse.ETHISISPRETTYBAD
Jeromy's avatar
Jeromy committed
341
				return err
Jeromy's avatar
Jeromy committed
342 343 344
			}
		}
		n.Nd = newNode
345

346
		/*/TEMP
Jeromy's avatar
Jeromy committed
347 348 349 350 351 352 353 354 355 356 357
		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
358
		fmt.Println(b)
359
		//*/
Jeromy's avatar
Jeromy committed
360

Jeromy's avatar
Jeromy committed
361
		n.writerBuf = nil
Jeromy's avatar
Jeromy committed
362

Jeromy's avatar
Jeromy committed
363
		n.wasChanged()
364 365 366
	}
	return nil
}
367

Jeromy's avatar
Jeromy committed
368
func (n *Node) wasChanged() {
369 370 371 372 373 374 375 376
	root := n.nsRoot
	if root == nil {
		root = n
	}

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

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

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

Jeromy's avatar
Jeromy committed
393
	n.writerBuf = nil
394

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

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

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

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

	child := &Node{
		Ipfs: n.Ipfs,
		Nd:   dagnd,
Jeromy's avatar
Jeromy committed
425
		name: req.Name,
426 427 428 429 430 431 432 433
	}

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

Jeromy's avatar
Jeromy committed
434 435 436 437 438 439 440 441 442 443 444
	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()
445

446 447 448 449
	return child, nil
}

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

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

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

	// New 'empty' file
470
	nd := &mdag.Node{Data: ft.FilePBData(nil, 0)}
471 472
	child := n.makeChild(req.Name, nd)

Jeromy's avatar
Jeromy committed
473 474 475
	nnode := n.Nd.Copy()

	err := nnode.AddNodeLink(req.Name, nd)
476 477 478 479
	if err != nil {
		log.Error("Error adding child to node: %s", err)
		return nil, nil, fuse.ENOENT
	}
Jeromy's avatar
Jeromy committed
480 481 482 483 484 485 486 487 488 489 490
	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()

491
	return child, child, nil
492 493 494
}

func (n *Node) Remove(req *fuse.RemoveRequest, intr fs.Intr) fuse.Error {
495
	log.Debug("[%s] Got Remove request: %s", n.name, req.Name)
Jeromy's avatar
Jeromy committed
496 497
	nnode := n.Nd.Copy()
	err := nnode.RemoveNodeLink(req.Name)
498 499 500 501
	if err != nil {
		log.Error("Remove: No such file.")
		return fuse.ENOENT
	}
Jeromy's avatar
Jeromy committed
502 503 504 505 506 507 508 509 510 511 512

	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()
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
	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
542
}
Jeromy's avatar
Jeromy committed
543 544

func (n *Node) update(name string, newnode *mdag.Node) error {
Jeromy's avatar
Jeromy committed
545
	log.Debug("update '%s' in '%s'", name, n.name)
Jeromy's avatar
Jeromy committed
546 547 548 549 550 551 552 553
	nnode := n.Nd.Copy()
	err := nnode.RemoveNodeLink(name)
	if err != nil {
		return err
	}
	nnode.AddNodeLink(name, newnode)

	if n.parent != nil {
Jeromy's avatar
Jeromy committed
554
		err := n.parent.update(n.name, nnode)
Jeromy's avatar
Jeromy committed
555 556 557 558 559 560 561
		if err != nil {
			return err
		}
	}
	n.Nd = nnode
	return nil
}