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