vipw: move copyfile to the lib

Also, a bug in pw_tmpfile was fixed: copyfile used tmp_file to report
errors, but pw_tmpfile only assigned that variable _after_ calling
copyfile.

Suggested-by: Sami Kerola <kerolasa@iki.fi>
Reviewed-by: Sami Kerola <kerolasa@iki.fi>
Signed-off-by: Egor Chelak <egor.chelak@gmail.com>
This commit is contained in:
Egor Chelak 2020-11-06 09:45:18 +02:00
parent 12235ef107
commit b9dcd38462
3 changed files with 27 additions and 18 deletions

View File

@ -74,4 +74,6 @@ static inline struct dirent *xreaddir(DIR *dp)
extern void close_all_fds(const int exclude[], size_t exsz);
int ul_copy_file(int from, int to);
#endif /* UTIL_LINUX_FILEUTILS */

View File

@ -10,6 +10,7 @@
#include <unistd.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <string.h>
#include "c.h"
#include "fileutils.h"
@ -246,3 +247,21 @@ char *stripoff_last_component(char *path)
*p = '\0';
return p + 1;
}
/* Copies the contents of a file. Returns -1 on read error, -2 on write error. */
int ul_copy_file(int from, int to)
{
ssize_t nr, nw, off;
char buf[8 * 1024];
while ((nr = read(from, buf, sizeof(buf))) > 0)
for (off = 0; nr > 0; nr -= nw, off += nw)
if ((nw = write(to, buf + off, nr)) < 0)
return -2;
if (nr < 0)
return -1;
#ifdef HAVE_EXPLICIT_BZERO
explicit_bzero(buf, sizeof(buf));
#endif
return 0;
}

View File

@ -88,23 +88,6 @@ static char *tmp_file; /* tmp file */
void pw_error (char *, int, int);
static void copyfile(int from, int to)
{
int nr, nw, off;
char buf[8 * 1024];
while ((nr = read(from, buf, sizeof(buf))) > 0)
for (off = 0; nr > 0; nr -= nw, off += nw)
if ((nw = write(to, buf + off, nr)) < 0)
pw_error(tmp_file, 1, 1);
if (nr < 0)
pw_error(orig_file, 1, 1);
#ifdef HAVE_EXPLICIT_BZERO
explicit_bzero(buf, sizeof(buf));
#endif
}
static void pw_init(void)
{
struct rlimit rlim;
@ -139,14 +122,19 @@ static FILE * pw_tmpfile(int lockfd)
{
FILE *fd;
char *tmpname = NULL;
int res;
if ((fd = xfmkstemp(&tmpname, "/etc", ".vipw")) == NULL) {
ulckpwdf();
err(EXIT_FAILURE, _("can't open temporary file"));
}
copyfile(lockfd, fileno(fd));
tmp_file = tmpname;
res = ul_copy_file(lockfd, fileno(fd));
if (res == -1)
pw_error(orig_file, 1, 1);
else if (res == -2)
pw_error(tmp_file, 1, 1);
return fd;
}