Content-Type auto detection for client
[dns-over-https.git] / doh-client / google.go
blob:a/doh-client/google.go -> blob:b/doh-client/google.go
--- a/doh-client/google.go
+++ b/doh-client/google.go
@@ -24,49 +24,41 @@
 package main
 
 import (
+	"context"
 	"encoding/json"
 	"fmt"
 	"io/ioutil"
 	"log"
-	"math/rand"
 	"net/http"
 	"net/url"
 	"strconv"
 	"strings"
-	"time"
 
-	"../json-dns"
+	"github.com/m13253/dns-over-https/doh-client/selector"
+	"github.com/m13253/dns-over-https/json-dns"
 	"github.com/miekg/dns"
 )
 
-func (c *Client) generateRequestGoogle(w dns.ResponseWriter, r *dns.Msg, isTCP bool) *DNSRequest {
-	reply := jsonDNS.PrepareReply(r)
-
-	if len(r.Question) != 1 {
-		log.Println("Number of questions is not 1")
-		reply.Rcode = dns.RcodeFormatError
+func (c *Client) generateRequestGoogle(ctx context.Context, w dns.ResponseWriter, r *dns.Msg, isTCP bool, upstream *selector.Upstream) *DNSRequest {
+	question := &r.Question[0]
+	questionName := question.Name
+	questionClass := question.Qclass
+	if questionClass != dns.ClassINET {
+		reply := jsonDNS.PrepareReply(r)
+		reply.Rcode = dns.RcodeRefused
 		w.WriteMsg(reply)
 		return &DNSRequest{
 			err: &dns.Error{},
 		}
 	}
-	question := &r.Question[0]
-	// knot-resolver scrambles capitalization, I think it is unfriendly to cache
-	questionName := strings.ToLower(question.Name)
 	questionType := ""
 	if qtype, ok := dns.TypeToString[question.Qtype]; ok {
 		questionType = qtype
 	} else {
-		questionType = strconv.Itoa(int(question.Qtype))
+		questionType = strconv.FormatUint(uint64(question.Qtype), 10)
 	}
 
-	if c.conf.Verbose {
-		fmt.Printf("%s - - [%s] \"%s IN %s\"\n", w.RemoteAddr(), time.Now().Format("02/Jan/2006:15:04:05 -0700"), questionName, questionType)
-	}
-
-	numServers := len(c.conf.UpstreamGoogle)
-	upstream := c.conf.UpstreamGoogle[rand.Intn(numServers)]
-	requestURL := fmt.Sprintf("%s?name=%s&type=%s", upstream, url.QueryEscape(questionName), url.QueryEscape(questionType))
+	requestURL := fmt.Sprintf("%s?ct=application/dns-json&name=%s&type=%s", upstream.Url, url.QueryEscape(questionName), url.QueryEscape(questionType))
 
 	if r.CheckingDisabled {
 		requestURL += "&cd=1"
@@ -82,23 +74,39 @@
 		requestURL += fmt.Sprintf("&edns_client_subnet=%s/%d", ednsClientAddress.String(), ednsClientNetmask)
 	}
 
-	req, err := http.NewRequest("GET", requestURL, nil)
+	req, err := http.NewRequest(http.MethodGet, requestURL, nil)
 	if err != nil {
 		log.Println(err)
+		reply := jsonDNS.PrepareReply(r)
 		reply.Rcode = dns.RcodeServerFailure
 		w.WriteMsg(reply)
 		return &DNSRequest{
 			err: err,
 		}
 	}
-	req.Header.Set("Accept", "application/json, application/dns-udpwireformat")
-	req.Header.Set("User-Agent", "DNS-over-HTTPS/1.1 (+https://github.com/m13253/dns-over-https)")
+
+	req.Header.Set("Accept", "application/json, application/dns-message, application/dns-udpwireformat")
+	req.Header.Set("User-Agent", USER_AGENT)
+	req = req.WithContext(ctx)
+
+	c.httpClientMux.RLock()
 	resp, err := c.httpClient.Do(req)
+	c.httpClientMux.RUnlock()
+
+	// if http Client.Do returns non-nil error, it always *url.Error
+	/*if err == context.DeadlineExceeded {
+		// Do not respond, silently fail to prevent caching of SERVFAIL
+		log.Println(err)
+		return &DNSRequest{
+			err: err,
+		}
+	}*/
+
 	if err != nil {
 		log.Println(err)
+		reply := jsonDNS.PrepareReply(r)
 		reply.Rcode = dns.RcodeServerFailure
 		w.WriteMsg(reply)
-		c.httpTransport.CloseIdleConnections()
 		return &DNSRequest{
 			err: err,
 		}
@@ -106,16 +114,17 @@
 
 	return &DNSRequest{
 		response:          resp,
-		reply:             reply,
+		reply:             jsonDNS.PrepareReply(r),
 		udpSize:           udpSize,
 		ednsClientAddress: ednsClientAddress,
 		ednsClientNetmask: ednsClientNetmask,
+		currentUpstream:   upstream.Url,
 	}
 }
 
-func (c *Client) parseResponseGoogle(w dns.ResponseWriter, r *dns.Msg, isTCP bool, req *DNSRequest) {
-	if req.response.StatusCode != 200 {
-		log.Printf("HTTP error: %s\n", req.response.Status)
+func (c *Client) parseResponseGoogle(ctx context.Context, w dns.ResponseWriter, r *dns.Msg, isTCP bool, req *DNSRequest) {
+	if req.response.StatusCode != http.StatusOK {
+		log.Printf("HTTP error from upstream %s: %s\n", req.currentUpstream, req.response.Status)
 		req.reply.Rcode = dns.RcodeServerFailure
 		contentType := req.response.Header.Get("Content-Type")
 		if contentType != "application/json" && !strings.HasPrefix(contentType, "application/json;") {