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