Plug an fd leak and closedir() two directories.
[dragonfly.git] / bin / df / df.c
1 /*
2  * Copyright (c) 1980, 1990, 1993, 1994
3  *      The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  * @(#) Copyright (c) 1980, 1990, 1993, 1994 The Regents of the University of California.  All rights reserved.
39  * @(#)df.c     8.9 (Berkeley) 5/8/95
40  * $FreeBSD: src/bin/df/df.c,v 1.23.2.9 2002/07/01 00:14:24 iedowse Exp $
41  * $DragonFly: src/bin/df/df.c,v 1.7 2006/01/12 13:43:10 corecode Exp $
42  */
43
44 #include <sys/cdefs.h>
45 #include <sys/param.h>
46 #include <sys/stat.h>
47 #include <sys/mount.h>
48 #include <sys/sysctl.h>
49 #include <vfs/ufs/ufsmount.h>
50 #include <vfs/ufs/fs.h>
51
52 #include <err.h>
53 #include <errno.h>
54 #include <fcntl.h>
55 #include <fstab.h>
56 #include <math.h>
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #include <sysexits.h>
61 #include <unistd.h>
62
63 #define UNITS_SI 1
64 #define UNITS_2 2
65
66 #define KILO_SZ(n) (n)
67 #define MEGA_SZ(n) ((n) * (n))
68 #define GIGA_SZ(n) ((n) * (n) * (n))
69 #define TERA_SZ(n) ((n) * (n) * (n) * (n))
70 #define PETA_SZ(n) ((n) * (n) * (n) * (n) * (n))
71
72 #define KILO_2_SZ (KILO_SZ(1024ULL))
73 #define MEGA_2_SZ (MEGA_SZ(1024ULL))
74 #define GIGA_2_SZ (GIGA_SZ(1024ULL))
75 #define TERA_2_SZ (TERA_SZ(1024ULL))
76 #define PETA_2_SZ (PETA_SZ(1024ULL))
77
78 #define KILO_SI_SZ (KILO_SZ(1000ULL))
79 #define MEGA_SI_SZ (MEGA_SZ(1000ULL))
80 #define GIGA_SI_SZ (GIGA_SZ(1000ULL))
81 #define TERA_SI_SZ (TERA_SZ(1000ULL))
82 #define PETA_SI_SZ (PETA_SZ(1000ULL))
83
84 /* Maximum widths of various fields. */
85 struct maxwidths {
86         int mntfrom;
87         int total;
88         int used;
89         int avail;
90         int iused;
91         int ifree;
92 };
93
94 unsigned long long vals_si [] = {1, KILO_SI_SZ, MEGA_SI_SZ, GIGA_SI_SZ, TERA_SI_SZ, PETA_SI_SZ};
95 unsigned long long vals_base2[] = {1, KILO_2_SZ, MEGA_2_SZ, GIGA_2_SZ, TERA_2_SZ, PETA_2_SZ};
96 unsigned long long *valp;
97
98 typedef enum { NONE, KILO, MEGA, GIGA, TERA, PETA, UNIT_MAX } unit_t;
99
100 unit_t unitp [] = { NONE, KILO, MEGA, GIGA, TERA, PETA };
101
102 int       bread(off_t, void *, int);
103 int       checkvfsname(const char *, char **);
104 char     *getmntpt(char *);
105 int       longwidth(long);
106 char     *makenetvfslist(void);
107 char    **makevfslist(char *);
108 void      prthuman(struct statfs *, long);
109 void      prthumanval(double);
110 void      prtstat(struct statfs *, struct maxwidths *);
111 long      regetmntinfo(struct statfs **, long, char **);
112 int       ufs_df(char *, struct maxwidths *);
113 unit_t    unit_adjust(double *);
114 void      update_maxwidths(struct maxwidths *, struct statfs *);
115 void      usage(void);
116
117 int     aflag = 0, hflag, iflag, nflag;
118 struct  ufs_args mdev;
119
120 static __inline int
121 imax(int a, int b)
122 {
123         return (a > b ? a : b);
124 }
125
126 int
127 main(int argc, char **argv)
128 {
129         struct stat stbuf;
130         struct statfs statfsbuf, *mntbuf;
131         struct maxwidths maxwidths;
132         const char *fstype;
133         char *mntpath, *mntpt, **vfslist;
134         long mntsize;
135         int ch, i, rv;
136
137         fstype = "ufs";
138
139         vfslist = NULL;
140         while ((ch = getopt(argc, argv, "abgHhiklmnPt:")) != -1)
141                 switch (ch) {
142                 case 'a':
143                         aflag = 1;
144                         break;
145                 case 'b':
146                                 /* FALLTHROUGH */
147                 case 'P':
148                         if (putenv("BLOCKSIZE=512") != 0)
149                                 warn("putenv: cannot set BLOCKSIZE=512");
150                         hflag = 0;
151                         break;
152                 case 'g':
153                         if (putenv("BLOCKSIZE=1g") != 0)
154                                 warn("putenv: cannot set BLOCKSIZE=1g");
155                         hflag = 0;
156                         break;
157                 case 'H':
158                         hflag = UNITS_SI;
159                         valp = vals_si;
160                         break;
161                 case 'h':
162                         hflag = UNITS_2;
163                         valp = vals_base2;
164                         break;
165                 case 'i':
166                         iflag = 1;
167                         break;
168                 case 'k':
169                         if (putenv("BLOCKSIZE=1k") != 0)
170                                 warn("putenv: cannot set BLOCKSIZE=1k");
171                         hflag = 0;
172                         break;
173                 case 'l':
174                         if (vfslist != NULL)
175                                 errx(1, "-l and -t are mutually exclusive.");
176                         vfslist = makevfslist(makenetvfslist());
177                         break;
178                 case 'm':
179                         if (putenv("BLOCKSIZE=1m") != 0)
180                                 warn("putenv: cannot set BLOCKSIZE=1m");
181                         hflag = 0;
182                         break;
183                 case 'n':
184                         nflag = 1;
185                         break;
186                 case 't':
187                         if (vfslist != NULL)
188                                 errx(1, "only one -t option may be specified");
189                         fstype = optarg;
190                         vfslist = makevfslist(optarg);
191                         break;
192                 case '?':
193                 default:
194                         usage();
195                 }
196         argc -= optind;
197         argv += optind;
198
199         mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
200         bzero(&maxwidths, sizeof(maxwidths));
201         for (i = 0; i < mntsize; i++)
202                 update_maxwidths(&maxwidths, &mntbuf[i]);
203
204         rv = 0;
205         if (!*argv) {
206                 mntsize = regetmntinfo(&mntbuf, mntsize, vfslist);
207                 bzero(&maxwidths, sizeof(maxwidths));
208                 for (i = 0; i < mntsize; i++)
209                         update_maxwidths(&maxwidths, &mntbuf[i]);
210                 for (i = 0; i < mntsize; i++) {
211                         if (aflag || (mntbuf[i].f_flags & MNT_IGNORE) == 0)
212                                 prtstat(&mntbuf[i], &maxwidths);
213                 }
214                 exit(rv);
215         }
216
217         for (; *argv; argv++) {
218                 if (stat(*argv, &stbuf) < 0) {
219                         if ((mntpt = getmntpt(*argv)) == 0) {
220                                 warn("%s", *argv);
221                                 rv = 1;
222                                 continue;
223                         }
224                 } else if (S_ISCHR(stbuf.st_mode)) {
225                         if ((mntpt = getmntpt(*argv)) == 0) {
226                                 mdev.fspec = *argv;
227                                 mntpath = strdup("/tmp/df.XXXXXX");
228                                 if (mntpath == NULL) {
229                                         warn("strdup failed");
230                                         rv = 1;
231                                         continue;
232                                 }
233                                 mntpt = mkdtemp(mntpath);
234                                 if (mntpt == NULL) {
235                                         warn("mkdtemp(\"%s\") failed", mntpath);
236                                         rv = 1;
237                                         free(mntpath);
238                                         continue;
239                                 }
240                                 if (mount(fstype, mntpt, MNT_RDONLY,
241                                     &mdev) != 0) {
242                                         rv = ufs_df(*argv, &maxwidths) || rv;
243                                         rmdir(mntpt);
244                                         free(mntpath);
245                                         continue;
246                                 } else if (statfs(mntpt, &statfsbuf) == 0) {
247                                         statfsbuf.f_mntonname[0] = '\0';
248                                         prtstat(&statfsbuf, &maxwidths);
249                                 } else {
250                                         warn("%s", *argv);
251                                         rv = 1;
252                                 }
253                                 unmount(mntpt, 0);
254                                 rmdir(mntpt);
255                                 free(mntpath);
256                                 continue;
257                         }
258                 } else
259                         mntpt = *argv;
260                 /*
261                  * Statfs does not take a `wait' flag, so we cannot
262                  * implement nflag here.
263                  */
264                 if (statfs(mntpt, &statfsbuf) < 0) {
265                         warn("%s", mntpt);
266                         rv = 1;
267                         continue;
268                 }
269                 if (argc == 1) {
270                         bzero(&maxwidths, sizeof(maxwidths));
271                         update_maxwidths(&maxwidths, &statfsbuf);
272                 }
273                 prtstat(&statfsbuf, &maxwidths);
274         }
275         return (rv);
276 }
277
278 char *
279 getmntpt(char *name)
280 {
281         long mntsize, i;
282         struct statfs *mntbuf;
283
284         mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
285         for (i = 0; i < mntsize; i++) {
286                 if (!strcmp(mntbuf[i].f_mntfromname, name))
287                         return (mntbuf[i].f_mntonname);
288         }
289         return (0);
290 }
291
292 /*
293  * Make a pass over the filesystem info in ``mntbuf'' filtering out
294  * filesystem types not in vfslist and possibly re-stating to get
295  * current (not cached) info.  Returns the new count of valid statfs bufs.
296  */
297 long
298 regetmntinfo(struct statfs **mntbufp, long mntsize, char **vfslist)
299 {
300         int i, j;
301         struct statfs *mntbuf;
302
303         if (vfslist == NULL)
304                 return (nflag ? mntsize : getmntinfo(mntbufp, MNT_WAIT));
305
306         mntbuf = *mntbufp;
307         for (j = 0, i = 0; i < mntsize; i++) {
308                 if (checkvfsname(mntbuf[i].f_fstypename, vfslist))
309                         continue;
310                 if (!nflag)
311                         statfs(mntbuf[i].f_mntonname,&mntbuf[j]);
312                 else if (i != j)
313                         mntbuf[j] = mntbuf[i];
314                 j++;
315         }
316         return (j);
317 }
318
319 /*
320  * Output in "human-readable" format.  Uses 3 digits max and puts
321  * unit suffixes at the end.  Makes output compact and easy to read,
322  * especially on huge disks.
323  *
324  */
325 unit_t
326 unit_adjust(double *val)
327 {
328         double abval;
329         unit_t unit;
330         unsigned int unit_sz;
331
332         abval = fabs(*val);
333
334         unit_sz = abval ? ilogb(abval) / 10 : 0;
335
336         if (unit_sz >= UNIT_MAX) {
337                 unit = NONE;
338         } else {
339                 unit = unitp[unit_sz];
340                 *val /= (double)valp[unit_sz];
341         }
342
343         return (unit);
344 }
345
346 void
347 prthuman(struct statfs *sfsp, long used)
348 {
349
350         prthumanval((double)sfsp->f_blocks * (double)sfsp->f_bsize);
351         prthumanval((double)used * (double)sfsp->f_bsize);
352         prthumanval((double)sfsp->f_bavail * (double)sfsp->f_bsize);
353 }
354
355 void
356 prthumanval(double bytes)
357 {
358
359         unit_t unit;
360         unit = unit_adjust(&bytes);
361
362         if (bytes == 0)
363                 printf("     0B");
364         else if (bytes > 10)
365                 printf(" %5.0f%c", bytes, "BKMGTPE"[unit]);
366         else
367                 printf(" %5.1f%c", bytes, "BKMGTPE"[unit]);
368 }
369
370 /*
371  * Convert statfs returned filesystem size into BLOCKSIZE units.
372  * Attempts to avoid overflow for large filesystems.
373  */
374 #define fsbtoblk(num, fsbs, bs) \
375         (((fsbs) != 0 && (fsbs) < (bs)) ? \
376                 (num) / ((bs) / (fsbs)) : (num) * ((fsbs) / (bs)))
377
378 /*
379  * Print out status about a filesystem.
380  */
381 void
382 prtstat(struct statfs *sfsp, struct maxwidths *mwp)
383 {
384         static long blocksize;
385         static int headerlen, timesthrough;
386         static const char *header;
387         long used, availblks, inodes;
388
389         if (++timesthrough == 1) {
390                 mwp->mntfrom = imax(mwp->mntfrom, strlen("Filesystem"));
391                 if (hflag) {
392                         header = "  Size";
393                         mwp->total = mwp->used = mwp->avail = strlen(header);
394                 } else {
395                         header = getbsize(&headerlen, &blocksize);
396                         mwp->total = imax(mwp->total, headerlen);
397                 }
398                 mwp->used = imax(mwp->used, strlen("Used"));
399                 mwp->avail = imax(mwp->avail, strlen("Avail"));
400
401                 printf("%-*s %-*s %*s %*s Capacity", mwp->mntfrom,
402                     "Filesystem", mwp->total, header, mwp->used, "Used",
403                     mwp->avail, "Avail");
404                 if (iflag) {
405                         mwp->iused = imax(mwp->iused, strlen("  iused"));
406                         mwp->ifree = imax(mwp->ifree, strlen("ifree"));
407                         printf(" %*s %*s %%iused", mwp->iused - 2,
408                             "iused", mwp->ifree, "ifree");
409                 }
410                 printf("  Mounted on\n");
411         }
412         printf("%-*s", mwp->mntfrom, sfsp->f_mntfromname);
413         used = sfsp->f_blocks - sfsp->f_bfree;
414         availblks = sfsp->f_bavail + used;
415         if (hflag) {
416                 prthuman(sfsp, used);
417         } else {
418                 printf(" %*ld %*ld %*ld", mwp->total,
419                     fsbtoblk(sfsp->f_blocks, sfsp->f_bsize, blocksize),
420                     mwp->used, fsbtoblk(used, sfsp->f_bsize, blocksize),
421                     mwp->avail, fsbtoblk(sfsp->f_bavail, sfsp->f_bsize,
422                     blocksize));
423         }
424         printf(" %5.0f%%",
425             availblks == 0 ? 100.0 : (double)used / (double)availblks * 100.0);
426         if (iflag) {
427                 inodes = sfsp->f_files;
428                 used = inodes - sfsp->f_ffree;
429                 printf(" %*ld %*ld %4.0f%% ", mwp->iused, used,
430                     mwp->ifree, sfsp->f_ffree, inodes == 0 ? 100.0 :
431                     (double)used / (double)inodes * 100.0);
432         } else
433                 printf("  ");
434         printf("  %s\n", sfsp->f_mntonname);
435 }
436
437 /*
438  * Update the maximum field-width information in `mwp' based on
439  * the filesystem specified by `sfsp'.
440  */
441 void
442 update_maxwidths(struct maxwidths *mwp, struct statfs *sfsp)
443 {
444         static long blocksize;
445         int dummy;
446
447         if (blocksize == 0)
448                 getbsize(&dummy, &blocksize);
449
450         mwp->mntfrom = imax(mwp->mntfrom, strlen(sfsp->f_mntfromname));
451         mwp->total = imax(mwp->total, longwidth(fsbtoblk(sfsp->f_blocks,
452             sfsp->f_bsize, blocksize)));
453         mwp->used = imax(mwp->used, longwidth(fsbtoblk(sfsp->f_blocks -
454             sfsp->f_bfree, sfsp->f_bsize, blocksize)));
455         mwp->avail = imax(mwp->avail, longwidth(fsbtoblk(sfsp->f_bavail,
456             sfsp->f_bsize, blocksize)));
457         mwp->iused = imax(mwp->iused, longwidth(sfsp->f_files -
458             sfsp->f_ffree));
459         mwp->ifree = imax(mwp->ifree, longwidth(sfsp->f_ffree));
460 }
461
462 /* Return the width in characters of the specified long. */
463 int
464 longwidth(long val)
465 {
466         int len;
467
468         len = 0;
469         /* Negative or zero values require one extra digit. */
470         if (val <= 0) {
471                 val = -val;
472                 len++;
473         }
474         while (val > 0) {
475                 len++;
476                 val /= 10;
477         }
478
479         return (len);
480 }
481
482 /*
483  * This code constitutes the pre-system call Berkeley df code for extracting
484  * information from filesystem superblocks.
485  */
486
487 union {
488         struct fs iu_fs;
489         char dummy[SBSIZE];
490 } sb;
491 #define sblock sb.iu_fs
492
493 int     rfd;
494
495 int
496 ufs_df(char *file, struct maxwidths *mwp)
497 {
498         struct statfs statfsbuf;
499         struct statfs *sfsp;
500         const char *mntpt;
501         static int synced;
502
503         if (synced++ == 0)
504                 sync();
505
506         if ((rfd = open(file, O_RDONLY)) < 0) {
507                 warn("%s", file);
508                 return (1);
509         }
510         if (bread((off_t)SBOFF, &sblock, SBSIZE) == 0) {
511                 close(rfd);
512                 return (1);
513         }
514         sfsp = &statfsbuf;
515         sfsp->f_type = 1;
516         strcpy(sfsp->f_fstypename, "ufs");
517         sfsp->f_flags = 0;
518         sfsp->f_bsize = sblock.fs_fsize;
519         sfsp->f_iosize = sblock.fs_bsize;
520         sfsp->f_blocks = sblock.fs_dsize;
521         sfsp->f_bfree = sblock.fs_cstotal.cs_nbfree * sblock.fs_frag +
522                 sblock.fs_cstotal.cs_nffree;
523         sfsp->f_bavail = freespace(&sblock, sblock.fs_minfree);
524         sfsp->f_files =  sblock.fs_ncg * sblock.fs_ipg;
525         sfsp->f_ffree = sblock.fs_cstotal.cs_nifree;
526         sfsp->f_fsid.val[0] = 0;
527         sfsp->f_fsid.val[1] = 0;
528         if ((mntpt = getmntpt(file)) == 0)
529                 mntpt = "";
530         memmove(&sfsp->f_mntonname[0], mntpt, (size_t)MNAMELEN);
531         memmove(&sfsp->f_mntfromname[0], file, (size_t)MNAMELEN);
532         prtstat(sfsp, mwp);
533         close(rfd);
534         return (0);
535 }
536
537 int
538 bread(off_t off, void *buf, int cnt)
539 {
540         ssize_t nr;
541
542         lseek(rfd, off, SEEK_SET);
543         if ((nr = read(rfd, buf, (size_t)cnt)) != (ssize_t)cnt) {
544                 /* Probably a dismounted disk if errno == EIO. */
545                 if (errno != EIO)
546                         fprintf(stderr, "\ndf: %lld: %s\n",
547                             (long long)off, strerror(nr > 0 ? EIO : errno));
548                 return (0);
549         }
550         return (1);
551 }
552
553 void
554 usage(void)
555 {
556
557         fprintf(stderr,
558             "usage: df [-b | -H | -h | -k | -m | -P] [-ailn] [-t type] [file | filesystem ...]\n");
559         exit(EX_USAGE);
560 }
561
562 char *
563 makenetvfslist(void)
564 {
565         char *str, *strptr, **listptr;
566         int mib[3], maxvfsconf, cnt=0, i;
567         size_t miblen;
568         struct ovfsconf *ptr;
569
570         mib[0] = CTL_VFS; mib[1] = VFS_GENERIC; mib[2] = VFS_MAXTYPENUM;
571         miblen=sizeof(maxvfsconf);
572         if (sysctl(mib, (unsigned int)(sizeof(mib) / sizeof(mib[0])),
573             &maxvfsconf, &miblen, NULL, 0)) {
574                 warnx("sysctl failed");
575                 return (NULL);
576         }
577
578         if ((listptr = malloc(sizeof(char*) * maxvfsconf)) == NULL) {
579                 warnx("malloc failed");
580                 return (NULL);
581         }
582
583         for (ptr = getvfsent(); ptr; ptr = getvfsent())
584                 if (ptr->vfc_flags & VFCF_NETWORK) {
585                         listptr[cnt++] = strdup(ptr->vfc_name);
586                         if (listptr[cnt-1] == NULL) {
587                                 warnx("malloc failed");
588                                 return (NULL);
589                         }
590                 }
591
592         if (cnt == 0 ||
593             (str = malloc(sizeof(char) * (32 * cnt + cnt + 2))) == NULL) {
594                 if (cnt > 0)
595                         warnx("malloc failed");
596                 free(listptr);
597                 return (NULL);
598         }
599
600         *str = 'n'; *(str + 1) = 'o';
601         for (i = 0, strptr = str + 2; i < cnt; i++, strptr++) {
602                 strncpy(strptr, listptr[i], 32);
603                 strptr += strlen(listptr[i]);
604                 *strptr = ',';
605                 free(listptr[i]);
606         }
607         *(--strptr) = NULL;
608
609         free(listptr);
610         return (str);
611 }