Centos7 内核编译及 RPM 包的制作

源码编译安装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
yum -y groups install "Development Tools"
yum install ncurses-devel make gcc bc openssl-devel

wget https://mirrors.edge.kernel.org/pub/linux/kernel/v4.x/linux-4.14.105.tar.gz

tar zxvf linux-4.14.105.tar.gz

cp /boot/config-`uname -r` ./linux-4.14.105/.config

cd linux-4.14.105

make menuconfig #进入后直接保存保存配置
make oldconfig

make kernelversion
make INSTALL_MOD_STRIP=1 all -j32

make INSTALL_MOD_STRIP=1 modules_install
# ls -lh /lib/modules

make INSTALL_MOD_STRIP=1 install
# ls -lh /boot

通过以上命令可以完成内核的编译。

Use the INSTALL_MOD_STRIP option for removing debugging symbols:

1
make INSTALL_MOD_STRIP=1 modules_install

打包 ——RPM

1
yum -y install rpm-build 
1
make rpm-pkg -j32 

编译完成在 ~/rpmbuild/RPMS/x86_64/ 目录下生成 rpm 安装包:

1
2
3
4
ls -lh ~/rpmbuild/RPMS/x86_64/
-rw-r--r-- 1 root root 515M 10月 10 06:28 /root/rpmbuild/RPMS/x86_64/kernel-4.14.105-1.x86_64.rpm
-rw-r--r-- 1 root root 135M 10月 10 06:30 /root/rpmbuild/RPMS/x86_64/kernel-devel-4.14.105-1.x86_64.rpm
-rw-r--r-- 1 root root 1.2M 10月 10 06:28 /root/rpmbuild/RPMS/x86_64/kernel-headers-4.14.105-1.x86_64.rpm

为啥 rpm 包这么大,官方 rpm 包一般五六十兆大小???

主要是编译生成的 ko 文件增大所致,应该包含了 debug 信息和符号表
make INSTALL_MOD_STRIP=1 rpm-pkg

安装

1
rpm -iUv ~/rpmbuild/RPMS/x86_64/kernel-*.rpm
1
yum install ~/rpmbuild/RPMS/x86_64/kernel-*.rpm

内核编译命令

编译内核生成 centos rpm 或 ubuntu deb 包

1
2
3
4
5
make rpm          #生成带源码的RPM包
make rpm-pkg #生成带源码的RPM包,同上
make binrpm-pkg #生成包含内核和驱动的RMP包
make deb-pkg #生成带源码的debian包
make bindeb-pkg #生成包含内核和驱动的debian包

rpm-pkg: 每次编译前会先 clean, 重复编译会很慢

linux 内核 make help:

1
2
3
4
5
6
7
8
9
10
11
12
13
Kernel packaging:
rpm-pkg - Build both source and binary RPM kernel packages
binrpm-pkg - Build only the binary kernel RPM package
deb-pkg - Build both source and binary deb kernel packages
bindeb-pkg - Build only the binary kernel deb package
tar-pkg - Build the kernel as an uncompressed tarball
targz-pkg - Build the kernel as a gzip compressed tarball
tarbz2-pkg - Build the kernel as a bzip2 compressed tarball
tarxz-pkg - Build the kernel as a xz compressed tarball
perf-tar-src-pkg - Build perf-4.14.105.tar source tarball
perf-targz-src-pkg - Build perf-4.14.105.tar.gz source tarball
perf-tarbz2-src-pkg - Build perf-4.14.105.tar.bz2 source tarball
perf-tarxz-src-pkg - Build perf-4.14.105.tar.xz source tarball
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
make clean            #删除编译中间文件,但是保留配置
make mrproper #删除包括配置文件的所有构建文件
make distclean #执行mrproper所做的一切,并删除备份文件

make menuconfig #文本图形方式配置内核
make oldconfig #基于当前的.config文件提示更新内核
make defconfig #生成默认的内核配置
make allmodconfig #所有的可选的选项构建成模块
make allyesconfig #生成全部选择是内核配置
make noconfig #生成全部选择否的内核配置

