xref: /csrg-svn/usr.sbin/chown/chgrp.c (revision 15583)
16392Sroot #ifndef lint
2*15583Smckusick static	char *sccsid = "@(#)chgrp.c	4.7 83/11/23";
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;
2112075Sralph int	fflag;
226392Sroot /* VARARGS */
236392Sroot int	fprintf();
24974Sbill 
25974Sbill main(argc, argv)
266392Sroot 	int argc;
276392Sroot 	char *argv[];
28974Sbill {
296037Swnj 	register c, i;
30974Sbill 
316392Sroot 	argc--, argv++;
3212075Sralph 	if (argc > 0 && strcmp(argv[0], "-f") == 0) {
3312075Sralph 		fflag++;
3412075Sralph 		argv++, argc--;
3512075Sralph 	}
366392Sroot 	if (argc < 2) {
3712075Sralph 		printf("usage: chgrp [-f] gid file ...\n");
386392Sroot 		exit(2);
39974Sbill 	}
406037Swnj 	uid = getuid();
416392Sroot 	if (isnumber(argv[0])) {
4210426Ssam 		gid = atoi(argv[0]);
436392Sroot 		gr = getgrgid(gid);
446392Sroot 		if (uid && gr == NULL) {
456392Sroot 			printf("%s: unknown group\n", argv[0]);
466392Sroot 			exit(2);
476037Swnj 		}
48974Sbill 	} else {
496392Sroot 		gr = getgrnam(argv[0]);
506392Sroot 		if (gr == NULL) {
516392Sroot 			printf("%s: unknown group\n", argv[0]);
526392Sroot 			exit(2);
53974Sbill 		}
54974Sbill 		gid = gr->gr_gid;
55974Sbill 	}
566392Sroot 	pwd = getpwuid(uid);
576392Sroot 	if (pwd == NULL) {
586392Sroot 		fprintf(stderr, "Who are you?\n");
596392Sroot 		exit(2);
606037Swnj 	}
616392Sroot 	if (uid && pwd->pw_gid != gid) {
626392Sroot 		for (i=0; gr->gr_mem[i]; i++)
636392Sroot 			if (!(strcmp(pwd->pw_name, gr->gr_mem[i])))
646392Sroot 				goto ok;
6512075Sralph 		if (fflag)
6612075Sralph 			exit(0);
676392Sroot 		fprintf(stderr, "You are not a member of the %s group.\n",
686392Sroot 		    argv[0]);
696392Sroot 		exit(2);
706037Swnj 	}
716392Sroot ok:
726392Sroot 	for (c = 1; c < argc; c++) {
73*15583Smckusick 		if (lstat(argv[c], &stbuf)) {
746392Sroot 			perror(argv[c]);
756392Sroot 			continue;
766392Sroot 		}
776037Swnj 		if (uid && uid != stbuf.st_uid) {
7812075Sralph 			if (fflag)
7912075Sralph 				continue;
806392Sroot 			fprintf(stderr, "You are not the owner of %s\n",
816392Sroot 			    argv[c]);
82974Sbill 			status = 1;
836392Sroot 			continue;
846392Sroot 		}
8512362Smckusick 		if (chown(argv[c], stbuf.st_uid, gid) && !fflag)
866392Sroot 			perror(argv[c]);
87974Sbill 	}
88974Sbill 	exit(status);
89974Sbill }
90974Sbill 
91974Sbill isnumber(s)
926392Sroot 	char *s;
93974Sbill {
946392Sroot 	register int c;
95974Sbill 
966392Sroot 	while (c = *s++)
976392Sroot 		if (!isdigit(c))
986392Sroot 			return (0);
996392Sroot 	return (1);
100974Sbill }
101