pax_global_header00006660000000000000000000000064131065307400014511gustar00rootroot0000000000000052 comment=256976a42706934b027729183e3a5af2ae646502 golang-github-mvo5-uboot-go-0.4+git256976a/000077500000000000000000000000001310653074000201435ustar00rootroot00000000000000golang-github-mvo5-uboot-go-0.4+git256976a/.travis.yml000066400000000000000000000001141310653074000222500ustar00rootroot00000000000000language: go install: - go get -t -v ./... script: - go test -v ./... golang-github-mvo5-uboot-go-0.4+git256976a/COPYING000066400000000000000000000020371310653074000212000ustar00rootroot00000000000000Copyright (c) 2014 Canonical Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: . The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. . THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. golang-github-mvo5-uboot-go-0.4+git256976a/README.md000066400000000000000000000026101310653074000214210ustar00rootroot00000000000000[![Build Status][travis-image]][travis-url] # Read/write uboot environment Small go package/app to read/write uboot env files that contain crc32 + 1 byte padding. Unlike fw_{set,print}env it does not needs a /etc/fw_env.config config file. Example of the API: ``` package main import ( "fmt" "github.com/mvo5/uboot-go/uenv" "os" ) func main() { env, _ := uenv.Open(os.Args[1]) fmt.Print(env) env.Set("foo", "bar") fmt.Print(env) } ``` Example of the cmdline app for existing files: ``` $ uboot-go uboot.env print initrd_addr=0x88080000 uenvcmd=load mmc ${bootpart} ${loadaddr} snappy-system.txt; env import -t $loadaddr $filesize; run snappy_boot bootpart=0:1 $ uboot-go uboot.env set key value $ uboot-go uboot.env print initrd_addr=0x88080000 uenvcmd=load mmc ${bootpart} ${loadaddr} snappy-system.txt; env import -t $loadaddr $filesize; run snappy_boot bootpart=0:1 key=value # echo "$(pwd)/uboot.env 0x000 0x20000" > /etc/fw_env.config $ fw_printenv initrd_addr=0x88080000 uenvcmd=load mmc ${bootpart} ${loadaddr} snappy-system.txt; env import -t $loadaddr $filesize; run snappy_boot bootpart=0:1 key=value ``` Example of the cmdline app for creating new env files: ``` $ uboot-go uboot.env create 4096 $ uboot-go uboot.env set foo bar $ uboot-go uboot.env print foo=bar ``` [travis-image]: https://travis-ci.org/mvo5/uboot-go.svg?branch=master [travis-url]: https://travis-ci.org/mvo5/uboot-go golang-github-mvo5-uboot-go-0.4+git256976a/main.go000066400000000000000000000027061310653074000214230ustar00rootroot00000000000000package main import ( "fmt" "log" "os" "strconv" "github.com/mvo5/uboot-go/uenv" ) func main() { // FIXME: argsparse ftw! envFile := os.Args[1] cmd := os.Args[2] switch cmd { case "print": env, err := uenv.Open(envFile) if err != nil { log.Fatalf("uenv.Open failed for %s: %s", envFile, err) } fmt.Print(env) case "create": size, err := strconv.Atoi(os.Args[3]) if err != nil { log.Fatalf("Atoi failed for %s: %s", envFile, err) } env, err := uenv.Create(envFile, size) if err != nil { log.Fatalf("uenv.Create failed for %s: %s", envFile, err) } if err := env.Save(); err != nil { log.Fatalf("env.Save failed: %s", err) } case "set": env, err := uenv.Open(envFile) if err != nil { log.Fatalf("uenv.Open failed for %s: %s", envFile, err) } name := os.Args[3] value := os.Args[4] env.Set(name, value) if err := env.Save(); err != nil { log.Fatalf("env.Save failed for %s: %s", envFile, err) } case "import": env, err := uenv.Open(envFile) if err != nil { log.Fatalf("uenv.Open failed for %s: %s", envFile, err) } fname := os.Args[3] r, err := os.Open(fname) if err != nil { log.Fatalf("Open failed for %s: %s", fname, err) } if err := env.Import(r); err != nil { log.Fatalf("env.Import failed for %s: %s", envFile, err) } if err := env.Save(); err != nil { log.Fatalf("env.Save failed for %s: %s", envFile, err) } default: log.Fatalf("unknown command %s", cmd) } } golang-github-mvo5-uboot-go-0.4+git256976a/run-checks000077500000000000000000000012631310653074000221350ustar00rootroot00000000000000#!/bin/sh set -e if which goctest >/dev/null; then goctest="goctest" else goctest="go test" fi echo Checking formatting fmt="$(gofmt -l .)" if [ -n "$fmt" ]; then echo "Formatting wrong in following files" echo "$fmt" exit 1 fi echo Installing godeps go get launchpad.net/godeps export PATH=$PATH:$GOPATH/bin echo Install golint go get github.com/golang/lint/golint export PATH=$PATH:$GOPATH/bin echo Building go build -v . # tests echo Running tests from $(pwd) $goctest -v -cover ./... # go vet echo Running vet go vet ./... # golint echo Running lint lint="$(golint ./...)" if [ -n "$lint" ]; then echo "Lint complains:" echo "$lint" exit 1 fi golang-github-mvo5-uboot-go-0.4+git256976a/uenv/000077500000000000000000000000001310653074000211205ustar00rootroot00000000000000golang-github-mvo5-uboot-go-0.4+git256976a/uenv/env.go000066400000000000000000000133501310653074000222410ustar00rootroot00000000000000package uenv import ( "bufio" "bytes" "encoding/binary" "fmt" "hash/crc32" "io" "io/ioutil" "os" "sort" "strings" ) // FIXME: add config option for that so that the user can select if // he/she wants env with or without flags var headerSize = 5 // Env contains the data of the uboot environment type Env struct { fname string size int 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() } // Create a new empty uboot env file with the given size func Create(fname string, size int) (*Env, error) { f, err := os.Create(fname) if err != nil { return nil, err } defer f.Close() env := &Env{ fname: fname, size: size, 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 := ioutil.ReadAll(f) if err != nil { return nil, err } crc := readUint32(contentWithHeader) payload := contentWithHeader[headerSize:] actualCRC := crc32.ChecksumIEEE(payload) if crc != actualCRC { return nil, fmt.Errorf("bad CRC: %v != %v", crc, actualCRC) } eof := bytes.Index(payload, []byte{0, 0}) data, err := parseData(payload[:eof], flags) if err != nil { return nil, err } env := &Env{ fname: fname, size: len(contentWithHeader), 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 { 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 } // 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 { 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()) // 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 } return f.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() } golang-github-mvo5-uboot-go-0.4+git256976a/uenv/env_test.go000066400000000000000000000121171310653074000233000ustar00rootroot00000000000000package uenv import ( "bytes" "hash/crc32" "io/ioutil" "os" "path/filepath" "strings" "testing" . "gopkg.in/check.v1" ) // Hook up check.v1 into the "go test" runner func Test(t *testing.T) { TestingT(t) } type uenvTestSuite struct { envFile string } var _ = Suite(&uenvTestSuite{}) func (u *uenvTestSuite) SetUpTest(c *C) { u.envFile = filepath.Join(c.MkDir(), "uboot.env") } func (u *uenvTestSuite) TestSetNoDuplicate(c *C) { env, err := Create(u.envFile, 4096) c.Assert(err, IsNil) env.Set("foo", "bar") env.Set("foo", "bar") c.Assert(env.String(), Equals, "foo=bar\n") } func (u *uenvTestSuite) TestOpenEnv(c *C) { env, err := Create(u.envFile, 4096) c.Assert(err, IsNil) env.Set("foo", "bar") c.Assert(env.String(), Equals, "foo=bar\n") err = env.Save() c.Assert(err, IsNil) env2, err := Open(u.envFile) c.Assert(err, IsNil) c.Assert(env2.String(), Equals, "foo=bar\n") } func (u *uenvTestSuite) TestGetSimple(c *C) { env, err := Create(u.envFile, 4096) c.Assert(err, IsNil) env.Set("foo", "bar") c.Assert(env.Get("foo"), Equals, "bar") } func (u *uenvTestSuite) TestGetNoSuchEntry(c *C) { env, err := Create(u.envFile, 4096) c.Assert(err, IsNil) c.Assert(env.Get("no-such-entry"), Equals, "") } func (u *uenvTestSuite) TestImport(c *C) { env, err := Create(u.envFile, 4096) c.Assert(err, IsNil) r := strings.NewReader("foo=bar\n#comment\n\nbaz=baz") err = env.Import(r) c.Assert(err, IsNil) // order is alphabetic c.Assert(env.String(), Equals, "baz=baz\nfoo=bar\n") } func (u *uenvTestSuite) TestImportHasError(c *C) { env, err := Create(u.envFile, 4096) c.Assert(err, IsNil) r := strings.NewReader("foxy") err = env.Import(r) c.Assert(err, ErrorMatches, "Invalid line: \"foxy\"") } func (u *uenvTestSuite) TestSetEmptyUnsets(c *C) { env, err := Create(u.envFile, 4096) c.Assert(err, IsNil) env.Set("foo", "bar") c.Assert(env.String(), Equals, "foo=bar\n") env.Set("foo", "") c.Assert(env.String(), Equals, "") } func (u *uenvTestSuite) makeUbootEnvFromData(c *C, mockData []byte) { w := bytes.NewBuffer(nil) crc := crc32.ChecksumIEEE(mockData) w.Write(writeUint32(crc)) w.Write([]byte{0}) w.Write(mockData) f, err := os.Create(u.envFile) c.Assert(err, IsNil) defer f.Close() _, err = f.Write(w.Bytes()) c.Assert(err, IsNil) } // ensure that the data after \0\0 is discarded (except for crc) func (u *uenvTestSuite) TestReadStopsAfterDoubleNull(c *C) { mockData := []byte{ // foo=bar 0x66, 0x6f, 0x6f, 0x3d, 0x62, 0x61, 0x72, // eof 0x00, 0x00, // junk after eof as written by fw_setenv sometimes // =b 0x3d, 62, // empty 0xff, 0xff, } u.makeUbootEnvFromData(c, mockData) env, err := Open(u.envFile) c.Assert(err, IsNil) c.Assert(env.String(), Equals, "foo=bar\n") } // ensure that the malformed data is not causing us to panic. func (u *uenvTestSuite) TestErrorOnMalformedData(c *C) { mockData := []byte{ // foo 0x66, 0x6f, 0x6f, // eof 0x00, 0x00, } u.makeUbootEnvFromData(c, mockData) env, err := Open(u.envFile) c.Assert(err, ErrorMatches, `cannot parse line "foo" as key=value pair`) c.Assert(env, IsNil) } // ensure that the malformed data is not causing us to panic. func (u *uenvTestSuite) TestOpenBestEffort(c *C) { mockData := []byte{ // key1=value1 0x6b, 0x65, 0x79, 0x31, 0x3d, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x31, 0x00, // foo 0x66, 0x6f, 0x6f, 0x00, // key2=value2 0x6b, 0x65, 0x79, 0x32, 0x3d, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x32, 0x00, // eof 0x00, 0x00, } u.makeUbootEnvFromData(c, mockData) env, err := OpenWithFlags(u.envFile, OpenBestEffort) c.Assert(err, IsNil) c.Assert(env.String(), Equals, "key1=value1\nkey2=value2\n") } func (u *uenvTestSuite) TestReadEmptyFile(c *C) { mockData := []byte{ // eof 0x00, 0x00, // empty 0xff, 0xff, } u.makeUbootEnvFromData(c, mockData) env, err := Open(u.envFile) c.Assert(err, IsNil) c.Assert(env.String(), Equals, "") } func (u *uenvTestSuite) TestWritesEmptyFileWithDoubleNewline(c *C) { env, err := Create(u.envFile, 12) c.Assert(err, IsNil) err = env.Save() c.Assert(err, IsNil) r, err := os.Open(u.envFile) c.Assert(err, IsNil) defer r.Close() content, err := ioutil.ReadAll(r) c.Assert(err, IsNil) c.Assert(content, DeepEquals, []byte{ // crc 0x11, 0x38, 0xb3, 0x89, // redundant 0x0, // eof 0x0, 0x0, // footer 0xff, 0xff, 0xff, 0xff, 0xff, }) env, err = Open(u.envFile) c.Assert(err, IsNil) c.Assert(env.String(), Equals, "") } func (u *uenvTestSuite) TestWritesContentCorrectly(c *C) { totalSize := 16 env, err := Create(u.envFile, totalSize) c.Assert(err, IsNil) env.Set("a", "b") env.Set("c", "d") err = env.Save() c.Assert(err, IsNil) r, err := os.Open(u.envFile) c.Assert(err, IsNil) defer r.Close() content, err := ioutil.ReadAll(r) c.Assert(err, IsNil) c.Assert(content, DeepEquals, []byte{ // crc 0xc7, 0xd9, 0x6b, 0xc5, // redundant 0x0, // a=b 0x61, 0x3d, 0x62, // eol 0x0, // c=d 0x63, 0x3d, 0x64, // eof 0x0, 0x0, // footer 0xff, 0xff, }) env, err = Open(u.envFile) c.Assert(err, IsNil) c.Assert(env.String(), Equals, "a=b\nc=d\n") c.Assert(env.size, Equals, totalSize) }