xref: /original-bsd/usr.bin/chpass/pw_copy.c (revision 3b6250d9)
1 /*-
2  * Copyright (c) 1990 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #ifndef lint
9 static char sccsid[] = "@(#)pw_copy.c	5.3 (Berkeley) 05/02/91";
10 #endif /* not lint */
11 
12 /*
13  * This module is used to copy the master password file, replacing a single
14  * record, by chpass(1) and passwd(1).
15  */
16 
17 #include <pwd.h>
18 #include <stdio.h>
19 #include <string.h>
20 
21 extern char *progname, *tempname;
22 
23 pw_copy(ffd, tfd, pw)
24 	int ffd, tfd;
25 	struct passwd *pw;
26 {
27 	register FILE *from, *to;
28 	register int done;
29 	register char *p;
30 	char buf[8192];
31 
32 	if (!(from = fdopen(ffd, "r")))
33 		pw_error(_PATH_MASTERPASSWD, 1, 1);
34 	if (!(to = fdopen(tfd, "w")))
35 		pw_error(tempname, 1, 1);
36 
37 	for (done = 0; fgets(buf, sizeof(buf), from);) {
38 		if (!index(buf, '\n')) {
39 			(void)fprintf(stderr, "%s: %s: line too long\n",
40 			    progname, _PATH_MASTERPASSWD);
41 			pw_error(NULL, 0, 1);
42 		}
43 		if (done) {
44 			(void)fprintf(to, "%s", buf);
45 			if (ferror(to))
46 				goto err;
47 			continue;
48 		}
49 		if (!(p = index(buf, ':'))) {
50 			(void)fprintf(stderr, "%s: %s: corrupted entry\n",
51 			    progname, _PATH_MASTERPASSWD);
52 			pw_error(NULL, 0, 1);
53 		}
54 		*p = '\0';
55 		if (strcmp(buf, pw->pw_name)) {
56 			*p = ':';
57 			(void)fprintf(to, "%s", buf);
58 			if (ferror(to))
59 				goto err;
60 			continue;
61 		}
62 		(void)fprintf(to, "%s:%s:%d:%d:%s:%ld:%ld:%s:%s:%s\n",
63 		    pw->pw_name, pw->pw_passwd, pw->pw_uid, pw->pw_gid,
64 		    pw->pw_class, pw->pw_change, pw->pw_expire, pw->pw_gecos,
65 		    pw->pw_dir, pw->pw_shell);
66 		done = 1;
67 		if (ferror(to))
68 			goto err;
69 	}
70 	if (!done)
71 		(void)fprintf(to, "%s:%s:%d:%d:%s:%ld:%ld:%s:%s:%s\n",
72 		    pw->pw_name, pw->pw_passwd, pw->pw_uid, pw->pw_gid,
73 		    pw->pw_class, pw->pw_change, pw->pw_expire, pw->pw_gecos,
74 		    pw->pw_dir, pw->pw_shell);
75 
76 	if (ferror(to))
77 err:		pw_error(NULL, 1, 1);
78 	(void)fclose(to);
79 }
80