Skip to content

Commit

Permalink
Merge pull request #4 from bschaatsbergen/f/touch-up-logging
Browse files Browse the repository at this point in the history
  • Loading branch information
mmourick committed Jul 12, 2023
2 parents 854c53e + e14adad commit 3f8dd99
Show file tree
Hide file tree
Showing 6 changed files with 93 additions and 30 deletions.
2 changes: 1 addition & 1 deletion README.md
@@ -1,6 +1,6 @@
# dnsee

[![Release](https://github.com/bschaatsbergen/dnsee/actions/workflows/goreleaser.yaml/badge.svg)](https://github.com/bschaatsbergen/dnsee/actions/workflows/goreleaser.yaml) ![GitHub release (latest SemVer)](https://img.shields.io/github/v/release/bschaatsbergen/dnsee) ![GitHub commits since latest release (by SemVer)](https://img.shields.io/github/commits-since/bschaatsbergen/dnsee/latest) [![Go Reference](https://pkg.go.dev/badge/github.com/bschaatsbergen/dnsee.svg)](https://pkg.go.dev/github.com/bschaatsbergen/dnsee)
[![Release](https://github.com/bschaatsbergen/dnsee/actions/workflows/goreleaser.yaml/badge.svg)](https://github.com/bschaatsbergen/dnsee/actions/workflows/goreleaser.yaml) ![GitHub release (latest SemVer)](https://img.shields.io/github/v/release/bschaatsbergen/dnsee) ![GitHub commits since latest release (by SemVer)](https://img.shields.io/github/commits-since/bschaatsbergen/dnsee/latest) [![Go Reference](https://pkg.go.dev/badge/github.com/bschaatsbergen/dnsee.svg)](https://pkg.go.dev/github.com/bschaatsbergen/dnsee) ![GitHub all releases](https://img.shields.io/github/downloads/bschaatsbergen/dnsee/total)

Check DNS configurations quickly

Expand Down
62 changes: 44 additions & 18 deletions cmd/root.go
Expand Up @@ -2,24 +2,32 @@ package cmd

import (
"fmt"
"log"
"os"
"strings"

"github.com/bschaatsbergen/dnsee/pkg/core"
"github.com/bschaatsbergen/dnsee/pkg/model"
"github.com/fatih/color"
"github.com/miekg/dns"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)

type PlainFormatter struct{}

var (
version string
dnsServerIP string
userSpecifiedQueryType string
version string
flagStore model.Flagstore

rootCmd = &cobra.Command{
Use: "dnsee",
Short: "dnsee - Check DNS configurations quickly",
Short: "dnsee - check DNS configurations quickly",
Version: version,
PreRun: toggleDebug,
Example: "dnsee " + color.New(color.FgBlue).SprintFunc()("example.com") + "." +
"\n" + "dnsee " + color.New(color.FgBlue).SprintFunc()("example.com") + "." + " -q A" +
"\n" + "dnsee " + color.New(color.FgBlue).SprintFunc()("example.com") + "." + " --dns-server-ip 8.8.8.8" +
"\n" + "dnsee " + color.New(color.FgBlue).SprintFunc()("example.com") + "." + " --debug",
Run: func(cmd *cobra.Command, args []string) {
if len(args) != 1 {
fmt.Println("error: provide a domain name")
Expand All @@ -34,14 +42,15 @@ var (
queryTypes := core.GetQueryTypes()

// If a specific query type is provided, filter the queryTypes slice to only include that type
if userSpecifiedQueryType != "" {
queryTypes = filterQueryTypes(queryTypes, userSpecifiedQueryType)
if flagStore.UserSpecifiedQueryType != "" {
queryTypes = core.FilterQueryTypes(queryTypes, flagStore.UserSpecifiedQueryType)
}

// Send a DNS query for each query type in the queryTypes slice
for _, queryType := range queryTypes {
msg := core.PrepareDNSQuery(domainName, queryType.Type)

response, _, err := core.SendDNSQuery(&client, msg, dnsServerIP)
response, _, err := core.SendDNSQuery(&client, msg, flagStore.DNSServerIP)
if err != nil {
log.Fatal(err)
}
Expand All @@ -53,9 +62,22 @@ var (
)

func init() {
setupCobraUsageTemplate()
rootCmd.CompletionOptions.DisableDefaultCmd = true
rootCmd.Flags().StringVar(&dnsServerIP, "dns-server-ip", "", "IP address of the DNS server")
rootCmd.Flags().StringVarP(&userSpecifiedQueryType, "query-type", "q", "", "Specific query type to filter on")
rootCmd.Flags().StringVar(&flagStore.DNSServerIP, "dns-server-ip", "", "IP address of the DNS server")
rootCmd.Flags().StringVarP(&flagStore.UserSpecifiedQueryType, "query-type", "q", "", "specific query type to filter on")
rootCmd.Flags().BoolVarP(&flagStore.Debug, "debug", "d", false, "verbose logging")
}

func setupCobraUsageTemplate() {
cobra.AddTemplateFunc("StyleHeading", color.New(color.FgGreen).SprintFunc())
usageTemplate := rootCmd.UsageTemplate()
usageTemplate = strings.NewReplacer(
`Usage:`, `{{StyleHeading "Usage:"}}`,
`Examples:`, `{{StyleHeading "Examples:"}}`,
`Flags:`, `{{StyleHeading "Flags:"}}`,
).Replace(usageTemplate)
rootCmd.SetUsageTemplate(usageTemplate)
}

func Execute() {
Expand All @@ -65,13 +87,17 @@ func Execute() {
}
}

func filterQueryTypes(queryTypes []model.QueryType, userSpecifiedQueryType string) []model.QueryType {
var filteredQueryTypes []model.QueryType
for _, queryType := range queryTypes {
if queryType.Name == userSpecifiedQueryType {
filteredQueryTypes = append(filteredQueryTypes, queryType)
break
}
func (f *PlainFormatter) Format(entry *log.Entry) ([]byte, error) {
return []byte(fmt.Sprintf("%s\n", entry.Message)), nil
}

func toggleDebug(cmd *cobra.Command, args []string) {
if flagStore.Debug {
log.SetLevel(log.DebugLevel)
log.Debug("Debug logs enabled")
log.SetFormatter(&log.TextFormatter{})
} else {
plainFormatter := new(PlainFormatter)
log.SetFormatter(plainFormatter)
}
return filteredQueryTypes
}
1 change: 1 addition & 0 deletions go.mod
Expand Up @@ -14,6 +14,7 @@ require (
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.17 // indirect
github.com/sirupsen/logrus v1.9.3
github.com/spf13/pflag v1.0.5 // indirect
golang.org/x/mod v0.8.0 // indirect
golang.org/x/sys v0.10.0 // indirect
Expand Down
9 changes: 9 additions & 0 deletions go.sum
@@ -1,4 +1,6 @@
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs=
github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
Expand All @@ -10,20 +12,27 @@ github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPn
github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/miekg/dns v1.1.55 h1:GoQ4hpsj0nFLYe+bWiCToyrBEJXkQfOOIvFGFy0lEgo=
github.com/miekg/dns v1.1.55/go.mod h1:uInx36IzPl7FYnDcMeVWxj9byh7DutNykX4G9Sj60FY=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I=
github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
golang.org/x/mod v0.8.0 h1:LUYupSeNrTNCGzR/hVBk2NHZO4hXcVaW1k4Qx7rjPx8=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.12.0 h1:cfawfvKITfUsFCeJIHJrbSxpeu/E81khclypR0GVT50=
golang.org/x/net v0.12.0/go.mod h1:zEVYFnQC7m/vmpQFELhcD1EWkZlX69l4oqgmer6hfKA=
golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA=
golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/tools v0.6.0 h1:BOw41kyTf3PuCW1pVQf8+Cyg8pMlkYB1oo9iJ6D/lKM=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
42 changes: 31 additions & 11 deletions pkg/core/core.go
Expand Up @@ -2,18 +2,19 @@ package core

import (
"fmt"
"os"
"runtime"
"time"

model "github.com/bschaatsbergen/dnsee/pkg/model"
"github.com/fatih/color"
"github.com/miekg/dns"
"github.com/sirupsen/logrus"
)

const Windows = "windows"
const ResolverPath = "/etc/resolv.conf"
const windows = "windows"
const resolverPath = "/etc/resolv.conf"

// GetQueryTypes returns a slice of all supported DNS query types
func GetQueryTypes() []model.QueryType {
return []model.QueryType{
{Type: dns.TypeA, Name: "A"},
Expand All @@ -27,30 +28,49 @@ func GetQueryTypes() []model.QueryType {
}
}

// FilterQueryTypes filters the queryTypes slice to only include the query type specified by the user
func FilterQueryTypes(queryTypes []model.QueryType, userSpecifiedQueryType string) []model.QueryType {
var filteredQueryTypes []model.QueryType
for _, queryType := range queryTypes {
if queryType.Name == userSpecifiedQueryType {
filteredQueryTypes = append(filteredQueryTypes, queryType)
break
}
}
return filteredQueryTypes
}

// PrepareDNSQuery prepares a DNS query for a given domain name and query type
func PrepareDNSQuery(domainName string, queryType uint16) dns.Msg {
msg := dns.Msg{}
msg.SetQuestion(dns.Fqdn(domainName), queryType)
return msg
}

// SendDNSQuery sends a DNS query to a given DNS server
func SendDNSQuery(client *dns.Client, msg dns.Msg, dnsServerIP string) (*dns.Msg, time.Duration, error) {
if dnsServerIP == "" {
goOS := runtime.GOOS
if goOS == Windows {
fmt.Println("Unable to retrieve DNS configuration on Windows systems. \nPlease specify ip explicitely with the --dns-server-ip flag.")
os.Exit(2)
if goOS == windows {
logrus.Fatal("error: Unable to retrieve DNS configuration on Windows. \nPlease specify a DNS server IP explicitely with the `--dns-server-ip` flag.")
}
conf, err := dns.ClientConfigFromFile(ResolverPath)
conf, err := dns.ClientConfigFromFile(resolverPath)
if err != nil {
fmt.Fprintln(os.Stderr, err)
fmt.Println("Could not retrieve DNS server ip from system configuration. \nPlease specify ip explicitely with the --dns-server-ip flag.")
os.Exit(2)
logrus.Errorf("error: %s. Unable to retrieve DNS configuration.", err)
logrus.Fatal("Please specify a DNS server IP explicitely with the `--dns-server-ip` flag.")
}
dnsServerIP = conf.Servers[0]
}
return client.Exchange(&msg, dnsServerIP+":53")
logrus.Debugf("Sending DNS query to %s", dnsServerIP)
response, timeDuration, err := client.Exchange(&msg, dnsServerIP+":53")
if err != nil {
logrus.Fatal(err)
}
logrus.Debugf("Received DNS response from %s, Round-trip time: %s", dnsServerIP, timeDuration)
return response, timeDuration, nil
}

// DisplayRecords displays the DNS records returned by the DNS server
func DisplayRecords(domainName string, queryType struct {
Type uint16
Name string
Expand Down
7 changes: 7 additions & 0 deletions pkg/model/flagstore.go
@@ -0,0 +1,7 @@
package model

type Flagstore struct {
DNSServerIP string
UserSpecifiedQueryType string
Debug bool
}

0 comments on commit 3f8dd99

Please sign in to comment.