summaryrefslogtreecommitdiffstats
path: root/disk-utils/fsck.c
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--disk-utils/fsck.c1695
-rw-r--r--disk-utils/fsck.cramfs.8106
-rw-r--r--disk-utils/fsck.cramfs.8.adoc62
-rw-r--r--disk-utils/fsck.cramfs.c733
4 files changed, 2596 insertions, 0 deletions
diff --git a/disk-utils/fsck.c b/disk-utils/fsck.c
new file mode 100644
index 0000000..505952c
--- /dev/null
+++ b/disk-utils/fsck.c
@@ -0,0 +1,1695 @@
+/*
+ * fsck --- A generic, parallelizing front-end for the fsck program.
+ * It will automatically try to run fsck programs in parallel if the
+ * devices are on separate spindles. It is based on the same ideas as
+ * the generic front end for fsck by David Engel and Fred van Kempen,
+ * but it has been completely rewritten from scratch to support
+ * parallel execution.
+ *
+ * Written by Theodore Ts'o, <tytso@mit.edu>
+ *
+ * Miquel van Smoorenburg (miquels@drinkel.ow.org) 20-Oct-1994:
+ * o Changed -t fstype to behave like with mount when -A (all file
+ * systems) or -M (like mount) is specified.
+ * o fsck looks if it can find the fsck.type program to decide
+ * if it should ignore the fs type. This way more fsck programs
+ * can be added without changing this front-end.
+ * o -R flag skip root file system.
+ *
+ * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
+ * 2001, 2002, 2003, 2004, 2005 by Theodore Ts'o.
+ *
+ * Copyright (C) 2009-2014 Karel Zak <kzak@redhat.com>
+ *
+ * This file may be redistributed under the terms of the GNU Public
+ * License.
+ */
+
+#define _XOPEN_SOURCE 600 /* for inclusion of sa_handler in Solaris */
+
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <sys/stat.h>
+#include <sys/file.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <stdio.h>
+#include <ctype.h>
+#include <string.h>
+#include <time.h>
+#include <stdlib.h>
+#include <paths.h>
+#include <unistd.h>
+#include <errno.h>
+#include <signal.h>
+#include <dirent.h>
+#include <sys/resource.h>
+#include <sys/time.h>
+#include <blkid.h>
+#include <libmount.h>
+
+#include "nls.h"
+#include "pathnames.h"
+#include "exitcodes.h"
+#include "c.h"
+#include "fileutils.h"
+#include "monotonic.h"
+#include "strutils.h"
+
+#define XALLOC_EXIT_CODE FSCK_EX_ERROR
+#include "xalloc.h"
+
+#define CLOSE_EXIT_CODE FSCK_EX_ERROR
+#include "closestream.h"
+
+#ifndef DEFAULT_FSTYPE
+# define DEFAULT_FSTYPE "ext2"
+#endif
+
+#define MAX_DEVICES 32
+#define MAX_ARGS 32
+
+#define FSCK_RUNTIME_DIRNAME "/run/fsck"
+
+static const char *ignored_types[] = {
+ "ignore",
+ "iso9660",
+ "sw",
+ NULL
+};
+
+static const char *really_wanted[] = {
+ "minix",
+ "ext2",
+ "ext3",
+ "ext4",
+ "ext4dev",
+ "jfs",
+ "reiserfs"
+};
+
+/*
+ * Internal structure for mount table entries.
+ */
+struct fsck_fs_data
+{
+ const char *device;
+ dev_t disk;
+ unsigned int stacked:1,
+ done:1,
+ eval_device:1;
+};
+
+/*
+ * Structure to allow exit codes to be stored
+ */
+struct fsck_instance {
+ int pid;
+ int flags; /* FLAG_{DONE|PROGRESS} */
+
+ int lock; /* flock()ed lockpath file descriptor or -1 */
+ char *lockpath; /* /run/fsck/<diskname>.lock or NULL */
+
+ int exit_status;
+ struct timeval start_time;
+ struct timeval end_time;
+ char * prog;
+ char * type;
+
+ struct rusage rusage;
+ struct libmnt_fs *fs;
+ struct fsck_instance *next;
+};
+
+#define FLAG_DONE 1
+#define FLAG_PROGRESS 2
+
+/*
+ * Global variables for options
+ */
+static char *devices[MAX_DEVICES];
+static char *args[MAX_ARGS];
+static int num_devices, num_args;
+
+static int lockdisk;
+static int verbose;
+static int doall;
+static int noexecute;
+static int serialize;
+static int skip_root;
+static int ignore_mounted;
+static int notitle;
+static int parallel_root;
+static int progress;
+static int progress_fd;
+static int force_all_parallel;
+static int report_stats;
+static FILE *report_stats_file;
+
+static int num_running;
+static int max_running;
+
+static volatile int cancel_requested;
+static int kill_sent;
+static char *fstype;
+static struct fsck_instance *instance_list;
+
+#define FSCK_DEFAULT_PATH "/sbin"
+static char *fsck_path;
+
+
+/* parsed fstab and mtab */
+static struct libmnt_table *fstab, *mtab;
+static struct libmnt_cache *mntcache;
+
+static int count_slaves(dev_t disk);
+
+static int string_to_int(const char *s)
+{
+ long l;
+ char *p;
+
+ errno = 0;
+ l = strtol(s, &p, 0);
+ if (errno || *p || l == LONG_MIN || l == LONG_MAX || l < 0 || l > INT_MAX)
+ return -1;
+
+ return (int) l;
+}
+
+/* Do we really really want to check this fs? */
+static int fs_check_required(const char *type)
+{
+ size_t i;
+
+ for(i = 0; i < ARRAY_SIZE(really_wanted); i++) {
+ if (strcmp(type, really_wanted[i]) == 0)
+ return 1;
+ }
+
+ return 0;
+}
+
+static int is_mounted(struct libmnt_fs *fs)
+{
+ int rc;
+ const char *src;
+
+ src = mnt_fs_get_source(fs);
+ if (!src)
+ return 0;
+ if (!mntcache)
+ mntcache = mnt_new_cache();
+ if (!mtab) {
+ mtab = mnt_new_table();
+ if (!mtab)
+ err(FSCK_EX_ERROR, ("failed to initialize libmount table"));
+ mnt_table_set_cache(mtab, mntcache);
+ mnt_table_parse_mtab(mtab, NULL);
+ }
+
+ rc = mnt_table_find_source(mtab, src, MNT_ITER_BACKWARD) ? 1 : 0;
+ if (verbose) {
+ if (rc)
+ printf(_("%s is mounted\n"), src);
+ else
+ printf(_("%s is not mounted\n"), src);
+ }
+ return rc;
+}
+
+static int ignore(struct libmnt_fs *);
+
+static struct fsck_fs_data *fs_create_data(struct libmnt_fs *fs)
+{
+ struct fsck_fs_data *data = mnt_fs_get_userdata(fs);
+
+ if (!data) {
+ data = xcalloc(1, sizeof(*data));
+ mnt_fs_set_userdata(fs, data);
+ }
+ return data;
+}
+
+/*
+ * fs from fstab might contains real device name as well as symlink,
+ * LABEL or UUID, this function returns canonicalized result.
+ */
+static const char *fs_get_device(struct libmnt_fs *fs)
+{
+ struct fsck_fs_data *data = mnt_fs_get_userdata(fs);
+
+ if (!data || !data->eval_device) {
+ const char *spec = mnt_fs_get_source(fs);
+
+ if (!data)
+ data = fs_create_data(fs);
+
+ data->eval_device = 1;
+ data->device = mnt_resolve_spec(spec, mnt_table_get_cache(fstab));
+ if (!data->device)
+ data->device = xstrdup(spec);
+ }
+
+ return data->device;
+}
+
+static dev_t fs_get_disk(struct libmnt_fs *fs, int check)
+{
+ struct fsck_fs_data *data;
+ const char *device;
+ struct stat st;
+
+ data = mnt_fs_get_userdata(fs);
+ if (data && data->disk)
+ return data->disk;
+
+ if (!check)
+ return 0;
+
+ if (mnt_fs_is_netfs(fs) || mnt_fs_is_pseudofs(fs))
+ return 0;
+
+ device = fs_get_device(fs);
+ if (!device)
+ return 0;
+
+ data = fs_create_data(fs);
+
+ if (!stat(device, &st) &&
+ !blkid_devno_to_wholedisk(st.st_rdev, NULL, 0, &data->disk)) {
+
+ if (data->disk)
+ data->stacked = count_slaves(data->disk) > 0 ? 1 : 0;
+ return data->disk;
+ }
+ return 0;
+}
+
+static int fs_is_stacked(struct libmnt_fs *fs)
+{
+ struct fsck_fs_data *data = mnt_fs_get_userdata(fs);
+ return data ? data->stacked : 0;
+}
+
+static int fs_is_done(struct libmnt_fs *fs)
+{
+ struct fsck_fs_data *data = mnt_fs_get_userdata(fs);
+ return data ? data->done : 0;
+}
+
+static void fs_set_done(struct libmnt_fs *fs)
+{
+ struct fsck_fs_data *data = fs_create_data(fs);
+
+ if (data)
+ data->done = 1;
+}
+
+static int is_irrotational_disk(dev_t disk)
+{
+ char path[PATH_MAX];
+ FILE *f;
+ int rc, x;
+
+
+ rc = snprintf(path, sizeof(path),
+ "/sys/dev/block/%d:%d/queue/rotational",
+ major(disk), minor(disk));
+
+ if (rc < 0 || (unsigned int) rc >= sizeof(path))
+ return 0;
+
+ f = fopen(path, "r");
+ if (!f)
+ return 0;
+
+ rc = fscanf(f, "%d", &x);
+ if (rc != 1) {
+ if (ferror(f))
+ warn(_("cannot read %s"), path);
+ else
+ warnx(_("parse error: %s"), path);
+ }
+ fclose(f);
+
+ return rc == 1 ? !x : 0;
+}
+
+static void lock_disk(struct fsck_instance *inst)
+{
+ dev_t disk = fs_get_disk(inst->fs, 1);
+ char *diskpath = NULL, *diskname;
+
+ inst->lock = -1;
+
+ if (!disk || is_irrotational_disk(disk))
+ goto done;
+
+ diskpath = blkid_devno_to_devname(disk);
+ if (!diskpath)
+ goto done;
+
+ if (access(FSCK_RUNTIME_DIRNAME, F_OK) != 0) {
+ int rc = mkdir(FSCK_RUNTIME_DIRNAME,
+ S_IWUSR|
+ S_IRUSR|S_IRGRP|S_IROTH|
+ S_IXUSR|S_IXGRP|S_IXOTH);
+ if (rc && errno != EEXIST) {
+ warn(_("cannot create directory %s"),
+ FSCK_RUNTIME_DIRNAME);
+ goto done;
+ }
+ }
+
+ diskname = stripoff_last_component(diskpath);
+ if (!diskname)
+ diskname = diskpath;
+
+ xasprintf(&inst->lockpath, FSCK_RUNTIME_DIRNAME "/%s.lock", diskname);
+
+ if (verbose)
+ printf(_("Locking disk by %s ... "), inst->lockpath);
+
+ inst->lock = open(inst->lockpath, O_RDONLY|O_CREAT|O_CLOEXEC,
+ S_IWUSR|S_IRUSR|S_IRGRP|S_IROTH);
+ if (inst->lock >= 0) {
+ int rc = -1;
+
+ /* inform users that we're waiting on the lock */
+ if (verbose &&
+ (rc = flock(inst->lock, LOCK_EX | LOCK_NB)) != 0 &&
+ errno == EWOULDBLOCK)
+ printf(_("(waiting) "));
+
+ if (rc != 0 && flock(inst->lock, LOCK_EX) != 0) {
+ close(inst->lock); /* failed */
+ inst->lock = -1;
+ }
+ }
+
+ if (verbose)
+ /* TRANSLATORS: These are followups to "Locking disk...". */
+ printf("%s.\n", inst->lock >= 0 ? _("succeeded") : _("failed"));
+
+
+done:
+ if (inst->lock < 0) {
+ free(inst->lockpath);
+ inst->lockpath = NULL;
+ }
+ free(diskpath);
+}
+
+static void unlock_disk(struct fsck_instance *inst)
+{
+ if (inst->lock < 0)
+ return;
+
+ if (verbose)
+ printf(_("Unlocking %s.\n"), inst->lockpath);
+
+ close(inst->lock); /* unlock */
+
+ free(inst->lockpath);
+
+ inst->lock = -1;
+ inst->lockpath = NULL;
+}
+
+static void free_instance(struct fsck_instance *i)
+{
+ if (lockdisk)
+ unlock_disk(i);
+ free(i->prog);
+ free(i->lockpath);
+ mnt_unref_fs(i->fs);
+ free(i);
+}
+
+static struct libmnt_fs *add_dummy_fs(const char *device)
+{
+ struct libmnt_fs *fs = mnt_new_fs();
+
+ if (fs && mnt_fs_set_source(fs, device) == 0 &&
+ mnt_table_add_fs(fstab, fs) == 0) {
+ mnt_unref_fs(fs);
+ return fs;
+ }
+
+ mnt_unref_fs(fs);
+ err(FSCK_EX_ERROR, _("failed to setup description for %s"), device);
+}
+
+static void fs_interpret_type(struct libmnt_fs *fs)
+{
+ const char *device;
+ const char *type = mnt_fs_get_fstype(fs);
+
+ if (type && strcmp(type, "auto") != 0)
+ return;
+
+ mnt_fs_set_fstype(fs, NULL);
+
+ device = fs_get_device(fs);
+ if (device) {
+ int ambi = 0;
+ char *tp;
+ struct libmnt_cache *cache = mnt_table_get_cache(fstab);
+
+ tp = mnt_get_fstype(device, &ambi, cache);
+ if (!ambi)
+ mnt_fs_set_fstype(fs, tp);
+ if (!cache)
+ free(tp);
+ }
+}
+
+static int parser_errcb(struct libmnt_table *tb __attribute__ ((__unused__)),
+ const char *filename, int line)
+{
+ warnx(_("%s: parse error at line %d -- ignored"), filename, line);
+ return 1;
+}
+
+/*
+ * Load the filesystem database from /etc/fstab
+ */
+static void load_fs_info(void)
+{
+ const char *path;
+
+ fstab = mnt_new_table();
+ if (!fstab)
+ err(FSCK_EX_ERROR, ("failed to initialize libmount table"));
+
+ mnt_table_set_parser_errcb(fstab, parser_errcb);
+ mnt_table_set_cache(fstab, mntcache);
+
+ errno = 0;
+
+ /*
+ * Let's follow libmount defaults if $FSTAB_FILE is not specified
+ */
+ path = getenv("FSTAB_FILE");
+
+ if (mnt_table_parse_fstab(fstab, path)) {
+ if (!path)
+ path = mnt_get_fstab_path();
+
+ /* don't print error when there is no fstab at all */
+ if (access(path, F_OK) == 0) {
+ if (errno)
+ warn(_("%s: failed to parse fstab"), path);
+ else
+ warnx(_("%s: failed to parse fstab"), path);
+ }
+ }
+}
+
+/*
+ * Lookup filesys in /etc/fstab and return the corresponding entry.
+ * The @path has to be real path (no TAG) by mnt_resolve_spec().
+ */
+static struct libmnt_fs *lookup(char *path)
+{
+ struct libmnt_fs *fs;
+
+ if (!path)
+ return NULL;
+
+ fs = mnt_table_find_srcpath(fstab, path, MNT_ITER_FORWARD);
+ if (!fs) {
+ /*
+ * Maybe mountpoint has been specified on fsck command line.
+ * Yeah, crazy feature...
+ *
+ * Note that mnt_table_find_target() may canonicalize paths in
+ * the fstab to support symlinks. This is really unwanted,
+ * because readlink() on mountpoints may trigger automounts.
+ *
+ * So, disable the cache and compare the paths as strings
+ * without care about symlinks...
+ */
+ mnt_table_set_cache(fstab, NULL);
+ fs = mnt_table_find_target(fstab, path, MNT_ITER_FORWARD);
+ mnt_table_set_cache(fstab, mntcache);
+ }
+ return fs;
+}
+
+/* Find fsck program for a given fs type. */
+static int find_fsck(const char *type, char **progpath)
+{
+ char *s;
+ const char *tpl;
+ char *prog = NULL;
+ char *p = xstrdup(fsck_path);
+ int rc;
+
+ /* Are we looking for a program or just a type? */
+ tpl = (strncmp(type, "fsck.", 5) ? "%s/fsck.%s" : "%s/%s");
+
+ for(s = strtok(p, ":"); s; s = strtok(NULL, ":")) {
+ xasprintf(&prog, tpl, s, type);
+ if (access(prog, X_OK) == 0)
+ break;
+ free(prog);
+ prog = NULL;
+ }
+
+ free(p);
+ rc = prog ? 1 : 0;
+
+ if (progpath)
+ *progpath = prog;
+ else
+ free(prog);
+
+ return rc;
+}
+
+static int progress_active(void)
+{
+ struct fsck_instance *inst;
+
+ for (inst = instance_list; inst; inst = inst->next) {
+ if (inst->flags & FLAG_DONE)
+ continue;
+ if (inst->flags & FLAG_PROGRESS)
+ return 1;
+ }
+ return 0;
+}
+
+/*
+ * Process run statistics for finished fsck instances.
+ *
+ * If report_stats is 0, do nothing, otherwise print a selection of
+ * interesting rusage statistics as well as elapsed wallclock time.
+ */
+static void print_stats(struct fsck_instance *inst)
+{
+ struct timeval delta;
+
+ if (!inst || !report_stats || noexecute)
+ return;
+
+ timersub(&inst->end_time, &inst->start_time, &delta);
+
+ if (report_stats_file)
+ fprintf(report_stats_file, "%s %d %ld"
+ " %"PRId64".%06"PRId64
+ " %"PRId64".%06"PRId64
+ " %"PRId64".%06"PRId64"\n",
+ fs_get_device(inst->fs),
+ inst->exit_status,
+ inst->rusage.ru_maxrss,
+ (int64_t)delta.tv_sec, (int64_t)delta.tv_usec,
+ (int64_t)inst->rusage.ru_utime.tv_sec,
+ (int64_t)inst->rusage.ru_utime.tv_usec,
+ (int64_t)inst->rusage.ru_stime.tv_sec,
+ (int64_t)inst->rusage.ru_stime.tv_usec);
+ else
+ fprintf(stdout, "%s: status %d, rss %ld, "
+ "real %"PRId64".%06"PRId64", "
+ "user %"PRId64".%06"PRId64", "
+ "sys %"PRId64".%06"PRId64"\n",
+ fs_get_device(inst->fs),
+ inst->exit_status,
+ inst->rusage.ru_maxrss,
+ (int64_t)delta.tv_sec, (int64_t)delta.tv_usec,
+ (int64_t)inst->rusage.ru_utime.tv_sec,
+ (int64_t)inst->rusage.ru_utime.tv_usec,
+ (int64_t)inst->rusage.ru_stime.tv_sec,
+ (int64_t)inst->rusage.ru_stime.tv_usec);
+}
+
+/*
+ * Execute a particular fsck program, and link it into the list of
+ * child processes we are waiting for.
+ */
+static int execute(const char *progname, const char *progpath,
+ const char *type, struct libmnt_fs *fs, int interactive)
+{
+ char *argv[80];
+ int argc, i;
+ struct fsck_instance *inst, *p;
+ pid_t pid;
+
+ inst = xcalloc(1, sizeof(*inst));
+
+ argv[0] = xstrdup(progname);
+ argc = 1;
+
+ for (i=0; i <num_args; i++)
+ argv[argc++] = xstrdup(args[i]);
+
+ if (progress &&
+ ((strcmp(type, "ext2") == 0) ||
+ (strcmp(type, "ext3") == 0) ||
+ (strcmp(type, "ext4") == 0) ||
+ (strcmp(type, "ext4dev") == 0))) {
+
+ char tmp[80];
+ tmp[0] = 0;
+ if (!progress_active()) {
+ snprintf(tmp, 80, "-C%d", progress_fd);
+ inst->flags |= FLAG_PROGRESS;
+ } else if (progress_fd)
+ snprintf(tmp, 80, "-C%d", progress_fd * -1);
+ if (tmp[0])
+ argv[argc++] = xstrdup(tmp);
+ }
+
+ argv[argc++] = xstrdup(fs_get_device(fs));
+ argv[argc] = NULL;
+
+ if (verbose || noexecute) {
+ const char *tgt = mnt_fs_get_target(fs);
+
+ if (!tgt)
+ tgt = fs_get_device(fs);
+ printf("[%s (%d) -- %s] ", progpath, num_running, tgt);
+ for (i=0; i < argc; i++)
+ printf("%s ", argv[i]);
+ printf("\n");
+ }
+
+ mnt_ref_fs(fs);
+ inst->fs = fs;
+ inst->lock = -1;
+
+ if (lockdisk)
+ lock_disk(inst);
+
+ /* Fork and execute the correct program. */
+ if (noexecute)
+ pid = -1;
+ else if ((pid = fork()) < 0) {
+ warn(_("fork failed"));
+ free_instance(inst);
+ return errno;
+ } else if (pid == 0) {
+ if (!interactive)
+ close(0);
+ execv(progpath, argv);
+ err(FSCK_EX_ERROR, _("%s: execute failed"), progpath);
+ }
+
+ for (i=0; i < argc; i++)
+ free(argv[i]);
+
+ inst->pid = pid;
+ inst->prog = xstrdup(progname);
+ inst->type = xstrdup(type);
+ gettime_monotonic(&inst->start_time);
+ inst->next = NULL;
+
+ /*
+ * Find the end of the list, so we add the instance on at the end.
+ */
+ for (p = instance_list; p && p->next; p = p->next);
+
+ if (p)
+ p->next = inst;
+ else
+ instance_list = inst;
+
+ return 0;
+}
+
+/*
+ * Send a signal to all outstanding fsck child processes
+ */
+static int kill_all(int signum)
+{
+ struct fsck_instance *inst;
+ int n = 0;
+
+ for (inst = instance_list; inst; inst = inst->next) {
+ if (inst->flags & FLAG_DONE)
+ continue;
+ kill(inst->pid, signum);
+ n++;
+ }
+ return n;
+}
+
+/*
+ * Wait for one child process to exit; when it does, unlink it from
+ * the list of executing child processes, and return it.
+ */
+static struct fsck_instance *wait_one(int flags)
+{
+ int status = 0;
+ int sig;
+ struct fsck_instance *inst, *inst2, *prev;
+ pid_t pid;
+ struct rusage rusage;
+
+ if (!instance_list)
+ return NULL;
+
+ if (noexecute) {
+ inst = instance_list;
+ prev = NULL;
+#ifdef RANDOM_DEBUG
+ while (inst->next && (random() & 1)) {
+ prev = inst;
+ inst = inst->next;
+ }
+#endif
+ inst->exit_status = 0;
+ goto ret_inst;
+ }
+
+ /*
+ * gcc -Wall fails saving throw against stupidity
+ * (inst and prev are thought to be uninitialized variables)
+ */
+ inst = prev = NULL;
+
+ do {
+ pid = wait4(-1, &status, flags, &rusage);
+ if (cancel_requested && !kill_sent) {
+ kill_all(SIGTERM);
+ kill_sent++;
+ }
+ if ((pid == 0) && (flags & WNOHANG))
+ return NULL;
+ if (pid < 0) {
+ if ((errno == EINTR) || (errno == EAGAIN))
+ continue;
+ if (errno == ECHILD) {
+ warnx(_("wait: no more child process?!?"));
+ return NULL;
+ }
+ warn(_("waitpid failed"));
+ continue;
+ }
+ for (prev = NULL, inst = instance_list;
+ inst;
+ prev = inst, inst = inst->next) {
+ if (inst->pid == pid)
+ break;
+ }
+ } while (!inst);
+
+ if (WIFEXITED(status))
+ status = WEXITSTATUS(status);
+ else if (WIFSIGNALED(status)) {
+ sig = WTERMSIG(status);
+ if (sig == SIGINT) {
+ status = FSCK_EX_UNCORRECTED;
+ } else {
+ warnx(_("Warning... %s for device %s exited "
+ "with signal %d."),
+ inst->prog, fs_get_device(inst->fs), sig);
+ status = FSCK_EX_ERROR;
+ }
+ } else {
+ warnx(_("%s %s: status is %x, should never happen."),
+ inst->prog, fs_get_device(inst->fs), status);
+ status = FSCK_EX_ERROR;
+ }
+
+ inst->exit_status = status;
+ inst->flags |= FLAG_DONE;
+ gettime_monotonic(&inst->end_time);
+ memcpy(&inst->rusage, &rusage, sizeof(struct rusage));
+
+ if (progress && (inst->flags & FLAG_PROGRESS) &&
+ !progress_active()) {
+ for (inst2 = instance_list; inst2; inst2 = inst2->next) {
+ if (inst2->flags & FLAG_DONE)
+ continue;
+ if (strcmp(inst2->type, "ext2") != 0 &&
+ strcmp(inst2->type, "ext3") &&
+ strcmp(inst2->type, "ext4") != 0 &&
+ strcmp(inst2->type, "ext4dev") != 0)
+ continue;
+ /*
+ * If we've just started the fsck, wait a tiny
+ * bit before sending the kill, to give it
+ * time to set up the signal handler
+ */
+ if (inst2->start_time.tv_sec < time(NULL) + 2) {
+ if (fork() == 0) {
+ sleep(1);
+ kill(inst2->pid, SIGUSR1);
+ exit(FSCK_EX_OK);
+ }
+ } else
+ kill(inst2->pid, SIGUSR1);
+ inst2->flags |= FLAG_PROGRESS;
+ break;
+ }
+ }
+ret_inst:
+ if (prev)
+ prev->next = inst->next;
+ else
+ instance_list = inst->next;
+
+ print_stats(inst);
+
+ if (verbose > 1)
+ printf(_("Finished with %s (exit status %d)\n"),
+ fs_get_device(inst->fs), inst->exit_status);
+ num_running--;
+ return inst;
+}
+
+#define FLAG_WAIT_ALL 0
+#define FLAG_WAIT_ATLEAST_ONE 1
+/*
+ * Wait until all executing child processes have exited; return the
+ * logical OR of all of their exit code values.
+ */
+static int wait_many(int flags)
+{
+ struct fsck_instance *inst;
+ int global_status = 0;
+ int wait_flags = 0;
+
+ while ((inst = wait_one(wait_flags))) {
+ global_status |= inst->exit_status;
+ free_instance(inst);
+#ifdef RANDOM_DEBUG
+ if (noexecute && (flags & WNOHANG) && !(random() % 3))
+ break;
+#endif
+ if (flags & FLAG_WAIT_ATLEAST_ONE)
+ wait_flags = WNOHANG;
+ }
+ return global_status;
+}
+
+/*
+ * Run the fsck program on a particular device
+ *
+ * If the type is specified using -t, and it isn't prefixed with "no"
+ * (as in "noext2") and only one filesystem type is specified, then
+ * use that type regardless of what is specified in /etc/fstab.
+ *
+ * If the type isn't specified by the user, then use either the type
+ * specified in /etc/fstab, or DEFAULT_FSTYPE.
+ */
+static int fsck_device(struct libmnt_fs *fs, int interactive)
+{
+ char *progname, *progpath;
+ const char *type;
+ int retval;
+
+ fs_interpret_type(fs);
+
+ type = mnt_fs_get_fstype(fs);
+
+ if (type && strcmp(type, "auto") != 0)
+ ;
+ else if (fstype && strncmp(fstype, "no", 2) != 0 &&
+ strncmp(fstype, "opts=", 5) != 0 && strncmp(fstype, "loop", 4) != 0 &&
+ !strchr(fstype, ','))
+ type = fstype;
+ else
+ type = DEFAULT_FSTYPE;
+
+ xasprintf(&progname, "fsck.%s", type);
+
+ if (!find_fsck(progname, &progpath)) {
+ free(progname);
+ if (fs_check_required(type)) {
+ retval = ENOENT;
+ goto err;
+ }
+ return 0;
+ }
+
+ num_running++;
+ retval = execute(progname, progpath, type, fs, interactive);
+ free(progname);
+ free(progpath);
+ if (retval) {
+ num_running--;
+ goto err;
+ }
+ return 0;
+err:
+ warnx(_("error %d (%s) while executing fsck.%s for %s"),
+ retval, strerror(errno), type, fs_get_device(fs));
+ return FSCK_EX_ERROR;
+}
+
+
+/*
+ * Deal with the fsck -t argument.
+ */
+static struct fs_type_compile {
+ char **list;
+ int *type;
+ int negate;
+} fs_type_compiled;
+
+#define FS_TYPE_NORMAL 0
+#define FS_TYPE_OPT 1
+#define FS_TYPE_NEGOPT 2
+
+static void compile_fs_type(char *fs_type, struct fs_type_compile *cmp)
+{
+ char *cp, *list, *s;
+ int num = 2;
+ int negate, first_negate = 1;
+
+ if (fs_type) {
+ for (cp=fs_type; *cp; cp++) {
+ if (*cp == ',')
+ num++;
+ }
+ }
+
+ cmp->list = xcalloc(num, sizeof(char *));
+ cmp->type = xcalloc(num, sizeof(int));
+ cmp->negate = 0;
+
+ if (!fs_type)
+ return;
+
+ list = xstrdup(fs_type);
+ num = 0;
+ s = strtok(list, ",");
+ while(s) {
+ negate = 0;
+ if (strncmp(s, "no", 2) == 0) {
+ s += 2;
+ negate = 1;
+ } else if (*s == '!') {
+ s++;
+ negate = 1;
+ }
+ if (strcmp(s, "loop") == 0)
+ /* loop is really short-hand for opts=loop */
+ goto loop_special_case;
+ else if (strncmp(s, "opts=", 5) == 0) {
+ s += 5;
+ loop_special_case:
+ cmp->type[num] = negate ? FS_TYPE_NEGOPT : FS_TYPE_OPT;
+ } else {
+ if (first_negate) {
+ cmp->negate = negate;
+ first_negate = 0;
+ }
+ if ((negate && !cmp->negate) ||
+ (!negate && cmp->negate)) {
+ errx(FSCK_EX_USAGE,
+ _("Either all or none of the filesystem types passed to -t must be prefixed\n"
+ "with 'no' or '!'."));
+ }
+ }
+
+ cmp->list[num++] = xstrdup(s);
+ s = strtok(NULL, ",");
+ }
+ free(list);
+}
+
+/*
+ * This function returns true if a particular option appears in a
+ * comma-delimited options list
+ */
+static int opt_in_list(const char *opt, const char *optlist)
+{
+ char *list, *s;
+
+ if (!optlist)
+ return 0;
+ list = xstrdup(optlist);
+
+ s = strtok(list, ",");
+ while(s) {
+ if (strcmp(s, opt) == 0) {
+ free(list);
+ return 1;
+ }
+ s = strtok(NULL, ",");
+ }
+ free(list);
+ return 0;
+}
+
+/* See if the filesystem matches the criteria given by the -t option */
+static int fs_match(struct libmnt_fs *fs, struct fs_type_compile *cmp)
+{
+ int n, ret = 0, checked_type = 0;
+ char *cp;
+
+ if (cmp->list == NULL || cmp->list[0] == NULL)
+ return 1;
+
+ for (n=0; (cp = cmp->list[n]); n++) {
+ switch (cmp->type[n]) {
+ case FS_TYPE_NORMAL:
+ {
+ const char *type = mnt_fs_get_fstype(fs);
+
+ checked_type++;
+ if (type && strcmp(cp, type) == 0)
+ ret = 1;
+ break;
+ }
+ case FS_TYPE_NEGOPT:
+ if (opt_in_list(cp, mnt_fs_get_options(fs)))
+ return 0;
+ break;
+ case FS_TYPE_OPT:
+ if (!opt_in_list(cp, mnt_fs_get_options(fs)))
+ return 0;
+ break;
+ }
+ }
+ if (checked_type == 0)
+ return 1;
+ return (cmp->negate ? !ret : ret);
+}
+
+/*
+ * Check if a device exists
+ */
+static int device_exists(const char *device)
+{
+ struct stat st;
+
+ if (stat(device, &st) == -1)
+ return 0;
+ if (!S_ISBLK(st.st_mode))
+ return 0;
+ return 1;
+}
+
+static int fs_ignored_type(struct libmnt_fs *fs)
+{
+ const char **ip, *type;
+
+ if (!mnt_fs_is_regularfs(fs))
+ return 1;
+
+ type = mnt_fs_get_fstype(fs);
+
+ for(ip = ignored_types; type && *ip; ip++) {
+ if (strcmp(type, *ip) == 0)
+ return 1;
+ }
+
+ return 0;
+}
+
+/* Check if we should ignore this filesystem. */
+static int ignore(struct libmnt_fs *fs)
+{
+ const char *type;
+
+ /*
+ * If the pass number is 0, ignore it.
+ */
+ if (mnt_fs_get_passno(fs) == 0)
+ return 1;
+
+ /*
+ * If this is a bind mount, ignore it.
+ */
+ if (opt_in_list("bind", mnt_fs_get_options(fs))) {
+ warnx(_("%s: skipping bad line in /etc/fstab: "
+ "bind mount with nonzero fsck pass number"),
+ mnt_fs_get_target(fs));
+ return 1;
+ }
+
+ /*
+ * ignore devices that don't exist and have the "nofail" mount option
+ */
+ if (!device_exists(fs_get_device(fs))) {
+ if (opt_in_list("nofail", mnt_fs_get_options(fs))) {
+ if (verbose)
+ printf(_("%s: skipping nonexistent device\n"),
+ fs_get_device(fs));
+ return 1;
+ }
+ if (verbose)
+ printf(_("%s: nonexistent device (\"nofail\" fstab "
+ "option may be used to skip this device)\n"),
+ fs_get_device(fs));
+ }
+
+ fs_interpret_type(fs);
+
+ /*
+ * If a specific fstype is specified, and it doesn't match,
+ * ignore it.
+ */
+ if (!fs_match(fs, &fs_type_compiled))
+ return 1;
+
+ type = mnt_fs_get_fstype(fs);
+ if (!type) {
+ if (verbose)
+ printf(_("%s: skipping unknown filesystem type\n"),
+ fs_get_device(fs));
+ return 1;
+ }
+
+ /* Are we ignoring this type? */
+ if (fs_ignored_type(fs))
+ return 1;
+
+
+
+ /* See if the <fsck.fs> program is available. */
+ if (!find_fsck(type, NULL)) {
+ if (fs_check_required(type))
+ warnx(_("cannot check %s: fsck.%s not found"),
+ fs_get_device(fs), type);
+ return 1;
+ }
+
+ /* We can and want to check this file system type. */
+ return 0;
+}
+
+static int count_slaves(dev_t disk)
+{
+ DIR *dir;
+ struct dirent *dp;
+ char dirname[PATH_MAX];
+ int count = 0;
+
+ snprintf(dirname, sizeof(dirname),
+ "/sys/dev/block/%u:%u/slaves/",
+ major(disk), minor(disk));
+
+ if (!(dir = opendir(dirname)))
+ return -1;
+
+ while ((dp = readdir(dir)) != NULL) {
+#ifdef _DIRENT_HAVE_D_TYPE
+ if (dp->d_type != DT_UNKNOWN && dp->d_type != DT_LNK)
+ continue;
+#endif
+ if (dp->d_name[0] == '.' &&
+ ((dp->d_name[1] == 0) ||
+ ((dp->d_name[1] == '.') && (dp->d_name[2] == 0))))
+ continue;
+
+ count++;
+ }
+
+ closedir(dir);
+ return count;
+}
+
+/*
+ * Returns TRUE if a partition on the same disk is already being
+ * checked.
+ */
+static int disk_already_active(struct libmnt_fs *fs)
+{
+ struct fsck_instance *inst;
+ dev_t disk;
+
+ if (force_all_parallel)
+ return 0;
+
+ if (instance_list && fs_is_stacked(instance_list->fs))
+ /* any instance for a stacked device is already running */
+ return 1;
+
+ disk = fs_get_disk(fs, 1);
+
+ /*
+ * If we don't know the base device, assume that the device is
+ * already active if there are any fsck instances running.
+ *
+ * Don't check a stacked device with any other disk too.
+ */
+ if (!disk || fs_is_stacked(fs))
+ return (instance_list != NULL);
+
+ for (inst = instance_list; inst; inst = inst->next) {
+ dev_t idisk = fs_get_disk(inst->fs, 0);
+
+ if (!idisk || disk == idisk)
+ return 1;
+ }
+
+ return 0;
+}
+
+/* Check all file systems, using the /etc/fstab table. */
+static int check_all(void)
+{
+ int not_done_yet = 1;
+ int passno = 1;
+ int pass_done;
+ int status = FSCK_EX_OK;
+
+ struct libmnt_fs *fs;
+ struct libmnt_iter *itr = mnt_new_iter(MNT_ITER_FORWARD);
+
+ if (!itr)
+ err(FSCK_EX_ERROR, _("failed to allocate iterator"));
+
+ /*
+ * Do an initial scan over the filesystem; mark filesystems
+ * which should be ignored as done, and resolve any "auto"
+ * filesystem types (done as a side-effect of calling ignore()).
+ */
+ while (mnt_table_next_fs(fstab, itr, &fs) == 0) {
+ if (ignore(fs)) {
+ fs_set_done(fs);
+ continue;
+ }
+ }
+
+ if (verbose)
+ fputs(_("Checking all file systems.\n"), stdout);
+
+ /*
+ * Find and check the root filesystem.
+ */
+ if (!parallel_root) {
+ fs = mnt_table_find_target(fstab, "/", MNT_ITER_FORWARD);
+ if (fs) {
+ if (!skip_root &&
+ !fs_is_done(fs) &&
+ !(ignore_mounted && is_mounted(fs))) {
+ status |= fsck_device(fs, 1);
+ status |= wait_many(FLAG_WAIT_ALL);
+ if (status > FSCK_EX_NONDESTRUCT) {
+ mnt_free_iter(itr);
+ return status;
+ }
+ }
+ fs_set_done(fs);
+ }
+ }
+
+ /*
+ * This is for the bone-headed user who enters the root
+ * filesystem twice. Skip root will skip all root entries.
+ */
+ if (skip_root) {
+ mnt_reset_iter(itr, MNT_ITER_FORWARD);
+
+ while(mnt_table_next_fs(fstab, itr, &fs) == 0) {
+ const char *tgt = mnt_fs_get_target(fs);
+
+ if (tgt && strcmp(tgt, "/") == 0)
+ fs_set_done(fs);
+ }
+ }
+
+ while (not_done_yet) {
+ not_done_yet = 0;
+ pass_done = 1;
+
+ mnt_reset_iter(itr, MNT_ITER_FORWARD);
+
+ while(mnt_table_next_fs(fstab, itr, &fs) == 0) {
+
+ if (cancel_requested)
+ break;
+ if (fs_is_done(fs))
+ continue;
+ /*
+ * If the filesystem's pass number is higher
+ * than the current pass number, then we don't
+ * do it yet.
+ */
+ if (mnt_fs_get_passno(fs) > passno) {
+ not_done_yet++;
+ continue;
+ }
+ if (ignore_mounted && is_mounted(fs)) {
+ fs_set_done(fs);
+ continue;
+ }
+ /*
+ * If a filesystem on a particular device has
+ * already been spawned, then we need to defer
+ * this to another pass.
+ */
+ if (disk_already_active(fs)) {
+ pass_done = 0;
+ continue;
+ }
+ /*
+ * Spawn off the fsck process
+ */
+ status |= fsck_device(fs, serialize);
+ fs_set_done(fs);
+
+ /*
+ * Only do one filesystem at a time, or if we
+ * have a limit on the number of fsck's extant
+ * at one time, apply that limit.
+ */
+ if (serialize ||
+ (max_running && (num_running >= max_running))) {
+ pass_done = 0;
+ break;
+ }
+ }
+ if (cancel_requested)
+ break;
+ if (verbose > 1)
+ printf(_("--waiting-- (pass %d)\n"), passno);
+
+ status |= wait_many(pass_done ? FLAG_WAIT_ALL :
+ FLAG_WAIT_ATLEAST_ONE);
+ if (pass_done) {
+ if (verbose > 1)
+ printf("----------------------------------\n");
+ passno++;
+ } else
+ not_done_yet++;
+ }
+
+ if (cancel_requested && !kill_sent) {
+ kill_all(SIGTERM);
+ kill_sent++;
+ }
+
+ status |= wait_many(FLAG_WAIT_ATLEAST_ONE);
+ mnt_free_iter(itr);
+ return status;
+}
+
+static void __attribute__((__noreturn__)) usage(void)
+{
+ FILE *out = stdout;
+ fputs(USAGE_HEADER, out);
+ fprintf(out, _(" %s [options] -- [fs-options] [<filesystem> ...]\n"),
+ program_invocation_short_name);
+
+ fputs(USAGE_SEPARATOR, out);
+ fputs(_("Check and repair a Linux filesystem.\n"), out);
+
+ fputs(USAGE_OPTIONS, out);
+ fputs(_(" -A check all filesystems\n"), out);
+ fputs(_(" -C [<fd>] display progress bar; file descriptor is for GUIs\n"), out);
+ fputs(_(" -l lock the device to guarantee exclusive access\n"), out);
+ fputs(_(" -M do not check mounted filesystems\n"), out);
+ fputs(_(" -N do not execute, just show what would be done\n"), out);
+ fputs(_(" -P check filesystems in parallel, including root\n"), out);
+ fputs(_(" -R skip root filesystem; useful only with '-A'\n"), out);
+ fputs(_(" -r [<fd>] report statistics for each device checked;\n"
+ " file descriptor is for GUIs\n"), out);
+ fputs(_(" -s serialize the checking operations\n"), out);
+ fputs(_(" -T do not show the title on startup\n"), out);
+ fputs(_(" -t <type> specify filesystem types to be checked;\n"
+ " <type> is allowed to be a comma-separated list\n"), out);
+ fputs(_(" -V explain what is being done\n"), out);
+
+ fputs(USAGE_SEPARATOR, out);
+ printf( " -?, --help %s\n", USAGE_OPTSTR_HELP);
+ printf( " --version %s\n", USAGE_OPTSTR_VERSION);
+ fputs(USAGE_SEPARATOR, out);
+ fputs(_("See the specific fsck.* commands for available fs-options."), out);
+ printf(USAGE_MAN_TAIL("fsck(8)"));
+ exit(FSCK_EX_OK);
+}
+
+static void signal_cancel(int sig __attribute__((__unused__)))
+{
+ cancel_requested++;
+}
+
+static void parse_argv(int argc, char *argv[])
+{
+ int i, j;
+ char *arg, *dev, *tmp = NULL;
+ char options[128];
+ int opt = 0;
+ int opts_for_fsck = 0;
+ struct sigaction sa;
+ int report_stats_fd = -1;
+
+ /*
+ * Set up signal action
+ */
+ memset(&sa, 0, sizeof(struct sigaction));
+ sa.sa_handler = signal_cancel;
+ sigaction(SIGINT, &sa, NULL);
+ sigaction(SIGTERM, &sa, NULL);
+
+ num_devices = 0;
+ num_args = 0;
+ instance_list = NULL;
+
+ for (i=1; i < argc; i++) {
+ arg = argv[i];
+ if (!arg)
+ continue;
+
+ /* the only two longopts to satisfy UL standards */
+ if (!opts_for_fsck && !strcmp(arg, "--help"))
+ usage();
+ if (!opts_for_fsck && !strcmp(arg, "--version"))
+ print_version(FSCK_EX_OK);
+
+ if ((arg[0] == '/' && !opts_for_fsck) || strchr(arg, '=')) {
+ if (num_devices >= MAX_DEVICES)
+ errx(FSCK_EX_ERROR, _("too many devices"));
+
+ dev = mnt_resolve_spec(arg, mntcache);
+
+ if (!dev && strchr(arg, '=')) {
+ /*
+ * Check to see if we failed because
+ * /proc/partitions isn't found.
+ */
+ if (access(_PATH_PROC_PARTITIONS, R_OK) < 0) {
+ warn(_("cannot open %s"),
+ _PATH_PROC_PARTITIONS);
+ errx(FSCK_EX_ERROR, _("Is /proc mounted?"));
+ }
+ /*
+ * Check to see if this is because
+ * we're not running as root
+ */
+ if (geteuid())
+ errx(FSCK_EX_ERROR,
+ _("must be root to scan for matching filesystems: %s"),
+ arg);
+ else
+ errx(FSCK_EX_ERROR,
+ _("couldn't find matching filesystem: %s"),
+ arg);
+ }
+ devices[num_devices++] = dev ? dev : xstrdup(arg);
+ continue;
+ }
+ if (arg[0] != '-' || opts_for_fsck) {
+ if (num_args >= MAX_ARGS)
+ errx(FSCK_EX_ERROR, _("too many arguments"));
+ args[num_args++] = xstrdup(arg);
+ continue;
+ }
+ for (j=1; arg[j]; j++) {
+ if (opts_for_fsck) {
+ options[++opt] = arg[j];
+ continue;
+ }
+ switch (arg[j]) {
+ case 'A':
+ doall = 1;
+ break;
+ case 'C':
+ progress = 1;
+ if (arg[j+1]) { /* -C<fd> */
+ progress_fd = string_to_int(arg+j+1);
+ if (progress_fd < 0)
+ progress_fd = 0;
+ else
+ goto next_arg;
+ } else if (i+1 < argc && *argv[i+1] != '-') { /* -C <fd> */
+ progress_fd = string_to_int(argv[i+1]);
+ if (progress_fd < 0)
+ progress_fd = 0;
+ else {
+ ++i;
+ goto next_arg;
+ }
+ }
+ break;
+ case 'l':
+ lockdisk = 1;
+ break;
+ case 'V':
+ verbose++;
+ break;
+ case 'N':
+ noexecute = 1;
+ break;
+ case 'R':
+ skip_root = 1;
+ break;
+ case 'T':
+ notitle = 1;
+ break;
+ case 'M':
+ ignore_mounted = 1;
+ break;
+ case 'P':
+ parallel_root = 1;
+ break;
+ case 'r':
+ report_stats = 1;
+ if (arg[j+1]) { /* -r<fd> */
+ report_stats_fd = strtou32_or_err(arg+j+1, _("invalid argument of -r"));
+ goto next_arg;
+ } else if (i+1 < argc && *argv[i+1] >= '0' && *argv[i+1] <= '9') { /* -r <fd> */
+ report_stats_fd = strtou32_or_err(argv[i+1], _("invalid argument of -r"));
+ ++i;
+ goto next_arg;
+ }
+ break;
+ case 's':
+ serialize = 1;
+ break;
+ case 't':
+ tmp = NULL;
+ if (fstype)
+ errx(FSCK_EX_USAGE,
+ _("option '%s' may be specified only once"), "-t");
+ if (arg[j+1])
+ tmp = arg+j+1;
+ else if ((i+1) < argc)
+ tmp = argv[++i];
+ else
+ errx(FSCK_EX_USAGE,
+ _("option '%s' requires an argument"), "-t");
+ fstype = xstrdup(tmp);
+ compile_fs_type(fstype, &fs_type_compiled);
+ goto next_arg;
+ case '-':
+ opts_for_fsck++;
+ break;
+ case '?':
+ usage();
+ break;
+ default:
+ options[++opt] = arg[j];
+ break;
+ }
+ }
+ next_arg:
+ if (opt) {
+ options[0] = '-';
+ options[++opt] = '\0';
+ if (num_args >= MAX_ARGS)
+ errx(FSCK_EX_ERROR, _("too many arguments"));
+ args[num_args++] = xstrdup(options);
+ opt = 0;
+ }
+ }
+
+ /* Validate the report stats file descriptor to avoid disasters */
+ if (report_stats_fd >= 0) {
+ report_stats_file = fdopen(report_stats_fd, "w");
+ if (!report_stats_file)
+ err(FSCK_EX_ERROR,
+ _("invalid argument of -r: %d"),
+ report_stats_fd);
+ }
+
+ if (getenv("FSCK_FORCE_ALL_PARALLEL"))
+ force_all_parallel++;
+ if (ul_strtos32(getenv("FSCK_MAX_INST"), &max_running, 10) != 0)
+ max_running = 0;
+}
+
+int main(int argc, char *argv[])
+{
+ int i, status = 0;
+ int interactive = 0;
+ struct libmnt_fs *fs;
+ const char *path = getenv("PATH");
+
+ setvbuf(stdout, NULL, _IONBF, BUFSIZ);
+ setvbuf(stderr, NULL, _IONBF, BUFSIZ);
+
+ setlocale(LC_MESSAGES, "");
+ setlocale(LC_CTYPE, "");
+ bindtextdomain(PACKAGE, LOCALEDIR);
+ textdomain(PACKAGE);
+ close_stdout_atexit();
+
+ strutils_set_exitcode(FSCK_EX_USAGE);
+ mnt_init_debug(0); /* init libmount debug mask */
+ mntcache = mnt_new_cache(); /* no fatal error if failed */
+
+ parse_argv(argc, argv);
+
+ if (!notitle)
+ printf(UTIL_LINUX_VERSION);
+
+ signal(SIGCHLD, SIG_DFL); /* clear any inherited settings */
+
+ load_fs_info();
+
+ fsck_path = xstrdup(path && *path ? path : FSCK_DEFAULT_PATH);
+
+ if ((num_devices == 1) || (serialize))
+ interactive = 1;
+
+ if (lockdisk && (doall || num_devices > 1)) {
+ warnx(_("the -l option can be used with one "
+ "device only -- ignore"));
+ lockdisk = 0;
+ }
+
+ /* If -A was specified ("check all"), do that! */
+ if (doall)
+ return check_all();
+
+ if (num_devices == 0) {
+ serialize++;
+ interactive++;
+ return check_all();
+ }
+ for (i = 0 ; i < num_devices; i++) {
+ if (cancel_requested) {
+ if (!kill_sent) {
+ kill_all(SIGTERM);
+ kill_sent++;
+ }
+ break;
+ }
+ fs = lookup(devices[i]);
+ if (!fs)
+ fs = add_dummy_fs(devices[i]);
+ else if (fs_ignored_type(fs))
+ continue;
+ if (ignore_mounted && is_mounted(fs))
+ continue;
+ status |= fsck_device(fs, interactive);
+ if (serialize ||
+ (max_running && (num_running >= max_running))) {
+ struct fsck_instance *inst;
+
+ inst = wait_one(0);
+ if (inst) {
+ status |= inst->exit_status;
+ free_instance(inst);
+ }
+ if (verbose > 1)
+ printf("----------------------------------\n");
+ }
+ }
+ status |= wait_many(FLAG_WAIT_ALL);
+ free(fsck_path);
+ mnt_unref_cache(mntcache);
+ mnt_unref_table(fstab);
+ mnt_unref_table(mtab);
+ return status;
+}
diff --git a/disk-utils/fsck.cramfs.8 b/disk-utils/fsck.cramfs.8
new file mode 100644
index 0000000..4630019
--- /dev/null
+++ b/disk-utils/fsck.cramfs.8
@@ -0,0 +1,106 @@
+'\" t
+.\" Title: fsck.cramfs
+.\" Author: [see the "AUTHOR(S)" section]
+.\" Generator: Asciidoctor 2.0.15
+.\" Date: 2022-05-11
+.\" Manual: System Administration
+.\" Source: util-linux 2.38.1
+.\" Language: English
+.\"
+.TH "FSCK.CRAMFS" "8" "2022-05-11" "util\-linux 2.38.1" "System Administration"
+.ie \n(.g .ds Aq \(aq
+.el .ds Aq '
+.ss \n[.ss] 0
+.nh
+.ad l
+.de URL
+\fI\\$2\fP <\\$1>\\$3
+..
+.als MTO URL
+.if \n[.g] \{\
+. mso www.tmac
+. am URL
+. ad l
+. .
+. am MTO
+. ad l
+. .
+. LINKSTYLE blue R < >
+.\}
+.SH "NAME"
+fsck.cramfs \- fsck compressed ROM file system
+.SH "SYNOPSIS"
+.sp
+\fBfsck.cramfs\fP [options] \fIfile\fP
+.SH "DESCRIPTION"
+.sp
+\fBfsck.cramfs\fP is used to check the cramfs file system.
+.SH "OPTIONS"
+.sp
+\fB\-v\fP, \fB\-\-verbose\fP
+.RS 4
+Enable verbose messaging.
+.RE
+.sp
+\fB\-b\fP, \fB\-\-blocksize\fP \fIblocksize\fP
+.RS 4
+Use this blocksize, defaults to page size. Must be equal to what was set at creation time. Only used for \fB\-\-extract\fP.
+.RE
+.sp
+\fB\-\-extract\fP[=\fIdirectory\fP]
+.RS 4
+Test to uncompress the whole file system. Optionally extract contents of the \fIfile\fP to \fIdirectory\fP.
+.RE
+.sp
+\fB\-a\fP
+.RS 4
+This option is silently ignored.
+.RE
+.sp
+\fB\-y\fP
+.RS 4
+This option is silently ignored.
+.RE
+.sp
+\fB\-h\fP, \fB\-\-help\fP
+.RS 4
+Display help text and exit.
+.RE
+.sp
+\fB\-V\fP, \fB\-\-version\fP
+.RS 4
+Print version and exit.
+.RE
+.SH "EXIT STATUS"
+.sp
+\fB0\fP
+.RS 4
+success
+.RE
+.sp
+\fB4\fP
+.RS 4
+file system was left uncorrected
+.RE
+.sp
+\fB8\fP
+.RS 4
+operation error, such as unable to allocate memory
+.RE
+.sp
+\fB16\fP
+.RS 4
+usage information was printed
+.RE
+.SH "SEE ALSO"
+.sp
+\fBmount\fP(8),
+\fBmkfs.cramfs\fP(8)
+.SH "REPORTING BUGS"
+.sp
+For bug reports, use the issue tracker at \c
+.URL "https://github.com/util\-linux/util\-linux/issues" "" "."
+.SH "AVAILABILITY"
+.sp
+The \fBfsck.cramfs\fP command is part of the util\-linux package which can be downloaded from \c
+.URL "https://www.kernel.org/pub/linux/utils/util\-linux/" "Linux Kernel Archive" "." \ No newline at end of file
diff --git a/disk-utils/fsck.cramfs.8.adoc b/disk-utils/fsck.cramfs.8.adoc
new file mode 100644
index 0000000..ec75262
--- /dev/null
+++ b/disk-utils/fsck.cramfs.8.adoc
@@ -0,0 +1,62 @@
+//po4a: entry man manual
+= fsck.cramfs(8)
+:doctype: manpage
+:man manual: System Administration
+:man source: util-linux {release-version}
+:page-layout: base
+:command: fsck.cramfs
+
+== NAME
+
+fsck.cramfs - fsck compressed ROM file system
+
+== SYNOPSIS
+
+*fsck.cramfs* [options] _file_
+
+== DESCRIPTION
+
+*fsck.cramfs* is used to check the cramfs file system.
+
+== OPTIONS
+
+*-v*, *--verbose*::
+Enable verbose messaging.
+
+*-b*, *--blocksize* _blocksize_::
+Use this blocksize, defaults to page size. Must be equal to what was set at creation time. Only used for *--extract*.
+
+*--extract*[=_directory_]::
+Test to uncompress the whole file system. Optionally extract contents of the _file_ to _directory_.
+
+*-a*::
+This option is silently ignored.
+
+*-y*::
+This option is silently ignored.
+
+include::man-common/help-version.adoc[]
+
+== EXIT STATUS
+
+*0*::
+success
+*4*::
+file system was left uncorrected
+*8*::
+operation error, such as unable to allocate memory
+*16*::
+usage information was printed
+
+== SEE ALSO
+
+*mount*(8),
+*mkfs.cramfs*(8)
+
+include::man-common/bugreports.adoc[]
+
+include::man-common/footer.adoc[]
+
+ifdef::translation[]
+include::man-common/translation.adoc[]
+endif::[]
diff --git a/disk-utils/fsck.cramfs.c b/disk-utils/fsck.cramfs.c
new file mode 100644
index 0000000..9b7e2a9
--- /dev/null
+++ b/disk-utils/fsck.cramfs.c
@@ -0,0 +1,733 @@
+/*
+ * cramfsck - check a cramfs file system
+ *
+ * Copyright (C) 2000-2002 Transmeta Corporation
+ * 2005 Adrian Bunk
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * 1999/12/03: Linus Torvalds (cramfs tester and unarchive program)
+ * 2000/06/03: Daniel Quinlan (CRC and length checking program)
+ * 2000/06/04: Daniel Quinlan (merged programs, added options, support
+ * for special files, preserve permissions and
+ * ownership, cramfs superblock v2, bogus mode
+ * test, pathname length test, etc.)
+ * 2000/06/06: Daniel Quinlan (support for holes, pretty-printing,
+ * symlink size test)
+ * 2000/07/11: Daniel Quinlan (file length tests, start at offset 0 or 512,
+ * fsck-compatible exit codes)
+ * 2000/07/15: Daniel Quinlan (initial support for block devices)
+ * 2002/01/10: Daniel Quinlan (additional checks, test more return codes,
+ * use read if mmap fails, standardize messages)
+ */
+
+#include <stdio.h>
+#include <stdarg.h>
+#include <stdint.h>
+#include <unistd.h>
+#include <dirent.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <string.h>
+#include <getopt.h>
+#include <fcntl.h>
+
+/* We don't use our include/crc32.h, but crc32 from zlib!
+ *
+ * The zlib implementation performs pre/post-conditioning. The util-linux
+ * imlemenation requires post-conditioning (xor) in the applications.
+ */
+#include <zlib.h>
+
+#include <sys/time.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/mman.h>
+
+#include "c.h"
+#include "cramfs.h"
+#include "nls.h"
+#include "blkdev.h"
+#include "exitcodes.h"
+#include "strutils.h"
+#include "closestream.h"
+
+#define XALLOC_EXIT_CODE FSCK_EX_ERROR
+#include "xalloc.h"
+
+static int fd; /* ROM image file descriptor */
+static char *filename; /* ROM image filename */
+static struct cramfs_super super; /* just find the cramfs superblock once */
+static int cramfs_is_big_endian = 0; /* source is big endian */
+static int opt_verbose = 0; /* 1 = verbose (-v), 2+ = very verbose (-vv) */
+static int opt_extract = 0; /* extract cramfs (-x) */
+static char *extract_dir = ""; /* optional extraction directory (-x) */
+
+#define PAD_SIZE 512
+
+static uid_t euid; /* effective UID */
+
+/* (cramfs_super + start) <= start_dir < end_dir <= start_data <= end_data */
+static unsigned long start_dir = ~0UL; /* start of first non-root inode */
+static unsigned long end_dir = 0; /* end of the directory structure */
+static unsigned long start_data = ~0UL; /* start of the data (256 MB = max) */
+static unsigned long end_data = 0; /* end of the data */
+
+
+/* Guarantee access to at least 2 * blksize at a time */
+#define CRAMFS_ROMBUFFER_BITS 13
+#define CRAMFS_ROMBUFFERSIZE (1 << CRAMFS_ROMBUFFER_BITS)
+#define CRAMFS_ROMBUFFERMASK (CRAMFS_ROMBUFFERSIZE - 1)
+
+/* Defaults, updated in main() according to block size */
+static size_t rombufbits = CRAMFS_ROMBUFFER_BITS;
+static size_t rombufsize = CRAMFS_ROMBUFFERSIZE;
+static size_t rombufmask = CRAMFS_ROMBUFFERMASK;
+
+static char *read_buffer;
+static unsigned long read_buffer_block = ~0UL;
+
+static z_stream stream;
+
+/* Prototypes */
+static void expand_fs(char *, struct cramfs_inode *);
+
+static char *outbuffer;
+
+static size_t blksize = 0;
+
+static void __attribute__((__noreturn__)) usage(void)
+{
+ FILE *out = stdout;
+
+ fputs(USAGE_HEADER, out);
+ fprintf(out,
+ _(" %s [options] <file>\n"), program_invocation_short_name);
+
+ fputs(USAGE_SEPARATOR, out);
+ fputs(_("Check and repair a compressed ROM filesystem.\n"), out);
+
+ fputs(USAGE_OPTIONS, out);
+ fputs(_(" -a for compatibility only, ignored\n"), out);
+ fputs(_(" -v, --verbose be more verbose\n"), out);
+ fputs(_(" -y for compatibility only, ignored\n"), out);
+ fputs(_(" -b, --blocksize <size> use this blocksize, defaults to page size\n"), out);
+ fputs(_(" --extract[=<dir>] test uncompression, optionally extract into <dir>\n"), out);
+ fputs(USAGE_SEPARATOR, out);
+ printf(USAGE_HELP_OPTIONS(26));
+
+ printf(USAGE_MAN_TAIL("fsck.cramfs(8)"));
+ exit(FSCK_EX_OK);
+}
+
+static int get_superblock_endianness(uint32_t magic)
+{
+ if (magic == CRAMFS_MAGIC) {
+ cramfs_is_big_endian = HOST_IS_BIG_ENDIAN;
+ return 0;
+ }
+
+ if (magic ==
+ u32_toggle_endianness(!HOST_IS_BIG_ENDIAN, CRAMFS_MAGIC)) {
+ cramfs_is_big_endian = !HOST_IS_BIG_ENDIAN;
+ return 0;
+ }
+
+ return -1;
+}
+
+static void test_super(int *start, size_t * length)
+{
+ struct stat st;
+
+
+ fd = open(filename, O_RDONLY);
+ if (fd < 0)
+ err(FSCK_EX_ERROR, _("cannot open %s"), filename);
+
+ /* find the physical size of the file or block device */
+ if (fstat(fd, &st) < 0)
+ err(FSCK_EX_ERROR, _("stat of %s failed"), filename);
+
+ if (S_ISBLK(st.st_mode)) {
+ unsigned long long bytes;
+ if (blkdev_get_size(fd, &bytes))
+ err(FSCK_EX_ERROR,
+ _("ioctl failed: unable to determine device size: %s"),
+ filename);
+ *length = bytes;
+ } else if (S_ISREG(st.st_mode))
+ *length = st.st_size;
+ else
+ errx(FSCK_EX_ERROR, _("not a block device or file: %s"), filename);
+
+ if (*length < sizeof(struct cramfs_super))
+ errx(FSCK_EX_UNCORRECTED, _("file length too short"));
+
+ /* find superblock */
+ if (read(fd, &super, sizeof(super)) != sizeof(super))
+ err(FSCK_EX_ERROR, _("cannot read %s"), filename);
+ if (get_superblock_endianness(super.magic) != -1)
+ *start = 0;
+ else if (*length >= (PAD_SIZE + sizeof(super))) {
+ if (lseek(fd, PAD_SIZE, SEEK_SET) == (off_t) -1)
+ err(FSCK_EX_ERROR, _("seek on %s failed"), filename);
+ if (read(fd, &super, sizeof(super)) != sizeof(super))
+ err(FSCK_EX_ERROR, _("cannot read %s"), filename);
+ if (get_superblock_endianness(super.magic) != -1)
+ *start = PAD_SIZE;
+ else
+ errx(FSCK_EX_UNCORRECTED, _("superblock magic not found"));
+ } else
+ errx(FSCK_EX_UNCORRECTED, _("superblock magic not found"));
+
+ if (opt_verbose)
+ printf(_("cramfs endianness is %s\n"),
+ cramfs_is_big_endian ? _("big") : _("little"));
+
+ super_toggle_endianness(cramfs_is_big_endian, &super);
+ if (super.flags & ~CRAMFS_SUPPORTED_FLAGS)
+ errx(FSCK_EX_ERROR, _("unsupported filesystem features"));
+
+ /* What are valid superblock sizes? */
+ if (super.size < *start + sizeof(struct cramfs_super))
+ errx(FSCK_EX_UNCORRECTED, _("superblock size (%d) too small"),
+ super.size);
+
+ if (super.flags & CRAMFS_FLAG_FSID_VERSION_2) {
+ if (super.fsid.files == 0)
+ errx(FSCK_EX_UNCORRECTED, _("zero file count"));
+ if (*length < super.size)
+ errx(FSCK_EX_UNCORRECTED, _("file length too short"));
+ else if (*length > super.size)
+ warnx(_("file extends past end of filesystem"));
+ } else
+ warnx(_("old cramfs format"));
+}
+
+static void test_crc(int start)
+{
+ void *buf;
+ uint32_t crc;
+
+ if (!(super.flags & CRAMFS_FLAG_FSID_VERSION_2)) {
+ warnx(_("unable to test CRC: old cramfs format"));
+ return;
+ }
+
+ crc = crc32(0L, NULL, 0);
+
+ buf =
+ mmap(NULL, super.size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
+ if (buf == MAP_FAILED) {
+ buf =
+ mmap(NULL, super.size, PROT_READ | PROT_WRITE,
+ MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+ if (buf != MAP_FAILED) {
+ ssize_t tmp;
+ if (lseek(fd, 0, SEEK_SET) == (off_t) -1)
+ err(FSCK_EX_ERROR, _("seek on %s failed"), filename);
+ tmp = read(fd, buf, super.size);
+ if (tmp < 0)
+ err(FSCK_EX_ERROR, _("cannot read %s"), filename);
+ if (tmp != (ssize_t) super.size)
+ errx(FSCK_EX_ERROR, _("failed to read %"PRIu32" bytes from file %s"),
+ super.size, filename);
+ }
+ }
+ if (buf != MAP_FAILED) {
+ ((struct cramfs_super *)((unsigned char *) buf + start))->fsid.crc =
+ crc32(0L, NULL, 0);
+ crc = crc32(crc, (unsigned char *) buf + start, super.size - start);
+ munmap(buf, super.size);
+ } else {
+ int retval;
+ size_t length = 0;
+
+ buf = xmalloc(4096);
+ if (lseek(fd, start, SEEK_SET) == (off_t) -1)
+ err(FSCK_EX_ERROR, _("seek on %s failed"), filename);
+ for (;;) {
+ retval = read(fd, buf, 4096);
+ if (retval < 0)
+ err(FSCK_EX_ERROR, _("cannot read %s"), filename);
+ else if (retval == 0)
+ break;
+ if (length == 0)
+ ((struct cramfs_super *)buf)->fsid.crc =
+ crc32(0L, NULL, 0);
+ length += retval;
+ if (length > (super.size - start)) {
+ crc = crc32(crc, buf,
+ retval - (length -
+ (super.size - start)));
+ break;
+ }
+ crc = crc32(crc, buf, retval);
+ }
+ free(buf);
+ }
+
+ if (crc != super.fsid.crc)
+ errx(FSCK_EX_UNCORRECTED, _("crc error"));
+}
+
+static void print_node(char type, struct cramfs_inode *i, char *name)
+{
+ char info[10];
+
+ if (S_ISCHR(i->mode) || (S_ISBLK(i->mode)))
+ /* major/minor numbers can be as high as 2^12 or 4096 */
+ snprintf(info, 10, "%4d,%4d", major(i->size), minor(i->size));
+ else
+ /* size be as high as 2^24 or 16777216 */
+ snprintf(info, 10, "%9d", i->size);
+
+ printf("%c %04o %s %5d:%-3d %s\n",
+ type, i->mode & ~S_IFMT, info, i->uid, i->gid,
+ !*name && type == 'd' ? "/" : name);
+}
+
+/*
+ * Create a fake "blocked" access
+ */
+static void *romfs_read(unsigned long offset)
+{
+ unsigned int block = offset >> rombufbits;
+ if (block != read_buffer_block) {
+ ssize_t x;
+
+ read_buffer_block = block;
+ if (lseek(fd, block << rombufbits, SEEK_SET) == (off_t) -1)
+ warn(_("seek failed"));
+
+ x = read(fd, read_buffer, rombufsize * 2);
+ if (x < 0)
+ warn(_("read romfs failed"));
+ }
+ return read_buffer + (offset & rombufmask);
+}
+
+static struct cramfs_inode *cramfs_iget(struct cramfs_inode *i)
+{
+ struct cramfs_inode *inode = xmalloc(sizeof(struct cramfs_inode));
+
+ inode_to_host(cramfs_is_big_endian, i, inode);
+ return inode;
+}
+
+static struct cramfs_inode *iget(unsigned int ino)
+{
+ return cramfs_iget(romfs_read(ino));
+}
+
+static void iput(struct cramfs_inode *inode)
+{
+ free(inode);
+}
+
+/*
+ * Return the offset of the root directory
+ */
+static struct cramfs_inode *read_super(void)
+{
+ struct cramfs_inode *root = cramfs_iget(&super.root);
+ unsigned long offset = root->offset << 2;
+
+ if (!S_ISDIR(root->mode))
+ errx(FSCK_EX_UNCORRECTED, _("root inode is not directory"));
+ if (!(super.flags & CRAMFS_FLAG_SHIFTED_ROOT_OFFSET) &&
+ ((offset != sizeof(struct cramfs_super)) &&
+ (offset != PAD_SIZE + sizeof(struct cramfs_super)))) {
+ errx(FSCK_EX_UNCORRECTED, _("bad root offset (%lu)"), offset);
+ }
+ return root;
+}
+
+static int uncompress_block(void *src, size_t len)
+{
+ int err;
+
+ stream.next_in = src;
+ stream.avail_in = len;
+
+ stream.next_out = (unsigned char *)outbuffer;
+ stream.avail_out = blksize * 2;
+
+ inflateReset(&stream);
+
+ if (len > blksize * 2)
+ errx(FSCK_EX_UNCORRECTED, _("data block too large"));
+
+ err = inflate(&stream, Z_FINISH);
+ if (err != Z_STREAM_END)
+ errx(FSCK_EX_UNCORRECTED, _("decompression error: %s"),
+ zError(err));
+ return stream.total_out;
+}
+
+#ifndef HAVE_LCHOWN
+#define lchown chown
+#endif
+
+static void do_uncompress(char *path, int outfd, unsigned long offset,
+ unsigned long size)
+{
+ unsigned long curr = offset + 4 * ((size + blksize - 1) / blksize);
+
+ do {
+ unsigned long out = blksize;
+ unsigned long next = u32_toggle_endianness(cramfs_is_big_endian,
+ *(uint32_t *)
+ romfs_read(offset));
+
+ if (next > end_data)
+ end_data = next;
+
+ offset += 4;
+ if (curr == next) {
+ if (opt_verbose > 1)
+ printf(_(" hole at %lu (%zu)\n"), curr,
+ blksize);
+ if (size < blksize)
+ out = size;
+ memset(outbuffer, 0x00, out);
+ } else {
+ if (opt_verbose > 1)
+ printf(_(" uncompressing block at %lu to %lu (%lu)\n"),
+ curr, next, next - curr);
+ out = uncompress_block(romfs_read(curr), next - curr);
+ }
+ if (size >= blksize) {
+ if (out != blksize)
+ errx(FSCK_EX_UNCORRECTED,
+ _("non-block (%ld) bytes"), out);
+ } else {
+ if (out != size)
+ errx(FSCK_EX_UNCORRECTED,
+ _("non-size (%ld vs %ld) bytes"), out,
+ size);
+ }
+ size -= out;
+ if (*extract_dir != '\0' && write(outfd, outbuffer, out) < 0)
+ err(FSCK_EX_ERROR, _("write failed: %s"), path);
+ curr = next;
+ } while (size);
+}
+static void change_file_status(char *path, struct cramfs_inode *i)
+{
+ const struct timeval epoch[] = { {0,0}, {0,0} };
+
+ if (euid == 0) {
+ if (lchown(path, i->uid, i->gid) < 0)
+ err(FSCK_EX_ERROR, _("lchown failed: %s"), path);
+ if (S_ISLNK(i->mode))
+ return;
+ if (((S_ISUID | S_ISGID) & i->mode) && chmod(path, i->mode) < 0)
+ err(FSCK_EX_ERROR, _("chown failed: %s"), path);
+ }
+ if (S_ISLNK(i->mode))
+ return;
+ if (utimes(path, epoch) < 0)
+ err(FSCK_EX_ERROR, _("utimes failed: %s"), path);
+}
+
+static void do_directory(char *path, struct cramfs_inode *i)
+{
+ int pathlen = strlen(path);
+ int count = i->size;
+ unsigned long offset = i->offset << 2;
+ char *newpath = xmalloc(pathlen + 256);
+
+ if (offset == 0 && count != 0)
+ errx(FSCK_EX_UNCORRECTED,
+ _("directory inode has zero offset and non-zero size: %s"),
+ path);
+
+ if (offset != 0 && offset < start_dir)
+ start_dir = offset;
+
+ /* TODO: Do we need to check end_dir for empty case? */
+ memcpy(newpath, path, pathlen);
+ newpath[pathlen] = '/';
+ pathlen++;
+ if (opt_verbose)
+ print_node('d', i, path);
+
+ if (*extract_dir != '\0') {
+ if (mkdir(path, i->mode) < 0)
+ err(FSCK_EX_ERROR, _("mkdir failed: %s"), path);
+ change_file_status(path, i);
+ }
+ while (count > 0) {
+ struct cramfs_inode *child = iget(offset);
+ int size;
+ int newlen = child->namelen << 2;
+
+ size = sizeof(struct cramfs_inode) + newlen;
+ count -= size;
+
+ offset += sizeof(struct cramfs_inode);
+
+ memcpy(newpath + pathlen, romfs_read(offset), newlen);
+ newpath[pathlen + newlen] = 0;
+ if (newlen == 0)
+ errx(FSCK_EX_UNCORRECTED, _("filename length is zero"));
+ if ((pathlen + newlen) - strlen(newpath) > 3)
+ errx(FSCK_EX_UNCORRECTED, _("bad filename length"));
+ expand_fs(newpath, child);
+
+ offset += newlen;
+
+ if (offset <= start_dir)
+ errx(FSCK_EX_UNCORRECTED, _("bad inode offset"));
+ if (offset > end_dir)
+ end_dir = offset;
+ iput(child); /* free(child) */
+ }
+ free(newpath);
+}
+
+static void do_file(char *path, struct cramfs_inode *i)
+{
+ unsigned long offset = i->offset << 2;
+ int outfd = 0;
+
+ if (offset == 0 && i->size != 0)
+ errx(FSCK_EX_UNCORRECTED,
+ _("file inode has zero offset and non-zero size"));
+ if (i->size == 0 && offset != 0)
+ errx(FSCK_EX_UNCORRECTED,
+ _("file inode has zero size and non-zero offset"));
+ if (offset != 0 && offset < start_data)
+ start_data = offset;
+ if (opt_verbose)
+ print_node('f', i, path);
+ if (*extract_dir != '\0') {
+ outfd = open(path, O_WRONLY | O_CREAT | O_TRUNC, i->mode);
+ if (outfd < 0)
+ err(FSCK_EX_ERROR, _("cannot open %s"), path);
+ }
+ if (i->size)
+ do_uncompress(path, outfd, offset, i->size);
+ if ( *extract_dir != '\0') {
+ if (close_fd(outfd) != 0)
+ err(FSCK_EX_ERROR, _("write failed: %s"), path);
+ change_file_status(path, i);
+ }
+}
+
+static void do_symlink(char *path, struct cramfs_inode *i)
+{
+ unsigned long offset = i->offset << 2;
+ unsigned long curr = offset + 4;
+ unsigned long next =
+ u32_toggle_endianness(cramfs_is_big_endian,
+ *(uint32_t *) romfs_read(offset));
+ unsigned long size;
+
+ if (offset == 0)
+ errx(FSCK_EX_UNCORRECTED, _("symbolic link has zero offset"));
+ if (i->size == 0)
+ errx(FSCK_EX_UNCORRECTED, _("symbolic link has zero size"));
+
+ if (offset < start_data)
+ start_data = offset;
+ if (next > end_data)
+ end_data = next;
+
+ size = uncompress_block(romfs_read(curr), next - curr);
+ if (size != i->size)
+ errx(FSCK_EX_UNCORRECTED, _("size error in symlink: %s"), path);
+ outbuffer[size] = 0;
+ if (opt_verbose) {
+ char *str;
+
+ xasprintf(&str, "%s -> %s", path, outbuffer);
+ print_node('l', i, str);
+ if (opt_verbose > 1)
+ printf(_(" uncompressing block at %lu to %lu (%lu)\n"),
+ curr, next, next - curr);
+ free(str);
+ }
+ if (*extract_dir != '\0') {
+ if (symlink(outbuffer, path) < 0)
+ err(FSCK_EX_ERROR, _("symlink failed: %s"), path);
+ change_file_status(path, i);
+ }
+}
+
+static void do_special_inode(char *path, struct cramfs_inode *i)
+{
+ dev_t devtype = 0;
+ char type;
+
+ if (i->offset)
+ /* no need to shift offset */
+ errx(FSCK_EX_UNCORRECTED,
+ _("special file has non-zero offset: %s"), path);
+
+ if (S_ISCHR(i->mode)) {
+ devtype = i->size;
+ type = 'c';
+ } else if (S_ISBLK(i->mode)) {
+ devtype = i->size;
+ type = 'b';
+ } else if (S_ISFIFO(i->mode)) {
+ if (i->size != 0)
+ errx(FSCK_EX_UNCORRECTED, _("fifo has non-zero size: %s"),
+ path);
+ type = 'p';
+ } else if (S_ISSOCK(i->mode)) {
+ if (i->size != 0)
+ errx(FSCK_EX_UNCORRECTED,
+ _("socket has non-zero size: %s"), path);
+ type = 's';
+ } else {
+ errx(FSCK_EX_UNCORRECTED, _("bogus mode: %s (%o)"), path, i->mode);
+ return; /* not reached */
+ }
+
+ if (opt_verbose)
+ print_node(type, i, path);
+
+ if (*extract_dir != '\0') {
+ if (mknod(path, i->mode, devtype) < 0)
+ err(FSCK_EX_ERROR, _("mknod failed: %s"), path);
+ change_file_status(path, i);
+ }
+}
+
+static void expand_fs(char *path, struct cramfs_inode *inode)
+{
+ if (S_ISDIR(inode->mode))
+ do_directory(path, inode);
+ else if (S_ISREG(inode->mode))
+ do_file(path, inode);
+ else if (S_ISLNK(inode->mode))
+ do_symlink(path, inode);
+ else
+ do_special_inode(path, inode);
+}
+
+static void test_fs(int start)
+{
+ struct cramfs_inode *root;
+
+ root = read_super();
+ umask(0);
+ euid = geteuid();
+ stream.next_in = NULL;
+ stream.avail_in = 0;
+ inflateInit(&stream);
+ expand_fs(extract_dir, root);
+ inflateEnd(&stream);
+ if (start_data != ~0UL) {
+ if (start_data < (sizeof(struct cramfs_super) + start))
+ errx(FSCK_EX_UNCORRECTED,
+ _("directory data start (%lu) < sizeof(struct cramfs_super) + start (%zu)"),
+ start_data, sizeof(struct cramfs_super) + start);
+ if (end_dir != start_data)
+ errx(FSCK_EX_UNCORRECTED,
+ _("directory data end (%lu) != file data start (%lu)"),
+ end_dir, start_data);
+ }
+ if (super.flags & CRAMFS_FLAG_FSID_VERSION_2 && end_data > super.size)
+ errx(FSCK_EX_UNCORRECTED, _("invalid file data offset"));
+
+ iput(root); /* free(root) */
+}
+
+int main(int argc, char **argv)
+{
+ int c; /* for getopt */
+ int start = 0;
+ size_t length = 0;
+
+ static const struct option longopts[] = {
+ {"verbose", no_argument, NULL, 'v'},
+ {"version", no_argument, NULL, 'V'},
+ {"help", no_argument, NULL, 'h'},
+ {"blocksize", required_argument, NULL, 'b'},
+ {"extract", optional_argument, NULL, 'x'},
+ {NULL, 0, NULL, 0},
+ };
+
+ setlocale(LC_MESSAGES, "");
+ setlocale(LC_CTYPE, "");
+ bindtextdomain(PACKAGE, LOCALEDIR);
+ textdomain(PACKAGE);
+ close_stdout_atexit();
+
+ strutils_set_exitcode(FSCK_EX_USAGE);
+
+ /* command line options */
+ while ((c = getopt_long(argc, argv, "ayvVhb:", longopts, NULL)) != EOF)
+ switch (c) {
+ case 'a': /* ignore */
+ case 'y':
+ break;
+ case 'h':
+ usage();
+ break;
+ case 'V':
+ print_version(FSCK_EX_OK);
+ case 'x':
+ opt_extract = 1;
+ if(optarg)
+ extract_dir = optarg;
+ break;
+ case 'v':
+ opt_verbose++;
+ break;
+ case 'b':
+ blksize = strtou32_or_err(optarg, _("invalid blocksize argument"));
+ break;
+ default:
+ errtryhelp(FSCK_EX_USAGE);
+ }
+
+ if ((argc - optind) != 1){
+ warnx(_("bad usage"));
+ errtryhelp(FSCK_EX_USAGE);
+ }
+ filename = argv[optind];
+
+ test_super(&start, &length);
+ test_crc(start);
+
+ if (opt_extract) {
+ size_t bufsize = 0;
+
+ if (blksize == 0)
+ blksize = getpagesize();
+
+ /* re-calculate according to blksize */
+ bufsize = rombufsize = blksize * 2;
+ rombufbits = 0;
+ while (bufsize >>= 1)
+ rombufbits++;
+ rombufmask = rombufsize - 1;
+
+ outbuffer = xmalloc(blksize * 2);
+ read_buffer = xmalloc(rombufsize * 2);
+ test_fs(start);
+ }
+
+ if (opt_verbose)
+ printf(_("%s: OK\n"), filename);
+
+ exit(FSCK_EX_OK);
+}