Xray-core/main/confloader/external/external.go

86 lines
1.8 KiB
Go
Raw Normal View History

2020-11-25 14:01:53 +03:00
package external
import (
"bytes"
"io"
"net/http"
"net/url"
"os"
"strings"
"time"
2020-12-04 04:36:16 +03:00
"github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/errors"
2020-12-04 04:36:16 +03:00
"github.com/xtls/xray-core/common/platform/ctlcmd"
"github.com/xtls/xray-core/main/confloader"
2020-11-25 14:01:53 +03:00
)
func ConfigLoader(arg string) (out io.Reader, err error) {
var data []byte
switch {
case strings.HasPrefix(arg, "http://"), strings.HasPrefix(arg, "https://"):
data, err = FetchHTTPContent(arg)
case arg == "stdin:":
data, err = io.ReadAll(os.Stdin)
2020-11-25 14:01:53 +03:00
default:
data, err = os.ReadFile(arg)
2020-11-25 14:01:53 +03:00
}
if err != nil {
return
}
out = bytes.NewBuffer(data)
return
}
func FetchHTTPContent(target string) ([]byte, error) {
parsedTarget, err := url.Parse(target)
if err != nil {
return nil, errors.New("invalid URL: ", target).Base(err)
2020-11-25 14:01:53 +03:00
}
if s := strings.ToLower(parsedTarget.Scheme); s != "http" && s != "https" {
return nil, errors.New("invalid scheme: ", parsedTarget.Scheme)
2020-11-25 14:01:53 +03:00
}
client := &http.Client{
Timeout: 30 * time.Second,
}
resp, err := client.Do(&http.Request{
Method: "GET",
URL: parsedTarget,
Close: true,
})
if err != nil {
return nil, errors.New("failed to dial to ", target).Base(err)
2020-11-25 14:01:53 +03:00
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, errors.New("unexpected HTTP status code: ", resp.StatusCode)
2020-11-25 14:01:53 +03:00
}
content, err := buf.ReadAllToBytes(resp.Body)
if err != nil {
return nil, errors.New("failed to read HTTP response").Base(err)
2020-11-25 14:01:53 +03:00
}
return content, nil
}
func ExtConfigLoader(files []string, reader io.Reader) (io.Reader, error) {
buf, err := ctlcmd.Run(append([]string{"convert"}, files...), reader)
if err != nil {
return nil, err
}
return strings.NewReader(buf.String()), nil
}
func init() {
confloader.EffectiveConfigFileLoader = ConfigLoader
confloader.EffectiveExtConfigLoader = ExtConfigLoader
}