2019-02-10 13:04:11 -05:00
|
|
|
package control
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
|
|
|
"os"
|
|
|
|
"strings"
|
2020-01-02 20:26:48 -05:00
|
|
|
"time"
|
2019-02-10 13:04:11 -05:00
|
|
|
|
2021-02-16 15:31:50 -05:00
|
|
|
"github.com/v2fly/v2ray-core/v4/common"
|
|
|
|
"github.com/v2fly/v2ray-core/v4/common/buf"
|
2019-02-10 13:04:11 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
type FetchCommand struct{}
|
|
|
|
|
|
|
|
func (c *FetchCommand) Name() string {
|
|
|
|
return "fetch"
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *FetchCommand) Description() Description {
|
|
|
|
return Description{
|
|
|
|
Short: "Fetch resources",
|
|
|
|
Usage: []string{"v2ctl fetch <url>"},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *FetchCommand) Execute(args []string) error {
|
|
|
|
if len(args) < 1 {
|
|
|
|
return newError("empty url")
|
|
|
|
}
|
2020-01-02 20:26:48 -05:00
|
|
|
content, err := FetchHTTPContent(args[0])
|
|
|
|
if err != nil {
|
|
|
|
return newError("failed to read HTTP response").Base(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
os.Stdout.Write(content)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// FetchHTTPContent dials https for remote content
|
|
|
|
func FetchHTTPContent(target string) ([]byte, error) {
|
2019-02-10 13:04:11 -05:00
|
|
|
parsedTarget, err := url.Parse(target)
|
|
|
|
if err != nil {
|
2020-01-02 20:26:48 -05:00
|
|
|
return nil, newError("invalid URL: ", target).Base(err)
|
2019-02-10 13:04:11 -05:00
|
|
|
}
|
2020-01-02 20:26:48 -05:00
|
|
|
|
|
|
|
if s := strings.ToLower(parsedTarget.Scheme); s != "http" && s != "https" {
|
|
|
|
return nil, newError("invalid scheme: ", parsedTarget.Scheme)
|
2019-02-10 13:04:11 -05:00
|
|
|
}
|
|
|
|
|
2020-01-02 20:26:48 -05:00
|
|
|
client := &http.Client{
|
|
|
|
Timeout: 30 * time.Second,
|
|
|
|
}
|
2019-02-10 13:04:11 -05:00
|
|
|
resp, err := client.Do(&http.Request{
|
|
|
|
Method: "GET",
|
|
|
|
URL: parsedTarget,
|
|
|
|
Close: true,
|
|
|
|
})
|
|
|
|
if err != nil {
|
2020-01-02 20:26:48 -05:00
|
|
|
return nil, newError("failed to dial to ", target).Base(err)
|
2019-02-10 13:04:11 -05:00
|
|
|
}
|
2020-01-02 20:26:48 -05:00
|
|
|
defer resp.Body.Close()
|
2019-02-10 13:04:11 -05:00
|
|
|
|
|
|
|
if resp.StatusCode != 200 {
|
2020-01-02 20:26:48 -05:00
|
|
|
return nil, newError("unexpected HTTP status code: ", resp.StatusCode)
|
2019-02-10 13:04:11 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
content, err := buf.ReadAllToBytes(resp.Body)
|
|
|
|
if err != nil {
|
2020-01-02 20:26:48 -05:00
|
|
|
return nil, newError("failed to read HTTP response").Base(err)
|
2019-02-10 13:04:11 -05:00
|
|
|
}
|
|
|
|
|
2020-01-02 20:26:48 -05:00
|
|
|
return content, nil
|
2019-02-10 13:04:11 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
common.Must(RegisterCommand(&FetchCommand{}))
|
|
|
|
}
|