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