Move cli to separate package

This commit is contained in:
9seconds
2021-03-11 05:50:04 +03:00
parent 1a02511afe
commit 6b28488fbd
7 changed files with 114 additions and 58 deletions
+165
View File
@@ -0,0 +1,165 @@
package cli
import (
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
"os"
"strconv"
"strings"
)
type accessResponse struct {
IPv4 *accessResponseURLs `json:"ipv4,omitempty"`
IPv6 *accessResponseURLs `json:"ipv6,omitempty"`
Secret struct {
Hex string `json:"hex"`
Base64 string `json:"base64"`
} `json:"secret"`
}
type accessResponseURLs struct {
IP net.IP `json:"ip"`
TgURL string `json:"tg_url"`
TgQrCode string `json:"tg_qrcode"`
TmeURL string `json:"tme_url"`
TmeQrCode string `json:"tme_qrcode"`
}
type Access struct {
base
ConfigPath string `arg required type:"existingfile" help:"Path to the configuration file." name:"config-path"` // nolint: lll, govet
Hex bool `help:"Print secret in hex encoding."`
}
func (c *Access) Run(cli *CLI) error {
if err := c.ReadConfig(cli.Access.ConfigPath); err != nil {
return fmt.Errorf("cannot init config: %w", err)
}
ipv4 := c.conf.Network.PublicIP.IPv4.Value(nil)
ipv6 := c.conf.Network.PublicIP.IPv6.Value(nil)
if ipv4 == nil {
ipv4 = c.getIP("tcp4")
}
if ipv6 == nil {
ipv6 = c.getIP("tcp6")
}
resp := accessResponse{
IPv4: c.makeURLs(ipv4, cli),
IPv6: c.makeURLs(ipv6, cli),
}
resp.Secret.Base64 = c.conf.Secret.Base64()
resp.Secret.Hex = c.conf.Secret.Hex()
encoder := json.NewEncoder(os.Stdout)
encoder.SetEscapeHTML(false)
encoder.SetIndent("", " ")
if err := encoder.Encode(resp); err != nil {
return fmt.Errorf("cannot dump access json: %w", err)
}
return nil
}
func (c *Access) getIP(protocol string) net.IP {
client := c.network.MakeHTTPClient(0)
client.Transport = &http.Transport{
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
return c.network.DialContext(ctx, protocol, address)
},
}
c.network.PrepareHTTPClient(client)
req, err := http.NewRequest(http.MethodGet, "https://ifconfig.co", nil)
if err != nil {
panic(err)
}
resp, err := client.Do(req)
if err != nil {
return nil
}
if resp.StatusCode != http.StatusOK {
return nil
}
defer func() {
io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close()
}()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil
}
return net.ParseIP(strings.TrimSpace(string(data)))
}
func (c *Access) makeURLs(ip net.IP, cli *CLI) *accessResponseURLs {
if ip == nil {
return nil
}
values := url.Values{}
values.Set("server", ip.String())
values.Set("port", strconv.Itoa(int(c.conf.BindTo.PortValue(0))))
if cli.Access.Hex {
values.Set("secret", c.conf.Secret.Hex())
} else {
values.Set("secret", c.conf.Secret.Base64())
}
urlQuery := values.Encode()
rv := &accessResponseURLs{
IP: ip,
TgURL: (&url.URL{
Scheme: "tg",
Host: "proxy",
RawQuery: urlQuery,
}).String(),
TmeURL: (&url.URL{
Scheme: "https",
Host: "t.me",
Path: "proxy",
RawQuery: urlQuery,
}).String(),
}
rv.TgQrCode = c.makeQRCode(rv.TgURL)
rv.TmeQrCode = c.makeQRCode(rv.TmeURL)
return rv
}
func (c *Access) makeQRCode(data string) string {
values := url.Values{}
values.Set("qzone", "4")
values.Set("format", "svg")
values.Set("data", data)
return (&url.URL{
Scheme: "https",
Host: "api.qrserver.com",
Path: "v1/create-qr-code",
RawQuery: values.Encode(),
}).String()
}
+77
View File
@@ -0,0 +1,77 @@
package cli
import (
"fmt"
"io/ioutil"
"net"
"net/url"
"github.com/9seconds/mtg/v2/config"
"github.com/9seconds/mtg/v2/mtglib/network"
)
type base struct {
network network.Network
conf *config.Config
}
func (b *base) ReadConfig(path string) error {
content, err := ioutil.ReadFile(path)
if err != nil {
return fmt.Errorf("cannot read config file: %w", err)
}
conf, err := config.Parse(content)
if err != nil {
return fmt.Errorf("cannot parse config: %w", err)
}
ntw, err := b.makeNetwork(conf)
if err != nil {
return fmt.Errorf("cannot build a network: %w", err)
}
b.conf = conf
b.network = ntw
return nil
}
func (b *base) makeNetwork(conf *config.Config) (network.Network, error) {
tcpTimeout := conf.Network.Timeout.TCP.Value(network.DefaultTimeout)
idleTimeout := conf.Network.Timeout.Idle.Value(network.DefaultIdleTimeout)
dohIP := conf.Network.DOHIP.Value(net.ParseIP(network.DefaultDOHHostname)).String()
bufferSize := conf.TCPBuffer.Value(network.DefaultBufferSize)
baseDialer, err := network.NewDefaultDialer(tcpTimeout, int(bufferSize))
if err != nil {
return nil, fmt.Errorf("cannot build a default dialer: %w", err)
}
proxyURLs := make([]*url.URL, 0, len(conf.Network.Proxies))
for _, v := range conf.Network.Proxies {
if value := v.Value(nil); value != nil {
proxyURLs = append(proxyURLs, v.Value(nil))
}
}
switch len(proxyURLs) {
case 0:
return network.NewNetwork(baseDialer, dohIP, idleTimeout)
case 1:
socksDialer, err := network.NewSocks5Dialer(baseDialer, proxyURLs[0])
if err != nil {
return nil, fmt.Errorf("cannot build socks5 dialer: %w", err)
}
return network.NewNetwork(socksDialer, dohIP, idleTimeout)
}
socksDialer, err := network.NewLoadBalancedSocks5Dialer(baseDialer, proxyURLs)
if err != nil {
return nil, fmt.Errorf("cannot build socks5 dialer: %w", err)
}
return network.NewNetwork(socksDialer, dohIP, idleTimeout)
}
+11
View File
@@ -0,0 +1,11 @@
package cli
import (
"github.com/alecthomas/kong"
)
type CLI struct {
GenerateSecret GenerateSecret `cmd help:"Generate new proxy secret"` // nolint: govet
Access Access `cmd help:"Print access information."` // nolint: govet
Version kong.VersionFlag `help:"Print version."`
}
+26
View File
@@ -0,0 +1,26 @@
package cli
import (
"fmt"
"github.com/9seconds/mtg/v2/mtglib"
)
type GenerateSecret struct {
base
HostName string `arg optional help:"Hostname to use for domain fronting. Default is '${domain_front}'." name:"hostname" default:"${domain_front}"` // nolint: lll, govet
Hex bool `help:"Print secret in hex encoding."`
}
func (c *GenerateSecret) Run(cli *CLI) error { // nolint: unparam
secret := mtglib.GenerateSecret(cli.GenerateSecret.HostName)
if cli.GenerateSecret.Hex {
fmt.Println(secret.Hex()) // nolint: forbidigo
} else {
fmt.Println(secret.Base64()) // nolint: forbidigo
}
return nil
}