summaryrefslogtreecommitdiff
path: root/groupmanage/groupmanage
blob: 24c007b72858b84656fc7349fa957af0f26bfffd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
#!/usr/bin/perl
#
# Copyright 1996-2013 Ian Jackson <ijackson@chiark.greenend.org.uk>
# Copyright 1998 David Damerell <damerell@chiark.greenend.org.uk>
# Copyright 1999,2003
#    Chancellor Masters and Scholars of the University of Cambridge
# Copyright 2010 Tony Finch <fanf@dotat.at>
#
# This is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with userv-utils; if not, see http://www.gnu.org/licenses/.

sub usage {
    &unlock;
    &p_out;
    print(<<END) || die "groupmanage: write usage: $!\n";
groupmanage: $_[0]
  usage:
    groupmanage <groupname> [--info]
    groupmanage <groupname> <action> [<action> ...]
    groupmanage <groupname> --create [<action> <action> ...]
  actions:
       --clear
       --add <username> <username> ...
       --remove <username> <username> ...
       --manager-clear
       --manager-add <username> <username> ...
       --manager-remove <username> <username> ...
       --title <string>
       --owner <username>  [root only]
groupmanage is Copyright.  It is free software, released under the GNU
GPL v2 or later.  There is NO WARRANTY.  See the GPL for details.
END
    exit(1);
}

@ARGV || &usage('too few arguments');

if ($>) {
    exec 'userv','root','groupmanage',@ARGV;
    &quit("unable to execute userv to gain root privilege: $!");
}

chdir("/etc") || die "groupmanage: chdir /etc: $!\n";

$groupname= shift(@ARGV);
$groupname =~ y/\n//d;

$groupname =~ m/^\w[-0-9A-Za-z]*$/ ||
    &quit("first argument is invalid - must be group name");

@ARGV || push(@ARGV,'--info');

$callinguser= exists $ENV{'USERV_UID'} ? $ENV{'USERV_UID'} : $<;

%opt= ('user-create','0',
       'user-create-minunameu','5',
       'user-create-min','10000',
       'user-create-max','19999',
       'user-create-nameintitle','0',
       'user-create-maxperu','5',
       'group-file','group',
       'gtmp-file','gtmp',
       'grouplist-file','grouplist',
       'name-regexp','',
       'name-maxlen','8',
       'admin-group','',
       'finish-command','');
%ovalid=  ('user-create','boolean',
           'user-create-minunameu','number',
           'user-create-min','number',
           'user-create-max','number',
           'user-create-nameintitle','boolean',
           'user-create-maxperu','number',
           'group-file','string',
           'gtmp-file','string',
           'grouplist-file','string',
           'name-regexp','string',
           'name-maxlen','number',
           'admin-group','string',
           'finish-command','string');

sub ov_boolean {
    $cov= $_ eq 'yes' ? 1 :
          $_ eq 'no' ? 0 :
          &quit("groupmanage.conf:$.: bad boolean value");
}

sub ov_number {
    m/^[0-9]{1,10}$/ || &quit("groupmanage.conf:$.: bad numerical value");
}

sub ov_string {

}

open(GMC,"groupmanage.conf") || &quit("read groupmanage.conf: $!");
while (<GMC>) {
    next if m/^\#/ || !m/\S/;
    s/\s*\n$//;
    s/^\s*([-0-9a-z]+)\s*// || &quit("groupmanage.conf:$.: bad option format");
    $co= $1;
    defined($opt{$co}) || &quit("groupmanage.conf:$.: unknown option $co");
    $cov= $_;
    $ovf= 'ov_'.$ovalid{$co};
    &$ovf;
    $opt{$co}= $cov;
}
close(GMC);

if ($ARGV[0] eq '--info') {
    @ARGV == 1 || &usage('no arguments allowed after --info');
    &p_out;
    &load;
    &checkexists;
    &display;
    &p_out;
    exit(0);
}

sub naming {
    $callinguser || return;
    &p_out;
    if ($opt{'user-create-minunameu'}) {
	print(STDERR <<END) || &quit("write err re name: $!");
groupmanage: groups you create must be named after you ...
    <usernamepart>-<identifier>
 You must quote at least $opt{'user-create-minunameu'} chars of your username $createby
 (or all of it if it is shorter).
END
    }
    if ($opt{'name-regexp'}) {
	print(STDERR <<END) || &quit("write err re name: $!");
groupmanage: groups you create must match a pattern...
  The pattern is the Perl regular expression /$opt{'name-regexp'}/.
END
    }
    exit(1);
}

