Skip to content

Commit

Permalink
Improve truncating
Browse files Browse the repository at this point in the history
  • Loading branch information
nekohasekai committed Mar 2, 2024
1 parent c2ca97c commit 4275776
Showing 1 changed file with 17 additions and 25 deletions.
42 changes: 17 additions & 25 deletions client_truncate.go
Original file line number Diff line number Diff line change
@@ -1,37 +1,29 @@
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, headroom 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(headroom*2 + 1 + responseLen)
buffer.Resize(headroom, 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
}

0 comments on commit 4275776

Please sign in to comment.