2022-07-03 12:59:25 +00:00
|
|
|
package dialer
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"net"
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
E "github.com/sagernet/sing/common/exceptions"
|
|
|
|
M "github.com/sagernet/sing/common/metadata"
|
|
|
|
N "github.com/sagernet/sing/common/network"
|
2022-07-06 07:01:09 +00:00
|
|
|
|
|
|
|
"github.com/sagernet/sing-box/adapter"
|
2022-07-03 12:59:25 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type detourDialer struct {
|
|
|
|
router adapter.Router
|
2022-07-06 15:11:48 +00:00
|
|
|
detour string
|
2022-07-03 12:59:25 +00:00
|
|
|
dialer N.Dialer
|
|
|
|
initOnce sync.Once
|
|
|
|
initErr error
|
|
|
|
}
|
|
|
|
|
2022-07-06 15:11:48 +00:00
|
|
|
func NewDetour(router adapter.Router, detour string) N.Dialer {
|
|
|
|
return &detourDialer{router: router, detour: detour}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *detourDialer) Start() error {
|
|
|
|
_, err := d.Dialer()
|
|
|
|
return err
|
2022-07-03 12:59:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (d *detourDialer) Dialer() (N.Dialer, error) {
|
|
|
|
d.initOnce.Do(func() {
|
|
|
|
var loaded bool
|
2022-07-06 15:11:48 +00:00
|
|
|
d.dialer, loaded = d.router.Outbound(d.detour)
|
2022-07-03 12:59:25 +00:00
|
|
|
if !loaded {
|
2022-07-06 15:11:48 +00:00
|
|
|
d.initErr = E.New("outbound detour not found: ", d.detour)
|
2022-07-03 12:59:25 +00:00
|
|
|
}
|
|
|
|
})
|
|
|
|
return d.dialer, d.initErr
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *detourDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
|
|
|
dialer, err := d.Dialer()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return dialer.DialContext(ctx, network, destination)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *detourDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
|
|
|
dialer, err := d.Dialer()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return dialer.ListenPacket(ctx, destination)
|
|
|
|
}
|