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
140static char *progname;
141
142static struct extra_opts extra;
143static unsigned long rwflag;
144
145static int
146do_mount(char *dev, char *dir, char *type, unsigned long rwflag, void *data, int loop,
147         char *loopdev)
148{
149	char *s;
150	int error = 0;
151
152    if (loop) {
153        int file_fd, device_fd;
154        int flags;
155
156        flags = (rwflag & MS_RDONLY) ? O_RDONLY : O_RDWR;
157
158        file_fd = open(dev, flags);
159        if (file_fd < 0) {
160            perror("open backing file failed");
161            return 1;
162        }
163        device_fd = open(loopdev, flags);
164        if (device_fd < 0) {
165            perror("open loop device failed");
166            close(file_fd);
167            return 1;
168        }
169        if (ioctl(device_fd, LOOP_SET_FD, file_fd) < 0) {
170            perror("ioctl LOOP_SET_FD failed");
171            close(file_fd);
172            close(device_fd);
173            return 1;
174        }
175
176        close(file_fd);
177        close(device_fd);
178        dev = loopdev;
179    }
180
181	while ((s = strsep(&type, ",")) != NULL) {
182retry:
183		if (mount(dev, dir, s, rwflag, data) == -1) {
184			error = errno;
185			/*
186			 * If the filesystem is not found, or the
187			 * superblock is invalid, try the next.
188			 */
189			if (error == ENODEV || error == EINVAL)
190				continue;
191
192			/*
193			 * If we get EACCESS, and we're trying to
194			 * mount readwrite and this isn't a remount,
195			 * try read only.
196			 */
197			if (error == EACCES &&
198			    (rwflag & (MS_REMOUNT|MS_RDONLY)) == 0) {
199				rwflag |= MS_RDONLY;
200				goto retry;
201			}
202			break;
203		}
204	}
205
206	if (error) {
207		errno = error;
208		perror("mount");
209		return 255;
210	}
211
212	return 0;
213}
214
215static int print_mounts()
216{
217    FILE* f;
218    int length;
219    char buffer[100];
220
221    f = fopen("/proc/mounts", "r");
222    if (!f) {
223        fprintf(stdout, "could not open /proc/mounts\n");
224        return -1;
225    }
226
227    do {
228        length = fread(buffer, 1, 100, f);
229        if (length > 0)
230            fwrite(buffer, 1, length, stdout);
231    } while (length > 0);
232
233    fclose(f);
234    return 0;
235}
236
237static int get_mounts_dev_dir(const char *arg, char **dev, char **dir)
238{
239	FILE *f;
240	char mount_dev[256];
241	char mount_dir[256];
242	char mount_type[256];
243	char mount_opts[256];
244	int mount_freq;
245	int mount_passno;
246	int match;
247
248	f = fopen("/proc/mounts", "r");
249	if (!f) {
250		fprintf(stdout, "could not open /proc/mounts\n");
251		return -1;
252	}
253
254	do {
255		match = fscanf(f, "%255s %255s %255s %255s %d %d\n",
256					   mount_dev, mount_dir, mount_type,
257					   mount_opts, &mount_freq, &mount_passno);
258		mount_dev[255] = 0;
259		mount_dir[255] = 0;
260		mount_type[255] = 0;
261		mount_opts[255] = 0;
262		if (match == 6 &&
263			(strcmp(arg, mount_dev) == 0 ||
264			 strcmp(arg, mount_dir) == 0)) {
265			*dev = strdup(mount_dev);
266			*dir = strdup(mount_dir);
267			fclose(f);
268			return 0;
269		}
270	} while (match != EOF);
271
272	fclose(f);
273	return -1;
274}
275
276int mount_main(int argc, char *argv[])
277{
278	char *type = NULL;
279	char *dev = NULL;
280	char *dir = NULL;
281	int c;
282	int loop = 0;
283	char loopdev[LOOPDEV_MAXLEN];
284
285	progname = argv[0];
286	rwflag = MS_VERBOSE;
287
288	// mount with no arguments is equivalent to "cat /proc/mounts"
289	if (argc == 1) return print_mounts();
290
291	do {
292		c = getopt(argc, argv, "o:rt:w");
293		if (c == EOF)
294			break;
295		switch (c) {
296		case 'o':
297			rwflag = parse_mount_options(optarg, rwflag, &extra, &loop, loopdev);
298			break;
299		case 'r':
300			rwflag |= MS_RDONLY;
301			break;
302		case 't':
303			type = optarg;
304			break;
305		case 'w':
306			rwflag &= ~MS_RDONLY;
307			break;
308		case '?':
309			fprintf(stderr, "%s: invalid option -%c\n",
310				progname, optopt);
311			exit(1);
312		}
313	} while (1);
314
315	/*
316	 * If remount, bind or move was specified, then we don't
317	 * have a "type" as such.  Use the dummy "none" type.
318	 */
319	if (rwflag & MS_TYPE)
320		type = "none";
321
322	if (optind + 2 == argc) {
323		dev = argv[optind];
324		dir = argv[optind + 1];
325	} else if (optind + 1 == argc && rwflag & MS_REMOUNT) {
326		get_mounts_dev_dir(argv[optind], &dev, &dir);
327	}
328
329	if (dev == NULL || dir == NULL || type == NULL) {
330		fprintf(stderr, "Usage: %s [-r] [-w] [-o options] [-t type] "
331			"device directory\n", progname);
332		exit(1);
333	}
334
335	return do_mount(dev, dir, type, rwflag, extra.str, loop, loopdev);
336	/* We leak dev and dir in some cases, but we're about to exit */
337}
338