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