xref: /freebsd/usr.sbin/pwd_mkdb/pwd_mkdb.c (revision b78ee15e9f04ae15c3e1200df974473167524d17)
1 /*-
2  * Copyright (c) 1991, 1993, 1994
3  *	The Regents of the University of California.  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  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #if 0
31 #ifndef lint
32 static const char copyright[] =
33 "@(#) Copyright (c) 1991, 1993, 1994\n\
34 	The Regents of the University of California.  All rights reserved.\n";
35 #endif /* not lint */
36 
37 #ifndef lint
38 static char sccsid[] = "@(#)pwd_mkdb.c	8.5 (Berkeley) 4/20/94";
39 #endif /* not lint */
40 #endif
41 
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
44 
45 #include <sys/param.h>
46 #include <sys/endian.h>
47 #include <sys/stat.h>
48 #include <arpa/inet.h>
49 
50 #include <db.h>
51 #include <err.h>
52 #include <errno.h>
53 #include <fcntl.h>
54 #include <limits.h>
55 #include <pwd.h>
56 #include <signal.h>
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #include <unistd.h>
61 
62 #include "pw_scan.h"
63 
64 #define	INSECURE	1
65 #define	SECURE		2
66 #define	PERM_INSECURE	(S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)
67 #define	PERM_SECURE	(S_IRUSR|S_IWUSR)
68 #define LEGACY_VERSION(x)  _PW_VERSIONED(x, 3)
69 #define CURRENT_VERSION(x) _PW_VERSIONED(x, 4)
70 
71 static HASHINFO openinfo = {
72 	4096,		/* bsize */
73 	32,		/* ffactor */
74 	256,		/* nelem */
75 	2048 * 1024,	/* cachesize */
76 	NULL,		/* hash() */
77 	BYTE_ORDER	/* lorder */
78 };
79 
80 static enum state { FILE_INSECURE, FILE_SECURE, FILE_ORIG } clean;
81 static struct passwd pwd;			/* password structure */
82 static char *pname;				/* password file name */
83 static char prefix[MAXPATHLEN];
84 
85 static int is_comment;	/* flag for comments */
86 static char line[LINE_MAX];
87 
88 void	cleanup(void);
89 void	error(const char *);
90 void	cp(char *, char *, mode_t mode);
91 void	mv(char *, char *);
92 int	scan(FILE *, struct passwd *);
93 static void	usage(void);
94 
95 int
96 main(int argc, char *argv[])
97 {
98 	static char verskey[] = _PWD_VERSION_KEY;
99 	char version = _PWD_CURRENT_VERSION;
100 	DB *dp, *sdp, *pw_db;
101 	DBT data, sdata, key;
102 	FILE *fp, *oldfp;
103 	sigset_t set;
104 	int ch, cnt, ypcnt, makeold, tfd, yp_enabled = 0;
105 	unsigned int len;
106 	uint32_t store;
107 	const char *t;
108 	char *p;
109 	char buf[MAX(MAXPATHLEN, LINE_MAX * 2)], tbuf[1024];
110 	char sbuf[MAX(MAXPATHLEN, LINE_MAX * 2)];
111 	char buf2[MAXPATHLEN];
112 	char sbuf2[MAXPATHLEN];
113 	char *username;
114 	u_int method, methoduid;
115 	int Cflag, dflag, iflag, lflag;
116 	int nblock = 0;
117 
118 	iflag = dflag = Cflag = lflag = 0;
119 	strcpy(prefix, _PATH_PWD);
120 	makeold = 0;
121 	username = NULL;
122 	oldfp = NULL;
123 	while ((ch = getopt(argc, argv, "BCLlNd:ips:u:v")) != -1)
124 		switch(ch) {
125 		case 'B':			/* big-endian output */
126 			openinfo.lorder = BIG_ENDIAN;
127 			break;
128 		case 'C':                       /* verify only */
129 			Cflag = 1;
130 			break;
131 		case 'l':			/* generate legacy entries */
132 			lflag = 1;
133 			break;
134 		case 'L':			/* little-endian output */
135 			openinfo.lorder = LITTLE_ENDIAN;
136 			break;
137 		case 'N':			/* do not wait for lock	*/
138 			nblock = LOCK_NB;	/* will fail if locked */
139 			break;
140 		case 'd':
141 			dflag++;
142 			strlcpy(prefix, optarg, sizeof(prefix));
143 			break;
144 		case 'i':
145 			iflag++;
146 			break;
147 		case 'p':			/* create V7 "file.orig" */
148 			makeold = 1;
149 			break;
150 		case 's':			/* change default cachesize */
151 			openinfo.cachesize = atoi(optarg) * 1024 * 1024;
152 			break;
153 		case 'u':			/* only update this record */
154 			username = optarg;
155 			break;
156 		case 'v':                       /* backward compatible */
157 			break;
158 		default:
159 			usage();
160 		}
161 	argc -= optind;
162 	argv += optind;
163 
164 	if (argc != 1 || (username && (*username == '+' || *username == '-')))
165 		usage();
166 
167 	/*
168 	 * This could be changed to allow the user to interrupt.
169 	 * Probably not worth the effort.
170 	 */
171 	sigemptyset(&set);
172 	sigaddset(&set, SIGTSTP);
173 	sigaddset(&set, SIGHUP);
174 	sigaddset(&set, SIGINT);
175 	sigaddset(&set, SIGQUIT);
176 	sigaddset(&set, SIGTERM);
177 	(void)sigprocmask(SIG_BLOCK, &set, (sigset_t *)NULL);
178 
179 	/* We don't care what the user wants. */
180 	(void)umask(0);
181 
182 	pname = *argv;
183 
184 	/*
185 	 * Open and lock the original password file.  We have to check
186 	 * the hardlink count after we get the lock to handle any potential
187 	 * unlink/rename race.
188 	 *
189 	 * This lock is necessary when someone runs pwd_mkdb manually, directly
190 	 * on master.passwd, to handle the case where a user might try to
191 	 * change his password while pwd_mkdb is running.
192 	 */
193 	for (;;) {
194 		struct stat st;
195 
196 		if (!(fp = fopen(pname, "r")))
197 			error(pname);
198 		if (flock(fileno(fp), LOCK_EX|nblock) < 0 && !(dflag && iflag))
199 			error("flock");
200 		if (fstat(fileno(fp), &st) < 0)
201 			error(pname);
202 		if (st.st_nlink != 0)
203 			break;
204 		fclose(fp);
205 		fp = NULL;
206 	}
207 
208 	/* check only if password database is valid */
209 	if (Cflag) {
210 		while (scan(fp, &pwd))
211 			if (!is_comment && strlen(pwd.pw_name) >= MAXLOGNAME) {
212 				warnx("%s: username too long", pwd.pw_name);
213 				exit(1);
214 			}
215 		exit(0);
216 	}
217 
218 	/* Open the temporary insecure password database. */
219 	(void)snprintf(buf, sizeof(buf), "%s/%s.tmp", prefix, _MP_DB);
220 	(void)snprintf(sbuf, sizeof(sbuf), "%s/%s.tmp", prefix, _SMP_DB);
221 	if (username) {
222 		int use_version;
223 
224 		(void)snprintf(buf2, sizeof(buf2), "%s/%s", prefix, _MP_DB);
225 		(void)snprintf(sbuf2, sizeof(sbuf2), "%s/%s", prefix, _SMP_DB);
226 
227 		clean = FILE_INSECURE;
228 		cp(buf2, buf, PERM_INSECURE);
229 		dp = dbopen(buf,
230 		    O_RDWR|O_EXCL, PERM_INSECURE, DB_HASH, &openinfo);
231 		if (dp == NULL)
232 			error(buf);
233 
234 		clean = FILE_SECURE;
235 		cp(sbuf2, sbuf, PERM_SECURE);
236 		sdp = dbopen(sbuf,
237 		    O_RDWR|O_EXCL, PERM_SECURE, DB_HASH, &openinfo);
238 		if (sdp == NULL)
239 			error(sbuf);
240 
241 		/*
242 		 * Do some trouble to check if we should store this users
243 		 * uid. Don't use getpwnam/getpwuid as that interferes
244 		 * with NIS.
245 		 */
246 		pw_db = dbopen(_PATH_MP_DB, O_RDONLY, 0, DB_HASH, NULL);
247 		if (!pw_db)
248 			error(_MP_DB);
249 
250 		key.data = verskey;
251 		key.size = sizeof(verskey)-1;
252 		if ((pw_db->get)(pw_db, &key, &data, 0) == 0)
253 			use_version = *(unsigned char *)data.data;
254 		else
255 			use_version = 3;
256 		buf[0] = _PW_VERSIONED(_PW_KEYBYNAME, use_version);
257 		len = strlen(username);
258 
259 		/* Only check that username fits in buffer */
260 		memmove(buf + 1, username, MIN(len, sizeof(buf) - 1));
261 		key.data = (u_char *)buf;
262 		key.size = len + 1;
263 		if ((pw_db->get)(pw_db, &key, &data, 0) == 0) {
264 			p = (char *)data.data;
265 
266 			/* jump over pw_name and pw_passwd, to get to pw_uid */
267 			while (*p++)
268 				;
269 			while (*p++)
270 				;
271 
272 			buf[0] = _PW_VERSIONED(_PW_KEYBYUID, use_version);
273 			memmove(buf + 1, p, sizeof(store));
274 			key.data = (u_char *)buf;
275 			key.size = sizeof(store) + 1;
276 
277 			if ((pw_db->get)(pw_db, &key, &data, 0) == 0) {
278 				/* First field of data.data holds pw_pwname */
279 				if (!strcmp(data.data, username))
280 					methoduid = 0;
281 				else
282 					methoduid = R_NOOVERWRITE;
283 			} else {
284 				methoduid = R_NOOVERWRITE;
285 			}
286 		} else {
287 			methoduid = R_NOOVERWRITE;
288 		}
289 		if ((pw_db->close)(pw_db))
290 			error("close pw_db");
291 		method = 0;
292 	} else {
293 		dp = dbopen(buf,
294 		    O_RDWR|O_CREAT|O_EXCL, PERM_INSECURE, DB_HASH, &openinfo);
295 		if (dp == NULL)
296 			error(buf);
297 		clean = FILE_INSECURE;
298 
299 		sdp = dbopen(sbuf,
300 		    O_RDWR|O_CREAT|O_EXCL, PERM_SECURE, DB_HASH, &openinfo);
301 		if (sdp == NULL)
302 			error(sbuf);
303 		clean = FILE_SECURE;
304 
305 		method = R_NOOVERWRITE;
306 		methoduid = R_NOOVERWRITE;
307 	}
308 
309 	/*
310 	 * Open file for old password file.  Minor trickiness -- don't want to
311 	 * chance the file already existing, since someone (stupidly) might
312 	 * still be using this for permission checking.  So, open it first and
313 	 * fdopen the resulting fd.  The resulting file should be readable by
314 	 * everyone.
315 	 */
316 	if (makeold) {
317 		(void)snprintf(buf, sizeof(buf), "%s.orig", pname);
318 		if ((tfd = open(buf,
319 		    O_WRONLY|O_CREAT|O_EXCL, PERM_INSECURE)) < 0)
320 			error(buf);
321 		if ((oldfp = fdopen(tfd, "w")) == NULL)
322 			error(buf);
323 		clean = FILE_ORIG;
324 	}
325 
326 	/*
327 	 * The databases actually contain three copies of the original data.
328 	 * Each password file entry is converted into a rough approximation
329 	 * of a ``struct passwd'', with the strings placed inline.  This
330 	 * object is then stored as the data for three separate keys.  The
331 	 * first key * is the pw_name field prepended by the _PW_KEYBYNAME
332 	 * character.  The second key is the pw_uid field prepended by the
333 	 * _PW_KEYBYUID character.  The third key is the line number in the
334 	 * original file prepended by the _PW_KEYBYNUM character.  (The special
335 	 * characters are prepended to ensure that the keys do not collide.)
336 	 */
337 	/* In order to transition this file into a machine-independent
338 	 * form, we have to change the format of entries.  However, since
339 	 * older binaries will still expect the old MD format entries, we
340 	 * create those as usual and use versioned tags for the new entries.
341 	 */
342 	if (username == NULL) {
343 		/* Do not add the VERSION tag when updating a single
344 		 * user.  When operating on `old format' databases, this
345 		 * would result in applications `seeing' only the updated
346 		 * entries.
347 		 */
348 		key.data = verskey;
349 		key.size = sizeof(verskey)-1;
350 		data.data = &version;
351 		data.size = 1;
352 		if ((dp->put)(dp, &key, &data, 0) == -1)
353 			error("put");
354 		if ((dp->put)(sdp, &key, &data, 0) == -1)
355 			error("put");
356 	}
357 	ypcnt = 0;
358 	data.data = (u_char *)buf;
359 	sdata.data = (u_char *)sbuf;
360 	key.data = (u_char *)tbuf;
361 	for (cnt = 1; scan(fp, &pwd); ++cnt) {
362 		if (!is_comment &&
363 		    (pwd.pw_name[0] == '+' || pwd.pw_name[0] == '-')) {
364 			yp_enabled = 1;
365 			ypcnt++;
366 		}
367 		if (is_comment)
368 			--cnt;
369 #define	COMPACT(e)	t = e; while ((*p++ = *t++));
370 #define SCALAR(e)	store = htonl((uint32_t)(e));      \
371 			memmove(p, &store, sizeof(store)); \
372 			p += sizeof(store);
373 #define	LSCALAR(e)	store = HTOL((uint32_t)(e));       \
374 			memmove(p, &store, sizeof(store)); \
375 			p += sizeof(store);
376 #define	HTOL(e)		(openinfo.lorder == BYTE_ORDER ? \
377 			(uint32_t)(e) : \
378 			bswap32((uint32_t)(e)))
379 		if (!is_comment &&
380 		    (!username || (strcmp(username, pwd.pw_name) == 0))) {
381 			/* Create insecure data. */
382 			p = buf;
383 			COMPACT(pwd.pw_name);
384 			COMPACT("*");
385 			SCALAR(pwd.pw_uid);
386 			SCALAR(pwd.pw_gid);
387 			SCALAR(pwd.pw_change);
388 			COMPACT(pwd.pw_class);
389 			COMPACT(pwd.pw_gecos);
390 			COMPACT(pwd.pw_dir);
391 			COMPACT(pwd.pw_shell);
392 			SCALAR(pwd.pw_expire);
393 			SCALAR(pwd.pw_fields);
394 			data.size = p - buf;
395 
396 			/* Create secure data. */
397 			p = sbuf;
398 			COMPACT(pwd.pw_name);
399 			COMPACT(pwd.pw_passwd);
400 			SCALAR(pwd.pw_uid);
401 			SCALAR(pwd.pw_gid);
402 			SCALAR(pwd.pw_change);
403 			COMPACT(pwd.pw_class);
404 			COMPACT(pwd.pw_gecos);
405 			COMPACT(pwd.pw_dir);
406 			COMPACT(pwd.pw_shell);
407 			SCALAR(pwd.pw_expire);
408 			SCALAR(pwd.pw_fields);
409 			sdata.size = p - sbuf;
410 
411 			/* Store insecure by name. */
412 			tbuf[0] = CURRENT_VERSION(_PW_KEYBYNAME);
413 			len = strlen(pwd.pw_name);
414 			memmove(tbuf + 1, pwd.pw_name, len);
415 			key.size = len + 1;
416 			if ((dp->put)(dp, &key, &data, method) == -1)
417 				error("put");
418 
419 			/* Store insecure by number. */
420 			tbuf[0] = CURRENT_VERSION(_PW_KEYBYNUM);
421 			store = htonl(cnt);
422 			memmove(tbuf + 1, &store, sizeof(store));
423 			key.size = sizeof(store) + 1;
424 			if ((dp->put)(dp, &key, &data, method) == -1)
425 				error("put");
426 
427 			/* Store insecure by uid. */
428 			tbuf[0] = CURRENT_VERSION(_PW_KEYBYUID);
429 			store = htonl(pwd.pw_uid);
430 			memmove(tbuf + 1, &store, sizeof(store));
431 			key.size = sizeof(store) + 1;
432 			if ((dp->put)(dp, &key, &data, methoduid) == -1)
433 				error("put");
434 
435 			/* Store secure by name. */
436 			tbuf[0] = CURRENT_VERSION(_PW_KEYBYNAME);
437 			len = strlen(pwd.pw_name);
438 			memmove(tbuf + 1, pwd.pw_name, len);
439 			key.size = len + 1;
440 			if ((sdp->put)(sdp, &key, &sdata, method) == -1)
441 				error("put");
442 
443 			/* Store secure by number. */
444 			tbuf[0] = CURRENT_VERSION(_PW_KEYBYNUM);
445 			store = htonl(cnt);
446 			memmove(tbuf + 1, &store, sizeof(store));
447 			key.size = sizeof(store) + 1;
448 			if ((sdp->put)(sdp, &key, &sdata, method) == -1)
449 				error("put");
450 
451 			/* Store secure by uid. */
452 			tbuf[0] = CURRENT_VERSION(_PW_KEYBYUID);
453 			store = htonl(pwd.pw_uid);
454 			memmove(tbuf + 1, &store, sizeof(store));
455 			key.size = sizeof(store) + 1;
456 			if ((sdp->put)(sdp, &key, &sdata, methoduid) == -1)
457 				error("put");
458 
459 			/* Store insecure and secure special plus and special minus */
460 			if (pwd.pw_name[0] == '+' || pwd.pw_name[0] == '-') {
461 				tbuf[0] = CURRENT_VERSION(_PW_KEYYPBYNUM);
462 				store = htonl(ypcnt);
463 				memmove(tbuf + 1, &store, sizeof(store));
464 				key.size = sizeof(store) + 1;
465 				if ((dp->put)(dp, &key, &data, method) == -1)
466 					error("put");
467 				if ((sdp->put)(sdp, &key, &sdata, method) == -1)
468 					error("put");
469 			}
470 
471 			if (lflag) {
472 				/* Create insecure data. (legacy version) */
473 				p = buf;
474 				COMPACT(pwd.pw_name);
475 				COMPACT("*");
476 				LSCALAR(pwd.pw_uid);
477 				LSCALAR(pwd.pw_gid);
478 				LSCALAR(pwd.pw_change);
479 				COMPACT(pwd.pw_class);
480 				COMPACT(pwd.pw_gecos);
481 				COMPACT(pwd.pw_dir);
482 				COMPACT(pwd.pw_shell);
483 				LSCALAR(pwd.pw_expire);
484 				LSCALAR(pwd.pw_fields);
485 				data.size = p - buf;
486 
487 				/* Create secure data. (legacy version) */
488 				p = sbuf;
489 				COMPACT(pwd.pw_name);
490 				COMPACT(pwd.pw_passwd);
491 				LSCALAR(pwd.pw_uid);
492 				LSCALAR(pwd.pw_gid);
493 				LSCALAR(pwd.pw_change);
494 				COMPACT(pwd.pw_class);
495 				COMPACT(pwd.pw_gecos);
496 				COMPACT(pwd.pw_dir);
497 				COMPACT(pwd.pw_shell);
498 				LSCALAR(pwd.pw_expire);
499 				LSCALAR(pwd.pw_fields);
500 				sdata.size = p - sbuf;
501 
502 				/* Store insecure by name. */
503 				tbuf[0] = LEGACY_VERSION(_PW_KEYBYNAME);
504 				len = strlen(pwd.pw_name);
505 				memmove(tbuf + 1, pwd.pw_name, len);
506 				key.size = len + 1;
507 				if ((dp->put)(dp, &key, &data, method) == -1)
508 					error("put");
509 
510 				/* Store insecure by number. */
511 				tbuf[0] = LEGACY_VERSION(_PW_KEYBYNUM);
512 				store = HTOL(cnt);
513 				memmove(tbuf + 1, &store, sizeof(store));
514 				key.size = sizeof(store) + 1;
515 				if ((dp->put)(dp, &key, &data, method) == -1)
516 					error("put");
517 
518 				/* Store insecure by uid. */
519 				tbuf[0] = LEGACY_VERSION(_PW_KEYBYUID);
520 				store = HTOL(pwd.pw_uid);
521 				memmove(tbuf + 1, &store, sizeof(store));
522 				key.size = sizeof(store) + 1;
523 				if ((dp->put)(dp, &key, &data, methoduid) == -1)
524 					error("put");
525 
526 				/* Store secure by name. */
527 				tbuf[0] = LEGACY_VERSION(_PW_KEYBYNAME);
528 				len = strlen(pwd.pw_name);
529 				memmove(tbuf + 1, pwd.pw_name, len);
530 				key.size = len + 1;
531 				if ((sdp->put)(sdp, &key, &sdata, method) == -1)
532 					error("put");
533 
534 				/* Store secure by number. */
535 				tbuf[0] = LEGACY_VERSION(_PW_KEYBYNUM);
536 				store = HTOL(cnt);
537 				memmove(tbuf + 1, &store, sizeof(store));
538 				key.size = sizeof(store) + 1;
539 				if ((sdp->put)(sdp, &key, &sdata, method) == -1)
540 					error("put");
541 
542 				/* Store secure by uid. */
543 				tbuf[0] = LEGACY_VERSION(_PW_KEYBYUID);
544 				store = HTOL(pwd.pw_uid);
545 				memmove(tbuf + 1, &store, sizeof(store));
546 				key.size = sizeof(store) + 1;
547 				if ((sdp->put)(sdp, &key, &sdata, methoduid) == -1)
548 					error("put");
549 
550 				/* Store insecure and secure special plus and special minus */
551 				if (pwd.pw_name[0] == '+' || pwd.pw_name[0] == '-') {
552 					tbuf[0] = LEGACY_VERSION(_PW_KEYYPBYNUM);
553 					store = HTOL(ypcnt);
554 					memmove(tbuf + 1, &store, sizeof(store));
555 					key.size = sizeof(store) + 1;
556 					if ((dp->put)(dp, &key, &data, method) == -1)
557 						error("put");
558 					if ((sdp->put)(sdp, &key, &sdata, method) == -1)
559 						error("put");
560 				}
561 			}
562 		}
563 		/* Create original format password file entry */
564 		if (is_comment && makeold){	/* copy comments */
565 			if (fprintf(oldfp, "%s\n", line) < 0)
566 				error("write old");
567 		} else if (makeold) {
568 			char uidstr[20];
569 			char gidstr[20];
570 
571 			snprintf(uidstr, sizeof(uidstr), "%u", pwd.pw_uid);
572 			snprintf(gidstr, sizeof(gidstr), "%u", pwd.pw_gid);
573 
574 			if (fprintf(oldfp, "%s:*:%s:%s:%s:%s:%s\n",
575 			    pwd.pw_name, pwd.pw_fields & _PWF_UID ? uidstr : "",
576 			    pwd.pw_fields & _PWF_GID ? gidstr : "",
577 			    pwd.pw_gecos, pwd.pw_dir, pwd.pw_shell) < 0)
578 				error("write old");
579 		}
580 	}
581 	/* If YP enabled, set flag. */
582 	if (yp_enabled) {
583 		buf[0] = yp_enabled + 2;
584 		data.size = 1;
585 		key.size = 1;
586 		tbuf[0] = CURRENT_VERSION(_PW_KEYYPENABLED);
587 		if ((dp->put)(dp, &key, &data, method) == -1)
588 			error("put");
589 		if ((sdp->put)(sdp, &key, &data, method) == -1)
590 			error("put");
591 		if (lflag) {
592 			tbuf[0] = LEGACY_VERSION(_PW_KEYYPENABLED);
593 			key.size = 1;
594 			if ((dp->put)(dp, &key, &data, method) == -1)
595 				error("put");
596 			if ((sdp->put)(sdp, &key, &data, method) == -1)
597 				error("put");
598 		}
599 	}
600 
601 	if ((dp->close)(dp) == -1)
602 		error("close");
603 	if ((sdp->close)(sdp) == -1)
604 		error("close");
605 	if (makeold) {
606 		(void)fflush(oldfp);
607 		if (fclose(oldfp) == EOF)
608 			error("close old");
609 	}
610 
611 	/* Set master.passwd permissions, in case caller forgot. */
612 	(void)fchmod(fileno(fp), S_IRUSR|S_IWUSR);
613 
614 	/* Install as the real password files. */
615 	(void)snprintf(buf, sizeof(buf), "%s/%s.tmp", prefix, _MP_DB);
616 	(void)snprintf(buf2, sizeof(buf2), "%s/%s", prefix, _MP_DB);
617 	mv(buf, buf2);
618 	(void)snprintf(buf, sizeof(buf), "%s/%s.tmp", prefix, _SMP_DB);
619 	(void)snprintf(buf2, sizeof(buf2), "%s/%s", prefix, _SMP_DB);
620 	mv(buf, buf2);
621 	if (makeold) {
622 		(void)snprintf(buf2, sizeof(buf2), "%s/%s", prefix, _PASSWD);
623 		(void)snprintf(buf, sizeof(buf), "%s.orig", pname);
624 		mv(buf, buf2);
625 	}
626 	/*
627 	 * Move the master password LAST -- chpass(1), passwd(1) and vipw(8)
628 	 * all use flock(2) on it to block other incarnations of themselves.
629 	 * The rename means that everything is unlocked, as the original file
630 	 * can no longer be accessed.
631 	 */
632 	(void)snprintf(buf, sizeof(buf), "%s/%s", prefix, _MASTERPASSWD);
633 	mv(pname, buf);
634 
635 	/*
636 	 * Close locked password file after rename()
637 	 */
638 	if (fclose(fp) == EOF)
639 		error("close fp");
640 
641 	exit(0);
642 }
643 
644 int
645 scan(FILE *fp, struct passwd *pw)
646 {
647 	static int lcnt;
648 	size_t len;
649 	char *p;
650 
651 	p = fgetln(fp, &len);
652 	if (p == NULL)
653 		return (0);
654 	++lcnt;
655 	/*
656 	 * ``... if I swallow anything evil, put your fingers down my
657 	 * throat...''
658 	 *	-- The Who
659 	 */
660 	if (len > 0 && p[len - 1] == '\n')
661 		len--;
662 	if (len >= sizeof(line) - 1) {
663 		warnx("line #%d too long", lcnt);
664 		goto fmt;
665 	}
666 	memcpy(line, p, len);
667 	line[len] = '\0';
668 
669 	/*
670 	 * Ignore comments: ^[ \t]*#
671 	 */
672 	for (p = line; *p != '\0'; p++)
673 		if (*p != ' ' && *p != '\t')
674 			break;
675 	if (*p == '#' || *p == '\0') {
676 		is_comment = 1;
677 		return(1);
678 	} else
679 		is_comment = 0;
680 
681 	if (!__pw_scan(line, pw, _PWSCAN_WARN|_PWSCAN_MASTER)) {
682 		warnx("at line #%d", lcnt);
683 fmt:		errno = EFTYPE;	/* XXX */
684 		error(pname);
685 	}
686 
687 	return (1);
688 }
689 
690 void
691 cp(char *from, char *to, mode_t mode)
692 {
693 	static char buf[MAXBSIZE];
694 	int from_fd, rcount, to_fd, wcount;
695 
696 	if ((from_fd = open(from, O_RDONLY, 0)) < 0)
697 		error(from);
698 	if ((to_fd = open(to, O_WRONLY|O_CREAT|O_EXCL, mode)) < 0)
699 		error(to);
700 	while ((rcount = read(from_fd, buf, MAXBSIZE)) > 0) {
701 		wcount = write(to_fd, buf, rcount);
702 		if (rcount != wcount || wcount == -1) {
703 			int sverrno = errno;
704 
705 			(void)snprintf(buf, sizeof(buf), "%s to %s", from, to);
706 			errno = sverrno;
707 			error(buf);
708 		}
709 	}
710 	if (rcount < 0) {
711 		int sverrno = errno;
712 
713 		(void)snprintf(buf, sizeof(buf), "%s to %s", from, to);
714 		errno = sverrno;
715 		error(buf);
716 	}
717 }
718 
719 
720 void
721 mv(char *from, char *to)
722 {
723 	char buf[MAXPATHLEN];
724 
725 	if (rename(from, to)) {
726 		int sverrno = errno;
727 		(void)snprintf(buf, sizeof(buf), "%s to %s", from, to);
728 		errno = sverrno;
729 		error(buf);
730 	}
731 }
732 
733 void
734 error(const char *name)
735 {
736 
737 	warn("%s", name);
738 	cleanup();
739 	exit(1);
740 }
741 
742 void
743 cleanup(void)
744 {
745 	char buf[MAXPATHLEN];
746 
747 	switch(clean) {
748 	case FILE_ORIG:
749 		(void)snprintf(buf, sizeof(buf), "%s.orig", pname);
750 		(void)unlink(buf);
751 		/* FALLTHROUGH */
752 	case FILE_SECURE:
753 		(void)snprintf(buf, sizeof(buf), "%s/%s.tmp", prefix, _SMP_DB);
754 		(void)unlink(buf);
755 		/* FALLTHROUGH */
756 	case FILE_INSECURE:
757 		(void)snprintf(buf, sizeof(buf), "%s/%s.tmp", prefix, _MP_DB);
758 		(void)unlink(buf);
759 	}
760 }
761 
762 static void
763 usage(void)
764 {
765 
766 	(void)fprintf(stderr,
767 "usage: pwd_mkdb [-BCiLNp] [-d directory] [-s cachesize] [-u username] file\n");
768 	exit(1);
769 }
770