File: main.go

package info (click to toggle)
snapd 2.73-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 81,460 kB
  • sloc: sh: 16,736; ansic: 16,652; python: 11,215; makefile: 1,966; exp: 190; awk: 58; xml: 22
file content (145 lines) | stat: -rw-r--r-- 4,753 bytes parent folder | download
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
// -*- 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 main

import (
	"errors"
	"fmt"
	"io"
	"io/fs"
	"os"
	"path/filepath"
	"syscall"

	"github.com/jessevdk/go-flags"

	"github.com/snapcore/snapd/dirs"
	"github.com/snapcore/snapd/logger"
)

var opts struct {
	FromSnapConfine bool `long:"from-snap-confine"`
	UserMounts      bool `long:"user-mounts"`
	UserID          int  `short:"u"`
	Positionals     struct {
		SnapName string `positional-arg-name:"SNAP_NAME" required:"yes"`
	} `positional-args:"true"`
}

// IMPORTANT: all the code in main() until bootstrap is finished may be run
// with elevated privileges when invoking snap-update-ns from snap-confine
// which grants additional capabilities.

func main() {
	logger.SimpleSetup(nil)
	if err := run(); err != nil {
		fmt.Printf("cannot update snap namespace: %s\n", err)
		os.Exit(1)
	}
	// END IMPORTANT
}

func parseArgs(args []string) error {
	parser := flags.NewParser(&opts, flags.HelpFlag|flags.PassDoubleDash|flags.PassAfterNonOption)
	_, err := parser.ParseArgs(args)
	return err
}

// IMPORTANT: all the code in run() until BootStrapError() is finished may
// be run with elevated privileges when invoking snap-update-ns from
// the setuid snap-confine.

func run() error {
	// There is some C code that runs before main() is started.
	// That code always runs and sets an error condition if it fails.
	// Here we just check for the error.
	if err := BootstrapError(); err != nil {
		// If there is no mount namespace to transition to let's just quit
		// instantly without any errors as there is nothing to do anymore.
		if err == ErrNoNamespace {
			logger.Debugf("no preserved mount namespace, nothing to update")
			return nil
		}
		return err
	}
	// END IMPORTANT

	if err := parseArgs(os.Args[1:]); err != nil {
		return err
	}

	setupOptInLogging(opts.Positionals.SnapName, opts.UserMounts)
	logger.Debugf("snap-update-ns invoked snap:%s, fromSnapConfine:%v, userMounts:%v",
		opts.Positionals.SnapName, opts.FromSnapConfine, opts.UserMounts)

	// Explicitly set the umask to 0 to prevent permission bits
	// being masked out when creating files and directories.
	//
	// While snap-confine already does this for us, we inherit
	// snapd's umask when it invokes us.
	syscall.Umask(0)

	var upCtx MountProfileUpdateContext
	if opts.UserMounts {
		userUpCtx, err := NewUserProfileUpdateContext(opts.Positionals.SnapName, opts.FromSnapConfine, os.Getuid())
		if err != nil {
			return fmt.Errorf("cannot create user profile update context: %v", err)
		}
		upCtx = userUpCtx
	} else {
		upCtx = NewSystemProfileUpdateContext(opts.Positionals.SnapName, opts.FromSnapConfine)
	}
	return executeMountProfileUpdate(upCtx)
}

// setupOptInLogging configures the logger to log to an existing file.
//
// Developers or users assisting in a debug session may be asked to touch empty
// files at /run/snapd/ns/snap.$SNAP_NAME.log and
// /run/snapd/ns/snap.$SNAP_NAME.user.$UID.log.
//
// Presence of either file activates verbose debug logging of mount namespace
// operations of the specific snap, and snap-uid pair.
//
// Nothing in snapd creates or removes those files. The content may be attached
// to bug reports to be investigated by snapd developers.
func setupOptInLogging(snapName string, userMounts bool) {
	var path string
	if userMounts {
		path = filepath.Join(dirs.SnapRunNsDir, fmt.Sprintf("snap.%s.user.%d.log", snapName, os.Getuid()))
	} else {
		path = filepath.Join(dirs.SnapRunNsDir, fmt.Sprintf("snap.%s.log", snapName))
	}

	// NOTE: This file is never closed.
	f, err := os.OpenFile(path, os.O_WRONLY, 0)
	if err != nil {
		if !errors.Is(err, fs.ErrNotExist) {
			logger.Debugf("Cannot open snap-update-ns log file: %v", err)
		}
		return
	}

	// Write logs to both os.Stderr and f. Due to how we use LoggerOptions, and
	// the limited nature of the logger, os.Stderr will see all debug logs even
	// if that setting is not enabled.  This could be addressed with slog-based
	// logger that uses a tee-like handler with distinct levels.
	logger.SetLogger(logger.New(io.MultiWriter(os.Stderr, f), 0, &logger.LoggerOptions{ForceDebug: true}))
}