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