github.com/hugh712/snapd@v0.0.0-20200910133618-1a99902bd583/kernel/kernel.go (about) 1 // -*- Mode: Go; indent-tabs-mode: t -*- 2 3 /* 4 * Copyright (C) 2020 Canonical Ltd 5 * 6 * This program is free software: you can redistribute it and/or modify 7 * it under the terms of the GNU General Public License version 3 as 8 * published by the Free Software Foundation. 9 * 10 * This program is distributed in the hope that it will be useful, 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * GNU General Public License for more details. 14 * 15 * You should have received a copy of the GNU General Public License 16 * along with this program. If not, see <http://www.gnu.org/licenses/>. 17 * 18 */ 19 20 package kernel 21 22 import ( 23 "fmt" 24 "io/ioutil" 25 "os" 26 "path/filepath" 27 "regexp" 28 29 "gopkg.in/yaml.v2" 30 31 "github.com/snapcore/snapd/gadget/edition" 32 ) 33 34 type Asset struct { 35 Edition edition.Number `yaml:"edition,omitempty"` 36 Content []string `yaml:"content,omitempty"` 37 } 38 39 type Info struct { 40 Assets map[string]*Asset `yaml:"assets,omitempty"` 41 } 42 43 // XXX: should we be more liberal? start conservative 44 var validAssetName = regexp.MustCompile("^[a-zA-Z0-9]+$") 45 46 // InfoFromKernelYaml reads the provided kernel metadata. 47 func InfoFromKernelYaml(kernelYaml []byte) (*Info, error) { 48 var ki Info 49 50 if err := yaml.Unmarshal(kernelYaml, &ki); err != nil { 51 return nil, fmt.Errorf("cannot parse kernel metadata: %v", err) 52 } 53 54 for name := range ki.Assets { 55 if !validAssetName.MatchString(name) { 56 return nil, fmt.Errorf("invalid asset name %q, please use only alphanumeric characters", name) 57 } 58 } 59 60 return &ki, nil 61 } 62 63 // ReadInfo reads the kernel specific metadata from meta/kernel.yaml 64 // in the snap root directory if the file exists. 65 func ReadInfo(kernelSnapRootDir string) (*Info, error) { 66 p := filepath.Join(kernelSnapRootDir, "meta", "kernel.yaml") 67 content, err := ioutil.ReadFile(p) 68 // meta/kernel.yaml is optional so we should not error here if 69 // it is missing 70 if os.IsNotExist(err) { 71 return &Info{}, nil 72 } 73 if err != nil { 74 return nil, fmt.Errorf("cannot read kernel info: %v", err) 75 } 76 return InfoFromKernelYaml(content) 77 }