1 #include "nameserver.h"
13 NameServer::Name::Name(const std::string& s)
15 std::istringstream iss(s);
17 while (std::getline(iss, tok, '.'))
21 std::ostream& operator<< (std::ostream& os, const NameServer::Name& name)
25 std::copy(name.begin(), name.end() - 1,
26 std::ostream_iterator< std::string >(os, "."));
27 return os << name.back();
30 NameServer::Name::operator std::string () const
38 static std::istream& parsezone(std::istream& is, NameServer::Zone& z)
39 throw (std::runtime_error)
41 std::string line, sname, ip;
42 // [dominio] [ttl] [parent ip]
43 while (std::getline(is, line) && (line == "")); // Salteo líneas en blanco
46 std::istringstream iss(line);
47 if (!(iss >> sname >> z.ttl >> ip))
48 throw std::runtime_error("Error al parsear");
51 std::cerr << "parsezone: IP = " << ip << "\n\n";
53 z.parent = IPAddr(ip);
54 // un record por linea, sin líneas vacías
56 while (std::getline(is, line) && (line != ""))
60 std::string key, type;
61 if (!(iss >> key >> type >> ip))
62 throw std::runtime_error("Error al parsear");
63 typedef NameServer::Record Rec;
65 std::cerr << "parsezone: IP = " << ip << "\n\n";
67 Rec r((type == "NS") ? Rec::NS : Rec::A, IPAddr(ip));
68 z.records.insert(NameServer::Zone::records_t::value_type(key, r));
71 std::cerr << "parsezone: " << z << "\n\n";
77 NameServer::Zone::Zone(std::string sname, size_t ttl, const IPAddr& parent):
78 name(sname), ttl(ttl), parent(parent)
83 NameServer::Zone::Zone(std::istream& is)
84 throw (std::runtime_error)
87 if (!parsezone(is, *this))
88 throw std::runtime_error("Error de parser, no hay zona");
92 void NameServer::Zone::clear()
99 NameServer::NameServer(std::istream& is, IPIn& ipin, IPOut& ipout,
100 DevQue& req_que, DevQue& res_que, DevQue& snd_que)
101 throw (std::runtime_error):
102 ipin(ipin), ipout(ipout), req_que(req_que), res_que(res_que),
106 while (parsezone(is, z))
111 std::cerr << "NameServer: " << z << "\n\n";
116 /// Devuelve la parte izquierda de n, si la parte derecha coincide exactamente
117 /// con m, si no devuelve un vector vacío.
118 /// Elemplo: name_split("mi.domi.nio", "domi.nio") == ["mi"]
119 /// name_split("dos.mi.domi.nio", "domi.nio") == ["dos", "mi"]
120 /// name_split("domi.nio", "domi.nio") == []
121 /// name_split("papeli.nio", "domi.nio") == []
122 static NameServer::Name
123 name_split(NameServer::Name n, NameServer::Name m)
126 std::reverse(n.begin(), n.end());
127 std::reverse(m.begin(), m.end());
128 // Si m es más grande o igual que n, no hay nada que hacer
129 if (n.size() <= m.size())
131 // Si no coincide la parte derecha, no hay nada que hacer
132 NameServer::Name::size_type i;
133 for (i = 0; i < m.size(); ++i)
136 // Si era todo igual y sobran cosas, devolvemos lo que "sobra"
139 std::reverse(r.begin(), r.end());
141 std::cerr << "name_split(" << n << ", " << m << ") -> " << r << "\n";
146 /// Devuelve -1 si es un nombre "hijo" (la parte derecha de n está contenida
147 /// completamente en m, pero m y n no son iguales), 0 si m == n y 1 si es
148 /// "padre" (m no coincide con la parte derecha de n).
149 /// Elemplo: namecmp("mi.domi.nio", "domi.nio") == -1
150 /// namecmp("otra.cosa", "domi.nio") == 1
151 /// namecmp("papeli.nio", "domi.nio") == 1
152 /// namecmp("domi.nio", "domi.nio") == 0
155 NC_DIRECT_CHILD, ///> Hijo directo, es decir, está en la zona m
156 NC_CHILD, ///> Hijo indirecto, está en una zona que cuelga de m
157 NC_EQUAL, ///> Es el host de la zona m
158 NC_DIRECT_PARENT, ///> Padre directo, es decir, coincide en parte con m
159 NC_PARENT ///> Padre indirecto, es completamente distinto a m
162 static int name_cmp(const NameServer::Name& n, const NameServer::Name& m)
164 // Si m es más grande que n, seguro es padre
165 if (n.size() < m.size())
167 // Si no coincide la parte derecha, seguro es padre
168 NameServer::Name::size_type i;
169 for (i = m.size(); i > 0; --i)
170 if (n[i-1] != m[i-1])
172 // Si era todo igual y sobran cosas, es hijo
175 // Si no, son iguales.
180 struct search_zone: std::unary_function< NameServer::Zone, bool >
183 ResolvProtoResponse resp;
184 const NameServer::Name& name;
185 search_zone(const NameServer::Name& n): local(false), name(n) {}
186 bool operator() (const NameServer::Zone& z)
189 NameServer::Name local_part = name_split(name, z.name);
190 if (!local_part.empty()) // Está en esta zona
193 std::string n = local_part.back(); // Obtengo última parte
195 typedef NameServer::Zone::records_t::const_iterator itt;
196 std::pair<itt, itt> p = z.records.equal_range(n);
197 for (; p.first != p.second; ++p.first)
199 const NameServer::Record& r = (*p.first).second;
200 // Tiene que buscar solo A porque era un nombre
201 if ((local_part.size() == 1) && (r.type != NameServer::Record::A))
203 // Tiene que seguir para abajo, solo busca NS
204 if ((local_part.size() > 1) && r.type != NameServer::Record::NS)
207 resp.ret = (r.type == NameServer::Record::NS) ? RP_RES_NS
210 resp.ips.push_back(r.ip);
217 /// Resuelve un nombre de forma directa (no recursiva)
218 ResolvProtoResponse NameServer::resolv_direct(const Name& n)
221 std::cerr << "resolv_direct -> tratando de resolver: " << n << "\n";
225 for (zones_t::const_iterator i = zones.begin(); i!= zones.end(); ++i)
226 if ((found = zs(*i)))
231 std::cerr << "resolv_direct found (local/hijo): " << zs.resp << "\n";
238 std::cerr << "resolv_direct NOT FOUND (es local pero no existe)\n";
240 return ResolvProtoResponse(RP_RES_NOTFOUND);
242 cache_t::const_iterator i = cache.find(n);
244 if (i != cache.end())
247 std::cerr << "resolv_direct found (en cache): " << i->second << "\n";
249 const CacheRecord& cr = i->second;
250 return ResolvProtoResponse(RP_RES_A, cr.ttl, cr.ips);
254 // Busco una zona con padre para ver si puedo "trepar"
255 for (zones_t::const_iterator i = zones.begin(); i != zones.end(); ++i)
258 std::cerr << "resolv_direct -> evaluando padre " << i->parent
261 if (i->parent != IPAddr(0))
264 std::cerr << "resolv_direct found (al padre): "
265 << i->parent << "\n";
267 ResolvProtoResponse rpr(RP_RES_NS, i->ttl);
268 rpr.ips.push_back(i->parent);
274 std::cerr << "resolv_direct NOT FOUND (no hay padre)\n";
276 // No hay padre, no puedo hacer nada más
277 return ResolvProtoResponse(RP_RES_NOTFOUND);
280 /// Resuelve un nombre de forma recursiva
281 ResolvProtoResponse NameServer::resolv_recursive(const Name& n)
283 ResolvProtoResponse rpr = resolv_direct(n);
288 std::cerr << "resolv_recursive -> redirect a " << rpr << "\n";
290 return resolv_recursive_r(n, rpr); // Sigo "bajando"
293 std::cerr << "resolv_recursive -> gotcha! " << rpr << "\n";
295 // TODO agregar a cache
298 return rpr; // Devuelvo el A o NOTFOUND
301 /// Resuelve un nombre de forma recursiva entrando a otros ns
302 ResolvProtoResponse NameServer::resolv_recursive_r(const Name& n,
303 ResolvProtoResponse rpr)
305 ResolvProtoResponse r;
306 for (ResolvProtoResponse::ipvec_t::const_iterator ip = rpr.ips.begin();
307 ip != rpr.ips.end(); ++ip)
314 std::cerr << "resolv_recursive_r -> redirect a " << r << "\n";
316 return resolv_recursive_r(n, r); // Sigo "bajando"
317 case RP_RES_NOTFOUND:
319 std::cerr << "resolv_recursive_r -> NOT FOUND en " << *ip
320 << ", sigo probando\n";
322 break; // Sigo probando del mismo nivel
325 std::cerr << "resolv_recursive_r -> gotcha! " << r << "\n";
327 // TODO agregar a cache
332 std::cerr << "resolv_recursive_r -> NOT FOUND, no hay más por hacer\n";
334 return r; // NOTFOUND
337 /// Consulta a otro name server sobre un nombre
338 ResolvProtoResponse NameServer::query(const Name& n, const IPAddr& ip)
340 ResolvProtoRequest r(std::string(n), RP_REQ_DIRECT);
342 std::cerr << "query -> pidiendo " << r << " a " << ip << "\n";
344 // Envía a través de la cola de envío
345 snd_que.transmit(std::string(r), ip);
346 Dev::mac_type mac = ip;
347 std::string buf = res_que.receive(mac);
348 ResolvProtoResponse resp(buf);
350 std::cerr << "query -> recibido " << resp << " de " << ip << "\n";
355 void NameServer::recv_loop()
361 std::string s = ipin.recv(proto, src, dst);
363 std::cout << "NameServer::recv_loop() -> recibido len=" << s.size()
364 << " de " << src << " para " << dst << " (proto = "
365 << unsigned(proto) << ")\n";
367 if (proto == NAMESERVER_PROTO) // Si es para nosotros
370 memcpy(&type, s.c_str(), sizeof(uint8_t));
375 case RP_REQ_RECURSIVE:
377 std::cout << "---> " << ResolvProtoRequest(s) << "\n";
379 req_que.transmit(s, src); // Encolo
384 std::cout << "---> " << ResolvProtoResponse(s) << "\n";
386 res_que.transmit(s, src); // Encolo
392 void NameServer::send_loop()
396 if (!req_que.empty())
398 Dev::mac_type mac = 0;
399 ResolvProtoRequest req(req_que.receive(mac));
401 std::cout << "NameServer::send_loop() -> recibido " << req << "\n";
403 ResolvProtoResponse res
404 = (req.query_type == RP_REQ_DIRECT)
405 ? resolv_direct(req.name)
406 : resolv_recursive(req.name);
408 std::cout << "NameServer::send_loop() -> respondo " << res << "\n";
410 ipout.send(res, NAMESERVER_PROTO, IPAddr(mac));
412 else if (!snd_que.empty()) // Hay un request para enviar
414 Dev::mac_type mac = 0;
415 std::string buf = snd_que.receive(mac);
417 std::cout << "NameServer::send_loop() -> envío request "
418 << ResolvProtoRequest(buf) << "\n";
420 ipout.send(buf, NAMESERVER_PROTO, IPAddr(mac));
422 else // No hay nada, esperamos un rato
429 std::ostream& operator<< (std::ostream& os, const NameServer::Record::type_t& t)
431 if (t == NameServer::Record::NS)
437 std::ostream& operator<< (std::ostream& os, const NameServer::Record& r)
439 return os << r.type << " " << r.ip;
442 std::ostream& operator<< (std::ostream& os,
443 const NameServer::Zone::records_t::value_type& p)
445 return os << p.first << ": " << p.second;
448 std::ostream& operator<< (std::ostream& os, const NameServer::Zone& z)
450 os << "Zone " << z.name << " " << z.ttl << " " << z.parent << "\n";
451 std::copy(z.records.begin(), z.records.end(), std::ostream_iterator<
452 NameServer::Zone::records_t::value_type >(os, "\n"));
456 std::ostream& operator<< (std::ostream& os, const NameServer::CacheRecord& cr)
458 os << "CacheRecord(ttl=" << cr.ttl << ", records=";
459 std::copy(cr.ips.begin(), cr.ips.end(),
460 std::ostream_iterator< IPAddr >(os, ","));
464 std::ostream& operator<< (std::ostream& os, const NameServer& ns)
466 os << "NameServer: zones[" << ns.zones.size() << "] (\n\n";
467 std::copy(ns.zones.begin(), ns.zones.end(),
468 std::ostream_iterator< NameServer::Zone >(os, "\n"));
472 // vim: set et sw=4 sts=4 :