editorial improvments and polishing
[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 Region {
38     off_t beg;
39     off_t end;
40 };
41
42 struct Source {
43     char *filename;
44     ssize_t from;
45     ssize_t to;
46     ssize_t start; // starting position in concatenated file
47     int fd;
48     int dirty;
49 };
50
51 static struct {
52     struct Source *array;
53     int count;
54     ssize_t size;
55 } sources;
56
57 static struct {
58     time_t atime;
59     time_t mtime;
60     time_t ctime;
61 } times;
62
63 /**
64  * Overlay
65  */
66 static struct {
67     struct Source source;
68     struct Region *table;
69     size_t count;
70     size_t limit;
71 } overlay;
72
73 static void usage();
74
75 /**
76  * Find the nearest overlay.table region below pos. Returns the index,
77  * or -1 if there is none, i.e. pos < overlay.table[0].
78  */
79 static ssize_t overlay_prior_fragment(off_t pos) {
80     size_t lo = 0, hi = overlay.count;
81     while ( lo < hi ) {
82         size_t m = ( lo + hi ) / 2;
83         if ( m == lo ) {
84             return overlay.table[m].beg <= pos? m : -1;
85         }
86         if ( overlay.table[m].beg <= pos ) {
87             lo = m;
88         } else {
89             hi = m;
90         }
91     }
92     return -1;
93 }
94
95 /**
96  * Save the entry count for overlay.table as 64-bit integer
97  * immediately following the overlay content at the index
98  * corresponding to the fused file size.
99  */
100 static void overlay_save_count() {
101     lseek( overlay.source.fd, overlay.source.to, SEEK_SET );
102     size_t size = sizeof( overlay.count );
103     char *p = (char *) &overlay.count ;
104     while ( size > 0 ) {
105         size_t n = write( overlay.source.fd, p, size );
106         if ( n < 0 ) {
107             perror( overlay.source.filename );
108             exit( 1 );
109         }
110         size -= n;
111         p += n;
112     }
113     if ( overlay.source.dirty++ > 1000 ) {
114         fsync( overlay.source.fd );
115         overlay.source.dirty = 0;
116     }
117 }
118
119 /**
120  * Update the on-disk cache of overlay.table between the given
121  * indexes. The table is laid out immediately following the table
122  * count with each region saved as two 64-bit unsigned integers.
123  */
124 static void overlay_save_table(size_t lo,size_t hi) {
125     char *p = (char *) &overlay.table[ lo ];
126     size_t pos =  overlay.source.to + sizeof( overlay.count ) +
127         lo * sizeof( struct Region );
128     size_t size = ( hi - lo ) * sizeof( struct Region );
129     if ( pos != lseek( overlay.source.fd, pos, SEEK_SET ) ) {
130         fprintf( stderr, "%s: seek error\n", overlay.source.filename );
131         exit( 1 );
132     }
133     while ( size > 0 ) {
134         size_t n = write( overlay.source.fd, p, size );
135         if ( n < 0 ) {
136             perror( overlay.source.filename );
137             exit( 1 );
138         }
139         size -= n;
140         p += n;
141     }
142     if ( overlay.source.dirty++ > 1000 ) {
143         fsync( overlay.source.fd );
144         overlay.source.dirty = 0;
145     }
146 }
147
148 /**
149  * Insert a new region at index p, with previous portion [p,count]
150  * moved up to make space.
151  */
152 static void overlay_insert(size_t p,off_t beg,off_t end) {
153     size_t bytes;
154     // Grow the table if needed
155     if ( overlay.count >= overlay.limit ) {
156         overlay.limit = overlay.count + 10;
157         bytes = overlay.limit * sizeof( struct Region );
158         overlay.table = overlay.table?
159             realloc( overlay.table, bytes ) : malloc( bytes );
160     }
161     bytes = ( overlay.count++ - p ) * sizeof( struct Region );
162     if ( bytes ) {
163         memmove( (char*) &overlay.table[ p+1 ],
164                  (char*) &overlay.table[ p ],
165                  bytes );
166     }
167     overlay.table[ p ].beg = beg;
168     overlay.table[ p ].end = end;
169     overlay_save_count();
170 }
171
172 /**
173  * Delete the region entry at p by moving the portion [p+1,count]
174  * down.
175  */
176 static void overlay_delete(size_t p) {
177     size_t bytes = ( --overlay.count - p ) * sizeof( struct Region );
178     if ( bytes ) {
179         memmove( (char*) &overlay.table[ p ],
180                  (char*) &overlay.table[ p+1 ],
181                  bytes );
182     }
183 }
184
185 /**
186  * Mark the given region as updated, i.e. written to the overlay. The
187  * mark region may attach to prior marked regions or be a new,
188  * separate region. If attaching, it causes the prior regions to
189  * expand and the table adjusted by deleting any regions that become
190  * fully contained in other regions.
191  */
192 static void overlay_mark(off_t beg,off_t end) {
193 #if DEBUG
194     fprintf( stderr, "overlay_mark( %ld, %ld )\n", beg, end );
195 #endif
196     int deleted = 0;
197     ssize_t q;
198     ssize_t p = overlay_prior_fragment( beg );
199     // p is the nearest region below or at beg (or -1)
200     if ( p >= 0 && beg <= overlay.table[p].end ) {
201         // p overlaps mark region
202         if ( end <= overlay.table[p].end ) {
203             // region p covers mark region already
204 #if DEBUG
205             fprintf( stderr, "overlay covering ( %ld %ld )\n",
206                      overlay.table[p].beg, overlay.table[p].end );
207 #endif
208             return;
209         }
210         // the new mark region extends region p
211         overlay.table[p].end = end;
212         q = p+1;
213         while ( q < overlay.count &&
214                 overlay.table[q].beg <= overlay.table[p].end ) {
215             // Extended region merges with subsequent region
216             if ( overlay.table[p].end < overlay.table[q].end ) {
217                 overlay.table[p].end = overlay.table[q].end;
218             }
219             overlay_delete( q );
220             deleted++;
221         }
222         if ( deleted ) {
223             overlay_save_count();
224             q = overlay.count;
225         }
226         overlay_save_table( p, q );
227 #if DEBUG
228         fprintf( stderr, "overlay expand ( %ld %ld ) deleted %d\n",
229                  overlay.table[p].beg, overlay.table[p].end, deleted );
230 #endif
231         return;
232     }
233     // The prior region p does not expand into new mark region
234     p++; // subsequent region 
235     if ( p >= overlay.count || end < overlay.table[p].beg ) {
236         // New mark region is a separate region at p
237         overlay_insert( p, beg, end );
238 #if DEBUG
239         fprintf( stderr, "overlay new ( %ld %ld )\n",
240                  overlay.table[p].beg, overlay.table[p].end );
241 #endif
242         overlay_save_table( p, overlay.count );
243         return;
244     }
245     // New marks start before and overlap with region p => change p
246     // and handle any subsequent regions being covered
247     overlay.table[p].beg = beg;
248     q = p+1;
249     if ( overlay.table[p].end < end ) {
250         overlay.table[p].end = end;
251         while ( q < overlay.count &&
252                 overlay.table[q].beg <= overlay.table[p].end ) {
253             if ( overlay.table[p].end < overlay.table[q].end ) {
254                 overlay.table[p].end = overlay.table[q].end;
255             }
256             overlay_delete( q );
257             deleted++;
258         }
259         if ( deleted ) {
260             overlay_save_count();
261             q = overlay.count;
262         }
263     }
264     overlay_save_table( p, q );
265 #if DEBUG
266     fprintf( stderr, "overlay before ( %ld %ld ) deleted %d\n",
267              overlay.table[p].beg, overlay.table[p].end, deleted );
268 #endif
269 }
270
271 static void setup_overlay(char *filename) {
272     overlay.source.filename = filename;
273     overlay.source.fd = open( filename, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR );
274     if ( overlay.source.fd < 0 ) {
275         perror( filename );
276         usage();
277     }
278 }
279
280 #if DEBUG
281 static void print_source(struct Source *p) {
282     fprintf( stderr, "%p { %s, %ld, %ld, %ld, %d }\n",
283              p, p->filename, p->from, p->to, p->start, p-> fd );
284 }
285 #endif
286
287 static char *range;
288 static unsigned int c;
289 static int RANGE(int s,int n ) {
290     return ( s == n ) && *(range+c) == 0;
291 }
292
293 static int setup_sources(char **argv,int i,int n) {
294     sources.array = calloc( n, sizeof( struct Source ) );
295     if ( sources.array == 0 ) {
296         return 1;
297     }
298     sources.count = n;
299     int j = 0;
300     sources.size = 0;
301     for ( ; j < n; i++, j++ ) {
302         struct stat filestat;
303         struct Source *p = sources.array + j;
304         // Open the fragment file rw if possible, else ro
305         range = strrchr( argv[i], '/' ); // last '/'
306         p->filename = range? strndup( argv[i], range - argv[i] ) : argv[i];
307         p->fd = open( p->filename, O_RDWR );
308         int rdonly = 0;
309         if ( p->fd < 0 ) {
310             rdonly = 1;
311             p->fd = open( p->filename, O_RDONLY );
312         }
313         if ( p->fd < 0 ) {
314             perror( p->filename );
315             return 1; // Error return
316         }
317         if ( stat( p->filename, &filestat ) ) {
318             perror( p->filename );
319             return 1; 
320         }
321         if ( rdonly ) {
322             fprintf( stderr, "** %s opened read-only\n", p->filename );
323         }
324         p->from = 0;
325         p->to = filestat.st_size;
326         // Process any range variation
327         if ( range && *(++range) ) {
328             int a,b;
329             if ( 0 ) {
330             } else if ( RANGE( sscanf( range, "%d:%d%n", &a, &b, &c ), 2 )) {
331                 p->from = ( a < 0 )? ( p->to + a ) : a;
332                 p->to = ( b < 0 )? ( p->to + b ) : b;
333             } else if ( RANGE( sscanf( range, "%d+%d%n", &a, &b, &c ), 2 )) {
334                 p->from = ( a < 0 )? ( p->to + a ) : a;
335                 p->to = ( ( b < 0 )? p->to : p->from ) + b;
336             } else if ( RANGE( sscanf( range, "%d+%n", &a, &c ), 1 )) {
337                 p->from = ( a < 0 )? ( p->to + a ) : a;
338             } else if ( RANGE( sscanf( range, ":%d%n", &b, &c ), 1 )) {
339                 p->to = ( b < 0 )? ( p->to + b ) : b;
340             } else if ( RANGE( sscanf( range, "%d:%n", &a, &c ), 1 )) {
341                 p->from = ( a < 0 )? ( p->to + a ) : a;
342             } else if ( RANGE( sscanf( range, "%d%n", &a, &c ), 1 )) {
343                 if ( a >= 0 ) {
344                     p->from = a;
345                 } else {
346                     p->from = p->to + a;
347                 }
348             } else if ( RANGE( sscanf( range, ":%n", &c), 0 ) ) {
349                 // to end from start
350             } else {
351                 fprintf( stderr, "** BAD RANGE: %s\n", argv[i] );
352                 return 1;
353             }
354         }
355         if ( ( filestat.st_mode &  S_IFMT ) == S_IFCHR ) {
356             filestat.st_size = p->to; // Pretend size of character device
357         }
358         if ( p->from < 0 ) {
359             p->from = 0;
360         }
361         if ( p->to > filestat.st_size ) {
362             p->to = filestat.st_size;
363         }
364         if ( p->from >= p->to || p->from >= filestat.st_size ) {
365             fprintf( stderr, "** BAD RANGE: %s [%ld:%ld]\n",
366                      argv[i], p->from, p->to );
367             return 1;
368         }
369         p->start = sources.size; // the fusefile position of fragment
370         sources.size += p->to - p->from;
371 #if DEBUG
372         print_source( p );
373 #endif
374     }
375     return 0;
376 }
377
378 static int fusefile_getattr(const char *path,struct stat *stbuf) {
379 #if DEBUG
380     fprintf( stderr, "fusefile_getattr( %s )\n", path );
381 #endif
382     if ( strcmp( path, "/" ) != 0 ) {
383         return -ENOENT;
384     }
385 #if DEBUG
386     fprintf( stderr, "getattr %ld\n", sources.size );
387 #endif
388     memset( stbuf, 0, sizeof( struct stat ) );
389     stbuf->st_mode = S_IFREG | 0644; // Hmmm
390     stbuf->st_nlink = 1;
391     stbuf->st_size = sources.size;
392     stbuf->st_atime = times.atime;
393     stbuf->st_mtime = times.mtime;
394     stbuf->st_ctime = times.ctime;
395     stbuf->st_uid = getuid();
396     stbuf->st_gid = getgid();
397     return 0;
398 }
399
400 static int fusefile_chmod(const char *path,mode_t m) {
401 #if DEBUG
402     fprintf( stderr, "fusefile_chmod( %s, %d )\n", path, m );
403 #endif
404     return -1;
405 }
406
407 static int fusefile_open(const char *path,struct fuse_file_info *fi) {
408 #if DEBUG
409     fprintf( stderr, "fusefile_open( %s, %d )\n", path, fi->flags );
410     fprintf( stderr, "fixing( %d )\n", fi->flags | O_CLOEXEC );
411 #endif
412     if ( strcmp( path, "/" ) != 0 ) {
413         return -ENOENT;
414     }
415     // set O-CLOEXEC  for this opening?
416     times.atime = time( 0 );
417     return 0;
418 }
419
420 static int find_source(off_t offset) {
421     int lo = 0;
422     int hi = sources.count;
423     if ( offset >= sources.size ) {
424         return -1;
425     }
426 #if DEBUG
427     fprintf( stderr, "find_source( %ld )\n", offset );
428 #endif
429     while ( lo + 1 < hi ) {
430         int m = ( lo + hi ) / 2;
431         if ( offset < sources.array[ m ].start ) {
432 #if DEBUG
433             fprintf( stderr, "  offset < [%d].start: %ld\n",
434                      m, sources.array[ m ].start );
435 #endif
436             hi = m;
437         } else {
438 #if DEBUG
439             fprintf( stderr, "  offset >= [%d].start: %ld\n",
440                      m, sources.array[ m ].start );
441 #endif
442             lo = m;
443         }
444     }
445 #if DEBUG
446     fprintf( stderr, "found %d\n", lo );
447 #endif
448     return lo;
449 }
450
451 static int overlay_merge(char *buf,off_t beg,off_t end) {
452 #if DEBUG
453     fprintf( stderr, "merge %ld %ld\n", beg, end );
454 #endif
455     // Find nearest overlay data before or at beg
456     ssize_t p = overlay_prior_fragment( beg );
457     if ( p < 0 ) {
458         p = 0;
459     }
460     for ( ; p < overlay.count && overlay.table[p].beg < end; p++ ) {
461         if ( overlay.table[p].end < beg ) {
462             continue;
463         }
464         if ( overlay.table[p].beg > beg ) {
465             size_t delta = overlay.table[p].beg - beg;
466             buf += delta;
467             beg += delta;
468         }
469         size_t size = ( overlay.table[p].end <= end )?
470             ( overlay.table[p].end - beg ) : ( end - beg ); 
471         lseek( overlay.source.fd, beg, SEEK_SET );
472         while ( size > 0 ) {
473             size_t n = read( overlay.source.fd, buf, size );
474             size -= n;
475             buf += n;
476             beg += n; //
477         }
478     }
479     return 0;
480 }
481
482 // Read <size> bytes from <offset> in file
483 static int fusefile_read(const char *path, char *buf, size_t size,
484                          off_t off, struct fuse_file_info *fi)
485 {
486 #if DEBUG
487     fprintf( stderr, "fusefile_read( %s )\n", path );
488 #endif
489     if( strcmp( path, "/" ) != 0 ) {
490         return -ENOENT;
491     }
492 #if DEBUG
493     fprintf( stderr, "read %ld %ld\n", off, size );
494 #endif
495     size_t rr = 0; // total reading
496     while ( size > 0 ) {
497 #if DEBUG
498         fprintf( stderr, "  find_source %ld %ld\n", off, size );
499 #endif
500         int i = find_source( off );
501         if ( i < 0 ) {
502             return ( off == sources.size )? rr : -ENOENT;
503         }
504         if ( sources.array[i].fd < 0 ) {
505             return -ENOENT;
506         }
507 #if DEBUG
508         print_source( &sources.array[i] );
509 #endif
510         times.atime = time( 0 );
511         size_t b = off - sources.array[i].start + sources.array[i].from;
512         size_t n = sources.array[i].to - b;
513         if ( n > size ) {
514             n = size;
515         }
516         if ( sources.array[i].dirty ) {
517             fsync( sources.array[i].fd );
518             sources.array[i].dirty = 0;
519         }
520 #if DEBUG
521         fprintf( stderr, "  seek fd=%d to %ld\n", sources.array[i].fd, b );
522 #endif
523         if ( lseek( sources.array[i].fd, b, SEEK_SET ) < 0 ) {
524             perror( sources.array[i].filename );
525             return -ENOENT;
526         }
527 #if DEBUG
528         fprintf( stderr, "  now read %ld from fd=%d\n",
529                  n, sources.array[i].fd );
530 #endif
531         ssize_t r = read( sources.array[i].fd, buf + rr, n );
532 #if DEBUG
533         fprintf( stderr, "  got %ld bytes\n", r );
534 #endif
535         if ( r < 0 ) {
536             perror( sources.array[i].filename );
537             return -ENOENT;
538         }
539         if ( r == 0 ) {
540             break;
541         }
542         if ( overlay.source.filename ) {
543             if ( overlay.source.dirty ) {
544                 fsync( overlay.source.fd );
545                 overlay.source.dirty = 0;
546             }
547             int x = overlay_merge( buf + rr, off + rr, off + rr + r );
548             if ( x ) {
549                 return x;
550             }
551         }
552         rr += r;
553         off += r;
554         size -= r;
555     }
556 #if DEBUG
557     fprintf( stderr, "  total reading %ld bytes\n", rr );
558 #endif
559     return rr;
560 }
561
562 /**
563  * Poll for IO readiness.
564  */
565 int fusefile_poll(const char *path, struct fuse_file_info *fi,
566                    struct fuse_pollhandle *ph, unsigned *reventsp )
567 {
568 #if DEBUG
569     fprintf( stderr, "fusefile_poll( %s ) %p %d\n", path, ph, *reventsp );
570 #endif
571     if( strcmp( path, "/" ) != 0 ) {
572         return -ENOENT;
573     }
574     if ( ph ) {
575         return fuse_notify_poll( ph );
576     }
577     return 0;
578 }
579
580 static void overlay_load() {
581     lseek( overlay.source.fd, overlay.source.to, SEEK_SET );
582     size_t x = 0;
583     size_t size = sizeof( overlay.count );
584     if ( read( overlay.source.fd, &x, size ) != size ) {
585         return;
586     }
587 #if DEBUG
588     fprintf( stderr, "overlay: %s with %ld regions\n",
589              overlay.source.filename, x );
590 #endif
591     struct Region f = { 0, 0 };
592     size = sizeof( struct Region );
593     while ( x-- > 0 ) {
594         if ( read( overlay.source.fd, &f, size ) != size ) {
595             fprintf( stderr, "%s: bad meta data\n", overlay.source.filename );
596             exit( 1 );
597         }
598 #if DEBUG
599         fprintf( stderr, "overlay region: %ld %ld\n", f.beg, f.end );
600 #endif
601         overlay_mark( f.beg, f.end );
602     }
603 }
604
605 /**
606  * Write a full block of data over the sources at the offset
607  */
608 static int write_block(off_t off,const char *buf,size_t size) {
609 #if DEBUG
610     fprintf( stderr, "write_block( %ld, ?, %ld )\n", off, size );
611 #endif
612     if ( overlay.source.filename ) {
613         overlay_mark( off, off + size ); // Mark region as written
614     }
615     while ( size > 0 ) {
616         int index = find_source( off ); // index of source file
617         if ( index < 0 ) {
618             return -EIO; // past EOF
619         }
620         struct Source *source = overlay.source.filename?
621             &overlay.source :  &sources.array[ index ];
622         off_t from = off - source->start + source->from;
623         off_t max = source->to - from;
624         if ( lseek( source->fd, from, SEEK_SET ) < 0 ) {
625             return -EIO;
626         }
627         ssize_t todo = ( size < max )? size : max;
628         while ( todo > 0 ) {
629             times.mtime = time( 0 );
630             ssize_t n = write( source->fd, buf, todo );
631             if ( n <= 0 ) {
632                 return -EIO; // Something wrong
633             }
634             buf += n;
635             todo -= n;
636             size -= n;
637             off += n;
638         }
639         if ( source->dirty++ >= 1000 ) {
640             fsync( source->fd );
641             source->dirty = 0;
642         }
643     }
644     return 0;
645 }
646
647 static int fusefile_write_buf(const char *path, struct fuse_bufvec *buf,
648                               off_t off, struct fuse_file_info *fi) {
649 #if DEBUG
650     fprintf( stderr, "fusefile_write_buf( %s )\n", path );
651 #endif
652     if ( strcmp( path, "/" ) != 0 ) {
653         return -ENOENT;
654     }
655
656     size_t size = 0;
657     int i;
658     for ( i = 0; i < buf->count; i++ ) {
659         struct fuse_buf *p = &buf->buf[i];
660         if ( p->flags & FUSE_BUF_IS_FD ) {
661 #if DEBUG
662             fprintf( stderr, "Content held in a file ... HELP!!\n" );
663 #endif
664             return -EIO;
665         }
666         if ( write_block( off, (char*) p->mem, p->size ) < 0 ) {
667             return -EIO;
668         }
669         size += p->size;
670     }
671 #if DEBUG
672     fprintf( stderr, "fusefile_write_buf written %ld\n", size );
673 #endif
674     return size;
675 }
676
677 /**
678  * Write a fragment at <off>. This overwrites files.
679  */
680 static int fusefile_write(const char *path, const char *buf, size_t size,
681                           off_t off, struct fuse_file_info *fi)
682 {
683 #if DEBUG
684     fprintf( stderr, "fusefile_write( %s %ld )\n", path, size );
685 #endif
686     if ( strcmp( path, "/" ) != 0 ) {
687         return -ENOENT;
688     }
689
690     if ( write_block( off, buf, size ) < 0 ) {
691         return -EIO;
692     }
693     return size;
694 }
695
696 static void fusefile_destroy(void *data) {
697     char *mnt = (char*) data; // As passed to fuse_main
698 #if DEBUG
699     fprintf( stderr, "fusefile_destroy( %s )\n", mnt? mnt : "" );
700 #endif
701     if ( mnt ) {
702         unlink( mnt );
703     }
704 }
705
706 static void fsync_all_dirty() {
707     int i = 0;
708     for ( ; i < sources.count; i++ ) {
709         if ( sources.array[i].dirty ) {
710             fsync( sources.array[i].fd );
711             sources.array[i].dirty = 0;
712         }
713     }
714     if ( overlay.source.filename && overlay.source.dirty ) {
715         fsync( overlay.source.fd );
716         overlay.source.dirty = 0;
717     }
718 }
719
720 static int fusefile_flush(const char *path, struct fuse_file_info *info) {
721 #if DEBUG
722     fprintf( stderr, "fusefile_flush( %s )\n", path );
723 #endif
724     if ( strcmp( path, "/" ) != 0 ) {
725         return -ENOENT;
726     }
727     fsync_all_dirty();
728     return 0;
729 }
730
731 static int fusefile_release(const char *path, struct fuse_file_info *fi) {
732 #if DEBUG
733     fprintf( stderr, "fusefile_release( %s, %d )\n", path, fi->flags );
734 #endif
735     if ( strcmp( path, "/" ) != 0 ) {
736         return -ENOENT;
737     }
738     return 0;
739 }
740
741 static int fusefile_fsync(const char *path, int x, struct fuse_file_info *fi) {
742 #if DEBUG
743     fprintf( stderr, "fusefile_fsync( %s, %d )\n", path, x );
744 #endif
745     if ( strcmp( path, "/" ) != 0 ) {
746         return -ENOENT;
747     }
748     fsync_all_dirty();
749     return 0;
750 }
751
752 /**
753  * 
754  */
755 static int fusefile_truncate(const char *path, off_t len) {
756 #if DEBUG
757     fprintf( stderr, "fusefile_truncate( %s, %ld )\n", path, len );
758 #endif
759     if ( strcmp( path, "/" ) != 0 ) {
760         return -ENOENT;
761     }
762     return -EIO;
763 }
764
765 void *fusefile_init(struct fuse_conn_info *fci) {
766 #if DEBUG
767     fprintf( stderr, "fusefile_init( %d, %d )\n", fci->async_read, fci->want );
768 #endif
769     // Disable asynchronous reading
770     fci->async_read = 0;
771     fci->want &= ~FUSE_CAP_ASYNC_READ;
772 #if DEBUG
773     fprintf( stderr, "fusefile_init( %d, %d )\n", fci->async_read, fci->want );
774 #endif
775     return 0;
776 }
777
778 static struct fuse_operations fusefile_oper = {
779     .getattr = fusefile_getattr,
780     .chmod = fusefile_chmod,
781     .open = fusefile_open,
782     .read = fusefile_read,
783     .poll = fusefile_poll,
784     .write = fusefile_write,
785     .write_buf = fusefile_write_buf,
786     .destroy = fusefile_destroy,
787     .flush = fusefile_flush,
788     .release = fusefile_release,
789     .fsync = fusefile_fsync,
790     .truncate = fusefile_truncate,
791     //.truncate = fusefile_truncate,
792     //.release = fusefile_release,
793     .init = fusefile_init,
794 };
795
796 static void usage() {
797     char *usage =
798 "Usage: fusefile [ <fuse options> ] <mount> <file/from-to> ... \n"
799 "Mounts a virtual, file that is a concatenation of file fragments\n"
800         ;
801     fprintf( stderr, "%s", usage );
802     exit( 1 );
803 }
804
805 /**
806  * Set up the arguments for the fuse_main call, adding our own.
807  * argv[argc] is the mount point argument
808  */
809 static int setup_argv(int argc,char ***argv) {
810     // note: (*argv)[ argc ] is the mount point argument
811     char *OURS[] = {
812         "-odefault_permissions",
813         (*argv)[ argc ]
814     };
815 #define OURSN ( sizeof( OURS ) / sizeof( char* ) )
816     int N = argc + OURSN;
817     // Allocate new arg array plus terminating null pointer
818     char **out = malloc( ( N + 1 ) * sizeof( char* ) ); 
819     int i;
820     for ( i = 0; i < argc; i++ ) {
821         out[ i ] = (*argv)[i];
822         //fprintf( stderr, " %s", out[ i ] );
823     }
824     for ( i = 0; i < OURSN; i++ ) {
825         out[ argc + i ] = OURS[i];
826         //fprintf( stderr, " %s", out[ i ] );
827     }
828     out[ N ] = 0;
829     //fprintf( stderr, "\n" );
830     (*argv) = out;
831     return N; // Don't include the terminating null pointer
832 }
833
834 /**
835  * Mount a concatenation of files,
836  * [ <fuse options> ] <mount> <file/from-to> ...
837  */
838 int main(int argc, char *argv[])
839 {
840     char *mnt;
841     int mt;
842     int fg;
843     int i;
844     int fuseargc;
845     struct stat stbuf;
846     int temporary = 0;
847     // Scan past options
848     for ( i = 1; i < argc; i++ ) {
849         if ( *argv[i] != '-' ) {
850             break;
851         }
852     }
853     if ( i > argc - 2 ) { // At least mount point plus one source
854         usage();
855     }
856     fuseargc = i;
857     mnt = argv[ i++ ]; // First non-option argument is the mount pount
858     char *overlaytag = "-overlay:";
859     int overlaytagsize = strlen( overlaytag );
860     if ( strncmp( argv[i], overlaytag, overlaytagsize ) == 0 ) {
861         // consume "-overlay:filename"
862         setup_overlay( argv[i++] + overlaytagsize ); // Need a writable file
863         if ( i >= argc ) {
864             usage();
865         }
866     }
867     if ( setup_sources( argv, i, argc-i ) ) {
868         return 1;
869     }
870     if ( overlay.source.filename ) {
871         overlay.source.to = sources.size; // Register total size.
872         overlay_load();
873     }
874     if ( stat( mnt, &stbuf ) == -1 ) {
875         int fd = open( mnt, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR );
876         if ( fd < 0 ) {
877             perror( mnt );
878             return 1;
879         }
880         time_t now = time( 0 );
881         times.atime = now;
882         times.mtime = now;
883         times.ctime = now;
884         temporary = 1;
885         close( fd );
886     } else if ( ! S_ISREG( stbuf.st_mode ) ) {
887         fprintf( stderr, "mountpoint is not a regular file\n" );
888         return 1;
889     } else {
890         times.atime = stbuf.st_atime;
891         times.mtime = stbuf.st_mtime;
892         times.ctime = stbuf.st_ctime;
893     }
894
895     {
896         int fd = open( mnt, O_RDWR, S_IRUSR | S_IWUSR );
897         if ( fd < 0 ) {
898             perror( mnt );
899             return 1;
900         }
901         if ( lseek( fd, sources.size, SEEK_SET ) < 0 ) {
902             return -EIO;
903         }
904     }
905     fuseargc = setup_argv( fuseargc, &argv );
906     struct fuse_args args = FUSE_ARGS_INIT( fuseargc, argv );
907     if ( fuse_parse_cmdline( &args, &mnt, &mt, &fg ) ) {
908         return 1;
909     }
910     fuse_opt_free_args( &args );
911     if ( ! mnt ) {
912         fprintf( stderr, "missing mountpoint parameter\n" );
913         return 1;
914     }
915     return fuse_main( fuseargc, argv, &fusefile_oper, temporary? mnt : NULL );
916 }