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
|
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/*
* This tool expects to be called from a udev rules file such as:
*
* ```
* SUBSYSTEM!="block", GOTO="ubuntu_core_partitions_end"
*
* ENV{DEVTYPE}=="disk", IMPORT{program}="/usr/lib/snapd/snap-bootstrap scan-disk"
* ENV{DEVTYPE}=="partition", IMPORT{parent}="UBUNTU_DISK"
* ENV{UBUNTU_DISK}!="1", GOTO="ubuntu_core_partitions_end"
*
* ENV{DEVTYPE}=="disk", SYMLINK+="disk/snapd/disk"
* ENV{DEVTYPE}=="partition", ENV{ID_PART_ENTRY_NAME}=="ubuntu-seed", SYMLINK+="disk/snapd/ubuntu-seed"
* ENV{DEVTYPE}=="partition", ENV{ID_PART_ENTRY_NAME}=="ubuntu-boot", SYMLINK+="disk/snapd/ubuntu-boot"
* ENV{DEVTYPE}=="partition", ENV{ID_PART_ENTRY_NAME}=="ubuntu-data", ENV{ID_FS_TYPE}=="crypto_LUKS", SYMLINK+="disk/snapd/ubuntu-data-luks"
* ENV{DEVTYPE}=="partition", ENV{ID_PART_ENTRY_NAME}=="ubuntu-data", ENV{ID_FS_TYPE}!="crypto_LUKS", SYMLINK+="disk/snapd/ubuntu-data"
* ENV{DEVTYPE}=="partition", ENV{ID_PART_ENTRY_NAME}=="ubuntu-save", ENV{ID_FS_TYPE}=="crypto_LUKS", SYMLINK+="disk/snapd/ubuntu-save-luks"
* ENV{DEVTYPE}=="partition", ENV{ID_PART_ENTRY_NAME}=="ubuntu-save", ENV{ID_FS_TYPE}!="crypto_LUKS", SYMLINK+="disk/snapd/ubuntu-save"
*
* LABEL="ubuntu_core_partitions_end"
*
* ENV{DM_UUID}=="CRYPT-*", ENV{DM_NAME}=="ubuntu-data-*", SYMLINK+="disk/snapd/ubuntu-data"
* ENV{DM_UUID}=="CRYPT-*", ENV{DM_NAME}=="ubuntu-save-*", SYMLINK+="disk/snapd/ubuntu-save"
* ```
*
* See
* core-initrd/latest/factory/usr/lib/udev/rules.d/90-ubuntu-core-partitions.rules
* for implementation.
*
* Note that symlink /dev/disk/snapd/disk can be expected by
* snap-bootstrap. In that case, snap-initramfs-mounts.service should
* have:
*
* ```
* BindsTo=dev-disk-snapd--disk.device
* After=dev-disk-snapd-disk.device
* ```
*
*/
package main
import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/jessevdk/go-flags"
"github.com/snapcore/snapd/boot"
"github.com/snapcore/snapd/cmd/snap-bootstrap/blkid"
"github.com/snapcore/snapd/dirs"
"github.com/snapcore/snapd/logger"
"github.com/snapcore/snapd/osutil/kcmdline"
)
func init() {
const (
short = "Verify that a disk is the booting disk"
long = "This tool is expected to be called from udev"
)
addCommandBuilder(func(parser *flags.Parser) {
if _, err := parser.AddCommand("scan-disk", short, long, &cmdScanDisk{}); err != nil {
panic(err)
}
})
}
type cmdScanDisk struct{}
func (c *cmdScanDisk) Execute([]string) error {
return ScanDisk(os.Stdout)
}
type Partition struct {
Name string
UUID string
// FilesystemLabel is the label of the filesystem of the
// partition. On MBR schemas, partitions do not have a name,
// instead we probe for the label of the filesystem. So this
// will only be set if it's a non-GPT.
FilesystemLabel string
}
func isGpt(probe blkid.AbstractBlkidProbe) bool {
pttype, err := probe.LookupValue("PTTYPE")
if err != nil {
return false
}
return pttype == "gpt"
}
// probeFilesystem probes filesystem information in leiu of when
// we cannot retrieve enough information from the partition table.
// <start> and <size> must be byte offsets, not sector counts.
func probeFilesystem(node string, start, size int64) (Partition, error) {
var p Partition
probe, err := blkid.NewProbeFromRange(node, start, size)
if err != nil {
return p, err
}
defer probe.Close()
probe.EnableSuperblocks(true)
probe.SetSuperblockFlags(blkid.BLKID_SUBLKS_LABEL)
if err := probe.DoSafeprobe(); err != nil {
return p, err
}
val, err := probe.LookupValue("LABEL")
if err != nil {
return p, err
}
p.FilesystemLabel = val
return p, nil
}
func probeDisk(node string) ([]Partition, error) {
probe, err := blkid.NewProbeFromFilename(node)
if err != nil {
return nil, err
}
defer probe.Close()
probe.EnablePartitions(true)
probe.SetPartitionsFlags(blkid.BLKID_PARTS_ENTRY_DETAILS)
if err := probe.DoSafeprobe(); err != nil {
return nil, err
}
gpt := isGpt(probe)
partitions, err := probe.GetPartitions()
if err != nil {
return nil, err
} else if partitions == nil {
// Observed on rpi4 with loop-devices from snaps, no
// partitions exists, but no error is returned either, so
// catch the partitions == nil cases to avoid crashes.
return nil, nil
}
sectorSize, err := probe.GetSectorSize()
if sectorSize == 0 && err != nil {
return nil, err
}
ret := make([]Partition, 0)
ss64 := int64(sectorSize)
for _, partition := range partitions.GetPartitions() {
if gpt {
ret = append(ret, Partition{
Name: partition.GetName(),
UUID: partition.GetUUID(),
})
} else {
// For MBR we have to probe the filesystem for details
p, err := probeFilesystem(node, partition.GetStart()*ss64, partition.GetSize()*ss64)
if err != nil {
// On the pi, it has been observed during the installation of a preseeded image, that it
// can trigger udev, which retriggers snap-bootstrap scan-disk where in the non-gpt
// case we try to probe the filesystem too early, before it's formatted (so no LABEL).
// So log a warning, but continue processing other partitions.
logger.Noticef("WARNING: cannot probe filesystem on non-GPT partition: %s", err)
continue
}
ret = append(ret, p)
}
}
return ret, nil
}
func samePath(a, b string) (bool, error) {
aSt, err := os.Stat(a)
if err != nil {
return false, err
}
bSt, err := os.Stat(b)
if err != nil {
return false, err
}
return os.SameFile(aSt, bSt), nil
}
func scanDiskNodeFallback(output io.Writer, node string) error {
var fallbackPartition string
partitions, err := probeDisk(node)
if err != nil {
return fmt.Errorf("cannot get partitions: %s\n", err)
}
/*
* If LoaderDevicePartUUID was not set, it is probably because
* we did not boot with UEFI. In that case we try to detect
* disk with partition labels.
*/
mode, _, err := boot.ModeAndRecoverySystemFromKernelCommandLine()
if err != nil {
return err
}
switch mode {
case "recover":
fallbackPartition = "ubuntu-seed"
case "install":
fallbackPartition = "ubuntu-seed"
case "factory-reset":
fallbackPartition = "ubuntu-seed"
case "run":
fallbackPartition = "ubuntu-boot"
case "cloudimg-rootfs":
fallbackPartition = "ubuntu-boot"
default:
return fmt.Errorf("internal error: mode not handled")
}
/*
* If we are not in UEFI mode and snapd_system_disk is
* defined, we need to verify the disk also matches that. If
* not, we just return, ignoring this disk.
*/
values, err := kcmdline.KeyValues("snapd_system_disk")
if err != nil {
return fmt.Errorf("cannot read kernel command line: %s\n", err)
}
if value, ok := values["snapd_system_disk"]; ok {
var currentPath string
var expectedPath string
if strings.HasPrefix(value, "/dev/") || !strings.HasPrefix(value, "/") {
name := strings.TrimPrefix(value, "/dev/")
expectedPath = fmt.Sprintf("/dev/%s", name)
currentPath = node
} else {
expectedPath = value
currentPath = osGetenv("DEVPATH")
}
same, err := samePath(filepath.Join(dirs.GlobalRootDir, expectedPath),
filepath.Join(dirs.GlobalRootDir, currentPath))
if err != nil {
return fmt.Errorf("cannot check snapd_system_disk kernel parameter: %s\n", err)
}
if !same {
/*
* This block device is not the device
* requested from the command line. But this
* is not an error. There are lots of block
* devices.
*/
return nil
}
}
for _, part := range partitions {
if part.Name == fallbackPartition || part.FilesystemLabel == fallbackPartition {
fmt.Fprintf(output, "UBUNTU_DISK=1\n")
return nil
}
}
/*
* We have found the block device is not a boot device. But
* this is not an error. There are plenty of block devices
* that are not the boot device.
*/
return nil
}
func isCVM() (bool, error) {
m, err := kcmdline.KeyValues("snapd_recovery_mode")
if err != nil {
return false, err
}
mode, hasMode := m["snapd_recovery_mode"]
return hasMode && mode == boot.ModeRunCVM, nil
}
func scanDiskNode(output io.Writer, node string) error {
/*
* We need to find out if the given node contains the ESP that
* was booted. The boot loader will set
* LoaderDevicePartUUID. We will need to scan all the
* partitions for that UUID.
*/
bootUUID, err := bootFindPartitionUUIDForBootedKernelDisk()
if err != nil {
return scanDiskNodeFallback(output, node)
}
partitions, err := probeDisk(node)
if err != nil {
return fmt.Errorf("cannot get partitions: %s\n", err)
}
/*
* Now we scan the partitions. We need to find the partition
* grub booted from.
*/
found := false
hasSeed := false
hasBoot := false
for _, part := range partitions {
if part.UUID == bootUUID {
/*
* We have just found the ESP boot partition!
*/
found = true
}
if part.Name == "ubuntu-seed" {
hasSeed = true
} else if part.Name == "ubuntu-boot" {
hasBoot = true
}
}
cvm, err := isCVM()
if err != nil {
logger.Noticef("WARNING: error while reading recovery mode: %v", err)
return nil
}
/*
* We now print the result if we confirmed we found the boot ESP.
*/
if found && (hasSeed || hasBoot || cvm) {
fmt.Fprintf(output, "UBUNTU_DISK=1\n")
}
/*
* We have found the block device is not a boot device. But
* this is not an error. There are plenty of block devices
* that are not the boot device.
*/
return nil
}
func ScanDisk(output io.Writer) error {
devname := osGetenv("DEVNAME")
if osGetenv("DEVTYPE") == "disk" {
return scanDiskNode(output, devname)
} else {
return fmt.Errorf("unknown type for block device %s\n", devname)
}
}
|