Mateusz Zalega | c71efc9 | 2021-09-07 16:46:25 +0200 | [diff] [blame] | 1 | // Copyright 2020 The Monogon Project Authors. |
| 2 | // |
| 3 | // SPDX-License-Identifier: Apache-2.0 |
| 4 | // |
| 5 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | // you may not use this file except in compliance with the License. |
| 7 | // You may obtain a copy of the License at |
| 8 | // |
| 9 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | // |
| 11 | // Unless required by applicable law or agreed to in writing, software |
| 12 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | // See the License for the specific language governing permissions and |
| 15 | // limitations under the License. |
| 16 | |
| 17 | // This package provides self-contained implementation used to generate |
| 18 | // Metropolis disk images. |
| 19 | package osimage |
| 20 | |
| 21 | import ( |
| 22 | "fmt" |
| 23 | "io" |
Mateusz Zalega | c71efc9 | 2021-09-07 16:46:25 +0200 | [diff] [blame] | 24 | "os" |
| 25 | |
| 26 | diskfs "github.com/diskfs/go-diskfs" |
| 27 | "github.com/diskfs/go-diskfs/disk" |
| 28 | "github.com/diskfs/go-diskfs/filesystem" |
| 29 | "github.com/diskfs/go-diskfs/partition/gpt" |
Mateusz Zalega | 612a033 | 2021-11-17 20:04:52 +0100 | [diff] [blame] | 30 | "github.com/google/uuid" |
Mateusz Zalega | c71efc9 | 2021-09-07 16:46:25 +0200 | [diff] [blame] | 31 | |
| 32 | "source.monogon.dev/metropolis/pkg/efivarfs" |
| 33 | ) |
| 34 | |
| 35 | const ( |
| 36 | systemPartitionType = gpt.Type("ee96055b-f6d0-4267-8bbb-724b2afea74c") |
| 37 | SystemVolumeLabel = "METROPOLIS-SYSTEM" |
| 38 | |
| 39 | dataPartitionType = gpt.Type("9eeec464-6885-414a-b278-4305c51f7966") |
| 40 | DataVolumeLabel = "METROPOLIS-NODE-DATA" |
| 41 | |
| 42 | ESPVolumeLabel = "ESP" |
| 43 | |
| 44 | EFIPayloadPath = "/EFI/BOOT/BOOTx64.EFI" |
Lorenz Brun | 6c35e97 | 2021-12-14 03:08:23 +0100 | [diff] [blame] | 45 | nodeParamsPath = "/metropolis/parameters.pb" |
Mateusz Zalega | c71efc9 | 2021-09-07 16:46:25 +0200 | [diff] [blame] | 46 | |
| 47 | mib = 1024 * 1024 |
| 48 | ) |
| 49 | |
| 50 | // put creates a file on the target filesystem fs and fills it with |
| 51 | // contents read from an io.Reader object src. |
| 52 | func put(fs filesystem.FileSystem, dst string, src io.Reader) error { |
| 53 | target, err := fs.OpenFile(dst, os.O_CREATE|os.O_RDWR) |
| 54 | if err != nil { |
| 55 | return fmt.Errorf("while opening %q: %w", dst, err) |
| 56 | } |
| 57 | |
| 58 | // If this is streamed (e.g. using io.Copy) it exposes a bug in diskfs, so |
| 59 | // do it in one go. |
| 60 | // TODO(mateusz@monogon.tech): Investigate the bug. |
Lorenz Brun | 764a2de | 2021-11-22 16:26:36 +0100 | [diff] [blame] | 61 | data, err := io.ReadAll(src) |
Mateusz Zalega | c71efc9 | 2021-09-07 16:46:25 +0200 | [diff] [blame] | 62 | if err != nil { |
| 63 | return fmt.Errorf("while reading %q: %w", src, err) |
| 64 | } |
| 65 | if _, err := target.Write(data); err != nil { |
| 66 | return fmt.Errorf("while writing to %q: %w", dst, err) |
| 67 | } |
| 68 | return nil |
| 69 | } |
| 70 | |
| 71 | // initializeESP creates an ESP filesystem in a partition specified by |
| 72 | // index. It then creates the EFI executable and copies into it contents |
| 73 | // of the reader object exec, which must not be nil. The node parameters |
| 74 | // file is optionally created if params is not nil. initializeESP may return |
| 75 | // an error. |
| 76 | func initializeESP(image *disk.Disk, index int, exec, params io.Reader) error { |
| 77 | // Create a FAT ESP filesystem inside a partition pointed to by |
| 78 | // index. |
| 79 | spec := disk.FilesystemSpec{ |
| 80 | Partition: index, |
| 81 | FSType: filesystem.TypeFat32, |
| 82 | VolumeLabel: ESPVolumeLabel, |
| 83 | } |
| 84 | fs, err := image.CreateFilesystem(spec) |
| 85 | if err != nil { |
| 86 | return fmt.Errorf("while creating an ESP filesystem: %w", err) |
| 87 | } |
| 88 | |
| 89 | // Create the EFI partition structure. |
Lorenz Brun | 6c35e97 | 2021-12-14 03:08:23 +0100 | [diff] [blame] | 90 | for _, dir := range []string{"/EFI", "/EFI/BOOT", "/metropolis"} { |
Mateusz Zalega | c71efc9 | 2021-09-07 16:46:25 +0200 | [diff] [blame] | 91 | if err := fs.Mkdir(dir); err != nil { |
| 92 | return fmt.Errorf("while creating %q: %w", dir, err) |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | // Copy the EFI payload to the newly created filesystem. |
| 97 | if exec == nil { |
| 98 | return fmt.Errorf("exec must not be nil") |
| 99 | } |
| 100 | if err := put(fs, EFIPayloadPath, exec); err != nil { |
| 101 | return fmt.Errorf("while writing an EFI payload: %w", err) |
| 102 | } |
| 103 | |
| 104 | if params != nil { |
| 105 | // Copy Node Parameters into the ESP. |
| 106 | if err := put(fs, nodeParamsPath, params); err != nil { |
| 107 | return fmt.Errorf("while writing node parameters: %w", err) |
| 108 | } |
| 109 | } |
| 110 | return nil |
| 111 | } |
| 112 | |
| 113 | // zeroSrc is a source of null bytes implementing io.Reader. It acts as a |
| 114 | // helper data type. |
| 115 | type zeroSrc struct{} |
| 116 | |
| 117 | // Read implements io.Reader for zeroSrc. It fills b with zero bytes. The |
| 118 | // returned error is always nil. |
| 119 | func (_ zeroSrc) Read(b []byte) (n int, err error) { |
| 120 | for i := range b { |
| 121 | b[i] = 0 |
| 122 | } |
| 123 | return len(b), nil |
| 124 | } |
| 125 | |
| 126 | // initializeSystemPartition copies system partition contents into a partition |
| 127 | // at index. The remaining partition space is zero-padded. This function may |
| 128 | // return an error. |
| 129 | func initializeSystemPartition(image *disk.Disk, index int, contents io.Reader) error { |
| 130 | // Check the parameters. |
| 131 | if contents == nil { |
| 132 | return fmt.Errorf("system partition contents parameter must not be nil") |
| 133 | } |
| 134 | if index <= 0 { |
| 135 | return fmt.Errorf("partition index must be greater than zero") |
| 136 | } |
| 137 | |
| 138 | // Get the system partition's size. |
| 139 | table, err := image.GetPartitionTable() |
| 140 | if err != nil { |
| 141 | return fmt.Errorf("while accessing a go-diskfs partition table: %w", err) |
| 142 | } |
| 143 | partitions := table.GetPartitions() |
| 144 | if index > len(partitions) { |
| 145 | return fmt.Errorf("partition index out of bounds") |
| 146 | } |
| 147 | size := partitions[index-1].GetSize() |
| 148 | |
| 149 | // Copy the contents of the Metropolis system image into the system partition |
| 150 | // at partitionIndex. Zero-pad the remaining space. |
| 151 | var zero zeroSrc |
| 152 | sys := io.LimitReader(io.MultiReader(contents, zero), size) |
| 153 | if _, err := image.WritePartitionContents(index, sys); err != nil { |
| 154 | return fmt.Errorf("while copying the system partition: %w", err) |
| 155 | } |
| 156 | return nil |
| 157 | } |
| 158 | |
| 159 | // mibToSectors converts a size expressed in mebibytes to a number of |
| 160 | // sectors needed to store data of that size. sectorSize parameter |
| 161 | // specifies the size of a logical sector. |
| 162 | func mibToSectors(size, sectorSize uint64) uint64 { |
| 163 | return (size * mib) / sectorSize |
| 164 | } |
| 165 | |
| 166 | // PartitionSizeInfo contains parameters used during partition table |
| 167 | // initialization and, in case of image files, space allocation. |
| 168 | type PartitionSizeInfo struct { |
| 169 | // Size of the EFI System Partition (ESP), in mebibytes. The size must |
| 170 | // not be zero. |
| 171 | ESP uint64 |
| 172 | // Size of the Metropolis system partition, in mebibytes. The partition |
| 173 | // won't be created if the size is zero. |
| 174 | System uint64 |
| 175 | // Size of the Metropolis data partition, in mebibytes. The partition |
| 176 | // won't be created if the size is zero. If the image is output to a |
| 177 | // block device, the partition will be extended to fill the remaining |
| 178 | // space. |
| 179 | Data uint64 |
| 180 | } |
| 181 | |
| 182 | // partitionList stores partition definitions in an ascending order. |
| 183 | type partitionList []*gpt.Partition |
| 184 | |
| 185 | // appendPartition puts a new partition at the end of a partitionList, |
| 186 | // automatically calculating its start and end markers based on data in |
| 187 | // the list and the argument psize. A partition type and a name are |
| 188 | // assigned to the partition. The containing image is used to calculate |
| 189 | // sector addresses based on its logical block size. |
| 190 | func (pl *partitionList) appendPartition(image *disk.Disk, ptype gpt.Type, pname string, psize uint64) { |
| 191 | // Calculate the start and end marker. |
| 192 | var pstart, pend uint64 |
| 193 | if len(*pl) != 0 { |
| 194 | pstart = (*pl)[len(*pl)-1].End + 1 |
| 195 | } else { |
| 196 | pstart = mibToSectors(1, uint64(image.LogicalBlocksize)) |
| 197 | } |
| 198 | pend = pstart + mibToSectors(psize, uint64(image.LogicalBlocksize)) - 1 |
| 199 | |
| 200 | // Put the new partition at the end of the list. |
| 201 | *pl = append(*pl, &gpt.Partition{ |
| 202 | Type: ptype, |
| 203 | Name: pname, |
| 204 | Start: pstart, |
| 205 | End: pend, |
| 206 | }) |
| 207 | } |
| 208 | |
| 209 | // extendLastPartition moves the end marker of the last partition in a |
| 210 | // partitionList to the end of image, assigning all of the remaining free |
| 211 | // space to it. It may return an error. |
| 212 | func (pl *partitionList) extendLastPartition(image *disk.Disk) error { |
| 213 | if len(*pl) == 0 { |
| 214 | return fmt.Errorf("no partitions defined") |
| 215 | } |
| 216 | if image.Size == 0 { |
| 217 | return fmt.Errorf("the image size mustn't be zero") |
| 218 | } |
| 219 | if image.LogicalBlocksize == 0 { |
| 220 | return fmt.Errorf("the image's logical block size mustn't be zero") |
| 221 | } |
| 222 | |
| 223 | // The last 33 blocks are occupied by the Secondary GPT. |
| 224 | (*pl)[len(*pl)-1].End = uint64(image.Size/image.LogicalBlocksize) - 33 |
| 225 | return nil |
| 226 | } |
| 227 | |
| 228 | // initializePartitionTable applies a Metropolis-compatible GPT partition |
| 229 | // table to an image. Logical and physical sector sizes are based on |
| 230 | // block sizes exposed by Disk. Partition extents are defined by the size |
| 231 | // argument. A diskGUID is associated with the partition table. In an event |
| 232 | // the table couldn't have been applied, the function will return an error. |
| 233 | func initializePartitionTable(image *disk.Disk, size *PartitionSizeInfo, diskGUID string) error { |
| 234 | // Start with preparing a partition list. |
| 235 | var pl partitionList |
| 236 | // Create the ESP. |
| 237 | if size.ESP == 0 { |
| 238 | return fmt.Errorf("ESP size mustn't be zero") |
| 239 | } |
| 240 | pl.appendPartition(image, gpt.EFISystemPartition, ESPVolumeLabel, size.ESP) |
| 241 | // Create the system partition only if its size is specified. |
| 242 | if size.System != 0 { |
| 243 | pl.appendPartition(image, systemPartitionType, SystemVolumeLabel, size.System) |
| 244 | } |
| 245 | // Create the data partition only if its size is specified. |
| 246 | if size.Data != 0 { |
| 247 | // Don't specify the last partition's length, as it will be extended |
| 248 | // to fit the image size anyway. size.Data will still be used in the |
| 249 | // space allocation step. |
| 250 | pl.appendPartition(image, dataPartitionType, DataVolumeLabel, 0) |
| 251 | if err := pl.extendLastPartition(image); err != nil { |
| 252 | return fmt.Errorf("while extending the last partition: %w", err) |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | // Build and apply the partition table. |
| 257 | table := &gpt.Table{ |
| 258 | LogicalSectorSize: int(image.LogicalBlocksize), |
| 259 | PhysicalSectorSize: int(image.PhysicalBlocksize), |
| 260 | ProtectiveMBR: true, |
| 261 | GUID: diskGUID, |
| 262 | Partitions: pl, |
| 263 | } |
| 264 | if err := image.Partition(table); err != nil { |
| 265 | // Return the error unwrapped. |
| 266 | return err |
| 267 | } |
| 268 | return nil |
| 269 | } |
| 270 | |
| 271 | // Params contains parameters used by Create to build a Metropolis OS |
| 272 | // image. |
| 273 | type Params struct { |
| 274 | // OutputPath is the path an OS image will be written to. If the path |
| 275 | // points to an existing block device, the data partition will be |
| 276 | // extended to fill it entirely. Otherwise, a regular image file will |
| 277 | // be created at OutputPath. The path must not point to an existing |
| 278 | // regular file. |
| 279 | OutputPath string |
| 280 | // EFIPayload provides contents of the EFI payload file. It must not be |
| 281 | // nil. |
| 282 | EFIPayload io.Reader |
| 283 | // SystemImage provides contents of the Metropolis system partition. |
| 284 | // If nil, no contents will be copied into the partition. |
| 285 | SystemImage io.Reader |
| 286 | // NodeParameters provides contents of the node parameters file. If nil, |
| 287 | // the node parameters file won't be created in the target ESP |
| 288 | // filesystem. |
| 289 | NodeParameters io.Reader |
| 290 | // DiskGUID is a unique identifier of the image and a part of GPT |
| 291 | // header. It's optional and can be left blank if the identifier is |
| 292 | // to be randomly generated. Setting it to a predetermined value can |
| 293 | // help in implementing reproducible builds. |
| 294 | DiskGUID string |
| 295 | // PartitionSize specifies a size for the ESP, Metropolis System and |
| 296 | // Metropolis data partition. |
| 297 | PartitionSize PartitionSizeInfo |
| 298 | } |
| 299 | |
| 300 | // Create writes a Metropolis OS image to either a newly created regular |
| 301 | // file or a block device. The image is parametrized by the params |
| 302 | // argument. In case a regular file already exists at params.OutputPath, |
| 303 | // the function will fail. It returns nil on success or an error, if one |
| 304 | // did occur. |
| 305 | func Create(params *Params) (*efivarfs.BootEntry, error) { |
| 306 | // Validate each parameter before use. |
| 307 | if params.OutputPath == "" { |
| 308 | return nil, fmt.Errorf("image output path must be set") |
| 309 | } |
| 310 | |
| 311 | // Learn whether we're creating a new image or writing to an existing |
| 312 | // block device by stat-ing the output path parameter. |
| 313 | outInfo, err := os.Stat(params.OutputPath) |
| 314 | if err != nil && !os.IsNotExist(err) { |
| 315 | return nil, err |
| 316 | } |
| 317 | |
| 318 | // Calculate the image size (bytes) by summing up partition sizes |
| 319 | // (mebibytes). |
| 320 | minSize := (int64(params.PartitionSize.ESP) + |
| 321 | int64(params.PartitionSize.System) + |
| 322 | int64(params.PartitionSize.Data) + 1) * mib |
| 323 | var diskImg *disk.Disk |
| 324 | if !os.IsNotExist(err) && outInfo.Mode()&os.ModeDevice != 0 { |
| 325 | // Open the block device. The data partition size parameter won't |
| 326 | // matter in this case, as said partition will be extended till the |
| 327 | // end of device. |
| 328 | diskImg, err = diskfs.Open(params.OutputPath) |
| 329 | if err != nil { |
| 330 | return nil, fmt.Errorf("couldn't open the block device at %q: %w", params.OutputPath, err) |
| 331 | } |
| 332 | // Make sure there's at least minSize space available on the block |
| 333 | // device. |
| 334 | if minSize > diskImg.Size { |
| 335 | return nil, fmt.Errorf("not enough space available on the block device at %q", params.OutputPath) |
| 336 | } |
| 337 | } else { |
| 338 | // Attempt to create an image file at params.OutputPath. diskfs.Create |
| 339 | // will abort in case a file already exists at the given path. |
| 340 | // Calculate the image size expressed in bytes by summing up declared |
| 341 | // partition lengths. |
| 342 | diskImg, err = diskfs.Create(params.OutputPath, minSize, diskfs.Raw) |
| 343 | if err != nil { |
| 344 | return nil, fmt.Errorf("couldn't create a disk image at %q: %w", params.OutputPath, err) |
| 345 | } |
| 346 | } |
| 347 | |
| 348 | // Go through the initialization steps, starting with applying a |
| 349 | // partition table according to params. |
| 350 | if err := initializePartitionTable(diskImg, ¶ms.PartitionSize, params.DiskGUID); err != nil { |
| 351 | return nil, fmt.Errorf("failed to initialize the partition table: %w", err) |
| 352 | } |
| 353 | // The system partition will be created only if its specified size isn't |
| 354 | // equal to zero, making the initialization step optional as well. In |
| 355 | // addition, params.SystemImage must be set. |
| 356 | if params.PartitionSize.System != 0 && params.SystemImage != nil { |
| 357 | if err := initializeSystemPartition(diskImg, 2, params.SystemImage); err != nil { |
| 358 | return nil, fmt.Errorf("failed to initialize the system partition: %w", err) |
| 359 | } |
| 360 | } else if params.PartitionSize.System == 0 && params.SystemImage != nil { |
| 361 | // Safeguard against contradicting parameters. |
| 362 | return nil, fmt.Errorf("the system image parameter was passed while the associated partition size is zero") |
| 363 | } |
| 364 | // Attempt to initialize the ESP unconditionally, as it's the only |
| 365 | // partition guaranteed to be created regardless of params.PartitionSize. |
| 366 | if err := initializeESP(diskImg, 1, params.EFIPayload, params.NodeParameters); err != nil { |
| 367 | return nil, fmt.Errorf("failed to initialize the ESP: %w", err) |
| 368 | } |
| 369 | // The data partition, even if created, is always left uninitialized. |
| 370 | |
| 371 | // Build an EFI boot entry pointing to the image's ESP. go-diskfs won't let |
| 372 | // you do that after you close the image. |
| 373 | t, err := diskImg.GetPartitionTable() |
| 374 | p := t.GetPartitions() |
| 375 | esp := (p[0]).(*gpt.Partition) |
Mateusz Zalega | 612a033 | 2021-11-17 20:04:52 +0100 | [diff] [blame] | 376 | guid, err := uuid.Parse(esp.GUID) |
| 377 | if err != nil { |
| 378 | return nil, fmt.Errorf("couldn't parse the GPT GUID: %w", err) |
| 379 | } |
Mateusz Zalega | c71efc9 | 2021-09-07 16:46:25 +0200 | [diff] [blame] | 380 | be := efivarfs.BootEntry{ |
| 381 | Description: "Metropolis", |
| 382 | Path: EFIPayloadPath, |
Mateusz Zalega | 612a033 | 2021-11-17 20:04:52 +0100 | [diff] [blame] | 383 | PartitionGUID: guid, |
Mateusz Zalega | c71efc9 | 2021-09-07 16:46:25 +0200 | [diff] [blame] | 384 | PartitionNumber: 1, |
| 385 | PartitionStart: esp.Start, |
| 386 | PartitionSize: esp.End - esp.Start + 1, |
| 387 | } |
| 388 | // Close the image and return the EFI boot entry. |
| 389 | if err := diskImg.File.Close(); err != nil { |
| 390 | return nil, fmt.Errorf("failed to finalize image: %w", err) |
| 391 | } |
| 392 | return &be, nil |
| 393 | } |