Use CloseRead and CloseWrites

This commit is contained in:
9seconds
2021-12-01 10:37:31 +03:00
parent 7b1f86b75d
commit ffad717829
32 changed files with 320 additions and 99 deletions
+5 -4
View File
@@ -4,12 +4,13 @@ import (
"bytes"
"context"
"io"
"net"
"sync"
"github.com/9seconds/mtg/v2/essentials"
)
type connTraffic struct {
net.Conn
essentials.Conn
streamID string
stream EventStream
@@ -37,7 +38,7 @@ func (c connTraffic) Write(b []byte) (int, error) {
}
type connRewind struct {
net.Conn
essentials.Conn
active io.Reader
buf bytes.Buffer
@@ -58,7 +59,7 @@ func (c *connRewind) Rewind() {
c.active = io.MultiReader(&c.buf, c.Conn)
}
func newConnRewind(conn net.Conn) *connRewind {
func newConnRewind(conn essentials.Conn) *connRewind {
rv := &connRewind{
Conn: conn,
}
+3 -3
View File
@@ -14,7 +14,7 @@ import (
)
type ConnRewindBaseConn struct {
testlib.NetConnMock
testlib.EssentialsConnMock
readBuffer bytes.Buffer
}
@@ -29,13 +29,13 @@ type ConnTrafficTestSuite struct {
suite.Suite
eventStreamMock *EventStreamMock
connMock *testlib.NetConnMock
connMock *testlib.EssentialsConnMock
conn io.ReadWriter
}
func (suite *ConnTrafficTestSuite) SetupTest() {
suite.eventStreamMock = &EventStreamMock{}
suite.connMock = &testlib.NetConnMock{}
suite.connMock = &testlib.EssentialsConnMock{}
suite.conn = connTraffic{
Conn: suite.connMock,
streamID: "CONNID",
+5 -3
View File
@@ -23,6 +23,8 @@ import (
"net"
"net/http"
"time"
"github.com/9seconds/mtg/v2/essentials"
)
var (
@@ -116,16 +118,16 @@ const (
// 3. Doing HTTP requests (for example, for FireHOL ipblocklist).
type Network interface {
// Dial establishes context-free TCP connections.
Dial(network, address string) (net.Conn, error)
Dial(network, address string) (essentials.Conn, error)
// DialContext dials using a context. This is a preferrable
// way of establishing TCP connections.
DialContext(ctx context.Context, network, address string) (net.Conn, error)
DialContext(ctx context.Context, network, address string) (essentials.Conn, error)
// MakeHTTPClient build an HTTP client with given dial function. If
// nothing is provided, then DialContext of this interface is going
// to be used.
MakeHTTPClient(func(ctx context.Context, network, address string) (net.Conn, error)) *http.Client
MakeHTTPClient(func(ctx context.Context, network, address string) (essentials.Conn, error)) *http.Client
}
// AntiReplayCache is an interface that is used to detect replay attacks
+2 -2
View File
@@ -4,13 +4,13 @@ import (
"bytes"
"fmt"
"math/rand"
"net"
"github.com/9seconds/mtg/v2/essentials"
"github.com/9seconds/mtg/v2/mtglib/internal/faketls/record"
)
type Conn struct {
net.Conn
essentials.Conn
readBuffer bytes.Buffer
}
+1 -1
View File
@@ -15,7 +15,7 @@ import (
)
type ConnMock struct {
testlib.NetConnMock
testlib.EssentialsConnMock
readBuffer bytes.Buffer
writeBuffer bytes.Buffer
@@ -42,7 +42,7 @@ func (suite *ClientHandshakeTestSuite) TestOk() {
writeData := make([]byte, len(snapshot.Encrypted.Text.data))
readData := make([]byte, len(snapshot.Decrypted.Text.data))
connMock := &testlib.NetConnMock{}
connMock := &testlib.EssentialsConnMock{}
connMock.On("Read", mock.Anything).
Once().
Return(len(snapshot.Decrypted.Text.data), nil).
+3 -2
View File
@@ -2,11 +2,12 @@ package obfuscated2
import (
"crypto/cipher"
"net"
"github.com/9seconds/mtg/v2/essentials"
)
type Conn struct {
net.Conn
essentials.Conn
Encryptor cipher.Stream
Decryptor cipher.Stream
@@ -16,7 +16,7 @@ import (
type ServerHandshakeTestSuite struct {
suite.Suite
connMock *testlib.NetConnMock
connMock *testlib.EssentialsConnMock
proxyConn obfuscated2.Conn
encryptor cipher.Stream
decryptor cipher.Stream
@@ -24,7 +24,7 @@ type ServerHandshakeTestSuite struct {
func (suite *ServerHandshakeTestSuite) SetupTest() {
buf := &bytes.Buffer{}
suite.connMock = &testlib.NetConnMock{}
suite.connMock = &testlib.EssentialsConnMock{}
encryptor, decryptor, err := obfuscated2.ServerHandshake(buf)
suite.NoError(err)
+23 -9
View File
@@ -2,11 +2,14 @@ package relay
import (
"context"
"net"
"errors"
"io"
"sync"
"github.com/9seconds/mtg/v2/essentials"
)
func Relay(ctx context.Context, log Logger, telegramConn, clientConn net.Conn) {
func Relay(ctx context.Context, log Logger, telegramConn, clientConn essentials.Conn) {
defer telegramConn.Close()
defer clientConn.Close()
@@ -29,14 +32,25 @@ func Relay(ctx context.Context, log Logger, telegramConn, clientConn net.Conn) {
wg.Wait()
}
func pump(log Logger, src, dst net.Conn, wg *sync.WaitGroup, direction string) {
defer wg.Done()
func pump(log Logger, src, dst essentials.Conn, wg *sync.WaitGroup, direction string) {
syncer := acquireSyncPair(src, dst)
defer releaseSyncPair(syncer)
defer syncer.Flush()
if n, err := syncer.Sync(); err != nil {
log.Printf("cannot pump %s (written %d bytes): %v", direction, n, err)
defer func() {
syncer.Flush()
releaseSyncPair(syncer)
src.CloseRead()
dst.CloseWrite()
wg.Done()
}()
n, err := syncer.Sync()
switch {
case err == nil:
log.Printf("%s has been finished", direction)
case errors.Is(err, io.EOF):
log.Printf("%s has been finished because of EOF. Written %d bytes", direction, n)
default:
log.Printf("%s has been finished (written %d bytes): %v", direction, n, err)
}
}
+10 -4
View File
@@ -17,8 +17,8 @@ type RelayTestSuite struct {
loggerMock relay.Logger
ctx context.Context
ctxCancel context.CancelFunc
telegramConnMock *testlib.NetConnMock
clientConnMock *testlib.NetConnMock
telegramConnMock *testlib.EssentialsConnMock
clientConnMock *testlib.EssentialsConnMock
}
func (suite *RelayTestSuite) SetupTest() {
@@ -26,8 +26,8 @@ func (suite *RelayTestSuite) SetupTest() {
suite.ctx = ctx
suite.ctxCancel = cancel
suite.loggerMock = &loggerMock{}
suite.telegramConnMock = &testlib.NetConnMock{}
suite.clientConnMock = &testlib.NetConnMock{}
suite.telegramConnMock = &testlib.EssentialsConnMock{}
suite.clientConnMock = &testlib.EssentialsConnMock{}
}
func (suite *RelayTestSuite) TearDownTest() {
@@ -38,12 +38,18 @@ func (suite *RelayTestSuite) TearDownTest() {
func (suite *RelayTestSuite) TestExit() {
suite.telegramConnMock.On("Close").Return(nil)
suite.telegramConnMock.On("CloseRead").Return(nil).Once()
suite.telegramConnMock.On("CloseWrite").Return(nil).Once()
suite.telegramConnMock.On("Read", mock.Anything).Return(10, io.EOF).Once()
suite.telegramConnMock.On("Write", mock.Anything).Return(10, io.EOF).Maybe()
suite.telegramConnMock.On("SetReadDeadline", mock.Anything).Return(nil).Maybe()
suite.clientConnMock.On("Read", mock.Anything).Return(0, io.EOF).Once()
suite.clientConnMock.On("Write", mock.Anything).Return(10, io.EOF).Maybe()
suite.clientConnMock.On("Close").Return(nil)
suite.clientConnMock.On("CloseRead").Return(nil).Once()
suite.clientConnMock.On("CloseWrite").Return(nil).Once()
suite.clientConnMock.On("SetReadDeadline", mock.Anything).Return(nil).Maybe()
relay.Relay(suite.ctx, suite.loggerMock, suite.telegramConnMock, suite.clientConnMock)
}
+1 -1
View File
@@ -48,7 +48,7 @@ func (s *syncPair) Flush() error {
s.mutex.Lock()
defer s.mutex.Unlock()
return s.writer.Flush()
return s.writer.Flush() // nolint: wrapcheck
}
func (s *syncPair) readBlocking(p []byte, blocking bool) (int, error) {
+3 -2
View File
@@ -2,7 +2,8 @@ package telegram
import (
"context"
"net"
"github.com/9seconds/mtg/v2/essentials"
)
type preferIP uint8
@@ -82,5 +83,5 @@ var (
)
type Dialer interface {
DialContext(ctx context.Context, network, address string) (net.Conn, error)
DialContext(ctx context.Context, network, address string) (essentials.Conn, error)
}
+4 -3
View File
@@ -3,8 +3,9 @@ package telegram
import (
"context"
"fmt"
"net"
"strings"
"github.com/9seconds/mtg/v2/essentials"
)
type Telegram struct {
@@ -13,7 +14,7 @@ type Telegram struct {
pool addressPool
}
func (t Telegram) Dial(ctx context.Context, dc int) (net.Conn, error) {
func (t Telegram) Dial(ctx context.Context, dc int) (essentials.Conn, error) {
var addresses []tgAddr
switch t.preferIP {
@@ -28,7 +29,7 @@ func (t Telegram) Dial(ctx context.Context, dc int) (net.Conn, error) {
}
var (
conn net.Conn
conn essentials.Conn
err error
)
+3 -2
View File
@@ -9,6 +9,7 @@ import (
"sync"
"time"
"github.com/9seconds/mtg/v2/essentials"
"github.com/9seconds/mtg/v2/mtglib/internal/faketls"
"github.com/9seconds/mtg/v2/mtglib/internal/faketls/record"
"github.com/9seconds/mtg/v2/mtglib/internal/obfuscated2"
@@ -44,7 +45,7 @@ func (p *Proxy) DomainFrontingAddress() string {
// ServeConn serves a connection. We do not check IP blocklist and
// concurrency limit here.
func (p *Proxy) ServeConn(conn net.Conn) {
func (p *Proxy) ServeConn(conn essentials.Conn) {
p.streamWaitGroup.Add(1)
defer p.streamWaitGroup.Done()
@@ -299,7 +300,7 @@ func NewProxy(opts ProxyOpts) (*Proxy, error) {
pool, err := ants.NewPoolWithFunc(opts.getConcurrency(),
func(arg interface{}) {
proxy.ServeConn(arg.(net.Conn))
proxy.ServeConn(arg.(essentials.Conn))
},
ants.WithLogger(opts.getLogger("ants")),
ants.WithNonblocking(true))
+5 -3
View File
@@ -6,13 +6,15 @@ import (
"encoding/base64"
"net"
"time"
"github.com/9seconds/mtg/v2/essentials"
)
type streamContext struct {
ctx context.Context
ctxCancel context.CancelFunc
clientConn net.Conn
telegramConn net.Conn
clientConn essentials.Conn
telegramConn essentials.Conn
streamID string
dc int
logger Logger
@@ -50,7 +52,7 @@ func (s *streamContext) ClientIP() net.IP {
return s.clientConn.RemoteAddr().(*net.TCPAddr).IP
}
func newStreamContext(ctx context.Context, logger Logger, clientConn net.Conn) *streamContext {
func newStreamContext(ctx context.Context, logger Logger, clientConn essentials.Conn) *streamContext {
connIDBytes := make([]byte, ConnectionIDBytesLength)
if _, err := rand.Read(connIDBytes); err != nil {
+3 -3
View File
@@ -12,7 +12,7 @@ import (
type StreamContextTestSuite struct {
suite.Suite
connMock *testlib.NetConnMock
connMock *testlib.EssentialsConnMock
logger NoopLogger
ctx *streamContext
ctxCancel context.CancelFunc
@@ -27,7 +27,7 @@ func (suite *StreamContextTestSuite) SetupTest() {
ctx = context.WithValue(ctx, "key", "value") // nolint: golint, revive, staticcheck
suite.ctxCancel = cancel
suite.connMock = &testlib.NetConnMock{}
suite.connMock = &testlib.EssentialsConnMock{}
addr := &net.TCPAddr{
IP: net.ParseIP("10.0.0.10"),
@@ -73,7 +73,7 @@ func (suite *StreamContextTestSuite) TestClientIP() {
func (suite *StreamContextTestSuite) TestClose() {
suite.connMock.On("Close").Once().Return(nil)
tgConnMock := &testlib.NetConnMock{}
tgConnMock := &testlib.EssentialsConnMock{}
tgConnMock.On("Close").Once().Return(nil)
suite.ctx.telegramConn = tgConnMock