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