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