用于 DNS over HTTPS (DoH) 的 JSON API AND dns-query

源码如下:

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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
package main

import (
"bytes"
"context"
"crypto/tls"
"encoding/base64"
"encoding/binary"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strings"
"sync"
"time"

"github.com/ameshkov/dnscrypt/v2"
"github.com/jedisct1/go-dnsstamps"
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
"github.com/miekg/dns"
quic "github.com/quic-go/quic-go"
"github.com/quic-go/quic-go/http3"
"golang.org/x/net/http2"
"golang.org/x/net/idna"
"gopkg.in/yaml.v3"
)

type Config struct {
DNSServers []string `yaml:"dns_servers"`
LogConfig LogConfig `yaml:"log_config"`
Port string `yaml:"port"`
UseTLS bool `yaml:"use_tls"`
TLSCertFile string `yaml:"tls_cert_file"`
TLSKeyFile string `yaml:"tls_key_file"`
}

type LogConfig struct {
LogToFile bool `yaml:"logEnabled"`
LogFile string `yaml:"log_file"`
MaxAgeDays int `yaml:"max_age_days"`
RotationDays int `yaml:"rotation_days"`
}

var (
config Config
logger *log.Logger
logChannel chan string
wg sync.WaitGroup // 用于等待所有 goroutine 完成
)

func main() {
configFile := flag.String("config", "config.yaml", "YAML配置文件路径")
flag.Parse()

loadConfig(*configFile)
initLogger()
// 启动日志处理goroutine
go logProcessor()

proxy := NewModifyRemoteAddrReverseProxy()

http.HandleFunc("/resolve", proxy.ServeHTTP)
http.HandleFunc("/dns-query", dnsQueryHandler)
fmt.Printf("DNS解析器监听端口 :%s...\n", config.Port)

var err error
if config.UseTLS {
err = http.ListenAndServeTLS(":"+config.Port, config.TLSCertFile, config.TLSKeyFile, nil)
} else {
err = http.ListenAndServe(":"+config.Port, nil)
}

if err != nil {
fmt.Printf("服务器启动失败: %v\n", err)
os.Exit(1)
}
}

type ModifyRemoteAddrReverseProxy struct {
httputil.ReverseProxy
}

func NewModifyRemoteAddrReverseProxy() *ModifyRemoteAddrReverseProxy {
return &ModifyRemoteAddrReverseProxy{
ReverseProxy: httputil.ReverseProxy{},
}
}

// 辅助函数用于移除重复的 DNS 记录
func removeDuplicates(records []dns.RR) []dns.RR {
seen := make(map[string]bool) // 创建一个映射,用于跟踪已经添加的记录
result := []dns.RR{} // 创建一个切片,用于存放去重后的记录
for _, record := range records {
// 使用记录的名称、类型和字符串表示形式生成唯一键
key := fmt.Sprintf("%s-%d-%s", record.Header().Name, record.Header().Rrtype, record.String())
if !seen[key] { // 如果记录还没有被处理过
seen[key] = true // 标记记录为已处理
result = append(result, record) // 将记录添加到结果切片中
}
}
return result // 返回去重后的记录切片
}

func (p *ModifyRemoteAddrReverseProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
name := r.URL.Query().Get("name")
if name == "" {
writeErrorResponse(w, "参数 'name' 是必需的", http.StatusBadRequest)
return
}

// 将中文域名转换为 ASCII(Punycode)
asciiName, err := idna.ToASCII(name)
if err != nil {
writeErrorResponse(w, "域名编码转换失败", http.StatusBadRequest)
return
}

if !strings.HasSuffix(asciiName, ".") {
asciiName += "."
}

clientIP := getClientIP(r)

// 创建两个 DNS 查询,一个查询 A 记录,一个查询 AAAA 记录
queryA := dns.Msg{}
queryA.SetQuestion(dns.Fqdn(asciiName), dns.TypeA)
edns0Subnet := getEDNS0SubnetOption(clientIP)
edns0 := &dns.OPT{Hdr: dns.RR_Header{Name: ".", Rrtype: dns.TypeOPT}, Option: []dns.EDNS0{edns0Subnet}}
queryA.Extra = append(queryA.Extra, edns0)

queryAAAA := dns.Msg{}
queryAAAA.SetQuestion(dns.Fqdn(asciiName), dns.TypeAAAA)
queryAAAA.Extra = append(queryAAAA.Extra, edns0)

msgA, err := queryA.Pack()
if err != nil {
writeErrorResponse(w, fmt.Sprintf("打包A记录DNS查询失败: %v", err), http.StatusInternalServerError)
return
}

msgAAAA, err := queryAAAA.Pack()
if err != nil {
writeErrorResponse(w, fmt.Sprintf("打包AAAA记录DNS查询失败: %v", err), http.StatusInternalServerError)
return
}

b64A := base64.RawURLEncoding.EncodeToString(msgA)
b64AAAA := base64.RawURLEncoding.EncodeToString(msgAAAA)
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()

resultsA := make(chan *http.Response, len(config.DNSServers))
resultsAAAA := make(chan *http.Response, len(config.DNSServers))
var wg sync.WaitGroup

for _, server := range config.DNSServers {
wg.Add(2)
go func(server string) {
defer wg.Done()
resp, err := sendDNSQuery(ctx, server, b64A, 3)
if err != nil {
log.Printf("A记录DNS查询失败: %v", err)
return
}
resultsA <- resp
}(server)

go func(server string) {
defer wg.Done()
resp, err := sendDNSQuery(ctx, server, b64AAAA, 3)
if err != nil {
log.Printf("AAAA记录DNS查询失败: %v", err)
return
}
resultsAAAA <- resp
}(server)
}

go func() {
wg.Wait()
close(resultsA)
close(resultsAAAA)
}()

var responseA, responseAAAA *dns.Msg
var cnameRecords []dns.CNAME

// 处理 A 记录
select {
case resp, ok := <-resultsA:
if ok {
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
resp.Body.Close()
writeErrorResponse(w, fmt.Sprintf("读取A记录响应体失败: %v", err), http.StatusInternalServerError)
return
}
defer resp.Body.Close()

responseA = &dns.Msg{}
err = responseA.Unpack(bodyBytes)
if err != nil {
writeErrorResponse(w, fmt.Sprintf("解包A记录DNS响应失败: %v", err), http.StatusInternalServerError)
return
}

// 从 A 响应中收集 CNAME 记录
for _, ans := range responseA.Answer {
if cname, ok := ans.(*dns.CNAME); ok {
cnameRecords = append(cnameRecords, *cname)
}
}
}
case <-ctx.Done():
writeErrorResponse(w, "A记录查询请求超时或被取消", http.StatusGatewayTimeout)
return
}

