xref: /csrg-svn/usr.sbin/chown/chgrp.c (revision 10426)
16392Sroot #ifndef lint
2*10426Ssam static	char *sccsid = "@(#)chgrp.c	4.4 83/01/20";
36392Sroot #endif
46392Sroot 
5974Sbill /*
6974Sbill  * chgrp gid file ...
7974Sbill  */
8974Sbill 
9974Sbill #include <stdio.h>
10974Sbill #include <ctype.h>
11974Sbill #include <sys/types.h>
12974Sbill #include <sys/stat.h>
13974Sbill #include <grp.h>
146037Swnj #include <pwd.h>
15974Sbill 
166392Sroot struct	group *gr, *getgrnam(), *getgrgid();
176392Sroot struct	passwd *getpwuid(), *pwd;
186392Sroot struct	stat stbuf;
196037Swnj int	gid, uid;
20974Sbill int	status;
216392Sroot /* VARARGS */
226392Sroot int	fprintf();
23974Sbill 
24974Sbill main(argc, argv)
256392Sroot 	int argc;
266392Sroot 	char *argv[];
27974Sbill {
286037Swnj 	register c, i;
29974Sbill 
306392Sroot 	argc--, argv++;
316392Sroot 	if (argc < 2) {
32974Sbill 		printf("usage: chgrp gid file ...\n");
336392Sroot 		exit(2);
34974Sbill 	}
356037Swnj 	uid = getuid();
366392Sroot 	if (isnumber(argv[0])) {
37*10426Ssam 		gid = atoi(argv[0]);
386392Sroot 		gr = getgrgid(gid);
396392Sroot 		if (uid && gr == NULL) {
406392Sroot 			printf("%s: unknown group\n", argv[0]);
416392Sroot 			exit(2);
426037Swnj 		}
43974Sbill 	} else {
446392Sroot 		gr = getgrnam(argv[0]);
456392Sroot 		if (gr == NULL) {
466392Sroot 			printf("%s: unknown group\n", argv[0]);
476392Sroot 			exit(2);
48974Sbill 		}
49974Sbill 		gid = gr->gr_gid;
50974Sbill 	}
516392Sroot 	pwd = getpwuid(uid);
526392Sroot 	if (pwd == NULL) {
536392Sroot 		fprintf(stderr, "Who are you?\n");
546392Sroot 		exit(2);
556037Swnj 	}
566392Sroot 	if (uid && pwd->pw_gid != gid) {
576392Sroot 		for (i=0; gr->gr_mem[i]; i++)
586392Sroot 			if (!(strcmp(pwd->pw_name, gr->gr_mem[i])))
596392Sroot 				goto ok;
606392Sroot 		fprintf(stderr, "You are not a member of the %s group.\n",
616392Sroot 		    argv[0]);
626392Sroot 		exit(2);
636037Swnj 	}
646392Sroot ok:
656392Sroot 	for (c = 1; c < argc; c++) {
666392Sroot 		if (stat(argv[c], &stbuf)) {
676392Sroot 			perror(argv[c]);
686392Sroot 			continue;
696392Sroot 		}
706037Swnj 		if (uid && uid != stbuf.st_uid) {
716392Sroot 			fprintf(stderr, "You are not the owner of %s\n",
726392Sroot 			    argv[c]);
73974Sbill 			status = 1;
746392Sroot 			continue;
756392Sroot 		}
766392Sroot 		if (chown(argv[c], stbuf.st_uid, gid))
776392Sroot 			perror(argv[c]);
78974Sbill 	}
79974Sbill 	exit(status);
80974Sbill }
81974Sbill 
82974Sbill isnumber(s)
836392Sroot 	char *s;
84974Sbill {
856392Sroot 	register int c;
86974Sbill 
876392Sroot 	while (c = *s++)
886392Sroot 		if (!isdigit(c))
896392Sroot 			return (0);
906392Sroot 	return (1);
91974Sbill }
92