]> git.ipfire.org Git - thirdparty/pdns.git/commitdiff
Wrap more FILE objects in smart pointers
authorRemi Gacogne <remi.gacogne@powerdns.com>
Wed, 10 Jun 2020 07:52:43 +0000 (09:52 +0200)
committerRemi Gacogne <remi.gacogne@powerdns.com>
Wed, 10 Jun 2020 07:52:43 +0000 (09:52 +0200)
modules/pipebackend/coprocess.cc
modules/pipebackend/coprocess.hh
pdns/dnsdist-cache.cc
pdns/dnspcap.cc
pdns/dnspcap.hh
pdns/dnspcap2protobuf.cc
pdns/dnstcpbench.cc
pdns/ixfrutils.cc
pdns/recursordist/test-negcache_cc.cc

index 8a5183977f93caddbeab60f4daf902e1119800d7..52ca5f95a33e9189e813369e965aa6d4a82e7a70 100644 (file)
@@ -232,12 +232,7 @@ UnixRemote::UnixRemote(const string& path, int timeout)
   if(connect(d_fd, (struct sockaddr*)&remote, sizeof(remote)) < 0)
     unixDie("Unable to connect to remote '"+path+"' using UNIX domain socket");
 
-  d_fp = fdopen(d_fd, "r");
-}
-
-UnixRemote::~UnixRemote()
-{
-  fclose(d_fp);
+  d_fp = std::unique_ptr<FILE, int(*)(FILE*)>(fdopen(d_fd, "r"), fclose);
 }
 
 void UnixRemote::send(const string& line)
@@ -250,7 +245,7 @@ void UnixRemote::send(const string& line)
 void UnixRemote::receive(string& line)
 {
   line.clear();
-  stringfgets(d_fp, line);
+  stringfgets(d_fp.get(), line);
   trim_right(line);
 }
 
index 84c516e3d0eaa64994ae4393e2a6bbd2bd11a560..87099db5667963a9661dfb168cbbb0e6c23210db 100644 (file)
@@ -61,12 +61,11 @@ class UnixRemote : public CoRemote
 {
 public:
   UnixRemote(const string &path, int timeout=0);
-  ~UnixRemote();
   void sendReceive(const string &send, string &receive) override;
   void receive(string &rcv) override;
   void send(const string &send) override;
 private:
   int d_fd;
-  FILE *d_fp;
+  std::unique_ptr<FILE, int(*)(FILE*)> d_fp{nullptr, fclose};
 };
 bool isUnixSocket(const string& fname);
index c97c6744532203e03383895ca67536a9d629987e..c31a0a554c05411033d0f88be06bb2b521d4a9c2 100644 (file)
@@ -447,12 +447,12 @@ uint64_t DNSDistPacketCache::getEntriesCount()
 
 uint64_t DNSDistPacketCache::dump(int fd)
 {
-  FILE * fp = fdopen(dup(fd), "w");
+  auto fp = std::unique_ptr<FILE, int(*)(FILE*)>(fdopen(dup(fd), "w"), fclose);
   if (fp == nullptr) {
     return 0;
   }
 
-  fprintf(fp, "; dnsdist's packet cache dump follows\n;\n");
+  fprintf(fp.get(), "; dnsdist's packet cache dump follows\n;\n");
 
   uint64_t count = 0;
   time_t now = time(nullptr);
@@ -465,14 +465,13 @@ uint64_t DNSDistPacketCache::dump(int fd)
       count++;
 
       try {
-        fprintf(fp, "%s %" PRId64 " %s ; key %" PRIu32 ", length %" PRIu16 ", tcp %d, added %" PRId64 "\n", value.qname.toString().c_str(), static_cast<int64_t>(value.validity - now), QType(value.qtype).getName().c_str(), entry.first, value.len, value.tcp, static_cast<int64_t>(value.added));
+        fprintf(fp.get(), "%s %" PRId64 " %s ; key %" PRIu32 ", length %" PRIu16 ", tcp %d, added %" PRId64 "\n", value.qname.toString().c_str(), static_cast<int64_t>(value.validity - now), QType(value.qtype).getName().c_str(), entry.first, value.len, value.tcp, static_cast<int64_t>(value.added));
       }
       catch(...) {
-        fprintf(fp, "; error printing '%s'\n", value.qname.empty() ? "EMPTY" : value.qname.toString().c_str());
+        fprintf(fp.get(), "; error printing '%s'\n", value.qname.empty() ? "EMPTY" : value.qname.toString().c_str());
       }
     }
   }
 
