1 #include "nameserver.h"
11 NameServer::Name::Name(const std::string& s)
13 std::istringstream iss(s);
15 while (std::getline(iss, tok, '.'))
19 std::ostream& operator<< (std::ostream& os, const NameServer::Name& name)
23 std::copy(name.begin(), name.end() - 1,
24 std::ostream_iterator< std::string >(os, "."));
25 return os << name.back();
28 NameServer::Name::operator std::string () const
36 static std::istream& parsezone(std::istream& is, NameServer::Zone& z)
37 throw (std::runtime_error)
39 std::string line, sname, ip;
40 // [dominio] [ttl] [parent ip]
41 while (std::getline(is, line) && (line == "")); // Salteo líneas en blanco
44 std::istringstream iss(line);
45 if (!(iss >> sname >> z.ttl >> ip))
46 throw std::runtime_error("Error al parsear");
49 std::cerr << "NameServer::parsezone: IP = " << ip << "\n\n";
51 z.parent = IPAddr(ip);
52 // un record por linea, sin líneas vacías
54 while (std::getline(is, line) && (line != ""))
58 std::string key, type;
59 if (!(iss >> key >> type >> ip))
60 throw std::runtime_error("Error al parsear");
61 typedef NameServer::Record Rec;
63 std::cerr << "NameServer::parsezone: IP = " << ip << "\n\n";
65 Rec r((type == "NS") ? Rec::NS : Rec::A, IPAddr(ip));
66 z.records.insert(NameServer::Zone::records_t::value_type(key, r));
69 std::cerr << "NameServer::parsezone: " << z << "\n\n";
75 NameServer::Zone::Zone(std::string sname, size_t ttl, const IPAddr& parent):
76 name(sname), ttl(ttl), parent(parent)
81 NameServer::Zone::Zone(std::istream& is)
82 throw (std::runtime_error)
85 if (!parsezone(is, *this))
86 throw std::runtime_error("Error de parser, no hay zona");
90 void NameServer::Zone::clear()
97 NameServer::NameServer(std::istream& is, IPIn& ipin, IPOut& ipout,
98 DevQue& req_que, DevQue& res_que, DevQue& snd_que)
99 throw (std::runtime_error):
100 ipin(ipin), ipout(ipout), req_que(req_que), res_que(res_que),
104 while (parsezone(is, z))
109 std::cerr << "NameServer::NameServer: " << z << "\n\n";
114 std::cout << "NameServer::NameServer: req_que_id = " << req_que.que_id
115 << ", res_que_id = " << res_que.que_id
116 << ", snd_que_id = " << snd_que.que_id << "\n";
120 /// Devuelve la parte izquierda de n, si la parte derecha coincide exactamente
121 /// con m, si no devuelve un vector vacío.
122 /// Elemplo: name_split("mi.domi.nio", "domi.nio") == ["mi"]
123 /// name_split("dos.mi.domi.nio", "domi.nio") == ["dos", "mi"]
124 /// name_split("domi.nio", "domi.nio") == []
125 /// name_split("papeli.nio", "domi.nio") == []
126 static NameServer::Name
127 name_split(NameServer::Name n, NameServer::Name m)
130 std::reverse(n.begin(), n.end());
131 std::reverse(m.begin(), m.end());
132 // Si m es más grande o igual que n, no hay nada que hacer
133 if (n.size() <= m.size())
135 // Si no coincide la parte derecha, no hay nada que hacer
136 NameServer::Name::size_type i;
137 for (i = 0; i < m.size(); ++i)
140 // Si era todo igual y sobran cosas, devolvemos lo que "sobra"
143 std::reverse(r.begin(), r.end());
145 std::cerr << "NameServer::name_split(" << n << ", " << m << ") -> "
151 /// Devuelve -1 si es un nombre "hijo" (la parte derecha de n está contenida
152 /// completamente en m, pero m y n no son iguales), 0 si m == n y 1 si es
153 /// "padre" (m no coincide con la parte derecha de n).
154 /// Elemplo: namecmp("mi.domi.nio", "domi.nio") == -1
155 /// namecmp("otra.cosa", "domi.nio") == 1
156 /// namecmp("papeli.nio", "domi.nio") == 1
157 /// namecmp("domi.nio", "domi.nio") == 0
160 NC_DIRECT_CHILD, ///> Hijo directo, es decir, está en la zona m
161 NC_CHILD, ///> Hijo indirecto, está en una zona que cuelga de m
162 NC_EQUAL, ///> Es el host de la zona m
163 NC_DIRECT_PARENT, ///> Padre directo, es decir, coincide en parte con m
164 NC_PARENT ///> Padre indirecto, es completamente distinto a m
167 static int name_cmp(const NameServer::Name& n, const NameServer::Name& m)
169 // Si m es más grande que n, seguro es padre
170 if (n.size() < m.size())
172 // Si no coincide la parte derecha, seguro es padre
173 NameServer::Name::size_type i;
174 for (i = m.size(); i > 0; --i)
175 if (n[i-1] != m[i-1])
177 // Si era todo igual y sobran cosas, es hijo
180 // Si no, son iguales.
185 struct search_zone: std::unary_function< NameServer::Zone, bool >
188 ResolvProtoResponse resp;
189 const NameServer::Name& name;
190 search_zone(const NameServer::Name& n): local(false), name(n) {}
191 bool operator() (const NameServer::Zone& z)
194 NameServer::Name local_part = name_split(name, z.name);
195 if (!local_part.empty()) // Está en esta zona
198 std::string n = local_part.back(); // Obtengo última parte
200 typedef NameServer::Zone::records_t::const_iterator itt;
201 std::pair<itt, itt> p = z.records.equal_range(n);
202 for (; p.first != p.second; ++p.first)
204 const NameServer::Record& r = (*p.first).second;
205 // Tiene que buscar solo A porque era un nombre
206 if ((local_part.size() == 1) && (r.type != NameServer::Record::A))
208 // Tiene que seguir para abajo, solo busca NS
209 if ((local_part.size() > 1) && r.type != NameServer::Record::NS)
212 resp.ret = (r.type == NameServer::Record::NS) ? RP_RES_NS
215 resp.ips.push_back(r.ip);
222 /// Resuelve un nombre de forma directa (no recursiva)
223 ResolvProtoResponse NameServer::resolv_direct(const Name& n)
226 std::cout << "NameServer::resolv_direct()\n";
229 std::cerr << "NameServer::resolv_direct -> tratando de resolver: "
234 for (zones_t::const_iterator i = zones.begin(); i!= zones.end(); ++i)
235 if ((found = zs(*i)))
240 std::cerr << "NameServer::resolv_direct -> found (local/hijo): "
248 std::cerr << "NameServer::resolv_direct -> NOT FOUND (es local pero "
251 return ResolvProtoResponse(RP_RES_NOTFOUND);
253 cache_t::const_iterator i = cache.find(n);
255 if (i != cache.end())
258 std::cerr << "NameServer::resolv_direct -> found (en cache): "
259 << i->second << "\n";
261 const CacheRecord& cr = i->second;
262 return ResolvProtoResponse(RP_RES_A, cr.ttl, cr.ips);
266 // Busco una zona con padre para ver si puedo "trepar"
267 for (zones_t::const_iterator i = zones.begin(); i != zones.end(); ++i)
270 std::cerr << "NameServer::resolv_direct -> evaluando padre "
271 << i->parent << "\n";
273 if (i->parent != IPAddr(0))
276 std::cerr << "NameServer::resolv_direct -> found (al padre): "
277 << i->parent << "\n";
279 ResolvProtoResponse rpr(RP_RES_NS, i->ttl);
280 rpr.ips.push_back(i->parent);
286 std::cerr << "NameServer::resolv_direct -> NOT FOUND (no hay padre)\n";
288 // No hay padre, no puedo hacer nada más
289 return ResolvProtoResponse(RP_RES_NOTFOUND);
292 /// Resuelve un nombre de forma recursiva
293 ResolvProtoResponse NameServer::resolv_recursive(const Name& n)
296 std::cout << "NameServer::resolv_recursive()\n";
298 ResolvProtoResponse rpr = resolv_direct(n);
303 std::cerr << "NameServer::resolv_recursive -> redirect a "
306 return resolv_recursive_r(n, rpr); // Sigo "bajando"
309 std::cerr << "NameServer::resolv_recursive -> gotcha! "
312 // TODO agregar a cache
315 return rpr; // Devuelvo el A o NOTFOUND
318 /// Resuelve un nombre de forma recursiva entrando a otros ns
319 ResolvProtoResponse NameServer::resolv_recursive_r(const Name& n,
320 ResolvProtoResponse rpr)
323 std::cout << "NameServer::resolv_recursive_r()\n";
325 ResolvProtoResponse r;
326 for (ResolvProtoResponse::ipvec_t::const_iterator ip = rpr.ips.begin();
327 ip != rpr.ips.end(); ++ip)
334 std::cerr << "NameServer::resolv_recursive_r -> redirect a "
337 return resolv_recursive_r(n, r); // Sigo "bajando"
338 case RP_RES_NOTFOUND:
340 std::cerr << "NameServer::resolv_recursive_r -> NOT FOUND en "
341 << *ip << ", sigo probando\n";
343 break; // Sigo probando del mismo nivel
346 std::cerr << "NameServer::resolv_recursive_r -> gotcha! "
349 // TODO agregar a cache
354 std::cerr << "NameServer::resolv_recursive_r -> NOT FOUND, no hay más "
357 return r; // NOTFOUND
360 /// Consulta a otro name server sobre un nombre
361 ResolvProtoResponse NameServer::query(const Name& n, const IPAddr& ip)
364 std::cout << "NameServer::query()\n";
366 ResolvProtoRequest r(std::string(n), RP_REQ_DIRECT);
368 std::cerr << "NameServer::query -> pidiendo " << r << " a " << ip << "\n";
370 // Envía a través de la cola de envío
371 snd_que.transmit(std::string(r), ip);
372 Dev::mac_type mac = ip;
373 std::string buf = res_que.receive(mac);
374 ResolvProtoResponse resp(buf);
376 std::cerr << "NameServer::query -> recibido " << resp << " de "
382 void NameServer::recv_loop()
385 std::cout << "NameServer::recv_loop()\n";
391 std::string s = ipin.recv(proto, src, dst);
393 std::cout << "NameServer::recv_loop() -> recibido len=" << s.size()
394 << " de " << src << " para " << dst << " (proto = "
395 << unsigned(proto) << ")\n";
397 if (proto == RESOLV_PROTO) // Si es para nosotros
400 memcpy(&type, s.data(), sizeof(uint8_t));
405 case RP_REQ_RECURSIVE:
407 std::cout << "---> " << ResolvProtoRequest(s) << "\n";
409 req_que.transmit(s, src); // Encolo
414 std::cout << "---> " << ResolvProtoResponse(s) << "\n";
416 res_que.transmit(s, src); // Encolo
422 void NameServer::send_loop()
425 std::cout << "NameServer::send_loop()\n";
429 Dev::mac_type mac = 0;
430 std::string buf = snd_que.receive(mac);
432 std::cout << "NameServer::send_loop() -> envío request "
433 << ResolvProtoResponse(buf) << "\n";
435 ipout.send(buf, RESOLV_PROTO, IPAddr(mac));
439 void NameServer::req_loop()
442 std::cout << "NameServer::req_loop()\n";
446 Dev::mac_type mac = 0;
447 ResolvProtoRequest req(req_que.receive(mac));
449 std::cout << "NameServer::req_loop() -> recibido " << req << "\n";
451 ResolvProtoResponse res
452 = (req.query_type == RP_REQ_DIRECT)
453 ? resolv_direct(req.name)
454 : resolv_recursive(req.name);
456 std::cout << "NameServer::req_loop() -> respondo " << res << "\n";
458 snd_que.transmit(std::string(res), IPAddr(mac));
462 std::ostream& operator<< (std::ostream& os, const NameServer::Record::type_t& t)
464 if (t == NameServer::Record::NS)
470 std::ostream& operator<< (std::ostream& os, const NameServer::Record& r)
472 return os << r.type << " " << r.ip;
475 std::ostream& operator<< (std::ostream& os,
476 const NameServer::Zone::records_t::value_type& p)
478 return os << p.first << ": " << p.second;
481 std::ostream& operator<< (std::ostream& os, const NameServer::Zone& z)
483 os << "Zone " << z.name << " " << z.ttl << " " << z.parent << "\n";
484 std::copy(z.records.begin(), z.records.end(), std::ostream_iterator<
485 NameServer::Zone::records_t::value_type >(os, "\n"));
489 std::ostream& operator<< (std::ostream& os, const NameServer::CacheRecord& cr)
491 os << "CacheRecord(ttl=" << cr.ttl << ", records=";
492 std::copy(cr.ips.begin(), cr.ips.end(),
493 std::ostream_iterator< IPAddr >(os, ","));
497 std::ostream& operator<< (std::ostream& os, const NameServer& ns)
499 os << "NameServer: zones[" << ns.zones.size() << "] (\n\n";
500 std::copy(ns.zones.begin(), ns.zones.end(),
501 std::ostream_iterator< NameServer::Zone >(os, "\n"));
505 // vim: set et sw=4 sts=4 :