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  */
tst_path_has_mnt_flags(void (cleanup_fn)(void),const char * path,const char * flags[])28 int 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 	}
48 
49 	f = setmntent("/proc/mounts", "r");
50 	if (f == NULL) {
51 		tst_brkm(TBROK | TERRNO, cleanup_fn,
52 			"tst_path_has_mnt_flags: failed to open /proc/mounts");
53 	}
54 
55 	while ((mnt = getmntent(f))) {
56 		/* ignore duplicit record for root fs */
57 		if (!strcmp(mnt->mnt_fsname, "rootfs"))
58 			continue;
59 
60 		prefix_len = strlen(mnt->mnt_dir);
61 
62 		if (strncmp(path, mnt->mnt_dir, prefix_len) == 0
63 				&& prefix_len > prefix_max) {
64 			prefix_max = prefix_len;
65 			flags_matched = 0;
66 			i = 0;
67 
68 			while (flags[i] != NULL) {
69 				if (hasmntopt(mnt, flags[i]) != NULL)
70 					flags_matched++;
71 				i++;
72 			}
73 		}
74 	}
75 
76 	endmntent(f);
77 
78 	free(tmpdir);
79 
80 	return flags_matched;
81 }
82