mount.c revision e18c0d508a6d8b4376c6f0b8c22600e5aca37f69
1/*
2 * mount.c, by rmk
3 */
4
5#include <sys/mount.h>
6#include <sys/stat.h>
7#include <fcntl.h>
8#include <errno.h>
9#include <stdio.h>
10#include <stdlib.h>
11#include <string.h>
12#include <unistd.h>
13
14#include <linux/loop.h>
15
16#define ARRAY_SIZE(x)	(sizeof(x) / sizeof(x[0]))
17
18#define DEFAULT_LOOP_DEVICE "/dev/block/loop0"
19#define LOOPDEV_MAXLEN 64
20
21struct mount_opts {
22	const char str[8];
23	unsigned long rwmask;
24	unsigned long rwset;
25	unsigned long rwnoset;
26};
27
28struct extra_opts {
29	char *str;
30	char *end;
31	int used_size;
32	int alloc_size;
33};
34
35/*
36 * These options define the function of "mount(2)".
37 */
38#define MS_TYPE	(MS_REMOUNT|MS_BIND|MS_MOVE)
39
40
41static const struct mount_opts options[] = {
42	/* name		mask		set		noset		*/
43	{ "async",	MS_SYNCHRONOUS,	0,		MS_SYNCHRONOUS	},
44	{ "atime",	MS_NOATIME,	0,		MS_NOATIME	},
45	{ "bind",	MS_TYPE,	MS_BIND,	0,		},
46	{ "dev",	MS_NODEV,	0,		MS_NODEV	},
47	{ "diratime",	MS_NODIRATIME,	0,		MS_NODIRATIME	},
48	{ "dirsync",	MS_DIRSYNC,	MS_DIRSYNC,	0		},
49	{ "exec",	MS_NOEXEC,	0,		MS_NOEXEC	},
50	{ "move",	MS_TYPE,	MS_MOVE,	0		},
51	{ "recurse",	MS_REC,		MS_REC,		0		},
52	{ "rec",	MS_REC,		MS_REC,		0		},
53	{ "remount",	MS_TYPE,	MS_REMOUNT,	0		},
54	{ "ro",		MS_RDONLY,	MS_RDONLY,	0		},
55	{ "rw",		MS_RDONLY,	0,		MS_RDONLY	},
56	{ "suid",	MS_NOSUID,	0,		MS_NOSUID	},
57	{ "sync",	MS_SYNCHRONOUS,	MS_SYNCHRONOUS,	0		},
58	{ "verbose",	MS_VERBOSE,	MS_VERBOSE,	0		},
59	{ "unbindable",	MS_UNBINDABLE,	MS_UNBINDABLE,	0		},
60	{ "private",	MS_PRIVATE,	MS_PRIVATE,	0		},
61	{ "slave",	MS_SLAVE,	MS_SLAVE,	0		},
62	{ "shared",	MS_SHARED,	MS_SHARED,	0		},
63};
64
65static void add_extra_option(struct extra_opts *extra, char *s)
66{
67	int len = strlen(s);
68	int newlen = extra->used_size + len;
69
70	if (extra->str)
71	       len++;			/* +1 for ',' */
72
73	if (newlen >= extra->alloc_size) {
74		char *new;
75
76		new = realloc(extra->str, newlen + 1);	/* +1 for NUL */
77		if (!new)
78			return;
79
80		extra->str = new;
81		extra->end = extra->str + extra->used_size;
82		extra->alloc_size = newlen;
83	}
84
85	if (extra->used_size) {
86		*extra->end = ',';
87		extra->end++;
88	}
89	strcpy(extra->end, s);
90	extra->used_size += len;
91
92}
93
94static unsigned long
95parse_mount_options(char *arg, unsigned long rwflag, struct extra_opts *extra, int* loop, char *loopdev)
96{
97	char *s;
98
99    *loop = 0;
100	while ((s = strsep(&arg, ",")) != NULL) {
101		char *opt = s;
102		unsigned int i;
103		int res, no = s[0] == 'n' && s[1] == 'o';
104
105		if (no)
106			s += 2;
107
108        if (strncmp(s, "loop=", 5) == 0) {
109            *loop = 1;
110            strlcpy(loopdev, s + 5, LOOPDEV_MAXLEN);
111            continue;
112        }
113
114        if (strcmp(s, "loop") == 0) {
115            *loop = 1;
116            strlcpy(loopdev, DEFAULT_LOOP_DEVICE, LOOPDEV_MAXLEN);
117            continue;
118        }
119		for (i = 0, res = 1; i < ARRAY_SIZE(options); i++) {
120			res = strcmp(s, options[i].str);
121
122			if (res == 0) {
123				rwflag &= ~options[i].rwmask;
124				if (no)
125					rwflag |= options[i].rwnoset;
126				else
127					rwflag |= options[i].rwset;
128			}
129			if (res <= 0)
130				break;
131		}
132
133		if (res != 0 && s[0])
134			add_extra_option(extra, opt);
135	}
136
137	return rwflag;
138}
139
140/*
141 * Mark the given block device as read-write, using the BLKROSET ioctl.
142 */
143static void fs_set_blk_rw(const char *blockdev)
144{
145    int fd;
146    int OFF = 0;
147
148    fd = open(blockdev, O_RDONLY);
149    if (fd < 0) {
150        // should never happen
151        return;
152    }
153
154    ioctl(fd, BLKROSET, &OFF);
155    close(fd);
156}
157
158static char *progname;
159
160static struct extra_opts extra;
161static unsigned long rwflag;
162
163static int
164do_mount(char *dev, char *dir, char *type, unsigned long rwflag, void *data, int loop,
165         char *loopdev)
166{
167	char *s;
168	int error = 0;
169
170    if (loop) {
171        int file_fd, device_fd;
172        int flags;
173
174        flags = (rwflag & MS_RDONLY) ? O_RDONLY : O_RDWR;
175
176        file_fd = open(dev, flags);
177        if (file_fd < 0) {
178            perror("open backing file failed");
179            return 1;
180        }
181        device_fd = open(loopdev, flags);
182        if (device_fd < 0) {
183            perror("open loop device failed");
184            close(file_fd);
185            return 1;
186        }
187        if (ioctl(device_fd, LOOP_SET_FD, file_fd) < 0) {
188            perror("ioctl LOOP_SET_FD failed");
189            close(file_fd);
190            close(device_fd);
191            return 1;
192        }
193
194        close(file_fd);
195        close(device_fd);
196        dev = loopdev;
197    }
198
199    if ((rwflag & MS_RDONLY) == 0) {
200        fs_set_blk_rw(dev);
201    }
202
203	while ((s = strsep(&type, ",")) != NULL) {
204retry:
205		if (mount(dev, dir, s, rwflag, data) == -1) {
206			error = errno;
207			/*
208			 * If the filesystem is not found, or the
209			 * superblock is invalid, try the next.
210			 */
211			if (error == ENODEV || error == EINVAL)
212				continue;
213
214			/*
215			 * If we get EACCESS, and we're trying to
216			 * mount readwrite and this isn't a remount,
217			 * try read only.
218			 */
219			if (error == EACCES &&
220			    (rwflag & (MS_REMOUNT|MS_RDONLY)) == 0) {
221				rwflag |= MS_RDONLY;
222				goto retry;
223			}
224			break;
225		}
226	}
227
228	if (error) {
229		errno = error;
230		perror("mount");
231		return 255;
232	}
233
234	return 0;
235}
236
237static int print_mounts()
238{
239    FILE* f;
240    int length;
241    char buffer[100];
242
243    f = fopen("/proc/mounts", "r");
244    if (!f) {
245        fprintf(stdout, "could not open /proc/mounts\n");
246        return -1;
247    }
248
249    do {
250        length = fread(buffer, 1, 100, f);
251        if (length > 0)
252            fwrite(buffer, 1, length, stdout);
253    } while (length > 0);
254
255    fclose(f);
256    return 0;
257}
258
259static int get_mounts_dev_dir(const char *arg, char **dev, char **dir)
260{
261	FILE *f;
262	char mount_dev[256];
263	char mount_dir[256];
264	char mount_type[256];
265	char mount_opts[256];
266	int mount_freq;
267	int mount_passno;
268	int match;
269
270	f = fopen("/proc/mounts", "r");
271	if (!f) {
272		fprintf(stdout, "could not open /proc/mounts\n");
273		return -1;
274	}
275
276	do {
277		match = fscanf(f, "%255s %255s %255s %255s %d %d\n",
278					   mount_dev, mount_dir, mount_type,
279					   mount_opts, &mount_freq, &mount_passno);
280		mount_dev[255] = 0;
281		mount_dir[255] = 0;
282		mount_type[255] = 0;
283		mount_opts[255] = 0;
284		if (match == 6 &&
285			(strcmp(arg, mount_dev) == 0 ||
286			 strcmp(arg, mount_dir) == 0)) {
287			*dev = strdup(mount_dev);
288			*dir = strdup(mount_dir);
289			fclose(f);
290			return 0;
291		}
292	} while (match != EOF);
293
294	fclose(f);
295	return -1;
296}
297
298int mount_main(int argc, char *argv[])
299{
300	char *type = NULL;
301	char *dev = NULL;
302	char *dir = NULL;
303	int c;
304	int loop = 0;
305	char loopdev[LOOPDEV_MAXLEN];
306
307	progname = argv[0];
308	rwflag = MS_VERBOSE;
309
310	// mount with no arguments is equivalent to "cat /proc/mounts"
311	if (argc == 1) return print_mounts();
312
313	do {
314		c = getopt(argc, argv, "o:rt:w");
315		if (c == EOF)
316			break;
317		switch (c) {
318		case 'o':
319			rwflag = parse_mount_options(optarg, rwflag, &extra, &loop, loopdev);
320			break;
321		case 'r':
322			rwflag |= MS_RDONLY;
323			break;
324		case 't':
325			type = optarg;
326			break;
327		case 'w':
328			rwflag &= ~MS_RDONLY;
329			break;
330		case '?':
331			fprintf(stderr, "%s: invalid option -%c\n",
332				progname, optopt);
333			exit(1);
334		}
335	} while (1);
336
337	/*
338	 * If remount, bind or move was specified, then we don't
339	 * have a "type" as such.  Use the dummy "none" type.
340	 */
341	if (rwflag & MS_TYPE)
342		type = "none";
343
344	if (optind + 2 == argc) {
345		dev = argv[optind];
346		dir = argv[optind + 1];
347	} else if (optind + 1 == argc && rwflag & MS_REMOUNT) {
348		get_mounts_dev_dir(argv[optind], &dev, &dir);
349	}
350
351	if (dev == NULL || dir == NULL || type == NULL) {
352		fprintf(stderr, "Usage: %s [-r] [-w] [-o options] [-t type] "
353			"device directory\n", progname);
354		exit(1);
355	}
356
357	return do_mount(dev, dir, type, rwflag, extra.str, loop, loopdev);
358	/* We leak dev and dir in some cases, but we're about to exit */
359}
360