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