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 ()
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)
100 throw (std::runtime_error)
103 while (parsezone(is, z))
108 std::cerr << "NameServer: " << z << "\n\n";
113 /// Devuelve la parte izquierda de n, si la parte derecha coincide exactamente
114 /// con m, si no devuelve un vector vacío.
115 /// Elemplo: name_split("mi.domi.nio", "domi.nio") == ["mi"]
116 /// name_split("dos.mi.domi.nio", "domi.nio") == ["dos", "mi"]
117 /// name_split("domi.nio", "domi.nio") == []
118 /// name_split("papeli.nio", "domi.nio") == []
119 static NameServer::Name
120 name_split(NameServer::Name n, NameServer::Name m)
123 std::reverse(n.begin(), n.end());
124 std::reverse(m.begin(), m.end());
125 // Si m es más grande o igual que n, no hay nada que hacer
126 if (n.size() <= m.size())
128 // Si no coincide la parte derecha, no hay nada que hacer
129 NameServer::Name::size_type i;
130 for (i = 0; i < m.size(); ++i)
133 // Si era todo igual y sobran cosas, devolvemos lo que "sobra"
136 std::reverse(r.begin(), r.end());
138 std::cerr << "name_split(" << n << ", " << m << ") -> " << r << "\n";
143 /// Devuelve -1 si es un nombre "hijo" (la parte derecha de n está contenida
144 /// completamente en m, pero m y n no son iguales), 0 si m == n y 1 si es
145 /// "padre" (m no coincide con la parte derecha de n).
146 /// Elemplo: namecmp("mi.domi.nio", "domi.nio") == -1
147 /// namecmp("otra.cosa", "domi.nio") == 1
148 /// namecmp("papeli.nio", "domi.nio") == 1
149 /// namecmp("domi.nio", "domi.nio") == 0
152 NC_DIRECT_CHILD, ///> Hijo directo, es decir, está en la zona m
153 NC_CHILD, ///> Hijo indirecto, está en una zona que cuelga de m
154 NC_EQUAL, ///> Es el host de la zona m
155 NC_DIRECT_PARENT, ///> Padre directo, es decir, coincide en parte con m
156 NC_PARENT ///> Padre indirecto, es completamente distinto a m
159 static int name_cmp(const NameServer::Name& n, const NameServer::Name& m)
161 // Si m es más grande que n, seguro es padre
162 if (n.size() < m.size())
164 // Si no coincide la parte derecha, seguro es padre
165 NameServer::Name::size_type i;
166 for (i = m.size(); i > 0; --i)
167 if (n[i-1] != m[i-1])
169 // Si era todo igual y sobran cosas, es hijo
172 // Si no, son iguales.
177 struct search_zone: std::unary_function< NameServer::Zone, bool >
180 ResolvProtoResponse resp;
181 const NameServer::Name& name;
182 search_zone(const NameServer::Name& n): local(false), name(n) {}
183 bool operator() (const NameServer::Zone& z)
186 NameServer::Name local_part = name_split(name, z.name);
187 if (!local_part.empty()) // Está en esta zona
190 std::string n = local_part.back(); // Obtengo última parte
192 typedef NameServer::Zone::records_t::const_iterator itt;
193 std::pair<itt, itt> p = z.records.equal_range(n);
194 for (; p.first != p.second; ++p.first)
196 const NameServer::Record& r = (*p.first).second;
197 // Tiene que buscar solo A porque era un nombre
198 if ((local_part.size() == 1) && (r.type != NameServer::Record::A))
200 // Tiene que seguir para abajo, solo busca NS
201 if ((local_part.size() > 1) && r.type != NameServer::Record::NS)
204 resp.ret = (r.type == NameServer::Record::NS)
205 ? ResolvProtoResponse::R_NS : ResolvProtoResponse::R_A;
207 resp.ips.push_back(r.ip);
214 /// Resuelve un nombre de forma directa (no recursiva)
215 ResolvProtoResponse NameServer::resolv_direct(const Name& n)
218 std::cerr << "resolv_direct -> tratando de resolver: " << n << "\n";
222 for (zones_t::const_iterator i = zones.begin(); i!= zones.end(); ++i)
223 if ((found = zs(*i)))
228 std::cerr << "resolv_direct found (local/hijo): " << zs.resp << "\n";
235 std::cerr << "resolv_direct NOT FOUND (es local pero no existe)\n";
237 return ResolvProtoResponse(ResolvProtoResponse::R_NOTFOUND);
239 cache_t::const_iterator i = cache.find(n);
241 if (i != cache.end())
244 std::cerr << "resolv_direct found (en cache): " << i->second << "\n";
246 const CacheRecord& cr = i->second;
247 return ResolvProtoResponse(ResolvProtoResponse::R_A, cr.ttl, cr.ips);
251 // Busco una zona con padre para ver si puedo "trepar"
252 for (zones_t::const_iterator i = zones.begin(); i != zones.end(); ++i)
255 std::cerr << "resolv_direct -> evaluando padre " << i->parent
258 if (i->parent != IPAddr(0))
261 std::cerr << "resolv_direct found (al padre): "
262 << i->parent << "\n";
264 ResolvProtoResponse rpr(ResolvProtoResponse::R_NS, i->ttl);
265 rpr.ips.push_back(i->parent);
271 std::cerr << "resolv_direct NOT FOUND (no hay padre)\n";
273 // No hay padre, no puedo hacer nada más
274 return ResolvProtoResponse(ResolvProtoResponse::R_NOTFOUND);
277 /// Resuelve un nombre de forma recursiva
278 ResolvProtoResponse NameServer::resolv_recursive(const Name& n)
280 ResolvProtoResponse rpr = resolv_direct(n);
283 case ResolvProtoResponse::R_NS:
285 std::cerr << "resolv_recursive -> redirect a " << rpr << "\n";
287 return resolv_recursive_r(n, rpr); // Sigo "bajando"
288 case ResolvProtoResponse::R_A:
290 std::cerr << "resolv_recursive -> gotcha! " << rpr << "\n";
292 // TODO agregar a cache
295 return rpr; // Devuelvo el A o NOTFOUND
298 /// Resuelve un nombre de forma recursiva entrando a otros ns
299 ResolvProtoResponse NameServer::resolv_recursive_r(const Name& n,
300 ResolvProtoResponse rpr)
302 ResolvProtoResponse r;
303 for (ResolvProtoResponse::ipvec_t::const_iterator ip = rpr.ips.begin();
304 ip != rpr.ips.end(); ++ip)
309 case ResolvProtoResponse::R_NS:
311 std::cerr << "resolv_recursive_r -> redirect a " << r << "\n";
313 return resolv_recursive_r(n, r); // Sigo "bajando"
314 case ResolvProtoResponse::R_NOTFOUND:
316 std::cerr << "resolv_recursive_r -> NOT FOUND en " << *ip
317 << ", sigo probando\n";
319 break; // Sigo probando del mismo nivel
320 case ResolvProtoResponse::R_A:
322 std::cerr << "resolv_recursive_r -> gotcha! " << r << "\n";
324 // TODO agregar a cache
329 std::cerr << "resolv_recursive_r -> NOT FOUND, no hay más por hacer\n";
331 return r; // NOTFOUND
334 /// Consulta a otro name server sobre un nombre
335 ResolvProtoResponse NameServer::query(const Name& n, const IPAddr& ip)
337 // TODO IMPLEMENTAR!!!
339 std::cerr << "query -> Haciendo query dummy\n";
341 if (ip == IPAddr("10.10.10.1"))
343 ResolvProtoResponse r(ResolvProtoResponse::R_NS, 500);
344 r.ips.push_back(IPAddr("10.10.10.2"));
345 r.ips.push_back(IPAddr("10.10.10.3"));
348 else if (ip == IPAddr("10.10.10.2"))
350 return ResolvProtoResponse(ResolvProtoResponse::R_NOTFOUND);
352 else if (ip == IPAddr("10.10.10.3"))
354 ResolvProtoResponse r(ResolvProtoResponse::R_NS, 666);
355 r.ips.push_back(IPAddr("10.10.10.4"));
360 ResolvProtoResponse r(ResolvProtoResponse::R_A, 1500);
361 r.ips.push_back(IPAddr("10.10.10.5"));
362 r.ips.push_back(IPAddr("10.10.10.6"));
367 std::ostream& operator<< (std::ostream& os, const NameServer::Record::type_t& t)
369 if (t == NameServer::Record::NS)
375 std::ostream& operator<< (std::ostream& os, const NameServer::Record& r)
377 return os << r.type << " " << r.ip;
380 std::ostream& operator<< (std::ostream& os,
381 const NameServer::Zone::records_t::value_type& p)
383 return os << p.first << ": " << p.second;
386 std::ostream& operator<< (std::ostream& os, const NameServer::Zone& z)
388 os << "Zone " << z.name << " " << z.ttl << " " << z.parent << "\n";
389 std::copy(z.records.begin(), z.records.end(), std::ostream_iterator<
390 NameServer::Zone::records_t::value_type >(os, "\n"));
394 std::ostream& operator<< (std::ostream& os, const NameServer::CacheRecord& cr)
396 os << "CacheRecord(ttl=" << cr.ttl << ", records=";
397 std::copy(cr.ips.begin(), cr.ips.end(),
398 std::ostream_iterator< IPAddr >(os, ","));
402 std::ostream& operator<< (std::ostream& os, const NameServer& ns)
404 os << "NameServer: zones[" << ns.zones.size() << "] (\n\n";
405 std::copy(ns.zones.begin(), ns.zones.end(),
406 std::ostream_iterator< NameServer::Zone >(os, "\n"));
410 // vim: set et sw=4 sts=4 :