-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
238 lines (196 loc) · 5.47 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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
/*
This program takes a list of domains and queries each against the OpenDNS
Investigate API, optionally outputting a CSV file.
Because querying every endpoint can be very time consuming, this program uses
a TOML file to configure which information should be queried.
For full documentation of usage, see the GitHub page:
https://github.com/dead10ck/domainstats
*/
package main
import (
"bufio"
"encoding/csv"
"flag"
"fmt"
"log"
"os"
"runtime"
"sync"
domainstats "github.com/dead10ck/domainstats/lib"
"github.com/dead10ck/goinvestigate"
)
type opt struct {
verbose bool
setup string
outFile string
configPath string
maxGoroutines int
}
var (
opts opt
numDomains int
)
const (
DEFAULT_MAX_GOROUTINES = 5
)
func init() {
runtime.GOMAXPROCS(runtime.NumCPU())
}
func main() {
flag.IntVar(&opts.maxGoroutines, "m", DEFAULT_MAX_GOROUTINES,
"Maximum number of goroutines to use for parallel HTTP requests")
flag.BoolVar(&opts.verbose, "v", false, "Print out verbose log messages.")
flag.StringVar(&opts.setup, "setup", "",
"Generate a default config file in ~/.domainstats/default.toml with"+
" the given API key.")
flag.StringVar(&opts.outFile, "out", "", "Output matching IPs to the given file")
flag.StringVar(&opts.configPath, "c", domainstats.DefaultConfigPath, "The config file to use")
flag.Parse()
if opts.setup != "" {
err := domainstats.GenerateDefaultConfig(opts.setup)
if err != nil {
log.Fatalf("error creating default config file: %v", err)
}
fmt.Printf(fmt.Sprintf("Config file generated in %s\n", domainstats.DefaultConfigPath))
os.Exit(0)
}
// if the default config file does not exist and the user did not specify
// a different config file, then the program cannot proceed
if _, err := os.Stat(domainstats.DefaultConfigPath); os.IsNotExist(err) && opts.configPath == domainstats.DefaultConfigPath {
log.Fatal("Default config file missing, and no other config file specified." +
" Please run domainstats with the -setup option to set up a default " +
"config file.")
}
config, err := domainstats.NewConfig(opts.configPath)
if err != nil {
log.Fatal(err)
}
var outWriter *csv.Writer
inv := goinvestigate.New(config.APIKey)
domainListFileName := flag.Arg(flag.NArg() - 1)
if domainListFileName == "" {
fmt.Println("Need a file name")
os.Exit(-1)
}
inChan := readDomainsFrom(domainListFileName)
if opts.verbose {
inv.SetVerbose(true)
}
if opts.outFile != "" {
outFile, err := os.Create(opts.outFile)
if err != nil {
log.Fatal(err)
}
outWriter = csv.NewWriter(outFile)
outWriter.Comma = rune('\t')
outWriter.Write(config.DeriveHeader())
defer func() {
outWriter.Flush()
outFile.Close()
}()
}
outChan := getInfo(config, inv, inChan)
mainWg := new(sync.WaitGroup)
mainWg.Add(1)
go writeOut(outWriter, outChan, mainWg)
mainWg.Wait()
}
func writeOut(outWriter *csv.Writer, outChan <-chan []string, wg *sync.WaitGroup) {
numProcessed := 0
msgChan := make(chan string, 10)
go printStdOut(msgChan)
for respRow := range outChan {
numProcessed++
msgChan <- fmt.Sprintf("\r%d/%d: %s", numProcessed, numDomains, respRow[0])
if outWriter != nil {
outWriter.Write(respRow)
}
}
close(msgChan)
wg.Done()
}
func printStdOut(msgChan <-chan string) {
for msg := range msgChan {
fmt.Printf("\r%120s", " ")
fmt.Print(msg)
}
fmt.Println()
}
// The goroutine which does the HTTP queries
func query(qChan <-chan *domainstats.DomainQueryMessage) {
for m := range qChan {
m.RespChan <- m.Q.Query()
}
}
func process(inv *goinvestigate.Investigate, config *domainstats.Config,
domainChan <-chan string,
qChan chan<- *domainstats.DomainQueryMessage,
outChan chan<- []string,
wg *sync.WaitGroup) {
domainLoop:
for domain := range domainChan {
// generate the list of queries to make for each domain
queries := config.DeriveMessages(inv, domain)
// send each query on the query channel for the query goroutines
// to receive
for _, q := range queries {
qChan <- q
}
row := []string{domain}
// receive once for each query that was sent
for _, q := range queries {
qmResp := <-q.RespChan
if qmResp.Err != nil {
log.Printf("error during query for %v: %v\nskipping this domain",
domain, qmResp.Err)
continue domainLoop
}
subRow, err := config.ExtractCSVSubRow(qmResp.Resp)
if err != nil {
inv.Logf("error extracting CSV sub row: %v", err)
continue
}
row = append(row, subRow...)
}
outChan <- row
}
wg.Done()
}
func getInfo(config *domainstats.Config, inv *goinvestigate.Investigate, domainChan <-chan string) <-chan []string {
outChan := make(chan []string, 100)
qChan := make(chan *domainstats.DomainQueryMessage)
wg := new(sync.WaitGroup)
// launch the query goroutines
for i := 0; i < opts.maxGoroutines; i++ {
go query(qChan)
}
// launch the processor goroutines
for i := 0; i < opts.maxGoroutines; i++ {
wg.Add(1)
go process(inv, config, domainChan, qChan, outChan, wg)
}
// launch a goroutine which closes the output channel when the processor
// goroutines are finished
go func() {
wg.Wait()
close(qChan)
close(outChan)
}()
return outChan
}
func readDomainsFrom(fName string) <-chan string {
file, err := os.Open(fName)
if err != nil {
log.Fatalf("\nError opening domain list %s: %v\n", fName, err)
}
domainChan := make(chan string, 100)
scanner := bufio.NewScanner(file)
go func() {
for scanner.Scan() {
domainChan <- scanner.Text()
numDomains++
}
close(domainChan)
}()
return domainChan
}