-  fclose(fp);
   return count;
 }
index aa17af85f1bbdd90430b62e00d7320e3e859292f..bf3ef84690e2d12d5e809b790ba882094b46b9ab 100644 (file)
 #include "namespaces.hh"
 PcapPacketReader::PcapPacketReader(const string& fname) : d_fname(fname)
 {
-  d_fp=fopen(fname.c_str(),"r");
-  if(!d_fp)
+  d_fp = std::unique_ptr<FILE, int(*)(FILE*)>(fopen(fname.c_str(), "r"), fclose);
+  if (!d_fp) {
     unixDie("Unable to open file " + fname);
-  
-  int flags=fcntl(fileno(d_fp),F_GETFL,0);
-  fcntl(fileno(d_fp), F_SETFL,flags&(~O_NONBLOCK)); // bsd needs this in stdin (??)
-  
+  }
+
+  int flags = fcntl(fileno(d_fp.get()), F_GETFL, 0);
+  fcntl(fileno(d_fp.get()), F_SETFL, flags & (~O_NONBLOCK)); // bsd needs this in stdin (??)
+
   checkedFread(&d_pfh);
-  
-  if(d_pfh.magic != 2712847316UL)
+
+  if (d_pfh.magic != 2712847316UL) {
     throw runtime_error((format("PCAP file %s has bad magic %x, should be %x") % fname % d_pfh.magic % 2712847316UL).str());
-  
+  }
+
   if( d_pfh.linktype==1) {
     d_skipMediaHeader=sizeof(struct ether_header);
   }
@@ -55,22 +57,17 @@ PcapPacketReader::PcapPacketReader(const string& fname) : d_fname(fname)
     d_skipMediaHeader=16;
   }
   else throw runtime_error((format("Unsupported link type %d") % d_pfh.linktype).str());
-  
-  d_runts = d_oversized = d_correctpackets = d_nonetheripudp = 0;
-}
 
-PcapPacketReader::~PcapPacketReader()
-{
-  fclose(d_fp);
+  d_runts = d_oversized = d_correctpackets = d_nonetheripudp = 0;
 }
 
-
 void PcapPacketReader::checkedFreadSize(void* ptr, size_t size) 
 {
-  int ret=fread(ptr, 1, size, d_fp);
-  if(ret < 0)
+  int ret = fread(ptr, 1, size, d_fp.get());
+  if (ret < 0) {
     unixDie( (format("Error reading %d bytes from %s") % size % d_fname).str());
-  
+  }
+
   if(!ret)
     throw EofException();
   
@@ -231,12 +228,14 @@ PcapPacketWriter::PcapPacketWriter(const string& fname, const PcapPacketReader&
 
 PcapPacketWriter::PcapPacketWriter(const string& fname) : d_fname(fname)
 {
-  d_fp=fopen(fname.c_str(),"w");
-  if(!d_fp)
+  d_fp = std::unique_ptr<FILE, int(*)(FILE*)>(fopen(fname.c_str(),"w"), fclose);
+
+  if (!d_fp) {
     unixDie("Unable to open file");
-  
-  int flags=fcntl(fileno(d_fp),F_GETFL,0);
-  fcntl(fileno(d_fp), F_SETFL,flags&(~O_NONBLOCK)); // bsd needs this in stdin (??)
+  }
+
+  int flags = fcntl(fileno(d_fp.get()), F_GETFL, 0);
+  fcntl(fileno(d_fp.get()), F_SETFL,flags & (~O_NONBLOCK)); // bsd needs this in stdin (??)
 }
 
 void PcapPacketWriter::write()
@@ -246,14 +245,9 @@ void PcapPacketWriter::write()
   }
 
   if(d_first) {
-    fwrite(&d_ppr->d_pfh, 1, sizeof(d_ppr->d_pfh), d_fp);
+    fwrite(&d_ppr->d_pfh, 1, sizeof(d_ppr->d_pfh), d_fp.get());
     d_first=false;
   }
-  fwrite(&d_ppr->d_pheader, 1, sizeof(d_ppr->d_pheader), d_fp);
-  fwrite(d_ppr->d_buffer, 1, d_ppr->d_pheader.caplen, d_fp);
-}
-
-PcapPacketWriter::~PcapPacketWriter()
-{
-  fclose(d_fp);
+  fwrite(&d_ppr->d_pheader, 1, sizeof(d_ppr->d_pheader), d_fp.get());
+  fwrite(d_ppr->d_buffer, 1, d_ppr->d_pheader.caplen, d_fp.get());
 }
