1 /*        $NetBSD: quotacheck.c,v 1.51 2023/01/07 19:41:30 chs Exp $  */
2 
3 /*
4  * Copyright (c) 1980, 1990, 1993
5  *        The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Robert Elz at The University of Melbourne.
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. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #include <sys/cdefs.h>
36 #ifndef lint
37 __COPYRIGHT("@(#) Copyright (c) 1980, 1990, 1993\
38  The Regents of the University of California.  All rights reserved.");
39 #endif /* not lint */
40 
41 #ifndef lint
42 #if 0
43 static char sccsid[] = "@(#)quotacheck.c          8.6 (Berkeley) 4/28/95";
44 #else
45 __RCSID("$NetBSD: quotacheck.c,v 1.51 2023/01/07 19:41:30 chs Exp $");
46 #endif
47 #endif /* not lint */
48 
49 /*
50  * Fix up / report on disk quotas & usage
51  */
52 #include <sys/param.h>
53 #include <sys/stat.h>
54 #include <sys/queue.h>
55 #include <sys/statvfs.h>
56 
57 #include <ufs/ufs/dinode.h>
58 #include <ufs/ufs/quota1.h>
59 #include <ufs/ufs/ufs_bswap.h>
60 #include <ufs/ffs/fs.h>
61 #include <ufs/ffs/ffs_extern.h>
62 
63 #include <err.h>
64 #include <fcntl.h>
65 #include <fstab.h>
66 #include <pwd.h>
67 #include <grp.h>
68 #include <errno.h>
69 #include <unistd.h>
70 #include <stdio.h>
71 #include <stdlib.h>
72 #include <string.h>
73 #include <util.h>
74 
75 #include "fsutil.h"
76 #include "quotautil.h"
77 
78 #ifndef FS_UFS1_MAGIC
79 # define FS_UFS1_MAGIC                  FS_MAGIC /* 0x011954 */
80 # define FS_UFS1_MAGIC_SWAPPED          0x54190100 /* bswap32(0x011954) */
81 # define DINODE1_SIZE                   sizeof(struct dinode)
82 # define DINODE2_SIZE                   0
83 #else
84 # define HAVE_UFSv2 1
85 #endif
86 
87 #ifndef SBLOCKSIZE
88 # define SBLOCKSIZE SBSIZE
89 #endif
90 #ifndef SBLOCKSEARCH
91 # define SBLOCKSEARCH         { SBSIZE, -1 }
92 #endif
93 
94 static const char *quotagroup = QUOTAGROUP;
95 
96 static union {
97           struct    fs        sblk;
98           char      dummy[MAXBSIZE];
99 } un;
100 #define   sblock    un.sblk
101 static long dev_bsize;
102 static long maxino;
103 
104 struct quotaname {
105           long      flags;
106           char      grpqfname[MAXPATHLEN + 1];
107           char      usrqfname[MAXPATHLEN + 1];
108 };
109 #define   HASUSR    1
110 #define   HASGRP    2
111 
112 struct fileusage {
113           struct    fileusage *fu_next;
114           u_long    fu_curinodes;
115           u_long    fu_curblocks;
116           uint32_t fu_id;               /* uid_t, gid_t */
117           char      fu_name[1];
118           /* actually bigger */
119 };
120 #define FUHASH 1024 /* must be power of two */
121 static struct fileusage *fuhead[MAXQUOTAS][FUHASH];
122 
123 
124 union comb_dinode {
125 #ifdef HAVE_UFSv2
126           struct ufs1_dinode dp1;
127           struct ufs2_dinode dp2;
128 #else
129           struct dinode dp1;
130 #endif
131 };
132 #ifdef HAVE_UFSv2
133 #define DIP(dp, field) \
134           (is_ufs2 ? (dp)->dp2.di_##field : (dp)->dp1.di_##field)
135 #else
136 #define DIP(dp, field) (dp)->dp1.di_##field
137 #endif
138 
139 
140 static int          aflag;              /* all file systems */
141 static int          gflag;              /* check group quotas */
142 static int          uflag;              /* check user quotas */
143 static int          vflag;              /* verbose */
144 static int          qflag;              /* quick but untidy mode */
145 static int          fi;                 /* open disk file descriptor */
146 static uint32_t highid[MAXQUOTAS];/* highest addid()'ed identifier per type */
147 static int needswap;          /* FS is in swapped order */
148 static int got_siginfo = 0; /* got a siginfo signal */
149 static int is_ufs2;
150 
151 
152 static void usage(void) __attribute__((__noreturn__));
153 static void *needchk(struct fstab *);
154 static int chkquota(const char *, const char *, const char *, void *, pid_t *);
155 static int update(const char *, const char *, int);
156 static uint32_t skipforward(uint32_t, uint32_t, FILE *);
157 static int getquotagid(void);
158 static struct fileusage *lookup(uint32_t, int);
159 static struct fileusage *addid(uint32_t, int, const char *);
160 static uint32_t subsequent(uint32_t, int) ;
161 static union comb_dinode *getnextinode(ino_t);
162 static void setinodebuf(ino_t);
163 static void freeinodebuf(void);
164 static void bread(daddr_t, char *, long);
165 static void infohandler(int sig);
166 static void swap_dinode1(union comb_dinode *, int);
167 #ifdef HAVE_UFSv2
168 static void swap_dinode2(union comb_dinode *, int);
169 #endif
170 
171 int
main(int argc,char * argv[])172 main(int argc, char *argv[])
173 {
174           struct fstab *fs;
175           struct passwd *pw;
176           struct group *gr;
177           struct quotaname *auxdata;
178           int i, argnum, maxrun, errs;
179           long done = 0;
180           int flags = CHECK_PREEN;
181           const char *name;
182           int ch;
183 
184           errs = maxrun = 0;
185           while ((ch = getopt(argc, argv, "aguvqdl:")) != -1) {
186                     switch(ch) {
187                     case 'a':
188                               aflag++;
189                               break;
190                     case 'd':
191                               flags |= CHECK_DEBUG;
192                               break;
193                     case 'g':
194                               gflag++;
195                               break;
196                     case 'u':
197                               uflag++;
198                               break;
199                     case 'q':
200                               qflag++;
201                               break;
202                     case 'v':
203                               vflag++;
204                               break;
205                     case 'l':
206                               maxrun = atoi(optarg);
207                               break;
208                     default:
209                               usage();
210                     }
211           }
212           argc -= optind;
213           argv += optind;
214           if ((argc == 0 && !aflag) || (argc > 0 && aflag) || (!aflag && maxrun))
215                     usage();
216           if (!gflag && !uflag) {
217                     gflag++;
218                     uflag++;
219           }
220 
221           /* If -a, we do not want to pay the cost of processing every
222            * group and password entry if there are no filesystems with quotas
223            */
224           if (aflag) {
225                     i = 0;
226                     while ((fs = getfsent()) != NULL) {
227                               if (needchk(fs))
228                                         i = 1;
229                     }
230                     endfsent();
231                     if (!i)   /* No filesystems with quotas */
232                               return 0;
233           }
234 
235           if (gflag) {
236                     setgrent();
237                     while ((gr = getgrent()) != 0)
238                               (void) addid((uint32_t)gr->gr_gid, GRPQUOTA, gr->gr_name);
239                     endgrent();
240           }
241           if (uflag) {
242                     setpwent();
243                     while ((pw = getpwent()) != 0)
244                               (void) addid((uint32_t)pw->pw_uid, USRQUOTA, pw->pw_name);
245                     endpwent();
246           }
247           if (aflag)
248                     exit(checkfstab(flags, maxrun, needchk, chkquota));
249           if (setfsent() == 0)
250                     err(1, "%s: can't open", FSTAB);
251           while ((fs = getfsent()) != NULL) {
252                     const char *fsspec;
253                     char buf[MAXPATHLEN];
254                     fsspec = getfsspecname(buf, sizeof(buf), fs->fs_spec);
255                     if (fsspec == NULL) {
256                               warn("%s", buf);
257                               continue;
258                     }
259                     if (((argnum = oneof(fs->fs_file, argv, argc)) >= 0 ||
260                         (argnum = oneof(fsspec, argv, argc)) >= 0) &&
261                         (auxdata = needchk(fs)) &&
262                         (name = blockcheck(fsspec))) {
263                               done |= 1 << argnum;
264                               errs += chkquota(fs->fs_type, name, fs->fs_file,
265                                   auxdata, NULL);
266                     }
267           }
268           endfsent();
269           for (i = 0; i < argc; i++)
270                     if ((done & (1 << i)) == 0)
271                               warnx("%s not found in %s", argv[i], FSTAB);
272           return errs;
273 }
274 
275 static void
usage(void)276 usage(void)
277 {
278           const char *p = getprogname();
279           (void)fprintf(stderr, "Usage: %s -a [-gquv] [-l <maxparallel>]\n"
280               "\t%s [-gquv] <filesys> ...\n", p, p);
281           exit(1);
282 }
283 
284 static void *
needchk(struct fstab * fs)285 needchk(struct fstab *fs)
286 {
287           struct quotaname *qnp;
288           char qfnp[MAXPATHLEN];
289 
290           if (strcmp(fs->fs_vfstype, "ffs") ||
291               strcmp(fs->fs_type, FSTAB_RW))
292                     return (NULL);
293           if ((qnp = malloc(sizeof(*qnp))) == NULL)
294                     err(1, "%s", strerror(errno));
295           qnp->flags = 0;
296           if (gflag && hasquota(qfnp, sizeof(qfnp), fs, GRPQUOTA)) {
297                     strlcpy(qnp->grpqfname, qfnp, sizeof(qnp->grpqfname));
298                     qnp->flags |= HASGRP;
299           }
300           if (uflag && hasquota(qfnp, sizeof(qfnp), fs, USRQUOTA)) {
301                     strlcpy(qnp->usrqfname, qfnp, sizeof(qnp->usrqfname));
302                     qnp->flags |= HASUSR;
303           }
304           if (qnp->flags)
305                     return (qnp);
306           free(qnp);
307           return (NULL);
308 }
309 
310 static off_t sblock_try[] = SBLOCKSEARCH;
311 
312 /*
313  * Scan the specified filesystem to check quota(s) present on it.
314  */
315 static int
chkquota(const char * type,const char * fsname,const char * mntpt,void * v,pid_t * pid)316 chkquota(const char *type, const char *fsname, const char *mntpt, void *v,
317     pid_t *pid)
318 {
319           struct quotaname *qnp = v;
320           struct fileusage *fup;
321           union comb_dinode *dp;
322           int i, mode, errs = 0, inosused;
323           uint32_t cg;
324           ino_t ino;
325           struct cg *cgp;
326           char msgbuf[4096];
327 
328           if (pid != NULL) {
329                     fflush(stdout);
330                     switch ((*pid = fork())) {
331                     default:
332                               return 0;
333                     case 0:
334                               break;
335                     case -1:
336                               err(1, "Cannot fork");
337                     }
338                     setvbuf(stdout, msgbuf, _IOFBF, sizeof msgbuf);
339           }
340 
341           if ((fi = open(fsname, O_RDONLY, 0)) < 0) {
342                     warn("Cannot open %s", fsname);
343                     if (pid != NULL)
344                               exit(1);
345                     return 1;
346           }
347           if (vflag) {
348                     (void)printf("*** Checking ");
349                     if (qnp->flags & HASUSR)
350                               (void)printf("%s%s", qfextension[USRQUOTA],
351                                   (qnp->flags & HASGRP) ? " and " : "");
352                     if (qnp->flags & HASGRP)
353                               (void)printf("%s", qfextension[GRPQUOTA]);
354                     (void)printf(" quotas for %s (%s)\n", fsname, mntpt);
355                     fflush(stdout);
356           }
357           signal(SIGINFO, infohandler);
358           sync();
359           dev_bsize = 1;
360 
361           for (i = 0; ; i++) {
362                     if (sblock_try[i] == -1) {
363                               warnx("%s: superblock not found", fsname);
364                               if (pid != NULL)
365                                         exit(1);
366                               return 1;
367                     }
368                     bread(sblock_try[i], (char *)&sblock, SBLOCKSIZE);
369                     switch (sblock.fs_magic) {
370 #ifdef HAVE_UFSv2
371                     case FS_UFS2EA_MAGIC:
372                               sblock.fs_magic = FS_UFS2_MAGIC;
373                               /*FALLTHROUGH*/
374                     case FS_UFS2_MAGIC:
375                               is_ufs2 = 1;
376                               /*FALLTHROUGH*/
377 #endif
378                     case FS_UFS1_MAGIC:
379                               break;
380 #ifdef HAVE_UFSv2
381                     case FS_UFS2EA_MAGIC_SWAPPED:
382                               sblock.fs_magic = FS_UFS2_MAGIC_SWAPPED;
383                               /*FALLTHROUGH*/
384                     case FS_UFS2_MAGIC_SWAPPED:
385                               is_ufs2 = 1;
386                               /*FALLTHROUGH*/
387 #endif
388                     case FS_UFS1_MAGIC_SWAPPED:
389                               needswap = 1;
390                               ffs_sb_swap(&sblock, &sblock);
391                               break;
392                     default:
393                               continue;
394                     }
395 
396 #ifdef HAVE_UFSv2
397                     if (is_ufs2 || sblock.fs_old_flags & FS_FLAGS_UPDATED) {
398                               if (sblock.fs_sblockloc != sblock_try[i])
399                                         continue;
400                     } else {
401                               if (sblock_try[i] == SBLOCK_UFS2)
402                                         continue;
403                     }
404 #endif
405                     break;
406           }
407 
408           cgp = malloc(sblock.fs_cgsize);
409           if (cgp == NULL) {
410                     warn("%s: can't allocate %d bytes of cg space", fsname,
411                         sblock.fs_cgsize);
412                     if (pid != NULL)
413                               exit(1);
414                     return 1;
415           }
416 
417           dev_bsize = sblock.fs_fsize / FFS_FSBTODB(&sblock, 1);
418           maxino = sblock.fs_ncg * sblock.fs_ipg;
419           for (cg = 0; cg < sblock.fs_ncg; cg++) {
420                     ino = cg * sblock.fs_ipg;
421                     setinodebuf(ino);
422 #ifdef HAVE_UFSv2
423                     if (sblock.fs_magic == FS_UFS2_MAGIC) {
424                               bread(FFS_FSBTODB(&sblock, cgtod(&sblock, cg)), (char *)cgp,
425                                   sblock.fs_cgsize);
426                               if (needswap)
427                                         ffs_cg_swap(cgp, cgp, &sblock);
428                               inosused = cgp->cg_initediblk;
429                     } else
430 #endif
431                               inosused = sblock.fs_ipg;
432                     for (i = 0; i < inosused; i++, ino++) {
433                               if (got_siginfo) {
434                                         fprintf(stderr,
435                                             "%s: cyl group %d of %d (%d%%)\n",
436                                             fsname, cg, sblock.fs_ncg,
437                                             cg * 100 / sblock.fs_ncg);
438                                         got_siginfo = 0;
439                               }
440                               if (ino < UFS_ROOTINO)
441                                         continue;
442                               if ((dp = getnextinode(ino)) == NULL)
443                                         continue;
444                               if ((mode = DIP(dp, mode) & IFMT) == 0)
445                                         continue;
446                               if (qnp->flags & HASGRP) {
447                                         fup = addid(DIP(dp, gid), GRPQUOTA,
448                                             (char *)0);
449                                         fup->fu_curinodes++;
450                                         if (mode == IFREG || mode == IFDIR ||
451                                             mode == IFLNK)
452                                                   fup->fu_curblocks += DIP(dp, blocks);
453                               }
454                               if (qnp->flags & HASUSR) {
455                                         fup = addid(DIP(dp, uid), USRQUOTA,
456                                             (char *)0);
457                                         fup->fu_curinodes++;
458                                         if (mode == IFREG || mode == IFDIR ||
459                                             mode == IFLNK)
460                                                   fup->fu_curblocks += DIP(dp, blocks);
461                               }
462                     }
463           }
464           freeinodebuf();
465           free(cgp);
466           if (qnp->flags & HASUSR)
467                     errs += update(mntpt, qnp->usrqfname, USRQUOTA);
468           if (qnp->flags & HASGRP)
469                     errs += update(mntpt, qnp->grpqfname, GRPQUOTA);
470           close(fi);
471           if (pid != NULL)
472                     exit(errs);
473           return errs;
474 }
475 
476 /*
477  * Update a specified quota file.
478  */
479 static int
update(const char * fsname,const char * quotafile,int type)480 update(const char *fsname, const char *quotafile, int type)
481 {
482           struct fileusage *fup;
483           FILE *qfi, *qfo;
484           uint32_t id, lastid, nextid;
485           int need_seek;
486           struct dqblk dqbuf;
487           static struct dqblk zerodqbuf;
488           static struct fileusage zerofileusage;
489           struct statvfs *fst;
490           int nfst, i;
491 
492           nfst = getmntinfo(&fst, MNT_WAIT);
493           if (nfst == 0)
494                     errx(1, "no filesystems mounted!");
495 
496           for (i = 0; i < nfst; i++) {
497                     if (strncmp(fst[i].f_fstypename, "ffs",
498                         sizeof(fst[i].f_fstypename)) == 0 &&
499                         strncmp(fst[i].f_mntonname, fsname,
500                         sizeof(fst[i].f_mntonname)) == 0 &&
501                         (fst[i].f_flag & ST_QUOTA) != 0) {
502                               warnx("filesystem %s has quotas already turned on",
503                                   fsname);
504                     }
505           }
506 
507           if ((qfo = fopen(quotafile, "r+")) == NULL) {
508                     if (errno == ENOENT)
509                               qfo = fopen(quotafile, "w+");
510                     if (qfo) {
511                               (void) fprintf(stderr,
512                                   "quotacheck: creating quota file %s\n", quotafile);
513 #define   MODE      (S_IRUSR|S_IWUSR|S_IRGRP)
514                               (void) fchown(fileno(qfo), getuid(), getquotagid());
515                               (void) fchmod(fileno(qfo), MODE);
516                     } else {
517                               (void) fprintf(stderr,
518                                   "quotacheck: %s: %s\n", quotafile, strerror(errno));
519                               return (1);
520                     }
521           }
522           if ((qfi = fopen(quotafile, "r")) == NULL) {
523                     (void) fprintf(stderr,
524                         "quotacheck: %s: %s\n", quotafile, strerror(errno));
525                     (void) fclose(qfo);
526                     return (1);
527           }
528           need_seek = 1;
529           for (lastid = highid[type], id = 0; id <= lastid; id = nextid) {
530                     if (fread((char *)&dqbuf, sizeof(struct dqblk), 1, qfi) == 0)
531                               dqbuf = zerodqbuf;
532                     if ((fup = lookup(id, type)) == 0)
533                               fup = &zerofileusage;
534 
535                     nextid = subsequent(id, type);
536                     /* watch out for id == UINT32_MAX */
537                     if (nextid > 0 && nextid != id + 1)
538                               nextid = skipforward(id, nextid, qfi);
539 
540                     if (got_siginfo) {
541                               /*
542                                * XXX this could try to show percentage through
543                                * the ID list
544                                */
545                               fprintf(stderr, "%s: updating %s quotas for id=%"
546                                   PRIu32 " (%s)\n", fsname,
547                                   qfextension[type < MAXQUOTAS ? type : MAXQUOTAS],
548                                   id, fup->fu_name);
549                               got_siginfo = 0;
550                     }
551                     if (dqbuf.dqb_curinodes == fup->fu_curinodes &&
552                         dqbuf.dqb_curblocks == fup->fu_curblocks) {
553                               fup->fu_curinodes = 0;        /* reset usage  */
554                               fup->fu_curblocks = 0;        /* for next filesystem */
555 
556                               need_seek = 1;
557                               /* infinite loop avoidance (OR do as "nextid < id"?) */
558                               if (id == UINT32_MAX || nextid == 0) {
559                                         break;
560                               }
561                               continue;
562                     }
563                     if (vflag) {
564                               if (aflag)
565                                         printf("%s: ", fsname);
566                               printf("%-8s fixed:", fup->fu_name);
567                               if (dqbuf.dqb_curinodes != fup->fu_curinodes)
568                                         (void)printf("\tinodes %d -> %ld",
569                                                   dqbuf.dqb_curinodes, fup->fu_curinodes);
570                               if (dqbuf.dqb_curblocks != fup->fu_curblocks)
571                                         (void)printf("\tblocks %d -> %ld",
572                                                   dqbuf.dqb_curblocks, fup->fu_curblocks);
573                               (void)printf("\n");
574                     }
575                     /*
576                      * Reset time limit if have a soft limit and were
577                      * previously under it, but are now over it.
578                      */
579                     if (dqbuf.dqb_bsoftlimit &&
580                         dqbuf.dqb_curblocks < dqbuf.dqb_bsoftlimit &&
581                         fup->fu_curblocks >= dqbuf.dqb_bsoftlimit)
582                               dqbuf.dqb_btime = 0;
583                     if (dqbuf.dqb_isoftlimit &&
584                         dqbuf.dqb_curinodes < dqbuf.dqb_isoftlimit &&
585                         fup->fu_curinodes >= dqbuf.dqb_isoftlimit)
586                               dqbuf.dqb_itime = 0;
587                     dqbuf.dqb_curinodes = fup->fu_curinodes;
588                     dqbuf.dqb_curblocks = fup->fu_curblocks;
589 
590                     if (need_seek) {
591                               (void) fseeko(qfo, (off_t)id * sizeof(struct dqblk),
592                                   SEEK_SET);
593                               need_seek = nextid != id + 1;
594                     }
595                     (void) fwrite(&dqbuf, sizeof(struct dqblk), 1, qfo);
596 
597                     fup->fu_curinodes = 0;
598                     fup->fu_curblocks = 0;
599                     /* infinite loop avoidance (OR do as "nextid < id"?) */
600                     if (id == UINT32_MAX || nextid == 0) {
601                               break;
602                     }
603           }
604           (void)fclose(qfi);
605           (void)fflush(qfo);
606           if (highid[type] != UINT32_MAX)
607                     (void)ftruncate(fileno(qfo),
608                         (off_t)((highid[type] + 1) * sizeof(struct dqblk)));
609           (void)fclose(qfo);
610           return 0;
611 }
612 
613 static uint32_t
skipforward(uint32_t cur,uint32_t to,FILE * qfi)614 skipforward(uint32_t cur, uint32_t to, FILE *qfi)
615 {
616           struct dqblk dqbuf;
617 
618           if (qflag) {
619                     (void)fseeko(qfi, (off_t)to * sizeof(struct dqblk), SEEK_SET);
620                     return to;
621           }
622 
623           while (++cur < to) {
624                     /*
625                      * if EOF occurs, nothing left to read, we're done
626                      */
627                     if (fread((char *)&dqbuf, sizeof(struct dqblk), 1, qfi) == 0)
628                               return (to);
629 
630                     /*
631                      * If we find an entry that shows usage, before the next
632                      * id that has actual usage, we have to stop here, so the
633                      * incorrect entry can be corrected in the file
634                      */
635                     if (dqbuf.dqb_curinodes != 0 || dqbuf.dqb_curblocks != 0) {
636                               (void)fseek(qfi, -(long)sizeof(struct dqblk), SEEK_CUR);
637                               return cur;
638                     }
639           }
640           return to;
641 }
642 
643 /*
644  * Determine the group identifier for quota files.
645  */
646 static int
getquotagid(void)647 getquotagid(void)
648 {
649           struct group *gr;
650 
651           if ((gr = getgrnam(quotagroup)) != NULL)
652                     return gr->gr_gid;
653           return -1;
654 }
655 
656 /*
657  * Routines to manage the file usage table.
658  *
659  * Lookup an id of a specific type.
660  */
661 static struct fileusage *
lookup(uint32_t id,int type)662 lookup(uint32_t id, int type)
663 {
664           struct fileusage *fup;
665 
666           for (fup = fuhead[type][id & (FUHASH-1)]; fup != 0; fup = fup->fu_next)
667                     if (fup->fu_id == id)
668                               return fup;
669           return NULL;
670 }
671 
672 /*
673  * Add a new file usage id if it does not already exist.
674  */
675 static struct fileusage *
addid(uint32_t id,int type,const char * name)676 addid(uint32_t id, int type, const char *name)
677 {
678           struct fileusage *fup, **fhp;
679           size_t len;
680 
681           if ((fup = lookup(id, type)) != NULL)
682                     return fup;
683           if (name)
684                     len = strlen(name);
685           else
686                     len = 10;
687           if ((fup = calloc(1, sizeof(*fup) + len)) == NULL)
688                     err(1, "%s", strerror(errno));
689           fhp = &fuhead[type][id & (FUHASH - 1)];
690           fup->fu_next = *fhp;
691           *fhp = fup;
692           fup->fu_id = id;
693           if (id > highid[type])
694                     highid[type] = id;
695           if (name)
696                     memmove(fup->fu_name, name, len + 1);
697           else
698                     (void)snprintf(fup->fu_name, len + 1, "%" PRIu32, id);
699           return fup;
700 }
701 
702 static uint32_t
subsequent(uint32_t id,int type)703 subsequent(uint32_t id, int type)
704 {
705           struct fileusage *fup, **iup, **cup;
706           uint32_t next, offset;
707 
708           next = highid[type] + 1;
709           offset = 0;
710           cup = iup = &fuhead[type][id & (FUHASH-1)];
711           do {
712                     ++offset;
713                     if (++cup >= &fuhead[type][FUHASH])
714                               cup = &fuhead[type][0];
715                     for (fup = *cup; fup != 0; fup = fup->fu_next) {
716                               if (fup->fu_id > id && fup->fu_id <= id + offset)
717                                         return (fup->fu_id);
718                               if (fup->fu_id > id && fup->fu_id < next)
719                                         next = fup->fu_id;
720                     }
721           } while (cup != iup);
722 
723           return next;
724 }
725 
726 /*
727  * Special purpose version of ginode used to optimize first pass
728  * over all the inodes in numerical order.
729  */
730 static ino_t nextino, lastinum, lastvalidinum;
731 static long readcnt, readpercg, fullcnt, inobufsize, partialcnt, partialsize;
732 static union comb_dinode *inodebuf;
733 #define INOBUFSIZE  56*1024   /* size of buffer to read inodes */
734 
735 static union comb_dinode *
getnextinode(ino_t inumber)736 getnextinode(ino_t inumber)
737 {
738           long size;
739           daddr_t dblk;
740           static union comb_dinode *dp;
741           union comb_dinode *ret;
742 
743           if (inumber != nextino++ || inumber > lastvalidinum) {
744                     errx(1, "bad inode number %llu to nextinode",
745                         (unsigned long long)inumber);
746           }
747 
748           if (inumber >= lastinum) {
749                     readcnt++;
750                     dblk = FFS_FSBTODB(&sblock, ino_to_fsba(&sblock, lastinum));
751                     if (readcnt % readpercg == 0) {
752                               size = partialsize;
753                               lastinum += partialcnt;
754                     } else {
755                               size = inobufsize;
756                               lastinum += fullcnt;
757                     }
758                     (void)bread(dblk, (caddr_t)inodebuf, size);
759                     if (needswap) {
760 #ifdef HAVE_UFSv2
761                               if (is_ufs2)
762                                         swap_dinode2(inodebuf, lastinum - inumber);
763                               else
764 #endif
765                                         swap_dinode1(inodebuf, lastinum - inumber);
766                     }
767                     dp = (union comb_dinode *)inodebuf;
768           }
769           ret = dp;
770           dp = (union comb_dinode *)
771               ((char *)dp + (is_ufs2 ? DINODE2_SIZE : DINODE1_SIZE));
772           return ret;
773 }
774 
775 static void
setinodebuf(ino_t inum)776 setinodebuf(ino_t inum)
777 {
778 
779           if (inum % sblock.fs_ipg != 0)
780                     errx(1, "bad inode number %llu to setinodebuf",
781                         (unsigned long long)inum);
782 
783           lastvalidinum = inum + sblock.fs_ipg - 1;
784           nextino = inum;
785           lastinum = inum;
786           readcnt = 0;
787           if (inodebuf != NULL)
788                     return;
789           inobufsize = ffs_blkroundup(&sblock, INOBUFSIZE);
790           fullcnt = inobufsize / (is_ufs2 ? DINODE2_SIZE : DINODE1_SIZE);
791           readpercg = sblock.fs_ipg / fullcnt;
792           partialcnt = sblock.fs_ipg % fullcnt;
793           partialsize = partialcnt * (is_ufs2 ? DINODE2_SIZE : DINODE1_SIZE);
794           if (partialcnt != 0) {
795                     readpercg++;
796           } else {
797                     partialcnt = fullcnt;
798                     partialsize = inobufsize;
799           }
800           if (inodebuf == NULL &&
801               (inodebuf = malloc((unsigned)inobufsize)) == NULL)
802                     errx(1, "Cannot allocate space for inode buffer");
803           while (nextino < UFS_ROOTINO)
804                     getnextinode(nextino);
805 }
806 
807 static void
freeinodebuf(void)808 freeinodebuf(void)
809 {
810 
811           free(inodebuf);
812           inodebuf = NULL;
813 }
814 
815 
816 #ifdef HAVE_UFSv2
817 static void
swap_dinode1(union comb_dinode * dp,int n)818 swap_dinode1(union comb_dinode *dp, int n)
819 {
820           int i;
821           struct ufs1_dinode *dp1;
822 
823           dp1 = (struct ufs1_dinode *)&dp->dp1;
824           for (i = 0; i < n; i++, dp1++)
825                     ffs_dinode1_swap(dp1, dp1);
826 }
827 
828 static void
swap_dinode2(union comb_dinode * dp,int n)829 swap_dinode2(union comb_dinode *dp, int n)
830 {
831           int i;
832           struct ufs2_dinode *dp2;
833 
834           dp2 = (struct ufs2_dinode *)&dp->dp2;
835           for (i = 0; i < n; i++, dp2++)
836                     ffs_dinode2_swap(dp2, dp2);
837 }
838 
839 #else
840 
841 static void
swap_dinode1(union comb_dinode * dp,int n)842 swap_dinode1(union comb_dinode *dp, int n)
843 {
844           int i;
845           struct dinode *dp1;
846 
847           dp1 = (struct dinode *) &dp->dp1;
848           for (i = 0; i < n; i++, dp1++)
849                     ffs_dinode_swap(dp1, dp1);
850 }
851 
852 #endif
853 
854 /*
855  * Read specified disk blocks.
856  */
857 static void
bread(daddr_t bno,char * buf,long cnt)858 bread(daddr_t bno, char *buf, long cnt)
859 {
860 
861           if (lseek(fi, (off_t)bno * dev_bsize, SEEK_SET) < 0 ||
862               read(fi, buf, cnt) != cnt)
863                     err(1, "block %lld", (long long)bno);
864 }
865 
866 static void
infohandler(int sig)867 infohandler(int sig)
868 {
869           got_siginfo = 1;
870 }
871