github.com/sagernet/sing-mux@v0.2.1-0.20240124034317-9bfb33698bb6/h2mux_conn.go (about)

     1  package mux
     2  
     3  import (
     4  	"context"
     5  	"io"
     6  	"net"
     7  	"os"
     8  	"time"
     9  
    10  	"github.com/sagernet/sing/common"
    11  	"github.com/sagernet/sing/common/baderror"
    12  	M "github.com/sagernet/sing/common/metadata"
    13  )
    14  
    15  type httpConn struct {
    16  	reader io.Reader
    17  	writer io.Writer
    18  	create chan struct{}
    19  	err    error
    20  	cancel context.CancelFunc
    21  }
    22  
    23  func newHTTPConn(reader io.Reader, writer io.Writer) *httpConn {
    24  	return &httpConn{
    25  		reader: reader,
    26  		writer: writer,
    27  	}
    28  }
    29  
    30  func newLateHTTPConn(writer io.Writer, cancel context.CancelFunc) *httpConn {
    31  	return &httpConn{
    32  		create: make(chan struct{}),
    33  		writer: writer,
    34  		cancel: cancel,
    35  	}
    36  }
    37  
    38  func (c *httpConn) setup(reader io.Reader, err error) {
    39  	c.reader = reader
    40  	c.err = err
    41  	close(c.create)
    42  }
    43  
    44  func (c *httpConn) Read(b []byte) (n int, err error) {
    45  	if c.reader == nil {
    46  		<-c.create
    47  		if c.err != nil {
    48  			return 0, c.err
    49  		}
    50  	}
    51  	n, err = c.reader.Read(b)
    52  	return n, baderror.WrapH2(err)
    53  }
    54  
    55  func (c *httpConn) Write(b []byte) (n int, err error) {
    56  	n, err = c.writer.Write(b)
    57  	return n, baderror.WrapH2(err)
    58  }
    59  
    60  func (c *httpConn) Close() error {
    61  	if c.cancel != nil {
    62  		c.cancel()
    63  	}
    64  	return common.Close(c.reader, c.writer)
    65  }
    66  
    67  func (c *httpConn) LocalAddr() net.Addr {
    68  	return M.Socksaddr{}
    69  }
    70  
    71  func (c *httpConn) RemoteAddr() net.Addr {
    72  	return M.Socksaddr{}
    73  }
    74  
    75  func (c *httpConn) SetDeadline(t time.Time) error {
    76  	return os.ErrInvalid
    77  }
    78  
    79  func (c *httpConn) SetReadDeadline(t time.Time) error {
    80  	return os.ErrInvalid
    81  }
    82  
    83  func (c *httpConn) SetWriteDeadline(t time.Time) error {
    84  	return os.ErrInvalid
    85  }
    86  
    87  func (c *httpConn) NeedAdditionalReadDeadline() bool {
    88  	return true
    89  }