summaryrefslogtreecommitdiffstats
path: root/src/detection/disk/disk_linux.c
blob: 720531731ffb349701f03d17a26bc7cd2586f3f6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
#include "disk.h"

#include "common/io.h"
#include "common/strutil.h"

#include <limits.h>
#include <ctype.h>
#include <dirent.h>
#include <mntent.h>
#include <sys/stat.h>
#include <sys/statvfs.h>

#if defined(STATX_BTIME) && !defined(__ANDROID__)
    #include <sys/syscall.h>
#endif

#ifdef __USE_LARGEFILE64
    #define stat stat64
    #define statvfs statvfs64
    #define dirent dirent64
    #define readdir readdir64
#endif

static bool isPhysicalDevice(const struct mntent* device) {
#ifndef __ANDROID__ // On Android, `/dev` is not accessible, so that the following checks always fail

    // Always show the root path
    if (ffStrEquals(device->mnt_dir, "/")) {
        return true;
    }

    if (ffStrEquals(device->mnt_fsname, "none")) {
        return false;
    }

    // DrvFs is a filesystem plugin to WSL that was designed to support interop between WSL and the Windows filesystem.
    if (ffStrEquals(device->mnt_type, "9p")) {
        return ffStrContains(device->mnt_opts, "aname=drvfs");
    }

    // ZFS pool
    if (ffStrEquals(device->mnt_type, "zfs")) {
        return true;
    }

    // sshfs
    if (ffStrEquals(device->mnt_type, "fuse.sshfs")) {
        return true;
    }

    // Pseudo filesystems don't have a device in /dev
    if (!ffStrStartsWith(device->mnt_fsname, "/dev/")) {
        return false;
    }

    // #731
    if (ffStrEquals(device->mnt_type, "bcachefs")) {
        return true;
    }

    if (
        ffStrStartsWith(device->mnt_fsname + 5, "loop") || // Ignore loop devices
        ffStrStartsWith(device->mnt_fsname + 5, "ram") ||  // Ignore ram devices
        ffStrStartsWith(device->mnt_fsname + 5, "fd")      // Ignore fd devices
    ) {
        return false;
    }

    if (ffStrStartsWith(device->mnt_dir, "/bedrock/")) { // Ignore Bedrock Linux subvolumes
        return false;
    }

    struct stat deviceStat;
    if (stat(device->mnt_fsname, &deviceStat) != 0) {
        return false;
    }

    // Ignore all devices that are not block devices
    if (!S_ISBLK(deviceStat.st_mode)) {
        return false;
    }

#else

    // Pseudo filesystems don't have a device in /dev
    if (!ffStrStartsWith(device->mnt_fsname, "/dev/")) {
        return false;
    }

    if (
        ffStrStartsWith(device->mnt_fsname + 5, "loop") || // Ignore loop devices
        ffStrStartsWith(device->mnt_fsname + 5, "ram") ||  // Ignore ram devices
        ffStrStartsWith(device->mnt_fsname + 5, "fd")      // Ignore fd devices
    ) {
        return false;
    }

    // https://source.android.com/docs/core/ota/apex?hl=zh-cn
    if (ffStrStartsWith(device->mnt_dir, "/apex/")) {
        return false;
    }

#endif // __ANDROID__

    return true;
}

static void detectNameFromPath(FFDisk* disk, const struct stat* deviceStat, FFstrbuf* basePath) {
    FF_AUTO_CLOSE_DIR DIR* dir = opendir(basePath->chars);
    if (dir == NULL) {
        return;
    }

    uint32_t basePathLength = basePath->length;

    struct dirent* entry;
    while ((entry = readdir(dir)) != NULL) {
        if (entry->d_name[0] == '.') {
            continue;
        }

        ffStrbufAppendS(basePath, entry->d_name);

        struct stat entryStat;
        bool ret = stat(basePath->chars, &entryStat) == 0;

        ffStrbufSubstrBefore(basePath, basePathLength);

        if (!ret || deviceStat->st_ino != entryStat.st_ino) {
            continue;
        }

        ffStrbufAppendS(&disk->name, entry->d_name);
        break;
    }
}

