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