if ($ARGV[0] eq '--create') {
    $opt{'user-create'} || !$callinguser ||
        &quit("group creation by users disabled by administrator");
    length($groupname) <= $opt{'name-maxlen'} ||
        &quit("group names must be $opt{'name-maxlen'} chars or fewer");
    $!=0; (@pw= getpwuid($callinguser))
	|| &quit("cannot get your passwd entry: $!");
    $createby= $pw[0];
    if ($opt{'user-create-minunameu'}) {
	$groupname =~ m/^([-0-9A-Za-z]+)-([0-9a-z]+)$/ || &naming;
	$upart= $1;
	$idpart= $2;
	$upart eq $createby ||
	    (length($upart) >= $opt{'user-create-minunameu'} &&
	     substr($createby,0,length($upart)) eq $upart)
		|| &naming;
    } else {
	$groupname =~ m/${opt{'name-regexp'}}/ || &naming;
    }
    $create= 1;
    shift(@ARGV);
}

&lock;
&load;

if ($create) {
    $bythisowner < $opt{'user-create-maxperu'} ||
        &quit("you already have $bythisowner group(s)");
    $groupfileix==-1 || &quit("group already exists, cannot create it");
    $grouplistix==-1 || &quit("group is already in grouplist, cannot create it");
    for ($gid= $opt{'user-create-min'};
         $gid < $opt{'user-create-max'} && defined(getgrgid($gid));
         $gid++) { }
    $gid <= $opt{'user-create-max'} || &quit("out of gids to use, contact admin");
    $password=''; @members=($createby);
    $description= "${createby}'s -- user-defined, no title";
    $owner= $createby; @managers=(); @members= ($createby);
    $groupfileix=$#groupfile+1;
    $grouplistix=$#grouplist+1;
    &p("created group $groupname");
} else {
    &checkexists;
    &p("modifying group $groupname");
}

&weare($owner) || grep(&weare($_),@managers) || !$callinguser ||
    &quit("you may not manage $groupname");

$action= 'none';
while (@ARGV) {
    $_= shift(@ARGV);
    if (m/^--(add|remove)$/) {
        $action= $1; $clist= 'members'; $what= 'member';
    } elsif (m/^--owner$/) {
	!$callinguser || &quit("only root may change owner");
	@ARGV || &usage("no username owner after --owner");
	$owner= shift(@ARGV);
	&p("owner set to $owner");
    } elsif (m/^--manager-(add|remove)$/) {
        $action= $1; $clist= 'managers'; $what= 'manager';
    } elsif (m/^--clear$/) {
        &p('cleared list of members');
        @members=(); $action='none'; $memc++;
    } elsif (m/^--manager-clear$/) {
        &p('cleared list of managers');
        @managers=(); $action='none';
    } elsif (m/^--title$/) {
        &weare($owner) || !$callinguser ||
	    &quit("only group's owner ($owner) may change title");
        @ARGV || &usage("no title after --title");
        $_= shift(@ARGV); y/\020-\176//cd; y/:\\//d;
        if ($opt{'user-create-nameintitle'} &&
            $gid >= $opt{'user-create-min'} && $gid <= $opt{'user-create-max'}) {
            $_= "${owner}'s -- $_";
        }
        $description= $_;
        &p("title set to $description");
    } elsif (m/^-/) {
        &usage("unknown option $_");
    } elsif (m/^\w[-0-9A-Za-z]*$/) {
        y/\n//d;
        $chgu=$_;
        defined(getpwnam($chgu)) || &quit("username $chgu does not exist");
        eval "\@l = \@$clist; 1" || &quit("internal error: $@");
        $already= grep($_ eq $chgu, @l);
        if ($action eq 'add') {
            if ($already) {
                &p("$chgu already $what");
            } else {
                &p("added $what $chgu");
                push(@l,$chgu);
                $memc+= ($clist eq 'members');
            }
        } elsif ($action eq 'remove') {
            if ($already) {
                &p("removed $what $chgu");
                @l= grep($_ ne $chgu, @l);
                $memc+= ($clist eq 'members');
            } else {
                &p("$chgu is already not $what");
            }
        } else {
            &usage("username found but no action to take for them");
        }
        eval "\@$clist = \@l; 1" || &quit("internal error: $@");
    } else {
        &usage("bad username or option $_");
    }
}
&p("nb: a change to group membership only takes effect at the user's next login")
    if $memc;
