From ba92b681e1a53ee7a07170c8128b24e6fe586c8b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=96=E7=95=8C?= Date: Wed, 28 Feb 2024 22:41:30 +0800 Subject: [PATCH] Improve truncating --- client_truncate.go | 43 ++++++++++++++++--------------------------- 1 file changed, 16 insertions(+), 27 deletions(-) diff --git a/client_truncate.go b/client_truncate.go index 50a9a38..a0b4afd 100644 --- a/client_truncate.go +++ b/client_truncate.go @@ -1,37 +1,26 @@ package dns -import "github.com/miekg/dns" +import ( + "github.com/sagernet/sing/common/buf" -func TruncateDNSMessage(request *dns.Msg, response *dns.Msg) (*dns.Msg, int) { + "github.com/miekg/dns" +) + +func TruncateDNSMessage(request *dns.Msg, response *dns.Msg, frontHeadroom int) (*buf.Buffer, error) { maxLen := 512 if edns0Option := request.IsEdns0(); edns0Option != nil { - if udpSize := int(edns0Option.UDPSize()); udpSize > 0 { + if udpSize := int(edns0Option.UDPSize()); udpSize > 512 { maxLen = udpSize } } - return truncateDNSMessage(response, maxLen) -} - -func truncateDNSMessage(response *dns.Msg, maxLen int) (*dns.Msg, int) { - responseLen := response.Len() - if responseLen <= maxLen { - return response, responseLen - } - newResponse := *response - response = &newResponse - response.Compress = true - responseLen = response.Len() - if responseLen <= maxLen { - return response, responseLen - } - for len(response.Answer) > 0 && responseLen > maxLen { - response.Answer = response.Answer[:len(response.Answer)-1] - response.Truncated = true - responseLen = response.Len() - } - if responseLen > maxLen { - response.Ns = nil - response.Extra = nil + response.Truncate(maxLen) + buffer := buf.NewSize(frontHeadroom + 1 + maxLen) + buffer.Resize(frontHeadroom, 0) + rawMessage, err := response.PackBuffer(buffer.FreeBytes()) + if err != nil { + buffer.Release() + return nil, err } - return response, response.Len() + buffer.Truncate(len(rawMessage)) + return buffer, nil }