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