5
5
"errors"
6
6
"net"
7
7
8
+ "github.com/metacubex/mihomo/adapter/inbound"
8
9
"github.com/metacubex/mihomo/common/sockopt"
9
10
"github.com/metacubex/mihomo/context"
10
11
"github.com/metacubex/mihomo/log"
20
21
)
21
22
22
23
type Server struct {
23
- * D.Server
24
- handler handler
24
+ handler handler
25
+ tcpServer * D.Server
26
+ udpServer * D.Server
25
27
}
26
28
27
29
// ServeDNS implement D.Handler ServeDNS
@@ -55,12 +57,19 @@ func ReCreateServer(addr string, resolver *Resolver, mapper *ResolverEnhancer) {
55
57
return
56
58
}
57
59
58
- if server .Server != nil {
59
- server .Shutdown ()
60
- server = & Server {}
61
- address = ""
60
+ if server .tcpServer != nil {
61
+ _ = server .tcpServer .Shutdown ()
62
+ server .tcpServer = nil
62
63
}
63
64
65
+ if server .udpServer != nil {
66
+ _ = server .udpServer .Shutdown ()
67
+ server .udpServer = nil
68
+ }
69
+
70
+ server .handler = nil
71
+ address = ""
72
+
64
73
if addr == "" {
65
74
return
66
75
}
@@ -77,31 +86,36 @@ func ReCreateServer(addr string, resolver *Resolver, mapper *ResolverEnhancer) {
77
86
return
78
87
}
79
88
80
- udpAddr , err := net .ResolveUDPAddr ("udp" , addr )
81
- if err != nil {
82
- return
83
- }
84
-
85
- p , err := net .ListenUDP ("udp" , udpAddr )
86
- if err != nil {
87
- return
88
- }
89
-
90
- err = sockopt .UDPReuseaddr (p )
91
- if err != nil {
92
- log .Warnln ("Failed to Reuse UDP Address: %s" , err )
93
-
94
- err = nil
95
- }
96
-
97
89
address = addr
98
90
handler := NewHandler (resolver , mapper )
99
91
server = & Server {handler : handler }
100
- server .Server = & D.Server {Addr : addr , PacketConn : p , Handler : server }
101
92
102
93
go func () {
103
- server .ActivateAndServe ()
94
+ p , err := inbound .ListenPacket ("udp" , addr )
95
+ if err != nil {
96
+ log .Errorln ("Start DNS server(UDP) error: %s" , err .Error ())
97
+ return
98
+ }
99
+
100
+ if err := sockopt .UDPReuseaddr (p ); err != nil {
101
+ log .Warnln ("Failed to Reuse UDP Address: %s" , err )
102
+ }
103
+
104
+ log .Infoln ("DNS server(UDP) listening at: %s" , p .LocalAddr ().String ())
105
+ server .udpServer = & D.Server {Addr : addr , PacketConn : p , Handler : server }
106
+ _ = server .udpServer .ActivateAndServe ()
107
+ }()
108
+
109
+ go func () {
110
+ l , err := inbound .Listen ("tcp" , addr )
111
+ if err != nil {
112
+ log .Errorln ("Start DNS server(TCP) error: %s" , err .Error ())
113
+ return
114
+ }
115
+
116
+ log .Infoln ("DNS server(TCP) listening at: %s" , l .Addr ().String ())
117
+ server .tcpServer = & D.Server {Addr : addr , Listener : l , Handler : server }
118
+ _ = server .tcpServer .ActivateAndServe ()
104
119
}()
105
120
106
- log .Infoln ("DNS server listening at: %s" , p .LocalAddr ().String ())
107
121
}
0 commit comments