mihomo/transport/snell/pool.go

85 lines
1.7 KiB
Go
Raw Permalink Normal View History

package snell
import (
"context"
"net"
"time"
2023-11-03 21:01:45 +08:00
"github.com/metacubex/mihomo/component/pool"
"github.com/metacubex/mihomo/transport/shadowsocks/shadowaead"
)
type Pool struct {
2022-04-24 02:07:57 +08:00
pool *pool.Pool[*Snell]
}
func (p *Pool) Get() (net.Conn, error) {
return p.GetContext(context.Background())
}
func (p *Pool) GetContext(ctx context.Context) (net.Conn, error) {
elm, err := p.pool.GetContext(ctx)
if err != nil {
return nil, err
}
2022-04-24 02:07:57 +08:00
return &PoolConn{elm, p}, nil
}
2022-04-24 02:07:57 +08:00
func (p *Pool) Put(conn *Snell) {
if err := HalfClose(conn); err != nil {
2022-04-24 02:07:57 +08:00
_ = conn.Close()
return
}
p.pool.Put(conn)
}
type PoolConn struct {
*Snell
pool *Pool
}
func (pc *PoolConn) Read(b []byte) (int, error) {
// save old status of reply (it mutable by Read)
reply := pc.Snell.reply
n, err := pc.Snell.Read(b)
if err == shadowaead.ErrZeroChunk {
// if reply is false, it should be client halfclose.
// ignore error and read data again.
if !reply {
pc.Snell.reply = false
return pc.Snell.Read(b)
}
}
return n, err
}
func (pc *PoolConn) Write(b []byte) (int, error) {
return pc.Snell.Write(b)
}
func (pc *PoolConn) Close() error {
2023-11-03 21:01:45 +08:00
// mihomo use SetReadDeadline to break bidirectional copy between client and server.
// reset it before reuse connection to avoid io timeout error.
2022-04-24 02:07:57 +08:00
_ = pc.Snell.Conn.SetReadDeadline(time.Time{})
pc.pool.Put(pc.Snell)
return nil
}
func NewPool(factory func(context.Context) (*Snell, error)) *Pool {
2022-04-24 02:07:57 +08:00
p := pool.New[*Snell](
func(ctx context.Context) (*Snell, error) {
return factory(ctx)
},
2022-04-24 02:07:57 +08:00
pool.WithAge[*Snell](15000),
pool.WithSize[*Snell](10),
pool.WithEvict[*Snell](func(item *Snell) {
_ = item.Close()
}),
)
2022-04-24 02:07:57 +08:00
return &Pool{pool: p}
}