/
main_repack-windows.go
749 lines (586 loc) · 20.3 KB
/
main_repack-windows.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
package main
import (
"bufio"
"bytes"
"encoding/hex"
"errors"
"fmt"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"slices"
"strconv"
"strings"
lxdShared "github.com/canonical/lxd/shared"
"github.com/flosch/pongo2/v4"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"golang.org/x/sys/unix"
"github.com/canonical/lxd-imagebuilder/shared"
"github.com/canonical/lxd-imagebuilder/windows"
)
type cmdRepackWindows struct {
global *cmdGlobal
flagDrivers string
flagWindowsVersion string
flagWindowsArchitecture string
}
func init() {
// Filters should be registered in the init() function
_ = pongo2.RegisterFilter("toHex", toHex)
}
func (c *cmdRepackWindows) command() *cobra.Command {
cmd := &cobra.Command{
Use: "repack-windows <source-iso> <target-iso> [--drivers=DRIVERS]",
Short: "Repack Windows ISO with drivers included",
Args: cobra.ExactArgs(2),
PreRunE: c.preRun,
RunE: func(cmd *cobra.Command, args []string) error {
defer func() {
_ = unix.Unmount(c.global.sourceDir, 0)
}()
sourceDir := filepath.Dir(args[0])
targetDir := filepath.Dir(args[1])
// If either the source or the target are located on a FUSE filesystem, disable overlay
// as it doesn't play well with wimlib-imagex.
for _, dir := range []string{sourceDir, targetDir} {
var stat unix.Statfs_t
err := unix.Statfs(dir, &stat)
if err != nil {
c.global.logger.WithFields(logrus.Fields{"dir": dir, "err": err}).Warn("Failed to get directory information")
continue
}
// Since there's no magic number for virtiofs, we need to check FUSE_SUPER_MAGIC (which is not defined in the unix package).
if stat.Type == 0x65735546 {
c.global.logger.Warn("FUSE filesystem detected, disabling overlay")
c.global.flagDisableOverlay = true
break
}
}
overlayDir, cleanup, err := c.global.getOverlayDir()
if err != nil {
return fmt.Errorf("Failed to get overlay directory: %w", err)
}
if cleanup != nil {
c.global.overlayCleanup = cleanup
defer func() {
cleanup()
c.global.overlayCleanup = nil
}()
}
return c.run(cmd, args, overlayDir)
},
}
cmd.Flags().StringVar(&c.flagDrivers, "drivers", "", "Path to drivers ISO"+"``")
cmd.Flags().StringVar(&c.flagWindowsVersion, "windows-version", "", "Windows version to repack"+"``")
cmd.Flags().StringVar(&c.flagWindowsArchitecture, "windows-arch", "", "Windows architecture to repack"+"``")
return cmd
}
// Create rw rootfs in preRun. Point global.sourceDir to the rw rootfs.
func (c *cmdRepackWindows) preRun(cmd *cobra.Command, args []string) error {
logger := c.global.logger
if c.flagWindowsVersion == "" {
detectedVersion := detectWindowsVersion(filepath.Base(args[0]))
if detectedVersion == "" {
return errors.New("Failed to detect Windows version. Please provide the version using the --windows-version flag")
}
c.flagWindowsVersion = detectedVersion
} else {
supportedVersions := []string{"w11", "w10", "2k19", "2k12", "2k16", "2k22"}
if !slices.Contains(supportedVersions, c.flagWindowsVersion) {
return fmt.Errorf("Version must be one of %v", supportedVersions)
}
}
if c.flagWindowsArchitecture == "" {
detectedArchitecture := detectWindowsArchitecture(filepath.Base(args[0]))
if detectedArchitecture == "" {
return errors.New("Failed to detect Windows architecture. Please provide the architecture using the --windows-arch flag")
}
c.flagWindowsArchitecture = detectedArchitecture
} else {
supportedArchitectures := []string{"amd64", "ARM64"}
if !slices.Contains(supportedArchitectures, c.flagWindowsArchitecture) {
return fmt.Errorf("Architecture must be one of %v", supportedArchitectures)
}
}
// Check dependencies
err := c.checkDependencies()
if err != nil {
return fmt.Errorf("Failed to check dependencies: %w", err)
}
// if an error is returned, disable the usage message
cmd.SilenceUsage = true
// Clean up cache directory before doing anything
err = os.RemoveAll(c.global.flagCacheDir)
if err != nil {
return fmt.Errorf("Failed to remove directory %q: %w", c.global.flagCacheDir, err)
}
success := false
err = os.Mkdir(c.global.flagCacheDir, 0755)
if err != nil {
return fmt.Errorf("Failed to create directory %q: %w", c.global.flagCacheDir, err)
}
defer func() {
if c.global.flagCleanup && !success {
os.RemoveAll(c.global.flagCacheDir)
}
}()
c.global.sourceDir = filepath.Join(c.global.flagCacheDir, "source")
// Create source path
err = os.MkdirAll(c.global.sourceDir, 0755)
if err != nil {
return fmt.Errorf("Failed to create directory %q: %w", c.global.sourceDir, err)
}
logger.Info("Mounting Windows ISO")
// Mount ISO
err = shared.RunCommand(c.global.ctx, nil, nil, "mount", "-t", "udf", "-o", "loop", args[0], c.global.sourceDir)
if err != nil {
return fmt.Errorf("Failed to mount %q at %q: %w", args[0], c.global.sourceDir, err)
}
success = true
return nil
}
func (c *cmdRepackWindows) run(cmd *cobra.Command, args []string, overlayDir string) error {
logger := c.global.logger
driverPath := filepath.Join(c.global.flagCacheDir, "drivers")
virtioISOPath := c.flagDrivers
if virtioISOPath == "" {
// Download vioscsi driver
virtioURL := "https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/latest-virtio/virtio-win.iso"
virtioISOPath = filepath.Join(c.global.flagSourcesDir, "windows", "virtio-win.iso")
if !lxdShared.PathExists(virtioISOPath) {
err := os.MkdirAll(filepath.Dir(virtioISOPath), 0755)
if err != nil {
return fmt.Errorf("Failed to create directory %q: %w", filepath.Dir(virtioISOPath), err)
}
f, err := os.Create(virtioISOPath)
if err != nil {
return fmt.Errorf("Failed to create file %q: %w", virtioISOPath, err)
}
defer f.Close()
var client http.Client
logger.Info("Downloading drivers ISO")
_, err = lxdShared.DownloadFileHash(c.global.ctx, &client, "", nil, nil, "virtio-win.iso", virtioURL, "", nil, f)
if err != nil {
f.Close()
os.Remove(virtioISOPath)
return fmt.Errorf("Failed to download %q: %w", virtioURL, err)
}
f.Close()
}
}
if !lxdShared.PathExists(driverPath) {
err := os.MkdirAll(driverPath, 0755)
if err != nil {
return fmt.Errorf("Failed to create directory %q: %w", driverPath, err)
}
}
logger.Info("Mounting driver ISO")
// Mount driver ISO
err := shared.RunCommand(c.global.ctx, nil, nil, "mount", "-t", "iso9660", "-o", "loop", virtioISOPath, driverPath)
if err != nil {
return fmt.Errorf("Failed to mount %q at %q: %w", virtioISOPath, driverPath, err)
}
defer func() {
_ = unix.Unmount(driverPath, 0)
}()
var sourcesDir string
entries, err := os.ReadDir(overlayDir)
if err != nil {
return fmt.Errorf("Failed to read directory %q: %w", overlayDir, err)
}
for _, entry := range entries {
if strings.ToLower(entry.Name()) == "sources" {
sourcesDir = filepath.Join(overlayDir, entry.Name())
break
}
}
entries, err = os.ReadDir(sourcesDir)
if err != nil {
return fmt.Errorf("Failed to read directory %q: %w", sourcesDir, err)
}
var bootWim string
var installWim string
// Find boot.wim and install.wim but consider their case.
for _, entry := range entries {
if bootWim != "" && installWim != "" {
break
}
if strings.ToLower(entry.Name()) == "boot.wim" {
bootWim = filepath.Join(sourcesDir, entry.Name())
continue
}
if strings.ToLower(entry.Name()) == "install.wim" {
installWim = filepath.Join(sourcesDir, entry.Name())
continue
}
}
if bootWim == "" {
return errors.New("Unable to find boot.wim")
}
if installWim == "" {
return errors.New("Unable to find install.wim")
}
var buf bytes.Buffer
err = shared.RunCommand(c.global.ctx, nil, &buf, "wimlib-imagex", "info", installWim)
if err != nil {
return fmt.Errorf("Failed to retrieve wim file information: %w", err)
}
indexes := []int{}
scanner := bufio.NewScanner(&buf)
for scanner.Scan() {
text := scanner.Text()
if strings.HasPrefix(text, "Index") {
fields := strings.Split(text, " ")
index, err := strconv.Atoi(fields[len(fields)-1])
if err != nil {
return fmt.Errorf("Failed to determine wim file indexes: %w", err)
}
indexes = append(indexes, index)
}
}
// This injects the drivers into the installation process
err = c.modifyWim(bootWim, 2)
if err != nil {
return fmt.Errorf("Failed to modify index 2 of %q: %w", filepath.Base(bootWim), err)
}
// This injects the drivers into the final OS
for _, idx := range indexes {
err = c.modifyWim(installWim, idx)
if err != nil {
return fmt.Errorf("Failed to modify index %d of %q: %w", idx, filepath.Base(installWim), err)
}
}
logger.Info("Generating new ISO")
var stdout strings.Builder
err = shared.RunCommand(c.global.ctx, nil, &stdout, "genisoimage", "--version")
if err != nil {
return fmt.Errorf("Failed to determine version of genisoimage: %w", err)
}
version := strings.Split(stdout.String(), "\n")[0]
if strings.HasPrefix(version, "mkisofs") {
err = shared.RunCommand(c.global.ctx, nil, nil, "genisoimage", "-iso-level", "3", "-l", "-no-emul-boot", "-b", "efi/microsoft/boot/efisys.bin", "-o", args[1], overlayDir)
} else {
err = shared.RunCommand(c.global.ctx, nil, nil, "genisoimage", "--allow-limited-size", "-l", "-no-emul-boot", "-b", "efi/microsoft/boot/efisys.bin", "-o", args[1], overlayDir)
}
if err != nil {
return fmt.Errorf("Failed to generate ISO: %w", err)
}
return nil
}
func (c *cmdRepackWindows) modifyWim(path string, index int) error {
logger := c.global.logger
// Mount VIM file
wimFile := filepath.Join(path)
wimPath := filepath.Join(c.global.flagCacheDir, "wim")
if !lxdShared.PathExists(wimPath) {
err := os.MkdirAll(wimPath, 0755)
if err != nil {
return fmt.Errorf("Failed to create directory %q: %w", wimPath, err)
}
}
success := false
err := shared.RunCommand(c.global.ctx, nil, nil, "wimlib-imagex", "mountrw", wimFile, strconv.Itoa(index), wimPath, "--allow-other")
if err != nil {
return fmt.Errorf("Failed to mount %q: %w", filepath.Base(wimFile), err)
}
defer func() {
if !success {
_ = shared.RunCommand(c.global.ctx, nil, nil, "wimlib-imagex", "unmount", wimPath)
}
}()
dirs, err := c.getWindowsDirectories(wimPath)
if err != nil {
return fmt.Errorf("Failed to get required windows directories: %w", err)
}
if dirs["filerepository"] == "" {
return errors.New("Failed to determine windows/system32/driverstore/filerepository path")
}
if dirs["inf"] == "" {
return errors.New("Failed to determine windows/inf path")
}
if dirs["config"] == "" {
return errors.New("Failed to determine windows/system32/config path")
}
if dirs["drivers"] == "" {
return errors.New("Failed to determine windows/system32/drivers path")
}
logger.WithFields(logrus.Fields{"file": filepath.Base(path), "index": index}).Info("Modifying WIM file")
// Create registry entries and copy files
err = c.injectDrivers(dirs)
if err != nil {
return fmt.Errorf("Failed to inject drivers: %w", err)
}
err = shared.RunCommand(c.global.ctx, nil, nil, "wimlib-imagex", "unmount", wimPath, "--commit")
if err != nil {
return fmt.Errorf("Failed to unmount WIM image: %w", err)
}
success = true
return nil
}
func (c *cmdRepackWindows) checkDependencies() error {
dependencies := []string{"genisoimage", "hivexregedit", "rsync", "wimlib-imagex"}
for _, dep := range dependencies {
_, err := exec.LookPath(dep)
if err != nil {
return fmt.Errorf("Required tool %q is missing", dep)
}
}
return nil
}
func (c *cmdRepackWindows) getWindowsDirectories(wimPath string) (map[string]string, error) {
windowsPath := ""
system32Path := ""
driverStorePath := ""
dirs := make(map[string]string)
entries, err := os.ReadDir(wimPath)
if err != nil {
return nil, err
}
// Get windows directory
for _, entry := range entries {
if !entry.IsDir() {
continue
}
if regexp.MustCompile(`^(?i)windows$`).MatchString(entry.Name()) {
windowsPath = filepath.Join(wimPath, entry.Name())
break
}
}
entries, err = os.ReadDir(windowsPath)
if err != nil {
return nil, err
}
for _, entry := range entries {
if dirs["inf"] != "" && system32Path != "" {
break
}
if !entry.IsDir() {
continue
}
if regexp.MustCompile(`^(?i)inf$`).MatchString(entry.Name()) {
dirs["inf"] = filepath.Join(windowsPath, entry.Name())
continue
}
if regexp.MustCompile(`^(?i)system32$`).MatchString(entry.Name()) {
system32Path = filepath.Join(windowsPath, entry.Name())
}
}
entries, err = os.ReadDir(system32Path)
if err != nil {
return nil, err
}
for _, entry := range entries {
if dirs["config"] != "" && dirs["drivers"] != "" && driverStorePath != "" {
break
}
if !entry.IsDir() {
continue
}
if regexp.MustCompile(`^(?i)config$`).MatchString(entry.Name()) {
dirs["config"] = filepath.Join(system32Path, entry.Name())
continue
}
if regexp.MustCompile(`^(?i)drivers$`).MatchString(entry.Name()) {
dirs["drivers"] = filepath.Join(system32Path, entry.Name())
continue
}
if regexp.MustCompile(`^(?i)driverstore$`).MatchString(entry.Name()) {
driverStorePath = filepath.Join(system32Path, entry.Name())
}
}
entries, err = os.ReadDir(driverStorePath)
if err != nil {
return nil, err
}
for _, entry := range entries {
if !entry.IsDir() {
continue
}
if regexp.MustCompile(`^(?i)filerepository$`).MatchString(entry.Name()) {
dirs["filerepository"] = filepath.Join(driverStorePath, entry.Name())
break
}
}
return dirs, nil
}
func (c *cmdRepackWindows) injectDrivers(dirs map[string]string) error {
logger := c.global.logger
driverPath := filepath.Join(c.global.flagCacheDir, "drivers")
i := 0
driversRegistry := "Windows Registry Editor Version 5.00"
systemRegistry := "Windows Registry Editor Version 5.00"
softwareRegistry := "Windows Registry Editor Version 5.00"
for driver, info := range windows.Drivers {
logger.WithField("driver", driver).Debug("Injecting driver")
ctx := pongo2.Context{
"infFile": fmt.Sprintf("oem%d.inf", i),
"packageName": info.PackageName,
"driverName": driver,
}
sourceDir := filepath.Join(driverPath, driver, c.flagWindowsVersion, c.flagWindowsArchitecture)
targetBasePath := filepath.Join(dirs["filerepository"], info.PackageName)
if !lxdShared.PathExists(targetBasePath) {
err := os.MkdirAll(targetBasePath, 0755)
if err != nil {
return fmt.Errorf("Failed to create directory %q: %w", targetBasePath, err)
}
}
err := filepath.Walk(sourceDir, func(path string, info os.FileInfo, err error) error {
ext := filepath.Ext(path)
targetPath := filepath.Join(targetBasePath, filepath.Base(path))
// Copy driver files
if slices.Contains([]string{".cat", ".dll", ".inf", ".sys"}, ext) {
logger.WithFields(logrus.Fields{"src": path, "dest": targetPath}).Debug("Copying file")
err := shared.Copy(path, targetPath)
if err != nil {
return fmt.Errorf("Failed to copy %q to %q: %w", filepath.Base(path), targetPath, err)
}
}
// Copy .inf file
if ext == ".inf" {
target := filepath.Join(dirs["inf"], ctx["infFile"].(string))
logger.WithFields(logrus.Fields{"src": path, "dest": target}).Debug("Copying file")
err := shared.Copy(path, target)
if err != nil {
return fmt.Errorf("Failed to copy %q to %q: %w", filepath.Base(path), target, err)
}
// Retrieve the ClassGuid which is needed for the Windows registry entries.
file, err := os.Open(path)
if err != nil {
return fmt.Errorf("Failed to open %s: %w", path, err)
}
re := regexp.MustCompile(`(?i)^ClassGuid[ ]*=[ ]*(.+)$`)
scanner := bufio.NewScanner(file)
for scanner.Scan() {
matches := re.FindStringSubmatch(scanner.Text())
if len(matches) > 0 {
ctx["classGuid"] = strings.TrimSpace(matches[1])
}
}
file.Close()
_, ok := ctx["classGuid"]
if !ok {
return fmt.Errorf("Failed to determine classGUID for driver %q", driver)
}
}
// Copy .sys and .dll files
if ext == ".dll" || ext == ".sys" {
target := filepath.Join(dirs["drivers"], filepath.Base(path))
logger.WithFields(logrus.Fields{"src": path, "dest": target}).Debug("Copying file")
err := shared.Copy(path, target)
if err != nil {
return fmt.Errorf("Failed to copy %q to %q: %w", filepath.Base(path), target, err)
}
}
return nil
})
if err != nil {
return fmt.Errorf("Failed to copy driver files: %w", err)
}
// Update Windows DRIVERS registry
if info.DriversRegistry != "" {
tpl, err := pongo2.FromString(info.DriversRegistry)
if err != nil {
return fmt.Errorf("Failed to parse template for driver %q: %w", driver, err)
}
out, err := tpl.Execute(ctx)
if err != nil {
return fmt.Errorf("Failed to render template for driver %q: %w", driver, err)
}
driversRegistry = fmt.Sprintf("%s\n\n%s", driversRegistry, out)
}
// Update Windows SYSTEM registry
if info.SystemRegistry != "" {
tpl, err := pongo2.FromString(info.SystemRegistry)
if err != nil {
return fmt.Errorf("Failed to parse template for driver %q: %w", driver, err)
}
out, err := tpl.Execute(ctx)
if err != nil {
return fmt.Errorf("Failed to render template for driver %q: %w", driver, err)
}
systemRegistry = fmt.Sprintf("%s\n\n%s", systemRegistry, out)
}
// Update Windows SOFTWARE registry
if info.SoftwareRegistry != "" {
tpl, err := pongo2.FromString(info.SoftwareRegistry)
if err != nil {
return fmt.Errorf("Failed to parse template for driver %q: %w", driver, err)
}
out, err := tpl.Execute(ctx)
if err != nil {
return fmt.Errorf("Failed to render template for driver %q: %w", driver, err)
}
softwareRegistry = fmt.Sprintf("%s\n\n%s", softwareRegistry, out)
}
i++
}
logger.WithField("hivefile", "DRIVERS").Debug("Updating Windows registry")
err := shared.RunCommand(c.global.ctx, strings.NewReader(driversRegistry), nil, "hivexregedit", "--merge", "--prefix='HKEY_LOCAL_MACHINE\\DRIVERS'", filepath.Join(dirs["config"], "DRIVERS"))
if err != nil {
return fmt.Errorf("Failed to edit Windows DRIVERS registry: %w", err)
}
logger.WithField("hivefile", "SYSTEM").Debug("Updating Windows registry")
err = shared.RunCommand(c.global.ctx, strings.NewReader(systemRegistry), nil, "hivexregedit", "--merge", "--prefix='HKEY_LOCAL_MACHINE\\SYSTEM'", filepath.Join(dirs["config"], "SYSTEM"))
if err != nil {
return fmt.Errorf("Failed to edit Windows SYSTEM registry: %w", err)
}
logger.WithField("hivefile", "SOFTWARE").Debug("Updating Windows registry")
err = shared.RunCommand(c.global.ctx, strings.NewReader(softwareRegistry), nil, "hivexregedit", "--merge", "--prefix='HKEY_LOCAL_MACHINE\\SOFTWARE'", filepath.Join(dirs["config"], "SOFTWARE"))
if err != nil {
return fmt.Errorf("Failed to edit Windows SOFTWARE registry: %w", err)
}
return nil
}
func detectWindowsVersion(fileName string) string {
aliases := map[string][]string{
"w11": {"w11", "win11", "windows.?11"},
"w10": {"w10", "win10", "windows.?10"},
"2k19": {"2k19", "w2k19", "win2k19", "windows.?server.?2019"},
"2k12": {"2k12", "w2k12", "win2k12", "windows.?server.?2012"},
"2k16": {"2k16", "w2k16", "win2k16", "windows.?server.?2016"},
"2k22": {"2k22", "w2k22", "win2k22", "windows.?server.?2022"},
}
for k, v := range aliases {
for _, alias := range v {
if regexp.MustCompile(fmt.Sprintf("(?i)%s", alias)).MatchString(fileName) {
return k
}
}
}
return ""
}
func detectWindowsArchitecture(fileName string) string {
aliases := map[string][]string{
"amd64": {"amd64", "x64"},
"ARM64": {"arm64"},
}
for k, v := range aliases {
for _, alias := range v {
if regexp.MustCompile(fmt.Sprintf("(?i)%s", alias)).MatchString(fileName) {
return k
}
}
}
return ""
}
// toHex is a pongo2 filter which converts the provided value to a hex value understood by the Windows registry.
func toHex(in *pongo2.Value, param *pongo2.Value) (out *pongo2.Value, err *pongo2.Error) {
dst := make([]byte, hex.EncodedLen(len(in.String())))
hex.Encode(dst, []byte(in.String()))
var builder strings.Builder
for i := 0; i < len(dst); i += 2 {
_, err := builder.Write(dst[i : i+2])
if err != nil {
return &pongo2.Value{}, &pongo2.Error{Sender: "filter:toHex", OrigError: err}
}
_, err = builder.WriteString(",00,")
if err != nil {
return &pongo2.Value{}, &pongo2.Error{Sender: "filter:toHex", OrigError: err}
}
}
return pongo2.AsValue(strings.TrimSuffix(builder.String(), ",")), nil
}