1/*
2 * Copyright (c) 2014 Fujitsu Ltd.
3 * Author: Xing Gu <gux.fnst@cn.fujitsu.com>
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of version 2 of the GNU General Public License as
7 * published by the Free Software Foundation.
8 *
9 * This program is distributed in the hope that it would be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
16 */
17
18#include <unistd.h>
19#include <mntent.h>
20#include <stdio.h>
21#include <string.h>
22#include "test.h"
23
24/*
25 * Check whether a path is on a filesystem that is mounted with
26 * specified flags.
27 */
28int tst_path_has_mnt_flags(void (cleanup_fn)(void),
29		const char *path, const char *flags[])
30{
31	struct mntent *mnt;
32	size_t prefix_max = 0, prefix_len;
33	int flags_matched = 0;
34	FILE *f;
35	int i;
36	char *tmpdir = NULL;
37
38	/*
39	 * Default parameter is test temporary directory
40	 */
41	if (path == NULL)
42		path = tmpdir = tst_get_tmpdir();
43
44	if (access(path, F_OK) == -1) {
45		tst_brkm(TBROK | TERRNO, cleanup_fn,
46			"tst_path_has_mnt_flags: path %s doesn't exist", path);
47		return -1;
48	}
49
50	f = setmntent("/proc/mounts", "r");
51	if (f == NULL) {
52		tst_brkm(TBROK | TERRNO, cleanup_fn,
53			"tst_path_has_mnt_flags: failed to open /proc/mounts");
54		return -1;
55	}
56
57	while ((mnt = getmntent(f))) {
58		/* ignore duplicit record for root fs */
59		if (!strcmp(mnt->mnt_fsname, "rootfs"))
60			continue;
61
62		prefix_len = strlen(mnt->mnt_dir);
63
64		if (strncmp(path, mnt->mnt_dir, prefix_len) == 0
65				&& prefix_len > prefix_max) {
66			prefix_max = prefix_len;
67			flags_matched = 0;
68			i = 0;
69
70			while (flags[i] != NULL) {
71				if (hasmntopt(mnt, flags[i]) != NULL)
72					flags_matched++;
73				i++;
74			}
75		}
76	}
77
78	endmntent(f);
79
80	free(tmpdir);
81
82	return flags_matched;
83}
84