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