Repository navigation
Expand file tree
/
Copy pathapp_connection.go
More file actions
263 lines (225 loc) · 6.68 KB
/
Copy pathapp_connection.go
File metadata and controls
263 lines (225 loc) · 6.68 KB
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
package main
import (
"context"
"fmt"
"net"
"time"
"changeme/internal/core"
"changeme/internal/storage"
"changeme/internal/sysproxy"
"changeme/internal/sysutil"
)
// resolveServerIPv4 resolves a server hostname or IP to an IPv4 string.
func resolveServerIPv4(host string) string {
if host == "" {
return ""
}
if ip := net.ParseIP(host); ip != nil {
if ip4 := ip.To4(); ip4 != nil {
return ip4.String()
}
return ip.String()
}
ips, err := net.LookupIP(host)
if err != nil {
return ""
}
for _, ip := range ips {
if ip4 := ip.To4(); ip4 != nil {
return ip4.String()
}
}
return ""
}
// buildProfileConfig generates the complete Xray configuration for a given profile.
func (a *AppService) buildProfileConfig(profile *storage.Profile, bindIP string) (string, error) {
settings := a.store.GetSettings()
var dnsServers []string
if settings.PrimaryDNS != "" {
dnsServers = append(dnsServers, settings.PrimaryDNS)
}
if settings.SecondaryDNS != "" {
dnsServers = append(dnsServers, settings.SecondaryDNS)
}
return core.MergeCompleteConfig(profile.OutboundJSON, core.ConfigMergerOptions{
SocksPort: settings.SocksPort,
HttpPort: settings.HttpPort,
ApiPort: 10807,
DnsServers: dnsServers,
BindIP: bindIP,
ServerDomain: profile.Server,
ServerIP: resolveServerIPv4(profile.Server),
})
}
// Connect connects to the designated profile using the specified operating mode (tun, proxy, or core).
func (a *AppService) Connect(profileID string, mode string) error {
a.mu.Lock()
defer a.mu.Unlock()
profile := a.store.GetProfile(profileID)
if profile == nil {
return fmt.Errorf("profile not found: %s", profileID)
}
settings := a.store.GetSettings()
if mode == "" {
mode = settings.Mode
}
if mode == "" {
mode = "proxy"
}
a.log("Generating Xray configuration for profile '%s' (%s)", profile.Name, profile.Protocol)
var bindIP string
if mode == "tun" {
if adapterInfo, err := a.tunMgr.GetPhysicalAdapterInfo(); err == nil && adapterInfo.LanIP != nil && !adapterInfo.LanIP.IsUnspecified() {
bindIP = adapterInfo.LanIP.String()
a.log("Binding Xray outbounds to physical adapter IP: %s", bindIP)
}
}
fullConfig, err := a.buildProfileConfig(profile, bindIP)
if err != nil {
a.log("Configuration build error: %v", err)
return fmt.Errorf("failed to build configuration: %w", err)
}
a.log("Starting embedded Xray instance via libxray...")
if err := a.xrayMgr.Start(fullConfig); err != nil {
a.log("Failed to start Xray: %v", err)
return err
}
a.log("Xray core running on 127.0.0.1:%d (SOCKS) & 127.0.0.1:%d (HTTP)", settings.SocksPort, settings.HttpPort)
switch mode {
case "proxy":
a.log("Setting Windows System Proxy to 127.0.0.1:%d...", settings.HttpPort)
if err := sysproxy.SetProxy(settings.HttpPort); err != nil {
a.log("Warning: Failed to set system proxy: %v", err)
_ = a.xrayMgr.Stop()
return err
}
a.log("Windows System Proxy activated successfully")
case "tun":
a.log("Activating Windows TUN Mode with DNS (%s / %s)...", settings.PrimaryDNS, settings.SecondaryDNS)
splitApps := settings.SplitDriverApps
if len(splitApps) == 0 && settings.SplitTunnelMode != "all" {
splitApps = settings.SplitTunnelApps
}
if err := a.tunMgr.Start(profile.Server, settings.SocksPort, settings.SplitTunnelMode, splitApps, settings.PrimaryDNS, settings.SecondaryDNS); err != nil {
a.log("Failed to activate TUN mode: %v", err)
_ = a.xrayMgr.Stop()
return fmt.Errorf("TUN mode failed (run as Administrator): %w", err)
}
a.log("Windows TUN Mode activated successfully")
case "core":
a.log("Core Only mode active: SOCKS5 127.0.0.1:%d, HTTP 127.0.0.1:%d", settings.SocksPort, settings.HttpPort)
}
a.connected = true
a.activeProfileID = profileID
a.activeMode = mode
if a.watchCancel != nil {
a.watchCancel()
a.watchCancel = nil
}
if mode == "tun" {
a.watchCtx, a.watchCancel = context.WithCancel(context.Background())
go a.startNetworkWatcher(a.watchCtx, profileID)
}
settings.SelectedProfileID = profileID
settings.Mode = mode
_ = a.store.UpdateSettings(settings)
if a.app != nil {
a.app.Event.Emit("vpn:status", VpnStatusEvent{
Connected: true,
ActiveProfileID: profileID,
ActiveMode: mode,
})
}
go func() {
time.Sleep(1 * time.Second)
ping := a.xrayMgr.MeasureServerPing(profile.Server, profile.Port, "http://cp.cloudflare.com/generate_204", settings.SocksPort)
if ping > 0 {
_ = a.store.UpdateProfilePing(profileID, ping, true)
a.log("Connection latency: %d ms", ping)
if a.app != nil {
a.app.Event.Emit("profile:ping", PingEvent{ID: profileID, Ping: ping})
}
}
}()
return nil
}
// Disconnect stops active proxy/TUN routing and terminates the embedded core engine.
func (a *AppService) Disconnect() error {
a.mu.Lock()
defer a.mu.Unlock()
if !a.connected && !a.xrayMgr.IsRunning() && !a.tunMgr.IsRunning() {
return nil
}
a.log("Disconnecting...")
if a.watchCancel != nil {
a.watchCancel()
a.watchCancel = nil
}
_ = sysproxy.ClearProxy()
_ = a.tunMgr.Stop()
_ = a.xrayMgr.Stop()
a.connected = false
a.activeProfileID = ""
a.log("Disconnected successfully")
if a.app != nil {
a.app.Event.Emit("vpn:status", VpnStatusEvent{
Connected: false,
ActiveProfileID: "",
ActiveMode: a.activeMode,
})
a.app.Event.Emit("traffic:update", core.TrafficStats{})
}
sysutil.TrimProcessMemory()
return nil
}
// ResetNetwork clears Windows system proxy settings, flushes virtual TUN routes, and stops core engines.
func (a *AppService) ResetNetwork() error {
a.mu.Lock()
defer a.mu.Unlock()
a.log("Resetting network: clearing system proxy and routing table...")
if a.watchCancel != nil {
a.watchCancel()
a.watchCancel = nil
}
_ = sysproxy.ClearProxy()
_ = a.tunMgr.CleanupStaleRoutes()
_ = a.tunMgr.Stop()
_ = a.xrayMgr.Stop()
a.connected = false
a.activeProfileID = ""
if a.app != nil {
a.app.Event.Emit("vpn:status", VpnStatusEvent{
Connected: false,
ActiveProfileID: "",
ActiveMode: a.activeMode,
})
a.app.Event.Emit("traffic:update", core.TrafficStats{})
}
a.log("Network settings reset to clean direct connection")
return nil
}
// ConnectDefault connects using the selected profile or the first available profile in storage.
func (a *AppService) ConnectDefault() error {
a.mu.Lock()
if a.connected {
a.mu.Unlock()
return nil
}
settings := a.store.GetSettings()
targetID := settings.SelectedProfileID
if targetID == "" {
profiles := a.store.GetProfiles()
if len(profiles) > 0 {
targetID = profiles[0].ID
}
}
a.mu.Unlock()
if targetID == "" {
return fmt.Errorf("no profile available to connect")
}
mode := settings.Mode
if mode == "" {
mode = "tun"
}
return a.Connect(targetID, mode)
}