5a51066232251a3db09dc310df5abdd4fbb6c043
[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 static char *range;
65 static unsigned int c;
66 static int RANGE(int SCAN,int N ) {
67     return ( SCAN == N ) && *(range+c) == 0;
68 }
69
70 static int setup_sources(char **argv,int i,int n) {
71     sources.array = calloc( n, sizeof( struct Source ) );
72     if ( sources.array == 0 ) {
73         return 1;
74     }
75     sources.count = n;
76     int j = 0;
77     sources.size = 0;
78     for ( ; j < n; i++, j++ ) {
79         struct stat filestat;
80         struct Source *p = sources.array + j;
81         // Open the fragment file rw if possible, else ro
82         range = strrchr( argv[i], '/' ); // last '/'
83         p->filename = range? strndup( argv[i], range - argv[i] ) : argv[i];
84         p->fd = open( p->filename, O_RDWR );
85         int rdonly = 0;
86         if ( p->fd < 0 ) {
87             rdonly = 1;
88             p->fd = open( p->filename, O_RDONLY );
89         }
90         if ( p->fd < 0 ) {
91             perror( p->filename );
92             return 1; // Error return
93         }
94         if ( stat( p->filename, &filestat ) ) {
95             perror( p->filename );
96             return 1; 
97         }
98         if ( rdonly ) {
99             fprintf( stderr, "** %s opened read-only\n", p->filename );
100         }
101         p->from = 0;
102         p->to = filestat.st_size;
103         // Process any range variation
104         if ( range && *(++range) ) {
105             unsigned int a,b;
106             if ( RANGE( sscanf( range, "%u-%u%n", &a, &b, &c ), 2 ) ) {
107                 p->from = a;
108                 p->to = b;
109             } else if ( RANGE( sscanf( range, "%u--%u%n", &a, &b, &c ), 2 ) ) {
110                 p->from = a;
111                 p->to -= b;
112             } else if ( RANGE( sscanf( range, "%u-%n", &a, &c ), 1 ) ) {
113                 p->from = a;
114             } else if ( RANGE( sscanf( range, "%u%n", &a, &c ), 1 ) ) {
115                 p->from = a;
116             } else if ( RANGE( sscanf( range, "-%u%n", &b, &c ), 1 ) ) {
117                 p->to = b;
118             } else if ( RANGE( sscanf( range, "--%u%n", &b, &c ), 1 ) ) {
119                 p->to -= b;
120             } else if ( RANGE( sscanf( range, "-%n", &c), 0 ) ) {
121                 // Acceptable as "start-end" range
122             } else {
123                 fprintf( stderr, "** BAD RANGE: %s\n", argv[i] );
124                 return 1;
125             }
126         }
127         p->start = sources.size; // the fusefile position of fragment
128         sources.size += p->to - p->from;
129 #if DEBUG
130         print_source( p );
131 #endif
132     }
133     return 0;
134 }
135
136 static int fusefile_getattr(const char *path,struct stat *stbuf) {
137 #if DEBUG
138     fprintf( stderr, "fusefile_getattr( %s )\n", path );
139 #endif
140     if ( strcmp( path, "/" ) != 0 ) {
141         return -ENOENT;
142     }
143 #if DEBUG
144     fprintf( stderr, "getattr %ld\n", sources.size );
145 #endif
146     memset( stbuf, 0, sizeof( struct stat ) );
147     stbuf->st_mode = S_IFREG | 0644; // Hmmm
148     stbuf->st_nlink = 1;
149     stbuf->st_size = sources.size;
150     stbuf->st_atime = times.atime;
151     stbuf->st_mtime = times.mtime;
152     stbuf->st_ctime = times.ctime;
153     stbuf->st_uid = getuid();
154     stbuf->st_gid = getgid();
155     return 0;
156 }
157
158 static int fusefile_chmod(const char *path,mode_t m) {
159 #if DEBUG
160     fprintf( stderr, "fusefile_chmod( %s, %d )\n", path, m );
161 #endif
162     return -1;
163 }
164
165 static int fusefile_open(const char *path,struct fuse_file_info *fi) {
166 #if DEBUG
167     fprintf( stderr, "fusefile_open( %s, %d )\n", path, fi->flags );
168     fprintf( stderr, "fixing( %d )\n", fi->flags | O_CLOEXEC );
169 #endif
170     if ( strcmp( path, "/" ) != 0 ) {
171         return -ENOENT;
172     }
173     // set O-CLOEXEC  for this opening?
174     times.atime = time( 0 );
175     return 0;
176 }
177
178 static int find_source(off_t offset) {
179     int lo = 0;
180     int hi = sources.count;
181     if ( offset >= sources.size ) {
182         return -1;
183     }
184     while ( lo + 1 < hi ) {
185         int m = ( lo + hi ) / 2;
186         if ( offset < sources.array[ m ].start ) {
187             hi = m;
188         } else {
189             lo = m;
190         }
191     }
192     return lo;
193 }
194
195 // Read <size> bytes from <offset> in file
196 static int fusefile_read(const char *path, char *buf, size_t size,
197                          off_t off, struct fuse_file_info *fi)
198 {
199 #if DEBUG
200     fprintf( stderr, "fusefile_read( %s )\n", path );
201 #endif
202     if( strcmp( path, "/" ) != 0 ) {
203         return -ENOENT;
204     }
205 #if DEBUG
206     fprintf( stderr, "read %ld %ld\n", off, size );
207 #endif
208     size_t rr = 0;
209     while ( size > 0 ) {
210 #if DEBUG
211         fprintf( stderr, "find_source %ld %ld\n", off, size );
212 #endif
213         int i = find_source( off );
214         if ( i < 0 ) {
215             return ( off == sources.size )? rr : -ENOENT;
216         }
217         if ( sources.array[i].fd < 0 ) {
218             return -ENOENT;
219         }
220 #if DEBUG
221         print_source( &sources.array[i] );
222 #endif
223         times.atime = time( 0 );
224         size_t b = off - sources.array[i].start + sources.array[i].from;
225         size_t n = sources.array[i].to - b;
226         if ( n > size ) {
227             n = size;
228         }
229         if ( lseek( sources.array[i].fd, b, SEEK_SET ) < 0 ) {
230             perror( sources.array[i].filename );
231             return -ENOENT;
232         }
233 #if DEBUG
234         fprintf( stderr, "get %ld bytes at %ld\n", n, rr );
235 #endif
236         ssize_t r = read( sources.array[i].fd, buf + rr, n );
237 #if DEBUG
238         fprintf( stderr, "got %ld bytes\n", r );
239 #endif
240         if ( r < 0 ) {
241             perror( sources.array[i].filename );
242             return -ENOENT;
243         }
244         if ( r == 0 ) {
245             break;
246         }
247         rr += r;
248         off += r;
249         size -= r;
250     }
251     return rr;
252 }
253
254 /**
255  * Poll for IO readiness.
256  */
257 int fusefile_poll(const char *path, struct fuse_file_info *fi,
258                    struct fuse_pollhandle *ph, unsigned *reventsp )
259 {
260 #if DEBUG
261     fprintf( stderr, "fusefile_poll( %s ) %p %d\n", path, ph, *reventsp );
262 #endif
263     if( strcmp( path, "/" ) != 0 ) {
264         return -ENOENT;
265     }
266     if ( ph ) {
267         return fuse_notify_poll( ph );
268     }
269     return 0;
270 }
271
272
273 /**
274  * Write a full block of data over the sources at the offset
275  */
276 static int write_block(off_t off,const char *buf,size_t size) {
277 #if DEBUG
278     fprintf( stderr, "write_block( %ld, ?, %ld )\n", off, size );
279 #endif
280     while ( size > 0 ) {
281         int index = find_source( off ); // index of source file
282         if ( index < 0 ) {
283             return -EIO; // past EOF
284         }
285         struct Source *source = &sources.array[ index ];
286         off_t from = off - source->start + source->from;
287         off_t max = source->to - from;
288         if ( lseek( source->fd, from, SEEK_SET ) < 0 ) {
289             return -EIO;
290         }
291         ssize_t todo = ( size < max )? size : max;
292         while ( todo > 0 ) {
293             times.mtime = time( 0 );
294             ssize_t n = write( source->fd, buf, todo );
295             if ( n <= 0 ) {
296                 return -EIO; // Something wrong
297             }
298             buf += n;
299             todo -= n;
300             size -= n;
301             off += n;
302         }
303     }
304     return 0;
305 }
306
307 static int fusefile_write_buf(const char *path, struct fuse_bufvec *buf,
308                               off_t off, struct fuse_file_info *fi) {
309 #if DEBUG
310     fprintf( stderr, "fusefile_write_buf( %s )\n", path );
311 #endif
312     if ( strcmp( path, "/" ) != 0 ) {
313         return -ENOENT;
314     }
315
316     size_t size = 0;
317     int i;
318     for ( i = 0; i < buf->count; i++ ) {
319         struct fuse_buf *p = &buf->buf[i];
320         if ( p->flags & FUSE_BUF_IS_FD ) {
321 #if DEBUG
322             fprintf( stderr, "Content held in a file ... HELP!!\n" );
323 #endif
324             return -EIO;
325         }
326         if ( write_block( off, (char*) p->mem, p->size ) < 0 ) {
327             return -EIO;
328         }
329         size += p->size;
330     }
331 #if DEBUG
332     fprintf( stderr, "fusefile_write_buf written %ld\n", size );
333 #endif
334     return size;
335 }
336
337 /**
338  * Write a fragment at <off>. This overwrites files.
339  */
340 static int fusefile_write(const char *path, const char *buf, size_t size,
341                           off_t off, struct fuse_file_info *fi)
342 {
343 #if DEBUG
344     fprintf( stderr, "fusefile_write( %s %ld )\n", path, size );
345 #endif
346     if ( strcmp( path, "/" ) != 0 ) {
347         return -ENOENT;
348     }
349
350     if ( write_block( off, buf, size ) < 0 ) {
351         return -EIO;
352     }
353     return size;
354 }
355
356 static void fusefile_destroy(void *data) {
357     char *mnt = (char*) data; // As passed to fuse_main
358 #if DEBUG
359     fprintf( stderr, "fusefile_destroy( %s )\n", mnt? mnt : "" );
360 #endif
361     if ( mnt ) {
362         unlink( mnt );
363     }
364 }
365
366 static int fusefile_flush(const char *path, struct fuse_file_info *info) {
367 #if DEBUG
368     fprintf( stderr, "fusefile_flush( %s )\n", path );
369 #endif
370     if ( strcmp( path, "/" ) != 0 ) {
371         return -ENOENT;
372     }
373     return 0;
374 }
375
376 static int fusefile_release(const char *path, struct fuse_file_info *fi) {
377 #if DEBUG
378     fprintf( stderr, "fusefile_release( %s, %d )\n", path, fi->flags );
379 #endif
380     if ( strcmp( path, "/" ) != 0 ) {
381         return -ENOENT;
382     }
383     return 0;
384 }
385
386 static int fusefile_fsync(const char *path, int x, struct fuse_file_info *fi) {
387 #if DEBUG
388     fprintf( stderr, "fusefile_fsync( %s, %d )\n", path, x );
389 #endif
390     if ( strcmp( path, "/" ) != 0 ) {
391         return -ENOENT;
392     }
393     return 0;
394 }
395
396 /**
397  * 
398  */
399 static int fusefile_truncate(const char *path, off_t len) {
400 #if DEBUG
401     fprintf( stderr, "fusefile_truncate( %s, %ld )\n", path, len );
402 #endif
403     if ( strcmp( path, "/" ) != 0 ) {
404         return -ENOENT;
405     }
406     return -EIO;
407 }
408
409 void *fusefile_init(struct fuse_conn_info *fci) {
410 #if DEBUG
411     fprintf( stderr, "fusefile_init( %d, %d )\n", fci->async_read, fci->want );
412 #endif
413     // Disable asynchronous reading
414     fci->async_read = 0;
415     fci->want &= ~FUSE_CAP_ASYNC_READ;
416 #if DEBUG
417     fprintf( stderr, "fusefile_init( %d, %d )\n", fci->async_read, fci->want );
418 #endif
419     return 0;
420 }
421
422 static struct fuse_operations fusefile_oper = {
423     .getattr = fusefile_getattr,
424     .chmod = fusefile_chmod,
425     .open = fusefile_open,
426     .read = fusefile_read,
427     .poll = fusefile_poll,
428     .write = fusefile_write,
429     .write_buf = fusefile_write_buf,
430     .destroy = fusefile_destroy,
431     .flush = fusefile_flush,
432     .release = fusefile_release,
433     .fsync = fusefile_fsync,
434     .truncate = fusefile_truncate,
435     //.truncate = fusefile_truncate,
436     //.release = fusefile_release,
437     .init = fusefile_init,
438 };
439
440 static void usage() {
441     char *usage =
442 "Usage: fusefile [ <fuse options> ] <mount> <file/from-to> ... \n"
443 "Mounts a virtual, read-only file that is a concatenation of file fragments\n"
444         ;
445     fprintf( stderr, "%s", usage );
446     exit( 1 );
447 }
448
449 /**
450  * Set up the arguments for the fuse_main call, adding our own.
451  * argv[argc] is the mount point argument
452  */
453 static int setup_argv(int argc,char ***argv) {
454     // note: (*argv)[ argc ] is the mount point argument
455     char *OURS[] = {
456         "-odefault_permissions",
457         (*argv)[ argc ]
458     };
459 #define OURSN ( sizeof( OURS ) / sizeof( char* ) )
460     int N = argc + OURSN;
461     // Allocate new arg array plus terminating null pointer
462     char **out = malloc( ( N + 1 ) * sizeof( char* ) ); 
463     int i;
464     for ( i = 0; i < argc; i++ ) {
465         out[ i ] = (*argv)[i];
466         //fprintf( stderr, " %s", out[ i ] );
467     }
468     for ( i = 0; i < OURSN; i++ ) {
469         out[ argc + i ] = OURS[i];
470         //fprintf( stderr, " %s", out[ i ] );
471     }
472     out[ N ] = 0;
473     //fprintf( stderr, "\n" );
474     (*argv) = out;
475     return N; // Don't include the terminating null pointer
476 }
477
478 /**
479  * Mount a concatenation of files,
480  * [ <fuse options> ] <mount> <file/from-to> ...
481  */
482 int main(int argc, char *argv[])
483 {
484     char *mnt;
485     int mt;
486     int fg;
487     int i;
488     int fuseargc;
489     struct stat stbuf;
490     int temporary = 0;
491     // Scan past options
492     for ( i = 1; i < argc; i++ ) {
493         if ( *argv[i] != '-' ) {
494             break;
495         }
496     }
497     if ( i > argc - 2 ) { // At least mount point plus one source
498         usage();
499     }
500     fuseargc = i;
501     mnt = argv[ i++ ]; // First non-option argument is the mount pount
502     if ( setup_sources( argv, i, argc-i ) ) {
503         return 1;
504     }
505     if ( stat( mnt, &stbuf ) == -1 ) {
506         int fd = open( mnt, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR );
507         if ( fd < 0 ) {
508             perror( mnt );
509             return 1;
510         }
511         time_t now = time( 0 );
512         times.atime = now;
513         times.mtime = now;
514         times.ctime = now;
515         temporary = 1;
516         close( fd );
517     } else if ( ! S_ISREG( stbuf.st_mode ) ) {
518         fprintf( stderr, "mountpoint is not a regular file\n" );
519         return 1;
520     } else {
521         times.atime = stbuf.st_atime;
522         times.mtime = stbuf.st_mtime;
523         times.ctime = stbuf.st_ctime;
524     }
525
526     fuseargc = setup_argv( fuseargc, &argv );
527     struct fuse_args args = FUSE_ARGS_INIT( fuseargc, argv );
528     if ( fuse_parse_cmdline( &args, &mnt, &mt, &fg ) ) {
529         return 1;
530     }
531     fuse_opt_free_args( &args );
532     if ( ! mnt ) {
533         fprintf( stderr, "missing mountpoint parameter\n" );
534         return 1;
535     }
536     return fuse_main( fuseargc, argv, &fusefile_oper, temporary? mnt : NULL );
537 }