-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
204 lines (165 loc) · 5.78 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
// Copyright 2021 Adam Chalkley
//
// https://github.com/atc0005/dnsc
//
// Licensed under the MIT License. See LICENSE file in the project root for
// full license information.
//go:generate go-winres make --product-version=git-tag --file-version=git-tag
package main
import (
"errors"
"fmt"
"os"
"sort"
"sync"
"time"
"github.com/atc0005/dnsc/internal/config"
"github.com/atc0005/dnsc/internal/dqrs"
"github.com/miekg/dns"
"github.com/apex/log"
)
func main() {
// This will use default logging settings (level filter, destination)
// as the application hasn't "booted up" far enough to apply custom
// choices yet.
log.Debug("Initializing application")
cfg, cfgErr := config.NewConfig()
switch {
case errors.Is(cfgErr, config.ErrVersionRequested):
config.Branding()
os.Exit(0)
case cfgErr != nil:
log.Fatalf("failed to initialize application: %s", cfgErr)
}
// Get a list of all record types that we should request when submitting
// DNS queries
queryTypes := cfg.QueryTypes()
queryTimeout := cfg.Timeout()
var expectedResponses int
switch {
case len(cfg.SrvProtocols()) > 0:
types := len(queryTypes) - 1 // exclude SRV record query type
protocols := len(cfg.SrvProtocols()) // SRV query type calculated here
servers := len(cfg.Servers())
expectedResponses = (types * servers) + (protocols * servers)
default:
expectedResponses = len(queryTypes) * len(cfg.Servers())
}
log.Debugf("%d queries to submit, equal number responses expected\n", expectedResponses)
results := make(dqrs.DNSQueryResponses, 0, expectedResponses)
resultsChan := make(chan dqrs.DNSQueryResponse)
var queriesWG sync.WaitGroup
var collectorWG sync.WaitGroup
// spin off "collector" for results channel
collectorWG.Add(1)
go func() {
defer collectorWG.Done()
// Collect all responses
for result := range resultsChan {
log.Debug("collector: Received result")
results = append(results, result)
if result.QueryError != nil {
// Check whether the user has opted to treat errors as fatal. If
// so, display current summary results and exit
if cfg.DNSErrorsFatal() {
results.PrintSummary(cfg.ResultsOutput(), cfg.OmitTimestamp())
os.Exit(1)
}
}
log.Debug("collector: Saved result")
}
log.Debug("collector: Exited collection loop")
}()
// spin off a separate goroutine for each of our DNS servers, send back
// results on a channel
for _, server := range cfg.Servers() {
queriesWG.Add(1)
go func(server string, query string, queryTypes []string, queryTimeout time.Duration, results chan dqrs.DNSQueryResponse) {
defer queriesWG.Done()
log.Debugf("Length of requested query types: %d", len(queryTypes))
for _, rrString := range queryTypes {
rrType, err := dqrs.RRStringToType(rrString)
if err != nil {
// Record the error, log the error and send a minimal
// DNSQueryResponse type back on the channel with the
// specific error embedded.
failedQueryRequest := dqrs.DNSQueryResponse{
Server: server,
Query: query,
QueryError: fmt.Errorf("error converting Resource Record string to native type: %w", err),
}
log.Warn(failedQueryRequest.Error())
queriesWG.Add(1)
go func() {
defer queriesWG.Done()
results <- failedQueryRequest
}()
}
var totalQueries int
switch {
case rrType == dns.TypeSRV && len(cfg.SrvProtocols()) > 0:
totalQueries = len(cfg.SrvProtocols())
default:
totalQueries = 1
}
queries := make([]string, 0, totalQueries)
switch {
// If performing SRV record queries, check to see if SRV
// protocols were specified. If so, submit a separate query
// for each one after resolving the protocol record syntax
// needed.
case rrType == dns.TypeSRV && len(cfg.SrvProtocols()) > 0:
for _, srvProtocol := range cfg.SrvProtocols() {
queryTemplate, err := config.SrvProtocolTmplLookup(srvProtocol)
if err != nil {
// Record the error, log the error and send a
// minimal DNSQueryResponse type back on the
// channel with the specific error embedded.
failedQueryRequest := dqrs.DNSQueryResponse{
Server: server,
Query: query,
QueryError: fmt.Errorf("error retrieving SRV protocol template: %w", err),
}
log.Warn(failedQueryRequest.Error())
queriesWG.Add(1)
go func() {
defer queriesWG.Done()
results <- failedQueryRequest
}()
}
queries = append(queries, fmt.Sprintf(queryTemplate, query))
}
// use the query string as-is if SRV protocols not specified
default:
queries = append(queries, query)
}
log.Debugf("Total queries collected: %d", len(queries))
for i := range queries {
log.Debugf("Submitting query for %q of type %q to %q",
queries[i], rrString, server)
queriesWG.Add(1)
go func(q string) {
defer queriesWG.Done()
results <- dqrs.PerformQuery(q, server, rrType, queryTimeout)
log.Debug("Query completed, results sent back on channel")
}(queries[i])
}
}
}(server, cfg.Query(), queryTypes, queryTimeout, resultsChan)
}
// Close results channel after all queries have been submitted and results
// are ready to be collected
queriesWG.Wait()
close(resultsChan)
// Wait on collector to finish saving results from earlier queries
collectorWG.Wait()
// Sort DNS query results by server used for query. This is done in an
// effort to arrange responses based on the group of DNS servers (assuming
// that they're grouped together using a consecutive IP block)
sort.Slice(results, func(i, j int) bool {
return results[i].Server < results[j].Server
})
// Generate summary of all collected query responses in the specified
// format
results.PrintSummary(cfg.ResultsOutput(), cfg.OmitTimestamp())
}