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