// 处理 AAAA 记录
select {
case resp, ok := <-resultsAAAA:
if ok {
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
resp.Body.Close()
writeErrorResponse(w, fmt.Sprintf("读取AAAA记录响应体失败: %v", err), http.StatusInternalServerError)
return
}
defer resp.Body.Close()

responseAAAA = &dns.Msg{}
err = responseAAAA.Unpack(bodyBytes)
if err != nil {
writeErrorResponse(w, fmt.Sprintf("解包AAAA记录DNS响应失败: %v", err), http.StatusInternalServerError)
return
}
}
case <-ctx.Done():
writeErrorResponse(w, "AAAA记录查询请求超时或被取消", http.StatusGatewayTimeout)
return
}

// 如果找到 CNAME 记录,则处理 CNAME 查询
if len(cnameRecords) > 0 {
for _, cname := range cnameRecords {
cnameQueryA := dns.Msg{}
cnameQueryA.SetQuestion(cname.Target, dns.TypeA)

cnameQueryAAAA := dns.Msg{}
cnameQueryAAAA.SetQuestion(cname.Target, dns.TypeAAAA)

// 为 A 类型的查询添加 EDNS0 选项
edns0Subnet := getEDNS0SubnetOption(clientIP)
edns0 := &dns.OPT{Hdr: dns.RR_Header{Name: ".", Rrtype: dns.TypeOPT}, Option: []dns.EDNS0{edns0Subnet}}
cnameQueryA.Extra = append(cnameQueryA.Extra, edns0)
cnameQueryAAAA.Extra = append(cnameQueryAAAA.Extra, edns0)

cnameQueryABytes, err := cnameQueryA.Pack()
if err != nil {
log.Printf("打包 CNAME 查询 A 记录失败: %v", err)
continue
}

cnameQueryAAAABytes, err := cnameQueryAAAA.Pack()
if err != nil {
log.Printf("打包 CNAME 查询 AAAA 记录失败: %v", err)
continue
}

var wgCNAME sync.WaitGroup
resultsCNAMEA := make(chan *http.Response, len(config.DNSServers))
resultsCNAMEAAAA := make(chan *http.Response, len(config.DNSServers))
wgCNAME.Add(2)
go func() {
defer wgCNAME.Done()
for _, server := range config.DNSServers {
resp, err := sendDNSQuery(ctx, server, base64.RawURLEncoding.EncodeToString(cnameQueryABytes), 3)
if err != nil {
log.Printf("CNAME记录A查询失败: %v", err)
continue
}
resultsCNAMEA <- resp
}
}()

go func() {
defer wgCNAME.Done()
for _, server := range config.DNSServers {
resp, err := sendDNSQuery(ctx, server, base64.RawURLEncoding.EncodeToString(cnameQueryAAAABytes), 3)
if err != nil {
log.Printf("CNAME记录AAAA查询失败: %v", err)
continue
}
resultsCNAMEAAAA <- resp
}
}()

wgCNAME.Wait()
close(resultsCNAMEA)
close(resultsCNAMEAAAA)

// 从 CNAME 响应中收集 A 和 AAAA 记录
for resp := range resultsCNAMEA {
bodyBytes, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
log.Printf("读取 CNAME A 记录响应体失败: %v", err)
continue
}
if err := responseA.Unpack(bodyBytes); err != nil {
log.Printf("解包 CNAME A 记录响应失败: %v", err)
continue
}
// 将结果添加到 cnameRecords
for _, ans := range responseA.Answer {
if cname, ok := ans.(*dns.CNAME); ok {
cnameRecords = append(cnameRecords, *cname)
}
// 收集 A 记录
if a, ok := ans.(*dns.A); ok {
responseA.Answer = append(responseA.Answer, a)
}
}
}

for resp := range resultsCNAMEAAAA {
bodyBytes, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
log.Printf("读取 CNAME AAAA 记录响应体失败: %v", err)
continue
}
if err := responseAAAA.Unpack(bodyBytes); err != nil {
log.Printf("解包 CNAME AAAA 记录响应失败: %v", err)
continue
}
// 收集 AAAA 记录
for _, ans := range responseAAAA.Answer {
if aaaa, ok := ans.(*dns.AAAA); ok {
responseAAAA.Answer = append(responseAAAA.Answer, aaaa)
}
}
}
}
}

