diff --git a/src/privfile.cpp b/src/privfile.cpp new file mode 100644 index 0000000..670598a --- /dev/null +++ b/src/privfile.cpp @@ -0,0 +1,61 @@ + +/* + * This file is part of Codecrypt. + * + * Copyright (C) 2013-2016 Mirek Kratochvil + * + * Codecrypt is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at + * your option) any later version. + * + * Codecrypt is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public + * License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Codecrypt. If not, see . + */ + +#include "privfile.h" + +#include +#include +#include +#include +#include +#include + +bool put_private_file (const std::string&fn, + const std::string&contents, bool force_perms) +{ + struct stat st; + if (stat (fn.c_str(), &st)) { + if (errno != ENOENT) + return false; + + //if it simply doesn't exist, create it + int fd; + fd = creat (fn.c_str(), S_IRUSR | S_IWUSR); + if (fd < 0) return false; + ssize_t res = write (fd, contents.c_str(), + contents.length()); + if (close (fd)) return false; + if ( (size_t) res != contents.length()) return false; + + } else { + if (!S_ISREG (st.st_mode)) + return false; + + //remove others' read/write. group r/w is untouched. + if (force_perms && (st.st_mode & 07)) { + if (chmod (fn.c_str(), st.st_mode & ~07)) + return false; + } + } + + if (access (fn.c_str(), R_OK | W_OK)) return false; + + return true; +} diff --git a/src/privfile.h b/src/privfile.h new file mode 100644 index 0000000..41d5979 --- /dev/null +++ b/src/privfile.h @@ -0,0 +1,30 @@ + +/* + * This file is part of Codecrypt. + * + * Copyright (C) 2013-2016 Mirek Kratochvil + * + * Codecrypt is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at + * your option) any later version. + * + * Codecrypt is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public + * License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Codecrypt. If not, see . + */ + +#ifndef _ccr_privfile_h_ +#define _ccr_privfile_h_ + +#include + +bool put_private_file (const std::string&fn, + const std::string&contents, + bool force_permissions); + +#endif