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
#![deny(missing_docs)]
#![forbid(unsafe_code)]

//! Expose `Read`+`Write`+`Seek` (or just `Read`+`Seek`) as a FUSE-backed regular file
//!
//! Example:
//! ```rust,no_run
//! extern crate fuse;
//! extern crate readwriteseekfs;
//! 
//! use std::fs::File;
//! use std::io::{Cursor, Result, Write};
//! 
//! fn main() -> Result<()> {
//!     let content = vec![0; 65536];
//!     let mut c = Cursor::new(content);
//!     c.write(b"Hello, world\n")?;
//!     let fs = readwriteseekfs::ReadWriteSeekFs::new(c, 1024)?;
//!     let _ = File::create(&"hello.txt");
//!     fuse::mount(fs, &"hello.txt", &[])
//! }
//!

extern crate fuse;
extern crate libc;
extern crate time;
use self::fuse::{
    FileAttr, FileType, Filesystem, ReplyAttr, ReplyData, ReplyEmpty, ReplyEntry, ReplyWrite,
    Request,
};
use self::time::Timespec;
use std::ffi::OsStr;
use std::io::{Error, ErrorKind, Read, Result, Seek, SeekFrom, Write};

const CREATE_TIME: Timespec = Timespec {
    sec: 1534631479,
    nsec: 0,
}; //FIXME

const TTL: Timespec = Timespec { sec: 9999, nsec: 0 };

use self::libc::{c_int, EROFS};
fn errmap(e: Error) -> c_int {
    use self::libc::*;
    use ErrorKind::*;
    // TODO parse Other's Display and derive more error codes
    match e.kind() {
        NotFound => ENOENT,
        PermissionDenied => EACCES,
        ConnectionRefused => ECONNREFUSED,
        ConnectionReset => ECONNREFUSED,
        ConnectionAborted => ECONNABORTED,
        NotConnected => ENOTCONN,
        AddrInUse => EADDRINUSE,
        AddrNotAvailable => EADDRNOTAVAIL,
        BrokenPipe => EPIPE,
        AlreadyExists => EEXIST,
        WouldBlock => EWOULDBLOCK,
        InvalidInput => EINVAL,
        InvalidData => EINVAL,
        TimedOut => ETIMEDOUT,
        WriteZero => EINVAL,
        UnexpectedEof => EINVAL,
        _ => EINVAL,
    }
}

trait MyReadEx: Read {
    // Based on https://doc.rust-lang.org/src/std/io/mod.rs.html#620
    fn read_exact2(&mut self, mut buf: &mut [u8]) -> ::std::io::Result<usize> {
        let mut successfully_read = 0;
        while !buf.is_empty() {
            match self.read(buf) {
                Ok(0) => break,
                Ok(n) => {
                    successfully_read += n;
                    let tmp = buf;
                    buf = &mut tmp[n..];
                }
                Err(ref e) if e.kind() == ::std::io::ErrorKind::Interrupted => {}
                Err(e) => return Err(e),
            }
        }
        Ok(successfully_read)
    }
}
impl<T: Read> MyReadEx for T {}

trait MyWriteEx: Write {
    fn write_all2(&mut self, mut buf: &[u8]) -> Result<usize> {
        let mut successfully_written = 0;
        while !buf.is_empty() {
            match self.write(buf) {
                Ok(0) => return Ok(successfully_written),
                Ok(n) => {
                    successfully_written += n;
                    buf = &buf[n..];
                }
                Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
                Err(e) => return Err(e),
            }
        }
        Ok(successfully_written)
    }
}
impl<T: Write> MyWriteEx for T {}

/// A read-only Filesystem for your Read+Seek [pseudo]file
pub struct ReadSeekFs<F: Read + Seek> {
    file: F,
    fa: FileAttr,
}

impl<F> ReadSeekFs<F>
where
    F: Read + Seek,
{
    /// Wrap your reader-seeking into a `fuse::Filesystem` implementation
    pub fn new(mut f: F, blocksize: usize) -> Result<ReadSeekFs<F>> {
        let len = f.seek(SeekFrom::End(0))?;
        let blocks = ((len - 1) / (blocksize as u64)) + 1;

        Ok(ReadSeekFs {
            file: f,
            fa: FileAttr {
                ino: 1,
                size: len,
                blocks: blocks,
                atime: CREATE_TIME,
                mtime: CREATE_TIME,
                ctime: CREATE_TIME,
                crtime: CREATE_TIME,
                kind: FileType::RegularFile,
                perm: 0o644,
                nlink: 1,
                uid: 0,
                gid: 0,
                rdev: 0,
                flags: 0,
            },
        })
    }

    fn seek(&mut self, offset: i64) -> Result<()> {
        if offset < 0 {
            Err(ErrorKind::InvalidInput)?;
        }
        self.file.seek(SeekFrom::Start(offset as u64))?;
        Ok(())
    }
    fn seek_and_read(&mut self, offset: i64, size: usize) -> Result<Vec<u8>> {
        self.seek(offset)?;
        let mut buf = vec![0; size as usize];
        let ret = self.file.read_exact2(&mut buf)?;
        buf.truncate(ret);
        Ok(buf)
    }
}