make all #构建所有目标
make bzImage #构建内核映像
make modules #构建所有驱动
make dir/ #构建指定目录
make dir/file.[s|o|i] #构建指定文件
make dir/file.ko #构建指定驱动

make install #安装内核
make modules_install #安装驱动

make xmldocs #生成xml文档
make pdfdocs #生成pdf文档
maek htmldocs #生成html文档

参考

我需要内核的源代码

我需要创建一个自设的内核

Building Source RPM as non-root under CentOS*

kernel 4.18.18 rpm 制作

Linux kernel 编译指南

报错处理

  1. npm ERR! ssh_exchange_identification: Connection closed by remote host
    npm ERR! fatal: Could not read from remote repository.

    MaxStartups 100

# 在sshd_config下加入
KexAlgorithms curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group14-sha1

Centos 7.9 升级openssh 9.8p1

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
#/bin/bash
now=`date +%Y%m%d`
yum install -y gcc gcc-c++ make autoconf openssl openssl-devel pcre-devel pam-devel perl-CPAN


# 安装perl执行环境
# https://blog.csdn.net/weixin_45920147/article/details/135200046
# https://blog.csdn.net/u013171471/article/details/136239375?spm=1001.2101.3001.6650.19&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-19-136239375-blog-137240622.235%5Ev43%5Epc_blog_bottom_relevance_base1&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-19-136239375-blog-137240622.235%5Ev43%5Epc_blog_bottom_relevance_base1&utm_relevant_index=23


# 安装 openssl-3.3.1
tar -xf openssl-3.3.1.tar.gz
mv /usr/bin/openssl /usr/bin/openssl_bak_${now}
mv /usr/include/openssl /usr/include/openssl_bak_${now}
cd openssl-3.3.1
./config --prefix=/usr/local/ssl-3.3.1 -d shared
make && make install

ln -s /usr/local/ssl-3.3.1/bin/openssl /usr/bin/openssl
ln -s /usr/local/ssl-3.3.1/include/openssl /usr/include/openssl

echo '/usr/local/ssl-3.3.1/lib64' >> /etc/ld.so.conf
ldconfig -v
openssl version

# 安装zlib-1.3.1
tar -xf zlib-1.3.1.tar.gz
cd ./zlib-1.3.1
./configure --prefix=/usr/local/zlib-1.3.1
make && make install
chmod 600 /etc/ssh/ssh_host_rsa_key
chmod 600 /etc/ssh/ssh_host_ed25519_key
chmod 600 /etc/ssh/ssh_host_ecdsa_key

# 安装openssh-9.8p1

tar -xf openssh-9.8p1.tar.gz
cd openssh-9.8p1
./configure --prefix=/usr/ --sysconfdir=/etc/ssh --with-openssl-includes=/usr/local/ssl-3.3.1/include --with-ssl-dir=/usr/local/ssl-3.3.1 --with-zlib=/usr/local/zlib-1.3.1 --with-md5-passwords --with-pam
cp -r /etc/ssh /etc/ssh_${now}
# make 报错的话执行以下命令
#autoreconf
make && make install

sed -i '/X11Forwarding/s/#X11Forwarding yes/X11Forwarding yes/' /etc/ssh/sshd_config
sed -i '/PermitRootLogin/s/#PermitRootLogin yes/PermitRootLogin yes/' /etc/ssh/sshd_config
sed -i '/UseDNS/s/#UseDNS yes/UseDNS no/' /etc/ssh/sshd_config
echo "KexAlgorithms curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha1,diffie-hellman-group-exchange-sha1,diffie-hellman-group1-sha1" >> /etc/ssh/sshd_config
\cp -a ./contrib/redhat/sshd.init /etc/init.d/sshd
\cp -a ./contrib/redhat/sshd.pam /etc/pam.d/sshd.pam

