github.com/Lephar/snapd@v0.0.0-20210825215435-c7fba9cef4d2/interfaces/mount/ns.go (about)

     1  // -*- Mode: Go; indent-tabs-mode: t -*-
     2  
     3  /*
     4   * Copyright (C) 2016-2017 Canonical Ltd
     5   *
     6   * This program is free software: you can redistribute it and/or modify
     7   * it under the terms of the GNU General Public License version 3 as
     8   * published by the Free Software Foundation.
     9   *
    10   * This program is distributed in the hope that it will be useful,
    11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13   * GNU General Public License for more details.
    14   *
    15   * You should have received a copy of the GNU General Public License
    16   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    17   *
    18   */
    19  
    20  package mount
    21  
    22  import (
    23  	"fmt"
    24  	"os/exec"
    25  	"path/filepath"
    26  
    27  	"github.com/snapcore/snapd/dirs"
    28  	"github.com/snapcore/snapd/osutil"
    29  	"github.com/snapcore/snapd/snapdtool"
    30  )
    31  
    32  // mountNsPath returns path of the mount namespace file of a given snap
    33  func mountNsPath(snapName string) string {
    34  	// NOTE: This value has to be synchronized with snap-confine
    35  	return filepath.Join(dirs.SnapRunNsDir, fmt.Sprintf("%s.mnt", snapName))
    36  }
    37  
    38  // Run an internal tool on a given snap namespace, if one exists.
    39  func runNamespaceTool(toolName, snapName string) ([]byte, error) {
    40  	mntFile := mountNsPath(snapName)
    41  	if osutil.FileExists(mntFile) {
    42  		toolPath, err := snapdtool.InternalToolPath(toolName)
    43  		if err != nil {
    44  			return nil, err
    45  		}
    46  		cmd := exec.Command(toolPath, snapName)
    47  		output, err := cmd.CombinedOutput()
    48  		return output, err
    49  	}
    50  	return nil, nil
    51  }
    52  
    53  // Discard the mount namespace of a given snap.
    54  func DiscardSnapNamespace(snapName string) error {
    55  	output, err := runNamespaceTool("snap-discard-ns", snapName)
    56  	if err != nil {
    57  		return fmt.Errorf("cannot discard preserved namespace of snap %q: %s", snapName, osutil.OutputErr(output, err))
    58  	}
    59  	return nil
    60  }
    61  
    62  // Update the mount namespace of a given snap.
    63  func UpdateSnapNamespace(snapName string) error {
    64  	output, err := runNamespaceTool("snap-update-ns", snapName)
    65  	if err != nil {
    66  		return fmt.Errorf("cannot update preserved namespace of snap %q: %s", snapName, osutil.OutputErr(output, err))
    67  	}
    68  	return nil
    69  }