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