121 lines
2.3 KiB
C
121 lines
2.3 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <unistd.h>
|
|
#include <dirent.h>
|
|
#include <sys/stat.h>
|
|
#include "make_path.h"
|
|
#include "get_stat.h"
|
|
#include "parse_mode.h"
|
|
|
|
int (*get_stat)(const char *prog_name, const char *path, struct stat *stat_path);
|
|
unsigned int r_flag;
|
|
unsigned int s_flag;
|
|
|
|
int change(const char *file, const char *mode_arg) {
|
|
struct stat old_file;
|
|
if (get_stat("chmod", file, &old_file))
|
|
return 1;
|
|
|
|
mode_t mode = mu_parse_mode(mode_arg, old_file.st_mode);
|
|
if (chmod(file, mode) == 0) {
|
|
struct stat new_file;
|
|
if (get_stat("chmod", file, &new_file))
|
|
return 1;
|
|
|
|
if (old_file.st_mode != new_file.st_mode)
|
|
return 0;
|
|
|
|
if (!s_flag)
|
|
fprintf(stderr, "chmod: %s unchanged\n", file);
|
|
|
|
return 1;
|
|
}
|
|
|
|
else
|
|
fprintf(stderr, "chmod: unable to chown %s: %s\n", file, strerror(errno));
|
|
|
|
return 0;
|
|
}
|
|
|
|
int chtree(const char *dst, const char *mode_arg) {
|
|
int ret = change(dst, mode_arg);
|
|
|
|
struct stat stat_path;
|
|
if (get_stat("chmod", 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("chmod", dst, ep->d_name);
|
|
if (full_path == NULL)
|
|
continue;
|
|
|
|
if (chtree(full_path, mode_arg))
|
|
ret = 1;
|
|
|
|
free(full_path);
|
|
}
|
|
|
|
closedir(dir);
|
|
return ret;
|
|
}
|
|
|
|
int main(int argc, char **argv) {
|
|
int i;
|
|
|
|
get_stat = mu_get_lstat;
|
|
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") || !strcmp(argv[i], "-f"))
|
|
s_flag = 1;
|
|
|
|
else if (!strcmp(argv[i], "-H"))
|
|
get_stat = mu_get_stat;
|
|
|
|
else if (!strcmp(argv[i], "--help")) {
|
|
printf("chmod [-H if a command line argument is a symbolic link] [-r recursive] [-s silent] [ugoa]{+|-|=}[rwxXst] / [sstrwxrwxrwx] [file1 file2...]\n");
|
|
return 0;
|
|
}
|
|
|
|
if (argc - i <= 2)
|
|
break;
|
|
}
|
|
|
|
if (argc - i < 2) {
|
|
fprintf(stderr, "chmod: missing operand\n");
|
|
return 1;
|
|
}
|
|
|
|
char *mode_arg = argv[i];
|
|
argv++;
|
|
argc--;
|
|
|
|
int ret = 0;
|
|
for (; i < argc; i++)
|
|
if (chtree(argv[i], mode_arg))
|
|
ret = 1;
|
|
|
|
return ret;
|
|
}
|
|
|
|
|