ocpasswd: added parameter to delete a user.

This commit is contained in:
Nikos Mavrogiannopoulos
2014-06-02 23:31:36 +02:00
parent f69353fedc
commit 3248651120
2 changed files with 70 additions and 0 deletions

View File

@@ -41,6 +41,13 @@ flag = {
doc = "";
};
flag = {
name = delete;
value = d;
descrip = "Delete user";
doc = "Removes the specified user from the password file";
};
flag = {
name = lock;
value = l;

View File

@@ -143,6 +143,67 @@ crypt_int(const char *fpasswd, const char *username, const char *groupname,
free(tmp_passwd);
}
static void
delete_user(const char *fpasswd, const char *username)
{
FILE * fd, *fd2;
char *tmp_passwd;
char *line, *p;
unsigned fpasswd_len = strlen(fpasswd);
unsigned tmp_passwd_len;
unsigned username_len = strlen(username);
int ret;
ssize_t len, l;
size_t line_size;
struct stat st;
tmp_passwd_len = fpasswd_len + 5;
tmp_passwd = malloc(tmp_passwd_len);
snprintf(tmp_passwd, tmp_passwd_len, "%s.tmp", fpasswd);
if (stat(tmp_passwd, &st) != -1) {
fprintf(stderr, "file '%s' is locked.\n", fpasswd);
exit(1);
}
fd = fopen(fpasswd, "r");
if (fd == NULL) {
fprintf(stderr, "Cannot open '%s' for reading.\n", fpasswd);
exit(1);
}
fd2 = fopen(tmp_passwd, "w");
if (fd2 == NULL) {
fprintf(stderr, "Cannot open '%s' for writing.\n", tmp_passwd);
exit(1);
}
line = NULL;
while ((len = getline(&line, &line_size, fd)) > 0) {
p = strchr(line, ':');
if (p == NULL)
continue;
l = p-line;
if (l == username_len && strncmp(line, username, l) == 0) {
continue;
} else {
fwrite(line, 1, len, fd2);
}
}
free(line);
fclose(fd);
fclose(fd2);
ret = rename(tmp_passwd, fpasswd);
if (ret == -1) {
fprintf(stderr, "Cannot write to '%s'.\n", fpasswd);
exit(1);
}
free(tmp_passwd);
}
static void
lock_user(const char *fpasswd, const char *username)
{
@@ -324,6 +385,8 @@ int main(int argc, char **argv)
lock_user(fpasswd, username);
else if (HAVE_OPT(UNLOCK))
unlock_user(fpasswd, username);
else if (HAVE_OPT(DELETE))
delete_user(fpasswd, username);
else { /* set password */
if (isatty(STDIN_FILENO)) {