1 #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 13 int 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 uid = pw->pw_uid; 40 } else { 41 char* endptr; 42 uid = (int) strtoul(user, &endptr, 0); 43 if (endptr == user) { // no conversion 44 fprintf(stderr, "No such user '%s'\n", user); 45 return 10; 46 } 47 } 48 49 if (group != NULL) { 50 grp = getgrnam(group); 51 if (grp != NULL) { 52 gid = grp->gr_gid; 53 } else { 54 char* endptr; 55 gid = (int) strtoul(group, &endptr, 0); 56 if (endptr == group) { // no conversion 57 fprintf(stderr, "No such group '%s'\n", group); 58 return 10; 59 } 60 } 61 } 62 63 for (i = 2; i < argc; i++) { 64 if (chown(argv[i], uid, gid) < 0) { 65 fprintf(stderr, "Unable to chmod %s: %s\n", argv[i], strerror(errno)); 66 return 10; 67 } 68 } 69 70 return 0; 71 } 72