public void Quit() { ConsolePainter.WriteWarning($"Saving data to {CacheFilename}..."); SerializeCache(); closed = true; udpListener?.Dispose(); }
private static byte[] UpdatePacketFromCache(DnsPacket packet, ushort newId) { packet.UpdateTtl(); packet.UpdateTransactionId(newId); ConsolePainter.WriteResponse($"MESSAGE FROM CACHE:\n{packet}"); return(packet.Data); }
public DnsServer() { var dnsips = Dns.GetHostAddresses("ns1.e1.ru"); remoteDns = new IPEndPoint(dnsips[0], 53); cache = DeserializeCache(); var total = 0; foreach (var kvp in cache) { foreach (var _ in kvp.Value.Values) { total++; } } ConsolePainter.WriteWarning($"Deserialized {total} entries"); }
private void RemoveOldEntries() { var toDelete = new List <(ResourceType, string)>(); foreach (var recordType in cache) { foreach (var record in recordType.Value) { if (record.Value.IsOutdated()) { toDelete.Add((recordType.Key, record.Key)); } } } foreach (var element in toDelete) { ConsolePainter.WriteWarning($"Deleting {element.Item2} entry from cache..."); cache[element.Item1].Remove(element.Item2); } }
private byte[] GetAnswerFromBetterServer(byte[] query, Dictionary <string, DnsPacket> subCache) { using (var client = new UdpClient()) { client.Client.ReceiveTimeout = 2000; client.Send(query, query.Length, remoteDns); byte[] response; try { response = client.Receive(ref remoteDns); } catch (SocketException) { ConsolePainter.WriteWarning("Couldn't connect to the upper server. Check internet connection"); return(null); } var responsePacket = new DnsPacket(response); ConsolePainter.WriteResponse($"SENDING:\n{responsePacket}"); subCache[responsePacket.Questions[0].Name] = responsePacket; return(response); } }
private byte[] HandleRequest(byte[] data) { var query = new DnsPacket(data); ConsolePainter.WriteRequest($"GOT:\n{query}"); if (!query.IsQuery) { return(null); } foreach (var question in query.Questions) { if (SupportedTypes.Contains(question.Type)) { return(FindCachedAnswerOrResend(query, cache[question.Type])); } ConsolePainter.WriteWarning( $"Message with the type code {question.Type} is not currently supported!"); } return(null); }
private bool TryModifyCache(DnsPacket query, out DnsPacket cached) { var question = query.Questions[0]; if (cache[question.Type].TryGetValue(question.Name, out cached)) { ConsolePainter.WriteResponse($"MESSAGE FROM CACHE:\n{cached}"); return(true); } if (TryFindRightCachedRecord(query, out cached)) { var gen = DnsPacket.GenerateAnswer(query.TransactionId, query.Questions, question.Type == ResourceType.A ? cached.AdditionalRecords : cached.AuthoritiveServers); ConsolePainter.WriteResponse($"Modified from cache:\n{gen}"); cached = gen; cache[query.Questions[0].Type].Add(query.Questions[0].Name, gen); return(true); } cached = null; return(false); }