├── .gitignore ├── coverage_badge.png ├── Dockerfile ├── .github ├── FUNDING.yml └── workflows │ ├── release.yml │ └── test.yml ├── transport ├── tls_test.go ├── dnscrypt_test.go ├── quic_test.go ├── transport.go ├── tls.go ├── odoh_test.go ├── plain_test.go ├── plain.go ├── dnscrypt.go ├── http_test.go ├── transport_test.go ├── http.go ├── quic.go ├── odoh.go └── LICENSE ├── update-usage-readme.sh ├── output ├── pretty_test.go ├── structured.go ├── ede.go ├── output_test.go ├── output.go ├── raw.go └── pretty.go ├── util ├── util_test.go ├── util.go └── tls │ └── tls.go ├── go.mod ├── .goreleaser.yml ├── xfr.go ├── resolver.go ├── go.sum ├── README.md ├── cli └── cli.go ├── main.go ├── main_test.go └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | dist/ 3 | q 4 | cover.out 5 | README.tmp.md 6 | *_recaxfr/ 7 | -------------------------------------------------------------------------------- /coverage_badge.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/natesales/q/HEAD/coverage_badge.png -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM alpine:latest 2 | COPY q /usr/bin/q 3 | ENTRYPOINT ["/usr/bin/q"] 4 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: ["natesales"] 4 | -------------------------------------------------------------------------------- /transport/tls_test.go: -------------------------------------------------------------------------------- 1 | package transport 2 | 3 | func tlsTransport() *TLS { 4 | return &TLS{ 5 | Common: Common{ 6 | Server: "dns.quad9.net:853", 7 | ReuseConn: false, 8 | }, 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /transport/dnscrypt_test.go: -------------------------------------------------------------------------------- 1 | package transport 2 | 3 | func dnscryptTransport() *DNSCrypt { 4 | return &DNSCrypt{ 5 | ServerStamp: "sdns://AQMAAAAAAAAAETk0LjE0MC4xNC4xNDo1NDQzINErR_JS3PLCu_iZEIbq95zkSV2LFsigxDIuUso_OQhzIjIuZG5zY3J5cHQuZGVmYXVsdC5uczEuYWRndWFyZC5jb20", 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /transport/quic_test.go: -------------------------------------------------------------------------------- 1 | package transport 2 | 3 | import "crypto/tls" 4 | 5 | func quicTransport() *QUIC { 6 | return &QUIC{ 7 | Common: Common{Server: "dns.adguard.com:8853"}, 8 | PMTUD: true, 9 | AddLengthPrefix: true, 10 | TLSConfig: &tls.Config{NextProtos: []string{"doq"}}, 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /update-usage-readme.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | cat README.md | sed '/# Usage/q' > README.tmp.md 4 | printf '\n```text\n' >> README.tmp.md 5 | stty rows 1000 cols 1000 6 | go build && ./q -h | sed -z '$ s/\n$//' >> README.tmp.md 7 | printf '```\n\n### Demo\n' >> README.tmp.md 8 | cat README.md | sed '1,/### Demo/d' >> README.tmp.md 9 | mv README.tmp.md README.md 10 | -------------------------------------------------------------------------------- /output/pretty_test.go: -------------------------------------------------------------------------------- 1 | package output 2 | 3 | import ( 4 | "bytes" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | 9 | "github.com/natesales/q/cli" 10 | "github.com/natesales/q/util" 11 | ) 12 | 13 | func TestOutputPrettyPrintColumn(t *testing.T) { 14 | var buf bytes.Buffer 15 | util.UseColor = false 16 | p := Printer{Out: &buf, Opts: &cli.Flags{Format: "column"}} 17 | p.PrintColumn(entries) 18 | assert.Contains(t, buf.String(), `A 86400 192.0.2.2`) 19 | assert.Contains(t, buf.String(), `MX 86400 0 .`) 20 | assert.Contains(t, buf.String(), `NS 86400 a.iana-servers.net.`) 21 | assert.Contains(t, buf.String(), `NS 86400 b.iana-servers.net.`) 22 | assert.Contains(t, buf.String(), `TXT 86400 "v=spf1 -all"`) 23 | } 24 | -------------------------------------------------------------------------------- /output/structured.go: -------------------------------------------------------------------------------- 1 | package output 2 | 3 | import ( 4 | "strings" 5 | 6 | "github.com/charmbracelet/log" 7 | jsoniter "github.com/json-iterator/go" 8 | "github.com/json-iterator/go/extra" 9 | "gopkg.in/yaml.v3" 10 | 11 | "github.com/natesales/q/util" 12 | ) 13 | 14 | func (p Printer) PrintStructured(entries []*Entry) { 15 | var marshaler func(any) ([]byte, error) 16 | if p.Opts.Format == "json" { 17 | extra.SetNamingStrategy(strings.ToLower) 18 | json := jsoniter.ConfigCompatibleWithStandardLibrary 19 | marshaler = json.Marshal 20 | } else { // yaml 21 | marshaler = yaml.Marshal 22 | } 23 | 24 | b, err := marshaler(entries) 25 | if err != nil { 26 | log.Fatalf("error marshaling output: %s", err) 27 | } 28 | 29 | util.MustWriteln(p.Out, string(b)) 30 | } 31 | -------------------------------------------------------------------------------- /output/ede.go: -------------------------------------------------------------------------------- 1 | package output 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/miekg/dns" 7 | ) 8 | 9 | type edeInfo struct { 10 | Code uint16 11 | Text string 12 | } 13 | 14 | // extractEDE returns any Extended DNS Errors (RFC 8914) present in the message. 15 | func extractEDE(m *dns.Msg) []edeInfo { 16 | var out []edeInfo 17 | if m == nil { 18 | return out 19 | } 20 | opt := m.IsEdns0() 21 | if opt == nil { 22 | return out 23 | } 24 | for _, o := range opt.Option { 25 | if o.Option() == dns.EDNS0EDE { 26 | if e, ok := o.(*dns.EDNS0_EDE); ok { 27 | out = append(out, edeInfo{Code: e.InfoCode, Text: e.ExtraText}) 28 | } 29 | } 30 | } 31 | return out 32 | } 33 | 34 | func edeName(code uint16) string { 35 | if s, ok := dns.ExtendedErrorCodeToString[code]; ok { 36 | return s 37 | } 38 | return fmt.Sprintf("Unknown EDE code: %d", code) 39 | } 40 | -------------------------------------------------------------------------------- /util/util_test.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "bytes" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | func TestUtilContainsAny(t *testing.T) { 11 | assert.True(t, ContainsAny("foo", []string{"foo", "bar"})) 12 | assert.True(t, ContainsAny("bar", []string{"foo", "bar"})) 13 | assert.False(t, ContainsAny("baz", []string{"foo", "bar"})) 14 | } 15 | 16 | func TestUtilMustWriteln(t *testing.T) { 17 | var out bytes.Buffer 18 | MustWriteln(&out, "foo") 19 | assert.Equal(t, "foo\n", out.String()) 20 | } 21 | 22 | func TestUtilMustWritef(t *testing.T) { 23 | var out bytes.Buffer 24 | MustWritef(&out, "foo %s", "bar") 25 | assert.Equal(t, "foo bar", out.String()) 26 | } 27 | 28 | func TestUtilColor(t *testing.T) { 29 | assert.Equal(t, "\033[1;31mfoo\033[0m", Color("red", "foo")) 30 | assert.Equal(t, "\033[1;37mfoo\033[0m", Color("white", "foo")) 31 | } 32 | -------------------------------------------------------------------------------- /transport/transport.go: -------------------------------------------------------------------------------- 1 | package transport 2 | 3 | import ( 4 | "github.com/miekg/dns" 5 | ) 6 | 7 | type Transport interface { 8 | Exchange(*dns.Msg) (*dns.Msg, error) 9 | Close() error 10 | } 11 | 12 | type Common struct { 13 | Server string 14 | ReuseConn bool 15 | } 16 | 17 | type Type string 18 | 19 | const ( 20 | TypePlain Type = "plain" 21 | TypeTCP Type = "tcp" 22 | TypeTLS Type = "tls" 23 | TypeHTTP Type = "http" 24 | TypeQUIC Type = "quic" 25 | TypeDNSCrypt Type = "dnscrypt" 26 | ) 27 | 28 | // Types is a list of all supported transports 29 | var Types = []Type{TypePlain, TypeTCP, TypeTLS, TypeHTTP, TypeQUIC, TypeDNSCrypt} 30 | 31 | // Interface guards 32 | var ( 33 | _ Transport = (*Plain)(nil) 34 | _ Transport = (*TLS)(nil) 35 | _ Transport = (*HTTP)(nil) 36 | _ Transport = (*ODoH)(nil) 37 | _ Transport = (*QUIC)(nil) 38 | _ Transport = (*DNSCrypt)(nil) 39 | ) 40 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: goreleaser 2 | 3 | on: 4 | push: 5 | tags: 6 | - "v*" 7 | 8 | jobs: 9 | goreleaser: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: Checkout 13 | uses: actions/checkout@v4 14 | with: 15 | fetch-depth: 0 16 | - name: Set up Go 17 | uses: actions/setup-go@v4 18 | with: 19 | go-version-file: go.mod 20 | - name: Docker Login 21 | uses: docker/login-action@v3 22 | with: 23 | registry: ghcr.io 24 | username: ${{ github.repository_owner }} 25 | password: ${{ secrets.GITHUB_TOKEN }} 26 | - name: Run GoReleaser 27 | uses: goreleaser/goreleaser-action@v6 28 | with: 29 | version: '~> v2' 30 | args: release --clean 31 | env: 32 | GITHUB_TOKEN: ${{ secrets.GH_TOKEN }} 33 | FURY_TOKEN: ${{ secrets.FURY_TOKEN }} 34 | -------------------------------------------------------------------------------- /transport/tls.go: -------------------------------------------------------------------------------- 1 | package transport 2 | 3 | import ( 4 | "crypto/tls" 5 | "fmt" 6 | "net" 7 | 8 | "github.com/miekg/dns" 9 | ) 10 | 11 | // TLS makes a DNS query over TLS 12 | type TLS struct { 13 | Common 14 | TLSConfig *tls.Config 15 | conn *tls.Conn 16 | } 17 | 18 | func (t *TLS) Exchange(msg *dns.Msg) (*dns.Msg, error) { 19 | if t.conn == nil || !t.ReuseConn { 20 | var err error 21 | t.conn, err = tls.DialWithDialer( 22 | &net.Dialer{}, 23 | "tcp", 24 | t.Server, 25 | t.TLSConfig, 26 | ) 27 | if err != nil { 28 | return nil, err 29 | } 30 | if err = t.conn.Handshake(); err != nil { 31 | return nil, err 32 | } 33 | } 34 | 35 | c := dns.Conn{Conn: t.conn} 36 | if err := c.WriteMsg(msg); err != nil { 37 | return nil, fmt.Errorf("write msg to %s: %v", t.Server, err) 38 | } 39 | 40 | return c.ReadMsg() 41 | } 42 | 43 | // Close closes the TLS connection 44 | func (t *TLS) Close() error { 45 | if t.conn != nil { 46 | return t.conn.Close() 47 | } 48 | return nil 49 | } 50 | -------------------------------------------------------------------------------- /output/output_test.go: -------------------------------------------------------------------------------- 1 | package output 2 | 3 | import ( 4 | "strings" 5 | "time" 6 | 7 | "github.com/miekg/dns" 8 | ) 9 | 10 | // replies returns a slice of example DNS answer messages 11 | func replies() []*dns.Msg { 12 | testZone := ` 13 | example.com. 86400 IN A 192.0.2.1 14 | example.com. 86400 IN A 192.0.2.2 15 | example.com. 86400 IN NS b.iana-servers.net. 16 | example.com. 86400 IN NS a.iana-servers.net. 17 | example.com. 86400 IN MX 0 . 18 | example.com. 86400 IN TXT "v=spf1 -all" 19 | ` 20 | 21 | // Convert the zone to DNS messages 22 | var msgs []*dns.Msg 23 | for _, line := range strings.Split(testZone, "\n") { 24 | if line != "" { 25 | rr, err := dns.NewRR(line) 26 | if err != nil { 27 | panic(err) 28 | } 29 | msgs = append(msgs, &dns.Msg{Answer: []dns.RR{rr}}) 30 | } 31 | } 32 | 33 | return msgs 34 | } 35 | 36 | var entries = []*Entry{ 37 | { 38 | Replies: replies(), 39 | Server: "192.0.2.10", 40 | Time: time.Second * 2, 41 | PTRs: nil, 42 | existingRRs: nil, 43 | }, 44 | } 45 | -------------------------------------------------------------------------------- /transport/odoh_test.go: -------------------------------------------------------------------------------- 1 | package transport 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func odohTransport() *ODoH { 10 | return &ODoH{ 11 | Common: Common{Server: "odoh.cloudflare-dns.com"}, 12 | Proxy: "odoh.crypto.sx", 13 | } 14 | } 15 | 16 | func TestODoHBuildURL(t *testing.T) { 17 | // Test with no query params 18 | u := buildURL("https://www.example.com", "") 19 | assert.Equal(t, "https://www.example.com", u.String()) 20 | 21 | // Test with query params 22 | u = buildURL("https://www.example.com", "?foo=bar&baz=qux") 23 | assert.Equal(t, "https://www.example.com/%3Ffoo=bar&baz=qux", u.String()) 24 | 25 | // Test with HTTP 26 | //goland:noinspection HttpUrlsUsage 27 | u = buildURL("http://www.example.com", "") 28 | //goland:noinspection HttpUrlsUsage 29 | assert.Equal(t, "http://www.example.com", u.String()) 30 | } 31 | 32 | func TestTransportODoHInvalidTarget(t *testing.T) { 33 | tp := odohTransport() 34 | tp.Server = "example.com" 35 | _, err := tp.Exchange(validQuery()) 36 | assert.NotNil(t, err) 37 | assert.Contains(t, err.Error(), "Invalid serialized ObliviousDoHConfig") 38 | } 39 | 40 | func TestTransportODoHInvalidProxy(t *testing.T) { 41 | tp := odohTransport() 42 | tp.Proxy = "example.com" 43 | _, err := tp.Exchange(validQuery()) 44 | assert.NotNil(t, err) 45 | assert.Contains(t, err.Error(), "responded with an invalid Content-Type header") 46 | } 47 | -------------------------------------------------------------------------------- /transport/plain_test.go: -------------------------------------------------------------------------------- 1 | package transport 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/miekg/dns" 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | func plainTransport() *Plain { 11 | return &Plain{ 12 | Common: Common{ 13 | Server: "9.9.9.9:53", 14 | }, 15 | PreferTCP: false, 16 | UDPBuffer: 1232, 17 | Timeout: 0, 18 | } 19 | } 20 | 21 | func TestTransportPlainPreferTCP(t *testing.T) { 22 | tp := plainTransport() 23 | tp.PreferTCP = true 24 | reply, err := tp.Exchange(validQuery()) 25 | assert.Nil(t, err) 26 | assert.Greater(t, len(reply.Answer), 0) 27 | } 28 | 29 | func TestTransportPlainInvalidResolver(t *testing.T) { 30 | tp := plainTransport() 31 | tp.Server = "127.127.127.127:53" 32 | _, err := tp.Exchange(validQuery()) 33 | assert.NotNil(t, err) 34 | } 35 | 36 | func TestTransportPlainLargeResponse(t *testing.T) { 37 | msg := dns.Msg{} 38 | msg.RecursionDesired = true 39 | msg.Question = []dns.Question{{ 40 | Name: ".", 41 | Qtype: dns.StringToType["AXFR"], 42 | Qclass: dns.ClassINET, 43 | }} 44 | opt := &dns.OPT{ 45 | Hdr: dns.RR_Header{ 46 | Name: ".", 47 | Class: dns.DefaultMsgSize, 48 | Rrtype: dns.TypeOPT, 49 | }, 50 | } 51 | opt.SetDo() 52 | msg.Extra = append(msg.Extra, opt) 53 | 54 | tp := plainTransport() 55 | tp.Server = "f.root-servers.net:53" 56 | reply, err := tp.Exchange(&msg) 57 | assert.Nil(t, err) 58 | assert.Greater(t, len(reply.Answer), 0) 59 | } 60 | -------------------------------------------------------------------------------- /transport/plain.go: -------------------------------------------------------------------------------- 1 | package transport 2 | 3 | import ( 4 | "time" 5 | 6 | "github.com/charmbracelet/log" 7 | "github.com/miekg/dns" 8 | ) 9 | 10 | // Plain makes a DNS query over TCP or UDP (with TCP fallback) 11 | type Plain struct { 12 | Common 13 | PreferTCP bool 14 | EDNS bool 15 | UDPBuffer uint16 16 | Timeout time.Duration 17 | } 18 | 19 | func (p *Plain) Exchange(m *dns.Msg) (*dns.Msg, error) { 20 | tcpClient := dns.Client{Net: "tcp", Timeout: p.Timeout} 21 | if p.PreferTCP { 22 | reply, _, tcpErr := tcpClient.Exchange(m, p.Server) 23 | return reply, tcpErr 24 | } 25 | 26 | // Ensure an EDNS0 OPT record is present (if enabled) and advertises our UDP buffer size 27 | // so large UDP responses are either sized appropriately or marked truncated, allowing TCP retry. 28 | if p.EDNS { 29 | if opt := m.IsEdns0(); opt == nil { 30 | m.Extra = append(m.Extra, &dns.OPT{ 31 | Hdr: dns.RR_Header{ 32 | Name: ".", 33 | Class: p.UDPBuffer, // UDP payload size 34 | Rrtype: dns.TypeOPT, 35 | }, 36 | }) 37 | } else if opt.UDPSize() < p.UDPBuffer { 38 | opt.SetUDPSize(p.UDPBuffer) 39 | } 40 | } 41 | 42 | client := dns.Client{UDPSize: p.UDPBuffer, Timeout: p.Timeout} 43 | reply, _, err := client.Exchange(m, p.Server) 44 | 45 | if reply != nil && reply.Truncated { 46 | log.Debugf("Truncated reply from %s for %s over UDP, retrying over TCP", p.Server, m.Question[0].String()) 47 | reply, _, err = tcpClient.Exchange(m, p.Server) 48 | } 49 | 50 | return reply, err 51 | } 52 | 53 | // Close is a no-op for the plain transport 54 | func (p *Plain) Close() error { 55 | return nil 56 | } 57 | -------------------------------------------------------------------------------- /transport/dnscrypt.go: -------------------------------------------------------------------------------- 1 | package transport 2 | 3 | import ( 4 | "github.com/ameshkov/dnscrypt/v2" 5 | "github.com/charmbracelet/log" 6 | "github.com/jedisct1/go-dnsstamps" 7 | "github.com/miekg/dns" 8 | ) 9 | 10 | type DNSCrypt struct { 11 | Common 12 | ServerStamp string 13 | TCP bool // default false (UDP) 14 | UDPSize int 15 | 16 | // ServerStamp takes precedence if set 17 | PublicKey string 18 | ProviderName string 19 | 20 | resolver *dnscrypt.ResolverInfo 21 | client *dnscrypt.Client 22 | } 23 | 24 | func (d *DNSCrypt) setup() { 25 | if d.client == nil || d.resolver == nil || !d.ReuseConn { 26 | d.client = &dnscrypt.Client{ 27 | UDPSize: d.UDPSize, 28 | } 29 | 30 | if d.ServerStamp == "" { 31 | stamp, err := dnsstamps.NewDNSCryptServerStampFromLegacy(d.Server, d.PublicKey, d.ProviderName, 0) 32 | if err != nil { 33 | log.Fatalf("failed to create stamp from provider information: %s", err) 34 | } 35 | d.ServerStamp = stamp.String() 36 | log.Debugf("Created DNS stamp from manual DNSCrypt configuration: %s", d.ServerStamp) 37 | } 38 | 39 | // Resolve server DNS stamp 40 | ro, err := d.client.Dial(d.ServerStamp) 41 | if err != nil { 42 | log.Fatalf("failed to dial DNSCrypt server: %s", err) 43 | } 44 | d.resolver = ro 45 | } 46 | if d.TCP { 47 | d.client.Net = "tcp" 48 | } else { 49 | d.client.Net = "udp" 50 | } 51 | } 52 | 53 | func (d *DNSCrypt) Exchange(msg *dns.Msg) (*dns.Msg, error) { 54 | d.setup() 55 | return d.client.Exchange(msg, d.resolver) 56 | } 57 | 58 | func (d *DNSCrypt) Close() error { 59 | d.resolver = nil 60 | d.client = nil 61 | return nil 62 | } 63 | -------------------------------------------------------------------------------- /util/util.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | "strings" 7 | 8 | "github.com/charmbracelet/log" 9 | ) 10 | 11 | var UseColor = true 12 | 13 | const ( 14 | ColorBlack = "black" 15 | ColorRed = "red" 16 | ColorGreen = "green" 17 | ColorYellow = "yellow" 18 | ColorPurple = "purple" 19 | ColorMagenta = "magenta" 20 | ColorTeal = "teal" 21 | ColorWhite = "white" 22 | ) 23 | 24 | // ANSI colors 25 | var colors = map[string]string{ 26 | ColorBlack: "\033[1;30m%s\033[0m", 27 | ColorRed: "\033[1;31m%s\033[0m", 28 | ColorGreen: "\033[1;32m%s\033[0m", 29 | ColorYellow: "\033[1;33m%s\033[0m", 30 | ColorPurple: "\033[1;34m%s\033[0m", 31 | ColorMagenta: "\033[1;35m%s\033[0m", 32 | ColorTeal: "\033[1;36m%s\033[0m", 33 | ColorWhite: "\033[1;37m%s\033[0m", 34 | } 35 | 36 | // Color returns a color formatted string 37 | func Color(color string, args ...interface{}) string { 38 | if _, ok := colors[color]; !ok { 39 | panic("invalid color: " + color) 40 | } 41 | 42 | if UseColor { 43 | return fmt.Sprintf(colors[color], fmt.Sprint(args...)) 44 | } else { 45 | return fmt.Sprint(args...) 46 | } 47 | } 48 | 49 | func ContainsAny(s string, subStrings []string) bool { 50 | for _, sub := range subStrings { 51 | if strings.Contains(s, sub) { 52 | return true 53 | } 54 | } 55 | return false 56 | } 57 | 58 | func MustWriteln(out io.Writer, s string) { 59 | if _, err := out.Write([]byte(s + "\n")); err != nil { 60 | log.Fatal(err) 61 | } 62 | } 63 | 64 | func MustWritef(out io.Writer, format string, a ...interface{}) { 65 | if _, err := out.Write([]byte(fmt.Sprintf(format, a...))); err != nil { 66 | log.Fatal(err) 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Run tests 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | paths: 8 | - "*.go" 9 | - ".github/workflows/*" 10 | - "README.md" 11 | 12 | pull_request: 13 | paths: 14 | - "*.go" 15 | - ".github/workflows/*" 16 | - "README.md" 17 | 18 | jobs: 19 | build: 20 | name: Build 21 | runs-on: ubuntu-latest 22 | steps: 23 | - uses: actions/checkout@v4 24 | - uses: actions/setup-go@v4 25 | with: 26 | go-version-file: go.mod 27 | - run: go build -v ./... 28 | - run: go install github.com/jpoles1/gopherbadger@latest 29 | - run: go install github.com/gotesttools/gotestfmt/v2/cmd/gotestfmt@latest 30 | 31 | # Run tests with nice formatting. Save the original log in /tmp/gotest.log 32 | - name: Run tests 33 | run: | 34 | set -euo pipefail 35 | go test -p 1 -json -v -covermode atomic -coverprofile=cover.out ./... 2>&1 | tee /tmp/gotest.log | gotestfmt 36 | 37 | - name: Upload original test log 38 | uses: actions/upload-artifact@v4 39 | if: always() 40 | with: 41 | name: test-log 42 | path: /tmp/gotest.log 43 | if-no-files-found: error 44 | 45 | - name: Generate coverage badge 46 | run: gopherbadger -style=for-the-badge -covercmd "go tool cover -func=cover.out" 47 | 48 | - name: Commit coverage badge 49 | uses: EndBug/add-and-commit@v7 50 | with: 51 | message: "ci: update coverage" 52 | add: "coverage_badge.png" 53 | author_name: "github-actions[bot]" 54 | author_email: "github-actions[bot]@users.noreply.github.com" 55 | 56 | - run: ./update-usage-readme.sh 57 | 58 | - name: Commit README update 59 | uses: EndBug/add-and-commit@v7 60 | with: 61 | message: "ci: update binary usage in README" 62 | add: "README.md" 63 | author_name: "github-actions[bot]" 64 | author_email: "github-actions[bot]@users.noreply.github.com" 65 | -------------------------------------------------------------------------------- /output/output.go: -------------------------------------------------------------------------------- 1 | package output 2 | 3 | import ( 4 | "io" 5 | "time" 6 | 7 | "github.com/natesales/q/transport" 8 | 9 | "github.com/charmbracelet/log" 10 | "github.com/miekg/dns" 11 | 12 | "github.com/natesales/q/cli" 13 | ) 14 | 15 | var ( 16 | FormatPretty = "pretty" 17 | FormatColumn = "column" 18 | FormatJSON = "json" 19 | FormatYAML = "yaml" 20 | FormatRAW = "raw" 21 | ) 22 | 23 | // Printer stores global options across multiple entries 24 | type Printer struct { 25 | Out io.Writer 26 | Opts *cli.Flags 27 | 28 | // Longest string lengths for column formatting 29 | longestTTL int 30 | longestRRType int 31 | } 32 | 33 | // Entry stores the replies from a server 34 | type Entry struct { 35 | Queries []dns.Msg 36 | Replies []*dns.Msg 37 | Server string 38 | 39 | // Time is the total time it took to query this server 40 | Time time.Duration 41 | 42 | PTRs map[string]string `json:"-"` // IP -> PTR value 43 | existingRRs map[string]bool 44 | } 45 | 46 | // LoadPTRs populates an entry's PTRs map with PTR values for all A/AAAA records 47 | func (e *Entry) LoadPTRs(txp *transport.Transport) { 48 | // Initialize PTR cache if it doesn't exist 49 | if e.PTRs == nil { 50 | e.PTRs = make(map[string]string) 51 | } 52 | 53 | for _, reply := range e.Replies { 54 | for _, rr := range reply.Answer { 55 | var ip string 56 | 57 | switch rr.Header().Rrtype { 58 | case dns.TypeA: 59 | ip = rr.(*dns.A).A.String() 60 | case dns.TypeAAAA: 61 | ip = rr.(*dns.AAAA).AAAA.String() 62 | default: 63 | continue 64 | } 65 | 66 | // Create PTR query 67 | qname, err := dns.ReverseAddr(ip) 68 | if err != nil { 69 | log.Fatalf("error reversing PTR record: %s", err) 70 | } 71 | msg := dns.Msg{} 72 | msg.SetQuestion(qname, dns.TypePTR) 73 | 74 | // Resolve qname and cache result 75 | resp, err := (*txp).Exchange(&msg) 76 | if err != nil { 77 | log.Warnf("error resolving PTR record: %s", err) 78 | continue 79 | } 80 | 81 | // Store in cache 82 | if resp != nil && len(resp.Answer) > 0 { 83 | e.PTRs[ip] = resp.Answer[0].(*dns.PTR).Ptr 84 | } 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /output/raw.go: -------------------------------------------------------------------------------- 1 | package output 2 | 3 | import ( 4 | "strconv" 5 | "time" 6 | 7 | "github.com/miekg/dns" 8 | 9 | "github.com/natesales/q/util" 10 | ) 11 | 12 | // rrSection generates a printable section from a given RR slice 13 | func rrSection(s, label string, rrs []dns.RR) string { 14 | if len(rrs) > 0 { 15 | s += "\n;; " + label + " SECTION:\n" 16 | for _, r := range rrs { 17 | if r != nil { 18 | s += r.String() + "\n" 19 | } 20 | } 21 | } 22 | 23 | return s 24 | } 25 | 26 | // PrintRaw a slice of entries in raw (dig-style) format 27 | func (p Printer) PrintRaw(entries []*Entry) { 28 | for _, entry := range entries { 29 | for i, reply := range entry.Replies { 30 | s := reply.MsgHdr.String() + " " 31 | s += "QUERY: " + strconv.Itoa(len(reply.Question)) + ", " 32 | s += "ANSWER: " + strconv.Itoa(len(reply.Answer)) + ", " 33 | s += "AUTHORITY: " + strconv.Itoa(len(reply.Ns)) + ", " 34 | s += "ADDITIONAL: " + strconv.Itoa(len(reply.Extra)) + "\n" 35 | opt := reply.IsEdns0() 36 | if opt != nil { 37 | // OPT PSEUDOSECTION 38 | s += opt.String() + "\n" 39 | } 40 | if p.Opts.ShowQuestion && len(reply.Question) > 0 { 41 | s += "\n;; QUESTION SECTION:\n" 42 | for _, r := range reply.Question { 43 | s += r.String() + "\n" 44 | } 45 | } 46 | if p.Opts.ShowAnswer { 47 | s += rrSection(s, "ANSWER", reply.Answer) 48 | } 49 | if p.Opts.ShowAuthority { 50 | s += rrSection(s, "AUTHORITY", reply.Ns) 51 | } 52 | if p.Opts.ShowAdditional && (opt == nil || len(reply.Extra) > 1) { 53 | s += rrSection(s, "ADDITIONAL", reply.Extra) 54 | } 55 | util.MustWriteln(p.Out, s) 56 | 57 | if p.Opts.ShowStats { 58 | util.MustWritef(p.Out, ";; Received %d B\n", reply.Len()) 59 | util.MustWritef(p.Out, ";; Time %s\n", time.Now().Format("15:04:05 01-02-2006 MST")) 60 | util.MustWritef(p.Out, ";; From %s in %s\n", entry.Server, entry.Time.Round(100*time.Microsecond)) 61 | } 62 | 63 | // Print separator if there is more than one query 64 | if len(entry.Replies) > 0 && i != len(entry.Replies)-1 { 65 | util.MustWritef(p.Out, "\n--\n\n") 66 | } 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/natesales/q 2 | 3 | go 1.25.0 4 | 5 | require ( 6 | github.com/ameshkov/dnscrypt/v2 v2.4.0 7 | github.com/charmbracelet/log v0.4.2 8 | github.com/jedisct1/go-dnsstamps v0.0.0-20240423203910-07a0735c7774 9 | github.com/jessevdk/go-flags v1.6.1 10 | github.com/json-iterator/go v1.1.12 11 | github.com/miekg/dns v1.1.68 12 | github.com/natesales/bgptools-go v0.0.0-20230212051756-2b519d61269c 13 | github.com/quic-go/quic-go v0.54.0 14 | github.com/sthorne/odoh-go v1.0.4 15 | github.com/stretchr/testify v1.10.0 16 | golang.org/x/net v0.44.0 17 | gopkg.in/yaml.v3 v3.0.1 18 | ) 19 | 20 | require ( 21 | github.com/AdguardTeam/golibs v0.34.1 // indirect 22 | github.com/ameshkov/dnsstamps v1.0.3 // indirect 23 | github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect 24 | github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect 25 | github.com/charmbracelet/lipgloss v1.1.0 // indirect 26 | github.com/charmbracelet/x/ansi v0.8.0 // indirect 27 | github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd // indirect 28 | github.com/charmbracelet/x/term v0.2.1 // indirect 29 | github.com/cisco/go-hpke v0.0.0-20230407100446-246075f83609 // indirect 30 | github.com/cisco/go-tls-syntax v0.0.0-20200617162716-46b0cfb76b9b // indirect 31 | github.com/cloudflare/circl v1.6.1 // indirect 32 | github.com/davecgh/go-spew v1.1.1 // indirect 33 | github.com/go-logfmt/logfmt v0.6.0 // indirect 34 | github.com/kr/pretty v0.3.1 // indirect 35 | github.com/lucasb-eyer/go-colorful v1.2.0 // indirect 36 | github.com/mattn/go-isatty v0.0.20 // indirect 37 | github.com/mattn/go-runewidth v0.0.16 // indirect 38 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect 39 | github.com/modern-go/reflect2 v1.0.2 // indirect 40 | github.com/muesli/termenv v0.16.0 // indirect 41 | github.com/pmezard/go-difflib v1.0.0 // indirect 42 | github.com/quic-go/qpack v0.5.1 // indirect 43 | github.com/rivo/uniseg v0.4.7 // indirect 44 | github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect 45 | go.uber.org/mock v0.6.0 // indirect 46 | golang.org/x/crypto v0.42.0 // indirect 47 | golang.org/x/exp v0.0.0-20250911091902-df9299821621 // indirect 48 | golang.org/x/mod v0.28.0 // indirect 49 | golang.org/x/sync v0.17.0 // indirect 50 | golang.org/x/sys v0.36.0 // indirect 51 | golang.org/x/text v0.29.0 // indirect 52 | golang.org/x/tools v0.37.0 // indirect 53 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect 54 | ) 55 | -------------------------------------------------------------------------------- /.goreleaser.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | 3 | before: 4 | hooks: 5 | - go mod download 6 | 7 | builds: 8 | - env: 9 | - CGO_ENABLED=0 10 | goos: 11 | - linux 12 | - darwin 13 | - freebsd 14 | - windows 15 | goarch: 16 | - amd64 17 | - arm64 18 | 19 | archives: 20 | - format_overrides: 21 | - goos: windows 22 | formats: ["zip"] 23 | 24 | changelog: 25 | sort: asc 26 | filters: 27 | exclude: 28 | - "^docs:" 29 | - "^test:" 30 | 31 | nfpms: 32 | - id: nfpm-default 33 | package_name: q 34 | file_name_template: "{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}" 35 | vendor: Nate Sales 36 | homepage: https://natesales.net/ 37 | maintainer: Nate Sales 38 | description: A tiny CLI DNS client library with support for UDP, TCP, DoT, DoH, and DoQ. 39 | license: GNU GPL-3.0 40 | section: utils 41 | priority: extra 42 | formats: 43 | - deb 44 | - rpm 45 | 46 | publishers: 47 | - name: fury.io 48 | ids: 49 | - nfpm-default 50 | dir: "{{ dir .ArtifactPath }}" 51 | cmd: curl -s -F package=@{{ .ArtifactName }} https://{{ .Env.FURY_TOKEN }}@push.fury.io/natesales/ 52 | 53 | brews: 54 | - name: q 55 | homepage: https://github.com/natesales/repo 56 | repository: 57 | owner: natesales 58 | name: repo 59 | 60 | dockers: 61 | - image_templates: 62 | - "ghcr.io/natesales/q:{{ .Version }}-amd64" 63 | use: buildx 64 | build_flag_templates: 65 | - --platform=linux/amd64 66 | - --label=org.opencontainers.image.version={{ .Version }} 67 | - --label=org.opencontainers.image.revision={{ .FullCommit }} 68 | - --label=org.opencontainers.image.licenses=GPL-3.0-only 69 | - image_templates: 70 | - "ghcr.io/natesales/q:{{ .Version }}-arm64" 71 | use: buildx 72 | build_flag_templates: 73 | - --platform=linux/arm64 74 | - --label=org.opencontainers.image.version={{ .Version }} 75 | - --label=org.opencontainers.image.revision={{ .FullCommit }} 76 | - --label=org.opencontainers.image.licenses=GPL-3.0-only 77 | goarch: arm64 78 | 79 | docker_manifests: 80 | - name_template: "ghcr.io/natesales/q:{{ .Version }}" 81 | image_templates: 82 | - "ghcr.io/natesales/q:{{ .Version }}-amd64" 83 | - "ghcr.io/natesales/q:{{ .Version }}-arm64" 84 | - name_template: "ghcr.io/natesales/q:latest" 85 | image_templates: 86 | - "ghcr.io/natesales/q:{{ .Version }}-amd64" 87 | - "ghcr.io/natesales/q:{{ .Version }}-arm64" 88 | -------------------------------------------------------------------------------- /xfr.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | "os" 7 | "path" 8 | "strings" 9 | "time" 10 | 11 | "github.com/charmbracelet/log" 12 | "github.com/miekg/dns" 13 | 14 | "github.com/natesales/q/util" 15 | ) 16 | 17 | var ( 18 | queried map[string]bool 19 | all []dns.RR 20 | ) 21 | 22 | func axfr(label, server string) []dns.RR { 23 | t := new(dns.Transfer) 24 | m := new(dns.Msg) 25 | m.SetAxfr(dns.Fqdn(label)) 26 | ch, err := t.In(m, server) 27 | if err != nil { 28 | log.Fatalf("Failed to transfer zone: %s", err) 29 | } 30 | 31 | var rrs []dns.RR 32 | for env := range ch { 33 | if env.Error != nil { 34 | log.Warnf("AXFR section error (%s): %s", label, env.Error) 35 | continue 36 | } 37 | rrs = append(rrs, env.RR...) 38 | } 39 | 40 | return rrs 41 | } 42 | 43 | // RecAXFR performs an AXFR on the given label and all of its children and writes the zone file to disk 44 | func RecAXFR(label, server string, out io.Writer) []dns.RR { 45 | util.MustWritef(out, "Attempting recursive AXFR for %s\n", label) 46 | 47 | // Reset state 48 | queried = make(map[string]bool) 49 | all = make([]dns.RR, 0) 50 | 51 | dir := fmt.Sprintf("%s_%s_recaxfr", 52 | strings.TrimPrefix(label, "."), 53 | strings.ReplaceAll(time.Now().Format(time.UnixDate), " ", "-"), 54 | ) 55 | 56 | // Create recursive AXFR directory if it doesn't exist 57 | if _, err := os.Stat(dir); os.IsNotExist(err) { 58 | err := os.MkdirAll(dir, 0755) 59 | if err != nil { 60 | log.Fatalf("creating recaxfr directory: %s", err) 61 | } 62 | } 63 | 64 | addToTree(label, dir, server, out) 65 | util.MustWritef(out, "AXFR complete, %d records saved to %s\n", len(all), dir) 66 | 67 | return all 68 | } 69 | 70 | func addToTree(label, dir, server string, out io.Writer) { 71 | label = dns.Fqdn(label) 72 | if queried[label] { 73 | return 74 | } 75 | util.MustWritef(out, "AXFR %s\n", label) 76 | queried[label] = true 77 | rrs := axfr(label, server) 78 | 79 | // Write RRs to zone file 80 | if len(rrs) > 0 { 81 | var zoneFile string 82 | for _, rr := range rrs { 83 | zoneFile += rr.String() + "\n" 84 | } 85 | if err := os.WriteFile( 86 | path.Join(dir, strings.TrimSuffix(label, ".")+".zone"), 87 | []byte(zoneFile), 88 | 0644, 89 | ); err != nil { 90 | log.Fatalf("Failed to write zone file: %s", err) 91 | } 92 | } 93 | 94 | for _, rr := range rrs { 95 | all = append(all, rr) 96 | if _, ok := rr.(*dns.NS); ok { 97 | addToTree(rr.Header().Name, dir, server, out) 98 | } 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /transport/http_test.go: -------------------------------------------------------------------------------- 1 | package transport 2 | 3 | import ( 4 | "net/http" 5 | "testing" 6 | "time" 7 | 8 | "github.com/miekg/dns" 9 | "github.com/stretchr/testify/assert" 10 | ) 11 | 12 | func httpTransport() *HTTP { 13 | return &HTTP{ 14 | Common: Common{ 15 | Server: "https://cloudflare-dns.com/dns-query", 16 | }, 17 | Method: http.MethodGet, 18 | } 19 | } 20 | 21 | func TestTransportHTTPPOST(t *testing.T) { 22 | tp := httpTransport() 23 | tp.Method = http.MethodPost 24 | reply, err := tp.Exchange(validQuery()) 25 | assert.Nil(t, err) 26 | assert.Greater(t, len(reply.Answer), 0) 27 | } 28 | 29 | func TestTransportHTTP3(t *testing.T) { 30 | tp := httpTransport() 31 | tp.HTTP3 = true 32 | reply, err := tp.Exchange(validQuery()) 33 | assert.Nil(t, err) 34 | assert.Greater(t, len(reply.Answer), 0) 35 | } 36 | 37 | func TestTransportHTTPInvalidResolver(t *testing.T) { 38 | tp := httpTransport() 39 | tp.Server = "https://example.com" 40 | _, err := tp.Exchange(validQuery()) 41 | assert.NotNil(t, err) 42 | assert.Contains(t, err.Error(), "unpacking DNS response") 43 | } 44 | 45 | func TestTransportHTTPServerError(t *testing.T) { 46 | listen := ":5380" 47 | go func() { 48 | if err := http.ListenAndServe(listen, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 49 | http.Error(w, "Server Error", http.StatusInternalServerError) 50 | })); err != nil { 51 | t.Errorf("error starting HTTP server: %s", err) 52 | } 53 | }() 54 | time.Sleep(50 * time.Millisecond) // Wait for server to start 55 | 56 | tp := httpTransport() 57 | tp.Server = "http://localhost" + listen 58 | _, err := tp.Exchange(validQuery()) 59 | assert.NotNil(t, err) 60 | assert.Contains(t, err.Error(), "got status code 500") 61 | } 62 | 63 | func TestTransportHTTPIDMismatch(t *testing.T) { 64 | listen := ":5381" 65 | go func() { 66 | if err := http.ListenAndServe(listen, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 67 | msg := dns.Msg{} 68 | msg.Id = 1 69 | buf, err := msg.Pack() 70 | if err != nil { 71 | t.Errorf("error packing DNS message: %s", err) 72 | return 73 | } 74 | if _, err := w.Write(buf); err != nil { 75 | t.Errorf("error writing DNS message: %s", err) 76 | } 77 | })); err != nil { 78 | t.Errorf("error starting HTTP server: %s", err) 79 | } 80 | }() 81 | time.Sleep(50 * time.Millisecond) // Wait for server to start 82 | 83 | tp := httpTransport() 84 | tp.Server = "http://localhost" + listen 85 | query := validQuery() 86 | reply, err := tp.Exchange(query) 87 | assert.Nil(t, err) 88 | assert.Equal(t, uint16(1), reply.Id) 89 | assert.NotEqual(t, 1, query.Id) 90 | } 91 | -------------------------------------------------------------------------------- /transport/transport_test.go: -------------------------------------------------------------------------------- 1 | package transport 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/miekg/dns" 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | // validQuery creates a simple, valid query for testing 11 | func validQuery() *dns.Msg { 12 | msg := dns.Msg{} 13 | msg.RecursionDesired = true 14 | msg.Id = dns.Id() 15 | msg.Question = []dns.Question{{ 16 | Name: "example.com.", 17 | Qtype: dns.StringToType["A"], 18 | Qclass: dns.ClassINET, 19 | }} 20 | return &msg 21 | } 22 | 23 | // invalidQuery creates a simple, invalid query for testing 24 | func invalidQuery() *dns.Msg { 25 | msg := &dns.Msg{} 26 | msg.RecursionDesired = true 27 | msg.Id = dns.Id() 28 | msg.Question = []dns.Question{{ 29 | Name: "invalid label!", 30 | }} 31 | return msg 32 | } 33 | 34 | func transportHarness(t *testing.T, transport Transport) { 35 | defer transport.Close() 36 | for _, tc := range []struct { 37 | // Name is the name of the test 38 | Name string 39 | 40 | // ShouldError is true if the test should error 41 | ShouldError bool 42 | 43 | // Query is the message to send 44 | Query *dns.Msg 45 | }{ 46 | {Name: "ValidQuery", ShouldError: false, Query: validQuery()}, 47 | {Name: "InvalidQuery", ShouldError: true, Query: invalidQuery()}, 48 | } { 49 | t.Run("TransportHarness"+tc.Name, func(t *testing.T) { 50 | reply, err := transport.Exchange(tc.Query) 51 | if tc.ShouldError { 52 | assert.NotNil(t, err) 53 | } else { 54 | assert.Nil(t, err) 55 | assert.Equal(t, tc.Query.Id, reply.Id) 56 | for _, q := range tc.Query.Question { 57 | for _, a := range reply.Answer { 58 | if q.Name == a.Header().Name { 59 | assert.Equal(t, q.Qtype, a.Header().Rrtype) 60 | assert.Equal(t, q.Qclass, a.Header().Class) 61 | } 62 | } 63 | } 64 | } 65 | }) 66 | } 67 | } 68 | 69 | func TestTransportPlain(t *testing.T) { 70 | transportHarness(t, plainTransport()) 71 | } 72 | 73 | func TestTransportTLS(t *testing.T) { 74 | transportHarness(t, tlsTransport()) 75 | } 76 | 77 | func TestTransportQUIC(t *testing.T) { 78 | transportHarness(t, quicTransport()) 79 | } 80 | 81 | func TestTransportHTTP(t *testing.T) { 82 | transportHarness(t, httpTransport()) 83 | } 84 | 85 | func TestTransportDNSCrypt(t *testing.T) { 86 | transportHarness(t, dnscryptTransport()) 87 | } 88 | 89 | func TestTransportReuseTLS(t *testing.T) { 90 | transport := tlsTransport() 91 | transport.ReuseConn = true 92 | transportHarness(t, transport) 93 | } 94 | 95 | func TestTransportReuseQUIC(t *testing.T) { 96 | transport := quicTransport() 97 | transport.ReuseConn = true 98 | transportHarness(t, transport) 99 | } 100 | 101 | func TestTransportReuseHTTP(t *testing.T) { 102 | transport := httpTransport() 103 | transport.ReuseConn = true 104 | transportHarness(t, transport) 105 | } 106 | 107 | func TestTransportReuseDNSCrypt(t *testing.T) { 108 | transport := dnscryptTransport() 109 | transport.ReuseConn = true 110 | transportHarness(t, transport) 111 | } 112 | 113 | // TODO: Enable test 114 | // func TestTransportODoH(t *testing.T) { 115 | // transportHarness(t, odohTransport()) 116 | // } 117 | // func TestTransportReuseODoH(t *testing.T) { 118 | // transport := odohTransport() 119 | // transport.ReuseConn = true 120 | // reuseTransportHarness(t, transport) 121 | // } 122 | -------------------------------------------------------------------------------- /transport/http.go: -------------------------------------------------------------------------------- 1 | package transport 2 | 3 | import ( 4 | "bytes" 5 | "crypto/tls" 6 | "encoding/base64" 7 | "fmt" 8 | "io" 9 | "net/http" 10 | 11 | "github.com/charmbracelet/log" 12 | "github.com/miekg/dns" 13 | "github.com/quic-go/quic-go" 14 | "github.com/quic-go/quic-go/http3" 15 | "golang.org/x/net/http2" 16 | ) 17 | 18 | // HTTP makes a DNS query over HTTP(s) 19 | type HTTP struct { 20 | Common 21 | TLSConfig *tls.Config 22 | UserAgent string 23 | Method string 24 | HTTP2, HTTP3 bool 25 | NoPMTUd bool 26 | Headers map[string][]string 27 | 28 | conn *http.Client 29 | } 30 | 31 | func (h *HTTP) Exchange(m *dns.Msg) (*dns.Msg, error) { 32 | if h.conn == nil || !h.ReuseConn { 33 | transport := http.DefaultTransport.(*http.Transport) 34 | transport.TLSClientConfig = h.TLSConfig 35 | h.conn = &http.Client{ 36 | Transport: transport, 37 | } 38 | if h.HTTP2 { 39 | log.Debug("Using HTTP/2") 40 | h.conn.Transport = &http2.Transport{ 41 | TLSClientConfig: h.TLSConfig, 42 | AllowHTTP: true, 43 | } 44 | } else if h.HTTP3 { 45 | log.Debug("Using HTTP/3") 46 | h.conn.Transport = &http3.Transport{ 47 | TLSClientConfig: h.TLSConfig, 48 | QUICConfig: &quic.Config{ 49 | DisablePathMTUDiscovery: h.NoPMTUd, 50 | }, 51 | } 52 | } 53 | } 54 | 55 | buf, err := m.Pack() 56 | if err != nil { 57 | return nil, fmt.Errorf("packing message: %w", err) 58 | } 59 | 60 | var queryURL string 61 | var req *http.Request 62 | switch h.Method { 63 | case http.MethodGet: 64 | queryURL = h.Server + "?dns=" + base64.RawURLEncoding.EncodeToString(buf) 65 | req, err = http.NewRequest(http.MethodGet, queryURL, nil) 66 | if err != nil { 67 | return nil, fmt.Errorf("creating http request to %s: %w", queryURL, err) 68 | } 69 | case http.MethodPost: 70 | queryURL = h.Server 71 | req, err = http.NewRequest(http.MethodPost, queryURL, bytes.NewReader(buf)) 72 | if err != nil { 73 | return nil, fmt.Errorf("creating http request to %s: %w", queryURL, err) 74 | } 75 | req.Header.Set("Content-Type", "application/dns-message") 76 | default: 77 | return nil, fmt.Errorf("unsupported HTTP method: %s", h.Method) 78 | } 79 | 80 | req.Header.Set("Accept", "application/dns-message") 81 | if h.UserAgent != "" { 82 | log.Debugf("Setting User-Agent to %s", h.UserAgent) 83 | req.Header.Set("User-Agent", h.UserAgent) 84 | } 85 | 86 | // Set custom headers if provided 87 | if h.Headers != nil { 88 | for name, values := range h.Headers { 89 | for _, value := range values { 90 | log.Debugf("Setting custom header %s: %s", name, value) 91 | req.Header.Add(name, value) 92 | } 93 | } 94 | } 95 | 96 | log.Debugf("[http] sending %s request to %s", h.Method, queryURL) 97 | resp, err := h.conn.Do(req) 98 | if resp != nil && resp.Body != nil { 99 | defer resp.Body.Close() 100 | } 101 | if err != nil { 102 | return nil, fmt.Errorf("requesting %s: %w", queryURL, err) 103 | } 104 | 105 | body, err := io.ReadAll(resp.Body) 106 | if err != nil { 107 | return nil, fmt.Errorf("reading %s: %w", queryURL, err) 108 | } 109 | 110 | if resp.StatusCode != http.StatusOK { 111 | return nil, fmt.Errorf("got status code %d from %s", resp.StatusCode, queryURL) 112 | } 113 | 114 | var response dns.Msg 115 | if err := response.Unpack(body); err != nil { 116 | return nil, fmt.Errorf("unpacking DNS response from %s: %w", queryURL, err) 117 | } 118 | 119 | return &response, nil 120 | } 121 | 122 | func (h *HTTP) Close() error { 123 | if h.conn == nil { 124 | return nil 125 | } 126 | // Close idle connections for standard transports 127 | h.conn.CloseIdleConnections() 128 | return nil 129 | } 130 | -------------------------------------------------------------------------------- /util/tls/tls.go: -------------------------------------------------------------------------------- 1 | package tls 2 | 3 | import ( 4 | "crypto/tls" 5 | 6 | "github.com/charmbracelet/log" 7 | ) 8 | 9 | // cipherSuiteToInt converts a cipher suite name to its integer identifier 10 | var cipherSuiteToInt = map[string]uint16{ 11 | // TLS 1.0 - 1.2 12 | "TLS_RSA_WITH_RC4_128_SHA": tls.TLS_RSA_WITH_RC4_128_SHA, 13 | "TLS_RSA_WITH_3DES_EDE_CBC_SHA": tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA, 14 | "TLS_RSA_WITH_AES_128_CBC_SHA": tls.TLS_RSA_WITH_AES_128_CBC_SHA, 15 | "TLS_RSA_WITH_AES_256_CBC_SHA": tls.TLS_RSA_WITH_AES_256_CBC_SHA, 16 | "TLS_RSA_WITH_AES_128_CBC_SHA256": tls.TLS_RSA_WITH_AES_128_CBC_SHA256, 17 | "TLS_RSA_WITH_AES_128_GCM_SHA256": tls.TLS_RSA_WITH_AES_128_GCM_SHA256, 18 | "TLS_RSA_WITH_AES_256_GCM_SHA384": tls.TLS_RSA_WITH_AES_256_GCM_SHA384, 19 | "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA": tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, 20 | "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA": tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, 21 | "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA": tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, 22 | "TLS_ECDHE_RSA_WITH_RC4_128_SHA": tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA, 23 | "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA": tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, 24 | "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA": tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, 25 | "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA": tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, 26 | "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256": tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, 27 | "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256": tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, 28 | "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256": tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 29 | "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256": tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 30 | "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384": tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, 31 | "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384": tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, 32 | "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256": tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, 33 | "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256": tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, 34 | 35 | // TLS 1.3 36 | "TLS_AES_128_GCM_SHA256": tls.TLS_AES_128_GCM_SHA256, 37 | "TLS_AES_256_GCM_SHA384": tls.TLS_AES_256_GCM_SHA384, 38 | "TLS_CHACHA20_POLY1305_SHA256": tls.TLS_CHACHA20_POLY1305_SHA256, 39 | } 40 | 41 | var curveToInt = map[string]tls.CurveID{ 42 | "P256": tls.CurveP256, 43 | "P384": tls.CurveP384, 44 | "P521": tls.CurveP521, 45 | "X25519": tls.X25519, 46 | } 47 | 48 | // ParseCipherSuites converts a slice of cipher suite names to a slice of cipher suite ints 49 | func ParseCipherSuites(cipherSuites []string) []uint16 { 50 | var cipherSuiteInts []uint16 51 | for _, cipherSuite := range cipherSuites { 52 | if cipherSuiteInt, ok := cipherSuiteToInt[cipherSuite]; ok { 53 | cipherSuiteInts = append(cipherSuiteInts, cipherSuiteInt) 54 | } else { 55 | log.Fatalf("Unknown TLS cipher suite: %s", cipherSuite) 56 | } 57 | } 58 | return cipherSuiteInts 59 | } 60 | 61 | // ParseCurves parses a slice of curves into their IDs 62 | func ParseCurves(curves []string) []tls.CurveID { 63 | var curveIDs []tls.CurveID 64 | for _, curve := range curves { 65 | if curveID, ok := curveToInt[curve]; ok { 66 | curveIDs = append(curveIDs, curveID) 67 | } else { 68 | log.Fatalf("Unknown TLS curve: %s", curve) 69 | } 70 | } 71 | return curveIDs 72 | } 73 | 74 | // Version returns a TLS version number by given protocol string with a fallback 75 | func Version(version string, fallback uint16) uint16 { 76 | switch version { 77 | case "1.0": 78 | return tls.VersionTLS10 79 | case "1.1": 80 | return tls.VersionTLS11 81 | case "1.2": 82 | return tls.VersionTLS12 83 | case "1.3": 84 | return tls.VersionTLS13 85 | default: 86 | return fallback 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /transport/quic.go: -------------------------------------------------------------------------------- 1 | package transport 2 | 3 | import ( 4 | "context" 5 | "crypto/tls" 6 | "encoding/binary" 7 | "fmt" 8 | "io" 9 | "net" 10 | 11 | "github.com/charmbracelet/log" 12 | "github.com/miekg/dns" 13 | "github.com/quic-go/quic-go" 14 | ) 15 | 16 | // DoQ Error Codes 17 | // https://datatracker.ietf.org/doc/html/rfc9250#section-8.4 18 | const ( 19 | DoQNoError = 0x0 // No error. This is used when the connection or stream needs to be closed, but there is no error to signal. 20 | DoQInternalError = 0x1 // The DoQ implementation encountered an internal error and is incapable of pursuing the transaction or the connection. 21 | DoQProtocolError = 0x2 // The DoQ implementation encountered a protocol error and is forcibly aborting the connection. 22 | DoQRequestCancelled = 0x3 // A DoQ client uses this to signal that it wants to cancel an outstanding transaction. 23 | DoQExcessiveLoad = 0x4 // A DoQ implementation uses this to signal when closing a connection due to excessive load. 24 | DoQUnspecifiedError = 0x5 // A DoQ implementation uses this in the absence of a more specific error code. 25 | DoQErrorReserved = 0xd098ea5e // Alternative error code used for tests. 26 | ) 27 | 28 | // QUIC makes a DNS query over QUIC 29 | type QUIC struct { 30 | Common 31 | TLSConfig *tls.Config 32 | PMTUD bool 33 | AddLengthPrefix bool 34 | 35 | conn *quic.Conn 36 | } 37 | 38 | func (q *QUIC) connection() *quic.Conn { 39 | return q.conn 40 | } 41 | 42 | // setServerName sets the TLS config server name to the QUIC server 43 | func (q *QUIC) setServerName() { 44 | host, _, err := net.SplitHostPort(q.Server) 45 | if err != nil { 46 | log.Fatalf("invalid QUIC server address: %s", err) 47 | } 48 | q.TLSConfig.ServerName = host 49 | } 50 | 51 | func (q *QUIC) Exchange(msg *dns.Msg) (*dns.Msg, error) { 52 | if q.conn == nil || !q.ReuseConn { 53 | log.Debugf("Connecting to %s", q.Server) 54 | q.setServerName() 55 | if len(q.TLSConfig.NextProtos) == 0 { 56 | log.Debug("No ALPN tokens specified, using default: \"doq\"") 57 | q.TLSConfig.NextProtos = []string{"doq"} 58 | } 59 | log.Debugf("Dialing with QUIC ALPN tokens: %v", q.TLSConfig.NextProtos) 60 | conn, err := quic.DialAddr( 61 | context.Background(), 62 | q.Server, 63 | q.TLSConfig, 64 | &quic.Config{ 65 | DisablePathMTUDiscovery: !q.PMTUD, 66 | }, 67 | ) 68 | if err != nil { 69 | return nil, fmt.Errorf("opening quic session to %s: %v", q.Server, err) 70 | } 71 | q.conn = conn 72 | } 73 | 74 | // Clients and servers MUST NOT send the edns-tcp-keepalive EDNS(0) Option [RFC7828] in any messages sent 75 | // on a DoQ connection (because it is specific to the use of TCP/TLS as a transport). 76 | // https://datatracker.ietf.org/doc/html/rfc9250#section-5.5.2 77 | if opt := msg.IsEdns0(); opt != nil { 78 | for _, option := range opt.Option { 79 | if option.Option() == dns.EDNS0TCPKEEPALIVE { 80 | _ = q.connection().CloseWithError(DoQProtocolError, "") // Already closing the connection, so we don't care about the error 81 | q.conn = nil 82 | return nil, fmt.Errorf("EDNS0 TCP keepalive option is set") 83 | } 84 | } 85 | } 86 | 87 | stream, err := q.connection().OpenStream() 88 | if err != nil { 89 | return nil, fmt.Errorf("open new stream to %s: %v", q.Server, err) 90 | } 91 | 92 | // When sending queries over a QUIC connection, the DNS Message ID MUST 93 | // be set to zero. The stream mapping for DoQ allows for unambiguous 94 | // correlation of queries and responses and so the Message ID field is 95 | // not required. 96 | // https://datatracker.ietf.org/doc/html/rfc9250#section-4.2.1 97 | msg.Id = 0 98 | buf, err := msg.Pack() 99 | if err != nil { 100 | return nil, err 101 | } 102 | 103 | if q.AddLengthPrefix { 104 | // All DNS messages (queries and responses) sent over DoQ connections 105 | // MUST be encoded as a 2-octet length field followed by the message 106 | // content as specified in [RFC1035]. 107 | // https://datatracker.ietf.org/doc/html/rfc9250#section-4.2-4 108 | _, err = stream.Write(addPrefix(buf)) 109 | } else { 110 | _, err = stream.Write(buf) 111 | } 112 | if err != nil { 113 | return nil, err 114 | } 115 | 116 | // The client MUST send the DNS query over the selected stream, and MUST 117 | // indicate through the STREAM FIN mechanism that no further data will 118 | // be sent on that stream. 119 | // https://datatracker.ietf.org/doc/html/rfc9250#section-4.2 120 | _ = stream.Close() 121 | 122 | respBuf, err := io.ReadAll(stream) 123 | if err != nil { 124 | return nil, fmt.Errorf("reading response from %s: %s", q.Server, err) 125 | } 126 | if len(respBuf) == 0 { 127 | return nil, fmt.Errorf("empty response from %s", q.Server) 128 | } 129 | 130 | reply := dns.Msg{} 131 | if q.AddLengthPrefix { 132 | err = reply.Unpack(respBuf[2:]) 133 | } else { 134 | err = reply.Unpack(respBuf) 135 | } 136 | if err != nil { 137 | return nil, fmt.Errorf("unpacking response from %s: %s", q.Server, err) 138 | } 139 | 140 | return &reply, nil 141 | } 142 | 143 | // addPrefix adds a 2-byte prefix with the DNS message length. 144 | func addPrefix(b []byte) (m []byte) { 145 | m = make([]byte, 2+len(b)) 146 | binary.BigEndian.PutUint16(m, uint16(len(b))) 147 | copy(m[2:], b) 148 | 149 | return m 150 | } 151 | 152 | func (q *QUIC) Close() error { 153 | return q.connection().CloseWithError(DoQNoError, "") 154 | } 155 | -------------------------------------------------------------------------------- /transport/odoh.go: -------------------------------------------------------------------------------- 1 | /* 2 | This implementation is based on https://github.com/cloudflare/odoh-client-go, per the MIT license below: 3 | 4 | The MIT License 5 | 6 | Copyright (c) 2019-2020, Cloudflare, Inc. and Christopher Wood. All rights reserved. 7 | 8 | Permission is hereby granted, free of charge, to any person obtaining a copy 9 | of this software and associated documentation files (the "Software"), to deal 10 | in the Software without restriction, including without limitation the rights 11 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | copies of the Software, and to permit persons to whom the Software is 13 | furnished to do so, subject to the following conditions: 14 | 15 | The above copyright notice and this permission notice shall be included in 16 | all copies or substantial portions of the Software. 17 | 18 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | THE SOFTWARE. 25 | */ 26 | 27 | package transport 28 | 29 | import ( 30 | "bytes" 31 | "crypto/tls" 32 | "errors" 33 | "fmt" 34 | "io" 35 | "net/http" 36 | "net/url" 37 | "strings" 38 | 39 | "github.com/charmbracelet/log" 40 | "github.com/miekg/dns" 41 | "github.com/sthorne/odoh-go" 42 | ) 43 | 44 | const ODoHContentType = "application/oblivious-dns-message" 45 | 46 | // buildURL adds HTTPS to argument s if it doesn't contain a protocol and appends defaultPath if no path is already specified 47 | func buildURL(s, defaultPath string) *url.URL { 48 | if //goland:noinspection HttpUrlsUsage 49 | !strings.HasPrefix(s, "https://") && !strings.HasPrefix(s, "http://") { 50 | s = "https://" + s 51 | } 52 | u, err := url.Parse(s) 53 | if err != nil { 54 | log.Fatalf("failed to parse url: %v", err) 55 | } 56 | if u.Path == "" { 57 | u.Path = defaultPath 58 | } 59 | return u 60 | } 61 | 62 | // ODoH makes a DNS query over ODoH 63 | type ODoH struct { 64 | Common // Server is the target 65 | Proxy string 66 | TLSConfig *tls.Config 67 | 68 | conn *http.Client 69 | } 70 | 71 | func (o *ODoH) Exchange(m *dns.Msg) (*dns.Msg, error) { 72 | // Query ODoH configs on target 73 | req, err := http.NewRequest( 74 | http.MethodGet, 75 | buildURL(strings.TrimSuffix(o.Server, "/dns-query"), "/.well-known/odohconfigs").String(), 76 | nil, 77 | ) 78 | if err != nil { 79 | return nil, fmt.Errorf("new target configs request: %s", err) 80 | } 81 | 82 | if o.conn == nil || !o.ReuseConn { 83 | o.conn = &http.Client{ 84 | Transport: &http.Transport{ 85 | TLSClientConfig: o.TLSConfig, 86 | }, 87 | } 88 | } 89 | resp, err := o.conn.Do(req) 90 | if err != nil { 91 | return nil, fmt.Errorf("do target configs request: %s", err) 92 | } 93 | defer resp.Body.Close() 94 | 95 | bodyBytes, err := io.ReadAll(resp.Body) 96 | if err != nil { 97 | return nil, err 98 | } 99 | odohConfigs, err := odoh.UnmarshalObliviousDoHConfigs(bodyBytes) 100 | if err != nil { 101 | return nil, fmt.Errorf("unmarshal target configs: %s", err) 102 | } 103 | 104 | if len(odohConfigs.Configs) == 0 { 105 | return nil, errors.New("target provided no valid ODoH configs") 106 | } 107 | log.Debugf("[odoh] retrieved %d ODoH configs", len(odohConfigs.Configs)) 108 | 109 | packedDnsQuery, err := m.Pack() 110 | if err != nil { 111 | return nil, err 112 | } 113 | 114 | firstODoHConfig := odohConfigs.Configs[0] 115 | log.Debugf("[odoh] using first ODoH config: %+v", firstODoHConfig) 116 | odnsMessage, queryContext, err := firstODoHConfig.Contents.EncryptQuery(odoh.CreateObliviousDNSQuery(packedDnsQuery, 0)) 117 | if err != nil { 118 | return nil, fmt.Errorf("encrypt query: %s", err) 119 | } 120 | 121 | t := buildURL(o.Server, "/dns-query") 122 | p := buildURL(o.Proxy, "/proxy") 123 | qry := p.Query() 124 | if qry.Get("targethost") == "" { 125 | qry.Set("targethost", t.Host) 126 | } 127 | if qry.Get("targetpath") == "" { 128 | qry.Set("targetpath", t.Path) 129 | } 130 | p.RawQuery = qry.Encode() 131 | 132 | log.Debugf("POST %s %+v", p, odnsMessage) 133 | req, err = http.NewRequest(http.MethodPost, p.String(), bytes.NewBuffer(odnsMessage.Marshal())) 134 | if err != nil { 135 | return nil, fmt.Errorf("create new request: %s", err) 136 | } 137 | req.Header.Set("Content-Type", ODoHContentType) 138 | req.Header.Set("Accept", ODoHContentType) 139 | 140 | resp, err = o.conn.Do(req) 141 | if err != nil { 142 | return nil, fmt.Errorf("do request: %s", err) 143 | } 144 | contentType := resp.Header.Get("Content-Type") 145 | if contentType != ODoHContentType { 146 | return nil, fmt.Errorf("%s responded with an invalid Content-Type header %s, expected %s", req.URL, contentType, ODoHContentType) 147 | } 148 | 149 | bodyBytes, err = io.ReadAll(resp.Body) 150 | if err != nil { 151 | return nil, fmt.Errorf("read response body: %s", err) 152 | } 153 | odohMessage, err := odoh.UnmarshalDNSMessage(bodyBytes) 154 | if err != nil { 155 | return nil, fmt.Errorf("odoh unmarshal: %s", err) 156 | } 157 | 158 | decryptedResponse, err := queryContext.OpenAnswer(odohMessage) 159 | if err != nil { 160 | return nil, fmt.Errorf("open answer: %s", err) 161 | } 162 | 163 | msg := &dns.Msg{} 164 | err = msg.Unpack(decryptedResponse) 165 | if err != nil { 166 | err = fmt.Errorf("unpack message: %s", err) 167 | } 168 | return msg, err 169 | } 170 | 171 | func (o *ODoH) Close() error { 172 | o.conn.CloseIdleConnections() 173 | return nil 174 | } 175 | -------------------------------------------------------------------------------- /resolver.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto/tls" 5 | "fmt" 6 | "net" 7 | "strings" 8 | 9 | "github.com/charmbracelet/log" 10 | "github.com/miekg/dns" 11 | 12 | "github.com/natesales/q/cli" 13 | "github.com/natesales/q/transport" 14 | ) 15 | 16 | // createQuery creates a slice of DNS queries 17 | func createQuery(opts cli.Flags, rrTypes []uint16) []dns.Msg { 18 | var queries []dns.Msg 19 | 20 | // Query for each requested RR type 21 | for _, qType := range rrTypes { 22 | req := dns.Msg{} 23 | 24 | if opts.ID != -1 { 25 | req.Id = uint16(opts.ID) 26 | } else { 27 | req.Id = dns.Id() 28 | } 29 | req.Authoritative = opts.AuthoritativeAnswer 30 | req.AuthenticatedData = opts.AuthenticData 31 | req.CheckingDisabled = opts.CheckingDisabled 32 | req.RecursionDesired = opts.RecursionDesired 33 | req.RecursionAvailable = opts.RecursionAvailable 34 | req.Zero = opts.Zero 35 | req.Truncated = opts.Truncated 36 | 37 | if opts.EDNS || opts.DNSSEC || opts.NSID || opts.Pad || opts.ClientSubnet != "" || opts.Cookie != "" { 38 | opt := &dns.OPT{ 39 | Hdr: dns.RR_Header{ 40 | Name: ".", 41 | Class: opts.UDPBuffer, 42 | Rrtype: dns.TypeOPT, 43 | }, 44 | } 45 | 46 | if opts.DNSSEC { 47 | opt.SetDo() 48 | } 49 | 50 | if opts.NSID { 51 | opt.Option = append(opt.Option, &dns.EDNS0_NSID{ 52 | Code: dns.EDNS0NSID, 53 | }) 54 | } 55 | 56 | if opts.Pad { 57 | paddingOpt := new(dns.EDNS0_PADDING) 58 | 59 | msgLen := req.Len() 60 | padLen := 128 - msgLen%128 61 | 62 | // Truncate padding to fit in UDP buffer 63 | if msgLen+padLen > int(opt.UDPSize()) { 64 | padLen = int(opt.UDPSize()) - msgLen 65 | if padLen < 0 { // Stop padding 66 | padLen = 0 67 | } 68 | } 69 | 70 | log.Debugf("Padding with %d bytes", padLen) 71 | paddingOpt.Padding = make([]byte, padLen) 72 | opt.Option = append(opt.Option, paddingOpt) 73 | } 74 | 75 | if opts.ClientSubnet != "" { 76 | ip, ipNet, err := net.ParseCIDR(opts.ClientSubnet) 77 | if err != nil { 78 | log.Fatalf("parsing subnet %s", opts.ClientSubnet) 79 | } 80 | mask, _ := ipNet.Mask.Size() 81 | log.Debugf("EDNS0 client subnet %s/%d", ip, mask) 82 | 83 | ednsSubnet := &dns.EDNS0_SUBNET{ 84 | Code: dns.EDNS0SUBNET, 85 | Address: ip, 86 | Family: 1, // IPv4 87 | SourceNetmask: uint8(mask), 88 | } 89 | 90 | if ednsSubnet.Address.To4() == nil { 91 | ednsSubnet.Family = 2 // IPv6 92 | } 93 | opt.Option = append(opt.Option, ednsSubnet) 94 | } 95 | 96 | if opts.Cookie != "" { 97 | cookie := &dns.EDNS0_COOKIE{ 98 | Code: dns.EDNS0COOKIE, 99 | Cookie: opts.Cookie, 100 | } 101 | opt.Option = append(opt.Option, cookie) 102 | } 103 | 104 | // Only include the OPT record if EDNS is enabled 105 | if opts.EDNS { 106 | req.Extra = append(req.Extra, opt) 107 | } 108 | } 109 | 110 | req.Question = []dns.Question{{ 111 | Name: dns.Fqdn(opts.Name), 112 | Qtype: qType, 113 | Qclass: opts.Class, 114 | }} 115 | 116 | queries = append(queries, req) 117 | } 118 | return queries 119 | } 120 | 121 | // newTransport creates a new transport based on local options 122 | func newTransport(server string, transportType transport.Type, tlsConfig *tls.Config) (*transport.Transport, error) { 123 | var ts transport.Transport 124 | 125 | common := transport.Common{ 126 | Server: server, 127 | ReuseConn: opts.ReuseConn, 128 | } 129 | 130 | switch transportType { 131 | case transport.TypeHTTP: 132 | if opts.ODoHProxy != "" { 133 | log.Debugf("Using ODoH transport with target %s proxy %s", server, opts.ODoHProxy) 134 | ts = &transport.ODoH{ 135 | Common: common, 136 | Proxy: opts.ODoHProxy, 137 | TLSConfig: tlsConfig, 138 | } 139 | } else { 140 | log.Debugf("Using HTTP(s) transport: %s", server) 141 | 142 | // Parse HTTP headers 143 | headers := make(map[string][]string) 144 | for _, header := range opts.HTTPHeaders { 145 | parts := strings.SplitN(header, ":", 2) 146 | if len(parts) == 2 { 147 | name := strings.TrimSpace(parts[0]) 148 | value := strings.TrimSpace(parts[1]) 149 | headers[name] = append(headers[name], value) 150 | log.Debugf("Added header %s: %s", name, value) 151 | } else { 152 | log.Warnf("Invalid header format: %s (expected 'Name: Value')", header) 153 | } 154 | } 155 | 156 | ts = &transport.HTTP{ 157 | Common: common, 158 | TLSConfig: tlsConfig, 159 | UserAgent: opts.HTTPUserAgent, 160 | Method: opts.HTTPMethod, 161 | HTTP2: opts.HTTP2, 162 | HTTP3: opts.HTTP3, 163 | NoPMTUd: !opts.PMTUD, 164 | Headers: headers, 165 | } 166 | } 167 | case transport.TypeDNSCrypt: 168 | log.Debugf("Using DNSCrypt transport: %s", server) 169 | if strings.HasPrefix(server, "sdns://") { 170 | log.Debug("Using provided DNS stamp for DNSCrypt") 171 | ts = &transport.DNSCrypt{ 172 | Common: common, 173 | ServerStamp: server, 174 | TCP: opts.DNSCryptTCP, 175 | UDPSize: opts.DNSCryptUDPSize, 176 | } 177 | } else { 178 | log.Debug("Using manual DNSCrypt configuration") 179 | ts = &transport.DNSCrypt{Common: common, 180 | 181 | TCP: opts.DNSCryptTCP, 182 | UDPSize: opts.DNSCryptUDPSize, 183 | PublicKey: opts.DNSCryptPublicKey, 184 | ProviderName: opts.DNSCryptProvider, 185 | } 186 | } 187 | case transport.TypeQUIC: 188 | log.Debugf("Using QUIC transport: %s", server) 189 | 190 | tc := tlsConfig.Clone() 191 | tc.NextProtos = opts.QUICALPNTokens 192 | 193 | ts = &transport.QUIC{ 194 | Common: common, 195 | TLSConfig: tc, 196 | PMTUD: opts.PMTUD, 197 | AddLengthPrefix: opts.QUICLengthPrefix, 198 | } 199 | case transport.TypeTLS: 200 | log.Debugf("Using TLS transport: %s", server) 201 | ts = &transport.TLS{ 202 | Common: common, 203 | TLSConfig: tlsConfig, 204 | } 205 | case transport.TypeTCP: 206 | log.Debugf("Using TCP transport: %s", server) 207 | ts = &transport.Plain{ 208 | Common: common, 209 | PreferTCP: true, 210 | EDNS: opts.EDNS, 211 | UDPBuffer: opts.UDPBuffer, 212 | Timeout: opts.Timeout, 213 | } 214 | case transport.TypePlain: 215 | log.Debugf("Using UDP with TCP fallback: %s", server) 216 | ts = &transport.Plain{ 217 | Common: common, 218 | PreferTCP: opts.TCP, 219 | EDNS: opts.EDNS, 220 | UDPBuffer: opts.UDPBuffer, 221 | Timeout: opts.Timeout, 222 | } 223 | default: 224 | return nil, fmt.Errorf("unknown transport protocol %s", transportType) 225 | } 226 | 227 | return &ts, nil 228 | } 229 | -------------------------------------------------------------------------------- /output/pretty.go: -------------------------------------------------------------------------------- 1 | package output 2 | 3 | import ( 4 | "encoding/hex" 5 | "fmt" 6 | "sort" 7 | "strconv" 8 | "strings" 9 | "time" 10 | 11 | "github.com/charmbracelet/log" 12 | "github.com/miekg/dns" 13 | whois "github.com/natesales/bgptools-go" 14 | 15 | "github.com/natesales/q/cli" 16 | "github.com/natesales/q/util" 17 | ) 18 | 19 | // PrettyPrintNSID prints the NSID from a slice of entries 20 | func (p Printer) PrettyPrintNSID(entries []*Entry, printPrefix bool) { 21 | for _, entry := range entries { 22 | for _, r := range entry.Replies { 23 | for _, o := range r.Extra { 24 | if o.Header().Rrtype == dns.TypeOPT { 25 | for _, e := range o.(*dns.OPT).Option { 26 | if e.Option() == dns.EDNS0NSID { 27 | nsidStr, err := hex.DecodeString(e.String()) 28 | if err != nil { 29 | log.Warnf("error decoding NSID: %s", err) 30 | return 31 | } 32 | var suffix string 33 | if len(entries) > 1 { 34 | suffix = fmt.Sprintf(" (%s)", entry.Server) 35 | } 36 | 37 | var prefix string 38 | if printPrefix { 39 | prefix = util.Color(util.ColorWhite, "NSID:") + " " 40 | } 41 | 42 | util.MustWritef(p.Out, "%s%s%s\n", 43 | prefix, 44 | util.Color(util.ColorPurple, string(nsidStr)), 45 | suffix, 46 | ) 47 | return 48 | } 49 | } 50 | } 51 | } 52 | } 53 | } 54 | } 55 | 56 | // parseRR converts an RR into a pretty string and returns the qname, ttl, type, value, and whether to skip printing it because it's a duplicate 57 | func (e *Entry) parseRR(a dns.RR, opts *cli.Flags) *RR { 58 | // Initialize existingRRs map if it doesn't exist 59 | if e.existingRRs == nil { 60 | e.existingRRs = make(map[string]bool) 61 | } 62 | 63 | val := a.String() 64 | for _, cut := range []string{a.Header().Name, strconv.Itoa(int(a.Header().Ttl)), dns.ClassToString[a.Header().Class], dns.TypeToString[a.Header().Rrtype]} { 65 | val = strings.TrimSpace( 66 | strings.TrimPrefix(val, cut), 67 | ) 68 | } 69 | 70 | rrSignature := fmt.Sprintf("%s %d %s %s %s", a.Header().Name, a.Header().Ttl, dns.TypeToString[a.Header().Rrtype], val, e.Server) 71 | // Skip if we've already printed this RR 72 | if ok := e.existingRRs[rrSignature]; ok { 73 | return nil 74 | } 75 | e.existingRRs[rrSignature] = true 76 | 77 | ttl := fmt.Sprintf("%d", a.Header().Ttl) 78 | if opts.PrettyTTLs { 79 | ttl = (time.Duration(a.Header().Ttl) * time.Second).String() 80 | if opts.ShortTTLs { 81 | ttl = strings.ReplaceAll(ttl, "m0s", "m") 82 | ttl = strings.ReplaceAll(ttl, "h0m", "h") 83 | } 84 | } 85 | 86 | // Copy val now before modifying it with a suffix 87 | valCopy := val 88 | 89 | // Handle whois 90 | if opts.Whois && (a.Header().Rrtype == dns.TypeA || a.Header().Rrtype == dns.TypeAAAA) { 91 | resp, err := whois.Query(valCopy) 92 | if err != nil { 93 | log.Warnf("bgp.tools query: %s", err) 94 | } else { 95 | val += util.Color(util.ColorTeal, fmt.Sprintf(" (AS%d %s)", resp.AS, resp.ASName)) 96 | } 97 | } 98 | 99 | // Handle PTR resolution 100 | if opts.ResolveIPs && (a.Header().Rrtype == dns.TypeA || a.Header().Rrtype == dns.TypeAAAA) { 101 | val += util.Color(util.ColorMagenta, fmt.Sprintf(" (%s)", e.PTRs[valCopy])) 102 | } 103 | 104 | // Server suffix 105 | if len(opts.Server) > 1 { 106 | val += util.Color(util.ColorTeal, fmt.Sprintf(" (%s)", e.Server)) 107 | } 108 | 109 | return &RR{ 110 | util.Color(util.ColorPurple, a.Header().Name), 111 | util.Color(util.ColorGreen, ttl), 112 | util.Color(util.ColorMagenta, dns.TypeToString[a.Header().Rrtype]), 113 | val, 114 | } 115 | } 116 | 117 | // sortSlices sorts a slice of slices of strings by the nth element of each slice 118 | func sortSlices(s [][]string, n int) [][]string { 119 | sort.Slice(s, func(i, j int) bool { 120 | return s[i][n] < s[j][n] 121 | }) 122 | return s 123 | } 124 | 125 | // sortToPrint sorts a slice of records first by record type, then by value 126 | func sortToPrint(s [][]string) [][]string { 127 | // Organize by record type 128 | records := make(map[string][][]string) 129 | for _, record := range s { 130 | rrType := record[2] 131 | records[rrType] = append(records[rrType], record) 132 | } 133 | 134 | // Sort each record type 135 | for rrType, recs := range records { 136 | records[rrType] = sortSlices(recs, 3) 137 | } 138 | 139 | // Sort record types 140 | var sortedTypes []string 141 | for rrType := range records { 142 | sortedTypes = append(sortedTypes, rrType) 143 | } 144 | sort.Strings(sortedTypes) 145 | 146 | // Build final result 147 | var result [][]string 148 | for _, rrType := range sortedTypes { 149 | result = append(result, records[rrType]...) 150 | } 151 | return result 152 | } 153 | 154 | type RR struct { 155 | Name, TTL, Type, Value string 156 | } 157 | 158 | func toRRs(rrs []dns.RR, e *Entry, p *Printer) []RR { 159 | var out []RR 160 | for _, rr := range rrs { 161 | if rr := e.parseRR(rr, p.Opts); rr != nil { 162 | out = append(out, *rr) 163 | } 164 | } 165 | 166 | return out 167 | } 168 | 169 | // printSection prints a slice of RRs 170 | func (p Printer) printSection(rrs []RR) { 171 | var toPrint [][]string 172 | 173 | for _, a := range rrs { 174 | if p.Opts.ValueOnly { 175 | util.MustWriteln(p.Out, a.Value) 176 | continue 177 | } 178 | 179 | if len(a.TTL) > p.longestTTL { 180 | p.longestTTL = len(a.TTL) 181 | } 182 | if len(a.Type) > p.longestRRType { 183 | p.longestRRType = len(a.Type) 184 | } 185 | 186 | toPrint = append(toPrint, []string{a.Name, a.TTL, a.Type, a.Value}) 187 | } 188 | 189 | // Sort by record type 190 | toPrint = sortToPrint(toPrint) 191 | 192 | for _, a := range toPrint { 193 | if p.Opts.Format == "column" { 194 | util.MustWritef(p.Out, "%"+strconv.Itoa(p.longestRRType)+"s %-"+strconv.Itoa(p.longestTTL)+"s %s\n", a[2], a[1], a[3]) 195 | } else { 196 | util.MustWritef(p.Out, "%s %s %s %s\n", a[0], a[1], a[2], a[3]) 197 | } 198 | } 199 | } 200 | 201 | // PrintColumn prints an entry slice in column format 202 | func (p Printer) PrintColumn(entries []*Entry) { 203 | var answers []RR 204 | for _, e := range entries { 205 | for _, r := range e.Replies { 206 | rrs := toRRs(r.Answer, e, &p) 207 | answers = append(answers, rrs...) 208 | } 209 | } 210 | 211 | p.printSection(answers) 212 | } 213 | 214 | // flags returns a string of flags from a dns.Msg 215 | func flags(m *dns.Msg) string { 216 | out := "" 217 | if m.MsgHdr.Response { 218 | out += "qr " 219 | } 220 | if m.MsgHdr.Authoritative { 221 | out += "aa " 222 | } 223 | if m.MsgHdr.Truncated { 224 | out += "tc " 225 | } 226 | if m.MsgHdr.RecursionDesired { 227 | out += "rd " 228 | } 229 | if m.MsgHdr.RecursionAvailable { 230 | out += "ra " 231 | } 232 | if m.MsgHdr.Zero { 233 | out += "z " 234 | } 235 | if m.MsgHdr.AuthenticatedData { 236 | out += "ad " 237 | } 238 | if m.MsgHdr.CheckingDisabled { 239 | out += "cd " 240 | } 241 | return strings.TrimSuffix(out, " ") 242 | } 243 | 244 | func (p Printer) PrintPretty(entries []*Entry) { 245 | for _, entry := range entries { 246 | for i, reply := range entry.Replies { 247 | if p.Opts.ShowQuestion { 248 | util.MustWriteln(p.Out, util.Color(util.ColorWhite, "Question:")) 249 | for _, a := range reply.Question { 250 | util.MustWritef(p.Out, "%s %s\n", 251 | util.Color(util.ColorPurple, a.Name), 252 | util.Color(util.ColorMagenta, dns.TypeToString[a.Qtype]), 253 | ) 254 | } 255 | } 256 | if p.Opts.ShowAnswer && len(reply.Answer) > 0 { 257 | if p.Opts.ShowQuestion || p.Opts.ShowAuthority || p.Opts.ShowAdditional { 258 | util.MustWriteln(p.Out, util.Color(util.ColorWhite, "Answer:")) 259 | } 260 | p.printSection(toRRs(reply.Answer, entry, &p)) 261 | } 262 | if p.Opts.ShowAuthority && len(reply.Ns) > 0 { 263 | util.MustWriteln(p.Out, util.Color(util.ColorWhite, "Authority:")) 264 | p.printSection(toRRs(reply.Ns, entry, &p)) 265 | } 266 | if p.Opts.ShowAdditional && len(reply.Extra) > 0 { 267 | util.MustWriteln(p.Out, util.Color(util.ColorWhite, "Additional:")) 268 | p.printSection(toRRs(reply.Extra, entry, &p)) 269 | } 270 | 271 | // Extended DNS Errors (RFC 8914) 272 | if p.Opts.ShowEDE { 273 | edes := extractEDE(reply) 274 | if len(edes) > 0 { 275 | util.MustWriteln(p.Out, util.Color(util.ColorWhite, "EDE:")) 276 | for _, e := range edes { 277 | util.MustWritef(p.Out, "%s (%s) %s\n", 278 | util.Color(util.ColorPurple, fmt.Sprintf("%d", e.Code)), 279 | util.Color(util.ColorMagenta, edeName(e.Code)), 280 | util.Color(util.ColorGreen, e.Text), 281 | ) 282 | } 283 | } 284 | } 285 | 286 | // Print separator if there is more than one query 287 | if (p.Opts.ShowQuestion || p.Opts.ShowAuthority || p.Opts.ShowAdditional) && 288 | (len(entry.Replies) > 0 && i != len(entry.Replies)-1) { 289 | util.MustWritef(p.Out, "\n──\n\n") 290 | } 291 | 292 | if p.Opts.ShowStats { 293 | util.MustWriteln(p.Out, util.Color(util.ColorWhite, "Stats:")) 294 | util.MustWritef(p.Out, "Received %s from %s in %s (%s)\n", 295 | util.Color(util.ColorPurple, fmt.Sprintf("%d B", reply.Len())), 296 | util.Color(util.ColorGreen, entry.Server), 297 | util.Color(util.ColorTeal, entry.Time.Round(100*time.Microsecond)), 298 | util.Color(util.ColorMagenta, time.Now().Format("15:04:05 01-02-2006 MST")), 299 | ) 300 | 301 | util.MustWritef(p.Out, "Opcode: %s Status: %s ID %s: Flags: %s (%s Q %s A %s N %s E)\n", 302 | util.Color(util.ColorMagenta, dns.OpcodeToString[reply.MsgHdr.Opcode]), 303 | util.Color(util.ColorTeal, dns.RcodeToString[reply.MsgHdr.Rcode]), 304 | util.Color(util.ColorGreen, fmt.Sprintf("%d", reply.MsgHdr.Id)), 305 | util.Color(util.ColorPurple, flags(reply)), 306 | util.Color(util.ColorPurple, fmt.Sprintf("%d", len(reply.Question))), 307 | util.Color(util.ColorGreen, fmt.Sprintf("%d", len(reply.Answer))), 308 | util.Color(util.ColorTeal, fmt.Sprintf("%d", len(reply.Ns))), 309 | util.Color(util.ColorMagenta, fmt.Sprintf("%d", len(reply.Extra))), 310 | ) 311 | } 312 | } 313 | } 314 | } 315 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | git.schwanenlied.me/yawning/x448.git v0.0.0-20170617130356-01b048fb03d6/go.mod h1:wQaGCqEu44ykB17jZHCevrgSVl3KJnwQBObUtrKU4uU= 2 | github.com/AdguardTeam/golibs v0.34.1 h1:RyBpZiXnJqlO3T+xjWldlxsEZDelmaFfKvXiJHDZZFQ= 3 | github.com/AdguardTeam/golibs v0.34.1/go.mod h1:K4C2EbfSEM1zY5YXoti9SfbTAHN/kIX97LpDtCwORrM= 4 | github.com/ameshkov/dnscrypt/v2 v2.4.0 h1:if6ZG2cuQmcP2TwSY+D0+8+xbPfoatufGlOQTMNkI9o= 5 | github.com/ameshkov/dnscrypt/v2 v2.4.0/go.mod h1:WpEFV2uhebXb8Jhes/5/fSdpmhGV8TL22RDaeWwV6hI= 6 | github.com/ameshkov/dnsstamps v1.0.3 h1:Srzik+J9mivH1alRACTbys2xOxs0lRH9qnTA7Y1OYVo= 7 | github.com/ameshkov/dnsstamps v1.0.3/go.mod h1:Ii3eUu73dx4Vw5O4wjzmT5+lkCwovjzaEZZ4gKyIH5A= 8 | github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= 9 | github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= 10 | github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs= 11 | github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk= 12 | github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY= 13 | github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30= 14 | github.com/charmbracelet/log v0.4.2 h1:hYt8Qj6a8yLnvR+h7MwsJv/XvmBJXiueUcI3cIxsyig= 15 | github.com/charmbracelet/log v0.4.2/go.mod h1:qifHGX/tc7eluv2R6pWIpyHDDrrb/AG71Pf2ysQu5nw= 16 | github.com/charmbracelet/x/ansi v0.8.0 h1:9GTq3xq9caJW8ZrBTe0LIe2fvfLR/bYXKTx2llXn7xE= 17 | github.com/charmbracelet/x/ansi v0.8.0/go.mod h1:wdYl/ONOLHLIVmQaxbIYEC/cRKOQyjTkowiI4blgS9Q= 18 | github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd h1:vy0GVL4jeHEwG5YOXDmi86oYw2yuYUGqz6a8sLwg0X8= 19 | github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs= 20 | github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ= 21 | github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg= 22 | github.com/cisco/go-hpke v0.0.0-20210215210317-01c430f1f302/go.mod h1:RSsoIHRMBe69FbF/fIbmWYa3rrC6vuPyC0MbNUpel3Q= 23 | github.com/cisco/go-hpke v0.0.0-20230407100446-246075f83609 h1:+zUH9Y9OFBb59WFBFAQJTK25GGTby/g0DU7P+Pz1WaI= 24 | github.com/cisco/go-hpke v0.0.0-20230407100446-246075f83609/go.mod h1:RJ2C6TWlNvW2BlTT+YcexuRwIyzXter42/IRyb2sOTg= 25 | github.com/cisco/go-tls-syntax v0.0.0-20200617162716-46b0cfb76b9b h1:Ves2turKTX7zruivAcUOQg155xggcbv3suVdbKCBQNM= 26 | github.com/cisco/go-tls-syntax v0.0.0-20200617162716-46b0cfb76b9b/go.mod h1:0AZAV7lYvynZQ5ErHlGMKH+4QYMyNCFd+AiL9MlrCYA= 27 | github.com/cloudflare/circl v1.0.0/go.mod h1:MhjB3NEEhJbTOdLLq964NIUisXDxaE1WkQPUxtgZXiY= 28 | github.com/cloudflare/circl v1.6.1 h1:zqIqSPIndyBh1bjLVVDHMPpVKqp8Su/V+6MeDzzQBQ0= 29 | github.com/cloudflare/circl v1.6.1/go.mod h1:uddAzsPgqdMAYatqJ0lsjX1oECcQLIlRpzZh3pJrofs= 30 | github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= 31 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 32 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 33 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 34 | github.com/go-logfmt/logfmt v0.6.0 h1:wGYYu3uicYdqXVgoYbvnkrPVXkuLM1p1ifugDMEdRi4= 35 | github.com/go-logfmt/logfmt v0.6.0/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs= 36 | github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= 37 | github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= 38 | github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= 39 | github.com/jedisct1/go-dnsstamps v0.0.0-20240423203910-07a0735c7774 h1:DobL5d8UxrYzlD0PbU/EVBAGHuDiFyH46gr6povMw50= 40 | github.com/jedisct1/go-dnsstamps v0.0.0-20240423203910-07a0735c7774/go.mod h1:mEGEFZsGe4sG5Mb3Xi89pmsy+TZ0946ArbYMGKAM5uA= 41 | github.com/jessevdk/go-flags v1.6.1 h1:Cvu5U8UGrLay1rZfv/zP7iLpSHGUZ/Ou68T0iX1bBK4= 42 | github.com/jessevdk/go-flags v1.6.1/go.mod h1:Mk8T1hIAWpOiJiHa9rJASDK2UGWji0EuPGBnNLMooyc= 43 | github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= 44 | github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= 45 | github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= 46 | github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= 47 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= 48 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= 49 | github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= 50 | github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= 51 | github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= 52 | github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= 53 | github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= 54 | github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= 55 | github.com/miekg/dns v1.1.68 h1:jsSRkNozw7G/mnmXULynzMNIsgY2dHC8LO6U6Ij2JEA= 56 | github.com/miekg/dns v1.1.68/go.mod h1:fujopn7TB3Pu3JM69XaawiU0wqjpL9/8xGop5UrTPps= 57 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 58 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= 59 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 60 | github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= 61 | github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= 62 | github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc= 63 | github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk= 64 | github.com/natesales/bgptools-go v0.0.0-20230212051756-2b519d61269c h1:bblm7D7Ld1/zkWvMU1j60lMk5h/F4AiKW23j1yffM5Y= 65 | github.com/natesales/bgptools-go v0.0.0-20230212051756-2b519d61269c/go.mod h1:jl8YnQACciyOXRgNIRhURrCF9FmRHjnfT8UCj3LBkyY= 66 | github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= 67 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 68 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 69 | github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI= 70 | github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1ZgaEg= 71 | github.com/quic-go/quic-go v0.54.0 h1:6s1YB9QotYI6Ospeiguknbp2Znb/jZYjZLRXn9kMQBg= 72 | github.com/quic-go/quic-go v0.54.0/go.mod h1:e68ZEaCdyviluZmy44P6Iey98v/Wfz6HCjQEm+l8zTY= 73 | github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= 74 | github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= 75 | github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= 76 | github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= 77 | github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= 78 | github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= 79 | github.com/sthorne/odoh-go v1.0.4 h1:RPJceVs/dIpNE3gyzk6wdSay+nR+tI1YXBUwykvCEXI= 80 | github.com/sthorne/odoh-go v1.0.4/go.mod h1:KdB/NGiepr9bLVs3k26uWl4HHPHqa2DaoPUgUfKNmJU= 81 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 82 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 83 | github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 84 | github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= 85 | github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 86 | github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= 87 | github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= 88 | go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y= 89 | go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= 90 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 91 | golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= 92 | golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= 93 | golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI= 94 | golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8= 95 | golang.org/x/exp v0.0.0-20250911091902-df9299821621 h1:2id6c1/gto0kaHYyrixvknJ8tUK/Qs5IsmBtrc+FtgU= 96 | golang.org/x/exp v0.0.0-20250911091902-df9299821621/go.mod h1:TwQYMMnGpvZyc+JpB/UAuTNIsVJifOlSkrZkhcvpVUk= 97 | golang.org/x/mod v0.28.0 h1:gQBtGhjxykdjY9YhZpSlZIsbnaE2+PgjfLWUQTnoZ1U= 98 | golang.org/x/mod v0.28.0/go.mod h1:yfB/L0NOf/kmEbXjzCPOx1iK1fRutOydrCMsqRhEBxI= 99 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 100 | golang.org/x/net v0.44.0 h1:evd8IRDyfNBMBTTY5XRF1vaZlD+EmWx6x8PkhR04H/I= 101 | golang.org/x/net v0.44.0/go.mod h1:ECOoLqd5U3Lhyeyo/QDCEVQ4sNgYsqvCZ722XogGieY= 102 | golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug= 103 | golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= 104 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 105 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 106 | golang.org/x/sys v0.0.0-20190602015325-4c4f7f33c9ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 107 | golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 108 | golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 109 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 110 | golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k= 111 | golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= 112 | golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= 113 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 114 | golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk= 115 | golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4= 116 | golang.org/x/tools v0.37.0 h1:DVSRzp7FwePZW356yEAChSdNcQo6Nsp+fex1SUW09lE= 117 | golang.org/x/tools v0.37.0/go.mod h1:MBN5QPQtLMHVdvsbtarmTNukZDdgwdwlO5qGacAzF0w= 118 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 119 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= 120 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 121 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 122 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 123 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 124 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 |

q

3 | 4 | A tiny and feature-rich command line DNS client with support for UDP, TCP, DoT, DoH, DoQ, and ODoH. 5 | 6 | [![Release](https://img.shields.io/github/v/release/natesales/q?style=for-the-badge)](https://github.com/natesales/q/releases) 7 | ![Coverage](coverage_badge.png) 8 | [![Go Report](https://goreportcard.com/badge/github.com/natesales/q?style=for-the-badge)](https://goreportcard.com/report/github.com/natesales/q) 9 | [![License](https://img.shields.io/github/license/natesales/q?style=for-the-badge)](https://raw.githubusercontent.com/natesales/q/main/LICENSE) 10 | 11 | ![q screenshot](carbon.svg) 12 |
13 | 14 | ### Examples 15 | 16 | ```text 17 | q example.com Lookup default records for a domain 18 | q example.com MX SOA ...or specify a list of types 19 | 20 | q example.com MX @9.9.9.9 Query a specific server 21 | q example.com MX @https://dns.quad9.net ...over HTTPS (or TCP, TLS, QUIC, or ODoH)... 22 | q @sdns://AgcAAAAAAAAAAAAHOS45LjkuOQA ...or from a DNS Stamp 23 | 24 | q example.com MX --format=raw Output in raw (dig) format 25 | q example.com MX --format=json ...or as JSON (or YAML) 26 | ``` 27 | 28 | ### Usage 29 | 30 | ```text 31 | Usage: 32 | q [OPTIONS] [@server] [type...] [name] 33 | 34 | All long form (--) flags can be toggled with the dig-standard +[no]flag notation. 35 | 36 | Application Options: 37 | -q, --qname= Query name 38 | -s, --server= DNS server(s) 39 | -t, --type= RR type (e.g. A, AAAA, MX, etc.) or type 40 | integer 41 | -x, --reverse Reverse lookup 42 | -d, --dnssec Set the DO (DNSSEC OK) bit in the OPT record 43 | -n, --nsid Set EDNS0 NSID opt 44 | -N, --nsid-only Set EDNS0 NSID opt and query only for the NSID 45 | --subnet= Set EDNS0 client subnet 46 | -c, --chaos Use CHAOS query class 47 | -C= Set query class (default: IN 0x01) (default: 48 | 1) 49 | -p, --odoh-proxy= ODoH proxy 50 | --timeout= Query timeout (default: 10s) 51 | --pad Set EDNS0 padding 52 | --http2 Use HTTP/2 for DoH 53 | --http3 Use HTTP/3 for DoH 54 | --id-check Check DNS response ID (default: true) 55 | --reuse-conn Reuse connections across queries to the same 56 | server (default: true) 57 | --txtconcat Concatenate TXT responses 58 | --qid= Set query ID (-1 for random) (default: -1) 59 | -b, --bootstrap-server= DNS server to use for bootstrapping 60 | --bootstrap-timeout= Bootstrapping timeout (default: 5s) 61 | --cookie= EDNS0 cookie 62 | --recaxfr Perform recursive AXFR 63 | -f, --format= Output format (pretty, column, json, yaml, 64 | raw) (default: pretty) 65 | --pretty-ttls Format TTLs in human readable format 66 | (default: true) 67 | --short-ttls Remove zero components of pretty TTLs. 68 | (24h0m0s->24h) (default: true) 69 | --color Enable color output 70 | --question Show question section 71 | --opt Show OPT records 72 | --ede Show Extended DNS Errors (RFC 8914) 73 | --answer Show answer section (default: true) 74 | --authority Show authority section 75 | --additional Show additional section 76 | -S, --stats Show time statistics 77 | --all Show all sections and statistics 78 | -w Resolve ASN/ASName for A and AAAA records 79 | -r, --short Show record values only 80 | -R, --resolve-ips Resolve PTR records for IP addresses in A and 81 | AAAA records 82 | --round-ttls Round TTLs to the nearest minute 83 | --aa Set AA (Authoritative Answer) flag in query 84 | --ad Set AD (Authentic Data) flag in query 85 | --cd Set CD (Checking Disabled) flag in query 86 | --rd Set RD (Recursion Desired) flag in query 87 | (default: true) 88 | --ra Set RA (Recursion Available) flag in query 89 | --z Set Z (Zero) flag in query 90 | --t Set TC (Truncated) flag in query 91 | -i, --tls-insecure-skip-verify Disable TLS certificate verification 92 | --tls-server-name= TLS server name for host verification 93 | --tls-min-version= Minimum TLS version to use (default: 1.0) 94 | --tls-max-version= Maximum TLS version to use (default: 1.3) 95 | --tls-next-protos= TLS next protocols for ALPN 96 | --tls-cipher-suites= TLS cipher suites 97 | --tls-curve-preferences= TLS curve preferences 98 | --tls-client-cert= TLS client certificate file 99 | --tls-client-key= TLS client key file 100 | --tls-key-log-file= TLS key log file [$SSLKEYLOGFILE] 101 | --http-user-agent= HTTP user agent 102 | --http-method= HTTP method (default: GET) 103 | --http-header= HTTP header in format 'Name: Value' 104 | --pmtud PMTU discovery (default: true) 105 | --edns Enable EDNS0 (default: true) 106 | --tcp Use TCP for plain DNS (force TCP) 107 | --quic-alpn-tokens= QUIC ALPN tokens (default: doq, doq-i11) 108 | --quic-length-prefix Add RFC 9250 compliant length prefix 109 | (default: true) 110 | --dnscrypt-tcp Use TCP for DNSCrypt (default UDP) 111 | --dnscrypt-udp-size= Maximum size of a DNS response this client 112 | can sent or receive (default: 0) 113 | --dnscrypt-key= DNSCrypt public key 114 | --dnscrypt-provider= DNSCrypt provider name 115 | --default-rr-types= Default record types (default: A, AAAA, NS, 116 | MX, TXT, CNAME) 117 | --udp-buffer= Set EDNS0 UDP size in query (default: 1232) 118 | -v, --verbose Show verbose log messages 119 | --trace Show trace log messages 120 | -V, --version Show version and exit 121 | 122 | Help Options: 123 | -h, --help Show this help message 124 | ``` 125 | 126 | ### Demo 127 | 128 | [![asciicast](https://asciinema.org/a/XdWPPvZgx4hEBFwGnGwL13bsZ.svg)](https://asciinema.org/a/XdWPPvZgx4hEBFwGnGwL13bsZ) 129 | 130 | ### Protocol Support 131 | 132 | - UDP/TCP DNS ([RFC 1034](https://tools.ietf.org/html/rfc1034)) 133 | - DNS over TLS ([RFC 7858](https://tools.ietf.org/html/rfc7858)) 134 | - DNS over HTTPS ([RFC 8484](https://tools.ietf.org/html/rfc8484)) 135 | - DNS over QUIC ([RFC 9250](https://tools.ietf.org/html/rfc9250)) 136 | - Oblivious DNS over HTTPS ([RFC 9230](https://tools.ietf.org/html/rfc9230)) 137 | - DNSCrypt v2 ([draft-dennis-dprive-dnscrypt](https://dnscrypt.github.io/dnscrypt-protocol/draft-denis-dprive-dnscrypt.html)) 138 | 139 | ### Installation 140 | 141 | `q` is available from: 142 | 143 | - [apt/yum/brew from my package repositories](https://github.com/natesales/repo) 144 | - [Homebrew core repository](https://formulae.brew.sh/formula/q) 145 | - [GitHub releases](https://github.com/natesales/q/releases) 146 | - [q-dns-git](https://aur.archlinux.org/packages/q-dns-git/) in the AUR 147 | - `go install github.com/natesales/q@latest` 148 | - `docker run --rm -it ghcr.io/natesales/q` 149 | 150 | To install `q` from source: 151 | 152 | ```sh 153 | git clone https://github.com/natesales/q && cd q 154 | go install 155 | 156 | # Without debug information 157 | go install -ldflags="-s -w -X main.version=release" 158 | ``` 159 | 160 | ### Server Selection 161 | 162 | `q` will use a server from the following sources, in order: 163 | 164 | 1. `@server` argument (e.g. `@9.9.9.9` or `@https://dns.google/dns-query`) 165 | 2. `Q_DEFAULT_SERVER` environment variable 166 | 3. `/etc/resolv.conf` 167 | 168 | ### TLS Decryption 169 | 170 | `q` supports TLS decryption through a key log file generated when 171 | the `SSLKEYLOGFILE` environment variable is set to a file path. 172 | 173 | ### Feature Comparison 174 | 175 | | Protocol | q | doggo | dog | kdig | dig | drill | 176 | |:------------------------------|:-:|:-----:|:---:|:----:|:---:|:-----:| 177 | | **Transport Protocols** | | | | | | | 178 | | UDP/TCP | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | 179 | | DNS over TLS | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | 180 | | DNS over HTTPS | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | 181 | | DNS over QUIC | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | 182 | | Oblivious DNS over HTTPS | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | 183 | | DNSCrypt v2 | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | 184 | | **Features** | | | | | | | 185 | | Recursive AXFR | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | 186 | | IP Whois | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | 187 | | Resolve PTRs from A/AAAAs | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | 188 | | Server from DNS Stamp | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | 189 | | **Output Formats** | | | | | | | 190 | | Raw (dig-style) | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | 191 | | Pretty colors | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | 192 | | JSON | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | 193 | | YAML | ✅ | ❌ | ❌ | ❌ | ✅ | ❌ | 194 | | **Output Control** | | | | | | | 195 | | Toggle question section | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | 196 | | Toggle answer section | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | 197 | | Toggle authority section | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | 198 | | Toggle additional section | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | 199 | | Show query time | ✅ | ✅ | ❌ | ✅ | ✅ | ❌ | 200 | | **Query Flags** | | | | | | | 201 | | AA | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | 202 | | AD | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | 203 | | CD | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | 204 | | RD | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | 205 | | Z | ✅ | ✅ | ❌ | ✅ | ✅ | ❌ | 206 | | DO | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | 207 | | TC | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | 208 | | **Protocol Tweaks** | | | | | | | 209 | | HTTP Method | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | 210 | | HTTP Headers | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | 211 | | QUIC ALPN Tokens | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | 212 | | QUIC toggle PMTU discovery | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | 213 | | QUIC timeouts (dial and idle) | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | 214 | | TLS handshake timeout | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | 215 | -------------------------------------------------------------------------------- /transport/LICENSE: -------------------------------------------------------------------------------- 1 | This implementation is based on https://github.com/AdguardTeam/dnsproxy, per the Apache license below 2 | 3 | Apache License 4 | Version 2.0, January 2004 5 | http://www.apache.org/licenses/ 6 | 7 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 8 | 9 | 1. Definitions. 10 | 11 | "License" shall mean the terms and conditions for use, reproduction, 12 | and distribution as defined by Sections 1 through 9 of this document. 13 | 14 | "Licensor" shall mean the copyright owner or entity authorized by 15 | the copyright owner that is granting the License. 16 | 17 | "Legal Entity" shall mean the union of the acting entity and all 18 | other entities that control, are controlled by, or are under common 19 | control with that entity. For the purposes of this definition, 20 | "control" means (i) the power, direct or indirect, to cause the 21 | direction or management of such entity, whether by contract or 22 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 23 | outstanding shares, or (iii) beneficial ownership of such entity. 24 | 25 | "You" (or "Your") shall mean an individual or Legal Entity 26 | exercising permissions granted by this License. 27 | 28 | "Source" form shall mean the preferred form for making modifications, 29 | including but not limited to software source code, documentation 30 | source, and configuration files. 31 | 32 | "Object" form shall mean any form resulting from mechanical 33 | transformation or translation of a Source form, including but 34 | not limited to compiled object code, generated documentation, 35 | and conversions to other media types. 36 | 37 | "Work" shall mean the work of authorship, whether in Source or 38 | Object form, made available under the License, as indicated by a 39 | copyright notice that is included in or attached to the work 40 | (an example is provided in the Appendix below). 41 | 42 | "Derivative Works" shall mean any work, whether in Source or Object 43 | form, that is based on (or derived from) the Work and for which the 44 | editorial revisions, annotations, elaborations, or other modifications 45 | represent, as a whole, an original work of authorship. For the purposes 46 | of this License, Derivative Works shall not include works that remain 47 | separable from, or merely link (or bind by name) to the interfaces of, 48 | the Work and Derivative Works thereof. 49 | 50 | "Contribution" shall mean any work of authorship, including 51 | the original version of the Work and any modifications or additions 52 | to that Work or Derivative Works thereof, that is intentionally 53 | submitted to Licensor for inclusion in the Work by the copyright owner 54 | or by an individual or Legal Entity authorized to submit on behalf of 55 | the copyright owner. For the purposes of this definition, "submitted" 56 | means any form of electronic, verbal, or written communication sent 57 | to the Licensor or its representatives, including but not limited to 58 | communication on electronic mailing lists, source code control systems, 59 | and issue tracking systems that are managed by, or on behalf of, the 60 | Licensor for the purpose of discussing and improving the Work, but 61 | excluding communication that is conspicuously marked or otherwise 62 | designated in writing by the copyright owner as "Not a Contribution." 63 | 64 | "Contributor" shall mean Licensor and any individual or Legal Entity 65 | on behalf of whom a Contribution has been received by Licensor and 66 | subsequently incorporated within the Work. 67 | 68 | 2. Grant of Copyright License. Subject to the terms and conditions of 69 | this License, each Contributor hereby grants to You a perpetual, 70 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 71 | copyright license to reproduce, prepare Derivative Works of, 72 | publicly display, publicly perform, sublicense, and distribute the 73 | Work and such Derivative Works in Source or Object form. 74 | 75 | 3. Grant of Patent License. Subject to the terms and conditions of 76 | this License, each Contributor hereby grants to You a perpetual, 77 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 78 | (except as stated in this section) patent license to make, have made, 79 | use, offer to sell, sell, import, and otherwise transfer the Work, 80 | where such license applies only to those patent claims licensable 81 | by such Contributor that are necessarily infringed by their 82 | Contribution(s) alone or by combination of their Contribution(s) 83 | with the Work to which such Contribution(s) was submitted. If You 84 | institute patent litigation against any entity (including a 85 | cross-claim or counterclaim in a lawsuit) alleging that the Work 86 | or a Contribution incorporated within the Work constitutes direct 87 | or contributory patent infringement, then any patent licenses 88 | granted to You under this License for that Work shall terminate 89 | as of the date such litigation is filed. 90 | 91 | 4. Redistribution. You may reproduce and distribute copies of the 92 | Work or Derivative Works thereof in any medium, with or without 93 | modifications, and in Source or Object form, provided that You 94 | meet the following conditions: 95 | 96 | (a) You must give any other recipients of the Work or 97 | Derivative Works a copy of this License; and 98 | 99 | (b) You must cause any modified files to carry prominent notices 100 | stating that You changed the files; and 101 | 102 | (c) You must retain, in the Source form of any Derivative Works 103 | that You distribute, all copyright, patent, trademark, and 104 | attribution notices from the Source form of the Work, 105 | excluding those notices that do not pertain to any part of 106 | the Derivative Works; and 107 | 108 | (d) If the Work includes a "NOTICE" text file as part of its 109 | distribution, then any Derivative Works that You distribute must 110 | include a readable copy of the attribution notices contained 111 | within such NOTICE file, excluding those notices that do not 112 | pertain to any part of the Derivative Works, in at least one 113 | of the following places: within a NOTICE text file distributed 114 | as part of the Derivative Works; within the Source form or 115 | documentation, if provided along with the Derivative Works; or, 116 | within a display generated by the Derivative Works, if and 117 | wherever such third-party notices normally appear. The contents 118 | of the NOTICE file are for informational purposes only and 119 | do not modify the License. You may add Your own attribution 120 | notices within Derivative Works that You distribute, alongside 121 | or as an addendum to the NOTICE text from the Work, provided 122 | that such additional attribution notices cannot be construed 123 | as modifying the License. 124 | 125 | You may add Your own copyright statement to Your modifications and 126 | may provide additional or different license terms and conditions 127 | for use, reproduction, or distribution of Your modifications, or 128 | for any such Derivative Works as a whole, provided Your use, 129 | reproduction, and distribution of the Work otherwise complies with 130 | the conditions stated in this License. 131 | 132 | 5. Submission of Contributions. Unless You explicitly state otherwise, 133 | any Contribution intentionally submitted for inclusion in the Work 134 | by You to the Licensor shall be under the terms and conditions of 135 | this License, without any additional terms or conditions. 136 | Notwithstanding the above, nothing herein shall supersede or modify 137 | the terms of any separate license agreement you may have executed 138 | with Licensor regarding such Contributions. 139 | 140 | 6. Trademarks. This License does not grant permission to use the trade 141 | names, trademarks, service marks, or product names of the Licensor, 142 | except as required for reasonable and customary use in describing the 143 | origin of the Work and reproducing the content of the NOTICE file. 144 | 145 | 7. Disclaimer of Warranty. Unless required by applicable law or 146 | agreed to in writing, Licensor provides the Work (and each 147 | Contributor provides its Contributions) on an "AS IS" BASIS, 148 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 149 | implied, including, without limitation, any warranties or conditions 150 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 151 | PARTICULAR PURPOSE. You are solely responsible for determining the 152 | appropriateness of using or redistributing the Work and assume any 153 | risks associated with Your exercise of permissions under this License. 154 | 155 | 8. Limitation of Liability. In no event and under no legal theory, 156 | whether in tort (including negligence), contract, or otherwise, 157 | unless required by applicable law (such as deliberate and grossly 158 | negligent acts) or agreed to in writing, shall any Contributor be 159 | liable to You for damages, including any direct, indirect, special, 160 | incidental, or consequential damages of any character arising as a 161 | result of this License or out of the use or inability to use the 162 | Work (including but not limited to damages for loss of goodwill, 163 | work stoppage, computer failure or malfunction, or any and all 164 | other commercial damages or losses), even if such Contributor 165 | has been advised of the possibility of such damages. 166 | 167 | 9. Accepting Warranty or Additional Liability. While redistributing 168 | the Work or Derivative Works thereof, You may choose to offer, 169 | and charge a fee for, acceptance of support, warranty, indemnity, 170 | or other liability obligations and/or rights consistent with this 171 | License. However, in accepting such obligations, You may act only 172 | on Your own behalf and on Your sole responsibility, not on behalf 173 | of any other Contributor, and only if You agree to indemnify, 174 | defend, and hold each Contributor harmless for any liability 175 | incurred by, or claims asserted against, such Contributor by reason 176 | of your accepting any such warranty or additional liability. 177 | 178 | END OF TERMS AND CONDITIONS 179 | 180 | APPENDIX: How to apply the Apache License to your work. 181 | 182 | To apply the Apache License to your work, attach the following 183 | boilerplate notice, with the fields enclosed by brackets "[]" 184 | replaced with your own identifying information. (Don't include 185 | the brackets!) The text should be enclosed in the appropriate 186 | comment syntax for the file format. We also recommend that a 187 | file or class name and description of purpose be included on the 188 | same "printed page" as the copyright notice for easier 189 | identification within third-party archives. 190 | 191 | Copyright 2020 Adguard Software Ltd 192 | 193 | Licensed under the Apache License, Version 2.0 (the "License"); 194 | you may not use this file except in compliance with the License. 195 | You may obtain a copy of the License at 196 | 197 | http://www.apache.org/licenses/LICENSE-2.0 198 | 199 | Unless required by applicable law or agreed to in writing, software 200 | distributed under the License is distributed on an "AS IS" BASIS, 201 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 202 | See the License for the specific language governing permissions and 203 | limitations under the License. 204 | -------------------------------------------------------------------------------- /cli/cli.go: -------------------------------------------------------------------------------- 1 | package cli 2 | 3 | import ( 4 | "fmt" 5 | "reflect" 6 | "strconv" 7 | "strings" 8 | "time" 9 | 10 | "github.com/charmbracelet/log" 11 | "github.com/miekg/dns" 12 | ) 13 | 14 | type Flags struct { 15 | Name string `short:"q" long:"qname" description:"Query name"` 16 | Server []string `short:"s" long:"server" description:"DNS server(s)"` 17 | Types []string `short:"t" long:"type" description:"RR type (e.g. A, AAAA, MX, etc.) or type integer"` 18 | Reverse bool `short:"x" long:"reverse" description:"Reverse lookup"` 19 | DNSSEC bool `short:"d" long:"dnssec" description:"Set the DO (DNSSEC OK) bit in the OPT record"` 20 | NSID bool `short:"n" long:"nsid" description:"Set EDNS0 NSID opt"` 21 | NSIDOnly bool `short:"N" long:"nsid-only" description:"Set EDNS0 NSID opt and query only for the NSID"` 22 | ClientSubnet string `long:"subnet" description:"Set EDNS0 client subnet"` 23 | Chaos bool `short:"c" long:"chaos" description:"Use CHAOS query class"` 24 | Class uint16 `short:"C" description:"Set query class (default: IN 0x01)" default:"1"` 25 | ODoHProxy string `short:"p" long:"odoh-proxy" description:"ODoH proxy"` 26 | Timeout time.Duration `long:"timeout" description:"Query timeout" default:"10s"` 27 | Pad bool `long:"pad" description:"Set EDNS0 padding"` 28 | HTTP2 bool `long:"http2" description:"Use HTTP/2 for DoH"` 29 | HTTP3 bool `long:"http3" description:"Use HTTP/3 for DoH"` 30 | IDCheck bool `long:"id-check" description:"Check DNS response ID (default: true)"` 31 | ReuseConn bool `long:"reuse-conn" description:"Reuse connections across queries to the same server (default: true)"` 32 | TXTConcat bool `long:"txtconcat" description:"Concatenate TXT responses"` 33 | ID int `long:"qid" description:"Set query ID (-1 for random)" default:"-1"` 34 | BootstrapServer string `short:"b" long:"bootstrap-server" description:"DNS server to use for bootstrapping"` 35 | BootstrapTimeout time.Duration `long:"bootstrap-timeout" description:"Bootstrapping timeout" default:"5s"` 36 | Cookie string `long:"cookie" description:"EDNS0 cookie"` 37 | 38 | // Special query modes 39 | RecAXFR bool `long:"recaxfr" description:"Perform recursive AXFR"` 40 | 41 | // Output 42 | Format string `short:"f" long:"format" description:"Output format (pretty, column, json, yaml, raw)" default:"pretty"` 43 | PrettyTTLs bool `long:"pretty-ttls" description:"Format TTLs in human readable format (default: true)"` 44 | ShortTTLs bool `long:"short-ttls" description:"Remove zero components of pretty TTLs. (24h0m0s->24h) (default: true)"` 45 | Color bool `long:"color" description:"Enable color output"` 46 | ShowQuestion bool `long:"question" description:"Show question section"` 47 | ShowOpt bool `long:"opt" description:"Show OPT records"` 48 | ShowEDE bool `long:"ede" description:"Show Extended DNS Errors (RFC 8914)"` 49 | ShowAnswer bool `long:"answer" description:"Show answer section (default: true)"` 50 | ShowAuthority bool `long:"authority" description:"Show authority section"` 51 | ShowAdditional bool `long:"additional" description:"Show additional section"` 52 | ShowStats bool `short:"S" long:"stats" description:"Show time statistics"` 53 | ShowAll bool `long:"all" description:"Show all sections and statistics"` 54 | Whois bool `short:"w" description:"Resolve ASN/ASName for A and AAAA records"` 55 | ValueOnly bool `short:"r" long:"short" description:"Show record values only"` 56 | ResolveIPs bool `short:"R" long:"resolve-ips" description:"Resolve PTR records for IP addresses in A and AAAA records"` 57 | RoundTTLs bool `long:"round-ttls" description:"Round TTLs to the nearest minute"` 58 | 59 | // Header flags 60 | AuthoritativeAnswer bool `long:"aa" description:"Set AA (Authoritative Answer) flag in query"` 61 | AuthenticData bool `long:"ad" description:"Set AD (Authentic Data) flag in query"` 62 | CheckingDisabled bool `long:"cd" description:"Set CD (Checking Disabled) flag in query"` 63 | RecursionDesired bool `long:"rd" description:"Set RD (Recursion Desired) flag in query (default: true)"` 64 | RecursionAvailable bool `long:"ra" description:"Set RA (Recursion Available) flag in query"` 65 | Zero bool `long:"z" description:"Set Z (Zero) flag in query"` 66 | Truncated bool `long:"t" description:"Set TC (Truncated) flag in query"` 67 | 68 | // TLS parameters 69 | TLSInsecureSkipVerify bool `short:"i" long:"tls-insecure-skip-verify" description:"Disable TLS certificate verification"` 70 | TLSServerName string `long:"tls-server-name" description:"TLS server name for host verification"` 71 | TLSMinVersion string `long:"tls-min-version" description:"Minimum TLS version to use" default:"1.0"` 72 | TLSMaxVersion string `long:"tls-max-version" description:"Maximum TLS version to use" default:"1.3"` 73 | TLSNextProtos []string `long:"tls-next-protos" description:"TLS next protocols for ALPN"` 74 | TLSCipherSuites []string `long:"tls-cipher-suites" description:"TLS cipher suites"` 75 | TLSCurvePreferences []string `long:"tls-curve-preferences" description:"TLS curve preferences"` 76 | TLSClientCertificate string `long:"tls-client-cert" description:"TLS client certificate file"` 77 | TLSClientKey string `long:"tls-client-key" description:"TLS client key file"` 78 | TLSKeyLogFile string `long:"tls-key-log-file" env:"SSLKEYLOGFILE" description:"TLS key log file"` 79 | 80 | // HTTP 81 | HTTPUserAgent string `long:"http-user-agent" description:"HTTP user agent" default:""` 82 | HTTPMethod string `long:"http-method" description:"HTTP method" default:"GET"` 83 | HTTPHeaders []string `long:"http-header" description:"HTTP header in format 'Name: Value'"` 84 | 85 | PMTUD bool `long:"pmtud" description:"PMTU discovery (default: true)"` 86 | 87 | // EDNS/compat flags (dig-like) 88 | EDNS bool `long:"edns" description:"Enable EDNS0 (default: true)"` 89 | TCP bool `long:"tcp" description:"Use TCP for plain DNS (force TCP)"` 90 | 91 | // QUIC 92 | QUICALPNTokens []string `long:"quic-alpn-tokens" description:"QUIC ALPN tokens" default:"doq" default:"doq-i11"` //nolint:golint,staticcheck 93 | QUICLengthPrefix bool `long:"quic-length-prefix" description:"Add RFC 9250 compliant length prefix (default: true)"` 94 | 95 | // DNSCrypt 96 | DNSCryptTCP bool `long:"dnscrypt-tcp" description:"Use TCP for DNSCrypt (default UDP)"` 97 | DNSCryptUDPSize int `long:"dnscrypt-udp-size" description:"Maximum size of a DNS response this client can sent or receive" default:"0"` 98 | DNSCryptPublicKey string `long:"dnscrypt-key" description:"DNSCrypt public key"` 99 | DNSCryptProvider string `long:"dnscrypt-provider" description:"DNSCrypt provider name"` 100 | 101 | DefaultRRTypes []string `long:"default-rr-types" description:"Default record types" default:"A" default:"AAAA" default:"NS" default:"MX" default:"TXT" default:"CNAME"` //nolint:golint,staticcheck 102 | 103 | UDPBuffer uint16 `long:"udp-buffer" description:"Set EDNS0 UDP size in query" default:"1232"` 104 | Verbose bool `short:"v" long:"verbose" description:"Show verbose log messages"` 105 | Trace bool `long:"trace" description:"Show trace log messages"` 106 | ShowVersion bool `short:"V" long:"version" description:"Show version and exit"` 107 | } 108 | 109 | // ParsePlusFlags parses a list of flags notated by +[no]flag and sets the corresponding opts fields 110 | func ParsePlusFlags(opts *Flags, args []string) { 111 | for _, arg := range args { 112 | if len(arg) > 3 && arg[0] == '+' { 113 | argFound := false 114 | 115 | flag := strings.ToLower(arg[3:]) 116 | state := arg[1:3] != "no" 117 | if state { 118 | flag = strings.ToLower(arg[1:]) 119 | } 120 | 121 | v := reflect.Indirect(reflect.ValueOf(opts)) 122 | vT := v.Type() 123 | for i := 0; i < v.NumField(); i++ { 124 | fieldTag := vT.Field(i).Tag.Get("long") 125 | if vT.Field(i).Type == reflect.TypeOf(true) && fieldTag == flag { 126 | argFound = true 127 | reflect.ValueOf(opts).Elem().Field(i).SetBool(state) 128 | break 129 | } 130 | } 131 | 132 | if !argFound { 133 | log.Fatalf("unknown flag %s", arg) 134 | } 135 | } 136 | } 137 | } 138 | 139 | // SetDefaultTrueBools enables boolean flags that are true by default 140 | func SetDefaultTrueBools(opts *Flags) { 141 | v := reflect.Indirect(reflect.ValueOf(opts)) 142 | vT := v.Type() 143 | for i := 0; i < v.NumField(); i++ { 144 | defaultTrue := strings.Contains(vT.Field(i).Tag.Get("description"), "default: true") 145 | if vT.Field(i).Type == reflect.TypeOf(true) && defaultTrue { 146 | reflect.ValueOf(opts).Elem().Field(i).SetBool(true) 147 | } 148 | } 149 | } 150 | 151 | // SetFalseBooleans sets boolean flags to false from a given argument list and returns the remaining arguments 152 | func SetFalseBooleans(opts *Flags, args []string) []string { 153 | // Add equal signs to separated flags (e.g. --foo bar becomes --foo=bar) 154 | for i, arg := range args { 155 | if len(arg) > 0 && arg[0] == '-' && !strings.Contains(arg, "=") && i+1 < len(args) && (args[i+1] == "true" || args[i+1] == "false") { 156 | args[i] = arg + "=" + args[i+1] 157 | args = append(args[:i+1], args[i+2:]...) 158 | } 159 | } 160 | 161 | var remainingArgs []string 162 | for _, arg := range args { 163 | if strings.HasSuffix(arg, "=true") || strings.HasSuffix(arg, "=false") { 164 | flag := strings.ToLower(strings.TrimLeft(arg, "-")) 165 | flag = strings.TrimSuffix(flag, "=true") 166 | flag = strings.TrimSuffix(flag, "=false") 167 | 168 | v := reflect.Indirect(reflect.ValueOf(opts)) 169 | vT := v.Type() 170 | for i := 0; i < v.NumField(); i++ { 171 | if vT.Field(i).Type == reflect.TypeOf(true) && (vT.Field(i).Tag.Get("long") == flag || vT.Field(i).Tag.Get("short") == flag) { 172 | boolState := strings.HasSuffix(arg, "=true") 173 | // log.Debugf("Setting %s to %t", arg, boolState) 174 | reflect.ValueOf(opts).Elem().Field(i).SetBool(boolState) 175 | break 176 | } 177 | } 178 | } else { 179 | remainingArgs = append(remainingArgs, arg) 180 | } 181 | } 182 | 183 | // log.Debugf("remaining args: %v", remainingArgs) 184 | return remainingArgs 185 | } 186 | 187 | // ParseRRTypes parses a list of RR types in string format ("A", "AAAA", etc.) or integer format (1, 28, etc.) 188 | func ParseRRTypes(t []string) (map[uint16]bool, error) { 189 | rrTypes := make(map[uint16]bool, len(t)) 190 | for _, rrType := range t { 191 | // Check for TYPE notation 192 | if strings.HasPrefix(strings.ToUpper(rrType), "TYPE") { 193 | typeStr := strings.TrimPrefix(strings.ToUpper(rrType), "TYPE") 194 | typeCode, err := strconv.Atoi(typeStr) 195 | if err != nil { 196 | return nil, fmt.Errorf("%s is not a valid RR type", rrType) 197 | } 198 | log.Debugf("using RR type %d from TYPE notation", typeCode) 199 | rrTypes[uint16(typeCode)] = true 200 | continue 201 | } 202 | 203 | typeCode, ok := dns.StringToType[strings.ToUpper(rrType)] 204 | if ok { 205 | rrTypes[typeCode] = true 206 | } else { 207 | typeCode, err := strconv.Atoi(rrType) 208 | if err != nil { 209 | return nil, fmt.Errorf("%s is not a valid RR type", rrType) 210 | } 211 | log.Debugf("using RR type %d as integer", typeCode) 212 | rrTypes[uint16(typeCode)] = true 213 | } 214 | } 215 | return rrTypes, nil 216 | } 217 | 218 | // isBool checks if a flag by a given name is a boolean flag of Flags 219 | func isBool(name string) bool { 220 | v := reflect.ValueOf(Flags{}) 221 | vT := v.Type() 222 | for i := 0; i < v.NumField(); i++ { 223 | if vT.Field(i).Tag.Get("short") == name || vT.Field(i).Tag.Get("long") == name { 224 | return vT.Field(i).Type == reflect.TypeOf(true) 225 | } 226 | } 227 | return false 228 | } 229 | 230 | // AddEqualSigns adds equal signs between long flags and their values, ignoring boolean flags 231 | func AddEqualSigns(args []string) []string { 232 | var newArgs []string 233 | skip := false 234 | for i, arg := range args { 235 | if skip { 236 | skip = false 237 | continue 238 | } 239 | 240 | // Skip flags that already have an equal sign (e.g. --server=1.2.3.4) 241 | if strings.Contains(arg, "=") { 242 | newArgs = append(newArgs, arg) 243 | continue 244 | } 245 | 246 | // Only process long flags (starting with --) 247 | isLongFlag := strings.HasPrefix(arg, "--") 248 | if isLongFlag { 249 | flagName := strings.TrimLeft(arg, "-") 250 | if isBool(flagName) { 251 | newArgs = append(newArgs, arg) 252 | } else { 253 | if i+1 < len(args) { 254 | nextArg := args[i+1] 255 | // Skip if the next argument is a server specified with @ 256 | if len(nextArg) > 0 && nextArg[0] == '@' { 257 | newArgs = append(newArgs, arg) 258 | continue 259 | } 260 | 261 | // If the next argument is a value (not a flag), combine them 262 | if len(nextArg) == 0 || nextArg[0] != '-' { 263 | newArgs = append(newArgs, arg+"="+nextArg) 264 | skip = true 265 | } else { 266 | newArgs = append(newArgs, arg) 267 | } 268 | } else { 269 | newArgs = append(newArgs, arg) 270 | } 271 | } 272 | } else { 273 | // Pass short flags and other arguments through unchanged 274 | newArgs = append(newArgs, arg) 275 | } 276 | } 277 | return newArgs 278 | } 279 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "crypto/tls" 6 | "fmt" 7 | "io" 8 | "net" 9 | "net/url" 10 | "os" 11 | "regexp" 12 | "slices" 13 | "strings" 14 | "time" 15 | 16 | "github.com/charmbracelet/log" 17 | "github.com/jedisct1/go-dnsstamps" 18 | "github.com/jessevdk/go-flags" 19 | "github.com/miekg/dns" 20 | "golang.org/x/net/idna" 21 | 22 | "github.com/natesales/q/cli" 23 | "github.com/natesales/q/output" 24 | "github.com/natesales/q/transport" 25 | "github.com/natesales/q/util" 26 | tlsutil "github.com/natesales/q/util/tls" 27 | ) 28 | 29 | const defaultServerVar = "Q_DEFAULT_SERVER" 30 | 31 | var opts = cli.Flags{} 32 | 33 | // Build process flags 34 | var ( 35 | version = "dev" 36 | commit = "unknown" 37 | date = "unknown" 38 | ) 39 | 40 | // clearOpts sets the default values for the CLI options 41 | func clearOpts() { 42 | opts = cli.Flags{} 43 | cli.SetDefaultTrueBools(&opts) 44 | 45 | // Enable color output if stdout is a terminal 46 | if fileInfo, _ := os.Stdout.Stat(); (fileInfo.Mode() & os.ModeCharDevice) != 0 { 47 | opts.Color = true 48 | } 49 | 50 | // Disable color output if NO_COLOR env var is set 51 | if os.Getenv("NO_COLOR") != "" { 52 | log.Debug("NO_COLOR set") 53 | opts.Color = false 54 | } 55 | util.UseColor = opts.Color 56 | } 57 | 58 | func txtConcat(m *dns.Msg) { 59 | var answers []dns.RR 60 | for _, answer := range m.Answer { 61 | if answer.Header().Rrtype == dns.TypeTXT { 62 | txt := answer.(*dns.TXT) 63 | 64 | // Concat TXT responses if requested 65 | if opts.TXTConcat { 66 | log.Debugf("Concatenating TXT response: %+v", txt.Txt) 67 | txt.Txt = []string{strings.Join(txt.Txt, "")} 68 | } 69 | answers = append(answers, txt) 70 | } else { 71 | answers = append(answers, answer) 72 | } 73 | } 74 | m.Answer = answers 75 | } 76 | 77 | // dnsStampToURL converts a DNS stamp string to a URL string 78 | func dnsStampToURL(s string) (string, error) { 79 | var u url.URL 80 | 81 | parsedStamp, err := dnsstamps.NewServerStampFromString(s) 82 | if err != nil { 83 | return "", err 84 | } 85 | 86 | switch parsedStamp.Proto { 87 | case dnsstamps.StampProtoTypePlain: 88 | u.Scheme = string(transport.TypePlain) 89 | case dnsstamps.StampProtoTypeTLS: 90 | u.Scheme = string(transport.TypeTLS) 91 | case dnsstamps.StampProtoTypeDoH: 92 | u.Scheme = string(transport.TypeHTTP) + "s" // default to HTTPS 93 | case dnsstamps.StampProtoTypeDNSCrypt: 94 | // DNS stamp parsing happens again in the DNSCrypt transport, so pass the input along unchanged 95 | return s, nil 96 | default: 97 | return "", fmt.Errorf("unsupported protocol %s in DNS stamp", parsedStamp.Proto.String()) 98 | } 99 | 100 | // TODO: This might be a source of problems...we might want to be using parsedStamp.ServerAddrStr 101 | u.Host = parsedStamp.ProviderName 102 | u.Path = parsedStamp.Path 103 | 104 | // log.Tracef("DNS stamp parsed into URL as %s", u.String()) 105 | return u.String(), nil 106 | } 107 | 108 | // setPort sets the port of a url.URL 109 | func setPort(u *url.URL, port int) { 110 | if strings.Contains(u.Host, ":") { 111 | if strings.Contains(u.Host, "[") && strings.Contains(u.Host, "]") { 112 | u.Host = fmt.Sprintf("%s]:%d", strings.Split(u.Host, "]")[0], port) 113 | return 114 | } 115 | u.Host = "[" + u.Host + "]" 116 | } 117 | u.Host = fmt.Sprintf("%s:%d", u.Host, port) 118 | } 119 | 120 | // parseServer is a revised version of parseServer that uses the URL package for parsing 121 | func parseServer(s string) (string, transport.Type, error) { 122 | // Remove IPv6 scope ID if present 123 | var scopeId string 124 | v6scopeRe := regexp.MustCompile(`(^|\[)[a-fA-F0-9:]+%[a-zA-Z0-9]+`) 125 | if v6scopeRe.MatchString(s) { 126 | v6scopeRemoveRe := regexp.MustCompile(`(%[a-zA-Z0-9]+)`) 127 | matches := v6scopeRemoveRe.FindStringSubmatch(s) 128 | if len(matches) > 1 { 129 | scopeId = matches[1] 130 | s = v6scopeRemoveRe.ReplaceAllString(s, "") 131 | } 132 | log.Debug("Removed IPv6 scope ID %s from server %s", scopeId, s) 133 | } 134 | 135 | // Handle DNS stamp 136 | if strings.HasPrefix(s, "sdns://") { 137 | var err error 138 | s, err = dnsStampToURL(s) 139 | if err != nil { 140 | return "", "", fmt.Errorf("converting DNS stamp to URL: %s", err) 141 | } 142 | // If s is still a DNS stamp, it's DNSCrypt 143 | if strings.HasPrefix(s, "sdns://") { 144 | return s, transport.TypeDNSCrypt, nil 145 | } 146 | } 147 | 148 | // Check if server starts with a scheme, if not, default to plain 149 | schemeRe := regexp.MustCompile(`^[a-zA-Z0-9]+://`) 150 | if !schemeRe.MatchString(s) { 151 | // Enclose in brackets if IPv6 152 | v6re := regexp.MustCompile(`^[a-fA-F0-9:]+$`) 153 | if v6re.MatchString(s) { 154 | s = "[" + s + "]" 155 | } 156 | s = "plain://" + s 157 | } 158 | 159 | // Parse server as URL 160 | tu, err := url.Parse(s) 161 | if err != nil { 162 | return "", "", fmt.Errorf("parsing %s as URL: %s", s, err) 163 | } 164 | 165 | // Parse transport type 166 | ts := transport.Type(tu.Scheme) 167 | if tu.Scheme == "https" { // Override HTTPS to HTTP, preserving tu.Scheme as HTTPS 168 | ts = transport.TypeHTTP 169 | } 170 | if !slices.Contains(transport.Types, ts) { 171 | return "", "", fmt.Errorf("unsupported transport %s. expected: %+v", ts, transport.Types) 172 | } 173 | 174 | // Set default port 175 | if tu.Port() == "" { 176 | switch ts { 177 | case transport.TypeQUIC, transport.TypeTLS: 178 | setPort(tu, 853) 179 | case transport.TypeHTTP: 180 | if tu.Scheme == "https" { 181 | setPort(tu, 443) 182 | } else { 183 | setPort(tu, 80) 184 | } 185 | case transport.TypePlain, transport.TypeTCP: 186 | setPort(tu, 53) 187 | } 188 | } 189 | 190 | // Add default path if missing 191 | if ts == transport.TypeHTTP && tu.Path == "" { 192 | tu.Path = "/dns-query" 193 | } 194 | 195 | server := tu.String() 196 | // Remove scheme from server if irrelevant to protocol 197 | if ts != transport.TypeHTTP { 198 | server = strings.Split(server, "://")[1] 199 | } 200 | 201 | // Add IPv6 scope ID back to server 202 | if scopeId != "" { 203 | server = strings.Replace(server, "]", scopeId+"]", 1) 204 | } 205 | 206 | return server, ts, nil 207 | } 208 | 209 | // driver is the "main" function for this program that accepts a flag slice for testing 210 | func driver(args []string, out io.Writer) error { 211 | args = cli.SetFalseBooleans(&opts, args) 212 | args = cli.AddEqualSigns(args) 213 | parser := flags.NewParser(&opts, flags.Default) 214 | parser.Usage = `[OPTIONS] [@server] [type...] [name] 215 | 216 | All long form (--) flags can be toggled with the dig-standard +[no]flag notation.` 217 | _, err := parser.ParseArgs(args) 218 | if err != nil { 219 | if !strings.Contains(err.Error(), "Usage") { 220 | log.Fatal(err) 221 | } 222 | os.Exit(1) 223 | } 224 | cli.ParsePlusFlags(&opts, args) 225 | util.UseColor = opts.Color 226 | 227 | log.SetReportTimestamp(false) 228 | 229 | if opts.Verbose { 230 | log.SetLevel(log.DebugLevel) 231 | } else if opts.Trace { 232 | log.SetLevel(log.DebugLevel) 233 | opts.ShowAll = true 234 | } 235 | 236 | if opts.ShowVersion { 237 | util.MustWritef(out, "https://github.com/natesales/q version %s (%s %s)\n", version, commit, date) 238 | return nil 239 | } 240 | 241 | if opts.ShowAll { 242 | opts.ShowQuestion = true 243 | opts.ShowAnswer = true 244 | opts.ShowAuthority = true 245 | opts.ShowAdditional = true 246 | opts.ShowStats = true 247 | } 248 | 249 | // Set bootstrap resolver 250 | if opts.BootstrapServer != "" { 251 | // Add port if not specified 252 | rePortSuffix := regexp.MustCompile(`:\d+$`) 253 | if !rePortSuffix.MatchString(opts.BootstrapServer) { 254 | opts.BootstrapServer += ":53" 255 | } 256 | 257 | net.DefaultResolver = &net.Resolver{ 258 | PreferGo: true, 259 | Dial: func(ctx context.Context, network, address string) (net.Conn, error) { 260 | d := net.Dialer{Timeout: opts.BootstrapTimeout} 261 | return d.DialContext(ctx, network, opts.BootstrapServer) 262 | }, 263 | } 264 | 265 | log.Debugf("Using bootstrap resolver %s", opts.BootstrapServer) 266 | } 267 | 268 | // Parse requested RR types 269 | rrTypes, err := cli.ParseRRTypes(opts.Types) 270 | if err != nil { 271 | return err 272 | } 273 | 274 | // Add non-flag RR types 275 | for _, arg := range args { 276 | // Find a server by @ symbol if it isn't set by flag 277 | if strings.HasPrefix(arg, "@") { 278 | opts.Server = append(opts.Server, strings.TrimPrefix(arg, "@")) 279 | } 280 | 281 | // Parse chaos class 282 | if strings.ToLower(arg) == "ch" { 283 | opts.Chaos = true 284 | } 285 | 286 | // Add non-flag RR types 287 | rrType, typeFound := dns.StringToType[strings.ToUpper(arg)] 288 | if typeFound { 289 | rrTypes[rrType] = true 290 | if rrType == dns.TypeNS { 291 | opts.ShowAuthority = true 292 | opts.ShowAdditional = true 293 | } 294 | } 295 | 296 | // Set qname if not set by flag 297 | if opts.Name == "" && 298 | !util.ContainsAny(arg, []string{"@", "/", "\\", "+"}) && // Not a server, path, or flag 299 | !typeFound && // Not a RR type 300 | !strings.HasSuffix(arg, ".exe") && // Not an executable 301 | !strings.HasPrefix(arg, "-") { // Not a flag 302 | opts.Name = arg 303 | } 304 | } 305 | 306 | // If no RR types are defined, set a list of default ones 307 | if len(rrTypes) < 1 { 308 | if opts.Name == "" { 309 | rrTypes[dns.StringToType["NS"]] = true 310 | } else { 311 | for _, defaultRRType := range opts.DefaultRRTypes { 312 | rrTypes[dns.StringToType[defaultRRType]] = true 313 | } 314 | } 315 | } 316 | 317 | // Reverse address if required 318 | if opts.Reverse { 319 | opts.Name, err = dns.ReverseAddr(opts.Name) 320 | if err != nil { 321 | return fmt.Errorf("dns reverse: %s", err) 322 | } 323 | rrTypes[dns.StringToType["PTR"]] = true 324 | } 325 | 326 | // IDNA (punycode) normalize non-ASCII domain names unless reverse lookup 327 | if opts.Name != "" && !opts.Reverse { 328 | // Skip if already an in-addr.arpa or ip6.arpa name 329 | lowerName := strings.ToLower(opts.Name) 330 | if !strings.HasSuffix(lowerName, ".in-addr.arpa") && !strings.HasSuffix(lowerName, ".ip6.arpa") { 331 | // Use a custom IDNA profile to allow underscores (non-LDH characters). 332 | // Standard IDNA Lookup enforces STD3 rules which forbid underscores, 333 | // but they are valid in DNS records (e.g. TXT, SRV). 334 | p := idna.New( 335 | idna.MapForLookup(), 336 | idna.StrictDomainName(false), 337 | ) 338 | 339 | asciiName, err := p.ToASCII(opts.Name) 340 | if err != nil { 341 | return fmt.Errorf("idna toascii: %s", err) 342 | } 343 | opts.Name = asciiName 344 | } 345 | } 346 | 347 | // Log RR types 348 | if opts.Verbose { 349 | log.Debugf("Name: %s", opts.Name) 350 | var rrTypeStrings []string 351 | for rrType := range rrTypes { 352 | rrS, ok := dns.TypeToString[rrType] 353 | if !ok { 354 | rrS = fmt.Sprintf("TYPE%d", rrType) 355 | } 356 | rrTypeStrings = append(rrTypeStrings, rrS) 357 | } 358 | log.Debugf("RR types: %+v", rrTypeStrings) 359 | } 360 | 361 | // Set default DNS server 362 | if len(opts.Server) == 0 { 363 | opts.Server = make([]string, 1) 364 | 365 | if os.Getenv(defaultServerVar) != "" { 366 | opts.Server[0] = os.Getenv(defaultServerVar) 367 | log.Debugf("Using %s from %s environment variable", opts.Server, defaultServerVar) 368 | } else { 369 | log.Debugf("No server specified or %s set, using /etc/resolv.conf", defaultServerVar) 370 | conf, err := dns.ClientConfigFromFile("/etc/resolv.conf") 371 | if err != nil { 372 | opts.Server[0] = "https://cloudflare-dns.com/dns-query" 373 | log.Debugf("no server set, using %s", opts.Server) 374 | } else { 375 | if len(conf.Servers) == 0 { 376 | opts.Server[0] = "https://cloudflare-dns.com/dns-query" 377 | log.Debugf("no server set, using %s", opts.Server) 378 | } else { 379 | opts.Server[0] = conf.Servers[0] 380 | log.Debugf("found server %s from /etc/resolv.conf", opts.Server) 381 | } 382 | } 383 | } 384 | } 385 | 386 | // Validate ODoH 387 | if opts.ODoHProxy != "" { 388 | if !strings.HasPrefix(opts.ODoHProxy, "https://") { 389 | return fmt.Errorf("ODoH proxy must use HTTPS") 390 | } 391 | for _, server := range opts.Server { 392 | if !strings.HasPrefix(server, "https://") { 393 | return fmt.Errorf("ODoH target must use HTTPS") 394 | } 395 | } 396 | } 397 | 398 | log.Debugf("Server(s): %s", opts.Server) 399 | 400 | if opts.Chaos { 401 | log.Debug("Flag set, using chaos class") 402 | opts.Class = dns.ClassCHAOS 403 | } 404 | 405 | if opts.NSIDOnly { 406 | opts.NSID = true 407 | } 408 | 409 | // Create TLS config 410 | tlsConfig := &tls.Config{ 411 | InsecureSkipVerify: opts.TLSInsecureSkipVerify, 412 | ServerName: opts.TLSServerName, 413 | MinVersion: tlsutil.Version(opts.TLSMinVersion, tls.VersionTLS10), 414 | MaxVersion: tlsutil.Version(opts.TLSMaxVersion, tls.VersionTLS13), 415 | NextProtos: opts.TLSNextProtos, 416 | CipherSuites: tlsutil.ParseCipherSuites(opts.TLSCipherSuites), 417 | CurvePreferences: tlsutil.ParseCurves(opts.TLSCurvePreferences), 418 | } 419 | 420 | // TLS client certificate authentication 421 | if opts.TLSClientCertificate != "" { 422 | cert, err := tls.LoadX509KeyPair(opts.TLSClientCertificate, opts.TLSClientKey) 423 | if err != nil { 424 | return fmt.Errorf("unable to load client certificate: %s", err) 425 | } 426 | tlsConfig.Certificates = []tls.Certificate{cert} 427 | } 428 | 429 | // TLS secret logging 430 | if opts.TLSKeyLogFile != "" { 431 | log.Warnf("TLS secret logging enabled") 432 | keyLogFile, err := os.OpenFile(opts.TLSKeyLogFile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666) 433 | if err != nil { 434 | return fmt.Errorf("unable to open TLS key log file: %s", err) 435 | } 436 | tlsConfig.KeyLogWriter = keyLogFile 437 | } 438 | 439 | var rrTypesSlice []uint16 440 | for rrType := range rrTypes { 441 | rrTypesSlice = append(rrTypesSlice, rrType) 442 | } 443 | msgs := createQuery(opts, rrTypesSlice) 444 | 445 | errChan := make(chan error) 446 | 447 | go func() { 448 | var entries []*output.Entry 449 | multiServer := len(opts.Server) > 1 450 | for _, serverStr := range opts.Server { 451 | // Parse server address and transport type 452 | server, transportType, err := parseServer(serverStr) 453 | if err != nil { 454 | if multiServer { 455 | log.Warnf("Skipping server %s: %v", serverStr, err) 456 | continue 457 | } 458 | errChan <- fmt.Errorf("parsing server %s: %s", serverStr, err) 459 | return 460 | } 461 | log.Debugf("Using server %s with transport %s", server, transportType) 462 | 463 | // Recursive zone transfer 464 | if opts.RecAXFR { 465 | if opts.Name == "" { 466 | errChan <- fmt.Errorf("no name specified for AXFR") 467 | return 468 | } 469 | _ = RecAXFR(opts.Name, server, out) 470 | errChan <- nil // exit immediately 471 | return 472 | } 473 | 474 | // Create transport 475 | txp, err := newTransport(server, transportType, tlsConfig) 476 | if err != nil { 477 | if multiServer { 478 | log.Warnf("Skipping server %s (transport error): %v", server, err) 479 | continue 480 | } 481 | errChan <- fmt.Errorf("creating transport: %s", err) 482 | return 483 | } 484 | 485 | startTime := time.Now() 486 | var replies []*dns.Msg 487 | var serverFailed error 488 | for _, msg := range msgs { 489 | if txp == nil { 490 | serverFailed = fmt.Errorf("transport is nil") 491 | break 492 | } 493 | reply, err := (*txp).Exchange(&msg) 494 | if err != nil { 495 | serverFailed = fmt.Errorf("exchange: %s", err) 496 | break 497 | } 498 | 499 | if reply == nil { 500 | serverFailed = fmt.Errorf("no reply from server") 501 | break 502 | } 503 | 504 | if opts.ShowOpt { 505 | for _, o := range reply.Extra { 506 | if o.Header().Rrtype == dns.TypeOPT { 507 | fmt.Printf("OPT: %v\n", o) 508 | } 509 | } 510 | } 511 | 512 | if transportType != transport.TypeQUIC && opts.IDCheck && reply.Id != msg.Id { 513 | serverFailed = fmt.Errorf("ID mismatch: expected %d, got %d", msg.Id, reply.Id) 514 | break 515 | } 516 | replies = append(replies, reply) 517 | } 518 | 519 | // If this server failed at any point, either skip (multi) or exit (single) 520 | if serverFailed != nil { 521 | _ = (*txp).Close() 522 | if multiServer { 523 | log.Warnf("Server %s failed: %v", server, serverFailed) 524 | continue 525 | } 526 | errChan <- serverFailed 527 | return 528 | } 529 | 530 | // Process TXT parsing 531 | if opts.TXTConcat { 532 | for _, reply := range replies { 533 | txtConcat(reply) 534 | } 535 | } 536 | 537 | // Round TTL 538 | if opts.RoundTTLs { 539 | for _, reply := range replies { 540 | for _, rr := range reply.Answer { 541 | rr.Header().Ttl = rr.Header().Ttl - (rr.Header().Ttl % 60) 542 | } 543 | } 544 | } 545 | 546 | e := &output.Entry{ 547 | Queries: msgs, 548 | Replies: replies, 549 | Server: server, 550 | Time: time.Since(startTime), 551 | } 552 | 553 | if opts.ResolveIPs { 554 | e.LoadPTRs(txp) 555 | } 556 | 557 | entries = append(entries, e) 558 | 559 | if err := (*txp).Close(); err != nil { 560 | if multiServer { 561 | log.Warnf("Server %s close error: %v", server, err) 562 | } else { 563 | errChan <- fmt.Errorf("closing transport: %s", err) 564 | return 565 | } 566 | } 567 | } 568 | 569 | // If none of the servers succeeded, return an error in multi-server mode 570 | if len(entries) == 0 { 571 | errChan <- fmt.Errorf("all servers failed") 572 | return 573 | } 574 | 575 | printer := output.Printer{ 576 | Out: out, 577 | Opts: &opts, 578 | } 579 | 580 | if (opts.NSID && (opts.Format == output.FormatPretty || opts.Format == output.FormatColumn)) || opts.NSIDOnly { 581 | printer.PrettyPrintNSID(entries, !opts.NSIDOnly) 582 | } 583 | 584 | // Skip printing if NSIDOnly is set 585 | if opts.NSIDOnly { 586 | errChan <- nil 587 | return 588 | } 589 | 590 | switch opts.Format { 591 | case output.FormatPretty: 592 | printer.PrintPretty(entries) 593 | case output.FormatColumn: 594 | printer.PrintColumn(entries) 595 | case output.FormatRAW: 596 | printer.PrintRaw(entries) 597 | case output.FormatJSON, output.FormatYAML, "yml": 598 | printer.PrintStructured(entries) 599 | default: 600 | errChan <- fmt.Errorf("invalid output format %s", opts.Format) 601 | return 602 | } 603 | 604 | errChan <- nil 605 | }() 606 | 607 | // When multiple servers are configured, queries are attempted sequentially. 608 | // Give the worker goroutine enough time to iterate through all servers by 609 | // scaling the overall timeout proportionally. This prevents the controller 610 | // from timing out before a later server succeeds. 611 | totalTimeout := opts.Timeout 612 | if len(opts.Server) > 1 { 613 | totalTimeout = opts.Timeout * time.Duration(len(opts.Server)) 614 | } 615 | 616 | select { 617 | case <-time.After(totalTimeout): 618 | return fmt.Errorf("timeout after %s", totalTimeout) 619 | case err := <-errChan: 620 | return err 621 | } 622 | } 623 | 624 | func main() { 625 | clearOpts() 626 | if err := driver(os.Args[1:], os.Stdout); err != nil { 627 | log.Fatal(err) 628 | } 629 | } 630 | -------------------------------------------------------------------------------- /main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "os" 6 | "path/filepath" 7 | "regexp" 8 | "strings" 9 | "testing" 10 | 11 | "github.com/stretchr/testify/assert" 12 | "golang.org/x/net/idna" 13 | 14 | "github.com/natesales/q/cli" 15 | "github.com/natesales/q/transport" 16 | ) 17 | 18 | func run(args ...string) (*bytes.Buffer, error) { 19 | clearOpts() 20 | var out bytes.Buffer 21 | err := driver(append([]string{"+nocolor"}, args...), &out) 22 | return &out, err 23 | } 24 | 25 | func TestMainQuery(t *testing.T) { 26 | out, err := run( 27 | "--all", 28 | "-q", "example.com", 29 | ) 30 | assert.Nil(t, err) 31 | assert.Regexp(t, regexp.MustCompile(`example.com. .* TXT "v=spf1 -all"`), out.String()) 32 | } 33 | 34 | func TestMainVersion(t *testing.T) { 35 | out, err := run("-V") 36 | assert.Nil(t, err) 37 | assert.Contains(t, out.String(), "https://github.com/natesales/q version dev (unknown unknown)") 38 | } 39 | 40 | // TODO 41 | //func TestMainODoHQuery(t *testing.T) { 42 | // out, err := run( 43 | // "--all", 44 | // "-q", "example.com", 45 | // "-s", "https://odoh.cloudflare-dns.com", 46 | // "--odoh-proxy", "https://odoh.crypto.sx", 47 | // ) 48 | // assert.Nil(t, err) 49 | // assert.Regexp(t, regexp.MustCompile(`example.com. .* TXT "v=spf1 -all"`), out.String()) 50 | //} 51 | 52 | func TestMainRawFormat(t *testing.T) { 53 | out, err := run( 54 | "--all", 55 | "-q", "example.com", 56 | "--format=raw", 57 | ) 58 | assert.Nil(t, err) 59 | assert.Contains(t, out.String(), "v=spf1 -all") 60 | assert.Contains(t, out.String(), "a.iana-servers.net") 61 | } 62 | 63 | func TestMainJSONFormat(t *testing.T) { 64 | out, err := run( 65 | "--all", 66 | "-q", "example.com", 67 | "--format=json", 68 | ) 69 | assert.Nil(t, err) 70 | o := strings.ReplaceAll(out.String(), `\\"`, `"`) 71 | assert.Contains(t, o, `"preference":0,"mx":"."`) 72 | assert.Contains(t, o, `"ns":"a.iana-servers.net."`) 73 | assert.Contains(t, o, `"txt":["v=spf1 -all"`) 74 | } 75 | 76 | func TestMainIDNAQuery(t *testing.T) { 77 | out, err := run( 78 | "--all", 79 | "-q", "www.饭太硬.com", 80 | "-t", "A", 81 | ) 82 | assert.Nil(t, err) 83 | ascii, err := idna.Lookup.ToASCII("www.饭太硬.com") 84 | assert.Nil(t, err) 85 | re := regexp.MustCompile(regexp.QuoteMeta(ascii + ".")) 86 | assert.Regexp(t, re, out.String()) 87 | } 88 | 89 | func TestMainInvalidOutputFormat(t *testing.T) { 90 | _, err := run( 91 | "--all", 92 | "-q", "example.com", 93 | "--format=invalid", 94 | ) 95 | if !(err != nil && strings.Contains(err.Error(), "invalid output format")) { 96 | t.Errorf("invalid output format should throw an error") 97 | } 98 | } 99 | 100 | func TestMainParseTypes(t *testing.T) { 101 | out, err := run( 102 | "--all", 103 | "-q", "example.com", 104 | "-t", "A", 105 | "-t", "AAAA", 106 | ) 107 | assert.Nil(t, err) 108 | assert.Regexp(t, regexp.MustCompile(`example.com. .* A .*`), out.String()) 109 | assert.Regexp(t, regexp.MustCompile(`example.com. .* AAAA .*`), out.String()) 110 | } 111 | 112 | func TestMainInvalidTypes(t *testing.T) { 113 | _, err := run( 114 | "--all", 115 | "-q", "example.com", 116 | "-t", "INVALID", 117 | ) 118 | if !(err != nil && strings.Contains(err.Error(), "INVALID is not a valid RR type")) { 119 | t.Errorf("expected invalid type error, got %+v", err) 120 | } 121 | } 122 | 123 | func TestMainInvalidODoHUpstream(t *testing.T) { 124 | _, err := run( 125 | "--all", 126 | "-q", "example.com", 127 | "-s", "tls://odoh.cloudflare-dns.com", 128 | "--odoh-proxy", "https://odoh.crypto.sx", 129 | ) 130 | assert.NotNil(t, err) 131 | assert.Contains(t, err.Error(), "ODoH target must use HTTPS") 132 | } 133 | 134 | func TestMainInvalidODoHProxy(t *testing.T) { 135 | _, err := run( 136 | "--all", 137 | "-q", "example.com", 138 | "-s", "https://odoh.cloudflare-dns.com", 139 | "--odoh-proxy", "tls://odoh1.surfdomeinen.nl", 140 | ) 141 | assert.NotNil(t, err) 142 | assert.Contains(t, err.Error(), "ODoH proxy must use HTTPS") 143 | } 144 | 145 | func TestMainReverseQuery(t *testing.T) { 146 | out, err := run( 147 | "--all", 148 | "-x", 149 | "-q", "1.1.1.1", 150 | ) 151 | assert.Nil(t, err) 152 | assert.Regexp(t, regexp.MustCompile(`1.1.1.1.in-addr.arpa. .* PTR one.one.one.one`), out.String()) 153 | } 154 | 155 | func TestMainInferredQname(t *testing.T) { 156 | out, err := run( 157 | "--all", 158 | "example.com", 159 | "A", 160 | ) 161 | assert.Nil(t, err) 162 | assert.Regexp(t, regexp.MustCompile(`example.com. .* A .*`), out.String()) 163 | } 164 | 165 | func TestMainInferredServer(t *testing.T) { 166 | out, err := run( 167 | "--all", 168 | "-q", "example.com", 169 | "@8.8.8.8", 170 | "-t", "A", 171 | ) 172 | assert.Nil(t, err) 173 | assert.Regexp(t, regexp.MustCompile(`example.com. .* A .*`), out.String()) 174 | } 175 | 176 | func TestMainInvalidReverseQuery(t *testing.T) { 177 | _, err := run( 178 | "--all", 179 | "-x", 180 | "example.com", 181 | ) 182 | if !(err != nil && strings.Contains(err.Error(), "unrecognized address: example.com")) { 183 | t.Errorf("expected address error, got %+v", err) 184 | } 185 | } 186 | 187 | func TestMainInvalidUpstream(t *testing.T) { 188 | _, err := run( 189 | "--all", 190 | "-s", "127.127.127.127:1", 191 | "--timeout", "2s", 192 | "example.com", 193 | ) 194 | 195 | expectedErrors := []string{"connection refused", "i/o timeout", "timeout after"} 196 | foundErr := false 197 | for _, expectedError := range expectedErrors { 198 | if strings.Contains(err.Error(), expectedError) { 199 | foundErr = true 200 | break 201 | } 202 | } 203 | assert.Truef(t, foundErr, "expected connection error, got: %+v", err) 204 | } 205 | 206 | func TestMainDNSSECArg(t *testing.T) { 207 | out, err := run( 208 | "--all", 209 | "example.com", 210 | "+dnssec", 211 | "@9.9.9.9", 212 | ) 213 | assert.Nil(t, err) 214 | assert.Regexp(t, regexp.MustCompile(`example.com. .* RRSIG .*`), out.String()) 215 | } 216 | 217 | func TestMainPad(t *testing.T) { 218 | out, err := run( 219 | "--all", 220 | "-q", "example.com", 221 | "--pad", 222 | "--format=json", 223 | ) 224 | assert.Nil(t, err) 225 | o := strings.ReplaceAll(out.String(), `\\"`, `"`) 226 | assert.Contains(t, o, `"truncated":false`) 227 | } 228 | 229 | func TestMainChaosClass(t *testing.T) { 230 | out, err := run( 231 | "--all", 232 | "id.server", 233 | "CH", 234 | "TXT", 235 | "@9.9.9.9", 236 | ) 237 | assert.Nil(t, err) 238 | assert.Regexp(t, regexp.MustCompile(`id.server. .* TXT "res.*"`), out.String()) 239 | } 240 | 241 | func TestMainParsePlusFlags(t *testing.T) { 242 | cli.ParsePlusFlags(&opts, []string{"+dnssec", "+nord"}) 243 | assert.True(t, opts.DNSSEC) 244 | assert.False(t, opts.RecursionDesired) 245 | } 246 | 247 | func TestMainTCPQuery(t *testing.T) { 248 | out, err := run( 249 | "--all", 250 | "-t", "A", 251 | "-q", "example.com", 252 | "@tcp://1.1.1.1", 253 | ) 254 | assert.Nil(t, err) 255 | assert.Regexp(t, regexp.MustCompile(`example.com. .* A .*`), out.String()) 256 | } 257 | 258 | func TestMainTLSQuery(t *testing.T) { 259 | out, err := run( 260 | "--all", 261 | "-q", "example.com", 262 | "-t", "A", 263 | "@tls://1.1.1.1", 264 | ) 265 | assert.Nil(t, err) 266 | assert.Regexp(t, regexp.MustCompile(`example.com. .* A .*`), out.String()) 267 | } 268 | 269 | func TestMainHTTPSQuery(t *testing.T) { 270 | out, err := run( 271 | "--all", 272 | "-q", "example.com", 273 | "-t", "A", 274 | "@https://dns.quad9.net", 275 | ) 276 | assert.Nil(t, err) 277 | assert.Regexp(t, regexp.MustCompile(`example.com. .* A .*`), out.String()) 278 | } 279 | 280 | func TestMainQUICQuery(t *testing.T) { 281 | out, err := run( 282 | "--all", 283 | "-q", "example.com", 284 | "-t", "A", 285 | "@quic://dns.adguard.com", 286 | ) 287 | assert.Nil(t, err) 288 | assert.Regexp(t, regexp.MustCompile(`example.com. .* A .*`), out.String()) 289 | } 290 | 291 | func TestMainDNSCryptStampQuery(t *testing.T) { 292 | out, err := run( 293 | "-q", "example.com", 294 | "-t", "A", 295 | "@sdns://AQMAAAAAAAAAETk0LjE0MC4xNC4xNDo1NDQzINErR_JS3PLCu_iZEIbq95zkSV2LFsigxDIuUso_OQhzIjIuZG5zY3J5cHQuZGVmYXVsdC5uczEuYWRndWFyZC5jb20", 296 | ) 297 | assert.Nil(t, err) 298 | assert.Regexp(t, regexp.MustCompile(`example.com. .* A .*`), out.String()) 299 | } 300 | 301 | func TestMainDNSCryptManualQuery(t *testing.T) { 302 | out, err := run( 303 | "-q", "example.com", 304 | "-t", "A", 305 | "@dnscrypt://94.140.14.14:5443", 306 | "--dnscrypt-key", "d12b47f252dcf2c2bbf8991086eaf79ce4495d8b16c8a0c4322e52ca3f390873", 307 | "--dnscrypt-provider", "2.dnscrypt.default.ns1.adguard.com", 308 | ) 309 | assert.Nil(t, err) 310 | assert.Regexp(t, regexp.MustCompile(`example.com. .* A .*`), out.String()) 311 | } 312 | 313 | func TestMainTCPFallbackOnAuthoritative(t *testing.T) { 314 | out, err := run( 315 | "--all", 316 | "@ns47.domaincontrol.com", 317 | "TXT", 318 | "chordline.com", 319 | ) 320 | assert.Nil(t, err) 321 | assert.Regexp(t, regexp.MustCompile(`chordline.com\. .* TXT .*`), out.String()) 322 | } 323 | 324 | func TestMainInvalidServerURL(t *testing.T) { 325 | out, err := run( 326 | "--all", 327 | "-q", "example.com", 328 | "@bad::server::url", 329 | "--format=json", 330 | ) 331 | assert.NotNil(t, err) 332 | assert.NotRegexp(t, regexp.MustCompile(`example.com. .* A .*`), out.String()) 333 | } 334 | 335 | func TestMainInvalidTransportScheme(t *testing.T) { 336 | out, err := run( 337 | "--all", 338 | "-q", "example.com", 339 | "@invalid://example.com", 340 | "--format=json", 341 | ) 342 | assert.NotNil(t, err) 343 | assert.NotRegexp(t, regexp.MustCompile(`example.com. .* A .*`), out.String()) 344 | } 345 | 346 | func TestMainTLS12(t *testing.T) { 347 | out, err := run( 348 | "--all", 349 | "-q", "example.com", 350 | "--tls-min-version=1.1", 351 | "--tls-max-version=1.2", 352 | "@tls://dns.quad9.net", 353 | "-t", "A", 354 | ) 355 | assert.Nil(t, err) 356 | assert.Regexp(t, regexp.MustCompile(`example.com. .* A .*`), out.String()) 357 | } 358 | 359 | func TestMainNSID(t *testing.T) { 360 | out, err := run( 361 | "--all", 362 | "@9.9.9.9", 363 | "+nsid", 364 | ) 365 | assert.Nil(t, err) 366 | assert.Regexp(t, regexp.MustCompile(`NSID: .*`), out.String()) 367 | } 368 | 369 | func TestMainECSv4(t *testing.T) { 370 | out, err := run( 371 | "--all", 372 | "@script-ns.packetframe.com", 373 | "TXT", 374 | "query.script.packetframe.com", 375 | "--subnet", "192.0.2.0/24", 376 | ) 377 | assert.Nil(t, err) 378 | assert.Contains(t, out.String(), `'subnet':'192.0.2.0/24/0'`) 379 | } 380 | 381 | func TestMainECSv6(t *testing.T) { 382 | out, err := run( 383 | "--all", 384 | "@script-ns.packetframe.com", 385 | "TXT", 386 | "query.script.packetframe.com", 387 | "--subnet", "2001:db8::/48", 388 | ) 389 | assert.Nil(t, err) 390 | assert.Contains(t, out.String(), `'subnet':'[2001:db8::]/48/0'`) 391 | } 392 | 393 | func TestMainHTTPUserAgent(t *testing.T) { 394 | out, err := run( 395 | "--all", 396 | "@https://dns.quad9.net", 397 | "--http-user-agent", "Example/1.0", 398 | "-t", "NS", 399 | ) 400 | assert.Nil(t, err) 401 | assert.Regexp(t, regexp.MustCompile(`. .* NS a.root-servers.net.`), out.String()) 402 | } 403 | 404 | func TestMainParseServer(t *testing.T) { 405 | for _, tc := range []struct { 406 | Server string 407 | Type transport.Type 408 | ExpectedHost string 409 | }{ 410 | { // IPv4 plain with no port 411 | Server: "1.1.1.1", 412 | Type: transport.TypePlain, 413 | ExpectedHost: "1.1.1.1:53", 414 | }, 415 | { // IPv4 plain with explicit port 416 | Server: "1.1.1.1:5353", 417 | Type: transport.TypePlain, 418 | ExpectedHost: "1.1.1.1:5353", 419 | }, 420 | { // IPv6 plain with no port 421 | Server: "2a09::", 422 | Type: transport.TypePlain, 423 | ExpectedHost: "[2a09::]:53", 424 | }, 425 | { // IPv6 plain with explicit port 426 | Server: "[2a09::]:5353", 427 | Type: transport.TypePlain, 428 | ExpectedHost: "[2a09::]:5353", 429 | }, 430 | { // TLS with no port 431 | Server: "tls://dns.quad9.net", 432 | Type: transport.TypeTLS, 433 | ExpectedHost: "dns.quad9.net:853", 434 | }, 435 | { // TLS with explicit port 436 | Server: "tls://dns.quad9.net:8530", 437 | Type: transport.TypeTLS, 438 | ExpectedHost: "dns.quad9.net:8530", 439 | }, 440 | { // HTTPS with no endpoint 441 | Server: "https://dns.quad9.net", 442 | Type: transport.TypeHTTP, 443 | ExpectedHost: "https://dns.quad9.net:443/dns-query", 444 | }, 445 | { // HTTPS with IPv4 address 446 | Server: "https://1.1.1.1", 447 | Type: transport.TypeHTTP, 448 | ExpectedHost: "https://1.1.1.1:443/dns-query", 449 | }, 450 | { // TCP with no port 451 | Server: "tcp://dns.quad9.net", 452 | Type: transport.TypeTCP, 453 | ExpectedHost: "dns.quad9.net:53", 454 | }, 455 | { // HTTPS with IPv6 address 456 | Server: "https://2a09::", 457 | Type: transport.TypeHTTP, 458 | ExpectedHost: "https://[2a09::]:443/dns-query", 459 | }, 460 | { // HTTPS with explicit endpoint 461 | Server: "https://dns.quad9.net/other-dns-endpoint", 462 | Type: transport.TypeHTTP, 463 | ExpectedHost: "https://dns.quad9.net:443/other-dns-endpoint", 464 | }, 465 | { // QUIC with no port 466 | Server: "quic://dns.adguard.com", 467 | Type: transport.TypeQUIC, 468 | ExpectedHost: "dns.adguard.com:853", 469 | }, 470 | { // QUIC with explicit port 471 | Server: "quic://dns.adguard.com:8530", 472 | Type: transport.TypeQUIC, 473 | ExpectedHost: "dns.adguard.com:8530", 474 | }, 475 | { // IPv6 plain with scope ID but without port 476 | Server: "fe80::1%en0", 477 | Type: transport.TypePlain, 478 | ExpectedHost: "[fe80::1%en0]:53", 479 | }, 480 | { // IPv6 with scope ID and explicit port 481 | Server: "plain://[fe80::1%en0]:53", 482 | Type: transport.TypePlain, 483 | ExpectedHost: "[fe80::1%en0]:53", 484 | }, 485 | { // DNS Stamp 486 | Server: "sdns://AgcAAAAAAAAAAAAHOS45LjkuOQA", 487 | Type: transport.TypeHTTP, 488 | ExpectedHost: "https://9.9.9.9:443/dns-query", 489 | }, 490 | { // URL encoded path (https://github.com/natesales/q/issues/66) 491 | Server: "https://localhost/1%3A89%3D%3D%3A64fx", 492 | Type: transport.TypeHTTP, 493 | ExpectedHost: "https://localhost:443/1%3A89%3D%3D%3A64fx", 494 | }, 495 | { // Colons in URL path (https://github.com/natesales/q/issues/66) 496 | Server: "https://localhost/1:89==:64fx", 497 | Type: transport.TypeHTTP, 498 | ExpectedHost: "https://localhost:443/1:89==:64fx", 499 | }, 500 | { // Plain IPv6 address 501 | Server: "2001:db8:11:8340:dea6:32ff:fe5b:a19e", 502 | Type: transport.TypePlain, 503 | ExpectedHost: "[2001:db8:11:8340:dea6:32ff:fe5b:a19e]:53", 504 | }, 505 | } { 506 | t.Run(tc.Server, func(t *testing.T) { 507 | server, transportType, err := parseServer(tc.Server) 508 | assert.Nil(t, err) 509 | assert.Equal(t, tc.ExpectedHost, server) 510 | assert.Equal(t, tc.Type, transportType) 511 | }) 512 | } 513 | } 514 | 515 | func TestMainRecAXFR(t *testing.T) { 516 | out, err := run( 517 | "--all", 518 | "+recaxfr", 519 | "@nsztm1.digi.ninja", "zonetransfer.me", 520 | ) 521 | assert.Nil(t, err) 522 | assert.Contains(t, out.String(), `AXFR zonetransfer.me.`) 523 | assert.Contains(t, out.String(), `AXFR internal.zonetransfer.me.`) 524 | 525 | // Remove zonetransfer files 526 | files, err := filepath.Glob("zonetransfer.me*") 527 | assert.Nil(t, err) 528 | for _, f := range files { 529 | assert.Nil(t, os.RemoveAll(f)) 530 | } 531 | } 532 | 533 | func TestMainShowAll(t *testing.T) { 534 | out, err := run( 535 | "@9.9.9.9", 536 | "--all", 537 | "+all", 538 | "example.com", 539 | "A", 540 | ) 541 | assert.Nil(t, err) 542 | assert.Contains(t, out.String(), "example.com.") 543 | assert.Contains(t, out.String(), "Question:") 544 | assert.Contains(t, out.String(), "Answer:") 545 | assert.Contains(t, out.String(), "Stats:") 546 | } 547 | 548 | func TestMainResolveIPs(t *testing.T) { 549 | out, err := run( 550 | "core1.fmt2.he.net", 551 | "A", "AAAA", 552 | "-R", 553 | ) 554 | assert.Nil(t, err) 555 | assert.Regexp(t, regexp.MustCompile(`core1.fmt2.he.net. .* A .* \(core1.fmt2.he.net.\)`), out.String()) 556 | } 557 | 558 | func TestMainQueryDomainWithRRType(t *testing.T) { 559 | out, err := run( 560 | "NS.network", 561 | "A", 562 | ) 563 | assert.Nil(t, err) 564 | assert.Regexp(t, regexp.MustCompile(`(?i)ns.network. .* A .*`), out.String()) 565 | } 566 | 567 | func TestMainQueryTypeFlag(t *testing.T) { 568 | out, err := run( 569 | "-t", "65", 570 | "cloudflare.com", 571 | "-v", 572 | ) 573 | assert.Nil(t, err) 574 | assert.Regexp(t, regexp.MustCompile(`cloudflare.com. .* HTTPS 1 .*`), out.String()) 575 | } 576 | 577 | func TestMainDnsstampDoH(t *testing.T) { 578 | out, err := run( 579 | "@sdns://AgcAAAAAAAAADjEwNC4xNi4yNDguMjQ5ABJjbG91ZGZsYXJlLWRucy5jb20A", // cloudflare-dns.com 580 | "--all", 581 | ) 582 | 583 | assert.Nil(t, err) 584 | assert.Contains(t, out.String(), "from https://cloudflare-dns.com:443/dns-query") 585 | } 586 | 587 | func TestMainDnsstampDoHPath(t *testing.T) { 588 | _, err := run( 589 | "@sdns://AgcAAAAAAAAADjEwNC4xNi4yNDguMjQ5ABJjbG91ZGZsYXJlLWRucy5jb20FL3Rlc3Q", // cloudflare-dns.com/test 590 | "--all", 591 | ) 592 | 593 | // use err here because the query will result in a 404 594 | assert.Contains(t, err.Error(), "from https://cloudflare-dns.com:443/test") 595 | } 596 | 597 | func TestMainDnsstampInvalid(t *testing.T) { 598 | _, err := run( 599 | "@sdns://invalid", 600 | "--all", 601 | ) 602 | 603 | assert.NotNil(t, err) 604 | assert.Contains(t, err.Error(), "converting DNS stamp to URL: illegal base64 data") 605 | } 606 | 607 | func TestMainTypeNotation(t *testing.T) { 608 | // Test invalid TYPE notation 609 | _, err := run( 610 | "--all", 611 | "-q", "example.com", 612 | "-t", "TYPEinvalid", 613 | ) 614 | assert.NotNil(t, err) 615 | assert.Contains(t, err.Error(), "TYPEinvalid is not a valid RR type") 616 | 617 | // Test that TYPE65 is equivalent to HTTPS 618 | outType65, err := run( 619 | "--all", 620 | "-q", "cloudflare.com", 621 | "-t", "TYPE65", 622 | ) 623 | assert.Nil(t, err) 624 | assert.Regexp(t, regexp.MustCompile(`cloudflare.com. .* HTTPS .*`), outType65.String()) 625 | } 626 | 627 | func TestIDNAUnderscoreASCII(t *testing.T) { 628 | // Ensure ASCII names with underscores are not mangled by IDNA processing 629 | out, err := run( 630 | "--all", 631 | "-q", "_acme-challenge.example.com", 632 | "-t", "TXT", 633 | ) 634 | assert.Nil(t, err) 635 | // Expect the question or answer to include the literal underscore name 636 | re := regexp.MustCompile(regexp.QuoteMeta("_acme-challenge.example.com.")) 637 | assert.Regexp(t, re, out.String()) 638 | } 639 | 640 | func TestMainEDE_Raw(t *testing.T) { 641 | out, err := run( 642 | "--all", 643 | "-f", "raw", 644 | "A", 645 | "ede-6.extended-dns-errors.com", 646 | "+ede", 647 | "@1.1.1.1", 648 | ) 649 | assert.Nil(t, err) 650 | s := out.String() 651 | assert.Contains(t, s, "EDE: 6 (DNSSEC Bogus)") 652 | assert.Contains(t, s, "This EDE was intentionally inserted by dnsdist") 653 | } 654 | 655 | func TestMainEDE_Pretty(t *testing.T) { 656 | out, err := run( 657 | "--all", 658 | "A", 659 | "ede-6.extended-dns-errors.com", 660 | "+ede", 661 | "@1.1.1.1", 662 | ) 663 | assert.Nil(t, err) 664 | s := out.String() 665 | assert.Contains(t, s, "EDE:") 666 | assert.Contains(t, s, "6 (DNSSEC Bogus)") 667 | assert.Contains(t, s, "This EDE was intentionally inserted by dnsdist") 668 | } 669 | 670 | func TestMainMultipleServersSkipFailures(t *testing.T) { 671 | out, err := run( 672 | "--all", 673 | "-q", "example.com", 674 | "-t", "A", 675 | "-s", "127.127.127.127:1", // expected to fail 676 | "-s", "8.8.8.8", // expected to succeed 677 | ) 678 | assert.Nil(t, err) 679 | s := out.String() 680 | assert.Regexp(t, regexp.MustCompile(`example\.com\. .* A .*`), s) 681 | // When multiple servers are used, the server suffix is appended to answers 682 | assert.Truef(t, strings.Contains(s, "(8.8.8.8:53)") || strings.Contains(s, "from 8.8.8.8:53"), "expected output to include successful server 8.8.8.8:53, got: %s", s) 683 | } 684 | 685 | func TestMainMultipleServersAllFail(t *testing.T) { 686 | _, err := run( 687 | "--all", 688 | "-q", "example.com", 689 | "-t", "A", 690 | "-s", "127.127.127.127:1", 691 | "-s", "127.127.127.127:2", 692 | "--timeout", "1s", 693 | ) 694 | assert.NotNil(t, err) 695 | 696 | timedOut := strings.Contains(err.Error(), "timeout after 2s") 697 | erroredOut := strings.Contains(err.Error(), "all servers failed") 698 | assert.True(t, timedOut || erroredOut) 699 | } 700 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | --------------------------------------------------------------------------------