Skip to content
This repository
tree: d4bc535c7b
Fetching contributors…

Cannot retrieve contributors at this time

file 493 lines (415 sloc) 10.719 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 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 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 93 94 95 96 97 98 99 100 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 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 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 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
// Copyright 2012 Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
"github.com/hanwen/go-fuse/fuse"
"io/ioutil"
"log"
"os"
"syscall"
"time"
)

type DeviceFs struct {
fuse.DefaultNodeFileSystem
backingDir string
root *rootNode
dev *Device
}

/* DeviceFs is a simple filesystem interface to an MTP device. It
should be wrapped in a Locking(Raw)FileSystem to make sure it is
threadsafe. The file system assumes the device does not touch the
storage. Arguments are the opened mtp device and a directory for the
backing store. */

func NewDeviceFs(d *Device, dir string) *DeviceFs {
root := rootNode{}
fs := &DeviceFs{root: &root, dev: d, backingDir: dir}
root.fs = fs
return fs
}

/*
TODO:

- Moving between directories
- Something intelligent with playlists/pictures, maybe?
- Statfs?
- expose properties as xattrs?

*/
func (fs *DeviceFs) Root() fuse.FsNode {
return fs.root
}

func (fs *DeviceFs) newFolder(id uint32, storage uint32) *folderNode {
return &folderNode{
fileNode: fileNode{
storageId: storage,
id: id,
fs: fs,
},
}
}

func (fs *DeviceFs) newFile(file *File) *fileNode {
n := &fileNode{
storageId: file.StorageId(),
id: file.Id(),
file: file,
fs: fs,
}

return n
}

type rootNode struct {
fuse.DefaultFsNode
fs *DeviceFs
}

func (fs *DeviceFs) OnMount(conn *fuse.FileSystemConnector) {
for _, s := range fs.dev.ListStorage() {
folder := fs.newFolder(NOPARENT_ID, s.Id())
inode := fs.root.Inode().New(true, folder)
fs.root.Inode().AddChild(s.Description(), inode)
}
}

////////////////
// files

type fileNode struct {
fuse.DefaultFsNode
fs *DeviceFs

storageId uint32
id uint32

// Underlying mtp file. Maybe nil for the root of a storage.
file *File

// local file containing the contents.
backing string
// If set, the backing file was changed.
dirty bool
}

func (n *fileNode) OnForget() {
if n.file != nil {
n.file.Destroy()
n.file = nil
}
}

func (n *fileNode) send() error {
if !n.dirty {
return nil
}

if n.backing == "" {
log.Panicf("sending file without backing store: %q", n.file.Name())
}
fi, err := os.Stat(n.backing)
if err != nil {
log.Printf("could not do stat for send: %v", err)
return err
}
if fi.Size() == 0 {
log.Printf("cannot send 0 byte file %q", n.file.Name())
return syscall.EINVAL
}
f, err := os.Open(n.backing)
if err != nil {
return err
}
defer f.Close()

if n.file.Name() == "" {
return nil
}
log.Printf("Sending file %q to device: %d bytes.", n.file.Name(), fi.Size())
if n.file.Id() != 0 {
// Apparently, you can't overwrite things in MTP.
err := n.fs.dev.DeleteObject(n.file.Id())
if err != nil {
return err
}
}
n.file.SetFilesize(uint64(fi.Size()))
start := time.Now()
err = n.fs.dev.SendFromFileDescriptor(n.file, f.Fd())
dt := time.Now().Sub(start)
log.Printf("Sent %d bytes in %d ms. %.1f MB/s", fi.Size(),
dt.Nanoseconds()/1e6, 1e3*float64(fi.Size())/float64(dt.Nanoseconds()))
n.dirty = false
return err
}

// PTP supports partial fetch (not exposed in libmtp), but we might as
// well get the whole thing.
func (n *fileNode) fetch() error {
if n.backing != "" {
return nil
}

f, err := ioutil.TempFile(n.fs.backingDir, "")
if err != nil {
return err
}

defer f.Close()

err = n.fs.dev.GetFileToFileDescriptor(n.id, f.Fd())
if err == nil {
n.backing = f.Name()
}
return err
}

