micro-utils/coreutils/chown.c
2023-11-06 23:00:26 +03:00

154 lines
2.6 KiB
C

#include <pwd.h>
#include <grp.h>
#include <stdio.h>
#include <errno.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include "make_path.h"
#include "get_stat.h"
unsigned int r_flag;
unsigned int s_flag;
int (*get_stat)(const char *prog_name, const char *path, struct stat *stat_path);
int (*chown_func)(const char *pathname, uid_t owner, gid_t group);
long gid;
long uid;
int change(const char *file) {
if (chown_func(file, uid, gid)) {
if (!s_flag)
fprintf(stderr, "chown: unable to chown %s: %s\n", file, strerror(errno));
return 1;
}
return 0;
}
int cntree(const char *dst) {
int ret = change(dst);
struct stat stat_path;
if (get_stat("chown", dst, &stat_path))
return 1;
if (!S_ISDIR(stat_path.st_mode) || !r_flag)
return ret;
DIR *dir = opendir(dst);
if (dir == NULL) {
if (!s_flag)
fprintf(stderr, "chown: %s: Can`t open directory\n", dst);
return 1;
}
struct dirent *ep;
while ((ep = readdir(dir)) != NULL) {
if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
continue;
char *full_path = mu_make_path("chown", dst, ep->d_name);
if (full_path == NULL)
continue;
if (cntree(full_path))
ret = 1;
free(full_path);
}
closedir(dir);
return ret;
}
void get_owner(const char *arg) {
char *group = strchr(arg, ':');
unsigned int g_flag = 1;
unsigned int u_flag = 1;
if (group == arg)
u_flag = 0;
else if (!group)
g_flag = 0;
if (g_flag) {
group[0] = '\0';
group++;
struct group *grp = getgrnam(group);
if (!grp) {
if (!s_flag)
fprintf(stderr, "chown: invalid group: %s\n", group);
exit(1);
}
gid = grp->gr_gid;
}
if (u_flag) {
struct passwd *pwd = getpwnam(arg);
if (!pwd) {
if (!s_flag)
fprintf(stderr, "chown: invalid user: %s\n", arg);
exit(1);
}
uid = pwd->pw_gid;
}
}
int main(const int argc, char **argv) {
get_stat = mu_get_lstat;
chown_func = lchown;
int i;
for (i = 1; i < argc; i++) {
if (argv[i][0] != '-')
break;
else if (!strcmp(argv[i], "-r"))
r_flag = 1;
else if (!strcmp(argv[i], "-s"))
s_flag = 1;
else if (!strcmp(argv[i], "-H")) {
chown_func = chown;
get_stat = mu_get_stat;
}
else if (!strcmp(argv[i], "--help")) {
printf("chown [group] [file1 file2...]\n\t[-H if a command line argument is a symbolic link]\n\t[-r recursive]\n");
return 0;
}
}
if (argc - i == 0) {
fprintf(stderr, "chown: missing operand\n");
return 1;
}
gid = -1;
uid = -1;
get_owner(argv[i++]);
if (argc - i == 0) {
fprintf(stderr, "chown: missing operand\n");
return 1;
}
int ret = 0;
for (; i < argc; i++)
if (cntree(argv[i]))
ret = 1;
return ret;
}