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