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