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::iterator i = cache.find(n);
254 if (i != cache.end())
256 const CacheRecord& cr = i->second;
258 std::cerr << "NameServer::resolv_direct -> found (en cache): "
261 if (unsigned(time(NULL)) > cr.expire) // Expiró
265 std::cerr << " -> pero no sirve, expiró "
266 "hace unos " << (time(NULL) - cr.expire) << " segundos\n";
271 return ResolvProtoResponse(RP_RES_A, cr.ttl, cr.ips);
276 // Busco una zona con padre para ver si puedo "trepar"
277 for (zones_t::const_iterator i = zones.begin(); i != zones.end(); ++i)
280 std::cerr << "NameServer::resolv_direct -> evaluando padre "
281 << i->parent << "\n";
283 if (i->parent != IPAddr(0))
286 std::cerr << "NameServer::resolv_direct -> found (al padre): "
287 << i->parent << "\n";
289 ResolvProtoResponse rpr(RP_RES_NS, i->ttl);
290 rpr.ips.push_back(i->parent);
296 std::cerr << "NameServer::resolv_direct -> NOT FOUND (no hay padre)\n";
298 // No hay padre, no puedo hacer nada más
299 return ResolvProtoResponse(RP_RES_NOTFOUND);
302 /// Resuelve un nombre de forma recursiva
303 ResolvProtoResponse NameServer::resolv_recursive(const Name& n)
306 std::cout << "NameServer::resolv_recursive()\n";
308 ResolvProtoResponse rpr = resolv_direct(n);
313 std::cerr << "NameServer::resolv_recursive -> redirect a "
316 return resolv_recursive_r(n, rpr); // Sigo "bajando"
319 std::cerr << "NameServer::resolv_recursive -> gotcha! "
324 return rpr; // Devuelvo el A o NOTFOUND
327 /// Resuelve un nombre de forma recursiva entrando a otros ns
328 ResolvProtoResponse NameServer::resolv_recursive_r(const Name& n,
329 ResolvProtoResponse rpr)
332 std::cout << "NameServer::resolv_recursive_r()\n";
334 ResolvProtoResponse r;
335 for (ResolvProtoResponse::ipvec_t::const_iterator ip = rpr.ips.begin();
336 ip != rpr.ips.end(); ++ip)
343 std::cerr << "NameServer::resolv_recursive_r -> redirect a "
346 return resolv_recursive_r(n, r); // Sigo "bajando"
347 case RP_RES_NOTFOUND:
349 std::cerr << "NameServer::resolv_recursive_r -> NOT FOUND en "
350 << *ip << ", sigo probando\n";
352 break; // Sigo probando del mismo nivel
355 std::cerr << "NameServer::resolv_recursive_r -> gotcha! "
362 std::cerr << "NameServer::resolv_recursive_r -> NOT FOUND, no hay más "
365 return r; // NOTFOUND
368 /// Consulta a otro name server sobre un nombre
369 ResolvProtoResponse NameServer::query(const Name& n, const IPAddr& ip)
372 std::cout << "NameServer::query()\n";
374 ResolvProtoRequest r(std::string(n), RP_REQ_DIRECT);
376 std::cerr << "NameServer::query -> pidiendo " << r << " a " << ip << "\n";
378 // Envía a través de la cola de envío
379 snd_que.transmit(std::string(r), ip);
380 Dev::mac_type mac = ip;
381 std::string buf = res_que.receive(mac);
382 ResolvProtoResponse resp(buf);
384 std::cerr << "NameServer::query -> recibido " << resp << " de "
388 if (resp.ret == RP_RES_A)
389 cache[n] = CacheRecord(time(NULL) + resp.ttl, resp.ttl, resp.ips);
393 void NameServer::recv_loop()
396 std::cout << "NameServer::recv_loop()\n";
402 std::string s = ipin.recv(proto, src, dst);
404 std::cout << "NameServer::recv_loop() -> recibido len=" << s.size()
405 << " de " << src << " para " << dst << " (proto = "
406 << unsigned(proto) << ")\n";
408 if (proto == RESOLV_PROTO) // Si es para nosotros
411 memcpy(&type, s.data(), sizeof(uint8_t));
416 case RP_REQ_RECURSIVE:
418 std::cout << "---> " << ResolvProtoRequest(s) << "\n";
420 req_que.transmit(s, src); // Encolo
425 std::cout << "---> " << ResolvProtoResponse(s) << "\n";
427 res_que.transmit(s, src); // Encolo
433 void NameServer::send_loop()
436 std::cout << "NameServer::send_loop()\n";
440 Dev::mac_type mac = 0;
441 std::string buf = snd_que.receive(mac);
444 memcpy(&type, buf.data(), sizeof(uint8_t));
445 std::cout << "NameServer::send_loop() -> envío ";
446 if (type == RP_REQ_DIRECT || type == RP_REQ_RECURSIVE)
447 std::cout << "request " << ResolvProtoRequest(buf) << "\n";
449 std::cout << "response " << ResolvProtoResponse(buf) << "\n";
451 ipout.send(buf, RESOLV_PROTO, IPAddr(mac));
455 void NameServer::req_loop()
458 std::cout << "NameServer::req_loop()\n";
463 std::cout << "----------------------------------------------------\n";
465 Dev::mac_type mac = 0;
466 ResolvProtoRequest req(req_que.receive(mac));
468 std::cout << "NameServer::req_loop() -> recibido " << req << "\n";
470 ResolvProtoResponse res
471 = (req.query_type == RP_REQ_DIRECT)
472 ? resolv_direct(req.name)
473 : resolv_recursive(req.name);
475 std::cout << "NameServer::req_loop() -> respondo " << res << "\n";
477 snd_que.transmit(std::string(res), IPAddr(mac));
481 std::ostream& operator<< (std::ostream& os, const NameServer::Record::type_t& t)
483 if (t == NameServer::Record::NS)
489 std::ostream& operator<< (std::ostream& os, const NameServer::Record& r)
491 return os << r.type << " " << r.ip;
494 std::ostream& operator<< (std::ostream& os,
495 const NameServer::Zone::records_t::value_type& p)
497 return os << p.first << ": " << p.second;
500 std::ostream& operator<< (std::ostream& os, const NameServer::Zone& z)
502 os << "Zone " << z.name << " " << z.ttl << " " << z.parent << "\n";
503 std::copy(z.records.begin(), z.records.end(), std::ostream_iterator<
504 NameServer::Zone::records_t::value_type >(os, "\n"));
508 std::ostream& operator<< (std::ostream& os, const NameServer::CacheRecord& cr)
510 os << "CacheRecord(expire=" << cr.expire << " [now=" << time(NULL)
511 << "], ttl=" << cr.ttl << ", records=";
512 std::copy(cr.ips.begin(), cr.ips.end(),
513 std::ostream_iterator< IPAddr >(os, ","));
517 std::ostream& operator<< (std::ostream& os, const NameServer& ns)
519 os << "NameServer: zones[" << ns.zones.size() << "] (\n\n";
520 std::copy(ns.zones.begin(), ns.zones.end(),
521 std::ostream_iterator< NameServer::Zone >(os, "\n"));
525 // vim: set et sw=4 sts=4 :