xref: /netbsd-src/usr.sbin/user/user.c (revision aaf4ece63a859a04e37cf3a7229b5fab0157cc06)
1 /* $NetBSD: user.c,v 1.101 2006/01/13 16:36:33 elad Exp $ */
2 
3 /*
4  * Copyright (c) 1999 Alistair G. Crooks.  All rights reserved.
5  * Copyright (c) 2005 Liam J. Foy.  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  * 3. The name of the author may not be used to endorse or promote
16  *    products derived from this software without specific prior written
17  *    permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
20  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
23  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
25  * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
27  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31 #include <sys/cdefs.h>
32 
33 #ifndef lint
34 __COPYRIGHT("@(#) Copyright (c) 1999 \
35 	        The NetBSD Foundation, Inc.  All rights reserved.");
36 __RCSID("$NetBSD: user.c,v 1.101 2006/01/13 16:36:33 elad Exp $");
37 #endif
38 
39 #include <sys/types.h>
40 #include <sys/param.h>
41 #include <sys/stat.h>
42 
43 #include <ctype.h>
44 #include <dirent.h>
45 #include <err.h>
46 #include <fcntl.h>
47 #include <grp.h>
48 #ifdef EXTENSIONS
49 #include <login_cap.h>
50 #endif
51 #include <paths.h>
52 #include <pwd.h>
53 #include <regex.h>
54 #include <stdarg.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <syslog.h>
59 #include <time.h>
60 #include <unistd.h>
61 #include <util.h>
62 #include <errno.h>
63 
64 #include "defs.h"
65 #include "usermgmt.h"
66 
67 
68 /* this struct describes a uid range */
69 typedef struct range_t {
70 	int	r_from;		/* low uid */
71 	int	r_to;		/* high uid */
72 } range_t;
73 
74 /* this struct encapsulates the user information */
75 typedef struct user_t {
76 	int		u_flags;		/* see below */
77 	int		u_uid;			/* uid of user */
78 	char	       *u_password;		/* encrypted password */
79 	char	       *u_comment;		/* comment field */
80 	char	       *u_home;			/* home directory */
81 	char	       *u_primgrp;		/* primary group */
82 	int		u_groupc;		/* # of secondary groups */
83 	const char     *u_groupv[NGROUPS_MAX];	/* secondary groups */
84 	char	       *u_shell;		/* user's shell */
85 	char	       *u_basedir;		/* base directory for home */
86 	char	       *u_expire;		/* when password will expire */
87 	char	       *u_inactive;		/* when account will expire */
88 	char	       *u_skeldir;		/* directory for startup files */
89 	char	       *u_class;		/* login class */
90 	unsigned	u_rsize;		/* size of range array */
91 	unsigned	u_rc;			/* # of ranges */
92 	range_t	       *u_rv;			/* the ranges */
93 	unsigned	u_defrc;		/* # of ranges in defaults */
94 	int		u_preserve;		/* preserve uids on deletion */
95 	int		u_allow_samba;		/* allow trailing '$' for samba login names */
96 	int		u_locked;		/* user account lock */
97 } user_t;
98 
99 /* flags for which fields of the user_t replace the passwd entry */
100 enum {
101 	F_COMMENT	= 0x0001,
102 	F_DUPUID  	= 0x0002,
103 	F_EXPIRE	= 0x0004,
104 	F_GROUP		= 0x0008,
105 	F_HOMEDIR	= 0x0010,
106 	F_MKDIR		= 0x0020,
107 	F_INACTIVE	= 0x0040,
108 	F_PASSWORD	= 0x0080,
109 	F_SECGROUP	= 0x0100,
110 	F_SHELL 	= 0x0200,
111 	F_UID		= 0x0400,
112 	F_USERNAME	= 0x0800,
113 	F_CLASS		= 0x1000
114 };
115 
116 #define	UNLOCK		0
117 #define LOCK		1
118 #define LOCKED		"*LOCKED*"
119 
120 #define	PATH_LOGINCONF	"/etc/login.conf"
121 
122 #ifndef DEF_GROUP
123 #define DEF_GROUP	"users"
124 #endif
125 
126 #ifndef DEF_BASEDIR
127 #define DEF_BASEDIR	"/home"
128 #endif
129 
130 #ifndef DEF_SKELDIR
131 #define DEF_SKELDIR	"/etc/skel"
132 #endif
133 
134 #ifndef DEF_SHELL
135 #define DEF_SHELL	_PATH_CSHELL
136 #endif
137 
138 #ifndef DEF_COMMENT
139 #define DEF_COMMENT	""
140 #endif
141 
142 #ifndef DEF_LOWUID
143 #define DEF_LOWUID	1000
144 #endif
145 
146 #ifndef DEF_HIGHUID
147 #define DEF_HIGHUID	60000
148 #endif
149 
150 #ifndef DEF_INACTIVE
151 #define DEF_INACTIVE	0
152 #endif
153 
154 #ifndef DEF_EXPIRE
155 #define DEF_EXPIRE	NULL
156 #endif
157 
158 #ifndef DEF_CLASS
159 #define DEF_CLASS	""
160 #endif
161 
162 #ifndef WAITSECS
163 #define WAITSECS	10
164 #endif
165 
166 #ifndef NOBODY_UID
167 #define NOBODY_UID	32767
168 #endif
169 
170 /* some useful constants */
171 enum {
172 	MaxShellNameLen = 256,
173 	MaxFileNameLen = MAXPATHLEN,
174 	MaxUserNameLen = LOGIN_NAME_MAX - 1,
175 	MaxCommandLen = 2048,
176 	MaxEntryLen = 2048,
177 	PasswordLength = 2048,
178 
179 	DES_Len = 13,
180 
181 	LowGid = DEF_LOWUID,
182 	HighGid = DEF_HIGHUID
183 };
184 
185 /* Full paths of programs used here */
186 #define CHMOD		"/bin/chmod"
187 #define CHOWN		"/usr/sbin/chown"
188 #define MKDIR		"/bin/mkdir"
189 #define MV		"/bin/mv"
190 #define NOLOGIN		"/sbin/nologin"
191 #define PAX		"/bin/pax"
192 #define RM		"/bin/rm"
193 
194 #define UNSET_INACTIVE	"Null (unset)"
195 #define UNSET_EXPIRY	"Null (unset)"
196 
197 static int		asystem(const char *fmt, ...)
198 			    __attribute__((__format__(__printf__, 1, 2)));
199 static int		is_number(const char *);
200 static struct group	*find_group_info(const char *);
201 static int		verbose;
202 
203 static char *
204 skipspace(char *s)
205 {
206 	for (; *s && isspace((unsigned char)*s) ; s++) {
207 	}
208 	return s;
209 }
210 
211 static int
212 check_numeric(const char *val, const char *name)
213 {
214 	if (!is_number(val)) {
215 		errx(EXIT_FAILURE, "When using [-%c %s], "
216 		    "the %s must be numeric", *name, name, name);
217 	}
218 	return atoi(val);
219 }
220 
221 /* if *cpp is non-null, free it, then assign `n' chars of `s' to it */
222 static void
223 memsave(char **cpp, const char *s, size_t n)
224 {
225 	if (*cpp != NULL) {
226 		FREE(*cpp);
227 	}
228 	NEWARRAY(char, *cpp, n + 1, exit(1));
229 	(void)memcpy(*cpp, s, n);
230 	(*cpp)[n] = '\0';
231 }
232 
233 /* a replacement for system(3) */
234 static int
235 asystem(const char *fmt, ...)
236 {
237 	va_list	vp;
238 	char	buf[MaxCommandLen];
239 	int	ret;
240 
241 	va_start(vp, fmt);
242 	(void)vsnprintf(buf, sizeof(buf), fmt, vp);
243 	va_end(vp);
244 	if (verbose) {
245 		(void)printf("Command: %s\n", buf);
246 	}
247 	if ((ret = system(buf)) != 0) {
248 		warn("Error running `%s'", buf);
249 	}
250 	return ret;
251 }
252 
253 /* remove a users home directory, returning 1 for success (ie, no problems encountered) */
254 static int
255 removehomedir(struct passwd *pwp)
256 {
257 	struct stat st;
258 
259 	/* userid not root? */
260 	if (pwp->pw_uid == 0) {
261 		warnx("Not deleting home directory `%s'; userid is 0", pwp->pw_dir);
262 		return 0;
263 	}
264 
265 	/* directory exists (and is a directory!) */
266 	if (stat(pwp->pw_dir, &st) < 0) {
267 		warn("Cannot access home directory `%s'", pwp->pw_dir);
268 		return 0;
269 	}
270 	if (!S_ISDIR(st.st_mode)) {
271 		warnx("Home directory `%s' is not a directory", pwp->pw_dir);
272 		return 0;
273 	}
274 
275 	/* userid matches directory owner? */
276 	if (st.st_uid != pwp->pw_uid) {
277 		warnx("User `%s' doesn't own directory `%s', not removed",
278 		    pwp->pw_name, pwp->pw_dir);
279 		return 0;
280 	}
281 
282 	(void)seteuid(pwp->pw_uid);
283 	/* we add the "|| true" to keep asystem() quiet if there is a non-zero exit status. */
284 	(void)asystem("%s -rf %s > /dev/null 2>&1 || true", RM, pwp->pw_dir);
285 	(void)seteuid(0);
286 	if (rmdir(pwp->pw_dir) < 0) {
287 		warn("Unable to remove all files in `%s'", pwp->pw_dir);
288 		return 0;
289 	}
290 	return 1;
291 }
292 
293 /* return 1 if all of `s' is numeric */
294 static int
295 is_number(const char *s)
296 {
297 	for ( ; *s ; s++) {
298 		if (!isdigit((unsigned char) *s)) {
299 			return 0;
300 		}
301 	}
302 	return 1;
303 }
304 
305 /*
306  * check that the effective uid is 0 - called from funcs which will
307  * modify data and config files.
308  */
309 static void
310 checkeuid(void)
311 {
312 	if (geteuid() != 0) {
313 		errx(EXIT_FAILURE, "Program must be run as root");
314 	}
315 }
316 
317 /* copy any dot files into the user's home directory */
318 static int
319 copydotfiles(char *skeldir, int uid, int gid, char *dir)
320 {
321 	struct dirent	*dp;
322 	DIR		*dirp;
323 	int		n;
324 
325 	if ((dirp = opendir(skeldir)) == NULL) {
326 		warn("Can't open source . files dir `%s'", skeldir);
327 		return 0;
328 	}
329 	for (n = 0; (dp = readdir(dirp)) != NULL && n == 0 ; ) {
330 		if (strcmp(dp->d_name, ".") == 0 ||
331 		    strcmp(dp->d_name, "..") == 0) {
332 			continue;
333 		}
334 		n = 1;
335 	}
336 	(void)closedir(dirp);
337 	if (n == 0) {
338 		warnx("No \"dot\" initialisation files found");
339 	} else {
340 		(void)asystem("cd %s && %s -rw -pe %s . %s",
341 				skeldir, PAX, (verbose) ? "-v" : "", dir);
342 	}
343 	(void)asystem("%s -R -h %d:%d %s", CHOWN, uid, gid, dir);
344 	(void)asystem("%s -R u+w %s", CHMOD, dir);
345 	return n;
346 }
347 
348 /* create a group entry with gid `gid' */
349 static int
350 creategid(char *group, int gid, const char *name)
351 {
352 	struct stat	st;
353 	FILE		*from;
354 	FILE		*to;
355 	char		buf[MaxEntryLen];
356 	char		f[MaxFileNameLen];
357 	int		fd;
358 	int		cc;
359 
360 	if (getgrnam(group) != NULL) {
361 		warnx("Can't create group `%s': already exists", group);
362 		return 0;
363 	}
364 	if ((from = fopen(_PATH_GROUP, "r")) == NULL) {
365 		warn("Can't create group `%s': can't open `%s'", name,
366 		    _PATH_GROUP);
367 		return 0;
368 	}
369 	if (flock(fileno(from), LOCK_EX | LOCK_NB) < 0) {
370 		warn("Can't lock `%s'", _PATH_GROUP);
371 		return 0;
372 	}
373 	(void)fstat(fileno(from), &st);
374 	(void)snprintf(f, sizeof(f), "%s.XXXXXX", _PATH_GROUP);
375 	if ((fd = mkstemp(f)) < 0) {
376 		warn("Can't create group `%s': mkstemp failed", group);
377 		(void)fclose(from);
378 		return 0;
379 	}
380 	if ((to = fdopen(fd, "w")) == NULL) {
381 		warn("Can't create group `%s': fdopen `%s' failed",
382 		    group, f);
383 		(void)fclose(from);
384 		(void)close(fd);
385 		(void)unlink(f);
386 		return 0;
387 	}
388 	while ((cc = fread(buf, sizeof(char), sizeof(buf), from)) > 0) {
389 		if (fwrite(buf, sizeof(char), (unsigned) cc, to) != cc) {
390 			warn("Can't create group `%s': short write to `%s'",
391 			    group, f);
392 			(void)fclose(from);
393 			(void)close(fd);
394 			(void)unlink(f);
395 			return 0;
396 		}
397 	}
398 	(void)fprintf(to, "%s:*:%d:%s\n", group, gid, name);
399 	(void)fclose(from);
400 	(void)fclose(to);
401 	if (rename(f, _PATH_GROUP) < 0) {
402 		warn("Can't create group `%s': can't rename `%s' to `%s'",
403 		    group, f, _PATH_GROUP);
404 		(void)unlink(f);
405 		return 0;
406 	}
407 	(void)chmod(_PATH_GROUP, st.st_mode & 07777);
408 	syslog(LOG_INFO, "New group added: name=%s, gid=%d", group, gid);
409 	return 1;
410 }
411 
412 /* modify the group entry with name `group' to be newent */
413 static int
414 modify_gid(char *group, char *newent)
415 {
416 	struct stat	st;
417 	FILE		*from;
418 	FILE		*to;
419 	char		buf[MaxEntryLen];
420 	char		f[MaxFileNameLen];
421 	char		*colon;
422 	int		groupc;
423 	int		entc;
424 	int		fd;
425 	int		cc;
426 
427 	if ((from = fopen(_PATH_GROUP, "r")) == NULL) {
428 		warn("Can't modify group `%s': can't open `%s'",
429 		    group, _PATH_GROUP);
430 		return 0;
431 	}
432 	if (flock(fileno(from), LOCK_EX | LOCK_NB) < 0) {
433 		warn("Can't modify group `%s': can't lock `%s'",
434 		    group, _PATH_GROUP);
435 		return 0;
436 	}
437 	(void)fstat(fileno(from), &st);
438 	(void)snprintf(f, sizeof(f), "%s.XXXXXX", _PATH_GROUP);
439 	if ((fd = mkstemp(f)) < 0) {
440 		warn("Can't modify group `%s': mkstemp failed", group);
441 		(void)fclose(from);
442 		return 0;
443 	}
444 	if ((to = fdopen(fd, "w")) == NULL) {
445 		warn("Can't modify group `%s': fdopen `%s' failed", group, f);
446 		(void)fclose(from);
447 		(void)close(fd);
448 		(void)unlink(f);
449 		return 0;
450 	}
451 	groupc = strlen(group);
452 	while (fgets(buf, sizeof(buf), from) != NULL) {
453 		cc = strlen(buf);
454 		if ((colon = strchr(buf, ':')) == NULL) {
455 			warnx("Badly formed entry `%s'", buf);
456 			continue;
457 		}
458 		entc = (int)(colon - buf);
459 		if (entc == groupc &&
460 		    strncmp(group, buf, (unsigned) entc) == 0) {
461 			if (newent == NULL) {
462 				struct group	*grp_rm;
463 				struct passwd	*user_pwd;
464 
465 				/*
466 				 * Check that the group being removed
467 				 * isn't any user's Primary group. Just
468 				 * warn if it is. This could cause problems
469 				 * if the group GID was reused for a
470 				 * different purpose.
471 				 */
472 
473 				grp_rm = find_group_info(group);
474 				while ((user_pwd = getpwent()) != NULL) {
475 					if (user_pwd->pw_gid == grp_rm->gr_gid) {
476 						warnx("Warning: group `%s'(%d)"
477 						   " is the primary group of"
478 						   " `%s'. Use caution if you"
479 						   " later add this GID.",
480 						   grp_rm->gr_name,
481 						   grp_rm->gr_gid, user_pwd->pw_name);
482 					}
483 				}
484 				endpwent();
485 				continue;
486 			} else {
487 				cc = strlen(newent);
488 				(void)strlcpy(buf, newent, sizeof(buf));
489 			}
490 		}
491 		if (fwrite(buf, sizeof(char), (unsigned) cc, to) != cc) {
492 			warn("Can't modify group `%s': short write to `%s'",
493 			    group, f);
494 			(void)fclose(from);
495 			(void)close(fd);
496 			(void)unlink(f);
497 			return 0;
498 		}
499 	}
500 	(void)fclose(from);
501 	(void)fclose(to);
502 	if (rename(f, _PATH_GROUP) < 0) {
503 		warn("Can't modify group `%s': can't rename `%s' to `%s'",
504 		    group, f, _PATH_GROUP);
505 		(void)unlink(f);
506 		return 0;
507 	}
508 	(void)chmod(_PATH_GROUP, st.st_mode & 07777);
509 	if (newent == NULL) {
510 		syslog(LOG_INFO, "group deleted: name=%s", group);
511 	} else {
512 		syslog(LOG_INFO, "group information modified: name=%s", group);
513 	}
514 	return 1;
515 }
516 
517 /* modify the group entries for all `groups', by adding `user' */
518 static int
519 append_group(char *user, int ngroups, const char **groups)
520 {
521 	struct group	*grp;
522 	struct stat	st;
523 	FILE		*from;
524 	FILE		*to;
525 	char		buf[MaxEntryLen];
526 	char		f[MaxFileNameLen];
527 	char		*colon;
528 	int		groupc;
529 	int		entc;
530 	int		fd;
531 	int		nc;
532 	int		cc;
533 	int		i;
534 	int		j;
535 
536 	for (i = 0 ; i < ngroups ; i++) {
537 		if ((grp = getgrnam(groups[i])) == NULL) {
538 			warnx("Can't append group `%s' for user `%s'",
539 			    groups[i], user);
540 		} else {
541 			for (j = 0 ; grp->gr_mem[j] ; j++) {
542 				if (strcmp(user, grp->gr_mem[j]) == 0) {
543 					/* already in it */
544 					groups[i] = "";
545 				}
546 			}
547 		}
548 	}
549 	if ((from = fopen(_PATH_GROUP, "r")) == NULL) {
550 		warn("Can't append group(s) for `%s': can't open `%s'",
551 		    user, _PATH_GROUP);
552 		return 0;
553 	}
554 	if (flock(fileno(from), LOCK_EX | LOCK_NB) < 0) {
555 		warn("Can't append group(s) for `%s': can't lock `%s'",
556 		    user, _PATH_GROUP);
557 		return 0;
558 	}
559 	(void)fstat(fileno(from), &st);
560 	(void)snprintf(f, sizeof(f), "%s.XXXXXX", _PATH_GROUP);
561 	if ((fd = mkstemp(f)) < 0) {
562 		warn("Can't append group(s) for `%s': mkstemp failed",
563 		    user);
564 		(void)fclose(from);
565 		return 0;
566 	}
567 	if ((to = fdopen(fd, "w")) == NULL) {
568 		warn("Can't append group(s) for `%s': fdopen `%s' failed",
569 		    user, f);
570 		(void)fclose(from);
571 		(void)close(fd);
572 		(void)unlink(f);
573 		return 0;
574 	}
575 	while (fgets(buf, sizeof(buf), from) != NULL) {
576 		cc = strlen(buf);
577 		if ((colon = strchr(buf, ':')) == NULL) {
578 			warnx("Badly formed entry `%s'", buf);
579 			continue;
580 		}
581 		entc = (int)(colon - buf);
582 		for (i = 0 ; i < ngroups ; i++) {
583 			if ((groupc = strlen(groups[i])) == 0) {
584 				continue;
585 			}
586 			if (entc == groupc &&
587 			    strncmp(groups[i], buf, (unsigned) entc) == 0) {
588 				if ((nc = snprintf(&buf[cc - 1],
589 				    sizeof(buf) - cc + 1, "%s%s\n",
590 				    (buf[cc - 2] == ':') ? "" : ",", user)) < 0) {
591 					warnx("Warning: group `%s' "
592 					    "entry too long", groups[i]);
593 				}
594 				cc += nc - 1;
595 			}
596 		}
597 		if (fwrite(buf, sizeof(char), (unsigned) cc, to) != cc) {
598 			warn("Can't append group(s) for `%s':"
599 			    " short write to `%s'", user, f);
600 			(void)fclose(from);
601 			(void)close(fd);
602 			(void)unlink(f);
603 			return 0;
604 		}
605 	}
606 	(void)fclose(from);
607 	(void)fclose(to);
608 	if (rename(f, _PATH_GROUP) < 0) {
609 		warn("Can't append group(s) for `%s': "
610 		    "can't rename `%s' to `%s'", user, f, _PATH_GROUP);
611 		(void)unlink(f);
612 		return 0;
613 	}
614 	(void)chmod(_PATH_GROUP, st.st_mode & 07777);
615 	return 1;
616 }
617 
618 /* the valid characters for login and group names */
619 #define VALID_CHAR(c)	(isalnum(c) || (c) == '.' || (c) == '_' || (c) == '-')
620 
621 /* return 1 if `login' is a valid login name */
622 static int
623 valid_login(char *login_name, int allow_samba)
624 {
625 	unsigned char	*cp;
626 
627 	/* First character of a login name cannot be '-'. */
628 	if (*login_name == '-') {
629 		return 0;
630 	}
631 	if (strlen(login_name) >= LOGIN_NAME_MAX) {
632 		return 0;
633 	}
634 	for (cp = (unsigned char *)login_name ; *cp ; cp++) {
635 		if (!VALID_CHAR(*cp)) {
636 #ifdef EXTENSIONS
637 			/* check for a trailing '$' in a Samba user name */
638 			if (allow_samba && *cp == '$' && *(cp + 1) == 0x0) {
639 				return 1;
640 			}
641 #endif
642 			return 0;
643 		}
644 	}
645 	return 1;
646 }
647 
648 /* return 1 if `group' is a valid group name */
649 static int
650 valid_group(char *group)
651 {
652 	unsigned char	*cp;
653 
654 	for (cp = (unsigned char *)group; *cp; cp++) {
655 		if (!VALID_CHAR(*cp)) {
656 			return 0;
657 		}
658 	}
659 	return 1;
660 }
661 
662 /* find the next gid in the range lo .. hi */
663 static int
664 getnextgid(int *gidp, int lo, int hi)
665 {
666 	for (*gidp = lo ; *gidp < hi ; *gidp += 1) {
667 		if (getgrgid((gid_t)*gidp) == NULL) {
668 			return 1;
669 		}
670 	}
671 	return 0;
672 }
673 
674 #ifdef EXTENSIONS
675 /* save a range of uids */
676 static int
677 save_range(user_t *up, char *cp)
678 {
679 	int	from;
680 	int	to;
681 	int	i;
682 
683 	if (up->u_rsize == 0) {
684 		up->u_rsize = 32;
685 		NEWARRAY(range_t, up->u_rv, up->u_rsize, return(0));
686 	} else if (up->u_rc == up->u_rsize) {
687 		up->u_rsize *= 2;
688 		RENEW(range_t, up->u_rv, up->u_rsize, return(0));
689 	}
690 	if (up->u_rv && sscanf(cp, "%d..%d", &from, &to) == 2) {
691 		for (i = up->u_defrc ; i < up->u_rc ; i++) {
692 			if (up->u_rv[i].r_from == from &&
693 			    up->u_rv[i].r_to == to) {
694 				break;
695 			}
696 		}
697 		if (i == up->u_rc) {
698 			up->u_rv[up->u_rc].r_from = from;
699 			up->u_rv[up->u_rc].r_to = to;
700 			up->u_rc += 1;
701 		}
702 	} else {
703 		warnx("Bad range `%s'", cp);
704 		return 0;
705 	}
706 	return 1;
707 }
708 #endif
709 
710 /* set the defaults in the defaults file */
711 static int
712 setdefaults(user_t *up)
713 {
714 	char	template[MaxFileNameLen];
715 	FILE	*fp;
716 	int	ret;
717 	int	fd;
718 #ifdef EXTENSIONS
719 	int	i;
720 #endif
721 
722 	(void)snprintf(template, sizeof(template), "%s.XXXXXX",
723 	    _PATH_USERMGMT_CONF);
724 	if ((fd = mkstemp(template)) < 0) {
725 		warn("Can't set defaults: can't mkstemp `%s' for writing",
726 		    _PATH_USERMGMT_CONF);
727 		return 0;
728 	}
729 	if ((fp = fdopen(fd, "w")) == NULL) {
730 		warn("Can't set defaults: can't fdopen `%s' for writing",
731 		    _PATH_USERMGMT_CONF);
732 		return 0;
733 	}
734 	ret = 1;
735 	if (fprintf(fp, "group\t\t%s\n", up->u_primgrp) <= 0 ||
736 	    fprintf(fp, "base_dir\t%s\n", up->u_basedir) <= 0 ||
737 	    fprintf(fp, "skel_dir\t%s\n", up->u_skeldir) <= 0 ||
738 	    fprintf(fp, "shell\t\t%s\n", up->u_shell) <= 0 ||
739 #ifdef EXTENSIONS
740 	    fprintf(fp, "class\t\t%s\n", up->u_class) <= 0 ||
741 #endif
742 	    fprintf(fp, "inactive\t%s\n", (up->u_inactive == NULL) ?
743 		UNSET_INACTIVE : up->u_inactive) <= 0 ||
744 	    fprintf(fp, "expire\t\t%s\n", (up->u_expire == NULL) ?
745 		UNSET_EXPIRY : up->u_expire) <= 0 ||
746 	    fprintf(fp, "preserve\t%s\n", (up->u_preserve == 0) ?
747 		"false" : "true") <= 0) {
748 		warn("Can't write to `%s'", _PATH_USERMGMT_CONF);
749 		ret = 0;
750 	}
751 #ifdef EXTENSIONS
752 	for (i = (up->u_defrc != up->u_rc) ? up->u_defrc : 0;
753 	    i < up->u_rc ; i++) {
754 		if (fprintf(fp, "range\t\t%d..%d\n", up->u_rv[i].r_from,
755 		    up->u_rv[i].r_to) <= 0) {
756 			warn("Can't set defaults: can't write to `%s'",
757 			    _PATH_USERMGMT_CONF);
758 			ret = 0;
759 		}
760 	}
761 #endif
762 	(void)fclose(fp);
763 	if (ret) {
764 		ret = ((rename(template, _PATH_USERMGMT_CONF) == 0) &&
765 		    (chmod(_PATH_USERMGMT_CONF, 0644) == 0));
766 	}
767 	return ret;
768 }
769 
770 /* read the defaults file */
771 static void
772 read_defaults(user_t *up)
773 {
774 	struct stat	st;
775 	size_t		lineno;
776 	size_t		len;
777 	FILE		*fp;
778 	char		*cp;
779 	char		*s;
780 
781 	memsave(&up->u_primgrp, DEF_GROUP, strlen(DEF_GROUP));
782 	memsave(&up->u_basedir, DEF_BASEDIR, strlen(DEF_BASEDIR));
783 	memsave(&up->u_skeldir, DEF_SKELDIR, strlen(DEF_SKELDIR));
784 	memsave(&up->u_shell, DEF_SHELL, strlen(DEF_SHELL));
785 	memsave(&up->u_comment, DEF_COMMENT, strlen(DEF_COMMENT));
786 #ifdef EXTENSIONS
787 	memsave(&up->u_class, DEF_CLASS, strlen(DEF_CLASS));
788 #endif
789 	up->u_rsize = 16;
790 	up->u_defrc = 0;
791 	NEWARRAY(range_t, up->u_rv, up->u_rsize, exit(1));
792 	up->u_inactive = DEF_INACTIVE;
793 	up->u_expire = DEF_EXPIRE;
794 	if ((fp = fopen(_PATH_USERMGMT_CONF, "r")) == NULL) {
795 		if (stat(_PATH_USERMGMT_CONF, &st) < 0 && !setdefaults(up)) {
796 			warn("Can't create `%s' defaults file",
797 			    _PATH_USERMGMT_CONF);
798 		}
799 		fp = fopen(_PATH_USERMGMT_CONF, "r");
800 	}
801 	if (fp != NULL) {
802 		while ((s = fparseln(fp, &len, &lineno, NULL, 0)) != NULL) {
803 			if (strncmp(s, "group", 5) == 0) {
804 				cp = skipspace(s + 5);
805 				memsave(&up->u_primgrp, (char *)cp, strlen(cp));
806 			} else if (strncmp(s, "base_dir", 8) == 0) {
807 				cp = skipspace(s + 8);
808 				memsave(&up->u_basedir, (char *)cp, strlen(cp));
809 			} else if (strncmp(s, "skel_dir", 8) == 0) {
810 				cp = skipspace(s + 8);
811 				memsave(&up->u_skeldir, (char *)cp, strlen(cp));
812 			} else if (strncmp(s, "shell", 5) == 0) {
813 				cp = skipspace(s + 5);
814 				memsave(&up->u_shell, cp, strlen(cp));
815 #ifdef EXTENSIONS
816 			} else if (strncmp((char *)s, "class", 5) == 0) {
817 				cp = skipspace(s + 5);
818 				memsave(&up->u_class, cp, strlen(cp));
819 #endif
820 			} else if (strncmp(s, "inactive", 8) == 0) {
821 				cp = skipspace(s + 8);
822 				if (strcmp(cp, UNSET_INACTIVE) == 0) {
823 					if (up->u_inactive) {
824 						FREE(up->u_inactive);
825 					}
826 					up->u_inactive = NULL;
827 				} else {
828 					memsave(&up->u_inactive, cp, strlen(cp));
829 				}
830 #ifdef EXTENSIONS
831 			} else if (strncmp(s, "range", 5) == 0) {
832 				cp = skipspace(s + 5);
833 				(void)save_range(up, cp);
834 #endif
835 #ifdef EXTENSIONS
836 			} else if (strncmp(s, "preserve", 8) == 0) {
837 				cp = skipspace(s + 8);
838 				up->u_preserve =
839 				    (strncmp(cp, "true", 4) == 0) ? 1 :
840 				    (strncmp(cp, "yes", 3) == 0) ? 1 : atoi(cp);
841 #endif
842 			} else if (strncmp(s, "expire", 6) == 0) {
843 				cp = skipspace(s + 6);
844 				if (strcmp(cp, UNSET_EXPIRY) == 0) {
845 					if (up->u_expire) {
846 						FREE(up->u_expire);
847 					}
848 					up->u_expire = NULL;
849 				} else {
850 					memsave(&up->u_expire, cp, strlen(cp));
851 				}
852 			}
853 			(void)free(s);
854 		}
855 		(void)fclose(fp);
856 	}
857 	if (up->u_rc == 0) {
858 		up->u_rv[up->u_rc].r_from = DEF_LOWUID;
859 		up->u_rv[up->u_rc].r_to = DEF_HIGHUID;
860 		up->u_rc += 1;
861 	}
862 	up->u_defrc = up->u_rc;
863 }
864 
865 /* return the next valid unused uid */
866 static int
867 getnextuid(int sync_uid_gid, int *uid, int low_uid, int high_uid)
868 {
869 	for (*uid = low_uid ; *uid <= high_uid ; (*uid)++) {
870 		if (getpwuid((uid_t)(*uid)) == NULL && *uid != NOBODY_UID) {
871 			if (sync_uid_gid) {
872 				if (getgrgid((gid_t)(*uid)) == NULL) {
873 					return 1;
874 				}
875 			} else {
876 				return 1;
877 			}
878 		}
879 	}
880 	return 0;
881 }
882 
883 /* structure which defines a password type */
884 typedef struct passwd_type_t {
885 	const char     *type;		/* optional type descriptor */
886 	size_t		desc_length;	/* length of type descriptor */
887 	size_t		length;		/* length of password */
888 	const char     *regex;		/* regexp to output the password */
889 	size_t		re_sub;		/* subscript of regexp to use */
890 } passwd_type_t;
891 
892 static passwd_type_t	passwd_types[] = {
893 	{ "$sha1",	5,	28,	"\\$[^$]+\\$[^$]+\\$[^$]+\\$(.*)", 1 },	/* SHA1 */
894 	{ "$2a",	3,	54,	"\\$[^$]+\\$[^$]+\\$(.*)",	1 },	/* Blowfish */
895 	{ "$1",		2,	34,	NULL,				0 },	/* MD5 */
896 	{ "",		0,	DES_Len,NULL,				0 },	/* standard DES */
897 	{ NULL,		(size_t)~0,	(size_t)~0,	NULL,		0 }
898 	/* none - terminate search */
899 };
900 
901 /* return non-zero if it's a valid password - check length for cipher type */
902 static int
903 valid_password_length(char *newpasswd)
904 {
905 	passwd_type_t  *pwtp;
906 	regmatch_t	matchv[10];
907 	regex_t		r;
908 
909 	for (pwtp = passwd_types; pwtp->desc_length != (size_t)~0; pwtp++) {
910 		if (strncmp(newpasswd, pwtp->type, pwtp->desc_length) == 0) {
911 			if (pwtp->regex == NULL) {
912 				return strlen(newpasswd) == pwtp->length;
913 			}
914 			(void)regcomp(&r, pwtp->regex, REG_EXTENDED);
915 			if (regexec(&r, newpasswd, 10, matchv, 0) == 0) {
916 				regfree(&r);
917 				return (int)(matchv[pwtp->re_sub].rm_eo -
918 				    matchv[pwtp->re_sub].rm_so + 1) ==
919 				    pwtp->length;
920 			}
921 			regfree(&r);
922 		}
923 	}
924 	return 0;
925 }
926 
927 #ifdef EXTENSIONS
928 static int
929 valid_class(char *class)
930 {
931 	login_cap_t *lc;
932 
933 	if (class == NULL || *class == '\0') {
934 		return 1;
935 	}
936 	/*
937 	 * Check if /etc/login.conf exists. login_getclass() will
938 	 * return 1 due to it not existing, so not informing the
939 	 * user the actual login class does not exist.
940 	 */
941 
942 	if (access(PATH_LOGINCONF, R_OK) == -1) {
943 		warn("Access failed for `%s'; will not validate class `%s'",
944 		    PATH_LOGINCONF, class);
945 		return 1;
946 	}
947 
948 	if ((lc = login_getclass(class)) != NULL) {
949 		login_close(lc);
950 		return 1;
951 	}
952 	return 0;
953 }
954 
955 static int
956 valid_shell(const char *shellname)
957 {
958 	char *shellp;
959 
960 	if (access(_PATH_SHELLS, R_OK) == -1) {
961 		/* Don't exit */
962 		warn("Access failed for `%s'; will not validate shell `%s'",
963 		    _PATH_SHELLS, shellname);
964 		return 1;
965 	}
966 
967 	if (strcmp(shellname, "/sbin/nologin") == 0)
968 		return 0;
969 
970 	while ((shellp = getusershell()) != NULL)
971 		if (strcmp(shellp, shellname) == 0)
972 			return 1;
973 
974 	return 0;
975 }
976 #endif
977 
978 /* look for a valid time, return 0 if it was specified but bad */
979 static int
980 scantime(time_t *tp, char *s)
981 {
982 	struct tm	tm;
983 	char *ep;
984 	long val;
985 
986 	*tp = 0;
987 	if (s != NULL) {
988 		(void)memset(&tm, 0, sizeof(tm));
989 		if (strptime(s, "%c", &tm) != NULL) {
990 			*tp = mktime(&tm);
991 			return (*tp == -1) ? 0 : 1;
992 		} else if (strptime(s, "%B %d %Y", &tm) != NULL) {
993 			*tp = mktime(&tm);
994 			return (*tp == -1) ? 0 : 1;
995 		} else {
996 			errno = 0;
997 			*tp = val = strtol(s, &ep, 10);
998 			if (*ep != '\0' || *tp < -1 || errno == ERANGE) {
999 				*tp = 0;
1000 				return 0;
1001 			}
1002 			if (*tp != val) {
1003 				return 0;
1004 			}
1005 		}
1006 	}
1007 	return 1;
1008 }
1009 
1010 /* add a user */
1011 static int
1012 adduser(char *login_name, user_t *up)
1013 {
1014 	struct group	*grp;
1015 	struct stat	st;
1016 	time_t		expire;
1017 	time_t		inactive;
1018 	char		password[PasswordLength + 1];
1019 	char		home[MaxFileNameLen];
1020 	char		buf[MaxFileNameLen];
1021 	int		sync_uid_gid;
1022 	int		masterfd;
1023 	int		ptmpfd;
1024 	int		gid;
1025 	int		cc;
1026 	int		i;
1027 
1028 	if (!valid_login(login_name, up->u_allow_samba)) {
1029 		errx(EXIT_FAILURE, "Can't add user `%s': invalid login name", login_name);
1030 	}
1031 #ifdef EXTENSIONS
1032 	if (!valid_class(up->u_class)) {
1033 		errx(EXIT_FAILURE, "Can't add user `%s': no such login class `%s'",
1034 		    login_name, up->u_class);
1035 	}
1036 #endif
1037 	if ((masterfd = open(_PATH_MASTERPASSWD, O_RDONLY)) < 0) {
1038 		err(EXIT_FAILURE, "Can't add user `%s': can't open `%s'",
1039 		    login_name, _PATH_MASTERPASSWD);
1040 	}
1041 	if (flock(masterfd, LOCK_EX | LOCK_NB) < 0) {
1042 		err(EXIT_FAILURE, "Can't add user `%s': can't lock `%s'",
1043 		    login_name, _PATH_MASTERPASSWD);
1044 	}
1045 	pw_init();
1046 	if ((ptmpfd = pw_lock(WAITSECS)) < 0) {
1047 		int serrno = errno;
1048 		(void)close(masterfd);
1049 		errno = serrno;
1050 		err(EXIT_FAILURE, "Can't add user `%s': can't obtain pw_lock",
1051 		    login_name);
1052 	}
1053 	while ((cc = read(masterfd, buf, sizeof(buf))) > 0) {
1054 		if (write(ptmpfd, buf, (size_t)(cc)) != cc) {
1055 			int serrno = errno;
1056 			(void)close(masterfd);
1057 			(void)close(ptmpfd);
1058 			(void)pw_abort();
1059 			errno = serrno;
1060 			err(EXIT_FAILURE, "Can't add user `%s': "
1061 			    "short write to /etc/ptmp", login_name);
1062 		}
1063 	}
1064 	/* if no uid was specified, get next one in [low_uid..high_uid] range */
1065 	sync_uid_gid = (strcmp(up->u_primgrp, "=uid") == 0);
1066 	if (up->u_uid == -1) {
1067 		int	got_id = 0;
1068 
1069 		/*
1070 		 * Look for a free UID in the command line ranges (if any).
1071 		 * These start after the ranges specified in the config file.
1072 		 */
1073 		for (i = up->u_defrc; !got_id && i < up->u_rc ; i++) {
1074 			got_id = getnextuid(sync_uid_gid, &up->u_uid,
1075 					up->u_rv[i].r_from, up->u_rv[i].r_to);
1076 		}
1077 		/*
1078 		 * If there were no free UIDs in the command line ranges,
1079 		 * try the ranges from the config file (there will always
1080 		 * be at least one default).
1081 		 */
1082 		for (i = 0; !got_id && i < up->u_defrc; i++) {
1083 			got_id = getnextuid(sync_uid_gid, &up->u_uid,
1084 					up->u_rv[i].r_from, up->u_rv[i].r_to);
1085 		}
1086 		if (!got_id) {
1087 			(void)close(ptmpfd);
1088 			(void)pw_abort();
1089 			errx(EXIT_FAILURE, "Can't add user `%s': "
1090 			    "can't get next uid for %d", login_name,
1091 			    up->u_uid);
1092 		}
1093 	}
1094 	/* check uid isn't already allocated */
1095 	if (!(up->u_flags & F_DUPUID) && getpwuid((uid_t)(up->u_uid)) != NULL) {
1096 		(void)close(ptmpfd);
1097 		(void)pw_abort();
1098 		errx(EXIT_FAILURE, "Can't add user `%s': "
1099 		    "uid %d is already in use", login_name, up->u_uid);
1100 	}
1101 	/* if -g=uid was specified, check gid is unused */
1102 	if (sync_uid_gid) {
1103 		if (getgrgid((gid_t)(up->u_uid)) != NULL) {
1104 			(void)close(ptmpfd);
1105 			(void)pw_abort();
1106 			errx(EXIT_FAILURE, "Can't add user `%s': "
1107 			    "gid %d is already in use", login_name,
1108 			    up->u_uid);
1109 		}
1110 		gid = up->u_uid;
1111 	} else if ((grp = getgrnam(up->u_primgrp)) != NULL) {
1112 		gid = grp->gr_gid;
1113 	} else if (is_number(up->u_primgrp) &&
1114 		   (grp = getgrgid((gid_t)atoi(up->u_primgrp))) != NULL) {
1115 		gid = grp->gr_gid;
1116 	} else {
1117 		(void)close(ptmpfd);
1118 		(void)pw_abort();
1119 		errx(EXIT_FAILURE, "Can't add user `%s': group %s not found",
1120 		    login_name, up->u_primgrp);
1121 	}
1122 	/* check name isn't already in use */
1123 	if (!(up->u_flags & F_DUPUID) && getpwnam(login_name) != NULL) {
1124 		(void)close(ptmpfd);
1125 		(void)pw_abort();
1126 		errx(EXIT_FAILURE, "Can't add user `%s': "
1127 		    "`%s' is already a user", login_name, login_name);
1128 	}
1129 	if (up->u_flags & F_HOMEDIR) {
1130 		(void)strlcpy(home, up->u_home, sizeof(home));
1131 	} else {
1132 		/* if home directory hasn't been given, make it up */
1133 		(void)snprintf(home, sizeof(home), "%s/%s", up->u_basedir,
1134 		    login_name);
1135 	}
1136 	if (up->u_flags & F_SHELL) {
1137 #ifdef EXTENSIONS
1138 		if (!valid_shell(up->u_shell)) {
1139 			(void)close(ptmpfd);
1140 			(void)pw_abort();
1141 			errx(EXIT_FAILURE, "Can't add user `%s': "
1142 			    "shell `%s' is not valid", login_name, up->u_shell);
1143 		}
1144 #endif
1145 	}
1146 
1147 	if (!scantime(&inactive, up->u_inactive)) {
1148 		warnx("Warning: inactive time `%s' invalid, password expiry off",
1149 				up->u_inactive);
1150 	}
1151 	if (!scantime(&expire, up->u_expire) || expire == -1) {
1152 		warnx("Warning: expire time `%s' invalid, account expiry off",
1153 				up->u_expire);
1154 		expire = 0; /* Just in case. */
1155 	}
1156 	if (lstat(home, &st) < 0 && !(up->u_flags & F_MKDIR)) {
1157 		warnx("Warning: home directory `%s' doesn't exist, "
1158 		    "and -m was not specified", home);
1159 	}
1160 	password[sizeof(password) - 1] = '\0';
1161 	if (up->u_password != NULL && valid_password_length(up->u_password)) {
1162 		(void)strlcpy(password, up->u_password, sizeof(password));
1163 	} else {
1164 		(void)memset(password, '*', DES_Len);
1165 		password[DES_Len] = 0;
1166 		if (up->u_password != NULL) {
1167 			warnx("Password `%s' is invalid: setting it to `%s'",
1168 				up->u_password, password);
1169 		}
1170 	}
1171 	cc = snprintf(buf, sizeof(buf), "%s:%s:%d:%d:%s:%ld:%ld:%s:%s:%s\n",
1172 			login_name,
1173 			password,
1174 			up->u_uid,
1175 			gid,
1176 #ifdef EXTENSIONS
1177 			up->u_class,
1178 #else
1179 			"",
1180 #endif
1181 			(long) inactive,
1182 			(long) expire,
1183 			up->u_comment,
1184 			home,
1185 			up->u_shell);
1186 	if (write(ptmpfd, buf, (size_t) cc) != cc) {
1187 		int serrno = errno;
1188 		(void)close(ptmpfd);
1189 		(void)pw_abort();
1190 		errno = serrno;
1191 		err(EXIT_FAILURE, "Can't add user `%s': write failed",
1192 		    login_name);
1193 	}
1194 	if (up->u_flags & F_MKDIR) {
1195 		if (lstat(home, &st) == 0) {
1196 			(void)close(ptmpfd);
1197 			(void)pw_abort();
1198 			errx(EXIT_FAILURE,
1199 			    "Can't add user `%s': home directory `%s' "
1200 			    "already exists", login_name, home);
1201 		} else {
1202 			if (asystem("%s -p %s", MKDIR, home) != 0) {
1203 				(void)close(ptmpfd);
1204 				(void)pw_abort();
1205 				errx(EXIT_FAILURE, "Can't add user `%s': "
1206 				    "can't mkdir `%s'", login_name, home);
1207 			}
1208 			(void)copydotfiles(up->u_skeldir, up->u_uid, gid, home);
1209 		}
1210 	}
1211 	if (strcmp(up->u_primgrp, "=uid") == 0 &&
1212 	    getgrnam(login_name) == NULL &&
1213 	    !creategid(login_name, gid, login_name)) {
1214 		(void)close(ptmpfd);
1215 		(void)pw_abort();
1216 		errx(EXIT_FAILURE, "Can't add user `%s': can't create gid %d ",
1217 		    login_name, gid);
1218 	}
1219 	if (up->u_groupc > 0 &&
1220 	    !append_group(login_name, up->u_groupc, up->u_groupv)) {
1221 		(void)close(ptmpfd);
1222 		(void)pw_abort();
1223 		errx(EXIT_FAILURE, "Can't add user `%s': can't append "
1224 		    "to new groups", login_name);
1225 	}
1226 	(void)close(ptmpfd);
1227 #if PW_MKDB_ARGC == 2
1228 	if (pw_mkdb(login_name, 0) < 0)
1229 #else
1230 	if (pw_mkdb() < 0)
1231 #endif
1232 	{
1233 		(void)pw_abort();
1234 		errx(EXIT_FAILURE, "Can't add user `%s': pw_mkdb failed",
1235 		    login_name);
1236 	}
1237 	syslog(LOG_INFO, "New user added: name=%s, uid=%d, gid=%d, home=%s, "
1238 	    "shell=%s", login_name, up->u_uid, gid, home, up->u_shell);
1239 	return 1;
1240 }
1241 
1242 /* remove a user from the groups file */
1243 static int
1244 rm_user_from_groups(char *login_name)
1245 {
1246 	struct stat	st;
1247 	regmatch_t	matchv[10];
1248 	regex_t		r;
1249 	FILE		*from;
1250 	FILE		*to;
1251 	char		line[MaxEntryLen];
1252 	char		buf[MaxEntryLen];
1253 	char		f[MaxFileNameLen];
1254 	int		fd;
1255 	int		cc;
1256 	int		sc;
1257 
1258 	(void)snprintf(line, sizeof(line), "(:|,)(%s)(,|$)", login_name);
1259 	if ((sc = regcomp(&r, line, REG_EXTENDED|REG_NEWLINE)) != 0) {
1260 		(void)regerror(sc, &r, buf, sizeof(buf));
1261 		warnx("Can't compile regular expression `%s' (%s)", line,
1262 		    buf);
1263 		return 0;
1264 	}
1265 	if ((from = fopen(_PATH_GROUP, "r")) == NULL) {
1266 		warn("Can't remove user `%s' from `%s': can't open `%s'",
1267 		    login_name, _PATH_GROUP, _PATH_GROUP);
1268 		return 0;
1269 	}
1270 	if (flock(fileno(from), LOCK_EX | LOCK_NB) < 0) {
1271 		warn("Can't remove user `%s' from `%s': can't lock `%s'",
1272 		    login_name, _PATH_GROUP, _PATH_GROUP);
1273 		return 0;
1274 	}
1275 	(void)fstat(fileno(from), &st);
1276 	(void)snprintf(f, sizeof(f), "%s.XXXXXX", _PATH_GROUP);
1277 	if ((fd = mkstemp(f)) < 0) {
1278 		warn("Can't remove user `%s' from `%s': mkstemp failed",
1279 		    login_name, _PATH_GROUP);
1280 		(void)fclose(from);
1281 		return 0;
1282 	}
1283 	if ((to = fdopen(fd, "w")) == NULL) {
1284 		warn("Can't remove user `%s' from `%s': fdopen `%s' failed",
1285 		    login_name, _PATH_GROUP, f);
1286 		(void)fclose(from);
1287 		(void)close(fd);
1288 		(void)unlink(f);
1289 		return 0;
1290 	}
1291 	while (fgets(buf, sizeof(buf), from) != NULL) {
1292 		cc = strlen(buf);
1293 		if (regexec(&r, buf, 10, matchv, 0) == 0) {
1294 			if (buf[(int)matchv[1].rm_so] == ',') {
1295 				matchv[2].rm_so = matchv[1].rm_so;
1296 			} else if (matchv[2].rm_eo != matchv[3].rm_eo) {
1297 				matchv[2].rm_eo = matchv[3].rm_eo;
1298 			}
1299 			cc -= (int) matchv[2].rm_eo;
1300 			sc = (int) matchv[2].rm_so;
1301 			if (fwrite(buf, sizeof(char), (size_t)sc, to) != sc ||
1302 			    fwrite(&buf[(int)matchv[2].rm_eo], sizeof(char),
1303 				(size_t)cc, to) != cc) {
1304 				warn("Can't remove user `%s' from `%s': "
1305 				    "short write to `%s'", login_name,
1306 				    _PATH_GROUP, f);
1307 				(void)fclose(from);
1308 				(void)close(fd);
1309 				(void)unlink(f);
1310 				return 0;
1311 			}
1312 		} else if (fwrite(buf, sizeof(char), (unsigned) cc, to) != cc) {
1313 			warn("Can't remove user `%s' from `%s': "
1314 			    "short write to `%s'", login_name, _PATH_GROUP, f);
1315 			(void)fclose(from);
1316 			(void)close(fd);
1317 			(void)unlink(f);
1318 			return 0;
1319 		}
1320 	}
1321 	(void)fclose(from);
1322 	(void)fclose(to);
1323 	if (rename(f, _PATH_GROUP) < 0) {
1324 		warn("Can't remove user `%s' from `%s': "
1325 		    "can't rename `%s' to `%s'",
1326 		    login_name, _PATH_GROUP, f, _PATH_GROUP);
1327 		(void)unlink(f);
1328 		return 0;
1329 	}
1330 	(void)chmod(_PATH_GROUP, st.st_mode & 07777);
1331 	return 1;
1332 }
1333 
1334 /* check that the user or group is local, not from YP/NIS */
1335 static int
1336 is_local(char *name, const char *file)
1337 {
1338 	FILE	       *fp;
1339 	char		buf[MaxEntryLen];
1340 	size_t		len;
1341 	int		ret;
1342 
1343 	if ((fp = fopen(file, "r")) == NULL) {
1344 		err(EXIT_FAILURE, "Can't open `%s'", file);
1345 	}
1346 	len = strlen(name);
1347 	for (ret = 0 ; fgets(buf, sizeof(buf), fp) != NULL ; ) {
1348 		if (strncmp(buf, name, len) == 0 && buf[len] == ':') {
1349 			ret = 1;
1350 			break;
1351 		}
1352 	}
1353 	(void)fclose(fp);
1354 	return ret;
1355 }
1356 
1357 /* modify a user */
1358 static int
1359 moduser(char *login_name, char *newlogin, user_t *up, int allow_samba)
1360 {
1361 	struct passwd  *pwp;
1362 	struct group   *grp;
1363 	const char     *homedir;
1364 	char	       *locked_pwd;
1365 	size_t		colonc;
1366 	size_t		loginc;
1367 	size_t		len;
1368 	size_t		cc;
1369 	FILE	       *master;
1370 	char		newdir[MaxFileNameLen];
1371 	char	        buf[MaxEntryLen];
1372 	char	       *colon;
1373 	int		masterfd;
1374 	int		ptmpfd;
1375 	int		error;
1376 
1377 	if (!valid_login(newlogin, allow_samba)) {
1378 		errx(EXIT_FAILURE, "Can't modify user `%s': invalid login name",
1379 		    login_name);
1380 	}
1381 	if ((pwp = getpwnam(login_name)) == NULL) {
1382 		errx(EXIT_FAILURE, "Can't modify user `%s': no such user",
1383 		    login_name);
1384 	}
1385 	if (!is_local(login_name, _PATH_MASTERPASSWD)) {
1386 		errx(EXIT_FAILURE, "Can't modify user `%s': must be a local user",
1387 		    login_name);
1388 	}
1389 	/* keep dir name in case we need it for '-m' */
1390 	homedir = pwp->pw_dir;
1391 
1392 	if ((masterfd = open(_PATH_MASTERPASSWD, O_RDONLY)) < 0) {
1393 		err(EXIT_FAILURE, "Can't modify user `%s': can't open `%s'",
1394 		    login_name, _PATH_MASTERPASSWD);
1395 	}
1396 	if (flock(masterfd, LOCK_EX | LOCK_NB) < 0) {
1397 		err(EXIT_FAILURE, "Can't modify user `%s': can't lock `%s'",
1398 		    login_name, _PATH_MASTERPASSWD);
1399 	}
1400 	pw_init();
1401 	if ((ptmpfd = pw_lock(WAITSECS)) < 0) {
1402 		int serrno = errno;
1403 		(void)close(masterfd);
1404 		errno = serrno;
1405 		err(EXIT_FAILURE, "Can't modify user `%s': "
1406 		    "can't obtain pw_lock", login_name);
1407 	}
1408 	if ((master = fdopen(masterfd, "r")) == NULL) {
1409 		int serrno = errno;
1410 		(void)close(masterfd);
1411 		(void)close(ptmpfd);
1412 		(void)pw_abort();
1413 		errno = serrno;
1414 		err(EXIT_FAILURE, "Can't modify user `%s': "
1415 		    "fdopen fd for %s", login_name, _PATH_MASTERPASSWD);
1416 	}
1417 	if (up != NULL) {
1418 		if (up->u_flags & F_USERNAME) {
1419 			/*
1420 			 * If changing name,
1421 			 * check new name isn't already in use
1422 			 */
1423 			if (strcmp(login_name, newlogin) != 0 &&
1424 			    getpwnam(newlogin) != NULL) {
1425 				(void)close(ptmpfd);
1426 				(void)pw_abort();
1427 				errx(EXIT_FAILURE, "Can't modify user `%s': "
1428 				    "`%s' is already a user", login_name,
1429 				    newlogin);
1430 			}
1431 			pwp->pw_name = newlogin;
1432 
1433 			/*
1434 			 * Provide a new directory name in case the
1435 			 * home directory is to be moved.
1436 			 */
1437 			if (up->u_flags & F_MKDIR) {
1438 				(void)snprintf(newdir, sizeof(newdir), "%s/%s",
1439 				    up->u_basedir, newlogin);
1440 				pwp->pw_dir = newdir;
1441 			}
1442 		}
1443 		if (up->u_flags & F_PASSWORD) {
1444 			if (up->u_password != NULL) {
1445 				if (!valid_password_length(up->u_password)) {
1446 					(void)close(ptmpfd);
1447 					(void)pw_abort();
1448 					errx(EXIT_FAILURE,
1449 					    "Can't modify user `%s': "
1450 					    "invalid password: `%s'",
1451 					    login_name, up->u_password);
1452 				}
1453 				if ((locked_pwd =
1454 				    strstr(pwp->pw_passwd, LOCKED)) != NULL) {
1455 					/*
1456 					 * account is locked - keep it locked
1457 					 * and just change the password.
1458 					 */
1459 					if (asprintf(&locked_pwd, "%s%s",
1460 					    LOCKED, up->u_password) == -1) {
1461 						(void)close(ptmpfd);
1462 						(void)pw_abort();
1463 						err(EXIT_FAILURE,
1464 						    "Can't modify user `%s': "
1465 						    "asprintf failed",
1466 						    login_name);
1467 					}
1468 					pwp->pw_passwd = locked_pwd;
1469 				} else {
1470 					pwp->pw_passwd = up->u_password;
1471 				}
1472 			}
1473 		}
1474 
1475 		/* check whether we should lock the account. */
1476 		if (up->u_locked == LOCK) {
1477 			/* check to see account if already locked. */
1478 			if ((locked_pwd = strstr(pwp->pw_passwd, LOCKED))
1479 			    != NULL) {
1480 				warnx("Account is already locked");
1481 			} else {
1482 				if (asprintf(&locked_pwd, "%s%s", LOCKED,
1483 				    pwp->pw_passwd) == -1) {
1484 					(void)close(ptmpfd);
1485 					(void)pw_abort();
1486 					err(EXIT_FAILURE,
1487 					    "Can't modify user `%s': "
1488 					    "asprintf failed", login_name);
1489 				}
1490 				pwp->pw_passwd = locked_pwd;
1491 			}
1492 		} else if (up->u_locked == UNLOCK) {
1493 			if ((locked_pwd = strstr(pwp->pw_passwd, LOCKED))
1494 			    == NULL) {
1495 				warnx("Can't modify user `%s': "
1496 				    "account is not locked", login_name);
1497 			} else {
1498 				pwp->pw_passwd = locked_pwd + strlen(LOCKED);
1499 			}
1500 		}
1501 
1502 		if (up->u_flags & F_UID) {
1503 			/* check uid isn't already allocated */
1504 			if (!(up->u_flags & F_DUPUID) &&
1505 			    getpwuid((uid_t)(up->u_uid)) != NULL) {
1506 				(void)close(ptmpfd);
1507 				(void)pw_abort();
1508 				errx(EXIT_FAILURE, "Can't modify user `%s': "
1509 				    "uid `%d' is already in use", login_name,
1510 				    up->u_uid);
1511 			}
1512 			pwp->pw_uid = up->u_uid;
1513 		}
1514 		if (up->u_flags & F_GROUP) {
1515 			/* if -g=uid was specified, check gid is unused */
1516 			if (strcmp(up->u_primgrp, "=uid") == 0) {
1517 				if (getgrgid((gid_t)(up->u_uid)) != NULL) {
1518 					(void)close(ptmpfd);
1519 					(void)pw_abort();
1520 					errx(EXIT_FAILURE,
1521 					    "Can't modify user `%s': "
1522 					    "gid %d is already in use",
1523 					    login_name, up->u_uid);
1524 				}
1525 				pwp->pw_gid = up->u_uid;
1526 			} else if ((grp = getgrnam(up->u_primgrp)) != NULL) {
1527 				pwp->pw_gid = grp->gr_gid;
1528 			} else if (is_number(up->u_primgrp) &&
1529 				   (grp = getgrgid(
1530 				   (gid_t)atoi(up->u_primgrp))) != NULL) {
1531 				pwp->pw_gid = grp->gr_gid;
1532 			} else {
1533 				(void)close(ptmpfd);
1534 				(void)pw_abort();
1535 				errx(EXIT_FAILURE, "Can't modify user `%s': "
1536 				    "group %s not found", login_name,
1537 				    up->u_primgrp);
1538 			}
1539 		}
1540 		if (up->u_flags & F_INACTIVE) {
1541 			if (!scantime(&pwp->pw_change, up->u_inactive)) {
1542 				warnx("Warning: inactive time `%s' invalid, "
1543 				    "password expiry off",
1544 					up->u_inactive);
1545 			}
1546 		}
1547 		if (up->u_flags & F_EXPIRE) {
1548 			if (!scantime(&pwp->pw_expire, up->u_expire) ||
1549 			      pwp->pw_expire == -1) {
1550 				warnx("Warning: expire time `%s' invalid, "
1551 				    "account expiry off",
1552 					up->u_expire);
1553 				pwp->pw_expire = 0;
1554 			}
1555 		}
1556 		if (up->u_flags & F_COMMENT) {
1557 			pwp->pw_gecos = up->u_comment;
1558 		}
1559 		if (up->u_flags & F_HOMEDIR) {
1560 			pwp->pw_dir = up->u_home;
1561 		}
1562 		if (up->u_flags & F_SHELL) {
1563 #ifdef EXTENSIONS
1564 		if (!valid_shell(up->u_shell)) {
1565 			(void)close(ptmpfd);
1566 			(void)pw_abort();
1567 			errx(EXIT_FAILURE, "Can't modify user `%s': "
1568 			    "shell `%s' is not valid", login_name, up->u_shell);
1569 		}
1570 		pwp->pw_shell = up->u_shell;
1571 #else
1572 		pwp->pw_shell = up->u_shell;
1573 #endif
1574 		}
1575 #ifdef EXTENSIONS
1576 		if (up->u_flags & F_CLASS) {
1577 			if (!valid_class(up->u_class)) {
1578 				(void)close(ptmpfd);
1579 				(void)pw_abort();
1580 				errx(EXIT_FAILURE, "Can't modify user `%s': "
1581 				    "no such login class `%s'", login_name,
1582 				    up->u_class);
1583 			}
1584 			pwp->pw_class = up->u_class;
1585 		}
1586 #endif
1587 	}
1588 	loginc = strlen(login_name);
1589 	while (fgets(buf, sizeof(buf), master) != NULL) {
1590 		if ((colon = strchr(buf, ':')) == NULL) {
1591 			warnx("Malformed entry `%s'. Skipping", buf);
1592 			continue;
1593 		}
1594 		colonc = (size_t)(colon - buf);
1595 		if (strncmp(login_name, buf, loginc) == 0 && loginc == colonc) {
1596 			if (up != NULL) {
1597 				len = snprintf(buf, sizeof(buf), "%s:%s:%d:%d:"
1598 #ifdef EXTENSIONS
1599 				    "%s"
1600 #endif
1601 				    ":%ld:%ld:%s:%s:%s\n",
1602 				    newlogin,
1603 				    pwp->pw_passwd,
1604 				    pwp->pw_uid,
1605 				    pwp->pw_gid,
1606 #ifdef EXTENSIONS
1607 				    pwp->pw_class,
1608 #endif
1609 				    (long)pwp->pw_change,
1610 				    (long)pwp->pw_expire,
1611 				    pwp->pw_gecos,
1612 				    pwp->pw_dir,
1613 				    pwp->pw_shell);
1614 				if (write(ptmpfd, buf, len) != len) {
1615 					int serrno = errno;
1616 					(void)close(ptmpfd);
1617 					(void)pw_abort();
1618 					errno = serrno;
1619 					err(EXIT_FAILURE, "Can't modify user "
1620 					    "`%s': write", login_name);
1621 				}
1622 			}
1623 		} else {
1624 			len = strlen(buf);
1625 			if ((cc = write(ptmpfd, buf, len)) != len) {
1626 				int serrno = errno;
1627 				(void)close(masterfd);
1628 				(void)close(ptmpfd);
1629 				(void)pw_abort();
1630 				errno = serrno;
1631 				err(EXIT_FAILURE, "Can't modify `%s': "
1632 				    "write", login_name);
1633 			}
1634 		}
1635 	}
1636 	if (up != NULL) {
1637 		if ((up->u_flags & F_MKDIR) &&
1638 		    asystem("%s %s %s", MV, homedir, pwp->pw_dir) != 0) {
1639 			(void)close(ptmpfd);
1640 			(void)pw_abort();
1641 			errx(EXIT_FAILURE, "Can't modify user `%s': "
1642 			    "can't move `%s' to `%s'",
1643 			    login_name, homedir, pwp->pw_dir);
1644 		}
1645 		if (up->u_groupc > 0 &&
1646 		    !append_group(newlogin, up->u_groupc, up->u_groupv)) {
1647 			(void)close(ptmpfd);
1648 			(void)pw_abort();
1649 			errx(EXIT_FAILURE, "Can't modify user `%s': "
1650 			    "can't append `%s' to new groups",
1651 			    login_name, newlogin);
1652 		}
1653 	}
1654 	(void)close(ptmpfd);
1655 #if PW_MKDB_ARGC == 2
1656 	if (up != NULL && strcmp(login_name, newlogin) == 0) {
1657 		error = pw_mkdb(login_name, 0);
1658 	} else {
1659 		error = pw_mkdb(NULL, 0);
1660 	}
1661 #else
1662 	error = pw_mkdb();
1663 #endif
1664 	if (error < 0) {
1665 		(void)pw_abort();
1666 		errx(EXIT_FAILURE, "Can't modify user `%s': pw_mkdb failed",
1667 		    login_name);
1668 	}
1669 	if (up == NULL) {
1670 		syslog(LOG_INFO, "User removed: name=%s", login_name);
1671 	} else if (strcmp(login_name, newlogin) == 0) {
1672 		syslog(LOG_INFO, "User information modified: name=%s, uid=%d, "
1673 		    "gid=%d, home=%s, shell=%s",
1674 		    login_name, pwp->pw_uid, pwp->pw_gid, pwp->pw_dir,
1675 		    pwp->pw_shell);
1676 	} else {
1677 		syslog(LOG_INFO, "User information modified: name=%s, "
1678 		    "new name=%s, uid=%d, gid=%d, home=%s, shell=%s",
1679 		    login_name, newlogin, pwp->pw_uid, pwp->pw_gid,
1680 		    pwp->pw_dir, pwp->pw_shell);
1681 	}
1682 	return 1;
1683 }
1684 
1685 #ifdef EXTENSIONS
1686 /* see if we can find out the user struct */
1687 static struct passwd *
1688 find_user_info(const char *name)
1689 {
1690 	struct passwd	*pwp;
1691 
1692 	if ((pwp = getpwnam(name)) != NULL) {
1693 		return pwp;
1694 	}
1695 	if (is_number(name) && (pwp = getpwuid((uid_t)atoi(name))) != NULL) {
1696 		return pwp;
1697 	}
1698 	return NULL;
1699 }
1700 #endif
1701 
1702 /* see if we can find out the group struct */
1703 static struct group *
1704 find_group_info(const char *name)
1705 {
1706 	struct group	*grp;
1707 
1708 	if ((grp = getgrnam(name)) != NULL) {
1709 		return grp;
1710 	}
1711 	if (is_number(name) && (grp = getgrgid((gid_t)atoi(name))) != NULL) {
1712 		return grp;
1713 	}
1714 	return NULL;
1715 }
1716 
1717 /* print out usage message, and then exit */
1718 void
1719 usermgmt_usage(const char *prog)
1720 {
1721 	if (strcmp(prog, "useradd") == 0) {
1722 		(void)fprintf(stderr, "usage: %s -D [-F] [-b base-dir] "
1723 		    "[-e expiry-time] [-f inactive-time]\n"
1724 		    "\t[-g gid | name | =uid] [-k skel-dir] [-L login-class]\n"
1725 		    "\t[-r lowuid..highuid] [-s shell]\n", prog);
1726 		(void)fprintf(stderr, "usage: %s [-moSv] [-b base-dir] "
1727 		    "[-c comment] [-d home-dir] [-e expiry-time]\n"
1728 		    "\t[-f inactive-time] [-G secondary-group] "
1729 		    "[-g gid | name | =uid]\n"
1730 		    "\t[-k skeletondir] [-L login-class] [-p password]"
1731 		    "[-r lowuid..highuid]\n"
1732 		    "\t[-s shell] [-u uid] user\n",
1733 		    prog);
1734 	} else if (strcmp(prog, "usermod") == 0) {
1735 		(void)fprintf(stderr, "usage: %s [-FmoSv] [-C yes/no] "
1736 		    "[-c comment] [-d home-dir] [-e expiry-time]\n"
1737 		    "\t[-f inactive] [-G secondary-group] "
1738 		    "[-g gid | name | =uid]\n"
1739 		    "\t[-L login-class] [-l new-login] [-p password] "
1740 		    "[-s shell] [-u uid]\n"
1741 		    "\tuser\n", prog);
1742 	} else if (strcmp(prog, "userdel") == 0) {
1743 		(void)fprintf(stderr, "usage: %s -D [-p preserve-value]\n", prog);
1744 		(void)fprintf(stderr,
1745 		    "usage: %s [-rSv] [-p preserve-value] user\n", prog);
1746 #ifdef EXTENSIONS
1747 	} else if (strcmp(prog, "userinfo") == 0) {
1748 		(void)fprintf(stderr, "usage: %s [-ev] user\n", prog);
1749 #endif
1750 	} else if (strcmp(prog, "groupadd") == 0) {
1751 		(void)fprintf(stderr, "usage: %s [-ov] [-g gid]"
1752 		    " [-r lowgid..highgid] group\n", prog);
1753 	} else if (strcmp(prog, "groupdel") == 0) {
1754 		(void)fprintf(stderr, "usage: %s [-v] group\n", prog);
1755 	} else if (strcmp(prog, "groupmod") == 0) {
1756 		(void)fprintf(stderr,
1757 		    "usage: %s [-ov] [-g gid] [-n newname] group\n", prog);
1758 	} else if (strcmp(prog, "user") == 0 || strcmp(prog, "group") == 0) {
1759 		(void)fprintf(stderr,
1760 		    "usage: %s ( add | del | mod | info ) ...\n", prog);
1761 #ifdef EXTENSIONS
1762 	} else if (strcmp(prog, "groupinfo") == 0) {
1763 		(void)fprintf(stderr, "usage: %s [-ev] group\n", prog);
1764 #endif
1765 	}
1766 	exit(EXIT_FAILURE);
1767 	/* NOTREACHED */
1768 }
1769 
1770 #ifdef EXTENSIONS
1771 #define ADD_OPT_EXTENSIONS	"p:r:vL:S"
1772 #else
1773 #define ADD_OPT_EXTENSIONS
1774 #endif
1775 
1776 int
1777 useradd(int argc, char **argv)
1778 {
1779 	user_t	u;
1780 	int	defaultfield;
1781 	int	bigD;
1782 	int	c;
1783 #ifdef EXTENSIONS
1784 	int	i;
1785 #endif
1786 
1787 	(void)memset(&u, 0, sizeof(u));
1788 	read_defaults(&u);
1789 	u.u_uid = -1;
1790 	defaultfield = bigD = 0;
1791 	while ((c = getopt(argc, argv, "DFG:b:c:d:e:f:g:k:mou:s:"
1792 	    ADD_OPT_EXTENSIONS)) != -1) {
1793 		switch(c) {
1794 		case 'D':
1795 			bigD = 1;
1796 			break;
1797 		case 'F':
1798 			/*
1799 			 * Setting -1 will force the new user to
1800 			 * change their password as soon as they
1801 			 * next log in - passwd(5).
1802 			 */
1803 			defaultfield = 1;
1804 			memsave(&u.u_inactive, "-1", strlen("-1"));
1805 			break;
1806 		case 'G':
1807 			while ((u.u_groupv[u.u_groupc] = strsep(&optarg, ",")) != NULL &&
1808 			       u.u_groupc < NGROUPS_MAX) {
1809 				if (u.u_groupv[u.u_groupc][0] != 0) {
1810 					u.u_groupc++;
1811 				}
1812 			}
1813 			if (optarg != NULL) {
1814 				warnx("Truncated list of secondary groups "
1815 				    "to %d entries", NGROUPS_MAX);
1816 			}
1817 			break;
1818 #ifdef EXTENSIONS
1819 		case 'S':
1820 			u.u_allow_samba = 1;
1821 			break;
1822 #endif
1823 		case 'b':
1824 			defaultfield = 1;
1825 			memsave(&u.u_basedir, optarg, strlen(optarg));
1826 			break;
1827 		case 'c':
1828 			memsave(&u.u_comment, optarg, strlen(optarg));
1829 			break;
1830 		case 'd':
1831 			memsave(&u.u_home, optarg, strlen(optarg));
1832 			u.u_flags |= F_HOMEDIR;
1833 			break;
1834 		case 'e':
1835 			defaultfield = 1;
1836 			memsave(&u.u_expire, optarg, strlen(optarg));
1837 			break;
1838 		case 'f':
1839 			defaultfield = 1;
1840 			memsave(&u.u_inactive, optarg, strlen(optarg));
1841 			break;
1842 		case 'g':
1843 			defaultfield = 1;
1844 			memsave(&u.u_primgrp, optarg, strlen(optarg));
1845 			break;
1846 		case 'k':
1847 			defaultfield = 1;
1848 			memsave(&u.u_skeldir, optarg, strlen(optarg));
1849 			break;
1850 #ifdef EXTENSIONS
1851 		case 'L':
1852 			defaultfield = 1;
1853 			memsave(&u.u_class, optarg, strlen(optarg));
1854 			break;
1855 #endif
1856 		case 'm':
1857 			u.u_flags |= F_MKDIR;
1858 			break;
1859 		case 'o':
1860 			u.u_flags |= F_DUPUID;
1861 			break;
1862 #ifdef EXTENSIONS
1863 		case 'p':
1864 			memsave(&u.u_password, optarg, strlen(optarg));
1865 			break;
1866 #endif
1867 #ifdef EXTENSIONS
1868 		case 'r':
1869 			defaultfield = 1;
1870 			(void)save_range(&u, optarg);
1871 			break;
1872 #endif
1873 		case 's':
1874 			u.u_flags |= F_SHELL;
1875 			defaultfield = 1;
1876 			memsave(&u.u_shell, optarg, strlen(optarg));
1877 			break;
1878 		case 'u':
1879 			u.u_uid = check_numeric(optarg, "uid");
1880 			break;
1881 #ifdef EXTENSIONS
1882 		case 'v':
1883 			verbose = 1;
1884 			break;
1885 #endif
1886 		default:
1887 			usermgmt_usage("useradd");
1888 			/* NOTREACHED */
1889 		}
1890 	}
1891 	if (bigD) {
1892 		if (defaultfield) {
1893 			checkeuid();
1894 			return setdefaults(&u) ? EXIT_SUCCESS : EXIT_FAILURE;
1895 		}
1896 		(void)printf("group\t\t%s\n", u.u_primgrp);
1897 		(void)printf("base_dir\t%s\n", u.u_basedir);
1898 		(void)printf("skel_dir\t%s\n", u.u_skeldir);
1899 		(void)printf("shell\t\t%s\n", u.u_shell);
1900 #ifdef EXTENSIONS
1901 		(void)printf("class\t\t%s\n", u.u_class);
1902 #endif
1903 		(void)printf("inactive\t%s\n", (u.u_inactive == NULL) ?
1904 		    UNSET_INACTIVE : u.u_inactive);
1905 		(void)printf("expire\t\t%s\n", (u.u_expire == NULL) ?
1906 		    UNSET_EXPIRY : u.u_expire);
1907 #ifdef EXTENSIONS
1908 		for (i = 0 ; i < u.u_rc ; i++) {
1909 			(void)printf("range\t\t%d..%d\n",
1910 			    u.u_rv[i].r_from, u.u_rv[i].r_to);
1911 		}
1912 #endif
1913 		return EXIT_SUCCESS;
1914 	}
1915 	argc -= optind;
1916 	argv += optind;
1917 	if (argc != 1) {
1918 		usermgmt_usage("useradd");
1919 	}
1920 	checkeuid();
1921 	openlog("useradd", LOG_PID, LOG_USER);
1922 	return adduser(*argv, &u) ? EXIT_SUCCESS : EXIT_FAILURE;
1923 }
1924 
1925 #ifdef EXTENSIONS
1926 #define MOD_OPT_EXTENSIONS	"p:vL:S"
1927 #else
1928 #define MOD_OPT_EXTENSIONS
1929 #endif
1930 
1931 int
1932 usermod(int argc, char **argv)
1933 {
1934 	user_t	u;
1935 	char	newuser[MaxUserNameLen + 1];
1936 	int	c, have_new_user;
1937 
1938 	(void)memset(&u, 0, sizeof(u));
1939 	(void)memset(newuser, 0, sizeof(newuser));
1940 	read_defaults(&u);
1941 	have_new_user = 0;
1942 	u.u_locked = -1;
1943 	while ((c = getopt(argc, argv, "C:FG:c:d:e:f:g:l:mos:u:"
1944 	    MOD_OPT_EXTENSIONS)) != -1) {
1945 		switch(c) {
1946 		case 'G':
1947 			while ((u.u_groupv[u.u_groupc] =
1948 			    strsep(&optarg, ",")) != NULL &&
1949 			    u.u_groupc < NGROUPS_MAX) {
1950 				if (u.u_groupv[u.u_groupc][0] != 0) {
1951 					u.u_groupc++;
1952 				}
1953 			}
1954 			if (optarg != NULL) {
1955 				warnx("Truncated list of secondary groups "
1956 				    "to %d entries", NGROUPS_MAX);
1957 			}
1958 			u.u_flags |= F_SECGROUP;
1959 			break;
1960 #ifdef EXTENSIONS
1961 		case 'S':
1962 			u.u_allow_samba = 1;
1963 			break;
1964 #endif
1965 		case 'c':
1966 			memsave(&u.u_comment, optarg, strlen(optarg));
1967 			u.u_flags |= F_COMMENT;
1968 			break;
1969 		case 'C':
1970 			if (strcasecmp(optarg, "yes") == 0) {
1971 				u.u_locked = LOCK;
1972 			} else if (strcasecmp(optarg, "no") == 0) {
1973 				u.u_locked = UNLOCK;
1974 			} else {
1975 				/* No idea. */
1976 				errx(EXIT_FAILURE,
1977 					"Please type 'yes' or 'no'");
1978 			}
1979 			break;
1980 		case 'F':
1981 			memsave(&u.u_inactive, "-1", strlen("-1"));
1982 			u.u_flags |= F_INACTIVE;
1983 			break;
1984 		case 'd':
1985 			memsave(&u.u_home, optarg, strlen(optarg));
1986 			u.u_flags |= F_HOMEDIR;
1987 			break;
1988 		case 'e':
1989 			memsave(&u.u_expire, optarg, strlen(optarg));
1990 			u.u_flags |= F_EXPIRE;
1991 			break;
1992 		case 'f':
1993 			memsave(&u.u_inactive, optarg, strlen(optarg));
1994 			u.u_flags |= F_INACTIVE;
1995 			break;
1996 		case 'g':
1997 			memsave(&u.u_primgrp, optarg, strlen(optarg));
1998 			u.u_flags |= F_GROUP;
1999 			break;
2000 		case 'l':
2001 			(void)strlcpy(newuser, optarg, sizeof(newuser));
2002 			have_new_user = 1;
2003 			u.u_flags |= F_USERNAME;
2004 			break;
2005 #ifdef EXTENSIONS
2006 		case 'L':
2007 			memsave(&u.u_class, optarg, strlen(optarg));
2008 			u.u_flags |= F_CLASS;
2009 			break;
2010 #endif
2011 		case 'm':
2012 			u.u_flags |= F_MKDIR;
2013 			break;
2014 		case 'o':
2015 			u.u_flags |= F_DUPUID;
2016 			break;
2017 #ifdef EXTENSIONS
2018 		case 'p':
2019 			memsave(&u.u_password, optarg, strlen(optarg));
2020 			u.u_flags |= F_PASSWORD;
2021 			break;
2022 #endif
2023 		case 's':
2024 			memsave(&u.u_shell, optarg, strlen(optarg));
2025 			u.u_flags |= F_SHELL;
2026 			break;
2027 		case 'u':
2028 			u.u_uid = check_numeric(optarg, "uid");
2029 			u.u_flags |= F_UID;
2030 			break;
2031 #ifdef EXTENSIONS
2032 		case 'v':
2033 			verbose = 1;
2034 			break;
2035 #endif
2036 		default:
2037 			usermgmt_usage("usermod");
2038 			/* NOTREACHED */
2039 		}
2040 	}
2041 	if ((u.u_flags & F_MKDIR) && !(u.u_flags & F_HOMEDIR) &&
2042 	    !(u.u_flags & F_USERNAME)) {
2043 		warnx("Option 'm' useless without 'd' or 'l' -- ignored");
2044 		u.u_flags &= ~F_MKDIR;
2045 	}
2046 	argc -= optind;
2047 	argv += optind;
2048 	if (argc != 1) {
2049 		usermgmt_usage("usermod");
2050 	}
2051 	checkeuid();
2052 	openlog("usermod", LOG_PID, LOG_USER);
2053 	return moduser(*argv, (have_new_user) ? newuser : *argv, &u,
2054 	    u.u_allow_samba) ? EXIT_SUCCESS : EXIT_FAILURE;
2055 }
2056 
2057 #ifdef EXTENSIONS
2058 #define DEL_OPT_EXTENSIONS	"Dp:vS"
2059 #else
2060 #define DEL_OPT_EXTENSIONS
2061 #endif
2062 
2063 int
2064 userdel(int argc, char **argv)
2065 {
2066 	struct passwd	*pwp;
2067 	user_t		u;
2068 	char		password[PasswordLength + 1];
2069 	int		defaultfield;
2070 	int		rmhome;
2071 	int		bigD;
2072 	int		c;
2073 
2074 	(void)memset(&u, 0, sizeof(u));
2075 	read_defaults(&u);
2076 	defaultfield = bigD = rmhome = 0;
2077 	while ((c = getopt(argc, argv, "r" DEL_OPT_EXTENSIONS)) != -1) {
2078 		switch(c) {
2079 #ifdef EXTENSIONS
2080 		case 'D':
2081 			bigD = 1;
2082 			break;
2083 #endif
2084 #ifdef EXTENSIONS
2085 		case 'S':
2086 			u.u_allow_samba = 1;
2087 			break;
2088 #endif
2089 #ifdef EXTENSIONS
2090 		case 'p':
2091 			defaultfield = 1;
2092 			u.u_preserve = (strcmp(optarg, "true") == 0) ? 1 :
2093 					(strcmp(optarg, "yes") == 0) ? 1 :
2094 					 atoi(optarg);
2095 			break;
2096 #endif
2097 		case 'r':
2098 			rmhome = 1;
2099 			break;
2100 #ifdef EXTENSIONS
2101 		case 'v':
2102 			verbose = 1;
2103 			break;
2104 #endif
2105 		default:
2106 			usermgmt_usage("userdel");
2107 			/* NOTREACHED */
2108 		}
2109 	}
2110 #ifdef EXTENSIONS
2111 	if (bigD) {
2112 		if (defaultfield) {
2113 			checkeuid();
2114 			return setdefaults(&u) ? EXIT_SUCCESS : EXIT_FAILURE;
2115 		}
2116 		(void)printf("preserve\t%s\n", (u.u_preserve) ? "true" :
2117 		    "false");
2118 		return EXIT_SUCCESS;
2119 	}
2120 #endif
2121 	argc -= optind;
2122 	argv += optind;
2123 	if (argc != 1) {
2124 		usermgmt_usage("userdel");
2125 	}
2126 	checkeuid();
2127 	if ((pwp = getpwnam(*argv)) == NULL) {
2128 		warnx("No such user `%s'", *argv);
2129 		return EXIT_FAILURE;
2130 	}
2131 	if (rmhome) {
2132 		(void)removehomedir(pwp);
2133 	}
2134 	if (u.u_preserve) {
2135 		u.u_flags |= F_SHELL;
2136 		memsave(&u.u_shell, NOLOGIN, strlen(NOLOGIN));
2137 		(void)memset(password, '*', DES_Len);
2138 		password[DES_Len] = 0;
2139 		memsave(&u.u_password, password, strlen(password));
2140 		u.u_flags |= F_PASSWORD;
2141 		openlog("userdel", LOG_PID, LOG_USER);
2142 		return moduser(*argv, *argv, &u, u.u_allow_samba) ?
2143 		    EXIT_SUCCESS : EXIT_FAILURE;
2144 	}
2145 	if (!rm_user_from_groups(*argv)) {
2146 		return 0;
2147 	}
2148 	openlog("userdel", LOG_PID, LOG_USER);
2149 	return moduser(*argv, *argv, NULL, u.u_allow_samba) ?
2150 	    EXIT_SUCCESS : EXIT_FAILURE;
2151 }
2152 
2153 #ifdef EXTENSIONS
2154 #define GROUP_ADD_OPT_EXTENSIONS	"r:v"
2155 #else
2156 #define GROUP_ADD_OPT_EXTENSIONS
2157 #endif
2158 
2159 /* add a group */
2160 int
2161 groupadd(int argc, char **argv)
2162 {
2163 	int	dupgid;
2164 	int	gid;
2165 	int	c;
2166 	int	lowgid;
2167 	int	highgid;
2168 
2169 	gid = -1;
2170 	dupgid = 0;
2171 	lowgid = LowGid;
2172 	highgid = HighGid;
2173 	while ((c = getopt(argc, argv, "g:o" GROUP_ADD_OPT_EXTENSIONS)) != -1) {
2174 		switch(c) {
2175 		case 'g':
2176 			gid = check_numeric(optarg, "gid");
2177 			break;
2178 		case 'o':
2179 			dupgid = 1;
2180 			break;
2181 #ifdef EXTENSIONS
2182 		case 'r':
2183 			if (sscanf(optarg, "%d..%d", &lowgid, &highgid) != 2) {
2184 				errx(EXIT_FAILURE, "Bad range `%s'", optarg);
2185 			}
2186 			break;
2187 		case 'v':
2188 			verbose = 1;
2189 			break;
2190 #endif
2191 		default:
2192 			usermgmt_usage("groupadd");
2193 			/* NOTREACHED */
2194 		}
2195 	}
2196 	argc -= optind;
2197 	argv += optind;
2198 	if (argc != 1) {
2199 		usermgmt_usage("groupadd");
2200 	}
2201 	checkeuid();
2202 	if (gid < 0 && !getnextgid(&gid, lowgid, highgid)) {
2203 		err(EXIT_FAILURE, "Can't add group: can't get next gid");
2204 	}
2205 	if (!dupgid && getgrgid((gid_t) gid) != NULL) {
2206 		errx(EXIT_FAILURE, "Can't add group: gid %d is a duplicate",
2207 		    gid);
2208 	}
2209 	if (!valid_group(*argv)) {
2210 		warnx("Invalid group name `%s'", *argv);
2211 	}
2212 	openlog("groupadd", LOG_PID, LOG_USER);
2213 	if (!creategid(*argv, gid, ""))
2214 		exit(EXIT_FAILURE);
2215 
2216 	return EXIT_SUCCESS;
2217 }
2218 
2219 #ifdef EXTENSIONS
2220 #define GROUP_DEL_OPT_EXTENSIONS	"v"
2221 #else
2222 #define GROUP_DEL_OPT_EXTENSIONS
2223 #endif
2224 
2225 /* remove a group */
2226 int
2227 groupdel(int argc, char **argv)
2228 {
2229 	int	c;
2230 
2231 	while ((c = getopt(argc, argv, "" GROUP_DEL_OPT_EXTENSIONS)) != -1) {
2232 		switch(c) {
2233 #ifdef EXTENSIONS
2234 		case 'v':
2235 			verbose = 1;
2236 			break;
2237 #endif
2238 		default:
2239 			usermgmt_usage("groupdel");
2240 			/* NOTREACHED */
2241 		}
2242 	}
2243 	argc -= optind;
2244 	argv += optind;
2245 	if (argc != 1) {
2246 		usermgmt_usage("groupdel");
2247 	}
2248 	if (getgrnam(*argv) == NULL) {
2249 		errx(EXIT_FAILURE, "No such group `%s'", *argv);
2250 	}
2251 	checkeuid();
2252 	openlog("groupdel", LOG_PID, LOG_USER);
2253 	if (!modify_gid(*argv, NULL))
2254 		exit(EXIT_FAILURE);
2255 
2256 	return EXIT_SUCCESS;
2257 }
2258 
2259 #ifdef EXTENSIONS
2260 #define GROUP_MOD_OPT_EXTENSIONS	"v"
2261 #else
2262 #define GROUP_MOD_OPT_EXTENSIONS
2263 #endif
2264 
2265 /* modify a group */
2266 int
2267 groupmod(int argc, char **argv)
2268 {
2269 	struct group	*grp;
2270 	char		buf[MaxEntryLen];
2271 	char		*newname;
2272 	char		**cpp;
2273 	int		dupgid;
2274 	int		gid;
2275 	int		cc;
2276 	int		c;
2277 
2278 	gid = -1;
2279 	dupgid = 0;
2280 	newname = NULL;
2281 	while ((c = getopt(argc, argv, "g:on:" GROUP_MOD_OPT_EXTENSIONS)) != -1) {
2282 		switch(c) {
2283 		case 'g':
2284 			gid = check_numeric(optarg, "gid");
2285 			break;
2286 		case 'o':
2287 			dupgid = 1;
2288 			break;
2289 		case 'n':
2290 			memsave(&newname, optarg, strlen(optarg));
2291 			break;
2292 #ifdef EXTENSIONS
2293 		case 'v':
2294 			verbose = 1;
2295 			break;
2296 #endif
2297 		default:
2298 			usermgmt_usage("groupmod");
2299 			/* NOTREACHED */
2300 		}
2301 	}
2302 	argc -= optind;
2303 	argv += optind;
2304 	if (argc != 1) {
2305 		usermgmt_usage("groupmod");
2306 	}
2307 	checkeuid();
2308 	if (gid < 0 && newname == NULL) {
2309 		errx(EXIT_FAILURE, "Nothing to change");
2310 	}
2311 	if (dupgid && gid < 0) {
2312 		errx(EXIT_FAILURE, "Duplicate which gid?");
2313 	}
2314 	if ((grp = find_group_info(*argv)) == NULL) {
2315 		errx(EXIT_FAILURE, "Can't find group `%s' to modify", *argv);
2316 	}
2317 	if (!is_local(*argv, _PATH_GROUP)) {
2318 		errx(EXIT_FAILURE, "Group `%s' must be a local group", *argv);
2319 	}
2320 	if (newname != NULL && !valid_group(newname)) {
2321 		warnx("Invalid group name `%s'", newname);
2322 	}
2323 	cc = snprintf(buf, sizeof(buf), "%s:%s:%d:",
2324 			(newname) ? newname : grp->gr_name,
2325 			grp->gr_passwd,
2326 			(gid < 0) ? grp->gr_gid : gid);
2327 	for (cpp = grp->gr_mem ; *cpp && cc < sizeof(buf) ; cpp++) {
2328 		cc += snprintf(&buf[cc], sizeof(buf) - cc, "%s%s", *cpp,
2329 			(cpp[1] == NULL) ? "" : ",");
2330 	}
2331 	cc += snprintf(&buf[cc], sizeof(buf) - cc, "\n");
2332 	openlog("groupmod", LOG_PID, LOG_USER);
2333 	if (!modify_gid(*argv, buf))
2334 		exit(EXIT_FAILURE);
2335 
2336 	return EXIT_SUCCESS;
2337 }
2338 
2339 #ifdef EXTENSIONS
2340 /* display user information */
2341 int
2342 userinfo(int argc, char **argv)
2343 {
2344 	struct passwd	*pwp;
2345 	struct group	*grp;
2346 	char		buf[MaxEntryLen];
2347 	char		**cpp;
2348 	int		exists;
2349 	int		cc;
2350 	int		i;
2351 
2352 	exists = 0;
2353 	while ((i = getopt(argc, argv, "ev")) != -1) {
2354 		switch(i) {
2355 		case 'e':
2356 			exists = 1;
2357 			break;
2358 		case 'v':
2359 			verbose = 1;
2360 			break;
2361 		default:
2362 			usermgmt_usage("userinfo");
2363 			/* NOTREACHED */
2364 		}
2365 	}
2366 	argc -= optind;
2367 	argv += optind;
2368 	if (argc != 1) {
2369 		usermgmt_usage("userinfo");
2370 	}
2371 	pwp = find_user_info(*argv);
2372 	if (exists) {
2373 		exit((pwp) ? EXIT_SUCCESS : EXIT_FAILURE);
2374 	}
2375 	if (pwp == NULL) {
2376 		errx(EXIT_FAILURE, "Can't find user `%s'", *argv);
2377 	}
2378 	(void)printf("login\t%s\n", pwp->pw_name);
2379 	(void)printf("passwd\t%s\n", pwp->pw_passwd);
2380 	(void)printf("uid\t%d\n", pwp->pw_uid);
2381 	for (cc = 0 ; (grp = getgrent()) != NULL ; ) {
2382 		for (cpp = grp->gr_mem ; *cpp ; cpp++) {
2383 			if (strcmp(*cpp, *argv) == 0 &&
2384 			    grp->gr_gid != pwp->pw_gid) {
2385 				cc += snprintf(&buf[cc], sizeof(buf) - cc,
2386 				    "%s ", grp->gr_name);
2387 			}
2388 		}
2389 	}
2390 	if ((grp = getgrgid(pwp->pw_gid)) == NULL) {
2391 		(void)printf("groups\t%d %s\n", pwp->pw_gid, buf);
2392 	} else {
2393 		(void)printf("groups\t%s %s\n", grp->gr_name, buf);
2394 	}
2395 	(void)printf("change\t%s", pwp->pw_change > 0 ?
2396 	    ctime(&pwp->pw_change) : pwp->pw_change == -1 ?
2397 	    "NEXT LOGIN\n" : "NEVER\n");
2398 	(void)printf("class\t%s\n", pwp->pw_class);
2399 	(void)printf("gecos\t%s\n", pwp->pw_gecos);
2400 	(void)printf("dir\t%s\n", pwp->pw_dir);
2401 	(void)printf("shell\t%s\n", pwp->pw_shell);
2402 	(void)printf("expire\t%s", pwp->pw_expire ?
2403 	    ctime(&pwp->pw_expire) : "NEVER\n");
2404 	return EXIT_SUCCESS;
2405 }
2406 #endif
2407 
2408 #ifdef EXTENSIONS
2409 /* display user information */
2410 int
2411 groupinfo(int argc, char **argv)
2412 {
2413 	struct group	*grp;
2414 	char		**cpp;
2415 	int		exists;
2416 	int		i;
2417 
2418 	exists = 0;
2419 	while ((i = getopt(argc, argv, "ev")) != -1) {
2420 		switch(i) {
2421 		case 'e':
2422 			exists = 1;
2423 			break;
2424 		case 'v':
2425 			verbose = 1;
2426 			break;
2427 		default:
2428 			usermgmt_usage("groupinfo");
2429 			/* NOTREACHED */
2430 		}
2431 	}
2432 	argc -= optind;
2433 	argv += optind;
2434 	if (argc != 1) {
2435 		usermgmt_usage("groupinfo");
2436 	}
2437 	grp = find_group_info(*argv);
2438 	if (exists) {
2439 		exit((grp) ? EXIT_SUCCESS : EXIT_FAILURE);
2440 	}
2441 	if (grp == NULL) {
2442 		errx(EXIT_FAILURE, "Can't find group `%s'", *argv);
2443 	}
2444 	(void)printf("name\t%s\n", grp->gr_name);
2445 	(void)printf("passwd\t%s\n", grp->gr_passwd);
2446 	(void)printf("gid\t%d\n", grp->gr_gid);
2447 	(void)printf("members\t");
2448 	for (cpp = grp->gr_mem ; *cpp ; cpp++) {
2449 		(void)printf("%s", *cpp);
2450 		if (*(cpp + 1)) {
2451 			(void) printf(", ");
2452 		}
2453 	}
2454 	(void)fputc('\n', stdout);
2455 	return EXIT_SUCCESS;
2456 }
2457 #endif
2458