xref: /netbsd-src/usr.sbin/user/user.c (revision e5548b402ae4c44fb816de42c7bba9581ce23ef5)
1 /* $NetBSD: user.c,v 1.98 2005/11/25 08:00:18 agc 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.98 2005/11/25 08:00:18 agc 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 #endif
955 
956 /* look for a valid time, return 0 if it was specified but bad */
957 static int
958 scantime(time_t *tp, char *s)
959 {
960 	struct tm	tm;
961 	char *ep;
962 	long val;
963 
964 	*tp = 0;
965 	if (s != NULL) {
966 		(void)memset(&tm, 0, sizeof(tm));
967 		if (strptime(s, "%c", &tm) != NULL) {
968 			*tp = mktime(&tm);
969 			return (*tp == -1) ? 0 : 1;
970 		} else if (strptime(s, "%B %d %Y", &tm) != NULL) {
971 			*tp = mktime(&tm);
972 			return (*tp == -1) ? 0 : 1;
973 		} else {
974 			errno = 0;
975 			*tp = val = strtol(s, &ep, 10);
976 			if (*ep != '\0' || *tp < -1 || errno == ERANGE) {
977 				*tp = 0;
978 				return 0;
979 			}
980 			if (*tp != val) {
981 				return 0;
982 			}
983 		}
984 	}
985 	return 1;
986 }
987 
988 /* add a user */
989 static int
990 adduser(char *login_name, user_t *up)
991 {
992 	struct group	*grp;
993 	struct stat	st;
994 	time_t		expire;
995 	time_t		inactive;
996 	char		password[PasswordLength + 1];
997 	char		home[MaxFileNameLen];
998 	char		buf[MaxFileNameLen];
999 	int		sync_uid_gid;
1000 	int		masterfd;
1001 	int		ptmpfd;
1002 	int		gid;
1003 	int		cc;
1004 	int		i;
1005 
1006 	if (!valid_login(login_name, up->u_allow_samba)) {
1007 		errx(EXIT_FAILURE, "Can't add user `%s': invalid login name", login_name);
1008 	}
1009 #ifdef EXTENSIONS
1010 	if (!valid_class(up->u_class)) {
1011 		errx(EXIT_FAILURE, "Can't add user `%s': no such login class `%s'",
1012 		    login_name, up->u_class);
1013 	}
1014 #endif
1015 	if ((masterfd = open(_PATH_MASTERPASSWD, O_RDONLY)) < 0) {
1016 		err(EXIT_FAILURE, "Can't add user `%s': can't open `%s'",
1017 		    login_name, _PATH_MASTERPASSWD);
1018 	}
1019 	if (flock(masterfd, LOCK_EX | LOCK_NB) < 0) {
1020 		err(EXIT_FAILURE, "Can't add user `%s': can't lock `%s'",
1021 		    login_name, _PATH_MASTERPASSWD);
1022 	}
1023 	pw_init();
1024 	if ((ptmpfd = pw_lock(WAITSECS)) < 0) {
1025 		int serrno = errno;
1026 		(void)close(masterfd);
1027 		errno = serrno;
1028 		err(EXIT_FAILURE, "Can't add user `%s': can't obtain pw_lock",
1029 		    login_name);
1030 	}
1031 	while ((cc = read(masterfd, buf, sizeof(buf))) > 0) {
1032 		if (write(ptmpfd, buf, (size_t)(cc)) != cc) {
1033 			int serrno = errno;
1034 			(void)close(masterfd);
1035 			(void)close(ptmpfd);
1036 			(void)pw_abort();
1037 			errno = serrno;
1038 			err(EXIT_FAILURE, "Can't add user `%s': "
1039 			    "short write to /etc/ptmp", login_name);
1040 		}
1041 	}
1042 	/* if no uid was specified, get next one in [low_uid..high_uid] range */
1043 	sync_uid_gid = (strcmp(up->u_primgrp, "=uid") == 0);
1044 	if (up->u_uid == -1) {
1045 		int	got_id = 0;
1046 
1047 		/*
1048 		 * Look for a free UID in the command line ranges (if any).
1049 		 * These start after the ranges specified in the config file.
1050 		 */
1051 		for (i = up->u_defrc; !got_id && i < up->u_rc ; i++) {
1052 			got_id = getnextuid(sync_uid_gid, &up->u_uid,
1053 					up->u_rv[i].r_from, up->u_rv[i].r_to);
1054 		}
1055 		/*
1056 		 * If there were no free UIDs in the command line ranges,
1057 		 * try the ranges from the config file (there will always
1058 		 * be at least one default).
1059 		 */
1060 		for (i = 0; !got_id && i < up->u_defrc; i++) {
1061 			got_id = getnextuid(sync_uid_gid, &up->u_uid,
1062 					up->u_rv[i].r_from, up->u_rv[i].r_to);
1063 		}
1064 		if (!got_id) {
1065 			(void)close(ptmpfd);
1066 			(void)pw_abort();
1067 			errx(EXIT_FAILURE, "Can't add user `%s': "
1068 			    "can't get next uid for %d", login_name,
1069 			    up->u_uid);
1070 		}
1071 	}
1072 	/* check uid isn't already allocated */
1073 	if (!(up->u_flags & F_DUPUID) && getpwuid((uid_t)(up->u_uid)) != NULL) {
1074 		(void)close(ptmpfd);
1075 		(void)pw_abort();
1076 		errx(EXIT_FAILURE, "Can't add user `%s': "
1077 		    "uid %d is already in use", login_name, up->u_uid);
1078 	}
1079 	/* if -g=uid was specified, check gid is unused */
1080 	if (sync_uid_gid) {
1081 		if (getgrgid((gid_t)(up->u_uid)) != NULL) {
1082 			(void)close(ptmpfd);
1083 			(void)pw_abort();
1084 			errx(EXIT_FAILURE, "Can't add user `%s': "
1085 			    "gid %d is already in use", login_name,
1086 			    up->u_uid);
1087 		}
1088 		gid = up->u_uid;
1089 	} else if ((grp = getgrnam(up->u_primgrp)) != NULL) {
1090 		gid = grp->gr_gid;
1091 	} else if (is_number(up->u_primgrp) &&
1092 		   (grp = getgrgid((gid_t)atoi(up->u_primgrp))) != NULL) {
1093 		gid = grp->gr_gid;
1094 	} else {
1095 		(void)close(ptmpfd);
1096 		(void)pw_abort();
1097 		errx(EXIT_FAILURE, "Can't add user `%s': group %s not found",
1098 		    login_name, up->u_primgrp);
1099 	}
1100 	/* check name isn't already in use */
1101 	if (!(up->u_flags & F_DUPUID) && getpwnam(login_name) != NULL) {
1102 		(void)close(ptmpfd);
1103 		(void)pw_abort();
1104 		errx(EXIT_FAILURE, "Can't add user `%s': "
1105 		    "`%s' is already a user", login_name, login_name);
1106 	}
1107 	if (up->u_flags & F_HOMEDIR) {
1108 		(void)strlcpy(home, up->u_home, sizeof(home));
1109 	} else {
1110 		/* if home directory hasn't been given, make it up */
1111 		(void)snprintf(home, sizeof(home), "%s/%s", up->u_basedir,
1112 		    login_name);
1113 	}
1114 	if (!scantime(&inactive, up->u_inactive)) {
1115 		warnx("Warning: inactive time `%s' invalid, password expiry off",
1116 				up->u_inactive);
1117 	}
1118 	if (!scantime(&expire, up->u_expire) || expire == -1) {
1119 		warnx("Warning: expire time `%s' invalid, account expiry off",
1120 				up->u_expire);
1121 		expire = 0; /* Just in case. */
1122 	}
1123 	if (lstat(home, &st) < 0 && !(up->u_flags & F_MKDIR)) {
1124 		warnx("Warning: home directory `%s' doesn't exist, "
1125 		    "and -m was not specified", home);
1126 	}
1127 	password[sizeof(password) - 1] = '\0';
1128 	if (up->u_password != NULL && valid_password_length(up->u_password)) {
1129 		(void)strlcpy(password, up->u_password, sizeof(password));
1130 	} else {
1131 		(void)memset(password, '*', DES_Len);
1132 		password[DES_Len] = 0;
1133 		if (up->u_password != NULL) {
1134 			warnx("Password `%s' is invalid: setting it to `%s'",
1135 				up->u_password, password);
1136 		}
1137 	}
1138 	cc = snprintf(buf, sizeof(buf), "%s:%s:%d:%d:%s:%ld:%ld:%s:%s:%s\n",
1139 			login_name,
1140 			password,
1141 			up->u_uid,
1142 			gid,
1143 #ifdef EXTENSIONS
1144 			up->u_class,
1145 #else
1146 			"",
1147 #endif
1148 			(long) inactive,
1149 			(long) expire,
1150 			up->u_comment,
1151 			home,
1152 			up->u_shell);
1153 	if (write(ptmpfd, buf, (size_t) cc) != cc) {
1154 		int serrno = errno;
1155 		(void)close(ptmpfd);
1156 		(void)pw_abort();
1157 		errno = serrno;
1158 		err(EXIT_FAILURE, "Can't add user `%s': write failed",
1159 		    login_name);
1160 	}
1161 	if (up->u_flags & F_MKDIR) {
1162 		if (lstat(home, &st) == 0) {
1163 			(void)close(ptmpfd);
1164 			(void)pw_abort();
1165 			errx(EXIT_FAILURE,
1166 			    "Can't add user `%s': home directory `%s' "
1167 			    "already exists", login_name, home);
1168 		} else {
1169 			if (asystem("%s -p %s", MKDIR, home) != 0) {
1170 				(void)close(ptmpfd);
1171 				(void)pw_abort();
1172 				errx(EXIT_FAILURE, "Can't add user `%s': "
1173 				    "can't mkdir `%s'", login_name, home);
1174 			}
1175 			(void)copydotfiles(up->u_skeldir, up->u_uid, gid, home);
1176 		}
1177 	}
1178 	if (strcmp(up->u_primgrp, "=uid") == 0 &&
1179 	    getgrnam(login_name) == NULL &&
1180 	    !creategid(login_name, gid, login_name)) {
1181 		(void)close(ptmpfd);
1182 		(void)pw_abort();
1183 		errx(EXIT_FAILURE, "Can't add user `%s': can't create gid %d ",
1184 		    login_name, gid);
1185 	}
1186 	if (up->u_groupc > 0 &&
1187 	    !append_group(login_name, up->u_groupc, up->u_groupv)) {
1188 		(void)close(ptmpfd);
1189 		(void)pw_abort();
1190 		errx(EXIT_FAILURE, "Can't add user `%s': can't append "
1191 		    "to new groups", login_name);
1192 	}
1193 	(void)close(ptmpfd);
1194 #if PW_MKDB_ARGC == 2
1195 	if (pw_mkdb(login_name, 0) < 0)
1196 #else
1197 	if (pw_mkdb() < 0)
1198 #endif
1199 	{
1200 		(void)pw_abort();
1201 		errx(EXIT_FAILURE, "Can't add user `%s': pw_mkdb failed",
1202 		    login_name);
1203 	}
1204 	syslog(LOG_INFO, "New user added: name=%s, uid=%d, gid=%d, home=%s, "
1205 	    "shell=%s", login_name, up->u_uid, gid, home, up->u_shell);
1206 	return 1;
1207 }
1208 
1209 /* remove a user from the groups file */
1210 static int
1211 rm_user_from_groups(char *login_name)
1212 {
1213 	struct stat	st;
1214 	regmatch_t	matchv[10];
1215 	regex_t		r;
1216 	FILE		*from;
1217 	FILE		*to;
1218 	char		line[MaxEntryLen];
1219 	char		buf[MaxEntryLen];
1220 	char		f[MaxFileNameLen];
1221 	int		fd;
1222 	int		cc;
1223 	int		sc;
1224 
1225 	(void)snprintf(line, sizeof(line), "(:|,)(%s)(,|$)", login_name);
1226 	if ((sc = regcomp(&r, line, REG_EXTENDED|REG_NEWLINE)) != 0) {
1227 		(void)regerror(sc, &r, buf, sizeof(buf));
1228 		warnx("Can't compile regular expression `%s' (%s)", line,
1229 		    buf);
1230 		return 0;
1231 	}
1232 	if ((from = fopen(_PATH_GROUP, "r")) == NULL) {
1233 		warn("Can't remove user `%s' from `%s': can't open `%s'",
1234 		    login_name, _PATH_GROUP, _PATH_GROUP);
1235 		return 0;
1236 	}
1237 	if (flock(fileno(from), LOCK_EX | LOCK_NB) < 0) {
1238 		warn("Can't remove user `%s' from `%s': can't lock `%s'",
1239 		    login_name, _PATH_GROUP, _PATH_GROUP);
1240 		return 0;
1241 	}
1242 	(void)fstat(fileno(from), &st);
1243 	(void)snprintf(f, sizeof(f), "%s.XXXXXX", _PATH_GROUP);
1244 	if ((fd = mkstemp(f)) < 0) {
1245 		warn("Can't remove user `%s' from `%s': mkstemp failed",
1246 		    login_name, _PATH_GROUP);
1247 		(void)fclose(from);
1248 		return 0;
1249 	}
1250 	if ((to = fdopen(fd, "w")) == NULL) {
1251 		warn("Can't remove user `%s' from `%s': fdopen `%s' failed",
1252 		    login_name, _PATH_GROUP, f);
1253 		(void)fclose(from);
1254 		(void)close(fd);
1255 		(void)unlink(f);
1256 		return 0;
1257 	}
1258 	while (fgets(buf, sizeof(buf), from) != NULL) {
1259 		cc = strlen(buf);
1260 		if (regexec(&r, buf, 10, matchv, 0) == 0) {
1261 			if (buf[(int)matchv[1].rm_so] == ',') {
1262 				matchv[2].rm_so = matchv[1].rm_so;
1263 			} else if (matchv[2].rm_eo != matchv[3].rm_eo) {
1264 				matchv[2].rm_eo = matchv[3].rm_eo;
1265 			}
1266 			cc -= (int) matchv[2].rm_eo;
1267 			sc = (int) matchv[2].rm_so;
1268 			if (fwrite(buf, sizeof(char), (size_t)sc, to) != sc ||
1269 			    fwrite(&buf[(int)matchv[2].rm_eo], sizeof(char),
1270 				(size_t)cc, to) != cc) {
1271 				warn("Can't remove user `%s' from `%s': "
1272 				    "short write to `%s'", login_name,
1273 				    _PATH_GROUP, f);
1274 				(void)fclose(from);
1275 				(void)close(fd);
1276 				(void)unlink(f);
1277 				return 0;
1278 			}
1279 		} else if (fwrite(buf, sizeof(char), (unsigned) cc, to) != cc) {
1280 			warn("Can't remove user `%s' from `%s': "
1281 			    "short write to `%s'", login_name, _PATH_GROUP, f);
1282 			(void)fclose(from);
1283 			(void)close(fd);
1284 			(void)unlink(f);
1285 			return 0;
1286 		}
1287 	}
1288 	(void)fclose(from);
1289 	(void)fclose(to);
1290 	if (rename(f, _PATH_GROUP) < 0) {
1291 		warn("Can't remove user `%s' from `%s': "
1292 		    "can't rename `%s' to `%s'",
1293 		    login_name, _PATH_GROUP, f, _PATH_GROUP);
1294 		(void)unlink(f);
1295 		return 0;
1296 	}
1297 	(void)chmod(_PATH_GROUP, st.st_mode & 07777);
1298 	return 1;
1299 }
1300 
1301 /* check that the user or group is local, not from YP/NIS */
1302 static int
1303 is_local(char *name, const char *file)
1304 {
1305 	FILE	       *fp;
1306 	char		buf[MaxEntryLen];
1307 	size_t		len;
1308 	int		ret;
1309 
1310 	if ((fp = fopen(file, "r")) == NULL) {
1311 		err(EXIT_FAILURE, "Can't open `%s'", file);
1312 	}
1313 	len = strlen(name);
1314 	for (ret = 0 ; fgets(buf, sizeof(buf), fp) != NULL ; ) {
1315 		if (strncmp(buf, name, len) == 0 && buf[len] == ':') {
1316 			ret = 1;
1317 			break;
1318 		}
1319 	}
1320 	(void)fclose(fp);
1321 	return ret;
1322 }
1323 
1324 /* modify a user */
1325 static int
1326 moduser(char *login_name, char *newlogin, user_t *up, int allow_samba)
1327 {
1328 	struct passwd  *pwp;
1329 	struct group   *grp;
1330 	const char     *homedir;
1331 	char	       *locked_pwd;
1332 	size_t		colonc;
1333 	size_t		loginc;
1334 	size_t		len;
1335 	size_t		cc;
1336 	FILE	       *master;
1337 	char		newdir[MaxFileNameLen];
1338 	char	        buf[MaxEntryLen];
1339 	char	       *colon;
1340 	int		masterfd;
1341 	int		ptmpfd;
1342 	int		error;
1343 
1344 	if (!valid_login(newlogin, allow_samba)) {
1345 		errx(EXIT_FAILURE, "Can't modify user `%s': invalid login name",
1346 		    login_name);
1347 	}
1348 	if ((pwp = getpwnam(login_name)) == NULL) {
1349 		errx(EXIT_FAILURE, "Can't modify user `%s': no such user",
1350 		    login_name);
1351 	}
1352 	if (!is_local(login_name, _PATH_MASTERPASSWD)) {
1353 		errx(EXIT_FAILURE, "Can't modify user `%s': must be a local user",
1354 		    login_name);
1355 	}
1356 	/* keep dir name in case we need it for '-m' */
1357 	homedir = pwp->pw_dir;
1358 
1359 	if ((masterfd = open(_PATH_MASTERPASSWD, O_RDONLY)) < 0) {
1360 		err(EXIT_FAILURE, "Can't modify user `%s': can't open `%s'",
1361 		    login_name, _PATH_MASTERPASSWD);
1362 	}
1363 	if (flock(masterfd, LOCK_EX | LOCK_NB) < 0) {
1364 		err(EXIT_FAILURE, "Can't modify user `%s': can't lock `%s'",
1365 		    login_name, _PATH_MASTERPASSWD);
1366 	}
1367 	pw_init();
1368 	if ((ptmpfd = pw_lock(WAITSECS)) < 0) {
1369 		int serrno = errno;
1370 		(void)close(masterfd);
1371 		errno = serrno;
1372 		err(EXIT_FAILURE, "Can't modify user `%s': "
1373 		    "can't obtain pw_lock", login_name);
1374 	}
1375 	if ((master = fdopen(masterfd, "r")) == NULL) {
1376 		int serrno = errno;
1377 		(void)close(masterfd);
1378 		(void)close(ptmpfd);
1379 		(void)pw_abort();
1380 		errno = serrno;
1381 		err(EXIT_FAILURE, "Can't modify user `%s': "
1382 		    "fdopen fd for %s", login_name, _PATH_MASTERPASSWD);
1383 	}
1384 	if (up != NULL) {
1385 		if (up->u_flags & F_USERNAME) {
1386 			/*
1387 			 * If changing name,
1388 			 * check new name isn't already in use
1389 			 */
1390 			if (strcmp(login_name, newlogin) != 0 &&
1391 			    getpwnam(newlogin) != NULL) {
1392 				(void)close(ptmpfd);
1393 				(void)pw_abort();
1394 				errx(EXIT_FAILURE, "Can't modify user `%s': "
1395 				    "`%s' is already a user", login_name,
1396 				    newlogin);
1397 			}
1398 			pwp->pw_name = newlogin;
1399 
1400 			/*
1401 			 * Provide a new directory name in case the
1402 			 * home directory is to be moved.
1403 			 */
1404 			if (up->u_flags & F_MKDIR) {
1405 				(void)snprintf(newdir, sizeof(newdir), "%s/%s",
1406 				    up->u_basedir, newlogin);
1407 				pwp->pw_dir = newdir;
1408 			}
1409 		}
1410 		if (up->u_flags & F_PASSWORD) {
1411 			if (up->u_password != NULL) {
1412 				if (!valid_password_length(up->u_password)) {
1413 					(void)close(ptmpfd);
1414 					(void)pw_abort();
1415 					errx(EXIT_FAILURE,
1416 					    "Can't modify user `%s': "
1417 					    "invalid password: `%s'",
1418 					    login_name, up->u_password);
1419 				}
1420 				if ((locked_pwd =
1421 				    strstr(pwp->pw_passwd, LOCKED)) != NULL) {
1422 					/*
1423 					 * account is locked - keep it locked
1424 					 * and just change the password.
1425 					 */
1426 					if (asprintf(&locked_pwd, "%s%s",
1427 					    LOCKED, up->u_password) == -1) {
1428 						(void)close(ptmpfd);
1429 						(void)pw_abort();
1430 						err(EXIT_FAILURE,
1431 						    "Can't modify user `%s': "
1432 						    "asprintf failed",
1433 						    login_name);
1434 					}
1435 					pwp->pw_passwd = locked_pwd;
1436 				} else {
1437 					pwp->pw_passwd = up->u_password;
1438 				}
1439 			}
1440 		}
1441 
1442 		/* check whether we should lock the account. */
1443 		if (up->u_locked == LOCK) {
1444 			/* check to see account if already locked. */
1445 			if ((locked_pwd = strstr(pwp->pw_passwd, LOCKED))
1446 			    != NULL) {
1447 				warnx("Account is already locked");
1448 			} else {
1449 				if (asprintf(&locked_pwd, "%s%s", LOCKED,
1450 				    pwp->pw_passwd) == -1) {
1451 					(void)close(ptmpfd);
1452 					(void)pw_abort();
1453 					err(EXIT_FAILURE,
1454 					    "Can't modify user `%s': "
1455 					    "asprintf failed", login_name);
1456 				}
1457 				pwp->pw_passwd = locked_pwd;
1458 			}
1459 		} else if (up->u_locked == UNLOCK) {
1460 			if ((locked_pwd = strstr(pwp->pw_passwd, LOCKED))
1461 			    == NULL) {
1462 				warnx("Can't modify user `%s': "
1463 				    "account is not locked", login_name);
1464 			} else {
1465 				pwp->pw_passwd = locked_pwd + strlen(LOCKED);
1466 			}
1467 		}
1468 
1469 		if (up->u_flags & F_UID) {
1470 			/* check uid isn't already allocated */
1471 			if (!(up->u_flags & F_DUPUID) &&
1472 			    getpwuid((uid_t)(up->u_uid)) != NULL) {
1473 				(void)close(ptmpfd);
1474 				(void)pw_abort();
1475 				errx(EXIT_FAILURE, "Can't modify user `%s': "
1476 				    "uid `%d' is already in use", login_name,
1477 				    up->u_uid);
1478 			}
1479 			pwp->pw_uid = up->u_uid;
1480 		}
1481 		if (up->u_flags & F_GROUP) {
1482 			/* if -g=uid was specified, check gid is unused */
1483 			if (strcmp(up->u_primgrp, "=uid") == 0) {
1484 				if (getgrgid((gid_t)(up->u_uid)) != NULL) {
1485 					(void)close(ptmpfd);
1486 					(void)pw_abort();
1487 					errx(EXIT_FAILURE,
1488 					    "Can't modify user `%s': "
1489 					    "gid %d is already in use",
1490 					    login_name, up->u_uid);
1491 				}
1492 				pwp->pw_gid = up->u_uid;
1493 			} else if ((grp = getgrnam(up->u_primgrp)) != NULL) {
1494 				pwp->pw_gid = grp->gr_gid;
1495 			} else if (is_number(up->u_primgrp) &&
1496 				   (grp = getgrgid(
1497 				   (gid_t)atoi(up->u_primgrp))) != NULL) {
1498 				pwp->pw_gid = grp->gr_gid;
1499 			} else {
1500 				(void)close(ptmpfd);
1501 				(void)pw_abort();
1502 				errx(EXIT_FAILURE, "Can't modify user `%s': "
1503 				    "group %s not found", login_name,
1504 				    up->u_primgrp);
1505 			}
1506 		}
1507 		if (up->u_flags & F_INACTIVE) {
1508 			if (!scantime(&pwp->pw_change, up->u_inactive)) {
1509 				warnx("Warning: inactive time `%s' invalid, "
1510 				    "password expiry off",
1511 					up->u_inactive);
1512 			}
1513 		}
1514 		if (up->u_flags & F_EXPIRE) {
1515 			if (!scantime(&pwp->pw_expire, up->u_expire) ||
1516 			      pwp->pw_expire == -1) {
1517 				warnx("Warning: expire time `%s' invalid, "
1518 				    "account expiry off",
1519 					up->u_expire);
1520 				pwp->pw_expire = 0;
1521 			}
1522 		}
1523 		if (up->u_flags & F_COMMENT) {
1524 			pwp->pw_gecos = up->u_comment;
1525 		}
1526 		if (up->u_flags & F_HOMEDIR) {
1527 			pwp->pw_dir = up->u_home;
1528 		}
1529 		if (up->u_flags & F_SHELL) {
1530 			pwp->pw_shell = up->u_shell;
1531 		}
1532 #ifdef EXTENSIONS
1533 		if (up->u_flags & F_CLASS) {
1534 			if (!valid_class(up->u_class)) {
1535 				(void)close(ptmpfd);
1536 				(void)pw_abort();
1537 				errx(EXIT_FAILURE, "Can't modify user `%s': "
1538 				    "no such login class `%s'", login_name,
1539 				    up->u_class);
1540 			}
1541 			pwp->pw_class = up->u_class;
1542 		}
1543 #endif
1544 	}
1545 	loginc = strlen(login_name);
1546 	while (fgets(buf, sizeof(buf), master) != NULL) {
1547 		if ((colon = strchr(buf, ':')) == NULL) {
1548 			warnx("Malformed entry `%s'. Skipping", buf);
1549 			continue;
1550 		}
1551 		colonc = (size_t)(colon - buf);
1552 		if (strncmp(login_name, buf, loginc) == 0 && loginc == colonc) {
1553 			if (up != NULL) {
1554 				len = snprintf(buf, sizeof(buf), "%s:%s:%d:%d:"
1555 #ifdef EXTENSIONS
1556 				    "%s"
1557 #endif
1558 				    ":%ld:%ld:%s:%s:%s\n",
1559 				    newlogin,
1560 				    pwp->pw_passwd,
1561 				    pwp->pw_uid,
1562 				    pwp->pw_gid,
1563 #ifdef EXTENSIONS
1564 				    pwp->pw_class,
1565 #endif
1566 				    (long)pwp->pw_change,
1567 				    (long)pwp->pw_expire,
1568 				    pwp->pw_gecos,
1569 				    pwp->pw_dir,
1570 				    pwp->pw_shell);
1571 				if (write(ptmpfd, buf, len) != len) {
1572 					int serrno = errno;
1573 					(void)close(ptmpfd);
1574 					(void)pw_abort();
1575 					errno = serrno;
1576 					err(EXIT_FAILURE, "Can't modify user "
1577 					    "`%s': write", login_name);
1578 				}
1579 			}
1580 		} else {
1581 			len = strlen(buf);
1582 			if ((cc = write(ptmpfd, buf, len)) != len) {
1583 				int serrno = errno;
1584 				(void)close(masterfd);
1585 				(void)close(ptmpfd);
1586 				(void)pw_abort();
1587 				errno = serrno;
1588 				err(EXIT_FAILURE, "Can't modify `%s': "
1589 				    "write", login_name);
1590 			}
1591 		}
1592 	}
1593 	if (up != NULL) {
1594 		if ((up->u_flags & F_MKDIR) &&
1595 		    asystem("%s %s %s", MV, homedir, pwp->pw_dir) != 0) {
1596 			(void)close(ptmpfd);
1597 			(void)pw_abort();
1598 			errx(EXIT_FAILURE, "Can't modify user `%s': "
1599 			    "can't move `%s' to `%s'",
1600 			    login_name, homedir, pwp->pw_dir);
1601 		}
1602 		if (up->u_groupc > 0 &&
1603 		    !append_group(newlogin, up->u_groupc, up->u_groupv)) {
1604 			(void)close(ptmpfd);
1605 			(void)pw_abort();
1606 			errx(EXIT_FAILURE, "Can't modify user `%s': "
1607 			    "can't append `%s' to new groups",
1608 			    login_name, newlogin);
1609 		}
1610 	}
1611 	(void)close(ptmpfd);
1612 #if PW_MKDB_ARGC == 2
1613 	if (up != NULL && strcmp(login_name, newlogin) == 0) {
1614 		error = pw_mkdb(login_name, 0);
1615 	} else {
1616 		error = pw_mkdb(NULL, 0);
1617 	}
1618 #else
1619 	error = pw_mkdb();
1620 #endif
1621 	if (error < 0) {
1622 		(void)pw_abort();
1623 		errx(EXIT_FAILURE, "Can't modify user `%s': pw_mkdb failed",
1624 		    login_name);
1625 	}
1626 	if (up == NULL) {
1627 		syslog(LOG_INFO, "User removed: name=%s", login_name);
1628 	} else if (strcmp(login_name, newlogin) == 0) {
1629 		syslog(LOG_INFO, "User information modified: name=%s, uid=%d, "
1630 		    "gid=%d, home=%s, shell=%s",
1631 		    login_name, pwp->pw_uid, pwp->pw_gid, pwp->pw_dir,
1632 		    pwp->pw_shell);
1633 	} else {
1634 		syslog(LOG_INFO, "User information modified: name=%s, "
1635 		    "new name=%s, uid=%d, gid=%d, home=%s, shell=%s",
1636 		    login_name, newlogin, pwp->pw_uid, pwp->pw_gid,
1637 		    pwp->pw_dir, pwp->pw_shell);
1638 	}
1639 	return 1;
1640 }
1641 
1642 #ifdef EXTENSIONS
1643 /* see if we can find out the user struct */
1644 static struct passwd *
1645 find_user_info(const char *name)
1646 {
1647 	struct passwd	*pwp;
1648 
1649 	if ((pwp = getpwnam(name)) != NULL) {
1650 		return pwp;
1651 	}
1652 	if (is_number(name) && (pwp = getpwuid((uid_t)atoi(name))) != NULL) {
1653 		return pwp;
1654 	}
1655 	return NULL;
1656 }
1657 #endif
1658 
1659 /* see if we can find out the group struct */
1660 static struct group *
1661 find_group_info(const char *name)
1662 {
1663 	struct group	*grp;
1664 
1665 	if ((grp = getgrnam(name)) != NULL) {
1666 		return grp;
1667 	}
1668 	if (is_number(name) && (grp = getgrgid((gid_t)atoi(name))) != NULL) {
1669 		return grp;
1670 	}
1671 	return NULL;
1672 }
1673 
1674 /* print out usage message, and then exit */
1675 void
1676 usermgmt_usage(const char *prog)
1677 {
1678 	if (strcmp(prog, "useradd") == 0) {
1679 		(void)fprintf(stderr, "usage: %s -D [-F] [-b base-dir] "
1680 		    "[-e expiry-time] [-f inactive-time]\n"
1681 		    "\t[-g gid | name | =uid] [-k skel-dir] [-L login-class]\n"
1682 		    "\t[-r lowuid..highuid] [-s shell]\n", prog);
1683 		(void)fprintf(stderr, "usage: %s [-moSv] [-b base-dir] "
1684 		    "[-c comment] [-d home-dir] [-e expiry-time]\n"
1685 		    "\t[-f inactive-time] [-G secondary-group] "
1686 		    "[-g gid | name | =uid]\n"
1687 		    "\t[-k skeletondir] [-L login-class] [-p password]"
1688 		    "[-r lowuid..highuid]\n"
1689 		    "\t[-s shell] [-u uid] user\n",
1690 		    prog);
1691 	} else if (strcmp(prog, "usermod") == 0) {
1692 		(void)fprintf(stderr, "usage: %s [-FmoSv] [-C yes/no] "
1693 		    "[-c comment] [-d home-dir] [-e expiry-time]\n"
1694 		    "\t[-f inactive] [-G secondary-group] "
1695 		    "[-g gid | name | =uid]\n"
1696 		    "\t[-L login-class] [-l new-login] [-p password] "
1697 		    "[-s shell] [-u uid]\n"
1698 		    "\tuser\n", prog);
1699 	} else if (strcmp(prog, "userdel") == 0) {
1700 		(void)fprintf(stderr, "usage: %s -D [-p preserve-value]\n", prog);
1701 		(void)fprintf(stderr,
1702 		    "usage: %s [-rSv] [-p preserve-value] user\n", prog);
1703 #ifdef EXTENSIONS
1704 	} else if (strcmp(prog, "userinfo") == 0) {
1705 		(void)fprintf(stderr, "usage: %s [-ev] user\n", prog);
1706 #endif
1707 	} else if (strcmp(prog, "groupadd") == 0) {
1708 		(void)fprintf(stderr, "usage: %s [-ov] [-g gid]"
1709 		    " [-r lowgid..highgid] group\n", prog);
1710 	} else if (strcmp(prog, "groupdel") == 0) {
1711 		(void)fprintf(stderr, "usage: %s [-v] group\n", prog);
1712 	} else if (strcmp(prog, "groupmod") == 0) {
1713 		(void)fprintf(stderr,
1714 		    "usage: %s [-ov] [-g gid] [-n newname] group\n", prog);
1715 	} else if (strcmp(prog, "user") == 0 || strcmp(prog, "group") == 0) {
1716 		(void)fprintf(stderr,
1717 		    "usage: %s ( add | del | mod | info ) ...\n", prog);
1718 #ifdef EXTENSIONS
1719 	} else if (strcmp(prog, "groupinfo") == 0) {
1720 		(void)fprintf(stderr, "usage: %s [-ev] group\n", prog);
1721 #endif
1722 	}
1723 	exit(EXIT_FAILURE);
1724 	/* NOTREACHED */
1725 }
1726 
1727 #ifdef EXTENSIONS
1728 #define ADD_OPT_EXTENSIONS	"p:r:vL:S"
1729 #else
1730 #define ADD_OPT_EXTENSIONS
1731 #endif
1732 
1733 int
1734 useradd(int argc, char **argv)
1735 {
1736 	user_t	u;
1737 	int	defaultfield;
1738 	int	bigD;
1739 	int	c;
1740 #ifdef EXTENSIONS
1741 	int	i;
1742 #endif
1743 
1744 	(void)memset(&u, 0, sizeof(u));
1745 	read_defaults(&u);
1746 	u.u_uid = -1;
1747 	defaultfield = bigD = 0;
1748 	while ((c = getopt(argc, argv, "DFG:b:c:d:e:f:g:k:mou:s:"
1749 	    ADD_OPT_EXTENSIONS)) != -1) {
1750 		switch(c) {
1751 		case 'D':
1752 			bigD = 1;
1753 			break;
1754 		case 'F':
1755 			/*
1756 			 * Setting -1 will force the new user to
1757 			 * change their password as soon as they
1758 			 * next log in - passwd(5).
1759 			 */
1760 			defaultfield = 1;
1761 			memsave(&u.u_inactive, "-1", strlen("-1"));
1762 			break;
1763 		case 'G':
1764 			while ((u.u_groupv[u.u_groupc] = strsep(&optarg, ",")) != NULL &&
1765 			       u.u_groupc < NGROUPS_MAX) {
1766 				if (u.u_groupv[u.u_groupc][0] != 0) {
1767 					u.u_groupc++;
1768 				}
1769 			}
1770 			if (optarg != NULL) {
1771 				warnx("Truncated list of secondary groups "
1772 				    "to %d entries", NGROUPS_MAX);
1773 			}
1774 			break;
1775 #ifdef EXTENSIONS
1776 		case 'S':
1777 			u.u_allow_samba = 1;
1778 			break;
1779 #endif
1780 		case 'b':
1781 			defaultfield = 1;
1782 			memsave(&u.u_basedir, optarg, strlen(optarg));
1783 			break;
1784 		case 'c':
1785 			memsave(&u.u_comment, optarg, strlen(optarg));
1786 			break;
1787 		case 'd':
1788 			memsave(&u.u_home, optarg, strlen(optarg));
1789 			u.u_flags |= F_HOMEDIR;
1790 			break;
1791 		case 'e':
1792 			defaultfield = 1;
1793 			memsave(&u.u_expire, optarg, strlen(optarg));
1794 			break;
1795 		case 'f':
1796 			defaultfield = 1;
1797 			memsave(&u.u_inactive, optarg, strlen(optarg));
1798 			break;
1799 		case 'g':
1800 			defaultfield = 1;
1801 			memsave(&u.u_primgrp, optarg, strlen(optarg));
1802 			break;
1803 		case 'k':
1804 			defaultfield = 1;
1805 			memsave(&u.u_skeldir, optarg, strlen(optarg));
1806 			break;
1807 #ifdef EXTENSIONS
1808 		case 'L':
1809 			defaultfield = 1;
1810 			memsave(&u.u_class, optarg, strlen(optarg));
1811 			break;
1812 #endif
1813 		case 'm':
1814 			u.u_flags |= F_MKDIR;
1815 			break;
1816 		case 'o':
1817 			u.u_flags |= F_DUPUID;
1818 			break;
1819 #ifdef EXTENSIONS
1820 		case 'p':
1821 			memsave(&u.u_password, optarg, strlen(optarg));
1822 			break;
1823 #endif
1824 #ifdef EXTENSIONS
1825 		case 'r':
1826 			defaultfield = 1;
1827 			(void)save_range(&u, optarg);
1828 			break;
1829 #endif
1830 		case 's':
1831 			defaultfield = 1;
1832 			memsave(&u.u_shell, optarg, strlen(optarg));
1833 			break;
1834 		case 'u':
1835 			u.u_uid = check_numeric(optarg, "uid");
1836 			break;
1837 #ifdef EXTENSIONS
1838 		case 'v':
1839 			verbose = 1;
1840 			break;
1841 #endif
1842 		default:
1843 			usermgmt_usage("useradd");
1844 			/* NOTREACHED */
1845 		}
1846 	}
1847 	if (bigD) {
1848 		if (defaultfield) {
1849 			checkeuid();
1850 			return setdefaults(&u) ? EXIT_SUCCESS : EXIT_FAILURE;
1851 		}
1852 		(void)printf("group\t\t%s\n", u.u_primgrp);
1853 		(void)printf("base_dir\t%s\n", u.u_basedir);
1854 		(void)printf("skel_dir\t%s\n", u.u_skeldir);
1855 		(void)printf("shell\t\t%s\n", u.u_shell);
1856 #ifdef EXTENSIONS
1857 		(void)printf("class\t\t%s\n", u.u_class);
1858 #endif
1859 		(void)printf("inactive\t%s\n", (u.u_inactive == NULL) ?
1860 		    UNSET_INACTIVE : u.u_inactive);
1861 		(void)printf("expire\t\t%s\n", (u.u_expire == NULL) ?
1862 		    UNSET_EXPIRY : u.u_expire);
1863 #ifdef EXTENSIONS
1864 		for (i = 0 ; i < u.u_rc ; i++) {
1865 			(void)printf("range\t\t%d..%d\n",
1866 			    u.u_rv[i].r_from, u.u_rv[i].r_to);
1867 		}
1868 #endif
1869 		return EXIT_SUCCESS;
1870 	}
1871 	argc -= optind;
1872 	argv += optind;
1873 	if (argc != 1) {
1874 		usermgmt_usage("useradd");
1875 	}
1876 	checkeuid();
1877 	openlog("useradd", LOG_PID, LOG_USER);
1878 	return adduser(*argv, &u) ? EXIT_SUCCESS : EXIT_FAILURE;
1879 }
1880 
1881 #ifdef EXTENSIONS
1882 #define MOD_OPT_EXTENSIONS	"p:vL:S"
1883 #else
1884 #define MOD_OPT_EXTENSIONS
1885 #endif
1886 
1887 int
1888 usermod(int argc, char **argv)
1889 {
1890 	user_t	u;
1891 	char	newuser[MaxUserNameLen + 1];
1892 	int	c, have_new_user;
1893 
1894 	(void)memset(&u, 0, sizeof(u));
1895 	(void)memset(newuser, 0, sizeof(newuser));
1896 	read_defaults(&u);
1897 	have_new_user = 0;
1898 	u.u_locked = -1;
1899 	while ((c = getopt(argc, argv, "C:FG:c:d:e:f:g:l:mos:u:"
1900 	    MOD_OPT_EXTENSIONS)) != -1) {
1901 		switch(c) {
1902 		case 'G':
1903 			while ((u.u_groupv[u.u_groupc] =
1904 			    strsep(&optarg, ",")) != NULL &&
1905 			    u.u_groupc < NGROUPS_MAX) {
1906 				if (u.u_groupv[u.u_groupc][0] != 0) {
1907 					u.u_groupc++;
1908 				}
1909 			}
1910 			if (optarg != NULL) {
1911 				warnx("Truncated list of secondary groups "
1912 				    "to %d entries", NGROUPS_MAX);
1913 			}
1914 			u.u_flags |= F_SECGROUP;
1915 			break;
1916 #ifdef EXTENSIONS
1917 		case 'S':
1918 			u.u_allow_samba = 1;
1919 			break;
1920 #endif
1921 		case 'c':
1922 			memsave(&u.u_comment, optarg, strlen(optarg));
1923 			u.u_flags |= F_COMMENT;
1924 			break;
1925 		case 'C':
1926 			if (strcasecmp(optarg, "yes") == 0) {
1927 				u.u_locked = LOCK;
1928 			} else if (strcasecmp(optarg, "no") == 0) {
1929 				u.u_locked = UNLOCK;
1930 			} else {
1931 				/* No idea. */
1932 				errx(EXIT_FAILURE,
1933 					"Please type 'yes' or 'no'");
1934 			}
1935 			break;
1936 		case 'F':
1937 			memsave(&u.u_inactive, "-1", strlen("-1"));
1938 			u.u_flags |= F_INACTIVE;
1939 			break;
1940 		case 'd':
1941 			memsave(&u.u_home, optarg, strlen(optarg));
1942 			u.u_flags |= F_HOMEDIR;
1943 			break;
1944 		case 'e':
1945 			memsave(&u.u_expire, optarg, strlen(optarg));
1946 			u.u_flags |= F_EXPIRE;
1947 			break;
1948 		case 'f':
1949 			memsave(&u.u_inactive, optarg, strlen(optarg));
1950 			u.u_flags |= F_INACTIVE;
1951 			break;
1952 		case 'g':
1953 			memsave(&u.u_primgrp, optarg, strlen(optarg));
1954 			u.u_flags |= F_GROUP;
1955 			break;
1956 		case 'l':
1957 			(void)strlcpy(newuser, optarg, sizeof(newuser));
1958 			have_new_user = 1;
1959 			u.u_flags |= F_USERNAME;
1960 			break;
1961 #ifdef EXTENSIONS
1962 		case 'L':
1963 			memsave(&u.u_class, optarg, strlen(optarg));
1964 			u.u_flags |= F_CLASS;
1965 			break;
1966 #endif
1967 		case 'm':
1968 			u.u_flags |= F_MKDIR;
1969 			break;
1970 		case 'o':
1971 			u.u_flags |= F_DUPUID;
1972 			break;
1973 #ifdef EXTENSIONS
1974 		case 'p':
1975 			memsave(&u.u_password, optarg, strlen(optarg));
1976 			u.u_flags |= F_PASSWORD;
1977 			break;
1978 #endif
1979 		case 's':
1980 			memsave(&u.u_shell, optarg, strlen(optarg));
1981 			u.u_flags |= F_SHELL;
1982 			break;
1983 		case 'u':
1984 			u.u_uid = check_numeric(optarg, "uid");
1985 			u.u_flags |= F_UID;
1986 			break;
1987 #ifdef EXTENSIONS
1988 		case 'v':
1989 			verbose = 1;
1990 			break;
1991 #endif
1992 		default:
1993 			usermgmt_usage("usermod");
1994 			/* NOTREACHED */
1995 		}
1996 	}
1997 	if ((u.u_flags & F_MKDIR) && !(u.u_flags & F_HOMEDIR) &&
1998 	    !(u.u_flags & F_USERNAME)) {
1999 		warnx("Option 'm' useless without 'd' or 'l' -- ignored");
2000 		u.u_flags &= ~F_MKDIR;
2001 	}
2002 	argc -= optind;
2003 	argv += optind;
2004 	if (argc != 1) {
2005 		usermgmt_usage("usermod");
2006 	}
2007 	checkeuid();
2008 	openlog("usermod", LOG_PID, LOG_USER);
2009 	return moduser(*argv, (have_new_user) ? newuser : *argv, &u,
2010 	    u.u_allow_samba) ? EXIT_SUCCESS : EXIT_FAILURE;
2011 }
2012 
2013 #ifdef EXTENSIONS
2014 #define DEL_OPT_EXTENSIONS	"Dp:vS"
2015 #else
2016 #define DEL_OPT_EXTENSIONS
2017 #endif
2018 
2019 int
2020 userdel(int argc, char **argv)
2021 {
2022 	struct passwd	*pwp;
2023 	user_t		u;
2024 	char		password[PasswordLength + 1];
2025 	int		defaultfield;
2026 	int		rmhome;
2027 	int		bigD;
2028 	int		c;
2029 
2030 	(void)memset(&u, 0, sizeof(u));
2031 	read_defaults(&u);
2032 	defaultfield = bigD = rmhome = 0;
2033 	while ((c = getopt(argc, argv, "r" DEL_OPT_EXTENSIONS)) != -1) {
2034 		switch(c) {
2035 #ifdef EXTENSIONS
2036 		case 'D':
2037 			bigD = 1;
2038 			break;
2039 #endif
2040 #ifdef EXTENSIONS
2041 		case 'S':
2042 			u.u_allow_samba = 1;
2043 			break;
2044 #endif
2045 #ifdef EXTENSIONS
2046 		case 'p':
2047 			defaultfield = 1;
2048 			u.u_preserve = (strcmp(optarg, "true") == 0) ? 1 :
2049 					(strcmp(optarg, "yes") == 0) ? 1 :
2050 					 atoi(optarg);
2051 			break;
2052 #endif
2053 		case 'r':
2054 			rmhome = 1;
2055 			break;
2056 #ifdef EXTENSIONS
2057 		case 'v':
2058 			verbose = 1;
2059 			break;
2060 #endif
2061 		default:
2062 			usermgmt_usage("userdel");
2063 			/* NOTREACHED */
2064 		}
2065 	}
2066 #ifdef EXTENSIONS
2067 	if (bigD) {
2068 		if (defaultfield) {
2069 			checkeuid();
2070 			return setdefaults(&u) ? EXIT_SUCCESS : EXIT_FAILURE;
2071 		}
2072 		(void)printf("preserve\t%s\n", (u.u_preserve) ? "true" :
2073 		    "false");
2074 		return EXIT_SUCCESS;
2075 	}
2076 #endif
2077 	argc -= optind;
2078 	argv += optind;
2079 	if (argc != 1) {
2080 		usermgmt_usage("userdel");
2081 	}
2082 	checkeuid();
2083 	if ((pwp = getpwnam(*argv)) == NULL) {
2084 		warnx("No such user `%s'", *argv);
2085 		return EXIT_FAILURE;
2086 	}
2087 	if (rmhome) {
2088 		(void)removehomedir(pwp);
2089 	}
2090 	if (u.u_preserve) {
2091 		u.u_flags |= F_SHELL;
2092 		memsave(&u.u_shell, NOLOGIN, strlen(NOLOGIN));
2093 		(void)memset(password, '*', DES_Len);
2094 		password[DES_Len] = 0;
2095 		memsave(&u.u_password, password, strlen(password));
2096 		u.u_flags |= F_PASSWORD;
2097 		openlog("userdel", LOG_PID, LOG_USER);
2098 		return moduser(*argv, *argv, &u, u.u_allow_samba) ?
2099 		    EXIT_SUCCESS : EXIT_FAILURE;
2100 	}
2101 	if (!rm_user_from_groups(*argv)) {
2102 		return 0;
2103 	}
2104 	openlog("userdel", LOG_PID, LOG_USER);
2105 	return moduser(*argv, *argv, NULL, u.u_allow_samba) ?
2106 	    EXIT_SUCCESS : EXIT_FAILURE;
2107 }
2108 
2109 #ifdef EXTENSIONS
2110 #define GROUP_ADD_OPT_EXTENSIONS	"r:v"
2111 #else
2112 #define GROUP_ADD_OPT_EXTENSIONS
2113 #endif
2114 
2115 /* add a group */
2116 int
2117 groupadd(int argc, char **argv)
2118 {
2119 	int	dupgid;
2120 	int	gid;
2121 	int	c;
2122 	int	lowgid;
2123 	int	highgid;
2124 
2125 	gid = -1;
2126 	dupgid = 0;
2127 	lowgid = LowGid;
2128 	highgid = HighGid;
2129 	while ((c = getopt(argc, argv, "g:o" GROUP_ADD_OPT_EXTENSIONS)) != -1) {
2130 		switch(c) {
2131 		case 'g':
2132 			gid = check_numeric(optarg, "gid");
2133 			break;
2134 		case 'o':
2135 			dupgid = 1;
2136 			break;
2137 #ifdef EXTENSIONS
2138 		case 'r':
2139 			if (sscanf(optarg, "%d..%d", &lowgid, &highgid) != 2) {
2140 				errx(EXIT_FAILURE, "Bad range `%s'", optarg);
2141 			}
2142 			break;
2143 		case 'v':
2144 			verbose = 1;
2145 			break;
2146 #endif
2147 		default:
2148 			usermgmt_usage("groupadd");
2149 			/* NOTREACHED */
2150 		}
2151 	}
2152 	argc -= optind;
2153 	argv += optind;
2154 	if (argc != 1) {
2155 		usermgmt_usage("groupadd");
2156 	}
2157 	checkeuid();
2158 	if (gid < 0 && !getnextgid(&gid, lowgid, highgid)) {
2159 		err(EXIT_FAILURE, "Can't add group: can't get next gid");
2160 	}
2161 	if (!dupgid && getgrgid((gid_t) gid) != NULL) {
2162 		errx(EXIT_FAILURE, "Can't add group: gid %d is a duplicate",
2163 		    gid);
2164 	}
2165 	if (!valid_group(*argv)) {
2166 		warnx("Invalid group name `%s'", *argv);
2167 	}
2168 	openlog("groupadd", LOG_PID, LOG_USER);
2169 	if (!creategid(*argv, gid, ""))
2170 		exit(EXIT_FAILURE);
2171 
2172 	return EXIT_SUCCESS;
2173 }
2174 
2175 #ifdef EXTENSIONS
2176 #define GROUP_DEL_OPT_EXTENSIONS	"v"
2177 #else
2178 #define GROUP_DEL_OPT_EXTENSIONS
2179 #endif
2180 
2181 /* remove a group */
2182 int
2183 groupdel(int argc, char **argv)
2184 {
2185 	int	c;
2186 
2187 	while ((c = getopt(argc, argv, "" GROUP_DEL_OPT_EXTENSIONS)) != -1) {
2188 		switch(c) {
2189 #ifdef EXTENSIONS
2190 		case 'v':
2191 			verbose = 1;
2192 			break;
2193 #endif
2194 		default:
2195 			usermgmt_usage("groupdel");
2196 			/* NOTREACHED */
2197 		}
2198 	}
2199 	argc -= optind;
2200 	argv += optind;
2201 	if (argc != 1) {
2202 		usermgmt_usage("groupdel");
2203 	}
2204 	if (getgrnam(*argv) == NULL) {
2205 		errx(EXIT_FAILURE, "No such group `%s'", *argv);
2206 	}
2207 	checkeuid();
2208 	openlog("groupdel", LOG_PID, LOG_USER);
2209 	if (!modify_gid(*argv, NULL))
2210 		exit(EXIT_FAILURE);
2211 
2212 	return EXIT_SUCCESS;
2213 }
2214 
2215 #ifdef EXTENSIONS
2216 #define GROUP_MOD_OPT_EXTENSIONS	"v"
2217 #else
2218 #define GROUP_MOD_OPT_EXTENSIONS
2219 #endif
2220 
2221 /* modify a group */
2222 int
2223 groupmod(int argc, char **argv)
2224 {
2225 	struct group	*grp;
2226 	char		buf[MaxEntryLen];
2227 	char		*newname;
2228 	char		**cpp;
2229 	int		dupgid;
2230 	int		gid;
2231 	int		cc;
2232 	int		c;
2233 
2234 	gid = -1;
2235 	dupgid = 0;
2236 	newname = NULL;
2237 	while ((c = getopt(argc, argv, "g:on:" GROUP_MOD_OPT_EXTENSIONS)) != -1) {
2238 		switch(c) {
2239 		case 'g':
2240 			gid = check_numeric(optarg, "gid");
2241 			break;
2242 		case 'o':
2243 			dupgid = 1;
2244 			break;
2245 		case 'n':
2246 			memsave(&newname, optarg, strlen(optarg));
2247 			break;
2248 #ifdef EXTENSIONS
2249 		case 'v':
2250 			verbose = 1;
2251 			break;
2252 #endif
2253 		default:
2254 			usermgmt_usage("groupmod");
2255 			/* NOTREACHED */
2256 		}
2257 	}
2258 	argc -= optind;
2259 	argv += optind;
2260 	if (argc != 1) {
2261 		usermgmt_usage("groupmod");
2262 	}
2263 	checkeuid();
2264 	if (gid < 0 && newname == NULL) {
2265 		errx(EXIT_FAILURE, "Nothing to change");
2266 	}
2267 	if (dupgid && gid < 0) {
2268 		errx(EXIT_FAILURE, "Duplicate which gid?");
2269 	}
2270 	if ((grp = find_group_info(*argv)) == NULL) {
2271 		errx(EXIT_FAILURE, "Can't find group `%s' to modify", *argv);
2272 	}
2273 	if (!is_local(*argv, _PATH_GROUP)) {
2274 		errx(EXIT_FAILURE, "Group `%s' must be a local group", *argv);
2275 	}
2276 	if (newname != NULL && !valid_group(newname)) {
2277 		warnx("Invalid group name `%s'", newname);
2278 	}
2279 	cc = snprintf(buf, sizeof(buf), "%s:%s:%d:",
2280 			(newname) ? newname : grp->gr_name,
2281 			grp->gr_passwd,
2282 			(gid < 0) ? grp->gr_gid : gid);
2283 	for (cpp = grp->gr_mem ; *cpp && cc < sizeof(buf) ; cpp++) {
2284 		cc += snprintf(&buf[cc], sizeof(buf) - cc, "%s%s", *cpp,
2285 			(cpp[1] == NULL) ? "" : ",");
2286 	}
2287 	cc += snprintf(&buf[cc], sizeof(buf) - cc, "\n");
2288 	openlog("groupmod", LOG_PID, LOG_USER);
2289 	if (!modify_gid(*argv, buf))
2290 		exit(EXIT_FAILURE);
2291 
2292 	return EXIT_SUCCESS;
2293 }
2294 
2295 #ifdef EXTENSIONS
2296 /* display user information */
2297 int
2298 userinfo(int argc, char **argv)
2299 {
2300 	struct passwd	*pwp;
2301 	struct group	*grp;
2302 	char		buf[MaxEntryLen];
2303 	char		**cpp;
2304 	int		exists;
2305 	int		cc;
2306 	int		i;
2307 
2308 	exists = 0;
2309 	while ((i = getopt(argc, argv, "ev")) != -1) {
2310 		switch(i) {
2311 		case 'e':
2312 			exists = 1;
2313 			break;
2314 		case 'v':
2315 			verbose = 1;
2316 			break;
2317 		default:
2318 			usermgmt_usage("userinfo");
2319 			/* NOTREACHED */
2320 		}
2321 	}
2322 	argc -= optind;
2323 	argv += optind;
2324 	if (argc != 1) {
2325 		usermgmt_usage("userinfo");
2326 	}
2327 	pwp = find_user_info(*argv);
2328 	if (exists) {
2329 		exit((pwp) ? EXIT_SUCCESS : EXIT_FAILURE);
2330 	}
2331 	if (pwp == NULL) {
2332 		errx(EXIT_FAILURE, "Can't find user `%s'", *argv);
2333 	}
2334 	(void)printf("login\t%s\n", pwp->pw_name);
2335 	(void)printf("passwd\t%s\n", pwp->pw_passwd);
2336 	(void)printf("uid\t%d\n", pwp->pw_uid);
2337 	for (cc = 0 ; (grp = getgrent()) != NULL ; ) {
2338 		for (cpp = grp->gr_mem ; *cpp ; cpp++) {
2339 			if (strcmp(*cpp, *argv) == 0 &&
2340 			    grp->gr_gid != pwp->pw_gid) {
2341 				cc += snprintf(&buf[cc], sizeof(buf) - cc,
2342 				    "%s ", grp->gr_name);
2343 			}
2344 		}
2345 	}
2346 	if ((grp = getgrgid(pwp->pw_gid)) == NULL) {
2347 		(void)printf("groups\t%d %s\n", pwp->pw_gid, buf);
2348 	} else {
2349 		(void)printf("groups\t%s %s\n", grp->gr_name, buf);
2350 	}
2351 	(void)printf("change\t%s", pwp->pw_change > 0 ?
2352 	    ctime(&pwp->pw_change) : pwp->pw_change == -1 ?
2353 	    "NEXT LOGIN\n" : "NEVER\n");
2354 	(void)printf("class\t%s\n", pwp->pw_class);
2355 	(void)printf("gecos\t%s\n", pwp->pw_gecos);
2356 	(void)printf("dir\t%s\n", pwp->pw_dir);
2357 	(void)printf("shell\t%s\n", pwp->pw_shell);
2358 	(void)printf("expire\t%s", pwp->pw_expire ?
2359 	    ctime(&pwp->pw_expire) : "NEVER\n");
2360 	return EXIT_SUCCESS;
2361 }
2362 #endif
2363 
2364 #ifdef EXTENSIONS
2365 /* display user information */
2366 int
2367 groupinfo(int argc, char **argv)
2368 {
2369 	struct group	*grp;
2370 	char		**cpp;
2371 	int		exists;
2372 	int		i;
2373 
2374 	exists = 0;
2375 	while ((i = getopt(argc, argv, "ev")) != -1) {
2376 		switch(i) {
2377 		case 'e':
2378 			exists = 1;
2379 			break;
2380 		case 'v':
2381 			verbose = 1;
2382 			break;
2383 		default:
2384 			usermgmt_usage("groupinfo");
2385 			/* NOTREACHED */
2386 		}
2387 	}
2388 	argc -= optind;
2389 	argv += optind;
2390 	if (argc != 1) {
2391 		usermgmt_usage("groupinfo");
2392 	}
2393 	grp = find_group_info(*argv);
2394 	if (exists) {
2395 		exit((grp) ? EXIT_SUCCESS : EXIT_FAILURE);
2396 	}
2397 	if (grp == NULL) {
2398 		errx(EXIT_FAILURE, "Can't find group `%s'", *argv);
2399 	}
2400 	(void)printf("name\t%s\n", grp->gr_name);
2401 	(void)printf("passwd\t%s\n", grp->gr_passwd);
2402 	(void)printf("gid\t%d\n", grp->gr_gid);
2403 	(void)printf("members\t");
2404 	for (cpp = grp->gr_mem ; *cpp ; cpp++) {
2405 		(void)printf("%s", *cpp);
2406 		if (*(cpp + 1)) {
2407 			(void) printf(", ");
2408 		}
2409 	}
2410 	(void)fputc('\n', stdout);
2411 	return EXIT_SUCCESS;
2412 }
2413 #endif
2414