• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright 2020 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package mount
16
17import (
18	"bufio"
19	"io"
20	"os"
21	"strings"
22	"syscall"
23)
24
25type systemMounter struct {
26}
27
28func NewSystemMounter() *systemMounter {
29	var f systemMounter
30	return &f
31}
32
33func (f *systemMounter) Mount(source string, target string, fstype string, flags uintptr, data string) error {
34	return syscall.Mount(source, target, fstype, flags, data)
35}
36
37func (f *systemMounter) Unmount(target string, flags int) error {
38	return syscall.Unmount(target, flags)
39}
40
41func (f *systemMounter) List() ([]string, error) {
42	mountsFile, err := os.Open("/proc/mounts")
43	if err != nil {
44		return nil, err
45	}
46	defer mountsFile.Close()
47	mounts, err := f.parseMounts(mountsFile)
48	if err != nil {
49		return nil, err
50	}
51	var mountList []string
52	for _, mount := range mounts {
53		mountList = append(mountList, mount.Path)
54	}
55	return mountList, err
56}
57
58type Mount struct {
59	Device string
60	Path   string
61	Type   string
62	Opts   string
63}
64
65func (f *systemMounter) parseMounts(mountSource io.Reader) ([]Mount, error) {
66	var mounts []Mount
67	scanner := bufio.NewScanner(mountSource)
68	for scanner.Scan() {
69		line := scanner.Text()
70		fields := strings.Fields(line)
71		mount := Mount{
72			Device: fields[0],
73			Path:   fields[1],
74			Type:   fields[2],
75			Opts:   fields[3],
76		}
77		mounts = append(mounts, mount)
78	}
79	return mounts, scanner.Err()
80}
81