github.com/hugh712/snapd@v0.0.0-20200910133618-1a99902bd583/asserts/fsentryutils.go (about) 1 // -*- Mode: Go; indent-tabs-mode: t -*- 2 3 /* 4 * Copyright (C) 2015-2016 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 asserts 21 22 import ( 23 "fmt" 24 "io/ioutil" 25 "os" 26 "path/filepath" 27 28 "github.com/snapcore/snapd/osutil" 29 ) 30 31 // utilities to read/write fs entries 32 33 func ensureTop(path string) error { 34 err := os.MkdirAll(path, 0775) 35 if err != nil { 36 return fmt.Errorf("cannot create assert storage root: %v", err) 37 } 38 info, err := os.Stat(path) 39 if err != nil { 40 return fmt.Errorf("cannot create assert storage root: %v", err) 41 } 42 if info.Mode().Perm()&0002 != 0 { 43 return fmt.Errorf("assert storage root unexpectedly world-writable: %v", path) 44 } 45 return nil 46 } 47 48 func atomicWriteEntry(data []byte, secret bool, top string, subpath ...string) error { 49 fpath := filepath.Join(top, filepath.Join(subpath...)) 50 dir := filepath.Dir(fpath) 51 err := os.MkdirAll(dir, 0775) 52 if err != nil { 53 return err 54 } 55 fperm := 0664 56 if secret { 57 fperm = 0600 58 } 59 return osutil.AtomicWriteFile(fpath, data, os.FileMode(fperm), 0) 60 } 61 62 func entryExists(top string, subpath ...string) bool { 63 fpath := filepath.Join(top, filepath.Join(subpath...)) 64 return osutil.FileExists(fpath) 65 } 66 67 func readEntry(top string, subpath ...string) ([]byte, error) { 68 fpath := filepath.Join(top, filepath.Join(subpath...)) 69 return ioutil.ReadFile(fpath) 70 }