This repository has been archived by the owner on May 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
fdns.go
113 lines (98 loc) · 2.25 KB
/
fdns.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
package fdns
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"strings"
"github.com/klauspost/pgzip"
)
// Parser object allows parsing datasets looking for records related with a domain.
type Parser struct {
Domains []string
// Records stores reported records.
Records []string
// Substrings stores the reported substrings.
Substrings []string
// Workers is the numer of simultaneous goroutines the parser will use.
Workers int
}
// Parse reads from the given io.Reader and reports results and errors.
func (p *Parser) Parse(ctx context.Context, r io.Reader, out chan<- string, errs chan<- error) {
defer close(out)
gz, err := pgzip.NewReader(r)
if err != nil {
errs <- err
return
}
defer gz.Close()
lines := make(chan []byte)
done := make(chan struct{})
finished := make(chan struct{}, p.Workers)
for i := 0; i < p.Workers; i++ {
go func() {
var e entry
for {
select {
case <-done:
finished <- struct{}{}
return
case v := <-lines:
if err := json.Unmarshal(v, &e); err != nil {
errs <- fmt.Errorf("could not decode JSON object: %w", err)
continue
}
if p.Substring(e) || (p.IsInterestingDomain(e) && p.IsInterestingRecord(e)) {
out <- e.Name
}
}
}
}()
}
sc := bufio.NewScanner(gz)
for sc.Scan() {
select {
case <-ctx.Done():
goto ctxDone
default: // avoid blocking.
}
lines <- append([]byte{}, sc.Bytes()...)
}
if err := sc.Err(); err != nil {
errs <- fmt.Errorf("could not scan: %w", err)
return
}
ctxDone:
close(done)
for i := 0; i < p.Workers; i++ {
<-finished
}
}
// IsInterestingRecord reports if the entry contains an interesting record.
func (p *Parser) IsInterestingRecord(e entry) bool {
for _, r := range p.Records {
if r == e.Type {
return true
}
}
return false
}
// IsInterestingDomain reports if the domain is a subdomain of the provided domains.
func (p *Parser) IsInterestingDomain(e entry) bool {
for _, d := range p.Domains {
if strings.HasSuffix(e.Name, d) {
return true
}
}
return false
}
// Substring reports if the domain contains an interesting substring.
func (p *Parser) Substring(e entry) bool {
for _, sb := range p.Substrings {
if strings.Contains(e.Name, sb) {
return true
}
}
return false
}