1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-23 10:37:09 -05:00
v2fly/main/json/config_json.go

82 lines
1.7 KiB
Go
Raw Normal View History

package json
//go:generate go run $GOPATH/src/v2ray.com/core/common/errors/errorgen/main.go -pkg json -path Main,Json
2016-10-15 18:46:30 -04:00
import (
2018-02-12 05:40:42 -05:00
"context"
"io"
"os"
"os/exec"
"v2ray.com/core"
2018-02-12 05:40:42 -05:00
"v2ray.com/core/common"
"v2ray.com/core/common/platform"
2018-02-12 05:40:42 -05:00
"v2ray.com/core/common/signal"
)
2018-02-12 05:40:42 -05:00
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")
2018-02-12 05:40:42 -05:00
if _, err := os.Stat(v2ctl); err != nil {
return nil, err
}
cmd := exec.Command(v2ctl, "config")
cmd.Stdin = input
2018-02-12 05:40:42 -05:00
cmd.Stderr = &logWriter{}
cmd.SysProcAttr = getSysProcAttr()
stdoutReader, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
defer stdoutReader.Close()
2017-11-16 18:51:04 -05:00
if err := cmd.Start(); err != nil {
return nil, err
}
2018-02-12 05:40:42 -05:00
var config *core.Config
loadTask := signal.ExecuteAsync(func() error {
2018-02-14 17:57:40 -05:00
c, err := core.LoadConfig("protobuf", "", stdoutReader)
2018-02-12 05:40:42 -05:00
if err != nil {
return err
}
config = c
return nil
})
waitTask := signal.ExecuteAsync(func() error {
return cmd.Wait()
})
2017-11-16 18:51:04 -05:00
2018-02-12 05:40:42 -05:00
if err := signal.ErrorOrFinish2(context.Background(), loadTask, waitTask); err != nil {
return nil, err
}
2017-11-16 18:51:04 -05:00
2018-02-12 05:40:42 -05:00
return config, nil
}
func init() {
2018-02-14 17:57:40 -05:00
common.Must(core.RegisterConfigLoader(&core.ConfigFormat{
Name: "JSON",
Extension: []string{"json"},
Loader: 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
},
2018-02-12 05:40:42 -05:00
}))
}