Skip to content

Commit

Permalink
Make a backup of the crontab file on deletion
Browse files Browse the repository at this point in the history
  • Loading branch information
iTrooz committed Dec 16, 2022
1 parent debc8db commit 8d65772
Showing 1 changed file with 49 additions and 5 deletions.
54 changes: 49 additions & 5 deletions src/crontab.c
Original file line number Diff line number Diff line change
Expand Up @@ -464,7 +464,11 @@ static void list_cmd(void) {
}

static void delete_cmd(void) {
char n[MAX_FNAME] = "";
char n[MAX_FNAME] = "", BackupFilename[MAX_FNAME];
int t;
FILE *CrontabFile;
FILE *BackupFile;

if (PromptOnDelete == 1) {
printf("crontab: really delete %s's crontab? ", User);
fflush(stdout);
Expand All @@ -479,13 +483,53 @@ static void delete_cmd(void) {
fprintf(stderr, "path too long\n");
exit(ERROR_EXIT);
}
if (unlink(n) != 0) {
if (errno == ENOENT)
fprintf(stderr, "no crontab for %s\n", User);
else
if (!glue_strings(BackupFilename, sizeof Filename, tmp_path(),
"crontab.XXXXXX", '/')) {
fprintf(stderr, "path too long\n");
exit(ERROR_EXIT);
}

if (!(CrontabFile = fopen(n, "r"))) {
if (errno != ENOENT) {
perror(n);
exit(ERROR_EXIT);
}
fprintf(stderr, "no crontab for %s\n", User);
exit(ERROR_EXIT);
}

if (swap_uids() == -1) {
perror("swapping uids");
exit(ERROR_EXIT);
}
if (-1 == (t = mkstemp(BackupFilename))) {
perror(BackupFilename);
exit(ERROR_EXIT);
}
if (swap_uids_back() < OK) {
perror("swapping uids back");
exit(ERROR_EXIT);
}

if (!(BackupFile = fdopen(t, "r+"))) {
perror("fdopen");
exit(ERROR_EXIT);
}

int ch = '\0';
if (EOF != ch)
while (EOF != (ch = get_char(CrontabFile)))
putc(ch, BackupFile);

fclose(CrontabFile);
fclose(BackupFile);

if (unlink(n) != 0) {
perror(n);
exit(ERROR_EXIT);
}
fprintf(stderr, "Deleted crontab for user %s.\nBackup is saved at %s\n", User, BackupFilename);

poke_daemon();
}

Expand Down

0 comments on commit 8d65772

Please sign in to comment.