Skip to content

Commit

Permalink
Remove all external dependencies (#23)
Browse files Browse the repository at this point in the history
  • Loading branch information
majst01 authored Oct 13, 2023
1 parent 07bc9b4 commit 9c89649
Show file tree
Hide file tree
Showing 8 changed files with 65 additions and 130 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
go-mmproxy
4 changes: 2 additions & 2 deletions buffers.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@ import (
var buffers sync.Pool

func init() {
buffers.New = func() interface{} { return make([]byte, math.MaxUint16) }
buffers.New = func() any { return make([]byte, math.MaxUint16) }
}

func GetBuffer() []byte {
return buffers.Get().([]byte)
}

func PutBuffer(buf []byte) {
buffers.Put(buf)
buffers.Put(buf) // nolint:staticcheck
}
7 changes: 0 additions & 7 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,10 +1,3 @@
module github.com/path-network/go-mmproxy

go 1.21

require go.uber.org/zap v1.15.0

require (
go.uber.org/atomic v1.6.0 // indirect
go.uber.org/multierr v1.5.0 // indirect
)
52 changes: 0 additions & 52 deletions go.sum

This file was deleted.

50 changes: 20 additions & 30 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,11 @@ package main
import (
"bufio"
"flag"
"log"
"log/slog"
"net"
"os"
"syscall"
"time"

"go.uber.org/zap"
)

type options struct {
Expand All @@ -26,7 +24,7 @@ type options struct {
allowedSubnetsPath string
AllowedSubnets []*net.IPNet
Listeners int
Logger *zap.Logger
Logger *slog.Logger
udpCloseAfter int
UDPCloseAfter time.Duration
}
Expand All @@ -50,8 +48,8 @@ func init() {
}

func listen(listenerNum int, errors chan<- error) {
logger := Opts.Logger.With(zap.Int("listenerNum", listenerNum),
zap.String("protocol", Opts.Protocol), zap.String("listenAdr", Opts.ListenAddr))
logger := Opts.Logger.With(slog.Int("listenerNum", listenerNum),
slog.String("protocol", Opts.Protocol), slog.String("listenAdr", Opts.ListenAddr))

listenConfig := net.ListenConfig{}
if Opts.Listeners > 1 {
Expand Down Expand Up @@ -87,57 +85,49 @@ func loadAllowedSubnets() error {
return err
}
Opts.AllowedSubnets = append(Opts.AllowedSubnets, ipNet)
Opts.Logger.Info("allowed subnet", zap.String("subnet", ipNet.String()))
Opts.Logger.Info("allowed subnet", slog.String("subnet", ipNet.String()))
}

return nil
}

func initLogger() error {
logConfig := zap.NewProductionConfig()
if Opts.Verbose > 0 {
logConfig.Level.SetLevel(zap.DebugLevel)
}

l, err := logConfig.Build()
if err == nil {
Opts.Logger = l
}
return err
}

func main() {
flag.Parse()
if err := initLogger(); err != nil {
log.Fatalf("Failed to initialize logging: %s", err.Error())
lvl := slog.LevelInfo
if Opts.Verbose > 0 {
lvl = slog.LevelDebug
}
defer Opts.Logger.Sync()
Opts.Logger = slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: lvl}))

if Opts.allowedSubnetsPath != "" {
if err := loadAllowedSubnets(); err != nil {
Opts.Logger.Fatal("failed to load allowed subnets file",
zap.String("path", Opts.allowedSubnetsPath), zap.Error(err))
Opts.Logger.Error("failed to load allowed subnets file", "path", Opts.allowedSubnetsPath, "error", err)
}
}

if Opts.Protocol != "tcp" && Opts.Protocol != "udp" {
Opts.Logger.Fatal("--protocol has to be one of udp, tcp", zap.String("protocol", Opts.Protocol))
Opts.Logger.Error("--protocol has to be one of udp, tcp", slog.String("protocol", Opts.Protocol))
os.Exit(1)
}

if Opts.Mark < 0 {
Opts.Logger.Fatal("--mark has to be >= 0", zap.Int("mark", Opts.Mark))
Opts.Logger.Error("--mark has to be >= 0", slog.Int("mark", Opts.Mark))
os.Exit(1)
}

if Opts.Verbose < 0 {
Opts.Logger.Fatal("-v has to be >= 0", zap.Int("verbose", Opts.Verbose))
Opts.Logger.Error("-v has to be >= 0", slog.Int("verbose", Opts.Verbose))
os.Exit(1)
}

if Opts.Listeners < 1 {
Opts.Logger.Fatal("--listeners has to be >= 1")
Opts.Logger.Error("--listeners has to be >= 1")
os.Exit(1)
}

if Opts.udpCloseAfter < 0 {
Opts.Logger.Fatal("--close-after has to be >= 0", zap.Int("close-after", Opts.udpCloseAfter))
Opts.Logger.Error("--close-after has to be >= 0", slog.Int("close-after", Opts.udpCloseAfter))
os.Exit(1)
}
Opts.UDPCloseAfter = time.Duration(Opts.udpCloseAfter) * time.Second

Expand Down
33 changes: 16 additions & 17 deletions tcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,22 @@ package main
import (
"context"
"io"
"log/slog"
"net"

"go.uber.org/zap"
)

func tcpCopyData(dst net.Conn, src net.Conn, ch chan<- error) {
_, err := io.Copy(dst, src)
ch <- err
}

func tcpHandleConnection(conn net.Conn, logger *zap.Logger) {
func tcpHandleConnection(conn net.Conn, logger *slog.Logger) {
defer conn.Close()
logger = logger.With(zap.String("remoteAddr", conn.RemoteAddr().String()),
zap.String("localAddr", conn.LocalAddr().String()))
logger = logger.With(slog.String("remoteAddr", conn.RemoteAddr().String()),
slog.String("localAddr", conn.LocalAddr().String()))

if !CheckOriginAllowed(conn.RemoteAddr().(*net.TCPAddr).IP) {
logger.Debug("connection origin not in allowed subnets", zap.Bool("dropConnection", true))
logger.Debug("connection origin not in allowed subnets", slog.Bool("dropConnection", true))
return
}

Expand All @@ -40,13 +39,13 @@ func tcpHandleConnection(conn net.Conn, logger *zap.Logger) {

n, err := conn.Read(buffer)
if err != nil {
logger.Debug("failed to read PROXY header", zap.Error(err), zap.Bool("dropConnection", true))
logger.Debug("failed to read PROXY header", "error", err, slog.Bool("dropConnection", true))
return
}

saddr, _, restBytes, err := PROXYReadRemoteAddr(buffer[:n], TCP)
if err != nil {
logger.Debug("failed to parse PROXY header", zap.Error(err), zap.Bool("dropConnection", true))
logger.Debug("failed to parse PROXY header", "error", err, slog.Bool("dropConnection", true))
return
}

Expand All @@ -63,7 +62,7 @@ func tcpHandleConnection(conn net.Conn, logger *zap.Logger) {
if saddr != nil {
clientAddr = saddr.String()
}
logger = logger.With(zap.String("clientAddr", clientAddr), zap.String("targetAddr", targetAddr))
logger = logger.With(slog.String("clientAddr", clientAddr), slog.String("targetAddr", targetAddr))
if Opts.Verbose > 1 {
logger.Debug("successfully parsed PROXY header")
}
Expand All @@ -74,7 +73,7 @@ func tcpHandleConnection(conn net.Conn, logger *zap.Logger) {
}
upstreamConn, err := dialer.Dial("tcp", targetAddr)
if err != nil {
logger.Debug("failed to establish upstream connection", zap.Error(err), zap.Bool("dropConnection", true))
logger.Debug("failed to establish upstream connection", "error", err, slog.Bool("dropConnection", true))
return
}

Expand All @@ -84,13 +83,13 @@ func tcpHandleConnection(conn net.Conn, logger *zap.Logger) {
}

if err := conn.(*net.TCPConn).SetNoDelay(true); err != nil {
logger.Debug("failed to set nodelay on downstream connection", zap.Error(err), zap.Bool("dropConnection", true))
logger.Debug("failed to set nodelay on downstream connection", "error", err, slog.Bool("dropConnection", true))
} else if Opts.Verbose > 1 {
logger.Debug("successfully set NoDelay on downstream connection")
}

if err := upstreamConn.(*net.TCPConn).SetNoDelay(true); err != nil {
logger.Debug("failed to set nodelay on upstream connection", zap.Error(err), zap.Bool("dropConnection", true))
logger.Debug("failed to set nodelay on upstream connection", "error", err, slog.Bool("dropConnection", true))
} else if Opts.Verbose > 1 {
logger.Debug("successfully set NoDelay on upstream connection")
}
Expand All @@ -99,7 +98,7 @@ func tcpHandleConnection(conn net.Conn, logger *zap.Logger) {
n, err := upstreamConn.Write(restBytes)
if err != nil {
logger.Debug("failed to write data to upstream connection",
zap.Error(err), zap.Bool("dropConnection", true))
"error", err, slog.Bool("dropConnection", true))
return
}
restBytes = restBytes[n:]
Expand All @@ -114,17 +113,17 @@ func tcpHandleConnection(conn net.Conn, logger *zap.Logger) {

err = <-outErr
if err != nil {
logger.Debug("connection broken", zap.Error(err), zap.Bool("dropConnection", true))
logger.Debug("connection broken", "error", err, slog.Bool("dropConnection", true))
} else if Opts.Verbose > 1 {
logger.Debug("connection closing")
}
}

func TCPListen(listenConfig *net.ListenConfig, logger *zap.Logger, errors chan<- error) {
func TCPListen(listenConfig *net.ListenConfig, logger *slog.Logger, errors chan<- error) {
ctx := context.Background()
ln, err := listenConfig.Listen(ctx, "tcp", Opts.ListenAddr)
if err != nil {
logger.Error("failed to bind listener", zap.Error(err))
logger.Error("failed to bind listener", "error", err)
errors <- err
return
}
Expand All @@ -134,7 +133,7 @@ func TCPListen(listenConfig *net.ListenConfig, logger *zap.Logger, errors chan<-
for {
conn, err := ln.Accept()
if err != nil {
logger.Error("failed to accept new connection", zap.Error(err))
logger.Error("failed to accept new connection", "error", err)
errors <- err
return
}
Expand Down
Loading

0 comments on commit 9c89649

Please sign in to comment.