// 准备最终的 DNS 响应
if net.ParseIP(clientIP).To4() != nil {
mergedResponse := &dns.Msg{}
if responseA != nil {
mergedResponse.Answer = append(mergedResponse.Answer, responseA.Answer...)
}
// 去重处理
mergedResponse.Answer = removeDuplicates(mergedResponse.Answer)
jsonResponse := convertDnsMsgToJSON(*mergedResponse)
jsonOutput, err := json.MarshalIndent(jsonResponse, "", " ")
if err != nil {
writeErrorResponse(w, fmt.Sprintf("序列化JSON失败: %v", err), http.StatusInternalServerError)
return
}
logDNSQuery(name, config.DNSServers, *mergedResponse, clientIP)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(jsonOutput)
} else {
// 合并A和AAAA的结果
mergedResponse := &dns.Msg{}
if responseA != nil {
mergedResponse.Answer = append(mergedResponse.Answer, responseA.Answer...)
}
if responseAAAA != nil {
mergedResponse.Answer = append(mergedResponse.Answer, responseAAAA.Answer...)
}

// 去重处理
mergedResponse.Answer = removeDuplicates(mergedResponse.Answer)

jsonResponse := convertDnsMsgToJSON(*mergedResponse)
jsonOutput, err := json.MarshalIndent(jsonResponse, "", " ")
if err != nil {
writeErrorResponse(w, fmt.Sprintf("序列化JSON失败: %v", err), http.StatusInternalServerError)
return
}
logDNSQuery(name, config.DNSServers, *mergedResponse, clientIP)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(jsonOutput)
}
}

func dnsQueryHandler(w http.ResponseWriter, r *http.Request) {
var dnsQuery []byte
var err error

// 创建一个带超时的 context
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()

switch r.Method {
case http.MethodGet:
dnsParam := r.URL.Query().Get("dns")
if dnsParam == "" {
writeErrorResponse(w, "缺少 'dns' 查询参数", http.StatusBadRequest)
return
}

dnsQuery, err = base64.RawURLEncoding.DecodeString(dnsParam)
if err != nil {
writeErrorResponse(w, "解码 'dns' 参数失败", http.StatusBadRequest)
return
}

case http.MethodPost:
dnsQuery, err = io.ReadAll(r.Body)
if err != nil {
writeErrorResponse(w, "读取请求体失败", http.StatusBadRequest)
return
}

default:
writeErrorResponse(w, "方法不被允许", http.StatusMethodNotAllowed)
return
}

msg := new(dns.Msg)
err = msg.Unpack(dnsQuery)
if err != nil {
writeErrorResponse(w, "解析 DNS 查询失败", http.StatusBadRequest)
return
}

clientIP := getClientIP(r)
query := dns.Msg{}
query.SetQuestion(dns.Fqdn(msg.Question[0].Name), msg.Question[0].Qtype)
query.Id = msg.Id

// 仅在查询类型为 A 或 AAAA 时添加 EDNS0 选项
if msg.Question[0].Qtype == dns.TypeA || msg.Question[0].Qtype == dns.TypeAAAA {
edns0Subnet := getEDNS0SubnetOption(clientIP)
edns0 := &dns.OPT{Hdr: dns.RR_Header{Name: ".", Rrtype: dns.TypeOPT}, Option: []dns.EDNS0{edns0Subnet}}
query.Extra = append(query.Extra, edns0)
}

queryBytes, err := query.Pack()
if err != nil {
log.Printf("打包查询失败: %v\n", err)
writeErrorResponse(w, fmt.Sprintf("打包查询失败: %v", err), http.StatusInternalServerError)
return
}

// Helper function to send DNS queries
sendQuery := func(queryBytes []byte, wg *sync.WaitGroup, results chan<- *http.Response) {
defer wg.Done()
for _, server := range config.DNSServers {
resp, err := sendDNSQuery(ctx, server, base64.RawURLEncoding.EncodeToString(queryBytes), 3)
if err != nil {
log.Printf("%s 记录 DNS 查询失败: %v", dns.TypeToString[msg.Question[0].Qtype], err)
continue
}
results <- resp
}
}

var wg sync.WaitGroup
results := make(chan *http.Response, len(config.DNSServers))
wg.Add(1)
go sendQuery(queryBytes, &wg, results)

wg.Wait()
close(results)

var responseMsg dns.Msg
var cnameRecords []dns.CNAME
foundARecord := false

for resp := range results {
bodyBytes, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
log.Printf("读取 %s 记录响应体失败: %v", dns.TypeToString[msg.Question[0].Qtype], err)
continue
}
if err := responseMsg.Unpack(bodyBytes); err != nil {
log.Printf("解包 %s 记录响应失败: %v", dns.TypeToString[msg.Question[0].Qtype], err)
continue
}

// 处理 CNAME 记录
for _, ans := range responseMsg.Answer {
if cname, ok := ans.(*dns.CNAME); ok {
cnameRecords = append(cnameRecords, *cname)
}
}

// 检查是否有 A 或 AAAA 记录
for _, ans := range responseMsg.Answer {
if ans.Header().Rrtype == dns.TypeA || ans.Header().Rrtype == dns.TypeAAAA {
foundARecord = true
break
}
}

if foundARecord {
break
}
}