static void detectName(FFDisk* disk) {
    struct stat deviceStat;
    if (stat(disk->mountFrom.chars, &deviceStat) != 0) {
        return;
    }

    FF_STRBUF_AUTO_DESTROY basePath = ffStrbufCreate();

    // Try label first
    ffStrbufSetS(&basePath, "/dev/disk/by-label/");
    detectNameFromPath(disk, &deviceStat, &basePath);

    if (disk->name.length == 0) {
        // Try partlabel second
        ffStrbufSetS(&basePath, "/dev/disk/by-partlabel/");
        detectNameFromPath(disk, &deviceStat, &basePath);
    }

    if (disk->name.length == 0) {
        return;
    }

    ffStrbufDecodeHexEscapeSequences(&disk->name);
}

#ifdef __ANDROID__

static void detectType(FF_A_UNUSED const FFlist* disks, FFDisk* currentDisk, FF_A_UNUSED struct mntent* device) {
    if (ffStrbufEqualS(&currentDisk->mountpoint, "/") || ffStrbufEqualS(&currentDisk->mountpoint, "/storage/emulated")) {
        currentDisk->type = FF_DISK_VOLUME_TYPE_REGULAR_BIT;
    } else if (ffStrbufStartsWithS(&currentDisk->mountpoint, "/mnt/media_rw/")) {
        currentDisk->type = FF_DISK_VOLUME_TYPE_EXTERNAL_BIT;
    } else {
        currentDisk->type = FF_DISK_VOLUME_TYPE_HIDDEN_BIT;
    }
}

#else

static bool isSubvolume(const FFlist* disks, FFDisk* currentDisk) {
    if (ffStrbufEqualS(&currentDisk->mountFrom, "drvfs")) { // WSL Windows drives
        return false;
    }

    if (ffStrbufEqualS(&currentDisk->filesystem, "zfs")) {
        // ZFS subvolumes
        uint32_t index = ffStrbufFirstIndexC(&currentDisk->mountFrom, '/');
        if (index == currentDisk->mountFrom.length) {
            return false;
        }

        FF_STRBUF_AUTO_DESTROY zpoolName = ffStrbufCreateNS(index, currentDisk->mountFrom.chars);
        for (uint32_t i = 0; i < disks->length - 1; i++) {
            const FFDisk* otherDevice = FF_LIST_GET(FFDisk, *disks, i);
            if (ffStrbufEqualS(&otherDevice->filesystem, "zfs") && ffStrbufStartsWith(&otherDevice->mountFrom, &zpoolName)) {
                return true;
            }
        }

        return false;
    } else {
        // Filter all disks which device was already found. This catches BTRFS subvolumes.
        for (uint32_t i = 0; i < disks->length - 1; i++) {
            const FFDisk* otherDevice = FF_LIST_GET(FFDisk, *disks, i);

            if (ffStrbufEqual(&currentDisk->mountFrom, &otherDevice->mountFrom)) {
                return true;
            }
        }
    }

    return false;
}

static bool isRemovable(FFDisk* currentDisk) {
    if (!ffStrbufStartsWithS(&currentDisk->mountFrom, "/dev/")) {
        return false;
    }

    char sysBlockPartition[64];
    snprintf(sysBlockPartition, ARRAY_SIZE(sysBlockPartition), "/sys/class/block/%s", currentDisk->mountFrom.chars + strlen("/dev/"));

    char sysBlockVolume[PATH_MAX]; // /sys/devices/pci0000:00/0000:00:14.0/usb4/4-3/4-3:1.0/host0/target0:0:0/0:0:0:0/block/sda/sda1
    if (realpath(sysBlockPartition, sysBlockVolume) == NULL) {
        return false;
    }
    char* lastSlash = strrchr(sysBlockVolume, '/');
    if (lastSlash == NULL) {
        return false;
    }
    strcpy(lastSlash + 1, "removable");

    char removableChar = '0';
    return ffReadFileData(sysBlockVolume, 1, &removableChar) > 0 && removableChar == '1';
}

