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 << "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 << "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 << "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: " << z << "\n\n";
114 std::cout << "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 << "name_split(" << n << ", " << m << ") -> " << r << "\n";
150 /// Devuelve -1 si es un nombre "hijo" (la parte derecha de n está contenida
151 /// completamente en m, pero m y n no son iguales), 0 si m == n y 1 si es
152 /// "padre" (m no coincide con la parte derecha de n).
153 /// Elemplo: namecmp("mi.domi.nio", "domi.nio") == -1
154 /// namecmp("otra.cosa", "domi.nio") == 1
155 /// namecmp("papeli.nio", "domi.nio") == 1
156 /// namecmp("domi.nio", "domi.nio") == 0
159 NC_DIRECT_CHILD, ///> Hijo directo, es decir, está en la zona m
160 NC_CHILD, ///> Hijo indirecto, está en una zona que cuelga de m
161 NC_EQUAL, ///> Es el host de la zona m
162 NC_DIRECT_PARENT, ///> Padre directo, es decir, coincide en parte con m
163 NC_PARENT ///> Padre indirecto, es completamente distinto a m
166 static int name_cmp(const NameServer::Name& n, const NameServer::Name& m)
168 // Si m es más grande que n, seguro es padre
169 if (n.size() < m.size())
171 // Si no coincide la parte derecha, seguro es padre
172 NameServer::Name::size_type i;
173 for (i = m.size(); i > 0; --i)
174 if (n[i-1] != m[i-1])
176 // Si era todo igual y sobran cosas, es hijo
179 // Si no, son iguales.
184 struct search_zone: std::unary_function< NameServer::Zone, bool >
187 ResolvProtoResponse resp;
188 const NameServer::Name& name;
189 search_zone(const NameServer::Name& n): local(false), name(n) {}
190 bool operator() (const NameServer::Zone& z)
193 NameServer::Name local_part = name_split(name, z.name);
194 if (!local_part.empty()) // Está en esta zona
197 std::string n = local_part.back(); // Obtengo última parte
199 typedef NameServer::Zone::records_t::const_iterator itt;
200 std::pair<itt, itt> p = z.records.equal_range(n);
201 for (; p.first != p.second; ++p.first)
203 const NameServer::Record& r = (*p.first).second;
204 // Tiene que buscar solo A porque era un nombre
205 if ((local_part.size() == 1) && (r.type != NameServer::Record::A))
207 // Tiene que seguir para abajo, solo busca NS
208 if ((local_part.size() > 1) && r.type != NameServer::Record::NS)
211 resp.ret = (r.type == NameServer::Record::NS) ? RP_RES_NS
214 resp.ips.push_back(r.ip);
221 /// Resuelve un nombre de forma directa (no recursiva)
222 ResolvProtoResponse NameServer::resolv_direct(const Name& n)
225 std::cout << "NameServer::resolv_direct()\n";
228 std::cerr << "resolv_direct -> tratando de resolver: " << n << "\n";
232 for (zones_t::const_iterator i = zones.begin(); i!= zones.end(); ++i)
233 if ((found = zs(*i)))
238 std::cerr << "resolv_direct found (local/hijo): " << zs.resp << "\n";
245 std::cerr << "resolv_direct NOT FOUND (es local pero no existe)\n";
247 return ResolvProtoResponse(RP_RES_NOTFOUND);
249 cache_t::const_iterator i = cache.find(n);
251 if (i != cache.end())
254 std::cerr << "resolv_direct found (en cache): " << i->second << "\n";
256 const CacheRecord& cr = i->second;
257 return ResolvProtoResponse(RP_RES_A, cr.ttl, cr.ips);
261 // Busco una zona con padre para ver si puedo "trepar"
262 for (zones_t::const_iterator i = zones.begin(); i != zones.end(); ++i)
265 std::cerr << "resolv_direct -> evaluando padre " << i->parent
268 if (i->parent != IPAddr(0))
271 std::cerr << "resolv_direct found (al padre): "
272 << i->parent << "\n";
274 ResolvProtoResponse rpr(RP_RES_NS, i->ttl);
275 rpr.ips.push_back(i->parent);
281 std::cerr << "resolv_direct NOT FOUND (no hay padre)\n";
283 // No hay padre, no puedo hacer nada más
284 return ResolvProtoResponse(RP_RES_NOTFOUND);
287 /// Resuelve un nombre de forma recursiva
288 ResolvProtoResponse NameServer::resolv_recursive(const Name& n)
291 std::cout << "NameServer::resolv_recursive()\n";
293 ResolvProtoResponse rpr = resolv_direct(n);
298 std::cerr << "resolv_recursive -> redirect a " << rpr << "\n";
300 return resolv_recursive_r(n, rpr); // Sigo "bajando"
303 std::cerr << "resolv_recursive -> gotcha! " << rpr << "\n";
305 // TODO agregar a cache
308 return rpr; // Devuelvo el A o NOTFOUND
311 /// Resuelve un nombre de forma recursiva entrando a otros ns
312 ResolvProtoResponse NameServer::resolv_recursive_r(const Name& n,
313 ResolvProtoResponse rpr)
316 std::cout << "NameServer::resolv_recursive_r()\n";
318 ResolvProtoResponse r;
319 for (ResolvProtoResponse::ipvec_t::const_iterator ip = rpr.ips.begin();
320 ip != rpr.ips.end(); ++ip)
327 std::cerr << "resolv_recursive_r -> redirect a " << r << "\n";
329 return resolv_recursive_r(n, r); // Sigo "bajando"
330 case RP_RES_NOTFOUND:
332 std::cerr << "resolv_recursive_r -> NOT FOUND en " << *ip
333 << ", sigo probando\n";
335 break; // Sigo probando del mismo nivel
338 std::cerr << "resolv_recursive_r -> gotcha! " << r << "\n";
340 // TODO agregar a cache
345 std::cerr << "resolv_recursive_r -> NOT FOUND, no hay más por hacer\n";
347 return r; // NOTFOUND
350 /// Consulta a otro name server sobre un nombre
351 ResolvProtoResponse NameServer::query(const Name& n, const IPAddr& ip)
354 std::cout << "NameServer::query()\n";
356 ResolvProtoRequest r(std::string(n), RP_REQ_DIRECT);
358 std::cerr << "query -> pidiendo " << r << " a " << ip << "\n";
360 // Envía a través de la cola de envío
361 snd_que.transmit(std::string(r), ip);
362 Dev::mac_type mac = ip;
363 std::string buf = res_que.receive(mac);
364 ResolvProtoResponse resp(buf);
366 std::cerr << "query -> recibido " << resp << " de " << ip << "\n";
371 void NameServer::recv_loop()
374 std::cout << "NameServer::recv_loop()\n";
380 std::string s = ipin.recv(proto, src, dst);
382 std::cout << "NameServer::recv_loop() -> recibido len=" << s.size()
383 << " de " << src << " para " << dst << " (proto = "
384 << unsigned(proto) << ")\n";
386 if (proto == RESOLV_PROTO) // Si es para nosotros
389 memcpy(&type, s.data(), sizeof(uint8_t));
394 case RP_REQ_RECURSIVE:
396 std::cout << "---> " << ResolvProtoRequest(s) << "\n";
398 req_que.transmit(s, src); // Encolo
403 std::cout << "---> " << ResolvProtoResponse(s) << "\n";
405 res_que.transmit(s, src); // Encolo
411 void NameServer::send_loop()
414 std::cout << "NameServer::send_loop()\n";
418 Dev::mac_type mac = 0;
419 std::string buf = snd_que.receive(mac);
421 std::cout << "NameServer::send_loop() -> envío request "
422 << ResolvProtoRequest(buf) << "\n";
424 ipout.send(buf, RESOLV_PROTO, IPAddr(mac));
428 void NameServer::req_loop()
431 std::cout << "NameServer::req_loop()\n";
435 Dev::mac_type mac = 0;
436 ResolvProtoRequest req(req_que.receive(mac));
438 std::cout << "NameServer::req_loop() -> recibido " << req << "\n";
440 ResolvProtoResponse res
441 = (req.query_type == RP_REQ_DIRECT)
442 ? resolv_direct(req.name)
443 : resolv_recursive(req.name);
445 std::cout << "NameServer::req_loop() -> respondo " << res << "\n";
447 snd_que.transmit(std::string(res), IPAddr(mac));
451 std::ostream& operator<< (std::ostream& os, const NameServer::Record::type_t& t)
453 if (t == NameServer::Record::NS)
459 std::ostream& operator<< (std::ostream& os, const NameServer::Record& r)
461 return os << r.type << " " << r.ip;
464 std::ostream& operator<< (std::ostream& os,
465 const NameServer::Zone::records_t::value_type& p)
467 return os << p.first << ": " << p.second;
470 std::ostream& operator<< (std::ostream& os, const NameServer::Zone& z)
472 os << "Zone " << z.name << " " << z.ttl << " " << z.parent << "\n";
473 std::copy(z.records.begin(), z.records.end(), std::ostream_iterator<
474 NameServer::Zone::records_t::value_type >(os, "\n"));
478 std::ostream& operator<< (std::ostream& os, const NameServer::CacheRecord& cr)
480 os << "CacheRecord(ttl=" << cr.ttl << ", records=";
481 std::copy(cr.ips.begin(), cr.ips.end(),
482 std::ostream_iterator< IPAddr >(os, ","));
486 std::ostream& operator<< (std::ostream& os, const NameServer& ns)
488 os << "NameServer: zones[" << ns.zones.size() << "] (\n\n";
489 std::copy(ns.zones.begin(), ns.zones.end(),
490 std::ostream_iterator< NameServer::Zone >(os, "\n"));
494 // vim: set et sw=4 sts=4 :