micro-utils/coreutils/chown.c

134 lines
2.4 KiB
C
Raw Normal View History

2023-10-27 19:55:18 +03:00
#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 <sys/stat.h>
2023-10-28 09:11:02 +03:00
unsigned int r_flag;
2023-10-27 19:55:18 +03:00
int (*chown_func)(const char *pathname, uid_t owner, gid_t group);
2023-10-28 09:11:02 +03:00
int (*stat_func)(const char *restrict pathname, struct stat *restrict statbuf);
2023-10-27 19:55:18 +03:00
long gid;
long uid;
2023-10-28 09:11:02 +03:00
int get_stat(const char *path, struct stat *stat_path) {
if (stat_func(path, stat_path)) {
fprintf(stderr, "chown: unable to stat %s: %s\n", path, strerror(errno));
return 1;
}
return 0;
}
int change(const char *file) {
struct stat old_file;
if (get_stat(file, &old_file))
return 1;
if (chown_func(file, uid, gid) == 0) {
struct stat new_file;
if (get_stat(file, &new_file))
return 1;
if (old_file.st_gid != new_file.st_gid || old_file.st_uid != new_file.st_uid)
return 0;
fprintf(stderr, "chown: %s unchanged\n", file);
}
else
fprintf(stderr, "chown: unable to stat %s: %s\n", file, strerror(errno));
return 1;
}
2023-10-27 19:55:18 +03:00
int cntree(const char *dst) {
2023-10-28 09:11:02 +03:00
change(dst);
2023-10-27 19:55:18 +03:00
2023-10-28 09:11:02 +03:00
//Recurs
2023-10-27 19:55:18 +03:00
return 0;
}
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) {
fprintf(stderr, "chown: invalid group: %s\n", group);
exit(1);
}
gid = grp->gr_gid;
}
if (u_flag) {
struct passwd *pwd = getpwnam(arg);
if (!pwd) {
fprintf(stderr, "chown: invalid user: %s\n", arg);
exit(1);
}
uid = pwd->pw_gid;
}
}
int main(const int argc, char **argv) {
chown_func = lchown;
2023-10-28 09:11:02 +03:00
stat_func = stat;
2023-10-27 19:55:18 +03:00
int i;
for (i = 1; i < argc; i++) {
if (argv[i][0] != '-')
break;
2023-10-28 09:11:02 +03:00
else if (!strcmp(argv[i], "-r"))
r_flag = 1;
else if (!strcmp(argv[i], "-H")) {
2023-10-27 19:55:18 +03:00
chown_func = chown;
2023-10-28 09:11:02 +03:00
stat_func = stat;
}
2023-10-27 19:55:18 +03:00
else if (!strcmp(argv[i], "--help")) {
2023-10-28 09:11:02 +03:00
printf("chown [-H (if a command line argument is a symbolic link)] [-r (recursive)] [owner]:[group] [file file2...]\n");
2023-10-27 19:55:18 +03:00
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;
}