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