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