-
Notifications
You must be signed in to change notification settings - Fork 185
/
libv2ray_main.go
315 lines (272 loc) · 7.2 KB
/
libv2ray_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
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
package libv2ray
import (
"context"
"errors"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"time"
mobasset "golang.org/x/mobile/asset"
v2net "github.com/xtls/xray-core/common/net"
v2filesystem "github.com/xtls/xray-core/common/platform/filesystem"
v2core "github.com/xtls/xray-core/core"
v2stats "github.com/xtls/xray-core/features/stats"
v2serial "github.com/xtls/xray-core/infra/conf/serial"
_ "github.com/xtls/xray-core/main/distro/all"
v2internet "github.com/xtls/xray-core/transport/internet"
v2applog "github.com/xtls/xray-core/app/log"
v2commlog "github.com/xtls/xray-core/common/log"
)
const (
v2Asset = "xray.location.asset"
xudpBaseKey = "xray.xudp.basekey"
)
/*
V2RayPoint V2Ray Point Server
This is territory of Go, so no getter and setters!
*/
type V2RayPoint struct {
SupportSet V2RayVPNServiceSupportsSet
statsManager v2stats.Manager
dialer *ProtectedDialer
v2rayOP sync.Mutex
closeChan chan struct{}
Vpoint *v2core.Instance
IsRunning bool
DomainName string
ConfigureFileContent string
AsyncResolve bool
}
/*V2RayVPNServiceSupportsSet To support Android VPN mode*/
type V2RayVPNServiceSupportsSet interface {
Setup(Conf string) int
Prepare() int
Shutdown() int
Protect(int) bool
OnEmitStatus(int, string) int
}
/*RunLoop Run V2Ray main loop
*/
func (v *V2RayPoint) RunLoop(prefIPv6 bool) (err error) {
v.v2rayOP.Lock()
defer v.v2rayOP.Unlock()
//Construct Context
if !v.IsRunning {
v.closeChan = make(chan struct{})
v.dialer.PrepareResolveChan()
go func() {
select {
// wait until resolved
case <-v.dialer.ResolveChan():
// shutdown VPNService if server name can not reolved
if !v.dialer.IsVServerReady() {
log.Println("vServer cannot resolved, shutdown")
v.StopLoop()
v.SupportSet.Shutdown()
}
// stop waiting if manually closed
case <-v.closeChan:
}
}()
if v.AsyncResolve {
go func() {
v.dialer.PrepareDomain(v.DomainName, v.closeChan, prefIPv6)
close(v.dialer.ResolveChan())
}()
} else {
v.dialer.PrepareDomain(v.DomainName, v.closeChan, prefIPv6)
close(v.dialer.ResolveChan())
}
err = v.pointloop()
}
return
}
/*StopLoop Stop V2Ray main loop
*/
func (v *V2RayPoint) StopLoop() (err error) {
v.v2rayOP.Lock()
defer v.v2rayOP.Unlock()
if v.IsRunning {
close(v.closeChan)
v.shutdownInit()
v.SupportSet.OnEmitStatus(0, "Closed")
}
return
}
// Delegate Funcation
func (v V2RayPoint) QueryStats(tag string, direct string) int64 {
if v.statsManager == nil {
return 0
}
counter := v.statsManager.GetCounter(fmt.Sprintf("outbound>>>%s>>>traffic>>>%s", tag, direct))
if counter == nil {
return 0
}
return counter.Set(0)
}
func (v *V2RayPoint) shutdownInit() {
v.IsRunning = false
v.Vpoint.Close()
v.Vpoint = nil
v.statsManager = nil
}
func (v *V2RayPoint) pointloop() error {
log.Println("loading core config")
config, err := v2serial.LoadJSONConfig(strings.NewReader(v.ConfigureFileContent))
if err != nil {
log.Println(err)
return err
}
log.Println("new core")
v.Vpoint, err = v2core.New(config)
if err != nil {
v.Vpoint = nil
log.Println(err)
return err
}
v.statsManager = v.Vpoint.GetFeature(v2stats.ManagerType()).(v2stats.Manager)
log.Println("start core")
v.IsRunning = true
if err := v.Vpoint.Start(); err != nil {
v.IsRunning = false
log.Println(err)
return err
}
v.SupportSet.Prepare()
v.SupportSet.Setup("")
v.SupportSet.OnEmitStatus(0, "Running")
return nil
}
func (v *V2RayPoint) MeasureDelay(url string) (int64, error) {
ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second)
go func() {
select {
case <-v.closeChan:
// cancel request if close called during meansure
cancel()
case <-ctx.Done():
}
}()
return measureInstDelay(ctx, v.Vpoint, url)
}
// InitV2Env set v2 asset path
func InitV2Env(envPath string, key string) {
//Initialize asset API, Since Raymond Will not let notify the asset location inside Process,
//We need to set location outside V2Ray
if len(envPath) > 0 {
os.Setenv(v2Asset, envPath)
}
if len(key) > 0 {
os.Setenv(xudpBaseKey, key)
}
//Now we handle read, fallback to gomobile asset (apk assets)
v2filesystem.NewFileReader = func(path string) (io.ReadCloser, error) {
if _, err := os.Stat(path); os.IsNotExist(err) {
_, file := filepath.Split(path)
return mobasset.Open(file)
}
return os.Open(path)
}
}
func MeasureOutboundDelay(ConfigureFileContent string, url string) (int64, error) {
config, err := v2serial.LoadJSONConfig(strings.NewReader(ConfigureFileContent))
if err != nil {
return -1, err
}
// dont listen to anything for test purpose
config.Inbound = nil
// config.App: (fakedns), log, dispatcher, InboundConfig, OutboundConfig, (stats), router, dns, (policy)
// keep only basic features
config.App = config.App[:5]
inst, err := v2core.New(config)
if err != nil {
return -1, err
}
inst.Start()
delay, err := measureInstDelay(context.Background(), inst, url)
inst.Close()
return delay, err
}
/*NewV2RayPoint new V2RayPoint*/
func NewV2RayPoint(s V2RayVPNServiceSupportsSet, adns bool) *V2RayPoint {
// inject our own log writer
v2applog.RegisterHandlerCreator(v2applog.LogType_Console,
func(lt v2applog.LogType,
options v2applog.HandlerCreatorOptions) (v2commlog.Handler, error) {
return v2commlog.NewLogger(createStdoutLogWriter()), nil
})
dialer := NewPreotectedDialer(s)
v2internet.UseAlternativeSystemDialer(dialer)
return &V2RayPoint{
SupportSet: s,
dialer: dialer,
AsyncResolve: adns,
}
}
/*
CheckVersionX string
This func will return libv2ray binding version and V2Ray version used.
*/
func CheckVersionX() string {
var version = 27
return fmt.Sprintf("Lib v%d, Xray-core v%s", version, v2core.Version())
}
func measureInstDelay(ctx context.Context, inst *v2core.Instance, url string) (int64, error) {
if inst == nil {
return -1, errors.New("core instance nil")
}
tr := &http.Transport{
TLSHandshakeTimeout: 6 * time.Second,
DisableKeepAlives: true,
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
dest, err := v2net.ParseDestination(fmt.Sprintf("%s:%s", network, addr))
if err != nil {
return nil, err
}
return v2core.Dial(ctx, inst, dest)
},
}
c := &http.Client{
Transport: tr,
Timeout: 12 * time.Second,
}
if len(url) <= 0 {
url = "https://www.google.com/generate_204"
}
req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
start := time.Now()
resp, err := c.Do(req)
if err != nil {
return -1, err
}
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
return -1, fmt.Errorf("status != 20x: %s", resp.Status)
}
resp.Body.Close()
return time.Since(start).Milliseconds(), nil
}
// This struct creates our own log writer without datatime stamp
// As Android adds time stamps on each line
type consoleLogWriter struct {
logger *log.Logger
}
func (w *consoleLogWriter) Write(s string) error {
w.logger.Print(s)
return nil
}
func (w *consoleLogWriter) Close() error {
return nil
}
// This logger won't print data/time stamps
func createStdoutLogWriter() v2commlog.WriterCreator {
return func() v2commlog.Writer {
return &consoleLogWriter{
logger: log.New(os.Stdout, "", 0)}
}
}