// 如果找到 CNAME 记录,则进行新的查询
if len(cnameRecords) > 0 && !foundARecord {
for _, cname := range cnameRecords {
cnameQuery := dns.Msg{}
cnameQuery.SetQuestion(cname.Target, msg.Question[0].Qtype)
cnameQuery.Id = msg.Id

// Add EDNS0 option if the query type is A or AAAA
if msg.Question[0].Qtype == dns.TypeA || msg.Question[0].Qtype == dns.TypeAAAA {
edns0Subnet := getEDNS0SubnetOption(clientIP)
edns0 := &dns.OPT{Hdr: dns.RR_Header{Name: ".", Rrtype: dns.TypeOPT}, Option: []dns.EDNS0{edns0Subnet}}
cnameQuery.Extra = append(cnameQuery.Extra, edns0)
}

cnameQueryBytes, err := cnameQuery.Pack()
if err != nil {
log.Printf("打包 CNAME 查询失败: %v\n", err)
continue
}

var wgCNAME sync.WaitGroup
resultsCNAME := make(chan *http.Response, len(config.DNSServers))
wgCNAME.Add(1)
go sendQuery(cnameQueryBytes, &wgCNAME, resultsCNAME)

wgCNAME.Wait()
close(resultsCNAME)

for resp := range resultsCNAME {
bodyBytes, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
log.Printf("读取 %s 记录响应体失败: %v", dns.TypeToString[msg.Question[0].Qtype], err)
continue
}
if err := responseMsg.Unpack(bodyBytes); err != nil {
log.Printf("解包 %s 记录响应失败: %v", dns.TypeToString[msg.Question[0].Qtype], err)
continue
}

// 检查是否有 A 或 AAAA 记录
for _, ans := range responseMsg.Answer {
if ans.Header().Rrtype == dns.TypeA || ans.Header().Rrtype == dns.TypeAAAA {
foundARecord = true
break
}
}

if foundARecord {
break
}
}

if foundARecord {
break
}
}
}

