PcapPacketWriter::PcapPacketWriter(const string& fname) : d_fname(fname)
{
- d_fp = pdns::UniqueFilePtr(fopen(fname.c_str(),"w"));
-
+ d_fp = pdns::openFileForWriting(fname, 0600, true, false);
if (!d_fp) {
unixDie("Unable to open file");
}
PcapPacketReader pr(argv[1]);
- auto filePtr = pdns::UniqueFilePtr(fopen(argv[2], "w"));
+ auto filePtr = pdns::openFileForWriting(argv[2], 0600, true, false);
if (!filePtr) {
- cerr<<"Error opening output file "<<argv[2]<<": "<<stringerror()<<endl;
+ auto error = errno;
+ cerr<<"Error opening output file "<<argv[2]<<": "<<stringerror(error)<<endl;
exit(EXIT_FAILURE);
}
pdns::UniqueFilePtr libssl_set_key_log_file(std::unique_ptr<SSL_CTX, decltype(&SSL_CTX_free)>& ctx, const std::string& logFile)
{
#ifdef HAVE_SSL_CTX_SET_KEYLOG_CALLBACK
- int fd = open(logFile.c_str(), O_WRONLY | O_CREAT | O_APPEND, 0600);
- if (fd == -1) {
- unixDie("Error opening TLS log file '" + logFile + "'");
- }
- auto filePtr = pdns::UniqueFilePtr(fdopen(fd, "a"));
+ auto filePtr = pdns::openFileForWriting(logFile, 0600, false, true);
if (!filePtr) {
- int error = errno; // close might clobber errno
- close(fd);
- throw std::runtime_error("Error opening TLS log file '" + logFile + "': " + stringerror(error));
+ auto error = errno;
+ throw std::runtime_error("Error opening file " + logFile + " for writing: " + stringerror(error));
}
-
SSL_CTX_set_ex_data(ctx.get(), s_keyLogIndex, filePtr.get());
SSL_CTX_set_keylog_callback(ctx.get(), &libssl_key_log_file_callback);
-
return filePtr;
#else
return pdns::UniqueFilePtr(nullptr);
return std::nullopt;
}
+
+UniqueFilePtr openFileForWriting(const std::string& filePath, mode_t permissions, bool mustNotExist, bool appendIfExists)
+{
+ int flags = O_WRONLY | O_CREAT;
+ if (mustNotExist) {
+ flags |= O_EXCL;
+ }
+ else if (appendIfExists) {
+ flags |= O_APPEND;
+ }
+ int fileDesc = open(filePath.c_str(), flags, permissions);
+ if (fileDesc == -1) {
+ return UniqueFilePtr(nullptr);
+ }
+ auto filePtr = pdns::UniqueFilePtr(fdopen(fileDesc, appendIfExists ? "a" : "w"));
+ if (!filePtr) {
+ auto error = errno;
+ close(fileDesc);
+ errno = error;
+ return UniqueFilePtr(nullptr);
+ }
+ return filePtr;
+}
+
}
};
using UniqueFilePtr = std::unique_ptr<FILE, FilePtrDeleter>;
+
+UniqueFilePtr openFileForWriting(const std::string& filePath, mode_t permissions, bool mustNotExist = true, bool appendIfExists = false);
}