static void detectType(const FFlist* disks, FFDisk* currentDisk, struct mntent* device) {
    if (hasmntopt(device, "x-gvfs-hide") || hasmntopt(device, "hidden")) {
        currentDisk->type = FF_DISK_VOLUME_TYPE_HIDDEN_BIT;
    } else if (isSubvolume(disks, currentDisk)) {
        currentDisk->type = FF_DISK_VOLUME_TYPE_SUBVOLUME_BIT;
    } else if (isRemovable(currentDisk)) {
        currentDisk->type = FF_DISK_VOLUME_TYPE_EXTERNAL_BIT;
    } else {
        currentDisk->type = FF_DISK_VOLUME_TYPE_REGULAR_BIT;
    }
    if (hasmntopt(device, MNTOPT_RO)) {
        currentDisk->type |= FF_DISK_VOLUME_TYPE_READONLY_BIT;
    }
}

#endif

static void detectStats(FFDisk* disk) {
    struct statvfs fs;
    if (statvfs(disk->mountpoint.chars, &fs) != 0) {
        memset(&fs, 0, sizeof(fs)); // Set all values to 0, so our values get initialized to 0 too
    }

    disk->bytesTotal = fs.f_blocks * (uint64_t) fs.f_frsize;
    disk->bytesFree = fs.f_bfree * (uint64_t) fs.f_frsize;
    disk->bytesAvailable = fs.f_bavail * (uint64_t) fs.f_frsize;
    disk->bytesUsed = 0; // To be filled in ./disk.c

    if (fs.f_files >= fs.f_ffree) {
        disk->filesTotal = (uint32_t) fs.f_files;
        disk->filesUsed = (uint32_t) (disk->filesTotal - fs.f_ffree);
    } else {
        // Windows filesystem in WSL
        disk->filesTotal = disk->filesUsed = 0;
    }

    disk->createTime = 0;
#ifdef SYS_statx
    struct statx stx;
    if (syscall(SYS_statx, 0, disk->mountpoint.chars, 0, STATX_BTIME, &stx) == 0 && (stx.stx_mask & STATX_BTIME) && stx.stx_btime.tv_sec > 685065600 /*birth of Linux*/) {
        disk->createTime = (uint64_t) ((stx.stx_btime.tv_sec * 1000) + (stx.stx_btime.tv_nsec / 1000000));
    }
#endif

#ifdef __ANDROID__ // hasmntopt requires a higher Android API level
    if (fs.f_flag & ST_RDONLY) {
        disk->type |= FF_DISK_VOLUME_TYPE_READONLY_BIT;
    }
#endif
}

const char* ffDetectDisksImpl(FFDiskOptions* options, FFlist* disks) {
    FILE* mountsFile = setmntent("/proc/mounts", "r");
    if (mountsFile == NULL) {
        return "setmntent(\"/proc/mounts\", \"r\") == NULL";
    }

    struct mntent* device;

    while ((device = getmntent(mountsFile))) {
        if (__builtin_expect(options->folders.length > 0, false)) {
            if (!ffStrbufSeparatedContainS(&options->folders, device->mnt_dir, FF_DISK_FOLDER_SEPARATOR)) {
                continue;
            }
        } else if (!isPhysicalDevice(device)) {
            continue;
        }

        if (options->hideFolders.length && ffDiskMatchesFolderPatterns(&options->hideFolders, device->mnt_dir, FF_DISK_FOLDER_SEPARATOR)) {
            continue;
        }

        if (options->hideFS.length && ffStrbufSeparatedContainS(&options->hideFS, device->mnt_type, ':')) {
            continue;
        }

        // We have a valid device, add it to the list
        FFDisk* disk = FF_LIST_ADD(FFDisk, *disks);
        disk->type = FF_DISK_VOLUME_TYPE_NONE;

        // detect mountFrom
        ffStrbufInitS(&disk->mountFrom, device->mnt_fsname);

        // detect mountpoint
        ffStrbufInitS(&disk->mountpoint, device->mnt_dir);

        // detect filesystem
        ffStrbufInitS(&disk->filesystem, device->mnt_type);

        // detect name
        ffStrbufInit(&disk->name);
        detectName(disk); // Also detects external devices

        // detect type
        detectType(disks, disk, device);

        // Detects stats
        detectStats(disk);
    }

    endmntent(mountsFile);

    return NULL;
}