SpoofDPI/proxy/server.go

73 lines
1.5 KiB
Go
Raw Normal View History

2024-07-22 10:59:11 +00:00
package proxy
2022-01-04 16:47:18 +00:00
import (
2024-08-22 08:49:05 +00:00
"context"
2022-05-12 12:21:54 +00:00
"errors"
2024-08-22 08:49:05 +00:00
"github.com/xvzc/SpoofDPI/util"
2022-06-05 05:50:55 +00:00
"io"
2022-01-04 16:47:18 +00:00
"net"
2022-03-04 23:46:47 +00:00
"time"
2022-01-11 15:05:16 +00:00
2024-08-22 08:49:05 +00:00
"github.com/xvzc/SpoofDPI/util/log"
2022-01-04 16:47:18 +00:00
)
2024-08-15 07:50:03 +00:00
const (
BufferSize = 1024
TLSHeaderLen = 5
)
2024-08-22 08:49:05 +00:00
func ReadBytes(ctx context.Context, conn *net.TCPConn, dest []byte) ([]byte, error) {
n, err := readBytesInternal(ctx, conn, dest)
return dest[:n], err
}
2022-05-12 12:21:54 +00:00
2024-08-22 08:49:05 +00:00
func readBytesInternal(ctx context.Context, conn *net.TCPConn, dest []byte) (int, error) {
2024-08-08 20:52:59 +00:00
totalRead, err := conn.Read(dest)
if err != nil {
var opError *net.OpError
switch {
case errors.As(err, &opError) && opError.Timeout():
2024-08-08 20:52:59 +00:00
return totalRead, errors.New("timed out")
default:
return totalRead, err
2022-11-29 07:54:28 +00:00
}
}
2024-08-08 20:52:59 +00:00
return totalRead, nil
2022-01-04 16:47:18 +00:00
}
2024-08-22 08:49:05 +00:00
func Serve(ctx context.Context, from *net.TCPConn, to *net.TCPConn, proto string, fd string, td string, timeout int) {
ctx = util.GetCtxWithScope(ctx, proto)
logger := log.GetCtxLogger(ctx)
defer func() {
from.Close()
to.Close()
2024-08-22 08:49:05 +00:00
logger.Debug().Msgf("closing proxy connection: %s -> %s", fd, td)
}()
2024-08-15 07:50:03 +00:00
buf := make([]byte, BufferSize)
2022-11-29 07:54:28 +00:00
for {
if timeout > 0 {
from.SetReadDeadline(
time.Now().Add(time.Millisecond * time.Duration(timeout)),
)
}
2023-09-08 08:35:41 +00:00
2024-08-22 08:49:05 +00:00
bytesRead, err := ReadBytes(ctx, from, buf)
2022-11-29 07:54:28 +00:00
if err != nil {
if err == io.EOF {
2024-08-22 08:49:05 +00:00
logger.Debug().Msgf("finished reading from %s", fd)
2022-11-29 07:54:28 +00:00
return
}
2024-08-22 08:49:05 +00:00
logger.Debug().Msgf("error reading from %s: %s", fd, err)
2022-11-29 07:54:28 +00:00
return
}
if _, err := to.Write(bytesRead); err != nil {
2024-08-22 08:49:05 +00:00
logger.Debug().Msgf("error Writing to %s", td)
2022-11-29 07:54:28 +00:00
return
}
}
2022-01-04 16:47:18 +00:00
}