]> CyberLeo.Net >> Repos - FreeBSD/releng/9.2.git/blob - sbin/fsdb/fsdb.c
- Copy stable/9 to releng/9.2 as part of the 9.2-RELEASE cycle.
[FreeBSD/releng/9.2.git] / sbin / fsdb / fsdb.c
1 /*      $NetBSD: fsdb.c,v 1.2 1995/10/08 23:18:10 thorpej Exp $ */
2
3 /*
4  *  Copyright (c) 1995 John T. Kohl
5  *  All rights reserved.
6  * 
7  *  Redistribution and use in source and binary forms, with or without
8  *  modification, are permitted provided that the following conditions
9  *  are met:
10  *  1. Redistributions of source code must retain the above copyright
11  *     notice, this list of conditions and the following disclaimer.
12  *  2. Redistributions in binary form must reproduce the above copyright
13  *     notice, this list of conditions and the following disclaimer in the
14  *     documentation and/or other materials provided with the distribution.
15  *  3. The name of the author may not be used to endorse or promote products
16  *     derived from this software without specific prior written permission.
17  * 
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR `AS IS'' AND ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
22  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28  * POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #ifndef lint
32 static const char rcsid[] =
33   "$FreeBSD$";
34 #endif /* not lint */
35
36 #include <sys/param.h>
37 #include <ctype.h>
38 #include <err.h>
39 #include <grp.h>
40 #include <histedit.h>
41 #include <pwd.h>
42 #include <string.h>
43 #include <time.h>
44 #include <timeconv.h>
45
46 #include <ufs/ufs/dinode.h>
47 #include <ufs/ufs/dir.h>
48 #include <ufs/ffs/fs.h>
49
50 #include "fsdb.h"
51 #include "fsck.h"
52
53 static void usage(void) __dead2;
54 int cmdloop(void);
55 static int compare_blk32(uint32_t *wantedblk, uint32_t curblk);
56 static int compare_blk64(uint64_t *wantedblk, uint64_t curblk);
57 static int founddatablk(uint64_t blk);
58 static int find_blks32(uint32_t *buf, int size, uint32_t *blknum);
59 static int find_blks64(uint64_t *buf, int size, uint64_t *blknum);
60 static int find_indirblks32(uint32_t blk, int ind_level, uint32_t *blknum);
61 static int find_indirblks64(uint64_t blk, int ind_level, uint64_t *blknum);
62
63 static void 
64 usage(void)
65 {
66         fprintf(stderr, "usage: fsdb [-d] [-f] [-r] fsname\n");
67         exit(1);
68 }
69
70 int returntosingle;
71 char nflag;
72
73 /*
74  * We suck in lots of fsck code, and just pick & choose the stuff we want.
75  *
76  * fsreadfd is set up to read from the file system, fswritefd to write to
77  * the file system.
78  */
79 int
80 main(int argc, char *argv[])
81 {
82         int ch, rval;
83         char *fsys = NULL;
84
85         while (-1 != (ch = getopt(argc, argv, "fdr"))) {
86                 switch (ch) {
87                 case 'f':
88                         /* The -f option is left for historical
89                          * reasons and has no meaning.
90                          */
91                         break;
92                 case 'd':
93                         debug++;
94                         break;
95                 case 'r':
96                         nflag++; /* "no" in fsck, readonly for us */
97                         break;
98                 default:
99                         usage();
100                 }
101         }
102         argc -= optind;
103         argv += optind;
104         if (argc != 1)
105                 usage();
106         else
107                 fsys = argv[0];
108
109         sblock_init();
110         if (!setup(fsys))
111                 errx(1, "cannot set up file system `%s'", fsys);
112         printf("%s file system `%s'\nLast Mounted on %s\n",
113                nflag? "Examining": "Editing", fsys, sblock.fs_fsmnt);
114         rval = cmdloop();
115         if (!nflag) {
116                 sblock.fs_clean = 0;    /* mark it dirty */
117                 sbdirty();
118                 ckfini(0);
119                 printf("*** FILE SYSTEM MARKED DIRTY\n");
120                 printf("*** BE SURE TO RUN FSCK TO CLEAN UP ANY DAMAGE\n");
121                 printf("*** IF IT WAS MOUNTED, RE-MOUNT WITH -u -o reload\n");
122         }
123         exit(rval);
124 }
125
126 #define CMDFUNC(func) int func(int argc, char *argv[])
127 #define CMDFUNCSTART(func) int func(int argc, char *argv[])
128
129 CMDFUNC(helpfn);
130 CMDFUNC(focus);                         /* focus on inode */
131 CMDFUNC(active);                        /* print active inode */
132 CMDFUNC(blocks);                        /* print blocks for active inode */
133 CMDFUNC(focusname);                     /* focus by name */
134 CMDFUNC(zapi);                          /* clear inode */
135 CMDFUNC(uplink);                        /* incr link */
136 CMDFUNC(downlink);                      /* decr link */
137 CMDFUNC(linkcount);                     /* set link count */
138 CMDFUNC(quit);                          /* quit */
139 CMDFUNC(findblk);                       /* find block */
140 CMDFUNC(ls);                            /* list directory */
141 CMDFUNC(rm);                            /* remove name */
142 CMDFUNC(ln);                            /* add name */
143 CMDFUNC(newtype);                       /* change type */
144 CMDFUNC(chmode);                        /* change mode */
145 CMDFUNC(chlen);                         /* change length */
146 CMDFUNC(chaflags);                      /* change flags */
147 CMDFUNC(chgen);                         /* change generation */
148 CMDFUNC(chowner);                       /* change owner */
149 CMDFUNC(chgroup);                       /* Change group */
150 CMDFUNC(back);                          /* pop back to last ino */
151 CMDFUNC(chbtime);                       /* Change btime */
152 CMDFUNC(chmtime);                       /* Change mtime */
153 CMDFUNC(chctime);                       /* Change ctime */
154 CMDFUNC(chatime);                       /* Change atime */
155 CMDFUNC(chinum);                        /* Change inode # of dirent */
156 CMDFUNC(chname);                        /* Change dirname of dirent */
157
158 struct cmdtable cmds[] = {
159         { "help", "Print out help", 1, 1, FL_RO, helpfn },
160         { "?", "Print out help", 1, 1, FL_RO, helpfn },
161         { "inode", "Set active inode to INUM", 2, 2, FL_RO, focus },
162         { "clri", "Clear inode INUM", 2, 2, FL_WR, zapi },
163         { "lookup", "Set active inode by looking up NAME", 2, 2, FL_RO | FL_ST, focusname },
164         { "cd", "Set active inode by looking up NAME", 2, 2, FL_RO | FL_ST, focusname },
165         { "back", "Go to previous active inode", 1, 1, FL_RO, back },
166         { "active", "Print active inode", 1, 1, FL_RO, active },
167         { "print", "Print active inode", 1, 1, FL_RO, active },
168         { "blocks", "Print block numbers of active inode", 1, 1, FL_RO, blocks },
169         { "uplink", "Increment link count", 1, 1, FL_WR, uplink },
170         { "downlink", "Decrement link count", 1, 1, FL_WR, downlink },
171         { "linkcount", "Set link count to COUNT", 2, 2, FL_WR, linkcount },
172         { "findblk", "Find inode owning disk block(s)", 2, 33, FL_RO, findblk},
173         { "ls", "List current inode as directory", 1, 1, FL_RO, ls },
174         { "rm", "Remove NAME from current inode directory", 2, 2, FL_WR | FL_ST, rm },
175         { "del", "Remove NAME from current inode directory", 2, 2, FL_WR | FL_ST, rm },
176         { "ln", "Hardlink INO into current inode directory as NAME", 3, 3, FL_WR | FL_ST, ln },
177         { "chinum", "Change dir entry number INDEX to INUM", 3, 3, FL_WR, chinum },
178         { "chname", "Change dir entry number INDEX to NAME", 3, 3, FL_WR | FL_ST, chname },
179         { "chtype", "Change type of current inode to TYPE", 2, 2, FL_WR, newtype },
180         { "chmod", "Change mode of current inode to MODE", 2, 2, FL_WR, chmode },
181         { "chlen", "Change length of current inode to LENGTH", 2, 2, FL_WR, chlen },
182         { "chown", "Change owner of current inode to OWNER", 2, 2, FL_WR, chowner },
183         { "chgrp", "Change group of current inode to GROUP", 2, 2, FL_WR, chgroup },
184         { "chflags", "Change flags of current inode to FLAGS", 2, 2, FL_WR, chaflags },
185         { "chgen", "Change generation number of current inode to GEN", 2, 2, FL_WR, chgen },
186         { "btime", "Change btime of current inode to BTIME", 2, 2, FL_WR, chbtime },
187         { "mtime", "Change mtime of current inode to MTIME", 2, 2, FL_WR, chmtime },
188         { "ctime", "Change ctime of current inode to CTIME", 2, 2, FL_WR, chctime },
189         { "atime", "Change atime of current inode to ATIME", 2, 2, FL_WR, chatime },
190         { "quit", "Exit", 1, 1, FL_RO, quit },
191         { "q", "Exit", 1, 1, FL_RO, quit },
192         { "exit", "Exit", 1, 1, FL_RO, quit },
193         { NULL, 0, 0, 0, 0, NULL },
194 };
195
196 int
197 helpfn(int argc, char *argv[])
198 {
199     struct cmdtable *cmdtp;
200
201     printf("Commands are:\n%-10s %5s %5s   %s\n",
202            "command", "min args", "max args", "what");
203     
204     for (cmdtp = cmds; cmdtp->cmd; cmdtp++)
205         printf("%-10s %5u %5u   %s\n",
206                 cmdtp->cmd, cmdtp->minargc-1, cmdtp->maxargc-1, cmdtp->helptxt);
207     return 0;
208 }
209
210 char *
211 prompt(EditLine *el)
212 {
213     static char pstring[64];
214     snprintf(pstring, sizeof(pstring), "fsdb (inum: %d)> ", curinum);
215     return pstring;
216 }
217
218
219 int
220 cmdloop(void)
221 {
222     char *line;
223     const char *elline;
224     int cmd_argc, rval = 0, known;
225 #define scratch known
226     char **cmd_argv;
227     struct cmdtable *cmdp;
228     History *hist;
229     EditLine *elptr;
230     HistEvent he;
231
232     curinode = ginode(ROOTINO);
233     curinum = ROOTINO;
234     printactive(0);
235
236     hist = history_init();
237     history(hist, &he, H_SETSIZE, 100); /* 100 elt history buffer */
238
239     elptr = el_init("fsdb", stdin, stdout, stderr);
240     el_set(elptr, EL_EDITOR, "emacs");
241     el_set(elptr, EL_PROMPT, prompt);
242     el_set(elptr, EL_HIST, history, hist);
243     el_source(elptr, NULL);
244
245     while ((elline = el_gets(elptr, &scratch)) != NULL && scratch != 0) {
246         if (debug)
247             printf("command `%s'\n", elline);
248
249         history(hist, &he, H_ENTER, elline);
250
251         line = strdup(elline);
252         cmd_argv = crack(line, &cmd_argc);
253         /*
254          * el_parse returns -1 to signal that it's not been handled
255          * internally.
256          */
257         if (el_parse(elptr, cmd_argc, (const char **)cmd_argv) != -1)
258             continue;
259         if (cmd_argc) {
260             known = 0;
261             for (cmdp = cmds; cmdp->cmd; cmdp++) {
262                 if (!strcmp(cmdp->cmd, cmd_argv[0])) {
263                     if ((cmdp->flags & FL_WR) == FL_WR && nflag)
264                         warnx("`%s' requires write access", cmd_argv[0]),
265                             rval = 1;
266                     else if (cmd_argc >= cmdp->minargc &&
267                         cmd_argc <= cmdp->maxargc)
268                         rval = (*cmdp->handler)(cmd_argc, cmd_argv);
269                     else if (cmd_argc >= cmdp->minargc &&
270                         (cmdp->flags & FL_ST) == FL_ST) {
271                         strcpy(line, elline);
272                         cmd_argv = recrack(line, &cmd_argc, cmdp->maxargc);
273                         rval = (*cmdp->handler)(cmd_argc, cmd_argv);
274                     } else
275                         rval = argcount(cmdp, cmd_argc, cmd_argv);
276                     known = 1;
277                     break;
278                 }
279             }
280             if (!known)
281                 warnx("unknown command `%s'", cmd_argv[0]), rval = 1;
282         } else
283             rval = 0;
284         free(line);
285         if (rval < 0)
286             /* user typed "quit" */
287             return 0;
288         if (rval)
289             warnx("rval was %d", rval);
290     }
291     el_end(elptr);
292     history_end(hist);
293     return rval;
294 }
295
296 union dinode *curinode;
297 ino_t curinum, ocurrent;
298
299 #define GETINUM(ac,inum)    inum = strtoul(argv[ac], &cp, 0); \
300     if (inum < ROOTINO || inum > maxino || cp == argv[ac] || *cp != '\0' ) { \
301         printf("inode %d out of range; range is [%d,%d]\n", \
302                inum, ROOTINO, maxino); \
303         return 1; \
304     }
305
306 /*
307  * Focus on given inode number
308  */
309 CMDFUNCSTART(focus)
310 {
311     ino_t inum;
312     char *cp;
313
314     GETINUM(1,inum);
315     curinode = ginode(inum);
316     ocurrent = curinum;
317     curinum = inum;
318     printactive(0);
319     return 0;
320 }
321
322 CMDFUNCSTART(back)
323 {
324     curinum = ocurrent;
325     curinode = ginode(curinum);
326     printactive(0);
327     return 0;
328 }
329
330 CMDFUNCSTART(zapi)
331 {
332     ino_t inum;
333     union dinode *dp;
334     char *cp;
335
336     GETINUM(1,inum);
337     dp = ginode(inum);
338     clearinode(dp);
339     inodirty();
340     if (curinode)                       /* re-set after potential change */
341         curinode = ginode(curinum);
342     return 0;
343 }
344
345 CMDFUNCSTART(active)
346 {
347     printactive(0);
348     return 0;
349 }
350
351 CMDFUNCSTART(blocks)
352 {
353     printactive(1);
354     return 0;
355 }
356
357 CMDFUNCSTART(quit)
358 {
359     return -1;
360 }
361
362 CMDFUNCSTART(uplink)
363 {
364     if (!checkactive())
365         return 1;
366     DIP_SET(curinode, di_nlink, DIP(curinode, di_nlink) + 1);
367     printf("inode %d link count now %d\n", curinum, DIP(curinode, di_nlink));
368     inodirty();
369     return 0;
370 }
371
372 CMDFUNCSTART(downlink)
373 {
374     if (!checkactive())
375         return 1;
376     DIP_SET(curinode, di_nlink, DIP(curinode, di_nlink) - 1);
377     printf("inode %d link count now %d\n", curinum, DIP(curinode, di_nlink));
378     inodirty();
379     return 0;
380 }
381
382 const char *typename[] = {
383     "unknown",
384     "fifo",
385     "char special",
386     "unregistered #3",
387     "directory",
388     "unregistered #5",
389     "blk special",
390     "unregistered #7",
391     "regular",
392     "unregistered #9",
393     "symlink",
394     "unregistered #11",
395     "socket",
396     "unregistered #13",
397     "whiteout",
398 };
399
400 int diroff; 
401 int slot;
402
403 int
404 scannames(struct inodesc *idesc)
405 {
406         struct direct *dirp = idesc->id_dirp;
407
408         printf("slot %d off %d ino %d reclen %d: %s, `%.*s'\n",
409                slot++, diroff, dirp->d_ino, dirp->d_reclen,
410                typename[dirp->d_type], dirp->d_namlen, dirp->d_name);
411         diroff += dirp->d_reclen;
412         return (KEEPON);
413 }
414
415 CMDFUNCSTART(ls)
416 {
417     struct inodesc idesc;
418     checkactivedir();                   /* let it go on anyway */
419
420     slot = 0;
421     diroff = 0;
422     idesc.id_number = curinum;
423     idesc.id_func = scannames;
424     idesc.id_type = DATA;
425     idesc.id_fix = IGNORE;
426     ckinode(curinode, &idesc);
427     curinode = ginode(curinum);
428
429     return 0;
430 }
431
432 static int findblk_numtofind;
433 static int wantedblksize;
434
435 CMDFUNCSTART(findblk)
436 {
437     ino_t inum, inosused;
438     uint32_t *wantedblk32;
439     uint64_t *wantedblk64;
440     struct bufarea *cgbp;
441     struct cg *cgp;
442     int c, i, is_ufs2;
443
444     wantedblksize = (argc - 1);
445     is_ufs2 = sblock.fs_magic == FS_UFS2_MAGIC;
446     ocurrent = curinum;
447
448     if (is_ufs2) {
449         wantedblk64 = calloc(wantedblksize, sizeof(uint64_t));
450         if (wantedblk64 == NULL)
451             err(1, "malloc");
452         for (i = 1; i < argc; i++)
453             wantedblk64[i - 1] = dbtofsb(&sblock, strtoull(argv[i], NULL, 0));
454     } else {
455         wantedblk32 = calloc(wantedblksize, sizeof(uint32_t));
456         if (wantedblk32 == NULL)
457             err(1, "malloc");
458         for (i = 1; i < argc; i++)
459             wantedblk32[i - 1] = dbtofsb(&sblock, strtoull(argv[i], NULL, 0));
460     }
461     findblk_numtofind = wantedblksize;
462     /*
463      * sblock.fs_ncg holds a number of cylinder groups.
464      * Iterate over all cylinder groups.
465      */
466     for (c = 0; c < sblock.fs_ncg; c++) {
467         /*
468          * sblock.fs_ipg holds a number of inodes per cylinder group.
469          * Calculate a highest inode number for a given cylinder group.
470          */
471         inum = c * sblock.fs_ipg;
472         /* Read cylinder group. */
473         cgbp = cgget(c);
474         cgp = cgbp->b_un.b_cg;
475         /*
476          * Get a highest used inode number for a given cylinder group.
477          * For UFS1 all inodes initialized at the newfs stage.
478          */
479         if (is_ufs2)
480             inosused = cgp->cg_initediblk;
481         else
482             inosused = sblock.fs_ipg;
483
484         for (; inosused > 0; inum++, inosused--) {
485             /* Skip magic inodes: 0, WINO, ROOTINO. */
486             if (inum < ROOTINO)
487                 continue;
488             /*
489              * Check if the block we are looking for is just an inode block.
490              *
491              * ino_to_fsba() - get block containing inode from its number.
492              * INOPB() - get a number of inodes in one disk block.
493              */
494             if (is_ufs2 ?
495                 compare_blk64(wantedblk64, ino_to_fsba(&sblock, inum)) :
496                 compare_blk32(wantedblk32, ino_to_fsba(&sblock, inum))) {
497                 printf("block %llu: inode block (%d-%d)\n",
498                     (unsigned long long)fsbtodb(&sblock,
499                         ino_to_fsba(&sblock, inum)),
500                     (inum / INOPB(&sblock)) * INOPB(&sblock),
501                     (inum / INOPB(&sblock) + 1) * INOPB(&sblock));
502                 findblk_numtofind--;
503                 if (findblk_numtofind == 0)
504                     goto end;
505             }
506             /* Get on-disk inode aka dinode. */
507             curinum = inum;
508             curinode = ginode(inum);
509             /* Find IFLNK dinode with allocated data blocks. */
510             switch (DIP(curinode, di_mode) & IFMT) {
511             case IFDIR:
512             case IFREG:
513                 if (DIP(curinode, di_blocks) == 0)
514                     continue;
515                 break;
516             case IFLNK:
517                 {
518                     uint64_t size = DIP(curinode, di_size);
519                     if (size > 0 && size < sblock.fs_maxsymlinklen &&
520                         DIP(curinode, di_blocks) == 0)
521                         continue;
522                     else
523                         break;
524                 }
525             default:
526                 continue;
527             }
528             /* Look through direct data blocks. */
529             if (is_ufs2 ?
530                 find_blks64(curinode->dp2.di_db, NDADDR, wantedblk64) :
531                 find_blks32(curinode->dp1.di_db, NDADDR, wantedblk32))
532                 goto end;
533             for (i = 0; i < NIADDR; i++) {
534                 /*
535                  * Does the block we are looking for belongs to the
536                  * indirect blocks?
537                  */
538                 if (is_ufs2 ?
539                     compare_blk64(wantedblk64, curinode->dp2.di_ib[i]) :
540                     compare_blk32(wantedblk32, curinode->dp1.di_ib[i]))
541                     if (founddatablk(is_ufs2 ? curinode->dp2.di_ib[i] :
542                         curinode->dp1.di_ib[i]))
543                         goto end;
544                 /*
545                  * Search through indirect, double and triple indirect
546                  * data blocks.
547                  */
548                 if (is_ufs2 ? (curinode->dp2.di_ib[i] != 0) :
549                     (curinode->dp1.di_ib[i] != 0))
550                     if (is_ufs2 ?
551                         find_indirblks64(curinode->dp2.di_ib[i], i,
552                             wantedblk64) :
553                         find_indirblks32(curinode->dp1.di_ib[i], i,
554                             wantedblk32))
555                         goto end;
556             }
557         }
558     }
559 end:
560     curinum = ocurrent;
561     curinode = ginode(curinum);
562     return 0;
563 }
564
565 static int
566 compare_blk32(uint32_t *wantedblk, uint32_t curblk)
567 {
568     int i;
569
570     for (i = 0; i < wantedblksize; i++) {
571         if (wantedblk[i] != 0 && wantedblk[i] == curblk) {
572             wantedblk[i] = 0;
573             return 1;
574         }
575     }
576     return 0;
577 }
578
579 static int
580 compare_blk64(uint64_t *wantedblk, uint64_t curblk)
581 {
582     int i;
583
584     for (i = 0; i < wantedblksize; i++) {
585         if (wantedblk[i] != 0 && wantedblk[i] == curblk) {
586             wantedblk[i] = 0;
587             return 1;
588         }
589     }
590     return 0;
591 }
592
593 static int
594 founddatablk(uint64_t blk)
595 {
596
597     printf("%llu: data block of inode %d\n",
598         (unsigned long long)fsbtodb(&sblock, blk), curinum);
599     findblk_numtofind--;
600     if (findblk_numtofind == 0)
601         return 1;
602     return 0;
603 }
604
605 static int
606 find_blks32(uint32_t *buf, int size, uint32_t *wantedblk)
607 {
608     int blk;
609     for (blk = 0; blk < size; blk++) {
610         if (buf[blk] == 0)
611             continue;
612         if (compare_blk32(wantedblk, buf[blk])) {
613             if (founddatablk(buf[blk]))
614                 return 1;
615         }
616     }
617     return 0;
618 }
619
620 static int
621 find_indirblks32(uint32_t blk, int ind_level, uint32_t *wantedblk)
622 {
623 #define MAXNINDIR      (MAXBSIZE / sizeof(uint32_t))
624     uint32_t idblk[MAXNINDIR];
625     int i;
626
627     blread(fsreadfd, (char *)idblk, fsbtodb(&sblock, blk), (int)sblock.fs_bsize);
628     if (ind_level <= 0) {
629         if (find_blks32(idblk, sblock.fs_bsize / sizeof(uint32_t), wantedblk))
630             return 1;
631     } else {
632         ind_level--;
633         for (i = 0; i < sblock.fs_bsize / sizeof(uint32_t); i++) {
634             if (compare_blk32(wantedblk, idblk[i])) {
635                 if (founddatablk(idblk[i]))
636                     return 1;
637             }
638             if (idblk[i] != 0)
639                 if (find_indirblks32(idblk[i], ind_level, wantedblk))
640                     return 1;
641         }
642     }
643 #undef MAXNINDIR
644     return 0;
645 }
646
647 static int
648 find_blks64(uint64_t *buf, int size, uint64_t *wantedblk)
649 {
650     int blk;
651     for (blk = 0; blk < size; blk++) {
652         if (buf[blk] == 0)
653             continue;
654         if (compare_blk64(wantedblk, buf[blk])) {
655             if (founddatablk(buf[blk]))
656                 return 1;
657         }
658     }
659     return 0;
660 }
661
662 static int
663 find_indirblks64(uint64_t blk, int ind_level, uint64_t *wantedblk)
664 {
665 #define MAXNINDIR      (MAXBSIZE / sizeof(uint64_t))
666     uint64_t idblk[MAXNINDIR];
667     int i;
668
669     blread(fsreadfd, (char *)idblk, fsbtodb(&sblock, blk), (int)sblock.fs_bsize);
670     if (ind_level <= 0) {
671         if (find_blks64(idblk, sblock.fs_bsize / sizeof(uint64_t), wantedblk))
672             return 1;
673     } else {
674         ind_level--;
675         for (i = 0; i < sblock.fs_bsize / sizeof(uint64_t); i++) {
676             if (compare_blk64(wantedblk, idblk[i])) {
677                 if (founddatablk(idblk[i]))
678                     return 1;
679             }
680             if (idblk[i] != 0)
681                 if (find_indirblks64(idblk[i], ind_level, wantedblk))
682                     return 1;
683         }
684     }
685 #undef MAXNINDIR
686     return 0;
687 }
688
689 int findino(struct inodesc *idesc); /* from fsck */
690 static int dolookup(char *name);
691
692 static int
693 dolookup(char *name)
694 {
695     struct inodesc idesc;
696
697     if (!checkactivedir())
698             return 0;
699     idesc.id_number = curinum;
700     idesc.id_func = findino;
701     idesc.id_name = name;
702     idesc.id_type = DATA;
703     idesc.id_fix = IGNORE;
704     if (ckinode(curinode, &idesc) & FOUND) {
705         curinum = idesc.id_parent;
706         curinode = ginode(curinum);
707         printactive(0);
708         return 1;
709     } else {
710         warnx("name `%s' not found in current inode directory", name);
711         return 0;
712     }
713 }
714
715 CMDFUNCSTART(focusname)
716 {
717     char *p, *val;
718
719     if (!checkactive())
720         return 1;
721
722     ocurrent = curinum;
723     
724     if (argv[1][0] == '/') {
725         curinum = ROOTINO;
726         curinode = ginode(ROOTINO);
727     } else {
728         if (!checkactivedir())
729             return 1;
730     }
731     for (p = argv[1]; p != NULL;) {
732         while ((val = strsep(&p, "/")) != NULL && *val == '\0');
733         if (val) {
734             printf("component `%s': ", val);
735             fflush(stdout);
736             if (!dolookup(val)) {
737                 curinode = ginode(curinum);
738                 return(1);
739             }
740         }
741     }
742     return 0;
743 }
744
745 CMDFUNCSTART(ln)
746 {
747     ino_t inum;
748     int rval;
749     char *cp;
750
751     GETINUM(1,inum);
752
753     if (!checkactivedir())
754         return 1;
755     rval = makeentry(curinum, inum, argv[2]);
756     if (rval)
757         printf("Ino %d entered as `%s'\n", inum, argv[2]);
758     else
759         printf("could not enter name? weird.\n");
760     curinode = ginode(curinum);
761     return rval;
762 }
763
764 CMDFUNCSTART(rm)
765 {
766     int rval;
767
768     if (!checkactivedir())
769         return 1;
770     rval = changeino(curinum, argv[1], 0);
771     if (rval & ALTERED) {
772         printf("Name `%s' removed\n", argv[1]);
773         return 0;
774     } else {
775         printf("could not remove name ('%s')? weird.\n", argv[1]);
776         return 1;
777     }
778 }
779
780 long slotcount, desired;
781
782 int
783 chinumfunc(struct inodesc *idesc)
784 {
785         struct direct *dirp = idesc->id_dirp;
786
787         if (slotcount++ == desired) {
788             dirp->d_ino = idesc->id_parent;
789             return STOP|ALTERED|FOUND;
790         }
791         return KEEPON;
792 }
793
794 CMDFUNCSTART(chinum)
795 {
796     char *cp;
797     ino_t inum;
798     struct inodesc idesc;
799     
800     slotcount = 0;
801     if (!checkactivedir())
802         return 1;
803     GETINUM(2,inum);
804
805     desired = strtol(argv[1], &cp, 0);
806     if (cp == argv[1] || *cp != '\0' || desired < 0) {
807         printf("invalid slot number `%s'\n", argv[1]);
808         return 1;
809     }
810
811     idesc.id_number = curinum;
812     idesc.id_func = chinumfunc;
813     idesc.id_fix = IGNORE;
814     idesc.id_type = DATA;
815     idesc.id_parent = inum;             /* XXX convenient hiding place */
816
817     if (ckinode(curinode, &idesc) & FOUND)
818         return 0;
819     else {
820         warnx("no %sth slot in current directory", argv[1]);
821         return 1;
822     }
823 }
824
825 int
826 chnamefunc(struct inodesc *idesc)
827 {
828         struct direct *dirp = idesc->id_dirp;
829         struct direct testdir;
830
831         if (slotcount++ == desired) {
832             /* will name fit? */
833             testdir.d_namlen = strlen(idesc->id_name);
834             if (DIRSIZ(NEWDIRFMT, &testdir) <= dirp->d_reclen) {
835                 dirp->d_namlen = testdir.d_namlen;
836                 strcpy(dirp->d_name, idesc->id_name);
837                 return STOP|ALTERED|FOUND;
838             } else
839                 return STOP|FOUND;      /* won't fit, so give up */
840         }
841         return KEEPON;
842 }
843
844 CMDFUNCSTART(chname)
845 {
846     int rval;
847     char *cp;
848     struct inodesc idesc;
849     
850     slotcount = 0;
851     if (!checkactivedir())
852         return 1;
853
854     desired = strtoul(argv[1], &cp, 0);
855     if (cp == argv[1] || *cp != '\0') {
856         printf("invalid slot number `%s'\n", argv[1]);
857         return 1;
858     }
859
860     idesc.id_number = curinum;
861     idesc.id_func = chnamefunc;
862     idesc.id_fix = IGNORE;
863     idesc.id_type = DATA;
864     idesc.id_name = argv[2];
865
866     rval = ckinode(curinode, &idesc);
867     if ((rval & (FOUND|ALTERED)) == (FOUND|ALTERED))
868         return 0;
869     else if (rval & FOUND) {
870         warnx("new name `%s' does not fit in slot %s\n", argv[2], argv[1]);
871         return 1;
872     } else {
873         warnx("no %sth slot in current directory", argv[1]);
874         return 1;
875     }
876 }
877
878 struct typemap {
879     const char *typename;
880     int typebits;
881 } typenamemap[]  = {
882     {"file", IFREG},
883     {"dir", IFDIR},
884     {"socket", IFSOCK},
885     {"fifo", IFIFO},
886 };
887
888 CMDFUNCSTART(newtype)
889 {
890     int type;
891     struct typemap *tp;
892
893     if (!checkactive())
894         return 1;
895     type = DIP(curinode, di_mode) & IFMT;
896     for (tp = typenamemap;
897          tp < &typenamemap[sizeof(typenamemap)/sizeof(*typenamemap)];
898          tp++) {
899         if (!strcmp(argv[1], tp->typename)) {
900             printf("setting type to %s\n", tp->typename);
901             type = tp->typebits;
902             break;
903         }
904     }
905     if (tp == &typenamemap[sizeof(typenamemap)/sizeof(*typenamemap)]) {
906         warnx("type `%s' not known", argv[1]);
907         warnx("try one of `file', `dir', `socket', `fifo'");
908         return 1;
909     }
910     DIP_SET(curinode, di_mode, DIP(curinode, di_mode) & ~IFMT);
911     DIP_SET(curinode, di_mode, DIP(curinode, di_mode) | type);
912     inodirty();
913     printactive(0);
914     return 0;
915 }
916
917 CMDFUNCSTART(chlen)
918 {
919     int rval = 1;
920     long len;
921     char *cp;
922
923     if (!checkactive())
924         return 1;
925
926     len = strtol(argv[1], &cp, 0);
927     if (cp == argv[1] || *cp != '\0' || len < 0) { 
928         warnx("bad length `%s'", argv[1]);
929         return 1;
930     }
931     
932     DIP_SET(curinode, di_size, len);
933     inodirty();
934     printactive(0);
935     return rval;
936 }
937
938 CMDFUNCSTART(chmode)
939 {
940     int rval = 1;
941     long modebits;
942     char *cp;
943
944     if (!checkactive())
945         return 1;
946
947     modebits = strtol(argv[1], &cp, 8);
948     if (cp == argv[1] || *cp != '\0' || (modebits & ~07777)) { 
949         warnx("bad modebits `%s'", argv[1]);
950         return 1;
951     }
952     
953     DIP_SET(curinode, di_mode, DIP(curinode, di_mode) & ~07777);
954     DIP_SET(curinode, di_mode, DIP(curinode, di_mode) | modebits);
955     inodirty();
956     printactive(0);
957     return rval;
958 }
959
960 CMDFUNCSTART(chaflags)
961 {
962     int rval = 1;
963     u_long flags;
964     char *cp;
965
966     if (!checkactive())
967         return 1;
968
969     flags = strtoul(argv[1], &cp, 0);
970     if (cp == argv[1] || *cp != '\0' ) { 
971         warnx("bad flags `%s'", argv[1]);
972         return 1;
973     }
974     
975     if (flags > UINT_MAX) {
976         warnx("flags set beyond 32-bit range of field (%lx)\n", flags);
977         return(1);
978     }
979     DIP_SET(curinode, di_flags, flags);
980     inodirty();
981     printactive(0);
982     return rval;
983 }
984
985 CMDFUNCSTART(chgen)
986 {
987     int rval = 1;
988     long gen;
989     char *cp;
990
991     if (!checkactive())
992         return 1;
993
994     gen = strtol(argv[1], &cp, 0);
995     if (cp == argv[1] || *cp != '\0' ) { 
996         warnx("bad gen `%s'", argv[1]);
997         return 1;
998     }
999     
1000     if (gen > INT_MAX || gen < INT_MIN) {
1001         warnx("gen set beyond 32-bit range of field (%lx)\n", gen);
1002         return(1);
1003     }
1004     DIP_SET(curinode, di_gen, gen);
1005     inodirty();
1006     printactive(0);
1007     return rval;
1008 }
1009
1010 CMDFUNCSTART(linkcount)
1011 {
1012     int rval = 1;
1013     int lcnt;
1014     char *cp;
1015
1016     if (!checkactive())
1017         return 1;
1018
1019     lcnt = strtol(argv[1], &cp, 0);
1020     if (cp == argv[1] || *cp != '\0' ) { 
1021         warnx("bad link count `%s'", argv[1]);
1022         return 1;
1023     }
1024     if (lcnt > USHRT_MAX || lcnt < 0) {
1025         warnx("max link count is %d\n", USHRT_MAX);
1026         return 1;
1027     }
1028     
1029     DIP_SET(curinode, di_nlink, lcnt);
1030     inodirty();
1031     printactive(0);
1032     return rval;
1033 }
1034
1035 CMDFUNCSTART(chowner)
1036 {
1037     int rval = 1;
1038     unsigned long uid;
1039     char *cp;
1040     struct passwd *pwd;
1041
1042     if (!checkactive())
1043         return 1;
1044
1045     uid = strtoul(argv[1], &cp, 0);
1046     if (cp == argv[1] || *cp != '\0' ) { 
1047         /* try looking up name */
1048         if ((pwd = getpwnam(argv[1]))) {
1049             uid = pwd->pw_uid;
1050         } else {
1051             warnx("bad uid `%s'", argv[1]);
1052             return 1;
1053         }
1054     }
1055     
1056     DIP_SET(curinode, di_uid, uid);
1057     inodirty();
1058     printactive(0);
1059     return rval;
1060 }
1061
1062 CMDFUNCSTART(chgroup)
1063 {
1064     int rval = 1;
1065     unsigned long gid;
1066     char *cp;
1067     struct group *grp;
1068
1069     if (!checkactive())
1070         return 1;
1071
1072     gid = strtoul(argv[1], &cp, 0);
1073     if (cp == argv[1] || *cp != '\0' ) { 
1074         if ((grp = getgrnam(argv[1]))) {
1075             gid = grp->gr_gid;
1076         } else {
1077             warnx("bad gid `%s'", argv[1]);
1078             return 1;
1079         }
1080     }
1081     
1082     DIP_SET(curinode, di_gid, gid);
1083     inodirty();
1084     printactive(0);
1085     return rval;
1086 }
1087
1088 int
1089 dotime(char *name, time_t *secp, int32_t *nsecp)
1090 {
1091     char *p, *val;
1092     struct tm t;
1093     int32_t nsec;
1094     p = strchr(name, '.');
1095     if (p) {
1096         *p = '\0';
1097         nsec = strtoul(++p, &val, 0);
1098         if (val == p || *val != '\0' || nsec >= 1000000000 || nsec < 0) {
1099                 warnx("invalid nanoseconds");
1100                 goto badformat;
1101         }
1102     } else
1103         nsec = 0;
1104     if (strlen(name) != 14) {
1105 badformat:
1106         warnx("date format: YYYYMMDDHHMMSS[.nsec]");
1107         return 1;
1108     }
1109     *nsecp = nsec;
1110
1111     for (p = name; *p; p++)
1112         if (*p < '0' || *p > '9')
1113             goto badformat;
1114     
1115     p = name;
1116 #define VAL() ((*p++) - '0')
1117     t.tm_year = VAL();
1118     t.tm_year = VAL() + t.tm_year * 10;
1119     t.tm_year = VAL() + t.tm_year * 10;
1120     t.tm_year = VAL() + t.tm_year * 10 - 1900;
1121     t.tm_mon = VAL();
1122     t.tm_mon = VAL() + t.tm_mon * 10 - 1;
1123     t.tm_mday = VAL();
1124     t.tm_mday = VAL() + t.tm_mday * 10;
1125     t.tm_hour = VAL();
1126     t.tm_hour = VAL() + t.tm_hour * 10;
1127     t.tm_min = VAL();
1128     t.tm_min = VAL() + t.tm_min * 10;
1129     t.tm_sec = VAL();
1130     t.tm_sec = VAL() + t.tm_sec * 10;
1131     t.tm_isdst = -1;
1132
1133     *secp = mktime(&t);
1134     if (*secp == -1) {
1135         warnx("date/time out of range");
1136         return 1;
1137     }
1138     return 0;
1139 }
1140
1141 CMDFUNCSTART(chbtime)
1142 {
1143     time_t secs;
1144     int32_t nsecs;
1145
1146     if (dotime(argv[1], &secs, &nsecs))
1147         return 1;
1148     if (sblock.fs_magic == FS_UFS1_MAGIC)
1149         return 1;
1150     curinode->dp2.di_birthtime = _time_to_time64(secs);
1151     curinode->dp2.di_birthnsec = nsecs;
1152     inodirty();
1153     printactive(0);
1154     return 0;
1155 }
1156
1157 CMDFUNCSTART(chmtime)
1158 {
1159     time_t secs;
1160     int32_t nsecs;
1161
1162     if (dotime(argv[1], &secs, &nsecs))
1163         return 1;
1164     if (sblock.fs_magic == FS_UFS1_MAGIC)
1165         curinode->dp1.di_mtime = _time_to_time32(secs);
1166     else
1167         curinode->dp2.di_mtime = _time_to_time64(secs);
1168     DIP_SET(curinode, di_mtimensec, nsecs);
1169     inodirty();
1170     printactive(0);
1171     return 0;
1172 }
1173
1174 CMDFUNCSTART(chatime)
1175 {
1176     time_t secs;
1177     int32_t nsecs;
1178
1179     if (dotime(argv[1], &secs, &nsecs))
1180         return 1;
1181     if (sblock.fs_magic == FS_UFS1_MAGIC)
1182         curinode->dp1.di_atime = _time_to_time32(secs);
1183     else
1184         curinode->dp2.di_atime = _time_to_time64(secs);
1185     DIP_SET(curinode, di_atimensec, nsecs);
1186     inodirty();
1187     printactive(0);
1188     return 0;
1189 }
1190
1191 CMDFUNCSTART(chctime)
1192 {
1193     time_t secs;
1194     int32_t nsecs;
1195
1196     if (dotime(argv[1], &secs, &nsecs))
1197         return 1;
1198     if (sblock.fs_magic == FS_UFS1_MAGIC)
1199         curinode->dp1.di_ctime = _time_to_time32(secs);
1200     else
1201         curinode->dp2.di_ctime = _time_to_time64(secs);
1202     DIP_SET(curinode, di_ctimensec, nsecs);
1203     inodirty();
1204     printactive(0);
1205     return 0;
1206 }