func (n *fileNode) Open(flags uint32, context *fuse.Context) (file fuse.File, code fuse.Status) {
n.fetch()
f, err := os.OpenFile(n.backing, int(flags), 0644)
if err != nil {
return nil, fuse.ToStatus(err)
}

if flags&fuse.O_ANYWRITE != 0 {
p := &pendingFile{
LoopbackFile: fuse.LoopbackFile{File: f},
node: n,
}
return p, fuse.OK
}
return &fuse.LoopbackFile{File: f}, fuse.OK
}

func (n *fileNode) Truncate(file fuse.File, size uint64, context *fuse.Context) (code fuse.Status) {
if file != nil {
return file.Truncate(size)
} else if n.backing != "" {
return fuse.ToStatus(os.Truncate(n.backing, int64(size)))
}
return fuse.OK
}

func (n *fileNode) GetAttr(out *fuse.Attr, file fuse.File, context *fuse.Context) (code fuse.Status) {
if file != nil {
return file.GetAttr(out)
}

out.Mode = fuse.S_IFREG | 0644

if n.backing != "" {
fi, err := os.Stat(n.backing)
if err != nil {
return fuse.ToStatus(err)
}
out.Size = uint64(fi.Size())
t := n.file.Mtime()
if n.dirty {
t = fi.ModTime()
}
out.SetTimes(&t, &t, &t)
} else if n.file != nil {
out.Size = uint64(n.file.filesize)

t := n.file.Mtime()
out.SetTimes(&t, &t, &t)
}

return fuse.OK
}

func (n *fileNode) Chown(file fuse.File, uid uint32, gid uint32, context *fuse.Context) (code fuse.Status) {
// Get rid of pesky messages from cp -a.
return fuse.OK
}

func (n *fileNode) Chmod(file fuse.File, perms uint32, context *fuse.Context) (code fuse.Status) {
// Get rid of pesky messages from cp -a.
return fuse.OK
}

func (n *fileNode) Utimens(file fuse.File, AtimeNs int64, MtimeNs int64, context *fuse.Context) (code fuse.Status) {
if n.file == nil {
return
}

// Unfortunately, we can't set the modtime; it's READONLY in
// the Android MTP implementation. We just change the time in
// the mount, but this is not persisted.
n.file.SetMtime(time.Unix(0, MtimeNs))
return fuse.OK
}

//////////////////
// folders

type folderNode struct {
fileNode
children map[string]*File
}

// Keep the root nodes for all device storages alive.
func (n *folderNode) Deletable() bool {
return n.id != NOPARENT_ID
}

// Fetches data from device returns false on failure.
func (n *folderNode) fetch() bool {
if n.children != nil {
return true
}
l, err := n.fs.dev.FilesAndFolders(n.storageId, n.id)
if err != nil {
log.Printf("FilesAndFolders failed: %v", err)
return false
}

n.children = map[string]*File{}
for _, f := range l {
n.children[f.Name()] = f
}
return true
}

func (n *folderNode) OpenDir(context *fuse.Context) (stream []fuse.DirEntry, status fuse.Status) {
if !n.fetch() {
return nil, fuse.EIO
}

stream = make([]fuse.DirEntry, 0, len(n.children))
for n, f := range n.children {
mode := fuse.S_IFREG | 0644
if f.Filetype() == FILETYPE_FOLDER {
mode = fuse.S_IFDIR | 0755
}

stream = append(stream, fuse.DirEntry{Name: n, Mode: uint32(mode)})
}
return stream, fuse.OK
}

func (n *folderNode) GetAttr(out *fuse.Attr, file fuse.File, context *fuse.Context) (code fuse.Status) {
out.Mode = fuse.S_IFDIR | 0755
return fuse.OK
}

func (n *folderNode) getChild(name string) (*File) {
return n.children[name]
}

func (n *folderNode) basenameRename(oldName string, newName string) error {
file := n.getChild(oldName)

err := n.fs.dev.SetFileName(file, newName)
if err != nil {
return err
}

delete(n.children, oldName)
n.children[newName] = file
ch := n.Inode().RmChild(oldName)
if ch == nil {
log.Panicf("child is not there for %q: got %v", oldName, n.Inode().Children())
}
n.Inode().AddChild(newName, ch)
return nil
}

