Workaround a bug causing Firefox 61-62 to reject responses with Content-Type = application/dns-message
Workaround a bug causing Firefox 61-62 to reject responses with Content-Type = application/dns-message

--- a/doh-server/google.go
+++ b/doh-server/google.go
@@ -181,6 +181,7 @@
 	now := time.Now().UTC().Format(http.TimeFormat)
 	w.Header().Set("Date", now)
 	w.Header().Set("Last-Modified", now)
+	w.Header().Set("Vary", "Accept")
 	if respJSON.HaveTTL {
 		if req.isTailored {
 			w.Header().Set("Cache-Control", "private, max-age="+strconv.Itoa(int(respJSON.LeastTTL)))

--- a/doh-server/ietf.go
+++ b/doh-server/ietf.go
@@ -159,6 +159,10 @@
 	now := time.Now().UTC().Format(http.TimeFormat)
 	w.Header().Set("Date", now)
 	w.Header().Set("Last-Modified", now)
+	w.Header().Set("Vary", "Accept")
+
+	_ = s.patchFirefoxContentType(w, r, req)
+
 	if respJSON.HaveTTL {
 		if req.isTailored {
 			w.Header().Set("Cache-Control", "private, max-age="+strconv.Itoa(int(respJSON.LeastTTL)))
@@ -168,8 +172,6 @@
 		w.Header().Set("Expires", respJSON.EarliestExpires.Format(http.TimeFormat))
 	}
 
-	_ = s.patchFirefoxContentType(w, r)
-
 	if respJSON.Status == dns.RcodeServerFailure {
 		w.WriteHeader(503)
 	}
@@ -181,6 +183,7 @@
 	if strings.Contains(r.UserAgent(), "dnscrypt-proxy") && bytes.Equal(requestBinary, []byte("\xca\xfe\x01\x00\x00\x01\x00\x00\x00\x00\x00\x01\x00\x00\x02\x00\x01\x00\x00\x29\x10\x00\x00\x00\x80\x00\x00\x00")) {
 		log.Println("DNSCrypt-Proxy detected. Patching response.")
 		w.Header().Set("Content-Type", "application/dns-message")
+		w.Header().Set("Vary", "Accept, User-Agent")
 		now := time.Now().UTC().Format(http.TimeFormat)
 		w.Header().Set("Date", now)
 		w.Write([]byte("\xca\xfe\x81\x05\x00\x01\x00\x01\x00\x00\x00\x00\x00\x00\x02\x00\x01\x00\x00\x10\x00\x01\x00\x00\x00\x00\x00\xa8\xa7\r\nWorkaround a bug causing DNSCrypt-Proxy to expect a response with TransactionID = 0xcafe\r\nRefer to https://github.com/jedisct1/dnscrypt-proxy/issues/526 for details."))
@@ -190,11 +193,12 @@
 }
 
 // Workaround a bug causing Firefox 61-62 to reject responses with Content-Type = application/dns-message
-func (s *Server) patchFirefoxContentType(w http.ResponseWriter, r *http.Request) bool {
+func (s *Server) patchFirefoxContentType(w http.ResponseWriter, r *http.Request, req *DNSRequest) bool {
 	if strings.Contains(r.UserAgent(), "Firefox") && strings.Contains(r.Header.Get("Accept"), "application/dns-udpwireformat") && !strings.Contains(r.Header.Get("Accept"), "application/dns-message") {
 		log.Println("Firefox 61-62 detected. Patching response.")
+		w.Header().Set("Content-Type", "application/dns-udpwireformat")
 		w.Header().Set("Vary", "Accept, User-Agent")
-		w.Header().Set("Content-Type", "application/dns-udpwireformat")
+		req.isTailored = true
 		return true
 	}
 	return false