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