Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Created function to copy file while keeping perms #229

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions libutils/file_lib.c
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,70 @@ bool File_Copy(const char *src, const char *dst)
return ret;
}

bool FileCopyKeepPerms(const char *src, const char *dst)
{
assert(src != NULL);
assert(dst != NULL);

struct stat src_sb;
if (lstat(src, &src_sb) != 0)
{
Log(LOG_LEVEL_ERR, "Failed to stat '%s': %s", src, GetErrorStr());
return false;
}

int src_fd = safe_open(src, O_RDONLY);
if (src_fd == -1)
{
Log(LOG_LEVEL_ERR, "Failed to open '%s': %s", src, GetErrorStr());
return false;
}

int dst_fd = safe_open_create_perms(dst, O_CREAT | O_WRONLY, src_sb.st_mode);
if (dst_fd == -1)
{
Log(LOG_LEVEL_ERR, "Failed to open '%s': %s", dst, GetErrorStr());
close(src_fd);
return false;
}

char buf[CF_BUFSIZE];
ssize_t n_read;
do
{
n_read = read(src_fd, buf, sizeof(buf));
if (n_read < 0)
{
Log(LOG_LEVEL_ERR, "Failed to read from '%s': %s", src, GetErrorStr());
close(src_fd);
close(dst_fd);
unlink(dst);
return false;
}

ssize_t n_written = 0;
do
{
ssize_t ret = write(dst_fd, buf, n_read - n_written);
if (ret < 0)
{
Log(LOG_LEVEL_ERR, "Failed to write to '%s': %s", dst, GetErrorStr());
close(src_fd);
close(dst_fd);
unlink(dst);
return false;
}

n_written += ret;
} while (n_read > n_written);
} while (n_read > 0);

close(src_fd);
close(dst_fd);
return true;
}


bool File_CopyToDir(const char *src, const char *dst_dir)
{
assert(src != NULL);
Expand Down
9 changes: 9 additions & 0 deletions libutils/file_lib.h
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,15 @@ ssize_t ReadFileStreamToBuffer(FILE *file, size_t max_bytes, char *buf);
*/
bool File_Copy(const char *src, const char *dst);

/**
* @brief Copies a file while keeping permissions.
* @param src The file to copy from
* @param dst The file to copy to
* @return True on success, otherwise false
* @note Does not follow symbolic links
*/
bool FileCopyKeepPerms(const char *src, const char *dst);

/**
* Same as CopyFile, except destination is a directory,
* and filename will match source
Expand Down
Loading