-
Notifications
You must be signed in to change notification settings - Fork 0
/
jre_installation.go
461 lines (371 loc) · 12.3 KB
/
jre_installation.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
package launcher
import (
"crypto/sha1"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path"
"path/filepath"
"runtime"
"github.com/brawaru/marct/launcher/download"
"github.com/brawaru/marct/launcher/java"
"github.com/brawaru/marct/utils"
"github.com/brawaru/marct/validfile"
"github.com/itchio/lzma"
)
// FileState represents the state of a file.
type FileState int
const (
FileStateUnknown FileState = iota // File has not yet been checked.
FileStateNotDownloaded // File has not yet been downloaded.
FileStateCorrupted // File is corrupted and must be deleted.
FileStateDownloaded // File is downloaded and ready to be mapped.
FileStateReady // File is mapped and ready.
)
type JREObject struct {
JavaFile // File to download.
Destination string // Where the object is stored.
ObjectDestination string // Where the unmapped object is stored.
State FileState // State of the file.
IsRaw bool // Whether the file stores is raw or compressed.
}
type JREInstallation struct {
Classifier string
Selector string
Descriptor *JavaVersionDescriptor
Manifest *JavaManifest
Path string // Root path of the installation
stagingPath string // Path to the staging directory where all the objects are downloaded
objects map[string]*JREObject // All objects in the installation
filesPath string // Path to the files' directory where the final files are stored
}
func NewInstallation(classifier string, selector string, descriptor *JavaVersionDescriptor, path string) *JREInstallation {
stagingPath := filepath.Join(path, classifier+"_staging")
filesPath := filepath.Join(path, classifier)
return &JREInstallation{
Classifier: classifier,
Selector: selector,
Descriptor: descriptor,
Path: path,
objects: make(map[string]*JREObject),
stagingPath: stagingPath,
filesPath: filesPath,
}
}
func (i *JREInstallation) fetchManifest() error {
if i.Descriptor == nil {
return errors.New("descriptor is nil")
}
dest := filepath.Join(i.Path, ".manifest")
if err := download.FromURL(i.Descriptor.Manifest.URL, dest, download.WithSHA1(i.Descriptor.Manifest.SHA1)); err != nil {
return fmt.Errorf("download %q to %q: %w", i.Descriptor.Manifest.URL, dest, err)
}
if bytes, err := os.ReadFile(dest); err != nil {
return fmt.Errorf("read manifest file %q: %w", dest, err)
} else if err := json.Unmarshal(bytes, &i.Manifest); err != nil {
return fmt.Errorf("unmarshal manifest file %q: %w", dest, err)
}
return nil
}
func (i *JREInstallation) prepareObjects() error {
if i.Manifest == nil {
return errors.New("manifest is nil")
}
i.objects = make(map[string]*JREObject, 0)
for dest, file := range i.Manifest.Files {
i.objects[dest] = &JREObject{
JavaFile: file,
Destination: filepath.Join(i.filesPath, filepath.FromSlash(dest)),
State: FileStateUnknown,
}
}
return nil
}
func (i *JREInstallation) validateObject(fp string, object *JREObject) error {
state := FileStateNotDownloaded
switch object.Type {
case java.TypeDir:
if exists, statErr := validfile.DirExists(object.Destination); statErr != nil {
if errors.Is(statErr, &validfile.WrongPathType{}) {
state = FileStateCorrupted
} else {
return fmt.Errorf("dir %q stat failed: %w", object.Destination, statErr)
}
} else if exists {
state = FileStateReady
}
case java.TypeLink:
tfp := path.Clean(path.Join(path.Dir(fp), object.Target))
target, exists := i.objects[tfp]
if !exists {
return fmt.Errorf("object %q targets %q, which is not present in object set", fp, tfp)
} else {
if runtime.GOOS == "windows" {
// cannot check where hardlink points to, so have to actually verify the file
if pathExists, err := validfile.PathExists(object.Destination); err != nil {
return fmt.Errorf("path %q stat failed: %w", object.Destination, err)
} else if pathExists {
rawDl := target.Downloads["raw"]
if validateErr := validfile.ValidateFileHex(object.Destination, sha1.New(), rawDl.SHA1); validateErr != nil {
if !utils.DoesNotExist(validateErr) {
var v *validfile.ValidateError
if !errors.As(validateErr, &v) || v.Mismatch() {
state = FileStateCorrupted // either refers to a different file or is actually corrupted
} else {
return fmt.Errorf("cannot validate linked file %q: %w", object.Destination, validateErr)
}
}
} else {
state = FileStateReady
}
} else {
state = FileStateNotDownloaded
}
} else {
linkDestination, err := os.Readlink(object.Destination)
if err != nil {
if !utils.DoesNotExist(err) {
return fmt.Errorf("cannot read link %q: %w", object.Destination, err)
}
} else if linkDestination == object.Target || linkDestination == target.Destination {
state = FileStateReady
} else {
state = FileStateCorrupted
}
}
}
case java.TypeFile:
rawDl := object.Downloads["raw"]
if validateErr := validfile.ValidateFileHex(object.Destination, sha1.New(), rawDl.SHA1); validateErr != nil {
if !utils.DoesNotExist(validateErr) {
var v *validfile.ValidateError
if !errors.As(validateErr, &v) || v.Mismatch() {
state = FileStateCorrupted
} else {
return fmt.Errorf("cannot validate file %q: %w", object.Destination, validateErr)
}
}
} else {
state = FileStateReady
}
}
object.State = state
return nil
}
func (i *JREInstallation) validateObjects() (bool, error) {
success := true
for fp, object := range i.objects {
if err := i.validateObject(fp, object); err != nil {
return false, fmt.Errorf("failed to validate object %q: %w", fp, err)
}
if object.State != FileStateReady {
success = false
}
}
return success, nil
}
func (i *JREInstallation) deleteCorrupted() error {
for _, object := range i.objects {
if object.State == FileStateCorrupted {
if err := os.RemoveAll(object.Destination); err != nil {
return fmt.Errorf("cannot delete corrupted file %q: %w", object.Destination, err)
}
}
}
return nil
}
func (i *JREInstallation) downloadFiles() error {
for fp, object := range i.objects {
if !object.Type.IsFile() {
continue
}
var objectDl Download
isRaw := false
if lzmaDl, hasLzma := object.Downloads["lzma"]; hasLzma {
objectDl = lzmaDl
} else if rawDl, hasRaw := object.Downloads["raw"]; hasRaw {
objectDl = rawDl
isRaw = true
} else {
return fmt.Errorf("file %q has no downloads?! O_o", fp)
}
dest := filepath.Join(i.stagingPath, objectDl.SHA1)
if err := download.FromURL(objectDl.URL, dest, download.WithSHA1(objectDl.SHA1)); err != nil {
return fmt.Errorf("download %q to %q: %w", objectDl.URL, fp, err)
}
object.IsRaw = isRaw
object.ObjectDestination = dest
object.State = FileStateDownloaded
}
return nil
}
func (i *JREInstallation) mapDir(_ string, object *JREObject) error {
if mdErr := os.MkdirAll(object.Destination, 0755); mdErr != nil {
return fmt.Errorf("cannot create directory %q: %w", object.Destination, mdErr)
}
return nil
}
func (i *JREInstallation) mapLink(fp string, object *JREObject) error {
tfp := path.Clean(path.Join(path.Dir(fp), object.Target))
target, exists := i.objects[tfp]
if !exists {
return fmt.Errorf("expected %q to exist", tfp)
}
if target.State != FileStateReady {
if mapErr := i.mapObject(tfp, target); mapErr != nil {
return fmt.Errorf("target %q cannot be mapped: %w", tfp, mapErr)
}
}
if err := os.MkdirAll(filepath.Dir(object.Destination), 0755); err != nil {
return fmt.Errorf("cannot create parent directories for %q: %w", target.Destination, err)
}
if runtime.GOOS == "windows" {
// on Windows, usage of symbolic links requires elevated privileges, thus we use hard links instead
if linkErr := os.Link(target.Destination, object.Destination); linkErr != nil {
return fmt.Errorf("hardlink failed: %w", linkErr)
}
} else {
if linkErr := os.Symlink(object.Target, object.Destination); linkErr != nil {
return fmt.Errorf("symlink failed: %w", linkErr)
}
}
return nil
}
func (i *JREInstallation) mapFile(_ string, object *JREObject) error {
if dir := filepath.Dir(object.Destination); dir != "." {
if mkdirErr := os.MkdirAll(dir, 0755); mkdirErr != nil {
return fmt.Errorf("cannot create parent directories for %q: %w", object.Destination, mkdirErr)
}
}
file, createErr := os.Create(object.Destination)
if createErr != nil {
return fmt.Errorf("cannot create file %q: %w", object.Destination, createErr)
}
objectFile, openErr := os.Open(object.ObjectDestination)
if openErr != nil {
return fmt.Errorf("cannot open file %q: %w", object.ObjectDestination, openErr)
}
srcReader := io.Reader(objectFile)
if !object.IsRaw {
srcReader = lzma.NewReader(objectFile)
}
if _, copyErr := io.Copy(file, srcReader); copyErr != nil {
return fmt.Errorf("cannot copy %q to %q: %w", object.ObjectDestination, object.Destination, copyErr)
}
utils.DClose(objectFile)
utils.DClose(file)
rawDl := object.Downloads["raw"]
if validateErr := validfile.ValidateFileHex(object.Destination, sha1.New(), rawDl.SHA1); validateErr != nil {
return validateErr
}
if object.Executable {
if stat, statErr := os.Stat(object.Destination); statErr != nil {
return fmt.Errorf("cannot stat file %q: %w", object.Destination, statErr)
} else if chmodErr := os.Chmod(object.Destination, stat.Mode()|0b1000000); chmodErr != nil {
return fmt.Errorf("cannot mark file %q as executable: %w", object.Destination, chmodErr)
}
}
return nil
}
func (i *JREInstallation) mapObject(fp string, object *JREObject) error {
if object.State == FileStateReady {
return nil
}
switch object.Type {
case java.TypeLink:
if err := i.mapLink(fp, object); err != nil {
return err
}
case java.TypeFile:
if err := i.mapFile(fp, object); err != nil {
return err
}
case java.TypeDir:
if err := i.mapDir(fp, object); err != nil {
return err
}
}
object.State = FileStateReady
return nil
}
func (i *JREInstallation) mapObjects() error {
for fp, object := range i.objects {
if err := i.mapObject(fp, object); err != nil {
return fmt.Errorf("cannot map %q: %w", fp, err)
}
}
return nil
}
func (i *JREInstallation) deleteStaging() error {
if err := os.RemoveAll(i.stagingPath); err != nil {
return fmt.Errorf("cannot delete staging directory %q: %w", i.stagingPath, err)
}
return nil
}
func (i *JREInstallation) writeVersion() error {
versionFile, createErr := os.Create(filepath.Join(i.Path, ".version"))
if createErr == nil {
defer utils.DClose(versionFile)
if _, writeErr := versionFile.WriteString(i.Descriptor.Version.Name); writeErr != nil {
return fmt.Errorf("cannot write version file: %w", writeErr)
}
}
return createErr
}
type PostValidationError struct {
BadObjects []JREObject
}
func (p *PostValidationError) Error() string {
return fmt.Sprintf("%d objects failed post-validation", len(p.BadObjects))
}
func (i *JREInstallation) Install() error {
// 0. fetch manifest
if i.Manifest == nil {
if err := i.fetchManifest(); err != nil {
return err
}
}
if err := i.prepareObjects(); err != nil {
return fmt.Errorf("cannot prepare objects: %w", err)
}
// 1. validate all files
if allValid, err := i.validateObjects(); err != nil {
return fmt.Errorf("cannot validate objects: %w", err)
} else if allValid {
return nil
}
// 2. delete corrupted ones
if err := i.deleteCorrupted(); err != nil {
return fmt.Errorf("cannot delete corrupted files: %w", err)
}
// 3. download missing ones
if err := i.downloadFiles(); err != nil {
return fmt.Errorf("cannot download files: %w", err)
}
// 4. map them
if err := i.mapObjects(); err != nil {
return fmt.Errorf("cannot map objects: %w", err)
}
// 5. delete staging directory
if err := i.deleteStaging(); err != nil {
return fmt.Errorf("cannot delete staging directory: %w", err)
}
// 6. write version file
if err := i.writeVersion(); err != nil {
return fmt.Errorf("cannot write version file: %w", err)
}
if allValid, err := i.validateObjects(); err != nil {
return err
} else if !allValid {
var faulty []JREObject
for _, object := range i.objects {
if object.State != FileStateReady {
faulty = append(faulty, *object)
}
}
return &PostValidationError{faulty}
}
return nil
}