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