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
|
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2017 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/>.
*
*/
package ubootenv
import (
"bufio"
"bytes"
"encoding/binary"
"errors"
"fmt"
"hash/crc32"
"io"
"os"
"path/filepath"
"sort"
"strings"
)
// Env contains the data of the uboot environment
type Env struct {
fname string
size int
headerFlagByte bool
data map[string]string
}
// little endian helpers
func readUint32(data []byte) uint32 {
var ret uint32
buf := bytes.NewBuffer(data)
binary.Read(buf, binary.LittleEndian, &ret)
return ret
}
func writeUint32(u uint32) []byte {
buf := bytes.NewBuffer(nil)
binary.Write(buf, binary.LittleEndian, &u)
return buf.Bytes()
}
const sizeOfUint32 = 4
func calcHeaderSize(headerFlagByte bool) int {
if headerFlagByte {
// If uboot uses a header flag byte, header is 4 byte crc + flag byte
return sizeOfUint32 + 1
}
// otherwise, just a 4 byte crc
return sizeOfUint32
}
type CreateOptions struct {
HeaderFlagByte bool
}
// Create a new empty uboot env file with the given size
func Create(fname string, size int, opts CreateOptions) (*Env, error) {
f, err := os.Create(fname)
if err != nil {
return nil, err
}
defer f.Close()
env := &Env{
fname: fname,
size: size,
headerFlagByte: opts.HeaderFlagByte,
data: make(map[string]string),
}
return env, nil
}
// OpenFlags instructs open how to alter its behavior.
type OpenFlags int
const (
// OpenBestEffort instructs OpenWithFlags to skip malformed data without returning an error.
OpenBestEffort OpenFlags = 1 << iota
)
// Open opens a existing uboot env file
func Open(fname string) (*Env, error) {
return OpenWithFlags(fname, OpenFlags(0))
}
// OpenWithFlags opens a existing uboot env file, passing additional flags.
func OpenWithFlags(fname string, flags OpenFlags) (*Env, error) {
f, err := os.Open(fname)
if err != nil {
return nil, err
}
defer f.Close()
contentWithHeader, err := io.ReadAll(f)
if err != nil {
return nil, err
}
// Most systems have SYS_REDUNDAND_ENVIRONMENT=y, so try that first
tryHeaderFlagByte := true
env, err := readEnv(contentWithHeader, flags, tryHeaderFlagByte)
// if there is a bad CRC, maybe we just assumed the wrong header size
if errors.Is(err, errBadCrc) {
tryHeaderFlagByte := false
env, err = readEnv(contentWithHeader, flags, tryHeaderFlagByte)
}
// if error was not one of the ones that might indicate we assumed the wrong
// header size, or there is still an error after checking both header sizes
// something is actually wrong
if err != nil {
return nil, fmt.Errorf("cannot open %q: %w", fname, err)
}
env.fname = fname
return env, nil
}
var errBadCrc = errors.New("bad CRC")
func readEnv(contentWithHeader []byte, flags OpenFlags, headerFlagByte bool) (*Env, error) {
// The minimum valid env is 6 bytes (4 byte CRC + 2 null bytes for EOF)
// The maximum header length is 5 bytes (4 byte CRC, + )
// If we always make sure our env is 6 bytes long, we'll never run into
// trouble doing some sort of OOB slicing below, but also we will
// accept all legal envs
if len(contentWithHeader) < 6 {
return nil, errors.New("smaller than expected environment block")
}
headerSize := calcHeaderSize(headerFlagByte)
crc := readUint32(contentWithHeader)
payload := contentWithHeader[headerSize:]
actualCRC := crc32.ChecksumIEEE(payload)
if crc != actualCRC {
return nil, fmt.Errorf("%w %v != %v", errBadCrc, crc, actualCRC)
}
if eof := bytes.Index(payload, []byte{0, 0}); eof >= 0 {
payload = payload[:eof]
}
data, err := parseData(payload, flags)
if err != nil {
return nil, err
}
env := &Env{
size: len(contentWithHeader),
headerFlagByte: headerFlagByte,
data: data,
}
return env, nil
}
func parseData(data []byte, flags OpenFlags) (map[string]string, error) {
out := make(map[string]string)
for _, envStr := range bytes.Split(data, []byte{0}) {
if len(envStr) == 0 || envStr[0] == 0 || envStr[0] == 255 {
continue
}
l := strings.SplitN(string(envStr), "=", 2)
if len(l) != 2 || l[0] == "" {
if flags&OpenBestEffort == OpenBestEffort {
continue
}
return nil, fmt.Errorf("cannot parse line %q as key=value pair", envStr)
}
key := l[0]
value := l[1]
out[key] = value
}
return out, nil
}
func (env *Env) String() string {
out := ""
env.iterEnv(func(key, value string) {
out += fmt.Sprintf("%s=%s\n", key, value)
})
return out
}
func (env *Env) Size() int {
return env.size
}
func (env *Env) HeaderFlagByte() bool {
return env.headerFlagByte
}
// Get the value of the environment variable
func (env *Env) Get(name string) string {
return env.data[name]
}
// Set an environment name to the given value, if the value is empty
// the variable will be removed from the environment
func (env *Env) Set(name, value string) {
if name == "" {
panic(fmt.Sprintf("Set() can not be called with empty key for value: %q", value))
}
if value == "" {
delete(env.data, name)
return
}
env.data[name] = value
}
// iterEnv calls the passed function f with key, value for environment
// vars. The order is guaranteed (unlike just iterating over the map)
func (env *Env) iterEnv(f func(key, value string)) {
keys := make([]string, 0, len(env.data))
for k := range env.data {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
if k == "" {
panic("iterEnv iterating over a empty key")
}
f(k, env.data[k])
}
}
// Save will write out the environment data
func (env *Env) Save() error {
headerSize := calcHeaderSize(env.headerFlagByte)
w := bytes.NewBuffer(nil)
// will panic if the buffer can't grow, all writes to
// the buffer will be ok because we sized it correctly
w.Grow(env.size - headerSize)
// write the payload
env.iterEnv(func(key, value string) {
w.Write([]byte(fmt.Sprintf("%s=%s", key, value)))
w.Write([]byte{0})
})
// write double \0 to mark the end of the env
w.Write([]byte{0})
// no keys, so no previous \0 was written so we write one here
if len(env.data) == 0 {
w.Write([]byte{0})
}
// write ff into the remaining parts
writtenSoFar := w.Len()
for i := 0; i < env.size-headerSize-writtenSoFar; i++ {
w.Write([]byte{0xff})
}
// checksum
crc := crc32.ChecksumIEEE(w.Bytes())
// ensure dir sync
dir, err := os.Open(filepath.Dir(env.fname))
if err != nil {
return err
}
defer dir.Close()
// Note that we overwrite the existing file and do not do
// the usual write-rename. The rationale is that we want to
// minimize the amount of writes happening on a potential
// FAT partition where the env is loaded from. The file will
// always be of a fixed size so we know the writes will not
// fail because of ENOSPC.
//
// The size of the env file never changes so we do not
// truncate it.
//
// We also do not O_TRUNC to avoid reallocations on the FS
// to minimize risk of fs corruption.
f, err := os.OpenFile(env.fname, os.O_WRONLY, 0666)
if err != nil {
return err
}
defer f.Close()
if _, err := f.Write(writeUint32(crc)); err != nil {
return err
}
// padding bytes (e.g. for redundant header)
pad := make([]byte, headerSize-binary.Size(crc))
if _, err := f.Write(pad); err != nil {
return err
}
if _, err := f.Write(w.Bytes()); err != nil {
return err
}
if err := f.Sync(); err != nil {
return err
}
return dir.Sync()
}
// Import is a helper that imports a given text file that contains
// "key=value" paris into the uboot env. Lines starting with ^# are
// ignored (like the input file on mkenvimage)
func (env *Env) Import(r io.Reader) error {
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "#") || len(line) == 0 {
continue
}
l := strings.SplitN(line, "=", 2)
if len(l) == 1 {
return fmt.Errorf("Invalid line: %q", line)
}
env.data[l[0]] = l[1]
}
return scanner.Err()
}
|