removefile_rename_unlink.c [plain text]
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include "removefile.h"
#include "removefile_priv.h"
static int empty_directory(const char *path) {
DIR *dp;
struct dirent *de;
dp = opendir(path);
if (dp == NULL) {
return -1;
}
while ((de = readdir(dp)) != NULL) {
if (de->d_namlen < 3 && (!strcmp(de->d_name, ".") || !strcmp(de->d_name, ".."))) {
continue;
}
(void)closedir(dp);
return -1;
}
(void)closedir(dp);
return 0;
}
int
__removefile_rename_unlink(const char *path, removefile_state_t state) {
char *p, c;
struct stat statbuf;
size_t new_name_size = strlen(path) + 15;
char new_name[new_name_size];
int i = 0;
strlcpy(new_name, path, new_name_size);
if ( (p = strrchr(new_name, '/')) != NULL ) {
p++;
*p = '\0';
} else {
p = new_name;
}
do {
i = 0;
while (i < 14) {
c = __removefile_random_char(state);
if (isalnum((int) c)) {
p[i] = c;
i++;
}
}
p[i] = '\0';
} while (lstat(new_name, &statbuf) == 0);
if (lstat(path, &statbuf) == -1)
return -1;
if (S_ISDIR(statbuf.st_mode) && (empty_directory(path) == -1)) {
errno = ENOTEMPTY;
return -1;
}
if (rename(path, new_name) == -1)
return -1;
if ((state->unlink_flags & REMOVEFILE_RECURSIVE) == 0) {
sync_volume_np(new_name, 0);
}
if (lstat(new_name, &statbuf) == -1) {
errno = ENOENT;
return -1;
}
if (S_ISDIR(statbuf.st_mode))
return rmdir(new_name);
return unlink(new_name);
}