-
Notifications
You must be signed in to change notification settings - Fork 7
Fix VHD parsing - Take 2. #364
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
// Copyright (c) Microsoft Corporation. | ||
// Licensed under the MIT License. | ||
|
||
package vhdutils | ||
|
||
import ( | ||
"flag" | ||
"os" | ||
"path/filepath" | ||
"testing" | ||
|
||
"github.com/microsoft/azurelinux/toolkit/tools/internal/logger" | ||
) | ||
|
||
var ( | ||
testsTempDir string | ||
) | ||
|
||
func TestMain(m *testing.M) { | ||
var err error | ||
|
||
logger.InitStderrLog() | ||
|
||
flag.Parse() | ||
|
||
workingDir, err := os.Getwd() | ||
if err != nil { | ||
logger.Log.Panicf("Failed to get working directory, error: %s", err) | ||
} | ||
|
||
testsTempDir = filepath.Join(workingDir, "_tmp") | ||
|
||
err = os.MkdirAll(testsTempDir, os.ModePerm) | ||
if err != nil { | ||
logger.Log.Panicf("Failed to create test temp directory, error: %s", err) | ||
} | ||
|
||
retVal := m.Run() | ||
|
||
err = os.RemoveAll(testsTempDir) | ||
if err != nil { | ||
logger.Log.Warnf("Failed to cleanup test temp dir (%s). Error: %s", testsTempDir, err) | ||
} | ||
|
||
os.Exit(retVal) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,137 @@ | ||
// Copyright (c) Microsoft Corporation. | ||
// Licensed under the MIT License. | ||
|
||
package vhdutils | ||
|
||
import ( | ||
"bytes" | ||
"encoding/binary" | ||
"errors" | ||
"io" | ||
"os" | ||
) | ||
|
||
const ( | ||
VhdFileFooterSize = 512 | ||
VhdFileSignature = "conectix" | ||
VhdFileVersion = 0x00010000 | ||
) | ||
|
||
type VhdFileFooter struct { | ||
Cookie [8]byte | ||
Features uint32 | ||
FileFormatVersion uint32 | ||
DataOffset uint64 | ||
TimeStamp uint32 | ||
CreatorApplication [4]byte | ||
CreatorVersion [4]byte | ||
CreatorHostOS [4]byte | ||
OriginalSize uint64 | ||
CurrentSize uint64 | ||
Cylinder uint16 | ||
Heads uint8 | ||
SectorsPerCylinder uint8 | ||
DiskType uint32 | ||
Checksum [4]byte | ||
UniqueId [16]byte | ||
SavedState uint8 | ||
Reserved [427]byte | ||
} | ||
|
||
var ( | ||
ErrVhdFileTooSmall = errors.New("file is too small to be a VHD") | ||
ErrVhdWrongFileSignature = errors.New("footer does not have correct VHD file signature") | ||
ErrVhdWrongFileVersion = errors.New("VHD footer has unsupported file format version") | ||
) | ||
|
||
type VhdFileSizeCalcType int | ||
|
||
const ( | ||
// File is not a VHD file. | ||
VhdFileSizeCalcTypeNone VhdFileSizeCalcType = iota | ||
// VHD uses "Current Size" field to calculate the disk size. | ||
VhdFileSizeCalcTypeCurrentSize | ||
// VHD uses "Disk Geometry" fields to calculate the disk size. | ||
VhdFileSizeCalcTypeDiskGeometry | ||
) | ||
|
||
func GetVhdFileSizeCalcType(filename string) (VhdFileSizeCalcType, error) { | ||
footer, err := ParseVhdFileFooter(filename) | ||
if errors.Is(err, ErrVhdFileTooSmall) || errors.Is(err, ErrVhdWrongFileSignature) { | ||
// Not a VHD file. | ||
return VhdFileSizeCalcTypeNone, nil | ||
} | ||
if err != nil { | ||
return VhdFileSizeCalcTypeNone, err | ||
} | ||
|
||
creatorApplication := string(footer.CreatorApplication[:]) | ||
|
||
// There are actually two different ways of calculating the disk size of a VHD file. The old method, which is | ||
// used by Microsoft Virtual PC, uses the VHD's footer's 'Disk Geometry' (cylinder, heads, and sectors per | ||
// track/cylinder) fields. Using 'Disk Geometry' limits what file sizes are possible. So, Hyper-V uses only uses the | ||
// the 'Current Size' field, which allows it to accept disks of any size. | ||
// Microsoft Virtual PC is pretty dead at this point. So, it is fairly safe to assume that almost all VHD files | ||
// use the Hyper-V format. Unfortunately, qemu-img still defaults to using 'Disk Geometry' when a user requests a | ||
// VHD (i.e. 'vpc') image. Image Customizer knows to pass the 'force_size=on' arg to qemu-img so that it uses | ||
// 'Current Size'. But users might not know that they need to do this when using qemu-img manually. | ||
// Fortunately, qemu-img is nice enough to use different values of the 'Creator Application' field depending on | ||
// the value of 'force_size'. Specifically, "qemu" for 'Disk Geometry' and "qem2 " for 'Current Size'. This can be | ||
// used to determine which type of VHD we are dealing with. | ||
// qemu-img uses the 'Creator Application' field internally to determine what type of VHD it is dealing with. | ||
// However, if it sees a 'Creator Application' value it doesn't recognize, it will assume it uses 'Disk Geometry'. | ||
// Whereas, nowadays it is more likely for a VHD to use 'Current Size'. | ||
switch creatorApplication { | ||
case "vpc ", "vs ", "qemu": | ||
return VhdFileSizeCalcTypeDiskGeometry, nil | ||
|
||
default: | ||
return VhdFileSizeCalcTypeCurrentSize, nil | ||
} | ||
} | ||
|
||
func ParseVhdFileFooter(filename string) (VhdFileFooter, error) { | ||
fd, err := os.Open(filename) | ||
if err != nil { | ||
return VhdFileFooter{}, err | ||
} | ||
defer fd.Close() | ||
|
||
stat, err := fd.Stat() | ||
if err != nil { | ||
return VhdFileFooter{}, err | ||
} | ||
|
||
if stat.Size() < VhdFileFooterSize { | ||
return VhdFileFooter{}, ErrVhdFileTooSmall | ||
} | ||
|
||
_, err = fd.Seek(-VhdFileFooterSize, io.SeekEnd) | ||
if err != nil { | ||
return VhdFileFooter{}, err | ||
} | ||
|
||
footerBytes := [VhdFileFooterSize]byte{} | ||
_, err = fd.Read([]byte(footerBytes[:])) | ||
if err != nil { | ||
return VhdFileFooter{}, err | ||
} | ||
|
||
footerReader := bytes.NewReader(footerBytes[:]) | ||
|
||
var footer VhdFileFooter | ||
err = binary.Read(footerReader, binary.BigEndian, &footer) | ||
if err != nil { | ||
return VhdFileFooter{}, err | ||
} | ||
|
||
if string(footer.Cookie[:]) != VhdFileSignature { | ||
return VhdFileFooter{}, ErrVhdWrongFileSignature | ||
} | ||
|
||
if footer.FileFormatVersion != VhdFileVersion { | ||
return VhdFileFooter{}, ErrVhdWrongFileVersion | ||
} | ||
|
||
return footer, nil | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
// Copyright (c) Microsoft Corporation. | ||
// Licensed under the MIT License. | ||
|
||
package vhdutils | ||
|
||
import ( | ||
"os" | ||
"path/filepath" | ||
"testing" | ||
|
||
"github.com/microsoft/azurelinux/toolkit/tools/internal/file" | ||
"github.com/microsoft/azurelinux/toolkit/tools/internal/shell" | ||
"github.com/stretchr/testify/assert" | ||
) | ||
|
||
func TestGetVhdFileSizeCalcTypeDiskGeometryDynamic(t *testing.T) { | ||
testGetVhdFileSizeCalcTypeHelper(t, "TestGetVhdFileSizeCalcTypeDiskGeometryDynamic", VhdFileSizeCalcTypeDiskGeometry, | ||
[]string{"-f", "vpc", "-o", "force_size=off,subformat=dynamic"}) | ||
} | ||
|
||
func TestGetVhdFileSizeCalcTypeDiskGeometryFixed(t *testing.T) { | ||
testGetVhdFileSizeCalcTypeHelper(t, "TestGetVhdFileSizeCalcTypeDiskGeometryFixed", VhdFileSizeCalcTypeDiskGeometry, | ||
[]string{"-f", "vpc", "-o", "force_size=off,subformat=fixed"}) | ||
} | ||
|
||
func TestGetVhdFileSizeCalcTypeCurrentSizeDynamic(t *testing.T) { | ||
testGetVhdFileSizeCalcTypeHelper(t, "TestGetVhdFileSizeCalcTypeCurrentSizeDynamic", VhdFileSizeCalcTypeCurrentSize, | ||
[]string{"-f", "vpc", "-o", "force_size=on,subformat=dynamic"}) | ||
} | ||
|
||
func TestGetVhdFileSizeCalcTypeCurrentSizeFixed(t *testing.T) { | ||
testGetVhdFileSizeCalcTypeHelper(t, "TestGetVhdFileSizeCalcTypeCurrentSizeFixed", VhdFileSizeCalcTypeCurrentSize, | ||
[]string{"-f", "vpc", "-o", "force_size=on,subformat=fixed"}) | ||
} | ||
|
||
func TestGetVhdFileSizeCalcTypeNoneVhdx(t *testing.T) { | ||
testGetVhdFileSizeCalcTypeHelper(t, "TestGetVhdFileSizeCalcTypeNoneVhdx", VhdFileSizeCalcTypeNone, | ||
[]string{"-f", "vhdx"}) | ||
} | ||
|
||
func TestGetVhdFileSizeCalcTypeNoneQcow2(t *testing.T) { | ||
testGetVhdFileSizeCalcTypeHelper(t, "TestGetVhdFileSizeCalcTypeNoneQcow2", VhdFileSizeCalcTypeNone, | ||
[]string{"-f", "qcow2"}) | ||
} | ||
|
||
func TestGetVhdFileSizeCalcTypeNoneRaw(t *testing.T) { | ||
testGetVhdFileSizeCalcTypeHelper(t, "TestGetVhdFileSizeCalcTypeNoneRaw", VhdFileSizeCalcTypeNone, | ||
[]string{"-f", "raw"}) | ||
} | ||
|
||
func testGetVhdFileSizeCalcTypeHelper(t *testing.T, testName string, expectedVhdFileSizeCalcType VhdFileSizeCalcType, qemuImgArgs []string) { | ||
qemuimgExists, err := file.CommandExists("qemu-img") | ||
assert.NoError(t, err) | ||
if !qemuimgExists { | ||
t.Skip("The 'qemu-img' command is not available") | ||
} | ||
|
||
testTempDir := filepath.Join(testsTempDir, testName) | ||
testVhdFile := filepath.Join(testTempDir, "test.vhd") | ||
|
||
err = os.MkdirAll(testTempDir, os.ModePerm) | ||
assert.NoError(t, err) | ||
|
||
args := []string{"create", testVhdFile, "1M"} | ||
args = append(args, qemuImgArgs...) | ||
|
||
err = shell.ExecuteLive(true, "qemu-img", args...) | ||
assert.NoError(t, err) | ||
|
||
vhdType, err := GetVhdFileSizeCalcType(testVhdFile) | ||
assert.NoError(t, err) | ||
assert.Equal(t, expectedVhdFileSizeCalcType, vhdType) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.