github.com/xraypb/Xray-core@v1.8.1/transport/internet/headers/dns/dns.go (about)

     1  package dns
     2  
     3  import (
     4  	"context"
     5  	"encoding/binary"
     6  
     7  	"github.com/miekg/dns"
     8  	"github.com/xraypb/Xray-core/common"
     9  	"github.com/xraypb/Xray-core/common/dice"
    10  )
    11  
    12  type DNS struct {
    13  	header []byte
    14  }
    15  
    16  func (d DNS) Size() int32 {
    17  	return int32(len(d.header))
    18  }
    19  
    20  // Serialize implements PacketHeader.
    21  func (d DNS) Serialize(b []byte) {
    22  	copy(b, d.header)
    23  	binary.BigEndian.PutUint16(b[0:], dice.RollUint16()) // random transaction ID
    24  }
    25  
    26  // NewDNS returns a new DNS instance based on given config.
    27  func NewDNS(ctx context.Context, config interface{}) (interface{}, error) {
    28  	var header []byte
    29  
    30  	header = binary.BigEndian.AppendUint16(header, 0x0000) // Transaction ID
    31  	header = binary.BigEndian.AppendUint16(header, 0x0100) // Flags: Standard query
    32  	header = binary.BigEndian.AppendUint16(header, 0x0001) // Questions
    33  	header = binary.BigEndian.AppendUint16(header, 0x0000) // Answer RRs
    34  	header = binary.BigEndian.AppendUint16(header, 0x0000) // Authority RRs
    35  	header = binary.BigEndian.AppendUint16(header, 0x0000) // Additional RRs
    36  
    37  	buf := make([]byte, 0x100)
    38  
    39  	off1, err := dns.PackDomainName(dns.Fqdn(config.(*Config).Domain), buf, 0, nil, false)
    40  	if err != nil {
    41  		return nil, err
    42  	}
    43  
    44  	header = append(header, buf[:off1]...)
    45  
    46  	header = binary.BigEndian.AppendUint16(header, 0x0001) // Type: A
    47  	header = binary.BigEndian.AppendUint16(header, 0x0001) // Class: IN
    48  
    49  	return DNS{
    50  		header: header,
    51  	}, nil
    52  }
    53  
    54  func init() {
    55  	common.Must(common.RegisterConfig((*Config)(nil), NewDNS))
    56  }