version change for submission to debian
[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
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_source(struct Source *p,char *frag) {
294     struct stat filestat;
295     // Open the fragment file rw if possible, else ro
296     range = strrchr( frag, '/' ); // last '/'
297     p->filename = range? strndup( frag, range - frag ) : frag;
298     p->fd = open( p->filename, O_RDWR );
299     int rdonly = 0;
300     if ( p->fd < 0 ) {
301         rdonly = 1;
302         p->fd = open( p->filename, O_RDONLY );
303     }
304     if ( p->fd < 0 ) {
305         perror( p->filename );
306         return 1; // Error return
307     }
308     if ( stat( p->filename, &filestat ) ) {
309         perror( p->filename );
310         return 1; 
311     }
312     if ( rdonly ) {
313         fprintf( stderr, "** %s opened read-only\n", p->filename );
314     }
315     p->from = 0;
316     p->to = filestat.st_size;
317     // Process any range variation
318     if ( range && *(++range) ) {
319         int a,b;
320         if ( 0 ) {
321         } else if ( RANGE( sscanf( range, "%d:%d%n", &a, &b, &c ), 2 )) {
322             p->from = ( a < 0 )? ( p->to + a ) : a;
323             p->to = ( b < 0 )? ( p->to + b ) : b;
324         } else if ( RANGE( sscanf( range, "%d+%d%n", &a, &b, &c ), 2 )) {
325             p->from = ( a < 0 )? ( p->to + a ) : a;
326             p->to = ( ( b < 0 )? p->to : p->from ) + b;
327         } else if ( RANGE( sscanf( range, "%d+%n", &a, &c ), 1 )) {
328             p->from = ( a < 0 )? ( p->to + a ) : a;
329         } else if ( RANGE( sscanf( range, ":%d%n", &b, &c ), 1 )) {
330             p->to = ( b < 0 )? ( p->to + b ) : b;
331         } else if ( RANGE( sscanf( range, "%d:%n", &a, &c ), 1 )) {
332             p->from = ( a < 0 )? ( p->to + a ) : a;
333         } else if ( RANGE( sscanf( range, "%d%n", &a, &c ), 1 )) {
334             if ( a >= 0 ) {
335                 p->from = a;
336             } else {
337                 p->from = p->to + a;
338             }
339         } else if ( RANGE( sscanf( range, ":%n", &c), 0 ) ) {
340             // to end from start
341         } else {
342             fprintf( stderr, "** BAD RANGE: %s\n", frag );
343             return 1;
344         }
345     }
346     if ( ( filestat.st_mode &  S_IFMT ) == S_IFCHR ) {
347         filestat.st_size = p->to; // Pretend size of character device
348     }
349     if ( p->from < 0 ) {
350         p->from = 0;
351     }
352     if ( p->to > filestat.st_size ) {
353         p->to = filestat.st_size;
354     }
355     if ( p->from >= p->to || p->from >= filestat.st_size ) {
356         fprintf( stderr, "** BAD RANGE: %s [%ld:%ld]\n",
357                  frag, p->from, p->to );
358         return 1;
359     }
360     p->start = sources.size; // the fusefile position of fragment
361     sources.size += p->to - p->from;
362     return 0;
363 }
364
365 static int setup_sources(char **argv,int i,int n) {
366     sources.array = calloc( n, sizeof( struct Source ) );
367     if ( sources.array == 0 ) {
368         return 1;
369     }
370     sources.count = n;
371     int j = 0;
372     sources.size = 0;
373     for ( ; j < n; i++, j++ ) {
374         struct Source *p = sources.array + j;
375         if ( setup_source( p, argv[i] ) ) {
376             return 1;
377         }
378         p->start = sources.size; // the fusefile position of fragment
379         sources.size += p->to - p->from;
380 #if DEBUG
381         print_source( p );
382 #endif
383     }
384     return 0;
385 }
386
387 static int fusefile_getattr(const char *path,struct stat *stbuf) {
388 #if DEBUG
389     fprintf( stderr, "fusefile_getattr( %s )\n", path );
390 #endif
391     if ( strcmp( path, "/" ) != 0 ) {
392         return -ENOENT;
393     }
394 #if DEBUG
395     fprintf( stderr, "getattr %ld\n", sources.size );
396 #endif
397     memset( stbuf, 0, sizeof( struct stat ) );
398     stbuf->st_mode = S_IFREG | 0644; // Hmmm
399     stbuf->st_nlink = 1;
400     stbuf->st_size = sources.size;
401     stbuf->st_atime = times.atime;
402     stbuf->st_mtime = times.mtime;
403     stbuf->st_ctime = times.ctime;
404     stbuf->st_uid = getuid();
405     stbuf->st_gid = getgid();
406     return 0;
407 }
408
409 static int fusefile_chmod(const char *path,mode_t m) {
410 #if DEBUG
411     fprintf( stderr, "fusefile_chmod( %s, %d )\n", path, m );
412 #endif
413     return -1;
414 }
415
416 static int fusefile_open(const char *path,struct fuse_file_info *fi) {
417 #if DEBUG
418     fprintf( stderr, "fusefile_open( %s, %d )\n", path, fi->flags );
419     fprintf( stderr, "fixing( %d )\n", fi->flags | O_CLOEXEC );
420 #endif
421     if ( strcmp( path, "/" ) != 0 ) {
422         return -ENOENT;
423     }
424     // set O-CLOEXEC  for this opening?
425     times.atime = time( 0 );
426     return 0;
427 }
428
429 static int find_source(off_t offset) {
430     int lo = 0;
431     int hi = sources.count;
432     if ( offset >= sources.size ) {
433         return -1;
434     }
435 #if DEBUG
436     fprintf( stderr, "find_source( %ld )\n", offset );
437 #endif
438     while ( lo + 1 < hi ) {
439         int m = ( lo + hi ) / 2;
440         if ( offset < sources.array[ m ].start ) {
441 #if DEBUG
442             fprintf( stderr, "  offset < [%d].start: %ld\n",
443                      m, sources.array[ m ].start );
444 #endif
445             hi = m;
446         } else {
447 #if DEBUG
448             fprintf( stderr, "  offset >= [%d].start: %ld\n",
449                      m, sources.array[ m ].start );
450 #endif
451             lo = m;
452         }
453     }
454 #if DEBUG
455     fprintf( stderr, "found %d\n", lo );
456 #endif
457     return lo;
458 }
459
460 static int overlay_merge(char *buf,off_t beg,off_t end) {
461 #if DEBUG
462     fprintf( stderr, "merge %ld %ld\n", beg, end );
463 #endif
464     // Find nearest overlay data before or at beg
465     ssize_t p = overlay_prior_fragment( beg );
466     if ( p < 0 ) {
467         p = 0;
468     }
469     for ( ; p < overlay.count && overlay.table[p].beg < end; p++ ) {
470         if ( overlay.table[p].end < beg ) {
471             continue;
472         }
473         if ( overlay.table[p].beg > beg ) {
474             size_t delta = overlay.table[p].beg - beg;
475             buf += delta;
476             beg += delta;
477         }
478         size_t size = ( overlay.table[p].end <= end )?
479             ( overlay.table[p].end - beg ) : ( end - beg ); 
480         lseek( overlay.source.fd, beg, SEEK_SET );
481         while ( size > 0 ) {
482             size_t n = read( overlay.source.fd, buf, size );
483             size -= n;
484             buf += n;
485             beg += n; //
486         }
487     }
488     return 0;
489 }
490
491 // Read <size> bytes from <offset> in file
492 static int fusefile_read(const char *path, char *buf, size_t size,
493                          off_t off, struct fuse_file_info *fi)
494 {
495 #if DEBUG
496     fprintf( stderr, "fusefile_read( %s )\n", path );
497 #endif
498     if( strcmp( path, "/" ) != 0 ) {
499         return -ENOENT;
500     }
501 #if DEBUG
502     fprintf( stderr, "read %ld %ld\n", off, size );
503 #endif
504     size_t rr = 0; // total reading
505     while ( size > 0 ) {
506 #if DEBUG
507         fprintf( stderr, "  find_source %ld %ld\n", off, size );
508 #endif
509         int i = find_source( off );
510         if ( i < 0 ) {
511             return ( off == sources.size )? rr : -ENOENT;
512         }
513         if ( sources.array[i].fd < 0 ) {
514             return -ENOENT;
515         }
516 #if DEBUG
517         print_source( &sources.array[i] );
518 #endif
519         times.atime = time( 0 );
520         size_t b = off - sources.array[i].start + sources.array[i].from;
521         size_t n = sources.array[i].to - b;
522         if ( n > size ) {
523             n = size;
524         }
525         if ( sources.array[i].dirty ) {
526             fsync( sources.array[i].fd );
527             sources.array[i].dirty = 0;
528         }
529 #if DEBUG
530         fprintf( stderr, "  seek fd=%d to %ld\n", sources.array[i].fd, b );
531 #endif
532         if ( lseek( sources.array[i].fd, b, SEEK_SET ) < 0 ) {
533             perror( sources.array[i].filename );
534             return -ENOENT;
535         }
536 #if DEBUG
537         fprintf( stderr, "  now read %ld from fd=%d\n",
538                  n, sources.array[i].fd );
539 #endif
540         ssize_t r = read( sources.array[i].fd, buf + rr, n );
541 #if DEBUG
542         fprintf( stderr, "  got %ld bytes\n", r );
543 #endif
544         if ( r < 0 ) {
545             perror( sources.array[i].filename );
546             return -ENOENT;
547         }
548         if ( r == 0 ) {
549             break;
550         }
551         if ( overlay.source.filename ) {
552             if ( overlay.source.dirty ) {
553                 fsync( overlay.source.fd );
554                 overlay.source.dirty = 0;
555             }
556             int x = overlay_merge( buf + rr, off + rr, off + rr + r );
557             if ( x ) {
558                 return x;
559             }
560         }
561         rr += r;
562         off += r;
563         size -= r;
564     }
565 #if DEBUG
566     fprintf( stderr, "  total reading %ld bytes\n", rr );
567 #endif
568     return rr;
569 }
570
571 /**
572  * Poll for IO readiness.
573  */
574 int fusefile_poll(const char *path, struct fuse_file_info *fi,
575                    struct fuse_pollhandle *ph, unsigned *reventsp )
576 {
577 #if DEBUG
578     fprintf( stderr, "fusefile_poll( %s ) %p %d\n", path, ph, *reventsp );
579 #endif
580     if( strcmp( path, "/" ) != 0 ) {
581         return -ENOENT;
582     }
583     if ( ph ) {
584         return fuse_notify_poll( ph );
585     }
586     return 0;
587 }
588
589 static void overlay_load() {
590     lseek( overlay.source.fd, overlay.source.to, SEEK_SET );
591     size_t x = 0;
592     size_t size = sizeof( overlay.count );
593     if ( read( overlay.source.fd, &x, size ) != size ) {
594         return;
595     }
596 #if DEBUG
597     fprintf( stderr, "overlay: %s with %ld regions\n",
598              overlay.source.filename, x );
599 #endif
600     struct Region f = { 0, 0 };
601     size = sizeof( struct Region );
602     while ( x-- > 0 ) {
603         if ( read( overlay.source.fd, &f, size ) != size ) {
604             fprintf( stderr, "%s: bad meta data\n", overlay.source.filename );
605             exit( 1 );
606         }
607 #if DEBUG
608         fprintf( stderr, "overlay region: %ld %ld\n", f.beg, f.end );
609 #endif
610         overlay_mark( f.beg, f.end );
611     }
612 }
613
614 /**
615  * Write a full block of data over the sources at the offset
616  */
617 static int write_block(off_t off,const char *buf,size_t size) {
618 #if DEBUG
619     fprintf( stderr, "write_block( %ld, ?, %ld )\n", off, size );
620 #endif
621     if ( overlay.source.filename ) {
622         overlay_mark( off, off + size ); // Mark region as written
623     }
624     while ( size > 0 ) {
625         int index = find_source( off ); // index of source file
626         if ( index < 0 ) {
627             return -EIO; // past EOF
628         }
629         struct Source *source = overlay.source.filename?
630             &overlay.source :  &sources.array[ index ];
631         off_t from = off - source->start + source->from;
632         off_t max = source->to - from;
633         if ( lseek( source->fd, from, SEEK_SET ) < 0 ) {
634             return -EIO;
635         }
636         ssize_t todo = ( size < max )? size : max;
637         while ( todo > 0 ) {
638             times.mtime = time( 0 );
639             ssize_t n = write( source->fd, buf, todo );
640             if ( n <= 0 ) {
641                 return -EIO; // Something wrong
642             }
643             buf += n;
644             todo -= n;
645             size -= n;
646             off += n;
647         }
648         if ( source->dirty++ >= 1000 ) {
649             fsync( source->fd );
650             source->dirty = 0;
651         }
652     }
653     return 0;
654 }
655
656 static int fusefile_write_buf(const char *path, struct fuse_bufvec *buf,
657                               off_t off, struct fuse_file_info *fi) {
658 #if DEBUG
659     fprintf( stderr, "fusefile_write_buf( %s )\n", path );
660 #endif
661     if ( strcmp( path, "/" ) != 0 ) {
662         return -ENOENT;
663     }
664
665     size_t size = 0;
666     int i;
667     for ( i = 0; i < buf->count; i++ ) {
668         struct fuse_buf *p = &buf->buf[i];
669         if ( p->flags & FUSE_BUF_IS_FD ) {
670 #if DEBUG
671             fprintf( stderr, "Content held in a file ... HELP!!\n" );
672 #endif
673             return -EIO;
674         }
675         if ( write_block( off, (char*) p->mem, p->size ) < 0 ) {
676             return -EIO;
677         }
678         size += p->size;
679     }
680 #if DEBUG
681     fprintf( stderr, "fusefile_write_buf written %ld\n", size );
682 #endif
683     return size;
684 }
685
686 /**
687  * Write a fragment at <off>. This overwrites files.
688  */
689 static int fusefile_write(const char *path, const char *buf, size_t size,
690                           off_t off, struct fuse_file_info *fi)
691 {
692 #if DEBUG
693     fprintf( stderr, "fusefile_write( %s %ld )\n", path, size );
694 #endif
695     if ( strcmp( path, "/" ) != 0 ) {
696         return -ENOENT;
697     }
698
699     if ( write_block( off, buf, size ) < 0 ) {
700         return -EIO;
701     }
702     return size;
703 }
704
705 static void fusefile_destroy(void *data) {
706     char *mnt = (char*) data; // As passed to fuse_main
707 #if DEBUG
708     fprintf( stderr, "fusefile_destroy( %s )\n", mnt? mnt : "" );
709 #endif
710     if ( mnt ) {
711         unlink( mnt );
712     }
713 }
714
715 static void fsync_all_dirty() {
716     int i = 0;
717     for ( ; i < sources.count; i++ ) {
718         if ( sources.array[i].dirty ) {
719             fsync( sources.array[i].fd );
720             sources.array[i].dirty = 0;
721         }
722     }
723     if ( overlay.source.filename && overlay.source.dirty ) {
724         fsync( overlay.source.fd );
725         overlay.source.dirty = 0;
726     }
727 }
728
729 static int fusefile_flush(const char *path, struct fuse_file_info *info) {
730 #if DEBUG
731     fprintf( stderr, "fusefile_flush( %s )\n", path );
732 #endif
733     if ( strcmp( path, "/" ) != 0 ) {
734         return -ENOENT;
735     }
736     fsync_all_dirty();
737     return 0;
738 }
739
740 static int fusefile_release(const char *path, struct fuse_file_info *fi) {
741 #if DEBUG
742     fprintf( stderr, "fusefile_release( %s, %d )\n", path, fi->flags );
743 #endif
744     if ( strcmp( path, "/" ) != 0 ) {
745         return -ENOENT;
746     }
747     return 0;
748 }
749
750 static int fusefile_fsync(const char *path, int x, struct fuse_file_info *fi) {
751 #if DEBUG
752     fprintf( stderr, "fusefile_fsync( %s, %d )\n", path, x );
753 #endif
754     if ( strcmp( path, "/" ) != 0 ) {
755         return -ENOENT;
756     }
757     fsync_all_dirty();
758     return 0;
759 }
760
761 /**
762  * 
763  */
764 static int fusefile_truncate(const char *path, off_t len) {
765 #if DEBUG
766     fprintf( stderr, "fusefile_truncate( %s, %ld )\n", path, len );
767 #endif
768     if ( strcmp( path, "/" ) != 0 ) {
769         return -ENOENT;
770     }
771     return -EIO;
772 }
773
774 void *fusefile_init(struct fuse_conn_info *fci) {
775 #if DEBUG
776     fprintf( stderr, "fusefile_init( %d, %d )\n", fci->async_read, fci->want );
777 #endif
778     // Disable asynchronous reading
779     fci->async_read = 0;
780     fci->want &= ~FUSE_CAP_ASYNC_READ;
781 #if DEBUG
782     fprintf( stderr, "fusefile_init( %d, %d )\n", fci->async_read, fci->want );
783 #endif
784     return 0;
785 }
786
787 #define ENDSOURCE( S ) ( S.start + ( S.to - S.from ) )
788
789 /**
790  * Dump the current fragmentation to stdout.
791  */
792 static int dump_fragments() {
793     int oly = 0;
794     int src = 0;
795     size_t pos = 0;
796     while ( src < sources.count ) {
797         size_t x = ( oly < overlay.count )?
798             overlay.table[ oly ].beg : sources.size;
799         for ( ; src < sources.count && 
800                   ENDSOURCE( sources.array[ src ] ) <= x; src++ ) {
801             // Dump sources.array[src] in full
802             fprintf( stdout, "%s/%ld:%ld\n",
803                      sources.array[ src ].filename,
804                      pos - sources.array[ src ].start,
805                      sources.array[ src ].to );
806             pos = ENDSOURCE( sources.array[ src ] );
807         }
808         if ( sources.array[ src ].start < x ) {
809             // Dump sources.array[src] up to x;
810             fprintf( stdout, "%s/%ld:%ld\n",
811                      sources.array[ src ].filename,
812                      pos - sources.array[ src ].start,
813                      x - sources.array[ src ].start );
814             pos = ENDSOURCE( sources.array[ src ] );
815         }
816         if ( oly < overlay.count ) {
817             fprintf( stdout, "%s/%ld:%ld\n",
818                      overlay.source.filename,
819                      overlay.table[ oly ].beg,
820                      overlay.table[ oly ].end );
821             pos = overlay.table[ oly++ ].end;
822         }
823         for ( ; src < sources.count &&
824                   ENDSOURCE( sources.array[ src ] ) <= pos; src++ ) {
825             // Just skip these fragments.
826         }
827     }
828     return( 0 );
829 }
830
831 static struct fuse_operations fusefile_oper = {
832     .getattr = fusefile_getattr,
833     // NYI .fgetattr = fusefile_fgetattr,
834     .chmod = fusefile_chmod,
835     .open = fusefile_open,
836     .read = fusefile_read,
837     .poll = fusefile_poll,
838     .write = fusefile_write,
839     .write_buf = fusefile_write_buf,
840     .destroy = fusefile_destroy,
841     // NYI .access = fusefile_access,
842     .flush = fusefile_flush,
843     .release = fusefile_release,
844     .fsync = fusefile_fsync,
845     // NYI .ftruncate = fusefile_ftruncate,
846     .truncate = fusefile_truncate,
847     //.truncate = fusefile_truncate,
848     //.release = fusefile_release,
849     .init = fusefile_init,
850 };
851
852 static void usage() {
853     char *usage =
854 "Usage: fusefile [ <fuse options> ] <mount> <file/from-to> ... \n"
855 "Mounts a virtual, file that is a concatenation of file fragments\n"
856         ;
857     fprintf( stderr, "%s", usage );
858     exit( 1 );
859 }
860
861 /**
862  * Set up the arguments for the fuse_main call, adding our own.
863  * argv[argc] is the mount point argument
864  */
865 static int setup_argv(int argc,char ***argv) {
866     // note: (*argv)[ argc ] is the mount point argument
867     char *OURS[] = {
868         "-odefault_permissions",
869         (*argv)[ argc ]
870     };
871 #define OURSN ( sizeof( OURS ) / sizeof( char* ) )
872     int N = argc + OURSN;
873     // Allocate new arg array plus terminating null pointer
874     char **out = malloc( ( N + 1 ) * sizeof( char* ) ); 
875     int i;
876     for ( i = 0; i < argc; i++ ) {
877         out[ i ] = (*argv)[i];
878         //fprintf( stderr, " %s", out[ i ] );
879     }
880     for ( i = 0; i < OURSN; i++ ) {
881         out[ argc + i ] = OURS[i];
882         //fprintf( stderr, " %s", out[ i ] );
883     }
884     out[ N ] = 0;
885     //fprintf( stderr, "\n" );
886     (*argv) = out;
887     return N; // Don't include the terminating null pointer
888 }
889
890 /**
891  * Mount a concatenation of files,
892  * [ <fuse options> ] <mount> <file/from-to> ...
893  */
894 int main(int argc, char *argv[])
895 {
896     char *mnt;
897     int mt;
898     int fg;
899     int i;
900     int fuseargc;
901     struct stat stbuf;
902     int temporary = 0;
903     // Scan past options
904     for ( i = 1; i < argc; i++ ) {
905         if ( *argv[i] != '-' ) {
906             break;
907         }
908     }
909     if ( i > argc - 2 ) { // At least mount point plus one source
910         usage();
911     }
912     fuseargc = i;
913     mnt = argv[ i++ ]; // First non-option argument is the mount pount
914     char *overlaytag = "-overlay:";
915     int overlaytagsize = strlen( overlaytag );
916     if ( strncmp( argv[i], overlaytag, overlaytagsize ) == 0 ) {
917         // consume "-overlay:filename"
918         setup_overlay( argv[i++] + overlaytagsize ); // Need a writable file
919         if ( i >= argc ) {
920             usage();
921         }
922     }
923     if ( setup_sources( argv, i, argc-i ) ) {
924         return 1;
925     }
926     if ( overlay.source.filename ) {
927         overlay.source.to = sources.size; // Register total size.
928         overlay_load();
929     }
930     if ( stat( mnt, &stbuf ) == -1 ) {
931         int fd = open( mnt, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR );
932         if ( fd < 0 ) {
933             perror( mnt );
934             return 1;
935         }
936         time_t now = time( 0 );
937         times.atime = now;
938         times.mtime = now;
939         times.ctime = now;
940         temporary = 1;
941         close( fd );
942     } else if ( ! S_ISREG( stbuf.st_mode ) ) {
943         fprintf( stderr, "mountpoint is not a regular file\n" );
944         return 1;
945     } else {
946         times.atime = stbuf.st_atime;
947         times.mtime = stbuf.st_mtime;
948         times.ctime = stbuf.st_ctime;
949     }
950
951     {
952         int fd = open( mnt, O_RDWR, S_IRUSR | S_IWUSR );
953         if ( fd < 0 ) {
954             perror( mnt );
955             return 1;
956         }
957         if ( lseek( fd, sources.size, SEEK_SET ) < 0 ) {
958             return -EIO;
959         }
960     }
961     fuseargc = setup_argv( fuseargc, &argv );
962     if ( strcmp( "-dump", argv[ 1 ] ) == 0 ) {
963         return dump_fragments();
964     }
965     struct fuse_args args = FUSE_ARGS_INIT( fuseargc, argv );
966     if ( fuse_parse_cmdline( &args, &mnt, &mt, &fg ) ) {
967         return 1;
968     }
969     fuse_opt_free_args( &args );
970     if ( ! mnt ) {
971         fprintf( stderr, "missing mountpoint parameter\n" );
972         return 1;
973     }
974     return fuse_main( fuseargc, argv, &fusefile_oper, temporary? mnt : NULL );
975 }