Whamcloud - gitweb
Fix gcc -Wall warnings.
[tools/e2fsprogs.git] / e2fsck / unix.c
1 /*
2  * unix.c - The unix-specific code for e2fsck
3  * 
4  * Copyright (C) 1993, 1994, 1995, 1996, 1997 Theodore Ts'o.
5  *
6  * %Begin-Header%
7  * This file may be redistributed under the terms of the GNU Public
8  * License.
9  * %End-Header%
10  */
11
12 #include <stdio.h>
13 #ifdef HAVE_STDLIB_H
14 #include <stdlib.h>
15 #endif
16 #include <string.h>
17 #include <fcntl.h>
18 #include <ctype.h>
19 #include <time.h>
20 #ifdef HAVE_SIGNAL_H
21 #include <signal.h>
22 #endif
23 #ifdef HAVE_GETOPT_H
24 #include <getopt.h>
25 #else
26 extern char *optarg;
27 extern int optind;
28 #endif
29 #include <unistd.h>
30 #ifdef HAVE_ERRNO_H
31 #include <errno.h>
32 #endif
33 #ifdef HAVE_MNTENT_H
34 #include <mntent.h>
35 #endif
36 #ifdef HAVE_SYS_IOCTL_H
37 #include <sys/ioctl.h>
38 #endif
39 #ifdef HAVE_MALLOC_H
40 #include <malloc.h>
41 #endif
42
43 #include "et/com_err.h"
44 #include "e2fsck.h"
45 #include "problem.h"
46 #include "../version.h"
47
48 /* Command line options */
49 static int swapfs = 0;
50 static int normalize_swapfs = 0;
51 static int cflag = 0;           /* check disk */
52 static int show_version_only = 0;
53 static int verbose = 0;
54
55 static int replace_bad_blocks = 0;
56 static char *bad_blocks_file = 0;
57
58 e2fsck_t e2fsck_global_ctx;     /* Try your very best not to use this! */
59
60 #ifdef CONFIG_JBD_DEBUG         /* Enabled by configure --enable-jfs-debug */
61 int journal_enable_debug = -1;
62 #endif
63
64 static void usage(e2fsck_t ctx)
65 {
66         fprintf(stderr,
67                 _("Usage: %s [-panyrcdfvstDFSV] [-b superblock] [-B blocksize]\n"
68                 "\t\t[-I inode_buffer_blocks] [-P process_inode_size]\n"
69                 "\t\t[-l|-L bad_blocks_file] [-C fd] [-j ext-journal]\n"
70                 "\t\t[-E extended-options] device\n"),
71                 ctx->program_name);
72
73         fprintf(stderr, _("\nEmergency help:\n"
74                 " -p                   Automatic repair (no questions)\n"
75                 " -n                   Make no changes to the filesystem\n"
76                 " -y                   Assume \"yes\" to all questions\n"
77                 " -c                   Check for bad blocks and add them to the badblock list\n"
78                 " -f                   Force checking even if filesystem is marked clean\n"));
79         fprintf(stderr, _(""
80                 " -v                   Be verbose\n"
81                 " -b superblock        Use alternative superblock\n"
82                 " -B blocksize         Force blocksize when looking for superblock\n"
83                 " -j external-journal  Set location of the external journal\n"
84                 " -l bad_blocks_file   Add to badblocks list\n"
85                 " -L bad_blocks_file   Set badblocks list\n"
86                 ));
87
88         exit(FSCK_USAGE);
89 }
90
91 static void show_stats(e2fsck_t ctx)
92 {
93         ext2_filsys fs = ctx->fs;
94         int inodes, inodes_used, blocks, blocks_used;
95         int dir_links;
96         int num_files, num_links;
97         int frag_percent;
98
99         dir_links = 2 * ctx->fs_directory_count - 1;
100         num_files = ctx->fs_total_count - dir_links;
101         num_links = ctx->fs_links_count - dir_links;
102         inodes = fs->super->s_inodes_count;
103         inodes_used = (fs->super->s_inodes_count -
104                        fs->super->s_free_inodes_count);
105         blocks = fs->super->s_blocks_count;
106         blocks_used = (fs->super->s_blocks_count -
107                        fs->super->s_free_blocks_count);
108
109         frag_percent = (10000 * ctx->fs_fragmented) / inodes_used;
110         frag_percent = (frag_percent + 5) / 10;
111         
112         if (!verbose) {
113                 printf(_("%s: %d/%d files (%0d.%d%% non-contiguous), %d/%d blocks\n"),
114                        ctx->device_name, inodes_used, inodes,
115                        frag_percent / 10, frag_percent % 10,
116                        blocks_used, blocks);
117                 return;
118         }
119         /*
120          * This is a bit ugly. But I think there will nearly always be more
121          * than one "thing" to report about, so I won't try writing complex
122          * code to handle one/two/many forms of all words.
123          * Some languages (Italian, at least) never uses the plural form
124          * of foreign words, so in real life this could not be a problem.
125          * md@linux.it - 2000-1-15
126          */
127 #ifdef ENABLE_NLS
128         printf (_("\n%8d inodes used (%d%%)\n"), inodes_used,
129                 100 * inodes_used / inodes);
130         printf (_("%8d non-contiguous inodes (%0d.%d%%)\n"),
131                 ctx->fs_fragmented, frag_percent / 10, frag_percent % 10);
132         printf (_("         # of inodes with ind/dind/tind blocks: %d/%d/%d\n"),
133                 ctx->fs_ind_count, ctx->fs_dind_count, ctx->fs_tind_count);
134         printf (_("%8d blocks used (%d%%)\n"
135                 "%8d bad blocks\n"), blocks_used,
136                 (int) ((long long) 100 * blocks_used / blocks),
137                 ctx->fs_badblocks_count);
138         printf(_("%8d large files\n"), ctx->large_files);
139         printf (_("\n%8d regular files\n"
140                 "%8d directories\n"
141                 "%8d character device files\n"
142                 "%8d block device files\n"
143                 "%8d fifos\n"
144                 "%8d links\n"
145                 "%8d symbolic links (%d fast symbolic links)\n"
146                 "%8d sockets\n"
147                 "--------\n"
148                 "%8d files\n"),
149                 ctx->fs_regular_count,
150                 ctx->fs_directory_count,
151                 ctx->fs_chardev_count,
152                 ctx->fs_blockdev_count,
153                 ctx->fs_fifo_count,
154                 ctx->fs_links_count - dir_links,
155                 ctx->fs_symlinks_count,
156                 ctx->fs_fast_symlinks_count,
157                 ctx->fs_sockets_count,
158                 ctx->fs_total_count - dir_links);
159 #else
160         printf ("\n%8d inode%s used (%d%%)\n", inodes_used,
161                 (inodes_used != 1) ? "s" : "",
162                 100 * inodes_used / inodes);
163         printf ("%8d non-contiguous inodes (%0d.%d%%)\n",
164                 ctx->fs_fragmented, frag_percent / 10, frag_percent % 10);
165         printf ("         # of inodes with ind/dind/tind blocks: %d/%d/%d\n",
166                 ctx->fs_ind_count, ctx->fs_dind_count, ctx->fs_tind_count);
167         printf ("%8d block%s used (%d%%)\n"
168                 "%8d bad block%s\n", blocks_used,
169                 (blocks_used != 1) ? "s" : "",
170                 100 * blocks_used / blocks, ctx->fs_badblocks_count,
171                 ctx->fs_badblocks_count != 1 ? "s" : "");
172         printf(_("%8d large file%s\n"), ctx->large_files,
173                (ctx->large_files != 1) ? "s" : "");
174         printf ("\n%8d regular file%s\n"
175                 "%8d director%s\n"
176                 "%8d character device file%s\n"
177                 "%8d block device file%s\n"
178                 "%8d fifo%s\n"
179                 "%8d link%s\n"
180                 "%8d symbolic link%s (%d fast symbolic link%s)\n"
181                 "%8d socket%s\n"
182                 "--------\n"
183                 "%8d file%s\n",
184                 ctx->fs_regular_count,
185                 (ctx->fs_regular_count != 1) ? "s" : "",
186                 ctx->fs_directory_count,
187                 (ctx->fs_directory_count != 1) ? "ies" : "y",
188                 ctx->fs_chardev_count,
189                 (ctx->fs_chardev_count != 1) ? "s" : "",
190                 ctx->fs_blockdev_count,
191                 (ctx->fs_blockdev_count != 1) ? "s" : "",
192                 ctx->fs_fifo_count,
193                 (ctx->fs_fifo_count != 1) ? "s" : "",
194                 ctx->fs_links_count - dir_links,
195                 ((ctx->fs_links_count - dir_links) != 1) ? "s" : "",
196                 ctx->fs_symlinks_count,
197                 (ctx->fs_symlinks_count != 1) ? "s" : "",
198                 ctx->fs_fast_symlinks_count,
199                 (ctx->fs_fast_symlinks_count != 1) ? "s" : "",
200                 ctx->fs_sockets_count, (ctx->fs_sockets_count != 1) ? "s" : "",
201                 ctx->fs_total_count - dir_links,
202                 ((ctx->fs_total_count - dir_links) != 1) ? "s" : "");
203 #endif
204 }
205
206 static void check_mount(e2fsck_t ctx)
207 {
208         errcode_t       retval;
209         int             cont;
210
211         retval = ext2fs_check_if_mounted(ctx->filesystem_name,
212                                          &ctx->mount_flags);
213         if (retval) {
214                 com_err("ext2fs_check_if_mount", retval,
215                         _("while determining whether %s is mounted."),
216                         ctx->filesystem_name);
217                 return;
218         }
219
220         /*
221          * If the filesystem isn't mounted, or it's the root filesystem
222          * and it's mounted read-only, then everything's fine.
223          */
224         if ((!(ctx->mount_flags & EXT2_MF_MOUNTED)) ||
225             ((ctx->mount_flags & EXT2_MF_ISROOT) &&
226              (ctx->mount_flags & EXT2_MF_READONLY)))
227                 return;
228
229         if (ctx->options & E2F_OPT_READONLY) {
230                 printf(_("Warning!  %s is mounted.\n"), ctx->filesystem_name);
231                 return;
232         }
233
234         printf(_("%s is mounted.  "), ctx->filesystem_name);
235         if (!isatty(0) || !isatty(1))
236                 fatal_error(ctx, _("Cannot continue, aborting.\n\n"));
237         printf(_("\n\n\007\007\007\007WARNING!!!  "
238                "Running e2fsck on a mounted filesystem may cause\n"
239                "SEVERE filesystem damage.\007\007\007\n\n"));
240         cont = ask_yn(_("Do you really want to continue"), -1);
241         if (!cont) {
242                 printf (_("check aborted.\n"));
243                 exit (0);
244         }
245         return;
246 }
247
248 /*
249  * This routine checks to see if a filesystem can be skipped; if so,
250  * it will exit with E2FSCK_OK.  Under some conditions it will print a
251  * message explaining why a check is being forced.
252  */
253 static void check_if_skip(e2fsck_t ctx)
254 {
255         ext2_filsys fs = ctx->fs;
256         const char *reason = NULL;
257         unsigned int reason_arg = 0;
258         
259         if ((ctx->options & E2F_OPT_FORCE) || bad_blocks_file ||
260             cflag || swapfs)
261                 return;
262         
263         if (fs->super->s_state & EXT2_ERROR_FS)
264                 reason = _(" contains a file system with errors");
265         else if ((fs->super->s_state & EXT2_VALID_FS) == 0)
266                 reason = _(" was not cleanly unmounted");
267         else if ((fs->super->s_max_mnt_count > 0) &&
268                  (fs->super->s_mnt_count >=
269                   (unsigned) fs->super->s_max_mnt_count)) {
270                 reason = _(" has been mounted %u times without being checked");
271                 reason_arg = fs->super->s_mnt_count;
272         } else if (fs->super->s_checkinterval &&
273                  time(0) >= (fs->super->s_lastcheck +
274                              fs->super->s_checkinterval)) {
275                 reason = _(" has gone %u days without being checked");
276                 reason_arg = (time(0) - fs->super->s_lastcheck)/(3600*24);
277         }
278         if (reason) {
279                 fputs(ctx->device_name, stdout);
280                 printf(reason, reason_arg);
281                 fputs(_(", check forced.\n"), stdout);
282                 return;
283         }
284         printf(_("%s: clean, %d/%d files, %d/%d blocks\n"), ctx->device_name,
285                fs->super->s_inodes_count - fs->super->s_free_inodes_count,
286                fs->super->s_inodes_count,
287                fs->super->s_blocks_count - fs->super->s_free_blocks_count,
288                fs->super->s_blocks_count);
289         ext2fs_close(fs);
290         ctx->fs = NULL;
291         e2fsck_free_context(ctx);
292         exit(FSCK_OK);
293 }
294
295 /*
296  * For completion notice
297  */
298 struct percent_tbl {
299         int     max_pass;
300         int     table[32];
301 };
302 struct percent_tbl e2fsck_tbl = {
303         5, { 0, 70, 90, 92,  95, 100 }
304 };
305 static char bar[] =
306         "==============================================================="
307         "===============================================================";
308 static char spaces[] =
309         "                                                               "
310         "                                                               ";
311
312 static float calc_percent(struct percent_tbl *tbl, int pass, int curr,
313                           int max)
314 {
315         float   percent;
316         
317         if (pass <= 0)
318                 return 0.0;
319         if (pass > tbl->max_pass || max == 0)
320                 return 100.0;
321         percent = ((float) curr) / ((float) max);
322         return ((percent * (tbl->table[pass] - tbl->table[pass-1]))
323                 + tbl->table[pass-1]);
324 }
325
326 extern void e2fsck_clear_progbar(e2fsck_t ctx)
327 {
328         if (!(ctx->flags & E2F_FLAG_PROG_BAR))
329                 return;
330         
331         printf("\001%s\r\002", spaces + (sizeof(spaces) - 80));
332         fflush(stdout);
333         ctx->flags &= ~E2F_FLAG_PROG_BAR;
334 }
335
336 int e2fsck_simple_progress(e2fsck_t ctx, const char *label, float percent,
337                            unsigned int dpynum)
338 {
339         static const char spinner[] = "\\|/-";
340         int     i;
341         int     tick;
342         struct timeval  tv;
343         int dpywidth;
344
345         if (ctx->flags & E2F_FLAG_PROG_SUPPRESS)
346                 return 0;
347
348         /*
349          * Calculate the new progress position.  If the
350          * percentage hasn't changed, then we skip out right
351          * away. 
352          */
353         if (ctx->progress_last_percent == (int) 10 * percent)
354                 return 0;
355         ctx->progress_last_percent = (int) 10 * percent;
356
357         /*
358          * If we've already updated the spinner once within
359          * the last 1/8th of a second, no point doing it
360          * again.
361          */
362         gettimeofday(&tv, NULL);
363         tick = (tv.tv_sec << 3) + (tv.tv_usec / (1000000 / 8));
364         if ((tick == ctx->progress_last_time) &&
365             (percent != 0.0) && (percent != 100.0))
366                 return 0;
367         ctx->progress_last_time = tick;
368
369         /*
370          * Advance the spinner, and note that the progress bar
371          * will be on the screen
372          */
373         ctx->progress_pos = (ctx->progress_pos+1) & 3;
374         ctx->flags |= E2F_FLAG_PROG_BAR;
375
376         dpywidth = 66 - strlen(label);
377         dpywidth = 8 * (dpywidth / 8);
378         if (dpynum)
379                 dpywidth -= 8;
380
381         i = ((percent * dpywidth) + 50) / 100;
382         printf("\001%s: |%s%s", label, bar + (sizeof(bar) - (i+1)),
383                spaces + (sizeof(spaces) - (dpywidth - i + 1)));
384         if (percent == 100.0)
385                 fputc('|', stdout);
386         else
387                 fputc(spinner[ctx->progress_pos & 3], stdout);
388         if (dpynum)
389                 printf(" %4.1f%%  %u\r\002", percent, dpynum);
390         else
391                 printf(" %4.1f%%   \r\002", percent);
392         
393         if (percent == 100.0)
394                 e2fsck_clear_progbar(ctx);
395         fflush(stdout);
396
397         return 0;
398 }
399
400 static int e2fsck_update_progress(e2fsck_t ctx, int pass,
401                                   unsigned long cur, unsigned long max)
402 {
403         char buf[80];
404         float percent;
405
406         if (pass == 0)
407                 return 0;
408         
409         if (ctx->progress_fd) {
410                 sprintf(buf, "%d %lu %lu\n", pass, cur, max);
411                 write(ctx->progress_fd, buf, strlen(buf));
412         } else {
413                 percent = calc_percent(&e2fsck_tbl, pass, cur, max);
414                 e2fsck_simple_progress(ctx, ctx->device_name,
415                                        percent, 0);
416         }
417         return 0;
418 }
419
420 #define PATH_SET "PATH=/sbin"
421
422 static void reserve_stdio_fds(void)
423 {
424         int     fd;
425
426         while (1) {
427                 fd = open("/dev/null", O_RDWR);
428                 if (fd > 2)
429                         break;
430                 if (fd < 0) {
431                         fprintf(stderr, _("ERROR: Couldn't open "
432                                 "/dev/null (%s)\n"),
433                                 strerror(errno));
434                         break;
435                 }
436         }
437         close(fd);
438 }
439
440 #ifdef HAVE_SIGNAL_H
441 static void signal_progress_on(int sig)
442 {
443         e2fsck_t ctx = e2fsck_global_ctx;
444
445         if (!ctx)
446                 return;
447
448         ctx->progress = e2fsck_update_progress;
449         ctx->progress_fd = 0;
450 }
451
452 static void signal_progress_off(int sig)
453 {
454         e2fsck_t ctx = e2fsck_global_ctx;
455
456         if (!ctx)
457                 return;
458
459         e2fsck_clear_progbar(ctx);
460         ctx->progress = 0;
461 }
462
463 static void signal_cancel(int sig)
464 {
465         e2fsck_t ctx = e2fsck_global_ctx;
466
467         if (!ctx)
468                 exit(FSCK_CANCELED);
469
470         ctx->flags |= E2F_FLAG_CANCEL;
471 }
472 #endif
473
474 static void parse_extended_opts(e2fsck_t ctx, const char *opts)
475 {
476         char    *buf, *token, *next, *p, *arg;
477         int     ea_ver;
478         int     extended_usage = 0;
479
480         buf = string_copy(ctx, opts, 0);
481         for (token = buf; token && *token; token = next) {
482                 p = strchr(token, ',');
483                 next = 0;
484                 if (p) {
485                         *p = 0;
486                         next = p+1;
487                 } 
488                 arg = strchr(token, '=');
489                 if (arg) {
490                         *arg = 0;
491                         arg++;
492                 }
493                 if (strcmp(token, "ea_ver") == 0) {
494                         if (!arg) {
495                                 extended_usage++;
496                                 continue;
497                         }
498                         ea_ver = strtoul(arg, &p, 0);
499                         if (*p ||
500                             ((ea_ver != 1) && (ea_ver != 2))) {
501                                 fprintf(stderr,
502                                         _("Invalid EA version.\n"));
503                                 extended_usage++;
504                                 continue;
505                         }
506                         ctx->ext_attr_ver = ea_ver;
507                 } else
508                         extended_usage++;
509         }
510         if (extended_usage) {
511                 fprintf(stderr, _("Extended options are separated by commas, "
512                         "and may take an argument which\n"
513                         "is set off by an equals ('=') sign.  "
514                         "Valid raid options are:\n"
515                         "\tea_ver=<ea_version (1 or 2)\n\n"));
516                 exit(1);
517         }
518 }       
519
520
521 static errcode_t PRS(int argc, char *argv[], e2fsck_t *ret_ctx)
522 {
523         int             flush = 0;
524         int             c, fd;
525 #ifdef MTRACE
526         extern void     *mallwatch;
527 #endif
528         e2fsck_t        ctx;
529         errcode_t       retval;
530 #ifdef HAVE_SIGNAL_H
531         struct sigaction        sa;
532 #endif
533         char            *extended_opts = 0;
534
535         retval = e2fsck_allocate_context(&ctx);
536         if (retval)
537                 return retval;
538
539         *ret_ctx = ctx;
540
541         setvbuf(stdout, NULL, _IONBF, BUFSIZ);
542         setvbuf(stderr, NULL, _IONBF, BUFSIZ);
543         initialize_ext2_error_table();
544         blkid_get_cache(&ctx->blkid, NULL);
545         
546         if (argc && *argv)
547                 ctx->program_name = *argv;
548         else
549                 ctx->program_name = "e2fsck";
550         while ((c = getopt (argc, argv, "panyrcC:B:dE:fvtFVM:b:I:j:P:l:L:N:SsD")) != EOF)
551                 switch (c) {
552                 case 'C':
553                         ctx->progress = e2fsck_update_progress;
554                         ctx->progress_fd = atoi(optarg);
555                         if (!ctx->progress_fd)
556                                 break;
557                         /* Validate the file descriptor to avoid disasters */
558                         fd = dup(ctx->progress_fd);
559                         if (fd < 0) {
560                                 fprintf(stderr,
561                                 _("Error validating file descriptor %d: %s\n"),
562                                         ctx->progress_fd,
563                                         error_message(errno));
564                                 fatal_error(ctx,
565                         _("Invalid completion information file descriptor"));
566                         } else
567                                 close(fd);
568                         break;
569                 case 'D':
570                         ctx->options |= E2F_OPT_COMPRESS_DIRS;
571                         break;
572                 case 'E':
573                         extended_opts = optarg;
574                         break;
575                 case 'p':
576                 case 'a':
577                         if (ctx->options & (E2F_OPT_YES|E2F_OPT_NO)) {
578                         conflict_opt:
579                                 fatal_error(ctx, 
580         _("Only one the options -p/-a, -n or -y may be specified."));
581                         }
582                         ctx->options |= E2F_OPT_PREEN;
583                         break;
584                 case 'n':
585                         if (ctx->options & (E2F_OPT_YES|E2F_OPT_PREEN))
586                                 goto conflict_opt;
587                         ctx->options |= E2F_OPT_NO;
588                         break;
589                 case 'y':
590                         if (ctx->options & (E2F_OPT_PREEN|E2F_OPT_NO))
591                                 goto conflict_opt;
592                         ctx->options |= E2F_OPT_YES;
593                         break;
594                 case 't':
595 #ifdef RESOURCE_TRACK
596                         if (ctx->options & E2F_OPT_TIME)
597                                 ctx->options |= E2F_OPT_TIME2;
598                         else
599                                 ctx->options |= E2F_OPT_TIME;
600 #else
601                         fprintf(stderr, _("The -t option is not "
602                                 "supported on this version of e2fsck.\n"));
603 #endif
604                         break;
605                 case 'c':
606                         if (cflag++)
607                                 ctx->options |= E2F_OPT_WRITECHECK;
608                         ctx->options |= E2F_OPT_CHECKBLOCKS;
609                         break;
610                 case 'r':
611                         /* What we do by default, anyway! */
612                         break;
613                 case 'b':
614                         ctx->use_superblock = atoi(optarg);
615                         ctx->flags |= E2F_FLAG_SB_SPECIFIED;
616                         break;
617                 case 'B':
618                         ctx->blocksize = atoi(optarg);
619                         break;
620                 case 'I':
621                         ctx->inode_buffer_blocks = atoi(optarg);
622                         break;
623                 case 'j':
624                         ctx->journal_name = string_copy(ctx, optarg, 0);
625                         break;
626                 case 'P':
627                         ctx->process_inode_size = atoi(optarg);
628                         break;
629                 case 'L':
630                         replace_bad_blocks++;
631                 case 'l':
632                         bad_blocks_file = string_copy(ctx, optarg, 0);
633                         break;
634                 case 'd':
635                         ctx->options |= E2F_OPT_DEBUG;
636                         break;
637                 case 'f':
638                         ctx->options |= E2F_OPT_FORCE;
639                         break;
640                 case 'F':
641                         flush = 1;
642                         break;
643                 case 'v':
644                         verbose = 1;
645                         break;
646                 case 'V':
647                         show_version_only = 1;
648                         break;
649 #ifdef MTRACE
650                 case 'M':
651                         mallwatch = (void *) strtol(optarg, NULL, 0);
652                         break;
653 #endif
654                 case 'N':
655                         ctx->device_name = optarg;
656                         break;
657 #ifdef ENABLE_SWAPFS
658                 case 's':
659                         normalize_swapfs = 1;
660                 case 'S':
661                         swapfs = 1;
662                         break;
663 #else
664                 case 's':
665                 case 'S':
666                         fprintf(stderr, _("Byte-swapping filesystems "
667                                           "not compiled in this version "
668                                           "of e2fsck\n"));
669                         exit(1);
670 #endif
671                 default:
672                         usage(ctx);
673                 }
674         if (show_version_only)
675                 return 0;
676         if (optind != argc - 1)
677                 usage(ctx);
678         if ((ctx->options & E2F_OPT_NO) && !bad_blocks_file &&
679             !cflag && !swapfs && !(ctx->options & E2F_OPT_COMPRESS_DIRS))
680                 ctx->options |= E2F_OPT_READONLY;
681         ctx->filesystem_name = blkid_get_devname(ctx->blkid, argv[optind], 0);
682         if (extended_opts)
683                 parse_extended_opts(ctx, extended_opts);
684         
685         if (flush) {
686                 fd = open(ctx->filesystem_name, O_RDONLY, 0);
687                 if (fd < 0) {
688                         com_err("open", errno,
689                                 _("while opening %s for flushing"),
690                                 ctx->filesystem_name);
691                         fatal_error(ctx, 0);
692                 }
693                 if ((retval = ext2fs_sync_device(fd, 1))) {
694                         com_err("ext2fs_sync_device", retval,
695                                 _("while trying to flush %s"),
696                                 ctx->filesystem_name);
697                         fatal_error(ctx, 0);
698                 }
699                 close(fd);
700         }
701 #ifdef ENABLE_SWAPFS
702         if (swapfs) {
703                 if (cflag || bad_blocks_file) {
704                         fprintf(stderr, _("Incompatible options not "
705                                           "allowed when byte-swapping.\n"));
706                         exit(FSCK_USAGE);
707                 }
708         }
709 #endif
710         if (cflag && bad_blocks_file) {
711                 fprintf(stderr, _("The -c and the -l/-L options may "
712                                   "not be both used at the same time.\n"));
713                 exit(FSCK_USAGE);
714         }
715 #ifdef HAVE_SIGNAL_H
716         /*
717          * Set up signal action
718          */
719         memset(&sa, 0, sizeof(struct sigaction));
720         sa.sa_handler = signal_cancel;
721         sigaction(SIGINT, &sa, 0);
722         sigaction(SIGTERM, &sa, 0);
723 #ifdef SA_RESTART
724         sa.sa_flags = SA_RESTART;
725 #endif
726         e2fsck_global_ctx = ctx;
727         sa.sa_handler = signal_progress_on;
728         sigaction(SIGUSR1, &sa, 0);
729         sa.sa_handler = signal_progress_off;
730         sigaction(SIGUSR2, &sa, 0);
731 #endif
732
733         /* Update our PATH to include /sbin if we need to run badblocks  */
734         if (cflag) {
735                 char *oldpath = getenv("PATH");
736                 if (oldpath) {
737                         char *newpath;
738
739                         newpath = (char *) malloc(sizeof (PATH_SET) + 1 +
740                                                   strlen (oldpath));
741                         if (!newpath)
742                                 fatal_error(ctx, "Couldn't malloc() newpath");
743                         strcpy (newpath, PATH_SET);
744                         strcat (newpath, ":");
745                         strcat (newpath, oldpath);
746                         putenv (newpath);
747                 } else
748                         putenv (PATH_SET);
749         }
750 #ifdef CONFIG_JBD_DEBUG
751         if (getenv("E2FSCK_JBD_DEBUG"))
752                 journal_enable_debug = atoi(getenv("E2FSCK_JBD_DEBUG"));
753 #endif
754         return 0;
755 }
756
757 static const char *my_ver_string = E2FSPROGS_VERSION;
758 static const char *my_ver_date = E2FSPROGS_DATE;
759                                         
760 int main (int argc, char *argv[])
761 {
762         errcode_t       retval = 0;
763         int             exit_value = FSCK_OK;
764         ext2_filsys     fs = 0;
765         io_manager      io_ptr;
766         struct ext2_super_block *sb;
767         const char      *lib_ver_date;
768         int             my_ver, lib_ver;
769         e2fsck_t        ctx;
770         struct problem_context pctx;
771         int flags, run_result;
772         
773         clear_problem_context(&pctx);
774 #ifdef MTRACE
775         mtrace();
776 #endif
777 #ifdef MCHECK
778         mcheck(0);
779 #endif
780 #ifdef ENABLE_NLS
781         setlocale(LC_MESSAGES, "");
782         setlocale(LC_CTYPE, "");
783         bindtextdomain(NLS_CAT_NAME, LOCALEDIR);
784         textdomain(NLS_CAT_NAME);
785 #endif
786         my_ver = ext2fs_parse_version_string(my_ver_string);
787         lib_ver = ext2fs_get_library_version(0, &lib_ver_date);
788         if (my_ver > lib_ver) {
789                 fprintf( stderr, _("Error: ext2fs library version "
790                         "out of date!\n"));
791                 show_version_only++;
792         }
793         
794         retval = PRS(argc, argv, &ctx);
795         if (retval) {
796                 com_err("e2fsck", retval,
797                         _("while trying to initialize program"));
798                 exit(FSCK_ERROR);
799         }
800         reserve_stdio_fds();
801         
802 #ifdef RESOURCE_TRACK
803         init_resource_track(&ctx->global_rtrack);
804 #endif
805
806         if (!(ctx->options & E2F_OPT_PREEN) || show_version_only)
807                 fprintf(stderr, "e2fsck %s (%s)\n", my_ver_string,
808                          my_ver_date);
809
810         if (show_version_only) {
811                 fprintf(stderr, _("\tUsing %s, %s\n"),
812                         error_message(EXT2_ET_BASE), lib_ver_date);
813                 exit(FSCK_OK);
814         }
815         
816         check_mount(ctx);
817         
818         if (!(ctx->options & E2F_OPT_PREEN) &&
819             !(ctx->options & E2F_OPT_NO) &&
820             !(ctx->options & E2F_OPT_YES)) {
821                 if (!isatty (0) || !isatty (1))
822                         fatal_error(ctx,
823                                     _("need terminal for interactive repairs"));
824         }
825         ctx->superblock = ctx->use_superblock;
826 restart:
827 #if 1
828         io_ptr = unix_io_manager;
829 #else
830         io_ptr = test_io_manager;
831         test_io_backing_manager = unix_io_manager;
832 #endif
833         flags = 0;
834         if ((ctx->options & E2F_OPT_READONLY) == 0)
835                 flags |= EXT2_FLAG_RW;
836
837         if (ctx->superblock && ctx->blocksize) {
838                 retval = ext2fs_open(ctx->filesystem_name, flags,
839                                      ctx->superblock, ctx->blocksize,
840                                      io_ptr, &fs);
841         } else if (ctx->superblock) {
842                 int blocksize;
843                 for (blocksize = EXT2_MIN_BLOCK_SIZE;
844                      blocksize <= EXT2_MAX_BLOCK_SIZE; blocksize *= 2) {
845                         retval = ext2fs_open(ctx->filesystem_name, flags,
846                                              ctx->superblock, blocksize,
847                                              io_ptr, &fs);
848                         if (!retval)
849                                 break;
850                 }
851         } else 
852                 retval = ext2fs_open(ctx->filesystem_name, flags, 
853                                      0, 0, io_ptr, &fs);
854         if (!ctx->superblock && !(ctx->options & E2F_OPT_PREEN) &&
855             !(ctx->flags & E2F_FLAG_SB_SPECIFIED) &&
856             ((retval == EXT2_ET_BAD_MAGIC) ||
857              ((retval == 0) && ext2fs_check_desc(fs)))) {
858                 if (!fs || (fs->group_desc_count > 1)) {
859                         printf(_("%s trying backup blocks...\n"),
860                                retval ? _("Couldn't find ext2 superblock,") :
861                                _("Group descriptors look bad..."));
862                         get_backup_sb(ctx, fs, ctx->filesystem_name, io_ptr);
863                         if (fs)
864                                 ext2fs_close(fs);
865                         goto restart;
866                 }
867         }
868         if (retval) {
869                 com_err(ctx->program_name, retval, _("while trying to open %s"),
870                         ctx->filesystem_name);
871                 if (retval == EXT2_ET_REV_TOO_HIGH) {
872                         printf(_("The filesystem revision is apparently "
873                                "too high for this version of e2fsck.\n"
874                                "(Or the filesystem superblock "
875                                "is corrupt)\n\n"));
876                         fix_problem(ctx, PR_0_SB_CORRUPT, &pctx);
877                 } else if (retval == EXT2_ET_SHORT_READ)
878                         printf(_("Could this be a zero-length partition?\n"));
879                 else if ((retval == EPERM) || (retval == EACCES))
880                         printf(_("You must have %s access to the "
881                                "filesystem or be root\n"),
882                                (ctx->options & E2F_OPT_READONLY) ?
883                                "r/o" : "r/w");
884                 else if (retval == ENXIO)
885                         printf(_("Possibly non-existent or swap device?\n"));
886 #ifdef EROFS
887                 else if (retval == EROFS)
888                         printf(_("Disk write-protected; use the -n option "
889                                "to do a read-only\n"
890                                "check of the device.\n"));
891 #endif
892                 else
893                         fix_problem(ctx, PR_0_SB_CORRUPT, &pctx);
894                 fatal_error(ctx, 0);
895         }
896         ctx->fs = fs;
897         fs->priv_data = ctx;
898         sb = fs->super;
899         if (sb->s_rev_level > E2FSCK_CURRENT_REV) {
900                 com_err(ctx->program_name, EXT2_ET_REV_TOO_HIGH,
901                         _("while trying to open %s"),
902                         ctx->filesystem_name);
903         get_newer:
904                 fatal_error(ctx, _("Get a newer version of e2fsck!"));
905         }
906
907         /*
908          * Set the device name, which is used whenever we print error
909          * or informational messages to the user.
910          */
911         if (ctx->device_name == 0 &&
912             (sb->s_volume_name[0] != 0)) {
913                 ctx->device_name = string_copy(ctx, sb->s_volume_name,
914                                                sizeof(sb->s_volume_name));
915         }
916         if (ctx->device_name == 0)
917                 ctx->device_name = ctx->filesystem_name;
918
919         /*
920          * Make sure the ext3 superblock fields are consistent.
921          */
922         retval = e2fsck_check_ext3_journal(ctx);
923         if (retval) {
924                 com_err(ctx->program_name, retval,
925                         _("while checking ext3 journal for %s"),
926                         ctx->device_name);
927                 fatal_error(ctx, 0);
928         }
929
930         /*
931          * Check to see if we need to do ext3-style recovery.  If so,
932          * do it, and then restart the fsck.
933          */
934         if (sb->s_feature_incompat & EXT3_FEATURE_INCOMPAT_RECOVER) {
935                 if (ctx->options & E2F_OPT_READONLY) {
936                         printf(_("Warning: skipping journal recovery "
937                                  "because doing a read-only filesystem "
938                                  "check.\n"));
939                         io_channel_flush(ctx->fs->io);
940                 } else {
941                         if (ctx->flags & E2F_FLAG_RESTARTED) {
942                                 /*
943                                  * Whoops, we attempted to run the
944                                  * journal twice.  This should never
945                                  * happen, unless the hardware or
946                                  * device driver is being bogus.
947                                  */
948                                 com_err(ctx->program_name, 0,
949                                         _("unable to set superblock flags on %s\n"), ctx->device_name);
950                                 fatal_error(ctx, 0);
951                         }
952                         retval = e2fsck_run_ext3_journal(ctx);
953                         if (retval) {
954                                 com_err(ctx->program_name, retval,
955                                 _("while recovering ext3 journal of %s"),
956                                         ctx->device_name);
957                                 fatal_error(ctx, 0);
958                         }
959                         ext2fs_close(ctx->fs);
960                         ctx->fs = 0;
961                         ctx->flags |= E2F_FLAG_RESTARTED;
962                         goto restart;
963                 }
964         }
965
966         /*
967          * Check for compatibility with the feature sets.  We need to
968          * be more stringent than ext2fs_open().
969          */
970         if ((sb->s_feature_compat & ~EXT2_LIB_FEATURE_COMPAT_SUPP) ||
971             (sb->s_feature_incompat & ~EXT2_LIB_FEATURE_INCOMPAT_SUPP)) {
972                 com_err(ctx->program_name, EXT2_ET_UNSUPP_FEATURE,
973                         "(%s)", ctx->device_name);
974                 goto get_newer;
975         }
976         if (sb->s_feature_ro_compat & ~EXT2_LIB_FEATURE_RO_COMPAT_SUPP) {
977                 com_err(ctx->program_name, EXT2_ET_RO_UNSUPP_FEATURE,
978                         "(%s)", ctx->device_name);
979                 goto get_newer;
980         }
981 #ifdef ENABLE_COMPRESSION
982         if (sb->s_feature_incompat & EXT2_FEATURE_INCOMPAT_COMPRESSION)
983                 com_err(ctx->program_name, 0,
984                         _("Warning: compression support is experimental.\n"));
985 #endif
986 #ifndef ENABLE_HTREE
987         if (sb->s_feature_compat & EXT2_FEATURE_COMPAT_DIR_INDEX) {
988                 com_err(ctx->program_name, 0,
989                         _("E2fsck not compiled with HTREE support,\n\t"
990                           "but filesystem %s has HTREE directories.\n"),
991                         ctx->device_name);
992                 goto get_newer;
993         }
994 #endif
995
996         /*
997          * If the user specified a specific superblock, presumably the
998          * master superblock has been trashed.  So we mark the
999          * superblock as dirty, so it can be written out.
1000          */
1001         if (ctx->superblock &&
1002             !(ctx->options & E2F_OPT_READONLY))
1003                 ext2fs_mark_super_dirty(fs);
1004
1005         /*
1006          * We only update the master superblock because (a) paranoia;
1007          * we don't want to corrupt the backup superblocks, and (b) we
1008          * don't need to update the mount count and last checked
1009          * fields in the backup superblock (the kernel doesn't
1010          * update the backup superblocks anyway).
1011          */
1012         fs->flags |= EXT2_FLAG_MASTER_SB_ONLY;
1013
1014         ehandler_init(fs->io);
1015
1016         if (ctx->superblock)
1017                 set_latch_flags(PR_LATCH_RELOC, PRL_LATCHED, 0);
1018         check_super_block(ctx);
1019         if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1020                 fatal_error(ctx, 0);
1021         check_if_skip(ctx);
1022         if (bad_blocks_file)
1023                 read_bad_blocks_file(ctx, bad_blocks_file, replace_bad_blocks);
1024         else if (cflag)
1025                 test_disk(ctx);
1026         if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1027                 fatal_error(ctx, 0);
1028 #ifdef ENABLE_SWAPFS
1029         if (normalize_swapfs) {
1030                 if ((fs->flags & EXT2_FLAG_SWAP_BYTES) ==
1031                     ext2fs_native_flag()) {
1032                         fprintf(stderr, _("%s: Filesystem byte order "
1033                                 "already normalized.\n"), ctx->device_name);
1034                         fatal_error(ctx, 0);
1035                 }
1036         }
1037         if (swapfs) {
1038                 swap_filesys(ctx);
1039                 if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1040                         fatal_error(ctx, 0);
1041         }
1042 #endif
1043
1044         /*
1045          * Mark the system as valid, 'til proven otherwise
1046          */
1047         ext2fs_mark_valid(fs);
1048
1049         retval = ext2fs_read_bb_inode(fs, &fs->badblocks);
1050         if (retval) {
1051                 com_err(ctx->program_name, retval,
1052                         _("while reading bad blocks inode"));
1053                 preenhalt(ctx);
1054                 printf(_("This doesn't bode well,"
1055                          " but we'll try to go on...\n"));
1056         }
1057
1058         run_result = e2fsck_run(ctx);
1059         e2fsck_clear_progbar(ctx);
1060         if (run_result == E2F_FLAG_RESTART) {
1061                 printf(_("Restarting e2fsck from the beginning...\n"));
1062                 retval = e2fsck_reset_context(ctx);
1063                 if (retval) {
1064                         com_err(ctx->program_name, retval,
1065                                 _("while resetting context"));
1066                         fatal_error(ctx, 0);
1067                 }
1068                 ext2fs_close(fs);
1069                 goto restart;
1070         }
1071         if (run_result & E2F_FLAG_CANCEL) {
1072                 printf(_("%s: e2fsck canceled.\n"), ctx->device_name ?
1073                        ctx->device_name : ctx->filesystem_name);
1074                 exit_value |= FSCK_CANCELED;
1075         }
1076         if (run_result & E2F_FLAG_ABORT)
1077                 fatal_error(ctx, _("aborted"));
1078
1079 #ifdef MTRACE
1080         mtrace_print("Cleanup");
1081 #endif
1082         if (ext2fs_test_changed(fs)) {
1083                 exit_value |= FSCK_NONDESTRUCT;
1084                 if (!(ctx->options & E2F_OPT_PREEN))
1085                     printf(_("\n%s: ***** FILE SYSTEM WAS MODIFIED *****\n"),
1086                                ctx->device_name);
1087                 if (ctx->mount_flags & EXT2_MF_ISROOT) {
1088                         printf(_("%s: ***** REBOOT LINUX *****\n"),
1089                                ctx->device_name);
1090                         exit_value |= FSCK_REBOOT;
1091                 }
1092         }
1093         if (!ext2fs_test_valid(fs)) {
1094                 printf(_("\n%s: ********** WARNING: Filesystem still has "
1095                          "errors **********\n\n"), ctx->device_name);
1096                 exit_value |= FSCK_UNCORRECTED;
1097                 exit_value &= ~FSCK_NONDESTRUCT;
1098         }
1099         if (exit_value & FSCK_CANCELED)
1100                 exit_value &= ~FSCK_NONDESTRUCT;
1101         else {
1102                 show_stats(ctx);
1103                 if (!(ctx->options & E2F_OPT_READONLY)) {
1104                         if (ext2fs_test_valid(fs)) {
1105                                 if (!(sb->s_state & EXT2_VALID_FS))
1106                                         exit_value |= FSCK_NONDESTRUCT;
1107                                 sb->s_state = EXT2_VALID_FS;
1108                         } else
1109                                 sb->s_state &= ~EXT2_VALID_FS;
1110                         sb->s_mnt_count = 0;
1111                         sb->s_lastcheck = time(NULL);
1112                         ext2fs_mark_super_dirty(fs);
1113                 }
1114         }
1115
1116         e2fsck_write_bitmaps(ctx);
1117         
1118         ext2fs_close(fs);
1119         ctx->fs = NULL;
1120         free(ctx->filesystem_name);
1121         free(ctx->journal_name);
1122         e2fsck_free_context(ctx);
1123         
1124 #ifdef RESOURCE_TRACK
1125         if (ctx->options & E2F_OPT_TIME)
1126                 print_resource_track(NULL, &ctx->global_rtrack);
1127 #endif
1128
1129         return exit_value;
1130 }