// 返回响应
logDNSQuery(msg.Question[0].Name, config.DNSServers, responseMsg, clientIP)
responseBytes, err := responseMsg.Pack()
if err != nil {
writeErrorResponse(w, fmt.Sprintf("打包 %s 记录响应失败: %v", dns.TypeToString[msg.Question[0].Qtype], err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/dns-message")
w.WriteHeader(http.StatusOK)
w.Write(responseBytes)
}

func getEDNS0SubnetOption(ip string) *dns.EDNS0_SUBNET {
subnet := &dns.EDNS0_SUBNET{
Code: dns.EDNS0SUBNET,
SourceScope: 0,
Address: net.ParseIP(ip),
}
if subnet.Address.To4() != nil {
subnet.Family = 1
subnet.SourceNetmask = 32
} else if subnet.Address.To16() != nil {
subnet.Family = 2
subnet.SourceNetmask = 128
}
return subnet
}

// writeErrorResponse 使用setJSONResponse来发送包含错误信息的JSON响应。
func headerWritten(w http.ResponseWriter) bool {
h := w.Header()
if len(h) == 0 {
return false
}
for _, v := range h {
if len(v) > 0 {
return true
}
}
return false
}

func setJSONResponse(w http.ResponseWriter, statusCode int, data interface{}) {
// 设置响应头
if w.Header().Get("Content-Type") == "" {
w.Header().Set("Content-Type", "application/json")
}

// 如果响应头尚未写入,则写入状态码
if !headerWritten(w) {
w.WriteHeader(statusCode)
}

// 尝试编码数据为 JSON 并写入响应
err := json.NewEncoder(w).Encode(data)
if err != nil {
// logger.Printf("Failed to encode JSON response: %v", err)
// 如果编码失败,写入错误信息
if !headerWritten(w) {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}
}

func writeErrorResponse(w http.ResponseWriter, message string, statusCode int) {
errorResponse := map[string]string{"error": message}
setJSONResponse(w, statusCode, errorResponse)
}

// 获取客户端 IP 地址
func getClientIP(r *http.Request) string {
if ip := r.Header.Get("X-Forwarded-For"); ip != "" {
ips := strings.Split(ip, ",")
if len(ips) > 0 {
return strings.TrimSpace(ips[0])
}
}
if ip := r.Header.Get("X-Real-Ip"); ip != "" {
return ip
}
if ip, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
return ip
}
// 如果 SplitHostPort 失败,可能是因为 RemoteAddr 不包含端口号,直接返回
return r.RemoteAddr
}

func sendDNSQuery(ctx context.Context, dnsServer, b64 string, retries int) (*http.Response, error) {
var resp *http.Response
var err error

for attempt := 0; attempt < retries; attempt++ {
resp, err = executeDNSQuery(ctx, dnsServer, b64)
if err == nil {
return resp, nil
}
// logger.Printf("DNS 查询失败 (尝试 %d/%d): %v\n", attempt+1, retries, err)
time.Sleep(10 * time.Second) // 等待一段时间后重试
}

return nil, fmt.Errorf("所有重试均失败: %v", err)
}

func executeDNSQuery(ctx context.Context, dnsServer, b64 string) (*http.Response, error) {
parsedURL, err := url.Parse(dnsServer)
if err != nil {
return nil, err
}

switch parsedURL.Scheme {
case "https":
return sendDoHQuery(ctx, dnsServer, b64)
case "tls":
return sendDoTQuery(ctx, dnsServer, b64)
case "tcp":
return sendTCPQuery(ctx, dnsServer, b64)
case "udp":
return sendUDPQuery(ctx, dnsServer, b64)
case "quic":
return sendDoQQuery(ctx, dnsServer, b64)
case "h3":
return sendH3Query(ctx, dnsServer, b64)
case "sdns":
return sendCryptQuery(ctx, dnsServer, b64)
default:
return nil, fmt.Errorf("不支持的协议: %s", parsedURL.Scheme)
}
}

func sendDoHQuery(ctx context.Context, dnsServer, b64 string) (*http.Response, error) {
// 公共的传输配置
tlsConfig := &tls.Config{InsecureSkipVerify: true}
timeout := 10 * time.Second
expectContinueTimeout := 1 * time.Second
maxIdleConns := 200
maxIdleConnsPerHost := 10

// HTTP/3 客户端
http3Transport := &http3.Transport{
TLSClientConfig: tlsConfig,
}
client := &http.Client{
Timeout: timeout,
Transport: http3Transport,
}

// 构建请求 URL
reqURL := dnsServer + "?dns=" + b64
req, err := http.NewRequestWithContext(ctx, "GET", reqURL, nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/dns-message")

// 尝试发送 HTTP/3 请求
resp, err := client.Do(req)
if err == nil && resp.StatusCode == http.StatusOK {
return resp, nil
}

// HTTP/2 Transport 配置
http2Transport := &http.Transport{
TLSClientConfig: tlsConfig,
TLSHandshakeTimeout: timeout,
ExpectContinueTimeout: expectContinueTimeout,
MaxIdleConns: maxIdleConns,
MaxIdleConnsPerHost: maxIdleConnsPerHost,
}
if err := http2.ConfigureTransport(http2Transport); err != nil {
return nil, fmt.Errorf("无法配置 HTTP/2: %v", err)
}
client.Transport = http2Transport

resp, err = client.Do(req)
if err == nil && resp.StatusCode == http.StatusOK {
return resp, nil
}

// HTTP/1.1 Transport 配置
http1Transport := &http.Transport{
TLSClientConfig: tlsConfig,
TLSHandshakeTimeout: timeout,
ExpectContinueTimeout: expectContinueTimeout,
MaxIdleConns: maxIdleConns,
MaxIdleConnsPerHost: maxIdleConnsPerHost,
ForceAttemptHTTP2: false, // 禁用 HTTP/2 以使用 HTTP/1.1
}
client.Transport = http1Transport

resp, err = client.Do(req)
if err != nil {
return nil, fmt.Errorf("DoH查询失败: %v", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("DoH查询失败, 状态码: %d", resp.StatusCode)
}

return resp, nil
}

func sendDoTQuery(ctx context.Context, dnsServer, b64 string) (*http.Response, error) {
parsedURL, err := url.Parse(dnsServer)
if err != nil {
return nil, err
}

host := parsedURL.Host
if !strings.Contains(host, ":") {
host += ":853" // 默认DoT端口
}

// 使用 DialContext 进行连接
dialer := &net.Dialer{}
conn, err := dialer.DialContext(ctx, "tcp", host)
if err != nil {
return nil, err
}
defer conn.Close()

// 创建 TLS 客户端连接
tlsConn := tls.Client(conn, &tls.Config{
InsecureSkipVerify: true,
})
defer tlsConn.Close()

query, err := base64.RawURLEncoding.DecodeString(b64)
if err != nil {
return nil, err
}

lengthField := make([]byte, 2)
lengthField[0] = byte(len(query) >> 8)
lengthField[1] = byte(len(query) & 0xff)

_, err = tlsConn.Write(lengthField)
if err != nil {
return nil, err
}
_, err = tlsConn.Write(query)
if err != nil {
return nil, err
}

respLength := make([]byte, 2)
_, err = io.ReadFull(tlsConn, respLength)
if err != nil {
return nil, err
}
respLen := int(respLength[0])<<8 | int(respLength[1])

resp := make([]byte, respLen)
_, err = io.ReadFull(tlsConn, resp)
if err != nil {
return nil, err
}

tempResp := &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(strings.NewReader(string(resp))),
}

return tempResp, nil
}

func sendTCPQuery(ctx context.Context, dnsServer, b64 string) (*http.Response, error) {
parsedURL, err := url.Parse(dnsServer)
if err != nil {
return nil, err
}

host := parsedURL.Host
if !strings.Contains(host, ":") {
host += ":53" // 默认TCP端口
}

dialer := &net.Dialer{}
conn, err := dialer.DialContext(ctx, "tcp", host)
if err != nil {
return nil, err
}
defer conn.Close()

query, err := base64.RawURLEncoding.DecodeString(b64)
if err != nil {
return nil, err
}

lengthField := make([]byte, 2)
lengthField[0] = byte(len(query) >> 8)
lengthField[1] = byte(len(query) & 0xff)

_, err = conn.Write(lengthField)
if err != nil {
return nil, err
}
_, err = conn.Write(query)
if err != nil {
return nil, err
}

respLength := make([]byte, 2)
_, err = io.ReadFull(conn, respLength)
if err != nil {
return nil, err
}
respLen := int(respLength[0])<<8 | int(respLength[1])

resp := make([]byte, respLen)
_, err = io.ReadFull(conn, resp)
if err != nil {
return nil, err
}

tempResp := &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(strings.NewReader(string(resp))),
}
return tempResp, nil
}

func sendUDPQuery(ctx context.Context, dnsServer, b64 string) (*http.Response, error) {
parsedURL, err := url.Parse(dnsServer)
if err != nil {
return nil, err
}

host := parsedURL.Host
if !strings.Contains(host, ":") {
host += ":53" // 默认UDP端口
}

// 设置 UDP 连接的上下文超时
dialer := &net.Dialer{}
conn, err := dialer.DialContext(ctx, "udp", host)
if err != nil {
return nil, err
}
defer conn.Close()

// 解码 base64 查询内容
query, err := base64.RawURLEncoding.DecodeString(b64)
if err != nil {
return nil, err
}

// 发送查询请求
_, err = conn.Write(query)
if err != nil {
return nil, err
}

// 设置读取超时,防止长时间阻塞
conn.SetReadDeadline(time.Now().Add(2 * time.Second))

resp := make([]byte, 512) // DNS 响应通常小于 512 字节
n, err := conn.Read(resp)
if err != nil {
return nil, err
}

// 返回 http.Response 对象
tempResp := &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewReader(resp[:n])),
}

return tempResp, nil
}

