Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: use zerolog #14

Merged
merged 1 commit into from
Mar 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ export GO111MODULE=on
TAGS=urfave_cli_no_docs,netgo
GOEXE=/opt/hostedtoolcache/go/1.22.0/x64/bin/go
BUILD=$(GOEXE) build -tags $(TAGS) -trimpath
LDFLAGS := -s -w -X main.Version="v0.2.5" -X main.Date=$(shell date +"%Y-%m-%d")
VER=$(shell git rev-parse --short HEAD)
DATE=$(shell date +"%Y-%m-%d")
LDFLAGS := -s -w -X main.Version=$(VER) -X main.Date=$(DATE)
TARGET := bin/localtunnel

.PHONY: fmt build vet clean build_local
Expand Down
6 changes: 3 additions & 3 deletions auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,21 @@ package main

import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"hash"

"github.com/google/uuid"
"golang.org/x/crypto/sha3"
)

type Authenticator struct {
hasher hash.Hash
}

func NewAuthenticator(secret string) *Authenticator {
digest := sha3.Sum256([]byte(secret))
digest := sha256.New().Sum([]byte(secret))
return &Authenticator{
hasher: hmac.New(sha3.New256, digest[:]),
hasher: hmac.New(sha256.New, digest[:]),
}
}

Expand Down
4 changes: 2 additions & 2 deletions cli.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package main

import (
"log/slog"
"time"

"github.com/rs/zerolog"
"github.com/urfave/cli/v2"
)

Expand Down Expand Up @@ -39,7 +39,7 @@ func newApp(local, server action) *cli.App {
Value: false,
Usage: "verbos log",
Action: func(_ *cli.Context, b bool) error {
UpdateLogger(slog.LevelDebug)
UpdateLogger(zerolog.TraceLevel)
return nil
},
},
Expand Down
56 changes: 31 additions & 25 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@ package main

import (
"encoding/binary"
"log/slog"
"errors"
"io"
"net"
"os"
"strconv"

"github.com/rs/zerolog/log"
)

