1 /* vi: set sw=4 ts=4: */
5 * update_passwd is a common function for passwd and chpasswd applets;
6 * it is responsible for updating password file (i.e. /etc/passwd or
7 * /etc/shadow) for a given user and password.
9 * Moved from loginutils/passwd.c by Alexander Shishkin <virtuoso@slind.org>
14 int update_passwd(const char *filename, const char *username,
28 int ret = -1; /* failure */
30 /* New passwd file, "/etc/passwd+" for now */
31 fnamesfx = xasprintf("%s+", filename);
32 sfx_char = &fnamesfx[strlen(fnamesfx)-1];
33 username = xasprintf("%s:", username);
34 user_len = strlen(username);
36 old_fp = fopen(filename, "r+");
39 old_fd = fileno(old_fp);
41 /* Try to create "/etc/passwd+". Wait if it exists. */
44 // FIXME: on last iteration try w/o O_EXCL but with O_TRUNC?
45 new_fd = open(fnamesfx, O_WRONLY|O_CREAT|O_EXCL, 0600);
46 if (new_fd >= 0) goto created;
47 if (errno != EEXIST) break;
48 usleep(100000); /* 0.1 sec */
50 bb_perror_msg("cannot create '%s'", fnamesfx);
54 if (!fstat(old_fd, &sb)) {
55 fchmod(new_fd, sb.st_mode & 0777); /* ignore errors */
56 fchown(new_fd, sb.st_uid, sb.st_gid);
58 new_fp = fdopen(new_fd, "w");
64 /* Backup file is "/etc/passwd-" */
66 /* Delete old backup */
67 i = (unlink(fnamesfx) && errno != ENOENT);
68 /* Create backup as a hardlink to current */
69 if (i || link(filename, fnamesfx))
70 bb_perror_msg("warning: cannot create backup copy '%s'", fnamesfx);
73 /* Lock the password file before updating */
74 lock.l_type = F_WRLCK;
75 lock.l_whence = SEEK_SET;
78 if (fcntl(old_fd, F_SETLK, &lock) < 0)
79 bb_perror_msg("warning: cannot lock '%s'", filename);
80 lock.l_type = F_UNLCK;
82 /* Read current password file, write updated /etc/passwd+ */
84 char *line = xmalloc_fgets(old_fp);
85 if (!line) break; /* EOF/error */
86 if (strncmp(username, line, user_len) == 0) {
87 /* we have a match with "username:"... */
88 const char *cp = line + user_len;
89 /* now cp -> old passwd, skip it: */
90 cp = strchrnul(cp, ':');
91 /* now cp -> ':' after old passwd or -> "" */
92 fprintf(new_fp, "%s%s%s", username, new_pw, cp);
98 fcntl(old_fd, F_SETLK, &lock);
100 /* We do want all of them to execute, thus | instead of || */
101 if ((ferror(old_fp) | fflush(new_fp) | fsync(new_fd) | fclose(new_fp))
102 || rename(fnamesfx, filename)
104 /* At least one of those failed */
107 ret = cnt; /* whee, success! */
110 if (ret < 0) unlink(fnamesfx);
117 free((char*)username);