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