802d7fa86d5768dfee8d5592b80aa73a248cc854
[oweals/busybox.git] / e2fsprogs / fsck.c
1 /*
2  * pfsck --- A generic, parallelizing front-end for the fsck program.
3  * It will automatically try to run fsck programs in parallel if the
4  * devices are on separate spindles.  It is based on the same ideas as
5  * the generic front end for fsck by David Engel and Fred van Kempen,
6  * but it has been completely rewritten from scratch to support
7  * parallel execution.
8  *
9  * Written by Theodore Ts'o, <tytso@mit.edu>
10  *
11  * Miquel van Smoorenburg (miquels@drinkel.ow.org) 20-Oct-1994:
12  *   o Changed -t fstype to behave like with mount when -A (all file
13  *     systems) or -M (like mount) is specified.
14  *   o fsck looks if it can find the fsck.type program to decide
15  *     if it should ignore the fs type. This way more fsck programs
16  *     can be added without changing this front-end.
17  *   o -R flag skip root file system.
18  *
19  * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
20  *      2001, 2002, 2003, 2004, 2005 by  Theodore Ts'o.
21  *
22  * %Begin-Header%
23  * This file may be redistributed under the terms of the GNU Public
24  * License.
25  * %End-Header%
26  */
27
28 #include <sys/types.h>
29 #include <sys/wait.h>
30 #include <sys/signal.h>
31 #include <sys/stat.h>
32 #include <limits.h>
33 #include <stdio.h>
34 #include <ctype.h>
35 #include <string.h>
36 #include <time.h>
37 #include <stdlib.h>
38 #include <errno.h>
39 #include <paths.h>
40 #include <unistd.h>
41 #include <errno.h>
42 #include <malloc.h>
43 #include <signal.h>
44
45 #include "fsck.h"
46 #include "blkid/blkid.h"
47
48 #include "e2fsbb.h"
49
50 #include "busybox.h"
51
52 #ifndef _PATH_MNTTAB
53 #define _PATH_MNTTAB    "/etc/fstab"
54 #endif
55
56 /*
57  * fsck.h
58  */
59
60 #ifndef DEFAULT_FSTYPE
61 #define DEFAULT_FSTYPE  "ext2"
62 #endif
63
64 #define MAX_DEVICES 32
65 #define MAX_ARGS 32
66
67 /*
68  * Internal structure for mount tabel entries.
69  */
70
71 struct fs_info {
72         char  *device;
73         char  *mountpt;
74         char  *type;
75         char  *opts;
76         int   freq;
77         int   passno;
78         int   flags;
79         struct fs_info *next;
80 };
81
82 #define FLAG_DONE 1
83 #define FLAG_PROGRESS 2
84
85 /*
86  * Structure to allow exit codes to be stored
87  */
88 struct fsck_instance {
89         int     pid;
90         int     flags;
91         int     exit_status;
92         time_t  start_time;
93         char *  prog;
94         char *  type;
95         char *  device;
96         char *  base_device;
97         struct fsck_instance *next;
98 };
99
100 /*
101  * base_device.c
102  *
103  * Return the "base device" given a particular device; this is used to
104  * assure that we only fsck one partition on a particular drive at any
105  * one time.  Otherwise, the disk heads will be seeking all over the
106  * place.  If the base device can not be determined, return NULL.
107  * 
108  * The base_device() function returns an allocated string which must
109  * be freed.
110  * 
111  */
112
113
114 #ifdef CONFIG_FEATURE_DEVFS
115 /*
116  * Required for the uber-silly devfs /dev/ide/host1/bus2/target3/lun3
117  * pathames.
118  */
119 static const char *devfs_hier[] = {
120         "host", "bus", "target", "lun", 0
121 };
122 #endif
123
124 static char *base_device(const char *device)
125 {
126         char *str, *cp;
127 #ifdef CONFIG_FEATURE_DEVFS
128         const char **hier, *disk;
129         int len;
130 #endif
131
132         cp = str = bb_xstrdup(device);
133
134         /* Skip over /dev/; if it's not present, give up. */
135         if (strncmp(cp, "/dev/", 5) != 0)
136                 goto errout;
137         cp += 5;
138
139 #if 0   /* this is for old stuff no one uses anymore ? */
140         /* Skip over /dev/dsk/... */
141         if (strncmp(cp, "dsk/", 4) == 0)
142                 cp += 4;
143 #endif
144
145         /*
146          * For md devices, we treat them all as if they were all
147          * on one disk, since we don't know how to parallelize them.
148          */
149         if (cp[0] == 'm' && cp[1] == 'd') {
150                 *(cp+2) = 0;
151                 return str;
152         }
153
154         /* Handle DAC 960 devices */
155         if (strncmp(cp, "rd/", 3) == 0) {
156                 cp += 3;
157                 if (cp[0] != 'c' || cp[2] != 'd' ||
158                     !isdigit(cp[1]) || !isdigit(cp[3]))
159                         goto errout;
160                 *(cp+4) = 0;
161                 return str;
162         }
163
164         /* Now let's handle /dev/hd* and /dev/sd* devices.... */
165         if ((cp[0] == 'h' || cp[0] == 's') && (cp[1] == 'd')) {
166                 cp += 2;
167                 /* If there's a single number after /dev/hd, skip it */
168                 if (isdigit(*cp))
169                         cp++;
170                 /* What follows must be an alpha char, or give up */
171                 if (!isalpha(*cp))
172                         goto errout;
173                 *(cp + 1) = 0;
174                 return str;
175         }
176
177 #ifdef CONFIG_FEATURE_DEVFS
178         /* Now let's handle devfs (ugh) names */
179         len = 0;
180         if (strncmp(cp, "ide/", 4) == 0)
181                 len = 4;
182         if (strncmp(cp, "scsi/", 5) == 0)
183                 len = 5;
184         if (len) {
185                 cp += len;
186                 /*
187                  * Now we proceed down the expected devfs hierarchy.
188                  * i.e., .../host1/bus2/target3/lun4/...
189                  * If we don't find the expected token, followed by
190                  * some number of digits at each level, abort.
191                  */
192                 for (hier = devfs_hier; *hier; hier++) {
193                         len = strlen(*hier);
194                         if (strncmp(cp, *hier, len) != 0)
195                                 goto errout;
196                         cp += len;
197                         while (*cp != '/' && *cp != 0) {
198                                 if (!isdigit(*cp))
199                                         goto errout;
200                                 cp++;
201                         }
202                         cp++;
203                 }
204                 *(cp - 1) = 0;
205                 return str;
206         }
207
208         /* Now handle devfs /dev/disc or /dev/disk names */
209         disk = 0;
210         if (strncmp(cp, "discs/", 6) == 0)
211                 disk = "disc";
212         else if (strncmp(cp, "disks/", 6) == 0)
213                 disk = "disk";
214         if (disk) {
215                 cp += 6;
216                 if (strncmp(cp, disk, 4) != 0)
217                         goto errout;
218                 cp += 4;
219                 while (*cp != '/' && *cp != 0) {
220                         if (!isdigit(*cp))
221                                 goto errout;
222                         cp++;
223                 }
224                 *cp = 0;
225                 return str;
226         }
227 #endif
228
229 errout:
230         free(str);
231         return NULL;
232 }
233
234
235 static const char * const ignored_types[] = {
236         "ignore",
237         "iso9660",
238         "nfs",
239         "proc",
240         "sw",
241         "swap",
242         "tmpfs",
243         "devpts",
244         NULL
245 };
246
247 static const char * const really_wanted[] = {
248         "minix",
249         "ext2",
250         "ext3",
251         "jfs",
252         "reiserfs",
253         "xiafs",
254         "xfs",
255         NULL
256 };
257
258 #define BASE_MD "/dev/md"
259
260 /*
261  * Global variables for options
262  */
263 static char *devices[MAX_DEVICES];
264 static char *args[MAX_ARGS];
265 static int num_devices, num_args;
266
267 static int verbose;
268 static int doall;
269 static int noexecute;
270 static int serialize;
271 static int skip_root;
272 static int like_mount;
273 static int notitle;
274 static int parallel_root;
275 static int progress;
276 static int progress_fd;
277 static int force_all_parallel;
278 static int num_running;
279 static int max_running;
280 static volatile int cancel_requested;
281 static int kill_sent;
282 static char *fstype;
283 static struct fs_info *filesys_info, *filesys_last;
284 static struct fsck_instance *instance_list;
285 static char *fsck_path;
286 static blkid_cache cache;
287
288 static char *string_copy(const char *s)
289 {
290         char    *ret;
291
292         if (!s)
293                 return 0;
294         ret = strdup(s);
295         return ret;
296 }
297
298 static int string_to_int(const char *s)
299 {
300         long l;
301         char *p;
302
303         l = strtol(s, &p, 0);
304         if (*p || l == LONG_MIN || l == LONG_MAX || l < 0 || l > INT_MAX)
305                 return -1;
306         else
307                 return (int) l;
308 }
309
310 static char *skip_over_blank(char *cp)
311 {
312         while (*cp && isspace(*cp))
313                 cp++;
314         return cp;
315 }
316
317 static char *skip_over_word(char *cp)
318 {
319         while (*cp && !isspace(*cp))
320                 cp++;
321         return cp;
322 }
323
324 static void strip_line(char *line)
325 {
326         char    *p;
327
328         while (*line) {
329                 p = line + strlen(line) - 1;
330                 if ((*p == '\n') || (*p == '\r'))
331                         *p = 0;
332                 else
333                         break;
334         }
335 }
336
337 static char *parse_word(char **buf)
338 {
339         char *word, *next;
340
341         word = *buf;
342         if (*word == 0)
343                 return 0;
344
345         word = skip_over_blank(word);
346         next = skip_over_word(word);
347         if (*next)
348                 *next++ = 0;
349         *buf = next;
350         return word;
351 }
352
353 static void parse_escape(char *word)
354 {
355         char    *q, c;
356         const char *p;
357
358         if (!word)
359                 return;
360
361         for (p = q = word; *p; q++) {
362                 c = *p++;
363                 if (c != '\\') {
364                         *q = c;
365                 } else {
366                         *q = bb_process_escape_sequence(&p);
367                 }
368         }
369         *q = 0;
370 }
371
372 static void free_instance(struct fsck_instance *i)
373 {
374         if (i->prog)
375                 free(i->prog);
376         if (i->device)
377                 free(i->device);
378         if (i->base_device)
379                 free(i->base_device);
380         free(i);
381         return;
382 }
383
384 static struct fs_info *create_fs_device(const char *device, const char *mntpnt,
385                                         const char *type, const char *opts,
386                                         int freq, int passno)
387 {
388         struct fs_info *fs;
389
390         if (!(fs = malloc(sizeof(struct fs_info))))
391                 return NULL;
392
393         fs->device = string_copy(device);
394         fs->mountpt = string_copy(mntpnt);
395         fs->type = string_copy(type);
396         fs->opts = string_copy(opts ? opts : "");
397         fs->freq = freq;
398         fs->passno = passno;
399         fs->flags = 0;
400         fs->next = NULL;
401
402         if (!filesys_info)
403                 filesys_info = fs;
404         else
405                 filesys_last->next = fs;
406         filesys_last = fs;
407
408         return fs;
409 }
410
411
412
413 static int parse_fstab_line(char *line, struct fs_info **ret_fs)
414 {
415         char    *dev, *device, *mntpnt, *type, *opts, *freq, *passno, *cp;
416         struct fs_info *fs;
417
418         *ret_fs = 0;
419         strip_line(line);
420         if ((cp = strchr(line, '#')))
421                 *cp = 0;        /* Ignore everything after the comment char */
422         cp = line;
423
424         device = parse_word(&cp);
425         mntpnt = parse_word(&cp);
426         type = parse_word(&cp);
427         opts = parse_word(&cp);
428         freq = parse_word(&cp);
429         passno = parse_word(&cp);
430
431         if (!device)
432                 return 0;       /* Allow blank lines */
433
434         if (!mntpnt || !type)
435                 return -1;
436
437         parse_escape(device);
438         parse_escape(mntpnt);
439         parse_escape(type);
440         parse_escape(opts);
441         parse_escape(freq);
442         parse_escape(passno);
443
444         dev = blkid_get_devname(cache, device, NULL);
445         if (dev)
446                 device = dev;
447
448         if (strchr(type, ','))
449                 type = 0;
450
451         fs = create_fs_device(device, mntpnt, type ? type : "auto", opts,
452                               freq ? atoi(freq) : -1,
453                               passno ? atoi(passno) : -1);
454         if (dev)
455                 free(dev);
456
457         if (!fs)
458                 return -1;
459         *ret_fs = fs;
460         return 0;
461 }
462
463 static void interpret_type(struct fs_info *fs)
464 {
465         char    *t;
466
467         if (strcmp(fs->type, "auto") != 0)
468                 return;
469         t = blkid_get_tag_value(cache, "TYPE", fs->device);
470         if (t) {
471                 free(fs->type);
472                 fs->type = t;
473         }
474 }
475
476 /*
477  * Load the filesystem database from /etc/fstab
478  */
479 static void load_fs_info(const char *filename)
480 {
481         FILE    *f;
482         char    buf[1024];
483         int     lineno = 0;
484         int     old_fstab = 1;
485         struct fs_info *fs;
486
487         if ((f = fopen(filename, "r")) == NULL) {
488                 bb_perror_msg("WARNING: couldn't open %s", filename);
489                 return;
490         }
491         while (!feof(f)) {
492                 lineno++;
493                 if (!fgets(buf, sizeof(buf), f))
494                         break;
495                 buf[sizeof(buf)-1] = 0;
496                 if (parse_fstab_line(buf, &fs) < 0) {
497                         bb_error_msg("WARNING: bad format "
498                                 "on line %d of %s\n", lineno, filename);
499                         continue;
500                 }
501                 if (!fs)
502                         continue;
503                 if (fs->passno < 0)
504                         fs->passno = 0;
505                 else
506                         old_fstab = 0;
507         }
508
509         fclose(f);
510
511         if (old_fstab) {
512                 fputs("\007\007\007"
513                 "WARNING: Your /etc/fstab does not contain the fsck passno\n"
514                 "       field.  I will kludge around things for you, but you\n"
515                 "       should fix your /etc/fstab file as soon as you can.\n\n", stderr);
516
517                 for (fs = filesys_info; fs; fs = fs->next) {
518                         fs->passno = 1;
519                 }
520         }
521 }
522
523 /* Lookup filesys in /etc/fstab and return the corresponding entry. */
524 static struct fs_info *lookup(char *filesys)
525 {
526         struct fs_info *fs;
527
528         /* No filesys name given. */
529         if (filesys == NULL)
530                 return NULL;
531
532         for (fs = filesys_info; fs; fs = fs->next) {
533                 if (!strcmp(filesys, fs->device) ||
534                     (fs->mountpt && !strcmp(filesys, fs->mountpt)))
535                         break;
536         }
537
538         return fs;
539 }
540
541 /* Find fsck program for a given fs type. */
542 static char *find_fsck(char *type)
543 {
544   char *s;
545   const char *tpl;
546   char *p = string_copy(fsck_path);
547   struct stat st;
548
549   /* Are we looking for a program or just a type? */
550   tpl = (strncmp(type, "fsck.", 5) ? "%s/fsck.%s" : "%s/%s");
551
552   for(s = strtok(p, ":"); s; s = strtok(NULL, ":")) {
553         s = bb_xasprintf(tpl, s, type);
554         if (stat(s, &st) == 0) break;
555         free(s);
556   }
557   free(p);
558   return(s);
559 }
560
561 static int progress_active(void)
562 {
563         struct fsck_instance *inst;
564
565         for (inst = instance_list; inst; inst = inst->next) {
566                 if (inst->flags & FLAG_DONE)
567                         continue;
568                 if (inst->flags & FLAG_PROGRESS)
569                         return 1;
570         }
571         return 0;
572 }
573
574 /*
575  * Execute a particular fsck program, and link it into the list of
576  * child processes we are waiting for.
577  */
578 static int execute(const char *type, const char *device, const char *mntpt,
579                    int interactive)
580 {
581         char *s, *argv[80];
582         char *prog;
583         int  argc, i;
584         struct fsck_instance *inst, *p;
585         pid_t   pid;
586
587         inst = malloc(sizeof(struct fsck_instance));
588         if (!inst)
589                 return ENOMEM;
590         memset(inst, 0, sizeof(struct fsck_instance));
591
592         prog = bb_xasprintf("fsck.%s", type);
593         argv[0] = prog;
594         argc = 1;
595
596         for (i=0; i <num_args; i++)
597                 argv[argc++] = string_copy(args[i]);
598
599         if (progress && !progress_active()) {
600                 if ((strcmp(type, "ext2") == 0) ||
601                     (strcmp(type, "ext3") == 0)) {
602                         char tmp[80];
603                         snprintf(tmp, 80, "-C%d", progress_fd);
604                         argv[argc++] = string_copy(tmp);
605                         inst->flags |= FLAG_PROGRESS;
606                 }
607         }
608
609         argv[argc++] = string_copy(device);
610         argv[argc] = 0;
611
612         s = find_fsck(prog);
613         if (s == NULL) {
614                 bb_error_msg("%s: not found", prog);
615                 return ENOENT;
616         }
617
618         if (verbose || noexecute) {
619                 printf("[%s (%d) -- %s] ", s, num_running,
620                        mntpt ? mntpt : device);
621                 for (i=0; i < argc; i++)
622                         printf("%s ", argv[i]);
623                 printf("\n");
624         }
625
626         /* Fork and execute the correct program. */
627         if (noexecute)
628                 pid = -1;
629         else if ((pid = fork()) < 0) {
630                 perror("fork");
631                 return errno;
632         } else if (pid == 0) {
633                 if (!interactive)
634                         close(0);
635                 (void) execv(s, argv);
636                 bb_perror_msg_and_die("%s", argv[0]);
637         }
638
639         for (i = 1; i < argc; i++)
640                 free(argv[i]);
641
642         free(s);
643         inst->pid = pid;
644         inst->prog = prog;
645         inst->type = string_copy(type);
646         inst->device = string_copy(device);
647         inst->base_device = base_device(device);
648         inst->start_time = time(0);
649         inst->next = NULL;
650
651         /*
652          * Find the end of the list, so we add the instance on at the end.
653          */
654         for (p = instance_list; p && p->next; p = p->next);
655
656         if (p)
657                 p->next = inst;
658         else
659                 instance_list = inst;
660
661         return 0;
662 }
663
664 /*
665  * Send a signal to all outstanding fsck child processes
666  */
667 static int kill_all(int signum)
668 {
669         struct fsck_instance *inst;
670         int     n = 0;
671
672         for (inst = instance_list; inst; inst = inst->next) {
673                 if (inst->flags & FLAG_DONE)
674                         continue;
675                 kill(inst->pid, signum);
676                 n++;
677         }
678         return n;
679 }
680
681 /*
682  * Wait for one child process to exit; when it does, unlink it from
683  * the list of executing child processes, and return it.
684  */
685 static struct fsck_instance *wait_one(int flags)
686 {
687         int     status;
688         int     sig;
689         struct fsck_instance *inst, *inst2, *prev;
690         pid_t   pid;
691
692         if (!instance_list)
693                 return NULL;
694
695         if (noexecute) {
696                 inst = instance_list;
697                 prev = 0;
698 #ifdef RANDOM_DEBUG
699                 while (inst->next && (random() & 1)) {
700                         prev = inst;
701                         inst = inst->next;
702                 }
703 #endif
704                 inst->exit_status = 0;
705                 goto ret_inst;
706         }
707
708         /*
709          * gcc -Wall fails saving throw against stupidity
710          * (inst and prev are thought to be uninitialized variables)
711          */
712         inst = prev = NULL;
713
714         do {
715                 pid = waitpid(-1, &status, flags);
716                 if (cancel_requested && !kill_sent) {
717                         kill_all(SIGTERM);
718                         kill_sent++;
719                 }
720                 if ((pid == 0) && (flags & WNOHANG))
721                         return NULL;
722                 if (pid < 0) {
723                         if ((errno == EINTR) || (errno == EAGAIN))
724                                 continue;
725                         if (errno == ECHILD) {
726                                 bb_error_msg("wait: No more child process?!?");
727                                 return NULL;
728                         }
729                         perror("wait");
730                         continue;
731                 }
732                 for (prev = 0, inst = instance_list;
733                      inst;
734                      prev = inst, inst = inst->next) {
735                         if (inst->pid == pid)
736                                 break;
737                 }
738         } while (!inst);
739
740         if (WIFEXITED(status))
741                 status = WEXITSTATUS(status);
742         else if (WIFSIGNALED(status)) {
743                 sig = WTERMSIG(status);
744                 if (sig == SIGINT) {
745                         status = EXIT_UNCORRECTED;
746                 } else {
747                         printf("Warning... %s for device %s exited "
748                                "with signal %d.\n",
749                                inst->prog, inst->device, sig);
750                         status = EXIT_ERROR;
751                 }
752         } else {
753                 printf("%s %s: status is %x, should never happen.\n",
754                        inst->prog, inst->device, status);
755                 status = EXIT_ERROR;
756         }
757         inst->exit_status = status;
758         if (progress && (inst->flags & FLAG_PROGRESS) &&
759             !progress_active()) {
760                 for (inst2 = instance_list; inst2; inst2 = inst2->next) {
761                         if (inst2->flags & FLAG_DONE)
762                                 continue;
763                         if (strcmp(inst2->type, "ext2") &&
764                             strcmp(inst2->type, "ext3"))
765                                 continue;
766                         /*
767                          * If we've just started the fsck, wait a tiny
768                          * bit before sending the kill, to give it
769                          * time to set up the signal handler
770                          */
771                         if (inst2->start_time < time(0)+2) {
772                                 if (fork() == 0) {
773                                         sleep(1);
774                                         kill(inst2->pid, SIGUSR1);
775                                         exit(0);
776                                 }
777                         } else
778                                 kill(inst2->pid, SIGUSR1);
779                         inst2->flags |= FLAG_PROGRESS;
780                         break;
781                 }
782         }
783 ret_inst:
784         if (prev)
785                 prev->next = inst->next;
786         else
787                 instance_list = inst->next;
788         if (verbose > 1)
789                 printf("Finished with %s (exit status %d)\n",
790                        inst->device, inst->exit_status);
791         num_running--;
792         return inst;
793 }
794
795 #define FLAG_WAIT_ALL           0
796 #define FLAG_WAIT_ATLEAST_ONE   1
797 /*
798  * Wait until all executing child processes have exited; return the
799  * logical OR of all of their exit code values.
800  */
801 static int wait_many(int flags)
802 {
803         struct fsck_instance *inst;
804         int     global_status = 0;
805         int     wait_flags = 0;
806
807         while ((inst = wait_one(wait_flags))) {
808                 global_status |= inst->exit_status;
809                 free_instance(inst);
810 #ifdef RANDOM_DEBUG
811                 if (noexecute && (flags & WNOHANG) && !(random() % 3))
812                         break;
813 #endif
814                 if (flags & FLAG_WAIT_ATLEAST_ONE)
815                         wait_flags = WNOHANG;
816         }
817         return global_status;
818 }
819
820 /*
821  * Run the fsck program on a particular device
822  *
823  * If the type is specified using -t, and it isn't prefixed with "no"
824  * (as in "noext2") and only one filesystem type is specified, then
825  * use that type regardless of what is specified in /etc/fstab.
826  *
827  * If the type isn't specified by the user, then use either the type
828  * specified in /etc/fstab, or DEFAULT_FSTYPE.
829  */
830 static void fsck_device(struct fs_info *fs, int interactive)
831 {
832         const char *type;
833         int retval;
834
835         interpret_type(fs);
836
837         if (strcmp(fs->type, "auto") != 0)
838                 type = fs->type;
839         else if (fstype && strncmp(fstype, "no", 2) &&
840             strncmp(fstype, "opts=", 5) && strncmp(fstype, "loop", 4) &&
841             !strchr(fstype, ','))
842                 type = fstype;
843         else
844                 type = DEFAULT_FSTYPE;
845
846         num_running++;
847         retval = execute(type, fs->device, fs->mountpt, interactive);
848         if (retval) {
849                 bb_error_msg("Error %d while executing fsck.%s for %s",
850                                                 retval, type, fs->device);
851                 num_running--;
852         }
853 }
854
855
856 /*
857  * Deal with the fsck -t argument.
858  */
859 struct fs_type_compile {
860         char **list;
861         int *type;
862         int  negate;
863 } fs_type_compiled;
864
865 #define FS_TYPE_NORMAL  0
866 #define FS_TYPE_OPT     1
867 #define FS_TYPE_NEGOPT  2
868
869 static const char *fs_type_syntax_error =
870 N_("Either all or none of the filesystem types passed to -t must be prefixed\n"
871    "with 'no' or '!'.\n");
872
873 static void compile_fs_type(char *fs_type, struct fs_type_compile *cmp)
874 {
875         char    *cp, *list, *s;
876         int     num = 2;
877         int     negate, first_negate = 1;
878
879         if (fs_type) {
880                 for (cp=fs_type; *cp; cp++) {
881                         if (*cp == ',')
882                                 num++;
883                 }
884         }
885
886         cmp->list = xcalloc(num, sizeof(char *));
887         cmp->type = xcalloc(num, sizeof(int));
888         cmp->negate = 0;
889
890         if (!fs_type)
891                 return;
892
893         list = string_copy(fs_type);
894         num = 0;
895         s = strtok(list, ",");
896         while(s) {
897                 negate = 0;
898                 if (strncmp(s, "no", 2) == 0) {
899                         s += 2;
900                         negate = 1;
901                 } else if (*s == '!') {
902                         s++;
903                         negate = 1;
904                 }
905                 if (strcmp(s, "loop") == 0)
906                         /* loop is really short-hand for opts=loop */
907                         goto loop_special_case;
908                 else if (strncmp(s, "opts=", 5) == 0) {
909                         s += 5;
910                 loop_special_case:
911                         cmp->type[num] = negate ? FS_TYPE_NEGOPT : FS_TYPE_OPT;
912                 } else {
913                         if (first_negate) {
914                                 cmp->negate = negate;
915                                 first_negate = 0;
916                         }
917                         if ((negate && !cmp->negate) ||
918                             (!negate && cmp->negate)) {
919                                 bb_error_msg_and_die("%s", fs_type_syntax_error);
920                         }
921                 }
922 #if 0
923                 printf("Adding %s to list (type %d).\n", s, cmp->type[num]);
924 #endif
925                 cmp->list[num++] = string_copy(s);
926                 s = strtok(NULL, ",");
927         }
928         free(list);
929 }
930
931 /*
932  * This function returns true if a particular option appears in a
933  * comma-delimited options list
934  */
935 static int opt_in_list(char *opt, char *optlist)
936 {
937         char    *list, *s;
938
939         if (!optlist)
940                 return 0;
941         list = string_copy(optlist);
942
943         s = strtok(list, ",");
944         while(s) {
945                 if (strcmp(s, opt) == 0) {
946                         free(list);
947                         return 1;
948                 }
949                 s = strtok(NULL, ",");
950         }
951         free(list);
952         return 0;
953 }
954
955 /* See if the filesystem matches the criteria given by the -t option */
956 static int fs_match(struct fs_info *fs, struct fs_type_compile *cmp)
957 {
958         int n, ret = 0, checked_type = 0;
959         char *cp;
960
961         if (cmp->list == 0 || cmp->list[0] == 0)
962                 return 1;
963
964         for (n=0; (cp = cmp->list[n]); n++) {
965                 switch (cmp->type[n]) {
966                 case FS_TYPE_NORMAL:
967                         checked_type++;
968                         if (strcmp(cp, fs->type) == 0) {
969                                 ret = 1;
970                         }
971                         break;
972                 case FS_TYPE_NEGOPT:
973                         if (opt_in_list(cp, fs->opts))
974                                 return 0;
975                         break;
976                 case FS_TYPE_OPT:
977                         if (!opt_in_list(cp, fs->opts))
978                                 return 0;
979                         break;
980                 }
981         }
982         if (checked_type == 0)
983                 return 1;
984         return (cmp->negate ? !ret : ret);
985 }
986
987 /* Check if we should ignore this filesystem. */
988 static int ignore(struct fs_info *fs)
989 {
990         const char * const *ip;
991         int wanted = 0;
992         char *s;
993
994         /*
995          * If the pass number is 0, ignore it.
996          */
997         if (fs->passno == 0)
998                 return 1;
999
1000         interpret_type(fs);
1001
1002         /*
1003          * If a specific fstype is specified, and it doesn't match,
1004          * ignore it.
1005          */
1006         if (!fs_match(fs, &fs_type_compiled)) return 1;
1007
1008         /* Are we ignoring this type? */
1009         for(ip = ignored_types; *ip; ip++)
1010                 if (strcmp(fs->type, *ip) == 0) return 1;
1011
1012         /* Do we really really want to check this fs? */
1013         for(ip = really_wanted; *ip; ip++)
1014                 if (strcmp(fs->type, *ip) == 0) {
1015                         wanted = 1;
1016                         break;
1017                 }
1018
1019         /* See if the <fsck.fs> program is available. */
1020         s = find_fsck(fs->type);
1021         if (s == NULL) {
1022                 if (wanted)
1023                         bb_error_msg("cannot check %s: fsck.%s not found",
1024                                 fs->device, fs->type);
1025                 return 1;
1026         }
1027         free(s);
1028
1029         /* We can and want to check this file system type. */
1030         return 0;
1031 }
1032
1033 /*
1034  * Returns TRUE if a partition on the same disk is already being
1035  * checked.
1036  */
1037 static int device_already_active(char *device)
1038 {
1039         struct fsck_instance *inst;
1040         char *base;
1041
1042         if (force_all_parallel)
1043                 return 0;
1044
1045 #ifdef BASE_MD
1046         /* Don't check a soft raid disk with any other disk */
1047         if (instance_list &&
1048             (!strncmp(instance_list->device, BASE_MD, sizeof(BASE_MD)-1) ||
1049              !strncmp(device, BASE_MD, sizeof(BASE_MD)-1)))
1050                 return 1;
1051 #endif
1052
1053         base = base_device(device);
1054         /*
1055          * If we don't know the base device, assume that the device is
1056          * already active if there are any fsck instances running.
1057          */
1058         if (!base)
1059                 return (instance_list != 0);
1060         for (inst = instance_list; inst; inst = inst->next) {
1061                 if (!inst->base_device || !strcmp(base, inst->base_device)) {
1062                         free(base);
1063                         return 1;
1064                 }
1065         }
1066         free(base);
1067         return 0;
1068 }
1069
1070 /* Check all file systems, using the /etc/fstab table. */
1071 static int check_all(void)
1072 {
1073         struct fs_info *fs = NULL;
1074         int status = EXIT_OK;
1075         int not_done_yet = 1;
1076         int passno = 1;
1077         int pass_done;
1078
1079         if (verbose)
1080                 fputs("Checking all file systems.\n", stdout);
1081
1082         /*
1083          * Do an initial scan over the filesystem; mark filesystems
1084          * which should be ignored as done, and resolve any "auto"
1085          * filesystem types (done as a side-effect of calling ignore()).
1086          */
1087         for (fs = filesys_info; fs; fs = fs->next) {
1088                 if (ignore(fs))
1089                         fs->flags |= FLAG_DONE;
1090         }
1091
1092         /*
1093          * Find and check the root filesystem.
1094          */
1095         if (!parallel_root) {
1096                 for (fs = filesys_info; fs; fs = fs->next) {
1097                         if (!strcmp(fs->mountpt, "/"))
1098                                 break;
1099                 }
1100                 if (fs) {
1101                         if (!skip_root && !ignore(fs)) {
1102                                 fsck_device(fs, 1);
1103                                 status |= wait_many(FLAG_WAIT_ALL);
1104                                 if (status > EXIT_NONDESTRUCT)
1105                                         return status;
1106                         }
1107                         fs->flags |= FLAG_DONE;
1108                 }
1109         }
1110         /*
1111          * This is for the bone-headed user who enters the root
1112          * filesystem twice.  Skip root will skep all root entries.
1113          */
1114         if (skip_root)
1115                 for (fs = filesys_info; fs; fs = fs->next)
1116                         if (!strcmp(fs->mountpt, "/"))
1117                                 fs->flags |= FLAG_DONE;
1118
1119         while (not_done_yet) {
1120                 not_done_yet = 0;
1121                 pass_done = 1;
1122
1123                 for (fs = filesys_info; fs; fs = fs->next) {
1124                         if (cancel_requested)
1125                                 break;
1126                         if (fs->flags & FLAG_DONE)
1127                                 continue;
1128                         /*
1129                          * If the filesystem's pass number is higher
1130                          * than the current pass number, then we don't
1131                          * do it yet.
1132                          */
1133                         if (fs->passno > passno) {
1134                                 not_done_yet++;
1135                                 continue;
1136                         }
1137                         /*
1138                          * If a filesystem on a particular device has
1139                          * already been spawned, then we need to defer
1140                          * this to another pass.
1141                          */
1142                         if (device_already_active(fs->device)) {
1143                                 pass_done = 0;
1144                                 continue;
1145                         }
1146                         /*
1147                          * Spawn off the fsck process
1148                          */
1149                         fsck_device(fs, serialize);
1150                         fs->flags |= FLAG_DONE;
1151
1152                         /*
1153                          * Only do one filesystem at a time, or if we
1154                          * have a limit on the number of fsck's extant
1155                          * at one time, apply that limit.
1156                          */
1157                         if (serialize ||
1158                             (max_running && (num_running >= max_running))) {
1159                                 pass_done = 0;
1160                                 break;
1161                         }
1162                 }
1163                 if (cancel_requested)
1164                         break;
1165                 if (verbose > 1)
1166                         printf("--waiting-- (pass %d)\n", passno);
1167                 status |= wait_many(pass_done ? FLAG_WAIT_ALL :
1168                                     FLAG_WAIT_ATLEAST_ONE);
1169                 if (pass_done) {
1170                         if (verbose > 1)
1171                                 printf("----------------------------------\n");
1172                         passno++;
1173                 } else
1174                         not_done_yet++;
1175         }
1176         if (cancel_requested && !kill_sent) {
1177                 kill_all(SIGTERM);
1178                 kill_sent++;
1179         }
1180         status |= wait_many(FLAG_WAIT_ATLEAST_ONE);
1181         return status;
1182 }
1183
1184 #if 0
1185 static void usage(void)
1186 {
1187         fputs("Usage: fsck [-ANPRTV] [ -C [ fd ] ] [-t fstype] [fs-options] [filesys ...]\n", stderr);
1188         exit(EXIT_USAGE);
1189 }
1190 #endif
1191
1192 static void signal_cancel(int sig FSCK_ATTR((unused)))
1193 {
1194         cancel_requested++;
1195 }
1196
1197 static void PRS(int argc, char *argv[])
1198 {
1199         int     i, j;
1200         char    *arg, *dev, *tmp = 0;
1201         char    options[128];
1202         int     opt = 0;
1203         int     opts_for_fsck = 0;
1204         struct sigaction        sa;
1205
1206         /*
1207          * Set up signal action
1208          */
1209         memset(&sa, 0, sizeof(struct sigaction));
1210         sa.sa_handler = signal_cancel;
1211         sigaction(SIGINT, &sa, 0);
1212         sigaction(SIGTERM, &sa, 0);
1213
1214         num_devices = 0;
1215         num_args = 0;
1216         instance_list = 0;
1217
1218         for (i=1; i < argc; i++) {
1219                 arg = argv[i];
1220                 if (!arg)
1221                         continue;
1222                 if ((arg[0] == '/' && !opts_for_fsck) || strchr(arg, '=')) {
1223                         if (num_devices >= MAX_DEVICES) {
1224                                 bb_error_msg_and_die("too many devices");
1225                         }
1226                         dev = blkid_get_devname(cache, arg, NULL);
1227                         if (!dev && strchr(arg, '=')) {
1228                                 /*
1229                                  * Check to see if we failed because
1230                                  * /proc/partitions isn't found.
1231                                  */
1232                                 if (access("/proc/partitions", R_OK) < 0) {
1233                                         bb_error_msg_and_die("Couldn't open /proc/partitions: %m\n"
1234                                                         "Is /proc mounted?");
1235                                 }
1236                                 /*
1237                                  * Check to see if this is because
1238                                  * we're not running as root
1239                                  */
1240                                 if (geteuid())
1241                                         bb_error_msg_and_die(
1242                 "Must be root to scan for matching filesystems: %s\n", arg);
1243                                 else
1244                                         bb_error_msg_and_die(
1245                 "Couldn't find matching filesystem: %s", arg);
1246                         }
1247                         devices[num_devices++] = dev ? dev : string_copy(arg);
1248                         continue;
1249                 }
1250                 if (arg[0] != '-' || opts_for_fsck) {
1251                         if (num_args >= MAX_ARGS) {
1252                                 bb_error_msg_and_die("too many arguments");
1253                         }
1254                         args[num_args++] = string_copy(arg);
1255                         continue;
1256                 }
1257                 for (j=1; arg[j]; j++) {
1258                         if (opts_for_fsck) {
1259                                 options[++opt] = arg[j];
1260                                 continue;
1261                         }
1262                         switch (arg[j]) {
1263                         case 'A':
1264                                 doall++;
1265                                 break;
1266                         case 'C':
1267                                 progress++;
1268                                 if (arg[j+1]) {
1269                                         progress_fd = string_to_int(arg+j+1);
1270                                         if (progress_fd < 0)
1271                                                 progress_fd = 0;
1272                                         else
1273                                                 goto next_arg;
1274                                 } else if ((i+1) < argc &&
1275                                            !strncmp(argv[i+1], "-", 1) == 0) {
1276                                         progress_fd = string_to_int(argv[i]);
1277                                         if (progress_fd < 0)
1278                                                 progress_fd = 0;
1279                                         else {
1280                                                 goto next_arg;
1281                                                 i++;
1282                                         }
1283                                 }
1284                                 break;
1285                         case 'V':
1286                                 verbose++;
1287                                 break;
1288                         case 'N':
1289                                 noexecute++;
1290                                 break;
1291                         case 'R':
1292                                 skip_root++;
1293                                 break;
1294                         case 'T':
1295                                 notitle++;
1296                                 break;
1297                         case 'M':
1298                                 like_mount++;
1299                                 break;
1300                         case 'P':
1301                                 parallel_root++;
1302                                 break;
1303                         case 's':
1304                                 serialize++;
1305                                 break;
1306                         case 't':
1307                                 tmp = 0;
1308                                 if (fstype)
1309                                         usage();
1310                                 if (arg[j+1])
1311                                         tmp = arg+j+1;
1312                                 else if ((i+1) < argc)
1313                                         tmp = argv[++i];
1314                                 else
1315                                         usage();
1316                                 fstype = string_copy(tmp);
1317                                 compile_fs_type(fstype, &fs_type_compiled);
1318                                 goto next_arg;
1319                         case '-':
1320                                 opts_for_fsck++;
1321                                 break;
1322                         case '?':
1323                                 usage();
1324                                 break;
1325                         default:
1326                                 options[++opt] = arg[j];
1327                                 break;
1328                         }
1329                 }
1330         next_arg:
1331                 if (opt) {
1332                         options[0] = '-';
1333                         options[++opt] = '\0';
1334                         if (num_args >= MAX_ARGS) {
1335                                 bb_error_msg("too many arguments");
1336                         }
1337                         args[num_args++] = string_copy(options);
1338                         opt = 0;
1339                 }
1340         }
1341         if (getenv("FSCK_FORCE_ALL_PARALLEL"))
1342                 force_all_parallel++;
1343         if ((tmp = getenv("FSCK_MAX_INST")))
1344             max_running = atoi(tmp);
1345 }
1346
1347 int fsck_main(int argc, char *argv[])
1348 {
1349         int i, status = 0;
1350         int interactive = 0;
1351         const char *fstab;
1352         struct fs_info *fs;
1353
1354         setvbuf(stdout, NULL, _IONBF, BUFSIZ);
1355         setvbuf(stderr, NULL, _IONBF, BUFSIZ);
1356
1357         blkid_get_cache(&cache, NULL);
1358         PRS(argc, argv);
1359
1360         if (!notitle)
1361                 printf("fsck %s (%s)\n", E2FSPROGS_VERSION, E2FSPROGS_DATE);
1362
1363         fstab = getenv("FSTAB_FILE");
1364         if (!fstab)
1365                 fstab = _PATH_MNTTAB;
1366         load_fs_info(fstab);
1367
1368         e2fs_set_sbin_path();
1369
1370         if ((num_devices == 1) || (serialize))
1371                 interactive = 1;
1372
1373         /* If -A was specified ("check all"), do that! */
1374         if (doall)
1375                 return check_all();
1376
1377         if (num_devices == 0) {
1378                 serialize++;
1379                 interactive++;
1380                 return check_all();
1381         }
1382         for (i = 0 ; i < num_devices; i++) {
1383                 if (cancel_requested) {
1384                         if (!kill_sent) {
1385                                 kill_all(SIGTERM);
1386                                 kill_sent++;
1387                         }
1388                         break;
1389                 }
1390                 fs = lookup(devices[i]);
1391                 if (!fs) {
1392                         fs = create_fs_device(devices[i], 0, "auto",
1393                                               0, -1, -1);
1394                         if (!fs)
1395                                 continue;
1396                 }
1397                 fsck_device(fs, interactive);
1398                 if (serialize ||
1399                     (max_running && (num_running >= max_running))) {
1400                         struct fsck_instance *inst;
1401
1402                         inst = wait_one(0);
1403                         if (inst) {
1404                                 status |= inst->exit_status;
1405                                 free_instance(inst);
1406                         }
1407                         if (verbose > 1)
1408                                 printf("----------------------------------\n");
1409                 }
1410         }
1411         status |= wait_many(FLAG_WAIT_ALL);
1412         if (ENABLE_FEATURE_CLEAN_UP)
1413                 free(fsck_path);
1414         blkid_put_cache(cache);
1415         return status;
1416 }