* Lock the master password file. */
| 161 | * Lock the master password file. |
| 162 | */ |
| 163 | int |
| 164 | pw_lock(void) |
| 165 | { |
| 166 | |
| 167 | if (*masterpasswd == '\0') |
| 168 | return (-1); |
| 169 | |
| 170 | /* |
| 171 | * If the master password file doesn't exist, the system is hosed. |
| 172 | * Might as well try to build one. Set the close-on-exec bit so |
| 173 | * that users can't get at the encrypted passwords while editing. |
| 174 | * Open should allow flock'ing the file; see 4.4BSD. XXX |
| 175 | */ |
| 176 | for (;;) { |
| 177 | struct stat st; |
| 178 | |
| 179 | lockfd = flopen(masterpasswd, O_RDONLY|O_NONBLOCK|O_CLOEXEC, 0); |
| 180 | if (lockfd == -1) { |
| 181 | if (errno == EWOULDBLOCK) { |
| 182 | errx(1, "the password db file is busy"); |
| 183 | } else { |
| 184 | err(1, "could not lock the passwd file"); |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | /* |
| 189 | * If the password file was replaced while we were trying to |
| 190 | * get the lock, our hardlink count will be 0 and we have to |
| 191 | * close and retry. |
| 192 | */ |
| 193 | if (fstat(lockfd, &st) == -1) |
| 194 | err(1, "fstat() failed"); |
| 195 | if (st.st_nlink != 0) |
| 196 | break; |
| 197 | close(lockfd); |
| 198 | lockfd = -1; |
| 199 | } |
| 200 | return (lockfd); |
| 201 | } |
| 202 | |
| 203 | /* |
| 204 | * Create and open a presumably safe temp file for editing the password |