This repository has been archived by the owner on Mar 22, 2023. It is now read-only.
/
package.go
806 lines (673 loc) · 18.4 KB
/
package.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
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
package vpkg
/**
* SPDX-License-Identifier: Apache-2.0
* Copyright 2020 vorteil.io Pty Ltd
*/
import (
"bytes"
"compress/flate"
"compress/gzip"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"hash"
"hash/adler32"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
"github.com/djherbis/buffer"
"github.com/djherbis/nio"
"github.com/vorteil/vorteil/pkg/vcfg"
"github.com/vorteil/vorteil/pkg/vio"
)
// Suffix is the canonical file-extension given to Vorteil
// package files.
const Suffix = ".vorteil"
/*
The Vorteil package structure includes a small package header
containing information used to determine the correct way to
read the package. It starts with a "magic number" used to
identify that the file is indeed a vorteil package.
After the package header the remainder of the file is an
optionally compressed archive containing all of the components
needed to produce a Vorteil disk image.
*/
const magic = 0x004c494554524f56 // "VORTEIL "
type header struct {
Magic uint64
VersionMajor uint8
VersionMinor uint8
VersionPatch uint8
Pad [501]byte
}
const headerLength = 512
// these path constants exist to standardize the names of
// critical package elements within Vorteil packages. They
// are named this way because the archiving logic orders
// them alphabetically, and we prefer the components to be
// extracted in this order for performance reasons.
const (
vcfgPath = "./1.vcfg"
iconPath = "./2.icon"
fsPath = "./4.fs"
)
// ..
const (
SemverMajor = 3
SemverMinor = 0
SemverRevision = 0
)
// Hasher ..
type Hasher struct {
hash.Hash32
}
// NewHasher ..
func NewHasher() *Hasher {
return &Hasher{
Hash32: adler32.New(),
}
}
// String ..
func (h *Hasher) String() string {
return fmt.Sprintf(hex.EncodeToString(h.Sum(nil)))
}
// Compression constants are defined here and copied from
// the standard library flate package so that code importing
// vpkg does not need to also import flate.
//
// The compression levels dictate how much work should be
// done to compress the contents of a package. Values other
// that those defined in these constants are acceptable,
// see the flate package documentation for for information.
const (
NoCompression = flate.NoCompression
BestSpeed = flate.BestSpeed
BestCompression = flate.BestCompression
DefaultCompression = flate.BestSpeed
HuffmanOnly = flate.HuffmanOnly
)
// Builder defines a class of object that can be used to
// organize and then construct the contents of a new Vorteil
// package.
type Builder interface {
Close() error
// Pack writes the Vorteil package to the provided
// io.Writer.
Pack(w io.Writer) error
// SetCompressionLevel is an advanced function that
// can be used to adjust the amount of compression
// that is done to the contents of the Vorteil
// package. The default is DefaultCompression.
SetCompressionLevel(level int)
// SetMonitoringOptions is an advanced function that
// can be used to add logging and progress reporting
// to packaging operations, in addition to other
// possible uses. See the documentation for the
// MonitoringOptions object for more information.
SetMonitoringOptions(opts MonitoringOptions)
// SetVCFG takes the provided vio.File and uses it
// as the vcfg for the package, overwriting any
// previously existing vcfg.
//
// Note: this is NOT a vcfg merge operation. It
// completely supercedes previous existing vcfgs.
SetVCFG(f vio.File) error
MergeVCFG(cfg *vcfg.VCFG) error
// SetIcon takes the provided vio.File and uses it
// as the icon for the package, overwriting any
// previously existing icon.
SetIcon(f vio.File) error
// RemoveFromFS removes a single filesystem mapping
// from the package.
RemoveFromFS(path string) error
// AddToFS takes the single vio.File and maps it
// into the filesystem for the package, replacing
// anything it conflicts with and automatically
// creating parent directories on demand if required.
//
// Absolute and relative paths are both acceptable,
// with relative paths being relative to the root
// directory of the filesystem. For example, the
// following are all equivalent:
//
// dir/file
// /dir/file
// ./dir/file
AddToFS(path string, f vio.File) error
// AddSubTreeToFS takes an entire vio.FileTree
// and maps it into the filesystem for the package,
// replacing anything it conflicts with and
// automatically creating parent directories on
// demand if required.
//
// Absolute and relative paths are both acceptable,
// with relative paths being relative to the root
// directory of the filesystem. For example, the
// following are all equivalent:
//
// dir/file
// /dir/file
// ./dir/file
AddSubTreeToFS(path string, sub vio.FileTree) error
}
type builder struct {
tree vio.FileTree
vcfg vio.File
compressionLevel int
monitoring MonitoringOptions
closeFunc func() error
}
// NewBuilder returns an implementation of the Builder
// interface. The returned Builder will have an empty
// filesystem and no defined binary, vcfg, or icon. At a
// minimum, the Builder.SetBinary and Builder.SetVCFG functions
// must each be called once before the Builder.Pack function
// to constitute a valid and complete package.
func NewBuilder() Builder {
mt, _ := time.ParseInLocation(time.RFC3339, "1970-01-01T00:00:00Z", time.UTC)
b := &builder{
tree: vio.NewFileTree(),
compressionLevel: DefaultCompression,
}
b.tree.Map(fsPath, vio.CustomFile(vio.CustomFileArgs{
Name: filepath.Base(fsPath),
Size: 0,
// ModTime: time.Unix(0, 0),
ModTime: mt,
IsDir: true,
ReadCloser: ioutil.NopCloser(strings.NewReader("")),
}))
return b
}
// NewBuilderFromReader returns an implementation of the
// Builder interface with all of its internal components
// initialized to the values stored within an existing
// Vorteil package, as found in a Reader.
//
// If no further changes are made to the Builder or Reader,
// this package guarantees that the output of its Builder.Pack
// function will be identical to the input for the Load
// function that created the Reader.
func NewBuilderFromReader(rdr Reader) (Builder, error) {
var err error
b := NewBuilder()
b.(*builder).closeFunc = rdr.Close
err = b.SetVCFG(rdr.VCFG())
if err != nil {
return nil, err
}
err = b.SetIcon(rdr.Icon())
if err != nil {
return nil, err
}
err = rdr.FS().Walk(func(path string, f vio.File) error {
return b.AddToFS(path, f)
})
if err != nil {
return nil, err
}
return b, nil
}
func (b *builder) Close() error {
if b.closeFunc != nil {
b.closeFunc()
}
return b.tree.Close()
}
func (b *builder) SetVCFG(f vio.File) error {
b.vcfg = f
return b.tree.Map(vcfgPath, f)
}
func (b *builder) MergeVCFG(cfg *vcfg.VCFG) error {
v, err := vcfg.LoadFile(b.vcfg)
if err != nil {
return err
}
err = v.Merge(cfg)
if err != nil {
return err
}
f, err := v.File()
if err != nil {
return err
}
err = b.SetVCFG(f)
if err != nil {
return err
}
return nil
}
func (b *builder) SetIcon(f vio.File) error {
return b.tree.Map(iconPath, f)
}
func (b *builder) SetCompressionLevel(level int) {
b.compressionLevel = level
}
func (b *builder) SetMonitoringOptions(opts MonitoringOptions) {
b.monitoring = opts
}
func (b *builder) RemoveFromFS(path string) error {
path = strings.TrimPrefix(path, "/")
if path == "" {
return errors.New("cannot remove empty path from filesystem")
}
return b.tree.Unmap(fsPath + "/" + path)
}
func (b *builder) AddToFS(path string, f vio.File) error {
path = strings.TrimPrefix(path, "/")
if path == "" {
return errors.New("cannot add empty path to filesystem")
}
return b.tree.Map(fsPath+"/"+path, f)
}
func (b *builder) AddSubTreeToFS(path string, sub vio.FileTree) error {
path = strings.TrimPrefix(path, "/")
err := sub.Walk(func(p string, f vio.File) error {
p = filepath.Clean(filepath.Join(path, p))
return b.AddToFS(p, f)
})
return err
// return b.tree.MapSubTree(fsPath+"/"+path, sub)
}
type multireader struct {
io.Reader
io.Closer
}
func (b *builder) Pack(w io.Writer) error {
var err error
err = b.monitoring.preprocess(b)
if err != nil {
return err
}
mw := b.monitoring.writer(w)
hdr := new(header)
hdr.Magic = magic
hdr.VersionMajor = SemverMajor
hdr.VersionMinor = SemverMinor
hdr.VersionPatch = SemverRevision
err = binary.Write(mw, binary.LittleEndian, hdr)
if err != nil {
return err
}
gz, err := gzip.NewWriterLevel(w, b.compressionLevel)
if err != nil {
return err
}
defer gz.Close()
mw = b.monitoring.writer(gz)
err = b.tree.Archive(mw, b.monitoring.archiveMonitoringFunc())
if err != nil {
return err
}
err = gz.Close()
if err != nil {
return err
}
return nil
}
// PreProcessReport contains information compiled by the
// packaging logic about an upcoming pack operation, before
// the packing actually begins. It is used only as an
// argument to the callback function at
// MonitoringOptions.PreProcessCompleteCallback, and is
// useful for initializing things like progress bars.
type PreProcessReport struct {
NodeCount int
PackageSize int
}
// MonitoringOptions contains optional fields that may be
// provided in a call to Builder.SetMonitoringOptions to
// receive live information about a pack operation as it
// occurs.
//
// The PreProcessCompleteCallback, if provided, will be
// called precisely once. It will be called before anything
// is written to the PreCompressionWriter, and before any
// calls to the NextFileCallback. It provides the callback
// with information it has compiled about the contents of
// the Builder such as the total size of the uncompressed
// package, which can be helpful for keeping live progress
// tracking. If an error is returned the Builder.Pack
// function will fail, which means this callback can also
// be used to cancel a job if the PreProcessReport is
// unacceptable. If left nil, no such information is compiled
// and the Builder.Pack operation will be faster.
//
// NextFileCallback will be called once for each file and
// directory within the package. It is called just before
// that file is added to the archive, and provides
// information that can be used to report specifically what
// part of the packaging process the Builder.Pack logic has
// reached at any time. If an error is returned the
// Builder.Pack function will fail, which means this callback
// can also be used to cancel a job.
//
// If not nil, all data written to the package will be cloned
// to the PreCompressionWriter, uncompressed. The main
// forseen use for this is to track byte-by-byte how far
// along the complete Builder.Pack operation has come.
// Errors returned by the PreCompressionWriter will cause
// the Builder.Pack operation to fail, which means this
// writer can also be used to cancel a job.
type MonitoringOptions struct {
PreProcessCompleteCallback func(report PreProcessReport) error
NextFileCallback func(path string, fi os.FileInfo) error
PreCompressionWriter io.Writer
}
func (opts *MonitoringOptions) preprocess(b Builder) error {
if opts.PreProcessCompleteCallback == nil {
return nil
}
report := new(PreProcessReport)
report.PackageSize += headerLength
report.PackageSize += 1024
a := b.(*builder)
err := a.tree.Walk(func(path string, f vio.File) error {
report.NodeCount++
report.PackageSize += ((f.Size()+512-1)/512)*512 + 512
if len(path) > 100 {
report.PackageSize += 1024
}
return nil
})
if err != nil {
return err
}
err = opts.PreProcessCompleteCallback(*report)
if err != nil {
return err
}
return nil
}
func (opts *MonitoringOptions) writer(w io.Writer) io.Writer {
if opts.PreCompressionWriter == nil {
return w
}
return io.MultiWriter(w, opts.PreCompressionWriter)
}
func (opts *MonitoringOptions) archiveMonitoringFunc() vio.ArchiveFunc {
if opts.NextFileCallback == nil {
return nil
}
return func(path string, f vio.File) error {
prefixes := []string{vcfgPath, iconPath, fsPath}
for _, prefix := range prefixes {
if strings.HasPrefix(path, prefix) {
path = strings.TrimPrefix(path, prefix)
break
}
}
if path == "" {
return nil
}
if path == "." {
path = "/"
}
return opts.NextFileCallback(path, vio.Info(f))
}
}
// ..
var (
SupportedPackageMajor = 3
)
// ErrNotAPackage is returned when attempting to extract the
// contents of a file that not a Vorteil package, or at least
// is broken or corrupt.
var ErrNotAPackage = errors.New("not a valid package")
// ErrVersionNotSupported is returned when attempting to read an unsupported
// Vorteil package version.
var ErrVersionNotSupported = fmt.Errorf("package version not supported (require version %v.x.x)", SupportedPackageMajor)
// Reader defines a class of object that can be used to
// read specific information from a Vorteil package.
type Reader interface {
// VCFG returns a vio.File object containing the
// complete Vorteil configuration settings to be
// used with the application.
VCFG() vio.File
// Icon returns a vio.File object containing a
// picture file used as an icon representing the
// package and application.
//
// This function will always returns a valid vio.File,
// but packages commonly will not have an icon and
// the calling logic should check the length of this
// file (which will be zero in this circumstance) to
// understand if an icon actually exists for the
// package.
Icon() vio.File
// FS returns a vio.FileTree object representing
// the total contents of the main filesystem on the
// app's virtual disk.
FS() vio.FileTree
Close() error
}
type reader struct {
closeFunc func() error
vcfg vio.File
icon vio.File
fs vio.FileTree
}
func (r *reader) Close() error {
if r.closeFunc != nil {
r.closeFunc()
}
r.vcfg.Close()
if r.icon != nil {
r.icon.Close()
}
r.fs.Close()
return nil
}
func ReaderFromBuilder(b Builder) (Reader, error) {
rdr := new(reader)
rdr.closeFunc = b.Close
bx, ok := b.(*builder)
if !ok {
r, w := nio.Pipe(buffer.New(0x100000))
go func() {
defer b.Close()
b.SetCompressionLevel(NoCompression)
err := b.Pack(w)
if err != nil {
w.CloseWithError(err)
return
}
w.Close()
}()
return Load(r)
}
tree := bx.tree
err := tree.Walk(func(path string, f vio.File) error {
switch path {
case vcfgPath:
rdr.vcfg = f
case iconPath:
rdr.icon = f
case fsPath:
return vio.ErrSkip
case ".":
return nil
default:
return fmt.Errorf("unexpected archive element: %v", path)
}
return nil
})
if err != nil {
return nil, err
}
rdr.fs, err = tree.SubTree(fsPath)
if err != nil {
return nil, err
}
return rdr, nil
}
// Load extracts information from the provided io.Reader
// and turns it into an implementation of the Reader interface,
// if the reader is a stream of valid Vorteil package data.
//
// This function loads information from the reader lazily,
// and in a predictable order that can be exploited by properly
// designed logic to minimize the amount of ram caching
// required without ever using temporary files.
//
// Because the Reader is loaded lazily, the provided io.Reader
// must remain valid for the lifetime of the Reader. If the
// provided io.Reader is also an io.Closer, it should NOT be
// closed until the reader is no longer required.
//
// The lazy loading won't necessarily consume the entire
// contents of the io.Reader up until EOF unless the calling
// logic makes use of the entire contents of the package.
// If it is important to consume the entire stream, you may
// want to io.Copy(ioutil.Discard, r) before closing it.
func Load(r io.Reader) (Reader, error) {
var err error
hdr := new(header)
err = binary.Read(r, binary.LittleEndian, hdr)
if err != nil {
return nil, err
}
if hdr.Magic != magic {
return nil, ErrNotAPackage
}
if hdr.VersionMajor != uint8(SupportedPackageMajor) {
return nil, ErrVersionNotSupported
}
gz, err := gzip.NewReader(r)
if err != nil {
return nil, err
}
defer gz.Close()
tree, err := vio.LoadArchive(gz)
if err != nil {
return nil, err
}
rdr := new(reader)
if closer, ok := r.(io.ReadCloser); ok {
rdr.closeFunc = closer.Close
}
err = tree.Walk(func(path string, f vio.File) error {
switch path {
case vcfgPath:
rdr.vcfg = f
case iconPath:
rdr.icon = f
case fsPath:
return vio.ErrSkip
case ".":
return nil
default:
return fmt.Errorf("unexpected archive element: %v", path)
}
return nil
})
if err != nil {
return nil, err
}
rdr.fs, err = tree.SubTree(fsPath)
if err != nil {
return nil, err
}
return rdr, nil
}
// VCFG ..
func (r *reader) VCFG() vio.File {
return r.vcfg
}
// Icon ..
func (r *reader) Icon() vio.File {
if r.icon == nil {
return vio.CustomFile(vio.CustomFileArgs{
ReadCloser: ioutil.NopCloser(strings.NewReader("")),
})
}
return r.icon
}
// FS ..
func (r *reader) FS() vio.FileTree {
return r.fs
}
// ComputeHash ..
func ComputeHash(r io.Reader) (string, error) {
hasher := NewHasher()
rdr, err := Load(r)
if err != nil {
return "", err
}
bldr, err := NewBuilderFromReader(rdr)
if err != nil {
return "", err
}
bldr.SetMonitoringOptions(MonitoringOptions{
PreCompressionWriter: hasher,
})
err = bldr.Pack(ioutil.Discard)
if err != nil {
return "", err
}
return hasher.String(), nil
}
type peekVCFGReader struct {
vcfg vio.File
vcfgdata []byte
Reader
}
// ReplaceVCFG ...
func ReplaceVCFG(r Reader, f vio.File) (Reader, error) {
rdr, err := PeekVCFG(r)
if err != nil {
return nil, err
}
rdr.VCFG()
data, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
x := rdr.(*peekVCFGReader)
x.vcfgdata = data
return x, nil
}
// PeekVCFG ..
func PeekVCFG(r Reader) (Reader, error) {
rdr := new(peekVCFGReader)
rdr.Reader = r
return rdr, nil
}
func (rdr *peekVCFGReader) VCFG() vio.File {
if rdr.vcfgdata == nil {
f := rdr.Reader.VCFG()
var err error
rdr.vcfgdata, err = ioutil.ReadAll(f)
if err != nil {
panic(err)
}
rdr.vcfg = vio.CustomFile(vio.CustomFileArgs{
Name: f.Name(),
Size: f.Size(),
ModTime: f.ModTime(),
IsDir: f.IsDir(),
IsSymlink: f.IsSymlink(),
ReadCloser: ioutil.NopCloser(bytes.NewReader(rdr.vcfgdata)),
})
return rdr.vcfg
}
return vio.CustomFile(vio.CustomFileArgs{
Name: rdr.vcfg.Name(),
Size: rdr.vcfg.Size(),
ModTime: rdr.vcfg.ModTime(),
IsDir: rdr.vcfg.IsDir(),
IsSymlink: rdr.vcfg.IsSymlink(),
ReadCloser: ioutil.NopCloser(bytes.NewReader(rdr.vcfgdata)),
})
}
func Open(path string) (Reader, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
return Load(f)
}