Skip to content

Commit

Permalink
cli: add json and type flags to query
Browse files Browse the repository at this point in the history
  • Loading branch information
cryptix committed Aug 1, 2024
1 parent 83d8d24 commit 7093034
Showing 1 changed file with 75 additions and 8 deletions.
83 changes: 75 additions & 8 deletions golang/cmd/sig0namectl/query.go
Original file line number Diff line number Diff line change
@@ -1,26 +1,53 @@
package main

import (
"encoding/json"
"fmt"
"os"
"strconv"
"strings"

"github.com/NetworkCommons/sig0namectl/sig0"
"github.com/davecgh/go-spew/spew"
"github.com/miekg/dns"
"github.com/urfave/cli/v2"
)

var queryCmd = &cli.Command{
Name: "query",
Usage: "query <name>",
Aliases: []string{"q"},
UsageText: "See flags for usage",
Action: queryAction,
Name: "query",
Usage: "query <name>",
Aliases: []string{"q"},
Flags: []cli.Flag{
&cli.GenericFlag{
Name: "type",
Usage: "type of query to run",
Value: &dnsRRTypeFlag{},
},

&cli.BoolFlag{
Name: "json",
Usage: "output JSON",
Value: false,
},
},
Action: queryAction,
}

func queryAction(cCtx *cli.Context) error {
name := cCtx.Args().First()
fmt.Printf("Q:(TXT):%v\n", name)

q, err := sig0.QueryA(name)
tf := cCtx.Generic("type")
typeFlag, ok := tf.(*dnsRRTypeFlag)
if !ok {
return fmt.Errorf("unexpected flag type: %T", tf)
}
// default
if typeFlag.qtype == 0 {
typeFlag.qtype = dns.TypeA
}
fmt.Fprintf(os.Stderr, "[Querying] %d:%v\n", typeFlag.qtype, name)

q, err := sig0.QueryWithType(name, typeFlag.qtype)
if err != nil {
return err
}
Expand All @@ -31,6 +58,46 @@ func queryAction(cCtx *cli.Context) error {
return err
}

spew.Dump(answer)
if cCtx.Bool("json") {
out, err := json.Marshal(answer)
if err != nil {
return fmt.Errorf("failed to encode answer to %d:%q as JSON: %w", typeFlag.qtype, name, err)
}
_, _ = os.Stdout.Write(out)
} else {
spew.Dump(answer)
}
return nil
}

type dnsRRTypeFlag struct {
qtype uint16
}

func (f *dnsRRTypeFlag) Set(value string) error {
switch strings.ToLower(value) {
case "a":
f.qtype = dns.TypeA
case "aaaa":
f.qtype = dns.TypeAAAA
case "any":
f.qtype = dns.TypeANY
case "key":
f.qtype = dns.TypeKEY
case "ptr":
f.qtype = dns.TypePTR
case "loc":
f.qtype = dns.TypeLOC
default:
asNum, err := strconv.ParseUint(value, 10, 16)
if err != nil {
return fmt.Errorf("unhandled dns type: %q: %w", value, err)
}
f.qtype = uint16(asNum)
}
return nil
}

func (f *dnsRRTypeFlag) String() string {
return fmt.Sprintf("dnsType:%d", f.qtype)
}

0 comments on commit 7093034

Please sign in to comment.