blob: f23376b0651045643564dcce29b242f43db05eba [file] [log] [blame]
Elliott Hughes63a31922016-06-09 17:41:22 -07001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "mounts.h"
18
19#include <errno.h>
20#include <fcntl.h>
21#include <mntent.h>
22#include <stdio.h>
23#include <stdlib.h>
24#include <string.h>
25#include <sys/mount.h>
26
27#include <string>
28#include <vector>
29
30struct MountedVolume {
31 std::string device;
32 std::string mount_point;
33 std::string filesystem;
34 std::string flags;
35};
36
37std::vector<MountedVolume*> g_mounts_state;
38
39bool scan_mounted_volumes() {
40 for (size_t i = 0; i < g_mounts_state.size(); ++i) {
41 delete g_mounts_state[i];
42 }
43 g_mounts_state.clear();
44
45 // Open and read mount table entries.
46 FILE* fp = setmntent("/proc/mounts", "re");
47 if (fp == NULL) {
48 return false;
49 }
50 mntent* e;
51 while ((e = getmntent(fp)) != NULL) {
52 MountedVolume* v = new MountedVolume;
53 v->device = e->mnt_fsname;
54 v->mount_point = e->mnt_dir;
55 v->filesystem = e->mnt_type;
56 v->flags = e->mnt_opts;
57 g_mounts_state.push_back(v);
58 }
59 endmntent(fp);
60 return true;
61}
62
63MountedVolume* find_mounted_volume_by_device(const char* device) {
64 for (size_t i = 0; i < g_mounts_state.size(); ++i) {
65 if (g_mounts_state[i]->device == device) return g_mounts_state[i];
66 }
67 return nullptr;
68}
69
70MountedVolume* find_mounted_volume_by_mount_point(const char* mount_point) {
71 for (size_t i = 0; i < g_mounts_state.size(); ++i) {
72 if (g_mounts_state[i]->mount_point == mount_point) return g_mounts_state[i];
73 }
74 return nullptr;
75}
76
77int unmount_mounted_volume(MountedVolume* volume) {
78 // Intentionally pass the empty string to umount if the caller tries
79 // to unmount a volume they already unmounted using this
80 // function.
81 std::string mount_point = volume->mount_point;
82 volume->mount_point.clear();
83 return umount(mount_point.c_str());
84}
85
86int remount_read_only(MountedVolume* volume) {
87 return mount(volume->device.c_str(), volume->mount_point.c_str(), volume->filesystem.c_str(),
88 MS_NOATIME | MS_NODEV | MS_NODIRATIME | MS_RDONLY | MS_REMOUNT, 0);
89}