xref: /freebsd/usr.sbin/pw/pw_user.c (revision f8ea072a542112d5e0e74a2d6ecf75d967c3054c)
1 /*-
2  * Copyright (C) 1996
3  *	David L. Nugent.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY DAVID L. NUGENT AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL DAVID L. NUGENT OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  */
27 
28 #ifndef lint
29 static const char rcsid[] =
30   "$FreeBSD$";
31 #endif /* not lint */
32 
33 #include <ctype.h>
34 #include <err.h>
35 #include <fcntl.h>
36 #include <sys/param.h>
37 #include <dirent.h>
38 #include <paths.h>
39 #include <termios.h>
40 #include <sys/types.h>
41 #include <sys/time.h>
42 #include <sys/resource.h>
43 #include <unistd.h>
44 #include <login_cap.h>
45 #include <pwd.h>
46 #include <grp.h>
47 #include <libutil.h>
48 #include "pw.h"
49 #include "bitmap.h"
50 
51 #define LOGNAMESIZE (MAXLOGNAME-1)
52 
53 static		char locked_str[] = "*LOCKED*";
54 
55 static int      print_user(struct passwd * pwd, int pretty, int v7);
56 static uid_t    pw_uidpolicy(struct userconf * cnf, struct cargs * args);
57 static uid_t    pw_gidpolicy(struct userconf * cnf, struct cargs * args, char *nam, gid_t prefer);
58 static time_t   pw_pwdpolicy(struct userconf * cnf, struct cargs * args);
59 static time_t   pw_exppolicy(struct userconf * cnf, struct cargs * args);
60 static char    *pw_homepolicy(struct userconf * cnf, struct cargs * args, char const * user);
61 static char    *pw_shellpolicy(struct userconf * cnf, struct cargs * args, char *newshell);
62 static char    *pw_password(struct userconf * cnf, struct cargs * args, char const * user);
63 static char    *shell_path(char const * path, char *shells[], char *sh);
64 static void     rmat(uid_t uid);
65 static void     rmopie(char const * name);
66 
67 /*-
68  * -C config      configuration file
69  * -q             quiet operation
70  * -n name        login name
71  * -u uid         user id
72  * -c comment     user name/comment
73  * -d directory   home directory
74  * -e date        account expiry date
75  * -p date        password expiry date
76  * -g grp         primary group
77  * -G grp1,grp2   additional groups
78  * -m [ -k dir ]  create and set up home
79  * -s shell       name of login shell
80  * -o             duplicate uid ok
81  * -L class       user class
82  * -l name        new login name
83  * -h fd          password filehandle
84  * -H fd          encrypted password filehandle
85  * -F             force print or add
86  *   Setting defaults:
87  * -D             set user defaults
88  * -b dir         default home root dir
89  * -e period      default expiry period
90  * -p period      default password change period
91  * -g group       default group
92  * -G             grp1,grp2.. default additional groups
93  * -L class       default login class
94  * -k dir         default home skeleton
95  * -s shell       default shell
96  * -w method      default password method
97  */
98 
99 int
100 pw_user(struct userconf * cnf, int mode, struct cargs * args)
101 {
102 	int	        rc, edited = 0;
103 	char           *p = NULL;
104 	char					 *passtmp;
105 	struct carg    *a_name;
106 	struct carg    *a_uid;
107 	struct carg    *arg;
108 	struct passwd  *pwd = NULL;
109 	struct group   *grp;
110 	struct stat     st;
111 	char            line[_PASSWORD_LEN+1];
112 	FILE	       *fp;
113 	char *dmode_c;
114 	void *set = NULL;
115 
116 	static struct passwd fakeuser =
117 	{
118 		NULL,
119 		"*",
120 		-1,
121 		-1,
122 		0,
123 		"",
124 		"User &",
125 		"/nonexistent",
126 		"/bin/sh",
127 		0
128 #if defined(__FreeBSD__)
129 		,0
130 #endif
131 	};
132 
133 
134 	/*
135 	 * With M_NEXT, we only need to return the
136 	 * next uid to stdout
137 	 */
138 	if (mode == M_NEXT)
139 	{
140 		uid_t next = pw_uidpolicy(cnf, args);
141 		if (getarg(args, 'q'))
142 			return next;
143 		printf("%ld:", (long)next);
144 		pw_group(cnf, mode, args);
145 		return EXIT_SUCCESS;
146 	}
147 
148 	/*
149 	 * We can do all of the common legwork here
150 	 */
151 
152 	if ((arg = getarg(args, 'b')) != NULL) {
153 		cnf->home = arg->val;
154 	}
155 
156 	if ((arg = getarg(args, 'M')) != NULL) {
157 		dmode_c = arg->val;
158 		if ((set = setmode(dmode_c)) == NULL)
159 			errx(EX_DATAERR, "invalid directory creation mode '%s'",
160 			    dmode_c);
161 		cnf->homemode = getmode(set, _DEF_DIRMODE);
162 		free(set);
163 	}
164 
165 	/*
166 	 * If we'll need to use it or we're updating it,
167 	 * then create the base home directory if necessary
168 	 */
169 	if (arg != NULL || getarg(args, 'm') != NULL) {
170 		int	l = strlen(cnf->home);
171 
172 		if (l > 1 && cnf->home[l-1] == '/')	/* Shave off any trailing path delimiter */
173 			cnf->home[--l] = '\0';
174 
175 		if (l < 2 || *cnf->home != '/')		/* Check for absolute path name */
176 			errx(EX_DATAERR, "invalid base directory for home '%s'", cnf->home);
177 
178 		if (stat(cnf->home, &st) == -1) {
179 			char	dbuf[MAXPATHLEN];
180 
181 			/*
182 			 * This is a kludge especially for Joerg :)
183 			 * If the home directory would be created in the root partition, then
184 			 * we really create it under /usr which is likely to have more space.
185 			 * But we create a symlink from cnf->home -> "/usr" -> cnf->home
186 			 */
187 			if (strchr(cnf->home+1, '/') == NULL) {
188 				strcpy(dbuf, "/usr");
189 				strncat(dbuf, cnf->home, MAXPATHLEN-5);
190 				if (mkdir(dbuf, _DEF_DIRMODE) != -1 || errno == EEXIST) {
191 					chown(dbuf, 0, 0);
192 					/*
193 					 * Skip first "/" and create symlink:
194 					 * /home -> usr/home
195 					 */
196 					symlink(dbuf+1, cnf->home);
197 				}
198 				/* If this falls, fall back to old method */
199 			}
200 			strlcpy(dbuf, cnf->home, sizeof(dbuf));
201 			p = dbuf;
202 			if (stat(dbuf, &st) == -1) {
203 				while ((p = strchr(p + 1, '/')) != NULL) {
204 					*p = '\0';
205 					if (stat(dbuf, &st) == -1) {
206 						if (mkdir(dbuf, _DEF_DIRMODE) == -1)
207 							goto direrr;
208 						chown(dbuf, 0, 0);
209 					} else if (!S_ISDIR(st.st_mode))
210 						errx(EX_OSFILE, "'%s' (root home parent) is not a directory", dbuf);
211 					*p = '/';
212 				}
213 			}
214 			if (stat(dbuf, &st) == -1) {
215 				if (mkdir(dbuf, _DEF_DIRMODE) == -1) {
216 				direrr:	err(EX_OSFILE, "mkdir '%s'", dbuf);
217 				}
218 				chown(dbuf, 0, 0);
219 			}
220 		} else if (!S_ISDIR(st.st_mode))
221 			errx(EX_OSFILE, "root home `%s' is not a directory", cnf->home);
222 	}
223 
224 	if ((arg = getarg(args, 'e')) != NULL)
225 		cnf->expire_days = atoi(arg->val);
226 
227 	if ((arg = getarg(args, 'y')) != NULL)
228 		cnf->nispasswd = arg->val;
229 
230 	if ((arg = getarg(args, 'p')) != NULL && arg->val)
231 		cnf->password_days = atoi(arg->val);
232 
233 	if ((arg = getarg(args, 'g')) != NULL) {
234 		if (!*(p = arg->val))	/* Handle empty group list specially */
235 			cnf->default_group = "";
236 		else {
237 			if ((grp = GETGRNAM(p)) == NULL) {
238 				if (!isdigit((unsigned char)*p) || (grp = GETGRGID((gid_t) atoi(p))) == NULL)
239 					errx(EX_NOUSER, "group `%s' does not exist", p);
240 			}
241 			cnf->default_group = newstr(grp->gr_name);
242 		}
243 	}
244 	if ((arg = getarg(args, 'L')) != NULL)
245 		cnf->default_class = pw_checkname((u_char *)arg->val, 0);
246 
247 	if ((arg = getarg(args, 'G')) != NULL && arg->val) {
248 		int i = 0;
249 
250 		for (p = strtok(arg->val, ", \t"); p != NULL; p = strtok(NULL, ", \t")) {
251 			if ((grp = GETGRNAM(p)) == NULL) {
252 				if (!isdigit((unsigned char)*p) || (grp = GETGRGID((gid_t) atoi(p))) == NULL)
253 					errx(EX_NOUSER, "group `%s' does not exist", p);
254 			}
255 			if (extendarray(&cnf->groups, &cnf->numgroups, i + 2) != -1)
256 				cnf->groups[i++] = newstr(grp->gr_name);
257 		}
258 		while (i < cnf->numgroups)
259 			cnf->groups[i++] = NULL;
260 	}
261 
262 	if ((arg = getarg(args, 'k')) != NULL) {
263 		if (stat(cnf->dotdir = arg->val, &st) == -1 || !S_ISDIR(st.st_mode))
264 			errx(EX_OSFILE, "skeleton `%s' is not a directory or does not exist", cnf->dotdir);
265 	}
266 
267 	if ((arg = getarg(args, 's')) != NULL)
268 		cnf->shell_default = arg->val;
269 
270 	if ((arg = getarg(args, 'w')) != NULL)
271 		cnf->default_password = boolean_val(arg->val, cnf->default_password);
272 	if (mode == M_ADD && getarg(args, 'D')) {
273 		if (getarg(args, 'n') != NULL)
274 			errx(EX_DATAERR, "can't combine `-D' with `-n name'");
275 		if ((arg = getarg(args, 'u')) != NULL && (p = strtok(arg->val, ", \t")) != NULL) {
276 			if ((cnf->min_uid = (uid_t) atoi(p)) == 0)
277 				cnf->min_uid = 1000;
278 			if ((p = strtok(NULL, " ,\t")) == NULL || (cnf->max_uid = (uid_t) atoi(p)) < cnf->min_uid)
279 				cnf->max_uid = 32000;
280 		}
281 		if ((arg = getarg(args, 'i')) != NULL && (p = strtok(arg->val, ", \t")) != NULL) {
282 			if ((cnf->min_gid = (gid_t) atoi(p)) == 0)
283 				cnf->min_gid = 1000;
284 			if ((p = strtok(NULL, " ,\t")) == NULL || (cnf->max_gid = (gid_t) atoi(p)) < cnf->min_gid)
285 				cnf->max_gid = 32000;
286 		}
287 
288 		arg = getarg(args, 'C');
289 		if (write_userconfig(arg ? arg->val : NULL))
290 			return EXIT_SUCCESS;
291 		warn("config update");
292 		return EX_IOERR;
293 	}
294 
295 	if (mode == M_PRINT && getarg(args, 'a')) {
296 		int             pretty = getarg(args, 'P') != NULL;
297 		int		v7 = getarg(args, '7') != NULL;
298 		SETPWENT();
299 		while ((pwd = GETPWENT()) != NULL)
300 			print_user(pwd, pretty, v7);
301 		ENDPWENT();
302 		return EXIT_SUCCESS;
303 	}
304 
305 	if ((a_name = getarg(args, 'n')) != NULL)
306 		pwd = GETPWNAM(pw_checkname((u_char *)a_name->val, 0));
307 	a_uid = getarg(args, 'u');
308 
309 	if (a_uid == NULL) {
310 		if (a_name == NULL)
311 			errx(EX_DATAERR, "user name or id required");
312 
313 		/*
314 		 * Determine whether 'n' switch is name or uid - we don't
315 		 * really don't really care which we have, but we need to
316 		 * know.
317 		 */
318 		if (mode != M_ADD && pwd == NULL
319 		    && strspn(a_name->val, "0123456789") == strlen(a_name->val)
320 		    && *a_name->val) {
321 			(a_uid = a_name)->ch = 'u';
322 			a_name = NULL;
323 		}
324 	}
325 
326 	/*
327 	 * Update, delete & print require that the user exists
328 	 */
329 	if (mode == M_UPDATE || mode == M_DELETE ||
330 	    mode == M_PRINT  || mode == M_LOCK   || mode == M_UNLOCK) {
331 
332 		if (a_name == NULL && pwd == NULL)	/* Try harder */
333 			pwd = GETPWUID(atoi(a_uid->val));
334 
335 		if (pwd == NULL) {
336 			if (mode == M_PRINT && getarg(args, 'F')) {
337 				fakeuser.pw_name = a_name ? a_name->val : "nouser";
338 				fakeuser.pw_uid = a_uid ? (uid_t) atol(a_uid->val) : -1;
339 				return print_user(&fakeuser,
340 						  getarg(args, 'P') != NULL,
341 						  getarg(args, '7') != NULL);
342 			}
343 			if (a_name == NULL)
344 				errx(EX_NOUSER, "no such uid `%s'", a_uid->val);
345 			errx(EX_NOUSER, "no such user `%s'", a_name->val);
346 		}
347 
348 		if (a_name == NULL)	/* May be needed later */
349 			a_name = addarg(args, 'n', newstr(pwd->pw_name));
350 
351 		/*
352 		 * The M_LOCK and M_UNLOCK functions simply add or remove
353 		 * a "*LOCKED*" prefix from in front of the password to
354 		 * prevent it decoding correctly, and therefore prevents
355 		 * access. Of course, this only prevents access via
356 		 * password authentication (not ssh, kerberos or any
357 		 * other method that does not use the UNIX password) but
358 		 * that is a known limitation.
359 		 */
360 
361 		if (mode == M_LOCK) {
362 			if (strncmp(pwd->pw_passwd, locked_str, sizeof(locked_str)-1) == 0)
363 				errx(EX_DATAERR, "user '%s' is already locked", pwd->pw_name);
364 			passtmp = malloc(strlen(pwd->pw_passwd) + sizeof(locked_str));
365 			if (passtmp == NULL)	/* disaster */
366 				errx(EX_UNAVAILABLE, "out of memory");
367 			strcpy(passtmp, locked_str);
368 			strcat(passtmp, pwd->pw_passwd);
369 			pwd->pw_passwd = passtmp;
370 			edited = 1;
371 		} else if (mode == M_UNLOCK) {
372 			if (strncmp(pwd->pw_passwd, locked_str, sizeof(locked_str)-1) != 0)
373 				errx(EX_DATAERR, "user '%s' is not locked", pwd->pw_name);
374 			pwd->pw_passwd += sizeof(locked_str)-1;
375 			edited = 1;
376 		} else if (mode == M_DELETE) {
377 			/*
378 			 * Handle deletions now
379 			 */
380 			char            file[MAXPATHLEN];
381 			char            home[MAXPATHLEN];
382 			uid_t           uid = pwd->pw_uid;
383 
384 			if (strcmp(pwd->pw_name, "root") == 0)
385 				errx(EX_DATAERR, "cannot remove user 'root'");
386 
387 			if (!PWALTDIR()) {
388 				/*
389 				 * Remove opie record from /etc/opiekeys
390 		        	 */
391 
392 				rmopie(pwd->pw_name);
393 
394 				/*
395 				 * Remove crontabs
396 				 */
397 				snprintf(file, sizeof(file), "/var/cron/tabs/%s", pwd->pw_name);
398 				if (access(file, F_OK) == 0) {
399 					sprintf(file, "crontab -u %s -r", pwd->pw_name);
400 					system(file);
401 				}
402 			}
403 			/*
404 			 * Save these for later, since contents of pwd may be
405 			 * invalidated by deletion
406 			 */
407 			sprintf(file, "%s/%s", _PATH_MAILDIR, pwd->pw_name);
408 			strlcpy(home, pwd->pw_dir, sizeof(home));
409 
410 			rc = delpwent(pwd);
411 			if (rc == -1)
412 				err(EX_IOERR, "user '%s' does not exist", pwd->pw_name);
413 			else if (rc != 0) {
414 				warn("passwd update");
415 				return EX_IOERR;
416 			}
417 
418 			if (cnf->nispasswd && *cnf->nispasswd=='/') {
419 				rc = delnispwent(cnf->nispasswd, a_name->val);
420 				if (rc == -1)
421 					warnx("WARNING: user '%s' does not exist in NIS passwd", pwd->pw_name);
422 				else if (rc != 0)
423 					warn("WARNING: NIS passwd update");
424 				/* non-fatal */
425 			}
426 
427 			grp = GETGRNAM(a_name->val);
428 			if (grp != NULL && *grp->gr_mem == NULL)
429 				delgrent(GETGRNAM(a_name->val));
430 			SETGRENT();
431 			while ((grp = GETGRENT()) != NULL) {
432 				int i;
433 				char group[MAXLOGNAME];
434 				for (i = 0; grp->gr_mem[i] != NULL; i++) {
435 					if (!strcmp(grp->gr_mem[i], a_name->val)) {
436 						while (grp->gr_mem[i] != NULL) {
437 							grp->gr_mem[i] = grp->gr_mem[i+1];
438 						}
439 						strlcpy(group, grp->gr_name, MAXLOGNAME);
440 						chggrent(group, grp);
441 					}
442 				}
443 			}
444 			ENDGRENT();
445 
446 			pw_log(cnf, mode, W_USER, "%s(%ld) account removed", a_name->val, (long) uid);
447 
448 			if (!PWALTDIR()) {
449 				/*
450 				 * Remove mail file
451 				 */
452 				remove(file);
453 
454 				/*
455 				 * Remove at jobs
456 				 */
457 				if (getpwuid(uid) == NULL)
458 					rmat(uid);
459 
460 				/*
461 				 * Remove home directory and contents
462 				 */
463 				if (getarg(args, 'r') != NULL && *home == '/' && getpwuid(uid) == NULL) {
464 					if (stat(home, &st) != -1) {
465 						rm_r(home, uid);
466 						pw_log(cnf, mode, W_USER, "%s(%ld) home '%s' %sremoved",
467 						       a_name->val, (long) uid, home,
468 						       stat(home, &st) == -1 ? "" : "not completely ");
469 					}
470 				}
471 			}
472 			return EXIT_SUCCESS;
473 		} else if (mode == M_PRINT)
474 			return print_user(pwd,
475 					  getarg(args, 'P') != NULL,
476 					  getarg(args, '7') != NULL);
477 
478 		/*
479 		 * The rest is edit code
480 		 */
481 		if ((arg = getarg(args, 'l')) != NULL) {
482 			if (strcmp(pwd->pw_name, "root") == 0)
483 				errx(EX_DATAERR, "can't rename `root' account");
484 			pwd->pw_name = pw_checkname((u_char *)arg->val, 0);
485 			edited = 1;
486 		}
487 
488 		if ((arg = getarg(args, 'u')) != NULL && isdigit((unsigned char)*arg->val)) {
489 			pwd->pw_uid = (uid_t) atol(arg->val);
490 			edited = 1;
491 			if (pwd->pw_uid != 0 && strcmp(pwd->pw_name, "root") == 0)
492 				errx(EX_DATAERR, "can't change uid of `root' account");
493 			if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
494 				warnx("WARNING: account `%s' will have a uid of 0 (superuser access!)", pwd->pw_name);
495 		}
496 
497 		if ((arg = getarg(args, 'g')) != NULL && pwd->pw_uid != 0) {	/* Already checked this */
498 			gid_t newgid = (gid_t) GETGRNAM(cnf->default_group)->gr_gid;
499 			if (newgid != pwd->pw_gid) {
500 				edited = 1;
501 				pwd->pw_gid = newgid;
502 			}
503 		}
504 
505 		if ((arg = getarg(args, 'p')) != NULL) {
506 			if (*arg->val == '\0' || strcmp(arg->val, "0") == 0) {
507 				if (pwd->pw_change != 0) {
508 					pwd->pw_change = 0;
509 					edited = 1;
510 				}
511 			}
512 			else {
513 				time_t          now = time(NULL);
514 				time_t          expire = parse_date(now, arg->val);
515 
516 				if (pwd->pw_change != expire) {
517 					pwd->pw_change = expire;
518 					edited = 1;
519 				}
520 			}
521 		}
522 
523 		if ((arg = getarg(args, 'e')) != NULL) {
524 			if (*arg->val == '\0' || strcmp(arg->val, "0") == 0) {
525 				if (pwd->pw_expire != 0) {
526 					pwd->pw_expire = 0;
527 					edited = 1;
528 				}
529 			}
530 			else {
531 				time_t          now = time(NULL);
532 				time_t          expire = parse_date(now, arg->val);
533 
534 				if (pwd->pw_expire != expire) {
535 					pwd->pw_expire = expire;
536 					edited = 1;
537 				}
538 			}
539 		}
540 
541 		if ((arg = getarg(args, 's')) != NULL) {
542 			char *shell = shell_path(cnf->shelldir, cnf->shells, arg->val);
543 			if (shell == NULL)
544 				shell = "";
545 			if (strcmp(shell, pwd->pw_shell) != 0) {
546 				pwd->pw_shell = shell;
547 				edited = 1;
548 			}
549 		}
550 
551 		if (getarg(args, 'L')) {
552 			if (cnf->default_class == NULL)
553 				cnf->default_class = "";
554 			if (strcmp(pwd->pw_class, cnf->default_class) != 0) {
555 				pwd->pw_class = cnf->default_class;
556 				edited = 1;
557 			}
558 		}
559 
560 		if ((arg  = getarg(args, 'd')) != NULL) {
561 			if (strcmp(pwd->pw_dir, arg->val))
562 				edited = 1;
563 			if (stat(pwd->pw_dir = arg->val, &st) == -1) {
564 				if (getarg(args, 'm') == NULL && strcmp(pwd->pw_dir, "/nonexistent") != 0)
565 				  warnx("WARNING: home `%s' does not exist", pwd->pw_dir);
566 			} else if (!S_ISDIR(st.st_mode))
567 				warnx("WARNING: home `%s' is not a directory", pwd->pw_dir);
568 		}
569 
570 		if ((arg = getarg(args, 'w')) != NULL &&
571 		    getarg(args, 'h') == NULL && getarg(args, 'H') == NULL) {
572 			login_cap_t *lc;
573 
574 			lc = login_getpwclass(pwd);
575 			if (lc == NULL ||
576 			    login_setcryptfmt(lc, "sha512", NULL) == NULL)
577 				warn("setting crypt(3) format");
578 			login_close(lc);
579 			pwd->pw_passwd = pw_password(cnf, args, pwd->pw_name);
580 			edited = 1;
581 		}
582 
583 	} else {
584 		login_cap_t *lc;
585 
586 		/*
587 		 * Add code
588 		 */
589 
590 		if (a_name == NULL)	/* Required */
591 			errx(EX_DATAERR, "login name required");
592 		else if ((pwd = GETPWNAM(a_name->val)) != NULL)	/* Exists */
593 			errx(EX_DATAERR, "login name `%s' already exists", a_name->val);
594 
595 		/*
596 		 * Now, set up defaults for a new user
597 		 */
598 		pwd = &fakeuser;
599 		pwd->pw_name = a_name->val;
600 		pwd->pw_class = cnf->default_class ? cnf->default_class : "";
601 		pwd->pw_uid = pw_uidpolicy(cnf, args);
602 		pwd->pw_gid = pw_gidpolicy(cnf, args, pwd->pw_name, (gid_t) pwd->pw_uid);
603 		pwd->pw_change = pw_pwdpolicy(cnf, args);
604 		pwd->pw_expire = pw_exppolicy(cnf, args);
605 		pwd->pw_dir = pw_homepolicy(cnf, args, pwd->pw_name);
606 		pwd->pw_shell = pw_shellpolicy(cnf, args, NULL);
607 		lc = login_getpwclass(pwd);
608 		if (lc == NULL || login_setcryptfmt(lc, "md5", NULL) == NULL)
609 			warn("setting crypt(3) format");
610 		login_close(lc);
611 		pwd->pw_passwd = pw_password(cnf, args, pwd->pw_name);
612 		edited = 1;
613 
614 		if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
615 			warnx("WARNING: new account `%s' has a uid of 0 (superuser access!)", pwd->pw_name);
616 	}
617 
618 	/*
619 	 * Shared add/edit code
620 	 */
621 	if ((arg = getarg(args, 'c')) != NULL) {
622 		char	*gecos = pw_checkname((u_char *)arg->val, 1);
623 		if (strcmp(pwd->pw_gecos, gecos) != 0) {
624 			pwd->pw_gecos = gecos;
625 			edited = 1;
626 		}
627 	}
628 
629 	if ((arg = getarg(args, 'h')) != NULL ||
630 	    (arg = getarg(args, 'H')) != NULL) {
631 		if (strcmp(arg->val, "-") == 0) {
632 			if (!pwd->pw_passwd || *pwd->pw_passwd != '*') {
633 				pwd->pw_passwd = "*";	/* No access */
634 				edited = 1;
635 			}
636 		} else {
637 			int             fd = atoi(arg->val);
638 			int		precrypt = (arg->ch == 'H');
639 			int             b;
640 			int             istty = isatty(fd);
641 			struct termios  t;
642 			login_cap_t	*lc;
643 
644 			if (istty) {
645 				if (tcgetattr(fd, &t) == -1)
646 					istty = 0;
647 				else {
648 					struct termios  n = t;
649 
650 					/* Disable echo */
651 					n.c_lflag &= ~(ECHO);
652 					tcsetattr(fd, TCSANOW, &n);
653 					printf("%s%spassword for user %s:",
654 					     (mode == M_UPDATE) ? "new " : "",
655 					     precrypt ? "encrypted " : "",
656 					     pwd->pw_name);
657 					fflush(stdout);
658 				}
659 			}
660 			b = read(fd, line, sizeof(line) - 1);
661 			if (istty) {	/* Restore state */
662 				tcsetattr(fd, TCSANOW, &t);
663 				fputc('\n', stdout);
664 				fflush(stdout);
665 			}
666 			if (b < 0) {
667 				warn("-%c file descriptor", precrypt ? 'H' :
668 				    'h');
669 				return EX_IOERR;
670 			}
671 			line[b] = '\0';
672 			if ((p = strpbrk(line, "\r\n")) != NULL)
673 				*p = '\0';
674 			if (!*line)
675 				errx(EX_DATAERR, "empty password read on file descriptor %d", fd);
676 			if (precrypt) {
677 				if (strchr(line, ':') != NULL)
678 					return EX_DATAERR;
679 				pwd->pw_passwd = line;
680 			} else {
681 				lc = login_getpwclass(pwd);
682 				if (lc == NULL ||
683 				    login_setcryptfmt(lc, "md5", NULL) == NULL)
684 					warn("setting crypt(3) format");
685 				login_close(lc);
686 				pwd->pw_passwd = pw_pwcrypt(line);
687 			}
688 			edited = 1;
689 		}
690 	}
691 
692 	/*
693 	 * Special case: -N only displays & exits
694 	 */
695 	if (getarg(args, 'N') != NULL)
696 		return print_user(pwd,
697 				  getarg(args, 'P') != NULL,
698 				  getarg(args, '7') != NULL);
699 
700 	if (mode == M_ADD) {
701 		edited = 1;	/* Always */
702 		rc = addpwent(pwd);
703 		if (rc == -1) {
704 			warnx("user '%s' already exists", pwd->pw_name);
705 			return EX_IOERR;
706 		} else if (rc != 0) {
707 			warn("passwd file update");
708 			return EX_IOERR;
709 		}
710 		if (cnf->nispasswd && *cnf->nispasswd=='/') {
711 			rc = addnispwent(cnf->nispasswd, pwd);
712 			if (rc == -1)
713 				warnx("User '%s' already exists in NIS passwd", pwd->pw_name);
714 			else
715 				warn("NIS passwd update");
716 			/* NOTE: we treat NIS-only update errors as non-fatal */
717 		}
718 	} else if (mode == M_UPDATE || mode == M_LOCK || mode == M_UNLOCK) {
719 		if (edited) {	/* Only updated this if required */
720 			rc = chgpwent(a_name->val, pwd);
721 			if (rc == -1) {
722 				warnx("user '%s' does not exist (NIS?)", pwd->pw_name);
723 				return EX_IOERR;
724 			} else if (rc != 0) {
725 				warn("passwd file update");
726 				return EX_IOERR;
727 			}
728 			if ( cnf->nispasswd && *cnf->nispasswd=='/') {
729 				rc = chgnispwent(cnf->nispasswd, a_name->val, pwd);
730 				if (rc == -1)
731 					warn("User '%s' not found in NIS passwd", pwd->pw_name);
732 				else
733 					warn("NIS passwd update");
734 				/* NOTE: NIS-only update errors are not fatal */
735 			}
736 		}
737 	}
738 
739 	/*
740 	 * Ok, user is created or changed - now edit group file
741 	 */
742 
743 	if (mode == M_ADD || getarg(args, 'G') != NULL) {
744 		int i;
745 		for (i = 0; cnf->groups[i] != NULL; i++) {
746 			grp = GETGRNAM(cnf->groups[i]);
747 			grp = gr_add(grp, pwd->pw_name);
748 			/*
749 			 * grp can only be NULL in 2 cases:
750 			 * - the new member is already a member
751 			 * - a problem with memory occurs
752 			 * in both cases we want to skip now.
753 			 */
754 			if (grp == NULL)
755 				continue;
756 			chggrent(cnf->groups[i], grp);
757 			free(grp);
758 		}
759 	}
760 
761 
762 	/* go get a current version of pwd */
763 	pwd = GETPWNAM(a_name->val);
764 	if (pwd == NULL) {
765 		/* This will fail when we rename, so special case that */
766 		if (mode == M_UPDATE && (arg = getarg(args, 'l')) != NULL) {
767 			a_name->val = arg->val;		/* update new name */
768 			pwd = GETPWNAM(a_name->val);	/* refetch renamed rec */
769 		}
770 	}
771 	if (pwd == NULL)	/* can't go on without this */
772 		errx(EX_NOUSER, "user '%s' disappeared during update", a_name->val);
773 
774 	grp = GETGRGID(pwd->pw_gid);
775 	pw_log(cnf, mode, W_USER, "%s(%ld):%s(%ld):%s:%s:%s",
776 	       pwd->pw_name, (long) pwd->pw_uid,
777 	    grp ? grp->gr_name : "unknown", (long) (grp ? grp->gr_gid : -1),
778 	       pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell);
779 
780 	/*
781 	 * If adding, let's touch and chown the user's mail file. This is not
782 	 * strictly necessary under BSD with a 0755 maildir but it also
783 	 * doesn't hurt anything to create the empty mailfile
784 	 */
785 	if (mode == M_ADD) {
786 		if (!PWALTDIR()) {
787 			sprintf(line, "%s/%s", _PATH_MAILDIR, pwd->pw_name);
788 			close(open(line, O_RDWR | O_CREAT, 0600));	/* Preserve contents &
789 									 * mtime */
790 			chown(line, pwd->pw_uid, pwd->pw_gid);
791 		}
792 	}
793 
794 	/*
795 	 * Let's create and populate the user's home directory. Note
796 	 * that this also `works' for editing users if -m is used, but
797 	 * existing files will *not* be overwritten.
798 	 */
799 	if (!PWALTDIR() && getarg(args, 'm') != NULL && pwd->pw_dir && *pwd->pw_dir == '/' && pwd->pw_dir[1]) {
800 		copymkdir(pwd->pw_dir, cnf->dotdir, cnf->homemode, pwd->pw_uid, pwd->pw_gid);
801 		pw_log(cnf, mode, W_USER, "%s(%ld) home %s made",
802 		       pwd->pw_name, (long) pwd->pw_uid, pwd->pw_dir);
803 	}
804 
805 
806 	/*
807 	 * Finally, send mail to the new user as well, if we are asked to
808 	 */
809 	if (mode == M_ADD && !PWALTDIR() && cnf->newmail && *cnf->newmail && (fp = fopen(cnf->newmail, "r")) != NULL) {
810 		FILE           *pfp = popen(_PATH_SENDMAIL " -t", "w");
811 
812 		if (pfp == NULL)
813 			warn("sendmail");
814 		else {
815 			fprintf(pfp, "From: root\n" "To: %s\n" "Subject: Welcome!\n\n", pwd->pw_name);
816 			while (fgets(line, sizeof(line), fp) != NULL) {
817 				/* Do substitutions? */
818 				fputs(line, pfp);
819 			}
820 			pclose(pfp);
821 			pw_log(cnf, mode, W_USER, "%s(%ld) new user mail sent",
822 			    pwd->pw_name, (long) pwd->pw_uid);
823 		}
824 		fclose(fp);
825 	}
826 
827 	return EXIT_SUCCESS;
828 }
829 
830 
831 static          uid_t
832 pw_uidpolicy(struct userconf * cnf, struct cargs * args)
833 {
834 	struct passwd  *pwd;
835 	uid_t           uid = (uid_t) - 1;
836 	struct carg    *a_uid = getarg(args, 'u');
837 
838 	/*
839 	 * Check the given uid, if any
840 	 */
841 	if (a_uid != NULL) {
842 		uid = (uid_t) atol(a_uid->val);
843 
844 		if ((pwd = GETPWUID(uid)) != NULL && getarg(args, 'o') == NULL)
845 			errx(EX_DATAERR, "uid `%ld' has already been allocated", (long) pwd->pw_uid);
846 	} else {
847 		struct bitmap   bm;
848 
849 		/*
850 		 * We need to allocate the next available uid under one of
851 		 * two policies a) Grab the first unused uid b) Grab the
852 		 * highest possible unused uid
853 		 */
854 		if (cnf->min_uid >= cnf->max_uid) {	/* Sanity
855 							 * claus^H^H^H^Hheck */
856 			cnf->min_uid = 1000;
857 			cnf->max_uid = 32000;
858 		}
859 		bm = bm_alloc(cnf->max_uid - cnf->min_uid + 1);
860 
861 		/*
862 		 * Now, let's fill the bitmap from the password file
863 		 */
864 		SETPWENT();
865 		while ((pwd = GETPWENT()) != NULL)
866 			if (pwd->pw_uid >= (uid_t) cnf->min_uid && pwd->pw_uid <= (uid_t) cnf->max_uid)
867 				bm_setbit(&bm, pwd->pw_uid - cnf->min_uid);
868 		ENDPWENT();
869 
870 		/*
871 		 * Then apply the policy, with fallback to reuse if necessary
872 		 */
873 		if (cnf->reuse_uids || (uid = (uid_t) (bm_lastset(&bm) + cnf->min_uid + 1)) > cnf->max_uid)
874 			uid = (uid_t) (bm_firstunset(&bm) + cnf->min_uid);
875 
876 		/*
877 		 * Another sanity check
878 		 */
879 		if (uid < cnf->min_uid || uid > cnf->max_uid)
880 			errx(EX_SOFTWARE, "unable to allocate a new uid - range fully used");
881 		bm_dealloc(&bm);
882 	}
883 	return uid;
884 }
885 
886 
887 static          uid_t
888 pw_gidpolicy(struct userconf * cnf, struct cargs * args, char *nam, gid_t prefer)
889 {
890 	struct group   *grp;
891 	gid_t           gid = (uid_t) - 1;
892 	struct carg    *a_gid = getarg(args, 'g');
893 
894 	/*
895 	 * If no arg given, see if default can help out
896 	 */
897 	if (a_gid == NULL && cnf->default_group && *cnf->default_group)
898 		a_gid = addarg(args, 'g', cnf->default_group);
899 
900 	/*
901 	 * Check the given gid, if any
902 	 */
903 	SETGRENT();
904 	if (a_gid != NULL) {
905 		if ((grp = GETGRNAM(a_gid->val)) == NULL) {
906 			gid = (gid_t) atol(a_gid->val);
907 			if ((gid == 0 && !isdigit((unsigned char)*a_gid->val)) || (grp = GETGRGID(gid)) == NULL)
908 				errx(EX_NOUSER, "group `%s' is not defined", a_gid->val);
909 		}
910 		gid = grp->gr_gid;
911 	} else if ((grp = GETGRNAM(nam)) != NULL && grp->gr_mem[0] == NULL) {
912 		gid = grp->gr_gid;  /* Already created? Use it anyway... */
913 	} else {
914 		struct cargs    grpargs;
915 		char            tmp[32];
916 
917 		LIST_INIT(&grpargs);
918 		addarg(&grpargs, 'n', nam);
919 
920 		/*
921 		 * We need to auto-create a group with the user's name. We
922 		 * can send all the appropriate output to our sister routine
923 		 * bit first see if we can create a group with gid==uid so we
924 		 * can keep the user and group ids in sync. We purposely do
925 		 * NOT check the gid range if we can force the sync. If the
926 		 * user's name dups an existing group, then the group add
927 		 * function will happily handle that case for us and exit.
928 		 */
929 		if (GETGRGID(prefer) == NULL) {
930 			sprintf(tmp, "%lu", (unsigned long) prefer);
931 			addarg(&grpargs, 'g', tmp);
932 		}
933 		if (getarg(args, 'N'))
934 		{
935 			addarg(&grpargs, 'N', NULL);
936 			addarg(&grpargs, 'q', NULL);
937 			gid = pw_group(cnf, M_NEXT, &grpargs);
938 		}
939 		else
940 		{
941 			pw_group(cnf, M_ADD, &grpargs);
942 			if ((grp = GETGRNAM(nam)) != NULL)
943 				gid = grp->gr_gid;
944 		}
945 		a_gid = LIST_FIRST(&grpargs);
946 		while (a_gid != NULL) {
947 			struct carg    *t = LIST_NEXT(a_gid, list);
948 			LIST_REMOVE(a_gid, list);
949 			a_gid = t;
950 		}
951 	}
952 	ENDGRENT();
953 	return gid;
954 }
955 
956 
957 static          time_t
958 pw_pwdpolicy(struct userconf * cnf, struct cargs * args)
959 {
960 	time_t          result = 0;
961 	time_t          now = time(NULL);
962 	struct carg    *arg = getarg(args, 'p');
963 
964 	if (arg != NULL) {
965 		if ((result = parse_date(now, arg->val)) == now)
966 			errx(EX_DATAERR, "invalid date/time `%s'", arg->val);
967 	} else if (cnf->password_days > 0)
968 		result = now + ((long) cnf->password_days * 86400L);
969 	return result;
970 }
971 
972 
973 static          time_t
974 pw_exppolicy(struct userconf * cnf, struct cargs * args)
975 {
976 	time_t          result = 0;
977 	time_t          now = time(NULL);
978 	struct carg    *arg = getarg(args, 'e');
979 
980 	if (arg != NULL) {
981 		if ((result = parse_date(now, arg->val)) == now)
982 			errx(EX_DATAERR, "invalid date/time `%s'", arg->val);
983 	} else if (cnf->expire_days > 0)
984 		result = now + ((long) cnf->expire_days * 86400L);
985 	return result;
986 }
987 
988 
989 static char    *
990 pw_homepolicy(struct userconf * cnf, struct cargs * args, char const * user)
991 {
992 	struct carg    *arg = getarg(args, 'd');
993 
994 	if (arg)
995 		return arg->val;
996 	else {
997 		static char     home[128];
998 
999 		if (cnf->home == NULL || *cnf->home == '\0')
1000 			errx(EX_CONFIG, "no base home directory set");
1001 		sprintf(home, "%s/%s", cnf->home, user);
1002 		return home;
1003 	}
1004 }
1005 
1006 static char    *
1007 shell_path(char const * path, char *shells[], char *sh)
1008 {
1009 	if (sh != NULL && (*sh == '/' || *sh == '\0'))
1010 		return sh;	/* specified full path or forced none */
1011 	else {
1012 		char           *p;
1013 		char            paths[_UC_MAXLINE];
1014 
1015 		/*
1016 		 * We need to search paths
1017 		 */
1018 		strlcpy(paths, path, sizeof(paths));
1019 		for (p = strtok(paths, ": \t\r\n"); p != NULL; p = strtok(NULL, ": \t\r\n")) {
1020 			int             i;
1021 			static char     shellpath[256];
1022 
1023 			if (sh != NULL) {
1024 				sprintf(shellpath, "%s/%s", p, sh);
1025 				if (access(shellpath, X_OK) == 0)
1026 					return shellpath;
1027 			} else
1028 				for (i = 0; i < _UC_MAXSHELLS && shells[i] != NULL; i++) {
1029 					sprintf(shellpath, "%s/%s", p, shells[i]);
1030 					if (access(shellpath, X_OK) == 0)
1031 						return shellpath;
1032 				}
1033 		}
1034 		if (sh == NULL)
1035 			errx(EX_OSFILE, "can't find shell `%s' in shell paths", sh);
1036 		errx(EX_CONFIG, "no default shell available or defined");
1037 		return NULL;
1038 	}
1039 }
1040 
1041 
1042 static char    *
1043 pw_shellpolicy(struct userconf * cnf, struct cargs * args, char *newshell)
1044 {
1045 	char           *sh = newshell;
1046 	struct carg    *arg = getarg(args, 's');
1047 
1048 	if (newshell == NULL && arg != NULL)
1049 		sh = arg->val;
1050 	return shell_path(cnf->shelldir, cnf->shells, sh ? sh : cnf->shell_default);
1051 }
1052 
1053 #define	SALTSIZE	32
1054 
1055 static char const chars[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ./";
1056 
1057 char           *
1058 pw_pwcrypt(char *password)
1059 {
1060 	int             i;
1061 	char            salt[SALTSIZE + 1];
1062 	char		*cryptpw;
1063 
1064 	static char     buf[256];
1065 
1066 	/*
1067 	 * Calculate a salt value
1068 	 */
1069 	for (i = 0; i < SALTSIZE; i++)
1070 		salt[i] = chars[arc4random_uniform(sizeof(chars) - 1)];
1071 	salt[SALTSIZE] = '\0';
1072 
1073 	cryptpw = crypt(password, salt);
1074 	if (cryptpw == NULL)
1075 		errx(EX_CONFIG, "crypt(3) failure");
1076 	return strcpy(buf, cryptpw);
1077 }
1078 
1079 
1080 static char    *
1081 pw_password(struct userconf * cnf, struct cargs * args, char const * user)
1082 {
1083 	int             i, l;
1084 	char            pwbuf[32];
1085 
1086 	switch (cnf->default_password) {
1087 	case -1:		/* Random password */
1088 		l = (arc4random() % 8 + 8);	/* 8 - 16 chars */
1089 		for (i = 0; i < l; i++)
1090 			pwbuf[i] = chars[arc4random_uniform(sizeof(chars)-1)];
1091 		pwbuf[i] = '\0';
1092 
1093 		/*
1094 		 * We give this information back to the user
1095 		 */
1096 		if (getarg(args, 'h') == NULL && getarg(args, 'H') == NULL &&
1097 		    getarg(args, 'N') == NULL) {
1098 			if (isatty(STDOUT_FILENO))
1099 				printf("Password for '%s' is: ", user);
1100 			printf("%s\n", pwbuf);
1101 			fflush(stdout);
1102 		}
1103 		break;
1104 
1105 	case -2:		/* No password at all! */
1106 		return "";
1107 
1108 	case 0:		/* No login - default */
1109 	default:
1110 		return "*";
1111 
1112 	case 1:		/* user's name */
1113 		strlcpy(pwbuf, user, sizeof(pwbuf));
1114 		break;
1115 	}
1116 	return pw_pwcrypt(pwbuf);
1117 }
1118 
1119 
1120 static int
1121 print_user(struct passwd * pwd, int pretty, int v7)
1122 {
1123 	if (!pretty) {
1124 		char            *buf;
1125 
1126 		if (!v7)
1127 			pwd->pw_passwd = (pwd->pw_passwd == NULL) ? "" : "*";
1128 
1129 		buf = v7 ? pw_make_v7(pwd) : pw_make(pwd);
1130 		printf("%s\n", buf);
1131 		free(buf);
1132 	} else {
1133 		int		j;
1134 		char           *p;
1135 		struct group   *grp = GETGRGID(pwd->pw_gid);
1136 		char            uname[60] = "User &", office[60] = "[None]",
1137 		                wphone[60] = "[None]", hphone[60] = "[None]";
1138 		char		acexpire[32] = "[None]", pwexpire[32] = "[None]";
1139 		struct tm *    tptr;
1140 
1141 		if ((p = strtok(pwd->pw_gecos, ",")) != NULL) {
1142 			strlcpy(uname, p, sizeof(uname));
1143 			if ((p = strtok(NULL, ",")) != NULL) {
1144 				strlcpy(office, p, sizeof(office));
1145 				if ((p = strtok(NULL, ",")) != NULL) {
1146 					strlcpy(wphone, p, sizeof(wphone));
1147 					if ((p = strtok(NULL, "")) != NULL) {
1148 						strlcpy(hphone, p,
1149 						    sizeof(hphone));
1150 					}
1151 				}
1152 			}
1153 		}
1154 		/*
1155 		 * Handle '&' in gecos field
1156 		 */
1157 		if ((p = strchr(uname, '&')) != NULL) {
1158 			int             l = strlen(pwd->pw_name);
1159 			int             m = strlen(p);
1160 
1161 			memmove(p + l, p + 1, m);
1162 			memmove(p, pwd->pw_name, l);
1163 			*p = (char) toupper((unsigned char)*p);
1164 		}
1165 		if (pwd->pw_expire > (time_t)0 && (tptr = localtime(&pwd->pw_expire)) != NULL)
1166 			strftime(acexpire, sizeof acexpire, "%c", tptr);
1167 		if (pwd->pw_change > (time_t)0 && (tptr = localtime(&pwd->pw_change)) != NULL)
1168 			strftime(pwexpire, sizeof pwexpire, "%c", tptr);
1169 		printf("Login Name: %-15s   #%-12ld Group: %-15s   #%ld\n"
1170 		       " Full Name: %s\n"
1171 		       "      Home: %-26.26s      Class: %s\n"
1172 		       "     Shell: %-26.26s     Office: %s\n"
1173 		       "Work Phone: %-26.26s Home Phone: %s\n"
1174 		       "Acc Expire: %-26.26s Pwd Expire: %s\n",
1175 		       pwd->pw_name, (long) pwd->pw_uid,
1176 		       grp ? grp->gr_name : "(invalid)", (long) pwd->pw_gid,
1177 		       uname, pwd->pw_dir, pwd->pw_class,
1178 		       pwd->pw_shell, office, wphone, hphone,
1179 		       acexpire, pwexpire);
1180 	        SETGRENT();
1181 		j = 0;
1182 		while ((grp=GETGRENT()) != NULL)
1183 		{
1184 			int     i = 0;
1185 			while (grp->gr_mem[i] != NULL)
1186 			{
1187 				if (strcmp(grp->gr_mem[i], pwd->pw_name)==0)
1188 				{
1189 					printf(j++ == 0 ? "    Groups: %s" : ",%s", grp->gr_name);
1190 					break;
1191 				}
1192 				++i;
1193 			}
1194 		}
1195 		ENDGRENT();
1196 		printf("%s", j ? "\n" : "");
1197 	}
1198 	return EXIT_SUCCESS;
1199 }
1200 
1201 char    *
1202 pw_checkname(u_char *name, int gecos)
1203 {
1204 	char showch[8];
1205 	u_char const *badchars, *ch, *showtype;
1206 	int reject;
1207 
1208 	ch = name;
1209 	reject = 0;
1210 	if (gecos) {
1211 		/* See if the name is valid as a gecos (comment) field. */
1212 		badchars = ":!@";
1213 		showtype = "gecos field";
1214 	} else {
1215 		/* See if the name is valid as a userid or group. */
1216 		badchars = " ,\t:+&#%$^()!@~*?<>=|\\/\"";
1217 		showtype = "userid/group name";
1218 		/* Userids and groups can not have a leading '-'. */
1219 		if (*ch == '-')
1220 			reject = 1;
1221 	}
1222 	if (!reject) {
1223 		while (*ch) {
1224 			if (strchr(badchars, *ch) != NULL || *ch < ' ' ||
1225 			    *ch == 127) {
1226 				reject = 1;
1227 				break;
1228 			}
1229 			/* 8-bit characters are only allowed in GECOS fields */
1230 			if (!gecos && (*ch & 0x80)) {
1231 				reject = 1;
1232 				break;
1233 			}
1234 			ch++;
1235 		}
1236 	}
1237 	/*
1238 	 * A `$' is allowed as the final character for userids and groups,
1239 	 * mainly for the benefit of samba.
1240 	 */
1241 	if (reject && !gecos) {
1242 		if (*ch == '$' && *(ch + 1) == '\0') {
1243 			reject = 0;
1244 			ch++;
1245 		}
1246 	}
1247 	if (reject) {
1248 		snprintf(showch, sizeof(showch), (*ch >= ' ' && *ch < 127)
1249 		    ? "`%c'" : "0x%02x", *ch);
1250 		errx(EX_DATAERR, "invalid character %s at position %td in %s",
1251 		    showch, (ch - name), showtype);
1252 	}
1253 	if (!gecos && (ch - name) > LOGNAMESIZE)
1254 		errx(EX_DATAERR, "name too long `%s' (max is %d)", name,
1255 		    LOGNAMESIZE);
1256 	return (char *)name;
1257 }
1258 
1259 
1260 static void
1261 rmat(uid_t uid)
1262 {
1263 	DIR            *d = opendir("/var/at/jobs");
1264 
1265 	if (d != NULL) {
1266 		struct dirent  *e;
1267 
1268 		while ((e = readdir(d)) != NULL) {
1269 			struct stat     st;
1270 
1271 			if (strncmp(e->d_name, ".lock", 5) != 0 &&
1272 			    stat(e->d_name, &st) == 0 &&
1273 			    !S_ISDIR(st.st_mode) &&
1274 			    st.st_uid == uid) {
1275 				char            tmp[MAXPATHLEN];
1276 
1277 				sprintf(tmp, "/usr/bin/atrm %s", e->d_name);
1278 				system(tmp);
1279 			}
1280 		}
1281 		closedir(d);
1282 	}
1283 }
1284 
1285 static void
1286 rmopie(char const * name)
1287 {
1288 	static const char etcopie[] = "/etc/opiekeys";
1289 	FILE   *fp = fopen(etcopie, "r+");
1290 
1291 	if (fp != NULL) {
1292 		char	tmp[1024];
1293 		off_t	atofs = 0;
1294 		int	length = strlen(name);
1295 
1296 		while (fgets(tmp, sizeof tmp, fp) != NULL) {
1297 			if (strncmp(name, tmp, length) == 0 && tmp[length]==' ') {
1298 				if (fseek(fp, atofs, SEEK_SET) == 0) {
1299 					fwrite("#", 1, 1, fp);	/* Comment username out */
1300 				}
1301 				break;
1302 			}
1303 			atofs = ftell(fp);
1304 		}
1305 		/*
1306 		 * If we got an error of any sort, don't update!
1307 		 */
1308 		fclose(fp);
1309 	}
1310 }
1311 
1312