sing-box/cmd/sing-box/cmd_tools_connect.go

74 lines
1.8 KiB
Go
Raw Normal View History

2023-03-18 12:26:58 +00:00
package main
import (
"context"
"os"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/bufio"
E "github.com/sagernet/sing/common/exceptions"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
"github.com/sagernet/sing/common/task"
"github.com/spf13/cobra"
)
var commandConnectFlagNetwork string
2023-03-18 12:26:58 +00:00
var commandConnect = &cobra.Command{
2023-12-01 05:24:12 +00:00
Use: "connect <address>",
2023-03-18 13:02:29 +00:00
Short: "Connect to an address",
2023-03-18 12:26:58 +00:00
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
err := connect(args[0])
if err != nil {
log.Fatal(err)
}
},
}
func init() {
commandConnect.Flags().StringVarP(&commandConnectFlagNetwork, "network", "n", "tcp", "network type")
2023-03-18 12:26:58 +00:00
commandTools.AddCommand(commandConnect)
}
func connect(address string) error {
2023-03-18 13:02:29 +00:00
switch N.NetworkName(commandConnectFlagNetwork) {
2023-03-18 12:26:58 +00:00
case N.NetworkTCP, N.NetworkUDP:
default:
2023-03-18 13:02:29 +00:00
return E.Cause(N.ErrUnknownNetwork, commandConnectFlagNetwork)
2023-03-18 12:26:58 +00:00
}
instance, err := createPreStartedClient()
if err != nil {
return err
}
2023-03-18 13:02:29 +00:00
defer instance.Close()
dialer, err := createDialer(instance, commandConnectFlagNetwork, commandToolsFlagOutbound)
2023-03-18 13:02:29 +00:00
if err != nil {
return err
2023-03-18 12:26:58 +00:00
}
2023-03-18 13:02:29 +00:00
conn, err := dialer.DialContext(context.Background(), commandConnectFlagNetwork, M.ParseSocksaddr(address))
2023-03-18 12:26:58 +00:00
if err != nil {
return E.Cause(err, "connect to server")
}
var group task.Group
group.Append("upload", func(ctx context.Context) error {
return common.Error(bufio.Copy(conn, os.Stdin))
})
group.Append("download", func(ctx context.Context) error {
return common.Error(bufio.Copy(os.Stdout, conn))
})
2023-03-18 13:02:29 +00:00
group.Cleanup(func() {
conn.Close()
})
2023-03-18 12:26:58 +00:00
err = group.Run(context.Background())
if E.IsClosed(err) {
log.Info(err)
} else {
log.Error(err)
}
return nil
}