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