chmod +x /etc/init.d/sshd
chkconfig --add sshd
chkconfig sshd on
mv /usr/lib/systemd/system/sshd.service /usr/lib/systemd/system/sshd.service.bak
systemctl daemon-reload
/etc/init.d/sshd restart

源码如下:

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 不能使用

源码如下:

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
package main

import (
"bytes"
"context"
"errors"
"flag"
"fmt"
"io"
"log"
"net/http"
"net/url"
"net"
"os"
"strings"
"sync"
"time"
"crypto/tls"

"gopkg.in/natefinch/lumberjack.v2"
"gopkg.in/yaml.v3"
)

// Config 是YAML配置文件的结构体
type Config struct {
Server struct {
Port int `yaml:"port"`
} `yaml:"server"`
Log struct {
Enabled bool `yaml:"enabled"`
File string `yaml:"file"`
MaxSizeMB int `yaml:"maxsize"`
MaxBackups int `yaml:"maxbackups"`
MaxAgeDays int `yaml:"maxage"`
Compress bool `yaml:"compress"`
} `yaml:"log"`
Reload int `yaml:"reload"`
}

var (
port = flag.Int("port", 8888, "监听端口号")
logEnabled = flag.Bool("log", true, "是否启用日志记录")
logFile = flag.String("logfile", "", "日志文件路径")
logMaxSizeMB = flag.Int("log.maxsize", 10, "日志文件大小限制(MB)")
logMaxBackups = flag.Int("log.maxbackups", 3, "保留的最大备份文件数")
logMaxAgeDays = flag.Int("log.maxage", 28, "保留日志文件的最大天数")
logCompress = flag.Bool("log.compress", true, "是否压缩日志文件")
configFilePath = flag.String("config", "", "YAML配置文件路径")
Reload = flag.Int("reload", 30, "配置文件重新加载间隔(秒")
serverCtx, cancel = context.WithCancel(context.Background())
logConfigMutex sync.Mutex
cfg Config
)
var ErrBrokenPipe = errors.New("broken pipe")

var bufferPool = sync.Pool{
New: func() interface{} {
return make([]byte, defaultBufferSize) // 默认缓冲区大小
},
}
const defaultBufferSize = 128 * 1024 // 默认缓冲区大小
func main() {
flag.Parse()

if *configFilePath != "" {
err := loadConfig(*configFilePath)
if err != nil {
log.Fatalf("读取YAML配置文件失败: %v", err)
}
} else {
cfg.Server.Port = *port
cfg.Log.Enabled = *logEnabled
cfg.Log.File = *logFile
cfg.Log.MaxSizeMB = *logMaxSizeMB
cfg.Log.MaxBackups = *logMaxBackups
cfg.Log.MaxAgeDays = *logMaxAgeDays
cfg.Log.Compress = *logCompress
cfg.Reload = *Reload
}

setupLogger()
// 启动配置文件自动加载
go watchConfigFile(*configFilePath)

http.HandleFunc("/", handler)

go func() {
if err := startHTTPServer(serverCtx); err != nil {
log.Fatalf("启动HTTP服务器失败: %v", err)
}
}()

<-serverCtx.Done()
}

func loadConfig(configPath string) error {

yamlData, err := os.ReadFile(configPath)
if err != nil {
return err
}

var newCfg Config
err = yaml.Unmarshal(yamlData, &newCfg)
if err != nil {
return err
}

logConfigMutex.Lock()
cfg = newCfg
logConfigMutex.Unlock()

// 重新设置日志记录器
setupLogger()

return nil
}

func watchConfigFile(configPath string) {
if configPath == "" {
return
}

ticker := time.NewTicker(time.Duration(cfg.Reload) * time.Second) // 定时器间隔可以根据需要调整
defer ticker.Stop()

lastModifiedTime := time.Now()

for range ticker.C {
fileInfo, err := os.Stat(configPath)
if err != nil {
log.Printf("无法获取配置文件信息: %v", err)
continue
}

if fileInfo.ModTime().After(lastModifiedTime) {
lastModifiedTime = fileInfo.ModTime()
log.Println("检测到配置文件修改,重新加载配置...")
err := loadConfig(configPath)
if err != nil {
log.Printf("重新加载配置文件失败: %v", err)
} else {
log.Println("配置文件重新加载完成")

// 重新设置 HTTP 服务器的监听端口
serverCtx, cancel = context.WithCancel(context.Background())
go func() {
if err := startHTTPServer(serverCtx); err != nil {
log.Fatalf("启动HTTP服务器失败: %v", err)
}
}()
}
}
}
}

