2022-07-03 15:23:18 +00:00
|
|
|
package outbound
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"io"
|
|
|
|
"net"
|
2024-07-23 06:54:54 +00:00
|
|
|
"time"
|
2022-07-03 15:23:18 +00:00
|
|
|
|
|
|
|
"github.com/sagernet/sing-box/adapter"
|
|
|
|
C "github.com/sagernet/sing-box/constant"
|
|
|
|
"github.com/sagernet/sing-box/log"
|
2024-07-23 06:54:54 +00:00
|
|
|
"github.com/sagernet/sing/common/buf"
|
|
|
|
"github.com/sagernet/sing/common/bufio"
|
2022-07-08 15:03:57 +00:00
|
|
|
M "github.com/sagernet/sing/common/metadata"
|
|
|
|
N "github.com/sagernet/sing/common/network"
|
2022-07-03 15:23:18 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var _ adapter.Outbound = (*Block)(nil)
|
|
|
|
|
|
|
|
type Block struct {
|
|
|
|
myOutboundAdapter
|
|
|
|
}
|
|
|
|
|
2022-07-12 07:17:29 +00:00
|
|
|
func NewBlock(logger log.ContextLogger, tag string) *Block {
|
2022-07-03 15:23:18 +00:00
|
|
|
return &Block{
|
|
|
|
myOutboundAdapter{
|
|
|
|
protocol: C.TypeBlock,
|
2022-07-29 16:29:22 +00:00
|
|
|
network: []string{N.NetworkTCP, N.NetworkUDP},
|
2022-07-03 15:23:18 +00:00
|
|
|
logger: logger,
|
|
|
|
tag: tag,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *Block) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
2022-07-12 07:17:29 +00:00
|
|
|
h.logger.InfoContext(ctx, "blocked connection to ", destination)
|
2022-07-03 15:23:18 +00:00
|
|
|
return nil, io.EOF
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *Block) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
2022-07-12 07:17:29 +00:00
|
|
|
h.logger.InfoContext(ctx, "blocked packet connection to ", destination)
|
2022-07-03 15:23:18 +00:00
|
|
|
return nil, io.EOF
|
|
|
|
}
|
|
|
|
|
2022-07-07 15:36:32 +00:00
|
|
|
func (h *Block) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
|
2022-07-03 15:23:18 +00:00
|
|
|
conn.Close()
|
2022-07-12 07:17:29 +00:00
|
|
|
h.logger.InfoContext(ctx, "blocked connection to ", metadata.Destination)
|
2022-07-03 15:23:18 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-07-07 15:36:32 +00:00
|
|
|
func (h *Block) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
|
2022-07-12 07:17:29 +00:00
|
|
|
h.logger.InfoContext(ctx, "blocked packet connection to ", metadata.Destination)
|
2024-07-23 06:54:54 +00:00
|
|
|
writer := &discardPacketWriter{
|
|
|
|
timer: time.AfterFunc(C.UDPTimeout, func() {
|
|
|
|
_ = conn.Close()
|
|
|
|
}),
|
|
|
|
}
|
|
|
|
_, _ = bufio.CopyPacket(writer, conn)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
type discardPacketWriter struct {
|
|
|
|
timer *time.Timer
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w *discardPacketWriter) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
|
|
|
|
if w.timer.Stop() {
|
|
|
|
w.timer.Reset(C.UDPTimeout)
|
|
|
|
}
|
|
|
|
buffer.Release()
|
2022-07-03 15:23:18 +00:00
|
|
|
return nil
|
|
|
|
}
|