#include <netinet/in.h>
#include <arpa/nameser.h>
#include <resolv.h>
-#include <chrono>
+#include <time.h>
#include <algorithm>
+#include <tuple>
#include <apt-pkg/configuration.h>
#include <apt-pkg/error.h>
#include "srvrec.h"
+bool SrvRec::operator==(SrvRec const &other) const
+{
+ return (std::tie(target, priority, weight, port) ==
+ std::tie(other.target, other.priority, other.weight, other.port));
+}
+
bool GetSrvRecords(std::string host, int port, std::vector<SrvRec> &Result)
{
std::string target;
- struct servent *s_ent = getservbyport(htons(port), "tcp");
- if (s_ent == NULL)
+ int res;
+ struct servent s_ent_buf;
+ struct servent *s_ent = nullptr;
+ std::vector<char> buf(1024);
+
+ res = getservbyport_r(htons(port), "tcp", &s_ent_buf, buf.data(), buf.size(), &s_ent);
+ if (res != 0 || s_ent == nullptr)
return false;
strprintf(target, "_%s._tcp.%s", s_ent->s_name, host.c_str());
unsigned char *pt = answer+sizeof(HEADER)+compressed_name_len+QFIXEDSZ;
while ((int)Result.size() < answer_count && pt < answer+answer_len)
{
- SrvRec rec;
u_int16_t type, klass, priority, weight, port, dlen;
char buf[MAXDNAME];
pt += compressed_name_len;
// add it to our class
- rec.priority = priority;
- rec.weight = weight;
- rec.port = port;
- rec.target = buf;
- Result.push_back(rec);
+ Result.emplace_back(buf, priority, weight, port);
}
// implement load balancing as specified in RFC-2782
#endif
// shuffle in a very simplistic way for now (equal weights)
- std::vector<SrvRec>::iterator I, J;
- I = J = Recs.begin();
- for(;I != Recs.end(); ++I)
- {
- if(I->priority != J->priority)
- break;
- }
-
- // FIXME: meeeeh, where to init this properly
- unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
- std::shuffle(J, I, std::default_random_engine(seed));
-
- // meh, no pop_front() in std::vector?
- SrvRec selected = *Recs.begin();
- Recs.erase(Recs.begin());
+ std::vector<SrvRec>::iterator I = Recs.begin();
+ std::vector<SrvRec>::iterator const J = std::find_if(Recs.begin(), Recs.end(),
+ [&I](SrvRec const &J) { return I->priority != J.priority; });
+
+ // clock seems random enough.
+ I += std::max(static_cast<clock_t>(0), clock()) % std::distance(I, J);
+ SrvRec const selected = std::move(*I);
+ Recs.erase(I);
if (_config->FindB("Debug::Acquire::SrvRecs", false) == true)
std::cerr << "PopFromSrvRecs: selecting " << selected.target << std::endl;