umount.c revision 52440
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 52440 1999-10-23 00:54: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;
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 = 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 vfsconf vfc;
191	struct fstab *fs;
192	int rval;
193	char *cp;
194	static int firstcall = 1;
195
196	if ((fs = getfsent()) != NULL) {
197		if (firstcall)
198			errx(1, "fstab reading failure");
199		firstcall = 0;
200	}
201	do {
202		/* Ignore the root. */
203		if (strcmp(fs->fs_file, "/") == 0)
204			continue;
205		/*
206		 * !!!
207		 * Historic practice: ignore unknown FSTAB_* fields.
208		 */
209		if (strcmp(fs->fs_type, FSTAB_RW) &&
210		    strcmp(fs->fs_type, FSTAB_RO) &&
211		    strcmp(fs->fs_type, FSTAB_RQ))
212			continue;
213		/* If an unknown file system type, complain. */
214		if (getvfsbyname(fs->fs_vfstype, &vfc) == -1) {
215			warnx("%s: unknown mount type", fs->fs_vfstype);
216			continue;
217		}
218		if (checkvfsname(fs->fs_vfstype, typelist))
219			continue;
220
221		/*
222		 * We want to unmount the file systems in the reverse order
223		 * that they were mounted.  So, we save off the file name
224		 * in some allocated memory, and then call recursively.
225		 */
226		if ((cp = malloc((size_t)strlen(fs->fs_file) + 1)) == NULL)
227			err(1, "malloc failed");
228		(void)strcpy(cp, fs->fs_file);
229		rval = umountall(typelist);
230		rval = umountfs(cp, typelist) || rval;
231		free(cp);
232		return (rval);
233	} while ((fs = getfsent()) != NULL);
234	return (0);
235}
236
237int
238umountfs(char *name, char **typelist)
239{
240	enum clnt_stat clnt_stat;
241	struct hostent *hp;
242	struct sockaddr_in saddr;
243	struct timeval pertry, try;
244	CLIENT *clp;
245	size_t len;
246	int so, speclen, do_rpc;
247	char *mntonname, *mntfromname;
248	char *mntfromnamerev;
249	char *nfsdirname, *orignfsdirname;
250	char *resolved, realname[MAXPATHLEN];
251	char *type, *delimp, *hostp, *origname;
252
253	len = 0;
254	mntfromname = mntonname = delimp = hostp = orignfsdirname = NULL;
255
256	/*
257	 * 1. Check if the name exists in the mounttable.
258	 */
259	(void)checkmntlist(name, &mntfromname, &mntonname, &type);
260	/*
261	 * 2. Remove trailing slashes if there are any. After that
262	 * we look up the name in the mounttable again.
263	 */
264	if (mntfromname == NULL && mntonname == NULL) {
265		speclen = strlen(name);
266		for (speclen = strlen(name);
267		    speclen > 1 && name[speclen - 1] == '/';
268		    speclen--)
269			name[speclen - 1] = '\0';
270		(void)checkmntlist(name, &mntfromname, &mntonname, &type);
271		resolved = name;
272		/* Save off original name in origname */
273		if ((origname = strdup(name)) == NULL)
274			err(1, "strdup");
275		/*
276		 * 3. Check if the deprecated nfs-syntax with an '@'
277		 * has been used and translate it to the ':' syntax.
278		 * Look up the name in the mounttable again.
279		 */
280		if (mntfromname == NULL && mntonname == NULL) {
281			if ((delimp = strrchr(name, '@')) != NULL) {
282				hostp = delimp + 1;
283				if (*hostp != '\0') {
284					/*
285					 * Make both '@' and ':'
286					 * notations equal
287					 */
288					char *host = strdup(hostp);
289					len = strlen(hostp);
290					if (host == NULL)
291						err(1, "strdup");
292					memmove(name + len + 1, name,
293					    (size_t)(delimp - name));
294					name[len] = ':';
295					memmove(name, host, len);
296					free(host);
297				}
298				for (speclen = strlen(name);
299				    speclen > 1 && name[speclen - 1] == '/';
300				    speclen--)
301					name[speclen - 1] = '\0';
302				name[len + speclen + 1] = '\0';
303				(void)checkmntlist(name, &mntfromname,
304				    &mntonname, &type);
305				resolved = name;
306			}
307			/*
308			 * 4. Check if a relative mountpoint has been
309			 * specified. This should happen as last check,
310			 * the order is important. To prevent possible
311			 * nfs-hangs, we just call realpath(3) on the
312			 * basedir of mountpoint and add the dirname again.
313			 * Check the name in mounttable one last time.
314			 */
315			if (mntfromname == NULL && mntonname == NULL) {
316				(void)strcpy(name, origname);
317				if ((getrealname(name, realname)) != NULL) {
318					(void)checkmntlist(realname,
319					    &mntfromname, &mntonname, &type);
320					resolved = realname;
321				}
322				/*
323				 * All tests failed, return to main()
324				 */
325				if (mntfromname == NULL && mntonname == NULL) {
326					(void)strcpy(name, origname);
327					warnx("%s: not currently mounted",
328					    origname);
329					free(origname);
330					return (1);
331				}
332			}
333		}
334		free(origname);
335	} else
336		resolved = name;
337
338	if (checkvfsname(type, typelist))
339		return (1);
340
341	hp = NULL;
342	nfsdirname = NULL;
343	if (!strcmp(type, "nfs")) {
344		if ((nfsdirname = strdup(mntfromname)) == NULL)
345			err(1, "strdup");
346		orignfsdirname = nfsdirname;
347		if ((delimp = strchr(nfsdirname, ':')) != NULL) {
348			*delimp = '\0';
349			hostp = nfsdirname;
350			if ((hp = gethostbyname(hostp)) == NULL) {
351				warnx("can't get net id for host");
352			}
353			nfsdirname = delimp + 1;
354		}
355	}
356	/*
357	 * Check if the reverse entrys of the mounttable are really the
358	 * same as the normal ones.
359	 */
360	if ((mntfromnamerev = strdup(getmntname(getmntname(mntfromname,
361	    NULL, MNTON, &type, NAME), NULL, MNTFROM, &type, NAME))) == NULL)
362		err(1, "strdup");
363	/*
364	 * Mark the uppermost mount as unmounted.
365	 */
366	(void)getmntname(mntfromname, mntonname, NOTHING, &type, MARK);
367	/*
368	 * If several equal mounts are in the mounttable, check the order
369	 * and warn the user if necessary.
370	 */
371	if (strcmp(mntfromnamerev, mntfromname ) != 0 &&
372	    strcmp(resolved, mntonname) != 0) {
373		warnx("cannot umount %s, %s\n        "
374		    "is mounted there, umount it first",
375		    mntonname, mntfromnamerev);
376
377		/* call getmntname again to set mntcheck[i] to 0 */
378		(void)getmntname(mntfromname, mntonname,
379		    NOTHING, &type, UNMARK);
380		return (1);
381	}
382	free(mntfromnamerev);
383	/*
384	 * Check if we have to start the rpc-call later.
385	 * If there are still identical nfs-names mounted,
386	 * we skip the rpc-call. Obviously this has to
387	 * happen before unmount(2), but it should happen
388	 * after the previous namecheck.
389	 */
390	if (strcmp(type, "nfs") == 0 && getmntname(mntfromname, NULL, NOTHING,
391	    &type, COUNT) != NULL)
392		do_rpc = 1;
393	else
394		do_rpc = 0;
395	if (!namematch(hp))
396		return (1);
397	if (unmount(mntonname, fflag) != 0 ) {
398		warn("unmount of %s failed", mntonname);
399		return (1);
400	}
401	if (vflag)
402		(void)printf("%s: unmount from %s\n", mntfromname, mntonname);
403	/*
404	 * Report to mountd-server which nfsname
405	 * has been unmounted.
406	 */
407	if (hp != NULL && !(fflag & MNT_FORCE) && do_rpc) {
408		memset(&saddr, 0, sizeof(saddr));
409		saddr.sin_family = AF_INET;
410		saddr.sin_port = 0;
411		memmove(&saddr.sin_addr, hp->h_addr,
412		    MIN(hp->h_length, sizeof(saddr.sin_addr)));
413		pertry.tv_sec = 3;
414		pertry.tv_usec = 0;
415		so = RPC_ANYSOCK;
416		if ((clp = clntudp_create(&saddr,
417		    RPCPROG_MNT, RPCMNT_VER1, pertry, &so)) == NULL) {
418			clnt_pcreateerror("Cannot MNT PRC");
419			return (1);
420		}
421		clp->cl_auth = authunix_create_default();
422		try.tv_sec = 20;
423		try.tv_usec = 0;
424		clnt_stat = clnt_call(clp, RPCMNT_UMOUNT, xdr_dir,
425		    nfsdirname, xdr_void, (caddr_t)0, try);
426		if (clnt_stat != RPC_SUCCESS) {
427			clnt_perror(clp, "Bad MNT RPC");
428			return (1);
429		}
430		free(orignfsdirname);
431		auth_destroy(clp->cl_auth);
432		clnt_destroy(clp);
433	}
434	return (0);
435}
436
437char *
438getmntname(const char *fromname, const char *onname,
439    mntwhat what, char **type, dowhat mark)
440{
441	static struct statfs *mntbuf;
442	static size_t mntsize = 0;
443	static char *mntcheck = NULL;
444	static char *mntcount = NULL;
445	int i, count;
446
447	if (mntsize <= 0) {
448		if ((mntsize = mntinfo(&mntbuf)) <= 0)
449			return (NULL);
450	}
451	if (mntcheck == NULL) {
452		if ((mntcheck = calloc(mntsize + 1, sizeof(int))) == NULL ||
453		    (mntcount = calloc(mntsize + 1, sizeof(int))) == NULL)
454			err(1, "calloc");
455	}
456	/*
457	 * We want to get the file systems in the reverse order
458	 * that they were mounted. Mounted and unmounted filesystems
459	 * are marked or unmarked in a table called 'mntcheck'.
460	 * Unmount(const char *dir, int flags) does only take the
461	 * mountpoint as argument, not the destination. If we don't pay
462	 * attention to the order, it can happen that a overlaying
463	 * filesystem get's unmounted instead of the one the user
464	 * has choosen.
465	 */
466	switch (mark) {
467	case NAME:
468		/* Return only the specific name */
469		for (i = mntsize - 1; i >= 0; i--) {
470			if (fromname != NULL && what == MNTON &&
471			    !strcmp(mntbuf[i].f_mntfromname, fromname) &&
472			    mntcheck[i] != 1) {
473				if (type)
474					*type = mntbuf[i].f_fstypename;
475				return (mntbuf[i].f_mntonname);
476			}
477			if (fromname != NULL && what == MNTFROM &&
478			    !strcmp(mntbuf[i].f_mntonname, fromname) &&
479			    mntcheck[i] != 1) {
480				if (type)
481					*type = mntbuf[i].f_fstypename;
482				return (mntbuf[i].f_mntfromname);
483			}
484		}
485		return (NULL);
486	case MARK:
487		/* Mark current mount with '1' and return name */
488		for (i = mntsize - 1; i >= 0; i--) {
489			if (mntcheck[i] == 0 &&
490			    (strcmp(mntbuf[i].f_mntonname, onname) == 0) &&
491			    (strcmp(mntbuf[i].f_mntfromname, fromname) == 0)) {
492				mntcheck[i] = 1;
493				return (mntbuf[i].f_mntonname);
494			}
495		}
496		return (NULL);
497	case UNMARK:
498		/* Unmark current mount with '0' and return name */
499		for (i = 0; i < mntsize; i++) {
500			if (mntcheck[i] == 1 &&
501			    (strcmp(mntbuf[i].f_mntonname, onname) == 0) &&
502			    (strcmp(mntbuf[i].f_mntfromname, fromname) == 0)) {
503				mntcheck[i] = 0;
504				return (mntbuf[i].f_mntonname);
505			}
506		}
507		return (NULL);
508	case COUNT:
509		/* Count the equal mntfromnames */
510		count = 0;
511		for (i = mntsize - 1; i >= 0; i--) {
512			if (strcmp(mntbuf[i].f_mntfromname, fromname) == 0)
513				count++;
514		}
515		/* Mark the already unmounted mounts and return
516		 * mntfromname if count <= 1. Else return NULL.
517		 */
518		for (i = mntsize - 1; i >= 0; i--) {
519			if (strcmp(mntbuf[i].f_mntfromname, fromname) == 0) {
520				if (mntcount[i] == 1)
521					count--;
522				else {
523					mntcount[i] = 1;
524					break;
525				}
526			}
527		}
528		if (count <= 1)
529			return (mntbuf[i].f_mntonname);
530		else
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				snprintf(realname, MAXPATHLEN, "%s", name);
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