morpheus-base

morpheus base system
git clone git://git.2f30.org/morpheus-base.git
Log | Files | Refs

chown.c (1500B)


      1 /* See LICENSE file for copyright and license details. */
      2 #include <errno.h>
      3 #include <grp.h>
      4 #include <pwd.h>
      5 #include <stdlib.h>
      6 #include <string.h>
      7 #include <unistd.h>
      8 
      9 #include "util.h"
     10 
     11 static void chownpwgr(const char *);
     12 
     13 static int rflag = 0;
     14 static uid_t uid = -1;
     15 static gid_t gid = -1;
     16 static int ret = 0;
     17 
     18 static void
     19 usage(void)
     20 {
     21 	eprintf("usage: %s [-Rr] [owner][:[group]] file...\n", argv0);
     22 }
     23 
     24 int
     25 main(int argc, char *argv[])
     26 {
     27 	char *owner, *group, *end;
     28 	struct passwd *pw;
     29 	struct group *gr;
     30 
     31 	ARGBEGIN {
     32 	case 'R':
     33 	case 'r':
     34 		rflag = 1;
     35 		break;
     36 	default:
     37 		usage();
     38 	} ARGEND;
     39 
     40 	if (argc == 0)
     41 		usage();
     42 
     43 	owner = argv[0];
     44 	argv++;
     45 	argc--;
     46 	if ((group = strchr(owner, ':')))
     47 		*group++ = '\0';
     48 
     49 	if (owner && *owner) {
     50 		errno = 0;
     51 		pw = getpwnam(owner);
     52 		if (pw) {
     53 			uid = pw->pw_uid;
     54 		} else {
     55 			if (errno != 0)
     56 				eprintf("getpwnam %s:", owner);
     57 			uid = strtoul(owner, &end, 10);
     58 			if (*end != '\0')
     59 				eprintf("getpwnam %s: no such user\n", owner);
     60 		}
     61 	}
     62 	if (group && *group) {
     63 		errno = 0;
     64 		gr = getgrnam(group);
     65 		if (gr) {
     66 			gid = gr->gr_gid;
     67 		} else {
     68 			if (errno != 0)
     69 				eprintf("getgrnam %s:", group);
     70 			gid = strtoul(group, &end, 10);
     71 			if (*end != '\0')
     72 				eprintf("getgrnam %s: no such group\n", group);
     73 		}
     74 	}
     75 	for (; argc > 0; argc--, argv++)
     76 		chownpwgr(argv[0]);
     77 
     78 	return ret;
     79 }
     80 
     81 void
     82 chownpwgr(const char *path)
     83 {
     84 	if (chown(path, uid, gid) < 0) {
     85 		weprintf("chown %s:", path);
     86 		ret = 1;
     87 	}
     88 	if (rflag)
     89 		recurse(path, chownpwgr);
     90 }