]> git.cameronkatri.com Git - pw-darwin.git/blob - adduser/adduser.perl
rmgroup - delete a Unix group
[pw-darwin.git] / adduser / adduser.perl
1 #!/usr/bin/perl
2 #
3 # Copyright (c) 1995-1996 Wolfram Schneider <wosch@FreeBSD.org>. Berlin.
4 # All rights reserved.
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions
8 # are met:
9 # 1. Redistributions of source code must retain the above copyright
10 # notice, this list of conditions and the following disclaimer.
11 # 2. Redistributions in binary form must reproduce the above copyright
12 # notice, this list of conditions and the following disclaimer in the
13 # documentation and/or other materials provided with the distribution.
14 #
15 # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25 # SUCH DAMAGE.
26 #
27 # $Id: adduser.perl,v 1.18 1996/09/14 23:22:23 wosch Exp $
28
29
30 # read variables
31 sub variables {
32 $verbose = 1; # verbose = [0-2]
33 $defaultpasswd = "yes"; # use password for new users
34 $dotdir = "/usr/share/skel"; # copy dotfiles from this dir
35 $dotdir_bak = $dotdir;
36 $send_message = "no"; # send message to new user
37 $send_message_bak = '/etc/adduser.message';
38 $config = "/etc/adduser.conf"; # config file for adduser
39 $config_read = 1; # read config file
40 $logfile = "/var/log/adduser"; # logfile
41 $home = "/home"; # default HOME
42 $etc_shells = "/etc/shells";
43 $etc_passwd = "/etc/master.passwd";
44 $group = "/etc/group";
45 $pwd_mkdb = "pwd_mkdb -p"; # program for building passwd database
46
47
48 # List of directories where shells located
49 @path = ('/bin', '/usr/bin', '/usr/local/bin');
50 # common shells, first element has higher priority
51 @shellpref = ('csh', 'sh', 'bash', 'tcsh', 'ksh');
52
53 $defaultshell = 'sh'; # defaultshell if not empty
54 $group_uniq = 'USER';
55 $defaultgroup = $group_uniq;# login groupname, $group_uniq means username
56
57 $uid_start = 1000; # new users get this uid
58 $uid_end = 32000; # max. uid
59
60 # global variables
61 # passwd
62 $username = ''; # $username{username} = uid
63 $uid = ''; # $uid{uid} = username
64 $pwgid = ''; # $pwgid{pwgid} = username; gid from passwd db
65
66 $password = ''; # password for new users
67
68 # group
69 $groupname =''; # $groupname{groupname} = gid
70 $groupmembers = ''; # $groupmembers{gid} = members of group/kommalist
71 $gid = ''; # $gid{gid} = groupname; gid form group db
72
73 # shell
74 $shell = ''; # $shell{`basename sh`} = sh
75
76 # only for me (=Wolfram)
77 if ($test) {
78 $home = "/home/w/tmp/adduser/home";
79 $etc_shells = "./shells";
80 $etc_passwd = "./master.passwd";
81 $group = "./group";
82 $pwd_mkdb = "pwd_mkdb -p -d .";
83 $config = "adduser.conf";
84 $send_message = "./adduser.message";
85 $logfile = "./log.adduser";
86 }
87
88 umask 022; # don't give login group write access
89
90 $ENV{'PATH'} = "/sbin:/bin:/usr/sbin:/usr/bin";
91 @passwd_backup = '';
92 @group_backup = '';
93 @message_buffer = '';
94 @user_variable_list = ''; # user variables in /etc/adduser.conf
95 $do_not_delete = '## DO NOT DELETE THIS LINE!';
96 }
97
98 # read shell database, see also: shells(5)
99 sub shells_read {
100 local($sh);
101 local($err) = 0;
102
103 print "Check $etc_shells\n" if $verbose;
104 open(S, $etc_shells) || die "$etc_shells:$!\n";
105
106 while(<S>) {
107 if (/^\s*\//) {
108 s/^\s*//; s/\s+.*//; # chop
109 $sh = $_;
110 if (-x $sh) {
111 $shell{&basename($sh)} = $sh;
112 } else {
113 warn "Shell: $sh not executable!\n";
114 $err++;
115 }
116 }
117 }
118
119 # Allow /nonexistent and /bin/date as a valid shell for system utils
120 push(@list, "/nonexistent");
121 push(@shellpref, "no");
122 $shell{"no"} = "/nonexistent";
123
124 push(@list, "/bin/date");
125 push(@shellpref, "date");
126 $shell{"date"} = "/bin/date";
127
128 return $err;
129 }
130
131 # add new shells if possible
132 sub shells_add {
133 local($sh,$dir,@list);
134
135 return 1 unless $verbose;
136
137 foreach $sh (@shellpref) {
138 # all known shells
139 if (!$shell{$sh}) {
140 # shell $sh is not defined as login shell
141 foreach $dir (@path) {
142 if (-x "$dir/$sh") {
143 # found shell
144 if (&confirm_yn("Found shell: $dir/$sh. Add to $etc_shells?", "yes")) {
145 push(@list, "$dir/$sh");
146 push(@shellpref, "$sh");
147 $shell{&basename("$dir/$sh")} = "$dir/$sh";
148 $changes++;
149 }
150 }
151 }
152 }
153 }
154 &append_file($etc_shells, @list) if $#list >= 0;
155 }
156
157 # choose your favourite shell and return the shell
158 sub shell_default {
159 local($e,$i,$new_shell);
160 local($sh);
161
162 $sh = &shell_default_valid($defaultshell);
163 return $sh unless $verbose;
164
165 $new_shell = &confirm_list("Enter your default shell:", 0,
166 $sh, sort(keys %shell));
167 print "Your default shell is: $new_shell -> $shell{$new_shell}\n";
168 $changes++ if $new_shell ne $sh;
169 return $new_shell;
170 }
171
172 sub shell_default_valid {
173 local($sh) = @_;
174 local($s,$e);
175
176 return $sh if $shell{$sh};
177
178 foreach $e (@shellpref) {
179 $s = $e;
180 last if defined($shell{$s});
181 }
182 $s = "sh" unless $s;
183 warn "Shell ``$sh'' is undefined, use ``$s''\n";
184 return $s;
185 }
186
187 # return default home partition (f.e. "/home")
188 # create base directory if nesseccary
189 sub home_partition {
190 local($home) = @_;
191 $home = &stripdir($home);
192 local($h) = $home;
193
194 return $h if !$verbose && $h eq &home_partition_valid($h);
195
196 while(1) {
197 $h = &confirm_list("Enter your default HOME partition:", 1, $home, "");
198 $h = &stripdir($h);
199 last if $h eq &home_partition_valid($h);
200 }
201
202 $changes++ if $h ne $home;
203 return $h;
204 }
205
206 sub home_partition_valid {
207 local($h) = @_;
208
209 $h = &stripdir($h);
210 # all right (I hope)
211 return $h if $h =~ "^/" && -e $h && -w $h && (-d $h || -l $h);
212
213 # Errors or todo
214 if ($h !~ "^/") {
215 warn "Please use absolute path for home: ``$h''.\a\n";
216 return 0;
217 }
218
219 if (-e $h) {
220 warn "$h exists, but is not a directory or symlink!\n"
221 unless -d $h || -l $h;
222 warn "$h is not writable!\n"
223 unless -w $h;
224 return 0;
225 } else {
226 # create home partition
227 return $h if &mkdir_home($h);
228 }
229 return 0;
230 }
231
232 # check for valid passwddb
233 sub passwd_check {
234 system("$pwd_mkdb -c $etc_passwd");
235 die "\nInvalid $etc_passwd - cannot add any users!\n" if $?;
236 }
237
238 # read /etc/passwd
239 sub passwd_read {
240 local($p_username, $pw, $p_uid, $p_gid, $sh, %shlist);
241
242 print "Check $etc_passwd\n" if $verbose;
243 open(P, "$etc_passwd") || die "$passwd: $!\n";
244
245 while(<P>) {
246 chop;
247 push(@passwd_backup, $_);
248 ($p_username, $pw, $p_uid, $p_gid, $sh) = (split(/:/, $_))[0..3,9];
249
250 print "$p_username already exists with uid: $username{$p_username}!\n"
251 if $username{$p_username} && $verbose;
252 $username{$p_username} = $p_uid;
253 print "User $p_username: uid $p_uid exists twice: $uid{$p_uid}\n"
254 if $uid{$p_uid} && $verbose && $p_uid; # don't warn for uid 0
255 print "User $p_username: illegal shell: ``$sh''\n"
256 if ($verbose && $sh &&
257 !$shell{&basename($sh)} &&
258 $p_username !~ /^(bin|uucp|falcon|nobody)$/ &&
259 $sh !~ /\/(pppd|sliplogin)$/);
260 $uid{$p_uid} = $p_username;
261 $pwgid{$p_gid} = $p_username;
262 }
263 close P;
264 }
265
266 # read /etc/group
267 sub group_read {
268 local($g_groupname,$pw,$g_gid, $memb);
269
270 print "Check $group\n" if $verbose;
271 open(G, "$group") || die "$group: $!\n";
272 while(<G>) {
273 chop;
274 push(@group_backup, $_);
275 ($g_groupname, $pw, $g_gid, $memb) = (split(/:/, $_))[0..3];
276
277 $groupmembers{$g_gid} = $memb;
278 warn "Groupname exists twice: $g_groupname:$g_gid -> $g_groupname:$groupname{$g_groupname}\n"
279 if $groupname{$g_groupname} && $verbose;
280 $groupname{$g_groupname} = $g_gid;
281 warn "Groupid exists twice: $g_groupname:$g_gid -> $gid{$g_gid}:$g_gid\n"
282 if $gid{$g_gid} && $verbose;
283 $gid{$g_gid} = $g_groupname;
284 }
285 close G;
286 }
287
288 # check gids /etc/passwd <-> /etc/group
289 sub group_check {
290 local($c_gid, $c_username, @list);
291
292 foreach $c_gid (keys %pwgid) {
293 if (!$gid{$c_gid}) {
294 $c_username = $pwgid{$c_gid};
295 warn "User ``$c_username'' has gid $c_gid but a group with this " .
296 "gid does not exist.\n" if $verbose;
297 }
298 }
299 }
300
301 #
302 # main loop for creating new users
303 #
304
305 # return username
306 sub new_users_name {
307 local($name);
308
309 while(1) {
310 $name = &confirm_list("Enter username", 1, "a-z0-9", "");
311 if (length($name) > 8) {
312 warn "Username is longer than 8 chars\a\n";
313 next;
314 }
315 last if (&new_users_name_valid($name) eq $name);
316 }
317 return $name;
318 }
319
320 sub new_users_name_valid {
321 local($name) = @_;
322
323 if ($name !~ /^[a-z0-9]+$/) {
324 warn "Wrong username. " .
325 "Please use only lowercase characters or digits\a\n";
326 return 0;
327 } elsif ($username{$name}) {
328 warn "Username ``$name'' already exists!\a\n"; return 0;
329 }
330 return $name;
331 }
332
333 # return full name
334 sub new_users_fullname {
335 local($name) = @_;
336 local($fullname);
337
338 while(1) {
339 $fullname = &confirm_list("Enter full name", 1, "", "");
340 last if $fullname eq &new_users_fullname_valid($fullname);
341 }
342 $fullname = $name unless $fullname;
343 return $fullname;
344 }
345
346 sub new_users_fullname_valid {
347 local($fullname) = @_;
348
349 return $fullname if $fullname !~ /:/;
350
351 warn "``:'' is not allowed!\a\n";
352 return 0;
353 }
354
355 # return shell (full path) for user
356 sub new_users_shell {
357 local($sh);
358
359 $sh = &confirm_list("Enter shell", 0, $defaultshell, keys %shell);
360 return $shell{$sh};
361 }
362
363 # return free uid and gid
364 sub new_users_id {
365 local($name) = @_;
366 local($u_id, $g_id) = &next_id($name);
367 local($u_id_tmp, $e);
368
369 while(1) {
370 $u_id_tmp = &confirm_list("Uid", 1, $u_id, "");
371 last if $u_id_tmp =~ /^[0-9]+$/ && $u_id_tmp <= $uid_end &&
372 ! $uid{$u_id_tmp};
373 if ($uid{$u_id_tmp}) {
374 warn "Uid ``$u_id_tmp'' in use!\a\n";
375 } else {
376 warn "Wrong uid.\a\n";
377 }
378 }
379 # use calculated uid
380 return ($u_id_tmp, $g_id) if $u_id_tmp eq $u_id;
381 # recalculate gid
382 $uid_start = $u_id_tmp;
383 return &next_id($name);
384 }
385
386 # add user to group
387 sub add_group {
388 local($gid, $name) = @_;
389
390 return 0 if
391 $groupmembers{$gid} =~ /^(.+,)?$name(,.+)?$/;
392
393 $groupmembers_bak{$gid} = $groupmembers{$gid};
394 $groupmembers{$gid} .= "," if $groupmembers{$gid};
395 $groupmembers{$gid} .= "$name";
396
397 local(@l) = split(',', $groupmembers{$gid});
398 # group(5): A group cannot have more than 200 members.
399 # The maximum line length of /etc/group is 1024 characters.
400 # Longer lines will be skiped.
401 if ($#l >= 200 ||
402 length($groupmembers{$gid}) > 1024 - 50) { # 50 is for group name
403 warn "WARNING, maybe group line ``$gid{$gid}'' is to long or to\n" .
404 "much users in group, see group(5)\a\n";
405 }
406 return $name;
407 }
408
409
410 # return login group
411 sub new_users_grplogin {
412 local($name, $defaultgroup, $new_users_ok) = @_;
413 local($group_login, $group);
414
415 $group = $name;
416 $group = $defaultgroup if $defaultgroup ne $group_uniq;
417
418 if ($new_users_ok) {
419 # clean up backup
420 foreach $e (keys %groupmembers_bak) { delete $groupmembers_bak{$e}; }
421 } else {
422 # restore old groupmembers, user was not accept
423 foreach $e (keys %groupmembers_bak) {
424 $groupmembers{$e} = $groupmembers_bak{$e};
425 }
426 }
427
428 while(1) {
429 $group_login = &confirm_list("Login group", 1, $group,
430 ($name, $group));
431 last if $group_login eq $group;
432 last if $group_login eq $name;
433 last if defined $groupname{$group_login};
434 if ($group_login eq $group_uniq) {
435 $group_login = $name; last;
436 }
437
438 if (defined $gid{$group_login}) {
439 # convert numeric groupname (gid) to groupname
440 $group_login = $gid{$group_login};
441 last;
442 }
443 warn "Group does not exist!\a\n";
444 }
445
446 #if (defined($groupname{$group_login})) {
447 # &add_group($groupname{$group_login}, $name);
448 #}
449
450 return ($group_login, $group_uniq) if $group_login eq $name;
451 return ($group_login, $group_login);
452 }
453
454 # return login group
455 sub new_users_grplogin_batch {
456 local($name, $defaultgroup) = @_;
457 local($group_login, $group);
458
459 $group_login = $name;
460 $group_login = $defaultgroup if $defaultgroup ne $group_uniq;
461
462 if (defined $gid{$group_login}) {
463 # convert numeric groupname (gid) to groupname
464 $group_login = $gid{$group_login};
465 }
466
467 # if (defined($groupname{$group_login})) {
468 # &add_group($groupname{$group_login}, $name);
469 # }
470
471 return $group_login
472 if defined($groupname{$group_login}) || $group_login eq $name;
473 warn "Group ``$group_login'' does not exist\a\n";
474 return 0;
475 }
476
477 # return other groups (string)
478 sub new_users_groups {
479 local($name, $other_groups) = @_;
480 local($string) =
481 "Login group is ``$group_login''. Invite $name into other groups:";
482 local($e, $flag);
483 local($new_groups,$groups);
484
485 $other_groups = "no" unless $other_groups;
486
487 while(1) {
488 $groups = &confirm_list($string, 1, $other_groups,
489 ("no", $other_groups, "guest"));
490 # no other groups
491 return "" if $groups eq "no";
492
493 ($flag, $new_groups) = &new_users_groups_valid($groups);
494 last unless $flag;
495 }
496 $new_groups =~ s/\s*$//;
497 return $new_groups;
498 }
499
500 sub new_users_groups_valid {
501 local($groups) = @_;
502 local($e, $new_groups);
503 local($flag) = 0;
504
505 foreach $e (split(/[,\s]+/, $groups)) {
506 # convert numbers to groupname
507 if ($e =~ /^[0-9]+$/ && $gid{$e}) {
508 $e = $gid{$e};
509 }
510 if (defined($groupname{$e})) {
511 if ($e eq $group_login) {
512 # do not add user to a group if this group
513 # is also the login group.
514 } elsif (&add_group($groupname{$e}, $name)) {
515 $new_groups .= "$e ";
516 } else {
517 warn "$name is already member of group ``$e''\n";
518 }
519 } else {
520 warn "Group ``$e'' does not exist\a\n"; $flag++;
521 }
522 }
523 return ($flag, $new_groups);
524 }
525
526 # your last change
527 sub new_users_ok {
528
529 print <<EOF;
530
531 Name: $name
532 Password: ****
533 Fullname: $fullname
534 Uid: $u_id
535 Gid: $g_id ($group_login)
536 Groups: $group_login $new_groups
537 HOME: $home/$name
538 Shell: $sh
539 EOF
540
541 return &confirm_yn("OK?", "yes");
542 }
543
544 # make password database
545 sub new_users_pwdmkdb {
546 local($last) = @_;
547
548 system("$pwd_mkdb $etc_passwd");
549 if ($?) {
550 warn "$last\n";
551 warn "``$pwd_mkdb'' failed\n";
552 exit($? >> 8);
553 }
554 }
555
556 # update group database
557 sub new_users_group_update {
558 local($e, @a);
559
560 # Add *new* group
561 if (!defined($groupname{$group_login}) &&
562 !defined($gid{$groupname{$group_login}})) {
563 push(@group_backup, "$group_login:*:$g_id:");
564 $groupname{$group_login} = $g_id;
565 $gid{$g_id} = $group_login;
566 # $groupmembers{$g_id} = $group_login;
567 }
568
569 if ($new_groups || defined($groupname{$group_login}) ||
570 defined($gid{$groupname{$group_login}}) &&
571 $gid{$groupname{$group_login}} ne "+") {
572 # new user is member of some groups
573 # new login group is already in name space
574 rename($group, "$group.bak");
575 #warn "$group_login $groupname{$group_login} $groupmembers{$groupname{$group_login}}\n";
576 foreach $e (sort {$a <=> $b} (keys %gid)) {
577 push(@a, "$gid{$e}:*:$e:$groupmembers{$e}");
578 }
579 &append_file($group, @a);
580 } else {
581 &append_file($group, "$group_login:*:$g_id:");
582 }
583
584 }
585
586 sub new_users_passwd_update {
587 # update passwd/group variables
588 push(@passwd_backup, $new_entry);
589 $username{$name} = $u_id;
590 $uid{$u_id} = $name;
591 $pwgid{$g_id} = $name;
592 }
593
594 # send message to new user
595 sub new_users_sendmessage {
596 return 1 if $send_message eq "no";
597
598 local($cc) =
599 &confirm_list("Send message to ``$name'' and:",
600 1, "no", ("root", "second_mail_address", "no"));
601 local($e);
602 $cc = "" if $cc eq "no";
603
604 foreach $e (@message_buffer) {
605 print eval "\"$e\"";
606 }
607 print "\n";
608
609 local(@message_buffer_append) = ();
610 if (!&confirm_yn("Add anything to default message", "no")) {
611 print "Use ``.'' or ^D alone on a line to finish your message.\n";
612 push(@message_buffer_append, "\n");
613 while($read = <STDIN>) {
614 last if $read eq "\.\n";
615 push(@message_buffer_append, $read);
616 }
617 }
618
619 &sendmessage("$name $cc", (@message_buffer, @message_buffer_append))
620 if (&confirm_yn("Send message", "yes"));
621 }
622
623 sub sendmessage {
624 local($to, @message) = @_;
625 local($e);
626
627 if (!open(M, "| mail -s Welcome $to")) {
628 warn "Cannot send mail to: $to!\n";
629 return 0;
630 } else {
631 foreach $e (@message) {
632 print M eval "\"$e\"";
633 }
634 close M;
635 }
636 }
637
638
639 sub new_users_password {
640
641 # empty password
642 return "" if $defaultpasswd ne "yes";
643
644 local($password);
645
646 while(1) {
647 system("stty -echo");
648 $password = &confirm_list("Enter password", 1, "", "");
649 system("stty echo");
650 print "\n";
651 if ($password ne "") {
652 system("stty -echo");
653 $newpass = &confirm_list("Enter password again", 1, "", "");
654 system("stty echo");
655 print "\n";
656 last if $password eq $newpass;
657 print "They didn't match, please try again\n";
658 }
659 elsif (&confirm_yn("Use an empty password?", "yes")) {
660 last;
661 }
662 }
663
664 return $password;
665 }
666
667
668 sub new_users {
669
670 print "\n" if $verbose;
671 print "Ok, let's go.\n" .
672 "Don't worry about mistakes. I will give you the chance later to " .
673 "correct any input.\n" if $verbose;
674
675 # name: Username
676 # fullname: Full name
677 # sh: shell
678 # u_id: user id
679 # g_id: group id
680 # group_login: groupname of g_id
681 # new_groups: some other groups
682 local($name, $group_login, $fullname, $sh, $u_id, $g_id, $new_groups);
683 local($groupmembers_bak, $cryptpwd);
684 local($new_users_ok) = 1;
685
686
687 $new_groups = "no";
688 $new_groups = "no" unless $groupname{$new_groups};
689
690 while(1) {
691 $name = &new_users_name;
692 $fullname = &new_users_fullname($name);
693 $sh = &new_users_shell;
694 ($u_id, $g_id) = &new_users_id($name);
695 ($group_login, $defaultgroup) =
696 &new_users_grplogin($name, $defaultgroup, $new_users_ok);
697 # do not use uniq username and login group
698 $g_id = $groupname{$group_login} if (defined($groupname{$group_login}));
699
700 $new_groups = &new_users_groups($name, $new_groups);
701 $password = &new_users_password;
702
703
704 if (&new_users_ok) {
705 $new_users_ok = 1;
706
707 $cryptpwd = "";
708 $cryptpwd = crypt($password, &salt) if $password ne "";
709 # obscure perl bug
710 $new_entry = "$name\:" . "$cryptpwd" .
711 "\:$u_id\:$g_id\::0:0:$fullname:$home/$name:$sh";
712 &append_file($etc_passwd, "$new_entry");
713 &new_users_pwdmkdb("$new_entry");
714 &new_users_group_update;
715 &new_users_passwd_update; print "Added user ``$name''\n";
716 &new_users_sendmessage;
717 &adduser_log("$name:*:$u_id:$g_id($group_login):$fullname");
718 &home_create($name, $group_login);
719 } else {
720 $new_users_ok = 0;
721 }
722 if (!&confirm_yn("Add another user?", "yes")) {
723 print "Goodbye!\n" if $verbose;
724 last;
725 }
726 print "\n" if !$verbose;
727 }
728 }
729
730 sub batch {
731 local($name, $groups, $fullname, $password) = @_;
732 local($sh);
733
734 $defaultshell = &shell_default_valid($defaultshell);
735 return 0 unless $home = &home_partition_valid($home);
736 return 0 if $dotdir ne &dotdir_default_valid($dotdir);
737 $send_message = &message_default;
738
739 return 0 if $name ne &new_users_name_valid($name);
740 $sh = $shell{$defaultshell};
741 ($u_id, $g_id) = &next_id($name);
742 $group_login = &new_users_grplogin_batch($name, $defaultgroup);
743 return 0 unless $group_login;
744 $g_id = $groupname{$group_login} if (defined($groupname{$group_login}));
745 ($flag, $new_groups) = &new_users_groups_valid($groups);
746 return 0 if $flag;
747
748 $cryptpwd = "";
749 $cryptpwd = crypt($password, &salt) if $password ne "";
750 # obscure perl bug
751 $new_entry = "$name\:" . "$cryptpwd" .
752 "\:$u_id\:$g_id\::0:0:$fullname:$home/$name:$sh";
753 &append_file($etc_passwd, "$new_entry");
754 &new_users_pwdmkdb("$new_entry");
755 &new_users_group_update;
756 &new_users_passwd_update; print "Added user ``$name''\n";
757 &sendmessage($name, @message_buffer) if $send_message ne "no";
758 &adduser_log("$name:*:$u_id:$g_id($group_login):$fullname");
759 &home_create($name, $group_login);
760 }
761
762 # ask for password usage
763 sub password_default {
764 local($p) = $defaultpasswd;
765 if ($verbose) {
766 $p = &confirm_yn("Use passwords", $defaultpasswd);
767 $changes++ unless $p;
768 }
769 return "yes" if (($defaultpasswd eq "yes" && $p) ||
770 ($defaultpasswd eq "no" && !$p));
771 return "no"; # otherwise
772 }
773
774 # misc
775 sub check_root {
776 die "You are not root!\n" if $< && !$test;
777 }
778
779 sub usage {
780 warn <<USAGE;
781 usage: adduser
782 [-batch username [group[,group]...] [fullname] [password]]
783 [-check_only]
784 [-config_create]
785 [-dotdir dotdir]
786 [-group login_group]
787 [-h|-help]
788 [-home home]
789 [-message message_file]
790 [-noconfig]
791 [-shell shell]
792 [-s|-silent|-q|-quit]
793 [-uid uid_start]
794 [-v|-verbose]
795
796 home=$home shell=$defaultshell dotdir=$dotdir login_group=$defaultgroup
797 message_file=$send_message uid_start=$uid_start
798 USAGE
799 exit 1;
800 }
801
802 # uniq(1)
803 sub uniq {
804 local(@list) = @_;
805 local($e, $last, @array);
806
807 foreach $e (sort @list) {
808 push(@array, $e) unless $e eq $last;
809 $last = $e;
810 }
811 return @array;
812 }
813
814 # see /usr/src/usr.bin/passwd/local_passwd.c or librcypt, crypt(3)
815 sub salt {
816 local($salt); # initialization
817 local($i, $rand);
818 local(@itoa64) = ( 0 .. 9, a .. z, A .. Z ); # 0 .. 63
819
820 warn "calculate salt\n" if $verbose > 1;
821 # to64
822 for ($i = 0; $i < 8; $i++) {
823 srand(time + $rand + $$);
824 $rand = rand(25*29*17 + $rand);
825 $salt .= $itoa64[$rand & $#itoa64];
826 }
827 warn "Salt is: $salt\n" if $verbose > 1;
828
829 return $salt;
830 }
831
832
833 # print banner
834 sub copyright {
835 return;
836 }
837
838 # hints
839 sub hints {
840 if ($verbose) {
841 print "Use option ``-silent'' if you don't want see " .
842 "all warnings & questions.\n\n";
843 } else {
844 print "Use option ``-verbose'' if you want see more warnings & " .
845 "questions \nor try to repair bugs.\n\n";
846 }
847 }
848
849 #
850 sub parse_arguments {
851 local(@argv) = @_;
852
853 while ($_ = $argv[0], /^-/) {
854 shift @argv;
855 last if /^--$/;
856 if (/^--?(v|verbose)$/) { $verbose = 1 }
857 elsif (/^--?(s|silent|q|quit)$/) { $verbose = 0 }
858 elsif (/^--?(debug)$/) { $verbose = 2 }
859 elsif (/^--?(h|help|\?)$/) { &usage }
860 elsif (/^--?(home)$/) { $home = $argv[0]; shift @argv }
861 elsif (/^--?(shell)$/) { $defaultshell = $argv[0]; shift @argv }
862 elsif (/^--?(dotdir)$/) { $dotdir = $argv[0]; shift @argv }
863 elsif (/^--?(uid)$/) { $uid_start = $argv[0]; shift @argv }
864 elsif (/^--?(group)$/) { $defaultgroup = $argv[0]; shift @argv }
865 elsif (/^--?(check_only)$/) { $check_only = 1 }
866 elsif (/^--?(message)$/) { $send_message = $argv[0]; shift @argv;
867 $sendmessage = 1; }
868 elsif (/^--?(batch)$/) {
869 @batch = splice(@argv, 0, 4); $verbose = 0;
870 die "batch: too few arguments\n" if $#batch < 0;
871 }
872 # see &config_read
873 elsif (/^--?(config_create)$/) { &create_conf; }
874 elsif (/^--?(noconfig)$/) { $config_read = 0; }
875 else { &usage }
876 }
877 #&usage if $#argv < 0;
878 }
879
880 sub basename {
881 local($name) = @_;
882 $name =~ s|/+$||;
883 $name =~ s|.*/+||;
884 return $name;
885 }
886
887 sub dirname {
888 local($name) = @_;
889 $name = &stripdir($name);
890 $name =~ s|/+[^/]+$||;
891 $name = "/" unless $name; # dirname of / is /
892 return $name;
893 }
894
895 # return 1 if $file is a readable file or link
896 sub filetest {
897 local($file, $verb) = @_;
898
899 if (-e $file) {
900 if (-f $file || -l $file) {
901 return 1 if -r _;
902 warn "$file unreadable\n" if $verbose;
903 } else {
904 warn "$file is not a plain file or link\n" if $verbose;
905 }
906 }
907 return 0;
908 }
909
910 # create configuration files and exit
911 sub create_conf {
912 $create_conf = 1;
913 if ($send_message ne 'no') {
914 &message_create($send_message);
915 } else {
916 &message_create($send_message_bak);
917 }
918 &config_write(1);
919 exit(0);
920 }
921
922 # log for new user in /var/log/adduser
923 sub adduser_log {
924 local($string) = @_;
925 local($e);
926
927 return 1 if $logfile eq "no";
928
929 local($sec, $min, $hour, $mday, $mon, $year) = localtime;
930 $mon++;
931
932 foreach $e ('sec', 'min', 'hour', 'mday', 'mon', 'year') {
933 # '7' -> '07'
934 eval "\$$e = 0 . \$$e" if (eval "\$$e" < 10);
935 }
936
937 &append_file($logfile, "$year/$mon/$mday $hour:$min:$sec $string");
938 }
939
940 # create HOME directory, copy dotfiles from $dotdir to $HOME
941 sub home_create {
942 local($name, $group) = @_;
943 local($homedir) = "$home/$name";
944
945 if (-e "$homedir") {
946 warn "HOME Directory ``$homedir'' already exist\a\n";
947 return 0;
948 }
949
950 if ($dotdir eq 'no') {
951 if (!mkdir("$homedir",0755)) {
952 warn "mkdir $homedir: $!\n"; return 0;
953 }
954 system 'chown', "$name:$group", $homedir;
955 return !$?;
956 }
957
958 # copy files from $dotdir to $homedir
959 # rename 'dot.foo' files to '.foo'
960 print "Copy files from $dotdir to $homedir\n" if $verbose;
961 system("cp -r $dotdir $homedir");
962 system("chmod -R u+wrX,go-w $homedir");
963 system("chown -R $name:$group $homedir");
964
965 # security
966 opendir(D, $homedir);
967 foreach $file (readdir(D)) {
968 if ($file =~ /^dot\./ && -f "$homedir/$file") {
969 $file =~ s/^dot\././;
970 rename("$homedir/dot$file", "$homedir/$file");
971 }
972 chmod(0600, "$homedir/$file")
973 if ($file =~ /^\.(rhosts|Xauthority|kermrc|netrc)$/);
974 chmod(0700, "$homedir/$file")
975 if ($file =~ /^(Mail|prv|\.(iscreen|term))$/);
976 }
977 closedir D;
978 return 1;
979 }
980
981 # makes a directory hierarchy
982 sub mkdir_home {
983 local($dir) = @_;
984 $dir = &stripdir($dir);
985 local($user_partition) = "/usr";
986 local($dirname) = &dirname($dir);
987
988
989 -e $dirname || &mkdirhier($dirname);
990
991 if (((stat($dirname))[0]) == ((stat("/"))[0])){
992 # home partition is on root partition
993 # create home partition on $user_partition and make
994 # a symlink from $dir to $user_partition/`basename $dir`
995 # For instance: /home -> /usr/home
996
997 local($basename) = &basename($dir);
998 local($d) = "$user_partition/$basename";
999
1000
1001 if (-d $d) {
1002 warn "Oops, $d already exist\n" if $verbose;
1003 } else {
1004 print "Create $d\n" if $verbose;
1005 if (!mkdir("$d", 0755)) {
1006 warn "$d: $!\a\n"; return 0;
1007 }
1008 }
1009
1010 unlink($dir); # symlink to nonexist file
1011 print "Create symlink: $dir -> $d\n" if $verbose;
1012 if (!symlink("$d", $dir)) {
1013 warn "Symlink $d: $!\a\n"; return 0;
1014 }
1015 } else {
1016 print "Create $dir\n" if $verbose;
1017 if (!mkdir("$dir", 0755)) {
1018 warn "Directory ``$dir'': $!\a\n"; return 0;
1019 }
1020 }
1021 return 1;
1022 }
1023
1024 sub mkdirhier {
1025 local($dir) = @_;
1026 local($d,$p);
1027
1028 $dir = &stripdir($dir);
1029
1030 foreach $d (split('/', $dir)) {
1031 $dir = "$p/$d";
1032 $dir =~ s|^//|/|;
1033 if (! -e "$dir") {
1034 print "Create $dir\n" if $verbose;
1035 if (!mkdir("$dir", 0755)) {
1036 warn "$dir: $!\n"; return 0;
1037 }
1038 }
1039 $p .= "/$d";
1040 }
1041 return 1;
1042 }
1043
1044 # stript unused '/'
1045 # F.i.: //usr///home// -> /usr/home
1046 sub stripdir {
1047 local($dir) = @_;
1048
1049 $dir =~ s|/+|/|g; # delete double '/'
1050 $dir =~ s|/$||; # delete '/' at end
1051 return $dir if $dir ne "";
1052 return '/';
1053 }
1054
1055 # Read one of the elements from @list. $confirm is default.
1056 # If !$allow accept only elements from @list.
1057 sub confirm_list {
1058 local($message, $allow, $confirm, @list) = @_;
1059 local($read, $c, $print);
1060
1061 $print = "$message" if $message;
1062 $print .= " " unless $message =~ /\n$/ || $#list == 0;
1063
1064 $print .= join($", &uniq(@list)); #"
1065 $print .= " " unless $message =~ /\n$/ && $#list == 0;
1066 print "$print";
1067 print "\n" if (length($print) + length($confirm)) > 60;
1068 print "[$confirm]: ";
1069
1070 chop($read = <STDIN>);
1071 $read =~ s/^\s*//;
1072 $read =~ s/\s*$//;
1073 return $confirm if $read eq "";
1074 return "$read" if $allow;
1075
1076 foreach $c (@list) {
1077 return $read if $c eq $read;
1078 }
1079 warn "$read: is not allowed!\a\n";
1080 return &confirm_list($message, $allow, $confirm, @list);
1081 }
1082
1083 # YES or NO question
1084 # return 1 if &confirm("message", "yes") and answer is yes
1085 # or if &confirm("message", "no") an answer is no
1086 # otherwise 0
1087 sub confirm_yn {
1088 local($message, $confirm) = @_;
1089 local($yes) = '^(yes|YES|y|Y)$';
1090 local($no) = '^(no|NO|n|N)$';
1091 local($read, $c);
1092
1093 if ($confirm && ($confirm =~ "$yes" || $confirm == 1)) {
1094 $confirm = "y";
1095 } else {
1096 $confirm = "n";
1097 }
1098 print "$message (y/n) [$confirm]: ";
1099 chop($read = <STDIN>);
1100 $read =~ s/^\s*//;
1101 $read =~ s/\s*$//;
1102 return 1 unless $read;
1103
1104 if (($confirm eq "y" && $read =~ "$yes") ||
1105 ($confirm eq "n" && $read =~ "$no")) {
1106 return 1;
1107 }
1108
1109 if ($read !~ "$yes" && $read !~ "$no") {
1110 warn "Wrong value. Enter again!\a\n";
1111 return &confirm_yn($message, $confirm);
1112 }
1113 return 0;
1114 }
1115
1116 # test if $dotdir exist
1117 # return "no" if $dotdir not exist or dotfiles should not copied
1118 sub dotdir_default {
1119 local($dir) = $dotdir;
1120
1121 return &dotdir_default_valid($dir) unless $verbose;
1122 while($verbose) {
1123 $dir = &confirm_list("Copy dotfiles from:", 1,
1124 $dir, ("no", $dotdir_bak, $dir));
1125 last if $dir eq &dotdir_default_valid($dir);
1126 }
1127 warn "Do not copy dotfiles.\n" if $verbose && $dir eq "no";
1128
1129 $changes++ if $dir ne $dotdir;
1130 return $dir;
1131 }
1132
1133 sub dotdir_default_valid {
1134 local($dir) = @_;
1135
1136 return $dir if (-e $dir && -r _ && (-d _ || -l $dir) && $dir =~ "^/");
1137 return $dir if $dir eq "no";
1138 warn "Dotdir ``$dir'' is not a directory\a\n";
1139 return "no";
1140 }
1141
1142 # ask for messages to new users
1143 sub message_default {
1144 local($file) = $send_message;
1145 local(@d) = ($file, $send_message_bak, "no");
1146
1147 while($verbose) {
1148 $file = &confirm_list("Send message from file:", 1, $file, @d);
1149 last if $file eq "no";
1150 last if &filetest($file, 1);
1151
1152 # maybe create message file
1153 &message_create($file) if &confirm_yn("Create ``$file''?", "yes");
1154 last if &filetest($file, 0);
1155 last if !&confirm_yn("File ``$file'' does not exist, try again?",
1156 "yes");
1157 }
1158
1159 if ($file eq "no" || !&filetest($file, 0)) {
1160 warn "Do not send message\n" if $verbose;
1161 $file = "no";
1162 } else {
1163 &message_read($file);
1164 }
1165
1166 $changes++ if $file ne $send_message && $verbose;
1167 return $file;
1168 }
1169
1170 # create message file
1171 sub message_create {
1172 local($file) = @_;
1173
1174 rename($file, "$file.bak");
1175 if (!open(M, "> $file")) {
1176 warn "Messagefile ``$file'': $!\n"; return 0;
1177 }
1178 print M <<EOF;
1179 #
1180 # Message file for adduser(8)
1181 # comment: ``#''
1182 # default variables: \$name, \$fullname, \$password
1183 # other variables: see /etc/adduser.conf after
1184 # line ``$do_not_delete''
1185 #
1186
1187 \$fullname,
1188
1189 your account ``\$name'' was created. Your password is ``\$password''.
1190 Please expire your password. Have fun!
1191
1192 See also chpass(1), finger(1), passwd(1)
1193 EOF
1194 close M;
1195 return 1;
1196 }
1197
1198 # read message file into buffer
1199 sub message_read {
1200 local($file) = @_;
1201 @message_buffer = '';
1202
1203 if (!open(R, "$file")) {
1204 warn "File ``$file'':$!\n"; return 0;
1205 }
1206 while(<R>) {
1207 push(@message_buffer, $_) unless /^\s*#/;
1208 }
1209 close R;
1210 }
1211
1212 # write @list to $file with file-locking
1213 sub append_file {
1214 local($file,@list) = @_;
1215 local($e);
1216 local($LOCK_EX) = 2;
1217 local($LOCK_NB) = 4;
1218 local($LOCK_UN) = 8;
1219
1220 open(F, ">> $file") || die "$file: $!\n";
1221 print "Lock $file.\n" if $verbose > 1;
1222 while(!flock(F, $LOCK_EX | $LOCK_NB)) {
1223 warn "Cannot lock file: $file\a\n";
1224 die "Sorry, give up\n"
1225 unless &confirm_yn("Try again?", "yes");
1226 }
1227 print F join("\n", @list) . "\n";
1228 close F;
1229 print "Unlock $file.\n" if $verbose > 1;
1230 flock(F, $LOCK_UN);
1231 }
1232
1233 # return free uid+gid
1234 # uid == gid if possible
1235 sub next_id {
1236 local($group) = @_;
1237
1238 $uid_start = 1000 if ($uid_start <= 0 || $uid_start >= $uid_end);
1239 # looking for next free uid
1240 while($uid{$uid_start}) {
1241 $uid_start++;
1242 $uid_start = 1000 if $uid_start >= $uid_end;
1243 print "$uid_start\n" if $verbose > 1;
1244 }
1245
1246 local($gid_start) = $uid_start;
1247 # group for user (username==groupname) already exist
1248 if ($groupname{$group}) {
1249 $gid_start = $groupname{$group};
1250 }
1251 # gid is in use, looking for another gid.
1252 # Note: uid an gid are not equal
1253 elsif ($gid{$uid_start}) {
1254 while($gid{$gid_start} || $uid{$gid_start}) {
1255 $gid_start--;
1256 $gid_start = $uid_end if $gid_start < 100;
1257 }
1258 }
1259 return ($uid_start, $gid_start);
1260 }
1261
1262 # read config file
1263 sub config_read {
1264 local($opt) = @_;
1265 local($user_flag) = 0;
1266
1267 # don't read config file
1268 return 1 if $opt =~ /-(noconfig|config_create)/ || !$config_read;
1269
1270 if(!open(C, "$config")) {
1271 warn "$config: $!\n"; return 0;
1272 }
1273
1274 while(<C>) {
1275 # user defined variables
1276 /^$do_not_delete/ && $user_flag++;
1277 # found @array or $variable
1278 if (s/^(\w+\s*=\s*\()/\@$1/ || s/^(\w+\s*=)/\$$1/) {
1279 eval $_;
1280 #warn "$_";
1281 }
1282 # lines with '^##' are not saved
1283 push(@user_variable_list, $_)
1284 if $user_flag && !/^##/ && (s/^[\$\@]// || /^[#\s]/);
1285 }
1286 #warn "X @user_variable_list X\n";
1287 close C;
1288 }
1289
1290
1291 # write config file
1292 sub config_write {
1293 local($silent) = @_;
1294
1295 # nothing to do
1296 return 1 unless ($changes || ! -e $config || !$config_read || $silent);
1297
1298 if (!$silent) {
1299 if (-e $config) {
1300 return 1 if &confirm_yn("\nWrite your changes to $config?", "no");
1301 } else {
1302 return 1 unless
1303 &confirm_yn("\nWrite your configuration to $config?", "yes");
1304 }
1305 }
1306
1307 rename($config, "$config.bak");
1308 open(C, "> $config") || die "$config: $!\n";
1309
1310 # prepare some variables
1311 $send_message = "no" unless $send_message;
1312 $defaultpasswd = "no" unless $defaultpasswd;
1313 local($shpref) = "'" . join("', '", @shellpref) . "'";
1314 local($shpath) = "'" . join("', '", @path) . "'";
1315 local($user_var) = join('', @user_variable_list);
1316
1317 print C <<EOF;
1318 #
1319 # $config - automatic generated by adduser(8)
1320 #
1321 # Note: adduser read *and* write this file.
1322 # You may change values, but don't add new things befor the
1323 # line ``$do_not_delete''
1324 #
1325
1326 # verbose = [0-2]
1327 verbose = $verbose
1328
1329 # use password for new users
1330 # defaultpasswd = yes | no
1331 defaultpasswd = $defaultpasswd
1332
1333 # copy dotfiles from this dir ("/usr/share/skel" or "no")
1334 dotdir = "$dotdir"
1335
1336 # send this file to new user ("/etc/adduser.message" or "no")
1337 send_message = "$send_message"
1338
1339 # config file for adduser ("/etc/adduser.conf")
1340 config = "$config"
1341
1342 # logfile ("/var/log/adduser" or "no")
1343 logfile = "$logfile"
1344
1345 # default HOME directory ("/home")
1346 home = "$home"
1347
1348 # List of directories where shells located
1349 # path = ('/bin', '/usr/bin', '/usr/local/bin')
1350 path = ($shpath)
1351
1352 # common shell list, first element has higher priority
1353 # shellpref = ('bash', 'tcsh', 'ksh', 'csh', 'sh')
1354 shellpref = ($shpref)
1355
1356 # defaultshell if not empty ("bash")
1357 defaultshell = "$defaultshell"
1358
1359 # defaultgroup ('USER' for same as username or any other valid group
1360 defaultgroup = $defaultgroup
1361
1362 # new users get this uid (1000)
1363 uid_start = 1000
1364
1365 $do_not_delete
1366 ## your own variables, see /etc/adduser.message
1367 $user_var
1368
1369 ## end
1370 EOF
1371 close C;
1372 }
1373
1374 ################
1375 # main
1376 #
1377 $test = 0; # test mode, only for development
1378 $check_only = 0;
1379
1380 &check_root; # you must be root to run this script!
1381 &variables; # initialize variables
1382 &config_read(@ARGV); # read variables form config-file
1383 &parse_arguments(@ARGV); # parse arguments
1384
1385 if (!$check_only && $#batch < 0) {
1386 &copyright; &hints;
1387 }
1388
1389 # check
1390 $changes = 0;
1391 &passwd_check; # check for valid passwdb
1392 &shells_read; # read /etc/shells
1393 &passwd_read; # read /etc/master.passwd
1394 &group_read; # read /etc/group
1395 &group_check; # check for incon*
1396 exit 0 if $check_only; # only check consistence and exit
1397
1398 exit(!&batch(@batch)) if $#batch >= 0; # batch mode
1399
1400 # interactive
1401 # some questions
1402 &shells_add; # maybe add some new shells
1403 $defaultshell = &shell_default; # enter default shell
1404 $home = &home_partition($home); # find HOME partition
1405 $dotdir = &dotdir_default; # check $dotdir
1406 $send_message = &message_default; # send message to new user
1407 $defaultpasswd = &password_default; # maybe use password
1408 &config_write(!$verbose); # write variables in file
1409
1410 # main loop for creating new users
1411 &new_users; # add new users
1412
1413 #end