X-Git-Url: https://git.llucax.com/z.facultad/75.74/practicos.git/blobdiff_plain/c1b28b595a388df043997c87faf75c06959405d0..78d6e1ce97611abe9f0d083033197773f93c33f7:/practicas/pipi/src/nameserver.cpp diff --git a/practicas/pipi/src/nameserver.cpp b/practicas/pipi/src/nameserver.cpp index 2814427..b007975 100644 --- a/practicas/pipi/src/nameserver.cpp +++ b/practicas/pipi/src/nameserver.cpp @@ -2,21 +2,23 @@ #include #include #include -#ifdef DEBUG2 +#include +#include +#ifdef DEBUG #include #endif -static void parsename(const std::string& s, NameServer::name_t& name) +#define DEBUG_RESOLV + +NameServer::Name::Name(const std::string& s) { std::istringstream iss(s); std::string tok; while (std::getline(iss, tok, '.')) - { - name.push_back(tok); - } + push_back(tok); } -static std::ostream& operator<< (std::ostream& os, const NameServer::name_t& name) +std::ostream& operator<< (std::ostream& os, const NameServer::Name& name) { if (name.empty()) return os; @@ -25,6 +27,13 @@ static std::ostream& operator<< (std::ostream& os, const NameServer::name_t& nam return os << name.back(); } +NameServer::Name::operator std::string () const +{ + std::stringstream ss; + ss << *this; + return ss.str(); +} + /// Parsea una zona static std::istream& parsezone(std::istream& is, NameServer::Zone& z) throw (std::runtime_error) @@ -37,8 +46,8 @@ static std::istream& parsezone(std::istream& is, NameServer::Zone& z) std::istringstream iss(line); if (!(iss >> sname >> z.ttl >> ip)) throw std::runtime_error("Error al parsear"); - parsename(sname, z.name); -#ifdef DEBUG2 + z.name = sname; +#ifdef DEBUG_PARSER std::cerr << "parsezone: IP = " << ip << "\n\n"; #endif z.parent = IPAddr(ip); @@ -52,13 +61,13 @@ static std::istream& parsezone(std::istream& is, NameServer::Zone& z) if (!(iss >> key >> type >> ip)) throw std::runtime_error("Error al parsear"); typedef NameServer::Record Rec; -#ifdef DEBUG2 +#ifdef DEBUG_PARSER std::cerr << "parsezone: IP = " << ip << "\n\n"; #endif Rec r((type == "NS") ? Rec::NS : Rec::A, IPAddr(ip)); z.records.insert(NameServer::Zone::records_t::value_type(key, r)); } -#ifdef DEBUG2 +#ifdef DEBUG_PARSER std::cerr << "parsezone: " << z << "\n\n"; #endif return is; @@ -66,9 +75,8 @@ static std::istream& parsezone(std::istream& is, NameServer::Zone& z) /// Constructor NameServer::Zone::Zone(std::string sname, size_t ttl, const IPAddr& parent): - ttl(ttl), parent(parent) + name(sname), ttl(ttl), parent(parent) { - parsename(sname, name); } /// Constructor @@ -88,27 +96,347 @@ void NameServer::Zone::clear() } /// Constructor -NameServer::NameServer(std::istream& is) - throw (std::runtime_error) +NameServer::NameServer(std::istream& is, IPIn& ipin, IPOut& ipout, + DevQue& req_que, DevQue& res_que, DevQue& snd_que) + throw (std::runtime_error): + ipin(ipin), ipout(ipout), req_que(req_que), res_que(res_que), + snd_que(snd_que) { Zone z; while (parsezone(is, z)) { zones.push_back(z); z.clear(); -#ifdef DEBUG2 +#ifdef DEBUG_PARSER std::cerr << "NameServer: " << z << "\n\n"; #endif } } -std::ostream& operator<< (std::ostream& os, const NameServer::Record& r) +/// Devuelve la parte izquierda de n, si la parte derecha coincide exactamente +/// con m, si no devuelve un vector vacío. +/// Elemplo: name_split("mi.domi.nio", "domi.nio") == ["mi"] +/// name_split("dos.mi.domi.nio", "domi.nio") == ["dos", "mi"] +/// name_split("domi.nio", "domi.nio") == [] +/// name_split("papeli.nio", "domi.nio") == [] +static NameServer::Name +name_split(NameServer::Name n, NameServer::Name m) +{ + NameServer::Name r; + std::reverse(n.begin(), n.end()); + std::reverse(m.begin(), m.end()); + // Si m es más grande o igual que n, no hay nada que hacer + if (n.size() <= m.size()) + return r; + // Si no coincide la parte derecha, no hay nada que hacer + NameServer::Name::size_type i; + for (i = 0; i < m.size(); ++i) + if (n[i] != m[i]) + return r; + // Si era todo igual y sobran cosas, devolvemos lo que "sobra" + while (i < n.size()) + r.push_back(n[i++]); + std::reverse(r.begin(), r.end()); +#ifdef DEBUG_NAME + std::cerr << "name_split(" << n << ", " << m << ") -> " << r << "\n"; +#endif + return r; +} + +/// Devuelve -1 si es un nombre "hijo" (la parte derecha de n está contenida +/// completamente en m, pero m y n no son iguales), 0 si m == n y 1 si es +/// "padre" (m no coincide con la parte derecha de n). +/// Elemplo: namecmp("mi.domi.nio", "domi.nio") == -1 +/// namecmp("otra.cosa", "domi.nio") == 1 +/// namecmp("papeli.nio", "domi.nio") == 1 +/// namecmp("domi.nio", "domi.nio") == 0 +/*enum name_cmp_t +{ + NC_DIRECT_CHILD, ///> Hijo directo, es decir, está en la zona m + NC_CHILD, ///> Hijo indirecto, está en una zona que cuelga de m + NC_EQUAL, ///> Es el host de la zona m + NC_DIRECT_PARENT, ///> Padre directo, es decir, coincide en parte con m + NC_PARENT ///> Padre indirecto, es completamente distinto a m +};*/ +#if 0 +static int name_cmp(const NameServer::Name& n, const NameServer::Name& m) +{ + // Si m es más grande que n, seguro es padre + if (n.size() < m.size()) + return 1; + // Si no coincide la parte derecha, seguro es padre + NameServer::Name::size_type i; + for (i = m.size(); i > 0; --i) + if (n[i-1] != m[i-1]) + return 1; + // Si era todo igual y sobran cosas, es hijo + if (i) + return -1; + // Si no, son iguales. + return 0; +} +#endif + +struct search_zone: std::unary_function< NameServer::Zone, bool > +{ + bool local; + ResolvProtoResponse resp; + const NameServer::Name& name; + search_zone(const NameServer::Name& n): local(false), name(n) {} + bool operator() (const NameServer::Zone& z) + { + bool found = false; + NameServer::Name local_part = name_split(name, z.name); + if (!local_part.empty()) // Está en esta zona + { + local = true; + std::string n = local_part.back(); // Obtengo última parte + // busco + typedef NameServer::Zone::records_t::const_iterator itt; + std::pair p = z.records.equal_range(n); + for (; p.first != p.second; ++p.first) + { + const NameServer::Record& r = (*p.first).second; + // Tiene que buscar solo A porque era un nombre + if ((local_part.size() == 1) && (r.type != NameServer::Record::A)) + continue; + // Tiene que seguir para abajo, solo busca NS + if ((local_part.size() > 1) && r.type != NameServer::Record::NS) + continue; + found = true; + resp.ret = (r.type == NameServer::Record::NS) ? RP_RES_NS + : RP_RES_A; + resp.ttl = z.ttl; + resp.ips.push_back(r.ip); + } + } + return found; + } +}; + +/// Resuelve un nombre de forma directa (no recursiva) +ResolvProtoResponse NameServer::resolv_direct(const Name& n) { - if (r.type == NameServer::Record::NS) - os << "NS "; +#ifdef DEBUG_RESOLV + std::cerr << "resolv_direct -> tratando de resolver: " << n << "\n"; +#endif + search_zone zs(n); + bool found; + for (zones_t::const_iterator i = zones.begin(); i!= zones.end(); ++i) + if ((found = zs(*i))) + break; + if (found) + { +#ifdef DEBUG_RESOLV + std::cerr << "resolv_direct found (local/hijo): " << zs.resp << "\n"; +#endif + return zs.resp; + } + if (zs.local) + { +#ifdef DEBUG_RESOLV + std::cerr << "resolv_direct NOT FOUND (es local pero no existe)\n"; +#endif + return ResolvProtoResponse(RP_RES_NOTFOUND); + } + cache_t::const_iterator i = cache.find(n); + // TODO TTL!?! + if (i != cache.end()) + { +#ifdef DEBUG_RESOLV + std::cerr << "resolv_direct found (en cache): " << i->second << "\n"; +#endif + const CacheRecord& cr = i->second; + return ResolvProtoResponse(RP_RES_A, cr.ttl, cr.ips); + } + if (zones.size()) + { + // Busco una zona con padre para ver si puedo "trepar" + for (zones_t::const_iterator i = zones.begin(); i != zones.end(); ++i) + { +#ifdef DEBUG_RESOLV + std::cerr << "resolv_direct -> evaluando padre " << i->parent + << "\n"; +#endif + if (i->parent != IPAddr(0)) + { +#ifdef DEBUG_RESOLV + std::cerr << "resolv_direct found (al padre): " + << i->parent << "\n"; +#endif + ResolvProtoResponse rpr(RP_RES_NS, i->ttl); + rpr.ips.push_back(i->parent); + return rpr; + } + } + } +#ifdef DEBUG_RESOLV + std::cerr << "resolv_direct NOT FOUND (no hay padre)\n"; +#endif + // No hay padre, no puedo hacer nada más + return ResolvProtoResponse(RP_RES_NOTFOUND); +} + +/// Resuelve un nombre de forma recursiva +ResolvProtoResponse NameServer::resolv_recursive(const Name& n) +{ + ResolvProtoResponse rpr = resolv_direct(n); + switch (rpr.ret) + { + case RP_RES_NS: +#ifdef DEBUG_RESOLV + std::cerr << "resolv_recursive -> redirect a " << rpr << "\n"; +#endif + return resolv_recursive_r(n, rpr); // Sigo "bajando" + case RP_RES_A: +#ifdef DEBUG_RESOLV + std::cerr << "resolv_recursive -> gotcha! " << rpr << "\n"; +#endif + // TODO agregar a cache + break; + } + return rpr; // Devuelvo el A o NOTFOUND +} + +/// Resuelve un nombre de forma recursiva entrando a otros ns +ResolvProtoResponse NameServer::resolv_recursive_r(const Name& n, + ResolvProtoResponse rpr) +{ + ResolvProtoResponse r; + for (ResolvProtoResponse::ipvec_t::const_iterator ip = rpr.ips.begin(); + ip != rpr.ips.end(); ++ip) + { + r = query(n, *ip); + switch (r.ret) + { + case RP_RES_NS: +#ifdef DEBUG_RESOLV + std::cerr << "resolv_recursive_r -> redirect a " << r << "\n"; +#endif + return resolv_recursive_r(n, r); // Sigo "bajando" + case RP_RES_NOTFOUND: +#ifdef DEBUG_RESOLV + std::cerr << "resolv_recursive_r -> NOT FOUND en " << *ip + << ", sigo probando\n"; +#endif + break; // Sigo probando del mismo nivel + case RP_RES_A: +#ifdef DEBUG_RESOLV + std::cerr << "resolv_recursive_r -> gotcha! " << r << "\n"; +#endif + // TODO agregar a cache + return r; // Gotcha! + } + } +#ifdef DEBUG_RESOLV + std::cerr << "resolv_recursive_r -> NOT FOUND, no hay más por hacer\n"; +#endif + return r; // NOTFOUND +} + +/// Consulta a otro name server sobre un nombre +ResolvProtoResponse NameServer::query(const Name& n, const IPAddr& ip) +{ + ResolvProtoRequest r(std::string(n), RP_REQ_DIRECT); +#ifdef DEBUG_RESOLV + std::cerr << "query -> pidiendo " << r << " a " << ip << "\n"; +#endif + // Envía a través de la cola de envío + snd_que.transmit(std::string(r), ip); + Dev::mac_type mac = ip; + std::string buf = res_que.receive(mac); + ResolvProtoResponse resp(buf); +#ifdef DEBUG_RESOLV + std::cerr << "query -> recibido " << resp << " de " << ip << "\n"; +#endif + return resp; +} + +void NameServer::recv_loop() +{ + while (true) + { + IPAddr src, dst; + uint8_t proto; + std::string s = ipin.recv(proto, src, dst); +#ifdef DEBUG_RESOLV + std::cout << "NameServer::recv_loop() -> recibido len=" << s.size() + << " de " << src << " para " << dst << " (proto = " + << unsigned(proto) << ")\n"; +#endif + if (proto == RESOLV_PROTO) // Si es para nosotros + { + rp_pkt_type_t type; + memcpy(&type, s.c_str(), sizeof(uint8_t)); + switch (type) + { + // Request + case RP_REQ_DIRECT: + case RP_REQ_RECURSIVE: +#ifdef DEBUG_RESOLV + std::cout << "---> " << ResolvProtoRequest(s) << "\n"; +#endif + req_que.transmit(s, src); // Encolo + break; + // Response + default: +#ifdef DEBUG_RESOLV + std::cout << "---> " << ResolvProtoResponse(s) << "\n"; +#endif + res_que.transmit(s, src); // Encolo + } + } + } +} + +void NameServer::send_loop() +{ + while (true) + { + if (!req_que.empty()) + { + Dev::mac_type mac = 0; + ResolvProtoRequest req(req_que.receive(mac)); +#ifdef DEBUG_RESOLV + std::cout << "NameServer::send_loop() -> recibido " << req << "\n"; +#endif + ResolvProtoResponse res + = (req.query_type == RP_REQ_DIRECT) + ? resolv_direct(req.name) + : resolv_recursive(req.name); +#ifdef DEBUG_RESOLV + std::cout << "NameServer::send_loop() -> respondo " << res << "\n"; +#endif + ipout.send(res, RESOLV_PROTO, IPAddr(mac)); + } + else if (!snd_que.empty()) // Hay un request para enviar + { + Dev::mac_type mac = 0; + std::string buf = snd_que.receive(mac); +#ifdef DEBUG_RESOLV + std::cout << "NameServer::send_loop() -> envío request " + << ResolvProtoRequest(buf) << "\n"; +#endif + ipout.send(buf, RESOLV_PROTO, IPAddr(mac)); + } + else // No hay nada, esperamos un rato + { + usleep(10000); + } + } +} + +std::ostream& operator<< (std::ostream& os, const NameServer::Record::type_t& t) +{ + if (t == NameServer::Record::NS) + return os << "NS"; else - os << "A "; - return os << r.ip; + return os << "A"; +} + +std::ostream& operator<< (std::ostream& os, const NameServer::Record& r) +{ + return os << r.type << " " << r.ip; } std::ostream& operator<< (std::ostream& os, @@ -125,6 +453,14 @@ std::ostream& operator<< (std::ostream& os, const NameServer::Zone& z) return os; } +std::ostream& operator<< (std::ostream& os, const NameServer::CacheRecord& cr) +{ + os << "CacheRecord(ttl=" << cr.ttl << ", records="; + std::copy(cr.ips.begin(), cr.ips.end(), + std::ostream_iterator< IPAddr >(os, ",")); + return os << ")"; +} + std::ostream& operator<< (std::ostream& os, const NameServer& ns) { os << "NameServer: zones[" << ns.zones.size() << "] (\n\n";