]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.sbin/adduser/adduser.sh
Revert "dtrace: make 'ring' and 'fill' policies imply 'noswitch' flag"
[FreeBSD/FreeBSD.git] / usr.sbin / adduser / adduser.sh
1 #!/bin/sh
2 #
3 # SPDX-License-Identifier: BSD-2-Clause
4 #
5 # Copyright (c) 2002-2004 Michael Telahun Makonnen. All rights reserved.
6 #
7 # Redistribution and use in source and binary forms, with or without
8 # modification, are permitted provided that the following conditions
9 # are met:
10 # 1. Redistributions of source code must retain the above copyright
11 #    notice, this list of conditions and the following disclaimer.
12 # 2. Redistributions in binary form must reproduce the above copyright
13 #    notice, this list of conditions and the following disclaimer in the
14 #    documentation and/or other materials provided with the distribution.
15 #
16 # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17 # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 # IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21 # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 #
27 #       Email: Mike Makonnen <mtm@FreeBSD.Org>
28 #
29 #
30
31 # err msg
32 #       Display $msg on stderr, unless we're being quiet.
33 #
34 err() {
35         if [ -z "$quietflag" ]; then
36                 echo 1>&2 ${THISCMD}: ERROR: $*
37         fi
38 }
39
40 # info msg
41 #       Display $msg on stdout, unless we're being quiet.
42 #
43 info() {
44         if [ -z "$quietflag" ]; then
45                 echo ${THISCMD}: INFO: $*
46         fi
47 }
48
49 # get_nextuid
50 #       Output the value of $_uid if it is available for use. If it
51 #       is not, output the value of the next higher uid that is available.
52 #       If a uid is not specified, output the first available uid, as indicated
53 #       by pw(8).
54 #
55 get_nextuid () {
56         local _uid=$1 _nextuid
57
58         if [ -z "$_uid" ]; then
59                 _nextuid="$(${PWCMD} usernext | cut -f1 -d:)"
60         else
61                 while : ; do
62                         if ! ${PWCMD} usershow $_uid > /dev/null 2>&1; then
63                                 _nextuid=$_uid
64                                 break
65                         fi
66                         _uid=$((_uid + 1))
67                 done
68         fi
69         echo $_nextuid
70 }
71
72 # show_usage
73 #       Display usage information for this utility.
74 #
75 show_usage() {
76         echo "usage: ${THISCMD} [options]"
77         echo "  options may include:"
78         echo "  -C              save to the configuration file only"
79         echo "  -D              do not attempt to create the home directory"
80         echo "  -E              disable this account after creation"
81         echo "  -G              additional groups to add accounts to"
82         echo "  -L              login class of the user"
83         echo "  -M              file permission for home directory"
84         echo "  -N              do not read configuration file"
85         echo "  -Z              do not attempt to create ZFS home dataset"
86         echo "  -S              a nonexistent shell is not an error"
87         echo "  -d              home directory"
88         echo "  -f              file from which input will be received"
89         echo "  -g              default login group"
90         echo "  -h              display this usage message"
91         echo "  -k              path to skeleton home directory"
92         echo "  -m              user welcome message file"
93         echo "  -q              absolute minimal user feedback"
94         echo "  -s              shell"
95         echo "  -u              uid to start at"
96         echo "  -w              password type: no, none, yes or random"
97 }
98
99 # valid_shells
100 #       Outputs a list of valid shells from /etc/shells. Only the
101 #       basename of the shell is output.
102 #
103 valid_shells() {
104         local _prefix
105
106         ${GREPCMD} '^[^#]' ${ETCSHELLS} |
107         while read _path _junk ; do
108                 echo -n "${_prefix}${_path##*/}"
109                 _prefix=' '
110         done
111
112         # /usr/sbin/nologin is a special case
113         [ -x "${NOLOGIN_PATH}" ] && echo -n " ${NOLOGIN}"
114 }
115
116 # fullpath_from_shell shell
117 #       Given $shell, which is either the full path to a shell or
118 #       the basename component of a valid shell, get the
119 #       full path to the shell from the /etc/shells file.
120 #
121 fullpath_from_shell() {
122         local _shell=$1 _fullpath
123
124         if [ -z "$_shell" ]; then
125                 return
126         fi
127
128         # /usr/sbin/nologin is a special case; it needs to be handled
129         # before the grep | while loop, since a 'return' from within
130         # a subshell will not terminate the function's execution, and
131         # the path to the nologin shell might be printed out twice.
132         #
133         if [ "$_shell" = "${NOLOGIN}" ] ||
134             [ "$_shell" = "${NOLOGIN_PATH}" ]; then
135                 echo ${NOLOGIN_PATH}
136                 return
137         fi
138
139         ${GREPCMD} '^[^#]' ${ETCSHELLS} |
140         while read _path _junk ; do
141                 if [ "$_path" = "$_shell" ] ||
142                     [ "${_path##*/}" = "$_shell" ]; then
143                         echo "$_path"
144                         break
145                 fi
146         done
147 }
148
149 # shell_exists shell
150 #       If the given shell is listed in ${ETCSHELLS} or it is
151 #       the nologin shell this function will return 0.
152 #       Otherwise, it will return 1. If shell is valid but
153 #       the path is invalid or it is not executable it
154 #       will emit an informational message saying so.
155 #
156 shell_exists() {
157         local _sh="$1"
158
159         if [ -z "$(fullpath_from_shell "$_sh")" ] ; then
160                 err "Invalid shell ($_sh) for user $username."
161                 return 1
162         fi
163         [ -x "$_sh" ] ||
164             info "The shell ($_sh) does not exist or is not executable."
165         return 0
166 }
167
168 # save_config
169 #       Save some variables to a configuration file.
170 #       Note: not all script variables are saved, only those that
171 #             it makes sense to save.
172 #
173 save_config() {
174         echo "# Configuration file for adduser(8)."     >  ${ADDUSERCONF}
175         echo "# NOTE: only *some* variables are saved." >> ${ADDUSERCONF}
176         echo "# Last Modified on $(${DATECMD})."        >> ${ADDUSERCONF}
177         echo ''                         >> ${ADDUSERCONF}
178         echo "defaultHomePerm=$uhomeperm" >> ${ADDUSERCONF}
179         echo "defaultLgroup=$ulogingroup" >> ${ADDUSERCONF}
180         echo "defaultclass=$uclass"     >> ${ADDUSERCONF}
181         echo "defaultgroups=$ugroups"   >> ${ADDUSERCONF}
182         echo "passwdtype=$passwdtype"   >> ${ADDUSERCONF}
183         echo "homeprefix=$homeprefix"   >> ${ADDUSERCONF}
184         echo "defaultshell=$ushell"     >> ${ADDUSERCONF}
185         echo "udotdir=$udotdir"         >> ${ADDUSERCONF}
186         echo "msgfile=$msgfile"         >> ${ADDUSERCONF}
187         echo "disableflag=$disableflag" >> ${ADDUSERCONF}
188         echo "uidstart=$uidstart"       >> ${ADDUSERCONF}
189 }
190
191 # add_user
192 #       Add a user to the user database. If the user chose to send a welcome
193 #       message or lock the account, do so.
194 #
195 add_user() {
196         local _uid _name _comment _gecos _home _group _grouplist _shell _class
197         local _dotdir _expire _pwexpire _passwd _upasswd _passwdmethod
198
199         # Is this a configuration run? If so, don't modify user database.
200         #
201         if [ -n "$configflag" ]; then
202                 save_config
203                 return
204         fi
205
206         _name="-n '$username'"
207         [ -n "$uuid" ] && _uid='-u "$uuid"'
208         [ -n "$ulogingroup" ] && _group='-g "$ulogingroup"'
209         [ -n "$ugroups" ] && _grouplist='-G "$ugroups"'
210         [ -n "$ushell" ] && _shell='-s "$ushell"'
211         [ -n "$uclass" ] && _class='-L "$uclass"'
212         [ -n "$ugecos" ] && _comment='-c "$ugecos"'
213         [ -n "$udotdir" ] && _dotdir='-k "$udotdir"'
214         [ -n "$uexpire" ] && _expire='-e "$uexpire"'
215         [ -n "$upwexpire" ] && _pwexpire='-p "$upwexpire"'
216         if [ -z "$Dflag" ] && [ -n "$uhome" ]; then
217                 # The /nonexistent home directory is special. It
218                 # means the user has no home directory.
219                 if [ "$uhome" = "$NOHOME" ]; then
220                         _home='-d "$uhome"'
221                 else
222                         # Use home directory permissions if specified
223                         if [ -n "$uhomeperm" ]; then
224                                 _home='-m -d "$uhome" -M "$uhomeperm"'
225                         else
226                                 _home='-m -d "$uhome"'
227                         fi
228                 fi
229         elif [ -n "$Dflag" ] && [ -n "$uhome" ]; then
230                 _home='-d "$uhome"'
231         fi
232         case $passwdtype in
233         no)
234                 _passwdmethod="-w no"
235                 _passwd="-h -"
236                 ;;
237         yes)
238                 # Note on processing the password: The outer double quotes
239                 # make literal everything except ` and \ and $.
240                 # The outer single quotes make literal ` and $.
241                 # We can ensure the \ isn't treated specially by specifying
242                 # the -r switch to the read command used to obtain the input.
243                 #
244                 _passwdmethod="-w yes"
245                 _passwd="-h 0"
246                 _upasswd='echo "$upass" |'
247                 ;;
248         none)
249                 _passwdmethod="-w none"
250                 ;;
251         random)
252                 _passwdmethod="-w random"
253                 ;;
254         esac
255
256         # create ZFS dataset before home directory is created with pw
257         if [ "${Zcreate}" = "yes" ]; then
258                 if [ "${Zencrypt}" = "yes" ]; then
259                         echo "Enter encryption keyphrase for ZFS dataset (${zhome}):"
260                 fi
261                 if [ -n "$BSDINSTALL_CHROOT" ]; then
262                         create_zfs_chrooted_dataset
263                 else
264                         if ! create_zfs_dataset; then
265                                 err "There was an error adding user ($username)."
266                                 return 1
267                         fi
268                 fi
269         fi
270
271         _pwcmd="$_upasswd ${PWCMD} useradd $_uid $_name $_group $_grouplist $_comment"
272         _pwcmd="$_pwcmd $_shell $_class $_home $_dotdir $_passwdmethod $_passwd"
273         _pwcmd="$_pwcmd $_expire $_pwexpire"
274
275         if ! _output=$(eval $_pwcmd) ; then
276                 err "There was an error adding user ($username)."
277                 return 1
278         else
279                 info "Successfully added ($username) to the user database."
280                 if [ "random" = "$passwdtype" ]; then
281                         randompass="$_output"
282                         info "Password for ($username) is: $randompass"
283                 fi
284         fi
285
286         if [ -n "$disableflag" ]; then
287                 if ${PWCMD} lock $username ; then
288                         info "Account ($username) is locked."
289                 else
290                         info "Account ($username) could NOT be locked."
291                 fi
292         fi
293
294         # give newly created user permissions to their home zfs dataset
295         if [ "${Zcreate}" = "yes" ]; then
296                 set_zfs_perms
297                 if [ -n "$BSDINSTALL_CHROOT" ]; then
298                         umount_legacy_zfs
299                 fi
300         fi
301
302         local _line _owner _perms _file _dir
303         if [ -n "$msgflag" ]; then
304                 if [ -r "$msgfile" ]; then
305                         # We're evaluating the contents of an external file.
306                         # Let's not open ourselves up for attack. _perms will
307                         # be empty if it's writeable only by the owner. _owner
308                         # will *NOT* be empty if the file is owned by root.
309                         #
310                         _dir="$(dirname "$msgfile")"
311                         _file="$(basename "$msgfile")"
312                         _perms=$(/usr/bin/find "$_dir" -name "$_file" -perm +07022 -prune)
313                         _owner=$(/usr/bin/find "$_dir" -name "$_file" -user 0 -prune)
314                         if [ -z "$_owner" ] || [ -n "$_perms" ]; then
315                                 err "The message file ($msgfile) may be writeable only by root."
316                                 return 1
317                         fi
318                         while read _line ; do
319                                 eval echo "$_line"
320                         done <"$msgfile" | ${MAILCMD} -s"Welcome" ${username}
321                         info "Sent welcome message to ($username)."
322                 fi
323         fi
324 }
325
326 # get_user
327 #       Reads username of the account from standard input or from a global
328 #       variable containing an account line from a file. The username is
329 #       required. If this is an interactive session it will prompt in
330 #       a loop until a username is entered. If it is batch processing from
331 #       a file it will output an error message and return to the caller.
332 #
333 get_user() {
334         local _input
335
336         # No need to take down user names if this is a configuration saving run.
337         [ -n "$configflag" ] && return
338
339         while : ; do
340                 if [ -z "$fflag" ]; then
341                         echo -n "Username: "
342                         read _input
343                 else
344                         _input="$(echo "$fileline" | cut -f1 -d:)"
345                 fi
346
347                 # There *must* be a username, and it must not exist. If
348                 # this is an interactive session give the user an
349                 # opportunity to retry.
350                 #
351                 if [ -z "$_input" ]; then
352                         err "You must enter a username!"
353                         [ -z "$fflag" ] && continue
354                 fi
355                 if ${PWCMD} usershow "$_input" > /dev/null 2>&1; then
356                         err "User exists!"
357                         [ -z "$fflag" ] && continue
358                 fi
359                 break
360         done
361         username="$_input"
362 }
363
364 # get_gecos
365 #       Reads extra information about the user. Can be used both in interactive
366 #       and batch (from file) mode.
367 #
368 get_gecos() {
369         local _input
370
371         # No need to take down additional user information for a configuration run.
372         [ -n "$configflag" ] && return
373
374         if [ -z "$fflag" ]; then
375                 echo -n "Full name: "
376                 read _input
377         else
378                 _input="$(echo "$fileline" | cut -f7 -d:)"
379         fi
380         ugecos="$_input"
381 }
382
383 # get_shell
384 #       Get the account's shell. Works in interactive and batch mode. It
385 #       accepts either the base name of the shell or the full path.
386 #       If an invalid shell is entered it will simply use the default shell.
387 #
388 get_shell() {
389         local _input _fullpath
390         ushell="$defaultshell"
391
392         # Make sure the current value of the shell is a valid one
393         if [ -z "$Sflag" ]; then
394                 if ! shell_exists $ushell ; then
395                         info "Using default shell ${defaultshell}."
396                         ushell="$defaultshell"
397                 fi
398         fi
399
400         if [ -z "$fflag" ]; then
401                 echo -n "Shell ($shells) [${ushell##*/}]: "
402                 read _input
403         else
404                 _input="$(echo "$fileline" | cut -f9 -d:)"
405         fi
406         if [ -n "$_input" ]; then
407                 if [ -n "$Sflag" ]; then
408                         ushell="$_input"
409                 else
410                         _fullpath=$(fullpath_from_shell "$_input")
411                         if [ -n "$_fullpath" ]; then
412                                 ushell="$_fullpath"
413                         else
414                                 err "Invalid shell ($_input) for user $username."
415                                 info "Using default shell ${defaultshell}."
416                                 ushell="$defaultshell"
417                         fi
418                 fi
419         fi
420 }
421
422 # get_homedir
423 #       Reads the account's home directory. Used both with interactive input
424 #       and batch input.
425 #
426 get_homedir() {
427         _input=
428         if [ -z "$fflag" ]; then
429                 echo -n "Home directory [${homeprefix}/${username}]: "
430                 read _input
431         else
432                 _input="$(echo "$fileline" | cut -f8 -d:)"
433         fi
434
435         if [ -n "$_input" ]; then
436                 uhome="$_input"
437                 # if this is a configuration run, then user input is the home
438                 # directory prefix. Otherwise it is understood to
439                 # be $prefix/$user
440                 #
441                 [ -z "$configflag" ] &&
442                     homeprefix="$(dirname "$uhome")" ||
443                     homeprefix="$uhome"
444         else
445                 uhome="${homeprefix}/${username}"
446         fi
447 }
448
449 # get_homeperm
450 #       Reads the account's home directory permissions.
451 #
452 get_homeperm() {
453         local _input _prompt
454         uhomeperm=$defaultHomePerm
455
456         if [ -n "$uhomeperm" ]; then
457                 _prompt="Home directory permissions [${uhomeperm}]: "
458         else
459                 _prompt="Home directory permissions (Leave empty for default): "
460         fi
461         if [ -z "$fflag" ]; then
462                 echo -n "$_prompt"
463                 read _input
464         fi
465
466         if [ -n "$_input" ]; then
467                 uhomeperm="$_input"
468         fi
469 }
470
471 # get_zfs_home
472 #       Determine if homeprefix is located on a ZFS filesystem and if
473 #       so, enable ZFS home dataset creation.
474 #
475 get_zfs_home() {
476         local _prefix
477
478         # check if zfs kernel module is loaded before attempting to run zfs to
479         # prevent loading the kernel module on systems that don't use ZFS
480         if ! "$KLDSTATCMD" -q -m zfs ||
481                 Zcreate="no"
482                 return
483         fi
484         if ! _prefix=$(${ZFSCMD} list -Ho name "${homeprefix}" 2>/dev/null) ||
485             [ -z "${_prefix}" ]; then
486                 Zcreate="no"
487                 return
488         fi
489         zhome="${_prefix}/${username}"
490 }
491
492 # get_uid
493 #       Reads a numeric userid in an interactive or batch session. Automatically
494 #       allocates one if it is not specified.
495 #
496 get_uid() {
497         local _input _prompt
498         uuid=${uidstart}
499
500         if [ -n "$uuid" ]; then
501                 uuid=$(get_nextuid "$uuid")
502                 _prompt="Uid [$uuid]: "
503         else
504                 _prompt="Uid (Leave empty for default): "
505         fi
506         if [ -z "$fflag" ]; then
507                 echo -n "$_prompt"
508                 read _input
509         else
510                 _input="$(echo "$fileline" | cut -f2 -d:)"
511         fi
512
513         [ -n "$_input" ] && uuid=$_input
514         uuid=$(get_nextuid "$uuid")
515         uidstart=$uuid
516 }
517
518 # get_class
519 #       Reads login class of account. Can be used in interactive or batch mode.
520 #
521 get_class() {
522         local _input _uclass
523         uclass="$defaultclass"
524         _class=${uclass:-"default"}
525
526         if [ -z "$fflag" ]; then
527                 echo -n "Login class [$_class]: "
528                 read _input
529         else
530                 _input="$(echo "$fileline" | cut -f4 -d:)"
531         fi
532
533         [ -n "$_input" ] && uclass="$_input"
534 }
535
536 # get_logingroup
537 #       Reads user's login group. Can be used in both interactive and batch
538 #       modes. The specified value can be a group name or its numeric id.
539 #       This routine leaves the field blank if nothing is provided and
540 #       a default login group has not been set. The pw(8) command
541 #       will then provide a login group with the same name as the username.
542 #
543 get_logingroup() {
544         local _input
545         ulogingroup="$defaultLgroup"
546
547         if [ -z "$fflag" ]; then
548                 echo -n "Login group [${ulogingroup:-$username}]: "
549                 read _input
550         else
551                 _input="$(echo "$fileline" | cut -f3 -d:)"
552         fi
553
554         # Pw(8) will use the username as login group if it's left empty
555         [ -n "$_input" ] && ulogingroup="$_input"
556 }
557
558 # get_groups
559 #       Read additional groups for the user. It can be used in both interactive
560 #       and batch modes.
561 #
562 get_groups() {
563         local _input _group
564         ugroups="$defaultgroups"
565         _group=${ulogingroup:-"${username}"}
566
567         if [ -z "$configflag" ]; then
568                 [ -z "$fflag" ] && echo -n "Login group is $_group. Invite $username"
569                 [ -z "$fflag" ] && echo -n " into other groups? [$ugroups]: "
570         else
571                 [ -z "$fflag" ] && echo -n "Enter additional groups [$ugroups]: "
572         fi
573         read _input
574
575         [ -n "$_input" ] && ugroups="$_input"
576 }
577
578 # get_expire_dates
579 #       Read expiry information for the account and also for the password. This
580 #       routine is used only from batch processing mode.
581 #
582 get_expire_dates() {
583         upwexpire="$(echo "$fileline" | cut -f5 -d:)"
584         uexpire="$(echo "$fileline" | cut -f6 -d:)"
585 }
586
587 # get_password
588 #       Read the password in batch processing mode. The password field matters
589 #       only when the password type is "yes" or "random". If the field is empty and the
590 #       password type is "yes", then it assumes the account has an empty passsword
591 #       and changes the password type accordingly. If the password type is "random"
592 #       and the password field is NOT empty, then it assumes the account will NOT
593 #       have a random password and set passwdtype to "yes."
594 #
595 get_password() {
596         # We may temporarily change a password type. Make sure it's changed
597         # back to whatever it was before we process the next account.
598         #
599         if [ -n "$savedpwtype" ]; then
600                 passwdtype=$savedpwtype
601                 savedpwtype=
602         fi
603
604         # There may be a ':' in the password
605         upass=${fileline#*:*:*:*:*:*:*:*:*:}
606
607         if [ -z "$upass" ]; then
608                 case $passwdtype in
609                 yes)
610                         # if it's empty, assume an empty password
611                         passwdtype=none
612                         savedpwtype=yes
613                         ;;
614                 esac
615         else
616                 case $passwdtype in
617                 random)
618                         passwdtype=yes
619                         savedpwtype=random
620                         ;;
621                 esac
622         fi
623 }
624
625 # get_zfs_encryption
626 #       Ask user if they want to enable encryption on their ZFS home dataset.
627 #
628 get_zfs_encryption() {
629         local _input _prompt
630         _prompt="Enable ZFS encryption? (yes/no) [${Zencrypt}]: "
631         while : ; do
632                 echo -n "$_prompt"
633                 read _input
634
635                 [ -z "$_input" ] && _input=$Zencrypt
636                 case $_input in
637                 [Nn][Oo]|[Nn])
638                         Zencrypt="no"
639                         break
640                         ;;
641                 [Yy][Ee][Ss]|[Yy][Ee]|[Yy])
642                         Zencrypt="yes"
643                         break
644                         ;;
645                 *)
646                         # invalid answer; repeat loop
647                         continue
648                         ;;
649                 esac
650         done
651
652         if [ "${Zencrypt}" = "yes" ]; then
653                 zfsopt="-o encryption=on -o keylocation=prompt -o keyformat=passphrase"
654         fi
655 }
656
657 # create_zfs_chrooted_dataset
658 #   Create ZFS dataset owned by the user that was just added within a bsdinstall chroot
659 #
660 create_zfs_chrooted_dataset() {
661         if ! ${ZFSCMD} create -u ${zfsopt} "${zhome}"; then
662                 err "There was an error creating ZFS dataset (${zhome})."
663                 return 1
664         fi
665         ${ZFSCMD} set mountpoint=legacy "${zhome}"
666         ${MKDIRCMD} -p "${uhome}"
667         ${MOUNTCMD} -t zfs "${zhome}" "${uhome}"
668 }
669
670 # umount_legacy_zfs
671 #   Unmount ZFS home directory created as a legacy mount and switch inheritance
672 #
673 umount_legacy_zfs() {
674         ${UMOUNTCMD} "${uhome}"
675         ${ZFSCMD} inherit mountpoint "${zhome}"
676 }
677
678 # create_zfs_dataset
679 #   Create ZFS dataset owned by the user that was just added.
680 #
681 create_zfs_dataset() {
682         if ! ${ZFSCMD} create ${zfsopt} "${zhome}"; then
683                 err "There was an error creating ZFS dataset (${zhome})."
684                 return 1
685         else
686                 info "Successfully created ZFS dataset (${zhome})."
687         fi
688 }
689
690 # set_zfs_perms
691 #   Give new user ownership of newly created zfs dataset.
692 #
693 set_zfs_perms() {
694         if ! ${ZFSCMD} allow "${username}" create,destroy,mount,snapshot "${zhome}"; then
695                 err "There was an error setting permissions on ZFS dataset (${zhome})."
696                 return 1
697         fi
698 }
699
700 # input_from_file
701 #       Reads a line of account information from standard input and
702 #       adds it to the user database.
703 #
704 input_from_file() {
705         local _field
706
707         while read -r fileline ; do
708                 case "$fileline" in
709                 \#*|'')
710                         ;;
711                 *)
712                         get_user || continue
713                         get_gecos
714                         get_uid
715                         get_logingroup
716                         get_class
717                         get_shell
718                         get_homedir
719                         get_zfs_home
720                         get_homeperm
721                         get_password
722                         get_expire_dates
723                         ugroups="$defaultgroups"
724
725                         add_user
726                         ;;
727                 esac
728         done
729 }
730
731 # input_interactive
732 #       Prompts for user information interactively, and commits to
733 #       the user database.
734 #
735 input_interactive() {
736         local _disable _pass _passconfirm _input
737         local _random="no"
738         local _emptypass="no"
739         local _usepass="yes"
740         local _logingroup_ok="no"
741         local _groups_ok="no"
742         local _all_ok="yes"
743         local _another_user="no"
744         case $passwdtype in
745         none)
746                 _emptypass="yes"
747                 _usepass="yes"
748                 ;;
749         no)
750                 _usepass="no"
751                 ;;
752         random)
753                 _random="yes"
754                 ;;
755         esac
756
757         get_user
758         get_gecos
759         get_uid
760
761         # The case where group = user is handled elsewhere, so
762         # validate any other groups the user is invited to.
763         until [ "$_logingroup_ok" = yes ]; do
764                 get_logingroup
765                 _logingroup_ok=yes
766                 if [ -n "$ulogingroup" ] && [ "$username" != "$ulogingroup" ]; then
767                         if ! ${PWCMD} show group $ulogingroup > /dev/null 2>&1; then
768                                 echo "Group $ulogingroup does not exist!"
769                                 _logingroup_ok=no
770                         fi
771                 fi
772         done
773         until [ "$_groups_ok" = yes ]; do
774                 get_groups
775                 _groups_ok=yes
776                 for i in $ugroups; do
777                         if [ "$username" != "$i" ]; then
778                                 if ! ${PWCMD} show group $i > /dev/null 2>&1; then
779                                         echo "Group $i does not exist!"
780                                         _groups_ok=no
781                                 fi
782                         fi
783                 done
784         done
785
786         get_class
787         get_shell
788         get_homedir
789         get_homeperm
790         get_zfs_home
791         [ "$Zcreate" = "yes" ] && get_zfs_encryption
792
793         while : ; do
794                 echo -n "Use password-based authentication? [$_usepass]: "
795                 read _input
796                 [ -z "$_input" ] && _input=$_usepass
797                 case $_input in
798                 [Nn][Oo]|[Nn])
799                         passwdtype="no"
800                         ;;
801                 [Yy][Ee][Ss]|[Yy][Ee]|[Yy])
802                         while : ; do
803                                 echo -n "Use an empty password? (yes/no) [$_emptypass]: "
804                                 read _input
805                                 [ -n "$_input" ] && _emptypass=$_input
806                                 case $_emptypass in
807                                 [Nn][Oo]|[Nn])
808                                         echo -n "Use a random password? (yes/no) [$_random]: "
809                                         read _input
810                                         [ -n "$_input" ] && _random="$_input"
811                                         case $_random in
812                                         [Yy][Ee][Ss]|[Yy][Ee]|[Yy])
813                                                 passwdtype="random"
814                                                 break
815                                                 ;;
816                                         esac
817                                         passwdtype="yes"
818                                         [ -n "$configflag" ] && break
819                                         trap 'stty echo; exit' 0 1 2 3 15
820                                         stty -echo
821                                         echo -n "Enter password: "
822                                         IFS= read -r upass
823                                         echo''
824                                         echo -n "Enter password again: "
825                                         IFS= read -r _passconfirm
826                                         echo ''
827                                         stty echo
828                                         # if user entered a blank password
829                                         # explicitly ask again.
830                                         [ -z "$upass$_passconfirm" ] && continue
831                                         ;;
832                                 [Yy][Ee][Ss]|[Yy][Ee]|[Yy])
833                                         passwdtype="none"
834                                         break;
835                                         ;;
836                                 *)
837                                         # invalid answer; repeat the loop
838                                         continue
839                                         ;;
840                                 esac
841                                 if [ "$upass" != "$_passconfirm" ]; then
842                                         echo "Passwords did not match!"
843                                         continue
844                                 fi
845                                 break
846                         done
847                         ;;
848                 *)
849                         # invalid answer; repeat loop
850                         continue
851                         ;;
852                 esac
853                 break;
854         done
855         _disable=${disableflag:-"no"}
856         while : ; do
857                 echo -n "Lock out the account after creation? [$_disable]: "
858                 read _input
859                 [ -z "$_input" ] && _input=$_disable
860                 case $_input in
861                 [Nn][Oo]|[Nn])
862                         disableflag=
863                         ;;
864                 [Yy][Ee][Ss]|[Yy][Ee]|[Yy])
865                         disableflag=yes
866                         ;;
867                 *)
868                         # invalid answer; repeat loop
869                         continue
870                         ;;
871                 esac
872                 break
873         done
874
875         # Display the information we have so far and prompt to
876         # commit it.
877         #
878         _disable=${disableflag:-"no"}
879         [ -z "$configflag" ] && printf "%-11s : %s\n" Username $username
880         case $passwdtype in
881         yes)
882                 _pass='*****'
883                 ;;
884         no)
885                 _pass='<disabled>'
886                 ;;
887         none)
888                 _pass='<blank>'
889                 ;;
890         random)
891                 _pass='<random>'
892                 ;;
893         esac
894         [ -z "$configflag" ] && printf "%-11s : %s\n" "Password" "$_pass"
895         [ -n "$configflag" ] && printf "%-11s : %s\n" "Pass Type" "$passwdtype"
896         [ -z "$configflag" ] && printf "%-11s : %s\n" "Full Name" "$ugecos"
897         [ -z "$configflag" ] && printf "%-11s : %s\n" "Uid" "$uuid"
898         [ "$Zcreate" = "yes" ] && [ -z "$configflag" ] &&
899             printf "%-11s : %s\n" "ZFS dataset" "${zhome}"
900         [ "$Zencrypt" = "yes" ] && [ -z "$configflag" ] &&
901             printf "%-11s : %s\n" "Encrypted" "${Zencrypt}"
902         printf "%-11s : %s\n" "Class" "$uclass"
903         printf "%-11s : %s %s\n" "Groups" "${ulogingroup:-$username}" "$ugroups"
904         printf "%-11s : %s\n" "Home" "$uhome"
905         printf "%-11s : %s\n" "Home Mode" "$uhomeperm"
906         printf "%-11s : %s\n" "Shell" "$ushell"
907         printf "%-11s : %s\n" "Locked" "$_disable"
908         while : ; do
909                 echo -n "OK? (yes/no) [$_all_ok]: "
910                 read _input
911                 if [ -z "$_input" ]; then
912                         _input=$_all_ok
913                 fi
914                 case $_input in
915                 [Nn][Oo]|[Nn])
916                         return 1
917                         ;;
918                 [Yy][Ee][Ss]|[Yy][Ee]|[Yy])
919                         add_user
920                         ;;
921                 *)
922                         continue
923                         ;;
924                 esac
925                 break
926         done
927         return 0
928 }
929
930 #### END SUBROUTINE DEFINITION ####
931
932 THISCMD=${0##*/}
933 DEFAULTSHELL=/bin/sh
934 ADDUSERCONF="${ADDUSERCONF:-/etc/adduser.conf}"
935 PWCMD="${PWCMD:-/usr/sbin/pw}"
936 MAILCMD="${MAILCMD:-mail}"
937 ETCSHELLS="${ETCSHELLS:-/etc/shells}"
938 NOHOME="/nonexistent"
939 NOLOGIN="nologin"
940 NOLOGIN_PATH="/usr/sbin/nologin"
941 GREPCMD="/usr/bin/grep"
942 DATECMD="/bin/date"
943 MKDIRCMD="/bin/mkdir"
944 MOUNTCMD="/sbin/mount"
945 UMOUNTCMD="/sbin/umount"
946 ZFSCMD="/sbin/zfs"
947 KLDSTATCMD="/sbin/kldstat"
948
949 # Set default values
950 #
951 username=
952 uuid=
953 uidstart=
954 ugecos=
955 ulogingroup=
956 uclass=
957 uhome=
958 uhomeperm=
959 upass=
960 ushell=
961 udotdir=/usr/share/skel
962 ugroups=
963 uexpire=
964 upwexpire=
965 shells="$(valid_shells)"
966 passwdtype="yes"
967 msgfile=/etc/adduser.msg
968 msgflag=
969 quietflag=
970 configflag=
971 fflag=
972 infile=
973 disableflag=
974 Dflag=
975 Sflag=
976 Zcreate="yes"
977 readconfig="yes"
978 homeprefix="/home"
979 randompass=
980 fileline=
981 savedpwtype=
982 defaultclass=
983 defaultLgroup=
984 defaultgroups=
985 defaultshell="${DEFAULTSHELL}"
986 defaultHomePerm=
987 zfsopt=
988 Zencrypt="no"
989
990 # Make sure the user running this program is root. This isn't a security
991 # measure as much as it is a useful method of reminding the user to
992 # 'su -' before he/she wastes time entering data that won't be saved.
993 #
994 procowner=${procowner:-$(/usr/bin/id -u)}
995 if [ "$procowner" != "0" ]; then
996         err 'you must be the super-user (uid 0) to use this utility.'
997         exit 1
998 fi
999
1000 # Override from our conf file
1001 # Quickly go through the commandline line to see if we should read
1002 # from our configuration file. The actual parsing of the commandline
1003 # arguments happens after we read in our configuration file (commandline
1004 # should override configuration file).
1005 #
1006 for _i in $* ; do
1007         if [ "$_i" = "-N" ]; then
1008                 readconfig=
1009                 break;
1010         fi
1011 done
1012 if [ -n "$readconfig" ] && [ -r "${ADDUSERCONF}" ]; then
1013         . "${ADDUSERCONF}"
1014 fi 
1015
1016 # Process command-line options
1017 #
1018 for _switch ; do
1019         case $_switch in
1020         -L)
1021                 defaultclass="$2"
1022                 shift; shift
1023                 ;;
1024         -C)
1025                 configflag=yes
1026                 shift
1027                 ;;
1028         -D)
1029                 Dflag=yes
1030                 shift
1031                 ;;
1032         -E)
1033                 disableflag=yes
1034                 shift
1035                 ;;
1036         -k)
1037                 udotdir="$2"
1038                 shift; shift
1039                 ;;
1040         -f)
1041                 [ "$2" != "-" ] && infile="$2"
1042                 fflag=yes
1043                 shift; shift
1044                 ;;
1045         -g)
1046                 defaultLgroup="$2"
1047                 shift; shift
1048                 ;;
1049         -G)
1050                 defaultgroups="$2"
1051                 shift; shift
1052                 ;;
1053         -h)
1054                 show_usage
1055                 exit 0
1056                 ;;
1057         -d)
1058                 homeprefix="$2"
1059                 shift; shift
1060                 ;;
1061         -m)
1062                 case "$2" in
1063                 [Nn][Oo])
1064                         msgflag=
1065                         ;;
1066                 *)
1067                         msgflag=yes
1068                         msgfile="$2"
1069                         ;;
1070                 esac
1071                 shift; shift
1072                 ;;
1073         -M)
1074                 defaultHomePerm=$2
1075                 shift; shift
1076                 ;;
1077         -N)
1078                 readconfig=
1079                 shift
1080                 ;;
1081         -w)
1082                 case "$2" in
1083                 no|none|random|yes)
1084                         passwdtype=$2
1085                         ;;
1086                 *)
1087                         show_usage
1088                         exit 1
1089                         ;;
1090                 esac
1091                 shift; shift
1092                 ;;
1093         -q)
1094                 quietflag=yes
1095                 shift
1096                 ;;
1097         -s)
1098                 defaultshell="$(fullpath_from_shell $2)"
1099                 shift; shift
1100                 ;;
1101         -S)
1102                 Sflag=yes
1103                 shift
1104                 ;;
1105         -u)
1106                 uidstart=$2
1107                 shift; shift
1108                 ;;
1109         -Z)
1110                 Zcreate="no"
1111                 shift
1112                 ;;
1113         esac
1114 done
1115
1116 # If the -f switch was used, get input from a file. Otherwise,
1117 # this is an interactive session.
1118 #
1119 if [ -n "$fflag" ]; then
1120         if [ -z "$infile" ]; then
1121                 input_from_file
1122         elif [ -n "$infile" ]; then
1123                 if [ -r "$infile" ]; then
1124                         input_from_file < $infile
1125                 else
1126                         err "File ($infile) is unreadable or does not exist."
1127                 fi
1128         fi
1129 else
1130         input_interactive
1131         while : ; do
1132                 if [ -z "$configflag" ]; then
1133                         echo -n "Add another user? (yes/no) [$_another_user]: "
1134                 else
1135                         echo -n "Re-edit the default configuration? (yes/no) [$_another_user]: "
1136                 fi
1137                 read _input
1138                 if [ -z "$_input" ]; then
1139                         _input=$_another_user
1140                 fi
1141                 case $_input in
1142                 [Yy][Ee][Ss]|[Yy][Ee]|[Yy])
1143                         uidstart=$(get_nextuid $uidstart)
1144                         input_interactive
1145                         continue
1146                         ;;
1147                 [Nn][Oo]|[Nn])
1148                         echo "Goodbye!"
1149                         ;;
1150                 *)
1151                         continue
1152                         ;;
1153                 esac
1154                 break
1155         done
1156 fi