awl/cli/misc.go
Sam Therapy 1b5d5a3fed
Some checks failed
continuous-integration/drone/push Build is failing
Do "a few things"
Signed-off-by: Sam Therapy <sam@samtherapy.net>
2022-07-20 23:14:15 +02:00

123 lines
2.6 KiB
Go

// SPDX-License-Identifier: BSD-3-Clause
package cli
import (
"fmt"
"math/rand"
"strings"
"git.froth.zone/sam/awl/conf"
"git.froth.zone/sam/awl/internal/structs"
"git.froth.zone/sam/awl/util"
"github.com/miekg/dns"
"golang.org/x/net/idna"
)
// Parse the wildcard arguments, drill style
func ParseMiscArgs(args []string, opts *Options) error {
var err error
for _, arg := range args {
r, ok := dns.StringToType[strings.ToUpper(arg)]
switch {
// If it starts with @, it's a DNS server
case strings.HasPrefix(arg, "@"):
opts.Request.Server = arg[1:]
case strings.Contains(arg, "."):
opts.Query, err = idna.ToASCII(arg)
if err != nil {
return err
}
case ok:
// If it's a DNS request, it's a DNS request (obviously)
opts.Type = r
case strings.HasPrefix(arg, "+"):
// Dig-style +queries
err = ParseDig(strings.ToLower(arg[1:]), opts)
default:
//else, assume it's a name
opts.Query, err = idna.ToASCII(arg)
if err != nil {
return err
}
}
}
// If nothing was set, set a default
if opts.Query == "" {
opts.Query = "."
if opts.Type == 0 {
opts.Type = dns.StringToType["NS"]
}
} else {
if opts.Type == 0 {
opts.Type = dns.StringToType["A"]
}
}
if opts.Request.Server == "" {
switch {
case opts.TLS:
opts.Request.Server = "dns.google"
case opts.HTTPS:
opts.Request.Server = "https://dns.cloudflare.com/dns-query"
case opts.QUIC:
opts.Request.Server = "dns.adguard.com"
default:
resolv, err := conf.GetDNSConfig()
if err != nil {
opts.Request.Server = "9.9.9.9"
} else {
for _, srv := range resolv.Servers {
if opts.IPv4 {
if strings.Contains(srv, ".") {
opts.Request.Server = srv
break
}
} else if opts.IPv6 {
if strings.Contains(srv, ":") {
opts.Request.Server = srv
break
}
} else {
//#nosec -- This isn't used for anything secure
opts.Request.Server = resolv.Servers[rand.Intn(len(resolv.Servers))]
break
}
}
}
}
}
// Make reverse adresses proper addresses
if opts.Reverse {
if dns.TypeToString[opts.Request.Type] == "A" {
opts.Type = dns.StringToType["PTR"]
}
opts.Query, err = util.ReverseDNS(opts.Query, opts.Request.Type)
if err != nil {
return err
}
}
if opts.Class == 0 {
opts.Class = dns.StringToClass["IN"]
}
// if the domain is not canonical, make it canonical
if !strings.HasSuffix(opts.Query, ".") {
opts.Query = fmt.Sprintf("%s.", opts.Query)
}
opts.Request = structs.Request{
Server: opts.Request.Server,
Type: opts.Type,
Class: opts.Class,
Name: opts.Query,
}
return nil
}