-
Notifications
You must be signed in to change notification settings - Fork 1
/
doh_client.go
77 lines (58 loc) · 1.24 KB
/
doh_client.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
package main
import (
"bytes"
"errors"
"io/ioutil"
"log"
"net/http"
"sync"
"github.com/miekg/dns"
)
type DohClient struct {
httpClient *http.Client
// Slice of URLs
urls []string
// Last used index
lIndex int
logQueries bool
sync.Mutex
}
func (c *DohClient) GetDNSResponse(msg *dns.Msg) (*dns.Msg, error) {
b, err := msg.Pack()
if err != nil {
return &dns.Msg{}, err
}
c.Lock()
url := c.urls[c.lIndex]
// Increase last index
c.lIndex++
if c.lIndex == len(c.urls) {
c.lIndex = 0
}
c.Unlock()
if c.logQueries {
log.Printf("Sending to %s for query: %s", url, msg.Question[0].String())
}
resp, err := c.httpClient.Post(url, "application/dns-message", bytes.NewBuffer(b))
if err != nil {
return &dns.Msg{}, err
}
if resp.StatusCode != http.StatusOK {
log.Printf("Response from DOH provider has status code: %d", resp.StatusCode)
return &dns.Msg{}, errors.New("error from DOH provider")
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return &dns.Msg{}, nil
}
r := &dns.Msg{}
err = r.Unpack(body)
return r, err
}
func NewDOHClient(c *http.Client, urls []string, logQueries bool) (*DohClient, error) {
return &DohClient{
httpClient: c,
urls: urls,
logQueries: logQueries,
}, nil
}