-
Notifications
You must be signed in to change notification settings - Fork 0
/
config_json.go
75 lines (62 loc) · 1.5 KB
/
config_json.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
package main
import (
"context"
"io"
"os"
"os/exec"
"v2ray.com/core"
"v2ray.com/core/common"
"v2ray.com/core/common/platform"
"v2ray.com/core/common/signal"
)
type logWriter struct{}
func (*logWriter) Write(b []byte) (int, error) {
n, err := os.Stderr.Write(b)
if err == nil {
os.Stderr.WriteString(platform.LineSeparator())
}
return n, err
}
func jsonToProto(input io.Reader) (*core.Config, error) {
v2ctl := platform.GetToolLocation("v2ctl")
if _, err := os.Stat(v2ctl); err != nil {
return nil, err
}
cmd := exec.Command(v2ctl, "config")
cmd.Stdin = input
cmd.Stderr = &logWriter{}
cmd.SysProcAttr = getSysProcAttr()
stdoutReader, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
defer stdoutReader.Close()
if err := cmd.Start(); err != nil {
return nil, err
}
var config *core.Config
loadTask := signal.ExecuteAsync(func() error {
c, err := core.LoadConfig(core.ConfigFormat_Protobuf, stdoutReader)
if err != nil {
return err
}
config = c
return nil
})
waitTask := signal.ExecuteAsync(func() error {
return cmd.Wait()
})
if err := signal.ErrorOrFinish2(context.Background(), loadTask, waitTask); err != nil {
return nil, err
}
return config, nil
}
func init() {
common.Must(core.RegisterConfigLoader(core.ConfigFormat_JSON, func(input io.Reader) (*core.Config, error) {
config, err := jsonToProto(input)
if err != nil {
return nil, newError("failed to execute v2ctl to convert config file.").Base(err).AtWarning()
}
return config, nil
}))
}