]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sbin/umount/umount.c
MFC r368207,368607:
[FreeBSD/stable/10.git] / sbin / umount / umount.c
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 #include <nfs/nfssvc.h>
53
54 #include <ctype.h>
55 #include <err.h>
56 #include <errno.h>
57 #include <fstab.h>
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <unistd.h>
62
63 #include "mounttab.h"
64
65 typedef enum { FIND, REMOVE, CHECKUNIQUE } dowhat;
66
67 static struct addrinfo *nfshost_ai = NULL;
68 static int      fflag, vflag;
69 static char     *nfshost;
70
71 struct statfs *checkmntlist(char *);
72 int      checkvfsname (const char *, char **);
73 struct statfs *getmntentry(const char *fromname, const char *onname,
74              fsid_t *fsid, dowhat what);
75 char   **makevfslist (const char *);
76 size_t   mntinfo (struct statfs **);
77 int      namematch (struct addrinfo *);
78 int      parsehexfsid(const char *hex, fsid_t *fsid);
79 int      sacmp (void *, void *);
80 int      umountall (char **);
81 int      checkname (char *, char **);
82 int      umountfs(struct statfs *sfs);
83 void     usage (void);
84 int      xdr_dir (XDR *, char *);
85
86 int
87 main(int argc, char *argv[])
88 {
89         int all, errs, ch, mntsize, error;
90         char **typelist = NULL;
91         struct statfs *mntbuf, *sfs;
92         struct addrinfo hints;
93
94         all = errs = 0;
95         while ((ch = getopt(argc, argv, "AaF:fh:t:v")) != -1)
96                 switch (ch) {
97                 case 'A':
98                         all = 2;
99                         break;
100                 case 'a':
101                         all = 1;
102                         break;
103                 case 'F':
104                         setfstab(optarg);
105                         break;
106                 case 'f':
107                         fflag = MNT_FORCE;
108                         break;
109                 case 'h':       /* -h implies -A. */
110                         all = 2;
111                         nfshost = optarg;
112                         break;
113                 case 't':
114                         if (typelist != NULL)
115                                 err(1, "only one -t option may be specified");
116                         typelist = makevfslist(optarg);
117                         break;
118                 case 'v':
119                         vflag = 1;
120                         break;
121                 default:
122                         usage();
123                         /* NOTREACHED */
124                 }
125         argc -= optind;
126         argv += optind;
127
128         /* Start disks transferring immediately. */
129         if ((fflag & MNT_FORCE) == 0)
130                 sync();
131
132         if ((argc == 0 && !all) || (argc != 0 && all))
133                 usage();
134
135         /* -h implies "-t nfs" if no -t flag. */
136         if ((nfshost != NULL) && (typelist == NULL))
137                 typelist = makevfslist("nfs");
138
139         if (nfshost != NULL) {
140                 memset(&hints, 0, sizeof hints);
141                 error = getaddrinfo(nfshost, NULL, &hints, &nfshost_ai);
142                 if (error)
143                         errx(1, "%s: %s", nfshost, gai_strerror(error));
144         }
145
146         switch (all) {
147         case 2:
148                 if ((mntsize = mntinfo(&mntbuf)) <= 0)
149                         break;
150                 /*
151                  * We unmount the nfs-mounts in the reverse order
152                  * that they were mounted.
153                  */
154                 for (errs = 0, mntsize--; mntsize > 0; mntsize--) {
155                         sfs = &mntbuf[mntsize];
156                         if (checkvfsname(sfs->f_fstypename, typelist))
157                                 continue;
158                         if (strcmp(sfs->f_mntonname, "/dev") == 0)
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 *mntname, 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(mntname);
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(mntname);
252                 while (len > 1 && mntname[len - 1] == '/')
253                         mntname[--len] = '\0';
254                 sfs = checkmntlist(mntname);
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(mntname, '@')) != NULL) {
262                 snprintf(buf, sizeof(buf), "%s:%.*s", delimp + 1,
263                     (int)(delimp - mntname), mntname);
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, mntname, NULL, FIND) != NULL &&
279             getmntentry(NULL, mntname, NULL, CHECKUNIQUE) == NULL)) {
280                 if (statfs(mntname, &sfsbuf) != 0) {
281                         warn("%s: statfs", mntname);
282                 } else if (stat(mntname, &sb) != 0) {
283                         warn("%s: stat", mntname);
284                 } else if (S_ISDIR(sb.st_mode)) {
285                         /* Check that `mntname' is the root directory. */
286                         dev = sb.st_dev;
287                         snprintf(buf, sizeof(buf), "%s/..", mntname);
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                                     mntname);
293                                 return (1);
294                         } else
295                                 sfs = &sfsbuf;
296                 }
297         }
298         if (sfs == NULL) {
299                 warnx("%s: unknown file system", mntname);
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         char buf[1024];
322         struct nfscl_dumpmntopts dumpmntopts;
323         const char *proto_ptr = NULL;
324
325         ai = NULL;
326         do_rpc = 0;
327         hostp = NULL;
328         nfsdirname = delimp = orignfsdirname = NULL;
329         memset(&hints, 0, sizeof hints);
330
331         if (strcmp(sfs->f_fstypename, "nfs") == 0) {
332                 if ((nfsdirname = strdup(sfs->f_mntfromname)) == NULL)
333                         err(1, "strdup");
334                 orignfsdirname = nfsdirname;
335                 if (*nfsdirname == '[' &&
336                     (delimp = strchr(nfsdirname + 1, ']')) != NULL &&
337                     *(delimp + 1) == ':') {
338                         hostp = nfsdirname + 1;
339                         nfsdirname = delimp + 2;
340                 } else if ((delimp = strrchr(nfsdirname, ':')) != NULL) {
341                         hostp = nfsdirname;
342                         nfsdirname = delimp + 1;
343                 }
344                 if (hostp != NULL) {
345                         *delimp = '\0';
346                         getaddrinfo(hostp, NULL, &hints, &ai);
347                         if (ai == NULL) {
348                                 warnx("can't get net id for host");
349                         }
350                 }
351
352                 /*
353                  * Check if we have to start the rpc-call later.
354                  * If there are still identical nfs-names mounted,
355                  * we skip the rpc-call. Obviously this has to
356                  * happen before unmount(2), but it should happen
357                  * after the previous namecheck.
358                  * A non-NULL return means that this is the last
359                  * mount from mntfromname that is still mounted.
360                  */
361                 if (getmntentry(sfs->f_mntfromname, NULL, NULL,
362                     CHECKUNIQUE) != NULL) {
363                         do_rpc = 1;
364                         proto_ptr = "udp";
365                         /*
366                          * Try and find out whether this NFS mount is NFSv4 and
367                          * what protocol is being used. If this fails, the
368                          * default is NFSv2,3 and use UDP for the Unmount RPC.
369                          */
370                         dumpmntopts.ndmnt_fname = sfs->f_mntonname;
371                         dumpmntopts.ndmnt_buf = buf;
372                         dumpmntopts.ndmnt_blen = sizeof(buf);
373                         if (nfssvc(NFSSVC_DUMPMNTOPTS, &dumpmntopts) >= 0) {
374                                 if (strstr(buf, "nfsv4,") != NULL)
375                                         do_rpc = 0;
376                                 else if (strstr(buf, ",tcp,") != NULL)
377                                         proto_ptr = "tcp";
378                         }
379                 }
380         }
381
382         if (!namematch(ai)) {
383                 free(orignfsdirname);
384                 return (1);
385         }
386         /* First try to unmount using the file system ID. */
387         snprintf(fsidbuf, sizeof(fsidbuf), "FSID:%d:%d", sfs->f_fsid.val[0],
388             sfs->f_fsid.val[1]);
389         if (unmount(fsidbuf, fflag | MNT_BYFSID) != 0) {
390                 /* XXX, non-root users get a zero fsid, so don't warn. */
391                 if (errno != ENOENT || sfs->f_fsid.val[0] != 0 ||
392                     sfs->f_fsid.val[1] != 0)
393                         warn("unmount of %s failed", sfs->f_mntonname);
394                 if (errno != ENOENT) {
395                         free(orignfsdirname);
396                         return (1);
397                 }
398                 /* Compatibility for old kernels. */
399                 if (sfs->f_fsid.val[0] != 0 || sfs->f_fsid.val[1] != 0)
400                         warnx("retrying using path instead of file system ID");
401                 if (unmount(sfs->f_mntonname, fflag) != 0) {
402                         warn("unmount of %s failed", sfs->f_mntonname);
403                         free(orignfsdirname);
404                         return (1);
405                 }
406         }
407         /* Mark this this file system as unmounted. */
408         getmntentry(NULL, NULL, &sfs->f_fsid, REMOVE);
409         if (vflag)
410                 (void)printf("%s: unmount from %s\n", sfs->f_mntfromname,
411                     sfs->f_mntonname);
412         /*
413          * Report to mountd-server which nfsname
414          * has been unmounted.
415          */
416         if (ai != NULL && !(fflag & MNT_FORCE) && do_rpc) {
417                 clp = clnt_create(hostp, MOUNTPROG, MOUNTVERS3, proto_ptr);
418                 if (clp  == NULL) {
419                         warnx("%s: %s", hostp,
420                             clnt_spcreateerror("MOUNTPROG"));
421                         free(orignfsdirname);
422                         return (1);
423                 }
424                 clp->cl_auth = authsys_create_default();
425                 try.tv_sec = 20;
426                 try.tv_usec = 0;
427                 clnt_stat = clnt_call(clp, MOUNTPROC_UMNT, (xdrproc_t)xdr_dir,
428                     nfsdirname, (xdrproc_t)xdr_void, (caddr_t)0, try);
429                 if (clnt_stat != RPC_SUCCESS) {
430                         warnx("%s: %s", hostp,
431                             clnt_sperror(clp, "RPCMNT_UMOUNT"));
432                         free(orignfsdirname);
433                         return (1);
434                 }
435                 /*
436                  * Remove the unmounted entry from /var/db/mounttab.
437                  */
438                 if (read_mtab()) {
439                         clean_mtab(hostp, nfsdirname, vflag);
440                         if(!write_mtab(vflag))
441                                 warnx("cannot remove mounttab entry %s:%s",
442                                     hostp, nfsdirname);
443                         free_mtab();
444                 }
445                 auth_destroy(clp->cl_auth);
446                 clnt_destroy(clp);
447         }
448         free(orignfsdirname);
449         return (0);
450 }
451
452 struct statfs *
453 getmntentry(const char *fromname, const char *onname, fsid_t *fsid, dowhat what)
454 {
455         static struct statfs *mntbuf;
456         static size_t mntsize = 0;
457         static char *mntcheck = NULL;
458         struct statfs *sfs, *foundsfs;
459         int i, count;
460
461         if (mntsize <= 0) {
462                 if ((mntsize = mntinfo(&mntbuf)) <= 0)
463                         return (NULL);
464         }
465         if (mntcheck == NULL) {
466                 if ((mntcheck = calloc(mntsize + 1, sizeof(int))) == NULL)
467                         err(1, "calloc");
468         }
469         /*
470          * We want to get the file systems in the reverse order
471          * that they were mounted. Unmounted file systems are marked
472          * in a table called 'mntcheck'.
473          */
474         count = 0;
475         foundsfs = NULL;
476         for (i = mntsize - 1; i >= 0; i--) {
477                 if (mntcheck[i])
478                         continue;
479                 sfs = &mntbuf[i];
480                 if (fromname != NULL && strcmp(sfs->f_mntfromname,
481                     fromname) != 0)
482                         continue;
483                 if (onname != NULL && strcmp(sfs->f_mntonname, onname) != 0)
484                         continue;
485                 if (fsid != NULL && bcmp(&sfs->f_fsid, fsid,
486                     sizeof(*fsid)) != 0)
487                         continue;
488
489                 switch (what) {
490                 case CHECKUNIQUE:
491                         foundsfs = sfs;
492                         count++;
493                         continue;
494                 case REMOVE:
495                         mntcheck[i] = 1;
496                         break;
497                 default:
498                         break;
499                 }
500                 return (sfs);
501         }
502
503         if (what == CHECKUNIQUE && count == 1)
504                 return (foundsfs);
505         return (NULL);
506 }
507
508 int
509 sacmp(void *sa1, void *sa2)
510 {
511         void *p1, *p2;
512         int len;
513
514         if (((struct sockaddr *)sa1)->sa_family !=
515             ((struct sockaddr *)sa2)->sa_family)
516                 return (1);
517
518         switch (((struct sockaddr *)sa1)->sa_family) {
519         case AF_INET:
520                 p1 = &((struct sockaddr_in *)sa1)->sin_addr;
521                 p2 = &((struct sockaddr_in *)sa2)->sin_addr;
522                 len = 4;
523                 break;
524         case AF_INET6:
525                 p1 = &((struct sockaddr_in6 *)sa1)->sin6_addr;
526                 p2 = &((struct sockaddr_in6 *)sa2)->sin6_addr;
527                 len = 16;
528                 if (((struct sockaddr_in6 *)sa1)->sin6_scope_id !=
529                     ((struct sockaddr_in6 *)sa2)->sin6_scope_id)
530                         return (1);
531                 break;
532         default:
533                 return (1);
534         }
535
536         return memcmp(p1, p2, len);
537 }
538
539 int
540 namematch(struct addrinfo *ai)
541 {
542         struct addrinfo *aip;
543
544         if (nfshost == NULL || nfshost_ai == NULL)
545                 return (1);
546
547         while (ai != NULL) {
548                 aip = nfshost_ai;
549                 while (aip != NULL) {
550                         if (sacmp(ai->ai_addr, aip->ai_addr) == 0)
551                                 return (1);
552                         aip = aip->ai_next;
553                 }
554                 ai = ai->ai_next;
555         }
556
557         return (0);
558 }
559
560 struct statfs *
561 checkmntlist(char *mntname)
562 {
563         struct statfs *sfs;
564         fsid_t fsid;
565
566         sfs = NULL;
567         if (parsehexfsid(mntname, &fsid) == 0)
568                 sfs = getmntentry(NULL, NULL, &fsid, FIND);
569         if (sfs == NULL)
570                 sfs = getmntentry(NULL, mntname, NULL, FIND);
571         if (sfs == NULL)
572                 sfs = getmntentry(mntname, NULL, NULL, FIND);
573         return (sfs);
574 }
575
576 size_t
577 mntinfo(struct statfs **mntbuf)
578 {
579         static struct statfs *origbuf;
580         size_t bufsize;
581         int mntsize;
582
583         mntsize = getfsstat(NULL, 0, MNT_NOWAIT);
584         if (mntsize <= 0)
585                 return (0);
586         bufsize = (mntsize + 1) * sizeof(struct statfs);
587         if ((origbuf = malloc(bufsize)) == NULL)
588                 err(1, "malloc");
589         mntsize = getfsstat(origbuf, (long)bufsize, MNT_NOWAIT);
590         *mntbuf = origbuf;
591         return (mntsize);
592 }
593
594 /*
595  * Convert a hexadecimal filesystem ID to an fsid_t.
596  * Returns 0 on success.
597  */
598 int
599 parsehexfsid(const char *hex, fsid_t *fsid)
600 {
601         char hexbuf[3];
602         int i;
603
604         if (strlen(hex) != sizeof(*fsid) * 2)
605                 return (-1);
606         hexbuf[2] = '\0';
607         for (i = 0; i < (int)sizeof(*fsid); i++) {
608                 hexbuf[0] = hex[i * 2];
609                 hexbuf[1] = hex[i * 2 + 1];
610                 if (!isxdigit(hexbuf[0]) || !isxdigit(hexbuf[1]))
611                         return (-1);
612                 ((u_char *)fsid)[i] = strtol(hexbuf, NULL, 16);
613         }
614         return (0);
615 }
616
617 /*
618  * xdr routines for mount rpc's
619  */
620 int
621 xdr_dir(XDR *xdrsp, char *dirp)
622 {
623
624         return (xdr_string(xdrsp, &dirp, MNTPATHLEN));
625 }
626
627 void
628 usage(void)
629 {
630
631         (void)fprintf(stderr, "%s\n%s\n",
632             "usage: umount [-fv] special ... | node ... | fsid ...",
633             "       umount -a | -A [-F fstab] [-fv] [-h host] [-t type]");
634         exit(1);
635 }