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