sing-box/common/mux/client.go

60 lines
1.8 KiB
Go
Raw Normal View History

2022-07-30 00:29:22 +08:00
package mux
import (
2024-04-29 11:55:25 +08:00
"context"
"net"
"github.com/sagernet/sing-box/adapter"
C "github.com/sagernet/sing-box/constant"
2022-07-30 00:29:22 +08:00
"github.com/sagernet/sing-box/option"
2023-04-20 11:16:22 +08:00
"github.com/sagernet/sing-mux"
E "github.com/sagernet/sing/common/exceptions"
"github.com/sagernet/sing/common/logger"
2024-04-29 11:55:25 +08:00
M "github.com/sagernet/sing/common/metadata"
2022-07-30 00:29:22 +08:00
N "github.com/sagernet/sing/common/network"
)
type Client = mux.Client
func NewClientWithOptions(dialer N.Dialer, logger logger.Logger, options option.OutboundMultiplexOptions) (*Client, error) {
2022-07-30 00:29:22 +08:00
if !options.Enabled {
2022-08-04 09:11:39 +08:00
return nil, nil
2022-07-30 00:29:22 +08:00
}
var brutalOptions mux.BrutalOptions
if options.Brutal != nil && options.Brutal.Enabled {
brutalOptions = mux.BrutalOptions{
Enabled: true,
SendBPS: uint64(options.Brutal.UpMbps * C.MbpsToBps),
ReceiveBPS: uint64(options.Brutal.DownMbps * C.MbpsToBps),
}
if brutalOptions.SendBPS < mux.BrutalMinSpeedBPS {
return nil, E.New("brutal: invalid upload speed")
}
if brutalOptions.ReceiveBPS < mux.BrutalMinSpeedBPS {
return nil, E.New("brutal: invalid download speed")
}
}
2023-04-20 11:16:22 +08:00
return mux.NewClient(mux.Options{
2024-04-29 11:55:25 +08:00
Dialer: &clientDialer{dialer},
Logger: logger,
2023-04-20 11:16:22 +08:00
Protocol: options.Protocol,
MaxConnections: options.MaxConnections,
MinStreams: options.MinStreams,
MaxStreams: options.MaxStreams,
Padding: options.Padding,
Brutal: brutalOptions,
2023-04-20 11:16:22 +08:00
})
2022-07-30 00:29:22 +08:00
}
2024-04-29 11:55:25 +08:00
type clientDialer struct {
N.Dialer
}
func (d *clientDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
return d.Dialer.DialContext(adapter.OverrideContext(ctx), network, destination)
}
func (d *clientDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
return d.Dialer.ListenPacket(adapter.OverrideContext(ctx), destination)
}