sing-box/transport/v2rayhttp/conn.go

111 lines
2 KiB
Go
Raw Normal View History

2022-08-22 14:19:25 +00:00
package v2rayhttp
import (
"io"
"net"
"net/http"
"os"
"time"
2022-08-29 02:10:41 +00:00
"github.com/sagernet/sing-box/common/baderror"
2022-08-22 14:19:25 +00:00
"github.com/sagernet/sing/common"
)
type HTTPConn struct {
reader io.Reader
writer io.Writer
create chan struct{}
err error
}
func newHTTPConn(reader io.Reader, writer io.Writer) HTTPConn {
return HTTPConn{
reader: reader,
writer: writer,
}
}
func newLateHTTPConn(writer io.Writer) *HTTPConn {
return &HTTPConn{
create: make(chan struct{}),
writer: writer,
}
}
func (c *HTTPConn) setup(reader io.Reader, err error) {
c.reader = reader
c.err = err
close(c.create)
2022-08-22 14:19:25 +00:00
}
func (c *HTTPConn) Read(b []byte) (n int, err error) {
if c.reader == nil {
<-c.create
if c.err != nil {
return 0, c.err
}
}
2022-08-25 02:56:57 +00:00
n, err = c.reader.Read(b)
2022-08-29 02:10:41 +00:00
return n, baderror.WrapH2(err)
2022-08-22 14:19:25 +00:00
}
func (c *HTTPConn) Write(b []byte) (n int, err error) {
2022-08-25 02:56:57 +00:00
n, err = c.writer.Write(b)
2022-08-29 02:10:41 +00:00
return n, baderror.WrapH2(err)
2022-08-22 14:19:25 +00:00
}
func (c *HTTPConn) Close() error {
return common.Close(c.reader, c.writer)
}
func (c *HTTPConn) LocalAddr() net.Addr {
return nil
}
func (c *HTTPConn) RemoteAddr() net.Addr {
return nil
}
func (c *HTTPConn) SetDeadline(t time.Time) error {
2022-11-11 14:08:20 +00:00
responseWriter, loaded := c.writer.(interface {
SetWriteDeadline(time.Time) error
})
if !loaded {
return os.ErrInvalid
}
return responseWriter.SetWriteDeadline(t)
2022-08-22 14:19:25 +00:00
}
func (c *HTTPConn) SetReadDeadline(t time.Time) error {
2022-11-11 14:08:20 +00:00
responseWriter, loaded := c.writer.(interface {
SetReadDeadline(time.Time) error
})
if !loaded {
return os.ErrInvalid
}
return responseWriter.SetReadDeadline(t)
2022-08-22 14:19:25 +00:00
}
func (c *HTTPConn) SetWriteDeadline(t time.Time) error {
2022-11-11 14:08:20 +00:00
responseWriter, loaded := c.writer.(interface {
SetWriteDeadline(time.Time) error
})
if !loaded {
return os.ErrInvalid
}
return responseWriter.SetWriteDeadline(t)
2022-08-22 14:19:25 +00:00
}
type ServerHTTPConn struct {
HTTPConn
flusher http.Flusher
}
func (c *ServerHTTPConn) Write(b []byte) (n int, err error) {
n, err = c.writer.Write(b)
if err == nil {
c.flusher.Flush()
}
return
}