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