umount.c revision 52340
1/*-
2 * Copyright (c) 1980, 1989, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *	This product includes software developed by the University of
16 *	California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34#ifndef lint
35static const char copyright[] =
36"@(#) Copyright (c) 1980, 1989, 1993\n\
37	The Regents of the University of California.  All rights reserved.\n";
38#endif /* not lint */
39
40#ifndef lint
41#if 0
42static char sccsid[] = "@(#)umount.c	8.8 (Berkeley) 5/8/95";
43#endif
44static const char rcsid[] =
45  "$FreeBSD: head/sbin/umount/umount.c 52340 1999-10-17 16:26:58Z green $";
46#endif /* not lint */
47
48#include <sys/param.h>
49#include <sys/mount.h>
50
51#include <netdb.h>
52#include <rpc/rpc.h>
53#include <nfs/rpcv2.h>
54
55#include <err.h>
56#include <fstab.h>
57#include <stdio.h>
58#include <stdlib.h>
59#include <string.h>
60#include <unistd.h>
61
62#define ISDOT(x)	((x)[0] == '.' && (x)[1] == '\0')
63#define ISDOTDOT(x)	((x)[0] == '.' && (x)[1] == '.' && (x)[2] == '\0')
64
65typedef enum { MNTON, MNTFROM, NOTHING } mntwhat;
66typedef enum { MARK, UNMARK, NAME, COUNT, FREE } dowhat;
67
68int	fflag, vflag, count;
69char   *nfshost;
70
71void	 checkmntlist (char *, char **, char **, char **);
72int	 checkvfsname (const char *, char **);
73char	*getmntname (const char *, const char *,
74	 mntwhat, char **, dowhat);
75char 	*getrealname(char *, char *resolved_path);
76char   **makevfslist (const char *);
77size_t	 mntinfo (struct statfs **);
78int	 namematch (struct hostent *);
79int	 selected (int);
80int	 umountall (char **);
81int	 umountfs (char *, char **);
82void	 usage (void);
83int	 xdr_dir (XDR *, char *);
84
85int
86main(int argc, char *argv[])
87{
88	int all, errs, ch, mntsize;
89	char **typelist = NULL, *mntonname, *mntfromname;
90	char *type, *mntfromnamerev, *mntonnamerev;
91	struct statfs *mntbuf;
92
93	/* Start disks transferring immediately. */
94	sync();
95
96	all = count = errs = 0;
97	while ((ch = getopt(argc, argv, "Aafh:t:v")) != -1)
98		switch (ch) {
99		case 'A':
100			all = 2;
101			break;
102		case 'a':
103			all = 1;
104			break;
105		case 'f':
106			fflag = MNT_FORCE;
107			break;
108		case 'h':	/* -h implies -A. */
109			all = 2;
110			nfshost = optarg;
111			break;
112		case 't':
113			if (typelist != NULL)
114				err(1, "only one -t option may be specified");
115			typelist = makevfslist(optarg);
116			break;
117		case 'v':
118			vflag = 1;
119			break;
120		default:
121			usage();
122			/* NOTREACHED */
123		}
124	argc -= optind;
125	argv += optind;
126
127	if ((argc == 0 && !all) || (argc != 0 && all))
128		usage();
129
130	/* -h implies "-t nfs" if no -t flag. */
131	if ((nfshost != NULL) && (typelist == NULL))
132		typelist = makevfslist("nfs");
133
134	switch (all) {
135	case 2:
136		if ((mntsize = mntinfo(&mntbuf)) <= 0)
137			break;
138		/*
139		 * We unmount the nfs-mounts in the reverse order
140		 * that they were mounted.
141		 */
142		for (errs = 0, mntsize--; mntsize > 0; mntsize--) {
143			if (checkvfsname(mntbuf[mntsize].f_fstypename,
144			    typelist))
145				continue;
146			/*
147			 * Check if a mountpoint is laid over by another mount.
148			 * A warning will be printed to stderr if this is
149			 * the case. The laid over mount remains unmounted.
150			 */
151			mntonname = mntbuf[mntsize].f_mntonname;
152			mntfromname = mntbuf[mntsize].f_mntfromname;
153			mntonnamerev = getmntname(getmntname(mntonname,
154			    NULL, MNTFROM, &type, NAME), NULL,
155			    MNTON, &type, NAME);
156
157			mntfromnamerev = getmntname(mntonnamerev,
158			    NULL, MNTFROM, &type, NAME);
159
160			if (strcmp(mntonnamerev, mntonname) == 0 &&
161			    strcmp(mntfromnamerev, mntfromname ) != 0)
162				warnx("cannot umount %s, %s\n        "
163				    "is mounted there, umount it first",
164				    mntonname, mntfromnamerev);
165
166			if (umountfs(mntbuf[mntsize].f_mntonname,
167			    typelist) != 0)
168				errs = 1;
169		}
170		free(mntbuf);
171		break;
172	case 1:
173		if (setfsent() == 0)
174			err(1, "%s", _PATH_FSTAB);
175		errs = umountall(typelist);
176		break;
177	case 0:
178		for (errs = 0; *argv != NULL; ++argv)
179			if (umountfs(*argv, typelist) != 0)
180				errs = 1;
181		break;
182	}
183	(void)getmntname(NULL, NULL, NOTHING, NULL, FREE);
184	exit(errs);
185}
186
187int
188umountall(char **typelist)
189{
190	struct fstab *fs;
191	int rval;
192	char *cp;
193	struct vfsconf vfc;
194
195	if ((fs = getfsent()) != NULL)
196		errx(1, "fstab reading failure");
197	do {
198		/* Ignore the root. */
199		if (strcmp(fs->fs_file, "/") == 0)
200			continue;
201		/*
202		 * !!!
203		 * Historic practice: ignore unknown FSTAB_* fields.
204		 */
205		if (strcmp(fs->fs_type, FSTAB_RW) &&
206		    strcmp(fs->fs_type, FSTAB_RO) &&
207		    strcmp(fs->fs_type, FSTAB_RQ))
208			continue;
209		/* If an unknown file system type, complain. */
210		if (getvfsbyname(fs->fs_vfstype, &vfc) == -1) {
211			warnx("%s: unknown mount type", fs->fs_vfstype);
212			continue;
213		}
214		if (checkvfsname(fs->fs_vfstype, typelist))
215			continue;
216
217		/*
218		 * We want to unmount the file systems in the reverse order
219		 * that they were mounted.  So, we save off the file name
220		 * in some allocated memory, and then call recursively.
221		 */
222		if ((cp = malloc((size_t)strlen(fs->fs_file) + 1)) == NULL)
223			err(1, "malloc failed");
224		(void)strcpy(cp, fs->fs_file);
225		rval = umountall(typelist);
226		return (umountfs(cp, typelist) || rval);
227	} while ((fs = getfsent()) != NULL);
228	free(cp);
229	return (0);
230}
231
232int
233umountfs(char *name, char **typelist)
234{
235	enum clnt_stat clnt_stat;
236	struct hostent *hp;
237	struct sockaddr_in saddr;
238	struct timeval pertry, try;
239	CLIENT *clp;
240	size_t len;
241	int so, speclen;
242	char *mntonname, *mntfromname;
243	char *mntfromnamerev, *mntonnamerev;
244	char *nfsdirname, *orignfsdirname;
245	char *resolved, realname[MAXPATHLEN + 1];
246	char *type, *delimp, *hostp, *origname;
247
248	mntfromname = mntonname = delimp = hostp = orignfsdirname = NULL;
249
250	/*
251	 * 1. Check if the name exists in the mounttable.
252	 */
253	(void)checkmntlist(name, &mntfromname, &mntonname, &type);
254	/*
255	 * 2. Remove trailing slashes if there are any. After that
256	 * we look up the name in the mounttable again.
257	 */
258	if (mntfromname == NULL && mntonname == NULL) {
259		speclen = strlen(name);
260		for (speclen = strlen(name);
261		    speclen > 1 && name[speclen - 1] == '/';
262		    speclen--)
263			name[speclen - 1] = '\0';
264		(void)checkmntlist(name, &mntfromname, &mntonname, &type);
265		resolved = name;
266		/* Save off original name in origname */
267		if ((origname = strdup(name)) == NULL)
268			err(1, "strdup");
269		/*
270		 * 3. Check if the deprecated nfs-syntax with an '@'
271		 * has been used and translate it to the ':' syntax.
272		 * Look up the name in the mounttable again.
273		 */
274		if (mntfromname == NULL && mntonname == NULL) {
275			if ((delimp = strrchr(name, '@')) != NULL) {
276				hostp = delimp + 1;
277				if (*hostp != '\0') {
278					/*
279					 * Make both '@' and ':'
280					 * notations equal
281					 */
282					char *host = strdup(hostp);
283					len = strlen(hostp);
284					if (host == NULL)
285						err(1, "strdup");
286					memmove(name + len + 1, name,
287					    (size_t)(delimp - name));
288					name[len] = ':';
289					memmove(name, host, len);
290					free(host);
291				}
292				for (speclen = strlen(name);
293				    speclen > 1 && name[speclen - 1] == '/';
294				    speclen--)
295					name[speclen - 1] = '\0';
296				name[len + speclen + 1] = '\0';
297				(void)checkmntlist(name, &mntfromname,
298				    &mntonname, &type);
299				resolved = name;
300			}
301			/*
302			 * 4. Check if a relative mountpoint has been
303			 * specified. This should happen as last check,
304			 * the order is important. To prevent possible
305			 * nfs-hangs, we just call realpath(3) on the
306			 * basedir of mountpoint and add the dirname again.
307			 * Check the name in mounttable one last time.
308			 */
309			if (mntfromname == NULL && mntonname == NULL) {
310				(void)strcpy(name, origname);
311				if ((getrealname(name, realname)) != NULL) {
312					(void)checkmntlist(realname,
313					    &mntfromname, &mntonname, &type);
314					resolved = realname;
315				}
316				/*
317				 * All tests failed, return to main()
318				 */
319				if (mntfromname == NULL && mntonname == NULL) {
320					(void)strcpy(name, origname);
321					warnx("%s: not currently mounted",
322					    origname);
323					free(origname);
324					return (1);
325				}
326			}
327		}
328		free(origname);
329	} else
330		resolved = name;
331
332	if (checkvfsname(type, typelist))
333		return (1);
334
335	hp = NULL;
336	nfsdirname = NULL;
337	if (!strcmp(type, "nfs")) {
338		if ((nfsdirname = strdup(mntfromname)) == NULL)
339			err(1, "strdup");
340		orignfsdirname = nfsdirname;
341		if ((delimp = strchr(nfsdirname, ':')) != NULL) {
342			*delimp = '\0';
343			hostp = nfsdirname;
344			if ((hp = gethostbyname(hostp)) == NULL) {
345				warnx("can't get net id for host");
346			}
347			nfsdirname = delimp + 1;
348		}
349	}
350	/*
351	 * Check if the reverse entrys of the mounttable are really the
352	 * same as the normal ones.
353	 */
354	if ((mntfromnamerev = strdup(getmntname(getmntname(mntfromname,
355	    NULL, MNTON, &type, NAME), NULL,
356	    MNTFROM, &type, NAME))) == NULL)
357		err(1, "strdup");
358	if ((mntonnamerev = strdup(getmntname(mntfromnamerev, NULL,
359	    MNTON, &type, NAME))) == NULL)
360		err(1, "strdup");
361	/*
362	 * Mark the uppermost mount as unmounted.
363	 */
364	(void)getmntname(mntfromnamerev, mntonnamerev, NOTHING, &type, MARK);
365	/*
366	 * If several equal mounts are in the mounttable, check the order
367	 * and warn the user if necessary.
368	 */
369	if (strcmp(mntfromnamerev, mntfromname ) != 0 &&
370	    strcmp(resolved, mntonname) != 0) {
371		warnx("cannot umount %s, %s\n        "
372		    "is mounted there, umount it first",
373		    mntonname, mntfromnamerev);
374
375		/* call getmntname again to set mntcheck[i] to 0 */
376		(void)getmntname(mntfromnamerev, mntonnamerev,
377		    NOTHING, &type, UNMARK);
378		return (1);
379	}
380	free(mntonnamerev);
381	free(mntfromnamerev);
382	/*
383	 * Check if we have to start the rpc-call later.
384	 * If there are still identical nfs-names mounted,
385	 * we skip the rpc-call. Obviously this has to
386	 * happen before unmount(2), but it should happen
387	 * after the previous namecheck.
388	 */
389	if (!strcmp(type, "nfs")) {
390		if (getmntname(mntfromname, NULL, NOTHING,
391		    &type, COUNT) == NULL)
392			count = 1;
393	}
394	else
395		count = 0;
396	if (!namematch(hp))
397		return (1);
398	if (unmount(mntonname, fflag) != 0 ) {
399		warn("unmount of %s failed", mntonname);
400		return (1);
401	}
402	if (vflag)
403		(void)printf("%s: unmount from %s\n", mntfromname, mntonname);
404	/*
405	 * Report to mountd-server which nfsname
406	 * has been unmounted.
407	 */
408	if (hp != NULL && !(fflag & MNT_FORCE) && count == 0) {
409		memset(&saddr, 0, sizeof(saddr));
410		saddr.sin_family = AF_INET;
411		saddr.sin_port = 0;
412		memmove(&saddr.sin_addr, hp->h_addr,
413		    MIN(hp->h_length, sizeof(saddr.sin_addr)));
414		pertry.tv_sec = 3;
415		pertry.tv_usec = 0;
416		so = RPC_ANYSOCK;
417		if ((clp = clntudp_create(&saddr,
418		    RPCPROG_MNT, RPCMNT_VER1, pertry, &so)) == NULL) {
419			clnt_pcreateerror("Cannot MNT PRC");
420			return (1);
421		}
422		clp->cl_auth = authunix_create_default();
423		try.tv_sec = 20;
424		try.tv_usec = 0;
425		clnt_stat = clnt_call(clp, RPCMNT_UMOUNT, xdr_dir,
426		    nfsdirname, xdr_void, (caddr_t)0, try);
427		if (clnt_stat != RPC_SUCCESS) {
428			clnt_perror(clp, "Bad MNT RPC");
429			return (1);
430		}
431		free(orignfsdirname);
432		auth_destroy(clp->cl_auth);
433		clnt_destroy(clp);
434	}
435	return (0);
436}
437
438char *
439getmntname(const char *fromname, const char *onname,
440    mntwhat what, char **type, dowhat mark)
441{
442	static struct statfs *mntbuf;
443	static size_t mntsize = 0;
444	static char *mntcheck = NULL;
445	static char *mntcount = NULL;
446	int i, count;
447
448	if (mntsize <= 0) {
449		if ((mntsize = mntinfo(&mntbuf)) <= 0)
450			return (NULL);
451	}
452	if (mntcheck == NULL) {
453		if ((mntcheck = calloc(mntsize + 1, sizeof(int))) == NULL ||
454		    (mntcount = calloc(mntsize + 1, sizeof(int))) == NULL)
455			err(1, "calloc");
456	}
457	/*
458	 * We want to get the file systems in the reverse order
459	 * that they were mounted. Mounted and unmounted filesystems
460	 * are marked or unmarked in a table called 'mntcheck'.
461	 * Unmount(const char *dir, int flags) does only take the
462	 * mountpoint as argument, not the destination. If we don't pay
463	 * attention to the order, it can happen that a overlaying
464	 * filesystem get's unmounted instead of the one the user
465	 * has choosen.
466	 */
467	switch (mark) {
468	case NAME:
469		/* Return only the specific name */
470		for (i = mntsize - 1; i >= 0; i--) {
471			if (fromname != NULL && what == MNTON &&
472			    !strcmp(mntbuf[i].f_mntfromname, fromname) &&
473			    mntcheck[i] != 1) {
474				if (type)
475					*type = mntbuf[i].f_fstypename;
476				return (mntbuf[i].f_mntonname);
477			}
478			if (fromname != NULL && what == MNTFROM &&
479			    !strcmp(mntbuf[i].f_mntonname, fromname) &&
480			    mntcheck[i] != 1) {
481				if (type)
482					*type = mntbuf[i].f_fstypename;
483				return (mntbuf[i].f_mntfromname);
484			}
485		}
486		return (NULL);
487	case MARK:
488		/* Mark current mount with '1' and return name */
489		for (i = mntsize - 1; i >= 0; i--) {
490			if (mntcheck[i] == 0 &&
491			    (strcmp(mntbuf[i].f_mntonname, onname) == 0) &&
492			    (strcmp(mntbuf[i].f_mntfromname, fromname) == 0)) {
493				mntcheck[i] = 1;
494				return (mntbuf[i].f_mntonname);
495			}
496		}
497		return (NULL);
498	case UNMARK:
499		/* Unmark current mount with '0' and return name */
500		for (i = 0; i < mntsize; i++) {
501			if (mntcheck[i] == 1 &&
502			    (strcmp(mntbuf[i].f_mntonname, onname) == 0) &&
503			    (strcmp(mntbuf[i].f_mntfromname, fromname) == 0)) {
504				mntcheck[i] = 0;
505				return (mntbuf[i].f_mntonname);
506			}
507		}
508		return (NULL);
509	case COUNT:
510		/* Count the equal mntfromnames */
511		count = 0;
512		for (i = mntsize - 1; i >= 0; i--) {
513			if (strcmp(mntbuf[i].f_mntfromname, fromname) == 0)
514				count++;
515		}
516		/* Mark the already unmounted mounts and return
517		 * mntfromname if count == 1. Else return NULL.
518		 */
519		for (i = mntsize - 1; i >= 0; i--) {
520			if (strcmp(mntbuf[i].f_mntfromname, fromname) == 0) {
521				if (mntcount[i] == 1)
522					count--;
523				else
524					mntcount[i] = 1;
525				if (count == 1)
526					return (mntbuf[i].f_mntonname);
527				else
528					return (NULL);
529			}
530		}
531		return (NULL);
532	case FREE:
533		free(mntbuf);
534		free(mntcheck);
535		return (NULL);
536	default:
537		return (NULL);
538	}
539}
540
541int
542namematch(struct hostent *hp)
543{
544	char *cp, **np;
545
546	if ((hp == NULL) || (nfshost == NULL))
547		return (1);
548
549	if (strcasecmp(nfshost, hp->h_name) == 0)
550		return (1);
551
552	if ((cp = strchr(hp->h_name, '.')) != NULL) {
553		*cp = '\0';
554		if (strcasecmp(nfshost, hp->h_name) == 0)
555			return (1);
556	}
557	for (np = hp->h_aliases; *np; np++) {
558		if (strcasecmp(nfshost, *np) == 0)
559			return (1);
560		if ((cp = strchr(*np, '.')) != NULL) {
561			*cp = '\0';
562			if (strcasecmp(nfshost, *np) == 0)
563				return (1);
564		}
565	}
566	return (0);
567}
568
569void
570checkmntlist(char *name, char **fromname, char **onname, char **type)
571{
572
573	*fromname = getmntname(name, NULL, MNTFROM, type, NAME);
574	if (*fromname == NULL) {
575		*onname = getmntname(name, NULL, MNTON, type, NAME);
576		if (*onname != NULL)
577			*fromname = name;
578	} else
579		*onname = name;
580}
581
582size_t
583mntinfo(struct statfs **mntbuf)
584{
585	static struct statfs *origbuf;
586	size_t bufsize;
587	int mntsize;
588
589	mntsize = getfsstat(NULL, 0l, MNT_NOWAIT);
590	if (mntsize <= 0)
591		return (0);
592	bufsize = (mntsize + 1) * sizeof(struct statfs);
593	if ((origbuf = malloc(bufsize)) == NULL)
594		err(1, "malloc");
595	mntsize = getfsstat(origbuf, (long)bufsize, MNT_NOWAIT);
596	*mntbuf = origbuf;
597	return (mntsize);
598}
599
600char *
601getrealname(char *name, char *realname)
602{
603	char *dirname;
604	int havedir;
605	size_t baselen;
606	size_t dirlen;
607
608	dirname = '\0';
609	havedir = 0;
610	if (*name == '/') {
611		if (ISDOT(name + 1) || ISDOTDOT(name + 1))
612			strcpy(realname, "/");
613		else {
614			if ((dirname = strrchr(name + 1, '/')) == NULL)
615				strncpy(realname, name, MAXPATHLEN);
616			else
617				havedir = 1;
618		}
619	} else {
620		if (ISDOT(name) || ISDOTDOT(name))
621			(void)realpath(name, realname);
622		else {
623			if ((dirname = strrchr(name, '/')) == NULL) {
624				if ((realpath(name, realname)) == NULL)
625					return (NULL);
626			} else
627				havedir = 1;
628		}
629	}
630	if (havedir) {
631		*dirname++ = '\0';
632		if (ISDOT(dirname)) {
633			*dirname = '\0';
634			if ((realpath(name, realname)) == NULL)
635				return (NULL);
636		} else if (ISDOTDOT(dirname)) {
637			*--dirname = '/';
638			if ((realpath(name, realname)) == NULL)
639				return (NULL);
640		} else {
641			if ((realpath(name, realname)) == NULL)
642				return (NULL);
643			baselen = strlen(realname);
644			dirlen = strlen(dirname);
645			if (baselen + dirlen + 1 > MAXPATHLEN)
646				return (NULL);
647			if (realname[1] == '\0') {
648				memmove(realname + 1, dirname, dirlen);
649				realname[dirlen + 1] = '\0';
650			} else {
651				realname[baselen] = '/';
652				memmove(realname + baselen + 1,
653				    dirname, dirlen);
654				realname[baselen + dirlen + 1] = '\0';
655			}
656		}
657	}
658	return (realname);
659}
660
661/*
662 * xdr routines for mount rpc's
663 */
664int
665xdr_dir(XDR *xdrsp, char *dirp)
666{
667
668	return (xdr_string(xdrsp, &dirp, RPCMNT_PATHLEN));
669}
670
671void
672usage()
673{
674
675	(void)fprintf(stderr, "%s\n%s\n",
676	    "usage: umount [-fv] special | node",
677	    "       umount -a | -A [-fv] [-h host] [-t type]");
678	exit(1);
679}
680