Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

proxy configuration for dmsgip #285

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 53 additions & 43 deletions cmd/dmsgip/commands/dmsgip.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ import (
"path/filepath"
"strings"

"github.com/skycoin/skywire-utilities/pkg/buildinfo"
"github.com/skycoin/skywire-utilities/pkg/cipher"
"github.com/skycoin/skywire-utilities/pkg/cmdutil"
"github.com/skycoin/skywire-utilities/pkg/logging"
"github.com/skycoin/skywire-utilities/pkg/skyenv"
"github.com/spf13/cobra"
"golang.org/x/net/proxy"

"github.com/skycoin/dmsg/pkg/disc"
"github.com/skycoin/dmsg/pkg/dmsg"
Expand All @@ -26,40 +26,37 @@ var (
sk cipher.SecKey
logLvl string
dmsgServers []string
proxyAddr string
httpClient *http.Client
)

func init() {
RootCmd.Flags().StringVarP(&dmsgDisc, "dmsg-disc", "c", "", "dmsg discovery url default:\n"+skyenv.DmsgDiscAddr)
RootCmd.Flags().StringVarP(&logLvl, "loglvl", "l", "fatal", "[ debug | warn | error | fatal | panic | trace | info ]\033[0m")
RootCmd.Flags().StringVarP(&dmsgDisc, "dmsg-disc", "c", skyenv.DmsgDiscAddr, "dmsg discovery url\n")
RootCmd.Flags().StringVarP(&proxyAddr, "proxy", "p", "", "connect to dmsg via proxy (i.e. '127.0.0.1:1080')")
RootCmd.Flags().StringVarP(&logLvl, "loglvl", "l", "fatal", "[debug|warn|error|fatal|panic|trace|info]\033[0m")
if os.Getenv("DMSGIP_SK") != "" {
sk.Set(os.Getenv("DMSGIP_SK")) //nolint
}
RootCmd.Flags().StringSliceVarP(&dmsgServers, "srv", "d", []string{}, "dmsg server public keys\n\r")
RootCmd.Flags().VarP(&sk, "sk", "s", "a random key is generated if unspecified\n\r")
}

// RootCmd containsa the root dmsgcurl command
// RootCmd contains the root dmsgcurl command
var RootCmd = &cobra.Command{
Use: func() string {
return strings.Split(filepath.Base(strings.ReplaceAll(strings.ReplaceAll(fmt.Sprintf("%v", os.Args), "[", ""), "]", "")), " ")[0]
}(),
Short: "DMSG ip utility",
Short: "DMSG IP utility",
Long: `
┌┬┐┌┬┐┌─┐┌─┐ ┬┌─┐
│││││└─┐│ ┬ │├─┘
─┴┘┴ ┴└─┘└─┘ ┴┴
DMSG ip utility`,
DMSG IP utility`,
SilenceErrors: true,
SilenceUsage: true,
DisableSuggestions: true,
DisableFlagsInUseLine: true,
Version: buildinfo.Version(),
PreRun: func(cmd *cobra.Command, args []string) {
if dmsgDisc == "" {
dmsgDisc = skyenv.DmsgDiscAddr
}
},
RunE: func(cmd *cobra.Command, args []string) error {
RunE: func(_ *cobra.Command, _ []string) error {
log := logging.MustGetLogger("dmsgip")

if logLvl != "" {
Expand All @@ -77,20 +74,56 @@ DMSG ip utility`,
srvs = append(srvs, pk)
}

ctx, cancel := cmdutil.SignalContext(context.Background(), log)
defer cancel()

pk, err := sk.PubKey()
if err != nil {
pk, sk = cipher.GenerateKeyPair()
}

dmsgC, closeDmsg, err := startDmsg(ctx, log, pk, sk)
if err != nil {
log.WithError(err).Error("failed to start dmsg")
ctx, cancel := cmdutil.SignalContext(context.Background(), log)
defer cancel()

httpClient = &http.Client{}
var dialer proxy.Dialer = proxy.Direct // Default dialer is direct connection

if proxyAddr != "" {
// Use SOCKS5 proxy dialer if specified
dialer, err = proxy.SOCKS5("tcp", proxyAddr, nil, proxy.Direct)
if err != nil {
log.Fatalf("Error creating SOCKS5 dialer: %v", err)
}
transport := &http.Transport{
Dial: dialer.Dial,
}
httpClient = &http.Client{
Transport: transport,
}
ctx = context.WithValue(context.Background(), "socks5_proxy", proxyAddr) //nolint
}
defer closeDmsg()

// Create DMSG client
dmsgC := dmsg.NewClient(pk, sk, disc.NewHTTP(dmsgDisc, httpClient, log), &dmsg.Config{MinSessions: dmsg.DefaultMinSessions})
go dmsgC.Serve(ctx) // Pass the context here

stop := func() {
err := dmsgC.Close()
log.WithError(err).Debug("Disconnected from dmsg network.")
fmt.Printf("\n")
}
defer stop()

log.WithField("public_key", pk.String()).WithField("dmsg_disc", dmsgDisc).
Debug("Connecting to dmsg network...")

select {
case <-ctx.Done():
stop()
return ctx.Err()

case <-dmsgC.Ready():
log.Debug("Dmsg network ready.")
}

// Perform IP lookup using the context with the proxy dialer
ip, err := dmsgC.LookupIP(ctx, srvs)
if err != nil {
log.WithError(err).Error("failed to lookup IP")
Expand All @@ -102,29 +135,6 @@ DMSG ip utility`,
},
}

func startDmsg(ctx context.Context, log *logging.Logger, pk cipher.PubKey, sk cipher.SecKey) (dmsgC *dmsg.Client, stop func(), err error) {
dmsgC = dmsg.NewClient(pk, sk, disc.NewHTTP(dmsgDisc, &http.Client{}, log), &dmsg.Config{MinSessions: dmsg.DefaultMinSessions})
go dmsgC.Serve(context.Background())

stop = func() {
err := dmsgC.Close()
log.WithError(err).Debug("Disconnected from dmsg network.")
fmt.Printf("\n")
}
log.WithField("public_key", pk.String()).WithField("dmsg_disc", dmsgDisc).
Debug("Connecting to dmsg network...")

select {
case <-ctx.Done():
stop()
return nil, nil, ctx.Err()

case <-dmsgC.Ready():
log.Debug("Dmsg network ready.")
return dmsgC, stop, nil
}
}

// Execute executes root CLI command.
func Execute() {
if err := RootCmd.Execute(); err != nil {
Expand Down
20 changes: 17 additions & 3 deletions pkg/dmsg/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"github.com/skycoin/skywire-utilities/pkg/cipher"
"github.com/skycoin/skywire-utilities/pkg/logging"
"github.com/skycoin/skywire-utilities/pkg/netutil"
"golang.org/x/net/proxy"

"github.com/skycoin/dmsg/pkg/disc"
)
Expand Down Expand Up @@ -502,6 +503,7 @@ func (ce *Client) dialSession(ctx context.Context, entry *disc.Entry) (cs Client
ce.log.WithField("remote_pk", entry.Static).Debug("Dialing session...")

const network = "tcp"
var conn net.Conn

// Trigger dial callback.
if err := ce.conf.Callbacks.OnSessionDial(network, entry.Server.Address); err != nil {
Expand All @@ -514,9 +516,21 @@ func (ce *Client) dialSession(ctx context.Context, entry *disc.Entry) (cs Client
}
}()

conn, err := net.Dial(network, entry.Server.Address)
if err != nil {
return ClientSession{}, err
proxyAddr, ok := ctx.Value("socks5_proxy").(string)
if ok && proxyAddr != "" {
socksDialer, err := proxy.SOCKS5("tcp", proxyAddr, nil, proxy.Direct)
if err != nil {
return ClientSession{}, fmt.Errorf("failed to create SOCKS5 dialer: %w", err)
}
conn, err = socksDialer.Dial(network, entry.Server.Address)
if err != nil {
return ClientSession{}, fmt.Errorf("failed to dial through SOCKS5 proxy: %w", err)
}
} else {
conn, err = net.Dial(network, entry.Server.Address)
if err != nil {
return ClientSession{}, fmt.Errorf("failed to dial: %w", err)
}
}

dSes, err := makeClientSession(&ce.EntityCommon, ce.porter, conn, entry.Static)
Expand Down
Loading