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