xref: /openbsd/usr.sbin/user/user.c (revision 7b36286a)
1 /* $OpenBSD: user.c,v 1.72 2007/08/02 16:18:05 deraadt 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 		if (strlcpy(home, up->u_home, sizeof(home)) >= sizeof(home)) {
1067 			(void) close(ptmpfd);
1068 			pw_abort();
1069 			errx(EXIT_FAILURE, "home directory `%s' too long",
1070 			    up->u_home);
1071 		}
1072 	} else {
1073 		/* if home directory hasn't been given, make it up */
1074 		if (snprintf(home, sizeof(home), "%s/%s", up->u_basedir,
1075 		    login_name) >= sizeof(home)) {
1076 			(void) close(ptmpfd);
1077 			pw_abort();
1078 			errx(EXIT_FAILURE, "home directory `%s/%s' too long",
1079 			    up->u_basedir, login_name);
1080 		}
1081 	}
1082 	if (!scantime(&inactive, up->u_inactive)) {
1083 		warnx("Warning: inactive time `%s' invalid, password expiry off",
1084 				up->u_inactive);
1085 	}
1086 	if (!scantime(&expire, up->u_expire)) {
1087 		warnx("Warning: expire time `%s' invalid, account expiry off",
1088 				up->u_expire);
1089 	}
1090 	if (lstat(home, &st) < 0 && !(up->u_flags & F_MKDIR) &&
1091 	    strcmp(home, _PATH_NONEXISTENT) != 0) {
1092 		warnx("Warning: home directory `%s' doesn't exist, and -m was"
1093 		    " not specified", home);
1094 	}
1095 	if (up->u_password != NULL && valid_password_length(up->u_password)) {
1096 		(void) strlcpy(password, up->u_password, sizeof(password));
1097 	} else {
1098 		(void) memset(password, '*', DES_Len);
1099 		password[DES_Len] = 0;
1100 		if (up->u_password != NULL) {
1101 			warnx("Password `%s' is invalid: setting it to `%s'",
1102 				up->u_password, password);
1103 		}
1104 	}
1105 	cc = snprintf(buf, sizeof(buf), "%s:%s:%d:%d:%s:%ld:%ld:%s:%s:%s\n",
1106 	    login_name,
1107 	    password,
1108 	    up->u_uid,
1109 	    gid,
1110 #ifdef EXTENSIONS
1111 	    up->u_class,
1112 #else
1113 	    "",
1114 #endif
1115 	    (long) inactive,
1116 	    (long) expire,
1117 	    up->u_comment,
1118 	    home,
1119 	    up->u_shell);
1120 	if (cc >= sizeof(buf) || cc < 0 ||
1121 	    cc + expand_len(up->u_comment, login_name) >= 1023) {
1122 		(void) close(ptmpfd);
1123 		pw_abort();
1124 		errx(EXIT_FAILURE, "can't add `%s', line too long", buf);
1125 	}
1126 	if (write(ptmpfd, buf, (size_t) cc) != cc) {
1127 		(void) close(ptmpfd);
1128 		pw_abort();
1129 		err(EXIT_FAILURE, "can't add `%s'", buf);
1130 	}
1131 	if (yp) {
1132 		cc = snprintf(buf, sizeof(buf), "+:*::::::::\n");
1133 		if (cc == -1 || cc >= sizeof(buf)) {
1134 			(void) close(ptmpfd);
1135 			pw_abort();
1136 			errx(EXIT_FAILURE, "can't add `%s', line too long", buf);
1137 		}
1138 		if (write(ptmpfd, buf, (size_t) cc) != cc) {
1139 			(void) close(ptmpfd);
1140 			pw_abort();
1141 			err(EXIT_FAILURE, "can't add `%s'", buf);
1142 		}
1143 	}
1144 	if (up->u_flags & F_MKDIR) {
1145 		if (lstat(home, &st) == 0) {
1146 			(void) close(ptmpfd);
1147 			pw_abort();
1148 			errx(EXIT_FAILURE, "home directory `%s' already exists",
1149 			    home);
1150 		} else {
1151 			if (asystem("%s -p %s", MKDIR, home) != 0) {
1152 				(void) close(ptmpfd);
1153 				pw_abort();
1154 				err(EXIT_FAILURE, "can't mkdir `%s'", home);
1155 			}
1156 			(void) copydotfiles(up->u_skeldir, up->u_uid, gid, home);
1157 		}
1158 	}
1159 	if (strcmp(up->u_primgrp, "=uid") == 0 &&
1160 	    getgrnam(login_name) == NULL &&
1161 	    !creategid(login_name, gid, login_name)) {
1162 		(void) close(ptmpfd);
1163 		pw_abort();
1164 		errx(EXIT_FAILURE, "can't create gid %d for login name %s",
1165 		    gid, login_name);
1166 	}
1167 	if (up->u_groupc > 0 && !append_group(login_name, up->u_groupc, up->u_groupv)) {
1168 		(void) close(ptmpfd);
1169 		pw_abort();
1170 		errx(EXIT_FAILURE, "can't append `%s' to new groups", login_name);
1171 	}
1172 	(void) close(ptmpfd);
1173 	if (pw_mkdb(yp ? NULL : login_name, 0) < 0) {
1174 		pw_abort();
1175 		err(EXIT_FAILURE, "pw_mkdb failed");
1176 	}
1177 	syslog(LOG_INFO, "new user added: name=%s, uid=%d, gid=%d, home=%s, shell=%s",
1178 		login_name, up->u_uid, gid, home, up->u_shell);
1179 	return 1;
1180 }
1181 
1182 /* remove a user from the groups file */
1183 static int
1184 rm_user_from_groups(char *login_name)
1185 {
1186 	struct stat	st;
1187 	size_t		login_len;
1188 	FILE		*from;
1189 	FILE		*to;
1190 	char		buf[LINE_MAX];
1191 	char		f[MaxFileNameLen];
1192 	char		*cp, *ep;
1193 	int		fd;
1194 	int		cc;
1195 
1196 	login_len = strlen(login_name);
1197 	if ((from = fopen(_PATH_GROUP, "r")) == NULL) {
1198 		warn("can't remove gid for `%s': can't open `%s'",
1199 		    login_name, _PATH_GROUP);
1200 		return 0;
1201 	}
1202 	if (flock(fileno(from), LOCK_EX | LOCK_NB) < 0) {
1203 		warn("can't lock `%s'", _PATH_GROUP);
1204 	}
1205 	(void) fstat(fileno(from), &st);
1206 	(void) snprintf(f, sizeof(f), "%s.XXXXXXXX", _PATH_GROUP);
1207 	if ((fd = mkstemp(f)) < 0) {
1208 		(void) fclose(from);
1209 		warn("can't remove gid for `%s': mkstemp failed", login_name);
1210 		return 0;
1211 	}
1212 	if ((to = fdopen(fd, "w")) == NULL) {
1213 		(void) fclose(from);
1214 		(void) close(fd);
1215 		(void) unlink(f);
1216 		warn("can't remove gid for `%s': fdopen `%s' failed",
1217 		    login_name, f);
1218 		return 0;
1219 	}
1220 	while (fgets(buf, sizeof(buf), from) > 0) {
1221 		cc = strlen(buf);
1222 		if (buf[cc - 1] != '\n' && !feof(from)) {
1223 			while (fgetc(from) != '\n' && !feof(from))
1224 				cc++;
1225 			warn("%s: line `%s' too long (%d bytes), skipping",
1226 			    _PATH_GROUP, buf, cc);
1227 			continue;
1228 		}
1229 
1230 		/* Break out the group list. */
1231 		for (cp = buf, cc = 0; *cp != '\0' && cc < 3; cp++) {
1232 			if (*cp == ':')
1233 				cc++;
1234 		}
1235 		if (cc != 3) {
1236 			warnx("Malformed entry `%.*s'. Skipping",
1237 			    (int)strlen(buf) - 1, buf);
1238 			continue;
1239 		}
1240 		while ((cp = strstr(cp, login_name)) != NULL) {
1241 			if ((cp[-1] == ':' || cp[-1] == ',') &&
1242 			    (cp[login_len] == ',' || cp[login_len] == '\n')) {
1243 				ep = cp + login_len;
1244 				if (cp[login_len] == ',')
1245 					ep++;
1246 				else if (cp[-1] == ',')
1247 					cp--;
1248 				memmove(cp, ep, strlen(ep) + 1);
1249 			} else {
1250 				if ((cp = strchr(cp, ',')) == NULL)
1251 					break;
1252 				cp++;
1253 			}
1254 		}
1255 		if (fwrite(buf, strlen(buf), 1, to) != 1) {
1256 			(void) fclose(from);
1257 			(void) fclose(to);
1258 			(void) unlink(f);
1259 			warn("can't remove gid for `%s': short write to `%s'",
1260 			    login_name, f);
1261 			return 0;
1262 		}
1263 	}
1264 	(void) fchmod(fileno(to), st.st_mode & 07777);
1265 	(void) fclose(from);
1266 	if (fclose(to) == EOF) {
1267 		(void) unlink(f);
1268 		warn("can't remove gid for `%s': short write to `%s'",
1269 		    login_name, f);
1270 		return 0;
1271 	}
1272 	if (rename(f, _PATH_GROUP) < 0) {
1273 		(void) unlink(f);
1274 		warn("can't remove gid for `%s': can't rename `%s' to `%s'",
1275 		    login_name, f, _PATH_GROUP);
1276 		return 0;
1277 	}
1278 	return 1;
1279 }
1280 
1281 /* check that the user or group is local, not from YP/NIS */
1282 static int
1283 is_local(char *name, const char *file)
1284 {
1285 	FILE	       *fp;
1286 	char		buf[LINE_MAX];
1287 	size_t		len;
1288 	int		ret;
1289 	int		cc;
1290 
1291 	if ((fp = fopen(file, "r")) == NULL) {
1292 		err(EXIT_FAILURE, "can't open `%s'", file);
1293 	}
1294 	len = strlen(name);
1295 	for (ret = 0 ; fgets(buf, sizeof(buf), fp) != NULL ; ) {
1296 		cc = strlen(buf);
1297 		if (buf[cc - 1] != '\n' && !feof(fp)) {
1298 			while (fgetc(fp) != '\n' && !feof(fp))
1299 				cc++;
1300 			warn("%s: line `%s' too long (%d bytes), skipping",
1301 			    file, buf, cc);
1302 			continue;
1303 		}
1304 		if (strncmp(buf, name, len) == 0 && buf[len] == ':') {
1305 			ret = 1;
1306 			break;
1307 		}
1308 	}
1309 	(void) fclose(fp);
1310 	return ret;
1311 }
1312 
1313 /* modify a user */
1314 static int
1315 moduser(char *login_name, char *newlogin, user_t *up)
1316 {
1317 	struct passwd	*pwp;
1318 	struct group	*grp;
1319 	const char	*homedir;
1320 	char		buf[LINE_MAX];
1321 	size_t		colonc, loginc;
1322 	size_t		cc;
1323 	FILE		*master;
1324 	char		newdir[MaxFileNameLen];
1325 	char		*colon;
1326 	int		len;
1327 	int		masterfd;
1328 	int		ptmpfd;
1329 	int		rval;
1330 
1331 	if (!valid_login(newlogin)) {
1332 		errx(EXIT_FAILURE, "`%s' is not a valid login name", login_name);
1333 	}
1334 	if ((pwp = getpwnam(login_name)) == NULL) {
1335 		errx(EXIT_FAILURE, "No such user `%s'", login_name);
1336 	}
1337 	if (!is_local(login_name, _PATH_MASTERPASSWD)) {
1338 		errx(EXIT_FAILURE, "User `%s' must be a local user", login_name);
1339 	}
1340 	/* keep dir name in case we need it for '-m' */
1341 	homedir = pwp->pw_dir;
1342 
1343 	if ((masterfd = open(_PATH_MASTERPASSWD, O_RDONLY)) < 0) {
1344 		err(EXIT_FAILURE, "can't open `%s'", _PATH_MASTERPASSWD);
1345 	}
1346 	if (flock(masterfd, LOCK_EX | LOCK_NB) < 0) {
1347 		err(EXIT_FAILURE, "can't lock `%s'", _PATH_MASTERPASSWD);
1348 	}
1349 	pw_init();
1350 	if ((ptmpfd = pw_lock(WAITSECS)) < 0) {
1351 		(void) close(masterfd);
1352 		err(EXIT_FAILURE, "can't obtain pw_lock");
1353 	}
1354 	if ((master = fdopen(masterfd, "r")) == NULL) {
1355 		(void) close(masterfd);
1356 		(void) close(ptmpfd);
1357 		pw_abort();
1358 		err(EXIT_FAILURE, "can't fdopen fd for %s", _PATH_MASTERPASSWD);
1359 	}
1360 	if (up != NULL) {
1361 		if (up->u_flags & F_USERNAME) {
1362 			/* if changing name, check new name isn't already in use */
1363 			if (strcmp(login_name, newlogin) != 0 && getpwnam(newlogin) != NULL) {
1364 				(void) close(ptmpfd);
1365 				pw_abort();
1366 				errx(EXIT_FAILURE, "already a `%s' user", newlogin);
1367 			}
1368 			pwp->pw_name = newlogin;
1369 
1370 			/*
1371 			 * Provide a new directory name in case the
1372 			 * home directory is to be moved.
1373 			 */
1374 			if (up->u_flags & F_MKDIR) {
1375 				(void) snprintf(newdir, sizeof(newdir),
1376 				    "%s/%s", up->u_basedir, newlogin);
1377 				pwp->pw_dir = newdir;
1378 			}
1379 		}
1380 		if (up->u_flags & F_PASSWORD) {
1381 			if (up->u_password != NULL) {
1382 				if (!valid_password_length(up->u_password)) {
1383 					(void) close(ptmpfd);
1384 					pw_abort();
1385 					errx(EXIT_FAILURE, "Invalid password: `%s'",
1386 						up->u_password);
1387 				}
1388 				pwp->pw_passwd = up->u_password;
1389 			}
1390 		}
1391 		if (up->u_flags & F_UID) {
1392 			/* check uid isn't already allocated */
1393 			if (!(up->u_flags & F_DUPUID) && getpwuid((uid_t)(up->u_uid)) != NULL) {
1394 				(void) close(ptmpfd);
1395 				pw_abort();
1396 				errx(EXIT_FAILURE, "uid %u is already in use", up->u_uid);
1397 			}
1398 			pwp->pw_uid = up->u_uid;
1399 		}
1400 		if (up->u_flags & F_GROUP) {
1401 			/* if -g=uid was specified, check gid is unused */
1402 			if (strcmp(up->u_primgrp, "=uid") == 0) {
1403 				if (getgrgid((gid_t)(up->u_uid)) != NULL) {
1404 					(void) close(ptmpfd);
1405 					pw_abort();
1406 					errx(EXIT_FAILURE, "gid %u is already in use", up->u_uid);
1407 				}
1408 				pwp->pw_gid = up->u_uid;
1409 			} else if ((grp = getgrnam(up->u_primgrp)) != NULL) {
1410 				pwp->pw_gid = grp->gr_gid;
1411 			} else if (is_number(up->u_primgrp) &&
1412 				   (grp = getgrgid((gid_t)atoi(up->u_primgrp))) != NULL) {
1413 				pwp->pw_gid = grp->gr_gid;
1414 			} else {
1415 				(void) close(ptmpfd);
1416 				pw_abort();
1417 				errx(EXIT_FAILURE, "group %s not found", up->u_primgrp);
1418 			}
1419 		}
1420 		if (up->u_flags & F_INACTIVE) {
1421 			if (!scantime(&pwp->pw_change, up->u_inactive)) {
1422 				warnx("Warning: inactive time `%s' invalid, password expiry off",
1423 					up->u_inactive);
1424 			}
1425 		}
1426 		if (up->u_flags & F_EXPIRE) {
1427 			if (!scantime(&pwp->pw_expire, up->u_expire)) {
1428 				warnx("Warning: expire time `%s' invalid, account expiry off",
1429 					up->u_expire);
1430 			}
1431 		}
1432 		if (up->u_flags & F_COMMENT)
1433 			pwp->pw_gecos = up->u_comment;
1434 		if (up->u_flags & F_HOMEDIR)
1435 			pwp->pw_dir = up->u_home;
1436 		if (up->u_flags & F_SHELL)
1437 			pwp->pw_shell = up->u_shell;
1438 #ifdef EXTENSIONS
1439 		if (up->u_flags & F_CLASS) {
1440 			if (!valid_class(up->u_class)) {
1441 				(void) close(ptmpfd);
1442 				pw_abort();
1443 				errx(EXIT_FAILURE,
1444 				    "No such login class `%s'", up->u_class);
1445 			}
1446 			pwp->pw_class = up->u_class;
1447 		}
1448 #endif
1449 	}
1450 	loginc = strlen(login_name);
1451 	while (fgets(buf, sizeof(buf), master) != NULL) {
1452 		if ((colon = strchr(buf, ':')) == NULL) {
1453 			warnx("Malformed entry `%s'. Skipping", buf);
1454 			continue;
1455 		}
1456 		colonc = (size_t)(colon - buf);
1457 		if (strncmp(login_name, buf, loginc) == 0 && loginc == colonc) {
1458 			if (up != NULL) {
1459 				if ((len = snprintf(buf, sizeof(buf),
1460 				    "%s:%s:%d:%d:%s:%ld:%ld:%s:%s:%s\n",
1461 				    newlogin,
1462 				    pwp->pw_passwd,
1463 				    pwp->pw_uid,
1464 				    pwp->pw_gid,
1465 #ifdef EXTENSIONS
1466 				    pwp->pw_class,
1467 #else
1468 				    "",
1469 #endif
1470 				    (long)pwp->pw_change,
1471 				    (long)pwp->pw_expire,
1472 				    pwp->pw_gecos,
1473 				    pwp->pw_dir,
1474 				    pwp->pw_shell)) >= sizeof(buf) || len < 0 ||
1475 				    len + expand_len(pwp->pw_gecos, newlogin)
1476 				    >= 1023) {
1477 					(void) close(ptmpfd);
1478 					pw_abort();
1479 					errx(EXIT_FAILURE, "can't add `%s', "
1480 					    "line too long (%d bytes)", buf,
1481 					    len + expand_len(pwp->pw_gecos,
1482 					    newlogin));
1483 				}
1484 				if (write(ptmpfd, buf, len) != len) {
1485 					(void) close(ptmpfd);
1486 					pw_abort();
1487 					err(EXIT_FAILURE, "can't add `%s'", buf);
1488 				}
1489 			}
1490 		} else {
1491 			len = strlen(buf);
1492 			if ((cc = write(ptmpfd, buf, len)) != len) {
1493 				(void) close(masterfd);
1494 				(void) close(ptmpfd);
1495 				pw_abort();
1496 				err(EXIT_FAILURE, "short write to /etc/ptmp (%lld not %lld chars)",
1497 				    (long long)cc, (long long)len);
1498 			}
1499 		}
1500 	}
1501 	if (up != NULL) {
1502 		if ((up->u_flags & F_MKDIR) &&
1503 		    asystem("%s %s %s", MV, homedir, pwp->pw_dir) != 0) {
1504 			(void) close(ptmpfd);
1505 			pw_abort();
1506 			err(EXIT_FAILURE, "can't move `%s' to `%s'",
1507 			    homedir, pwp->pw_dir);
1508 		}
1509 		if (up->u_groupc > 0 &&
1510 		    !append_group(newlogin, up->u_groupc, up->u_groupv)) {
1511 			(void) close(ptmpfd);
1512 			pw_abort();
1513 			errx(EXIT_FAILURE, "can't append `%s' to new groups",
1514 			    newlogin);
1515 		}
1516 	}
1517 	(void) close(ptmpfd);
1518 	if (up != NULL && strcmp(login_name, newlogin) == 0)
1519 		rval = pw_mkdb(login_name, 0);
1520 	else
1521 		rval = pw_mkdb(NULL, 0);
1522 	if (rval == -1) {
1523 		pw_abort();
1524 		err(EXIT_FAILURE, "pw_mkdb failed");
1525 	}
1526 	if (up == NULL) {
1527 		syslog(LOG_INFO, "user removed: name=%s", login_name);
1528 	} else if (strcmp(login_name, newlogin) == 0) {
1529 		syslog(LOG_INFO, "user information modified: name=%s, uid=%d, gid=%d, home=%s, shell=%s",
1530 			login_name, pwp->pw_uid, pwp->pw_gid, pwp->pw_dir, pwp->pw_shell);
1531 	} else {
1532 		syslog(LOG_INFO, "user information modified: name=%s, new name=%s, uid=%d, gid=%d, home=%s, shell=%s",
1533 			login_name, newlogin, pwp->pw_uid, pwp->pw_gid, pwp->pw_dir, pwp->pw_shell);
1534 	}
1535 	return 1;
1536 }
1537 
1538 
1539 #ifdef EXTENSIONS
1540 /* see if we can find out the user struct */
1541 static struct passwd *
1542 find_user_info(char *name)
1543 {
1544 	struct passwd	*pwp;
1545 
1546 	if ((pwp = getpwnam(name)) != NULL) {
1547 		return pwp;
1548 	}
1549 	if (is_number(name) && (pwp = getpwuid((uid_t)atoi(name))) != NULL) {
1550 		return pwp;
1551 	}
1552 	return NULL;
1553 }
1554 #endif
1555 
1556 #ifdef EXTENSIONS
1557 /* see if we can find out the group struct */
1558 static struct group *
1559 find_group_info(char *name)
1560 {
1561 	struct group	*grp;
1562 
1563 	if ((grp = getgrnam(name)) != NULL) {
1564 		return grp;
1565 	}
1566 	if (is_number(name) && (grp = getgrgid((gid_t)atoi(name))) != NULL) {
1567 		return grp;
1568 	}
1569 	return NULL;
1570 }
1571 #endif
1572 
1573 /* print out usage message, and then exit */
1574 void
1575 usermgmt_usage(const char *prog)
1576 {
1577 	if (strcmp(prog, "useradd") == 0) {
1578 		(void) fprintf(stderr, "usage: %s -D [-b basedir] [-e expiry] "
1579 		    "[-f changetime] [-g group]\n\t\t[-k skeletondir] "
1580 		    "[-r low..high] [-s shell] [-L class]\n", prog);
1581 		(void) fprintf(stderr, "usage: %s [-mov] [-G group[,group,...]]"
1582 		    " [-b basedir] [-c comment]\n\t\t"
1583 		    "[-d homedir] [-e expiry] [-f changetime] [-g group]\n\t\t"
1584 		    "[-k skeletondir] [-p password] "
1585 		    "[-r lowuid..highuid]\n\t\t[-s shell] [-u uid] [-L class] "
1586 		    "user\n", prog);
1587 	} else if (strcmp(prog, "usermod") == 0) {
1588 		(void) fprintf(stderr, "usage: %s [-mov] [-G group[,group,...]]"
1589 		    " [-c comment] [-d homedir]\n\t\t"
1590 		    "[-e expire] [-f changetime] [-g group] [-l newname]\n\t\t"
1591 		    "[-p password] [-s shell] [-u uid] [-L class] user\n",
1592 		    prog);
1593 	} else if (strcmp(prog, "userdel") == 0) {
1594 		(void) fprintf(stderr, "usage: %s -D [-p preserve]\n", prog);
1595 		(void) fprintf(stderr, "usage: %s [-prv] user\n", prog);
1596 #ifdef EXTENSIONS
1597 	} else if (strcmp(prog, "userinfo") == 0) {
1598 		(void) fprintf(stderr, "usage: %s [-ev] user\n", prog);
1599 #endif
1600 	} else if (strcmp(prog, "groupadd") == 0) {
1601 		(void) fprintf(stderr, "usage: %s [-ov] [-g gid] group\n",
1602 		    prog);
1603 	} else if (strcmp(prog, "groupdel") == 0) {
1604 		(void) fprintf(stderr, "usage: %s [-v] group\n", prog);
1605 	} else if (strcmp(prog, "groupmod") == 0) {
1606 		(void) fprintf(stderr, "usage: %s [-ov] [-g gid] [-n newname] "
1607 		    "group\n", prog);
1608 	} else if (strcmp(prog, "user") == 0 || strcmp(prog, "group") == 0) {
1609 		(void) fprintf(stderr, "usage: %s [ add | del | mod "
1610 #ifdef EXTENSIONS
1611 		"| info "
1612 #endif
1613 		"] ...\n",
1614 		    prog);
1615 #ifdef EXTENSIONS
1616 	} else if (strcmp(prog, "groupinfo") == 0) {
1617 		(void) fprintf(stderr, "usage: %s [-ev] group\n", prog);
1618 #endif
1619 	} else {
1620 		(void) fprintf(stderr, "This program must be called as {user,group}{add,del,mod,info},\n%s is not an understood name.\n", prog);
1621 	}
1622 	exit(EXIT_FAILURE);
1623 	/* NOTREACHED */
1624 }
1625 
1626 #ifdef EXTENSIONS
1627 #define ADD_OPT_EXTENSIONS	"p:r:vL:"
1628 #else
1629 #define ADD_OPT_EXTENSIONS
1630 #endif
1631 
1632 int
1633 useradd(int argc, char **argv)
1634 {
1635 	user_t	u;
1636 	int	defaultfield;
1637 	int	bigD;
1638 	int	c;
1639 #ifdef EXTENSIONS
1640 	int	i;
1641 #endif
1642 
1643 	(void) memset(&u, 0, sizeof(u));
1644 	read_defaults(&u);
1645 	u.u_uid = UID_MAX;
1646 	defaultfield = bigD = 0;
1647 	while ((c = getopt(argc, argv, "DG:b:c:d:e:f:g:k:mou:s:" ADD_OPT_EXTENSIONS)) != -1) {
1648 		switch(c) {
1649 		case 'D':
1650 			bigD = 1;
1651 			break;
1652 		case 'G':
1653 			while ((u.u_groupv[u.u_groupc] = strsep(&optarg, ",")) != NULL &&
1654 			    u.u_groupc < NGROUPS_MAX - 2) {
1655 				if (u.u_groupv[u.u_groupc][0] != 0) {
1656 					u.u_groupc++;
1657 				}
1658 			}
1659 			if (optarg != NULL) {
1660 				warnx("Truncated list of secondary groups to %d entries", NGROUPS_MAX - 2);
1661 			}
1662 			break;
1663 		case 'b':
1664 			defaultfield = 1;
1665 			memsave(&u.u_basedir, optarg, strlen(optarg));
1666 			break;
1667 		case 'c':
1668 			memsave(&u.u_comment, optarg, strlen(optarg));
1669 			break;
1670 		case 'd':
1671 			memsave(&u.u_home, optarg, strlen(optarg));
1672 			u.u_flags |= F_HOMEDIR;
1673 			break;
1674 		case 'e':
1675 			defaultfield = 1;
1676 			memsave(&u.u_expire, optarg, strlen(optarg));
1677 			break;
1678 		case 'f':
1679 			defaultfield = 1;
1680 			memsave(&u.u_inactive, optarg, strlen(optarg));
1681 			break;
1682 		case 'g':
1683 			defaultfield = 1;
1684 			memsave(&u.u_primgrp, optarg, strlen(optarg));
1685 			break;
1686 		case 'k':
1687 			defaultfield = 1;
1688 			memsave(&u.u_skeldir, optarg, strlen(optarg));
1689 			break;
1690 #ifdef EXTENSIONS
1691 		case 'L':
1692 			defaultfield = 1;
1693 			memsave(&u.u_class, optarg, strlen(optarg));
1694 			break;
1695 #endif
1696 		case 'm':
1697 			u.u_flags |= F_MKDIR;
1698 			break;
1699 		case 'o':
1700 			u.u_flags |= F_DUPUID;
1701 			break;
1702 #ifdef EXTENSIONS
1703 		case 'p':
1704 			memsave(&u.u_password, optarg, strlen(optarg));
1705 			memset(optarg, 'X', strlen(optarg));
1706 			break;
1707 #endif
1708 #ifdef EXTENSIONS
1709 		case 'r':
1710 			defaultfield = 1;
1711 			(void) save_range(&u, optarg);
1712 			break;
1713 #endif
1714 		case 's':
1715 			defaultfield = 1;
1716 			memsave(&u.u_shell, optarg, strlen(optarg));
1717 			break;
1718 		case 'u':
1719 			if (!is_number(optarg)) {
1720 				errx(EXIT_FAILURE, "When using [-u uid], the uid must be numeric");
1721 			}
1722 			u.u_uid = atoi(optarg);
1723 			break;
1724 #ifdef EXTENSIONS
1725 		case 'v':
1726 			verbose = 1;
1727 			break;
1728 #endif
1729 		default:
1730 			usermgmt_usage("useradd");
1731 			/* NOTREACHED */
1732 		}
1733 	}
1734 	if (bigD) {
1735 		if (defaultfield) {
1736 			checkeuid();
1737 			return setdefaults(&u) ? EXIT_SUCCESS : EXIT_FAILURE;
1738 		}
1739 		(void) printf("group\t\t%s\n", u.u_primgrp);
1740 		(void) printf("base_dir\t%s\n", u.u_basedir);
1741 		(void) printf("skel_dir\t%s\n", u.u_skeldir);
1742 		(void) printf("shell\t\t%s\n", u.u_shell);
1743 #ifdef EXTENSIONS
1744 		(void) printf("class\t\t%s\n", u.u_class);
1745 #endif
1746 		(void) printf("inactive\t%s\n", (u.u_inactive == NULL) ? UNSET_INACTIVE : u.u_inactive);
1747 		(void) printf("expire\t\t%s\n", (u.u_expire == NULL) ? UNSET_EXPIRY : u.u_expire);
1748 #ifdef EXTENSIONS
1749 		for (i = 0 ; i < u.u_rc ; i++) {
1750 			(void) printf("range\t\t%d..%d\n", u.u_rv[i].r_from, u.u_rv[i].r_to);
1751 		}
1752 #endif
1753 		return EXIT_SUCCESS;
1754 	}
1755 	argc -= optind;
1756 	argv += optind;
1757 	if (argc != 1) {
1758 		usermgmt_usage("useradd");
1759 	}
1760 	checkeuid();
1761 	openlog("useradd", LOG_PID, LOG_USER);
1762 	return adduser(*argv, &u) ? EXIT_SUCCESS : EXIT_FAILURE;
1763 }
1764 
1765 #ifdef EXTENSIONS
1766 #define MOD_OPT_EXTENSIONS	"p:vL:"
1767 #else
1768 #define MOD_OPT_EXTENSIONS
1769 #endif
1770 
1771 int
1772 usermod(int argc, char **argv)
1773 {
1774 	user_t	u;
1775 	char	newuser[MaxUserNameLen + 1];
1776 	int	c, have_new_user;
1777 
1778 	(void) memset(&u, 0, sizeof(u));
1779 	(void) memset(newuser, 0, sizeof(newuser));
1780 	read_defaults(&u);
1781 	free(u.u_primgrp);
1782 	u.u_primgrp = NULL;
1783 	have_new_user = 0;
1784 	while ((c = getopt(argc, argv, "G:c:d:e:f:g:l:mos:u:" MOD_OPT_EXTENSIONS)) != -1) {
1785 		switch(c) {
1786 		case 'G':
1787 			while ((u.u_groupv[u.u_groupc] = strsep(&optarg, ",")) != NULL &&
1788 			    u.u_groupc < NGROUPS_MAX - 2) {
1789 				if (u.u_groupv[u.u_groupc][0] != 0) {
1790 					u.u_groupc++;
1791 				}
1792 			}
1793 			if (optarg != NULL) {
1794 			  	warnx("Truncated list of secondary groups to %d entries", NGROUPS_MAX - 2);
1795 			}
1796 			u.u_flags |= F_SECGROUP;
1797 			break;
1798 		case 'c':
1799 			memsave(&u.u_comment, optarg, strlen(optarg));
1800 			u.u_flags |= F_COMMENT;
1801 			break;
1802 		case 'd':
1803 			memsave(&u.u_home, optarg, strlen(optarg));
1804 			u.u_flags |= F_HOMEDIR;
1805 			break;
1806 		case 'e':
1807 			memsave(&u.u_expire, optarg, strlen(optarg));
1808 			u.u_flags |= F_EXPIRE;
1809 			break;
1810 		case 'f':
1811 			memsave(&u.u_inactive, optarg, strlen(optarg));
1812 			u.u_flags |= F_INACTIVE;
1813 			break;
1814 		case 'g':
1815 			memsave(&u.u_primgrp, optarg, strlen(optarg));
1816 			u.u_flags |= F_GROUP;
1817 			break;
1818 		case 'l':
1819 			if (strlcpy(newuser, optarg, sizeof(newuser)) >=
1820 			    sizeof(newuser))
1821 				errx(EXIT_FAILURE, "username `%s' too long",
1822 				    optarg);
1823 			have_new_user = 1;
1824 			u.u_flags |= F_USERNAME;
1825 			break;
1826 #ifdef EXTENSIONS
1827 		case 'L':
1828 			memsave(&u.u_class, optarg, strlen(optarg));
1829 			u.u_flags |= F_CLASS;
1830 			break;
1831 #endif
1832 		case 'm':
1833 			u.u_flags |= F_MKDIR;
1834 			break;
1835 		case 'o':
1836 			u.u_flags |= F_DUPUID;
1837 			break;
1838 #ifdef EXTENSIONS
1839 		case 'p':
1840 			memsave(&u.u_password, optarg, strlen(optarg));
1841 			memset(optarg, 'X', strlen(optarg));
1842 			u.u_flags |= F_PASSWORD;
1843 			break;
1844 #endif
1845 		case 's':
1846 			memsave(&u.u_shell, optarg, strlen(optarg));
1847 			u.u_flags |= F_SHELL;
1848 			break;
1849 		case 'u':
1850 			if (!is_number(optarg)) {
1851 				errx(EXIT_FAILURE, "When using [-u uid], the uid must be numeric");
1852 			}
1853 			u.u_uid = atoi(optarg);
1854 			u.u_flags |= F_UID;
1855 			break;
1856 #ifdef EXTENSIONS
1857 		case 'v':
1858 			verbose = 1;
1859 			break;
1860 #endif
1861 		default:
1862 			usermgmt_usage("usermod");
1863 			/* NOTREACHED */
1864 		}
1865 	}
1866 	if ((u.u_flags & F_MKDIR) && !(u.u_flags & F_HOMEDIR) &&
1867 	    !(u.u_flags & F_USERNAME)) {
1868 		warnx("option 'm' useless without 'd' or 'l' -- ignored");
1869 		u.u_flags &= ~F_MKDIR;
1870 	}
1871 	argc -= optind;
1872 	argv += optind;
1873 	if (argc != 1) {
1874 		usermgmt_usage("usermod");
1875 	}
1876 	checkeuid();
1877 	openlog("usermod", LOG_PID, LOG_USER);
1878 	return moduser(*argv, (have_new_user) ? newuser : *argv, &u) ?
1879 	    EXIT_SUCCESS : EXIT_FAILURE;
1880 }
1881 
1882 #ifdef EXTENSIONS
1883 #define DEL_OPT_EXTENSIONS	"Dp:v"
1884 #else
1885 #define DEL_OPT_EXTENSIONS
1886 #endif
1887 
1888 int
1889 userdel(int argc, char **argv)
1890 {
1891 	struct passwd	*pwp;
1892 	user_t		u;
1893 	char		password[PasswordLength + 1];
1894 	int		defaultfield;
1895 	int		rmhome;
1896 	int		bigD;
1897 	int		c;
1898 
1899 	(void) memset(&u, 0, sizeof(u));
1900 	read_defaults(&u);
1901 	defaultfield = bigD = rmhome = 0;
1902 	while ((c = getopt(argc, argv, "r" DEL_OPT_EXTENSIONS)) != -1) {
1903 		switch(c) {
1904 #ifdef EXTENSIONS
1905 		case 'D':
1906 			bigD = 1;
1907 			break;
1908 #endif
1909 #ifdef EXTENSIONS
1910 		case 'p':
1911 			defaultfield = 1;
1912 			u.u_preserve = (strcmp(optarg, "true") == 0) ? 1 :
1913 					(strcmp(optarg, "yes") == 0) ? 1 :
1914 					 atoi(optarg);
1915 			break;
1916 #endif
1917 		case 'r':
1918 			rmhome = 1;
1919 			break;
1920 #ifdef EXTENSIONS
1921 		case 'v':
1922 			verbose = 1;
1923 			break;
1924 #endif
1925 		default:
1926 			usermgmt_usage("userdel");
1927 			/* NOTREACHED */
1928 		}
1929 	}
1930 #ifdef EXTENSIONS
1931 	if (bigD) {
1932 		if (defaultfield) {
1933 			checkeuid();
1934 			return setdefaults(&u) ? EXIT_SUCCESS : EXIT_FAILURE;
1935 		}
1936 		(void) printf("preserve\t%s\n", (u.u_preserve) ? "true" : "false");
1937 		return EXIT_SUCCESS;
1938 	}
1939 #endif
1940 	argc -= optind;
1941 	argv += optind;
1942 	if (argc != 1) {
1943 		usermgmt_usage("userdel");
1944 	}
1945 	checkeuid();
1946 	if ((pwp = getpwnam(*argv)) == NULL) {
1947 		warnx("No such user `%s'", *argv);
1948 		return EXIT_FAILURE;
1949 	}
1950 	if (rmhome)
1951 		(void)removehomedir(pwp->pw_name, pwp->pw_uid, pwp->pw_dir);
1952 	if (u.u_preserve) {
1953 		u.u_flags |= F_SHELL;
1954 		memsave(&u.u_shell, NOLOGIN, strlen(NOLOGIN));
1955 		(void) memset(password, '*', DES_Len);
1956 		password[DES_Len] = 0;
1957 		memsave(&u.u_password, password, strlen(password));
1958 		u.u_flags |= F_PASSWORD;
1959 		openlog("userdel", LOG_PID, LOG_USER);
1960 		return moduser(*argv, *argv, &u) ? EXIT_SUCCESS : EXIT_FAILURE;
1961 	}
1962 	if (!rm_user_from_groups(*argv)) {
1963 		return 0;
1964 	}
1965 	openlog("userdel", LOG_PID, LOG_USER);
1966 	return moduser(*argv, *argv, NULL) ? EXIT_SUCCESS : EXIT_FAILURE;
1967 }
1968 
1969 #ifdef EXTENSIONS
1970 #define GROUP_ADD_OPT_EXTENSIONS	"v"
1971 #else
1972 #define GROUP_ADD_OPT_EXTENSIONS
1973 #endif
1974 
1975 /* add a group */
1976 int
1977 groupadd(int argc, char **argv)
1978 {
1979 	int	dupgid;
1980 	int	gid;
1981 	int	c;
1982 
1983 	gid = GID_MAX;
1984 	dupgid = 0;
1985 	while ((c = getopt(argc, argv, "g:o" GROUP_ADD_OPT_EXTENSIONS)) != -1) {
1986 		switch(c) {
1987 		case 'g':
1988 			if (!is_number(optarg)) {
1989 				errx(EXIT_FAILURE, "When using [-g gid], the gid must be numeric");
1990 			}
1991 			gid = atoi(optarg);
1992 			break;
1993 		case 'o':
1994 			dupgid = 1;
1995 			break;
1996 #ifdef EXTENSIONS
1997 		case 'v':
1998 			verbose = 1;
1999 			break;
2000 #endif
2001 		default:
2002 			usermgmt_usage("groupadd");
2003 			/* NOTREACHED */
2004 		}
2005 	}
2006 	argc -= optind;
2007 	argv += optind;
2008 	if (argc != 1) {
2009 		usermgmt_usage("groupadd");
2010 	}
2011 	checkeuid();
2012 	if (!valid_group(*argv)) {
2013 		errx(EXIT_FAILURE, "invalid group name `%s'", *argv);
2014 	}
2015 	if (gid < 0 && !getnextgid(&gid, LowGid, HighGid)) {
2016 		errx(EXIT_FAILURE, "can't add group: can't get next gid");
2017 	}
2018 	if (!dupgid && getgrgid((gid_t) gid) != NULL) {
2019 		errx(EXIT_FAILURE, "can't add group: gid %d is a duplicate", gid);
2020 	}
2021 	openlog("groupadd", LOG_PID, LOG_USER);
2022 	if (!creategid(*argv, gid, "")) {
2023 		errx(EXIT_FAILURE, "can't add group: problems with %s file",
2024 		    _PATH_GROUP);
2025 	}
2026 	return EXIT_SUCCESS;
2027 }
2028 
2029 #ifdef EXTENSIONS
2030 #define GROUP_DEL_OPT_EXTENSIONS	"v"
2031 #else
2032 #define GROUP_DEL_OPT_EXTENSIONS
2033 #endif
2034 
2035 /* remove a group */
2036 int
2037 groupdel(int argc, char **argv)
2038 {
2039 	int	c;
2040 
2041 	while ((c = getopt(argc, argv, "" GROUP_DEL_OPT_EXTENSIONS)) != -1) {
2042 		switch(c) {
2043 #ifdef EXTENSIONS
2044 		case 'v':
2045 			verbose = 1;
2046 			break;
2047 #endif
2048 		default:
2049 			usermgmt_usage("groupdel");
2050 			/* NOTREACHED */
2051 		}
2052 	}
2053 	argc -= optind;
2054 	argv += optind;
2055 	if (argc != 1) {
2056 		usermgmt_usage("groupdel");
2057 	}
2058 	checkeuid();
2059 	openlog("groupdel", LOG_PID, LOG_USER);
2060 	if (getgrnam(*argv) == NULL) {
2061 		warnx("No such group: `%s'", *argv);
2062 		return EXIT_FAILURE;
2063 	}
2064 	if (!modify_gid(*argv, NULL)) {
2065 		err(EXIT_FAILURE, "can't change %s file", _PATH_GROUP);
2066 	}
2067 	return EXIT_SUCCESS;
2068 }
2069 
2070 #ifdef EXTENSIONS
2071 #define GROUP_MOD_OPT_EXTENSIONS	"v"
2072 #else
2073 #define GROUP_MOD_OPT_EXTENSIONS
2074 #endif
2075 
2076 /* modify a group */
2077 int
2078 groupmod(int argc, char **argv)
2079 {
2080 	struct group	*grp;
2081 	char		buf[LINE_MAX];
2082 	char		*newname;
2083 	char		**cpp;
2084 	int		dupgid;
2085 	int		gid;
2086 	int		cc;
2087 	int		c;
2088 
2089 	gid = GID_MAX;
2090 	dupgid = 0;
2091 	newname = NULL;
2092 	while ((c = getopt(argc, argv, "g:on:" GROUP_MOD_OPT_EXTENSIONS)) != -1) {
2093 		switch(c) {
2094 		case 'g':
2095 			if (!is_number(optarg)) {
2096 				errx(EXIT_FAILURE, "When using [-g gid], the gid must be numeric");
2097 			}
2098 			gid = atoi(optarg);
2099 			break;
2100 		case 'o':
2101 			dupgid = 1;
2102 			break;
2103 		case 'n':
2104 			memsave(&newname, optarg, strlen(optarg));
2105 			break;
2106 #ifdef EXTENSIONS
2107 		case 'v':
2108 			verbose = 1;
2109 			break;
2110 #endif
2111 		default:
2112 			usermgmt_usage("groupmod");
2113 			/* NOTREACHED */
2114 		}
2115 	}
2116 	argc -= optind;
2117 	argv += optind;
2118 	if (argc != 1) {
2119 		usermgmt_usage("groupmod");
2120 	}
2121 	checkeuid();
2122 	if (gid < 0 && newname == NULL) {
2123 		errx(EXIT_FAILURE, "Nothing to change");
2124 	}
2125 	if (dupgid && gid < 0) {
2126 		errx(EXIT_FAILURE, "Duplicate which gid?");
2127 	}
2128 	if ((grp = getgrnam(*argv)) == NULL) {
2129 		errx(EXIT_FAILURE, "can't find group `%s' to modify", *argv);
2130 	}
2131 	if (!is_local(*argv, _PATH_GROUP)) {
2132 		errx(EXIT_FAILURE, "Group `%s' must be a local group", *argv);
2133 	}
2134 	if (newname != NULL && !valid_group(newname)) {
2135 		errx(EXIT_FAILURE, "invalid group name `%s'", newname);
2136 	}
2137 	if ((cc = snprintf(buf, sizeof(buf), "%s:%s:%u:",
2138 	    (newname) ? newname : grp->gr_name, grp->gr_passwd,
2139 	    (gid < 0) ? grp->gr_gid : gid)) >= sizeof(buf) || cc < 0)
2140 		errx(EXIT_FAILURE, "group `%s' entry too long", grp->gr_name);
2141 
2142 	for (cpp = grp->gr_mem ; *cpp ; cpp++) {
2143 		cc = strlcat(buf, *cpp, sizeof(buf)) + 1;
2144 		if (cc >= sizeof(buf))
2145 			errx(EXIT_FAILURE, "group `%s' entry too long",
2146 			    grp->gr_name);
2147 		if (cpp[1] != NULL) {
2148 			buf[cc - 1] = ',';
2149 			buf[cc] = '\0';
2150 		}
2151 	}
2152 	cc = strlcat(buf, "\n", sizeof(buf));
2153 	if (cc >= sizeof(buf))
2154 		errx(EXIT_FAILURE, "group `%s' entry too long", grp->gr_name);
2155 
2156 	openlog("groupmod", LOG_PID, LOG_USER);
2157 	if (!modify_gid(*argv, buf))
2158 		err(EXIT_FAILURE, "can't change %s file", _PATH_GROUP);
2159 	return EXIT_SUCCESS;
2160 }
2161 
2162 #ifdef EXTENSIONS
2163 /* display user information */
2164 int
2165 userinfo(int argc, char **argv)
2166 {
2167 	struct passwd	*pwp;
2168 	struct group	*grp;
2169 	char		**cpp;
2170 	int		exists;
2171 	int		i;
2172 
2173 	exists = 0;
2174 	while ((i = getopt(argc, argv, "ev")) != -1) {
2175 		switch(i) {
2176 		case 'e':
2177 			exists = 1;
2178 			break;
2179 		case 'v':
2180 			verbose = 1;
2181 			break;
2182 		default:
2183 			usermgmt_usage("userinfo");
2184 			/* NOTREACHED */
2185 		}
2186 	}
2187 	argc -= optind;
2188 	argv += optind;
2189 	if (argc != 1) {
2190 		usermgmt_usage("userinfo");
2191 	}
2192 	pwp = find_user_info(*argv);
2193 	if (exists) {
2194 		exit((pwp) ? EXIT_SUCCESS : EXIT_FAILURE);
2195 	}
2196 	if (pwp == NULL) {
2197 		errx(EXIT_FAILURE, "can't find user `%s'", *argv);
2198 	}
2199 	(void) printf("login\t%s\n", pwp->pw_name);
2200 	(void) printf("passwd\t%s\n", pwp->pw_passwd);
2201 	(void) printf("uid\t%u\n", pwp->pw_uid);
2202 	if ((grp = getgrgid(pwp->pw_gid)) == NULL)
2203 		(void) printf("groups\t%u", pwp->pw_gid);
2204 	else
2205 		(void) printf("groups\t%s", grp->gr_name);
2206 	while ((grp = getgrent()) != NULL) {
2207 		for (cpp = grp->gr_mem ; *cpp ; cpp++) {
2208 			if (strcmp(*cpp, pwp->pw_name) == 0 &&
2209 			    grp->gr_gid != pwp->pw_gid)
2210 				(void) printf(" %s", grp->gr_name);
2211 		}
2212 	}
2213 	(void) fputc('\n', stdout);
2214 	(void) printf("change\t%s", pwp->pw_change ? ctime(&pwp->pw_change) : "NEVER\n");
2215 #ifdef EXTENSIONS
2216 	(void) printf("class\t%s\n", pwp->pw_class);
2217 #endif
2218 	(void) printf("gecos\t%s\n", pwp->pw_gecos);
2219 	(void) printf("dir\t%s\n", pwp->pw_dir);
2220 	(void) printf("shell\t%s\n", pwp->pw_shell);
2221 	(void) printf("expire\t%s", pwp->pw_expire ? ctime(&pwp->pw_expire) : "NEVER\n");
2222 	return EXIT_SUCCESS;
2223 }
2224 #endif
2225 
2226 #ifdef EXTENSIONS
2227 /* display user information */
2228 int
2229 groupinfo(int argc, char **argv)
2230 {
2231 	struct group	*grp;
2232 	char		**cpp;
2233 	int		exists;
2234 	int		i;
2235 
2236 	exists = 0;
2237 	while ((i = getopt(argc, argv, "ev")) != -1) {
2238 		switch(i) {
2239 		case 'e':
2240 			exists = 1;
2241 			break;
2242 		case 'v':
2243 			verbose = 1;
2244 			break;
2245 		default:
2246 			usermgmt_usage("groupinfo");
2247 			/* NOTREACHED */
2248 		}
2249 	}
2250 	argc -= optind;
2251 	argv += optind;
2252 	if (argc != 1) {
2253 		usermgmt_usage("groupinfo");
2254 	}
2255 	grp = find_group_info(*argv);
2256 	if (exists) {
2257 		exit((grp) ? EXIT_SUCCESS : EXIT_FAILURE);
2258 	}
2259 	if (grp == NULL) {
2260 		errx(EXIT_FAILURE, "can't find group `%s'", *argv);
2261 	}
2262 	(void) printf("name\t%s\n", grp->gr_name);
2263 	(void) printf("passwd\t%s\n", grp->gr_passwd);
2264 	(void) printf("gid\t%u\n", grp->gr_gid);
2265 	(void) printf("members\t");
2266 	for (cpp = grp->gr_mem ; *cpp ; cpp++) {
2267 		(void) printf("%s ", *cpp);
2268 	}
2269 	(void) fputc('\n', stdout);
2270 	return EXIT_SUCCESS;
2271 }
2272 #endif
2273