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