func setupLogger() {
logConfigMutex.Lock()
defer logConfigMutex.Unlock()

if !cfg.Log.Enabled {
// 如果日志记录被禁用,则将日志输出设置为丢弃
log.SetOutput(io.Discard)
log.Println("日志记录已禁用")
return
}

if cfg.Log.File == "" {
// 如果日志文件路径为空,则默认将日志输出到标准输出
log.SetOutput(os.Stdout)
log.Println("日志记录已启用: 输出到标准输出")
return
}

// 否则,根据配置设置日志记录到指定文件
logger := &lumberjack.Logger{
Filename: cfg.Log.File,
MaxSize: cfg.Log.MaxSizeMB,
MaxBackups: cfg.Log.MaxBackups,
MaxAge: cfg.Log.MaxAgeDays,
Compress: cfg.Log.Compress,
}
log.SetOutput(logger)
log.Printf("日志记录已启用: 输出到文件 %s", cfg.Log.File)
}

func startHTTPServer(ctx context.Context) error {
logConfigMutex.Lock()
addr := fmt.Sprintf(":%d", cfg.Server.Port)
logConfigMutex.Unlock()

fmt.Printf("监听端口: %d...\n", cfg.Server.Port)

srv := &http.Server{Addr: addr}

go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Printf("HTTP服务器启动失败: %v", err)
}
}()

<-ctx.Done()

shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 5*time.Second)
defer shutdownCancel()

if err := srv.Shutdown(shutdownCtx); err != nil {
log.Printf("HTTP服务器关闭失败: %v", err)
}
return nil
}

