xref: /freebsd/sbin/umount/umount.c (revision 5b31cc94b10d4bb7109c6b27940a0fc76a44a331)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1980, 1989, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #ifndef lint
33 static const char copyright[] =
34 "@(#) Copyright (c) 1980, 1989, 1993\n\
35 	The Regents of the University of California.  All rights reserved.\n";
36 #endif /* not lint */
37 
38 #ifndef lint
39 #endif /* not lint */
40 
41 #include <sys/param.h>
42 #include <sys/mount.h>
43 #include <sys/socket.h>
44 #include <sys/stat.h>
45 
46 #include <netdb.h>
47 #include <rpc/rpc.h>
48 #include <rpcsvc/mount.h>
49 #include <nfs/nfssvc.h>
50 
51 #include <ctype.h>
52 #include <err.h>
53 #include <errno.h>
54 #include <fstab.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <unistd.h>
59 
60 #include "mounttab.h"
61 
62 typedef enum { FIND, REMOVE, CHECKUNIQUE } dowhat;
63 
64 static struct addrinfo *nfshost_ai = NULL;
65 static int	fflag, vflag;
66 static char	*nfshost;
67 
68 struct statfs *checkmntlist(char *);
69 int	 checkvfsname (const char *, char **);
70 struct statfs *getmntentry(const char *fromname, const char *onname,
71 	     fsid_t *fsid, dowhat what);
72 char   **makevfslist (const char *);
73 size_t	 mntinfo (struct statfs **);
74 int	 namematch (struct addrinfo *);
75 int	 parsehexfsid(const char *hex, fsid_t *fsid);
76 int	 sacmp (void *, void *);
77 int	 umountall (char **);
78 int	 checkname (char *, char **);
79 int	 umountfs(struct statfs *sfs);
80 void	 usage (void);
81 int	 xdr_dir (XDR *, char *);
82 
83 int
84 main(int argc, char *argv[])
85 {
86 	int all, errs, ch, mntsize, error, nfsforce, ret;
87 	char **typelist = NULL;
88 	struct statfs *mntbuf, *sfs;
89 	struct addrinfo hints;
90 
91 	nfsforce = all = errs = 0;
92 	while ((ch = getopt(argc, argv, "AaF:fh:Nnt:v")) != -1)
93 		switch (ch) {
94 		case 'A':
95 			all = 2;
96 			break;
97 		case 'a':
98 			all = 1;
99 			break;
100 		case 'F':
101 			setfstab(optarg);
102 			break;
103 		case 'f':
104 			fflag |= MNT_FORCE;
105 			break;
106 		case 'h':	/* -h implies -A. */
107 			all = 2;
108 			nfshost = optarg;
109 			break;
110 		case 'N':
111 			nfsforce = 1;
112 			break;
113 		case 'n':
114 			fflag |= MNT_NONBUSY;
115 			break;
116 		case 't':
117 			if (typelist != NULL)
118 				err(1, "only one -t option may be specified");
119 			typelist = makevfslist(optarg);
120 			break;
121 		case 'v':
122 			vflag = 1;
123 			break;
124 		default:
125 			usage();
126 			/* NOTREACHED */
127 		}
128 	argc -= optind;
129 	argv += optind;
130 
131 	if ((fflag & MNT_FORCE) != 0 && (fflag & MNT_NONBUSY) != 0)
132 		err(1, "-f and -n are mutually exclusive");
133 
134 	if ((argc == 0 && !all) || (argc != 0 && all))
135 		usage();
136 
137 	if (nfsforce != 0 && (argc == 0 || nfshost != NULL || typelist != NULL))
138 		usage();
139 
140 	/* -h implies "-t nfs" if no -t flag. */
141 	if ((nfshost != NULL) && (typelist == NULL))
142 		typelist = makevfslist("nfs");
143 
144 	if (nfshost != NULL) {
145 		memset(&hints, 0, sizeof hints);
146 		error = getaddrinfo(nfshost, NULL, &hints, &nfshost_ai);
147 		if (error)
148 			errx(1, "%s: %s", nfshost, gai_strerror(error));
149 	}
150 
151 	switch (all) {
152 	case 2:
153 		if ((mntsize = mntinfo(&mntbuf)) <= 0)
154 			break;
155 		/*
156 		 * We unmount the nfs-mounts in the reverse order
157 		 * that they were mounted.
158 		 */
159 		for (errs = 0, mntsize--; mntsize > 0; mntsize--) {
160 			sfs = &mntbuf[mntsize];
161 			if (checkvfsname(sfs->f_fstypename, typelist))
162 				continue;
163 			if (strcmp(sfs->f_mntonname, "/dev") == 0)
164 				continue;
165 			if (umountfs(sfs) != 0)
166 				errs = 1;
167 		}
168 		free(mntbuf);
169 		break;
170 	case 1:
171 		if (setfsent() == 0)
172 			err(1, "%s", getfstab());
173 		errs = umountall(typelist);
174 		break;
175 	case 0:
176 		for (errs = 0; *argv != NULL; ++argv)
177 			if (nfsforce != 0) {
178 				/*
179 				 * First do the nfssvc() syscall to shut down
180 				 * the mount point and then do the forced
181 				 * dismount.
182 				 */
183 				ret = nfssvc(NFSSVC_FORCEDISM, *argv);
184 				if (ret >= 0)
185 					ret = unmount(*argv, MNT_FORCE);
186 				if (ret < 0) {
187 					warn("%s", *argv);
188 					errs = 1;
189 				}
190 			} else if (checkname(*argv, typelist) != 0)
191 				errs = 1;
192 		break;
193 	}
194 	exit(errs);
195 }
196 
197 int
198 umountall(char **typelist)
199 {
200 	struct xvfsconf vfc;
201 	struct fstab *fs;
202 	int rval;
203 	char *cp;
204 	static int firstcall = 1;
205 
206 	if ((fs = getfsent()) != NULL)
207 		firstcall = 0;
208 	else if (firstcall)
209 		errx(1, "fstab reading failure");
210 	else
211 		return (0);
212 	do {
213 		/* Ignore the root. */
214 		if (strcmp(fs->fs_file, "/") == 0)
215 			continue;
216 		/*
217 		 * !!!
218 		 * Historic practice: ignore unknown FSTAB_* fields.
219 		 */
220 		if (strcmp(fs->fs_type, FSTAB_RW) &&
221 		    strcmp(fs->fs_type, FSTAB_RO) &&
222 		    strcmp(fs->fs_type, FSTAB_RQ))
223 			continue;
224 		/* Ignore unknown file system types. */
225 		if (getvfsbyname(fs->fs_vfstype, &vfc) == -1)
226 			continue;
227 		if (checkvfsname(fs->fs_vfstype, typelist))
228 			continue;
229 
230 		/*
231 		 * We want to unmount the file systems in the reverse order
232 		 * that they were mounted.  So, we save off the file name
233 		 * in some allocated memory, and then call recursively.
234 		 */
235 		if ((cp = malloc((size_t)strlen(fs->fs_file) + 1)) == NULL)
236 			err(1, "malloc failed");
237 		(void)strcpy(cp, fs->fs_file);
238 		rval = umountall(typelist);
239 		rval = checkname(cp, typelist) || rval;
240 		free(cp);
241 		return (rval);
242 	} while ((fs = getfsent()) != NULL);
243 	return (0);
244 }
245 
246 /*
247  * Do magic checks on mountpoint/device/fsid, and then call unmount(2).
248  */
249 int
250 checkname(char *mntname, char **typelist)
251 {
252 	char buf[MAXPATHLEN];
253 	struct statfs sfsbuf;
254 	struct stat sb;
255 	struct statfs *sfs;
256 	char *delimp;
257 	dev_t dev;
258 	int len;
259 
260 	/*
261 	 * 1. Check if the name exists in the mounttable.
262 	 */
263 	sfs = checkmntlist(mntname);
264 	/*
265 	 * 2. Remove trailing slashes if there are any. After that
266 	 * we look up the name in the mounttable again.
267 	 */
268 	if (sfs == NULL) {
269 		len = strlen(mntname);
270 		while (len > 1 && mntname[len - 1] == '/')
271 			mntname[--len] = '\0';
272 		sfs = checkmntlist(mntname);
273 	}
274 	/*
275 	 * 3. Check if the deprecated NFS syntax with an '@' has been used
276 	 * and translate it to the ':' syntax. Look up the name in the
277 	 * mount table again.
278 	 */
279 	if (sfs == NULL && (delimp = strrchr(mntname, '@')) != NULL) {
280 		snprintf(buf, sizeof(buf), "%s:%.*s", delimp + 1,
281 		    (int)(delimp - mntname), mntname);
282 		len = strlen(buf);
283 		while (len > 1 && buf[len - 1] == '/')
284 			buf[--len] = '\0';
285 		sfs = checkmntlist(buf);
286 	}
287 	/*
288 	 * 4. Resort to a statfs(2) call. This is the last check so that
289 	 * hung NFS filesystems for example can be unmounted without
290 	 * potentially blocking forever in statfs() as long as the
291 	 * filesystem is specified unambiguously. This covers all the
292 	 * hard cases such as symlinks and mismatches between the
293 	 * mount list and reality.
294 	 * We also do this if an ambiguous mount point was specified.
295 	 */
296 	if (sfs == NULL || (getmntentry(NULL, mntname, NULL, FIND) != NULL &&
297 	    getmntentry(NULL, mntname, NULL, CHECKUNIQUE) == NULL)) {
298 		if (statfs(mntname, &sfsbuf) != 0) {
299 			warn("%s: statfs", mntname);
300 		} else if (stat(mntname, &sb) != 0) {
301 			warn("%s: stat", mntname);
302 		} else if (S_ISDIR(sb.st_mode)) {
303 			/* Check that `mntname' is the root directory. */
304 			dev = sb.st_dev;
305 			snprintf(buf, sizeof(buf), "%s/..", mntname);
306 			if (stat(buf, &sb) != 0) {
307 				warn("%s: stat", buf);
308 			} else if (sb.st_dev == dev) {
309 				warnx("%s: not a file system root directory",
310 				    mntname);
311 				return (1);
312 			} else
313 				sfs = &sfsbuf;
314 		}
315 	}
316 	if (sfs == NULL) {
317 		warnx("%s: unknown file system", mntname);
318 		return (1);
319 	}
320 	if (checkvfsname(sfs->f_fstypename, typelist))
321 		return (1);
322 	return (umountfs(sfs));
323 }
324 
325 /*
326  * NFS stuff and unmount(2) call
327  */
328 int
329 umountfs(struct statfs *sfs)
330 {
331 	char fsidbuf[64];
332 	enum clnt_stat clnt_stat;
333 	struct timeval try;
334 	struct addrinfo *ai, hints;
335 	int do_rpc;
336 	CLIENT *clp;
337 	char *nfsdirname, *orignfsdirname;
338 	char *hostp, *delimp;
339 	char buf[1024];
340 	struct nfscl_dumpmntopts dumpmntopts;
341 	const char *proto_ptr = NULL;
342 
343 	ai = NULL;
344 	do_rpc = 0;
345 	hostp = NULL;
346 	nfsdirname = delimp = orignfsdirname = NULL;
347 	memset(&hints, 0, sizeof hints);
348 
349 	if (strcmp(sfs->f_fstypename, "nfs") == 0) {
350 		if ((nfsdirname = strdup(sfs->f_mntfromname)) == NULL)
351 			err(1, "strdup");
352 		orignfsdirname = nfsdirname;
353 		if (*nfsdirname == '[' &&
354 		    (delimp = strchr(nfsdirname + 1, ']')) != NULL &&
355 		    *(delimp + 1) == ':') {
356 			hostp = nfsdirname + 1;
357 			nfsdirname = delimp + 2;
358 		} else if ((delimp = strrchr(nfsdirname, ':')) != NULL) {
359 			hostp = nfsdirname;
360 			nfsdirname = delimp + 1;
361 		}
362 		if (hostp != NULL) {
363 			*delimp = '\0';
364 			getaddrinfo(hostp, NULL, &hints, &ai);
365 			if (ai == NULL) {
366 				warnx("can't get net id for host");
367 			}
368 		}
369 
370 		/*
371 		 * Check if we have to start the rpc-call later.
372 		 * If there are still identical nfs-names mounted,
373 		 * we skip the rpc-call. Obviously this has to
374 		 * happen before unmount(2), but it should happen
375 		 * after the previous namecheck.
376 		 * A non-NULL return means that this is the last
377 		 * mount from mntfromname that is still mounted.
378 		 */
379 		if (getmntentry(sfs->f_mntfromname, NULL, NULL,
380 		    CHECKUNIQUE) != NULL) {
381 			do_rpc = 1;
382 			proto_ptr = "udp";
383 			/*
384 			 * Try and find out whether this NFS mount is NFSv4 and
385 			 * what protocol is being used. If this fails, the
386 			 * default is NFSv2,3 and use UDP for the Unmount RPC.
387 			 */
388 			dumpmntopts.ndmnt_fname = sfs->f_mntonname;
389 			dumpmntopts.ndmnt_buf = buf;
390 			dumpmntopts.ndmnt_blen = sizeof(buf);
391 			if (nfssvc(NFSSVC_DUMPMNTOPTS, &dumpmntopts) >= 0) {
392 				if (strstr(buf, "nfsv4,") != NULL)
393 					do_rpc = 0;
394 				else if (strstr(buf, ",tcp,") != NULL)
395 					proto_ptr = "tcp";
396 			}
397 		}
398 	}
399 
400 	if (!namematch(ai)) {
401 		free(orignfsdirname);
402 		return (1);
403 	}
404 	/* First try to unmount using the file system ID. */
405 	snprintf(fsidbuf, sizeof(fsidbuf), "FSID:%d:%d", sfs->f_fsid.val[0],
406 	    sfs->f_fsid.val[1]);
407 	if (unmount(fsidbuf, fflag | MNT_BYFSID) != 0) {
408 		/* XXX, non-root users get a zero fsid, so don't warn. */
409 		if (errno != ENOENT || sfs->f_fsid.val[0] != 0 ||
410 		    sfs->f_fsid.val[1] != 0)
411 			warn("unmount of %s failed", sfs->f_mntonname);
412 		if (errno != ENOENT) {
413 			free(orignfsdirname);
414 			return (1);
415 		}
416 		/* Compatibility for old kernels. */
417 		if (sfs->f_fsid.val[0] != 0 || sfs->f_fsid.val[1] != 0)
418 			warnx("retrying using path instead of file system ID");
419 		if (unmount(sfs->f_mntonname, fflag) != 0) {
420 			warn("unmount of %s failed", sfs->f_mntonname);
421 			free(orignfsdirname);
422 			return (1);
423 		}
424 	}
425 	/* Mark this file system as unmounted. */
426 	getmntentry(NULL, NULL, &sfs->f_fsid, REMOVE);
427 	if (vflag)
428 		(void)printf("%s: unmount from %s\n", sfs->f_mntfromname,
429 		    sfs->f_mntonname);
430 	/*
431 	 * Report to mountd-server which nfsname
432 	 * has been unmounted.
433 	 */
434 	if (ai != NULL && !(fflag & MNT_FORCE) && do_rpc) {
435 		clp = clnt_create(hostp, MOUNTPROG, MOUNTVERS3, proto_ptr);
436 		if (clp  == NULL) {
437 			warnx("%s: %s", hostp,
438 			    clnt_spcreateerror("MOUNTPROG"));
439 			free(orignfsdirname);
440 			return (1);
441 		}
442 		clp->cl_auth = authsys_create_default();
443 		try.tv_sec = 20;
444 		try.tv_usec = 0;
445 		clnt_stat = clnt_call(clp, MOUNTPROC_UMNT, (xdrproc_t)xdr_dir,
446 		    nfsdirname, (xdrproc_t)xdr_void, (caddr_t)0, try);
447 		if (clnt_stat != RPC_SUCCESS) {
448 			warnx("%s: %s", hostp,
449 			    clnt_sperror(clp, "RPCMNT_UMOUNT"));
450 			free(orignfsdirname);
451 			return (1);
452 		}
453 		/*
454 		 * Remove the unmounted entry from /var/db/mounttab.
455 		 */
456 		if (read_mtab()) {
457 			clean_mtab(hostp, nfsdirname, vflag);
458 			if(!write_mtab(vflag))
459 				warnx("cannot remove mounttab entry %s:%s",
460 				    hostp, nfsdirname);
461 			free_mtab();
462 		}
463 		auth_destroy(clp->cl_auth);
464 		clnt_destroy(clp);
465 	}
466 	free(orignfsdirname);
467 	return (0);
468 }
469 
470 struct statfs *
471 getmntentry(const char *fromname, const char *onname, fsid_t *fsid, dowhat what)
472 {
473 	static struct statfs *mntbuf;
474 	static size_t mntsize = 0;
475 	static int *mntcheck = NULL;
476 	struct statfs *sfs, *foundsfs;
477 	int i, count;
478 
479 	if (mntsize <= 0) {
480 		if ((mntsize = mntinfo(&mntbuf)) <= 0)
481 			return (NULL);
482 	}
483 	if (mntcheck == NULL) {
484 		if ((mntcheck = calloc(mntsize + 1, sizeof(int))) == NULL)
485 			err(1, "calloc");
486 	}
487 	/*
488 	 * We want to get the file systems in the reverse order
489 	 * that they were mounted. Unmounted file systems are marked
490 	 * in a table called 'mntcheck'.
491 	 */
492 	count = 0;
493 	foundsfs = NULL;
494 	for (i = mntsize - 1; i >= 0; i--) {
495 		if (mntcheck[i])
496 			continue;
497 		sfs = &mntbuf[i];
498 		if (fromname != NULL && strcmp(sfs->f_mntfromname,
499 		    fromname) != 0)
500 			continue;
501 		if (onname != NULL && strcmp(sfs->f_mntonname, onname) != 0)
502 			continue;
503 		if (fsid != NULL && fsidcmp(&sfs->f_fsid, fsid) != 0)
504 			continue;
505 
506 		switch (what) {
507 		case CHECKUNIQUE:
508 			foundsfs = sfs;
509 			count++;
510 			continue;
511 		case REMOVE:
512 			mntcheck[i] = 1;
513 			break;
514 		default:
515 			break;
516 		}
517 		return (sfs);
518 	}
519 
520 	if (what == CHECKUNIQUE && count == 1)
521 		return (foundsfs);
522 	return (NULL);
523 }
524 
525 int
526 sacmp(void *sa1, void *sa2)
527 {
528 	void *p1, *p2;
529 	int len;
530 
531 	if (((struct sockaddr *)sa1)->sa_family !=
532 	    ((struct sockaddr *)sa2)->sa_family)
533 		return (1);
534 
535 	switch (((struct sockaddr *)sa1)->sa_family) {
536 	case AF_INET:
537 		p1 = &((struct sockaddr_in *)sa1)->sin_addr;
538 		p2 = &((struct sockaddr_in *)sa2)->sin_addr;
539 		len = 4;
540 		break;
541 	case AF_INET6:
542 		p1 = &((struct sockaddr_in6 *)sa1)->sin6_addr;
543 		p2 = &((struct sockaddr_in6 *)sa2)->sin6_addr;
544 		len = 16;
545 		if (((struct sockaddr_in6 *)sa1)->sin6_scope_id !=
546 		    ((struct sockaddr_in6 *)sa2)->sin6_scope_id)
547 			return (1);
548 		break;
549 	default:
550 		return (1);
551 	}
552 
553 	return memcmp(p1, p2, len);
554 }
555 
556 int
557 namematch(struct addrinfo *ai)
558 {
559 	struct addrinfo *aip;
560 
561 	if (nfshost == NULL || nfshost_ai == NULL)
562 		return (1);
563 
564 	while (ai != NULL) {
565 		aip = nfshost_ai;
566 		while (aip != NULL) {
567 			if (sacmp(ai->ai_addr, aip->ai_addr) == 0)
568 				return (1);
569 			aip = aip->ai_next;
570 		}
571 		ai = ai->ai_next;
572 	}
573 
574 	return (0);
575 }
576 
577 struct statfs *
578 checkmntlist(char *mntname)
579 {
580 	struct statfs *sfs;
581 	fsid_t fsid;
582 
583 	sfs = NULL;
584 	if (parsehexfsid(mntname, &fsid) == 0)
585 		sfs = getmntentry(NULL, NULL, &fsid, FIND);
586 	if (sfs == NULL)
587 		sfs = getmntentry(NULL, mntname, NULL, FIND);
588 	if (sfs == NULL)
589 		sfs = getmntentry(mntname, NULL, NULL, FIND);
590 	return (sfs);
591 }
592 
593 size_t
594 mntinfo(struct statfs **mntbuf)
595 {
596 	static struct statfs *origbuf;
597 	size_t bufsize;
598 	int mntsize;
599 
600 	mntsize = getfsstat(NULL, 0, MNT_NOWAIT);
601 	if (mntsize <= 0)
602 		return (0);
603 	bufsize = (mntsize + 1) * sizeof(struct statfs);
604 	if ((origbuf = malloc(bufsize)) == NULL)
605 		err(1, "malloc");
606 	mntsize = getfsstat(origbuf, (long)bufsize, MNT_NOWAIT);
607 	*mntbuf = origbuf;
608 	return (mntsize);
609 }
610 
611 /*
612  * Convert a hexadecimal filesystem ID to an fsid_t.
613  * Returns 0 on success.
614  */
615 int
616 parsehexfsid(const char *hex, fsid_t *fsid)
617 {
618 	char hexbuf[3];
619 	int i;
620 
621 	if (strlen(hex) != sizeof(*fsid) * 2)
622 		return (-1);
623 	hexbuf[2] = '\0';
624 	for (i = 0; i < (int)sizeof(*fsid); i++) {
625 		hexbuf[0] = hex[i * 2];
626 		hexbuf[1] = hex[i * 2 + 1];
627 		if (!isxdigit(hexbuf[0]) || !isxdigit(hexbuf[1]))
628 			return (-1);
629 		((u_char *)fsid)[i] = strtol(hexbuf, NULL, 16);
630 	}
631 	return (0);
632 }
633 
634 /*
635  * xdr routines for mount rpc's
636  */
637 int
638 xdr_dir(XDR *xdrsp, char *dirp)
639 {
640 
641 	return (xdr_string(xdrsp, &dirp, MNTPATHLEN));
642 }
643 
644 void
645 usage(void)
646 {
647 
648 	(void)fprintf(stderr, "%s\n%s\n",
649 	    "usage: umount [-fNnv] special ... | node ... | fsid ...",
650 	    "       umount -a | -A [-F fstab] [-fnv] [-h host] [-t type]");
651 	exit(1);
652 }
653