func (n *folderNode) Rename(oldName string, newParent fuse.FsNode, newName string, context *fuse.Context) (code fuse.Status) {
fn, ok := newParent.(*folderNode);
if !ok {
return fuse.ENOSYS
}
fn.fetch()
n.fetch()

if f := n.getChild(newName); f != nil {
if fn != n {
log.Println("old folder already has child %q", newName)
return fuse.ENOSYS
} else {
// does mtp overwrite the destination?
}
}

if fn != n {
return fuse.ENOSYS
}

if newName != oldName {
err := n.basenameRename(oldName, newName)
if err != nil {
log.Printf("basenameRename failed: %v", err)
return fuse.EIO
}
}

return fuse.OK
}

func (n *folderNode) Lookup(out *fuse.Attr, name string, context *fuse.Context) (node fuse.FsNode, code fuse.Status) {
if !n.fetch() {
return nil, fuse.EIO
}
f := n.children[name]
if f == nil {
return nil, fuse.ENOENT
}

if f.Filetype() == FILETYPE_FOLDER {
fNode := n.fs.newFolder(f.Id(), n.storageId)
fNode.file = f
node = fNode
} else {
node = n.fs.newFile(f)
}

n.Inode().AddChild(name, n.Inode().New(true, node))
s := node.GetAttr(out, nil, context)
return node, s
}

func (n *folderNode) Mkdir(name string, mode uint32, context *fuse.Context) (fuse.FsNode, fuse.Status) {
if !n.fetch() {
return nil, fuse.EIO
}
newId, err := n.fs.dev.CreateFolder(n.id, name, n.storageId)
if err != nil {
log.Printf("CreateFolder failed: %v", err)
return nil, fuse.EIO
}

f := n.fs.newFolder(newId, n.storageId)
n.Inode().AddChild(name, n.Inode().New(true, f))

if meta, err := n.fs.dev.Filemetadata(newId); err != nil {
log.Printf("Filemetadata failed for directory %q: %v", name, err)
return nil, fuse.EIO
} else {
n.children[name] = meta
}
return f, fuse.OK
}

func (n *folderNode) Unlink(name string, c *fuse.Context) fuse.Status {
if !n.fetch() {
return fuse.EIO
}

f := n.getChild(name)
if f == nil {
return fuse.ENOENT
}

if f.Id() != 0 {
err := n.fs.dev.DeleteObject(f.Id())
if err != nil {
log.Printf("DeleteObject failed: %v", err)
return fuse.EIO
}
} else {
f.SetName("")
}
n.Inode().RmChild(name)

delete(n.children, name)
return fuse.OK
}

func (n *folderNode) Rmdir(name string, c *fuse.Context) fuse.Status {
return n.Unlink(name, c)
}

func (n *folderNode) Create(name string, flags uint32, mode uint32, context *fuse.Context) (file fuse.File, node fuse.FsNode, code fuse.Status) {
if !n.fetch() {
return nil, nil, fuse.EIO
}
f, err := ioutil.TempFile(n.fs.backingDir, "")
if err != nil {
return nil, nil, fuse.ToStatus(err)

}
now := time.Now()
fn := &fileNode{
storageId: n.storageId,
file: NewFile(0, n.id, n.storageId, name,
0, now, FILETYPE_UNKNOWN),
fs: n.fs,
dirty: true,
}
fn.backing = f.Name()
n.children[name] = fn.file
n.Inode().AddChild(name, n.Inode().New(false, fn))

p := &pendingFile{
LoopbackFile: fuse.LoopbackFile{File: f},
node: fn,
}

return p, fn, fuse.OK
}

////////////////
// writing files.

type pendingFile struct {
fuse.LoopbackFile
node *fileNode
}

func (p *pendingFile) Write(data []byte, off int64) (uint32, fuse.Status) {
p.node.dirty = true
return p.LoopbackFile.Write(data, off)
}

func (p *pendingFile) Truncate(size uint64) fuse.Status {
p.node.dirty = true
return p.LoopbackFile.Truncate(size)
}

func (p *pendingFile) Flush() fuse.Status {
code := p.LoopbackFile.Flush()
if !code.Ok() {
return code
}

s := fuse.ToStatus(p.node.send())
if s == fuse.ENOSYS {
return fuse.EIO
}
return s
}

func (p *pendingFile) Release() {
p.LoopbackFile.Release()
p.node.send()
}
Something went wrong with that request. Please try again.