$groupfile[$groupfileix]=
    "$groupname:$password:$gid:".join(',',@members)."\n";
$grouplist[$grouplistix]=
    "$groupname:$description:$owner:".join(',',@managers).":$homedir\n";
&save($opt{'group-file'},@groupfile);
&save($opt{'grouplist-file'},@grouplist);
if ($opt{'finish-command'}) {
    !system($opt{'finish-command'}) || &quit("finish-command: $?");
}
unlink($opt{'gtmp-file'}) || &quit("unlock group (remove gtmp): $!");
&p_out;
exit(0);

sub load {
    open(GF,"< $opt{'group-file'}") || &quit("read group: $!");
    @groupfile=<GF>; close(GF);
    $groupfileix=-1;
    for ($i=0; $i<=$#groupfile; $i++) {
        $_= $groupfile[$i]; s/\n$//;
        next if m/^\#/;
        m/^(\w[-0-9A-Za-z]*):([^:]*):(\d+):([-0-9A-Za-z,]*)$/ ||
            &quit("bad entry in group: $_");
        $gname2gid{$1}=$3;
        next unless $1 eq $groupname;
        $groupfileix<0 || &quit("duplicate entries in group");
        $groupfileix= $i;
        $password= $2;
        $gid= $3;
        @members= split(/,/,$4);
    }
    open(GL,"< $opt{'grouplist-file'}") || &quit("read grouplist: $!");
    @grouplist=<GL>; close(GL);
    $grouplistix=-1;
    for ($i=0; $i<=$#grouplist; $i++) {
        $_= $grouplist[$i]; s/\n$//;
        next if m/^\#/;
        m/^(\w[-0-9A-Za-z]*):([^:]*):(\w[-0-9A-Za-z]*):([-0-9A-Za-z,]*):([^:]*)$/ ||
            &quit("bad entry in grouplist: $_");
        $bythisowner++ if ($create && $3 eq $createby &&
                           $gname2gid{$1} >= $opt{'user-create-min'} &&
                           $gname2gid{$1} <= $opt{'user-create-max'});
        next unless $1 eq $groupname;
        $grouplistix<0 || &quit("duplicate entries in grouplist");
        $grouplistix= $i;
        $description= $2;
        $owner= $3;
        $homedir= $5;
        @managers= split(/,/,$4);
    }
}

sub checkexists {
    $grouplistix>=0 || &quit("no entry in grouplist for $groupname");
    $groupfileix>=0 || &quit("no entry in group for $groupname");
}

sub weare {
    return 0 if $_[0] eq '';
    @pw= getpwnam($_[0]);
    return @pw && $pw[2] == $callinguser ? 1 : 0;
}

sub save {
    $filename= shift(@_);
    unlink("$filename~");
    open(DUMP,"> $filename.new") || &quit("create new $filename: $!");
    print(DUMP @_) || &quit("write new $filename: $!");
    close(DUMP) || &quit("close new $filename: $!");
    link("$filename","$filename~") || &quit("create backup $filename: $!");
    rename("$filename.new","$filename") || &quit("install new $filename: $!");
}

sub quit {
    &unlock;
    &p_out;
    die "groupmanage: @_\n";
}

sub lock {
    link($opt{'group-file'},$opt{'gtmp-file'}) || &quit("create gtmp: $!");
    $locked++;
}

sub unlock {
    return unless $locked;
    $locked--;
    unlink($opt{'gtmp-file'}) || warn("unlock group file (remove gtmp): $!\n");
}

sub display {
    print(<<END) || &quit("write to stdout: $!\n");
group       $groupname
gid         $gid
description $description
owner       $owner
managers    @managers
members     @members
homedir     $homedir
END
}

sub p_out {
    print(STDOUT "$stdout_string") || &quit("write to stdout: $!\n");
    $stdout_string= '';
}

sub p {
    $stdout_string.= $_[0]."\n";
}