Skip to content

Commit 41f78bd

Browse files
committed
gophertunnel: Clean up error messages and use %w verb instead of %v for embedding errors within errors.
1 parent ef41ef4 commit 41f78bd

19 files changed

+125
-135
lines changed

main.go

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -74,8 +74,9 @@ func handleConn(conn *minecraft.Conn, listener *minecraft.Listener, config confi
7474
return
7575
}
7676
if err := serverConn.WritePacket(pk); err != nil {
77-
if disconnect, ok := errors.Unwrap(err).(minecraft.DisconnectError); ok {
78-
_ = listener.Disconnect(conn, disconnect.Error())
77+
var disc minecraft.DisconnectError
78+
if ok := errors.As(err, &disc); ok {
79+
_ = listener.Disconnect(conn, disc.Error())
7980
}
8081
return
8182
}
@@ -87,8 +88,9 @@ func handleConn(conn *minecraft.Conn, listener *minecraft.Listener, config confi
8788
for {
8889
pk, err := serverConn.ReadPacket()
8990
if err != nil {
90-
if disconnect, ok := errors.Unwrap(err).(minecraft.DisconnectError); ok {
91-
_ = listener.Disconnect(conn, disconnect.Error())
91+
var disc minecraft.DisconnectError
92+
if ok := errors.As(err, &disc); ok {
93+
_ = listener.Disconnect(conn, disc.Error())
9294
}
9395
return
9496
}
@@ -111,30 +113,30 @@ func readConfig() config {
111113
if _, err := os.Stat("config.toml"); os.IsNotExist(err) {
112114
f, err := os.Create("config.toml")
113115
if err != nil {
114-
log.Fatalf("error creating config: %v", err)
116+
log.Fatalf("create config: %v", err)
115117
}
116118
data, err := toml.Marshal(c)
117119
if err != nil {
118-
log.Fatalf("error encoding default config: %v", err)
120+
log.Fatalf("encode default config: %v", err)
119121
}
120122
if _, err := f.Write(data); err != nil {
121-
log.Fatalf("error writing encoded default config: %v", err)
123+
log.Fatalf("write default config: %v", err)
122124
}
123125
_ = f.Close()
124126
}
125127
data, err := os.ReadFile("config.toml")
126128
if err != nil {
127-
log.Fatalf("error reading config: %v", err)
129+
log.Fatalf("read config: %v", err)
128130
}
129131
if err := toml.Unmarshal(data, &c); err != nil {
130-
log.Fatalf("error decoding config: %v", err)
132+
log.Fatalf("decode config: %v", err)
131133
}
132134
if c.Connection.LocalAddress == "" {
133135
c.Connection.LocalAddress = "0.0.0.0:19132"
134136
}
135137
data, _ = toml.Marshal(c)
136138
if err := os.WriteFile("config.toml", data, 0644); err != nil {
137-
log.Fatalf("error writing config file: %v", err)
139+
log.Fatalf("write config: %v", err)
138140
}
139141
return c
140142
}

minecraft/auth/minecraft.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ func RequestMinecraftChain(ctx context.Context, token *XBLToken, key *ecdsa.Priv
3636
c := &http.Client{}
3737
resp, err := c.Do(request)
3838
if err != nil {
39-
return "", fmt.Errorf("POST %v: %v", minecraftAuthURL, err)
39+
return "", fmt.Errorf("POST %v: %w", minecraftAuthURL, err)
4040
}
4141
if resp.StatusCode != 200 {
4242
return "", fmt.Errorf("POST %v: %v", minecraftAuthURL, resp.Status)

minecraft/auth/xbox.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ func obtainXBLToken(ctx context.Context, c *http.Client, key *ecdsa.PrivateKey,
8787

8888
resp, err := c.Do(req)
8989
if err != nil {
90-
return nil, fmt.Errorf("POST %v: %v", "https://sisu.xboxlive.com/authorize", err)
90+
return nil, fmt.Errorf("POST %v: %w", "https://sisu.xboxlive.com/authorize", err)
9191
}
9292
defer func() {
9393
_ = resp.Body.Close()
@@ -132,7 +132,7 @@ func obtainDeviceToken(ctx context.Context, c *http.Client, key *ecdsa.PrivateKe
132132

133133
resp, err := c.Do(request)
134134
if err != nil {
135-
return nil, fmt.Errorf("POST %v: %v", "https://device.auth.xboxlive.com/device/authenticate", err)
135+
return nil, fmt.Errorf("POST %v: %w", "https://device.auth.xboxlive.com/device/authenticate", err)
136136
}
137137
defer func() {
138138
_ = resp.Body.Close()

minecraft/conn.go

Lines changed: 36 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -442,7 +442,7 @@ func (conn *Conn) Flush() error {
442442
if len(conn.bufferedSend) > 0 {
443443
if err := conn.enc.Encode(conn.bufferedSend); err != nil && !errors.Is(err, net.ErrClosed) {
444444
// Should never happen.
445-
panic(fmt.Errorf("error encoding packet batch: %v", err))
445+
panic(fmt.Errorf("error encoding packet batch: %w", err))
446446
}
447447
// First manually clear out conn.bufferedSend so that re-using the slice after resetting its length to
448448
// 0 doesn't result in an 'invisible' memory leak.
@@ -612,7 +612,7 @@ func (conn *Conn) handleMultiple(pks []packet.Packet) error {
612612
var err error
613613
for _, pk := range pks {
614614
if e := conn.handlePacket(pk); e != nil {
615-
err = e
615+
err = fmt.Errorf("handle %T: %w", pk, e)
616616
}
617617
}
618618
return err
@@ -685,15 +685,15 @@ func (conn *Conn) handleRequestNetworkSettings(pk *packet.RequestNetworkSettings
685685
status = packet.PlayStatusLoginFailedServer
686686
}
687687
_ = conn.WritePacket(&packet.PlayStatus{Status: status})
688-
return fmt.Errorf("%v connected with an incompatible protocol: expected protocol = %v, client protocol = %v", conn.identityData.DisplayName, protocol.CurrentProtocol, pk.ClientProtocol)
688+
return fmt.Errorf("incompatible protocol version: expected %v, got %v", protocol.CurrentProtocol, pk.ClientProtocol)
689689
}
690690

691691
conn.expect(packet.IDLogin)
692692
if err := conn.WritePacket(&packet.NetworkSettings{
693693
CompressionThreshold: 512,
694694
CompressionAlgorithm: conn.compression.EncodeCompression(),
695695
}); err != nil {
696-
return fmt.Errorf("error sending network settings: %v", err)
696+
return fmt.Errorf("send NetworkSettings: %w", err)
697697
}
698698
_ = conn.Flush()
699699
conn.enc.EnableCompression(conn.compression)
@@ -705,7 +705,7 @@ func (conn *Conn) handleRequestNetworkSettings(pk *packet.RequestNetworkSettings
705705
func (conn *Conn) handleNetworkSettings(pk *packet.NetworkSettings) error {
706706
alg, ok := packet.CompressionByID(pk.CompressionAlgorithm)
707707
if !ok {
708-
return fmt.Errorf("unknown compression algorithm: %v", pk.CompressionAlgorithm)
708+
return fmt.Errorf("unknown compression algorithm %v", pk.CompressionAlgorithm)
709709
}
710710
conn.enc.EnableCompression(alg)
711711
conn.dec.EnableCompression()
@@ -730,10 +730,10 @@ func (conn *Conn) handleLogin(pk *packet.Login) error {
730730
// Make sure the player is logged in with XBOX Live when necessary.
731731
if !authResult.XBOXLiveAuthenticated && conn.authEnabled {
732732
_ = conn.WritePacket(&packet.Disconnect{Message: text.Colourf("<red>You must be logged in with XBOX Live to join.</red>")})
733-
return fmt.Errorf("connection %v was not authenticated to XBOX Live", conn.RemoteAddr())
733+
return fmt.Errorf("client was not authenticated to XBOX Live")
734734
}
735735
if err := conn.enableEncryption(authResult.PublicKey); err != nil {
736-
return fmt.Errorf("error enabling encryption: %v", err)
736+
return fmt.Errorf("enable encryption: %w", err)
737737
}
738738
return nil
739739
}
@@ -743,7 +743,7 @@ func (conn *Conn) handleClientToServerHandshake() error {
743743
// The next expected packet is a resource pack client response.
744744
conn.expect(packet.IDResourcePackClientResponse, packet.IDClientCacheStatus)
745745
if err := conn.WritePacket(&packet.PlayStatus{Status: packet.PlayStatusLoginSuccess}); err != nil {
746-
return fmt.Errorf("error sending play status login success: %v", err)
746+
return fmt.Errorf("send PlayStatus (Status=LoginSuccess): %w", err)
747747
}
748748
pk := &packet.ResourcePacksInfo{TexturePackRequired: conn.texturePacksRequired}
749749
for _, pack := range conn.resourcePacks {
@@ -775,7 +775,7 @@ func (conn *Conn) handleClientToServerHandshake() error {
775775
}
776776
// Finally we send the packet after the play status.
777777
if err := conn.WritePacket(pk); err != nil {
778-
return fmt.Errorf("error sending resource packs info: %v", err)
778+
return fmt.Errorf("send ResourcePacksInfo: %w", err)
779779
}
780780
return nil
781781
}
@@ -809,7 +809,7 @@ func (conn *Conn) handleServerToClientHandshake(pk *packet.ServerToClientHandsha
809809
c.Salt = strings.TrimRight(c.Salt, "=")
810810
salt, err := base64.RawStdEncoding.DecodeString(c.Salt)
811811
if err != nil {
812-
return fmt.Errorf("error base64 decoding ServerToClientHandshake salt: %v", err)
812+
return fmt.Errorf("decode ServerToClientHandshake salt: %w", err)
813813
}
814814

815815
x, _ := pub.Curve.ScalarMult(pub.X, pub.Y, conn.privateKey.D.Bytes())
@@ -849,7 +849,7 @@ func (conn *Conn) handleResourcePacksInfo(pk *packet.ResourcePacksInfo) error {
849849

850850
for index, pack := range pk.TexturePacks {
851851
if _, ok := conn.packQueue.downloadingPacks[pack.UUID]; ok {
852-
conn.log.Printf("duplicate texture pack entry %v in resource pack info\n", pack.UUID)
852+
conn.log.Printf("handle ResourcePacksInfo: duplicate texture pack (UUID=%v)\n", pack.UUID)
853853
conn.packQueue.packAmount--
854854
continue
855855
}
@@ -872,7 +872,7 @@ func (conn *Conn) handleResourcePacksInfo(pk *packet.ResourcePacksInfo) error {
872872
}
873873
for index, pack := range pk.BehaviourPacks {
874874
if _, ok := conn.packQueue.downloadingPacks[pack.UUID]; ok {
875-
conn.log.Printf("duplicate behaviour pack entry %v in resource pack info\n", pack.UUID)
875+
conn.log.Printf("handle ResourcePacksInfo: duplicate behaviour pack (UUID=%v)\n", pack.UUID)
876876
conn.packQueue.packAmount--
877877
continue
878878
}
@@ -918,17 +918,17 @@ func (conn *Conn) handleResourcePackStack(pk *packet.ResourcePackStack) error {
918918
if pack.UUID == behaviourPack.UUID {
919919
// We had a behaviour pack with the same UUID as the texture pack, so we drop the texture
920920
// pack and log it.
921-
conn.log.Printf("dropping behaviour pack with UUID %v due to a texture pack with the same UUID\n", pack.UUID)
921+
conn.log.Printf("handle ResourcePackStack: dropping behaviour pack (UUID=%v) due to a texture pack with the same UUID\n", pack.UUID)
922922
pk.BehaviourPacks = append(pk.BehaviourPacks[:i], pk.BehaviourPacks[i+1:]...)
923923
}
924924
}
925925
if !conn.hasPack(pack.UUID, pack.Version, false) {
926-
return fmt.Errorf("texture pack {uuid=%v, version=%v} not downloaded", pack.UUID, pack.Version)
926+
return fmt.Errorf("texture pack (UUID=%v, version=%v) not downloaded", pack.UUID, pack.Version)
927927
}
928928
}
929929
for _, pack := range pk.BehaviourPacks {
930930
if !conn.hasPack(pack.UUID, pack.Version, true) {
931-
return fmt.Errorf("behaviour pack {uuid=%v, version=%v} not downloaded", pack.UUID, pack.Version)
931+
return fmt.Errorf("behaviour pack (UUID=%v, version=%v) not downloaded", pack.UUID, pack.Version)
932932
}
933933
}
934934
conn.expect(packet.IDStartGame)
@@ -977,7 +977,7 @@ func (conn *Conn) handleResourcePackClientResponse(pk *packet.ResourcePackClient
977977
packs := pk.PacksToDownload
978978
conn.packQueue = &resourcePackQueue{packs: conn.resourcePacks}
979979
if err := conn.packQueue.Request(packs); err != nil {
980-
return fmt.Errorf("error looking up resource packs to download: %v", err)
980+
return fmt.Errorf("lookup resource packs by UUID: %w", err)
981981
}
982982
// Proceed with the first resource pack download. We run all downloads in sequence rather than in
983983
// parallel, as it's less prone to packet loss.
@@ -1003,12 +1003,12 @@ func (conn *Conn) handleResourcePackClientResponse(pk *packet.ResourcePackClient
10031003
})
10041004
}
10051005
if err := conn.WritePacket(pk); err != nil {
1006-
return fmt.Errorf("error writing resource pack stack packet: %v", err)
1006+
return fmt.Errorf("send ResourcePackStack: %w", err)
10071007
}
10081008
case packet.PackResponseCompleted:
10091009
conn.loggedIn = true
10101010
default:
1011-
return fmt.Errorf("unknown resource pack client response: %v", pk.Response)
1011+
return fmt.Errorf("unknown ResourcePackClientResponse response type %v", pk.Response)
10121012
}
10131013
return nil
10141014
}
@@ -1069,7 +1069,7 @@ func (conn *Conn) nextResourcePackDownload() error {
10691069
return fmt.Errorf("no resource packs to download")
10701070
}
10711071
if err := conn.WritePacket(pk); err != nil {
1072-
return fmt.Errorf("error sending resource pack data info packet: %v", err)
1072+
return fmt.Errorf("send ResourcePackDataInfo: %w", err)
10731073
}
10741074
// Set the next expected packet to ResourcePackChunkRequest packets.
10751075
conn.expect(packet.IDResourcePackChunkRequest)
@@ -1085,12 +1085,12 @@ func (conn *Conn) handleResourcePackDataInfo(pk *packet.ResourcePackDataInfo) er
10851085
if !ok {
10861086
// We either already downloaded the pack or we got sent an invalid UUID, that did not match any pack
10871087
// sent in the ResourcePacksInfo packet.
1088-
return fmt.Errorf("unknown pack to download with UUID %v", id)
1088+
return fmt.Errorf("unknown pack (UUID=%v)", id)
10891089
}
10901090
if pack.size != pk.Size {
10911091
// Size mismatch: The ResourcePacksInfo packet had a size for the pack that did not match with the
10921092
// size sent here.
1093-
conn.log.Printf("pack %v had a different size in the ResourcePacksInfo packet than the ResourcePackDataInfo packet\n", id)
1093+
conn.log.Printf("pack (UUID=%v) had a different size in ResourcePacksInfo than in ResourcePackDataInfo\n", id)
10941094
pack.size = pk.Size
10951095
}
10961096

@@ -1126,13 +1126,13 @@ func (conn *Conn) handleResourcePackDataInfo(pk *packet.ResourcePackDataInfo) er
11261126
defer conn.packMu.Unlock()
11271127

11281128
if pack.buf.Len() != int(pack.size) {
1129-
conn.log.Printf("incorrect resource pack size: expected %v, but got %v\n", pack.size, pack.buf.Len())
1129+
conn.log.Printf("incorrect resource pack size (UUID=%v): expected %v, got %v\n", id, pack.size, pack.buf.Len())
11301130
return
11311131
}
11321132
// First parse the resource pack from the total byte buffer we obtained.
11331133
newPack, err := resource.Read(pack.buf)
11341134
if err != nil {
1135-
conn.log.Printf("invalid full resource pack data for UUID %v: %v\n", id, err)
1135+
conn.log.Printf("invalid full resource pack data (UUID=%v): %v\n", id, err)
11361136
return
11371137
}
11381138
conn.packQueue.packAmount--
@@ -1154,16 +1154,16 @@ func (conn *Conn) handleResourcePackChunkData(pk *packet.ResourcePackChunkData)
11541154
if !ok {
11551155
// We haven't received a ResourcePackDataInfo packet from the server, so we can't use this data to
11561156
// download a resource pack.
1157-
return fmt.Errorf("resource pack chunk data for resource pack that was not being downloaded")
1157+
return fmt.Errorf("chunk data for resource pack that was not being downloaded")
11581158
}
11591159
lastData := pack.buf.Len()+int(pack.chunkSize) >= int(pack.size)
11601160
if !lastData && uint32(len(pk.Data)) != pack.chunkSize {
11611161
// The chunk data didn't have the full size and wasn't the last data to be sent for the resource pack,
11621162
// meaning we got too little data.
1163-
return fmt.Errorf("resource pack chunk data had a length of %v, but expected %v", len(pk.Data), pack.chunkSize)
1163+
return fmt.Errorf("expected chunk size %v, got %v", pack.chunkSize, len(pk.Data))
11641164
}
11651165
if pk.ChunkIndex != pack.expectedIndex {
1166-
return fmt.Errorf("resource pack chunk data had chunk index %v, but expected %v", pk.ChunkIndex, pack.expectedIndex)
1166+
return fmt.Errorf("expected chunk index %v, got %v", pack.expectedIndex, pk.ChunkIndex)
11671167
}
11681168
pack.expectedIndex++
11691169
pack.newFrag <- pk.Data
@@ -1175,10 +1175,10 @@ func (conn *Conn) handleResourcePackChunkData(pk *packet.ResourcePackChunkData)
11751175
func (conn *Conn) handleResourcePackChunkRequest(pk *packet.ResourcePackChunkRequest) error {
11761176
current := conn.packQueue.currentPack
11771177
if current.UUID() != pk.UUID {
1178-
return fmt.Errorf("resource pack chunk request had unexpected UUID: expected %v, but got %v", current.UUID(), pk.UUID)
1178+
return fmt.Errorf("expected pack UUID %v, but got %v", current.UUID(), pk.UUID)
11791179
}
11801180
if conn.packQueue.currentOffset != uint64(pk.ChunkIndex)*packChunkSize {
1181-
return fmt.Errorf("resource pack chunk request had unexpected chunk index: expected %v, but got %v", conn.packQueue.currentOffset/packChunkSize, pk.ChunkIndex)
1181+
return fmt.Errorf("expected pack UUID %v, but got %v", conn.packQueue.currentOffset/packChunkSize, pk.ChunkIndex)
11821182
}
11831183
response := &packet.ResourcePackChunkData{
11841184
UUID: pk.UUID,
@@ -1192,7 +1192,7 @@ func (conn *Conn) handleResourcePackChunkRequest(pk *packet.ResourcePackChunkReq
11921192
// If we hit an EOF, we don't need to return an error, as we've simply reached the end of the content
11931193
// AKA the last chunk.
11941194
if err != io.EOF {
1195-
return fmt.Errorf("error reading resource pack chunk: %v", err)
1195+
return fmt.Errorf("read resource pack chunk: %w", err)
11961196
}
11971197
response.Data = response.Data[:n]
11981198

@@ -1205,7 +1205,7 @@ func (conn *Conn) handleResourcePackChunkRequest(pk *packet.ResourcePackChunkReq
12051205
}()
12061206
}
12071207
if err := conn.WritePacket(response); err != nil {
1208-
return fmt.Errorf("error writing resource pack chunk data packet: %v", err)
1208+
return fmt.Errorf("send ResourcePackChunkData: %w", err)
12091209
}
12101210

12111211
return nil
@@ -1263,7 +1263,7 @@ func (conn *Conn) handleStartGame(pk *packet.StartGame) error {
12631263
// of the connection, and spawns the player.
12641264
func (conn *Conn) handleRequestChunkRadius(pk *packet.RequestChunkRadius) error {
12651265
if pk.ChunkRadius < 1 {
1266-
return fmt.Errorf("requested chunk radius must be at least 1, got %v", pk.ChunkRadius)
1266+
return fmt.Errorf("expected chunk radius of at least 1, got %v", pk.ChunkRadius)
12671267
}
12681268
conn.expect(packet.IDSetLocalPlayerAsInitialised)
12691269
radius := pk.ChunkRadius
@@ -1295,7 +1295,7 @@ func (conn *Conn) handleRequestChunkRadius(pk *packet.RequestChunkRadius) error
12951295
// radius of the connection.
12961296
func (conn *Conn) handleChunkRadiusUpdated(pk *packet.ChunkRadiusUpdated) error {
12971297
if pk.ChunkRadius < 1 {
1298-
return fmt.Errorf("new chunk radius must be at least 1, got %v", pk.ChunkRadius)
1298+
return fmt.Errorf("expected chunk radius of at least 1, got %v", pk.ChunkRadius)
12991299
}
13001300
conn.expect(packet.IDPlayStatus)
13011301

@@ -1311,7 +1311,7 @@ func (conn *Conn) handleChunkRadiusUpdated(pk *packet.ChunkRadiusUpdated) error
13111311
// logged in.
13121312
func (conn *Conn) handleSetLocalPlayerAsInitialised(pk *packet.SetLocalPlayerAsInitialised) error {
13131313
if pk.EntityRuntimeID != conn.gameData.EntityRuntimeID {
1314-
return fmt.Errorf("entity runtime ID mismatch: entity runtime ID in StartGame and SetLocalPlayerAsInitialised packets should be equal")
1314+
return fmt.Errorf("entity runtime ID mismatch: expected %v (from StartGame), got %v", conn.gameData.EntityRuntimeID, pk.EntityRuntimeID)
13151315
}
13161316
if conn.waitingForSpawn.CompareAndSwap(true, false) {
13171317
close(conn.spawn)
@@ -1325,7 +1325,7 @@ func (conn *Conn) handlePlayStatus(pk *packet.PlayStatus) error {
13251325
switch pk.Status {
13261326
case packet.PlayStatusLoginSuccess:
13271327
if err := conn.WritePacket(&packet.ClientCacheStatus{Enabled: conn.cacheEnabled}); err != nil {
1328-
return fmt.Errorf("error sending client cache status: %v", err)
1328+
return fmt.Errorf("send ClientCacheStatus: %w", err)
13291329
}
13301330
// The next packet we expect is the ResourcePacksInfo packet.
13311331
conn.expect(packet.IDResourcePacksInfo)
@@ -1360,7 +1360,7 @@ func (conn *Conn) handlePlayStatus(pk *packet.PlayStatus) error {
13601360
_ = conn.Close()
13611361
return fmt.Errorf("cannot join an editor game on vanilla")
13621362
default:
1363-
return fmt.Errorf("unknown play status in PlayStatus packet %v", pk.Status)
1363+
return fmt.Errorf("unknown play status %v", pk.Status)
13641364
}
13651365
}
13661366

@@ -1391,7 +1391,7 @@ func (conn *Conn) enableEncryption(clientPublicKey *ecdsa.PublicKey) error {
13911391
return fmt.Errorf("compact serialise server JWT: %w", err)
13921392
}
13931393
if err := conn.WritePacket(&packet.ServerToClientHandshake{JWT: []byte(serverJWT)}); err != nil {
1394-
return fmt.Errorf("error sending ServerToClientHandshake packet: %v", err)
1394+
return fmt.Errorf("send ServerToClientHandshake: %w", err)
13951395
}
13961396
// Flush immediately as we'll enable encryption after this.
13971397
_ = conn.Flush()

0 commit comments

Comments
 (0)