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