#include <sys/cdefs.h>
#ifndef lint
__RCSID("$NetBSD: check.c,v 1.20 2022/08/28 10:20:25 mlelstv Exp $");
#endif
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include "ext.h"
#include "fsutil.h"
#include "exitvalues.h"
int
checkfilesys(const char *filename)
{
int dosfs;
struct bootblock boot;
struct fatEntry *fat = NULL;
int finish_dosdirsection=0;
u_int i;
int mod = 0;
int ret = FSCK_EXIT_CHECK_FAILED;
rdonly = alwaysno;
if (!preen)
printf("** %s", filename);
dosfs = open(filename, rdonly ? O_RDONLY : O_RDWR, 0);
if (dosfs < 0 && !rdonly) {
dosfs = open(filename, O_RDONLY, 0);
if (dosfs >= 0)
pwarn(" (NO WRITE)\n");
else if (!preen)
printf("\n");
rdonly = 1;
} else if (!preen)
printf("\n");
if (dosfs < 0) {
perr("Can't open `%s'", filename);
return FSCK_EXIT_CHECK_FAILED;
}
mod = readboot(dosfs, &boot);
if (mod & FSFATAL) {
close(dosfs);
printf("\n");
return FSCK_EXIT_CHECK_FAILED;
}
if (!preen) {
if (boot.ValidFat < 0)
printf("** Phase 1 - Read and Compare FATs\n");
else
printf("** Phase 1 - Read FAT\n");
}
mod |= readfat(dosfs, &boot, boot.ValidFat >= 0 ? boot.ValidFat : 0, &fat);
if (mod & FSFATAL) {
close(dosfs);
return FSCK_EXIT_CHECK_FAILED;
}
if (boot.ValidFat < 0)
for (i = 1; i < boot.FATs; i++) {
struct fatEntry *currentFat;
mod |= readfat(dosfs, &boot, i, ¤tFat);
if (mod & FSFATAL)
goto out;
mod |= comparefat(&boot, fat, currentFat, i);
free(currentFat);
if (mod & FSFATAL)
goto out;
}
if (!preen)
printf("** Phase 2 - Check Cluster Chains\n");
mod |= checkfat(&boot, fat);
if (mod & FSFATAL)
goto out;
if (!preen)
printf("** Phase 3 - Checking Directories\n");
mod |= resetDosDirSection(&boot, fat);
finish_dosdirsection = 1;
if (mod & FSFATAL)
goto out;
mod |= handleDirTree(dosfs, &boot, fat);
if (mod & FSFATAL)
goto out;
if (!preen)
printf("** Phase 4 - Checking for Lost Files\n");
mod |= checklost(dosfs, &boot, fat);
if (mod & FSFATAL)
goto out;
if (mod & (FSFATMOD|FSFIXFAT)) {
if (ask(1, "Update FATs")) {
mod |= writefat(dosfs, &boot, fat, mod & FSFIXFAT);
if (mod & FSFATAL)
goto out;
} else
mod |= FSERROR;
}
if (boot.NumBad)
pwarn("%d files, %d free (%d clusters), %d bad (%d clusters)\n",
boot.NumFiles,
boot.NumFree * boot.ClusterSize / 1024, boot.NumFree,
boot.NumBad * boot.ClusterSize / 1024, boot.NumBad);
else
pwarn("%d files, %d free (%d clusters)\n",
boot.NumFiles,
boot.NumFree * boot.ClusterSize / 1024, boot.NumFree);
if (mod && (mod & FSERROR) == 0) {
if (mod & FSDIRTY) {
if (ask(1, "MARK FILE SYSTEM CLEAN") == 0)
mod &= ~FSDIRTY;
if (mod & FSDIRTY) {
pwarn("MARKING FILE SYSTEM CLEAN\n");
mod |= writefat(dosfs, &boot, fat, 1);
} else {
pwarn("\n***** FILE SYSTEM IS LEFT MARKED AS DIRTY *****\n");
mod |= FSERROR;
}
}
}
if (mod & (FSFATAL | FSERROR))
goto out;
ret = FSCK_EXIT_OK;
out:
if (finish_dosdirsection)
finishDosDirSection();
free(fat);
close(dosfs);
if (mod & (FSFATMOD|FSDIRMOD))
pwarn("\n***** FILE SYSTEM WAS MODIFIED *****\n");
return ret;
}