blob: 13617db681088a8e5b33aa3a7b6b16a627ac82c1 [file] [log] [blame]
The Android Open Source Project13f797d2009-02-10 15:44:07 -08001#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4#include <sys/types.h>
5#include <dirent.h>
6#include <errno.h>
7#include <pwd.h>
8#include <grp.h>
9
10#include <unistd.h>
11#include <time.h>
12
13int chown_main(int argc, char **argv)
14{
15 int i;
16
17 if (argc < 3) {
18 fprintf(stderr, "Usage: chown <USER>[.GROUP] <FILE1> [FILE2] ...\n");
19 return 10;
20 }
21
22 // Copy argv[1] to 'user' so we can truncate it at the period
23 // if a group id specified.
24 char user[32];
25 char *group = NULL;
26 strncpy(user, argv[1], sizeof(user));
27 if ((group = strchr(user, '.')) != NULL) {
28 *group++ = '\0';
29 }
30
31 // Lookup uid (and gid if specified)
32 struct passwd *pw;
33 struct group *grp = NULL;
34 uid_t uid;
35 gid_t gid = -1; // passing -1 to chown preserves current group
36
37 pw = getpwnam(user);
38 if (pw == NULL) {
39 fprintf(stderr, "No such user '%s'\n", user);
40 return 10;
41 }
42 uid = pw->pw_uid;
43
44 if (group != NULL) {
45 grp = getgrnam(group);
46 if (grp == NULL) {
47 fprintf(stderr, "No such group '%s'\n", group);
48 return 10;
49 }
50 gid = grp->gr_gid;
51 }
52
53 for (i = 2; i < argc; i++) {
54 if (chown(argv[i], uid, gid) < 0) {
55 fprintf(stderr, "Unable to chmod %s: %s\n", argv[i], strerror(errno));
56 return 10;
57 }
58 }
59
60 return 0;
61}
62