index a8a6e9a1201cc2dc3d58e46625a600faf4e9c5bd..5cb73a325c3c6d921f845be23b0cf8ea537a68c3 100644 (file)
@@ -90,8 +90,6 @@ public:
 
   PcapPacketReader(const string& fname); 
 
-  ~PcapPacketReader();
-
   template<typename T>
   void checkedFread(T* ptr)
   {
@@ -119,7 +117,7 @@ public:
   unsigned int d_runts, d_oversized, d_correctpackets, d_nonetheripudp;
   char d_buffer[32768];
 private:
-  FILE* d_fp;
+  std::unique_ptr<FILE, int(*)(FILE*)> d_fp{nullptr, fclose};
   string d_fname;
   unsigned int d_skipMediaHeader;
 };
@@ -132,12 +130,11 @@ public:
   
   void write();
   void setPPR(const PcapPacketReader& ppr) { d_ppr = &ppr; }
-  ~PcapPacketWriter();
 
 private:
   string d_fname;
   const PcapPacketReader* d_ppr{nullptr};
 
-  FILE *d_fp;
+  std::unique_ptr<FILE, int(*)(FILE*)> d_fp{nullptr, fclose};
   bool d_first{true};
 }; 
index 22482737b06ee2764e1f15b2ff4255f7d1307a32..664ba89e5ecbc3eb615b1ed4c599678597a14fc6 100644 (file)
@@ -64,7 +64,7 @@ try {
 
   PcapPacketReader pr(argv[1]);
 
-  FILE* fp = fopen(argv[2], "w");
+  auto fp = std::unique_ptr<FILE, int(*)(FILE*)>(fopen(argv[2], "w"), fclose);
   if (!fp) {
     cerr<<"Error opening output file "<<argv[2]<<": "<<stringerror()<<endl;
     exit(EXIT_FAILURE);
@@ -149,17 +149,14 @@ try {
       message.serialize(str);
 
       uint16_t mlen = htons(str.length());
-      fwrite(&mlen, 1, sizeof(mlen), fp);
-      fwrite(str.c_str(), 1, str.length(), fp);
+      fwrite(&mlen, 1, sizeof(mlen), fp.get());
+      fwrite(str.c_str(), 1, str.length(), fp.get());
     }
   }
   catch (const std::exception& e) {
     cerr<<"Error while parsing the PCAP file: "<<e.what()<<endl;
-    fclose(fp);
     exit(EXIT_FAILURE);
   }
-
-  fclose(fp);
 }
 catch(const std::exception& e) {
   cerr<<"Error opening PCAP file: "<<e.what()<<endl;
index 4f36ff2e995442c33ea0cc8b3a46a7738230136b..68cfddb67d741d4539ba2154b10403d39ce91689 100644 (file)
@@ -255,23 +255,25 @@ try
   std::vector<std::thread> workers;
   workers.reserve(numworkers);
 
-  FILE* fp;
-  if(!g_vm.count("file"))
-    fp=fdopen(0, "r");
+  std::unique_ptr<FILE, int(*)(FILE*)> fp{nullptr, fclose};
+  if (!g_vm.count("file")) {
+    fp = std::unique_ptr<FILE, int(*)(FILE*)>(fdopen(0, "r"), fclose);
+  }
   else {
-    fp=fopen(g_vm["file"].as<string>().c_str(), "r");
-    if(!fp)
+    fp = std::unique_ptr<FILE, int(*)(FILE*)>(fopen(g_vm["file"].as<string>().c_str(), "r"), fclose);
+    if (!fp) {
       unixDie("Unable to open "+g_vm["file"].as<string>()+" for input");
+    }
   }
   pair<string, string> q;
   string line;
-  while(stringfgets(fp, line)) {
+  while(stringfgets(fp.get(), line)) {
     trim_right(line);
     q=splitField(line, ' ');
     g_queries.push_back(BenchQuery(q.first, DNSRecordContent::TypeToNumber(q.second)));
   }
-  fclose(fp);
-    
+  fp.reset();
+
   for (unsigned int n = 0; n < numworkers; ++n) {
     workers.push_back(std::thread(worker));
   }
index feec7c33927eb86f217b07502a184c46f3bbb3a5..9d94c821508de0e384c14beff90d75a194fae5fa 100644 (file)
@@ -124,30 +124,31 @@ void writeZoneToDisk(const records_t& records, const DNSName& zone, const std::s
   DNSRecord soa;
   auto serial = getSerialFromRecords(records, soa);
   string fname=directory +"/"+std::to_string(serial);
-  FILE* fp=fopen((fname+".partial").c_str(), "w");
-  if(!fp)
+  auto fp = std::unique_ptr<FILE, int(*)(FILE*)>(fopen((fname+".partial").c_str(), "w"), fclose);
+  if (!fp) {
     throw runtime_error("Unable to open file '"+fname+".partial' for writing: "+stringerror());
+  }
 
   records_t soarecord;
   soarecord.insert(soa);
-  if(fprintf(fp, "$ORIGIN %s\n", zone.toString().c_str()) < 0) {
+  if (fprintf(fp.get(), "$ORIGIN %s\n", zone.toString().c_str()) < 0) {
     string error = "Error writing to zone file for " + zone.toLogString() + " in file " + fname + ".partial" + ": " + stringerror();
-    fclose(fp);
+    fp.reset();
     unlink((fname+".partial").c_str());
     throw std::runtime_error(error);
   }
 
   try {
-    writeRecords(fp, soarecord);
-    writeRecords(fp, records);
-    writeRecords(fp, soarecord);
+    writeRecords(fp.get(), soarecord);
+    writeRecords(fp.get(), records);
+    writeRecords(fp.get(), soarecord);
   } catch (runtime_error &e) {
-    fclose(fp);
+    fp.reset();
     unlink((fname+".partial").c_str());
     throw runtime_error("Error closing zone file for " + zone.toLogString() + " in file " + fname + ".partial" + ": " + e.what());
   }
 
-  if(fclose(fp) != 0) {
+  if (fclose(fp.release()) != 0) {
     string error = "Error closing zone file for " + zone.toLogString() + " in file " + fname + ".partial" + ": " + stringerror();
     unlink((fname+".partial").c_str());
     throw std::runtime_error(error);
index 5a96f2fd0ac6a536625204fe7d1f24862343749b..198c8c515a7a712b575a240c1bbc0049a8d0b94a 100644 (file)
@@ -436,19 +436,19 @@ BOOST_AUTO_TEST_CASE(test_dumpToFile)
   cache.add(genNegCacheEntry(DNSName("www1.powerdns.com"), DNSName("powerdns.com"), now));
   cache.add(genNegCacheEntry(DNSName("www2.powerdns.com"), DNSName("powerdns.com"), now));
 
-  FILE* fp = tmpfile();
+  auto fp = std::unique_ptr<FILE, int(*)(FILE*)>(tmpfile(), fclose);
   if (!fp)
     BOOST_FAIL("Temporary file could not be opened");
 
-  cache.dumpToFile(fp);
+  cache.dumpToFile(fp.get());
 
-  rewind(fp);
+  rewind(fp.get());
   char* line = nullptr;
   size_t len = 0;
   ssize_t read;
 
   for (const auto& str : expected) {
-    read = getline(&line, &len, fp);
+    read = getline(&line, &len, fp.get());
     if (read == -1)
       BOOST_FAIL("Unable to read a line from the temp file");
     BOOST_CHECK_EQUAL(line, str);
@@ -460,8 +460,6 @@ BOOST_AUTO_TEST_CASE(test_dumpToFile)
        last allocation if any. */
     free(line);
   }
-
-  fclose(fp);
 }
 
 BOOST_AUTO_TEST_CASE(test_count)