func handler(w http.ResponseWriter, r *http.Request) {
// 设置连接关闭标头,告知客户端和代理服务器都关闭连接
r.Header.Set("Connection", "close")
w.Header().Set("Connection", "close")

// 保留原始请求的路径,获取目标路径
targetPath := getTargetPath(r)
// 根据目标路径获取目标 URL
targetURL := getTargetURL(r, targetPath)

// 创建代理请求
proxyReq, err := createProxyRequest(r, targetURL)
if err != nil {
// 请求创建失败,返回 500 错误
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

// 发送代理请求
proxyResp, err := sendProxyRequest(proxyReq, r)
if err != nil {
// 发送请求失败,返回 502 错误
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
// 确保代理响应体在函数结束时关闭
defer proxyResp.Body.Close()

// 如果响应是 301(永久移动)或 302(临时移动)重定向
if proxyResp.StatusCode == http.StatusMovedPermanently || proxyResp.StatusCode == http.StatusFound {
// 获取原始请求的协议(Scheme),如果没有则使用默认的 http 协议
scheme := r.URL.Scheme
if scheme == "" {
if r.TLS != nil {
scheme = "https"
} else {
scheme = "http"
}
}
// 获取原始请求的主机(Host),如果没有则使用 r.Host
host := r.URL.Host
if host == "" {
host = r.Host
}
// 构造基础 URL,包含协议和主机
baseURL := fmt.Sprintf("%s://%s", scheme, host)

// 获取 Location 标头(重定向地址)
location := proxyResp.Header.Get("Location")
if location != "" {
// 如果 Location 不完整,拼接基础 URL 和 Location
location = baseURL + "/" + location

// 输出重定向的目标 URL
log.Printf("正在重定向到: %s", location)
// 设置响应的 Location 标头,进行重定向
w.Header().Set("Location", location)
}

// 设置响应状态码并返回
w.WriteHeader(proxyResp.StatusCode)
return
}

// 记录请求和响应信息(可选,日志记录)
logRequestAndResponse(r, targetURL, proxyResp)
// 将代理响应复制到客户端
ctx, cancel := context.WithCancel(context.Background()) // 没有超时限制
defer cancel()

copyResponseToClientWithContext(ctx, w, proxyResp)

}

var client = &http.Client{
Timeout: 0, // 整个请求超时
Transport: &http.Transport{
DialContext: (&net.Dialer{
Timeout: 10 * time.Second, // 连接超时
KeepAlive: 30 * time.Second, // 长连接保持时间
DualStack: true,
}).DialContext,
ResponseHeaderTimeout: 10 * time.Second, // 接收响应头超时
TLSClientConfig: &tls.Config{}, // 移除 InsecureSkipVerify,除非绝对必要
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
MaxIdleConns: 100,
MaxIdleConnsPerHost: 10,
MaxConnsPerHost: 100, // 可选:限制每个主机的最大连接数
},
CheckRedirect: func(req *http.Request, via []*http.Request) error {
const maxRedirects = 10 // 最大重定向次数
redirectCount := len(via)

// 超过最大重定向次数,直接返回错误
if redirectCount >= maxRedirects {
return fmt.Errorf("超出最大重定向次数 (%d 次)", maxRedirects)
}

// 获取上一个请求的 URL
previousURL := via[redirectCount-1].URL

// 根据响应头解析目标重定向 URL
redirectURL, err := url.Parse(req.Response.Header.Get("Location"))
if err != nil {
return fmt.Errorf("无效的重定向 URL: %w", err)
}

// 计算目标 URL,支持相对路径
targetURL := previousURL.ResolveReference(redirectURL)
req.URL = targetURL

log.Printf("从 %s 重定向到 %s", previousURL, targetURL)

// 根据需要选择是否跟随重定向
return http.ErrUseLastResponse // 不跟随重定向
},
}
func sendProxyRequest(proxyReq *http.Request, r *http.Request) (*http.Response, error) {
// 执行代理请求
resp, err := client.Do(proxyReq)
if err != nil {
log.Printf("发送请求失败: %v", err)
return nil, err
}

return resp, nil
}

func getTargetPath(r *http.Request) string {
targetPath := r.URL.Path[1:]
query := r.URL.RawQuery
if query != "" {
targetPath += "?" + query
}
return targetPath
}

func getTargetURL(r *http.Request, targetPath string) string {
if strings.HasPrefix(targetPath, "http:/") {
targetPath = strings.TrimPrefix(targetPath, "http:/")
} else if strings.HasPrefix(targetPath, "https:/") {
targetPath = strings.TrimPrefix(targetPath, "https:/")
}
useHTTPS := strings.HasPrefix(r.URL.Path, "/https:/")

var targetURL string
if useHTTPS {
targetURL = "https://" + r.URL.Host + targetPath
} else {
targetURL = "http://" + r.URL.Host + targetPath
}
return targetURL
}

func createProxyRequest(r *http.Request, targetURL string) (*http.Request, error) {
// 创建新的请求,将原始请求的方法和URL传入
proxyReq, err := http.NewRequest(r.Method, targetURL, nil)
if err != nil {
return nil, err
}

// 处理请求体
if r.Body != nil {
bodyCopy, err := io.ReadAll(r.Body)
if err != nil {
return nil, err
}
r.Body = io.NopCloser(bytes.NewBuffer(bodyCopy)) // 还原原始请求的 Body
proxyReq.Body = io.NopCloser(bytes.NewBuffer(bodyCopy)) // 设置代理请求的 Body
}

// 复制头部信息
proxyReq.Header = make(http.Header)
copyHeader(proxyReq.Header, r.Header)

// 添加 X-Forwarded-For 头部,包含客户端的 IP
clientIP := strings.Split(r.RemoteAddr, ":")[0]
if prior, ok := proxyReq.Header["X-Forwarded-For"]; ok {
clientIP = prior[0] + ", " + clientIP
}
proxyReq.Header.Set("X-Forwarded-For", clientIP)

return proxyReq, nil
}


func logRequestAndResponse(r *http.Request, targetURL string, proxyResp *http.Response) {
remoteAddr := r.RemoteAddr
forwardedFor := r.Header.Get("X-Forwarded-For")
userAgent := r.Header.Get("User-Agent")

if forwardedFor != "" {
log.Printf("[X-Forwarded-For: %s] [%s] %s %s %s %d [User-Agent: %s]",
forwardedFor, remoteAddr, r.Method, targetURL, r.Proto, proxyResp.StatusCode, userAgent)
} else {
log.Printf("[%s] %s %s %s %d [User-Agent: %s]",
remoteAddr, r.Method, targetURL, r.Proto, proxyResp.StatusCode, userAgent)
}
}

func copyResponseToClientWithContext(ctx context.Context, w http.ResponseWriter, proxyResp *http.Response) {
defer func() {
if err := proxyResp.Body.Close(); err != nil {
log.Printf("关闭响应体错误: %v", err)
}
}()

// 复制响应头
copyHeader(w.Header(), proxyResp.Header)
w.WriteHeader(proxyResp.StatusCode)

buf := bufferPool.Get().([]byte)
defer bufferPool.Put(buf) // 将缓冲区放回池中

done := make(chan struct{}) // 通知完成的通道
go func() {
defer close(done)
if err := copyWithContext(ctx, w, proxyResp.Body, buf); err != nil {
handleCopyError(w, err, proxyResp)
}
}()

select {
case <-ctx.Done(): // 客户端断开连接
log.Println("客户端断开连接")
case <-done:
log.Println("响应成功完成")
}
}


func copyWithContext(ctx context.Context, dst io.Writer, src io.Reader, buf []byte) error {
for {
select {
case <-ctx.Done():
return ctx.Err() // 客户端取消或断开连接
default:
// 从源读取数据
n, readErr := src.Read(buf)
if n > 0 {
written := 0
for written < n {
wn, writeErr := dst.Write(buf[written:n])
if writeErr != nil {
return fmt.Errorf("写入错误: %w", writeErr)
}
written += wn
}
}

if readErr != nil {
if errors.Is(readErr, io.EOF) {
return nil // 流结束(对于 FLV 通常不会发生)
}
return fmt.Errorf("读取错误: %w", readErr)
}
}
}
}


func handleCopyError(w http.ResponseWriter, err error, proxyResp *http.Response) {
if errors.Is(err, context.Canceled) {
log.Printf("传输被取消: %v, URL: %s", err, proxyResp.Request.URL.String())
} else if errors.Is(err, context.DeadlineExceeded) {
log.Printf("传输超时: %v, URL: %s", err, proxyResp.Request.URL.String())
} else {
log.Printf("传输错误: %v, URL: %s", err, proxyResp.Request.URL.String())
}

// 可选:向客户端返回错误
if w.Header().Get("Content-Length") == "" {
http.Error(w, "服务器错误", http.StatusInternalServerError)
}
}

// copyHeader 负责复制请求头
func copyHeader(dst, src http.Header) {
for k, vv := range src {
for _, v := range vv {
dst.Add(k, v)
}
}
}

配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
server:
#监听端口
port: 8888

# 日志输出配置
log:
# 是否输出日志
enabled: true
# 日志输出文件地址
file:
# 日志大小M单位
maxsize: 10
# 压缩文件备份个数
maxbackups: 3
# 日志保留天数
maxage: 28
# 是否压缩
compress: true

# 配置文件重新加载时间秒
reload: 30

编译

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

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

[Install]
WantedBy=multi-user.target

# 查看配置参数CMD的
/usr/local/bin/proxy -help
# 设置开机启动
systemctl enable proxy
# 启动
systemctl start proxy
# 代理 m3u8
http://代理ip:代理端口/mgsp-tx.live.miguvideo.com/wd_r2/cctv/cctv1hd/1200/01.m3u8
http://代理ip:代理端口/1.v.smtcdns.net/qctv.fengshows.cn/live/0701pcc72.flv
# https 打开记得携带上
http://代理ip:代理端口/https://1.v.smtcdns.net/qctv.fengshows.cn/live/0701pcc72.flv
# git 下载
wget http://代理ip:代理端口/https://github.com/kubernetes/kubernetes/archive/refs/tags/v1.30.0.zip
git clone http://代理ip:代理端口/https://github.com/kubernetes/kubernetes.git
同时还支持别站点下载还原使用

下载yaml

官方地址:https://openelb.io/docs/

1
wget https://raw.githubusercontent.com/openelb/openelb/master/deploy/openelb.yaml

修改 镜像地址

1
2
3
4
5
6
image: docker.io/juestnow/openelb:v0.5.1
imagePullPolicy: IfNotPresent
image: docker.io/juestnow/kube-webhook-certgen:v1.1.1
imagePullPolicy: IfNotPresent
image: docker.io/juestnow/kube-webhook-certgen:v1.1.1
imagePullPolicy: IfNotPresent

部署 OpenELB

1
kubectl apply -f openelb.yaml

创建 layer2 级别路由

  • eip.openelb.kubesphere.io/is-default-eip: “true” svc 配置为LoadBalancer 自动添加注释到svc 生成IP
  • address node 子网 未使用ip 地址池
  • interface 指定出口网卡名字 NIC on which OpenELB listens for ARP or NDP requests. This field is valid only when protocol is set to layer2.
  • protocol Specifies which mode of OpenELB the Eip object is used for. The value can be bgp, layer2, or vip. If this field is not specified, the default value bgp is used.
  • disable: Specifies whether the Eip object is disabled. The value can be:
    。 false: OpenELB can assign IP addresses in the Eip object to new LoadBalancer Services.
    。 true: OpenELB stops assigning IP addresses in the Eip object to new LoadBalancer Services. Existing Services are not affected.
1
2
3
4
5
6
7
8
9
10
11
12
13
cat <<EOF | kubectl apply -f -
apiVersion: network.kubesphere.io/v1alpha2
kind: Eip
metadata:
annotations:
eip.openelb.kubesphere.io/is-default-eip: "true"
name: layer2-eip
spec:
address: 192.168.3.251-192.168.3.254
interface: eth0
protocol: layer2
disable: false
EOF

测试svc申请 lb ip

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
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: Service
metadata:
annotations:
eip.openelb.kubesphere.io/v1alpha2: layer2-eip
lb.kubesphere.io/v1alpha1: openelb
protocol.openelb.kubesphere.io/v1alpha1: layer2
labels:
app.kubernetes.io/component: controller
app.kubernetes.io/instance: ingress-nginx
app.kubernetes.io/name: ingress-nginx
app.kubernetes.io/version: 1.2.0
name: ingress-nginx-controller
namespace: ingress-nginx
spec:
externalTrafficPolicy: Local
ipFamilies:
- IPv4
ipFamilyPolicy: SingleStack
ports:
- appProtocol: http
name: http
port: 80
protocol: TCP
targetPort: http
- appProtocol: https
name: https
port: 443
protocol: TCP
targetPort: https
selector:
app.kubernetes.io/component: controller
app.kubernetes.io/instance: ingress-nginx
app.kubernetes.io/name: ingress-nginx
sessionAffinity: None
type: LoadBalancer
EOF

查看结果

1
2
3
4
5
6
7
8
9
10
11
12
13
root@Qist:/# kubectl -n ingress-nginx get svc ingress-nginx-controller
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
ingress-nginx-controller LoadBalancer 10.66.113.108 192.168.3.251 80:57482/TCP,443:46604/TCP 15d

# 远程访问可以正常打开
root@Qist:/# curl 192.168.3.251
# <html>
# <head><title>404 Not Found</title></head>
# <body>
# <center><h1>404 Not Found</h1></center>
# <hr><center>nginx</center>
# </body>
# </html>