Whamcloud - gitweb
Make debugfs's stat command print the size of the extra inode fields,
[tools/e2fsprogs.git] / debugfs / debugfs.c
1 /*
2  * debugfs.c --- a program which allows you to attach an ext2fs
3  * filesystem and play with it.
4  *
5  * Copyright (C) 1993 Theodore Ts'o.  This file may be redistributed
6  * under the terms of the GNU Public License.
7  * 
8  * Modifications by Robert Sanders <gt8134b@prism.gatech.edu>
9  */
10
11 #include <stdio.h>
12 #include <unistd.h>
13 #include <stdlib.h>
14 #include <ctype.h>
15 #include <string.h>
16 #include <time.h>
17 #ifdef HAVE_GETOPT_H
18 #include <getopt.h>
19 #else 
20 extern int optind;
21 extern char *optarg;
22 #endif
23 #ifdef HAVE_ERRNO_H
24 #include <errno.h>
25 #endif
26 #include <fcntl.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29
30 #include "et/com_err.h"
31 #include "ss/ss.h"
32 #include "debugfs.h"
33 #include "uuid/uuid.h"
34 #include "e2p/e2p.h"
35
36 #include <ext2fs/ext2_ext_attr.h>
37
38 #include "../version.h"
39
40 extern ss_request_table debug_cmds;
41
42 ext2_filsys     current_fs = NULL;
43 ext2_ino_t      root, cwd;
44
45 static void open_filesystem(char *device, int open_flags, blk_t superblock,
46                             blk_t blocksize, int catastrophic, 
47                             char *data_filename)
48 {
49         int     retval;
50         io_channel data_io = 0;
51
52         if (superblock != 0 && blocksize == 0) {
53                 com_err(device, 0, "if you specify the superblock, you must also specify the block size");
54                 current_fs = NULL;
55                 return;
56         }
57
58         if (data_filename) {
59                 if ((open_flags & EXT2_FLAG_IMAGE_FILE) == 0) {
60                         com_err(device, 0, 
61                                 "The -d option is only valid when reading an e2image file");
62                         current_fs = NULL;
63                         return;
64                 }
65                 retval = unix_io_manager->open(data_filename, 0, &data_io);
66                 if (retval) {
67                         com_err(data_filename, 0, "while opening data source");
68                         current_fs = NULL;
69                         return;
70                 }
71         }
72
73         if (catastrophic && (open_flags & EXT2_FLAG_RW)) {
74                 com_err(device, 0,
75                         "opening read-only because of catastrophic mode");
76                 open_flags &= ~EXT2_FLAG_RW;
77         }
78         
79         retval = ext2fs_open(device, open_flags, superblock, blocksize,
80                              unix_io_manager, &current_fs);
81         if (retval) {
82                 com_err(device, retval, "while opening filesystem");
83                 current_fs = NULL;
84                 return;
85         }
86
87         if (catastrophic)
88                 com_err(device, 0, "catastrophic mode - not reading inode or group bitmaps");
89         else {
90                 retval = ext2fs_read_inode_bitmap(current_fs);
91                 if (retval) {
92                         com_err(device, retval, "while reading inode bitmap");
93                         goto errout;
94                 }
95                 retval = ext2fs_read_block_bitmap(current_fs);
96                 if (retval) {
97                         com_err(device, retval, "while reading block bitmap");
98                         goto errout;
99                 }
100         }
101
102         if (data_io) {
103                 retval = ext2fs_set_data_io(current_fs, data_io);
104                 if (retval) {
105                         com_err(device, retval, 
106                                 "while setting data source");
107                         goto errout;
108                 }
109         }
110
111         root = cwd = EXT2_ROOT_INO;
112         return;
113
114 errout:
115         retval = ext2fs_close(current_fs);
116         if (retval)
117                 com_err(device, retval, "while trying to close filesystem");
118         current_fs = NULL;
119 }
120
121 void do_open_filesys(int argc, char **argv)
122 {
123         const char *usage = "Usage: open [-s superblock] [-b blocksize] [-c] [-w] <device>";
124         int     c, err;
125         int     catastrophic = 0;
126         blk_t   superblock = 0;
127         blk_t   blocksize = 0;
128         int     open_flags = 0;
129         char    *data_filename = 0;
130         
131         reset_getopt();
132         while ((c = getopt (argc, argv, "iwfcb:s:d:")) != EOF) {
133                 switch (c) {
134                 case 'i':
135                         open_flags |= EXT2_FLAG_IMAGE_FILE;
136                         break;
137                 case 'w':
138                         open_flags |= EXT2_FLAG_RW;
139                         break;
140                 case 'f':
141                         open_flags |= EXT2_FLAG_FORCE;
142                         break;
143                 case 'c':
144                         catastrophic = 1;
145                         break;
146                 case 'd':
147                         data_filename = optarg;
148                         break;
149                 case 'b':
150                         blocksize = parse_ulong(optarg, argv[0],
151                                                 "block size", &err);
152                         if (err)
153                                 return;
154                         break;
155                 case 's':
156                         superblock = parse_ulong(optarg, argv[0],
157                                                  "superblock number", &err);
158                         if (err)
159                                 return;
160                         break;
161                 default:
162                         com_err(argv[0], 0, usage);
163                         return;
164                 }
165         }
166         if (optind != argc-1) {
167                 com_err(argv[0], 0, usage);
168                 return;
169         }
170         if (check_fs_not_open(argv[0]))
171                 return;
172         open_filesystem(argv[optind], open_flags,
173                         superblock, blocksize, catastrophic, 
174                         data_filename);
175 }
176
177 void do_lcd(int argc, char **argv)
178 {
179         if (common_args_process(argc, argv, 2, 2, "lcd",
180                                 "<native dir>", 0))
181                 return;
182
183         if (chdir(argv[1]) == -1) {
184                 com_err(argv[0], errno,
185                         "while trying to change native directory to %s",
186                         argv[1]);
187                 return;
188         }
189 }
190
191 static void close_filesystem(NOARGS)
192 {
193         int     retval;
194         
195         if (current_fs->flags & EXT2_FLAG_IB_DIRTY) {
196                 retval = ext2fs_write_inode_bitmap(current_fs);
197                 if (retval)
198                         com_err("ext2fs_write_inode_bitmap", retval, "");
199         }
200         if (current_fs->flags & EXT2_FLAG_BB_DIRTY) {
201                 retval = ext2fs_write_block_bitmap(current_fs);
202                 if (retval)
203                         com_err("ext2fs_write_block_bitmap", retval, "");
204         }
205         retval = ext2fs_close(current_fs);
206         if (retval)
207                 com_err("ext2fs_close", retval, "");
208         current_fs = NULL;
209         return;
210 }
211
212 void do_close_filesys(int argc, char **argv)
213 {
214         if (common_args_process(argc, argv, 1, 1, "close_filesys", "", 0))
215                 return;
216         close_filesystem();
217 }
218
219 void do_init_filesys(int argc, char **argv)
220 {
221         struct ext2_super_block param;
222         errcode_t       retval;
223         int             err;
224         
225         if (common_args_process(argc, argv, 3, 3, "initialize",
226                                 "<device> <blocksize>", CHECK_FS_NOTOPEN))
227                 return;
228
229         memset(&param, 0, sizeof(struct ext2_super_block));
230         param.s_blocks_count = parse_ulong(argv[2], argv[0],
231                                            "blocks count", &err);
232         if (err)
233                 return;
234         retval = ext2fs_initialize(argv[1], 0, &param,
235                                    unix_io_manager, &current_fs);
236         if (retval) {
237                 com_err(argv[1], retval, "while initializing filesystem");
238                 current_fs = NULL;
239                 return;
240         }
241         root = cwd = EXT2_ROOT_INO;
242         return;
243 }
244
245 static void print_features(struct ext2_super_block * s, FILE *f)
246 {
247         int     i, j, printed=0;
248         __u32   *mask = &s->s_feature_compat, m;
249
250         fputs("Filesystem features:", f);
251         for (i=0; i <3; i++,mask++) {
252                 for (j=0,m=1; j < 32; j++, m<<=1) {
253                         if (*mask & m) {
254                                 fprintf(f, " %s", e2p_feature2string(i, m));
255                                 printed++;
256                         }
257                 }
258         }
259         if (printed == 0)
260                 fputs("(none)", f);
261         fputs("\n", f);
262 }
263
264 void do_show_super_stats(int argc, char *argv[])
265 {
266         dgrp_t  i;
267         FILE    *out;
268         struct ext2_group_desc *gdp;
269         int     c, header_only = 0;
270         int     numdirs = 0;
271         const char *usage = "Usage: show_super [-h]";
272
273         reset_getopt();
274         while ((c = getopt (argc, argv, "h")) != EOF) {
275                 switch (c) {
276                 case 'h':
277                         header_only++;
278                         break;
279                 default:
280                         com_err(argv[0], 0, usage);
281                         return;
282                 }
283         }
284         if (optind != argc) {
285                 com_err(argv[0], 0, usage);
286                 return;
287         }
288         if (check_fs_open(argv[0]))
289                 return;
290         out = open_pager();
291
292         list_super2(current_fs->super, out);
293         for (i=0; i < current_fs->group_desc_count; i++)
294                 numdirs += current_fs->group_desc[i].bg_used_dirs_count;
295         fprintf(out, "Directories:              %d\n", numdirs);
296         
297         if (header_only) {
298                 close_pager(out);
299                 return;
300         }
301         
302         gdp = &current_fs->group_desc[0];
303         for (i = 0; i < current_fs->group_desc_count; i++, gdp++)
304                 fprintf(out, " Group %2d: block bitmap at %d, "
305                         "inode bitmap at %d, "
306                         "inode table at %d\n"
307                         "           %d free %s, "
308                         "%d free %s, "
309                         "%d used %s\n",
310                         i, gdp->bg_block_bitmap,
311                         gdp->bg_inode_bitmap, gdp->bg_inode_table,
312                         gdp->bg_free_blocks_count,
313                         gdp->bg_free_blocks_count != 1 ? "blocks" : "block",
314                         gdp->bg_free_inodes_count,
315                         gdp->bg_free_inodes_count != 1 ? "inodes" : "inode",
316                         gdp->bg_used_dirs_count,
317                         gdp->bg_used_dirs_count != 1 ? "directories"
318                                 : "directory");
319         close_pager(out);
320 }
321
322 void do_dirty_filesys(int argc EXT2FS_ATTR((unused)), 
323                       char **argv EXT2FS_ATTR((unused)))
324 {
325         if (check_fs_open(argv[0]))
326                 return;
327         if (check_fs_read_write(argv[0]))
328                 return;
329
330         if (argv[1] && !strcmp(argv[1], "-clean"))
331                 current_fs->super->s_state |= EXT2_VALID_FS;
332         else
333                 current_fs->super->s_state &= ~EXT2_VALID_FS;
334         ext2fs_mark_super_dirty(current_fs);
335 }
336
337 struct list_blocks_struct {
338         FILE            *f;
339         e2_blkcnt_t     total;
340         blk_t           first_block, last_block;
341         e2_blkcnt_t     first_bcnt, last_bcnt;
342         e2_blkcnt_t     first;
343 };
344
345 static void finish_range(struct list_blocks_struct *lb)
346 {
347         if (lb->first_block == 0)
348                 return;
349         if (lb->first)
350                 lb->first = 0;
351         else
352                 fprintf(lb->f, ", ");
353         if (lb->first_block == lb->last_block)
354                 fprintf(lb->f, "(%lld):%d", lb->first_bcnt, lb->first_block);
355         else
356                 fprintf(lb->f, "(%lld-%lld):%d-%d", lb->first_bcnt,
357                         lb->last_bcnt, lb->first_block, lb->last_block);
358         lb->first_block = 0;
359 }
360
361 static int list_blocks_proc(ext2_filsys fs EXT2FS_ATTR((unused)), 
362                             blk_t *blocknr, e2_blkcnt_t blockcnt, 
363                             blk_t ref_block EXT2FS_ATTR((unused)),
364                             int ref_offset EXT2FS_ATTR((unused)), 
365                             void *private)
366 {
367         struct list_blocks_struct *lb = (struct list_blocks_struct *) private;
368
369         lb->total++;
370         if (blockcnt >= 0) {
371                 /*
372                  * See if we can add on to the existing range (if it exists)
373                  */
374                 if (lb->first_block &&
375                     (lb->last_block+1 == *blocknr) &&
376                     (lb->last_bcnt+1 == blockcnt)) {
377                         lb->last_block = *blocknr;
378                         lb->last_bcnt = blockcnt;
379                         return 0;
380                 }
381                 /*
382                  * Start a new range.
383                  */
384                 finish_range(lb);
385                 lb->first_block = lb->last_block = *blocknr;
386                 lb->first_bcnt = lb->last_bcnt = blockcnt;
387                 return 0;
388         }
389         /*
390          * Not a normal block.  Always force a new range.
391          */
392         finish_range(lb);
393         if (lb->first)
394                 lb->first = 0;
395         else
396                 fprintf(lb->f, ", ");
397         if (blockcnt == -1)
398                 fprintf(lb->f, "(IND):%d", *blocknr);
399         else if (blockcnt == -2)
400                 fprintf(lb->f, "(DIND):%d", *blocknr);
401         else if (blockcnt == -3)
402                 fprintf(lb->f, "(TIND):%d", *blocknr);
403         return 0;
404 }
405
406 void dump_xattr_string(FILE *out, const unsigned char *str, int len)
407 {
408         int printable = 1;
409         int i;
410         
411         /* check is string printable? */
412         for (i = 0; i < len; i++)
413                 if (!isprint(str[i])) {
414                         printable = 0;
415                         break;
416                 }
417
418         for (i = 0; i < len; i++)
419                 if (printable)
420                         fprintf(out, "%c", str[i]);
421                 else
422                         fprintf(out, "%02x ", str[i]);
423 }
424
425 void internal_dump_inode_extra(FILE *out, const char *prefix,
426                          ext2_ino_t inode_num, struct ext2_inode_large *inode)
427 {
428         struct ext2_ext_attr_entry *entry;
429         __u32 *magic;
430         char *start, *end;
431         int storage_size;
432         int i;
433
434         fprintf(out, "Size of extra inode fields: %d\n", inode->i_extra_isize);
435         if (inode->i_extra_isize > EXT2_INODE_SIZE(current_fs->super) -
436                         EXT2_GOOD_OLD_INODE_SIZE) {
437                 fprintf(stderr, "invalid inode->i_extra_isize (%u)\n",
438                                 inode->i_extra_isize);
439                 return;
440         }
441         storage_size = EXT2_INODE_SIZE(current_fs->super) -
442                         EXT2_GOOD_OLD_INODE_SIZE -
443                         inode->i_extra_isize;
444         magic = (__u32 *)((char *)inode + EXT2_GOOD_OLD_INODE_SIZE +
445                         inode->i_extra_isize);
446         if (*magic == EXT2_EXT_ATTR_MAGIC) {
447                 fprintf(out, "Extended attributes stored in inode body: \n");
448                 end = (char *) inode + EXT2_INODE_SIZE(current_fs->super);
449                 start = (char *) magic + sizeof(__u32);
450                 entry = (struct ext2_ext_attr_entry *) start;
451                 while (!EXT2_EXT_IS_LAST_ENTRY(entry)) {
452                         struct ext2_ext_attr_entry *next =
453                                 EXT2_EXT_ATTR_NEXT(entry);
454                         if (entry->e_value_size > storage_size ||
455                                         (char *) next >= end) {
456                                 fprintf(out, "invalid EA entry in inode\n");
457                                 return;
458                         }
459                         fprintf(out, "  ");
460                         dump_xattr_string(out, EXT2_EXT_ATTR_NAME(entry), 
461                                           entry->e_name_len);
462                         fprintf(out, " = \"");
463                         dump_xattr_string(out, start + entry->e_value_offs,
464                                                 entry->e_value_size);
465                         fprintf(out, "\" (%d)\n", entry->e_value_size);
466                         entry = next;
467                 }
468         }
469 }
470
471 static void dump_blocks(FILE *f, const char *prefix, ext2_ino_t inode)
472 {
473         struct list_blocks_struct lb;
474
475         fprintf(f, "%sBLOCKS:\n%s", prefix, prefix);
476         lb.total = 0;
477         lb.first_block = 0;
478         lb.f = f;
479         lb.first = 1;
480         ext2fs_block_iterate2(current_fs, inode, 0, NULL,
481                              list_blocks_proc, (void *)&lb);
482         finish_range(&lb);
483         if (lb.total)
484                 fprintf(f, "\n%sTOTAL: %lld\n", prefix, lb.total);
485         fprintf(f,"\n");
486 }
487
488
489 void internal_dump_inode(FILE *out, const char *prefix,
490                          ext2_ino_t inode_num, struct ext2_inode *inode,
491                          int do_dump_blocks)
492 {
493         const char *i_type;
494         char frag, fsize;
495         int os = current_fs->super->s_creator_os;
496         
497         if (LINUX_S_ISDIR(inode->i_mode)) i_type = "directory";
498         else if (LINUX_S_ISREG(inode->i_mode)) i_type = "regular";
499         else if (LINUX_S_ISLNK(inode->i_mode)) i_type = "symlink";
500         else if (LINUX_S_ISBLK(inode->i_mode)) i_type = "block special";
501         else if (LINUX_S_ISCHR(inode->i_mode)) i_type = "character special";
502         else if (LINUX_S_ISFIFO(inode->i_mode)) i_type = "FIFO";
503         else if (LINUX_S_ISSOCK(inode->i_mode)) i_type = "socket";
504         else i_type = "bad type";
505         fprintf(out, "%sInode: %u   Type: %s    ", prefix, inode_num, i_type);
506         fprintf(out, "%sMode:  %04o   Flags: 0x%x   Generation: %u\n",
507                 prefix, 
508                 inode->i_mode & 0777, inode->i_flags, inode->i_generation);
509         fprintf(out, "%sUser: %5d   Group: %5d   Size: ",
510                 prefix, inode->i_uid, inode->i_gid);
511         if (LINUX_S_ISREG(inode->i_mode)) {
512                 __u64 i_size = (inode->i_size |
513                                 ((unsigned long long)inode->i_size_high << 32));
514
515                 fprintf(out, "%lld\n", i_size);
516         } else
517                 fprintf(out, "%d\n", inode->i_size);
518         if (current_fs->super->s_creator_os == EXT2_OS_HURD)
519                 fprintf(out,
520                         "%sFile ACL: %d    Directory ACL: %d Translator: %d\n",
521                         prefix,
522                         inode->i_file_acl, LINUX_S_ISDIR(inode->i_mode) ? inode->i_dir_acl : 0,
523                         inode->osd1.hurd1.h_i_translator);
524         else
525                 fprintf(out, "%sFile ACL: %d    Directory ACL: %d\n",
526                         prefix,
527                         inode->i_file_acl, LINUX_S_ISDIR(inode->i_mode) ? inode->i_dir_acl : 0);
528         fprintf(out, "%sLinks: %d   Blockcount: %d\n", 
529                 prefix, inode->i_links_count, inode->i_blocks);
530         switch (os) {
531             case EXT2_OS_LINUX:
532                 frag = inode->osd2.linux2.l_i_frag;
533                 fsize = inode->osd2.linux2.l_i_fsize;
534                 break;
535             case EXT2_OS_HURD:
536                 frag = inode->osd2.hurd2.h_i_frag;
537                 fsize = inode->osd2.hurd2.h_i_fsize;
538                 break;
539             case EXT2_OS_MASIX:
540                 frag = inode->osd2.masix2.m_i_frag;
541                 fsize = inode->osd2.masix2.m_i_fsize;
542                 break;
543             default:
544                 frag = fsize = 0;
545         }
546         fprintf(out, "%sFragment:  Address: %d    Number: %d    Size: %d\n",
547                 prefix, inode->i_faddr, frag, fsize);
548         fprintf(out, "%sctime: 0x%08x -- %s", prefix, inode->i_ctime,
549                 time_to_string(inode->i_ctime));
550         fprintf(out, "%satime: 0x%08x -- %s", prefix, inode->i_atime,
551                 time_to_string(inode->i_atime));
552         fprintf(out, "%smtime: 0x%08x -- %s", prefix, inode->i_mtime,
553                 time_to_string(inode->i_mtime));
554         if (inode->i_dtime) 
555           fprintf(out, "%sdtime: 0x%08x -- %s", prefix, inode->i_dtime,
556                   time_to_string(inode->i_dtime));
557         if (EXT2_INODE_SIZE(current_fs->super) > EXT2_GOOD_OLD_INODE_SIZE)
558                 internal_dump_inode_extra(out, prefix, inode_num,
559                                           (struct ext2_inode_large *) inode);
560         if (LINUX_S_ISLNK(inode->i_mode) && ext2fs_inode_data_blocks(current_fs,inode) == 0)
561                 fprintf(out, "%sFast_link_dest: %.*s\n", prefix,
562                         (int) inode->i_size, (char *)inode->i_block);
563         else if (LINUX_S_ISBLK(inode->i_mode) || LINUX_S_ISCHR(inode->i_mode)) {
564                 int major, minor;
565                 const char *devnote;
566
567                 if (inode->i_block[0]) {
568                         major = (inode->i_block[0] >> 8) & 255;
569                         minor = inode->i_block[0] & 255;
570                         devnote = "";
571                 } else {
572                         major = (inode->i_block[1] & 0xfff00) >> 8;
573                         minor = ((inode->i_block[1] & 0xff) | 
574                                  ((inode->i_block[1] >> 12) & 0xfff00));
575                         devnote = "(New-style) ";
576                 }
577                 fprintf(out, "%sDevice major/minor number: %02d:%02d (hex %02x:%02x)\n", 
578                         devnote, major, minor, major, minor);
579         }
580         else if (do_dump_blocks)
581                 dump_blocks(out, prefix, inode_num);
582 }
583
584 static void dump_inode(ext2_ino_t inode_num, struct ext2_inode *inode)
585 {
586         FILE    *out;
587         
588         out = open_pager();
589         internal_dump_inode(out, "", inode_num, inode, 1);
590         close_pager(out);
591 }
592
593 void do_stat(int argc, char *argv[])
594 {
595         ext2_ino_t      inode;
596         struct ext2_inode * inode_buf;
597
598         inode_buf = (struct ext2_inode *)
599                         malloc(EXT2_INODE_SIZE(current_fs->super));
600         if (!inode_buf) {
601                 fprintf(stderr, "do_stat: can't allocate buffer\n");
602                 return;
603         }
604
605         if (common_inode_args_process(argc, argv, &inode, 0)) {
606                 free(inode_buf);
607                 return;
608         }
609
610         if (debugfs_read_inode_full(inode, inode_buf, argv[0],
611                                         EXT2_INODE_SIZE(current_fs->super))) {
612                 free(inode_buf);
613                 return;
614         }
615
616         dump_inode(inode, inode_buf);
617         free(inode_buf);
618         return;
619 }
620
621 void do_chroot(int argc, char *argv[])
622 {
623         ext2_ino_t inode;
624         int retval;
625
626         if (common_inode_args_process(argc, argv, &inode, 0))
627                 return;
628
629         retval = ext2fs_check_directory(current_fs, inode);
630         if (retval)  {
631                 com_err(argv[1], retval, "");
632                 return;
633         }
634         root = inode;
635 }
636
637 void do_clri(int argc, char *argv[])
638 {
639         ext2_ino_t inode;
640         struct ext2_inode inode_buf;
641
642         if (common_inode_args_process(argc, argv, &inode, CHECK_FS_RW))
643                 return;
644
645         if (debugfs_read_inode(inode, &inode_buf, argv[0]))
646                 return;
647         memset(&inode_buf, 0, sizeof(inode_buf));
648         if (debugfs_write_inode(inode, &inode_buf, argv[0]))
649                 return;
650 }
651
652 void do_freei(int argc, char *argv[])
653 {
654         ext2_ino_t inode;
655
656         if (common_inode_args_process(argc, argv, &inode,
657                                       CHECK_FS_RW | CHECK_FS_BITMAPS))
658                 return;
659
660         if (!ext2fs_test_inode_bitmap(current_fs->inode_map,inode))
661                 com_err(argv[0], 0, "Warning: inode already clear");
662         ext2fs_unmark_inode_bitmap(current_fs->inode_map,inode);
663         ext2fs_mark_ib_dirty(current_fs);
664 }
665
666 void do_seti(int argc, char *argv[])
667 {
668         ext2_ino_t inode;
669
670         if (common_inode_args_process(argc, argv, &inode,
671                                       CHECK_FS_RW | CHECK_FS_BITMAPS))
672                 return;
673
674         if (ext2fs_test_inode_bitmap(current_fs->inode_map,inode))
675                 com_err(argv[0], 0, "Warning: inode already set");
676         ext2fs_mark_inode_bitmap(current_fs->inode_map,inode);
677         ext2fs_mark_ib_dirty(current_fs);
678 }
679
680 void do_testi(int argc, char *argv[])
681 {
682         ext2_ino_t inode;
683
684         if (common_inode_args_process(argc, argv, &inode, CHECK_FS_BITMAPS))
685                 return;
686
687         if (ext2fs_test_inode_bitmap(current_fs->inode_map,inode))
688                 printf("Inode %u is marked in use\n", inode);
689         else
690                 printf("Inode %u is not in use\n", inode);
691 }
692
693 void do_freeb(int argc, char *argv[])
694 {
695         blk_t block;
696         int count = 1;
697
698         if (common_block_args_process(argc, argv, &block, &count))
699                 return;
700         if (check_fs_read_write(argv[0]))
701                 return;
702         while (count-- > 0) {
703                 if (!ext2fs_test_block_bitmap(current_fs->block_map,block))
704                         com_err(argv[0], 0, "Warning: block %d already clear",
705                                 block);
706                 ext2fs_unmark_block_bitmap(current_fs->block_map,block);
707                 block++;
708         }
709         ext2fs_mark_bb_dirty(current_fs);
710 }
711
712 void do_setb(int argc, char *argv[])
713 {
714         blk_t block;
715         int count = 1;
716
717         if (common_block_args_process(argc, argv, &block, &count))
718                 return;
719         if (check_fs_read_write(argv[0]))
720                 return;
721         while (count-- > 0) {
722                 if (ext2fs_test_block_bitmap(current_fs->block_map,block))
723                         com_err(argv[0], 0, "Warning: block %d already set",
724                                 block);
725                 ext2fs_mark_block_bitmap(current_fs->block_map,block);
726                 block++;
727         }
728         ext2fs_mark_bb_dirty(current_fs);
729 }
730
731 void do_testb(int argc, char *argv[])
732 {
733         blk_t block;
734         int count = 1;
735
736         if (common_block_args_process(argc, argv, &block, &count))
737                 return;
738         while (count-- > 0) {
739                 if (ext2fs_test_block_bitmap(current_fs->block_map,block))
740                         printf("Block %d marked in use\n", block);
741                 else
742                         printf("Block %d not in use\n", block);
743                 block++;
744         }
745 }
746
747 static void modify_u8(char *com, const char *prompt,
748                       const char *format, __u8 *val)
749 {
750         char buf[200];
751         unsigned long v;
752         char *tmp;
753
754         sprintf(buf, format, *val);
755         printf("%30s    [%s] ", prompt, buf);
756         fgets(buf, sizeof(buf), stdin);
757         if (buf[strlen (buf) - 1] == '\n')
758                 buf[strlen (buf) - 1] = '\0';
759         if (!buf[0])
760                 return;
761         v = strtoul(buf, &tmp, 0);
762         if (*tmp)
763                 com_err(com, 0, "Bad value - %s", buf);
764         else
765                 *val = v;
766 }
767
768 static void modify_u16(char *com, const char *prompt,
769                        const char *format, __u16 *val)
770 {
771         char buf[200];
772         unsigned long v;
773         char *tmp;
774
775         sprintf(buf, format, *val);
776         printf("%30s    [%s] ", prompt, buf);
777         fgets(buf, sizeof(buf), stdin);
778         if (buf[strlen (buf) - 1] == '\n')
779                 buf[strlen (buf) - 1] = '\0';
780         if (!buf[0])
781                 return;
782         v = strtoul(buf, &tmp, 0);
783         if (*tmp)
784                 com_err(com, 0, "Bad value - %s", buf);
785         else
786                 *val = v;
787 }
788
789 static void modify_u32(char *com, const char *prompt,
790                        const char *format, __u32 *val)
791 {
792         char buf[200];
793         unsigned long v;
794         char *tmp;
795
796         sprintf(buf, format, *val);
797         printf("%30s    [%s] ", prompt, buf);
798         fgets(buf, sizeof(buf), stdin);
799         if (buf[strlen (buf) - 1] == '\n')
800                 buf[strlen (buf) - 1] = '\0';
801         if (!buf[0])
802                 return;
803         v = strtoul(buf, &tmp, 0);
804         if (*tmp)
805                 com_err(com, 0, "Bad value - %s", buf);
806         else
807                 *val = v;
808 }
809
810
811 void do_modify_inode(int argc, char *argv[])
812 {
813         struct ext2_inode inode;
814         ext2_ino_t      inode_num;
815         int             i;
816         unsigned char   *frag, *fsize;
817         char            buf[80];
818         int             os;
819         const char      *hex_format = "0x%x";
820         const char      *octal_format = "0%o";
821         const char      *decimal_format = "%d";
822         
823         if (common_inode_args_process(argc, argv, &inode_num, CHECK_FS_RW))
824                 return;
825
826         os = current_fs->super->s_creator_os;
827
828         if (debugfs_read_inode(inode_num, &inode, argv[1]))
829                 return;
830         
831         modify_u16(argv[0], "Mode", octal_format, &inode.i_mode);
832         modify_u16(argv[0], "User ID", decimal_format, &inode.i_uid);
833         modify_u16(argv[0], "Group ID", decimal_format, &inode.i_gid);
834         modify_u32(argv[0], "Size", decimal_format, &inode.i_size);
835         modify_u32(argv[0], "Creation time", decimal_format, &inode.i_ctime);
836         modify_u32(argv[0], "Modification time", decimal_format, &inode.i_mtime);
837         modify_u32(argv[0], "Access time", decimal_format, &inode.i_atime);
838         modify_u32(argv[0], "Deletion time", decimal_format, &inode.i_dtime);
839         modify_u16(argv[0], "Link count", decimal_format, &inode.i_links_count);
840         modify_u32(argv[0], "Block count", decimal_format, &inode.i_blocks);
841         modify_u32(argv[0], "File flags", hex_format, &inode.i_flags);
842         modify_u32(argv[0], "Generation", hex_format, &inode.i_generation);
843 #if 0
844         modify_u32(argv[0], "Reserved1", decimal_format, &inode.i_reserved1);
845 #endif
846         modify_u32(argv[0], "File acl", decimal_format, &inode.i_file_acl);
847         if (LINUX_S_ISDIR(inode.i_mode))
848                 modify_u32(argv[0], "Directory acl", decimal_format, &inode.i_dir_acl);
849         else
850                 modify_u32(argv[0], "High 32bits of size", decimal_format, &inode.i_size_high);
851
852         if (current_fs->super->s_creator_os == EXT2_OS_HURD)
853                 modify_u32(argv[0], "Translator Block",
854                             decimal_format, &inode.osd1.hurd1.h_i_translator);
855         
856         modify_u32(argv[0], "Fragment address", decimal_format, &inode.i_faddr);
857         switch (os) {
858             case EXT2_OS_LINUX:
859                 frag = &inode.osd2.linux2.l_i_frag;
860                 fsize = &inode.osd2.linux2.l_i_fsize;
861                 break;
862             case EXT2_OS_HURD:
863                 frag = &inode.osd2.hurd2.h_i_frag;
864                 fsize = &inode.osd2.hurd2.h_i_fsize;
865                 break;
866             case EXT2_OS_MASIX:
867                 frag = &inode.osd2.masix2.m_i_frag;
868                 fsize = &inode.osd2.masix2.m_i_fsize;
869                 break;
870             default:
871                 frag = fsize = 0;
872         }
873         if (frag)
874                 modify_u8(argv[0], "Fragment number", decimal_format, frag);
875         if (fsize)
876                 modify_u8(argv[0], "Fragment size", decimal_format, fsize);
877
878         for (i=0;  i < EXT2_NDIR_BLOCKS; i++) {
879                 sprintf(buf, "Direct Block #%d", i);
880                 modify_u32(argv[0], buf, decimal_format, &inode.i_block[i]);
881         }
882         modify_u32(argv[0], "Indirect Block", decimal_format,
883                     &inode.i_block[EXT2_IND_BLOCK]);    
884         modify_u32(argv[0], "Double Indirect Block", decimal_format,
885                     &inode.i_block[EXT2_DIND_BLOCK]);
886         modify_u32(argv[0], "Triple Indirect Block", decimal_format,
887                     &inode.i_block[EXT2_TIND_BLOCK]);
888         if (debugfs_write_inode(inode_num, &inode, argv[1]))
889                 return;
890 }
891
892 void do_change_working_dir(int argc, char *argv[])
893 {
894         ext2_ino_t      inode;
895         int             retval;
896         
897         if (common_inode_args_process(argc, argv, &inode, 0))
898                 return;
899
900         retval = ext2fs_check_directory(current_fs, inode);
901         if (retval) {
902                 com_err(argv[1], retval, "");
903                 return;
904         }
905         cwd = inode;
906         return;
907 }
908
909 void do_print_working_directory(int argc, char *argv[])
910 {
911         int     retval;
912         char    *pathname = NULL;
913         
914         if (common_args_process(argc, argv, 1, 1,
915                                 "print_working_directory", "", 0))
916                 return;
917
918         retval = ext2fs_get_pathname(current_fs, cwd, 0, &pathname);
919         if (retval) {
920                 com_err(argv[0], retval,
921                         "while trying to get pathname of cwd");
922         }
923         printf("[pwd]   INODE: %6u  PATH: %s\n", cwd, pathname);
924         free(pathname);
925         retval = ext2fs_get_pathname(current_fs, root, 0, &pathname);
926         if (retval) {
927                 com_err(argv[0], retval,
928                         "while trying to get pathname of root");
929         }
930         printf("[root]  INODE: %6u  PATH: %s\n", root, pathname);
931         free(pathname);
932         return;
933 }
934
935 /*
936  * Given a mode, return the ext2 file type
937  */
938 static int ext2_file_type(unsigned int mode)
939 {
940         if (LINUX_S_ISREG(mode))
941                 return EXT2_FT_REG_FILE;
942
943         if (LINUX_S_ISDIR(mode))
944                 return EXT2_FT_DIR;
945         
946         if (LINUX_S_ISCHR(mode))
947                 return EXT2_FT_CHRDEV;
948         
949         if (LINUX_S_ISBLK(mode))
950                 return EXT2_FT_BLKDEV;
951         
952         if (LINUX_S_ISLNK(mode))
953                 return EXT2_FT_SYMLINK;
954
955         if (LINUX_S_ISFIFO(mode))
956                 return EXT2_FT_FIFO;
957         
958         if (LINUX_S_ISSOCK(mode))
959                 return EXT2_FT_SOCK;
960         
961         return 0;
962 }
963
964 static void make_link(char *sourcename, char *destname)
965 {
966         ext2_ino_t      ino;
967         struct ext2_inode inode;
968         int             retval;
969         ext2_ino_t      dir;
970         char            *dest, *cp, *basename;
971
972         /*
973          * Get the source inode
974          */
975         ino = string_to_inode(sourcename);
976         if (!ino)
977                 return;
978         basename = strrchr(sourcename, '/');
979         if (basename)
980                 basename++;
981         else
982                 basename = sourcename;
983         /*
984          * Figure out the destination.  First see if it exists and is
985          * a directory.  
986          */
987         if (! (retval=ext2fs_namei(current_fs, root, cwd, destname, &dir)))
988                 dest = basename;
989         else {
990                 /*
991                  * OK, it doesn't exist.  See if it is
992                  * '<dir>/basename' or 'basename'
993                  */
994                 cp = strrchr(destname, '/');
995                 if (cp) {
996                         *cp = 0;
997                         dir = string_to_inode(destname);
998                         if (!dir)
999                                 return;
1000                         dest = cp+1;
1001                 } else {
1002                         dir = cwd;
1003                         dest = destname;
1004                 }
1005         }
1006
1007         if (debugfs_read_inode(ino, &inode, sourcename))
1008                 return;
1009         
1010         retval = ext2fs_link(current_fs, dir, dest, ino, 
1011                              ext2_file_type(inode.i_mode));
1012         if (retval)
1013                 com_err("make_link", retval, "");
1014         return;
1015 }
1016
1017
1018 void do_link(int argc, char *argv[])
1019 {
1020         if (common_args_process(argc, argv, 3, 3, "link",
1021                                 "<source file> <dest_name>", CHECK_FS_RW))
1022                 return;
1023
1024         make_link(argv[1], argv[2]);
1025 }
1026
1027 static int mark_blocks_proc(ext2_filsys fs, blk_t *blocknr,
1028                             int blockcnt EXT2FS_ATTR((unused)), 
1029                             void *private EXT2FS_ATTR((unused)))
1030 {
1031         blk_t   block;
1032
1033         block = *blocknr;
1034         ext2fs_block_alloc_stats(fs, block, +1);
1035         return 0;
1036 }
1037
1038 void do_undel(int argc, char *argv[])
1039 {
1040         ext2_ino_t      ino;
1041         struct ext2_inode inode;
1042
1043         if (common_args_process(argc, argv, 3, 3, "undelete",
1044                                 "<inode_num> <dest_name>",
1045                                 CHECK_FS_RW | CHECK_FS_BITMAPS))
1046                 return;
1047
1048         ino = string_to_inode(argv[1]);
1049         if (!ino)
1050                 return;
1051
1052         if (debugfs_read_inode(ino, &inode, argv[1]))
1053                 return;
1054
1055         if (ext2fs_test_inode_bitmap(current_fs->inode_map, ino)) {
1056                 com_err(argv[1], 0, "Inode is not marked as deleted");
1057                 return;
1058         }
1059
1060         /*
1061          * XXX this function doesn't handle changing the links count on the
1062          * parent directory when undeleting a directory.  
1063          */
1064         inode.i_links_count = LINUX_S_ISDIR(inode.i_mode) ? 2 : 1;
1065         inode.i_dtime = 0;
1066
1067         if (debugfs_write_inode(ino, &inode, argv[0]))
1068                 return;
1069
1070         ext2fs_block_iterate(current_fs, ino, 0, NULL,
1071                              mark_blocks_proc, NULL);
1072
1073         ext2fs_inode_alloc_stats2(current_fs, ino, +1, 0);
1074
1075         make_link(argv[1], argv[2]);
1076 }
1077
1078 static void unlink_file_by_name(char *filename)
1079 {
1080         int             retval;
1081         ext2_ino_t      dir;
1082         char            *basename;
1083         
1084         basename = strrchr(filename, '/');
1085         if (basename) {
1086                 *basename++ = '\0';
1087                 dir = string_to_inode(filename);
1088                 if (!dir)
1089                         return;
1090         } else {
1091                 dir = cwd;
1092                 basename = filename;
1093         }
1094         retval = ext2fs_unlink(current_fs, dir, basename, 0, 0);
1095         if (retval)
1096                 com_err("unlink_file_by_name", retval, "");
1097         return;
1098 }
1099
1100 void do_unlink(int argc, char *argv[])
1101 {
1102         if (common_args_process(argc, argv, 2, 2, "link",
1103                                 "<pathname>", CHECK_FS_RW))
1104                 return;
1105
1106         unlink_file_by_name(argv[1]);
1107 }
1108
1109 void do_find_free_block(int argc, char *argv[])
1110 {
1111         blk_t   free_blk, goal;
1112         int             count;
1113         errcode_t       retval;
1114         char            *tmp;
1115         
1116         if ((argc > 3) || (argc==2 && *argv[1] == '?')) {
1117                 com_err(argv[0], 0, "Usage: find_free_block [count [goal]]");
1118                 return;
1119         }
1120         if (check_fs_open(argv[0]))
1121                 return;
1122
1123         if (argc > 1) {
1124                 count = strtol(argv[1],&tmp,0);
1125                 if (*tmp) {
1126                         com_err(argv[0], 0, "Bad count - %s", argv[1]);
1127                         return;
1128                 }
1129         } else
1130                 count = 1;
1131
1132         if (argc > 2) {
1133                 goal = strtol(argv[2], &tmp, 0);
1134                 if (*tmp) {
1135                         com_err(argv[0], 0, "Bad goal - %s", argv[1]);
1136                         return;
1137                 }
1138         }
1139         else
1140                 goal = current_fs->super->s_first_data_block;
1141
1142         printf("Free blocks found: ");
1143         free_blk = goal - 1;    
1144         while (count-- > 0) {
1145                 retval = ext2fs_new_block(current_fs, free_blk + 1, 0,
1146                                           &free_blk);
1147                 if (retval) {
1148                         com_err("ext2fs_new_block", retval, "");
1149                         return;
1150                 } else
1151                         printf("%d ", free_blk);
1152         }
1153         printf("\n");
1154 }
1155
1156 void do_find_free_inode(int argc, char *argv[])
1157 {
1158         ext2_ino_t      free_inode, dir;
1159         int             mode;
1160         int             retval;
1161         char            *tmp;
1162         
1163         if (argc > 3 || (argc>1 && *argv[1] == '?')) {
1164                 com_err(argv[0], 0, "Usage: find_free_inode [dir] [mode]");
1165                 return;
1166         }
1167         if (check_fs_open(argv[0]))
1168                 return;
1169
1170         if (argc > 1) {
1171                 dir = strtol(argv[1], &tmp, 0);
1172                 if (*tmp) {
1173                         com_err(argv[0], 0, "Bad dir - %s", argv[1]);
1174                         return;
1175                 }
1176         }
1177         else
1178                 dir = root;
1179         if (argc > 2) {
1180                 mode = strtol(argv[2], &tmp, 0);
1181                 if (*tmp) {
1182                         com_err(argv[0], 0, "Bad mode - %s", argv[2]);
1183                         return;
1184                 }
1185         } else
1186                 mode = 010755;
1187
1188         retval = ext2fs_new_inode(current_fs, dir, mode, 0, &free_inode);
1189         if (retval)
1190                 com_err("ext2fs_new_inode", retval, "");
1191         else
1192                 printf("Free inode found: %u\n", free_inode);
1193 }
1194
1195 static errcode_t copy_file(int fd, ext2_ino_t newfile)
1196 {
1197         ext2_file_t     e2_file;
1198         errcode_t       retval;
1199         int             got;
1200         unsigned int    written;
1201         char            buf[8192];
1202         char            *ptr;
1203
1204         retval = ext2fs_file_open(current_fs, newfile,
1205                                   EXT2_FILE_WRITE, &e2_file);
1206         if (retval)
1207                 return retval;
1208
1209         while (1) {
1210                 got = read(fd, buf, sizeof(buf));
1211                 if (got == 0)
1212                         break;
1213                 if (got < 0) {
1214                         retval = errno;
1215                         goto fail;
1216                 }
1217                 ptr = buf;
1218                 while (got > 0) {
1219                         retval = ext2fs_file_write(e2_file, ptr,
1220                                                    got, &written);
1221                         if (retval)
1222                                 goto fail;
1223
1224                         got -= written;
1225                         ptr += written;
1226                 }
1227         }
1228         retval = ext2fs_file_close(e2_file);
1229         return retval;
1230
1231 fail:
1232         (void) ext2fs_file_close(e2_file);
1233         return retval;
1234 }
1235
1236
1237 void do_write(int argc, char *argv[])
1238 {
1239         int             fd;
1240         struct stat     statbuf;
1241         ext2_ino_t      newfile;
1242         errcode_t       retval;
1243         struct ext2_inode inode;
1244
1245         if (common_args_process(argc, argv, 3, 3, "write",
1246                                 "<native file> <new file>", CHECK_FS_RW))
1247                 return;
1248
1249         fd = open(argv[1], O_RDONLY);
1250         if (fd < 0) {
1251                 com_err(argv[1], errno, "");
1252                 return;
1253         }
1254         if (fstat(fd, &statbuf) < 0) {
1255                 com_err(argv[1], errno, "");
1256                 close(fd);
1257                 return;
1258         }
1259
1260         retval = ext2fs_namei(current_fs, root, cwd, argv[2], &newfile);
1261         if (retval == 0) {
1262                 com_err(argv[0], 0, "The file '%s' already exists\n", argv[2]);
1263                 close(fd);
1264                 return;
1265         }
1266
1267         retval = ext2fs_new_inode(current_fs, cwd, 010755, 0, &newfile);
1268         if (retval) {
1269                 com_err(argv[0], retval, "");
1270                 close(fd);
1271                 return;
1272         }
1273         printf("Allocated inode: %u\n", newfile);
1274         retval = ext2fs_link(current_fs, cwd, argv[2], newfile,
1275                              EXT2_FT_REG_FILE);
1276         if (retval == EXT2_ET_DIR_NO_SPACE) {
1277                 retval = ext2fs_expand_dir(current_fs, cwd);
1278                 if (retval) {
1279                         com_err(argv[0], retval, "while expanding directory");
1280                         return;
1281                 }
1282                 retval = ext2fs_link(current_fs, cwd, argv[2], newfile,
1283                                      EXT2_FT_REG_FILE);
1284         }
1285         if (retval) {
1286                 com_err(argv[2], retval, "");
1287                 close(fd);
1288                 return;
1289         }
1290         if (ext2fs_test_inode_bitmap(current_fs->inode_map,newfile))
1291                 com_err(argv[0], 0, "Warning: inode already set");
1292         ext2fs_inode_alloc_stats2(current_fs, newfile, +1, 0);
1293         memset(&inode, 0, sizeof(inode));
1294         inode.i_mode = (statbuf.st_mode & ~LINUX_S_IFMT) | LINUX_S_IFREG;
1295         inode.i_atime = inode.i_ctime = inode.i_mtime = time(NULL);
1296         inode.i_links_count = 1;
1297         inode.i_size = statbuf.st_size;
1298         if (debugfs_write_new_inode(newfile, &inode, argv[0])) {
1299                 close(fd);
1300                 return;
1301         }
1302         if (LINUX_S_ISREG(inode.i_mode)) {
1303                 retval = copy_file(fd, newfile);
1304                 if (retval)
1305                         com_err("copy_file", retval, "");
1306         }
1307         close(fd);
1308 }
1309
1310 void do_mknod(int argc, char *argv[])
1311 {
1312         unsigned long   mode, major, minor;
1313         ext2_ino_t      newfile;
1314         errcode_t       retval;
1315         struct ext2_inode inode;
1316         int             filetype, nr;
1317
1318         if (check_fs_open(argv[0]))
1319                 return;
1320         if (argc < 3 || argv[2][1]) {
1321         usage:
1322                 com_err(argv[0], 0, "Usage: mknod <name> [p| [c|b] <major> <minor>]");
1323                 return;
1324         }
1325         mode = minor = major = 0;
1326         switch (argv[2][0]) {
1327                 case 'p':
1328                         mode = LINUX_S_IFIFO;
1329                         filetype = EXT2_FT_FIFO;
1330                         nr = 3;
1331                         break;
1332                 case 'c':
1333                         mode = LINUX_S_IFCHR;
1334                         filetype = EXT2_FT_CHRDEV;
1335                         nr = 5;
1336                         break;
1337                 case 'b':
1338                         mode = LINUX_S_IFBLK;
1339                         filetype = EXT2_FT_BLKDEV;
1340                         nr = 5;
1341                         break;
1342                 default:
1343                         filetype = 0;
1344                         nr = 0;
1345         }
1346         if (nr == 5) {
1347                 major = strtoul(argv[3], argv+3, 0);
1348                 minor = strtoul(argv[4], argv+4, 0);
1349                 if (major > 65535 || minor > 65535 || argv[3][0] || argv[4][0])
1350                         nr = 0;
1351         }
1352         if (argc != nr)
1353                 goto usage;
1354         if (check_fs_read_write(argv[0]))
1355                 return;
1356         retval = ext2fs_new_inode(current_fs, cwd, 010755, 0, &newfile);
1357         if (retval) {
1358                 com_err(argv[0], retval, "");
1359                 return;
1360         }
1361         printf("Allocated inode: %u\n", newfile);
1362         retval = ext2fs_link(current_fs, cwd, argv[1], newfile, filetype);
1363         if (retval == EXT2_ET_DIR_NO_SPACE) {
1364                 retval = ext2fs_expand_dir(current_fs, cwd);
1365                 if (retval) {
1366                         com_err(argv[0], retval, "while expanding directory");
1367                         return;
1368                 }
1369                 retval = ext2fs_link(current_fs, cwd, argv[1], newfile,
1370                                      filetype);
1371         }
1372         if (retval) {
1373                 com_err(argv[1], retval, "");
1374                 return;
1375         }
1376         if (ext2fs_test_inode_bitmap(current_fs->inode_map,newfile))
1377                 com_err(argv[0], 0, "Warning: inode already set");
1378         ext2fs_mark_inode_bitmap(current_fs->inode_map, newfile);
1379         ext2fs_mark_ib_dirty(current_fs);
1380         memset(&inode, 0, sizeof(inode));
1381         inode.i_mode = mode;
1382         inode.i_atime = inode.i_ctime = inode.i_mtime = time(NULL);
1383         if ((major < 256) && (minor < 256)) {
1384                 inode.i_block[0] = major*256+minor;
1385                 inode.i_block[1] = 0;
1386         } else {
1387                 inode.i_block[0] = 0;
1388                 inode.i_block[1] = (minor & 0xff) | (major << 8) | ((minor & ~0xff) << 12);
1389         }
1390         inode.i_links_count = 1;
1391         if (debugfs_write_new_inode(newfile, &inode, argv[0]))
1392                 return;
1393 }
1394
1395 void do_mkdir(int argc, char *argv[])
1396 {
1397         char    *cp;
1398         ext2_ino_t      parent;
1399         char    *name;
1400         errcode_t retval;
1401
1402         if (common_args_process(argc, argv, 2, 2, "mkdir",
1403                                 "<filename>", CHECK_FS_RW))
1404                 return;
1405
1406         cp = strrchr(argv[1], '/');
1407         if (cp) {
1408                 *cp = 0;
1409                 parent = string_to_inode(argv[1]);
1410                 if (!parent) {
1411                         com_err(argv[1], ENOENT, "");
1412                         return;
1413                 }
1414                 name = cp+1;
1415         } else {
1416                 parent = cwd;
1417                 name = argv[1];
1418         }
1419
1420 try_again:
1421         retval = ext2fs_mkdir(current_fs, parent, 0, name);
1422         if (retval == EXT2_ET_DIR_NO_SPACE) {
1423                 retval = ext2fs_expand_dir(current_fs, parent);
1424                 if (retval) {
1425                         com_err("argv[0]", retval, "while expanding directory");
1426                         return;
1427                 }
1428                 goto try_again;
1429         }
1430         if (retval) {
1431                 com_err("ext2fs_mkdir", retval, "");
1432                 return;
1433         }
1434
1435 }
1436
1437 static int release_blocks_proc(ext2_filsys fs, blk_t *blocknr,
1438                                int blockcnt EXT2FS_ATTR((unused)), 
1439                                void *private EXT2FS_ATTR((unused)))
1440 {
1441         blk_t   block;
1442
1443         block = *blocknr;
1444         ext2fs_block_alloc_stats(fs, block, -1);
1445         return 0;
1446 }
1447
1448 static void kill_file_by_inode(ext2_ino_t inode)
1449 {
1450         struct ext2_inode inode_buf;
1451
1452         if (debugfs_read_inode(inode, &inode_buf, 0))
1453                 return;
1454         inode_buf.i_dtime = time(NULL);
1455         if (debugfs_write_inode(inode, &inode_buf, 0))
1456                 return;
1457         if (!ext2fs_inode_has_valid_blocks(&inode_buf))
1458                 return;
1459
1460         ext2fs_block_iterate(current_fs, inode, 0, NULL,
1461                              release_blocks_proc, NULL);
1462         printf("\n");
1463         ext2fs_inode_alloc_stats2(current_fs, inode, -1,
1464                                   LINUX_S_ISDIR(inode_buf.i_mode));
1465 }
1466
1467
1468 void do_kill_file(int argc, char *argv[])
1469 {
1470         ext2_ino_t inode_num;
1471
1472         if (common_inode_args_process(argc, argv, &inode_num, CHECK_FS_RW))
1473                 return;
1474
1475         kill_file_by_inode(inode_num);
1476 }
1477
1478 void do_rm(int argc, char *argv[])
1479 {
1480         int retval;
1481         ext2_ino_t inode_num;
1482         struct ext2_inode inode;
1483
1484         if (common_args_process(argc, argv, 2, 2, "rm",
1485                                 "<filename>", CHECK_FS_RW))
1486                 return;
1487
1488         retval = ext2fs_namei(current_fs, root, cwd, argv[1], &inode_num);
1489         if (retval) {
1490                 com_err(argv[0], retval, "while trying to resolve filename");
1491                 return;
1492         }
1493
1494         if (debugfs_read_inode(inode_num, &inode, argv[0]))
1495                 return;
1496
1497         if (LINUX_S_ISDIR(inode.i_mode)) {
1498                 com_err(argv[0], 0, "file is a directory");
1499                 return;
1500         }
1501
1502         --inode.i_links_count;
1503         if (debugfs_write_inode(inode_num, &inode, argv[0]))
1504                 return;
1505
1506         unlink_file_by_name(argv[1]);
1507         if (inode.i_links_count == 0)
1508                 kill_file_by_inode(inode_num);
1509 }
1510
1511 struct rd_struct {
1512         ext2_ino_t      parent;
1513         int             empty;
1514 };
1515
1516 static int rmdir_proc(ext2_ino_t dir EXT2FS_ATTR((unused)),
1517                       int       entry EXT2FS_ATTR((unused)),
1518                       struct ext2_dir_entry *dirent,
1519                       int       offset EXT2FS_ATTR((unused)),
1520                       int       blocksize EXT2FS_ATTR((unused)),
1521                       char      *buf EXT2FS_ATTR((unused)),
1522                       void      *private)
1523 {
1524         struct rd_struct *rds = (struct rd_struct *) private;
1525
1526         if (dirent->inode == 0)
1527                 return 0;
1528         if (((dirent->name_len&0xFF) == 1) && (dirent->name[0] == '.'))
1529                 return 0;
1530         if (((dirent->name_len&0xFF) == 2) && (dirent->name[0] == '.') &&
1531             (dirent->name[1] == '.')) {
1532                 rds->parent = dirent->inode;
1533                 return 0;
1534         }
1535         rds->empty = 0;
1536         return 0;
1537 }
1538         
1539 void do_rmdir(int argc, char *argv[])
1540 {
1541         int retval;
1542         ext2_ino_t inode_num;
1543         struct ext2_inode inode;
1544         struct rd_struct rds;
1545
1546         if (common_args_process(argc, argv, 2, 2, "rmdir",
1547                                 "<filename>", CHECK_FS_RW))
1548                 return;
1549
1550         retval = ext2fs_namei(current_fs, root, cwd, argv[1], &inode_num);
1551         if (retval) {
1552                 com_err(argv[0], retval, "while trying to resolve filename");
1553                 return;
1554         }
1555
1556         if (debugfs_read_inode(inode_num, &inode, argv[0]))
1557                 return;
1558
1559         if (!LINUX_S_ISDIR(inode.i_mode)) {
1560                 com_err(argv[0], 0, "file is not a directory");
1561                 return;
1562         }
1563
1564         rds.parent = 0;
1565         rds.empty = 1;
1566
1567         retval = ext2fs_dir_iterate2(current_fs, inode_num, 0,
1568                                     0, rmdir_proc, &rds);
1569         if (retval) {
1570                 com_err(argv[0], retval, "while iterating over directory");
1571                 return;
1572         }
1573         if (rds.empty == 0) {
1574                 com_err(argv[0], 0, "directory not empty");
1575                 return;
1576         }
1577
1578         inode.i_links_count = 0;
1579         if (debugfs_write_inode(inode_num, &inode, argv[0]))
1580                 return;
1581
1582         unlink_file_by_name(argv[1]);
1583         kill_file_by_inode(inode_num);
1584
1585         if (rds.parent) {
1586                 if (debugfs_read_inode(rds.parent, &inode, argv[0]))
1587                         return;
1588                 if (inode.i_links_count > 1)
1589                         inode.i_links_count--;
1590                 if (debugfs_write_inode(rds.parent, &inode, argv[0]))
1591                         return;
1592         }
1593 }
1594
1595 void do_show_debugfs_params(int argc EXT2FS_ATTR((unused)), 
1596                             char *argv[] EXT2FS_ATTR((unused)))
1597 {
1598         FILE *out = stdout;
1599
1600         if (current_fs)
1601                 fprintf(out, "Open mode: read-%s\n",
1602                         current_fs->flags & EXT2_FLAG_RW ? "write" : "only");
1603         fprintf(out, "Filesystem in use: %s\n",
1604                 current_fs ? current_fs->device_name : "--none--");
1605 }
1606
1607 void do_expand_dir(int argc, char *argv[])
1608 {
1609         ext2_ino_t inode;
1610         int retval;
1611
1612         if (common_inode_args_process(argc, argv, &inode, CHECK_FS_RW))
1613                 return;
1614
1615         retval = ext2fs_expand_dir(current_fs, inode);
1616         if (retval)
1617                 com_err("ext2fs_expand_dir", retval, "");
1618         return;
1619 }
1620
1621 void do_features(int argc, char *argv[])
1622 {
1623         int     i;
1624         
1625         if (check_fs_open(argv[0]))
1626                 return;
1627
1628         if ((argc != 1) && check_fs_read_write(argv[0]))
1629                 return;
1630         for (i=1; i < argc; i++) {
1631                 if (e2p_edit_feature(argv[i],
1632                                      &current_fs->super->s_feature_compat, 0))
1633                         com_err(argv[0], 0, "Unknown feature: %s\n",
1634                                 argv[i]);
1635                 else
1636                         ext2fs_mark_super_dirty(current_fs);
1637         }
1638         print_features(current_fs->super, stdout);
1639 }
1640
1641 void do_bmap(int argc, char *argv[])
1642 {
1643         ext2_ino_t      ino;
1644         blk_t           blk, pblk;
1645         int             err;
1646         errcode_t       errcode;
1647         
1648         if (common_args_process(argc, argv, 3, 3, argv[0],
1649                                 "<file> logical_blk", 0))
1650                 return;
1651
1652         ino = string_to_inode(argv[1]);
1653         if (!ino)
1654                 return;
1655         blk = parse_ulong(argv[2], argv[0], "logical_block", &err);
1656
1657         errcode = ext2fs_bmap(current_fs, ino, 0, 0, 0, blk, &pblk);
1658         if (errcode) {
1659                 com_err("argv[0]", errcode,
1660                         "while mapping logical block %d\n", blk);
1661                 return;
1662         }
1663         printf("%d\n", pblk);
1664 }
1665
1666 void do_imap(int argc, char *argv[])
1667 {
1668         ext2_ino_t      ino;
1669         unsigned long   group, block, block_nr, offset;
1670
1671         if (common_args_process(argc, argv, 2, 2, argv[0],
1672                                 "<file>", 0))
1673                 return;
1674         ino = string_to_inode(argv[1]);
1675         if (!ino)
1676                 return;
1677
1678         group = (ino - 1) / EXT2_INODES_PER_GROUP(current_fs->super);
1679         offset = ((ino - 1) % EXT2_INODES_PER_GROUP(current_fs->super)) *
1680                 EXT2_INODE_SIZE(current_fs->super);
1681         block = offset >> EXT2_BLOCK_SIZE_BITS(current_fs->super);
1682         if (!current_fs->group_desc[(unsigned)group].bg_inode_table) {
1683                 com_err(argv[0], 0, "Inode table for group %lu is missing\n",
1684                         group);
1685                 return;
1686         }
1687         block_nr = current_fs->group_desc[(unsigned)group].bg_inode_table + 
1688                 block;
1689         offset &= (EXT2_BLOCK_SIZE(current_fs->super) - 1);
1690
1691         printf("Inode %d is part of block group %lu\n"
1692                "\tlocated at block %lu, offset 0x%04lx\n", ino, group,
1693                block_nr, offset);
1694
1695 }
1696
1697
1698
1699 static int source_file(const char *cmd_file, int sci_idx)
1700 {
1701         FILE            *f;
1702         char            buf[256];
1703         char            *cp;
1704         int             exit_status = 0;
1705         int             retval;
1706
1707         if (strcmp(cmd_file, "-") == 0)
1708                 f = stdin;
1709         else {
1710                 f = fopen(cmd_file, "r");
1711                 if (!f) {
1712                         perror(cmd_file);
1713                         exit(1);
1714                 }
1715         }
1716         setbuf(stdout, NULL);
1717         setbuf(stderr, NULL);
1718         while (!feof(f)) {
1719                 if (fgets(buf, sizeof(buf), f) == NULL)
1720                         break;
1721                 cp = strchr(buf, '\n');
1722                 if (cp)
1723                         *cp = 0;
1724                 cp = strchr(buf, '\r');
1725                 if (cp)
1726                         *cp = 0;
1727                 printf("debugfs: %s\n", buf);
1728                 retval = ss_execute_line(sci_idx, buf);
1729                 if (retval) {
1730                         ss_perror(sci_idx, retval, buf);
1731                         exit_status++;
1732                 }
1733         }
1734         return exit_status;
1735 }
1736
1737 int main(int argc, char **argv)
1738 {
1739         int             retval;
1740         int             sci_idx;
1741         const char      *usage = "Usage: debugfs [-b blocksize] [-s superblock] [-f cmd_file] [-R request] [-V] [[-w] [-c] device]";
1742         int             c;
1743         int             open_flags = 0;
1744         char            *request = 0;
1745         int             exit_status = 0;
1746         char            *cmd_file = 0;
1747         blk_t           superblock = 0;
1748         blk_t           blocksize = 0;
1749         int             catastrophic = 0;
1750         char            *data_filename = 0;
1751         
1752         initialize_ext2_error_table();
1753         fprintf (stderr, "debugfs %s (%s)\n", E2FSPROGS_VERSION,
1754                  E2FSPROGS_DATE);
1755
1756         while ((c = getopt (argc, argv, "iwcR:f:b:s:Vd:")) != EOF) {
1757                 switch (c) {
1758                 case 'R':
1759                         request = optarg;
1760                         break;
1761                 case 'f':
1762                         cmd_file = optarg;
1763                         break;
1764                 case 'd':
1765                         data_filename = optarg;
1766                         break;
1767                 case 'i':
1768                         open_flags |= EXT2_FLAG_IMAGE_FILE;
1769                         break;
1770                 case 'w':
1771                         open_flags |= EXT2_FLAG_RW;
1772                         break;
1773                 case 'b':
1774                         blocksize = parse_ulong(optarg, argv[0], 
1775                                                 "block size", 0);
1776                         break;
1777                 case 's':
1778                         superblock = parse_ulong(optarg, argv[0], 
1779                                                  "superblock number", 0);
1780                         break;
1781                 case 'c':
1782                         catastrophic = 1;
1783                         break;
1784                 case 'V':
1785                         /* Print version number and exit */
1786                         fprintf(stderr, "\tUsing %s\n",
1787                                 error_message(EXT2_ET_BASE));
1788                         exit(0);
1789                 default:
1790                         com_err(argv[0], 0, usage);
1791                         return 1;
1792                 }
1793         }
1794         if (optind < argc)
1795                 open_filesystem(argv[optind], open_flags,
1796                                 superblock, blocksize, catastrophic,
1797                                 data_filename);
1798         
1799         sci_idx = ss_create_invocation("debugfs", "0.0", (char *) NULL,
1800                                        &debug_cmds, &retval);
1801         if (retval) {
1802                 ss_perror(sci_idx, retval, "creating invocation");
1803                 exit(1);
1804         }
1805         ss_get_readline(sci_idx);
1806
1807         (void) ss_add_request_table (sci_idx, &ss_std_requests, 1, &retval);
1808         if (retval) {
1809                 ss_perror(sci_idx, retval, "adding standard requests");
1810                 exit (1);
1811         }
1812         if (request) {
1813                 retval = 0;
1814                 retval = ss_execute_line(sci_idx, request);
1815                 if (retval) {
1816                         ss_perror(sci_idx, retval, request);
1817                         exit_status++;
1818                 }
1819         } else if (cmd_file) {
1820                 exit_status = source_file(cmd_file, sci_idx);
1821         } else {
1822                 ss_listen(sci_idx);
1823         }
1824
1825         if (current_fs)
1826                 close_filesystem();
1827         
1828         return exit_status;
1829 }