/
fs.go
721 lines (624 loc) · 16 KB
/
fs.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package ext2 implements read-only access to EXT2 file systems.
package ext2
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"os"
"reflect"
"strconv"
"strings"
"time"
)
const (
bytesPerSector = 512
superOff = 1024 // superblock offset
superSize = 1024 // superblock size
superMagic = 0xEF53 // superblock magic
minBlockSize = 1024
maxBlockSize = 4096
rootInode = 2
firstInode = 11
validFS = 0x0001
errorFS = 0x0002
numDirBlocks = 12
indBlock = numDirBlocks // indirect block
ind2Block = indBlock + 1 // double-indirect block
ind3Block = ind2Block + 1 // triple-indirect block
numBlocks = ind3Block + 1
nameLen = 255
// permissions in Inode.mode
iexec = 00100
iwrite = 00200
iread = 00400
isvtx = 01000
isgid = 02000
isuid = 04000
// type in Inode.mode
ifmt = 0170000
ififo = 0010000
ifchr = 0020000
ifdir = 0040000
ifblk = 0060000
ifreg = 0100000
iflnk = 0120000
ifsock = 0140000
ifwht = 0160000
)
func dirlen(nameLen int) int {
return (nameLen + 8 + 3) &^ 3
}
type diskSuper struct {
Ninode uint32 /* Inodes count */
Nblock uint32 /* Blocks count */
Rblockcount uint32 /* Reserved blocks count */
Freeblockcount uint32 /* Free blocks count */
Freeinodecount uint32 /* Free inodes count */
Firstdatablock uint32 /* First Data Block */
Logblocksize uint32 /* Block size */
Logfragsize uint32 /* Fragment size */
Blockspergroup uint32 /* # Blocks per group */
Fragpergroup uint32 /* # Fragments per group */
Inospergroup uint32 /* # Inodes per group */
Mtime uint32 /* Mount time */
Wtime uint32 /* Write time */
Mntcount uint16 /* Mount count */
Maxmntcount uint16 /* Maximal mount count */
Magic uint16 /* Magic signature */
State uint16 /* File system state */
Errors uint16 /* Behaviour when detecting errors */
Pad uint16
Lastcheck uint32 /* time of last check */
Checkinterval uint32 /* max. time between checks */
Creatoros uint32 /* OS */
Revlevel uint32 /* Revision level */
Defresuid uint16 /* Default uid for reserved blocks */
Defresgid uint16 /* Default gid for reserved blocks */
/* the following are only available with revlevel = 1 */
Firstino uint32 /* First non-reserved inode */
Inosize uint16 /* size of inode structure */
Blockgroupnr uint16 /* block group # of this super block */
}
type diskGroup struct {
Bitblock uint32 /* Blocks bitmap block */
Inodebitblock uint32 /* Inodes bitmap block */
Inodeaddr uint32 /* Inodes table block */
Freeblockscount uint16 /* Free blocks count */
Freeinodescount uint16 /* Free inodes count */
Useddirscount uint16 /* Directories count */
}
const diskGroupSize = 32
type diskInode struct {
Mode uint16 /* File mode */
Uid uint16 /* Owner Uid */
Size uint32 /* Size in bytes */
Atime uint32 /* Access time */
Ctime uint32 /* Creation time */
Mtime uint32 /* Modification time */
Dtime uint32 /* Deletion Time */
Gid uint16 /* Group Id */
Nlink uint16 /* Links count */
Nblock uint32 /* Blocks count */
Flags uint32 /* File flags */
Osd1 uint32
Block [numBlocks]uint32 /* Pointers to blocks */
Version uint32 /* File version (for NFS) */
Fileacl uint32 /* File ACL */
Diracl uint32 /* Directory ACL or high size bits */
Faddr uint32 /* Fragment address */
}
type diskDirent struct {
Ino uint32 /* Inode number */
Reclen uint16 /* Directory entry length */
Namlen uint8 /* Name length */
}
const minDirentSize = 4 + 2 + 1 + 1
// An FS represents a file system.
type FS struct {
BlockSize int
NumBlock int64
numGroup uint32
inodesPerGroup uint32
blocksPerGroup uint32
inodesPerBlock uint32
inodeSize uint32
groupAddr uint32
descPerBlock uint32
firstBlock uint32
g []*diskGroup
r io.ReaderAt
c io.Closer
buf []byte
cache [16]block
cacheAge int64
cacheHit int64
}
type block struct {
off int64
lastUse int64
buf []byte
}
// A readerAtOffset wraps a ReaderAt but translates all the I/O by the given offset.
type readerAtOffset struct {
r io.ReaderAt
off int64
}
func (r *readerAtOffset) ReadAt(p []byte, off int64) (n int, err error) {
return r.r.ReadAt(p, off+r.off)
}
// Open opens the file system in the named file.
//
// If the name contains an @ sign, it is taken to be
// of the form file@offset, where offset is a decimal,
// hexadecimal, or octal number according to its prefix,
// and the file system is assumed to start at the given
// offset in the file instead of at the beginning of the file.
func Open(name string) (*FS, error) {
var off int64
if i := strings.Index(name, "@"); i >= 0 {
v, err := strconv.ParseInt(name[i+1:], 0, 64)
if err != nil {
return nil, fmt.Errorf("invalid offset in name %q", name)
}
off = v
name = name[:i]
}
f, err := os.Open(name)
if err != nil {
return nil, err
}
var r io.ReaderAt = f
if off != 0 {
r = &readerAtOffset{r, off}
}
fs, err := Init(r)
if err != nil {
f.Close()
return nil, err
}
fs.c = f
return fs, nil
}
// Init returns an FS reading from the file system stored in r.
func Init(r io.ReaderAt) (*FS, error) {
fs := &FS{
r: r,
buf: make([]byte, 1024),
BlockSize: superSize,
}
var super diskSuper
if _, err := fs.read(superOff, 0, &super); err != nil {
return nil, err
}
if super.Magic != superMagic {
return nil, fmt.Errorf("bad magic %#x wanted %#x", super.Magic, superMagic)
}
bsize := uint32(minBlockSize << super.Logblocksize)
fs.BlockSize = int(bsize)
fs.NumBlock = int64(super.Nblock)
fs.numGroup = (super.Nblock + super.Blockspergroup - 1) / super.Blockspergroup
fs.g = make([]*diskGroup, fs.numGroup)
fs.inodesPerGroup = super.Inospergroup
fs.blocksPerGroup = super.Blockspergroup
if super.Revlevel >= 1 {
fs.inodeSize = uint32(super.Inosize)
} else {
fs.inodeSize = 128
}
fs.inodesPerBlock = bsize / fs.inodeSize
if bsize == superOff {
fs.groupAddr = 2
} else {
fs.groupAddr = 1
}
fs.descPerBlock = bsize / diskGroupSize
fs.firstBlock = super.Firstdatablock
return fs, nil
}
// A File represents a file or directory in a file system.
type File struct {
fs *FS
inum uint32
ino diskInode
}
// File returns the file with the given inode number.
func (fs *FS) File(inode uint32) (*File, error) {
g, ioff, err := fs.igroup(inode)
if err != nil {
return nil, err
}
addr := int64(fs.BlockSize) * int64(g.Inodeaddr+ioff/fs.inodesPerBlock)
ivoff := (ioff % fs.inodesPerBlock) * fs.inodeSize
file := &File{fs: fs, inum: inode}
if _, err := fs.read(addr, int(ivoff), &file.ino); err != nil {
return nil, err
}
switch file.ino.Mode & ifmt {
case ififo, ifchr, ifdir, ifblk, ifreg, iflnk, ifsock:
// okay
default:
return nil, fmt.Errorf("invalid inode mode %#x", file.ino.Mode)
}
return file, nil
}
func (fs *FS) igroup(inum uint32) (g *diskGroup, ioff uint32, err error) {
gnum := (inum - 1) / fs.inodesPerGroup
if gnum >= fs.numGroup {
return nil, 0, fmt.Errorf("inode number %#x out of range", inum)
}
ioff = (inum - 1) % fs.inodesPerGroup
g, err = fs.group(gnum)
return
}
func (fs *FS) group(gnum uint32) (g *diskGroup, err error) {
// cache to avoid repeated loads from disk
if g := fs.g[gnum]; g != nil {
return g, nil
}
g = new(diskGroup)
addr := int64(fs.BlockSize) * int64(fs.groupAddr+gnum/fs.descPerBlock)
voff := gnum % fs.descPerBlock * diskGroupSize
if _, err := fs.read(addr, int(voff), g); err != nil {
return nil, err
}
if g.Inodeaddr < fs.groupAddr+fs.numGroup/fs.descPerBlock {
return nil, fmt.Errorf("implausible inode group descriptor at %#x[%d:]: %+v", addr, voff, *g)
}
fs.g[gnum] = g
return g, nil
}
// Size returns the file's size in bytes.
func (f *File) Size() int64 {
size := int64(f.ino.Size)
if f.ino.Mode&ifmt == ifreg {
size |= int64(f.ino.Diracl) << 32
}
return size
}
// Mode returns the file's mode.
func (f *File) Mode() os.FileMode {
mode := os.FileMode(f.ino.Mode & 0777)
switch f.ino.Mode & ifmt {
case ififo:
mode |= os.ModeNamedPipe
default: // ifchr, ifblk, unknown
mode |= os.ModeDevice
case ifdir:
mode |= os.ModeDir
case ifreg:
// no bits
case iflnk:
mode |= os.ModeSymlink
case ifsock:
mode |= os.ModeSocket
}
return mode
}
func (f *File) IsDir() bool {
return f.ino.Mode&ifmt == ifdir
}
// ModTime returns the file's modification time.
func (f *File) ModTime() time.Time {
return time.Unix(int64(f.ino.Mtime), 0)
}
// ReadAt implements the io.ReaderAt interface.
func (f *File) ReadAt(buf []byte, off int64) (n int, err error) {
size := f.Size()
if off >= size {
return 0, io.EOF
}
if n = len(buf); int64(n) > size-off {
n = int(size - off)
}
lfrag := int(uint32(off) % uint32(f.fs.BlockSize))
off -= int64(lfrag)
want := lfrag + n
rfrag := -want & (f.fs.BlockSize - 1)
want += rfrag
offb := uint32(off / int64(f.fs.BlockSize))
nblock := want / f.fs.BlockSize
for i := 0; i < nblock; i++ {
b, err := f.dblock(offb + uint32(i))
if err != nil {
return 0, err
}
dbuf, err := f.fs.readData(b, 0, nil)
if err != nil {
return 0, err
}
m := copy(buf, dbuf[lfrag:])
buf = buf[m:]
lfrag = 0
}
return n, nil
}
// ReadLink returns the symbolic link content of f.
func (f *File) ReadLink() (string, error) {
if f.ino.Mode&ifmt != iflnk {
return "", fmt.Errorf("not a symbolic link")
}
size := f.ino.Size
if f.ino.Nblock != 0 {
if size > uint32(f.fs.BlockSize) {
return "", fmt.Errorf("invalid symlink size")
}
// Symlink fits in one block.
b, err := f.dblock(0)
if err != nil {
return "", err
}
buf, err := f.fs.readData(b, 0, nil)
if err != nil {
return "", err
}
return string(buf[:size]), nil
}
if size > 4*numBlocks {
return "", fmt.Errorf("invalid symlink size")
}
var buf [4 * numBlocks]byte
for i := 0; i < numBlocks; i++ {
binary.LittleEndian.PutUint32(buf[4*i:], f.ino.Block[i])
}
return string(buf[:size]), nil
}
// A Dir represents a directory entry.
type Dir struct {
Name string
Inode uint32
}
func (f *File) walkDir(run func(name []byte, ino uint32) bool) error {
if f.ino.Mode&ifmt != ifdir {
return fmt.Errorf("file is not a directory")
}
nblock := (int(f.ino.Size) + f.fs.BlockSize - 1) / f.fs.BlockSize
for i := 0; i < nblock; i++ {
b, err := f.dblock(uint32(i))
if err != nil {
return err
}
buf, err := f.fs.readData(b, 0, nil)
if err != nil {
return err
}
for len(buf) > 0 {
var de diskDirent
if err := unpack(buf, &de); err != nil {
return err
}
minLen := minDirentSize
recLen := int(de.Reclen)
nameLen := int(de.Namlen)
if minLen+nameLen > recLen || recLen > len(buf) {
return fmt.Errorf("corrupt directory entry")
}
name := buf[minLen : minLen+nameLen]
buf = buf[recLen:]
if de.Ino == 0 {
continue
}
if !run(name, de.Ino) {
break
}
}
}
return nil
}
// ReadDir returns all the directory entries in f.
func (f *File) ReadDir() ([]Dir, error) {
var dirs []Dir
err := f.walkDir(func(name []byte, ino uint32) bool {
dirs = append(dirs, Dir{string(name), ino})
return true
})
return dirs, err
}
// Lookup looks up the name in the directory f, returning the corresponding child file.
func (f *File) Lookup(name string) (*File, error) {
var bino uint32
bname := []byte(name)
err := f.walkDir(func(name []byte, ino uint32) bool {
if bytes.Equal(bname, name) {
bino = ino
return false
}
return true
})
if err != nil {
return nil, err
}
if bino == 0 {
return nil, fmt.Errorf("file not found")
}
return f.fs.File(bino)
}
func (f *File) dblock(block uint32) (uint32, error) {
b := block
// direct?
if b < numDirBlocks {
return f.ino.Block[b], nil
}
b -= numDirBlocks
// single indirect?
p := uint32(f.fs.BlockSize) / 4
if b < p {
var b1 uint32
if _, err := f.fs.readData(f.ino.Block[indBlock], int(4*b), &b1); err != nil {
return 0, err
}
return b1, nil
}
b -= p
// double indirect?
if b < p*p {
i1 := b / p
i2 := b % p
var b1, b2 uint32
if _, err := f.fs.readData(f.ino.Block[ind2Block], int(4*i1), &b1); err != nil {
return 0, err
}
if _, err := f.fs.readData(b1, int(4*i2), &b2); err != nil {
return 0, err
}
return b2, nil
}
b -= p * p
// triple indirect?
if b < p*p*p {
i1 := b / (p * p)
i2 := b % (p * p) / p
i3 := b % p
var b1, b2, b3 uint32
if _, err := f.fs.readData(f.ino.Block[ind3Block], int(4*i1), &b1); err != nil {
return 0, err
}
if _, err := f.fs.readData(b1, int(4*i2), &b2); err != nil {
return 0, err
}
if _, err := f.fs.readData(b1, int(4*i3), &b3); err != nil {
return 0, err
}
return b3, nil
}
return 0, fmt.Errorf("block number %d out of range", block)
}
// Open returns an io.Reader for the file.
func (f *File) Open() (io.Reader, error) {
if f.ino.Mode&ifmt != ifreg {
return nil, fmt.Errorf("not a regular file")
}
return &fileReader{f, 0}, nil
}
type fileReader struct {
f *File
off int64
}
func (r *fileReader) Read(buf []byte) (n int, err error) {
n, err = r.f.ReadAt(buf, r.off)
if n > 0 {
err = nil
}
r.off += int64(n)
return
}
// Root returns the root directory of the file system.
func (fs *FS) Root() (*File, error) {
return fs.File(rootInode)
}
const maxCache = 32
func (fs *FS) read(off int64, voff int, val interface{}) ([]byte, error) {
var buf []byte
// look in cache
fs.cacheAge++
if fs.cacheAge%10000 == 0 {
fmt.Printf("cache %d/%d\n", fs.cacheHit, fs.cacheAge)
}
var oldest *block
for i := range fs.cache {
b := &fs.cache[i]
if b.off == off {
b.lastUse = fs.cacheAge
buf = b.buf
fs.cacheHit++
goto unpack
}
if oldest == nil || b.lastUse < oldest.lastUse {
oldest = b
}
}
// load into b
{
b := oldest
if len(b.buf) < fs.BlockSize {
b.buf = make([]byte, fs.BlockSize)
}
b.off = 0
n, err := fs.r.ReadAt(b.buf, off)
if n < fs.BlockSize {
if err == nil {
err = fmt.Errorf("short read")
}
return nil, fmt.Errorf("reading %d bytes at offset %#x: %v", len(b.buf), off, err)
}
b.off = off
b.lastUse = fs.cacheAge
buf = b.buf
}
unpack:
if val != nil {
if err := unpack(buf[voff:], val); err != nil {
return nil, fmt.Errorf("parsing offset %#x[%d:%d] as %T: %v", off, voff, fs.BlockSize, val, err)
}
}
return buf, nil
}
func (fs *FS) readData(block uint32, voff int, val *uint32) ([]byte, error) {
b := block
if b < fs.firstBlock {
return nil, fmt.Errorf("block number %d out of range", block)
}
b -= fs.firstBlock
g, err := fs.group(b / fs.blocksPerGroup)
if err != nil {
return nil, err
}
buf, err := fs.read(int64(g.Bitblock)*int64(fs.BlockSize), 0, nil)
if err != nil {
return nil, err
}
boff := b % fs.blocksPerGroup
if buf[boff>>3]&(1<<(boff&7)) == 0 {
return nil, fmt.Errorf("block %d not allocated", block)
}
buf, err = fs.read(int64(block)*int64(fs.BlockSize), 0, nil)
if err != nil {
return nil, err
}
if val != nil {
*val = binary.LittleEndian.Uint32(buf[voff:])
}
return buf, nil
}
func unpack(data []byte, val interface{}) error {
v := reflect.ValueOf(val).Elem()
if v.Kind() != reflect.Struct || !v.CanSet() {
return fmt.Errorf("must unpack into ptr to struct")
}
for i := 0; i < v.NumField(); i++ {
switch p := v.Field(i).Addr().Interface().(type) {
case *uint8:
if len(data) < 1 {
return fmt.Errorf("buffer smaller than data structure")
}
*p = data[0]
data = data[1:]
case *uint16:
if len(data) < 2 {
return fmt.Errorf("buffer smaller than data structure")
}
*p = binary.LittleEndian.Uint16(data)
data = data[2:]
case *uint32:
if len(data) < 4 {
return fmt.Errorf("buffer smaller than data structure")
}
*p = binary.LittleEndian.Uint32(data)
data = data[4:]
case *[numBlocks]uint32:
for i := 0; i < numBlocks; i++ {
if len(data) < 4 {
return fmt.Errorf("buffer smaller than data structure")
}
p[i] = binary.LittleEndian.Uint32(data)
data = data[4:]
}
default:
return fmt.Errorf("unexpected field type %T", p)
}
}
return nil
}