xref: /freebsd/sbin/umount/umount.c (revision 3193579b66fd7067f898dbc54bdea81a0e6f9bd0)
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
35 static 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
42 static char sccsid[] = "@(#)umount.c	8.8 (Berkeley) 5/8/95";
43 #endif
44 static const char rcsid[] =
45   "$FreeBSD$";
46 #endif /* not lint */
47 
48 #include <sys/param.h>
49 #include <sys/mount.h>
50 #include <sys/socket.h>
51 #include <sys/stat.h>
52 
53 #include <netdb.h>
54 #include <rpc/rpc.h>
55 #include <nfs/rpcv2.h>
56 
57 #include <ctype.h>
58 #include <err.h>
59 #include <errno.h>
60 #include <fstab.h>
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <string.h>
64 #include <unistd.h>
65 
66 #include "mounttab.h"
67 
68 typedef enum { FIND, REMOVE, CHECKUNIQUE } dowhat;
69 
70 struct  addrinfo *nfshost_ai = NULL;
71 int	fflag, vflag;
72 char   *nfshost;
73 
74 struct statfs *checkmntlist(char *);
75 int	 checkvfsname (const char *, char **);
76 struct statfs *getmntentry(const char *fromname, const char *onname,
77 	     fsid_t *fsid, dowhat what);
78 char   **makevfslist (const char *);
79 size_t	 mntinfo (struct statfs **);
80 int	 namematch (struct addrinfo *);
81 int	 parsehexfsid(const char *hex, fsid_t *fsid);
82 int	 sacmp (struct sockaddr *, struct sockaddr *);
83 int	 umountall (char **);
84 int	 checkname (char *, char **);
85 int	 umountfs(struct statfs *sfs);
86 void	 usage (void);
87 int	 xdr_dir (XDR *, char *);
88 
89 int
90 main(int argc, char *argv[])
91 {
92 	int all, errs, ch, mntsize, error;
93 	char **typelist = NULL;
94 	struct statfs *mntbuf, *sfs;
95 	struct addrinfo hints;
96 
97 	/* Start disks transferring immediately. */
98 	sync();
99 
100 	all = errs = 0;
101 	while ((ch = getopt(argc, argv, "AaF:fh:t:v")) != -1)
102 		switch (ch) {
103 		case 'A':
104 			all = 2;
105 			break;
106 		case 'a':
107 			all = 1;
108 			break;
109 		case 'F':
110 			setfstab(optarg);
111 			break;
112 		case 'f':
113 			fflag = MNT_FORCE;
114 			break;
115 		case 'h':	/* -h implies -A. */
116 			all = 2;
117 			nfshost = optarg;
118 			break;
119 		case 't':
120 			if (typelist != NULL)
121 				err(1, "only one -t option may be specified");
122 			typelist = makevfslist(optarg);
123 			break;
124 		case 'v':
125 			vflag = 1;
126 			break;
127 		default:
128 			usage();
129 			/* NOTREACHED */
130 		}
131 	argc -= optind;
132 	argv += optind;
133 
134 	if ((argc == 0 && !all) || (argc != 0 && all))
135 		usage();
136 
137 	/* -h implies "-t nfs" if no -t flag. */
138 	if ((nfshost != NULL) && (typelist == NULL))
139 		typelist = makevfslist("nfs");
140 
141 	if (nfshost != NULL) {
142 		memset(&hints, 0, sizeof hints);
143 		error = getaddrinfo(nfshost, NULL, &hints, &nfshost_ai);
144 		if (error)
145 			errx(1, "%s: %s", nfshost, gai_strerror(error));
146 	}
147 
148 	switch (all) {
149 	case 2:
150 		if ((mntsize = mntinfo(&mntbuf)) <= 0)
151 			break;
152 		/*
153 		 * We unmount the nfs-mounts in the reverse order
154 		 * that they were mounted.
155 		 */
156 		for (errs = 0, mntsize--; mntsize > 0; mntsize--) {
157 			sfs = &mntbuf[mntsize];
158 			if (checkvfsname(sfs->f_fstypename, typelist))
159 				continue;
160 			if (umountfs(sfs) != 0)
161 				errs = 1;
162 		}
163 		free(mntbuf);
164 		break;
165 	case 1:
166 		if (setfsent() == 0)
167 			err(1, "%s", getfstab());
168 		errs = umountall(typelist);
169 		break;
170 	case 0:
171 		for (errs = 0; *argv != NULL; ++argv)
172 			if (checkname(*argv, typelist) != 0)
173 				errs = 1;
174 		break;
175 	}
176 	exit(errs);
177 }
178 
179 int
180 umountall(char **typelist)
181 {
182 	struct xvfsconf vfc;
183 	struct fstab *fs;
184 	int rval;
185 	char *cp;
186 	static int firstcall = 1;
187 
188 	if ((fs = getfsent()) != NULL)
189 		firstcall = 0;
190 	else if (firstcall)
191 		errx(1, "fstab reading failure");
192 	else
193 		return (0);
194 	do {
195 		/* Ignore the root. */
196 		if (strcmp(fs->fs_file, "/") == 0)
197 			continue;
198 		/*
199 		 * !!!
200 		 * Historic practice: ignore unknown FSTAB_* fields.
201 		 */
202 		if (strcmp(fs->fs_type, FSTAB_RW) &&
203 		    strcmp(fs->fs_type, FSTAB_RO) &&
204 		    strcmp(fs->fs_type, FSTAB_RQ))
205 			continue;
206 		/* Ignore unknown file system types. */
207 		if (getvfsbyname(fs->fs_vfstype, &vfc) == -1)
208 			continue;
209 		if (checkvfsname(fs->fs_vfstype, typelist))
210 			continue;
211 
212 		/*
213 		 * We want to unmount the file systems in the reverse order
214 		 * that they were mounted.  So, we save off the file name
215 		 * in some allocated memory, and then call recursively.
216 		 */
217 		if ((cp = malloc((size_t)strlen(fs->fs_file) + 1)) == NULL)
218 			err(1, "malloc failed");
219 		(void)strcpy(cp, fs->fs_file);
220 		rval = umountall(typelist);
221 		rval = checkname(cp, typelist) || rval;
222 		free(cp);
223 		return (rval);
224 	} while ((fs = getfsent()) != NULL);
225 	return (0);
226 }
227 
228 /*
229  * Do magic checks on mountpoint/device/fsid, and then call unmount(2).
230  */
231 int
232 checkname(char *name, char **typelist)
233 {
234 	char buf[MAXPATHLEN];
235 	struct statfs sfsbuf;
236 	struct stat sb;
237 	struct statfs *sfs;
238 	char *delimp;
239 	dev_t dev;
240 	int len;
241 
242 	/*
243 	 * 1. Check if the name exists in the mounttable.
244 	 */
245 	sfs = checkmntlist(name);
246 	/*
247 	 * 2. Remove trailing slashes if there are any. After that
248 	 * we look up the name in the mounttable again.
249 	 */
250 	if (sfs == NULL) {
251 		len = strlen(name);
252 		while (len > 1 && name[len - 1] == '/')
253 			name[--len] = '\0';
254 		sfs = checkmntlist(name);
255 	}
256 	/*
257 	 * 3. Check if the deprecated NFS syntax with an '@' has been used
258 	 * and translate it to the ':' syntax. Look up the name in the
259 	 * mount table again.
260 	 */
261 	if (sfs == NULL && (delimp = strrchr(name, '@')) != NULL) {
262 		snprintf(buf, sizeof(buf), "%s:%.*s", delimp + 1, delimp - name,
263 		    name);
264 		len = strlen(buf);
265 		while (len > 1 && buf[len - 1] == '/')
266 			buf[--len] = '\0';
267 		sfs = checkmntlist(buf);
268 	}
269 	/*
270 	 * 4. Resort to a statfs(2) call. This is the last check so that
271 	 * hung NFS filesystems for example can be unmounted without
272 	 * potentially blocking forever in statfs() as long as the
273 	 * filesystem is specified unambiguously. This covers all the
274 	 * hard cases such as symlinks and mismatches between the
275 	 * mount list and reality.
276 	 * We also do this if an ambiguous mount point was specified.
277 	 */
278 	if (sfs == NULL || (getmntentry(NULL, name, NULL, FIND) != NULL &&
279 	    getmntentry(NULL, name, NULL, CHECKUNIQUE) == NULL)) {
280 		if (statfs(name, &sfsbuf) != 0) {
281 			warn("%s: statfs", name);
282 		} else if (stat(name, &sb) != 0) {
283 			warn("%s: stat", name);
284 		} else if (S_ISDIR(sb.st_mode)) {
285 			/* Check that `name' is the root directory. */
286 			dev = sb.st_dev;
287 			snprintf(buf, sizeof(buf), "%s/..", name);
288 			if (stat(buf, &sb) != 0) {
289 				warn("%s: stat", buf);
290 			} else if (sb.st_dev == dev) {
291 				warnx("%s: not a file system root directory",
292 				    name);
293 				return (1);
294 			} else
295 				sfs = &sfsbuf;
296 		}
297 	}
298 	if (sfs == NULL) {
299 		warnx("%s: unknown file system", name);
300 		return (1);
301 	}
302 	if (checkvfsname(sfs->f_fstypename, typelist))
303 		return (1);
304 	return (umountfs(sfs));
305 }
306 
307 /*
308  * NFS stuff and unmount(2) call
309  */
310 int
311 umountfs(struct statfs *sfs)
312 {
313 	char fsidbuf[64];
314 	enum clnt_stat clnt_stat;
315 	struct timeval try;
316 	struct addrinfo *ai, hints;
317 	int do_rpc;
318 	CLIENT *clp;
319 	char *nfsdirname, *orignfsdirname;
320 	char *hostp, *delimp;
321 
322 	ai = NULL;
323 	do_rpc = 0;
324 	hostp = NULL;
325 	nfsdirname = delimp = orignfsdirname = NULL;
326 	memset(&hints, 0, sizeof hints);
327 
328 	if (strcmp(sfs->f_fstypename, "nfs") == 0) {
329 		if ((nfsdirname = strdup(sfs->f_mntfromname)) == NULL)
330 			err(1, "strdup");
331 		orignfsdirname = nfsdirname;
332 		if ((delimp = strrchr(nfsdirname, ':')) != NULL) {
333 			*delimp = '\0';
334 			hostp = nfsdirname;
335 			getaddrinfo(hostp, NULL, &hints, &ai);
336 			if (ai == NULL) {
337 				warnx("can't get net id for host");
338 			}
339 			nfsdirname = delimp + 1;
340 		}
341 
342 		/*
343 		 * Check if we have to start the rpc-call later.
344 		 * If there are still identical nfs-names mounted,
345 		 * we skip the rpc-call. Obviously this has to
346 		 * happen before unmount(2), but it should happen
347 		 * after the previous namecheck.
348 		 * A non-NULL return means that this is the last
349 		 * mount from mntfromname that is still mounted.
350 		 */
351 		if (getmntentry(sfs->f_mntfromname, NULL, NULL,
352 		    CHECKUNIQUE) != NULL)
353 			do_rpc = 1;
354 	}
355 
356 	if (!namematch(ai))
357 		return (1);
358 	/* First try to unmount using the file system ID. */
359 	snprintf(fsidbuf, sizeof(fsidbuf), "FSID:%d:%d", sfs->f_fsid.val[0],
360 	    sfs->f_fsid.val[1]);
361 	if (unmount(fsidbuf, fflag | MNT_BYFSID) != 0) {
362 		/* XXX, non-root users get a zero fsid, so don't warn. */
363 		if (errno != ENOENT || sfs->f_fsid.val[0] != 0 ||
364 		    sfs->f_fsid.val[1] != 0)
365 			warn("unmount of %s failed", sfs->f_mntonname);
366 		if (errno != ENOENT)
367 			return (1);
368 		/* Compatability for old kernels. */
369 		warnx("retrying using path instead of file system ID");
370 		if (unmount(sfs->f_mntonname, fflag) != 0) {
371 			warn("unmount of %s failed", sfs->f_mntonname);
372 			return (1);
373 		}
374 	}
375 	/* Mark this this file system as unmounted. */
376 	getmntentry(NULL, NULL, &sfs->f_fsid, REMOVE);
377 	if (vflag)
378 		(void)printf("%s: unmount from %s\n", sfs->f_mntfromname,
379 		    sfs->f_mntonname);
380 	/*
381 	 * Report to mountd-server which nfsname
382 	 * has been unmounted.
383 	 */
384 	if (ai != NULL && !(fflag & MNT_FORCE) && do_rpc) {
385 		clp = clnt_create(hostp, RPCPROG_MNT, RPCMNT_VER1, "udp");
386 		if (clp  == NULL) {
387 			warnx("%s: %s", hostp,
388 			    clnt_spcreateerror("RPCPROG_MNT"));
389 			return (1);
390 		}
391 		clp->cl_auth = authsys_create_default();
392 		try.tv_sec = 20;
393 		try.tv_usec = 0;
394 		clnt_stat = clnt_call(clp, RPCMNT_UMOUNT, (xdrproc_t)xdr_dir,
395 		    nfsdirname, (xdrproc_t)xdr_void, (caddr_t)0, try);
396 		if (clnt_stat != RPC_SUCCESS) {
397 			warnx("%s: %s", hostp,
398 			    clnt_sperror(clp, "RPCMNT_UMOUNT"));
399 			return (1);
400 		}
401 		/*
402 		 * Remove the unmounted entry from /var/db/mounttab.
403 		 */
404 		if (read_mtab()) {
405 			clean_mtab(hostp, nfsdirname, vflag);
406 			if(!write_mtab(vflag))
407 				warnx("cannot remove mounttab entry %s:%s",
408 				    hostp, nfsdirname);
409 			free_mtab();
410 		}
411 		free(orignfsdirname);
412 		auth_destroy(clp->cl_auth);
413 		clnt_destroy(clp);
414 	}
415 	return (0);
416 }
417 
418 struct statfs *
419 getmntentry(const char *fromname, const char *onname, fsid_t *fsid, dowhat what)
420 {
421 	static struct statfs *mntbuf;
422 	static size_t mntsize = 0;
423 	static char *mntcheck = NULL;
424 	struct statfs *sfs, *foundsfs;
425 	int i, count;
426 
427 	if (mntsize <= 0) {
428 		if ((mntsize = mntinfo(&mntbuf)) <= 0)
429 			return (NULL);
430 	}
431 	if (mntcheck == NULL) {
432 		if ((mntcheck = calloc(mntsize + 1, sizeof(int))) == NULL)
433 			err(1, "calloc");
434 	}
435 	/*
436 	 * We want to get the file systems in the reverse order
437 	 * that they were mounted. Unmounted file systems are marked
438 	 * in a table called 'mntcheck'.
439 	 */
440 	count = 0;
441 	foundsfs = NULL;
442 	for (i = mntsize - 1; i >= 0; i--) {
443 		if (mntcheck[i])
444 			continue;
445 		sfs = &mntbuf[i];
446 		if (fromname != NULL && strcmp(sfs->f_mntfromname,
447 		    fromname) != 0)
448 			continue;
449 		if (onname != NULL && strcmp(sfs->f_mntonname, onname) != 0)
450 			continue;
451 		if (fsid != NULL && bcmp(&sfs->f_fsid, fsid,
452 		    sizeof(*fsid)) != 0)
453 			continue;
454 
455 		switch (what) {
456 		case CHECKUNIQUE:
457 			foundsfs = sfs;
458 			count++;
459 			continue;
460 		case REMOVE:
461 			mntcheck[i] = 1;
462 			break;
463 		default:
464 			break;
465 		}
466 		return (sfs);
467 	}
468 
469 	if (what == CHECKUNIQUE && count == 1)
470 		return (foundsfs);
471 	return (NULL);
472 }
473 
474 int
475 sacmp(struct sockaddr *sa1, struct sockaddr *sa2)
476 {
477 	void *p1, *p2;
478 	int len;
479 
480 	if (sa1->sa_family != sa2->sa_family)
481 		return (1);
482 
483 	switch (sa1->sa_family) {
484 	case AF_INET:
485 		p1 = &((struct sockaddr_in *)sa1)->sin_addr;
486 		p2 = &((struct sockaddr_in *)sa2)->sin_addr;
487 		len = 4;
488 		break;
489 	case AF_INET6:
490 		p1 = &((struct sockaddr_in6 *)sa1)->sin6_addr;
491 		p2 = &((struct sockaddr_in6 *)sa2)->sin6_addr;
492 		len = 16;
493 		if (((struct sockaddr_in6 *)sa1)->sin6_scope_id !=
494 		    ((struct sockaddr_in6 *)sa2)->sin6_scope_id)
495 			return (1);
496 		break;
497 	default:
498 		return (1);
499 	}
500 
501 	return memcmp(p1, p2, len);
502 }
503 
504 int
505 namematch(struct addrinfo *ai)
506 {
507 	struct addrinfo *aip;
508 
509 	if (nfshost == NULL || nfshost_ai == NULL)
510 		return (1);
511 
512 	while (ai != NULL) {
513 		aip = nfshost_ai;
514 		while (aip != NULL) {
515 			if (sacmp(ai->ai_addr, aip->ai_addr) == 0)
516 				return (1);
517 			aip = aip->ai_next;
518 		}
519 		ai = ai->ai_next;
520 	}
521 
522 	return (0);
523 }
524 
525 struct statfs *
526 checkmntlist(char *name)
527 {
528 	struct statfs *sfs;
529 	fsid_t fsid;
530 
531 	sfs = NULL;
532 	if (parsehexfsid(name, &fsid) == 0)
533 		sfs = getmntentry(NULL, NULL, &fsid, FIND);
534 	if (sfs == NULL)
535 		sfs = getmntentry(NULL, name, NULL, FIND);
536 	if (sfs == NULL)
537 		sfs = getmntentry(name, NULL, NULL, FIND);
538 	return (sfs);
539 }
540 
541 size_t
542 mntinfo(struct statfs **mntbuf)
543 {
544 	static struct statfs *origbuf;
545 	size_t bufsize;
546 	int mntsize;
547 
548 	mntsize = getfsstat(NULL, 0, MNT_NOWAIT);
549 	if (mntsize <= 0)
550 		return (0);
551 	bufsize = (mntsize + 1) * sizeof(struct statfs);
552 	if ((origbuf = malloc(bufsize)) == NULL)
553 		err(1, "malloc");
554 	mntsize = getfsstat(origbuf, (long)bufsize, MNT_NOWAIT);
555 	*mntbuf = origbuf;
556 	return (mntsize);
557 }
558 
559 /*
560  * Convert a hexidecimal filesystem ID to an fsid_t.
561  * Returns 0 on success.
562  */
563 int
564 parsehexfsid(const char *hex, fsid_t *fsid)
565 {
566 	char hexbuf[3];
567 	int i;
568 
569 	if (strlen(hex) != sizeof(*fsid) * 2)
570 		return (-1);
571 	hexbuf[2] = '\0';
572 	for (i = 0; i < (int)sizeof(*fsid); i++) {
573 		hexbuf[0] = hex[i * 2];
574 		hexbuf[1] = hex[i * 2 + 1];
575 		if (!isxdigit(hexbuf[0]) || !isxdigit(hexbuf[1]))
576 			return (-1);
577 		((u_char *)fsid)[i] = strtol(hexbuf, NULL, 16);
578 	}
579 	return (0);
580 }
581 
582 /*
583  * xdr routines for mount rpc's
584  */
585 int
586 xdr_dir(XDR *xdrsp, char *dirp)
587 {
588 
589 	return (xdr_string(xdrsp, &dirp, RPCMNT_PATHLEN));
590 }
591 
592 void
593 usage()
594 {
595 
596 	(void)fprintf(stderr, "%s\n%s\n",
597 	    "usage: umount [-fv] special | node",
598 	    "       umount -a | -A [ -F fstab] [-fv] [-h host] [-t type]");
599 	exit(1);
600 }
601