2022-07-03 12:59:25 +00:00
|
|
|
package dialer
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"net"
|
|
|
|
"sync"
|
|
|
|
|
2022-07-08 15:03:57 +00:00
|
|
|
"github.com/sagernet/sing-box/adapter"
|
2022-07-03 12:59:25 +00:00
|
|
|
E "github.com/sagernet/sing/common/exceptions"
|
|
|
|
M "github.com/sagernet/sing/common/metadata"
|
|
|
|
N "github.com/sagernet/sing/common/network"
|
|
|
|
)
|
|
|
|
|
2022-07-07 13:47:21 +00:00
|
|
|
type DetourDialer struct {
|
2024-11-09 13:16:11 +00:00
|
|
|
outboundManager adapter.OutboundManager
|
|
|
|
detour string
|
|
|
|
dialer N.Dialer
|
|
|
|
initOnce sync.Once
|
|
|
|
initErr error
|
2022-07-03 12:59:25 +00:00
|
|
|
}
|
|
|
|
|
2024-11-09 13:16:11 +00:00
|
|
|
func NewDetour(outboundManager adapter.OutboundManager, detour string) N.Dialer {
|
|
|
|
return &DetourDialer{outboundManager: outboundManager, detour: detour}
|
2022-07-06 15:11:48 +00:00
|
|
|
}
|
|
|
|
|
2022-07-07 13:47:21 +00:00
|
|
|
func (d *DetourDialer) Start() error {
|
2022-07-06 15:11:48 +00:00
|
|
|
_, err := d.Dialer()
|
|
|
|
return err
|
2022-07-03 12:59:25 +00:00
|
|
|
}
|
|
|
|
|
2022-07-07 13:47:21 +00:00
|
|
|
func (d *DetourDialer) Dialer() (N.Dialer, error) {
|
2022-07-03 12:59:25 +00:00
|
|
|
d.initOnce.Do(func() {
|
|
|
|
var loaded bool
|
2024-11-09 13:16:11 +00:00
|
|
|
d.dialer, loaded = d.outboundManager.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
|
|
|
|
}
|
|
|
|
|
2022-07-07 13:47:21 +00:00
|
|
|
func (d *DetourDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
2022-07-03 12:59:25 +00:00
|
|
|
dialer, err := d.Dialer()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2023-12-01 04:24:29 +00:00
|
|
|
return dialer.DialContext(ctx, network, destination)
|
2022-07-03 12:59:25 +00:00
|
|
|
}
|
|
|
|
|
2022-07-07 13:47:21 +00:00
|
|
|
func (d *DetourDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
2022-07-03 12:59:25 +00:00
|
|
|
dialer, err := d.Dialer()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return dialer.ListenPacket(ctx, destination)
|
|
|
|
}
|
2022-07-07 13:47:21 +00:00
|
|
|
|
|
|
|
func (d *DetourDialer) Upstream() any {
|
|
|
|
detour, _ := d.Dialer()
|
|
|
|
return detour
|
|
|
|
}
|