Skip to content

Commit

Permalink
Improve truncating
Browse files Browse the repository at this point in the history
  • Loading branch information
nekohasekai committed Feb 28, 2024
1 parent e7b9678 commit ba92b68
Showing 1 changed file with 16 additions and 27 deletions.
43 changes: 16 additions & 27 deletions client_truncate.go
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit ba92b68

Please sign in to comment.