type Client struct {
Expand All @@ -19,12 +22,12 @@ type Client struct {
func NewClient(localPort, mappingPort int, secret, tunnelAddr string) *Client {
addr, err := net.ResolveTCPAddr("tcp", tunnelAddr)
if err != nil {
slog.Error("invalid tunnel address.", slog.Any("err", err))
log.Error().Err(err).Msg("invalid tunnel address.")
os.Exit(1)
}
conn, err := net.DialTCP("tcp", nil, addr)
if err != nil {
slog.Error("connect to tunnel fail", slog.Any("err", err))
log.Error().Err(err).Msg("connect to tunnel fail")
os.Exit(1)
}

Expand All @@ -37,45 +40,45 @@ func NewClient(localPort, mappingPort int, secret, tunnelAddr string) *Client {
if len(secret) > 0 {
client.author = NewAuthenticator(secret)
if err := client.handShake(client.tunnel); err != nil {
slog.Error("handShake fail.", slog.Any("err", err))
log.Error().Err(err).Msg("handShake fail.")
_ = client.tunnel.Close()
os.Exit(1)
}
}

slog.Info("client handShake success.")
log.Info().Msg("client handShake success.")

bs := helloPacket(uint16(mappingPort))

if _, err := client.tunnel.Write(bs); err != nil {
slog.Error("send hello fail.", slog.Any("err", err))
log.Error().Err(err).Msg("send hello fail.")
os.Exit(1)
}

var ttype ttype

if err := binary.Read(client.tunnel, binary.BigEndian, &ttype); err != nil {
slog.Error("read hello fail.", slog.Any("err", err))
log.Error().Err(err).Msg("read hello fail.")
os.Exit(1)
}

slog.Info("read message type.", slog.Any("ttype", ttype))
log.Info().Uint8("type", uint8(ttype)).Msg("read message type.")

switch ttype {
case fail:
msg := parseFailPacket(client.tunnel)
slog.Error("receive error.", slog.String("err", msg))
log.Error().Str("err", msg).Msg("receive error.")
os.Exit(1)
case hello:
rport, err := parseHelloPacket(client.tunnel)
if err != nil {
slog.Error("read hello fail.", slog.Any("err", err))
log.Error().Err(err).Msg("read hello fail.")
os.Exit(1)
}
client.mappingPort = rport

mappingAddr := addr.IP.String() + ":" + strconv.FormatUint(uint64(rport), 10)
slog.Info("forward info", slog.String("to", mappingAddr))
log.Info().Str("to", mappingAddr).Msg("forward info")
default:
panic("unhandled default case")
}
Expand All @@ -87,20 +90,25 @@ func (c *Client) Start() error {
for {
var ttype ttype
if err := binary.Read(c.tunnel, binary.BigEndian, &ttype); err != nil {
slog.Error("read fail.", slog.Any("err", err))
if errors.Is(err, io.EOF) {
log.Warn().Msg("server shutdown.")
} else {
log.Error().Err(err).Msg("read fail.")
}
os.Exit(1)
}

slog.Info("ttype ", slog.Any("ttype", ttype))
log.Info().Uint8("type", uint8(ttype)).Msg("receive request")

switch ttype {
case connect:
if err := c.handleConnect(); err != nil {
slog.Error("connect fail.", slog.Any("err", err))
log.Error().Err(err).Msg("connect fail.")
os.Exit(1)
}
case fail:
msg := parseFailPacket(c.tunnel)
slog.Error("receive error.", slog.String("err", msg))
log.Error().Str("err", msg).Msg("receive error.")
os.Exit(1)
default:
panic("unhandled default case")
Expand All @@ -115,11 +123,11 @@ func (c *Client) handShake(remote net.Conn) error {
return err
}

slog.Info("client handShake.", slog.Any("id", uid.String()))
log.Info().Str("id", uid.String()).Msg("client handShake.")

sign := c.author.Sign(uid)

slog.Debug("client handShake. sign ", slog.Any("sign", sign))
log.Debug().Str("sign", sign).Msg("client handShake. sign ")

bs := authPacket(sign)

Expand All @@ -140,33 +148,31 @@ func (c *Client) handleConnect() error {
}

if c.author != nil {
slog.Debug("client handShake")
log.Debug().Msg("client handShake")
if err := c.handShake(remote); err != nil {
slog.Error("handShake fail.", slog.Any("err", err))
log.Error().Err(err).Msg("handShake fail.")
os.Exit(1)
}
}
slog.Debug("client handShake success")
log.Debug().Msg("client handShake success")

packet := transferOrConnectPacket(uid, transfer)

if _, err := remote.Write(packet); err != nil {
slog.Error("Write fail.", slog.Any("err", err))
log.Error().Err(err).Msg("Write fail.")
os.Exit(1)
}

addr := "localhost:" + strconv.FormatInt(int64(c.localPort), 10)
local, err := net.Dial("tcp", addr)
if err != nil {
slog.Error("dial localfail.", slog.Any("err", err))
log.Error().Err(err).Msg("dial localfail.")
os.Exit(1)
}

inCount, outCount, _ := relay(local, remote)

slog.Info("forward success.", slog.Int64("read_size", inCount),
slog.Int64("write_size", outCount))

log.Info().Int64("in_size", inCount).Int64("out_size", outCount).Msg("forward success")
return nil
}

Expand Down
4 changes: 2 additions & 2 deletions cmd.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package main

import (
"log/slog"
"os"

"github.com/google/uuid"
"github.com/rs/zerolog/log"
"github.com/urfave/cli/v2"
)

Expand All @@ -26,6 +26,6 @@ func main() {
}

if err := newApp(local, server).Run(os.Args); err != nil {
slog.Error("start error.", slog.Any("err", err))
log.Fatal().Err(err).Msg("start error.")
}
}
5 changes: 3 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@ go 1.22

require (
github.com/google/uuid v1.6.0
github.com/lmittmann/tint v1.0.4
github.com/rs/zerolog v1.32.0
github.com/urfave/cli/v2 v2.27.1
golang.org/x/crypto v0.19.0
)

require (
github.com/cpuguy83/go-md2man/v2 v2.0.3 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/xrash/smetrics v0.0.0-20231213231151-1d8dd44e695e // indirect
golang.org/x/sys v0.17.0 // indirect
Expand Down
19 changes: 15 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,16 +1,27 @@
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/cpuguy83/go-md2man/v2 v2.0.3 h1:qMCsGGgs+MAzDFyp9LpAe1Lqy/fY/qCovCm0qnXZOBM=
github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/lmittmann/tint v1.0.4 h1:LeYihpJ9hyGvE0w+K2okPTGUdVLfng1+nDNVR4vWISc=
github.com/lmittmann/tint v1.0.4/go.mod h1:HIS3gSy7qNwGCj+5oRjAutErFBl4BzdQP6cJZ0NfMwE=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/zerolog v1.32.0 h1:keLypqrlIjaFsbmJOBdB/qvyF8KEtCWHwobLp5l/mQ0=
github.com/rs/zerolog v1.32.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/urfave/cli/v2 v2.27.1 h1:8xSQ6szndafKVRmfyeUMxkNUJQMjL1F2zmsZ+qHpfho=
github.com/urfave/cli/v2 v2.27.1/go.mod h1:8qnjx1vcq5s2/wpsqoZFndg2CE5tNFyrTvS6SinrnYQ=
github.com/xrash/smetrics v0.0.0-20231213231151-1d8dd44e695e h1:+SOyEddqYF09QP7vr7CgJ1eti3pY9Fn3LHO1M1r/0sI=
github.com/xrash/smetrics v0.0.0-20231213231151-1d8dd44e695e/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8=
golang.org/x/crypto v0.19.0 h1:ENy+Az/9Y1vSrlrvBSyna3PITt4tiZLf7sgCjZBX7Wo=
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
23 changes: 8 additions & 15 deletions logger.go
Original file line number Diff line number Diff line change
@@ -1,27 +1,20 @@
package main

import (
"io"
"log/slog"
"os"
"time"

"github.com/lmittmann/tint"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)

func init() {
logger := NewLevelHandler(slog.LevelInfo, os.Stderr)
slog.SetDefault(logger)
log.Logger = log.Output(zerolog.ConsoleWriter{
Out: os.Stderr,
TimeFormat: time.StampMilli,
})
}

func UpdateLogger(level slog.Level) {
logger := NewLevelHandler(level, os.Stderr)
slog.SetDefault(logger)
}

func NewLevelHandler(level slog.Level, writer io.Writer) *slog.Logger {
return slog.New(tint.NewHandler(writer, &tint.Options{
Level: level,
TimeFormat: time.RFC3339,
}))
func UpdateLogger(level zerolog.Level) {
zerolog.SetGlobalLevel(level)
}
6 changes: 3 additions & 3 deletions protocol.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ package main
import (
"bytes"
"encoding/binary"
"log/slog"
"net"

"github.com/google/uuid"
"github.com/rs/zerolog/log"
)

type (
Expand Down Expand Up @@ -78,12 +78,12 @@ func authPacket(tag string) []byte {
func parseFailPacket(conn net.Conn) string {
var size uint32
if err := binary.Read(conn, binary.BigEndian, &size); err != nil {
slog.Error("parseFailPacket err.", slog.Any("err", err))
log.Error().Err(err).Msg("parseFailPacket err.")
return ""
}
data := make([]byte, size)
if err := binary.Read(conn, binary.BigEndian, &data); err != nil {
slog.Error("parseFailPacket err.", slog.Any("err", err))
log.Error().Err(err).Msg("parseFailPacket err.")
return ""
}
return string(data)
Expand Down
Loading