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