forked from mcstatus-io/mcutil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
raw_status.go
92 lines (70 loc) · 1.87 KB
/
raw_status.go
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
package mcutil
import (
"context"
"errors"
"fmt"
"math/rand"
"net"
"time"
"github.com/mcstatus-io/mcutil/v2/options"
)
// StatusRaw returns the raw status data of any 1.7+ Minecraft server
func StatusRaw(ctx context.Context, host string, port uint16, options ...options.JavaStatus) (map[string]interface{}, error) {
r := make(chan map[string]interface{}, 1)
e := make(chan error, 1)
go func() {
result, err := getStatusRaw(host, port, options...)
if err != nil {
e <- err
} else if result != nil {
r <- result
}
}()
select {
case <-ctx.Done():
if v := ctx.Err(); v != nil {
return nil, v
}
return nil, errors.New("context finished before server sent response")
case v := <-r:
return v, nil
case v := <-e:
return nil, v
}
}
func getStatusRaw(host string, port uint16, options ...options.JavaStatus) (map[string]interface{}, error) {
opts := parseJavaStatusOptions(options...)
if opts.EnableSRV && port == 25565 {
record, err := LookupSRV("tcp", host)
if err == nil && record != nil {
host = record.Target
port = record.Port
}
}
conn, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", host, port), opts.Timeout)
if err != nil {
return nil, err
}
defer conn.Close()
if err = conn.SetDeadline(time.Now().Add(opts.Timeout)); err != nil {
return nil, err
}
if err = writeJavaStatusHandshakeRequestPacket(conn, int32(opts.ProtocolVersion), host, port); err != nil {
return nil, err
}
if err = writeJavaStatusStatusRequestPacket(conn); err != nil {
return nil, err
}
result := make(map[string]interface{})
if err = readJavaStatusStatusResponsePacket(conn, &result); err != nil {
return nil, err
}
payload := rand.Int63()
if err = writeJavaStatusPingPacket(conn, payload); err != nil {
return nil, err
}
if err = readJavaStatusPongPacket(conn, payload); err != nil {
return nil, err
}
return result, nil
}