Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a6102b7ec9 | ||
|
|
254b75e76b | ||
|
|
33cec6ecc9 | ||
|
|
fbf9bacd05 | ||
|
|
29baf8da9f | ||
|
|
43fea40d08 | ||
|
|
b107eba37c | ||
|
|
abc0f6aebb | ||
|
|
8c6172dcda | ||
|
|
57e78478cd | ||
|
|
f554e91354 | ||
|
|
e0cf1834f1 | ||
|
|
047c4d02ff | ||
|
|
c516cc5283 | ||
|
|
165075ea02 | ||
|
|
2eee7bde24 | ||
|
|
73d4e07b06 | ||
|
|
5dfd8fc499 | ||
|
|
1b36949316 | ||
|
|
5c455bd2c8 | ||
|
|
8d1a4b581b | ||
|
|
085b83cb71 | ||
|
|
65bf63d67e | ||
|
|
d8cc9cab48 | ||
|
|
f7d7a72b7c | ||
|
|
29b1b92113 | ||
|
|
bd83b9689e | ||
|
|
85529b965b |
@@ -1,3 +1,4 @@
|
||||
.devres/
|
||||
.idea/
|
||||
.failed_packets/
|
||||
tools/.*/
|
||||
@@ -1,202 +1,61 @@
|
||||
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below.
|
||||
0. Additional Definitions.
|
||||
|
||||
1. Definitions.
|
||||
As used herein, “this License” refers to version 3 of the GNU Lesser General Public License, and the “GNU GPL” refers to version 3 of the GNU General Public License.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
“The Library” refers to a covered work governed by this License, other than an Application or a Combined Work as defined below.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
An “Application” is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
A “Combined Work” is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the “Linked Version”.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
The “Minimal Corresponding Source” for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
The “Corresponding Application Code” for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work.
|
||||
1. Exception to Section 3 of the GNU GPL.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL.
|
||||
2. Conveying Modified Versions.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version:
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or
|
||||
b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
3. Object Code Incorporating Material from Library Header Files.
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following:
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License.
|
||||
b) Accompany the object code with a copy of the GNU GPL and this license document.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
4. Combined Works.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License.
|
||||
b) Accompany the Combined Work with a copy of the GNU GPL and this license document.
|
||||
c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document.
|
||||
d) Do one of the following:
|
||||
0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.
|
||||
1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version.
|
||||
e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.)
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
5. Combined Libraries.
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following:
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License.
|
||||
b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
6. Revised Versions of the GNU Lesser General Public License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.
|
||||
+17
-3
@@ -7,14 +7,28 @@ import (
|
||||
"github.com/admin-else/strom/proto_base"
|
||||
)
|
||||
|
||||
// Connect connects to the given address note that it does not resolve the SRV records it's just a raw net.Dial
|
||||
// You must close the connection when you're done with it
|
||||
func Connect(addr string) (ret *proto.Conn, err error) {
|
||||
ret = &proto.Conn{}
|
||||
err = ret.SetVersion("1.21.8")
|
||||
s, err := Status(addr)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ret, err = ConnectVersionLess(addr)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = ret.SetProtocolVersion(s.Version.Protocol)
|
||||
return
|
||||
}
|
||||
|
||||
// ConnectVersionLess connects to the given address without setting the version you should set it
|
||||
// when using this function.
|
||||
// You must close the connection when you're done with it
|
||||
func ConnectVersionLess(addr string) (ret *proto.Conn, err error) {
|
||||
ret = &proto.Conn{}
|
||||
ret.SetState(proto_base.Handshaking)
|
||||
ret.CompressionThreshold = -1
|
||||
ret.SetCompressionThreshold(-1)
|
||||
ret.Actor = proto_base.Client
|
||||
ret.Conn, err = net.Dial("tcp", addr)
|
||||
if err != nil {
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
package modules
|
||||
package client
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
"github.com/admin-else/strom/event"
|
||||
"github.com/admin-else/strom/proto"
|
||||
@@ -14,8 +15,12 @@ type ConfigIgnorer struct {
|
||||
*proto.Conn
|
||||
}
|
||||
|
||||
func (c *ConfigIgnorer) Default(event any) (err error) {
|
||||
fmt.Printf("%#v\n", event)
|
||||
func (c *ConfigIgnorer) OnStart() (err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func (c *ConfigIgnorer) Default(event event.Anything) (err error) {
|
||||
slog.Debug("Config ignorer", "packet", fmt.Sprintf("%#v", event))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -23,7 +28,7 @@ func (c *ConfigIgnorer) OnKnownPacks(packet *v1_21_8.ConfigurationToClientPacket
|
||||
return c.Send(&v1_21_8.ConfigurationToServerPacketCommonSelectKnownPacks{Packs: packet.Packs})
|
||||
}
|
||||
|
||||
func (c *ConfigIgnorer) OnFinish(_ v1_21_8.ConfigurationToClientPacketFinishConfiguration) (err error) {
|
||||
func (c *ConfigIgnorer) OnFinish(_ *v1_21_8.ConfigurationToClientPacketFinishConfiguration) (err error) {
|
||||
err = c.Send(&v1_21_8.ConfigurationToServerPacketFinishConfiguration{})
|
||||
if err != nil {
|
||||
return
|
||||
@@ -44,7 +49,14 @@ func (c *ConfigIgnorer) OnKeepAlive(packet *v1_21_8.ConfigurationToClientPacketK
|
||||
}
|
||||
|
||||
func IgnoreConfig(c *proto.Conn) (err error) {
|
||||
err = c.Start(&ConfigIgnorer{c})
|
||||
ci := &ConfigIgnorer{c}
|
||||
ci.RegisterCritical(ci.Default)
|
||||
ci.RegisterUntilLatest(ci.OnKnownPacks)
|
||||
ci.RegisterUntilLatest(ci.OnFinish)
|
||||
ci.RegisterUntilLatest(ci.OnPing)
|
||||
ci.RegisterUntilLatest(ci.OnKeepAlive)
|
||||
|
||||
err = ci.Start()
|
||||
if err != nil {
|
||||
err = errors.Join(err, errors.New("failed to ignore config"))
|
||||
}
|
||||
+113
-9
@@ -1,22 +1,126 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func LookupMinecraftSRV(host string, port uint16) (hostRet string, portRet uint16) {
|
||||
hostRet = host // in case of error
|
||||
portRet = port
|
||||
if port != 25565 {
|
||||
type DNSCheckFunc func(addr string) error
|
||||
|
||||
// DoDns resolves a DNS name to an IP address
|
||||
// It should resolve a minecraft compatible address into something net.Dial
|
||||
func DoDns(in string) (out string, host string, portN uint16, err error) {
|
||||
return DoDNSChecked(in, nil)
|
||||
}
|
||||
|
||||
// DoDNSChecked resolves a DNS name to an IP address
|
||||
// It should resolve a minecraft compatible address into something net.Dial
|
||||
// It also optionally accepts a function to "check" the address
|
||||
func DoDNSChecked(in string, f DNSCheckFunc) (connectTo string, host string, portN uint16, err error) {
|
||||
// https://mcsrc.dev/1/26.1-pre-1/net/minecraft/client/multiplayer/resolver/ServerAddress#L34
|
||||
host, port, err := net.SplitHostPort(in)
|
||||
if err != nil {
|
||||
var addrErr *net.AddrError
|
||||
if errors.As(err, &addrErr) && addrErr.Err == "missing port in address" {
|
||||
err = nil
|
||||
host = in
|
||||
port = "25565"
|
||||
} else {
|
||||
return
|
||||
}
|
||||
}
|
||||
porti, err := strconv.Atoi(port)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_, srvs, err := net.LookupSRV("minecraft", "tcp", host)
|
||||
if err != nil || len(srvs) == 0 {
|
||||
if f == nil {
|
||||
f = func(addr string) error { return nil }
|
||||
}
|
||||
|
||||
err = f(host)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
target := strings.TrimSuffix(srvs[0].Target, ".")
|
||||
hostRet = target
|
||||
portRet = srvs[0].Port
|
||||
portN = uint16(porti)
|
||||
outIP, err := net.ResolveIPAddr("ip", host)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = f(outIP.String())
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
connectTo = outIP.String() + ":" + port
|
||||
if portN != 25565 {
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second) // otherwise this takes 10+ seconds
|
||||
defer cancel()
|
||||
|
||||
r := &net.Resolver{}
|
||||
|
||||
_, srvs, _ := r.LookupSRV(ctx, "minecraft", "tcp", host)
|
||||
if len(srvs) == 0 {
|
||||
|
||||
return
|
||||
}
|
||||
host = strings.TrimSuffix(srvs[0].Target, ".")
|
||||
portN = srvs[0].Port
|
||||
outIP, err = net.ResolveIPAddr("ip", host)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = f(outIP.String())
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
connectTo = outIP.String() + ":" + port
|
||||
return
|
||||
}
|
||||
|
||||
// DoDnsSimple resolves a DNS name to an IP address
|
||||
// It should resolve a minecraft compatible address into something net.Dial
|
||||
// It does not check the address
|
||||
func DoDnsSimple(in string) (out string, err error) {
|
||||
host, port, err := net.SplitHostPort(in)
|
||||
if err != nil {
|
||||
var addrErr *net.AddrError
|
||||
if errors.As(err, &addrErr) && addrErr.Err == "missing port in address" {
|
||||
err = nil
|
||||
host = in
|
||||
port = "25565"
|
||||
} else {
|
||||
return
|
||||
}
|
||||
}
|
||||
porti, err := strconv.Atoi(port)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
portN := uint16(porti)
|
||||
_, err = net.ResolveIPAddr("ip", host)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
out = in
|
||||
if portN != 25565 {
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second) // otherwise this takes 10+ seconds
|
||||
defer cancel()
|
||||
|
||||
r := &net.Resolver{}
|
||||
|
||||
_, srvs, _ := r.LookupSRV(ctx, "minecraft", "tcp", host)
|
||||
if len(srvs) == 0 {
|
||||
return
|
||||
}
|
||||
host = strings.TrimSuffix(srvs[0].Target, ".")
|
||||
portN = srvs[0].Port
|
||||
out = host + ":" + strconv.Itoa(int(portN))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package client
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestDoDNS(t *testing.T) {
|
||||
type Case struct {
|
||||
Input string
|
||||
Host string
|
||||
portN uint16
|
||||
}
|
||||
cases := []Case{
|
||||
{"localhost", "localhost", 25565},
|
||||
{"play.hypixel.net", "play.hypixel.net", 25565},
|
||||
{"1f2d.net", "tcpshield.1f2d.net", 25565},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Logf("Testing %s", c.Input)
|
||||
_, host, portN, err := DoDns(c.Input)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
continue
|
||||
}
|
||||
if host != c.Host || portN != c.portN {
|
||||
t.Errorf("expected %s:%d, got %s:%d", c.Host, c.portN, host, portN)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"net"
|
||||
"strconv"
|
||||
|
||||
"github.com/admin-else/strom/proto"
|
||||
"github.com/admin-else/strom/proto_base"
|
||||
"github.com/admin-else/strom/proto_generated/v1_21_8"
|
||||
)
|
||||
|
||||
func MakeHandshakePacket(c *proto.Conn, nextState proto_base.State) (p *v1_21_8.HandshakingToServerPacketSetProtocol, err error) {
|
||||
return MakeHandshakePacketAddr(c, nextState, c.RemoteAddr().String())
|
||||
}
|
||||
|
||||
func MakeHandshakePacketAddr(s *proto.Conn, nextState proto_base.State, addr string) (p *v1_21_8.HandshakingToServerPacketSetProtocol, err error) {
|
||||
p = &v1_21_8.HandshakingToServerPacketSetProtocol{NextState: int32(nextState), ProtocolVersion: s.ProtocolVersion}
|
||||
var portStr string
|
||||
p.ServerHost, portStr, err = net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var portUint uint64
|
||||
portUint, err = strconv.ParseUint(portStr, 10, 16)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
p.ServerPort = uint16(portUint)
|
||||
return
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package modules
|
||||
package client
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
@@ -7,11 +7,8 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"strconv"
|
||||
|
||||
"github.com/admin-else/strom/api"
|
||||
"github.com/admin-else/strom/client"
|
||||
"github.com/admin-else/strom/crypto"
|
||||
"github.com/admin-else/strom/event"
|
||||
"github.com/admin-else/strom/proto"
|
||||
@@ -30,6 +27,12 @@ type LoginClient struct {
|
||||
GivenAccount *v1_21_8.LoginToClientPacketSuccess
|
||||
}
|
||||
|
||||
var (
|
||||
NoTokenErr = errors.New("the account has no token so we cant join online servers")
|
||||
BadPublicKeyTypeErr = errors.New("the public key is not rsa")
|
||||
FailedToLoginErr = errors.New("failed to login")
|
||||
)
|
||||
|
||||
type KickedDuringLoginErr struct {
|
||||
text.Component
|
||||
}
|
||||
@@ -38,7 +41,7 @@ func (k KickedDuringLoginErr) Error() string {
|
||||
return k.String()
|
||||
}
|
||||
|
||||
func (s *LoginClient) Default(event event.Unhandled) (err error) {
|
||||
func (s *LoginClient) OnDefault(event event.Unhandled) (err error) {
|
||||
err = fmt.Errorf("unexpected event: %#v", event)
|
||||
return
|
||||
}
|
||||
@@ -47,37 +50,12 @@ func (s *LoginClient) OnCycle(_ event.Tick) (err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func (s *LoginClient) OnStart(_ event.OnStart) (err error) {
|
||||
if s.ServerHost == "" && s.ServerPort == 0 {
|
||||
var portStr string
|
||||
s.ServerHost, portStr, err = net.SplitHostPort(s.RemoteAddr().String())
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var portUint uint64
|
||||
portUint, err = strconv.ParseUint(portStr, 10, 16)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
s.ServerPort = uint16(portUint)
|
||||
}
|
||||
|
||||
err = s.Send(&v1_21_8.HandshakingToServerPacketSetProtocol{
|
||||
ProtocolVersion: s.ProtocolVersion,
|
||||
ServerHost: s.ServerHost,
|
||||
ServerPort: s.ServerPort,
|
||||
NextState: int32(proto_base.Login),
|
||||
})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
s.SetState(proto_base.Login)
|
||||
err = s.Send(&v1_21_8.LoginToServerPacketLoginStart{Username: s.Account.Name, PlayerUUID: s.Account.Uuid})
|
||||
func (s *LoginClient) OnClose(_ event.Close) (err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func (s *LoginClient) OnCompress(compress *v1_21_8.LoginToClientPacketCompress) (err error) {
|
||||
s.CompressionThreshold = compress.Threshold
|
||||
s.SetCompressionThreshold(compress.Threshold)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -87,7 +65,7 @@ func (s *LoginClient) OnEncrypt(packet *v1_21_8.LoginToClientPacketEncryptionBeg
|
||||
|
||||
if packet.ShouldAuthenticate {
|
||||
if s.Account.Ygg == "" {
|
||||
err = fmt.Errorf("the account has no token so we cant join online servers")
|
||||
err = NoTokenErr
|
||||
return
|
||||
}
|
||||
serverId := crypto.AuthDigest([]byte(packet.ServerId), sharedSecret, packet.PublicKey)
|
||||
@@ -103,7 +81,7 @@ func (s *LoginClient) OnEncrypt(packet *v1_21_8.LoginToClientPacketEncryptionBeg
|
||||
}
|
||||
pub, ok := pubAny.(*rsa.PublicKey)
|
||||
if !ok {
|
||||
err = fmt.Errorf("public key is not rsa")
|
||||
err = BadPublicKeyTypeErr
|
||||
return
|
||||
}
|
||||
verifyTokenEnc, err := rsa.EncryptPKCS1v15(rand.Reader, pub, packet.VerifyToken)
|
||||
@@ -145,28 +123,50 @@ func (s *LoginClient) OnSuccess(success *v1_21_8.LoginToClientPacketSuccess) (er
|
||||
return
|
||||
}
|
||||
|
||||
func (s *LoginClient) OnStart() (err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func Login(c *proto.Conn, account *api.Account) (err error) {
|
||||
err = c.Start(&LoginClient{
|
||||
lc := &LoginClient{
|
||||
Conn: c,
|
||||
Account: account,
|
||||
})
|
||||
}
|
||||
lc.RegisterCritical(lc.OnDefault)
|
||||
lc.RegisterCritical(lc.OnCycle)
|
||||
lc.RegisterCritical(lc.OnClose)
|
||||
lc.RegisterUntilLatest(lc.OnCompress)
|
||||
lc.RegisterUntilLatest(lc.OnEncrypt)
|
||||
lc.RegisterUntilLatest(lc.OnDisconnect)
|
||||
lc.RegisterUntilLatest(lc.OnSuccess)
|
||||
|
||||
p, err := MakeHandshakePacket(lc.Conn, proto_base.Login)
|
||||
if err != nil {
|
||||
err = errors.Join(err, errors.New("failed to login"))
|
||||
return
|
||||
}
|
||||
|
||||
err = lc.Send(p)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
lc.SetState(proto_base.Login)
|
||||
err = lc.Send(&v1_21_8.LoginToServerPacketLoginStart{Username: lc.Account.Name, PlayerUUID: lc.Account.Uuid})
|
||||
|
||||
err = lc.Start()
|
||||
if err != nil {
|
||||
err = errors.Join(FailedToLoginErr, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func ConnectAndLogin(connectTo string, account *api.Account) (c *proto.Conn, err error) {
|
||||
c, err = client.Connect(connectTo)
|
||||
c, err = Connect(connectTo)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = c.Start(&LoginClient{
|
||||
Conn: c,
|
||||
Account: account,
|
||||
})
|
||||
err = Login(c, account)
|
||||
if err != nil {
|
||||
err = errors.Join(errors.New("failed to login"), err)
|
||||
err = errors.Join(FailedToLoginErr, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
package modules
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/admin-else/strom/event"
|
||||
"github.com/admin-else/strom/proto"
|
||||
"github.com/admin-else/strom/proto_base"
|
||||
|
||||
"github.com/admin-else/strom/data"
|
||||
"github.com/admin-else/strom/proto_generated/v1_21_8"
|
||||
)
|
||||
|
||||
type StatusClient struct {
|
||||
*proto.Conn
|
||||
Status string
|
||||
}
|
||||
|
||||
func (s *StatusClient) Default(event any) (err error) {
|
||||
err = fmt.Errorf("unexpected event: %v", event)
|
||||
return
|
||||
}
|
||||
|
||||
func (s *StatusClient) OnStart(_ event.OnStart) (err error) {
|
||||
parts := strings.Split(s.RemoteAddr().String(), ":")
|
||||
versionData, err := data.LookUpProtocolVersionByName(s.Version)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
port, err := strconv.Atoi(parts[1])
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = s.Send(&v1_21_8.HandshakingToServerPacketSetProtocol{
|
||||
ProtocolVersion: int32(versionData.Version),
|
||||
ServerHost: parts[0],
|
||||
ServerPort: uint16(port),
|
||||
NextState: int32(proto_base.Status),
|
||||
})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
s.SetState(proto_base.Status)
|
||||
err = s.Send(&v1_21_8.StatusToServerPacketPingStart{})
|
||||
return
|
||||
}
|
||||
|
||||
func (s *StatusClient) OnStatus(p v1_21_8.StatusToClientPacketServerInfo) (err error) {
|
||||
s.Status = p.Response
|
||||
err = event.HandlerDoneErr{}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/admin-else/strom/event"
|
||||
"github.com/admin-else/strom/proto"
|
||||
"github.com/admin-else/strom/proto_base"
|
||||
"github.com/admin-else/strom/server"
|
||||
|
||||
"github.com/admin-else/strom/proto_generated/v1_21_8"
|
||||
)
|
||||
|
||||
type StatusClient struct {
|
||||
*proto.Conn
|
||||
Status string
|
||||
PingSendTime, PingReceiveTime time.Time
|
||||
DoPingRoundTripTime bool
|
||||
}
|
||||
|
||||
func (s *StatusClient) OnStart() (err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func (s *StatusClient) OnStatus(p *v1_21_8.StatusToClientPacketServerInfo) (err error) {
|
||||
s.Status = p.Response
|
||||
s.PingSendTime = time.Now()
|
||||
if s.DoPingRoundTripTime {
|
||||
err = s.Send(&v1_21_8.StatusToServerPacketPing{Time: s.PingSendTime.UnixMilli()})
|
||||
} else {
|
||||
err = event.HandlerDoneErr{}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *StatusClient) OnPong(p *v1_21_8.StatusToClientPacketPing) (err error) {
|
||||
s.PingReceiveTime = time.Now()
|
||||
err = event.HandlerDoneErr{}
|
||||
return
|
||||
}
|
||||
|
||||
// StatusRaw returns a StatusClient that is not connected to a server.
|
||||
// So ignore the resource leak warning. And maybe attach a warn ignore comment
|
||||
func StatusRaw(addr string) (s *StatusClient, err error) {
|
||||
c, err := ConnectVersionLess(addr)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer c.Close()
|
||||
err = c.SetVersion("1.21.8")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
s = &StatusClient{
|
||||
Conn: c,
|
||||
}
|
||||
s.Loop = event.NewLoop()
|
||||
s.RegisterUntilLatest(s.OnStatus)
|
||||
s.RegisterUntilLatest(s.OnPong)
|
||||
|
||||
p, err := MakeHandshakePacketAddr(s.Conn, proto_base.Status, addr)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = s.Send(p)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
s.SetState(proto_base.Status)
|
||||
err = s.Send(&v1_21_8.StatusToServerPacketPingStart{})
|
||||
|
||||
err = s.StartConn()
|
||||
return
|
||||
}
|
||||
|
||||
func Status(addr string) (status server.StatusResponse, err error) {
|
||||
s, err := StatusRaw(addr)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = json.Unmarshal([]byte(s.Status), &status)
|
||||
return
|
||||
}
|
||||
+132
-12
@@ -1,6 +1,10 @@
|
||||
package data
|
||||
|
||||
// {
|
||||
import (
|
||||
"errors"
|
||||
)
|
||||
|
||||
// {
|
||||
// "id": 0,
|
||||
// "name": "air",
|
||||
// "displayName": "Air",
|
||||
@@ -35,29 +39,43 @@ type Block struct {
|
||||
DefaultState int32
|
||||
MinStateId int32
|
||||
MaxStateId int32
|
||||
States []struct {
|
||||
Name string
|
||||
Type string
|
||||
NumValues int
|
||||
}
|
||||
Drops []int
|
||||
BoundingBox string
|
||||
States []BlockState
|
||||
Drops []int
|
||||
BoundingBox string
|
||||
}
|
||||
|
||||
var BlocksCache = make(map[string][]Block)
|
||||
type BlockState struct {
|
||||
Name string
|
||||
Type string
|
||||
NumValues int32 `json:"num_values"`
|
||||
Values []string
|
||||
}
|
||||
|
||||
func BlocksForVersion(v string) (ret []Block) {
|
||||
var BlocksCache = make(map[string][]*Block)
|
||||
|
||||
func BlocksForVersion(v string) (ret []*Block) {
|
||||
var ok bool
|
||||
if ret, ok = BlocksCache[v]; ok {
|
||||
return
|
||||
}
|
||||
var b []Block
|
||||
var b []*Block
|
||||
must(LoadVersionedJson(v, "blocks", &b))
|
||||
BlocksCache[v] = b
|
||||
return b
|
||||
}
|
||||
|
||||
func LookupBlockByStateId(version string, stateId int32) (block Block, ok bool) {
|
||||
func LookupBlockByStateId(version string, stateId int32) (block *Block, ok bool) {
|
||||
for _, b := range BlocksForVersion(version) {
|
||||
if b.MinStateId <= stateId && stateId <= b.MaxStateId {
|
||||
block = b
|
||||
ok = true
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func LookupBlockByName(version string, stateId int32) (block *Block, ok bool) {
|
||||
for _, b := range BlocksForVersion(version) {
|
||||
if b.MinStateId <= stateId && stateId <= b.MaxStateId {
|
||||
block = b
|
||||
@@ -66,3 +84,105 @@ func LookupBlockByStateId(version string, stateId int32) (block Block, ok bool)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
var BlockStateOutOfRangeErr = errors.New("stateId out of range")
|
||||
var BlockNotFoundErr = errors.New("block not found")
|
||||
var InvalidBoolValueErr = errors.New("invalid bool value")
|
||||
var BadBlockStateTypeErr = errors.New("bad block state type")
|
||||
var BadEnumErr = errors.New("bad enum")
|
||||
var SupplyAllStatesErr = errors.New("supply all states")
|
||||
|
||||
func FromBlockState(version string, stateId int32) (b *Block, stateData map[string]any, err error) {
|
||||
b, ok := LookupBlockByStateId(version, stateId)
|
||||
if !ok {
|
||||
err = BlockNotFoundErr
|
||||
}
|
||||
stateData, err = b.StateMapFromId(stateId)
|
||||
return
|
||||
}
|
||||
|
||||
// TODO: mc stores these as strings so we will do the same
|
||||
|
||||
func mcDataBlockStateTypeParse(n int32, s *BlockState) (v any, err error) {
|
||||
switch s.Type {
|
||||
case "int":
|
||||
v = n
|
||||
case "enum":
|
||||
v = s.Values[n]
|
||||
case "bool":
|
||||
if n == 0 { // MOJANK: 0 is true, 1 is false
|
||||
v = true
|
||||
} else if n == 1 {
|
||||
v = false
|
||||
} else {
|
||||
err = InvalidBoolValueErr
|
||||
}
|
||||
default:
|
||||
err = BadBlockStateTypeErr
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func mcDataBlockStateTypeSerialize(v any, s *BlockState) (n int32, err error) {
|
||||
switch t := v.(type) {
|
||||
case int32:
|
||||
n = t
|
||||
case bool:
|
||||
if t {
|
||||
n = 0
|
||||
} else {
|
||||
n = 1
|
||||
}
|
||||
case string:
|
||||
for i, enumValue := range s.Values {
|
||||
if enumValue == t {
|
||||
return int32(i), nil
|
||||
}
|
||||
}
|
||||
err = BadEnumErr
|
||||
default:
|
||||
err = BadBlockStateTypeErr
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (b *Block) StateMapFromId(stateId int32) (ret map[string]any, err error) {
|
||||
if stateId < b.MinStateId || stateId > b.MaxStateId {
|
||||
err = BlockStateOutOfRangeErr
|
||||
return
|
||||
}
|
||||
ret = make(map[string]any)
|
||||
stateId -= b.MinStateId
|
||||
|
||||
a := int32(1)
|
||||
for i := range len(b.States) {
|
||||
s := b.States[len(b.States)-1-i]
|
||||
ret[s.Name], err = mcDataBlockStateTypeParse((stateId/a)%s.NumValues, &s)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
a *= s.NumValues
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (b *Block) IdFromStateMap(m map[string]any) (ret int32, err error) {
|
||||
a := int32(1)
|
||||
for i := range len(b.States) {
|
||||
s := b.States[len(b.States)-1-i]
|
||||
v, found := m[s.Name]
|
||||
if !found {
|
||||
err = SupplyAllStatesErr
|
||||
return
|
||||
}
|
||||
var n int32
|
||||
n, err = mcDataBlockStateTypeSerialize(v, &s)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ret += n * a
|
||||
a *= s.NumValues
|
||||
}
|
||||
ret += b.MinStateId
|
||||
return
|
||||
}
|
||||
|
||||
@@ -14,3 +14,21 @@ func TestLookupBlockByStateId(t *testing.T) {
|
||||
}
|
||||
fmt.Println(b)
|
||||
}
|
||||
|
||||
func TestBlockStates(t *testing.T) {
|
||||
var stateId int32 = 8301
|
||||
b, stateMap, err := data.FromBlockState("1.21.8", stateId)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
return
|
||||
}
|
||||
t.Logf("Block state map: %v, block: %v", stateMap, b.Name)
|
||||
stateId2, err := b.IdFromStateMap(stateMap)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
return
|
||||
}
|
||||
if stateId2 != stateId {
|
||||
t.Fatal("state id mismatch")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package data
|
||||
|
||||
// {
|
||||
// "id": 2,
|
||||
// "name": "granite",
|
||||
// "displayName": "Granite",
|
||||
// "stackSize": 64
|
||||
// },
|
||||
|
||||
type Item struct {
|
||||
Id int32
|
||||
Name string
|
||||
DisplayName string
|
||||
StackSize int32
|
||||
}
|
||||
|
||||
var ItemsCache = make(map[string][]*Item)
|
||||
|
||||
func ItemsForVersion(v string) (ret []*Item) {
|
||||
var ok bool
|
||||
if ret, ok = ItemsCache[v]; ok {
|
||||
return
|
||||
}
|
||||
var b []*Item
|
||||
must(LoadVersionedJson(v, "items", &b))
|
||||
ItemsCache[v] = b
|
||||
return b
|
||||
}
|
||||
|
||||
func LookupItemById(version string, id int32) (item *Item, ok bool) {
|
||||
for _, i := range ItemsForVersion(version) {
|
||||
if i.Id == id {
|
||||
item = i
|
||||
ok = true
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func LookupItemByName(version string, name string) (item *Item, ok bool) {
|
||||
for _, i := range ItemsForVersion(version) {
|
||||
if i.Name == name {
|
||||
item = i
|
||||
ok = true
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
+1
-1
Submodule data/minecraft-data updated: 9443ed0dec...3e12d39f67
@@ -9,18 +9,18 @@ package data
|
||||
// "releaseType": "snapshot"
|
||||
// },
|
||||
|
||||
type ProtocolVersion struct {
|
||||
type VersionInfo struct {
|
||||
MinecraftVersion string
|
||||
Version int
|
||||
Version int32
|
||||
DataVersion int
|
||||
UsesNetty bool
|
||||
MajorVersion string
|
||||
ReleaseType string
|
||||
}
|
||||
|
||||
var ProtocolVersions []ProtocolVersion
|
||||
var ProtocolVersions []VersionInfo
|
||||
|
||||
func LookUpProtocolVersionByName(name string) (ret ProtocolVersion, err error) {
|
||||
func LookUpVersionByName(name string) (ret VersionInfo, err error) {
|
||||
for _, v := range ProtocolVersions {
|
||||
if v.MinecraftVersion == name {
|
||||
ret = v
|
||||
@@ -31,7 +31,7 @@ func LookUpProtocolVersionByName(name string) (ret ProtocolVersion, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func LookUpProtocolVersionByVersion(version int) (ret ProtocolVersion, err error) {
|
||||
func LookUpVersionByProtocolVersion(version int32) (ret VersionInfo, err error) {
|
||||
for _, v := range ProtocolVersions {
|
||||
if v.Version == version {
|
||||
ret = v
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
)
|
||||
|
||||
func TestLookUpProtocolVersion(t *testing.T) {
|
||||
version, err := data.LookUpProtocolVersionByVersion(772)
|
||||
version, err := data.LookUpVersionByProtocolVersion(772)
|
||||
if err != nil {
|
||||
t.Fatalf("Expected to find version 772, got error: %v", err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package data
|
||||
|
||||
import (
|
||||
"embed"
|
||||
|
||||
"github.com/admin-else/strom/nbt"
|
||||
)
|
||||
|
||||
//go:embed registry/*
|
||||
var Registry embed.FS
|
||||
|
||||
func LoadRegistry(name string) (n *nbt.Tag, err error) {
|
||||
r, err := Registry.Open("registry/" + name + ".nbt")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer r.Close()
|
||||
n, err = nbt.ReadFile(r)
|
||||
return
|
||||
}
|
||||
Binary file not shown.
+89
-30
@@ -2,16 +2,25 @@
|
||||
package event
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"reflect"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
LoopsPerSecond = 100 // i dunno seems reasonable
|
||||
TimePerLoop = time.Second / LoopsPerSecond
|
||||
)
|
||||
|
||||
type Loop struct {
|
||||
HandlerFunctions map[reflect.Type][]reflect.Value
|
||||
Handlers []any
|
||||
HandlerIndex int
|
||||
|
||||
Ctx context.Context
|
||||
ErrChan chan error
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
type Unhandled struct {
|
||||
@@ -23,8 +32,7 @@ type Anything struct {
|
||||
}
|
||||
|
||||
type (
|
||||
OnStart struct{}
|
||||
Tick struct{}
|
||||
Tick struct{}
|
||||
)
|
||||
|
||||
// HandlerDoneErr will stop the event loop and return the error if provided.
|
||||
@@ -32,6 +40,11 @@ type HandlerDoneErr struct {
|
||||
Return error
|
||||
}
|
||||
|
||||
// Close is fired when the loop shuts down.
|
||||
type Close struct {
|
||||
Reason error
|
||||
}
|
||||
|
||||
func (e HandlerDoneErr) Error() string {
|
||||
return "HandlerDoneErr"
|
||||
}
|
||||
@@ -42,28 +55,53 @@ func (e HandlerDoneErr) Unwrap() error {
|
||||
|
||||
// ErrDontForward will stop the event from being forwarded to other handlers, including anything handlers.
|
||||
var ErrDontForward = errors.New("dont forward")
|
||||
var WhileClosingErr = errors.New("error while closing")
|
||||
|
||||
// FindHandlers initializes and populates the HandlerFunctions map by reflecting over methods of registered handlers.
|
||||
func (l *Loop) FindHandlers() {
|
||||
l.HandlerFunctions = make(map[reflect.Type][]reflect.Value)
|
||||
for _, inst := range l.Handlers {
|
||||
t := reflect.TypeOf(inst)
|
||||
v := reflect.ValueOf(inst)
|
||||
for i := 0; i < t.NumMethod(); i++ {
|
||||
method := t.Method(i)
|
||||
if strings.HasPrefix(method.Name, "On") {
|
||||
if method.Type.NumIn() != 2 || method.Type.NumOut() != 1 || method.Type.Out(0) != reflect.TypeFor[error]() {
|
||||
fmt.Println("Invalid event handler signature:", t.String(), ".", method.Name)
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
continue
|
||||
}
|
||||
eventType := method.Type.In(1)
|
||||
l.HandlerFunctions[eventType] = append(l.HandlerFunctions[eventType], v.Method(i))
|
||||
//fmt.Println("Registered Handler:", t.String(), ".", method.Name, "(", eventType.String(), ")")
|
||||
}
|
||||
func ValidateHandler(h any) (eventType reflect.Type, hv reflect.Value) {
|
||||
hv = reflect.ValueOf(h)
|
||||
if hv.Kind() != reflect.Func {
|
||||
panic("expected method")
|
||||
}
|
||||
if hv.Type().NumIn() != 1 {
|
||||
panic("expected method with one argument")
|
||||
}
|
||||
if hv.Type().NumOut() != 1 || hv.Type().Out(0) != reflect.TypeFor[error]() {
|
||||
panic("expected method that returns an error")
|
||||
}
|
||||
eventType = hv.Type().In(0)
|
||||
return
|
||||
}
|
||||
|
||||
// Register registers a handler that will not close the loop if it returns an error.
|
||||
// Instead, it will log it to slog.Error
|
||||
// Warning: If a bad handler is passed in the program will panic.
|
||||
func (l *Loop) Register(h any) {
|
||||
l.RegisterCustomType(ValidateHandler(h))
|
||||
}
|
||||
|
||||
// RegisterCustomType registers a handler that will not close the loop if it returns an error.
|
||||
// Instead, it will log it to slog.Error
|
||||
// Warning: If a bad handler is passed in the program will panic.
|
||||
func (l *Loop) RegisterCustomType(eventType reflect.Type, hv reflect.Value) {
|
||||
handleFunc := func(packet any) error {
|
||||
v := hv.Call([]reflect.Value{reflect.ValueOf(packet)})[0]
|
||||
if !v.IsNil() {
|
||||
slog.Error("handler failed", "err", v.Interface().(error))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
l.RegisterDirect(eventType, reflect.ValueOf(handleFunc))
|
||||
}
|
||||
|
||||
// RegisterCritical registers a handler that will close the loop if it returns an error.
|
||||
// Warning: If a bad handler is passed in the program will panic.
|
||||
func (l *Loop) RegisterCritical(h any) {
|
||||
eventType, hv := ValidateHandler(h)
|
||||
l.RegisterDirect(eventType, hv)
|
||||
}
|
||||
|
||||
func (l *Loop) RegisterDirect(k reflect.Type, h reflect.Value) {
|
||||
l.HandlerFunctions[k] = append(l.HandlerFunctions[k], h)
|
||||
}
|
||||
|
||||
// FireFound triggers all handlers registered for the specified event type and returns if handlers were found or an error occurred.
|
||||
@@ -101,18 +139,39 @@ func (l *Loop) Fire(event any) (err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func (l *Loop) Start() (err error) {
|
||||
_ = *l // exit early on nil connection
|
||||
l.FindHandlers()
|
||||
err = l.Fire(OnStart{})
|
||||
for err == nil {
|
||||
func (l *Loop) startLoop() (err error) {
|
||||
_ = *l // exit early on nil loop
|
||||
for {
|
||||
tickStartTime := time.Now()
|
||||
err = l.Fire(Tick{})
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
time.Sleep(TimePerLoop - time.Since(tickStartTime))
|
||||
}
|
||||
if errors.Is(err, HandlerDoneErr{}) {
|
||||
err = errors.Unwrap(err)
|
||||
}
|
||||
closeErr := l.Fire(Close{err})
|
||||
if closeErr != nil {
|
||||
err = errors.Join(err, errors.Join(WhileClosingErr, closeErr))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (l *Loop) Start() (err error) {
|
||||
go func() {
|
||||
l.ErrChan <- l.startLoop()
|
||||
}()
|
||||
err = <-l.ErrChan
|
||||
l.cancel()
|
||||
return
|
||||
}
|
||||
|
||||
func NewLoop() (l *Loop) {
|
||||
l = &Loop{}
|
||||
l.ErrChan = make(chan error)
|
||||
l.Ctx, l.cancel = context.WithCancel(context.Background())
|
||||
l.HandlerFunctions = make(map[reflect.Type][]reflect.Value)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package event
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"os"
|
||||
)
|
||||
|
||||
type Stdin struct {
|
||||
Val string
|
||||
}
|
||||
|
||||
type StdinHandler struct {
|
||||
*Loop
|
||||
stdInChan chan Stdin
|
||||
Ctx context.Context
|
||||
}
|
||||
|
||||
func (s *StdinHandler) OnTick(_ Tick) (err error) {
|
||||
select {
|
||||
case stdin := <-s.stdInChan:
|
||||
err = s.Fire(Stdin{stdin.Val})
|
||||
default:
|
||||
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *StdinHandler) ScanJob() {
|
||||
scanner := bufio.NewScanner(os.Stdin)
|
||||
for scanner.Scan() {
|
||||
select {
|
||||
case <-s.Ctx.Done():
|
||||
return
|
||||
default:
|
||||
s.stdInChan <- Stdin{scanner.Text()}
|
||||
}
|
||||
}
|
||||
}
|
||||
func (s *StdinHandler) OnStart() (err error) {
|
||||
s.RegisterCritical(s.OnTick)
|
||||
s.stdInChan = make(chan Stdin)
|
||||
go s.ScanJob()
|
||||
return
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
package modules
|
||||
package event
|
||||
|
||||
import "time"
|
||||
import (
|
||||
"slices"
|
||||
"time"
|
||||
)
|
||||
|
||||
type IntervalTask struct {
|
||||
F func() error
|
||||
@@ -33,18 +36,15 @@ func (t *Timer) Tick() (err error) {
|
||||
}
|
||||
t.Interval[i] = task
|
||||
}
|
||||
var triggerLater []OnceTask
|
||||
for _, task := range t.Once {
|
||||
for i, task := range t.Once {
|
||||
if task.Trigger.After(time.Now()) {
|
||||
err = task.F()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
} else {
|
||||
triggerLater = append(triggerLater, task)
|
||||
t.Once = slices.Delete(t.Once, i, i)
|
||||
}
|
||||
}
|
||||
t.Once = triggerLater
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
module github.com/admin-else/strom
|
||||
|
||||
go 1.24
|
||||
go 1.25
|
||||
|
||||
require (
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0
|
||||
|
||||
@@ -2,5 +2,7 @@ github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9L
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4=
|
||||
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ=
|
||||
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=
|
||||
|
||||
+28
-32
@@ -2,8 +2,6 @@ package level
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
|
||||
@@ -22,7 +20,8 @@ func UnpackArrayPalette(r io.Reader, bitsPerEntry uint8, numberOfEntries int) (d
|
||||
}
|
||||
var pallet []int32 // remember we can't use make because this is user-controlled data
|
||||
for range palletLen {
|
||||
entry, err := proto_base.DecodeVarInt(r)
|
||||
var entry int32
|
||||
entry, err = proto_base.DecodeVarInt(r)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -60,7 +59,7 @@ func UnpackSingleValuePalette(r io.Reader, numberOfEntries int) (data []int32, e
|
||||
}
|
||||
data = make([]int32, numberOfEntries)
|
||||
for i := range data {
|
||||
data[i] = int32(entry)
|
||||
data[i] = entry
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -76,74 +75,71 @@ func LongsToData(data []uint64, n, bpe int32) (ret []int32) {
|
||||
return
|
||||
}
|
||||
|
||||
func UnpackBlockData(r io.Reader) (blocks [BlocksPerChunkSection]int32, err error) {
|
||||
// UnpackBlockData minecraft does this at net.minecraft.world.chunk.PaletteProvider
|
||||
func UnpackBlockData(r io.Reader) (blocks []int32, err error) {
|
||||
var bitsPerEntry uint8
|
||||
err = binary.Read(r, binary.BigEndian, &bitsPerEntry)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var blocksSlice []int32
|
||||
fmt.Println("blocks bpe", bitsPerEntry)
|
||||
switch bitsPerEntry {
|
||||
case 0:
|
||||
blocksSlice, err = UnpackSingleValuePalette(r, BlocksPerChunkSection)
|
||||
case 1, 2, 3, 4:
|
||||
blocksSlice, err = UnpackArrayPalette(r, bitsPerEntry, BlocksPerChunkSection)
|
||||
case 5, 6, 7, 8:
|
||||
err = errors.New("unimplemented")
|
||||
blocks, err = UnpackSingleValuePalette(r, BlocksPerChunkSection)
|
||||
case 1, 2, 3, 4, 5, 6, 7, 8:
|
||||
blocks, err = UnpackArrayPalette(r, bitsPerEntry, BlocksPerChunkSection)
|
||||
default:
|
||||
blocksSlice, err = UnpackLongData(r, bitsPerEntry, BlocksPerChunkSection)
|
||||
blocks, err = UnpackLongData(r, bitsPerEntry, BlocksPerChunkSection)
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
blocks = [BlocksPerChunkSection]int32(blocksSlice)
|
||||
return
|
||||
}
|
||||
|
||||
func UnpackBiomeData(r io.Reader) (biomes [BiomesPerChunkSection]int32, err error) {
|
||||
func UnpackBiomeData(r io.Reader) (biomes []int32, err error) {
|
||||
// net.minecraft.world.chunk.PaletteProvider#forBiomes
|
||||
var bitsPerEntry uint8
|
||||
err = binary.Read(r, binary.BigEndian, &bitsPerEntry)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var biomesSlice []int32
|
||||
fmt.Println("biome bpe", bitsPerEntry)
|
||||
switch bitsPerEntry {
|
||||
case 0:
|
||||
biomesSlice, err = UnpackSingleValuePalette(r, BiomesPerChunkSection)
|
||||
biomes, err = UnpackSingleValuePalette(r, BiomesPerChunkSection)
|
||||
case 1, 2, 3:
|
||||
biomesSlice, err = UnpackArrayPalette(r, bitsPerEntry, BiomesPerChunkSection)
|
||||
biomes, err = UnpackArrayPalette(r, bitsPerEntry, BiomesPerChunkSection)
|
||||
default:
|
||||
biomesSlice, err = UnpackLongData(r, bitsPerEntry, BiomesPerChunkSection)
|
||||
biomes, err = UnpackLongData(r, bitsPerEntry, BiomesPerChunkSection)
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
biomes = [BiomesPerChunkSection]int32(biomesSlice)
|
||||
return
|
||||
}
|
||||
|
||||
type ChunkSection struct {
|
||||
BlockData [BlocksPerChunkSection]int32
|
||||
BiomeData [BiomesPerChunkSection]int32
|
||||
}
|
||||
|
||||
func UnpackSection(r io.Reader) (s ChunkSection, err error) {
|
||||
func UnpackSection(r io.Reader) (blocks, biomes []int32, err error) {
|
||||
var blockCount int16
|
||||
err = binary.Read(r, binary.BigEndian, &blockCount)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
s.BlockData, err = UnpackBlockData(r)
|
||||
blocks, err = UnpackBlockData(r)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
s.BiomeData, err = UnpackBiomeData(r)
|
||||
if err != nil {
|
||||
return
|
||||
biomes, err = UnpackBiomeData(r)
|
||||
return
|
||||
}
|
||||
|
||||
func UnpackNSections(r io.Reader, n int) (blocks, biomes [][]int32, err error) {
|
||||
for range n {
|
||||
var blocksSection, biomesSections []int32
|
||||
blocksSection, biomesSections, err = UnpackSection(r)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
blocks = append(blocks, blocksSection)
|
||||
biomes = append(biomes, biomesSections)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package level
|
||||
|
||||
import (
|
||||
"github.com/admin-else/strom/nbt"
|
||||
"github.com/go-viper/mapstructure/v2"
|
||||
)
|
||||
|
||||
func LoadStructure(fileName string) (s *Structure, err error) {
|
||||
n, err := nbt.ReadFilePath(fileName)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
s = &Structure{}
|
||||
err = mapstructure.Decode(n.Value, s)
|
||||
return
|
||||
}
|
||||
|
||||
type Structure struct {
|
||||
DataVersion int32
|
||||
Blocks []struct {
|
||||
Pos [3]int32
|
||||
State int
|
||||
}
|
||||
Palette []struct {
|
||||
Name string
|
||||
Properties map[string]string
|
||||
}
|
||||
Size [3]int32
|
||||
}
|
||||
|
||||
func (s *Structure) GetBlock(x, y, z int32) (name string) {
|
||||
for _, block := range s.Blocks {
|
||||
if block.Pos[0] == x && block.Pos[1] == y && block.Pos[2] == z {
|
||||
palletIndex := block.State
|
||||
|
||||
if palletIndex >= len(s.Palette) {
|
||||
return ""
|
||||
}
|
||||
|
||||
return s.Palette[palletIndex].Name
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package nbt
|
||||
|
||||
import (
|
||||
"compress/gzip"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
func WriteFile(file io.Writer, n Tag) (err error) {
|
||||
gzw := gzip.NewWriter(file)
|
||||
defer gzw.Close()
|
||||
err = n.Encode(gzw)
|
||||
return
|
||||
}
|
||||
|
||||
func ReadFile(file io.Reader) (n *Tag, err error) {
|
||||
r, err := gzip.NewReader(file)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer r.Close()
|
||||
n = &Tag{}
|
||||
err = n.Decode(r)
|
||||
return
|
||||
}
|
||||
|
||||
func ReadFilePath(path string) (n *Tag, err error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
return ReadFile(f)
|
||||
}
|
||||
+2
-2
@@ -62,7 +62,7 @@ func (s *Anon) Encode(w io.Writer) (err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Tag) Read(r io.Reader) (err error) {
|
||||
func (s *Tag) Decode(r io.Reader) (err error) {
|
||||
id := int8(0)
|
||||
err = binary.Read(r, Order, &id)
|
||||
if err != nil {
|
||||
@@ -81,7 +81,7 @@ func (s *Tag) Read(r io.Reader) (err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Tag) Write(w io.Writer) (err error) {
|
||||
func (s *Tag) Encode(w io.Writer) (err error) {
|
||||
id, err := getId(s.Value)
|
||||
if err != nil {
|
||||
return
|
||||
|
||||
+142
-35
@@ -3,19 +3,32 @@ package proto
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"reflect"
|
||||
"sync"
|
||||
|
||||
"github.com/admin-else/strom/data"
|
||||
"github.com/admin-else/strom/event"
|
||||
"github.com/admin-else/strom/proto_base"
|
||||
"github.com/admin-else/strom/proto_generated"
|
||||
)
|
||||
|
||||
var BadPacketTypeError = errors.New("bad packet type")
|
||||
var BadPacketIdError = errors.New("bad packet id")
|
||||
var PacketNotFullyDecodedError = errors.New("packet not fully decoded")
|
||||
var (
|
||||
BadPacketTypeErr = errors.New("bad packet type")
|
||||
BadPacketIdErr = errors.New("bad packet id")
|
||||
PacketNotFullyDecodedErr = errors.New("packet not fully decoded")
|
||||
ContextDoneErr = errors.New("context done")
|
||||
WrongStateErr = errors.New("wrong state")
|
||||
WrongDirectionErr = errors.New("wrong direction")
|
||||
CantTranslateErr = errors.New("cant translate packet")
|
||||
PacketDoesntExistInFutureVersionErr = errors.New("packet doesnt exist in future version")
|
||||
)
|
||||
|
||||
// UnCodablePacket represents a packet that could not be decoded due to proto_generated not supporting all packets.
|
||||
var LatestVersion = proto_generated.SupportedVersions[len(proto_generated.SupportedVersions)-1]
|
||||
|
||||
// UnCodablePacket represents a packet that could not be decoded.
|
||||
type UnCodablePacket struct {
|
||||
Err error
|
||||
Data []byte
|
||||
@@ -40,6 +53,30 @@ type Conn struct {
|
||||
Actor proto_base.Actor
|
||||
Version string
|
||||
ProtocolVersion int32
|
||||
|
||||
receiveRoutine bool
|
||||
packetCh chan proto_base.EncodeDecodeAble
|
||||
}
|
||||
|
||||
func (c *Conn) StartConn() (err error) {
|
||||
c.RegisterCritical(c.OnTick)
|
||||
return c.Loop.Start()
|
||||
}
|
||||
|
||||
func (c *Conn) ReceiveJob() {
|
||||
for {
|
||||
select {
|
||||
case <-c.Ctx.Done():
|
||||
return
|
||||
default:
|
||||
packet, err := c.Receive()
|
||||
if err != nil {
|
||||
c.ErrChan <- err
|
||||
return
|
||||
}
|
||||
c.packetCh <- packet
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Conn) SetState(state proto_base.State) {
|
||||
@@ -55,35 +92,92 @@ func (c *Conn) State() proto_base.State {
|
||||
}
|
||||
|
||||
func (c *Conn) SetVersion(version string) (err error) {
|
||||
c.Version = version
|
||||
versionData, err := data.LookUpProtocolVersionByName(c.Version)
|
||||
versionData, err := data.LookUpVersionByName(version)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
c.ProtocolVersion = int32(versionData.Version)
|
||||
c.ProtocolVersion = versionData.Version
|
||||
c.Version = version
|
||||
return
|
||||
}
|
||||
|
||||
func (c *Conn) SetProtocolVersion(version int32) (err error) {
|
||||
versionData, err := data.LookUpVersionByProtocolVersion(version)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
c.ProtocolVersion = versionData.Version
|
||||
c.Version = versionData.MinecraftVersion
|
||||
return
|
||||
}
|
||||
|
||||
// ActivateReceiveRoutine activates the receive-routine.
|
||||
// It ensures that the receive-routine is only started once and creates a buffered channel for packet handling.
|
||||
func (c *Conn) ActivateReceiveRoutine() {
|
||||
if c.receiveRoutine {
|
||||
return
|
||||
}
|
||||
c.packetCh = make(chan proto_base.EncodeDecodeAble, 100) // i dunno how many to buffer 100 seems reasonable
|
||||
go c.ReceiveJob()
|
||||
c.receiveRoutine = true
|
||||
}
|
||||
|
||||
func (c *Conn) translatePacketVersion(packet proto_base.EncodeDecodeAble, packetInfo proto_base.PacketInfo) (convertedPacket proto_base.EncodeDecodeAble, err error) {
|
||||
packetInfoReal, found := LookupPacketInfoByNameProtocolVersionAndState(packetInfo.Name, c.ProtocolVersion, c.State())
|
||||
if !found {
|
||||
err = PacketDoesntExistInFutureVersionErr
|
||||
return
|
||||
}
|
||||
|
||||
dstType := reflect.TypeOf(packetInfoReal.Type)
|
||||
if !SmartConvertibleTo(reflect.TypeOf(packetInfo.Type), dstType) {
|
||||
err = CantTranslateErr
|
||||
return
|
||||
}
|
||||
// can't fail cause pacetinfo.type is proto_base.EncodeDecodeAble
|
||||
convertedPacket = SmartConvert(reflect.ValueOf(packet), dstType).Interface().(proto_base.EncodeDecodeAble)
|
||||
return
|
||||
}
|
||||
|
||||
func (c *Conn) sendRegisteredPacket(packet proto_base.EncodeDecodeAble) (err error) {
|
||||
i, ok := LookupPacketInfoByTypeAndState(packet, c.State())
|
||||
if !ok {
|
||||
err = BadPacketTypeErr
|
||||
return
|
||||
}
|
||||
if i.Direction != c.Actor.SendDirection() {
|
||||
err = WrongDirectionErr
|
||||
return
|
||||
}
|
||||
if i.State != c.State() {
|
||||
err = WrongStateErr
|
||||
return
|
||||
}
|
||||
if i.ProtocolVersion != c.ProtocolVersion {
|
||||
packet, err = c.translatePacketVersion(packet, i)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
var packetBuff = bytes.NewBuffer(nil)
|
||||
err = proto_base.EncodeVarInt(packetBuff, i.PacketId)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = packet.Encode(packetBuff)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
slog.Debug("send", "actor", c.Actor, "packet", fmt.Sprintf("%#v", packet))
|
||||
return c.SendRaw(packetBuff.Bytes())
|
||||
}
|
||||
|
||||
func (c *Conn) Send(packet proto_base.EncodeDecodeAble) (err error) {
|
||||
//fmt.Println("send:", packet)
|
||||
switch packet := packet.(type) {
|
||||
case *UnCodablePacket:
|
||||
err = c.SendRaw(packet.Data)
|
||||
default:
|
||||
i, ok := LookupPacketInfoByTypeLookupPacketInfoByTypeAndMore(packet, c.State())
|
||||
if !ok {
|
||||
err = BadPacketTypeError
|
||||
}
|
||||
var packetBuff = bytes.NewBuffer(nil)
|
||||
err = proto_base.EncodeVarInt(packetBuff, i.PacketId)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = packet.Encode(packetBuff)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = c.SendRaw(packetBuff.Bytes())
|
||||
return c.sendRegisteredPacket(packet)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -100,36 +194,49 @@ func (c *Conn) Receive() (packet proto_base.EncodeDecodeAble, err error) {
|
||||
}
|
||||
packet, ok := LookUpTypeByPacketInfoAndCopyType(c.Actor.ReceiveDirection(), c.State(), id, c.ProtocolVersion)
|
||||
if !ok {
|
||||
packet = &UnCodablePacket{Err: BadPacketIdError, Data: packetBytes, Direction: c.Actor.ReceiveDirection()}
|
||||
packet = &UnCodablePacket{Err: BadPacketIdErr, Data: packetBytes, Direction: c.Actor.ReceiveDirection()}
|
||||
return
|
||||
}
|
||||
err = packet.Decode(b)
|
||||
if err != nil {
|
||||
packet = &UnCodablePacket{Err: err, Data: packetBytes, Direction: c.Actor.ReceiveDirection()}
|
||||
err = nil
|
||||
return
|
||||
}
|
||||
if b.Len() != 0 {
|
||||
err = nil
|
||||
packet = &UnCodablePacket{Err: PacketNotFullyDecodedError, Data: packetBytes, Direction: c.Actor.ReceiveDirection()}
|
||||
packet = &UnCodablePacket{Err: PacketNotFullyDecodedErr, Data: packetBytes, Direction: c.Actor.ReceiveDirection()}
|
||||
return
|
||||
}
|
||||
//fmt.Println("recv:", packet)
|
||||
return
|
||||
}
|
||||
|
||||
func (c *Conn) OnTick(_ event.Tick) (err error) {
|
||||
packet, err := c.Receive()
|
||||
if err != nil {
|
||||
return
|
||||
var packet proto_base.EncodeDecodeAble
|
||||
if c.receiveRoutine {
|
||||
select {
|
||||
case packet = <-c.packetCh:
|
||||
slog.Debug("receive", "actor", c.Actor, "packet", fmt.Sprintf("%#v", packet))
|
||||
err = c.Loop.Fire(packet)
|
||||
case <-c.Ctx.Done():
|
||||
err = ContextDoneErr
|
||||
return
|
||||
default:
|
||||
}
|
||||
} else {
|
||||
packet, err = c.Receive()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
slog.Debug("receive", "actor", c.Actor, "packet", fmt.Sprintf("%#v", packet))
|
||||
err = c.Loop.Fire(packet)
|
||||
}
|
||||
err = c.Loop.Fire(packet)
|
||||
return
|
||||
}
|
||||
|
||||
func (c *Conn) Start(handlers ...any) (err error) {
|
||||
c.Loop = &event.Loop{}
|
||||
c.Handlers = append(c.Handlers, c)
|
||||
c.Handlers = append(c.Handlers, handlers...)
|
||||
err = c.Loop.Start()
|
||||
return
|
||||
func (c *Conn) Start() (err error) {
|
||||
if c.Loop == nil {
|
||||
c.Loop = &event.Loop{}
|
||||
}
|
||||
return c.Loop.Start()
|
||||
}
|
||||
|
||||
+16
-32
@@ -7,7 +7,7 @@ import (
|
||||
"github.com/admin-else/strom/proto_generated"
|
||||
)
|
||||
|
||||
// I know this is in-performant and i dont care until it becomes a problem for somebody it will stay like this and it is pretty easy to make caches or simular to speed this up so yeah
|
||||
// I know this is in-performant and i dont care until it becomes a problem for somebody it will stay like this and it is pretty easy to make caches or similar to speed this up so yeah
|
||||
|
||||
func LookUpTypeByPacketInfo(direction proto_base.Direction, state proto_base.State, pid, version int32) (p proto_base.PacketInfo, ok bool) {
|
||||
for _, pin := range proto_generated.Packets {
|
||||
@@ -29,43 +29,27 @@ func LookUpTypeByPacketInfoAndCopyType(direction proto_base.Direction, state pro
|
||||
}
|
||||
|
||||
func LookupPacketInfoByType(packet proto_base.EncodeDecodeAble) (p proto_base.PacketInfo, ok bool) {
|
||||
switch packet := packet.(type) {
|
||||
case *UnCodablePacket:
|
||||
p = proto_base.PacketInfo{
|
||||
Type: &UnCodablePacket{},
|
||||
Name: "undecodeable",
|
||||
Direction: packet.Direction,
|
||||
State: -1,
|
||||
PacketId: -1,
|
||||
ProtocolVersion: -1,
|
||||
}
|
||||
ok = true
|
||||
default:
|
||||
for _, p := range proto_generated.Packets {
|
||||
if reflect.TypeOf(p.Type) == reflect.TypeOf(packet) {
|
||||
return p, true
|
||||
}
|
||||
for _, p := range proto_generated.Packets {
|
||||
if reflect.TypeOf(p.Type) == reflect.TypeOf(packet) {
|
||||
return p, true
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func LookupPacketInfoByTypeLookupPacketInfoByTypeAndMore(packet proto_base.EncodeDecodeAble, state proto_base.State) (p proto_base.PacketInfo, ok bool) {
|
||||
switch packet := packet.(type) {
|
||||
case *UnCodablePacket:
|
||||
p = proto_base.PacketInfo{
|
||||
Type: &UnCodablePacket{},
|
||||
Name: "undecodeable",
|
||||
Direction: packet.Direction,
|
||||
State: -1,
|
||||
PacketId: -1,
|
||||
ProtocolVersion: -1,
|
||||
func LookupPacketInfoByTypeAndState(packet proto_base.EncodeDecodeAble, state proto_base.State) (p proto_base.PacketInfo, ok bool) {
|
||||
for _, p := range proto_generated.Packets {
|
||||
if state == p.State && reflect.TypeOf(p.Type) == reflect.TypeOf(packet) {
|
||||
return p, true
|
||||
}
|
||||
default:
|
||||
for _, p := range proto_generated.Packets {
|
||||
if state == p.State && reflect.TypeOf(p.Type) == reflect.TypeOf(packet) {
|
||||
return p, true
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func LookupPacketInfoByNameProtocolVersionAndState(name string, version int32, state proto_base.State) (p proto_base.PacketInfo, ok bool) {
|
||||
for _, p := range proto_generated.Packets {
|
||||
if state == p.State && p.Name == name && p.ProtocolVersion == version {
|
||||
return p, true
|
||||
}
|
||||
}
|
||||
return
|
||||
|
||||
+22
-8
@@ -8,6 +8,7 @@ import (
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
|
||||
"github.com/admin-else/strom/crypto"
|
||||
"github.com/admin-else/strom/proto_base"
|
||||
@@ -15,22 +16,36 @@ import (
|
||||
|
||||
type RawConn struct {
|
||||
net.Conn
|
||||
R io.Reader
|
||||
W io.Writer
|
||||
CompressionThreshold int32
|
||||
R io.Reader
|
||||
W io.Writer
|
||||
compressionThreshold int32
|
||||
CompressionThresholdMut sync.RWMutex
|
||||
}
|
||||
|
||||
func (c *RawConn) SetCompressionThreshold(threshold int32) {
|
||||
c.CompressionThresholdMut.Lock()
|
||||
defer c.CompressionThresholdMut.Unlock()
|
||||
c.compressionThreshold = threshold
|
||||
}
|
||||
|
||||
func (c *RawConn) GetCompressionThreshold() int32 {
|
||||
c.CompressionThresholdMut.RLock()
|
||||
defer c.CompressionThresholdMut.RUnlock()
|
||||
return c.compressionThreshold
|
||||
}
|
||||
|
||||
func (c *RawConn) SendRaw(rawPacketBytes []byte) (err error) {
|
||||
//fmt.Println("send:", rawPacketBytes)
|
||||
var packetBytes []byte
|
||||
if c.CompressionThreshold > 0 {
|
||||
threshold := c.GetCompressionThreshold()
|
||||
if threshold > 0 {
|
||||
packetBuffer := bytes.NewBuffer(nil)
|
||||
if int32(len(rawPacketBytes)) >= c.CompressionThreshold {
|
||||
if int32(len(rawPacketBytes)) >= threshold {
|
||||
err = proto_base.EncodeVarInt(packetBuffer, int32(len(rawPacketBytes)))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
zW := zlib.NewWriter(packetBuffer)
|
||||
zW := zlib.NewWriter(packetBuffer) // ignore we don't care about the result if it errors
|
||||
_, err = zW.Write(rawPacketBytes)
|
||||
if err != nil {
|
||||
return
|
||||
@@ -80,7 +95,7 @@ func (c *RawConn) ReceiveRaw() (packetBytes []byte, err error) {
|
||||
return
|
||||
}
|
||||
rawPacketBuffer := bytes.NewBuffer(rawPacketBytes)
|
||||
if c.CompressionThreshold > 0 {
|
||||
if c.GetCompressionThreshold() > 0 {
|
||||
var packetLen int32
|
||||
packetLen, err = proto_base.DecodeVarInt(rawPacketBuffer)
|
||||
if err != nil {
|
||||
@@ -106,7 +121,6 @@ func (c *RawConn) ReceiveRaw() (packetBytes []byte, err error) {
|
||||
} else {
|
||||
packetBytes = rawPacketBytes
|
||||
}
|
||||
//fmt.Println("recv:", packetBytes)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
package proto
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"slices"
|
||||
|
||||
"github.com/admin-else/strom/data"
|
||||
"github.com/admin-else/strom/event"
|
||||
"github.com/admin-else/strom/proto_base"
|
||||
"github.com/admin-else/strom/proto_generated"
|
||||
)
|
||||
|
||||
func SmartConvertibleTo(from, to reflect.Type) bool {
|
||||
switch from.Kind() {
|
||||
case reflect.Struct:
|
||||
if from.NumField() != to.NumField() {
|
||||
return false
|
||||
}
|
||||
for i := range from.NumField() {
|
||||
if !SmartConvertibleTo(from.Field(i).Type, to.Field(i).Type) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
case reflect.Ptr:
|
||||
return SmartConvertibleTo(from.Elem(), to.Elem())
|
||||
default:
|
||||
return from.ConvertibleTo(to)
|
||||
}
|
||||
}
|
||||
|
||||
func SmartConvert(from reflect.Value, to reflect.Type) (ret reflect.Value) {
|
||||
switch from.Kind() {
|
||||
case reflect.Struct:
|
||||
ret = reflect.New(to).Elem()
|
||||
for i := range from.NumField() {
|
||||
ret.Field(i).Set(SmartConvert(from.Field(i), to.Field(i).Type))
|
||||
}
|
||||
return ret
|
||||
case reflect.Ptr:
|
||||
if from.IsNil() {
|
||||
return reflect.Zero(to)
|
||||
}
|
||||
return SmartConvert(from.Elem(), to.Elem()).Addr()
|
||||
default:
|
||||
return from.Convert(to)
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterUntilLatest registers a handler for all versions between the passed in packet version and the latest supported version.
|
||||
// Warning: If a bad handler is passed in, the program will panic.
|
||||
func (c *Conn) RegisterUntilLatest(h any) {
|
||||
c.registerUntil(h, LatestVersion, false)
|
||||
}
|
||||
|
||||
// RegisterUntil registers a handler for all versions between the passed in packet version and the specified version.
|
||||
// Warning: If a bad handler is passed in, the program will panic.
|
||||
func (c *Conn) RegisterUntil(h any, until string) {
|
||||
c.registerUntil(h, until, false)
|
||||
}
|
||||
|
||||
// RegisterCriticalUntilLatest registers a handler for all versions between the passed in packet version and the latest supported version.
|
||||
// If this handler returns an error, the connection will be closed.
|
||||
// Warning: If a bad handler is passed in, the program will panic.
|
||||
func (c *Conn) RegisterCriticalUntilLatest(h any) {
|
||||
c.registerUntil(h, LatestVersion, true)
|
||||
}
|
||||
|
||||
// RegisterCriticalUntil registers a handler for all versions between the passed in packet version and the specified version.
|
||||
// If this handler returns an error, the connection will be closed.
|
||||
// Warning: If a bad handler is passed in, the program will panic.
|
||||
func (c *Conn) RegisterCriticalUntil(h any, until string) {
|
||||
c.registerUntil(h, until, true)
|
||||
}
|
||||
|
||||
func (c *Conn) registerUntil(h any, until string, critical bool) {
|
||||
eventType, hv := event.ValidateHandler(h)
|
||||
c.RegisterDirect(eventType, hv)
|
||||
if !eventType.Implements(reflect.TypeFor[proto_base.EncodeDecodeAble]()) {
|
||||
panic("expected method with argument that implements proto_base.EncodeDecodeAble")
|
||||
}
|
||||
packetInfo, found := LookupPacketInfoByType(reflect.Zero(eventType).Interface().(proto_base.EncodeDecodeAble))
|
||||
if !found {
|
||||
panic("packet not found")
|
||||
}
|
||||
versionInfo, err := data.LookUpVersionByProtocolVersion(packetInfo.ProtocolVersion)
|
||||
if err != nil {
|
||||
panic("protocol version not found")
|
||||
}
|
||||
startIndex := slices.Index(proto_generated.SupportedVersions, versionInfo.MinecraftVersion)
|
||||
endIndex := slices.Index(proto_generated.SupportedVersions, until)
|
||||
for i := startIndex + 1; i <= endIndex; i++ {
|
||||
versionName := proto_generated.SupportedVersions[i]
|
||||
versionInfo, err = data.LookUpVersionByName(versionName)
|
||||
if err != nil {
|
||||
panic("protocol version not found")
|
||||
}
|
||||
var newPacketInfo proto_base.PacketInfo
|
||||
newPacketInfo, found = LookupPacketInfoByNameProtocolVersionAndState(packetInfo.Name, versionInfo.Version, packetInfo.State)
|
||||
if !found {
|
||||
panic("packet not found")
|
||||
}
|
||||
newT := reflect.TypeOf(newPacketInfo.Type)
|
||||
if !SmartConvertibleTo(newT, reflect.TypeOf(packetInfo.Type)) {
|
||||
panic(fmt.Sprintf("packet %v is not convertible to %v", newT, reflect.TypeOf(packetInfo.Type)))
|
||||
}
|
||||
handleFunc := func(packet any) error {
|
||||
v := hv.Call([]reflect.Value{SmartConvert(reflect.ValueOf(packet), reflect.TypeOf(packetInfo.Type))})[0]
|
||||
if v.IsNil() {
|
||||
return nil
|
||||
}
|
||||
return v.Interface().(error)
|
||||
}
|
||||
if critical {
|
||||
c.RegisterCustomType(newT, reflect.ValueOf(handleFunc))
|
||||
} else {
|
||||
c.RegisterDirect(newT, reflect.ValueOf(handleFunc))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package proto_test
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/admin-else/strom/proto"
|
||||
"github.com/admin-else/strom/proto_generated/v1_21_8"
|
||||
"github.com/admin-else/strom/proto_generated/v1_21_9"
|
||||
)
|
||||
|
||||
func TestCanSmartConvert(t *testing.T) {
|
||||
packet := &v1_21_9.PlayToClientPacketPosition{Flags: v1_21_9.PlayToClientPositionUpdateRelatives{Val: 2}, X: 5}
|
||||
can := proto.SmartConvertibleTo(reflect.TypeOf(packet), reflect.TypeFor[*v1_21_8.PlayToClientPacketPosition]())
|
||||
if !can {
|
||||
t.Fatal("can't smart convert")
|
||||
}
|
||||
ret := proto.SmartConvert(reflect.ValueOf(packet), reflect.TypeFor[*v1_21_8.PlayToClientPacketPosition]())
|
||||
t.Logf("%#v", ret)
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
go test fuzz v1
|
||||
[]byte("\x05\x000000")
|
||||
@@ -0,0 +1,2 @@
|
||||
go test fuzz v1
|
||||
[]byte("0")
|
||||
@@ -0,0 +1,2 @@
|
||||
go test fuzz v1
|
||||
[]byte("00")
|
||||
@@ -0,0 +1,2 @@
|
||||
go test fuzz v1
|
||||
[]byte("\x040000")
|
||||
@@ -0,0 +1,2 @@
|
||||
go test fuzz v1
|
||||
[]byte("\x0400000")
|
||||
@@ -0,0 +1,2 @@
|
||||
go test fuzz v1
|
||||
[]byte("\x86\x00000000")
|
||||
@@ -0,0 +1,2 @@
|
||||
go test fuzz v1
|
||||
[]byte("")
|
||||
@@ -0,0 +1,2 @@
|
||||
go test fuzz v1
|
||||
[]byte("80\x00\x01\x05\x01\x010\x01\x00")
|
||||
@@ -6,6 +6,10 @@ import (
|
||||
"io"
|
||||
)
|
||||
|
||||
var (
|
||||
UnimplementedErr = errors.New("unimplemented")
|
||||
)
|
||||
|
||||
type Direction int
|
||||
|
||||
const (
|
||||
@@ -45,6 +49,17 @@ const (
|
||||
Client
|
||||
)
|
||||
|
||||
func (a Actor) String() string {
|
||||
switch a {
|
||||
case Servee:
|
||||
return "Servee"
|
||||
case Client:
|
||||
return "Client"
|
||||
default:
|
||||
return "Unknown"
|
||||
}
|
||||
}
|
||||
|
||||
func (a Actor) SendDirection() Direction {
|
||||
switch a {
|
||||
case Servee:
|
||||
@@ -67,12 +82,6 @@ func (a Actor) ReceiveDirection() Direction {
|
||||
}
|
||||
}
|
||||
|
||||
type PacketIdentifier struct {
|
||||
Direction Direction
|
||||
State State
|
||||
Name string
|
||||
}
|
||||
|
||||
type (
|
||||
ToDo struct{}
|
||||
RestBuffer []byte
|
||||
@@ -213,6 +222,15 @@ type EncodeDecodeAble interface {
|
||||
Decode(r io.Reader) (err error)
|
||||
}
|
||||
|
||||
type Void struct{}
|
||||
|
||||
func (v Void) Encode(w io.Writer) (err error) {
|
||||
return
|
||||
}
|
||||
func (v Void) Decode(r io.Reader) (err error) {
|
||||
return
|
||||
}
|
||||
|
||||
type PacketInfo struct {
|
||||
Type EncodeDecodeAble
|
||||
Name string
|
||||
@@ -221,3 +239,31 @@ type PacketInfo struct {
|
||||
PacketId int32
|
||||
ProtocolVersion int32
|
||||
}
|
||||
|
||||
func Bool2uint8(b bool) uint8 {
|
||||
if b {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func Bool2uint16(b bool) uint16 {
|
||||
if b {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func Bool2uint32(b bool) uint32 {
|
||||
if b {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func Bool2uint64(b bool) uint64 {
|
||||
if b {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
+9437
-10562
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -15,6 +15,7 @@ type TypesInfo struct {
|
||||
|
||||
type PacketInfo struct {
|
||||
TName, Name, Direction, State, PacketId, ProtocolVersion, MinecraftVersion string
|
||||
PacketDef any
|
||||
}
|
||||
|
||||
func GeneratePacketInfoFile(versions []string, packetInfos []PacketInfo) (err error) {
|
||||
@@ -31,10 +32,8 @@ func GeneratePacketInfoFile(versions []string, packetInfos []PacketInfo) (err er
|
||||
vUnderscore := "v" + strings.ReplaceAll(p.MinecraftVersion, ".", "_")
|
||||
typeName := p.TName
|
||||
var typeExpr ast.Expr
|
||||
if typeName == "struct{}" {
|
||||
typeExpr = &ast.StructType{Fields: &ast.FieldList{}}
|
||||
} else if strings.HasPrefix(typeName, "proto_base.") {
|
||||
typeExpr = Selector("proto_base", strings.TrimPrefix(typeName, "proto_base."))
|
||||
if p.PacketDef == "void" {
|
||||
typeExpr = Selector("proto_base", "Void")
|
||||
} else {
|
||||
typeExpr = Selector(vUnderscore, typeName)
|
||||
}
|
||||
@@ -46,11 +45,17 @@ func GeneratePacketInfoFile(versions []string, packetInfos []PacketInfo) (err er
|
||||
KeyValueExpr(Ident("Type"), AddrOf(CompLit(typeExpr, nil))),
|
||||
KeyValueExpr(Ident("Name"), StrLit(p.Name)),
|
||||
KeyValueExpr(Ident("Direction"), Selector("proto_base", p.Direction)),
|
||||
KeyValueExpr(Ident("state"), Selector("proto_base", p.State)),
|
||||
KeyValueExpr(Ident("State"), Selector("proto_base", p.State)),
|
||||
KeyValueExpr(Ident("PacketId"), NumLit(int(packetId))),
|
||||
KeyValueExpr(Ident("ProtocolVersion"), NumLit(protocolVersion)),
|
||||
}))
|
||||
}
|
||||
|
||||
var supportedVersionsExprs []ast.Expr
|
||||
for _, v := range versions {
|
||||
supportedVersionsExprs = append(supportedVersionsExprs, StrLit(v))
|
||||
}
|
||||
AppendDecl(f, VarValues("SupportedVersions", CompLit(Slice(Ident("string")), supportedVersionsExprs)))
|
||||
AppendDecl(f, VarValues("Packets", CompLit(Slice(Selector("proto_base", "PacketInfo")), packetInfoExprs)))
|
||||
out, err := os.Create("proto_generated/packet_info.go")
|
||||
if err != nil {
|
||||
|
||||
+22
-18
@@ -38,6 +38,12 @@ type ContainerStackEntry struct {
|
||||
VarToSet ast.Expr
|
||||
}
|
||||
|
||||
type ExprGeneratorFunc func(g *Generator, data any) (ast.Expr, error)
|
||||
|
||||
type CompareToGeneratorFunc func(g *Generator, parts []string, inExpr ast.Expr, data any) (e ast.Expr, cet CaseExprType, err error)
|
||||
|
||||
type FunctionGeneratorFunc func(g *Generator, varToSet ast.Expr, data any, name string) ([]ast.Stmt, error)
|
||||
|
||||
type Generator struct {
|
||||
packetInfos []PacketInfo
|
||||
|
||||
@@ -60,7 +66,6 @@ type Generator struct {
|
||||
Depth int
|
||||
Declared []string
|
||||
ContainerStack []ContainerStackEntry
|
||||
VtsStack []ast.Expr
|
||||
}
|
||||
|
||||
func (g *Generator) Decl(name string, t token.Token, e ast.Expr) {
|
||||
@@ -104,12 +109,6 @@ func ParseType(t any) (tName string, tData any, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
type ExprGeneratorFunc func(g *Generator, data any) (ast.Expr, error)
|
||||
|
||||
type CompareToGeneratorFunc func(g *Generator, parts []string, inExpr ast.Expr, data any) (ast.Expr, error)
|
||||
|
||||
type FunctionGeneratorFunc func(g *Generator, varToSet ast.Expr, data any, name string) ([]ast.Stmt, error)
|
||||
|
||||
func (g *Generator) VisitType(data any) (e ast.Expr, err error) {
|
||||
tName, tData, err := ParseType(data)
|
||||
if err != nil {
|
||||
@@ -247,7 +246,7 @@ func (g *Generator) GenerateTypes(prefix string, types Types) (err error) {
|
||||
}
|
||||
|
||||
func (g *Generator) GenerateProtocol(protocol Protocol, version string) (err error) {
|
||||
versionData, err := data.LookUpProtocolVersionByName(version)
|
||||
versionData, err := data.LookUpVersionByName(version)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -271,7 +270,8 @@ func (g *Generator) GenerateProtocol(protocol Protocol, version string) (err err
|
||||
v := protocol.Types.Types[k]
|
||||
if strings.Contains(k, "packet") {
|
||||
delete(protocol.Types.Types, k)
|
||||
for prefix, types := range prefixTypeMap {
|
||||
for _, prefix := range OrderedKeys(prefixTypeMap) {
|
||||
types := prefixTypeMap[prefix]
|
||||
if prefix == "" {
|
||||
continue
|
||||
}
|
||||
@@ -280,32 +280,36 @@ func (g *Generator) GenerateProtocol(protocol Protocol, version string) (err err
|
||||
}
|
||||
}
|
||||
|
||||
for prefix, types := range prefixTypeMap {
|
||||
for k, v := range types.Types.Types {
|
||||
for _, prefix := range OrderedKeys(prefixTypeMap) {
|
||||
types := prefixTypeMap[prefix]
|
||||
for _, k := range OrderedKeys(types.Types.Types) {
|
||||
typeData := types.Types.Types[k]
|
||||
if k != "packet" {
|
||||
continue
|
||||
}
|
||||
packetIds := v.([]any)[1].([]any)[0].(map[string]any)["type"].([]any)[1].(map[string]any)["mappings"].(map[string]any)
|
||||
packetIds := typeData.([]any)[1].([]any)[0].(map[string]any)["type"].([]any)[1].(map[string]any)["mappings"].(map[string]any)
|
||||
packetIdsStrings := AssertAndConvertMapValues[string](packetIds)
|
||||
packetIdsRev := ReverseMap(packetIdsStrings)
|
||||
v := v.([]any)[1].([]any)[1].(map[string]any)["type"].([]any)[1].(map[string]any)["fields"].(map[string]any)
|
||||
for k2, v2 := range v {
|
||||
v2 := v2.(string)
|
||||
v := typeData.([]any)[1].([]any)[1].(map[string]any)["type"].([]any)[1].(map[string]any)["fields"].(map[string]any)
|
||||
for _, k2 := range OrderedKeys(v) {
|
||||
v2 := v[k2].(string)
|
||||
typeName := prefix + CamelCase(v2)
|
||||
g.packetInfos = append(g.packetInfos, PacketInfo{
|
||||
PacketDef: v2,
|
||||
TName: typeName,
|
||||
Name: k2,
|
||||
Direction: types.Direction,
|
||||
State: types.State,
|
||||
PacketId: packetIdsRev[k2],
|
||||
ProtocolVersion: strconv.Itoa(versionData.Version),
|
||||
ProtocolVersion: strconv.Itoa(int(versionData.Version)),
|
||||
MinecraftVersion: version,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for prefix, types := range prefixTypeMap {
|
||||
for _, prefix := range OrderedKeys(prefixTypeMap) {
|
||||
types := prefixTypeMap[prefix]
|
||||
err = g.GenerateTypes(prefix, types.Types)
|
||||
if err != nil {
|
||||
return
|
||||
@@ -378,7 +382,7 @@ func GenerateVersions(versions []string) (err error) {
|
||||
}
|
||||
|
||||
func main() {
|
||||
err := GenerateVersions([]string{"1.21.8"})
|
||||
err := GenerateVersions([]string{"1.21.8", "1.21.9", "1.21.11"})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
@@ -6,10 +6,11 @@ import (
|
||||
"go/ast"
|
||||
"strings"
|
||||
|
||||
"github.com/admin-else/strom/proto_generator/protodef"
|
||||
"github.com/go-viper/mapstructure/v2"
|
||||
)
|
||||
|
||||
func (g *Generator) ParseCompareTo(compareTo string) (e ast.Expr, err error) {
|
||||
func (g *Generator) ParseCompareTo(compareTo string) (e ast.Expr, cet CaseExprType, err error) {
|
||||
parts := strings.Split(compareTo, "/")
|
||||
downPrefixCount := 0
|
||||
for _, part := range parts {
|
||||
@@ -19,12 +20,12 @@ func (g *Generator) ParseCompareTo(compareTo string) (e ast.Expr, err error) {
|
||||
}
|
||||
parts = parts[downPrefixCount:]
|
||||
startingPoint := g.ContainerStack[len(g.ContainerStack)-downPrefixCount-1]
|
||||
e, err = g.VisitCompareTo(parts, startingPoint.VarToSet, CombineNamAndData("container", startingPoint.Data))
|
||||
e, cet, err = g.VisitCompareTo(parts, startingPoint.VarToSet, CombineNamAndData("container", startingPoint.Data))
|
||||
// return ParseCompareToLegacy(compareTo, varToSet)
|
||||
return
|
||||
}
|
||||
|
||||
func (g *Generator) VisitCompareTo(parts []string, inExpr ast.Expr, data any) (e ast.Expr, err error) {
|
||||
func (g *Generator) VisitCompareTo(parts []string, inExpr ast.Expr, data any) (e ast.Expr, cet CaseExprType, err error) {
|
||||
tName, tData, err := ParseType(data)
|
||||
if err != nil {
|
||||
return
|
||||
@@ -37,12 +38,8 @@ func (g *Generator) VisitCompareTo(parts []string, inExpr ast.Expr, data any) (e
|
||||
return
|
||||
}
|
||||
|
||||
func ContainerCompareTo(g *Generator, parts []string, inExpr ast.Expr, dataRaw any) (e ast.Expr, err error) {
|
||||
var data []struct {
|
||||
Name string
|
||||
Type any
|
||||
Anon bool
|
||||
}
|
||||
func ContainerCompareTo(g *Generator, parts []string, inExpr ast.Expr, dataRaw any) (e ast.Expr, cet CaseExprType, err error) {
|
||||
var data protodef.Container
|
||||
err = mapstructure.Decode(dataRaw, &data)
|
||||
if err != nil {
|
||||
return
|
||||
@@ -62,15 +59,40 @@ func ContainerCompareTo(g *Generator, parts []string, inExpr ast.Expr, dataRaw a
|
||||
return
|
||||
}
|
||||
|
||||
func ReturnInputCompareTo(_ *Generator, _ []string, inExpr ast.Expr, _ any) (e ast.Expr, err error) {
|
||||
return inExpr, nil
|
||||
func ReturnInputCompareTo(_ *Generator, _ []string, inExpr ast.Expr, _ any) (e ast.Expr, cet CaseExprType, err error) {
|
||||
return inExpr, CaseExprTypeUnset, nil
|
||||
}
|
||||
|
||||
func BitflagsCompareTo(_ *Generator, parts []string, inExpr ast.Expr, dataRaw any) (e ast.Expr, err error) {
|
||||
var data struct {
|
||||
Flags []string
|
||||
Type any
|
||||
func BitfieldCompareTo(_ *Generator, parts []string, inExpr ast.Expr, dataRaw any) (e ast.Expr, cet CaseExprType, err error) {
|
||||
var data protodef.BitField
|
||||
err = mapstructure.Decode(dataRaw, &data)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
fieldName, parts, found := PopFront(parts)
|
||||
if !found {
|
||||
err = errors.New("expected name part")
|
||||
return
|
||||
}
|
||||
var field protodef.BitFieldEntry
|
||||
for _, f := range data {
|
||||
if f.Name == fieldName {
|
||||
field = f
|
||||
break
|
||||
}
|
||||
}
|
||||
if field.Size == 1 {
|
||||
cet = CaseExprTypeOnlyBool
|
||||
} else {
|
||||
cet = CaseExprTypeOnlyNumber
|
||||
}
|
||||
|
||||
e = SelectorExprAndStr(inExpr, CamelCase(fieldName))
|
||||
return
|
||||
}
|
||||
|
||||
func BitflagsCompareTo(_ *Generator, parts []string, inExpr ast.Expr, dataRaw any) (e ast.Expr, cet CaseExprType, err error) {
|
||||
var data protodef.BitFlags
|
||||
err = mapstructure.Decode(dataRaw, &data)
|
||||
if err != nil {
|
||||
return
|
||||
@@ -98,7 +120,7 @@ func (g *Generator) RegisterCompareToNatives() {
|
||||
"bool": ReturnInputCompareTo,
|
||||
"mapper": ReturnInputCompareTo,
|
||||
"varint": ReturnInputCompareTo,
|
||||
"bitfield": ReturnInputCompareTo,
|
||||
"bitfield": BitfieldCompareTo,
|
||||
"u8": ReturnInputCompareTo,
|
||||
"i8": ReturnInputCompareTo,
|
||||
"bitflags": BitflagsCompareTo,
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"slices"
|
||||
"strconv"
|
||||
|
||||
"github.com/admin-else/strom/proto_generator/protodef"
|
||||
"github.com/go-viper/mapstructure/v2"
|
||||
)
|
||||
|
||||
@@ -31,11 +32,7 @@ func UUIDDecoder(_ *Generator, varToSet ast.Expr, _ any, _ string) (s []ast.Stmt
|
||||
}
|
||||
|
||||
func ContainerDecoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
||||
var data []struct {
|
||||
Name string
|
||||
Type any
|
||||
Anon bool
|
||||
}
|
||||
var data protodef.Container
|
||||
err = mapstructure.Decode(dataRaw, &data)
|
||||
if err != nil {
|
||||
return
|
||||
@@ -108,11 +105,7 @@ func OptionDecoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s
|
||||
}
|
||||
|
||||
func ArrayDecoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
||||
var data struct {
|
||||
CountType any
|
||||
Count string
|
||||
Type any
|
||||
}
|
||||
var data protodef.Array
|
||||
lName := "l" + CamelCase(name)
|
||||
err = mapstructure.Decode(dataRaw, &data)
|
||||
if err != nil {
|
||||
@@ -136,7 +129,7 @@ func ArrayDecoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s
|
||||
if err == nil {
|
||||
e = NumLit(n)
|
||||
} else {
|
||||
e, err = g.ParseCompareTo(data.Count)
|
||||
e, _, err = g.ParseCompareTo(data.Count)
|
||||
}
|
||||
s2 = append(s2, Assign121(Ident(lName), e))
|
||||
}
|
||||
@@ -171,16 +164,14 @@ func ArrayDecoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s
|
||||
}
|
||||
|
||||
func TypeForwardDecoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
||||
var data struct {
|
||||
Type string
|
||||
}
|
||||
var data protodef.TypeForward
|
||||
if err = mapstructure.Decode(dataRaw, &data); err != nil {
|
||||
return
|
||||
}
|
||||
return g.VisitDecoder(varToSet, data.Type, name)
|
||||
}
|
||||
|
||||
var DontStringify = []string{"true", "false"}
|
||||
var BooleanValues = []string{"true", "false"}
|
||||
|
||||
// CaseExprType This exists to fix this
|
||||
// "switch",
|
||||
@@ -194,13 +185,22 @@ var DontStringify = []string{"true", "false"}
|
||||
// "default": [
|
||||
//
|
||||
// Protodef is best!!!
|
||||
// they are also inconsistent with bool compare to sometimes they use false sometimes they use numbers
|
||||
// that's why this bullshit exists
|
||||
type CaseExprType int
|
||||
|
||||
const (
|
||||
CaseExprTypeUnset CaseExprType = iota
|
||||
CaseExprTypeNumber
|
||||
CaseExprTypeSpecial
|
||||
CaseExprTypeBool
|
||||
CaseExprTypeString
|
||||
|
||||
// CaseExprTypeOnlyNumber CaseExprTypeOnlyBool CaseExprTypeStringOnly These are special overwrite values retuned by
|
||||
// the compare to for the case of being certain that it's the right type.
|
||||
|
||||
CaseExprTypeOnlyNumber
|
||||
CaseExprTypeOnlyBool
|
||||
CaseExprTypeStringOnly
|
||||
)
|
||||
|
||||
func MultiTypeFix(s string, t *CaseExprType) (e ast.Expr) {
|
||||
@@ -210,9 +210,9 @@ func MultiTypeFix(s string, t *CaseExprType) (e ast.Expr) {
|
||||
err = nil
|
||||
e = NumLit(n)
|
||||
ct = CaseExprTypeNumber
|
||||
} else if slices.Contains(DontStringify, s) {
|
||||
} else if slices.Contains(BooleanValues, s) {
|
||||
e = Ident(s)
|
||||
ct = CaseExprTypeSpecial
|
||||
ct = CaseExprTypeBool
|
||||
} else {
|
||||
e = StrLit(s)
|
||||
ct = CaseExprTypeString
|
||||
@@ -222,27 +222,32 @@ func MultiTypeFix(s string, t *CaseExprType) (e ast.Expr) {
|
||||
*t = ct
|
||||
return
|
||||
}
|
||||
if *t != ct {
|
||||
e = nil
|
||||
if *t == ct {
|
||||
return
|
||||
}
|
||||
|
||||
if ct == CaseExprTypeNumber && *t == CaseExprTypeOnlyBool {
|
||||
if s == "0" {
|
||||
e = Ident("false")
|
||||
} else {
|
||||
e = Ident("true")
|
||||
}
|
||||
return
|
||||
}
|
||||
e = nil
|
||||
return
|
||||
}
|
||||
|
||||
func SwitchDecoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
||||
var data struct {
|
||||
CompareTo string
|
||||
Fields map[string]any
|
||||
Default any
|
||||
}
|
||||
var data protodef.Switch
|
||||
err = mapstructure.Decode(dataRaw, &data)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
compareToExpr, err := g.ParseCompareTo(data.CompareTo)
|
||||
compareToExpr, cet, err := g.ParseCompareTo(data.CompareTo)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
cet := CaseExprTypeUnset
|
||||
for _, fName := range OrderedKeys(data.Fields) {
|
||||
fType := data.Fields[fName]
|
||||
e := MultiTypeFix(fName, &cet)
|
||||
@@ -258,7 +263,7 @@ func SwitchDecoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s
|
||||
s1 := VarStmt(tName, tType)
|
||||
s3 := Assign121(varToSet, Ident(tName))
|
||||
var caseDecodeValueStmts []ast.Stmt
|
||||
caseDecodeValueStmts, err = g.VisitDecoder(Ident(tName), fType, name)
|
||||
caseDecodeValueStmts, err = g.VisitDecoder(Ident(tName), fType, tName)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -299,10 +304,7 @@ func ToDoDecoder(_ *Generator, _ ast.Expr, _ any, _ string) (s []ast.Stmt, err e
|
||||
}
|
||||
|
||||
func MapperDecoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
||||
var data struct {
|
||||
Mappings map[string]string
|
||||
Type any
|
||||
}
|
||||
var data protodef.Mapper
|
||||
err = mapstructure.Decode(dataRaw, &data)
|
||||
if err != nil {
|
||||
return
|
||||
@@ -335,10 +337,7 @@ func MapperDecoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s
|
||||
}
|
||||
|
||||
func BufferDecoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
||||
var data struct {
|
||||
Count int
|
||||
CountType any
|
||||
}
|
||||
var data protodef.Buffer
|
||||
err = mapstructure.Decode(dataRaw, &data)
|
||||
if err != nil {
|
||||
return
|
||||
@@ -373,11 +372,7 @@ func BufferDecoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s
|
||||
}
|
||||
|
||||
func BitFieldDecoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
||||
var data []struct {
|
||||
Name string
|
||||
Singed bool
|
||||
Size int
|
||||
}
|
||||
var data protodef.BitField
|
||||
err = mapstructure.Decode(dataRaw, &data)
|
||||
if err != nil {
|
||||
return
|
||||
@@ -386,24 +381,74 @@ func BitFieldDecoder(g *Generator, varToSet ast.Expr, dataRaw any, name string)
|
||||
for _, field := range data {
|
||||
totalSize += field.Size
|
||||
}
|
||||
p, err := TotalBitfieldSizeToProtodefName(totalSize)
|
||||
packedTypeProtodef, err := BitSizeToProtodef(totalSize, false)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return g.VisitDecoder(varToSet, p, name)
|
||||
t, err := g.VisitType(packedTypeProtodef)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
packed := name + "Packed"
|
||||
packedVarStmt := VarStmt(packed, t)
|
||||
stmts, err := g.VisitDecoder(Ident(packed), packedTypeProtodef, name)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
s = append(s, packedVarStmt)
|
||||
s = append(s, stmts...)
|
||||
lShiftBy := 0
|
||||
for _, field := range data {
|
||||
var fieldTypeProtodef string
|
||||
fieldTypeProtodef, err = BitSizeToProtodef(field.Size, field.Signed)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var fieldType ast.Expr
|
||||
fieldType, err = g.VisitType(fieldTypeProtodef)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
rShiftBy := totalSize - field.Size
|
||||
fieldToSet := SelectorExprAndStr(varToSet, CamelCase(field.Name))
|
||||
|
||||
var getDataExpr ast.Expr
|
||||
getDataExpr = RightShift(
|
||||
LeftShift(
|
||||
Ident(packed),
|
||||
NumLit(lShiftBy)),
|
||||
NumLit(rShiftBy),
|
||||
)
|
||||
if fieldTypeProtodef == "bool" {
|
||||
getDataExpr = Equals(getDataExpr, NumLit(1))
|
||||
} else if fieldTypeProtodef != packedTypeProtodef {
|
||||
getDataExpr = Call(fieldType, getDataExpr)
|
||||
}
|
||||
|
||||
s = append(s, Assign121(fieldToSet, getDataExpr))
|
||||
if field.Signed {
|
||||
s = append(s, If(
|
||||
GreaterThanOrEqual(
|
||||
fieldToSet,
|
||||
LeftShift(NumLit(1), NumLit(field.Size-1)),
|
||||
),
|
||||
NewBlockEllipsis(
|
||||
SubAssign(
|
||||
fieldToSet,
|
||||
LeftShift(NumLit(1), NumLit(field.Size)),
|
||||
),
|
||||
),
|
||||
))
|
||||
}
|
||||
|
||||
lShiftBy += field.Size
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func RegistryEntryHolderSetDecoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
||||
var data struct {
|
||||
Base struct {
|
||||
Name string
|
||||
Type any
|
||||
}
|
||||
Otherwise struct {
|
||||
Name string
|
||||
Type any
|
||||
}
|
||||
}
|
||||
var data protodef.RegistryEntryHolderSet
|
||||
err = mapstructure.Decode(dataRaw, &data)
|
||||
if err != nil {
|
||||
return
|
||||
@@ -462,7 +507,7 @@ func RegistryEntryHolderSetDecoder(g *Generator, varToSet ast.Expr, dataRaw any,
|
||||
}
|
||||
|
||||
func RegistryEntryHolderDecoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
||||
var data EntryHolderSet
|
||||
var data protodef.EntryHolderSet
|
||||
err = mapstructure.Decode(dataRaw, &data)
|
||||
if err != nil {
|
||||
return
|
||||
@@ -532,6 +577,7 @@ func (g *Generator) RegisterDecoderNatives() {
|
||||
"varlong": VarLongDecoder,
|
||||
"anonymousNbt": DefaultDecoder,
|
||||
"anonOptionalNbt": DefaultDecoder, // I have no idea what the difference is between these two
|
||||
"lpVec3": ToDoDecoder,
|
||||
"UUID": UUIDDecoder,
|
||||
"restBuffer": DefaultDecoder,
|
||||
|
||||
|
||||
@@ -3,7 +3,10 @@ package main
|
||||
import (
|
||||
"go/ast"
|
||||
"go/token"
|
||||
"slices"
|
||||
"strconv"
|
||||
|
||||
"github.com/admin-else/strom/proto_generator/protodef"
|
||||
"github.com/go-viper/mapstructure/v2"
|
||||
)
|
||||
|
||||
@@ -20,11 +23,7 @@ func DefaultEncoder(_ *Generator, varToSet ast.Expr, _ any, _ string) (s []ast.S
|
||||
}
|
||||
|
||||
func ContainerEncoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
||||
var data []struct {
|
||||
Name string
|
||||
Type any
|
||||
Anon bool
|
||||
}
|
||||
var data protodef.Container
|
||||
err = mapstructure.Decode(dataRaw, &data)
|
||||
if err != nil {
|
||||
return
|
||||
@@ -63,11 +62,7 @@ func SimpleTypeEncoder(_ *Generator, data ast.Expr, _ any, _ string) (s []ast.St
|
||||
}
|
||||
|
||||
func ArrayEncoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
||||
var data struct {
|
||||
CountType any
|
||||
Count string
|
||||
Type any
|
||||
}
|
||||
var data protodef.Array
|
||||
err = mapstructure.Decode(dataRaw, &data)
|
||||
if err != nil {
|
||||
return
|
||||
@@ -116,10 +111,7 @@ func OptionEncoder(g *Generator, data ast.Expr, dataRaw any, name string) (s []a
|
||||
}
|
||||
|
||||
func BufferEncoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
||||
var data struct {
|
||||
Count int
|
||||
CountType any
|
||||
}
|
||||
var data protodef.Buffer
|
||||
err = mapstructure.Decode(dataRaw, &data)
|
||||
if err != nil {
|
||||
return
|
||||
@@ -146,11 +138,7 @@ func BufferEncoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s
|
||||
}
|
||||
|
||||
func BitFieldEncoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
||||
var data []struct {
|
||||
Name string
|
||||
Singed bool
|
||||
Size int
|
||||
}
|
||||
var data protodef.BitField
|
||||
err = mapstructure.Decode(dataRaw, &data)
|
||||
if err != nil {
|
||||
return
|
||||
@@ -159,28 +147,59 @@ func BitFieldEncoder(g *Generator, varToSet ast.Expr, dataRaw any, name string)
|
||||
for _, field := range data {
|
||||
totalSize += field.Size
|
||||
}
|
||||
p, err := TotalBitfieldSizeToProtodefName(totalSize)
|
||||
packedVarName := name + "Packed"
|
||||
packedExpr := Ident(packedVarName)
|
||||
packedTypeStr := "uint" + strconv.Itoa(totalSize)
|
||||
|
||||
s = append(s, VarStmt(packedVarName, Ident(packedTypeStr)))
|
||||
|
||||
slices.Reverse(data)
|
||||
shiftBy := 0
|
||||
for _, field := range data {
|
||||
boolFix := packedTypeStr
|
||||
if field.Size == 1 {
|
||||
boolFix = "proto_base.Bool2" + boolFix
|
||||
}
|
||||
|
||||
s = append(s, OrAssign( // lisp ahh
|
||||
packedExpr,
|
||||
LeftShift(
|
||||
Grouping(
|
||||
BinAnd(
|
||||
Call(
|
||||
Ident(boolFix),
|
||||
SelectorExprAndStr(
|
||||
varToSet,
|
||||
CamelCase(field.Name),
|
||||
),
|
||||
),
|
||||
NumLitHex((1<<field.Size)-1),
|
||||
),
|
||||
),
|
||||
NumLitHex(shiftBy),
|
||||
),
|
||||
))
|
||||
shiftBy += field.Size
|
||||
}
|
||||
|
||||
encodePacked, err := g.VisitEncoder(packedExpr, "u"+strconv.Itoa(totalSize), name)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return g.VisitEncoder(varToSet, p, name)
|
||||
s = append(s, encodePacked...)
|
||||
return
|
||||
}
|
||||
|
||||
func SwitchEncoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
||||
var data struct {
|
||||
CompareTo string
|
||||
Fields map[string]any
|
||||
Default any
|
||||
}
|
||||
var data protodef.Switch
|
||||
err = mapstructure.Decode(dataRaw, &data)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
compareToExpr, err := g.ParseCompareTo(data.CompareTo)
|
||||
compareToExpr, cet, err := g.ParseCompareTo(data.CompareTo)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
cet := CaseExprTypeUnset
|
||||
for _, fName := range OrderedKeys(data.Fields) {
|
||||
fType := data.Fields[fName]
|
||||
e := MultiTypeFix(fName, &cet)
|
||||
@@ -234,9 +253,7 @@ func SwitchEncoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s
|
||||
}
|
||||
|
||||
func TypeForwardEncoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
||||
var data struct {
|
||||
Type string
|
||||
}
|
||||
var data protodef.TypeForward
|
||||
if err = mapstructure.Decode(dataRaw, &data); err != nil {
|
||||
return
|
||||
}
|
||||
@@ -244,10 +261,7 @@ func TypeForwardEncoder(g *Generator, varToSet ast.Expr, dataRaw any, name strin
|
||||
}
|
||||
|
||||
func MapperEncoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
||||
var data struct {
|
||||
Mappings map[string]string
|
||||
Type any
|
||||
}
|
||||
var data protodef.Mapper
|
||||
err = mapstructure.Decode(dataRaw, &data)
|
||||
if err != nil {
|
||||
return
|
||||
@@ -294,7 +308,7 @@ func UUIDEncoder(_ *Generator, varToSet ast.Expr, _ any, _ string) (s []ast.Stmt
|
||||
}
|
||||
|
||||
func RegistryEntryHolderEncoder(g *Generator, varToSet ast.Expr, dataRaw any, name string) (s []ast.Stmt, err error) {
|
||||
var data EntryHolderSet
|
||||
var data protodef.EntryHolderSet
|
||||
err = mapstructure.Decode(dataRaw, &data)
|
||||
otherwiseType, err := g.VisitType(data.Otherwise.Type)
|
||||
if err != nil {
|
||||
@@ -359,6 +373,7 @@ func (g *Generator) RegisterEncoderNatives() {
|
||||
"anonOptionalNbt": DefaultEncoder, // I have no idea what the difference is between these two
|
||||
"UUID": UUIDEncoder,
|
||||
"restBuffer": DefaultEncoder,
|
||||
"lpVec3": ToDoEncoder,
|
||||
"string": StringEncoder,
|
||||
|
||||
"f32": SimpleTypeEncoder,
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
"go/ast"
|
||||
|
||||
"github.com/admin-else/strom/proto_generator/protodef"
|
||||
"github.com/go-viper/mapstructure/v2"
|
||||
)
|
||||
|
||||
@@ -27,7 +28,8 @@ func VisitContainerType(g *Generator, dataRaw any) (ast.Expr, error) {
|
||||
|
||||
s := NewStruct()
|
||||
for _, field := range data {
|
||||
t, err := g.VisitType(field.Type)
|
||||
var t ast.Expr
|
||||
t, err = g.VisitType(field.Type)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -59,13 +61,16 @@ func VisitBufferType(_ *Generator, dataRaw any) (e ast.Expr, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func VisitArrayTypeVisitorType(g *Generator, dataRaw any) (ast.Expr, error) {
|
||||
func VisitArrayTypeVisitorType(g *Generator, dataRaw any) (e ast.Expr, err error) {
|
||||
var data struct {
|
||||
CountType any
|
||||
Type any
|
||||
}
|
||||
must(mapstructure.Decode(dataRaw, &data))
|
||||
e, err := g.VisitType(data.Type)
|
||||
err = mapstructure.Decode(dataRaw, &data)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
e, err = g.VisitType(data.Type)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -90,15 +95,24 @@ func VisitOptionType(g *Generator, dataRaw any) (e ast.Expr, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func TotalBitfieldSizeToProtodefName(totalSize int) (e string, err error) {
|
||||
func BitSizeToProtodef(totalSize int, singed bool) (e string, err error) {
|
||||
if !singed && totalSize == 1 {
|
||||
e = "bool"
|
||||
return
|
||||
}
|
||||
if singed {
|
||||
e = "i"
|
||||
} else {
|
||||
e = "u"
|
||||
}
|
||||
if totalSize <= 8 {
|
||||
e = "u8"
|
||||
e += "8"
|
||||
} else if totalSize <= 16 {
|
||||
e = "u16"
|
||||
e += "16"
|
||||
} else if totalSize <= 32 {
|
||||
e = "u32"
|
||||
e += "32"
|
||||
} else if totalSize <= 64 {
|
||||
e = "u64"
|
||||
e += "64"
|
||||
} else {
|
||||
err = errors.New("bitfield size too large")
|
||||
}
|
||||
@@ -106,25 +120,27 @@ func TotalBitfieldSizeToProtodefName(totalSize int) (e string, err error) {
|
||||
}
|
||||
|
||||
func VisitBitFieldType(g *Generator, dataRaw any) (e ast.Expr, err error) {
|
||||
var data []struct {
|
||||
Name string
|
||||
Singed bool
|
||||
Size int
|
||||
}
|
||||
var data protodef.BitField
|
||||
err = mapstructure.Decode(dataRaw, &data)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
totalSize := 0
|
||||
ret := NewStruct()
|
||||
for _, field := range data {
|
||||
totalSize += field.Size
|
||||
var p string
|
||||
p, err = BitSizeToProtodef(field.Size, field.Signed)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var fieldType ast.Expr
|
||||
fieldType, err = g.VisitType(p)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
AddFieldToStruct(ret, CamelCase(field.Name), fieldType)
|
||||
}
|
||||
// TODO: we will want to generate Methods and other stuff
|
||||
p, err := TotalBitfieldSizeToProtodefName(totalSize)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return g.VisitType(p)
|
||||
e = ret
|
||||
return
|
||||
}
|
||||
|
||||
func VisitBitFlagsType(g *Generator, dataRaw any) (e ast.Expr, err error) {
|
||||
@@ -194,5 +210,6 @@ func (g *Generator) RegisterNatives() {
|
||||
"bitflags": VisitBitFlagsType,
|
||||
"topBitSetTerminatedArray": VisitToDoType,
|
||||
"todo": VisitToDoType,
|
||||
"lpVec3": VisitToDoType,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,7 +95,7 @@ func NumLit(n int) *ast.BasicLit {
|
||||
}
|
||||
|
||||
func NumLitHex(n int) *ast.BasicLit {
|
||||
return NumLitStr(fmt.Sprintf("%X", n))
|
||||
return NumLitStr(fmt.Sprintf("0x%X", n))
|
||||
}
|
||||
|
||||
func NumLitStr(n string) *ast.BasicLit {
|
||||
@@ -186,6 +186,22 @@ func Define121(lhs, rhs ast.Expr) (s *ast.AssignStmt) {
|
||||
}
|
||||
}
|
||||
|
||||
func SubAssign(lhs, rhs ast.Expr) (s *ast.AssignStmt) {
|
||||
return &ast.AssignStmt{
|
||||
Lhs: []ast.Expr{lhs},
|
||||
Tok: token.SUB_ASSIGN,
|
||||
Rhs: []ast.Expr{rhs},
|
||||
}
|
||||
}
|
||||
|
||||
func OrAssign(lhs, rhs ast.Expr) (s *ast.AssignStmt) {
|
||||
return &ast.AssignStmt{
|
||||
Lhs: []ast.Expr{lhs},
|
||||
Tok: token.OR_ASSIGN,
|
||||
Rhs: []ast.Expr{rhs},
|
||||
}
|
||||
}
|
||||
|
||||
func Exprs(exprs ...ast.Expr) []ast.Expr {
|
||||
return exprs
|
||||
}
|
||||
@@ -231,6 +247,14 @@ func Equals(lhs, rhs ast.Expr) *ast.BinaryExpr {
|
||||
}
|
||||
}
|
||||
|
||||
func GreaterThanOrEqual(lhs, rhs ast.Expr) *ast.BinaryExpr {
|
||||
return &ast.BinaryExpr{
|
||||
X: lhs,
|
||||
Op: token.GEQ,
|
||||
Y: rhs,
|
||||
}
|
||||
}
|
||||
|
||||
func Nil() ast.Expr {
|
||||
return Ident("nil")
|
||||
}
|
||||
@@ -479,3 +503,25 @@ func BinAnd(lhs, rhs ast.Expr) *ast.BinaryExpr {
|
||||
Y: rhs,
|
||||
}
|
||||
}
|
||||
|
||||
func RightShift(lhs, rhs ast.Expr) *ast.BinaryExpr {
|
||||
return &ast.BinaryExpr{
|
||||
X: lhs,
|
||||
Op: token.SHR,
|
||||
Y: rhs,
|
||||
}
|
||||
}
|
||||
|
||||
func LeftShift(lhs, rhs ast.Expr) *ast.BinaryExpr {
|
||||
return &ast.BinaryExpr{
|
||||
X: lhs,
|
||||
Op: token.SHL,
|
||||
Y: rhs,
|
||||
}
|
||||
}
|
||||
|
||||
func Grouping(e ast.Expr) *ast.ParenExpr {
|
||||
return &ast.ParenExpr{
|
||||
X: e,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package protodef
|
||||
|
||||
type (
|
||||
BitFieldEntry struct {
|
||||
Name string
|
||||
Signed bool
|
||||
Size int
|
||||
}
|
||||
|
||||
BitField []BitFieldEntry
|
||||
|
||||
EntryHolderSet struct {
|
||||
BaseName string
|
||||
Otherwise struct {
|
||||
Name string
|
||||
Type any
|
||||
}
|
||||
}
|
||||
|
||||
Switch struct {
|
||||
CompareTo string
|
||||
Fields map[string]any
|
||||
Default any
|
||||
}
|
||||
|
||||
// TypeForward is not a real type, I just didn't implement it all yet, and it's just the underlying type
|
||||
TypeForward struct {
|
||||
Type string
|
||||
}
|
||||
|
||||
Buffer struct {
|
||||
Count int
|
||||
CountType any
|
||||
}
|
||||
|
||||
Array struct {
|
||||
CountType any
|
||||
Count string
|
||||
Type any
|
||||
}
|
||||
|
||||
Container []struct {
|
||||
Name string
|
||||
Type any
|
||||
Anon bool
|
||||
}
|
||||
|
||||
Mapper struct {
|
||||
Mappings map[string]string
|
||||
Type any
|
||||
}
|
||||
|
||||
RegistryEntryHolderSet struct {
|
||||
Base struct {
|
||||
Name string
|
||||
Type any
|
||||
}
|
||||
Otherwise struct {
|
||||
Name string
|
||||
Type any
|
||||
}
|
||||
}
|
||||
BitFlags struct {
|
||||
Flags []string
|
||||
Type any
|
||||
}
|
||||
)
|
||||
@@ -1,9 +1 @@
|
||||
package main
|
||||
|
||||
type EntryHolderSet struct {
|
||||
BaseName string
|
||||
Otherwise struct {
|
||||
Name string
|
||||
Type any
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,12 +49,6 @@ func ReverseMap[M map[K]V, K cmp.Ordered, V cmp.Ordered](m M) map[V]K {
|
||||
return ret
|
||||
}
|
||||
|
||||
func must(err error) {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func PopFront[T any](s []T) (T, []T, bool) {
|
||||
if len(s) == 0 {
|
||||
var zero T
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
"github.com/admin-else/strom/data"
|
||||
"github.com/admin-else/strom/event"
|
||||
"github.com/admin-else/strom/nbt"
|
||||
"github.com/admin-else/strom/proto"
|
||||
"github.com/admin-else/strom/proto_base"
|
||||
"github.com/admin-else/strom/proto_generated/v1_21_8"
|
||||
)
|
||||
|
||||
type ConfigServer struct {
|
||||
*proto.Conn
|
||||
}
|
||||
|
||||
func (c *ConfigServer) Default(event event.Anything) (err error) {
|
||||
slog.Debug("Config server", "packet", fmt.Sprintf("%#v", event.Val))
|
||||
return
|
||||
}
|
||||
|
||||
func ServeConfig(c *proto.Conn) (err error) {
|
||||
n, err := data.LoadRegistry(c.Version)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, p := range n.Value.(map[string]any)["Registries"].([]any) {
|
||||
packet := &v1_21_8.ConfigurationToClientPacketRegistryData{Id: p.(map[string]any)["Id"].(string)}
|
||||
for _, entry := range p.(map[string]any)["Entries"].([]any) {
|
||||
entryTyped := entry.(map[string]any)
|
||||
packet.Entries = append(packet.Entries, struct {
|
||||
Key string
|
||||
Value *nbt.Anon
|
||||
}{entryTyped["TagType"].(string), &nbt.Anon{Value: entryTyped["Value"]}})
|
||||
}
|
||||
err = c.Send(packet)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
tagsPacket := &v1_21_8.ConfigurationToClientPacketTags{}
|
||||
for _, p := range n.Value.(map[string]any)["Tags"].([]any) {
|
||||
p := p.(map[string]any)
|
||||
tags := v1_21_8.Tags{}
|
||||
for _, entry := range p["Entries"].([]any) {
|
||||
entry := entry.(map[string]any)
|
||||
tags.Val = append(tags.Val, struct {
|
||||
TagName string
|
||||
Entries []int32
|
||||
}{
|
||||
TagName: entry["TagName"].(string),
|
||||
Entries: entry["Entries"].([]int32),
|
||||
})
|
||||
}
|
||||
tagsPacket.Tags = append(tagsPacket.Tags, struct {
|
||||
TagType string
|
||||
Tags v1_21_8.Tags
|
||||
}{TagType: p["TagType"].(string), Tags: tags})
|
||||
}
|
||||
err = c.Send(tagsPacket)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = c.Send(&v1_21_8.ConfigurationToClientPacketFinishConfiguration{})
|
||||
cs := &ConfigServer{c}
|
||||
return cs.Start()
|
||||
}
|
||||
|
||||
func (c *ConfigServer) OnFinishConfiguration(_ *v1_21_8.ConfigurationToServerPacketFinishConfiguration) (err error) {
|
||||
c.SetState(proto_base.Play)
|
||||
err = event.HandlerDoneErr{}
|
||||
return
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package server_modules
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
@@ -1,4 +1,4 @@
|
||||
package server_modules
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var StatusServedError = errors.New("status served")
|
||||
var StatusServedErr = errors.New("status served")
|
||||
|
||||
var UnexpectedStatusRequest = UnexpectedNextStateError{proto_base.Status}
|
||||
|
||||
@@ -32,8 +32,6 @@ func (u UnexpectedNextStateError) Error() string {
|
||||
return fmt.Sprintf("unexpected next state: %v", u.NextState)
|
||||
}
|
||||
|
||||
var IncompatibleProtocolVersionError = fmt.Errorf("incompatible protocol version")
|
||||
|
||||
type LoginServer struct {
|
||||
*proto.Conn
|
||||
//OnlineMode bool FIXME: implement this
|
||||
@@ -41,7 +39,7 @@ type LoginServer struct {
|
||||
ServerPort uint16
|
||||
Requested NameAndUUID
|
||||
Given *NameAndUUID
|
||||
CompressionThreshold int32
|
||||
CompressionThreshold int32 //FIXME: implement this
|
||||
Status []byte
|
||||
CompatibleVersions []int32
|
||||
}
|
||||
@@ -51,16 +49,20 @@ func (l *LoginServer) OnHandshake(packet *v1_21_8.HandshakingToServerPacketSetPr
|
||||
l.ServerHost = packet.ServerHost
|
||||
l.ServerPort = packet.ServerPort
|
||||
|
||||
if len(l.CompatibleVersions) != 0 {
|
||||
if !slices.Contains(l.CompatibleVersions, packet.ProtocolVersion) {
|
||||
err = IncompatibleProtocolVersionError
|
||||
return
|
||||
}
|
||||
if packet.NextState == int32(proto_base.Status) && l.Status != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if packet.NextState != int32(proto_base.Login) && !(l.Status != nil && packet.NextState == int32(proto_base.Status)) {
|
||||
if packet.NextState != int32(proto_base.Login) {
|
||||
err = UnexpectedNextStateError{proto_base.State(packet.NextState)}
|
||||
return
|
||||
}
|
||||
|
||||
if len(l.CompatibleVersions) != 0 && !slices.Contains(l.CompatibleVersions, packet.ProtocolVersion) {
|
||||
err = fmt.Errorf("incompatible protocol version please use one of %v you can look up the real corresponding version at https://minecraft.wiki/w/Minecraft_Wiki:Projects/wiki.vg_merge/Protocol_version_numbers", l.CompatibleVersions)
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
@@ -74,7 +76,7 @@ func (l *LoginServer) OnStatusPing(packet *v1_21_8.StatusToServerPacketPing) (er
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return event.HandlerDoneErr{Return: StatusServedError}
|
||||
return event.HandlerDoneErr{Return: StatusServedErr}
|
||||
}
|
||||
|
||||
func (l *LoginServer) SetCompressionThreshold(threshold int32) (err error) {
|
||||
@@ -88,10 +90,6 @@ func (l *LoginServer) SetCompressionThreshold(threshold int32) (err error) {
|
||||
|
||||
func (l *LoginServer) OnLoginStart(packet *v1_21_8.LoginToServerPacketLoginStart) (err error) {
|
||||
l.Requested = NameAndUUID{packet.Username, packet.PlayerUUID}
|
||||
//err = l.SetCompressionThreshold(l.CompressionThreshold)
|
||||
//if err != nil {
|
||||
// return
|
||||
//}
|
||||
if l.Given == nil {
|
||||
l.Given = &l.Requested
|
||||
}
|
||||
@@ -111,15 +109,6 @@ func (l *LoginServer) OnLoginAcknowledged(_ *v1_21_8.LoginToServerPacketLoginAck
|
||||
|
||||
func (l *LoginServer) OnDefault(event event.Unhandled) (err error) {
|
||||
err = fmt.Errorf("unexpected event during login: %#v", event)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
func (l *LoginServer) OnStart(_ event.OnStart) (err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func (l *LoginServer) OnCycle(_ event.Tick) (err error) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -153,19 +142,15 @@ func WithStatus(response StatusResponse) LoginServerSetting {
|
||||
return WithRawStatus(status)
|
||||
}
|
||||
|
||||
func WithCompatibleVersion(versions int32) LoginServerSetting {
|
||||
return WithCompatibleVersions([]int32{versions})
|
||||
}
|
||||
|
||||
func WithCompatibleVersionsRange(start, end int32) LoginServerSetting {
|
||||
var versions []int32
|
||||
for i := start; i <= end; i++ {
|
||||
versions = append(versions, i)
|
||||
}
|
||||
return WithCompatibleVersions(versions)
|
||||
return WithCompatibleVersions(versions...)
|
||||
}
|
||||
|
||||
func WithCompatibleVersions(versions []int32) LoginServerSetting {
|
||||
func WithCompatibleVersions(versions ...int32) LoginServerSetting {
|
||||
return func(s *LoginServer) {
|
||||
s.CompatibleVersions = versions
|
||||
}
|
||||
@@ -173,10 +158,16 @@ func WithCompatibleVersions(versions []int32) LoginServerSetting {
|
||||
|
||||
func ServeLogin(c *proto.Conn, settings ...LoginServerSetting) (ret *LoginServer, err error) {
|
||||
ret = &LoginServer{Conn: c}
|
||||
ret.RegisterCritical(ret.OnDefault)
|
||||
ret.RegisterUntilLatest(ret.OnHandshake)
|
||||
ret.RegisterUntilLatest(ret.OnLoginStart)
|
||||
ret.RegisterUntilLatest(ret.OnLoginAcknowledged)
|
||||
ret.RegisterUntilLatest(ret.OnStatusRequest)
|
||||
ret.RegisterUntilLatest(ret.OnStatusPing)
|
||||
for _, s := range settings {
|
||||
s(ret)
|
||||
}
|
||||
ret.CompressionThreshold = 256
|
||||
err = ret.Start(ret)
|
||||
err = ret.Start()
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package server
|
||||
|
||||
type SchematicServer interface {
|
||||
}
|
||||
+24
-6
@@ -1,12 +1,12 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net"
|
||||
|
||||
"github.com/admin-else/strom/proto"
|
||||
"github.com/admin-else/strom/proto_base"
|
||||
"github.com/admin-else/strom/server/server_modules"
|
||||
"github.com/admin-else/strom/text"
|
||||
)
|
||||
|
||||
@@ -14,7 +14,7 @@ func Servee(c net.Conn) (ret *proto.Conn) {
|
||||
ret = &proto.Conn{}
|
||||
_ = ret.SetVersion("1.21.8") // cant fail
|
||||
ret.SetState(proto_base.Handshaking)
|
||||
ret.CompressionThreshold = -1
|
||||
ret.SetCompressionThreshold(-1)
|
||||
ret.Actor = proto_base.Servee
|
||||
ret.Conn = c
|
||||
ret.R = c
|
||||
@@ -22,17 +22,32 @@ func Servee(c net.Conn) (ret *proto.Conn) {
|
||||
return
|
||||
}
|
||||
|
||||
func ServeClient(cNet net.Conn, factory func(c *proto.Conn) (h any, err error)) (err error) {
|
||||
type ConnAcceptor func(c net.Conn) (err error)
|
||||
|
||||
type Factory func(c *proto.Conn) (h ConnAcceptor, err error)
|
||||
|
||||
func ServeClient(cNet net.Conn, factory Factory) {
|
||||
c := Servee(cNet)
|
||||
defer c.Close()
|
||||
h, err := factory(c)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = c.Start(h)
|
||||
err = h(c)
|
||||
if errors.Is(err, StatusServedErr) {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
slog.Error("Error while handling client", "error", err, "client", c.Conn.RemoteAddr())
|
||||
err = Kick(c, text.Pretty(err.Error()))
|
||||
if err != nil {
|
||||
slog.Error("Error while kicking client", "error", err, "client", c.Conn.RemoteAddr())
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func StartServerWithFactory(listenAddr string, factory func(c *proto.Conn) (h any, err error)) (err error) {
|
||||
func StartServerWithFactory(listenAddr string, factory Factory) (err error) {
|
||||
l, err := net.Listen("tcp", listenAddr)
|
||||
if err != nil {
|
||||
return
|
||||
@@ -63,8 +78,11 @@ func StartServerWithOnConn(listenAddr string, onConn func(c *proto.Conn) (err er
|
||||
defer c.Close()
|
||||
connErr := onConn(c)
|
||||
if connErr != nil {
|
||||
if c.State() == proto_base.Status || c.State() == proto_base.Handshaking {
|
||||
return // we dont care about status packets
|
||||
}
|
||||
slog.Error("Error while handling client", "error", connErr, "client", c.Conn.RemoteAddr())
|
||||
connErr = server_modules.Kick(c, text.Pretty(connErr.Error()))
|
||||
connErr = Kick(c, text.Pretty(connErr.Error()))
|
||||
if connErr != nil {
|
||||
slog.Error("Error while kicking client", "error", connErr, "client", c.Conn.RemoteAddr())
|
||||
}
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
package server_modules
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/admin-else/strom/proto"
|
||||
"github.com/admin-else/strom/proto_generated/v1_21_8"
|
||||
"github.com/admin-else/strom/text"
|
||||
)
|
||||
|
||||
// StatusResponse here is the structure I used: https://minecraft.wiki/w/Java_Edition_protocol/Server_List_Ping#Status_Response
|
||||
type StatusResponse struct {
|
||||
Version struct {
|
||||
Name *text.Component `json:"name"`
|
||||
Protocol int `json:"protocol"`
|
||||
} `json:"version"`
|
||||
Players struct {
|
||||
Max int `json:"max"`
|
||||
Online int `json:"online"`
|
||||
Sample []struct {
|
||||
Name *text.Component `json:"name"`
|
||||
ID string `json:"id"`
|
||||
} `json:"sample"`
|
||||
} `json:"players"`
|
||||
Description *text.Component `json:"description"`
|
||||
Favicon string `json:"favicon"`
|
||||
EnforcesSecureChat bool `json:"enforcesSecureChat"`
|
||||
}
|
||||
|
||||
type StatusServer struct {
|
||||
*proto.Conn
|
||||
Status string
|
||||
}
|
||||
|
||||
func (p *StatusServer) Default(_ any) (err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func (p *StatusServer) OnStatusRequest(_ *v1_21_8.StatusToServerPacketPingStart) (err error) {
|
||||
return p.Send(&v1_21_8.StatusToClientPacketServerInfo{Response: p.Status})
|
||||
}
|
||||
|
||||
func (p *StatusServer) OnStatusPing(packet *v1_21_8.StatusToServerPacketPing) (err error) {
|
||||
return p.Send(&v1_21_8.StatusToClientPacketPing{Time: packet.Time})
|
||||
}
|
||||
|
||||
func ServeStatus(c *proto.Conn, s StatusResponse) (err error) {
|
||||
status, err := json.Marshal(s)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
server := &StatusServer{
|
||||
Conn: c,
|
||||
Status: string(status),
|
||||
}
|
||||
err = server.Start(server)
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/admin-else/strom/proto"
|
||||
"github.com/admin-else/strom/proto_generated/v1_21_8"
|
||||
"github.com/admin-else/strom/text"
|
||||
)
|
||||
|
||||
// These are separate types so a status definition looks less ugly
|
||||
|
||||
type StatusResponseVersion struct {
|
||||
Name *text.Component `json:"name"`
|
||||
Protocol int32 `json:"protocol"`
|
||||
}
|
||||
|
||||
type StatusResponseSample struct {
|
||||
Name *text.Component `json:"name"`
|
||||
ID string `json:"id"`
|
||||
}
|
||||
type StatusResponsePlayers struct {
|
||||
Max int `json:"max"`
|
||||
Online int `json:"online"`
|
||||
Sample []StatusResponseSample `json:"sample"`
|
||||
}
|
||||
|
||||
// StatusResponse here is the structure I used: https://minecraft.wiki/w/Java_Edition_protocol/Server_List_Ping#Status_Response
|
||||
type StatusResponse struct {
|
||||
Version StatusResponseVersion `json:"version"`
|
||||
Players StatusResponsePlayers `json:"players"`
|
||||
Description *text.Component `json:"description"`
|
||||
Favicon string `json:"favicon"`
|
||||
EnforcesSecureChat bool `json:"enforcesSecureChat"`
|
||||
}
|
||||
|
||||
// MustMarshal is a utility for marshalling StatusResponse to JSON
|
||||
func (s StatusResponse) MustMarshal() []byte {
|
||||
b, err := json.Marshal(s)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
type StatusServer struct {
|
||||
*proto.Conn
|
||||
Status string
|
||||
}
|
||||
|
||||
func (p *StatusServer) OnStatusRequest(_ *v1_21_8.StatusToServerPacketPingStart) (err error) {
|
||||
return p.Send(&v1_21_8.StatusToClientPacketServerInfo{Response: p.Status})
|
||||
}
|
||||
|
||||
func (p *StatusServer) OnStatusPing(packet *v1_21_8.StatusToServerPacketPing) (err error) {
|
||||
return p.Send(&v1_21_8.StatusToClientPacketPing{Time: packet.Time})
|
||||
}
|
||||
|
||||
func ServeStatus(c *proto.Conn, s StatusResponse) (err error) {
|
||||
status, err := json.Marshal(s)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
server := &StatusServer{
|
||||
Conn: c,
|
||||
Status: string(status),
|
||||
}
|
||||
server.RegisterUntilLatest(server.OnStatusRequest)
|
||||
server.RegisterUntilLatest(server.OnStatusPing)
|
||||
err = server.Start()
|
||||
return
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/admin-else/strom/nbt"
|
||||
)
|
||||
|
||||
// Component represents a Minecraft text component.
|
||||
@@ -60,11 +62,56 @@ func (c *Component) MarshalJSON() ([]byte, error) {
|
||||
if c.isSimpleText() {
|
||||
return json.Marshal(c.Text)
|
||||
}
|
||||
if c.hasFormattingButNoContent() {
|
||||
// just like component but text does not have omitempty
|
||||
type AliasWithText struct {
|
||||
Bold *bool `json:"bold,omitempty"`
|
||||
Italic *bool `json:"italic,omitempty"`
|
||||
Underlined *bool `json:"underlined,omitempty"`
|
||||
Strikethrough *bool `json:"strikethrough,omitempty"`
|
||||
Obfuscated *bool `json:"obfuscated,omitempty"`
|
||||
Font string `json:"font,omitempty"`
|
||||
Color string `json:"color,omitempty"`
|
||||
Insertion string `json:"insertion,omitempty"`
|
||||
ClickEvent *ClickEvent `json:"clickEvent,omitempty"`
|
||||
HoverEvent *HoverEvent `json:"hoverEvent,omitempty"`
|
||||
Extra []Component `json:"extra,omitempty"`
|
||||
|
||||
Text string `json:"text"`
|
||||
|
||||
Translate string `json:"translate,omitempty"`
|
||||
With []Component `json:"with,omitempty"`
|
||||
Score *Score `json:"score,omitempty"`
|
||||
Selector string `json:"selector,omitempty"`
|
||||
Keybind string `json:"keybind,omitempty"`
|
||||
NBT string `json:"nbt,omitempty"`
|
||||
Interpret bool `json:"interpret,omitempty"`
|
||||
Block string `json:"block,omitempty"`
|
||||
Entity string `json:"entity,omitempty"`
|
||||
Storage string `json:"storage,omitempty"`
|
||||
Separator *Component `json:"separator,omitempty"`
|
||||
}
|
||||
return json.Marshal(AliasWithText(*c))
|
||||
}
|
||||
type Alias Component
|
||||
|
||||
return json.Marshal(Alias(*c))
|
||||
}
|
||||
|
||||
// hasFormattingButNoContent checks if the component has formatting/styling but no content fields
|
||||
func (c *Component) hasFormattingButNoContent() bool {
|
||||
hasFormatting := c.Bold != nil || c.Italic != nil || c.Underlined != nil ||
|
||||
c.Strikethrough != nil || c.Obfuscated != nil || c.Font != "" ||
|
||||
c.Color != "" || c.Insertion != "" || c.ClickEvent != nil ||
|
||||
c.HoverEvent != nil || len(c.Extra) > 0 || c.Separator != nil
|
||||
|
||||
hasContent := c.Text != "" || c.Translate != "" || len(c.With) > 0 ||
|
||||
c.Score != nil || c.Selector != "" || c.Keybind != "" ||
|
||||
c.NBT != "" || c.Block != "" || c.Entity != "" || c.Storage != ""
|
||||
|
||||
return hasFormatting && !hasContent
|
||||
}
|
||||
|
||||
func (c *Component) isSimpleText() bool {
|
||||
return c.Text != "" &&
|
||||
c.Bold == nil && c.Italic == nil && c.Underlined == nil && c.Strikethrough == nil && c.Obfuscated == nil &&
|
||||
@@ -213,6 +260,10 @@ func (c *Component) ToNBT() any {
|
||||
m["separator"] = c.Separator.ToNBT()
|
||||
}
|
||||
|
||||
if c.hasFormattingButNoContent() {
|
||||
m["text"] = ""
|
||||
}
|
||||
|
||||
return m
|
||||
}
|
||||
|
||||
@@ -538,3 +589,14 @@ func (c *Component) writePretty(sb *strings.Builder) {
|
||||
extra.writePretty(sb)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Component) AsNBT() nbt.Anon {
|
||||
return nbt.Anon{Value: c.ToNBT()}
|
||||
}
|
||||
|
||||
func (c *Component) AsOldNBT() nbt.Tag {
|
||||
return nbt.Tag{
|
||||
Name: "",
|
||||
Value: c.ToNBT(),
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -167,14 +167,14 @@ func TestPretty(t *testing.T) {
|
||||
|
||||
func TestPrettyF(t *testing.T) {
|
||||
got := PrettyF("Hello §b%s", "World")
|
||||
want := Component{
|
||||
want := &Component{
|
||||
Text: "Hello ",
|
||||
Extra: []Component{
|
||||
{Text: "World", Color: "aqua"},
|
||||
},
|
||||
}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("PrettyF() = %+v, want %+v", got, want)
|
||||
t.Errorf("PrettyF() = \n%+v\n, want \n%+v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"maps"
|
||||
"os"
|
||||
"slices"
|
||||
|
||||
"github.com/admin-else/strom/tools/cli/offline_uuid"
|
||||
"github.com/admin-else/strom/tools/cli/print_nbt"
|
||||
"github.com/admin-else/strom/tools/cli/status"
|
||||
)
|
||||
|
||||
var ExpectedASubcommandErr = errors.New("expected a subcommand")
|
||||
var UnknownSubcommandErr = errors.New("unknown subcommand")
|
||||
|
||||
var subcommands = map[string]func(args []string) error{
|
||||
"offline-uuid": offline_uuid.Run,
|
||||
"print-nbt": print_nbt.Run,
|
||||
"status": status.Run,
|
||||
}
|
||||
|
||||
func Help(args []string) (err error) {
|
||||
fmt.Println("Available subcommands", slices.Collect(maps.Keys(subcommands)))
|
||||
return
|
||||
}
|
||||
|
||||
func mainE() (err error) {
|
||||
subcommands["help"] = Help // this is here because if it isn't tools/cli/main.go:17:5: initialization cycle for subcommands
|
||||
// tools/cli/main.go:17:5: subcommands refers to Help
|
||||
// tools/cli/main.go:22:6: Help refers to subcommands
|
||||
args := os.Args
|
||||
|
||||
// Debug stuff
|
||||
//slog.SetLogLoggerLevel(slog.LevelDebug)
|
||||
//args = []string{"TEST", "status", "-srv", "-addr", "tcpshield.1f2d.net:25565"}
|
||||
|
||||
if len(args) < 2 {
|
||||
err = ExpectedASubcommandErr
|
||||
return
|
||||
}
|
||||
|
||||
f, ok := subcommands[args[1]]
|
||||
if !ok {
|
||||
err = UnknownSubcommandErr
|
||||
return
|
||||
}
|
||||
err = f(args[2:])
|
||||
return
|
||||
}
|
||||
|
||||
func main() {
|
||||
err := mainE()
|
||||
if err != nil {
|
||||
slog.Error("exiting", "err", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package offline_uuid
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
|
||||
"github.com/admin-else/strom/crypto"
|
||||
)
|
||||
|
||||
var cmd = flag.NewFlagSet("offline-uuid", flag.ContinueOnError)
|
||||
var nameFlag = cmd.String("name", "Notch", "name of the player")
|
||||
|
||||
func Run(args []string) (err error) {
|
||||
err = cmd.Parse(args)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
fmt.Println(crypto.FromOfflinePlayer(*nameFlag))
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package print_nbt
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"os"
|
||||
|
||||
"github.com/admin-else/strom/nbt"
|
||||
)
|
||||
|
||||
var (
|
||||
cmd = flag.NewFlagSet("print-nbt", flag.ContinueOnError)
|
||||
FileFlag = cmd.String("file", "", "The NBT file to print")
|
||||
)
|
||||
|
||||
func Run(args []string) (err error) {
|
||||
err = cmd.Parse(args)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
f, err := os.Open(*FileFlag)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
n, err := nbt.ReadFile(f)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
b, err := json.MarshalIndent(n, "", " ")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_, err = os.Stdout.Write(b)
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package status
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
|
||||
"github.com/admin-else/strom/client"
|
||||
)
|
||||
|
||||
var cmd = flag.NewFlagSet("status", flag.ContinueOnError)
|
||||
var addrFlag = cmd.String("addr", "localhost:25565", "address to connect to")
|
||||
var srvFlag = cmd.Bool("srv", false, "use SRV records to resolve the address")
|
||||
|
||||
func Run(args []string) (err error) {
|
||||
err = cmd.Parse(args)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if *srvFlag {
|
||||
*addrFlag, err = client.DoDnsSimple(*addrFlag)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
status, err := client.StatusRaw(*addrFlag)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
fmt.Println(status.Status)
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"os"
|
||||
|
||||
"github.com/admin-else/strom/api"
|
||||
"github.com/admin-else/strom/client"
|
||||
"github.com/admin-else/strom/data"
|
||||
"github.com/admin-else/strom/event"
|
||||
"github.com/admin-else/strom/nbt"
|
||||
"github.com/admin-else/strom/proto"
|
||||
"github.com/admin-else/strom/proto_base"
|
||||
"github.com/admin-else/strom/proto_generated/v1_21_8"
|
||||
"github.com/admin-else/strom/server"
|
||||
"github.com/admin-else/strom/text"
|
||||
)
|
||||
|
||||
func wontFail[T any](v T, err error) T {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
var (
|
||||
// Edit these two
|
||||
|
||||
SaveAs = "1.21.8"
|
||||
Version = "1.21.8"
|
||||
|
||||
CompatibleProtocolVersion = wontFail(data.LookUpVersionByName(Version)).Version
|
||||
FinishedConfigErr = errors.New("finished configuration")
|
||||
)
|
||||
|
||||
var Status = wontFail(json.Marshal(server.StatusResponse{
|
||||
Version: server.StatusResponseVersion{
|
||||
Name: nil,
|
||||
Protocol: CompatibleProtocolVersion,
|
||||
},
|
||||
Description: text.Pretty("Registry data hunter"),
|
||||
}))
|
||||
|
||||
type Proxy struct {
|
||||
Client, Servee *proto.Conn
|
||||
Data nbt.Tag
|
||||
}
|
||||
|
||||
func (p *Proxy) OnStart() (err error) {
|
||||
p.Client.RegisterCritical(p.OnAnything)
|
||||
p.Servee.RegisterCritical(p.OnAnything)
|
||||
|
||||
p.Client.RegisterCriticalUntilLatest(p.OnFinishConfiguration)
|
||||
return
|
||||
}
|
||||
|
||||
func (p *Proxy) OnAnything(e event.Anything) (err error) {
|
||||
packet, ok := e.Val.(proto_base.EncodeDecodeAble)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
packetInfo, ok := proto.LookupPacketInfoByType(packet)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
switch packetInfo.Direction {
|
||||
case proto_base.ToServer:
|
||||
err = p.Client.Send(packet)
|
||||
case proto_base.ToClient:
|
||||
err = p.Servee.Send(packet)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (p *Proxy) OnFinishConfiguration(_ *v1_21_8.ConfigurationToClientPacketFinishConfiguration) (err error) {
|
||||
err = FinishedConfigErr
|
||||
return
|
||||
}
|
||||
|
||||
func (p *Proxy) OnData(data *v1_21_8.ConfigurationToClientPacketRegistryData) (err error) {
|
||||
d := p.Data.Value.(map[string]any)["Registries"].([]any)
|
||||
var entries []any
|
||||
for _, entry := range data.Entries {
|
||||
entries = append(entries, map[string]any{"TagType": entry.Key, "Value": entry.Value.Value})
|
||||
}
|
||||
d = append(d, map[string]any{"Id": data.Id, "Entries": entries})
|
||||
p.Data.Value.(map[string]any)["Registries"] = d
|
||||
return
|
||||
}
|
||||
|
||||
func (p *Proxy) OnTags(data *v1_21_8.ConfigurationToClientPacketTags) (err error) {
|
||||
var tags []any
|
||||
for _, tag := range data.Tags {
|
||||
var entries []any
|
||||
for _, entry := range tag.Tags.Val {
|
||||
entries = append(entries, map[string]any{"TagName": entry.TagName, "Entries": entry.Entries})
|
||||
}
|
||||
tags = append(tags, map[string]any{"TagType": tag.TagType, "Entries": entries})
|
||||
}
|
||||
p.Data.Value.(map[string]any)["Tags"] = tags
|
||||
return
|
||||
}
|
||||
|
||||
func handleClient(c *proto.Conn) (err error) {
|
||||
acc := api.NewOfflineAccount("RegistryHunter")
|
||||
|
||||
// ignore resource leak warning we own c conn so we should not close it here
|
||||
_, err = server.ServeLogin(c, server.WithOtherAccount(acc), server.WithCompatibleVersions(CompatibleProtocolVersion), server.WithRawStatus(Status))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
sockPuppet, err := client.Connect(":25566")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer sockPuppet.Close()
|
||||
err = sockPuppet.Start(&client.LoginClient{
|
||||
Conn: sockPuppet,
|
||||
Account: acc,
|
||||
})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
errChan := make(chan error)
|
||||
p := &Proxy{Client: sockPuppet, Servee: c}
|
||||
p.Data.Value = map[string]any{"Registries": []any{}}
|
||||
go func() {
|
||||
errChan <- p.Client.Start(p)
|
||||
}()
|
||||
go func() {
|
||||
errChan <- p.Servee.Start(p)
|
||||
}()
|
||||
err = <-errChan
|
||||
f, err := os.Create("data/registry/" + SaveAs + ".nbt")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
err = nbt.WriteFile(f, p.Data)
|
||||
return
|
||||
}
|
||||
|
||||
func main() {
|
||||
slog.SetLogLoggerLevel(slog.LevelDebug)
|
||||
err := server.StartServerWithOnConn(":25565", handleClient)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -1,19 +1,18 @@
|
||||
// THIS THING IS BROKEN
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
|
||||
"github.com/admin-else/strom/api"
|
||||
"github.com/admin-else/strom/client/modules"
|
||||
"github.com/admin-else/strom/client"
|
||||
"github.com/admin-else/strom/event"
|
||||
"github.com/admin-else/strom/proto"
|
||||
"github.com/admin-else/strom/proto_base"
|
||||
"github.com/admin-else/strom/proto_generated/v1_21_8"
|
||||
"github.com/admin-else/strom/server"
|
||||
"github.com/admin-else/strom/server/server_modules"
|
||||
"github.com/admin-else/strom/text"
|
||||
)
|
||||
|
||||
@@ -35,11 +34,11 @@ func (p *ProxyClient) OnCycle(_ event.Tick) (err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func (p *ProxyClient) OnStart(_ event.OnStart) (err error) {
|
||||
func (p *ProxyClient) OnStart() (err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func (p *ProxyClient) OnUnCodeAble(packet proto.UnCodablePacket) (err error) {
|
||||
func (p *ProxyClient) OnUnCodeAble(packet *proto.UnCodablePacket) (err error) {
|
||||
err = p.OnDefault(event.Unhandled{Val: packet})
|
||||
if err != nil {
|
||||
return
|
||||
@@ -66,7 +65,7 @@ func (p *Proxy) OnCycle(_ event.Tick) (err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func (p *Proxy) OnStart(_ event.OnStart) (err error) {
|
||||
func (p *Proxy) OnStart() (err error) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -80,7 +79,7 @@ func (p *Proxy) OnFinishConfiguration(packet *v1_21_8.ConfigurationToServerPacke
|
||||
return
|
||||
}
|
||||
|
||||
func (p *Proxy) OnUnCodeAble(packet proto.UnCodablePacket) (err error) {
|
||||
func (p *Proxy) OnUnCodeAble(packet *proto.UnCodablePacket) (err error) {
|
||||
err = p.OnDefault(event.Unhandled{Val: packet})
|
||||
if err != nil {
|
||||
return
|
||||
@@ -102,58 +101,51 @@ import (
|
||||
func TestFailedPacket%10X(t *testing.T) {
|
||||
p := v1_21_8.Play%vPacket{}
|
||||
b := bytes.NewBuffer(%#v)
|
||||
p, err := p.Decode(b)
|
||||
err := p.Decode(b)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
func SaveUnCodeAbleAsTest(d proto_base.Direction, packet proto.UnCodablePacket) {
|
||||
func SaveUnCodeAbleAsTest(d proto_base.Direction, packet *proto.UnCodablePacket) {
|
||||
hUntrimmed := sha256.Sum256(packet.Data)
|
||||
h := hUntrimmed[:8]
|
||||
f, err := os.Create(fmt.Sprintf(".failed_packets/%v_%10x_test.go", len(packet.Data), h))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
//goland:noinspection GoUnhandledErrorResult
|
||||
defer f.Close()
|
||||
_, err = fmt.Fprintf(f, TestSrcF, packet.Err, h, d.Opposite(), packet.Data)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
fmt.Println("Error", packet.Err, "saved to", f.Name(), "data:", packet.Data)
|
||||
slog.Info("Packet failed to parse", "error", packet.Err, "saved", f.Name(), "data", fmt.Sprintf("%q", packet.Data))
|
||||
}
|
||||
|
||||
var StatusResponse = server_modules.StatusResponse{
|
||||
Version: struct {
|
||||
Name *text.Component `json:"name"`
|
||||
Protocol int `json:"protocol"`
|
||||
}{
|
||||
var StatusResponse = server.StatusResponse{
|
||||
Version: server.StatusResponseVersion{
|
||||
Name: text.Pretty("STROM"),
|
||||
Protocol: 772,
|
||||
},
|
||||
Players: struct {
|
||||
Max int `json:"max"`
|
||||
Online int `json:"online"`
|
||||
Sample []struct {
|
||||
Name *text.Component `json:"name"`
|
||||
ID string `json:"id"`
|
||||
} `json:"sample"`
|
||||
}{},
|
||||
Description: text.Pretty("Hunt the uncodeable packets"),
|
||||
Players: server.StatusResponsePlayers{},
|
||||
Description: text.Pretty("Hunt the un-code-able packets"),
|
||||
Favicon: "",
|
||||
EnforcesSecureChat: false,
|
||||
}
|
||||
|
||||
func main() {
|
||||
slog.SetLogLoggerLevel(slog.LevelDebug)
|
||||
err := server.StartServerWithOnConn(":25565", func(serveeConn *proto.Conn) (err error) {
|
||||
p := &Proxy{Conn: serveeConn, Client: nil}
|
||||
acc := api.NewOfflineAccount("sigma")
|
||||
_, err = server_modules.ServeLogin(serveeConn, server_modules.WithOtherAccount(acc), server_modules.WithStatus(StatusResponse))
|
||||
_, err = server.ServeLogin(serveeConn, server.WithOtherAccount(acc), server.WithStatus(StatusResponse))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
c, err := modules.ConnectAndLogin("127.0.0.1:25566", acc)
|
||||
c, err := client.ConnectAndLogin("127.0.0.1:25566", acc)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -161,7 +153,6 @@ func main() {
|
||||
p.Client = pc
|
||||
errChan := make(chan error)
|
||||
defer pc.Close()
|
||||
defer p.Close()
|
||||
go func() {
|
||||
errChan <- pc.Start(pc)
|
||||
}()
|
||||
|
||||
Reference in New Issue
Block a user