kapetan / dns

A DNS library written in C#
MIT License
418 stars 127 forks source link

Request.FromStream for handling DNS over TCP? #79

Closed GF-Huang closed 3 years ago

GF-Huang commented 3 years ago

Is there any plans? Or will accept any PRs?

kapetan commented 3 years ago

It's something I've considered and looked into before, but the problem is all the parsing and serializing is done using byte arrays, so this might require many changes. I'm not sure I want such big refactoring.

GF-Huang commented 3 years ago

Maybe a simplest workaround, but not best performance. And consider using PipeReader instead of List<byte> to improve performance.

public Task<Request> FromStream(Stream stream) {
    var reader = new Reader(stream);
    Request request = null;
    List<byte> data = new();
    do {
        var d = reader.ReadMoreData();
        if (d.Length != 0)
            data.AddRange(d);

        try {
            request = Request.FromArray(data);
            break;

        } catch {
            if (d.Length == 0) // no more data but still parse fail
                // throw something exception say invalid data parse fail
        }
    } while (request == null);
}

references:

kapetan commented 3 years ago

I'm not sure I like this approach, it might give people the impression that it's streaming the request, but it's actually reading everything into memory. Also people can add this in their code.

GF-Huang commented 3 years ago

So the only way is to refactor 😢

GF-Huang commented 3 years ago

I found that the DNS over TCP will contains a Length field at the first two bytes in the stream. So I think Request.FromStream is not necessary.

reference: https://tools.ietf.org/html/rfc7766#page-11