summaryrefslogtreecommitdiff
path: root/command/chown.c
blob: 7f9cb0f509f3e42cddd8d63d2ca02c0576451705 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
/**
 *  file: chown.c
 *  author: Tyler Murphy
 */

#include "command.h"
#include "lslib.h"

#include <dirent.h>
#include <grp.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <pwd.h>

/**
 * File flags to be used with chown
 */
static struct {
    bool recurse;       /* -R if to recurse directorys */
    bool list_changed;  /* -c if to list what was changed */
    bool verbose;       /* -v if to list all output */
    bool quiet;         /* -f if to silence errors */
    uid_t uid;          /* the uid to set the file to */
    gid_t gid;          /* the gid to set the file to */
} flags;

/**
 * Help function for chown
 */
static void help (void) {
    printf("Usage: chown [-Rcvf]... USER[:[GRP]] FILE...\n\n");
    printf("Change the owner and/or group of FILEs to USER and/or GRP\n\n");
    printf("\t-R\tRecurse\n");
	printf("\t-c\tList changed files\n");
	printf("\t-v\tVerbose\n");
	printf("\t-f\tHide errors\n");
}

/** 
 * Takes in each argument that has a single - and parses it 
 * @param c the character after the -
 * @param next the next argument in argv that hasnt been parsed
 * @reutrn if the next arg was used or if the arg was invalid
 */
static int short_arg(char c, char* next) {
    UNUSED(next);
    switch (c) {
        case 'R':
            flags.recurse = true;
            break;
        case 'c':
            flags.list_changed = true;
            break;
        case 'v':
            flags.verbose = true;
            break;
        case 'f':
            flags.quiet = true;
            break;
        default:
            return ARG_INVALID;
    }
    return ARG_UNUSED;
}

/**
 * Given a file path change the filw ownership with the given flags
 * @param path the file to change the ownership
 */
static void chown_file(char* path) {

    /* allocate arguments on the stack */
    int save; /* path buffer save */
    struct stat s; /* file stats */
    DIR* d; /* recursing dir if recursing */
    struct dirent* file; /*if recursing current file being read */

    save = push_path_buffer(path);
    
    /* attempt to change file ownership, if failed error and return */
    if (chown(get_path_buffer(), flags.uid, flags.gid) < 0) {
        if (!flags.quiet) {
            error_s("cannot chown '%s'", get_path_buffer()); /* error if failed */
        }
        pop_path_buffer(save); /* cleanup */
        return;
    } else if (flags.list_changed) { /* list changed if verbose */
        output("changed '%s' to %u:%u", get_path_buffer(), flags.uid, flags.gid);
    }

    /* if not recurse dont do future checks and return */
    if (!flags.recurse) {
        pop_path_buffer(save);
        return;
    }

    /* stat file info and return if failed */
    if (lstat(get_path_buffer(), &s) < 0) {
        if (!flags.quiet) {
            error_s("cannot stat '%s'", get_path_buffer()); /* error if failed */
        }
        pop_path_buffer(save); /* clean up */
        return;
    }

    /* if not dir, cannot recurse so return */
    if (!S_ISDIR(s.st_mode)) {
        pop_path_buffer(save); /* clean up */
        return;
    }

    /* open dir, if failed return and error */
    d = opendir(get_path_buffer());
    if (d == NULL) {
        if (!flags.quiet) {
            error_s("cannot open dir '%s'", get_path_buffer()); /* error if failed */
        }
        pop_path_buffer(save); /* clean up */
        return;
    }

    /* read each file in directory, and modify its ownership recursivly */
    while ((file = readdir(d)) != NULL) {
        if (is_dot_dir(file->d_name)) continue; /* if dot dir skip */
        chown_file(file->d_name);
    }
    
    /* clean up */
    closedir(d);
    pop_path_buffer(save);
}

/** 
 * Parse a given user and group from a string
 * @param str the stirng to parse
 */
static void parse_ownership(char* str) {
    char* user = str; /* a copy of the input string */
    char* group = NULL; /* the group name found in str */
    char* end = NULL; /* the end of a string to parse a number if passed */
    unsigned long i; /* a number i */
    struct passwd* p = NULL; /* a user if found */
    struct group* g = NULL; /* a group if found */
    
    /* attempy to find a colon seperating the user and group in the string, if not parse it as a user only */
    for (i = 0; i < strlen(str); i++) {
        if (str[i] == ':') {
            str[i] = '\0';
            group = &str[i] + 1;
            break;
        }
    }

    /* attempt to parse input as a number */
    flags.uid = strtol(user, &end, 10);
    if (end != user) goto group; /* if successfull they ave a direct uid */

    /* if not try to get the user by the string */
    if ((p = getpwnam(user)) == NULL) {
        error("invalid user '%s'", user); /* error and abort if failed */
    } else {
        flags.uid = p->pw_uid; /* update flags */
    }

group:

    /* if the group string was not found set the gorup to the user */
    if (group == NULL) {
        if (p == NULL) {
            flags.gid = flags.uid; /* if a int was passed set that int to the group as well */
        } else {
            flags.gid = p->pw_gid; /* if a user was passed set the group to the users gid */
        }
        return;
    }

    /* if a group was passed, attempt to parse it as a gid first */
    flags.gid = strtol(group, &end, 10);
    if (end != group) return; /* if succssfull return were done */

    /* otherwise try to get the group from the name */
    if ((g = getgrnam(group)) == NULL) {
        error("invalid group '%s'", group); /* error and abort if failed */
    } else {
        flags.gid = g->gr_gid; /* update gid */
    }
}

COMMAND(chown_main) {

    int start, i;
    
    /* set default flags for chown */
    flags.recurse = false;
    flags.list_changed = false;
    flags.verbose = false;
    flags.quiet = false;

    /* parse argument */
    start = parse_args(argc, argv, help, short_arg, NULL);

    /* if no more arguments error and abort since no ownership passed */
    if (argc - start < 1) {
        if (!flags.quiet) { /* if not set to hide errors */
            error("no onwership passed");
        } else {
            return EXIT_FAILURE;
        }
    }

    parse_ownership(argv[start]);

    /* if not more arugumnets error and abort since no files passed */
    if (argc - start < 1) {
        if (!flags.quiet) { /* if not set to hide errors */
            error("no files passed"); 
        } else {
            return EXIT_FAILURE;
        }
    }

    /* change ownership for each file passed */
    for (i = start + 1; i < argc; i++) {
        chown_file(argv[i]);
    }

    return EXIT_SUCCESS; /* done */
}