impl<F> Filesystem for ReadSeekFs<F>
where
    F: Read + Seek,
{
    fn lookup(&mut self, _req: &Request, _parent: u64, _name: &OsStr, reply: ReplyEntry) {
        reply.entry(&TTL, &self.fa, 0);
    }

    fn getattr(&mut self, _req: &Request, _ino: u64, reply: ReplyAttr) {
        reply.attr(&TTL, &self.fa);
    }

    fn read(
        &mut self,
        _req: &Request,
        _ino: u64,
        _fh: u64,
        offset: i64,
        size: u32,
        reply: ReplyData,
    ) {
        match self.seek_and_read(offset, size as usize) {
            Ok(buf) => reply.data(buf.as_slice()),
            Err(e) => reply.error(errmap(e)),
        }
    }

    fn write(
        &mut self,
        _req: &Request,
        _ino: u64,
        _fh: u64,
        _offset: i64,
        _data: &[u8],
        _flags: u32,
        reply: ReplyWrite,
    ) {
        reply.error(EROFS);
    }

    fn setattr(
        &mut self,
        _req: &Request,
        _ino: u64,
        _mode: Option<u32>,
        _uid: Option<u32>,
        _gid: Option<u32>,
        _size: Option<u64>,
        _atime: Option<Timespec>,
        _mtime: Option<Timespec>,
        _fh: Option<u64>,
        _crtime: Option<Timespec>,
        _chgtime: Option<Timespec>,
        _bkuptime: Option<Timespec>,
        _flags: Option<u32>,
        reply: ReplyAttr,
    ) {
        reply.error(EROFS);
    }
}

/// A read-write Filesystem for your Read+Write+Seek [pseudo]file
pub struct ReadWriteSeekFs<F: Read + Write + Seek>(ReadSeekFs<F>);

impl<F> ReadWriteSeekFs<F>
where
    F: Read + Write + Seek,
{
    /// Wrap your writable [pseudo]file into an implementation of `fuse::Filesystem`
    pub fn new(f: F, blocksize: usize) -> Result<ReadWriteSeekFs<F>> {
        Ok(ReadWriteSeekFs(ReadSeekFs::new(f, blocksize)?))
    }

    fn seek_and_write(&mut self, offset: i64, data: &[u8]) -> Result<usize> {
        self.0.seek(offset)?;
        self.0.file.write_all2(data)
    }
}

impl<F> Filesystem for ReadWriteSeekFs<F>
where
    F: Read + Write + Seek,
{
    fn lookup(&mut self, _req: &Request, _parent: u64, _name: &OsStr, reply: ReplyEntry) {
        reply.entry(&TTL, &self.0.fa, 0);
    }

    fn getattr(&mut self, _req: &Request, _ino: u64, reply: ReplyAttr) {
        reply.attr(&TTL, &self.0.fa);
    }

    fn read(
        &mut self,
        _req: &Request,
        ino: u64,
        _fh: u64,
        offset: i64,
        size: u32,
        reply: ReplyData,
    ) {
        self.0.read(_req, ino, _fh, offset, size, reply)
    }

    fn write(
        &mut self,
        _req: &Request,
        _ino: u64,
        _fh: u64,
        offset: i64,
        data: &[u8],
        _flags: u32,
        reply: ReplyWrite,
    ) {
        match self.seek_and_write(offset, data) {
            Ok(len) => reply.written(len as u32),
            Err(e) => reply.error(errmap(e)),
        }
    }

    fn flush(&mut self, _req: &Request, _ino: u64, _fh: u64, _lock_owner: u64, reply: ReplyEmpty) {
        match self.0.file.flush() {
            Ok(()) => reply.ok(),
            Err(e) => reply.error(errmap(e)),
        }
    }

    fn setattr(
        &mut self,
        _req: &Request,
        _ino: u64,
        _mode: Option<u32>,
        _uid: Option<u32>,
        _gid: Option<u32>,
        _size: Option<u64>,
        _atime: Option<Timespec>,
        _mtime: Option<Timespec>,
        _fh: Option<u64>,
        _crtime: Option<Timespec>,
        _chgtime: Option<Timespec>,
        _bkuptime: Option<Timespec>,
        _flags: Option<u32>,
        reply: ReplyAttr,
    ) {
        reply.attr(&TTL, &self.0.fa);
    }
}