pw_user.c revision 285412
1236594Sobrien/*-
2236594Sobrien * Copyright (C) 1996
3236594Sobrien *	David L. Nugent.  All rights reserved.
4236594Sobrien *
5236594Sobrien * Redistribution and use in source and binary forms, with or without
6236594Sobrien * modification, are permitted provided that the following conditions
7236594Sobrien * are met:
8236594Sobrien * 1. Redistributions of source code must retain the above copyright
9236594Sobrien *    notice, this list of conditions and the following disclaimer.
10236594Sobrien * 2. Redistributions in binary form must reproduce the above copyright
11236594Sobrien *    notice, this list of conditions and the following disclaimer in the
12236594Sobrien *    documentation and/or other materials provided with the distribution.
13236594Sobrien *
14236594Sobrien * THIS SOFTWARE IS PROVIDED BY DAVID L. NUGENT AND CONTRIBUTORS ``AS IS'' AND
15236594Sobrien * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16236594Sobrien * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17236594Sobrien * ARE DISCLAIMED.  IN NO EVENT SHALL DAVID L. NUGENT OR CONTRIBUTORS BE LIABLE
18236594Sobrien * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19236594Sobrien * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20236594Sobrien * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21236594Sobrien * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22236594Sobrien * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23236594Sobrien * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24236594Sobrien * SUCH DAMAGE.
25236594Sobrien *
26236594Sobrien */
27236594Sobrien
28236594Sobrien#ifndef lint
29236594Sobrienstatic const char rcsid[] =
30236594Sobrien  "$FreeBSD: head/usr.sbin/pw/pw_user.c 285412 2015-07-11 23:07:17Z bapt $";
31236594Sobrien#endif /* not lint */
32236594Sobrien
33236594Sobrien#include <ctype.h>
34236594Sobrien#include <err.h>
35236594Sobrien#include <fcntl.h>
36236594Sobrien#include <sys/param.h>
37236594Sobrien#include <dirent.h>
38236594Sobrien#include <paths.h>
39236594Sobrien#include <termios.h>
40236594Sobrien#include <sys/types.h>
41236594Sobrien#include <sys/time.h>
42236594Sobrien#include <sys/resource.h>
43236594Sobrien#include <login_cap.h>
44236594Sobrien#include <pwd.h>
45236594Sobrien#include <grp.h>
46251368Sobrien#include <libutil.h>
47251368Sobrien#include "pw.h"
48251368Sobrien#include "bitmap.h"
49251368Sobrien
50236594Sobrien#define LOGNAMESIZE (MAXLOGNAME-1)
51236594Sobrien
52251368Sobrienstatic		char locked_str[] = "*LOCKED*";
53236594Sobrien
54236594Sobrienstatic int	pw_userdel(char *name, long id);
55236594Sobrienstatic int	print_user(struct passwd * pwd);
56236594Sobrienstatic uid_t    pw_uidpolicy(struct userconf * cnf, long id);
57236594Sobrienstatic uid_t    pw_gidpolicy(struct cargs * args, char *nam, gid_t prefer);
58236594Sobrienstatic time_t   pw_pwdpolicy(struct userconf * cnf, struct cargs * args);
59236594Sobrienstatic time_t   pw_exppolicy(struct userconf * cnf, struct cargs * args);
60236594Sobrienstatic char    *pw_homepolicy(struct userconf * cnf, struct cargs * args, char const * user);
61236620Sobrienstatic char    *pw_shellpolicy(struct userconf * cnf, struct cargs * args, char *newshell);
62236594Sobrienstatic char    *pw_password(struct userconf * cnf, char const * user);
63236594Sobrienstatic char    *shell_path(char const * path, char *shells[], char *sh);
64236594Sobrienstatic void     rmat(uid_t uid);
65236594Sobrienstatic void     rmopie(char const * name);
66236594Sobrien
67236594Sobrienstatic void
68236620Sobriencreate_and_populate_homedir(struct passwd *pwd)
69236620Sobrien{
70236620Sobrien	char *homedir, *dotdir;
71236620Sobrien	struct userconf *cnf = conf.userconf;
72236620Sobrien
73251368Sobrien	homedir = dotdir = NULL;
74236620Sobrien
75236620Sobrien	if (conf.rootdir[0] != '\0') {
76236620Sobrien		asprintf(&homedir, "%s/%s", conf.rootdir, pwd->pw_dir);
77236620Sobrien		if (homedir == NULL)
78236594Sobrien			errx(EX_OSERR, "out of memory");
79236594Sobrien		asprintf(&dotdir, "%s/%s", conf.rootdir, cnf->dotdir);
80236594Sobrien	}
81236620Sobrien
82236594Sobrien	copymkdir(homedir ? homedir : pwd->pw_dir, dotdir ? dotdir: cnf->dotdir,
83236594Sobrien	    cnf->homemode, pwd->pw_uid, pwd->pw_gid);
84236594Sobrien	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							err(EX_OSFILE, "mkdir '%s'", dbuf);
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					err(EX_OSFILE, "mkdir '%s'", dbuf);
413				chown(dbuf, 0, 0);
414			}
415		} else if (!S_ISDIR(st.st_mode))
416			errx(EX_OSFILE, "root home `%s' is not a directory", cnf->home);
417	}
418
419	if ((arg = getarg(args, 'e')) != NULL)
420		cnf->expire_days = atoi(arg->val);
421
422	if ((arg = getarg(args, 'y')) != NULL)
423		cnf->nispasswd = arg->val;
424
425	if ((arg = getarg(args, 'p')) != NULL && arg->val)
426		cnf->password_days = atoi(arg->val);
427
428	if ((arg = getarg(args, 'g')) != NULL) {
429		if (!*(p = arg->val))	/* Handle empty group list specially */
430			cnf->default_group = "";
431		else {
432			if ((grp = GETGRNAM(p)) == NULL) {
433				if (!isdigit((unsigned char)*p) || (grp = GETGRGID((gid_t) atoi(p))) == NULL)
434					errx(EX_NOUSER, "group `%s' does not exist", p);
435			}
436			cnf->default_group = newstr(grp->gr_name);
437		}
438	}
439	if ((arg = getarg(args, 'L')) != NULL)
440		cnf->default_class = pw_checkname(arg->val, 0);
441
442	if ((arg = getarg(args, 'G')) != NULL && arg->val) {
443		for (p = strtok(arg->val, ", \t"); p != NULL; p = strtok(NULL, ", \t")) {
444			if ((grp = GETGRNAM(p)) == NULL) {
445				if (!isdigit((unsigned char)*p) || (grp = GETGRGID((gid_t) atoi(p))) == NULL)
446					errx(EX_NOUSER, "group `%s' does not exist", p);
447			}
448			sl_add(cnf->groups, newstr(grp->gr_name));
449		}
450	}
451
452	if ((arg = getarg(args, 'k')) != NULL) {
453		if (stat(cnf->dotdir = arg->val, &st) == -1 || !S_ISDIR(st.st_mode))
454			errx(EX_OSFILE, "skeleton `%s' is not a directory or does not exist", cnf->dotdir);
455	}
456
457	if ((arg = getarg(args, 's')) != NULL)
458		cnf->shell_default = arg->val;
459
460	if ((arg = getarg(args, 'w')) != NULL)
461		cnf->default_password = boolean_val(arg->val, cnf->default_password);
462	if (mode == M_ADD && getarg(args, 'D')) {
463		if (name != NULL)
464			errx(EX_DATAERR, "can't combine `-D' with `-n name'");
465		if ((arg = getarg(args, 'u')) != NULL && (p = strtok(arg->val, ", \t")) != NULL) {
466			if ((cnf->min_uid = (uid_t) atoi(p)) == 0)
467				cnf->min_uid = 1000;
468			if ((p = strtok(NULL, " ,\t")) == NULL || (cnf->max_uid = (uid_t) atoi(p)) < cnf->min_uid)
469				cnf->max_uid = 32000;
470		}
471		if ((arg = getarg(args, 'i')) != NULL && (p = strtok(arg->val, ", \t")) != NULL) {
472			if ((cnf->min_gid = (gid_t) atoi(p)) == 0)
473				cnf->min_gid = 1000;
474			if ((p = strtok(NULL, " ,\t")) == NULL || (cnf->max_gid = (gid_t) atoi(p)) < cnf->min_gid)
475				cnf->max_gid = 32000;
476		}
477
478		if (write_userconfig(conf.config))
479			return (EXIT_SUCCESS);
480		err(EX_IOERR, "config udpate");
481	}
482
483	if (name != NULL)
484		pwd = GETPWNAM(pw_checkname(name, 0));
485
486	if (id < 0 && name == NULL)
487		errx(EX_DATAERR, "user name or id required");
488
489	/*
490	 * Update require that the user exists
491	 */
492	if (mode == M_UPDATE) {
493
494		if (name == NULL && pwd == NULL)	/* Try harder */
495			pwd = GETPWUID(id);
496
497		if (pwd == NULL) {
498			if (name == NULL)
499				errx(EX_NOUSER, "no such uid `%ld'", id);
500			errx(EX_NOUSER, "no such user `%s'", name);
501		}
502
503		if (name == NULL)
504			name = pwd->pw_name;
505
506		/*
507		 * The rest is edit code
508		 */
509		if (conf.newname != NULL) {
510			if (strcmp(pwd->pw_name, "root") == 0)
511				errx(EX_DATAERR, "can't rename `root' account");
512			pwd->pw_name = pw_checkname(conf.newname, 0);
513			edited = 1;
514		}
515
516		if (id > 0 && isdigit((unsigned char)*arg->val)) {
517			pwd->pw_uid = (uid_t)id;
518			edited = 1;
519			if (pwd->pw_uid != 0 && strcmp(pwd->pw_name, "root") == 0)
520				errx(EX_DATAERR, "can't change uid of `root' account");
521			if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
522				warnx("WARNING: account `%s' will have a uid of 0 (superuser access!)", pwd->pw_name);
523		}
524
525		if ((arg = getarg(args, 'g')) != NULL && pwd->pw_uid != 0) {	/* Already checked this */
526			gid_t newgid = (gid_t) GETGRNAM(cnf->default_group)->gr_gid;
527			if (newgid != pwd->pw_gid) {
528				edited = 1;
529				pwd->pw_gid = newgid;
530			}
531		}
532
533		if ((arg = getarg(args, 'p')) != NULL) {
534			if (*arg->val == '\0' || strcmp(arg->val, "0") == 0) {
535				if (pwd->pw_change != 0) {
536					pwd->pw_change = 0;
537					edited = 1;
538				}
539			}
540			else {
541				time_t          now = time(NULL);
542				time_t          expire = parse_date(now, arg->val);
543
544				if (pwd->pw_change != expire) {
545					pwd->pw_change = expire;
546					edited = 1;
547				}
548			}
549		}
550
551		if ((arg = getarg(args, 'e')) != NULL) {
552			if (*arg->val == '\0' || strcmp(arg->val, "0") == 0) {
553				if (pwd->pw_expire != 0) {
554					pwd->pw_expire = 0;
555					edited = 1;
556				}
557			}
558			else {
559				time_t          now = time(NULL);
560				time_t          expire = parse_date(now, arg->val);
561
562				if (pwd->pw_expire != expire) {
563					pwd->pw_expire = expire;
564					edited = 1;
565				}
566			}
567		}
568
569		if ((arg = getarg(args, 's')) != NULL) {
570			char *shell = shell_path(cnf->shelldir, cnf->shells, arg->val);
571			if (shell == NULL)
572				shell = "";
573			if (strcmp(shell, pwd->pw_shell) != 0) {
574				pwd->pw_shell = shell;
575				edited = 1;
576			}
577		}
578
579		if (getarg(args, 'L')) {
580			if (cnf->default_class == NULL)
581				cnf->default_class = "";
582			if (strcmp(pwd->pw_class, cnf->default_class) != 0) {
583				pwd->pw_class = cnf->default_class;
584				edited = 1;
585			}
586		}
587
588		if ((arg  = getarg(args, 'd')) != NULL) {
589			if (strcmp(pwd->pw_dir, arg->val))
590				edited = 1;
591			if (stat(pwd->pw_dir = arg->val, &st) == -1) {
592				if (getarg(args, 'm') == NULL && strcmp(pwd->pw_dir, "/nonexistent") != 0)
593				  warnx("WARNING: home `%s' does not exist", pwd->pw_dir);
594			} else if (!S_ISDIR(st.st_mode))
595				warnx("WARNING: home `%s' is not a directory", pwd->pw_dir);
596		}
597
598		if ((arg = getarg(args, 'w')) != NULL && conf.fd == -1) {
599			login_cap_t *lc;
600
601			lc = login_getpwclass(pwd);
602			if (lc == NULL ||
603			    login_setcryptfmt(lc, "sha512", NULL) == NULL)
604				warn("setting crypt(3) format");
605			login_close(lc);
606			pwd->pw_passwd = pw_password(cnf, pwd->pw_name);
607			edited = 1;
608		}
609
610	} else {
611		login_cap_t *lc;
612
613		/*
614		 * Add code
615		 */
616
617		if (name == NULL)	/* Required */
618			errx(EX_DATAERR, "login name required");
619		else if ((pwd = GETPWNAM(name)) != NULL)	/* Exists */
620			errx(EX_DATAERR, "login name `%s' already exists", name);
621
622		/*
623		 * Now, set up defaults for a new user
624		 */
625		pwd = &fakeuser;
626		pwd->pw_name = name;
627		pwd->pw_class = cnf->default_class ? cnf->default_class : "";
628		pwd->pw_uid = pw_uidpolicy(cnf, id);
629		pwd->pw_gid = pw_gidpolicy(args, pwd->pw_name, (gid_t) pwd->pw_uid);
630		pwd->pw_change = pw_pwdpolicy(cnf, args);
631		pwd->pw_expire = pw_exppolicy(cnf, args);
632		pwd->pw_dir = pw_homepolicy(cnf, args, pwd->pw_name);
633		pwd->pw_shell = pw_shellpolicy(cnf, args, NULL);
634		lc = login_getpwclass(pwd);
635		if (lc == NULL || login_setcryptfmt(lc, "sha512", NULL) == NULL)
636			warn("setting crypt(3) format");
637		login_close(lc);
638		pwd->pw_passwd = pw_password(cnf, pwd->pw_name);
639		edited = 1;
640
641		if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
642			warnx("WARNING: new account `%s' has a uid of 0 (superuser access!)", pwd->pw_name);
643	}
644
645	/*
646	 * Shared add/edit code
647	 */
648	if (conf.gecos != NULL) {
649		if (strcmp(pwd->pw_gecos, conf.gecos) != 0) {
650			pwd->pw_gecos = conf.gecos;
651			edited = 1;
652		}
653	}
654
655	if (conf.fd != -1)
656		edited = set_passwd(pwd, mode == M_UPDATE);
657
658	/*
659	 * Special case: -N only displays & exits
660	 */
661	if (conf.dryrun)
662		return print_user(pwd);
663
664	if (mode == M_ADD) {
665		edited = 1;	/* Always */
666		rc = addpwent(pwd);
667		if (rc == -1)
668			errx(EX_IOERR, "user '%s' already exists",
669			    pwd->pw_name);
670		else if (rc != 0)
671			err(EX_IOERR, "passwd file update");
672		if (cnf->nispasswd && *cnf->nispasswd=='/') {
673			rc = addnispwent(cnf->nispasswd, pwd);
674			if (rc == -1)
675				warnx("User '%s' already exists in NIS passwd", pwd->pw_name);
676			else
677				warn("NIS passwd update");
678			/* NOTE: we treat NIS-only update errors as non-fatal */
679		}
680	} else if (mode == M_UPDATE && edited) /* Only updated this if required */
681		perform_chgpwent(name, pwd);
682
683	/*
684	 * Ok, user is created or changed - now edit group file
685	 */
686
687	if (mode == M_ADD || getarg(args, 'G') != NULL) {
688		int j;
689		size_t i;
690		/* First remove the user from all group */
691		SETGRENT();
692		while ((grp = GETGRENT()) != NULL) {
693			char group[MAXLOGNAME];
694			if (grp->gr_mem == NULL)
695				continue;
696			for (i = 0; grp->gr_mem[i] != NULL; i++) {
697				if (strcmp(grp->gr_mem[i] , pwd->pw_name) != 0)
698					continue;
699				for (j = i; grp->gr_mem[j] != NULL ; j++)
700					grp->gr_mem[j] = grp->gr_mem[j+1];
701				strlcpy(group, grp->gr_name, MAXLOGNAME);
702				chggrent(group, grp);
703			}
704		}
705		ENDGRENT();
706
707		/* now add to group where needed */
708		for (i = 0; i < cnf->groups->sl_cur; i++) {
709			grp = GETGRNAM(cnf->groups->sl_str[i]);
710			grp = gr_add(grp, pwd->pw_name);
711			/*
712			 * grp can only be NULL in 2 cases:
713			 * - the new member is already a member
714			 * - a problem with memory occurs
715			 * in both cases we want to skip now.
716			 */
717			if (grp == NULL)
718				continue;
719			chggrent(grp->gr_name, grp);
720			free(grp);
721		}
722	}
723
724
725	/* go get a current version of pwd */
726	pwd = GETPWNAM(name);
727	if (pwd == NULL) {
728		/* This will fail when we rename, so special case that */
729		if (mode == M_UPDATE && conf.newname != NULL) {
730			name = conf.newname;		/* update new name */
731			pwd = GETPWNAM(name);	/* refetch renamed rec */
732		}
733	}
734	if (pwd == NULL)	/* can't go on without this */
735		errx(EX_NOUSER, "user '%s' disappeared during update", name);
736
737	grp = GETGRGID(pwd->pw_gid);
738	pw_log(cnf, mode, W_USER, "%s(%u):%s(%u):%s:%s:%s",
739	       pwd->pw_name, pwd->pw_uid,
740	    grp ? grp->gr_name : "unknown", (grp ? grp->gr_gid : (uid_t)-1),
741	       pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell);
742
743	/*
744	 * If adding, let's touch and chown the user's mail file. This is not
745	 * strictly necessary under BSD with a 0755 maildir but it also
746	 * doesn't hurt anything to create the empty mailfile
747	 */
748	if (mode == M_ADD) {
749		if (PWALTDIR() != PWF_ALT) {
750			arg = getarg(args, 'R');
751			snprintf(path, sizeof(path), "%s%s/%s",
752			    arg ? arg->val : "", _PATH_MAILDIR, pwd->pw_name);
753			close(open(path, O_RDWR | O_CREAT, 0600));	/* Preserve contents &
754									 * mtime */
755			chown(path, pwd->pw_uid, pwd->pw_gid);
756		}
757	}
758
759	/*
760	 * Let's create and populate the user's home directory. Note
761	 * that this also `works' for editing users if -m is used, but
762	 * existing files will *not* be overwritten.
763	 */
764	if (PWALTDIR() != PWF_ALT && getarg(args, 'm') != NULL && pwd->pw_dir &&
765	    *pwd->pw_dir == '/' && pwd->pw_dir[1])
766		create_and_populate_homedir(pwd);
767
768	/*
769	 * Finally, send mail to the new user as well, if we are asked to
770	 */
771	if (mode == M_ADD && !PWALTDIR() && cnf->newmail && *cnf->newmail && (fp = fopen(cnf->newmail, "r")) != NULL) {
772		FILE           *pfp = popen(_PATH_SENDMAIL " -t", "w");
773
774		if (pfp == NULL)
775			warn("sendmail");
776		else {
777			fprintf(pfp, "From: root\n" "To: %s\n" "Subject: Welcome!\n\n", pwd->pw_name);
778			while (fgets(line, sizeof(line), fp) != NULL) {
779				/* Do substitutions? */
780				fputs(line, pfp);
781			}
782			pclose(pfp);
783			pw_log(cnf, mode, W_USER, "%s(%u) new user mail sent",
784			    pwd->pw_name, pwd->pw_uid);
785		}
786		fclose(fp);
787	}
788
789	return EXIT_SUCCESS;
790}
791
792
793static          uid_t
794pw_uidpolicy(struct userconf * cnf, long id)
795{
796	struct passwd  *pwd;
797	uid_t           uid = (uid_t) - 1;
798
799	/*
800	 * Check the given uid, if any
801	 */
802	if (id > 0) {
803		uid = (uid_t) id;
804
805		if ((pwd = GETPWUID(uid)) != NULL && conf.checkduplicate)
806			errx(EX_DATAERR, "uid `%u' has already been allocated", pwd->pw_uid);
807	} else {
808		struct bitmap   bm;
809
810		/*
811		 * We need to allocate the next available uid under one of
812		 * two policies a) Grab the first unused uid b) Grab the
813		 * highest possible unused uid
814		 */
815		if (cnf->min_uid >= cnf->max_uid) {	/* Sanity
816							 * claus^H^H^H^Hheck */
817			cnf->min_uid = 1000;
818			cnf->max_uid = 32000;
819		}
820		bm = bm_alloc(cnf->max_uid - cnf->min_uid + 1);
821
822		/*
823		 * Now, let's fill the bitmap from the password file
824		 */
825		SETPWENT();
826		while ((pwd = GETPWENT()) != NULL)
827			if (pwd->pw_uid >= (uid_t) cnf->min_uid && pwd->pw_uid <= (uid_t) cnf->max_uid)
828				bm_setbit(&bm, pwd->pw_uid - cnf->min_uid);
829		ENDPWENT();
830
831		/*
832		 * Then apply the policy, with fallback to reuse if necessary
833		 */
834		if (cnf->reuse_uids || (uid = (uid_t) (bm_lastset(&bm) + cnf->min_uid + 1)) > cnf->max_uid)
835			uid = (uid_t) (bm_firstunset(&bm) + cnf->min_uid);
836
837		/*
838		 * Another sanity check
839		 */
840		if (uid < cnf->min_uid || uid > cnf->max_uid)
841			errx(EX_SOFTWARE, "unable to allocate a new uid - range fully used");
842		bm_dealloc(&bm);
843	}
844	return uid;
845}
846
847
848static          uid_t
849pw_gidpolicy(struct cargs * args, char *nam, gid_t prefer)
850{
851	struct group   *grp;
852	gid_t           gid = (uid_t) - 1;
853	struct carg    *a_gid = getarg(args, 'g');
854	struct userconf	*cnf = conf.userconf;
855
856	/*
857	 * If no arg given, see if default can help out
858	 */
859	if (a_gid == NULL && cnf->default_group && *cnf->default_group)
860		a_gid = addarg(args, 'g', cnf->default_group);
861
862	/*
863	 * Check the given gid, if any
864	 */
865	SETGRENT();
866	if (a_gid != NULL) {
867		if ((grp = GETGRNAM(a_gid->val)) == NULL) {
868			gid = (gid_t) atol(a_gid->val);
869			if ((gid == 0 && !isdigit((unsigned char)*a_gid->val)) || (grp = GETGRGID(gid)) == NULL)
870				errx(EX_NOUSER, "group `%s' is not defined", a_gid->val);
871		}
872		gid = grp->gr_gid;
873	} else if ((grp = GETGRNAM(nam)) != NULL &&
874	    (grp->gr_mem == NULL || grp->gr_mem[0] == NULL)) {
875		gid = grp->gr_gid;  /* Already created? Use it anyway... */
876	} else {
877		struct cargs    grpargs;
878		char            tmp[32];
879
880		LIST_INIT(&grpargs);
881
882		/*
883		 * We need to auto-create a group with the user's name. We
884		 * can send all the appropriate output to our sister routine
885		 * bit first see if we can create a group with gid==uid so we
886		 * can keep the user and group ids in sync. We purposely do
887		 * NOT check the gid range if we can force the sync. If the
888		 * user's name dups an existing group, then the group add
889		 * function will happily handle that case for us and exit.
890		 */
891		if (GETGRGID(prefer) == NULL) {
892			snprintf(tmp, sizeof(tmp), "%u", prefer);
893			addarg(&grpargs, 'g', tmp);
894		}
895		if (conf.dryrun) {
896			gid = pw_groupnext(cnf, true);
897		} else {
898			pw_group(M_ADD, nam, -1, &grpargs);
899			if ((grp = GETGRNAM(nam)) != NULL)
900				gid = grp->gr_gid;
901		}
902		a_gid = LIST_FIRST(&grpargs);
903		while (a_gid != NULL) {
904			struct carg    *t = LIST_NEXT(a_gid, list);
905			LIST_REMOVE(a_gid, list);
906			a_gid = t;
907		}
908	}
909	ENDGRENT();
910	return gid;
911}
912
913
914static          time_t
915pw_pwdpolicy(struct userconf * cnf, struct cargs * args)
916{
917	time_t          result = 0;
918	time_t          now = time(NULL);
919	struct carg    *arg = getarg(args, 'p');
920
921	if (arg != NULL) {
922		if ((result = parse_date(now, arg->val)) == now)
923			errx(EX_DATAERR, "invalid date/time `%s'", arg->val);
924	} else if (cnf->password_days > 0)
925		result = now + ((long) cnf->password_days * 86400L);
926	return result;
927}
928
929
930static          time_t
931pw_exppolicy(struct userconf * cnf, struct cargs * args)
932{
933	time_t          result = 0;
934	time_t          now = time(NULL);
935	struct carg    *arg = getarg(args, 'e');
936
937	if (arg != NULL) {
938		if ((result = parse_date(now, arg->val)) == now)
939			errx(EX_DATAERR, "invalid date/time `%s'", arg->val);
940	} else if (cnf->expire_days > 0)
941		result = now + ((long) cnf->expire_days * 86400L);
942	return result;
943}
944
945
946static char    *
947pw_homepolicy(struct userconf * cnf, struct cargs * args, char const * user)
948{
949	struct carg    *arg = getarg(args, 'd');
950	static char     home[128];
951
952	if (arg)
953		return (arg->val);
954
955	if (cnf->home == NULL || *cnf->home == '\0')
956		errx(EX_CONFIG, "no base home directory set");
957	snprintf(home, sizeof(home), "%s/%s", cnf->home, user);
958
959	return (home);
960}
961
962static char    *
963shell_path(char const * path, char *shells[], char *sh)
964{
965	if (sh != NULL && (*sh == '/' || *sh == '\0'))
966		return sh;	/* specified full path or forced none */
967	else {
968		char           *p;
969		char            paths[_UC_MAXLINE];
970
971		/*
972		 * We need to search paths
973		 */
974		strlcpy(paths, path, sizeof(paths));
975		for (p = strtok(paths, ": \t\r\n"); p != NULL; p = strtok(NULL, ": \t\r\n")) {
976			int             i;
977			static char     shellpath[256];
978
979			if (sh != NULL) {
980				snprintf(shellpath, sizeof(shellpath), "%s/%s", p, sh);
981				if (access(shellpath, X_OK) == 0)
982					return shellpath;
983			} else
984				for (i = 0; i < _UC_MAXSHELLS && shells[i] != NULL; i++) {
985					snprintf(shellpath, sizeof(shellpath), "%s/%s", p, shells[i]);
986					if (access(shellpath, X_OK) == 0)
987						return shellpath;
988				}
989		}
990		if (sh == NULL)
991			errx(EX_OSFILE, "can't find shell `%s' in shell paths", sh);
992		errx(EX_CONFIG, "no default shell available or defined");
993		return NULL;
994	}
995}
996
997
998static char    *
999pw_shellpolicy(struct userconf * cnf, struct cargs * args, char *newshell)
1000{
1001	char           *sh = newshell;
1002	struct carg    *arg = getarg(args, 's');
1003
1004	if (newshell == NULL && arg != NULL)
1005		sh = arg->val;
1006	return shell_path(cnf->shelldir, cnf->shells, sh ? sh : cnf->shell_default);
1007}
1008
1009#define	SALTSIZE	32
1010
1011static char const chars[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ./";
1012
1013char           *
1014pw_pwcrypt(char *password)
1015{
1016	int             i;
1017	char            salt[SALTSIZE + 1];
1018	char		*cryptpw;
1019
1020	static char     buf[256];
1021
1022	/*
1023	 * Calculate a salt value
1024	 */
1025	for (i = 0; i < SALTSIZE; i++)
1026		salt[i] = chars[arc4random_uniform(sizeof(chars) - 1)];
1027	salt[SALTSIZE] = '\0';
1028
1029	cryptpw = crypt(password, salt);
1030	if (cryptpw == NULL)
1031		errx(EX_CONFIG, "crypt(3) failure");
1032	return strcpy(buf, cryptpw);
1033}
1034
1035
1036static char    *
1037pw_password(struct userconf * cnf, char const * user)
1038{
1039	int             i, l;
1040	char            pwbuf[32];
1041
1042	switch (cnf->default_password) {
1043	case -1:		/* Random password */
1044		l = (arc4random() % 8 + 8);	/* 8 - 16 chars */
1045		for (i = 0; i < l; i++)
1046			pwbuf[i] = chars[arc4random_uniform(sizeof(chars)-1)];
1047		pwbuf[i] = '\0';
1048
1049		/*
1050		 * We give this information back to the user
1051		 */
1052		if (conf.fd == -1 && !conf.dryrun) {
1053			if (isatty(STDOUT_FILENO))
1054				printf("Password for '%s' is: ", user);
1055			printf("%s\n", pwbuf);
1056			fflush(stdout);
1057		}
1058		break;
1059
1060	case -2:		/* No password at all! */
1061		return "";
1062
1063	case 0:		/* No login - default */
1064	default:
1065		return "*";
1066
1067	case 1:		/* user's name */
1068		strlcpy(pwbuf, user, sizeof(pwbuf));
1069		break;
1070	}
1071	return pw_pwcrypt(pwbuf);
1072}
1073
1074static int
1075pw_userdel(char *name, long id)
1076{
1077	struct passwd *pwd = NULL;
1078	char		 file[MAXPATHLEN];
1079	char		 home[MAXPATHLEN];
1080	uid_t		 uid;
1081	struct group	*gr, *grp;
1082	char		 grname[LOGNAMESIZE];
1083	int		 rc;
1084	struct stat	 st;
1085
1086	if (id < 0 && name == NULL)
1087		errx(EX_DATAERR, "username or id required");
1088
1089	pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
1090	if (pwd == NULL) {
1091		if (name == NULL)
1092			errx(EX_NOUSER, "no such uid `%ld'", id);
1093		errx(EX_NOUSER, "no such user `%s'", name);
1094	}
1095	uid = pwd->pw_uid;
1096	if (name == NULL)
1097		name = pwd->pw_name;
1098
1099	if (strcmp(pwd->pw_name, "root") == 0)
1100		errx(EX_DATAERR, "cannot remove user 'root'");
1101
1102	if (!PWALTDIR()) {
1103		/*
1104		 * Remove opie record from /etc/opiekeys
1105		*/
1106
1107		rmopie(pwd->pw_name);
1108
1109		/*
1110		 * Remove crontabs
1111		 */
1112		snprintf(file, sizeof(file), "/var/cron/tabs/%s", pwd->pw_name);
1113		if (access(file, F_OK) == 0) {
1114			snprintf(file, sizeof(file), "crontab -u %s -r", pwd->pw_name);
1115			system(file);
1116		}
1117	}
1118	/*
1119	 * Save these for later, since contents of pwd may be
1120	 * invalidated by deletion
1121	 */
1122	snprintf(file, sizeof(file), "%s/%s", _PATH_MAILDIR, pwd->pw_name);
1123	strlcpy(home, pwd->pw_dir, sizeof(home));
1124	gr = GETGRGID(pwd->pw_gid);
1125	if (gr != NULL)
1126		strlcpy(grname, gr->gr_name, LOGNAMESIZE);
1127	else
1128		grname[0] = '\0';
1129
1130	rc = delpwent(pwd);
1131	if (rc == -1)
1132		err(EX_IOERR, "user '%s' does not exist", pwd->pw_name);
1133	else if (rc != 0)
1134		err(EX_IOERR, "passwd update");
1135
1136	if (conf.userconf->nispasswd && *conf.userconf->nispasswd=='/') {
1137		rc = delnispwent(conf.userconf->nispasswd, name);
1138		if (rc == -1)
1139			warnx("WARNING: user '%s' does not exist in NIS passwd",
1140			    pwd->pw_name);
1141		else if (rc != 0)
1142			warn("WARNING: NIS passwd update");
1143		/* non-fatal */
1144	}
1145
1146	grp = GETGRNAM(name);
1147	if (grp != NULL &&
1148	    (grp->gr_mem == NULL || *grp->gr_mem == NULL) &&
1149	    strcmp(name, grname) == 0)
1150		delgrent(GETGRNAM(name));
1151	SETGRENT();
1152	while ((grp = GETGRENT()) != NULL) {
1153		int i, j;
1154		char group[MAXLOGNAME];
1155		if (grp->gr_mem == NULL)
1156			continue;
1157
1158		for (i = 0; grp->gr_mem[i] != NULL; i++) {
1159			if (strcmp(grp->gr_mem[i], name) != 0)
1160				continue;
1161
1162			for (j = i; grp->gr_mem[j] != NULL; j++)
1163				grp->gr_mem[j] = grp->gr_mem[j+1];
1164			strlcpy(group, grp->gr_name, MAXLOGNAME);
1165			chggrent(group, grp);
1166		}
1167	}
1168	ENDGRENT();
1169
1170	pw_log(conf.userconf, M_DELETE, W_USER, "%s(%u) account removed", name,
1171	    uid);
1172
1173	if (!PWALTDIR()) {
1174		/*
1175		 * Remove mail file
1176		 */
1177		remove(file);
1178
1179		/*
1180		 * Remove at jobs
1181		 */
1182		if (getpwuid(uid) == NULL)
1183			rmat(uid);
1184
1185		/*
1186		 * Remove home directory and contents
1187		 */
1188		if (conf.deletehome && *home == '/' && getpwuid(uid) == NULL &&
1189		    stat(home, &st) != -1) {
1190			rm_r(home, uid);
1191			pw_log(conf.userconf, M_DELETE, W_USER, "%s(%u) home '%s' %sremoved",
1192			       name, uid, home,
1193			       stat(home, &st) == -1 ? "" : "not completely ");
1194		}
1195	}
1196
1197	return (EXIT_SUCCESS);
1198}
1199
1200static int
1201print_user(struct passwd * pwd)
1202{
1203	if (!conf.pretty) {
1204		char            *buf;
1205
1206		buf = conf.v7 ? pw_make_v7(pwd) : pw_make(pwd);
1207		printf("%s\n", buf);
1208		free(buf);
1209	} else {
1210		int		j;
1211		char           *p;
1212		struct group   *grp = GETGRGID(pwd->pw_gid);
1213		char            uname[60] = "User &", office[60] = "[None]",
1214		                wphone[60] = "[None]", hphone[60] = "[None]";
1215		char		acexpire[32] = "[None]", pwexpire[32] = "[None]";
1216		struct tm *    tptr;
1217
1218		if ((p = strtok(pwd->pw_gecos, ",")) != NULL) {
1219			strlcpy(uname, p, sizeof(uname));
1220			if ((p = strtok(NULL, ",")) != NULL) {
1221				strlcpy(office, p, sizeof(office));
1222				if ((p = strtok(NULL, ",")) != NULL) {
1223					strlcpy(wphone, p, sizeof(wphone));
1224					if ((p = strtok(NULL, "")) != NULL) {
1225						strlcpy(hphone, p,
1226						    sizeof(hphone));
1227					}
1228				}
1229			}
1230		}
1231		/*
1232		 * Handle '&' in gecos field
1233		 */
1234		if ((p = strchr(uname, '&')) != NULL) {
1235			int             l = strlen(pwd->pw_name);
1236			int             m = strlen(p);
1237
1238			memmove(p + l, p + 1, m);
1239			memmove(p, pwd->pw_name, l);
1240			*p = (char) toupper((unsigned char)*p);
1241		}
1242		if (pwd->pw_expire > (time_t)0 && (tptr = localtime(&pwd->pw_expire)) != NULL)
1243			strftime(acexpire, sizeof acexpire, "%c", tptr);
1244		if (pwd->pw_change > (time_t)0 && (tptr = localtime(&pwd->pw_change)) != NULL)
1245			strftime(pwexpire, sizeof pwexpire, "%c", tptr);
1246		printf("Login Name: %-15s   #%-12u Group: %-15s   #%u\n"
1247		       " Full Name: %s\n"
1248		       "      Home: %-26.26s      Class: %s\n"
1249		       "     Shell: %-26.26s     Office: %s\n"
1250		       "Work Phone: %-26.26s Home Phone: %s\n"
1251		       "Acc Expire: %-26.26s Pwd Expire: %s\n",
1252		       pwd->pw_name, pwd->pw_uid,
1253		       grp ? grp->gr_name : "(invalid)", pwd->pw_gid,
1254		       uname, pwd->pw_dir, pwd->pw_class,
1255		       pwd->pw_shell, office, wphone, hphone,
1256		       acexpire, pwexpire);
1257	        SETGRENT();
1258		j = 0;
1259		while ((grp=GETGRENT()) != NULL)
1260		{
1261			int     i = 0;
1262			if (grp->gr_mem != NULL) {
1263				while (grp->gr_mem[i] != NULL)
1264				{
1265					if (strcmp(grp->gr_mem[i], pwd->pw_name)==0)
1266					{
1267						printf(j++ == 0 ? "    Groups: %s" : ",%s", grp->gr_name);
1268						break;
1269					}
1270					++i;
1271				}
1272			}
1273		}
1274		ENDGRENT();
1275		printf("%s", j ? "\n" : "");
1276	}
1277	return EXIT_SUCCESS;
1278}
1279
1280char *
1281pw_checkname(char *name, int gecos)
1282{
1283	char showch[8];
1284	const char *badchars, *ch, *showtype;
1285	int reject;
1286
1287	ch = name;
1288	reject = 0;
1289	if (gecos) {
1290		/* See if the name is valid as a gecos (comment) field. */
1291		badchars = ":!@";
1292		showtype = "gecos field";
1293	} else {
1294		/* See if the name is valid as a userid or group. */
1295		badchars = " ,\t:+&#%$^()!@~*?<>=|\\/\"";
1296		showtype = "userid/group name";
1297		/* Userids and groups can not have a leading '-'. */
1298		if (*ch == '-')
1299			reject = 1;
1300	}
1301	if (!reject) {
1302		while (*ch) {
1303			if (strchr(badchars, *ch) != NULL || *ch < ' ' ||
1304			    *ch == 127) {
1305				reject = 1;
1306				break;
1307			}
1308			/* 8-bit characters are only allowed in GECOS fields */
1309			if (!gecos && (*ch & 0x80)) {
1310				reject = 1;
1311				break;
1312			}
1313			ch++;
1314		}
1315	}
1316	/*
1317	 * A `$' is allowed as the final character for userids and groups,
1318	 * mainly for the benefit of samba.
1319	 */
1320	if (reject && !gecos) {
1321		if (*ch == '$' && *(ch + 1) == '\0') {
1322			reject = 0;
1323			ch++;
1324		}
1325	}
1326	if (reject) {
1327		snprintf(showch, sizeof(showch), (*ch >= ' ' && *ch < 127)
1328		    ? "`%c'" : "0x%02x", *ch);
1329		errx(EX_DATAERR, "invalid character %s at position %td in %s",
1330		    showch, (ch - name), showtype);
1331	}
1332	if (!gecos && (ch - name) > LOGNAMESIZE)
1333		errx(EX_DATAERR, "name too long `%s' (max is %d)", name,
1334		    LOGNAMESIZE);
1335
1336	return (name);
1337}
1338
1339
1340static void
1341rmat(uid_t uid)
1342{
1343	DIR            *d = opendir("/var/at/jobs");
1344
1345	if (d != NULL) {
1346		struct dirent  *e;
1347
1348		while ((e = readdir(d)) != NULL) {
1349			struct stat     st;
1350
1351			if (strncmp(e->d_name, ".lock", 5) != 0 &&
1352			    stat(e->d_name, &st) == 0 &&
1353			    !S_ISDIR(st.st_mode) &&
1354			    st.st_uid == uid) {
1355				char            tmp[MAXPATHLEN];
1356
1357				snprintf(tmp, sizeof(tmp), "/usr/bin/atrm %s", e->d_name);
1358				system(tmp);
1359			}
1360		}
1361		closedir(d);
1362	}
1363}
1364
1365static void
1366rmopie(char const * name)
1367{
1368	static const char etcopie[] = "/etc/opiekeys";
1369	FILE   *fp = fopen(etcopie, "r+");
1370
1371	if (fp != NULL) {
1372		char	tmp[1024];
1373		off_t	atofs = 0;
1374		int	length = strlen(name);
1375
1376		while (fgets(tmp, sizeof tmp, fp) != NULL) {
1377			if (strncmp(name, tmp, length) == 0 && tmp[length]==' ') {
1378				if (fseek(fp, atofs, SEEK_SET) == 0) {
1379					fwrite("#", 1, 1, fp);	/* Comment username out */
1380				}
1381				break;
1382			}
1383			atofs = ftell(fp);
1384		}
1385		/*
1386		 * If we got an error of any sort, don't update!
1387		 */
1388		fclose(fp);
1389	}
1390}
1391
1392