chiark / gitweb /
*** empty log message ***
[userv-utils.git] / groupmanage / groupmanage
1 #!/usr/bin/perl
2 #
3 # Copyright (C) 1995-9, 2003 Ian Jackson <ijackson@chiark.greenend.org.uk>
4 # Copyright (C) 1999, 2003
5 #   Chancellor Masters and Scholars of the University of Cambridge
6 #
7 # Improved by Ben Harris <bjh21@cam.ac.uk> in 1999 and 2003 for Unix
8 # Support's own nefarious purposes.
9 #
10 # This is free software; you can redistribute it and/or modify it
11 # under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 2, or (at your option)
13 # any later version.
14 #
15 # It is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 # GNU General Public License for more details.
19 #
20 # $Id$
21
22 sub usage {
23     &unlock;
24     &p_out;
25     print(<<END) || die "groupmanage: write usage: $!\n";
26 groupmanage: $_[0]
27   usage:
28     groupmanage <groupname> [--info]
29     groupmanage <groupname> <action> [<action> ...]
30     groupmanage <groupname> --create [<action> <action> ...]
31   actions:
32        --clear
33        --add <username> <username> ...
34        --remove <username> <username> ...
35        --manager-clear
36        --manager-add <username> <username> ...
37        --manager-remove <username> <username> ...
38        --title <string>
39        --owner <username>  [root only]
40 groupmanage is Copyright.  It is free software, released under the GNU
41 GPL v2 or later.  There is NO WARRANTY.  See the GPL for details.
42 END
43     exit(1);
44 }
45
46 @ARGV || &usage('too few arguments');
47
48 if ($>) {
49     exec 'userv','root','groupmanage',@ARGV;
50     &quit("unable to execute userv to gain root privilege: $!");
51 }
52
53 chdir("/etc") || die "groupmanage: chdir /etc: $!\n";
54
55 $groupname= shift(@ARGV);
56 $groupname =~ y/\n//d;
57
58 $groupname =~ m/^\w[-0-9A-Za-z]*$/ ||
59     &quit("first argument is invalid - must be group name");
60
61 @ARGV || push(@ARGV,'--info');
62
63 $callinguser= exists $ENV{'USERV_UID'} ? $ENV{'USERV_UID'} : $<;
64
65 %opt= ('user-create','0',
66        'user-create-minunameu','5',
67        'user-create-min','10000',
68        'user-create-max','19999',
69        'user-create-nameintitle','0',
70        'user-create-maxperu','5',
71        'group-file','group',
72        'gtmp-file','gtmp',
73        'grouplist-file','grouplist',
74        'name-regexp','',
75        'admin-group','',
76        'finish-command','');
77 %ovalid=  ('user-create','boolean',
78            'user-create-minunameu','number',
79            'user-create-min','number',
80            'user-create-max','number',
81            'user-create-nameintitle','boolean',
82            'user-create-maxperu','number',
83            'group-file','string',
84            'gtmp-file','string',
85            'grouplist-file','string',
86            'name-regexp','string',
87            'admin-group','string',
88            'finish-command','string');
89
90 sub ov_boolean {
91     $cov= $_ eq 'yes' ? 1 :
92           $_ eq 'no' ? 0 :
93           &quit("groupmanage.conf:$.: bad boolean value");
94 }
95
96 sub ov_number {
97     m/^[0-9]{1,10}$/ || &quit("groupmanage.conf:$.: bad numerical value");
98 }
99
100 sub ov_string {
101
102 }
103
104 open(GMC,"groupmanage.conf") || &quit("read groupmanage.conf: $!");
105 while (<GMC>) {
106     next if m/^\#/ || !m/\S/;
107     s/\s*\n$//;
108     s/^\s*([-0-9a-z]+)\s*// || &quit("groupmanage.conf:$.: bad option format");
109     $co= $1;
110     defined($opt{$co}) || &quit("groupmanage.conf:$.: unknown option $co");
111     $cov= $_;
112     $ovf= 'ov_'.$ovalid{$co};
113     &$ovf;
114     $opt{$co}= $cov;
115 }
116 close(GMC);
117
118 if ($ARGV[0] eq '--info') {
119     @ARGV == 1 || &usage('no arguments allowed after --info');
120     &p_out;
121     &load;
122     &checkexists;
123     &display;
124     &p_out;
125     exit(0);
126 }
127
128 sub naming {
129     $callinguser || return;
130     &p_out;
131     if ($opt{'user-create-minunameu'}) {
132         print(STDERR <<END) || &quit("write err re name: $!");
133 groupmanage: groups you create must be named after you ...
134     <usernamepart>-<identifier>
135  You must quote at least $opt{'user-create-minunameu'} chars of your username $createby
136  (or all of it if it is shorter).
137 END
138     }
139     if ($opt{'name-regexp'}) {
140         print(STDERR <<END) || &quit("write err re name: $!");
141 groupmanage: groups you create must match a pattern...
142   The pattern is the Perl regular expression /$opt{'name-regexp'}/.
143 END
144     }
145     exit(1);
146 }
147
148 if ($ARGV[0] eq '--create') {
149     $opt{'user-create'} || !$callinguser ||
150         &quit("group creation by users disabled by administrator");
151     length($groupname) <= 8 || &quit("group names must be 8 chars or fewer");
152     $!=0; (@pw= getpwuid($callinguser))
153         || &quit("cannot get your passwd entry: $!");
154     $createby= $pw[0];
155     if ($opt{'user-create-minunameu'}) {
156         $groupname =~ m/^([-0-9A-Za-z]+)-([0-9a-z]+)$/ || &naming;
157         $upart= $1;
158         $idpart= $2;
159         $upart eq $createby ||
160             (length($upart) >= $opt{'user-create-minunameu'} &&
161              substr($createby,0,length($upart)) eq $upart)
162                 || &naming;
163     } else {
164         $groupname =~ m/${opt{'name-regexp'}}/ || &naming;
165     }
166     $create= 1;
167     shift(@ARGV);
168 }
169
170 &lock;
171 &load;
172
173 if ($create) {
174     $bythisowner < $opt{'user-create-maxperu'} ||
175         &quit("you already have $bythisowner group(s)");
176     $groupfileix==-1 || &quit("group already exists, cannot create it");
177     $grouplistix==-1 || &quit("group is already in grouplist, cannot create it");
178     for ($gid= $opt{'user-create-min'};
179          $gid < $opt{'user-create-max'} && defined(getgrgid($gid));
180          $gid++) { }
181     $gid <= $opt{'user-create-max'} || &quit("out of gids to use, contact admin");
182     $password=''; @members=($createby);
183     $description= "${createby}'s -- user-defined, no title";
184     $owner= $createby; @managers=(); @members= ($createby);
185     $groupfileix=$#groupfile+1;
186     $grouplistix=$#grouplist+1;
187     &p("created group $groupname");
188 } else {
189     &checkexists;
190     &p("modifying group $groupname");
191 }
192
193 &weare($owner) || grep(&weare($_),@managers) || !$callinguser ||
194     &quit("you may not manage $groupname");
195
196 $action= 'none';
197 while (@ARGV) {
198     $_= shift(@ARGV);
199     if (m/^--(add|remove)$/) {
200         $action= $1; $clist= 'members'; $what= 'member';
201     } elsif (m/^--owner$/) {
202         !$callinguser || &quit("only root may change owner");
203         @ARGV || &usage("no username owner after --owner");
204         $owner= shift(@ARGV);
205         &p("owner set to $owner");
206     } elsif (m/^--manager-(add|remove)$/) {
207         $action= $1; $clist= 'managers'; $what= 'manager';
208     } elsif (m/^--clear$/) {
209         &p('cleared list of members');
210         @members=(); $action='none'; $memc++;
211     } elsif (m/^--manager-clear$/) {
212         &p('cleared list of managers');
213         @managers=(); $action='none';
214     } elsif (m/^--title$/) {
215         &weare($owner) || !$callinguser ||
216             &quit("only group's owner ($owner) may change title");
217         @ARGV || &usage("no title after --title");
218         $_= shift(@ARGV); y/\020-\176//cd; y/:\\//d;
219         if ($opt{'user-create-nameintitle'} &&
220             $gid >= $opt{'user-create-min'} && $gid <= $opt{'user-create-max'}) {
221             $_= "${owner}'s -- $_";
222         }
223         $description= $_;
224         &p("title set to $description");
225     } elsif (m/^-/) {
226         &usage("unknown option $_");
227     } elsif (m/^\w[-0-9A-Za-z]*$/) {
228         y/\n//d;
229         $chgu=$_;
230         getpwnam($chgu) || &quit("username $chgu does not exist");
231         eval "\@l = \@$clist; 1" || &quit("internal error: $@");
232         $already= grep($_ eq $chgu, @l);
233         if ($action eq 'add') {
234             if ($already) {
235                 &p("$chgu already $what");
236             } else {
237                 &p("added $what $chgu");
238                 push(@l,$chgu);
239                 $memc+= ($clist eq 'members');
240             }
241         } elsif ($action eq 'remove') {
242             if ($already) {
243                 &p("removed $what $chgu");
244                 @l= grep($_ ne $chgu, @l);
245                 $memc+= ($clist eq 'members');
246             } else {
247                 &p("$chgu is already not $what");
248             }
249         } else {
250             &usage("username found but no action to take for them");
251         }
252         eval "\@$clist = \@l; 1" || &quit("internal error: $@");
253     } else {
254         &usage("bad username or option $_");
255     }
256 }
257 &p("nb: a change to group membership only takes effect at the user's next login")
258     if $memc;
259 $groupfile[$groupfileix]=
260     "$groupname:$password:$gid:".join(',',@members)."\n";
261 $grouplist[$grouplistix]=
262     "$groupname:$description:$owner:".join(',',@managers).":$homedir\n";
263 &save($opt{'group-file'},@groupfile);
264 &save($opt{'grouplist-file'},@grouplist);
265 if ($opt{'finish-command'}) {
266     !system($opt{'finish-command'}) || &quit("finish-command: $?");
267 }
268 unlink($opt{'gtmp-file'}) || &quit("unlock group (remove gtmp): $!");
269 &p_out;
270 exit(0);
271
272 sub load {
273     open(GF,"< $opt{'group-file'}") || &quit("read group: $!");
274     @groupfile=<GF>; close(GF);
275     $groupfileix=-1;
276     for ($i=0; $i<=$#groupfile; $i++) {
277         $_= $groupfile[$i]; s/\n$//;
278         next if m/^\#/;
279         m/^(\w[-0-9A-Za-z]*):([^:]*):(\d+):([-0-9A-Za-z,]*)$/ ||
280             &quit("bad entry in group: $_");
281         $gname2gid{$1}=$3;
282         next unless $1 eq $groupname;
283         $groupfileix<0 || &quit("duplicate entries in group");
284         $groupfileix= $i;
285         $password= $2;
286         $gid= $3;
287         @members= split(/,/,$4);
288     }
289     open(GL,"< $opt{'grouplist-file'}") || &quit("read grouplist: $!");
290     @grouplist=<GL>; close(GL);
291     $grouplistix=-1;
292     for ($i=0; $i<=$#grouplist; $i++) {
293         $_= $grouplist[$i]; s/\n$//;
294         next if m/^\#/;
295         m/^(\w[-0-9A-Za-z]*):([^:]*):(\w[-0-9A-Za-z]*):([-0-9A-Za-z,]*):([^:]*)$/ ||
296             &quit("bad entry in grouplist: $_");
297         $bythisowner++ if ($create && $3 eq $createby &&
298                            $gname2gid{$1} >= $opt{'user-create-min'} &&
299                            $gname2gid{$1} <= $opt{'user-create-max'});
300         next unless $1 eq $groupname;
301         $grouplistix<0 || &quit("duplicate entries in grouplist");
302         $grouplistix= $i;
303         $description= $2;
304         $owner= $3;
305         $homedir= $5;
306         @managers= split(/,/,$4);
307     }
308 }
309
310 sub checkexists {
311     $grouplistix>=0 || &quit("no entry in grouplist for $groupname");
312     $groupfileix>=0 || &quit("no entry in group for $groupname");
313 }
314
315 sub weare {
316     return 0 if $_[0] eq '';
317     @pw= getpwnam($_[0]);
318     return @pw && $pw[2] == $callinguser ? 1 : 0;
319 }
320
321 sub save {
322     $filename= shift(@_);
323     unlink("$filename~");
324     open(DUMP,"> $filename.new") || &quit("create new $filename: $!");
325     print(DUMP @_) || &quit("write new $filename: $!");
326     close(DUMP) || &quit("close new $filename: $!");
327     link("$filename","$filename~") || &quit("create backup $filename: $!");
328     rename("$filename.new","$filename") || &quit("install new $filename: $!");
329 }
330
331 sub quit {
332     &unlock;
333     &p_out;
334     die "groupmanage: @_\n";
335 }
336
337 sub lock {
338     link($opt{'group-file'},$opt{'gtmp-file'}) || &quit("create gtmp: $!");
339     $locked++;
340 }
341
342 sub unlock {
343     return unless $locked;
344     $locked--;
345     unlink($opt{'gtmp-file'}) || warn("unlock group file (remove gtmp): $!\n");
346 }
347
348 sub display {
349     print(<<END) || &quit("write to stdout: $!\n");
350 group       $groupname
351 gid         $gid
352 description $description
353 owner       $owner
354 managers    @managers
355 members     @members
356 homedir     $homedir
357 END
358 }
359
360 sub p_out {
361     print(STDOUT "$stdout_string") || &quit("write to stdout: $!\n");
362     $stdout_string= '';
363 }
364
365 sub p {
366     $stdout_string.= $_[0]."\n";
367 }