ismounted.c revision c555aebde40afdc0d15d674f2c81c0e05cfded3f
1/*
2 * ismounted.c --- Check to see if the filesystem was mounted
3 *
4 * Copyright (C) 1995 Theodore Ts'o.
5 *
6 * %Begin-Header%
7 * This file may be redistributed under the terms of the GNU Public
8 * License.
9 * %End-Header%
10 */
11
12#include <stdio.h>
13#if HAVE_UNISTD_H
14#include <unistd.h>
15#endif
16#if HAVE_STDLIB_H
17#include <stdlib.h>
18#endif
19#include <fcntl.h>
20#ifdef HAVE_LINUX_FS_H
21#include <linux/fs.h>
22#endif
23#ifdef HAVE_LINUX_FD_H
24#include <linux/fd.h>
25#endif
26#ifdef HAVE_MNTENT_H
27#include <mntent.h>
28#endif
29#ifdef HAVE_GETMNTINFO
30#include <paths.h>
31#include <sys/param.h>
32#include <sys/mount.h>
33#endif /* HAVE_GETMNTINFO */
34
35#include <linux/ext2_fs.h>
36#include "ext2fs.h"
37
38#ifdef HAVE_MNTENT_H
39/*
40 * XXX we only check to see if the mount is readonly when it's the
41 * root filesystem.
42 */
43static errcode_t check_mntent(const char *file, int *mount_flags)
44{
45	FILE * f;
46	struct mntent * mnt;
47	int	fd;
48
49	*mount_flags = 0;
50	if ((f = setmntent (MOUNTED, "r")) == NULL)
51		return errno;
52	while ((mnt = getmntent (f)) != NULL)
53		if (strcmp(file, mnt->mnt_fsname) == 0)
54			break;
55	endmntent (f);
56	if (mnt == 0)
57		return 0;
58	*mount_flags = EXT2_MF_MOUNTED;
59
60	if (!strcmp(mnt->mnt_dir, "/")) {
61		*mount_flags |= EXT2_MF_ISROOT;
62		fd = open(MOUNTED, O_RDWR);
63		if (fd < 0) {
64			if (errno == EROFS)
65				*mount_flags |= EXT2_MF_READONLY;
66		} else
67			close(fd);
68	}
69	return 0;
70}
71#endif
72
73#ifdef HAVE_GETMNTINFO
74static errcode_t check_getmntinfo(const char *file, int *mount_flags)
75{
76	struct statfs *mp;
77        int    len, n;
78        const  char   *s1;
79	char	*s2;
80
81        n = getmntinfo(&mp, MNT_NOWAIT);
82        if (n == 0)
83		return errno;
84
85        len = sizeof(_PATH_DEV) - 1;
86        s1 = file;
87        if (strncmp(_PATH_DEV, s1, len) == 0)
88                s1 += len;
89
90	*mount_flags = 0;
91        while (--n >= 0) {
92                s2 = mp->f_mntfromname;
93                if (strncmp(_PATH_DEV, s2, len) == 0) {
94                        s2 += len - 1;
95                        *s2 = 'r';
96                }
97                if (strcmp(s1, s2) == 0 || strcmp(s1, &s2[1]) == 0) {
98			*mount_flags = EXT2_MF_MOUNTED;
99			break;
100		}
101                ++mp;
102	}
103	return 0;
104}
105#endif /* HAVE_GETMNTINFO */
106
107/*
108 * Is_mounted is set to 1 if the device is mounted, 0 otherwise
109 */
110#ifdef __TURBOC__
111#pragma argsused
112#endif
113errcode_t ext2fs_check_if_mounted(const char *file, int *mount_flags)
114{
115#ifdef HAVE_MNTENT_H
116	return check_mntent(file, mount_flags);
117#else
118#ifdef HAVE_GETMNTINFO
119	return check_getmntinfo(file, mount_flags);
120#else
121	*mount_flags = 0;
122	return 0;
123#endif /* HAVE_GETMNTINFO */
124#endif /* HAVE_MNTENT_H */
125}
126