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