sing-box/common/proxyproto/listener.go

63 lines
1.3 KiB
Go
Raw Normal View History

2022-08-23 13:07:35 +00:00
package proxyproto
import (
std_bufio "bufio"
"net"
"github.com/sagernet/sing/common/buf"
"github.com/sagernet/sing/common/bufio"
M "github.com/sagernet/sing/common/metadata"
"github.com/pires/go-proxyproto"
)
type Listener struct {
net.Listener
2022-09-07 15:01:57 +00:00
AcceptNoHeader bool
2022-08-23 13:07:35 +00:00
}
func (l *Listener) Accept() (net.Conn, error) {
conn, err := l.Listener.Accept()
if err != nil {
return nil, err
}
bufReader := std_bufio.NewReader(conn)
header, err := proxyproto.Read(bufReader)
2022-09-07 15:01:57 +00:00
if err != nil && !(l.AcceptNoHeader && err == proxyproto.ErrNoProxyProtocol) {
2023-03-01 16:18:35 +00:00
return nil, &Error{err}
2022-08-23 13:07:35 +00:00
}
if bufReader.Buffered() > 0 {
cache := buf.NewSize(bufReader.Buffered())
_, err = cache.ReadFullFrom(bufReader, cache.FreeLen())
if err != nil {
2023-03-01 16:18:35 +00:00
return nil, &Error{err}
2022-08-23 13:07:35 +00:00
}
conn = bufio.NewCachedConn(conn, cache)
}
2022-09-07 15:01:57 +00:00
if header != nil {
return &bufio.AddrConn{Conn: conn, Metadata: M.Metadata{
2022-09-25 14:16:24 +00:00
Source: M.SocksaddrFromNet(header.SourceAddr).Unwrap(),
Destination: M.SocksaddrFromNet(header.DestinationAddr).Unwrap(),
2022-09-07 15:01:57 +00:00
}}, nil
}
return conn, nil
2022-08-23 13:07:35 +00:00
}
2023-03-01 16:18:35 +00:00
var _ net.Error = (*Error)(nil)
type Error struct {
error
}
func (e *Error) Unwrap() error {
return e.error
}
func (e *Error) Timeout() bool {
return false
}
func (e *Error) Temporary() bool {
return true
}