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! "
314 return rpr; // Devuelvo el A o NOTFOUND
317 /// Resuelve un nombre de forma recursiva entrando a otros ns
318 ResolvProtoResponse NameServer::resolv_recursive_r(const Name& n,
319 ResolvProtoResponse rpr)
322 std::cout << "NameServer::resolv_recursive_r()\n";
324 ResolvProtoResponse r;
325 for (ResolvProtoResponse::ipvec_t::const_iterator ip = rpr.ips.begin();
326 ip != rpr.ips.end(); ++ip)
333 std::cerr << "NameServer::resolv_recursive_r -> redirect a "
336 return resolv_recursive_r(n, r); // Sigo "bajando"
337 case RP_RES_NOTFOUND:
339 std::cerr << "NameServer::resolv_recursive_r -> NOT FOUND en "
340 << *ip << ", sigo probando\n";
342 break; // Sigo probando del mismo nivel
345 std::cerr << "NameServer::resolv_recursive_r -> gotcha! "
352 std::cerr << "NameServer::resolv_recursive_r -> NOT FOUND, no hay más "
355 return r; // NOTFOUND
358 /// Consulta a otro name server sobre un nombre
359 ResolvProtoResponse NameServer::query(const Name& n, const IPAddr& ip)
362 std::cout << "NameServer::query()\n";
364 ResolvProtoRequest r(std::string(n), RP_REQ_DIRECT);
366 std::cerr << "NameServer::query -> pidiendo " << r << " a " << ip << "\n";
368 // Envía a través de la cola de envío
369 snd_que.transmit(std::string(r), ip);
370 Dev::mac_type mac = ip;
371 std::string buf = res_que.receive(mac);
372 ResolvProtoResponse resp(buf);
374 std::cerr << "NameServer::query -> recibido " << resp << " de "
378 if (resp.ret == RP_RES_A)
379 cache[n] = CacheRecord(time(NULL) + resp.ttl, resp.ips);
383 void NameServer::recv_loop()
386 std::cout << "NameServer::recv_loop()\n";
392 std::string s = ipin.recv(proto, src, dst);
394 std::cout << "NameServer::recv_loop() -> recibido len=" << s.size()
395 << " de " << src << " para " << dst << " (proto = "
396 << unsigned(proto) << ")\n";
398 if (proto == RESOLV_PROTO) // Si es para nosotros
401 memcpy(&type, s.data(), sizeof(uint8_t));
406 case RP_REQ_RECURSIVE:
408 std::cout << "---> " << ResolvProtoRequest(s) << "\n";
410 req_que.transmit(s, src); // Encolo
415 std::cout << "---> " << ResolvProtoResponse(s) << "\n";
417 res_que.transmit(s, src); // Encolo
423 void NameServer::send_loop()
426 std::cout << "NameServer::send_loop()\n";
430 Dev::mac_type mac = 0;
431 std::string buf = snd_que.receive(mac);
434 memcpy(&type, buf.data(), sizeof(uint8_t));
435 std::cout << "NameServer::send_loop() -> envío ";
436 if (type == RP_REQ_DIRECT || type == RP_REQ_RECURSIVE)
437 std::cout << "request " << ResolvProtoRequest(buf) << "\n";
439 std::cout << "response " << ResolvProtoResponse(buf) << "\n";
441 ipout.send(buf, RESOLV_PROTO, IPAddr(mac));
445 void NameServer::req_loop()
448 std::cout << "NameServer::req_loop()\n";
452 Dev::mac_type mac = 0;
453 ResolvProtoRequest req(req_que.receive(mac));
455 std::cout << "NameServer::req_loop() -> recibido " << req << "\n";
457 ResolvProtoResponse res
458 = (req.query_type == RP_REQ_DIRECT)
459 ? resolv_direct(req.name)
460 : resolv_recursive(req.name);
462 std::cout << "NameServer::req_loop() -> respondo " << res << "\n";
464 snd_que.transmit(std::string(res), IPAddr(mac));
468 std::ostream& operator<< (std::ostream& os, const NameServer::Record::type_t& t)
470 if (t == NameServer::Record::NS)
476 std::ostream& operator<< (std::ostream& os, const NameServer::Record& r)
478 return os << r.type << " " << r.ip;
481 std::ostream& operator<< (std::ostream& os,
482 const NameServer::Zone::records_t::value_type& p)
484 return os << p.first << ": " << p.second;
487 std::ostream& operator<< (std::ostream& os, const NameServer::Zone& z)
489 os << "Zone " << z.name << " " << z.ttl << " " << z.parent << "\n";
490 std::copy(z.records.begin(), z.records.end(), std::ostream_iterator<
491 NameServer::Zone::records_t::value_type >(os, "\n"));
495 std::ostream& operator<< (std::ostream& os, const NameServer::CacheRecord& cr)
497 os << "CacheRecord(ttl=" << cr.ttl << ", records=";
498 std::copy(cr.ips.begin(), cr.ips.end(),
499 std::ostream_iterator< IPAddr >(os, ","));
503 std::ostream& operator<< (std::ostream& os, const NameServer& ns)
505 os << "NameServer: zones[" << ns.zones.size() << "] (\n\n";
506 std::copy(ns.zones.begin(), ns.zones.end(),
507 std::ostream_iterator< NameServer::Zone >(os, "\n"));
511 // vim: set et sw=4 sts=4 :