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 376 377 378 379 380 381 382 383 384
|
// -*- 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 osutil
import (
"fmt"
"math"
"os"
"regexp"
"strings"
)
// MountEntry describes an /etc/fstab-like mount entry.
//
// Fields are named after names in struct returned by getmntent(3).
//
// struct mntent {
// char *mnt_fsname; /* name of mounted filesystem */
// char *mnt_dir; /* filesystem path prefix */
// char *mnt_type; /* mount type (see Mntent.h) */
// char *mnt_opts; /* mount options (see Mntent.h) */
// int mnt_freq; /* dump frequency in days */
// int mnt_passno; /* pass number on parallel fsck */
// };
type MountEntry struct {
Name string // Device name, bind source, pseudo name
Dir string // Directory name, bind target (including file)
Type string // File system type
Options []string
DumpFrequency int
CheckPassNumber int
}
func equalStrings(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if a[i] != b[i] {
return false
}
}
return true
}
// Equal checks if one entry is equal to another
func (e *MountEntry) Equal(o *MountEntry) bool {
return (e.Name == o.Name && e.Dir == o.Dir && e.Type == o.Type &&
equalStrings(e.Options, o.Options) && e.DumpFrequency == o.DumpFrequency &&
e.CheckPassNumber == o.CheckPassNumber)
}
// escape replaces whitespace characters so that getmntent can parse it correctly.
var escape = strings.NewReplacer(
" ", `\040`,
"\t", `\011`,
"\n", `\012`,
"\\", `\134`,
).Replace
// unescape replaces escape sequences used by setmnt with whitespace characters.
var unescape = strings.NewReplacer(
`\040`, " ",
`\011`, "\t",
`\012`, "\n",
`\134`, "\\",
).Replace
// Escape returns the given path with space, tab, newline and forward slash escaped.
func Escape(path string) string {
return escape(path)
}
// Unescape returns the given path with space, tab, newline and forward slash unescaped.
func Unescape(path string) string {
return unescape(path)
}
// ReplaceMountEntryOption replaces the first mount entry option that has
// the same prefix as the given option with the given option
func ReplaceMountEntryOption(entry *MountEntry, option string) {
if entry == nil {
return
}
kv := strings.SplitN(option, "=", 2)
if len(kv) < 2 {
return
}
if kv[1] == "" {
return
}
prefix := kv[0] + "="
for i, opt := range entry.Options {
if strings.HasPrefix(opt, prefix) {
entry.Options[i] = option
return
}
}
}
func (e MountEntry) String() string {
// Name represents name of the device in a mount entry.
name := "none"
if e.Name != "" {
name = escape(e.Name)
}
// Dir represents mount directory in a mount entry.
dir := "none"
if e.Dir != "" {
dir = escape(e.Dir)
}
// Type represents file system type in a mount entry.
fsType := "none"
if e.Type != "" {
fsType = escape(e.Type)
}
// Options represents mount options in a mount entry.
options := "defaults"
if len(e.Options) != 0 {
options = escape(strings.Join(e.Options, ","))
}
return fmt.Sprintf("%s %s %s %s %d %d",
name, dir, fsType, options, e.DumpFrequency, e.CheckPassNumber)
}
// OptStr returns the value part of a key=value mount option.
// The name of the option must not contain the trailing "=" character.
func (e *MountEntry) OptStr(name string) (string, bool) {
prefix := name + "="
for _, opt := range e.Options {
if strings.HasPrefix(opt, prefix) {
kv := strings.SplitN(opt, "=", 2)
return kv[1], true
}
}
return "", false
}
// OptBool returns true if a given mount option is present.
func (e *MountEntry) OptBool(name string) bool {
for _, opt := range e.Options {
if opt == name {
return true
}
}
return false
}
var (
validModeRe = regexp.MustCompile("^0[0-7]{3}$")
validUserGroupRe = regexp.MustCompile("(^[0-9]+$)")
)
// XSnapdMode returns the file mode associated with x-snapd.mode mount option.
// If the mode is not specified explicitly then a default mode of 0755 is assumed.
func (e *MountEntry) XSnapdMode() (os.FileMode, error) {
if opt, ok := e.OptStr("x-snapd.mode"); ok {
if !validModeRe.MatchString(opt) {
return 0, fmt.Errorf("cannot parse octal file mode from %q", opt)
}
var mode os.FileMode
n, err := fmt.Sscanf(opt, "%o", &mode)
if err != nil || n != 1 {
return 0, fmt.Errorf("cannot parse octal file mode from %q", opt)
}
return mode, nil
}
return 0755, nil
}
// XSnapdUID returns the user associated with x-snapd-user mount option. If
// the mode is not specified explicitly then a default "root" use is
// returned.
func (e *MountEntry) XSnapdUID() (uid uint64, err error) {
if opt, ok := e.OptStr("x-snapd.uid"); ok {
if !validUserGroupRe.MatchString(opt) {
return math.MaxUint64, fmt.Errorf("cannot parse user name %q", opt)
}
// Try to parse a numeric ID first.
if n, err := fmt.Sscanf(opt, "%d", &uid); n == 1 && err == nil {
return uid, nil
}
return uid, nil
}
return 0, nil
}
// XSnapdGID returns the user associated with x-snapd-user mount option. If
// the mode is not specified explicitly then a default "root" use is
// returned.
func (e *MountEntry) XSnapdGID() (gid uint64, err error) {
if opt, ok := e.OptStr("x-snapd.gid"); ok {
if !validUserGroupRe.MatchString(opt) {
return math.MaxUint64, fmt.Errorf("cannot parse group name %q", opt)
}
// Try to parse a numeric ID first.
if n, err := fmt.Sscanf(opt, "%d", &gid); n == 1 && err == nil {
return gid, nil
}
return gid, nil
}
return 0, nil
}
// XSnapdEntryID returns the identifier of a given mount entry.
//
// Identifiers are kept in the x-snapd.id mount option. The value is a string
// that identifies a mount entry and is stable across invocations of snapd. In
// absence of that identifier the entry mount point is returned.
func (e *MountEntry) XSnapdEntryID() string {
if val, ok := e.OptStr("x-snapd.id"); ok {
return val
}
return e.Dir
}
// XSnapdNeededBy the identifier of an entry which needs this entry to function.
//
// The "needed by" identifiers are kept in the x-snapd.needed-by mount option.
// The value is a string that identifies another mount entry which, in order to
// be feasible, has spawned one or more additional support entries. Each such
// entry contains the needed-by attribute.
func (e *MountEntry) XSnapdNeededBy() string {
val, _ := e.OptStr("x-snapd.needed-by")
return val
}
// XSnapdOrigin returns the origin of a given mount entry.
//
// Currently only "layout" entries are identified with a unique origin string.
func (e *MountEntry) XSnapdOrigin() string {
val, _ := e.OptStr("x-snapd.origin")
return val
}
// XSnapdSynthetic returns true of a given mount entry is synthetic.
//
// Synthetic mount entries are created by snap-update-ns itself, separately
// from what snapd instructed. Such entries are needed to make other things
// possible. They are identified by having the "x-snapd.synthetic" mount
// option.
func (e *MountEntry) XSnapdSynthetic() bool {
return e.OptBool("x-snapd.synthetic")
}
// XSnapdKind returns the kind of a given mount entry.
//
// There are four kinds of mount entries today: one for directories, one for
// files, one for symlinks and one for ensuring directories exist. The values are
// "", "file", "symlink" and "ensure-dir respectively.
//
// Directories use the empty string (in fact they don't need the option at
// all) as this was the default and is retained for backwards compatibility.
//
// An "ensure-dir" mount does not result in actual mounting. It is an instruction
// to create missing directories within a target directory path.
func (e *MountEntry) XSnapdKind() string {
val, _ := e.OptStr("x-snapd.kind")
return val
}
// XSnapdDetach returns true if a mount entry should be detached rather than unmounted.
//
// Whenever we create a recursive bind mount we don't want to just unmount it
// as it may have replicated additional mount entries. For simplicity and
// race-free behavior we just detach such mount entries and let the kernel do
// the rest.
func (e *MountEntry) XSnapdDetach() bool {
return e.OptBool("x-snapd.detach")
}
// XSnapdSymlink returns the target for a symlink mount entry.
//
// For non-symlinks an empty string is returned.
func (e *MountEntry) XSnapdSymlink() string {
val, _ := e.OptStr("x-snapd.symlink")
return val
}
// XSnapdIgnoreMissing returns true if a mount entry should be ignored
// if the source or target are missing.
//
// By default, snap-update-ns will try to create missing source and
// target paths when processing a mount entry. In some cases, this
// behaviour is not desired and it would be better to ignore the mount
// entry when the source or target are missing.
func (e *MountEntry) XSnapdIgnoreMissing() bool {
return e.OptBool("x-snapd.ignore-missing")
}
// XSnapdMustExistDir returns the path that must exist as prequisite
// to a mount operation.
func (e *MountEntry) XSnapdMustExistDir() string {
val, _ := e.OptStr("x-snapd.must-exist-dir")
return val
}
// XSnapdNeededBy returns the string "x-snapd.needed-by=..." with the given path appended.
func XSnapdNeededBy(path string) string {
return fmt.Sprintf("x-snapd.needed-by=%s", path)
}
// XSnapdSynthetic returns the string "x-snapd.synthetic".
func XSnapdSynthetic() string {
return "x-snapd.synthetic"
}
// XSnapdDetach returns the string "x-snapd.detach".
func XSnapdDetach() string {
return "x-snapd.detach"
}
// XSnapdKindSymlink returns the string "x-snapd.kind=symlink".
func XSnapdKindSymlink() string {
return "x-snapd.kind=symlink"
}
// XSnapdKindFile returns the string "x-snapd.kind=file".
func XSnapdKindFile() string {
return "x-snapd.kind=file"
}
// XSnapdKindEnsureDir returns the string "x-snapd.kind=ensure-dir".
func XSnapdKindEnsureDir() string {
return "x-snapd.kind=ensure-dir"
}
// XSnapdOriginLayout returns the string "x-snapd.origin=layout"
func XSnapdOriginLayout() string {
return "x-snapd.origin=layout"
}
// XSnapdOriginOvername returns the string "x-snapd.origin=overname"
func XSnapdOriginOvername() string {
return "x-snapd.origin=overname"
}
// XSnapdUser returns the string "x-snapd.user=%d".
func XSnapdUser(uid uint32) string {
return fmt.Sprintf("x-snapd.user=%d", uid)
}
// XSnapdGroup returns the string "x-snapd.group=%d".
func XSnapdGroup(gid uint32) string {
return fmt.Sprintf("x-snapd.group=%d", gid)
}
// XSnapdMode returns the string "x-snapd.mode=%#o".
func XSnapdMode(mode uint32) string {
return fmt.Sprintf("x-snapd.mode=%#o", mode)
}
// XSnapdSymlink returns the string "x-snapd.symlink=%s".
func XSnapdSymlink(oldname string) string {
return fmt.Sprintf("x-snapd.symlink=%s", oldname)
}
// XSnapdMustExistDir returns the string "x-snapd.must-exist-dir=%s".
func XSnapdMustExistDir(path string) string {
return fmt.Sprintf("x-snapd.must-exist-dir=%s", path)
}
// XSnapdIgnoreMissing returns the string "x-snapd.ignore-missing".
func XSnapdIgnoreMissing() string {
return "x-snapd.ignore-missing"
}
|