-
Notifications
You must be signed in to change notification settings - Fork 30
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
a4a1dd8
commit f5e8dd5
Showing
1 changed file
with
17 additions
and
25 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |