update for writability
[rrq/fusefile.git] / fusefile.c
1 /***
2     fusefile - overlay a file path with a concatenation of parts of
3     other files, read only.
4
5     Copyright (C) 2019  Ralph Ronnquist
6
7     This program is free software: you can redistribute it and/or
8     modify it under the terms of the GNU General Public License as
9     published by the Free Software Foundation, either version 3 of the
10     License, or (at your option) any later version.
11
12     This program is distributed in the hope that it will be useful,
13     but WITHOUT ANY WARRANTY; without even the implied warranty of
14     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15     General Public License for more details.
16
17     You should have received a copy of the GNU General Public License
18     along with this program. If not, see
19     <http://www.gnu.org/licenses/>.
20
21     This source was inspired by the "null.c" example of the libfuse
22     sources, which is distributed under GPL2, and copyright (C)
23     2001-2007 Miklos Szeredi <miklos@szeredi.hu>.
24 */
25
26 #define FUSE_USE_VERSION 33
27
28 #include <fuse.h>
29 #include <fuse/fuse_lowlevel.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <unistd.h>
34 #include <time.h>
35 #include <errno.h>
36
37 struct Source {
38     char *filename;
39     ssize_t from;
40     ssize_t to;
41     ssize_t start; // starting position in concatenated file
42     int fd;
43 };
44
45 static struct {
46     struct Source *array;
47     int count;
48     ssize_t size;
49 } sources;
50
51 static struct {
52     time_t atime;
53     time_t mtime;
54     time_t ctime;
55 } times;
56     
57 #if DEBUG
58 static void print_source(struct Source *p) {
59     fprintf( stderr, "%p { %s, %ld, %ld, %ld, %d }\n",
60              p, p->filename, p->from, p->to, p->start, p-> fd );
61 }
62 #endif
63
64 // Scan the source specification, and return the length of the
65 // inclusion. "filename/from,to"
66 // filename
67 // filename/from
68 // filename/-to
69 // filename/from-to
70 static size_t scan_source(char *in,struct Source *p) {
71     int e = strlen( in );
72     int i = e-1;
73     int s = -1;
74     int m = -1;
75     // scan for last '/' and last '-'
76     for ( ; i >= 0; i-- ) {
77         if ( in[i] == '/' ) {
78             s = i;
79             break;
80         }
81         if ( in[i] == '-' ) {
82             m = i;
83         }
84     }
85 #if DEBUG
86     fprintf( stderr, "m=%d s=%d\n", m, s );
87 #endif
88     // Copy the filename, and set from and to
89     p->filename = strndup( in, ( s < 0 )? e : s );
90     struct stat buf;
91     if ( stat( p->filename, & buf ) ) {
92         perror( p->filename );
93         return 1; 
94     }
95     p->from = ( s < 0 )? 0 : atol( in+s+1 );
96     if ( p->from < 0 ) {
97         p->from = 0;
98     }
99 #if DEBUG
100     fprintf( stderr, "p->from=%ld\n", p->from );
101 #endif
102     p->to = ( m < 0 )? buf.st_size : atol( in+m+1 );
103     if ( p->from > p->to || p->to > buf.st_size ) {
104         return 1;
105     }
106     return 0;
107 }
108
109 static int setup_sources(char **argv,int i,int n) {
110     sources.array = calloc( n, sizeof( struct Source ) );
111     if ( sources.array == 0 ) {
112         return 1;
113     }
114     sources.count = n;
115     int j = 0;
116     sources.size = 0;
117     for ( ; j < n; i++, j++ ) {
118         struct Source *p = sources.array + j;
119         if ( scan_source( argv[i], p ) ) {
120             // should free everything malloc-ed
121             return 1;
122         }
123         p->start = sources.size;
124         sources.size += p->to - p->from;
125         p->fd = open( p->filename, O_RDWR );
126         if ( p->fd < 0 ) {
127             fprintf( stderr, "** %s opened read-only\n", p->filename );
128             p->fd = open( p->filename, O_RDONLY );
129         }
130         if ( p->fd < 0 ) {
131             perror( p->filename );
132             return 1;
133         }
134 #if DEBUG
135         print_source( p );
136 #endif
137     }
138     return 0;
139 }
140
141 static int fusefile_getattr(const char *path,struct stat *stbuf) {
142 #if DEBUG
143     fprintf( stderr, "fusefile_getattr( %s )\n", path );
144 #endif
145     if ( strcmp( path, "/" ) != 0 ) {
146         return -ENOENT;
147     }
148 #if DEBUG
149     fprintf( stderr, "getattr %ld\n", sources.size );
150 #endif
151     memset( stbuf, 0, sizeof( struct stat ) );
152     stbuf->st_mode = S_IFREG | 0644; // Hmmm
153     stbuf->st_nlink = 1;
154     stbuf->st_size = sources.size;
155     stbuf->st_atime = times.atime;
156     stbuf->st_mtime = times.mtime;
157     stbuf->st_ctime = times.ctime;
158     stbuf->st_uid = getuid();
159     stbuf->st_gid = getgid();
160     return 0;
161 }
162
163 static int fusefile_chmod(const char *path,mode_t m) {
164 #if DEBUG
165     fprintf( stderr, "fusefile_chmod( %s, %d )\n", path, m );
166 #endif
167     return -1;
168 }
169
170 static int fusefile_open(const char *path,struct fuse_file_info *fi) {
171 #if DEBUG
172     fprintf( stderr, "fusefile_open( %s, %d )\n", path, fi->flags );
173     fprintf( stderr, "fixing( %d )\n", fi->flags | O_CLOEXEC );
174 #endif
175     if ( strcmp( path, "/" ) != 0 ) {
176         return -ENOENT;
177     }
178     // set O-CLOEXEC  for this opening?
179     times.atime = time( 0 );
180     return 0;
181 }
182
183 static int find_source(off_t offset) {
184     int lo = 0;
185     int hi = sources.count;
186     if ( offset >= sources.size ) {
187         return -1;
188     }
189     while ( lo + 1 < hi ) {
190         int m = ( lo + hi ) / 2;
191         if ( offset < sources.array[ m ].start ) {
192             hi = m;
193         } else {
194             lo = m;
195         }
196     }
197     return lo;
198 }
199
200 // Read <size> bytes from <offset> in file
201 static int fusefile_read(const char *path, char *buf, size_t size,
202                          off_t off, struct fuse_file_info *fi)
203 {
204 #if DEBUG
205     fprintf( stderr, "fusefile_read( %s )\n", path );
206 #endif
207     if( strcmp( path, "/" ) != 0 ) {
208         return -ENOENT;
209     }
210 #if DEBUG
211     fprintf( stderr, "read %ld %ld\n", off, size );
212 #endif
213     size_t rr = 0;
214     while ( size > 0 ) {
215 #if DEBUG
216         fprintf( stderr, "find_source %ld %ld\n", off, size );
217 #endif
218         int i = find_source( off );
219         if ( i < 0 ) {
220             return ( off == sources.size )? rr : -ENOENT;
221         }
222         if ( sources.array[i].fd < 0 ) {
223             return -ENOENT;
224         }
225 #if DEBUG
226         print_source( &sources.array[i] );
227 #endif
228         size_t b = off - sources.array[i].start + sources.array[i].from;
229         size_t n = sources.array[i].to - b;
230         if ( n > size ) {
231             n = size;
232         }
233         if ( lseek( sources.array[i].fd, b, SEEK_SET ) < 0 ) {
234             perror( sources.array[i].filename );
235             return -ENOENT;
236         }
237 #if DEBUG
238         fprintf( stderr, "get %ld bytes at %ld\n", n, rr );
239 #endif
240         ssize_t r = read( sources.array[i].fd, buf + rr, n );
241 #if DEBUG
242         fprintf( stderr, "got %ld bytes\n", r );
243 #endif
244         if ( r < 0 ) {
245             perror( sources.array[i].filename );
246             return -ENOENT;
247         }
248         if ( r == 0 ) {
249             break;
250         }
251         rr += r;
252         off += r;
253         size -= r;
254     }
255     times.atime = time( 0 );
256     return rr;
257 }
258
259 /**
260  * Poll for IO readiness.
261  */
262 int fusefile_poll(const char *path, struct fuse_file_info *fi,
263                    struct fuse_pollhandle *ph, unsigned *reventsp )
264 {
265 #if DEBUG
266     fprintf( stderr, "fusefile_poll( %s ) %p %d\n", path, ph, *reventsp );
267 #endif
268     if( strcmp( path, "/" ) != 0 ) {
269         return -ENOENT;
270     }
271     if ( ph ) {
272         return fuse_notify_poll( ph );
273     }
274     return 0;
275 }
276
277
278 /**
279  * Write a full block of data over the sources at the offset
280  */
281 static int write_block(off_t off,const char *buf,size_t size) {
282 #if DEBUG
283     fprintf( stderr, "write_block( %ld, ?, %ld )\n", off, size );
284 #endif
285     while ( size > 0 ) {
286         int index = find_source( off ); // index of source file
287         if ( index < 0 ) {
288             return -EIO; // past EOF
289         }
290         struct Source *source = &sources.array[ index ];
291         off_t from = off - source->start + source->from;
292         off_t max = source->to - from;
293         if ( lseek( source->fd, from, SEEK_SET ) < 0 ) {
294             return -EIO;
295         }
296         ssize_t todo = ( size < max )? size : max;
297         while ( todo > 0 ) {
298             times.mtime = time( 0 );
299             ssize_t n = write( source->fd, buf, todo );
300             if ( n <= 0 ) {
301                 return -EIO; // Something wrong
302             }
303             buf += n;
304             todo -= n;
305             size -= n;
306             off += n;
307         }
308     }
309     return 0;
310 }
311
312 static int fusefile_write_buf(const char *path, struct fuse_bufvec *buf,
313                               off_t off, struct fuse_file_info *fi) {
314 #if DEBUG
315     fprintf( stderr, "fusefile_write_buf( %s )\n", path );
316 #endif
317     if ( strcmp( path, "/" ) != 0 ) {
318         return -ENOENT;
319     }
320
321     size_t size = 0;
322     int i;
323     for ( i = 0; i < buf->count; i++ ) {
324         struct fuse_buf *p = &buf->buf[i];
325         if ( p->flags & FUSE_BUF_IS_FD ) {
326 #if DEBUG
327             fprintf( stderr, "Content held in a file ... HELP!!\n" );
328 #endif
329             return -EIO;
330         }
331         if ( write_block( off, (char*) p->mem, p->size ) < 0 ) {
332             return -EIO;
333         }
334         size += p->size;
335     }
336 #if DEBUG
337     fprintf( stderr, "fusefile_write_buf written %ld\n", size );
338 #endif
339     return size;
340 }
341
342 /**
343  * Write a fragment at <off>. This overwrites files.
344  */
345 static int fusefile_write(const char *path, const char *buf, size_t size,
346                           off_t off, struct fuse_file_info *fi)
347 {
348 #if DEBUG
349     fprintf( stderr, "fusefile_write( %s %ld )\n", path, size );
350 #endif
351     if ( strcmp( path, "/" ) != 0 ) {
352         return -ENOENT;
353     }
354
355     if ( write_block( off, buf, size ) < 0 ) {
356         return -EIO;
357     }
358     return size;
359 }
360
361 static void fusefile_destroy(void *data) {
362     char *mnt = (char*) data; // As passed to fuse_main
363 #if DEBUG
364     fprintf( stderr, "fusefile_destroy( %s )\n", mnt? mnt : "" );
365 #endif
366     if ( mnt ) {
367         unlink( mnt );
368     }
369 }
370
371 static int fusefile_flush(const char *path, struct fuse_file_info *info) {
372 #if DEBUG
373     fprintf( stderr, "fusefile_flush( %s )\n", path );
374 #endif
375     if ( strcmp( path, "/" ) != 0 ) {
376         return -ENOENT;
377     }
378     return 0;
379 }
380
381 static int fusefile_release(const char *path, struct fuse_file_info *fi) {
382 #if DEBUG
383     fprintf( stderr, "fusefile_release( %s, %d )\n", path, fi->flags );
384 #endif
385     if ( strcmp( path, "/" ) != 0 ) {
386         return -ENOENT;
387     }
388     return 0;
389 }
390
391 static int fusefile_fsync(const char *path, int x, struct fuse_file_info *fi) {
392 #if DEBUG
393     fprintf( stderr, "fusefile_fsync( %s, %d )\n", path, x );
394 #endif
395     if ( strcmp( path, "/" ) != 0 ) {
396         return -ENOENT;
397     }
398     return 0;
399 }
400
401 /**
402  * 
403  */
404 static int fusefile_truncate(const char *path, off_t len) {
405 #if DEBUG
406     fprintf( stderr, "fusefile_truncate( %s, %ld )\n", path, len );
407 #endif
408     if ( strcmp( path, "/" ) != 0 ) {
409         return -ENOENT;
410     }
411     return -EIO;
412 }
413
414 static struct fuse_operations fusefile_oper = {
415     .getattr = fusefile_getattr,
416     .chmod = fusefile_chmod,
417     .open = fusefile_open,
418     .read = fusefile_read,
419     .poll = fusefile_poll,
420     .write = fusefile_write,
421     .write_buf = fusefile_write_buf,
422     .destroy = fusefile_destroy,
423     .flush = fusefile_flush,
424     .release = fusefile_release,
425     .fsync = fusefile_fsync,
426     .truncate = fusefile_truncate,
427     //.truncate = fusefile_truncate,
428     //.release = fusefile_release,
429     //void *(*init) (struct fuse_conn_info *conn);
430 };
431
432 static void usage() {
433     char *usage =
434 "Usage: fusefile [ <fuse options> ] <mount> <file/from-to> ... \n"
435 "Mounts a virtual, read-only file that is a concatenation of file fragments\n"
436         ;
437     fprintf( stderr, "%s", usage );
438     exit( 1 );
439 }
440
441 /**
442  * Set up the arguments for the fuse_main call, adding our own.
443  * argv[argc] is the mount point argument
444  */
445 static int setup_argv(int argc,char ***argv) {
446     // note: (*argv)[ argc ] is the mount point argument
447     char *OURS[] = {
448         "-odefault_permissions",
449         (*argv)[ argc ]
450     };
451 #define OURSN ( sizeof( OURS ) / sizeof( char* ) )
452     int N = argc + OURSN;
453     // Allocate new arg array plus terminating null pointer
454     char **out = malloc( ( N + 1 ) * sizeof( char* ) ); 
455     int i;
456     for ( i = 0; i < argc; i++ ) {
457         out[ i ] = (*argv)[i];
458         //fprintf( stderr, " %s", out[ i ] );
459     }
460     for ( i = 0; i < OURSN; i++ ) {
461         out[ argc + i ] = OURS[i];
462         //fprintf( stderr, " %s", out[ i ] );
463     }
464     out[ N ] = 0;
465     //fprintf( stderr, "\n" );
466     (*argv) = out;
467     return N; // Don't include the terminating null pointer
468 }
469
470 /**
471  * Mount a concatenation of files,
472  * [ <fuse options> ] <mount> <file/from-to> ...
473  */
474 int main(int argc, char *argv[])
475 {
476     char *mnt;
477     int mt;
478     int fg;
479     int i;
480     int fuseargc;
481     struct stat stbuf;
482     int temporary = 0;
483     // Scan past options
484     for ( i = 1; i < argc; i++ ) {
485         if ( *argv[i] != '-' ) {
486             break;
487         }
488     }
489     if ( i > argc - 2 ) { // At least mount point plus one source
490         usage();
491     }
492     fuseargc = i;
493     mnt = argv[ i++ ]; // First non-option argument is the mount pount
494     if ( setup_sources( argv, i, argc-i ) ) {
495         return 1;
496     }
497     if ( stat( mnt, &stbuf ) == -1 ) {
498         int fd = open( mnt, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR );
499         if ( fd < 0 ) {
500             perror( mnt );
501             return 1;
502         }
503         time_t now = time( 0 );
504         times.atime = now;
505         times.mtime = now;
506         times.ctime = now;
507         temporary = 1;
508         close( fd );
509     } else if ( ! S_ISREG( stbuf.st_mode ) ) {
510         fprintf( stderr, "mountpoint is not a regular file\n" );
511         return 1;
512     } else {
513         times.atime = stbuf.st_atime;
514         times.mtime = stbuf.st_mtime;
515         times.ctime = stbuf.st_ctime;
516     }
517
518     fuseargc = setup_argv( fuseargc, &argv );
519     struct fuse_args args = FUSE_ARGS_INIT( fuseargc, argv );
520     if ( fuse_parse_cmdline( &args, &mnt, &mt, &fg ) ) {
521         return 1;
522     }
523     fuse_opt_free_args( &args );
524     if ( ! mnt ) {
525         fprintf( stderr, "missing mountpoint parameter\n" );
526         return 1;
527     }
528     return fuse_main( fuseargc, argv, &fusefile_oper, temporary? mnt : NULL );
529 }