Exemplo n.º 1
0
        public async Task <DnsAnswer> Query(DnsHeader query, CancellationToken token)
        {
            var raw = DnsByteExtensions.ToBytes(query).ToArray();

            var payload = DnsByteExtensions.ToBytes((ushort)raw.Length).Concat(raw).ToArray();
            var stream  = _socket.GetStream();

            await stream.WriteAsync(payload, 0, payload.Length, token);

            var buffer  = new byte[4096];
            var receive = await stream.ReadAsync(buffer, 0, buffer.Length, token);

            stream.Close();

            var offset         = 0;
            var responseLength = DnsByteExtensions.ReadUInt16(buffer, ref offset);

            var response = DnsByteExtensions.ReadBytes(buffer, responseLength, ref offset);

            if (response.Length != responseLength)
            {
                throw new InvalidOperationException();
            }

            return(DnsByteExtensions.FromBytes <DnsAnswer>(response));
        }
Exemplo n.º 2
0
        public async Task InvokeAsync(HttpContext context)
        {
            if (context.Request.Path != _middlewareConfig.Path)
            {
                await _next(context);

                return;
            }

            if (context.Request.GetTypedHeaders().Accept.All(x => x.MediaType != DnsMessageType))
            {
                context.Response.StatusCode = (int)HttpStatusCode.UnprocessableEntity;
                return;
            }

            var ms = await context.Request.BodyReader.ReadAsync(context.RequestAborted);

            var buffer = ms.Buffer.ToArray();

            var header = DnsByteExtensions.FromBytes <DnsHeader>(buffer);

            var answer = await _dnsClient.Query(header, context.RequestAborted);

            context.Response.Headers.Add("Content-Type", new StringValues(DnsMessageType));

            await context.Response.BodyWriter.WriteAsync(DnsByteExtensions.ToBytes(answer), context.RequestAborted);
        }
Exemplo n.º 3
0
        public void ReadQuery1Packet()
        {
            var header = DnsByteExtensions.FromBytes <DnsHeader>(SampleDnsPackets.Query1);

            Assert.Equal(DnsQueryClass.IN, header.QueryClass);
            Assert.Equal(DnsQueryType.A, header.QueryType);
            Assert.Equal("cognito-identity.us-east-1.amazonaws.com", header.Host);
            Assert.Equal(0, header.AnswerRecordCount);
            Assert.Equal(0, header.AdditionalRecordCount);
            Assert.Equal(1, header.QuestionCount);
            Assert.Equal(0, header.NameServerRecordCount);
            Assert.False(header.IsQueryResponse);
            Assert.False(header.Truncation);
            Assert.False(header.RecursionAvailable);
            Assert.True(header.RecusionDesired);
            Assert.Equal(DnsResponseCode.NoError, header.ResponseCode);

            var header2 = new DnsHeader
            {
                Id              = header.Id,
                QueryClass      = DnsQueryClass.IN,
                QueryType       = DnsQueryType.A,
                RecusionDesired = true,
                Labels          = header.Labels,
                QuestionCount   = 1,
            };

            var bytes = DnsByteExtensions.ToBytes(header2).ToArray();

            Assert.Equal(SampleDnsPackets.Query1, bytes);
        }
Exemplo n.º 4
0
        /// <inheritdoc/>
        public async Task <DnsAnswer> Query(DnsHeader query, CancellationToken token)
        {
            var raw = DnsByteExtensions.ToBytes(query).ToArray();

            var completionSource = _pending.GetOrAdd(ToMessageId(query), key => SendQueryInternal(key, raw, token));

            var result = await completionSource.Task;

            var answer = DnsByteExtensions.FromBytes <DnsAnswer>(result);

            // Copy the same ID from the request
            answer.Header.Id = query.Id;

            return(answer);
        }
Exemplo n.º 5
0
        /// <inheritdoc/>
        public IEnumerable <IEnumerable <byte> > WriteBytes()
        {
            yield return(DnsByteExtensions.ToBytes(MName.Split('.')));

            yield return(DnsByteExtensions.ToBytes(RName.Split('.')));

            yield return(DnsByteExtensions.ToBytes(Serial));

            yield return(DnsByteExtensions.ToBytes((int)Refresh.TotalSeconds));

            yield return(DnsByteExtensions.ToBytes((int)Retry.TotalSeconds));

            yield return(DnsByteExtensions.ToBytes((int)Expire.TotalSeconds));

            yield return(DnsByteExtensions.ToBytes((uint)Minimum.TotalSeconds));
        }
Exemplo n.º 6
0
        private async void Respond(UdpReceiveResult query, CancellationToken token)
        {
            var stopwatch = Stopwatch.StartNew();

            DnsHeader message;

            try
            {
                message = DnsByteExtensions.FromBytes <DnsHeader>(query.Buffer);
            }
            catch (Exception e)
            {
                _logger.LogCritical(e, "Unable to parse incoming packet: {0}", DnsByteExtensions.ToDebugString(query.Buffer));
                return;
            }

            DnsAnswer answer;

            try
            {
                answer = await _dnsClient.Query(message, token);
            }
            catch (Exception e)
            {
                _logger.LogCritical(e, "Unable to resolve {0}", message);
                return;
            }

            var answerBytes = DnsByteExtensions.ToBytes(answer).ToArray();

            try
            {
                await _listener.SendAsync(answerBytes, answerBytes.Length, query.RemoteEndPoint);
            }
            catch (Exception e)
            {
                _logger.LogCritical(e, "Unable to send back response to {0}", query.RemoteEndPoint);
                return;
            }

            _logger.LogTrace("Responded to DNS request for {Domain} in {ResponseTime}", message.Host, stopwatch.Elapsed.TotalSeconds);
        }
Exemplo n.º 7
0
 public DnsCacheEntry(DnsAnswer answer)
 {
     LowestRecordTimeToLive = answer.Answers.Min(x => x.TimeToLive);
     Data = DnsByteExtensions.ToBytes(answer);
 }
Exemplo n.º 8
0
        public void TestRoundTripAnswers(byte[] answerBytes)
        {
            var answer = DnsByteExtensions.FromBytes <DnsAnswer>(answerBytes);

            Assert.Equal(answer, DnsByteExtensions.FromBytes <DnsAnswer>(DnsByteExtensions.ToBytes(answer).ToArray()));
        }
Exemplo n.º 9
0
        public void TestRoundTripQueries(byte[] queryBytes)
        {
            var query = DnsByteExtensions.FromBytes <DnsHeader>(queryBytes);

            Assert.Equal(query, DnsByteExtensions.FromBytes <DnsHeader>(DnsByteExtensions.ToBytes(query).ToArray()));
        }
Exemplo n.º 10
0
        /// <inheritdoc/>
        public IEnumerable <IEnumerable <byte> > WriteBytes()
        {
            yield return(DnsByteExtensions.ToBytes(Preference));

            yield return(DnsByteExtensions.ToBytes(Exchange.Split('.')));
        }
Exemplo n.º 11
0
 /// <inheritdoc/>
 public IEnumerable <IEnumerable <byte> > WriteBytes()
 {
     yield return(DnsByteExtensions.ToBytes(Text.Split('.')));
 }