// QUIC 是用于通过 QUIC 协议进行 DNS 查询的结构体
type QUIC struct {
Server string
TLSConfig *tls.Config
PMTUD bool
ReuseConn bool
conn quic.Connection // 接口类型,而不是指针
}

// setServerName 设置 TLS 配置中的服务器名称
func (q *QUIC) setServerName() {
host, _, err := net.SplitHostPort(q.Server)
if err != nil {
fmt.Printf("无效的 QUIC 服务器地址: %s", err)
}
q.TLSConfig.ServerName = host
}

// sendDoQQuery 将 base64 编码的 DNS 查询发送到 QUIC 服务器并返回响应
func sendDoQQuery(ctx context.Context, dnsServer, b64 string) (*http.Response, error) {
parsedURL, err := url.Parse(dnsServer)
if err != nil {
return nil, err
}

host := parsedURL.Host
if !strings.Contains(host, ":") {
host += ":853" // 默认 QUIC 端口
}

// 解码 base64 查询内容
query, err := base64.RawURLEncoding.DecodeString(b64)
if err != nil {
return nil, err
}

// 创建 QUIC 连接和 TLS 配置
tlsConfig := &tls.Config{
ServerName: host,
InsecureSkipVerify: true, // 测试时可以使用 true,生产时应关闭
NextProtos: []string{"doq"},
SessionTicketsDisabled: false,
}

quicConfig := &quic.Config{
DisablePathMTUDiscovery: true, // 默认启用 PMTU
KeepAlivePeriod: time.Second * 20, // 默认值为 30s
TokenStore: newQUICTokenStore(),
}

// 设置 DNS over QUIC 客户端
quicClient := &QUIC{
Server: host,
TLSConfig: tlsConfig,
}

// 建立 QUIC 连接
if quicClient.conn == nil || !quicClient.ReuseConn {
quicClient.setServerName()

conn, err := quic.DialAddr(
ctx,
host,
tlsConfig,
quicConfig,
)
if err != nil {
return nil, fmt.Errorf("打开到 %s 的 QUIC 会话失败: %v", host, err)
}
quicClient.conn = conn
}

// 打开 QUIC 流并发送查询
stream, err := quicClient.conn.OpenStream()
if err != nil {
return nil, fmt.Errorf("打开 QUIC 流失败: %v", err)
}

// 发送查询
_, err = stream.Write(addPrefix(query))
if err != nil {
return nil, fmt.Errorf("无法写入 QUIC 流: %w", err)
}

// 关闭流并读取响应
_ = stream.Close()

respBuf, err := io.ReadAll(stream)
if err != nil {
return nil, fmt.Errorf("从 QUIC 流读取响应失败: %v", err)
}
if len(respBuf) == 0 {
return nil, fmt.Errorf("从 %s 收到空响应", host)
}

// 解包 DNS 响应
m := new(dns.Msg)
err = m.Unpack(respBuf[2:]) // 跳过前 2 个字节的长度前缀
if err != nil {
return nil, fmt.Errorf("DNS 响应解包失败: %w", err)
}

// 重新打包 DNS 响应
packedResp, err := m.Pack()
if err != nil {
return nil, fmt.Errorf("DNS 响应打包失败: %w", err)
}

// 构造 HTTP 响应
tempResp := &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewReader(packedResp)),
}

return tempResp, nil
}

func addPrefix(b []byte) (m []byte) {
m = make([]byte, 2+len(b))
binary.BigEndian.PutUint16(m, uint16(len(b)))
copy(m[2:], b)

return m
}

func newQUICTokenStore() (s quic.TokenStore) {
return quic.NewLRUTokenStore(1, 10)
}

