Skip to content

Commit

Permalink
reorganize and cleanuo
Browse files Browse the repository at this point in the history
  • Loading branch information
olebeck committed Jul 20, 2024
1 parent d02e52b commit 8ab8490
Show file tree
Hide file tree
Showing 53 changed files with 2,262 additions and 1,359 deletions.
61 changes: 13 additions & 48 deletions cmd/bedrocktool/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,28 +24,23 @@ import (
_ "github.com/bedrock-tool/bedrocktool/subcommands/skins"
_ "github.com/bedrock-tool/bedrocktool/subcommands/world"

"github.com/google/subcommands"
"github.com/sirupsen/logrus"
)

var uis = map[string]ui.UI{}

func selectUI() ui.UI {
var ui ui.UI
if len(os.Args) < 2 {
var ok bool
ui, ok = uis["gui"]
if !ok {
ui = uis["tui"]
}
utils.Options.IsInteractive = true
} else {
ui = uis["cli"]
ui, ok := uis["gui"]
if ok {
return ui
}
}
return ui
return uis["cli"]
}

func setupLogging() {
func setupLogging(isDebug bool) {
logFile, err := os.Create("bedrocktool.log")
if err != nil {
panic(err)
Expand All @@ -63,17 +58,21 @@ func setupLogging() {

redirectStderr(logFile)

logrus.SetLevel(logrus.DebugLevel)
if isDebug {
logrus.SetLevel(logrus.TraceLevel)
}
logrus.SetOutput(originalStdout)
logrus.AddHook(lfshook.NewHook(logFile, &logrus.TextFormatter{
DisableColors: true,
}))
}

func main() {
setupLogging()

isDebug := updater.Version == ""

setupLogging(isDebug)

if isDebug {
f, err := os.Create("cpu.pprof")
if err != nil {
Expand All @@ -83,7 +82,6 @@ func main() {
defer pprof.StopCPUProfile()
}

logrus.SetLevel(logrus.DebugLevel)
log := logrus.WithField("part", "main")

if !isDebug {
Expand Down Expand Up @@ -111,18 +109,13 @@ func main() {
os.Exit(1)
}

flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ContinueOnError)
//flag.StringVar(&utils.RealmsEnv, "realms-env", "", "realms env")
flag.BoolVar(&utils.Options.Debug, "debug", false, locale.Loc("debug_mode", nil))
flag.BoolVar(&utils.Options.ExtraDebug, "extra-debug", false, locale.Loc("extra_debug", nil))
flag.StringVar(&utils.Options.PathCustomUserData, "userdata", "", locale.Loc("custom_user_data", nil))
flag.String("lang", "", "lang")
flag.BoolVar(&utils.Options.Capture, "capture", false, "Capture pcap2 file")

subcommands.Register(subcommands.HelpCommand(), "")
subcommands.ImportantFlag("debug")
subcommands.ImportantFlag("capture")
subcommands.HelpCommand()

ui := selectUI()

// exit cleanup
Expand Down Expand Up @@ -173,34 +166,6 @@ func (c *TransCMD) Execute(ctx context.Context) error {
return nil
}

/*
type CreateCustomDataCMD struct {
path string
}
func (*CreateCustomDataCMD) Name() string { return "create-customdata" }
func (*CreateCustomDataCMD) Synopsis() string { return "" }
func (c *CreateCustomDataCMD) SetFlags(f *flag.FlagSet) {
f.StringVar(&c.path, "path", "customdata.json", "where to save")
}
func (c *CreateCustomDataCMD) Execute(_ context.Context, ui ui.UI) error {
var data proxy.CustomClientData
fio, err := os.Create(c.path)
if err != nil {
return err
}
defer fio.Close()
e := json.NewEncoder(fio)
if err = e.Encode(data); err != nil {
return err
}
return nil
}
*/

func init() {
commands.RegisterCommand(&TransCMD{})
//commands.RegisterCommand(&CreateCustomDataCMD{})
}
7 changes: 0 additions & 7 deletions cmd/bedrocktool/tui.go

This file was deleted.

3 changes: 0 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ require (
github.com/fatih/color v1.17.0
github.com/flytam/filenamify v1.2.0
github.com/go-gl/mathgl v1.1.0
github.com/google/subcommands v1.2.0
github.com/google/uuid v1.6.0
github.com/gregwebs/go-recovery v0.3.2
github.com/klauspost/compress v1.17.9
Expand Down Expand Up @@ -45,7 +44,6 @@ require (
gioui.org/cpu v0.0.0-20220412190645-f1e9e8c3b1f7 // indirect
git.wow.st/gmp/jni v0.0.0-20210610011705-34026c7e22d0 // indirect
github.com/brentp/intintmap v0.0.0-20190211203843-30dc0ade9af9 // indirect
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/changkun/lockfree v0.0.1 // indirect
github.com/df-mc/atomic v1.10.0 // indirect
github.com/df-mc/worldupgrader v1.0.15 // indirect
Expand All @@ -63,7 +61,6 @@ require (
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/muhammadmuzzammil1998/jsonc v1.0.0 // indirect
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect
github.com/rogpeppe/go-internal v1.11.0 // indirect
github.com/segmentio/fasthash v1.0.3 // indirect
github.com/tklauser/go-sysconf v0.3.14 // indirect
github.com/tklauser/numcpus v0.8.0 // indirect
Expand Down
6 changes: 0 additions & 6 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@ github.com/OneOfOne/xxhash v1.2.8 h1:31czK/TI9sNkxIKfaUfGlU47BAxQ0ztGgd9vPyqimf8
github.com/OneOfOne/xxhash v1.2.8/go.mod h1:eZbhyaAYD41SGSSsnmcpxVoRiQ/MPUTjUdIIOT9Um7Q=
github.com/brentp/intintmap v0.0.0-20190211203843-30dc0ade9af9 h1:/G0ghZwrhou0Wq21qc1vXXMm/t/aKWkALWwITptKbE0=
github.com/brentp/intintmap v0.0.0-20190211203843-30dc0ade9af9/go.mod h1:TOk10ahXejq9wkEaym3KPRNeuR/h5Jx+s8QRWIa2oTM=
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/changkun/lockfree v0.0.1 h1:5WefVJLglY4IHRqOQmh6Ao6wkJYaJkarshKU8VUtId4=
github.com/changkun/lockfree v0.0.1/go.mod h1:3bKiaXn/iNzIPlSvSOMSVbRQUQtAp8qUAyBUtzU11s4=
github.com/cloudfoundry/jibber_jabber v0.0.0-20151120183258-bcc4c8345a21 h1:tuijfIjZyjZaHq9xDUh0tNitwXshJpbLkqMOJv4H3do=
Expand Down Expand Up @@ -74,8 +72,6 @@ github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/pprof v0.0.0-20240618054019-d3b898a103f8 h1:ASJ/LAqdCHOyMYI+dwNxn7Rd8FscNkMyTr1KZU1JI/M=
github.com/google/pprof v0.0.0-20240618054019-d3b898a103f8/go.mod h1:K1liHPHnj73Fdn/EKuT8nrFqBihUSKXoLYU0BuatOYo=
github.com/google/subcommands v1.2.0 h1:vWQspBTo2nEqTUFita5/KeEWlUL8kQObDFbub/EN9oE=
github.com/google/subcommands v1.2.0/go.mod h1:ZjhPrFU+Olkh9WazFPsl27BQ4UPiG37m3yTrtFlrHVk=
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/gregwebs/errors v1.2.2 h1:JQG47s42qKzMPdIT8pmCkZ+2Trhoyskgimxbyp7lD+U=
Expand Down Expand Up @@ -111,8 +107,6 @@ github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
github.com/rifflock/lfshook v0.0.0-20180920164130-b9218ef580f5 h1:mZHayPoR0lNmnHyvtYjDeq0zlVHn9K/ZXoy17ylucdo=
github.com/rifflock/lfshook v0.0.0-20180920164130-b9218ef580f5/go.mod h1:GEXHk5HgEKCvEIIrSpFI3ozzG5xOKA2DVlEX/gGnewM=
github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M=
github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA=
github.com/sandertv/go-raknet v1.14.0 h1:2vtO1m1DFLFszeCcV7mVZfVgkDcAbSxcjM2BlrVrEGs=
github.com/sandertv/go-raknet v1.14.0/go.mod h1:/yysjwfCXm2+2OY8mBazLzcxJ3irnylKCyG3FLgUPVU=
github.com/sandertv/gophertunnel v1.38.0 h1:hGCq9uhAmIFOLAaw/qcLkmcHVo7dVzf3I9Iqx0GOb+0=
Expand Down
2 changes: 1 addition & 1 deletion gophertunnel
24 changes: 12 additions & 12 deletions handlers/capture.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import (
"github.com/sirupsen/logrus"
)

func (p *packetCapturer) dumpPacket(toServer bool, payload []byte) {
func (p *packetCapturer) dumpPacket(toServer bool, payload []byte, timeReceived time.Time) {
p.dumpLock.Lock()
payloadCompressed := s2.EncodeBetter(nil, payload)

Expand All @@ -30,15 +30,15 @@ func (p *packetCapturer) dumpPacket(toServer bool, payload []byte) {
} else {
buf = append(buf, 0)
}
buf = binary.LittleEndian.AppendUint64(buf, uint64(time.Now().UnixMilli()))
buf = binary.LittleEndian.AppendUint64(buf, uint64(timeReceived.UnixMilli()))
buf = append(buf, payloadCompressed...)
buf = append(buf, []byte{0xBB, 0xBB, 0xBB, 0xBB}...)
p.wPacket.Write(buf)
p.dumpLock.Unlock()
}

type packetCapturer struct {
proxy *proxy.Context
session *proxy.Session
file *os.File
wPacket io.Writer
tempBuf *bytes.Buffer
Expand All @@ -47,7 +47,7 @@ type packetCapturer struct {
log *logrus.Entry
}

func (p *packetCapturer) AddressAndName(address, hostname string) (err error) {
func (p *packetCapturer) onServerName(hostname string) (err error) {
p.hostname = hostname
// temporary buffer
p.tempBuf = bytes.NewBuffer(nil)
Expand All @@ -62,7 +62,7 @@ func (p *packetCapturer) OnServerConnect() (disconnect bool, err error) {
return false, err
}

packs := p.proxy.Server.ResourcePacks()
packs := p.session.Server.ResourcePacks()

p.file.WriteString("BTCP")
binary.Write(p.file, binary.LittleEndian, uint32(5))
Expand Down Expand Up @@ -113,11 +113,11 @@ func (p *packetCapturer) OnServerConnect() (disconnect bool, err error) {
return false, nil
}

func (p *packetCapturer) PacketFunc(header packet.Header, payload []byte, src, dst net.Addr) {
func (p *packetCapturer) PacketFunc(header packet.Header, payload []byte, src, dst net.Addr, timeReceived time.Time) {
buf := bytes.NewBuffer(nil)
header.Write(buf)
buf.Write(payload)
p.dumpPacket(p.proxy.IsClient(src), buf.Bytes())
p.dumpPacket(p.session.IsClient(src), buf.Bytes(), timeReceived)
}

func NewPacketCapturer() *proxy.Handler {
Expand All @@ -126,12 +126,12 @@ func NewPacketCapturer() *proxy.Handler {
}
return &proxy.Handler{
Name: "Packet Capturer",
ProxyReference: func(pc *proxy.Context) {
p.proxy = pc
SessionStart: func(s *proxy.Session, serverName string) error {
p.session = s
return p.onServerName(serverName)
},
OnAddressAndName: p.AddressAndName,
OnServerConnect: p.OnServerConnect,
PacketRaw: p.PacketFunc,
OnServerConnect: p.OnServerConnect,
PacketRaw: p.PacketFunc,
OnSessionEnd: func() {
p.dumpLock.Lock()
defer p.dumpLock.Unlock()
Expand Down
6 changes: 3 additions & 3 deletions handlers/chat_log.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,16 +36,16 @@ func NewChatLogger() *proxy.Handler {
return &proxy.Handler{
Name: "Packet Capturer",
PacketCallback: c.PacketCB,
OnAddressAndName: func(address, hostname string) error {
filename := fmt.Sprintf("%s_%s_chat.log", hostname, time.Now().Format("2006-01-02_15-04-05_Z07"))
SessionStart: func(s *proxy.Session, serverName string) error {
filename := fmt.Sprintf("%s_%s_chat.log", serverName, time.Now().Format("2006-01-02_15-04-05_Z07"))
f, err := os.Create(filename)
if err != nil {
return err
}
c.fio = f
return nil
},
OnProxyEnd: func() {
OnSessionEnd: func() {
c.fio.Close()
},
}
Expand Down
30 changes: 14 additions & 16 deletions handlers/skins.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ import (
)

type SkinSaver struct {
proxy *proxy.Context
log *logrus.Entry
session *proxy.Session
log *logrus.Entry

PlayerNameFilter string
OnlyIfHasGeometry bool
Expand Down Expand Up @@ -88,7 +88,7 @@ func (s *SkinSaver) AddSkin(player *skinPlayer, playerSkin *protocol.Skin) (*uti
}
if player.SkinPack.AddSkin(skin) {
addedStr := fmt.Sprintf("Added a skin %s", player.Name)
s.proxy.SendPopup(addedStr)
s.session.SendPopup(addedStr)
s.log.Info(addedStr)
added = true
}
Expand Down Expand Up @@ -155,7 +155,7 @@ func (s *SkinSaver) ProcessPacket(pk packet.Packet) (out []SkinAdd) {
player.AltName = pk.Username
player.RuntimeID = pk.EntityRuntimeID
case *packet.Animate:
if pk.EntityRuntimeID == s.proxy.Player.RuntimeID && pk.ActionType == packet.AnimateActionSwingArm {
if pk.EntityRuntimeID == s.session.Player.RuntimeID && pk.ActionType == packet.AnimateActionSwingArm {
s.stealSkin()
}
case *packet.ChangeDimension:
Expand All @@ -180,10 +180,8 @@ func NewSkinSaver(skinCB func(SkinAdd)) *proxy.Handler {
}
return &proxy.Handler{
Name: "Skin Saver",
ProxyReference: func(pc *proxy.Context) {
s.proxy = pc
},
OnAddressAndName: func(address, hostname string) error {
SessionStart: func(session *proxy.Session, hostname string) error {
s.session = session
outPathBase := fmt.Sprintf("skins/%s", hostname)
os.MkdirAll(outPathBase, 0o755)
s.baseDir = outPathBase
Expand Down Expand Up @@ -212,19 +210,19 @@ func (s *SkinSaver) stealSkin() {

var dist float64 = 40

pitch := mgl64.DegToRad(float64(s.proxy.Player.Pitch))
yaw := mgl64.DegToRad(float64(s.proxy.Player.HeadYaw + 90))
pitch := mgl64.DegToRad(float64(s.session.Player.Pitch))
yaw := mgl64.DegToRad(float64(s.session.Player.HeadYaw + 90))

dir := mgl64.Vec3{
math.Cos(yaw) * math.Cos(pitch),
math.Sin(-pitch),
math.Sin(yaw) * math.Cos(pitch),
}.Normalize()

pos := s.proxy.Player.Position
pos := s.session.Player.Position
traceStart := mgl64.Vec3{float64(pos[0]), float64(pos[1]), float64(pos[2])}
traceEnd := traceStart.Add(dir.Mul(dist))
s.proxy.ClientWritePacket(&packet.SpawnParticleEffect{
s.session.ClientWritePacket(&packet.SpawnParticleEffect{
Dimension: 0,
EntityUniqueID: -1,
Position: mgl32.Vec3{float32(traceEnd[0]), float32(traceEnd[1]), float32(traceEnd[2])},
Expand All @@ -243,21 +241,21 @@ func (s *SkinSaver) stealSkin() {
fmt.Printf("res: %v\n", res.Position())
interceptPos := res.Position()

s.proxy.ClientWritePacket(&packet.SpawnParticleEffect{
s.session.ClientWritePacket(&packet.SpawnParticleEffect{
Dimension: 0,
EntityUniqueID: -1,
Position: mgl32.Vec3{float32(interceptPos[0]), float32(interceptPos[1]), float32(interceptPos[2])},
ParticleName: "hivehub:emote_confounded",
})

id := uuid.MustParse(s.proxy.Client.IdentityData().Identity)
id := uuid.MustParse(s.session.Client.IdentityData().Identity)

s.proxy.ClientWritePacket(&packet.PlayerSkin{
s.session.ClientWritePacket(&packet.PlayerSkin{
UUID: id,
Skin: *sp.CurrentSkin.Skin,
})

s.proxy.Server.WritePacket(&packet.PlayerSkin{
s.session.Server.WritePacket(&packet.PlayerSkin{
UUID: id,
Skin: *sp.CurrentSkin.Skin,
})
Expand Down
4 changes: 2 additions & 2 deletions handlers/worlds/chunk.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func (w *worldsHandler) processLevelChunk(pk *packet.LevelChunk) {
}

dimId, _ := world.DimensionID(w.currentWorld.Dimension())
_ = w.proxy.Server.WritePacket(&packet.SubChunkRequest{
_ = w.session.Server.WritePacket(&packet.SubChunkRequest{
Dimension: int32(dimId),
Position: protocol.SubChunkPos{
pk.Position.X(), 0, pk.Position.Z(),
Expand All @@ -97,7 +97,7 @@ func (w *worldsHandler) processLevelChunk(pk *packet.LevelChunk) {
//}
}

w.proxy.SendPopup(locale.Locm("popup_chunk_count", locale.Strmap{
w.session.SendPopup(locale.Locm("popup_chunk_count", locale.Strmap{
"Chunks": len(w.currentWorld.StoredChunks),
"Entities": w.currentWorld.EntityCount(),
"Name": w.currentWorld.Name,
Expand Down
Loading

0 comments on commit 8ab8490

Please sign in to comment.