-
Notifications
You must be signed in to change notification settings - Fork 42
/
isoutils.go
740 lines (636 loc) · 18.1 KB
/
isoutils.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
// Copyright © 2020 Intel Corporation
//
// SPDX-License-Identifier: GPL-3.0-only
package isoutils
import (
"bytes"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"syscall"
"text/template"
"github.com/clearlinux/clr-installer/args"
"github.com/clearlinux/clr-installer/cmd"
"github.com/clearlinux/clr-installer/log"
"github.com/clearlinux/clr-installer/model"
"github.com/clearlinux/clr-installer/progress"
"github.com/clearlinux/clr-installer/swupd"
"github.com/clearlinux/clr-installer/utils"
)
type paths int
const (
clrEfi paths = iota + 0
clrImgEfi // Location to mount the EFI partition in the passed-in img file
clrInitrd
clrRootfs
clrCdroot
)
var (
tmpPaths = make([]string, 5)
)
func mkTmpDirs() error {
msg := "Making temp directories for ISO creation"
prg := progress.NewLoop(msg)
log.Info(msg)
var err error
tmpPaths[clrEfi], err = ioutil.TempDir("", "clrEfi-")
if err != nil {
prg.Failure()
return err
}
tmpPaths[clrInitrd], err = ioutil.TempDir("", "clrInitrd-")
if err != nil {
prg.Failure()
return err
}
tmpPaths[clrCdroot], err = ioutil.TempDir("", "clrCdroot-")
if err != nil {
prg.Failure()
return err
}
/* Create specific directories for the new cd's root */
for _, d := range []string{
tmpPaths[clrCdroot] + "/isolinux",
tmpPaths[clrCdroot] + "/EFI",
tmpPaths[clrCdroot] + "/images",
tmpPaths[clrCdroot] + "/kernel",
} {
if _, err := os.Stat(d); os.IsNotExist(err) {
err = os.Mkdir(d, os.ModePerm)
if err != nil {
prg.Failure()
return err
}
}
}
prg.Success()
return err
}
func mkRootfs() error {
msg := "Making squashfs of rootfs"
prg := progress.NewLoop(msg)
log.Info(msg)
/* TODO: This takes a long time to run, it'd be nice to see it's output as it's running */
args := []string{
"mksquashfs",
tmpPaths[clrRootfs],
tmpPaths[clrCdroot] + "/images/rootfs.img",
"-b",
"131072",
"-comp",
"gzip",
"-e",
"boot/",
"-e",
"proc/",
"-e",
"sys/",
"-e",
"dev/",
"-e",
"run/",
}
err := cmd.RunAndLog(args...)
if err != nil {
prg.Failure()
return err
}
prg.Success()
return err
}
// GetIsoLoopDevice returns the name of the ISO loop device
func GetIsoLoopDevice() string {
w := bytes.NewBuffer(nil)
args := []string{
"losetup",
"-j",
"/mnt/media/images/rootfs.img",
"-O",
"NAME",
"-n",
}
err := cmd.Run(w, args...)
if err != nil {
return ""
}
if strings.Compare(w.String(), "") == 0 {
return ""
}
return strings.TrimSuffix(w.String(), "\n")
}
// ExtractSquashfs extracts the src directory from a squashfs to the dest directory
func ExtractSquashfs(src, dest, loopDev string) error {
args := []string{
"unsquashfs",
"-d",
dest,
"-f",
loopDev,
"-e",
src,
}
err := cmd.RunAndLog(args...)
if err != nil {
return err
}
return err
}
func mkInitrd(version string, model *model.SystemInstall, options args.Args) error {
msg := "Installing the base system for initrd"
var prg progress.Progress
log.Info(msg)
var err error
options.SwupdStateDir = tmpPaths[clrInitrd] + "/var/lib/swupd/"
options.SwupdFormat = "staging"
sw := swupd.New(tmpPaths[clrInitrd], options, model)
/* Install os-core and os-core-plus (we only need kmod-bin) as initrd */
if err := sw.OSInstall(version, swupd.IsoPrefix, []string{"clr-installer-iso-init"}); err != nil {
prg = progress.NewLoop(msg)
prg.Failure()
return err
}
prg = progress.NewLoop(msg)
prg.Success()
return err
}
func mkInitrdInitScript(templatePath string) error {
msg := "Creating and installing init script to initrd"
prg := progress.NewLoop(msg)
log.Info(msg)
type Modules struct {
Modules []string
IsoMediaBootOption string
}
mods := Modules{IsoMediaBootOption: args.KernelMediaCheck}
//Modules to insmod during init, paths relative to the kernel folder
modules := []string{
"/kernel/drivers/cdrom/cdrom.ko",
"/kernel/drivers/scsi/sr_mod.ko",
"/kernel/fs/isofs/isofs.ko",
"/kernel/fs/overlayfs/overlay.ko",
}
/* Find kernel, then break the name into kernelVersion */
kernelGlob, err := filepath.Glob(tmpPaths[clrRootfs] + "/lib/kernel/org.clearlinux.*")
if err != nil || len(kernelGlob) != 1 {
prg.Failure()
log.Error("Failed to determine kernel revision or > 1 kernel found")
return err
}
kernelTypeVersion := strings.SplitAfter(filepath.Base((kernelGlob[0])), "org.clearlinux.")[1]
kernelType := strings.Split(kernelTypeVersion, ".")[0] //kernelType examples: native,kvm,lts2018,hyperv
kernelVersion := strings.SplitAfter(kernelTypeVersion, kernelType+".")[1]
/* Copy files to initrd, and add to mods so they're added to the init template */
for _, i := range modules {
rootfsModPath := tmpPaths[clrRootfs] + "/usr/lib/modules/" + kernelVersion + "." + kernelType + i
/* copy kernel module to initramfs */
initrdModPath := filepath.Dir(tmpPaths[clrInitrd] + "/usr/lib/modules/" + kernelVersion + "." + kernelType + i)
if _, err := os.Stat(initrdModPath); os.IsNotExist(err) {
err = os.MkdirAll(initrdModPath, os.ModePerm)
if err != nil {
prg.Failure()
return err
}
}
err = utils.CopyFile(rootfsModPath, initrdModPath+"/"+filepath.Base(i))
if err != nil {
prg.Failure()
return err
}
mods.Modules = append(mods.Modules, "/usr/lib/modules/"+kernelVersion+"."+kernelType+i)
}
tmpl, err := ioutil.ReadFile(templatePath + "/initrd_init_template")
if err != nil {
prg.Failure()
log.Error("Failed to open: initrd template at %s\n", templatePath+"initrd_init_template")
return err
}
t := template.New("Modules template")
t, err = t.Parse(string(tmpl))
if err != nil {
prg.Failure()
log.Error("Failed to parse init's template")
return err
}
f, err := os.Create(tmpPaths[clrInitrd] + "/init")
if err != nil {
prg.Failure()
log.Error("Failed to create init file for initrd!")
return err
}
defer func() {
_ = f.Close()
}()
err = t.Execute(f, mods)
if err != nil {
prg.Failure()
log.Error("Failed to execute template filling")
return err
}
log.Debug("Init script contents after template expansion: ")
// soft error just needed for logging
_ = cmd.RunAndLog("cat", tmpPaths[clrInitrd]+"/init")
/* Set correct owner and permissions on initrd's init */
if err = os.Chown(tmpPaths[clrInitrd]+"/init", 0, 0); err != nil {
prg.Failure()
return err
}
if err = os.Chmod(tmpPaths[clrInitrd]+"/init", 0700); err != nil {
prg.Failure()
return err
}
prg.Success()
return err
}
/* Build initrd image, and copy to the correct location */
func buildInitrdImage() error {
msg := "Building initrd image"
prg := progress.NewLoop(msg)
log.Info(msg)
// Determine current user's path so we can revert to it when this function ends
currPath, err := os.Getwd()
if err != nil {
prg.Failure()
return err
}
/* find all files in the initrd path, create the initrd */
/* The find command must return filenames without a path (eg, must be run in the current dir) */
err = os.Chdir(tmpPaths[clrInitrd])
if err != nil {
prg.Failure()
return err
}
initrdPath := tmpPaths[clrCdroot] + "/EFI/BOOT/"
if _, err := os.Stat(initrdPath); os.IsNotExist(err) {
err = os.MkdirAll(initrdPath, os.ModePerm)
if err != nil {
prg.Failure()
return err
}
}
args := "sudo find .| cpio -o -H newc | gzip >" + initrdPath + "initrd.gz"
_, err = exec.Command("bash", "-c", args).CombinedOutput()
if err != nil {
prg.Failure()
return err
}
err = os.Chdir(currPath)
if err != nil {
prg.Failure()
return err
}
prg.Success()
return err
}
// We take a copy of options from normal EFI entry and edit it for new EFI entry: /loader/entries/iso-checksum.conf
func prepareISOCheckSumBootEntry(inputOptions []string) []string {
outputOptions := append([]string(nil), inputOptions...)
for i, option := range outputOptions {
if strings.Contains(option, "title") {
outputOptions[i] = "title Verify ISO Integrity"
}
if i == len(outputOptions)-1 {
outputOptions[i] = strings.TrimSpace(option) + " " + args.KernelMediaCheck
}
}
return outputOptions
}
func mkEfiBoot() error {
msg := "Building efiboot image"
prg := progress.NewLoop(msg)
log.Info(msg)
cmds := [][]string{
{"fallocate", "-l", "192M", tmpPaths[clrCdroot] + "/EFI/efiboot.img"},
{"mkfs.fat", "-n", "CLEAR_EFI", tmpPaths[clrCdroot] + "/EFI/efiboot.img"},
{"mount", "-t", "vfat", "-o", "loop", tmpPaths[clrCdroot] + "/EFI/efiboot.img", tmpPaths[clrEfi]},
{"cp", "-pr", tmpPaths[clrImgEfi] + "/.", tmpPaths[clrEfi]},
}
for _, i := range cmds {
err := cmd.RunAndLog(i...)
if err != nil {
prg.Failure()
return err
}
}
/* Modify loader/entries/Clear-linux-*, add initrd= line and remove ROOT= from kernel command line options */
entriesGlob, err := filepath.Glob(tmpPaths[clrEfi] + "/loader/entries/Clear-linux-*")
entriesIsoChecksum := filepath.Join(tmpPaths[clrEfi] + "/loader/entries/iso-checksum.conf")
if err != nil || len(entriesGlob) != 1 {
prg.Failure()
log.Error("Failed to modify efi entries file")
return err
}
input, err := ioutil.ReadFile(entriesGlob[0])
if err != nil {
prg.Failure()
log.Error("Failed to read EFI entries file")
return err
}
/* Replace current options line with initrd information, extract options line for modification */
lines := strings.Split(string(input), "\n")
var optionsLine string
for i, line := range lines {
if strings.Contains(line, "options") {
optionsLine = line
lines[i] = "initrd /EFI/BOOT/initrd.gz"
}
}
options := strings.Split(optionsLine, " ")
for i, option := range options {
if strings.Contains(option, "PARTUUID") {
options = append(options[:i], options[i+1:]...) //remove slice from options
break //no other ops
}
}
lines = append(lines, strings.Join(options, " "))
err = ioutil.WriteFile(entriesGlob[0], []byte(strings.Join(lines, "\n")), 0644)
if err != nil {
prg.Failure()
log.Error("Failed to write kernel boot parameters file")
return err
}
isoBootMenuLines := prepareISOCheckSumBootEntry(lines)
err = ioutil.WriteFile(entriesIsoChecksum, []byte(strings.Join(isoBootMenuLines, "\n")), 0644)
if err != nil {
prg.Failure()
log.Error("Failed to write kernel boot parameters file for isomd5sum check")
return err
}
/* Copy EFI files to the cdroot for Rufus support */
cpCmd := []string{"cp", "-pr", tmpPaths[clrEfi] + "/.", tmpPaths[clrCdroot]}
err = cmd.RunAndLog(cpCmd...)
if err != nil {
prg.Failure()
return err
}
/* Copy initrd to efiboot.img and finally unmount efiboot.img */
initrdPaths := []string{tmpPaths[clrCdroot] + "/EFI/BOOT/initrd.gz", tmpPaths[clrEfi] + "/EFI/BOOT/initrd.gz"}
err = utils.CopyFile(initrdPaths[0], initrdPaths[1])
if err != nil {
prg.Failure()
return err
}
/*
Copy initrd to iso-checksum.conf.
If we dont do this, mkLegacyBoot will fail to find it while creating correspoding isolinux entry
*/
err = utils.CopyFile(tmpPaths[clrEfi]+"/loader/entries/iso-checksum.conf",
tmpPaths[clrImgEfi]+"/loader/entries/iso-checksum.conf")
if err != nil {
prg.Failure()
return err
}
/* Unmount EFI partition here, because this must be unmounted when calling xorriso! */
if err := syscall.Unmount(tmpPaths[clrEfi], syscall.MNT_FORCE|syscall.MNT_DETACH); err != nil {
prg.Failure()
return err
}
prg.Success()
return err
}
func mkLegacyBoot(templatePath string) error {
msg := "Setting up BIOS boot with isolinux"
prg := progress.NewLoop(msg)
log.Info(msg)
type BootConf struct {
Options string
OptionsMediaCheck string
}
bc := BootConf{}
/* Find kernel path so we can copy the kernel later */
kernelGlob, err := filepath.Glob(tmpPaths[clrRootfs] + "/lib/kernel/org.clearlinux.*")
if err != nil || len(kernelGlob) != 1 {
prg.Failure()
return err
}
kernelPath := kernelGlob[0]
paths := [][]string{
{"/usr/share/syslinux/isohdpfx.bin", tmpPaths[clrCdroot] + "/isolinux/isohdpfx.bin"},
{"/usr/share/syslinux/isolinux.bin", tmpPaths[clrCdroot] + "/isolinux/isolinux.bin"},
{"/usr/share/syslinux/ldlinux.c32", tmpPaths[clrCdroot] + "/isolinux/ldlinux.c32"},
{"/usr/share/syslinux/menu.c32", tmpPaths[clrCdroot] + "/isolinux/menu.c32"},
{"/usr/share/syslinux/libutil.c32", tmpPaths[clrCdroot] + "/isolinux/libutil.c32"},
{kernelPath, tmpPaths[clrCdroot] + "/kernel/kernel.xz"},
}
for _, i := range paths {
err = utils.CopyFile(i[0], i[1])
if err != nil {
prg.Failure()
return err
}
}
/* Create the 'boot.txt' file for isolinux */
bootFile, err := os.Create(tmpPaths[clrCdroot] + "/isolinux/boot.txt")
if err != nil {
prg.Failure()
return err
}
defer func() {
_ = bootFile.Close()
}()
_, err = bootFile.WriteString("\n\nClear Linux OS for Intel Architecture\n")
if err != nil {
prg.Failure()
return err
}
// inner Function to remove filter unwanted parts like PARTUUID, word: `option` for different boot menus
filterOptionsLineFunc := func(optionLine []byte) string {
/* Read options from the EFI partition, remove the string 'options' and root=PARTUUID from the options line */
lines := strings.Split(string(optionLine), "\n")
var optionsLineTemp string
for _, line := range lines {
if strings.Contains(line, "options") {
optionsLineTemp = line
}
}
options := strings.Split(optionsLineTemp, " ")
for i, option := range options {
if strings.Contains(option, "options") || strings.Contains(option, "PARTUUID") {
options[i] = ""
}
}
return strings.Join(options, " ")
}
/* Find the (kernel boot) options file, load it into bc.Options */
optionsGlob, err := filepath.Glob(tmpPaths[clrImgEfi] + "/loader/entries/Clear-linux-*")
if err != nil || len(optionsGlob) > 1 { // Fail if there's >1 match
prg.Failure()
log.Error("Failed to determine boot options for kernel")
return err
}
optionsFile, err := ioutil.ReadFile(optionsGlob[0])
if err != nil {
prg.Failure()
log.Error("Failed to read options file from rootfs")
return err
}
bc.Options = filterOptionsLineFunc(optionsFile)
// ISO Integrity boot option
entriesIsoChecksum, err := filepath.Glob(tmpPaths[clrImgEfi] + "/loader/entries/iso-checksum*")
if err != nil || len(entriesIsoChecksum) > 1 { // Fail if there's >1 match
prg.Failure()
log.Error("Failed to determine boot options for ISO Integrity check")
return err
}
optionsFileISO, err := ioutil.ReadFile(entriesIsoChecksum[0])
if err != nil {
prg.Failure()
log.Error("Failed to read options file from iso boot menu")
return err
}
bc.OptionsMediaCheck = filterOptionsLineFunc(optionsFileISO)
/* Fill boot options in isolinux.cfg */
tmpl, err := ioutil.ReadFile(templatePath + "/isolinux.cfg.template")
if err != nil {
prg.Failure()
log.Error("Failed to find template")
return err
}
t := template.New("Modules template")
t, err = t.Parse(string(tmpl))
if err != nil {
prg.Failure()
log.Error("Failed to parse template.")
return err
}
f, err := os.Create(tmpPaths[clrCdroot] + "/isolinux/isolinux.cfg")
if err != nil {
prg.Failure()
log.Error("Failed to create isolinux.cfg on cd root!")
return err
}
defer func() {
_ = f.Close()
}()
err = t.Execute(f, bc)
if err != nil {
prg.Failure()
log.Error("Failed to execute template filling")
return err
}
prg.Success()
return err
}
func implantIsoChecksum(imgName string) error {
msg := "Adding Checksums for ISO Integrity"
prg := progress.NewLoop(msg)
log.Info(msg)
args := []string{
"implantisomd5",
}
if len(imgName) > 0 {
isoName := imgName + ".iso"
args = append(args, isoName)
}
err := cmd.RunAndLog(args...)
if err != nil {
prg.Failure()
return err
}
prg.Success()
return err
}
func packageIso(imgName, appID, publisher string) error {
msg := "Building ISO"
prg := progress.NewLoop(msg)
log.Info(msg)
args := []string{
"xorriso", "-as", "mkisofs",
"-o", imgName + ".iso",
"-V", "CLR_ISO",
}
if len(appID) > 0 {
args = append(args, "-appid", appID)
}
if len(publisher) > 0 {
args = append(args, "-publisher", publisher)
}
args = append(args,
"-isohybrid-mbr", tmpPaths[clrCdroot]+"/isolinux/isohdpfx.bin",
"-c", "isolinux/boot.cat", "-b", "isolinux/isolinux.bin",
"-no-emul-boot", "-boot-load-size", "4", "-boot-info-table",
"-eltorito-alt-boot", "-e", "EFI/efiboot.img", "-no-emul-boot",
"-isohybrid-gpt-basdat", tmpPaths[clrCdroot],
)
err := cmd.RunAndLog(args...)
if err != nil {
prg.Failure()
return err
}
prg.Success()
return err
}
func cleanup() {
msg := "Cleaning up from ISO creation"
prg := progress.NewLoop(msg)
log.Info(msg)
var err error
/* In case something fails during mkEfiBoot, check and umount clrImgEfi */
if err = syscall.Unmount(tmpPaths[clrEfi], syscall.MNT_FORCE|syscall.MNT_DETACH); err != nil {
// Failed to unmount, usually the normal case, but could be umount actually failed.
}
/* Remove all directories in /tmp/clr_* */
for _, d := range tmpPaths {
if d == tmpPaths[clrRootfs] || d == tmpPaths[clrImgEfi] { //both these paths are handled by clr-installer
continue
}
err = os.RemoveAll(d)
if err != nil {
log.Warning("Failed to remove dir: %s", d)
}
}
prg.Success()
}
/*MakeIso creates an ISO image from a built image in the current directory*/
func MakeIso(rootDir string, imgName string, model *model.SystemInstall, options args.Args) error {
tmpPaths[clrRootfs] = rootDir
tmpPaths[clrImgEfi] = rootDir + "/boot"
var err error
templateDir, err := utils.LookupISOTemplateDir()
if err != nil {
return err
}
// Determine version from the root filesystem
version, err := ioutil.ReadFile(rootDir + "/usr/share/clear/version")
if err != nil {
return err
}
if err = mkTmpDirs(); err != nil {
return err
}
defer cleanup()
if err = mkRootfs(); err != nil {
return err
}
if err = mkInitrd(string(version), model, options); err != nil {
return err
}
if err = mkInitrdInitScript(templateDir); err != nil {
return err
}
if err = buildInitrdImage(); err != nil {
return err
}
if err = mkEfiBoot(); err != nil {
return err
}
err = mkLegacyBoot(templateDir)
if err != nil {
return err
}
appID := model.ISOApplicationID
if len(appID) == 0 {
appID = "server"
if model.IsTargetDesktopInstall() {
appID = "desktop"
}
}
if err = packageIso(imgName, appID, model.ISOPublisher); err != nil {
return err
}
if err = implantIsoChecksum(imgName); err != nil {
return err
}
return err
}