-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapp.go
More file actions
555 lines (506 loc) · 15.1 KB
/
Copy pathapp.go
File metadata and controls
555 lines (506 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
package main
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net"
"os"
"os/exec"
"runtime"
"sync"
"time"
"github.com/df-mc/atomic"
"github.com/df-mc/dragonfly/server/world"
"github.com/google/uuid"
"github.com/pkg/browser"
"github.com/sandertv/gophertunnel/minecraft"
"github.com/sandertv/gophertunnel/minecraft/auth"
"github.com/sandertv/gophertunnel/minecraft/nbt"
"github.com/sandertv/gophertunnel/minecraft/protocol"
"github.com/sandertv/gophertunnel/minecraft/protocol/packet"
"github.com/sandertv/gophertunnel/minecraft/resource"
"github.com/tedacmc/tedac/tedac"
"github.com/tedacmc/tedac/tedac/chunk"
"github.com/tedacmc/tedac/tedac/latestmappings"
"github.com/tedacmc/tedac/tedac/legacyprotocol/legacypacket"
"golang.org/x/oauth2"
)
// App ...
type App struct {
listener *minecraft.Listener
remoteAddress string
localPort uint16
src oauth2.TokenSource
pendingDeviceCode string
ctx context.Context
c chan interface{}
}
// NewApp creates a new App application struct.
func NewApp() *App {
return &App{c: make(chan interface{})}
}
// ProxyInfo ...
type ProxyInfo struct {
RemoteAddress string `json:"remote_address"`
LocalAddress string `json:"local_address"`
}
// ProxyingInfo returns info about the current Tedac connection. If no connection is active, an error is returned.
func (a *App) ProxyingInfo() (ProxyInfo, error) {
if a.listener == nil {
return ProxyInfo{}, errors.New("no connection active")
}
return ProxyInfo{
RemoteAddress: a.remoteAddress,
LocalAddress: fmt.Sprintf("127.0.0.1:%d", a.localPort),
}, nil
}
// Terminate terminates any existing Tedac connection.
func (a *App) Terminate() {
if a.listener == nil {
return
}
a.c <- struct{}{}
_ = a.listener.Close()
}
// Connect starts Tedac and connects to a remote server. If localPort is 0, a random available port is used.
func (a *App) Connect(address string, localPort uint16) error {
if a.src == nil {
// Try loading a cached token.
token := new(oauth2.Token)
tokenData, err := os.ReadFile("token.tok")
if err == nil {
_ = json.Unmarshal(tokenData, token)
src := auth.RefreshTokenSource(token)
if _, err = src.Token(); err == nil {
tok, _ := src.Token()
b, _ := json.Marshal(tok)
_ = os.WriteFile("token.tok", b, 0644)
a.src = src
}
}
if a.src == nil {
return errors.New("authentication required")
}
}
port := int(localPort)
if port == 0 {
temp, err := net.ResolveUDPAddr("udp", ":0")
if err != nil {
return err
}
l, err := net.ListenUDP("udp", temp)
if err != nil {
return err
}
port = l.LocalAddr().(*net.UDPAddr).Port
if err = l.Close(); err != nil {
return err
}
}
p, err := minecraft.NewForeignStatusProvider(address)
if err != nil {
return err
}
err = os.Mkdir("packcache", 0644)
useCache := err == nil || os.IsExist(err)
var cachedPackNames []string
conn, err := minecraft.Dialer{
TokenSource: a.src,
DownloadResourcePack: func(id uuid.UUID, version string, _, _ int) bool {
if useCache {
name := fmt.Sprintf("%s_%s", id, version)
_, err = os.Stat(fmt.Sprintf("packcache/%s.mcpack", name))
if err == nil {
cachedPackNames = append(cachedPackNames, name)
return false
}
}
return true
},
}.DialTimeout("raknet", address, time.Minute*2)
if err != nil {
return err
}
packs := conn.ResourcePacks()
_ = conn.Close()
var cachedPacks []*resource.Pack
if useCache {
for _, name := range cachedPackNames {
pack, err := resource.ReadPath(fmt.Sprintf("packcache/%s.mcpack", name))
if err != nil {
continue
}
cachedPacks = append(cachedPacks, pack)
}
for _, pack := range packs {
packData := make([]byte, pack.Len())
_, err = pack.ReadAt(packData, 0)
if err != nil {
continue
}
name := fmt.Sprintf("%s_%s", pack.UUID(), pack.Version())
_ = os.WriteFile(fmt.Sprintf("packcache/%s.mcpack", name), packData, 0644)
}
}
a.remoteAddress = address
a.localPort = uint16(port)
a.listener, err = minecraft.ListenConfig{
AllowInvalidPackets: true,
AllowUnknownPackets: true,
StatusProvider: p,
ResourcePacks: append(packs, cachedPacks...),
AcceptedProtocols: []minecraft.Protocol{tedac.Protocol{}},
}.Listen("raknet", fmt.Sprintf(":%d", port))
if err != nil {
return err
}
go func() {
for {
c, err := a.listener.Accept()
if err != nil {
break
}
go a.handleConn(c.(*minecraft.Conn))
}
}()
return nil
}
// CheckNetIsolation checks if a loopback exempt is in place to allow the hosting device to join the server. This is
// only relevant on Windows.
func (a *App) CheckNetIsolation() bool {
if runtime.GOOS != "windows" {
// Only an issue on Windows.
return true
}
data, _ := exec.Command("CheckNetIsolation", "LoopbackExempt", "-s", `-n="microsoft.minecraftuwp_8wekyb3d8bbwe"`).CombinedOutput()
return bytes.Contains(data, []byte("microsoft.minecraftuwp_8wekyb3d8bbwe"))
}
// startup is called when the app starts. The context is saved, so we can call the runtime methods.
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
}
var (
// airRID is the runtime ID of the air block in the latest version of the game.
airRID, _ = latestmappings.StateToRuntimeID("minecraft:air", nil)
// defaultSkinResourcePatch holds the skin resource patch assigned to a player when they wear a custom skin.
defaultSkinResourcePatch = base64.StdEncoding.EncodeToString([]byte(`
{
"geometry" : {
"default" : "geometry.humanoid.custom"
}
}
`))
)
// handleConn handles a new incoming minecraft.Conn from the minecraft.Listener passed.
func (a *App) handleConn(conn *minecraft.Conn) {
clientData := conn.ClientData()
if _, ok := conn.Protocol().(tedac.Protocol); ok { // TODO: Adjust this inside Protocol itself.
clientData.GameVersion = protocol.CurrentVersion
clientData.SkinResourcePatch = defaultSkinResourcePatch
clientData.DeviceModel = "TEDAC CLIENT"
data, _ := base64.StdEncoding.DecodeString(clientData.SkinData)
switch len(data) {
case 32 * 64 * 4:
clientData.SkinImageHeight = 32
clientData.SkinImageWidth = 64
case 64 * 64 * 4:
clientData.SkinImageHeight = 64
clientData.SkinImageWidth = 64
case 128 * 128 * 4:
clientData.SkinImageHeight = 128
clientData.SkinImageWidth = 128
}
}
serverConn, err := minecraft.Dialer{
TokenSource: a.src,
ClientData: clientData,
}.DialTimeout("raknet", a.remoteAddress, time.Minute*2)
if err != nil {
panic(err)
}
data := serverConn.GameData()
var g sync.WaitGroup
g.Add(2)
go func() {
if err := conn.StartGame(data); err != nil {
panic(err)
}
g.Done()
}()
go func() {
if err := serverConn.DoSpawn(); err != nil {
panic(err)
}
g.Done()
}()
g.Wait()
// TODO: Component-ize the shit below.
rid := data.EntityRuntimeID
r := world.Overworld.Range()
pos := atomic.NewValue(data.PlayerPosition)
lastPos := atomic.NewValue(data.PlayerPosition)
yaw, pitch := atomic.NewValue(data.Yaw), atomic.NewValue(data.Pitch)
startedSneaking, stoppedSneaking := atomic.NewValue(false), atomic.NewValue(false)
startedSprinting, stoppedSprinting := atomic.NewValue(false), atomic.NewValue(false)
startedGliding, stoppedGliding := atomic.NewValue(false), atomic.NewValue(false)
startedSwimming, stoppedSwimming := atomic.NewValue(false), atomic.NewValue(false)
startedJumping := atomic.NewValue(false)
biomeBufferCache := make(map[protocol.ChunkPos][]byte)
go func() {
t := time.NewTicker(time.Second / 20)
defer t.Stop()
var tick uint64
for range t.C {
currentPos, originalPos := pos.Load(), lastPos.Load()
lastPos.Store(currentPos)
currentYaw, currentPitch := yaw.Load(), pitch.Load()
inputs := protocol.NewBitset(packet.PlayerAuthInputBitsetSize)
if startedSneaking.CompareAndSwap(true, false) {
inputs.Set(packet.InputFlagStartSneaking)
}
if stoppedSneaking.CompareAndSwap(true, false) {
inputs.Set(packet.InputFlagStopSneaking)
}
if startedSprinting.CompareAndSwap(true, false) {
inputs.Set(packet.InputFlagStartSprinting)
}
if stoppedSprinting.CompareAndSwap(true, false) {
inputs.Set(packet.InputFlagStopSprinting)
}
if startedGliding.CompareAndSwap(true, false) {
inputs.Set(packet.InputFlagStartGliding)
}
if stoppedGliding.CompareAndSwap(true, false) {
inputs.Set(packet.InputFlagStopGliding)
}
if startedSwimming.CompareAndSwap(true, false) {
inputs.Set(packet.InputFlagStartSwimming)
}
if stoppedSwimming.CompareAndSwap(true, false) {
inputs.Set(packet.InputFlagStopSwimming)
}
if startedJumping.CompareAndSwap(true, false) {
inputs.Set(packet.InputFlagJumping)
}
if err = serverConn.WritePacket(&packet.PlayerAuthInput{
Delta: currentPos.Sub(originalPos),
HeadYaw: currentYaw,
InputData: inputs,
InputMode: packet.InputModeMouse,
InteractionModel: packet.InteractionModelCrosshair,
Pitch: currentPitch,
PlayMode: packet.PlayModeNormal,
Position: currentPos,
Tick: tick,
Yaw: currentYaw,
}); err != nil {
return
}
_ = serverConn.Flush()
tick++
}
}()
go func() {
defer a.listener.Disconnect(conn, "connection lost")
defer serverConn.Close()
for {
pk, err := conn.ReadPacket()
if err != nil {
return
}
switch pk := pk.(type) {
case *packet.MovePlayer:
pos.Store(pk.Position)
yaw.Store(pk.Yaw)
pitch.Store(pk.Pitch)
continue
case *packet.PlayerAction:
switch pk.ActionType {
case legacypacket.PlayerActionJump:
startedJumping.Store(true)
continue
case legacypacket.PlayerActionStartSprint:
startedSprinting.Store(true)
continue
case legacypacket.PlayerActionStopSprint:
stoppedSprinting.Store(true)
continue
case legacypacket.PlayerActionStartSneak:
startedSneaking.Store(true)
continue
case legacypacket.PlayerActionStopSneak:
stoppedSneaking.Store(true)
continue
case legacypacket.PlayerActionStartSwimming:
startedSwimming.Store(true)
continue
case legacypacket.PlayerActionStopSwimming:
stoppedSwimming.Store(true)
continue
case legacypacket.PlayerActionStartGlide:
startedGliding.Store(true)
continue
case legacypacket.PlayerActionStopGlide:
stoppedGliding.Store(true)
continue
}
}
if err := serverConn.WritePacket(pk); err != nil {
var disconnect minecraft.DisconnectError
if errors.As(errors.Unwrap(err), &disconnect) {
_ = a.listener.Disconnect(conn, disconnect.Error())
}
return
}
_ = serverConn.Flush()
}
}()
go func() {
defer serverConn.Close()
defer a.listener.Disconnect(conn, "connection lost")
for {
pk, err := serverConn.ReadPacket()
if err != nil {
var disconnect minecraft.DisconnectError
if errors.As(errors.Unwrap(err), &disconnect) {
_ = a.listener.Disconnect(conn, disconnect.Error())
}
return
}
switch pk := pk.(type) {
case *packet.MovePlayer:
if pk.EntityRuntimeID == rid {
pos.Store(pk.Position)
yaw.Store(pk.Yaw)
pitch.Store(pk.Pitch)
}
case *packet.MoveActorAbsolute:
if pk.EntityRuntimeID == rid {
pos.Store(pk.Position)
yaw.Store(pk.Rotation[2])
pitch.Store(pk.Rotation[0])
}
case *packet.MoveActorDelta:
if pk.EntityRuntimeID == rid {
pos.Store(pk.Position)
yaw.Store(pk.Rotation[2])
pitch.Store(pk.Rotation[0])
}
case *packet.SubChunk:
if _, ok := conn.Protocol().(tedac.Protocol); !ok {
// Only Tedac clients should receive the old format.
break
}
chunkBuf := bytes.NewBuffer(nil)
blockEntities := make([]map[string]any, 0)
for _, entry := range pk.SubChunkEntries {
if entry.Result != protocol.SubChunkResultSuccess {
chunkBuf.Write([]byte{
chunk.SubChunkVersion,
0, // The client will treat this as all air.
uint8(entry.Offset[1]),
})
continue
}
var ind uint8
readBuf := bytes.NewBuffer(entry.RawPayload)
sub, err := chunk.DecodeSubChunk(airRID, r, readBuf, &ind, chunk.NetworkEncoding)
if err != nil {
fmt.Println(err)
continue
}
var blockEntity map[string]any
dec := nbt.NewDecoderWithEncoding(readBuf, nbt.NetworkLittleEndian)
for {
if err := dec.Decode(&blockEntity); err != nil {
break
}
blockEntities = append(blockEntities, blockEntity)
}
chunkBuf.Write(chunk.EncodeSubChunk(sub, chunk.NetworkEncoding, r, int(ind)))
}
chunkPos := protocol.ChunkPos{pk.Position.X(), pk.Position.Z()}
_, _ = chunkBuf.Write(append(biomeBufferCache[chunkPos], 0))
delete(biomeBufferCache, chunkPos)
enc := nbt.NewEncoderWithEncoding(chunkBuf, nbt.NetworkLittleEndian)
for _, b := range blockEntities {
_ = enc.Encode(b)
}
_ = conn.WritePacket(&packet.LevelChunk{
Position: chunkPos,
SubChunkCount: uint32(len(pk.SubChunkEntries)),
RawPayload: append([]byte(nil), chunkBuf.Bytes()...),
})
_ = conn.Flush()
continue
case *packet.LevelChunk:
if pk.SubChunkCount != protocol.SubChunkRequestModeLimitless && pk.SubChunkCount != protocol.SubChunkRequestModeLimited {
// No changes to be made here.
break
}
if _, ok := conn.Protocol().(tedac.Protocol); !ok {
// Only Tedac clients should receive the old format.
break
}
max := r.Height() >> 4
if pk.SubChunkCount == protocol.SubChunkRequestModeLimited {
max = int(pk.HighestSubChunk)
}
offsets := make([]protocol.SubChunkOffset, 0, max)
for i := 0; i < max; i++ {
offsets = append(offsets, protocol.SubChunkOffset{0, int8(i + (r[0] >> 4)), 0})
}
biomeBufferCache[pk.Position] = pk.RawPayload[:len(pk.RawPayload)-1]
_ = serverConn.WritePacket(&packet.SubChunkRequest{
Position: protocol.SubChunkPos{pk.Position.X(), 0, pk.Position.Z()},
Offsets: offsets,
})
_ = serverConn.Flush()
continue
case *packet.Transfer:
a.remoteAddress = fmt.Sprintf("%s:%d", pk.Address, pk.Port)
pk.Address = "127.0.0.1"
pk.Port = a.localPort
}
if err := conn.WritePacket(pk); err != nil {
return
}
_ = conn.Flush()
}
}()
}
// StartAuth begins the Microsoft device code authentication flow. It returns the URL the user should
// visit to complete authentication.
func (a *App) StartAuth() (string, error) {
resp, err := auth.StartDeviceAuth()
if err != nil {
return "", err
}
a.pendingDeviceCode = resp.DeviceCode
url := "https://login.live.com/oauth20_remoteconnect.srf?lc=1033&otc=" + resp.UserCode
_ = browser.OpenURL(url)
return url, nil
}
// FinishAuth polls for the completion of the device code authentication flow and saves the token.
func (a *App) FinishAuth() error {
if a.pendingDeviceCode == "" {
return errors.New("no authentication in progress")
}
t, err := auth.PollDeviceAuth(a.pendingDeviceCode)
a.pendingDeviceCode = ""
if err != nil {
return err
}
if t == nil {
return errors.New("authentication timed out or was cancelled")
}
src := auth.RefreshTokenSource(t)
tok, _ := src.Token()
b, _ := json.Marshal(tok)
_ = os.WriteFile("token.tok", b, 0644)
a.src = src
return nil
}