func sendH3Query(ctx context.Context, dnsServer, b64 string) (*http.Response, error) {
tlsConfig := &tls.Config{InsecureSkipVerify: true}
timeout := 10 * time.Second

if strings.HasPrefix(dnsServer, "h3://") {
dnsServer = "https://" + dnsServer[5:]
}

// HTTP/3 客户端
http3Transport := &http3.Transport{
TLSClientConfig: tlsConfig,
}
client := &http.Client{
Timeout: timeout,
Transport: http3Transport,
}

// 构建请求 URL
reqURL := dnsServer + "?dns=" + b64
req, err := http.NewRequestWithContext(ctx, "GET", reqURL, nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/dns-message")

// 尝试发送 HTTP/3 请求
resp, err := client.Do(req)
if err == nil && resp.StatusCode == http.StatusOK {
// return resp, nil
}
return resp, nil
}

func sendCryptQuery(ctx context.Context, dnsServer, b64 string) (*http.Response, error) {
// 解码 base64 编码的 DNS 查询
queryBytes, err := base64.RawURLEncoding.DecodeString(b64)
if err != nil {
return nil, fmt.Errorf("base64 解码查询失败: %w", err)
}

// 初始化 DNSCrypt 客户端
client := &dnscrypt.Client{
Timeout: 5 * time.Second, // 设置超时时间为 5 秒
Net: "udp", // 默认使用 UDP
}

// 解析 DNSCrypt stamp
stamp, err := dnsstamps.NewServerStampFromString(dnsServer)
if err != nil {
return nil, fmt.Errorf("解析 DNSCrypt stamp 失败: %w", err)
}

// 定义函数用于切换协议
dialWithFallback := func() (*dnscrypt.ResolverInfo, error) {
// 尝试 UDP 连接
resolver, err := client.Dial(stamp.String())
if err == nil {
return resolver, nil
}
// 切换到 TCP
client.Net = "tcp"
resolver, err = client.Dial(stamp.String())
if err == nil {
return resolver, nil
}
return nil, fmt.Errorf("UDP 和 TCP 均连接失败: %w", err)
}

// 连接 DNSCrypt 服务器,自动切换 UDP -> TCP
resolver, err := dialWithFallback()
if err != nil {
return nil, fmt.Errorf("连接 DNSCrypt 服务器失败(UDP 和 TCP 均失败): %w", err)
}

// 将 queryBytes 转换为 *dns.Msg
msg := &dns.Msg{}
if err = msg.Unpack(queryBytes); err != nil {
return nil, fmt.Errorf("解包 DNS 查询失败: %w", err)
}

// 使用 DNSCrypt 客户端发送查询
respMsg, err := client.Exchange(msg, resolver)
if err != nil {
return nil, fmt.Errorf("DNSCrypt 查询失败: %w", err)
}

// 使用 ctx 超时控制,保证在查询响应过程中不中断
select {
case <-ctx.Done():
// 如果 ctx 被取消或超时,返回错误
return nil, fmt.Errorf("请求被取消或超时: %w", ctx.Err())
default:
// 否则继续处理响应
}

// 将响应转换为字节切片
packedResp, err := respMsg.Pack()
if err != nil {
return nil, fmt.Errorf("打包 DNS 响应失败: %w", err)
}

// 构造 HTTP 响应并返回
tempResp := &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewReader(packedResp)),
}

return tempResp, nil
}

func convertDnsMsgToJSON(msg dns.Msg) map[string]interface{} {
// 初始化返回的JSON结构
result := map[string]interface{}{
"Status": msg.Rcode, // DNS响应码
"TC": msg.Truncated, // 是否被截断
"RD": msg.RecursionDesired, // 是否需要递归
"RA": msg.RecursionAvailable, // 服务器是否支持递归
"AD": msg.AuthenticatedData, // 数据是否被验证
"CD": msg.CheckingDisabled, // 是否禁用检查
"Question": map[string]interface{}{}, // 问题部分
"Answer": []map[string]interface{}{}, // 回答部分
}

// 处理问题部分,如果存在的话
if len(msg.Question) > 0 {
q := msg.Question[0]
result["Question"] = map[string]interface{}{
"name": q.Name, // 域名
"type": q.Qtype, // 查询类型
}
}

// 遍历回答部分,处理每一条记录
for _, a := range msg.Answer {
var data string
switch a.Header().Rrtype {
case dns.TypeA:
data = a.(*dns.A).A.String() // 处理A记录
case dns.TypeAAAA:
data = a.(*dns.AAAA).AAAA.String() // 处理AAAA记录
case dns.TypeCNAME:
data = a.(*dns.CNAME).Target // 处理CNAME记录
default:
data = a.String() // 其他记录类型
}

// 处理多余的`\t`字符
dataParts := strings.Split(data, "\t")
if len(dataParts) > 1 {
data = dataParts[len(dataParts)-1]
}

// 添加记录到结果中
result["Answer"] = append(result["Answer"].([]map[string]interface{}), map[string]interface{}{
"name": a.Header().Name, // 记录名
"TTL": a.Header().Ttl, // 生存时间
"type": a.Header().Rrtype, // 记录类型
"data": data, // 记录内容
})
}

return result // 返回结果
}

func logDNSQuery(name string, servers []string, response dns.Msg, clientIP string) {
if config.LogConfig.LogToFile {
if config.LogConfig.LogFile != "" {
logEntry := fmt.Sprintf("查询名称: %s, 解析服务器: %v, 客户端IP: %s, 响应: %v", name, servers, clientIP, response)
select {
case logChannel <- logEntry:
default:
fmt.Println("日志通道已满,无法记录日志条目")
}
} else {
logEntry := fmt.Sprintf("查询名称: %s, 解析服务器: %v, 客户端IP: %s, 响应: %v", name, servers, clientIP, response)
select {
case logChannel <- logEntry:
default:
fmt.Println("日志通道已满,无法记录日志条目")
}
}
} else {
log.SetOutput(io.Discard)
}
}

