fork/gdu

git clone https://git.julia.blue/fork/gdu

VXNCXNXfix(device): skip malformed mount lines (#625)81b1d22

ignore
2.4 KiB109 linesraw
1package device
2
3import (
4	"bufio"
5	"fmt"
6	"io"
7	"os"
8	"strings"
9
10	"golang.org/x/sys/unix"
11)
12
13// LinuxDevicesInfoGetter returns info for Linux devices
14type LinuxDevicesInfoGetter struct {
15	MountsPath string
16}
17
18// Getter is current instance of DevicesInfoGetter
19var Getter DevicesInfoGetter = LinuxDevicesInfoGetter{MountsPath: "/proc/mounts"}
20
21// GetMounts returns all mounted filesystems from /proc/mounts
22func (t LinuxDevicesInfoGetter) GetMounts() (devices Devices, err error) {
23	file, err := os.Open(t.MountsPath)
24	if err != nil {
25		return nil, err
26	}
27
28	devices, err = readMountsFile(file)
29	if err != nil {
30		if cerr := file.Close(); cerr != nil {
31			return nil, fmt.Errorf("%w; %s", err, cerr.Error())
32		}
33		return nil, err
34	}
35	if err := file.Close(); err != nil {
36		return nil, err
37	}
38	return devices, nil
39}
40
41// GetDevicesInfo returns result of GetMounts with usage info about mounted devices (by calling Statfs syscall)
42func (t LinuxDevicesInfoGetter) GetDevicesInfo() (devices Devices, err error) {
43	mounts, err := t.GetMounts()
44	if err != nil {
45		return nil, err
46	}
47
48	return processMounts(mounts, false)
49}
50
51func readMountsFile(file io.Reader) (mounts Devices, err error) {
52	mounts = Devices{}
53
54	scanner := bufio.NewScanner(file)
55	for scanner.Scan() {
56		line := scanner.Text()
57		parts := strings.Fields(line)
58
59		// skip malformed lines, a valid entry has at least device, mount point and fstype
60		if len(parts) < 3 {
61			continue
62		}
63
64		device := &Device{
65			Name:       parts[0],
66			MountPoint: unescapeString(parts[1]),
67			Fstype:     parts[2],
68		}
69		mounts = append(mounts, device)
70	}
71
72	if err := scanner.Err(); err != nil {
73		return nil, err
74	}
75
76	return mounts, nil
77}
78
79func processMounts(mounts Devices, ignoreErrors bool) (devices Devices, err error) {
80	devices = Devices{}
81
82	for _, mount := range mounts {
83		if strings.Contains(mount.MountPoint, "/snap/") {
84			continue
85		}
86
87		if strings.HasPrefix(mount.Name, "/dev") ||
88			mount.Fstype == "zfs" ||
89			mount.Fstype == "nfs" ||
90			mount.Fstype == "nfs4" {
91			info := &unix.Statfs_t{}
92			err = unix.Statfs(mount.MountPoint, info)
93			if err != nil && !ignoreErrors {
94				return nil, err
95			}
96
97			mount.Size = int64(info.Bsize) * int64(info.Blocks)
98			mount.Free = int64(info.Bsize) * int64(info.Bavail)
99
100			devices = append(devices, mount)
101		}
102	}
103
104	return devices, nil
105}
106
107func unescapeString(str string) string {
108	return strings.ReplaceAll(str, "\\040", " ")
109}