xref: /original-bsd/usr.sbin/chown/chgrp.c (revision b3b53e97)
1 #ifndef lint
2 static	char *sccsid = "@(#)chgrp.c	4.3 82/03/31";
3 #endif
4 
5 /*
6  * chgrp gid file ...
7  */
8 
9 #include <stdio.h>
10 #include <ctype.h>
11 #include <sys/types.h>
12 #include <sys/stat.h>
13 #include <grp.h>
14 #include <pwd.h>
15 
16 struct	group *gr, *getgrnam(), *getgrgid();
17 struct	passwd *getpwuid(), *pwd;
18 struct	stat stbuf;
19 int	gid, uid;
20 int	status;
21 /* VARARGS */
22 int	fprintf();
23 
24 main(argc, argv)
25 	int argc;
26 	char *argv[];
27 {
28 	register c, i;
29 
30 	argc--, argv++;
31 	if (argc < 2) {
32 		printf("usage: chgrp gid file ...\n");
33 		exit(2);
34 	}
35 	uid = getuid();
36 	if (isnumber(argv[0])) {
37 		gid = atoi(argv[1]);
38 		gr = getgrgid(gid);
39 		if (uid && gr == NULL) {
40 			printf("%s: unknown group\n", argv[0]);
41 			exit(2);
42 		}
43 	} else {
44 		gr = getgrnam(argv[0]);
45 		if (gr == NULL) {
46 			printf("%s: unknown group\n", argv[0]);
47 			exit(2);
48 		}
49 		gid = gr->gr_gid;
50 	}
51 	pwd = getpwuid(uid);
52 	if (pwd == NULL) {
53 		fprintf(stderr, "Who are you?\n");
54 		exit(2);
55 	}
56 	if (uid && pwd->pw_gid != gid) {
57 		for (i=0; gr->gr_mem[i]; i++)
58 			if (!(strcmp(pwd->pw_name, gr->gr_mem[i])))
59 				goto ok;
60 		fprintf(stderr, "You are not a member of the %s group.\n",
61 		    argv[0]);
62 		exit(2);
63 	}
64 ok:
65 	for (c = 1; c < argc; c++) {
66 		if (stat(argv[c], &stbuf)) {
67 			perror(argv[c]);
68 			continue;
69 		}
70 		if (uid && uid != stbuf.st_uid) {
71 			fprintf(stderr, "You are not the owner of %s\n",
72 			    argv[c]);
73 			status = 1;
74 			continue;
75 		}
76 		if (chown(argv[c], stbuf.st_uid, gid))
77 			perror(argv[c]);
78 	}
79 	exit(status);
80 }
81 
82 isnumber(s)
83 	char *s;
84 {
85 	register int c;
86 
87 	while (c = *s++)
88 		if (!isdigit(c))
89 			return (0);
90 	return (1);
91 }
92