func loadConfig(file string) {
yamlFile, err := os.ReadFile(file)
if err != nil {
fmt.Printf("读取YAML文件失败: %v\n", err)
os.Exit(1)
}

err = yaml.Unmarshal(yamlFile, &config)
if err != nil {
fmt.Printf("解析YAML失败: %v\n", err)
os.Exit(1)
}
}

func initLogger() {
logChannel = make(chan string, 10000)
if config.LogConfig.LogToFile {
if config.LogConfig.LogFile == "" {
logger = log.New(os.Stdout, "", log.LstdFlags)
} else {
logPath := config.LogConfig.LogFile
logRotate, err := rotatelogs.New(
logPath+".%Y%m%d%H%M",
rotatelogs.WithMaxAge(time.Duration(config.LogConfig.MaxAgeDays)*24*time.Hour),
rotatelogs.WithRotationTime(time.Duration(config.LogConfig.RotationDays)*24*time.Hour),
)
if err != nil {
fmt.Printf("创建日志切割器失败: %v\n", err)
logger = log.New(os.Stdout, "", log.LstdFlags)
} else {
logger = log.New(logRotate, "", log.LstdFlags)
}
}
} else {
// 如果 LogToFile 是 false,禁用日志记录
logger = log.New(io.Discard, "", log.LstdFlags)
}
}

func logProcessor() {
defer wg.Done()

for logEntry := range logChannel {
logger.Println(logEntry)
}
}


配置

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
#DNS服务器地址
dns_servers:
- https://dns.alidns.com/dns-query
- tls://223.5.5.5
- tcp://47.94.105.9:5353
- udp://114.114.114.114
- h3://dns.alidns.com/dns-query
- quic://dns.adguard-dns.com
- sdns://AQIAAAAAAAAAETk0LjE0MC4xNC4xNDo1NDQzINErR_JS3PLCu_iZEIbq95zkSV2LFsigxDIuUso_OQhzIjIuZG5zY3J5cHQuZGVmYXVsdC5uczEuYWRndWFyZC5jb20
# 监听端口
port: "8080"
# 开始是否使用TLS
use_tls: false
# 证书文件地址
tls_cert_file: ""
# 密钥文件地址
tls_key_file: ""
log_config:
# 开始是否记录日志
logEnabled: true
# 日志文件输出地址 为空是标准输出
log_file:
# 日志保留7天
max_age_days: 7
# 每天生成一个日志文件
rotation_days: 1

编译

1
2
3
go mod init dns
go mod tidy
go build -o dns 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
# 启动服务
/usr/lib/systemd/system/dns.service
[Unit]
Description=dns - high performance web server
After=network.target

[Service]
LimitCORE=infinity
LimitNOFILE=100000
LimitNPROC=100000
ExecStart=/usr/local/bin/dns -config=/app/config.yaml
PrivateTmp=true

[Install]
WantedBy=multi-user.target

# 查看配置参数CMD的
/usr/local/bin/dns -help
# 设置开机启动
systemctl enable dns
# 启动
systemctl start dns

# nginx 代理
upstream dns {
least_conn;
server 127.0.0.1:9090 max_fails=3 fail_timeout=30s;
keepalive 10000;
}

location /resolve {
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $clientRealIp;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_ssl_session_reuse off;
proxy_ssl_server_name on;
proxy_ignore_client_abort on;
proxy_connect_timeout 120;
proxy_send_timeout 120;
proxy_read_timeout 120;
proxy_buffer_size 8k;
proxy_buffers 8 32k;
proxy_busy_buffers_size 128k;
proxy_http_version 1.1;
proxy_set_header Accept-Encoding "";
proxy_pass http://dns;
}
location /dns-query {
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $clientRealIp;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_ssl_session_reuse off;
proxy_ssl_server_name on;
proxy_ignore_client_abort on;
proxy_connect_timeout 120;
proxy_send_timeout 120;
proxy_read_timeout 120;
proxy_buffer_size 8k;
proxy_buffers 8 32k;
proxy_busy_buffers_size 128k;
proxy_http_version 1.1;
proxy_set_header Accept-Encoding "";
proxy_pass http://dns;
}
# 访问
https://域名/resolve?name=www.qq.com
# 输出内容
{
"AD": false,
"Answer": [
{
"TTL": 1,
"data": "ins-r23tsuuf.ias.tencent-cloud.net.",
"name": "www.qq.com.",
"type": 5
},
{
"TTL": 1,
"data": "121.14.77.201",
"name": "ins-r23tsuuf.ias.tencent-cloud.net.",
"type": 1
},
{
"TTL": 1,
"data": "121.14.77.221",
"name": "ins-r23tsuuf.ias.tencent-cloud.net.",
"type": 1
}
],
"CD": false,
"Question": {
"name": "www.qq.com.",
"type": 1
},
"RA": false,
"RD": true,
"Status": 0,
"TC": false
}
dns-query 接口测试
curl --doh-url https://域名/dns-query https://www.baidu.com/
可以进程配置tls或者ng 配置tls 不配置 doh 不能使用