From d097436c1cd4846fdfcef39aed83e5de3c6a61b9 Mon Sep 17 00:00:00 2001 From: Miguel Pires Date: Mon, 9 Jan 2023 14:39:58 +0000 Subject: [PATCH] many: fix formatting w/ gofmt 1.19 Go 1.19 includes some changes to gofmt which intend to make lists and heading clearer when rendered (https://go.dev/doc/go1.19). This commit is the result of running the new gofmt and manually fixing some of it. This was necessary because the new gofmt assumed lines beginning w/ tabs to start lists or examples. While this is often true in our codebase, we occasionally also use tabs to indent the lines after a TODO or FIXME prefix or in yaml (e.g., excerpts of a snap.yaml). This meant that a lot of the reformatted comments were broken and had to be fixed manually. Signed-off-by: Miguel Pires --- aspects/aspects.go | 12 +- asserts/asserts.go | 27 +++-- asserts/internal/grouping.go | 14 +-- asserts/model.go | 6 +- asserts/pool.go | 30 ++--- boot/boot.go | 30 ++--- boot/makebootable.go | 8 +- bootloader/bootloader.go | 3 +- bootloader/lkenv/lkenv_v1.go | 24 ++-- bootloader/piboot.go | 23 ++-- bootloader/ubootenv/env.go | 4 +- client/snapctl.go | 2 +- cmd/snap-bootstrap/cmd_initramfs_mounts.go | 17 +-- cmd/snap-recovery-chooser/main.go | 10 +- cmd/snap-seccomp/main_test.go | 20 ++-- cmd/snap-update-ns/trespassing.go | 10 +- cmd/snap-update-ns/utils.go | 10 +- cmd/snap/cmd_booted.go | 7 +- cmd/snap/cmd_debug_timings.go | 10 +- cmd/snap/cmd_first_boot.go | 7 +- cmd/snap/cmd_get.go | 8 +- cmd/snap/cmd_keys_test.go | 4 +- cmd/snap/color.go | 24 ++-- daemon/api_apps.go | 22 ++-- daemon/api_systems.go | 5 +- dbusutil/dbusutil.go | 6 +- gadget/device/encrypt.go | 2 +- gadget/gadget.go | 10 +- gadget/layout.go | 4 +- gadget/mountedfilesystem.go | 17 +-- gadget/update.go | 31 +++-- image/preseed/preseed.go | 3 +- interfaces/apparmor/apparmor.go | 6 +- interfaces/apparmor/spec.go | 31 ++--- interfaces/apparmor/template.go | 10 +- interfaces/builtin/appstream_metadata.go | 3 +- interfaces/builtin/dm_crypt.go | 4 +- interfaces/builtin/mount_control.go | 11 +- interfaces/builtin/netlink_driver.go | 10 +- interfaces/builtin/network_control.go | 12 +- interfaces/builtin/posix_mq.go | 9 +- interfaces/builtin/serial_port.go | 20 ++-- interfaces/builtin/ubuntu_download_manager.go | 4 +- interfaces/builtin/utils.go | 11 +- interfaces/mount/backend.go | 6 +- interfaces/mount/spec.go | 2 +- interfaces/policy/policy_test.go | 61 +++++----- interfaces/seccomp/backend.go | 10 +- interfaces/seccomp/template.go | 17 ++- interfaces/system_key.go | 31 ++--- interfaces/udev/udev.go | 11 +- kernel/fde/fde.go | 5 +- osutil/io.go | 2 +- osutil/mkdirallchown.go | 5 +- osutil/mountentry.go | 16 +-- osutil/strace/timing_test.go | 3 +- overlord/devicestate/devicemgr.go | 10 +- overlord/devicestate/devicestate.go | 20 ++-- overlord/ifacestate/ifacestate.go | 1 - overlord/patch/patch4.go | 6 +- overlord/patch/patch6.go | 2 +- overlord/patch/patch6_1.go | 2 +- overlord/patch/patch6_2.go | 4 +- overlord/patch/patch6_3.go | 2 +- overlord/snapstate/backend_test.go | 5 +- overlord/state/change.go | 7 +- overlord/state/change_test.go | 13 +-- overlord/state/state.go | 14 +-- overlord/state/taskrunner_test.go | 14 +-- polkit/pid_start_time.go | 3 +- progress/progress.go | 10 +- secboot/secboot.go | 2 +- seed/seedwriter/writer.go | 106 +++++++++--------- snap/channel/channel.go | 17 +-- snap/container.go | 12 +- snap/epoch.go | 10 +- snap/info.go | 12 +- snap/info_snap_yaml.go | 21 ++-- snap/naming/validate.go | 23 ++-- snap/snaptest/snaptest.go | 2 +- snap/squashfs/squashfs.go | 7 +- snap/system_usernames.go | 80 ++++++------- spdx/licenses.go | 1 + store/cache.go | 14 +-- store/store.go | 40 +++---- store/store_test.go | 84 +++++++------- store/userinfo_test.go | 5 +- strutil/pathiter.go | 10 +- strutil/shlex/shlex.go | 19 ++-- strutil/version.go | 7 +- syscheck/squashfs.go | 30 +++-- systemd/escape.go | 6 +- systemd/systemd.go | 14 +-- tests/lib/gendeveloper1/main.go | 24 ++-- testutil/exec.go | 9 +- testutil/intcheckers.go | 18 ++- timeutil/schedule.go | 30 ++--- timings/timings.go | 32 +++--- usersession/userd/launcher.go | 14 +-- .../userd/privileged_desktop_launcher.go | 10 +- wrappers/desktop.go | 18 +-- 101 files changed, 775 insertions(+), 725 deletions(-) diff --git a/aspects/aspects.go b/aspects/aspects.go index 5d2a6c4fc71..db49c3ea579 100644 --- a/aspects/aspects.go +++ b/aspects/aspects.go @@ -169,8 +169,8 @@ func newAspect(dir *Directory, name string, aspectPatterns []map[string]string) } // validateNamePathPair checks that: -// * names and paths are composed of valid subkeys (see: validateAspectString) -// * all placeholders in a name are in the path and vice-versa +// - names and paths are composed of valid subkeys (see: validateAspectString) +// - all placeholders in a name are in the path and vice-versa func validateNamePathPair(name, path string) error { if err := validateAspectDottedPath(name); err != nil { return fmt.Errorf("invalid access name %q: %w", name, err) @@ -202,10 +202,10 @@ var ( ) // validateAspectDottedPath validates that names/paths in an aspect definition are: -// * composed of non-empty, dot-separated subkeys with optional placeholders ("foo.{bar}") -// * non-placeholder subkeys are made up of lowercase alphanumeric ASCII characters, -// optionally with dashes between alphanumeric characters (e.g., "a-b-c") -// * placeholder subkeys are composed of non-placeholder subkeys wrapped in curly brackets +// - composed of non-empty, dot-separated subkeys with optional placeholders ("foo.{bar}") +// - non-placeholder subkeys are made up of lowercase alphanumeric ASCII characters, +// optionally with dashes between alphanumeric characters (e.g., "a-b-c") +// - placeholder subkeys are composed of non-placeholder subkeys wrapped in curly brackets func validateAspectDottedPath(path string) (err error) { subkeys := strings.Split(path, ".") diff --git a/asserts/asserts.go b/asserts/asserts.go index 834ac82f5b1..19c9535e2cd 100644 --- a/asserts/asserts.go +++ b/asserts/asserts.go @@ -665,26 +665,26 @@ var _ Assertion = (*assertionBase)(nil) // // The expected serialisation format looks like: // -// HEADER ("\n\n" BODY?)? "\n\n" SIGNATURE +// HEADER ("\n\n" BODY?)? "\n\n" SIGNATURE // // where: // -// HEADER is a set of header entries separated by "\n" -// BODY can be arbitrary text, -// SIGNATURE is the signature +// HEADER is a set of header entries separated by "\n" +// BODY can be arbitrary text, +// SIGNATURE is the signature // // Both BODY and HEADER must be UTF8. // // A header entry for a single line value (no '\n' in it) looks like: // -// NAME ": " SIMPLEVALUE +// NAME ": " SIMPLEVALUE // // The format supports multiline text values (with '\n's in them) and // lists or maps, possibly nested, with string scalars in them. // // For those a header entry looks like: // -// NAME ":\n" MULTI(baseindent) +// NAME ":\n" MULTI(baseindent) // // where MULTI can be // @@ -692,11 +692,11 @@ var _ Assertion = (*assertionBase)(nil) // // * entries of a list each of the form: // -// " "*baseindent " -" ( " " SIMPLEVALUE | "\n" MULTI ) +// " "*baseindent " -" ( " " SIMPLEVALUE | "\n" MULTI ) // // * entries of map each of the form: // -// " "*baseindent " " NAME ":" ( " " SIMPLEVALUE | "\n" MULTI ) +// " "*baseindent " " NAME ":" ( " " SIMPLEVALUE | "\n" MULTI ) // // baseindent starts at 0 and then grows with nesting matching the // previous level introduction (e.g. the " "*baseindent " -" bit) @@ -704,8 +704,8 @@ var _ Assertion = (*assertionBase)(nil) // // In general the following headers are mandatory: // -// type -// authority-id (except for on the wire/self-signed assertions like serial-request) +// type +// authority-id (except for on the wire/self-signed assertions like serial-request) // // Further for a given assertion type all the primary key headers // must be non empty and must not contain '/'. @@ -713,12 +713,11 @@ var _ Assertion = (*assertionBase)(nil) // The following headers expect string representing integer values and // if omitted otherwise are assumed to be 0: // -// revision (a positive int) -// body-length (expected to be equal to the length of BODY) -// format (a positive int for the format iteration of the type used) +// revision (a positive int) +// body-length (expected to be equal to the length of BODY) +// format (a positive int for the format iteration of the type used) // // Times are expected to be in the RFC3339 format: "2006-01-02T15:04:05Z07:00". -// func Decode(serializedAssertion []byte) (Assertion, error) { // copy to get an independent backstorage that can't be mutated later assertionSnapshot := make([]byte, len(serializedAssertion)) diff --git a/asserts/internal/grouping.go b/asserts/internal/grouping.go index 06ba7998d75..ad66ea53d84 100644 --- a/asserts/internal/grouping.go +++ b/asserts/internal/grouping.go @@ -31,9 +31,9 @@ import ( // Labels are implemented as subsets of integers from 0 // up to an excluded maximum, where the integers represent the groups. // Assumptions: -// - most labels are for one group or very few -// - a few labels are sparse with more groups in them -// - very few comprise the universe of all groups +// - most labels are for one group or very few +// - a few labels are sparse with more groups in them +// - very few comprise the universe of all groups type Groupings struct { n uint maxGroup uint16 @@ -80,10 +80,10 @@ func (g Grouping) Copy() Grouping { } // search locates group among the sorted Grouping elements, it returns: -// * true if found -// * false if not found -// * the index at which group should be inserted to keep the -// elements sorted if not found and the bit-set representation is not in use +// - true if found +// - false if not found +// - the index at which group should be inserted to keep the +// elements sorted if not found and the bit-set representation is not in use func (gr *Groupings) search(g *Grouping, group uint16) (found bool, j uint16) { if g.size > gr.bitsetThreshold { return bitsetContains(g, group), 0 diff --git a/asserts/model.go b/asserts/model.go index 6a77cb4f967..2241e9e63ba 100644 --- a/asserts/model.go +++ b/asserts/model.go @@ -380,9 +380,9 @@ var validStorageSafeties = []string{string(StorageSafetyEncrypted), string(Stora var validModelGrades = []string{string(ModelSecured), string(ModelSigned), string(ModelDangerous)} // gradeToCode encodes grades into 32 bits, trying to be slightly future-proof: -// * lower 16 bits are reserved -// * in the higher bits use the sequence 1, 8, 16 to have some space -// to possibly add new grades in between +// - lower 16 bits are reserved +// - in the higher bits use the sequence 1, 8, 16 to have some space +// to possibly add new grades in between var gradeToCode = map[ModelGrade]uint32{ ModelGradeUnset: 0, ModelDangerous: 0x10000, diff --git a/asserts/pool.go b/asserts/pool.go index d1afed032ca..8b1ba29f6a9 100644 --- a/asserts/pool.go +++ b/asserts/pool.go @@ -51,16 +51,15 @@ type Grouping string // any Add or AddBatch AddUnresolved/AddToUpdate can also be used // again. // -// V -// | -// /-> AddUnresolved, AddToUpdate -// | | -// | V -// |------> ToResolve -> empty? done -// | | -// | V -// \ __________ Add -// +// V +// | +// /-> AddUnresolved, AddToUpdate +// | | +// | V +// |------> ToResolve -> empty? done +// | | +// | V +// \ __________ Add // // If errors prevent from fulfilling assertions from a ToResolve, // AddError and AddGroupingError can be used to report the errors so @@ -739,11 +738,12 @@ var ( // unresolvedBookkeeping processes any left over unresolved assertions // since the last ToResolve invocation and intervening calls to Add/AddBatch, -// * they were either marked as in error which will be propagated -// to all groups requiring them -// * simply unresolved, which will be propagated to groups requiring them -// as ErrUnresolved -// * unchanged (update case) +// - they were either marked as in error which will be propagated +// to all groups requiring them +// - simply unresolved, which will be propagated to groups requiring them +// as ErrUnresolved +// - unchanged (update case) +// // unresolvedBookkeeping will also promote any recorded prerequisites // into actively unresolved, as long as not all the groups requiring them // are in error. diff --git a/boot/boot.go b/boot/boot.go index 41da0f2f98f..e9c748749a6 100644 --- a/boot/boot.go +++ b/boot/boot.go @@ -337,21 +337,21 @@ type bootStateUpdate interface { // target for rollback. // // The states that a boot goes through for UC16/18 are the following: -// - By default snap_mode is "" in which case the bootloader loads -// two squashfs'es denoted by variables snap_core and snap_kernel. -// - On a refresh of core/kernel snapd will set snap_mode=try and -// will also set snap_try_{core,kernel} to the core/kernel that -// will be tried next. -// - On reboot the bootloader will inspect the snap_mode and if the -// mode is set to "try" it will set "snap_mode=trying" and then -// try to boot the snap_try_{core,kernel}". -// - On a successful boot snapd resets snap_mode to "" and copies -// snap_try_{core,kernel} to snap_{core,kernel}. The snap_try_* -// values are cleared afterwards. -// - On a failing boot the bootloader will see snap_mode=trying which -// means snapd did not start successfully. In this case the bootloader -// will set snap_mode="" and the system will boot with the known good -// values from snap_{core,kernel} +// - By default snap_mode is "" in which case the bootloader loads +// two squashfs'es denoted by variables snap_core and snap_kernel. +// - On a refresh of core/kernel snapd will set snap_mode=try and +// will also set snap_try_{core,kernel} to the core/kernel that +// will be tried next. +// - On reboot the bootloader will inspect the snap_mode and if the +// mode is set to "try" it will set "snap_mode=trying" and then +// try to boot the snap_try_{core,kernel}". +// - On a successful boot snapd resets snap_mode to "" and copies +// snap_try_{core,kernel} to snap_{core,kernel}. The snap_try_* +// values are cleared afterwards. +// - On a failing boot the bootloader will see snap_mode=trying which +// means snapd did not start successfully. In this case the bootloader +// will set snap_mode="" and the system will boot with the known good +// values from snap_{core,kernel} func MarkBootSuccessful(dev snap.Device) error { const errPrefix = "cannot mark boot successful: %s" diff --git a/boot/makebootable.go b/boot/makebootable.go index e3c5c5678dd..8e4a0c744b5 100644 --- a/boot/makebootable.go +++ b/boot/makebootable.go @@ -92,10 +92,10 @@ func MakeBootablePartition(partDir string, opts *bootloader.Options, bootWith *B // makeBootable16 setups the image filesystem for boot with UC16 // and UC18 models. This entails: -// - installing the bootloader configuration from the gadget -// - creating symlinks for boot snaps from seed to the runtime blob dir -// - setting boot env vars pointing to the revisions of the boot snaps to use -// - extracting kernel assets as needed by the bootloader +// - installing the bootloader configuration from the gadget +// - creating symlinks for boot snaps from seed to the runtime blob dir +// - setting boot env vars pointing to the revisions of the boot snaps to use +// - extracting kernel assets as needed by the bootloader func makeBootable16(model *asserts.Model, rootdir string, bootWith *BootableSet) error { opts := &bootloader.Options{ PrepareImageTime: true, diff --git a/bootloader/bootloader.go b/bootloader/bootloader.go index a9056f89635..0efacc63351 100644 --- a/bootloader/bootloader.go +++ b/bootloader/bootloader.go @@ -329,7 +329,8 @@ var ( // // The rootdir option is useful for image creation operations. It // can also be used to find the recovery bootloader, e.g. on uc20: -// bootloader.Find("/run/mnt/ubuntu-seed") +// +// bootloader.Find("/run/mnt/ubuntu-seed") func Find(rootdir string, opts *Options) (Bootloader, error) { if err := opts.validate(); err != nil { return nil, err diff --git a/bootloader/lkenv/lkenv_v1.go b/bootloader/lkenv/lkenv_v1.go index d24f154ef4a..931e12d5fe5 100644 --- a/bootloader/lkenv/lkenv_v1.go +++ b/bootloader/lkenv/lkenv_v1.go @@ -23,19 +23,17 @@ import ( "fmt" ) -/** - * Following structure has to be kept in sync with c structure defined by - * include/lk/snappy-boot_v1.h - * c headerfile is used by bootloader, this ensures sync of the environment - * between snapd and bootloader - - * when this structure needs to be updated, - * new version should be introduced instead together with c header file, - * which is to be adopted by bootloader - * - * !!! Support for old version has to be maintained, as it is not guaranteed - * all existing bootloader would adopt new version! - */ +// Following structure has to be kept in sync with c structure defined by +// include/lk/snappy-boot_v1.h +// c headerfile is used by bootloader, this ensures sync of the environment +// between snapd and bootloader +// +// when this structure needs to be updated, +// new version should be introduced instead together with c header file, +// which is to be adopted by bootloader +// +// !!! Support for old version has to be maintained, as it is not guaranteed +// all existing bootloader would adopt new version! type SnapBootSelect_v1 struct { /* Contains value BOOTSELECT_SIGNATURE defined above */ Signature uint32 diff --git a/bootloader/piboot.go b/bootloader/piboot.go index e31574fa35b..400f82fa2d9 100644 --- a/bootloader/piboot.go +++ b/bootloader/piboot.go @@ -115,17 +115,20 @@ func (p *piboot) Present() (bool, error) { } // Variables stored in ubuntu-seed: -// snapd_recovery_system -// snapd_recovery_mode -// snapd_recovery_kernel +// +// snapd_recovery_system +// snapd_recovery_mode +// snapd_recovery_kernel +// // Variables stored in ubuntu-boot: -// kernel_status -// snap_kernel -// snap_try_kernel -// snapd_extra_cmdline_args -// snapd_full_cmdline_args -// recovery_system_status -// try_recovery_system +// +// kernel_status +// snap_kernel +// snap_try_kernel +// snapd_extra_cmdline_args +// snapd_full_cmdline_args +// recovery_system_status +// try_recovery_system func (p *piboot) SetBootVars(values map[string]string) error { env, err := ubootenv.OpenWithFlags(p.envFile(), ubootenv.OpenBestEffort) if err != nil { diff --git a/bootloader/ubootenv/env.go b/bootloader/ubootenv/env.go index 16c7874933d..ec541fe4af8 100644 --- a/bootloader/ubootenv/env.go +++ b/bootloader/ubootenv/env.go @@ -33,8 +33,8 @@ import ( "strings" ) -// FIXME: add config option for that so that the user can select if -// he/she wants env with or without flags +// 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 diff --git a/client/snapctl.go b/client/snapctl.go index 2d1a8cdb448..d0a8f5a172b 100644 --- a/client/snapctl.go +++ b/client/snapctl.go @@ -50,7 +50,7 @@ type SnapCtlOptions struct { // SnapCtlPostData is the data posted to the daemon /v2/snapctl endpoint // TODO: this can be removed again once we no longer need to pass stdin data -// but instead use a real stdin stream +// but instead use a real stdin stream type SnapCtlPostData struct { SnapCtlOptions diff --git a/cmd/snap-bootstrap/cmd_initramfs_mounts.go b/cmd/snap-bootstrap/cmd_initramfs_mounts.go index 6cd25132213..1787f336b5a 100644 --- a/cmd/snap-bootstrap/cmd_initramfs_mounts.go +++ b/cmd/snap-bootstrap/cmd_initramfs_mounts.go @@ -253,7 +253,7 @@ func copyNetworkConfig(src, dst string) error { // copyUbuntuDataMisc copies miscellaneous other files from the run mode system // to the recover system such as: -// - timesync clock to keep the same time setting in recover as in run mode +// - timesync clock to keep the same time setting in recover as in run mode func copyUbuntuDataMisc(src, dst string) error { for _, globEx := range []string{ // systemd's timesync clock file so that the time in recover mode moves @@ -273,9 +273,10 @@ func copyUbuntuDataMisc(src, dst string) error { } // copyUbuntuDataAuth copies the authentication files like -// - extrausers passwd,shadow etc -// - sshd host configuration -// - user .ssh dir +// - extrausers passwd,shadow etc +// - sshd host configuration +// - user .ssh dir +// // to the target directory. This is used to copy the authentication // data from a real uc20 ubuntu-data partition into a ephemeral one. func copyUbuntuDataAuth(src, dst string) error { @@ -825,10 +826,10 @@ func (m *recoverModeStateMachine) trustData() bool { // mountBoot is the first state to execute in the state machine, it can // transition to the following states: -// - if ubuntu-boot is mounted successfully, execute unlockDataRunKey -// - if ubuntu-boot can't be mounted, execute unlockDataFallbackKey -// - if we mounted the wrong ubuntu-boot (or otherwise can't verify which one we -// mounted), return fatal error +// - if ubuntu-boot is mounted successfully, execute unlockDataRunKey +// - if ubuntu-boot can't be mounted, execute unlockDataFallbackKey +// - if we mounted the wrong ubuntu-boot (or otherwise can't verify which one we +// mounted), return fatal error func (m *recoverModeStateMachine) mountBoot() (stateFunc, error) { part := m.degradedState.partition("ubuntu-boot") // use the disk we mounted ubuntu-seed from as a reference to find diff --git a/cmd/snap-recovery-chooser/main.go b/cmd/snap-recovery-chooser/main.go index 81a72e02276..2055d57483b 100644 --- a/cmd/snap-recovery-chooser/main.go +++ b/cmd/snap-recovery-chooser/main.go @@ -27,14 +27,14 @@ // // The JSON object carrying the list of systems is the client.ChooserSystems // structure. The response is defined as follows: -// { -// "label": "", "", } +// +// {"", "", } // // Eg to test that the rule 'read >=2' is allowed with 'read(2)' and 'read(3)' // and denied with 'read(1)' and 'read(0)', add the following tests: -// {"read >=2", "read;native;2", Allow}, -// {"read >=2", "read;native;3", Allow}, -// {"read >=2", "read;native;1", main.SeccompRetKill}, -// {"read >=2", "read;native;0", main.SeccompRetKill}, +// +// {"read >=2", "read;native;2", Allow}, +// {"read >=2", "read;native;3", Allow}, +// {"read >=2", "read;native;1", main.SeccompRetKill}, +// {"read >=2", "read;native;0", main.SeccompRetKill}, func (s *snapSeccompSuite) TestCompile(c *C) { for _, t := range []struct { diff --git a/cmd/snap-update-ns/trespassing.go b/cmd/snap-update-ns/trespassing.go index c7b9b4faafa..bdccf9ddd1f 100644 --- a/cmd/snap-update-ns/trespassing.go +++ b/cmd/snap-update-ns/trespassing.go @@ -127,11 +127,11 @@ func (as *Assumptions) AddChange(change *Change) { // canWriteToDirectory returns true if writing to a given directory is allowed. // // Writing is allowed in one of thee cases: -// 1) The directory is in one of the explicitly permitted locations. -// This is the strongest permission as it explicitly allows writing to -// places that may show up on the host, one of the examples being $SNAP_DATA. -// 2) The directory is on a read-only filesystem. -// 3) The directory is on a tmpfs created by snapd. +// 1. The directory is in one of the explicitly permitted locations. +// This is the strongest permission as it explicitly allows writing to +// places that may show up on the host, one of the examples being $SNAP_DATA. +// 2. The directory is on a read-only filesystem. +// 3. The directory is on a tmpfs created by snapd. func (as *Assumptions) canWriteToDirectory(dirFd int, dirName string) (bool, error) { if !as.isRestricted(dirName) { return true, nil diff --git a/cmd/snap-update-ns/utils.go b/cmd/snap-update-ns/utils.go index dfa93f12e09..008981d885d 100644 --- a/cmd/snap-update-ns/utils.go +++ b/cmd/snap-update-ns/utils.go @@ -570,11 +570,11 @@ type FatalError struct { // Certain assumptions are made about the plan, it must closely resemble that // created by planWritableMimic, in particular the sequence must look like this: // -// - bind a directory aside into safekeeping location -// - cover the original with tmpfs -// - bind mount something from safekeeping location to an empty file or -// directory in the tmpfs; this step can repeat any number of times -// - unbind the safekeeping location +// - bind a directory aside into safekeeping location +// - cover the original with tmpfs +// - bind mount something from safekeeping location to an empty file or +// directory in the tmpfs; this step can repeat any number of times +// - unbind the safekeeping location // // Apart from merely executing the plan a fake plan is returned for undo. The // undo plan skips the following elements as compared to the original plan: diff --git a/cmd/snap/cmd_booted.go b/cmd/snap/cmd_booted.go index 5501cb75826..912d1e8b4ac 100644 --- a/cmd/snap/cmd_booted.go +++ b/cmd/snap/cmd_booted.go @@ -37,10 +37,9 @@ func init() { cmd.hidden = true } -// WARNING: do not remove this command, older systems may still have -// a systemd snapd.firstboot.service job in /etc/systemd/system -// that we did not cleanup. so we need this sample command or -// those units will start failing. +// WARNING: do not remove this command, older systems may still have a systemd +// snapd.firstboot.service job in /etc/systemd/system that we did not cleanup. +// So we need this sample command or those units will start failing. func (x *cmdBooted) Execute(args []string) error { if len(args) > 0 { return ErrExtraArgs diff --git a/cmd/snap/cmd_debug_timings.go b/cmd/snap/cmd_debug_timings.go index 23a793d7f27..4c014428557 100644 --- a/cmd/snap/cmd_debug_timings.go +++ b/cmd/snap/cmd_debug_timings.go @@ -94,11 +94,11 @@ func printTaskTiming(w io.Writer, t *Timing, verbose, doing bool) { } // sortTimingsTasks sorts tasks from changeTimings by lane and ready time with special treatment of lane 0 tasks: -// - tasks from lanes >0 are grouped by lanes and sorted by ready time. -// - tasks from lane 0 are sorted by ready time and inserted before and after other lanes based on the min/max -// ready times of non-zero lanes. -// - tasks from lane 0 with ready time between non-zero lane tasks are not really expected in our system and will -// appear after non-zero lane tasks. +// - tasks from lanes >0 are grouped by lanes and sorted by ready time. +// - tasks from lane 0 are sorted by ready time and inserted before and after other lanes based on the min/max +// ready times of non-zero lanes. +// - tasks from lane 0 with ready time between non-zero lane tasks are not really expected in our system and will +// appear after non-zero lane tasks. func sortTimingsTasks(timings map[string]changeTimings) []string { tasks := make([]string, 0, len(timings)) diff --git a/cmd/snap/cmd_first_boot.go b/cmd/snap/cmd_first_boot.go index 95be8d565f3..8970b7bffee 100644 --- a/cmd/snap/cmd_first_boot.go +++ b/cmd/snap/cmd_first_boot.go @@ -37,10 +37,9 @@ func init() { cmd.hidden = true } -// WARNING: do not remove this command, older systems may still have -// a systemd snapd.firstboot.service job in /etc/systemd/system -// that we did not cleanup. so we need this sample command or -// those units will start failing. +// WARNING: do not remove this command, older systems may still have systemd +// snapd.firstboot.service job in /etc/systemd/system that we did not cleanup. +// so we need this sample command or those units will start failing. func (x *cmdInternalFirstBoot) Execute(args []string) error { if len(args) > 0 { return ErrExtraArgs diff --git a/cmd/snap/cmd_get.go b/cmd/snap/cmd_get.go index 2c5316824fe..e39ed327f2b 100644 --- a/cmd/snap/cmd_get.go +++ b/cmd/snap/cmd_get.go @@ -179,10 +179,10 @@ func (x *cmdGet) outputList(conf map[string]interface{}) error { // outputDefault will be used when no commandline switch to override the // output where used. The output follows the following rules: -// - a single key with a string value is printed directly -// - multiple keys are printed as a list to the terminal (if there is one) -// or as json if there is no terminal -// - the option "typed" is honored +// - a single key with a string value is printed directly +// - multiple keys are printed as a list to the terminal (if there is one) +// or as json if there is no terminal +// - the option "typed" is honored func (x *cmdGet) outputDefault(conf map[string]interface{}, snapName string, confKeys []string) error { if rootRequested(confKeys) && len(conf) == 0 { return fmt.Errorf("snap %q has no configuration", snapName) diff --git a/cmd/snap/cmd_keys_test.go b/cmd/snap/cmd_keys_test.go index 00dab5f6c0e..74a6883f230 100644 --- a/cmd/snap/cmd_keys_test.go +++ b/cmd/snap/cmd_keys_test.go @@ -40,8 +40,8 @@ type SnapKeysSuite struct { } // FIXME: Ideally we would just use gpg2 and remove the gnupg2_test.go file. -// However currently there is LP: #1621839 which prevents us from -// switching to gpg2 fully. Once this is resolved we should switch. +// However currently there is LP: #1621839 which prevents us from switching to +// gpg2 fully. Once this is resolved we should switch. var _ = Suite(&SnapKeysSuite{GnupgCmd: "/usr/bin/gpg"}) var fakePinentryData = []byte(`#!/bin/sh diff --git a/cmd/snap/color.go b/cmd/snap/color.go index 036e87a4c0a..96093e6ff7c 100644 --- a/cmd/snap/color.go +++ b/cmd/snap/color.go @@ -163,14 +163,14 @@ func fillerPublisher(esc *escapes) string { // longPublisher returns a string that'll present the publisher of a snap to the // terminal user: // -// * if the publisher's username and display name match, it's just the display -// name; otherwise, it'll include the username in parentheses +// - if the publisher's username and display name match, it's just the display +// name; otherwise, it'll include the username in parentheses // -// * if the publisher is "starred" it'll include a yellow star; if the -// publisher is "verified", it'll include a green check mark; otherwise, -// it'll include a no-op escape sequence of the same length as the escape -// sequence used to make it colorful (this so that tabwriter gets things -// right). +// - if the publisher is "starred" it'll include a yellow star; if the +// publisher is "verified", it'll include a green check mark; otherwise, +// it'll include a no-op escape sequence of the same length as the escape +// sequence used to make it colorful (this so that tabwriter gets things +// right). func longPublisher(esc *escapes, storeAccount *snap.StoreAccount) string { if storeAccount == nil { return esc.dash + esc.green + esc.end @@ -200,11 +200,11 @@ func longPublisher(esc *escapes, storeAccount *snap.StoreAccount) string { // // * it'll always be just the username // -// * if the publisher is "starred" it'll include a yellow star; if the -// publisher is "verified", it'll include a green check mark; otherwise, -// it'll include a no-op escape sequence of the same length as the escape -// sequence used to make it colorful (this so that tabwriter gets things -// right). +// - if the publisher is "starred" it'll include a yellow star; if the +// publisher is "verified", it'll include a green check mark; otherwise, +// it'll include a no-op escape sequence of the same length as the escape +// sequence used to make it colorful (this so that tabwriter gets things +// right). func shortPublisher(esc *escapes, storeAccount *snap.StoreAccount) string { if storeAccount == nil { return "-" + esc.green + esc.end diff --git a/daemon/api_apps.go b/daemon/api_apps.go index 1063a5c4ee7..ddd050be39a 100644 --- a/daemon/api_apps.go +++ b/daemon/api_apps.go @@ -94,14 +94,15 @@ func (opts appInfoOptions) String() string { // appInfosFor returns a sorted list apps described by names. // -// * If names is empty, returns all apps of the wanted kinds (which -// could be an empty list). -// * An element of names can be a snap name, in which case all apps -// from the snap of the wanted kind are included in the result (and -// it's an error if the snap has no apps of the wanted kind). -// * An element of names can instead be snap.app, in which case that app is -// included in the result (and it's an error if the snap and app don't -// both exist, or if the app is not a wanted kind) +// - If names is empty, returns all apps of the wanted kinds (which +// could be an empty list). +// - An element of names can be a snap name, in which case all apps +// from the snap of the wanted kind are included in the result (and +// it's an error if the snap has no apps of the wanted kind). +// - An element of names can instead be snap.app, in which case that app is +// included in the result (and it's an error if the snap and app don't +// both exist, or if the app is not a wanted kind) +// // On error an appropriate *apiError is returned; a nil *apiError means // no error. // @@ -169,8 +170,9 @@ func appInfosFor(st *state.State, names []string, opts appInfoOptions) ([]*snap. // this differs from snap.SplitSnapApp in the handling of the // snap-only case: -// snap.SplitSnapApp("foo") is ("foo", "foo"), -// splitAppName("foo") is ("foo", ""). +// +// snap.SplitSnapApp("foo") is ("foo", "foo"), +// splitAppName("foo") is ("foo", ""). func splitAppName(s string) (snap, app string) { if idx := strings.IndexByte(s, '.'); idx > -1 { return s[:idx], s[idx+1:] diff --git a/daemon/api_systems.go b/daemon/api_systems.go index 1200d92cf6c..6dc6d15fa9e 100644 --- a/daemon/api_systems.go +++ b/daemon/api_systems.go @@ -203,9 +203,8 @@ func postSystemsAction(c *Command, r *http.Request, user *auth.UserState) Respon } } -// XXX: should deviceManager return more sensible errors here? -// E.g. UnsupportedActionError{systemLabel, mode} -// SystemDoesNotExistError{systemLabel} +// XXX: should deviceManager return more sensible errors here? e.g.: +// UnsupportedActionError{systemLabel, mode}, SystemDoesNotExistError{systemLabel} func handleSystemActionErr(err error, systemLabel string) Response { if os.IsNotExist(err) { return NotFound("requested seed system %q does not exist", systemLabel) diff --git a/dbusutil/dbusutil.go b/dbusutil/dbusutil.go index 5f37854523f..6c70543bf51 100644 --- a/dbusutil/dbusutil.go +++ b/dbusutil/dbusutil.go @@ -56,9 +56,9 @@ func isSessionBusLikelyPresent() bool { // a new dbus-daemon when a bus is not already available. // // The go-dbus package will launch a session bus instance on demand when none -// is present, something we do not want to do. In all contexts where there is a need -// to use the session bus, we expect session bus daemon to have been started and -// managed by the corresponding user session manager. +// is present, something we do not want to do. In all contexts where there is a +// need to use the session bus, we expect session bus daemon to have been started +// and managed by the corresponding user session manager. // // This function is mockable by either MockConnections or // MockOnlySessionBusAvailable. diff --git a/gadget/device/encrypt.go b/gadget/device/encrypt.go index a23f87275fe..86469d69418 100644 --- a/gadget/device/encrypt.go +++ b/gadget/device/encrypt.go @@ -102,7 +102,7 @@ func TpmLockoutAuthUnder(saveDeviceFDEDir string) string { return filepath.Join(saveDeviceFDEDir, "tpm-lockout-auth") } -/// ErrNoSealedKeys error if there are no sealed keys +// ErrNoSealedKeys error if there are no sealed keys var ErrNoSealedKeys = errors.New("no sealed keys") // SealingMethod represents the sealing method diff --git a/gadget/gadget.go b/gadget/gadget.go index 9911bb8a9b8..27455b0d35f 100644 --- a/gadget/gadget.go +++ b/gadget/gadget.go @@ -453,8 +453,8 @@ func AllDiskVolumeDeviceTraits(allLaidOutVols map[string]*LaidOutVolume, optsPer // GadgetConnect describes an interface connection requested by the gadget // between seeded snaps. The syntax is of a mapping like: // -// plug: (|system):plug -// [slot: (|system):slot] +// plug: (|system):plug +// [slot: (|system):slot] // // "system" indicates a system plug or slot. // Fully omitting the slot part indicates a system slot with the same name @@ -1359,8 +1359,10 @@ func KernelCommandLineFromGadget(gadgetDirOrSnapPath string) (cmdline string, fu // According to https://elixir.bootlin.com/linux/latest/source/Documentation/admin-guide/kernel-parameters.txt // the # character can appear as part of a valid kernel command line argument, // specifically in the following argument: -// memmap=nn[KMG]#ss[KMG] -// memmap=100M@2G,100M#3G,1G!1024G +// +// memmap=nn[KMG]#ss[KMG] +// memmap=100M@2G,100M#3G,1G!1024G +// // Thus a lone # or a token starting with # are treated as errors. func parseCommandLineFromGadget(content []byte) (string, error) { s := bufio.NewScanner(bytes.NewBuffer(content)) diff --git a/gadget/layout.go b/gadget/layout.go index b5f1d85e3a8..a49fd1c1af7 100644 --- a/gadget/layout.go +++ b/gadget/layout.go @@ -157,8 +157,8 @@ func (b byStartOffset) Less(i, j int) bool { return b[i].StartOffset < b[j].Star // LaidOutContent describes raw content that has been placed within the // encompassing structure and volume // -// TODO: this can't have "$kernel:" refs at this point, fail in validate -// for bare structures with "$kernel:" refs +// TODO: this can't have "$kernel:" refs at this point, fail in validate for +// bare structures with "$kernel:" refs type LaidOutContent struct { *VolumeContent diff --git a/gadget/mountedfilesystem.go b/gadget/mountedfilesystem.go index 845b609ae7c..49558b2be96 100644 --- a/gadget/mountedfilesystem.go +++ b/gadget/mountedfilesystem.go @@ -138,8 +138,9 @@ func (m *MountedFilesystemWriter) Write(whereDir string, preserve []string) erro // writeDirectory copies the source directory, or its contents under target // location dst. Follows rsync like semantics, that is: -// /foo/ -> /bar - writes contents of foo under /bar -// /foo -> /bar - writes foo and its subtree under /bar +// +// /foo/ -> /bar - writes contents of foo under /bar +// /foo -> /bar - writes foo and its subtree under /bar func (m *MountedFilesystemWriter) writeDirectory(volumeRoot, src, dst string, preserveInDst []string) error { hasDirSourceSlash := strings.HasSuffix(src, "/") @@ -202,8 +203,10 @@ func (m *MountedFilesystemWriter) observedWriteFileOrSymlink(volumeRoot, src, ds // writeFileOrSymlink writes the source file or a symlink at given location or // under given directory. Follows rsync like semantics, that is: -// /foo -> /bar/ - writes foo as /bar/foo -// /foo -> /bar - writes foo as /bar +// +// /foo -> /bar/ - writes foo as /bar/foo +// /foo -> /bar - writes foo as /bar +// // The destination location is overwritten. func writeFileOrSymlink(src, dst string, preserveInDst []string) error { if strings.HasSuffix(dst, "/") { @@ -394,8 +397,9 @@ func (f *mountedFilesystemUpdater) sourceDirectoryEntries(srcPath string) ([]os. // targetInSourceDir resolves the actual target for given source directory name // and target specification. -// source: /foo/bar/ target: /baz => /bar/ (contents of /foo/bar/ under /baz) -// source: /foo/bar target: /baz => /bar/bar (directory /foo/bar under /baz, contents under /baz/bar) +// +// source: /foo/bar/ target: /baz => /bar/ (contents of /foo/bar/ under /baz) +// source: /foo/bar target: /baz => /bar/bar (directory /foo/bar under /baz, contents under /baz/bar) func targetForSourceDir(source, target string) string { if strings.HasSuffix(source, "/") { // contents of source directory land under target @@ -528,7 +532,6 @@ func (f *mountedFilesystemUpdater) updateVolumeContent(volumeRoot string, conten // ├── b.same <-- stamp indicating ./b is identical to the update data // ├── c.ignore <-- stamp indicating change to ./c was requested to be ignored // └── d.preserve <-- stamp indicating ./d is to be preserved -// func (f *mountedFilesystemUpdater) Backup() error { backupRoot := fsStructBackupPath(f.backupDir, f.ps) diff --git a/gadget/update.go b/gadget/update.go index badf6a3aa1b..b17c312d017 100644 --- a/gadget/update.go +++ b/gadget/update.go @@ -1150,27 +1150,26 @@ func volumeStructureToLocationMapImpl(old GadgetData, mod Model, laidOutVols map // rollback directory. Should the apply step fail, the modified data is // recovered. // -// // The rules for gadget/kernel updates with "$kernel:refs": // -// 1. When installing a kernel with assets that have "update: true" -// there *must* be a matching entry in gadget.yaml. If not we risk -// bricking the system because the kernel tells us that it *needs* -// this file to boot but without gadget.yaml we would not put it -// anywhere. -// 2. When installing a gadget with "$kernel:ref" content it is okay -// if this content cannot get resolved as long as there is no -// "edition" jump. This means adding new "$kernel:ref" without -// "edition" updates is always possible. +// 1. When installing a kernel with assets that have "update: true" +// there *must* be a matching entry in gadget.yaml. If not we risk +// bricking the system because the kernel tells us that it *needs* +// this file to boot but without gadget.yaml we would not put it +// anywhere. +// 2. When installing a gadget with "$kernel:ref" content it is okay +// if this content cannot get resolved as long as there is no +// "edition" jump. This means adding new "$kernel:ref" without +// "edition" updates is always possible. // // To add a new "$kernel:ref" to gadget/kernel: -// a. Update gadget and gadget.yaml and add "$kernel:ref" but do not -// update edition (if edition update is needed, use epoch) +// a. Update gadget and gadget.yaml and add "$kernel:ref" but do not update +// edition (if edition update is needed, use epoch) // b. Update kernel and kernel.yaml with new assets. -// c. snapd will refresh gadget (see rule 2) but refuse to take the -// new kernel (rule 1) -// d. After step (c) is completed the kernel refresh will now also -// work (no more violation of rule 1) +// c. snapd will refresh gadget (see rule 2) but refuse to take the new +// kernel (rule 1) +// d. After step (c) is completed the kernel refresh will now also work (no more +// violation of rule 1) func Update(model Model, old, new GadgetData, rollbackDirPath string, updatePolicy UpdatePolicyFunc, observer ContentUpdateObserver) error { // if the volumes from the old and the new gadgets do not match, then fail - // we don't support adding or removing volumes from the gadget.yaml diff --git a/image/preseed/preseed.go b/image/preseed/preseed.go index 99d9826840b..a42156ac9d3 100644 --- a/image/preseed/preseed.go +++ b/image/preseed/preseed.go @@ -49,8 +49,7 @@ var ( Stderr io.Writer = os.Stderr ) -// CoreOptions provides required and optional options for core -// preseeding. +// CoreOptions provides required and optional options for core preseeding. type CoreOptions struct { // prepare image directory PrepareImageDir string diff --git a/interfaces/apparmor/apparmor.go b/interfaces/apparmor/apparmor.go index 05550c2d2a7..99c3b8a9e64 100644 --- a/interfaces/apparmor/apparmor.go +++ b/interfaces/apparmor/apparmor.go @@ -20,9 +20,9 @@ // Package apparmor contains primitives for working with apparmor. // // References: -// - http://wiki.apparmor.net/index.php/Kernel_interfaces -// - http://apparmor.wiki.kernel.org/ -// - http://manpages.ubuntu.com/manpages/xenial/en/man7/apparmor.7.html +// - http://wiki.apparmor.net/index.php/Kernel_interfaces +// - http://apparmor.wiki.kernel.org/ +// - http://manpages.ubuntu.com/manpages/xenial/en/man7/apparmor.7.html package apparmor import ( diff --git a/interfaces/apparmor/spec.go b/interfaces/apparmor/spec.go index 2c7a5a4c661..e9556e98d3c 100644 --- a/interfaces/apparmor/spec.go +++ b/interfaces/apparmor/spec.go @@ -161,13 +161,13 @@ func (spec *Specification) AddDeduplicatedSnippet(snippet string) { // // For example the code: // -// AddParametricSnippet([]string{"/dev/", "rw,"}, "sda1") -// AddParametricSnippet([]string{"/dev/", "rw,"}, "sda3") -// AddParametricSnippet([]string{"/dev/", "rw,"}, "sdb2") +// AddParametricSnippet([]string{"/dev/", "rw,"}, "sda1") +// AddParametricSnippet([]string{"/dev/", "rw,"}, "sda3") +// AddParametricSnippet([]string{"/dev/", "rw,"}, "sdb2") // // Results in a single apparmor rule: // -// "/dev/{sda1,sda3,sdb2} rw," +// "/dev/{sda1,sda3,sdb2} rw," // // This function should be used whenever the apparmor template features more // than one use of "**" syntax (which represent arbitrary many directories or @@ -276,17 +276,18 @@ func (spec *Specification) emitLayout(si *snap.Info, layout *snap.Layout) { // // The per-snap snap-update-ns profiles are composed via a template and // snippets for the snap. The snippets may allow (depending on the snippet): -// - mount profiles via the content interface -// - creating missing mount point directories under $SNAP* (the 'tree' -// of permissions is needed for SecureMkDirAll that uses -// open(..., O_NOFOLLOW) and mkdirat() using the resulting file descriptor) -// - creating a placeholder directory in /tmp/.snap/ in the per-snap mount -// namespace to support writable mimic which uses tmpfs and bind mount to -// poke holes in arbitrary read-only locations -// - mounting/unmounting any part of $SNAP into placeholder directory -// - mounting/unmounting tmpfs over the original $SNAP/** location -// - mounting/unmounting from placeholder back to $SNAP/** (for reconstructing -// the data) +// - mount profiles via the content interface +// - creating missing mount point directories under $SNAP* (the 'tree' +// of permissions is needed for SecureMkDirAll that uses +// open(..., O_NOFOLLOW) and mkdirat() using the resulting file descriptor) +// - creating a placeholder directory in /tmp/.snap/ in the per-snap mount +// namespace to support writable mimic which uses tmpfs and bind mount to +// poke holes in arbitrary read-only locations +// - mounting/unmounting any part of $SNAP into placeholder directory +// - mounting/unmounting tmpfs over the original $SNAP/** location +// - mounting/unmounting from placeholder back to $SNAP/** (for reconstructing +// the data) +// // Importantly, the above mount operations are happening within the per-snap // mount namespace. func (spec *Specification) AddLayout(snapInfo *snap.Info) { diff --git a/interfaces/apparmor/template.go b/interfaces/apparmor/template.go index 8ceac2c735c..95c0c5ffa58 100644 --- a/interfaces/apparmor/template.go +++ b/interfaces/apparmor/template.go @@ -60,7 +60,6 @@ package apparmor // The preamble and default accesses common to all bases go in templateCommon. // These rules include the aformentioned host file rules as well as non-file // rules (eg signal, dbus, unix, etc). -// var templateCommon = ` # vim:syntax=apparmor @@ -782,10 +781,10 @@ var defaultOtherBaseTemplate = templateCommon + defaultOtherBaseTemplateRules + // to send signals to other users (even within the same snap). We want to // maintain this with our privilege dropping rules, so we omit 'capability // kill' since snaps can work within the system without 'capability kill': -// - root parent can drop, spawn a child and later (dropped) parent can send a -// signal -// - root parent can spawn a child that drops, then later temporarily drop -// (ie, seteuid/setegid), send the signal, then reraise +// - root parent can drop, spawn a child and later (dropped) parent can send a +// signal +// - root parent can spawn a child that drops, then later temporarily drop +// (ie, seteuid/setegid), send the signal, then reraise var privDropAndChownRules = ` # allow setuid, setgid and chown for privilege dropping (mediation is done # via seccomp). Note: CAP_SETUID allows (and CAP_SETGID is the same, but @@ -818,7 +817,6 @@ var privDropAndChownRules = ` // coreSnippet contains apparmor rules specific only for // snaps on native core systems. -// var coreSnippet = ` # Allow each snaps to access each their own folder on the # ubuntu-save partition, with write permissions. diff --git a/interfaces/builtin/appstream_metadata.go b/interfaces/builtin/appstream_metadata.go index 70c899a0180..c00db1ef8c1 100644 --- a/interfaces/builtin/appstream_metadata.go +++ b/interfaces/builtin/appstream_metadata.go @@ -42,7 +42,8 @@ const appstreamMetadataBaseDeclarationSlots = ` // Paths for upstream and collection metadata are defined in the // AppStream specification: -// https://www.freedesktop.org/software/appstream/docs/ +// +// https://www.freedesktop.org/software/appstream/docs/ const appstreamMetadataConnectedPlugAppArmor = ` # Description: Allow access to AppStream metadata from the host system diff --git a/interfaces/builtin/dm_crypt.go b/interfaces/builtin/dm_crypt.go index 5ff3a84eab4..6cf604e2f60 100644 --- a/interfaces/builtin/dm_crypt.go +++ b/interfaces/builtin/dm_crypt.go @@ -41,8 +41,8 @@ const dmCryptBaseDeclarationPlugs = ` // The type for this interface type dmCryptInterface struct{} -// XXX: this should not hardcode mount points like /run/media/ but -// unless we have an interface like "mount-control" this is needed +// XXX: this should not hardcode mount points like /run/media/ but unless we +// have an interface like "mount-control" this is needed const dmCryptConnectedPlugAppArmor = ` # Allow mapper access /dev/mapper/control rw, diff --git a/interfaces/builtin/mount_control.go b/interfaces/builtin/mount_control.go index afa7b2675dd..5b053d9cc22 100644 --- a/interfaces/builtin/mount_control.go +++ b/interfaces/builtin/mount_control.go @@ -157,9 +157,13 @@ type mountControlInterface struct { // The "what" and "where" attributes end up in the AppArmor profile, surrounded // by double quotes; to ensure that a malicious snap cannot inject arbitrary // rules by specifying something like -// where: $SNAP_DATA/foo", /** rw, # +// +// where: $SNAP_DATA/foo", /** rw, # +// // which would generate a profile line like: -// mount options=() "$SNAP_DATA/foo", /** rw, #" +// +// mount options=() "$SNAP_DATA/foo", /** rw, #" +// // (which would grant read-write access to the whole filesystem), it's enough // to exclude the `"` character: without it, whatever is written in the // attribute will not be able to escape being treated like a pattern. @@ -184,7 +188,8 @@ var ( // Excluding spaces and other characters which might allow constructing a // malicious string like -// auto) options=() /malicious/content /var/lib/snapd/hostfs/...,\n mount fstype=( +// +// auto) options=() /malicious/content /var/lib/snapd/hostfs/...,\n mount fstype=( var typeRegexp = regexp.MustCompile(`^[a-z0-9]+$`) type MountInfo struct { diff --git a/interfaces/builtin/netlink_driver.go b/interfaces/builtin/netlink_driver.go index 19b1722ebb5..8d49aa6dcb8 100644 --- a/interfaces/builtin/netlink_driver.go +++ b/interfaces/builtin/netlink_driver.go @@ -56,11 +56,11 @@ capability net_admin, ` // regex for family-name must match: -// * at least 2 characters long -// * must start with letter -// * must not end in a hyphen -// * can contain numbers, letters and hyphens for all character positions except -// as described above +// - at least 2 characters long +// - must start with letter +// - must not end in a hyphen +// - can contain numbers, letters and hyphens for all character positions except +// as described above var familyNameRegexp = regexp.MustCompile(`^[a-z]+[a-z0-9-]*[^\-]$`) // BeforePrepareSlot checks the slot definition is valid diff --git a/interfaces/builtin/network_control.go b/interfaces/builtin/network_control.go index d5b480b0b81..82c2f5c1217 100644 --- a/interfaces/builtin/network_control.go +++ b/interfaces/builtin/network_control.go @@ -370,11 +370,13 @@ var networkControlConnectedPlugMount = []osutil.MountEntry{{ // // When setting up a mount entry, we also need corresponding // snap-updates-ns rules. Eg, if have: -// []osutil.MountEntry{{ -// Name: "/foo/bar", -// Dir: "/bar", -// Options: []string{"rw", "bind"}, -// }} +// +// []osutil.MountEntry{{ +// Name: "/foo/bar", +// Dir: "/bar", +// Options: []string{"rw", "bind"}, +// }} +// // Then you can expect to need: // /foo/ r, // /foo/bar/ r, diff --git a/interfaces/builtin/posix_mq.go b/interfaces/builtin/posix_mq.go index c045782e323..ca176dd8e7a 100644 --- a/interfaces/builtin/posix_mq.go +++ b/interfaces/builtin/posix_mq.go @@ -82,10 +82,11 @@ var posixMQDefaultPlugPermissions = []string{ } // Ensure that the name matches the criteria from the mq_overview man page: -// Each message queue is identified by a name of the form /somename; -// that is, a null-terminated string of up to NAME_MAX (i.e., 255) -// characters consisting of an initial slash, followed by one or more -// characters, none of which are slashes. +// +// Each message queue is identified by a name of the form /somename; +// that is, a null-terminated string of up to NAME_MAX (i.e., 255) +// characters consisting of an initial slash, followed by one or more +// characters, none of which are slashes. var posixMQNamePattern = regexp.MustCompile(`^/[^/]{1,255}$`) type posixMQInterface struct { diff --git a/interfaces/builtin/serial_port.go b/interfaces/builtin/serial_port.go index f32ad3cd58c..2efb1f53a0a 100644 --- a/interfaces/builtin/serial_port.go +++ b/interfaces/builtin/serial_port.go @@ -66,16 +66,16 @@ func (iface *serialPortInterface) String() string { // Pattern to match allowed serial device nodes, path attributes will be // compared to this for validity when not using udev identification // Known device node patterns we need to support -// - ttyUSBX (UART over USB devices) -// - ttyACMX (ACM modem devices ) -// - ttyXRUSBx (Exar Corp. USB UART devices) -// - ttySX (UART serial ports) -// - ttyOX (UART serial ports on ARM) -// - ttymxcX (serial ports on i.mx6UL) -// - ttySCX (NXP SC16IS7xx serial devices) -// - ttyMSMX (Qualcomm msm7x serial devices) -// - ttyHSX (Qualcomm GENI based QTI serial cores) -// - ttyGSX (USB gadget serial devices) +// - ttyUSBX (UART over USB devices) +// - ttyACMX (ACM modem devices ) +// - ttyXRUSBx (Exar Corp. USB UART devices) +// - ttySX (UART serial ports) +// - ttyOX (UART serial ports on ARM) +// - ttymxcX (serial ports on i.mx6UL) +// - ttySCX (NXP SC16IS7xx serial devices) +// - ttyMSMX (Qualcomm msm7x serial devices) +// - ttyHSX (Qualcomm GENI based QTI serial cores) +// - ttyGSX (USB gadget serial devices) var serialDeviceNodePattern = regexp.MustCompile("^/dev/tty(mxc|USB|ACM|AMA|XRUSB|S|O|SC|MSM|HS|GS)[0-9]+$") // Pattern that is considered valid for the udev symlink to the serial device, diff --git a/interfaces/builtin/ubuntu_download_manager.go b/interfaces/builtin/ubuntu_download_manager.go index e2ff5aab432..d79f8e0ab57 100644 --- a/interfaces/builtin/ubuntu_download_manager.go +++ b/interfaces/builtin/ubuntu_download_manager.go @@ -37,8 +37,8 @@ const ubuntuDownloadManagerBaseDeclarationSlots = ` deny-connection: true ` -/* The methods: allowGSMDownload, createMmsDownload, exit and setDefaultThrottle - are deliberately left out of this profile due to their privileged nature. */ +// The methods: allowGSMDownload, createMmsDownload, exit and setDefaultThrottle +// are deliberately left out of this profile due to their privileged nature. const downloadConnectedPlugAppArmor = ` # Description: Can access the download manager. diff --git a/interfaces/builtin/utils.go b/interfaces/builtin/utils.go index 9e18d41a622..ac95fba2a2a 100644 --- a/interfaces/builtin/utils.go +++ b/interfaces/builtin/utils.go @@ -129,11 +129,12 @@ func verifySlotPathAttribute(slotRef *interfaces.SlotRef, attrs interfaces.Attre // aareExclusivePatterns takes a string and generates deny alternations. Eg, // aareExclusivePatterns("foo") returns: -// []string{ -// "[^f]*", -// "f[^o]*", -// "fo[^o]*", -// } +// +// []string{ +// "[^f]*", +// "f[^o]*", +// "fo[^o]*", +// } func aareExclusivePatterns(orig string) []string { // This function currently is only intended to be used with desktop // prefixes as calculated by info.DesktopPrefix (the snap name and diff --git a/interfaces/mount/backend.go b/interfaces/mount/backend.go index e498b9c6a76..35acdf8bac8 100644 --- a/interfaces/mount/backend.go +++ b/interfaces/mount/backend.go @@ -24,8 +24,10 @@ // into the snap. // // Each fstab like file looks like a regular fstab entry: -// /src/dir /dst/dir none bind 0 0 -// /src/dir /dst/dir none bind,rw 0 0 +// +// /src/dir /dst/dir none bind 0 0 +// /src/dir /dst/dir none bind,rw 0 0 +// // but only bind mounts are supported package mount diff --git a/interfaces/mount/spec.go b/interfaces/mount/spec.go index fe2a26b5410..d6a401bcc82 100644 --- a/interfaces/mount/spec.go +++ b/interfaces/mount/spec.go @@ -54,7 +54,7 @@ func (spec *Specification) AddMountEntry(e osutil.MountEntry) error { return nil } -//AddUserMountEntry adds a new user mount entry. +// AddUserMountEntry adds a new user mount entry. func (spec *Specification) AddUserMountEntry(e osutil.MountEntry) error { spec.user = append(spec.user, e) return nil diff --git a/interfaces/policy/policy_test.go b/interfaces/policy/policy_test.go index 9d361ad737f..54b4223348c 100644 --- a/interfaces/policy/policy_test.go +++ b/interfaces/policy/policy_test.go @@ -2490,39 +2490,44 @@ func (s *policySuite) TestNameConstraintsAutoConnection(c *C) { // makes it easy to verify correctness of a related set of patterns // // Eg, if base decl has: -// slots: -// system-files: -// allow-installation: -// slot-snap-type: -// - core -// plugs: -// system-files: -// allow-installation: false +// +// slots: +// system-files: +// allow-installation: +// slot-snap-type: +// - core +// plugs: +// system-files: +// allow-installation: false // // then test snap decls of the form: -// plugs: -// system-files: -// allow-installation: -// plug-attributes: -// write: ... +// +// plugs: +// system-files: +// allow-installation: +// plug-attributes: +// write: ... +// // or: -// plugs: -// system-files: -// allow-installation: -// - -// plug-attributes: -// write: ... +// +// plugs: +// system-files: +// allow-installation: +// - +// plug-attributes: +// write: ... +// // or: -// plugs: -// system-files: -// allow-installation: -// - -// plug-attributes: -// write: ... -// - -// plug-attributes: -// write: ... // +// plugs: +// system-files: +// allow-installation: +// - +// plug-attributes: +// write: ... +// - +// plug-attributes: +// write: ... func (s *policySuite) TestSnapDeclListAttribWithBaseAllowInstallationFalse(c *C) { baseDeclStr := `type: base-declaration authority-id: canonical diff --git a/interfaces/seccomp/backend.go b/interfaces/seccomp/backend.go index 9ddc03f37de..9149ec1f649 100644 --- a/interfaces/seccomp/backend.go +++ b/interfaces/seccomp/backend.go @@ -416,9 +416,9 @@ func (b *Backend) SandboxFeatures() []string { } // Determine if the system requires the use of socketcall(). Factors: -// - if the kernel architecture is amd64, armhf or arm64, do not require -// socketcall (unused on these architectures) -// - if the kernel architecture is i386 or s390x +// - if the kernel architecture is amd64, armhf or arm64, do not require +// socketcall (unused on these architectures) +// - if the kernel architecture is i386 or s390x // - if the kernel is < 4.3, force the use of socketcall() // - for backwards compatibility, if the system is Ubuntu 14.04 or lower, // force use of socketcall() @@ -426,8 +426,8 @@ func (b *Backend) SandboxFeatures() []string { // "core16", then force use of socketcall() // - otherwise (ie, if new enough kernel, not 14.04, and a non-16 base // snap), don't force use of socketcall() -// - if the kernel architecture is not any of the above, force the use of -// socketcall() +// - if the kernel architecture is not any of the above, force the use of +// socketcall() func requiresSocketcallImpl(baseSnap string) bool { switch dpkgKernelArchitecture() { case "i386", "s390x": diff --git a/interfaces/seccomp/template.go b/interfaces/seccomp/template.go index f34764c35f4..3664b97df25 100644 --- a/interfaces/seccomp/template.go +++ b/interfaces/seccomp/template.go @@ -696,14 +696,19 @@ setresuid32 u:root u:root -1 // Template for privilege drop and chown operations. This intentionally does // not support all combinations of users or obscure combinations (we can add // combinations as users dictate). Eg, these are supported: -// chown foo:foo -// chown foo -// chgrp foo +// +// chown foo:foo +// chown foo +// chgrp foo +// // but these are not: -// chown foo:bar -// chown bar:foo +// +// chown foo:bar +// chown bar:foo +// // For now, users who want 'foo:bar' can do: -// chown foo ; chgrp bar +// +// chown foo ; chgrp bar var privDropAndChownSyscalls = ` # allow setgid to ###GROUP### setgid g:###GROUP### diff --git a/interfaces/system_key.go b/interfaces/system_key.go index 899f24acbd3..a8981290a10 100644 --- a/interfaces/system_key.go +++ b/interfaces/system_key.go @@ -198,25 +198,26 @@ func WriteSystemKey() error { // system-key than what is on disk. // // This is used in two places: -// - snap run: when there is a mismatch it will wait for snapd -// to re-generate the security profiles -// - snapd: on startup it checks if the system-key has changed and -// if so re-generate the security profiles +// - snap run: when there is a mismatch it will wait for snapd +// to re-generate the security profiles +// - snapd: on startup it checks if the system-key has changed and +// if so re-generate the security profiles // // This ensures that "snap run" and "snapd" have a consistent set // of security profiles. Without it we may have the following // scenario: -// 1. snapd gets refreshed and snaps need updated security profiles -// to work (e.g. because snap-exec needs a new permission) -// 2. The system reboots to start the new snapd. At this point -// the old security profiles are on disk (because the new -// snapd did not run yet) -// 3. Snaps that run as daemon get started during boot by systemd -// (e.g. network-manager). This may happen before snapd had a -// chance to refresh the security profiles. -// 4. Because the security profiles are for the old version of -// the snaps that run before snapd fail to start. For e.g. -// network-manager this is of course catastrophic. +// 1. snapd gets refreshed and snaps need updated security profiles +// to work (e.g. because snap-exec needs a new permission) +// 2. The system reboots to start the new snapd. At this point +// the old security profiles are on disk (because the new +// snapd did not run yet) +// 3. Snaps that run as daemon get started during boot by systemd +// (e.g. network-manager). This may happen before snapd had a +// chance to refresh the security profiles. +// 4. Because the security profiles are for the old version of +// the snaps that run before snapd fail to start. For e.g. +// network-manager this is of course catastrophic. +// // To prevent this, in step(4) we have this wait-for-snapd // step to ensure the expected profiles are on disk. // diff --git a/interfaces/udev/udev.go b/interfaces/udev/udev.go index 991a6fe314f..063a4dc4c08 100644 --- a/interfaces/udev/udev.go +++ b/interfaces/udev/udev.go @@ -52,11 +52,14 @@ func udevadmTrigger(args ...string) error { // reloadRules runs three commands that reload udev rule database. // // The commands are: udevadm control --reload-rules -// udevadm trigger --subsystem-nomatch=input -// udevadm settle --timeout=3 +// +// udevadm trigger --subsystem-nomatch=input +// udevadm settle --timeout=3 +// // and optionally trigger other subsystems as defined in the interfaces. Eg: -// udevadm trigger --subsystem-match=input -// udevadm trigger --property-match=ID_INPUT_JOYSTICK=1 +// +// udevadm trigger --subsystem-match=input +// udevadm trigger --property-match=ID_INPUT_JOYSTICK=1 func (b *Backend) reloadRules(subsystemTriggers []string) error { if b.preseed { return nil diff --git a/kernel/fde/fde.go b/kernel/fde/fde.go index 21a9f52d03e..7599d1c9b92 100644 --- a/kernel/fde/fde.go +++ b/kernel/fde/fde.go @@ -89,8 +89,9 @@ func unmarshalInitialSetupResult(hookOutput []byte) (*InitialSetupResult, error) } // TODO: unexport this because how the hook is driven is an implemenation -// detail. It creates quite a bit of churn unfortunately, see -// https://github.com/snapcore/snapd/compare/master...mvo5:ice/refactor-fde?expand=1 +// +// detail. It creates quite a bit of churn unfortunately, see +// https://github.com/snapcore/snapd/compare/master...mvo5:ice/refactor-fde?expand=1 // // SetupRequest carries the operation and parameters for the fde-setup hooks // made available to them via the snapctl fde-setup-request command. diff --git a/osutil/io.go b/osutil/io.go index 2e2e6aaf439..1ada46c730a 100644 --- a/osutil/io.go +++ b/osutil/io.go @@ -66,7 +66,7 @@ type AtomicFile struct { // NewAtomicFile builds an AtomicFile backed by an *os.File that will have // the given filename, permissions and uid/gid when Committed. // -// It _might_ be implemented using O_TMPFILE (see open(2)). +// It _might_ be implemented using O_TMPFILE (see open(2)). // // Note that it won't follow symlinks and will replace existing symlinks with // the real file, unless the AtomicWriteFollow flag is specified. diff --git a/osutil/mkdirallchown.go b/osutil/mkdirallchown.go index bae0b78379e..6025f3a0884 100644 --- a/osutil/mkdirallchown.go +++ b/osutil/mkdirallchown.go @@ -29,8 +29,9 @@ import ( ) // XXX: we need to come back and fix this; this is a hack to unblock us. -// As part of the fixing we should unify with the similar code in -// cmd/snap-update-ns/utils.(*Secure).MkdirAll +// +// As part of the fixing we should unify with the similar code in +// cmd/snap-update-ns/utils.(*Secure).MkdirAll var mu sync.Mutex // MkdirAllChown is like os.MkdirAll but it calls os.Chown on any diff --git a/osutil/mountentry.go b/osutil/mountentry.go index a54c7445ac4..f5a7f68ff1b 100644 --- a/osutil/mountentry.go +++ b/osutil/mountentry.go @@ -31,14 +31,14 @@ import ( // // 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 */ -// }; +// 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 Dir string diff --git a/osutil/strace/timing_test.go b/osutil/strace/timing_test.go index 2fb1b28866e..bebd140f4f7 100644 --- a/osutil/strace/timing_test.go +++ b/osutil/strace/timing_test.go @@ -81,7 +81,8 @@ func (s *timingSuite) TestExecveTimingPrunes(c *C) { } // generated with: -// sudo /usr/lib/snapd/snap-discard-ns test-snapd-tools && sudo strace -u $USER -o strace.log -f -e trace=execve,execveat -ttt test-snapd-tools.echo foo && cat strace.log +// +// sudo /usr/lib/snapd/snap-discard-ns test-snapd-tools && sudo strace -u $USER -o strace.log -f -e trace=execve,execveat -ttt test-snapd-tools.echo foo && cat strace.log var sampleStraceSimple = []byte(`21616 1542882400.198907 execve("/snap/bin/test-snapd-tools.echo", ["test-snapd-tools.echo", "foo"], 0x7fff7f275f48 /* 27 vars */) = 0 21616 1542882400.204710 execve("/snap/core/current/usr/bin/snap", ["test-snapd-tools.echo", "foo"], 0xc42011c8c0 /* 27 vars */ 21621 1542882400.204845 +++ exited with 0 +++ diff --git a/overlord/devicestate/devicemgr.go b/overlord/devicestate/devicemgr.go index f34dd020028..44ac9842675 100644 --- a/overlord/devicestate/devicemgr.go +++ b/overlord/devicestate/devicemgr.go @@ -381,11 +381,11 @@ func (m *DeviceManager) ensureUbuntuSaveIsMounted() error { // /var/lib/snapd/save/snap/. This is normally done during installation // of a snap, but there are two cases where this can be insufficient. // -// 1. When migrating to a newer snapd, folders are not automatically created for -// snaps that are already installed. They will only be created during a refresh of -// the snap itself, whereas we want to cover all the cases. -// 2. During install mode for the gadget/kernel/etc, the folders are not created. -// So this function can be invoked as a part of system-setup. +// 1. When migrating to a newer snapd, folders are not automatically created for +// snaps that are already installed. They will only be created during a refresh of +// the snap itself, whereas we want to cover all the cases. +// 2. During install mode for the gadget/kernel/etc, the folders are not created. +// So this function can be invoked as a part of system-setup. func (m *DeviceManager) ensureUbuntuSaveSnapFolders() error { snaps, err := snapstate.All(m.state) if err != nil { diff --git a/overlord/devicestate/devicestate.go b/overlord/devicestate/devicestate.go index 8bf07debb13..2c268b73a8b 100644 --- a/overlord/devicestate/devicestate.go +++ b/overlord/devicestate/devicestate.go @@ -286,11 +286,11 @@ func interfaceConnected(st *state.State, snapName, ifName string) bool { // switched to the "core.refresh.schedule=managed" mode. // // TODO: -// - Move the CanManageRefreshes code into the ifstate -// - Look at the connections and find the connection for snapd-control -// with the managed attribute -// - Take the snap from this connection and look at the snapstate to see -// if that snap has a snap declaration (to ensure it comes from the store) +// - Move the CanManageRefreshes code into the ifstate +// - Look at the connections and find the connection for snapd-control +// with the managed attribute +// - Take the snap from this connection and look at the snapstate to see +// if that snap has a snap declaration (to ensure it comes from the store) func CanManageRefreshes(st *state.State) bool { snapStates, err := snapstate.All(st) if err != nil { @@ -857,11 +857,11 @@ func remodelTasks(ctx context.Context, st *state.State, current, new *asserts.Mo // transition is not possible. // // TODO: -// - Check estimated disk size delta -// - Check all relevant snaps exist in new store -// (need to check that even unchanged snaps are accessible) -// - Make sure this works with Core 20 as well, in the Core 20 case -// we must enforce the default-channels from the model as well +// - Check estimated disk size delta +// - Check all relevant snaps exist in new store +// (need to check that even unchanged snaps are accessible) +// - Make sure this works with Core 20 as well, in the Core 20 case +// we must enforce the default-channels from the model as well func Remodel(st *state.State, new *asserts.Model) (*state.Change, error) { var seeded bool err := st.Get("seeded", &seeded) diff --git a/overlord/ifacestate/ifacestate.go b/overlord/ifacestate/ifacestate.go index 569e9ac1649..c7796e067e6 100644 --- a/overlord/ifacestate/ifacestate.go +++ b/overlord/ifacestate/ifacestate.go @@ -88,7 +88,6 @@ type connectOpts struct { } // Connect returns a set of tasks for connecting an interface. -// func Connect(st *state.State, plugSnap, plugName, slotSnap, slotName string) (*state.TaskSet, error) { if err := snapstate.CheckChangeConflictMany(st, []string{plugSnap, slotSnap}, ""); err != nil { return nil, err diff --git a/overlord/patch/patch4.go b/overlord/patch/patch4.go index 843e5740c8e..aeac39c1a13 100644 --- a/overlord/patch/patch4.go +++ b/overlord/patch/patch4.go @@ -273,9 +273,9 @@ func (p4 patch4T) addRevertFlag(task *state.Task) error { } // patch4: -// - add Revert flag to in-progress revert-snap changes -// - move from had-candidate to old-candidate-index in link-snap tasks -// - add cleanup task to in-progress changes that have a copy-snap-data task +// - add Revert flag to in-progress revert-snap changes +// - move from had-candidate to old-candidate-index in link-snap tasks +// - add cleanup task to in-progress changes that have a copy-snap-data task func patch4(s *state.State) error { p4 := patch4T{} for _, change := range s.Changes() { diff --git a/overlord/patch/patch6.go b/overlord/patch/patch6.go index 21ee07be044..47d8494cc09 100644 --- a/overlord/patch/patch6.go +++ b/overlord/patch/patch6.go @@ -68,7 +68,7 @@ func patch6FlagsFromPatch4(old patch4Flags) patch6Flags { } // patch6: -// - move from a flags-are-ints world to a flags-are-struct-of-bools world +// - move from a flags-are-ints world to a flags-are-struct-of-bools world func patch6(st *state.State) error { var oldStateMap map[string]*patch4SnapState err := st.Get("snaps", &oldStateMap) diff --git a/overlord/patch/patch6_1.go b/overlord/patch/patch6_1.go index 015d9bcd6f9..b7697d6402e 100644 --- a/overlord/patch/patch6_1.go +++ b/overlord/patch/patch6_1.go @@ -97,7 +97,7 @@ func processConns(conns map[string]connStatePatch6_1, infos map[string]*snap.Inf } // patch6_1: -// - add static plug and slot attributes to connections that miss them. Attributes are read from current snap info. +// - add static plug and slot attributes to connections that miss them. Attributes are read from current snap info. func patch6_1(st *state.State) error { infos := make(map[string]*snap.Info) diff --git a/overlord/patch/patch6_2.go b/overlord/patch/patch6_2.go index bec2042b0b4..de2a29f8f1a 100644 --- a/overlord/patch/patch6_2.go +++ b/overlord/patch/patch6_2.go @@ -105,8 +105,8 @@ func hasSnapdSnapID(snapst patch62SnapState) bool { } // patch6_2: -// - ensure snapd snaps in the snapstate have TypeSnapd for backward compatibility with old snapd snap releases. -// - ensure snapd snaps have TypeSnapd in pending install tasks. +// - ensure snapd snaps in the snapstate have TypeSnapd for backward compatibility with old snapd snap releases. +// - ensure snapd snaps have TypeSnapd in pending install tasks. func patch6_2(st *state.State) error { var snaps map[string]*json.RawMessage if err := st.Get("snaps", &snaps); err != nil && !errors.Is(err, state.ErrNoState) { diff --git a/overlord/patch/patch6_3.go b/overlord/patch/patch6_3.go index 8bf95932dab..6ee16a0101d 100644 --- a/overlord/patch/patch6_3.go +++ b/overlord/patch/patch6_3.go @@ -41,7 +41,7 @@ func normChan(in string) string { } // patch6_3: -// - ensure channel spec is valid +// - ensure channel spec is valid func patch6_3(st *state.State) error { var snaps map[string]*json.RawMessage if err := st.Get("snaps", &snaps); err != nil && !errors.Is(err, state.ErrNoState) { diff --git a/overlord/snapstate/backend_test.go b/overlord/snapstate/backend_test.go index 445d0e2c9fd..98fb739c243 100644 --- a/overlord/snapstate/backend_test.go +++ b/overlord/snapstate/backend_test.go @@ -830,8 +830,9 @@ func (f *fakeSnappyBackend) OpenSnapFile(snapFilePath string, si *snap.SideInfo) } // XXX: this is now something that is overridden by tests that need a -// different service setup so it should be configurable and part -// of the fakeSnappyBackend? +// +// different service setup so it should be configurable and part +// of the fakeSnappyBackend? var servicesSnapYaml = `name: services-snap apps: svc1: diff --git a/overlord/state/change.go b/overlord/state/change.go index 02427ec4bfc..bb5e5ce9a56 100644 --- a/overlord/state/change.go +++ b/overlord/state/change.go @@ -287,10 +287,9 @@ func init() { // of the individual tasks related to the change, according to the following // decision sequence: // -// - With at least one task in DoStatus, return DoStatus -// - With at least one task in ErrorStatus, return ErrorStatus -// - Otherwise, return DoneStatus -// +// - With at least one task in DoStatus, return DoStatus +// - With at least one task in ErrorStatus, return ErrorStatus +// - Otherwise, return DoneStatus func (c *Change) Status() Status { c.state.reading() if c.status == DefaultStatus { diff --git a/overlord/state/change_test.go b/overlord/state/change_test.go index 1557d174f2a..7ac95bac256 100644 --- a/overlord/state/change_test.go +++ b/overlord/state/change_test.go @@ -543,16 +543,17 @@ func (cs *changeSuite) TestAbortKⁿ(c *C) { // Task wait order: // -// => t21 => t22 -// / \ +// => t21 => t22 +// / \ +// // t11 => t12 => t41 => t42 -// \ / -// => t31 => t32 +// +// \ / +// => t31 => t32 // // setup and result lines are :[:,...] // // "*" as task name means "all remaining". -// var abortLanesTests = []struct { setup string abort []int @@ -746,11 +747,9 @@ func (ts *taskRunnerSuite) TestAbortLanes(c *C) { } } -// // setup and result lines are :[:,...] // order is -> (implies task2 waits for task 1) // "*" as task name means "all remaining". -// var abortUnreadyLanesTests = []struct { setup string order string diff --git a/overlord/state/state.go b/overlord/state/state.go index 2d48d7a2c2f..19c691bece3 100644 --- a/overlord/state/state.go +++ b/overlord/state/state.go @@ -397,15 +397,15 @@ func (s *State) RegisterPendingChangeByAttr(attr string, f func(*Change) bool) { // Prune does several cleanup tasks to the in-memory state: // -// * it removes changes that became ready for more than pruneWait and aborts -// tasks spawned for more than abortWait unless prevented by predicates -// registered with RegisterPendingChangeByAttr. +// - it removes changes that became ready for more than pruneWait and aborts +// tasks spawned for more than abortWait unless prevented by predicates +// registered with RegisterPendingChangeByAttr. // -// * it removes tasks unlinked to changes after pruneWait. When there are more -// changes than the limit set via "maxReadyChanges" those changes in ready -// state will also removed even if they are below the pruneWait duration. +// - it removes tasks unlinked to changes after pruneWait. When there are more +// changes than the limit set via "maxReadyChanges" those changes in ready +// state will also removed even if they are below the pruneWait duration. // -// * it removes expired warnings. +// - it removes expired warnings. func (s *State) Prune(startOfOperation time.Time, pruneWait, abortWait time.Duration, maxReadyChanges int) { now := time.Now() pruneLimit := now.Add(-pruneWait) diff --git a/overlord/state/taskrunner_test.go b/overlord/state/taskrunner_test.go index a4ea1e5af21..e5f49a96297 100644 --- a/overlord/state/taskrunner_test.go +++ b/overlord/state/taskrunner_test.go @@ -89,19 +89,19 @@ func ensureChange(c *C, r *state.TaskRunner, sb *stateBackend, chg *state.Change // handlers will be called, assuming the provided setup is in place. // // Setup options: -// :was- - set task status before calling ensure (must be sensible) -// :(do|undo)-block - block handler until task tomb dies -// :(do|undo)-retry - return from handler with with state.Retry -// :(do|undo)-error - return from handler with an error -// :...:1,2 - one of the above, and add task to lanes 1 and 2 -// chg:abort - call abort on the change +// +// :was- - set task status before calling ensure (must be sensible) +// :(do|undo)-block - block handler until task tomb dies +// :(do|undo)-retry - return from handler with with state.Retry +// :(do|undo)-error - return from handler with an error +// :...:1,2 - one of the above, and add task to lanes 1 and 2 +// chg:abort - call abort on the change // // Task wait order: ( t11 | t12 ) => ( t21 ) => ( t31 | t32 ) // // Task t12 has no undo. // // Final task statuses are tested based on the resulting events list. -// var sequenceTests = []struct{ setup, result string }{{ setup: "", result: "t11:do t12:do t21:do t31:do t32:do", diff --git a/polkit/pid_start_time.go b/polkit/pid_start_time.go index f1870a233f2..f3e39199e83 100644 --- a/polkit/pid_start_time.go +++ b/polkit/pid_start_time.go @@ -37,7 +37,8 @@ func getStartTimeForPid(pid int32) (uint64, error) { // getStartTimeForProcStatFile determines the start time from a process stat file // // The implementation is intended to be compatible with polkit: -// https://cgit.freedesktop.org/polkit/tree/src/polkit/polkitunixprocess.c +// +// https://cgit.freedesktop.org/polkit/tree/src/polkit/polkitunixprocess.c func getStartTimeForProcStatFile(filename string) (uint64, error) { data, err := ioutil.ReadFile(filename) if err != nil { diff --git a/progress/progress.go b/progress/progress.go index ccf6cd14c08..5ee12391829 100644 --- a/progress/progress.go +++ b/progress/progress.go @@ -100,11 +100,11 @@ var isTerminal = func() bool { // MakeProgressBar creates an appropriate progress.Meter for the environ in // which it is called: // -// * if MockMeter has been called, return that. -// * if w is not nil nor os.Stdout, a QuietMeter outputting to it is returned. -// * if no terminal is attached, or we think we're running a test, -// a minimalistic QuietMeter outputting to stdout is returned. -// * otherwise, an ANSIMeter is returned. +// - if MockMeter has been called, return that. +// - if w is not nil nor os.Stdout, a QuietMeter outputting to it is returned. +// - if no terminal is attached, or we think we're running a test, +// a minimalistic QuietMeter outputting to stdout is returned. +// - otherwise, an ANSIMeter is returned. func MakeProgressBar(w io.Writer) Meter { if testMeter != nil { return testMeter diff --git a/secboot/secboot.go b/secboot/secboot.go index bff34c509c7..48616fb9fe5 100644 --- a/secboot/secboot.go +++ b/secboot/secboot.go @@ -204,7 +204,7 @@ func EncryptedPartitionName(name string) string { // MarkSuccessful marks the secure boot parts of the boot as // successful. // -//This means that the dictionary attack (DA) lockout counter is reset. +// This means that the dictionary attack (DA) lockout counter is reset. func MarkSuccessful() error { sealingMethod, err := device.SealedKeysMethod(dirs.GlobalRootDir) if err != nil && err != device.ErrNoSealedKeys { diff --git a/seed/seedwriter/writer.go b/seed/seedwriter/writer.go index d463eb24feb..0c7f37aa1ae 100644 --- a/seed/seedwriter/writer.go +++ b/seed/seedwriter/writer.go @@ -100,62 +100,56 @@ func (sn *SeedSnap) modes() []string { var _ naming.SnapRef = (*SeedSnap)(nil) -/* Writer writes Core 16/18 and Core 20 seeds. - -Its methods need to be called in sequences that match prescribed -flows. - -Some methods can be skipped given some conditions. - -SnapsToDownload and Downloaded needs to be called in a loop where the -SeedSnaps returned by SnapsToDownload get SetInfo called with -*snap.Info retrieved from the store and then the snaps can be -downloaded at SeedSnap.Path, after which Downloaded must be invoked -and the flow breaks out of the loop only when it returns complete = -true. In the loop as well assertions for the snaps can be fetched and -SeedSnap.ARefs set. - -Optionally a similar but simpler mechanism covers local snaps, where -LocalSnaps returns SeedSnaps that can be filled with information -derived from the snap at SeedSnap.Path, then InfoDerived is called. - - V-------->\ - | | - SetOptionsSnaps | - | v - | ________/ - v - / Start \ - | | | - | v | - | / LocalSnaps | - no | | | | - local | | v | no option - snaps | | SetInfo* | snaps - | | | | - | | v | - | | InfoDerived | - | | | | - \ \ | / - > > SnapsToDownload< - | ^ - v | - SetInfo* | - | | complete = false - v / - Downloaded - | - | complete = true - | - v - SeedSnaps (copy files) - | - v - WriteMeta - - * = 0 or many calls (as needed) - -*/ +// Writer writes Core 16/18 and Core 20 seeds. Its methods need to be called in +// sequences that match prescribed flows. +// Some methods can be skipped given some conditions. +// +// SnapsToDownload and Downloaded needs to be called in a loop where the +// SeedSnaps returned by SnapsToDownload get SetInfo called with *snap.Info +// retrieved from the store and then the snaps can be downloaded at +// SeedSnap.Path, after which Downloaded must be invoked and the flow breaks +// out of the loop only when it returns complete = true. In the loop as well +// assertions for the snaps can be fetched and SeedSnap.ARefs set. +// +// Optionally a similar but simpler mechanism covers local snaps, where +// LocalSnaps returns SeedSnaps that can be filled with information derived +// from the snap at SeedSnap.Path, then InfoDerived is called. +// +// V-------->\ +// | | +// SetOptionsSnaps | +// | v +// | ________/ +// v +// / Start \ +// | | | +// | v | +// | / LocalSnaps | +// no | | | | +// local | | v | no option +// snaps | | SetInfo* | snaps +// | | | | +// | | v | +// | | InfoDerived | +// | | | | +// \ \ | / +// > > SnapsToDownload< +// | ^ +// v | +// SetInfo* | +// | | complete = false +// v / +// Downloaded +// | +// | complete = true +// | +// v +// SeedSnaps (copy files) +// | +// v +// WriteMeta +// +// * = 0 or many calls (as needed) type Writer struct { model *asserts.Model opts *Options diff --git a/snap/channel/channel.go b/snap/channel/channel.go index be522bf81ed..d4f2adfa033 100644 --- a/snap/channel/channel.go +++ b/snap/channel/channel.go @@ -211,14 +211,15 @@ type ChannelMatch struct { } // String returns the string represantion of the match, results can be: -// "architecture:track:risk" -// "architecture:track" -// "architecture:risk" -// "track:risk" -// "architecture" -// "track" -// "risk" -// "" +// +// "architecture:track:risk" +// "architecture:track" +// "architecture:risk" +// "track:risk" +// "architecture" +// "track" +// "risk" +// "" func (cm ChannelMatch) String() string { matching := []string{} if cm.Architecture { diff --git a/snap/container.go b/snap/container.go index 26f042043b3..24abf7404df 100644 --- a/snap/container.go +++ b/snap/container.go @@ -229,12 +229,12 @@ func ValidateContainer(c Container, s *Info, logf func(format string, v ...inter // app's RestartCommand, which might be empty to mean there is no such thing), // and cleans it. // -// * empty paths are returned as is -// * if the path is not relative, it's initial / is dropped -// * if the path goes "outside" (ie starts with ../), the empty string is -// returned (i.e. "ignore") -// * if there's a space in the command, ignore the rest of the string -// (see also cmd/snap-exec/main.go's comment about strings.Split) +// - empty paths are returned as is +// - if the path is not relative, it's initial / is dropped +// - if the path goes "outside" (ie starts with ../), the empty string is +// returned (i.e. "ignore") +// - if there's a space in the command, ignore the rest of the string +// (see also cmd/snap-exec/main.go's comment about strings.Split) func normPath(path string) string { if path == "" { return "" diff --git a/snap/epoch.go b/snap/epoch.go index 0e0cef5c57b..db94c27724d 100644 --- a/snap/epoch.go +++ b/snap/epoch.go @@ -33,11 +33,11 @@ import ( // order, there's a simplified expression they can use which should cover the // majority of the cases: // -// epoch: N +// epoch: N // // means a snap can read/write exactly the Nth epoch's data, and // -// epoch: N* +// epoch: N* // // means a snap can additionally read (N-1)th epoch's data, which means it's a // snap that can migrate epochs (so a user on epoch 0 can get offered a refresh @@ -46,9 +46,9 @@ import ( // If the above is not enough, a developer can explicitly describe what epochs a // snap can read and write: // -// epoch: -// read: [1, 2, 3] -// write: [1, 3] +// epoch: +// read: [1, 2, 3] +// write: [1, 3] // // the read attribute defaults to the value of the write attribute, and the // write attribute defaults to the last item in the read attribute. If both are diff --git a/snap/info.go b/snap/info.go index 1276ad7f60c..0ea10343806 100644 --- a/snap/info.go +++ b/snap/info.go @@ -1075,12 +1075,12 @@ type HookInfo struct { // SystemUsernameInfo provides information about a system username (ie, a // UNIX user and group with the same name). The scope defines visibility of the // username wrt the snap and the system. Defined scopes: -// - shared static, snapd-managed user/group shared between host and all -// snaps -// - private static, snapd-managed user/group private to a particular snap -// (currently not implemented) -// - external dynamic user/group shared between host and all snaps (currently -// not implented) +// - shared static, snapd-managed user/group shared between host and all +// snaps +// - private static, snapd-managed user/group private to a particular snap +// (currently not implemented) +// - external dynamic user/group shared between host and all snaps (currently +// not implented) type SystemUsernameInfo struct { Name string Scope string diff --git a/snap/info_snap_yaml.go b/snap/info_snap_yaml.go index 05cb18c1104..e8fd8b5a689 100644 --- a/snap/info_snap_yaml.go +++ b/snap/info_snap_yaml.go @@ -696,16 +696,19 @@ func convertToSlotOrPlugData(plugOrSlot, name string, data interface{}) (iface, } // Short form: -// system-usernames: -// snap_daemon: shared # 'scope' is 'shared' -// lxd: external # currently unsupported -// foo: private # currently unsupported +// +// system-usernames: +// snap_daemon: shared # 'scope' is 'shared' +// lxd: external # currently unsupported +// foo: private # currently unsupported +// // Attributes form: -// system-usernames: -// snap_daemon: -// scope: shared -// attrib1: ... -// attrib2: ... +// +// system-usernames: +// snap_daemon: +// scope: shared +// attrib1: ... +// attrib2: ... func convertToUsernamesData(user string, data interface{}) (scope string, attrs map[string]interface{}, err error) { switch data.(type) { case string: diff --git a/snap/naming/validate.go b/snap/naming/validate.go index d5556333314..e6f3e5cbfa4 100644 --- a/snap/naming/validate.go +++ b/snap/naming/validate.go @@ -26,18 +26,17 @@ import ( "strings" ) -// almostValidName is part of snap and socket name validation. -// the full regexp we could use, "^(?:[a-z0-9]+-?)*[a-z](?:-?[a-z0-9])*$", is -// O(2ⁿ) on the length of the string in python. An equivalent regexp that -// doesn't have the nested quantifiers that trip up Python's re would be -// "^(?:[a-z0-9]|(?<=[a-z0-9])-)*[a-z](?:[a-z0-9]|-(?=[a-z0-9]))*$", but Go's -// regexp package doesn't support look-aheads nor look-behinds, so in order to -// have a unified implementation in the Go and Python bits of the project -// we're doing it this way instead. Check the length (if applicable), check -// this regexp, then check the dashes. -// This still leaves sc_snap_name_validate (in cmd/snap-confine/snap.c) and -// snap_validate (cmd/snap-update-ns/bootstrap.c) with their own handcrafted -// validators. +// almostValidName is part of snap and socket name validation. The full regexp +// we could use, "^(?:[a-z0-9]+-?)*[a-z](?:-?[a-z0-9])*$", is O(2ⁿ) on the +// length of the string in python. An equivalent regexp that doesn't have the +// nested quantifiers that trip up Python's re would be +// "^(?:[a-z0-9]|(?<=[a-z0-9])-)*[a-z](?:[a-z0-9]|-(?=[a-z0-9]))*$", but Go's +// regexp package doesn't support look-aheads nor look-behinds, so in order to +// have a unified implementation in the Go and Python bits of the project we're +// doing it this way instead. Check the length (if applicable), check this +// regexp, then check the dashes. This still leaves sc_snap_name_validate +// (in cmd/snap-confine/snap.c) and snap_validate +// (cmd/snap-update-ns/bootstrap.c) with their own handcrafted validators. var almostValidName = regexp.MustCompile("^[a-z0-9-]*[a-z][a-z0-9-]*$") // validInstanceKey is a regular expression describing a valid snap instance key diff --git a/snap/snaptest/snaptest.go b/snap/snaptest/snaptest.go index e49a50e5691..04b60b39f49 100644 --- a/snap/snaptest/snaptest.go +++ b/snap/snaptest/snaptest.go @@ -168,7 +168,7 @@ func MockInvalidInfo(c *check.C, yamlText string, sideInfo *snap.SideInfo) *snap // directory with given content // // The caller is responsible for mocking root directory with dirs.SetRootDir() -//and for altering the overlord state if required. +// and for altering the overlord state if required. func MockSnapWithFiles(c *check.C, yamlText string, si *snap.SideInfo, files [][]string) *snap.Info { info := MockSnap(c, yamlText, si) diff --git a/snap/squashfs/squashfs.go b/snap/squashfs/squashfs.go index 1f39d2f5845..28d7a681991 100644 --- a/snap/squashfs/squashfs.go +++ b/snap/squashfs/squashfs.go @@ -299,9 +299,10 @@ func (sk skipper) Has(path string) bool { } // pre-4.5 unsquashfs writes a funny header like: -// "Parallel unsquashfs: Using 1 processor" -// "1 inodes (1 blocks) to write" -// "" <-- empty line +// +// "Parallel unsquashfs: Using 1 processor" +// "1 inodes (1 blocks) to write" +// "" <-- empty line var maybeHeaderRegex = regexp.MustCompile(`^(Parallel unsquashfs: Using .* processor.*|[0-9]+ inodes .* to write)$`) // Walk (part of snap.Container) is like filepath.Walk, without the ordering guarantee. diff --git a/snap/system_usernames.go b/snap/system_usernames.go index d7e25160e4d..9b4cba8ba7a 100644 --- a/snap/system_usernames.go +++ b/snap/system_usernames.go @@ -36,31 +36,31 @@ type systemUsername struct { // 'external' (currently snapd only supports 'scope: shared') with the // following characteristics: // -// - uid and gid shall match for the specified system-username -// - a snapd-allocated [ug]id for a user/group name shall never change -// - snapd should avoid [ug]ids that are known to overlap with uid ranges of -// common use cases and user namespace container managers so that DAC and -// AppArmor owner match work as intended. -// - [ug]id shall be < 2^31 to avoid (at least) broken devpts kernel code -// - [ug]id shall be >= 524288 (0x00080000) to give plenty of room for large -// sites, default uid/gid ranges for docker (231072-296608), LXD installs -// that setup a default /etc/sub{uid,gid} (100000-165536) and podman whose -// tutorials reference setting up a specific default user and range -// (100000-165536) -// - [ug]id shall be < 1,000,000 and > 1,001,000,000 (ie, 1,000,000 subordinate -// uid with 1,000,000,000 range) to avoid overlapping with LXD's minimum and -// maximum id ranges. LXD allows for any id range >= 65536 and doesn't -// perform any [ug]id overlap detection with current users -// - [ug]ids assigned by snapd initially will fall within a 65536 (2^16) range -// (see below) where the first [ug]id in the range has the 16 lower bits all -// set to zero. This allows snapd to conveniently be bitwise aligned, follows -// sensible conventions (see https://systemd.io/UIDS-GIDS.html) but also -// potentially discoverable by systemd-nspawn (it assigns a different 65536 -// range to each container. Its allocation algorithm is not sequential and -// may choose anything within its range that isn't already allocated. It's -// detection algorithm includes (effectively) performing a getpwent() -// operation on CANDIDATE_UID & 0XFFFF0000 and selecting another range if it -// is assigned). +// - uid and gid shall match for the specified system-username +// - a snapd-allocated [ug]id for a user/group name shall never change +// - snapd should avoid [ug]ids that are known to overlap with uid ranges of +// common use cases and user namespace container managers so that DAC and +// AppArmor owner match work as intended. +// - [ug]id shall be < 2^31 to avoid (at least) broken devpts kernel code +// - [ug]id shall be >= 524288 (0x00080000) to give plenty of room for large +// sites, default uid/gid ranges for docker (231072-296608), LXD installs +// that setup a default /etc/sub{uid,gid} (100000-165536) and podman whose +// tutorials reference setting up a specific default user and range +// (100000-165536) +// - [ug]id shall be < 1,000,000 and > 1,001,000,000 (ie, 1,000,000 subordinate +// uid with 1,000,000,000 range) to avoid overlapping with LXD's minimum and +// maximum id ranges. LXD allows for any id range >= 65536 and doesn't +// perform any [ug]id overlap detection with current users +// - [ug]ids assigned by snapd initially will fall within a 65536 (2^16) range +// (see below) where the first [ug]id in the range has the 16 lower bits all +// set to zero. This allows snapd to conveniently be bitwise aligned, follows +// sensible conventions (see https://systemd.io/UIDS-GIDS.html) but also +// potentially discoverable by systemd-nspawn (it assigns a different 65536 +// range to each container. Its allocation algorithm is not sequential and +// may choose anything within its range that isn't already allocated. It's +// detection algorithm includes (effectively) performing a getpwent() +// operation on CANDIDATE_UID & 0XFFFF0000 and selecting another range if it +// is assigned). // // What [ug]id range(s) should snapd use? // @@ -94,21 +94,21 @@ type systemUsername struct { // Looking at the LSB and distribution defaults for login.defs, we can observe // uids and gids in the system's initial 65536 range (ie, 0-65536): // -// - 0-99 LSB-suggested statically assigned range (eg, root, daemon, -// etc) -// - 0 mandatory 'root' user -// - 100-499 LSB-suggested dynamically assigned range for system users -// (distributions often prefer a higher range, see below) -// - 500-999 typical distribution default for dynamically assigned range -// for system users (some distributions use a smaller -// SYS_[GU]ID_MIN) -// - 1000-60000 typical distribution default for dynamically assigned range -// for regular users -// - 65535 (-1) should not be assigned since '-1' might be evaluated as this -// with set[ug]id* and chown families of functions -// - 65534 (-2) nobody/nogroup user for NFS/etc [ug]id anonymous squashing -// - 65519-65533 systemd recommended reserved range for site-local anonymous -// additions, etc +// - 0-99 LSB-suggested statically assigned range (eg, root, daemon, +// etc) +// - 0 mandatory 'root' user +// - 100-499 LSB-suggested dynamically assigned range for system users +// (distributions often prefer a higher range, see below) +// - 500-999 typical distribution default for dynamically assigned range +// for system users (some distributions use a smaller +// SYS_[GU]ID_MIN) +// - 1000-60000 typical distribution default for dynamically assigned range +// for regular users +// - 65535 (-1) should not be assigned since '-1' might be evaluated as this +// with set[ug]id* and chown families of functions +// - 65534 (-2) nobody/nogroup user for NFS/etc [ug]id anonymous squashing +// - 65519-65533 systemd recommended reserved range for site-local anonymous +// additions, etc // // To facilitate potential future use cases within the 65536 range snapd will // assign from, snapd will only assign from the following subset of ranges diff --git a/spdx/licenses.go b/spdx/licenses.go index 591a3f841ba..c946e975944 100644 --- a/spdx/licenses.go +++ b/spdx/licenses.go @@ -24,6 +24,7 @@ package spdx // Version: 3.11 2020-11-25 // // jq < json/licenses.json '.licenses | .[] | select(.isOsiApproved == true) | .licenseId' | sort | sed -e 's/$/,/' +// //nolint:deadcode,unused var osi = []string{ "0BSD", diff --git a/store/cache.go b/store/cache.go index 9d7b34ea12a..aa5147c3c6c 100644 --- a/store/cache.go +++ b/store/cache.go @@ -73,13 +73,13 @@ type CacheManager struct { // and the given maximum amount of items. The idea behind it is the // following algorithm: // -// 1. When starting a download, check if it exists in $cacheDir -// 2. If found, update its mtime, hardlink into target location, and -// return success -// 3. If not found, download the snap -// 4. On success, hardlink into $cacheDir/ -// 5. If cache dir has more than maxItems entries, remove oldest mtimes -// until it has maxItems +// 1. When starting a download, check if it exists in $cacheDir +// 2. If found, update its mtime, hardlink into target location, and +// return success +// 3. If not found, download the snap +// 4. On success, hardlink into $cacheDir/ +// 5. If cache dir has more than maxItems entries, remove oldest mtimes +// until it has maxItems // // The caching part is done here, the downloading happens in the store.go // code. diff --git a/store/store.go b/store/store.go index 6ff3ddd1ab4..32eac7a23ee 100644 --- a/store/store.go +++ b/store/store.go @@ -832,26 +832,26 @@ func (s *Store) extractSuggestedCurrency(resp *http.Response) { // ordersResult encapsulates the order data sent to us from the software center agent. // -// { -// "orders": [ -// { -// "snap_id": "abcd1234efgh5678ijkl9012", -// "currency": "USD", -// "amount": "2.99", -// "state": "Complete", -// "refundable_until": null, -// "purchase_date": "2016-09-20T15:00:00+00:00" -// }, -// { -// "snap_id": "abcd1234efgh5678ijkl9012", -// "currency": null, -// "amount": null, -// "state": "Complete", -// "refundable_until": null, -// "purchase_date": "2016-09-20T15:00:00+00:00" -// } -// ] -// } +// { +// "orders": [ +// { +// "snap_id": "abcd1234efgh5678ijkl9012", +// "currency": "USD", +// "amount": "2.99", +// "state": "Complete", +// "refundable_until": null, +// "purchase_date": "2016-09-20T15:00:00+00:00" +// }, +// { +// "snap_id": "abcd1234efgh5678ijkl9012", +// "currency": null, +// "amount": null, +// "state": "Complete", +// "refundable_until": null, +// "purchase_date": "2016-09-20T15:00:00+00:00" +// } +// ] +// } type ordersResult struct { Orders []*order `json:"orders"` } diff --git a/store/store_test.go b/store/store_test.go index c1845a70c1d..6a470406286 100644 --- a/store/store_test.go +++ b/store/store_test.go @@ -1069,34 +1069,41 @@ const mockSingleOrderJSON = `{ ] }` -/* acquired via - -http --pretty=format --print b https://api.snapcraft.io/v2/snaps/info/hello-world architecture==amd64 fields==architectures,base,confinement,links,contact,created-at,description,download,epoch,license,name,prices,private,publisher,revision,snap-id,snap-yaml,summary,title,type,version,media,common-ids,website Snap-Device-Series:16 | xsel -b - -on 2022-10-20. Then, by hand: -- set prices to {"EUR": "0.99", "USD": "1.23"}, -- set base in first channel-map entry to "bogus-base", -- set snap-yaml in first channel-map entry to the one from the 'edge', plus the following pastiche: -apps: - content-plug: - command: bin/content-plug - plugs: [shared-content-plug] -plugs: - shared-content-plug: - interface: content - target: import - content: mylib - default-provider: test-snapd-content-slot -slots: - shared-content-slot: - interface: content - content: mylib - read: - - / - -- change edge entry to have different revision, version and "released-at" to something randomish - -*/ +// acquired via: +// +// http --pretty=format --print b https://api.snapcraft.io/v2/snaps/info/hello-world architecture==amd64 fields==architectures,base,confinement,links,contact,created-at,description,download,epoch,license,name,prices,private,publisher,revision,snap-id,snap-yaml,summary,title,type,version,media,common-ids,website Snap-Device-Series:16 | xsel -b +// +// on 2022-10-20. Then, by hand: +// +// - set prices to {"EUR": "0.99", "USD": "1.23"}, +// +// - set base in first channel-map entry to "bogus-base", +// +// - set snap-yaml in first channel-map entry to the one from the 'edge', plus the following pastiche: +// apps: +// +// content-plug: +// command: bin/content-plug +// plugs: [shared-content-plug] +// +// plugs: +// +// shared-content-plug: +// interface: content +// target: import +// content: mylib +// default-provider: test-snapd-content-slot +// +// slots: +// +// shared-content-slot: +// interface: content +// content: mylib +// read: +// +// - / +// +// change edge entry to have different revision, version and "released-at" to something randomish const mockInfoJSON = `{ "channel-map": [ { @@ -1977,14 +1984,11 @@ func (s *storeTestSuite) TestExistsNotFound(c *C) { c.Assert(ch, IsNil) } -/* -acquired via - -http --pretty=format --print b https://api.snapcraft.io/v2/snaps/info/no:such:package architecture==amd64 fields==architectures,base,confinement,contact,created-at,description,download,epoch,license,name,prices,private,publisher,revision,snap-id,snap-yaml,summary,title,type,version,media,common-ids Snap-Device-Series:16 | xsel -b - -on 2018-06-14 - -*/ +// acquired via: +// +// http --pretty=format --print b https://api.snapcraft.io/v2/snaps/info/no:such:package architecture==amd64 fields==architectures,base,confinement,contact,created-at,description,download,epoch,license,name,prices,private,publisher,revision,snap-id,snap-yaml,summary,title,type,version,media,common-ids Snap-Device-Series:16 | xsel -b +// +// on 2018-06-14 const MockNoDetailsJSON = `{ "error-list": [ { @@ -2021,7 +2025,9 @@ func (s *storeTestSuite) TestNoInfo(c *C) { c.Assert(result, IsNil) } -/* acquired via looking at the query snapd does for "snap find 'hello-world of snaps' --narrow" (on core) and adding size=1: +/* + acquired via looking at the query snapd does for "snap find 'hello-world of snaps' --narrow" (on core) and adding size=1: + curl -s -H "accept: application/hal+json" -H "X-Ubuntu-Release: 16" -H "X-Ubuntu-Wire-Protocol: 1" -H "X-Ubuntu-Architecture: amd64" 'https://api.snapcraft.io/api/v1/snaps/search?confinement=strict&fields=anon_download_url%2Carchitecture%2Cchannel%2Cdownload_sha3_384%2Csummary%2Cdescription%2Cbinary_filesize%2Cdownload_url%2Clast_updated%2Cpackage_name%2Cprices%2Cpublisher%2Cratings_average%2Crevision%2Csnap_id%2Clicense%2Cbase%2Cmedia%2Csupport_url%2Ccontact%2Ctitle%2Ccontent%2Cversion%2Corigin%2Cdeveloper_id%2Cdeveloper_name%2Cdeveloper_validation%2Cprivate%2Cconfinement%2Ccommon_ids&q=hello-world+of+snaps&size=1' | python -m json.tool | xsel -b And then add base and prices, increase title's length, and remove the _links dict @@ -2218,7 +2224,9 @@ func (s *storeTestSuite) TestFindV1Queries(c *C) { c.Check(v1Fallback, Equals, true) } -/* acquired via: +/* + acquired via: + curl -s -H "accept: application/hal+json" -H "X-Ubuntu-Release: 16" -H "X-Ubuntu-Device-Channel: edge" -H "X-Ubuntu-Wire-Protocol: 1" -H "X-Ubuntu-Architecture: amd64" 'https://api.snapcraft.io/api/v1/snaps/sections' */ const MockSectionsJSON = `{ diff --git a/store/userinfo_test.go b/store/userinfo_test.go index 3b51bcc578d..c7806a185c1 100644 --- a/store/userinfo_test.go +++ b/store/userinfo_test.go @@ -44,8 +44,9 @@ type userInfoSuite struct { var _ = check.Suite(&userInfoSuite{}) // obtained via: -// `curl https://login.staging.ubuntu.com/api/v2/keys/mvo@ubuntu.com` -// `curl https://login.staging.ubuntu.com/api/v2/keys/xDPXBdB` +// +// `curl https://login.staging.ubuntu.com/api/v2/keys/mvo@ubuntu.com` +// `curl https://login.staging.ubuntu.com/api/v2/keys/xDPXBdB` var mockServerJSON = `{ "username": "mvo", "ssh_keys": [ diff --git a/strutil/pathiter.go b/strutil/pathiter.go index 4a2304694a3..613a0173283 100644 --- a/strutil/pathiter.go +++ b/strutil/pathiter.go @@ -35,10 +35,12 @@ import ( // A simple example on how to use the iterator: // ``` // iter:= NewPathIterator(path) -// for iter.Next() { -// // Use iter.CurrentName() with openat(2) family of functions. -// // Use iter.CurrentPath() or iter.CurrentBase() for context. -// } +// +// for iter.Next() { +// // Use iter.CurrentName() with openat(2) family of functions. +// // Use iter.CurrentPath() or iter.CurrentBase() for context. +// } +// // ``` type PathIterator struct { path string diff --git a/strutil/shlex/shlex.go b/strutil/shlex/shlex.go index 8bee5a934c2..878677c4a73 100644 --- a/strutil/shlex/shlex.go +++ b/strutil/shlex/shlex.go @@ -20,22 +20,21 @@ shell-style rules for quoting and commenting. The basic use case uses the default ASCII lexer to split a string into sub-strings: - shlex.Split("one \"two three\" four") -> []string{"one", "two three", "four"} + shlex.Split("one \"two three\" four") -> []string{"one", "two three", "four"} To process a stream of strings: - l := NewLexer(os.Stdin) - for ; token, err := l.Next(); err != nil { - // process token - } + l := NewLexer(os.Stdin) + for ; token, err := l.Next(); err != nil { + // process token + } To access the raw token stream (which includes tokens for comments): - t := NewTokenizer(os.Stdin) - for ; token, err := t.Next(); err != nil { - // process token - } - + t := NewTokenizer(os.Stdin) + for ; token, err := t.Next(); err != nil { + // process token + } */ package shlex diff --git a/strutil/version.go b/strutil/version.go index 816f81159d7..566bcc8f38f 100644 --- a/strutil/version.go +++ b/strutil/version.go @@ -145,9 +145,10 @@ func compareSubversion(va, vb string) int { // VersionCompare compare two version strings that follow the debian // version policy and // Returns: -// -1 if a is smaller than b -// 0 if a equals b -// +1 if a is bigger than b +// +// -1 if a is smaller than b +// 0 if a equals b +// +1 if a is bigger than b func VersionCompare(va, vb string) (res int, err error) { // FIXME: return err here instead if !versionIsValid(va) { diff --git a/syscheck/squashfs.go b/syscheck/squashfs.go index 24c2d73fc62..e62a56f7ae8 100644 --- a/syscheck/squashfs.go +++ b/syscheck/squashfs.go @@ -40,22 +40,20 @@ func init() { checks = append(checks, checkSquashfsMount) } -/* This image was created using: - -#!/bin/sh - -cd $(mktemp -d) -cat > canary.txt<<'EOF' -This file is used to check that snapd can read a squashfs image. - -The squashfs was generated with: -EOF -cat $0 >> canary.txt - -mksquashfs . /tmp/canary.squashfs -noappend -comp xz -no-xattrs -no-fragments >/dev/nul -cat /tmp/canary.squashfs | gzip - | base64 - -*/ +// This image was created using: +// +// #!/bin/sh +// +// cd $(mktemp -d) +// cat > canary.txt<<'EOF' +// This file is used to check that snapd can read a squashfs image. +// +// The squashfs was generated with: +// EOF +// cat $0 >> canary.txt +// +// mksquashfs . /tmp/canary.squashfs -noappend -comp xz -no-xattrs -no-fragments >/dev/nul +// cat /tmp/canary.squashfs | gzip - | base64 var b64SquashfsImage = []byte(` H4sIAGxdFVsAA8soLixmYmBgyIkVjWZgALEYGFgYBBkuMDECaQYGFQYI4INIMbBB6f9Q0MAI4R+D 0s+g9A8o/de8KiKKgYExU+meGfOB54wzmBUZuYDiVhPYbR4wTme4H8ugJcWpniK5waL4VLewwsUC diff --git a/systemd/escape.go b/systemd/escape.go index 70995ab6bed..2b84d7c992e 100644 --- a/systemd/escape.go +++ b/systemd/escape.go @@ -29,10 +29,8 @@ import ( const allowed = `:_.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789` // EscapeUnitNamePath works like systemd-escape --path -// FIXME: we could use github.com/coreos/go-systemd/unit/escape.go -// and EscapePath from it. -// -// But thats not in the archive and it won't work with go1.3 +// FIXME: we could use github.com/coreos/go-systemd/unit/escape.go and EscapePath +// from it. But that's not in the archive and it won't work with go1.3 func EscapeUnitNamePath(in string) string { // "" is the same as "/" which is escaped to "-" // the filepath.Clean will turn "" into "." and make this incorrect diff --git a/systemd/systemd.go b/systemd/systemd.go index f90a9516dc7..dd6f92e9df5 100644 --- a/systemd/systemd.go +++ b/systemd/systemd.go @@ -428,16 +428,16 @@ type RunOptions struct { // In almost all cases, the strings map to a single string value, but as per the // manpage for journalctl, under the json format, // -// Journal entries permit non-unique fields within the same log entry. JSON -// does not allow non-unique fields within objects. Due to this, if a -// non-unique field is encountered a JSON array is used as field value, -// listing all field values as elements. +// Journal entries permit non-unique fields within the same log entry. JSON +// does not allow non-unique fields within objects. Due to this, if a +// non-unique field is encountered a JSON array is used as field value, +// listing all field values as elements. // // and this snippet as well, // -// Fields containing non-printable or non-UTF8 bytes are -// encoded as arrays containing the raw bytes individually -// formatted as unsigned numbers. +// Fields containing non-printable or non-UTF8 bytes are +// encoded as arrays containing the raw bytes individually +// formatted as unsigned numbers. // // as such, we sometimes get array values which need to be handled differently, // so we manually try to decode the json for each message into different types. diff --git a/tests/lib/gendeveloper1/main.go b/tests/lib/gendeveloper1/main.go index 92a8f16a270..7ed927a96ba 100644 --- a/tests/lib/gendeveloper1/main.go +++ b/tests/lib/gendeveloper1/main.go @@ -17,25 +17,25 @@ * */ -// The ``gendeveloper1'' tool can be used generate model assertions for use in +// The “gendeveloper1” tool can be used generate model assertions for use in // tests. It reads the assetion headers in form of a JSON from stdin, and // outputs a model assertion, signed by the test key to stdout. // // Usage: -// gendeveloper1 sign-model < headers.json > assertion.model // -// Example input: +// gendeveloper1 sign-model < headers.json > assertion.model // -// { -// "type": "model", -// "brand-id": "developer1", -// "model": "my-model", -// "architecture": "amd64", -// "gadget": "test-snapd-pc", -// "kernel": "pc-kernel=18", -// "timestamp": "2018-09-11T22:00:00+00:00" -// } +// Example input: // +// { +// "type": "model", +// "brand-id": "developer1", +// "model": "my-model", +// "architecture": "amd64", +// "gadget": "test-snapd-pc", +// "kernel": "pc-kernel=18", +// "timestamp": "2018-09-11T22:00:00+00:00" +// } package main import ( diff --git a/testutil/exec.go b/testutil/exec.go index d5c496f470c..6f2288c824e 100644 --- a/testutil/exec.go +++ b/testutil/exec.go @@ -187,10 +187,11 @@ func (cmd *MockCmd) Restore() { // Calls returns a list of calls that were made to the mock command. // of the form: -// [][]string{ -// {"cmd", "arg1", "arg2"}, // first invocation of "cmd" -// {"cmd", "arg1", "arg2"}, // second invocation of "cmd" -// } +// +// [][]string{ +// {"cmd", "arg1", "arg2"}, // first invocation of "cmd" +// {"cmd", "arg1", "arg2"}, // second invocation of "cmd" +// } func (cmd *MockCmd) Calls() [][]string { raw, err := ioutil.ReadFile(cmd.logFile) if os.IsNotExist(err) { diff --git a/testutil/intcheckers.go b/testutil/intcheckers.go index 21993233f9f..a83259c8c1e 100644 --- a/testutil/intcheckers.go +++ b/testutil/intcheckers.go @@ -64,35 +64,41 @@ func (checker *intChecker) Check(params []interface{}, names []string) (result b // IntLessThan checker verifies that one integer is less than other integer. // // For example: -// c.Assert(1, IntLessThan, 2) +// +// c.Assert(1, IntLessThan, 2) var IntLessThan = &intChecker{CheckerInfo: &check.CheckerInfo{Name: "IntLessThan", Params: []string{"a", "b"}}, rel: "<"} // IntLessEqual checker verifies that one integer is less than or equal to other integer. // // For example: -// c.Assert(1, IntLessEqual, 1) +// +// c.Assert(1, IntLessEqual, 1) var IntLessEqual = &intChecker{CheckerInfo: &check.CheckerInfo{Name: "IntLessEqual", Params: []string{"a", "b"}}, rel: "<="} // IntEqual checker verifies that one integer is equal to other integer. // // For example: -// c.Assert(1, IntEqual, 1) +// +// c.Assert(1, IntEqual, 1) var IntEqual = &intChecker{CheckerInfo: &check.CheckerInfo{Name: "IntEqual", Params: []string{"a", "b"}}, rel: "=="} // IntNotEqual checker verifies that one integer is not equal to other integer. // // For example: -// c.Assert(1, IntNotEqual, 2) +// +// c.Assert(1, IntNotEqual, 2) var IntNotEqual = &intChecker{CheckerInfo: &check.CheckerInfo{Name: "IntNotEqual", Params: []string{"a", "b"}}, rel: "!="} // IntGreaterThan checker verifies that one integer is greater than other integer. // // For example: -// c.Assert(2, IntGreaterThan, 1) +// +// c.Assert(2, IntGreaterThan, 1) var IntGreaterThan = &intChecker{CheckerInfo: &check.CheckerInfo{Name: "IntGreaterThan", Params: []string{"a", "b"}}, rel: ">"} // IntGreaterEqual checker verifies that one integer is greater than or equal to other integer. // // For example: -// c.Assert(1, IntGreaterEqual, 2) +// +// c.Assert(1, IntGreaterEqual, 2) var IntGreaterEqual = &intChecker{CheckerInfo: &check.CheckerInfo{Name: "IntGreaterEqual", Params: []string{"a", "b"}}, rel: ">="} diff --git a/timeutil/schedule.go b/timeutil/schedule.go index 772243d430a..9d5d724150a 100644 --- a/timeutil/schedule.go +++ b/timeutil/schedule.go @@ -620,28 +620,28 @@ func ParseLegacySchedule(scheduleSpec string) ([]*Schedule, error) { // ParseSchedule parses a schedule in V2 format. The format is described as: // -// eventlist = eventset *( ",," eventset ) -// eventset = wdaylist / timelist / wdaylist "," timelist +// eventlist = eventset *( ",," eventset ) +// eventset = wdaylist / timelist / wdaylist "," timelist // -// wdaylist = wdayset *( "," wdayset ) -// wdayset = wday / wdaynumber / wdayspan -// wday = ( "sun" / "mon" / "tue" / "wed" / "thu" / "fri" / "sat" ) -// wdaynumber = ( "sun" / "mon" / "tue" / "wed" / "thu" / "fri" / "sat" ) DIGIT -// wdayspan = wday "-" wday / wdaynumber "-" wday / wday "-" wdaynumber +// wdaylist = wdayset *( "," wdayset ) +// wdayset = wday / wdaynumber / wdayspan +// wday = ( "sun" / "mon" / "tue" / "wed" / "thu" / "fri" / "sat" ) +// wdaynumber = ( "sun" / "mon" / "tue" / "wed" / "thu" / "fri" / "sat" ) DIGIT +// wdayspan = wday "-" wday / wdaynumber "-" wday / wday "-" wdaynumber // -// timelist = timeset *( "," timeset ) -// timeset = time / timespan -// time = 2DIGIT ":" 2DIGIT -// timespan = time ( "-" / "~" ) time [ "/" ( time / count ) ] -// count = 1*DIGIT +// timelist = timeset *( "," timeset ) +// timeset = time / timespan +// time = 2DIGIT ":" 2DIGIT +// timespan = time ( "-" / "~" ) time [ "/" ( time / count ) ] +// count = 1*DIGIT // // Examples: // mon,10:00,,fri,15:00 (Monday at 10:00, Friday at 15:00) // mon,fri,10:00,15:00 (Monday at 10:00 and 15:00, Friday at 10:00 and 15:00) // mon-wed,fri,9:00-11:00/2 (Monday to Wednesday and on Friday, twice between -// 9:00 and 11:00) -// mon,9:00~11:00,,wed,22:00~23:00 (Monday, sometime between 9:00 and 11:00, and -// on Wednesday, sometime between 22:00 and 23:00) +// 9:00 and 11:00) +// mon,9:00~11:00,,wed,22:00~23:00 (Monday, sometime between 9:00 and 11:00, +// and on Wednesday, sometime between 22:00 and 23:00) // mon,wed (Monday and on Wednesday) // mon,,wed (same as above) // mon1-wed (1st Monday of the month to the following Wednesday) diff --git a/timings/timings.go b/timings/timings.go index 57f4d03e10d..49ed29862f5 100644 --- a/timings/timings.go +++ b/timings/timings.go @@ -36,24 +36,26 @@ var timeNow = time.Now // to the above, nested measurements need to be finished by calling Stop on them. // // Typical usage: -// troot := timings.New(map[string]string{"task-id": task.ID(), "change-id": task.Change().ID()}) -// t1 := troot.StartSpan("computation", "...") -// .... -// nestedTiming := t1.StartSpan("sub-computation", "...") -// .... -// nestedTiming.Stop() -// t1.Stop() -// troot.Save() +// +// troot := timings.New(map[string]string{"task-id": task.ID(), "change-id": task.Change().ID()}) +// t1 := troot.StartSpan("computation", "...") +// .... +// nestedTiming := t1.StartSpan("sub-computation", "...") +// .... +// nestedTiming.Stop() +// t1.Stop() +// troot.Save() // // In addition, a few helpers exist to simplify typical use cases, for example the above example // can be reduced to: -// troot := state.TimingsForTask(task) // tags set automatically from task -// t1 := troot.StartSpan("computation", "...") -// timings.Run(t1, "sub-computation", "...", func(nested *Span) { -// ... expensive computation -// }) -// t1.Stop() -// troot.Save(task.State()) +// +// troot := state.TimingsForTask(task) // tags set automatically from task +// t1 := troot.StartSpan("computation", "...") +// timings.Run(t1, "sub-computation", "...", func(nested *Span) { +// ... expensive computation +// }) +// t1.Stop() +// troot.Save(task.State()) type Timings struct { tags map[string]string timings []*Span diff --git a/usersession/userd/launcher.go b/usersession/userd/launcher.go index a16046e96ba..9940d0601c8 100644 --- a/usersession/userd/launcher.go +++ b/usersession/userd/launcher.go @@ -65,13 +65,13 @@ const launcherIntrospectionXML = ` // https://github.com/snapcore/snapd/pull/7731#pullrequestreview-362900171 // // The current criteria for adding url schemes is: -// * understanding and documenting the scheme in this file -// * the scheme itself does not cause xdg-open to open files (eg, file:// or -// matching '^[[:alpha:]+\.\-]+:' (from xdg-open source)) -// * verifying that the recipient of the url (ie, what xdg-open calls) won't -// process file paths/etc that can be leveraged to break out of the sandbox -// (but understanding how the url can drive the recipient application is -// important) +// - understanding and documenting the scheme in this file +// - the scheme itself does not cause xdg-open to open files (eg, file:// or +// matching '^[[:alpha:]+\.\-]+:' (from xdg-open source)) +// - verifying that the recipient of the url (ie, what xdg-open calls) won't +// process file paths/etc that can be leveraged to break out of the sandbox +// (but understanding how the url can drive the recipient application is +// important) // // This code uses golang's net/url.Parse() which will help ensure the url is // ok before passing to xdg-open. xdg-open itself properly quotes the url so diff --git a/usersession/userd/privileged_desktop_launcher.go b/usersession/userd/privileged_desktop_launcher.go index 64501fa30fa..de711df0f2e 100644 --- a/usersession/userd/privileged_desktop_launcher.go +++ b/usersession/userd/privileged_desktop_launcher.go @@ -157,10 +157,12 @@ func desktopFileSearchPath() []string { // Per https://standards.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#desktop-file-id, // if desktop entries have dashes in the name ('-'), this could be an indication of subdirectories, so search // for those too. Eg, given foo-bar_baz_norf.desktop the following are searched for: -// o .../foo-bar_baz-norf.desktop -// o .../foo/bar_baz-norf.desktop -// o .../foo/bar_baz/norf.desktop -// o .../foo-bar_baz/norf.desktop +// +// o .../foo-bar_baz-norf.desktop +// o .../foo/bar_baz-norf.desktop +// o .../foo/bar_baz/norf.desktop +// o .../foo-bar_baz/norf.desktop +// // We're not required to diagnose multiple files matching the desktop file ID. func findDesktopFile(baseDir string, splitFileId []string) (string, error) { desktopFile := filepath.Join(baseDir, strings.Join(splitFileId, "-")) diff --git a/wrappers/desktop.go b/wrappers/desktop.go index 3ae206dbdee..31d88813c49 100644 --- a/wrappers/desktop.go +++ b/wrappers/desktop.go @@ -38,16 +38,16 @@ import ( // From the freedesktop Desktop Entry Specification¹, // -// Keys with type localestring may be postfixed by [LOCALE], where -// LOCALE is the locale type of the entry. LOCALE must be of the form -// lang_COUNTRY.ENCODING@MODIFIER, where _COUNTRY, .ENCODING, and -// @MODIFIER may be omitted. If a postfixed key occurs, the same key -// must be also present without the postfix. +// Keys with type localestring may be postfixed by [LOCALE], where +// LOCALE is the locale type of the entry. LOCALE must be of the form +// lang_COUNTRY.ENCODING@MODIFIER, where _COUNTRY, .ENCODING, and +// @MODIFIER may be omitted. If a postfixed key occurs, the same key +// must be also present without the postfix. // -// When reading in the desktop entry file, the value of the key is -// selected by matching the current POSIX locale for the LC_MESSAGES -// category against the LOCALE postfixes of all occurrences of the -// key, with the .ENCODING part stripped. +// When reading in the desktop entry file, the value of the key is +// selected by matching the current POSIX locale for the LC_MESSAGES +// category against the LOCALE postfixes of all occurrences of the +// key, with the .ENCODING part stripped. // // sadly POSIX doesn't mention what values are valid for LC_MESSAGES, // beyond mentioning² that it's implementation-defined (and can be of